Module: ActiveRecord::ConnectionAdapters::MysqlAdapterForeignKeyMethods
- Included in:
- Mysql2Adapter, MysqlAdapter
- Defined in:
- lib/foreign_key_saver/foreign_key_saver_patches.rb
Overview
common to mysql & mysql2
Class Method Summary collapse
Instance Method Summary collapse
- #foreign_key_constraints_on(table_name) ⇒ Object
- #remove_foreign_key_constraint(table_name, constraint) ⇒ Object
- #remove_foreign_key_constraints_referencing(table_name) ⇒ Object
Class Method Details
.columns_from_sql(column_list_sql) ⇒ Object
123 124 125 |
# File 'lib/foreign_key_saver/foreign_key_saver_patches.rb', line 123 def self.columns_from_sql(column_list_sql) column_list_sql.scan(/`([^`]+)`/).collect(&:first) end |
.constraints_from_sql(create_table_sql) ⇒ Object
116 117 118 119 120 121 |
# File 'lib/foreign_key_saver/foreign_key_saver_patches.rb', line 116 def self.constraints_from_sql(create_table_sql) # the clauses look like this: CONSTRAINT `ab` FOREIGN KEY (`ac`, `bc`) REFERENCES `parent` (`a`, `b`) ON DELETE SET NULL ON UPDATE CASCADE create_table_sql.scan(/CONSTRAINT `([^`]+)` FOREIGN KEY \((`(?:[^`]+)`(?:, `(?:[^`]+)`)*)\) REFERENCES `([^`]+)` \((`(?:[^`]+)`(?:, `(?:[^`]+)`)*)\)(?: ON DELETE (CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT))?(?: ON UPDATE (CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT))?/).collect do |capture| ForeignKeyConstraint.new(capture[0], columns_from_sql(capture[1]), capture[2], columns_from_sql(capture[3]), capture[5], capture[4]) end end |
Instance Method Details
#foreign_key_constraints_on(table_name) ⇒ Object
112 113 114 |
# File 'lib/foreign_key_saver/foreign_key_saver_patches.rb', line 112 def foreign_key_constraints_on(table_name) self.class.constraints_from_sql(select_one("SHOW CREATE TABLE #{quote_table_name(table_name)}")["Create Table"]) end |
#remove_foreign_key_constraint(table_name, constraint) ⇒ Object
98 99 100 |
# File 'lib/foreign_key_saver/foreign_key_saver_patches.rb', line 98 def remove_foreign_key_constraint(table_name, constraint) execute "ALTER TABLE #{quote_table_name(table_name)} DROP FOREIGN KEY #{quote_column_name(constraint)}" end |
#remove_foreign_key_constraints_referencing(table_name) ⇒ Object
102 103 104 105 106 107 108 109 110 |
# File 'lib/foreign_key_saver/foreign_key_saver_patches.rb', line 102 def remove_foreign_key_constraints_referencing(table_name) select_rows( "SELECT DISTINCT TABLE_NAME, CONSTRAINT_NAME" + " FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE" + " WHERE REFERENCED_TABLE_SCHEMA = SCHEMA()" + " AND REFERENCED_TABLE_NAME = #{quote(table_name)}").each do |table_name, constraint_name| remove_foreign_key_constraint(table_name, constraint_name) end end |