class PGTrunk::Operations::ForeignKeys::Base
@abstract @private Base
class for operations with foreign keys
Public Instance Methods
By default foreign keys are sorted by tables and names.
# File lib/pg_trunk/operations/foreign_keys/base.rb, line 33 def <=>(other) return unless other.is_a?(self.class) result = table <=> other.table result.zero? ? super : result end
Private Instance Methods
Notice that in Rails the key ‘if_not_exists: true` means that the constraint should not be created if the table has ANY fk reference to the other table (even though the keys differ).
@param [#table, reference] operation @return [Boolean]
# File lib/pg_trunk/operations/foreign_keys/base.rb, line 131 def added? PGTrunk.database.foreign_key_exists?(table.name, reference.name) end
Add a name of the existing foreign key
# File lib/pg_trunk/operations/foreign_keys/base.rb, line 136 def current_name @current_name ||= AddForeignKey.find do |fk| fk.table == table && fk.columns == columns && fk.reference == reference && fk.primary_key == primary_key end&.name end
Check if the fk name wasn’t generated by Rails @param [#name] operation The operation @return [Boolean]
# File lib/pg_trunk/operations/foreign_keys/base.rb, line 109 def custom_name?(qname = name) qname&.differs_from?(/^fk_rails_\w+$/) end
Check if the only column is custom @param [#table, reference, columns, primary_key] operation
# File lib/pg_trunk/operations/foreign_keys/base.rb, line 115 def default_columns? columns == generated_columns end
Check if columns are default for the reference @param [#table, reference, columns, primary_key] operation
# File lib/pg_trunk/operations/foreign_keys/base.rb, line 121 def default_pkey? primary_key == %w[id] end
@param [#reference] operation @return [Array<String>]
# File lib/pg_trunk/operations/foreign_keys/base.rb, line 73 def generated_columns return @generated_columns if instance_variable_defined?(:@generated_columns) @generated_columns = begin return if reference.blank? || primary_key.blank? prefix = PGTrunk .database .strip_table_name(reference.name) .to_s .singularize primary_key.map { |pk| "#{prefix}_#{pk}" } end end
Generate the name for the foreign key using the essential options @return [PGTrunk::QualifiedName]
# File lib/pg_trunk/operations/foreign_keys/base.rb, line 92 def generated_name return @generated_name if instance_variable_defined?(:@generated_name) @generated_name = begin return if table.blank? || reference.blank? return if primary_key.blank? || columns.blank? key_options = to_h.slice(:reference, :columns, :primary_key) identifier = "#{table.lean}_#{key_options}_fk" hashed_identifier = Digest::SHA256.hexdigest(identifier).first(10) PGTrunk::QualifiedName.wrap("fk_rails_#{hashed_identifier}") end end
# File lib/pg_trunk/operations/foreign_keys/base.rb, line 145 def sql_action(key) case key when :nullify then "SET NULL" when :reset then "SET DEFAULT" when :restrict then "RESTRICT" when :cascade then "CASCADE" else "NO ACTION" end end