Skip to content

Commit c497b56

Browse files
Benjamin Burkhartbenny-burkhart
Benjamin Burkhart
authored andcommitted
Include check constraints in structure.sql
See issue #2213
1 parent 2e9eb80 commit c497b56

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb

+19
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ def structure_dump # :nodoc:
5151
structure << ddl
5252
structure << structure_dump_indexes(table_name)
5353
structure << structure_dump_unique_keys(table_name)
54+
structure << structure_dump_check_constraints(table_name)
5455
structure << structure_dump_table_comments(table_name)
5556
structure << structure_dump_column_comments(table_name)
5657
end
@@ -161,6 +162,24 @@ def structure_dump_fk_constraints # :nodoc:
161162
join_with_statement_token(fks)
162163
end
163164

165+
def structure_dump_check_constraints(table)
166+
keys = {}
167+
check_constraints = select_all(<<~SQL.squish, "SCHEMA")
168+
SELECT /*+ OPTIMIZER_FEATURES_ENABLE('11.2.0.2') */ c.CONSTRAINT_NAME, c.SEARCH_CONDITION
169+
FROM all_constraints c
170+
WHERE c.table_name = '#{table.upcase}'
171+
AND c.constraint_type = 'C'
172+
AND c.owner = SYS_CONTEXT('userenv', 'current_schema')
173+
AND c.generated = 'USER NAME'
174+
SQL
175+
check_constraints.each do |check_constraint|
176+
keys[check_constraint["constraint_name"]] = check_constraint["search_condition"]
177+
end
178+
keys.map do |k, v|
179+
"ALTER TABLE #{table.upcase} ADD CONSTRAINT #{k} CHECK (#{v})"
180+
end
181+
end
182+
164183
def structure_dump_table_comments(table_name)
165184
comments = []
166185
comment = table_comment(table_name)

spec/active_record/connection_adapters/oracle_enhanced/structure_dump_spec.rb

+12
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,18 @@ class ::TestPost < ActiveRecord::Base
215215
expect(dump).to match(/CREATE TABLE "BARS" \(\n "ID" NUMBER\(38,0\) NOT NULL,\n "SUPER" RAW\(255\)/)
216216
end
217217

218+
it "should dump check constraints" do
219+
@conn.execute <<~SQL
220+
ALTER TABLE test_posts
221+
add CONSTRAINT foo_is_json CHECK(foo is json)
222+
SQL
223+
dump = ActiveRecord::Base.connection.structure_dump_check_constraints("test_posts")
224+
expect(dump).to eq(["ALTER TABLE FORM_SUBMISSIONS ADD CONSTRAINT FOO_IS_JSON CHECK (foo is json)"])
225+
226+
dump = ActiveRecord::Base.connection.structure_dump
227+
expect(dump).to match(/ALTER TABLE FORM_SUBMISSIONS ADD CONSTRAINT FOO_IS_JSON CHECK \(foo is json\)/)
228+
end
229+
218230
it "should dump table comments" do
219231
comment_sql = %Q(COMMENT ON TABLE "TEST_POSTS" IS 'Test posts with ''some'' "quotes"')
220232
@conn.execute comment_sql

0 commit comments

Comments
 (0)