Class: Templaty::Migrations::AddColumnGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/generators/templaty/migrations/add_column_generator.rb

Instance Method Summary collapse

Instance Method Details

#add_columnObject

Add the column without a default value.

github.com/ankane/strong_migrations#good-1



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/generators/templaty/migrations/add_column_generator.rb', line 20

def add_column
  if options[:null] == false && options[:default].blank?
    raise('[Templaty] Options "default" cannot be blank when option "null" is false.')
  end

  target = "db/migrate/#{timestamp(0)}_add_column_#{options[:column]}_to_#{options[:table]}.rb"

  template('db/migrate/add_column.rb.erb', target)

  `open #{target}`
end

#backfillObject

There are three keys to backfilling safely: batching, throttling, and running it outside a transaction. Use the Rails console or a separate migration with disable_ddl_transaction!.

github.com/ankane/strong_migrations#good-2



37
38
39
40
41
42
43
44
45
# File 'lib/generators/templaty/migrations/add_column_generator.rb', line 37

def backfill
  return unless options.key?(:default) || options[:null] != true # non declared null is `null: true`

  target = "db/migrate/#{timestamp(1)}_backfill_#{options[:column]}_to_#{options[:table].pluralize}.rb"

  template('db/migrate/backfill.rb.erb', target)

  `open #{target}`
end

#not_nullObject



64
65
66
67
68
69
70
71
72
# File 'lib/generators/templaty/migrations/add_column_generator.rb', line 64

def not_null
  return unless options[:null] == false

  target = "db/migrate/#{timestamp(3)}_not_null_#{options[:column]}_to_#{options[:table].pluralize}.rb"

  template('db/migrate/not_null.rb.erb', target)

  `open #{target}`
end

#set_defaultObject



50
51
52
53
54
55
56
57
58
# File 'lib/generators/templaty/migrations/add_column_generator.rb', line 50

def set_default
  return unless options.key?(:default)

  target = "db/migrate/#{timestamp(2)}_set_column_#{options[:column]}_default_to_#{options[:table].pluralize}.rb"

  template('db/migrate/set_default.rb.erb', target)

  `open #{target}`
end

#validate_not_nullObject

Then validate it in a separate migration. A NOT NULL check constraint is functionally equivalent to setting NOT NULL on the column. In Postgres 12+, once the check constraint is validated, you can safely set NOT NULL on the column and drop the check constraint.

github.com/ankane/strong_migrations#good-11



81
82
83
84
85
86
87
88
89
# File 'lib/generators/templaty/migrations/add_column_generator.rb', line 81

def validate_not_null
  return unless options[:null] == false

  target = "db/migrate/#{timestamp(4)}_validate_not_null_#{options[:column]}_to_#{options[:table].pluralize}.rb"

  template('db/migrate/validate_not_null.rb.erb', target)

  `open #{target}`
end