schema_definitions.rb 20.1 KB
Newer Older
1 2
module ActiveRecord
  module ConnectionAdapters #:nodoc:
3 4
    # Abstract representation of an index definition on a table. Instances of
    # this type are typically created and returned by methods in database
5
    # adapters. e.g. ActiveRecord::ConnectionAdapters::MySQL::SchemaStatements#indexes
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    class IndexDefinition # :nodoc:
      attr_reader :table, :name, :unique, :columns, :lengths, :orders, :where, :type, :using, :comment

      def initialize(
        table, name,
        unique = false,
        columns = [],
        lengths: {},
        orders: {},
        where: nil,
        type: nil,
        using: nil,
        comment: nil
      )
        @table = table
        @name = name
        @unique = unique
        @columns = columns
        @lengths = lengths
        @orders = orders
        @where = where
        @type = type
        @using = using
        @comment = comment
      end
    end
32

P
Pratik Naik 已提交
33 34 35 36
    # 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.
37
    ColumnDefinition = Struct.new(:name, :type, :options, :sql_type) do # :nodoc:
A
Aaron Patterson 已提交
38
      def primary_key?
39 40 41 42 43 44 45 46 47 48 49 50 51
        options[:primary_key]
      end

      [:limit, :precision, :scale, :default, :null, :collation, :comment].each do |option_name|
        module_eval <<-CODE, __FILE__, __LINE__ + 1
          def #{option_name}
            options[:#{option_name}]
          end

          def #{option_name}=(value)
            options[:#{option_name}] = value
          end
        CODE
A
Aaron Patterson 已提交
52
      end
53 54
    end

55
    AddColumnDefinition = Struct.new(:column) # :nodoc:
56

57
    ChangeColumnDefinition = Struct.new(:column, :name) #:nodoc:
58

59
    PrimaryKeyDefinition = Struct.new(:name) # :nodoc:
60

61
    ForeignKeyDefinition = Struct.new(:from_table, :to_table, :options) do #:nodoc:
62 63 64 65 66 67 68 69 70
      def name
        options[:name]
      end

      def column
        options[:column]
      end

      def primary_key
Y
Yves Senn 已提交
71
        options[:primary_key] || default_primary_key
72
      end
73

74 75
      def on_delete
        options[:on_delete]
76
      end
Y
Yves Senn 已提交
77 78 79 80

      def on_update
        options[:on_update]
      end
Y
Yves Senn 已提交
81 82 83 84 85

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

S
Sean Griffin 已提交
86 87 88
      def defined_for?(to_table_ord = nil, to_table: nil, **options)
        if to_table_ord
          self.to_table == to_table_ord.to_s
89
        else
S
Sean Griffin 已提交
90 91
          (to_table.nil? || to_table.to_s == self.to_table) &&
            options.all? { |k, v| self.options[k].to_s == v.to_s }
92 93 94
        end
      end

Y
Yves Senn 已提交
95
      private
96 97 98
        def default_primary_key
          "id"
        end
99 100
    end

101 102 103 104
    class ReferenceDefinition # :nodoc:
      def initialize(
        name,
        polymorphic: false,
105
        index: true,
106
        foreign_key: false,
107
        type: :bigint,
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        **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

A
Akira Matsuda 已提交
136 137
      # TODO Change this to private once we've dropped Ruby 2.2 support.
      # Workaround for Ruby 2.2 "private attribute?" warning.
138 139
      protected

140
        attr_reader :name, :polymorphic, :index, :foreign_key, :type, :options
141 142 143

      private

144 145
        def as_options(value)
          value.is_a?(Hash) ? value : {}
146 147
        end

148
        def polymorphic_options
149
          as_options(polymorphic).merge(null: options[:null])
150
        end
151

152 153 154
        def index_options
          as_options(index)
        end
155

156 157 158
        def foreign_key_options
          as_options(foreign_key).merge(column: column_name)
        end
159

160 161 162 163 164 165
        def columns
          result = [[column_name, type, options]]
          if polymorphic
            result.unshift(["#{name}_type", :string, polymorphic_options])
          end
          result
166 167
        end

168 169 170
        def column_name
          "#{name}_id"
        end
171

172 173 174
        def column_names
          columns.map(&:first)
        end
175

176 177 178 179
        def foreign_table_name
          foreign_key_options.fetch(:to_table) do
            Base.pluralize_table_names ? name.to_s.pluralize : name
          end
180
        end
181 182
    end

183 184 185 186 187 188
    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
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

      # 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,
209
        :virtual,
210 211 212 213 214 215 216
      ].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
217
      alias_method :numeric, :decimal
218 219
    end

P
Pratik Naik 已提交
220 221 222
    # Represents the schema of an SQL table in an abstract way. This class
    # provides methods for manipulating the schema representation.
    #
223
    # Inside migration files, the +t+ object in {create_table}[rdoc-ref:SchemaStatements#create_table]
224
    # is actually of this type:
P
Pratik Naik 已提交
225
    #
226
    #   class SomeMigration < ActiveRecord::Migration[5.0]
A
Akira Matsuda 已提交
227
    #     def up
P
Pratik Naik 已提交
228 229 230 231
    #       create_table :foo do |t|
    #         puts t.class  # => "ActiveRecord::ConnectionAdapters::TableDefinition"
    #       end
    #     end
P
Pratik Naik 已提交
232
    #
A
Akira Matsuda 已提交
233
    #     def down
P
Pratik Naik 已提交
234 235 236 237
    #       ...
    #     end
    #   end
    #
238
    class TableDefinition
239 240
      include ColumnMethods

241
      attr_accessor :indexes
242
      attr_reader :name, :temporary, :options, :as, :foreign_keys, :comment
243

244
      def initialize(name, temporary = false, options = nil, as = nil, comment: nil)
245
        @columns_hash = {}
246
        @indexes = []
247
        @foreign_keys = []
248
        @primary_keys = nil
249 250
        @temporary = temporary
        @options = options
251
        @as = as
252
        @name = name
253
        @comment = comment
254 255
      end

256 257 258 259 260
      def primary_keys(name = nil) # :nodoc:
        @primary_keys = PrimaryKeyDefinition.new(name) if name
        @primary_keys
      end

261
      # Returns an array of ColumnDefinition objects for the columns of the table.
262 263
      def columns; @columns_hash.values; end

264
      # Returns a ColumnDefinition for the column with name +name+.
265
      def [](name)
266
        @columns_hash[name.to_s]
267 268
      end

269
      # Instantiates a new column for the table.
270 271
      # See {connection.add_column}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_column]
      # for available options.
272
      #
273
      # Additional options are:
274 275
      # * <tt>:index</tt> -
      #   Create an index for the column. Can be either <tt>true</tt> or an options hash.
276
      #
277 278
      # This method returns <tt>self</tt>.
      #
279
      # == Examples
280
      #
281 282
      #  # Assuming +td+ is an instance of TableDefinition
      #  td.column(:granted, :boolean, index: true)
P
Pratik Naik 已提交
283
      #
284 285
      # == Short-hand examples
      #
286
      # Instead of calling #column directly, you can also work with the short-hand definitions for the default types.
287 288 289 290 291
      # 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:
      #
292
      #   create_table :products do |t|
293 294 295 296 297 298 299
      #     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
300
      #   end
301
      #   add_index :products, :item_number
302
      #
303
      # can also be written as follows using the short-hand:
304 305 306
      #
      #   create_table :products do |t|
      #     t.integer :shop_id, :creator_id
307
      #     t.string  :item_number, index: true
A
AvnerCohen 已提交
308
      #     t.string  :name, :value, default: "Untitled"
309
      #     t.timestamps null: false
310 311
      #   end
      #
312
      # There's a short-hand method for each of the type values declared at the top. And then there's
313
      # TableDefinition#timestamps that'll add +created_at+ and +updated_at+ as datetimes.
314 315
      #
      # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
316
      # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of
317
      # options, these will be used when creating the <tt>_type</tt> column. The <tt>:index</tt> option
318 319
      # will also create an index, similar to calling {add_index}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_index].
      # So what can be written like this:
320 321 322 323
      #
      #   create_table :taggings do |t|
      #     t.integer :tag_id, :tagger_id, :taggable_id
      #     t.string  :tagger_type
A
AvnerCohen 已提交
324
      #     t.string  :taggable_type, default: 'Photo'
325
      #   end
A
AvnerCohen 已提交
326
      #   add_index :taggings, :tag_id, name: 'index_taggings_on_tag_id'
327
      #   add_index :taggings, [:tagger_id, :tagger_type]
328 329 330 331
      #
      # Can also be written as follows using references:
      #
      #   create_table :taggings do |t|
A
AvnerCohen 已提交
332 333 334
      #     t.references :tag, index: { name: 'index_taggings_on_tag_id' }
      #     t.references :tagger, polymorphic: true, index: true
      #     t.references :taggable, polymorphic: { default: 'Photo' }
335
      #   end
336
      def column(name, type, options = {})
337
        name = name.to_s
338
        type = type.to_sym if type
339
        options = options.dup
340

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

345 346
        index_options = options.delete(:index)
        index(name, index_options.is_a?(Hash) ? index_options : {}) if index_options
347
        @columns_hash[name] = new_column_definition(name, type, options)
348 349
        self
      end
350

351 352
      # remove the column +name+ from the table.
      #   remove_column(:account_id)
353 354 355 356
      def remove_column(name)
        @columns_hash.delete name.to_s
      end

357 358
      # 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
359
      #
A
AvnerCohen 已提交
360
      #   index(:account_id, name: 'index_projects_on_account_id')
361
      def index(column_name, options = {})
362
        indexes << [column_name, options]
363
      end
364

365
      def foreign_key(table_name, options = {}) # :nodoc:
366 367 368
        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}"
369
        foreign_keys.push([table_name, options])
370 371
      end

372
      # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
373
      # <tt>:updated_at</tt> to the table. See {connection.add_timestamps}[rdoc-ref:SchemaStatements#add_timestamps]
374 375
      #
      #   t.timestamps null: false
376
      def timestamps(**options)
377 378
        options[:null] = false if options[:null].nil?

379 380
        column(:created_at, :datetime, options)
        column(:updated_at, :datetime, options)
381 382
      end

383
      # Adds a reference.
384 385
      #
      #  t.references(:user)
386
      #  t.belongs_to(:supplier, foreign_key: true)
387
      #
388
      # See {connection.add_reference}[rdoc-ref:SchemaStatements#add_reference] for details of the options you can use.
389
      def references(*args, **options)
390 391
        args.each do |ref_name|
          ReferenceDefinition.new(ref_name, options).add_to(self)
392 393 394 395
        end
      end
      alias :belongs_to :references

396
      def new_column_definition(name, type, **options) # :nodoc:
397
        type = aliased_types(type.to_s, type)
398 399 400
        options[:primary_key] ||= type == :primary_key
        options[:null] = false if options[:primary_key]
        create_column_definition(name, type, options)
401 402
      end

403
      private
404 405
        def create_column_definition(name, type, options)
          ColumnDefinition.new(name, type, options)
406
        end
407

408 409 410
        def aliased_types(name, fallback)
          "timestamp" == name ? :datetime : fallback
        end
411
    end
412

413
    class AlterTable # :nodoc:
A
Aaron Patterson 已提交
414
      attr_reader :adds
415 416
      attr_reader :foreign_key_adds
      attr_reader :foreign_key_drops
417 418

      def initialize(td)
A
Aaron Patterson 已提交
419 420
        @td   = td
        @adds = []
421 422
        @foreign_key_adds = []
        @foreign_key_drops = []
423 424 425 426
      end

      def name; @td.name; end

427 428 429 430 431 432 433 434
      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

435 436 437
      def add_column(name, type, options)
        name = name.to_s
        type = type.to_sym
438
        @adds << AddColumnDefinition.new(@td.new_column_definition(name, type, options))
439 440 441
      end
    end

442
    # Represents an SQL table in an abstract way for updating a table.
443
    # Also see TableDefinition and {connection.create_table}[rdoc-ref:SchemaStatements#create_table]
444 445 446 447
    #
    # Available transformations are:
    #
    #   change_table :table do |t|
448
    #     t.primary_key
449 450
    #     t.column
    #     t.index
J
Jarek Radosz 已提交
451
    #     t.rename_index
452 453 454 455 456 457 458 459 460
    #     t.timestamps
    #     t.change
    #     t.change_default
    #     t.rename
    #     t.references
    #     t.belongs_to
    #     t.string
    #     t.text
    #     t.integer
461
    #     t.bigint
462 463
    #     t.float
    #     t.decimal
464
    #     t.numeric
465 466 467 468 469 470 471 472 473 474 475 476 477 478
    #     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
479 480
      include ColumnMethods

481 482
      attr_reader :name

483
      def initialize(table_name, base)
484
        @name = table_name
485 486 487 488
        @base = base
      end

      # Adds a new column to the named table.
489
      #
490
      #  t.column(:name, :string)
491 492
      #
      # See TableDefinition#column for details of the options you can use.
493
      def column(column_name, type, options = {})
494
        @base.add_column(name, column_name, type, options)
495 496
      end

497 498
      # Checks to see if a column exists.
      #
O
Orhan Toy 已提交
499
      #  t.string(:name) unless t.column_exists?(:name, :string)
500
      #
501
      # See {connection.column_exists?}[rdoc-ref:SchemaStatements#column_exists?]
502
      def column_exists?(column_name, type = nil, options = {})
503
        @base.column_exists?(name, column_name, type, options)
504 505
      end

506
      # Adds a new index to the table. +column_name+ can be a single Symbol, or
507
      # an Array of Symbols.
508 509
      #
      #  t.index(:name)
A
AvnerCohen 已提交
510 511
      #  t.index([:branch_id, :party_id], unique: true)
      #  t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')
512
      #
513
      # See {connection.add_index}[rdoc-ref:SchemaStatements#add_index] for details of the options you can use.
514
      def index(column_name, options = {})
515
        @base.add_index(name, column_name, options)
516 517
      end

518 519
      # Checks to see if an index exists.
      #
O
Orhan Toy 已提交
520 521 522
      #  unless t.index_exists?(:branch_id)
      #    t.index(:branch_id)
      #  end
523
      #
524
      # See {connection.index_exists?}[rdoc-ref:SchemaStatements#index_exists?]
525
      def index_exists?(column_name, options = {})
526
        @base.index_exists?(name, column_name, options)
527 528
      end

J
Jarek Radosz 已提交
529 530 531
      # Renames the given index on the table.
      #
      #  t.rename_index(:user_id, :account_id)
532
      #
533
      # See {connection.rename_index}[rdoc-ref:SchemaStatements#rename_index]
J
Jarek Radosz 已提交
534
      def rename_index(index_name, new_index_name)
535
        @base.rename_index(name, index_name, new_index_name)
J
Jarek Radosz 已提交
536 537
      end

538 539 540
      # Adds timestamps (+created_at+ and +updated_at+) columns to the table.
      #
      #  t.timestamps(null: false)
541
      #
542
      # See {connection.add_timestamps}[rdoc-ref:SchemaStatements#add_timestamps]
543
      def timestamps(options = {})
544
        @base.add_timestamps(name, options)
545 546 547
      end

      # Changes the column's definition according to the new options.
548
      #
A
AvnerCohen 已提交
549
      #  t.change(:name, :string, limit: 80)
550
      #  t.change(:description, :text)
551 552
      #
      # See TableDefinition#column for details of the options you can use.
553
      def change(column_name, type, options = {})
554
        @base.change_column(name, column_name, type, options)
555 556
      end

557
      # Sets a new default value for a column.
558
      #
559 560
      #  t.change_default(:qualification, 'new')
      #  t.change_default(:authorized, 1)
561
      #  t.change_default(:status, from: nil, to: "draft")
562
      #
563
      # See {connection.change_column_default}[rdoc-ref:SchemaStatements#change_column_default]
564 565
      def change_default(column_name, default_or_changes)
        @base.change_column_default(name, column_name, default_or_changes)
566 567 568
      end

      # Removes the column(s) from the table definition.
569
      #
570 571
      #  t.remove(:qualification)
      #  t.remove(:qualification, :experience)
572
      #
573
      # See {connection.remove_columns}[rdoc-ref:SchemaStatements#remove_columns]
574
      def remove(*column_names)
575
        @base.remove_columns(name, *column_names)
576 577
      end

578
      # Removes the given index from the table.
579
      #
580 581 582 583
      #   t.remove_index(:branch_id)
      #   t.remove_index(column: [:branch_id, :party_id])
      #   t.remove_index(name: :by_branch_party)
      #
584
      # See {connection.remove_index}[rdoc-ref:SchemaStatements#remove_index]
585
      def remove_index(options = {})
586
        @base.remove_index(name, options)
587 588
      end

589
      # Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
590
      #
591
      #  t.remove_timestamps
592
      #
593
      # See {connection.remove_timestamps}[rdoc-ref:SchemaStatements#remove_timestamps]
594 595
      def remove_timestamps(options = {})
        @base.remove_timestamps(name, options)
596 597 598
      end

      # Renames a column.
599
      #
600
      #  t.rename(:description, :name)
601
      #
602
      # See {connection.rename_column}[rdoc-ref:SchemaStatements#rename_column]
603
      def rename(column_name, new_column_name)
604
        @base.rename_column(name, column_name, new_column_name)
605 606
      end

607
      # Adds a reference.
608
      #
609
      #  t.references(:user)
610
      #  t.belongs_to(:supplier, foreign_key: true)
611
      #
612
      # See {connection.add_reference}[rdoc-ref:SchemaStatements#add_reference] for details of the options you can use.
613
      def references(*args, **options)
614
        args.each do |ref_name|
615
          @base.add_reference(name, ref_name, options)
616 617 618 619
        end
      end
      alias :belongs_to :references

620
      # Removes a reference. Optionally removes a +type+ column.
621
      #
622 623 624
      #  t.remove_references(:user)
      #  t.remove_belongs_to(:supplier, polymorphic: true)
      #
625
      # See {connection.remove_reference}[rdoc-ref:SchemaStatements#remove_reference]
626
      def remove_references(*args, **options)
627
        args.each do |ref_name|
628
          @base.remove_reference(name, ref_name, options)
629 630
        end
      end
631
      alias :remove_belongs_to :remove_references
632

633 634 635 636
      # Adds a foreign key.
      #
      # t.foreign_key(:authors)
      #
637
      # See {connection.add_foreign_key}[rdoc-ref:SchemaStatements#add_foreign_key]
638 639 640 641
      def foreign_key(*args) # :nodoc:
        @base.add_foreign_key(name, *args)
      end

642 643 644 645
      # Checks to see if a foreign key exists.
      #
      # t.foreign_key(:authors) unless t.foreign_key_exists?(:authors)
      #
646
      # See {connection.foreign_key_exists?}[rdoc-ref:SchemaStatements#foreign_key_exists?]
A
Anton 已提交
647 648 649
      def foreign_key_exists?(*args) # :nodoc:
        @base.foreign_key_exists?(name, *args)
      end
650
    end
651
  end
652
end