diff options
author | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2014-06-26 17:12:46 -0300 |
---|---|---|
committer | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2014-06-26 17:12:46 -0300 |
commit | ea93a15316d93896227c4c9d1ec5e47469575453 (patch) | |
tree | d766406aaefddedfc108297354e73bef80d95b06 /activerecord/lib/active_record/connection_adapters/postgresql | |
parent | 5add8b8d6d27afac9fe46bcee09cd341fb124294 (diff) | |
parent | a5b3f372ab30e043d25b25b05e603e6ed33c0ee9 (diff) | |
download | rails-ea93a15316d93896227c4c9d1ec5e47469575453.tar.gz rails-ea93a15316d93896227c4c9d1ec5e47469575453.tar.bz2 rails-ea93a15316d93896227c4c9d1ec5e47469575453.zip |
Merge pull request #15606 from senny/ar/foreign_key_support
Basic support for adding and removing foreign keys
Diffstat (limited to 'activerecord/lib/active_record/connection_adapters/postgresql')
-rw-r--r-- | activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb index b2aeb3a058..30df98be1b 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -448,6 +448,42 @@ module ActiveRecord execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}" end + def foreign_keys(table_name) + fk_info = select_all <<-SQL.strip_heredoc + SELECT t2.relname AS to_table, a1.attname AS column, a2.attname AS primary_key, c.conname AS name, c.confupdtype AS on_update, c.confdeltype AS on_delete + FROM pg_constraint c + JOIN pg_class t1 ON c.conrelid = t1.oid + JOIN pg_class t2 ON c.confrelid = t2.oid + JOIN pg_attribute a1 ON a1.attnum = c.conkey[1] AND a1.attrelid = t1.oid + JOIN pg_attribute a2 ON a2.attnum = c.confkey[1] AND a2.attrelid = t2.oid + JOIN pg_namespace t3 ON c.connamespace = t3.oid + WHERE c.contype = 'f' + AND t1.relname = #{quote(table_name)} + AND t3.nspname = ANY (current_schemas(false)) + ORDER BY c.conname + SQL + + fk_info.map do |row| + options = { + column: row['column'], + name: row['name'], + primary_key: row['primary_key'] + } + + options[:on_delete] = extract_foreign_key_action(row['on_delete']) + options[:on_update] = extract_foreign_key_action(row['on_update']) + ForeignKeyDefinition.new(table_name, row['to_table'], options) + end + end + + def extract_foreign_key_action(specifier) # :nodoc: + case specifier + when 'c'; :cascade + when 'n'; :nullify + when 'r'; :restrict + end + end + def index_name_length 63 end |