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
13 ISO_DATE
= /\A(\d{4})-(\d\d)-(\d\d)\z/
14 ISO_DATETIME
= /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
17 attr_reader
:name, :default, :type, :limit, :null, :sql_type, :precision, :scale
18 attr_accessor
:primary
20 # Instantiates a new column in the table.
22 # +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
23 # +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
24 # +sql_type+ is only used to extract the column's length, if necessary. For example +60+ in <tt>company_name varchar(60)</tt>.
25 # +null+ determines if this column allows +NULL+ values.
26 def initialize(name
, default
, sql_type
= nil, null
= true)
27 @name, @sql_type, @null = name
, sql_type
, null
28 @limit, @precision, @scale = extract_limit(sql_type
), extract_precision(sql_type
), extract_scale(sql_type
)
29 @type = simplified_type(sql_type
)
30 @default = extract_default(default
)
36 type
== :string || type
== :text
40 type
== :integer || type
== :float || type
== :decimal
47 # Returns the Ruby class that corresponds to the abstract data type.
50 when :integer then Fixnum
51 when :float then Float
52 when :decimal then BigDecimal
53 when :datetime then Time
55 when :timestamp then Time
57 when :text, :string then String
58 when :binary then String
59 when :boolean then Object
63 # Casts value (which is a String) to an appropriate instance.
65 return nil if value
.nil?
67 when :string then value
69 when :integer then value
.to_i
rescue value
? 1 : 0
70 when :float then value
.to_f
71 when :decimal then self.class.value_to_decimal(value
)
72 when :datetime then self.class.string_to_time(value
)
73 when :timestamp then self.class.string_to_time(value
)
74 when :time then self.class.string_to_dummy_time(value
)
75 when :date then self.class.string_to_date(value
)
76 when :binary then self.class.binary_to_string(value
)
77 when :boolean then self.class.value_to_boolean(value
)
82 def type_cast_code(var_name
)
86 when :integer then "(#{var_name}.to_i rescue #{var_name} ? 1 : 0)"
87 when :float then "#{var_name}.to_f"
88 when :decimal then "#{self.class.name}.value_to_decimal(#{var_name})"
89 when :datetime then "#{self.class.name}.string_to_time(#{var_name})"
90 when :timestamp then "#{self.class.name}.string_to_time(#{var_name})"
91 when :time then "#{self.class.name}.string_to_dummy_time(#{var_name})"
92 when :date then "#{self.class.name}.string_to_date(#{var_name})"
93 when :binary then "#{self.class.name}.binary_to_string(#{var_name})"
94 when :boolean then "#{self.class.name}.value_to_boolean(#{var_name})"
99 # Returns the human name of the column name.
102 # Column.new('sales_stage', ...).human_name # => 'Sales stage'
104 Base
.human_attribute_name(@name)
107 def extract_default(default
)
112 # Used to convert from Strings to BLOBs
113 def string_to_binary(value
)
117 # Used to convert from BLOBs to Strings
118 def binary_to_string(value
)
122 def string_to_date(string
)
123 return string
unless string
.is_a
?(String
)
124 return nil if string
.empty
?
126 fast_string_to_date(string
) || fallback_string_to_date(string
)
129 def string_to_time(string
)
130 return string
unless string
.is_a
?(String
)
131 return nil if string
.empty
?
133 fast_string_to_time(string
) || fallback_string_to_time(string
)
136 def string_to_dummy_time(string
)
137 return string
unless string
.is_a
?(String
)
138 return nil if string
.empty
?
140 string_to_time
"2000-01-01 #{string}"
143 # convert something to a boolean
144 def value_to_boolean(value
)
145 if value
.is_a
?(String
) && value
.blank
?
148 TRUE_VALUES
.include?(value
)
152 # convert something to a BigDecimal
153 def value_to_decimal(value
)
154 # Using .class is faster than .is_a? and
155 # subclasses of BigDecimal will be handled
157 if value
.class == BigDecimal
159 elsif value
.respond_to
?(:to_d)
167 # '0.123456' -> 123456
168 # '1.123456' -> 123456
169 def microseconds(time
)
170 ((time
[:sec_fraction].to_f
% 1) * 1_000_000).to_i
173 def new_date(year
, mon
, mday
)
175 Date
.new(year
, mon
, mday
) rescue nil
179 def new_time(year
, mon
, mday
, hour
, min
, sec
, microsec
)
180 # Treat 0000-00-00 00:00:00 as nil.
181 return nil if year
.nil? || year
== 0
183 Time
.time_with_datetime_fallback(Base
.default_timezone
, year
, mon
, mday
, hour
, min
, sec
, microsec
) rescue nil
186 def fast_string_to_date(string
)
187 if string
=~ Format
::ISO_DATE
188 new_date
$1.to_i
, $2.to_i
, $3.to_i
192 # Doesn't handle time zones.
193 def fast_string_to_time(string
)
194 if string
=~ Format
::ISO_DATETIME
195 microsec
= ($7.to_f
* 1_000_000).to_i
196 new_time
$1.to_i
, $2.to_i
, $3.to_i
, $4.to_i
, $5.to_i
, $6.to_i
, microsec
200 def fallback_string_to_date(string
)
201 new_date(*::Date._parse(string
, false).values_at(:year, :mon, :mday))
204 def fallback_string_to_time(string
)
205 time_hash
= Date
._parse(string
)
206 time_hash
[:sec_fraction] = microseconds(time_hash
)
208 new_time(*time_hash
.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
213 def extract_limit(sql_type
)
214 $1.to_i
if sql_type
=~
/\((.*)\)/
217 def extract_precision(sql_type
)
218 $2.to_i
if sql_type
=~
/^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
221 def extract_scale(sql_type
)
223 when /^(numeric|decimal|number)\((\d+)\)/i
then 0
224 when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i
then $4.to_i
228 def simplified_type(field_type
)
234 when /decimal|numeric|number/i
235 extract_scale(field_type
) == 0 ? :integer : :decimal
244 when /clob/i
, /text/i
246 when /blob/i
, /binary/i
248 when /char/i
, /string/i
256 class IndexDefinition
< Struct
.new(:table, :name, :unique, :columns) #:nodoc:
259 # Abstract representation of a column definition. Instances of this type
260 # are typically created by methods in TableDefinition, and added to the
261 # +columns+ attribute of said TableDefinition object, in order to be used
262 # for generating a number of table creation or table changing SQL statements.
263 class ColumnDefinition
< Struct
.new(:base, :name, :type, :limit, :precision, :scale, :default, :null) #:nodoc:
266 base
.type_to_sql(type
.to_sym
, limit
, precision
, scale
) rescue type
270 column_sql
= "#{base.quote_column_name(name)} #{sql_type}"
272 column_options
[:null] = null
unless null
.nil?
273 column_options
[:default] = default
unless default
.nil?
274 add_column_options
!(column_sql
, column_options
) unless type
.to_sym
== :primary_key
281 def add_column_options
!(sql
, options
)
282 base
.add_column_options
!(sql
, options
.merge(:column => self))
286 # Represents the schema of an SQL table in an abstract way. This class
287 # provides methods for manipulating the schema representation.
289 # Inside migration files, the +t+ object in +create_table+ and
290 # +change_table+ is actually of this type:
292 # class SomeMigration < ActiveRecord::Migration
294 # create_table :foo do |t|
295 # puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
304 # The table definitions
305 # The Columns are stored as a ColumnDefinition in the +columns+ attribute.
306 class TableDefinition
307 # An array of ColumnDefinition objects, representing the column changes
308 # that have been defined.
309 attr_accessor
:columns
316 # Appends a primary key definition to the table definition.
317 # Can be called multiple times, but this is probably not a good idea.
318 def primary_key(name
)
319 column(name
, :primary_key)
322 # Returns a ColumnDefinition for the column with name +name+.
324 @columns.find
{|column
| column
.name
.to_s
== name
.to_s
}
327 # Instantiates a new column for the table.
328 # The +type+ parameter is normally one of the migrations native types,
329 # which is one of the following:
330 # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
331 # <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
332 # <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
333 # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>.
335 # You may use a type not in this list as long as it is supported by your
336 # database (for example, "polygon" in MySQL), but this will not be database
337 # agnostic and should usually be avoided.
339 # Available options are (none of these exists by default):
340 # * <tt>:limit</tt> -
341 # 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.
342 # * <tt>:default</tt> -
343 # The column's default value. Use nil for NULL.
345 # Allows or disallows +NULL+ values in the column. This option could
346 # have been named <tt>:null_allowed</tt>.
347 # * <tt>:precision</tt> -
348 # Specifies the precision for a <tt>:decimal</tt> column.
349 # * <tt>:scale</tt> -
350 # Specifies the scale for a <tt>:decimal</tt> column.
352 # For clarity's sake: the precision is the number of significant digits,
353 # while the scale is the number of digits that can be stored following
354 # the decimal point. For example, the number 123.45 has a precision of 5
355 # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
356 # range from -999.99 to 999.99.
358 # Please be aware of different RDBMS implementations behavior with
359 # <tt>:decimal</tt> columns:
360 # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
361 # <tt>:precision</tt>, and makes no comments about the requirements of
362 # <tt>:precision</tt>.
363 # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
365 # * PostgreSQL: <tt>:precision</tt> [1..infinity],
366 # <tt>:scale</tt> [0..infinity]. No default.
367 # * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
368 # Internal storage as strings. No default.
369 # * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
370 # but the maximum supported <tt>:precision</tt> is 16. No default.
371 # * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
373 # * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
375 # * Firebird: <tt>:precision</tt> [1..18], <tt>:scale</tt> [0..18].
376 # Default (9,0). Internal types NUMERIC and DECIMAL have different
377 # storage rules, decimal being better.
378 # * FrontBase?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
379 # Default (38,0). WARNING Max <tt>:precision</tt>/<tt>:scale</tt> for
380 # NUMERIC is 19, and DECIMAL is 38.
381 # * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
383 # * Sybase: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
385 # * OpenBase?: Documentation unclear. Claims storage in <tt>double</tt>.
387 # This method returns <tt>self</tt>.
390 # # Assuming td is an instance of TableDefinition
391 # td.column(:granted, :boolean)
394 # td.column(:picture, :binary, :limit => 2.megabytes)
395 # # => picture BLOB(2097152)
397 # td.column(:sales_stage, :string, :limit => 20, :default => 'new', :null => false)
398 # # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL
400 # td.column(:bill_gates_money, :decimal, :precision => 15, :scale => 2)
401 # # => bill_gates_money DECIMAL(15,2)
403 # td.column(:sensor_reading, :decimal, :precision => 30, :scale => 20)
404 # # => sensor_reading DECIMAL(30,20)
406 # # While <tt>:scale</tt> defaults to zero on most databases, it
407 # # probably wouldn't hurt to include it.
408 # td.column(:huge_integer, :decimal, :precision => 30)
409 # # => huge_integer DECIMAL(30)
411 # # Defines a column with a database-specific type.
412 # td.column(:foo, 'polygon')
415 # == Short-hand examples
417 # Instead of calling +column+ directly, you can also work with the short-hand definitions for the default types.
418 # They use the type as the method name instead of as a parameter and allow for multiple columns to be defined
419 # in a single statement.
421 # What can be written like this with the regular calls to column:
423 # create_table "products", :force => true do |t|
424 # t.column "shop_id", :integer
425 # t.column "creator_id", :integer
426 # t.column "name", :string, :default => "Untitled"
427 # t.column "value", :string, :default => "Untitled"
428 # t.column "created_at", :datetime
429 # t.column "updated_at", :datetime
432 # Can also be written as follows using the short-hand:
434 # create_table :products do |t|
435 # t.integer :shop_id, :creator_id
436 # t.string :name, :value, :default => "Untitled"
440 # There's a short-hand method for each of the type values declared at the top. And then there's
441 # TableDefinition#timestamps that'll add created_at and +updated_at+ as datetimes.
443 # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
444 # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of options, these will be
445 # used when creating the <tt>_type</tt> column. So what can be written like this:
447 # create_table :taggings do |t|
448 # t.integer :tag_id, :tagger_id, :taggable_id
449 # t.string :tagger_type
450 # t.string :taggable_type, :default => 'Photo'
453 # Can also be written as follows using references:
455 # create_table :taggings do |t|
457 # t.references :tagger, :polymorphic => true
458 # t.references :taggable, :polymorphic => { :default => 'Photo' }
460 def column(name
, type
, options
= {})
461 column
= self[name
] || ColumnDefinition
.new(@base, name
, type
)
463 column
.limit
= options
[:limit]
464 elsif native
[type
.to_sym
].is_a
?(Hash
)
465 column
.limit
= native
[type
.to_sym
][:limit]
467 column
.precision
= options
[:precision]
468 column
.scale
= options
[:scale]
469 column
.default
= options
[:default]
470 column
.null
= options
[:null]
471 @columns << column
unless @columns.include? column
475 %w( string text integer float decimal datetime timestamp time date binary boolean
).each
do |column_type
|
477 def #{column_type}(*args)
478 options = args.extract_options!
481 column_names.each { |name| column(name, '#{column_type}', options) }
486 # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
487 # <tt>:updated_at</tt> to the table.
488 def timestamps(*args
)
489 options
= args
.extract_options
!
490 column(:created_at, :datetime, options
)
491 column(:updated_at, :datetime, options
)
494 def references(*args
)
495 options
= args
.extract_options
!
496 polymorphic
= options
.delete(:polymorphic)
498 column("#{col}_id", :integer, options
)
499 column("#{col}_type", :string, polymorphic
.is_a
?(Hash
) ? polymorphic
: options
) unless polymorphic
.nil?
502 alias :belongs_to :references
504 # Returns a String whose contents are the column definitions
505 # concatenated together. This string can then be prepended and appended to
506 # to generate the final SQL to create the table.
513 @base.native_database_types
517 # Represents a SQL table in an abstract way for updating a table.
518 # Also see TableDefinition and SchemaStatements#create_table
520 # Available transformations are:
522 # change_table :table do |t|
543 # t.remove_references
544 # t.remove_belongs_to
546 # t.remove_timestamps
550 def initialize(table_name
, base
)
551 @table_name = table_name
555 # Adds a new column to the named table.
556 # See TableDefinition#column for details of the options you can use.
558 # ====== Creating a simple column
559 # t.column(:name, :string)
560 def column(column_name
, type
, options
= {})
561 @base.add_column(@table_name, column_name
, type
, options
)
564 # Adds a new index to the table. +column_name+ can be a single Symbol, or
565 # an Array of Symbols. See SchemaStatements#add_index
568 # ====== Creating a simple index
570 # ====== Creating a unique index
571 # t.index([:branch_id, :party_id], :unique => true)
572 # ====== Creating a named index
573 # t.index([:branch_id, :party_id], :unique => true, :name => 'by_branch_party')
574 def index(column_name
, options
= {})
575 @base.add_index(@table_name, column_name
, options
)
578 # Adds timestamps (created_at and updated_at) columns to the table. See SchemaStatements#add_timestamps
582 @base.add_timestamps(@table_name)
585 # Changes the column's definition according to the new options.
586 # See TableDefinition#column for details of the options you can use.
588 # t.change(:name, :string, :limit => 80)
589 # t.change(:description, :text)
590 def change(column_name
, type
, options
= {})
591 @base.change_column(@table_name, column_name
, type
, options
)
594 # Sets a new default value for a column. See SchemaStatements#change_column_default
596 # t.change_default(:qualification, 'new')
597 # t.change_default(:authorized, 1)
598 def change_default(column_name
, default
)
599 @base.change_column_default(@table_name, column_name
, default
)
602 # Removes the column(s) from the table definition.
604 # t.remove(:qualification)
605 # t.remove(:qualification, :experience)
606 def remove(*column_names
)
607 @base.remove_column(@table_name, column_names
)
610 # Removes the given index from the table.
613 # ====== Remove the suppliers_name_index in the suppliers table
614 # t.remove_index :name
615 # ====== Remove the index named accounts_branch_id_index in the accounts table
616 # t.remove_index :column => :branch_id
617 # ====== Remove the index named accounts_branch_id_party_id_index in the accounts table
618 # t.remove_index :column => [:branch_id, :party_id]
619 # ====== Remove the index named by_branch_party in the accounts table
620 # t.remove_index :name => :by_branch_party
621 def remove_index(options
= {})
622 @base.remove_index(@table_name, options
)
625 # Removes the timestamp columns (created_at and updated_at) from the table.
627 # t.remove_timestamps
628 def remove_timestamps
629 @base.remove_timestamps(@table_name)
634 # t.rename(:description, :name)
635 def rename(column_name
, new_column_name
)
636 @base.rename_column(@table_name, column_name
, new_column_name
)
639 # Adds a reference. Optionally adds a +type+ column.
640 # <tt>references</tt> and <tt>belongs_to</tt> are acceptable.
642 # t.references(:goat)
643 # t.references(:goat, :polymorphic => true)
644 # t.belongs_to(:goat)
645 def references(*args
)
646 options
= args
.extract_options
!
647 polymorphic
= options
.delete(:polymorphic)
649 @base.add_column(@table_name, "#{col}_id", :integer, options
)
650 @base.add_column(@table_name, "#{col}_type", :string, polymorphic
.is_a
?(Hash
) ? polymorphic
: options
) unless polymorphic
.nil?
653 alias :belongs_to :references
655 # Removes a reference. Optionally removes a +type+ column.
656 # <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
658 # t.remove_references(:goat)
659 # t.remove_references(:goat, :polymorphic => true)
660 # t.remove_belongs_to(:goat)
661 def remove_references(*args
)
662 options
= args
.extract_options
!
663 polymorphic
= options
.delete(:polymorphic)
665 @base.remove_column(@table_name, "#{col}_id")
666 @base.remove_column(@table_name, "#{col}_type") unless polymorphic
.nil?
669 alias :remove_belongs_to :remove_references
671 # Adds a column or columns of a specified type
674 # t.string(:goat, :sheep)
675 %w( string text integer float decimal datetime timestamp time date binary boolean
).each
do |column_type
|
677 def #{column_type}(*args)
678 options = args.extract_options!
681 column_names.each do |name|
682 column = ColumnDefinition.new(@base, name, '#{column_type}')
684 column.limit = options[:limit]
685 elsif native['#{column_type}'.to_sym].is_a?(Hash)
686 column.limit = native['#{column_type}'.to_sym][:limit]
688 column.precision = options[:precision]
689 column.scale = options[:scale]
690 column.default = options[:default]
691 column.null = options[:null]
692 @base.add_column(@table_name, name, column.sql_type, options)
700 @base.native_database_types