Skip to content

fix: keep schema qualifier on routine types shadowed by pg_catalog (#701) - #727

Merged
tianzhou merged 4 commits into
mainfrom
fix/issue-701-shadowed-type-qualifier
Nov 29, 2026
Merged

tianzhou merged 4 commits into
mainfrom
fix/issue-701-shadowed-type-qualifier

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #701. A user type that shares its name with a pg_catalog type (e.g. the row type of CREATE TABLE name) needs its schema qualifier. pg_catalog is always searched first, so nm public.name stripped to nm name replays as pg_catalog.name. pgschema stripped same-schema qualifiers unconditionally in four places. Each one now keeps the qualifier for these names:

  • Inspector: the new buildShadowedTypes records type names in the target/managed schema that pg_catalog also has, in Metadata.ShadowedTypes. stripSameSchemaPrefix keeps the qualifier for those names. That covers parameters, RETURNS, SETOF, arrays and TABLE(...) columns.
  • Normalize: stripSchemaFromReturnType / stripSchemaPrefix skip shadowed names (ir.IsShadowedTypeName).
  • Diff: function and procedure DDL render types through stripTypeSchemaPrefix, using the union of both IRs' ShadowedTypes.
  • Desired state (embedded and external plan DB): before stripSchemaQualifications, qualifyShadowedTypeReferences rewrites public.X to "<tmp>".X for each object the SQL creates whose name is a pg_catalog type. Without this, public.name became bare name in the temp schema and bound to pg_catalog.name, so the plan said "No changes".
  • Plan: normalizeSchemaNames now also maps the temp schema in the Functions/Procedures map keys, because a qualified argument type is part of the key (nc_core(pgschema_tmp_….name)).

Built-in references such as nc_builtin(n name) RETURNS name stay unqualified.

Tests

  • Dump test issue_701_shadowed_type_param covers parameters, return types, SETOF, arrays, TABLE(...), procedures and the built-in name type.
  • Diff/plan test create_function/issue_701_shadowed_type_param checks two things. Moving from nm name to nm public.name drops and recreates the function. Applying the same desired state a second time plans no changes.
  • New unit test TestQualifyShadowedTypeReferences.
  • Ran locally: ./ir, ./internal/postgres, ./internal/diff, ./cmd/dump, ./cmd/plan, and TestPlanAndApply for create_function/, create_procedure/, create_aggregate/, create_type/, dependency/ and privilege/.

Link to Devin session: https://app.devin.ai/sessions/2160d3f08fd1454bb91db03645ac0427
Open in Devin Desktop: https://app.devin.ai/desktop/session/2160d3f08fd1454bb91db03645ac0427?variant=devin
Requested by: @tianzhou


👀 1 finding for you to triage · Follow Devin's work

Devin Review

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@greptile-apps

greptile-apps Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5 · Fix the two desired-state rewrite failures before merging.RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The change reaches routine dumps, migrations, and plan comparisons.

Fix the two desired-state rewrite failures before merging.

Findings

  1. P1 Column aliases get rewritten ▶
  2. P1 Created table names get lost ▶

Summary

Keeps schema qualifiers on routine types whose names also exist in pg_catalog.

  • Routine signatures keep qualifiers when their types share a built-in name.
  • Plan comparisons keep shadowed types in the temporary schema.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Desired SQL] --> B[Find created names shared with pg_catalog]
  B --> C[Point matching qualifiers at temporary schema]
  C --> D[Strip remaining target schema qualifiers]
  D --> E[External provider extracts created names again]
  E --> F[Rewrite selected function body references]
  F --> G[Apply SQL and inspect]
Loading

Reviews (1) · Last reviewed commit: "fix: keep schema qualifier on routine ty..." · Reviewed by Greptile

Comment on lines +271 to +275
result.WriteString(mapCodePreservingStrings(seg.text, func(code string) string {
code = rewrite(sr.re1, code, 1, quoted)
code = rewrite(sr.re2, code, 1, quoted)
code = rewrite(sr.re3, code, 2, unquoted)
return rewrite(sr.re4, code, 2, unquoted)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Column aliases get rewritten

qualifyShadowedTypeReferences also changes column references whose table alias matches the managed schema. With CREATE TABLE public.name(id int), the valid view query SELECT public.name FROM (SELECT 1 AS name) public becomes SELECT "tmp".name FROM (SELECT 1 AS name) public. There is no table alias named tmp, so planning fails. The old stripping pass produced the valid unqualified column name. Keep column references out of this rewrite.

Comment on lines +246 to +247
schemaAgnosticSQL := qualifyShadowedTypeReferences(sql, schema, ed.tempSchema, catalogTypes)
schemaAgnosticSQL = stripSchemaQualifications(schemaAgnosticSQL, schema)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Created table names get lost

The new pass turns CREATE TABLE public.name into CREATE TABLE "<tmp>".name. The later extractCreatedObjectNames call reads only the first identifier after TABLE, so it records the temporary schema instead of name. This makes qualifyFunctionBodiesWithTempSchema leave public.name unchanged inside function bodies.

If the external plan database lacks public.name, an immutable SQL function reading that table can fail when a materialized view calls it during planning. The table exists only in the temporary schema. Collect the created names before adding qualifiers, or teach the extractor to read qualified names.

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 4 findings. Devin fixed 3 findings; 1 finding is left for you to triage below.

Fixed by Devin (3)
  • Broken routine references in external plans — createdObjectRe now skips an optional schema qualifier, so CREATE TABLE .name records 'name'. Unit test added.
  • Premature revokes block function migrations — normalizeSchemaNames now maps Function.IdentityArguments from the temp schema, so functionPrivilegeObjectName matches the privilege ObjectName; unit test added.
  • Restricted overload retains public execution — Privilege signatures (inspector identity args, privilege object names, normalizePrivilegeObjectName) now keep the qualifier on shadowed types; plan maps it from the temp schema. Regression: overload nc_core(name)/nc_core(public.name) with REVOKE in dump and plan fixtures.

View findings in Devin Review · Follow Devin's work

Devin Review

Comment thread internal/diff/function.go
// Add parameter name and type
// Strip schema prefix from data type if it matches the target schema
dataType := stripSchemaPrefixMode(param.DataType, targetSchema, qualifySchema)
dataType := stripTypeSchemaPrefix(param.DataType, targetSchema, qualifySchema, shadowedTypes)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Wrong type casts in routine defaults

For an enum parameter of type public.name, formatFunctionParameter preserves the declaration but emits 'main'::name as the default. normalizeDefaultValue strips the cast qualifier for functions and procedures. PostgreSQL rejects the built-in name default for the enum parameter.

Devin left this for you to triage: Real but narrow: needs an enum/domain named like a pg_catalog type used as a routine parameter with a default; the '::public.name' cast is stripped by normalizeDefaultValue and the pgschema_tmp_ cast regex. Recommend a follow-up that threads shadowedTypes into default-value normalization rather than widening this PR.

Learn more

The parameter declaration and its default expression travel through different normalization paths. normalizeFunction and normalizeProcedure both call normalizeDefaultValue, which unconditionally strips same-schema qualifiers from casts. normalizeSchemaNames also strips qualifiers from parameter defaults when planning, and function rendering performs another cast-stripping pass. The declaration now preserves its enum type while the default still resolves to the built-in type.

Example: Declare CREATE TYPE public.name AS ENUM ('main') and a function with n public.name DEFAULT 'main'::public.name. The generated declaration has n public.name DEFAULT 'main'::name. PostgreSQL resolves the default cast to pg_catalog.name, which is not implicitly coercible to the enum.

Recommended fix: Preserve casts to shadowed types through inspection, temporary-to-target remapping, and SQL rendering for both functions and procedures. Verify replay and a subsequent no-op plan for a routine with a typed enum default.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@tianzhou
tianzhou merged commit 3034748 into main Nov 29, 2026
2 checks passed

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 finding. It is left for you to triage in Devin Review.

View findings in Devin Review · Follow Devin's work

Devin Review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Function parameter typed as a user type that shadows a pg_catalog type (public.name) is dumped unqualified and replayed as the built-in type

1 participant