Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions cmd/plan/plan.go
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,11 @@ func normalizeSchemaNames(irData *ir.IR, fromSchema, toSchema string) {
for _, name := range irData.Metadata.ShadowedOperators {
shadowedOperators[name] = true
}
stripQualifiers := newSameSchemaQualifierStripper(toSchema, shadowedOperators)
shadowedTypes := make(map[string]bool, len(irData.Metadata.ShadowedTypes))
for _, name := range irData.Metadata.ShadowedTypes {
shadowedTypes[name] = true
}
stripQualifiers := newSameSchemaQualifierStripper(toSchema, shadowedOperators, shadowedTypes)

// Normalize schema names in Schemas map
if schema, exists := irData.Schemas[fromSchema]; exists {
Expand Down Expand Up @@ -889,7 +893,7 @@ func newSchemaStringReplacer(fromSchema, toSchema string) func(string) string {
// shadowedOperators names the operators that must keep their qualifier because
// an unqualified reference would resolve to a pg_catalog operator instead (see
// ir.Metadata.ShadowedOperators).
func newSameSchemaQualifierStripper(schema string, shadowedOperators map[string]bool) func(string) string {
func newSameSchemaQualifierStripper(schema string, shadowedOperators, shadowedTypes map[string]bool) func(string) string {
if schema == "" {
return func(s string) string { return s }
}
Expand Down Expand Up @@ -928,7 +932,9 @@ func newSameSchemaQualifierStripper(schema string, shadowedOperators map[string]
}
return name
})
return typePattern.ReplaceAllString(s, "::")
// A kept qualifier may be the raw name newSchemaStringReplacer wrote
// ("My Schema."), so write it in quote_ident form.
return ir.StripCastQualifiers(s, typePattern, shadowedTypes, "::"+ir.QuoteIdentifier(schema)+".")
}
containsPrefix := func(s string) bool {
for _, p := range prefixes {
Expand Down
22 changes: 22 additions & 0 deletions cmd/plan/plan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,3 +455,25 @@ func TestNormalizeSchemaNames_MapsShadowedTypeRoutineSignatures(t *testing.T) {
t.Errorf("privilege ObjectName = %q, want %q", priv.ObjectName, "nc_core(nm public.name)")
}
}

func TestNormalizeSchemaNames_QuotesKeptShadowedTypeCast(t *testing.T) {
const tempSchema = "pgschema_tmp_20260326_123456_abcd1234"
def := "'main'::" + tempSchema + ".name"
fn := &ir.Function{
Schema: tempSchema,
Name: "pick",
Parameters: []*ir.Parameter{{Name: "p", DataType: tempSchema + ".name", DefaultValue: &def}},
}
irData := &ir.IR{
Metadata: ir.Metadata{ShadowedTypes: []string{"name"}},
Schemas: map[string]*ir.Schema{
tempSchema: {Name: tempSchema, Functions: map[string]*ir.Function{"pick(" + tempSchema + ".name)": fn}},
},
}

normalizeSchemaNames(irData, tempSchema, "My Schema")

if want := `'main'::"My Schema".name`; *fn.Parameters[0].DefaultValue != want {
t.Errorf("default = %q, want %q", *fn.Parameters[0].DefaultValue, want)
}
}
2 changes: 1 addition & 1 deletion internal/diff/function.go
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ func formatFunctionParameter(param *ir.Parameter, includeDefault bool, targetSch
if includeDefault && param.DefaultValue != nil {
defaultVal := *param.DefaultValue
// Strip target schema prefix
defaultVal = stripSchemaPrefixMode(defaultVal, targetSchema, qualifySchema)
defaultVal = stripDefaultSchemaPrefix(defaultVal, targetSchema, qualifySchema, shadowedTypes)
// Also strip temporary embedded postgres schema prefixes (pgschema_tmp_*)
defaultVal = stripTempSchemaPrefix(defaultVal)
part += " DEFAULT " + defaultVal
Expand Down
16 changes: 16 additions & 0 deletions internal/diff/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package diff

import (
"fmt"
"regexp"
"sort"
"strings"

Expand All @@ -26,6 +27,21 @@ func stripTypeSchemaPrefix(typeName, targetSchema string, qualifySchema bool, sh
return stripped
}

// stripDefaultSchemaPrefix is stripSchemaPrefixMode for a default expression,
// except that a cast to a type a pg_catalog type shadows keeps its prefix
// (issue #701).
func stripDefaultSchemaPrefix(value, targetSchema string, qualifySchema bool, shadowedTypes map[string]bool) string {
stripped := stripSchemaPrefixMode(value, targetSchema, qualifySchema)
if stripped == value || len(shadowedTypes) == 0 || !strings.Contains(value, "::") {
return stripped
}
pattern := `::` + regexp.QuoteMeta(targetSchema+".")
if quoted := ir.QuoteIdentifier(targetSchema); quoted != targetSchema {
pattern = `::(?:` + regexp.QuoteMeta(targetSchema+".") + `|` + regexp.QuoteMeta(quoted+".") + `)`
}
return ir.StripCastQualifiers(value, regexp.MustCompile(pattern), shadowedTypes, "")
}

// stripSchemaPrefixMode is like stripSchemaPrefix, but when qualifySchema is true the
// target-schema prefix is preserved (not stripped) so type names stay fully qualified.
func stripSchemaPrefixMode(typeName, targetSchema string, qualifySchema bool) string {
Expand Down
69 changes: 57 additions & 12 deletions ir/normalize.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func normalizeSchema(schema *Schema, shadowed, shadowedTypes map[string]bool) {

// Normalize procedures
for _, procedure := range schema.Procedures {
normalizeProcedure(procedure, shadowed)
normalizeProcedure(procedure, shadowed, shadowedTypes)
}

// Normalize types (including domains)
Expand Down Expand Up @@ -235,13 +235,13 @@ func normalizeColumn(column *Column, tableSchema string, shadowed map[string]boo
return
}

normalized := normalizeDefaultValue(*column.DefaultValue, tableSchema, shadowed)
normalized := normalizeDefaultValue(*column.DefaultValue, tableSchema, shadowed, nil)
column.DefaultValue = &normalized
}

// normalizeDefaultValue normalizes default values for semantic comparison
// tableSchema is used to strip same-schema qualifiers from function calls
func normalizeDefaultValue(value string, tableSchema string, shadowed map[string]bool) string {
func normalizeDefaultValue(value string, tableSchema string, shadowed, shadowedTypes map[string]bool) string {
// Remove unnecessary whitespace
value = strings.TrimSpace(value)

Expand Down Expand Up @@ -303,28 +303,26 @@ func normalizeDefaultValue(value string, tableSchema string, shadowed map[string
// These are used internally during plan generation and should be normalized away
// Pattern: ::pgschema_tmp_YYYYMMDD_HHMMSS_XXXXXXXX.typename -> ::typename
if strings.Contains(value, "::pgschema_tmp_") {
re := regexp.MustCompile(`::pgschema_tmp_[^.]+\.`)
value = re.ReplaceAllString(value, "::")
value = StripCastQualifiers(value, tempSchemaCastRe, shadowedTypes, "")
}
// Also strip same-schema type qualifiers for consistent comparison during plan/diff
// This ensures that '::public.typename' from current state matches '::typename' from
// desired state (after pgschema_tmp_* is stripped). Both are semantically equivalent
// within the same schema context. (Issue #218)
if tableSchema != "" && strings.Contains(value, "::"+tableSchema+".") {
re := regexp.MustCompile(`::\Q` + tableSchema + `\E\.`)
value = re.ReplaceAllString(value, "::")
value = StripCastQualifiers(value, re, shadowedTypes, "")
}

// Handle NULL::type -> NULL
// Example: NULL::text -> NULL
re := regexp.MustCompile(`\bNULL::(?:[a-zA-Z_][\w\s.]*)(?:\[\])?`)
value = re.ReplaceAllString(value, "NULL")
value = stripTypedNulls(value)

// Handle numeric literals with type casts
// Example: '-1'::integer -> -1
// Example: '100'::bigint -> 100
// Note: PostgreSQL sometimes casts numeric literals to different types, e.g., -1::integer stored as numeric
re = regexp.MustCompile(`'(-?\d+(?:\.\d+)?)'::(?:integer|bigint|smallint|numeric|decimal|real|double precision|int2|int4|int8|float4|float8)`)
re := regexp.MustCompile(`'(-?\d+(?:\.\d+)?)'::(?:integer|bigint|smallint|numeric|decimal|real|double precision|int2|int4|int8|float4|float8)`)
value = re.ReplaceAllString(value, "$1")

// Handle string literals with ONLY truly redundant type casts
Expand Down Expand Up @@ -486,7 +484,7 @@ func normalizeFunction(function *Function, shadowed, shadowedTypes map[string]bo
}
// Normalize default values (pass function schema for context)
if param.DefaultValue != nil {
normalized := normalizeDefaultValue(*param.DefaultValue, function.Schema, shadowed)
normalized := normalizeDefaultValue(*param.DefaultValue, function.Schema, shadowed, shadowedTypes)
param.DefaultValue = &normalized
}
}
Expand Down Expand Up @@ -808,6 +806,53 @@ func stripSchemaQualifiersKeeping(s, schema string, shadowedTypes map[string]boo
return out.String()
}

var tempSchemaCastRe = regexp.MustCompile(`::pgschema_tmp_[^.]+\.`)

var typedNullRe = regexp.MustCompile(`\bNULL::(?:[a-zA-Z_][\w\s.]*)(?:\[\])?`)

// stripTypedNulls rewrites NULL::type as NULL. A match followed by a quote
// stopped short of a quoted name (NULL::public."char"), so it is left as is.
func stripTypedNulls(value string) string {
var out strings.Builder
last := 0
for _, m := range typedNullRe.FindAllStringIndex(value, -1) {
if m[1] < len(value) && value[m[1]] == '"' {
continue
}
out.WriteString(value[last:m[0]])
out.WriteString("NULL")
last = m[1]
}
out.WriteString(value[last:])
return out.String()
}

// StripCastQualifiers replaces each match of castQualifier, a "::schema."
// pattern, with "::", except before a type named in shadowedTypes: its bare
// name would resolve to the pg_catalog type (issue #701). A kept match is
// written as keepAs when that is set, else left as is.
func StripCastQualifiers(value string, castQualifier *regexp.Regexp, shadowedTypes map[string]bool, keepAs string) string {
if len(shadowedTypes) == 0 {
return castQualifier.ReplaceAllString(value, "::")
}
var out strings.Builder
last := 0
for _, m := range castQualifier.FindAllStringIndex(value, -1) {
out.WriteString(value[last:m[0]])
switch {
case !IsShadowedTypeName(nextIdentifier(value[m[1]:]), shadowedTypes):
out.WriteString("::")
case keepAs != "":
out.WriteString(keepAs)
default:
out.WriteString(value[m[0]:m[1]])
}
last = m[1]
}
out.WriteString(value[last:])
return out.String()
}

// nextIdentifier returns the bare or quoted identifier at the start of s.
func nextIdentifier(s string) string {
if strings.HasPrefix(s, `"`) {
Expand Down Expand Up @@ -844,7 +889,7 @@ func isIdentChar(b byte) bool {
}

// normalizeProcedure normalizes procedure representation
func normalizeProcedure(procedure *Procedure, shadowed map[string]bool) {
func normalizeProcedure(procedure *Procedure, shadowed, shadowedTypes map[string]bool) {
if procedure == nil {
return
}
Expand All @@ -862,7 +907,7 @@ func normalizeProcedure(procedure *Procedure, shadowed map[string]bool) {
}
// Normalize default values (pass procedure schema for context)
if param.DefaultValue != nil {
normalized := normalizeDefaultValue(*param.DefaultValue, procedure.Schema, shadowed)
normalized := normalizeDefaultValue(*param.DefaultValue, procedure.Schema, shadowed, shadowedTypes)
param.DefaultValue = &normalized
}
}
Expand Down
36 changes: 32 additions & 4 deletions ir/normalize_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ir

import (
"regexp"
"strings"
"testing"
)
Expand Down Expand Up @@ -842,13 +843,13 @@ func TestNormalizeOperatorSyntax(t *testing.T) {
if got := normalizeDeparsedExpression("(h OPERATOR(public.->) 'a'::text)", "public", shadowed); got != "(h -> 'a'::text)" {
t.Errorf("normalizeDeparsedExpression left operator syntax: %q", got)
}
if got := normalizeDefaultValue(`('"a"=>"1"'::hstore OPERATOR(public.->) 'a')`, "public", shadowed); got != `('"a"=>"1"'::hstore -> 'a')` {
if got := normalizeDefaultValue(`('"a"=>"1"'::hstore OPERATOR(public.->) 'a')`, "public", shadowed, nil); got != `('"a"=>"1"'::hstore -> 'a')` {
t.Errorf("normalizeDefaultValue left operator syntax: %q", got)
}
if got := normalizeDefaultValue("ARRAY[nextval('s'::regclass)::integer] OPERATOR(public.->) ARRAY[1]", "public", shadowed); got != "ARRAY[nextval('s'::regclass)::integer] -> ARRAY[1]" {
if got := normalizeDefaultValue("ARRAY[nextval('s'::regclass)::integer] OPERATOR(public.->) ARRAY[1]", "public", shadowed, nil); got != "ARRAY[nextval('s'::regclass)::integer] -> ARRAY[1]" {
t.Errorf("normalizeDefaultValue skipped the nextval default: %q", got)
}
if got := normalizeDefaultValue("(1 OPERATOR(public.+) 2)", "public", shadowed); got != "(1 OPERATOR(public.+) 2)" {
if got := normalizeDefaultValue("(1 OPERATOR(public.+) 2)", "public", shadowed, nil); got != "(1 OPERATOR(public.+) 2)" {
t.Errorf("normalizeDefaultValue rewrote a shadowed operator: %q", got)
}

Expand Down Expand Up @@ -877,8 +878,35 @@ func TestNormalizeDefaultValueStripsQuotedFunctionQualifier(t *testing.T) {
`public.get_status()`: `get_status()`,
`'public."MyFunc"()'::text`: `'public."MyFunc"()'`,
} {
if got := normalizeDefaultValue(input, "public", nil); got != want {
if got := normalizeDefaultValue(input, "public", nil, nil); got != want {
t.Errorf("normalizeDefaultValue(%q) = %q, want %q", input, got, want)
}
}
}

func TestStripCastQualifiersKeepsShadowedTypes(t *testing.T) {
shadowedTypes := map[string]bool{"name": true}
re := regexp.MustCompile(`::public\.`)
input := "ARRAY['a'::public.name, 'b'::public.status, 'c'::public.\"name\"]"
want := "ARRAY['a'::public.name, 'b'::status, 'c'::public.\"name\"]"
if got := StripCastQualifiers(input, re, shadowedTypes, ""); got != want {
t.Errorf("StripCastQualifiers(%q) = %q, want %q", input, got, want)
}
if got := normalizeDefaultValue("'main'::pgschema_tmp_20260101_000000_abcd.name", "public", nil, shadowedTypes); got != "'main'::pgschema_tmp_20260101_000000_abcd.name" {
t.Errorf("temp-schema cast to a shadowed type was stripped: %q", got)
}
}

func TestNormalizeDefaultValueTypedNullOfShadowedQuotedType(t *testing.T) {
shadowedTypes := map[string]bool{"char": true}
for input, want := range map[string]string{
`NULL::public."char"`: `NULL::public."char"`,
`NULL::"App Data".status`: `NULL::"App Data".status`,
`'NULL::"Status"'::text`: `'NULL::"Status"'`,
`COALESCE(NULL::text, 'x')`: `COALESCE(NULL, 'x')`,
} {
if got := normalizeDefaultValue(input, "public", nil, shadowedTypes); got != want {
t.Errorf("normalizeDefaultValue(%s) = %q, want %q", input, got, want)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE OR REPLACE FUNCTION pick(
p public.name DEFAULT 'main'::public.name
)
RETURNS text
LANGUAGE sql
VOLATILE
AS $$ SELECT p::text
$$;

CREATE OR REPLACE PROCEDURE pick_proc(
IN p public.name DEFAULT 'other'::public.name
)
LANGUAGE sql
AS $$ SELECT 1
$$;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE TYPE name AS ENUM ('main', 'other');

CREATE FUNCTION pick(p public.name DEFAULT 'main') RETURNS text
LANGUAGE sql AS $$ SELECT p::text $$;

CREATE PROCEDURE pick_proc(p public.name DEFAULT 'other')
LANGUAGE sql AS $$ SELECT 1 $$;

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CREATE TYPE name AS ENUM ('main', 'other');
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"version": "1.0.0",
"pgschema_version": "2.0.0",
"created_at": "1970-01-01T00:00:00Z",
"source_fingerprint": {
"hash": "6696beb1e1da58a117b6a8fe773e0c111ae1a411ac11a84b0e6ffc6cce56a08e"
},
"groups": [
{
"steps": [
{
"sql": "CREATE OR REPLACE FUNCTION pick(\n p public.name DEFAULT 'main'::public.name\n)\nRETURNS text\nLANGUAGE sql\nVOLATILE\nAS $$ SELECT p::text\n$$;",
"type": "function",
"operation": "create",
"path": "public.pick"
},
{
"sql": "CREATE OR REPLACE PROCEDURE pick_proc(\n IN p public.name DEFAULT 'other'::public.name\n)\nLANGUAGE sql\nAS $$ SELECT 1 \n$$;",
"type": "procedure",
"operation": "create",
"path": "public.pick_proc"
}
]
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE OR REPLACE FUNCTION pick(
p public.name DEFAULT 'main'::public.name
)
RETURNS text
LANGUAGE sql
VOLATILE
AS $$ SELECT p::text
$$;

CREATE OR REPLACE PROCEDURE pick_proc(
IN p public.name DEFAULT 'other'::public.name
)
LANGUAGE sql
AS $$ SELECT 1
$$;
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Plan: 2 to add.

Summary by type:
functions: 1 to add
procedures: 1 to add

Functions:
+ pick

Procedures:
+ pick_proc

DDL to be executed:
--------------------------------------------------

CREATE OR REPLACE FUNCTION pick(
p public.name DEFAULT 'main'::public.name
)
RETURNS text
LANGUAGE sql
VOLATILE
AS $$ SELECT p::text
$$;

CREATE OR REPLACE PROCEDURE pick_proc(
IN p public.name DEFAULT 'other'::public.name
)
LANGUAGE sql
AS $$ SELECT 1
$$;