Skip to content

Commit

Permalink
Include check constraints in structure.sql
Browse files Browse the repository at this point in the history
See issue #2213
  • Loading branch information
Benjamin Burkhart authored and benny-burkhart committed Dec 1, 2021
1 parent 2e9eb80 commit c497b56
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def structure_dump # :nodoc:
structure << ddl
structure << structure_dump_indexes(table_name)
structure << structure_dump_unique_keys(table_name)
structure << structure_dump_check_constraints(table_name)
structure << structure_dump_table_comments(table_name)
structure << structure_dump_column_comments(table_name)
end
Expand Down Expand Up @@ -161,6 +162,24 @@ def structure_dump_fk_constraints # :nodoc:
join_with_statement_token(fks)
end

def structure_dump_check_constraints(table)
keys = {}
check_constraints = select_all(<<~SQL.squish, "SCHEMA")
SELECT /*+ OPTIMIZER_FEATURES_ENABLE('11.2.0.2') */ c.CONSTRAINT_NAME, c.SEARCH_CONDITION
FROM all_constraints c
WHERE c.table_name = '#{table.upcase}'
AND c.constraint_type = 'C'
AND c.owner = SYS_CONTEXT('userenv', 'current_schema')
AND c.generated = 'USER NAME'
SQL
check_constraints.each do |check_constraint|
keys[check_constraint["constraint_name"]] = check_constraint["search_condition"]
end
keys.map do |k, v|
"ALTER TABLE #{table.upcase} ADD CONSTRAINT #{k} CHECK (#{v})"
end
end

def structure_dump_table_comments(table_name)
comments = []
comment = table_comment(table_name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,18 @@ class ::TestPost < ActiveRecord::Base
expect(dump).to match(/CREATE TABLE "BARS" \(\n "ID" NUMBER\(38,0\) NOT NULL,\n "SUPER" RAW\(255\)/)
end

it "should dump check constraints" do
@conn.execute <<~SQL
ALTER TABLE test_posts
add CONSTRAINT foo_is_json CHECK(foo is json)
SQL
dump = ActiveRecord::Base.connection.structure_dump_check_constraints("test_posts")
expect(dump).to eq(["ALTER TABLE FORM_SUBMISSIONS ADD CONSTRAINT FOO_IS_JSON CHECK (foo is json)"])

dump = ActiveRecord::Base.connection.structure_dump
expect(dump).to match(/ALTER TABLE FORM_SUBMISSIONS ADD CONSTRAINT FOO_IS_JSON CHECK \(foo is json\)/)
end

it "should dump table comments" do
comment_sql = %Q(COMMENT ON TABLE "TEST_POSTS" IS 'Test posts with ''some'' "quotes"')
@conn.execute comment_sql
Expand Down

0 comments on commit c497b56

Please sign in to comment.