1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #43963 from fatkodima/fix-postgres-check-constraint-expression

Correctly parse complex check constraint expressions for PostgreSQL
This commit is contained in:
Ryuta Kamizono 2021-12-22 17:05:11 +09:00 committed by GitHub
commit a8d088fbdc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 2 deletions

View file

@ -525,7 +525,7 @@ module ActiveRecord
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'
@ -537,7 +537,7 @@ module ActiveRecord
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

View file

@ -43,6 +43,19 @@ if ActiveRecord::Base.connection.supports_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