schema_definitions.rb 19.8 KB
Newer Older
1 2
module ActiveRecord
  module ConnectionAdapters #:nodoc:
3 4 5
    # 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
6
    class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders, :where, :type, :using, :comment) #:nodoc:
7 8
    end

P
Pratik Naik 已提交
9 10 11 12
    # 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.
13
    class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null, :first, :after, :auto_increment, :primary_key, :collation, :sql_type, :comment) #:nodoc:
A
Aaron Patterson 已提交
14
      def primary_key?
15
        primary_key || type.to_sym == :primary_key
A
Aaron Patterson 已提交
16
      end
17 18
    end

19 20 21
    class AddColumnDefinition < Struct.new(:column) # :nodoc:
    end

22
    class ChangeColumnDefinition < Struct.new(:column, :name) #:nodoc:
23 24
    end

25 26 27
    class PrimaryKeyDefinition < Struct.new(:name) # :nodoc:
    end

28
    class ForeignKeyDefinition < Struct.new(:from_table, :to_table, :options) #:nodoc:
29 30 31 32 33 34 35 36 37
      def name
        options[:name]
      end

      def column
        options[:column]
      end

      def primary_key
Y
Yves Senn 已提交
38
        options[:primary_key] || default_primary_key
39
      end
40

41 42
      def on_delete
        options[:on_delete]
43
      end
Y
Yves Senn 已提交
44 45 46 47

      def on_update
        options[:on_update]
      end
Y
Yves Senn 已提交
48 49 50 51 52

      def custom_primary_key?
        options[:primary_key] != default_primary_key
      end

S
Sean Griffin 已提交
53 54 55
      def defined_for?(to_table_ord = nil, to_table: nil, **options)
        if to_table_ord
          self.to_table == to_table_ord.to_s
56
        else
S
Sean Griffin 已提交
57 58
          (to_table.nil? || to_table.to_s == self.to_table) &&
            options.all? { |k, v| self.options[k].to_s == v.to_s }
59 60 61
        end
      end

Y
Yves Senn 已提交
62
      private
63 64 65
        def default_primary_key
          "id"
        end
66 67
    end

68 69 70 71
    class ReferenceDefinition # :nodoc:
      def initialize(
        name,
        polymorphic: false,
72
        index: true,
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
        foreign_key: false,
        type: :integer,
        **options
      )
        @name = name
        @polymorphic = polymorphic
        @index = index
        @foreign_key = foreign_key
        @type = type
        @options = options

        if polymorphic && foreign_key
          raise ArgumentError, "Cannot add a foreign key to a polymorphic relation"
        end
      end

      def add_to(table)
        columns.each do |column_options|
          table.column(*column_options)
        end

        if index
          table.index(column_names, index_options)
        end

        if foreign_key
          table.foreign_key(foreign_table_name, foreign_key_options)
        end
      end

      protected

105
        attr_reader :name, :polymorphic, :index, :foreign_key, :type, :options
106 107 108

      private

109 110 111 112 113 114
        def as_options(value, default = {})
          if value.is_a?(Hash)
            value
          else
            default
          end
115 116
        end

117 118 119
        def polymorphic_options
          as_options(polymorphic, options)
        end
120

121 122 123
        def index_options
          as_options(index)
        end
124

125 126 127
        def foreign_key_options
          as_options(foreign_key).merge(column: column_name)
        end
128

129 130 131 132 133 134
        def columns
          result = [[column_name, type, options]]
          if polymorphic
            result.unshift(["#{name}_type", :string, polymorphic_options])
          end
          result
135 136
        end

137 138 139
        def column_name
          "#{name}_id"
        end
140

141 142 143
        def column_names
          columns.map(&:first)
        end
144

145 146 147 148
        def foreign_table_name
          foreign_key_options.fetch(:to_table) do
            Base.pluralize_table_names ? name.to_s.pluralize : name
          end
149
        end
150 151
    end

152 153 154 155 156 157
    module ColumnMethods
      # Appends a primary key definition to the table definition.
      # Can be called multiple times, but this is probably not a good idea.
      def primary_key(name, type = :primary_key, **options)
        column(name, type, options.merge(primary_key: true))
      end
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

      # Appends a column or columns of a specified type.
      #
      #  t.string(:goat)
      #  t.string(:goat, :sheep)
      #
      # See TableDefinition#column
      [
        :bigint,
        :binary,
        :boolean,
        :date,
        :datetime,
        :decimal,
        :float,
        :integer,
        :string,
        :text,
        :time,
        :timestamp,
      ].each do |column_type|
        module_eval <<-CODE, __FILE__, __LINE__ + 1
          def #{column_type}(*args, **options)
            args.each { |name| column(name, :#{column_type}, options) }
          end
        CODE
      end
185
      alias_method :numeric, :decimal
186 187
    end

P
Pratik Naik 已提交
188 189 190
    # Represents the schema of an SQL table in an abstract way. This class
    # provides methods for manipulating the schema representation.
    #
191
    # Inside migration files, the +t+ object in {create_table}[rdoc-ref:SchemaStatements#create_table]
192
    # is actually of this type:
P
Pratik Naik 已提交
193
    #
194
    #   class SomeMigration < ActiveRecord::Migration[5.0]
A
Akira Matsuda 已提交
195
    #     def up
P
Pratik Naik 已提交
196 197 198 199
    #       create_table :foo do |t|
    #         puts t.class  # => "ActiveRecord::ConnectionAdapters::TableDefinition"
    #       end
    #     end
P
Pratik Naik 已提交
200
    #
A
Akira Matsuda 已提交
201
    #     def down
P
Pratik Naik 已提交
202 203 204 205
    #       ...
    #     end
    #   end
    #
206
    class TableDefinition
207 208
      include ColumnMethods

209
      attr_accessor :indexes
210
      attr_reader :name, :temporary, :options, :as, :foreign_keys, :comment
211

212
      def initialize(name, temporary = false, options = nil, as = nil, comment: nil)
213
        @columns_hash = {}
214
        @indexes = {}
215
        @foreign_keys = []
216
        @primary_keys = nil
217 218
        @temporary = temporary
        @options = options
219
        @as = as
220
        @name = name
221
        @comment = comment
222 223
      end

224 225 226 227 228
      def primary_keys(name = nil) # :nodoc:
        @primary_keys = PrimaryKeyDefinition.new(name) if name
        @primary_keys
      end

229
      # Returns an array of ColumnDefinition objects for the columns of the table.
230 231
      def columns; @columns_hash.values; end

232
      # Returns a ColumnDefinition for the column with name +name+.
233
      def [](name)
234
        @columns_hash[name.to_s]
235 236
      end

237
      # Instantiates a new column for the table.
238 239
      # See {connection.add_column}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_column]
      # for available options.
240
      #
241
      # Additional options are:
242 243
      # * <tt>:index</tt> -
      #   Create an index for the column. Can be either <tt>true</tt> or an options hash.
244
      #
245 246
      # This method returns <tt>self</tt>.
      #
247
      # == Examples
248
      #
249 250
      #  # Assuming +td+ is an instance of TableDefinition
      #  td.column(:granted, :boolean, index: true)
P
Pratik Naik 已提交
251
      #
252 253
      # == Short-hand examples
      #
254
      # Instead of calling #column directly, you can also work with the short-hand definitions for the default types.
255 256 257 258 259
      # 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:
      #
260
      #   create_table :products do |t|
261 262 263 264 265 266 267
      #     t.column :shop_id,     :integer
      #     t.column :creator_id,  :integer
      #     t.column :item_number, :string
      #     t.column :name,        :string, default: "Untitled"
      #     t.column :value,       :string, default: "Untitled"
      #     t.column :created_at,  :datetime
      #     t.column :updated_at,  :datetime
268
      #   end
269
      #   add_index :products, :item_number
270
      #
271
      # can also be written as follows using the short-hand:
272 273 274
      #
      #   create_table :products do |t|
      #     t.integer :shop_id, :creator_id
275
      #     t.string  :item_number, index: true
A
AvnerCohen 已提交
276
      #     t.string  :name, :value, default: "Untitled"
277
      #     t.timestamps null: false
278 279
      #   end
      #
280
      # There's a short-hand method for each of the type values declared at the top. And then there's
281
      # TableDefinition#timestamps that'll add +created_at+ and +updated_at+ as datetimes.
282 283
      #
      # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
284
      # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of
285
      # options, these will be used when creating the <tt>_type</tt> column. The <tt>:index</tt> option
286 287
      # will also create an index, similar to calling {add_index}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_index].
      # So what can be written like this:
288 289 290 291
      #
      #   create_table :taggings do |t|
      #     t.integer :tag_id, :tagger_id, :taggable_id
      #     t.string  :tagger_type
A
AvnerCohen 已提交
292
      #     t.string  :taggable_type, default: 'Photo'
293
      #   end
A
AvnerCohen 已提交
294
      #   add_index :taggings, :tag_id, name: 'index_taggings_on_tag_id'
295
      #   add_index :taggings, [:tagger_id, :tagger_type]
296 297 298 299
      #
      # Can also be written as follows using references:
      #
      #   create_table :taggings do |t|
A
AvnerCohen 已提交
300 301 302
      #     t.references :tag, index: { name: 'index_taggings_on_tag_id' }
      #     t.references :tagger, polymorphic: true, index: true
      #     t.references :taggable, polymorphic: { default: 'Photo' }
303
      #   end
304
      def column(name, type, options = {})
305 306
        name = name.to_s
        type = type.to_sym
307
        options = options.dup
308

309
        if @columns_hash[name] && @columns_hash[name].primary_key?
310 311 312
          raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
        end

313 314
        index_options = options.delete(:index)
        index(name, index_options.is_a?(Hash) ? index_options : {}) if index_options
315
        @columns_hash[name] = new_column_definition(name, type, options)
316 317
        self
      end
318

319 320
      # remove the column +name+ from the table.
      #   remove_column(:account_id)
321 322 323 324
      def remove_column(name)
        @columns_hash.delete name.to_s
      end

325 326
      # 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
327
      #
A
AvnerCohen 已提交
328
      #   index(:account_id, name: 'index_projects_on_account_id')
329 330 331
      def index(column_name, options = {})
        indexes[column_name] = options
      end
332

333
      def foreign_key(table_name, options = {}) # :nodoc:
334 335 336
        table_name_prefix = ActiveRecord::Base.table_name_prefix
        table_name_suffix = ActiveRecord::Base.table_name_suffix
        table_name = "#{table_name_prefix}#{table_name}#{table_name_suffix}"
337
        foreign_keys.push([table_name, options])
338 339
      end

340
      # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
341
      # <tt>:updated_at</tt> to the table. See {connection.add_timestamps}[rdoc-ref:SchemaStatements#add_timestamps]
342 343
      #
      #   t.timestamps null: false
344
      def timestamps(*args)
345
        options = args.extract_options!
346 347 348

        options[:null] = false if options[:null].nil?

349 350
        column(:created_at, :datetime, options)
        column(:updated_at, :datetime, options)
351 352
      end

353
      # Adds a reference.
354 355
      #
      #  t.references(:user)
356
      #  t.belongs_to(:supplier, foreign_key: true)
357
      #
358
      # See {connection.add_reference}[rdoc-ref:SchemaStatements#add_reference] for details of the options you can use.
359
      def references(*args, **options)
360
        args.each do |col|
361
          ReferenceDefinition.new(col, **options).add_to(self)
362 363 364 365
        end
      end
      alias :belongs_to :references

366
      def new_column_definition(name, type, options) # :nodoc:
367
        type = aliased_types(type.to_s, type)
368 369
        column = create_column_definition name, type

370
        column.limit       = options[:limit]
371 372 373 374 375 376
        column.precision   = options[:precision]
        column.scale       = options[:scale]
        column.default     = options[:default]
        column.null        = options[:null]
        column.first       = options[:first]
        column.after       = options[:after]
377
        column.auto_increment = options[:auto_increment]
378
        column.primary_key = type == :primary_key || options[:primary_key]
379
        column.collation   = options[:collation]
380
        column.comment     = options[:comment]
381
        column
382 383
      end

384
      private
385 386 387
        def create_column_definition(name, type)
          ColumnDefinition.new name, type
        end
388

389 390 391
        def aliased_types(name, fallback)
          "timestamp" == name ? :datetime : fallback
        end
392
    end
393

394
    class AlterTable # :nodoc:
A
Aaron Patterson 已提交
395
      attr_reader :adds
396 397
      attr_reader :foreign_key_adds
      attr_reader :foreign_key_drops
398 399

      def initialize(td)
A
Aaron Patterson 已提交
400 401
        @td   = td
        @adds = []
402 403
        @foreign_key_adds = []
        @foreign_key_drops = []
404 405 406 407
      end

      def name; @td.name; end

408 409 410 411 412 413 414 415
      def add_foreign_key(to_table, options)
        @foreign_key_adds << ForeignKeyDefinition.new(name, to_table, options)
      end

      def drop_foreign_key(name)
        @foreign_key_drops << name
      end

416 417 418
      def add_column(name, type, options)
        name = name.to_s
        type = type.to_sym
419
        @adds << AddColumnDefinition.new(@td.new_column_definition(name, type, options))
420 421 422
      end
    end

423
    # Represents an SQL table in an abstract way for updating a table.
424
    # Also see TableDefinition and {connection.create_table}[rdoc-ref:SchemaStatements#create_table]
425 426 427 428
    #
    # Available transformations are:
    #
    #   change_table :table do |t|
429
    #     t.primary_key
430 431
    #     t.column
    #     t.index
J
Jarek Radosz 已提交
432
    #     t.rename_index
433 434 435 436 437 438 439 440 441
    #     t.timestamps
    #     t.change
    #     t.change_default
    #     t.rename
    #     t.references
    #     t.belongs_to
    #     t.string
    #     t.text
    #     t.integer
442
    #     t.bigint
443 444
    #     t.float
    #     t.decimal
445
    #     t.numeric
446 447 448 449 450 451 452 453 454 455 456 457 458 459
    #     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
460 461
      include ColumnMethods

462 463
      attr_reader :name

464
      def initialize(table_name, base)
465
        @name = table_name
466 467 468 469
        @base = base
      end

      # Adds a new column to the named table.
470
      #
471
      #  t.column(:name, :string)
472 473
      #
      # See TableDefinition#column for details of the options you can use.
474
      def column(column_name, type, options = {})
475
        @base.add_column(name, column_name, type, options)
476 477
      end

478 479
      # Checks to see if a column exists.
      #
480 481
      # t.string(:name) unless t.column_exists?(:name, :string)
      #
482
      # See {connection.column_exists?}[rdoc-ref:SchemaStatements#column_exists?]
483
      def column_exists?(column_name, type = nil, options = {})
484
        @base.column_exists?(name, column_name, type, options)
485 486
      end

487
      # Adds a new index to the table. +column_name+ can be a single Symbol, or
488
      # an Array of Symbols.
489 490
      #
      #  t.index(:name)
A
AvnerCohen 已提交
491 492
      #  t.index([:branch_id, :party_id], unique: true)
      #  t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')
493
      #
494
      # See {connection.add_index}[rdoc-ref:SchemaStatements#add_index] for details of the options you can use.
495
      def index(column_name, options = {})
496
        @base.add_index(name, column_name, options)
497 498
      end

499 500
      # Checks to see if an index exists.
      #
501 502 503 504
      # unless t.index_exists?(:branch_id)
      #   t.index(:branch_id)
      # end
      #
505
      # See {connection.index_exists?}[rdoc-ref:SchemaStatements#index_exists?]
506
      def index_exists?(column_name, options = {})
507
        @base.index_exists?(name, column_name, options)
508 509
      end

J
Jarek Radosz 已提交
510 511 512
      # Renames the given index on the table.
      #
      #  t.rename_index(:user_id, :account_id)
513
      #
514
      # See {connection.rename_index}[rdoc-ref:SchemaStatements#rename_index]
J
Jarek Radosz 已提交
515
      def rename_index(index_name, new_index_name)
516
        @base.rename_index(name, index_name, new_index_name)
J
Jarek Radosz 已提交
517 518
      end

519 520 521
      # Adds timestamps (+created_at+ and +updated_at+) columns to the table.
      #
      #  t.timestamps(null: false)
522
      #
523
      # See {connection.add_timestamps}[rdoc-ref:SchemaStatements#add_timestamps]
524
      def timestamps(options = {})
525
        @base.add_timestamps(name, options)
526 527 528
      end

      # Changes the column's definition according to the new options.
529
      #
A
AvnerCohen 已提交
530
      #  t.change(:name, :string, limit: 80)
531
      #  t.change(:description, :text)
532 533
      #
      # See TableDefinition#column for details of the options you can use.
534
      def change(column_name, type, options = {})
535
        @base.change_column(name, column_name, type, options)
536 537
      end

538
      # Sets a new default value for a column.
539
      #
540 541
      #  t.change_default(:qualification, 'new')
      #  t.change_default(:authorized, 1)
542
      #  t.change_default(:status, from: nil, to: "draft")
543
      #
544
      # See {connection.change_column_default}[rdoc-ref:SchemaStatements#change_column_default]
545 546
      def change_default(column_name, default_or_changes)
        @base.change_column_default(name, column_name, default_or_changes)
547 548 549
      end

      # Removes the column(s) from the table definition.
550
      #
551 552
      #  t.remove(:qualification)
      #  t.remove(:qualification, :experience)
553
      #
554
      # See {connection.remove_columns}[rdoc-ref:SchemaStatements#remove_columns]
555
      def remove(*column_names)
556
        @base.remove_columns(name, *column_names)
557 558
      end

559
      # Removes the given index from the table.
560
      #
561 562 563 564
      #   t.remove_index(:branch_id)
      #   t.remove_index(column: [:branch_id, :party_id])
      #   t.remove_index(name: :by_branch_party)
      #
565
      # See {connection.remove_index}[rdoc-ref:SchemaStatements#remove_index]
566
      def remove_index(options = {})
567
        @base.remove_index(name, options)
568 569
      end

570
      # Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
571
      #
572
      #  t.remove_timestamps
573
      #
574
      # See {connection.remove_timestamps}[rdoc-ref:SchemaStatements#remove_timestamps]
575 576
      def remove_timestamps(options = {})
        @base.remove_timestamps(name, options)
577 578 579
      end

      # Renames a column.
580
      #
581
      #  t.rename(:description, :name)
582
      #
583
      # See {connection.rename_column}[rdoc-ref:SchemaStatements#rename_column]
584
      def rename(column_name, new_column_name)
585
        @base.rename_column(name, column_name, new_column_name)
586 587
      end

588
      # Adds a reference.
589
      #
590
      #  t.references(:user)
591
      #  t.belongs_to(:supplier, foreign_key: true)
592
      #
593
      # See {connection.add_reference}[rdoc-ref:SchemaStatements#add_reference] for details of the options you can use.
594 595
      def references(*args)
        options = args.extract_options!
596
        args.each do |ref_name|
597
          @base.add_reference(name, ref_name, options)
598 599 600 601
        end
      end
      alias :belongs_to :references

602
      # Removes a reference. Optionally removes a +type+ column.
603
      #
604 605 606
      #  t.remove_references(:user)
      #  t.remove_belongs_to(:supplier, polymorphic: true)
      #
607
      # See {connection.remove_reference}[rdoc-ref:SchemaStatements#remove_reference]
608 609
      def remove_references(*args)
        options = args.extract_options!
610
        args.each do |ref_name|
611
          @base.remove_reference(name, ref_name, options)
612 613
        end
      end
614
      alias :remove_belongs_to :remove_references
615

616 617 618 619
      # Adds a foreign key.
      #
      # t.foreign_key(:authors)
      #
620
      # See {connection.add_foreign_key}[rdoc-ref:SchemaStatements#add_foreign_key]
621 622 623 624
      def foreign_key(*args) # :nodoc:
        @base.add_foreign_key(name, *args)
      end

625 626 627 628
      # Checks to see if a foreign key exists.
      #
      # t.foreign_key(:authors) unless t.foreign_key_exists?(:authors)
      #
629
      # See {connection.foreign_key_exists?}[rdoc-ref:SchemaStatements#foreign_key_exists?]
A
Anton 已提交
630 631 632
      def foreign_key_exists?(*args) # :nodoc:
        @base.foreign_key_exists?(name, *args)
      end
633
    end
634
  end
635
end