fix(pgsql): handle nullability/type/default drift on existing columns
Existing databases that already ran an old migration kept stale NOT NULL constraints and mismatched column types/defaults, because the schema writer only emitted idempotent ADD COLUMN IF NOT EXISTS guards and never altered columns that already existed. - Emit guarded ALTER COLUMN ... SET/DROP NOT NULL when a column's nullability differs from the model. - Emit guarded ALTER COLUMN ... TYPE, falling back to renaming the old column and adding a fresh one when the in-place conversion fails. - Emit guarded ALTER COLUMN ... SET/DROP DEFAULT for default drift. - Collapse the previously duplicated plain/guarded templates so WriteSchema (full-schema, live-state-checking) and WriteMigration (diff-based) share the same guarded SQL templates and Go helpers instead of maintaining the logic twice.
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
DO $$
|
||||
DECLARE
|
||||
current_default text;
|
||||
BEGIN
|
||||
SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid)
|
||||
INTO current_default
|
||||
FROM pg_attribute a
|
||||
JOIN pg_class t ON t.oid = a.attrelid
|
||||
JOIN pg_namespace n ON n.oid = t.relnamespace
|
||||
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
|
||||
WHERE n.nspname = '{{.SchemaName}}'
|
||||
AND t.relname = '{{.TableName}}'
|
||||
AND a.attname = '{{.ColumnName}}'
|
||||
AND a.attnum > 0
|
||||
AND NOT a.attisdropped;
|
||||
|
||||
{{- if .SetDefault }}
|
||||
IF current_default IS DISTINCT FROM {{quote .DefaultValue}} THEN
|
||||
ALTER TABLE {{qual_table .SchemaName .TableName}}
|
||||
ALTER COLUMN {{quote_ident .ColumnName}} SET DEFAULT {{.DefaultValue}};
|
||||
END IF;
|
||||
{{- else }}
|
||||
IF current_default IS NOT NULL THEN
|
||||
ALTER TABLE {{qual_table .SchemaName .TableName}}
|
||||
ALTER COLUMN {{quote_ident .ColumnName}} DROP DEFAULT;
|
||||
END IF;
|
||||
{{- end }}
|
||||
END;
|
||||
$$;
|
||||
Reference in New Issue
Block a user