diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1d7780825..eade77086 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -117,6 +117,18 @@ jobs:
runs-on:
group: databricks-ghec-untrusted-runner-group
labels: linux-ubuntu-latest-untrusted-2core-8gb
+ services:
+ postgres:
+ image: postgres:17@sha256:2d2b8998d31037bf721cfdf764d76ba74171b4fab3431b7f72c27c56ddbdf9e3
+ env:
+ POSTGRES_PASSWORD: postgres
+ ports:
+ - 5432:5432
+ options: >-
+ --health-cmd "pg_isready -U postgres"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 10
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
@@ -131,6 +143,8 @@ jobs:
run: pnpm install --frozen-lockfile
- name: Run Tests
run: pnpm test
+ env:
+ APPKIT_TEST_PG_URL: postgres://postgres:postgres@localhost:5432/postgres
playground-integration-test:
name: Playground Integration Tests
diff --git a/.gitignore b/.gitignore
index f29e32849..767735099 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,6 +19,9 @@ coverage
.databricks
+# `appkit db` holds it while a command changes the migration history
+**/config/database/.appkit-db.lock
+
.claude/scheduled_tasks.lock
internal
diff --git a/.oxlintrc.json b/.oxlintrc.json
index a457847df..09492ed41 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -58,6 +58,50 @@
"rules": {
"no-restricted-imports": "off"
}
+ },
+ {
+ "files": ["packages/appkit/src/**"],
+ "rules": {
+ "no-restricted-imports": [
+ "error",
+ {
+ "patterns": [
+ {
+ "group": ["@databricks/sdk-*", "@databricks/sdk-*/**"],
+ "message": "Import the Databricks SDK only through the wrapper in packages/shared/src/workspace-client (modular.ts builds the modular @databricks/sdk-* clients). Add a re-export there if you need a new symbol."
+ },
+ {
+ "group": ["drizzle-kit", "drizzle-kit/**"],
+ "message": "drizzle-kit is an optional dev dependency that deployed apps do not install. Only packages/appkit/src/database/tooling may import it."
+ },
+ {
+ "group": [
+ "**/tooling",
+ "**/tooling/**",
+ "@databricks/appkit/beta/database-tooling"
+ ],
+ "message": "The database tooling may import drizzle-kit, so only the CLI loads it. Runtime code must not import it."
+ }
+ ]
+ }
+ ]
+ }
+ },
+ {
+ "files": ["packages/appkit/src/database/tooling/**"],
+ "rules": {
+ "no-restricted-imports": [
+ "error",
+ {
+ "patterns": [
+ {
+ "group": ["@databricks/sdk-*", "@databricks/sdk-*/**"],
+ "message": "Import the Databricks SDK only through the wrapper in packages/shared/src/workspace-client (modular.ts builds the modular @databricks/sdk-* clients). Add a re-export there if you need a new symbol."
+ }
+ ]
+ }
+ ]
+ }
}
],
"ignorePatterns": [
diff --git a/apps/dev-playground/config/database/schema.ts b/apps/dev-playground/config/database/schema.ts
index b3674026d..8299193b4 100644
--- a/apps/dev-playground/config/database/schema.ts
+++ b/apps/dev-playground/config/database/schema.ts
@@ -1,6 +1,7 @@
// Annotations a reviewer leaves on a saved dashboard, plus an audit trail table
// for them. The operations in server/database/routes/ are the only HTTP access.
-// The DatabasePlugin does not create these tables, so the app expects them to exist.
+// The DatabasePlugin does not create these tables, so the app expects them to
+// exist in public, where they were created before the default schema became app.
import {
defineSchema,
@@ -11,34 +12,37 @@ import {
varchar,
} from "@databricks/appkit/beta";
-export const schema = defineSchema(({ table }) => {
- const boards = table("boards", {
- id: id(),
- slug: varchar(64).notNull().unique(),
- title: text().notNull(),
- created_at: timestamp({ withTimezone: true }).defaultNow().notNull(),
- });
+export const schema = defineSchema(
+ ({ table }) => {
+ const boards = table("boards", {
+ id: id(),
+ slug: varchar(64).notNull().unique(),
+ title: text().notNull(),
+ created_at: timestamp({ withTimezone: true }).defaultNow().notNull(),
+ });
- const notes = table("notes", {
- id: id(),
- board_id: fk(() => boards.id)
- .notNull()
- .onDelete("cascade"),
- author: text().notNull(),
- // Server code needs it to notify the reviewer; no client should see it.
- author_email: text().private(),
- body: text().notNull(),
- created_at: timestamp({ withTimezone: true }).defaultNow().notNull(),
- });
+ const notes = table("notes", {
+ id: id(),
+ board_id: fk(() => boards.id)
+ .notNull()
+ .onDelete("cascade"),
+ author: text().notNull(),
+ // Server code needs it to notify the reviewer; no client should see it.
+ author_email: text().private(),
+ body: text().notNull(),
+ created_at: timestamp({ withTimezone: true }).defaultNow().notNull(),
+ });
- const note_events = table("note_events", {
- id: id(),
- note_id: fk(() => notes.id)
- .notNull()
- .onDelete("cascade"),
- action: varchar(32).notNull(),
- created_at: timestamp({ withTimezone: true }).defaultNow().notNull(),
- });
+ const note_events = table("note_events", {
+ id: id(),
+ note_id: fk(() => notes.id)
+ .notNull()
+ .onDelete("cascade"),
+ action: varchar(32).notNull(),
+ created_at: timestamp({ withTimezone: true }).defaultNow().notNull(),
+ });
- return { boards, notes, note_events };
-});
+ return { boards, notes, note_events };
+ },
+ { schemaName: "public" },
+);
diff --git a/apps/dev-playground/server/testing/database-edges.ts b/apps/dev-playground/server/testing/database-edges.ts
index 0d17ff664..df5df6afa 100644
--- a/apps/dev-playground/server/testing/database-edges.ts
+++ b/apps/dev-playground/server/testing/database-edges.ts
@@ -232,10 +232,15 @@ export function memoryDatabase(schema: Schema): MemoryDatabase {
if (row) remove(table, row);
return row !== undefined;
},
- // Setup runs `select 1`, then reads pg_catalog to confirm that every
- // declared column exists. This database holds exactly the declared ones.
- raw: async (strings) =>
- strings.join("?").includes("pg_catalog")
+ // Setup runs `select 1`, reads whether its role may use the app schema,
+ // then reads pg_catalog to confirm that every declared column exists.
+ // The role may, and this database holds exactly the declared columns.
+ raw: async (strings) => {
+ const sql = strings.join("?");
+ if (sql.includes("has_schema_privilege")) {
+ return [{ owner: "app", current_user: "app", usage: true }];
+ }
+ return sql.includes("pg_catalog")
? tables.flatMap((table) =>
Object.values(table.$columns).map((meta) => ({
table_name: table.$name,
@@ -243,7 +248,8 @@ export function memoryDatabase(schema: Schema): MemoryDatabase {
relation_kind: "r",
})),
)
- : [{ "?column?": 1 }],
+ : [{ "?column?": 1 }];
+ },
// AppKit joins nested transactions itself; one never reaches the edge.
transaction: async () => {
throw new Error("memory database: nested transaction");
diff --git a/bundle-size-baseline.json b/bundle-size-baseline.json
index 9c233b8d1..5b202ed79 100644
--- a/bundle-size-baseline.json
+++ b/bundle-size-baseline.json
@@ -3,25 +3,25 @@
{
"name": "@databricks/appkit",
"tarball": {
- "packed": 1409598,
- "unpacked": 4822638
+ "packed": 1605551,
+ "unpacked": 5476020
},
"dist": {
"total": {
- "raw": 4807205,
- "gzip": 1647276
+ "raw": 5460206,
+ "gzip": 1866593
},
"js": {
- "raw": 1441621,
- "gzip": 512746
+ "raw": 1662583,
+ "gzip": 589547
},
"types": {
- "raw": 493520,
- "gzip": 177925
+ "raw": 509717,
+ "gzip": 185285
},
"maps": {
- "raw": 2861269,
- "gzip": 952787
+ "raw": 3277111,
+ "gzip": 1087943
},
"css": {
"raw": 0,
@@ -31,22 +31,22 @@
"raw": 10795,
"gzip": 3818
},
- "fileCount": 934
+ "fileCount": 1023
},
"entries": [
{
"id": ".",
- "gzip": 123587,
+ "gzip": 123615,
"composition": {
- "initialGzip": 121096,
- "lazyGzip": 2491,
- "totalGzip": 123587,
- "own": 387234,
+ "initialGzip": 121125,
+ "lazyGzip": 2490,
+ "totalGzip": 123615,
+ "own": 387319,
"nodeModules": null,
"chunks": [
{
"label": "index.js",
- "gzip": 116420,
+ "gzip": 116449,
"kind": "initial"
},
{
@@ -56,7 +56,7 @@
},
{
"label": "remote-tunnel-manager.js",
- "gzip": 2491,
+ "gzip": 2490,
"kind": "lazy"
}
]
@@ -64,17 +64,17 @@
},
{
"id": "./beta",
- "gzip": 125709,
+ "gzip": 134608,
"composition": {
- "initialGzip": 121052,
- "lazyGzip": 4657,
- "totalGzip": 125709,
- "own": 364797,
+ "initialGzip": 129943,
+ "lazyGzip": 4665,
+ "totalGzip": 134608,
+ "own": 390343,
"nodeModules": null,
"chunks": [
{
"label": "beta.js",
- "gzip": 94097,
+ "gzip": 102908,
"kind": "initial"
},
{
@@ -84,7 +84,7 @@
},
{
"label": "define-schema.js",
- "gzip": 5952,
+ "gzip": 6032,
"kind": "initial"
},
{
@@ -119,7 +119,7 @@
},
{
"label": "index.js",
- "gzip": 4144,
+ "gzip": 4152,
"kind": "lazy"
},
{
@@ -140,14 +140,32 @@
]
}
},
+ {
+ "id": "./beta/database-tooling",
+ "gzip": 57006,
+ "composition": {
+ "initialGzip": 57006,
+ "lazyGzip": 0,
+ "totalGzip": 57006,
+ "own": 170568,
+ "nodeModules": null,
+ "chunks": [
+ {
+ "label": "index.js",
+ "gzip": 57006,
+ "kind": "initial"
+ }
+ ]
+ }
+ },
{
"id": "./testing",
- "gzip": 86976,
+ "gzip": 87002,
"composition": {
"initialGzip": 47639,
- "lazyGzip": 39337,
- "totalGzip": 86976,
- "own": 251577,
+ "lazyGzip": 39363,
+ "totalGzip": 87002,
+ "own": 251662,
"nodeModules": null,
"chunks": [
{
@@ -167,7 +185,7 @@
},
{
"label": "index.js",
- "gzip": 34987,
+ "gzip": 35013,
"kind": "lazy"
},
{
@@ -203,17 +221,17 @@
},
{
"id": "./type-generator",
- "gzip": 31746,
+ "gzip": 31777,
"composition": {
- "initialGzip": 31746,
+ "initialGzip": 31777,
"lazyGzip": 0,
- "totalGzip": 31746,
- "own": 91419,
+ "totalGzip": 31777,
+ "own": 91504,
"nodeModules": null,
"chunks": [
{
"label": "index.js",
- "gzip": 31746,
+ "gzip": 31777,
"kind": "initial"
}
]
diff --git a/designs/001_DatabaseDevelopmentFlow.md b/designs/001_DatabaseDevelopmentFlow.md
index e89eb661a..cb77f584e 100644
--- a/designs/001_DatabaseDevelopmentFlow.md
+++ b/designs/001_DatabaseDevelopmentFlow.md
@@ -225,9 +225,12 @@ uses your dev branch. `--session` and `--dev` switch between them.
The plugin applies migrations in `setup()`, after the pool opens and before the schema check and `server.start()`. It
runs only when `APPKIT_DB_MIGRATE_ON_START=true` and the process connects as the app's own service principal. Apps sets
`DATABRICKS_CLIENT_ID` and `DATABRICKS_CLIENT_SECRET` for the app, and sets `PGUSER` to that client ID for every app
-with a bound database. So the plugin migrates only when `PGUSER` is set and equals `DATABRICKS_CLIENT_ID`. An unset
+with a bound database. So the plugin migrates only when `DATABRICKS_CLIENT_ID` and `DATABRICKS_CLIENT_SECRET` are set
+and `PGUSER` is set and equals `DATABRICKS_CLIENT_ID`. An unset
`PGUSER` does not qualify, though the pool would then connect with the client ID. When the flag is set and the process
-does not qualify, the plugin logs why and does not migrate. The template's `app.yaml.tmpl` writes the flag for apps that
+does not qualify, the plugin logs why and does not migrate. A process that qualifies also needs `LAKEBASE_ENDPOINT` set
+to the endpoint's full resource name, `projects/
/branches//endpoints/`, because the plugin reads the branch
+from it. When it is unset or has another form, startup fails and names the variable. The template's `app.yaml.tmpl` writes the flag for apps that
select the plugin, which `apps init` offers only after the reveal. Until then, an app that adds the plugin by hand adds
the flag to `app.yaml` too. `.env` never carries it.
@@ -240,7 +243,8 @@ deploy branch. This gap closes before the reveal.
A deployed app bound to a branch with the exact shape of a dev or session branch, `dev--` or
`session--`, refuses to start and names the branch. Only a developer migrates those branches. A deploy
-branch named `session-store` does not have that shape, so it migrates.
+branch named `session-store` does not have that shape, so it migrates. The refusal runs inside migrate on start, so it
+covers only a start that migrates. An app without the flag, or a process that does not qualify, starts on such a branch.
Rejected alternatives:
@@ -343,11 +347,11 @@ Two limits are different and easy to confuse:
and its transaction end.
A killed instance is not cancelled for certain either. The migrating session also sets
-`client_connection_check_interval`, which Lakebase allows and sets to 60 seconds server-wide, so Postgres cancels a
-statement whose client went away. That is best effort. Postgres sees a closed connection only when the server's kernel
-reports it, and a host that vanished without closing the socket may not be seen until TCP keepalive gives up. When the
-server rejects the setting, the migrator logs a warning and goes on. Until Postgres notices, the killed instance's
-statement keeps running and holds its locks, the advisory lock included.
+`client_connection_check_interval` to 10 seconds, so Postgres cancels a statement whose client went away. Lakebase
+allows the setting and sets it to 60 seconds server-wide. That is best effort. Postgres sees a closed connection only
+when the server's kernel reports it, and a host that vanished without closing the socket may not be seen until TCP
+keepalive gives up. When the server rejects the setting, the migrator logs a warning and goes on. Until Postgres
+notices, the killed instance's statement keeps running and holds its locks, the advisory lock included.
For a stuck start, the lock-wait log names the holder's pid. `select pg_cancel_backend()` cancels its statement.
`select pg_terminate_backend()` ends its session, which releases the advisory lock. A role with the
@@ -368,8 +372,10 @@ and `clean --delete-branch` take none. A second `appkit db` command that needs t
says who holds it. `init` holds one lock for its whole run, so no other command that takes the lock runs between its
clean and its migrate. `init --schema none` changes no migration history and takes no lock.
-A command killed by a signal leaves the file behind. The next command fails the same way and says whether the
-holder's pid still runs on this machine. AppKit never takes over or deletes a lock it does not hold. Once no
+A command releases the lock when it finishes or exits, and on SIGINT or SIGTERM when nothing else in the process handles
+the signal. When another handler keeps the process running, the command keeps the lock until it exits. A command that
+ends any other way, such as SIGKILL, can leave the file behind. The next command fails the same way, reports the lock as
+stale, and says whether the holder's pid still runs on this machine. AppKit never takes over or deletes a lock it does not hold. Once no
`appkit db` command runs in the checkout, the developer deletes the file and reruns the command. The template's
`.gitignore` lists the file.
@@ -390,12 +396,14 @@ again under it when an entry is pending and none is stranded:
| `current` | Every entry recorded with its hash. | Nothing. |
| `stranded` | An entry older than the last recorded one, not recorded. | Fail. Nothing changes. |
| `edited` | A recorded entry whose file hash changed, with either line ending. | Fail. The CLI only warns. |
+| `ambiguous` | Entries and rows at one `when` that no exact hash pairs, other than one of each. | Fail. Nothing changes. |
| `ahead` | A recorded row with no committed entry, for example after a code rollback. | Warn, or fail when an entry is also `pending`. |
| `partial-baseline` | `0000_baseline` tables exist only in part. | Fail. Nothing changes. |
Committed entries and recorded rows that share a `when` match one to one, exact hashes first. A committed entry left
-with no row is `pending` or `stranded`, never `edited`. So a migration that never ran cannot hide behind an edited
-one with the same timestamp.
+with no row is `pending` or `stranded`, never `edited`. So a migration that never ran cannot hide behind an edited one
+with the same timestamp. One entry and one row left at a `when` are `edited`. Any other remainder is `ambiguous`,
+because the migrator cannot tell which entries ran.
Before it reads the rows, startup checks the journal relation itself. It refuses a `__drizzle_migrations` in the app
schema that is not an ordinary table. It records only into a journal it trusts, one owned by its own role, by a role it
@@ -560,6 +568,12 @@ Introspect keeps the `.private()` an existing `schema.ts` declares, because the
columns from its reads by default. Every other column it writes is public. When `schema.ts` does not load, introspect
refuses before it reads the branch, because it could not keep the columns the file marks private.
+Before it replaces `schema.ts`, introspect copies the old file to `schema.ts.bak`. It writes the backup only when the
+new file differs, so a second run with the same catalog keeps the first backup. With history, introspect refuses to
+write a migration that drops an object the branch still has but `schema.ts` cannot express, such as a skipped column.
+It would record that migration as applied, and the deployed app would run the drop on start. The refusal names each
+object, says why introspect left it out, and says the deployed app would drop it.
+
### Flag Strategy
| Flag | Default | Introduced in | Turning it off |
@@ -597,7 +611,8 @@ scaffold to deploy in six steps:
committed migrations, so the new branch holds no copied app rows. With `--schema none`, init stops after it writes
`.env`, and a later plain init still rebuilds.
3. The developer declares a table in `schema.ts` and runs `appkit db migrate`. It writes `0000_migration.sql`,
- regenerates `shared/appkit-types/database.d.ts`, and applies the migration to the dev branch.
+ regenerates `shared/appkit-types/database.d.ts` and `database-operations.d.ts`, and applies the migration to the
+ dev branch.
4. The developer adds authorized operations in `server/database/routes/` and uses them in the UI, as design 002
describes. Changes to storage still require `appkit db migrate`, and editing an operation never applies DDL.
5. The developer commits `config/database/`, the operations with their generated contracts, and the UI changes. After
@@ -743,6 +758,9 @@ the `applied`, `adopted`, `edited` and `unknown` (the `ahead` rows) counts, `loc
is missing, init writes its own keys and the profile or host it authenticated with. It never copies `.env.example`,
whose `DATABRICKS_HOST` is a placeholder. It replaces a `PGSSLMODE` of `prefer` or `disable` with `require` and says
so, because `prefer` does not verify the server's certificate.
+- **`appkit db` connects only with TLS that verifies.** Of the modes the Lakebase pool takes, only `PGSSLMODE=require`
+ verifies the server's certificate, and an unset `PGSSLMODE` means `require`. The CLI refuses `prefer`, `disable` and
+ `allow`, says why, and does not connect.
- **Session branches are bound to a user.** With the user hash in the name, a copied `.env` fails the guard for
everyone but its creator.
@@ -768,13 +786,15 @@ start and the schema check passes. Keep the expand and contract migration checks
1. **Design.** Land this doc. Done when the Apps, Lakebase and CLI reviewers have answered the open questions marked
for them.
2. **Runtime, dark.** Land #654 and #655 with the flag, the per-migration transactions, the reconcile states and the
- bounded lock. Done when a real-Postgres test suite passes in CI, and the dev-playground deployed with the flag on
- applies `0000` and then `0001`.
-3. **Commands, hidden.** Land #666 to #674. Done when a developer on the dev-playground runs `init`, `migrate` and
- `verify` on their own branch, and the deployed app applies the migration.
+ bounded lock. Done when a real-Postgres test suite passes in CI, and a throwaway app scaffolded from the template,
+ with the plugin and the flag added by hand, deploys and applies `0000` and then `0001`.
+3. **Commands, hidden.** Land #666 to #674. Done when a developer on a throwaway app scaffolded from the template runs
+ `init`, `migrate` and `verify` on their own branch, and the deployed app applies the migration.
4. **Template and docs, hidden.** Land #675, then #678 (`appkit db check`). #675 keeps the plugin `hidden: true` and out
- of `template/appkit.plugins.json`, and keeps `appkit db` hidden from `appkit --help`. Done when two people on the
- dev-playground add migrations on parallel git branches, `appkit db check` fails a merge that keeps both, and the
+ of `template/appkit.plugins.json`, and keeps `appkit db` hidden from `appkit --help`. Its `process.exit(1)` on a
+ failed start applies to every app the template scaffolds, with or without the plugin, so any app whose startup
+ fails stops instead of serving without its routes. Done when two people on a throwaway app scaffolded from the
+ template add migrations on parallel git branches, `appkit db check` fails a merge that keeps both, and the
documented fix passes.
5. **Reveal.** A later, separate change offers the plugin in `apps init`, moves the `database` export from `beta.ts`
into the generated barrel, and shows `appkit db` in `appkit --help`. Until a CLI release runs `appkit db init`, the
diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md
index 31dbc039b..439f794fe 100644
--- a/docs/docs/plugins/database.md
+++ b/docs/docs/plugins/database.md
@@ -31,10 +31,11 @@ Configure a Lakebase `postgres` resource and its connection environment variable
as described in [Lakebase configuration](./lakebase.md#environment-variables).
Apps scaffolded with the Database plugin selected include an empty
-`config/database/schema.ts`, so `database()` can start without requiring sample
-tables. Replace the empty declaration with your tables once they exist in
-PostgreSQL. The plugin never creates or migrates tables. At startup, it checks
-that every declared table and column exists and fails setup if one is missing.
+`config/database/schema.ts` in the Postgres schema `app`, and set
+`APPKIT_DB_MIGRATE_ON_START=true` in `app.yaml` so the deployed app applies its
+migrations on start. Run `npx appkit db init` once to point `.env` at a branch of
+your own, declare your tables, then run `npx appkit db migrate` to create them there
+(see [Development workflow](#development-workflow)).
For local development, the PostgreSQL username is resolved from your Databricks
credentials when `PGUSER` and `DATABRICKS_CLIENT_ID` are absent. An explicitly
@@ -86,6 +87,605 @@ identifier-only messages for known missing-column or missing-table errors (for
example, `column notes.board_id does not exist`). Other driver messages, details,
and hints are omitted because they may contain row values.
+Tables live in the Postgres schema `app` unless the second argument of
+`defineSchema()` names another one, for example `{ schemaName: "public" }`. The
+default is not `public` because the deployed app's service principal creates and
+owns `app`, but has no `CREATE` privilege on `public`.
+
+Give each app its own `schemaName`. Two apps bound to one database with the same
+schema are unsupported. They would share the schema, its migration journal and
+the migration lock, and the second app's service principal cannot change the
+tables the first one owns.
+
+### Apps with tables in `public`
+
+Earlier releases put tables in `public` by default. An app that created its
+tables there fails setup after the upgrade, and the error says the tables are in
+`public`. With `APPKIT_DB_MIGRATE_ON_START=true`, startup refuses before any
+migration runs when `defineSchema()` was given no `schemaName`, none of the
+declared tables exist in `app`, and some exist in `public`; `npx appkit db migrate`
+refuses to apply on a dev branch in the same case. Otherwise the first
+migration would create empty copies in `app`, the check would pass, and the app
+would serve the empty tables. Keep the tables in `public` with:
+
+```ts
+export const schema = defineSchema(
+ ({ table }) => ({
+ notes: table("notes", { id: id(), body: text().notNull() }),
+ }),
+ { schemaName: "public" },
+);
+```
+
+To use `app` instead, move the tables first
+(`ALTER TABLE public.notes SET SCHEMA app`). When the tables in `public` belong
+to another app, pass `{ schemaName: "app" }` explicitly and neither startup nor
+`migrate` refuses.
+
+Migrations applied on start into `public` also need
+`GRANT CREATE ON SCHEMA public` to the app's service principal, because it does
+not own `public`.
+
+## Development workflow
+
+:::note
+`appkit db` is hidden from `appkit --help` while the database development flow is
+in beta. Its logic ships in `@databricks/appkit/beta/database-tooling`, which
+only the AppKit CLI of the same release imports. It has no semver guarantee.
+:::
+
+You develop against a Lakebase branch of your own, never the deployed one. Tables
+are created and changed through migrations: generated locally from `schema.ts`,
+committed with your code, and applied by the deployed app when it starts.
+
+### Set up your branch
+
+Run `npx appkit db init` once after scaffolding, and again after cloning. Until
+`databricks apps init` runs it for you, the scaffolded `.env` points at the branch
+you picked in its prompts, usually the branch the app deploys to, and
+`npx appkit db verify` warns about that.
+
+`db init` asks nothing:
+
+1. It keeps this checkout's session branch when `.env` points at one, and
+ otherwise uses your dev branch, `dev--`. When the branch does not
+ exist yet, it forks the branch that the default `databricks.yml` target
+ binds, or the project's default branch when that target does not resolve,
+ and prints which one it forked. `--session` uses a branch for this checkout
+ that expires after 7 days (`--ttl` changes that), and `--dev` goes back to
+ your dev branch.
+2. It makes sure the branch has an endpoint and your Postgres role, and points
+ `.env` at the branch.
+3. It sets up the schema, and reads the branch to decide how. When the app
+ schema still belongs to the fork's copy of the app's service principal, the
+ branch is an untouched copy. `init` then tags the copied migration journal,
+ hands you the schema (see [One owner per branch](#one-owner-per-branch)),
+ drops it, and rebuilds it from the committed migrations, so the tables start
+ without the copied rows. Without `schema.ts`, it first writes `schema.ts`
+ and a `0000_baseline` migration from the fork's tables (`introspect`), then
+ rebuilds from that baseline. A branch this run created is rebuilt the same
+ way even when its app schema is already yours, because every row on it is
+ the fork's copy. In schema `public`, which no app owns, a rebuild drops only
+ the tables you own, and lists the tables that keep their copied rows. When
+ the app schema was already yours on a branch that existed before this run,
+ `init` keeps the rows. With `schema.ts` it runs `migrate`, which writes a
+ migration when `schema.ts` changed since the last one, then applies the
+ committed migrations. Without `schema.ts`, it runs `introspect`. To keep
+ the copied rows on a new branch, pass `--schema migrate`, or
+ `--schema introspect` without `schema.ts`, and `init` says that they stay.
+ The rows are yours from then on, so a later plain `init` keeps them, and
+ `--schema clean` removes them. `--schema clean` drops the app schema first,
+ after a confirmation. Without a terminal, it needs `--yes`. `--schema none`
+ only sets up the branch and `.env`. It reads no `schema.ts`, hands over no
+ schema, and leaves the schema and its owner as the fork copied them. The
+ next plain `init` still rebuilds a copy the app's service principal owns.
+ If you already owned the schema on the source, that later run sees your
+ working branch, so run `--schema clean` then.
+4. Unless `--schema none`, it installs the drizzle-kit version AppKit pins as a
+ dev dependency when the app does not have it. `migrate` and `introspect`
+ generate migrations with it.
+
+`db init` never changes the project's default branch, a protected branch or a
+branch `databricks.yml` deploys to, and never edits `databricks.yml`.
+
+:::caution[A new branch copies the branch the app deploys to]
+A new branch forks the branch the default `databricks.yml` target binds, or the
+project's default branch when `init` cannot resolve that target, so it starts
+with a copy of its rows, production data included. By default, `db init` drops
+the copy in the app schema. Until it does, and in other schemas, the rows stay
+on the branch. Your role there is a member of `DATABRICKS_SUPERUSER`, which
+reads and writes every table on the branch and bypasses row-level security.
+Creating a branch needs CAN MANAGE on the Lakebase project, which also allows
+deleting any branch, the deploy branch included. Use a project whose deploy
+branch holds only data every developer may see.
+:::
+
+### Commands
+
+| Command | What it does |
+| --- | --- |
+| `npx appkit db init` | Points `.env` at your dev branch, or with `--session` at a branch for this checkout that expires, then sets up the schema. |
+| `npx appkit db migrate` | Writes `config/database/migrations/NNNN_migration.sql` when `schema.ts` changed, regenerates `shared/appkit-types/database.d.ts` and `database-operations.d.ts`, and applies pending migrations to your branch. |
+| `npx appkit db introspect` | Writes `schema.ts` from tables that already exist, and a `0000_baseline` migration (or `NNNN_introspect` when migrations already exist), and regenerates both type files. |
+| `npx appkit db clean` | Drops the app schema on your branch; `migrate` then rebuilds it from the migrations. `--delete-branch` deletes your session branch instead. |
+| `npx appkit db seed` | Runs `config/database/seed.sql` on your branch in one transaction. |
+| `npx appkit db verify` | Read-only check of your branch: missing tables or columns, pending migrations, migrations that will never run there, and migrations it ran that this checkout does not commit. `--deployed` checks a target's deployed app instead. |
+| `npx appkit db check` | Offline check of the committed migrations, for CI: their order and files, and no `schema.ts` change without a migration. |
+
+`migrate`, `clean` and `seed` change only branches `db init` created for you (your
+dev branch, or this checkout's session branch). A session branch name includes a
+hash of the user who created it, so a `.env` copied from another developer does
+not make their session branch yours. On any other branch, including the
+project's default branch, a protected branch, or a branch `databricks.yml`
+deploys to, `clean` and `seed` refuse, and `migrate` only writes the migration
+files and the generated types in `shared/appkit-types/`.
+
+A typical change:
+
+```bash
+# edit config/database/schema.ts
+npx appkit db migrate # writes and applies NNNN_migration.sql on your branch
+git add config/database # commit schema.ts with its migrations
+databricks apps deploy # the deployed app applies it on start
+npx appkit db verify --deployed # the app runs, and its source has every committed migration
+```
+
+### Warnings about a generated migration
+
+`migrate` prints a warning for each of two classes of statement in the
+migration it wrote, and names the statements. One statement can be in both
+classes.
+
+Statements that break instances still running the previous release. Drops,
+renames, type changes, `SET NOT NULL` and a new `NOT NULL` column without a
+default are in this class. Those instances can still serve while the new one
+migrates on start, and a code rollback does not undo a migration. Deploy code
+that works with both the old and the new schema first, then this change in a
+later deploy.
+
+Statements that may fail on existing rows. `SET NOT NULL`, a new `NOT NULL`
+column without a default, a type change, a new constraint (`UNIQUE`,
+`PRIMARY KEY`, `CHECK`, `FOREIGN KEY` or `EXCLUDE`) and a unique index are in
+this class. Postgres checks them against the rows already in the table. A new
+dev branch has no rows, so they pass there and can fail on the deploy branch.
+Test the migration on a branch that has a copy of the deploy branch's data
+before you deploy, for example a session branch created with
+`npx appkit db init --session --schema migrate`.
+
+### Your branch's data
+
+`npx appkit db init` creates your dev branch, or this checkout's session branch
+with `--session`, as a fork of the branch `databricks.yml` deploys to, else of
+the project's default branch, and points `.env` at it. A fork copies every row
+of its source, production data included. `init` reads from the branch what its
+app schema is. While the app's service principal still owns the schema, it is
+the fork's untouched copy. `init` hands it to you, drops it and recreates it
+from the committed migrations, so the branch starts without the copied rows.
+A branch `init` forked in this run holds only what the fork copied, whoever
+owns its schema. So a schema you already owned on the source is rebuilt too,
+with no hand-off to make. Without `config/database/schema.ts`, `init` first
+writes it and `0000_baseline.sql` from the fork's schema, then rebuilds the
+schema from that baseline.
+
+Before the hand-off, `init` inserts one row with the hash `appkit:fork-copy`
+into the copied `__drizzle_migrations` journal. It writes the row only where
+the migrator would record. That is a journal owned by your role, by a role it
+inherits, or by the schema's owner, which is what a fork's copy has. A journal
+another role owns could run that role's code as you through a trigger, a rule,
+a default or a policy, so `init` leaves it alone. It then warns that it could
+not mark the copy and rebuilds anyway. A copy with no journal gets the same
+warning. If such a run stops before the rebuild finishes, the next `init` sees
+a schema that looks like your working branch and keeps the copied rows. Run
+`npx appkit db init --schema clean` then. Dropping the schema removes the row. A
+run that stops between the hand-off and the drop leaves a schema you own whose
+journal still carries that row, and the next `init`, from any checkout,
+finishes the rebuild.
+
+`npx appkit db migrate`, `npx appkit db introspect` and `npx appkit db seed` refuse a
+schema that is still a copy. That is one the service principal still owns, with
+no row yet, or one handed to you whose journal still carries the row. The message
+says to run `npx appkit db init` to rebuild it, or `npx appkit db init --schema
+migrate` (`introspect` for introspect) to keep the copied rows. Schema `public`
+is never refused.
+`npx appkit db verify` reports both kinds of copy with the same advice.
+
+To keep the copied rows, pass `--schema migrate`, or `--schema introspect`.
+`init` then hands the schema to you, removes the row, keeps the data, and says
+where it came from. From then on the schema is your working branch. A plain
+`init` migrates it and keeps the rows. `npx appkit db init --schema clean` drops
+the app schema with everything in it and rebuilds it from the committed
+migrations, after a confirmation or with `--yes`. On a branch an earlier run
+created, a schema you own with no such row is your working branch. `init`
+migrates it, or introspects it without `schema.ts`. A copy's rebuild asks
+nothing, because `migrate` refuses a copy and a fresh fork holds only what it
+copied, so none of your work can be on it. `--schema none` touches nothing.
+The next plain `init` still rebuilds a copy the service principal owns. A fresh
+fork of a schema you already owned looks like your working branch to that
+later run, so run `npx appkit db init --schema clean` then.
+
+In schema `public`, `init` and `clean` remove only the objects your role owns,
+and `init` never hands `public` off or tags it. On a fork of the deploy branch
+the app's service principal owns the tables, so `init` migrates the schema, the
+tables stay with their rows, and the report lists them as kept.
+
+### Branches `databricks.yml` deploys to
+
+`migrate` never applies migrations to a branch that `databricks.yml` deploys to.
+It reads every target, every `postgres` resource of every app, the
+`postgres_branch` variable, and the files that `include:` names. It also reads
+the variable values `databricks bundle` keeps for a target in
+`.databricks/bundle//variable-overrides.json`. A branch named there
+counts as well as the one `databricks.yml` names, because a deploy from this
+checkout uses the file's value.
+
+If a branch or database reference has no value in those files, `migrate` cannot
+tell which branch the reference names. Examples are a target that leaves
+`postgres_branch` unset and `${workspace.current_user.short_name}`. The same
+holds for a `${var.…}` reference in place of an app's `resources` list, one of
+its entries, or a `postgres` block, because the files do not say what it binds.
+While any such reference exists, `migrate` applies migrations to no branch, and
+`init`, `introspect`, `clean` and `seed` refuse every branch. The message names
+the target and where the reference is. To continue, give the reference a value
+in `databricks.yml`, or in the `variable-overrides.json` the message names. A
+`variable-overrides.json` that is not a JSON object stops these commands too.
+
+The check reads only this checkout's files. It does not see values passed at
+deploy time with `--var` or `BUNDLE_VAR_*`, or resources defined in Python. It
+protects branches from the CLI, and does not replace Lakebase permissions or
+protected branches.
+
+### One command at a time
+
+While `migrate`, `introspect`, `clean` or `init` runs, it holds
+`config/database/.appkit-db.lock`. Another of these commands in the same
+checkout fails and names the process that holds the lock. `seed`, `verify`,
+`check` and `clean --delete-branch` change no migration history and take no
+lock. The lock goes when the command finishes or exits. `init` holds it for its
+whole run, including the clean and migrate it starts. `init --schema none`
+changes no migration history, so it takes no lock.
+
+A command stopped by a signal, such as SIGKILL, can leave the file behind. The
+next command then names the holder. When that process no longer runs, the
+message says the holder stopped. When its pid runs on this machine, the message
+says to wait for it. A pid can also belong to an unrelated process, for example
+after a reboot reused it. In either case, if no `appkit db` command runs in the
+checkout, delete `config/database/.appkit-db.lock` and run the command again.
+AppKit never deletes a lock it does not hold. Scaffolded apps list the file in
+`.gitignore`.
+
+### Changing tables in use
+
+A migration must work with the code that is still running or may run again. On
+no-downtime compute, instances of the previous release keep serving while the
+new release migrates on start. On classic compute the old process stops first,
+but a [rollback](#rolling-back) redeploys the previous release against the
+migrated schema. A change that drops or renames a table or column, changes a
+column's type, or makes a column required breaks that code, and `db migrate`
+warns when it writes one. Split such a change over two deploys. First deploy
+code that works with both the old and the new schema, with a migration that
+only adds. Then, in a later deploy, drop what the old code used.
+
+`db migrate` warns separately when a migration has a statement that may fail
+on rows the deploy branch already has. Your dev branch starts without the
+copied rows, so a `SET NOT NULL` on a column with NULL rows, or a `UNIQUE`
+constraint on a column with duplicates, passes there and fails on deploy. Test
+such a migration on a session branch that keeps the copied rows,
+`npx appkit db init --session --schema migrate`. If it still fails on deploy,
+repair the rows, as
+[When a migration fails on deploy](#when-a-migration-fails-on-deploy) describes.
+
+### Migrations on deploy
+
+When the deployed app starts with `APPKIT_DB_MIGRATE_ON_START=true` in `app.yaml`,
+`database()` applies the committed migrations the deploy branch has not recorded
+yet, before it checks the tables and serves requests. Apps scaffolded with the
+plugin set it; add it to the `env` of an app that predates it:
+
+```yaml
+env:
+ - name: APPKIT_DB_MIGRATE_ON_START
+ value: "true"
+```
+
+The flag alone does not migrate. A start migrates only when `PGUSER` is set
+and equals `DATABRICKS_CLIENT_ID`, so that the process connects as the deployed
+app's own service principal. Databricks Apps sets both for an app with a bound
+database. `npx appkit db init` writes your user name to `PGUSER` in `.env`, so
+a local start (`npm run dev`, `npm start`, `databricks apps run-local`)
+connects as you and never migrates, with or without exported M2M credentials.
+Before `db init` writes `.env`, `PGUSER` is unset, and the start skips for that
+reason. A start that skips logs why. Use `npx appkit db migrate` on your
+branch instead. A deployed app bound to a branch with the exact shape of a dev
+branch, `dev--<6 hex>`, or of a session branch refuses to start, because
+`appkit db` owns those branches.
+
+Migrations run as the app's service principal, one instance at a time, each in
+its own transaction. If one fails, it is rolled back, the ones before it stay
+applied, and the app does not start. The server log names the migration and the
+SQLSTATE, or the missing migration file. An instance waits up to 5 minutes for
+another one to finish migrating. A migration that waits more than 5 seconds for a
+table lock, for example behind a long transaction of the running app, is rolled
+back and retried twice, then fails instead of blocking that table.
+
+A deploy start also refuses two histories. One is an edited migration, a
+committed migration the deploy branch recorded with different content. A
+checkout that turned its line endings into CRLF does not count as edited. The
+other is a diverged history, where the checkout has migrations the branch never
+recorded while the branch recorded migrations the checkout lacks. On your dev
+branch, `npx appkit db migrate` only warns about both. See
+[When a migration fails on deploy](#when-a-migration-fails-on-deploy) for the
+first and [Rolling back](#rolling-back) for the second.
+
+A `0000_baseline` from `introspect` is recorded without running when its tables
+already exist on the deploy branch and no migration was ever applied there. If
+only some of them exist, the app does not start, and nothing is changed.
+
+#### What a deploy waits for
+
+Databricks Apps counts a deploy as succeeded once the app process has lived for
+2 seconds, unless `app.yaml` declares a `health_check`. Then the health check
+must pass within its timeout, 300 seconds by default and at most. The template
+declares `health_check` on `/health`, and AppKit binds `/health` only after the
+database plugin's setup, migrations included. So with the health check, a
+deploy succeeds only after the migrations ran, and fails when they fail or do
+not finish within 300 seconds. Keep it. Without it, a deploy succeeds while the
+app is still migrating, and a failed migration shows up only as a crashed app.
+
+What happens to the running app depends on its compute:
+
+- On classic compute, Apps stops the old process before it starts the new one.
+ A failed migration takes the app down.
+- On no-downtime compute, which horizontally scaled apps use, the old instance
+ keeps serving while the new one starts, and keeps serving when the health
+ check fails.
+- A crashed process is not restarted. The app stays down until the next deploy.
+- An app that scales to zero runs its start again on every cold start,
+ migrations included.
+
+#### When a migration fails on deploy
+
+`databricks apps logs` names the migration and the SQLSTATE. The migration was
+rolled back and is not recorded. On classic compute the app is down. On
+no-downtime compute the previous release still serves.
+
+Never edit a migration a deploy branch has applied. A deploy start refuses an
+edited migration. Edit a migration in place only while no deploy branch
+recorded it. Otherwise, write the change as a new migration.
+
+A migration that failed because of the data, for example `SET NOT NULL` on a
+column with NULL rows, needs the rows repaired, not the migration. Repair them
+on the deploy branch, then redeploy the same commit, and the app applies the
+same migration. The app's service principal owns the tables, but a role with
+the `DATABRICKS_SUPERUSER` membership on the deploy branch reads and writes its
+rows. Someone with CAN USE on the Lakebase project creates that role with
+`databricks postgres create-role`.
+
+#### Long backfills
+
+A migration runs inside the start, so it has to finish within the 300 second
+health-check limit. A backfill that needs longer is not one migration. Split it
+in three steps:
+
+1. An expand migration, for example a new nullable column.
+2. A batched DML job that fills the rows, run as a role with the
+ `DATABRICKS_SUPERUSER` membership on the deploy branch. On a Lakebase branch
+ such a role can `SELECT`, `INSERT`, `UPDATE`, `DELETE` and `TRUNCATE` the
+ service principal's tables and create new tables in its schema. It cannot
+ `ALTER`, `DROP` or index them, so the schema stays the app's.
+3. A contract migration, for example `SET NOT NULL`, once every row has a value.
+
+#### A stuck start
+
+While an instance migrates, its session has `application_name` set to
+`appkit-migrate` and holds the migration lock, and other instances wait for it.
+A role with the `DATABRICKS_SUPERUSER` membership on the deploy branch can end
+that session, because `databricks_superuser` inherits `pg_signal_backend` and
+the app's service principal is not a superuser. Find the session, then cancel
+its statement or end it:
+
+```sql
+select pid, state, query_start from pg_stat_activity
+ where application_name = 'appkit-migrate';
+select pg_cancel_backend();
+select pg_terminate_backend();
+```
+
+When that does not free the branch, restart its compute, which needs CAN
+MANAGE on the Lakebase project.
+
+### Existing apps
+
+- **Tables created by hand or by earlier code.** Without `schema.ts`,
+ `npx appkit db init` creates your dev branch from the branch the app deploys to
+ and introspects it. It writes `schema.ts` from the tables in schema `app` and a
+ `0000_baseline` migration. When schema `app` on the branch still belongs to the
+ fork's copy of the app's service principal, init then rebuilds it from that
+ baseline, so the tables start without the rows the fork copied. With a
+ `schema.ts` already, run
+ `npx appkit db init --schema introspect`. On a new branch, a plain `db init`
+ drops the app schema and rebuilds it from the committed migrations, so it keeps
+ only the tables those migrations create. Commit `schema.ts` and the baseline. The
+ deployed app records the baseline without running it, because the tables already
+ exist on the deploy branch. Once the baseline is committed,
+ `db init --schema migrate` keeps the rows a new branch copied.
+- **Tables in `public`.** Earlier releases used `public` by default. Keep them there
+ with `schemaName: "public"`, as [Apps with tables in `public`](#apps-with-tables-in-public)
+ shows. With a `schema.ts`, `npx appkit db introspect` reads the schema it sets in
+ `schemaName`. Without one, `db init` and `db introspect` read schema `app`, so run
+ `npx appkit db init --schema none`, then
+ `npx appkit db introspect --schema-name public`. The `schema.ts` it writes
+ sets `schemaName: "public"`, so later runs read `public` without the flag. The
+ tables keep the rows the fork copied.
+- **No migrate-on-start flag.** Add `APPKIT_DB_MIGRATE_ON_START=true` to `app.yaml`,
+ as [Migrations on deploy](#migrations-on-deploy) shows. Without it, the app checks
+ its tables on start but creates none.
+
+### Rolling back
+
+Migrations only go forward. There are no down migrations, and the app never undoes
+one. Redeploying an older commit leaves the newer tables and their recorded
+migrations in place. The app logs that the branch recorded migrations the older
+code does not have, and applies nothing. It starts when every table and column the
+older `schema.ts` declares still exists. It refuses to start only when the
+checkout also has committed migrations the branch never recorded, because then
+the two histories diverged, and a rollback alone does not produce that. Deploy
+from one branch, usually `main`, and merge a feature's migrations unchanged into
+it before it deploys again.
+
+You can roll back only to a commit whose code works with the current schema. A
+migration that only adds, as the first step of a
+[two-step change](#changing-tables-in-use) does, keeps the previous release
+working. A migration that drops or renames a table or column ends rollbacks to
+every commit whose `schema.ts` declares it, because that code no longer starts.
+The second step of a two-step change is such a migration, so deploy it only when
+you no longer need to roll back past the first step. To undo a schema change,
+commit a new migration that reverses it, and deploy it.
+
+### One owner per branch
+
+Each branch has one owner of the app schema, and only the owner can change its
+tables:
+
+- On the deploy branch, the app's service principal creates schema `app` on its
+ first start and owns everything in it. The `postgres` resource's
+ `CAN_CONNECT_AND_CREATE` permission is all it needs; no grants are required.
+- On your dev or session branch, you own it. A fork copies its parent's objects
+ with their owners, so `db init` hands the app schema to you: it deletes the
+ branch's copy of the role that owns it, with its objects reassigned to you.
+ `db init --schema none` hands over nothing. Schema `public` is never handed
+ over, because it belongs to the database rather than to an app.
+
+Do not apply migrations to the deploy branch yourself. You would own those
+objects, and the app could no longer change them.
+
+If the app schema on the deploy branch already belongs to another role, the app
+cannot migrate it, and the server log names both roles. Two apps bound to the
+same database each need their own `schemaName` in `defineSchema()`. Otherwise
+the app was recreated with a new service principal, or its database resource
+was removed and added again. Lakebase then leaves the objects with a role the
+app no longer has, the old service principal's role or the role of the person
+who removed the resource. No Postgres role can hand them back. `ALTER ... OWNER
+TO` the new service principal fails with `must be able to SET ROLE`, because
+nobody holds that role. Only Lakebase moves them, by deleting the owning role
+and reassigning what it owns. The delete reassigns the objects the role owns
+on the branch, drops the role's memberships and grants, and removes the role. If
+the role still owns objects in another database of the branch, the delete can
+fail. So first take the inventory `db init` takes before it hands a
+schema over. In each database of the branch, list what the role owns there:
+
+```sql
+select o.type, o.identity
+ from pg_shdepend s
+ cross join lateral pg_identify_object(s.classid, s.objid, s.objsubid) o
+ where s.refclassid = 'pg_authid'::regclass
+ and s.refobjid = (select oid from pg_roles where rolname = '')
+ and s.deptype = 'o'
+ and s.dbid = (select oid from pg_database where datname = current_database())
+ order by 1, 2;
+```
+
+Then count what else depends on the role, grants included, in the other
+databases and in shared objects such as a database it owns. Run the first query
+in each database this one names:
+
+```sql
+select coalesce(d.datname, 'shared objects') as database, count(*)
+ from pg_shdepend s
+ left join pg_database d on d.oid = s.dbid
+ where s.refclassid = 'pg_authid'::regclass
+ and s.refobjid = (select oid from pg_roles where rolname = '')
+ and not (s.deptype = 'o'
+ and s.dbid = (select oid from pg_database where datname = current_database()))
+ group by 1
+ order by 1;
+```
+
+Reassign or drop anything unrelated to the app before you delete the role.
+Then someone with CAN MANAGE on the Lakebase project moves the objects:
+
+```bash
+# Both roles, by their client IDs or user names
+databricks postgres list-roles projects//branches/
+databricks postgres delete-role projects//branches//roles/ \
+ --reassign-owned-to projects//branches//roles/
+```
+
+### Verify the deployed app
+
+`npx appkit db verify --deployed` checks a `databricks.yml` target's app through
+the Databricks API: the app exists, its `postgres` resource names the target's
+branch and database with `CAN_CONNECT_AND_CREATE`, its service principal has a role
+on the branch, and the app is running. When the checkout has
+`.databricks/bundle//variable-overrides.json`, the branch and database
+come from it, as a deploy from this checkout uses them. It also reads the source
+the app's active deployment runs: every committed migration must be there with
+the same journal entry and SQL, and the deployment must have no migration this
+checkout does not commit. It compares the deployment's journal entry by entry,
+so a duplicated, malformed or reordered entry fails too. When verify cannot read
+that source, or the API reports no service principal for the app, it fails and
+says why.
+
+It reads no database, so it does not check that the migrations ran on the
+deploy branch. An app with `APPKIT_DB_MIGRATE_ON_START=true` applies them on
+start, and a migration that fails stops the start; `databricks apps logs` shows
+why.
+
+`-t, --target` picks the target; without it, verify uses the bundle's default
+target. When the target's `workspace.host` is not the workspace your shell is
+authenticated against, verify refuses and names the profile to set. A
+`workspace.host` the checkout's files cannot resolve, such as a `${var.…}` with
+no value, is refused before any API call. It needs no
+access to the deploy branch's database and changes nothing. A failed check names
+`databricks apps logs`, `start` or `deploy`.
+
+### CI
+
+`appkit db init` sets up branches for developers, and CI does not need one. On
+every pull request, run the offline check after installing the app's
+dependencies:
+
+```bash
+npx appkit db check
+```
+
+It needs no Databricks or Lakebase credentials. It is not a sandbox, though. To
+load `schema.ts` it imports that file and everything the file imports, so it
+runs the pull request's code. Give the CI job that runs it no secrets. It
+compares the snapshots with each other and with `schema.ts`, and does not read
+the `.sql` files, so SQL edited by hand is not checked against its snapshot. It
+exits 1 when:
+
+- `schema.ts` changed and no committed migration has the change;
+- a migration is listed after one generated later, which a branch that ran the
+ later one never runs;
+- two migrations were generated from the same snapshot on parallel git branches;
+- the first migration was not generated from an empty database, so the ones
+ before it are missing;
+- an entry's `idx` is not its position in the journal, or its `when` is not an
+ integer timestamp;
+- a migration's `.sql` or snapshot is not committed, a snapshot is not a
+ drizzle-kit snapshot, or a `.sql` is not in the journal.
+
+Two pull requests that each add a migration conflict in
+`config/database/migrations` once one of them is merged, and keeping both sides
+fails the check. Resolve the conflict with `main`'s migrations instead. Save any
+SQL you wrote by hand in your migration, such as a backfill. Merge `main`, reset
+`config/database/migrations` to `main`'s, then run `npx appkit db clean` and
+`npx appkit db migrate`. `migrate` writes your schema change again after
+`main`'s migrations. Add the saved SQL back to the migration it writes and
+review it before you commit.
+
+After a deploy, check the deployed app with workspace credentials:
+
+```bash
+databricks apps deploy -t prod
+npx appkit db verify --deployed -t prod
+```
+
+It exits 1 when the app is not running or is bound to another branch, when
+verify cannot confirm that its deployment has every committed migration with the
+same SQL, and when the deployment has a migration this checkout does not commit.
+
## Schema discovery and overrides
During setup, `database()` loads the discovered routes registry's schema. Without
diff --git a/knip.json b/knip.json
index 8e2d0f8a1..fd886e190 100644
--- a/knip.json
+++ b/knip.json
@@ -30,7 +30,8 @@
"@databricks/sdk-statementexecution",
"@databricks/sdk-warehouses",
"@mlflow/core",
- "autoevals"
+ "autoevals",
+ "drizzle-kit"
]
},
"packages/appkit-ui": {
diff --git a/packages/appkit/package.json b/packages/appkit/package.json
index 50bafcc10..fa5829599 100644
--- a/packages/appkit/package.json
+++ b/packages/appkit/package.json
@@ -42,6 +42,11 @@
"development": "./src/type-generator/index.ts",
"default": "./dist/type-generator/index.js"
},
+ "./beta/database-tooling": {
+ "types": "./dist/database/tooling/index.d.ts",
+ "development": "./src/database/tooling/index.ts",
+ "default": "./dist/database/tooling/index.js"
+ },
"./testing": {
"types": "./dist/testing/index.d.ts",
"development": "./src/testing/index.ts",
@@ -127,6 +132,7 @@
"peerDependencies": {
"@mlflow/core": "0.4.0",
"autoevals": "0.3.0",
+ "drizzle-kit": "0.31.10",
"vitest": ">=3"
},
"peerDependenciesMeta": {
@@ -136,6 +142,9 @@
"autoevals": {
"optional": true
},
+ "drizzle-kit": {
+ "optional": true
+ },
"vitest": {
"optional": true
}
@@ -150,6 +159,7 @@
"@types/ws": "8.18.1",
"@vitejs/plugin-react": "5.1.1",
"autoevals": "0.3.0",
+ "drizzle-kit": "0.31.10",
"vitest": "3.2.4"
},
"overrides": {
@@ -162,6 +172,7 @@
"./beta": "./dist/beta.js",
"./dist/shared/src/plugin": "./dist/shared/src/plugin.d.ts",
"./type-generator": "./dist/type-generator/index.js",
+ "./beta/database-tooling": "./dist/database/tooling/index.js",
"./testing": {
"types": "./dist/testing/index.d.ts",
"default": "./dist/testing/index.js"
diff --git a/packages/appkit/src/connectors/lakebase/endpoint-host.ts b/packages/appkit/src/connectors/lakebase/endpoint-host.ts
index dfa94c9e1..078ebaa7e 100644
--- a/packages/appkit/src/connectors/lakebase/endpoint-host.ts
+++ b/packages/appkit/src/connectors/lakebase/endpoint-host.ts
@@ -145,7 +145,7 @@ async function compareHosts(
}
/** Read every host the endpoint serves, read-write and read-only. */
-function endpointHosts(response: unknown): string[] {
+export function endpointHosts(response: unknown): string[] {
if (!response || typeof response !== "object") return [];
const status = Reflect.get(response, "status");
if (!status || typeof status !== "object") return [];
diff --git a/packages/appkit/src/database/branch-names.ts b/packages/appkit/src/database/branch-names.ts
new file mode 100644
index 000000000..1f318d8f1
--- /dev/null
+++ b/packages/appkit/src/database/branch-names.ts
@@ -0,0 +1,38 @@
+// The branch ids `appkit db init` gives dev and session branches. Runtime
+// code reads them to refuse a deploy bound to one, so they live outside
+// tooling/, which runtime code may not import.
+
+/** Lakebase's limit on a branch id. */
+export const MAX_BRANCH_ID = 63;
+export const DEV_PREFIX = "dev-";
+export const SESSION_PREFIX = "session-";
+/** Hex characters of the user's name hash in both shapes. */
+export const HASH_LENGTH = 6;
+/** The longest session id that keeps session-- within MAX_BRANCH_ID. */
+export const SESSION_ID_LENGTH =
+ MAX_BRANCH_ID - SESSION_PREFIX.length - HASH_LENGTH - 1;
+
+const DEVELOPMENT_BRANCH_SHAPES = {
+ dev: new RegExp(
+ `^${DEV_PREFIX}[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{${HASH_LENGTH}}$`,
+ ),
+ session: new RegExp(
+ `^${SESSION_PREFIX}[0-9a-f]{${HASH_LENGTH}}-[a-z0-9]{1,${SESSION_ID_LENGTH}}$`,
+ ),
+} as const;
+
+export type DevelopmentBranchKind = keyof typeof DEVELOPMENT_BRANCH_SHAPES;
+
+/**
+ * Which kind of development branch the id has the exact shape of:
+ * `dev--` or `session--`. undefined for any other id,
+ * such as a deploy branch named `session-store`.
+ */
+export function developmentBranchKind(
+ branchId: string,
+): DevelopmentBranchKind | undefined {
+ if (branchId.length > MAX_BRANCH_ID) return undefined;
+ return (
+ Object.keys(DEVELOPMENT_BRANCH_SHAPES) as DevelopmentBranchKind[]
+ ).find((kind) => DEVELOPMENT_BRANCH_SHAPES[kind].test(branchId));
+}
diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts
new file mode 100644
index 000000000..857710d0d
--- /dev/null
+++ b/packages/appkit/src/database/migrations/apply.ts
@@ -0,0 +1,1232 @@
+import { createHash } from "node:crypto";
+import fs from "node:fs";
+import { setTimeout as sleep } from "node:timers/promises";
+
+import { readMigrationFiles } from "drizzle-orm/migrator";
+import type { Pool, PoolClient } from "pg";
+import { MIGRATION_HISTORY_REWRITE } from "shared";
+
+import { createLogger } from "../../logging/logger";
+import {
+ type AmbiguousTimestamp,
+ type MigrationFile,
+ type MigrationHistory,
+ type RecordedMigration,
+ reconcileMigrations,
+} from "./history";
+import {
+ INSUFFICIENT_PRIVILEGE,
+ ownershipHint,
+ schemaOwnership,
+} from "./ownership";
+import {
+ BASELINE_TAG,
+ type Journal,
+ MIGRATIONS_TABLE,
+ MigrationFilesError,
+ migrationFile,
+ readJournal,
+ readJsonFile,
+ snapshotFile,
+} from "./paths";
+
+const logger = createLogger("database");
+
+type DriftPolicy = "warn" | "refuse";
+
+interface ApplyMigrationsOptions {
+ /** Absolute path of the committed migrations folder. */
+ readonly migrationsFolder: string;
+ /** Journal schema = app schema. */
+ readonly schemaName: string;
+ /** Longest wait for another session's migration lock, in milliseconds. */
+ readonly lockWaitMs?: number;
+ /** Longest wait for each table lock a migration takes, in milliseconds. */
+ readonly lockTimeoutMs?: number;
+ readonly onDrift?: DriftPolicy;
+ /**
+ * Runs on the migrating connection, under the migration lock, once a
+ * migration is pending and before any is applied. What it throws reaches
+ * the caller unchanged, and nothing is applied.
+ */
+ readonly beforeApply?: (client: PoolClient) => Promise;
+}
+
+interface ApplyMigrationsResult {
+ /** Tags applied by this call, in order. */
+ readonly applied: readonly string[];
+ /** Tags recorded without running, because the catalog already held them (the baseline). */
+ readonly adopted: readonly string[];
+ /** Recorded migrations whose committed file changed since; the change never runs. */
+ readonly edited: readonly string[];
+ /** Recorded migrations that are not committed here. */
+ readonly unknown: number;
+ /** Time spent waiting for another session's migration lock. */
+ readonly lockWaitMs: number;
+}
+
+/** A deploy waits this long for another instance to finish migrating, then fails. */
+const LOCK_WAIT_MS = 5 * 60_000;
+/**
+ * Longest wait for one table lock. Past it the migration rolls back and is
+ * retried: a longer wait would queue every other query on that table behind it.
+ */
+const LOCK_TIMEOUT_MS = 5_000;
+/** Tries per migration when a table lock is not granted within the lock timeout. */
+const LOCK_ATTEMPTS = 3;
+const LOCK_POLL_MS = 1_000;
+const LOCK_REPORT_MS = 30_000;
+/** Shown in pg_stat_activity, so a waiting instance can name the lock holder. */
+const APPLICATION_NAME = "appkit-migrate";
+/** Lets the server cancel a migration whose instance died. Linux servers only. */
+const CONNECTION_CHECK_INTERVAL = "10s";
+
+/** lock_not_available: a table lock was not granted within the lock timeout. */
+const LOCK_NOT_AVAILABLE = "55P03";
+/** SQLSTATE classes of failures the existing rows cause: data_exception and integrity_constraint_violation. */
+const DATA_FAILURE_CLASSES = ["22", "23"];
+
+/**
+ * A step of applying migrations failed. Each migration commits in its own
+ * transaction: the failing one rolled back, the ones before it stay applied.
+ */
+export class MigrationApplyError extends Error {
+ /** The migration that failed and rolled back; undefined when another step failed. */
+ readonly failed?: string;
+ /** Committed migrations still not applied, the failed one first. */
+ readonly pending: readonly string[];
+ /** Tags this run applied before the failure. */
+ readonly applied: readonly string[];
+ /** Tags this run recorded as applied (adopted) before the failure. */
+ readonly adopted: readonly string[];
+ /** SQLSTATE of the failing statement, when the driver reported one. */
+ readonly code?: string;
+
+ constructor(details: {
+ /** What failed when no migration did, e.g. "Connecting to the database". */
+ readonly step: string;
+ readonly failed?: string;
+ readonly pending?: readonly string[];
+ readonly applied?: readonly string[];
+ readonly adopted?: readonly string[];
+ readonly hint?: string;
+ readonly cause?: unknown;
+ }) {
+ const pending = details.pending ?? [];
+ const applied = details.applied ?? [];
+ const adopted = details.adopted ?? [];
+ const code = sqlStateOf(details.cause);
+ const systemCode = code ? undefined : systemCodeOf(details.cause);
+ const reason = code
+ ? ` (SQLSTATE ${code})`
+ : systemCode
+ ? ` (${systemCode})`
+ : "";
+ const parts = [
+ details.failed
+ ? `Migration ${details.failed} failed${reason} and was rolled back.`
+ : `${details.step} failed${reason}.`,
+ ];
+ if (adopted.length > 0) {
+ parts.push(
+ `${adopted.join(", ")} stays recorded as applied: its tables already existed.`,
+ );
+ }
+ if (applied.length > 0) {
+ parts.push(`Applied before the failure: ${applied.join(", ")}.`);
+ }
+ parts.push(
+ pending.length > 0
+ ? `Not applied: ${pending.join(", ")}.`
+ : "No migration was applied.",
+ );
+ if (details.hint) parts.push(details.hint);
+ super(parts.join(" "), { cause: details.cause });
+ this.name = "MigrationApplyError";
+ this.failed = details.failed;
+ this.pending = Object.freeze([...pending]);
+ this.applied = Object.freeze([...applied]);
+ this.adopted = Object.freeze([...adopted]);
+ this.code = code;
+ }
+}
+
+/**
+ * Nothing is recorded yet and the database holds only part of what
+ * 0000_baseline declares: neither running nor adopting the baseline would be safe.
+ */
+export class MigrationBaselineMismatchError extends Error {
+ readonly problems: readonly string[];
+
+ constructor(schemaName: string, problems: readonly string[]) {
+ super(
+ `Cannot adopt ${BASELINE_TAG}: schema "${schemaName}" has no recorded migrations and only part of the baseline: ${problems.join("; ")}. ` +
+ "Create the missing tables and columns (or drop the partial ones), or regenerate the baseline with `appkit db introspect` against this database.",
+ );
+ this.name = "MigrationBaselineMismatchError";
+ this.problems = Object.freeze([...problems]);
+ }
+}
+
+/** Why the committed history cannot be applied over the recorded one. */
+type HistoryRefusal =
+ /** Older than the last recorded migration and never applied, so they would never run. */
+ | { readonly stranded: readonly string[]; readonly last: string }
+ /** Files and rows at one timestamp that cannot be told apart. */
+ | { readonly ambiguous: AmbiguousTimestamp }
+ | { readonly edited: readonly string[] }
+ | {
+ readonly diverged: {
+ readonly unrecorded: readonly string[];
+ readonly unknown: readonly RecordedMigration[];
+ };
+ };
+
+/**
+ * The committed migrations and the recorded ones disagree in a way the
+ * migrator refuses to resolve by itself. Nothing was applied.
+ */
+export class MigrationHistoryError extends Error {
+ constructor(
+ schemaName: string,
+ readonly refusal: HistoryRefusal,
+ ) {
+ super(refusalMessage(schemaName, refusal));
+ this.name = "MigrationHistoryError";
+ }
+}
+
+function refusalMessage(schemaName: string, refusal: HistoryRefusal): string {
+ if ("stranded" in refusal) {
+ return strandedMessage(schemaName, refusal.stranded, refusal.last);
+ }
+ if ("ambiguous" in refusal) {
+ return ambiguousMessage(schemaName, refusal.ambiguous);
+ }
+ if ("edited" in refusal) return editedMessage(schemaName, refusal.edited);
+ return divergedMessage(schemaName, refusal.diverged);
+}
+
+function strandedMessage(
+ schemaName: string,
+ stranded: readonly string[],
+ last: string,
+): string {
+ const many = stranded.length > 1;
+ return (
+ `Migration${many ? "s" : ""} ${stranded.join(", ")} ${many ? "are" : "is"} older than ${last}, which schema "${schemaName}" already recorded, ` +
+ `and ${many ? "were" : "was"} never applied, so ${many ? "they" : "it"} would never run. This happens when migrations from parallel branches merge. ` +
+ `${MIGRATION_HISTORY_REWRITE} No migration was applied.`
+ );
+}
+
+function ambiguousMessage(
+ schemaName: string,
+ { when, files, recorded }: AmbiguousTimestamp,
+): string {
+ return (
+ `Schema "${schemaName}" recorded ${recorded} migration${recorded === 1 ? "" : "s"} at ${new Date(when).toISOString()}, ` +
+ `and ${files.length} ${files.length === 1 ? "is" : "are"} committed with that timestamp (${tags(files).join(", ")}), none with a recorded hash. ` +
+ "The migrator cannot tell which of them ran and changed since, and which never ran. " +
+ `Compare the hash column of ${journalTable(schemaName)} with the sha256 of each file's versions in version control. ` +
+ "Restore the applied versions; for the others, delete the .sql file, snapshot and journal entry and generate the migration again from schema.ts. " +
+ "No migration was applied."
+ );
+}
+
+function editedMessage(schemaName: string, edited: readonly string[]): string {
+ const many = edited.length > 1;
+ return (
+ `Migration${many ? "s" : ""} ${edited.join(", ")} changed after schema "${schemaName}" applied ${many ? "them" : "it"}, ` +
+ `so ${many ? "their files are" : "its file is"} not what this branch ran. ` +
+ `Restore ${many ? "each" : "the"} file to the version this branch applied and put the change in a new migration. ` +
+ "If the migration failed on deploy because of data, repair the rows on the deploy branch and deploy the unchanged file again. " +
+ "No migration was applied."
+ );
+}
+
+function divergedMessage(
+ schemaName: string,
+ {
+ unrecorded,
+ unknown,
+ }: { unrecorded: readonly string[]; unknown: readonly RecordedMigration[] },
+): string {
+ const created = unknown
+ .map((row) =>
+ row.createdAt === null
+ ? "no timestamp"
+ : new Date(row.createdAt).toISOString(),
+ )
+ .join(", ");
+ return (
+ `Schema "${schemaName}" recorded ${unknown.length} migration${unknown.length === 1 ? "" : "s"} this checkout does not have (created ${created}), ` +
+ `and ${unrecorded.join(", ")} ${unrecorded.length === 1 ? "is" : "are"} committed here but not applied. ` +
+ "The deploy branch ran migrations from a commit this one lacks. " +
+ "Deploy a commit whose journal contains the recorded migrations, or merge them into main unchanged, before main's own migrations. " +
+ "No migration was applied."
+ );
+}
+
+/** What pg_catalog holds at the journal's name, seen from the migrating session. */
+interface JournalRelation {
+ readonly relkind: string;
+ readonly owner: string;
+ readonly schemaOwner: string;
+ /** The role the migrator connects as. */
+ readonly currentUser: string;
+ /** Row-level security is enabled, so a policy runs on every read by a non-owner. */
+ readonly rowSecurity: boolean;
+ /** The current role owns it or inherits its owner, or its owner is the schema's. */
+ readonly trusted: boolean;
+}
+
+/** What the migrator is about to do with the journal. */
+export type JournalUse = "read" | "record";
+
+/** Why the relation at the journal's name is refused for a use. */
+type JournalRefusal =
+ /** Not an ordinary table. */
+ | "kind"
+ /** Recording into a table of an untrusted owner's. */
+ | "owner"
+ /** Reading a table of an untrusted owner's under row-level security. */
+ | "row-security";
+
+/**
+ * A relation at the journal's name can run its owner's code with the app's
+ * privileges: a view when read, a row-security policy when a non-owner
+ * reads, and triggers, rules or column defaults when recorded into. So only
+ * an ordinary table is used, and one of an untrusted owner's only for a read
+ * without row-level security.
+ */
+export function journalRefusal(
+ relation: JournalRelation,
+ use: JournalUse,
+): JournalRefusal | undefined {
+ if (relation.relkind !== "r") return "kind";
+ if (relation.trusted) return undefined;
+ if (use === "record") return "owner";
+ return relation.rowSecurity ? "row-security" : undefined;
+}
+
+/** pg_class.relkind, for the error message. */
+const RELATION_KINDS: Readonly> = {
+ r: "a table",
+ p: "a partitioned table",
+ v: "a view",
+ m: "a materialized view",
+ f: "a foreign table",
+ S: "a sequence",
+};
+
+/** The relation at the journal's name cannot be used as the journal (see journalRefusal). Nothing was applied. */
+export class MigrationJournalError extends Error {
+ constructor(
+ schemaName: string,
+ relation: JournalRelation,
+ refusal: JournalRefusal,
+ ) {
+ super(
+ `${journalRefusalMessage(schemaName, relation, refusal)} No migration was applied.`,
+ );
+ this.name = "MigrationJournalError";
+ }
+}
+
+function journalRefusalMessage(
+ schemaName: string,
+ relation: JournalRelation,
+ refusal: JournalRefusal,
+): string {
+ const table = journalTable(schemaName);
+ const untrusted = `The migrator connects as "${relation.currentUser}", which neither owns it nor inherits "${relation.owner}"`;
+ // ALTER TABLE ... OWNER TO the app's role fails on Lakebase ("must be able to SET ROLE").
+ const transfer = `have Lakebase move the table to "${relation.currentUser}", since no Postgres role can hand it over. Then deploy again.`;
+ switch (refusal) {
+ case "kind": {
+ const kind =
+ RELATION_KINDS[relation.relkind] ??
+ `a relation of kind "${relation.relkind}"`;
+ return (
+ `${table} is ${kind} owned by "${relation.owner}". ` +
+ "The migrator reads and records applied migrations only in an ordinary table. Drop or rename it, then deploy again."
+ );
+ }
+ case "owner":
+ return (
+ `${table} is a table owned by "${relation.owner}". ${untrusted}, ` +
+ `and records applied migrations only in a table owned by its role or by "${relation.schemaOwner}", the owner of schema "${schemaName}", ` +
+ "because a trigger, rule or column default on another role's table would run that role's code as the app. " +
+ `Have "${relation.owner}" run the migration, or ${transfer}`
+ );
+ case "row-security":
+ return (
+ `${table} is a table owned by "${relation.owner}" with row-level security enabled. ${untrusted}, ` +
+ "so a policy would run that role's code as the app on every read. " +
+ `Have "${relation.owner}" disable row-level security on it, or ${transfer}`
+ );
+ }
+}
+
+/** The migration lock stayed taken past the wait limit. */
+class MigrationLockWaitError extends Error {
+ constructor(readonly holder: string | undefined) {
+ super("migration lock wait timed out");
+ }
+}
+
+const SQLSTATE = /^[0-9A-Z]{5}$/;
+const SYSTEM_CODE = /^E[A-Z0-9_]+$/;
+
+/** drizzle and the connector wrap driver errors; the code lives somewhere on the cause chain. */
+function findCode(
+ error: unknown,
+ matches: (code: string) => boolean,
+): string | undefined {
+ let current = error;
+ for (let depth = 0; depth < 5 && current; depth++) {
+ const code = (current as { code?: unknown }).code;
+ if (typeof code === "string" && matches(code)) return code;
+ current = (current as { cause?: unknown }).cause;
+ }
+ return undefined;
+}
+
+// No SQLSTATE class starts with "E"; Node system errors (EPIPE, ECONNREFUSED, …) all do.
+function sqlStateOf(error: unknown): string | undefined {
+ return findCode(error, (code) => SQLSTATE.test(code) && code[0] !== "E");
+}
+
+function systemCodeOf(error: unknown): string | undefined {
+ return findCode(error, (code) => SYSTEM_CODE.test(code));
+}
+
+export function quoteIdentifier(name: string): string {
+ return `"${name.replace(/"/g, '""')}"`;
+}
+
+function journalTable(schemaName: string): string {
+ return `${quoteIdentifier(schemaName)}.${quoteIdentifier(MIGRATIONS_TABLE)}`;
+}
+
+/** One lock per app schema, so concurrent instances apply in turn. */
+export function migrationLockKey(schemaName: string): string {
+ return createHash("sha256")
+ .update(`appkit:migrations:${schemaName}`)
+ .digest()
+ .readBigInt64BE(0)
+ .toString();
+}
+
+type QueryClient = Pick;
+
+/** drizzle-kit's separator; drizzle-orm's reader splits the file on it, so joining on it gives the file back. */
+const STATEMENT_BREAKPOINT = "--> statement-breakpoint";
+
+function sha256(text: string): string {
+ return createHash("sha256").update(text).digest("hex");
+}
+
+/**
+ * The hashes any checkout of this file records. drizzle hashes the bytes as
+ * read, and git's autocrlf checks the same committed file out with CRLF on
+ * Windows, so one file can be recorded under either line ending.
+ */
+function lineEndingHashes(content: string, hash: string): string[] {
+ const lf = content.replace(/\r\n/g, "\n");
+ const crlf = lf.replace(/\n/g, "\r\n");
+ return [...new Set([hash, sha256(lf), sha256(crlf)])];
+}
+
+/**
+ * drizzle-orm reports any read failure as "No file … found", so read the files
+ * again to name the one that fails and why.
+ */
+function unreadableMigrationError(
+ folder: string,
+ journal: Journal,
+ error: unknown,
+): MigrationFilesError {
+ for (const entry of journal.entries) {
+ const file = migrationFile(folder, entry.tag);
+ try {
+ fs.readFileSync(file);
+ } catch (cause) {
+ return new MigrationFilesError(
+ `Cannot read ${file}: ${cause instanceof Error ? cause.message : String(cause)}. Check that the app can read it.`,
+ { cause },
+ );
+ }
+ }
+ return new MigrationFilesError(
+ `Cannot read the migrations in ${folder}: ${error instanceof Error ? error.message : String(error)}.`,
+ { cause: error },
+ );
+}
+
+/** Every committed migration, in journal order. Fails on a missing file before connecting. */
+function readMigrations(folder: string, journal: Journal): MigrationFile[] {
+ for (const entry of journal.entries) {
+ const file = migrationFile(folder, entry.tag);
+ if (!fs.existsSync(file)) {
+ throw new MigrationFilesError(
+ `Missing ${file}, listed in meta/_journal.json. Restore it from version control.`,
+ );
+ }
+ }
+ let files: ReturnType;
+ try {
+ // drizzle-orm's reader, so `hash` matches what drizzle-kit records.
+ files = readMigrationFiles({ migrationsFolder: folder });
+ } catch (error) {
+ throw unreadableMigrationError(folder, journal, error);
+ }
+ return journal.entries.map((entry, index) => {
+ const file = files[index];
+ if (!file) {
+ throw new MigrationFilesError(
+ `Cannot read ${entry.tag}.sql in ${folder}. Restore it from version control.`,
+ );
+ }
+ return {
+ tag: entry.tag,
+ idx: entry.idx,
+ when: entry.when,
+ hash: file.hash,
+ hashes: lineEndingHashes(file.sql.join(STATEMENT_BREAKPOINT), file.hash),
+ statements: file.sql,
+ };
+ });
+}
+
+function historyRefusal(
+ history: MigrationHistory,
+ files: readonly MigrationFile[],
+ onDrift: DriftPolicy,
+): HistoryRefusal | undefined {
+ const ambiguous = history.ambiguous[0];
+ if (ambiguous) return { ambiguous };
+ const diverged = onDrift === "refuse" && branchDeployedFirst(history);
+ if (history.stranded.length > 0) {
+ if (diverged) return divergence(history);
+ const last =
+ files.find((file) => file.when === history.lastRecorded)?.tag ??
+ `the migration recorded at ${new Date(history.lastRecorded ?? 0).toISOString()}`;
+ return { stranded: tags(history.stranded), last };
+ }
+ if (onDrift === "warn") return undefined;
+ if (history.edited.length > 0) return { edited: tags(history.edited) };
+ if (diverged) return divergence(history);
+ return undefined;
+}
+
+function branchDeployedFirst(history: MigrationHistory): boolean {
+ const unrecorded = history.stranded.length + history.pending.length;
+ return unrecorded > 0 && history.unknown.length > 0;
+}
+
+function divergence(history: MigrationHistory): HistoryRefusal {
+ return {
+ diverged: {
+ unrecorded: tags([...history.stranded, ...history.pending]),
+ unknown: history.unknown,
+ },
+ };
+}
+
+/** The relation at the journal's name, as pg_catalog describes it; null when there is none. */
+export async function readJournalRelation(
+ client: QueryClient,
+ schemaName: string,
+): Promise {
+ // pg_catalog needs no privileges, so a missing grant is not mistaken for a missing table.
+ const { rows } = await client.query<{
+ relkind: string;
+ owner: string;
+ schema_owner: string;
+ current_user: string;
+ row_security: boolean;
+ trusted: boolean;
+ }>(
+ `select c.relkind::text as relkind,
+ pg_catalog.pg_get_userbyid(c.relowner) as owner,
+ pg_catalog.pg_get_userbyid(n.nspowner) as schema_owner,
+ current_user::text as current_user,
+ c.relrowsecurity as row_security,
+ (pg_catalog.pg_has_role(current_user, c.relowner, 'USAGE') or c.relowner = n.nspowner) as trusted
+ from pg_catalog.pg_class c
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
+ where n.nspname = $1 and c.relname = $2`,
+ [schemaName, MIGRATIONS_TABLE],
+ );
+ const found = rows[0];
+ if (!found) return null;
+ return {
+ relkind: found.relkind,
+ owner: found.owner,
+ schemaOwner: found.schema_owner,
+ currentUser: found.current_user,
+ rowSecurity: found.row_security,
+ trusted: found.trusted,
+ };
+}
+
+/**
+ * Whether the journal table exists. Every read of the journal and every
+ * record into it starts here, so a relation at its name that is unfit for
+ * that use is refused (see journalRefusal).
+ */
+async function journalTableExists(
+ client: QueryClient,
+ schemaName: string,
+ use: JournalUse,
+): Promise {
+ const relation = await readJournalRelation(client, schemaName);
+ if (!relation) return false;
+ const refusal = journalRefusal(relation, use);
+ if (refusal) throw new MigrationJournalError(schemaName, relation, refusal);
+ return true;
+}
+
+/** The journal table's rows; none when the table does not exist yet. */
+async function readRecordedMigrations(
+ client: QueryClient,
+ schemaName: string,
+): Promise {
+ if (!(await journalTableExists(client, schemaName, "read"))) return [];
+ const { rows } = await client.query<{
+ hash: string;
+ created_at: string | number | null;
+ }>(`select hash, created_at from ${journalTable(schemaName)} order by id`);
+ return rows.map((row) => ({
+ hash: row.hash,
+ createdAt: row.created_at === null ? null : Number(row.created_at),
+ }));
+}
+
+/** Session settings for migrating, each added to `reset` once set. */
+async function prepareMigrationSession(
+ client: QueryClient,
+ reset: string[],
+): Promise {
+ await client.query("SET statement_timeout = 0");
+ reset.push("statement_timeout");
+ await client.query(`SET application_name = '${APPLICATION_NAME}'`);
+ reset.push("application_name");
+ try {
+ await client.query(
+ `SET client_connection_check_interval = '${CONNECTION_CHECK_INTERVAL}'`,
+ );
+ reset.push("client_connection_check_interval");
+ } catch (error) {
+ // Postgres before 14, or a server that cannot poll sockets. With
+ // statement_timeout off, nothing else ends a dead instance's statement.
+ logger.warn(
+ "client_connection_check_interval not set (%s). If this instance dies while a migration statement runs, the server notices only once the statement ends, and the statement keeps its locks until then. " +
+ "To end it sooner, find its pid in pg_stat_activity (application_name '%s') and run select pg_terminate_backend(pid).",
+ error instanceof Error ? error.message : String(error),
+ APPLICATION_NAME,
+ );
+ }
+}
+
+/** pg_locks splits a bigint advisory key into classid (high 32 bits) and objid (low 32 bits). */
+function lockKeyParts(key: string): [string, string] {
+ const unsigned = BigInt.asUintN(64, BigInt(key));
+ return [(unsigned >> 32n).toString(), (unsigned & 0xffffffffn).toString()];
+}
+
+/** "pid 123 (appkit-migrate, active)" for the session holding the migration lock. */
+async function migrationLockHolder(
+ client: QueryClient,
+ key: string,
+): Promise {
+ const [classid, objid] = lockKeyParts(key);
+ const { rows } = await client.query<{
+ pid: number;
+ application_name: string | null;
+ state: string | null;
+ }>(
+ `select a.pid, a.application_name, a.state
+ from pg_catalog.pg_locks l
+ join pg_catalog.pg_stat_activity a on a.pid = l.pid
+ where l.locktype = 'advisory' and l.granted
+ and l.database = (select d.oid from pg_catalog.pg_database d where d.datname = current_database())
+ and l.classid = $1::oid and l.objid = $2::oid and l.objsubid = 1`,
+ [classid, objid],
+ );
+ const holder = rows[0];
+ if (!holder) return undefined;
+ const details = [holder.application_name, holder.state].filter(Boolean);
+ return `pid ${holder.pid}${details.length > 0 ? ` (${details.join(", ")})` : ""}`;
+}
+
+/**
+ * Take the per-schema advisory lock, polling so the wait has a limit and the
+ * log names the holder. Returns how long it waited.
+ */
+async function acquireMigrationLock(
+ client: QueryClient,
+ schemaName: string,
+ waitMs: number,
+): Promise {
+ const key = migrationLockKey(schemaName);
+ const started = Date.now();
+ let reportAt = started;
+ for (;;) {
+ const { rows } = await client.query<{ locked: boolean }>(
+ "select pg_catalog.pg_try_advisory_lock($1::bigint) as locked",
+ [key],
+ );
+ if (rows[0]?.locked) return Date.now() - started;
+ const waited = Date.now() - started;
+ if (waited >= waitMs || Date.now() >= reportAt) {
+ const holder = await migrationLockHolder(client, key).catch(
+ () => undefined,
+ );
+ if (waited >= waitMs) throw new MigrationLockWaitError(holder);
+ logger.info(
+ "Waiting for another session to finish migrating schema %s (lock held by %s)",
+ schemaName,
+ holder ?? "an unknown session",
+ );
+ reportAt = Date.now() + LOCK_REPORT_MS;
+ }
+ await sleep(Math.min(LOCK_POLL_MS, waitMs - waited));
+ }
+}
+
+export async function inTransaction(
+ client: QueryClient,
+ work: () => Promise,
+): Promise {
+ await client.query("begin");
+ try {
+ const result = await work();
+ await client.query("commit");
+ return result;
+ } catch (error) {
+ await client.query("rollback").catch(() => undefined);
+ throw error;
+ }
+}
+
+/** drizzle-orm's own journal table, so drizzle-kit reads and extends it too. */
+async function ensureJournalTable(
+ client: QueryClient,
+ schemaName: string,
+): Promise {
+ if (await journalTableExists(client, schemaName, "record")) return;
+ // CREATE SCHEMA checks CREATE on the database before IF NOT EXISTS, which
+ // an app that only owns its schema does not have.
+ const { rows } = await client.query(
+ "select 1 from pg_catalog.pg_namespace where nspname = $1",
+ [schemaName],
+ );
+ if (rows.length === 0) {
+ await client.query(
+ `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(schemaName)}`,
+ );
+ }
+ // Not IF NOT EXISTS: a relation that appeared at this name since the check
+ // fails the transaction instead of receiving the record.
+ await client.query(
+ `CREATE TABLE ${journalTable(schemaName)} (
+ id SERIAL PRIMARY KEY,
+ hash text NOT NULL,
+ created_at bigint
+ )`,
+ );
+}
+
+/** Record a migration the way drizzle-orm's migrator does: its file hash and the journal's `when`. */
+async function recordMigration(
+ client: QueryClient,
+ schemaName: string,
+ file: MigrationFile,
+): Promise {
+ await client.query(
+ `insert into ${journalTable(schemaName)} ("hash", "created_at") values($1, $2)`,
+ [file.hash, file.when],
+ );
+}
+
+/**
+ * Run one migration and record it in one transaction. A table lock not granted
+ * within the lock timeout rolls it back; it is retried LOCK_ATTEMPTS times.
+ */
+async function applyMigration(
+ client: QueryClient,
+ schemaName: string,
+ file: MigrationFile,
+ lockTimeoutMs: number,
+): Promise {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ await inTransaction(client, async () => {
+ await ensureJournalTable(client, schemaName);
+ for (const statement of file.statements) {
+ if (statement.trim()) await client.query(statement);
+ }
+ await recordMigration(client, schemaName, file);
+ });
+ return;
+ } catch (error) {
+ if (
+ attempt >= LOCK_ATTEMPTS ||
+ sqlStateOf(error) !== LOCK_NOT_AVAILABLE
+ ) {
+ throw error;
+ }
+ logger.warn(
+ "Migration %s waited over %dms for a table lock (try %d of %d); retrying",
+ file.tag,
+ lockTimeoutMs,
+ attempt,
+ LOCK_ATTEMPTS,
+ );
+ await sleep(Math.min(attempt * LOCK_POLL_MS, lockTimeoutMs));
+ }
+ }
+}
+
+/** The tables and columns a migration snapshot (meta/NNNN_snapshot.json) declares in one schema. */
+function snapshotTables(
+ folder: string,
+ idx: number,
+ schemaName: string,
+): Map {
+ const file = snapshotFile(folder, idx);
+ if (!fs.existsSync(file)) {
+ throw new MigrationFilesError(
+ `Missing ${file} for ${BASELINE_TAG}. Restore it from version control; it lists the tables the baseline adopts.`,
+ );
+ }
+ const snapshot = readJsonFile<{
+ tables?: Record<
+ string,
+ { name: string; schema?: string; columns: Record }
+ >;
+ }>(file);
+ const tables = new Map();
+ for (const table of Object.values(snapshot.tables ?? {})) {
+ if ((table.schema || "public") !== schemaName) continue;
+ tables.set(table.name, Object.keys(table.columns));
+ }
+ return tables;
+}
+
+type BaselineState =
+ | { readonly kind: "absent" }
+ | { readonly kind: "present" }
+ | { readonly kind: "partial"; readonly problems: readonly string[] };
+
+/** Compare the baseline's tables and columns with pg_catalog. */
+async function baselineState(
+ client: QueryClient,
+ options: ApplyMigrationsOptions,
+ baseline: MigrationFile,
+): Promise {
+ const declared = snapshotTables(
+ options.migrationsFolder,
+ baseline.idx,
+ options.schemaName,
+ );
+ if (declared.size === 0) return { kind: "absent" };
+ const { rows } = await client.query<{
+ table_name: string;
+ column_name: string | null;
+ }>(
+ `select c.relname::text as table_name, a.attname::text as column_name
+ from pg_catalog.pg_class c
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
+ left join pg_catalog.pg_attribute a
+ on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
+ where n.nspname = $1 and c.relkind in ('r', 'p')
+ and c.relname = any($2::text[])`,
+ [options.schemaName, [...declared.keys()]],
+ );
+ const found = new Map>();
+ for (const row of rows) {
+ const columns = found.get(row.table_name) ?? new Set();
+ if (row.column_name) columns.add(row.column_name);
+ found.set(row.table_name, columns);
+ }
+ if (found.size === 0) return { kind: "absent" };
+
+ const problems: string[] = [];
+ for (const [table, columns] of declared) {
+ const qualified = `${options.schemaName}.${table}`;
+ const present = found.get(table);
+ if (!present) {
+ problems.push(`table ${qualified} does not exist`);
+ continue;
+ }
+ const missing = columns.filter((column) => !present.has(column));
+ if (missing.length > 0) {
+ problems.push(
+ `table ${qualified} is missing ${missing.length === 1 ? "column" : "columns"} ${missing.join(", ")}`,
+ );
+ }
+ }
+ return problems.length > 0
+ ? { kind: "partial", problems }
+ : { kind: "present" };
+}
+
+/** Unlock and reset the session. A connection whose cleanup fails is destroyed, not reused. */
+async function releaseMigrationClient(
+ client: PoolClient,
+ lockKey: string | undefined,
+ reset: readonly string[],
+): Promise {
+ const cleanup: Array<() => Promise> = [];
+ if (lockKey) {
+ cleanup.push(() =>
+ client.query("select pg_catalog.pg_advisory_unlock($1::bigint)", [
+ lockKey,
+ ]),
+ );
+ }
+ for (const name of [...reset].reverse()) {
+ cleanup.push(() => client.query(`RESET ${name}`));
+ }
+ let cleanupError: Error | undefined;
+ for (const step of cleanup) {
+ try {
+ await step();
+ } catch (error) {
+ cleanupError ??=
+ error instanceof Error ? error : new Error(String(error));
+ }
+ }
+ client.release(cleanupError);
+}
+
+function tags(files: readonly MigrationFile[]): string[] {
+ return files.map((file) => file.tag);
+}
+
+function duration(ms: number): string {
+ if (ms >= 60_000) {
+ const minutes = Math.round(ms / 60_000);
+ return `${minutes} minute${minutes === 1 ? "" : "s"}`;
+ }
+ if (ms >= 1_000) return `${Math.round(ms / 1_000)}s`;
+ return `${ms}ms`;
+}
+
+/** How the branch's recorded migrations differ from the committed ones. */
+interface MigrationDrift {
+ /** Committed, not recorded, newer than every recorded one. */
+ readonly pending: readonly string[];
+ /** Committed, not recorded, older than the last recorded one. */
+ readonly stranded: readonly string[];
+ /** Recorded, but the committed file changed since: the branch ran another version. */
+ readonly edited: readonly string[];
+ /** Recorded rows no committed migration matches: the branch is ahead of the checkout. */
+ readonly unknown: number;
+}
+
+function driftOf(
+ history: ReturnType,
+): MigrationDrift {
+ return {
+ pending: tags(history.pending),
+ stranded: tags(history.stranded),
+ edited: tags(history.edited),
+ unknown: history.unknown.length,
+ };
+}
+
+function committedMigrations(folder: string): MigrationFile[] {
+ const journal = readJournal(folder);
+ return journal ? readMigrations(folder, journal) : [];
+}
+
+/** Read without the lock; markMigrationsApplied checks again under it. */
+export async function readMigrationDrift(
+ client: QueryClient,
+ options: ApplyMigrationsOptions & {
+ readonly ignoreHashes?: readonly string[];
+ },
+): Promise {
+ const ignored = new Set(options.ignoreHashes);
+ const recorded = await readRecordedMigrations(client, options.schemaName);
+ return driftOf(
+ reconcileMigrations(
+ committedMigrations(options.migrationsFolder),
+ recorded.filter((row) => !ignored.has(row.hash)),
+ ),
+ );
+}
+
+/** The branch ran these migrations as they were before an edit, so the committed history is not what it holds. */
+export function editedReason(edited: readonly string[]): string {
+ return `it applied ${edited.join(", ")} before ${edited.length === 1 ? "its file" : "their files"} changed`;
+}
+
+/** Why the branch's history is not the committed one plus toRecord; undefined when it is. */
+function driftReason(
+ drift: MigrationDrift,
+ toRecord: readonly string[],
+): string | undefined {
+ const notApplied = drift.pending.filter((tag) => !toRecord.includes(tag));
+ const recorded = toRecord.filter((tag) => !drift.pending.includes(tag));
+ const reasons = [
+ drift.unknown > 0
+ ? `it records ${drift.unknown} migration${drift.unknown === 1 ? "" : "s"} this checkout does not have`
+ : "",
+ drift.stranded.length > 0 ? `it skipped ${drift.stranded.join(", ")}` : "",
+ drift.edited.length > 0 ? editedReason(drift.edited) : "",
+ notApplied.length > 0 ? `it has not applied ${notApplied.join(", ")}` : "",
+ recorded.length > 0 ? `it already records ${recorded.join(", ")}` : "",
+ ].filter(Boolean);
+ return reasons.length > 0 ? reasons.join("; ") : undefined;
+}
+
+/**
+ * Record migrations as applied without running them: the branch already holds
+ * what they describe. Under the migration lock, and only when they are exactly
+ * the branch's pending migrations, so DDL the branch never ran is not recorded.
+ */
+export async function markMigrationsApplied(
+ pool: Pick,
+ options: ApplyMigrationsOptions,
+ toRecord: readonly string[],
+): Promise {
+ const files = committedMigrations(options.migrationsFolder);
+ const missing = toRecord.filter(
+ (tag) => !files.some((file) => file.tag === tag),
+ );
+ if (missing.length > 0) {
+ throw new MigrationFilesError(
+ `Cannot record ${missing.join(", ")} as applied: not in ${options.migrationsFolder}/meta/_journal.json.`,
+ );
+ }
+ const { schemaName } = options;
+ const client = await pool.connect();
+ const reset: string[] = [];
+ let locked = false;
+ try {
+ await prepareMigrationSession(client, reset);
+ await acquireMigrationLock(
+ client,
+ schemaName,
+ options.lockWaitMs ?? LOCK_WAIT_MS,
+ );
+ locked = true;
+ const history = reconcileMigrations(
+ files,
+ await readRecordedMigrations(client, schemaName),
+ );
+ const reason = driftReason(driftOf(history), toRecord);
+ if (reason) {
+ throw new Error(
+ `Schema "${schemaName}" changed while this ran (${reason}), so nothing was recorded.`,
+ );
+ }
+ await inTransaction(client, async () => {
+ await ensureJournalTable(client, schemaName);
+ for (const file of history.pending) {
+ await recordMigration(client, schemaName, file);
+ }
+ });
+ } catch (error) {
+ if (!(error instanceof MigrationLockWaitError)) throw error;
+ throw new Error(
+ `${error.holder ? `Session ${error.holder}` : "Another session"} held the migration lock of schema "${schemaName}" for over ${duration(options.lockWaitMs ?? LOCK_WAIT_MS)}, so nothing was recorded. Rerun once it finishes.`,
+ { cause: error },
+ );
+ } finally {
+ await releaseMigrationClient(
+ client,
+ locked ? migrationLockKey(schemaName) : undefined,
+ reset,
+ );
+ }
+}
+
+/**
+ * Apply every committed migration the database has not recorded yet.
+ *
+ * Runs on one connection as the connecting identity, which owns what it
+ * creates (see ownership.ts). The recorded history is read first without a
+ * lock; only when something is pending does it take the per-schema advisory
+ * lock and read again. Each migration then runs and is recorded in its own
+ * transaction, so a failure keeps the ones before it.
+ *
+ * Fails closed, changing nothing, when a committed migration is older than the
+ * last recorded one but was never applied, or when the files and rows at one
+ * timestamp cannot be paired.
+ *
+ * Baseline adoption: when nothing is recorded yet and `0000_baseline` comes
+ * first, the baseline's tables are looked up in pg_catalog. None present → it
+ * runs like any migration. All present → it is recorded as applied, in its own
+ * transaction, and only later migrations run. Anything in between →
+ * MigrationBaselineMismatchError, nothing changes.
+ */
+export async function applyPendingMigrations(
+ pool: Pick,
+ options: ApplyMigrationsOptions,
+): Promise {
+ const journal = readJournal(options.migrationsFolder);
+ if (!journal || journal.entries.length === 0) {
+ return { applied: [], adopted: [], edited: [], unknown: 0, lockWaitMs: 0 };
+ }
+ const files = readMigrations(options.migrationsFolder, journal);
+ const { schemaName } = options;
+ const lockWaitMs = options.lockWaitMs ?? LOCK_WAIT_MS;
+ const lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;
+ const onDrift = options.onDrift ?? "warn";
+
+ let client: PoolClient;
+ try {
+ client = await pool.connect();
+ } catch (error) {
+ throw new MigrationApplyError({
+ step: "Connecting to the database",
+ cause: error,
+ });
+ }
+
+ const reset: string[] = [];
+ let locked = false;
+ const applied: string[] = [];
+ const adopted: string[] = [];
+ let pending: string[] = [];
+ let step = "Reading the recorded migrations";
+ let failed: string | undefined;
+ let inBeforeApply = false;
+ try {
+ let history = reconcileMigrations(
+ files,
+ await readRecordedMigrations(client, schemaName),
+ );
+ let refusal = historyRefusal(history, files, onDrift);
+ let waitedMs = 0;
+ if (history.pending.length > 0 && !refusal) {
+ pending = tags(history.pending);
+ step = "Waiting for the migration lock";
+ await prepareMigrationSession(client, reset);
+ waitedMs = await acquireMigrationLock(client, schemaName, lockWaitMs);
+ locked = true;
+ await client.query(`SET lock_timeout = '${lockTimeoutMs}ms'`);
+ reset.push("lock_timeout");
+ step = "Reading the recorded migrations";
+ // Another instance may have applied them while this one waited.
+ history = reconcileMigrations(
+ files,
+ await readRecordedMigrations(client, schemaName),
+ );
+ refusal = historyRefusal(history, files, onDrift);
+ }
+
+ if (refusal) throw new MigrationHistoryError(schemaName, refusal);
+ if (history.edited.length > 0) {
+ logger.warn(
+ "Migrations %s changed after schema %s applied them; the changes never run. Restore the files and put the change in a new migration.",
+ tags(history.edited).join(", "),
+ schemaName,
+ );
+ }
+ if (history.unknown.length > 0) {
+ logger.warn(
+ "Schema %s recorded %d migration(s) that are not committed here. A newer release applied them, or their files were deleted.",
+ schemaName,
+ history.unknown.length,
+ );
+ }
+
+ const toApply = [...history.pending];
+ pending = tags(toApply);
+ if (toApply.length > 0 && options.beforeApply) {
+ inBeforeApply = true;
+ await options.beforeApply(client);
+ inBeforeApply = false;
+ }
+ const baseline = toApply[0];
+ if (history.lastRecorded === null && baseline?.tag === BASELINE_TAG) {
+ failed = BASELINE_TAG;
+ const state = await baselineState(client, options, baseline);
+ if (state.kind === "partial") {
+ throw new MigrationBaselineMismatchError(schemaName, state.problems);
+ }
+ if (state.kind === "present") {
+ await inTransaction(client, async () => {
+ await ensureJournalTable(client, schemaName);
+ await recordMigration(client, schemaName, baseline);
+ });
+ adopted.push(BASELINE_TAG);
+ toApply.shift();
+ pending.shift();
+ }
+ }
+
+ for (const file of toApply) {
+ failed = file.tag;
+ const started = Date.now();
+ await applyMigration(client, schemaName, file, lockTimeoutMs);
+ applied.push(file.tag);
+ pending.shift();
+ logger.info(
+ "Applied migration %s to schema %s in %dms",
+ file.tag,
+ schemaName,
+ Date.now() - started,
+ );
+ }
+ return {
+ applied,
+ adopted,
+ edited: tags(history.edited),
+ unknown: history.unknown.length,
+ lockWaitMs: waitedMs,
+ };
+ } catch (error) {
+ if (
+ inBeforeApply ||
+ error instanceof MigrationBaselineMismatchError ||
+ error instanceof MigrationFilesError ||
+ error instanceof MigrationHistoryError ||
+ error instanceof MigrationJournalError
+ ) {
+ throw error;
+ }
+ const code = sqlStateOf(error);
+ let hint: string | undefined;
+ if (error instanceof MigrationLockWaitError) {
+ const holder = error.holder
+ ? `Session ${error.holder}`
+ : "Another session";
+ hint = `${holder} held the migration lock for over ${duration(lockWaitMs)}. Deploy again once it finishes; if it is stuck, end it with pg_terminate_backend.`;
+ } else if (code === LOCK_NOT_AVAILABLE) {
+ hint = `Another session held a lock on a table this migration changes for over ${duration(lockTimeoutMs)}, ${LOCK_ATTEMPTS} times. Deploy again once the long-running query or transaction finishes.`;
+ } else if (code === INSUFFICIENT_PRIVILEGE) {
+ const ownership = await schemaOwnership(client, schemaName).catch(
+ () => undefined,
+ );
+ hint = ownershipHint(code, ownership);
+ } else if (code && DATA_FAILURE_CLASSES.includes(code.slice(0, 2))) {
+ hint =
+ "It failed on rows already in the database, not on its SQL. Repair those rows, then apply the same migration again. " +
+ "On the deploy branch, repair them as a role with the DATABRICKS_SUPERUSER membership, which someone with CAN USE on the Lakebase project creates, and deploy again.";
+ }
+ throw new MigrationApplyError({
+ step,
+ failed,
+ pending,
+ applied,
+ adopted,
+ hint,
+ cause: error,
+ });
+ } finally {
+ await releaseMigrationClient(
+ client,
+ locked ? migrationLockKey(schemaName) : undefined,
+ reset,
+ );
+ }
+}
diff --git a/packages/appkit/src/database/migrations/history.ts b/packages/appkit/src/database/migrations/history.ts
new file mode 100644
index 000000000..727383e87
--- /dev/null
+++ b/packages/appkit/src/database/migrations/history.ts
@@ -0,0 +1,117 @@
+/** A committed migration: its journal entry plus what drizzle-orm reads from its .sql file. */
+export interface MigrationFile {
+ readonly tag: string;
+ readonly idx: number;
+ /** The journal's `when`, recorded as `created_at`. */
+ readonly when: number;
+ readonly hash: string;
+ readonly hashes: readonly string[];
+ /** The file split on `--> statement-breakpoint`. */
+ readonly statements: readonly string[];
+}
+
+/** One row of the journal table. */
+export interface RecordedMigration {
+ readonly hash: string;
+ readonly createdAt: number | null;
+}
+
+/**
+ * Committed migrations at one `when` that cannot be paired one to one with
+ * the rows recorded at it: more than one of each, or one file with several
+ * rows, none matching by hash.
+ */
+export interface AmbiguousTimestamp {
+ readonly when: number;
+ /** Committed at `when`, none with a recorded hash. */
+ readonly files: readonly MigrationFile[];
+ /** Rows recorded at `when`, none with a committed hash. */
+ readonly recorded: number;
+}
+
+/** Committed migrations compared with what the database recorded. */
+export interface MigrationHistory {
+ /** Not recorded and newer than every recorded migration: applied next, oldest first. */
+ readonly pending: readonly MigrationFile[];
+ /** Not recorded but older than the last recorded migration, so a later one ran first. */
+ readonly stranded: readonly MigrationFile[];
+ /** Recorded, but the committed file changed since; the change never runs. */
+ readonly edited: readonly MigrationFile[];
+ /** Timestamps where the files and rows left after exact matches cannot be paired. */
+ readonly ambiguous: readonly AmbiguousTimestamp[];
+ /** Recorded rows no committed migration matches: a newer release ran, or files were deleted. */
+ readonly unknown: readonly RecordedMigration[];
+ /** `created_at` of the newest recorded migration; null when none is. */
+ readonly lastRecorded: number | null;
+}
+
+type Classified = "pending" | "stranded" | "edited";
+
+function groupBy(
+ items: readonly T[],
+ key: (item: T) => number,
+): Map {
+ const groups = new Map();
+ for (const item of items) {
+ const group = groups.get(key(item)) ?? [];
+ group.push(item);
+ groups.set(key(item), group);
+ }
+ return groups;
+}
+
+/**
+ * Match committed migrations with recorded rows by `when` = `created_at`,
+ * the pair drizzle-orm's migrator writes, one row per file. Two entries can
+ * share a `when` after a hand edit or a merge, so each `when` is reconciled
+ * as a bucket: exact hash matches are consumed first, then one file left
+ * with one row left is an edited migration. Files left with no row are
+ * pending or stranded; rows left with no file are unknown. Any other
+ * remainder is ambiguous, for the caller to refuse rather than guess.
+ */
+export function reconcileMigrations(
+ files: readonly MigrationFile[],
+ recorded: readonly RecordedMigration[],
+): MigrationHistory {
+ const rowsAt = groupBy(
+ recorded.filter((row) => row.createdAt !== null),
+ (row) => row.createdAt as number,
+ );
+ const lastRecorded = rowsAt.size > 0 ? Math.max(...rowsAt.keys()) : null;
+
+ const kind = new Map();
+ const accounted = new Set();
+ const ambiguous: AmbiguousTimestamp[] = [];
+ for (const [when, bucket] of groupBy(files, (file) => file.when)) {
+ const rows = [...(rowsAt.get(when) ?? [])];
+ const unmatched: MigrationFile[] = [];
+ for (const file of bucket) {
+ const match = rows.findIndex((row) => file.hashes.includes(row.hash));
+ if (match === -1) unmatched.push(file);
+ else accounted.add(rows.splice(match, 1)[0] as RecordedMigration);
+ }
+ if (unmatched.length === 0) continue;
+ if (rows.length === 0) {
+ const left =
+ lastRecorded === null || when > lastRecorded ? "pending" : "stranded";
+ for (const file of unmatched) kind.set(file, left);
+ } else if (unmatched.length === 1 && rows.length === 1) {
+ kind.set(unmatched[0] as MigrationFile, "edited");
+ accounted.add(rows[0] as RecordedMigration);
+ } else {
+ ambiguous.push({ when, files: unmatched, recorded: rows.length });
+ for (const row of rows) accounted.add(row);
+ }
+ }
+
+ const of = (classified: Classified) =>
+ files.filter((file) => kind.get(file) === classified);
+ return {
+ pending: of("pending"),
+ stranded: of("stranded"),
+ edited: of("edited"),
+ ambiguous,
+ unknown: recorded.filter((row) => !accounted.has(row)),
+ lastRecorded,
+ };
+}
diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts
new file mode 100644
index 000000000..e09481db2
--- /dev/null
+++ b/packages/appkit/src/database/migrations/ownership.ts
@@ -0,0 +1,95 @@
+// Ownership model: each branch has one owner, the identity its migrations run
+// as, and that identity owns the app's objects there. On the deploy branch it
+// is the app's service principal, which creates the app schema on first start.
+// There is no shared owner role and no SET ROLE: a shared role needs someone
+// holding ADMIN OPTION on it to grant it to every new app, which a deployed
+// app cannot do for itself.
+
+import type { PoolClient } from "pg";
+
+/** insufficient_privilege: "must be owner of …", "permission denied for …". */
+export const INSUFFICIENT_PRIVILEGE = "42501";
+
+/** Who owns the app schema, next to who is connected; owner and canCreate are null when the schema does not exist. */
+interface SchemaOwnership {
+ readonly schemaName: string;
+ readonly owner: string | null;
+ readonly currentUser: string;
+ /** Whether the connecting role holds CREATE on the schema. */
+ readonly canCreate: boolean | null;
+}
+
+/** Read the app schema's owner and the connecting role's CREATE on it. pg_catalog needs no privileges. */
+export async function schemaOwnership(
+ client: Pick,
+ schemaName: string,
+): Promise {
+ const { rows } = await client.query<{
+ owner: string | null;
+ can_create: boolean | null;
+ current_user: string;
+ }>(
+ `select (select pg_catalog.pg_get_userbyid(n.nspowner)
+ from pg_catalog.pg_namespace n where n.nspname = $1) as owner,
+ (select pg_catalog.has_schema_privilege(current_user, n.oid, 'CREATE')
+ from pg_catalog.pg_namespace n where n.nspname = $1) as can_create,
+ current_user::text as current_user`,
+ [schemaName],
+ );
+ return {
+ schemaName,
+ owner: rows[0]?.owner ?? null,
+ currentUser: rows[0]?.current_user ?? "",
+ canCreate: rows[0]?.can_create ?? null,
+ };
+}
+
+/** How to fix a migration that failed for lack of privileges; undefined for any other SQLSTATE. */
+export function ownershipHint(
+ code: string | undefined,
+ ownership?: SchemaOwnership,
+): string | undefined {
+ if (code !== INSUFFICIENT_PRIVILEGE) return undefined;
+ if (ownership && ownership.owner === null) {
+ return (
+ `Role "${ownership.currentUser}" cannot create schema "${ownership.schemaName}". ` +
+ "On the deploy branch that role is the app's service principal: bind the database to the app with CAN_CONNECT_AND_CREATE."
+ );
+ }
+ if (
+ ownership?.schemaName === "public" &&
+ ownership.owner !== ownership.currentUser
+ ) {
+ // Nobody owns public as an app, so the fault is either CREATE or an object another role owns.
+ if (ownership.canCreate === false) {
+ return (
+ `Schema public belongs to "${ownership.owner}", and the app's role "${ownership.currentUser}" has no CREATE on it. ` +
+ `Grant it once with GRANT CREATE ON SCHEMA public TO "${ownership.currentUser}", or drop schemaName from defineSchema() to use the default schema app, which the app creates and owns.`
+ );
+ }
+ return (
+ `Role "${ownership.currentUser}" can create in schema public, so an object this migration changes belongs to another role, and no Postgres role can hand it to "${ownership.currentUser}". ` +
+ "Drop schemaName from defineSchema() to use the default schema app, which the app creates and owns."
+ );
+ }
+ if (ownership && ownership.owner !== ownership.currentUser) {
+ // ALTER ... OWNER TO the app's role fails with "must be able to SET ROLE":
+ // nobody holds ADMIN or SET on an Apps service principal role, so only the
+ // platform's delete-role --reassign-owned-to can move the objects.
+ return (
+ `Schema "${ownership.schemaName}" is owned by "${ownership.owner}", but the app connects as "${ownership.currentUser}". ` +
+ "If two apps share this database, give each its own schemaName in schema.ts. " +
+ "Otherwise the app was recreated with a new service principal, or its database resource was removed and added again, " +
+ `and Lakebase handed the objects to "${ownership.owner}". No Postgres role can hand them back to "${ownership.currentUser}"; only Lakebase can move them. ` +
+ `If "${ownership.owner}" belonged to a deleted app, or is the role of the person who removed the resource, someone with CAN MANAGE on the Lakebase project moves its objects with ` +
+ `\`databricks postgres delete-role --reassign-owned-to \` (\`databricks postgres list-roles \` names both). ` +
+ "That moves every object the role owns on the branch and deletes the role, so first check what it owns in each database. " +
+ "On your dev or session branch, rerun `appkit db init`, which hands you the schema."
+ );
+ }
+ return (
+ "The connecting role lacks a privilege this migration needs: CREATE on the database, or ownership of the app schema and its tables. " +
+ "On the deploy branch that role is the app's service principal: bind the database to the app with CAN_CONNECT_AND_CREATE. " +
+ "If another role owns an object the migration changes, no Postgres role can hand it to the service principal; only Lakebase can move it."
+ );
+}
diff --git a/packages/appkit/src/database/migrations/paths.ts b/packages/appkit/src/database/migrations/paths.ts
new file mode 100644
index 000000000..d4f669aa7
--- /dev/null
+++ b/packages/appkit/src/database/migrations/paths.ts
@@ -0,0 +1,100 @@
+import fs from "node:fs";
+import path from "node:path";
+
+/** Committed migration history, relative to the application root. */
+const MIGRATIONS_DIR = "config/database/migrations";
+/** Journal table drizzle-orm's migrator keeps in the app schema. */
+export const MIGRATIONS_TABLE = "__drizzle_migrations";
+/**
+ * First migration `appkit db introspect` writes for tables that already exist.
+ * The migrator adopts it (records it without running it) when the catalog
+ * already holds every one of its tables and columns.
+ */
+export const BASELINE_TAG = "0000_baseline";
+
+/** One entry of drizzle-kit's v7 `meta/_journal.json`. */
+export interface JournalEntry {
+ idx: number;
+ version: "7";
+ when: number;
+ tag: string;
+ breakpoints: true;
+}
+
+/** drizzle-kit's v7 `meta/_journal.json`. */
+export interface Journal {
+ version: "7";
+ dialect: "postgresql";
+ entries: JournalEntry[];
+}
+
+/** Absolute migrations folder for an application root. */
+export function migrationsFolder(root: string): string {
+ return path.resolve(root, MIGRATIONS_DIR);
+}
+
+// drizzle-kit 0.31's v7 folder layout. drizzle-kit v1 replaces it with one
+// folder per migration, so every path into the folder is built here.
+
+/** Folder of the journal and the snapshots. */
+export function metaFolder(folder: string): string {
+ return path.join(folder, "meta");
+}
+
+/** Path of the journal inside a migrations folder. */
+export function journalFile(folder: string): string {
+ return path.join(metaFolder(folder), "_journal.json");
+}
+
+/** The `NNNN` that starts the tag of the migration at journal index idx. */
+export function migrationPrefix(idx: number): string {
+ return String(idx).padStart(4, "0");
+}
+
+/** Path of a migration's SQL. */
+export function migrationFile(folder: string, tag: string): string {
+ return path.join(folder, `${tag}.sql`);
+}
+
+/** Path of the snapshot written with the migration at journal index idx. */
+export function snapshotFile(folder: string, idx: number): string {
+ return path.join(metaFolder(folder), `${migrationPrefix(idx)}_snapshot.json`);
+}
+
+/** A committed migration file is missing or unreadable; the message names the file. */
+export class MigrationFilesError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message, options);
+ this.name = "MigrationFilesError";
+ }
+}
+
+/** Parse a committed JSON file of the migration history. */
+export function readJsonFile(file: string): T {
+ try {
+ return JSON.parse(fs.readFileSync(file, "utf-8")) as T;
+ } catch (error) {
+ throw new MigrationFilesError(
+ `Cannot read ${file}: ${error instanceof Error ? error.message : String(error)}. Restore it from version control.`,
+ { cause: error },
+ );
+ }
+}
+
+/** A parsed meta/_journal.json, checked to be drizzle-kit's PostgreSQL journal; label names it in the error. */
+export function parseJournal(json: unknown, label: string): Journal {
+ const parsed = json as Partial | null;
+ if (parsed?.dialect !== "postgresql" || !Array.isArray(parsed.entries)) {
+ throw new MigrationFilesError(
+ `${label} is not a drizzle-kit PostgreSQL migration journal`,
+ );
+ }
+ return parsed as Journal;
+}
+
+/** null when meta/_journal.json is absent (nothing committed yet). */
+export function readJournal(folder: string): Journal | null {
+ const file = journalFile(folder);
+ if (!fs.existsSync(file)) return null;
+ return parseJournal(readJsonFile(file), file);
+}
diff --git a/packages/appkit/src/database/migrations/tables-left-in-public.ts b/packages/appkit/src/database/migrations/tables-left-in-public.ts
new file mode 100644
index 000000000..e74d124e8
--- /dev/null
+++ b/packages/appkit/src/database/migrations/tables-left-in-public.ts
@@ -0,0 +1,100 @@
+// Apps from before the default schema moved to `app` keep their tables in
+// `public`. With the schema name left to its default, a migration would create
+// a second, empty copy of each table in `app`, the startup check would pass,
+// and the app would serve the empty copy. The check and the migration guard
+// below share one catalog lookup so they name that case the same way.
+
+import type { Schema } from "../schema-builder";
+import { schemaNameIsExplicit } from "../schema-builder/define-schema";
+
+/** Tagged SQL whose interpolations are parameter values; `DataPath.raw` has this shape. */
+export type CatalogSql = (
+ strings: TemplateStringsArray,
+ ...values: unknown[]
+) => Promise;
+
+/** The one method of a pg Pool or PoolClient the lookup needs. */
+interface CatalogClient {
+ query(
+ text: string,
+ values: unknown[],
+ ): Promise<{ readonly rows: readonly unknown[] }>;
+}
+
+/** Run tagged SQL on a pg pool or client, for callers that have no DataPath yet. */
+export function catalogSqlOf(client: CatalogClient): CatalogSql {
+ return async (strings: TemplateStringsArray, ...values: unknown[]) => {
+ const text = strings.reduce((sql, part, index) => `${sql}$${index}${part}`);
+ const { rows } = await client.query(text, values);
+ return rows as T[];
+ };
+}
+
+/** Where the declared tables are, in declaration order. */
+interface TablePlacement {
+ /** Declared tables that exist in the schema the app targets. */
+ readonly inSchema: readonly string[];
+ /** Declared tables that exist in `public`. */
+ readonly inPublic: readonly string[];
+}
+
+/**
+ * Find the named tables in `schemaName` and in `public`. pg_catalog is read
+ * rather than information_schema, which hides objects the role cannot access
+ * and would report a privilege gap as a missing table.
+ */
+export async function locateTables(
+ sql: CatalogSql,
+ schemaName: string,
+ tableNames: readonly string[],
+): Promise {
+ if (tableNames.length === 0) return { inSchema: [], inPublic: [] };
+ const rows = await sql<{ schema_name: string; table_name: string }>`
+ select n.nspname::text as schema_name, c.relname::text as table_name
+ from pg_catalog.pg_class c
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
+ where n.nspname::text in (${schemaName}, 'public')
+ and c.relname::text = any(${tableNames}::text[])
+ and c.relkind in ('r', 'p')`;
+ const within = (schema: string) => {
+ const found = new Set(
+ rows
+ .filter((row) => row.schema_name === schema)
+ .map((row) => row.table_name),
+ );
+ return tableNames.filter((name) => found.has(name));
+ };
+ return { inSchema: within(schemaName), inPublic: within("public") };
+}
+
+/** How to keep using the tables in `public`; the sentence every caller ends with. */
+export function keepInPublicAdvice(schemaName: string): string {
+ return (
+ `defineSchema() puts tables in schema "${schemaName}" unless told otherwise. ` +
+ 'To keep them in public, pass { schemaName: "public" } as the second argument of defineSchema() in config/database/schema.ts.'
+ );
+}
+
+/**
+ * Why migrating this schema must not proceed, or undefined when it may: the
+ * schema name is explicit, some declared table already exists in it, or
+ * `public` holds none of them. Run before any migration is applied, by the
+ * deployed app and by the CLI alike.
+ */
+export async function detectTablesLeftInPublic(
+ sql: CatalogSql,
+ schema: Schema,
+): Promise {
+ if (schemaNameIsExplicit(schema)) return undefined;
+ const schemaName = schema.$schemaName;
+ const declared = Object.values(schema.$tables).map((table) => table.$name);
+ const { inSchema, inPublic } = await locateTables(sql, schemaName, declared);
+ if (inSchema.length > 0 || inPublic.length === 0) return undefined;
+ return (
+ `none of the declared tables exist in schema "${schemaName}", but public has ${inPublic.join(", ")}. ` +
+ `Migrating would create empty copies in "${schemaName}" and the app would serve those. ` +
+ `${keepInPublicAdvice(schemaName)} ` +
+ `To use schema "${schemaName}", move the tables there first (ALTER TABLE public. SET SCHEMA ${schemaName}), ` +
+ `or pass { schemaName: "${schemaName}" } explicitly when the tables in public belong to another app.`
+ );
+}
diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts
new file mode 100644
index 000000000..40d15f104
--- /dev/null
+++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts
@@ -0,0 +1,761 @@
+import { randomUUID } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+
+import { Pool, type PoolClient } from "pg";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+
+import {
+ applyPendingMigrations,
+ MigrationApplyError,
+ MigrationHistoryError,
+ markMigrationsApplied,
+ MigrationJournalError,
+ migrationLockKey,
+ readMigrationDrift,
+} from "../apply";
+import { schemaOwnership } from "../ownership";
+import { MigrationFilesError } from "../paths";
+import { hashOf, removeMigrationFolders, writeMigrations } from "./fixtures";
+
+// A real server, for what a fake cannot show: transactions, enum rules, locks
+// and catalogs. Point it at a scratch database, e.g.
+// APPKIT_TEST_PG_URL=postgres://localhost:5432/postgres
+const url = process.env.APPKIT_TEST_PG_URL;
+const ROLE_PASSWORD = "appkit-test";
+
+describe.skipIf(!url)("applyPendingMigrations against Postgres", () => {
+ let admin: Pool;
+ let schema: string;
+ const pools: Pool[] = [];
+ const held: PoolClient[] = [];
+
+ const newPool = (config: { user?: string; max?: number } = {}) => {
+ const target = new URL(url ?? "");
+ if (config.user) {
+ target.username = config.user;
+ target.password = ROLE_PASSWORD;
+ }
+ const pool = new Pool({
+ connectionString: target.toString(),
+ max: config.max ?? 2,
+ });
+ pools.push(pool);
+ return pool;
+ };
+ const q = (name: string) => `"${schema}"."${name}"`;
+ const options = (folder: string) => ({
+ migrationsFolder: folder,
+ schemaName: schema,
+ });
+ const recorded = async () =>
+ (
+ await admin.query<{ hash: string; created_at: string }>(
+ `select hash, created_at from ${q("__drizzle_migrations")} order by id`,
+ )
+ ).rows.map((row) => ({
+ hash: row.hash,
+ createdAt: Number(row.created_at),
+ }));
+ const columns = async (table: string) =>
+ (
+ await admin.query<{ column_name: string }>(
+ `select column_name from information_schema.columns
+ where table_schema = $1 and table_name = $2 order by ordinal_position`,
+ [schema, table],
+ )
+ ).rows.map((row) => row.column_name);
+
+ beforeAll(() => {
+ admin = new Pool({ connectionString: url, max: 4 });
+ });
+ afterAll(async () => {
+ await admin.end();
+ });
+ beforeEach(() => {
+ schema = `appkit_test_${randomUUID().slice(0, 8)}`;
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ });
+ afterEach(async () => {
+ for (const client of held.splice(0)) client.release(true);
+ await Promise.all(pools.splice(0).map((pool) => pool.end()));
+ await admin.query(`drop schema if exists "${schema}" cascade`);
+ removeMigrationFolders();
+ vi.restoreAllMocks();
+ });
+
+ const notes = () =>
+ writeMigrations([
+ {
+ tag: "0000_notes",
+ when: 1000,
+ sql: [`CREATE TABLE ${q("notes")} ("id" integer PRIMARY KEY);`],
+ },
+ {
+ tag: "0001_body",
+ when: 2000,
+ sql: [
+ `ALTER TABLE ${q("notes")} ADD COLUMN "body" text;`,
+ `ALTER TABLE ${q("notes")} ADD COLUMN "title" text;`,
+ ],
+ },
+ ]);
+
+ test("applies each migration once and records what drizzle-kit records", async () => {
+ const folder = notes();
+ const pool = newPool();
+
+ const first = await applyPendingMigrations(pool, options(folder));
+ const second = await applyPendingMigrations(pool, options(folder));
+
+ expect(first.applied).toEqual(["0000_notes", "0001_body"]);
+ expect(second.applied).toEqual([]);
+ expect(await columns("notes")).toEqual(["id", "body", "title"]);
+ expect(await recorded()).toEqual([
+ { hash: hashOf(folder, "0000_notes"), createdAt: 1000 },
+ { hash: hashOf(folder, "0001_body"), createdAt: 2000 },
+ ]);
+ });
+
+ test("an enum value one migration adds can be used by the next one", async () => {
+ // In one transaction for all, Postgres rejects this with 55P04.
+ const folder = writeMigrations([
+ {
+ tag: "0000_mood",
+ when: 1000,
+ sql: [
+ `CREATE TYPE ${q("mood")} AS ENUM ('ok');`,
+ `CREATE TABLE ${q("notes")} ("id" integer, "mood" ${q("mood")});`,
+ ],
+ },
+ {
+ tag: "0001_great",
+ when: 2000,
+ sql: [`ALTER TYPE ${q("mood")} ADD VALUE 'great';`],
+ },
+ {
+ tag: "0002_default",
+ when: 3000,
+ sql: [
+ `ALTER TABLE ${q("notes")} ALTER COLUMN "mood" SET DEFAULT 'great';`,
+ ],
+ },
+ ]);
+
+ const result = await applyPendingMigrations(newPool(), options(folder));
+
+ expect(result.applied).toEqual(["0000_mood", "0001_great", "0002_default"]);
+ });
+
+ test("a failing migration keeps the ones before it, and runs once it is fixed", async () => {
+ const folder = writeMigrations([
+ {
+ tag: "0000_notes",
+ when: 1000,
+ sql: [`CREATE TABLE ${q("notes")} ("id" integer);`],
+ },
+ {
+ tag: "0001_broken",
+ when: 2000,
+ sql: [`ALTER TABLE ${q("missing")} ADD COLUMN "x" integer;`],
+ },
+ ]);
+ const pool = newPool();
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationApplyError);
+ expect(error).toMatchObject({
+ failed: "0001_broken",
+ applied: ["0000_notes"],
+ code: "42P01",
+ });
+ expect(await columns("notes")).toEqual(["id"]);
+ expect(await recorded()).toHaveLength(1);
+
+ const fixed = writeMigrations([
+ {
+ tag: "0000_notes",
+ when: 1000,
+ sql: [`CREATE TABLE ${q("notes")} ("id" integer);`],
+ },
+ {
+ tag: "0001_broken",
+ when: 2000,
+ sql: [`ALTER TABLE ${q("notes")} ADD COLUMN "x" integer;`],
+ },
+ ]);
+ const result = await applyPendingMigrations(pool, options(fixed));
+ expect(result.applied).toEqual(["0001_broken"]);
+ });
+
+ test.each([
+ [
+ "a NOT NULL the rows break (class 23)",
+ `ALTER TABLE NOTES ALTER COLUMN "body" SET NOT NULL;`,
+ "23502",
+ ],
+ [
+ "a retype the rows cannot take (class 22)",
+ `ALTER TABLE NOTES ALTER COLUMN "body" TYPE integer USING "body"::integer;`,
+ "22P02",
+ ],
+ ])(
+ "%s: the error says to repair the rows and deploy the same migration again",
+ async (_label, statement, code) => {
+ const created = {
+ tag: "0000_notes",
+ when: 1000,
+ sql: [`CREATE TABLE ${q("notes")} ("id" integer, "body" text);`],
+ };
+ const pool = newPool();
+ await applyPendingMigrations(pool, options(writeMigrations([created])));
+ await admin.query(
+ `insert into ${q("notes")} values (1, null), (2, 'not a number')`,
+ );
+ const folder = writeMigrations([
+ created,
+ {
+ tag: "0001_tighten",
+ when: 2000,
+ sql: [statement.replace("NOTES", q("notes"))],
+ },
+ ]);
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationApplyError);
+ expect(error).toMatchObject({ failed: "0001_tighten", code });
+ expect((error as Error).message).toContain(
+ "It failed on rows already in the database, not on its SQL. Repair those rows, then apply the same migration again. " +
+ "On the deploy branch, repair them as a role with the DATABRICKS_SUPERUSER membership, which someone with CAN USE on the Lakebase project creates, and deploy again.",
+ );
+ },
+ );
+
+ test("a migration merged behind the last recorded one fails closed and changes nothing", async () => {
+ const a = {
+ tag: "0000_a",
+ when: 1000,
+ sql: [`CREATE TABLE ${q("a")} ("id" integer);`],
+ };
+ const c = {
+ tag: "0002_c",
+ when: 3000,
+ sql: [`CREATE TABLE ${q("c")} ("id" integer);`],
+ };
+ const pool = newPool();
+ await applyPendingMigrations(pool, options(writeMigrations([a, c])));
+
+ const merged = writeMigrations([
+ a,
+ {
+ tag: "0001_b",
+ when: 2000,
+ sql: [`CREATE TABLE ${q("b")} ("id" integer);`],
+ },
+ c,
+ {
+ tag: "0003_d",
+ when: 4000,
+ sql: [`CREATE TABLE ${q("d")} ("id" integer);`],
+ },
+ ]);
+ const error = await applyPendingMigrations(pool, options(merged)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationHistoryError);
+ expect(error).toMatchObject({ refusal: { stranded: ["0001_b"] } });
+ expect(await recorded()).toHaveLength(2);
+ expect(await columns("d")).toEqual([]);
+ });
+
+ test("instances starting together apply each migration once", async () => {
+ const folder = notes();
+
+ const results = await Promise.all([
+ applyPendingMigrations(newPool(), options(folder)),
+ applyPendingMigrations(newPool(), options(folder)),
+ applyPendingMigrations(newPool(), options(folder)),
+ ]);
+
+ expect(results.flatMap((result) => result.applied).sort()).toEqual([
+ "0000_notes",
+ "0001_body",
+ ]);
+ expect(await recorded()).toHaveLength(2);
+ });
+
+ test("the wait for another session's migration lock has a limit, and the error names the holder", async () => {
+ const holder = await admin.connect();
+ held.push(holder);
+ await holder.query("set application_name = 'another-deploy'");
+ await holder.query("select pg_advisory_lock($1::bigint)", [
+ migrationLockKey(schema),
+ ]);
+ const pid = (
+ await holder.query<{ pid: number }>("select pg_backend_pid() as pid")
+ ).rows[0]?.pid;
+
+ const error = await applyPendingMigrations(newPool(), {
+ ...options(notes()),
+ lockWaitMs: 300,
+ }).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(MigrationApplyError);
+ expect((error as Error).message).toContain(
+ `Session pid ${pid} (another-deploy, idle) held the migration lock for over 300ms.`,
+ );
+ });
+
+ test("a table lock held elsewhere is retried, and the migration applies once it is released", async () => {
+ const folder = notes();
+ const pool = newPool();
+ await applyPendingMigrations(pool, {
+ ...options(
+ writeMigrations([
+ {
+ tag: "0000_notes",
+ when: 1000,
+ sql: [`CREATE TABLE ${q("notes")} ("id" integer PRIMARY KEY);`],
+ },
+ ]),
+ ),
+ });
+ const holder = await admin.connect();
+ held.push(holder);
+ await holder.query("begin");
+ await holder.query(`lock table ${q("notes")} in access share mode`);
+ setTimeout(() => void holder.query("commit"), 300);
+
+ const result = await applyPendingMigrations(pool, {
+ ...options(folder),
+ lockTimeoutMs: 200,
+ });
+
+ expect(result.applied).toEqual(["0001_body"]);
+ expect(console.warn).toHaveBeenCalled();
+ });
+
+ test("a table lock held through every try fails with 55P03 and leaves the migration unapplied", async () => {
+ const pool = newPool();
+ await applyPendingMigrations(pool, {
+ ...options(
+ writeMigrations([
+ {
+ tag: "0000_notes",
+ when: 1000,
+ sql: [`CREATE TABLE ${q("notes")} ("id" integer PRIMARY KEY);`],
+ },
+ ]),
+ ),
+ });
+ const holder = await admin.connect();
+ held.push(holder);
+ await holder.query("begin");
+ await holder.query(`lock table ${q("notes")} in access share mode`);
+
+ const error = await applyPendingMigrations(pool, {
+ ...options(notes()),
+ lockTimeoutMs: 100,
+ }).catch((caught: unknown) => caught);
+ await holder.query("rollback");
+
+ expect(error).toMatchObject({ failed: "0001_body", code: "55P03" });
+ expect(await columns("notes")).toEqual(["id"]);
+ });
+
+ test("the session goes back to the pool reset and unlocked", async () => {
+ const pool = newPool({ max: 1 });
+ const before = await pool.query<{ application_name: string }>(
+ "select current_setting('application_name') as application_name",
+ );
+
+ await applyPendingMigrations(pool, options(notes()));
+
+ const after = await pool.query<{
+ application_name: string;
+ lock_timeout: string;
+ locks: string;
+ }>(
+ `select current_setting('application_name') as application_name,
+ current_setting('lock_timeout') as lock_timeout,
+ (select count(*) from pg_locks where locktype = 'advisory' and pid = pg_backend_pid())::text as locks`,
+ );
+ expect(after.rows[0]).toEqual({
+ application_name: before.rows[0]?.application_name,
+ lock_timeout: "0",
+ locks: "0",
+ });
+ });
+
+ test("an existing schema owned by another role: the error names both roles", async () => {
+ const suffix = schema.slice(-8);
+ const owner = `appkit_owner_${suffix}`;
+ const app = `appkit_app_${suffix}`;
+ await admin.query(`create role "${owner}" nologin`);
+ await admin.query(`create role "${app}" login password '${ROLE_PASSWORD}'`);
+ await admin.query(`create schema "${schema}" authorization "${owner}"`);
+ try {
+ const error = await applyPendingMigrations(
+ newPool({ user: app }),
+ options(notes()),
+ ).catch((caught: unknown) => caught);
+
+ expect(error).toMatchObject({ code: "42501" });
+ expect((error as Error).message).toContain(
+ `Schema "${schema}" is owned by "${owner}", but the app connects as "${app}".`,
+ );
+ } finally {
+ await Promise.all(pools.splice(0).map((pool) => pool.end()));
+ await admin.query(`drop schema if exists "${schema}" cascade`);
+ await admin.query(`drop owned by "${app}"`);
+ await admin.query(`drop role "${app}"`);
+ await admin.query(`drop role "${owner}"`);
+ }
+ });
+
+ test("schemaOwnership reads the owner and whether the connecting role may CREATE", async () => {
+ const suffix = schema.slice(-8);
+ const owner = `appkit_owner_${suffix}`;
+ const app = `appkit_app_${suffix}`;
+ await admin.query(`create role "${owner}" nologin`);
+ await admin.query(`create role "${app}" login password '${ROLE_PASSWORD}'`);
+ await admin.query(`create schema "${schema}" authorization "${owner}"`);
+ await admin.query(`grant usage on schema "${schema}" to "${app}"`);
+ const asApp = newPool({ user: app });
+ try {
+ const withoutCreate = await schemaOwnership(asApp, schema);
+ await admin.query(`grant create on schema "${schema}" to "${app}"`);
+ const withCreate = await schemaOwnership(asApp, schema);
+ const missing = await schemaOwnership(asApp, `${schema}_missing`);
+
+ expect(withoutCreate).toEqual({
+ schemaName: schema,
+ owner,
+ currentUser: app,
+ canCreate: false,
+ });
+ expect(withCreate).toMatchObject({ owner, canCreate: true });
+ expect(missing).toMatchObject({ owner: null, canCreate: null });
+ } finally {
+ await Promise.all(pools.splice(0).map((pool) => pool.end()));
+ await admin.query(`drop schema if exists "${schema}" cascade`);
+ await admin.query(`drop owned by "${app}"`);
+ await admin.query(`drop role "${app}"`);
+ await admin.query(`drop role "${owner}"`);
+ }
+ });
+
+ test("a schema the app already owns needs no CREATE on the database", async () => {
+ const app = `appkit_app_${schema.slice(-8)}`;
+ await admin.query(`create role "${app}" login password '${ROLE_PASSWORD}'`);
+ await admin.query(`create schema "${schema}" authorization "${app}"`);
+ try {
+ const result = await applyPendingMigrations(
+ newPool({ user: app }),
+ options(notes()),
+ );
+
+ expect(result.applied).toEqual(["0000_notes", "0001_body"]);
+ } finally {
+ await Promise.all(pools.splice(0).map((pool) => pool.end()));
+ await admin.query(`drop schema if exists "${schema}" cascade`);
+ await admin.query(`drop role "${app}"`);
+ }
+ });
+
+ test("the app's own journal in a schema another role owns (public) is read and recorded into on every start", async () => {
+ // Like `public` under CAN_CONNECT_AND_CREATE: the schema belongs to the
+ // database owner, the app may create in it, and the journal it creates
+ // there is the app's.
+ const suffix = schema.slice(-8);
+ const owner = `appkit_owner_${suffix}`;
+ const app = `appkit_app_${suffix}`;
+ const database = (
+ await admin.query<{ database: string }>(
+ "select current_database() as database",
+ )
+ ).rows[0]?.database;
+ await admin.query(`create role "${owner}" nologin`);
+ await admin.query(`create role "${app}" login password '${ROLE_PASSWORD}'`);
+ await admin.query(`grant create on database "${database}" to "${app}"`);
+ await admin.query(`create schema "${schema}" authorization "${owner}"`);
+ await admin.query(`grant usage, create on schema "${schema}" to "${app}"`);
+ try {
+ const folder = notes();
+ const pool = newPool({ user: app });
+
+ const first = await applyPendingMigrations(pool, options(folder));
+ const second = await applyPendingMigrations(pool, options(folder));
+
+ expect(first.applied).toEqual(["0000_notes", "0001_body"]);
+ expect(second.applied).toEqual([]);
+ expect(await recorded()).toEqual([
+ { hash: hashOf(folder, "0000_notes"), createdAt: 1000 },
+ { hash: hashOf(folder, "0001_body"), createdAt: 2000 },
+ ]);
+ } finally {
+ await Promise.all(pools.splice(0).map((pool) => pool.end()));
+ await admin.query(`drop schema if exists "${schema}" cascade`);
+ await admin.query(`drop owned by "${app}"`);
+ await admin.query(`drop role "${app}"`);
+ await admin.query(`drop role "${owner}"`);
+ }
+ });
+
+ test("a view at the journal's name is refused, and nothing is created", async () => {
+ await admin.query(`create schema "${schema}"`);
+ await admin.query(
+ `create view ${q("__drizzle_migrations")} as select 'x'::text as hash, 1::bigint as created_at`,
+ );
+ const role = (
+ await admin.query<{ role: string }>("select current_user::text as role")
+ ).rows[0]?.role;
+
+ const error = await applyPendingMigrations(
+ newPool(),
+ options(notes()),
+ ).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(MigrationJournalError);
+ expect((error as Error).message).toContain(
+ `"${schema}"."__drizzle_migrations" is a view owned by "${role}". The migrator reads and records applied migrations only in an ordinary table`,
+ );
+ expect(await columns("notes")).toEqual([]);
+ });
+
+ test("a deploy start refuses an applied migration whose file changed, and changes nothing", async () => {
+ const folder = notes();
+ const pool = newPool();
+ await applyPendingMigrations(pool, options(folder));
+ const file = path.join(folder, "0001_body.sql");
+ fs.appendFileSync(file, `\nALTER TABLE ${q("notes")} DROP COLUMN "title";`);
+ const before = await recorded();
+
+ const error = await applyPendingMigrations(pool, {
+ ...options(folder),
+ onDrift: "refuse",
+ }).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(MigrationHistoryError);
+ expect(error).toMatchObject({ refusal: { edited: ["0001_body"] } });
+ expect(await columns("notes")).toEqual(["id", "body", "title"]);
+ expect(await recorded()).toEqual(before);
+ });
+
+ test("a file read back with CRLF after it was applied is still that migration, and the as-is hash stays recorded", async () => {
+ const folder = notes();
+ const pool = newPool();
+ await applyPendingMigrations(pool, options(folder));
+ const file = path.join(folder, "0001_body.sql");
+ fs.writeFileSync(
+ file,
+ fs.readFileSync(file, "utf-8").replace(/\n/g, "\r\n"),
+ );
+
+ const again = await applyPendingMigrations(pool, {
+ ...options(folder),
+ onDrift: "refuse",
+ });
+
+ expect(again).toMatchObject({ applied: [], edited: [], unknown: 0 });
+ expect(await recorded()).toEqual([
+ { hash: hashOf(folder, "0000_notes"), createdAt: 1000 },
+ { hash: hashOf(folder, "0001_body", "lf"), createdAt: 2000 },
+ ]);
+ });
+
+ test("a baseline whose tables already exist is adopted, and later migrations apply", async () => {
+ await admin.query(`create schema "${schema}"`);
+ await admin.query(`create table ${q("notes")} ("id" integer primary key)`);
+ const folder = writeMigrations(
+ [
+ {
+ tag: "0000_baseline",
+ when: 1000,
+ sql: [`CREATE TABLE ${q("notes")} ("id" integer PRIMARY KEY);`],
+ snapshot: { notes: ["id"] },
+ },
+ {
+ tag: "0001_body",
+ when: 2000,
+ sql: [`ALTER TABLE ${q("notes")} ADD COLUMN "body" text;`],
+ },
+ ],
+ schema,
+ );
+
+ const result = await applyPendingMigrations(newPool(), options(folder));
+
+ expect(result).toMatchObject({
+ adopted: ["0000_baseline"],
+ applied: ["0001_body"],
+ });
+ expect(await columns("notes")).toEqual(["id", "body"]);
+ });
+
+ describe("recording migrations the branch already has", () => {
+ const withTags = () =>
+ writeMigrations([
+ {
+ tag: "0000_notes",
+ when: 1000,
+ sql: [`CREATE TABLE ${q("notes")} ("id" integer PRIMARY KEY);`],
+ },
+ {
+ tag: "0001_introspect",
+ when: 3000,
+ sql: [`ALTER TABLE ${q("notes")} ADD COLUMN "body" text;`],
+ },
+ ]);
+ /** The branch applied 0000_notes and recorded a 2000 migration this checkout lacks. */
+ const aheadOfCheckout = async (folder: string) => {
+ await applyPendingMigrations(newPool(), {
+ ...options(folder),
+ migrationsFolder: notes(),
+ });
+ await admin.query(
+ `delete from ${q("__drizzle_migrations")} where created_at <> 1000`,
+ );
+ await admin.query(
+ `insert into ${q("__drizzle_migrations")} (hash, created_at) values ('teammate', 2000)`,
+ );
+ };
+
+ test("the drift lists unrecorded committed migrations, recorded ones the checkout lacks, and recorded ones whose file changed", async () => {
+ const folder = withTags();
+ expect(await readMigrationDrift(newPool(), options(folder))).toEqual({
+ pending: ["0000_notes", "0001_introspect"],
+ stranded: [],
+ edited: [],
+ unknown: 0,
+ });
+
+ await aheadOfCheckout(folder);
+
+ expect(await readMigrationDrift(newPool(), options(folder))).toEqual({
+ pending: ["0001_introspect"],
+ stranded: [],
+ edited: [],
+ unknown: 1,
+ });
+
+ fs.appendFileSync(path.join(folder, "0000_notes.sql"), "\n-- edited");
+
+ expect(await readMigrationDrift(newPool(), options(folder))).toEqual({
+ pending: ["0001_introspect"],
+ stranded: [],
+ edited: ["0000_notes"],
+ unknown: 1,
+ });
+ });
+
+ test("records exactly the pending migrations, without running them", async () => {
+ await admin.query(`create schema "${schema}"`);
+ const folder = withTags();
+
+ await markMigrationsApplied(newPool(), options(folder), [
+ "0000_notes",
+ "0001_introspect",
+ ]);
+
+ expect(await recorded()).toEqual([
+ { hash: hashOf(folder, "0000_notes"), createdAt: 1000 },
+ { hash: hashOf(folder, "0001_introspect"), createdAt: 3000 },
+ ]);
+ expect(await columns("notes")).toEqual([]);
+ });
+
+ test.each([
+ [
+ "records a migration the checkout lacks",
+ aheadOfCheckout,
+ ["0001_introspect"],
+ "it records 1 migration this checkout does not have",
+ ],
+ [
+ "has not applied an earlier one",
+ async () => {
+ await admin.query(`create schema "${schema}"`);
+ },
+ ["0001_introspect"],
+ "it has not applied 0000_notes",
+ ],
+ [
+ "applied a migration whose committed file changed since",
+ async (folder: string) => {
+ await applyPendingMigrations(newPool(), options(folder));
+ await admin.query(
+ `delete from ${q("__drizzle_migrations")} where created_at = 3000`,
+ );
+ fs.appendFileSync(path.join(folder, "0000_notes.sql"), "\n-- edited");
+ },
+ ["0001_introspect"],
+ "it applied 0000_notes before its file changed",
+ ],
+ ])(
+ "refuses when the branch %s, and records nothing",
+ async (_label, arrange, toRecord, reason) => {
+ const folder = withTags();
+ await arrange(folder);
+ const before = await recorded().catch(() => []);
+
+ await expect(
+ markMigrationsApplied(newPool(), options(folder), toRecord),
+ ).rejects.toThrow(
+ `Schema "${schema}" changed while this ran (${reason}), so nothing was recorded.`,
+ );
+ expect(await recorded().catch(() => [])).toEqual(before);
+ },
+ );
+
+ test("a tag missing from the journal fails before connecting", async () => {
+ const pool = newPool();
+ const connect = vi.spyOn(pool, "connect");
+
+ await expect(
+ markMigrationsApplied(pool, options(withTags()), ["0002_introspect"]),
+ ).rejects.toBeInstanceOf(MigrationFilesError);
+ expect(connect).not.toHaveBeenCalled();
+ });
+
+ test("the wait for the migration lock has a limit, and nothing is recorded", async () => {
+ await admin.query(`create schema "${schema}"`);
+ const holder = await admin.connect();
+ held.push(holder);
+ await holder.query("set application_name = 'another-deploy'");
+ await holder.query("select pg_advisory_lock($1::bigint)", [
+ migrationLockKey(schema),
+ ]);
+
+ await expect(
+ markMigrationsApplied(
+ newPool(),
+ { ...options(withTags()), lockWaitMs: 300 },
+ ["0000_notes", "0001_introspect"],
+ ),
+ ).rejects.toThrow(
+ new RegExp(
+ `^Session pid \\d+ \\(another-deploy, idle\\) held the migration lock of schema "${schema}" for over 300ms, so nothing was recorded\\. Rerun once it finishes\\.$`,
+ ),
+ );
+ expect(await recorded().catch(() => [])).toEqual([]);
+ });
+ });
+});
diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts
new file mode 100644
index 000000000..868b83da3
--- /dev/null
+++ b/packages/appkit/src/database/migrations/tests/apply.test.ts
@@ -0,0 +1,1356 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { MIGRATION_HISTORY_REWRITE } from "shared";
+import { afterEach, describe, expect, test, vi } from "vitest";
+
+import {
+ applyPendingMigrations,
+ MigrationApplyError,
+ MigrationBaselineMismatchError,
+ MigrationHistoryError,
+ MigrationJournalError,
+ migrationLockKey,
+} from "../apply";
+import { MigrationFilesError } from "../paths";
+import {
+ hashOf,
+ removeMigrationFolders,
+ writeMigrations as migrations,
+} from "./fixtures";
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ removeMigrationFolders();
+});
+
+interface JournalRow {
+ hash: string;
+ created_at: number | null;
+}
+
+interface FakeState {
+ /** Rows of the journal table; null while the table does not exist. */
+ recorded: JournalRow[] | null;
+ failOn?: RegExp;
+ /** SQLSTATE of the failOn error; defaults to 42P07 (duplicate_table). */
+ failCode?: string;
+ /** How many failOn matches fail before one succeeds; all of them when unset. */
+ failTimes?: number;
+ failCleanupOn?: RegExp;
+ /** pg_catalog (table, column) pairs the baseline check sees. */
+ catalog?: Array<[string, string]>;
+ /** What pg_catalog holds at the journal's name; the connecting role's own table when unset. */
+ journal?: {
+ relkind: string;
+ owner: string;
+ schema_owner?: string;
+ row_security?: boolean;
+ };
+ /** Another session holds the migration lock. */
+ lockHeld?: boolean;
+ lockHolder?: { pid: number; application_name: string; state: string };
+ ownership?: { owner: string | null; current_user: string };
+}
+
+/**
+ * A pg PoolClient that records every statement and keeps journal inserts
+ * only when their transaction commits.
+ */
+class RecordingClient {
+ readonly statements: string[] = [];
+ released: { error: unknown } | undefined;
+ private uncommitted: JournalRow[] | undefined;
+ private failures = 0;
+
+ constructor(private readonly state: FakeState) {}
+
+ async query(
+ input: string | { text: string; values?: unknown[] },
+ values?: unknown[],
+ ) {
+ const text = (typeof input === "string" ? input : input.text).trim();
+ const params = values ?? (typeof input === "string" ? [] : input.values);
+ this.statements.push(text);
+ if (
+ this.state.failOn?.test(text) &&
+ (this.state.failTimes === undefined ||
+ this.failures < this.state.failTimes)
+ ) {
+ this.failures++;
+ throw Object.assign(new Error("statement failed"), {
+ code: this.state.failCode ?? "42P07",
+ });
+ }
+ if (this.state.failCleanupOn?.test(text)) {
+ throw new Error("connection lost");
+ }
+ if (text === "begin") this.uncommitted = [];
+ if (text === "commit") {
+ if (this.uncommitted?.length) {
+ this.state.recorded = [
+ ...(this.state.recorded ?? []),
+ ...this.uncommitted,
+ ];
+ }
+ this.uncommitted = undefined;
+ }
+ if (text === "rollback") this.uncommitted = undefined;
+ if (text.includes("pg_try_advisory_lock(")) {
+ return { rows: [{ locked: !this.state.lockHeld }] };
+ }
+ if (text.includes("pg_catalog.pg_locks")) {
+ return { rows: this.state.lockHolder ? [this.state.lockHolder] : [] };
+ }
+ if (text.includes("c.relowner")) {
+ if (this.state.recorded === null) return { rows: [] };
+ // The fake connects as "app-sp" and, like the server, trusts the
+ // relation's owner when it is that role or the schema's owner.
+ const journal = {
+ relkind: "r",
+ owner: "app-sp",
+ schema_owner: "app-sp",
+ row_security: false,
+ ...this.state.journal,
+ };
+ return {
+ rows: [
+ {
+ ...journal,
+ current_user: "app-sp",
+ trusted:
+ journal.owner === "app-sp" ||
+ journal.owner === journal.schema_owner,
+ },
+ ],
+ };
+ }
+ if (text.includes("pg_get_userbyid")) {
+ return {
+ rows: [
+ this.state.ownership ?? { owner: "app-sp", current_user: "app-sp" },
+ ],
+ };
+ }
+ if (text.includes("pg_catalog.pg_attribute")) {
+ return {
+ rows: (this.state.catalog ?? []).map(([table_name, column_name]) => ({
+ table_name,
+ column_name,
+ })),
+ };
+ }
+ if (text.startsWith("select hash, created_at")) {
+ return { rows: this.state.recorded ?? [] };
+ }
+ if (text.startsWith(`insert into "app"."__drizzle_migrations"`)) {
+ this.uncommitted?.push({
+ hash: String(params?.[0]),
+ created_at: Number(params?.[1]),
+ });
+ }
+ return { rows: [] };
+ }
+
+ release(error?: unknown) {
+ this.released = { error };
+ }
+}
+
+function fakePool(state: FakeState) {
+ const client = new RecordingClient(state);
+ let connects = 0;
+ return {
+ client,
+ state,
+ connects: () => connects,
+ pool: {
+ connect: async () => {
+ connects++;
+ return client as never;
+ },
+ },
+ };
+}
+
+const twoMigrations = () =>
+ migrations([
+ {
+ tag: "0000_migration",
+ when: 1000,
+ sql: [`CREATE TABLE "app"."notes" ("id" integer);`],
+ },
+ {
+ tag: "0001_migration",
+ when: 2000,
+ sql: [
+ `ALTER TABLE "app"."notes" ADD COLUMN "body" text;`,
+ `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`,
+ ],
+ },
+ ]);
+
+const options = (folder: string) => ({
+ migrationsFolder: folder,
+ schemaName: "app",
+});
+
+/** Collapse the recorded statements into readable steps. */
+function steps(statements: readonly string[]): string[] {
+ return statements.map((statement) => {
+ if (statement.includes("pg_try_advisory_lock(")) return "try lock";
+ if (statement.includes("pg_advisory_unlock(")) return "unlock";
+ if (statement.includes("pg_catalog.pg_locks")) return "lock holder?";
+ if (statement.includes("c.relowner")) return "journal table?";
+ if (statement.includes("pg_get_userbyid")) return "schema owner?";
+ if (statement.includes("pg_catalog.pg_attribute"))
+ return "baseline tables?";
+ if (statement.startsWith("select hash, created_at")) return "recorded?";
+ if (statement.startsWith("select 1 from pg_catalog.pg_namespace"))
+ return "schema?";
+ if (statement.startsWith(`CREATE SCHEMA IF NOT EXISTS`))
+ return "create schema";
+ if (statement.startsWith(`CREATE TABLE "app"."__drizzle_migrations"`))
+ return "create journal";
+ if (statement.startsWith(`insert into "app"."__drizzle_migrations"`))
+ return "record";
+ return statement.replace(/\s+/g, " ");
+ });
+}
+
+const SESSION_SETUP = [
+ "SET statement_timeout = 0",
+ "SET application_name = 'appkit-migrate'",
+ "SET client_connection_check_interval = '10s'",
+ "try lock",
+ "SET lock_timeout = '5000ms'",
+];
+
+const SESSION_CLEANUP = [
+ "unlock",
+ "RESET lock_timeout",
+ "RESET client_connection_check_interval",
+ "RESET application_name",
+ "RESET statement_timeout",
+];
+
+describe("applyPendingMigrations", () => {
+ test("reads without the lock, then applies each pending migration in its own transaction under it", async () => {
+ const folder = twoMigrations();
+ const { pool, client, state } = fakePool({ recorded: null });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result).toEqual({
+ applied: ["0000_migration", "0001_migration"],
+ adopted: [],
+ edited: [],
+ unknown: 0,
+ lockWaitMs: expect.any(Number),
+ });
+ expect(steps(client.statements)).toEqual([
+ "journal table?",
+ ...SESSION_SETUP,
+ "journal table?",
+ "begin",
+ "journal table?",
+ "schema?",
+ "create schema",
+ "create journal",
+ `CREATE TABLE "app"."notes" ("id" integer);`,
+ "record",
+ "commit",
+ "begin",
+ "journal table?",
+ `ALTER TABLE "app"."notes" ADD COLUMN "body" text;`,
+ `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`,
+ "record",
+ "commit",
+ ...SESSION_CLEANUP,
+ ]);
+ // The rows drizzle-orm's migrator would have written.
+ expect(state.recorded).toEqual([
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ { hash: hashOf(folder, "0001_migration"), created_at: 2000 },
+ ]);
+ expect(client.released).toEqual({ error: undefined });
+ });
+
+ test("applies only migrations newer than the last recorded one", async () => {
+ const folder = twoMigrations();
+ const { pool, client } = fakePool({
+ recorded: [{ hash: hashOf(folder, "0000_migration"), created_at: 1000 }],
+ });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result.applied).toEqual(["0001_migration"]);
+ expect(client.statements).not.toContain(
+ `CREATE TABLE "app"."notes" ("id" integer);`,
+ );
+ });
+
+ test("with nothing pending, it only reads: no lock, no session settings", async () => {
+ const folder = twoMigrations();
+ const { pool, client } = fakePool({
+ recorded: [
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ { hash: hashOf(folder, "0001_migration"), created_at: 2000 },
+ ],
+ });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result.applied).toEqual([]);
+ expect(steps(client.statements)).toEqual(["journal table?", "recorded?"]);
+ expect(client.released).toEqual({ error: undefined });
+ });
+
+ test("another instance applied everything while this one waited: nothing runs twice", async () => {
+ const folder = twoMigrations();
+ const fake = fakePool({ recorded: null });
+ const query = fake.client.query.bind(fake.client);
+ vi.spyOn(fake.client, "query").mockImplementation(async (input, values) => {
+ const result = await query(input, values);
+ if (String(input).includes("pg_try_advisory_lock(")) {
+ fake.state.recorded = [
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ { hash: hashOf(folder, "0001_migration"), created_at: 2000 },
+ ];
+ }
+ return result;
+ });
+
+ const result = await applyPendingMigrations(fake.pool, options(folder));
+
+ expect(result.applied).toEqual([]);
+ expect(fake.client.statements).not.toContain("begin");
+ });
+
+ describe("beforeApply", () => {
+ test("nothing pending: never runs", async () => {
+ const folder = twoMigrations();
+ const { pool } = fakePool({
+ recorded: [
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ { hash: hashOf(folder, "0001_migration"), created_at: 2000 },
+ ],
+ });
+ const beforeApply = vi.fn(async () => undefined);
+
+ await applyPendingMigrations(pool, { ...options(folder), beforeApply });
+
+ expect(beforeApply).not.toHaveBeenCalled();
+ });
+
+ test("something pending: runs once on the migrating connection, under the lock, before the first migration", async () => {
+ const folder = twoMigrations();
+ const { pool, client } = fakePool({ recorded: null });
+ const beforeApply = vi.fn(
+ async (connection: { query(text: string): unknown }) => {
+ await connection.query("select 'before apply'");
+ },
+ );
+
+ await applyPendingMigrations(pool, { ...options(folder), beforeApply });
+
+ expect(beforeApply).toHaveBeenCalledTimes(1);
+ const order = steps(client.statements);
+ expect(order.indexOf("select 'before apply'")).toBeGreaterThan(
+ order.indexOf("try lock"),
+ );
+ expect(order.indexOf("select 'before apply'")).toBeLessThan(
+ order.indexOf("begin"),
+ );
+ });
+
+ test("what it throws reaches the caller unchanged: nothing applied, the lock released", async () => {
+ const folder = twoMigrations();
+ const { pool, client, state } = fakePool({ recorded: null });
+ const refusal = new Error("tables left in public");
+
+ const error = await applyPendingMigrations(pool, {
+ ...options(folder),
+ beforeApply: async () => {
+ throw refusal;
+ },
+ }).catch((caught: unknown) => caught);
+
+ expect(error).toBe(refusal);
+ expect(client.statements).not.toContain("begin");
+ expect(state.recorded).toBeNull();
+ expect(steps(client.statements)).toContain("unlock");
+ expect(client.released).toEqual({ error: undefined });
+ });
+ });
+
+ test("without a journal it never connects", async () => {
+ const folder = migrations([]);
+ fs.rmSync(path.join(folder, "meta"), { recursive: true });
+ const fake = fakePool({ recorded: null });
+
+ await expect(
+ applyPendingMigrations(fake.pool, options(folder)),
+ ).resolves.toEqual({
+ applied: [],
+ adopted: [],
+ edited: [],
+ unknown: 0,
+ lockWaitMs: 0,
+ });
+ expect(fake.connects()).toBe(0);
+ });
+
+ test("a failing migration rolls back alone: the ones before it stay applied", async () => {
+ const folder = twoMigrations();
+ const { pool, client, state } = fakePool({
+ recorded: null,
+ failOn: /ADD COLUMN "title"/,
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationApplyError);
+ expect(error).toMatchObject({
+ failed: "0001_migration",
+ applied: ["0000_migration"],
+ pending: ["0001_migration"],
+ code: "42P07",
+ });
+ expect((error as Error).message).toBe(
+ "Migration 0001_migration failed (SQLSTATE 42P07) and was rolled back. Applied before the failure: 0000_migration. Not applied: 0001_migration.",
+ );
+ expect(state.recorded).toEqual([
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ ]);
+ expect(steps(client.statements).slice(-6)).toEqual([
+ "rollback",
+ ...SESSION_CLEANUP,
+ ]);
+ expect(client.released).toEqual({ error: undefined });
+ });
+
+ test("a migration older than the last recorded one, never applied, fails closed before taking the lock", async () => {
+ const folder = migrations([
+ { tag: "0000_a", when: 1000, sql: [`SELECT 1;`] },
+ { tag: "0001_parallel", when: 1500, sql: [`SELECT 2;`] },
+ { tag: "0002_b", when: 2000, sql: [`SELECT 3;`] },
+ ]);
+ const { pool, client } = fakePool({
+ recorded: [
+ { hash: hashOf(folder, "0000_a"), created_at: 1000 },
+ { hash: hashOf(folder, "0002_b"), created_at: 2000 },
+ ],
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationHistoryError);
+ expect(error).toMatchObject({ refusal: { stranded: ["0001_parallel"] } });
+ expect((error as Error).message).toBe(
+ 'Migration 0001_parallel is older than 0002_b, which schema "app" already recorded, and was never applied, so it would never run. ' +
+ `This happens when migrations from parallel branches merge. ${MIGRATION_HISTORY_REWRITE} ` +
+ "No migration was applied.",
+ );
+ expect(steps(client.statements)).toEqual(["journal table?", "recorded?"]);
+ });
+
+ test("a stranded migration also stops the pending ones after it", async () => {
+ const folder = migrations([
+ { tag: "0000_a", when: 1000, sql: [`SELECT 1;`] },
+ { tag: "0001_parallel", when: 1500, sql: [`SELECT 2;`] },
+ { tag: "0002_b", when: 2000, sql: [`SELECT 3;`] },
+ { tag: "0003_c", when: 3000, sql: [`SELECT 4;`] },
+ ]);
+ const { pool, client } = fakePool({
+ recorded: [
+ { hash: hashOf(folder, "0000_a"), created_at: 1000 },
+ { hash: hashOf(folder, "0002_b"), created_at: 2000 },
+ ],
+ });
+
+ await expect(
+ applyPendingMigrations(pool, options(folder)),
+ ).rejects.toBeInstanceOf(MigrationHistoryError);
+ expect(client.statements).not.toContain("SELECT 4;");
+ });
+
+ test("two migrations with one timestamp, neither matching the row recorded at it, fail closed before taking the lock", async () => {
+ const folder = migrations([
+ { tag: "0000_a", when: 1000, sql: [`SELECT 1;`] },
+ { tag: "0001_b", when: 1000, sql: [`SELECT 2;`] },
+ ]);
+ const { pool, client } = fakePool({
+ recorded: [{ hash: "hash-of-0000_a-before-the-edit", created_at: 1000 }],
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationHistoryError);
+ expect(error).toMatchObject({
+ refusal: {
+ ambiguous: {
+ when: 1000,
+ files: [
+ expect.objectContaining({ tag: "0000_a" }),
+ expect.objectContaining({ tag: "0001_b" }),
+ ],
+ recorded: 1,
+ },
+ },
+ });
+ expect((error as Error).message).toMatch(
+ /^Schema "app" recorded 1 migration at 1970-01-01T00:00:01\.000Z, and 2 are committed with that timestamp \(0000_a, 0001_b\), none with a recorded hash\./,
+ );
+ expect(steps(client.statements)).toEqual(["journal table?", "recorded?"]);
+ });
+
+ test("an applied migration whose file changed is logged, and its change does not run", async () => {
+ const folder = twoMigrations();
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const { pool } = fakePool({
+ recorded: [
+ { hash: "the-hash-before-the-edit", created_at: 1000 },
+ { hash: hashOf(folder, "0001_migration"), created_at: 2000 },
+ ],
+ });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result).toMatchObject({ applied: [], edited: ["0000_migration"] });
+ expect(warn.mock.calls.flat().map(String).join(" ")).toContain(
+ "Migrations 0000_migration changed after schema app applied them",
+ );
+ });
+
+ test("recorded migrations that are not committed here are logged", async () => {
+ const folder = twoMigrations();
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const { pool } = fakePool({
+ recorded: [
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ { hash: hashOf(folder, "0001_migration"), created_at: 2000 },
+ { hash: "from-a-newer-release", created_at: 3000 },
+ ],
+ });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result).toMatchObject({ applied: [], unknown: 1 });
+ expect(warn.mock.calls.flat().map(String).join(" ")).toContain(
+ "Schema app recorded 1 migration(s) that are not committed here",
+ );
+ });
+
+ describe("onDrift: refuse (a deploy start)", () => {
+ const refusing = (folder: string) => ({
+ ...options(folder),
+ onDrift: "refuse" as const,
+ });
+
+ test("an applied migration whose file changed refuses before taking the lock, and names the fix", async () => {
+ const folder = twoMigrations();
+ const { pool, client, state } = fakePool({
+ recorded: [{ hash: "the-hash-before-the-edit", created_at: 1000 }],
+ });
+
+ const error = await applyPendingMigrations(pool, refusing(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationHistoryError);
+ expect(error).toMatchObject({ refusal: { edited: ["0000_migration"] } });
+ expect((error as Error).message).toBe(
+ 'Migration 0000_migration changed after schema "app" applied it, so its file is not what this branch ran. ' +
+ "Restore the file to the version this branch applied and put the change in a new migration. " +
+ "If the migration failed on deploy because of data, repair the rows on the deploy branch and deploy the unchanged file again. " +
+ "No migration was applied.",
+ );
+ expect(steps(client.statements)).toEqual(["journal table?", "recorded?"]);
+ expect(state.recorded).toHaveLength(1);
+ });
+
+ test("two edited migrations are both named", async () => {
+ const folder = twoMigrations();
+ const { pool } = fakePool({
+ recorded: [
+ { hash: "before-the-first-edit", created_at: 1000 },
+ { hash: "before-the-second-edit", created_at: 2000 },
+ ],
+ });
+
+ const error = await applyPendingMigrations(pool, refusing(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toMatchObject({
+ refusal: { edited: ["0000_migration", "0001_migration"] },
+ });
+ expect((error as Error).message).toMatch(
+ /^Migrations 0000_migration, 0001_migration changed after schema "app" applied them, so their files are not what this branch ran\. Restore each file/,
+ );
+ });
+
+ test.each([
+ ["LF", "\n", "crlf"],
+ ["CRLF", "\r\n", "lf"],
+ ] as const)(
+ "a file checked out with %s, recorded by a checkout with the other line endings, is applied, not edited",
+ async (_label, eol, recordedBy) => {
+ const folder = migrations([
+ {
+ tag: "0000_notes",
+ when: 1000,
+ sql: [`CREATE TABLE "app"."notes" (${eol} "id" integer${eol});`],
+ },
+ ]);
+ const { pool, client } = fakePool({
+ recorded: [
+ {
+ hash: hashOf(folder, "0000_notes", recordedBy),
+ created_at: 1000,
+ },
+ ],
+ });
+
+ const result = await applyPendingMigrations(pool, refusing(folder));
+
+ expect(result).toMatchObject({ applied: [], edited: [], unknown: 0 });
+ expect(steps(client.statements)).toEqual([
+ "journal table?",
+ "recorded?",
+ ]);
+ },
+ );
+
+ test("pending migrations next to recorded ones this checkout lacks refuse: the histories diverged", async () => {
+ const folder = twoMigrations();
+ const { pool, client, state } = fakePool({
+ recorded: [
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ { hash: "from-a-branch-deployed-early", created_at: 1500 },
+ ],
+ });
+
+ const error = await applyPendingMigrations(pool, refusing(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationHistoryError);
+ expect(error).toMatchObject({
+ refusal: {
+ diverged: {
+ unrecorded: ["0001_migration"],
+ unknown: [
+ { hash: "from-a-branch-deployed-early", createdAt: 1500 },
+ ],
+ },
+ },
+ });
+ expect((error as Error).message).toBe(
+ 'Schema "app" recorded 1 migration this checkout does not have (created 1970-01-01T00:00:01.500Z), and 0001_migration is committed here but not applied. ' +
+ "The deploy branch ran migrations from a commit this one lacks. " +
+ "Deploy a commit whose journal contains the recorded migrations, or merge them into main unchanged, before main's own migrations. " +
+ "No migration was applied.",
+ );
+ expect(steps(client.statements)).toEqual(["journal table?", "recorded?"]);
+ expect(state.recorded).toHaveLength(2);
+ });
+
+ const strandedBehindABranch = () => {
+ const folder = migrations([
+ { tag: "0000_a", when: 1000, sql: [`SELECT 1;`] },
+ { tag: "0001_main", when: 1200, sql: [`SELECT 2;`] },
+ ]);
+ return {
+ folder,
+ recorded: [
+ { hash: hashOf(folder, "0000_a"), created_at: 1000 },
+ { hash: "from-a-branch-deployed-early", created_at: 1500 },
+ ],
+ };
+ };
+
+ test("a stranded migration next to recorded ones this checkout lacks refuses as diverged, with the same runbook", async () => {
+ const { folder, recorded } = strandedBehindABranch();
+ const { pool, client, state } = fakePool({ recorded });
+
+ const error = await applyPendingMigrations(pool, refusing(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationHistoryError);
+ expect(error).toMatchObject({
+ refusal: {
+ diverged: {
+ unrecorded: ["0001_main"],
+ unknown: [
+ { hash: "from-a-branch-deployed-early", createdAt: 1500 },
+ ],
+ },
+ },
+ });
+ expect((error as Error).message).toBe(
+ 'Schema "app" recorded 1 migration this checkout does not have (created 1970-01-01T00:00:01.500Z), and 0001_main is committed here but not applied. ' +
+ "The deploy branch ran migrations from a commit this one lacks. " +
+ "Deploy a commit whose journal contains the recorded migrations, or merge them into main unchanged, before main's own migrations. " +
+ "No migration was applied.",
+ );
+ expect(steps(client.statements)).toEqual(["journal table?", "recorded?"]);
+ expect(state.recorded).toHaveLength(2);
+ });
+
+ test("the same history without the option refuses as stranded, with the history rewrite and no advice to delete main's migration", async () => {
+ const { folder, recorded } = strandedBehindABranch();
+ const { pool } = fakePool({ recorded });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationHistoryError);
+ expect(error).toMatchObject({ refusal: { stranded: ["0001_main"] } });
+ expect((error as Error).message).toMatch(
+ /^Migration 0001_main is older than the migration recorded at 1970-01-01T00:00:01\.500Z, which schema "app" already recorded, and was never applied, so it would never run\. /,
+ );
+ expect((error as Error).message).toContain(MIGRATION_HISTORY_REWRITE);
+ expect((error as Error).message).not.toMatch(/delete/i);
+ });
+
+ test("recorded migrations this checkout lacks with nothing pending (a code rollback) only warn", async () => {
+ const folder = twoMigrations();
+ const warn = vi
+ .spyOn(console, "warn")
+ .mockImplementation(() => undefined);
+ const { pool } = fakePool({
+ recorded: [
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ { hash: hashOf(folder, "0001_migration"), created_at: 2000 },
+ { hash: "from-a-newer-release", created_at: 3000 },
+ ],
+ });
+
+ const result = await applyPendingMigrations(pool, refusing(folder));
+
+ expect(result).toMatchObject({ applied: [], unknown: 1 });
+ expect(warn.mock.calls.flat().map(String).join(" ")).toContain(
+ "Schema app recorded 1 migration(s) that are not committed here",
+ );
+ });
+
+ test("without the option, an edited migration and a divergence still only warn", async () => {
+ const folder = twoMigrations();
+ const warn = vi
+ .spyOn(console, "warn")
+ .mockImplementation(() => undefined);
+ const { pool } = fakePool({
+ recorded: [
+ { hash: "the-hash-before-the-edit", created_at: 1000 },
+ { hash: "from-a-branch-deployed-early", created_at: 1500 },
+ ],
+ });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result).toMatchObject({
+ applied: ["0001_migration"],
+ edited: ["0000_migration"],
+ unknown: 1,
+ });
+ expect(warn).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ test("a table lock not granted in time is retried, then fails with the hint", async () => {
+ const folder = twoMigrations();
+ const { pool, client } = fakePool({
+ recorded: [{ hash: hashOf(folder, "0000_migration"), created_at: 1000 }],
+ failOn: /ADD COLUMN "body"/,
+ failCode: "55P03",
+ });
+
+ const error = await applyPendingMigrations(pool, {
+ ...options(folder),
+ lockTimeoutMs: 1,
+ }).catch((caught: unknown) => caught);
+
+ expect(client.statements.filter((s) => s === "rollback")).toHaveLength(3);
+ expect((error as Error).message).toBe(
+ "Migration 0001_migration failed (SQLSTATE 55P03) and was rolled back. Not applied: 0001_migration. " +
+ "Another session held a lock on a table this migration changes for over 1ms, 3 times. Deploy again once the long-running query or transaction finishes.",
+ );
+ });
+
+ test("a table lock granted on the retry applies the migration", async () => {
+ const folder = twoMigrations();
+ const { pool } = fakePool({
+ recorded: [{ hash: hashOf(folder, "0000_migration"), created_at: 1000 }],
+ failOn: /ADD COLUMN "body"/,
+ failCode: "55P03",
+ failTimes: 1,
+ });
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+
+ const result = await applyPendingMigrations(pool, {
+ ...options(folder),
+ lockTimeoutMs: 1,
+ });
+
+ expect(result.applied).toEqual(["0001_migration"]);
+ });
+
+ test("the wait for another session's migration lock has a limit, and the error names the holder", async () => {
+ const folder = twoMigrations();
+ const { pool, client } = fakePool({
+ recorded: null,
+ lockHeld: true,
+ lockHolder: {
+ pid: 42,
+ application_name: "appkit-migrate",
+ state: "active",
+ },
+ });
+
+ const error = await applyPendingMigrations(pool, {
+ ...options(folder),
+ lockWaitMs: 0,
+ }).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(MigrationApplyError);
+ expect((error as Error).message).toBe(
+ "Waiting for the migration lock failed. Not applied: 0000_migration, 0001_migration. " +
+ "Session pid 42 (appkit-migrate, active) held the migration lock for over 0ms. Deploy again once it finishes; if it is stuck, end it with pg_terminate_backend.",
+ );
+ // Never locked, so never unlocked; the session settings are still reset.
+ expect(steps(client.statements).slice(-3)).toEqual([
+ "RESET client_connection_check_interval",
+ "RESET application_name",
+ "RESET statement_timeout",
+ ]);
+ });
+
+ test("a server that cannot check client connections still migrates, and warns how to end a killed instance's statement", async () => {
+ const folder = twoMigrations();
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const { pool, client } = fakePool({
+ recorded: null,
+ failOn: /client_connection_check_interval/,
+ failCode: "22023",
+ });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result.applied).toHaveLength(2);
+ expect(client.statements).not.toContain(
+ "RESET client_connection_check_interval",
+ );
+ expect(warn.mock.calls.flat().map(String).join(" ")).toContain(
+ "client_connection_check_interval not set (statement failed). If this instance dies while a migration statement runs, the server notices only once the statement ends, and the statement keeps its locks until then. " +
+ "To end it sooner, find its pid in pg_stat_activity (application_name 'appkit-migrate') and run select pg_terminate_backend(pid).",
+ );
+ });
+
+ test("an ownership failure (42501) names the schema owner and the connecting role", async () => {
+ const folder = twoMigrations();
+ const { pool } = fakePool({
+ recorded: null,
+ failOn: /CREATE TABLE "app"."notes"/,
+ failCode: "42501",
+ ownership: { owner: "old-app-sp", current_user: "new-app-sp" },
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toMatchObject({ code: "42501" });
+ expect((error as Error).message).toContain(
+ `Schema "app" is owned by "old-app-sp", but the app connects as "new-app-sp".`,
+ );
+ });
+
+ test("reading the recorded migrations fails (42501): the hint, and nothing applied", async () => {
+ const folder = twoMigrations();
+ const { pool } = fakePool({
+ recorded: [],
+ failOn: /^select hash, created_at/,
+ failCode: "42501",
+ ownership: { owner: "someone-else", current_user: "app-sp" },
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toMatchObject({ pending: [], code: "42501" });
+ expect((error as Error).message).toMatch(
+ /^Reading the recorded migrations failed \(SQLSTATE 42501\)\. No migration was applied\. Schema "app" is owned by "someone-else"/,
+ );
+ });
+
+ test("the app's own journal in a schema another role owns (public) is read and recorded into", async () => {
+ const folder = twoMigrations();
+ const { pool, state } = fakePool({
+ recorded: [{ hash: hashOf(folder, "0000_migration"), created_at: 1000 }],
+ journal: {
+ relkind: "r",
+ owner: "app-sp",
+ schema_owner: "pg_database_owner",
+ },
+ });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result.applied).toEqual(["0001_migration"]);
+ expect(state.recorded).toEqual([
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ { hash: hashOf(folder, "0001_migration"), created_at: 2000 },
+ ]);
+ });
+
+ test("another role's journal table without row security is read", async () => {
+ const folder = twoMigrations();
+ const { pool, client } = fakePool({
+ recorded: [
+ { hash: hashOf(folder, "0000_migration"), created_at: 1000 },
+ { hash: hashOf(folder, "0001_migration"), created_at: 2000 },
+ ],
+ journal: { relkind: "r", owner: "mallory", schema_owner: "app-sp" },
+ });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result.applied).toEqual([]);
+ expect(steps(client.statements)).toEqual(["journal table?", "recorded?"]);
+ });
+
+ test("another role's journal table is not recorded into, and the error names both roles and the fix", async () => {
+ const folder = twoMigrations();
+ const { pool, client, state } = fakePool({
+ recorded: [{ hash: hashOf(folder, "0000_migration"), created_at: 1000 }],
+ journal: { relkind: "r", owner: "mallory", schema_owner: "app-sp" },
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationJournalError);
+ expect((error as Error).message).toContain(
+ `"app"."__drizzle_migrations" is a table owned by "mallory". The migrator connects as "app-sp", which neither owns it nor inherits "mallory"`,
+ );
+ expect((error as Error).message).toContain(
+ `Have "mallory" run the migration, or have Lakebase move the table to "app-sp", since no Postgres role can hand it over. Then deploy again. No migration was applied.`,
+ );
+ expect(steps(client.statements)).toEqual([
+ "journal table?",
+ "recorded?",
+ ...SESSION_SETUP,
+ "journal table?",
+ "recorded?",
+ "begin",
+ "journal table?",
+ "rollback",
+ ...SESSION_CLEANUP,
+ ]);
+ expect(state.recorded).toHaveLength(1);
+ });
+
+ test("another role's journal table with row security is not read", async () => {
+ const folder = twoMigrations();
+ const { pool, client } = fakePool({
+ recorded: [],
+ journal: {
+ relkind: "r",
+ owner: "mallory",
+ schema_owner: "app-sp",
+ row_security: true,
+ },
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationJournalError);
+ expect((error as Error).message).toContain(
+ `"app"."__drizzle_migrations" is a table owned by "mallory" with row-level security enabled. The migrator connects as "app-sp", which neither owns it nor inherits "mallory"`,
+ );
+ expect((error as Error).message).toContain(
+ `Have "mallory" disable row-level security on it, or have Lakebase move the table to "app-sp", since no Postgres role can hand it over. Then deploy again.`,
+ );
+ expect(steps(client.statements)).toEqual(["journal table?"]);
+ });
+
+ test("a view at the journal's name is refused before anything runs", async () => {
+ const folder = twoMigrations();
+ const { pool, client } = fakePool({
+ recorded: [],
+ journal: { relkind: "v", owner: "app-sp" },
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationJournalError);
+ expect((error as Error).message).toContain(
+ `"app"."__drizzle_migrations" is a view owned by "app-sp". The migrator reads and records applied migrations only in an ordinary table`,
+ );
+ expect(steps(client.statements)).toEqual(["journal table?"]);
+ });
+
+ test("a connection failure carries the system error code", async () => {
+ const folder = twoMigrations();
+ const pool = {
+ connect: async () => {
+ throw Object.assign(new Error("connect ECONNREFUSED"), {
+ code: "ECONNREFUSED",
+ });
+ },
+ };
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationApplyError);
+ expect(error).toMatchObject({ code: undefined });
+ expect((error as Error).message).toBe(
+ "Connecting to the database failed (ECONNREFUSED). No migration was applied.",
+ );
+ });
+
+ test("a Node system error is not reported as a SQLSTATE", async () => {
+ const folder = twoMigrations();
+ const { pool } = fakePool({
+ recorded: [{ hash: hashOf(folder, "0000_migration"), created_at: 1000 }],
+ failOn: /ADD COLUMN "body"/,
+ failCode: "EPIPE",
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toMatchObject({ code: undefined });
+ expect((error as Error).message).toBe(
+ "Migration 0001_migration failed (EPIPE) and was rolled back. Not applied: 0001_migration.",
+ );
+ });
+
+ test("a failed unlock destroys the connection instead of returning it to the pool", async () => {
+ const folder = twoMigrations();
+ const { pool, client } = fakePool({
+ recorded: null,
+ failCleanupOn: /pg_advisory_unlock/,
+ });
+
+ await applyPendingMigrations(pool, options(folder));
+
+ // The remaining cleanup still runs.
+ expect(steps(client.statements).slice(-5)).toEqual(SESSION_CLEANUP);
+ expect(client.released?.error).toBeInstanceOf(Error);
+ });
+
+ test("a missing .sql file fails before connecting, naming the file", async () => {
+ const folder = twoMigrations();
+ fs.rmSync(path.join(folder, "0001_migration.sql"));
+ const fake = fakePool({ recorded: null });
+
+ const error = await applyPendingMigrations(
+ fake.pool,
+ options(folder),
+ ).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(MigrationFilesError);
+ expect((error as Error).message).toMatch(
+ /^Missing .*0001_migration\.sql, listed in meta\/_journal\.json\. Restore it from version control\.$/,
+ );
+ expect(fake.connects()).toBe(0);
+ });
+
+ test.each([
+ [
+ "is a directory",
+ (file: string) => {
+ fs.rmSync(file);
+ fs.mkdirSync(file);
+ },
+ "EISDIR",
+ ],
+ [
+ "has no read permission",
+ (file: string) => fs.chmodSync(file, 0o000),
+ "EACCES",
+ ],
+ ])(
+ "a .sql file that %s fails before connecting, naming the file and the reason",
+ async (_label, breakFile, reason) => {
+ if (reason === "EACCES" && process.getuid?.() === 0) return;
+ const folder = twoMigrations();
+ const file = path.join(folder, "0001_migration.sql");
+ breakFile(file);
+ const fake = fakePool({ recorded: null });
+
+ const error = await applyPendingMigrations(
+ fake.pool,
+ options(folder),
+ ).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(MigrationFilesError);
+ expect((error as Error).message).toContain(`Cannot read ${file}: `);
+ expect((error as Error).message).toContain(reason);
+ expect(fake.connects()).toBe(0);
+ },
+ );
+
+ test.each([
+ [
+ "not JSON",
+ "{",
+ /^Cannot read .*_journal\.json: .*Restore it from version control\.$/,
+ ],
+ [
+ "another dialect",
+ JSON.stringify({ version: "7", dialect: "mysql", entries: [] }),
+ /_journal\.json is not a drizzle-kit PostgreSQL migration journal$/,
+ ],
+ ])(
+ "a journal that is %s fails before connecting, naming the file",
+ async (_label, contents, message) => {
+ const folder = twoMigrations();
+ fs.writeFileSync(path.join(folder, "meta/_journal.json"), contents);
+ const fake = fakePool({ recorded: null });
+
+ const error = await applyPendingMigrations(
+ fake.pool,
+ options(folder),
+ ).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(MigrationFilesError);
+ expect((error as Error).message).toMatch(message);
+ expect(fake.connects()).toBe(0);
+ },
+ );
+});
+
+describe("migrationLockKey", () => {
+ test("is a stable signed 64-bit key per schema", () => {
+ const key = migrationLockKey("app");
+ expect(key).toBe(migrationLockKey("app"));
+ expect(key).not.toBe(migrationLockKey("public"));
+ const value = BigInt(key);
+ expect(value).toBeGreaterThanOrEqual(-(2n ** 63n));
+ expect(value).toBeLessThan(2n ** 63n);
+ });
+});
+
+const BASELINE_SQL = [
+ `CREATE TABLE "app"."notes" ("id" integer PRIMARY KEY, "body" text);`,
+ `CREATE TABLE "app"."tags" ("id" integer PRIMARY KEY);`,
+];
+
+/** 0000_baseline (notes, tags) followed by one ordinary migration. */
+const baselineThenMigration = () =>
+ migrations([
+ {
+ tag: "0000_baseline",
+ when: 1000,
+ sql: BASELINE_SQL,
+ snapshot: { notes: ["id", "body"], tags: ["id"] },
+ },
+ {
+ tag: "0001_migration",
+ when: 2000,
+ sql: [`ALTER TABLE "app"."notes" ADD COLUMN "title" text;`],
+ snapshot: { notes: ["id", "body", "title"], tags: ["id"] },
+ },
+ ]);
+
+const BASELINE_CATALOG: Array<[string, string]> = [
+ ["notes", "id"],
+ ["notes", "body"],
+ ["tags", "id"],
+];
+
+describe("applyPendingMigrations — baseline adoption", () => {
+ test("none of the baseline's tables exist: the baseline runs like any migration", async () => {
+ const folder = baselineThenMigration();
+ const { pool, client } = fakePool({ recorded: null, catalog: [] });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result).toMatchObject({
+ applied: ["0000_baseline", "0001_migration"],
+ adopted: [],
+ });
+ expect(client.statements).toContain(BASELINE_SQL[0]);
+ });
+
+ test("every baseline table and column exists: the baseline is recorded, not run, and later migrations apply", async () => {
+ const folder = baselineThenMigration();
+ const { pool, client, state } = fakePool({
+ recorded: null,
+ catalog: BASELINE_CATALOG,
+ });
+
+ const result = await applyPendingMigrations(pool, options(folder));
+
+ expect(result).toMatchObject({
+ applied: ["0001_migration"],
+ adopted: ["0000_baseline"],
+ });
+ expect(client.statements).not.toContain(BASELINE_SQL[0]);
+ expect(client.statements).toContain(
+ `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`,
+ );
+ // The adopted row carries exactly what drizzle-orm's migrator would have written.
+ expect(state.recorded?.[0]).toEqual({
+ hash: hashOf(folder, "0000_baseline"),
+ created_at: 1000,
+ });
+ });
+
+ test("adopting a lone baseline applies nothing else", async () => {
+ const folder = migrations([
+ {
+ tag: "0000_baseline",
+ when: 1000,
+ sql: BASELINE_SQL,
+ snapshot: { notes: ["id", "body"], tags: ["id"] },
+ },
+ ]);
+ const { pool } = fakePool({ recorded: null, catalog: BASELINE_CATALOG });
+
+ await expect(
+ applyPendingMigrations(pool, options(folder)),
+ ).resolves.toMatchObject({ applied: [], adopted: ["0000_baseline"] });
+ });
+
+ test("only part of the baseline exists: MigrationBaselineMismatchError, nothing recorded or run", async () => {
+ const folder = baselineThenMigration();
+ const { pool, client, state } = fakePool({
+ recorded: null,
+ catalog: [["notes", "id"]],
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationBaselineMismatchError);
+ expect((error as MigrationBaselineMismatchError).problems).toEqual([
+ "table app.notes is missing column body",
+ "table app.tags does not exist",
+ ]);
+ expect((error as Error).message).toMatch(
+ /^Cannot adopt 0000_baseline: schema "app" has no recorded migrations and only part of the baseline: /,
+ );
+ expect(state.recorded).toBeNull();
+ expect(client.statements).not.toContain("begin");
+ expect(client.released).toEqual({ error: undefined });
+ });
+
+ test("recording the adopted baseline fails: MigrationApplyError with the SQLSTATE and the ownership hint", async () => {
+ const folder = baselineThenMigration();
+ const { pool, client } = fakePool({
+ recorded: null,
+ catalog: BASELINE_CATALOG,
+ // The schema belongs to another role, so the journal table cannot be created in it.
+ failOn: /^CREATE TABLE "app"\."__drizzle_migrations"/,
+ failCode: "42501",
+ ownership: { owner: "someone-else", current_user: "app-sp" },
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationApplyError);
+ expect(error).toMatchObject({
+ failed: "0000_baseline",
+ pending: ["0000_baseline", "0001_migration"],
+ code: "42501",
+ });
+ expect((error as Error).message).toContain(
+ `Schema "app" is owned by "someone-else"`,
+ );
+ expect(client.statements).toContain("rollback");
+ expect(client.statements).not.toContain(
+ `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`,
+ );
+ });
+
+ test("with a recorded migration, the baseline is never adopted", async () => {
+ const folder = baselineThenMigration();
+ const { pool, client } = fakePool({
+ recorded: [{ hash: hashOf(folder, "0000_baseline"), created_at: 1000 }],
+ catalog: [["notes", "id"]],
+ });
+
+ await expect(
+ applyPendingMigrations(pool, options(folder)),
+ ).resolves.toMatchObject({ applied: ["0001_migration"], adopted: [] });
+ expect(
+ client.statements.some((s) => s.includes("pg_catalog.pg_attribute")),
+ ).toBe(false);
+ });
+
+ test("an empty journal table still adopts the baseline", async () => {
+ const folder = baselineThenMigration();
+ const { pool } = fakePool({ recorded: [], catalog: BASELINE_CATALOG });
+
+ await expect(
+ applyPendingMigrations(pool, options(folder)),
+ ).resolves.toMatchObject({
+ applied: ["0001_migration"],
+ adopted: ["0000_baseline"],
+ });
+ });
+
+ test("a migration failing after the adoption says the baseline stays recorded", async () => {
+ const folder = baselineThenMigration();
+ const { pool, state } = fakePool({
+ recorded: null,
+ catalog: BASELINE_CATALOG,
+ failOn: /ADD COLUMN "title"/,
+ });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationApplyError);
+ expect(error).toMatchObject({
+ pending: ["0001_migration"],
+ adopted: ["0000_baseline"],
+ });
+ expect((error as Error).message).toBe(
+ "Migration 0001_migration failed (SQLSTATE 42P07) and was rolled back. 0000_baseline stays recorded as applied: its tables already existed. Not applied: 0001_migration.",
+ );
+ expect(state.recorded).toHaveLength(1);
+ });
+
+ test("a missing baseline snapshot names the file", async () => {
+ const folder = baselineThenMigration();
+ fs.rmSync(path.join(folder, "meta/0000_snapshot.json"));
+ const { pool, client } = fakePool({ recorded: null });
+
+ const error = await applyPendingMigrations(pool, options(folder)).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toBeInstanceOf(MigrationFilesError);
+ expect((error as Error).message).toMatch(
+ /^Missing .*meta\/0000_snapshot\.json for 0000_baseline\. Restore it from version control/,
+ );
+ expect(client.released).toEqual({ error: undefined });
+ });
+});
diff --git a/packages/appkit/src/database/migrations/tests/fixtures.ts b/packages/appkit/src/database/migrations/tests/fixtures.ts
new file mode 100644
index 000000000..b2071b874
--- /dev/null
+++ b/packages/appkit/src/database/migrations/tests/fixtures.ts
@@ -0,0 +1,92 @@
+import { createHash } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import type { Journal } from "../paths";
+
+interface MigrationFixture {
+ tag: string;
+ when: number;
+ sql: string[];
+ /** Tables (name → columns) for meta/NNNN_snapshot.json. */
+ snapshot?: Record;
+}
+
+const folders: string[] = [];
+
+/** Write a v7 journal with one SQL file per entry, the way drizzle-kit lays them out. */
+export function writeMigrations(
+ entries: MigrationFixture[],
+ schemaName = "app",
+): string {
+ const folder = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-apply-"));
+ folders.push(folder);
+ fs.mkdirSync(path.join(folder, "meta"));
+ const journal: Journal = {
+ version: "7",
+ dialect: "postgresql",
+ entries: entries.map((entry, idx) => ({
+ idx,
+ version: "7",
+ when: entry.when,
+ tag: entry.tag,
+ breakpoints: true,
+ })),
+ };
+ fs.writeFileSync(
+ path.join(folder, "meta/_journal.json"),
+ JSON.stringify(journal),
+ );
+ entries.forEach((entry, idx) => {
+ fs.writeFileSync(
+ path.join(folder, `${entry.tag}.sql`),
+ entry.sql.join("--> statement-breakpoint\n"),
+ );
+ if (entry.snapshot) {
+ const tables = Object.fromEntries(
+ Object.entries(entry.snapshot).map(([name, columns]) => [
+ `${schemaName}.${name}`,
+ {
+ name,
+ schema: schemaName,
+ columns: Object.fromEntries(columns.map((c) => [c, { name: c }])),
+ },
+ ]),
+ );
+ fs.writeFileSync(
+ path.join(
+ folder,
+ "meta",
+ `${String(idx).padStart(4, "0")}_snapshot.json`,
+ ),
+ JSON.stringify({
+ version: "7",
+ dialect: "postgresql",
+ tables,
+ enums: {},
+ }),
+ );
+ }
+ });
+ return folder;
+}
+
+export function hashOf(
+ folder: string,
+ tag: string,
+ lineEndings?: "lf" | "crlf",
+): string {
+ let content = fs.readFileSync(path.join(folder, `${tag}.sql`), "utf-8");
+ if (lineEndings) {
+ content = content.replace(/\r\n/g, "\n");
+ if (lineEndings === "crlf") content = content.replace(/\n/g, "\r\n");
+ }
+ return createHash("sha256").update(content).digest("hex");
+}
+
+export function removeMigrationFolders(): void {
+ for (const folder of folders.splice(0)) {
+ fs.rmSync(folder, { recursive: true, force: true });
+ }
+}
diff --git a/packages/appkit/src/database/migrations/tests/history.test.ts b/packages/appkit/src/database/migrations/tests/history.test.ts
new file mode 100644
index 000000000..63a8a8f61
--- /dev/null
+++ b/packages/appkit/src/database/migrations/tests/history.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, test } from "vitest";
+
+import { type MigrationFile, reconcileMigrations } from "../history";
+
+const file = (
+ tag: string,
+ when: number,
+ hash = `hash-${tag}`,
+ hashes: readonly string[] = [hash],
+): MigrationFile => ({
+ tag,
+ idx: 0,
+ when,
+ hash,
+ hashes,
+ statements: [],
+});
+
+const tags = (files: readonly MigrationFile[]) => files.map((f) => f.tag);
+
+describe("reconcileMigrations", () => {
+ const files = [
+ file("0000_a", 1000),
+ file("0001_b", 2000),
+ file("0002_c", 3000),
+ ];
+
+ test("nothing recorded: every migration is pending", () => {
+ const history = reconcileMigrations(files, []);
+ expect(tags(history.pending)).toEqual(["0000_a", "0001_b", "0002_c"]);
+ expect(history.lastRecorded).toBeNull();
+ });
+
+ test("newer than the last recorded migration: pending", () => {
+ const history = reconcileMigrations(files, [
+ { hash: "hash-0000_a", createdAt: 1000 },
+ ]);
+ expect(tags(history.pending)).toEqual(["0001_b", "0002_c"]);
+ expect(history.stranded).toEqual([]);
+ expect(history.lastRecorded).toBe(1000);
+ });
+
+ test("older than the last recorded migration and never recorded: stranded", () => {
+ const history = reconcileMigrations(files, [
+ { hash: "hash-0000_a", createdAt: 1000 },
+ { hash: "hash-0002_c", createdAt: 3000 },
+ ]);
+ expect(tags(history.stranded)).toEqual(["0001_b"]);
+ expect(history.pending).toEqual([]);
+ });
+
+ test("recorded with another hash: edited", () => {
+ const history = reconcileMigrations(files, [
+ { hash: "before-the-edit", createdAt: 1000 },
+ { hash: "hash-0001_b", createdAt: 2000 },
+ { hash: "hash-0002_c", createdAt: 3000 },
+ ]);
+ expect(tags(history.edited)).toEqual(["0000_a"]);
+ expect(history.pending).toEqual([]);
+ });
+
+ test("recorded with the hash another checkout of the same file reads: applied, not edited", () => {
+ const checkedOutElsewhere = file("0000_a", 1000, "hash-0000_a", [
+ "hash-0000_a",
+ "hash-0000_a-with-crlf",
+ ]);
+ const history = reconcileMigrations(
+ [checkedOutElsewhere],
+ [{ hash: "hash-0000_a-with-crlf", createdAt: 1000 }],
+ );
+ expect(history.edited).toEqual([]);
+ expect(history.pending).toEqual([]);
+ expect(history.unknown).toEqual([]);
+ });
+
+ test("recorded rows no committed migration matches: unknown, and they still set the last recorded", () => {
+ const unknownRow = { hash: "newer-release", createdAt: 4000 };
+ const nullRow = { hash: "no-timestamp", createdAt: null };
+ const history = reconcileMigrations(files, [
+ { hash: "hash-0000_a", createdAt: 1000 },
+ { hash: "hash-0001_b", createdAt: 2000 },
+ { hash: "hash-0002_c", createdAt: 3000 },
+ unknownRow,
+ nullRow,
+ ]);
+ expect(history.unknown).toEqual([unknownRow, nullRow]);
+ expect(history.lastRecorded).toBe(4000);
+ expect(history.pending).toEqual([]);
+ expect(history.stranded).toEqual([]);
+ });
+
+ test("two entries with one `when` keep their own rows: both recorded is clean, one recorded strands the other", () => {
+ const twins = [file("0000_a", 1000), file("0001_twin", 1000)];
+ const both = reconcileMigrations(twins, [
+ { hash: "hash-0000_a", createdAt: 1000 },
+ { hash: "hash-0001_twin", createdAt: 1000 },
+ ]);
+ expect([...both.pending, ...both.stranded, ...both.edited]).toEqual([]);
+
+ const one = reconcileMigrations(twins, [
+ { hash: "hash-0000_a", createdAt: 1000 },
+ ]);
+ expect(tags(one.stranded)).toEqual(["0001_twin"]);
+ expect(one.edited).toEqual([]);
+ });
+
+ test("one row and two unmatched files at one `when`: ambiguous, so nothing is edited, pending or stranded", () => {
+ // A was applied and edited since; B was added by hand with A's timestamp.
+ const twins = [
+ file("0000_a", 1000, "hash-a-after-the-edit"),
+ file("0001_b", 1000),
+ ];
+ const history = reconcileMigrations(twins, [
+ { hash: "hash-0000_a", createdAt: 1000 },
+ ]);
+ expect(history.ambiguous).toEqual([
+ { when: 1000, files: twins, recorded: 1 },
+ ]);
+ expect([
+ ...history.pending,
+ ...history.stranded,
+ ...history.edited,
+ ]).toEqual([]);
+ expect(history.unknown).toEqual([]);
+ });
+
+ test("a second row at a committed `when` that no file matches: unknown, not edited", () => {
+ const other = { hash: "hash-other", createdAt: 1000 };
+ const history = reconcileMigrations(
+ [file("0000_a", 1000)],
+ [{ hash: "hash-0000_a", createdAt: 1000 }, other],
+ );
+ expect(history.unknown).toEqual([other]);
+ expect(history.edited).toEqual([]);
+ expect(history.ambiguous).toEqual([]);
+ });
+
+ test("two unmatched files and two unmatched rows at one `when`: ambiguous", () => {
+ const twins = [
+ file("0000_a", 1000, "hash-a-after-the-edit"),
+ file("0001_b", 1000, "hash-b-after-the-edit"),
+ ];
+ const history = reconcileMigrations(twins, [
+ { hash: "hash-0000_a", createdAt: 1000 },
+ { hash: "hash-0001_b", createdAt: 1000 },
+ ]);
+ expect(history.ambiguous).toEqual([
+ { when: 1000, files: twins, recorded: 2 },
+ ]);
+ expect(history.edited).toEqual([]);
+ expect(history.unknown).toEqual([]);
+ });
+
+ test("an exact match at a shared `when` is consumed before the rest are paired, so the pair left is edited", () => {
+ const twins = [
+ file("0000_a", 1000),
+ file("0001_b", 1000, "hash-b-after-the-edit"),
+ ];
+ const history = reconcileMigrations(twins, [
+ { hash: "hash-0001_b", createdAt: 1000 },
+ { hash: "hash-0000_a", createdAt: 1000 },
+ ]);
+ expect(tags(history.edited)).toEqual(["0001_b"]);
+ expect(history.ambiguous).toEqual([]);
+ expect(history.unknown).toEqual([]);
+ });
+
+ test("clean, pending, stranded and ambiguous timestamps classify independently", () => {
+ const all = [
+ file("0000_a", 1000),
+ file("0001_b", 2000, "hash-b-after-the-edit"),
+ file("0002_c", 2000),
+ file("0003_d", 3000),
+ file("0004_e", 2500),
+ ];
+ const history = reconcileMigrations(all, [
+ { hash: "hash-0000_a", createdAt: 1000 },
+ { hash: "hash-0001_b", createdAt: 2000 },
+ { hash: "hash-0003_d", createdAt: 3000 },
+ ]);
+ expect(history.ambiguous.map((entry) => tags(entry.files))).toEqual([
+ ["0001_b", "0002_c"],
+ ]);
+ expect(tags(history.stranded)).toEqual(["0004_e"]);
+ expect(history.pending).toEqual([]);
+ expect(history.edited).toEqual([]);
+ });
+});
diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts
new file mode 100644
index 000000000..bd966d8a2
--- /dev/null
+++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, test } from "vitest";
+
+import { ownershipHint } from "../ownership";
+
+describe("ownership: one owner per branch", () => {
+ test("insufficient_privilege gets the branch-owner rule and the fix, and never suggests ALTER OWNER", () => {
+ expect(ownershipHint("42501")).toBe(
+ "The connecting role lacks a privilege this migration needs: CREATE on the database, or ownership of the app schema and its tables. " +
+ "On the deploy branch that role is the app's service principal: bind the database to the app with CAN_CONNECT_AND_CREATE. " +
+ "If another role owns an object the migration changes, no Postgres role can hand it to the service principal; only Lakebase can move it.",
+ );
+ });
+
+ test("a schema owned by another role: two apps first, then the Lakebase-only recovery", () => {
+ const hint = ownershipHint("42501", {
+ schemaName: "app",
+ owner: "old-app-sp",
+ currentUser: "new-app-sp",
+ canCreate: false,
+ }) as string;
+ expect(hint).toContain(
+ `Schema "app" is owned by "old-app-sp", but the app connects as "new-app-sp".`,
+ );
+ const twoApps =
+ "If two apps share this database, give each its own schemaName in schema.ts.";
+ const recovery = `If "old-app-sp" belonged to a deleted app, or is the role of the person who removed the resource, someone with CAN MANAGE on the Lakebase project moves its objects with \`databricks postgres delete-role --reassign-owned-to \``;
+ expect(hint).toContain(twoApps);
+ expect(hint).toContain(recovery);
+ expect(hint.indexOf(twoApps)).toBeLessThan(hint.indexOf(recovery));
+ expect(hint).toContain(
+ `the app was recreated with a new service principal, or its database resource was removed and added again, and Lakebase handed the objects to "old-app-sp"`,
+ );
+ expect(hint).toContain(
+ `No Postgres role can hand them back to "new-app-sp"; only Lakebase can move them.`,
+ );
+ expect(hint).toContain(
+ "That moves every object the role owns on the branch and deletes the role, so first check what it owns in each database.",
+ );
+ expect(hint).not.toContain("ALTER");
+ expect(hint).toContain(
+ "On your dev or session branch, rerun `appkit db init`, which hands you the schema.",
+ );
+ });
+
+ test("a schema that does not exist yet points at CREATE on the database", () => {
+ expect(
+ ownershipHint("42501", {
+ schemaName: "app",
+ owner: null,
+ currentUser: "app-sp",
+ canCreate: null,
+ }),
+ ).toBe(
+ `Role "app-sp" cannot create schema "app". On the deploy branch that role is the app's service principal: bind the database to the app with CAN_CONNECT_AND_CREATE.`,
+ );
+ });
+
+ test("public without CREATE for the app gets the grant or the default schema", () => {
+ expect(
+ ownershipHint("42501", {
+ schemaName: "public",
+ owner: "pg_database_owner",
+ currentUser: "app-sp",
+ canCreate: false,
+ }),
+ ).toBe(
+ `Schema public belongs to "pg_database_owner", and the app's role "app-sp" has no CREATE on it. ` +
+ `Grant it once with GRANT CREATE ON SCHEMA public TO "app-sp", or drop schemaName from defineSchema() to use the default schema app, which the app creates and owns.`,
+ );
+ });
+
+ test("public with CREATE already granted: another role owns the object, and no role can hand it to the app", () => {
+ expect(
+ ownershipHint("42501", {
+ schemaName: "public",
+ owner: "pg_database_owner",
+ currentUser: "app-sp",
+ canCreate: true,
+ }),
+ ).toBe(
+ `Role "app-sp" can create in schema public, so an object this migration changes belongs to another role, and no Postgres role can hand it to "app-sp". ` +
+ "Drop schemaName from defineSchema() to use the default schema app, which the app creates and owns.",
+ );
+ });
+
+ test("any other failure gets no ownership hint", () => {
+ expect(ownershipHint("42P07")).toBeUndefined();
+ expect(ownershipHint(undefined)).toBeUndefined();
+ });
+});
diff --git a/packages/appkit/src/database/migrations/tests/tables-left-in-public.pg.test.ts b/packages/appkit/src/database/migrations/tests/tables-left-in-public.pg.test.ts
new file mode 100644
index 000000000..10a77e8ea
--- /dev/null
+++ b/packages/appkit/src/database/migrations/tests/tables-left-in-public.pg.test.ts
@@ -0,0 +1,69 @@
+import { randomUUID } from "node:crypto";
+
+import { Pool } from "pg";
+import { afterAll, afterEach, beforeAll, describe, expect, test } from "vitest";
+
+import { defineSchema, id } from "../../schema-builder";
+import {
+ catalogSqlOf,
+ detectTablesLeftInPublic,
+ locateTables,
+} from "../tables-left-in-public";
+
+// A real server, for what a fake cannot show: the catalog query, the array
+// parameter binding through pg, and the relkind filter. Point it at a scratch
+// database, e.g. APPKIT_TEST_PG_URL=postgres://localhost:5432/postgres
+const url = process.env.APPKIT_TEST_PG_URL;
+
+describe.skipIf(!url)("tables left in public, against Postgres", () => {
+ let pool: Pool;
+ const cleanup: string[] = [];
+ const unique = () => `appkit_test_${randomUUID().slice(0, 8)}`;
+
+ beforeAll(() => {
+ pool = new Pool({ connectionString: url, max: 2 });
+ });
+ afterAll(async () => {
+ await pool.end();
+ });
+ afterEach(async () => {
+ for (const statement of cleanup.splice(0)) await pool.query(statement);
+ });
+
+ test("finds tables in the target schema and in public, skipping views", async () => {
+ const schema = unique();
+ const [here, there, view] = [unique(), unique(), unique()];
+ cleanup.push(
+ `drop schema if exists "${schema}" cascade`,
+ `drop table if exists public."${there}"`,
+ `drop view if exists public."${view}"`,
+ );
+ await pool.query(`create schema "${schema}"`);
+ await pool.query(`create table "${schema}"."${here}" (id int)`);
+ await pool.query(`create table public."${there}" (id int)`);
+ await pool.query(`create view public."${view}" as select 1 as id`);
+
+ const placement = await locateTables(catalogSqlOf(pool), schema, [
+ here,
+ there,
+ view,
+ "never_created",
+ ]);
+
+ expect(placement).toEqual({ inSchema: [here], inPublic: [there] });
+ });
+
+ test("an app table still in public, with nothing in the default schema, is refused", async () => {
+ const table = unique();
+ cleanup.push(`drop table if exists public."${table}"`);
+ const schema = defineSchema(({ table: declare }) => ({
+ [table]: declare(table, { id: id() }),
+ }));
+ await pool.query(`create table public."${table}" (id int)`);
+
+ const refused = await detectTablesLeftInPublic(catalogSqlOf(pool), schema);
+
+ expect(refused).toContain(`public has ${table}`);
+ expect(refused).toContain('pass { schemaName: "public" }');
+ });
+});
diff --git a/packages/appkit/src/database/migrations/tests/tables-left-in-public.test.ts b/packages/appkit/src/database/migrations/tests/tables-left-in-public.test.ts
new file mode 100644
index 000000000..feb6a33a2
--- /dev/null
+++ b/packages/appkit/src/database/migrations/tests/tables-left-in-public.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, test, vi } from "vitest";
+
+import { defineSchema, id } from "../../schema-builder";
+import {
+ type CatalogSql,
+ catalogSqlOf,
+ detectTablesLeftInPublic,
+ locateTables,
+} from "../tables-left-in-public";
+
+type PlacementRow = { schema_name: string; table_name: string };
+
+/** A catalog that answers every lookup with the given (schema, table) rows. */
+function catalog(rows: PlacementRow[]) {
+ const sql = vi.fn(async () => rows) as unknown as CatalogSql;
+ return { sql, calls: sql as unknown as ReturnType };
+}
+
+const implicit = defineSchema(({ table }) => ({
+ boards: table("boards", { id: id() }),
+ notes: table("notes", { id: id() }),
+}));
+
+describe("catalogSqlOf", () => {
+ test("renders tagged SQL as numbered parameters and returns the rows", async () => {
+ const client = {
+ query: vi.fn(async () => ({ rows: [{ n: 1 }] })),
+ };
+ const sql = catalogSqlOf(client);
+
+ const rows = await sql`select ${"a"} as x, ${["b", "c"]}::text[] as y`;
+
+ expect(rows).toEqual([{ n: 1 }]);
+ expect(client.query).toHaveBeenCalledWith(
+ "select $1 as x, $2::text[] as y",
+ ["a", ["b", "c"]],
+ );
+ });
+});
+
+describe("locateTables", () => {
+ test("reports each table under the schema it was found in, in declaration order", async () => {
+ const { sql } = catalog([
+ { schema_name: "public", table_name: "notes" },
+ { schema_name: "app", table_name: "tags" },
+ { schema_name: "public", table_name: "boards" },
+ ]);
+
+ const placement = await locateTables(sql, "app", [
+ "boards",
+ "notes",
+ "tags",
+ ]);
+
+ expect(placement).toEqual({
+ inSchema: ["tags"],
+ inPublic: ["boards", "notes"],
+ });
+ });
+
+ test("passes the schema and the table names as parameter values", async () => {
+ const { sql, calls } = catalog([]);
+
+ await locateTables(sql, "playground", ["tags"]);
+
+ const [strings, ...values] = calls.mock.calls[0] as unknown as [
+ TemplateStringsArray,
+ ...unknown[],
+ ];
+ expect(strings.join("?")).toContain("pg_catalog.pg_class");
+ expect(values).toEqual(["playground", ["tags"]]);
+ });
+
+ test("asks nothing for an empty table list", async () => {
+ const { sql, calls } = catalog([]);
+
+ await expect(locateTables(sql, "app", [])).resolves.toEqual({
+ inSchema: [],
+ inPublic: [],
+ });
+ expect(calls).not.toHaveBeenCalled();
+ });
+});
+
+describe("detectTablesLeftInPublic", () => {
+ test("the default schema, nothing in it, and the tables in public: the refusal names them and the fix", async () => {
+ const { sql } = catalog([
+ { schema_name: "public", table_name: "boards" },
+ { schema_name: "public", table_name: "notes" },
+ ]);
+
+ const reason = await detectTablesLeftInPublic(sql, implicit);
+
+ expect(reason).toContain(
+ 'none of the declared tables exist in schema "app", but public has boards, notes',
+ );
+ expect(reason).toContain(
+ 'pass { schemaName: "public" } as the second argument of defineSchema()',
+ );
+ expect(reason).toContain("ALTER TABLE public. SET SCHEMA app");
+ expect(reason).toContain('pass { schemaName: "app" } explicitly');
+ });
+
+ test("some declared tables in public, none in app: still refused, naming only those in public", async () => {
+ const { sql } = catalog([{ schema_name: "public", table_name: "notes" }]);
+
+ await expect(detectTablesLeftInPublic(sql, implicit)).resolves.toContain(
+ "public has notes.",
+ );
+ });
+
+ test.each([
+ [
+ "a declared table already in app",
+ [
+ { schema_name: "app", table_name: "boards" },
+ { schema_name: "public", table_name: "notes" },
+ ],
+ ],
+ ["a fresh database", []],
+ ])("%s is migrated", async (_label, rows) => {
+ const { sql } = catalog(rows);
+
+ await expect(detectTablesLeftInPublic(sql, implicit)).resolves.toBe(
+ undefined,
+ );
+ });
+
+ test('schemaName "app" named explicitly is migrated without consulting the catalog', async () => {
+ const explicit = defineSchema(
+ ({ table }) => ({ notes: table("notes", { id: id() }) }),
+ { schemaName: "app" },
+ );
+ const { sql, calls } = catalog([
+ { schema_name: "public", table_name: "notes" },
+ ]);
+
+ await expect(detectTablesLeftInPublic(sql, explicit)).resolves.toBe(
+ undefined,
+ );
+ expect(calls).not.toHaveBeenCalled();
+ });
+
+ test("a schema with no tables is migrated without consulting the catalog", async () => {
+ const { sql, calls } = catalog([]);
+
+ await expect(
+ detectTablesLeftInPublic(
+ sql,
+ defineSchema(() => ({})),
+ ),
+ ).resolves.toBe(undefined);
+ expect(calls).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/appkit/src/database/runtime/tests/drizzle-data-path.test.ts b/packages/appkit/src/database/runtime/tests/drizzle-data-path.test.ts
index b9d35409b..7c9bc7241 100644
--- a/packages/appkit/src/database/runtime/tests/drizzle-data-path.test.ts
+++ b/packages/appkit/src/database/runtime/tests/drizzle-data-path.test.ts
@@ -23,22 +23,26 @@ import {
} from "../engine/drizzle-data-path";
import { returningColumns } from "../engine/translate";
-const schema = defineSchema((builder) => {
- const users = builder.table("users", {
- id: id(),
- email: text().unique(),
- name: text(),
- active: boolean(),
- secret: text().private(),
- });
- const posts = builder.table("posts", {
- id: id(),
- authorId: fk(() => users.id),
- title: text(),
- secret: text().private(),
- });
- return { users, posts };
-});
+// Explicitly public: the order-by assertion expects unqualified SQL ("users"."secret").
+const schema = defineSchema(
+ (builder) => {
+ const users = builder.table("users", {
+ id: id(),
+ email: text().unique(),
+ name: text(),
+ active: boolean(),
+ secret: text().private(),
+ });
+ const posts = builder.table("posts", {
+ id: id(),
+ authorId: fk(() => users.id),
+ title: text(),
+ secret: text().private(),
+ });
+ return { users, posts };
+ },
+ { schemaName: "public" },
+);
const users = schema.$tables.users;
const naturalKeySchema = defineSchema((builder) => ({
diff --git a/packages/appkit/src/database/runtime/tests/translate.test.ts b/packages/appkit/src/database/runtime/tests/translate.test.ts
index cf2c11fa9..cd90de104 100644
--- a/packages/appkit/src/database/runtime/tests/translate.test.ts
+++ b/packages/appkit/src/database/runtime/tests/translate.test.ts
@@ -35,27 +35,31 @@ import {
translateWhere,
} from "../engine/translate";
-const schema = defineSchema((builder) => {
- const users = builder.table("users", {
- id: id(),
- name: text(),
- age: integer(),
- active: boolean().notNull(),
- large: bigint().notNull(),
- createdAt: timestamp().notNull(),
- externalId: uuid().notNull(),
- status: enumColumn("user_status", ["active", "disabled"]).notNull(),
- metadata: jsonb(),
- secret: text().private(),
- });
- const posts = builder.table("posts", {
- id: id(),
- authorId: fk(() => users.id),
- title: text(),
- secret: text().private(),
- });
- return { users, posts };
-});
+// Explicitly public: the assertions expect unqualified column SQL ("users"."name").
+const schema = defineSchema(
+ (builder) => {
+ const users = builder.table("users", {
+ id: id(),
+ name: text(),
+ age: integer(),
+ active: boolean().notNull(),
+ large: bigint().notNull(),
+ createdAt: timestamp().notNull(),
+ externalId: uuid().notNull(),
+ status: enumColumn("user_status", ["active", "disabled"]).notNull(),
+ metadata: jsonb(),
+ secret: text().private(),
+ });
+ const posts = builder.table("posts", {
+ id: id(),
+ authorId: fk(() => users.id),
+ title: text(),
+ secret: text().private(),
+ });
+ return { users, posts };
+ },
+ { schemaName: "public" },
+);
const users = schema.$tables.users;
const dialect = new PgDialect();
diff --git a/packages/appkit/src/database/schema-builder/define-schema.ts b/packages/appkit/src/database/schema-builder/define-schema.ts
index 0970a5f35..2a62d9a6f 100644
--- a/packages/appkit/src/database/schema-builder/define-schema.ts
+++ b/packages/appkit/src/database/schema-builder/define-schema.ts
@@ -46,6 +46,11 @@ const RESERVED_OBJECT_KEYS = new Set(["__proto__", "prototype", "constructor"]);
const RESERVED_DATABASE_EXPORT_KEYS = new Set(["sql", "transaction"]);
// A global symbol lets typegen recognize schemas loaded through another AppKit instance.
const FINALIZED_SCHEMA = Symbol.for("@databricks/appkit.database.schema");
+// Whether defineSchema() was told the schema name, read by the migration guard
+// that refuses to create tables in the default schema next to an older copy in public.
+const EXPLICIT_SCHEMA_NAME = Symbol.for(
+ "@databricks/appkit.database.schema.explicitSchemaName",
+);
const TABLE_METADATA_KEYS = [
"$name",
"$schemaName",
@@ -72,9 +77,27 @@ function assertName(value: string, label: string): void {
}
}
+/** Table names defineSchema() refuses. */
+export function isReservedTableName(name: string): boolean {
+ return (
+ !name ||
+ RESERVED_OBJECT_KEYS.has(name) ||
+ RESERVED_DATABASE_EXPORT_KEYS.has(name)
+ );
+}
+
+/** Column keys that collide with the runtime metadata on a table handle. */
+function collidesWithMetadata(key: string): boolean {
+ return key.startsWith("$") || key === "and" || key === "or";
+}
+
+/** Column names defineSchema() refuses. */
+export function isReservedColumnName(name: string): boolean {
+ return !name || RESERVED_OBJECT_KEYS.has(name) || collidesWithMetadata(name);
+}
+
function assertTableName(value: string): void {
- assertName(value, "Table name");
- if (RESERVED_DATABASE_EXPORT_KEYS.has(value)) {
+ if (isReservedTableName(value)) {
throw new SchemaBuildError(`Table name "${value}" is reserved`);
}
}
@@ -120,7 +143,7 @@ function declareTable>(
const handle = Object.create(null) as Record;
for (const [key, column] of Object.entries(columns)) {
assertName(key, `Column name on table "${name}"`);
- if (key.startsWith("$") || key === "and" || key === "or") {
+ if (collidesWithMetadata(key)) {
throw new SchemaBuildError(
`Column "${name}.${key}" collides with AppKit runtime metadata`,
);
@@ -291,6 +314,7 @@ function publishSchema(
raw: ReadonlyMap,
candidates: ReadonlyMap,
schemaName: string,
+ explicitSchemaName: boolean,
): Schema {
const publications = [...raw.values()].map((table) => {
const candidate = candidates.get(table.name);
@@ -325,6 +349,9 @@ function publishSchema(
$engine: Object.freeze(engine),
};
Object.defineProperty(schema, FINALIZED_SCHEMA, { value: true });
+ Object.defineProperty(schema, EXPLICIT_SCHEMA_NAME, {
+ value: explicitSchemaName,
+ });
return Object.freeze(schema);
}
@@ -339,6 +366,18 @@ export function assertFinalizedSchema(value: unknown): asserts value is Schema {
}
}
+/** @internal True when `defineSchema()` was given `schemaName` rather than defaulting to `app`. */
+export function schemaNameIsExplicit(schema: Schema): boolean {
+ return Reflect.get(schema, EXPLICIT_SCHEMA_NAME) === true;
+}
+
+/**
+ * Postgres schema of every table when `schemaName` is omitted. Not `public`:
+ * the deployed app's service principal can create and own a schema of its
+ * own, but has no CREATE on `public`.
+ */
+export const DEFAULT_SCHEMA_NAME = "app";
+
/**
* Compile one declared schema. The returned type keeps the table names the
* builder returned, so `api.tables` can name only real tables.
@@ -347,7 +386,7 @@ export function defineSchema>(
builder: (context: SchemaBuilderContext) => TTables,
options?: DefineSchemaOptions,
): Schema> {
- const schemaName = options?.schemaName ?? "public";
+ const schemaName = options?.schemaName ?? DEFAULT_SCHEMA_NAME;
if (!schemaName) throw new SchemaBuildError("Schema name cannot be empty");
const state: DeclarationState = {
@@ -366,5 +405,10 @@ export function defineSchema>(
const relations = buildRelations(state.raw);
validateRelationKeys(state.raw, relations);
const candidates = prepareTables(state.raw, schemaName, relations);
- return publishSchema(state.raw, candidates, schemaName);
+ return publishSchema(
+ state.raw,
+ candidates,
+ schemaName,
+ options?.schemaName !== undefined,
+ );
}
diff --git a/packages/appkit/src/database/schema-builder/tests/define-schema.test.ts b/packages/appkit/src/database/schema-builder/tests/define-schema.test.ts
index 6afa07afe..a8fe2ac0b 100644
--- a/packages/appkit/src/database/schema-builder/tests/define-schema.test.ts
+++ b/packages/appkit/src/database/schema-builder/tests/define-schema.test.ts
@@ -79,8 +79,10 @@ describe("defineSchema finalization", () => {
expect(Object.getPrototypeOf(schema.$tables.users.$columns)).toBeNull();
});
- it("defaults to public and supports a safe custom schema", () => {
- expect(schema.$schemaName).toBe("public");
+ it("defaults to app and supports a safe custom schema", () => {
+ // Not public: the deployed app's service principal has no CREATE there.
+ expect(schema.$schemaName).toBe("app");
+ expect(schema.$tables.users.$schemaName).toBe("app");
const options: DefineSchemaOptions = { schemaName: "application" };
const custom = defineSchema(
(builder) => ({ widgets: builder.table("widgets", { id: id() }) }),
@@ -90,6 +92,26 @@ describe("defineSchema finalization", () => {
expect(custom.$tables.widgets.$schemaName).toBe("application");
});
+ it.each([
+ ["by default, in app", undefined, "app"],
+ ['with schemaName "public", unqualified', "public", undefined],
+ ] as const)("creates tables and enums %s", (_label, schemaName, expected) => {
+ const schema = defineSchema(
+ (builder) => ({
+ tickets: builder.table("tickets", {
+ status: builder.enum("ticket_status", ["open", "closed"]),
+ }),
+ }),
+ schemaName ? { schemaName } : undefined,
+ );
+ const config = getTableConfig(pgOf(schema.$tables.tickets.$engine));
+ expect(config.schema).toBe(expected);
+ expect(
+ (config.columns[0] as unknown as { enum?: { schema?: string } }).enum
+ ?.schema,
+ ).toBe(expected);
+ });
+
it("accepts the explicit builder context type", () => {
const build = (builder: SchemaBuilderContext) => {
const users: TableHandle<{ id: ColumnBuilder; email: ColumnBuilder }> =
diff --git a/packages/appkit/src/database/schema-builder/types.ts b/packages/appkit/src/database/schema-builder/types.ts
index d49a14b02..133cbb77a 100644
--- a/packages/appkit/src/database/schema-builder/types.ts
+++ b/packages/appkit/src/database/schema-builder/types.ts
@@ -157,6 +157,7 @@ export type TableHandle> = AppKitTable & {
};
export interface DefineSchemaOptions {
+ /** Postgres schema of every table. Default: `"app"`. */
readonly schemaName?: string;
}
diff --git a/packages/appkit/src/database/tests/branch-names.test.ts b/packages/appkit/src/database/tests/branch-names.test.ts
new file mode 100644
index 000000000..19774fc9a
--- /dev/null
+++ b/packages/appkit/src/database/tests/branch-names.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, test } from "vitest";
+
+import { developmentBranchKind } from "../branch-names";
+
+describe("developmentBranchKind", () => {
+ // The names `appkit db init` generates, at the edges of its naming rules.
+ test.each([
+ ["a person's dev branch", "dev-jane-a1b2c3"],
+ ["a dev branch from a dotted local part", "dev-jane-doe-2-a1b2c3"],
+ ["the fallback slug when nothing is left", "dev-user-a1b2c3"],
+ [
+ "a service principal's application id",
+ "dev-0a1b2c3d-4e5f-6789-abcd-ef0123456789-a1b2c3",
+ ],
+ ["a slug cut to 52 characters, 63 in all", `dev-${"a".repeat(52)}-a1b2c3`],
+ ])("%s is a dev branch", (_label, branch) => {
+ expect(developmentBranchKind(branch)).toBe("dev");
+ });
+
+ test.each([
+ ["a generated 8-character id", "session-a1b2c3-k3x9q2m7"],
+ ["a one-character id set by hand", "session-a1b2c3-x"],
+ ["a 48-character id, 63 in all", `session-a1b2c3-${"z9".repeat(24)}`],
+ ])("%s is a session branch", (_label, branch) => {
+ expect(developmentBranchKind(branch)).toBe("session");
+ });
+
+ test.each([
+ ["the production branch", "production"],
+ ["a branch that only starts with dev-", "dev-environment"],
+ ["a dev- branch without six hex characters", "dev-jane-a1b2c"],
+ ["a dev- branch with an uppercase hash", "dev-jane-A1B2C3"],
+ ["a dev- shape over 63 characters", `dev-${"a".repeat(53)}-a1b2c3`],
+ ["a session- branch that is not an agent session", "session-store"],
+ ["a session- branch with no hash", "session-k3x9q2m7"],
+ ["a session id over 48 characters", `session-a1b2c3-${"a".repeat(49)}`],
+ ])("%s is neither", (_label, branch) => {
+ expect(developmentBranchKind(branch)).toBeUndefined();
+ });
+});
diff --git a/packages/appkit/src/database/tooling/branch-sql.ts b/packages/appkit/src/database/tooling/branch-sql.ts
new file mode 100644
index 000000000..8f2de812e
--- /dev/null
+++ b/packages/appkit/src/database/tooling/branch-sql.ts
@@ -0,0 +1,24 @@
+import type { PoolClient } from "pg";
+
+import { inTransaction } from "../migrations/apply";
+import { type DbContext, withBranchPool } from "./context";
+
+/** Run work in one transaction on the `.env` branch. */
+export function runInTransaction(
+ ctx: DbContext,
+ work: (client: PoolClient) => Promise,
+): Promise {
+ return withBranchPool(ctx, async (pool) => {
+ const client = await pool.connect();
+ let failed: Error | undefined;
+ try {
+ return await inTransaction(client, () => work(client));
+ } catch (error) {
+ failed = error instanceof Error ? error : new Error(String(error));
+ throw error;
+ } finally {
+ // A connection whose transaction state is unknown is not reused.
+ client.release(failed);
+ }
+ });
+}
diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts
new file mode 100644
index 000000000..008878441
--- /dev/null
+++ b/packages/appkit/src/database/tooling/check.ts
@@ -0,0 +1,201 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { MIGRATION_HISTORY_REWRITE } from "shared";
+import { z } from "zod";
+
+import { DEFAULT_SCHEMA_FILE } from "../../plugins/database/load-schema";
+import { loadDatabaseSchema } from "../../type-generator/database";
+import {
+ type JournalEntry,
+ MigrationFilesError,
+ migrationFile,
+ migrationsFolder,
+ readJournal,
+ readJsonFile,
+ snapshotFile,
+} from "../migrations/paths";
+import type { DbContext } from "./context";
+import { requireSchemaFile } from "./migrate";
+import { hasUnmigratedChanges, ORIGIN_ID } from "./migrations";
+
+export interface CheckReport {
+ /** Committed migrations, in journal order. */
+ readonly migrations: readonly string[];
+ /** What is wrong with the committed history, each with its fix. */
+ readonly problems: readonly string[];
+ readonly ok: boolean;
+}
+
+/** Entries numbered or ordered in a way the migrator or drizzle-kit misreads. */
+function orderProblems(entries: readonly JournalEntry[]): string[] {
+ const problems: string[] = [];
+ entries.forEach((entry, index) => {
+ if (entry.idx !== index) {
+ problems.push(
+ `${entry.tag} is entry ${index} of meta/_journal.json, but its idx is ${entry.idx}, so drizzle-kit reads another snapshot for it. ${MIGRATION_HISTORY_REWRITE}`,
+ );
+ }
+ // The journal is parsed, not validated, so `when` can hold anything.
+ if (!Number.isSafeInteger(entry.when)) {
+ problems.push(
+ `The when of ${entry.tag} in meta/_journal.json is ${JSON.stringify(entry.when) ?? "missing"}, not an integer timestamp, so the migrator never runs it. ${MIGRATION_HISTORY_REWRITE}`,
+ );
+ return;
+ }
+ const before = entries[index - 1];
+ if (
+ before &&
+ Number.isSafeInteger(before.when) &&
+ entry.when <= before.when
+ ) {
+ problems.push(
+ `${entry.tag} is listed after ${before.tag} but was generated before it, so a branch that ran ${before.tag} never runs ${entry.tag}. ${MIGRATION_HISTORY_REWRITE}`,
+ );
+ }
+ });
+ return problems;
+}
+
+/** The parts of a snapshot that chain it to the one before. */
+interface SnapshotLink {
+ readonly id: string;
+ readonly prevId: string;
+}
+
+/** drizzle-kit's PostgreSQL v7 snapshot, as far as telling it from a stub needs. */
+const snapshotShape = z.object({
+ version: z.literal("7"),
+ dialect: z.literal("postgresql"),
+ id: z.string(),
+ prevId: z.string(),
+ tables: z.record(z.string(), z.unknown()),
+ enums: z.record(z.string(), z.unknown()),
+ schemas: z.record(z.string(), z.unknown()),
+});
+
+/** The snapshot's JSON, or undefined when it is not JSON, as when a merge left conflict markers in it. */
+function readSnapshotJson(file: string): unknown {
+ try {
+ return readJsonFile(file);
+ } catch (error) {
+ if (
+ error instanceof MigrationFilesError &&
+ error.cause instanceof SyntaxError
+ ) {
+ return undefined;
+ }
+ throw error;
+ }
+}
+
+/** The empty database drizzle-kit diffs the first migration from. */
+const ORIGIN: SnapshotLink = { id: ORIGIN_ID, prevId: "" };
+
+/**
+ * Each snapshot must follow the one before it, and the first one the empty
+ * database. Two migrations generated from the same snapshot on parallel
+ * branches both follow that one, so the later one was written without the
+ * other's changes.
+ */
+function chainProblems(
+ entries: readonly JournalEntry[],
+ links: readonly (SnapshotLink | null)[],
+): string[] {
+ const problems: string[] = [];
+ entries.forEach((entry, index) => {
+ const link = links[index];
+ const before = index === 0 ? ORIGIN : links[index - 1];
+ if (!link || !before || link.prevId === before.id) return;
+ if (index === 0) {
+ problems.push(
+ `${entry.tag} is the first entry of meta/_journal.json but was not generated from an empty database, so the migrations before it are missing. Restore them from version control.`,
+ );
+ return;
+ }
+ const parent = links.findIndex((other) => other?.id === link.prevId);
+ const after =
+ link.prevId === ORIGIN_ID
+ ? "from an empty database"
+ : parent === -1
+ ? "after a snapshot that is not committed"
+ : `after ${entries[parent]?.tag ?? "an earlier snapshot"}`;
+ problems.push(
+ `${entry.tag} was generated ${after}, not after ${entries[index - 1]?.tag}: they were written on parallel branches, so ${entry.tag} lacks the other's changes. ${MIGRATION_HISTORY_REWRITE}`,
+ );
+ });
+ return problems;
+}
+
+/**
+ * `appkit db check`: the committed migrations are in order, every file they
+ * list is committed, and schema.ts has no change without a migration. It
+ * imports schema.ts and needs no Databricks or Lakebase access, so CI runs it
+ * on every pull request.
+ */
+export async function runCheck(ctx: DbContext): Promise {
+ requireSchemaFile(ctx.root, "check");
+ const folder = migrationsFolder(ctx.root);
+ const shown = (file: string) => path.relative(ctx.root, file);
+ const entries = readJournal(folder)?.entries ?? [];
+ const problems = orderProblems(entries);
+
+ const links = entries.map((entry): SnapshotLink | null => {
+ const file = snapshotFile(folder, entry.idx);
+ if (!fs.existsSync(file)) {
+ problems.push(
+ `${shown(file)}, the snapshot of ${entry.tag}, is not committed. Restore it from version control: the next migration is generated from it.`,
+ );
+ return null;
+ }
+ const snapshot = snapshotShape.safeParse(readSnapshotJson(file));
+ if (snapshot.success) {
+ return { id: snapshot.data.id, prevId: snapshot.data.prevId };
+ }
+ problems.push(
+ `${shown(file)}, the snapshot of ${entry.tag}, is not a drizzle-kit snapshot. Restore it from version control.`,
+ );
+ return null;
+ });
+ for (const entry of entries) {
+ const file = migrationFile(folder, entry.tag);
+ if (!fs.existsSync(file)) {
+ problems.push(
+ `${shown(file)} is listed in meta/_journal.json but not committed. Restore it from version control.`,
+ );
+ }
+ }
+ const listed = new Set(entries.map((entry) => `${entry.tag}.sql`));
+ const unlisted = fs.existsSync(folder)
+ ? fs
+ .readdirSync(folder)
+ .filter((name) => name.endsWith(".sql") && !listed.has(name))
+ .sort()
+ : [];
+ for (const name of unlisted) {
+ problems.push(
+ `${shown(path.join(folder, name))} is not in meta/_journal.json, so no deploy runs it. ${MIGRATION_HISTORY_REWRITE}`,
+ );
+ }
+ problems.push(...chainProblems(entries, links));
+
+ // drizzle-kit diffs from the latest snapshot, which must exist.
+ if (entries.length === 0 || links.at(-1)) {
+ const schema = await loadDatabaseSchema(
+ path.join(ctx.root, DEFAULT_SCHEMA_FILE),
+ { showImportError: true },
+ );
+ if (await hasUnmigratedChanges(folder, schema)) {
+ const last = entries.at(-1)?.tag;
+ problems.push(
+ `${DEFAULT_SCHEMA_FILE} changed ${last ? `since ${last}` : "and no migration is committed"}, so the deployed app would not get the change. Run \`appkit db migrate\` and commit the migration it writes.`,
+ );
+ }
+ }
+
+ return {
+ migrations: entries.map((entry) => entry.tag),
+ problems,
+ ok: problems.length === 0,
+ };
+}
diff --git a/packages/appkit/src/database/tooling/clean.ts b/packages/appkit/src/database/tooling/clean.ts
new file mode 100644
index 000000000..83ac19f66
--- /dev/null
+++ b/packages/appkit/src/database/tooling/clean.ts
@@ -0,0 +1,323 @@
+import path from "node:path";
+
+import type { PoolClient } from "pg";
+
+import { DEFAULT_SCHEMA_FILE } from "../../plugins/database/load-schema";
+import { loadDatabaseSchema } from "../../type-generator/database";
+import { quoteIdentifier } from "../migrations/apply";
+import { schemaOwnership } from "../migrations/ownership";
+import { runInTransaction } from "./branch-sql";
+import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context";
+import { notYourBranch, resolveEnvBranch, writableEnvBranch } from "./guard";
+import { type HistoryLock, withHistoryLock } from "./history-lock";
+import { shown } from "./introspect/render";
+import { requireSchemaFile } from "./migrate";
+import { resourceId } from "./targets";
+
+/**
+ * Drop the app schema with everything in it, the migration journal included.
+ * Schema public is never dropped: only the relations, types and routines the
+ * connected role owns go, and objects an extension installed stay.
+ */
+export function cleanStatements(schemaName: string): readonly string[] {
+ if (schemaName !== "public") {
+ return [`DROP SCHEMA IF EXISTS ${quoteIdentifier(schemaName)} CASCADE`];
+ }
+ return [
+ `DO $appkit$
+DECLARE
+ me oid := (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = current_user);
+ ns oid := (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = 'public');
+ r record;
+BEGIN
+ FOR r IN
+ SELECT c.relname, c.relkind FROM pg_catalog.pg_class c
+ WHERE c.relnamespace = ns
+ AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
+ AND c.relowner = me
+ AND NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_depend d
+ WHERE d.classid = 'pg_catalog.pg_class'::regclass AND d.objid = c.oid
+ AND d.deptype IN ('a', 'i', 'e'))
+ LOOP
+ EXECUTE pg_catalog.format('DROP %s IF EXISTS public.%I CASCADE',
+ CASE r.relkind WHEN 'v' THEN 'VIEW' WHEN 'm' THEN 'MATERIALIZED VIEW'
+ WHEN 'f' THEN 'FOREIGN TABLE' WHEN 'S' THEN 'SEQUENCE' ELSE 'TABLE' END,
+ r.relname);
+ END LOOP;
+ FOR r IN
+ SELECT t.typname FROM pg_catalog.pg_type t
+ WHERE t.typnamespace = ns
+ AND t.typowner = me
+ AND (t.typtype IN ('e', 'd')
+ OR (t.typtype = 'c' AND EXISTS (
+ SELECT 1 FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid AND c.relkind = 'c')))
+ AND NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_depend d
+ WHERE d.deptype = 'e'
+ AND ((d.classid = 'pg_catalog.pg_type'::regclass AND d.objid = t.oid)
+ OR (d.classid = 'pg_catalog.pg_class'::regclass AND d.objid = t.typrelid)))
+ LOOP
+ EXECUTE pg_catalog.format('DROP TYPE IF EXISTS public.%I CASCADE', r.typname);
+ END LOOP;
+ FOR r IN
+ SELECT p.proname, p.prokind, pg_catalog.pg_get_function_identity_arguments(p.oid) AS args
+ FROM pg_catalog.pg_proc p
+ WHERE p.pronamespace = ns
+ AND p.prokind IN ('f', 'p', 'a', 'w')
+ AND p.proowner = me
+ AND NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_depend d
+ WHERE d.classid = 'pg_catalog.pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
+ LOOP
+ -- args is null when an earlier CASCADE already dropped the routine.
+ CONTINUE WHEN r.args IS NULL;
+ EXECUTE pg_catalog.format('DROP %s IF EXISTS public.%I(%s) CASCADE',
+ CASE r.prokind WHEN 'a' THEN 'AGGREGATE' WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END,
+ r.proname,
+ CASE WHEN r.prokind = 'a' AND r.args = '' THEN '*' ELSE r.args END);
+ END LOOP;
+END
+$appkit$`,
+ ];
+}
+
+/**
+ * Objects outside what clean drops that CASCADE removes with it: a view in
+ * another schema, a view over that view, a foreign key into an app table, a
+ * column of an app type. For public, "outside" also means owned by another
+ * role. The closure follows pg_depend the way DROP does: through normal, auto
+ * and internal dependencies, where a view's rewrite rule or a view's column
+ * stands for the view. Like DROP's own notice, it lists what a normal
+ * dependency reached; what went along automatically (an index on a dropped
+ * column) is not listed.
+ */
+const DEPENDENTS_SQL = `
+with recursive target as (
+ select oid from pg_catalog.pg_namespace where nspname = $1
+), me as (
+ select oid from pg_catalog.pg_roles where rolname = current_user
+), dropped(classid, objid) as (
+ select 'pg_catalog.pg_class'::regclass, c.oid from pg_catalog.pg_class c, target, me
+ where c.relnamespace = target.oid and (not $2 or c.relowner = me.oid)
+ union all
+ select 'pg_catalog.pg_type'::regclass, t.oid from pg_catalog.pg_type t, target, me
+ where t.typnamespace = target.oid and (not $2 or t.typowner = me.oid)
+ union all
+ select 'pg_catalog.pg_proc'::regclass, p.oid from pg_catalog.pg_proc p, target, me
+ where p.pronamespace = target.oid and (not $2 or p.proowner = me.oid)
+), gone(classid, objid, objsubid, listed) as (
+ select classid, objid, 0, false from dropped
+ union
+ select
+ case when d.classid = 'pg_catalog.pg_rewrite'::regclass
+ then 'pg_catalog.pg_class'::regclass else d.classid end,
+ coalesce(rule.ev_class, d.objid),
+ case when rule.oid is not null or view.oid is not null then 0 else d.objsubid end,
+ d.deptype = 'n'
+ from gone g
+ join pg_catalog.pg_depend d
+ on d.refclassid = g.classid and d.refobjid = g.objid
+ and (g.objsubid = 0 or d.refobjsubid = g.objsubid)
+ left join pg_catalog.pg_rewrite rule
+ on d.classid = 'pg_catalog.pg_rewrite'::regclass and rule.oid = d.objid
+ left join pg_catalog.pg_class view
+ on d.classid = 'pg_catalog.pg_class'::regclass and d.objsubid <> 0
+ and view.oid = d.objid and view.relkind in ('v', 'm')
+ where d.deptype in ('n', 'a', 'i')
+)
+select distinct o.label
+ from gone g
+ cross join lateral (
+ select c.relnamespace as namespace, c.relowner as owner,
+ pg_catalog.pg_describe_object(g.classid, g.objid, g.objsubid) as label
+ from pg_catalog.pg_class c
+ where g.classid = 'pg_catalog.pg_class'::regclass and c.oid = g.objid
+ union all
+ select con.connamespace, coalesce(c.relowner, t.typowner),
+ pg_catalog.pg_describe_object(g.classid, g.objid, 0)
+ from pg_catalog.pg_constraint con
+ left join pg_catalog.pg_class c on c.oid = con.conrelid
+ left join pg_catalog.pg_type t on t.oid = con.contypid
+ where g.classid = 'pg_catalog.pg_constraint'::regclass and con.oid = g.objid
+ union all
+ select p.pronamespace, p.proowner, pg_catalog.pg_describe_object(g.classid, g.objid, 0)
+ from pg_catalog.pg_proc p
+ where g.classid = 'pg_catalog.pg_proc'::regclass and p.oid = g.objid
+ union all
+ select t.typnamespace, t.typowner, pg_catalog.pg_describe_object(g.classid, g.objid, 0)
+ from pg_catalog.pg_type t
+ where g.classid = 'pg_catalog.pg_type'::regclass and t.oid = g.objid
+ union all
+ select c.relnamespace, c.relowner, pg_catalog.pg_describe_object(g.classid, g.objid, 0)
+ from pg_catalog.pg_trigger tg join pg_catalog.pg_class c on c.oid = tg.tgrelid
+ where g.classid = 'pg_catalog.pg_trigger'::regclass and tg.oid = g.objid
+ union all
+ select c.relnamespace, c.relowner, pg_catalog.pg_describe_object(g.classid, g.objid, 0)
+ from pg_catalog.pg_attrdef a join pg_catalog.pg_class c on c.oid = a.adrelid
+ where g.classid = 'pg_catalog.pg_attrdef'::regclass and a.oid = g.objid
+ union all
+ select c.relnamespace, c.relowner, pg_catalog.pg_describe_object(g.classid, g.objid, 0)
+ from pg_catalog.pg_policy pol join pg_catalog.pg_class c on c.oid = pol.polrelid
+ where g.classid = 'pg_catalog.pg_policy'::regclass and pol.oid = g.objid
+ ) o
+ cross join target
+ cross join me
+ where g.listed
+ and (o.namespace <> target.oid or ($2 and o.owner <> me.oid))
+ order by 1`;
+
+export async function readCascadeDependents(
+ client: Pick,
+ schemaName: string,
+): Promise {
+ const { rows } = await client.query<{ label: string }>(DEPENDENTS_SQL, [
+ schemaName,
+ schemaName === "public",
+ ]);
+ return rows.map((row) => shown(row.label));
+}
+
+/**
+ * The relations, types and routines in schema public that other roles own,
+ * which clean leaves with their rows; an extension's objects are not listed.
+ * Nothing for another schema, which the drop takes whole.
+ */
+const KEPT_SQL = `
+with ns as (
+ select oid from pg_catalog.pg_namespace where nspname = 'public'
+), me as (
+ select oid from pg_catalog.pg_roles where rolname = current_user
+), kept(classid, objid) as (
+ select 'pg_catalog.pg_class'::regclass, c.oid from pg_catalog.pg_class c, ns, me
+ where c.relnamespace = ns.oid and c.relowner <> me.oid
+ and c.relkind in ('r', 'p', 'v', 'm', 'f', 'S')
+ union all
+ select 'pg_catalog.pg_type'::regclass, t.oid from pg_catalog.pg_type t, ns, me
+ where t.typnamespace = ns.oid and t.typowner <> me.oid
+ and (t.typtype in ('e', 'd')
+ or (t.typtype = 'c' and exists (
+ select 1 from pg_catalog.pg_class c where c.oid = t.typrelid and c.relkind = 'c')))
+ union all
+ select 'pg_catalog.pg_proc'::regclass, p.oid from pg_catalog.pg_proc p, ns, me
+ where p.pronamespace = ns.oid and p.proowner <> me.oid and p.prokind in ('f', 'p', 'a', 'w')
+)
+select pg_catalog.pg_describe_object(k.classid, k.objid, 0) as label
+ from kept k
+ where not exists (
+ select 1 from pg_catalog.pg_depend d
+ where d.deptype = 'e' and d.classid = k.classid and d.objid = k.objid)
+ order by 1`;
+
+export async function readKeptObjects(
+ client: Pick,
+ schemaName: string,
+): Promise {
+ if (schemaName !== "public") return [];
+ const { rows } = await client.query<{ label: string }>(KEPT_SQL);
+ return rows.map((row) => shown(row.label));
+}
+
+export interface CleanReport {
+ readonly branch: string;
+ readonly schemaName: string;
+ /** Objects outside the app schema that depend on it, which the drop removes too. */
+ readonly dependents: readonly string[];
+ /** In schema public, the objects other roles own, which stay with their rows. */
+ readonly kept: readonly string[];
+}
+
+async function cleanTarget(ctx: DbContext) {
+ requireSchemaFile(ctx.root, "clean");
+ const branch = await writableEnvBranch(ctx, "clean");
+ const schema = await loadDatabaseSchema(
+ path.join(ctx.root, DEFAULT_SCHEMA_FILE),
+ { showImportError: true },
+ );
+ return { branch: branch.name, schemaName: schema.$schemaName };
+}
+
+/**
+ * An app schema another role owns is the fork's untouched copy. Only its owner
+ * may drop it, and init takes it over first.
+ */
+async function refuseUntouchedCopy(
+ client: Pick,
+ target: { readonly branch: string; readonly schemaName: string },
+): Promise {
+ if (target.schemaName === "public") return;
+ const { owner, currentUser } = await schemaOwnership(
+ client,
+ target.schemaName,
+ );
+ if (owner === null || owner === currentUser) return;
+ throw new Error(
+ `Refusing to clean: ${resourceId(target.branch)} still holds the rows the fork copied into schema "${target.schemaName}", which "${shown(owner)}" still owns, so your role cannot drop it. Run \`appkit db init\` to take it over and rebuild it from the committed migrations.`,
+ );
+}
+
+/** What `appkit db clean` would drop, read without changing anything. */
+export async function previewClean(ctx: DbContext): Promise {
+ const target = await cleanTarget(ctx);
+ return withBranchPool(ctx, async (pool) => {
+ await refuseUntouchedCopy(pool, target);
+ const dependents = await readCascadeDependents(pool, target.schemaName);
+ // Before the drop, another role's object that depends on yours is still there; it goes.
+ const kept = (await readKeptObjects(pool, target.schemaName)).filter(
+ (label) => !dependents.includes(label),
+ );
+ return { ...target, dependents, kept };
+ });
+}
+
+/**
+ * `appkit db clean`: remove every app-schema object, the migration journal
+ * included, on your dev or session branch. Refuses any other branch before
+ * connecting. One command at a time owns the checkout's history.
+ */
+export async function runClean(ctx: DbContext): Promise {
+ // Before the lock, which creates config/database.
+ requireSchemaFile(ctx.root, "clean");
+ return withHistoryLock(ctx.root, "clean", (lock) => cleanHolding(ctx, lock));
+}
+
+/** runClean for a caller that already holds the checkout's history lock. */
+export async function cleanHolding(
+ ctx: DbContext,
+ lock: HistoryLock,
+): Promise {
+ // Dropping the schema drops the branch's migration journal too.
+ lock.assertHeld();
+ const target = await cleanTarget(ctx);
+ return runInTransaction(ctx, async (client) => {
+ await refuseUntouchedCopy(client, target);
+ const dependents = await readCascadeDependents(client, target.schemaName);
+ for (const statement of cleanStatements(target.schemaName)) {
+ await client.query(statement);
+ }
+ const kept = await readKeptObjects(client, target.schemaName);
+ return { ...target, dependents, kept };
+ });
+}
+
+/**
+ * `appkit db clean --delete-branch`: delete this checkout's session branch.
+ * The dev branch is kept, so the next `appkit db init` finds it.
+ */
+export async function deleteSessionBranch(
+ ctx: DbContext,
+): Promise<{ readonly branch: string }> {
+ const env = await resolveEnvBranch(ctx);
+ if (!env) throw new Error(`Did not delete the branch: ${NO_ENV_BRANCH}.`);
+ const { name } = env.branch;
+ if (env.kind === "dev") {
+ throw new Error(
+ `Refusing to delete ${resourceId(name)}: --delete-branch deletes session branches only, and your dev branch stays for the next \`appkit db init\`. Delete it with \`databricks postgres delete-branch ${name}\`.`,
+ );
+ }
+ if (env.kind !== "session") {
+ throw new Error(`Refusing to delete the branch: ${notYourBranch(env)}.`);
+ }
+ await ctx.api().deleteBranch(name);
+ return { branch: name };
+}
diff --git a/packages/appkit/src/database/tooling/context.ts b/packages/appkit/src/database/tooling/context.ts
new file mode 100644
index 000000000..b1879afba
--- /dev/null
+++ b/packages/appkit/src/database/tooling/context.ts
@@ -0,0 +1,184 @@
+import type { LakebasePoolConfig } from "@databricks/lakebase";
+import type { Pool } from "pg";
+
+import { createLakebasePool } from "../../connectors/lakebase";
+import { endpointHosts } from "../../connectors/lakebase/endpoint-host";
+import { getClientOptions } from "../../context/client-options";
+import {
+ createWorkspaceClient,
+ type WorkspaceRequest,
+} from "../../workspace-client";
+import { currentIdentity } from "./identity";
+import { LakebaseApi, type LakebaseEndpoint } from "./lakebase-api";
+
+/** One Lakebase REST call, before LakebaseApi encodes it as a workspace request. */
+export interface ToolingRequest {
+ path: string;
+ method: "GET" | "POST" | "PATCH" | "DELETE";
+ query?: Record;
+ payload?: unknown;
+}
+
+/**
+ * The slice of AppKit's workspace client the tooling uses. It is also all the
+ * Lakebase pool needs, since token refresh goes through `request`.
+ */
+export interface ToolingWorkspaceClient {
+ request(request: WorkspaceRequest): Promise;
+ readonly currentUser: {
+ me(request: { attributes?: string }): Promise<{ userName?: string }>;
+ };
+ /** The resolved workspace host, which init writes to a new .env and verify compares with a target's host. */
+ getHost(): Promise;
+}
+
+/** Where a command runs: the app root, its environment and its Databricks identity. */
+export interface DbContext {
+ readonly root: string;
+ readonly env: NodeJS.ProcessEnv;
+ /** Lazy; the profile comes from DATABRICKS_CONFIG_PROFILE. */
+ workspace(): ToolingWorkspaceClient;
+ /** Lazy Lakebase REST client over workspace(). */
+ api(): LakebaseApi;
+}
+
+export function createDbContext(
+ options: { root?: string; env?: NodeJS.ProcessEnv } = {},
+): DbContext {
+ const root = options.root ?? process.cwd();
+ const env = options.env ?? process.env;
+ let client: ToolingWorkspaceClient | undefined;
+ let api: LakebaseApi | undefined;
+ const ctx: DbContext = {
+ root,
+ env,
+ workspace() {
+ if (!client) {
+ const profile = env.DATABRICKS_CONFIG_PROFILE;
+ client = createWorkspaceClient({
+ ...(profile ? { profile } : {}),
+ clientOptions: getClientOptions(),
+ });
+ }
+ return client;
+ },
+ api() {
+ api ??= new LakebaseApi(ctx.workspace());
+ return api;
+ },
+ };
+ return ctx;
+}
+
+/** The workspace host a Databricks config profile names, as the SDK resolves it; no API call. */
+export function profileHost(profile: string): Promise {
+ return createWorkspaceClient({
+ profile,
+ clientOptions: getClientOptions(),
+ }).getHost();
+}
+
+/**
+ * The guard checks the branch named by LAKEBASE_ENDPOINT, but the pool connects
+ * to PGHOST. The runtime only warns when it cannot verify that PGHOST serves that
+ * endpoint; a command that writes refuses instead.
+ */
+async function assertHostServesEndpoint(
+ ctx: DbContext,
+ endpoint: string,
+ host: string,
+): Promise {
+ let found: LakebaseEndpoint | null;
+ try {
+ found = await ctx.api().getEndpoint(endpoint);
+ } catch (error) {
+ throw new Error(
+ `Could not verify that PGHOST ${host} serves LAKEBASE_ENDPOINT ${endpoint}, so it did not connect.`,
+ { cause: error },
+ );
+ }
+ if (!found) {
+ throw new Error(
+ `LAKEBASE_ENDPOINT ${endpoint} does not exist, so it did not connect. Run \`appkit db init\` to point .env at your branch.`,
+ );
+ }
+ const hosts = endpointHosts(found);
+ if (!hosts.includes(host.toLowerCase())) {
+ throw new Error(
+ `PGHOST ${host} is not a host of LAKEBASE_ENDPOINT ${endpoint} (${hosts.length > 0 ? `expected ${hosts.join(" or ")}` : "it has no hosts"}), so it did not connect. Run \`appkit db init\` to rewrite .env.`,
+ );
+ }
+}
+
+export const NO_ENV_BRANCH =
+ "no branch is configured in .env (PGHOST, PGDATABASE and LAKEBASE_ENDPOINT); run `appkit db init`";
+
+/** Whether .env names a branch to connect to. */
+export function hasEnvBranch(env: NodeJS.ProcessEnv): boolean {
+ return Boolean(env.PGHOST && env.PGDATABASE && env.LAKEBASE_ENDPOINT);
+}
+
+const UNVERIFIED_SSL_MODES: ReadonlySet = new Set([
+ "prefer",
+ "disable",
+ "allow",
+]);
+
+/**
+ * The pool's TLS mode for PGSSLMODE. Of the modes createLakebasePool takes,
+ * only require verifies the server's certificate. Unset is passed as require
+ * too: createLakebasePool would read process.env.PGSSLMODE instead.
+ */
+function verifyingSslMode(
+ mode: string | undefined,
+): LakebasePoolConfig["sslMode"] {
+ if (mode === undefined || mode === "") return "require";
+ if (UNVERIFIED_SSL_MODES.has(mode)) {
+ throw new Error(
+ `PGSSLMODE=${mode} does not verify the server's certificate, so it did not connect. Set PGSSLMODE to require, or unset it.`,
+ );
+ }
+ return mode as LakebasePoolConfig["sslMode"];
+}
+
+/**
+ * The pool is created directly: initializeLakebasePool would look the endpoint
+ * and the user up a second time.
+ */
+async function openBranchPool(ctx: DbContext): Promise {
+ const { PGHOST, PGDATABASE, LAKEBASE_ENDPOINT } = ctx.env;
+ if (!PGHOST || !PGDATABASE || !LAKEBASE_ENDPOINT) {
+ throw new Error(`Did not connect: ${NO_ENV_BRANCH}.`);
+ }
+ const sslMode = verifyingSslMode(ctx.env.PGSSLMODE);
+ const [user] = await Promise.all([
+ ctx.env.PGUSER || currentIdentity(ctx).then(({ userName }) => userName),
+ assertHostServesEndpoint(ctx, LAKEBASE_ENDPOINT, PGHOST),
+ ]);
+ const port = ctx.env.PGPORT ? Number(ctx.env.PGPORT) : undefined;
+ return createLakebasePool({
+ host: PGHOST,
+ database: PGDATABASE,
+ endpoint: LAKEBASE_ENDPOINT,
+ user,
+ ...(port ? { port } : {}),
+ sslMode,
+ workspaceClient: ctx.workspace(),
+ // One-shot CLI pools: a small cap, and no lingering idle connections.
+ max: 2,
+ idleTimeoutMillis: 1_000,
+ });
+}
+
+/** Run fn with a pool on the .env branch, and close the pool after. */
+export async function withBranchPool(
+ ctx: DbContext,
+ fn: (pool: Pool) => Promise,
+): Promise {
+ const pool = await openBranchPool(ctx);
+ try {
+ return await fn(pool);
+ } finally {
+ await pool.end().catch(() => undefined);
+ }
+}
diff --git a/packages/appkit/src/database/tooling/drizzle-exports.ts b/packages/appkit/src/database/tooling/drizzle-exports.ts
new file mode 100644
index 000000000..038d0fa84
--- /dev/null
+++ b/packages/appkit/src/database/tooling/drizzle-exports.ts
@@ -0,0 +1,24 @@
+import { getTableColumns, is, type Table } from "drizzle-orm";
+import { PgEnumColumn } from "drizzle-orm/pg-core";
+
+import type { Schema } from "../schema-builder";
+
+/**
+ * The "module exports" drizzle-kit snapshots: every engine table plus every
+ * enum a column references. The pgSchema object is never included, so
+ * generated SQL contains no CREATE SCHEMA; the migrator creates the schema as
+ * the identity that applies the migrations, which then owns it.
+ */
+export function drizzleKitImports(schema: Schema): Record {
+ const imports: Record = Object.create(null);
+ for (const [name, table] of Object.entries(schema.$engine)) {
+ imports[`table:${name}`] = table;
+ const columns = getTableColumns(table as unknown as Table);
+ for (const column of Object.values(columns)) {
+ if (is(column, PgEnumColumn)) {
+ imports[`enum:${column.enum.enumName}`] = column.enum;
+ }
+ }
+ }
+ return imports;
+}
diff --git a/packages/appkit/src/database/tooling/drizzle-kit-install.ts b/packages/appkit/src/database/tooling/drizzle-kit-install.ts
new file mode 100644
index 000000000..980eefa4e
--- /dev/null
+++ b/packages/appkit/src/database/tooling/drizzle-kit-install.ts
@@ -0,0 +1,105 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+
+import {
+ declaredPackageManager,
+ detectPackageManager,
+ type PackageManager,
+} from "../../../../shared/src/cli/package-manager";
+import { DRIZZLE_KIT_VERSION, drizzleKitVersionAt } from "./migrations";
+
+/** Runs a command in `cwd`; throws when it fails. */
+export type RunCommand = (
+ command: string,
+ args: readonly string[],
+ cwd: string,
+) => void;
+
+/** Each manager's exact dev-dependency install. */
+const INSTALL_ARGS: Record = {
+ pnpm: ["add", "-D", "-E"],
+ yarn: ["add", "-D", "-E"],
+ bun: ["add", "-d", "--exact"],
+ npm: ["install", "--save-dev", "--save-exact"],
+};
+
+interface Install {
+ readonly command: string;
+ readonly args: readonly string[];
+}
+
+/**
+ * The install with the manager the app declares, by packageManager field or
+ * lockfile, in its own directory or the nearest ancestor's up to the
+ * repository root (a workspace member has neither; its root does). Without
+ * one, the manager that launched this command, else npm.
+ */
+export function drizzleKitInstall(root: string): Install {
+ let manager: PackageManager | null = null;
+ for (let dir = path.resolve(root); ; dir = path.dirname(dir)) {
+ manager = declaredPackageManager(dir);
+ if (
+ manager ||
+ fs.existsSync(path.join(dir, ".git")) ||
+ dir === path.dirname(dir)
+ ) {
+ break;
+ }
+ }
+ const command = manager ?? detectPackageManager(root, "npm");
+ return {
+ command,
+ args: [...INSTALL_ARGS[command], `drizzle-kit@${DRIZZLE_KIT_VERSION}`],
+ };
+}
+
+export const runCommand: RunCommand = (command, args, cwd) => {
+ const result = spawnSync(command, args, {
+ cwd,
+ encoding: "utf-8",
+ stdio: "pipe",
+ // Windows runs package managers through their .cmd shims.
+ shell: process.platform === "win32",
+ });
+ if (result.error) throw result.error;
+ if (result.status !== 0) {
+ const output = (result.stderr || result.stdout || "").trim();
+ throw new Error(
+ `${[command, ...args].join(" ")} exited with code ${result.status}${output ? `: ${output}` : ""}`,
+ );
+ }
+};
+
+/**
+ * Install drizzle-kit as an exact dev dependency when the app cannot resolve
+ * it, or resolves another version. Returns the command it ran; null when the
+ * pinned version was there, or there is no package.json to add it to.
+ */
+export function ensureDrizzleKit(
+ root: string,
+ run: RunCommand,
+ onStep: (message: string) => void,
+): string | null {
+ const found = drizzleKitVersionAt(root);
+ if (
+ found === DRIZZLE_KIT_VERSION ||
+ !fs.existsSync(path.join(root, "package.json"))
+ ) {
+ return null;
+ }
+ const { command, args } = drizzleKitInstall(root);
+ const line = [command, ...args].join(" ");
+ onStep(
+ `Installing drizzle-kit ${DRIZZLE_KIT_VERSION}${found ? ` in place of ${found}` : ""}, which writes migrations (${line})`,
+ );
+ try {
+ run(command, args, root);
+ } catch (error) {
+ throw new Error(
+ `Installing drizzle-kit failed. Run \`${line}\`, then rerun \`appkit db init\`.`,
+ { cause: error },
+ );
+ }
+ return line;
+}
diff --git a/packages/appkit/src/database/tooling/env-file.ts b/packages/appkit/src/database/tooling/env-file.ts
new file mode 100644
index 000000000..35e9abea2
--- /dev/null
+++ b/packages/appkit/src/database/tooling/env-file.ts
@@ -0,0 +1,125 @@
+import fs from "node:fs";
+
+import {
+ refuseSymlink as refuseLink,
+ SymlinkRefusedError,
+ writeFileAtomic,
+} from "./files";
+
+/**
+ * An entry's first line: indentation and `export ` (kept on rewrite), the key,
+ * the value. dotenv also reads `KEY: value` (a colon, then whitespace); a
+ * rewrite writes it back as `KEY=`.
+ */
+const ENTRY = /^(\s*(?:export\s+)?)([\w.-]+)(?:\s*=\s*|:\s+)(.*)$/;
+const QUOTES = new Set(['"', "'", "`"]);
+const PLAIN_VALUE = /^[A-Za-z0-9_./:@+-]*$/;
+
+/**
+ * A value dotenv reads back unchanged, always on one line: plain; else
+ * double-quoted, where dotenv turns `\n` and `\r` back into line breaks; else
+ * single-quoted, which dotenv takes literally.
+ */
+function formatValue(key: string, value: string): string {
+ if (PLAIN_VALUE.test(value)) return value;
+ if (!/["\\]/.test(value)) {
+ return `"${value.replace(/\r/g, "\\r").replace(/\n/g, "\\n")}"`;
+ }
+ if (!/['\r\n]/.test(value)) return `'${value}'`;
+ throw new Error(
+ `Cannot write ${key} to .env: its value mixes quotes, backslashes and line breaks.`,
+ );
+}
+
+/** Like dotenv, a quote preceded by a backslash does not close the value. */
+function closes(text: string, quote: string, from: number): boolean {
+ for (let i = from; i < text.length; i++) {
+ if (text[i] === quote && text[i - 1] !== "\\") return true;
+ }
+ return false;
+}
+
+interface Entry {
+ /** null for comments, blank lines and lines dotenv does not read as `KEY=`. */
+ readonly key: string | null;
+ readonly prefix: string;
+ readonly lines: readonly string[];
+}
+
+/** A quoted value without its closing quote continues on the next lines, as dotenv reads it. */
+function entries(lines: readonly string[]): Entry[] {
+ const out: Entry[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i] as string;
+ const match = ENTRY.exec(line);
+ if (!match) {
+ out.push({ key: null, prefix: "", lines: [line] });
+ continue;
+ }
+ const value = match[3] ?? "";
+ const quote = value[0] ?? "";
+ let end = i;
+ if (QUOTES.has(quote) && !closes(value, quote, 1)) {
+ const closing = lines.findIndex(
+ (next, j) => j > i && closes(next, quote, 0),
+ );
+ if (closing !== -1) end = closing;
+ }
+ out.push({
+ key: match[2] ?? null,
+ prefix: match[1] ?? "",
+ lines: lines.slice(i, end + 1),
+ });
+ i = end;
+ }
+ return out;
+}
+
+export function refuseSymlink(file: string): void {
+ try {
+ refuseLink(file);
+ } catch (error) {
+ if (!(error instanceof SymlinkRefusedError)) throw error;
+ throw new Error(
+ `Refusing to rewrite ${file}: it is a symbolic link to ${fs.readlinkSync(file)}, and writing through it would change that file. Replace it with a regular file, then rerun.`,
+ );
+ }
+}
+
+/**
+ * Replace `KEY=…` entries, append missing keys, and remove the keys whose
+ * value is null. Comments, blank lines, other keys, their order, `export `
+ * prefixes and CRLF line endings are kept. Written 0600 through a temporary
+ * file; a symbolic link is refused.
+ */
+export function updateEnvFile(
+ file: string,
+ values: Readonly>,
+): void {
+ refuseSymlink(file);
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : "";
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
+ const lines =
+ text.length > 0 ? text.replace(/\r?\n$/, "").split(/\r?\n/) : [];
+
+ const written = new Set();
+ const out: string[] = [];
+ for (const entry of entries(lines)) {
+ const { key } = entry;
+ if (key === null || !Object.hasOwn(values, key)) {
+ out.push(...entry.lines);
+ continue;
+ }
+ const value = values[key];
+ // Later duplicates of a managed key are dropped, so the value is unambiguous.
+ if (value === null || written.has(key)) continue;
+ written.add(key);
+ out.push(`${entry.prefix}${key}=${formatValue(key, value ?? "")}`);
+ }
+ for (const [key, value] of Object.entries(values)) {
+ if (value !== null && !written.has(key)) {
+ out.push(`${key}=${formatValue(key, value)}`);
+ }
+ }
+ writeFileAtomic(file, `${out.join(eol)}${eol}`, { mode: 0o600 });
+}
diff --git a/packages/appkit/src/database/tooling/files.ts b/packages/appkit/src/database/tooling/files.ts
new file mode 100644
index 000000000..bc0a8c89c
--- /dev/null
+++ b/packages/appkit/src/database/tooling/files.ts
@@ -0,0 +1,41 @@
+import { randomUUID } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+
+/** The destination of a write is a symbolic link, which a plain write would follow. */
+export class SymlinkRefusedError extends Error {
+ constructor(readonly file: string) {
+ super(`${file} is a symbolic link`);
+ this.name = "SymlinkRefusedError";
+ }
+}
+
+/** Throw when `file` is a symbolic link, dangling or not. A missing or regular file passes. */
+export function refuseSymlink(file: string): void {
+ if (fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) {
+ throw new SymlinkRefusedError(file);
+ }
+}
+
+/**
+ * Replace `file` with `content` through a sibling temporary file and a rename,
+ * so a crash leaves the old file or the new one, never half of either. The
+ * rename would swap a link at `file` for a plain file; the refusal says so instead.
+ */
+export function writeFileAtomic(
+ file: string,
+ content: string,
+ options: { readonly mode?: number } = {},
+): void {
+ refuseSymlink(file);
+ const temporary = path.join(
+ path.dirname(file),
+ `.${path.basename(file)}.${randomUUID()}.tmp`,
+ );
+ try {
+ fs.writeFileSync(temporary, content, { ...options, flag: "wx" });
+ fs.renameSync(temporary, file);
+ } finally {
+ fs.rmSync(temporary, { force: true });
+ }
+}
diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts
new file mode 100644
index 000000000..3dc81f905
--- /dev/null
+++ b/packages/appkit/src/database/tooling/guard.ts
@@ -0,0 +1,185 @@
+import { type DbContext, hasEnvBranch, NO_ENV_BRANCH } from "./context";
+import { currentIdentity } from "./identity";
+import type { LakebaseBranch } from "./lakebase-api";
+import { devBranchId, sessionBranchId } from "./naming";
+import {
+ type DeployBoundary,
+ parseResourceName,
+ readDeployBoundary,
+ readLocalTarget,
+ resourceId,
+} from "./targets";
+
+/** What a branch is to this developer, checked in this order. */
+type BranchKind =
+ | "default"
+ | "protected"
+ | "deploy-target"
+ | "dev"
+ | "session"
+ | "other";
+
+interface Classification {
+ readonly kind: BranchKind;
+ /** Why the branch takes no writes; undefined for dev and session branches. */
+ readonly reason?: string;
+}
+
+/**
+ * Why databricks.yml makes a branch one it deploys to; null when it does not.
+ * A reference the files cannot resolve may name any branch, so it refuses all;
+ * everyBranchRefusal names the references.
+ */
+export function deployRefusal(
+ boundary: DeployBoundary,
+ branch: string,
+): string | null {
+ if (boundary.unresolved.length > 0) {
+ return "databricks.yml may deploy to it through a reference this checkout's files do not resolve";
+ }
+ return boundary.branches.has(branch)
+ ? "it is a branch databricks.yml deploys to"
+ : null;
+}
+
+/**
+ * While databricks.yml has a reference this checkout's files cannot resolve,
+ * any branch may be one it deploys to: `migrate` applies migrations to no
+ * branch, and `init`, `introspect`, `clean` and `seed` refuse every branch.
+ * This says so, names the references and where to give them values; null when
+ * every reference resolves.
+ */
+export function everyBranchRefusal(boundary: DeployBoundary): string | null {
+ if (boundary.unresolved.length === 0) return null;
+ const references = boundary.unresolved
+ .map(({ target, at, written, file, environment }) => {
+ const values = [file, environment].filter(Boolean).join(" and ");
+ return `${at} in target ${target}${values ? ` with ${values}` : ""} (${written ? JSON.stringify(written) : "no value"})`;
+ })
+ .join(", ");
+ const where = [
+ "databricks.yml",
+ ...(boundary.unresolved.some(({ file }) => file)
+ ? ["the variable-overrides.json named"]
+ : []),
+ ...(boundary.unresolved.some(({ environment }) => environment)
+ ? ["the BUNDLE_VAR_ variable named"]
+ : []),
+ ].join(" or ");
+ return `The files do not resolve ${references}, so \`appkit db migrate\` applies migrations to no branch, and \`init\`, \`introspect\`, \`clean\` and \`seed\` refuse every branch. Give ${boundary.unresolved.length > 1 ? "them values" : "it a value"} in ${where}`;
+}
+
+/**
+ * Why a command writes nothing to a branch: `why`, then `advice` when it
+ * applies. While every branch is refused (see everyBranchRefusal), advice that
+ * leads to `appkit db init` or another branch cannot help, so the text names
+ * the references to resolve instead.
+ */
+export function writeRefusal(
+ why: string,
+ boundary: DeployBoundary,
+ advice?: string,
+): string {
+ const next = everyBranchRefusal(boundary) ?? advice;
+ return next ? `${why}. ${next}` : why;
+}
+
+export function classifyBranch(input: {
+ branch: LakebaseBranch;
+ userName: string;
+ sessionId: string | null;
+ /** What databricks.yml deploys to; the deployed app migrates those branches itself. */
+ boundary: DeployBoundary;
+}): Classification {
+ const { branch, userName, sessionId, boundary } = input;
+ if (branch.status?.default) {
+ return { kind: "default", reason: "it is the project's default branch" };
+ }
+ if (branch.status?.is_protected) {
+ return { kind: "protected", reason: "it is a protected branch" };
+ }
+ const deployReason = deployRefusal(boundary, branch.name);
+ if (deployReason) return { kind: "deploy-target", reason: deployReason };
+ const id = resourceId(branch.name);
+ if (id === devBranchId(userName)) return { kind: "dev" };
+ const session = sessionId ? sessionBranchId(userName, sessionId) : null;
+ if (id === session) return { kind: "session" };
+ return {
+ kind: "other",
+ reason: `it is not your dev branch (${devBranchId(userName)})${
+ session ? ` or this checkout's session branch (${session})` : ""
+ }`,
+ };
+}
+
+/**
+ * Commands write only to branches `appkit db init` created for this developer
+ * (dev-…) or this checkout (session-…).
+ */
+export function takesWrites(kind: BranchKind): boolean {
+ return kind === "dev" || kind === "session";
+}
+
+/** The .env branch, what it is to this developer, and the boundary that decided it. */
+interface EnvBranch extends Classification {
+ readonly branch: LakebaseBranch;
+ readonly boundary: DeployBoundary;
+}
+
+/** Why a command does not write to the .env branch, then `advice` when it applies (see writeRefusal). */
+export function notYourBranch(env: EnvBranch, advice?: string): string {
+ return writeRefusal(
+ `${resourceId(env.branch.name)} is not your dev or session branch (${env.reason})`,
+ env.boundary,
+ advice,
+ );
+}
+
+/**
+ * Classify the .env branch through the API, without connecting. null when .env
+ * does not name a branch to connect to (see NO_ENV_BRANCH).
+ */
+export async function resolveEnvBranch(
+ ctx: DbContext,
+): Promise {
+ const local = readLocalTarget(ctx.env);
+ const name = parseResourceName(local.endpoint ?? undefined)?.branch;
+ if (!name || !hasEnvBranch(ctx.env)) return null;
+ const boundary = readDeployBoundary(ctx.root, ctx.env);
+ const [branch, { userName }] = await Promise.all([
+ ctx.api().getBranch(name),
+ currentIdentity(ctx),
+ ]);
+ if (!branch) {
+ throw new Error(
+ `${writeRefusal(
+ `The .env branch ${name} does not exist (deleted or expired)`,
+ boundary,
+ "Run `appkit db init` to create or pick one",
+ )}.`,
+ );
+ }
+ return {
+ branch,
+ boundary,
+ ...classifyBranch({
+ branch,
+ userName,
+ sessionId: local.session,
+ boundary,
+ }),
+ };
+}
+
+/** The .env branch, for a command that only runs on your dev or session branch. */
+export async function writableEnvBranch(
+ ctx: DbContext,
+ action: string,
+): Promise {
+ const env = await resolveEnvBranch(ctx);
+ if (!env) throw new Error(`Did not ${action}: ${NO_ENV_BRANCH}.`);
+ if (!takesWrites(env.kind)) {
+ throw new Error(`Refusing to ${action}: ${notYourBranch(env)}.`);
+ }
+ return env.branch;
+}
diff --git a/packages/appkit/src/database/tooling/hand-off.ts b/packages/appkit/src/database/tooling/hand-off.ts
new file mode 100644
index 000000000..2370b0197
--- /dev/null
+++ b/packages/appkit/src/database/tooling/hand-off.ts
@@ -0,0 +1,192 @@
+import type { PoolClient } from "pg";
+
+import { schemaOwnership } from "../migrations/ownership";
+import { type DbContext, withBranchPool } from "./context";
+import { shown } from "./introspect/render";
+import type { LakebaseRole } from "./lakebase-api";
+import { resourceId } from "./targets";
+
+/**
+ * What can keep a role from being dropped once its objects in the current
+ * database are reassigned: objects it owns in other databases or shared ones
+ * (databases), and privileges granted to it anywhere.
+ */
+const DEPENDENCIES_SQL = `
+select case when s.deptype = 'o' then 'owned' else 'granted' end as kind,
+ coalesce(d.datname, '') as database, count(*)::int as count
+ from pg_catalog.pg_shdepend s
+ left join pg_catalog.pg_database d on d.oid = s.dbid
+ where s.refclassid = 'pg_catalog.pg_authid'::regclass
+ and s.refobjid = (select oid from pg_catalog.pg_roles where rolname = $1)
+ and not (s.deptype = 'o' and s.dbid = (select oid from pg_catalog.pg_database
+ where datname = current_database()))
+ group by 1, 2
+ order by 1, 2`;
+
+interface Dependents {
+ /** Empty for shared objects. */
+ readonly database: string;
+ readonly count: number;
+}
+
+interface RoleDependencies {
+ /** In other databases, or shared objects such as a database. */
+ readonly owned: readonly Dependents[];
+ readonly granted: readonly Dependents[];
+}
+
+export async function readRoleDependencies(
+ client: Pick,
+ role: string,
+): Promise {
+ const { rows } = await client.query<
+ Dependents & { kind: "owned" | "granted" }
+ >(DEPENDENCIES_SQL, [role]);
+ const of = (kind: "owned" | "granted") =>
+ rows
+ .filter((row) => row.kind === kind)
+ .map(({ database, count }) => ({ database: shown(database), count }));
+ return { owned: of("owned"), granted: of("granted") };
+}
+
+/**
+ * What the role owns in the current database besides the app schema and its
+ * contents, which a delete with reassign would hand over as well. System
+ * schemas are left out; a schema the role owns is listed by name.
+ */
+const OWNED_OUTSIDE_SQL = `
+select o.type || ' ' || o.identity as label
+ from pg_catalog.pg_shdepend s
+ cross join lateral pg_catalog.pg_identify_object(s.classid, s.objid, s.objsubid) o
+ where s.refclassid = 'pg_catalog.pg_authid'::regclass
+ and s.refobjid = (select oid from pg_catalog.pg_roles where rolname = $1)
+ and s.deptype = 'o'
+ and s.dbid = (select oid from pg_catalog.pg_database where datname = current_database())
+ and (o.schema is null
+ or (o.schema <> $2
+ and o.schema not in ('pg_catalog', 'information_schema')
+ and o.schema not like 'pg\\_toast%'
+ and o.schema not like 'pg\\_temp%'))
+ and not (o.type = 'schema' and o.identity = pg_catalog.quote_ident($2))
+ order by 1`;
+
+export async function readOwnedOutsideSchema(
+ client: Pick,
+ role: string,
+ schemaName: string,
+): Promise {
+ const { rows } = await client.query<{ label: string }>(OWNED_OUTSIDE_SQL, [
+ role,
+ schemaName,
+ ]);
+ return rows.map((row) => shown(row.label));
+}
+
+function describe(dependents: readonly Dependents[]): string {
+ return dependents
+ .map(
+ ({ database, count }) =>
+ `${database ? `database ${database}` : "shared objects"} (${count})`,
+ )
+ .join(", ");
+}
+
+interface HandOff {
+ /** The branch .env points at. */
+ readonly branch: string;
+ readonly database: string;
+ readonly schemaName: string;
+ /** Your role on the branch, which receives the objects. */
+ readonly developer: LakebaseRole;
+ readonly roles: readonly LakebaseRole[];
+ readonly onStep: (message: string) => void;
+}
+
+/**
+ * A fork copies its parent's objects with their owners, so on a fork of the
+ * deploy branch the app's service principal owns the app schema. Hand it to
+ * you by deleting that owner's copy of its role on this branch, with its
+ * objects reassigned to you. Only the app schema's owner is deleted, and only
+ * while the app schema is all it owns here: the reassign would hand over its
+ * other objects too, so those are listed and the delete is refused. Objects
+ * it owns in another database of the branch are refused too, since the
+ * reassign cannot reach them. Returns the owner, escaped for display; null
+ * when you already own the schema or it does not exist. Schema public is never handed off: it belongs to the database
+ * (pg_database_owner on PostgreSQL 15 and later, the bootstrap superuser
+ * before), never to an app, so AppKit never deletes its owner or reassigns its
+ * objects.
+ */
+export async function handOffAppSchema(
+ ctx: DbContext,
+ input: HandOff,
+): Promise {
+ if (input.schemaName === "public") return null;
+ const found = await withBranchPool(ctx, async (pool) => {
+ const { owner, currentUser } = await schemaOwnership(
+ pool,
+ input.schemaName,
+ );
+ if (!owner || owner === currentUser) return null;
+ return {
+ owner,
+ ownedOutside: await readOwnedOutsideSchema(pool, owner, input.schemaName),
+ dependencies: await readRoleDependencies(pool, owner),
+ };
+ });
+ if (!found) return null;
+
+ const { owner, ownedOutside, dependencies } = found;
+ const ownerName = shown(owner);
+ const where = `schema ${input.schemaName} in database ${shown(input.database)} on ${resourceId(input.branch)}`;
+ const role = input.roles.find((r) => r.status?.postgres_role === owner);
+ if (!role) {
+ throw new Error(
+ `Cannot hand ${where} to you: it belongs to "${ownerName}", which is not a Lakebase-managed role, and no Postgres role can hand it to you. .env already points at the branch. Set another schemaName in schema.ts, then rerun \`appkit db init\`.`,
+ );
+ }
+ if (ownedOutside.length > 0) {
+ throw new Error(
+ `Refusing to hand ${where} to you: deleting role "${ownerName}" would also give you what else it owns on this branch: ${ownedOutside.join(", ")}. .env already points at the branch. Reassign or drop them, or take them all with \`databricks postgres delete-role ${role.name} --reassign-owned-to ${input.developer.name}\`, then rerun \`appkit db init\`.`,
+ );
+ }
+ const inOtherDatabases = dependencies.owned.filter((d) => d.database);
+ if (inOtherDatabases.length > 0) {
+ throw new Error(
+ `Refusing to hand ${where} to you: role "${ownerName}" also owns objects in other databases on this branch, which deleting it cannot reassign: ${describe(inOtherDatabases)}. .env already points at the branch. Reassign or drop them in those databases, then rerun \`appkit db init\`.`,
+ );
+ }
+ input.onStep(
+ `Handing ${where} to you: deleting this branch's copy of role ${ownerName}, which owns it, with its objects reassigned to you`,
+ );
+ try {
+ await ctx
+ .api()
+ .deleteRole(role.name, { reassignOwnedTo: input.developer.name });
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ const { owned, granted } = dependencies;
+ const fix =
+ owned.length > 0 && granted.length > 0
+ ? "Reassign or drop what it owns and revoke its privileges"
+ : owned.length > 0
+ ? "Reassign or drop what it owns"
+ : "Revoke its privileges";
+ const details = [
+ ...(owned.length > 0
+ ? [
+ `"${ownerName}" still owns ${describe(owned)}, which block the delete.`,
+ ]
+ : []),
+ ...(granted.length > 0
+ ? [`Privileges granted to "${ownerName}": ${describe(granted)}.`]
+ : []),
+ ];
+ throw new Error(
+ details.length > 0
+ ? `Could not hand ${where} to you: deleting role "${ownerName}" failed (${reason}). ${details.join(" ")} .env already points at the branch. ${fix}, then rerun \`appkit db init\`.`
+ : `Could not hand ${where} to you: deleting role "${ownerName}" failed (${reason}). .env already points at the branch; rerun \`appkit db init\` to retry.`,
+ { cause: error },
+ );
+ }
+ return ownerName;
+}
diff --git a/packages/appkit/src/database/tooling/history-lock.ts b/packages/appkit/src/database/tooling/history-lock.ts
new file mode 100644
index 000000000..75c962e7a
--- /dev/null
+++ b/packages/appkit/src/database/tooling/history-lock.ts
@@ -0,0 +1,155 @@
+import { randomUUID } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { migrationsFolder } from "../migrations/paths";
+
+declare const held: unique symbol;
+
+/**
+ * Proof that the caller owns a checkout's migration history, from
+ * withHistoryLock until its callback settles. Only withHistoryLock makes one.
+ */
+export interface HistoryLock {
+ readonly [held]: true;
+ /** The checkout's migrations folder, the one this lock lets the caller write. */
+ readonly folder: string;
+ /** Throws once withHistoryLock's callback has settled. */
+ assertHeld(): void;
+}
+
+/** The lock file's contents: who holds it, and the token only that holder knows. */
+interface LockOwner {
+ readonly pid: number;
+ readonly host: string;
+ readonly command: string;
+ readonly startedAt: string;
+ readonly token: string;
+}
+
+const LOCK_FILE = ".appkit-db.lock";
+
+/** Ctrl+C and a plain kill; SIGKILL cannot be caught and leaves the file. */
+const RELEASE_SIGNALS = ["SIGINT", "SIGTERM"] as const;
+
+function readOwner(file: string): Partial | null {
+ try {
+ const owner: unknown = JSON.parse(fs.readFileSync(file, "utf-8"));
+ return typeof owner === "object" && owner !== null
+ ? (owner as Partial)
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Whether a process with this pid runs on this host; EPERM means it runs as another user. */
+function isRunning(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+function heldError(root: string, file: string): Error {
+ const relative = path.relative(root, file);
+ const owner = readOwner(file);
+ const recovery = `Make sure no appkit db command runs in this checkout, delete ${relative}, then rerun.`;
+ if (
+ typeof owner?.pid !== "number" ||
+ typeof owner.command !== "string" ||
+ owner.host !== os.hostname()
+ ) {
+ return new Error(
+ `${relative} says another appkit db command${typeof owner?.host === "string" ? ` on ${owner.host}` : ""} is changing the migration history. ${recovery}`,
+ );
+ }
+ if (!isRunning(owner.pid)) {
+ return new Error(
+ `\`appkit db ${owner.command}\` (pid ${owner.pid}) stopped without releasing ${relative}. ${recovery}`,
+ );
+ }
+ return new Error(
+ `Another \`appkit db ${owner.command}\` (pid ${owner.pid} on ${owner.host}, since ${owner.startedAt}) is changing the migration history in ${path.dirname(relative)}. Wait for it to finish, then rerun. If pid ${owner.pid} is not an appkit db command, for example because a reboot reused it, the lock is stale. ${recovery}`,
+ );
+}
+
+/**
+ * Run fn as the only writer of the checkout's migration history. The lock is
+ * config/database/.appkit-db.lock, created exclusively; a second command in
+ * the same checkout, in this process or another, fails with who holds it.
+ * Released when fn settles, the process exits, or SIGINT or SIGTERM arrives
+ * with nothing else listening for it. A process ended otherwise leaves the
+ * file behind: the next command reports it as stale, and it is deleted by
+ * hand, never taken over.
+ */
+export async function withHistoryLock(
+ root: string,
+ command: string,
+ fn: (lock: HistoryLock) => Promise,
+): Promise {
+ const folder = migrationsFolder(root);
+ const file = path.join(path.dirname(folder), LOCK_FILE);
+ const owner: LockOwner = {
+ pid: process.pid,
+ host: os.hostname(),
+ command,
+ startedAt: new Date().toISOString(),
+ token: randomUUID(),
+ };
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ let fd: number;
+ try {
+ fd = fs.openSync(file, "wx", 0o600);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ throw heldError(root, file);
+ }
+ try {
+ fs.writeFileSync(fd, JSON.stringify(owner));
+ } catch (error) {
+ fs.rmSync(file, { force: true });
+ throw error;
+ } finally {
+ fs.closeSync(fd);
+ }
+
+ let released = false;
+ const release = () => {
+ if (released) return;
+ released = true;
+ process.removeListener("exit", release);
+ for (const signal of RELEASE_SIGNALS)
+ process.removeListener(signal, onSignal);
+ if (readOwner(file)?.token === owner.token)
+ fs.rmSync(file, { force: true });
+ };
+ // A listener replaces the signal's default exit, so when this is the only
+ // one, release and re-raise. Another listener may keep the process running,
+ // and fn with it, so keep the lock; the exit listener releases it.
+ const onSignal = (signal: NodeJS.Signals) => {
+ if (process.listenerCount(signal) > 1) return;
+ release();
+ process.kill(process.pid, signal);
+ };
+ process.on("exit", release);
+ for (const signal of RELEASE_SIGNALS) process.on(signal, onSignal);
+ const lock = {
+ folder,
+ assertHeld() {
+ if (released) {
+ throw new Error(
+ `The migration history lock of ${root} was released; take it again before writing.`,
+ );
+ }
+ },
+ } as HistoryLock;
+ try {
+ return await fn(lock);
+ } finally {
+ release();
+ }
+}
diff --git a/packages/appkit/src/database/tooling/identity.ts b/packages/appkit/src/database/tooling/identity.ts
new file mode 100644
index 000000000..c0976b29c
--- /dev/null
+++ b/packages/appkit/src/database/tooling/identity.ts
@@ -0,0 +1,38 @@
+import type { DbContext } from "./context";
+import type { IdentityType } from "./lakebase-api";
+
+/** Who runs the command: the Postgres role name is the user name (email or SP client ID). */
+export interface Identity {
+ readonly userName: string;
+ readonly identityType: IdentityType;
+}
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/** A service principal's user name is its application (client) ID. */
+export function identityTypeOf(userName: string): IdentityType {
+ return UUID.test(userName) ? "SERVICE_PRINCIPAL" : "USER";
+}
+
+const identities = new WeakMap>();
+
+/** currentUser.me(), once per context. */
+export function currentIdentity(ctx: DbContext): Promise {
+ let identity = identities.get(ctx);
+ if (!identity) {
+ identity = ctx
+ .workspace()
+ .currentUser.me({})
+ .then(({ userName }) => {
+ if (!userName) {
+ throw new Error(
+ "Could not determine the current Databricks user (currentUser.me returned no userName). Check DATABRICKS_CONFIG_PROFILE.",
+ );
+ }
+ return { userName, identityType: identityTypeOf(userName) };
+ });
+ identity.catch(() => identities.delete(ctx));
+ identities.set(ctx, identity);
+ }
+ return identity;
+}
diff --git a/packages/appkit/src/database/tooling/index.ts b/packages/appkit/src/database/tooling/index.ts
new file mode 100644
index 000000000..2c0b23665
--- /dev/null
+++ b/packages/appkit/src/database/tooling/index.ts
@@ -0,0 +1,33 @@
+/**
+ * `@databricks/appkit/beta/database-tooling` — CLI-only logic behind `appkit db`.
+ * Loaded lazily by the shared CLI; it may import drizzle-kit, so the runtime
+ * plugin never imports it.
+ *
+ * Beta and internal to the AppKit CLI: it has no semver guarantee, and only
+ * the CLI of the same AppKit release should import it.
+ */
+export { type CheckReport, runCheck } from "./check";
+export {
+ type CleanReport,
+ deleteSessionBranch,
+ previewClean,
+ runClean,
+} from "./clean";
+export { createDbContext, type DbContext } from "./context";
+export {
+ type InitOptions,
+ type InitReport,
+ type InitStart,
+ type KeptCopy,
+ runInit,
+ type SchemaStart,
+} from "./init";
+export {
+ type IntrospectOptions,
+ type IntrospectReport,
+ runIntrospect,
+} from "./introspect";
+export { type MigrateOptions, type MigrateReport, runMigrate } from "./migrate";
+export { runSeed } from "./seed";
+export type { BranchMode } from "./targets";
+export { runVerify, type VerifyOptions, type VerifyReport } from "./verify";
diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts
new file mode 100644
index 000000000..af37c9da4
--- /dev/null
+++ b/packages/appkit/src/database/tooling/init.ts
@@ -0,0 +1,911 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import dotenv from "dotenv";
+import type { PoolClient } from "pg";
+
+import { DEFAULT_SCHEMA_FILE } from "../../plugins/database/load-schema";
+import { loadDatabaseSchema } from "../../type-generator/database";
+import { DEFAULT_SCHEMA_NAME } from "../schema-builder/define-schema";
+import { type CleanReport, cleanHolding } from "./clean";
+import { type DbContext, withBranchPool } from "./context";
+import {
+ ensureDrizzleKit,
+ type RunCommand,
+ runCommand,
+} from "./drizzle-kit-install";
+import { refuseSymlink, updateEnvFile } from "./env-file";
+import {
+ classifyBranch,
+ deployRefusal,
+ takesWrites,
+ writeRefusal,
+} from "./guard";
+import { handOffAppSchema } from "./hand-off";
+import { type HistoryLock, withHistoryLock } from "./history-lock";
+import { currentIdentity, type Identity } from "./identity";
+import {
+ introspectHolding,
+ type IntrospectOptions,
+ type IntrospectReport,
+ IntrospectRefusedError,
+} from "./introspect";
+import { shown } from "./introspect/render";
+import {
+ isAlreadyExists,
+ isBranchLimit,
+ isPermissionDenied,
+ type LakebaseBranch,
+ type LakebaseEndpoint,
+ type LakebaseRole,
+ READ_WRITE_ENDPOINT,
+ SUPERUSER_MEMBERSHIP,
+} from "./lakebase-api";
+import {
+ hasSchemaFile,
+ type MigrateReport,
+ migrateHolding,
+ requireSchemaFile,
+} from "./migrate";
+import {
+ devBranchId,
+ isUsersBranchId,
+ isUsersSessionBranchId,
+ newSessionId,
+ parseTtl,
+ SESSION_BRANCH_TTL,
+ sessionBranchId,
+} from "./naming";
+import {
+ planStart,
+ readSchemaState,
+ type SchemaStart,
+ type SchemaState,
+ type StartPlan,
+ tagForkCopy,
+ untagForkCopy,
+} from "./schema-state";
+import {
+ type BranchMode,
+ type DeployBoundary,
+ type DeployTarget,
+ type LocalTarget,
+ parseResourceName,
+ readDeployBoundary,
+ readDeployTarget,
+ readLocalTarget,
+ resourceId,
+} from "./targets";
+
+export type { SchemaStart } from "./schema-state";
+
+export interface InitOptions {
+ /**
+ * Default: this checkout's session branch when .env points at it, or when a
+ * --session run stopped before .env did; else your dev branch.
+ */
+ readonly mode?: BranchMode;
+ readonly schema?: SchemaStart;
+ readonly confirmClean?: (target: {
+ readonly branch: string;
+ readonly schemaName: string;
+ }) => Promise;
+ /** A new session branch's TTL as `--ttl` takes it (30m, 1h, 7d); default seven days. */
+ readonly ttl?: string;
+ /** Passed to migrate and introspect: false makes an ambiguous rename fail instead of prompting. */
+ readonly interactive?: boolean;
+ /** One line per step that calls the Lakebase API or changes a file. */
+ readonly onStep?: (message: string) => void;
+ readonly onWarning?: (message: string) => void;
+ /** Runs the drizzle-kit install. */
+ readonly runCommand?: RunCommand;
+}
+
+type RoleAction = "kept" | "created" | "updated";
+
+type RebuildReason = "fork-copy" | "requested";
+
+/** The app schema dropped, then recreated from the committed migrations. */
+interface Rebuild {
+ readonly clean: CleanReport;
+ readonly migrate: MigrateReport;
+ readonly reason: RebuildReason;
+}
+
+export type InitStart =
+ | { readonly kind: "none" }
+ | { readonly kind: "cancelled"; readonly schemaName: string }
+ | { readonly kind: "migrate"; readonly migrate: MigrateReport }
+ | {
+ readonly kind: "introspect";
+ readonly introspect: IntrospectReport;
+ readonly rebuilt: Rebuild | null;
+ }
+ | ({ readonly kind: "clean" } & Rebuild);
+
+export type KeptCopy =
+ | { readonly reason: "requested"; readonly from: string | null }
+ | { readonly reason: "public"; readonly objects: readonly string[] };
+
+export interface InitReport {
+ readonly mode: BranchMode;
+ readonly branch: string;
+ readonly created: boolean;
+ /** The branch a new fork was created from. */
+ readonly sourceBranch?: string;
+ /** When the branch expires; null for a branch without expiry. */
+ readonly expireTime: string | null;
+ readonly endpoint: string;
+ readonly endpointCreated: boolean;
+ readonly host: string;
+ /** The Postgres database .env names, escaped for display. */
+ readonly database: string;
+ readonly user: string;
+ readonly role: { readonly name: string; readonly action: RoleAction };
+ /**
+ * The Postgres role whose copy of the app schema was handed to you; null when
+ * you owned it, the schema is public, or `--schema none` left it alone.
+ */
+ readonly handedOff: string | null;
+ readonly keptCopy: KeptCopy | null;
+ readonly envFile: string;
+ /** The drizzle-kit install init ran; null when it was installed. */
+ readonly installed: string | null;
+ readonly start: InitStart;
+}
+
+const ENV_FILE = ".env";
+const DEFAULT_ENDPOINT_ID = "primary";
+/** An idle compute counts against the project's 20 active ones. */
+const SUSPEND_TIMEOUT = "300s";
+/** How long init waits for a read-write endpoint another run is still creating. */
+const ENDPOINT_HOST_WAIT = { intervalMs: 2_000, timeoutMs: 90_000 };
+/** Every Lakebase branch has it; used when nothing names another database. */
+const DEFAULT_DATABASE = "databricks_postgres";
+/**
+ * The one PGSSLMODE under which the Lakebase pool checks the server's
+ * certificate: it maps prefer to rejectUnauthorized: false, disable to no TLS,
+ * and rejects every other value.
+ */
+const TLS_MODE = "require";
+
+/** LAKEBASE_PROJECT, else the project of LAKEBASE_ENDPOINT, else of the bundle's postgres_branch. */
+function resolveProject(
+ local: LocalTarget,
+ deploy: DeployTarget | null,
+): string {
+ const project =
+ local.project ??
+ parseResourceName(local.endpoint ?? undefined)?.project ??
+ parseResourceName(deploy?.branch)?.project;
+ if (!project) {
+ throw new Error(
+ "No Lakebase project configured. Set LAKEBASE_PROJECT=projects/ in .env, or bind postgres_branch in databricks.yml (`databricks apps init` does).",
+ );
+ }
+ return project;
+}
+
+/** Drop .env connection values and a deploy binding that belong to another project than LAKEBASE_PROJECT. */
+function scopeToProject(
+ project: string,
+ local: LocalTarget,
+ deploy: DeployTarget | null,
+): { local: LocalTarget; deploy: DeployTarget | null } {
+ const inProject = (name: string | null | undefined) =>
+ parseResourceName(name ?? undefined)?.project === project;
+ return {
+ local: inProject(local.endpoint)
+ ? local
+ : { ...local, endpoint: null, database: null },
+ deploy: deploy && inProject(deploy.branch) ? deploy : null,
+ };
+}
+
+/**
+ * Session when .env names a session id and points at one of your session
+ * branches: this checkout's, or the gone one a rotation replaced before it
+ * stopped short of rewriting .env, which the rerun then finishes. Session too
+ * when .env points anywhere but your dev branch and the id's branch exists: a
+ * --session run that stopped before it rewrote .env. Dev otherwise.
+ */
+async function defaultMode(
+ ctx: DbContext,
+ project: string,
+ local: LocalTarget,
+ userName: string,
+): Promise {
+ if (!local.session) return "dev";
+ const branch = parseResourceName(local.endpoint ?? undefined)?.branch;
+ const id = branch ? resourceId(branch) : null;
+ if (id && isUsersSessionBranchId(userName, id)) return "session";
+ if (id === devBranchId(userName)) return "dev";
+ const stopped = await ctx
+ .api()
+ .getBranch(
+ `${project}/branches/${sessionBranchId(userName, local.session)}`,
+ );
+ return stopped && !isGone(stopped) ? "session" : "dev";
+}
+
+/**
+ * A plain rerun picks the dev branch when .env does not point at the session
+ * branch yet, so a failed session run's advice names --session.
+ */
+function withSessionRerun(error: unknown): unknown {
+ if (error instanceof Error) {
+ error.message = error.message.replace(
+ /([Rr]erun `appkit db init)(?! --session)/g,
+ "$1 --session",
+ );
+ }
+ return error;
+}
+
+function isGone(branch: LakebaseBranch, now = Date.now()): boolean {
+ if (branch.status?.current_state === "DELETED") return true;
+ const expires = branch.status?.expire_time;
+ return !!expires && Date.parse(expires) <= now;
+}
+
+interface BranchRequest {
+ readonly project: string;
+ readonly mode: BranchMode;
+ readonly identity: Identity;
+ readonly session: string | null;
+ /** The API's duration ("3600s"), and how the developer wrote it. */
+ readonly ttl: { readonly api: string; readonly label: string };
+ readonly boundary: DeployBoundary;
+ readonly envFile: string;
+ readonly deploy: DeployTarget | null;
+ readonly onStep: (message: string) => void;
+}
+
+type FoundBranch = {
+ readonly branch: LakebaseBranch;
+ readonly session: string | null;
+} & (
+ | { readonly created: false }
+ | {
+ /** Forked by this run. */
+ readonly created: true;
+ readonly sourceBranch: string;
+ /** The bound database's Postgres name, read on the source before the fork. */
+ readonly boundDatabase: string | null;
+ }
+);
+
+function branchLimitError(
+ project: string,
+ branches: readonly LakebaseBranch[],
+ userName: string,
+ cause: unknown,
+): Error {
+ const yours = branches.filter(
+ (b) => isUsersBranchId(userName, resourceId(b.name)) && !isGone(b),
+ );
+ const message =
+ yours.length > 0
+ ? `Project ${project} is at its branch limit, so init created nothing. Delete one of your other branches, then rerun \`appkit db init\`:\n${yours
+ .map(
+ (b) =>
+ ` databricks postgres delete-branch ${b.name}${b.status?.expire_time ? ` # expires ${b.status.expire_time}` : ""}`,
+ )
+ .join("\n")}`
+ : `Project ${project} is at its branch limit, so init created nothing, and none of its branches are yours. Ask a project owner to delete unused branches, then rerun \`appkit db init\`.`;
+ return new Error(message, { cause });
+}
+
+/** What init says after refusing a branch, unless every branch is refused. */
+const INIT_SETS_UP =
+ "`appkit db init` only sets up your dev branch or this checkout's session branch";
+
+async function findOrCreateBranch(
+ ctx: DbContext,
+ request: BranchRequest,
+): Promise {
+ const { project, mode, identity, boundary, onStep } = request;
+ const api = ctx.api();
+ let session = mode === "session" ? (request.session ?? newSessionId()) : null;
+ let rotated = false;
+ const branchName = () =>
+ `${project}/branches/${
+ session === null
+ ? devBranchId(identity.userName)
+ : sessionBranchId(identity.userName, session)
+ }`;
+
+ const reuse = (branch: LakebaseBranch): FoundBranch => {
+ const verdict = classifyBranch({
+ branch,
+ userName: identity.userName,
+ sessionId: session,
+ boundary,
+ });
+ if (!takesWrites(verdict.kind)) {
+ throw new Error(
+ `Refusing to set up ${writeRefusal(`${resourceId(branch.name)}: ${verdict.reason}`, boundary, INIT_SETS_UP)}.`,
+ );
+ }
+ onStep(`Using ${resourceId(branch.name)}`);
+ return { branch, created: false, session };
+ };
+ const replaceGone = (name: string): void => {
+ if (session === null) {
+ throw new Error(
+ `Your dev branch ${name} was deleted or expired. Restore it, or delete it for good, then rerun \`appkit db init\`. \`appkit db init --session\` sets up a session branch meanwhile.`,
+ );
+ }
+ if (rotated) {
+ throw new Error(
+ `Could not create a session branch: ${name} was deleted or expired too. Rerun \`appkit db init --session\`.`,
+ );
+ }
+ rotated = true;
+ session = newSessionId();
+ };
+
+ for (;;) {
+ const name = branchName();
+ const refusal = deployRefusal(boundary, name);
+ if (refusal) {
+ throw new Error(
+ `Refusing to set up ${writeRefusal(`${resourceId(name)}: ${refusal}`, boundary, INIT_SETS_UP)}.`,
+ );
+ }
+ const existing = await api.getBranch(name);
+ if (existing && !isGone(existing)) return reuse(existing);
+ if (existing) {
+ replaceGone(name);
+ continue;
+ }
+
+ const branches = await api.listBranches(project);
+ const deployed = branches.find(
+ (b) => b.name === request.deploy?.branch && !isGone(b),
+ );
+ const parent = deployed ?? branches.find((b) => b.status?.default);
+ if (!parent) {
+ throw new Error(`Project ${project} has no default branch to fork from.`);
+ }
+ // A fork has its source's databases.
+ const boundDatabase = await readBoundDatabase(
+ ctx,
+ parent.name,
+ request.deploy,
+ name,
+ );
+ persistSessionIdBeforeFork(request, session);
+ onStep(
+ `Creating ${resourceId(name)} from ${resourceId(parent.name)} (${deployed ? "the branch databricks.yml deploys to" : "the project's default branch"})${session === null ? "" : `, expiring after ${request.ttl.label}`}`,
+ );
+ try {
+ const branch = await api.createBranch(project, resourceId(name), {
+ source_branch: parent.name,
+ ...(session === null
+ ? { no_expiry: true as const }
+ : { ttl: request.ttl.api }),
+ });
+ return {
+ branch: branch?.name ? branch : { name },
+ created: true,
+ sourceBranch: parent.name,
+ boundDatabase,
+ session,
+ };
+ } catch (error) {
+ if (isPermissionDenied(error)) {
+ throw new Error(
+ `Creating ${resourceId(name)} needs CAN MANAGE on ${project}. Ask a project owner for it, then rerun \`appkit db init\`.`,
+ { cause: error },
+ );
+ }
+ if (isBranchLimit(error)) {
+ throw branchLimitError(project, branches, identity.userName, error);
+ }
+ if (!isAlreadyExists(error)) throw error;
+ // Another run created it first, or the name is held by a deleted branch.
+ const raced = await api.getBranch(name);
+ if (raced && !isGone(raced)) return reuse(raced);
+ replaceGone(name);
+ }
+ }
+}
+
+function persistSessionIdBeforeFork(
+ request: BranchRequest,
+ session: string | null,
+): void {
+ if (session !== null && session !== request.session) {
+ updateEnvFile(request.envFile, { APPKIT_DB_SESSION: session });
+ }
+}
+
+const sleep = (ms: number) =>
+ new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * The branch's read-write endpoint, created when it has none. Another run of
+ * init on the same branch can create it first: its 409 is followed by a reread,
+ * and an endpoint that is still coming up is waited for until it has a host.
+ */
+async function ensureReadWriteEndpoint(
+ ctx: DbContext,
+ branch: string,
+ onStep: (message: string) => void,
+): Promise<{ endpoint: LakebaseEndpoint; created: boolean; host: string }> {
+ const api = ctx.api();
+ const readWrite = (endpoints: LakebaseEndpoint[]) =>
+ endpoints.find((e) => e.status?.endpoint_type === READ_WRITE_ENDPOINT);
+
+ let endpoint = readWrite(await api.listEndpoints(branch));
+ let created = false;
+ if (!endpoint) {
+ onStep(
+ `Creating a read-write endpoint on ${resourceId(branch)} that suspends after 5 idle minutes`,
+ );
+ try {
+ endpoint = await api.createEndpoint(branch, DEFAULT_ENDPOINT_ID, {
+ suspendTimeout: SUSPEND_TIMEOUT,
+ });
+ created = true;
+ } catch (error) {
+ if (!isAlreadyExists(error)) throw error;
+ endpoint = readWrite(await api.listEndpoints(branch));
+ if (!endpoint) {
+ throw new Error(
+ `Endpoint ${DEFAULT_ENDPOINT_ID} on ${branch} exists but is not a read-write endpoint, so init cannot use it. Create a read-write endpoint on the branch, then rerun \`appkit db init\`.`,
+ { cause: error },
+ );
+ }
+ }
+ }
+ const deadline = Date.now() + ENDPOINT_HOST_WAIT.timeoutMs;
+ let waiting = false;
+ while (!endpoint?.status?.hosts?.host && Date.now() < deadline) {
+ if (!waiting) {
+ waiting = true;
+ onStep(
+ `Waiting for the read-write endpoint of ${resourceId(branch)} to get a host`,
+ );
+ }
+ await sleep(ENDPOINT_HOST_WAIT.intervalMs);
+ endpoint = readWrite(await api.listEndpoints(branch)) ?? endpoint;
+ }
+ const host = endpoint?.status?.hosts?.host;
+ if (!endpoint?.name || !host) {
+ throw new Error(
+ `The read-write endpoint of ${branch} has no host yet. Rerun \`appkit db init\` in a minute.`,
+ );
+ }
+ return { endpoint, created, host };
+}
+
+/**
+ * Your role on the branch with DATABRICKS_SUPERUSER, created or updated when
+ * needed. Another run of init on the same branch can create it first: its 409
+ * is followed by a reread, and the reread role gets the same membership check.
+ */
+async function ensureDeveloperRole(
+ ctx: DbContext,
+ branch: string,
+ identity: Identity,
+ roles: readonly LakebaseRole[],
+ onStep: (message: string) => void,
+): Promise<{ role: LakebaseRole; action: RoleAction }> {
+ const api = ctx.api();
+ const mine = (list: readonly LakebaseRole[]) =>
+ list.find((r) => r.status?.postgres_role === identity.userName);
+
+ let existing = mine(roles);
+ if (!existing) {
+ onStep(
+ `Creating your role ${identity.userName} with ${SUPERUSER_MEMBERSHIP}`,
+ );
+ let created: LakebaseRole | undefined;
+ try {
+ created = await api.createRole(branch, {
+ identity_type: identity.identityType,
+ postgres_role: identity.userName,
+ auth_method: "LAKEBASE_OAUTH_V1",
+ membership_roles: [SUPERUSER_MEMBERSHIP],
+ });
+ } catch (error) {
+ if (!isAlreadyExists(error)) throw error;
+ }
+ if (created?.name) return { role: created, action: "created" };
+ // Either the operation response did not carry the role, or another run created it.
+ existing = mine(await api.listRoles(branch));
+ if (!existing) {
+ throw new Error(
+ `Creating your role on ${branch} did not return it, and listing the branch's roles did not find it. Rerun \`appkit db init\`.`,
+ );
+ }
+ if (created) return { role: existing, action: "created" };
+ }
+ if (existing.status?.membership_roles?.includes(SUPERUSER_MEMBERSHIP)) {
+ return { role: existing, action: "kept" };
+ }
+ onStep(`Adding ${SUPERUSER_MEMBERSHIP} to your role ${identity.userName}`);
+ const role = await api.setRoleMemberships(existing.name, [
+ SUPERUSER_MEMBERSHIP,
+ ]);
+ return { role: role?.name ? role : existing, action: "updated" };
+}
+
+/**
+ * The Postgres name of the database databricks.yml binds, read on `branch`;
+ * null when it binds none. A bound database the branch lacks is refused:
+ * pointing .env at another one would run the app on a database its deploy does
+ * not use. `forking` names the branch a fork of `branch` would create.
+ */
+async function readBoundDatabase(
+ ctx: DbContext,
+ branch: string,
+ deploy: DeployTarget | null,
+ forking?: string,
+): Promise {
+ if (!deploy?.database) return null;
+ const id = resourceId(deploy.database);
+ const database = await ctx.api().getDatabase(`${branch}/databases/${id}`);
+ if (!database) {
+ const where = forking
+ ? `${resourceId(branch)}, the branch ${resourceId(forking)} would fork from, so init created nothing`
+ : resourceId(branch);
+ throw new Error(
+ `Database ${id}, which databricks.yml binds, is not on ${where}. Create it there (databricks postgres create-database ${branch} --database-id ${id}), or bind a database the project's branches have, then rerun \`appkit db init\`.`,
+ );
+ }
+ if (!database.status?.postgres_database) {
+ throw new Error(
+ `Lakebase returned database ${id} on ${resourceId(branch)} without its Postgres database name. Rerun \`appkit db init\` in a minute.`,
+ );
+ }
+ return database.status.postgres_database;
+}
+
+/** The bound database, else the one .env names, else the project's default database. */
+function chooseDatabase(
+ bound: string | null,
+ local: LocalTarget,
+ onWarning: (message: string) => void,
+): string {
+ if (bound === null) return local.database ?? DEFAULT_DATABASE;
+ if (local.database && local.database !== bound) {
+ onWarning(
+ `Setting PGDATABASE=${shown(bound)} in .env: it was ${shown(local.database)}, and databricks.yml binds ${shown(bound)}`,
+ );
+ }
+ return bound;
+}
+
+const SCHEMA_NAME_ADVICE = "Pass --schema-name to read another schema.";
+
+/** introspectHolding, with advice an init user can follow: init has no --schema-name. */
+async function introspectForInit(
+ ctx: DbContext,
+ lock: HistoryLock,
+ options: IntrospectOptions,
+): Promise {
+ try {
+ return await introspectHolding(ctx, lock, options);
+ } catch (error) {
+ if (
+ !(error instanceof IntrospectRefusedError) ||
+ !error.message.includes(SCHEMA_NAME_ADVICE)
+ ) {
+ throw error;
+ }
+ throw new IntrospectRefusedError(
+ error.message.replace(
+ SCHEMA_NAME_ADVICE,
+ "Run `appkit db introspect --schema-name ` to read another schema.",
+ ),
+ { cause: error },
+ );
+ }
+}
+
+/** The profile or host init authenticated with, for a .env that names neither. */
+async function authValues(
+ ctx: DbContext,
+ current: Record,
+): Promise> {
+ if (current.DATABRICKS_CONFIG_PROFILE || current.DATABRICKS_HOST) return {};
+ const profile = ctx.env.DATABRICKS_CONFIG_PROFILE;
+ if (profile) return { DATABRICKS_CONFIG_PROFILE: profile };
+ const host = ctx.env.DATABRICKS_HOST || (await ctx.workspace().getHost());
+ return host ? { DATABRICKS_HOST: host } : {};
+}
+
+function readEnvValues(file: string): Record {
+ return fs.existsSync(file)
+ ? dotenv.parse(fs.readFileSync(file, "utf-8"))
+ : {};
+}
+
+/**
+ * One lock on the checkout's history covers the whole run, so no other
+ * `appkit db` command runs between its clean and migrate; `--schema none`
+ * changes no history and takes none.
+ */
+export async function runInit(
+ ctx: DbContext,
+ options: InitOptions = {},
+): Promise {
+ const requested = options.schema;
+ if (requested === "none") return initHolding(ctx, { kind: "none" }, options);
+ // Before the lock, which creates config/database.
+ if (requested === "migrate" || requested === "clean") {
+ requireSchemaFile(ctx.root, requested);
+ }
+ return withHistoryLock(ctx.root, "init", (lock) =>
+ initHolding(ctx, { kind: "locked", lock, requested }, options),
+ );
+}
+
+type StartRequest =
+ | { readonly kind: "none" }
+ | {
+ readonly kind: "locked";
+ readonly lock: HistoryLock;
+ readonly requested: Exclude | undefined;
+ };
+
+async function initHolding(
+ ctx: DbContext,
+ request: StartRequest,
+ options: InitOptions,
+): Promise {
+ const onStep = options.onStep ?? (() => undefined);
+ const onWarning = options.onWarning ?? onStep;
+ const interactive = options.interactive ?? false;
+ const ttl =
+ options.ttl === undefined
+ ? { api: SESSION_BRANCH_TTL, label: "7 days" }
+ : { api: parseTtl(options.ttl), label: options.ttl.trim() };
+
+ // Before any change, check the .env init may write and read the schema the
+ // hand-off and the start are for: the one schema.ts declares, which
+ // introspect reads too. --schema none does neither, so it reads no schema.ts.
+ const envFile = path.join(ctx.root, ENV_FILE);
+ refuseSymlink(envFile);
+ const hasSchema = hasSchemaFile(ctx.root);
+ const schemaName =
+ hasSchema && request.kind === "locked"
+ ? (
+ await loadDatabaseSchema(path.join(ctx.root, DEFAULT_SCHEMA_FILE), {
+ showImportError: true,
+ })
+ ).$schemaName
+ : DEFAULT_SCHEMA_NAME;
+
+ const configured = {
+ local: readLocalTarget(ctx.env),
+ deploy: readDeployTarget(ctx.root, ctx.env),
+ };
+ const project = resolveProject(configured.local, configured.deploy);
+ const { local, deploy } = scopeToProject(
+ project,
+ configured.local,
+ configured.deploy,
+ );
+ const identity = await currentIdentity(ctx);
+ const mode =
+ options.mode ?? (await defaultMode(ctx, project, local, identity.userName));
+ if (options.ttl !== undefined && mode !== "session") {
+ throw new Error("--ttl applies to session branches only; add --session.");
+ }
+ try {
+ const before = readEnvValues(envFile);
+
+ const found = await findOrCreateBranch(ctx, {
+ project,
+ mode,
+ identity,
+ session: local.session,
+ ttl,
+ boundary: readDeployBoundary(ctx.root, ctx.env),
+ envFile,
+ deploy,
+ onStep,
+ });
+ const { branch } = found;
+
+ const {
+ endpoint,
+ created: endpointCreated,
+ host,
+ } = await ensureReadWriteEndpoint(ctx, branch.name, onStep);
+ const roles = await ctx.api().listRoles(branch.name);
+ const { role, action } = await ensureDeveloperRole(
+ ctx,
+ branch.name,
+ identity,
+ roles,
+ onStep,
+ );
+ const database = chooseDatabase(
+ found.created
+ ? found.boundDatabase
+ : await readBoundDatabase(ctx, branch.name, deploy),
+ local,
+ onWarning,
+ );
+
+ const values: Record = {
+ LAKEBASE_PROJECT: project,
+ PGHOST: host,
+ LAKEBASE_ENDPOINT: endpoint.name,
+ PGDATABASE: database,
+ PGUSER: identity.userName,
+ ...(found.session === null ? {} : { APPKIT_DB_SESSION: found.session }),
+ ...(before.PGPORT && /^\d+$/.test(before.PGPORT)
+ ? {}
+ : { PGPORT: "5432" }),
+ ...(before.PGSSLMODE === TLS_MODE ? {} : { PGSSLMODE: TLS_MODE }),
+ ...(await authValues(ctx, before)),
+ };
+ if (before.PGSSLMODE && before.PGSSLMODE !== TLS_MODE) {
+ onStep(
+ `Setting PGSSLMODE=${TLS_MODE} in .env: it was ${before.PGSSLMODE}, and only ${TLS_MODE} makes every connection use TLS and check the server's certificate`,
+ );
+ }
+ onStep(
+ `Pointing .env at ${resourceId(branch.name)}, database ${shown(database)}`,
+ );
+ updateEnvFile(envFile, values);
+ const branchCtx: DbContext = { ...ctx, env: { ...ctx.env, ...values } };
+
+ const base = {
+ mode,
+ branch: branch.name,
+ created: found.created,
+ ...(found.created ? { sourceBranch: found.sourceBranch } : {}),
+ expireTime: branch.status?.expire_time ?? null,
+ endpoint: endpoint.name,
+ endpointCreated,
+ host,
+ database: shown(database),
+ user: identity.userName,
+ role: { name: role.name, action },
+ envFile,
+ };
+ if (request.kind === "none") {
+ return {
+ ...base,
+ handedOff: null,
+ keptCopy: null,
+ installed: null,
+ start: { kind: "none" },
+ };
+ }
+ const { lock, requested } = request;
+
+ const state = await withBranchPool(branchCtx, (pool) =>
+ readSchemaState(pool, schemaName),
+ );
+ const plan = planStart(state, requested, hasSchema, found.created);
+ const on = `on ${resourceId(branch.name)}`;
+ if (
+ plan.confirm &&
+ options.confirmClean &&
+ !(await options.confirmClean({ branch: branch.name, schemaName }))
+ ) {
+ return {
+ ...base,
+ handedOff: null,
+ keptCopy: null,
+ installed: null,
+ start: { kind: "cancelled", schemaName },
+ };
+ }
+ const onBranch = (
+ work: (client: Pick) => Promise,
+ ) => withBranchPool(branchCtx, work);
+ if (
+ plan.tag &&
+ !(await onBranch((client) => tagForkCopy(client, schemaName)))
+ ) {
+ onWarning(
+ `Could not mark schema ${schemaName} ${on} as the fork's copy. It has no journal table, or one owned by a role init does not trust. If this run stops before the rebuild finishes, the next \`appkit db init\` will see a schema that looks like your working branch and keep the copied rows. Run \`appkit db init --schema clean\` then.`,
+ );
+ }
+ const installed = ensureDrizzleKit(
+ ctx.root,
+ options.runCommand ?? runCommand,
+ onStep,
+ );
+
+ const introspect = (recordAsApplied: boolean) => {
+ onStep(`Writing schema.ts from schema ${schemaName} ${on}`);
+ return introspectForInit(branchCtx, lock, {
+ interactive,
+ schemaName,
+ recordAsApplied,
+ });
+ };
+ let introspected: IntrospectReport | null = null;
+ if (plan.kind === "introspect" && plan.rebuild) {
+ introspected = await introspect(false);
+ }
+
+ const handedOff = plan.handOff
+ ? await handOffAppSchema(branchCtx, {
+ branch: branch.name,
+ database,
+ schemaName,
+ developer: role,
+ roles,
+ onStep,
+ })
+ : null;
+ if (plan.keepsCopy) {
+ await onBranch((client) => untagForkCopy(client, schemaName));
+ }
+
+ const rebuildSchema = async (): Promise => {
+ const reason: RebuildReason =
+ requested === undefined ? "fork-copy" : "requested";
+ const why =
+ reason === "fork-copy"
+ ? ": the branch still holds the rows the fork copied, and the committed migrations recreate its tables"
+ : "";
+ onStep(
+ schemaName === "public"
+ ? `Removing your objects in schema public ${on}${why}`
+ : `Dropping schema ${schemaName} ${on}${why}`,
+ );
+ const clean = await cleanHolding(branchCtx, lock);
+ const migrate = await migrateHolding(branchCtx, lock, {
+ interactive,
+ generate: false,
+ });
+ return { clean, migrate, reason };
+ };
+ let start: InitStart;
+ if (plan.kind === "migrate") {
+ onStep(`Migrating schema ${schemaName} ${on}`);
+ start = {
+ kind: "migrate",
+ migrate: await migrateHolding(branchCtx, lock, { interactive }),
+ };
+ } else if (plan.kind === "introspect") {
+ start = {
+ kind: "introspect",
+ introspect: introspected ?? (await introspect(true)),
+ rebuilt: plan.rebuild ? await rebuildSchema() : null,
+ };
+ } else {
+ start = { kind: "clean", ...(await rebuildSchema()) };
+ }
+
+ return {
+ ...base,
+ handedOff,
+ keptCopy: keptCopyOf(
+ state,
+ plan,
+ found.created
+ ? found.sourceBranch
+ : (branch.status?.source_branch ?? null),
+ ),
+ installed,
+ start,
+ };
+ } catch (error) {
+ throw mode === "session" ? withSessionRerun(error) : error;
+ }
+}
+
+function keptCopyOf(
+ state: SchemaState,
+ plan: StartPlan,
+ source: string | null,
+): KeptCopy | null {
+ if (plan.keepsCopy) return { reason: "requested", from: source };
+ if (state.kind === "public" && !plan.rebuild && state.kept.length > 0) {
+ return { reason: "public", objects: state.kept };
+ }
+ return null;
+}
diff --git a/packages/appkit/src/database/tooling/introspect/catalog.ts b/packages/appkit/src/database/tooling/introspect/catalog.ts
new file mode 100644
index 000000000..852a01633
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/catalog.ts
@@ -0,0 +1,356 @@
+import { MIGRATIONS_TABLE } from "../../migrations/paths";
+import type { ReferentialAction } from "../../schema-builder/types";
+
+/** Run one parameterized query and return its rows (a pg Pool fits: `(t, v) => pool.query(t, v).then(r => r.rows)`). */
+export type CatalogQuery = (
+ text: string,
+ values: readonly unknown[],
+) => Promise;
+
+export interface IntrospectedEnum {
+ readonly name: string;
+ readonly schema: string;
+ readonly values: readonly string[];
+}
+
+/** Options of the sequence behind a serial or identity column, as text so bigint bounds survive JSON. */
+export interface IntrospectedSequence {
+ readonly start: string;
+ readonly increment: string;
+ readonly min: string;
+ readonly max: string;
+ readonly cache: string;
+ readonly cycle: boolean;
+}
+
+export interface IntrospectedColumn {
+ readonly name: string;
+ /** format_type(), e.g. "character varying(120)". */
+ readonly type: string;
+ readonly notNull: boolean;
+ /** attidentity: "" none, "a" always, "d" by default. */
+ readonly identity: "" | "a" | "d";
+ /** Generated column, stored or virtual (attgenerated 's' or 'v'). */
+ readonly generated: boolean;
+ /** pg_get_expr() of the default (or generation expression). */
+ readonly defaultExpr: string | null;
+ readonly enum?: IntrospectedEnum;
+ /** The sequence a serial or identity column owns; absent otherwise. */
+ readonly sequence?: IntrospectedSequence;
+}
+
+export interface IntrospectedForeignKey {
+ readonly name: string;
+ readonly columns: readonly string[];
+ readonly schema: string;
+ readonly table: string;
+ readonly refColumns: readonly string[];
+ readonly onDelete: ReferentialAction;
+ readonly onUpdate: ReferentialAction;
+ /** DEFERRABLE or MATCH FULL, neither of which the builder declares. */
+ readonly deferrable: boolean;
+ readonly matchFull: boolean;
+}
+
+export interface IntrospectedUnique {
+ readonly name: string;
+ readonly columns: readonly string[];
+ /** DEFERRABLE, which the builder does not declare. */
+ readonly deferrable: boolean;
+}
+
+export interface IntrospectedTable {
+ readonly name: string;
+ /** relkind 'p': partitioned in the database. */
+ readonly partitioned: boolean;
+ readonly columns: readonly IntrospectedColumn[];
+ readonly primaryKey: readonly string[];
+ readonly unique: readonly IntrospectedUnique[];
+ readonly foreignKeys: readonly IntrospectedForeignKey[];
+ /** CHECK and EXCLUDE constraint names. */
+ readonly checks: readonly string[];
+ /** Index names, except the indexes behind primary-key, unique and exclusion constraints. */
+ readonly indexes: readonly string[];
+}
+
+/** pg_constraint.confdeltype / confupdtype. */
+const ACTIONS: Record = {
+ a: "no action",
+ r: "restrict",
+ c: "cascade",
+ n: "set null",
+ d: "set default",
+};
+
+export interface ColumnRow {
+ table_name: string;
+ name: string;
+ type: string;
+ not_null: boolean;
+ identity: string;
+ generated: string;
+ default_expr: string | null;
+ type_kind: string;
+ type_schema: string;
+ type_name: string;
+ enum_values: string[] | null;
+ sequence: IntrospectedSequence | null;
+}
+
+export interface TableRow {
+ name: string;
+ partitioned: boolean;
+}
+
+export interface ConstraintRow {
+ table_name: string;
+ name: string;
+ kind: "p" | "u" | "f" | "c" | "x";
+ columns: string[];
+ ref_schema: string | null;
+ ref_table: string | null;
+ ref_columns: string[] | null;
+ on_delete: string;
+ on_update: string;
+ deferrable?: boolean;
+ /** confmatchtype: "f" full, "s" simple. */
+ match_type?: string;
+}
+
+export interface IndexRow {
+ table_name: string;
+ name: string;
+}
+
+// pg_catalog, never information_schema: it hides objects the role cannot access.
+// Ordinary and partitioned tables only; partitions belong to their parent.
+const TABLES_SQL = `
+select c.relname::text as name, c.relkind = 'p' as partitioned
+ from pg_catalog.pg_class c
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
+ where n.nspname = $1 and c.relkind in ('r', 'p') and not c.relispartition
+ and c.relname <> $2
+ order by c.relname`;
+
+const COLUMNS_SQL = `
+select c.relname::text as table_name, a.attname::text as name,
+ pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
+ a.attnotnull as not_null, a.attidentity::text as identity,
+ a.attgenerated::text as generated,
+ pg_catalog.pg_get_expr(d.adbin, d.adrelid) as default_expr,
+ t.typtype::text as type_kind, tn.nspname::text as type_schema,
+ t.typname::text as type_name,
+ case when t.typtype = 'e' then array(
+ select e.enumlabel::text from pg_catalog.pg_enum e
+ where e.enumtypid = t.oid order by e.enumsortorder)
+ end as enum_values,
+ seq.options as sequence
+ from pg_catalog.pg_attribute a
+ join pg_catalog.pg_class c on c.oid = a.attrelid
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
+ join pg_catalog.pg_type t on t.oid = a.atttypid
+ join pg_catalog.pg_namespace tn on tn.oid = t.typnamespace
+ left join pg_catalog.pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum
+ -- The sequence a serial (deptype a) or identity (deptype i) column owns; bounds as text, since bigint exceeds JSON numbers.
+ left join lateral (
+ select jsonb_build_object(
+ 'start', s.seqstart::text, 'increment', s.seqincrement::text,
+ 'min', s.seqmin::text, 'max', s.seqmax::text,
+ 'cache', s.seqcache::text, 'cycle', s.seqcycle) as options
+ from pg_catalog.pg_depend sd
+ join pg_catalog.pg_sequence s on s.seqrelid = sd.objid
+ where sd.classid = 'pg_catalog.pg_class'::regclass
+ and sd.refclassid = 'pg_catalog.pg_class'::regclass
+ and sd.refobjid = a.attrelid and sd.refobjsubid = a.attnum
+ and sd.deptype in ('a', 'i')
+ limit 1) seq on true
+ where n.nspname = $1 and c.relkind in ('r', 'p') and not c.relispartition
+ and c.relname <> $2 and a.attnum > 0 and not a.attisdropped
+ order by c.relname, a.attnum`;
+
+const CONSTRAINTS_SQL = `
+select c.relname::text as table_name, k.conname::text as name, k.contype::text as kind,
+ array(select a.attname::text
+ from unnest(k.conkey) with ordinality as u(attnum, ord)
+ join pg_catalog.pg_attribute a on a.attrelid = k.conrelid and a.attnum = u.attnum
+ order by u.ord) as columns,
+ rn.nspname::text as ref_schema, rc.relname::text as ref_table,
+ array(select a.attname::text
+ from unnest(k.confkey) with ordinality as u(attnum, ord)
+ join pg_catalog.pg_attribute a on a.attrelid = k.confrelid and a.attnum = u.attnum
+ order by u.ord) as ref_columns,
+ k.confdeltype::text as on_delete, k.confupdtype::text as on_update,
+ k.condeferrable as deferrable, k.confmatchtype::text as match_type
+ from pg_catalog.pg_constraint k
+ join pg_catalog.pg_class c on c.oid = k.conrelid
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
+ left join pg_catalog.pg_class rc on rc.oid = k.confrelid
+ left join pg_catalog.pg_namespace rn on rn.oid = rc.relnamespace
+ where n.nspname = $1 and k.contype in ('p', 'u', 'f', 'c', 'x') and c.relname <> $2
+ -- A foreign key to a partitioned table has one copy per partition; keep the original.
+ and k.conparentid = 0
+ order by c.relname, k.conname`;
+
+// Indexes no constraint stands for: schema.ts cannot declare them.
+const INDEXES_SQL = `
+select c.relname::text as table_name, i.relname::text as name
+ from pg_catalog.pg_index x
+ join pg_catalog.pg_class c on c.oid = x.indrelid
+ join pg_catalog.pg_class i on i.oid = x.indexrelid
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
+ where n.nspname = $1 and c.relname <> $2
+ and not exists (
+ select 1 from pg_catalog.pg_constraint k
+ where k.conrelid = x.indrelid and k.conindid = x.indexrelid
+ and k.contype in ('p', 'u', 'x'))
+ order by c.relname, i.relname`;
+
+// What readCatalog does not read, so the report can name it. Objects an
+// extension owns are left out: the extension recreates them.
+const UNREAD_SQL = `
+with ns as (select oid from pg_catalog.pg_namespace where nspname = $1),
+objects (label, classid, objid) as (
+ select case c.relkind when 'v' then 'view ' when 'm' then 'materialized view '
+ when 'f' then 'foreign table ' else 'sequence ' end || c.relname,
+ 'pg_catalog.pg_class'::regclass, c.oid
+ from pg_catalog.pg_class c
+ where c.relnamespace = (select oid from ns) and c.relkind in ('v', 'm', 'f', 'S')
+ -- serial and identity sequences belong to their column
+ and not exists (
+ select 1 from pg_catalog.pg_depend d
+ where d.classid = 'pg_catalog.pg_class'::regclass and d.objid = c.oid
+ and d.refclassid = 'pg_catalog.pg_class'::regclass and d.deptype in ('a', 'i'))
+ union all
+ select 'trigger ' || t.tgname || ' on ' || c.relname, 'pg_catalog.pg_trigger'::regclass, t.oid
+ from pg_catalog.pg_trigger t
+ join pg_catalog.pg_class c on c.oid = t.tgrelid
+ where c.relnamespace = (select oid from ns) and not t.tgisinternal
+ union all
+ select 'policy ' || p.polname || ' on ' || c.relname, 'pg_catalog.pg_policy'::regclass, p.oid
+ from pg_catalog.pg_policy p
+ join pg_catalog.pg_class c on c.oid = p.polrelid
+ where c.relnamespace = (select oid from ns)
+ union all
+ select 'row-level security on ' || c.relname, 'pg_catalog.pg_class'::regclass, c.oid
+ from pg_catalog.pg_class c
+ where c.relnamespace = (select oid from ns) and c.relrowsecurity
+ union all
+ select 'inheritance of ' || c.relname || ' from ' || p.relname, 'pg_catalog.pg_class'::regclass, c.oid
+ from pg_catalog.pg_inherits i
+ join pg_catalog.pg_class c on c.oid = i.inhrelid
+ join pg_catalog.pg_class p on p.oid = i.inhparent
+ where c.relnamespace = (select oid from ns) and not c.relispartition
+ union all
+ select case p.prokind when 'p' then 'procedure ' when 'a' then 'aggregate ' else 'function ' end
+ || p.proname || '(' || pg_catalog.pg_get_function_identity_arguments(p.oid) || ')',
+ 'pg_catalog.pg_proc'::regclass, p.oid
+ from pg_catalog.pg_proc p
+ where p.pronamespace = (select oid from ns)
+ union all
+ select case t.typtype when 'd' then 'domain ' else 'type ' end || t.typname,
+ 'pg_catalog.pg_type'::regclass, t.oid
+ from pg_catalog.pg_type t
+ where t.typnamespace = (select oid from ns)
+ and (t.typtype in ('d', 'r')
+ or (t.typtype = 'c' and exists (
+ select 1 from pg_catalog.pg_class c where c.oid = t.typrelid and c.relkind = 'c'))
+ -- an enum is read through the columns that use it
+ or (t.typtype = 'e' and not exists (
+ select 1 from pg_catalog.pg_attribute a
+ join pg_catalog.pg_class c on c.oid = a.attrelid
+ where a.atttypid = t.oid and c.relkind in ('r', 'p') and not a.attisdropped)))
+)
+select o.label from objects o
+ where not exists (
+ select 1 from pg_catalog.pg_depend d
+ where d.classid = o.classid and d.objid = o.objid and d.deptype = 'e')
+ order by o.label`;
+
+function toColumn(row: ColumnRow): IntrospectedColumn {
+ const identity =
+ row.identity === "a" || row.identity === "d" ? row.identity : "";
+ return {
+ name: row.name,
+ type: row.type,
+ notNull: row.not_null,
+ identity,
+ generated: row.generated !== "",
+ defaultExpr: row.default_expr,
+ ...(row.type_kind === "e"
+ ? {
+ enum: {
+ name: row.type_name,
+ schema: row.type_schema,
+ values: row.enum_values ?? [],
+ },
+ }
+ : {}),
+ ...(row.sequence ? { sequence: row.sequence } : {}),
+ };
+}
+
+/** Assemble the model from the catalog result sets (exported for fixture tests). */
+export function buildTables(
+ tables: readonly TableRow[],
+ columns: readonly ColumnRow[],
+ constraints: readonly ConstraintRow[],
+ indexes: readonly IndexRow[] = [],
+): IntrospectedTable[] {
+ return tables.map(({ name, partitioned }) => {
+ const own = constraints.filter((row) => row.table_name === name);
+ return {
+ name,
+ partitioned,
+ columns: columns.filter((row) => row.table_name === name).map(toColumn),
+ primaryKey: own.find((row) => row.kind === "p")?.columns ?? [],
+ unique: own
+ .filter((row) => row.kind === "u")
+ .map((row) => ({
+ name: row.name,
+ columns: row.columns,
+ deferrable: row.deferrable === true,
+ })),
+ foreignKeys: own
+ .filter((row) => row.kind === "f" && row.ref_table)
+ .map((row) => ({
+ name: row.name,
+ columns: row.columns,
+ schema: row.ref_schema ?? "",
+ table: row.ref_table ?? "",
+ refColumns: row.ref_columns ?? [],
+ onDelete: ACTIONS[row.on_delete] ?? "no action",
+ onUpdate: ACTIONS[row.on_update] ?? "no action",
+ deferrable: row.deferrable === true,
+ matchFull: row.match_type === "f",
+ })),
+ checks: own
+ .filter((row) => row.kind === "c" || row.kind === "x")
+ .map((row) => row.name),
+ indexes: indexes
+ .filter((row) => row.table_name === name)
+ .map((row) => row.name),
+ };
+ });
+}
+
+/** Tables of one schema from pg_catalog, excluding the migration journal. */
+export async function readCatalog(
+ query: CatalogQuery,
+ schemaName: string,
+): Promise {
+ const params = [schemaName, MIGRATIONS_TABLE];
+ const tables = await query(TABLES_SQL, params);
+ const columns = await query(COLUMNS_SQL, params);
+ const constraints = await query(CONSTRAINTS_SQL, params);
+ const indexes = await query(INDEXES_SQL, params);
+ return buildTables(tables, columns, constraints, indexes);
+}
+
+/** Objects of the schema readCatalog does not read, e.g. "trigger audit on notes". */
+export async function readUnreadObjects(
+ query: CatalogQuery,
+ schemaName: string,
+): Promise {
+ const rows = await query<{ label: string }>(UNREAD_SQL, [schemaName]);
+ return rows.map((row) => row.label);
+}
diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts
new file mode 100644
index 000000000..16c3487a6
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/index.ts
@@ -0,0 +1,406 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { DEFAULT_SCHEMA_FILE } from "../../../plugins/database/load-schema";
+import { loadDatabaseSchema } from "../../../type-generator/database";
+import {
+ editedReason,
+ markMigrationsApplied,
+ readMigrationDrift,
+} from "../../migrations/apply";
+import { readJournal } from "../../migrations/paths";
+import { DEFAULT_SCHEMA_NAME } from "../../schema-builder/define-schema";
+import type { Schema } from "../../schema-builder/types";
+import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "../context";
+import { refuseSymlink, SymlinkRefusedError, writeFileAtomic } from "../files";
+import { notYourBranch, resolveEnvBranch, takesWrites } from "../guard";
+import { type HistoryLock, withHistoryLock } from "../history-lock";
+import { generatedTypesOf, writeGeneratedTypes } from "../migrate";
+import {
+ breakingStatements,
+ discardMigrationFiles,
+ type GeneratedMigration,
+ generateMigrationFiles,
+ generatesPending,
+ type PlannedMigration,
+} from "../migrations";
+import {
+ FORK_COPY_TAG,
+ forkCopyRefusal,
+ readSchemaState,
+} from "../schema-state";
+import { resourceId } from "../targets";
+import { readCatalog, readUnreadObjects } from "./catalog";
+import {
+ renderSchemaSource,
+ type Skip,
+ shown,
+ type Unexpressed,
+} from "./render";
+
+export interface IntrospectOptions {
+ /** false: an ambiguous rename against existing history throws instead of prompting. */
+ readonly interactive: boolean;
+ /** Schema to read. Default: the one schema.ts declares, else DEFAULT_SCHEMA_NAME. */
+ readonly schemaName?: string;
+ /** Module the written schema.ts imports the builder from. Default "@databricks/appkit/beta". */
+ readonly importSource?: string;
+ readonly recordAsApplied?: boolean;
+}
+
+export interface IntrospectReport {
+ readonly branch: string;
+ readonly schemaName: string;
+ /** Tables written to schema.ts. */
+ readonly tables: readonly string[];
+ readonly schemaFile: string;
+ /** Where the previous schema.ts went, when this run replaced a different one. */
+ readonly backupFile: string | null;
+ readonly skipped: readonly Skip[];
+ readonly warnings: readonly string[];
+ /** What schema.ts declares differently from the database, which keeps it as it is. */
+ readonly approximated: readonly string[];
+ /** 0000_baseline without history, NNNN_introspect with it; null when nothing changed. */
+ readonly migration: GeneratedMigration | null;
+ /** Tags recorded as applied: the migration, and any an interrupted run wrote but did not record. */
+ readonly recorded: readonly string[];
+ readonly typesFile: string;
+ readonly operationsTypesFile: string;
+}
+
+/** Introspect would record history the branch or the deployed app contradicts. */
+export class IntrospectRefusedError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "IntrospectRefusedError";
+ }
+}
+
+/** Tags introspect writes. A pending one is recorded when introspect would write the same SQL now. */
+const INTROSPECT_TAG = /^\d{4}_(introspect|baseline)$/;
+
+/** File contents, or null when it does not exist. */
+function readIfExists(file: string): string | null {
+ return fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : null;
+}
+
+function writeOrRemove(file: string, contents: string | null): void {
+ if (contents === null) fs.rmSync(file, { force: true });
+ else writeFileAtomic(file, contents);
+}
+
+/** Introspect replaces `file`, so a link there would be swapped for a plain file or written through. */
+function refuseSymlinkedDestination(root: string, file: string): void {
+ try {
+ refuseSymlink(path.join(root, file));
+ } catch (error) {
+ if (!(error instanceof SymlinkRefusedError)) throw error;
+ throw new IntrospectRefusedError(
+ `Refusing to introspect: ${file} is a symbolic link, and introspect replaces files instead of writing through links. Replace it with a regular file, then rerun.`,
+ { cause: error },
+ );
+ }
+}
+
+const plural = (count: number, word: string) =>
+ `${count} ${word}${count === 1 ? "" : "s"}`;
+
+/** How a refusal names it. */
+function described(item: Unexpressed, schemaName: string): string {
+ const table = `${schemaName}.${item.name}`;
+ switch (item.kind) {
+ case "table":
+ return `table ${table}`;
+ case "column":
+ return `column ${table}.${item.member}`;
+ case "default":
+ return `the default of ${table}.${item.member}`;
+ case "constraint":
+ return `constraint ${item.member} of ${table}`;
+ case "type":
+ return `type ${table}`;
+ }
+}
+
+/**
+ * With history, the migration is recorded here as applied and runs on deploy.
+ * A drop of what the branch still has but schema.ts cannot express would be
+ * recorded falsely here, and would remove it from every deployed database.
+ */
+function refuseDropsOfUnexpressed(
+ migration: PlannedMigration,
+ unexpressed: readonly Unexpressed[],
+ schemaName: string,
+): void {
+ const refused = unexpressed.filter((item) => migration.removes(item));
+ if (refused.length === 0) return;
+ throw new IntrospectRefusedError(
+ `Refusing to write a migration that drops what the branch still has but schema.ts cannot express: ${refused
+ .map(
+ (item) =>
+ `${shown(described(item, schemaName))} (${shown(item.reason)})`,
+ )
+ .join(
+ "; ",
+ )}. The deployed app would drop ${refused.length === 1 ? "it" : "them"} on start.`,
+ );
+}
+
+/**
+ * The schema.ts introspect replaces; null when there is none. The rewrite
+ * keeps its private columns and its foreign keys, so a file that does not load
+ * refuses the run before anything is read or written.
+ */
+async function readPreviousSchema(root: string): Promise {
+ if (!fs.existsSync(path.join(root, DEFAULT_SCHEMA_FILE))) return null;
+ try {
+ return await loadDatabaseSchema(path.join(root, DEFAULT_SCHEMA_FILE), {
+ showImportError: true,
+ });
+ } catch (error) {
+ throw new IntrospectRefusedError(
+ `Refusing to introspect: ${DEFAULT_SCHEMA_FILE} does not load, so introspect cannot keep the columns it marks private. Fix it, then rerun.`,
+ { cause: error },
+ );
+ }
+}
+
+/**
+ * `appkit db introspect`: read the `.env` branch's app schema from pg_catalog
+ * (the one schema.ts declares, unless `--schema-name` names another), write
+ * schema.ts (the previous file goes to schema.ts.bak), write the migration
+ * that brings history up to the database, and record it as applied. A column
+ * the previous schema.ts marks private stays private. Runs only on your dev or
+ * session branch, and only when the branch records exactly the committed
+ * migrations. A failure puts back schema.ts, the backup, the generated types
+ * and the migrations folder. One command at a time owns the checkout's history.
+ */
+export async function runIntrospect(
+ ctx: DbContext,
+ options: IntrospectOptions,
+): Promise {
+ return withHistoryLock(ctx.root, "introspect", (lock) =>
+ introspectHolding(ctx, lock, options),
+ );
+}
+
+/** runIntrospect for a caller that already holds the checkout's history lock. */
+export async function introspectHolding(
+ ctx: DbContext,
+ lock: HistoryLock,
+ options: IntrospectOptions,
+): Promise {
+ const schemaFile = path.join(ctx.root, DEFAULT_SCHEMA_FILE);
+ refuseSymlinkedDestination(ctx.root, DEFAULT_SCHEMA_FILE);
+ refuseSymlinkedDestination(ctx.root, `${DEFAULT_SCHEMA_FILE}.bak`);
+ const previousSchema = await readPreviousSchema(ctx.root);
+ const schemaName =
+ options.schemaName || previousSchema?.$schemaName || DEFAULT_SCHEMA_NAME;
+ const { folder } = lock;
+ const migrationOptions = { migrationsFolder: folder, schemaName };
+ const hasHistory = (readJournal(folder)?.entries.length ?? 0) > 0;
+
+ const env = await resolveEnvBranch(ctx);
+ if (!env) throw new Error(`Did not introspect: ${NO_ENV_BRANCH}.`);
+ if (!takesWrites(env.kind)) {
+ throw new IntrospectRefusedError(
+ `Refusing to introspect: ${notYourBranch(
+ env,
+ "Introspect records the migration it writes as applied, so it runs only on branches `appkit db init` created for you. " +
+ `Run \`appkit db init\`: it creates your dev branch from the branch the default databricks.yml target binds, else the project's default branch, and introspects it when there is no ${DEFAULT_SCHEMA_FILE}`,
+ )}.`,
+ );
+ }
+ const branchId = resourceId(env.branch.name);
+ const recordAsApplied = options.recordAsApplied ?? true;
+
+ return withBranchPool(ctx, async (pool) => {
+ if (recordAsApplied) {
+ const refusal = forkCopyRefusal(
+ env.branch.name,
+ schemaName,
+ await readSchemaState(pool, schemaName),
+ "introspect",
+ );
+ if (refusal) {
+ throw new IntrospectRefusedError(`Refusing to introspect: ${refusal}`);
+ }
+ }
+ // The diff starts from the latest committed snapshot, so the branch must
+ // record exactly the committed migrations: one it lacks would come out
+ // reversed, one the checkout lacks would come out again, and one whose
+ // file changed after it ran left the branch where the snapshot is not.
+ const drift = await readMigrationDrift(pool, {
+ ...migrationOptions,
+ ignoreHashes: [FORK_COPY_TAG],
+ });
+ const refuse = (reason: string, advice: string) =>
+ new IntrospectRefusedError(
+ `Refusing to introspect ${branchId}: ${reason} in schema "${schemaName}". ${advice}`,
+ );
+ if (drift.unknown > 0) {
+ throw refuse(
+ `it records ${plural(drift.unknown, "migration")} this checkout does not have`,
+ "Pull the latest config/database/migrations, then rerun.",
+ );
+ }
+ if (drift.stranded.length > 0) {
+ throw refuse(
+ `it skipped ${drift.stranded.join(", ")}`,
+ "Run `appkit db migrate`, which says how to fix it.",
+ );
+ }
+ if (drift.edited.length > 0) {
+ throw refuse(
+ editedReason(drift.edited),
+ `Restore ${drift.edited.length === 1 ? "the file" : "the files"} to what the branch ran and put the change in a new migration, or rebuild the branch with \`appkit db clean\`.`,
+ );
+ }
+ // An interrupted run leaves its migration written but not recorded.
+ const unrecorded = drift.pending.every((tag) => INTROSPECT_TAG.test(tag))
+ ? drift.pending
+ : [];
+ const notApplied = (them: string) =>
+ refuse(
+ `it has not applied ${drift.pending.join(", ")}`,
+ `${them} Run \`appkit db migrate\` first.`,
+ );
+ if (drift.pending.length > unrecorded.length) {
+ throw notApplied(
+ `The migration would undo ${drift.pending.length === 1 ? "it" : "them"}.`,
+ );
+ }
+
+ const query = async (text: string, values: readonly unknown[]) =>
+ (await pool.query(text, [...values])).rows as T[];
+ const tables = await readCatalog(query, schemaName);
+ const unread = await readUnreadObjects(query, schemaName);
+ const rendered = renderSchemaSource(tables, schemaName, {
+ importSource: options.importSource,
+ previous: previousSchema,
+ });
+ // An app on another schema that forgot --schema-name must not lose its
+ // schema.ts to an empty one; with history, an empty schema drops every table.
+ if (
+ rendered.tables.length === 0 &&
+ (hasHistory || fs.existsSync(schemaFile))
+ ) {
+ const reasons = rendered.skipped
+ .filter((skip) => !skip.column)
+ .map((skip) => `${skip.table}: ${skip.reason}`);
+ throw new IntrospectRefusedError(
+ `Schema "${schemaName}" on ${branchId} has no tables${tables.length > 0 ? ` introspect can write (${reasons.join("; ")})` : ""}, so introspect would ${hasHistory ? "write a migration that drops every table" : `replace ${DEFAULT_SCHEMA_FILE} with an empty one`}. Pass --schema-name to read another schema.`,
+ );
+ }
+ const backupFile = `${schemaFile}.bak`;
+ const generatedTypes = generatedTypesOf(ctx.root);
+ const previous = readIfExists(schemaFile);
+ const previousBackup = readIfExists(backupFile);
+ const previousTypes = Object.values(generatedTypes).map(
+ (file) => [file, readIfExists(file)] as const,
+ );
+ const backsUp = previous !== null && previous !== rendered.source;
+ let migration: GeneratedMigration | null = null;
+ let recorded: string[] = [];
+ try {
+ if (backsUp) writeFileAtomic(backupFile, previous);
+ fs.mkdirSync(path.dirname(schemaFile), { recursive: true });
+ writeFileAtomic(schemaFile, rendered.source);
+ let schema: Schema;
+ try {
+ schema = await loadDatabaseSchema(schemaFile, {
+ showImportError: true,
+ });
+ } catch (error) {
+ throw new Error(
+ `The schema.ts introspect generated does not load. This is a bug in \`appkit db introspect\`; please report it with the catalog of schema "${schemaName}".`,
+ { cause: error },
+ );
+ }
+
+ migration = await generateMigrationFiles(lock, {
+ schema,
+ tag: hasHistory ? "introspect" : "baseline",
+ interactive: options.interactive,
+ ...(hasHistory
+ ? {
+ beforeWrite: (planned: PlannedMigration) =>
+ refuseDropsOfUnexpressed(
+ planned,
+ rendered.unexpressed,
+ schemaName,
+ ),
+ }
+ : {}),
+ });
+ if (unrecorded.length > 0) {
+ const one = unrecorded.length === 1;
+ if (migration) {
+ throw notApplied(
+ `Its tables differ from what ${one ? "it describes" : "they describe"}.`,
+ );
+ }
+ // A file someone edited after introspect wrote it may do more than its snapshot says.
+ if (
+ !(await generatesPending(
+ folder,
+ schema,
+ unrecorded,
+ options.interactive,
+ ))
+ ) {
+ throw notApplied(
+ `${one ? "Its" : "Their"} SQL is not what introspect would write for the branch now, so recording ${one ? "it" : "them"} without running ${one ? "it" : "them"} could skip a change.`,
+ );
+ }
+ }
+ await writeGeneratedTypes(ctx.root, schema);
+ // The database already holds what the migrations describe; recording is the last step.
+ recorded = recordAsApplied
+ ? [...unrecorded, ...(migration ? [migration.tag] : [])]
+ : [];
+ if (recorded.length > 0) {
+ await markMigrationsApplied(pool, migrationOptions, recorded);
+ }
+ } catch (error) {
+ writeOrRemove(schemaFile, previous);
+ if (backsUp) writeOrRemove(backupFile, previousBackup);
+ for (const [file, contents] of previousTypes) {
+ writeOrRemove(file, contents);
+ }
+ if (migration) await discardMigrationFiles(lock, migration);
+ if (error instanceof IntrospectRefusedError) throw error;
+ throw new Error(
+ `Introspect changed nothing: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: error },
+ );
+ }
+
+ const warnings = [...rendered.warnings];
+ if (unread.length > 0) {
+ warnings.push(
+ `Not read: ${unread.map(shown).join(", ")}. schema.ts and its migrations leave ${unread.length === 1 ? "it" : "them"} out, so a database the migrations create will not have ${unread.length === 1 ? "it" : "them"}.`,
+ );
+ }
+ const breaking = breakingStatements(migration?.statements ?? []);
+ if (migration && breaking.length > 0) {
+ warnings.push(
+ `${migration.tag} breaks instances still running the previous release, which keep serving while the new one migrates on start: ${breaking.map(shown).join(" ")}`,
+ );
+ }
+ return {
+ branch: env.branch.name,
+ schemaName,
+ tables: rendered.tables,
+ schemaFile,
+ backupFile: backsUp ? backupFile : null,
+ skipped: rendered.skipped,
+ warnings,
+ approximated: rendered.approximated,
+ migration,
+ recorded,
+ typesFile: generatedTypes.typesFile,
+ operationsTypesFile: generatedTypes.operationsTypesFile,
+ };
+ });
+}
diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts
new file mode 100644
index 000000000..f1cb85607
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/render.ts
@@ -0,0 +1,1031 @@
+import {
+ DEFAULT_SCHEMA_NAME,
+ isReservedColumnName,
+ isReservedTableName,
+} from "../../schema-builder/define-schema";
+import type { AppKitTable, Schema } from "../../schema-builder/types";
+import type { SchemaObject } from "../migrations";
+import type {
+ IntrospectedColumn,
+ IntrospectedForeignKey,
+ IntrospectedSequence,
+ IntrospectedTable,
+} from "./catalog";
+
+/**
+ * Something introspect left out of schema.ts, with an `// appkit: skipped …` comment.
+ * Display text: catalog names come with control characters escaped (see shown()).
+ */
+export interface Skip {
+ readonly table: string;
+ readonly column?: string;
+ readonly reason: string;
+}
+
+/**
+ * Something the branch has that schema.ts leaves out. A migration that drops
+ * it must not be recorded as applied: the branch keeps it.
+ */
+export interface Unexpressed extends SchemaObject {
+ readonly reason: string;
+}
+
+interface SchemaSource {
+ readonly source: string;
+ /** Tables written to schema.ts. */
+ readonly tables: readonly string[];
+ readonly skipped: readonly Skip[];
+ readonly unexpressed: readonly Unexpressed[];
+ /** Omissions that change behavior, e.g. a NOT NULL column app.database. can no longer fill. */
+ readonly warnings: readonly string[];
+ /** What schema.ts declares differently from the database, which keeps it as it is. */
+ readonly approximated: readonly string[];
+}
+
+interface RenderOptions {
+ /** Module the builder is imported from. Default "@databricks/appkit/beta". */
+ readonly importSource?: string;
+ /**
+ * The schema.ts this render replaces; null when there is none. A column it
+ * declares (same schema, table and column name) keeps its `.private()`, and
+ * of two foreign keys on one column, the one it declares is kept.
+ */
+ readonly previous: Schema | null;
+}
+
+/** Storage as the builder sees it; id/bigid are server-generated integer/bigint keys. */
+type Storage =
+ | "id"
+ | "bigid"
+ | "integer"
+ | "bigint"
+ | "text"
+ | "varchar"
+ | "boolean"
+ | "uuid"
+ | "timestamp"
+ | "jsonb"
+ | "enum";
+
+interface BaseType {
+ /** Builder call, e.g. `varchar(120)`. */
+ readonly call: string;
+ /** Import it needs ("" for the context's enum). */
+ readonly importName: string;
+ readonly storage: Storage;
+ readonly varcharLength?: number;
+ /** How the call differs from the database type. */
+ readonly approximation?: string;
+}
+
+interface ColumnPlan {
+ readonly column: IntrospectedColumn;
+ base: BaseType;
+ /** Set when `fk(() => .)` replaces the base call. */
+ fk?: {
+ readonly table: string;
+ readonly column: string;
+ readonly actions: string[];
+ };
+ readonly isPrimaryKey: boolean;
+ readonly isUnique: boolean;
+ defaultCall?: string;
+ readonly comments: string[];
+}
+
+interface TablePlan {
+ readonly table: IntrospectedTable;
+ readonly columns: ColumnPlan[];
+ /** Table-level comments, rendered first. */
+ readonly comments: string[];
+ /** Columns and skipped-column comments, in catalog order. */
+ readonly body: Array;
+ variable: string;
+}
+
+const JS_RESERVED = new Set(
+ (
+ "break case catch class const continue debugger default delete do else enum export extends false finally for " +
+ "function if import in instanceof new null return super switch this throw true try typeof var void while with " +
+ "yield let static implements interface package private protected public await arguments eval undefined"
+ ).split(" "),
+);
+const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
+const INT32 = { min: -2147483648, max: 2147483647 };
+
+/**
+ * Line separators end a `//` comment, and bidi controls reorder what an editor
+ * shows. JSON.stringify keeps both.
+ */
+const UNSAFE_IN_SOURCE =
+ /[\u061c\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
+const escaped = (char: string) =>
+ `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`;
+const q = (value: string) =>
+ JSON.stringify(value).replace(UNSAFE_IN_SOURCE, escaped);
+/**
+ * Catalog text for a `//` comment or a terminal line. A quoted Postgres name can
+ * hold a newline, which would end the comment and turn the rest of the name
+ * into code.
+ */
+export const shown = (text: string) =>
+ Array.from(text, (char) => {
+ const code = char.charCodeAt(0);
+ return code < 0x20 || code === 0x7f ? escaped(char) : char;
+ })
+ .join("")
+ .replace(UNSAFE_IN_SOURCE, escaped);
+/** Postgres keeps the first 63 bytes of a name, cut on a character boundary. */
+function pgName(name: string): string {
+ let bytes = 0;
+ let kept = "";
+ for (const char of name) {
+ bytes += Buffer.byteLength(char);
+ if (bytes > 63) break;
+ kept += char;
+ }
+ return kept;
+}
+const key = (name: string) => (IDENTIFIER.test(name) ? name : q(name));
+const access = (variable: string, name: string) =>
+ IDENTIFIER.test(name) ? `${variable}.${name}` : `${variable}[${q(name)}]`;
+/** The server entity client of a table, which inserts through schema.ts. */
+const client = (table: string) => access("app.database", table);
+const list = (names: readonly string[]) => names.join(", ");
+
+function baseType(
+ column: IntrospectedColumn,
+ schemaName: string,
+): BaseType | string {
+ const type = column.type;
+ if (column.enum) {
+ if (column.enum.schema !== schemaName) {
+ return `enum type "${column.enum.schema}.${column.enum.name}" lives outside schema "${schemaName}"`;
+ }
+ if (column.enum.values.length === 0) {
+ return `enum type "${column.enum.name}" has no values`;
+ }
+ if (column.enum.values.includes("")) {
+ return `enum type "${column.enum.name}" has an empty label, which the builder does not accept`;
+ }
+ return {
+ call: `enumType(${q(column.enum.name)}, [${column.enum.values.map(q).join(", ")}])`,
+ importName: "",
+ storage: "enum",
+ };
+ }
+ switch (type) {
+ case "integer":
+ return { call: "integer()", importName: "integer", storage: "integer" };
+ case "bigint":
+ return { call: "bigint()", importName: "bigint", storage: "bigint" };
+ case "text":
+ return { call: "text()", importName: "text", storage: "text" };
+ case "character varying":
+ return {
+ call: "text()",
+ importName: "text",
+ storage: "text",
+ approximation:
+ "character varying without a length is declared as text()",
+ };
+ case "boolean":
+ return { call: "boolean()", importName: "boolean", storage: "boolean" };
+ case "uuid":
+ return { call: "uuid()", importName: "uuid", storage: "uuid" };
+ case "jsonb":
+ return { call: "jsonb()", importName: "jsonb", storage: "jsonb" };
+ }
+ const varchar = /^character varying\((\d+)\)$/.exec(type);
+ if (varchar) {
+ const length = Number(varchar[1]);
+ return {
+ call: `varchar(${length})`,
+ importName: "varchar",
+ storage: "varchar",
+ varcharLength: length,
+ };
+ }
+ const timestamp = /^timestamp(\(\d\))? (with|without) time zone$/.exec(type);
+ if (timestamp) {
+ return {
+ call:
+ timestamp[2] === "with"
+ ? "timestamp({ withTimezone: true })"
+ : "timestamp()",
+ importName: "timestamp",
+ storage: "timestamp",
+ ...(timestamp[1]
+ ? { approximation: `${type} is declared without its precision` }
+ : {}),
+ };
+ }
+ return `type "${type}" is not supported`;
+}
+
+const isSequenceDefault = (expr: string | null) =>
+ !!expr && /^nextval\(/.test(expr);
+
+/** id()/bigid(), whose sequence drizzle-kit writes with Postgres' defaults up to the type's bound. */
+const SERVER_KEYS = {
+ integer: {
+ base: { call: "id()", importName: "id", storage: "id" },
+ max: "2147483647",
+ },
+ bigint: {
+ base: { call: "bigid()", importName: "bigid", storage: "bigid" },
+ max: "9223372036854775807",
+ },
+} as const satisfies Record;
+const SEQUENCE_DEFAULTS = { start: "1", increment: "1", min: "1", cache: "1" };
+const SEQUENCE_CLAUSES: ReadonlyArray<
+ [Exclude, string]
+> = [
+ ["start", "START WITH"],
+ ["increment", "INCREMENT BY"],
+ ["min", "MINVALUE"],
+ ["max", "MAXVALUE"],
+ ["cache", "CACHE"],
+];
+
+/** What `sequence` has that the defaults do not, and the defaults in its place; null when it has the defaults. */
+function sequenceDifferences(
+ sequence: IntrospectedSequence,
+ max: string,
+): { has: string; declared: string } | null {
+ const defaults = { ...SEQUENCE_DEFAULTS, max };
+ const has: string[] = [];
+ const declared: string[] = [];
+ for (const [option, clause] of SEQUENCE_CLAUSES) {
+ if (sequence[option] === defaults[option]) continue;
+ has.push(`${clause} ${sequence[option]}`);
+ declared.push(`${clause} ${defaults[option]}`);
+ }
+ if (sequence.cycle) {
+ has.push("CYCLE");
+ declared.push("NO CYCLE");
+ }
+ return has.length > 0 ? { has: list(has), declared: list(declared) } : null;
+}
+
+/**
+ * A quoted literal, with the cast pg_get_expr adds: `'x'::text`, `'x'::character
+ * varying`, `'x'::app."order-status"`. A quoted name holds any character but `"`.
+ */
+const LITERAL_WITH_CAST = /^'((?:[^']|'')*)'(?:::(?:[\w .]|"(?:[^"]|"")*")+)?$/;
+
+/** A builder default call, or why the database default cannot be expressed. */
+function defaultCall(
+ expr: string,
+ base: BaseType,
+ enumValues: readonly string[] | undefined,
+): { call: string } | { skip: string } {
+ const unsupported = { skip: `default ${expr} is not supported` };
+ switch (base.storage) {
+ case "timestamp":
+ return /^(now\(\)|CURRENT_TIMESTAMP)$/i.test(expr)
+ ? { call: ".defaultNow()" }
+ : unsupported;
+ case "uuid":
+ return expr === "gen_random_uuid()"
+ ? { call: ".defaultRandom()" }
+ : unsupported;
+ case "boolean":
+ return expr === "true" || expr === "false"
+ ? { call: `.default(${expr})` }
+ : unsupported;
+ case "integer": {
+ const match = /^\(?'?(-?\d+)'?(?:::integer)?\)?$/.exec(expr);
+ const value = match ? Number(match[1]) : Number.NaN;
+ return Number.isInteger(value) && value >= INT32.min && value <= INT32.max
+ ? { call: `.default(${value})` }
+ : unsupported;
+ }
+ case "text":
+ case "varchar":
+ case "enum": {
+ const match = LITERAL_WITH_CAST.exec(expr);
+ if (!match) return unsupported;
+ const value = (match[1] ?? "").replace(/''/g, "'");
+ if (
+ base.storage === "varchar" &&
+ value.length > (base.varcharLength ?? 0)
+ ) {
+ return unsupported;
+ }
+ if (base.storage === "enum" && !enumValues?.includes(value)) {
+ return unsupported;
+ }
+ return { call: `.default(${q(value)})` };
+ }
+ default:
+ // The builder accepts no literal defaults for bigint and jsonb.
+ return unsupported;
+ }
+}
+
+function importLine(names: readonly string[], source: string): string {
+ const line = `import { ${names.join(", ")} } from ${q(source)};`;
+ if (line.length <= 80) return line;
+ return `import {\n${names.map((name) => ` ${name},`).join("\n")}\n} from ${q(source)};`;
+}
+
+/** Something the branch has that schema.ts leaves out, by raw catalog name. */
+type Omission =
+ | { readonly kind: "table"; readonly table: string; readonly reason: string }
+ | {
+ readonly kind: "column";
+ readonly table: string;
+ readonly column: string;
+ readonly reason: string;
+ /** NOT NULL with nothing to fill it: inserts through the entity client fail. */
+ readonly failsInserts: boolean;
+ }
+ | {
+ readonly kind: "default";
+ readonly table: string;
+ readonly column: string;
+ readonly defaultExpr: string;
+ readonly reason: string;
+ /** NOT NULL: inserts through the entity client must give a value. */
+ readonly failsInserts: boolean;
+ }
+ | {
+ readonly kind: "constraint";
+ readonly table: string;
+ /** The names a migration may drop it by. */
+ readonly names: readonly string[];
+ /** The columns the Skipped line names; null: it names only the table. */
+ readonly columns: string | null;
+ /** false: the comment of its skipped column already covers it. */
+ readonly listed: boolean;
+ readonly reason: string;
+ }
+ | { readonly kind: "type"; readonly name: string; readonly reason: string };
+
+/** Defaults the builder allows only on uuid / timestamp columns, never on fk(). */
+const TYPED_DEFAULTS = new Set([".defaultRandom()", ".defaultNow()"]);
+
+/** The storage an fk() column inherits from its target. */
+function mirrored(target: BaseType): string {
+ if (target.storage === "id") return "integer()";
+ if (target.storage === "bigid") return "bigint()";
+ return target.call;
+}
+
+/**
+ * Render pg_catalog tables as a `defineSchema` source the builder accepts.
+ * What the builder cannot express is left out with an `// appkit: skipped …`
+ * comment; a CHECK, EXCLUDE or index it cannot declare is a warning; what it
+ * declares differently (a timestamp without its precision, say) is listed in
+ * `approximated`. A column `previous` declares keeps its
+ * `.private()`.
+ */
+export function renderSchemaSource(
+ tables: readonly IntrospectedTable[],
+ schemaName: string,
+ options: RenderOptions,
+): SchemaSource {
+ const skipped: Skip[] = [];
+ const unexpressed: Unexpressed[] = [];
+ const warnings: string[] = [];
+ const approximated: string[] = [];
+ /** Constraints whose database name is not the one migrations use: "db (migrations)". */
+ const renamed: string[] = [];
+ const tableComments: string[] = [];
+ const qualified = (table: string, column?: string) =>
+ `${schemaName}.${table}${column ? `.${column}` : ""}`;
+ /**
+ * Record what schema.ts leaves out: its `Skipped` line, its `Unexpressed`
+ * entry and its warning, and its `// appkit: skipped` comment into `comments`.
+ */
+ const omit = (omission: Omission, comments?: Pick) => {
+ const { reason } = omission;
+ const skip = (table: string, column?: string) =>
+ skipped.push({
+ table: shown(table),
+ ...(column === undefined ? {} : { column: shown(column) }),
+ reason: shown(reason),
+ });
+ switch (omission.kind) {
+ case "type":
+ unexpressed.push({ ...omission });
+ return;
+ case "table": {
+ const { table } = omission;
+ unexpressed.push({ kind: "table", name: table, reason });
+ skip(table);
+ comments?.push(
+ `// appkit: skipped table "${shown(table)}": ${shown(reason)}`,
+ );
+ return;
+ }
+ case "column": {
+ const { table, column } = omission;
+ unexpressed.push({
+ kind: "column",
+ name: table,
+ member: column,
+ reason,
+ });
+ skip(table, column);
+ comments?.push(
+ `// appkit: skipped column "${shown(column)}": ${shown(reason)}`,
+ );
+ if (omission.failsInserts) {
+ warnings.push(
+ `${qualified(table, column)} is NOT NULL with no default but is not in schema.ts (${reason}). Inserts through ${client(table)} will fail until it gets a default, becomes nullable, or is dropped.`,
+ );
+ }
+ return;
+ }
+ case "default": {
+ const { table, column } = omission;
+ unexpressed.push({
+ kind: "default",
+ name: table,
+ member: column,
+ reason,
+ });
+ skip(table, column);
+ comments?.push(`// appkit: skipped ${shown(reason)}`);
+ if (omission.failsInserts) {
+ warnings.push(
+ `${qualified(table, column)}: its default ${omission.defaultExpr} is not in schema.ts, so ${client(table)} requires a value for it on insert.`,
+ );
+ }
+ return;
+ }
+ case "constraint": {
+ const { table } = omission;
+ for (const member of omission.names) {
+ unexpressed.push({ kind: "constraint", name: table, member, reason });
+ }
+ if (!omission.listed) return;
+ skip(table, omission.columns ?? undefined);
+ comments?.push(`// appkit: skipped ${shown(reason)}`);
+ return;
+ }
+ }
+ };
+ const skipTable = (table: string, reason: string) =>
+ omit({ kind: "table", table, reason }, tableComments);
+ /** The builder type of a column, or why the builder cannot declare it. */
+ const columnBase = (
+ column: IntrospectedColumn,
+ isPrimaryKey: boolean,
+ ): BaseType | string => {
+ if (isReservedColumnName(column.name)) {
+ return `the name "${column.name}" is reserved by AppKit`;
+ }
+ if (column.generated) return "generated columns are not supported";
+ const base = baseType(column, schemaName);
+ if (typeof base === "string" || column.identity === "" || isPrimaryKey) {
+ return base;
+ }
+ return "identity columns other than the primary key are not supported";
+ };
+ const { previous } = options;
+ // A declaration of another schema declares nothing in this one.
+ const previousTables = new Map(
+ previous && previous.$schemaName === schemaName
+ ? Object.values(previous.$tables).map((table): [string, AppKitTable] => [
+ table.$name,
+ table,
+ ])
+ : [],
+ );
+ /** Whether `previous` declares this FK; its toMany reverse comes with it. */
+ const declaresForeignKey = (
+ table: string,
+ foreignKey: IntrospectedForeignKey,
+ ): boolean =>
+ foreignKey.columns.length === 1 &&
+ (previousTables
+ .get(table)
+ ?.$relations.some(
+ (relation) =>
+ relation.cardinality === "toOne" &&
+ relation.localColumn === foreignKey.columns[0] &&
+ relation.targetTable === foreignKey.table &&
+ relation.targetColumn === foreignKey.refColumns[0],
+ ) ??
+ false);
+ /** Whether `previous` declares this column private. */
+ const isPrivate = (table: string, column: string): boolean =>
+ Object.values(previousTables.get(table)?.$columns ?? {}).find(
+ (meta) => meta.columnName === column,
+ )?.isPrivate ?? false;
+
+ // 1. Tables the builder can key: one primary-key column, a usable name.
+ const names = new Set(tables.map((table) => table.name));
+ const plans = new Map();
+ for (const table of tables) {
+ if (isReservedTableName(table.name)) {
+ skipTable(table.name, `the name "${table.name}" is reserved by AppKit`);
+ } else if (
+ table.name.endsWith("Relations") &&
+ names.has(table.name.slice(0, -"Relations".length))
+ ) {
+ skipTable(
+ table.name,
+ `the name collides with the relation metadata AppKit generates for "${table.name.slice(0, -"Relations".length)}"`,
+ );
+ } else if (table.primaryKey.length === 0) {
+ skipTable(table.name, "it has no primary key");
+ } else if (table.primaryKey.length > 1) {
+ skipTable(
+ table.name,
+ `composite primary key (${list(table.primaryKey)}) is not supported`,
+ );
+ } else {
+ plans.set(table.name, {
+ table,
+ columns: [],
+ comments: [],
+ body: [],
+ variable: "",
+ });
+ }
+ }
+
+ // 2. Columns. A table whose primary-key column cannot be expressed is skipped whole.
+ for (const plan of [...plans.values()]) {
+ const { table } = plan;
+ const pk = table.primaryKey[0] as string;
+ const pkColumn = table.columns.find((column) => column.name === pk);
+ const pkBase = pkColumn ? columnBase(pkColumn, true) : "unsupported";
+ if (typeof pkBase === "string") {
+ plans.delete(table.name);
+ skipTable(
+ table.name,
+ `its primary key column "${pk}" cannot be expressed (${pkBase})`,
+ );
+ continue;
+ }
+ /** Single-column unique constraints, by column. */
+ const singleUnique = new Map(
+ table.unique
+ .filter((unique) => unique.columns.length === 1)
+ .map((unique) => [unique.columns[0] as string, unique]),
+ );
+ for (const unique of table.unique.filter((u) => u.columns.length > 1)) {
+ omit(
+ {
+ kind: "constraint",
+ table: table.name,
+ names: [unique.name],
+ columns: null,
+ listed: true,
+ reason: `unique constraint (${list(unique.columns)}) spans several columns, which is not supported`,
+ },
+ plan.comments,
+ );
+ }
+
+ for (const column of table.columns) {
+ const isPrimaryKey = column.name === pk;
+ const base = columnBase(column, isPrimaryKey);
+ if (typeof base === "string") {
+ const generatesValue =
+ column.identity !== "" || column.generated || !!column.defaultExpr;
+ omit(
+ {
+ kind: "column",
+ table: table.name,
+ column: column.name,
+ reason: base,
+ failsInserts: column.notNull && !generatesValue,
+ },
+ plan.body,
+ );
+ continue;
+ }
+
+ const columnPlan: ColumnPlan = {
+ column,
+ base,
+ isPrimaryKey,
+ isUnique: singleUnique.has(column.name) && !isPrimaryKey,
+ comments: [],
+ };
+ if (base.approximation) {
+ approximated.push(
+ `${qualified(table.name, column.name)}: ${base.approximation}`,
+ );
+ }
+ const unique = singleUnique.get(column.name);
+ const migrationsUnique = pgName(`${table.name}_${column.name}_unique`);
+ if (columnPlan.isUnique && unique) {
+ if (unique.name !== migrationsUnique) {
+ renamed.push(`${unique.name} (${migrationsUnique})`);
+ }
+ if (unique.deferrable) {
+ approximated.push(
+ `${qualified(table.name, column.name)}: the unique constraint is declared without DEFERRABLE`,
+ );
+ }
+ }
+ const generatesKey =
+ column.identity !== "" || isSequenceDefault(column.defaultExpr);
+ if (
+ isPrimaryKey &&
+ generatesKey &&
+ (base.storage === "integer" || base.storage === "bigint")
+ ) {
+ // A serial or identity key is the builder's server-generated id()/bigid().
+ const serverKey = SERVER_KEYS[base.storage];
+ columnPlan.base = serverKey.base;
+ if (column.identity !== "d") {
+ approximated.push(
+ `${qualified(table.name, column.name)}: ${column.identity === "a" ? "GENERATED ALWAYS AS IDENTITY" : "a serial key"} is declared as ${serverKey.base.call}, an identity generated BY DEFAULT`,
+ );
+ }
+ const differences = column.sequence
+ ? sequenceDifferences(column.sequence, serverKey.max)
+ : null;
+ if (differences) {
+ approximated.push(
+ `${qualified(table.name, column.name)}: the key's sequence has ${differences.has}; ${serverKey.base.call} declares the defaults (${differences.declared})`,
+ );
+ }
+ } else if (column.defaultExpr) {
+ const parsed = defaultCall(
+ column.defaultExpr,
+ base,
+ column.enum?.values,
+ );
+ if ("call" in parsed) {
+ columnPlan.defaultCall = parsed.call;
+ } else {
+ omit(
+ {
+ kind: "default",
+ table: table.name,
+ column: column.name,
+ defaultExpr: column.defaultExpr,
+ reason: parsed.skip,
+ failsInserts: column.notNull,
+ },
+ columnPlan.comments,
+ );
+ }
+ }
+ plan.columns.push(columnPlan);
+ plan.body.push(columnPlan);
+ }
+
+ if (table.partitioned) {
+ approximated.push(
+ `${qualified(table.name)}: a partitioned table is declared as a plain table`,
+ );
+ }
+ for (const [one, many, names] of [
+ [
+ "CHECK or EXCLUDE constraint",
+ "CHECK or EXCLUDE constraints",
+ table.checks,
+ ],
+ ["index", "indexes", table.indexes],
+ ] as const) {
+ if (names.length > 0) {
+ const single = names.length === 1;
+ warnings.push(
+ `${qualified(table.name)}: ${single ? `${one} ${names[0]} is` : `${many} ${list(names)} are`} not in schema.ts, so a database the migrations create will not have ${single ? "it" : "them"}.`,
+ );
+ }
+ }
+ }
+
+ // 3. Foreign keys the builder can express; the rest stay plain columns.
+ const edges = new Map>();
+ const reaches = (from: string, to: string): boolean => {
+ const seen = new Set();
+ const stack = [from];
+ while (stack.length > 0) {
+ const node = stack.pop() as string;
+ if (node === to) return true;
+ if (seen.has(node)) continue;
+ seen.add(node);
+ stack.push(...(edges.get(node) ?? []));
+ }
+ return false;
+ };
+ /** Why the builder cannot express this FK; null when it can. */
+ const fkProblem = (
+ plan: TablePlan,
+ foreignKey: IntrospectedForeignKey,
+ source: ColumnPlan | undefined,
+ seenTargets: ReadonlySet,
+ ): string | null => {
+ if (foreignKey.columns.length !== 1) {
+ return "foreign keys over several columns are not supported";
+ }
+ if (!source) return "its column is skipped";
+ if (source.fk) {
+ // One fk() per column; declared keys come first, so a refresh keeps the declared one.
+ return `its column already keeps the foreign key to ${source.fk.table}(${source.fk.column})`;
+ }
+ if (foreignKey.schema !== schemaName) {
+ return `it references schema "${foreignKey.schema}"`;
+ }
+ if (foreignKey.table === plan.table.name) {
+ // The builder takes one with a TableHandle annotation, which introspect does not write.
+ return "introspect does not write self-references";
+ }
+ const target = plans.get(foreignKey.table);
+ if (!target) return `table "${foreignKey.table}" is skipped`;
+ const targetColumn = target.columns.find(
+ (c) => c.column.name === foreignKey.refColumns[0],
+ );
+ if (!targetColumn) {
+ return `column ${foreignKey.table}.${foreignKey.refColumns[0]} is skipped`;
+ }
+ if (!targetColumn.isPrimaryKey && !targetColumn.isUnique) {
+ return `${foreignKey.table}.${foreignKey.refColumns[0]} is not a primary key or single-column unique key`;
+ }
+ if (seenTargets.has(foreignKey.table)) {
+ return `a second foreign key to "${foreignKey.table}" would make the relation ambiguous`;
+ }
+ if (plan.table.columns.some((c) => c.name === foreignKey.table)) {
+ return `the relation "${foreignKey.table}" would clash with the column of the same name`;
+ }
+ if (target.table.columns.some((c) => c.name === plan.table.name)) {
+ return `the reverse relation "${plan.table.name}" would clash with column ${foreignKey.table}.${plan.table.name}`;
+ }
+ if (reaches(foreignKey.table, plan.table.name)) {
+ // TypeScript cannot infer a cycle of fk() thunks without TableHandle annotations (TS7022).
+ return "it would close a cycle of foreign keys";
+ }
+ if (mirrored(targetColumn.base) !== source.base.call) {
+ return `its type ${source.base.call} differs from ${foreignKey.table}.${foreignKey.refColumns[0]}`;
+ }
+ const actions = [foreignKey.onDelete, foreignKey.onUpdate];
+ if (actions.includes("set null") && source.column.notNull) {
+ return "SET NULL on a NOT NULL column";
+ }
+ const fkDefault =
+ source.defaultCall && !TYPED_DEFAULTS.has(source.defaultCall);
+ if (actions.includes("set default") && !fkDefault) {
+ return "SET DEFAULT without a default the builder can express";
+ }
+ return null;
+ };
+
+ for (const plan of plans.values()) {
+ const targets = new Set();
+ // Declared FKs go first, so an undeclared one to the same table cannot take the relation.
+ const foreignKeys = [...plan.table.foreignKeys].sort(
+ (a, b) =>
+ Number(declaresForeignKey(plan.table.name, b)) -
+ Number(declaresForeignKey(plan.table.name, a)),
+ );
+ for (const foreignKey of foreignKeys) {
+ const source = plan.columns.find(
+ (c) => c.column.name === foreignKey.columns[0],
+ );
+ const problem = fkProblem(plan, foreignKey, source, targets);
+ if (problem) {
+ // Migrations name it after its column; a schema.ts that declared it gave it that name.
+ const names = [foreignKey.name];
+ if (foreignKey.columns.length === 1) {
+ names.push(
+ pgName(
+ `${plan.table.name}_${foreignKey.columns[0]}_${foreignKey.table}_${foreignKey.refColumns[0]}_fk`,
+ ),
+ );
+ }
+ omit(
+ {
+ kind: "constraint",
+ table: plan.table.name,
+ names: [...new Set(names)],
+ columns: foreignKey.columns.join(", "),
+ listed: !!source || foreignKey.columns.length > 1,
+ reason: `foreign key to ${foreignKey.table}(${list(foreignKey.refColumns)}) is not kept: ${problem}`,
+ },
+ source?.comments ?? plan.comments,
+ );
+ continue;
+ }
+ const sourceColumn = source as ColumnPlan;
+ const target = plans.get(foreignKey.table) as TablePlan;
+ const targetColumn = target.columns.find(
+ (c) => c.column.name === foreignKey.refColumns[0],
+ ) as ColumnPlan;
+ sourceColumn.base = { ...targetColumn.base };
+ if (
+ sourceColumn.defaultCall &&
+ TYPED_DEFAULTS.has(sourceColumn.defaultCall)
+ ) {
+ // fk() takes no defaultRandom()/defaultNow(); the key matters more than the default.
+ const defaultExpr = sourceColumn.column.defaultExpr as string;
+ omit(
+ {
+ kind: "default",
+ table: plan.table.name,
+ column: sourceColumn.column.name,
+ defaultExpr,
+ reason: `default ${defaultExpr} is not supported on a foreign key column`,
+ failsInserts: sourceColumn.column.notNull,
+ },
+ sourceColumn.comments,
+ );
+ delete sourceColumn.defaultCall;
+ }
+ for (const [flag, what] of [
+ [foreignKey.deferrable, "DEFERRABLE"],
+ [foreignKey.matchFull, "MATCH FULL"],
+ ] as const) {
+ if (flag) {
+ approximated.push(
+ `${qualified(plan.table.name, sourceColumn.column.name)}: the foreign key is declared without ${what}`,
+ );
+ }
+ }
+ const migrationsFk = pgName(
+ `${plan.table.name}_${sourceColumn.column.name}_${foreignKey.table}_${foreignKey.refColumns[0]}_fk`,
+ );
+ if (foreignKey.name !== migrationsFk) {
+ renamed.push(`${foreignKey.name} (${migrationsFk})`);
+ }
+ sourceColumn.fk = {
+ table: foreignKey.table,
+ column: foreignKey.refColumns[0] as string,
+ actions: [
+ ...(foreignKey.onDelete !== "no action"
+ ? [`.onDelete(${q(foreignKey.onDelete)})`]
+ : []),
+ ...(foreignKey.onUpdate !== "no action"
+ ? [`.onUpdate(${q(foreignKey.onUpdate)})`]
+ : []),
+ ],
+ };
+ targets.add(foreignKey.table);
+ const out = edges.get(plan.table.name) ?? new Set();
+ out.add(foreignKey.table);
+ edges.set(plan.table.name, out);
+ }
+ }
+
+ const declaredEnums = new Set(
+ [...plans.values()].flatMap((plan) =>
+ plan.columns.flatMap((c) =>
+ c.base.storage === "enum" && c.column.enum ? [c.column.enum.name] : [],
+ ),
+ ),
+ );
+ const undeclaredEnums = new Set(
+ tables.flatMap((table) =>
+ table.columns.flatMap((column) =>
+ column.enum?.schema === schemaName &&
+ !declaredEnums.has(column.enum.name)
+ ? [column.enum.name]
+ : [],
+ ),
+ ),
+ );
+ for (const name of undeclaredEnums) {
+ omit({
+ kind: "type",
+ name,
+ reason: "only what schema.ts leaves out uses it",
+ });
+ }
+
+ // 4. Declaration order: targets before the tables that reference them.
+ const ordered: TablePlan[] = [];
+ const placed = new Set();
+ const place = (plan: TablePlan) => {
+ if (placed.has(plan.table.name)) return;
+ placed.add(plan.table.name);
+ for (const target of [...(edges.get(plan.table.name) ?? [])].sort()) {
+ const targetPlan = plans.get(target);
+ if (targetPlan) place(targetPlan);
+ }
+ ordered.push(plan);
+ };
+ for (const plan of plans.values()) place(plan);
+
+ // 5. Identifiers and imports.
+ const imports = new Set(["defineSchema"]);
+ for (const plan of ordered) {
+ for (const column of plan.columns) {
+ if (column.fk) imports.add("fk");
+ else if (column.base.importName) imports.add(column.base.importName);
+ }
+ }
+ const usesEnum = ordered.some((plan) =>
+ plan.columns.some((c) => !c.fk && c.base.storage === "enum"),
+ );
+ const used = new Set([...imports, "table", "enumType", "schema"]);
+ for (const plan of ordered) {
+ let candidate = plan.table.name.replace(/[^A-Za-z0-9_$]/g, "_");
+ if (!/^[A-Za-z_$]/.test(candidate)) candidate = `_${candidate}`;
+ if (used.has(candidate) || JS_RESERVED.has(candidate)) {
+ candidate = `${candidate}Table`;
+ }
+ let variable = candidate;
+ for (let n = 2; used.has(variable); n++) variable = `${candidate}${n}`;
+ used.add(variable);
+ plan.variable = variable;
+ }
+
+ // 6. Source.
+ const lines: string[] = [
+ `// Generated by \`appkit db introspect\` from schema "${shown(schemaName)}". Edit tables here,`,
+ "// then run `npx appkit db migrate` on your dev branch.",
+ importLine(
+ [...imports].sort(),
+ options.importSource ?? "@databricks/appkit/beta",
+ ),
+ "",
+ ];
+ // Only a schema other than the default is passed to defineSchema().
+ const schemaOption =
+ schemaName === DEFAULT_SCHEMA_NAME
+ ? undefined
+ : `{ schemaName: ${q(schemaName)} }`;
+ if (renamed.length > 0) {
+ warnings.push(
+ `Constraint names differ from the ones migrations use: ${list(renamed)}. A later migration that drops or changes one of them fails until it is renamed in the database (ALTER TABLE … RENAME CONSTRAINT).`,
+ );
+ }
+ const result = (source: string): SchemaSource => ({
+ source,
+ tables: ordered.map((plan) => plan.table.name),
+ skipped,
+ unexpressed,
+ warnings: warnings.map(shown),
+ approximated: approximated.map(shown),
+ });
+ if (ordered.length === 0) {
+ lines.push(...tableComments);
+ lines.push(
+ `export const schema = defineSchema(() => ({})${schemaOption ? `, ${schemaOption}` : ""});`,
+ "",
+ );
+ return result(lines.join("\n"));
+ }
+
+ // The builder's body, indented one level.
+ const body: string[] = [];
+ for (const plan of ordered) {
+ body.push(` const ${plan.variable} = table(${q(plan.table.name)}, {`);
+ for (const comment of plan.comments) body.push(` ${comment}`);
+ for (const entry of plan.body) {
+ if (typeof entry === "string") {
+ body.push(` ${entry}`);
+ continue;
+ }
+ const column = entry;
+ for (const comment of column.comments) body.push(` ${comment}`);
+ const chain: string[] = [];
+ const head = column.fk
+ ? `fk(() => ${access((plans.get(column.fk.table) as TablePlan).variable, column.fk.column)})`
+ : column.base.call;
+ const serverKey =
+ !column.fk &&
+ (column.base.storage === "id" || column.base.storage === "bigid");
+ if (column.isPrimaryKey && !serverKey) chain.push(".primaryKey()");
+ else if (column.column.notNull && !serverKey) chain.push(".notNull()");
+ if (column.isUnique) chain.push(".unique()");
+ if (column.defaultCall) chain.push(column.defaultCall);
+ chain.push(...(column.fk?.actions ?? []));
+ if (isPrivate(plan.table.name, column.column.name)) {
+ chain.push(".private()");
+ }
+ body.push(` ${key(column.column.name)}: ${head}${chain.join("")},`);
+ }
+ body.push(" });", "");
+ }
+ for (const comment of tableComments) body.push(` ${comment}`);
+ if (tableComments.length > 0) body.push("");
+ const entries = ordered.map((plan) =>
+ plan.variable === plan.table.name
+ ? plan.variable
+ : `${key(plan.table.name)}: ${plan.variable}`,
+ );
+ body.push(` return { ${entries.join(", ")} };`);
+
+ const builder = `({ table${usesEnum ? ", enum: enumType" : ""} }) =>`;
+ if (schemaOption) {
+ lines.push(
+ "export const schema = defineSchema(",
+ ` ${builder} {`,
+ ...body.map((line) => (line ? ` ${line}` : line)),
+ " },",
+ ` ${schemaOption},`,
+ ");",
+ "",
+ );
+ } else {
+ lines.push(
+ `export const schema = defineSchema(${builder} {`,
+ ...body,
+ "});",
+ "",
+ );
+ }
+ return result(lines.join("\n"));
+}
diff --git a/packages/appkit/src/database/tooling/introspect/tests/catalog.pg.test.ts b/packages/appkit/src/database/tooling/introspect/tests/catalog.pg.test.ts
new file mode 100644
index 000000000..610bdbb2c
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/tests/catalog.pg.test.ts
@@ -0,0 +1,198 @@
+import { randomUUID } from "node:crypto";
+
+import { Pool } from "pg";
+import { afterAll, beforeAll, describe, expect, test } from "vitest";
+
+import { type CatalogQuery, readCatalog, readUnreadObjects } from "../catalog";
+
+// The catalog SQL against a real server. Point it at a scratch database, e.g.
+// APPKIT_TEST_PG_URL=postgres://localhost:5432/postgres
+const url = process.env.APPKIT_TEST_PG_URL;
+
+describe.skipIf(!url)("readCatalog against Postgres", () => {
+ const schema = `appkit_catalog_${randomUUID().slice(0, 8)}`;
+ let pool: Pool;
+ const query: CatalogQuery = async (
+ text: string,
+ values: readonly unknown[],
+ ) => (await pool.query(text, [...values])).rows as T[];
+
+ beforeAll(async () => {
+ pool = new Pool({ connectionString: url, max: 1 });
+ const s = `"${schema}"`;
+ await pool.query(`
+ create schema ${s};
+ create table ${s}.__drizzle_migrations (id serial primary key, hash text not null, created_at bigint);
+ create type ${s}.ticket_status as enum ('open', 'closed');
+ create table ${s}.authors (
+ id serial primary key,
+ email varchar(255) not null unique,
+ created_at timestamptz not null default now()
+ );
+ create table ${s}.posts (
+ id integer generated by default as identity primary key,
+ author_id integer not null references ${s}.authors (id) on delete cascade,
+ status ${s}.ticket_status not null default 'open',
+ total integer generated always as (id * 2) stored,
+ score numeric(10, 2) check (score > 0)
+ );
+ create index posts_status_idx on ${s}.posts (status);
+ create table ${s}.events (a integer, b integer, primary key (a, b));
+ create table ${s}.parts (id integer primary key) partition by range (id);
+ create table ${s}.parts_1 partition of ${s}.parts for values from (0) to (100);
+ create table ${s}.refs (id integer primary key, part_id integer references ${s}.parts (id));
+ create type ${s}."order-status" as enum ('open', 'closed');
+ create table ${s}.orders (
+ id integer primary key,
+ status ${s}."order-status" not null default 'open'
+ );
+ create table ${s}.counters (
+ id integer generated by default as identity (start with 100 increment by 10) primary key,
+ slug text unique deferrable initially deferred
+ );
+
+ create view ${s}.active_authors as select * from ${s}.authors;
+ create materialized view ${s}.mv as select 1 as x;
+ create sequence ${s}.standalone;
+ create function ${s}.touch() returns trigger language plpgsql as 'begin return new; end';
+ create trigger audit before update on ${s}.authors for each row execute function ${s}.touch();
+ alter table ${s}.authors enable row level security;
+ create policy own on ${s}.authors using (true);
+ create table ${s}.base (id integer primary key);
+ create table ${s}.child (extra integer) inherits (${s}.base);
+ create domain ${s}.positive as integer check (value > 0);
+ create type ${s}.pair as (a integer, b integer);
+ create type ${s}.unused_kind as enum ('x');
+ `);
+ });
+ afterAll(async () => {
+ await pool.query(`drop schema if exists "${schema}" cascade`);
+ await pool.end();
+ });
+
+ test("reads tables, keys, foreign keys, enums, generated and identity columns, and what schema.ts cannot declare", async () => {
+ const tables = await readCatalog(query, schema);
+ const byName = Object.fromEntries(tables.map((t) => [t.name, t]));
+
+ expect(tables.map((t) => t.name)).toEqual([
+ "authors",
+ "base",
+ "child",
+ "counters",
+ "events",
+ "orders",
+ "parts",
+ "posts",
+ "refs",
+ ]);
+ expect(byName.authors).toMatchObject({
+ primaryKey: ["id"],
+ unique: [{ name: "authors_email_key", columns: ["email"] }],
+ columns: [
+ {
+ name: "id",
+ type: "integer",
+ notNull: true,
+ identity: "",
+ defaultExpr: `nextval('${schema}.authors_id_seq'::regclass)`,
+ },
+ { name: "email", type: "character varying(255)", notNull: true },
+ {
+ name: "created_at",
+ type: "timestamp with time zone",
+ defaultExpr: "now()",
+ },
+ ],
+ });
+ expect(byName.posts).toMatchObject({
+ primaryKey: ["id"],
+ foreignKeys: [
+ {
+ name: "posts_author_id_fkey",
+ columns: ["author_id"],
+ schema,
+ table: "authors",
+ refColumns: ["id"],
+ onDelete: "cascade",
+ onUpdate: "no action",
+ },
+ ],
+ checks: ["posts_score_check"],
+ indexes: ["posts_status_idx"],
+ });
+ const posts = Object.fromEntries(
+ (byName.posts?.columns ?? []).map((c) => [c.name, c]),
+ );
+ expect(posts.id?.identity).toBe("d");
+ expect(posts.total?.generated).toBe(true);
+ expect(posts.status?.enum).toEqual({
+ name: "ticket_status",
+ schema,
+ values: ["open", "closed"],
+ });
+ expect(byName.counters).toMatchObject({
+ unique: [
+ { name: "counters_slug_key", columns: ["slug"], deferrable: true },
+ ],
+ columns: [
+ {
+ name: "id",
+ identity: "d",
+ sequence: {
+ start: "100",
+ increment: "10",
+ min: "1",
+ max: "2147483647",
+ cache: "1",
+ cycle: false,
+ },
+ },
+ { name: "slug" },
+ ],
+ });
+ // A serial key owns a sequence with the defaults; a plain column owns none.
+ expect(byName.authors?.columns[0]?.sequence).toEqual({
+ start: "1",
+ increment: "1",
+ min: "1",
+ max: "2147483647",
+ cache: "1",
+ cycle: false,
+ });
+ expect(posts.author_id).not.toHaveProperty("sequence");
+ // A type name with punctuation comes back quoted in the default's cast.
+ expect(byName.orders?.columns.find((c) => c.name === "status")).toEqual({
+ name: "status",
+ type: `${schema}."order-status"`,
+ notNull: true,
+ identity: "",
+ generated: false,
+ defaultExpr: `'open'::${schema}."order-status"`,
+ enum: { name: "order-status", schema, values: ["open", "closed"] },
+ });
+ expect(byName.events?.primaryKey).toEqual(["a", "b"]);
+ expect(byName.parts?.partitioned).toBe(true);
+ // One foreign key, not one more per partition of its target.
+ expect(byName.refs?.foreignKeys.map((fk) => fk.table)).toEqual(["parts"]);
+ });
+
+ test("names what it does not read, leaving out sequences that belong to a column", async () => {
+ const unread = await readUnreadObjects(query, schema);
+
+ expect([...unread].sort()).toEqual(
+ [
+ "domain positive",
+ "function touch()",
+ "inheritance of child from base",
+ "materialized view mv",
+ "policy own on authors",
+ "row-level security on authors",
+ "sequence standalone",
+ "trigger audit on authors",
+ "type pair",
+ "type unused_kind",
+ "view active_authors",
+ ].sort(),
+ );
+ });
+});
diff --git a/packages/appkit/src/database/tooling/introspect/tests/catalog.test.ts b/packages/appkit/src/database/tooling/introspect/tests/catalog.test.ts
new file mode 100644
index 000000000..29fd0f42a
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/tests/catalog.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, test } from "vitest";
+
+import { buildTables, readCatalog } from "../catalog";
+import { catalogResponder, catalogRows } from "./fixture";
+
+describe("readCatalog", () => {
+ test("maps catalog rows to tables, columns, keys, foreign keys and enums", async () => {
+ const { respond } = catalogResponder();
+ const [authors, posts] = await readCatalog(respond, "app");
+
+ expect(authors).toEqual({
+ name: "authors",
+ partitioned: false,
+ primaryKey: ["id"],
+ unique: [
+ { name: "authors_email_key", columns: ["email"], deferrable: false },
+ ],
+ foreignKeys: [],
+ checks: [],
+ indexes: [],
+ columns: [
+ {
+ name: "id",
+ type: "integer",
+ notNull: true,
+ identity: "",
+ generated: false,
+ defaultExpr: "nextval('app.authors_id_seq'::regclass)",
+ },
+ {
+ name: "email",
+ type: "character varying(255)",
+ notNull: true,
+ identity: "",
+ generated: false,
+ defaultExpr: null,
+ },
+ {
+ name: "created_at",
+ type: "timestamp with time zone",
+ notNull: true,
+ identity: "",
+ generated: false,
+ defaultExpr: "now()",
+ },
+ ],
+ });
+ expect(posts?.primaryKey).toEqual(["id"]);
+ expect(posts?.foreignKeys).toEqual([
+ {
+ name: "posts_author_id_fkey",
+ columns: ["author_id"],
+ schema: "app",
+ table: "authors",
+ refColumns: ["id"],
+ onDelete: "cascade",
+ onUpdate: "no action",
+ deferrable: false,
+ matchFull: false,
+ },
+ ]);
+ expect(posts?.indexes).toEqual(["posts_status_idx"]);
+ expect(posts?.columns.find((c) => c.name === "id")?.identity).toBe("d");
+ expect(posts?.columns.find((c) => c.name === "total")?.generated).toBe(
+ true,
+ );
+ expect(posts?.columns.find((c) => c.name === "status")?.enum).toEqual({
+ name: "ticket_status",
+ schema: "app",
+ values: ["open", "closed"],
+ });
+ });
+
+ test("partitioned tables, CHECK and EXCLUDE constraints, indexes, DEFERRABLE and MATCH FULL are kept for the report", () => {
+ const row = (kind: "c" | "x" | "f" | "u", name: string, extra = {}) => ({
+ ...catalogRows.constraints[2],
+ kind,
+ name,
+ ...extra,
+ });
+ const [table] = buildTables(
+ [{ name: "posts", partitioned: true }],
+ [],
+ [
+ row("c", "posts_score_check"),
+ row("x", "posts_no_overlap"),
+ row("f", "posts_author_id_fkey", {
+ deferrable: true,
+ match_type: "f",
+ }),
+ row("u", "posts_slug_key", { columns: ["slug"], deferrable: true }),
+ ] as never,
+ [
+ { table_name: "posts", name: "posts_status_idx" },
+ { table_name: "authors", name: "authors_name_idx" },
+ ],
+ );
+ expect(table).toMatchObject({
+ partitioned: true,
+ checks: ["posts_score_check", "posts_no_overlap"],
+ indexes: ["posts_status_idx"],
+ foreignKeys: [{ deferrable: true, matchFull: true }],
+ unique: [{ name: "posts_slug_key", columns: ["slug"], deferrable: true }],
+ });
+ });
+
+ test("an identity or serial column carries the options of the sequence it owns", () => {
+ const sequence = {
+ start: "100",
+ increment: "10",
+ min: "1",
+ max: "2147483647",
+ cache: "1",
+ cycle: false,
+ };
+ const [table] = buildTables(
+ [{ name: "t", partitioned: false }],
+ [
+ { ...catalogRows.columns[0], table_name: "t", sequence },
+ { ...catalogRows.columns[1], table_name: "t", sequence: null },
+ ] as never,
+ [],
+ );
+ expect(table?.columns[0]?.sequence).toEqual(sequence);
+ expect(table?.columns[1]).not.toHaveProperty("sequence");
+ });
+
+ test("stored and virtual (PG18) generated columns are both generated", () => {
+ const [table] = buildTables(
+ [{ name: "t", partitioned: false }],
+ ["s", "v", ""].map((generated, i) => ({
+ ...catalogRows.columns[0],
+ table_name: "t",
+ name: `c${i}`,
+ generated,
+ })) as never,
+ [],
+ );
+ expect(table?.columns.map((c) => c.generated)).toEqual([true, true, false]);
+ });
+
+ test("referential action letters map to builder actions", () => {
+ const fkRow = (on_delete: string, on_update: string) => ({
+ ...catalogRows.constraints[2],
+ on_delete,
+ on_update,
+ });
+ const [table] = buildTables(
+ [{ name: "posts", partitioned: false }],
+ [],
+ ["r", "c", "n", "d", "a"].map((letter) => fkRow(letter, letter)) as never,
+ );
+ expect(table?.foreignKeys.map((fk) => [fk.onDelete, fk.onUpdate])).toEqual([
+ ["restrict", "restrict"],
+ ["cascade", "cascade"],
+ ["set null", "set null"],
+ ["set default", "set default"],
+ ["no action", "no action"],
+ ]);
+ });
+});
diff --git a/packages/appkit/src/database/tooling/introspect/tests/fixture.ts b/packages/appkit/src/database/tooling/introspect/tests/fixture.ts
new file mode 100644
index 000000000..652e0a168
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/tests/fixture.ts
@@ -0,0 +1,295 @@
+import path from "node:path";
+
+import type {
+ CatalogQuery,
+ ColumnRow,
+ ConstraintRow,
+ IndexRow,
+ IntrospectedColumn,
+ IntrospectedForeignKey,
+ IntrospectedTable,
+ IntrospectedUnique,
+ TableRow,
+} from "../catalog";
+
+/** The builder by absolute path, so rendered sources load from a temp root. */
+export const BUILDER = path.resolve(
+ import.meta.dirname,
+ "../../../schema-builder/index.ts",
+);
+
+export const col = (
+ name: string,
+ type: string,
+ extra: Partial = {},
+): IntrospectedColumn => ({
+ name,
+ type,
+ notNull: false,
+ identity: "",
+ generated: false,
+ defaultExpr: null,
+ ...extra,
+});
+
+/** A catalog table; what a test does not set is empty. */
+export const tableOf = (
+ table: Pick &
+ Partial,
+): IntrospectedTable => ({
+ partitioned: false,
+ primaryKey: [],
+ unique: [],
+ foreignKeys: [],
+ checks: [],
+ indexes: [],
+ ...table,
+});
+
+export const foreignKey = (
+ key: Omit &
+ Partial,
+): IntrospectedForeignKey => ({ deferrable: false, matchFull: false, ...key });
+
+/** A unique constraint with the name Postgres gives it. */
+export const uniqueKey = (
+ table: string,
+ ...columns: string[]
+): IntrospectedUnique => ({
+ name: `${table}_${columns.join("_")}_key`,
+ columns,
+ deferrable: false,
+});
+
+const status = {
+ name: "ticket_status",
+ schema: "app",
+ values: ["open", "closed"],
+};
+
+/** Supported types, defaults, FKs and enums, plus one of each skip. Listed out of dependency order. */
+export const richTables: IntrospectedTable[] = [
+ tableOf({
+ name: "posts",
+ primaryKey: ["id"],
+ unique: [],
+ foreignKeys: [
+ foreignKey({
+ name: "posts_author_id_fkey",
+ columns: ["author_id"],
+ schema: "app",
+ table: "authors",
+ refColumns: ["id"],
+ onDelete: "cascade",
+ onUpdate: "no action",
+ }),
+ foreignKey({
+ name: "posts_editor_id_fkey",
+ columns: ["editor_id"],
+ schema: "app",
+ table: "authors",
+ refColumns: ["id"],
+ onDelete: "set null",
+ onUpdate: "no action",
+ }),
+ ],
+ columns: [
+ col("id", "uuid", { notNull: true, defaultExpr: "gen_random_uuid()" }),
+ col("author_id", "integer", { notNull: true }),
+ col("editor_id", "integer"),
+ col("status", "app.ticket_status", {
+ notNull: true,
+ defaultExpr: "'open'::app.ticket_status",
+ enum: status,
+ }),
+ col("body", "jsonb", { defaultExpr: "'{}'::jsonb" }),
+ col("views", "bigint", { notNull: true, defaultExpr: "0" }),
+ col("my col", "character varying"),
+ ],
+ }),
+ tableOf({
+ name: "authors",
+ primaryKey: ["id"],
+ unique: [uniqueKey("authors", "email")],
+ foreignKeys: [],
+ columns: [
+ col("id", "integer", {
+ notNull: true,
+ defaultExpr: "nextval('app.authors_id_seq'::regclass)",
+ }),
+ col("email", "character varying(255)", { notNull: true }),
+ col("bio", "text", { defaultExpr: "'it''s me'::text" }),
+ col("active", "boolean", { notNull: true, defaultExpr: "true" }),
+ col("score", "numeric(10,2)", { notNull: true }),
+ col("rank", "integer", { defaultExpr: "'-1'::integer" }),
+ col("created_at", "timestamp with time zone", {
+ notNull: true,
+ defaultExpr: "now()",
+ }),
+ col("seen_at", "timestamp(3) without time zone"),
+ ],
+ }),
+ tableOf({
+ name: "events",
+ primaryKey: ["a", "b"],
+ unique: [],
+ foreignKeys: [],
+ columns: [
+ col("a", "integer", { notNull: true }),
+ col("b", "integer", { notNull: true }),
+ ],
+ }),
+ tableOf({
+ name: "logs",
+ primaryKey: [],
+ unique: [],
+ foreignKeys: [],
+ columns: [col("line", "text")],
+ }),
+ tableOf({
+ name: "default",
+ primaryKey: ["id"],
+ unique: [],
+ foreignKeys: [],
+ columns: [col("id", "bigint", { notNull: true, identity: "d" })],
+ }),
+];
+
+export const columnRow = (
+ table_name: string,
+ name: string,
+ type: string,
+ extra: Partial = {},
+): ColumnRow => ({
+ table_name,
+ name,
+ type,
+ not_null: false,
+ identity: "",
+ generated: "",
+ default_expr: null,
+ type_kind: "b",
+ type_schema: "pg_catalog",
+ type_name: type,
+ enum_values: null,
+ sequence: null,
+ ...extra,
+});
+
+/** What the three pg_catalog queries return for a small hand-made schema. */
+export const catalogRows = {
+ tables: [
+ { name: "authors", partitioned: false },
+ { name: "posts", partitioned: false },
+ ] satisfies TableRow[],
+ columns: [
+ columnRow("authors", "id", "integer", {
+ not_null: true,
+ default_expr: "nextval('app.authors_id_seq'::regclass)",
+ }),
+ columnRow("authors", "email", "character varying(255)", {
+ not_null: true,
+ }),
+ columnRow("authors", "created_at", "timestamp with time zone", {
+ not_null: true,
+ default_expr: "now()",
+ }),
+ columnRow("posts", "id", "integer", { not_null: true, identity: "d" }),
+ columnRow("posts", "author_id", "integer", { not_null: true }),
+ columnRow("posts", "status", "app.ticket_status", {
+ not_null: true,
+ default_expr: "'open'::app.ticket_status",
+ type_kind: "e",
+ type_schema: "app",
+ type_name: "ticket_status",
+ enum_values: ["open", "closed"],
+ }),
+ columnRow("posts", "score", "numeric(10,2)", { not_null: true }),
+ columnRow("posts", "total", "integer", {
+ generated: "s",
+ default_expr: "1",
+ }),
+ ] satisfies ColumnRow[],
+ constraints: [
+ {
+ table_name: "authors",
+ name: "authors_email_key",
+ kind: "u",
+ columns: ["email"],
+ ref_schema: null,
+ ref_table: null,
+ ref_columns: [],
+ on_delete: " ",
+ on_update: " ",
+ },
+ {
+ table_name: "authors",
+ name: "authors_pkey",
+ kind: "p",
+ columns: ["id"],
+ ref_schema: null,
+ ref_table: null,
+ ref_columns: [],
+ on_delete: " ",
+ on_update: " ",
+ },
+ {
+ table_name: "posts",
+ name: "posts_author_id_fkey",
+ kind: "f",
+ columns: ["author_id"],
+ ref_schema: "app",
+ ref_table: "authors",
+ ref_columns: ["id"],
+ on_delete: "c",
+ on_update: "a",
+ },
+ {
+ table_name: "posts",
+ name: "posts_pkey",
+ kind: "p",
+ columns: ["id"],
+ ref_schema: null,
+ ref_table: null,
+ ref_columns: [],
+ on_delete: " ",
+ on_update: " ",
+ },
+ ] satisfies ConstraintRow[],
+ indexes: [
+ { table_name: "posts", name: "posts_status_idx" },
+ ] satisfies IndexRow[],
+};
+
+/** A CatalogQuery answering the catalog queries from rows, and the unread-objects query from labels. */
+export function catalogResponder(
+ rows: {
+ readonly tables: readonly TableRow[];
+ readonly columns: readonly ColumnRow[];
+ readonly constraints: readonly ConstraintRow[];
+ readonly indexes: readonly IndexRow[];
+ } = catalogRows,
+ unread: readonly string[] = [],
+) {
+ const calls: Array<{ text: string; values: readonly unknown[] }> = [];
+ const respond: CatalogQuery = async (
+ text: string,
+ values: readonly unknown[],
+ ) => {
+ calls.push({ text, values });
+ // Each query is told apart by text only it has; the index query mentions pg_constraint, so it goes before that one.
+ const result = text.includes("select o.label")
+ ? unread.map((label) => ({ label }))
+ : text.includes("pg_catalog.pg_index")
+ ? rows.indexes
+ : text.includes("pg_catalog.pg_constraint")
+ ? rows.constraints
+ : text.includes("format_type")
+ ? rows.columns
+ : text.includes("select c.relname::text as name")
+ ? rows.tables
+ : [];
+ return result as unknown as T[];
+ };
+ return { calls, respond };
+}
diff --git a/packages/appkit/src/database/tooling/introspect/tests/golden/rich.schema.ts.txt b/packages/appkit/src/database/tooling/introspect/tests/golden/rich.schema.ts.txt
new file mode 100644
index 000000000..2fe3e54d5
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/tests/golden/rich.schema.ts.txt
@@ -0,0 +1,51 @@
+// Generated by `appkit db introspect` from schema "app". Edit tables here,
+// then run `npx appkit db migrate` on your dev branch.
+import {
+ bigid,
+ bigint,
+ boolean,
+ defineSchema,
+ fk,
+ id,
+ integer,
+ jsonb,
+ text,
+ timestamp,
+ uuid,
+ varchar,
+} from "@databricks/appkit/beta";
+
+export const schema = defineSchema(({ table, enum: enumType }) => {
+ const authors = table("authors", {
+ id: id(),
+ email: varchar(255).notNull().unique(),
+ bio: text().default("it's me"),
+ active: boolean().notNull().default(true),
+ // appkit: skipped column "score": type "numeric(10,2)" is not supported
+ rank: integer().default(-1),
+ created_at: timestamp({ withTimezone: true }).notNull().defaultNow(),
+ seen_at: timestamp(),
+ });
+
+ const posts = table("posts", {
+ id: uuid().primaryKey().defaultRandom(),
+ author_id: fk(() => authors.id).notNull().onDelete("cascade"),
+ // appkit: skipped foreign key to authors(id) is not kept: a second foreign key to "authors" would make the relation ambiguous
+ editor_id: integer(),
+ status: enumType("ticket_status", ["open", "closed"]).notNull().default("open"),
+ // appkit: skipped default '{}'::jsonb is not supported
+ body: jsonb(),
+ // appkit: skipped default 0 is not supported
+ views: bigint().notNull(),
+ "my col": text(),
+ });
+
+ const defaultTable = table("default", {
+ id: bigid(),
+ });
+
+ // appkit: skipped table "events": composite primary key (a, b) is not supported
+ // appkit: skipped table "logs": it has no primary key
+
+ return { authors, posts, default: defaultTable };
+});
diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts
new file mode 100644
index 000000000..60bd29efe
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts
@@ -0,0 +1,1192 @@
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import path from "node:path";
+
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+const { markMigrationsApplied, resolveEnvBranch, withBranchPool, writeTypes } =
+ vi.hoisted(() => ({
+ markMigrationsApplied: vi.fn(),
+ resolveEnvBranch: vi.fn(),
+ withBranchPool: vi.fn(),
+ writeTypes: vi.fn(),
+ }));
+
+vi.mock("../../context", async (importOriginal) => ({
+ ...(await importOriginal()),
+ withBranchPool,
+}));
+vi.mock("../../guard", async (importOriginal) => ({
+ ...(await importOriginal()),
+ resolveEnvBranch,
+}));
+vi.mock("../../../migrations/apply", async (importOriginal) => ({
+ ...(await importOriginal()),
+ markMigrationsApplied,
+}));
+vi.mock("../../../../type-generator/database", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("../../../../type-generator/database")
+ >()),
+ writeDatabaseTypes: writeTypes,
+}));
+
+import { loadDefaultDatabaseSchema } from "../../../../plugins/database/load-schema";
+import { readJournal } from "../../../migrations/paths";
+import { hashOf } from "../../../migrations/tests/fixtures";
+import { withHistoryLock } from "../../history-lock";
+import { generateMigrationFiles } from "../../migrations";
+import { FORK_COPY_TAG } from "../../schema-state";
+import { cleanupTempApps, fakeContext, tempApp } from "../../tests/fakes";
+import type { ColumnRow, ConstraintRow, TableRow } from "../catalog";
+import { IntrospectRefusedError, runIntrospect } from "../index";
+import { BUILDER, catalogResponder, columnRow } from "./fixture";
+
+const { writeDatabaseTypes } = await vi.importActual<
+ typeof import("../../../../type-generator/database")
+>("../../../../type-generator/database");
+
+const SCHEMA = "config/database/schema.ts";
+const MIGRATIONS = "config/database/migrations";
+const TYPES = "shared/appkit-types/database.d.ts";
+const OPERATION_TYPES = "shared/appkit-types/database-operations.d.ts";
+const OPERATIONS_MODULE = path.resolve(
+ import.meta.dirname,
+ "../../../../plugins/database/operations.ts",
+);
+const ZOD_PACKAGE = path.dirname(
+ createRequire(import.meta.url).resolve("zod/package.json"),
+);
+const DEV = "projects/p/branches/dev-alice-3f9a2c";
+const PRODUCTION = "projects/p/branches/production";
+
+const previousSchema = `import { defineSchema, id, text } from ${JSON.stringify(BUILDER)};
+export const schema = defineSchema(({ table }) => ({
+ authors: table("authors", { id: id(), email: text() }),
+}));
+`;
+
+/** Declares both tables of the default catalog and its foreign key, with email private. */
+const declaredSchema = `import { defineSchema, fk, id, text } from ${JSON.stringify(BUILDER)};
+export const schema = defineSchema(({ table }) => {
+ const authors = table("authors", { id: id(), email: text().private() });
+ const posts = table("posts", {
+ id: id(),
+ author_id: fk(() => authors.id).notNull(),
+ });
+ return { authors, posts };
+});
+`;
+
+const RESOLVED = { branches: new Set(), unresolved: [] };
+const onDevBranch = { branch: { name: DEV }, boundary: RESOLVED, kind: "dev" };
+const onProduction = {
+ branch: { name: PRODUCTION, status: { default: true } },
+ boundary: RESOLVED,
+ kind: "default",
+ reason: "it is the project's default branch",
+};
+
+let catalog: ReturnType;
+/** The journal rows of the branch, as drizzle-orm records them; empty: no journal table. */
+let recorded: Array<{ when: number; hash: string }>;
+let tagged: boolean;
+let schemaOwner: string;
+/** The row the branch records for the last committed migration. */
+const lastCommitted = (root: string) => {
+ const folder = path.join(root, MIGRATIONS);
+ const entry = readJournal(folder)?.entries.at(-1);
+ if (!entry) throw new Error(`no migration committed under ${folder}`);
+ return { when: entry.when, hash: hashOf(folder, entry.tag) };
+};
+const pool = {
+ query: vi.fn(async (text: string, values: unknown[]) => {
+ // readMigrationDrift: whether the journal table exists, then its rows.
+ if (text.includes("c.relname = $2")) {
+ // The app's own journal: an ordinary table its role owns.
+ const journal = {
+ relkind: "r",
+ owner: "app-sp",
+ schema_owner: "app-sp",
+ current_user: "app-sp",
+ row_security: false,
+ trusted: true,
+ };
+ return { rows: recorded.length > 0 ? [journal] : [] };
+ }
+ if (text.includes("where hash = $1")) return { rows: tagged ? [{}] : [] };
+ if (text.includes("has_schema_privilege")) {
+ return {
+ rows: [
+ { owner: schemaOwner, can_create: true, current_user: "app-sp" },
+ ],
+ };
+ }
+ if (text.includes("select hash, created_at")) {
+ return {
+ rows: recorded.map(({ when, hash }) => ({
+ hash,
+ created_at: String(when),
+ })),
+ };
+ }
+ return { rows: await catalog.respond(text, values) };
+ }),
+ end: vi.fn(async () => undefined),
+};
+
+beforeEach(() => {
+ catalog = catalogResponder();
+ recorded = [];
+ tagged = false;
+ schemaOwner = "app-sp";
+ resolveEnvBranch.mockReset().mockResolvedValue(onDevBranch);
+ withBranchPool
+ .mockReset()
+ .mockImplementation(
+ async (_ctx: unknown, fn: (p: typeof pool) => Promise) => {
+ try {
+ return await fn(pool);
+ } finally {
+ await pool.end();
+ }
+ },
+ );
+ markMigrationsApplied
+ .mockReset()
+ .mockImplementation(
+ async (
+ _pool: unknown,
+ options: { migrationsFolder: string },
+ tags: readonly string[],
+ ) => {
+ const entries = readJournal(options.migrationsFolder)?.entries ?? [];
+ for (const tag of tags) {
+ recorded.push({
+ when: entries.find((entry) => entry.tag === tag)?.when ?? 0,
+ hash: hashOf(options.migrationsFolder, tag),
+ });
+ }
+ },
+ );
+ writeTypes.mockReset().mockImplementation(writeDatabaseTypes);
+ pool.end.mockClear();
+});
+afterEach(cleanupTempApps);
+
+const authorsPkey: ConstraintRow = {
+ table_name: "authors",
+ name: "authors_pkey",
+ kind: "p",
+ columns: ["id"],
+ ref_schema: null,
+ ref_table: null,
+ ref_columns: [],
+ on_delete: " ",
+ on_update: " ",
+};
+
+/** A catalog with authors(id) plus the given authors columns, and any extra tables. */
+const authorsOnly = (
+ columns: ColumnRow[] = [],
+ extra: {
+ tables: TableRow[];
+ columns: ColumnRow[];
+ constraints?: ConstraintRow[];
+ } = {
+ tables: [],
+ columns: [],
+ },
+) =>
+ catalogResponder({
+ tables: [{ name: "authors", partitioned: false }, ...extra.tables],
+ columns: [
+ columnRow("authors", "id", "integer", { not_null: true, identity: "d" }),
+ ...columns,
+ ...extra.columns,
+ ],
+ constraints: [authorsPkey, ...(extra.constraints ?? [])],
+ indexes: [],
+ });
+
+/** A schema.ts of authors and posts, whose author_id is a foreign key to authors. */
+const postsOfAuthors = (schemaOption?: string) =>
+ `import { defineSchema, fk, id } from ${JSON.stringify(BUILDER)};
+export const schema = defineSchema(({ table }) => {
+ const authors = table("authors", { id: id() });
+ const posts = table("posts", { id: id(), author_id: fk(() => authors.id).notNull() });
+ return { authors, posts };
+}${schemaOption ? `, ${schemaOption}` : ""});
+`;
+
+/** postsOfAuthors' tables, with a foreign key the builder cannot declare: SET NULL on a NOT NULL column. */
+const setNullOnNotNull = (schemaName: string) =>
+ authorsOnly([], {
+ tables: [{ name: "posts", partitioned: false }],
+ columns: [
+ columnRow("posts", "id", "integer", { not_null: true, identity: "d" }),
+ columnRow("posts", "author_id", "integer", { not_null: true }),
+ ],
+ constraints: [
+ { ...authorsPkey, table_name: "posts", name: "posts_pkey" },
+ {
+ ...authorsPkey,
+ table_name: "posts",
+ name: "posts_author_id_fkey",
+ kind: "f",
+ columns: ["author_id"],
+ ref_schema: schemaName,
+ ref_table: "authors",
+ ref_columns: ["id"],
+ on_delete: "n",
+ on_update: "a",
+ },
+ ],
+ });
+
+/** Commit a migration of the current schema.ts; `applied`: the branch has recorded it. */
+async function commitMigration(root: string, applied = true): Promise {
+ await withHistoryLock(root, "migrate", async (lock) =>
+ generateMigrationFiles(lock, {
+ schema: await loadDefaultDatabaseSchema(root),
+ interactive: false,
+ }),
+ );
+ if (applied) recorded.push(lastCommitted(root));
+}
+
+/** Every file under config/, with its contents. */
+function tree(root: string): Record {
+ const files: Record = {};
+ const walk = (dir: string) => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full);
+ else files[path.relative(root, full)] = fs.readFileSync(full, "utf-8");
+ }
+ };
+ if (fs.existsSync(path.join(root, "config"))) walk(path.join(root, "config"));
+ return files;
+}
+
+const ctxFor = (root: string) => fakeContext({ root });
+const introspect = (root: string) =>
+ runIntrospect(ctxFor(root), { interactive: false, importSource: BUILDER });
+/** The error a run fails with; a run that succeeds fails the test. */
+const rejection = (run: Promise) =>
+ run.then(
+ () => {
+ throw new Error("expected introspect to fail");
+ },
+ (caught: unknown) => caught as Error,
+ );
+const refusal = (root: string) => rejection(introspect(root));
+
+describe("runIntrospect", () => {
+ test("without history: schema.ts (+ .bak), 0000_baseline recorded as applied, database.d.ts", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+
+ const report = await introspect(root);
+
+ expect(catalog.calls.every((call) => call.values[0] === "app")).toBe(true);
+ expect(fs.readFileSync(path.join(root, `${SCHEMA}.bak`), "utf-8")).toBe(
+ declaredSchema,
+ );
+ const written = fs.readFileSync(path.join(root, SCHEMA), "utf-8");
+ expect(written).toContain('const authors = table("authors", {');
+ expect(written).toContain(
+ 'author_id: fk(() => authors.id).notNull().onDelete("cascade"),',
+ );
+ // What the replaced schema.ts declares keeps its .private(); the rest renders as the catalog has it.
+ expect(written).toContain(
+ "email: varchar(255).notNull().unique().private(),",
+ );
+ expect(written).toContain(
+ "created_at: timestamp({ withTimezone: true }).notNull().defaultNow(),",
+ );
+ expect(written).toContain("id: id(),");
+ expect(report).toMatchObject({
+ branch: DEV,
+ schemaName: "app",
+ tables: ["authors", "posts"],
+ schemaFile: path.join(root, SCHEMA),
+ backupFile: path.join(root, `${SCHEMA}.bak`),
+ recorded: ["0000_baseline"],
+ migration: { tag: "0000_baseline" },
+ });
+ expect(report.skipped.map((skip) => skip.column)).toEqual([
+ "score",
+ "total",
+ ]);
+ expect(report.warnings).toEqual([
+ expect.stringMatching(/^app\.posts\.score is NOT NULL with no default/),
+ "app.posts: index posts_status_idx is not in schema.ts, so a database the migrations create will not have it.",
+ expect.stringMatching(
+ /^Constraint names differ from the ones migrations use: authors_email_key \(authors_email_unique\), posts_author_id_fkey \(posts_author_id_authors_id_fk\)\./,
+ ),
+ ]);
+ expect(report.approximated).toEqual([
+ "app.authors.id: a serial key is declared as id(), an identity generated BY DEFAULT",
+ ]);
+ expect(
+ fs.existsSync(path.join(root, MIGRATIONS, "0000_baseline.sql")),
+ ).toBe(true);
+ expect(markMigrationsApplied).toHaveBeenCalledWith(
+ pool,
+ { migrationsFolder: path.join(root, MIGRATIONS), schemaName: "app" },
+ ["0000_baseline"],
+ );
+ expect(fs.readFileSync(report.typesFile, "utf-8")).toContain("authors");
+ expect(pool.end).toHaveBeenCalledOnce();
+ // The written schema is what the plugin loads.
+ await expect(loadDefaultDatabaseSchema(root)).resolves.toMatchObject({
+ $schemaName: "app",
+ });
+ });
+
+ test("regenerates database-operations.d.ts from server/database/routes", async () => {
+ const root = tempApp({
+ [SCHEMA]: declaredSchema,
+ "server/database/routes/authors.ts": `import { z } from "zod";
+ import { defineOperation } from ${JSON.stringify(OPERATIONS_MODULE)};
+ export const getAuthor = defineOperation({
+ name: "authors.get",
+ method: "GET",
+ input: z.object({ id: z.number() }),
+ output: z.object({ id: z.number() }),
+ authorize: () => true,
+ execute: ({ input, db }) => db.authors.find(input.id),
+ });`,
+ });
+ fs.mkdirSync(path.join(root, "node_modules"));
+ fs.symlinkSync(ZOD_PACKAGE, path.join(root, "node_modules/zod"), "dir");
+
+ const report = await introspect(root);
+
+ expect(report.operationsTypesFile).toBe(path.join(root, OPERATION_TYPES));
+ expect(fs.readFileSync(report.operationsTypesFile, "utf-8")).toContain(
+ '"authors.get"',
+ );
+ });
+
+ test.each([
+ ["without history", false],
+ ["with history", true],
+ ])(
+ "on a branch that is not yours (%s): refuses before connecting and points to appkit db init",
+ async (_label, history) => {
+ resolveEnvBranch.mockResolvedValue(onProduction);
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ if (history) await commitMigration(root);
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ "Refusing to introspect: production is not your dev or session branch (it is the project's default branch). Introspect records the migration it writes as applied, so it runs only on branches `appkit db init` created for you. " +
+ "Run `appkit db init`: it creates your dev branch from the branch the default databricks.yml target binds, else the project's default branch, and introspects it when there is no config/database/schema.ts.",
+ );
+ expect(withBranchPool).not.toHaveBeenCalled();
+ expect(tree(root)).toEqual(before);
+ },
+ );
+
+ test("while databricks.yml leaves a reference unresolved, the refusal names it instead of pointing to appkit db init", async () => {
+ resolveEnvBranch.mockResolvedValue({
+ branch: { name: DEV },
+ boundary: {
+ branches: new Set(),
+ unresolved: [
+ {
+ target: "default",
+ at: "variables.postgres_branch",
+ written: "",
+ },
+ ],
+ },
+ kind: "deploy-target",
+ reason:
+ "databricks.yml may deploy to it through a reference this checkout's files do not resolve",
+ });
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ "Refusing to introspect: dev-alice-3f9a2c is not your dev or session branch (databricks.yml may deploy to it through a reference this checkout's files do not resolve). " +
+ "The files do not resolve variables.postgres_branch in target default (no value), so `appkit db migrate` applies migrations to no branch, and `init`, `introspect`, `clean` and `seed` refuse every branch. Give it a value in databricks.yml.",
+ );
+ expect(withBranchPool).not.toHaveBeenCalled();
+ expect(tree(root)).toEqual(before);
+ });
+
+ test("with history: writes and records the next NNNN_introspect", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ await commitMigration(root);
+
+ const report = await introspect(root);
+
+ expect(report.migration?.tag).toBe("0001_introspect");
+ expect(report.migration?.statements.join("\n")).toContain(
+ 'ALTER TABLE "app"."posts" ADD COLUMN "status"',
+ );
+ expect(report.recorded).toEqual(["0001_introspect"]);
+ expect(markMigrationsApplied).toHaveBeenCalledWith(
+ pool,
+ expect.anything(),
+ ["0001_introspect"],
+ );
+ });
+
+ test("a second run with no catalog change writes no migration and records nothing", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ await introspect(root);
+ markMigrationsApplied.mockClear();
+
+ const report = await introspect(root);
+
+ expect(report.migration).toBeNull();
+ expect(report.recorded).toEqual([]);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ });
+
+ test("a branch whose journal still carries init's fork-copy tag is refused before anything is written", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ await introspect(root);
+ const written = fs.readFileSync(path.join(root, SCHEMA), "utf-8");
+ markMigrationsApplied.mockClear();
+ tagged = true;
+
+ const refused = introspect(root);
+
+ await expect(refused).rejects.toBeInstanceOf(IntrospectRefusedError);
+ await expect(refused).rejects.toThrow(
+ 'Refusing to introspect: dev-alice-3f9a2c still holds the rows the fork copied into schema "app", and its rebuild did not finish. Run `appkit db init` to rebuild it from the committed migrations, or `appkit db init --schema introspect` to keep them.',
+ );
+ expect(fs.readFileSync(path.join(root, SCHEMA), "utf-8")).toBe(written);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ });
+
+ test("an untouched copy another role owns is refused before anything is written", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ schemaOwner = "other-sp";
+
+ const refused = introspect(root);
+
+ await expect(refused).rejects.toBeInstanceOf(IntrospectRefusedError);
+ await expect(refused).rejects.toThrow(
+ 'Refusing to introspect: dev-alice-3f9a2c still holds the rows the fork copied into schema "app", which "other-sp" still owns. Run `appkit db init` to rebuild it from the committed migrations, or `appkit db init --schema introspect` to keep them.',
+ );
+ expect(fs.readFileSync(path.join(root, SCHEMA), "utf-8")).toBe(
+ declaredSchema,
+ );
+ expect(fs.existsSync(path.join(root, MIGRATIONS))).toBe(false);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ });
+
+ test("recordAsApplied: false reads a copy for init's rebuild, since it writes nothing on the branch", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ schemaOwner = "other-sp";
+
+ const report = await runIntrospect(fakeContext({ root }), {
+ interactive: false,
+ recordAsApplied: false,
+ });
+
+ expect(report.migration).toMatchObject({ tag: "0000_baseline" });
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ });
+
+ test("recordAsApplied: false reads a copy an earlier init tagged: the tag row in the journal is not a migration", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ schemaOwner = "other-sp";
+ recorded = [{ when: 0, hash: FORK_COPY_TAG }];
+
+ const report = await runIntrospect(fakeContext({ root }), {
+ interactive: false,
+ recordAsApplied: false,
+ });
+
+ expect(report.migration).toMatchObject({ tag: "0000_baseline" });
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ });
+
+ test("recordAsApplied: false writes schema.ts and the migration, and records nothing on the branch", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+
+ const report = await runIntrospect(fakeContext({ root }), {
+ interactive: false,
+ recordAsApplied: false,
+ });
+
+ expect(report.migration).toMatchObject({ tag: "0000_baseline" });
+ expect(report.recorded).toEqual([]);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ expect(
+ fs.existsSync(path.join(root, MIGRATIONS, "0000_baseline.sql")),
+ ).toBe(true);
+ });
+
+ test("a migration an interrupted run wrote but did not record is recorded when the branch matches it", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ await introspect(root);
+ // The run stopped after writing 0000_baseline, before recording it.
+ recorded = [];
+ markMigrationsApplied.mockClear();
+
+ const report = await introspect(root);
+
+ expect(report.migration).toBeNull();
+ expect(report.recorded).toEqual(["0000_baseline"]);
+ expect(markMigrationsApplied).toHaveBeenCalledWith(
+ pool,
+ expect.anything(),
+ ["0000_baseline"],
+ );
+ });
+
+ test("an unrecorded introspect migration the branch no longer matches is refused, and nothing changes", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ await introspect(root);
+ recorded = [];
+ catalog = authorsOnly();
+ markMigrationsApplied.mockClear();
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ 'Refusing to introspect dev-alice-3f9a2c: it has not applied 0000_baseline in schema "app". Its tables differ from what it describes. Run `appkit db migrate` first.',
+ );
+ expect(tree(root)).toEqual(before);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ });
+
+ test("a pending introspect migration someone edited after introspect wrote it is refused, and nothing changes", async () => {
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ await commitMigration(root);
+ // A teammate introspected their branch, then edited 0001_introspect before committing it.
+ await introspect(root);
+ recorded = recorded.slice(0, 1);
+ fs.appendFileSync(
+ path.join(root, MIGRATIONS, "0001_introspect.sql"),
+ `--> statement-breakpoint\nUPDATE "app"."posts" SET "status" = 'closed';`,
+ );
+ markMigrationsApplied.mockClear();
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ 'Refusing to introspect dev-alice-3f9a2c: it has not applied 0001_introspect in schema "app". Its SQL is not what introspect would write for the branch now, so recording it without running it could skip a change. Run `appkit db migrate` first.',
+ );
+ expect(tree(root)).toEqual(before);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ });
+
+ test("without schema.ts it reads the app schema and creates the file", async () => {
+ const root = tempApp();
+
+ const report = await introspect(root);
+
+ expect(catalog.calls.every((call) => call.values[0] === "app")).toBe(true);
+ expect(report).toMatchObject({
+ schemaName: "app",
+ backupFile: null,
+ tables: ["authors", "posts"],
+ migration: { tag: "0000_baseline" },
+ recorded: ["0000_baseline"],
+ });
+ expect(fs.readFileSync(path.join(root, SCHEMA), "utf-8")).toMatch(
+ /from schema "app"\.[^]*export const schema = defineSchema\(\(\{ table[^}]*\}\) => \{/,
+ );
+ expect(fs.existsSync(path.join(root, `${SCHEMA}.bak`))).toBe(false);
+ });
+
+ test("--schema-name picks another schema", async () => {
+ const root = tempApp();
+
+ const report = await runIntrospect(ctxFor(root), {
+ interactive: false,
+ importSource: BUILDER,
+ schemaName: "sales",
+ });
+
+ expect(catalog.calls.every((call) => call.values[0] === "sales")).toBe(
+ true,
+ );
+ expect(report.schemaName).toBe("sales");
+ });
+
+ test.each([
+ ["a syntax error", "export const schema = ;\n"],
+ ["a single line", "// todo\n"],
+ [
+ "a missing import",
+ `import { defineSchema } from ${JSON.stringify(BUILDER)};\nexport const schema = defineSchema(({ table }) => ({ x: table("x", { id: id() }) }));\n`,
+ ],
+ ])(
+ "a schema.ts with %s is refused before anything is read or written, since its private columns cannot be kept",
+ async (_label, broken) => {
+ const root = tempApp({ [SCHEMA]: broken });
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ "Refusing to introspect: config/database/schema.ts does not load, so introspect cannot keep the columns it marks private. Fix it, then rerun.",
+ );
+ expect(resolveEnvBranch).not.toHaveBeenCalled();
+ expect(catalog.calls).toEqual([]);
+ expect(tree(root)).toEqual(before);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ },
+ );
+
+ test("a schema.ts that fails to import keeps the import error for the CLI to show", async () => {
+ const root = tempApp({ [SCHEMA]: "export const schema = ;\n" });
+
+ const error = await refusal(root);
+
+ expect(((error.cause as Error).cause as Error).message).toMatch(
+ /schema\.ts:\d+:\d+/,
+ );
+ });
+
+ test.each([
+ ["schema.ts", SCHEMA, previousSchema],
+ ["schema.ts.bak", `${SCHEMA}.bak`, "// an older backup\n"],
+ ])(
+ "a symlinked %s is refused before anything is read or written, since introspect does not write through links",
+ async (_label, file, contents) => {
+ catalog = authorsOnly();
+ const root = tempApp({
+ [SCHEMA]: previousSchema,
+ "elsewhere/target.ts": contents,
+ });
+ const link = path.join(root, file);
+ fs.rmSync(link, { force: true });
+ fs.symlinkSync(path.join(root, "elsewhere/target.ts"), link);
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ `Refusing to introspect: config/database/${_label} is a symbolic link, and introspect replaces files instead of writing through links. Replace it with a regular file, then rerun.`,
+ );
+ expect(resolveEnvBranch).not.toHaveBeenCalled();
+ expect(catalog.calls).toEqual([]);
+ expect(fs.lstatSync(link).isSymbolicLink()).toBe(true);
+ expect(
+ fs.readFileSync(path.join(root, "elsewhere/target.ts"), "utf-8"),
+ ).toBe(contents);
+ expect(tree(root)).toEqual(before);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ },
+ );
+
+ test("--schema-name public is written explicitly, so the app never looks for the tables in the default app schema", async () => {
+ const root = tempApp();
+
+ const report = await runIntrospect(ctxFor(root), {
+ interactive: false,
+ importSource: BUILDER,
+ schemaName: "public",
+ });
+
+ expect(report.schemaName).toBe("public");
+ expect(fs.readFileSync(path.join(root, SCHEMA), "utf-8")).toContain(
+ '{ schemaName: "public" }',
+ );
+ expect((await loadDefaultDatabaseSchema(root)).$schemaName).toBe("public");
+ });
+
+ test("without --schema-name, the schema schema.ts declares is read", async () => {
+ catalog = authorsOnly();
+ const root = tempApp({
+ [SCHEMA]: previousSchema.replace("}));", '}), { schemaName: "sales" });'),
+ });
+
+ const report = await introspect(root);
+
+ expect(catalog.calls.every((call) => call.values[0] === "sales")).toBe(
+ true,
+ );
+ expect(report.schemaName).toBe("sales");
+ expect((await loadDefaultDatabaseSchema(root)).$schemaName).toBe("sales");
+ expect(markMigrationsApplied).toHaveBeenCalledWith(
+ pool,
+ { migrationsFolder: path.join(root, MIGRATIONS), schemaName: "sales" },
+ ["0000_baseline"],
+ );
+ });
+
+ test("--schema-name overrides the schema schema.ts declares, which then declares nothing in it", async () => {
+ const salesSchema = previousSchema
+ .replace("email: text()", "email: text().private()")
+ .replace("}));", '}), { schemaName: "sales" });');
+ const root = tempApp({ [SCHEMA]: salesSchema });
+
+ const report = await runIntrospect(ctxFor(root), {
+ interactive: false,
+ importSource: BUILDER,
+ schemaName: "app",
+ });
+
+ expect(catalog.calls.every((call) => call.values[0] === "app")).toBe(true);
+ expect(report.schemaName).toBe("app");
+ // sales.authors.email being private says nothing about app.authors.email.
+ const written = fs.readFileSync(path.join(root, SCHEMA), "utf-8");
+ expect(written).toContain("email: varchar(255).notNull().unique(),");
+ expect(written).toContain(
+ 'author_id: fk(() => authors.id).notNull().onDelete("cascade"),',
+ );
+ expect(fs.readFileSync(path.join(root, `${SCHEMA}.bak`), "utf-8")).toBe(
+ salesSchema,
+ );
+ expect((await loadDefaultDatabaseSchema(root)).$schemaName).toBe("app");
+ });
+
+ test("a foreign key the replaced schema.ts does not declare renders with fk(); its .private() is kept", async () => {
+ const root = tempApp({
+ [SCHEMA]: `import { defineSchema, id, integer, text } from ${JSON.stringify(BUILDER)};
+export const schema = defineSchema(({ table }) => ({
+ authors: table("authors", { id: id(), email: text().private() }),
+ posts: table("posts", { id: id(), author_id: integer().notNull() }),
+}));
+`,
+ });
+ await commitMigration(root);
+
+ const report = await introspect(root);
+
+ const written = fs.readFileSync(path.join(root, SCHEMA), "utf-8");
+ expect(written).toContain(
+ 'author_id: fk(() => authors.id).notNull().onDelete("cascade"),',
+ );
+ expect(written).toContain(
+ "email: varchar(255).notNull().unique().private(),",
+ );
+ expect(written).toContain(
+ "created_at: timestamp({ withTimezone: true }).notNull().defaultNow(),",
+ );
+ expect(report.migration?.tag).toBe("0001_introspect");
+ expect(report.migration?.statements.join("\n")).toContain(
+ 'ALTER TABLE "app"."posts" ADD CONSTRAINT "posts_author_id_authors_id_fk" FOREIGN KEY ("author_id") REFERENCES "app"."authors"("id") ON DELETE cascade',
+ );
+ expect(report.recorded).toEqual(["0001_introspect"]);
+ expect(
+ report.warnings.filter((warning) => warning.includes("private")),
+ ).toEqual([]);
+ });
+
+ test("an empty schema next to an existing schema.ts refuses before writing anything", async () => {
+ catalog = catalogResponder({
+ tables: [],
+ columns: [],
+ constraints: [],
+ indexes: [],
+ });
+ const root = tempApp({ [SCHEMA]: previousSchema });
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ 'Schema "app" on dev-alice-3f9a2c has no tables, so introspect would replace config/database/schema.ts with an empty one. Pass --schema-name to read another schema.',
+ );
+ expect(fs.readFileSync(path.join(root, SCHEMA), "utf-8")).toBe(
+ previousSchema,
+ );
+ expect(fs.existsSync(path.join(root, `${SCHEMA}.bak`))).toBe(false);
+ expect(fs.existsSync(path.join(root, MIGRATIONS))).toBe(false);
+ });
+
+ test("an empty schema without schema.ts still writes an empty one", async () => {
+ catalog = catalogResponder({
+ tables: [],
+ columns: [],
+ constraints: [],
+ indexes: [],
+ });
+ const root = tempApp();
+
+ const report = await introspect(root);
+
+ expect(report.tables).toEqual([]);
+ expect(report.migration).toBeNull();
+ expect(report.recorded).toEqual([]);
+ expect(fs.readFileSync(path.join(root, SCHEMA), "utf-8")).toContain(
+ "export const schema = defineSchema(() => ({}));",
+ );
+ });
+
+ test("without a configured branch it fails before writing", async () => {
+ resolveEnvBranch.mockResolvedValue(null);
+ const root = tempApp({ [SCHEMA]: previousSchema });
+
+ await expect(introspect(root)).rejects.toThrow(
+ "Did not introspect: no branch is configured in .env (PGHOST, PGDATABASE and LAKEBASE_ENDPOINT); run `appkit db init`.",
+ );
+ expect(fs.readFileSync(path.join(root, SCHEMA), "utf-8")).toBe(
+ previousSchema,
+ );
+ });
+
+ test("while another appkit db command changes the migration history, it refuses before reading the catalog", async () => {
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ const before = tree(root);
+
+ const error = await withHistoryLock(root, "migrate", () => refusal(root));
+
+ expect(error.message).toMatch(
+ /^Another `appkit db migrate` \(pid \d+ on .+\) is changing the migration history in config\/database\. /,
+ );
+ expect(catalog.calls).toEqual([]);
+ expect(tree(root)).toEqual(before);
+ });
+
+ test("with history, a branch that has not applied every committed migration refuses before reading the catalog", async () => {
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ await commitMigration(root);
+ // A teammate's migration, pulled but not applied on this branch yet.
+ fs.writeFileSync(
+ path.join(root, SCHEMA),
+ previousSchema.replace(
+ "email: text() }),",
+ 'email: text() }),\n tags: table("tags", { id: id() }),',
+ ),
+ );
+ await commitMigration(root, false);
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ 'Refusing to introspect dev-alice-3f9a2c: it has not applied 0001_migration in schema "app". The migration would undo it. Run `appkit db migrate` first.',
+ );
+ expect(catalog.calls).toEqual([]);
+ expect(tree(root)).toEqual(before);
+ });
+
+ test.each([
+ ["without history", false],
+ ["with history", true],
+ ])(
+ "a branch that records a migration the checkout lacks (%s) is refused before reading the catalog",
+ async (_label, history) => {
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ if (history) await commitMigration(root);
+ recorded.push({ when: Date.now() + 60_000, hash: "teammate" });
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ 'Refusing to introspect dev-alice-3f9a2c: it records 1 migration this checkout does not have in schema "app". Pull the latest config/database/migrations, then rerun.',
+ );
+ expect(catalog.calls).toEqual([]);
+ expect(tree(root)).toEqual(before);
+ },
+ );
+
+ test("a branch that skipped a committed migration is refused", async () => {
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ await commitMigration(root, false);
+ fs.writeFileSync(
+ path.join(root, SCHEMA),
+ previousSchema.replace("email: text() }", "email: text(), bio: text() }"),
+ );
+ await commitMigration(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ 'Refusing to introspect dev-alice-3f9a2c: it skipped 0000_migration in schema "app". Run `appkit db migrate`, which says how to fix it.',
+ );
+ });
+
+ test("a recorded migration whose committed file changed since is refused before reading the catalog", async () => {
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ await commitMigration(root);
+ fs.appendFileSync(
+ path.join(root, MIGRATIONS, "0000_migration.sql"),
+ '\n--> statement-breakpoint\nALTER TABLE "app"."authors" ADD COLUMN "bio" text;',
+ );
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ 'Refusing to introspect dev-alice-3f9a2c: it applied 0000_migration before its file changed in schema "app". Restore the file to what the branch ran and put the change in a new migration, or rebuild the branch with `appkit db clean`.',
+ );
+ expect(catalog.calls).toEqual([]);
+ expect(tree(root)).toEqual(before);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ });
+
+ test("with history and no schema.ts, an empty schema refuses instead of dropping every table", async () => {
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ await commitMigration(root);
+ fs.rmSync(path.join(root, SCHEMA));
+ catalog = catalogResponder({
+ tables: [],
+ columns: [],
+ constraints: [],
+ indexes: [],
+ });
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ 'Schema "app" on dev-alice-3f9a2c has no tables, so introspect would write a migration that drops every table. Pass --schema-name to read another schema.',
+ );
+ expect(tree(root)).toEqual(before);
+ });
+
+ test.each([
+ [
+ "a column it cannot declare",
+ previousSchema,
+ authorsOnly([columnRow("authors", "email", "numeric")]),
+ 'column app.authors.email (type "numeric" is not supported)',
+ ],
+ [
+ "a default it cannot declare",
+ previousSchema.replace("email: text()", 'email: text().default("x")'),
+ authorsOnly([
+ columnRow("authors", "email", "text", { default_expr: "lower('X')" }),
+ ]),
+ "the default of app.authors.email (default lower('X') is not supported)",
+ ],
+ [
+ "a table it cannot key",
+ previousSchema.replace(
+ "email: text() }),",
+ 'email: text() }),\n tags: table("tags", { id: id() }),',
+ ),
+ authorsOnly([columnRow("authors", "email", "text")], {
+ tables: [{ name: "tags", partitioned: false }],
+ columns: [columnRow("tags", "id", "integer", { not_null: true })],
+ }),
+ "table app.tags (it has no primary key)",
+ ],
+ [
+ "a column in the public schema",
+ previousSchema.replace("}));", '}), { schemaName: "public" });'),
+ authorsOnly([columnRow("authors", "email", "numeric")]),
+ 'column public.authors.email (type "numeric" is not supported)',
+ ],
+ [
+ "an enum type in the public schema",
+ `import { defineSchema, id } from ${JSON.stringify(BUILDER)};
+export const schema = defineSchema(
+ ({ table, enum: enumType }) => ({
+ authors: table("authors", { id: id(), mood: enumType("mood", ["a", "b"]) }),
+ }),
+ { schemaName: "public" },
+);
+`,
+ // Only a table introspect cannot key still uses the type.
+ authorsOnly([], {
+ tables: [{ name: "events", partitioned: false }],
+ columns: [
+ columnRow("events", "kind", "mood", {
+ type_kind: "e",
+ type_schema: "public",
+ type_name: "mood",
+ enum_values: ["a", "b"],
+ }),
+ ],
+ }),
+ "type public.mood (only what schema.ts leaves out uses it)",
+ ],
+ [
+ "a foreign key it cannot declare",
+ postsOfAuthors(),
+ setNullOnNotNull("app"),
+ "constraint posts_author_id_authors_id_fk of app.posts (foreign key to authors(id) is not kept: SET NULL on a NOT NULL column)",
+ ],
+ [
+ "a foreign key in the public schema",
+ postsOfAuthors('{ schemaName: "public" }'),
+ setNullOnNotNull("public"),
+ "constraint posts_author_id_authors_id_fk of public.posts (foreign key to authors(id) is not kept: SET NULL on a NOT NULL column)",
+ ],
+ ])(
+ "with history, a migration that drops %s the branch still has is refused and nothing changes",
+ async (_label, committed, branch, refused) => {
+ const root = tempApp({ [SCHEMA]: committed });
+ await commitMigration(root);
+ catalog = branch;
+ const before = tree(root);
+
+ const error = await rejection(
+ runIntrospect(ctxFor(root), {
+ interactive: false,
+ importSource: BUILDER,
+ schemaName: (await loadDefaultDatabaseSchema(root)).$schemaName,
+ }),
+ );
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ `Refusing to write a migration that drops what the branch still has but schema.ts cannot express: ${refused}. The deployed app would drop it on start.`,
+ );
+ expect(tree(root)).toEqual(before);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ },
+ );
+
+ test("with history, a skip elsewhere does not block dropping what the branch no longer has, which is recorded and warned about", async () => {
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ await commitMigration(root);
+ catalog = authorsOnly([], {
+ tables: [{ name: "events", partitioned: false }],
+ columns: [columnRow("events", "line", "text")],
+ });
+
+ const report = await introspect(root);
+
+ expect(report.skipped).toEqual([
+ { table: "events", reason: "it has no primary key" },
+ ]);
+ expect(report.migration?.tag).toBe("0001_introspect");
+ expect(report.migration?.statements).toEqual([
+ 'ALTER TABLE "app"."authors" DROP COLUMN "email";',
+ ]);
+ expect(report.recorded).toEqual(["0001_introspect"]);
+ expect(report.warnings).toEqual([
+ '0001_introspect breaks instances still running the previous release, which keep serving while the new one migrates on start: ALTER TABLE "app"."authors" DROP COLUMN "email";',
+ ]);
+ });
+
+ test("the warning about statements that break the previous release escapes catalog names", async () => {
+ const root = tempApp({
+ [SCHEMA]: previousSchema.replace("email: text()", '"e\\u2028x": text()'),
+ });
+ await commitMigration(root);
+ catalog = authorsOnly();
+
+ const report = await introspect(root);
+
+ expect(report.warnings).toEqual([
+ '0001_introspect breaks instances still running the previous release, which keep serving while the new one migrates on start: ALTER TABLE "app"."authors" DROP COLUMN "e\\u2028x";',
+ ]);
+ });
+
+ test("objects introspect does not read are named in a warning", async () => {
+ catalog = catalogResponder(undefined, [
+ "trigger audit on authors",
+ "view active_authors",
+ ]);
+ const root = tempApp();
+
+ const report = await introspect(root);
+
+ expect(report.warnings.at(-1)).toBe(
+ "Not read: trigger audit on authors, view active_authors. schema.ts and its migrations leave them out, so a database the migrations create will not have them.",
+ );
+ });
+
+ test.each([
+ [
+ "recording",
+ () =>
+ markMigrationsApplied.mockRejectedValueOnce(new Error("lock timeout")),
+ "lock timeout",
+ ],
+ [
+ "writing database.d.ts",
+ () => writeTypes.mockRejectedValueOnce(new Error("disk full")),
+ "disk full",
+ ],
+ ])(
+ "when %s fails, schema.ts, its backup, the generated types and the migrations are put back, so a rerun records",
+ async (_label, failOnce, message) => {
+ const root = tempApp({
+ [SCHEMA]: declaredSchema,
+ [`${SCHEMA}.bak`]: "// an older backup\n",
+ });
+ const before = tree(root);
+ failOnce();
+
+ const error = await refusal(root);
+
+ expect(error.message).toBe(`Introspect changed nothing: ${message}`);
+ expect(tree(root)).toEqual(before);
+ expect(fs.existsSync(path.join(root, MIGRATIONS))).toBe(false);
+ expect(fs.existsSync(path.join(root, TYPES))).toBe(false);
+ expect(fs.existsSync(path.join(root, OPERATION_TYPES))).toBe(false);
+ expect(recorded).toEqual([]);
+
+ const report = await introspect(root);
+ expect(report).toMatchObject({
+ migration: { tag: "0000_baseline" },
+ recorded: ["0000_baseline"],
+ });
+ },
+ );
+
+ test("a second run with the same catalog keeps the original .bak", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ await introspect(root);
+
+ const second = await introspect(root);
+
+ expect(second.backupFile).toBeNull();
+ expect(fs.readFileSync(path.join(root, `${SCHEMA}.bak`), "utf-8")).toBe(
+ declaredSchema,
+ );
+ });
+
+ test("when every table is skipped, an existing schema.ts is kept", async () => {
+ catalog = catalogResponder({
+ tables: [{ name: "logs", partitioned: false }],
+ columns: [columnRow("logs", "line", "text")],
+ constraints: [],
+ indexes: [],
+ });
+ const root = tempApp({ [SCHEMA]: previousSchema });
+ const before = tree(root);
+
+ const error = await refusal(root);
+
+ expect(error).toBeInstanceOf(IntrospectRefusedError);
+ expect(error.message).toBe(
+ 'Schema "app" on dev-alice-3f9a2c has no tables introspect can write (logs: it has no primary key), so introspect would replace config/database/schema.ts with an empty one. Pass --schema-name to read another schema.',
+ );
+ expect(tree(root)).toEqual(before);
+ });
+
+ test("a generated schema.ts that does not load is reported as a bug, and schema.ts is put back", async () => {
+ const root = tempApp({ [SCHEMA]: declaredSchema });
+ const before = tree(root);
+
+ const error = await rejection(
+ runIntrospect(ctxFor(root), {
+ interactive: false,
+ importSource: path.join(root, "missing-builder.ts"),
+ }),
+ );
+
+ expect(error.message).toBe(
+ 'Introspect changed nothing: The schema.ts introspect generated does not load. This is a bug in `appkit db introspect`; please report it with the catalog of schema "app".',
+ );
+ expect(tree(root)).toEqual(before);
+ expect(markMigrationsApplied).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts
new file mode 100644
index 000000000..a1003b3ad
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts
@@ -0,0 +1,992 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { describe, expect, test } from "vitest";
+
+import {
+ defineSchema,
+ fk as references,
+ id,
+ integer,
+ text,
+ uuid,
+} from "../../../schema-builder";
+import type { IntrospectedForeignKey, IntrospectedTable } from "../catalog";
+import { renderSchemaSource } from "../render";
+import { col, richTables, tableOf, uniqueKey } from "./fixture";
+
+const golden = (name: string) =>
+ fs.readFileSync(path.join(import.meta.dirname, "golden", name), "utf-8");
+
+const fk = (
+ column: string,
+ table: string,
+ extra: Partial = {},
+): IntrospectedForeignKey => ({
+ name: `${column}_fkey`,
+ columns: [column],
+ schema: "app",
+ table,
+ refColumns: ["id"],
+ onDelete: "no action",
+ onUpdate: "no action",
+ deferrable: false,
+ matchFull: false,
+ ...extra,
+});
+
+/** A table with an integer identity key plus the given columns and FKs. */
+const keyed = (
+ name: string,
+ columns: IntrospectedTable["columns"] = [],
+ foreignKeys: IntrospectedForeignKey[] = [],
+ unique: string[][] = [],
+): IntrospectedTable =>
+ tableOf({
+ name,
+ primaryKey: ["id"],
+ unique: unique.map((columns) => uniqueKey(name, ...columns)),
+ foreignKeys,
+ columns: [
+ col("id", "integer", { notNull: true, identity: "d" }),
+ ...columns,
+ ],
+ });
+
+/** A table with a uuid primary key plus the given columns and FKs. */
+const uuidKeyed = (
+ name: string,
+ columns: IntrospectedTable["columns"] = [],
+ foreignKeys: IntrospectedForeignKey[] = [],
+): IntrospectedTable =>
+ tableOf({
+ name,
+ primaryKey: ["id"],
+ foreignKeys,
+ columns: [col("id", "uuid", { notNull: true }), ...columns],
+ });
+
+const body = (source: string) =>
+ source.slice(source.indexOf("export const schema"));
+
+/** A render with no schema.ts to replace: builder defaults, nothing private. */
+const firstRender = (
+ tables: readonly IntrospectedTable[],
+ schemaName = "app",
+) => renderSchemaSource(tables, schemaName, { previous: null });
+
+describe("renderSchemaSource", () => {
+ test("golden: supported types, defaults, FKs and enums, with skip comments", () => {
+ const out = firstRender(richTables, "app");
+
+ expect(out.source).toBe(golden("rich.schema.ts.txt"));
+ expect(out.skipped).toEqual(
+ expect.arrayContaining([
+ {
+ table: "events",
+ reason: "composite primary key (a, b) is not supported",
+ },
+ { table: "logs", reason: "it has no primary key" },
+ {
+ table: "authors",
+ column: "score",
+ reason: 'type "numeric(10,2)" is not supported',
+ },
+ {
+ table: "posts",
+ column: "body",
+ reason: "default '{}'::jsonb is not supported",
+ },
+ {
+ table: "posts",
+ column: "views",
+ reason: "default 0 is not supported",
+ },
+ {
+ table: "posts",
+ column: "editor_id",
+ reason:
+ 'foreign key to authors(id) is not kept: a second foreign key to "authors" would make the relation ambiguous',
+ },
+ ]),
+ );
+ expect(out.skipped).toHaveLength(6);
+ });
+
+ test("a skipped NOT NULL column without a default is a loud warning", () => {
+ const { warnings } = firstRender(richTables, "app");
+ expect(warnings).toContain(
+ 'app.authors.score is NOT NULL with no default but is not in schema.ts (type "numeric(10,2)" is not supported). Inserts through app.database.authors will fail until it gets a default, becomes nullable, or is dropped.',
+ );
+ expect(warnings).toContain(
+ "app.posts.views: its default 0 is not in schema.ts, so app.database.posts requires a value for it on insert.",
+ );
+ expect(
+ warnings.filter((warning) => !warning.startsWith("Constraint names")),
+ ).toHaveLength(2);
+ });
+
+ test.each([
+ ["app", "export const schema = defineSchema(() => ({}));\n"],
+ [
+ "public",
+ 'export const schema = defineSchema(() => ({}), { schemaName: "public" });\n',
+ ],
+ ])(
+ "no tables in %s renders an empty schema, naming the schema only when it is not app",
+ (schemaName, expected) => {
+ expect(body(firstRender([], schemaName).source)).toBe(expected);
+ },
+ );
+
+ test("tables in a schema other than app pass it to defineSchema", () => {
+ expect(body(firstRender([keyed("notes")], "public").source)).toBe(
+ [
+ "export const schema = defineSchema(",
+ " ({ table }) => {",
+ ' const notes = table("notes", {',
+ " id: id(),",
+ " });",
+ "",
+ " return { notes };",
+ " },",
+ ' { schemaName: "public" },',
+ ");",
+ "",
+ ].join("\n"),
+ );
+ });
+
+ test("declares FK targets first, whatever the catalog order", () => {
+ const { source } = firstRender(
+ [
+ keyed("c", [col("b_id", "integer")], [fk("b_id", "b")]),
+ keyed("b", [col("a_id", "integer")], [fk("a_id", "a")]),
+ keyed("a"),
+ ],
+ "app",
+ );
+ const order = ["a", "b", "c"].map((name) =>
+ source.indexOf(`const ${name} = table`),
+ );
+ expect(order).toEqual([...order].sort((x, y) => x - y));
+ expect(source).toContain("return { a, b, c };");
+ });
+
+ test("FKs the builder cannot express stay plain columns, each with its reason", () => {
+ const cases: Array<[IntrospectedTable[], string]> = [
+ [
+ [keyed("t", [col("parent_id", "integer")], [fk("parent_id", "t")])],
+ "introspect does not write self-references",
+ ],
+ [
+ [
+ keyed("a", [col("b_id", "integer")], [fk("b_id", "b")]),
+ keyed("b", [col("a_id", "integer")], [fk("a_id", "a")]),
+ ],
+ "it would close a cycle of foreign keys",
+ ],
+ [
+ [
+ keyed(
+ "t",
+ [col("x", "integer"), col("y", "integer")],
+ [{ ...fk("x", "u"), columns: ["x", "y"], refColumns: ["id", "k"] }],
+ ),
+ keyed("u"),
+ ],
+ "foreign keys over several columns are not supported",
+ ],
+ [
+ [
+ keyed(
+ "t",
+ [col("u_id", "integer")],
+ [fk("u_id", "u", { schema: "public" })],
+ ),
+ keyed("u"),
+ ],
+ 'it references schema "public"',
+ ],
+ [
+ [
+ keyed(
+ "t",
+ [col("u_code", "integer")],
+ [fk("u_code", "u", { refColumns: ["code"] })],
+ ),
+ keyed("u", [col("code", "integer")]),
+ ],
+ "u.code is not a primary key or single-column unique key",
+ ],
+ [
+ [keyed("t", [col("u_id", "bigint")], [fk("u_id", "u")]), keyed("u")],
+ "its type bigint() differs from u.id",
+ ],
+ [
+ [
+ keyed(
+ "t",
+ [col("u_id", "integer", { notNull: true })],
+ [fk("u_id", "u", { onDelete: "set null" })],
+ ),
+ keyed("u"),
+ ],
+ "SET NULL on a NOT NULL column",
+ ],
+ [
+ [
+ keyed(
+ "t",
+ [col("u_id", "integer")],
+ [fk("u_id", "u", { onDelete: "set default" })],
+ ),
+ keyed("u"),
+ ],
+ "SET DEFAULT without a default",
+ ],
+ [
+ [
+ keyed(
+ "t",
+ [col("u_id", "integer"), col("u", "text")],
+ [fk("u_id", "u")],
+ ),
+ keyed("u"),
+ ],
+ 'the relation "u" would clash with the column of the same name',
+ ],
+ [
+ [
+ keyed("t", [col("u_id", "integer")], [fk("u_id", "u")]),
+ keyed("u", [col("t", "text")]),
+ ],
+ 'the reverse relation "t" would clash with column u.t',
+ ],
+ [
+ [
+ keyed("t", [col("u_id", "integer")], [fk("u_id", "u")]),
+ { ...keyed("u"), primaryKey: ["id", "x"] },
+ ],
+ 'table "u" is skipped',
+ ],
+ ];
+ for (const [tables, reason] of cases) {
+ const out = firstRender(tables, "app");
+ expect(out.source, reason).toContain(reason);
+ const fkSkips = out.skipped.filter((skip) =>
+ skip.reason.startsWith("foreign key"),
+ );
+ expect(fkSkips, reason).toHaveLength(1);
+ // Exactly one fk() survives only in the cycle case (the first edge).
+ expect(out.source.includes("fk(() =>"), reason).toBe(
+ reason.includes("cycle"),
+ );
+ }
+ });
+
+ test("an FK keeps NOT NULL, unique, a default and its actions", () => {
+ const { source } = firstRender(
+ [
+ keyed(
+ "t",
+ [col("u_id", "integer", { notNull: true, defaultExpr: "1" })],
+ [fk("u_id", "u", { onDelete: "set default", onUpdate: "cascade" })],
+ [["u_id"]],
+ ),
+ keyed("u"),
+ ],
+ "app",
+ );
+ expect(source).toContain(
+ 'u_id: fk(() => u.id).notNull().unique().default(1).onDelete("set default").onUpdate("cascade"),',
+ );
+ });
+
+ test.each([
+ ["identity", keyed, "integer"],
+ ["uuid", uuidKeyed, "uuid"],
+ ] as const)(
+ "a second foreign key on the same column (%s keys) is skipped, and the first is kept",
+ (_label, target, type) => {
+ const out = firstRender([
+ target("users"),
+ target("people"),
+ keyed(
+ "posts",
+ [col("author_id", type)],
+ [
+ fk("author_id", "users"),
+ fk("author_id", "people", { name: "posts_author_id_people_fkey" }),
+ ],
+ ),
+ ]);
+
+ expect(body(out.source)).toContain("author_id: fk(() => users.id),");
+ expect(out.skipped).toEqual([
+ {
+ table: "posts",
+ column: "author_id",
+ reason:
+ "foreign key to people(id) is not kept: its column already keeps the foreign key to users(id)",
+ },
+ ]);
+ },
+ );
+
+ test("a table whose primary key cannot be expressed is skipped whole", () => {
+ const out = firstRender(
+ [
+ tableOf({
+ name: "t",
+ primaryKey: ["code"],
+ unique: [],
+ foreignKeys: [],
+ columns: [
+ col("code", "smallint", { notNull: true }),
+ col("x", "numeric", { notNull: true }),
+ ],
+ }),
+ ],
+ "app",
+ );
+ expect(out.skipped).toEqual([
+ {
+ table: "t",
+ reason:
+ 'its primary key column "code" cannot be expressed (type "smallint" is not supported)',
+ },
+ ]);
+ // The table is gone, so its columns produce no warnings.
+ expect(out.warnings).toEqual([]);
+ });
+
+ test("names AppKit reserves are skipped; unusual names are quoted or renamed", () => {
+ const out = firstRender(
+ [
+ keyed("sql"),
+ keyed("my-table", [
+ col("$meta", "text"),
+ col("and", "text"),
+ col("select", "text"),
+ ]),
+ keyed("users"),
+ keyed("usersRelations"),
+ ],
+ "app",
+ );
+ expect(
+ out.skipped.map((skip) => [skip.table, skip.column ?? null, skip.reason]),
+ ).toEqual([
+ ["sql", null, 'the name "sql" is reserved by AppKit'],
+ [
+ "usersRelations",
+ null,
+ 'the name collides with the relation metadata AppKit generates for "users"',
+ ],
+ ["my-table", "$meta", 'the name "$meta" is reserved by AppKit'],
+ ["my-table", "and", 'the name "and" is reserved by AppKit'],
+ ]);
+ expect(out.source).toContain('const my_table = table("my-table", {');
+ expect(out.source).toContain(" select: text(),");
+ expect(out.source).toContain('return { "my-table": my_table, users };');
+ });
+
+ test("unsupported defaults are dropped with a comment; nextval on a key becomes id()", () => {
+ const { source, skipped } = firstRender(
+ [
+ tableOf({
+ name: "t",
+ primaryKey: ["id"],
+ unique: [],
+ foreignKeys: [],
+ columns: [
+ col("id", "bigint", {
+ notNull: true,
+ defaultExpr: "nextval('t_id_seq'::regclass)",
+ }),
+ col("code", "character varying(2)", {
+ defaultExpr: "'toolong'::character varying",
+ }),
+ col("at", "timestamp without time zone", {
+ defaultExpr: "'2020-01-01 00:00:00'::timestamp without time zone",
+ }),
+ col("n", "integer", { defaultExpr: "nextval('n_seq'::regclass)" }),
+ ],
+ }),
+ ],
+ "app",
+ );
+ expect(source).toContain(" id: bigid(),");
+ expect(skipped.map((skip) => skip.column)).toEqual(["code", "at", "n"]);
+ expect(source).toContain(" code: varchar(2),");
+ });
+
+ test("a literal default cast to a quoted type name keeps its value", () => {
+ const { source, skipped } = firstRender([
+ keyed("t", [
+ col("status", 'app."order-status"', {
+ notNull: true,
+ defaultExpr: `'open'::app."order-status"`,
+ enum: {
+ name: "order-status",
+ schema: "app",
+ values: ["open", "closed"],
+ },
+ }),
+ col("etat", 'app."état"', {
+ defaultExpr: `'ouvert'::app."état"`,
+ enum: { name: "état", schema: "app", values: ["ouvert", "fermé"] },
+ }),
+ ]),
+ ]);
+
+ expect(source).toContain(
+ ' status: enumType("order-status", ["open", "closed"]).notNull().default("open"),',
+ );
+ expect(source).toContain(
+ ' etat: enumType("état", ["ouvert", "fermé"]).default("ouvert"),',
+ );
+ expect(skipped).toEqual([]);
+ });
+
+ test("an enum with an empty label is skipped, since the builder does not accept it", () => {
+ const out = firstRender([
+ keyed("t", [
+ col("mood", "app.mood", {
+ notNull: true,
+ enum: { name: "mood", schema: "app", values: ["", "ok"] },
+ }),
+ ]),
+ ]);
+
+ expect(out.skipped).toEqual([
+ {
+ table: "t",
+ column: "mood",
+ reason:
+ 'enum type "mood" has an empty label, which the builder does not accept',
+ },
+ ]);
+ expect(out.unexpressed).toContainEqual({
+ kind: "type",
+ name: "mood",
+ reason: "only what schema.ts leaves out uses it",
+ });
+ expect(out.warnings).toEqual([
+ expect.stringMatching(/^app\.t\.mood is NOT NULL with no default/),
+ ]);
+ });
+
+ test("a catalog name with a line break stays inside its comment", () => {
+ const evil = "x\nrequire('node:child_process').execSync('touch /tmp/p')//";
+ const { source, skipped, warnings } = firstRender(
+ [
+ keyed("t", [
+ col(evil, "numeric", { notNull: true }),
+ col("y\u2028z", "numeric"),
+ ]),
+ ],
+ "app",
+ );
+ for (const line of source.split("\n")) {
+ expect(line.trimStart().startsWith("require(")).toBe(false);
+ }
+ expect(source).not.toMatch(/[\u2028\u2029]/);
+ expect(source).toContain(
+ `// appkit: skipped column "x\\u000arequire('node:child_process').execSync('touch /tmp/p')//": type "numeric" is not supported`,
+ );
+ expect(source).toContain(
+ '// appkit: skipped column "y\\u2028z": type "numeric" is not supported',
+ );
+ expect(skipped.map((skip) => skip.column)).toEqual([
+ "x\\u000arequire('node:child_process').execSync('touch /tmp/p')//",
+ "y\\u2028z",
+ ]);
+ expect(warnings[0]).toMatch(/^app\.t\.x\\u000arequire/);
+ });
+
+ test("the schema name in the header comment is escaped too", () => {
+ const { source } = firstRender([keyed("t")], "a\nb");
+ expect(source.split("\n")[0]).toBe(
+ '// Generated by `appkit db introspect` from schema "a\\u000ab". Edit tables here,',
+ );
+ expect(source).toContain('{ schemaName: "a\\nb" }');
+ });
+
+ test("returns the tables it wrote", () => {
+ expect(firstRender(richTables, "app").tables).toEqual([
+ "authors",
+ "posts",
+ "default",
+ ]);
+ });
+
+ test("what schema.ts declares differently from the database is approximated; CHECK, EXCLUDE and indexes it cannot declare are warnings", () => {
+ const { approximated, warnings } = firstRender(
+ [
+ tableOf({
+ name: "a",
+ partitioned: true,
+ primaryKey: ["id"],
+ checks: ["a_n_check"],
+ indexes: ["a_n_idx", "a_m_idx"],
+ unique: [{ name: "a_n_unique", columns: ["n"], deferrable: true }],
+ columns: [
+ col("id", "integer", {
+ notNull: true,
+ identity: "a",
+ sequence: {
+ start: "100",
+ increment: "10",
+ min: "1",
+ max: "2147483647",
+ cache: "1",
+ cycle: false,
+ },
+ }),
+ col("n", "character varying"),
+ col("at", "timestamp(3) with time zone"),
+ ],
+ }),
+ keyed(
+ "b",
+ [col("a_id", "integer")],
+ [
+ fk("a_id", "a", {
+ name: "b_a_id_a_id_fk",
+ deferrable: true,
+ matchFull: true,
+ }),
+ ],
+ ),
+ ],
+ "app",
+ );
+ expect(approximated).toEqual([
+ "app.a.id: GENERATED ALWAYS AS IDENTITY is declared as id(), an identity generated BY DEFAULT",
+ "app.a.id: the key's sequence has START WITH 100, INCREMENT BY 10; id() declares the defaults (START WITH 1, INCREMENT BY 1)",
+ "app.a.n: character varying without a length is declared as text()",
+ "app.a.n: the unique constraint is declared without DEFERRABLE",
+ "app.a.at: timestamp(3) with time zone is declared without its precision",
+ "app.a: a partitioned table is declared as a plain table",
+ "app.b.a_id: the foreign key is declared without DEFERRABLE",
+ "app.b.a_id: the foreign key is declared without MATCH FULL",
+ ]);
+ expect(warnings).toEqual(
+ expect.arrayContaining([
+ "app.a: CHECK or EXCLUDE constraint a_n_check is not in schema.ts, so a database the migrations create will not have it.",
+ "app.a: indexes a_n_idx, a_m_idx are not in schema.ts, so a database the migrations create will not have them.",
+ ]),
+ );
+ });
+
+ test("a key whose sequence has the default options is exact; other bounds and CYCLE are approximated", () => {
+ const defaults = {
+ start: "1",
+ increment: "1",
+ min: "1",
+ max: "9223372036854775807",
+ cache: "1",
+ cycle: false,
+ };
+ const bigKey = (name: string, sequence: typeof defaults) =>
+ tableOf({
+ name,
+ primaryKey: ["id"],
+ columns: [
+ col("id", "bigint", { notNull: true, identity: "d", sequence }),
+ ],
+ });
+
+ const { approximated } = firstRender([
+ bigKey("a", defaults),
+ bigKey("b", { ...defaults, max: "1000", cycle: true }),
+ ]);
+
+ expect(approximated).toEqual([
+ "app.b.id: the key's sequence has MAXVALUE 1000, CYCLE; bigid() declares the defaults (MAXVALUE 9223372036854775807, NO CYCLE)",
+ ]);
+ });
+
+ test("constraint names that differ from the ones migrations use are one warning", () => {
+ const { warnings } = firstRender(richTables, "app");
+ expect(warnings).toContain(
+ "Constraint names differ from the ones migrations use: authors_email_key (authors_email_unique), posts_author_id_fkey (posts_author_id_authors_id_fk). A later migration that drops or changes one of them fails until it is renamed in the database (ALTER TABLE … RENAME CONSTRAINT).",
+ );
+ });
+
+ test("constraint names migrations would use raise no warning", () => {
+ const { warnings } = firstRender(
+ [
+ tableOf({
+ ...keyed("u", [col("email", "text")]),
+ unique: [
+ { name: "u_email_unique", columns: ["email"], deferrable: false },
+ ],
+ }),
+ keyed(
+ "t",
+ [col("u_id", "integer")],
+ [fk("u_id", "u", { name: "t_u_id_u_id_fk" })],
+ ),
+ ],
+ "app",
+ );
+ expect(warnings).toEqual([]);
+ });
+
+ test("migrations' constraint names are cut at 63 bytes, as Postgres cuts them", () => {
+ const column = "ç".repeat(40);
+ const { warnings } = firstRender(
+ [
+ tableOf({
+ ...keyed("t", [col(column, "text")]),
+ // "t_" plus 30 two-byte characters is 62 bytes; one more would pass 63.
+ unique: [
+ {
+ name: `t_${"ç".repeat(30)}`,
+ columns: [column],
+ deferrable: false,
+ },
+ ],
+ }),
+ ],
+ "app",
+ );
+ expect(warnings).toEqual([]);
+ });
+
+ test("bidi and line-separator characters are escaped in string literals", () => {
+ const name = "t\u202e\u2066\u061c\u2028x";
+ const { source } = firstRender([keyed(name)], "app");
+ expect(source).not.toMatch(/[\u2028\u202e\u2066\u061c]/);
+ expect(source).toContain('table("t\\u202e\\u2066\\u061c\\u2028x", {');
+ });
+
+ test("what schema.ts leaves out is listed by raw name, for the drop check", () => {
+ const status = { name: "status", schema: "app", values: ["a"] };
+ const { unexpressed } = firstRender(
+ [
+ keyed(
+ "t",
+ [
+ col("n", "numeric"),
+ col("s", "app.status", { generated: true, enum: status }),
+ col("d", "text", { defaultExpr: "lower('X')" }),
+ col("x", "integer"),
+ col("y", "integer"),
+ col("p", "integer"),
+ ],
+ [fk("p", "t")],
+ [["x", "y"]],
+ ),
+ tableOf({ name: "logs", columns: [col("line", "text")] }),
+ ],
+ "app",
+ );
+ expect(unexpressed).toEqual([
+ { kind: "table", name: "logs", reason: "it has no primary key" },
+ {
+ kind: "constraint",
+ name: "t",
+ member: "t_x_y_key",
+ reason:
+ "unique constraint (x, y) spans several columns, which is not supported",
+ },
+ {
+ kind: "column",
+ name: "t",
+ member: "n",
+ reason: 'type "numeric" is not supported',
+ },
+ {
+ kind: "column",
+ name: "t",
+ member: "s",
+ reason: "generated columns are not supported",
+ },
+ {
+ kind: "default",
+ name: "t",
+ member: "d",
+ reason: "default lower('X') is not supported",
+ },
+ ...["p_fkey", "t_p_t_id_fk"].map((member) => ({
+ kind: "constraint",
+ name: "t",
+ member,
+ reason:
+ "foreign key to t(id) is not kept: introspect does not write self-references",
+ })),
+ {
+ kind: "type",
+ name: "status",
+ reason: "only what schema.ts leaves out uses it",
+ },
+ ]);
+ });
+
+ test("a uuid FK keeps the key and skips gen_random_uuid(), which fk() does not take", () => {
+ const { source, skipped, warnings } = firstRender(
+ [
+ tableOf({
+ name: "u",
+ primaryKey: ["id"],
+ columns: [
+ col("id", "uuid", {
+ notNull: true,
+ defaultExpr: "gen_random_uuid()",
+ }),
+ ],
+ }),
+ keyed(
+ "t",
+ [
+ col("u_id", "uuid", {
+ notNull: true,
+ defaultExpr: "gen_random_uuid()",
+ }),
+ ],
+ [fk("u_id", "u", { name: "t_u_id_u_id_fk" })],
+ ),
+ ],
+ "app",
+ );
+ expect(source).toContain(" u_id: fk(() => u.id).notNull(),");
+ expect(source).not.toContain("fk(() => u.id).notNull().defaultRandom()");
+ expect(skipped).toEqual([
+ {
+ table: "t",
+ column: "u_id",
+ reason:
+ "default gen_random_uuid() is not supported on a foreign key column",
+ },
+ ]);
+ expect(warnings).toEqual([
+ "app.t.u_id: its default gen_random_uuid() is not in schema.ts, so app.database.t requires a value for it on insert.",
+ ]);
+ });
+
+ test("SET DEFAULT needs a default fk() can take", () => {
+ const { skipped } = firstRender(
+ [
+ tableOf({
+ name: "u",
+ primaryKey: ["id"],
+ columns: [col("id", "uuid", { notNull: true })],
+ }),
+ keyed(
+ "t",
+ [col("u_id", "uuid", { defaultExpr: "gen_random_uuid()" })],
+ [fk("u_id", "u", { onDelete: "set default" })],
+ ),
+ ],
+ "app",
+ );
+ expect(skipped.map((skip) => skip.reason)).toEqual([
+ "foreign key to u(id) is not kept: SET DEFAULT without a default the builder can express",
+ ]);
+ });
+});
+
+describe("renderSchemaSource over the schema.ts it replaces", () => {
+ const previous = defineSchema(({ table }) => {
+ const boards = table("boards", { id: id(), title: text().notNull() });
+ const notes = table("notes", {
+ id: id(),
+ board_id: references(() => boards.id).notNull(),
+ author_email: text().private(),
+ body: text().notNull(),
+ });
+ return { boards, notes };
+ });
+ const boards = keyed("boards", [col("title", "text", { notNull: true })]);
+ const notes = (
+ columns: IntrospectedTable["columns"] = [],
+ foreignKeys = [fk("board_id", "boards")],
+ ) =>
+ keyed(
+ "notes",
+ [
+ col("board_id", "integer", { notNull: true }),
+ col("author_email", "text"),
+ col("body", "text", { notNull: true }),
+ ...columns,
+ ],
+ foreignKeys,
+ );
+
+ /** Warnings other than the constraint-name one the fixture's `_fkey` names raise. */
+ const otherWarnings = (warnings: readonly string[]) =>
+ warnings.filter((warning) => !warning.startsWith("Constraint names"));
+
+ test("a declared column keeps its .private(); a new column and a new table render as the catalog has them", () => {
+ const out = renderSchemaSource(
+ [
+ boards,
+ notes([col("summary", "text")]),
+ keyed("tags", [col("label", "text")]),
+ ],
+ "app",
+ { previous },
+ );
+
+ expect(body(out.source)).toBe(
+ [
+ "export const schema = defineSchema(({ table }) => {",
+ ' const boards = table("boards", {',
+ " id: id(),",
+ " title: text().notNull(),",
+ " });",
+ "",
+ ' const notes = table("notes", {',
+ " id: id(),",
+ " board_id: fk(() => boards.id).notNull(),",
+ " author_email: text().private(),",
+ " body: text().notNull(),",
+ " summary: text(),",
+ " });",
+ "",
+ ' const tags = table("tags", {',
+ " id: id(),",
+ " label: text(),",
+ " });",
+ "",
+ " return { boards, notes, tags };",
+ "});",
+ "",
+ ].join("\n"),
+ );
+ expect(otherWarnings(out.warnings)).toEqual([]);
+ });
+
+ test("a foreign key it declares stays, and one the catalog dropped needs nothing", () => {
+ const kept = renderSchemaSource([boards, notes()], "app", { previous });
+ expect(kept.source).toContain("board_id: fk(() => boards.id).notNull(),");
+
+ const dropped = renderSchemaSource([boards, notes([], [])], "app", {
+ previous,
+ });
+ expect(dropped.source).toContain("board_id: integer().notNull(),");
+ });
+
+ test("a foreign key it does not declare renders with fk(), like a declared one", () => {
+ const plain = defineSchema(({ table }) => ({
+ boards: table("boards", { id: id(), title: text().notNull() }),
+ notes: table("notes", {
+ id: id(),
+ board_id: integer().notNull(),
+ author_email: text().private(),
+ body: text().notNull(),
+ }),
+ }));
+
+ const out = renderSchemaSource(
+ [
+ boards,
+ notes(
+ [col("reviewer_id", "integer")],
+ [fk("board_id", "boards"), fk("reviewer_id", "users")],
+ ),
+ keyed("users"),
+ keyed("tags", [col("note_id", "integer")], [fk("note_id", "notes")]),
+ ],
+ "app",
+ { previous: plain },
+ );
+
+ expect(out.source).toContain("board_id: fk(() => boards.id).notNull(),");
+ expect(out.source).toContain("reviewer_id: fk(() => users.id),");
+ expect(out.source).toContain("note_id: fk(() => notes.id),");
+ expect(out.source).toContain("author_email: text().private(),");
+ expect(out.skipped).toEqual([]);
+ expect(otherWarnings(out.warnings)).toEqual([]);
+ });
+
+ test("a declared foreign key keeps its relation when an undeclared one targets the same table", () => {
+ const declared = defineSchema(({ table }) => {
+ const users = table("users", { id: id() });
+ const posts = table("posts", {
+ id: id(),
+ author_id: integer(),
+ editor_id: references(() => users.id),
+ });
+ return { users, posts };
+ });
+
+ const out = renderSchemaSource(
+ [
+ keyed("users"),
+ keyed(
+ "posts",
+ [col("author_id", "integer"), col("editor_id", "integer")],
+ [fk("author_id", "users"), fk("editor_id", "users")],
+ ),
+ ],
+ "app",
+ { previous: declared },
+ );
+
+ expect(out.source).toContain("editor_id: fk(() => users.id),");
+ expect(out.source).toContain("author_id: integer(),");
+ expect(out.skipped.map((skip) => skip.reason)).toContain(
+ 'foreign key to users(id) is not kept: a second foreign key to "users" would make the relation ambiguous',
+ );
+ });
+
+ test("of two foreign keys on one column, the one it declares is kept", () => {
+ const declared = defineSchema(({ table }) => {
+ const people = table("people", { id: uuid().primaryKey() });
+ const posts = table("posts", {
+ id: id(),
+ author_id: references(() => people.id),
+ });
+ return { people, posts };
+ });
+
+ const out = renderSchemaSource(
+ [
+ uuidKeyed("users"),
+ uuidKeyed("people"),
+ keyed(
+ "posts",
+ [col("author_id", "uuid")],
+ [
+ fk("author_id", "users"),
+ fk("author_id", "people", { name: "posts_author_id_people_fkey" }),
+ ],
+ ),
+ ],
+ "app",
+ { previous: declared },
+ );
+
+ expect(body(out.source)).toContain("author_id: fk(() => people.id),");
+ expect(out.skipped.map((skip) => skip.reason)).toEqual([
+ "foreign key to users(id) is not kept: its column already keeps the foreign key to people(id)",
+ ]);
+ });
+
+ test("a declaration of another schema keeps nothing: its .private() does not carry over", () => {
+ const out = renderSchemaSource(
+ [
+ keyed("boards", [col("title", "text", { notNull: true })]),
+ notes([], [fk("board_id", "boards", { schema: "sales" })]),
+ ],
+ "sales",
+ { previous },
+ );
+
+ expect(out.source).toContain("author_email: text(),");
+ expect(out.source).toContain("board_id: fk(() => boards.id).notNull(),");
+ expect(out.source).not.toContain(".private()");
+ expect(otherWarnings(out.warnings)).toEqual([]);
+ });
+
+ test("without a schema.ts to replace, nothing is private", () => {
+ const out = firstRender([boards, notes()]);
+
+ expect(out.source).not.toContain(".private()");
+ });
+});
diff --git a/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts
new file mode 100644
index 000000000..a5d06f9ac
--- /dev/null
+++ b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts
@@ -0,0 +1,552 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { getTableConfig, type PgTable } from "drizzle-orm/pg-core";
+import { afterEach, describe, expect, test } from "vitest";
+
+import { loadDefaultDatabaseSchema } from "../../../../plugins/database/load-schema";
+import type { Schema } from "../../../schema-builder/types";
+import { drizzleKitImports } from "../../drizzle-exports";
+import { withHistoryLock } from "../../history-lock";
+import { generateMigrationFiles } from "../../migrations";
+import type { IntrospectedTable } from "../catalog";
+import { renderSchemaSource } from "../render";
+import {
+ BUILDER,
+ col,
+ foreignKey,
+ richTables,
+ tableOf,
+ uniqueKey,
+} from "./fixture";
+
+const roots: string[] = [];
+afterEach(() => {
+ for (const root of roots.splice(0))
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+/** Write the source as an app's schema.ts and load it the way the plugin does. */
+async function loadSource(source: string) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-introspect-"));
+ roots.push(root);
+ const file = path.join(root, "config/database/schema.ts");
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, source);
+ return { root, schema: await loadDefaultDatabaseSchema(root) };
+}
+
+/** Render the tables as a first schema.ts and load it. */
+const load = (tables: IntrospectedTable[]) =>
+ loadSource(
+ renderSchemaSource(tables, "app", { importSource: BUILDER, previous: null })
+ .source,
+ );
+
+interface KitColumn {
+ name: string;
+ type: string;
+ notNull: boolean;
+ primaryKey: boolean;
+ default?: unknown;
+}
+interface KitTable {
+ name: string;
+ schema: string;
+ columns: Record;
+ foreignKeys: Record<
+ string,
+ {
+ tableTo: string;
+ columnsFrom: string[];
+ columnsTo: string[];
+ onDelete?: string;
+ }
+ >;
+ uniqueConstraints: Record;
+}
+
+interface TableShape {
+ /** Column name to "type[ not null][ pk][ default ]". */
+ columns: Record;
+ unique: string[][];
+ /** " -> ()[ on delete ]". */
+ foreignKeys: string[];
+ private: string[];
+}
+
+/** What the schema declares per table, as drizzle-kit sees it, plus which columns are private. */
+async function shape(schema: Schema): Promise> {
+ const { generateDrizzleJson } = await import("drizzle-kit/api");
+ const snapshot = generateDrizzleJson(drizzleKitImports(schema), undefined, [
+ schema.$schemaName,
+ ]) as unknown as { tables: Record };
+ return Object.fromEntries(
+ Object.values(schema.$tables).map((table): [string, TableShape] => {
+ const kit = snapshot.tables[
+ `${schema.$schemaName}.${table.$name}`
+ ] as KitTable;
+ return [
+ table.$name,
+ {
+ columns: Object.fromEntries(
+ Object.values(kit.columns).map((c) => [
+ c.name,
+ `${c.type}${c.notNull ? " not null" : ""}${c.primaryKey ? " pk" : ""}${c.default === undefined ? "" : ` default ${String(c.default)}`}`,
+ ]),
+ ),
+ unique: Object.values(kit.uniqueConstraints).map((u) => u.columns),
+ foreignKeys: Object.values(kit.foreignKeys).map(
+ (fk) =>
+ `${fk.columnsFrom.join(", ")} -> ${fk.tableTo}(${fk.columnsTo.join(", ")})${fk.onDelete && fk.onDelete !== "no action" ? ` on delete ${fk.onDelete}` : ""}`,
+ ),
+ private: Object.values(table.$columns)
+ .filter((c) => c.isPrivate)
+ .map((c) => c.columnName),
+ },
+ ];
+ }),
+ );
+}
+
+describe("introspect round trip", () => {
+ test("the rendered source loads through loadDefaultDatabaseSchema, and drizzle-kit sees the same tables", async () => {
+ const { schema } = await load(richTables);
+ expect(schema.$schemaName).toBe("app");
+ expect(Object.keys(schema.$tables).sort()).toEqual([
+ "authors",
+ "default",
+ "posts",
+ ]);
+
+ const { generateDrizzleJson } = await import("drizzle-kit/api");
+ const snapshot = generateDrizzleJson(drizzleKitImports(schema), undefined, [
+ "app",
+ ]) as unknown as {
+ tables: Record;
+ enums: Record;
+ };
+ const columns = (table: string) =>
+ Object.fromEntries(
+ Object.values(snapshot.tables[`app.${table}`]?.columns ?? {}).map(
+ (c) => [
+ c.name,
+ `${c.type}${c.notNull ? " not null" : ""}${c.primaryKey ? " pk" : ""}`,
+ ],
+ ),
+ );
+
+ expect(columns("authors")).toEqual({
+ id: "integer not null pk",
+ email: "varchar(255) not null",
+ bio: "text",
+ active: "boolean not null",
+ rank: "integer",
+ created_at: "timestamp with time zone not null",
+ seen_at: "timestamp",
+ });
+ expect(columns("posts")).toEqual({
+ id: "uuid not null pk",
+ author_id: "integer not null",
+ editor_id: "integer",
+ status: "ticket_status not null",
+ body: "jsonb",
+ views: "bigint not null",
+ "my col": "text",
+ });
+ expect(columns("default")).toEqual({ id: "bigint not null pk" });
+ expect(
+ Object.values(snapshot.tables["app.posts"]?.foreignKeys ?? {}),
+ ).toEqual([
+ expect.objectContaining({
+ tableTo: "authors",
+ columnsFrom: ["author_id"],
+ columnsTo: ["id"],
+ onDelete: "cascade",
+ }),
+ ]);
+ expect(snapshot.enums["app.ticket_status"]).toMatchObject({
+ values: ["open", "closed"],
+ });
+ });
+
+ test("the baseline is generated from the empty snapshot: it creates every rendered table", async () => {
+ const { root, schema } = await load(richTables);
+ const migration = await withHistoryLock(root, "migrate", (lock) =>
+ generateMigrationFiles(lock, {
+ schema,
+ tag: "baseline",
+ interactive: false,
+ }),
+ );
+
+ expect(migration?.tag).toBe("0000_baseline");
+ const sql = migration?.statements.join("\n") ?? "";
+ for (const table of ["authors", "posts", "default"]) {
+ expect(sql).toContain(`CREATE TABLE "app"."${table}"`);
+ }
+ expect(sql).toContain(
+ `CREATE TYPE "app"."ticket_status" AS ENUM('open', 'closed')`,
+ );
+ expect(sql).not.toContain("CREATE SCHEMA");
+ });
+
+ test("every skip path still yields a loadable schema", async () => {
+ const tables: IntrospectedTable[] = [
+ tableOf({
+ name: "a",
+ primaryKey: ["id"],
+ unique: [uniqueKey("a", "x", "y")],
+ foreignKeys: [
+ foreignKey({
+ name: "self",
+ columns: ["parent_id"],
+ schema: "app",
+ table: "a",
+ refColumns: ["id"],
+ onDelete: "no action",
+ onUpdate: "no action",
+ }),
+ foreignKey({
+ name: "to_b",
+ columns: ["b_id"],
+ schema: "app",
+ table: "b",
+ refColumns: ["id"],
+ onDelete: "set null",
+ onUpdate: "no action",
+ }),
+ ],
+ columns: [
+ col("id", "integer", { notNull: true, identity: "a" }),
+ col("parent_id", "integer"),
+ col("b_id", "integer", { notNull: true }),
+ col("x", "integer"),
+ col("y", "integer"),
+ col("g", "integer", { generated: true, defaultExpr: "(x + y)" }),
+ col("seq", "integer", { identity: "d" }),
+ col("tags", "text[]"),
+ col("mood", "app.mood", {
+ enum: { name: "mood", schema: "app", values: ["", "ok"] },
+ }),
+ ],
+ }),
+ tableOf({
+ name: "b",
+ primaryKey: ["id"],
+ unique: [],
+ foreignKeys: [
+ foreignKey({
+ name: "to_a",
+ columns: ["a_id"],
+ schema: "app",
+ table: "a",
+ refColumns: ["id"],
+ onDelete: "no action",
+ onUpdate: "no action",
+ }),
+ ],
+ columns: [
+ col("id", "integer", { notNull: true, identity: "d" }),
+ col("a_id", "integer"),
+ ],
+ }),
+ ];
+ const { schema } = await load(tables);
+ expect(Object.keys(schema.$tables).sort()).toEqual(["a", "b"]);
+ expect(Object.keys(schema.$tables.a?.$columns ?? {})).toEqual([
+ "id",
+ "parent_id",
+ "b_id",
+ "x",
+ "y",
+ ]);
+ });
+
+ test("a uuid FK with gen_random_uuid() and names with line breaks still load, with no extra code", async () => {
+ const marker = "__introspect_injected__";
+ const { schema } = await load([
+ tableOf({
+ name: "u",
+ primaryKey: ["id"],
+ columns: [
+ col("id", "uuid", {
+ notNull: true,
+ defaultExpr: "gen_random_uuid()",
+ }),
+ ],
+ }),
+ tableOf({
+ name: "t",
+ primaryKey: ["id"],
+ foreignKeys: [
+ foreignKey({
+ name: "t_u_id_fkey",
+ columns: ["u_id"],
+ schema: "app",
+ table: "u",
+ refColumns: ["id"],
+ onDelete: "no action",
+ onUpdate: "no action",
+ }),
+ ],
+ columns: [
+ col("id", "integer", { notNull: true, identity: "d" }),
+ col("u_id", "uuid", {
+ notNull: true,
+ defaultExpr: "gen_random_uuid()",
+ }),
+ col(`x\nglobalThis.${marker} = true; //`, "numeric"),
+ col(`y\u2028globalThis.${marker} = true; //`, "numeric"),
+ ],
+ }),
+ ]);
+
+ expect((globalThis as Record)[marker]).toBeUndefined();
+ expect(Object.keys(schema.$tables).sort()).toEqual(["t", "u"]);
+ expect(Object.keys(schema.$tables.t?.$columns ?? {})).toEqual([
+ "id",
+ "u_id",
+ ]);
+ });
+
+ test("hostile names reach every place render writes them and load back unchanged, with no code run", async () => {
+ const marker = "__introspect_hostile__";
+ const payload = `globalThis.${marker} = true; //`;
+ const [
+ lf,
+ cr,
+ ls,
+ ps,
+ quote,
+ apostrophe,
+ backslash,
+ backtick,
+ bidi,
+ close,
+ ] = [
+ `lf\n${payload}`,
+ `cr\r${payload}`,
+ `ls\u2028${payload}`,
+ `ps\u2029${payload}`,
+ `q"]; ${payload}`,
+ `s'); ${payload}`,
+ `b\\"; ${payload}`,
+ `t\`\${globalThis.${marker} = true}\``,
+ "bidi\u202e\u2066x",
+ `*/ ${payload}`,
+ ];
+ const texts = [lf, cr, ls, ps, apostrophe, backslash, backtick, bidi];
+ const literal = (value: string) => `'${value.replace(/'/g, "''")}'::text`;
+ const kind = { name: close, schema: "app", values: [quote, cr, bidi] };
+ const level = { name: "level", schema: "app", values: [ls, bidi] };
+ const tables = [
+ tableOf({
+ name: "target",
+ primaryKey: [quote],
+ columns: [col(quote, "integer", { notNull: true, identity: "d" })],
+ }),
+ tableOf({
+ name: "source",
+ primaryKey: ["id"],
+ foreignKeys: [
+ foreignKey({
+ name: apostrophe,
+ columns: [backslash],
+ schema: "app",
+ table: "target",
+ refColumns: [quote],
+ onDelete: "no action",
+ onUpdate: "no action",
+ }),
+ ],
+ columns: [
+ col("id", "integer", { notNull: true, identity: "d" }),
+ col(backslash, "integer", { notNull: true }),
+ ...texts.map((name) =>
+ col(`c ${name}`, "text", { defaultExpr: literal(name) }),
+ ),
+ col("kind", `app."${close}"`, { enum: kind }),
+ col("level", "app.level", {
+ defaultExpr: `'${bidi}'::app.level`,
+ enum: level,
+ }),
+ ...[lf, cr, ls, ps].map((name) => col(`skipped ${name}`, "numeric")),
+ ],
+ }),
+ tableOf({
+ name: close,
+ primaryKey: ["id"],
+ columns: [col("id", "integer", { notNull: true, identity: "d" })],
+ }),
+ tableOf({ name: ps, columns: [col(cr, "text")] }),
+ ];
+
+ const { schema } = await load(tables);
+
+ expect((globalThis as Record)[marker]).toBeUndefined();
+ expect(Object.keys(schema.$tables).sort()).toEqual(
+ ["source", "target", close].sort(),
+ );
+ const config = (name: string) =>
+ getTableConfig(schema.$engine[name] as unknown as PgTable);
+ expect(config(close).name).toBe(close);
+ expect(config("target").columns.map((c) => c.name)).toEqual([quote]);
+ const source = config("source");
+ expect(source.columns.map((c) => c.name)).toEqual([
+ "id",
+ backslash,
+ ...texts.map((name) => `c ${name}`),
+ "kind",
+ "level",
+ ]);
+ const column = (name: string) =>
+ source.columns.find((c) => c.name === name);
+ for (const name of texts) expect(column(`c ${name}`)?.default).toBe(name);
+ expect(
+ (column("kind") as unknown as { enum: { enumName: string } }).enum
+ .enumName,
+ ).toBe(close);
+ expect(column("kind")?.enumValues).toEqual(kind.values);
+ expect(column("level")?.enumValues).toEqual(level.values);
+ expect(column("level")?.default).toBe(bidi);
+ expect(
+ source.foreignKeys.map((fk) =>
+ fk.reference().foreignColumns.map((c) => c.name),
+ ),
+ ).toEqual([[quote]]);
+ });
+
+ test("a refresh over the schema.ts it replaces keeps what it declares, and adds the rest as the catalog has it", async () => {
+ const before =
+ await loadSource(`import { defineSchema, fk, id, text, timestamp } from ${JSON.stringify(BUILDER)};
+export const schema = defineSchema(({ table }) => {
+ const boards = table("boards", {
+ id: id(),
+ title: text().notNull(),
+ created_at: timestamp({ withTimezone: true }).notNull().defaultNow(),
+ });
+ const notes = table("notes", {
+ id: id(),
+ board_id: fk(() => boards.id).notNull().onDelete("cascade"),
+ slug: text().unique(),
+ author_email: text().private(),
+ body: text().notNull().default("-"),
+ });
+ return { boards, notes };
+});
+`);
+ const key = col("id", "integer", { notNull: true, identity: "d" });
+ const catalog = [
+ tableOf({
+ name: "boards",
+ primaryKey: ["id"],
+ columns: [
+ key,
+ col("title", "text", { notNull: true }),
+ col("created_at", "timestamp with time zone", {
+ notNull: true,
+ defaultExpr: "now()",
+ }),
+ ],
+ }),
+ tableOf({
+ name: "notes",
+ primaryKey: ["id"],
+ unique: [
+ { name: "notes_slug_unique", columns: ["slug"], deferrable: false },
+ ],
+ foreignKeys: [
+ foreignKey({
+ name: "notes_board_id_boards_id_fk",
+ columns: ["board_id"],
+ schema: "app",
+ table: "boards",
+ refColumns: ["id"],
+ onDelete: "cascade",
+ onUpdate: "no action",
+ }),
+ foreignKey({
+ name: "notes_reviewer_id_reviewers_id_fk",
+ columns: ["reviewer_id"],
+ schema: "app",
+ table: "reviewers",
+ refColumns: ["id"],
+ onDelete: "no action",
+ onUpdate: "no action",
+ }),
+ ],
+ columns: [
+ key,
+ col("board_id", "integer", { notNull: true }),
+ col("slug", "text"),
+ col("author_email", "text"),
+ col("body", "text", { notNull: true, defaultExpr: "'-'::text" }),
+ col("summary", "text"),
+ col("reviewer_id", "integer"),
+ ],
+ }),
+ tableOf({
+ name: "reviewers",
+ primaryKey: ["id"],
+ columns: [key, col("label", "text")],
+ }),
+ ];
+
+ const rendered = renderSchemaSource(catalog, "app", {
+ importSource: BUILDER,
+ previous: before.schema,
+ });
+ const after = await loadSource(rendered.source);
+ const was = await shape(before.schema);
+ const is = await shape(after.schema);
+
+ expect(was).toEqual({
+ boards: {
+ columns: {
+ id: "integer not null pk",
+ title: "text not null",
+ created_at: "timestamp with time zone not null default now()",
+ },
+ unique: [],
+ foreignKeys: [],
+ private: [],
+ },
+ notes: {
+ columns: {
+ id: "integer not null pk",
+ board_id: "integer not null",
+ slug: "text",
+ author_email: "text",
+ body: "text not null default '-'",
+ },
+ unique: [["slug"]],
+ foreignKeys: ["board_id -> boards(id) on delete cascade"],
+ private: ["author_email"],
+ },
+ });
+ for (const [table, declared] of Object.entries(was)) {
+ const kept = is[table] as TableShape;
+ expect(kept.columns).toMatchObject(declared.columns);
+ expect(kept.unique).toEqual(expect.arrayContaining(declared.unique));
+ expect(kept.foreignKeys).toEqual(
+ expect.arrayContaining(declared.foreignKeys),
+ );
+ expect(kept.private).toEqual(declared.private);
+ }
+ expect(is.notes).toMatchObject({
+ columns: { summary: "text", reviewer_id: "integer" },
+ foreignKeys: [
+ "board_id -> boards(id) on delete cascade",
+ "reviewer_id -> reviewers(id)",
+ ],
+ });
+ expect(is.reviewers).toEqual({
+ columns: { id: "integer not null pk", label: "text" },
+ unique: [],
+ foreignKeys: [],
+ private: [],
+ });
+ });
+});
diff --git a/packages/appkit/src/database/tooling/lakebase-api.ts b/packages/appkit/src/database/tooling/lakebase-api.ts
new file mode 100644
index 000000000..d3332968d
--- /dev/null
+++ b/packages/appkit/src/database/tooling/lakebase-api.ts
@@ -0,0 +1,428 @@
+import { z } from "zod";
+
+import type { ToolingRequest, ToolingWorkspaceClient } from "./context";
+
+// Lakebase Postgres REST API through the workspace client's raw requests. Paths,
+// query parameters and bodies mirror the Go SDK (service/postgres/impl.go).
+
+export interface LakebaseBranch {
+ name: string;
+ status?: {
+ default?: boolean;
+ is_protected?: boolean;
+ current_state?: string;
+ expire_time?: string;
+ source_branch?: string;
+ };
+}
+
+export interface LakebaseEndpoint {
+ name: string;
+ status?: {
+ endpoint_type?: string;
+ hosts?: { host?: string };
+ };
+}
+
+export interface LakebaseRole {
+ name: string;
+ status?: {
+ postgres_role?: string;
+ membership_roles?: string[];
+ };
+}
+
+export interface LakebaseDatabase {
+ name: string;
+ status?: { postgres_database?: string };
+}
+
+export type IdentityType = "USER" | "SERVICE_PRINCIPAL";
+
+export const SUPERUSER_MEMBERSHIP = "DATABRICKS_SUPERUSER";
+export const READ_WRITE_ENDPOINT = "ENDPOINT_TYPE_READ_WRITE";
+
+export interface RoleSpec {
+ identity_type: IdentityType;
+ postgres_role: string;
+ auth_method: "LAKEBASE_OAUTH_V1";
+ membership_roles: [typeof SUPERUSER_MEMBERSHIP];
+}
+
+export type BranchSpec = { source_branch: string } & (
+ | { no_expiry: true }
+ | { ttl: string }
+);
+
+interface Operation {
+ name?: string;
+ done?: boolean;
+ error?: { message?: string; error_code?: string };
+ response?: unknown;
+}
+
+export class LakebaseApiError extends Error {
+ /** HTTP status of the failing call; absent for a failed long-running operation. */
+ readonly statusCode?: number;
+ /** The API's error code, e.g. ALREADY_EXISTS, from the call or the operation. */
+ readonly errorCode?: string;
+ /** What was being done, e.g. "create branch projects/p/branches/b". */
+ readonly operation: string;
+
+ constructor(
+ operation: string,
+ message: string,
+ options: { statusCode?: number; errorCode?: string; cause?: unknown } = {},
+ ) {
+ super(`Lakebase: ${operation} failed: ${message}`, {
+ cause: options.cause,
+ });
+ this.name = "LakebaseApiError";
+ this.operation = operation;
+ this.statusCode = options.statusCode;
+ this.errorCode = options.errorCode;
+ }
+}
+
+function failedWith(
+ error: unknown,
+ statusCode: number,
+ errorCodes: readonly string[],
+): boolean {
+ return (
+ error instanceof LakebaseApiError &&
+ (error.statusCode === statusCode ||
+ (error.errorCode !== undefined && errorCodes.includes(error.errorCode)))
+ );
+}
+
+export const isAlreadyExists = (error: unknown) =>
+ failedWith(error, 409, ["ALREADY_EXISTS", "RESOURCE_ALREADY_EXISTS"]);
+export const isPermissionDenied = (error: unknown) =>
+ failedWith(error, 403, ["PERMISSION_DENIED"]);
+const isNotFound = (error: unknown) =>
+ failedWith(error, 404, ["NOT_FOUND", "RESOURCE_DOES_NOT_EXIST"]);
+
+/** The project holds as many branches as it may: "unarchived branches limit exceeded". */
+export function isBranchLimit(error: unknown): boolean {
+ return (
+ error instanceof LakebaseApiError &&
+ /branches limit exceeded/i.test(error.message)
+ );
+}
+
+const API = "/api/2.0/postgres";
+
+// The guard decides from `default` and `is_protected` whether a command may
+// write to a branch. proto3 JSON omits false values, so a missing one reads as
+// false. A response without `status`, or with a non-boolean value, fails.
+const branchResponse = z.looseObject({
+ name: z.string(),
+ status: z.looseObject({
+ default: z.boolean().optional(),
+ is_protected: z.boolean().optional(),
+ current_state: z.string().optional(),
+ expire_time: z.string().optional(),
+ source_branch: z.string().optional(),
+ }),
+});
+
+const endpointResponse = z.looseObject({
+ name: z.string(),
+ status: z
+ .looseObject({
+ hosts: z.looseObject({ host: z.string().optional() }).optional(),
+ })
+ .optional(),
+});
+
+function statusCodeOf(error: unknown): number | undefined {
+ const code = (error as { statusCode?: unknown } | undefined)?.statusCode;
+ return typeof code === "number" ? code : undefined;
+}
+
+function errorCodeOf(error: unknown): string | undefined {
+ const code = (error as { errorCode?: unknown } | undefined)?.errorCode;
+ return typeof code === "string" && code ? code : undefined;
+}
+
+function messageOf(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+/** Workspace requests take string query values; unset ones are left out. */
+function encodeQuery(
+ query: ToolingRequest["query"],
+): Record | undefined {
+ const entries = Object.entries(query ?? {}).flatMap(([key, value]) =>
+ value === undefined ? [] : [[key, String(value)] as const],
+ );
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+}
+
+const sleep = (ms: number) =>
+ new Promise((resolve) => setTimeout(resolve, ms));
+
+interface LakebaseApiOptions {
+ /** First poll delay for long-running operations; doubles up to 5 s. */
+ readonly pollIntervalMs?: number;
+ /** Give up waiting for one long-running operation after this long. */
+ readonly timeoutMs?: number;
+}
+
+export class LakebaseApi {
+ private readonly pollIntervalMs: number;
+ private readonly timeoutMs: number;
+
+ constructor(
+ private readonly client: Pick,
+ options: LakebaseApiOptions = {},
+ ) {
+ this.pollIntervalMs = options.pollIntervalMs ?? 500;
+ this.timeoutMs = options.timeoutMs ?? 10 * 60_000;
+ }
+
+ getBranch(name: string): Promise {
+ return this.getParsedOrNull(`get branch ${name}`, name, branchResponse);
+ }
+
+ getEndpoint(name: string): Promise {
+ return this.getParsedOrNull(`get endpoint ${name}`, name, endpointResponse);
+ }
+
+ private async getParsedOrNull(
+ operation: string,
+ name: string,
+ schema: z.ZodType,
+ ): Promise {
+ const response = await this.getOrNull(operation, name);
+ if (response === null) return null;
+ const parsed = schema.safeParse(response);
+ if (parsed.success) return parsed.data;
+ const issues = parsed.error.issues
+ .map((issue) => `${issue.path.join(".") || "body"}: ${issue.message}`)
+ .join("; ");
+ throw new LakebaseApiError(operation, `unexpected response (${issues})`);
+ }
+
+ listBranches(project: string): Promise {
+ return this.list(
+ `list branches of ${project}`,
+ `${project}/branches`,
+ "branches",
+ );
+ }
+
+ async createBranch(
+ project: string,
+ branchId: string,
+ spec: BranchSpec,
+ ): Promise {
+ const operation = `create branch ${project}/branches/${branchId}`;
+ const op = await this.call(operation, {
+ path: `${API}/${project}/branches`,
+ method: "POST",
+ query: { branch_id: branchId },
+ payload: { spec },
+ });
+ return this.wait(operation, op);
+ }
+
+ listEndpoints(branch: string): Promise {
+ return this.list(
+ `list endpoints of ${branch}`,
+ `${branch}/endpoints`,
+ "endpoints",
+ );
+ }
+
+ /** A read-write endpoint that suspends after `suspendTimeout` idle (e.g. "300s"). */
+ async createEndpoint(
+ branch: string,
+ endpointId: string,
+ options: { suspendTimeout: string },
+ ): Promise {
+ const operation = `create endpoint ${branch}/endpoints/${endpointId}`;
+ const op = await this.call(operation, {
+ path: `${API}/${branch}/endpoints`,
+ method: "POST",
+ query: { endpoint_id: endpointId },
+ payload: {
+ spec: {
+ endpoint_type: READ_WRITE_ENDPOINT,
+ suspend_timeout_duration: options.suspendTimeout,
+ },
+ },
+ });
+ return this.wait(operation, op);
+ }
+
+ /** A branch that is already gone counts as deleted. */
+ async deleteBranch(name: string): Promise {
+ await this.deleteResource(`delete branch ${name}`, name);
+ }
+
+ getDatabase(name: string): Promise {
+ return this.getOrNull(`get database ${name}`, name);
+ }
+
+ listRoles(branch: string): Promise {
+ return this.list(`list roles of ${branch}`, `${branch}/roles`, "roles");
+ }
+
+ /** Without a role_id; the API derives one (sidesteps the USER role_id format). */
+ async createRole(branch: string, spec: RoleSpec): Promise {
+ const operation = `create role ${spec.postgres_role} on ${branch}`;
+ const op = await this.call(operation, {
+ path: `${API}/${branch}/roles`,
+ method: "POST",
+ payload: { spec },
+ });
+ return this.wait(operation, op);
+ }
+
+ async setRoleMemberships(
+ role: string,
+ memberships: RoleSpec["membership_roles"],
+ ): Promise {
+ const operation = `update role ${role}`;
+ const op = await this.call(operation, {
+ path: `${API}/${role}`,
+ method: "PATCH",
+ query: { update_mask: "spec.membership_roles" },
+ payload: { spec: { membership_roles: memberships } },
+ });
+ return this.wait(operation, op);
+ }
+
+ /** Every object the role owns is reassigned first (runs SQL on the branch's compute). */
+ async deleteRole(
+ role: string,
+ options: { reassignOwnedTo: string },
+ ): Promise {
+ await this.deleteResource(`delete role ${role}`, role, {
+ reassign_owned_to: options.reassignOwnedTo,
+ });
+ }
+
+ /**
+ * A NOT_FOUND counts as deleted only when the resource is gone: it can name
+ * another resource the delete needs, such as a missing reassign target.
+ */
+ private async deleteResource(
+ operation: string,
+ name: string,
+ query?: ToolingRequest["query"],
+ ): Promise