pgschema
pgschema copied to clipboard
CHECK constraint with LIKE loses the conditions after the pattern
Summary
In a CHECK constraint that uses LIKE, pgschema drops everything after the pattern literal. This affects dump and apply, and plan can't detect it.
Reproduce (v1.13.1, PostgreSQL 16)
CREATE TABLE t (
a varchar(20),
b varchar(20),
CONSTRAINT t_a_check CHECK (a IS NULL OR (a LIKE 'p-%' AND b IS NOT NULL))
);
pg_get_constraintdef returns:
CHECK (((a IS NULL) OR (((a)::text ~~ 'p-%'::text) AND (b IS NOT NULL))))
pgschema dumpwritesCHECK (a IS NULL OR a::text LIKE 'p-%'). TheAND b IS NOT NULLclause is gone.- Applying the original
CREATE TABLEto an empty schema withpgschema applycreates the constraint without that clause. - If a database has
CHECK (a IS NULL OR a LIKE 'p-%')and the desired state has the full constraint,pgschema planreportsNo changes detected.
Cause
applyLegacyCheckNormalizations in ir/normalize.go splits the clause on " ~~ " and truncates the right-hand side at its first :::
parts := strings.Split(clause, " ~~ ")
if len(parts) == 2 {
columnName := strings.TrimSpace(parts[0])
pattern := strings.TrimSpace(parts[1])
if idx := strings.Index(pattern, "::"); idx != -1 {
pattern = pattern[:idx] // drops ") AND (b IS NOT NULL))"
}
return fmt.Sprintf("%s LIKE %s", columnName, pattern)
}
The desired state and the current state both go through this function, so they compare equal and the diff never shows the lost clause.
Expected
Only the ~~ '<literal>'::text operand is rewritten, and the rest of the expression is left as it is:
CHECK ((a IS NULL) OR ((a::text LIKE 'p-%') AND (b IS NOT NULL)))
I have a fix with tests and will open a PR.