Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correctly parse complex check constraint expressions for PostgreSQL #43963

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ def check_constraints(table_name) # :nodoc:
scope = quoted_scope(table_name)

check_info = exec_query(<<-SQL, "SCHEMA")
SELECT conname, pg_get_constraintdef(c.oid) AS constraintdef, c.convalidated AS valid
SELECT conname, pg_get_constraintdef(c.oid, true) AS constraintdef, c.convalidated AS valid
FROM pg_constraint c
JOIN pg_class t ON c.conrelid = t.oid
WHERE c.contype = 'c'
Expand All @@ -537,7 +537,7 @@ def check_constraints(table_name) # :nodoc:
name: row["conname"],
validate: row["valid"]
}
expression = row["constraintdef"][/CHECK \({2}(.+)\){2}/, 1]
expression = row["constraintdef"][/CHECK \((.+)\)/m, 1]

CheckConstraintDefinition.new(table_name, expression, options)
end
Expand Down
13 changes: 13 additions & 0 deletions activerecord/test/cases/migration/check_constraint_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ def test_check_constraints
else
assert_equal "price > discounted_price", constraint.expression
end

if current_adapter?(:PostgreSQLAdapter)
begin
# Test that complex expression is correctly parsed from the database
@connection.add_check_constraint(:trades,
"CASE WHEN price IS NOT NULL THEN true ELSE false END", name: "price_is_required")

constraint = @connection.check_constraints("trades").find { |c| c.name == "price_is_required" }
assert_includes constraint.expression, "WHEN price IS NOT NULL"
ensure
@connection.remove_check_constraint(:trades, name: "price_is_required")
end
end
end

def test_add_check_constraint
Expand Down