Skip to content

feat(postgrest-typegen): add PostgREST introspection engine (+ transitional TS/Go/Python/Swift generators) - #94

Merged
spydon merged 17 commits into
mainfrom
feat/postgrest-typegen
Aug 28, 2026
Merged

spydon merged 17 commits into
mainfrom
feat/postgrest-typegen

Conversation

@spydon

@spydon spydon commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements SDK-1617: a postgrest-typegen package inside supabase/sdk, owned by the SDK team, that produces the intermediate representation (GeneratorMetadata) used for PostgREST type generation.

Huge thanks to Andrew Valleteau (@avallete) for the original extraction work in supabase/pg-toolbelt#302 — this PR ports that engine (introspection + TypeScript/Go/Python/Swift generators) wholesale rather than reinventing it. The credit for the hard part, splitting introspection from generation behind the GeneratorMetadata contract and the byte-parity test harness, is his.

The CI workflow for this package is stacked on top, in #95.

End-state architecture

  1. postgrest-typegen (permanent): owns introspection and the GeneratorMetadata contract, including the JSON boundary itself (serializeGeneratorMetadata + a published JSON Schema, generatorMetadataJsonSchema).
  2. Every new language's generator lives in its own SDK repo (permanent): consumes postgrest-typegen's JSON output directly. Starting with Dart: dart run supabase_typegen inside supabase-flutter (supabase-flutter#1634/#1635). Not inside postgrest-typegen.
  3. supabase gen types --lang <language> (CLI): imports @supabase/postgrest-typegen directly, in-process — no postgres-meta involved in this path at all. For a new language, pipes the JSON into that language's own SDK-repo generator. TypeScript/Go/Python/Swift are on this same end state too — they're just not there yet (see the plan below).
  4. postgres-meta's hosted service is a separate consumer. Its /generators/* HTTP routes (Studio's dashboard, the Management API's hosted --linked path with no direct DB connection) aren't reached by point 3. postgres-meta cuts over to calling postgrest-typegen internally instead of its own embedded templates, so that path stays byte-parity without duplicating generator logic.

Plan to get there (this PR is Phase 1 only)

Flagged during review: it's easy to misread this PR as "postgrest-typegen is the shared home for all four generators, permanently," and to conflate "wire the CLI to the package" with "cut postgres-meta's hosted routes over to it" as if they were the same step. Neither is true — it's sequenced into five phases:

  1. Phase 1 — this PR. Ports postgrest-typegen from feat(auth): Add spec for AuthClient.signOut() #302 as-is, which includes byte-parity TypeScript/Go/Python/Swift generators inside the package. Kept here transitionally, purely so supabase gen types keeps working with zero behavior change. Not the target architecture for those four — it exists so Phases 2/3 have something to cut over to.
  2. Phase 2 — wire the CLI to postgrest-typegen directly (not started, no ticket yet). supabase gen types adds @supabase/postgrest-typegen as a dependency and calls it in-process, against the user's own DB connection. Doesn't touch postgres-meta at all — no Docker container needed just to generate types. Independent of Phase 3; doesn't need to wait for it.
  3. Phase 3 — postgres-meta hosted-route cutover (not started, no ticket yet). postgres-meta deletes its own embedded templates and calls into postgrest-typegen for all four languages instead, so its /generators/* HTTP routes stay byte-parity. Hard gate: no-op for existing consumers of that endpoint.
  4. Phase 4 — new languages (in progress, parallel to this PR). Dart's supabase_typegen already follows the target pattern. Every future new language follows the same pattern, never Phase 1's.
  5. Phase 5 — decided, tracked in SDK-1641, not yet scheduled. TS/Go/Python/Swift generation moves out of postgrest-typegen into per-SDK repos too, matching Phase 4 — postgrest-typegen is not a permanent home for any generator, only for introspection and the JSON contract. Sequenced after Phase 3 settles, so there's a stable byte-parity baseline to migrate each language off of one at a time.

SDK-1617, SDK-1641, and this package's own CLAUDE.md/README.md all say this explicitly now, so the next reader (human or agent) doesn't have to re-derive it from the diff.

What changed vs. #302

Per SDK-1617, this package lives in supabase/sdk (not a standalone repo), and owns JSON serialization of the contract itself:

  • GeneratorMetadata.version — a version field on the serialized contract, so out-of-process consumers (a generator in another SDK repo, fed JSON over a process boundary) can detect a shape change instead of only failing at read time.
  • type_schema on columns — schema-qualifies the enum/composite/domain type in PostgresColumn.format, so two schemas defining a same-named enum no longer resolve ambiguously. Verified against a real database (see test plan).
  • primaryKeys — restored as a flat, top-level collection (PostgresPrimaryKey[]) with its own introspection query, since feat(auth): Add spec for AuthClient.signOut() #302 dropped it entirely on the grounds that no existing template used it. Planned Dart features (upsert with onConflict defaults, FK relationship getters) need it.
  • generatorMetadataJsonSchema + serializeGeneratorMetadata — postgrest-typegen now owns the JSON boundary. A generator living in its own SDK repo (e.g. a future supabase_typegen for Dart) consumes ready-made JSON and a published JSON Schema, rather than each consumer serializing the contract its own way.

These directly address the three review comments left on #302.

Also picked up since #302 was drafted

  • fix(typegen): only collapse ROWS 1 return types when SetofOptions is emitted (postgres-meta#1096, @mandarini) — ported into the TypeScript generator. Verified it's a no-op against this package's own fixture DB (every ROWS 1 function there resolves a returnTableName), so parity holds.
  • fix: avoid quadratic relationship lookup in typescript generator (postgres-meta#1101) — ported (Map-based lookup instead of a per-call linear scan).

Dependencies

Bumped to current releases (TypeScript 7, arktype, testcontainers, oxlint/oxfmt) — except prettier, kept pinned exact to 3.5.3, matching postgres-meta's own currently-resolved version. I initially bumped it to latest too; the Docker-backed parity suite caught that this silently reformats the TypeScript generator's output and breaks real byte-parity with postgres-meta's CLI, not just this package's own snapshots. Reverted, documented the reasoning in CLAUDE.md so it doesn't happen again on the next dependency bump.

Review passes

Three rounds of review after the initial draft, each caught real issues:

Round 1 (after first running the Docker-backed suites, not run in the initial draft):

  • Byte-parity regression from the prettier bump above, caught by test/parity/parity.test.ts.
  • Missing privilege filter on PRIMARY_KEYS_SQL: in postgres-meta, primary key data is a LEFT JOIN inside TABLES_SQL, so it inherits that query's pg_has_role/has_table_privilege filter for free. As a new standalone query it had no such filter, so it could return primary key metadata for tables the querying role can't otherwise see. Added the matching filter.
  • Added test coverage that was missing for the new surface: generatorMetadataJsonSchema, serializeGeneratorMetadata, and primaryKeys ordering in sortGeneratorMetadata.

Round 2:

  • type_schema and primaryKeys, the actual point of this ticket, had no assertions against a real database, only hand-written fixture data. Extended the Docker-backed integration suite to cover both.
  • Running the full check sequence from a clean checkout (no cached node_modules/dist) surfaced a formatting issue a warm local environment had masked.
  • Root-level README.md/CLAUDE.md still described this package as "an empty scaffold" post-implementation.
  • PostgresPrimaryKey landed out of the alphabetical ordering the rest of types.ts follows.

Round 3 (architecture question raised in review, see above): the PR/ticket read as "postgrest-typegen is the permanent home for all four generators," contradicting SDK-1617's "every language owns its own generator" line. Resolved as a documented transitional decision rather than silently picking a side; opened SDK-1641 to track the actual decision.

Round 4: mandarini flagged two more real issues, both fixed:

  • pgTypeToTsType resolved ambiguous enum/composite/table/view references by the table's own schema, never actually consulting type_schema — meaning the exact ambiguity bug type_schema was added to fix was still live in the TypeScript generator's real output. Added a regression test with a genuine cross-schema collision; confirmed it fails without the fix and passes with it.
  • package.json's exports maps listed "types" after "import"/"require", which only resolves today via TypeScript's legacy same-name .d.ts fallback and can break under strict resolvers or attw/publint. Reordered "types" first in each conditional block.

Also documented, rather than mechanically fixed, a third: the parity gate's committed goldens are maintained by regenerating them from this package itself, so an intentional generator change and its golden update land in the same PR — the gate then only proves self-consistency, not real agreement with postgres-meta. This led directly to the CI job below.

Nightly job: parity vs. real postgres-meta (packages/postgrest-typegen/scripts/{load-fixtures,print-generated}.ts)

Boots a shared Postgres, loads the same fixture schema test/parity/ uses, runs postgres-meta's real npm run gen:types:* against it, runs this package's own generators against the same DB, and diffs the two. Comparison is order-independent (sorted declaration blocks, not raw bytes) — confirmed by test-running this against postgres-meta's actual master branch, both locally and via workflow_dispatch in this PR's own CI: TypeScript and Swift matched byte-for-byte; Go and Python matched in content but not raw declaration order, which is sortGeneratorMetadata's canonical semantic ordering (already documented as a deliberate improvement over postgres-meta's environment-dependent heap order) rather than a regression. Verified the order-independent comparison still catches a real injected difference before relying on it. Nightly + manual dispatch only, never on push/pull_request, since postgres-meta can drift for reasons unrelated to any change here — same pattern as capability-matrix's existing "Tier 2" external-reference checks.

Known gaps (follow-up)

  • The four existing generators (TS/Go/Python/Swift) are otherwise an unmodified, byte-parity port — the ~19 pre-existing correctness issues Andrew catalogued on feat(auth): Add spec for AuthClient.signOut() #302 (unescaped enum labels, generated columns in Insert, missing foreign tables in Go/Python, etc.) are still deferred, same rationale as feat(auth): Add spec for AuthClient.signOut() #302: fix upstream in postgres-meta first, then re-port.
  • SDK-1641: whether TS/Go/Python/Swift generation eventually moves out of this package.

Test plan

  • bun run check-types
  • bun run format-and-lint
  • bun run knip
  • bun run build
  • bun test — 91 tests passing, run from a clean checkout, including the Docker-backed introspection + parity suites (byte-parity gate against postgres-meta's actual output, and real-database assertions on type_schema/primaryKeys)

Ports the introspection and generation engine from Andrew Valleteau's
draft supabase/pg-toolbelt#302, with the SQL-based introspector and
TypeScript/Go/Python/Swift generators split by a shared GeneratorMetadata
contract.

On top of the port:
- GeneratorMetadata now carries a version field, a schema-qualified
  type_schema on columns, and primary key metadata, addressing review
  feedback left on #302.
- postgrest-typegen owns JSON serialization of the contract and exposes
  its JSON Schema, so out-of-process generators (e.g. a future Dart
  generator) consume ready-made JSON instead of each doing this
  themselves.
- Dependencies bumped to current releases (TypeScript 7, prettier,
  arktype, testcontainers, oxlint/oxfmt), with snapshots and fixtures
  regenerated accordingly.
@coderabbitai

coderabbitai Bot commented Aug 26, 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: Pro Plus

Run ID: f44c0926-8258-425e-84b5-5dc86de20a51


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.

spydon added 3 commits August 26, 2026 16:56
Full review pass after running the Docker-backed integration/parity
suite for the first time:

- Revert prettier from 3.9.6 back to 3.5.3 (postgres-meta's actual
  resolved version). The bump silently broke real byte-parity with
  postgres-meta's CLI output, only caught by the parity test; other
  dependencies were bumped safely since they don't affect generator
  output byte-for-byte.
- PRIMARY_KEYS_SQL was missing the relkind/privilege filter that the
  original postgres-meta subquery inherited for free by living inside
  TABLES_SQL. Standalone, it could leak primary key metadata for
  tables the querying role can't see. Added the matching filter.
- Add test coverage for generatorMetadataJsonSchema,
  serializeGeneratorMetadata, and primaryKeys ordering, none of which
  had any tests.
Runs check-types, format-and-lint, knip, build, and the full test suite
(including the Docker-backed introspection/parity suites, which work
against GitHub Actions' default Docker daemon with no extra setup) on
PRs and pushes to main touching the package.

bun is installed via the official install script rather than a
third-party setup action, since the repo's Actions policy only
allows GitHub-owned/verified actions by default.
@spydon spydon mentioned this pull request Aug 26, 2026
1 of 2 tasks
spydon added 4 commits August 27, 2026 09:50
…real DB

Review pass found these two new GeneratorMetadata fields, the actual
point of this ticket, had no assertions in the Docker-backed
introspection suite: only fixture-based unit tests exercised them,
never real introspection output. Extends the existing users-columns
snapshot with type_schema and adds a primary-keys describe block.

Also caught by re-running the full CI sequence from a clean checkout
(no cached node_modules/dist): oxfmt flagged formatting on the edited
test file that a warm local environment had masked.
…scaffold

Both still described the package as an empty scaffold after this PR
implemented it.
…yKey

types.ts orders every Postgres* schema alphabetically; PostgresPrimaryKey
landed between ForeignTable and Function instead of between
MaterializedView and Relationship.
The four bundled generators (TS/Go/Python/Swift) read as this
package's permanent architecture, contradicting SDK-1617's decision
that every language's generator lives in its own SDK repo. Document
explicitly that keeping them here is a deliberate transition (mirrors
pg-toolbelt#302, lets postgres-meta cut over first), not the pattern
for new languages, and that whether they move out later is tracked
separately in SDK-1641.
@spydon spydon changed the title feat(postgrest-typegen): add PostgREST type generation engine feat(postgrest-typegen): add PostgREST introspection engine (+ transitional TS/Go/Python/Swift generators) Aug 27, 2026
…t open

Corrects wording that framed moving TS/Go/Python/Swift generators out
to per-SDK repos as an undecided question. It's decided; only the
scheduling (after the postgres-meta cutover settles) is open.
@spydon
spydon marked this pull request as ready for review August 27, 2026 11:01
@spydon
spydon requested a review from a team as a code owner August 27, 2026 11:01
## Summary

Stacked on #94. Adds the CI workflow for the new `postgrest-typegen`
package.

Runs `check-types`, `format-and-lint`, `knip`, `build`, and the full
test suite (including the Docker-backed introspection/parity suites,
which work against GitHub Actions' default Docker daemon with no extra
setup) on PRs and pushes to `main` that touch the package.

`bun` is installed via the official install script rather than a
third-party setup action, since the repo's Actions policy only allows
GitHub-owned/verified actions by default (see the SHA-pinned
`dart-lang/setup-dart` allowlist precedent for what a third-party
exception looks like).

## Test plan

- [x] `actionlint` passes on the new workflow file
- [ ] Full CI run green (verifying)

@avallete avallete left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM ! Thank's for your work here that's great !

Addresses review from avallete on #94. The comment claimed the
generator "sorts every collection internally, so it is
order-insensitive", which is stale and self-contradictory with the
very next clause telling callers to pre-sort. It doesn't re-sort;
callers must pass input through sortGeneratorMetadata first. Only the
cross-collection merge-sorts (tables+foreign tables,
views+materialized views per schema) stay here, since sortGeneratorMetadata
can't express those.
@mandarini

Copy link
Copy Markdown
Contributor

@spydon it seems that pgTypeToTsType resolves enum references by the table's own schema, not by the column's type_schema. So type_schema is introspected and carried through GeneratorMetadata but never actually consumed, I believe. For example table in schema tenant has a column referencing enum public.status. schema tenant also defines its own status enum. Generated output will reference tenant.status instead of public.status, silently wrong. Per the PR description the GeneratorMetadata carries the fix but the TS generator doesn't use it, I believe. Maybe we should wire pgTypeToTsType to resolve by type_schema instead of the table's schema?

Comment thread packages/postgrest-typegen/package.json Resolved
spydon added 6 commits August 27, 2026 15:08
…e_schema

Addresses review from mandarini on #94
(#94 (comment)).
pgTypeToTsType resolved ambiguous type names by preferring a match in
the current table's own schema, never consulting the column's
type_schema. A table in schema `tenant` referencing `public.status`,
where `tenant` also defines its own `status` enum, would silently
resolve to `tenant.status` instead. type_schema was introspected and
carried through GeneratorMetadata but never actually consumed by the
generator, defeating the point of adding it.

pgTypeToTsType now accepts an optional typeSchema override, used
instead of the table's own schema when resolving enums, composites,
table row types, and view row types. Falls back to the previous
behavior when not provided (function args/return types have no
type_schema-equivalent field yet). No byte-parity impact: the fixture
DB has no colliding type names, so existing snapshots and the
postgres-meta parity gate are unaffected.
Addresses review from mandarini on #94
(#94 (comment)).
Listing "types" after "import"/"require" in a conditional exports
block only resolves today via TypeScript's legacy same-name .d.ts
fallback, and can break under strict resolvers or attw/publint
checks. "types" must be the first matching condition in each block.
Addresses review from mandarini on #94
(#94 (comment)).
The docblock asserted the goldens are byte-identical to postgres-meta's
CLI output without noting how they're actually maintained: the
established workflow for an intentional generator change is to
regenerate the goldens from this package itself, in the same PR as the
change. At that point the gate only proves the generator agrees with
its own golden, not with postgres-meta's real current output, and
can't catch a regression in that same change. Documents this
explicitly and recommends periodically re-verifying against a real
postgres-meta run instead of trusting a self-regenerated golden alone.
…-meta

Addresses review from mandarini on #94
(#94 (comment)):
the committed parity goldens are maintained by regenerating them from
this package itself, so the existing parity test only proves
self-consistency, not agreement with postgres-meta's actual current
output.

Adds a nightly (+ workflow_dispatch) job that boots a shared Postgres,
loads the same fixture schema as test/parity/, runs postgres-meta's
real `gen:types:*` scripts against it, runs this package's own
generators against it, and diffs the two. Not run on push/pull_request:
postgres-meta can drift for reasons unrelated to any change here,
matching the existing nightly-only pattern used for capability-matrix's
external reference checks.

Comparison is order-independent (sorted declaration blocks, not raw
bytes): sortGeneratorMetadata canonicalizes collection order across
all four generators as a deliberate improvement over postgres-meta's
environment-dependent heap order, confirmed by test-running this
against postgres-meta's actual master branch locally — TypeScript and
Swift matched byte-for-byte, Go and Python matched in content but not
raw order (the expected, already-documented divergence), and the
order-independent comparison correctly resolves that while still
catching a real injected difference in manual testing.
@spydon
spydon merged commit 3d63578 into main Aug 28, 2026
4 checks passed
@spydon
spydon deleted the feat/postgrest-typegen branch August 28, 2026 11:20
spydon pushed a commit that referenced this pull request Aug 28, 2026
🤖 I have created a release *beep* *boop*
---


## [1.5.0](v1.4.0...v1.5.0)
(2026-08-28)


### Features

* **postgrest-typegen:** add PostgREST introspection engine (+
transitional TS/Go/Python/Swift generators)
([#94](#94))
([3d63578](3d63578))


### Bug Fixes

* **ci:** unquoted colon made compliance action manifests invalid YAML
([#109](#109))
([fd53fdb](fd53fdb))

---
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>
@supabase-releaser supabase-releaser Bot mentioned this pull request Aug 28, 2026
spydon pushed a commit that referenced this pull request Aug 28, 2026
🤖 I have created a release *beep* *boop*
---


<details><summary>capability-matrix: 1.6.0</summary>

##
[1.6.0](capability-matrix-v1.5.0...capability-matrix-v1.6.0)
(2026-08-28)


### Features

* Add spec for single row database modifiers
([#99](#99))
([b39cce3](b39cce3))


### Bug Fixes

* Specs ([#100](#100))
([de17547](de17547))


### Miscellaneous Chores

* release 1.3.0 ([#97](#97))
([ee2ef6e](ee2ef6e))
</details>

<details><summary>postgrest-typegen: 0.1.0</summary>

## 0.1.0 (2026-08-28)


### Features

* **postgrest-typegen:** add PostgREST introspection engine (+
transitional TS/Go/Python/Swift generators)
([#94](#94))
([3d63578](3d63578))


### Miscellaneous Chores

* release 1.3.0 ([#97](#97))
([ee2ef6e](ee2ef6e))
</details>

---
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.

3 participants