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.
27 lines
751 B
Cheetah
27 lines
751 B
Cheetah
DO $$
|
|
DECLARE
|
|
current_not_null boolean;
|
|
BEGIN
|
|
SELECT a.attnotnull
|
|
INTO current_not_null
|
|
FROM pg_attribute a
|
|
JOIN pg_class t ON t.oid = a.attrelid
|
|
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
WHERE n.nspname = '{{.SchemaName}}'
|
|
AND t.relname = '{{.TableName}}'
|
|
AND a.attname = '{{.ColumnName}}'
|
|
AND a.attnum > 0
|
|
AND NOT a.attisdropped;
|
|
|
|
IF current_not_null IS NOT NULL AND current_not_null IS DISTINCT FROM {{.NotNull}} THEN
|
|
{{- if .NotNull }}
|
|
ALTER TABLE {{qual_table .SchemaName .TableName}}
|
|
ALTER COLUMN {{quote_ident .ColumnName}} SET NOT NULL;
|
|
{{- else }}
|
|
ALTER TABLE {{qual_table .SchemaName .TableName}}
|
|
ALTER COLUMN {{quote_ident .ColumnName}} DROP NOT NULL;
|
|
{{- end }}
|
|
END IF;
|
|
END;
|
|
$$;
|