52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
# File 'lib/active_record/connection_adapters/firebird/schema_statements.rb', line 52
def foreign_keys(table_name)
result = query(<<-SQL.strip_heredoc, "SCHEMA")
WITH FK_FIELDS AS (
SELECT
AA2.RDB$RELATION_NAME,
AA2.RDB$CONSTRAINT_NAME,
BB2.RDB$CONST_NAME_UQ AS LINK_UK_OR_PK,
EE2.RDB$RELATION_NAME AS REFERENCE_TABLE,
CC2.RDB$FIELD_NAME,
AA2.RDB$CONSTRAINT_TYPE
FROM
RDB$RELATION_CONSTRAINTS AA2
LEFT JOIN RDB$REF_CONSTRAINTS BB2 ON BB2.RDB$CONSTRAINT_NAME = AA2.RDB$CONSTRAINT_NAME
LEFT JOIN RDB$INDEX_SEGMENTS CC2 ON CC2.RDB$INDEX_NAME = AA2.RDB$INDEX_NAME
LEFT JOIN RDB$RELATION_FIELDS DD2 ON DD2.RDB$FIELD_NAME = CC2.RDB$FIELD_NAME AND DD2.RDB$RELATION_NAME = AA2.RDB$RELATION_NAME
LEFT JOIN RDB$RELATION_CONSTRAINTS EE2 ON EE2.RDB$CONSTRAINT_NAME = BB2.RDB$CONST_NAME_UQ
)
SELECT
AA.RDB$CONSTRAINT_NAME,
BB.REFERENCE_TABLE,
BB.FIELDS,
BB.REFERENCE_FIELDS
FROM
RDB$RELATION_CONSTRAINTS AA
LEFT JOIN (
SELECT
AA1.RDB$RELATION_NAME,
AA1.RDB$CONSTRAINT_NAME,
AA1.LINK_UK_OR_PK,
AA1.REFERENCE_TABLE,
(
SELECT LIST(TRIM(AA3.RDB$FIELD_NAME), ', ') FROM FK_FIELDS AA3 WHERE AA3.RDB$CONSTRAINT_NAME = AA1.RDB$CONSTRAINT_NAME ROWS 1
) AS FIELDS,
(
SELECT LIST(TRIM(AA4.RDB$FIELD_NAME), ', ') FROM FK_FIELDS AA4 WHERE AA4.RDB$CONSTRAINT_NAME = AA1.LINK_UK_OR_PK ROWS 1
) AS REFERENCE_FIELDS
FROM
FK_FIELDS AA1
GROUP BY
AA1.RDB$RELATION_NAME,
AA1.RDB$CONSTRAINT_NAME,
AA1.REFERENCE_TABLE,
AA1.LINK_UK_OR_PK
) BB ON BB.RDB$RELATION_NAME = AA.RDB$RELATION_NAME AND BB.RDB$CONSTRAINT_NAME = AA.RDB$CONSTRAINT_NAME
WHERE
AA.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY'
AND AA.RDB$RELATION_NAME = '#{table_name.upcase}';
SQL
result.map do |row|
options = {
column: row[2].downcase,
name: row[0].strip.downcase,
primary_key: row[3].downcase
}
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(table_name, row[1].strip.downcase, options)
end
end
|