schema_definitions.rb 21.2 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
      #     t.references :tag, index: { name: 'index_taggings_on_tag_id' }
351 352
      #     t.references :tagger, polymorphic: true
      #     t.references :taggable, polymorphic: { default: 'Photo' }, index: false
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 360 361 362 363 364
        if @columns_hash[name]
          if @columns_hash[name].primary_key?
            raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
          else
            raise ArgumentError, "you can't define an already defined column '#{name}'."
          end
365 366
        end

367 368
        index_options = options.delete(:index)
        index(name, index_options.is_a?(Hash) ? index_options : {}) if index_options
369
        @columns_hash[name] = new_column_definition(name, type, options)
370 371
        self
      end
372

373 374
      # remove the column +name+ from the table.
      #   remove_column(:account_id)
375 376 377 378
      def remove_column(name)
        @columns_hash.delete name.to_s
      end

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

387
      def foreign_key(table_name, options = {}) # :nodoc:
388 389 390
        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}"
391
        foreign_keys.push([table_name, options])
392 393
      end

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

401 402
        column(:created_at, :datetime, options)
        column(:updated_at, :datetime, options)
403 404
      end

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

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

428
      private
429 430
        def create_column_definition(name, type, options)
          ColumnDefinition.new(name, type, options)
431
        end
432

433 434 435
        def aliased_types(name, fallback)
          "timestamp" == name ? :datetime : fallback
        end
436 437 438 439

        def integer_like_primary_key?(type, options)
          options[:primary_key] && [:integer, :bigint].include?(type) && !options.key?(:default)
        end
440 441 442 443

        def integer_like_primary_key_type(type, options)
          type
        end
444
    end
445

446
    class AlterTable # :nodoc:
A
Aaron Patterson 已提交
447
      attr_reader :adds
448 449
      attr_reader :foreign_key_adds
      attr_reader :foreign_key_drops
450 451

      def initialize(td)
A
Aaron Patterson 已提交
452 453
        @td   = td
        @adds = []
454 455
        @foreign_key_adds = []
        @foreign_key_drops = []
456 457 458 459
      end

      def name; @td.name; end

460 461 462 463 464 465 466 467
      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

468 469 470
      def add_column(name, type, options)
        name = name.to_s
        type = type.to_sym
471
        @adds << AddColumnDefinition.new(@td.new_column_definition(name, type, options))
472 473 474
      end
    end

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

517 518
      attr_reader :name

519
      def initialize(table_name, base)
520
        @name = table_name
521 522 523 524
        @base = base
      end

      # Adds a new column to the named table.
525
      #
526
      #  t.column(:name, :string)
527 528
      #
      # See TableDefinition#column for details of the options you can use.
529
      def column(column_name, type, options = {})
530
        index_options = options.delete(:index)
531
        @base.add_column(name, column_name, type, options)
532
        index(column_name, index_options.is_a?(Hash) ? index_options : {}) if index_options
533 534
      end

535 536
      # Checks to see if a column exists.
      #
O
Orhan Toy 已提交
537
      #  t.string(:name) unless t.column_exists?(:name, :string)
538
      #
539
      # See {connection.column_exists?}[rdoc-ref:SchemaStatements#column_exists?]
540
      def column_exists?(column_name, type = nil, options = {})
541
        @base.column_exists?(name, column_name, type, options)
542 543
      end

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

556 557
      # Checks to see if an index exists.
      #
O
Orhan Toy 已提交
558 559 560
      #  unless t.index_exists?(:branch_id)
      #    t.index(:branch_id)
      #  end
561
      #
562
      # See {connection.index_exists?}[rdoc-ref:SchemaStatements#index_exists?]
563
      def index_exists?(column_name, options = {})
564
        @base.index_exists?(name, column_name, options)
565 566
      end

J
Jarek Radosz 已提交
567 568 569
      # Renames the given index on the table.
      #
      #  t.rename_index(:user_id, :account_id)
570
      #
571
      # See {connection.rename_index}[rdoc-ref:SchemaStatements#rename_index]
J
Jarek Radosz 已提交
572
      def rename_index(index_name, new_index_name)
573
        @base.rename_index(name, index_name, new_index_name)
J
Jarek Radosz 已提交
574 575
      end

576 577 578
      # Adds timestamps (+created_at+ and +updated_at+) columns to the table.
      #
      #  t.timestamps(null: false)
579
      #
580
      # See {connection.add_timestamps}[rdoc-ref:SchemaStatements#add_timestamps]
581
      def timestamps(options = {})
582
        @base.add_timestamps(name, options)
583 584 585
      end

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

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

      # Removes the column(s) from the table definition.
607
      #
608 609
      #  t.remove(:qualification)
      #  t.remove(:qualification, :experience)
610
      #
611
      # See {connection.remove_columns}[rdoc-ref:SchemaStatements#remove_columns]
612
      def remove(*column_names)
613
        @base.remove_columns(name, *column_names)
614 615
      end

616
      # Removes the given index from the table.
617
      #
618 619 620 621
      #   t.remove_index(:branch_id)
      #   t.remove_index(column: [:branch_id, :party_id])
      #   t.remove_index(name: :by_branch_party)
      #
622
      # See {connection.remove_index}[rdoc-ref:SchemaStatements#remove_index]
623
      def remove_index(options = {})
624
        @base.remove_index(name, options)
625 626
      end

627
      # Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
628
      #
629
      #  t.remove_timestamps
630
      #
631
      # See {connection.remove_timestamps}[rdoc-ref:SchemaStatements#remove_timestamps]
632 633
      def remove_timestamps(options = {})
        @base.remove_timestamps(name, options)
634 635 636
      end

      # Renames a column.
637
      #
638
      #  t.rename(:description, :name)
639
      #
640
      # See {connection.rename_column}[rdoc-ref:SchemaStatements#rename_column]
641
      def rename(column_name, new_column_name)
642
        @base.rename_column(name, column_name, new_column_name)
643 644
      end

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

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

671 672
      # Adds a foreign key.
      #
673
      #  t.foreign_key(:authors)
674
      #
675
      # See {connection.add_foreign_key}[rdoc-ref:SchemaStatements#add_foreign_key]
676
      def foreign_key(*args)
677 678 679
        @base.add_foreign_key(name, *args)
      end

680 681
      # Checks to see if a foreign key exists.
      #
682
      #  t.foreign_key(:authors) unless t.foreign_key_exists?(:authors)
683
      #
684
      # See {connection.foreign_key_exists?}[rdoc-ref:SchemaStatements#foreign_key_exists?]
685
      def foreign_key_exists?(*args)
A
Anton 已提交
686 687
        @base.foreign_key_exists?(name, *args)
      end
688
    end
689
  end
690
end