Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/tags/rel_1-2-3/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb

Revision 5945, 12.5 kB (checked in by bitsweat, 2 years ago)

Merge [5944] from trunk. References #7048.

Line 
1 require 'date'
2 require 'bigdecimal'
3 require 'bigdecimal/util'
4
5 module ActiveRecord
6   module ConnectionAdapters #:nodoc:
7     # An abstract definition of a column in a table.
8     class Column
9       attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale
10       attr_accessor :primary
11
12       # Instantiates a new column in the table.
13       #
14       # +name+ is the column's name, as in <tt><b>supplier_id</b> int(11)</tt>.
15       # +default+ is the type-casted default value, such as <tt>sales_stage varchar(20) default <b>'new'</b></tt>.
16       # +sql_type+ is only used to extract the column's length, if necessary.  For example, <tt>company_name varchar(<b>60</b>)</tt>.
17       # +null+ determines if this column allows +NULL+ values.
18       def initialize(name, default, sql_type = nil, null = true)
19         @name, @sql_type, @null = name, sql_type, null
20         @limit, @precision, @scale  = extract_limit(sql_type), extract_precision(sql_type), extract_scale(sql_type)
21         @type = simplified_type(sql_type)
22         @default = type_cast(default)
23
24         @primary = nil
25       end
26
27       def text?
28         [:string, :text].include? type
29       end
30
31       def number?
32         [:float, :integer, :decimal].include? type
33       end
34
35       # Returns the Ruby class that corresponds to the abstract data type.
36       def klass
37         case type
38           when :integer       then Fixnum
39           when :float         then Float
40           when :decimal       then BigDecimal
41           when :datetime      then Time
42           when :date          then Date
43           when :timestamp     then Time
44           when :time          then Time
45           when :text, :string then String
46           when :binary        then String
47           when :boolean       then Object
48         end
49       end
50
51       # Casts value (which is a String) to an appropriate instance.
52       def type_cast(value)
53         return nil if value.nil?
54         case type
55           when :string    then value
56           when :text      then value
57           when :integer   then value.to_i rescue value ? 1 : 0
58           when :float     then value.to_f
59           when :decimal   then self.class.value_to_decimal(value)
60           when :datetime  then self.class.string_to_time(value)
61           when :timestamp then self.class.string_to_time(value)
62           when :time      then self.class.string_to_dummy_time(value)
63           when :date      then self.class.string_to_date(value)
64           when :binary    then self.class.binary_to_string(value)
65           when :boolean   then self.class.value_to_boolean(value)
66           else value
67         end
68       end
69
70       def type_cast_code(var_name)
71         case type
72           when :string    then nil
73           when :text      then nil
74           when :integer   then "(#{var_name}.to_i rescue #{var_name} ? 1 : 0)"
75           when :float     then "#{var_name}.to_f"
76           when :decimal   then "#{self.class.name}.value_to_decimal(#{var_name})"
77           when :datetime  then "#{self.class.name}.string_to_time(#{var_name})"
78           when :timestamp then "#{self.class.name}.string_to_time(#{var_name})"
79           when :time      then "#{self.class.name}.string_to_dummy_time(#{var_name})"
80           when :date      then "#{self.class.name}.string_to_date(#{var_name})"
81           when :binary    then "#{self.class.name}.binary_to_string(#{var_name})"
82           when :boolean   then "#{self.class.name}.value_to_boolean(#{var_name})"
83           else nil
84         end
85       end
86
87       # Returns the human name of the column name.
88       #
89       # ===== Examples
90       #  Column.new('sales_stage', ...).human_name #=> 'Sales stage'
91       def human_name
92         Base.human_attribute_name(@name)
93       end
94
95       # Used to convert from Strings to BLOBs
96       def self.string_to_binary(value)
97         value
98       end
99
100       # Used to convert from BLOBs to Strings
101       def self.binary_to_string(value)
102         value
103       end
104
105       def self.string_to_date(string)
106         return string unless string.is_a?(String)
107         date_array = ParseDate.parsedate(string)
108         # treat 0000-00-00 as nil
109         Date.new(date_array[0], date_array[1], date_array[2]) rescue nil
110       end
111
112       def self.string_to_time(string)
113         return string unless string.is_a?(String)
114         time_hash = Date._parse(string)
115         time_hash[:sec_fraction] = microseconds(time_hash)
116         time_array = time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction)
117         # treat 0000-00-00 00:00:00 as nil
118         Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
119       end
120
121       def self.string_to_dummy_time(string)
122         return string unless string.is_a?(String)
123         return nil if string.empty?
124         time_hash = Date._parse(string)
125         time_hash[:sec_fraction] = microseconds(time_hash)
126         # pad the resulting array with dummy date information
127         time_array = [2000, 1, 1]
128         time_array += time_hash.values_at(:hour, :min, :sec, :sec_fraction)
129         Time.send(Base.default_timezone, *time_array) rescue nil
130       end
131
132       # convert something to a boolean
133       def self.value_to_boolean(value)
134         if value == true || value == false
135           value
136         else
137           %w(true t 1).include?(value.to_s.downcase)
138         end
139       end
140
141       # convert something to a BigDecimal
142       def self.value_to_decimal(value)
143         if value.is_a?(BigDecimal)
144           value
145         elsif value.respond_to?(:to_d)
146           value.to_d
147         else
148           value.to_s.to_d
149         end
150       end
151
152       private
153         # '0.123456' -> 123456
154         # '1.123456' -> 123456
155         def self.microseconds(time)
156           ((time[:sec_fraction].to_f % 1) * 1_000_000).to_i
157         end
158
159         def extract_limit(sql_type)
160           $1.to_i if sql_type =~ /\((.*)\)/
161         end
162
163         def extract_precision(sql_type)
164           $2.to_i if sql_type =~ /^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
165         end
166
167         def extract_scale(sql_type)
168           case sql_type
169             when /^(numeric|decimal|number)\((\d+)\)/i then 0
170             when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i then $4.to_i
171           end
172         end
173
174         def simplified_type(field_type)
175           case field_type
176             when /int/i
177               :integer
178             when /float|double/i
179               :float
180             when /decimal|numeric|number/i
181               extract_scale(field_type) == 0 ? :integer : :decimal
182             when /datetime/i
183               :datetime
184             when /timestamp/i
185               :timestamp
186             when /time/i
187               :time
188             when /date/i
189               :date
190             when /clob/i, /text/i
191               :text
192             when /blob/i, /binary/i
193               :binary
194             when /char/i, /string/i
195               :string
196             when /boolean/i
197               :boolean
198           end
199         end
200     end
201
202     class IndexDefinition < Struct.new(:table, :name, :unique, :columns) #:nodoc:
203     end
204
205     class ColumnDefinition < Struct.new(:base, :name, :type, :limit, :precision, :scale, :default, :null) #:nodoc:
206      
207       def sql_type
208         base.type_to_sql(type.to_sym, limit, precision, scale) rescue type
209       end
210      
211       def to_sql
212         column_sql = "#{base.quote_column_name(name)} #{sql_type}"
213         add_column_options!(column_sql, :null => null, :default => default) unless type.to_sym == :primary_key
214         column_sql
215       end
216       alias to_s :to_sql
217
218       private
219
220         def add_column_options!(sql, options)
221           base.add_column_options!(sql, options.merge(:column => self))
222         end
223     end
224
225     # Represents a SQL table in an abstract way.
226     # Columns are stored as ColumnDefinition in the #columns attribute.
227     class TableDefinition
228       attr_accessor :columns
229
230       def initialize(base)
231         @columns = []
232         @base = base
233       end
234
235       # Appends a primary key definition to the table definition.
236       # Can be called multiple times, but this is probably not a good idea.
237       def primary_key(name)
238         column(name, :primary_key)
239       end
240
241       # Returns a ColumnDefinition for the column with name +name+.
242       def [](name)
243         @columns.find {|column| column.name.to_s == name.to_s}
244       end
245
246       # Instantiates a new column for the table.
247       # The +type+ parameter must be one of the following values:
248       # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
249       # <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
250       # <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
251       # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>.
252       #
253       # Available options are (none of these exists by default):
254       # * <tt>:limit</tt>:
255       #   Requests a maximum column length (<tt>:string</tt>, <tt>:text</tt>,
256       #   <tt>:binary</tt> or <tt>:integer</tt> columns only)
257       # * <tt>:default</tt>:
258       #   The column's default value. Use nil for NULL.
259       # * <tt>:null</tt>:
260       #   Allows or disallows +NULL+ values in the column.  This option could
261       #   have been named <tt>:null_allowed</tt>.
262       # * <tt>:precision</tt>:
263       #   Specifies the precision for a <tt>:decimal</tt> column.
264       # * <tt>:scale</tt>:
265       #   Specifies the scale for a <tt>:decimal</tt> column.
266       #
267       # Please be aware of different RDBMS implementations behavior with
268       # <tt>:decimal</tt> columns:
269       # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
270       #   <tt>:precision</tt>, and makes no comments about the requirements of
271       #   <tt>:precision</tt>.
272       # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
273       #   Default is (10,0).
274       # * PostgreSQL: <tt>:precision</tt> [1..infinity],
275       #   <tt>:scale</tt> [0..infinity]. No default.
276       # * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
277       #   Internal storage as strings. No default.
278       # * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
279       #   but the maximum supported <tt>:precision</tt> is 16. No default.
280       # * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
281       #   Default is (38,0).
282       # * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
283       #   Default unknown.
284       # * Firebird: <tt>:precision</tt> [1..18], <tt>:scale</tt> [0..18].
285       #   Default (9,0). Internal types NUMERIC and DECIMAL have different
286       #   storage rules, decimal being better.
287       # * FrontBase?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
288       #   Default (38,0). WARNING Max <tt>:precision</tt>/<tt>:scale</tt> for
289       #   NUMERIC is 19, and DECIMAL is 38.
290       # * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
291       #   Default (38,0).
292       # * Sybase: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
293       #   Default (38,0).
294       # * OpenBase?: Documentation unclear. Claims storage in <tt>double</tt>.
295       #
296       # This method returns <tt>self</tt>.
297       #
298       # ===== Examples
299       #  # Assuming td is an instance of TableDefinition
300       #  td.column(:granted, :boolean)
301       #    #=> granted BOOLEAN
302       #
303       #  td.column(:picture, :binary, :limit => 2.megabytes)
304       #    #=> picture BLOB(2097152)
305       #
306       #  td.column(:sales_stage, :string, :limit => 20, :default => 'new', :null => false)
307       #    #=> sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL
308       #
309       #  def.column(:bill_gates_money, :decimal, :precision => 15, :scale => 2)
310       #    #=> bill_gates_money DECIMAL(15,2)
311       #
312       #  def.column(:sensor_reading, :decimal, :precision => 30, :scale => 20)
313       #    #=> sensor_reading DECIMAL(30,20)
314       #
315       #  # While <tt>:scale</tt> defaults to zero on most databases, it
316       #  # probably wouldn't hurt to include it.
317       #  def.column(:huge_integer, :decimal, :precision => 30)
318       #    #=> huge_integer DECIMAL(30)
319       def column(name, type, options = {})
320         column = self[name] || ColumnDefinition.new(@base, name, type)
321         column.limit = options[:limit] || native[type.to_sym][:limit] if options[:limit] or native[type.to_sym]
322         column.precision = options[:precision]
323         column.scale = options[:scale]
324         column.default = options[:default]
325         column.null = options[:null]
326         @columns << column unless @columns.include? column
327         self
328       end
329
330       # Returns a String whose contents are the column definitions
331       # concatenated together.  This string can then be pre and appended to
332       # to generate the final SQL to create the table.
333       def to_sql
334         @columns * ', '
335       end
336
337       private
338         def native
339           @base.native_database_types
340         end
341     end
342   end
343 end
Note: See TracBrowser for help on using the browser.