4 require 'bigdecimal/util'
7 module ConnectionAdapters
#:nodoc:
8 # An abstract definition of a column in a table.
10 TRUE_VALUES
= [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
11 FALSE_VALUES
= [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set
14 ISO_DATE
= /\A(\d{4})-(\d\d)-(\d\d)\z/
15 ISO_DATETIME
= /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
18 attr_reader
:name, :default, :type, :limit, :null, :sql_type, :precision, :scale
19 attr_accessor
:primary
21 # Instantiates a new column in the table.
23 # +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
24 # +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
25 # +sql_type+ is only used to extract the column's length, if necessary. For example +60+ in <tt>company_name varchar(60)</tt>.
26 # +null+ determines if this column allows +NULL+ values.
27 def initialize(name
, default
, sql_type
= nil, null
= true)
28 @name, @sql_type, @null = name
, sql_type
, null
29 @limit, @precision, @scale = extract_limit(sql_type
), extract_precision(sql_type
), extract_scale(sql_type
)
30 @type = simplified_type(sql_type
)
31 @default = extract_default(default
)
36 # Returns +true+ if the column is either of type string or text.
38 type
== :string || type
== :text
41 # Returns +true+ if the column is either of type integer, float or decimal.
43 type
== :integer || type
== :float || type
== :decimal
50 # Returns the Ruby class that corresponds to the abstract data type.
53 when :integer then Fixnum
54 when :float then Float
55 when :decimal then BigDecimal
56 when :datetime then Time
58 when :timestamp then Time
60 when :text, :string then String
61 when :binary then String
62 when :boolean then Object
66 # Casts value (which is a String) to an appropriate instance.
68 return nil if value
.nil?
70 when :string then value
72 when :integer then value
.to_i
rescue value
? 1 : 0
73 when :float then value
.to_f
74 when :decimal then self.class.value_to_decimal(value
)
75 when :datetime then self.class.string_to_time(value
)
76 when :timestamp then self.class.string_to_time(value
)
77 when :time then self.class.string_to_dummy_time(value
)
78 when :date then self.class.string_to_date(value
)
79 when :binary then self.class.binary_to_string(value
)
80 when :boolean then self.class.value_to_boolean(value
)
85 def type_cast_code(var_name
)
89 when :integer then "(#{var_name}.to_i rescue #{var_name} ? 1 : 0)"
90 when :float then "#{var_name}.to_f"
91 when :decimal then "#{self.class.name}.value_to_decimal(#{var_name})"
92 when :datetime then "#{self.class.name}.string_to_time(#{var_name})"
93 when :timestamp then "#{self.class.name}.string_to_time(#{var_name})"
94 when :time then "#{self.class.name}.string_to_dummy_time(#{var_name})"
95 when :date then "#{self.class.name}.string_to_date(#{var_name})"
96 when :binary then "#{self.class.name}.binary_to_string(#{var_name})"
97 when :boolean then "#{self.class.name}.value_to_boolean(#{var_name})"
102 # Returns the human name of the column name.
105 # Column.new('sales_stage', ...).human_name # => 'Sales stage'
107 Base
.human_attribute_name(@name)
110 def extract_default(default
)
115 # Used to convert from Strings to BLOBs
116 def string_to_binary(value
)
120 # Used to convert from BLOBs to Strings
121 def binary_to_string(value
)
125 def string_to_date(string
)
126 return string
unless string
.is_a
?(String
)
127 return nil if string
.empty
?
129 fast_string_to_date(string
) || fallback_string_to_date(string
)
132 def string_to_time(string
)
133 return string
unless string
.is_a
?(String
)
134 return nil if string
.empty
?
136 fast_string_to_time(string
) || fallback_string_to_time(string
)
139 def string_to_dummy_time(string
)
140 return string
unless string
.is_a
?(String
)
141 return nil if string
.empty
?
143 string_to_time
"2000-01-01 #{string}"
146 # convert something to a boolean
147 def value_to_boolean(value
)
148 if value
.is_a
?(String
) && value
.blank
?
151 TRUE_VALUES
.include?(value
)
155 # convert something to a BigDecimal
156 def value_to_decimal(value
)
157 # Using .class is faster than .is_a? and
158 # subclasses of BigDecimal will be handled
160 if value
.class == BigDecimal
162 elsif value
.respond_to
?(:to_d)
170 # '0.123456' -> 123456
171 # '1.123456' -> 123456
172 def microseconds(time
)
173 ((time
[:sec_fraction].to_f
% 1) * 1_000_000).to_i
176 def new_date(year
, mon
, mday
)
178 Date
.new(year
, mon
, mday
) rescue nil
182 def new_time(year
, mon
, mday
, hour
, min
, sec
, microsec
)
183 # Treat 0000-00-00 00:00:00 as nil.
184 return nil if year
.nil? || year
== 0
186 Time
.time_with_datetime_fallback(Base
.default_timezone
, year
, mon
, mday
, hour
, min
, sec
, microsec
) rescue nil
189 def fast_string_to_date(string
)
190 if string
=~ Format
::ISO_DATE
191 new_date
$1.to_i
, $2.to_i
, $3.to_i
195 # Doesn't handle time zones.
196 def fast_string_to_time(string
)
197 if string
=~ Format
::ISO_DATETIME
198 microsec
= ($7.to_f
* 1_000_000).to_i
199 new_time
$1.to_i
, $2.to_i
, $3.to_i
, $4.to_i
, $5.to_i
, $6.to_i
, microsec
203 def fallback_string_to_date(string
)
204 new_date(*::Date._parse(string
, false).values_at(:year, :mon, :mday))
207 def fallback_string_to_time(string
)
208 time_hash
= Date
._parse(string
)
209 time_hash
[:sec_fraction] = microseconds(time_hash
)
211 new_time(*time_hash
.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
216 def extract_limit(sql_type
)
217 $1.to_i
if sql_type
=~
/\((.*)\)/
220 def extract_precision(sql_type
)
221 $2.to_i
if sql_type
=~
/^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
224 def extract_scale(sql_type
)
226 when /^(numeric|decimal|number)\((\d+)\)/i
then 0
227 when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i
then $4.to_i
231 def simplified_type(field_type
)
237 when /decimal|numeric|number/i
238 extract_scale(field_type
) == 0 ? :integer : :decimal
247 when /clob/i
, /text/i
249 when /blob/i
, /binary/i
251 when /char/i
, /string/i
259 class IndexDefinition
< Struct
.new(:table, :name, :unique, :columns) #:nodoc:
262 # Abstract representation of a column definition. Instances of this type
263 # are typically created by methods in TableDefinition, and added to the
264 # +columns+ attribute of said TableDefinition object, in order to be used
265 # for generating a number of table creation or table changing SQL statements.
266 class ColumnDefinition
< Struct
.new(:base, :name, :type, :limit, :precision, :scale, :default, :null) #:nodoc:
269 base
.type_to_sql(type
.to_sym
, limit
, precision
, scale
) rescue type
273 column_sql
= "#{base.quote_column_name(name)} #{sql_type}"
275 column_options
[:null] = null
unless null
.nil?
276 column_options
[:default] = default
unless default
.nil?
277 add_column_options
!(column_sql
, column_options
) unless type
.to_sym
== :primary_key
284 def add_column_options
!(sql
, options
)
285 base
.add_column_options
!(sql
, options
.merge(:column => self))
289 # Represents the schema of an SQL table in an abstract way. This class
290 # provides methods for manipulating the schema representation.
292 # Inside migration files, the +t+ object in +create_table+ and
293 # +change_table+ is actually of this type:
295 # class SomeMigration < ActiveRecord::Migration
297 # create_table :foo do |t|
298 # puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
307 # The table definitions
308 # The Columns are stored as a ColumnDefinition in the +columns+ attribute.
309 class TableDefinition
310 # An array of ColumnDefinition objects, representing the column changes
311 # that have been defined.
312 attr_accessor
:columns
319 # Appends a primary key definition to the table definition.
320 # Can be called multiple times, but this is probably not a good idea.
321 def primary_key(name
)
322 column(name
, :primary_key)
325 # Returns a ColumnDefinition for the column with name +name+.
327 @columns.find
{|column
| column
.name
.to_s
== name
.to_s
}
330 # Instantiates a new column for the table.
331 # The +type+ parameter is normally one of the migrations native types,
332 # which is one of the following:
333 # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
334 # <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
335 # <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
336 # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>.
338 # You may use a type not in this list as long as it is supported by your
339 # database (for example, "polygon" in MySQL), but this will not be database
340 # agnostic and should usually be avoided.
342 # Available options are (none of these exists by default):
343 # * <tt>:limit</tt> -
344 # Requests a maximum column length. This is number of characters for <tt>:string</tt> and <tt>:text</tt> columns and number of bytes for :binary and :integer columns.
345 # * <tt>:default</tt> -
346 # The column's default value. Use nil for NULL.
348 # Allows or disallows +NULL+ values in the column. This option could
349 # have been named <tt>:null_allowed</tt>.
350 # * <tt>:precision</tt> -
351 # Specifies the precision for a <tt>:decimal</tt> column.
352 # * <tt>:scale</tt> -
353 # Specifies the scale for a <tt>:decimal</tt> column.
355 # For clarity's sake: the precision is the number of significant digits,
356 # while the scale is the number of digits that can be stored following
357 # the decimal point. For example, the number 123.45 has a precision of 5
358 # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
359 # range from -999.99 to 999.99.
361 # Please be aware of different RDBMS implementations behavior with
362 # <tt>:decimal</tt> columns:
363 # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
364 # <tt>:precision</tt>, and makes no comments about the requirements of
365 # <tt>:precision</tt>.
366 # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
368 # * PostgreSQL: <tt>:precision</tt> [1..infinity],
369 # <tt>:scale</tt> [0..infinity]. No default.
370 # * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
371 # Internal storage as strings. No default.
372 # * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
373 # but the maximum supported <tt>:precision</tt> is 16. No default.
374 # * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
376 # * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
378 # * Firebird: <tt>:precision</tt> [1..18], <tt>:scale</tt> [0..18].
379 # Default (9,0). Internal types NUMERIC and DECIMAL have different
380 # storage rules, decimal being better.
381 # * FrontBase?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
382 # Default (38,0). WARNING Max <tt>:precision</tt>/<tt>:scale</tt> for
383 # NUMERIC is 19, and DECIMAL is 38.
384 # * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
386 # * Sybase: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
388 # * OpenBase?: Documentation unclear. Claims storage in <tt>double</tt>.
390 # This method returns <tt>self</tt>.
393 # # Assuming td is an instance of TableDefinition
394 # td.column(:granted, :boolean)
397 # td.column(:picture, :binary, :limit => 2.megabytes)
398 # # => picture BLOB(2097152)
400 # td.column(:sales_stage, :string, :limit => 20, :default => 'new', :null => false)
401 # # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL
403 # td.column(:bill_gates_money, :decimal, :precision => 15, :scale => 2)
404 # # => bill_gates_money DECIMAL(15,2)
406 # td.column(:sensor_reading, :decimal, :precision => 30, :scale => 20)
407 # # => sensor_reading DECIMAL(30,20)
409 # # While <tt>:scale</tt> defaults to zero on most databases, it
410 # # probably wouldn't hurt to include it.
411 # td.column(:huge_integer, :decimal, :precision => 30)
412 # # => huge_integer DECIMAL(30)
414 # # Defines a column with a database-specific type.
415 # td.column(:foo, 'polygon')
418 # == Short-hand examples
420 # Instead of calling +column+ directly, you can also work with the short-hand definitions for the default types.
421 # They use the type as the method name instead of as a parameter and allow for multiple columns to be defined
422 # in a single statement.
424 # What can be written like this with the regular calls to column:
426 # create_table "products", :force => true do |t|
427 # t.column "shop_id", :integer
428 # t.column "creator_id", :integer
429 # t.column "name", :string, :default => "Untitled"
430 # t.column "value", :string, :default => "Untitled"
431 # t.column "created_at", :datetime
432 # t.column "updated_at", :datetime
435 # Can also be written as follows using the short-hand:
437 # create_table :products do |t|
438 # t.integer :shop_id, :creator_id
439 # t.string :name, :value, :default => "Untitled"
443 # There's a short-hand method for each of the type values declared at the top. And then there's
444 # TableDefinition#timestamps that'll add created_at and +updated_at+ as datetimes.
446 # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
447 # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of options, these will be
448 # used when creating the <tt>_type</tt> column. So what can be written like this:
450 # create_table :taggings do |t|
451 # t.integer :tag_id, :tagger_id, :taggable_id
452 # t.string :tagger_type
453 # t.string :taggable_type, :default => 'Photo'
456 # Can also be written as follows using references:
458 # create_table :taggings do |t|
460 # t.references :tagger, :polymorphic => true
461 # t.references :taggable, :polymorphic => { :default => 'Photo' }
463 def column(name
, type
, options
= {})
464 column
= self[name
] || ColumnDefinition
.new(@base, name
, type
)
466 column
.limit
= options
[:limit]
467 elsif native
[type
.to_sym
].is_a
?(Hash
)
468 column
.limit
= native
[type
.to_sym
][:limit]
470 column
.precision
= options
[:precision]
471 column
.scale
= options
[:scale]
472 column
.default
= options
[:default]
473 column
.null
= options
[:null]
474 @columns << column
unless @columns.include? column
478 %w( string text integer float decimal datetime timestamp time date binary boolean
).each
do |column_type
|
480 def #{column_type}(*args) # def string(*args)
481 options = args.extract_options! # options = args.extract_options!
482 column_names = args # column_names = args
484 column_names.each { |name| column(name, '#{column_type}', options) } # column_names.each { |name| column(name, 'string', options) }
489 # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
490 # <tt>:updated_at</tt> to the table.
491 def timestamps(*args
)
492 options
= args
.extract_options
!
493 column(:created_at, :datetime, options
)
494 column(:updated_at, :datetime, options
)
497 def references(*args
)
498 options
= args
.extract_options
!
499 polymorphic
= options
.delete(:polymorphic)
501 column("#{col}_id", :integer, options
)
502 column("#{col}_type", :string, polymorphic
.is_a
?(Hash
) ? polymorphic
: options
) unless polymorphic
.nil?
505 alias :belongs_to :references
507 # Returns a String whose contents are the column definitions
508 # concatenated together. This string can then be prepended and appended to
509 # to generate the final SQL to create the table.
516 @base.native_database_types
520 # Represents a SQL table in an abstract way for updating a table.
521 # Also see TableDefinition and SchemaStatements#create_table
523 # Available transformations are:
525 # change_table :table do |t|
546 # t.remove_references
547 # t.remove_belongs_to
549 # t.remove_timestamps
553 def initialize(table_name
, base
)
554 @table_name = table_name
558 # Adds a new column to the named table.
559 # See TableDefinition#column for details of the options you can use.
561 # ====== Creating a simple column
562 # t.column(:name, :string)
563 def column(column_name
, type
, options
= {})
564 @base.add_column(@table_name, column_name
, type
, options
)
567 # Adds a new index to the table. +column_name+ can be a single Symbol, or
568 # an Array of Symbols. See SchemaStatements#add_index
571 # ====== Creating a simple index
573 # ====== Creating a unique index
574 # t.index([:branch_id, :party_id], :unique => true)
575 # ====== Creating a named index
576 # t.index([:branch_id, :party_id], :unique => true, :name => 'by_branch_party')
577 def index(column_name
, options
= {})
578 @base.add_index(@table_name, column_name
, options
)
581 # Adds timestamps (created_at and updated_at) columns to the table. See SchemaStatements#add_timestamps
585 @base.add_timestamps(@table_name)
588 # Changes the column's definition according to the new options.
589 # See TableDefinition#column for details of the options you can use.
591 # t.change(:name, :string, :limit => 80)
592 # t.change(:description, :text)
593 def change(column_name
, type
, options
= {})
594 @base.change_column(@table_name, column_name
, type
, options
)
597 # Sets a new default value for a column. See SchemaStatements#change_column_default
599 # t.change_default(:qualification, 'new')
600 # t.change_default(:authorized, 1)
601 def change_default(column_name
, default
)
602 @base.change_column_default(@table_name, column_name
, default
)
605 # Removes the column(s) from the table definition.
607 # t.remove(:qualification)
608 # t.remove(:qualification, :experience)
609 def remove(*column_names
)
610 @base.remove_column(@table_name, column_names
)
613 # Removes the given index from the table.
616 # ====== Remove the suppliers_name_index in the suppliers table
617 # t.remove_index :name
618 # ====== Remove the index named accounts_branch_id_index in the accounts table
619 # t.remove_index :column => :branch_id
620 # ====== Remove the index named accounts_branch_id_party_id_index in the accounts table
621 # t.remove_index :column => [:branch_id, :party_id]
622 # ====== Remove the index named by_branch_party in the accounts table
623 # t.remove_index :name => :by_branch_party
624 def remove_index(options
= {})
625 @base.remove_index(@table_name, options
)
628 # Removes the timestamp columns (created_at and updated_at) from the table.
630 # t.remove_timestamps
631 def remove_timestamps
632 @base.remove_timestamps(@table_name)
637 # t.rename(:description, :name)
638 def rename(column_name
, new_column_name
)
639 @base.rename_column(@table_name, column_name
, new_column_name
)
642 # Adds a reference. Optionally adds a +type+ column.
643 # <tt>references</tt> and <tt>belongs_to</tt> are acceptable.
645 # t.references(:goat)
646 # t.references(:goat, :polymorphic => true)
647 # t.belongs_to(:goat)
648 def references(*args
)
649 options
= args
.extract_options
!
650 polymorphic
= options
.delete(:polymorphic)
652 @base.add_column(@table_name, "#{col}_id", :integer, options
)
653 @base.add_column(@table_name, "#{col}_type", :string, polymorphic
.is_a
?(Hash
) ? polymorphic
: options
) unless polymorphic
.nil?
656 alias :belongs_to :references
658 # Removes a reference. Optionally removes a +type+ column.
659 # <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
661 # t.remove_references(:goat)
662 # t.remove_references(:goat, :polymorphic => true)
663 # t.remove_belongs_to(:goat)
664 def remove_references(*args
)
665 options
= args
.extract_options
!
666 polymorphic
= options
.delete(:polymorphic)
668 @base.remove_column(@table_name, "#{col}_id")
669 @base.remove_column(@table_name, "#{col}_type") unless polymorphic
.nil?
672 alias :remove_belongs_to :remove_references
674 # Adds a column or columns of a specified type
677 # t.string(:goat, :sheep)
678 %w( string text integer float decimal datetime timestamp time date binary boolean
).each
do |column_type
|
680 def #{column_type}(*args) # def string(*args)
681 options = args.extract_options! # options = args.extract_options!
682 column_names = args # column_names = args
684 column_names.each do |name| # column_names.each do |name|
685 column = ColumnDefinition.new(@base, name, '#{column_type}') # column = ColumnDefinition.new(@base, name, 'string')
686 if options[:limit] # if options[:limit]
687 column.limit = options[:limit] # column.limit = options[:limit]
688 elsif native['#{column_type}'.to_sym].is_a?(Hash) # elsif native['string'.to_sym].is_a?(Hash)
689 column.limit = native['#{column_type}'.to_sym][:limit] # column.limit = native['string'.to_sym][:limit]
691 column.precision = options[:precision] # column.precision = options[:precision]
692 column.scale = options[:scale] # column.scale = options[:scale]
693 column.default = options[:default] # column.default = options[:default]
694 column.null = options[:null] # column.null = options[:null]
695 @base.add_column(@table_name, name, column.sql_type, options) # @base.add_column(@table_name, name, column.sql_type, options)
703 @base.native_database_types