diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb index a2c1d6e0f0207..1840c6b683b68 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -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' @@ -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 diff --git a/activerecord/test/cases/migration/check_constraint_test.rb b/activerecord/test/cases/migration/check_constraint_test.rb index 153c994a8ffd8..670cf9e27658c 100644 --- a/activerecord/test/cases/migration/check_constraint_test.rb +++ b/activerecord/test/cases/migration/check_constraint_test.rb @@ -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