From 38298f24362752e9ac838eb8c1db0e5ae7fa4ad4 Mon Sep 17 00:00:00 2001 From: Kevin Deisz Date: Fri, 3 Feb 2017 17:03:58 -0500 Subject: [PATCH] Foreign key support --- bin/console | 5 ++++- lib/odbc_adapter/schema_statements.rb | 21 ++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/bin/console b/bin/console index 6b5a622f..7853a78b 100755 --- a/bin/console +++ b/bin/console @@ -3,7 +3,10 @@ require 'bundler/setup' require 'odbc_adapter' -ActiveRecord::Base.establish_connection(adapter: 'odbc', dsn: ENV['DSN']) if ENV['DSN'] +options = { adapter: 'odbc' } +options[:dsn] = ENV['DSN'] if ENV['DSN'] +options[:conn_str] = ENV['CONN_STR'] if ENV['CONN_STR'] +ActiveRecord::Base.establish_connection(options) if options.any? require 'irb' IRB.start diff --git a/lib/odbc_adapter/schema_statements.rb b/lib/odbc_adapter/schema_statements.rb index af208e0c..828a76ab 100644 --- a/lib/odbc_adapter/schema_statements.rb +++ b/lib/odbc_adapter/schema_statements.rb @@ -51,7 +51,7 @@ def indexes(table_name, name = nil) next_row = result[row_idx + 1] if (row_idx == result.length - 1) || (next_row[6] == 0 || next_row[7] == 1) - indices << IndexDefinition.new(table_name, format_case(index_name), unique, index_cols) + indices << ActiveRecord::ConnectionAdapters::IndexDefinition.new(table_name, format_case(index_name), unique, index_cols) end end end @@ -95,6 +95,25 @@ def primary_key(table_name) result[0] && result[0][3] end + def foreign_keys(table_name) + stmt = @connection.foreign_keys(native_case(table_name.to_s)) + result = stmt.fetch_all || [] + stmt.drop unless stmt.nil? + + result.map do |key| + fk_from_table = key[2] # PKTABLE_NAME + fk_to_table = key[6] # FKTABLE_NAME + + ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(fk_from_table, fk_to_table, + name: key[11], # FK_NAME + column: key[3], # PKCOLUMN_NAME + primary_key: key[7], # FKCOLUMN_NAME + on_delete: key[10], # DELETE_RULE + on_update: key[9] # UPDATE_RULE + ) + end + end + # Ensure it's shorter than the maximum identifier length for the current # dbms def index_name(table_name, options)