schema_definitions.rb 17.9 KB
Newer Older
1
require 'date'
2
require 'set'
3 4
require 'bigdecimal'
require 'bigdecimal/util'
5

6 7
module ActiveRecord
  module ConnectionAdapters #:nodoc:
8 9 10
    # Abstract representation of an index definition on a table. Instances of
    # this type are typically created and returned by methods in database
    # adapters. e.g. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter#indexes
11
    class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders, :where) #:nodoc:
12 13
    end

P
Pratik Naik 已提交
14 15 16 17
    # Abstract representation of a column definition. Instances of this type
    # are typically created by methods in TableDefinition, and added to the
    # +columns+ attribute of said TableDefinition object, in order to be used
    # for generating a number of table creation or table changing SQL statements.
18
    class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null) #:nodoc:
19 20 21 22
      def string_to_binary(value)
        value
      end

A
Aaron Patterson 已提交
23
      def primary_key?
A
Anupam Choudhury 已提交
24
        type.to_sym == :primary_key
A
Aaron Patterson 已提交
25
      end
26 27
    end

P
Pratik Naik 已提交
28 29 30
    # Represents the schema of an SQL table in an abstract way. This class
    # provides methods for manipulating the schema representation.
    #
31 32
    # Inside migration files, the +t+ object in +create_table+
    # is actually of this type:
P
Pratik Naik 已提交
33 34
    #
    #   class SomeMigration < ActiveRecord::Migration
A
Akira Matsuda 已提交
35
    #     def up
P
Pratik Naik 已提交
36 37 38 39
    #       create_table :foo do |t|
    #         puts t.class  # => "ActiveRecord::ConnectionAdapters::TableDefinition"
    #       end
    #     end
P
Pratik Naik 已提交
40
    #
A
Akira Matsuda 已提交
41
    #     def down
P
Pratik Naik 已提交
42 43 44 45 46 47
    #       ...
    #     end
    #   end
    #
    # The table definitions
    # The Columns are stored as a ColumnDefinition in the +columns+ attribute.
48
    class TableDefinition
P
Pratik Naik 已提交
49 50
      # An array of ColumnDefinition objects, representing the column changes
      # that have been defined.
51
      attr_accessor :indexes
52
      attr_reader :name, :temporary, :options
53

54
      def initialize(types, name, temporary, options)
55
        @columns_hash = {}
56
        @indexes = {}
57
        @native = types
58 59 60
        @temporary = temporary
        @options = options
        @name = name
61 62
      end

63 64
      def columns; @columns_hash.values; end

65 66
      # Appends a primary key definition to the table definition.
      # Can be called multiple times, but this is probably not a good idea.
67 68
      def primary_key(name)
        column(name, :primary_key)
69
      end
70 71

      # Returns a ColumnDefinition for the column with name +name+.
72
      def [](name)
73
        @columns_hash[name.to_s]
74 75
      end

76
      # Instantiates a new column for the table.
77 78
      # The +type+ parameter is normally one of the migrations native types,
      # which is one of the following:
79
      # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
80 81 82
      # <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
      # <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
      # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>.
83
      #
84 85 86 87
      # You may use a type not in this list as long as it is supported by your
      # database (for example, "polygon" in MySQL), but this will not be database
      # agnostic and should usually be avoided.
      #
88
      # Available options are (none of these exists by default):
89
      # * <tt>:limit</tt> -
90
      #   Requests a maximum column length. This is number of characters for <tt>:string</tt> and
91
      #   <tt>:text</tt> columns and number of bytes for <tt>:binary</tt> and <tt>:integer</tt> columns.
92
      # * <tt>:default</tt> -
93
      #   The column's default value. Use nil for NULL.
94
      # * <tt>:null</tt> -
95
      #   Allows or disallows +NULL+ values in the column. This option could
96
      #   have been named <tt>:null_allowed</tt>.
97
      # * <tt>:precision</tt> -
98
      #   Specifies the precision for a <tt>:decimal</tt> column.
99
      # * <tt>:scale</tt> -
100
      #   Specifies the scale for a <tt>:decimal</tt> column.
101
      #
P
Pratik Naik 已提交
102 103 104 105 106 107
      # For clarity's sake: the precision is the number of significant digits,
      # while the scale is the number of digits that can be stored following
      # the decimal point. For example, the number 123.45 has a precision of 5
      # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
      # range from -999.99 to 999.99.
      #
108 109 110 111 112
      # Please be aware of different RDBMS implementations behavior with
      # <tt>:decimal</tt> columns:
      # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
      #   <tt>:precision</tt>, and makes no comments about the requirements of
      #   <tt>:precision</tt>.
113
      # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
114
      #   Default is (10,0).
115
      # * PostgreSQL: <tt>:precision</tt> [1..infinity],
116
      #   <tt>:scale</tt> [0..infinity]. No default.
117
      # * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
118
      #   Internal storage as strings. No default.
119
      # * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
120
      #   but the maximum supported <tt>:precision</tt> is 16. No default.
121
      # * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
122
      #   Default is (38,0).
123
      # * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
124
      #   Default unknown.
125
      # * Firebird: <tt>:precision</tt> [1..18], <tt>:scale</tt> [0..18].
126 127
      #   Default (9,0). Internal types NUMERIC and DECIMAL have different
      #   storage rules, decimal being better.
128
      # * FrontBase?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
129 130
      #   Default (38,0). WARNING Max <tt>:precision</tt>/<tt>:scale</tt> for
      #   NUMERIC is 19, and DECIMAL is 38.
131
      # * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
132
      #   Default (38,0).
133
      # * Sybase: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
134 135
      #   Default (38,0).
      # * OpenBase?: Documentation unclear. Claims storage in <tt>double</tt>.
136 137 138
      #
      # This method returns <tt>self</tt>.
      #
139
      # == Examples
140
      #  # Assuming +td+ is an instance of TableDefinition
141
      #  td.column(:granted, :boolean)
P
Pratik Naik 已提交
142
      #  # granted BOOLEAN
143
      #
A
AvnerCohen 已提交
144
      #  td.column(:picture, :binary, limit: 2.megabytes)
P
Pratik Naik 已提交
145
      #  # => picture BLOB(2097152)
146
      #
A
AvnerCohen 已提交
147
      #  td.column(:sales_stage, :string, limit: 20, default: 'new', null: false)
P
Pratik Naik 已提交
148
      #  # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL
149
      #
A
AvnerCohen 已提交
150
      #  td.column(:bill_gates_money, :decimal, precision: 15, scale: 2)
P
Pratik Naik 已提交
151
      #  # => bill_gates_money DECIMAL(15,2)
152
      #
A
AvnerCohen 已提交
153
      #  td.column(:sensor_reading, :decimal, precision: 30, scale: 20)
P
Pratik Naik 已提交
154
      #  # => sensor_reading DECIMAL(30,20)
155 156 157
      #
      #  # While <tt>:scale</tt> defaults to zero on most databases, it
      #  # probably wouldn't hurt to include it.
A
AvnerCohen 已提交
158
      #  td.column(:huge_integer, :decimal, precision: 30)
P
Pratik Naik 已提交
159
      #  # => huge_integer DECIMAL(30)
160
      #
P
Pratik Naik 已提交
161 162 163 164
      #  # Defines a column with a database-specific type.
      #  td.column(:foo, 'polygon')
      #  # => foo polygon
      #
165 166
      # == Short-hand examples
      #
P
Pratik Naik 已提交
167
      # Instead of calling +column+ directly, you can also work with the short-hand definitions for the default types.
168 169 170 171 172
      # They use the type as the method name instead of as a parameter and allow for multiple columns to be defined
      # in a single statement.
      #
      # What can be written like this with the regular calls to column:
      #
173 174 175 176 177 178 179
      #   create_table :products do |t|
      #     t.column :shop_id,    :integer
      #     t.column :creator_id, :integer
      #     t.column :name,       :string, default: "Untitled"
      #     t.column :value,      :string, default: "Untitled"
      #     t.column :created_at, :datetime
      #     t.column :updated_at, :datetime
180 181
      #   end
      #
182
      # can also be written as follows using the short-hand:
183 184 185
      #
      #   create_table :products do |t|
      #     t.integer :shop_id, :creator_id
A
AvnerCohen 已提交
186
      #     t.string  :name, :value, default: "Untitled"
187 188 189
      #     t.timestamps
      #   end
      #
190
      # There's a short-hand method for each of the type values declared at the top. And then there's
191
      # TableDefinition#timestamps that'll add +created_at+ and +updated_at+ as datetimes.
192 193
      #
      # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
194
      # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of
195 196
      # options, these will be used when creating the <tt>_type</tt> column. The <tt>:index</tt> option
      # will also create an index, similar to calling <tt>add_index</tt>. So what can be written like this:
197 198 199 200
      #
      #   create_table :taggings do |t|
      #     t.integer :tag_id, :tagger_id, :taggable_id
      #     t.string  :tagger_type
A
AvnerCohen 已提交
201
      #     t.string  :taggable_type, default: 'Photo'
202
      #   end
A
AvnerCohen 已提交
203
      #   add_index :taggings, :tag_id, name: 'index_taggings_on_tag_id'
204
      #   add_index :taggings, [:tagger_id, :tagger_type]
205 206 207 208
      #
      # Can also be written as follows using references:
      #
      #   create_table :taggings do |t|
A
AvnerCohen 已提交
209 210 211
      #     t.references :tag, index: { name: 'index_taggings_on_tag_id' }
      #     t.references :tagger, polymorphic: true, index: true
      #     t.references :taggable, polymorphic: { default: 'Photo' }
212
      #   end
213
      def column(name, type, options = {})
214 215 216
        name = name.to_s
        type = type.to_sym

217 218 219 220
        if primary_key_column_name == name
          raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
        end

221
        column = @columns_hash[name] ||= new_column_definition(name, type)
222 223 224

        limit = options.fetch(:limit) do
          native[type][:limit] if native[type].is_a?(Hash)
225
        end
226 227

        column.limit     = limit
228
        column.precision = options[:precision]
229 230 231
        column.scale     = options[:scale]
        column.default   = options[:default]
        column.null      = options[:null]
232 233
        self
      end
234

235 236 237 238
      def remove_column(name)
        @columns_hash.delete name.to_s
      end

239 240 241 242 243 244
      [:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
        define_method column_type do |*args|
          options = args.extract_options!
          column_names = args
          column_names.each { |name| column(name, column_type, options) }
        end
245
      end
246

247 248
      # Adds index options to the indexes hash, keyed by column name
      # This is primarily used to track indexes that need to be created after the table
249
      #
A
AvnerCohen 已提交
250
      #   index(:account_id, name: 'index_projects_on_account_id')
251 252 253
      def index(column_name, options = {})
        indexes[column_name] = options
      end
254 255

      # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
256
      # <tt>:updated_at</tt> to the table.
257
      def timestamps(*args)
258
        options = args.extract_options!
259 260
        column(:created_at, :datetime, options)
        column(:updated_at, :datetime, options)
261 262
      end

263 264 265
      def references(*args)
        options = args.extract_options!
        polymorphic = options.delete(:polymorphic)
266
        index_options = options.delete(:index)
267 268
        args.each do |col|
          column("#{col}_id", :integer, options)
269
          column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
270
          index(polymorphic ? %w(id type).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : nil) if index_options
271 272 273 274
        end
      end
      alias :belongs_to :references

275
      private
276 277
      def create_column_definition(name, type)
        ColumnDefinition.new name, type
278 279
      end

280
      def new_column_definition(name, type)
281
        create_column_definition name, type
282 283
      end

284
      def primary_key_column_name
A
Aaron Patterson 已提交
285
        primary_key_column = columns.detect { |c| c.primary_key? }
286 287 288
        primary_key_column && primary_key_column.name
      end

289
      def native
290
        @native
291
      end
292
    end
293

294
    # Represents an SQL table in an abstract way for updating a table.
295 296 297 298 299 300 301
    # Also see TableDefinition and SchemaStatements#create_table
    #
    # Available transformations are:
    #
    #   change_table :table do |t|
    #     t.column
    #     t.index
J
Jarek Radosz 已提交
302
    #     t.rename_index
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    #     t.timestamps
    #     t.change
    #     t.change_default
    #     t.rename
    #     t.references
    #     t.belongs_to
    #     t.string
    #     t.text
    #     t.integer
    #     t.float
    #     t.decimal
    #     t.datetime
    #     t.timestamp
    #     t.time
    #     t.date
    #     t.binary
    #     t.boolean
    #     t.remove
    #     t.remove_references
    #     t.remove_belongs_to
    #     t.remove_index
    #     t.remove_timestamps
    #   end
    #
    class Table
      def initialize(table_name, base)
        @table_name = table_name
        @base = base
      end

      # Adds a new column to the named table.
      # See TableDefinition#column for details of the options you can use.
335
      #
336
      # ====== Creating a simple column
337 338 339 340 341
      #  t.column(:name, :string)
      def column(column_name, type, options = {})
        @base.add_column(@table_name, column_name, type, options)
      end

342
      # Checks to see if a column exists. See SchemaStatements#column_exists?
343
      def column_exists?(column_name, type = nil, options = {})
344 345 346
        @base.column_exists?(@table_name, column_name, type, options)
      end

347 348
      # Adds a new index to the table. +column_name+ can be a single Symbol, or
      # an Array of Symbols. See SchemaStatements#add_index
349 350 351 352
      #
      # ====== Creating a simple index
      #  t.index(:name)
      # ====== Creating a unique index
A
AvnerCohen 已提交
353
      #  t.index([:branch_id, :party_id], unique: true)
354
      # ====== Creating a named index
A
AvnerCohen 已提交
355
      #  t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')
356 357 358 359
      def index(column_name, options = {})
        @base.add_index(@table_name, column_name, options)
      end

360 361 362 363 364
      # Checks to see if an index exists. See SchemaStatements#index_exists?
      def index_exists?(column_name, options = {})
        @base.index_exists?(@table_name, column_name, options)
      end

J
Jarek Radosz 已提交
365 366 367 368 369 370 371
      # Renames the given index on the table.
      #
      #  t.rename_index(:user_id, :account_id)
      def rename_index(index_name, new_index_name)
        @base.rename_index(@table_name, index_name, new_index_name)
      end

372
      # Adds timestamps (+created_at+ and +updated_at+) columns to the table. See SchemaStatements#add_timestamps
373
      #
374 375 376 377 378 379 380
      #  t.timestamps
      def timestamps
        @base.add_timestamps(@table_name)
      end

      # Changes the column's definition according to the new options.
      # See TableDefinition#column for details of the options you can use.
381
      #
A
AvnerCohen 已提交
382
      #  t.change(:name, :string, limit: 80)
383 384 385 386 387
      #  t.change(:description, :text)
      def change(column_name, type, options = {})
        @base.change_column(@table_name, column_name, type, options)
      end

388
      # Sets a new default value for a column. See SchemaStatements#change_column_default
389
      #
390 391 392 393 394 395 396
      #  t.change_default(:qualification, 'new')
      #  t.change_default(:authorized, 1)
      def change_default(column_name, default)
        @base.change_column_default(@table_name, column_name, default)
      end

      # Removes the column(s) from the table definition.
397
      #
398 399 400
      #  t.remove(:qualification)
      #  t.remove(:qualification, :experience)
      def remove(*column_names)
401
        @base.remove_columns(@table_name, *column_names)
402 403
      end

404
      # Removes the given index from the table.
405
      #
406 407 408
      # ====== Remove the index_table_name_on_column in the table_name table
      #   t.remove_index :column
      # ====== Remove the index named index_table_name_on_branch_id in the table_name table
A
AvnerCohen 已提交
409
      #   t.remove_index column: :branch_id
410
      # ====== Remove the index named index_table_name_on_branch_id_and_party_id in the table_name table
A
AvnerCohen 已提交
411
      #   t.remove_index column: [:branch_id, :party_id]
412
      # ====== Remove the index named by_branch_party in the table_name table
A
AvnerCohen 已提交
413
      #   t.remove_index name: :by_branch_party
414 415 416 417
      def remove_index(options = {})
        @base.remove_index(@table_name, options)
      end

418
      # Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
419
      #
420 421 422 423 424 425
      #  t.remove_timestamps
      def remove_timestamps
        @base.remove_timestamps(@table_name)
      end

      # Renames a column.
426
      #
427 428 429 430 431
      #  t.rename(:description, :name)
      def rename(column_name, new_column_name)
        @base.rename_column(@table_name, column_name, new_column_name)
      end

432
      # Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
433
      # <tt>references</tt> and <tt>belongs_to</tt> are acceptable.
434
      #
435 436 437
      #  t.references(:user)
      #  t.belongs_to(:supplier, polymorphic: true)
      #
438 439
      def references(*args)
        options = args.extract_options!
440 441
        args.each do |ref_name|
          @base.add_reference(@table_name, ref_name, options)
442 443 444 445
        end
      end
      alias :belongs_to :references

446 447
      # Removes a reference. Optionally removes a +type+ column.
      # <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
448
      #
449 450 451
      #  t.remove_references(:user)
      #  t.remove_belongs_to(:supplier, polymorphic: true)
      #
452 453
      def remove_references(*args)
        options = args.extract_options!
454 455
        args.each do |ref_name|
          @base.remove_reference(@table_name, ref_name, options)
456 457
        end
      end
458
      alias :remove_belongs_to :remove_references
459 460

      # Adds a column or columns of a specified type
461
      #
462 463
      #  t.string(:goat)
      #  t.string(:goat, :sheep)
464 465 466 467 468 469
      [:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
        define_method column_type do |*args|
          options = args.extract_options!
          args.each do |name|
            @base.add_column(@table_name, name, column_type, options)
          end
470
        end
471 472 473 474 475 476 477 478
      end

      private
        def native
          @base.native_database_types
        end
    end

479
  end
480
end