schema_definitions.rb 20.9 KB
Newer Older
1 2
# frozen_string_literal: true

3 4
module ActiveRecord
  module ConnectionAdapters #:nodoc:
5 6
    # Abstract representation of an index definition on a table. Instances of
    # this type are typically created and returned by methods in database
7
    # adapters. e.g. ActiveRecord::ConnectionAdapters::MySQL::SchemaStatements#indexes
8
    class IndexDefinition # :nodoc:
9
      attr_reader :table, :name, :unique, :columns, :lengths, :orders, :opclasses, :where, :type, :using, :comment
10 11 12 13 14 15 16

      def initialize(
        table, name,
        unique = false,
        columns = [],
        lengths: {},
        orders: {},
17
        opclasses: {},
18 19 20 21 22 23 24 25 26
        where: nil,
        type: nil,
        using: nil,
        comment: nil
      )
        @table = table
        @name = name
        @unique = unique
        @columns = columns
27 28 29
        @lengths = concise_options(lengths)
        @orders = concise_options(orders)
        @opclasses = concise_options(opclasses)
30 31 32 33 34
        @where = where
        @type = type
        @using = using
        @comment = comment
      end
35 36 37 38 39 40 41 42 43

      private
        def concise_options(options)
          if columns.size == options.size && options.values.uniq.size == 1
            options.values.first
          else
            options
          end
        end
44
    end
45

P
Pratik Naik 已提交
46 47 48 49
    # 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.
50
    ColumnDefinition = Struct.new(:name, :type, :options, :sql_type) do # :nodoc:
A
Aaron Patterson 已提交
51
      def primary_key?
52 53 54 55 56 57 58 59 60 61 62 63 64
        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 已提交
65
      end
66 67
    end

68
    AddColumnDefinition = Struct.new(:column) # :nodoc:
69

70
    ChangeColumnDefinition = Struct.new(:column, :name) #:nodoc:
71

72
    PrimaryKeyDefinition = Struct.new(:name) # :nodoc:
73

74
    ForeignKeyDefinition = Struct.new(:from_table, :to_table, :options) do #:nodoc:
75 76 77 78 79 80 81 82 83
      def name
        options[:name]
      end

      def column
        options[:column]
      end

      def primary_key
Y
Yves Senn 已提交
84
        options[:primary_key] || default_primary_key
85
      end
86

87 88
      def on_delete
        options[:on_delete]
89
      end
Y
Yves Senn 已提交
90 91 92 93

      def on_update
        options[:on_update]
      end
Y
Yves Senn 已提交
94 95 96 97 98

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

99 100 101 102 103
      def validate?
        options.fetch(:validate, true)
      end
      alias validated? validate?

104
      def export_name_on_schema_dump?
105
        name !~ ActiveRecord::SchemaDumper.fk_ignore_pattern
106 107
      end

S
Sean Griffin 已提交
108 109 110
      def defined_for?(to_table_ord = nil, to_table: nil, **options)
        if to_table_ord
          self.to_table == to_table_ord.to_s
111
        else
S
Sean Griffin 已提交
112 113
          (to_table.nil? || to_table.to_s == self.to_table) &&
            options.all? { |k, v| self.options[k].to_s == v.to_s }
114 115 116
        end
      end

Y
Yves Senn 已提交
117
      private
118 119 120
        def default_primary_key
          "id"
        end
121 122
    end

123 124 125 126
    class ReferenceDefinition # :nodoc:
      def initialize(
        name,
        polymorphic: false,
127
        index: true,
128
        foreign_key: false,
129
        type: :bigint,
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        **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

      private
J
Jeremy Daer 已提交
159
        attr_reader :name, :polymorphic, :index, :foreign_key, :type, :options
160

161 162
        def as_options(value)
          value.is_a?(Hash) ? value : {}
163 164
        end

165
        def polymorphic_options
166
          as_options(polymorphic).merge(options.slice(:null, :first, :after))
167
        end
168

169 170 171
        def index_options
          as_options(index)
        end
172

173 174 175
        def foreign_key_options
          as_options(foreign_key).merge(column: column_name)
        end
176

177 178 179 180 181 182
        def columns
          result = [[column_name, type, options]]
          if polymorphic
            result.unshift(["#{name}_type", :string, polymorphic_options])
          end
          result
183 184
        end

185 186 187
        def column_name
          "#{name}_id"
        end
188

189 190 191
        def column_names
          columns.map(&:first)
        end
192

193 194 195 196
        def foreign_table_name
          foreign_key_options.fetch(:to_table) do
            Base.pluralize_table_names ? name.to_s.pluralize : name
          end
197
        end
198 199
    end

200 201 202 203 204 205
    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
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

      # 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,
222
        :json,
223 224 225 226
        :string,
        :text,
        :time,
        :timestamp,
227
        :virtual,
228 229 230 231 232 233 234
      ].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
235
      alias_method :numeric, :decimal
236 237
    end

P
Pratik Naik 已提交
238 239 240
    # Represents the schema of an SQL table in an abstract way. This class
    # provides methods for manipulating the schema representation.
    #
241
    # Inside migration files, the +t+ object in {create_table}[rdoc-ref:SchemaStatements#create_table]
242
    # is actually of this type:
P
Pratik Naik 已提交
243
    #
244
    #   class SomeMigration < ActiveRecord::Migration[5.0]
A
Akira Matsuda 已提交
245
    #     def up
P
Pratik Naik 已提交
246 247 248 249
    #       create_table :foo do |t|
    #         puts t.class  # => "ActiveRecord::ConnectionAdapters::TableDefinition"
    #       end
    #     end
P
Pratik Naik 已提交
250
    #
A
Akira Matsuda 已提交
251
    #     def down
P
Pratik Naik 已提交
252 253 254 255
    #       ...
    #     end
    #   end
    #
256
    class TableDefinition
257 258
      include ColumnMethods

259
      attr_accessor :indexes
260
      attr_reader :name, :temporary, :options, :as, :foreign_keys, :comment
261

262
      def initialize(name, temporary = false, options = nil, as = nil, comment: nil)
263
        @columns_hash = {}
264
        @indexes = []
265
        @foreign_keys = []
266
        @primary_keys = nil
267 268
        @temporary = temporary
        @options = options
269
        @as = as
270
        @name = name
271
        @comment = comment
272 273
      end

274 275 276 277 278
      def primary_keys(name = nil) # :nodoc:
        @primary_keys = PrimaryKeyDefinition.new(name) if name
        @primary_keys
      end

279
      # Returns an array of ColumnDefinition objects for the columns of the table.
280 281
      def columns; @columns_hash.values; end

282
      # Returns a ColumnDefinition for the column with name +name+.
283
      def [](name)
284
        @columns_hash[name.to_s]
285 286
      end

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

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

363 364
        index_options = options.delete(:index)
        index(name, index_options.is_a?(Hash) ? index_options : {}) if index_options
365
        @columns_hash[name] = new_column_definition(name, type, options)
366 367
        self
      end
368

369 370
      # remove the column +name+ from the table.
      #   remove_column(:account_id)
371 372 373 374
      def remove_column(name)
        @columns_hash.delete name.to_s
      end

375 376
      # 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
377
      #
A
AvnerCohen 已提交
378
      #   index(:account_id, name: 'index_projects_on_account_id')
379
      def index(column_name, options = {})
380
        indexes << [column_name, options]
381
      end
382

383
      def foreign_key(table_name, options = {}) # :nodoc:
384 385 386
        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}"
387
        foreign_keys.push([table_name, options])
388 389
      end

390
      # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
391
      # <tt>:updated_at</tt> to the table. See {connection.add_timestamps}[rdoc-ref:SchemaStatements#add_timestamps]
392 393
      #
      #   t.timestamps null: false
394
      def timestamps(**options)
395 396
        options[:null] = false if options[:null].nil?

397 398
        column(:created_at, :datetime, options)
        column(:updated_at, :datetime, options)
399 400
      end

401
      # Adds a reference.
402 403
      #
      #  t.references(:user)
404
      #  t.belongs_to(:supplier, foreign_key: true)
405
      #
406
      # See {connection.add_reference}[rdoc-ref:SchemaStatements#add_reference] for details of the options you can use.
407
      def references(*args, **options)
408 409
        args.each do |ref_name|
          ReferenceDefinition.new(ref_name, options).add_to(self)
410 411 412 413
        end
      end
      alias :belongs_to :references

414
      def new_column_definition(name, type, **options) # :nodoc:
415 416 417
        if integer_like_primary_key?(type, options)
          type = integer_like_primary_key_type(type, options)
        end
418
        type = aliased_types(type.to_s, type)
419 420 421
        options[:primary_key] ||= type == :primary_key
        options[:null] = false if options[:primary_key]
        create_column_definition(name, type, options)
422 423
      end

424
      private
425 426
        def create_column_definition(name, type, options)
          ColumnDefinition.new(name, type, options)
427
        end
428

429 430 431
        def aliased_types(name, fallback)
          "timestamp" == name ? :datetime : fallback
        end
432 433 434 435

        def integer_like_primary_key?(type, options)
          options[:primary_key] && [:integer, :bigint].include?(type) && !options.key?(:default)
        end
436 437 438 439

        def integer_like_primary_key_type(type, options)
          type
        end
440
    end
441

442
    class AlterTable # :nodoc:
A
Aaron Patterson 已提交
443
      attr_reader :adds
444 445
      attr_reader :foreign_key_adds
      attr_reader :foreign_key_drops
446 447

      def initialize(td)
A
Aaron Patterson 已提交
448 449
        @td   = td
        @adds = []
450 451
        @foreign_key_adds = []
        @foreign_key_drops = []
452 453 454 455
      end

      def name; @td.name; end

456 457 458 459 460 461 462 463
      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

464 465 466
      def add_column(name, type, options)
        name = name.to_s
        type = type.to_sym
467
        @adds << AddColumnDefinition.new(@td.new_column_definition(name, type, options))
468 469 470
      end
    end

471
    # Represents an SQL table in an abstract way for updating a table.
472
    # Also see TableDefinition and {connection.create_table}[rdoc-ref:SchemaStatements#create_table]
473 474 475 476
    #
    # Available transformations are:
    #
    #   change_table :table do |t|
477
    #     t.primary_key
478 479
    #     t.column
    #     t.index
J
Jarek Radosz 已提交
480
    #     t.rename_index
481 482 483 484 485 486 487 488 489
    #     t.timestamps
    #     t.change
    #     t.change_default
    #     t.rename
    #     t.references
    #     t.belongs_to
    #     t.string
    #     t.text
    #     t.integer
490
    #     t.bigint
491 492
    #     t.float
    #     t.decimal
493
    #     t.numeric
494 495 496 497 498 499
    #     t.datetime
    #     t.timestamp
    #     t.time
    #     t.date
    #     t.binary
    #     t.boolean
500 501 502
    #     t.foreign_key
    #     t.json
    #     t.virtual
503 504 505 506 507 508 509 510
    #     t.remove
    #     t.remove_references
    #     t.remove_belongs_to
    #     t.remove_index
    #     t.remove_timestamps
    #   end
    #
    class Table
511 512
      include ColumnMethods

513 514
      attr_reader :name

515
      def initialize(table_name, base)
516
        @name = table_name
517 518 519 520
        @base = base
      end

      # Adds a new column to the named table.
521
      #
522
      #  t.column(:name, :string)
523 524
      #
      # See TableDefinition#column for details of the options you can use.
525
      def column(column_name, type, options = {})
526
        @base.add_column(name, column_name, type, options)
527 528
      end

529 530
      # Checks to see if a column exists.
      #
O
Orhan Toy 已提交
531
      #  t.string(:name) unless t.column_exists?(:name, :string)
532
      #
533
      # See {connection.column_exists?}[rdoc-ref:SchemaStatements#column_exists?]
534
      def column_exists?(column_name, type = nil, options = {})
535
        @base.column_exists?(name, column_name, type, options)
536 537
      end

538
      # Adds a new index to the table. +column_name+ can be a single Symbol, or
539
      # an Array of Symbols.
540 541
      #
      #  t.index(:name)
A
AvnerCohen 已提交
542 543
      #  t.index([:branch_id, :party_id], unique: true)
      #  t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')
544
      #
545
      # See {connection.add_index}[rdoc-ref:SchemaStatements#add_index] for details of the options you can use.
546
      def index(column_name, options = {})
547
        @base.add_index(name, column_name, options)
548 549
      end

550 551
      # Checks to see if an index exists.
      #
O
Orhan Toy 已提交
552 553 554
      #  unless t.index_exists?(:branch_id)
      #    t.index(:branch_id)
      #  end
555
      #
556
      # See {connection.index_exists?}[rdoc-ref:SchemaStatements#index_exists?]
557
      def index_exists?(column_name, options = {})
558
        @base.index_exists?(name, column_name, options)
559 560
      end

J
Jarek Radosz 已提交
561 562 563
      # Renames the given index on the table.
      #
      #  t.rename_index(:user_id, :account_id)
564
      #
565
      # See {connection.rename_index}[rdoc-ref:SchemaStatements#rename_index]
J
Jarek Radosz 已提交
566
      def rename_index(index_name, new_index_name)
567
        @base.rename_index(name, index_name, new_index_name)
J
Jarek Radosz 已提交
568 569
      end

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

      # Changes the column's definition according to the new options.
580
      #
A
AvnerCohen 已提交
581
      #  t.change(:name, :string, limit: 80)
582
      #  t.change(:description, :text)
583 584
      #
      # See TableDefinition#column for details of the options you can use.
585
      def change(column_name, type, options = {})
586
        @base.change_column(name, column_name, type, options)
587 588
      end

589
      # Sets a new default value for a column.
590
      #
591 592
      #  t.change_default(:qualification, 'new')
      #  t.change_default(:authorized, 1)
593
      #  t.change_default(:status, from: nil, to: "draft")
594
      #
595
      # See {connection.change_column_default}[rdoc-ref:SchemaStatements#change_column_default]
596 597
      def change_default(column_name, default_or_changes)
        @base.change_column_default(name, column_name, default_or_changes)
598 599 600
      end

      # Removes the column(s) from the table definition.
601
      #
602 603
      #  t.remove(:qualification)
      #  t.remove(:qualification, :experience)
604
      #
605
      # See {connection.remove_columns}[rdoc-ref:SchemaStatements#remove_columns]
606
      def remove(*column_names)
607
        @base.remove_columns(name, *column_names)
608 609
      end

610
      # Removes the given index from the table.
611
      #
612 613 614 615
      #   t.remove_index(:branch_id)
      #   t.remove_index(column: [:branch_id, :party_id])
      #   t.remove_index(name: :by_branch_party)
      #
616
      # See {connection.remove_index}[rdoc-ref:SchemaStatements#remove_index]
617
      def remove_index(options = {})
618
        @base.remove_index(name, options)
619 620
      end

621
      # Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
622
      #
623
      #  t.remove_timestamps
624
      #
625
      # See {connection.remove_timestamps}[rdoc-ref:SchemaStatements#remove_timestamps]
626 627
      def remove_timestamps(options = {})
        @base.remove_timestamps(name, options)
628 629 630
      end

      # Renames a column.
631
      #
632
      #  t.rename(:description, :name)
633
      #
634
      # See {connection.rename_column}[rdoc-ref:SchemaStatements#rename_column]
635
      def rename(column_name, new_column_name)
636
        @base.rename_column(name, column_name, new_column_name)
637 638
      end

639
      # Adds a reference.
640
      #
641
      #  t.references(:user)
642
      #  t.belongs_to(:supplier, foreign_key: true)
643
      #
644
      # See {connection.add_reference}[rdoc-ref:SchemaStatements#add_reference] for details of the options you can use.
645
      def references(*args, **options)
646
        args.each do |ref_name|
647
          @base.add_reference(name, ref_name, options)
648 649 650 651
        end
      end
      alias :belongs_to :references

652
      # Removes a reference. Optionally removes a +type+ column.
653
      #
654 655 656
      #  t.remove_references(:user)
      #  t.remove_belongs_to(:supplier, polymorphic: true)
      #
657
      # See {connection.remove_reference}[rdoc-ref:SchemaStatements#remove_reference]
658
      def remove_references(*args, **options)
659
        args.each do |ref_name|
660
          @base.remove_reference(name, ref_name, options)
661 662
        end
      end
663
      alias :remove_belongs_to :remove_references
664

665 666 667 668
      # Adds a foreign key.
      #
      # t.foreign_key(:authors)
      #
669
      # See {connection.add_foreign_key}[rdoc-ref:SchemaStatements#add_foreign_key]
670 671 672 673
      def foreign_key(*args) # :nodoc:
        @base.add_foreign_key(name, *args)
      end

674 675 676 677
      # Checks to see if a foreign key exists.
      #
      # t.foreign_key(:authors) unless t.foreign_key_exists?(:authors)
      #
678
      # See {connection.foreign_key_exists?}[rdoc-ref:SchemaStatements#foreign_key_exists?]
A
Anton 已提交
679 680 681
      def foreign_key_exists?(*args) # :nodoc:
        @base.foreign_key_exists?(name, *args)
      end
682
    end
683
  end
684
end