Repository navigation
feat(postgrest-typegen): add PostgREST introspection engine (+ transitional TS/Go/Python/Swift generators) - #94
Conversation
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.
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars. ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 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. Comment |
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.
This reverts commit ad93385.
…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.
…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.
## 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
left a comment
There was a problem hiding this comment.
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.
|
@spydon it seems that |
…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.
🤖 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>
🤖 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>
Summary
Implements SDK-1617: a
postgrest-typegenpackage insidesupabase/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
GeneratorMetadatacontract and the byte-parity test harness, is his.The CI workflow for this package is stacked on top, in #95.
End-state architecture
postgrest-typegen(permanent): owns introspection and theGeneratorMetadatacontract, including the JSON boundary itself (serializeGeneratorMetadata+ a published JSON Schema,generatorMetadataJsonSchema).postgrest-typegen's JSON output directly. Starting with Dart:dart run supabase_typegeninsidesupabase-flutter(supabase-flutter#1634/#1635). Not insidepostgrest-typegen.supabase gen types --lang <language>(CLI): imports@supabase/postgrest-typegendirectly, 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)./generators/*HTTP routes (Studio's dashboard, the Management API's hosted--linkedpath with no direct DB connection) aren't reached by point 3. postgres-meta cuts over to callingpostgrest-typegeninternally 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:
postgrest-typegenfrom feat(auth): Add spec forAuthClient.signOut()#302 as-is, which includes byte-parity TypeScript/Go/Python/Swift generators inside the package. Kept here transitionally, purely sosupabase gen typeskeeps working with zero behavior change. Not the target architecture for those four — it exists so Phases 2/3 have something to cut over to.postgrest-typegendirectly (not started, no ticket yet).supabase gen typesadds@supabase/postgrest-typegenas 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.postgrest-typegenfor all four languages instead, so its/generators/*HTTP routes stay byte-parity. Hard gate: no-op for existing consumers of that endpoint.supabase_typegenalready follows the target pattern. Every future new language follows the same pattern, never Phase 1's.postgrest-typegeninto per-SDK repos too, matching Phase 4 —postgrest-typegenis 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.mdall 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_schemaon columns — schema-qualifies the enum/composite/domain type inPostgresColumn.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 forAuthClient.signOut()#302 dropped it entirely on the grounds that no existing template used it. Planned Dart features (upsertwithonConflictdefaults, FK relationship getters) need it.generatorMetadataJsonSchema+serializeGeneratorMetadata—postgrest-typegennow owns the JSON boundary. A generator living in its own SDK repo (e.g. a futuresupabase_typegenfor 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 (everyROWS 1function there resolves areturnTableName), 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 to3.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 inCLAUDE.mdso 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):
test/parity/parity.test.ts.PRIMARY_KEYS_SQL: in postgres-meta, primary key data is aLEFT JOINinsideTABLES_SQL, so it inherits that query'spg_has_role/has_table_privilegefilter 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.generatorMetadataJsonSchema,serializeGeneratorMetadata, andprimaryKeysordering insortGeneratorMetadata.Round 2:
type_schemaandprimaryKeys, 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.node_modules/dist) surfaced a formatting issue a warm local environment had masked.README.md/CLAUDE.mdstill described this package as "an empty scaffold" post-implementation.PostgresPrimaryKeylanded out of the alphabetical ordering the rest oftypes.tsfollows.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:
pgTypeToTsTyperesolved ambiguous enum/composite/table/view references by the table's own schema, never actually consultingtype_schema— meaning the exact ambiguity bugtype_schemawas 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'sexportsmaps listed"types"after"import"/"require", which only resolves today via TypeScript's legacy same-name.d.tsfallback and can break under strict resolvers orattw/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 realnpm 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 actualmasterbranch, both locally and viaworkflow_dispatchin this PR's own CI: TypeScript and Swift matched byte-for-byte; Go and Python matched in content but not raw declaration order, which issortGeneratorMetadata'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)
AuthClient.signOut()#302 (unescaped enum labels, generated columns inInsert, missing foreign tables in Go/Python, etc.) are still deferred, same rationale as feat(auth): Add spec forAuthClient.signOut()#302: fix upstream in postgres-meta first, then re-port.Test plan
bun run check-typesbun run format-and-lintbun run knipbun run buildbun 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 ontype_schema/primaryKeys)