Skip to content

Commit

Permalink
Move length-validation for encrypted columns after schema is loaded
Browse files Browse the repository at this point in the history
Doing it before meant it required a database connection at class loading
time, which was a source a trouble.

See rails#42991 (comment)
  • Loading branch information
jorgemanrubia committed Aug 12, 2021
1 parent c84dec3 commit f0fe547
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions activerecord/lib/active_record/encryption/encryptable_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ def encrypt_attribute(name, attribute_scheme)
end

preserve_original_encrypted(name) if attribute_scheme.ignore_case?
validate_column_size(name) if ActiveRecord::Encryption.config.validate_column_size
ActiveRecord::Encryption.encrypted_attribute_was_declared(self, name)
end

Expand Down Expand Up @@ -121,12 +120,22 @@ def override_accessors_to_preserve_original(name, original_attribute_name)
end)
end

def load_schema!
super

add_length_validation_for_encrypted_columns if ActiveRecord::Encryption.config.validate_column_size
end

def add_length_validation_for_encrypted_columns
encrypted_attributes&.each do |attribute_name|
validate_column_size attribute_name
end
end

def validate_column_size(attribute_name)
if table_exists? && limit = columns_hash[attribute_name.to_s]&.limit
validates_length_of attribute_name, maximum: limit
end
rescue ActiveRecord::ConnectionNotEstablished => e
Rails.logger.warn "Skipping adding length validation for #{self.name}\##{attribute_name}. Can't check column limit due to: #{e.inspect}"
end
end

Expand Down

0 comments on commit f0fe547

Please sign in to comment.