Skip to content

Commit

Permalink
Merge pull request #9 from localytics/foreign-keys
Browse files Browse the repository at this point in the history
Foreign key support
  • Loading branch information
kddnewton authored Feb 3, 2017
2 parents 5060b5b + 38298f2 commit 4d989b8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
5 changes: 4 additions & 1 deletion bin/console
Original file line number Diff line number Diff line change
Expand Up @@ -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
21 changes: 20 additions & 1 deletion lib/odbc_adapter/schema_statements.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 4d989b8

Please sign in to comment.