Skip to content

fix(postgrest-typegen): resolve composite args on foreign tables and matviews - #143

Merged
spydon merged 3 commits into
mainfrom
fix/composite-args-foreign-tables-matviews
Sep 2, 2026
Merged

spydon merged 3 commits into
mainfrom
fix/composite-args-foreign-tables-matviews

Conversation

@spydon

@spydon spydon commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

What

pgTypeToTsType resolved a relation-typed value against tables and views only, never foreignTables or materializedViews. Both of those are generated (foreign tables under Tables, materialized views under Views) and have a Row to point at, so an argument or column typed as one fell through to unknown:

// before
foreign_table_label: { Args: { ft: unknown }; Returns: string }
get_todos_by_matview: { Args: { "": unknown }; ... }

// after
foreign_table_label: {
  Args: { ft: Database["public"]["Tables"]["foreign_table"]["Row"] }
  Returns: string
}
get_todos_by_matview: {
  Args: { "": Database["public"]["Views"]["todos_matview"]["Row"] }
  ...
}

Follow-up to #137, where this was surfaced during review and deliberately left out to keep that change focused.

How

The pgTypeToTsType context gains foreignTables and materializedViews. Both are optional, so the exported signature stays backwards compatible (postgres-meta calls it directly). The context type is named and exported as TypeResolutionContext, matching how GenerateTypescriptOptions is exported.

generateTypescript had the same { types, schemas, tables, views } literal repeated at thirteen call sites. Those collapse into one typeContext built once, which is what keeps the two new collections from being threaded through some call sites and not others.

Resolution order (behaviour change)

Adding two collections exposed a latent ordering bug, so this also changes how same-named relations are disambiguated. Two linked fixes:

1. Schema before kind. The resolver settled the relation kind before the schema: it took the first table-like match by name and only consulted preferredSchema within that bucket. Harmless while just tables and views were consulted, but once foreign tables joined the table-like bucket, a foreign table in an unrelated schema outranked the view the caller actually meant:

view public.foo + foreign table other.foo, resolving "foo" for schema public
  →  Database["other"]['Tables']["foo"]['Row']   // wrong

It now matches on the preferred schema across every relation kind first, then falls back to kind order. This also fixes the pre-existing table-versus-view form of the same bug.

2. The preferred schema has to be right. Fix 1 only helps if preferredSchema is accurate, and function argument and return types never passed one, so the resolver fell back to guessing the schema being generated. That guess then actively misresolved an argument genuinely typed other.foo to a same-named relation in public, where the old kind-first order had got it right by accident. Those six call sites already hold the resolved PostgresType, which carries the schema that owns it, so they now pass it. Columns already did this via type_schema.

Both only affect databases with the same relation or type name in more than one generated schema; the parity goldens are unchanged by either.

Scope of the output change

Only TypeScript is affected. Go, Python, and Swift emit no functions at all, and their goldens are byte-identical.

The parity golden moves by 10 lines, and notably get_todos_by_matview was already in the fixture and already wrong, so this is not only about newly reachable cases.

Testing

Each test below was verified to fail without its corresponding fix:

  • Foreign table and materialized view arguments resolve to their Row rather than unknown.
  • Resolution order pins schema-before-kind in both directions.
  • A function argument resolves in the schema that owns its type, end to end through generateTypescript so the call-site wiring is covered, not just the resolver.
  • New fixture function todos_matview_label(mv public.todos_matview) pins the materialized view path through the parity golden. The foreign table path was already pinned by foreign_table_label, added in fix(postgrest-typegen): match computed fields by argument type, not name #137.
  • Added a baseForeignTable builder to test/generation/fixtures.ts, matching the existing baseView / baseMaterializedView pattern.

Full suite against a real database: 129 pass, 0 fail, parity gate included. check-types, oxfmt, oxlint, knip, and build all clean.

Note for the release

This changes generated output, so the nightly Parity vs. real postgres-meta job stays red until a release ships and postgres-meta bumps its lockfile and regenerates the inline snapshots in test/server/typegen.ts. Same situation as #137, and the two can be handled in one postgres-meta pull request.

…matviews

pgTypeToTsType resolved a relation-typed value against tables and views only, so a value typed as a foreign table or as a materialized view fell through to unknown. Both are generated (foreign tables under Tables, materialized views under Views) and have a Row to point at, so the lookups now include them.

The option bag gains foreignTables and materializedViews as optional fields, keeping the exported signature backwards compatible, and the eight identical inline context literals inside generateTypescript collapse into one shared object so the collections cannot drift apart again.
@spydon
spydon requested a review from a team as a code owner September 2, 2026 11:34
@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: 0f06d48c-097a-4006-a3fc-edd2f718275a


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…re kind

Review of the previous commit turned up a regression it introduced. The resolver settled the relation kind before the schema, so once foreign tables joined the table-like bucket a foreign table in an unrelated schema outranked the view in the schema the caller actually meant:

  before: Database["public"]['Views']["foo"]['Row']
  after:  Database["other"]['Tables']["foo"]['Row']

Match on the preferred schema across every relation kind first, then fall back to kind order. This also fixes the pre-existing table-versus-view form of the same bug, which was unreachable in practice until now.

Two smaller things from the same pass: pgTypeToTsType takes the context as one value rather than destructuring it in the signature, so the array-element recursion forwards it directly instead of rebuilding a literal that a later edit could silently drop a field from, and the relation lookup no longer spreads both collections into a throwaway array on every call.
…schema

A second review pass on the previous two commits turned up a worse case of the same root cause. Making the preferred schema decide before the relation kind only helps if the preferred schema is right, and function argument and return types never passed one, so the resolver fell back to guessing the schema being generated. That guess now actively misresolved an argument genuinely typed other.foo to a same-named relation in public, where the old kind-first order had got it right by accident.

Those six call sites already hold the resolved PostgresType, which carries the schema that owns it, so they pass it. The guess becomes an exact match and the preferred-schema rule is sound rather than amplifying a bad signal. No effect on the parity goldens, which have no cross-schema name collisions.

Also export TypeResolutionContext. Naming the parameter type in the previous commit left the exported pgTypeToTsType signature referring to a type consumers cannot name, where it used to be an inline literal; GenerateTypescriptOptions is exported for the same reason.
@spydon
spydon merged commit e422eb7 into main Sep 2, 2026
6 checks passed
@spydon
spydon deleted the fix/composite-args-foreign-tables-matviews branch September 2, 2026 13:56
spydon added a commit that referenced this pull request Sep 3, 2026
…backs (#144)

Closes SDK-1720.

## What

Four branches of the TypeScript generator produced real, user-visible
output that no test asserted. Tests only, no source or golden changes.

**Three are one theme: a type owned by a schema that is not being
generated.** A column can reference an enum, a composite type, or a
relation living in a schema the caller did not ask for. Emitting
`Database["other"][...]` there would dangle, since no `other` key is
written, so each kind degrades instead:

| Referenced kind | Fallback | Why |
| --- | --- | --- |
| enum | inlines its variants, `"happy" \| "sad"` | the values travel
with the type, so nothing is lost |
| composite type | `unknown` | its shape lives in the schema that was
skipped |
| relation | `unknown` | same |

**The fourth is unrelated but found the same way:** a non-updatable
column on a writable view has to be spelled `?: never` in `Update`, so
writing one is a type error rather than a runtime rejection. The
`Insert` side and both table equivalents were already covered; only the
view `Update` path was not.

## Every assertion is mutation-verified

Each test was checked by inverting the branch it targets and confirming
the test fails. That was not paranoia here:

> Bun's coverage stopped reporting line 897 as uncovered **merely
because an unrelated test was added**, while mutating that line still
broke nothing. It attributes the four identical `?: never` lines
unreliably.

So the coverage delta below is reported for context, not as the
evidence. Mutation testing is the evidence.

```
before  src/generation/typescript.ts   97.50% funcs   98.14% lines
after   src/generation/typescript.ts   98.75% funcs   98.88% lines
```

Of the three lines still listed as uncovered, `55-59` is the `oxfmt`
failure throw, `304-305` is one arm of the PostgREST-resolvability
filter, and `469` is the `unknown` fallback when a function's return
type id misses. Those are follow-up material, not part of this change.

## Testing

131 pass, 0 fail against a real database, parity gate included.
`check-types`, `oxfmt`, `oxlint`, `knip`, and `build` all clean. Goldens
untouched, as expected for a test-only change.

## Context

Came out of an audit prompted by #143, which shipped a resolver whose
`unknown` branch had no test. Sibling ticket SDK-1721 covers the Swift
generator's scalar mapping table, where `Bool`, `Int16`, `Float`, and
`Double` are similarly unexercised.
spydon pushed a commit that referenced this pull request Sep 15, 2026
🤖 I have created a release *beep* *boop*
---


##
[0.2.2](postgrest-typegen-v0.2.1...postgrest-typegen-v0.2.2)
(2026-09-15)


### Bug Fixes

* **postgrest-typegen:** order generated output with a fixed collation
([#181](#181))
([af7f8e8](af7f8e8))
* **postgrest-typegen:** resolve composite args on foreign tables and
matviews ([#143](#143))
([e422eb7](e422eb7))
* **postgrest-typegen:** update-only trigger views, PG18 virtual
generated columns, legacy metadata compatibility
([#128](#128))
([50661bd](50661bd))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: supabase-releaser[bot] <223506987+supabase-releaser[bot]@users.noreply.github.com>
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.

2 participants