lib/strong_migrations/checks.rb in strong_migrations-1.3.0 vs lib/strong_migrations/checks.rb in strong_migrations-1.3.1
- old
+ new
@@ -30,13 +30,15 @@
def check_add_column(*args)
options = args.extract_options!
table, column, type = args
default = options[:default]
- # Active Record has special case for uuid columns that allows function default values
+ # Check key since DEFAULT NULL behaves differently from no default
+ #
+ # Also, Active Record has special case for uuid columns that allows function default values
# https://github.com/rails/rails/blob/v7.0.3.1/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb#L92-L93
- if !default.nil? && (!adapter.add_column_default_safe? || (volatile = (postgresql? && type.to_s == "uuid" && default.to_s.include?("()") && adapter.default_volatile?(default))))
+ if options.key?(:default) && (!adapter.add_column_default_safe? || (volatile = (postgresql? && type.to_s == "uuid" && default.to_s.include?("()") && adapter.default_volatile?(default))))
if options[:null] == false
options = options.except(:null)
append = "
Then add the NOT NULL constraint in separate migrations."
@@ -220,13 +222,11 @@
throw :safe
end
add_constraint_code =
if constraint_methods
- # only quote when needed
- expr_column = column.to_s =~ /\A[a-z0-9_]+\z/ ? column : connection.quote_column_name(column)
- command_str(:add_check_constraint, [table, "#{expr_column} IS NOT NULL", {name: constraint_name, validate: false}])
+ command_str(:add_check_constraint, [table, "#{quote_column_if_needed(column)} IS NOT NULL", {name: constraint_name, validate: false}])
else
safety_assured_str(add_code)
end
validate_constraint_code =
@@ -422,13 +422,20 @@
def backfill_code(table, column, default, function = false)
model = table.to_s.classify
if function
# update_all(column: Arel.sql(default)) also works in newer versions of Active Record
- "#{model}.unscoped.in_batches do |relation| \n relation.where(#{column}: nil).update_all(\"#{column} = #{default}\")\n sleep(0.01)\n end"
+ update_expr = "#{quote_column_if_needed(column)} = #{default}"
+ "#{model}.unscoped.in_batches do |relation| \n relation.where(#{column}: nil).update_all(#{update_expr.inspect})\n sleep(0.01)\n end"
else
"#{model}.unscoped.in_batches do |relation| \n relation.update_all #{column}: #{default.inspect}\n sleep(0.01)\n end"
end
+ end
+
+ # only quote when needed
+ # important! only use for display purposes
+ def quote_column_if_needed(column)
+ column.to_s =~ /\A[a-z0-9_]+\z/ ? column : connection.quote_column_name(column)
end
def new_table?(table)
@new_tables.include?(table.to_s)
end