From 16106acfd13ed8b74c2fcc361872b5e2843639ac Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 12 Oct 2026 13:20:49 +0100 Subject: [PATCH 001/317] feat(appkit): apply committed database migrations on deploy start A deployed DatabasePlugin app now applies the migrations committed under config/database/migrations before its startup checks, as its own service principal and under a per-schema advisory lock. Pending migrations run in one transaction, and a table lock held for over 30s fails the migration instead of stalling the table. A 0000_baseline whose tables already exist is recorded, in its own transaction, instead of run. Any failure stops startup, and the server log names it: the tags and SQLSTATE, or the missing migration file. Local runs never migrate on start. Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 469 ++++++++++ .../src/database/migrations/ownership.ts | 18 + .../appkit/src/database/migrations/paths.ts | 72 ++ .../database/migrations/tests/apply.test.ts | 832 ++++++++++++++++++ .../migrations/tests/ownership.test.ts | 21 + .../appkit/src/plugins/database/lifecycle.ts | 8 +- .../src/plugins/database/migrate-on-start.ts | 78 ++ .../src/plugins/database/schema-check.ts | 10 +- .../plugins/database/tests/lifecycle.test.ts | 97 +- .../database/tests/migrate-on-start.test.ts | 187 ++++ 10 files changed, 1784 insertions(+), 8 deletions(-) create mode 100644 packages/appkit/src/database/migrations/apply.ts create mode 100644 packages/appkit/src/database/migrations/ownership.ts create mode 100644 packages/appkit/src/database/migrations/paths.ts create mode 100644 packages/appkit/src/database/migrations/tests/apply.test.ts create mode 100644 packages/appkit/src/database/migrations/tests/ownership.test.ts create mode 100644 packages/appkit/src/plugins/database/migrate-on-start.ts create mode 100644 packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts new file mode 100644 index 000000000..a4e6dd704 --- /dev/null +++ b/packages/appkit/src/database/migrations/apply.ts @@ -0,0 +1,469 @@ +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; + +import { readMigrationFiles } from "drizzle-orm/migrator"; +import { drizzle } from "drizzle-orm/node-postgres"; +import { migrate } from "drizzle-orm/node-postgres/migrator"; +import type { Pool, PoolClient } from "pg"; + +import { createLogger } from "../../logging/logger"; +import { ownershipHint } from "./ownership"; +import { + BASELINE_TAG, + type Journal, + type JournalEntry, + MIGRATIONS_TABLE, + MigrationFilesError, + readJournal, + readJsonFile, +} from "./paths"; + +const logger = createLogger("database"); + +interface ApplyMigrationsOptions { + /** Absolute path of the committed migrations folder. */ + readonly migrationsFolder: string; + /** Journal schema = app schema. */ + readonly schemaName: string; +} + +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[]; +} + +/** lock_not_available: a table lock was not granted within LOCK_TIMEOUT. */ +const LOCK_NOT_AVAILABLE = "55P03"; +/** + * Longest wait for a table lock while migrating. Past it the migration fails; + * waiting longer would queue every other query on that table behind it. + */ +const LOCK_TIMEOUT = "30s"; + +function failureHint(code: string | undefined): string | undefined { + if (code === LOCK_NOT_AVAILABLE) { + return `Another session held a lock on a table this migration changes for over ${LOCK_TIMEOUT}; deploy again once it finishes.`; + } + return ownershipHint(code); +} + +/** + * A statement failed while migrating. Pending migrations run in one drizzle-orm + * migrator transaction, so none of them were applied; a baseline adopted just + * before commits on its own and stays recorded. + */ +export class MigrationApplyError extends Error { + /** Tags that were being applied; empty when reading the recorded migrations failed. */ + readonly pending: readonly string[]; + /** SQLSTATE of the failing statement, when the driver reported one. */ + readonly code?: string; + /** Tags this run recorded as applied before the failure. */ + readonly adopted: readonly string[]; + + constructor( + pending: readonly string[], + code: string | undefined, + options: { cause?: unknown; adopted?: readonly string[] } = {}, + ) { + const adopted = options.adopted ?? []; + const sqlState = code ? ` (SQLSTATE ${code})` : ""; + const failure = + pending.length > 0 + ? `Applying migration${pending.length === 1 ? "" : "s"} ${pending.join(", ")} failed${sqlState}; none were applied.` + : `Reading the recorded migrations in ${MIGRATIONS_TABLE} failed${sqlState}; none were applied.`; + const kept = + adopted.length > 0 + ? ` ${adopted.join(", ")} stays recorded as applied: its tables already existed.` + : ""; + const hint = failureHint(code); + super(`${failure}${kept}${hint ? ` ${hint}` : ""}`, { + cause: options.cause, + }); + this.name = "MigrationApplyError"; + this.pending = Object.freeze([...pending]); + this.code = code; + this.adopted = Object.freeze([...adopted]); + } +} + +/** + * 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 against this database.", + ); + this.name = "MigrationBaselineMismatchError"; + this.problems = Object.freeze([...problems]); + } +} + +const SQLSTATE = /^[0-9A-Z]{5}$/; + +/** drizzle wraps driver errors; the SQLSTATE lives somewhere on the cause chain. */ +function sqlStateOf(error: unknown): string | undefined { + let current = error; + for (let depth = 0; depth < 5 && current; depth++) { + const code = (current as { code?: unknown }).code; + // No SQLSTATE class starts with "E"; Node system errors (EPIPE, EPERM, …) all do. + if (typeof code === "string" && SQLSTATE.test(code) && code[0] !== "E") { + return code; + } + current = (current as { cause?: unknown }).cause; + } + return undefined; +} + +function quoteIdentifier(name: string): string { + return `"${name.replace(/"/g, '""')}"`; +} + +/** 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; + +/** + * `created_at` of the last migration the database recorded; null when none is. + * An empty journal table counts as nothing recorded: drizzle-orm creates it + * before its transaction, so a failed first deploy leaves one behind. + */ +async function lastRecordedMigration( + client: QueryClient, + schemaName: string, +): Promise { + // pg_catalog needs no privileges, so a missing grant is not mistaken for a missing table. + const table = await client.query( + `select 1 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], + ); + if (table.rows.length === 0) return null; + const last = await client.query<{ last: string | number | null }>( + `select max(created_at) as last from ${quoteIdentifier(schemaName)}.${quoteIdentifier(MIGRATIONS_TABLE)}`, + ); + const value = last.rows[0]?.last; + return value === null || value === undefined ? null : Number(value); +} + +/** + * Journal entries newer than the last recorded migration: drizzle-orm's own + * rule, so this agrees with what its migrator runs. + * + * Known gap, shared with drizzle-orm: an entry older than the last recorded one + * (e.g. merged from a parallel branch) is never applied, and an applied + * migration edited later goes unnoticed. Comparing the recorded hashes with the + * journal would catch both. + */ +function pendingEntries( + journal: Journal, + lastRecorded: number | null, +): JournalEntry[] { + if (lastRecorded === null) return journal.entries; + return journal.entries.filter((entry) => entry.when > lastRecorded); +} + +/** Fail before connecting, naming the file, rather than inside drizzle-orm's migrator. */ +function assertMigrationFiles(folder: string, journal: Journal): void { + for (const entry of journal.entries) { + const file = path.join(folder, `${entry.tag}.sql`); + if (!fs.existsSync(file)) { + throw new MigrationFilesError( + `Missing ${file}, listed in meta/_journal.json. Restore it from version control.`, + ); + } + } +} + +/** + * Run `work` on one dedicated connection under the per-schema advisory lock, + * with no statement timeout and at most LOCK_TIMEOUT per table lock. The + * connection is always unlocked, reset and released; a connection whose + * cleanup fails is destroyed, not reused. + */ +async function withMigrationLock( + pool: Pick, + schemaName: string, + work: (client: PoolClient) => Promise, +): Promise { + const lockKey = migrationLockKey(schemaName); + const client = await pool.connect(); + let locked = false; + try { + await client.query("SET statement_timeout = 0"); + const attempt = await client.query<{ locked: boolean }>( + "select pg_catalog.pg_try_advisory_lock($1::bigint) as locked", + [lockKey], + ); + if (!attempt.rows[0]?.locked) { + logger.info( + "Waiting for another instance to finish migrating schema %s", + schemaName, + ); + await client.query("select pg_catalog.pg_advisory_lock($1::bigint)", [ + lockKey, + ]); + } + locked = true; + // Only now: lock_timeout would also cut short the wait for the advisory lock. + await client.query(`SET lock_timeout = '${LOCK_TIMEOUT}'`); + return await work(client); + } finally { + const cleanup: Array<() => Promise> = []; + if (locked) { + cleanup.push(() => + client.query("select pg_catalog.pg_advisory_unlock($1::bigint)", [ + lockKey, + ]), + ); + } + cleanup.push(() => client.query("RESET lock_timeout")); + cleanup.push(() => client.query("RESET statement_timeout")); + + let cleanupError: Error | undefined; + for (const step of cleanup) { + try { + await step(); + } catch (error) { + cleanupError ??= + error instanceof Error ? error : new Error(String(error)); + } + } + // A connection that may still hold the lock or the session settings must not be reused. + client.release(cleanupError); + } +} + +async function inTransaction( + client: QueryClient, + work: () => Promise, +): Promise { + await client.query("begin"); + try { + await work(); + await client.query("commit"); + } catch (error) { + await client.query("rollback").catch(() => undefined); + throw error; + } +} + +/** 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 = path.join( + folder, + "meta", + `${String(idx).padStart(4, "0")}_snapshot.json`, + ); + 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: JournalEntry, +): 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" }; +} + +/** + * Record migrations as applied without running them: create the journal table + * as drizzle-orm's migrator does, then insert one row per tag with the + * migrator's own hash (sha256 of the .sql file) and `created_at` (the journal's + * `when`). Runs on the caller's connection; wrap it in a transaction. + */ +async function recordMigrationsApplied( + client: QueryClient, + options: ApplyMigrationsOptions, + journal: Journal, + tags: readonly string[], +): Promise { + // One file per journal entry, in journal order. + const files = readMigrationFiles({ + migrationsFolder: options.migrationsFolder, + }); + const schema = quoteIdentifier(options.schemaName); + const table = `${schema}.${quoteIdentifier(MIGRATIONS_TABLE)}`; + await client.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`); + // drizzle-orm's own definition, so its migrator later reads and extends this table. + await client.query( + `CREATE TABLE IF NOT EXISTS ${table} ( + id SERIAL PRIMARY KEY, + hash text NOT NULL, + created_at bigint + )`, + ); + for (const tag of tags) { + const index = journal.entries.findIndex((entry) => entry.tag === tag); + const file = files[index]; + if (index < 0 || !file) { + throw new Error(`Migration ${tag} is not in the journal.`); + } + await client.query( + `insert into ${table} ("hash", "created_at") values($1, $2)`, + [file.hash, file.folderMillis], + ); + } +} + +/** + * Apply every committed migration the database has not recorded yet. + * + * Runs on one dedicated connection as the connecting identity, which owns what + * it creates (see ownership.ts), under a per-schema advisory lock; drizzle-orm's + * migrator runs only when something is pending. + * + * 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: [] }; + } + assertMigrationFiles(options.migrationsFolder, journal); + + return withMigrationLock(pool, options.schemaName, async (client) => { + const adopted: string[] = []; + // What the failing step was applying, for the error. + let applying: readonly string[] = []; + try { + const lastRecorded = await lastRecordedMigration( + client, + options.schemaName, + ); + let pending = pendingEntries(journal, lastRecorded); + if (pending.length === 0) return { applied: [], adopted }; + + const first = journal.entries[0]; + if (lastRecorded === null && first?.tag === BASELINE_TAG) { + applying = [BASELINE_TAG]; + const state = await baselineState(client, options, first); + if (state.kind === "partial") { + throw new MigrationBaselineMismatchError( + options.schemaName, + state.problems, + ); + } + if (state.kind === "present") { + await inTransaction(client, () => + recordMigrationsApplied(client, options, journal, [BASELINE_TAG]), + ); + adopted.push(BASELINE_TAG); + pending = pending.filter((entry) => entry.tag !== BASELINE_TAG); + if (pending.length === 0) return { applied: [], adopted }; + } + } + + applying = pending.map((entry) => entry.tag); + await migrate(drizzle({ client }), { + migrationsFolder: options.migrationsFolder, + migrationsSchema: options.schemaName, + migrationsTable: MIGRATIONS_TABLE, + }); + return { applied: applying, adopted }; + } catch (error) { + if ( + error instanceof MigrationBaselineMismatchError || + error instanceof MigrationFilesError + ) { + throw error; + } + throw new MigrationApplyError(applying, sqlStateOf(error), { + cause: error, + adopted, + }); + } + }); +} diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts new file mode 100644 index 000000000..606efb1d1 --- /dev/null +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -0,0 +1,18 @@ +// 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 owner role is not +// possible: Lakebase rejects `GRANT … TO databricks_superuser`. + +/** insufficient_privilege: "must be owner of …", "permission denied for …". */ +const INSUFFICIENT_PRIVILEGE = "42501"; + +/** How to fix a migration that failed for lack of privileges; undefined for any other SQLSTATE. */ +export function ownershipHint(code: string | undefined): string | undefined { + if (code !== INSUFFICIENT_PRIVILEGE) return undefined; + 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, " + + "and if another role created the schema, use another schemaName in schema.ts or have that role transfer the schema and its objects." + ); +} diff --git a/packages/appkit/src/database/migrations/paths.ts b/packages/appkit/src/database/migrations/paths.ts new file mode 100644 index 000000000..e331080b0 --- /dev/null +++ b/packages/appkit/src/database/migrations/paths.ts @@ -0,0 +1,72 @@ +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); +} + +/** Path of the journal inside a migrations folder. */ +function journalFile(folder: string): string { + return path.join(folder, "meta", "_journal.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 }, + ); + } +} + +/** 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; + const parsed = readJsonFile>(file); + if (parsed.dialect !== "postgresql" || !Array.isArray(parsed.entries)) { + throw new MigrationFilesError( + `${file} is not a drizzle-kit PostgreSQL migration journal`, + ); + } + return parsed as Journal; +} 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..4fc178d14 --- /dev/null +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -0,0 +1,832 @@ +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { + applyPendingMigrations, + MigrationApplyError, + MigrationBaselineMismatchError, + migrationLockKey, +} from "../apply"; +import { type Journal, MigrationFilesError } from "../paths"; + +const folders: string[] = []; + +/** Write a v7 journal with one SQL file per entry, the way drizzle-kit lays them out. */ +function migrations( + entries: Array<{ + tag: string; + when: number; + sql: string[]; + /** Tables (name → columns) for meta/NNNN_snapshot.json. */ + snapshot?: Record; + }>, +) { + 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]) => [ + `app.${name}`, + { + name, + schema: "app", + 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; +} + +afterEach(() => { + vi.restoreAllMocks(); + for (const folder of folders.splice(0)) { + fs.rmSync(folder, { recursive: true, force: true }); + } +}); + +interface FakeState { + journalTableExists: boolean; + lastCreatedAt: number | null; + failOn?: RegExp; + /** SQLSTATE of the failOn error; defaults to 42P07 (duplicate_table). */ + failCode?: string; + failCleanupOn?: RegExp; + /** pg_catalog (table, column) pairs the baseline check sees. */ + catalog?: Array<[string, string]>; + /** Another instance holds the migration lock, so the first try fails. */ + lockHeld?: boolean; +} + +/** + * A pg PoolClient that records every statement. Its class name must not contain + * "Pool": drizzle-orm would take it for a pool and call connect() on it. + */ +class RecordingClient { + readonly statements: string[] = []; + /** Parameters of each journal insert. */ + readonly recorded: unknown[][] = []; + released: { error: unknown } | undefined; + + 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)) { + throw Object.assign(new Error("relation already exists"), { + code: this.state.failCode ?? "42P07", + }); + } + if (this.state.failCleanupOn?.test(text)) { + throw new Error("connection lost"); + } + if (text.includes("pg_try_advisory_lock(")) { + return { rows: [{ locked: !this.state.lockHeld }] }; + } + if (text.includes("pg_catalog.pg_attribute")) { + return { + rows: (this.state.catalog ?? []).map(([table_name, column_name]) => ({ + table_name, + column_name, + })), + }; + } + if (text.includes("pg_catalog.pg_class")) { + return { rows: this.state.journalTableExists ? [{ one: 1 }] : [] }; + } + if (text.startsWith(`insert into "app"."__drizzle_migrations"`)) { + this.recorded.push(params ?? []); + this.state.journalTableExists = true; + this.state.lastCreatedAt = Number(params?.[1]); + } + if (text.startsWith("select max(created_at)")) { + return { rows: [{ last: this.state.lastCreatedAt }] }; + } + if (text.includes("order by created_at desc limit 1")) { + return { + rows: + this.state.lastCreatedAt === null + ? [] + : [{ id: 1, hash: "h", created_at: this.state.lastCreatedAt }], + }; + } + return { rows: [] }; + } + + release(error?: unknown) { + this.released = { error }; + } +} + +function fakePool(state: FakeState) { + const client = new RecordingClient(state); + let connects = 0; + return { + client, + 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;`, + ], + }, + ]); + +/** 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_lock(")) return "lock"; + if (statement.includes("pg_advisory_unlock(")) return "unlock"; + if (statement.includes("pg_catalog.pg_attribute")) + return "baseline tables?"; + if (statement.includes("pg_catalog.pg_class")) return "journal table?"; + if (statement.startsWith("select max(created_at)")) return "last applied?"; + return statement.replace(/\s+/g, " "); + }); +} + +describe("applyPendingMigrations", () => { + test("applies every pending migration as the connecting identity under the advisory lock, then unlocks and releases", async () => { + const folder = twoMigrations(); + const { pool, client } = fakePool({ + journalTableExists: false, + lastCreatedAt: null, + }); + + const result = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }); + + expect(result.applied).toEqual(["0000_migration", "0001_migration"]); + expect(steps(client.statements)).toEqual([ + "SET statement_timeout = 0", + "try lock", + "SET lock_timeout = '30s'", + "journal table?", + // drizzle-orm's migrator as the connecting identity (no SET ROLE), journal in the app schema: + `CREATE SCHEMA IF NOT EXISTS "app"`, + `CREATE TABLE IF NOT EXISTS "app"."__drizzle_migrations" ( id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint )`, + `select id, hash, created_at from "app"."__drizzle_migrations" order by created_at desc limit 1`, + "begin", + `CREATE TABLE "app"."notes" ("id" integer);`, + `insert into "app"."__drizzle_migrations" ("hash", "created_at") values($1, $2)`, + `ALTER TABLE "app"."notes" ADD COLUMN "body" text;`, + `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`, + `insert into "app"."__drizzle_migrations" ("hash", "created_at") values($1, $2)`, + "commit", + "unlock", + "RESET lock_timeout", + "RESET statement_timeout", + ]); + expect(client.released).toEqual({ error: undefined }); + }); + + test("applies only entries newer than the last recorded migration", async () => { + const folder = twoMigrations(); + const { pool, client } = fakePool({ + journalTableExists: true, + lastCreatedAt: 1000, + }); + + const result = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }); + + expect(result.applied).toEqual(["0001_migration"]); + expect(client.statements).not.toContain( + `CREATE TABLE "app"."notes" ("id" integer);`, + ); + expect(client.statements).toContain( + `ALTER TABLE "app"."notes" ADD COLUMN "body" text;`, + ); + }); + + test("with nothing pending, issues no migration SQL", async () => { + const folder = twoMigrations(); + const { pool, client } = fakePool({ + journalTableExists: true, + lastCreatedAt: 2000, + }); + + const result = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }); + + expect(result.applied).toEqual([]); + expect(steps(client.statements)).toEqual([ + "SET statement_timeout = 0", + "try lock", + "SET lock_timeout = '30s'", + "journal table?", + "last applied?", + "unlock", + "RESET lock_timeout", + "RESET statement_timeout", + ]); + expect(client.released).toEqual({ error: undefined }); + }); + + test("without a journal it never connects", async () => { + const folder = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-apply-")); + folders.push(folder); + const fake = fakePool({ journalTableExists: false, lastCreatedAt: null }); + + await expect( + applyPendingMigrations(fake.pool, { + migrationsFolder: folder, + schemaName: "app", + }), + ).resolves.toEqual({ applied: [], adopted: [] }); + expect(fake.connects()).toBe(0); + }); + + test("a failing statement rolls back all pending migrations and still unlocks and releases", async () => { + const folder = twoMigrations(); + const { pool, client } = fakePool({ + journalTableExists: false, + lastCreatedAt: null, + failOn: /ADD COLUMN "title"/, + }); + + const error = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(MigrationApplyError); + expect(error).toMatchObject({ + pending: ["0000_migration", "0001_migration"], + code: "42P07", + }); + expect((error as Error).message).toBe( + "Applying migrations 0000_migration, 0001_migration failed (SQLSTATE 42P07); none were applied.", + ); + expect(steps(client.statements).slice(-5)).toEqual([ + `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`, + "rollback", + "unlock", + "RESET lock_timeout", + "RESET statement_timeout", + ]); + expect(client.released).toEqual({ error: undefined }); + }); + + test("an ownership failure (42501) names the branch-owner rule and the fix", async () => { + const folder = twoMigrations(); + const { pool } = fakePool({ + journalTableExists: false, + lastCreatedAt: null, + failOn: /ADD COLUMN "body"/, + failCode: "42501", + }); + + const error = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }).catch((caught: unknown) => caught); + + expect(error).toMatchObject({ code: "42501" }); + expect((error as Error).message).toMatch( + /^Applying migrations 0000_migration, 0001_migration failed \(SQLSTATE 42501\); none were applied\. The connecting role lacks a privilege this migration needs: /, + ); + }); + + test("a failed unlock destroys the connection instead of returning it to the pool", async () => { + const folder = twoMigrations(); + const { pool, client } = fakePool({ + journalTableExists: false, + lastCreatedAt: null, + failCleanupOn: /pg_advisory_unlock/, + }); + + await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }); + + // The remaining cleanup still runs. + expect(steps(client.statements).slice(-3)).toEqual([ + "unlock", + "RESET lock_timeout", + "RESET statement_timeout", + ]); + expect(client.released?.error).toBeInstanceOf(Error); + }); + + test("a failure before the lock is held releases without unlocking", async () => { + const folder = twoMigrations(); + const { pool, client } = fakePool({ + journalTableExists: false, + lastCreatedAt: null, + failOn: /pg_try_advisory_lock/, + }); + + await expect( + applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }), + ).rejects.toThrow("relation already exists"); + expect(steps(client.statements)).toEqual([ + "SET statement_timeout = 0", + "try lock", + "RESET lock_timeout", + "RESET statement_timeout", + ]); + expect(client.released).toEqual({ error: undefined }); + }); +}); + +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"] }, + }, + ]); + +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({ + journalTableExists: false, + lastCreatedAt: null, + catalog: [], + }); + + const result = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }); + + expect(result).toEqual({ + 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 } = fakePool({ + journalTableExists: false, + lastCreatedAt: null, + catalog: [ + ["notes", "id"], + ["notes", "body"], + ["tags", "id"], + ], + }); + + const result = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }); + + expect(result).toEqual({ + 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. + const baselineFile = fs.readFileSync( + path.join(folder, "0000_baseline.sql"), + "utf-8", + ); + expect(client.recorded[0]).toEqual([ + createHash("sha256").update(baselineFile).digest("hex"), + 1000, + ]); + expect(steps(client.statements).slice(0, 10)).toEqual([ + "SET statement_timeout = 0", + "try lock", + "SET lock_timeout = '30s'", + "journal table?", + "baseline tables?", + "begin", + `CREATE SCHEMA IF NOT EXISTS "app"`, + `CREATE TABLE IF NOT EXISTS "app"."__drizzle_migrations" ( id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint )`, + `insert into "app"."__drizzle_migrations" ("hash", "created_at") values($1, $2)`, + "commit", + ]); + expect(client.released).toEqual({ error: undefined }); + }); + + 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, client } = fakePool({ + journalTableExists: false, + lastCreatedAt: null, + catalog: [ + ["notes", "id"], + ["notes", "body"], + ["tags", "id"], + ], + }); + + await expect( + applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }), + ).resolves.toEqual({ applied: [], adopted: ["0000_baseline"] }); + expect(client.statements.slice(-3)).toEqual([ + expect.stringContaining("pg_advisory_unlock"), + "RESET lock_timeout", + "RESET statement_timeout", + ]); + }); + + test("only part of the baseline exists: MigrationBaselineMismatchError, nothing recorded or run", async () => { + const folder = baselineThenMigration(); + const { pool, client } = fakePool({ + journalTableExists: false, + lastCreatedAt: null, + catalog: [["notes", "id"]], + }); + + const error = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }).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(client.recorded).toEqual([]); + expect(client.statements).not.toContain("begin"); + expect(steps(client.statements).slice(-3)).toEqual([ + "unlock", + "RESET lock_timeout", + "RESET statement_timeout", + ]); + 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({ + journalTableExists: false, + lastCreatedAt: null, + catalog: [ + ["notes", "id"], + ["notes", "body"], + ["tags", "id"], + ], + // The schema belongs to another role, so the journal table cannot be created in it. + failOn: /^CREATE TABLE IF NOT EXISTS "app"\."__drizzle_migrations"/, + failCode: "42501", + }); + + const error = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(MigrationApplyError); + expect(error).toMatchObject({ pending: ["0000_baseline"], code: "42501" }); + expect((error as Error).message).toContain( + "On the deploy branch that role is the app's service principal", + ); + 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({ + journalTableExists: true, + lastCreatedAt: 1000, + catalog: [["notes", "id"]], + }); + + await expect( + applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }), + ).resolves.toEqual({ applied: ["0001_migration"], adopted: [] }); + expect( + client.statements.some((s) => s.includes("pg_catalog.pg_attribute")), + ).toBe(false); + }); + + test("an empty journal table, left by a failed first deploy, still adopts the baseline", async () => { + const folder = baselineThenMigration(); + const { pool } = fakePool({ + journalTableExists: true, + lastCreatedAt: null, + catalog: [ + ["notes", "id"], + ["notes", "body"], + ["tags", "id"], + ], + }); + + await expect( + applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }), + ).resolves.toEqual({ + applied: ["0001_migration"], + adopted: ["0000_baseline"], + }); + }); + + test("a migration failing after the adoption says the baseline stays recorded", async () => { + const folder = baselineThenMigration(); + const { pool, client } = fakePool({ + journalTableExists: false, + lastCreatedAt: null, + catalog: [ + ["notes", "id"], + ["notes", "body"], + ["tags", "id"], + ], + failOn: /ADD COLUMN "title"/, + }); + + const error = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(MigrationApplyError); + expect(error).toMatchObject({ + pending: ["0001_migration"], + adopted: ["0000_baseline"], + }); + expect((error as Error).message).toBe( + "Applying migration 0001_migration failed (SQLSTATE 42P07); none were applied. 0000_baseline stays recorded as applied: its tables already existed.", + ); + expect(client.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({ + journalTableExists: false, + lastCreatedAt: null, + }); + + const error = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }).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 }); + }); +}); + +describe("applyPendingMigrations — failures name their cause", () => { + test("reading the recorded migrations fails (42501): the hint, and nothing applied", async () => { + const folder = twoMigrations(); + const { pool, client } = fakePool({ + journalTableExists: true, + lastCreatedAt: 1000, + // The journal table belongs to another role. + failOn: /^select max\(created_at\)/, + failCode: "42501", + }); + + const error = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(MigrationApplyError); + expect(error).toMatchObject({ pending: [], code: "42501" }); + expect((error as Error).message).toMatch( + /^Reading the recorded migrations in __drizzle_migrations failed \(SQLSTATE 42501\); none were applied\. The connecting role lacks a privilege/, + ); + expect(steps(client.statements).slice(-3)).toEqual([ + "unlock", + "RESET lock_timeout", + "RESET statement_timeout", + ]); + }); + + test("a table lock held past the lock timeout says to deploy again", async () => { + const folder = twoMigrations(); + const { pool } = fakePool({ + journalTableExists: true, + lastCreatedAt: 1000, + failOn: /ADD COLUMN "body"/, + failCode: "55P03", + }); + + const error = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }).catch((caught: unknown) => caught); + + expect((error as Error).message).toBe( + "Applying migration 0001_migration failed (SQLSTATE 55P03); none were applied. Another session held a lock on a table this migration changes for over 30s; deploy again once it finishes.", + ); + }); + + test("a Node system error is not reported as a SQLSTATE", async () => { + const folder = twoMigrations(); + const { pool } = fakePool({ + journalTableExists: true, + lastCreatedAt: 1000, + failOn: /ADD COLUMN "body"/, + failCode: "EPIPE", + }); + + const error = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }).catch((caught: unknown) => caught); + + expect(error).toMatchObject({ code: undefined }); + expect((error as Error).message).toBe( + "Applying migration 0001_migration failed; none were applied.", + ); + }); + + 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({ journalTableExists: false, lastCreatedAt: null }); + + const error = await applyPendingMigrations(fake.pool, { + migrationsFolder: folder, + schemaName: "app", + }).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([ + [ + "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({ journalTableExists: false, lastCreatedAt: null }); + + const error = await applyPendingMigrations(fake.pool, { + migrationsFolder: folder, + schemaName: "app", + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(MigrationFilesError); + expect((error as Error).message).toMatch(message); + expect(fake.connects()).toBe(0); + }, + ); + + test("waits for another instance's lock, and says so", async () => { + const folder = twoMigrations(); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + const { pool, client } = fakePool({ + journalTableExists: true, + lastCreatedAt: 2000, + lockHeld: true, + }); + + await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName: "app", + }); + + expect(steps(client.statements).slice(0, 4)).toEqual([ + "SET statement_timeout = 0", + "try lock", + "lock", + "SET lock_timeout = '30s'", + ]); + expect(log.mock.calls.flat().map(String).join(" ")).toContain( + "Waiting for another instance to finish migrating schema app", + ); + }); +}); 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..56ea47022 --- /dev/null +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -0,0 +1,21 @@ +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", () => { + const hint = ownershipHint("42501"); + expect(hint).toContain( + "lacks a privilege this migration needs: CREATE on the database, or ownership of the app schema and its tables", + ); + expect(hint).toContain( + "On the deploy branch that role is the app's service principal: bind the database to the app with CAN_CONNECT_AND_CREATE", + ); + expect(hint).toContain("use another schemaName in schema.ts"); + }); + + test("any other failure gets no ownership hint", () => { + expect(ownershipHint("42P07")).toBeUndefined(); + expect(ownershipHint(undefined)).toBeUndefined(); + }); +}); diff --git a/packages/appkit/src/plugins/database/lifecycle.ts b/packages/appkit/src/plugins/database/lifecycle.ts index c50badf6f..aff2abc08 100644 --- a/packages/appkit/src/plugins/database/lifecycle.ts +++ b/packages/appkit/src/plugins/database/lifecycle.ts @@ -23,6 +23,7 @@ import type { SqlTag, TransactionClient, } from "./entity-types"; +import { migrateOnStart, shouldMigrateOnStart } from "./migrate-on-start"; import { assertSchemaMatchesDatabase } from "./schema-check"; import { createMutationScope, type MutationScope } from "./scope"; import type { DatabaseHooks } from "./types"; @@ -163,8 +164,9 @@ function buildDatabaseExports(context: ExportContext): DatabaseExports { } /** - * Validate the schema, create one pool-backed API, and verify connectivity and - * that every declared table and column exists. + * Validate the schema, create one pool-backed API, apply committed migrations + * when deployed, and verify connectivity and that every declared table and + * column exists. */ export async function createDatabaseState( schema: TSchema, @@ -188,6 +190,8 @@ export async function createDatabaseState( statement_timeout: STATEMENT_TIMEOUT_MS, idle_in_transaction_session_timeout: IDLE_IN_TRANSACTION_TIMEOUT_MS, }); + // A deployed app applies committed migrations as its own identity before the checks below. + if (shouldMigrateOnStart()) await migrateOnStart(pool, schema); const db = createDrizzleDb(pool, schema); const dataPath = createDrizzleDataPath(db, schema, { columnAccess: "trusted", diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts new file mode 100644 index 000000000..8061c1124 --- /dev/null +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -0,0 +1,78 @@ +import type { Pool } from "pg"; + +import { databaseSetupFailed } from "../../database/errors"; +import { + applyPendingMigrations, + MigrationApplyError, + MigrationBaselineMismatchError, +} from "../../database/migrations/apply"; +import { + MigrationFilesError, + migrationsFolder, +} from "../../database/migrations/paths"; +import type { Schema } from "../../database/schema-builder"; +import { createLogger } from "../../logging/logger"; + +const logger = createLogger("database"); + +/** + * True only inside a deployed Databricks App: not local development, and the + * runtime has set the app's name and its service principal's credentials, as + * Databricks Apps does for every app. `databricks apps run-local` sets the + * name but not the credentials. Locally, `appkit db migrate` applies + * migrations instead. + */ +export function shouldMigrateOnStart( + env: NodeJS.ProcessEnv = process.env, +): boolean { + return ( + env.NODE_ENV !== "development" && + Boolean(env.DATABRICKS_APP_NAME) && + Boolean(env.DATABRICKS_CLIENT_ID) && + Boolean(env.DATABRICKS_CLIENT_SECRET) + ); +} + +/** + * Apply pending committed migrations from /config/database/migrations as + * the app's identity (see database/migrations/ownership.ts). No journal → + * no-op. A failed or unadoptable migration, or a missing or unreadable + * migration file, becomes a setup failure that names it; any other error + * (e.g. no connection) is left to lifecycle's generic sanitizer. + */ +export async function migrateOnStart( + pool: Pick, + schema: Schema, + root: string = process.cwd(), +): Promise { + let result: Awaited>; + try { + result = await applyPendingMigrations(pool, { + migrationsFolder: migrationsFolder(root), + schemaName: schema.$schemaName, + }); + } catch (error) { + if ( + error instanceof MigrationApplyError || + error instanceof MigrationBaselineMismatchError || + error instanceof MigrationFilesError + ) { + throw databaseSetupFailed(error.message); + } + throw error; + } + if (result.adopted.length > 0) { + logger.info( + "Adopted %s in schema %s: its tables already existed", + result.adopted.join(", "), + schema.$schemaName, + ); + } + if (result.applied.length > 0) { + logger.info( + "Applied migrations %s to schema %s", + result.applied.join(", "), + schema.$schemaName, + ); + } +} diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index f1334ecda..9b6f7176a 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -10,10 +10,10 @@ interface CatalogColumn { /** * Confirm every declared table and column exists before routes are published. - * The plugin never migrates, so drift would otherwise surface on each request - * as an undefined-table or undefined-column failure. pg_catalog is read rather - * than information_schema, which hides objects the role cannot access and - * would report a privilege gap as a missing column. + * Even after a deployed app applies its migrations, drift would surface on each + * request as an undefined-table or undefined-column failure, so check up front. + * pg_catalog is read rather than information_schema, which hides objects the + * role cannot access and would report a privilege gap as a missing column. */ export async function assertSchemaMatchesDatabase( dataPath: DataPath, @@ -76,7 +76,7 @@ export async function assertSchemaMatchesDatabase( } if (problems.length > 0) { throw databaseSetupFailed( - `the declared schema does not match the database: ${problems.join("; ")}. Create or migrate these before starting the app; the plugin does not.`, + `the declared schema does not match the database: ${problems.join("; ")}. Create them, or commit migrations under config/database/migrations so the deployed app applies them on start.`, ); } } diff --git a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts index aae7c04d2..0401912f6 100644 --- a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts +++ b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts @@ -9,6 +9,8 @@ const mocks = vi.hoisted(() => ({ createDrizzleDb: vi.fn(), createDrizzleDataPath: vi.fn(), assertSchemaMatchesDatabase: vi.fn(), + shouldMigrateOnStart: vi.fn(() => false), + migrateOnStart: vi.fn(async () => undefined), })); vi.mock("../../../connectors/lakebase", () => ({ initializeLakebasePool: mocks.initializeLakebasePool, @@ -21,6 +23,11 @@ vi.mock("../../../database/runtime/engine/drizzle-data-path", () => ({ vi.mock("../schema-check", () => ({ assertSchemaMatchesDatabase: mocks.assertSchemaMatchesDatabase, })); +// The migrator has its own suite; here only its place in setup matters. +vi.mock("../migrate-on-start", () => ({ + shouldMigrateOnStart: mocks.shouldMigrateOnStart, + migrateOnStart: mocks.migrateOnStart, +})); import { IDLE_IN_TRANSACTION_TIMEOUT_MS, @@ -94,7 +101,11 @@ function arrange(path = fakePath()) { return { pool, db, path, execute }; } -beforeEach(() => vi.clearAllMocks()); +beforeEach(() => { + vi.clearAllMocks(); + // clearAllMocks keeps implementations; a test that turns migration on must not leak it. + mocks.shouldMigrateOnStart.mockReturnValue(false); +}); afterEach(() => vi.restoreAllMocks()); describe("createDatabaseState", () => { @@ -216,6 +227,90 @@ describe("createDatabaseState", () => { expect(pool.end).toHaveBeenCalledTimes(1); }); + test("a deployed app applies migrations after the pool opens, before readiness and the catalog check", async () => { + const order: string[] = []; + const path = fakePath({ + raw: vi.fn(async () => { + order.push("select 1"); + return []; + }) as unknown as DataPath["raw"], + }); + const { pool, execute } = arrange(path); + mocks.initializeLakebasePool.mockImplementationOnce(async () => { + order.push("pool"); + return pool; + }); + mocks.shouldMigrateOnStart.mockReturnValue(true); + mocks.migrateOnStart.mockImplementationOnce(async () => { + order.push("migrate"); + }); + mocks.assertSchemaMatchesDatabase.mockImplementationOnce(async () => { + order.push("catalog"); + }); + + await createDatabaseState(schema, execute); + + expect(order).toEqual(["pool", "migrate", "select 1", "catalog"]); + expect(mocks.migrateOnStart).toHaveBeenCalledWith(pool, schema); + }); + + test("local runs never call the migrator", async () => { + const { execute } = arrange(); + mocks.shouldMigrateOnStart.mockReturnValue(false); + + await createDatabaseState(schema, execute); + + expect(mocks.migrateOnStart).not.toHaveBeenCalled(); + }); + + test("a migration failure keeps its reason, ends the pool and publishes nothing", async () => { + const { pool, path, execute } = arrange(); + const errorLog = vi + .spyOn(console, "error") + .mockImplementation(() => undefined); + mocks.shouldMigrateOnStart.mockReturnValue(true); + const failure = new DatabasePluginError( + "SETUP_FAILED", + "setup", + "Database setup failed: Applying migration 0001_migration failed (SQLSTATE 42501); none were applied.", + ); + mocks.migrateOnStart.mockRejectedValueOnce(failure); + + const error = await createDatabaseState(schema, execute).catch( + (caught) => caught, + ); + + expect(error).toBe(failure); + expect(errorLog.mock.calls.flat().map(String).join(" ")).toContain( + "0001_migration failed (SQLSTATE 42501)", + ); + expect(pool.end).toHaveBeenCalledTimes(1); + expect(path.raw).not.toHaveBeenCalled(); + expect(mocks.assertSchemaMatchesDatabase).not.toHaveBeenCalled(); + }); + + test("an unexpected migrator error is sanitized like any driver error", async () => { + const { pool, execute } = arrange(); + const errorLog = vi + .spyOn(console, "error") + .mockImplementation(() => undefined); + mocks.shouldMigrateOnStart.mockReturnValue(true); + mocks.migrateOnStart.mockRejectedValueOnce( + new Error("secret connection string"), + ); + + const error = await createDatabaseState(schema, execute).catch( + (caught) => caught, + ); + + expect(error).toMatchObject({ category: "SETUP_FAILED", phase: "setup" }); + expect(error.message).toBe("Database setup failed"); + expect(errorLog.mock.calls.flat().map(String).join(" ")).not.toContain( + "secret connection string", + ); + expect(pool.end).toHaveBeenCalledTimes(1); + }); + test("sanitizes connector initialization failures", async () => { const { execute } = arrange(); const errorLog = vi diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts new file mode 100644 index 000000000..cf453a32d --- /dev/null +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -0,0 +1,187 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { applyPendingMigrations } = vi.hoisted(() => ({ + applyPendingMigrations: vi.fn(), +})); +vi.mock("../../../database/migrations/apply", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../database/migrations/apply") + >()), + applyPendingMigrations, +})); + +import { DatabasePluginError } from "../../../database/errors"; +import * as apply from "../../../database/migrations/apply"; +import { MigrationFilesError } from "../../../database/migrations/paths"; +import { defineSchema, id } from "../../../database/schema-builder"; +import { migrateOnStart, shouldMigrateOnStart } from "../migrate-on-start"; + +const schema = defineSchema( + ({ table }) => ({ notes: table("notes", { id: id() }) }), + { schemaName: "app" }, +); +const roots: string[] = []; +const pool = { connect: vi.fn() }; + +function appRoot(): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-migrate-start-")); + roots.push(root); + return root; +} + +beforeEach(async () => { + const actual = await vi.importActual< + typeof import("../../../database/migrations/apply") + >("../../../database/migrations/apply"); + applyPendingMigrations.mockReset(); + applyPendingMigrations.mockImplementation(actual.applyPendingMigrations); + pool.connect.mockReset(); +}); + +afterEach(() => { + vi.restoreAllMocks(); + for (const root of roots.splice(0)) { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +describe("shouldMigrateOnStart", () => { + const credentials = { + DATABRICKS_CLIENT_ID: "sp-client-id", + DATABRICKS_CLIENT_SECRET: "secret", + }; + const app = { DATABRICKS_APP_NAME: "my-app", ...credentials }; + + test.each([ + ["a deployed app", { ...app, NODE_ENV: "production" }, true], + ["a deployed app without NODE_ENV", app, true], + [ + "local development, even with app credentials", + { ...app, NODE_ENV: "development" }, + false, + ], + [ + "`databricks apps run-local`: the app name without its credentials", + { DATABRICKS_APP_NAME: "my-app", NODE_ENV: "production" }, + false, + ], + [ + "a local production start with app credentials in .env but no app name", + { ...credentials, NODE_ENV: "production" }, + false, + ], + [ + "no client secret (a developer's own credentials)", + { + DATABRICKS_APP_NAME: "my-app", + DATABRICKS_CLIENT_ID: "x", + NODE_ENV: "production", + }, + false, + ], + [ + "no client id", + { + DATABRICKS_APP_NAME: "my-app", + DATABRICKS_CLIENT_SECRET: "x", + NODE_ENV: "production", + }, + false, + ], + ["nothing set", {}, false], + ] as const)("%s → %s", (_label, env, expected) => { + expect(shouldMigrateOnStart(env)).toBe(expected); + }); +}); + +describe("migrateOnStart", () => { + test("no committed journal: a no-op that never connects", async () => { + await migrateOnStart(pool, schema, appRoot()); + + expect(pool.connect).not.toHaveBeenCalled(); + }); + + test("applies from /config/database/migrations into the schema's own journal, and logs what it did", async () => { + const root = appRoot(); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + applyPendingMigrations.mockResolvedValueOnce({ + applied: ["0001_migration"], + adopted: ["0000_baseline"], + }); + + await migrateOnStart(pool, schema, root); + + expect(applyPendingMigrations).toHaveBeenCalledWith(pool, { + migrationsFolder: path.join(root, "config/database/migrations"), + schemaName: "app", + }); + const logged = log.mock.calls.map((call) => call.map(String).join(" ")); + expect(logged).toEqual([ + expect.stringContaining( + "Adopted 0000_baseline in schema app: its tables already existed", + ), + expect.stringContaining( + "Applied migrations 0001_migration to schema app", + ), + ]); + }); + + test("nothing pending logs nothing", async () => { + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + applyPendingMigrations.mockResolvedValueOnce({ applied: [], adopted: [] }); + + await migrateOnStart(pool, schema, appRoot()); + + expect(log).not.toHaveBeenCalled(); + }); + + test.each([ + [ + "a failed migration", + new apply.MigrationApplyError(["0001_migration"], "42501"), + "Applying migration 0001_migration failed (SQLSTATE 42501); none were applied.", + ], + [ + "a baseline that only partly matches", + new apply.MigrationBaselineMismatchError("app", [ + "table app.tags does not exist", + ]), + "Cannot adopt 0000_baseline", + ], + [ + "a missing migration file", + new MigrationFilesError( + "Missing /app/config/database/migrations/0001_migration.sql, listed in meta/_journal.json. Restore it from version control.", + ), + "Missing /app/config/database/migrations/0001_migration.sql", + ], + ])( + "%s becomes a setup failure that names it", + async (_label, failure, reason) => { + applyPendingMigrations.mockRejectedValueOnce(failure); + + const error = await migrateOnStart(pool, schema, appRoot()).catch( + (caught: unknown) => caught, + ); + + expect(error).toBeInstanceOf(DatabasePluginError); + expect(error).toMatchObject({ category: "SETUP_FAILED", phase: "setup" }); + expect((error as Error).message).toContain(reason); + // Only the stable message crosses a request boundary. + expect((error as DatabasePluginError).clientMessage).toBe( + "Database setup failed", + ); + }, + ); + + test("any other error is left to lifecycle's sanitizer", async () => { + const raw = new Error("connection reset"); + applyPendingMigrations.mockRejectedValueOnce(raw); + + await expect(migrateOnStart(pool, schema, appRoot())).rejects.toBe(raw); + }); +}); From 19adf06c5f575f1917401926c7cc2733c81ac31b Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 19 Oct 2026 14:07:23 +0200 Subject: [PATCH 002/317] fix(appkit): apply each migration in its own transaction and fail closed - Run and record each pending migration in its own transaction. An enum value added by one migration can now be used by the next (55P04), and a failure keeps the migrations before it. - Compare the committed journal with the recorded rows by hash and created_at. Fail closed on a migration older than the last recorded one; warn on edited migrations and on recorded rows with no committed file. - Read the history without the lock first. Take the lock only when something is pending, then read again. - Bound the wait for the migration lock to 5 minutes and name its holder. Set application_name and client_connection_check_interval. Lower lock_timeout to 5s with three tries per migration. - Migrate on start only with APPKIT_DB_MIGRATE_ON_START=true and service principal credentials. Skip dev- and session- branches; refuse a -pooler host. - Name the failed step and the SQLSTATE or system code. On 42501, name the schema owner and the connecting role. - Add real-Postgres tests gated on APPKIT_TEST_PG_URL; CI runs them against a postgres:17 service. Signed-off-by: ditadi --- .github/workflows/ci.yml | 14 + .../appkit/src/database/migrations/apply.ts | 723 +++++++++---- .../appkit/src/database/migrations/history.ts | 64 ++ .../src/database/migrations/ownership.ts | 58 +- .../appkit/src/database/migrations/paths.ts | 2 +- .../migrations/tests/apply.pg.test.ts | 408 ++++++++ .../database/migrations/tests/apply.test.ts | 984 +++++++++--------- .../src/database/migrations/tests/fixtures.ts | 86 ++ .../database/migrations/tests/history.test.ts | 75 ++ .../migrations/tests/ownership.test.ts | 28 +- .../src/plugins/database/migrate-on-start.ts | 79 +- .../src/plugins/database/schema-check.ts | 2 +- .../database/tests/migrate-on-start.test.ts | 160 ++- 13 files changed, 1909 insertions(+), 774 deletions(-) create mode 100644 packages/appkit/src/database/migrations/history.ts create mode 100644 packages/appkit/src/database/migrations/tests/apply.pg.test.ts create mode 100644 packages/appkit/src/database/migrations/tests/fixtures.ts create mode 100644 packages/appkit/src/database/migrations/tests/history.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 23bb21c94..8a2cea71f 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/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index a4e6dd704..bc9a1f99d 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -1,18 +1,25 @@ import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; import { readMigrationFiles } from "drizzle-orm/migrator"; -import { drizzle } from "drizzle-orm/node-postgres"; -import { migrate } from "drizzle-orm/node-postgres/migrator"; import type { Pool, PoolClient } from "pg"; import { createLogger } from "../../logging/logger"; -import { ownershipHint } from "./ownership"; +import { + type MigrationFile, + type RecordedMigration, + reconcileMigrations, +} from "./history"; +import { + INSUFFICIENT_PRIVILEGE, + ownershipHint, + schemaOwnership, +} from "./ownership"; import { BASELINE_TAG, type Journal, - type JournalEntry, MIGRATIONS_TABLE, MigrationFilesError, readJournal, @@ -26,6 +33,10 @@ interface ApplyMigrationsOptions { 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; } interface ApplyMigrationsResult { @@ -33,59 +44,95 @@ interface ApplyMigrationsResult { 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; } -/** lock_not_available: a table lock was not granted within LOCK_TIMEOUT. */ -const LOCK_NOT_AVAILABLE = "55P03"; +/** A deploy waits this long for another instance to finish migrating, then fails. */ +const LOCK_WAIT_MS = 5 * 60_000; /** - * Longest wait for a table lock while migrating. Past it the migration fails; - * waiting longer would queue every other query on that table behind it. + * 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 = "30s"; +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"; -function failureHint(code: string | undefined): string | undefined { - if (code === LOCK_NOT_AVAILABLE) { - return `Another session held a lock on a table this migration changes for over ${LOCK_TIMEOUT}; deploy again once it finishes.`; - } - return ownershipHint(code); -} +/** lock_not_available: a table lock was not granted within the lock timeout. */ +const LOCK_NOT_AVAILABLE = "55P03"; /** - * A statement failed while migrating. Pending migrations run in one drizzle-orm - * migrator transaction, so none of them were applied; a baseline adopted just - * before commits on its own and stays recorded. + * 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 { - /** Tags that were being applied; empty when reading the recorded migrations failed. */ + /** 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; - /** Tags this run recorded as applied before the failure. */ - readonly adopted: readonly string[]; - constructor( - pending: readonly string[], - code: string | undefined, - options: { cause?: unknown; adopted?: readonly string[] } = {}, - ) { - const adopted = options.adopted ?? []; - const sqlState = code ? ` (SQLSTATE ${code})` : ""; - const failure = - pending.length > 0 - ? `Applying migration${pending.length === 1 ? "" : "s"} ${pending.join(", ")} failed${sqlState}; none were applied.` - : `Reading the recorded migrations in ${MIGRATIONS_TABLE} failed${sqlState}; none were applied.`; - const kept = - adopted.length > 0 - ? ` ${adopted.join(", ")} stays recorded as applied: its tables already existed.` + 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 hint = failureHint(code); - super(`${failure}${kept}${hint ? ` ${hint}` : ""}`, { - cause: options.cause, - }); + 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.code = code; + this.applied = Object.freeze([...applied]); this.adopted = Object.freeze([...adopted]); + this.code = code; } } @@ -106,26 +153,67 @@ export class MigrationBaselineMismatchError extends Error { } } +/** + * Committed migrations are older than the last one the database recorded and + * were never applied, so they would never run. Nothing was applied. + */ +export class MigrationHistoryError extends Error { + readonly stranded: readonly string[]; + + constructor(schemaName: string, stranded: readonly string[], last: string) { + const many = stranded.length > 1; + super( + `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. ` + + `Delete ${many ? "their" : "its"} .sql file, snapshot and journal entry, generate the migration again from schema.ts, and deploy again. ` + + "No migration was applied.", + ); + this.name = "MigrationHistoryError"; + this.stranded = Object.freeze([...stranded]); + } +} + +/** 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 wraps driver errors; the SQLSTATE lives somewhere on the cause chain. */ -function sqlStateOf(error: unknown): string | undefined { +/** 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; - // No SQLSTATE class starts with "E"; Node system errors (EPIPE, EPERM, …) all do. - if (typeof code === "string" && SQLSTATE.test(code) && code[0] !== "E") { - return 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)); +} + 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") @@ -137,15 +225,40 @@ export function migrationLockKey(schemaName: string): string { type QueryClient = Pick; -/** - * `created_at` of the last migration the database recorded; null when none is. - * An empty journal table counts as nothing recorded: drizzle-orm creates it - * before its transaction, so a failed first deploy leaves one behind. - */ -async function lastRecordedMigration( +/** 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 = path.join(folder, `${entry.tag}.sql`); + if (!fs.existsSync(file)) { + throw new MigrationFilesError( + `Missing ${file}, listed in meta/_journal.json. Restore it from version control.`, + ); + } + } + // drizzle-orm's reader, so `hash` matches what drizzle-kit records. + const files = readMigrationFiles({ migrationsFolder: folder }); + 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, + statements: file.sql, + }; + }); +} + +/** The journal table's rows; none when the table does not exist yet. */ +async function readRecordedMigrations( client: QueryClient, schemaName: string, -): Promise { +): Promise { // pg_catalog needs no privileges, so a missing grant is not mistaken for a missing table. const table = await client.query( `select 1 from pg_catalog.pg_class c @@ -153,99 +266,103 @@ async function lastRecordedMigration( where n.nspname = $1 and c.relname = $2`, [schemaName, MIGRATIONS_TABLE], ); - if (table.rows.length === 0) return null; - const last = await client.query<{ last: string | number | null }>( - `select max(created_at) as last from ${quoteIdentifier(schemaName)}.${quoteIdentifier(MIGRATIONS_TABLE)}`, - ); - const value = last.rows[0]?.last; - return value === null || value === undefined ? null : Number(value); + if (table.rows.length === 0) 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), + })); } -/** - * Journal entries newer than the last recorded migration: drizzle-orm's own - * rule, so this agrees with what its migrator runs. - * - * Known gap, shared with drizzle-orm: an entry older than the last recorded one - * (e.g. merged from a parallel branch) is never applied, and an applied - * migration edited later goes unnoticed. Comparing the recorded hashes with the - * journal would catch both. - */ -function pendingEntries( - journal: Journal, - lastRecorded: number | null, -): JournalEntry[] { - if (lastRecorded === null) return journal.entries; - return journal.entries.filter((entry) => entry.when > lastRecorded); +/** 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. + logger.debug( + "client_connection_check_interval not set: %s", + error instanceof Error ? error.message : String(error), + ); + } } -/** Fail before connecting, naming the file, rather than inside drizzle-orm's migrator. */ -function assertMigrationFiles(folder: string, journal: Journal): void { - for (const entry of journal.entries) { - const file = path.join(folder, `${entry.tag}.sql`); - if (!fs.existsSync(file)) { - throw new MigrationFilesError( - `Missing ${file}, listed in meta/_journal.json. Restore it from version control.`, - ); - } - } +/** 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(", ")})` : ""}`; } /** - * Run `work` on one dedicated connection under the per-schema advisory lock, - * with no statement timeout and at most LOCK_TIMEOUT per table lock. The - * connection is always unlocked, reset and released; a connection whose - * cleanup fails is destroyed, not reused. + * 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 withMigrationLock( - pool: Pick, +async function acquireMigrationLock( + client: QueryClient, schemaName: string, - work: (client: PoolClient) => Promise, -): Promise { - const lockKey = migrationLockKey(schemaName); - const client = await pool.connect(); - let locked = false; - try { - await client.query("SET statement_timeout = 0"); - const attempt = await client.query<{ locked: boolean }>( + 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", - [lockKey], + [key], ); - if (!attempt.rows[0]?.locked) { + 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 instance to finish migrating schema %s", + "Waiting for another session to finish migrating schema %s (lock held by %s)", schemaName, + holder ?? "an unknown session", ); - await client.query("select pg_catalog.pg_advisory_lock($1::bigint)", [ - lockKey, - ]); + reportAt = Date.now() + LOCK_REPORT_MS; } - locked = true; - // Only now: lock_timeout would also cut short the wait for the advisory lock. - await client.query(`SET lock_timeout = '${LOCK_TIMEOUT}'`); - return await work(client); - } finally { - const cleanup: Array<() => Promise> = []; - if (locked) { - cleanup.push(() => - client.query("select pg_catalog.pg_advisory_unlock($1::bigint)", [ - lockKey, - ]), - ); - } - cleanup.push(() => client.query("RESET lock_timeout")); - cleanup.push(() => client.query("RESET statement_timeout")); - - let cleanupError: Error | undefined; - for (const step of cleanup) { - try { - await step(); - } catch (error) { - cleanupError ??= - error instanceof Error ? error : new Error(String(error)); - } - } - // A connection that may still hold the lock or the session settings must not be reused. - client.release(cleanupError); + await sleep(Math.min(LOCK_POLL_MS, waitMs - waited)); } } @@ -263,6 +380,74 @@ async function inTransaction( } } +/** drizzle-orm's own journal table, so drizzle-kit reads and extends it too. */ +async function ensureJournalTable( + client: QueryClient, + schemaName: string, +): Promise { + await client.query( + `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(schemaName)}`, + ); + await client.query( + `CREATE TABLE IF NOT EXISTS ${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, @@ -302,7 +487,7 @@ type BaselineState = async function baselineState( client: QueryClient, options: ApplyMigrationsOptions, - baseline: JournalEntry, + baseline: MigrationFile, ): Promise { const declared = snapshotTables( options.migrationsFolder, @@ -351,52 +536,60 @@ async function baselineState( : { kind: "present" }; } -/** - * Record migrations as applied without running them: create the journal table - * as drizzle-orm's migrator does, then insert one row per tag with the - * migrator's own hash (sha256 of the .sql file) and `created_at` (the journal's - * `when`). Runs on the caller's connection; wrap it in a transaction. - */ -async function recordMigrationsApplied( - client: QueryClient, - options: ApplyMigrationsOptions, - journal: Journal, - tags: readonly string[], +/** 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 { - // One file per journal entry, in journal order. - const files = readMigrationFiles({ - migrationsFolder: options.migrationsFolder, - }); - const schema = quoteIdentifier(options.schemaName); - const table = `${schema}.${quoteIdentifier(MIGRATIONS_TABLE)}`; - await client.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`); - // drizzle-orm's own definition, so its migrator later reads and extends this table. - await client.query( - `CREATE TABLE IF NOT EXISTS ${table} ( - id SERIAL PRIMARY KEY, - hash text NOT NULL, - created_at bigint - )`, - ); - for (const tag of tags) { - const index = journal.entries.findIndex((entry) => entry.tag === tag); - const file = files[index]; - if (index < 0 || !file) { - throw new Error(`Migration ${tag} is not in the journal.`); - } - await client.query( - `insert into ${table} ("hash", "created_at") values($1, $2)`, - [file.hash, file.folderMillis], + 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`; } /** * Apply every committed migration the database has not recorded yet. * - * Runs on one dedicated connection as the connecting identity, which owns what - * it creates (see ownership.ts), under a per-schema advisory lock; drizzle-orm's - * migrator runs only when something is pending. + * 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. An applied migration whose file + * changed, and recorded migrations that are not committed, are logged. * * 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 @@ -410,60 +603,150 @@ export async function applyPendingMigrations( ): Promise { const journal = readJournal(options.migrationsFolder); if (!journal || journal.entries.length === 0) { - return { applied: [], adopted: [] }; + return { applied: [], adopted: [], edited: [], unknown: 0, lockWaitMs: 0 }; } - assertMigrationFiles(options.migrationsFolder, journal); + const files = readMigrations(options.migrationsFolder, journal); + const { schemaName } = options; + const lockWaitMs = options.lockWaitMs ?? LOCK_WAIT_MS; + const lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS; - return withMigrationLock(pool, options.schemaName, async (client) => { - const adopted: string[] = []; - // What the failing step was applying, for the error. - let applying: readonly string[] = []; - try { - const lastRecorded = await lastRecordedMigration( - client, - options.schemaName, + 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; + try { + let history = reconcileMigrations( + files, + await readRecordedMigrations(client, schemaName), + ); + let waitedMs = 0; + if (history.pending.length > 0 && history.stranded.length === 0) { + 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), ); - let pending = pendingEntries(journal, lastRecorded); - if (pending.length === 0) return { applied: [], adopted }; - - const first = journal.entries[0]; - if (lastRecorded === null && first?.tag === BASELINE_TAG) { - applying = [BASELINE_TAG]; - const state = await baselineState(client, options, first); - if (state.kind === "partial") { - throw new MigrationBaselineMismatchError( - options.schemaName, - state.problems, - ); - } - if (state.kind === "present") { - await inTransaction(client, () => - recordMigrationsApplied(client, options, journal, [BASELINE_TAG]), - ); - adopted.push(BASELINE_TAG); - pending = pending.filter((entry) => entry.tag !== BASELINE_TAG); - if (pending.length === 0) return { applied: [], adopted }; - } - } + } - applying = pending.map((entry) => entry.tag); - await migrate(drizzle({ client }), { - migrationsFolder: options.migrationsFolder, - migrationsSchema: options.schemaName, - migrationsTable: MIGRATIONS_TABLE, - }); - return { applied: applying, adopted }; - } catch (error) { - if ( - error instanceof MigrationBaselineMismatchError || - error instanceof MigrationFilesError - ) { - throw error; + if (history.stranded.length > 0) { + const last = + files.find((file) => file.when === history.lastRecorded)?.tag ?? + `the migration recorded at ${new Date(history.lastRecorded ?? 0).toISOString()}`; + throw new MigrationHistoryError(schemaName, tags(history.stranded), last); + } + 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); + 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(); } - throw new MigrationApplyError(applying, sqlStateOf(error), { - cause: error, - adopted, - }); } - }); + + 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 ( + error instanceof MigrationBaselineMismatchError || + error instanceof MigrationFilesError || + error instanceof MigrationHistoryError + ) { + 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); + } + 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..c7ca35cda --- /dev/null +++ b/packages/appkit/src/database/migrations/history.ts @@ -0,0 +1,64 @@ +/** 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; + /** sha256 of the .sql file, recorded as `hash`. */ + readonly hash: 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 compared with what the database recorded. */ +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[]; + /** 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; +} + +/** + * Match each committed migration with a recorded row by `when` = `created_at`, + * the pair drizzle-orm's migrator writes, then compare hashes. + */ +export function reconcileMigrations( + files: readonly MigrationFile[], + recorded: readonly RecordedMigration[], +): MigrationHistory { + const hashAt = new Map(); + for (const row of recorded) { + if (row.createdAt !== null) hashAt.set(row.createdAt, row.hash); + } + const lastRecorded = hashAt.size > 0 ? Math.max(...hashAt.keys()) : null; + + const pending: MigrationFile[] = []; + const stranded: MigrationFile[] = []; + const edited: MigrationFile[] = []; + for (const file of files) { + const hash = hashAt.get(file.when); + if (hash === undefined) { + if (lastRecorded === null || file.when > lastRecorded) pending.push(file); + else stranded.push(file); + } else if (hash !== file.hash) { + edited.push(file); + } + } + const committed = new Set(files.map((file) => file.when)); + const unknown = recorded.filter( + (row) => row.createdAt === null || !committed.has(row.createdAt), + ); + return { pending, stranded, edited, unknown, lastRecorded }; +} diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index 606efb1d1..ec2dd75ac 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -1,18 +1,66 @@ // 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 owner role is not -// possible: Lakebase rejects `GRANT … TO databricks_superuser`. +// 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 …". */ -const INSUFFICIENT_PRIVILEGE = "42501"; +export const INSUFFICIENT_PRIVILEGE = "42501"; + +/** Who owns the app schema, next to who is connected; owner is null when the schema does not exist. */ +interface SchemaOwnership { + readonly schemaName: string; + readonly owner: string | null; + readonly currentUser: string; +} + +/** Read the app schema's owner. pg_catalog needs no privileges. */ +export async function schemaOwnership( + client: Pick, + schemaName: string, +): Promise { + const { rows } = await client.query<{ + owner: string | 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, + current_user::text as current_user`, + [schemaName], + ); + return { + schemaName, + owner: rows[0]?.owner ?? null, + currentUser: rows[0]?.current_user ?? "", + }; +} /** How to fix a migration that failed for lack of privileges; undefined for any other SQLSTATE. */ -export function ownershipHint(code: string | undefined): string | undefined { +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 && ownership.owner !== ownership.currentUser) { + return ( + `Schema "${ownership.schemaName}" is owned by "${ownership.owner}", but the app connects as "${ownership.currentUser}". ` + + "This happens when the app's database resource was removed and added again, or the app was recreated with a new service principal: " + + `Lakebase hands the objects to another role. Have "${ownership.owner}" transfer the schema and its tables to "${ownership.currentUser}" ` + + "(ALTER … OWNER TO), or set another schemaName in schema.ts." + ); + } 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, " + - "and if another role created the schema, use another schemaName in schema.ts or have that role transfer the schema and its objects." + "and if another role created an object the migration changes, have that role transfer it to the app's service principal." ); } diff --git a/packages/appkit/src/database/migrations/paths.ts b/packages/appkit/src/database/migrations/paths.ts index e331080b0..8d5126076 100644 --- a/packages/appkit/src/database/migrations/paths.ts +++ b/packages/appkit/src/database/migrations/paths.ts @@ -34,7 +34,7 @@ export function migrationsFolder(root: string): string { } /** Path of the journal inside a migrations folder. */ -function journalFile(folder: string): string { +export function journalFile(folder: string): string { return path.join(folder, "meta", "_journal.json"); } 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..7e4875576 --- /dev/null +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -0,0 +1,408 @@ +import { randomUUID } from "node:crypto"; + +import { Pool, type PoolClient } from "pg"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + test, + vi, +} from "vitest"; + +import { + applyPendingMigrations, + MigrationApplyError, + MigrationHistoryError, + migrationLockKey, +} from "../apply"; +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("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({ 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("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"]); + }); +}); diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 4fc178d14..6892e5df0 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -1,6 +1,4 @@ -import { createHash } from "node:crypto"; import fs from "node:fs"; -import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, test, vi } from "vitest"; @@ -9,103 +7,52 @@ import { applyPendingMigrations, MigrationApplyError, MigrationBaselineMismatchError, + MigrationHistoryError, migrationLockKey, } from "../apply"; -import { type Journal, MigrationFilesError } from "../paths"; - -const folders: string[] = []; - -/** Write a v7 journal with one SQL file per entry, the way drizzle-kit lays them out. */ -function migrations( - entries: Array<{ - tag: string; - when: number; - sql: string[]; - /** Tables (name → columns) for meta/NNNN_snapshot.json. */ - snapshot?: Record; - }>, -) { - 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]) => [ - `app.${name}`, - { - name, - schema: "app", - 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; -} +import { MigrationFilesError } from "../paths"; +import { + hashOf, + removeMigrationFolders, + writeMigrations as migrations, +} from "./fixtures"; afterEach(() => { vi.restoreAllMocks(); - for (const folder of folders.splice(0)) { - fs.rmSync(folder, { recursive: true, force: true }); - } + removeMigrationFolders(); }); +interface JournalRow { + hash: string; + created_at: number | null; +} + interface FakeState { - journalTableExists: boolean; - lastCreatedAt: number | null; + /** 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]>; - /** Another instance holds the migration lock, so the first try fails. */ + /** 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. Its class name must not contain - * "Pool": drizzle-orm would take it for a pool and call connect() on it. + * A pg PoolClient that records every statement and keeps journal inserts + * only when their transaction commits. */ class RecordingClient { readonly statements: string[] = []; - /** Parameters of each journal insert. */ - readonly recorded: unknown[][] = []; released: { error: unknown } | undefined; + private uncommitted: JournalRow[] | undefined; + private failures = 0; constructor(private readonly state: FakeState) {} @@ -116,17 +63,43 @@ class RecordingClient { 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)) { - throw Object.assign(new Error("relation already exists"), { + 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("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]) => ({ @@ -136,23 +109,16 @@ class RecordingClient { }; } if (text.includes("pg_catalog.pg_class")) { - return { rows: this.state.journalTableExists ? [{ one: 1 }] : [] }; - } - if (text.startsWith(`insert into "app"."__drizzle_migrations"`)) { - this.recorded.push(params ?? []); - this.state.journalTableExists = true; - this.state.lastCreatedAt = Number(params?.[1]); + return { rows: this.state.recorded ? [{ one: 1 }] : [] }; } - if (text.startsWith("select max(created_at)")) { - return { rows: [{ last: this.state.lastCreatedAt }] }; + if (text.startsWith("select hash, created_at")) { + return { rows: this.state.recorded ?? [] }; } - if (text.includes("order by created_at desc limit 1")) { - return { - rows: - this.state.lastCreatedAt === null - ? [] - : [{ id: 1, hash: "h", created_at: this.state.lastCreatedAt }], - }; + if (text.startsWith(`insert into "app"."__drizzle_migrations"`)) { + this.uncommitted?.push({ + hash: String(params?.[0]), + created_at: Number(params?.[1]), + }); } return { rows: [] }; } @@ -167,6 +133,7 @@ function fakePool(state: FakeState) { let connects = 0; return { client, + state, connects: () => connects, pool: { connect: async () => { @@ -194,213 +161,490 @@ const twoMigrations = () => }, ]); +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_lock(")) return "lock"; if (statement.includes("pg_advisory_unlock(")) return "unlock"; + if (statement.includes("pg_catalog.pg_locks")) return "lock holder?"; + if (statement.includes("pg_get_userbyid")) return "schema owner?"; if (statement.includes("pg_catalog.pg_attribute")) return "baseline tables?"; if (statement.includes("pg_catalog.pg_class")) return "journal table?"; - if (statement.startsWith("select max(created_at)")) return "last applied?"; + if (statement.startsWith("select hash, created_at")) return "recorded?"; + if (statement.startsWith(`CREATE SCHEMA IF NOT EXISTS`)) + return "create schema"; + if (statement.startsWith(`CREATE TABLE IF NOT EXISTS "app"."__drizzle`)) + 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("applies every pending migration as the connecting identity under the advisory lock, then unlocks and releases", async () => { + test("reads without the lock, then applies each pending migration in its own transaction under it", async () => { const folder = twoMigrations(); - const { pool, client } = fakePool({ - journalTableExists: false, - lastCreatedAt: null, - }); + const { pool, client, state } = fakePool({ recorded: null }); - const result = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }); + const result = await applyPendingMigrations(pool, options(folder)); - expect(result.applied).toEqual(["0000_migration", "0001_migration"]); + expect(result).toEqual({ + applied: ["0000_migration", "0001_migration"], + adopted: [], + edited: [], + unknown: 0, + lockWaitMs: expect.any(Number), + }); expect(steps(client.statements)).toEqual([ - "SET statement_timeout = 0", - "try lock", - "SET lock_timeout = '30s'", "journal table?", - // drizzle-orm's migrator as the connecting identity (no SET ROLE), journal in the app schema: - `CREATE SCHEMA IF NOT EXISTS "app"`, - `CREATE TABLE IF NOT EXISTS "app"."__drizzle_migrations" ( id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint )`, - `select id, hash, created_at from "app"."__drizzle_migrations" order by created_at desc limit 1`, + ...SESSION_SETUP, + "journal table?", "begin", + "create schema", + "create journal", `CREATE TABLE "app"."notes" ("id" integer);`, - `insert into "app"."__drizzle_migrations" ("hash", "created_at") values($1, $2)`, + "record", + "commit", + "begin", + "create schema", + "create journal", `ALTER TABLE "app"."notes" ADD COLUMN "body" text;`, `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`, - `insert into "app"."__drizzle_migrations" ("hash", "created_at") values($1, $2)`, + "record", "commit", - "unlock", - "RESET lock_timeout", - "RESET statement_timeout", + ...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 entries newer than the last recorded migration", async () => { + test("applies only migrations newer than the last recorded one", async () => { const folder = twoMigrations(); const { pool, client } = fakePool({ - journalTableExists: true, - lastCreatedAt: 1000, + recorded: [{ hash: hashOf(folder, "0000_migration"), created_at: 1000 }], }); - const result = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }); + const result = await applyPendingMigrations(pool, options(folder)); expect(result.applied).toEqual(["0001_migration"]); expect(client.statements).not.toContain( `CREATE TABLE "app"."notes" ("id" integer);`, ); - expect(client.statements).toContain( - `ALTER TABLE "app"."notes" ADD COLUMN "body" text;`, - ); }); - test("with nothing pending, issues no migration SQL", async () => { + test("with nothing pending, it only reads: no lock, no session settings", async () => { const folder = twoMigrations(); const { pool, client } = fakePool({ - journalTableExists: true, - lastCreatedAt: 2000, + recorded: [ + { hash: hashOf(folder, "0000_migration"), created_at: 1000 }, + { hash: hashOf(folder, "0001_migration"), created_at: 2000 }, + ], }); - const result = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }); + const result = await applyPendingMigrations(pool, options(folder)); expect(result.applied).toEqual([]); - expect(steps(client.statements)).toEqual([ - "SET statement_timeout = 0", - "try lock", - "SET lock_timeout = '30s'", - "journal table?", - "last applied?", - "unlock", - "RESET lock_timeout", - "RESET statement_timeout", - ]); + 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"); + }); + test("without a journal it never connects", async () => { - const folder = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-apply-")); - folders.push(folder); - const fake = fakePool({ journalTableExists: false, lastCreatedAt: null }); + const folder = migrations([]); + fs.rmSync(path.join(folder, "meta"), { recursive: true }); + const fake = fakePool({ recorded: null }); await expect( - applyPendingMigrations(fake.pool, { - migrationsFolder: folder, - schemaName: "app", - }), - ).resolves.toEqual({ applied: [], adopted: [] }); + applyPendingMigrations(fake.pool, options(folder)), + ).resolves.toEqual({ + applied: [], + adopted: [], + edited: [], + unknown: 0, + lockWaitMs: 0, + }); expect(fake.connects()).toBe(0); }); - test("a failing statement rolls back all pending migrations and still unlocks and releases", async () => { + test("a failing migration rolls back alone: the ones before it stay applied", async () => { const folder = twoMigrations(); - const { pool, client } = fakePool({ - journalTableExists: false, - lastCreatedAt: null, + const { pool, client, state } = fakePool({ + recorded: null, failOn: /ADD COLUMN "title"/, }); - const error = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }).catch((caught: unknown) => caught); + const error = await applyPendingMigrations(pool, options(folder)).catch( + (caught: unknown) => caught, + ); expect(error).toBeInstanceOf(MigrationApplyError); expect(error).toMatchObject({ - pending: ["0000_migration", "0001_migration"], + failed: "0001_migration", + applied: ["0000_migration"], + pending: ["0001_migration"], code: "42P07", }); expect((error as Error).message).toBe( - "Applying migrations 0000_migration, 0001_migration failed (SQLSTATE 42P07); none were applied.", + "Migration 0001_migration failed (SQLSTATE 42P07) and was rolled back. Applied before the failure: 0000_migration. Not applied: 0001_migration.", ); - expect(steps(client.statements).slice(-5)).toEqual([ - `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`, + expect(state.recorded).toEqual([ + { hash: hashOf(folder, "0000_migration"), created_at: 1000 }, + ]); + expect(steps(client.statements).slice(-6)).toEqual([ "rollback", - "unlock", - "RESET lock_timeout", - "RESET statement_timeout", + ...SESSION_CLEANUP, ]); expect(client.released).toEqual({ error: undefined }); }); - test("an ownership failure (42501) names the branch-owner rule and the fix", async () => { + 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({ stranded: ["0001_parallel"] }); + expect((error as Error).message).toMatch( + /^Migration 0001_parallel is older than 0002_b, which schema "app" already recorded, and was never 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("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({ - journalTableExists: false, - lastCreatedAt: null, + 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", + ); + }); + + 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: "42501", + failCode: "55P03", }); const error = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", + ...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", async () => { + const folder = twoMigrations(); + 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", + ); + }); + + 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( - /^Applying migrations 0000_migration, 0001_migration failed \(SQLSTATE 42501\); none were applied\. The connecting role lacks a privilege this migration needs: /, + /^Reading the recorded migrations failed \(SQLSTATE 42501\)\. No migration was applied\. Schema "app" is owned by "someone-else"/, + ); + }); + + 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({ - journalTableExists: false, - lastCreatedAt: null, + recorded: null, failCleanupOn: /pg_advisory_unlock/, }); - await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }); + await applyPendingMigrations(pool, options(folder)); // The remaining cleanup still runs. - expect(steps(client.statements).slice(-3)).toEqual([ - "unlock", - "RESET lock_timeout", - "RESET statement_timeout", - ]); + expect(steps(client.statements).slice(-5)).toEqual(SESSION_CLEANUP); expect(client.released?.error).toBeInstanceOf(Error); }); - test("a failure before the lock is held releases without unlocking", async () => { + test("a missing .sql file fails before connecting, naming the file", async () => { const folder = twoMigrations(); - const { pool, client } = fakePool({ - journalTableExists: false, - lastCreatedAt: null, - failOn: /pg_try_advisory_lock/, - }); + fs.rmSync(path.join(folder, "0001_migration.sql")); + const fake = fakePool({ recorded: null }); - await expect( - applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }), - ).rejects.toThrow("relation already exists"); - expect(steps(client.statements)).toEqual([ - "SET statement_timeout = 0", - "try lock", - "RESET lock_timeout", - "RESET statement_timeout", - ]); - expect(client.released).toEqual({ error: undefined }); + 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([ + [ + "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", () => { @@ -436,21 +680,20 @@ const baselineThenMigration = () => }, ]); +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({ - journalTableExists: false, - lastCreatedAt: null, - catalog: [], - }); + const { pool, client } = fakePool({ recorded: null, catalog: [] }); - const result = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }); + const result = await applyPendingMigrations(pool, options(folder)); - expect(result).toEqual({ + expect(result).toMatchObject({ applied: ["0000_baseline", "0001_migration"], adopted: [], }); @@ -459,22 +702,14 @@ describe("applyPendingMigrations — baseline adoption", () => { test("every baseline table and column exists: the baseline is recorded, not run, and later migrations apply", async () => { const folder = baselineThenMigration(); - const { pool, client } = fakePool({ - journalTableExists: false, - lastCreatedAt: null, - catalog: [ - ["notes", "id"], - ["notes", "body"], - ["tags", "id"], - ], + const { pool, client, state } = fakePool({ + recorded: null, + catalog: BASELINE_CATALOG, }); - const result = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }); + const result = await applyPendingMigrations(pool, options(folder)); - expect(result).toEqual({ + expect(result).toMatchObject({ applied: ["0001_migration"], adopted: ["0000_baseline"], }); @@ -483,27 +718,10 @@ describe("applyPendingMigrations — baseline adoption", () => { `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`, ); // The adopted row carries exactly what drizzle-orm's migrator would have written. - const baselineFile = fs.readFileSync( - path.join(folder, "0000_baseline.sql"), - "utf-8", - ); - expect(client.recorded[0]).toEqual([ - createHash("sha256").update(baselineFile).digest("hex"), - 1000, - ]); - expect(steps(client.statements).slice(0, 10)).toEqual([ - "SET statement_timeout = 0", - "try lock", - "SET lock_timeout = '30s'", - "journal table?", - "baseline tables?", - "begin", - `CREATE SCHEMA IF NOT EXISTS "app"`, - `CREATE TABLE IF NOT EXISTS "app"."__drizzle_migrations" ( id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint )`, - `insert into "app"."__drizzle_migrations" ("hash", "created_at") values($1, $2)`, - "commit", - ]); - expect(client.released).toEqual({ error: undefined }); + expect(state.recorded?.[0]).toEqual({ + hash: hashOf(folder, "0000_baseline"), + created_at: 1000, + }); }); test("adopting a lone baseline applies nothing else", async () => { @@ -515,41 +733,23 @@ describe("applyPendingMigrations — baseline adoption", () => { snapshot: { notes: ["id", "body"], tags: ["id"] }, }, ]); - const { pool, client } = fakePool({ - journalTableExists: false, - lastCreatedAt: null, - catalog: [ - ["notes", "id"], - ["notes", "body"], - ["tags", "id"], - ], - }); + const { pool } = fakePool({ recorded: null, catalog: BASELINE_CATALOG }); await expect( - applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }), - ).resolves.toEqual({ applied: [], adopted: ["0000_baseline"] }); - expect(client.statements.slice(-3)).toEqual([ - expect.stringContaining("pg_advisory_unlock"), - "RESET lock_timeout", - "RESET statement_timeout", - ]); + 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 } = fakePool({ - journalTableExists: false, - lastCreatedAt: null, + const { pool, client, state } = fakePool({ + recorded: null, catalog: [["notes", "id"]], }); - const error = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }).catch((caught: unknown) => caught); + const error = await applyPendingMigrations(pool, options(folder)).catch( + (caught: unknown) => caught, + ); expect(error).toBeInstanceOf(MigrationBaselineMismatchError); expect((error as MigrationBaselineMismatchError).problems).toEqual([ @@ -559,40 +759,34 @@ describe("applyPendingMigrations — baseline adoption", () => { expect((error as Error).message).toMatch( /^Cannot adopt 0000_baseline: schema "app" has no recorded migrations and only part of the baseline: /, ); - expect(client.recorded).toEqual([]); + expect(state.recorded).toBeNull(); expect(client.statements).not.toContain("begin"); - expect(steps(client.statements).slice(-3)).toEqual([ - "unlock", - "RESET lock_timeout", - "RESET statement_timeout", - ]); 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({ - journalTableExists: false, - lastCreatedAt: null, - catalog: [ - ["notes", "id"], - ["notes", "body"], - ["tags", "id"], - ], + recorded: null, + catalog: BASELINE_CATALOG, // The schema belongs to another role, so the journal table cannot be created in it. failOn: /^CREATE TABLE IF NOT EXISTS "app"\."__drizzle_migrations"/, failCode: "42501", + ownership: { owner: "someone-else", current_user: "app-sp" }, }); - const error = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }).catch((caught: unknown) => caught); + const error = await applyPendingMigrations(pool, options(folder)).catch( + (caught: unknown) => caught, + ); expect(error).toBeInstanceOf(MigrationApplyError); - expect(error).toMatchObject({ pending: ["0000_baseline"], code: "42501" }); + expect(error).toMatchObject({ + failed: "0000_baseline", + pending: ["0000_baseline", "0001_migration"], + code: "42501", + }); expect((error as Error).message).toContain( - "On the deploy branch that role is the app's service principal", + `Schema "app" is owned by "someone-else"`, ); expect(client.statements).toContain("rollback"); expect(client.statements).not.toContain( @@ -603,40 +797,25 @@ describe("applyPendingMigrations — baseline adoption", () => { test("with a recorded migration, the baseline is never adopted", async () => { const folder = baselineThenMigration(); const { pool, client } = fakePool({ - journalTableExists: true, - lastCreatedAt: 1000, + recorded: [{ hash: hashOf(folder, "0000_baseline"), created_at: 1000 }], catalog: [["notes", "id"]], }); await expect( - applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }), - ).resolves.toEqual({ applied: ["0001_migration"], adopted: [] }); + 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, left by a failed first deploy, still adopts the baseline", async () => { + test("an empty journal table still adopts the baseline", async () => { const folder = baselineThenMigration(); - const { pool } = fakePool({ - journalTableExists: true, - lastCreatedAt: null, - catalog: [ - ["notes", "id"], - ["notes", "body"], - ["tags", "id"], - ], - }); + const { pool } = fakePool({ recorded: [], catalog: BASELINE_CATALOG }); await expect( - applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }), - ).resolves.toEqual({ + applyPendingMigrations(pool, options(folder)), + ).resolves.toMatchObject({ applied: ["0001_migration"], adopted: ["0000_baseline"], }); @@ -644,21 +823,15 @@ describe("applyPendingMigrations — baseline adoption", () => { test("a migration failing after the adoption says the baseline stays recorded", async () => { const folder = baselineThenMigration(); - const { pool, client } = fakePool({ - journalTableExists: false, - lastCreatedAt: null, - catalog: [ - ["notes", "id"], - ["notes", "body"], - ["tags", "id"], - ], + const { pool, state } = fakePool({ + recorded: null, + catalog: BASELINE_CATALOG, failOn: /ADD COLUMN "title"/, }); - const error = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }).catch((caught: unknown) => caught); + const error = await applyPendingMigrations(pool, options(folder)).catch( + (caught: unknown) => caught, + ); expect(error).toBeInstanceOf(MigrationApplyError); expect(error).toMatchObject({ @@ -666,23 +839,19 @@ describe("applyPendingMigrations — baseline adoption", () => { adopted: ["0000_baseline"], }); expect((error as Error).message).toBe( - "Applying migration 0001_migration failed (SQLSTATE 42P07); none were applied. 0000_baseline stays recorded as applied: its tables already existed.", + "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(client.recorded).toHaveLength(1); + 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({ - journalTableExists: false, - lastCreatedAt: null, - }); + const { pool, client } = fakePool({ recorded: null }); - const error = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }).catch((caught: unknown) => caught); + const error = await applyPendingMigrations(pool, options(folder)).catch( + (caught: unknown) => caught, + ); expect(error).toBeInstanceOf(MigrationFilesError); expect((error as Error).message).toMatch( @@ -691,142 +860,3 @@ describe("applyPendingMigrations — baseline adoption", () => { expect(client.released).toEqual({ error: undefined }); }); }); - -describe("applyPendingMigrations — failures name their cause", () => { - test("reading the recorded migrations fails (42501): the hint, and nothing applied", async () => { - const folder = twoMigrations(); - const { pool, client } = fakePool({ - journalTableExists: true, - lastCreatedAt: 1000, - // The journal table belongs to another role. - failOn: /^select max\(created_at\)/, - failCode: "42501", - }); - - const error = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }).catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(MigrationApplyError); - expect(error).toMatchObject({ pending: [], code: "42501" }); - expect((error as Error).message).toMatch( - /^Reading the recorded migrations in __drizzle_migrations failed \(SQLSTATE 42501\); none were applied\. The connecting role lacks a privilege/, - ); - expect(steps(client.statements).slice(-3)).toEqual([ - "unlock", - "RESET lock_timeout", - "RESET statement_timeout", - ]); - }); - - test("a table lock held past the lock timeout says to deploy again", async () => { - const folder = twoMigrations(); - const { pool } = fakePool({ - journalTableExists: true, - lastCreatedAt: 1000, - failOn: /ADD COLUMN "body"/, - failCode: "55P03", - }); - - const error = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }).catch((caught: unknown) => caught); - - expect((error as Error).message).toBe( - "Applying migration 0001_migration failed (SQLSTATE 55P03); none were applied. Another session held a lock on a table this migration changes for over 30s; deploy again once it finishes.", - ); - }); - - test("a Node system error is not reported as a SQLSTATE", async () => { - const folder = twoMigrations(); - const { pool } = fakePool({ - journalTableExists: true, - lastCreatedAt: 1000, - failOn: /ADD COLUMN "body"/, - failCode: "EPIPE", - }); - - const error = await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }).catch((caught: unknown) => caught); - - expect(error).toMatchObject({ code: undefined }); - expect((error as Error).message).toBe( - "Applying migration 0001_migration failed; none were applied.", - ); - }); - - 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({ journalTableExists: false, lastCreatedAt: null }); - - const error = await applyPendingMigrations(fake.pool, { - migrationsFolder: folder, - schemaName: "app", - }).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([ - [ - "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({ journalTableExists: false, lastCreatedAt: null }); - - const error = await applyPendingMigrations(fake.pool, { - migrationsFolder: folder, - schemaName: "app", - }).catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(MigrationFilesError); - expect((error as Error).message).toMatch(message); - expect(fake.connects()).toBe(0); - }, - ); - - test("waits for another instance's lock, and says so", async () => { - const folder = twoMigrations(); - const log = vi.spyOn(console, "log").mockImplementation(() => undefined); - const { pool, client } = fakePool({ - journalTableExists: true, - lastCreatedAt: 2000, - lockHeld: true, - }); - - await applyPendingMigrations(pool, { - migrationsFolder: folder, - schemaName: "app", - }); - - expect(steps(client.statements).slice(0, 4)).toEqual([ - "SET statement_timeout = 0", - "try lock", - "lock", - "SET lock_timeout = '30s'", - ]); - expect(log.mock.calls.flat().map(String).join(" ")).toContain( - "Waiting for another instance to finish migrating schema app", - ); - }); -}); 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..33d5d1baa --- /dev/null +++ b/packages/appkit/src/database/migrations/tests/fixtures.ts @@ -0,0 +1,86 @@ +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; +} + +/** The hash drizzle-orm's migrator records for a migration file. */ +export function hashOf(folder: string, tag: string): string { + return createHash("sha256") + .update(fs.readFileSync(path.join(folder, `${tag}.sql`), "utf-8")) + .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..04da4ac6e --- /dev/null +++ b/packages/appkit/src/database/migrations/tests/history.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, test } from "vitest"; + +import { type MigrationFile, reconcileMigrations } from "../history"; + +const file = ( + tag: string, + when: number, + hash = `hash-${tag}`, +): MigrationFile => ({ + tag, + idx: 0, + when, + hash, + 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 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([]); + }); +}); diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index 56ea47022..4f93e59d7 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -11,7 +11,33 @@ describe("ownership: one owner per branch", () => { expect(hint).toContain( "On the deploy branch that role is the app's service principal: bind the database to the app with CAN_CONNECT_AND_CREATE", ); - expect(hint).toContain("use another schemaName in schema.ts"); + }); + + test("a schema owned by another role names both roles and how that happens", () => { + const hint = ownershipHint("42501", { + schemaName: "app", + owner: "old-app-sp", + currentUser: "new-app-sp", + }); + expect(hint).toContain( + `Schema "app" is owned by "old-app-sp", but the app connects as "new-app-sp".`, + ); + expect(hint).toContain( + "the app's database resource was removed and added again, or the app was recreated", + ); + expect(hint).toContain("set another schemaName in schema.ts"); + }); + + test("a schema that does not exist yet points at CREATE on the database", () => { + expect( + ownershipHint("42501", { + schemaName: "app", + owner: null, + currentUser: "app-sp", + }), + ).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("any other failure gets no ownership hint", () => { diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index 8061c1124..a350b3537 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -1,3 +1,5 @@ +import fs from "node:fs"; + import type { Pool } from "pg"; import { databaseSetupFailed } from "../../database/errors"; @@ -5,8 +7,10 @@ import { applyPendingMigrations, MigrationApplyError, MigrationBaselineMismatchError, + MigrationHistoryError, } from "../../database/migrations/apply"; import { + journalFile, MigrationFilesError, migrationsFolder, } from "../../database/migrations/paths"; @@ -15,64 +19,89 @@ import { createLogger } from "../../logging/logger"; const logger = createLogger("database"); +/** Branches `appkit db` creates for one developer or one agent session; only they migrate them. */ +const DEVELOPER_BRANCH = /^(dev-[a-z0-9-]+-[0-9a-f]{6}|session-[a-z0-9-]+)$/; + /** - * True only inside a deployed Databricks App: not local development, and the - * runtime has set the app's name and its service principal's credentials, as - * Databricks Apps does for every app. `databricks apps run-local` sets the - * name but not the credentials. Locally, `appkit db migrate` applies - * migrations instead. + * True when the app opts in with APPKIT_DB_MIGRATE_ON_START=true (app.yaml) + * and runs with service principal credentials, as Databricks Apps sets for + * every app. `.env` never carries the flag, so a local start does not migrate; + * `databricks apps run-local` reads app.yaml but sets no credentials. */ export function shouldMigrateOnStart( env: NodeJS.ProcessEnv = process.env, ): boolean { return ( - env.NODE_ENV !== "development" && - Boolean(env.DATABRICKS_APP_NAME) && + env.APPKIT_DB_MIGRATE_ON_START === "true" && Boolean(env.DATABRICKS_CLIENT_ID) && Boolean(env.DATABRICKS_CLIENT_SECRET) ); } +/** The branch id in LAKEBASE_ENDPOINT (projects/

/branches//endpoints/). */ +function endpointBranch(endpoint: string | undefined): string | undefined { + return endpoint?.match(/\/branches\/([^/]+)\//)?.[1]; +} + /** * Apply pending committed migrations from /config/database/migrations as * the app's identity (see database/migrations/ownership.ts). No journal → - * no-op. A failed or unadoptable migration, or a missing or unreadable - * migration file, becomes a setup failure that names it; any other error - * (e.g. no connection) is left to lifecycle's generic sanitizer. + * no-op. Every migration failure becomes a setup failure that names it. */ export async function migrateOnStart( pool: Pick, schema: Schema, root: string = process.cwd(), + env: NodeJS.ProcessEnv = process.env, ): Promise { + const folder = migrationsFolder(root); + const branch = endpointBranch(env.LAKEBASE_ENDPOINT); + if (branch && DEVELOPER_BRANCH.test(branch)) { + logger.warn( + "Not migrating branch %s on start: it belongs to a developer or agent session, which migrates it with `appkit db migrate`.", + branch, + ); + return; + } + if (!fs.existsSync(journalFile(folder))) { + logger.info("No committed migrations at %s; nothing to apply", folder); + return; + } + // A transaction-mode pooler hands each statement to any server session, so + // the session-level migration lock would not exclude other instances. + if (env.PGHOST?.includes("-pooler.")) { + throw databaseSetupFailed( + `PGHOST ${env.PGHOST} is a pooled endpoint, and migrations need a direct connection. Use the host without "-pooler".`, + ); + } + + const started = Date.now(); let result: Awaited>; try { result = await applyPendingMigrations(pool, { - migrationsFolder: migrationsFolder(root), + migrationsFolder: folder, schemaName: schema.$schemaName, }); } catch (error) { if ( error instanceof MigrationApplyError || error instanceof MigrationBaselineMismatchError || + error instanceof MigrationHistoryError || error instanceof MigrationFilesError ) { throw databaseSetupFailed(error.message); } throw error; } - if (result.adopted.length > 0) { - logger.info( - "Adopted %s in schema %s: its tables already existed", - result.adopted.join(", "), - schema.$schemaName, - ); - } - if (result.applied.length > 0) { - logger.info( - "Applied migrations %s to schema %s", - result.applied.join(", "), - schema.$schemaName, - ); - } + logger.info( + "Migrations for schema %s from %s: applied=%d adopted=%d edited=%d unknown=%d lock_wait_ms=%d duration_ms=%d", + schema.$schemaName, + folder, + result.applied.length, + result.adopted.length, + result.edited.length, + result.unknown, + result.lockWaitMs, + Date.now() - started, + ); } diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index 9b6f7176a..bf206c427 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -76,7 +76,7 @@ export async function assertSchemaMatchesDatabase( } if (problems.length > 0) { throw databaseSetupFailed( - `the declared schema does not match the database: ${problems.join("; ")}. Create them, or commit migrations under config/database/migrations so the deployed app applies them on start.`, + `the declared schema does not match the database: ${problems.join("; ")}. Create them, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start.`, ); } } diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index cf453a32d..6d53bc5c4 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -26,6 +26,10 @@ const schema = defineSchema( ); const roots: string[] = []; const pool = { connect: vi.fn() }; +const deployEnv = { + LAKEBASE_ENDPOINT: "projects/p/branches/production/endpoints/primary", + PGHOST: "ep-abc.database.cloud.databricks.com", +}; function appRoot(): string { const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-migrate-start-")); @@ -33,6 +37,26 @@ function appRoot(): string { return root; } +/** An app root with a committed (empty) journal. */ +function appRootWithMigrations(): string { + const root = appRoot(); + const meta = path.join(root, "config/database/migrations/meta"); + fs.mkdirSync(meta, { recursive: true }); + fs.writeFileSync( + path.join(meta, "_journal.json"), + JSON.stringify({ version: "7", dialect: "postgresql", entries: [] }), + ); + return root; +} + +const nothingDone = { + applied: [], + adopted: [], + edited: [], + unknown: 0, + lockWaitMs: 0, +}; + beforeEach(async () => { const actual = await vi.importActual< typeof import("../../../database/migrations/apply") @@ -54,44 +78,31 @@ describe("shouldMigrateOnStart", () => { DATABRICKS_CLIENT_ID: "sp-client-id", DATABRICKS_CLIENT_SECRET: "secret", }; - const app = { DATABRICKS_APP_NAME: "my-app", ...credentials }; + const optIn = { APPKIT_DB_MIGRATE_ON_START: "true" }; test.each([ - ["a deployed app", { ...app, NODE_ENV: "production" }, true], - ["a deployed app without NODE_ENV", app, true], + ["a deployed app that opts in", { ...optIn, ...credentials }, true], [ - "local development, even with app credentials", - { ...app, NODE_ENV: "development" }, + "a deployed app without the flag", + { DATABRICKS_APP_NAME: "my-app", ...credentials }, false, ], [ - "`databricks apps run-local`: the app name without its credentials", - { DATABRICKS_APP_NAME: "my-app", NODE_ENV: "production" }, + "a flag other than true", + { APPKIT_DB_MIGRATE_ON_START: "1", ...credentials }, false, ], [ - "a local production start with app credentials in .env but no app name", - { ...credentials, NODE_ENV: "production" }, + "`databricks apps run-local`: the flag from app.yaml, no credentials", + { ...optIn, DATABRICKS_APP_NAME: "my-app" }, false, ], [ "no client secret (a developer's own credentials)", - { - DATABRICKS_APP_NAME: "my-app", - DATABRICKS_CLIENT_ID: "x", - NODE_ENV: "production", - }, - false, - ], - [ - "no client id", - { - DATABRICKS_APP_NAME: "my-app", - DATABRICKS_CLIENT_SECRET: "x", - NODE_ENV: "production", - }, + { ...optIn, DATABRICKS_CLIENT_ID: "x" }, false, ], + ["no client id", { ...optIn, DATABRICKS_CLIENT_SECRET: "x" }, false], ["nothing set", {}, false], ] as const)("%s → %s", (_label, env, expected) => { expect(shouldMigrateOnStart(env)).toBe(expected); @@ -99,21 +110,29 @@ describe("shouldMigrateOnStart", () => { }); describe("migrateOnStart", () => { - test("no committed journal: a no-op that never connects", async () => { - await migrateOnStart(pool, schema, appRoot()); + test("no committed journal: says so and never connects", async () => { + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + const root = appRoot(); + + await migrateOnStart(pool, schema, root, deployEnv); expect(pool.connect).not.toHaveBeenCalled(); + expect(log.mock.calls.flat().map(String).join(" ")).toContain( + `No committed migrations at ${path.join(root, "config/database/migrations")}`, + ); }); - test("applies from /config/database/migrations into the schema's own journal, and logs what it did", async () => { - const root = appRoot(); + test("applies from /config/database/migrations into the schema's own journal, and logs one summary", async () => { + const root = appRootWithMigrations(); const log = vi.spyOn(console, "log").mockImplementation(() => undefined); applyPendingMigrations.mockResolvedValueOnce({ + ...nothingDone, applied: ["0001_migration"], adopted: ["0000_baseline"], + lockWaitMs: 12, }); - await migrateOnStart(pool, schema, root); + await migrateOnStart(pool, schema, root, deployEnv); expect(applyPendingMigrations).toHaveBeenCalledWith(pool, { migrationsFolder: path.join(root, "config/database/migrations"), @@ -121,29 +140,77 @@ describe("migrateOnStart", () => { }); const logged = log.mock.calls.map((call) => call.map(String).join(" ")); expect(logged).toEqual([ - expect.stringContaining( - "Adopted 0000_baseline in schema app: its tables already existed", - ), - expect.stringContaining( - "Applied migrations 0001_migration to schema app", + expect.stringMatching( + /Migrations for schema app from .*: applied=1 adopted=1 edited=0 unknown=0 lock_wait_ms=12 duration_ms=\d+/, ), ]); }); - test("nothing pending logs nothing", async () => { - const log = vi.spyOn(console, "log").mockImplementation(() => undefined); - applyPendingMigrations.mockResolvedValueOnce({ applied: [], adopted: [] }); + test.each([ + ["a developer branch", "dev-jane-a1b2c3"], + ["an agent session branch", "session-k3x9q2m7"], + ])( + "%s is never migrated on start, even with committed migrations", + async (_label, branch) => { + const warn = vi + .spyOn(console, "warn") + .mockImplementation(() => undefined); + + await migrateOnStart(pool, schema, appRootWithMigrations(), { + ...deployEnv, + LAKEBASE_ENDPOINT: `projects/p/branches/${branch}/endpoints/primary`, + }); + + expect(applyPendingMigrations).not.toHaveBeenCalled(); + expect(warn.mock.calls.flat().map(String).join(" ")).toContain( + `Not migrating branch ${branch} on start`, + ); + }, + ); - await migrateOnStart(pool, schema, appRoot()); + test.each([ + ["a branch that only starts with dev-", "dev-environment"], + ["the production branch", "production"], + ])("%s is migrated", async (_label, branch) => { + vi.spyOn(console, "log").mockImplementation(() => undefined); + applyPendingMigrations.mockResolvedValueOnce(nothingDone); - expect(log).not.toHaveBeenCalled(); + await migrateOnStart(pool, schema, appRootWithMigrations(), { + ...deployEnv, + LAKEBASE_ENDPOINT: `projects/p/branches/${branch}/endpoints/primary`, + }); + + expect(applyPendingMigrations).toHaveBeenCalled(); + }); + + test("a pooled endpoint is refused: the migration lock would not hold", async () => { + const error = await migrateOnStart(pool, schema, appRootWithMigrations(), { + ...deployEnv, + PGHOST: "ep-abc-pooler.database.cloud.databricks.com", + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(DatabasePluginError); + expect((error as Error).message).toContain( + "is a pooled endpoint, and migrations need a direct connection", + ); + expect(applyPendingMigrations).not.toHaveBeenCalled(); }); test.each([ [ "a failed migration", - new apply.MigrationApplyError(["0001_migration"], "42501"), - "Applying migration 0001_migration failed (SQLSTATE 42501); none were applied.", + new apply.MigrationApplyError({ + step: "Applying migrations", + failed: "0001_migration", + pending: ["0001_migration"], + cause: Object.assign(new Error("denied"), { code: "42501" }), + }), + "Migration 0001_migration failed (SQLSTATE 42501) and was rolled back.", + ], + [ + "a stranded migration", + new apply.MigrationHistoryError("app", ["0001_parallel"], "0002_b"), + "Migration 0001_parallel is older than 0002_b", ], [ "a baseline that only partly matches", @@ -164,9 +231,12 @@ describe("migrateOnStart", () => { async (_label, failure, reason) => { applyPendingMigrations.mockRejectedValueOnce(failure); - const error = await migrateOnStart(pool, schema, appRoot()).catch( - (caught: unknown) => caught, - ); + const error = await migrateOnStart( + pool, + schema, + appRootWithMigrations(), + deployEnv, + ).catch((caught: unknown) => caught); expect(error).toBeInstanceOf(DatabasePluginError); expect(error).toMatchObject({ category: "SETUP_FAILED", phase: "setup" }); @@ -182,6 +252,8 @@ describe("migrateOnStart", () => { const raw = new Error("connection reset"); applyPendingMigrations.mockRejectedValueOnce(raw); - await expect(migrateOnStart(pool, schema, appRoot())).rejects.toBe(raw); + await expect( + migrateOnStart(pool, schema, appRootWithMigrations(), deployEnv), + ).rejects.toBe(raw); }); }); From ad62acb919f6f365649c4b964fb8262493344cb9 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 12 Oct 2026 13:23:23 +0100 Subject: [PATCH 003/317] feat(appkit): default defineSchema tables to the app schema defineSchema() without a schemaName now places its tables in the Postgres schema "app" instead of "public". The deployed app's service principal can create and own a schema of its own, but has no CREATE on public, so tables in public could not be migrated on deploy without a manual grant. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 5 ++ .../runtime/tests/drizzle-data-path.test.ts | 36 ++++++++------- .../database/runtime/tests/translate.test.ts | 46 ++++++++++--------- .../database/schema-builder/define-schema.ts | 9 +++- .../tests/define-schema.test.ts | 26 ++++++++++- .../src/database/schema-builder/types.ts | 1 + .../plugins/database/tests/lifecycle.test.ts | 4 +- .../database/tests/migrate-on-start.test.ts | 8 ++-- .../database/tests/schema-check.test.ts | 24 ++++++---- 9 files changed, 103 insertions(+), 56 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 7f8aa77e1..0317bcd5a 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -84,6 +84,11 @@ public column, list with an explicit non-empty `order`. A keyless table with no sortable columns has no list route. `upsert` is available to server code but has no generated HTTP route. +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`. + ## Schema discovery and overrides `database()` and `database({})` use the same defaults. During setup, the plugin 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 64ed5ff2d..5d8cf3d91 100644 --- a/packages/appkit/src/database/schema-builder/define-schema.ts +++ b/packages/appkit/src/database/schema-builder/define-schema.ts @@ -339,6 +339,13 @@ export function assertFinalizedSchema(value: unknown): asserts value is Schema { } } +/** + * 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`. + */ +const DEFAULT_SCHEMA_NAME = "app"; + /** * Compile one declared schema. The returned type keeps the table names the * builder returned, so `api.tables` and `hooks` can name only real tables. @@ -347,7 +354,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 = { 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/plugins/database/tests/lifecycle.test.ts b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts index 0401912f6..fe7695dc7 100644 --- a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts +++ b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts @@ -209,7 +209,7 @@ describe("createDatabaseState", () => { const drift = new DatabasePluginError( "SETUP_FAILED", "setup", - "Database setup failed: table public.tags does not exist", + "Database setup failed: table app.tags does not exist", ); mocks.assertSchemaMatchesDatabase.mockRejectedValueOnce(drift); @@ -223,7 +223,7 @@ describe("createDatabaseState", () => { schema, ); expect(error).toBe(drift); - expect(error.message).toContain("table public.tags does not exist"); + expect(error.message).toContain("table app.tags does not exist"); expect(pool.end).toHaveBeenCalledTimes(1); }); diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index 6d53bc5c4..a1aaa09a3 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -20,10 +20,10 @@ import { MigrationFilesError } from "../../../database/migrations/paths"; import { defineSchema, id } from "../../../database/schema-builder"; import { migrateOnStart, shouldMigrateOnStart } from "../migrate-on-start"; -const schema = defineSchema( - ({ table }) => ({ notes: table("notes", { id: id() }) }), - { schemaName: "app" }, -); +// The default schema, app, holds the journal too. +const schema = defineSchema(({ table }) => ({ + notes: table("notes", { id: id() }), +})); const roots: string[] = []; const pool = { connect: vi.fn() }; const deployEnv = { diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index 6f10836a8..1ece4fb92 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -4,16 +4,20 @@ import type { DataPath } from "../../../database/runtime"; import { defineSchema, fk, id, text } from "../../../database/schema-builder"; import { assertSchemaMatchesDatabase } from "../schema-check"; -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(), - }); - return { boards, notes }; -}); +// Explicitly public: the assertions name the tables public.boards and public.notes. +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(), + }); + return { boards, notes }; + }, + { schemaName: "public" }, +); type CatalogRow = { table_name: string; From 59ba0370b1617ff770bb2c603621d75dd2037f8e Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 19 Oct 2026 14:25:25 +0200 Subject: [PATCH 004/317] fix(appkit): point apps with tables in public at the schemaName option An app whose tables predate the app default fails setup with advice to commit migrations, which would create an empty copy in app. Name the public tables instead, give public its own ownership hint, document one schema per app, and pin the dev-playground to public. Signed-off-by: ditadi --- apps/dev-playground/config/database/schema.ts | 62 ++++++++++--------- docs/docs/plugins/database.md | 23 +++++++ .../src/database/migrations/ownership.ts | 9 +++ .../migrations/tests/ownership.test.ts | 13 ++++ .../src/plugins/database/schema-check.ts | 30 ++++++++- .../database/tests/schema-check.test.ts | 48 +++++++++++++- 6 files changed, 153 insertions(+), 32 deletions(-) diff --git a/apps/dev-playground/config/database/schema.ts b/apps/dev-playground/config/database/schema.ts index 2bc9a0126..1d779f597 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 the audit trail the // plugin keeps for them. Three tables is enough to exercise a two-edge include; -// the DatabasePlugin does not create them, so the app expects them to exist. +// the DatabasePlugin does not create them, 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/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 0317bcd5a..1467dd10b 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -89,6 +89,29 @@ Tables live in the Postgres schema `app` unless the second argument of 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 schema. Two apps on one database and one schema share the +migration history, 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`. Keep them there with: + +```ts +export const schema = defineSchema( + ({ table }) => ({ + notes: table("notes", { id: id(), body: text().notNull() }), + }), + { schemaName: "public" }, +); +``` + +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`. + ## Schema discovery and overrides `database()` and `database({})` use the same defaults. During setup, the plugin diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index ec2dd75ac..3136b0daa 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -50,6 +50,15 @@ export function ownershipHint( "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 + ) { + 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.` + ); + } if (ownership && ownership.owner !== ownership.currentUser) { return ( `Schema "${ownership.schemaName}" is owned by "${ownership.owner}", but the app connects as "${ownership.currentUser}". ` + diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index 4f93e59d7..27acc56b5 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -40,6 +40,19 @@ describe("ownership: one owner per branch", () => { ); }); + test("public, which the app never owns, gets the grant or the default schema", () => { + expect( + ownershipHint("42501", { + schemaName: "public", + owner: "pg_database_owner", + currentUser: "app-sp", + }), + ).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("any other failure gets no ownership hint", () => { expect(ownershipHint("42P07")).toBeUndefined(); expect(ownershipHint(undefined)).toBeUndefined(); diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index bf206c427..69a6d575e 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -75,8 +75,36 @@ export async function assertSchemaMatchesDatabase( } } if (problems.length > 0) { + const absent = tableNames.filter((name) => !found.has(name)); + const advice = + (await inPublicInstead(dataPath, schemaName, absent)) ?? + "Create them, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start."; throw databaseSetupFailed( - `the declared schema does not match the database: ${problems.join("; ")}. Create them, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start.`, + `the declared schema does not match the database: ${problems.join("; ")}. ${advice}`, ); } } + +/** + * Apps from before the default schema moved to `app` keep their tables in + * `public`. Name that case; migrating would create a second, empty copy. + */ +async function inPublicInstead( + dataPath: DataPath, + schemaName: string, + absent: readonly string[], +): Promise { + if (schemaName === "public" || absent.length === 0) return undefined; + const rows = await dataPath.raw<{ table_name: string }>` + select 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 = 'public' + and c.relname::text = any(${absent}::text[]) + and c.relkind in ('r', 'p')`; + if (rows.length < absent.length) return undefined; + return ( + `Schema public has ${absent.length === 1 ? "that table" : "those tables"}, but 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.' + ); +} diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index 1ece4fb92..2abb3d26c 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -25,10 +25,11 @@ type CatalogRow = { relation_kind: string; }; -/** Answer the catalog query with the given tables and columns. */ +/** Answer the catalog query with the given tables and columns, and the lookup in public with `inPublic`. */ function catalog( tables: Record, kinds: Record = {}, + inPublic: string[] = [], ) { const rows: CatalogRow[] = Object.entries(tables).flatMap( ([name, columns]): CatalogRow[] => @@ -46,10 +47,53 @@ function catalog( relation_kind: kinds[name] ?? "r", })), ); - const raw = vi.fn(async () => rows); + const raw = vi.fn(async (strings: TemplateStringsArray) => + strings.join("?").includes("n.nspname = 'public'") + ? inPublic.map((table_name) => ({ table_name })) + : rows, + ); return { raw, path: { raw } as unknown as DataPath }; } +describe("assertSchemaMatchesDatabase — tables left in public", () => { + const appSchema = defineSchema(({ table }) => ({ + boards: table("boards", { id: id() }), + notes: table("notes", { id: id() }), + })); + + test("every missing table is in public: says so and how to keep them there, not to migrate", async () => { + const { path } = catalog({}, {}, ["boards", "notes"]); + + const error = await assertSchemaMatchesDatabase(path, appSchema).catch( + (caught) => caught, + ); + + expect(error.message).toContain("table app.boards does not exist"); + expect(error.message).toContain( + `Schema public has those tables, but defineSchema() puts tables in schema "app" unless told otherwise. ` + + 'To keep them in public, pass { schemaName: "public" } as the second argument of defineSchema()', + ); + expect(error.message).not.toContain("commit migrations"); + }); + + test("only some missing tables are in public: the usual advice", async () => { + const { path } = catalog({}, {}, ["boards"]); + + await expect(assertSchemaMatchesDatabase(path, appSchema)).rejects.toThrow( + "commit migrations under config/database/migrations", + ); + }); + + test("a schema declared as public never looks in public twice", async () => { + const { raw, path } = catalog({ boards: ["id", "title"] }); + + await expect(assertSchemaMatchesDatabase(path, schema)).rejects.toThrow( + "commit migrations", + ); + expect(raw).toHaveBeenCalledTimes(1); + }); +}); + describe("assertSchemaMatchesDatabase", () => { test("accepts a database with every declared column, and extra ones", async () => { const { path } = catalog({ From 76c39abac02942f0c771c1cccee437ea07629ddd Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 12 Oct 2026 13:33:40 +0100 Subject: [PATCH 005/317] feat(appkit): add appkit db migrate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `appkit db migrate` generates a migration from config/database/schema.ts with drizzle-kit, regenerates shared/appkit-types/database.d.ts, and applies pending migrations to the branch .env points at. It applies only to a branch created for this developer (dev-…) or this checkout (session-…); on any other branch, including the project default and any branch databricks.yml deploys to, it generates and says why nothing was applied. It connects only after the Lakebase API confirms that PGHOST is a host of LAKEBASE_ENDPOINT. The logic lives in a new @databricks/appkit/database-tooling entry point that the shared CLI loads lazily, so the runtime never imports drizzle-kit. drizzle-kit is an optional peer dependency: apps that generate migrations install it as a dev dependency, and the command says how when it is missing. `appkit db` stays hidden from --help until the database plugin is offered by `databricks apps init`. Signed-off-by: ditadi --- knip.json | 3 +- packages/appkit/package.json | 11 + .../src/connectors/lakebase/endpoint-host.ts | 2 +- .../appkit/src/database/tooling/context.ts | 122 ++++ .../src/database/tooling/drizzle-exports.ts | 24 + packages/appkit/src/database/tooling/guard.ts | 84 +++ .../appkit/src/database/tooling/identity.ts | 29 + packages/appkit/src/database/tooling/index.ts | 7 + .../src/database/tooling/lakebase-api.ts | 104 +++ .../appkit/src/database/tooling/migrate.ts | 127 ++++ .../appkit/src/database/tooling/migrations.ts | 262 ++++++++ .../appkit/src/database/tooling/naming.ts | 48 ++ .../appkit/src/database/tooling/targets.ts | 115 ++++ .../database/tooling/tests/context.test.ts | 140 +++++ .../tooling/tests/drizzle-exports.test.ts | 47 ++ .../tests/drizzle-kit-dependency.test.ts | 104 +++ .../src/database/tooling/tests/fakes.ts | 122 ++++ .../src/database/tooling/tests/guard.test.ts | 167 +++++ .../database/tooling/tests/identity.test.ts | 32 + .../tooling/tests/lakebase-api.test.ts | 87 +++ .../database/tooling/tests/migrate.test.ts | 253 ++++++++ .../database/tooling/tests/migrations.test.ts | 343 ++++++++++ .../src/database/tooling/tests/naming.test.ts | 39 ++ .../database/tooling/tests/targets.test.ts | 111 ++++ .../src/plugins/database/load-schema.ts | 14 +- .../src/plugins/database/schema-check.ts | 2 +- packages/appkit/tsdown.config.ts | 1 + .../src/cli/commands/db/database-tooling.d.ts | 39 ++ packages/shared/src/cli/commands/db/index.ts | 11 + .../src/cli/commands/db/migrate.test.ts | 152 +++++ .../shared/src/cli/commands/db/migrate.ts | 31 + packages/shared/src/cli/commands/db/output.ts | 68 ++ packages/shared/src/cli/index.ts | 3 + pnpm-lock.yaml | 590 +++++++++++++++++- 34 files changed, 3267 insertions(+), 27 deletions(-) create mode 100644 packages/appkit/src/database/tooling/context.ts create mode 100644 packages/appkit/src/database/tooling/drizzle-exports.ts create mode 100644 packages/appkit/src/database/tooling/guard.ts create mode 100644 packages/appkit/src/database/tooling/identity.ts create mode 100644 packages/appkit/src/database/tooling/index.ts create mode 100644 packages/appkit/src/database/tooling/lakebase-api.ts create mode 100644 packages/appkit/src/database/tooling/migrate.ts create mode 100644 packages/appkit/src/database/tooling/migrations.ts create mode 100644 packages/appkit/src/database/tooling/naming.ts create mode 100644 packages/appkit/src/database/tooling/targets.ts create mode 100644 packages/appkit/src/database/tooling/tests/context.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/drizzle-exports.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/fakes.ts create mode 100644 packages/appkit/src/database/tooling/tests/guard.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/identity.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/lakebase-api.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/migrate.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/migrations.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/naming.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/targets.test.ts create mode 100644 packages/shared/src/cli/commands/db/database-tooling.d.ts create mode 100644 packages/shared/src/cli/commands/db/index.ts create mode 100644 packages/shared/src/cli/commands/db/migrate.test.ts create mode 100644 packages/shared/src/cli/commands/db/migrate.ts create mode 100644 packages/shared/src/cli/commands/db/output.ts 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 968531019..8dbc988db 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" }, + "./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", @@ -126,6 +131,7 @@ "peerDependencies": { "@mlflow/core": "0.4.0", "autoevals": "0.3.0", + "drizzle-kit": "0.31.10", "vitest": ">=3" }, "peerDependenciesMeta": { @@ -135,6 +141,9 @@ "autoevals": { "optional": true }, + "drizzle-kit": { + "optional": true + }, "vitest": { "optional": true } @@ -149,6 +158,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": { @@ -161,6 +171,7 @@ "./beta": "./dist/beta.js", "./dist/shared/src/plugin": "./dist/shared/src/plugin.d.ts", "./type-generator": "./dist/type-generator/index.js", + "./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/tooling/context.ts b/packages/appkit/src/database/tooling/context.ts new file mode 100644 index 000000000..c8850dea0 --- /dev/null +++ b/packages/appkit/src/database/tooling/context.ts @@ -0,0 +1,122 @@ +import type { LakebasePoolConfig } from "@databricks/lakebase"; +import type { Pool } from "pg"; + +import { initializeLakebasePool } from "../../connectors/lakebase"; +import { endpointHosts } from "../../connectors/lakebase/endpoint-host"; +import { getClientOptions } from "../../context/client-options"; +import { createWorkspaceClient } from "../../workspace-client"; +import { LakebaseApi, type LakebaseEndpoint } from "./lakebase-api"; + +/** One REST call through the SDK's unified-auth client. */ +export interface ToolingRequest { + path: string; + method: "GET" | "POST" | "PATCH" | "DELETE"; + query?: Record; + headers: Headers; + raw: boolean; + payload?: unknown; +} + +/** + * The slice of the SDK client the tooling uses. It is also everything the + * Lakebase pool needs: token refresh calls `apiClient.request` and the user + * lookup calls `currentUser.me`. + */ +export interface ToolingWorkspaceClient { + readonly apiClient: { request(options: ToolingRequest): Promise }; + readonly currentUser: { me(): Promise<{ userName?: string }> }; +} + +/** 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(), + }).toLegacyWorkspaceClient(); + } + return client; + }, + api() { + api ??= new LakebaseApi(ctx.workspace()); + return api; + }, + }; + return ctx; +} + +/** + * 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.`, + ); + } +} + +/** null when PGHOST / PGDATABASE / LAKEBASE_ENDPOINT are not configured. */ +export async function openBranchPool(ctx: DbContext): Promise { + const { PGHOST, PGDATABASE, LAKEBASE_ENDPOINT } = ctx.env; + if (!PGHOST || !PGDATABASE || !LAKEBASE_ENDPOINT) return null; + await assertHostServesEndpoint(ctx, LAKEBASE_ENDPOINT, PGHOST); + const port = ctx.env.PGPORT ? Number(ctx.env.PGPORT) : undefined; + const sslMode = ctx.env.PGSSLMODE as LakebasePoolConfig["sslMode"]; + return initializeLakebasePool({ + host: PGHOST, + database: PGDATABASE, + endpoint: LAKEBASE_ENDPOINT, + user: ctx.env.PGUSER || undefined, + ...(port ? { port } : {}), + ...(sslMode ? { sslMode } : {}), + // Only apiClient.request and currentUser.me are used (see ToolingWorkspaceClient). + workspaceClient: ctx.workspace() as unknown as NonNullable< + LakebasePoolConfig["workspaceClient"] + >, + // One-shot CLI pools: a small cap, and no lingering idle connections. + max: 2, + idleTimeoutMillis: 1_000, + }); +} 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/guard.ts b/packages/appkit/src/database/tooling/guard.ts new file mode 100644 index 000000000..f135e8258 --- /dev/null +++ b/packages/appkit/src/database/tooling/guard.ts @@ -0,0 +1,84 @@ +import type { DbContext } from "./context"; +import { currentIdentity } from "./identity"; +import type { LakebaseBranch } from "./lakebase-api"; +import { devBranchId, sessionBranchId } from "./naming"; +import { + parseResourceName, + readDeployBranches, + readLocalTarget, + resourceId, +} from "./targets"; + +// Commands that write to a branch run only on branches `appkit db init` +// created for this developer (dev-…) or this checkout (session-…). + +interface BranchVerdict { + readonly appkitOwned: boolean; + /** Why the branch is not AppKit-owned. */ + readonly reason?: string; +} + +export function classifyBranch(input: { + branch: LakebaseBranch; + userName: string; + sessionId: string | null; + /** Every branch databricks.yml deploys to; the deployed app migrates those itself. */ + deployBranches: readonly string[]; +}): BranchVerdict { + const { branch, userName, sessionId, deployBranches } = input; + if (branch.status?.default) { + return { appkitOwned: false, reason: "it is the project's default branch" }; + } + if (branch.status?.is_protected) { + return { appkitOwned: false, reason: "it is a protected branch" }; + } + if (deployBranches.includes(branch.name)) { + return { + appkitOwned: false, + reason: "it is a branch databricks.yml deploys to", + }; + } + const id = resourceId(branch.name); + if (id === devBranchId(userName)) return { appkitOwned: true }; + if (sessionId && id === sessionBranchId(sessionId)) { + return { appkitOwned: true }; + } + return { + appkitOwned: false, + reason: `it is not your dev branch (${devBranchId(userName)})${ + sessionId + ? ` or this checkout's session branch (${sessionBranchId(sessionId)})` + : "" + }`, + }; +} + +interface BranchCheck { + readonly branch: LakebaseBranch; + readonly verdict: BranchVerdict; +} + +/** Classify the `.env` branch through the API (no database connection); null when none is configured. */ +export async function checkAppkitBranch( + ctx: DbContext, +): Promise { + const local = readLocalTarget(ctx.env); + const name = parseResourceName(local.endpoint ?? undefined)?.branch; + if (!name) return null; + const branch = await ctx.api().getBranch(name); + if (!branch) { + throw new Error( + `The .env branch ${name} does not exist (deleted or expired). Run \`appkit db init\` to create or pick one.`, + ); + } + const { userName } = await currentIdentity(ctx); + return { + branch, + verdict: classifyBranch({ + branch, + userName, + sessionId: local.session, + deployBranches: readDeployBranches(ctx.root), + }), + }; +} diff --git a/packages/appkit/src/database/tooling/identity.ts b/packages/appkit/src/database/tooling/identity.ts new file mode 100644 index 000000000..3b539abc6 --- /dev/null +++ b/packages/appkit/src/database/tooling/identity.ts @@ -0,0 +1,29 @@ +import type { DbContext } from "./context"; + +/** Who runs the command: the Postgres role name is the user name (email or SP client ID). */ +interface Identity { + readonly userName: string; +} + +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 }; + }); + 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..7167ac662 --- /dev/null +++ b/packages/appkit/src/database/tooling/index.ts @@ -0,0 +1,7 @@ +/** + * `@databricks/appkit/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. + */ +export { createDbContext, type DbContext } from "./context"; +export { type MigrateOptions, type MigrateReport, runMigrate } from "./migrate"; 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..1bde6df9d --- /dev/null +++ b/packages/appkit/src/database/tooling/lakebase-api.ts @@ -0,0 +1,104 @@ +import type { ToolingRequest, ToolingWorkspaceClient } from "./context"; + +// Lakebase Postgres REST API through the SDK's unified-auth client. 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?: { hosts?: { host?: string } }; +} + +export class LakebaseApiError extends Error { + /** HTTP status of the failing call. */ + readonly statusCode?: number; + /** What was being done, e.g. "create branch projects/p/branches/b". */ + readonly operation: string; + + constructor( + operation: string, + message: string, + options: { statusCode?: number; cause?: unknown } = {}, + ) { + super(`Lakebase: ${operation} failed: ${message}`, { + cause: options.cause, + }); + this.name = "LakebaseApiError"; + this.operation = operation; + this.statusCode = options.statusCode; + } +} + +const API = "/api/2.0/postgres"; + +function statusCodeOf(error: unknown): number | undefined { + const code = (error as { statusCode?: unknown } | undefined)?.statusCode; + return typeof code === "number" ? code : undefined; +} + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +export class LakebaseApi { + constructor( + private readonly client: Pick, + ) {} + + getBranch(name: string): Promise { + return this.getOrNull(`get branch ${name}`, name); + } + + getEndpoint(name: string): Promise { + return this.getOrNull(`get endpoint ${name}`, name); + } + + private async call( + operation: string, + request: Omit, + ): Promise { + const headers = new Headers({ Accept: "application/json" }); + if (request.payload !== undefined) { + headers.set("Content-Type", "application/json"); + } + try { + return (await this.client.apiClient.request({ + ...request, + headers, + raw: false, + })) as T; + } catch (error) { + throw new LakebaseApiError(operation, messageOf(error), { + statusCode: statusCodeOf(error), + cause: error, + }); + } + } + + private async getOrNull( + operation: string, + name: string, + ): Promise { + try { + return await this.call(operation, { + path: `${API}/${name}`, + method: "GET", + }); + } catch (error) { + if (error instanceof LakebaseApiError && error.statusCode === 404) { + return null; + } + throw error; + } + } +} diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts new file mode 100644 index 000000000..d0be9ec6d --- /dev/null +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -0,0 +1,127 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +import { + DATABASE_TYPES_FILE, + generateDatabaseTypes, +} from "../../type-generator/database"; +import { applyPendingMigrations } from "../migrations/apply"; +import { migrationsFolder, readJournal } from "../migrations/paths"; +import { type DbContext, openBranchPool } from "./context"; +import { checkAppkitBranch } from "./guard"; +import { type GeneratedMigration, generateMigrationFiles } from "./migrations"; +import { resourceId } from "./targets"; + +/** Same application-relative conventions as the plugin and `appkit generate-types`. */ +const SCHEMA_FILE = "config/database/schema.ts"; + +/** Whether the checkout has a config/database/schema.ts yet. */ +function hasSchemaFile(root: string): boolean { + return fs.existsSync(path.join(root, SCHEMA_FILE)); +} + +/** Without schema.ts, point to introspect instead of a load error. */ +function requireSchemaFile(root: string): void { + if (hasSchemaFile(root)) return; + throw new Error( + `No ${SCHEMA_FILE} yet, so there is nothing to migrate. Run \`appkit db introspect\` to write it from the branch's tables, or create it.`, + ); +} +const DATABASE_TYPES_PATH = path.join( + "shared/appkit-types", + DATABASE_TYPES_FILE, +); + +export interface MigrateReport { + /** The migration written by this run; null when schema.ts matches the latest snapshot. */ + readonly generated: GeneratedMigration | null; + /** Tags applied to the `.env` branch by this run. */ + readonly applied: readonly string[]; + /** Tags recorded without running because their tables already existed (0000_baseline). */ + readonly adopted?: readonly string[]; + /** Why nothing was applied, when applying was skipped. */ + readonly notApplied?: string; + readonly typesFile: string; +} + +export interface MigrateOptions { + /** false: an ambiguous rename throws instead of prompting. */ + readonly interactive: boolean; +} + +type ApplyOutcome = Pick; + +const NO_BRANCH = + "no branch configured (PGHOST, PGDATABASE, LAKEBASE_ENDPOINT) — run appkit db init"; + +/** Why migrations must not be applied to the `.env` branch; undefined when they may. */ +async function applyBlocker(ctx: DbContext): Promise { + const check = await checkAppkitBranch(ctx); + if (!check) return NO_BRANCH; + if (check.verdict.appkitOwned) return undefined; + return `${resourceId(check.branch.name)} is not an AppKit dev or session branch (${check.verdict.reason}). Migrations are applied only to branches \`appkit db init\` created for you; the deployed app applies committed migrations to its own branch`; +} + +/** Apply pending migrations to the `.env` branch, or say why they were not. */ +async function applyToEnvBranch( + ctx: DbContext, + folder: string, + schemaName: string, +): Promise { + const blocker = readJournal(folder) + ? await applyBlocker(ctx) + : "no migrations to apply — schema.ts declares no tables yet"; + if (blocker) return { applied: [], notApplied: blocker }; + const pool = await openBranchPool(ctx); + if (!pool) return { applied: [], notApplied: NO_BRANCH }; + try { + const { applied, adopted } = await applyPendingMigrations(pool, { + migrationsFolder: folder, + schemaName, + }); + return { applied, ...(adopted.length > 0 ? { adopted } : {}) }; + } finally { + await pool.end().catch(() => undefined); + } +} + +/** + * `appkit db migrate`: generate a migration when schema.ts changed, regenerate + * database.d.ts, and apply pending migrations to the `.env` branch (only AppKit + * dev/session branches). + */ +export async function runMigrate( + ctx: DbContext, + options: MigrateOptions, +): Promise { + requireSchemaFile(ctx.root); + const schema = await loadDefaultDatabaseSchema(ctx.root, { + showImportError: true, + }); + const folder = migrationsFolder(ctx.root); + const generated = await generateMigrationFiles({ + folder, + schema, + interactive: options.interactive, + }); + + // The types follow schema.ts alone, so they are current even if applying fails. + const typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); + await generateDatabaseTypes({ + schemaFile: path.join(ctx.root, SCHEMA_FILE), + outFile: typesFile, + }); + + let outcome: ApplyOutcome; + try { + outcome = await applyToEnvBranch(ctx, folder, schema.$schemaName); + } catch (error) { + if (!generated) throw error; + throw new Error( + `Wrote ${path.relative(ctx.root, generated.file)}, but did not apply it: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + return { generated, ...outcome, typesFile }; +} diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts new file mode 100644 index 000000000..135d4401d --- /dev/null +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -0,0 +1,262 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { + type Journal, + type JournalEntry, + journalFile, + readJournal, + readJsonFile, +} from "../migrations/paths"; +import type { Schema } from "../schema-builder"; +import { drizzleKitImports } from "./drizzle-exports"; + +/** + * The drizzle-kit release the snapshots and SQL are written for; the optional + * peer dependency in package.json pins the same version. + */ +export const DRIZZLE_KIT_VERSION = "0.31.10"; + +interface GenerateOptions { + /** Absolute migrations folder. */ + readonly folder: string; + readonly schema: Schema; + /** false: an ambiguous rename throws instead of prompting. */ + readonly interactive: boolean; +} + +export interface GeneratedMigration { + /** e.g. "0001_migration". */ + readonly tag: string; + /** Absolute path of the written .sql file. */ + readonly file: string; + readonly statements: readonly string[]; +} + +/** + * drizzle-kit can't tell a rename from a drop plus a create without asking. + * Raised in non-interactive runs instead of prompting. + */ +export class MigrationRenameAmbiguityError extends Error { + readonly kind: "table" | "column" | "enum"; + /** The table whose columns changed, or the schema for table and enum changes. */ + readonly table: string; + readonly created: readonly string[]; + readonly deleted: readonly string[]; + + constructor( + kind: MigrationRenameAmbiguityError["kind"], + table: string, + created: readonly string[], + deleted: readonly string[], + ) { + const scope = + kind === "column" ? `columns of table "${table}"` : `${kind}s`; + super( + `Cannot tell whether ${scope} were renamed: removed ${deleted.join(", ")}; added ${created.join(", ")}. ` + + "Run `appkit db migrate` in an interactive terminal to choose between a rename and a drop plus create.", + ); + this.name = "MigrationRenameAmbiguityError"; + this.kind = kind; + this.table = table; + this.created = Object.freeze([...created]); + this.deleted = Object.freeze([...deleted]); + } +} + +/** drizzle-kit's statement separator in v7 migration files. */ +const BREAKPOINT = "--> statement-breakpoint\n"; +const ORIGIN_ID = "00000000-0000-0000-0000-000000000000"; + +/** The parts of a drizzle-kit PostgreSQL snapshot this module reads. */ +interface Snapshot { + id: string; + tables: Record }>; + enums: Record; + [key: string]: unknown; +} + +/** drizzle-kit's empty starting snapshot (its `dryPg`). */ +function originSnapshot(): Snapshot { + return { + id: ORIGIN_ID, + prevId: "", + version: "7", + dialect: "postgresql", + tables: {}, + enums: {}, + schemas: {}, + sequences: {}, + roles: {}, + policies: {}, + views: {}, + _meta: { schemas: {}, tables: {}, columns: {} }, + }; +} + +function prefixOf(idx: number): string { + return String(idx).padStart(4, "0"); +} + +function snapshotFile(folder: string, idx: number): string { + return path.join(folder, "meta", `${prefixOf(idx)}_snapshot.json`); +} + +function latestSnapshot(folder: string, journal: Journal | null): Snapshot { + const last = journal?.entries.at(-1); + if (!last) return originSnapshot(); + const file = snapshotFile(folder, last.idx); + if (!fs.existsSync(file)) { + throw new Error( + `Missing ${file} for migration ${last.tag}. Restore it from version control; it is the baseline for the next migration.`, + ); + } + return readJsonFile(file); +} + +function keyDiff( + before: Record, + after: Record, +): { created: string[]; deleted: string[] } { + return { + created: Object.keys(after).filter((key) => !Object.hasOwn(before, key)), + deleted: Object.keys(before).filter((key) => !Object.hasOwn(after, key)), + }; +} + +/** The same "created and deleted together" conditions that make drizzle-kit prompt. */ +function findRenameAmbiguity( + prev: Snapshot, + cur: Snapshot, + schemaName: string, +): MigrationRenameAmbiguityError | null { + const tables = keyDiff(prev.tables, cur.tables); + if (tables.created.length > 0 && tables.deleted.length > 0) { + return new MigrationRenameAmbiguityError( + "table", + schemaName, + tables.created, + tables.deleted, + ); + } + const enums = keyDiff(prev.enums, cur.enums); + if (enums.created.length > 0 && enums.deleted.length > 0) { + return new MigrationRenameAmbiguityError( + "enum", + schemaName, + enums.created, + enums.deleted, + ); + } + for (const [key, table] of Object.entries(cur.tables)) { + const before = prev.tables[key]; + if (!before) continue; + const columns = keyDiff(before.columns, table.columns); + if (columns.created.length > 0 && columns.deleted.length > 0) { + return new MigrationRenameAmbiguityError( + "column", + key, + columns.created, + columns.deleted, + ); + } + } + return null; +} + +/** Whether drizzle-kit itself is not installed; module loaders may wrap that error. */ +function isDrizzleKitMissing(error: unknown): boolean { + let current = error; + for (let depth = 0; depth < 3 && current instanceof Error; depth++) { + if ( + (current as { code?: unknown }).code === "ERR_MODULE_NOT_FOUND" && + /['"]drizzle-kit['"]/.test(current.message) + ) { + return true; + } + current = current.cause; + } + return false; +} + +/** + * drizzle-kit is large, so apps install it as a dev dependency and it is loaded + * only when a migration is generated. + */ +async function loadDrizzleKit(): Promise { + try { + return await import("drizzle-kit/api"); + } catch (error) { + if (!isDrizzleKitMissing(error)) throw error; + throw new Error( + `Generating migrations needs drizzle-kit, which is not installed. Add it as a dev dependency: npm install --save-dev drizzle-kit@${DRIZZLE_KIT_VERSION}`, + { cause: error }, + ); + } +} + +/** + * Diff the schema against the latest committed snapshot with drizzle-kit and + * write the next v7 migration: `NNNN_migration.sql`, `meta/NNNN_snapshot.json`, + * and the appended `meta/_journal.json`. null when nothing changed. + */ +export async function generateMigrationFiles( + options: GenerateOptions, +): Promise { + const { generateDrizzleJson, generateMigration } = await loadDrizzleKit(); + + const journal = readJournal(options.folder); + const prev = latestSnapshot(options.folder, journal); + const cur = generateDrizzleJson(drizzleKitImports(options.schema), prev.id, [ + options.schema.$schemaName, + ]) as unknown as Snapshot; + + if (!options.interactive) { + const ambiguity = findRenameAmbiguity( + prev, + cur, + options.schema.$schemaName, + ); + if (ambiguity) throw ambiguity; + } + + type KitSnapshot = Parameters[0]; + const statements = await generateMigration( + prev as unknown as KitSnapshot, + cur as unknown as KitSnapshot, + ); + if (statements.length === 0) return null; + + const entries = journal?.entries ?? []; + const last = entries.at(-1); + const idx = last ? last.idx + 1 : 0; + const tag = `${prefixOf(idx)}_migration`; + const entry: JournalEntry = { + idx, + version: "7", + // The migrator applies entries newer than the last recorded one, so `when` must increase. + when: Math.max(Date.now(), (last?.when ?? 0) + 1), + tag, + breakpoints: true, + }; + const next: Journal = { + version: "7", + dialect: "postgresql", + entries: [...entries, entry], + }; + + const file = path.join(options.folder, `${tag}.sql`); + fs.mkdirSync(path.join(options.folder, "meta"), { recursive: true }); + fs.writeFileSync( + snapshotFile(options.folder, idx), + JSON.stringify( + { ...cur, _meta: { columns: {}, schemas: {}, tables: {} } }, + null, + 2, + ), + ); + fs.writeFileSync(file, statements.join(BREAKPOINT)); + // The journal is written last: it is what makes the migration visible. + fs.writeFileSync(journalFile(options.folder), JSON.stringify(next, null, 2)); + return { tag, file, statements }; +} diff --git a/packages/appkit/src/database/tooling/naming.ts b/packages/appkit/src/database/tooling/naming.ts new file mode 100644 index 000000000..aadaf374b --- /dev/null +++ b/packages/appkit/src/database/tooling/naming.ts @@ -0,0 +1,48 @@ +import { createHash } from "node:crypto"; + +// Branch names AppKit creates. Branch IDs: 1-63 chars, start with a +// lowercase letter, lowercase letters, digits and hyphens only. + +const MAX_BRANCH_ID = 63; +const DEV_PREFIX = "dev-"; +const SESSION_PREFIX = "session-"; +const HASH_LENGTH = 6; + +const SESSION_ID = /^[a-z0-9]{1,55}$/; + +function slug(value: string): string { + return value + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); +} + +/** + * dev--. The hash keeps users who share + * a local part apart; the name is the same on every machine. + */ +export function devBranchId(userName: string): string { + const normalized = userName.trim().toLowerCase(); + const hash = createHash("sha256") + .update(normalized) + .digest("hex") + .slice(0, HASH_LENGTH); + const room = MAX_BRANCH_ID - DEV_PREFIX.length - 1 - HASH_LENGTH; + const local = slug(normalized.split("@")[0] ?? "") + .slice(0, room) + .replace(/-+$/, ""); + return `${DEV_PREFIX}${local || "user"}-${hash}`; +} + +export function isValidSessionId(sessionId: string): boolean { + return SESSION_ID.test(sessionId); +} + +export function sessionBranchId(sessionId: string): string { + if (!isValidSessionId(sessionId)) { + throw new Error( + `Invalid APPKIT_DB_SESSION ${JSON.stringify(sessionId)}: use 1-55 lowercase letters or digits.`, + ); + } + return `${SESSION_PREFIX}${sessionId}`; +} diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts new file mode 100644 index 000000000..ff1cef3e8 --- /dev/null +++ b/packages/appkit/src/database/tooling/targets.ts @@ -0,0 +1,115 @@ +import fs from "node:fs"; +import path from "node:path"; + +import yaml from "js-yaml"; + +import { isValidSessionId } from "./naming"; + +/** Full resource names, e.g. branch = "projects/p/branches/b". */ +interface ResourceName { + readonly project: string; + readonly branch?: string; + readonly endpoint?: string; + readonly database?: string; +} + +const RESOURCE = + /^(projects\/[^/\s]+)(?:\/branches\/([^/\s]+)(?:\/(endpoints|databases)\/([^/\s]+))?)?$/; + +/** null for anything that is not a Lakebase project/branch/endpoint/database name (e.g. a placeholder). */ +export function parseResourceName( + name: string | undefined, +): ResourceName | null { + const match = name ? RESOURCE.exec(name.trim()) : null; + if (!match) return null; + const [, project, branchId, kind, leafId] = match; + if (!project) return null; + const branch = branchId ? `${project}/branches/${branchId}` : undefined; + const leaf = branch && leafId ? `${branch}/${kind}/${leafId}` : undefined; + return { + project, + ...(branch ? { branch } : {}), + ...(kind === "endpoints" && leaf ? { endpoint: leaf } : {}), + ...(kind === "databases" && leaf ? { database: leaf } : {}), + }; +} + +/** The last path segment of a resource name. */ +export function resourceId(name: string): string { + return name.slice(name.lastIndexOf("/") + 1); +} + +/** What `.env` says about the local branch. Unparseable values (template placeholders) read as null. */ +interface LocalTarget { + readonly endpoint: string | null; + readonly session: string | null; +} + +export function readLocalTarget(env: NodeJS.ProcessEnv): LocalTarget { + const endpoint = parseResourceName(env.LAKEBASE_ENDPOINT)?.endpoint ?? null; + const session = + env.APPKIT_DB_SESSION && isValidSessionId(env.APPKIT_DB_SESSION) + ? env.APPKIT_DB_SESSION + : null; + return { endpoint, session }; +} + +type Yaml = Record | undefined; + +function record(value: unknown): Yaml { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +/** databricks.yml, parsed; null without one. Invalid YAML throws, so no check that reads it passes silently. */ +function readBundle(root: string): Record | null { + const file = ["databricks.yml", "databricks.yaml"] + .map((name) => path.join(root, name)) + .find((candidate) => fs.existsSync(candidate)); + if (!file) return null; + try { + return record(yaml.load(fs.readFileSync(file, "utf-8"))) ?? {}; + } catch (error) { + const reason = error instanceof Error ? error.message.split("\n")[0] : ""; + throw new Error( + `Cannot read ${path.basename(file)}, so the branches it deploys to are unknown: ${reason}`, + { cause: error }, + ); + } +} + +/** A target's value for a bundle variable, else the variable's default. */ +function variableOf( + bundle: Record, + target: Yaml, + name: string, +): string | null { + const value = + record(target?.variables)?.[name] ?? + record(record(bundle.variables)?.[name])?.default ?? + null; + return typeof value === "string" && value ? value : null; +} + +/** + * Every branch databricks.yml can deploy to: each target's postgres_branch and + * the variable's default. Empty without databricks.yml or a postgres binding. + */ +export function readDeployBranches(root: string): string[] { + const bundle = readBundle(root); + if (!bundle) return []; + const targets = [ + undefined, + ...Object.values(record(bundle.targets) ?? {}).map(record), + ]; + const branches = targets + .map( + (target) => + parseResourceName( + variableOf(bundle, target, "postgres_branch") ?? undefined, + )?.branch, + ) + .filter((branch): branch is string => !!branch); + return [...new Set(branches)]; +} diff --git a/packages/appkit/src/database/tooling/tests/context.test.ts b/packages/appkit/src/database/tooling/tests/context.test.ts new file mode 100644 index 000000000..e7ac24dd5 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/context.test.ts @@ -0,0 +1,140 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { createWorkspaceClient, initializeLakebasePool } = vi.hoisted(() => ({ + createWorkspaceClient: vi.fn(), + initializeLakebasePool: vi.fn(), +})); + +vi.mock("../../../connectors/lakebase", () => ({ initializeLakebasePool })); +vi.mock("../../../workspace-client", () => ({ createWorkspaceClient })); + +import { getClientOptions } from "../../../context/client-options"; +import { createDbContext, openBranchPool } from "../context"; +import type { LakebaseApi } from "../lakebase-api"; +import { cleanupTempApps, FakeLakebase, fakeContext, tempApp } from "./fakes"; + +const BRANCH = "projects/p/branches/dev-alice-3f9a2c"; +const ENDPOINT = `${BRANCH}/endpoints/primary`; +const HOST = "primary.dev-alice-3f9a2c.example.com"; +const pool = { end: vi.fn() }; + +beforeEach(() => { + initializeLakebasePool.mockReset().mockResolvedValue(pool); + createWorkspaceClient.mockReset(); +}); +afterEach(cleanupTempApps); + +function contextFor(env: NodeJS.ProcessEnv, api: LakebaseApi) { + return fakeContext({ root: tempApp(), env, api }); +} + +describe("openBranchPool", () => { + test("null without PGHOST, PGDATABASE and LAKEBASE_ENDPOINT, before any API call", async () => { + const lakebase = new FakeLakebase(); + + await expect( + openBranchPool( + contextFor({ PGHOST: HOST, PGDATABASE: "db" }, lakebase.api()), + ), + ).resolves.toBeNull(); + expect(lakebase.calls).toEqual([]); + expect(initializeLakebasePool).not.toHaveBeenCalled(); + }); + + test("connects to PGHOST once it is a host of LAKEBASE_ENDPOINT", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(BRANCH); + const ctx = contextFor( + { + PGHOST: HOST.toUpperCase(), + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: ENDPOINT, + PGUSER: "alice@example.com", + }, + lakebase.api(), + ); + + await expect(openBranchPool(ctx)).resolves.toBe(pool); + expect(lakebase.calls).toEqual([`getEndpoint ${ENDPOINT}`]); + expect(initializeLakebasePool).toHaveBeenCalledWith( + expect.objectContaining({ + host: HOST.toUpperCase(), + database: "databricks_postgres", + endpoint: ENDPOINT, + user: "alice@example.com", + max: 2, + }), + ); + }); + + test("refuses another branch's host, a missing endpoint, or a failed lookup, and never connects", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(BRANCH); + const env = { + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: ENDPOINT, + }; + + await expect( + openBranchPool( + contextFor( + { ...env, PGHOST: "primary.production.example.com" }, + lakebase.api(), + ), + ), + ).rejects.toThrow( + `PGHOST primary.production.example.com is not a host of LAKEBASE_ENDPOINT ${ENDPOINT} (expected ${HOST}), so it did not connect. Run \`appkit db init\` to rewrite .env.`, + ); + await expect( + openBranchPool( + contextFor( + { + ...env, + PGHOST: HOST, + LAKEBASE_ENDPOINT: `${BRANCH}/endpoints/gone`, + }, + lakebase.api(), + ), + ), + ).rejects.toThrow( + `LAKEBASE_ENDPOINT ${BRANCH}/endpoints/gone does not exist, so it did not connect.`, + ); + + const lookupFailure = new Error("Lakebase: get endpoint failed: timeout"); + const failing = { + getEndpoint: async () => { + throw lookupFailure; + }, + } as unknown as LakebaseApi; + const error = (await openBranchPool( + contextFor({ ...env, PGHOST: HOST }, failing), + ).catch((caught: unknown) => caught)) as Error; + expect(error.message).toBe( + `Could not verify that PGHOST ${HOST} serves LAKEBASE_ENDPOINT ${ENDPOINT}, so it did not connect.`, + ); + expect(error.cause).toBe(lookupFailure); + + expect(initializeLakebasePool).not.toHaveBeenCalled(); + }); +}); + +describe("createDbContext", () => { + test("the workspace client uses the .env profile and AppKit's client options, once", () => { + const legacy = { apiClient: {}, currentUser: {} }; + createWorkspaceClient.mockReturnValue({ + toLegacyWorkspaceClient: () => legacy, + }); + const ctx = createDbContext({ + root: tempApp(), + env: { DATABRICKS_CONFIG_PROFILE: "dev" }, + }); + + expect(ctx.workspace()).toBe(legacy); + expect(ctx.workspace()).toBe(legacy); + expect(createWorkspaceClient).toHaveBeenCalledOnce(); + expect(createWorkspaceClient).toHaveBeenCalledWith({ + profile: "dev", + clientOptions: getClientOptions(), + }); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/drizzle-exports.test.ts b/packages/appkit/src/database/tooling/tests/drizzle-exports.test.ts new file mode 100644 index 000000000..cda0e8a9a --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/drizzle-exports.test.ts @@ -0,0 +1,47 @@ +import { is } from "drizzle-orm"; +import { isPgEnum, PgSchema, PgTable } from "drizzle-orm/pg-core"; +import { describe, expect, test } from "vitest"; + +import { defineSchema, enumColumn, fk, id, text } from "../../schema-builder"; +import { drizzleKitImports } from "../drizzle-exports"; + +describe("drizzleKitImports", () => { + const schema = defineSchema(({ table }) => { + const users = table("users", { + id: id(), + role: enumColumn("user_role", ["admin", "member"]), + backup: enumColumn("user_role", ["admin", "member"]), + }); + const posts = table("posts", { + id: id(), + author: fk(() => users.id), + title: text(), + }); + return { users, posts }; + }); + + test("exports every engine table and each referenced enum once", () => { + const values = Object.values(drizzleKitImports(schema)); + expect(values.filter((value) => is(value, PgTable))).toEqual([ + schema.$engine.users, + schema.$engine.posts, + ]); + const enums = values.filter((value) => isPgEnum(value)); + expect(enums).toHaveLength(1); + const [userRole] = enums; + expect(userRole.enumName).toBe("user_role"); + expect(userRole.schema).toBe("app"); + expect(userRole.enumValues).toEqual(["admin", "member"]); + }); + + test("never exports the pgSchema object, so drizzle-kit emits no CREATE SCHEMA", () => { + const values = Object.values(drizzleKitImports(schema)); + expect(values.some((value) => is(value, PgSchema))).toBe(false); + }); + + test("an empty schema has nothing to export", () => { + expect(Object.keys(drizzleKitImports(defineSchema(() => ({}))))).toEqual( + [], + ); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts b/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts new file mode 100644 index 000000000..ec9bcb2d1 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts @@ -0,0 +1,104 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { defineSchema, id } from "../../schema-builder"; + +const SRC = path.resolve(import.meta.dirname, "../../.."); +const folders: string[] = []; + +afterEach(() => { + vi.doUnmock("drizzle-kit/api"); + vi.resetModules(); + for (const folder of folders.splice(0)) { + fs.rmSync(folder, { recursive: true, force: true }); + } +}); + +/** Load ../migrations with `import("drizzle-kit/api")` failing like Node's resolver does. */ +async function withoutPackage(name: string) { + vi.resetModules(); + vi.doMock("drizzle-kit/api", () => { + throw Object.assign( + new Error( + `Cannot find package '${name}' imported from /app/node_modules/@databricks/appkit/dist/database/tooling/migrations.js`, + ), + { code: "ERR_MODULE_NOT_FOUND" }, + ); + }); + return import("../migrations"); +} + +function generate(migrations: typeof import("../migrations")) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-drizzle-kit-")); + folders.push(root); + return migrations.generateMigrationFiles({ + folder: path.join(root, "migrations"), + schema: defineSchema(({ table }) => ({ + notes: table("notes", { id: id() }), + })), + interactive: false, + }); +} + +/** Source files outside tests, relative to src/. */ +function sourceFiles(): string[] { + return (fs.readdirSync(SRC, { recursive: true }) as string[]).filter( + (file) => + /\.tsx?$/.test(file) && + !/\.test\.tsx?$/.test(file) && + !file.split(path.sep).includes("tests"), + ); +} + +describe("drizzle-kit dependency", () => { + test("without drizzle-kit, generating says how to install it", async () => { + const migrations = await withoutPackage("drizzle-kit"); + + await expect(generate(migrations)).rejects.toThrow( + `Generating migrations needs drizzle-kit, which is not installed. Add it as a dev dependency: npm install --save-dev drizzle-kit@${migrations.DRIZZLE_KIT_VERSION}`, + ); + }); + + test("another missing package is not reported as a missing drizzle-kit", async () => { + const migrations = await withoutPackage("esbuild"); + + const error = (await generate(migrations).catch( + (caught: unknown) => caught, + )) as Error; + expect(error.message).not.toContain("npm install"); + }); + + test("it is an optional peer dependency pinned to DRIZZLE_KIT_VERSION, never a dependency", async () => { + const { DRIZZLE_KIT_VERSION } = await import("../migrations"); + const pkg = JSON.parse( + fs.readFileSync(path.resolve(SRC, "../package.json"), "utf-8"), + ); + + expect(pkg.dependencies["drizzle-kit"]).toBeUndefined(); + expect(pkg.peerDependencies["drizzle-kit"]).toBe(DRIZZLE_KIT_VERSION); + expect(pkg.peerDependenciesMeta["drizzle-kit"]).toEqual({ optional: true }); + expect(pkg.devDependencies["drizzle-kit"]).toBe(DRIZZLE_KIT_VERSION); + }); + + test("only the tooling imports drizzle-kit, and no runtime module imports the tooling", () => { + const imports = (file: string, pattern: RegExp) => + pattern.test(fs.readFileSync(path.join(SRC, file), "utf-8")); + const tooling = path.join("database", "tooling"); + + expect( + sourceFiles().filter((file) => + imports(file, /(?:from\s+|import\s*\(\s*)["']drizzle-kit/), + ), + ).toEqual([path.join(tooling, "migrations.ts")]); + expect( + sourceFiles().filter( + (file) => + !file.startsWith(`${tooling}${path.sep}`) && + imports(file, /from\s+["'][^"']*\/tooling(?:\/[^"']*)?["']/), + ), + ).toEqual([]); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/fakes.ts b/packages/appkit/src/database/tooling/tests/fakes.ts new file mode 100644 index 000000000..c10e139af --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/fakes.ts @@ -0,0 +1,122 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import type { DbContext } from "../context"; +import type { + LakebaseApi, + LakebaseBranch, + LakebaseEndpoint, +} from "../lakebase-api"; + +/** In-memory Lakebase: the branches the guard looks up, and their endpoints. */ +export class FakeLakebase { + readonly branches = new Map(); + readonly endpoints = new Map(); + readonly calls: string[] = []; + + addBranch( + name: string, + status: LakebaseBranch["status"] = {}, + ): LakebaseBranch { + const branch = { name, status: { current_state: "READY", ...status } }; + this.branches.set(name, branch); + this.endpoints.set(name, [this.endpoint(name, "primary")]); + return branch; + } + + endpoint(branch: string, id: string): LakebaseEndpoint { + return { + name: `${branch}/endpoints/${id}`, + status: { + hosts: { host: `${id}.${branch.split("/").pop()}.example.com` }, + }, + }; + } + + api(): LakebaseApi { + const fake = this; + const api = { + async getBranch(name: string) { + fake.calls.push(`getBranch ${name}`); + return fake.branches.get(name) ?? null; + }, + async getEndpoint(name: string) { + fake.calls.push(`getEndpoint ${name}`); + const branch = name.slice(0, name.indexOf("/endpoints/")); + return ( + fake.endpoints + .get(branch) + ?.find((endpoint) => endpoint.name === name) ?? null + ); + }, + }; + return api as unknown as LakebaseApi; + } +} + +const roots: string[] = []; + +/** A temp app root with optional files (relative path → contents). */ +export function tempApp(files: Record = {}): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-db-tooling-")); + roots.push(root); + for (const [file, contents] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + fs.writeFileSync(path.join(root, file), contents); + } + return root; +} + +export function cleanupTempApps(): void { + for (const root of roots.splice(0)) + fs.rmSync(root, { recursive: true, force: true }); +} + +export function fakeContext(options: { + root: string; + env?: NodeJS.ProcessEnv; + userName?: string; + api?: LakebaseApi; +}): DbContext { + const userName = options.userName ?? "alice@example.com"; + return { + root: options.root, + env: { ...options.env }, + workspace: () => ({ + apiClient: { + request: async () => { + throw new Error("no raw API calls expected"); + }, + }, + currentUser: { me: async () => ({ userName }) }, + }), + api: () => { + if (!options.api) throw new Error("no Lakebase API calls expected"); + return options.api; + }, + }; +} + +/** The bundle `databricks apps init` writes for a database app. */ +export function databricksYml(branch: string, database: string): string { + return `bundle: + name: my-app +variables: + postgres_branch: + description: Lakebase branch resource name + postgres_database: + description: Lakebase database resource name +resources: + apps: + app: + name: "my-app" + source_code_path: ./ +targets: + default: + default: true + variables: + postgres_branch: ${branch} + postgres_database: ${database} +`; +} diff --git a/packages/appkit/src/database/tooling/tests/guard.test.ts b/packages/appkit/src/database/tooling/tests/guard.test.ts new file mode 100644 index 000000000..175f9823c --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/guard.test.ts @@ -0,0 +1,167 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { checkAppkitBranch, classifyBranch } from "../guard"; +import { devBranchId } from "../naming"; +import { + cleanupTempApps, + databricksYml, + FakeLakebase, + fakeContext, + tempApp, +} from "./fakes"; + +afterEach(cleanupTempApps); + +const USER = "alice@example.com"; +const P = "projects/p"; +const dev = `${P}/branches/${devBranchId(USER)}`; + +function verdict( + name: string, + status = {}, + sessionId: string | null = "k2x9q0ab", + deployBranches: string[] = [], +) { + return classifyBranch({ + branch: { name, status }, + userName: USER, + sessionId, + deployBranches, + }); +} + +describe("classifyBranch", () => { + test("only this developer's dev branch and this checkout's session branch are AppKit-owned", () => { + expect(verdict(dev)).toEqual({ appkitOwned: true }); + expect(verdict(`${P}/branches/session-k2x9q0ab`)).toEqual({ + appkitOwned: true, + }); + }); + + test("everything else is refused, with the reason", () => { + expect( + verdict(`${P}/branches/production`, { default: true }), + ).toMatchObject({ + appkitOwned: false, + reason: "it is the project's default branch", + }); + expect(verdict(dev, { is_protected: true })).toMatchObject({ + appkitOwned: false, + reason: "it is a protected branch", + }); + expect( + verdict(dev, {}, null, [`${P}/branches/staging`, dev]), + ).toMatchObject({ + appkitOwned: false, + reason: "it is a branch databricks.yml deploys to", + }); + expect( + verdict(`${P}/branches/${devBranchId("bob@example.com")}`).appkitOwned, + ).toBe(false); + expect(verdict(`${P}/branches/session-other`).appkitOwned).toBe(false); + expect( + verdict(`${P}/branches/session-k2x9q0ab`, {}, null).appkitOwned, + ).toBe(false); + expect(verdict(`${P}/branches/staging`).reason).toContain( + devBranchId(USER), + ); + }); +}); + +describe("checkAppkitBranch", () => { + const envFor = (branch: string) => ({ + LAKEBASE_ENDPOINT: `${branch}/endpoints/primary`, + }); + + test("classifies the .env branch through the API, without connecting", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(dev); + lakebase.addBranch(`${P}/branches/production`, { default: true }); + + const onDev = await checkAppkitBranch( + fakeContext({ root: tempApp(), env: envFor(dev), api: lakebase.api() }), + ); + expect(onDev).toMatchObject({ + branch: { name: dev }, + verdict: { appkitOwned: true }, + }); + + const onDefault = await checkAppkitBranch( + fakeContext({ + root: tempApp(), + env: envFor(`${P}/branches/production`), + api: lakebase.api(), + }), + ); + expect(onDefault?.verdict).toEqual({ + appkitOwned: false, + reason: "it is the project's default branch", + }); + expect(lakebase.calls.every((call) => call.startsWith("getBranch"))).toBe( + true, + ); + }); + + test("a branch databricks.yml deploys to is never AppKit-owned", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(dev); + const root = tempApp({ + "databricks.yml": databricksYml( + dev, + `${dev}/databases/databricks-postgres`, + ), + }); + + const check = await checkAppkitBranch( + fakeContext({ root, env: envFor(dev), api: lakebase.api() }), + ); + + expect(check?.verdict).toEqual({ + appkitOwned: false, + reason: "it is a branch databricks.yml deploys to", + }); + }); + + test("a non-default target counts too, and an unreadable databricks.yml refuses", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(dev); + const personalTarget = tempApp({ + "databricks.yml": `${databricksYml(`${P}/branches/production`, `${P}/branches/production/databases/db`)} personal: + variables: + postgres_branch: ${dev} +`, + }); + const broken = tempApp({ "databricks.yml": "targets:\n default: [\n" }); + + const check = await checkAppkitBranch( + fakeContext({ + root: personalTarget, + env: envFor(dev), + api: lakebase.api(), + }), + ); + expect(check?.verdict).toEqual({ + appkitOwned: false, + reason: "it is a branch databricks.yml deploys to", + }); + await expect( + checkAppkitBranch( + fakeContext({ root: broken, env: envFor(dev), api: lakebase.api() }), + ), + ).rejects.toThrow( + /^Cannot read databricks\.yml, so the branches it deploys to are unknown: /, + ); + }); + + test("null without a configured branch; a deleted branch points at init", async () => { + const lakebase = new FakeLakebase(); + await expect( + checkAppkitBranch(fakeContext({ root: tempApp(), api: lakebase.api() })), + ).resolves.toBeNull(); + await expect( + checkAppkitBranch( + fakeContext({ root: tempApp(), env: envFor(dev), api: lakebase.api() }), + ), + ).rejects.toThrow(/does not exist.*appkit db init/); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/identity.test.ts b/packages/appkit/src/database/tooling/tests/identity.test.ts new file mode 100644 index 000000000..d600a844b --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/identity.test.ts @@ -0,0 +1,32 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { currentIdentity } from "../identity"; +import { cleanupTempApps, fakeContext, tempApp } from "./fakes"; + +afterEach(cleanupTempApps); + +describe("identity", () => { + test("currentUser.me() is called once per context", async () => { + const ctx = fakeContext({ root: tempApp() }); + const me = vi.fn(async () => ({ userName: "alice@example.com" })); + const client = { ...ctx.workspace(), currentUser: { me } }; + const counted = { ...ctx, workspace: () => client }; + + await expect(currentIdentity(counted)).resolves.toEqual({ + userName: "alice@example.com", + }); + await currentIdentity(counted); + expect(me).toHaveBeenCalledOnce(); + }); + + test("no userName is an error that points at the profile", async () => { + const ctx = fakeContext({ root: tempApp() }); + const client = { + ...ctx.workspace(), + currentUser: { me: async () => ({}) }, + }; + await expect( + currentIdentity({ ...ctx, workspace: () => client }), + ).rejects.toThrow(/DATABRICKS_CONFIG_PROFILE/); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts new file mode 100644 index 000000000..22adaa0f3 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, test } from "vitest"; + +import type { ToolingRequest } from "../context"; +import { LakebaseApi, LakebaseApiError } from "../lakebase-api"; + +type Reply = unknown | ((request: ToolingRequest) => unknown); + +/** apiClient fake: replies in order, records each request. */ +function client(replies: Reply[]) { + const requests: ToolingRequest[] = []; + return { + requests, + apiClient: { + async request(request: ToolingRequest) { + requests.push(request); + if (replies.length === 0) + throw new Error( + `unexpected request ${request.method} ${request.path}`, + ); + const reply = replies.shift(); + const value = + typeof reply === "function" + ? (reply as (r: ToolingRequest) => unknown)(request) + : reply; + if (value instanceof Error) throw value; + return value; + }, + }, + }; +} + +const apiError = (statusCode: number, message: string) => + Object.assign(new Error(message), { statusCode, errorCode: "X" }); + +describe("LakebaseApi", () => { + test("getBranch: GET /api/2.0/postgres/{name}; 404 → null; other errors keep their status", async () => { + const fake = client([ + { name: "projects/p/branches/b" }, + apiError(404, "NOT_FOUND"), + apiError(403, "PERMISSION_DENIED"), + ]); + const api = new LakebaseApi(fake); + + await expect(api.getBranch("projects/p/branches/b")).resolves.toEqual({ + name: "projects/p/branches/b", + }); + await expect( + api.getBranch("projects/p/branches/missing"), + ).resolves.toBeNull(); + const error = await api + .getBranch("projects/p/branches/x") + .catch((e: unknown) => e); + expect(error).toBeInstanceOf(LakebaseApiError); + expect(error).toMatchObject({ + statusCode: 403, + operation: "get branch projects/p/branches/x", + }); + + expect(fake.requests[0]).toMatchObject({ + path: "/api/2.0/postgres/projects/p/branches/b", + method: "GET", + raw: false, + }); + expect(fake.requests[0]?.headers.get("Accept")).toBe("application/json"); + expect(fake.requests[0]?.headers.get("Content-Type")).toBeNull(); + }); + + test("getEndpoint: GET /api/2.0/postgres/{name}; 404 → null", async () => { + const endpoint = { + name: "projects/p/branches/b/endpoints/primary", + status: { hosts: { host: "ep-1.example.com" } }, + }; + const fake = client([endpoint, apiError(404, "NOT_FOUND")]); + const api = new LakebaseApi(fake); + + await expect(api.getEndpoint(endpoint.name)).resolves.toEqual(endpoint); + await expect( + api.getEndpoint("projects/p/branches/b/endpoints/gone"), + ).resolves.toBeNull(); + expect( + fake.requests.map((request) => [request.method, request.path]), + ).toEqual([ + ["GET", "/api/2.0/postgres/projects/p/branches/b/endpoints/primary"], + ["GET", "/api/2.0/postgres/projects/p/branches/b/endpoints/gone"], + ]); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts new file mode 100644 index 000000000..93f0eb500 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -0,0 +1,253 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { applyPendingMigrations, checkAppkitBranch, openBranchPool } = + vi.hoisted(() => ({ + applyPendingMigrations: vi.fn(), + checkAppkitBranch: vi.fn(), + openBranchPool: vi.fn(), + })); + +vi.mock("../../migrations/apply", () => ({ applyPendingMigrations })); +vi.mock("../guard", () => ({ checkAppkitBranch })); +vi.mock("../context", async (importOriginal) => ({ + ...(await importOriginal()), + openBranchPool, +})); + +import type { DbContext } from "../context"; +import { runMigrate } from "../migrate"; + +const builder = path.resolve( + import.meta.dirname, + "../../schema-builder/index.ts", +); +const roots: string[] = []; + +function app(tables: string): DbContext { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-db-migrate-")); + roots.push(root); + const file = path.join(root, "config/database/schema.ts"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync( + file, + `import { defineSchema, id, text } from ${JSON.stringify(builder)}; + export const schema = defineSchema(({ table }) => ({ ${tables} }));`, + ); + return { + root, + env: {}, + workspace: () => { + throw new Error("no workspace calls expected"); + }, + api: () => { + throw new Error("no Lakebase API calls expected"); + }, + }; +} + +const devBranch = { + branch: { name: "projects/p/branches/dev-alice-3f9a2c" }, + verdict: { appkitOwned: true }, +}; + +const pool = { end: vi.fn(async () => undefined) }; + +beforeEach(() => { + applyPendingMigrations.mockReset(); + openBranchPool.mockReset(); + checkAppkitBranch.mockReset(); + checkAppkitBranch.mockResolvedValue(devBranch); + pool.end.mockClear(); +}); + +afterEach(() => { + for (const root of roots.splice(0)) { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +describe("runMigrate", () => { + test("without schema.ts it points to introspect before touching anything", async () => { + const ctx = app(""); + fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); + + await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( + "No config/database/schema.ts yet, so there is nothing to migrate. Run `appkit db introspect` to write it from the branch's tables, or create it.", + ); + expect(checkAppkitBranch).not.toHaveBeenCalled(); + expect( + fs.existsSync(path.join(ctx.root, "config/database/migrations")), + ).toBe(false); + }); + + test("an empty schema generates nothing, applies nothing, and still writes database.d.ts", async () => { + const ctx = app(""); + const report = await runMigrate(ctx, { interactive: false }); + + expect(report.generated).toBeNull(); + expect(report.applied).toEqual([]); + expect(report.notApplied).toMatch(/no migrations/); + expect(openBranchPool).not.toHaveBeenCalled(); + expect(checkAppkitBranch).not.toHaveBeenCalled(); + expect(report.typesFile).toBe( + path.join(ctx.root, "shared/appkit-types/database.d.ts"), + ); + expect(fs.existsSync(report.typesFile)).toBe(true); + }); + + test("generates, regenerates types, applies to the .env branch with the app schema, and ends the pool", async () => { + const ctx = app(`notes: table("notes", { id: id(), body: text() })`); + openBranchPool.mockResolvedValue(pool); + applyPendingMigrations.mockResolvedValue({ + applied: ["0000_migration"], + adopted: [], + }); + + const report = await runMigrate(ctx, { interactive: false }); + + expect(report.generated?.tag).toBe("0000_migration"); + expect(openBranchPool).toHaveBeenCalledWith(ctx); + expect(applyPendingMigrations).toHaveBeenCalledWith(pool, { + migrationsFolder: path.join(ctx.root, "config/database/migrations"), + schemaName: "app", + }); + expect(report.applied).toEqual(["0000_migration"]); + expect(report.notApplied).toBeUndefined(); + expect(pool.end).toHaveBeenCalledOnce(); + expect(fs.readFileSync(report.typesFile, "utf-8")).toContain("notes"); + }); + + test("applies committed migrations even when schema.ts did not change", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + openBranchPool.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + + openBranchPool.mockResolvedValue(pool); + applyPendingMigrations.mockResolvedValue({ + applied: ["0000_migration"], + adopted: [], + }); + const report = await runMigrate(ctx, { interactive: false }); + + expect(report.generated).toBeNull(); + expect(report.applied).toEqual(["0000_migration"]); + }); + + test("without a configured branch it still generates, and says why nothing was applied", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + checkAppkitBranch.mockResolvedValue(null); + + const report = await runMigrate(ctx, { interactive: false }); + + expect(report.generated?.tag).toBe("0000_migration"); + expect(applyPendingMigrations).not.toHaveBeenCalled(); + expect(report.notApplied).toMatch(/appkit db init/); + expect(fs.existsSync(report.typesFile)).toBe(true); + }); + + test("on a branch AppKit did not create for you it generates, never connects, and says why", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + checkAppkitBranch.mockResolvedValue({ + branch: { name: "projects/p/branches/production" }, + verdict: { + appkitOwned: false, + reason: "it is the project's default branch", + }, + }); + + const report = await runMigrate(ctx, { interactive: false }); + + expect(report.generated?.tag).toBe("0000_migration"); + expect(openBranchPool).not.toHaveBeenCalled(); + expect(applyPendingMigrations).not.toHaveBeenCalled(); + expect(report.notApplied).toBe( + "production is not an AppKit dev or session branch (it is the project's default branch). Migrations are applied only to branches `appkit db init` created for you; the deployed app applies committed migrations to its own branch", + ); + expect(fs.existsSync(report.typesFile)).toBe(true); + }); + + test("reports a baseline adopted without running it", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + checkAppkitBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + + checkAppkitBranch.mockResolvedValue(devBranch); + openBranchPool.mockResolvedValue(pool); + applyPendingMigrations.mockResolvedValue({ + applied: [], + adopted: ["0000_baseline"], + }); + const report = await runMigrate(ctx, { interactive: false }); + + expect(report).toMatchObject({ applied: [], adopted: ["0000_baseline"] }); + }); + + test("an apply failure ends the pool and says the generated migration was written but not applied", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + openBranchPool.mockResolvedValue(pool); + const failure = new Error("apply failed"); + applyPendingMigrations.mockRejectedValue(failure); + + const error = (await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + )) as Error; + + expect(error.message).toBe( + `Wrote ${path.join("config/database/migrations", "0000_migration.sql")}, but did not apply it: apply failed`, + ); + expect(error.cause).toBe(failure); + expect(pool.end).toHaveBeenCalledOnce(); + expect( + fs.existsSync( + path.join(ctx.root, "config/database/migrations/0000_migration.sql"), + ), + ).toBe(true); + expect( + fs.readFileSync( + path.join(ctx.root, "shared/appkit-types/database.d.ts"), + "utf-8", + ), + ).toContain("notes"); + }); + + test("a guard failure after generating says so too, and never connects", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + checkAppkitBranch.mockRejectedValue( + new Error("The .env branch projects/p/branches/dev-a does not exist"), + ); + + await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( + /^Wrote .*0000_migration\.sql, but did not apply it: The \.env branch .* does not exist$/, + ); + expect(openBranchPool).not.toHaveBeenCalled(); + }); + + test("a failure with nothing generated propagates unchanged", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + checkAppkitBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + + checkAppkitBranch.mockResolvedValue(devBranch); + openBranchPool.mockResolvedValue(pool); + const failure = new Error("apply failed"); + applyPendingMigrations.mockRejectedValue(failure); + + await expect(runMigrate(ctx, { interactive: false })).rejects.toBe(failure); + }); + + test("a schema.ts that fails to import names the import error, not the runtime hint", async () => { + const ctx = app(`notes: table("notes", { id: id( })`); + + const error = (await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + )) as Error; + + expect(error.message).toBe("Could not load config/database/schema.ts."); + expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); + expect(checkAppkitBranch).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts new file mode 100644 index 000000000..39c8bf193 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -0,0 +1,343 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { readMigrationFiles } from "drizzle-orm/migrator"; +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { readJournal } from "../../migrations/paths"; +import { + bigid, + boolean, + defineSchema, + enumColumn, + fk, + id, + integer, + text, + timestamp, + varchar, +} from "../../schema-builder"; +import { + generateMigrationFiles, + MigrationRenameAmbiguityError, +} from "../migrations"; + +const folders: string[] = []; + +function tempFolder(): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-migrations-")); + folders.push(root); + return path.join(root, "config/database/migrations"); +} + +/** Every file under a folder, relative, sorted — to prove nothing was written. */ +function listFiles(folder: string): string[] { + if (!fs.existsSync(folder)) return []; + return (fs.readdirSync(folder, { recursive: true }) as string[]) + .filter((entry) => fs.statSync(path.join(folder, entry)).isFile()) + .sort(); +} + +afterEach(() => { + vi.useRealTimers(); + for (const folder of folders.splice(0)) { + fs.rmSync(folder, { recursive: true, force: true }); + } +}); + +const blog = (extraPostColumns = {}) => + defineSchema(({ table }) => { + const authors = table("authors", { + id: id(), + email: text().notNull().unique(), + role: enumColumn("author_role", ["admin", "writer"]) + .notNull() + .default("writer"), + createdAt: timestamp({ withTimezone: true }).defaultNow(), + }); + const posts = table("posts", { + id: bigid(), + author: fk(() => authors.id).onDelete("cascade"), + title: varchar(120).notNull(), + published: boolean().default(false), + ...extraPostColumns, + }); + return { authors, posts }; + }); + +describe("generateMigrationFiles", () => { + test("writes a v7 migration from real drizzle-kit output for the builder's tables", async () => { + const folder = tempFolder(); + const generated = await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + + expect(generated?.tag).toBe("0000_migration"); + expect(generated?.file).toBe(path.join(folder, "0000_migration.sql")); + const sql = fs.readFileSync( + path.join(folder, "0000_migration.sql"), + "utf-8", + ); + + expect(sql).toContain( + `CREATE TYPE "app"."author_role" AS ENUM('admin', 'writer');`, + ); + expect(sql).toContain(`CREATE TABLE "app"."authors"`); + expect(sql).toContain(`CREATE TABLE "app"."posts"`); + expect(sql).toMatch( + /"id" integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY/, + ); + expect(sql).toMatch( + /"id" bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY/, + ); + expect(sql).toContain( + `"role" "app"."author_role" DEFAULT 'writer' NOT NULL`, + ); + expect(sql).toMatch( + /FOREIGN KEY \("author"\) REFERENCES "app"\."authors"\("id"\) ON DELETE cascade/, + ); + // The migrator creates the schema as the identity that applies it; generated SQL never does. + expect(sql).not.toMatch(/CREATE SCHEMA/i); + expect(sql).toContain("--> statement-breakpoint\n"); + + expect(listFiles(folder)).toEqual([ + "0000_migration.sql", + path.join("meta", "0000_snapshot.json"), + path.join("meta", "_journal.json"), + ]); + const journal = readJournal(folder); + expect(journal).toMatchObject({ + version: "7", + dialect: "postgresql", + entries: [ + { idx: 0, version: "7", tag: "0000_migration", breakpoints: true }, + ], + }); + const snapshot = JSON.parse( + fs.readFileSync(path.join(folder, "meta/0000_snapshot.json"), "utf-8"), + ); + expect(Object.keys(snapshot.tables)).toEqual(["app.authors", "app.posts"]); + expect(snapshot.prevId).toBe("00000000-0000-0000-0000-000000000000"); + }); + + test("returns null and writes nothing when the schema matches the latest snapshot", async () => { + const folder = tempFolder(); + await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + const before = listFiles(folder).map((file) => [ + file, + fs.readFileSync(path.join(folder, file), "utf-8"), + ]); + + await expect( + generateMigrationFiles({ folder, schema: blog(), interactive: false }), + ).resolves.toBeNull(); + expect( + listFiles(folder).map((file) => [ + file, + fs.readFileSync(path.join(folder, file), "utf-8"), + ]), + ).toEqual(before); + }); + + test("an added column produces the next migration with an ALTER TABLE", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); + const folder = tempFolder(); + await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + + // A clock that did not move must still yield a newer journal entry. + const next = await generateMigrationFiles({ + folder, + schema: blog({ views: integer().notNull().default(0) }), + interactive: false, + }); + + expect(next?.tag).toBe("0001_migration"); + expect(next?.statements).toEqual([ + `ALTER TABLE "app"."posts" ADD COLUMN "views" integer DEFAULT 0 NOT NULL;`, + ]); + const journal = readJournal(folder); + expect(journal?.entries.map((entry) => entry.tag)).toEqual([ + "0000_migration", + "0001_migration", + ]); + const [first, second] = journal?.entries ?? []; + expect(second.when).toBeGreaterThan(first.when); + const prev = JSON.parse( + fs.readFileSync(path.join(folder, "meta/0000_snapshot.json"), "utf-8"), + ); + const cur = JSON.parse( + fs.readFileSync(path.join(folder, "meta/0001_snapshot.json"), "utf-8"), + ); + expect(cur.prevId).toBe(prev.id); + }); + + test("a non-interactive column rename throws instead of prompting, and writes nothing", async () => { + const folder = tempFolder(); + await generateMigrationFiles({ + folder, + schema: blog({ summary: text() }), + interactive: false, + }); + const before = listFiles(folder); + + const error = await generateMigrationFiles({ + folder, + schema: blog({ abstract: text() }), + interactive: false, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(MigrationRenameAmbiguityError); + expect(error).toMatchObject({ + kind: "column", + table: "app.posts", + created: ["abstract"], + deleted: ["summary"], + }); + expect((error as Error).message).toMatch(/interactive terminal/); + expect(listFiles(folder)).toEqual(before); + }); + + test("a non-interactive table rename throws too", async () => { + const folder = tempFolder(); + const named = (name: string) => + defineSchema(({ table }) => ({ [name]: table(name, { id: id() }) })); + await generateMigrationFiles({ + folder, + schema: named("notes"), + interactive: false, + }); + + await expect( + generateMigrationFiles({ + folder, + schema: named("memos"), + interactive: false, + }), + ).rejects.toMatchObject({ + name: "MigrationRenameAmbiguityError", + kind: "table", + created: ["app.memos"], + deleted: ["app.notes"], + }); + }); + + test("an empty schema with no history writes nothing", async () => { + const folder = tempFolder(); + await expect( + generateMigrationFiles({ + folder, + schema: defineSchema(() => ({})), + interactive: false, + }), + ).resolves.toBeNull(); + expect(listFiles(folder)).toEqual([]); + }); + + test("drizzle-orm's runtime migrator reads the written files", async () => { + const folder = tempFolder(); + await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + await generateMigrationFiles({ + folder, + schema: blog({ views: integer() }), + interactive: false, + }); + + const migrations = readMigrationFiles({ migrationsFolder: folder }); + const journal = readJournal(folder); + expect(migrations.map((migration) => migration.folderMillis)).toEqual( + journal?.entries.map((entry) => entry.when), + ); + // Four statements: the enum, two tables, the FK. + expect(migrations[0].sql).toHaveLength(4); + expect(migrations[1].sql).toEqual([ + `ALTER TABLE "app"."posts" ADD COLUMN "views" integer;`, + ]); + }); + + test("a non-interactive enum rename throws too, and writes nothing", async () => { + const folder = tempFolder(); + const roles = (enumName: string) => + defineSchema(({ table }) => ({ + users: table("users", { + id: id(), + role: enumColumn(enumName, ["admin", "member"]), + }), + })); + await generateMigrationFiles({ + folder, + schema: roles("user_role"), + interactive: false, + }); + const before = listFiles(folder); + + const error = await generateMigrationFiles({ + folder, + schema: roles("member_role"), + interactive: false, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(MigrationRenameAmbiguityError); + expect(error).toMatchObject({ + kind: "enum", + created: ["app.member_role"], + deleted: ["app.user_role"], + }); + expect(listFiles(folder)).toEqual(before); + }); + + test("refuses to diff when the latest snapshot is missing", async () => { + const folder = tempFolder(); + await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + fs.rmSync(path.join(folder, "meta/0000_snapshot.json")); + await expect( + generateMigrationFiles({ + folder, + schema: blog({ views: integer() }), + interactive: false, + }), + ).rejects.toThrow(/Restore it from version control/); + }); + + test("a corrupt snapshot names the file and how to recover", async () => { + const folder = tempFolder(); + await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + const snapshot = path.join(folder, "meta/0000_snapshot.json"); + fs.writeFileSync(snapshot, "{ not json"); + + await expect( + generateMigrationFiles({ + folder, + schema: blog({ views: integer() }), + interactive: false, + }), + ).rejects.toThrow( + new RegExp( + `^Cannot read ${snapshot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}: .+\\. Restore it from version control\\.$`, + ), + ); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/naming.test.ts b/packages/appkit/src/database/tooling/tests/naming.test.ts new file mode 100644 index 000000000..423f33ad0 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/naming.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, test } from "vitest"; + +import { devBranchId, isValidSessionId, sessionBranchId } from "../naming"; + +const BRANCH_ID = /^[a-z][a-z0-9-]{0,62}$/; + +describe("branch naming", () => { + test("dev branches are dev--<6 hex>, stable and case-insensitive", () => { + const id = devBranchId("Alice.Smith@example.com"); + expect(id).toMatch(/^dev-alice-smith-[0-9a-f]{6}$/); + expect(devBranchId("alice.smith@example.com")).toBe(id); + expect(id).toMatch(BRANCH_ID); + }); + + test("users sharing a local part get different branches", () => { + expect(devBranchId("alice@example.com")).not.toBe( + devBranchId("alice@example.org"), + ); + }); + + test("long or odd local parts stay within the 63-character limit", () => { + const id = devBranchId(`${"x".repeat(80)}@example.com`); + expect(id.length).toBeLessThanOrEqual(63); + expect(id).toMatch(BRANCH_ID); + expect(devBranchId("__@example.com")).toMatch(/^dev-user-[0-9a-f]{6}$/); + }); + + test("a service principal's client ID makes a valid branch ID too", () => { + expect(devBranchId("11111111-2222-3333-4444-555555555555")).toMatch( + BRANCH_ID, + ); + }); + + test("session branches are session-; ids are lowercase base36", () => { + expect(sessionBranchId("k2x9q0ab")).toBe("session-k2x9q0ab"); + expect(isValidSessionId("Bad-Id")).toBe(false); + expect(() => sessionBranchId("Bad-Id")).toThrow(/APPKIT_DB_SESSION/); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts new file mode 100644 index 000000000..ac159a7df --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -0,0 +1,111 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { + parseResourceName, + readDeployBranches, + readLocalTarget, +} from "../targets"; +import { cleanupTempApps, databricksYml, tempApp } from "./fakes"; + +afterEach(cleanupTempApps); + +describe("parseResourceName", () => { + test("splits project, branch, endpoint and database names", () => { + expect( + parseResourceName("projects/p/branches/b/endpoints/primary"), + ).toEqual({ + project: "projects/p", + branch: "projects/p/branches/b", + endpoint: "projects/p/branches/b/endpoints/primary", + }); + expect( + parseResourceName("projects/p/branches/b/databases/databricks-postgres"), + ).toEqual({ + project: "projects/p", + branch: "projects/p/branches/b", + database: "projects/p/branches/b/databases/databricks-postgres", + }); + expect(parseResourceName("projects/p")).toEqual({ project: "projects/p" }); + }); + + test("template placeholders and junk are null", () => { + expect(parseResourceName("your_postgres_endpointPath")).toBeNull(); + expect(parseResourceName("")).toBeNull(); + expect(parseResourceName(undefined)).toBeNull(); + }); +}); + +describe("readLocalTarget", () => { + test("reads the .env endpoint and this checkout's session", () => { + expect( + readLocalTarget({ + LAKEBASE_ENDPOINT: "projects/p/branches/b/endpoints/primary", + PGHOST: "ep.example.com", + APPKIT_DB_SESSION: "k2x9q0ab", + }), + ).toEqual({ + endpoint: "projects/p/branches/b/endpoints/primary", + session: "k2x9q0ab", + }); + }); + + test("placeholders from .env.example read as not configured", () => { + expect( + readLocalTarget({ + LAKEBASE_ENDPOINT: "your_postgres_endpointPath", + APPKIT_DB_SESSION: "NOT VALID", + }), + ).toEqual({ endpoint: null, session: null }); + }); +}); + +describe("readDeployBranches", () => { + test("reads the default target's postgres_branch", () => { + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/databricks-postgres", + ), + }); + expect(readDeployBranches(root)).toEqual([ + "projects/p/branches/production", + ]); + }); + + test("every target's branch counts, and the variable's default", () => { + const root = tempApp({ + "databricks.yml": `variables: + postgres_branch: + default: projects/p/branches/main +targets: + default: + default: true + personal: + variables: + postgres_branch: projects/p/branches/dev-alice-1a2b3c + staging: + variables: + postgres_branch: projects/p/branches/staging +`, + }); + expect(readDeployBranches(root)).toEqual([ + "projects/p/branches/main", + "projects/p/branches/dev-alice-1a2b3c", + "projects/p/branches/staging", + ]); + }); + + test("empty without databricks.yml or without a postgres binding", () => { + expect(readDeployBranches(tempApp())).toEqual([]); + expect( + readDeployBranches(tempApp({ "databricks.yml": "bundle:\n name: x\n" })), + ).toEqual([]); + }); + + test("an invalid databricks.yml throws instead of reading as no binding", () => { + const root = tempApp({ "databricks.yml": "targets:\n default: [\n" }); + expect(() => readDeployBranches(root)).toThrow( + /^Cannot read databricks\.yml, so the branches it deploys to are unknown: .+\(\d+:\d+\)$/, + ); + }); +}); diff --git a/packages/appkit/src/plugins/database/load-schema.ts b/packages/appkit/src/plugins/database/load-schema.ts index 9378dfd6f..fa9f3ef0f 100644 --- a/packages/appkit/src/plugins/database/load-schema.ts +++ b/packages/appkit/src/plugins/database/load-schema.ts @@ -8,9 +8,15 @@ import { assertFinalizedSchema } from "../../database/schema-builder/define-sche /** Same application-relative convention used by appkit generate-types. */ const DEFAULT_SCHEMA_FILE = "config/database/schema.ts"; +interface LoadSchemaOptions { + /** Report why the module failed to import. Only for local CLI runs: see the catch below. */ + readonly showImportError?: boolean; +} + /** Load application-owned declarations during setup, never during registration. */ export async function loadDefaultDatabaseSchema( root = process.cwd(), + options: LoadSchemaOptions = {}, ): Promise { const file = path.resolve(root, DEFAULT_SCHEMA_FILE); const label = JSON.stringify(file); @@ -34,8 +40,14 @@ export async function loadDefaultDatabaseSchema( module = await createJiti(import.meta.url, { moduleCache: false }).import( file, ); - } catch { + } catch (error) { // Import errors can contain credentials, row values, or application internals. + // A CLI run shows them to the developer who wrote the file; the runtime never does. + if (options.showImportError) { + throw new Error(`Could not load ${DEFAULT_SCHEMA_FILE}.`, { + cause: error, + }); + } throw databaseSetupFailed( `Could not load the default schema at ${label}. Check the module and its imports, or pass database({ schema }).`, ); diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index 69a6d575e..1a9067e78 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -78,7 +78,7 @@ export async function assertSchemaMatchesDatabase( const absent = tableNames.filter((name) => !found.has(name)); const advice = (await inPublicInstead(dataPath, schemaName, absent)) ?? - "Create them, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start."; + "Run `npx appkit db migrate` locally, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start."; throw databaseSetupFailed( `the declared schema does not match the database: ${problems.join("; ")}. ${advice}`, ); diff --git a/packages/appkit/tsdown.config.ts b/packages/appkit/tsdown.config.ts index bb17c29ba..d11a7b42d 100644 --- a/packages/appkit/tsdown.config.ts +++ b/packages/appkit/tsdown.config.ts @@ -14,6 +14,7 @@ export default defineConfig([ "src/testing/index.ts", "src/tsdown/index.ts", "src/type-generator/index.ts", + "src/database/tooling/index.ts", ], outDir: "dist", hash: false, diff --git a/packages/shared/src/cli/commands/db/database-tooling.d.ts b/packages/shared/src/cli/commands/db/database-tooling.d.ts new file mode 100644 index 000000000..b1c18beee --- /dev/null +++ b/packages/shared/src/cli/commands/db/database-tooling.d.ts @@ -0,0 +1,39 @@ +/** + * Intentionally narrowed mirror of `@databricks/appkit/database-tooling`. + * + * `shared` is a leaf package and must not statically depend on `appkit`, so the + * CLI loads the tooling via a dynamic `import(...)` and this declares its shape + * without a build-time dependency (same pattern as ../type-generator.d.ts). + * There is NO compile-time link to the real exports — if they change, re-sync + * this by hand against `packages/appkit/src/database/tooling/index.ts`. + */ +declare module "@databricks/appkit/database-tooling" { + export interface DbContext { + readonly root: string; + readonly env: NodeJS.ProcessEnv; + } + + export function createDbContext(options?: { + root?: string; + env?: NodeJS.ProcessEnv; + }): DbContext; + + export interface GeneratedMigration { + readonly tag: string; + readonly file: string; + readonly statements: readonly string[]; + } + + export interface MigrateReport { + readonly generated: GeneratedMigration | null; + readonly applied: readonly string[]; + readonly adopted?: readonly string[]; + readonly notApplied?: string; + readonly typesFile: string; + } + + export function runMigrate( + ctx: DbContext, + options: { interactive: boolean }, + ): Promise; +} diff --git a/packages/shared/src/cli/commands/db/index.ts b/packages/shared/src/cli/commands/db/index.ts new file mode 100644 index 000000000..aca41b888 --- /dev/null +++ b/packages/shared/src/cli/commands/db/index.ts @@ -0,0 +1,11 @@ +import { Command } from "commander"; + +import { dbMigrateCommand } from "./migrate"; + +/** + * Lakebase database lifecycle for the DatabasePlugin. The logic lives in + * `@databricks/appkit/database-tooling`; these commands only parse, prompt and print. + */ +export const dbCommand = new Command("db") + .description("Lakebase database lifecycle") + .addCommand(dbMigrateCommand); diff --git a/packages/shared/src/cli/commands/db/migrate.test.ts b/packages/shared/src/cli/commands/db/migrate.test.ts new file mode 100644 index 000000000..1640b5223 --- /dev/null +++ b/packages/shared/src/cli/commands/db/migrate.test.ts @@ -0,0 +1,152 @@ +import path from "node:path"; + +import { + afterEach, + beforeEach, + describe, + expect, + type MockInstance, + test, + vi, +} from "vitest"; + +const { createDbContext, runMigrate } = vi.hoisted(() => ({ + createDbContext: vi.fn(() => ({ root: "/app", env: {} })), + runMigrate: vi.fn(), +})); + +// The tooling is an ambient module loaded with a dynamic import; mock it so the +// command never touches drizzle-kit or a database. +vi.mock("@databricks/appkit/database-tooling", () => ({ + createDbContext, + runMigrate, +})); + +import { dbCommand } from "./index"; + +let log: MockInstance; +let error: MockInstance; + +function output(spy: MockInstance): string { + return spy.mock.calls.map((call) => call.join(" ")).join("\n"); +} + +beforeEach(() => { + runMigrate.mockReset(); + createDbContext.mockClear(); + log = vi.spyOn(console, "log").mockImplementation(() => undefined); + error = vi.spyOn(console, "error").mockImplementation(() => undefined); +}); + +afterEach(() => { + vi.restoreAllMocks(); + process.exitCode = undefined; +}); + +const typesFile = path.join(process.cwd(), "shared/appkit-types/database.d.ts"); + +describe("appkit db migrate", () => { + test("is registered under the db group", () => { + expect(dbCommand.commands.map((command) => command.name())).toContain( + "migrate", + ); + }); + + test("prints the generated file, the applied tags and the types file", async () => { + runMigrate.mockResolvedValue({ + generated: { + tag: "0001_migration", + file: path.join( + process.cwd(), + "config/database/migrations/0001_migration.sql", + ), + statements: ["a", "b"], + }, + applied: ["0001_migration"], + typesFile, + }); + + await dbCommand.parseAsync(["migrate"], { from: "user" }); + + expect(createDbContext).toHaveBeenCalledWith(); + expect(runMigrate).toHaveBeenCalledWith( + { root: "/app", env: {} }, + // Vitest workers have no TTY, so the run is non-interactive. + { interactive: false }, + ); + const printed = output(log); + expect(printed).toContain( + `Generated ${path.join("config/database/migrations/0001_migration.sql")} (2 statements)`, + ); + expect(printed).toContain("Applied 0001_migration to the .env branch"); + expect(printed).toContain( + `Generated ${path.join("shared/appkit-types/database.d.ts")}`, + ); + expect(process.exitCode).toBeUndefined(); + }); + + test("reports an unchanged schema and an up-to-date branch", async () => { + runMigrate.mockResolvedValue({ generated: null, applied: [], typesFile }); + + await dbCommand.parseAsync(["migrate"], { from: "user" }); + + const printed = output(log); + expect(printed).toContain("No schema changes since the last migration"); + expect(printed).toContain("The .env branch is up to date"); + }); + + test("reports a baseline adopted without running it", async () => { + runMigrate.mockResolvedValue({ + generated: null, + applied: ["0001_migration"], + adopted: ["0000_baseline"], + typesFile, + }); + + await dbCommand.parseAsync(["migrate"], { from: "user" }); + + const printed = output(log); + expect(printed).toContain( + "Adopted 0000_baseline: its tables already existed, so it was recorded without running", + ); + expect(printed).toContain("Applied 0001_migration to the .env branch"); + }); + + test("says why nothing was applied", async () => { + runMigrate.mockResolvedValue({ + generated: null, + applied: [], + notApplied: "no branch configured — run appkit db init", + typesFile, + }); + + await dbCommand.parseAsync(["migrate"], { from: "user" }); + + expect(output(log)).toContain( + "Not applied: no branch configured — run appkit db init", + ); + expect(process.exitCode).toBeUndefined(); + }); + + test("prints the error and its root cause, and exits 1", async () => { + const driverError = new Error('relation "notes" already exists'); + const wrapped = new Error("Failed query: CREATE TABLE ...", { + cause: driverError, + }); + runMigrate.mockRejectedValue( + new Error( + "Applying migration 0000_migration failed (SQLSTATE 42P07); none were applied.", + { cause: wrapped }, + ), + ); + + await dbCommand.parseAsync(["migrate"], { from: "user" }); + + const printed = output(error); + expect(printed).toContain( + "Applying migration 0000_migration failed (SQLSTATE 42P07); none were applied.", + ); + expect(printed).toContain('relation "notes" already exists'); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/packages/shared/src/cli/commands/db/migrate.ts b/packages/shared/src/cli/commands/db/migrate.ts new file mode 100644 index 000000000..8d061f6b0 --- /dev/null +++ b/packages/shared/src/cli/commands/db/migrate.ts @@ -0,0 +1,31 @@ +import { Command } from "commander"; + +import { fail, isInteractive, printMigrateReport } from "./output"; + +async function runDbMigrate(): Promise { + try { + const tooling = await import("@databricks/appkit/database-tooling"); + const report = await tooling.runMigrate(tooling.createDbContext(), { + interactive: isInteractive(), + }); + printMigrateReport(report); + } catch (error) { + fail(error); + } +} + +export const dbMigrateCommand = new Command("migrate") + .description( + "Generate a migration from config/database/schema.ts, apply pending migrations to the .env branch, and regenerate database.d.ts", + ) + .addHelpText( + "after", + ` +Migrations are written to config/database/migrations/. Commit them with schema.ts; +the deployed app applies pending committed migrations when it starts. They are +applied locally only on your dev or session branch (see \`appkit db init\`). + +Examples: + $ appkit db migrate`, + ) + .action(runDbMigrate); diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts new file mode 100644 index 000000000..2cfba1973 --- /dev/null +++ b/packages/shared/src/cli/commands/db/output.ts @@ -0,0 +1,68 @@ +import path from "node:path"; +import process from "node:process"; + +import type { MigrateReport } from "@databricks/appkit/database-tooling"; +import pc from "picocolors"; + +/** Prompts only when a human can answer them. */ +export function isInteractive(): boolean { + return Boolean(process.stdin.isTTY && process.stdout.isTTY); +} + +export function relative(file: string): string { + return path.relative(process.cwd(), file) || file; +} + +export const ok = (message: string) => + console.log(`${pc.green("✔")} ${message}`); +export const info = (message: string) => + console.log(`${pc.dim("•")} ${message}`); +export const warn = (message: string) => + console.log(`${pc.yellow("!")} ${message}`); + +/** Innermost message: drizzle wraps the driver error, whose text names the failing object. */ +function rootCause(error: unknown): string | undefined { + let current = (error as { cause?: unknown } | undefined)?.cause; + let message: string | undefined; + for (let depth = 0; depth < 5 && current instanceof Error; depth++) { + message = current.message; + current = (current as { cause?: unknown }).cause; + } + return message; +} + +/** Print the error and its root cause, and fail the process. */ +export function fail(error: unknown): void { + const message = error instanceof Error ? error.message : String(error); + console.error(`${pc.red("✖")} ${message}`); + const cause = rootCause(error); + if (cause && cause !== message && !message.includes(cause)) + console.error(` ${cause}`); + process.exitCode = 1; +} + +export function printMigrateReport(report: MigrateReport): void { + if (report.generated) { + const count = report.generated.statements.length; + ok( + `Generated ${relative(report.generated.file)} (${count} statement${count === 1 ? "" : "s"})`, + ); + } else { + info("No schema changes since the last migration"); + } + + if (report.adopted?.length) { + ok( + `Adopted ${report.adopted.join(", ")}: its tables already existed, so it was recorded without running`, + ); + } + if (report.applied.length > 0) { + ok(`Applied ${report.applied.join(", ")} to the .env branch`); + } else if (report.notApplied) { + warn(`Not applied: ${report.notApplied}`); + } else if (!report.adopted?.length) { + info("The .env branch is up to date"); + } + + ok(`Generated ${relative(report.typesFile)}`); +} diff --git a/packages/shared/src/cli/index.ts b/packages/shared/src/cli/index.ts index af8c22e6e..2fce08005 100644 --- a/packages/shared/src/cli/index.ts +++ b/packages/shared/src/cli/index.ts @@ -8,6 +8,7 @@ import { Command } from "commander"; import { agentCommand } from "./commands/agent/index.js"; import { codemodCommand } from "./commands/codemod/index.js"; +import { dbCommand } from "./commands/db/index.js"; import { docsCommand } from "./commands/docs.js"; import { doctorCommand } from "./commands/doctor/index.js"; import { generateTypesCommand } from "./commands/generate-types.js"; @@ -35,6 +36,8 @@ cmd.addCommand(docsCommand); cmd.addCommand(pluginCommand); cmd.addCommand(codemodCommand); cmd.addCommand(doctorCommand); +// Hidden from --help until the database plugin is offered by `databricks apps init`. +cmd.addCommand(dbCommand, { hidden: true }); // Registry commands are executable but hidden from --help while the feature // is still in development (registry + add work end-to-end but aren't announced). cmd.addCommand(registryCommand, { hidden: true }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 702d0fa74..b17bf9317 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -137,7 +137,7 @@ importers: version: 19.2.3(@types/react@19.2.7) '@vitejs/plugin-react': specifier: 5.1.1 - version: 5.1.1(vite@7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2)) + version: 5.1.1(vite@7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2)) eslint: specifier: 9.39.1 version: 9.39.1(jiti@2.6.1) @@ -158,7 +158,7 @@ importers: version: 8.49.0(eslint@9.39.1(jiti@2.6.1))(typescript@5.9.3) vite: specifier: 7.2.4 - version: 7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) + version: 7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2) apps/dev-playground: dependencies: @@ -427,7 +427,7 @@ importers: version: link:../shared vite: specifier: npm:rolldown-vite@7.1.14 - version: rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) + version: rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2) ws: specifier: 8.21.0 version: 8.21.0 @@ -458,13 +458,16 @@ importers: version: 8.18.1 '@vitejs/plugin-react': specifier: 5.1.1 - version: 5.1.1(rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2)) + version: 5.1.1(rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2)) autoevals: specifier: 0.3.0 version: 0.3.0(ws@8.21.0)(zod@4.3.6) + drizzle-kit: + specifier: 0.31.10 + version: 0.31.10 vitest: specifier: 3.2.4 - version: 3.2.4(@types/debug@4.1.12)(@types/node@25.2.3)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.6))(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) + version: 3.2.4(@types/debug@4.1.12)(@types/node@25.2.3)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.6))(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2) packages/appkit-ui: dependencies: @@ -2377,6 +2380,9 @@ packages: resolution: {integrity: sha512-lBSBiRruFurFKXr5Hbsl2thmGweAPmddhF3jb99U4EMDA5L+e5Y1rAkOS07Nvrup7HUMBDrCV45meaxZnt28nQ==} engines: {node: '>=20.0'} + '@drizzle-team/brocli@0.10.2': + resolution: {integrity: sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w==} + '@emnapi/core@1.8.1': resolution: {integrity: sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg==} @@ -2386,162 +2392,458 @@ packages: '@emnapi/wasi-threads@1.1.0': resolution: {integrity: sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ==} + '@esbuild-kit/core-utils@3.3.2': + resolution: {integrity: sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ==} + deprecated: 'Merged into tsx: https://tsx.hirok.io' + + '@esbuild-kit/esm-loader@2.6.5': + resolution: {integrity: sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA==} + deprecated: 'Merged into tsx: https://tsx.hirok.io' + '@esbuild/aix-ppc64@0.25.10': resolution: {integrity: sha512-0NFWnA+7l41irNuaSVlLfgNT12caWJVLzp5eAVhZ0z1qpxbockccEt3s+149rE64VUI3Ml2zt8Nv5JVc4QXTsw==} engines: {node: '>=18'} cpu: [ppc64] os: [aix] + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.18.20': + resolution: {integrity: sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + '@esbuild/android-arm64@0.25.10': resolution: {integrity: sha512-LSQa7eDahypv/VO6WKohZGPSJDq5OVOo3UoFR1E4t4Gj1W7zEQMUhI+lo81H+DtB+kP+tDgBp+M4oNCwp6kffg==} engines: {node: '>=18'} cpu: [arm64] os: [android] + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.18.20': + resolution: {integrity: sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + '@esbuild/android-arm@0.25.10': resolution: {integrity: sha512-dQAxF1dW1C3zpeCDc5KqIYuZ1tgAdRXNoZP7vkBIRtKZPYe2xVr/d3SkirklCHudW1B45tGiUlz2pUWDfbDD4w==} engines: {node: '>=18'} cpu: [arm] os: [android] + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.18.20': + resolution: {integrity: sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + '@esbuild/android-x64@0.25.10': resolution: {integrity: sha512-MiC9CWdPrfhibcXwr39p9ha1x0lZJ9KaVfvzA0Wxwz9ETX4v5CHfF09bx935nHlhi+MxhA63dKRRQLiVgSUtEg==} engines: {node: '>=18'} cpu: [x64] os: [android] + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.18.20': + resolution: {integrity: sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + '@esbuild/darwin-arm64@0.25.10': resolution: {integrity: sha512-JC74bdXcQEpW9KkV326WpZZjLguSZ3DfS8wrrvPMHgQOIEIG/sPXEN/V8IssoJhbefLRcRqw6RQH2NnpdprtMA==} engines: {node: '>=18'} cpu: [arm64] os: [darwin] + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.18.20': + resolution: {integrity: sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + '@esbuild/darwin-x64@0.25.10': resolution: {integrity: sha512-tguWg1olF6DGqzws97pKZ8G2L7Ig1vjDmGTwcTuYHbuU6TTjJe5FXbgs5C1BBzHbJ2bo1m3WkQDbWO2PvamRcg==} engines: {node: '>=18'} cpu: [x64] os: [darwin] + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.18.20': + resolution: {integrity: sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + '@esbuild/freebsd-arm64@0.25.10': resolution: {integrity: sha512-3ZioSQSg1HT2N05YxeJWYR+Libe3bREVSdWhEEgExWaDtyFbbXWb49QgPvFH8u03vUPX10JhJPcz7s9t9+boWg==} engines: {node: '>=18'} cpu: [arm64] os: [freebsd] + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.18.20': + resolution: {integrity: sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + '@esbuild/freebsd-x64@0.25.10': resolution: {integrity: sha512-LLgJfHJk014Aa4anGDbh8bmI5Lk+QidDmGzuC2D+vP7mv/GeSN+H39zOf7pN5N8p059FcOfs2bVlrRr4SK9WxA==} engines: {node: '>=18'} cpu: [x64] os: [freebsd] + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.18.20': + resolution: {integrity: sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + '@esbuild/linux-arm64@0.25.10': resolution: {integrity: sha512-5luJWN6YKBsawd5f9i4+c+geYiVEw20FVW5x0v1kEMWNq8UctFjDiMATBxLvmmHA4bf7F6hTRaJgtghFr9iziQ==} engines: {node: '>=18'} cpu: [arm64] os: [linux] + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.18.20': + resolution: {integrity: sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + '@esbuild/linux-arm@0.25.10': resolution: {integrity: sha512-oR31GtBTFYCqEBALI9r6WxoU/ZofZl962pouZRTEYECvNF/dtXKku8YXcJkhgK/beU+zedXfIzHijSRapJY3vg==} engines: {node: '>=18'} cpu: [arm] os: [linux] + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.18.20': + resolution: {integrity: sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + '@esbuild/linux-ia32@0.25.10': resolution: {integrity: sha512-NrSCx2Kim3EnnWgS4Txn0QGt0Xipoumb6z6sUtl5bOEZIVKhzfyp/Lyw4C1DIYvzeW/5mWYPBFJU3a/8Yr75DQ==} engines: {node: '>=18'} cpu: [ia32] os: [linux] + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.18.20': + resolution: {integrity: sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + '@esbuild/linux-loong64@0.25.10': resolution: {integrity: sha512-xoSphrd4AZda8+rUDDfD9J6FUMjrkTz8itpTITM4/xgerAZZcFW7Dv+sun7333IfKxGG8gAq+3NbfEMJfiY+Eg==} engines: {node: '>=18'} cpu: [loong64] os: [linux] + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.18.20': + resolution: {integrity: sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + '@esbuild/linux-mips64el@0.25.10': resolution: {integrity: sha512-ab6eiuCwoMmYDyTnyptoKkVS3k8fy/1Uvq7Dj5czXI6DF2GqD2ToInBI0SHOp5/X1BdZ26RKc5+qjQNGRBelRA==} engines: {node: '>=18'} cpu: [mips64el] os: [linux] + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.18.20': + resolution: {integrity: sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + '@esbuild/linux-ppc64@0.25.10': resolution: {integrity: sha512-NLinzzOgZQsGpsTkEbdJTCanwA5/wozN9dSgEl12haXJBzMTpssebuXR42bthOF3z7zXFWH1AmvWunUCkBE4EA==} engines: {node: '>=18'} cpu: [ppc64] os: [linux] + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.18.20': + resolution: {integrity: sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + '@esbuild/linux-riscv64@0.25.10': resolution: {integrity: sha512-FE557XdZDrtX8NMIeA8LBJX3dC2M8VGXwfrQWU7LB5SLOajfJIxmSdyL/gU1m64Zs9CBKvm4UAuBp5aJ8OgnrA==} engines: {node: '>=18'} cpu: [riscv64] os: [linux] + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.18.20': + resolution: {integrity: sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + '@esbuild/linux-s390x@0.25.10': resolution: {integrity: sha512-3BBSbgzuB9ajLoVZk0mGu+EHlBwkusRmeNYdqmznmMc9zGASFjSsxgkNsqmXugpPk00gJ0JNKh/97nxmjctdew==} engines: {node: '>=18'} cpu: [s390x] os: [linux] + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.18.20': + resolution: {integrity: sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + '@esbuild/linux-x64@0.25.10': resolution: {integrity: sha512-QSX81KhFoZGwenVyPoberggdW1nrQZSvfVDAIUXr3WqLRZGZqWk/P4T8p2SP+de2Sr5HPcvjhcJzEiulKgnxtA==} engines: {node: '>=18'} cpu: [x64] os: [linux] + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + '@esbuild/netbsd-arm64@0.25.10': resolution: {integrity: sha512-AKQM3gfYfSW8XRk8DdMCzaLUFB15dTrZfnX8WXQoOUpUBQ+NaAFCP1kPS/ykbbGYz7rxn0WS48/81l9hFl3u4A==} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.18.20': + resolution: {integrity: sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + '@esbuild/netbsd-x64@0.25.10': resolution: {integrity: sha512-7RTytDPGU6fek/hWuN9qQpeGPBZFfB4zZgcz2VK2Z5VpdUxEI8JKYsg3JfO0n/Z1E/6l05n0unDCNc4HnhQGig==} engines: {node: '>=18'} cpu: [x64] os: [netbsd] + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + '@esbuild/openbsd-arm64@0.25.10': resolution: {integrity: sha512-5Se0VM9Wtq797YFn+dLimf2Zx6McttsH2olUBsDml+lm0GOCRVebRWUvDtkY4BWYv/3NgzS8b/UM3jQNh5hYyw==} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.18.20': + resolution: {integrity: sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + '@esbuild/openbsd-x64@0.25.10': resolution: {integrity: sha512-XkA4frq1TLj4bEMB+2HnI0+4RnjbuGZfet2gs/LNs5Hc7D89ZQBHQ0gL2ND6Lzu1+QVkjp3x1gIcPKzRNP8bXw==} engines: {node: '>=18'} cpu: [x64] os: [openbsd] + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + '@esbuild/openharmony-arm64@0.25.10': resolution: {integrity: sha512-AVTSBhTX8Y/Fz6OmIVBip9tJzZEUcY8WLh7I59+upa5/GPhh2/aM6bvOMQySspnCCHvFi79kMtdJS1w0DXAeag==} engines: {node: '>=18'} cpu: [arm64] os: [openharmony] + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.18.20': + resolution: {integrity: sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + '@esbuild/sunos-x64@0.25.10': resolution: {integrity: sha512-fswk3XT0Uf2pGJmOpDB7yknqhVkJQkAQOcW/ccVOtfx05LkbWOaRAtn5SaqXypeKQra1QaEa841PgrSL9ubSPQ==} engines: {node: '>=18'} cpu: [x64] os: [sunos] + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.18.20': + resolution: {integrity: sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + '@esbuild/win32-arm64@0.25.10': resolution: {integrity: sha512-ah+9b59KDTSfpaCg6VdJoOQvKjI33nTaQr4UluQwW7aEwZQsbMCfTmfEO4VyewOxx4RaDT/xCy9ra2GPWmO7Kw==} engines: {node: '>=18'} cpu: [arm64] os: [win32] + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.18.20': + resolution: {integrity: sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + '@esbuild/win32-ia32@0.25.10': resolution: {integrity: sha512-QHPDbKkrGO8/cz9LKVnJU22HOi4pxZnZhhA2HYHez5Pz4JeffhDjf85E57Oyco163GnzNCVkZK0b/n4Y0UHcSw==} engines: {node: '>=18'} cpu: [ia32] os: [win32] + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.18.20': + resolution: {integrity: sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + '@esbuild/win32-x64@0.25.10': resolution: {integrity: sha512-9KpxSVFCu0iK1owoez6aC/s/EdUQLDN3adTxGCqxMVhrPDj6bt5dbrHDXUuq+Bs2vATFBBrQS5vdQ/Ed2P+nbw==} engines: {node: '>=18'} cpu: [x64] os: [win32] + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + '@eslint-community/eslint-utils@4.9.0': resolution: {integrity: sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -7366,6 +7668,10 @@ packages: resolution: {integrity: sha512-iGCHkfUc5kFekGiqhe8B/mdaurD+lakO9txNnTvKtA6PISrw86LgqHvRzWYPyoE2Ph5aMIrCw9/uko6XHTKCwA==} deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. + drizzle-kit@0.31.10: + resolution: {integrity: sha512-7OZcmQUrdGI+DUNNsKBn1aW8qSoKuTH7d0mYgSP8bAzdFzKoovxEFnoGQp2dVs82EOJeYycqRtciopszwUf8bw==} + hasBin: true + drizzle-orm@0.45.2: resolution: {integrity: sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q==} peerDependencies: @@ -7607,11 +7913,21 @@ packages: esast-util-from-js@2.0.1: resolution: {integrity: sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw==} + esbuild@0.18.20: + resolution: {integrity: sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA==} + engines: {node: '>=12'} + hasBin: true + esbuild@0.25.10: resolution: {integrity: sha512-9RiGKvCwaqxO2owP61uQ4BgNborAQskMR6QusfWzQqv7AZOg5oGehdY2pRJMTKuwxd1IDBP4rSbI5lHzU7SMsQ==} engines: {node: '>=18'} hasBin: true + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + escalade@3.2.0: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} @@ -11931,6 +12247,11 @@ packages: engines: {node: '>=18.0.0'} hasBin: true + tsx@4.23.15: + resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==} + engines: {node: '>=18.0.0'} + hasBin: true + tunnel-agent@0.6.0: resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} @@ -15402,6 +15723,8 @@ snapshots: - uglify-js - webpack-cli + '@drizzle-team/brocli@0.10.2': {} + '@emnapi/core@1.8.1': dependencies: '@emnapi/wasi-threads': 1.1.0 @@ -15418,84 +15741,238 @@ snapshots: tslib: 2.8.1 optional: true + '@esbuild-kit/core-utils@3.3.2': + dependencies: + esbuild: 0.18.20 + source-map-support: 0.5.21 + + '@esbuild-kit/esm-loader@2.6.5': + dependencies: + '@esbuild-kit/core-utils': 3.3.2 + get-tsconfig: 4.13.6 + '@esbuild/aix-ppc64@0.25.10': optional: true + '@esbuild/aix-ppc64@0.28.2': + optional: true + + '@esbuild/android-arm64@0.18.20': + optional: true + '@esbuild/android-arm64@0.25.10': optional: true + '@esbuild/android-arm64@0.28.2': + optional: true + + '@esbuild/android-arm@0.18.20': + optional: true + '@esbuild/android-arm@0.25.10': optional: true + '@esbuild/android-arm@0.28.2': + optional: true + + '@esbuild/android-x64@0.18.20': + optional: true + '@esbuild/android-x64@0.25.10': optional: true + '@esbuild/android-x64@0.28.2': + optional: true + + '@esbuild/darwin-arm64@0.18.20': + optional: true + '@esbuild/darwin-arm64@0.25.10': optional: true + '@esbuild/darwin-arm64@0.28.2': + optional: true + + '@esbuild/darwin-x64@0.18.20': + optional: true + '@esbuild/darwin-x64@0.25.10': optional: true + '@esbuild/darwin-x64@0.28.2': + optional: true + + '@esbuild/freebsd-arm64@0.18.20': + optional: true + '@esbuild/freebsd-arm64@0.25.10': optional: true + '@esbuild/freebsd-arm64@0.28.2': + optional: true + + '@esbuild/freebsd-x64@0.18.20': + optional: true + '@esbuild/freebsd-x64@0.25.10': optional: true + '@esbuild/freebsd-x64@0.28.2': + optional: true + + '@esbuild/linux-arm64@0.18.20': + optional: true + '@esbuild/linux-arm64@0.25.10': optional: true + '@esbuild/linux-arm64@0.28.2': + optional: true + + '@esbuild/linux-arm@0.18.20': + optional: true + '@esbuild/linux-arm@0.25.10': optional: true + '@esbuild/linux-arm@0.28.2': + optional: true + + '@esbuild/linux-ia32@0.18.20': + optional: true + '@esbuild/linux-ia32@0.25.10': optional: true + '@esbuild/linux-ia32@0.28.2': + optional: true + + '@esbuild/linux-loong64@0.18.20': + optional: true + '@esbuild/linux-loong64@0.25.10': optional: true + '@esbuild/linux-loong64@0.28.2': + optional: true + + '@esbuild/linux-mips64el@0.18.20': + optional: true + '@esbuild/linux-mips64el@0.25.10': optional: true + '@esbuild/linux-mips64el@0.28.2': + optional: true + + '@esbuild/linux-ppc64@0.18.20': + optional: true + '@esbuild/linux-ppc64@0.25.10': optional: true + '@esbuild/linux-ppc64@0.28.2': + optional: true + + '@esbuild/linux-riscv64@0.18.20': + optional: true + '@esbuild/linux-riscv64@0.25.10': optional: true + '@esbuild/linux-riscv64@0.28.2': + optional: true + + '@esbuild/linux-s390x@0.18.20': + optional: true + '@esbuild/linux-s390x@0.25.10': optional: true + '@esbuild/linux-s390x@0.28.2': + optional: true + + '@esbuild/linux-x64@0.18.20': + optional: true + '@esbuild/linux-x64@0.25.10': optional: true + '@esbuild/linux-x64@0.28.2': + optional: true + '@esbuild/netbsd-arm64@0.25.10': optional: true + '@esbuild/netbsd-arm64@0.28.2': + optional: true + + '@esbuild/netbsd-x64@0.18.20': + optional: true + '@esbuild/netbsd-x64@0.25.10': optional: true + '@esbuild/netbsd-x64@0.28.2': + optional: true + '@esbuild/openbsd-arm64@0.25.10': optional: true + '@esbuild/openbsd-arm64@0.28.2': + optional: true + + '@esbuild/openbsd-x64@0.18.20': + optional: true + '@esbuild/openbsd-x64@0.25.10': optional: true + '@esbuild/openbsd-x64@0.28.2': + optional: true + '@esbuild/openharmony-arm64@0.25.10': optional: true + '@esbuild/openharmony-arm64@0.28.2': + optional: true + + '@esbuild/sunos-x64@0.18.20': + optional: true + '@esbuild/sunos-x64@0.25.10': optional: true + '@esbuild/sunos-x64@0.28.2': + optional: true + + '@esbuild/win32-arm64@0.18.20': + optional: true + '@esbuild/win32-arm64@0.25.10': optional: true + '@esbuild/win32-arm64@0.28.2': + optional: true + + '@esbuild/win32-ia32@0.18.20': + optional: true + '@esbuild/win32-ia32@0.25.10': optional: true + '@esbuild/win32-ia32@0.28.2': + optional: true + + '@esbuild/win32-x64@0.18.20': + optional: true + '@esbuild/win32-x64@0.25.10': optional: true + '@esbuild/win32-x64@0.28.2': + optional: true + '@eslint-community/eslint-utils@4.9.0(eslint@9.39.1(jiti@2.6.1))': dependencies: eslint: 9.39.1(jiti@2.6.1) @@ -18950,7 +19427,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@vitejs/plugin-react@5.1.1(rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2))': + '@vitejs/plugin-react@5.1.1(rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2))': dependencies: '@babel/core': 7.28.5 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.5) @@ -18958,11 +19435,11 @@ snapshots: '@rolldown/pluginutils': 1.0.0-beta.47 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 - vite: rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) + vite: rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2) transitivePeerDependencies: - supports-color - '@vitejs/plugin-react@5.1.1(vite@7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2))': + '@vitejs/plugin-react@5.1.1(vite@7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2))': dependencies: '@babel/core': 7.28.5 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.5) @@ -18970,7 +19447,7 @@ snapshots: '@rolldown/pluginutils': 1.0.0-beta.47 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 - vite: 7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) + vite: 7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2) transitivePeerDependencies: - supports-color @@ -19006,13 +19483,13 @@ snapshots: optionalDependencies: vite: 7.2.4(@types/node@24.7.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) - '@vitest/mocker@3.2.4(vite@7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2))': + '@vitest/mocker@3.2.4(vite@7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2))': dependencies: '@vitest/spy': 3.2.4 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) + vite: 7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2) '@vitest/pretty-format@3.2.4': dependencies: @@ -20722,6 +21199,13 @@ snapshots: dottie@2.0.6: {} + drizzle-kit@0.31.10: + dependencies: + '@drizzle-team/brocli': 0.10.2 + '@esbuild-kit/esm-loader': 2.6.5 + esbuild: 0.25.10 + tsx: 4.23.15 + drizzle-orm@0.45.2(@opentelemetry/api@1.9.0)(@types/pg@8.16.0)(pg@8.18.0): optionalDependencies: '@opentelemetry/api': 1.9.0 @@ -20859,6 +21343,31 @@ snapshots: esast-util-from-estree: 2.0.0 vfile-message: 4.0.3 + esbuild@0.18.20: + optionalDependencies: + '@esbuild/android-arm': 0.18.20 + '@esbuild/android-arm64': 0.18.20 + '@esbuild/android-x64': 0.18.20 + '@esbuild/darwin-arm64': 0.18.20 + '@esbuild/darwin-x64': 0.18.20 + '@esbuild/freebsd-arm64': 0.18.20 + '@esbuild/freebsd-x64': 0.18.20 + '@esbuild/linux-arm': 0.18.20 + '@esbuild/linux-arm64': 0.18.20 + '@esbuild/linux-ia32': 0.18.20 + '@esbuild/linux-loong64': 0.18.20 + '@esbuild/linux-mips64el': 0.18.20 + '@esbuild/linux-ppc64': 0.18.20 + '@esbuild/linux-riscv64': 0.18.20 + '@esbuild/linux-s390x': 0.18.20 + '@esbuild/linux-x64': 0.18.20 + '@esbuild/netbsd-x64': 0.18.20 + '@esbuild/openbsd-x64': 0.18.20 + '@esbuild/sunos-x64': 0.18.20 + '@esbuild/win32-arm64': 0.18.20 + '@esbuild/win32-ia32': 0.18.20 + '@esbuild/win32-x64': 0.18.20 + esbuild@0.25.10: optionalDependencies: '@esbuild/aix-ppc64': 0.25.10 @@ -20888,6 +21397,35 @@ snapshots: '@esbuild/win32-ia32': 0.25.10 '@esbuild/win32-x64': 0.25.10 + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + escalade@3.2.0: {} escape-goat@4.0.0: {} @@ -25160,7 +25698,7 @@ snapshots: tsx: 4.20.6 yaml: 2.8.2 - rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2): + rolldown-vite@7.1.14(@types/node@25.2.3)(esbuild@0.25.10)(jiti@2.6.1)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2): dependencies: '@oxc-project/runtime': 0.92.0 fdir: 6.5.0(picomatch@4.0.3) @@ -25175,7 +25713,7 @@ snapshots: fsevents: 2.3.3 jiti: 2.6.1 terser: 5.44.1 - tsx: 4.20.6 + tsx: 4.23.15 yaml: 2.8.2 rolldown@1.0.0-beta.41: @@ -26062,6 +26600,12 @@ snapshots: optionalDependencies: fsevents: 2.3.3 + tsx@4.23.15: + dependencies: + esbuild: 0.28.2 + optionalDependencies: + fsevents: 2.3.3 + tunnel-agent@0.6.0: dependencies: safe-buffer: 5.2.1 @@ -26472,13 +27016,13 @@ snapshots: - tsx - yaml - vite-node@3.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2): + vite-node@3.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2): dependencies: cac: 6.7.14 debug: 4.4.3 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) + vite: 7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2) transitivePeerDependencies: - '@types/node' - jiti @@ -26504,7 +27048,7 @@ snapshots: - supports-color - typescript - vite@7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2): + vite@7.2.4(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2): dependencies: esbuild: 0.25.10 fdir: 6.5.0(picomatch@4.0.3) @@ -26518,7 +27062,7 @@ snapshots: jiti: 2.6.1 lightningcss: 1.30.2 terser: 5.44.1 - tsx: 4.20.6 + tsx: 4.23.15 yaml: 2.8.2 vite@7.2.4(@types/node@24.7.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2): @@ -26538,7 +27082,7 @@ snapshots: tsx: 4.20.6 yaml: 2.8.2 - vite@7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2): + vite@7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2): dependencies: esbuild: 0.25.10 fdir: 6.5.0(picomatch@4.0.3) @@ -26552,7 +27096,7 @@ snapshots: jiti: 2.6.1 lightningcss: 1.30.2 terser: 5.44.1 - tsx: 4.20.6 + tsx: 4.23.15 yaml: 2.8.2 vitest@3.2.4(@types/debug@4.1.12)(@types/node@24.7.2)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.6))(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2): @@ -26598,11 +27142,11 @@ snapshots: - tsx - yaml - vitest@3.2.4(@types/debug@4.1.12)(@types/node@25.2.3)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.6))(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2): + vitest@3.2.4(@types/debug@4.1.12)(@types/node@25.2.3)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.6))(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 - '@vitest/mocker': 3.2.4(vite@7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2)) + '@vitest/mocker': 3.2.4(vite@7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2)) '@vitest/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -26620,8 +27164,8 @@ snapshots: tinyglobby: 0.2.15 tinypool: 1.1.1 tinyrainbow: 2.0.0 - vite: 7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) - vite-node: 3.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.8.2) + vite: 7.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2) + vite-node: 3.2.4(@types/node@25.2.3)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.23.15)(yaml@2.8.2) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.12 From 9ad03888dc989e55d4664563b4f4a35f63373097 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 19 Oct 2026 14:44:21 +0200 Subject: [PATCH 006/317] fix(appkit): let appkit db migrate recover from a failed migration A generated migration that fails to apply is removed and the journal restored, so a fix in schema.ts replaces it instead of stacking behind it. Also: refuse a drizzle-kit other than the pinned one or one loading another drizzle-orm, parse the branch and endpoint responses the guard decides on, type the CLI against a contract appkit's typecheck enforces, and enforce the drizzle-kit and tooling import boundary with oxlint. Signed-off-by: ditadi --- .oxlintrc.json | 50 +++++++ .../appkit/src/database/tooling/context.ts | 18 ++- packages/appkit/src/database/tooling/guard.ts | 6 +- packages/appkit/src/database/tooling/index.ts | 3 + .../src/database/tooling/lakebase-api.ts | 43 +++++- .../appkit/src/database/tooling/migrate.ts | 59 ++++++--- .../appkit/src/database/tooling/migrations.ts | 108 +++++++++++++++- .../database/tooling/tests/context.test.ts | 36 +++++- .../database/tooling/tests/contract.test.ts | 20 +++ .../tests/drizzle-kit-dependency.test.ts | 122 ++++++++++++------ .../tooling/tests/lakebase-api.test.ts | 47 ++++++- .../database/tooling/tests/migrate.pg.test.ts | 115 +++++++++++++++++ .../database/tooling/tests/migrate.test.ts | 87 ++++++++++++- .../database/tooling/tests/migrations.test.ts | 40 ++++++ .../src/plugins/database/load-schema.ts | 2 +- .../src/type-generator/database/generate.ts | 8 ++ .../src/type-generator/database/index.ts | 1 + .../src/cli/commands/db/database-tooling.d.ts | 43 +----- .../src/cli/commands/db/load-tooling.ts | 6 + .../shared/src/cli/commands/db/migrate.ts | 3 +- packages/shared/src/cli/commands/db/output.ts | 3 +- .../src/cli/commands/db/tooling-contract.ts | 37 ++++++ 22 files changed, 733 insertions(+), 124 deletions(-) create mode 100644 packages/appkit/src/database/tooling/tests/contract.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/migrate.pg.test.ts create mode 100644 packages/shared/src/cli/commands/db/load-tooling.ts create mode 100644 packages/shared/src/cli/commands/db/tooling-contract.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index a457847df..dce5b9c8e 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -58,6 +58,56 @@ "rules": { "no-restricted-imports": "off" } + }, + { + "files": ["packages/appkit/src/**"], + "rules": { + "no-restricted-imports": [ + "error", + { + "patterns": [ + { + "group": [ + "@databricks/sdk-experimental", + "@databricks/sdk-experimental/**" + ], + "message": "Import the Databricks SDK only through the wrapper in packages/shared/src/workspace-client. 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/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-experimental", + "@databricks/sdk-experimental/**" + ], + "message": "Import the Databricks SDK only through the wrapper in packages/shared/src/workspace-client. Add a re-export there if you need a new symbol." + } + ] + } + ] + } } ], "ignorePatterns": [ diff --git a/packages/appkit/src/database/tooling/context.ts b/packages/appkit/src/database/tooling/context.ts index c8850dea0..580ee303d 100644 --- a/packages/appkit/src/database/tooling/context.ts +++ b/packages/appkit/src/database/tooling/context.ts @@ -1,10 +1,11 @@ import type { LakebasePoolConfig } from "@databricks/lakebase"; import type { Pool } from "pg"; -import { initializeLakebasePool } from "../../connectors/lakebase"; +import { createLakebasePool } from "../../connectors/lakebase"; import { endpointHosts } from "../../connectors/lakebase/endpoint-host"; import { getClientOptions } from "../../context/client-options"; import { createWorkspaceClient } from "../../workspace-client"; +import { currentIdentity } from "./identity"; import { LakebaseApi, type LakebaseEndpoint } from "./lakebase-api"; /** One REST call through the SDK's unified-auth client. */ @@ -97,18 +98,25 @@ async function assertHostServesEndpoint( } } -/** null when PGHOST / PGDATABASE / LAKEBASE_ENDPOINT are not configured. */ +/** + * null when PGHOST / PGDATABASE / LAKEBASE_ENDPOINT are not configured. The + * pool is created directly: initializeLakebasePool would look the endpoint and + * the user up a second time. + */ export async function openBranchPool(ctx: DbContext): Promise { const { PGHOST, PGDATABASE, LAKEBASE_ENDPOINT } = ctx.env; if (!PGHOST || !PGDATABASE || !LAKEBASE_ENDPOINT) return null; - await assertHostServesEndpoint(ctx, LAKEBASE_ENDPOINT, PGHOST); + 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; const sslMode = ctx.env.PGSSLMODE as LakebasePoolConfig["sslMode"]; - return initializeLakebasePool({ + return createLakebasePool({ host: PGHOST, database: PGDATABASE, endpoint: LAKEBASE_ENDPOINT, - user: ctx.env.PGUSER || undefined, + user, ...(port ? { port } : {}), ...(sslMode ? { sslMode } : {}), // Only apiClient.request and currentUser.me are used (see ToolingWorkspaceClient). diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts index f135e8258..001afd60b 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -65,13 +65,15 @@ export async function checkAppkitBranch( const local = readLocalTarget(ctx.env); const name = parseResourceName(local.endpoint ?? undefined)?.branch; if (!name) return null; - const branch = await ctx.api().getBranch(name); + const [branch, { userName }] = await Promise.all([ + ctx.api().getBranch(name), + currentIdentity(ctx), + ]); if (!branch) { throw new Error( `The .env branch ${name} does not exist (deleted or expired). Run \`appkit db init\` to create or pick one.`, ); } - const { userName } = await currentIdentity(ctx); return { branch, verdict: classifyBranch({ diff --git a/packages/appkit/src/database/tooling/index.ts b/packages/appkit/src/database/tooling/index.ts index 7167ac662..bbec5337a 100644 --- a/packages/appkit/src/database/tooling/index.ts +++ b/packages/appkit/src/database/tooling/index.ts @@ -2,6 +2,9 @@ * `@databricks/appkit/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. + * + * Internal to the AppKit CLI: it has no semver guarantee, and only the CLI of + * the same AppKit release should import it. */ export { createDbContext, type DbContext } from "./context"; export { type MigrateOptions, type MigrateReport, runMigrate } from "./migrate"; diff --git a/packages/appkit/src/database/tooling/lakebase-api.ts b/packages/appkit/src/database/tooling/lakebase-api.ts index 1bde6df9d..a460846a1 100644 --- a/packages/appkit/src/database/tooling/lakebase-api.ts +++ b/packages/appkit/src/database/tooling/lakebase-api.ts @@ -1,3 +1,5 @@ +import { z } from "zod"; + import type { ToolingRequest, ToolingWorkspaceClient } from "./context"; // Lakebase Postgres REST API through the SDK's unified-auth client. Paths, @@ -41,6 +43,28 @@ export class LakebaseApiError extends Error { const API = "/api/2.0/postgres"; +// The guard decides from these fields whether a command may write to a branch. +// A response without them must fail, not read as "not default, not protected". +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; @@ -56,11 +80,26 @@ export class LakebaseApi { ) {} getBranch(name: string): Promise { - return this.getOrNull(`get branch ${name}`, name); + return this.getParsedOrNull(`get branch ${name}`, name, branchResponse); } getEndpoint(name: string): Promise { - return this.getOrNull(`get endpoint ${name}`, name); + 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})`); } private async call( diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index d0be9ec6d..0182d49ce 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -1,33 +1,50 @@ import fs from "node:fs"; import path from "node:path"; -import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +import { + DEFAULT_SCHEMA_FILE, + loadDefaultDatabaseSchema, +} from "../../plugins/database/load-schema"; import { DATABASE_TYPES_FILE, - generateDatabaseTypes, + writeDatabaseTypes, } from "../../type-generator/database"; -import { applyPendingMigrations } from "../migrations/apply"; -import { migrationsFolder, readJournal } from "../migrations/paths"; +import { + applyPendingMigrations, + MigrationApplyError, +} from "../migrations/apply"; +import { + journalFile, + migrationsFolder, + readJournal, +} from "../migrations/paths"; import { type DbContext, openBranchPool } from "./context"; import { checkAppkitBranch } from "./guard"; -import { type GeneratedMigration, generateMigrationFiles } from "./migrations"; +import { + discardMigrationFiles, + type GeneratedMigration, + generateMigrationFiles, +} from "./migrations"; import { resourceId } from "./targets"; -/** Same application-relative conventions as the plugin and `appkit generate-types`. */ -const SCHEMA_FILE = "config/database/schema.ts"; - /** Whether the checkout has a config/database/schema.ts yet. */ function hasSchemaFile(root: string): boolean { - return fs.existsSync(path.join(root, SCHEMA_FILE)); + return fs.existsSync(path.join(root, DEFAULT_SCHEMA_FILE)); } /** Without schema.ts, point to introspect instead of a load error. */ function requireSchemaFile(root: string): void { if (hasSchemaFile(root)) return; throw new Error( - `No ${SCHEMA_FILE} yet, so there is nothing to migrate. Run \`appkit db introspect\` to write it from the branch's tables, or create it.`, + `No ${DEFAULT_SCHEMA_FILE} yet, so there is nothing to migrate. Run \`appkit db introspect\` to write it from the branch's tables, or create it.`, ); } + +/** The journal's text before this run writes to it; null when there is none. */ +function readJournalText(folder: string): string | null { + const file = journalFile(folder); + return fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : null; +} const DATABASE_TYPES_PATH = path.join( "shared/appkit-types", DATABASE_TYPES_FILE, @@ -100,6 +117,7 @@ export async function runMigrate( showImportError: true, }); const folder = migrationsFolder(ctx.root); + const journalBefore = readJournalText(folder); const generated = await generateMigrationFiles({ folder, schema, @@ -108,18 +126,29 @@ export async function runMigrate( // The types follow schema.ts alone, so they are current even if applying fails. const typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); - await generateDatabaseTypes({ - schemaFile: path.join(ctx.root, SCHEMA_FILE), - outFile: typesFile, - }); + await writeDatabaseTypes(schema, typesFile); let outcome: ApplyOutcome; try { outcome = await applyToEnvBranch(ctx, folder, schema.$schemaName); } catch (error) { if (!generated) throw error; + const file = path.relative(ctx.root, generated.file); + // A failed migration left in the journal runs first on every later try, so a + // fix in schema.ts would stack behind it and never apply. + if ( + error instanceof MigrationApplyError && + error.failed === generated.tag && + error.code + ) { + discardMigrationFiles(folder, generated, journalBefore); + throw new Error( + `${error.message} Removed ${file}, so the next run writes it again from ${DEFAULT_SCHEMA_FILE}. Change ${DEFAULT_SCHEMA_FILE} or the branch's data, then rerun \`appkit db migrate\`.`, + { cause: error }, + ); + } throw new Error( - `Wrote ${path.relative(ctx.root, generated.file)}, but did not apply it: ${error instanceof Error ? error.message : String(error)}`, + `Wrote ${file}, but did not apply it: ${error instanceof Error ? error.message : String(error)}`, { cause: error }, ); } diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 135d4401d..021ca2595 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -1,4 +1,6 @@ +import { randomUUID } from "node:crypto"; import fs from "node:fs"; +import { createRequire } from "node:module"; import path from "node:path"; import { @@ -164,13 +166,19 @@ function findRenameAmbiguity( return null; } -/** Whether drizzle-kit itself is not installed; module loaders may wrap that error. */ +/** + * Whether drizzle-kit itself is not installed, or is a release without the + * `./api` export; module loaders may wrap that error. + */ function isDrizzleKitMissing(error: unknown): boolean { let current = error; for (let depth = 0; depth < 3 && current instanceof Error; depth++) { + const code = (current as { code?: unknown }).code; if ( - (current as { code?: unknown }).code === "ERR_MODULE_NOT_FOUND" && - /['"]drizzle-kit['"]/.test(current.message) + (code === "ERR_MODULE_NOT_FOUND" && + /['"]drizzle-kit['"]/.test(current.message)) || + (code === "ERR_PACKAGE_PATH_NOT_EXPORTED" && + current.message.includes("drizzle-kit")) ) { return true; } @@ -179,11 +187,65 @@ function isDrizzleKitMissing(error: unknown): boolean { return false; } +interface InstalledPackage { + readonly version: string; + /** The resolved entry file, to resolve that package's own imports from. */ + readonly entry: string; +} + +/** The package `name` resolves to from `from`; null when it does not resolve. */ +function installedPackage(name: string, from: string): InstalledPackage | null { + let entry: string; + try { + entry = createRequire(from).resolve(name); + } catch { + return null; + } + // Neither drizzle-kit nor drizzle-orm exports ./package.json. + for ( + let dir = path.dirname(entry); + dir !== path.dirname(dir); + dir = path.dirname(dir) + ) { + const file = path.join(dir, "package.json"); + if (!fs.existsSync(file)) continue; + const pkg = readJsonFile<{ name?: unknown; version?: unknown }>(file); + if (pkg.name === name && typeof pkg.version === "string") { + return { version: pkg.version, entry }; + } + } + return null; +} + +/** + * Why the drizzle-kit that resolves from `from` must not write migrations; + * undefined when it may, or when it is not installed at all. drizzle-kit reads + * the schema's tables through whichever drizzle-orm it resolves, and declares + * no drizzle-orm dependency of its own. + */ +export function drizzleKitMismatch( + from: string = import.meta.url, +): string | undefined { + const kit = installedPackage("drizzle-kit", from); + if (!kit) return undefined; + if (kit.version !== DRIZZLE_KIT_VERSION) { + return `AppKit writes migrations with drizzle-kit ${DRIZZLE_KIT_VERSION}, but ${kit.version} is installed. Install that version: npm install --save-dev drizzle-kit@${DRIZZLE_KIT_VERSION}`; + } + const orm = installedPackage("drizzle-orm", import.meta.url); + const kitOrm = installedPackage("drizzle-orm", kit.entry); + if (orm && kitOrm && kitOrm.version !== orm.version) { + return `drizzle-kit loads drizzle-orm ${kitOrm.version}, but AppKit builds schemas with ${orm.version}. Use the same version: npm install drizzle-orm@${orm.version}`; + } + return undefined; +} + /** * drizzle-kit is large, so apps install it as a dev dependency and it is loaded * only when a migration is generated. */ async function loadDrizzleKit(): Promise { + const mismatch = drizzleKitMismatch(); + if (mismatch) throw new Error(mismatch); try { return await import("drizzle-kit/api"); } catch (error) { @@ -195,6 +257,20 @@ async function loadDrizzleKit(): Promise { } } +/** Replace a file through a rename, so a crash never leaves it half written. */ +function writeFileAtomic(file: string, content: string): void { + const temporary = path.join( + path.dirname(file), + `.${path.basename(file)}.${randomUUID()}.tmp`, + ); + try { + fs.writeFileSync(temporary, content); + fs.renameSync(temporary, file); + } finally { + fs.rmSync(temporary, { force: true }); + } +} + /** * Diff the schema against the latest committed snapshot with drizzle-kit and * write the next v7 migration: `NNNN_migration.sql`, `meta/NNNN_snapshot.json`, @@ -257,6 +333,30 @@ export async function generateMigrationFiles( ); fs.writeFileSync(file, statements.join(BREAKPOINT)); // The journal is written last: it is what makes the migration visible. - fs.writeFileSync(journalFile(options.folder), JSON.stringify(next, null, 2)); + writeFileAtomic(journalFile(options.folder), JSON.stringify(next, null, 2)); return { tag, file, statements }; } + +/** + * Remove a migration generateMigrationFiles wrote and put back the journal it + * replaced (null: there was none, so the folders it created go too). + */ +export function discardMigrationFiles( + folder: string, + migration: GeneratedMigration, + journalBefore: string | null, +): void { + fs.rmSync(migration.file, { force: true }); + fs.rmSync(snapshotFile(folder, Number.parseInt(migration.tag, 10)), { + force: true, + }); + if (journalBefore !== null) { + writeFileAtomic(journalFile(folder), journalBefore); + return; + } + fs.rmSync(journalFile(folder), { force: true }); + for (const dir of [path.join(folder, "meta"), folder]) { + if (fs.existsSync(dir) && fs.readdirSync(dir).length === 0) + fs.rmdirSync(dir); + } +} diff --git a/packages/appkit/src/database/tooling/tests/context.test.ts b/packages/appkit/src/database/tooling/tests/context.test.ts index e7ac24dd5..d787f442f 100644 --- a/packages/appkit/src/database/tooling/tests/context.test.ts +++ b/packages/appkit/src/database/tooling/tests/context.test.ts @@ -1,11 +1,11 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; -const { createWorkspaceClient, initializeLakebasePool } = vi.hoisted(() => ({ +const { createWorkspaceClient, createLakebasePool } = vi.hoisted(() => ({ createWorkspaceClient: vi.fn(), - initializeLakebasePool: vi.fn(), + createLakebasePool: vi.fn(), })); -vi.mock("../../../connectors/lakebase", () => ({ initializeLakebasePool })); +vi.mock("../../../connectors/lakebase", () => ({ createLakebasePool })); vi.mock("../../../workspace-client", () => ({ createWorkspaceClient })); import { getClientOptions } from "../../../context/client-options"; @@ -19,7 +19,7 @@ const HOST = "primary.dev-alice-3f9a2c.example.com"; const pool = { end: vi.fn() }; beforeEach(() => { - initializeLakebasePool.mockReset().mockResolvedValue(pool); + createLakebasePool.mockReset().mockReturnValue(pool); createWorkspaceClient.mockReset(); }); afterEach(cleanupTempApps); @@ -38,7 +38,7 @@ describe("openBranchPool", () => { ), ).resolves.toBeNull(); expect(lakebase.calls).toEqual([]); - expect(initializeLakebasePool).not.toHaveBeenCalled(); + expect(createLakebasePool).not.toHaveBeenCalled(); }); test("connects to PGHOST once it is a host of LAKEBASE_ENDPOINT", async () => { @@ -56,7 +56,7 @@ describe("openBranchPool", () => { await expect(openBranchPool(ctx)).resolves.toBe(pool); expect(lakebase.calls).toEqual([`getEndpoint ${ENDPOINT}`]); - expect(initializeLakebasePool).toHaveBeenCalledWith( + expect(createLakebasePool).toHaveBeenCalledWith( expect.objectContaining({ host: HOST.toUpperCase(), database: "databricks_postgres", @@ -67,6 +67,28 @@ describe("openBranchPool", () => { ); }); + test("without PGUSER the pool connects as the Databricks identity, and the endpoint is looked up once", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(BRANCH); + const ctx = fakeContext({ + root: tempApp(), + env: { + PGHOST: HOST, + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: ENDPOINT, + }, + userName: "4b2c1e0a-9d8f-4e7a-b6c5-3d2e1f0a9b8c", + api: lakebase.api(), + }); + + await openBranchPool(ctx); + + expect(lakebase.calls).toEqual([`getEndpoint ${ENDPOINT}`]); + expect(createLakebasePool).toHaveBeenCalledWith( + expect.objectContaining({ user: "4b2c1e0a-9d8f-4e7a-b6c5-3d2e1f0a9b8c" }), + ); + }); + test("refuses another branch's host, a missing endpoint, or a failed lookup, and never connects", async () => { const lakebase = new FakeLakebase(); lakebase.addBranch(BRANCH); @@ -114,7 +136,7 @@ describe("openBranchPool", () => { ); expect(error.cause).toBe(lookupFailure); - expect(initializeLakebasePool).not.toHaveBeenCalled(); + expect(createLakebasePool).not.toHaveBeenCalled(); }); }); diff --git a/packages/appkit/src/database/tooling/tests/contract.test.ts b/packages/appkit/src/database/tooling/tests/contract.test.ts new file mode 100644 index 000000000..f4e3765d3 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/contract.test.ts @@ -0,0 +1,20 @@ +import { expect, test } from "vitest"; + +import type { DatabaseTooling } from "../../../../../shared/src/cli/commands/db/tooling-contract"; +import type { DbContext } from "../context"; +import * as tooling from "../index"; + +// The CLI in `shared` types this module with DatabaseTooling and cannot see +// these exports, so the assignment below is what keeps the two in step. +const exports: DatabaseTooling = tooling; + +const contractKeys = { + createDbContext: true, + runMigrate: true, +} satisfies Record; + +test("every function the CLI is typed with is exported", () => { + for (const key of Object.keys(contractKeys) as (keyof DatabaseTooling)[]) { + expect(typeof exports[key]).toBe("function"); + } +}); diff --git a/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts b/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts index ec9bcb2d1..badf5ff76 100644 --- a/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts +++ b/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts @@ -1,6 +1,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { pathToFileURL } from "node:url"; import { afterEach, describe, expect, test, vi } from "vitest"; @@ -18,24 +19,30 @@ afterEach(() => { }); /** Load ../migrations with `import("drizzle-kit/api")` failing like Node's resolver does. */ -async function withoutPackage(name: string) { +async function failingImport(error: { message: string; code: string }) { vi.resetModules(); vi.doMock("drizzle-kit/api", () => { - throw Object.assign( - new Error( - `Cannot find package '${name}' imported from /app/node_modules/@databricks/appkit/dist/database/tooling/migrations.js`, - ), - { code: "ERR_MODULE_NOT_FOUND" }, - ); + throw Object.assign(new Error(error.message), { code: error.code }); }); return import("../migrations"); } -function generate(migrations: typeof import("../migrations")) { +function withoutPackage(name: string) { + return failingImport({ + message: `Cannot find package '${name}' imported from /app/node_modules/@databricks/appkit/dist/database/tooling/migrations.js`, + code: "ERR_MODULE_NOT_FOUND", + }); +} + +function tempRoot(): string { const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-drizzle-kit-")); folders.push(root); + return root; +} + +function generate(migrations: typeof import("../migrations")) { return migrations.generateMigrationFiles({ - folder: path.join(root, "migrations"), + folder: path.join(tempRoot(), "migrations"), schema: defineSchema(({ table }) => ({ notes: table("notes", { id: id() }), })), @@ -43,16 +50,30 @@ function generate(migrations: typeof import("../migrations")) { }); } -/** Source files outside tests, relative to src/. */ -function sourceFiles(): string[] { - return (fs.readdirSync(SRC, { recursive: true }) as string[]).filter( - (file) => - /\.tsx?$/.test(file) && - !/\.test\.tsx?$/.test(file) && - !file.split(path.sep).includes("tests"), - ); +/** A file URL in an app whose node_modules holds these drizzle-kit and drizzle-orm versions. */ +function appWith(versions: { kit?: string; orm?: string }): string { + const root = tempRoot(); + for (const [name, version] of [ + ["drizzle-kit", versions.kit], + ["drizzle-orm", versions.orm], + ] as const) { + if (!version) continue; + const dir = path.join(root, "node_modules", name); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, "package.json"), + JSON.stringify({ name, version, main: "index.js" }), + ); + fs.writeFileSync(path.join(dir, "index.js"), ""); + } + return pathToFileURL(path.join(root, "app.js")).href; } +const pkg = JSON.parse( + fs.readFileSync(path.resolve(SRC, "../package.json"), "utf-8"), +); +const ORM_VERSION: string = pkg.dependencies["drizzle-orm"]; + describe("drizzle-kit dependency", () => { test("without drizzle-kit, generating says how to install it", async () => { const migrations = await withoutPackage("drizzle-kit"); @@ -62,6 +83,51 @@ describe("drizzle-kit dependency", () => { ); }); + test("a drizzle-kit without the ./api export gets the same install hint", async () => { + const migrations = await failingImport({ + message: `Package subpath './api' is not defined by "exports" in /app/node_modules/drizzle-kit/package.json`, + code: "ERR_PACKAGE_PATH_NOT_EXPORTED", + }); + + await expect(generate(migrations)).rejects.toThrow( + `npm install --save-dev drizzle-kit@${migrations.DRIZZLE_KIT_VERSION}`, + ); + }); + + test("the pinned drizzle-kit on AppKit's drizzle-orm may write migrations", async () => { + const { DRIZZLE_KIT_VERSION, drizzleKitMismatch } = + await import("../migrations"); + + expect( + drizzleKitMismatch( + appWith({ kit: DRIZZLE_KIT_VERSION, orm: ORM_VERSION }), + ), + ).toBeUndefined(); + expect(drizzleKitMismatch(appWith({}))).toBeUndefined(); + }); + + test("another drizzle-kit version is refused with the command that installs the pinned one", async () => { + const { DRIZZLE_KIT_VERSION, drizzleKitMismatch } = + await import("../migrations"); + + expect( + drizzleKitMismatch(appWith({ kit: "0.30.6", orm: ORM_VERSION })), + ).toBe( + `AppKit writes migrations with drizzle-kit ${DRIZZLE_KIT_VERSION}, but 0.30.6 is installed. Install that version: npm install --save-dev drizzle-kit@${DRIZZLE_KIT_VERSION}`, + ); + }); + + test("a drizzle-kit that loads another drizzle-orm is refused", async () => { + const { DRIZZLE_KIT_VERSION, drizzleKitMismatch } = + await import("../migrations"); + + expect( + drizzleKitMismatch(appWith({ kit: DRIZZLE_KIT_VERSION, orm: "0.44.0" })), + ).toBe( + `drizzle-kit loads drizzle-orm 0.44.0, but AppKit builds schemas with ${ORM_VERSION}. Use the same version: npm install drizzle-orm@${ORM_VERSION}`, + ); + }); + test("another missing package is not reported as a missing drizzle-kit", async () => { const migrations = await withoutPackage("esbuild"); @@ -73,32 +139,10 @@ describe("drizzle-kit dependency", () => { test("it is an optional peer dependency pinned to DRIZZLE_KIT_VERSION, never a dependency", async () => { const { DRIZZLE_KIT_VERSION } = await import("../migrations"); - const pkg = JSON.parse( - fs.readFileSync(path.resolve(SRC, "../package.json"), "utf-8"), - ); expect(pkg.dependencies["drizzle-kit"]).toBeUndefined(); expect(pkg.peerDependencies["drizzle-kit"]).toBe(DRIZZLE_KIT_VERSION); expect(pkg.peerDependenciesMeta["drizzle-kit"]).toEqual({ optional: true }); expect(pkg.devDependencies["drizzle-kit"]).toBe(DRIZZLE_KIT_VERSION); }); - - test("only the tooling imports drizzle-kit, and no runtime module imports the tooling", () => { - const imports = (file: string, pattern: RegExp) => - pattern.test(fs.readFileSync(path.join(SRC, file), "utf-8")); - const tooling = path.join("database", "tooling"); - - expect( - sourceFiles().filter((file) => - imports(file, /(?:from\s+|import\s*\(\s*)["']drizzle-kit/), - ), - ).toEqual([path.join(tooling, "migrations.ts")]); - expect( - sourceFiles().filter( - (file) => - !file.startsWith(`${tooling}${path.sep}`) && - imports(file, /from\s+["'][^"']*\/tooling(?:\/[^"']*)?["']/), - ), - ).toEqual([]); - }); }); diff --git a/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts index 22adaa0f3..75d8a85e2 100644 --- a/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts +++ b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts @@ -34,16 +34,20 @@ const apiError = (statusCode: number, message: string) => describe("LakebaseApi", () => { test("getBranch: GET /api/2.0/postgres/{name}; 404 → null; other errors keep their status", async () => { + const branch = { + name: "projects/p/branches/b", + status: { current_state: "READY" }, + }; const fake = client([ - { name: "projects/p/branches/b" }, + branch, apiError(404, "NOT_FOUND"), apiError(403, "PERMISSION_DENIED"), ]); const api = new LakebaseApi(fake); - await expect(api.getBranch("projects/p/branches/b")).resolves.toEqual({ - name: "projects/p/branches/b", - }); + await expect(api.getBranch("projects/p/branches/b")).resolves.toEqual( + branch, + ); await expect( api.getBranch("projects/p/branches/missing"), ).resolves.toBeNull(); @@ -84,4 +88,39 @@ describe("LakebaseApi", () => { ["GET", "/api/2.0/postgres/projects/p/branches/b/endpoints/gone"], ]); }); + + test("getBranch refuses a branch the guard could not classify: no status, or a status of the wrong type", async () => { + const api = new LakebaseApi( + client([ + { name: "projects/p/branches/b" }, + { name: "projects/p/branches/b", status: { default: "true" } }, + ]), + ); + + await expect(api.getBranch("projects/p/branches/b")).rejects.toThrow( + "Lakebase: get branch projects/p/branches/b failed: unexpected response (status: ", + ); + await expect(api.getBranch("projects/p/branches/b")).rejects.toThrow( + /unexpected response \(status\.default: /, + ); + }); + + test("getBranch keeps the fields it does not check", async () => { + const branch = { + name: "projects/p/branches/b", + uid: "br-1", + status: { default: true, logical_size_bytes: 10 }, + }; + const api = new LakebaseApi(client([branch])); + + await expect(api.getBranch(branch.name)).resolves.toEqual(branch); + }); + + test("getEndpoint refuses a response without a name", async () => { + const api = new LakebaseApi(client([{ status: {} }])); + + await expect( + api.getEndpoint("projects/p/branches/b/endpoints/primary"), + ).rejects.toThrow(/unexpected response \(name: /); + }); }); diff --git a/packages/appkit/src/database/tooling/tests/migrate.pg.test.ts b/packages/appkit/src/database/tooling/tests/migrate.pg.test.ts new file mode 100644 index 000000000..34e6c99db --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/migrate.pg.test.ts @@ -0,0 +1,115 @@ +import { randomUUID } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { Pool } from "pg"; +import { afterAll, beforeAll, describe, expect, test, vi } from "vitest"; + +const { checkAppkitBranch, openBranchPool } = vi.hoisted(() => ({ + checkAppkitBranch: vi.fn(), + openBranchPool: vi.fn(), +})); + +vi.mock("../guard", () => ({ checkAppkitBranch })); +vi.mock("../context", async (importOriginal) => ({ + ...(await importOriginal()), + openBranchPool, +})); + +import type { DbContext } from "../context"; +import { runMigrate } from "../migrate"; + +// drizzle-kit and the migrator against a real server: the branch guard and the +// Lakebase pool are replaced, nothing else. APPKIT_TEST_PG_URL points at a +// scratch database, e.g. postgres://localhost:5432/postgres +const url = process.env.APPKIT_TEST_PG_URL; +const builder = path.resolve( + import.meta.dirname, + "../../schema-builder/index.ts", +); + +describe.skipIf(!url)("runMigrate against Postgres", () => { + const schema = `migrate_${randomUUID().slice(0, 8)}`; + let admin: Pool; + let ctx: DbContext; + + const writeSchema = (columns: string) => { + const file = path.join(ctx.root, "config/database/schema.ts"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync( + file, + `import { defineSchema, id, text } from ${JSON.stringify(builder)}; + export const schema = defineSchema( + ({ table }) => ({ notes: table("notes", { ${columns} }) }), + { schemaName: ${JSON.stringify(schema)} }, + );`, + ); + }; + const journalTags = () => + ( + JSON.parse( + fs.readFileSync( + path.join(ctx.root, "config/database/migrations/meta/_journal.json"), + "utf-8", + ), + ) as { entries: { tag: string }[] } + ).entries.map((entry) => entry.tag); + + beforeAll(() => { + admin = new Pool({ connectionString: url, max: 1 }); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-migrate-pg-")); + ctx = { + root, + env: {}, + workspace: () => { + throw new Error("no workspace calls expected"); + }, + api: () => { + throw new Error("no Lakebase API calls expected"); + }, + }; + checkAppkitBranch.mockResolvedValue({ + branch: { name: "projects/p/branches/dev-alice-3f9a2c" }, + verdict: { appkitOwned: true }, + }); + openBranchPool.mockImplementation( + async () => new Pool({ connectionString: url, max: 2 }), + ); + }); + + afterAll(async () => { + await admin.query(`drop schema if exists "${schema}" cascade`); + await admin.end(); + fs.rmSync(ctx.root, { recursive: true, force: true }); + }); + + test("a migration that fails on the branch's data is removed, and the fixed schema.ts applies", async () => { + writeSchema("id: id(), body: text()"); + await expect( + runMigrate(ctx, { interactive: false }), + ).resolves.toMatchObject({ applied: ["0000_migration"] }); + await admin.query(`insert into "${schema}".notes (body) values ('kept')`); + + writeSchema("id: id(), body: text(), title: text().notNull()"); + const error = (await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + )) as Error; + expect(error.message).toMatch( + /^Migration 0001_migration failed \(SQLSTATE 23502\) and was rolled back\. .*Removed .*0001_migration\.sql, so the next run writes it again/, + ); + expect(journalTags()).toEqual(["0000_migration"]); + + writeSchema( + 'id: id(), body: text(), title: text().notNull().default("untitled")', + ); + await expect( + runMigrate(ctx, { interactive: false }), + ).resolves.toMatchObject({ applied: ["0001_migration"] }); + expect(journalTags()).toEqual(["0000_migration", "0001_migration"]); + const { rows } = await admin.query<{ body: string; title: string }>( + `select body, title from "${schema}".notes`, + ); + expect(rows).toEqual([{ body: "kept", title: "untitled" }]); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 93f0eb500..619fd7f08 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -11,13 +11,17 @@ const { applyPendingMigrations, checkAppkitBranch, openBranchPool } = openBranchPool: vi.fn(), })); -vi.mock("../../migrations/apply", () => ({ applyPendingMigrations })); +vi.mock("../../migrations/apply", async (importOriginal) => ({ + ...(await importOriginal()), + applyPendingMigrations, +})); vi.mock("../guard", () => ({ checkAppkitBranch })); vi.mock("../context", async (importOriginal) => ({ ...(await importOriginal()), openBranchPool, })); +import { MigrationApplyError } from "../../migrations/apply"; import type { DbContext } from "../context"; import { runMigrate } from "../migrate"; @@ -27,9 +31,7 @@ const builder = path.resolve( ); const roots: string[] = []; -function app(tables: string): DbContext { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-db-migrate-")); - roots.push(root); +function writeSchema(root: string, tables: string): void { const file = path.join(root, "config/database/schema.ts"); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync( @@ -37,6 +39,12 @@ function app(tables: string): DbContext { `import { defineSchema, id, text } from ${JSON.stringify(builder)}; export const schema = defineSchema(({ table }) => ({ ${tables} }));`, ); +} + +function app(tables: string): DbContext { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-db-migrate-")); + roots.push(root); + writeSchema(root, tables); return { root, env: {}, @@ -214,6 +222,77 @@ describe("runMigrate", () => { ).toContain("notes"); }); + test("when the migration this run wrote fails to apply, it is removed so a fix in schema.ts can replace it", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + checkAppkitBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + const folder = path.join(ctx.root, "config/database/migrations"); + const journal = fs.readFileSync( + path.join(folder, "meta/_journal.json"), + "utf-8", + ); + + writeSchema( + ctx.root, + `notes: table("notes", { id: id(), title: text().notNull() })`, + ); + checkAppkitBranch.mockResolvedValue(devBranch); + openBranchPool.mockResolvedValue(pool); + const failure = new MigrationApplyError({ + step: "Applying migrations", + failed: "0001_migration", + pending: ["0001_migration"], + cause: Object.assign( + new Error('column "title" of relation "notes" contains null values'), + { code: "23502" }, + ), + }); + applyPendingMigrations.mockRejectedValue(failure); + + const error = (await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + )) as Error; + + expect(error.message).toBe( + `${failure.message} Removed ${path.join("config/database/migrations", "0001_migration.sql")}, so the next run writes it again from config/database/schema.ts. Change config/database/schema.ts or the branch's data, then rerun \`appkit db migrate\`.`, + ); + expect(error.cause).toBe(failure); + expect(fs.existsSync(path.join(folder, "0001_migration.sql"))).toBe(false); + expect(fs.existsSync(path.join(folder, "meta/0001_snapshot.json"))).toBe( + false, + ); + expect( + fs.readFileSync(path.join(folder, "meta/_journal.json"), "utf-8"), + ).toBe(journal); + }); + + test("when an earlier migration fails, the one this run wrote stays for the next try", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + checkAppkitBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + + writeSchema(ctx.root, `notes: table("notes", { id: id(), body: text() })`); + checkAppkitBranch.mockResolvedValue(devBranch); + openBranchPool.mockResolvedValue(pool); + applyPendingMigrations.mockRejectedValue( + new MigrationApplyError({ + step: "Applying migrations", + failed: "0000_migration", + pending: ["0000_migration", "0001_migration"], + cause: Object.assign(new Error("duplicate key"), { code: "23505" }), + }), + ); + + await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( + /^Wrote .*0001_migration\.sql, but did not apply it: Migration 0000_migration failed/, + ); + expect( + fs.existsSync( + path.join(ctx.root, "config/database/migrations/0001_migration.sql"), + ), + ).toBe(true); + }); + test("a guard failure after generating says so too, and never connects", async () => { const ctx = app(`notes: table("notes", { id: id() })`); checkAppkitBranch.mockRejectedValue( diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index 39c8bf193..79ed30f2e 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -19,6 +19,7 @@ import { varchar, } from "../../schema-builder"; import { + discardMigrationFiles, generateMigrationFiles, MigrationRenameAmbiguityError, } from "../migrations"; @@ -341,3 +342,42 @@ describe("generateMigrationFiles", () => { ); }); }); + +describe("discardMigrationFiles", () => { + test("a first migration goes with the folders it created", async () => { + const folder = tempFolder(); + const migration = await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + + discardMigrationFiles(folder, migration as never, null); + + expect(fs.existsSync(folder)).toBe(false); + }); + + test("a later migration goes, and the previous journal comes back byte for byte", async () => { + const folder = tempFolder(); + await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + const journalFile = path.join(folder, "meta/_journal.json"); + const journalBefore = `${fs.readFileSync(journalFile, "utf-8")}\n`; + fs.writeFileSync(journalFile, journalBefore); + const filesBefore = listFiles(folder); + const migration = await generateMigrationFiles({ + folder, + schema: blog({ summary: text() }), + interactive: false, + }); + expect(listFiles(folder)).not.toEqual(filesBefore); + + discardMigrationFiles(folder, migration as never, journalBefore); + + expect(listFiles(folder)).toEqual(filesBefore); + expect(fs.readFileSync(journalFile, "utf-8")).toBe(journalBefore); + }); +}); diff --git a/packages/appkit/src/plugins/database/load-schema.ts b/packages/appkit/src/plugins/database/load-schema.ts index fa9f3ef0f..a94438635 100644 --- a/packages/appkit/src/plugins/database/load-schema.ts +++ b/packages/appkit/src/plugins/database/load-schema.ts @@ -6,7 +6,7 @@ import type { Schema } from "../../database/schema-builder"; import { assertFinalizedSchema } from "../../database/schema-builder/define-schema"; /** Same application-relative convention used by appkit generate-types. */ -const DEFAULT_SCHEMA_FILE = "config/database/schema.ts"; +export const DEFAULT_SCHEMA_FILE = "config/database/schema.ts"; interface LoadSchemaOptions { /** Report why the module failed to import. Only for local CLI runs: see the catch below. */ diff --git a/packages/appkit/src/type-generator/database/generate.ts b/packages/appkit/src/type-generator/database/generate.ts index aea019c65..f4917d496 100644 --- a/packages/appkit/src/type-generator/database/generate.ts +++ b/packages/appkit/src/type-generator/database/generate.ts @@ -119,6 +119,14 @@ async function writeIfChanged(outFile: string, content: string): Promise { } } +/** Write the registry types for a schema the caller already loaded. */ +export function writeDatabaseTypes( + schema: Schema, + outFile: string, +): Promise { + return writeIfChanged(outFile, render(schema)); +} + /** Disable Jiti's module cache so watch-mode runs observe schema edits. */ async function importSchema(schemaFile: string): Promise { const { createJiti } = await import("jiti"); diff --git a/packages/appkit/src/type-generator/database/index.ts b/packages/appkit/src/type-generator/database/index.ts index 0648bba2c..e3581fb7f 100644 --- a/packages/appkit/src/type-generator/database/index.ts +++ b/packages/appkit/src/type-generator/database/index.ts @@ -2,4 +2,5 @@ export { DATABASE_TYPES_FILE, DatabaseTypegenError, generateDatabaseTypes, + writeDatabaseTypes, } from "./generate"; diff --git a/packages/shared/src/cli/commands/db/database-tooling.d.ts b/packages/shared/src/cli/commands/db/database-tooling.d.ts index b1c18beee..b133e7871 100644 --- a/packages/shared/src/cli/commands/db/database-tooling.d.ts +++ b/packages/shared/src/cli/commands/db/database-tooling.d.ts @@ -1,39 +1,4 @@ -/** - * Intentionally narrowed mirror of `@databricks/appkit/database-tooling`. - * - * `shared` is a leaf package and must not statically depend on `appkit`, so the - * CLI loads the tooling via a dynamic `import(...)` and this declares its shape - * without a build-time dependency (same pattern as ../type-generator.d.ts). - * There is NO compile-time link to the real exports — if they change, re-sync - * this by hand against `packages/appkit/src/database/tooling/index.ts`. - */ -declare module "@databricks/appkit/database-tooling" { - export interface DbContext { - readonly root: string; - readonly env: NodeJS.ProcessEnv; - } - - export function createDbContext(options?: { - root?: string; - env?: NodeJS.ProcessEnv; - }): DbContext; - - export interface GeneratedMigration { - readonly tag: string; - readonly file: string; - readonly statements: readonly string[]; - } - - export interface MigrateReport { - readonly generated: GeneratedMigration | null; - readonly applied: readonly string[]; - readonly adopted?: readonly string[]; - readonly notApplied?: string; - readonly typesFile: string; - } - - export function runMigrate( - ctx: DbContext, - options: { interactive: boolean }, - ): Promise; -} +// `shared` must not depend on `appkit`, so this only makes the dynamic import +// resolve. Its type is DatabaseTooling in ./tooling-contract.ts, which appkit's +// typecheck checks against the real exports. +declare module "@databricks/appkit/database-tooling"; diff --git a/packages/shared/src/cli/commands/db/load-tooling.ts b/packages/shared/src/cli/commands/db/load-tooling.ts new file mode 100644 index 000000000..870d1ad98 --- /dev/null +++ b/packages/shared/src/cli/commands/db/load-tooling.ts @@ -0,0 +1,6 @@ +import type { DatabaseTooling } from "./tooling-contract"; + +/** The appkit tooling, loaded on first use and typed by the checked contract. */ +export function loadDatabaseTooling(): Promise { + return import("@databricks/appkit/database-tooling"); +} diff --git a/packages/shared/src/cli/commands/db/migrate.ts b/packages/shared/src/cli/commands/db/migrate.ts index 8d061f6b0..7096022ba 100644 --- a/packages/shared/src/cli/commands/db/migrate.ts +++ b/packages/shared/src/cli/commands/db/migrate.ts @@ -1,10 +1,11 @@ import { Command } from "commander"; +import { loadDatabaseTooling } from "./load-tooling"; import { fail, isInteractive, printMigrateReport } from "./output"; async function runDbMigrate(): Promise { try { - const tooling = await import("@databricks/appkit/database-tooling"); + const tooling = await loadDatabaseTooling(); const report = await tooling.runMigrate(tooling.createDbContext(), { interactive: isInteractive(), }); diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 2cfba1973..ec652b74a 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -1,9 +1,10 @@ import path from "node:path"; import process from "node:process"; -import type { MigrateReport } from "@databricks/appkit/database-tooling"; import pc from "picocolors"; +import type { MigrateReport } from "./tooling-contract"; + /** Prompts only when a human can answer them. */ export function isInteractive(): boolean { return Boolean(process.stdin.isTTY && process.stdout.isTTY); diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts new file mode 100644 index 000000000..c8eea40b3 --- /dev/null +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -0,0 +1,37 @@ +/** What the CLI reads from a tooling context; the rest belongs to the tooling. */ +export interface DbContext { + readonly root: string; + readonly env: NodeJS.ProcessEnv; +} + +export interface GeneratedMigration { + readonly tag: string; + readonly file: string; + readonly statements: readonly string[]; +} + +export interface MigrateReport { + readonly generated: GeneratedMigration | null; + readonly applied: readonly string[]; + readonly adopted?: readonly string[]; + readonly notApplied?: string; + readonly typesFile: string; +} + +/** + * The exports of `@databricks/appkit/database-tooling` the CLI calls. `shared` + * must not depend on appkit, so the CLI imports the tooling dynamically and + * types it with this interface, and appkit's typecheck checks its real exports + * against it (`database/tooling/tests/contract.test.ts`). Function properties, + * not methods, so a parameter narrowed in appkit fails that check. + */ +export interface DatabaseTooling { + readonly createDbContext: (options?: { + root?: string; + env?: NodeJS.ProcessEnv; + }) => Ctx; + readonly runMigrate: ( + ctx: Ctx, + options: { interactive: boolean }, + ) => Promise; +} From ef0c3992d23798e65fd39e56009cf334dc53f2b6 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 19 Oct 2026 15:10:08 +0200 Subject: [PATCH 007/317] refactor(appkit): resolve the .env branch kind once and share the branch pool resolveEnvBranch returns the branch kind (default, protected, deploy target, dev, session, other), and takesWrites is the one rule for which kinds take writes. It needs PGHOST, PGDATABASE and LAKEBASE_ENDPOINT, like the pool. withBranchPool opens and always closes the pool. The drizzle-kit v7 file names live only in migrations/paths.ts. Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 11 +-- .../appkit/src/database/migrations/paths.ts | 25 ++++- .../appkit/src/database/tooling/context.ts | 32 ++++++- packages/appkit/src/database/tooling/guard.ts | 62 ++++++++---- .../appkit/src/database/tooling/migrate.ts | 24 ++--- .../appkit/src/database/tooling/migrations.ts | 20 ++-- .../database/tooling/tests/context.test.ts | 54 ++++++++--- .../src/database/tooling/tests/guard.test.ts | 91 +++++++++--------- .../database/tooling/tests/migrate.pg.test.ts | 28 ++++-- .../database/tooling/tests/migrate.test.ts | 95 +++++++++---------- 10 files changed, 269 insertions(+), 173 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index bc9a1f99d..c8e5f9c3f 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -1,6 +1,5 @@ import { createHash } from "node:crypto"; import fs from "node:fs"; -import path from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { readMigrationFiles } from "drizzle-orm/migrator"; @@ -22,8 +21,10 @@ import { type Journal, MIGRATIONS_TABLE, MigrationFilesError, + migrationFile, readJournal, readJsonFile, + snapshotFile, } from "./paths"; const logger = createLogger("database"); @@ -228,7 +229,7 @@ type QueryClient = Pick; /** 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 = path.join(folder, `${entry.tag}.sql`); + 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.`, @@ -454,11 +455,7 @@ function snapshotTables( idx: number, schemaName: string, ): Map { - const file = path.join( - folder, - "meta", - `${String(idx).padStart(4, "0")}_snapshot.json`, - ); + 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.`, diff --git a/packages/appkit/src/database/migrations/paths.ts b/packages/appkit/src/database/migrations/paths.ts index 8d5126076..63a8b7263 100644 --- a/packages/appkit/src/database/migrations/paths.ts +++ b/packages/appkit/src/database/migrations/paths.ts @@ -33,9 +33,32 @@ 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(folder, "meta", "_journal.json"); + 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. */ diff --git a/packages/appkit/src/database/tooling/context.ts b/packages/appkit/src/database/tooling/context.ts index 580ee303d..76d95f25e 100644 --- a/packages/appkit/src/database/tooling/context.ts +++ b/packages/appkit/src/database/tooling/context.ts @@ -98,14 +98,23 @@ async function assertHostServesEndpoint( } } +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); +} + /** - * null when PGHOST / PGDATABASE / LAKEBASE_ENDPOINT are not configured. The - * pool is created directly: initializeLakebasePool would look the endpoint and - * the user up a second time. + * The pool is created directly: initializeLakebasePool would look the endpoint + * and the user up a second time. */ -export async function openBranchPool(ctx: DbContext): Promise { +async function openBranchPool(ctx: DbContext): Promise { const { PGHOST, PGDATABASE, LAKEBASE_ENDPOINT } = ctx.env; - if (!PGHOST || !PGDATABASE || !LAKEBASE_ENDPOINT) return null; + if (!PGHOST || !PGDATABASE || !LAKEBASE_ENDPOINT) { + throw new Error(`Did not connect: ${NO_ENV_BRANCH}.`); + } const [user] = await Promise.all([ ctx.env.PGUSER || currentIdentity(ctx).then(({ userName }) => userName), assertHostServesEndpoint(ctx, LAKEBASE_ENDPOINT, PGHOST), @@ -128,3 +137,16 @@ export async function openBranchPool(ctx: DbContext): Promise { 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/guard.ts b/packages/appkit/src/database/tooling/guard.ts index 001afd60b..994fe1fac 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -1,4 +1,4 @@ -import type { DbContext } from "./context"; +import { type DbContext, hasEnvBranch } from "./context"; import { currentIdentity } from "./identity"; import type { LakebaseBranch } from "./lakebase-api"; import { devBranchId, sessionBranchId } from "./naming"; @@ -9,12 +9,18 @@ import { resourceId, } from "./targets"; -// Commands that write to a branch run only on branches `appkit db init` -// created for this developer (dev-…) or this checkout (session-…). +/** What a branch is to this developer, checked in this order. */ +type BranchKind = + | "default" + | "protected" + | "deploy-target" + | "dev" + | "session" + | "other"; -interface BranchVerdict { - readonly appkitOwned: boolean; - /** Why the branch is not AppKit-owned. */ +interface Classification { + readonly kind: BranchKind; + /** Why the branch takes no writes; undefined for dev and session branches. */ readonly reason?: string; } @@ -24,27 +30,27 @@ export function classifyBranch(input: { sessionId: string | null; /** Every branch databricks.yml deploys to; the deployed app migrates those itself. */ deployBranches: readonly string[]; -}): BranchVerdict { +}): Classification { const { branch, userName, sessionId, deployBranches } = input; if (branch.status?.default) { - return { appkitOwned: false, reason: "it is the project's default branch" }; + return { kind: "default", reason: "it is the project's default branch" }; } if (branch.status?.is_protected) { - return { appkitOwned: false, reason: "it is a protected branch" }; + return { kind: "protected", reason: "it is a protected branch" }; } if (deployBranches.includes(branch.name)) { return { - appkitOwned: false, + kind: "deploy-target", reason: "it is a branch databricks.yml deploys to", }; } const id = resourceId(branch.name); - if (id === devBranchId(userName)) return { appkitOwned: true }; + if (id === devBranchId(userName)) return { kind: "dev" }; if (sessionId && id === sessionBranchId(sessionId)) { - return { appkitOwned: true }; + return { kind: "session" }; } return { - appkitOwned: false, + kind: "other", reason: `it is not your dev branch (${devBranchId(userName)})${ sessionId ? ` or this checkout's session branch (${sessionBranchId(sessionId)})` @@ -53,18 +59,34 @@ export function classifyBranch(input: { }; } -interface BranchCheck { +/** + * 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 and what it is to this developer. */ +interface EnvBranch extends Classification { readonly branch: LakebaseBranch; - readonly verdict: BranchVerdict; } -/** Classify the `.env` branch through the API (no database connection); null when none is configured. */ -export async function checkAppkitBranch( +/** Why a command does not write to the branch. */ +export function notYourBranch(env: EnvBranch): string { + return `${resourceId(env.branch.name)} is not your dev or session branch (${env.reason})`; +} + +/** + * 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 { +): Promise { const local = readLocalTarget(ctx.env); const name = parseResourceName(local.endpoint ?? undefined)?.branch; - if (!name) return null; + if (!name || !hasEnvBranch(ctx.env)) return null; const [branch, { userName }] = await Promise.all([ ctx.api().getBranch(name), currentIdentity(ctx), @@ -76,7 +98,7 @@ export async function checkAppkitBranch( } return { branch, - verdict: classifyBranch({ + ...classifyBranch({ branch, userName, sessionId: local.session, diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 0182d49ce..dbcb41a7d 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -18,14 +18,13 @@ import { migrationsFolder, readJournal, } from "../migrations/paths"; -import { type DbContext, openBranchPool } from "./context"; -import { checkAppkitBranch } from "./guard"; +import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context"; +import { notYourBranch, resolveEnvBranch, takesWrites } from "./guard"; import { discardMigrationFiles, type GeneratedMigration, generateMigrationFiles, } from "./migrations"; -import { resourceId } from "./targets"; /** Whether the checkout has a config/database/schema.ts yet. */ function hasSchemaFile(root: string): boolean { @@ -69,15 +68,12 @@ export interface MigrateOptions { type ApplyOutcome = Pick; -const NO_BRANCH = - "no branch configured (PGHOST, PGDATABASE, LAKEBASE_ENDPOINT) — run appkit db init"; - /** Why migrations must not be applied to the `.env` branch; undefined when they may. */ async function applyBlocker(ctx: DbContext): Promise { - const check = await checkAppkitBranch(ctx); - if (!check) return NO_BRANCH; - if (check.verdict.appkitOwned) return undefined; - return `${resourceId(check.branch.name)} is not an AppKit dev or session branch (${check.verdict.reason}). Migrations are applied only to branches \`appkit db init\` created for you; the deployed app applies committed migrations to its own branch`; + const env = await resolveEnvBranch(ctx); + if (!env) return NO_ENV_BRANCH; + if (takesWrites(env.kind)) return undefined; + return `${notYourBranch(env)}. Migrations are applied only to branches \`appkit db init\` created for you; the deployed app applies committed migrations to its own branch`; } /** Apply pending migrations to the `.env` branch, or say why they were not. */ @@ -90,17 +86,13 @@ async function applyToEnvBranch( ? await applyBlocker(ctx) : "no migrations to apply — schema.ts declares no tables yet"; if (blocker) return { applied: [], notApplied: blocker }; - const pool = await openBranchPool(ctx); - if (!pool) return { applied: [], notApplied: NO_BRANCH }; - try { + return withBranchPool(ctx, async (pool) => { const { applied, adopted } = await applyPendingMigrations(pool, { migrationsFolder: folder, schemaName, }); return { applied, ...(adopted.length > 0 ? { adopted } : {}) }; - } finally { - await pool.end().catch(() => undefined); - } + }); } /** diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 021ca2595..21ada21bd 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -7,8 +7,12 @@ import { type Journal, type JournalEntry, journalFile, + metaFolder, + migrationFile, + migrationPrefix, readJournal, readJsonFile, + snapshotFile, } from "../migrations/paths"; import type { Schema } from "../schema-builder"; import { drizzleKitImports } from "./drizzle-exports"; @@ -96,14 +100,6 @@ function originSnapshot(): Snapshot { }; } -function prefixOf(idx: number): string { - return String(idx).padStart(4, "0"); -} - -function snapshotFile(folder: string, idx: number): string { - return path.join(folder, "meta", `${prefixOf(idx)}_snapshot.json`); -} - function latestSnapshot(folder: string, journal: Journal | null): Snapshot { const last = journal?.entries.at(-1); if (!last) return originSnapshot(); @@ -306,7 +302,7 @@ export async function generateMigrationFiles( const entries = journal?.entries ?? []; const last = entries.at(-1); const idx = last ? last.idx + 1 : 0; - const tag = `${prefixOf(idx)}_migration`; + const tag = `${migrationPrefix(idx)}_migration`; const entry: JournalEntry = { idx, version: "7", @@ -321,8 +317,8 @@ export async function generateMigrationFiles( entries: [...entries, entry], }; - const file = path.join(options.folder, `${tag}.sql`); - fs.mkdirSync(path.join(options.folder, "meta"), { recursive: true }); + const file = migrationFile(options.folder, tag); + fs.mkdirSync(metaFolder(options.folder), { recursive: true }); fs.writeFileSync( snapshotFile(options.folder, idx), JSON.stringify( @@ -355,7 +351,7 @@ export function discardMigrationFiles( return; } fs.rmSync(journalFile(folder), { force: true }); - for (const dir of [path.join(folder, "meta"), folder]) { + for (const dir of [metaFolder(folder), folder]) { if (fs.existsSync(dir) && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir); } diff --git a/packages/appkit/src/database/tooling/tests/context.test.ts b/packages/appkit/src/database/tooling/tests/context.test.ts index d787f442f..df06855ea 100644 --- a/packages/appkit/src/database/tooling/tests/context.test.ts +++ b/packages/appkit/src/database/tooling/tests/context.test.ts @@ -9,17 +9,19 @@ vi.mock("../../../connectors/lakebase", () => ({ createLakebasePool })); vi.mock("../../../workspace-client", () => ({ createWorkspaceClient })); import { getClientOptions } from "../../../context/client-options"; -import { createDbContext, openBranchPool } from "../context"; +import { createDbContext, withBranchPool } from "../context"; import type { LakebaseApi } from "../lakebase-api"; import { cleanupTempApps, FakeLakebase, fakeContext, tempApp } from "./fakes"; const BRANCH = "projects/p/branches/dev-alice-3f9a2c"; const ENDPOINT = `${BRANCH}/endpoints/primary`; const HOST = "primary.dev-alice-3f9a2c.example.com"; -const pool = { end: vi.fn() }; +const pool = { end: vi.fn(async () => undefined) }; +const usePool = async (p: unknown) => p; beforeEach(() => { createLakebasePool.mockReset().mockReturnValue(pool); + pool.end.mockClear(); createWorkspaceClient.mockReset(); }); afterEach(cleanupTempApps); @@ -28,15 +30,18 @@ function contextFor(env: NodeJS.ProcessEnv, api: LakebaseApi) { return fakeContext({ root: tempApp(), env, api }); } -describe("openBranchPool", () => { - test("null without PGHOST, PGDATABASE and LAKEBASE_ENDPOINT, before any API call", async () => { +describe("withBranchPool", () => { + test("refuses without PGHOST, PGDATABASE and LAKEBASE_ENDPOINT, before any API call", async () => { const lakebase = new FakeLakebase(); await expect( - openBranchPool( + withBranchPool( contextFor({ PGHOST: HOST, PGDATABASE: "db" }, lakebase.api()), + usePool, ), - ).resolves.toBeNull(); + ).rejects.toThrow( + "Did not connect: no branch is configured in .env (PGHOST, PGDATABASE and LAKEBASE_ENDPOINT); run `appkit db init`.", + ); expect(lakebase.calls).toEqual([]); expect(createLakebasePool).not.toHaveBeenCalled(); }); @@ -54,7 +59,8 @@ describe("openBranchPool", () => { lakebase.api(), ); - await expect(openBranchPool(ctx)).resolves.toBe(pool); + await expect(withBranchPool(ctx, usePool)).resolves.toBe(pool); + expect(pool.end).toHaveBeenCalledOnce(); expect(lakebase.calls).toEqual([`getEndpoint ${ENDPOINT}`]); expect(createLakebasePool).toHaveBeenCalledWith( expect.objectContaining({ @@ -81,7 +87,7 @@ describe("openBranchPool", () => { api: lakebase.api(), }); - await openBranchPool(ctx); + await withBranchPool(ctx, usePool); expect(lakebase.calls).toEqual([`getEndpoint ${ENDPOINT}`]); expect(createLakebasePool).toHaveBeenCalledWith( @@ -98,17 +104,18 @@ describe("openBranchPool", () => { }; await expect( - openBranchPool( + withBranchPool( contextFor( { ...env, PGHOST: "primary.production.example.com" }, lakebase.api(), ), + usePool, ), ).rejects.toThrow( `PGHOST primary.production.example.com is not a host of LAKEBASE_ENDPOINT ${ENDPOINT} (expected ${HOST}), so it did not connect. Run \`appkit db init\` to rewrite .env.`, ); await expect( - openBranchPool( + withBranchPool( contextFor( { ...env, @@ -117,6 +124,7 @@ describe("openBranchPool", () => { }, lakebase.api(), ), + usePool, ), ).rejects.toThrow( `LAKEBASE_ENDPOINT ${BRANCH}/endpoints/gone does not exist, so it did not connect.`, @@ -128,8 +136,9 @@ describe("openBranchPool", () => { throw lookupFailure; }, } as unknown as LakebaseApi; - const error = (await openBranchPool( + const error = (await withBranchPool( contextFor({ ...env, PGHOST: HOST }, failing), + usePool, ).catch((caught: unknown) => caught)) as Error; expect(error.message).toBe( `Could not verify that PGHOST ${HOST} serves LAKEBASE_ENDPOINT ${ENDPOINT}, so it did not connect.`, @@ -138,6 +147,29 @@ describe("openBranchPool", () => { expect(createLakebasePool).not.toHaveBeenCalled(); }); + + test("closes the pool when fn fails, and rethrows fn's error", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(BRANCH); + const ctx = contextFor( + { + PGHOST: HOST, + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: ENDPOINT, + PGUSER: "alice@example.com", + }, + lakebase.api(), + ); + const failure = new Error("query failed"); + pool.end.mockRejectedValueOnce(new Error("end failed")); + + await expect( + withBranchPool(ctx, async () => { + throw failure; + }), + ).rejects.toBe(failure); + expect(pool.end).toHaveBeenCalledOnce(); + }); }); describe("createDbContext", () => { diff --git a/packages/appkit/src/database/tooling/tests/guard.test.ts b/packages/appkit/src/database/tooling/tests/guard.test.ts index 175f9823c..ee79cbf59 100644 --- a/packages/appkit/src/database/tooling/tests/guard.test.ts +++ b/packages/appkit/src/database/tooling/tests/guard.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, test } from "vitest"; -import { checkAppkitBranch, classifyBranch } from "../guard"; +import { classifyBranch, resolveEnvBranch, takesWrites } from "../guard"; import { devBranchId } from "../naming"; import { cleanupTempApps, @@ -31,45 +31,48 @@ function verdict( } describe("classifyBranch", () => { - test("only this developer's dev branch and this checkout's session branch are AppKit-owned", () => { - expect(verdict(dev)).toEqual({ appkitOwned: true }); + test("only this developer's dev branch and this checkout's session branch take writes", () => { + expect(verdict(dev)).toEqual({ kind: "dev" }); expect(verdict(`${P}/branches/session-k2x9q0ab`)).toEqual({ - appkitOwned: true, + kind: "session", }); + expect(takesWrites("dev")).toBe(true); + expect(takesWrites("session")).toBe(true); }); - test("everything else is refused, with the reason", () => { - expect( - verdict(`${P}/branches/production`, { default: true }), - ).toMatchObject({ - appkitOwned: false, + test("everything else is another kind, with the reason", () => { + expect(verdict(`${P}/branches/production`, { default: true })).toEqual({ + kind: "default", reason: "it is the project's default branch", }); - expect(verdict(dev, { is_protected: true })).toMatchObject({ - appkitOwned: false, + expect(verdict(dev, { is_protected: true })).toEqual({ + kind: "protected", reason: "it is a protected branch", }); - expect( - verdict(dev, {}, null, [`${P}/branches/staging`, dev]), - ).toMatchObject({ - appkitOwned: false, + expect(verdict(dev, {}, null, [`${P}/branches/staging`, dev])).toEqual({ + kind: "deploy-target", reason: "it is a branch databricks.yml deploys to", }); expect( - verdict(`${P}/branches/${devBranchId("bob@example.com")}`).appkitOwned, - ).toBe(false); - expect(verdict(`${P}/branches/session-other`).appkitOwned).toBe(false); - expect( - verdict(`${P}/branches/session-k2x9q0ab`, {}, null).appkitOwned, - ).toBe(false); + verdict(`${P}/branches/${devBranchId("bob@example.com")}`).kind, + ).toBe("other"); + expect(verdict(`${P}/branches/session-other`).kind).toBe("other"); + expect(verdict(`${P}/branches/session-k2x9q0ab`, {}, null).kind).toBe( + "other", + ); expect(verdict(`${P}/branches/staging`).reason).toContain( devBranchId(USER), ); + for (const kind of ["default", "protected", "deploy-target", "other"]) { + expect(takesWrites(kind as "other")).toBe(false); + } }); }); -describe("checkAppkitBranch", () => { +describe("resolveEnvBranch", () => { const envFor = (branch: string) => ({ + PGHOST: "primary.example.com", + PGDATABASE: "databricks_postgres", LAKEBASE_ENDPOINT: `${branch}/endpoints/primary`, }); @@ -78,23 +81,21 @@ describe("checkAppkitBranch", () => { lakebase.addBranch(dev); lakebase.addBranch(`${P}/branches/production`, { default: true }); - const onDev = await checkAppkitBranch( + const onDev = await resolveEnvBranch( fakeContext({ root: tempApp(), env: envFor(dev), api: lakebase.api() }), ); - expect(onDev).toMatchObject({ - branch: { name: dev }, - verdict: { appkitOwned: true }, - }); + expect(onDev).toMatchObject({ branch: { name: dev }, kind: "dev" }); + expect(onDev?.reason).toBeUndefined(); - const onDefault = await checkAppkitBranch( + const onDefault = await resolveEnvBranch( fakeContext({ root: tempApp(), env: envFor(`${P}/branches/production`), api: lakebase.api(), }), ); - expect(onDefault?.verdict).toEqual({ - appkitOwned: false, + expect(onDefault).toMatchObject({ + kind: "default", reason: "it is the project's default branch", }); expect(lakebase.calls.every((call) => call.startsWith("getBranch"))).toBe( @@ -102,7 +103,7 @@ describe("checkAppkitBranch", () => { ); }); - test("a branch databricks.yml deploys to is never AppKit-owned", async () => { + test("a branch databricks.yml deploys to never takes writes", async () => { const lakebase = new FakeLakebase(); lakebase.addBranch(dev); const root = tempApp({ @@ -112,12 +113,12 @@ describe("checkAppkitBranch", () => { ), }); - const check = await checkAppkitBranch( + const env = await resolveEnvBranch( fakeContext({ root, env: envFor(dev), api: lakebase.api() }), ); - expect(check?.verdict).toEqual({ - appkitOwned: false, + expect(env).toMatchObject({ + kind: "deploy-target", reason: "it is a branch databricks.yml deploys to", }); }); @@ -133,19 +134,16 @@ describe("checkAppkitBranch", () => { }); const broken = tempApp({ "databricks.yml": "targets:\n default: [\n" }); - const check = await checkAppkitBranch( + const env = await resolveEnvBranch( fakeContext({ root: personalTarget, env: envFor(dev), api: lakebase.api(), }), ); - expect(check?.verdict).toEqual({ - appkitOwned: false, - reason: "it is a branch databricks.yml deploys to", - }); + expect(env).toMatchObject({ kind: "deploy-target" }); await expect( - checkAppkitBranch( + resolveEnvBranch( fakeContext({ root: broken, env: envFor(dev), api: lakebase.api() }), ), ).rejects.toThrow( @@ -153,13 +151,20 @@ describe("checkAppkitBranch", () => { ); }); - test("null without a configured branch; a deleted branch points at init", async () => { + test("null unless .env names a branch to connect to; a deleted branch points at init", async () => { const lakebase = new FakeLakebase(); await expect( - checkAppkitBranch(fakeContext({ root: tempApp(), api: lakebase.api() })), + resolveEnvBranch(fakeContext({ root: tempApp(), api: lakebase.api() })), + ).resolves.toBeNull(); + const { PGHOST: _host, ...noHost } = envFor(dev); + await expect( + resolveEnvBranch( + fakeContext({ root: tempApp(), env: noHost, api: lakebase.api() }), + ), ).resolves.toBeNull(); + expect(lakebase.calls).toEqual([]); await expect( - checkAppkitBranch( + resolveEnvBranch( fakeContext({ root: tempApp(), env: envFor(dev), api: lakebase.api() }), ), ).rejects.toThrow(/does not exist.*appkit db init/); diff --git a/packages/appkit/src/database/tooling/tests/migrate.pg.test.ts b/packages/appkit/src/database/tooling/tests/migrate.pg.test.ts index 34e6c99db..b4748d573 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.pg.test.ts @@ -6,15 +6,18 @@ import path from "node:path"; import { Pool } from "pg"; import { afterAll, beforeAll, describe, expect, test, vi } from "vitest"; -const { checkAppkitBranch, openBranchPool } = vi.hoisted(() => ({ - checkAppkitBranch: vi.fn(), - openBranchPool: vi.fn(), +const { resolveEnvBranch, withBranchPool } = vi.hoisted(() => ({ + resolveEnvBranch: vi.fn(), + withBranchPool: vi.fn(), })); -vi.mock("../guard", () => ({ checkAppkitBranch })); +vi.mock("../guard", async (importOriginal) => ({ + ...(await importOriginal()), + resolveEnvBranch, +})); vi.mock("../context", async (importOriginal) => ({ ...(await importOriginal()), - openBranchPool, + withBranchPool, })); import type { DbContext } from "../context"; @@ -69,12 +72,19 @@ describe.skipIf(!url)("runMigrate against Postgres", () => { throw new Error("no Lakebase API calls expected"); }, }; - checkAppkitBranch.mockResolvedValue({ + resolveEnvBranch.mockResolvedValue({ branch: { name: "projects/p/branches/dev-alice-3f9a2c" }, - verdict: { appkitOwned: true }, + kind: "dev", }); - openBranchPool.mockImplementation( - async () => new Pool({ connectionString: url, max: 2 }), + withBranchPool.mockImplementation( + async (_ctx, fn: (pool: Pool) => Promise) => { + const pool = new Pool({ connectionString: url, max: 2 }); + try { + return await fn(pool); + } finally { + await pool.end(); + } + }, ); }); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 619fd7f08..dd88e8e33 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -4,21 +4,25 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; -const { applyPendingMigrations, checkAppkitBranch, openBranchPool } = - vi.hoisted(() => ({ +const { applyPendingMigrations, resolveEnvBranch, withBranchPool } = vi.hoisted( + () => ({ applyPendingMigrations: vi.fn(), - checkAppkitBranch: vi.fn(), - openBranchPool: vi.fn(), - })); + resolveEnvBranch: vi.fn(), + withBranchPool: vi.fn(), + }), +); vi.mock("../../migrations/apply", async (importOriginal) => ({ ...(await importOriginal()), applyPendingMigrations, })); -vi.mock("../guard", () => ({ checkAppkitBranch })); +vi.mock("../guard", async (importOriginal) => ({ + ...(await importOriginal()), + resolveEnvBranch, +})); vi.mock("../context", async (importOriginal) => ({ ...(await importOriginal()), - openBranchPool, + withBranchPool, })); import { MigrationApplyError } from "../../migrations/apply"; @@ -59,17 +63,18 @@ function app(tables: string): DbContext { const devBranch = { branch: { name: "projects/p/branches/dev-alice-3f9a2c" }, - verdict: { appkitOwned: true }, + kind: "dev", }; -const pool = { end: vi.fn(async () => undefined) }; +const pool = {}; beforeEach(() => { applyPendingMigrations.mockReset(); - openBranchPool.mockReset(); - checkAppkitBranch.mockReset(); - checkAppkitBranch.mockResolvedValue(devBranch); - pool.end.mockClear(); + withBranchPool + .mockReset() + .mockImplementation((_ctx, fn: (p: unknown) => unknown) => fn(pool)); + resolveEnvBranch.mockReset(); + resolveEnvBranch.mockResolvedValue(devBranch); }); afterEach(() => { @@ -86,7 +91,7 @@ describe("runMigrate", () => { await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( "No config/database/schema.ts yet, so there is nothing to migrate. Run `appkit db introspect` to write it from the branch's tables, or create it.", ); - expect(checkAppkitBranch).not.toHaveBeenCalled(); + expect(resolveEnvBranch).not.toHaveBeenCalled(); expect( fs.existsSync(path.join(ctx.root, "config/database/migrations")), ).toBe(false); @@ -99,17 +104,16 @@ describe("runMigrate", () => { expect(report.generated).toBeNull(); expect(report.applied).toEqual([]); expect(report.notApplied).toMatch(/no migrations/); - expect(openBranchPool).not.toHaveBeenCalled(); - expect(checkAppkitBranch).not.toHaveBeenCalled(); + expect(withBranchPool).not.toHaveBeenCalled(); + expect(resolveEnvBranch).not.toHaveBeenCalled(); expect(report.typesFile).toBe( path.join(ctx.root, "shared/appkit-types/database.d.ts"), ); expect(fs.existsSync(report.typesFile)).toBe(true); }); - test("generates, regenerates types, applies to the .env branch with the app schema, and ends the pool", async () => { + test("generates, regenerates types, and applies to the .env branch with the app schema", async () => { const ctx = app(`notes: table("notes", { id: id(), body: text() })`); - openBranchPool.mockResolvedValue(pool); applyPendingMigrations.mockResolvedValue({ applied: ["0000_migration"], adopted: [], @@ -118,23 +122,22 @@ describe("runMigrate", () => { const report = await runMigrate(ctx, { interactive: false }); expect(report.generated?.tag).toBe("0000_migration"); - expect(openBranchPool).toHaveBeenCalledWith(ctx); + expect(withBranchPool).toHaveBeenCalledWith(ctx, expect.any(Function)); expect(applyPendingMigrations).toHaveBeenCalledWith(pool, { migrationsFolder: path.join(ctx.root, "config/database/migrations"), schemaName: "app", }); expect(report.applied).toEqual(["0000_migration"]); expect(report.notApplied).toBeUndefined(); - expect(pool.end).toHaveBeenCalledOnce(); expect(fs.readFileSync(report.typesFile, "utf-8")).toContain("notes"); }); test("applies committed migrations even when schema.ts did not change", async () => { const ctx = app(`notes: table("notes", { id: id() })`); - openBranchPool.mockResolvedValue(null); + resolveEnvBranch.mockResolvedValue(null); await runMigrate(ctx, { interactive: false }); - openBranchPool.mockResolvedValue(pool); + resolveEnvBranch.mockResolvedValue(devBranch); applyPendingMigrations.mockResolvedValue({ applied: ["0000_migration"], adopted: [], @@ -147,44 +150,43 @@ describe("runMigrate", () => { test("without a configured branch it still generates, and says why nothing was applied", async () => { const ctx = app(`notes: table("notes", { id: id() })`); - checkAppkitBranch.mockResolvedValue(null); + resolveEnvBranch.mockResolvedValue(null); const report = await runMigrate(ctx, { interactive: false }); expect(report.generated?.tag).toBe("0000_migration"); expect(applyPendingMigrations).not.toHaveBeenCalled(); - expect(report.notApplied).toMatch(/appkit db init/); + expect(report.notApplied).toBe( + "no branch is configured in .env (PGHOST, PGDATABASE and LAKEBASE_ENDPOINT); run `appkit db init`", + ); expect(fs.existsSync(report.typesFile)).toBe(true); }); test("on a branch AppKit did not create for you it generates, never connects, and says why", async () => { const ctx = app(`notes: table("notes", { id: id() })`); - checkAppkitBranch.mockResolvedValue({ + resolveEnvBranch.mockResolvedValue({ branch: { name: "projects/p/branches/production" }, - verdict: { - appkitOwned: false, - reason: "it is the project's default branch", - }, + kind: "default", + reason: "it is the project's default branch", }); const report = await runMigrate(ctx, { interactive: false }); expect(report.generated?.tag).toBe("0000_migration"); - expect(openBranchPool).not.toHaveBeenCalled(); + expect(withBranchPool).not.toHaveBeenCalled(); expect(applyPendingMigrations).not.toHaveBeenCalled(); expect(report.notApplied).toBe( - "production is not an AppKit dev or session branch (it is the project's default branch). Migrations are applied only to branches `appkit db init` created for you; the deployed app applies committed migrations to its own branch", + "production is not your dev or session branch (it is the project's default branch). Migrations are applied only to branches `appkit db init` created for you; the deployed app applies committed migrations to its own branch", ); expect(fs.existsSync(report.typesFile)).toBe(true); }); test("reports a baseline adopted without running it", async () => { const ctx = app(`notes: table("notes", { id: id() })`); - checkAppkitBranch.mockResolvedValue(null); + resolveEnvBranch.mockResolvedValue(null); await runMigrate(ctx, { interactive: false }); - checkAppkitBranch.mockResolvedValue(devBranch); - openBranchPool.mockResolvedValue(pool); + resolveEnvBranch.mockResolvedValue(devBranch); applyPendingMigrations.mockResolvedValue({ applied: [], adopted: ["0000_baseline"], @@ -194,9 +196,8 @@ describe("runMigrate", () => { expect(report).toMatchObject({ applied: [], adopted: ["0000_baseline"] }); }); - test("an apply failure ends the pool and says the generated migration was written but not applied", async () => { + test("an apply failure says the generated migration was written but not applied", async () => { const ctx = app(`notes: table("notes", { id: id() })`); - openBranchPool.mockResolvedValue(pool); const failure = new Error("apply failed"); applyPendingMigrations.mockRejectedValue(failure); @@ -208,7 +209,6 @@ describe("runMigrate", () => { `Wrote ${path.join("config/database/migrations", "0000_migration.sql")}, but did not apply it: apply failed`, ); expect(error.cause).toBe(failure); - expect(pool.end).toHaveBeenCalledOnce(); expect( fs.existsSync( path.join(ctx.root, "config/database/migrations/0000_migration.sql"), @@ -224,7 +224,7 @@ describe("runMigrate", () => { test("when the migration this run wrote fails to apply, it is removed so a fix in schema.ts can replace it", async () => { const ctx = app(`notes: table("notes", { id: id() })`); - checkAppkitBranch.mockResolvedValue(null); + resolveEnvBranch.mockResolvedValue(null); await runMigrate(ctx, { interactive: false }); const folder = path.join(ctx.root, "config/database/migrations"); const journal = fs.readFileSync( @@ -236,8 +236,7 @@ describe("runMigrate", () => { ctx.root, `notes: table("notes", { id: id(), title: text().notNull() })`, ); - checkAppkitBranch.mockResolvedValue(devBranch); - openBranchPool.mockResolvedValue(pool); + resolveEnvBranch.mockResolvedValue(devBranch); const failure = new MigrationApplyError({ step: "Applying migrations", failed: "0001_migration", @@ -268,12 +267,11 @@ describe("runMigrate", () => { test("when an earlier migration fails, the one this run wrote stays for the next try", async () => { const ctx = app(`notes: table("notes", { id: id() })`); - checkAppkitBranch.mockResolvedValue(null); + resolveEnvBranch.mockResolvedValue(null); await runMigrate(ctx, { interactive: false }); writeSchema(ctx.root, `notes: table("notes", { id: id(), body: text() })`); - checkAppkitBranch.mockResolvedValue(devBranch); - openBranchPool.mockResolvedValue(pool); + resolveEnvBranch.mockResolvedValue(devBranch); applyPendingMigrations.mockRejectedValue( new MigrationApplyError({ step: "Applying migrations", @@ -295,23 +293,22 @@ describe("runMigrate", () => { test("a guard failure after generating says so too, and never connects", async () => { const ctx = app(`notes: table("notes", { id: id() })`); - checkAppkitBranch.mockRejectedValue( + resolveEnvBranch.mockRejectedValue( new Error("The .env branch projects/p/branches/dev-a does not exist"), ); await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( /^Wrote .*0000_migration\.sql, but did not apply it: The \.env branch .* does not exist$/, ); - expect(openBranchPool).not.toHaveBeenCalled(); + expect(withBranchPool).not.toHaveBeenCalled(); }); test("a failure with nothing generated propagates unchanged", async () => { const ctx = app(`notes: table("notes", { id: id() })`); - checkAppkitBranch.mockResolvedValue(null); + resolveEnvBranch.mockResolvedValue(null); await runMigrate(ctx, { interactive: false }); - checkAppkitBranch.mockResolvedValue(devBranch); - openBranchPool.mockResolvedValue(pool); + resolveEnvBranch.mockResolvedValue(devBranch); const failure = new Error("apply failed"); applyPendingMigrations.mockRejectedValue(failure); @@ -327,6 +324,6 @@ describe("runMigrate", () => { expect(error.message).toBe("Could not load config/database/schema.ts."); expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); - expect(checkAppkitBranch).not.toHaveBeenCalled(); + expect(resolveEnvBranch).not.toHaveBeenCalled(); }); }); From 96b93812cb2261497b64a1a06e28f8220cdad32b Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 19 Oct 2026 15:11:20 +0200 Subject: [PATCH 008/317] feat(appkit): warn when appkit db migrate writes a migration that breaks the previous release Apps keeps instances of the previous release serving while the new one migrates on start, and a code rollback cannot undo a migration. When the generated migration drops, renames, retypes or makes a column NOT NULL, the report lists those statements and the CLI says to ship code that works with both schemas first. Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrate.ts | 11 +++++++- .../appkit/src/database/tooling/migrations.ts | 21 +++++++++++++++ .../database/tooling/tests/migrate.test.ts | 15 +++++++++++ .../database/tooling/tests/migrations.test.ts | 27 +++++++++++++++++++ .../src/cli/commands/db/migrate.test.ts | 23 ++++++++++++++++ packages/shared/src/cli/commands/db/output.ts | 6 +++++ .../src/cli/commands/db/tooling-contract.ts | 1 + 7 files changed, 103 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index dbcb41a7d..ec2343450 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -21,6 +21,7 @@ import { import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context"; import { notYourBranch, resolveEnvBranch, takesWrites } from "./guard"; import { + breakingStatements, discardMigrationFiles, type GeneratedMigration, generateMigrationFiles, @@ -56,6 +57,8 @@ export interface MigrateReport { readonly applied: readonly string[]; /** Tags recorded without running because their tables already existed (0000_baseline). */ readonly adopted?: readonly string[]; + /** Statements of the generated migration that break instances still running the previous release. */ + readonly breaking?: readonly string[]; /** Why nothing was applied, when applying was skipped. */ readonly notApplied?: string; readonly typesFile: string; @@ -144,5 +147,11 @@ export async function runMigrate( { cause: error }, ); } - return { generated, ...outcome, typesFile }; + const breaking = breakingStatements(generated?.statements ?? []); + return { + generated, + ...(breaking.length > 0 ? { breaking } : {}), + ...outcome, + typesFile, + }; } diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 21ada21bd..81786a253 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -253,6 +253,27 @@ async function loadDrizzleKit(): Promise { } } +const BREAKS_PREVIOUS_RELEASE = [ + /^DROP (TABLE|VIEW|MATERIALIZED VIEW|TYPE|SEQUENCE|SCHEMA)\b/i, + /\bDROP COLUMN\b/i, + /\bRENAME\b/i, + /\bSET DATA TYPE\b/i, + /\bSET NOT NULL\b/i, +]; + +/** + * Statements that break instances still running the previous release. Apps + * keeps them serving while the new instance migrates on start, and a code + * rollback cannot undo a migration. + */ +export function breakingStatements(statements: readonly string[]): string[] { + return statements.filter((statement) => + BREAKS_PREVIOUS_RELEASE.some((pattern) => + pattern.test(statement.trimStart()), + ), + ); +} + /** Replace a file through a rename, so a crash never leaves it half written. */ function writeFileAtomic(file: string, content: string): void { const temporary = path.join( diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index dd88e8e33..15056e199 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -129,6 +129,7 @@ describe("runMigrate", () => { }); expect(report.applied).toEqual(["0000_migration"]); expect(report.notApplied).toBeUndefined(); + expect(report.breaking).toBeUndefined(); expect(fs.readFileSync(report.typesFile, "utf-8")).toContain("notes"); }); @@ -326,4 +327,18 @@ describe("runMigrate", () => { expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); expect(resolveEnvBranch).not.toHaveBeenCalled(); }); + + test("reports the statements that break instances of the previous release", async () => { + const ctx = app(`notes: table("notes", { id: id(), body: text() })`); + resolveEnvBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + + writeSchema(ctx.root, `notes: table("notes", { id: id() })`); + const report = await runMigrate(ctx, { interactive: false }); + + expect(report.generated?.statements).toEqual([ + 'ALTER TABLE "app"."notes" DROP COLUMN "body";', + ]); + expect(report.breaking).toEqual(report.generated?.statements); + }); }); diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index 79ed30f2e..edfdf0fb8 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -19,6 +19,7 @@ import { varchar, } from "../../schema-builder"; import { + breakingStatements, discardMigrationFiles, generateMigrationFiles, MigrationRenameAmbiguityError, @@ -343,6 +344,32 @@ describe("generateMigrationFiles", () => { }); }); +describe("breakingStatements", () => { + test("drops, renames, type changes and new NOT NULLs; additions and relaxations pass", () => { + const breaking = [ + 'DROP TABLE "app"."tags" CASCADE;', + 'ALTER TABLE "app"."notes" DROP COLUMN "body";', + 'ALTER TABLE "app"."notes" RENAME COLUMN "body" TO "text";', + 'ALTER TABLE "app"."notes" RENAME TO "posts";', + 'ALTER TABLE "app"."notes" ALTER COLUMN "n" SET DATA TYPE bigint;', + 'ALTER TABLE "app"."notes" ALTER COLUMN "title" SET NOT NULL;', + 'DROP TYPE "app"."mood";', + `ALTER TYPE "app"."mood" RENAME VALUE 'sad' TO 'blue';`, + ]; + const safe = [ + 'CREATE TABLE "app"."tags" ("id" serial PRIMARY KEY);', + 'ALTER TABLE "app"."notes" ADD COLUMN "title" text;', + 'ALTER TABLE "app"."notes" ALTER COLUMN "title" DROP NOT NULL;', + 'ALTER TABLE "app"."notes" ALTER COLUMN "title" DROP DEFAULT;', + 'ALTER TABLE "app"."notes" DROP CONSTRAINT "notes_tag_fk";', + 'DROP INDEX "app"."notes_title_idx";', + `ALTER TYPE "app"."mood" ADD VALUE 'calm';`, + ]; + + expect(breakingStatements([...safe, ...breaking])).toEqual(breaking); + }); +}); + describe("discardMigrationFiles", () => { test("a first migration goes with the folders it created", async () => { const folder = tempFolder(); diff --git a/packages/shared/src/cli/commands/db/migrate.test.ts b/packages/shared/src/cli/commands/db/migrate.test.ts index 1640b5223..d1fe7cd8c 100644 --- a/packages/shared/src/cli/commands/db/migrate.test.ts +++ b/packages/shared/src/cli/commands/db/migrate.test.ts @@ -112,6 +112,29 @@ describe("appkit db migrate", () => { expect(printed).toContain("Applied 0001_migration to the .env branch"); }); + test("warns when the migration breaks instances of the previous release", async () => { + const drop = 'ALTER TABLE "app"."notes" DROP COLUMN "body";'; + runMigrate.mockResolvedValue({ + generated: { + tag: "0002_migration", + file: path.join( + process.cwd(), + "config/database/migrations/0002_migration.sql", + ), + statements: [drop], + }, + breaking: [drop], + applied: ["0002_migration"], + typesFile, + }); + + await dbCommand.parseAsync(["migrate"], { from: "user" }); + + expect(output(log)).toContain( + `0002_migration breaks instances still running the previous release, which keep serving while the new one migrates on start: ${drop} Deploy code that works with both the old and the new schema first, then this change in a later deploy.`, + ); + }); + test("says why nothing was applied", async () => { runMigrate.mockResolvedValue({ generated: null, diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index ec652b74a..f3dc540a4 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -51,6 +51,12 @@ export function printMigrateReport(report: MigrateReport): void { } else { info("No schema changes since the last migration"); } + if (report.generated && report.breaking?.length) { + warn( + `${report.generated.tag} breaks instances still running the previous release, which keep serving while the new one migrates on start: ${report.breaking.join(" ")} ` + + "Deploy code that works with both the old and the new schema first, then this change in a later deploy.", + ); + } if (report.adopted?.length) { ok( diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index c8eea40b3..06e73e359 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -14,6 +14,7 @@ export interface MigrateReport { readonly generated: GeneratedMigration | null; readonly applied: readonly string[]; readonly adopted?: readonly string[]; + readonly breaking?: readonly string[]; readonly notApplied?: string; readonly typesFile: string; } From 0d1dfaf8349a76637ba3248867fb4b0c090c45fd Mon Sep 17 00:00:00 2001 From: ditadi Date: Tue, 20 Oct 2026 13:16:16 +0200 Subject: [PATCH 009/317] refactor(appkit): run the database tooling on the modular workspace client Signed-off-by: ditadi --- .../appkit/src/database/tooling/context.ts | 27 ++++--- .../appkit/src/database/tooling/identity.ts | 2 +- .../src/database/tooling/lakebase-api.ts | 31 ++++++-- .../database/tooling/tests/context.test.ts | 10 ++- .../src/database/tooling/tests/fakes.ts | 6 +- .../database/tooling/tests/identity.test.ts | 5 +- .../tooling/tests/lakebase-api.test.ts | 70 +++++++++++++------ 7 files changed, 98 insertions(+), 53 deletions(-) diff --git a/packages/appkit/src/database/tooling/context.ts b/packages/appkit/src/database/tooling/context.ts index 76d95f25e..b417297da 100644 --- a/packages/appkit/src/database/tooling/context.ts +++ b/packages/appkit/src/database/tooling/context.ts @@ -4,28 +4,30 @@ 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 } from "../../workspace-client"; +import { + createWorkspaceClient, + type WorkspaceRequest, +} from "../../workspace-client"; import { currentIdentity } from "./identity"; import { LakebaseApi, type LakebaseEndpoint } from "./lakebase-api"; -/** One REST call through the SDK's unified-auth client. */ +/** One Lakebase REST call, before LakebaseApi encodes it as a workspace request. */ export interface ToolingRequest { path: string; method: "GET" | "POST" | "PATCH" | "DELETE"; query?: Record; - headers: Headers; - raw: boolean; payload?: unknown; } /** - * The slice of the SDK client the tooling uses. It is also everything the - * Lakebase pool needs: token refresh calls `apiClient.request` and the user - * lookup calls `currentUser.me`. + * 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 { - readonly apiClient: { request(options: ToolingRequest): Promise }; - readonly currentUser: { me(): Promise<{ userName?: string }> }; + request(request: WorkspaceRequest): Promise; + readonly currentUser: { + me(request: { attributes?: string }): Promise<{ userName?: string }>; + }; } /** Where a command runs: the app root, its environment and its Databricks identity. */ @@ -54,7 +56,7 @@ export function createDbContext( client = createWorkspaceClient({ ...(profile ? { profile } : {}), clientOptions: getClientOptions(), - }).toLegacyWorkspaceClient(); + }); } return client; }, @@ -128,10 +130,7 @@ async function openBranchPool(ctx: DbContext): Promise { user, ...(port ? { port } : {}), ...(sslMode ? { sslMode } : {}), - // Only apiClient.request and currentUser.me are used (see ToolingWorkspaceClient). - workspaceClient: ctx.workspace() as unknown as NonNullable< - LakebasePoolConfig["workspaceClient"] - >, + workspaceClient: ctx.workspace(), // One-shot CLI pools: a small cap, and no lingering idle connections. max: 2, idleTimeoutMillis: 1_000, diff --git a/packages/appkit/src/database/tooling/identity.ts b/packages/appkit/src/database/tooling/identity.ts index 3b539abc6..e457c79a2 100644 --- a/packages/appkit/src/database/tooling/identity.ts +++ b/packages/appkit/src/database/tooling/identity.ts @@ -13,7 +13,7 @@ export function currentIdentity(ctx: DbContext): Promise { if (!identity) { identity = ctx .workspace() - .currentUser.me() + .currentUser.me({}) .then(({ userName }) => { if (!userName) { throw new Error( diff --git a/packages/appkit/src/database/tooling/lakebase-api.ts b/packages/appkit/src/database/tooling/lakebase-api.ts index a460846a1..e020e28ca 100644 --- a/packages/appkit/src/database/tooling/lakebase-api.ts +++ b/packages/appkit/src/database/tooling/lakebase-api.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import type { ToolingRequest, ToolingWorkspaceClient } from "./context"; -// Lakebase Postgres REST API through the SDK's unified-auth client. Paths, +// 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 { @@ -74,9 +74,19 @@ 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; +} + export class LakebaseApi { constructor( - private readonly client: Pick, + private readonly client: Pick, ) {} getBranch(name: string): Promise { @@ -104,18 +114,25 @@ export class LakebaseApi { private async call( operation: string, - request: Omit, + request: ToolingRequest, ): Promise { const headers = new Headers({ Accept: "application/json" }); if (request.payload !== undefined) { headers.set("Content-Type", "application/json"); } try { - return (await this.client.apiClient.request({ - ...request, + const response = await this.client.request({ + method: request.method, + path: request.path, + query: encodeQuery(request.query), headers, - raw: false, - })) as T; + body: + request.payload === undefined + ? undefined + : JSON.stringify(request.payload), + }); + const text = await response.text(); + return (text ? JSON.parse(text) : {}) as T; } catch (error) { throw new LakebaseApiError(operation, messageOf(error), { statusCode: statusCodeOf(error), diff --git a/packages/appkit/src/database/tooling/tests/context.test.ts b/packages/appkit/src/database/tooling/tests/context.test.ts index df06855ea..3b57978aa 100644 --- a/packages/appkit/src/database/tooling/tests/context.test.ts +++ b/packages/appkit/src/database/tooling/tests/context.test.ts @@ -174,17 +174,15 @@ describe("withBranchPool", () => { describe("createDbContext", () => { test("the workspace client uses the .env profile and AppKit's client options, once", () => { - const legacy = { apiClient: {}, currentUser: {} }; - createWorkspaceClient.mockReturnValue({ - toLegacyWorkspaceClient: () => legacy, - }); + const client = { request: vi.fn(), currentUser: {} }; + createWorkspaceClient.mockReturnValue(client); const ctx = createDbContext({ root: tempApp(), env: { DATABRICKS_CONFIG_PROFILE: "dev" }, }); - expect(ctx.workspace()).toBe(legacy); - expect(ctx.workspace()).toBe(legacy); + expect(ctx.workspace()).toBe(client); + expect(ctx.workspace()).toBe(client); expect(createWorkspaceClient).toHaveBeenCalledOnce(); expect(createWorkspaceClient).toHaveBeenCalledWith({ profile: "dev", diff --git a/packages/appkit/src/database/tooling/tests/fakes.ts b/packages/appkit/src/database/tooling/tests/fakes.ts index c10e139af..ceaf6006a 100644 --- a/packages/appkit/src/database/tooling/tests/fakes.ts +++ b/packages/appkit/src/database/tooling/tests/fakes.ts @@ -84,10 +84,8 @@ export function fakeContext(options: { root: options.root, env: { ...options.env }, workspace: () => ({ - apiClient: { - request: async () => { - throw new Error("no raw API calls expected"); - }, + request: async () => { + throw new Error("no raw API calls expected"); }, currentUser: { me: async () => ({ userName }) }, }), diff --git a/packages/appkit/src/database/tooling/tests/identity.test.ts b/packages/appkit/src/database/tooling/tests/identity.test.ts index d600a844b..cc49fcc56 100644 --- a/packages/appkit/src/database/tooling/tests/identity.test.ts +++ b/packages/appkit/src/database/tooling/tests/identity.test.ts @@ -8,7 +8,9 @@ afterEach(cleanupTempApps); describe("identity", () => { test("currentUser.me() is called once per context", async () => { const ctx = fakeContext({ root: tempApp() }); - const me = vi.fn(async () => ({ userName: "alice@example.com" })); + const me = vi.fn(async (_request: object) => ({ + userName: "alice@example.com", + })); const client = { ...ctx.workspace(), currentUser: { me } }; const counted = { ...ctx, workspace: () => client }; @@ -17,6 +19,7 @@ describe("identity", () => { }); await currentIdentity(counted); expect(me).toHaveBeenCalledOnce(); + expect(me).toHaveBeenCalledWith({}); }); test("no userName is an error that points at the profile", async () => { diff --git a/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts index 75d8a85e2..139ee959a 100644 --- a/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts +++ b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts @@ -1,30 +1,45 @@ import { describe, expect, test } from "vitest"; -import type { ToolingRequest } from "../context"; +import type { WorkspaceRequest } from "../../../workspace-client"; import { LakebaseApi, LakebaseApiError } from "../lakebase-api"; -type Reply = unknown | ((request: ToolingRequest) => unknown); +/** A request as LakebaseApi sent it, with its JSON body decoded. */ +interface Sent { + method: string; + path: string; + query?: Record; + headers: Headers; + payload?: unknown; +} + +type Reply = unknown | ((request: Sent) => unknown); -/** apiClient fake: replies in order, records each request. */ +/** Workspace client fake: replies in order with JSON, records each request. */ function client(replies: Reply[]) { - const requests: ToolingRequest[] = []; + const requests: Sent[] = []; return { requests, - apiClient: { - async request(request: ToolingRequest) { - requests.push(request); - if (replies.length === 0) - throw new Error( - `unexpected request ${request.method} ${request.path}`, - ); - const reply = replies.shift(); - const value = - typeof reply === "function" - ? (reply as (r: ToolingRequest) => unknown)(request) - : reply; - if (value instanceof Error) throw value; - return value; - }, + async request(request: WorkspaceRequest): Promise { + const sent: Sent = { + method: request.method, + path: request.path, + query: request.query, + headers: new Headers(request.headers), + payload: + typeof request.body === "string" + ? JSON.parse(request.body) + : undefined, + }; + requests.push(sent); + if (replies.length === 0) + throw new Error(`unexpected request ${sent.method} ${sent.path}`); + const reply = replies.shift(); + const value = + typeof reply === "function" + ? (reply as (r: Sent) => unknown)(sent) + : reply; + if (value instanceof Error) throw value; + return new Response(value === undefined ? null : JSON.stringify(value)); }, }; } @@ -63,12 +78,27 @@ describe("LakebaseApi", () => { expect(fake.requests[0]).toMatchObject({ path: "/api/2.0/postgres/projects/p/branches/b", method: "GET", - raw: false, }); + expect(fake.requests[0]?.query).toBeUndefined(); + expect(fake.requests[0]?.payload).toBeUndefined(); expect(fake.requests[0]?.headers.get("Accept")).toBe("application/json"); expect(fake.requests[0]?.headers.get("Content-Type")).toBeNull(); }); + test("a request that fails before a status keeps its message and has no status", async () => { + const api = new LakebaseApi(client([new Error("socket hang up")])); + + const error = await api + .getBranch("projects/p/branches/b") + .catch((e: unknown) => e); + expect(error).toBeInstanceOf(LakebaseApiError); + expect(error).toMatchObject({ + message: + "Lakebase: get branch projects/p/branches/b failed: socket hang up", + statusCode: undefined, + }); + }); + test("getEndpoint: GET /api/2.0/postgres/{name}; 404 → null", async () => { const endpoint = { name: "projects/p/branches/b/endpoints/primary", From a45e7df75df1d654668d15f04a340ddf9917f453 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 12 Oct 2026 13:36:54 +0100 Subject: [PATCH 010/317] feat(appkit): add appkit db introspect `appkit db introspect` reads an existing Postgres schema (default: app) from pg_catalog and writes config/database/schema.ts from it, keeping the previous file as schema.ts.bak. It also writes the migration that brings history up to the database, 0000_baseline first and NNNN_introspect after, and records it as applied. That is only true on the branch it read, so it runs only on the developer's dev or session branch, which `appkit db init` creates. The deployed app adopts 0000_baseline on start when its tables already exist. What the schema builder cannot express is skipped and reported, and what it declares differently from the database (a timestamp precision, an index) is listed. Objects it does not read (views, triggers, policies, functions, standalone sequences) are named in a warning, since a database the migrations create will not have them. It refuses when the branch's journal and the checkout's migrations differ, and it refuses a migration that drops something schema.ts left out, since the deployed app runs that migration on start. Recording takes the migration lock and checks the journal again, and a run interrupted before recording is finished by the next one. If anything fails after schema.ts is written, schema.ts, its backup, database.d.ts and the migrations are put back. Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 120 ++- .../migrations/tests/apply.pg.test.ts | 129 +++ .../database/schema-builder/define-schema.ts | 26 +- packages/appkit/src/database/tooling/index.ts | 5 + .../database/tooling/introspect/catalog.ts | 322 +++++++ .../src/database/tooling/introspect/index.ts | 315 +++++++ .../src/database/tooling/introspect/render.ts | 864 ++++++++++++++++++ .../introspect/tests/catalog.pg.test.ts | 147 +++ .../tooling/introspect/tests/catalog.test.ts | 136 +++ .../tooling/introspect/tests/fixture.ts | 293 ++++++ .../tests/golden/rich.schema.ts.txt | 51 ++ .../introspect/tests/introspect.test.ts | 741 +++++++++++++++ .../tooling/introspect/tests/render.test.ts | 623 +++++++++++++ .../introspect/tests/roundtrip.test.ts | 368 ++++++++ .../appkit/src/database/tooling/migrate.ts | 2 +- .../appkit/src/database/tooling/migrations.ts | 18 +- .../database/tooling/tests/contract.test.ts | 1 + .../database/tooling/tests/migrations.test.ts | 70 ++ packages/shared/src/cli/commands/db/index.ts | 4 +- .../src/cli/commands/db/introspect.test.ts | 171 ++++ .../shared/src/cli/commands/db/introspect.ts | 43 + packages/shared/src/cli/commands/db/output.ts | 48 +- .../src/cli/commands/db/tooling-contract.ts | 24 + 23 files changed, 4510 insertions(+), 11 deletions(-) create mode 100644 packages/appkit/src/database/tooling/introspect/catalog.ts create mode 100644 packages/appkit/src/database/tooling/introspect/index.ts create mode 100644 packages/appkit/src/database/tooling/introspect/render.ts create mode 100644 packages/appkit/src/database/tooling/introspect/tests/catalog.pg.test.ts create mode 100644 packages/appkit/src/database/tooling/introspect/tests/catalog.test.ts create mode 100644 packages/appkit/src/database/tooling/introspect/tests/fixture.ts create mode 100644 packages/appkit/src/database/tooling/introspect/tests/golden/rich.schema.ts.txt create mode 100644 packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts create mode 100644 packages/appkit/src/database/tooling/introspect/tests/render.test.ts create mode 100644 packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts create mode 100644 packages/shared/src/cli/commands/db/introspect.test.ts create mode 100644 packages/shared/src/cli/commands/db/introspect.ts diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index c8e5f9c3f..b9f528640 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -147,7 +147,7 @@ export class MigrationBaselineMismatchError extends Error { 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 against this database.", + "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]); @@ -575,6 +575,124 @@ function duration(ms: number): string { 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 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), + 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, +): Promise { + return driftOf( + reconcileMigrations( + committedMigrations(options.migrationsFolder), + await readRecordedMigrations(client, options.schemaName), + ), + ); +} + +/** 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(", ")}` : "", + 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. * diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts index 7e4875576..c3b2d7b99 100644 --- a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -16,8 +16,11 @@ import { applyPendingMigrations, MigrationApplyError, MigrationHistoryError, + markMigrationsApplied, migrationLockKey, + readMigrationDrift, } from "../apply"; +import { MigrationFilesError } from "../paths"; import { hashOf, removeMigrationFolders, writeMigrations } from "./fixtures"; // A real server, for what a fake cannot show: transactions, enum rules, locks @@ -405,4 +408,130 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { }); 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 and recorded ones the checkout lacks", async () => { + const folder = withTags(); + expect(await readMigrationDrift(newPool(), options(folder))).toEqual({ + pending: ["0000_notes", "0001_introspect"], + stranded: [], + unknown: 0, + }); + + await aheadOfCheckout(folder); + + expect(await readMigrationDrift(newPool(), options(folder))).toEqual({ + pending: ["0001_introspect"], + stranded: [], + 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", + ], + ])( + "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/schema-builder/define-schema.ts b/packages/appkit/src/database/schema-builder/define-schema.ts index 5d8cf3d91..8d8038d08 100644 --- a/packages/appkit/src/database/schema-builder/define-schema.ts +++ b/packages/appkit/src/database/schema-builder/define-schema.ts @@ -72,9 +72,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 +138,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`, ); @@ -344,7 +362,7 @@ export function assertFinalizedSchema(value: unknown): asserts value is Schema { * the deployed app's service principal can create and own a schema of its * own, but has no CREATE on `public`. */ -const DEFAULT_SCHEMA_NAME = "app"; +export const DEFAULT_SCHEMA_NAME = "app"; /** * Compile one declared schema. The returned type keeps the table names the diff --git a/packages/appkit/src/database/tooling/index.ts b/packages/appkit/src/database/tooling/index.ts index bbec5337a..29adba529 100644 --- a/packages/appkit/src/database/tooling/index.ts +++ b/packages/appkit/src/database/tooling/index.ts @@ -7,4 +7,9 @@ * the same AppKit release should import it. */ export { createDbContext, type DbContext } from "./context"; +export { + type IntrospectOptions, + type IntrospectReport, + runIntrospect, +} from "./introspect"; export { type MigrateOptions, type MigrateReport, runMigrate } from "./migrate"; 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..07703b0aa --- /dev/null +++ b/packages/appkit/src/database/tooling/introspect/catalog.ts @@ -0,0 +1,322 @@ +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[]; +} + +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; +} + +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[]; +} + +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; +} + +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 + 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 + 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 ?? [], + }, + } + : {}), + }; +} + +/** 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 })), + 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..66ce9bd7d --- /dev/null +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -0,0 +1,315 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { + DEFAULT_SCHEMA_FILE, + loadDefaultDatabaseSchema, +} from "../../../plugins/database/load-schema"; +import { writeDatabaseTypes } from "../../../type-generator/database"; +import { + markMigrationsApplied, + readMigrationDrift, +} from "../../migrations/apply"; +import { + journalFile, + migrationsFolder, + readJournal, +} from "../../migrations/paths"; +import { DEFAULT_SCHEMA_NAME } from "../../schema-builder/define-schema"; +import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "../context"; +import { notYourBranch, resolveEnvBranch, takesWrites } from "../guard"; +import { DATABASE_TYPES_PATH } from "../migrate"; +import { + breakingStatements, + discardMigrationFiles, + type GeneratedMigration, + generateMigrationFiles, +} from "../migrations"; +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; defaults to DEFAULT_SCHEMA_NAME. The current schema.ts is never read. */ + readonly schemaName?: string; + /** Module the written schema.ts imports the builder from. Default "@databricks/appkit/beta". */ + readonly importSource?: string; +} + +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; +} + +/** Introspect would record history the branch or the deployed app contradicts. */ +export class IntrospectRefusedError extends Error { + constructor(message: string) { + super(message); + this.name = "IntrospectRefusedError"; + } +} + +/** Tags introspect writes. Pending ones match the branch when a fresh render adds nothing. */ +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 fs.writeFileSync(file, contents); +} + +const plural = (count: number, word: string) => + `${count} ${word}${count === 1 ? "" : "s"}`; + +/** The statement drizzle-kit 0.31 writes to remove it. */ +function dropStatement(item: Unexpressed, schemaName: string): string { + // drizzle-kit leaves the public schema out of the name. + const named = + schemaName === "public" + ? `"${item.name}"` + : `"${schemaName}"."${item.name}"`; + switch (item.kind) { + case "table": + return `DROP TABLE ${named} CASCADE;`; + case "column": + return `ALTER TABLE ${named} DROP COLUMN "${item.member}";`; + case "default": + return `ALTER TABLE ${named} ALTER COLUMN "${item.member}" DROP DEFAULT;`; + case "constraint": + return `ALTER TABLE ${named} DROP CONSTRAINT "${item.member}";`; + case "type": + return `DROP TYPE ${named};`; + } +} + +/** + * 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( + statements: readonly string[], + unexpressed: readonly Unexpressed[], + schemaName: string, +): void { + const reasons = new Map( + unexpressed.map((item) => [dropStatement(item, schemaName), item.reason]), + ); + const refused = statements + .map((statement) => statement.trim()) + .filter((statement) => reasons.has(statement)); + 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( + (statement) => + `${shown(statement)} (${shown(reasons.get(statement) ?? "")})`, + ) + .join( + " ", + )}. The deployed app would run ${refused.length === 1 ? "it" : "them"} on start.`, + ); +} + +/** + * `appkit db introspect`: read the `.env` branch's app schema from pg_catalog, + * 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. + * 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, + * database.d.ts and the migrations folder. + */ +export async function runIntrospect( + ctx: DbContext, + options: IntrospectOptions, +): Promise { + const schemaFile = path.join(ctx.root, DEFAULT_SCHEMA_FILE); + // Introspect replaces schema.ts, so the current file (missing, empty or broken) is never read. + const schemaName = options.schemaName || DEFAULT_SCHEMA_NAME; + const folder = migrationsFolder(ctx.root); + 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 project's default branch, and introspects it when there is no ${DEFAULT_SCHEMA_FILE}.`, + ); + } + const branchId = resourceId(env.branch.name); + + return withBranchPool(ctx, async (pool) => { + // The diff starts from the latest committed snapshot, so the branch must + // record exactly the committed migrations: one it lacks would come out + // reversed, and one the checkout lacks would come out again. + const drift = await readMigrationDrift(pool, migrationOptions); + 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.", + ); + } + // 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, + }); + // 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 typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); + const previous = readIfExists(schemaFile); + const previousBackup = readIfExists(backupFile); + const previousTypes = readIfExists(typesFile); + const backsUp = previous !== null && previous !== rendered.source; + const journalBefore = readIfExists(journalFile(folder)); + let migration: GeneratedMigration | null = null; + let recorded: string[] = []; + try { + if (backsUp) fs.writeFileSync(backupFile, previous); + fs.mkdirSync(path.dirname(schemaFile), { recursive: true }); + fs.writeFileSync(schemaFile, rendered.source); + let schema: Awaited>; + try { + schema = await loadDefaultDatabaseSchema(ctx.root, { + 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({ + folder, + schema, + tag: hasHistory ? "introspect" : "baseline", + interactive: options.interactive, + ...(hasHistory + ? { + beforeWrite: (statements: readonly string[]) => + refuseDropsOfUnexpressed( + statements, + rendered.unexpressed, + schemaName, + ), + } + : {}), + }); + if (unrecorded.length > 0 && migration) { + throw notApplied( + `Its tables differ from what ${unrecorded.length === 1 ? "it describes" : "they describe"}.`, + ); + } + await writeDatabaseTypes(schema, typesFile); + // The database already holds what the migrations describe; recording is the last step. + recorded = [...unrecorded, ...(migration ? [migration.tag] : [])]; + if (recorded.length > 0) { + await markMigrationsApplied(pool, migrationOptions, recorded); + } + } catch (error) { + writeOrRemove(schemaFile, previous); + if (backsUp) writeOrRemove(backupFile, previousBackup); + writeOrRemove(typesFile, previousTypes); + if (migration) discardMigrationFiles(folder, migration, journalBefore); + 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.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, + }; + }); +} 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..b8378f5e5 --- /dev/null +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -0,0 +1,864 @@ +import { + DEFAULT_SCHEMA_NAME, + isReservedColumnName, + isReservedTableName, +} from "../../schema-builder/define-schema"; +import type { + IntrospectedColumn, + IntrospectedForeignKey, + 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, by raw catalog name. A + * migration that drops it must not be recorded as applied: the branch keeps it. + */ +export interface Unexpressed { + readonly kind: "table" | "column" | "default" | "constraint" | "type"; + /** The table, or the enum type for "type". */ + readonly name: string; + /** The column for "column" and "default", the constraint for "constraint". */ + readonly member?: string; + 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 the API 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; +} + +/** 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 = + /[\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)}]`; +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`; + } + 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); + +/** 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 = /^'((?:[^']|'')*)'(?:::[\w." ]+)?$/.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)};`; +} + +function makeSkip( + table: string, + column: string | undefined, + reason: string, +): Skip { + return { + table: shown(table), + ...(column === undefined ? {} : { column: shown(column) }), + reason: shown(reason), + }; +} + +function skipComment(skip: Skip): string { + return `// appkit: skipped ${skip.column ? `column "${skip.column}"` : `table "${skip.table}"`}: ${skip.reason}`; +} + +/** 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; what it declares differently (a timestamp without its precision, + * say) is listed in `approximated`. + */ +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}` : ""}`; + const skipTable = (table: string, reason: string) => { + const skip = makeSkip(table, undefined, reason); + skipped.push(skip); + unexpressed.push({ kind: "table", name: table, reason }); + tableComments.push(skipComment(skip)); + }; + + // 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]; + const tableSkips: Skip[] = []; + const tableWarnings: string[] = []; + const tableApproximated: string[] = []; + const tableRenamed: string[] = []; + const columnReasons = new Map(); + /** Single-column unique constraints: column → constraint name. */ + const singleUnique = new Map( + table.unique + .filter((unique) => unique.columns.length === 1) + .map((unique) => [unique.columns[0] as string, unique.name]), + ); + const tableUnexpressed: Unexpressed[] = []; + for (const unique of table.unique.filter((u) => u.columns.length > 1)) { + const reason = `unique constraint (${list(unique.columns)}) spans several columns, which is not supported`; + const skip = makeSkip(table.name, undefined, reason); + tableSkips.push(skip); + tableUnexpressed.push({ + kind: "constraint", + name: table.name, + member: unique.name, + reason, + }); + plan.comments.push(`// appkit: skipped ${skip.reason}`); + } + + for (const column of table.columns) { + const skipColumn = (reason: string) => { + const skip = makeSkip(table.name, column.name, reason); + tableSkips.push(skip); + tableUnexpressed.push({ + kind: "column", + name: table.name, + member: column.name, + reason, + }); + columnReasons.set(column.name, reason); + plan.body.push(skipComment(skip)); + const generatesValue = + column.identity !== "" || column.generated || !!column.defaultExpr; + if (column.notNull && !generatesValue) { + tableWarnings.push( + `${qualified(table.name, column.name)} is NOT NULL with no default but is not in schema.ts (${reason}). Inserts through the API will fail until it gets a default, becomes nullable, or is dropped.`, + ); + } + }; + + if (isReservedColumnName(column.name)) { + skipColumn(`the name "${column.name}" is reserved by AppKit`); + continue; + } + if (column.generated) { + skipColumn("generated columns are not supported"); + continue; + } + const base = baseType(column, schemaName); + if (typeof base === "string") { + skipColumn(base); + continue; + } + const isPrimaryKey = column.name === pk; + if (column.identity !== "" && !isPrimaryKey) { + skipColumn( + "identity columns other than the primary key are not supported", + ); + continue; + } + + const columnPlan: ColumnPlan = { + column, + base, + isPrimaryKey, + isUnique: singleUnique.has(column.name) && !isPrimaryKey, + comments: [], + }; + if (base.approximation) { + tableApproximated.push( + `${qualified(table.name, column.name)}: ${base.approximation}`, + ); + } + const uniqueName = singleUnique.get(column.name); + const migrationsUnique = pgName(`${table.name}_${column.name}_unique`); + if (columnPlan.isUnique && uniqueName !== migrationsUnique) { + tableRenamed.push(`${uniqueName} (${migrationsUnique})`); + } + 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(). + columnPlan.base = + base.storage === "integer" + ? { call: "id()", importName: "id", storage: "id" } + : { call: "bigid()", importName: "bigid", storage: "bigid" }; + if (column.identity !== "d") { + tableApproximated.push( + `${qualified(table.name, column.name)}: ${column.identity === "a" ? "GENERATED ALWAYS AS IDENTITY" : "a serial key"} is declared as ${columnPlan.base.call}, an identity generated BY DEFAULT`, + ); + } + } else if (column.defaultExpr) { + const parsed = defaultCall( + column.defaultExpr, + base, + column.enum?.values, + ); + if ("call" in parsed) { + columnPlan.defaultCall = parsed.call; + } else { + const skip = makeSkip(table.name, column.name, parsed.skip); + tableSkips.push(skip); + tableUnexpressed.push({ + kind: "default", + name: table.name, + member: column.name, + reason: parsed.skip, + }); + columnPlan.comments.push(`// appkit: skipped ${skip.reason}`); + if (column.notNull) { + tableWarnings.push( + `${qualified(table.name, column.name)}: its ${parsed.skip.replace(/ is not supported$/, "")} is not in schema.ts, so the API requires a value for it on insert.`, + ); + } + } + } + plan.columns.push(columnPlan); + plan.body.push(columnPlan); + } + + if (!plan.columns.some((c) => c.isPrimaryKey)) { + plans.delete(table.name); + skipTable( + table.name, + `its primary key column "${pk}" cannot be expressed (${columnReasons.get(pk as string) ?? "unsupported"})`, + ); + continue; + } + skipped.push(...tableSkips); + unexpressed.push(...tableUnexpressed); + warnings.push(...tableWarnings); + if (table.partitioned) { + tableApproximated.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) { + tableApproximated.push( + `${qualified(table.name)}: ${names.length === 1 ? `${one} ${names[0]} is` : `${many} ${list(names)} are`} not declared`, + ); + } + } + approximated.push(...tableApproximated); + renamed.push(...tableRenamed); + } + + // 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 (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(); + for (const foreignKey of plan.table.foreignKeys) { + const source = plan.columns.find( + (c) => c.column.name === foreignKey.columns[0], + ); + const problem = fkProblem(plan, foreignKey, source, targets); + if (problem) { + const reason = `foreign key to ${foreignKey.table}(${list(foreignKey.refColumns)}) is not kept: ${problem}`; + // Migrations name it after its column; a schema.ts that declared it gave it that name. + const constraintNames = [foreignKey.name]; + if (foreignKey.columns.length === 1) { + constraintNames.push( + pgName( + `${plan.table.name}_${foreignKey.columns[0]}_${foreignKey.table}_${foreignKey.refColumns[0]}_fk`, + ), + ); + } + for (const member of new Set(constraintNames)) { + unexpressed.push({ + kind: "constraint", + name: plan.table.name, + member, + reason, + }); + } + // A skipped column already carries its own comment. + if (source || foreignKey.columns.length > 1) { + const skip = makeSkip( + plan.table.name, + foreignKey.columns.join(", "), + reason, + ); + skipped.push(skip); + (source?.comments ?? plan.comments).push( + `// appkit: skipped ${skip.reason}`, + ); + } + 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 reason = `default ${sourceColumn.column.defaultExpr} is not supported on a foreign key column`; + const skip = makeSkip( + plan.table.name, + sourceColumn.column.name, + reason, + ); + skipped.push(skip); + unexpressed.push({ + kind: "default", + name: plan.table.name, + member: sourceColumn.column.name, + reason, + }); + sourceColumn.comments.push(`// appkit: skipped ${skip.reason}`); + delete sourceColumn.defaultCall; + if (sourceColumn.column.notNull) { + warnings.push( + `${qualified(plan.table.name, sourceColumn.column.name)}: its default ${sourceColumn.column.defaultExpr} is not in schema.ts, so the API requires a value for it on insert.`, + ); + } + } + 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) { + unexpressed.push({ + 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 ?? [])); + 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..a7334f852 --- /dev/null +++ b/packages/appkit/src/database/tooling/introspect/tests/catalog.pg.test.ts @@ -0,0 +1,147 @@ +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 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", + "events", + "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.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..ca7f64170 --- /dev/null +++ b/packages/appkit/src/database/tooling/introspect/tests/catalog.test.ts @@ -0,0 +1,136 @@ +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"] }], + 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", 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", + }), + ] 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 }], + }); + }); + + 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..2f8b2f9ff --- /dev/null +++ b/packages/appkit/src/database/tooling/introspect/tests/fixture.ts @@ -0,0 +1,293 @@ +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, +}); + +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, + ...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 }); + // The unread and index queries mention what the others match on, so they go first. + const result = text.includes("pg_catalog.pg_depend") + ? 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..dc3fe1bb6 --- /dev/null +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -0,0 +1,741 @@ +import fs from "node:fs"; +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 { generateMigrationFiles } from "../../migrations"; +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 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() }), +})); +`; + +const onDevBranch = { branch: { name: DEV }, kind: "dev" }; +const onProduction = { + branch: { name: PRODUCTION, status: { default: true } }, + kind: "default", + reason: "it is the project's default branch", +}; + +let catalog: ReturnType; +/** `when` of each migration the branch recorded; empty: no journal table. */ +let recorded: number[]; +const lastWhen = (root: string) => + readJournal(path.join(root, MIGRATIONS))?.entries.at(-1)?.when ?? 0; +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")) { + return { rows: recorded.length > 0 ? [{ "?column?": 1 }] : [] }; + } + if (text.includes("select hash, created_at")) { + return { + rows: recorded.map((when) => ({ hash: "h", created_at: String(when) })), + }; + } + return { rows: await catalog.respond(text, values) }; + }), + end: vi.fn(async () => undefined), +}; + +beforeEach(() => { + catalog = catalogResponder(); + recorded = []; + 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(entries.find((entry) => entry.tag === tag)?.when ?? 0); + } + }, + ); + 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[] } = { + 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], + indexes: [], + }); + +/** Commit a migration of the current schema.ts; `applied`: the branch has recorded it. */ +async function commitMigration(root: string, applied = true): Promise { + await generateMigrationFiles({ + folder: path.join(root, MIGRATIONS), + schema: await loadDefaultDatabaseSchema(root), + interactive: false, + }); + if (applied) recorded.push(lastWhen(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]: previousSchema }); + + 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( + previousSchema, + ); + 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"),', + ); + 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/), + 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", + "app.posts: index posts_status_idx is not declared", + ]); + 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.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 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("with history: writes and records the next NNNN_introspect", async () => { + const root = tempApp({ [SCHEMA]: previousSchema }); + await commitMigration(root); + + const report = await introspect(root); + + expect(report.migration?.tag).toBe("0001_introspect"); + expect(report.migration?.statements.join("\n")).toContain( + 'CREATE TABLE "app"."posts"', + ); + 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]: previousSchema }); + await introspect(root); + markMigrationsApplied.mockClear(); + + const report = await introspect(root); + + expect(report.migration).toBeNull(); + expect(report.recorded).toEqual([]); + expect(markMigrationsApplied).not.toHaveBeenCalled(); + }); + + test("a migration an interrupted run wrote but did not record is recorded when the branch matches it", async () => { + const root = tempApp({ [SCHEMA]: previousSchema }); + 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]: previousSchema }); + 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("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 never read: it goes to .bak and is replaced from the app schema", + async (_label, broken) => { + const root = tempApp({ [SCHEMA]: broken }); + + const report = await introspect(root); + + expect(catalog.calls.every((call) => call.values[0] === "app")).toBe( + true, + ); + expect(report).toMatchObject({ + schemaName: "app", + tables: ["authors", "posts"], + backupFile: path.join(root, `${SCHEMA}.bak`), + migration: { tag: "0000_baseline" }, + }); + expect(fs.readFileSync(path.join(root, `${SCHEMA}.bak`), "utf-8")).toBe( + broken, + ); + expect(fs.readFileSync(path.join(root, SCHEMA), "utf-8")).toMatch( + /from schema "app"\.[^]*export const schema = defineSchema\(\(\{ table[^}]*\}\) => \{/, + ); + }, + ); + + 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("the schema schema.ts declares does not change which schema is read", async () => { + const root = tempApp({ + [SCHEMA]: previousSchema.replace("}));", '}), { schemaName: "sales" });'), + }); + + const report = await introspect(root); + + expect(catalog.calls.every((call) => call.values[0] === "app")).toBe(true); + expect(report.schemaName).toBe("app"); + }); + + 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("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(Date.now() + 60_000); + 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("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")]), + 'ALTER TABLE "app"."authors" DROP COLUMN "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')" }), + ]), + `ALTER TABLE "app"."authors" ALTER COLUMN "email" DROP DEFAULT; (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 })], + }), + 'DROP TABLE "app"."tags" CASCADE; (it has no primary key)', + ], + [ + "a column in the public schema", + previousSchema.replace("}));", '}), { schemaName: "public" });'), + authorsOnly([columnRow("authors", "email", "numeric")]), + 'ALTER TABLE "authors" DROP COLUMN "email"; (type "numeric" is not supported)', + ], + ])( + "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 run 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("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, database.d.ts and the migrations are put back, so a rerun records", + async (_label, failOnce, message) => { + const root = tempApp({ + [SCHEMA]: previousSchema, + [`${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(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]: previousSchema }); + await introspect(root); + + const second = await introspect(root); + + expect(second.backupFile).toBeNull(); + expect(fs.readFileSync(path.join(root, `${SCHEMA}.bak`), "utf-8")).toBe( + previousSchema, + ); + }); + + 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]: previousSchema }); + 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..1211a18a9 --- /dev/null +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -0,0 +1,623 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { describe, expect, test } from "vitest"; + +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, + ], + }); + +const body = (source: string) => + source.slice(source.indexOf("export const schema")); + +describe("renderSchemaSource", () => { + test("golden: supported types, defaults, FKs and enums, with skip comments", () => { + const out = renderSchemaSource(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 } = renderSchemaSource(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 the API 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 the API 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(renderSchemaSource([], schemaName).source)).toBe(expected); + }, + ); + + test("tables in a schema other than app pass it to defineSchema", () => { + expect(body(renderSchemaSource([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 } = renderSchemaSource( + [ + 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 = renderSchemaSource(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 } = renderSchemaSource( + [ + 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("a table whose primary key cannot be expressed is skipped whole", () => { + const out = renderSchemaSource( + [ + 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 = renderSchemaSource( + [ + 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 } = renderSchemaSource( + [ + 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 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 } = renderSchemaSource( + [ + 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 } = renderSchemaSource([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(renderSchemaSource(richTables, "app").tables).toEqual([ + "authors", + "posts", + "default", + ]); + }); + + test("what schema.ts declares differently from the database is listed as approximated", () => { + const { approximated } = renderSchemaSource( + [ + tableOf({ + name: "a", + partitioned: true, + primaryKey: ["id"], + checks: ["a_n_check"], + indexes: ["a_n_idx", "a_m_idx"], + columns: [ + col("id", "integer", { notNull: true, identity: "a" }), + 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.n: character varying without a length is declared as text()", + "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.a: CHECK or EXCLUDE constraint a_n_check is not declared", + "app.a: indexes a_n_idx, a_m_idx are not declared", + "app.b.a_id: the foreign key is declared without DEFERRABLE", + "app.b.a_id: the foreign key is declared without MATCH FULL", + ]); + }); + + test("constraint names that differ from the ones migrations use are one warning", () => { + const { warnings } = renderSchemaSource(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 } = renderSchemaSource( + [ + tableOf({ + ...keyed("u", [col("email", "text")]), + unique: [{ name: "u_email_unique", columns: ["email"] }], + }), + 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 } = renderSchemaSource( + [ + 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] }], + }), + ], + "app", + ); + expect(warnings).toEqual([]); + }); + + test("bidi and line-separator characters are escaped in string literals", () => { + const name = "t\u202e\u2066\u2028x"; + const { source } = renderSchemaSource([keyed(name)], "app"); + expect(source).not.toMatch(/[\u2028\u202e\u2066]/); + expect(source).toContain('table("t\\u202e\\u2066\\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 } = renderSchemaSource( + [ + 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 } = renderSchemaSource( + [ + 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 the API requires a value for it on insert.", + ]); + }); + + test("SET DEFAULT needs a default fk() can take", () => { + const { skipped } = renderSchemaSource( + [ + 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", + ]); + }); +}); 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..f3d52d3c2 --- /dev/null +++ b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts @@ -0,0 +1,368 @@ +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 { drizzleKitImports } from "../../drizzle-exports"; +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 rendered source as an app's schema.ts and load it the way the plugin does. */ +async function load(tables: IntrospectedTable[]) { + 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, + renderSchemaSource(tables, "app", { importSource: BUILDER }).source, + ); + return { root, schema: await loadDefaultDatabaseSchema(root) }; +} + +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; + } + >; +} + +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 folder = path.join(root, "config/database/migrations"); + + const migration = await generateMigrationFiles({ + folder, + 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[]"), + ], + }), + 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]]); + }); +}); diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index ec2343450..1613bb9d9 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -45,7 +45,7 @@ function readJournalText(folder: string): string | null { const file = journalFile(folder); return fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : null; } -const DATABASE_TYPES_PATH = path.join( +export const DATABASE_TYPES_PATH = path.join( "shared/appkit-types", DATABASE_TYPES_FILE, ); diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 81786a253..0983b5b74 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -27,8 +27,12 @@ interface GenerateOptions { /** Absolute migrations folder. */ readonly folder: string; readonly schema: Schema; + /** Default "migration" → "NNNN_migration". */ + readonly tag?: string; /** false: an ambiguous rename throws instead of prompting. */ readonly interactive: boolean; + /** Sees the SQL before anything is written; throwing writes nothing. */ + readonly beforeWrite?: (statements: readonly string[]) => void; } export interface GeneratedMigration { @@ -60,7 +64,7 @@ export class MigrationRenameAmbiguityError extends Error { kind === "column" ? `columns of table "${table}"` : `${kind}s`; super( `Cannot tell whether ${scope} were renamed: removed ${deleted.join(", ")}; added ${created.join(", ")}. ` + - "Run `appkit db migrate` in an interactive terminal to choose between a rename and a drop plus create.", + "Run the command in an interactive terminal to choose between a rename and a drop plus create.", ); this.name = "MigrationRenameAmbiguityError"; this.kind = kind; @@ -73,6 +77,7 @@ export class MigrationRenameAmbiguityError extends Error { /** drizzle-kit's statement separator in v7 migration files. */ const BREAKPOINT = "--> statement-breakpoint\n"; const ORIGIN_ID = "00000000-0000-0000-0000-000000000000"; +const TAG_NAME = /^[a-z0-9_]+$/; /** The parts of a drizzle-kit PostgreSQL snapshot this module reads. */ interface Snapshot { @@ -290,12 +295,18 @@ function writeFileAtomic(file: string, content: string): void { /** * Diff the schema against the latest committed snapshot with drizzle-kit and - * write the next v7 migration: `NNNN_migration.sql`, `meta/NNNN_snapshot.json`, + * write the next v7 migration: `NNNN_.sql`, `meta/NNNN_snapshot.json`, * and the appended `meta/_journal.json`. null when nothing changed. */ export async function generateMigrationFiles( options: GenerateOptions, ): Promise { + const name = options.tag ?? "migration"; + if (!TAG_NAME.test(name)) { + throw new Error( + `Migration tag "${name}" must use lowercase letters, digits and underscores`, + ); + } const { generateDrizzleJson, generateMigration } = await loadDrizzleKit(); const journal = readJournal(options.folder); @@ -319,11 +330,12 @@ export async function generateMigrationFiles( cur as unknown as KitSnapshot, ); if (statements.length === 0) return null; + options.beforeWrite?.(statements); const entries = journal?.entries ?? []; const last = entries.at(-1); const idx = last ? last.idx + 1 : 0; - const tag = `${migrationPrefix(idx)}_migration`; + const tag = `${migrationPrefix(idx)}_${name}`; const entry: JournalEntry = { idx, version: "7", diff --git a/packages/appkit/src/database/tooling/tests/contract.test.ts b/packages/appkit/src/database/tooling/tests/contract.test.ts index f4e3765d3..192305dcf 100644 --- a/packages/appkit/src/database/tooling/tests/contract.test.ts +++ b/packages/appkit/src/database/tooling/tests/contract.test.ts @@ -10,6 +10,7 @@ const exports: DatabaseTooling = tooling; const contractKeys = { createDbContext: true, + runIntrospect: true, runMigrate: true, } satisfies Record; diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index edfdf0fb8..c187abf92 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -303,6 +303,17 @@ describe("generateMigrationFiles", () => { expect(listFiles(folder)).toEqual(before); }); + test("rejects a tag that is not a safe file name", async () => { + await expect( + generateMigrationFiles({ + folder: tempFolder(), + schema: blog(), + tag: "../escape", + interactive: false, + }), + ).rejects.toThrow(/lowercase letters/); + }); + test("refuses to diff when the latest snapshot is missing", async () => { const folder = tempFolder(); await generateMigrationFiles({ @@ -342,6 +353,65 @@ describe("generateMigrationFiles", () => { ), ); }); + + test("beforeWrite sees the SQL first, and throwing from it writes nothing", async () => { + const folder = tempFolder(); + const seen: string[][] = []; + + const error = await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + beforeWrite: (statements) => { + seen.push([...statements]); + throw new Error("refused"); + }, + }).catch((caught: unknown) => caught); + + expect((error as Error).message).toBe("refused"); + expect(seen).toHaveLength(1); + expect(seen[0]?.join("\n")).toContain('CREATE TABLE "app"."authors"'); + expect(listFiles(folder)).toEqual([]); + }); +}); + +describe("discardMigrationFiles", () => { + test("a first migration goes with the folders it created", async () => { + const folder = tempFolder(); + const migration = await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + + discardMigrationFiles(folder, migration as never, null); + + expect(fs.existsSync(folder)).toBe(false); + }); + + test("a later migration goes, and the previous journal comes back byte for byte", async () => { + const folder = tempFolder(); + await generateMigrationFiles({ + folder, + schema: blog(), + interactive: false, + }); + const journalFile = path.join(folder, "meta/_journal.json"); + const journalBefore = `${fs.readFileSync(journalFile, "utf-8")}\n`; + fs.writeFileSync(journalFile, journalBefore); + const filesBefore = listFiles(folder); + const migration = await generateMigrationFiles({ + folder, + schema: blog({ summary: text() }), + interactive: false, + }); + expect(listFiles(folder)).not.toEqual(filesBefore); + + discardMigrationFiles(folder, migration as never, journalBefore); + + expect(listFiles(folder)).toEqual(filesBefore); + expect(fs.readFileSync(journalFile, "utf-8")).toBe(journalBefore); + }); }); describe("breakingStatements", () => { diff --git a/packages/shared/src/cli/commands/db/index.ts b/packages/shared/src/cli/commands/db/index.ts index aca41b888..35ff2f721 100644 --- a/packages/shared/src/cli/commands/db/index.ts +++ b/packages/shared/src/cli/commands/db/index.ts @@ -1,5 +1,6 @@ import { Command } from "commander"; +import { dbIntrospectCommand } from "./introspect"; import { dbMigrateCommand } from "./migrate"; /** @@ -8,4 +9,5 @@ import { dbMigrateCommand } from "./migrate"; */ export const dbCommand = new Command("db") .description("Lakebase database lifecycle") - .addCommand(dbMigrateCommand); + .addCommand(dbMigrateCommand) + .addCommand(dbIntrospectCommand); diff --git a/packages/shared/src/cli/commands/db/introspect.test.ts b/packages/shared/src/cli/commands/db/introspect.test.ts new file mode 100644 index 000000000..8c9e2e6c1 --- /dev/null +++ b/packages/shared/src/cli/commands/db/introspect.test.ts @@ -0,0 +1,171 @@ +import { + afterEach, + beforeEach, + describe, + expect, + type MockInstance, + test, + vi, +} from "vitest"; + +const tooling = vi.hoisted(() => ({ + createDbContext: vi.fn(() => ({ root: "/app", env: {} })), + runIntrospect: vi.fn(), +})); + +vi.mock("@databricks/appkit/database-tooling", () => tooling); + +import { dbCommand } from "./index"; + +let log: MockInstance; +let error: MockInstance; +const output = (spy: MockInstance) => + spy.mock.calls.map((call) => call.join(" ")).join("\n"); + +const report = { + branch: "projects/p/branches/dev-alice-3f9a2c", + schemaName: "app", + tables: ["authors", "posts"], + schemaFile: `${process.cwd()}/config/database/schema.ts`, + backupFile: `${process.cwd()}/config/database/schema.ts.bak`, + skipped: [ + { + table: "events", + reason: "composite primary key (a, b) is not supported", + }, + { + table: "posts", + column: "score", + reason: 'type "numeric(10,2)" is not supported', + }, + ], + warnings: [ + "app.posts.score is NOT NULL with no default but is not in schema.ts.", + ], + approximated: [ + "app.authors.id: a serial key is declared as id(), an identity generated BY DEFAULT", + ], + migration: { + tag: "0000_baseline", + file: `${process.cwd()}/config/database/migrations/0000_baseline.sql`, + statements: ["CREATE TABLE a", "CREATE TABLE b"], + }, + recorded: ["0000_baseline"], + typesFile: `${process.cwd()}/shared/appkit-types/database.d.ts`, +}; + +beforeEach(() => { + for (const option of dbCommand.commands.flatMap((c) => + c.options.map((o) => [c, o] as const), + )) { + option[0].setOptionValueWithSource( + option[1].attributeName(), + undefined, + "default", + ); + } + tooling.runIntrospect.mockReset().mockResolvedValue(report); + log = vi.spyOn(console, "log").mockImplementation(() => undefined); + error = vi.spyOn(console, "error").mockImplementation(() => undefined); +}); + +afterEach(() => { + vi.restoreAllMocks(); + process.exitCode = undefined; +}); + +describe("appkit db introspect", () => { + test("prints the written schema, each skip, the loud warnings, and the recorded baseline", async () => { + await dbCommand.parseAsync(["introspect"], { from: "user" }); + + expect(tooling.runIntrospect).toHaveBeenCalledWith( + { root: "/app", env: {} }, + { interactive: false }, + ); + const printed = output(log); + expect(printed).toContain( + "Wrote config/database/schema.ts from schema app on dev-alice-3f9a2c (2 tables); the previous file is config/database/schema.ts.bak", + ); + expect(printed).toContain( + "Skipped table events: composite primary key (a, b) is not supported", + ); + expect(printed).toContain( + 'Skipped posts.score: type "numeric(10,2)" is not supported', + ); + expect(printed).toContain("app.posts.score is NOT NULL with no default"); + expect(printed).toContain( + "Approximated app.authors.id: a serial key is declared as id(), an identity generated BY DEFAULT", + ); + expect(printed).toContain( + "This branch keeps the approximated objects as they are; a database the migrations create gets what schema.ts declares.", + ); + expect(printed).toContain( + "Generated config/database/migrations/0000_baseline.sql (2 statements)", + ); + expect(printed).toContain( + "Recorded 0000_baseline as applied on dev-alice-3f9a2c: the branch already has what it describes", + ); + expect(printed).toContain("Generated shared/appkit-types/database.d.ts"); + expect(process.exitCode).toBeUndefined(); + }); + + test("--schema-name is passed through", async () => { + await dbCommand.parseAsync(["introspect", "--schema-name", "app"], { + from: "user", + }); + + expect(tooling.runIntrospect).toHaveBeenCalledWith(expect.anything(), { + interactive: false, + schemaName: "app", + }); + }); + + test("migrations an interrupted run left unrecorded are listed with the one it recorded", async () => { + tooling.runIntrospect.mockResolvedValue({ + ...report, + migration: null, + recorded: ["0002_introspect"], + }); + + await dbCommand.parseAsync(["introspect"], { from: "user" }); + + expect(output(log)).toContain( + "Recorded 0002_introspect as applied on dev-alice-3f9a2c: the branch already has what it describes", + ); + }); + + test.each([ + [[], "No migration needed: schema.ts has no tables"], + [ + ["authors"], + "No migration needed: the migrations already describe this schema", + ], + ])("without a migration, %j tables print %j", async (tables, line) => { + tooling.runIntrospect.mockResolvedValue({ + ...report, + tables, + migration: null, + recorded: [], + }); + + await dbCommand.parseAsync(["introspect"], { from: "user" }); + + expect(output(log)).toContain(line); + expect(output(log)).not.toContain("Recorded"); + }); + + test("a refusal is printed and exits 1", async () => { + tooling.runIntrospect.mockRejectedValue( + new Error( + "Refusing to introspect: production is not your dev or session branch (it is the project's default branch).", + ), + ); + + await dbCommand.parseAsync(["introspect"], { from: "user" }); + + expect(output(error)).toContain( + "Refusing to introspect: production is not your dev or session branch", + ); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/packages/shared/src/cli/commands/db/introspect.ts b/packages/shared/src/cli/commands/db/introspect.ts new file mode 100644 index 000000000..1d2b37031 --- /dev/null +++ b/packages/shared/src/cli/commands/db/introspect.ts @@ -0,0 +1,43 @@ +import { Command } from "commander"; + +import { loadDatabaseTooling } from "./load-tooling"; +import { fail, isInteractive, printIntrospectReport } from "./output"; + +async function runDbIntrospect(flags: { schemaName?: string }): Promise { + try { + const tooling = await loadDatabaseTooling(); + const report = await tooling.runIntrospect(tooling.createDbContext(), { + interactive: isInteractive(), + ...(flags.schemaName ? { schemaName: flags.schemaName } : {}), + }); + printIntrospectReport(report); + } catch (error) { + fail(error); + } +} + +export const dbIntrospectCommand = new Command("introspect") + .description( + "Write config/database/schema.ts from the .env branch's tables, plus the migration that brings history up to them", + ) + .option("--schema-name ", "Postgres schema to read (default: app)") + .addHelpText( + "after", + ` +The previous schema.ts is kept as schema.ts.bak. What the schema builder cannot +express (composite keys, unsupported types or defaults, some foreign keys) is left +out with an "// appkit: skipped …" comment. + +Without migration history this writes 0000_baseline; with history, the next +NNNN_introspect, once the branch has applied every committed migration. The +migration is recorded as applied, so introspect runs only on your dev or session +branch; \`appkit db init\` creates one from the project's default branch. The +deployed app adopts 0000_baseline on start when its tables already exist. If +anything fails, schema.ts, database.d.ts and the migrations are left as they +were. + +Examples: + $ appkit db introspect + $ appkit db introspect --schema-name sales`, + ) + .action(runDbIntrospect); diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index f3dc540a4..b73bbe163 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -3,7 +3,7 @@ import process from "node:process"; import pc from "picocolors"; -import type { MigrateReport } from "./tooling-contract"; +import type { IntrospectReport, MigrateReport } from "./tooling-contract"; /** Prompts only when a human can answer them. */ export function isInteractive(): boolean { @@ -14,6 +14,11 @@ export function relative(file: string): string { return path.relative(process.cwd(), file) || file; } +/** The last segment of a Lakebase resource name: projects/p/branches/dev-a → dev-a. */ +function shortName(name: string): string { + return name.slice(name.lastIndexOf("/") + 1); +} + export const ok = (message: string) => console.log(`${pc.green("✔")} ${message}`); export const info = (message: string) => @@ -73,3 +78,44 @@ export function printMigrateReport(report: MigrateReport): void { ok(`Generated ${relative(report.typesFile)}`); } + +export function printIntrospectReport(report: IntrospectReport): void { + const count = report.tables.length; + ok( + `Wrote ${relative(report.schemaFile)} from schema ${report.schemaName} on ${shortName(report.branch)} (${count} table${count === 1 ? "" : "s"})${report.backupFile ? `; the previous file is ${relative(report.backupFile)}` : ""}`, + ); + for (const skip of report.skipped) { + warn( + `Skipped ${skip.column ? `${skip.table}.${skip.column}` : `table ${skip.table}`}: ${skip.reason}`, + ); + } + for (const warning of report.warnings) { + console.log(`${pc.bold(pc.red("!"))} ${pc.bold(warning)}`); + } + for (const difference of report.approximated) { + info(`Approximated ${difference}`); + } + if (report.approximated.length > 0) { + info( + "This branch keeps the approximated objects as they are; a database the migrations create gets what schema.ts declares.", + ); + } + if (report.migration) { + const statements = report.migration.statements.length; + ok( + `Generated ${relative(report.migration.file)} (${statements} statement${statements === 1 ? "" : "s"})`, + ); + } else { + info( + report.tables.length === 0 + ? "No migration needed: schema.ts has no tables" + : "No migration needed: the migrations already describe this schema", + ); + } + if (report.recorded.length > 0) { + ok( + `Recorded ${report.recorded.join(", ")} as applied on ${shortName(report.branch)}: the branch already has ${report.recorded.length === 1 ? "what it describes" : "what they describe"}`, + ); + } + ok(`Generated ${relative(report.typesFile)}`); +} diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 06e73e359..cb39f69b2 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -19,6 +19,26 @@ export interface MigrateReport { readonly typesFile: string; } +export interface Skip { + readonly table: string; + readonly column?: string; + readonly reason: string; +} + +export interface IntrospectReport { + readonly branch: string; + readonly schemaName: string; + readonly tables: readonly string[]; + readonly schemaFile: string; + readonly backupFile: string | null; + readonly skipped: readonly Skip[]; + readonly warnings: readonly string[]; + readonly approximated: readonly string[]; + readonly migration: GeneratedMigration | null; + readonly recorded: readonly string[]; + readonly typesFile: string; +} + /** * The exports of `@databricks/appkit/database-tooling` the CLI calls. `shared` * must not depend on appkit, so the CLI imports the tooling dynamically and @@ -35,4 +55,8 @@ export interface DatabaseTooling { ctx: Ctx, options: { interactive: boolean }, ) => Promise; + readonly runIntrospect: ( + ctx: Ctx, + options: { interactive: boolean; schemaName?: string }, + ) => Promise; } From 98ef27bcf47035fc1de3d59fec38a200cd4062a3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Tue, 13 Oct 2026 00:05:20 +0100 Subject: [PATCH 011/317] feat(appkit): add appkit db init, clean and seed `appkit db init` gives a checkout its own Lakebase branch, forked from the project's default branch: your dev branch, or with --session a branch for this checkout that expires after 7 days (or --ttl). It asks nothing. It refuses the default branch, protected branches and branches databricks.yml deploys to before any change, and when the project is at its branch limit it lists your branches to delete. It makes sure the branch has a read-write endpoint that suspends after 5 idle minutes and a Postgres role for you, points .env at it with an atomic 0600 write, hands you the app schema when the fork copied it owned by another Lakebase role, installs drizzle-kit when the app lacks it, then starts the schema by migrating, introspecting or cleaning. `appkit db clean` drops the app schema (only your objects in public) and lists what outside it went along; --delete-branch deletes this checkout's session branch instead. `appkit db seed` runs config/database/seed.sql in one transaction with the app schema on the search_path. Both run only on a branch created for you or this checkout. Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 11 +- .../src/database/migrations/ownership.ts | 3 +- .../migrations/tests/ownership.test.ts | 3 + .../appkit/src/database/tooling/branch-sql.ts | 24 + packages/appkit/src/database/tooling/clean.ts | 219 +++++ .../appkit/src/database/tooling/context.ts | 2 + .../database/tooling/drizzle-kit-install.ts | 91 ++ .../appkit/src/database/tooling/env-file.ts | 124 +++ packages/appkit/src/database/tooling/guard.ts | 24 +- .../appkit/src/database/tooling/hand-off.ts | 104 +++ .../appkit/src/database/tooling/identity.ts | 13 +- packages/appkit/src/database/tooling/index.ts | 15 + packages/appkit/src/database/tooling/init.ts | 572 ++++++++++++ .../src/database/tooling/lakebase-api.ts | 277 +++++- .../appkit/src/database/tooling/migrate.ts | 31 +- .../appkit/src/database/tooling/migrations.ts | 16 + .../appkit/src/database/tooling/naming.ts | 76 +- packages/appkit/src/database/tooling/seed.ts | 47 + .../appkit/src/database/tooling/targets.ts | 57 +- .../database/tooling/tests/clean-seed.test.ts | 262 ++++++ .../database/tooling/tests/clean.pg.test.ts | 164 ++++ .../database/tooling/tests/contract.test.ts | 5 + .../tooling/tests/drizzle-kit-install.test.ts | 74 ++ .../database/tooling/tests/env-file.test.ts | 181 ++++ .../src/database/tooling/tests/fakes.ts | 141 ++- .../src/database/tooling/tests/guard.test.ts | 82 +- .../tooling/tests/hand-off.pg.test.ts | 75 ++ .../database/tooling/tests/identity.test.ts | 10 +- .../src/database/tooling/tests/init.test.ts | 838 ++++++++++++++++++ .../tooling/tests/lakebase-api.test.ts | 278 +++++- .../database/tooling/tests/migrate.test.ts | 23 + .../src/database/tooling/tests/naming.test.ts | 59 +- .../database/tooling/tests/targets.test.ts | 71 +- packages/shared/src/cli/commands/db/clean.ts | 81 ++ packages/shared/src/cli/commands/db/index.ts | 8 +- .../cli/commands/db/init-clean-seed.test.ts | 377 ++++++++ packages/shared/src/cli/commands/db/init.ts | 143 +++ packages/shared/src/cli/commands/db/output.ts | 21 +- packages/shared/src/cli/commands/db/seed.ts | 27 + .../src/cli/commands/db/tooling-contract.ts | 58 ++ 40 files changed, 4617 insertions(+), 70 deletions(-) create mode 100644 packages/appkit/src/database/tooling/branch-sql.ts create mode 100644 packages/appkit/src/database/tooling/clean.ts create mode 100644 packages/appkit/src/database/tooling/drizzle-kit-install.ts create mode 100644 packages/appkit/src/database/tooling/env-file.ts create mode 100644 packages/appkit/src/database/tooling/hand-off.ts create mode 100644 packages/appkit/src/database/tooling/init.ts create mode 100644 packages/appkit/src/database/tooling/seed.ts create mode 100644 packages/appkit/src/database/tooling/tests/clean-seed.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/clean.pg.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/env-file.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/init.test.ts create mode 100644 packages/shared/src/cli/commands/db/clean.ts create mode 100644 packages/shared/src/cli/commands/db/init-clean-seed.test.ts create mode 100644 packages/shared/src/cli/commands/db/init.ts create mode 100644 packages/shared/src/cli/commands/db/seed.ts diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index b9f528640..14d08800c 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -207,7 +207,7 @@ function systemCodeOf(error: unknown): string | undefined { return findCode(error, (code) => SYSTEM_CODE.test(code)); } -function quoteIdentifier(name: string): string { +export function quoteIdentifier(name: string): string { return `"${name.replace(/"/g, '""')}"`; } @@ -367,14 +367,15 @@ async function acquireMigrationLock( } } -async function inTransaction( +export async function inTransaction( client: QueryClient, - work: () => Promise, -): Promise { + work: () => Promise, +): Promise { await client.query("begin"); try { - await work(); + const result = await work(); await client.query("commit"); + return result; } catch (error) { await client.query("rollback").catch(() => undefined); throw error; diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index 3136b0daa..59a7be8d4 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -64,7 +64,8 @@ export function ownershipHint( `Schema "${ownership.schemaName}" is owned by "${ownership.owner}", but the app connects as "${ownership.currentUser}". ` + "This happens when the app's database resource was removed and added again, or the app was recreated with a new service principal: " + `Lakebase hands the objects to another role. Have "${ownership.owner}" transfer the schema and its tables to "${ownership.currentUser}" ` + - "(ALTER … OWNER TO), or set another schemaName in schema.ts." + "(ALTER … OWNER TO), or set another schemaName in schema.ts. " + + "On your dev or session branch, rerun `appkit db init`, which hands you the schema." ); } return ( diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index 27acc56b5..d1dda3838 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -26,6 +26,9 @@ describe("ownership: one owner per branch", () => { "the app's database resource was removed and added again, or the app was recreated", ); expect(hint).toContain("set another schemaName in schema.ts"); + 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", () => { 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/clean.ts b/packages/appkit/src/database/tooling/clean.ts new file mode 100644 index 000000000..ffba81e41 --- /dev/null +++ b/packages/appkit/src/database/tooling/clean.ts @@ -0,0 +1,219 @@ +import type { PoolClient } from "pg"; + +import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +import { quoteIdentifier } from "../migrations/apply"; +import { runInTransaction } from "./branch-sql"; +import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context"; +import { notYourBranch, resolveEnvBranch, writableEnvBranch } from "./guard"; +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 depend on it, so CASCADE removes them + * too: a view in another schema, a foreign key into an app table, a column of + * an app type. For public, "outside" also means owned by another role. + */ +const DEPENDENTS_SQL = ` +with 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) +) +select distinct o.label + from pg_catalog.pg_depend d + join dropped on d.refclassid = dropped.classid and d.refobjid = dropped.objid + cross join lateral ( + select c.relnamespace as namespace, c.relowner as owner, + pg_catalog.pg_describe_object(d.classid, d.objid, d.objsubid) as label + from pg_catalog.pg_class c + where d.classid = 'pg_catalog.pg_class'::regclass and c.oid = d.objid + union all + select c.relnamespace, c.relowner, + pg_catalog.pg_describe_object('pg_catalog.pg_class'::regclass, c.oid, 0) + from pg_catalog.pg_rewrite r join pg_catalog.pg_class c on c.oid = r.ev_class + where d.classid = 'pg_catalog.pg_rewrite'::regclass and r.oid = d.objid + union all + select con.connamespace, coalesce(c.relowner, t.typowner), + pg_catalog.pg_describe_object(d.classid, d.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 d.classid = 'pg_catalog.pg_constraint'::regclass and con.oid = d.objid + union all + select p.pronamespace, p.proowner, pg_catalog.pg_describe_object(d.classid, d.objid, 0) + from pg_catalog.pg_proc p + where d.classid = 'pg_catalog.pg_proc'::regclass and p.oid = d.objid + union all + select t.typnamespace, t.typowner, pg_catalog.pg_describe_object(d.classid, d.objid, 0) + from pg_catalog.pg_type t + where d.classid = 'pg_catalog.pg_type'::regclass and t.oid = d.objid + union all + select c.relnamespace, c.relowner, pg_catalog.pg_describe_object(d.classid, d.objid, 0) + from pg_catalog.pg_trigger tg join pg_catalog.pg_class c on c.oid = tg.tgrelid + where d.classid = 'pg_catalog.pg_trigger'::regclass and tg.oid = d.objid + union all + select c.relnamespace, c.relowner, pg_catalog.pg_describe_object(d.classid, d.objid, 0) + from pg_catalog.pg_attrdef a join pg_catalog.pg_class c on c.oid = a.adrelid + where d.classid = 'pg_catalog.pg_attrdef'::regclass and a.oid = d.objid + union all + select c.relnamespace, c.relowner, pg_catalog.pg_describe_object(d.classid, d.objid, 0) + from pg_catalog.pg_policy pol join pg_catalog.pg_class c on c.oid = pol.polrelid + where d.classid = 'pg_catalog.pg_policy'::regclass and pol.oid = d.objid + ) o + cross join target + cross join me + where d.deptype = 'n' + 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) => 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[]; +} + +async function cleanTarget(ctx: DbContext) { + requireSchemaFile(ctx.root, "clean"); + const branch = await writableEnvBranch(ctx, "clean"); + const schema = await loadDefaultDatabaseSchema(ctx.root, { + showImportError: true, + }); + return { branch: branch.name, schemaName: schema.$schemaName }; +} + +/** What `appkit db clean` would drop, read without changing anything. */ +export async function previewClean(ctx: DbContext): Promise { + const target = await cleanTarget(ctx); + const dependents = await withBranchPool(ctx, (pool) => + readCascadeDependents(pool, target.schemaName), + ); + return { ...target, dependents }; +} + +/** + * `appkit db clean`: remove every app-schema object, the migration journal + * included, on your dev or session branch. Refuses any other branch before + * connecting. + */ +export async function runClean(ctx: DbContext): Promise { + const target = await cleanTarget(ctx); + const dependents = await runInTransaction(ctx, async (client) => { + const found = await readCascadeDependents(client, target.schemaName); + for (const statement of cleanStatements(target.schemaName)) { + await client.query(statement); + } + return found; + }); + return { ...target, dependents }; +} + +/** + * `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 index b417297da..1f479f942 100644 --- a/packages/appkit/src/database/tooling/context.ts +++ b/packages/appkit/src/database/tooling/context.ts @@ -28,6 +28,8 @@ export interface ToolingWorkspaceClient { readonly currentUser: { me(request: { attributes?: string }): Promise<{ userName?: string }>; }; + /** The resolved workspace host, which init writes to a new .env. */ + getHost(): Promise; } /** Where a command runs: the app root, its environment and its Databricks identity. */ 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..9fa9e9c36 --- /dev/null +++ b/packages/appkit/src/database/tooling/drizzle-kit-install.ts @@ -0,0 +1,91 @@ +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; + +import { DRIZZLE_KIT_VERSION, hasDrizzleKit } from "./migrations"; + +/** Runs a command in `cwd`; throws when it fails. */ +export type RunCommand = ( + command: string, + args: readonly string[], + cwd: string, +) => void; + +/** Exact dev-dependency installs, by the lockfile that names the package manager. */ +const MANAGERS: ReadonlyArray< + readonly [lockfile: string, command: string, args: readonly string[]] +> = [ + ["pnpm-lock.yaml", "pnpm", ["add", "-D", "-E"]], + ["yarn.lock", "yarn", ["add", "-D", "-E"]], + ["bun.lock", "bun", ["add", "-d", "--exact"]], + ["bun.lockb", "bun", ["add", "-d", "--exact"]], + ["package-lock.json", "npm", ["install", "--save-dev", "--save-exact"]], +]; + +interface Install { + readonly command: string; + readonly args: readonly string[]; +} + +/** The install with the package manager whose lockfile is nearest `root`; npm without one. */ +export function drizzleKitInstall(root: string): Install { + const spec = `drizzle-kit@${DRIZZLE_KIT_VERSION}`; + for (let dir = path.resolve(root); ; dir = path.dirname(dir)) { + for (const [lockfile, command, args] of MANAGERS) { + if (fs.existsSync(path.join(dir, lockfile))) { + return { command, args: [...args, spec] }; + } + } + if (dir === path.dirname(dir)) break; + } + return { + command: "npm", + args: ["install", "--save-dev", "--save-exact", spec], + }; +} + +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. Returns the command it ran; null when drizzle-kit 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 { + if (hasDrizzleKit(root) || !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}, 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..63eccdb18 --- /dev/null +++ b/packages/appkit/src/database/tooling/env-file.ts @@ -0,0 +1,124 @@ +import { randomBytes } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; + +/** An entry's first line: indentation and `export ` (kept on rewrite), the key, the value. */ +const ENTRY = /^(\s*(?:export\s+)?)([\w.-]+)\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 { + if (!fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) return; + 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.`, + ); +} + +/** A crash leaves the old file or the new one, never a truncated one. */ +function writeAtomically(file: string, contents: string): void { + const temp = path.join( + path.dirname(file), + `.${path.basename(file)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`, + ); + try { + fs.writeFileSync(temp, contents, { mode: 0o600, flag: "wx" }); + fs.renameSync(temp, file); + } catch (error) { + fs.rmSync(temp, { force: true }); + throw error; + } +} + +/** + * Replace `KEY=…` entries and append missing keys. 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; + } + // Later duplicates of a managed key are dropped, so the value is unambiguous. + if (written.has(key)) continue; + written.add(key); + out.push(`${entry.prefix}${key}=${formatValue(key, values[key] ?? "")}`); + } + for (const [key, value] of Object.entries(values)) { + if (!written.has(key)) out.push(`${key}=${formatValue(key, value)}`); + } + writeAtomically(file, `${out.join(eol)}${eol}`); +} diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts index 994fe1fac..fc55e2385 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -1,4 +1,4 @@ -import { type DbContext, hasEnvBranch } from "./context"; +import { type DbContext, hasEnvBranch, NO_ENV_BRANCH } from "./context"; import { currentIdentity } from "./identity"; import type { LakebaseBranch } from "./lakebase-api"; import { devBranchId, sessionBranchId } from "./naming"; @@ -46,15 +46,12 @@ export function classifyBranch(input: { } const id = resourceId(branch.name); if (id === devBranchId(userName)) return { kind: "dev" }; - if (sessionId && id === sessionBranchId(sessionId)) { - return { kind: "session" }; - } + 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)})${ - sessionId - ? ` or this checkout's session branch (${sessionBranchId(sessionId)})` - : "" + session ? ` or this checkout's session branch (${session})` : "" }`, }; } @@ -106,3 +103,16 @@ export async function resolveEnvBranch( }), }; } + +/** 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..adb3d17ae --- /dev/null +++ b/packages/appkit/src/database/tooling/hand-off.ts @@ -0,0 +1,104 @@ +import type { PoolClient } from "pg"; + +import { schemaOwnership } from "../migrations/ownership"; +import { type DbContext, withBranchPool } from "./context"; +import type { LakebaseRole } from "./lakebase-api"; +import { resourceId } from "./targets"; + +/** + * What keeps a role from being dropped once its objects in the current + * database are reassigned: objects it owns in other databases, shared objects + * (databases), and privileges granted to it anywhere. + */ +const BLOCKERS_SQL = ` +select 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 + order by 1`; + +interface RoleBlocker { + /** Empty for shared objects. */ + readonly database: string; + readonly count: number; +} + +export async function readRoleBlockers( + client: Pick, + role: string, +): Promise { + const { rows } = await client.query(BLOCKERS_SQL, [role]); + return rows; +} + +function describeBlockers(blockers: readonly RoleBlocker[]): string { + return blockers + .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. Returns + * that owner; null when you already own the schema or it does not exist. + */ +export async function handOffAppSchema( + ctx: DbContext, + input: HandOff, +): Promise { + const found = await withBranchPool(ctx, async (pool) => { + const { owner, currentUser } = await schemaOwnership( + pool, + input.schemaName, + ); + if (!owner || owner === currentUser) return null; + return { owner, blockers: await readRoleBlockers(pool, owner) }; + }); + if (!found) return null; + + const { owner, blockers } = found; + const where = `schema ${input.schemaName} in database ${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 "${owner}", which is not a Lakebase-managed role. .env already points at the branch. Have "${owner}" transfer the schema and its objects to you (ALTER … OWNER TO), or set another schemaName in schema.ts, then rerun \`appkit db init\`.`, + ); + } + input.onStep( + `Handing ${where} to you: deleting this branch's copy of role ${owner}, 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); + throw new Error( + blockers.length > 0 + ? `Could not hand ${where} to you: deleting role "${owner}" failed (${reason}). These objects and privileges of "${owner}" block the delete: ${describeBlockers(blockers)}. .env already points at the branch. Drop them or reassign them to you, then rerun \`appkit db init\`.` + : `Could not hand ${where} to you: deleting role "${owner}" failed (${reason}). .env already points at the branch; rerun \`appkit db init\` to retry.`, + { cause: error }, + ); + } + return owner; +} diff --git a/packages/appkit/src/database/tooling/identity.ts b/packages/appkit/src/database/tooling/identity.ts index e457c79a2..c0976b29c 100644 --- a/packages/appkit/src/database/tooling/identity.ts +++ b/packages/appkit/src/database/tooling/identity.ts @@ -1,8 +1,17 @@ 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). */ -interface Identity { +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>(); @@ -20,7 +29,7 @@ export function currentIdentity(ctx: DbContext): Promise { "Could not determine the current Databricks user (currentUser.me returned no userName). Check DATABRICKS_CONFIG_PROFILE.", ); } - return { userName }; + return { userName, identityType: identityTypeOf(userName) }; }); identity.catch(() => identities.delete(ctx)); identities.set(ctx, identity); diff --git a/packages/appkit/src/database/tooling/index.ts b/packages/appkit/src/database/tooling/index.ts index 29adba529..c355b52c2 100644 --- a/packages/appkit/src/database/tooling/index.ts +++ b/packages/appkit/src/database/tooling/index.ts @@ -6,10 +6,25 @@ * Internal to the AppKit CLI: it has no semver guarantee, and only the CLI of * the same AppKit release should import it. */ +export { + type CleanReport, + deleteSessionBranch, + previewClean, + runClean, +} from "./clean"; export { createDbContext, type DbContext } from "./context"; +export { + type InitOptions, + type InitReport, + type InitStart, + 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"; diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts new file mode 100644 index 000000000..6a5118980 --- /dev/null +++ b/packages/appkit/src/database/tooling/init.ts @@ -0,0 +1,572 @@ +import fs from "node:fs"; +import path from "node:path"; + +import dotenv from "dotenv"; + +import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +import { DEFAULT_SCHEMA_NAME } from "../schema-builder/define-schema"; +import { type CleanReport, runClean } from "./clean"; +import type { DbContext } from "./context"; +import { + ensureDrizzleKit, + type RunCommand, + runCommand, +} from "./drizzle-kit-install"; +import { refuseSymlink, updateEnvFile } from "./env-file"; +import { classifyBranch, takesWrites } from "./guard"; +import { handOffAppSchema } from "./hand-off"; +import { currentIdentity, type Identity } from "./identity"; +import { type IntrospectReport, runIntrospect } from "./introspect"; +import { + isAlreadyExists, + isBranchLimit, + isPermissionDenied, + type LakebaseBranch, + type LakebaseEndpoint, + type LakebaseRole, + READ_WRITE_ENDPOINT, + SUPERUSER_MEMBERSHIP, +} from "./lakebase-api"; +import { + hasSchemaFile, + type MigrateReport, + requireSchemaFile, + runMigrate, +} from "./migrate"; +import { + devBranchId, + isUsersBranchId, + newSessionId, + parseTtl, + SESSION_BRANCH_TTL, + sessionBranchId, +} from "./naming"; +import { + type BranchMode, + type DeployTarget, + type LocalTarget, + parseResourceName, + readDeployBranches, + readDeployTarget, + readLocalTarget, + resourceId, +} from "./targets"; + +/** How init leaves the schema; "none" leaves it as the fork has it. */ +export type SchemaStart = "migrate" | "introspect" | "clean" | "none"; + +export interface InitOptions { + /** Default: this checkout's session branch when .env points at it, else your dev branch. */ + readonly mode?: BranchMode; + /** Default: migrate when schema.ts exists, introspect otherwise. */ + readonly schema?: SchemaStart; + /** 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; + /** Runs the drizzle-kit install. */ + readonly runCommand?: RunCommand; +} + +type RoleAction = "kept" | "created" | "updated"; + +export type InitStart = + | { readonly kind: "none" } + | { readonly kind: "migrate"; readonly migrate: MigrateReport } + | { readonly kind: "introspect"; readonly introspect: IntrospectReport } + | { + readonly kind: "clean"; + readonly clean: CleanReport; + readonly migrate: MigrateReport; + }; + +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; + 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. */ + readonly handedOff: string | 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"; +/** Every Lakebase branch has it; used when nothing names another database. */ +const DEFAULT_DATABASE = "databricks_postgres"; + +/** 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 points at this checkout's session branch; dev otherwise. */ +function defaultMode(local: LocalTarget, userName: string): BranchMode { + const branch = parseResourceName(local.endpoint ?? undefined)?.branch; + return local.session && + branch && + resourceId(branch) === sessionBranchId(userName, local.session) + ? "session" + : "dev"; +} + +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 deployBranches: readonly string[]; + readonly envFile: string; + readonly onStep: (message: string) => void; +} + +interface FoundBranch { + readonly branch: LakebaseBranch; + readonly created: boolean; + readonly sourceBranch?: string; + readonly session: 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 }); +} + +/** + * Your dev branch or this checkout's session branch: found with one GET, or + * forked from the project's default branch. The branch id is resolved and + * checked against databricks.yml before any API call or .env write. An expired + * session branch gets a new session id; an expired dev branch is an error. + */ +async function findOrCreateBranch( + ctx: DbContext, + request: BranchRequest, +): Promise { + const { project, mode, identity, deployBranches, 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, + deployBranches, + }); + if (!takesWrites(verdict.kind)) { + throw new Error( + `Refusing to set up ${resourceId(branch.name)}: ${verdict.reason}. \`appkit db init\` only sets up your dev branch or this checkout's session branch.`, + ); + } + 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(); + if (deployBranches.includes(name)) { + throw new Error( + `Refusing to set up ${resourceId(name)}: it is a branch databricks.yml deploys to, and the deployed app migrates it itself.`, + ); + } + 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 parent = branches.find((b) => b.status?.default); + if (!parent) { + throw new Error(`Project ${project} has no default branch to fork from.`); + } + if (session !== null && session !== request.session) { + // Written first, so a failed or interrupted run reuses this id instead of forking again. + updateEnvFile(request.envFile, { APPKIT_DB_SESSION: session }); + } + onStep( + `Creating ${resourceId(name)} from ${resourceId(parent.name)}${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, + 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); + } + } +} + +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`, + ); + endpoint = await api.createEndpoint(branch, DEFAULT_ENDPOINT_ID, { + suspendTimeout: SUSPEND_TIMEOUT, + }); + created = true; + } + let host = endpoint?.status?.hosts?.host; + if (!host) { + endpoint = readWrite(await api.listEndpoints(branch)) ?? endpoint; + 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 }; +} + +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 existing = roles.find( + (r) => r.status?.postgres_role === identity.userName, + ); + if (!existing) { + onStep( + `Creating your role ${identity.userName} with ${SUPERUSER_MEMBERSHIP}`, + ); + const role = await api.createRole(branch, { + identity_type: identity.identityType, + postgres_role: identity.userName, + auth_method: "LAKEBASE_OAUTH_V1", + membership_roles: [SUPERUSER_MEMBERSHIP], + }); + if (role?.name) return { role, action: "created" }; + // The operation response normally carries the role; fall back to a lookup. + const found = (await api.listRoles(branch)).find( + (r) => r.status?.postgres_role === identity.userName, + ); + if (!found) { + throw new Error(`Creating your role on ${branch} did not return it.`); + } + return { role: found, 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" }; +} + +async function resolveDatabase( + ctx: DbContext, + branch: string, + local: LocalTarget, + deploy: DeployTarget | null, +): Promise { + // A real .env endpoint came with its database; forks inherit the parent's databases. + if (local.database) return local.database; + if (deploy?.database) { + const database = await ctx + .api() + .getDatabase(`${branch}/databases/${resourceId(deploy.database)}`); + if (database?.status?.postgres_database) + return database.status.postgres_database; + } + return DEFAULT_DATABASE; +} + +/** 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")) + : {}; +} + +/** + * `appkit db init`: find or create your dev branch or this checkout's session + * branch, ensure a read-write endpoint and your DATABRICKS_SUPERUSER role, + * point `.env` at the branch, hand the app schema the fork copied to you, then + * start the schema. No prompts: every choice has a default. It refuses the + * project's default branch, protected branches and branches databricks.yml + * deploys to before changing anything, and never touches the deploy bundle. + */ +export async function runInit( + ctx: DbContext, + options: InitOptions = {}, +): Promise { + const onStep = options.onStep ?? (() => undefined); + 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: a .env init may write, what the start needs, and the schema the hand-off is for. + const envFile = path.join(ctx.root, ENV_FILE); + refuseSymlink(envFile); + const hasSchema = hasSchemaFile(ctx.root); + const startKind = options.schema ?? (hasSchema ? "migrate" : "introspect"); + if (startKind === "migrate" || startKind === "clean") { + requireSchemaFile(ctx.root, startKind); + } + const schemaName = + hasSchema && startKind !== "introspect" + ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) + .$schemaName + : DEFAULT_SCHEMA_NAME; + + const configured = { + local: readLocalTarget(ctx.env), + deploy: readDeployTarget(ctx.root), + }; + 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 ?? defaultMode(local, identity.userName); + if (options.ttl !== undefined && mode !== "session") { + throw new Error("--ttl applies to session branches only; add --session."); + } + const before = readEnvValues(envFile); + + const found = await findOrCreateBranch(ctx, { + project, + mode, + identity, + session: local.session, + ttl, + deployBranches: readDeployBranches(ctx.root), + envFile, + 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 = await resolveDatabase(ctx, branch.name, local, deploy); + + 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 ? {} : { PGSSLMODE: "require" }), + ...(await authValues(ctx, before)), + }; + onStep(`Pointing .env at ${resourceId(branch.name)}, database ${database}`); + updateEnvFile(envFile, values); + const branchCtx: DbContext = { ...ctx, env: { ...ctx.env, ...values } }; + + const handedOff = await handOffAppSchema(branchCtx, { + branch: branch.name, + database, + schemaName, + developer: role, + roles, + onStep, + }); + + const installed = + startKind === "migrate" || startKind === "introspect" + ? ensureDrizzleKit(ctx.root, options.runCommand ?? runCommand, onStep) + : null; + + let start: InitStart; + const on = `on ${resourceId(branch.name)}`; + if (startKind === "migrate") { + onStep(`Migrating schema ${schemaName} ${on}`); + start = { + kind: "migrate", + migrate: await runMigrate(branchCtx, { interactive }), + }; + } else if (startKind === "introspect") { + onStep(`Writing schema.ts from schema ${schemaName} ${on}`); + start = { + kind: "introspect", + introspect: await runIntrospect(branchCtx, { interactive }), + }; + } else if (startKind === "clean") { + onStep(`Dropping schema ${schemaName} ${on}`); + const clean = await runClean(branchCtx); + // Recreate from the committed migrations, so the startup check passes. + start = { + kind: "clean", + clean, + migrate: await runMigrate(branchCtx, { interactive, generate: false }), + }; + } else { + start = { kind: "none" }; + } + + return { + mode, + branch: branch.name, + created: found.created, + ...(found.sourceBranch ? { sourceBranch: found.sourceBranch } : {}), + expireTime: branch.status?.expire_time ?? null, + endpoint: endpoint.name, + endpointCreated, + host, + database, + user: identity.userName, + role: { name: role.name, action }, + handedOff, + envFile, + installed, + start, + }; +} diff --git a/packages/appkit/src/database/tooling/lakebase-api.ts b/packages/appkit/src/database/tooling/lakebase-api.ts index e020e28ca..f4fc45fda 100644 --- a/packages/appkit/src/database/tooling/lakebase-api.ts +++ b/packages/appkit/src/database/tooling/lakebase-api.ts @@ -18,19 +18,61 @@ export interface LakebaseBranch { export interface LakebaseEndpoint { name: string; - status?: { hosts?: { host?: 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. */ + /** 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; cause?: unknown } = {}, + options: { statusCode?: number; errorCode?: string; cause?: unknown } = {}, ) { super(`Lakebase: ${operation} failed: ${message}`, { cause: options.cause, @@ -38,9 +80,37 @@ export class LakebaseApiError extends Error { 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 these fields whether a command may write to a branch. @@ -70,6 +140,11 @@ function statusCodeOf(error: unknown): number | undefined { 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); } @@ -84,10 +159,27 @@ function encodeQuery( 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); @@ -112,6 +204,124 @@ export class LakebaseApi { 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}`, { + path: `${API}/${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}`, { + path: `${API}/${role}`, + query: { reassign_owned_to: options.reassignOwnedTo }, + }); + } + + private async deleteResource( + operation: string, + request: { path: string; query?: ToolingRequest["query"] }, + ): Promise { + try { + const op = await this.call(operation, { + ...request, + method: "DELETE", + }); + await this.wait(operation, op); + } catch (error) { + if (!isNotFound(error)) throw error; + } + } + private async call( operation: string, request: ToolingRequest, @@ -136,6 +346,7 @@ export class LakebaseApi { } catch (error) { throw new LakebaseApiError(operation, messageOf(error), { statusCode: statusCodeOf(error), + errorCode: errorCodeOf(error), cause: error, }); } @@ -151,10 +362,62 @@ export class LakebaseApi { method: "GET", }); } catch (error) { - if (error instanceof LakebaseApiError && error.statusCode === 404) { - return null; - } + if (isNotFound(error)) return null; throw error; } } + + private async list( + operation: string, + collection: string, + key: string, + ): Promise { + const items: T[] = []; + let pageToken: string | undefined; + do { + const page = await this.call>(operation, { + path: `${API}/${collection}`, + method: "GET", + ...(pageToken ? { query: { page_token: pageToken } } : {}), + }); + items.push(...((page?.[key] as T[] | undefined) ?? [])); + pageToken = (page?.next_page_token as string | undefined) || undefined; + } while (pageToken); + return items; + } + + /** Poll GET /api/2.0/postgres/{operation.name} until done. */ + private async wait(operation: string, first: Operation): Promise { + const deadline = Date.now() + this.timeoutMs; + let delay = this.pollIntervalMs; + let current = first; + while (!current?.done) { + if (!current?.name) { + throw new LakebaseApiError( + operation, + "the API returned an unfinished operation without a name", + ); + } + if (Date.now() >= deadline) { + throw new LakebaseApiError( + operation, + `timed out after ${Math.round(this.timeoutMs / 1000)}s waiting for ${current.name}`, + ); + } + await sleep(delay); + delay = Math.min(delay * 2, 5_000); + current = await this.call(operation, { + path: `${API}/${current.name}`, + method: "GET", + }); + } + if (current.error) { + throw new LakebaseApiError( + operation, + current.error.message ?? current.error.error_code ?? "unknown error", + { errorCode: current.error.error_code }, + ); + } + return current.response as T; + } } diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 1613bb9d9..985e1b147 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -28,15 +28,23 @@ import { } from "./migrations"; /** Whether the checkout has a config/database/schema.ts yet. */ -function hasSchemaFile(root: string): boolean { +export function hasSchemaFile(root: string): boolean { return fs.existsSync(path.join(root, DEFAULT_SCHEMA_FILE)); } +const WITHOUT_SCHEMA = { + migrate: "there is nothing to migrate", + clean: "clean cannot tell which schema to drop", +} as const; + /** Without schema.ts, point to introspect instead of a load error. */ -function requireSchemaFile(root: string): void { +export function requireSchemaFile( + root: string, + command: keyof typeof WITHOUT_SCHEMA, +): void { if (hasSchemaFile(root)) return; throw new Error( - `No ${DEFAULT_SCHEMA_FILE} yet, so there is nothing to migrate. Run \`appkit db introspect\` to write it from the branch's tables, or create it.`, + `No ${DEFAULT_SCHEMA_FILE} yet, so ${WITHOUT_SCHEMA[command]}. Run \`appkit db introspect\` to write it from the branch's tables, or create it.`, ); } @@ -67,6 +75,8 @@ export interface MigrateReport { export interface MigrateOptions { /** false: an ambiguous rename throws instead of prompting. */ readonly interactive: boolean; + /** false: apply the committed migrations only, without writing one from schema.ts. */ + readonly generate?: boolean; } type ApplyOutcome = Pick; @@ -107,17 +117,20 @@ export async function runMigrate( ctx: DbContext, options: MigrateOptions, ): Promise { - requireSchemaFile(ctx.root); + requireSchemaFile(ctx.root, "migrate"); const schema = await loadDefaultDatabaseSchema(ctx.root, { showImportError: true, }); const folder = migrationsFolder(ctx.root); const journalBefore = readJournalText(folder); - const generated = await generateMigrationFiles({ - folder, - schema, - interactive: options.interactive, - }); + const generated = + options.generate === false + ? null + : await generateMigrationFiles({ + folder, + schema, + interactive: options.interactive, + }); // The types follow schema.ts alone, so they are current even if applying fails. const typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 0983b5b74..2ed8488eb 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -218,6 +218,22 @@ function installedPackage(name: string, from: string): InstalledPackage | null { return null; } +/** + * Whether the app at `root` has drizzle-kit, at any version. The node_modules + * walk is what ESM resolution does; createRequire would also follow NODE_PATH, + * which `import("drizzle-kit/api")` ignores. + */ +export function hasDrizzleKit(root: string): boolean { + for (let dir = path.resolve(root); ; dir = path.dirname(dir)) { + if ( + fs.existsSync(path.join(dir, "node_modules/drizzle-kit/package.json")) + ) { + return true; + } + if (dir === path.dirname(dir)) return false; + } +} + /** * Why the drizzle-kit that resolves from `from` must not write migrations; * undefined when it may, or when it is not installed at all. drizzle-kit reads diff --git a/packages/appkit/src/database/tooling/naming.ts b/packages/appkit/src/database/tooling/naming.ts index aadaf374b..2310baf95 100644 --- a/packages/appkit/src/database/tooling/naming.ts +++ b/packages/appkit/src/database/tooling/naming.ts @@ -1,4 +1,4 @@ -import { createHash } from "node:crypto"; +import { createHash, randomInt } from "node:crypto"; // Branch names AppKit creates. Branch IDs: 1-63 chars, start with a // lowercase letter, lowercase letters, digits and hyphens only. @@ -8,7 +8,12 @@ const DEV_PREFIX = "dev-"; const SESSION_PREFIX = "session-"; const HASH_LENGTH = 6; -const SESSION_ID = /^[a-z0-9]{1,55}$/; +/** Seven days: a session branch outlives a working week, then expires on its own. */ +export const SESSION_BRANCH_TTL = "604800s"; + +const SESSION_ID_LENGTH = + MAX_BRANCH_ID - SESSION_PREFIX.length - HASH_LENGTH - 1; +const SESSION_ID = new RegExp(`^[a-z0-9]{1,${SESSION_ID_LENGTH}}$`); function slug(value: string): string { return value @@ -17,32 +22,75 @@ function slug(value: string): string { .replace(/^-+|-+$/g, ""); } +function normalized(userName: string): string { + return userName.trim().toLowerCase(); +} + +/** sha256(userName)[0:6]: the part of a branch name that says whose it is. */ +function userHash(userName: string): string { + return createHash("sha256") + .update(normalized(userName)) + .digest("hex") + .slice(0, HASH_LENGTH); +} + /** - * dev--. The hash keeps users who share - * a local part apart; the name is the same on every machine. + * dev--. The hash keeps users who share a local + * part apart; the name is the same on every machine. */ export function devBranchId(userName: string): string { - const normalized = userName.trim().toLowerCase(); - const hash = createHash("sha256") - .update(normalized) - .digest("hex") - .slice(0, HASH_LENGTH); const room = MAX_BRANCH_ID - DEV_PREFIX.length - 1 - HASH_LENGTH; - const local = slug(normalized.split("@")[0] ?? "") + const local = slug(normalized(userName).split("@")[0] ?? "") .slice(0, room) .replace(/-+$/, ""); - return `${DEV_PREFIX}${local || "user"}-${hash}`; + return `${DEV_PREFIX}${local || "user"}-${userHash(userName)}`; } export function isValidSessionId(sessionId: string): boolean { return SESSION_ID.test(sessionId); } -export function sessionBranchId(sessionId: string): string { +/** + * session--. The id lives in this checkout's .env; the + * hash makes a copied .env name a branch only its creator passes the guard on. + */ +export function sessionBranchId(userName: string, sessionId: string): string { if (!isValidSessionId(sessionId)) { throw new Error( - `Invalid APPKIT_DB_SESSION ${JSON.stringify(sessionId)}: use 1-55 lowercase letters or digits.`, + `Invalid APPKIT_DB_SESSION ${JSON.stringify(sessionId)}: use 1-${SESSION_ID_LENGTH} lowercase letters or digits.`, + ); + } + return `${SESSION_PREFIX}${userHash(userName)}-${sessionId}`; +} + +/** Whether a branch id is one of this user's dev or session branches. */ +export function isUsersBranchId(userName: string, branchId: string): boolean { + return ( + branchId === devBranchId(userName) || + branchId.startsWith(`${SESSION_PREFIX}${userHash(userName)}-`) + ); +} + +const BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz"; + +/** 8 random base36 characters, generated once per checkout and kept in .env. */ +export function newSessionId(): string { + let id = ""; + for (let i = 0; i < 8; i++) id += BASE36[randomInt(BASE36.length)]; + return id; +} + +const TTL = /^(\d+)([smhd])$/; +const SECONDS = { s: 1, m: 60, h: 3_600, d: 86_400 } as const; + +/** `--ttl 30m`, `1h`, `7d` or `3600s` as the API's duration ("3600s"). */ +export function parseTtl(value: string): string { + const match = TTL.exec(value.trim()); + const amount = Number(match?.[1]); + if (!match || amount <= 0) { + throw new Error( + `Invalid --ttl ${JSON.stringify(value)}: use a positive number of seconds, minutes, hours or days, e.g. 30m, 1h or 7d.`, ); } - return `${SESSION_PREFIX}${sessionId}`; + return `${amount * SECONDS[match[2] as keyof typeof SECONDS]}s`; } diff --git a/packages/appkit/src/database/tooling/seed.ts b/packages/appkit/src/database/tooling/seed.ts new file mode 100644 index 000000000..6deaa2953 --- /dev/null +++ b/packages/appkit/src/database/tooling/seed.ts @@ -0,0 +1,47 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +import { quoteIdentifier } from "../migrations/apply"; +import { DEFAULT_SCHEMA_NAME } from "../schema-builder/define-schema"; +import { runInTransaction } from "./branch-sql"; +import type { DbContext } from "./context"; +import { writableEnvBranch } from "./guard"; +import { hasSchemaFile } from "./migrate"; + +export const SEED_FILE = "config/database/seed.sql"; + +interface SeedReport { + readonly branch: string; + readonly file: string; +} + +/** + * `appkit db seed`: run config/database/seed.sql in one transaction on your + * dev or session branch, with the app schema first on the search_path so + * unqualified names resolve to it. Refuses any other branch before connecting. + */ +export async function runSeed(ctx: DbContext): Promise { + const file = path.join(ctx.root, SEED_FILE); + if (!fs.existsSync(file)) { + throw new Error( + `No seed file at ${SEED_FILE}. Create it with the SQL to run.`, + ); + } + const branch = await writableEnvBranch(ctx, "seed"); + const schemaName = hasSchemaFile(ctx.root) + ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) + .$schemaName + : DEFAULT_SCHEMA_NAME; + const searchPath = + schemaName === "public" + ? "public" + : `${quoteIdentifier(schemaName)}, public`; + const sql = fs.readFileSync(file, "utf-8"); + await runInTransaction(ctx, async (client) => { + await client.query(`SET LOCAL search_path TO ${searchPath}`); + // One simple-protocol query: the file may hold several statements. + await client.query(sql); + }); + return { branch: branch.name, file }; +} diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index ff1cef3e8..b359e9364 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -5,6 +5,8 @@ import yaml from "js-yaml"; import { isValidSessionId } from "./naming"; +export type BranchMode = "dev" | "session"; + /** Full resource names, e.g. branch = "projects/p/branches/b". */ interface ResourceName { readonly project: string; @@ -39,9 +41,26 @@ export function resourceId(name: string): string { return name.slice(name.lastIndexOf("/") + 1); } +const PROJECT_ID = /^[a-z0-9][a-z0-9-]{0,62}$/; + +/** + * LAKEBASE_PROJECT as a project resource name: accepts "projects/" or a bare + * ""; null for anything else (e.g. the .env.example placeholder). + */ +export function parseProject(value: string | undefined): string | null { + const trimmed = value?.trim() ?? ""; + const id = trimmed.startsWith("projects/") + ? trimmed.slice("projects/".length) + : trimmed; + return PROJECT_ID.test(id) ? `projects/${id}` : null; +} + /** What `.env` says about the local branch. Unparseable values (template placeholders) read as null. */ -interface LocalTarget { +export interface LocalTarget { + /** LAKEBASE_PROJECT, normalized to "projects/". */ + readonly project: string | null; readonly endpoint: string | null; + readonly database: string | null; readonly session: string | null; } @@ -51,7 +70,19 @@ export function readLocalTarget(env: NodeJS.ProcessEnv): LocalTarget { env.APPKIT_DB_SESSION && isValidSessionId(env.APPKIT_DB_SESSION) ? env.APPKIT_DB_SESSION : null; - return { endpoint, session }; + return { + project: parseProject(env.LAKEBASE_PROJECT), + endpoint, + // Without a real endpoint PGDATABASE is a template placeholder too. + database: endpoint ? env.PGDATABASE || null : null, + session, + }; +} + +/** The branch the bundle's default target deploys to. */ +export interface DeployTarget { + readonly branch: string; + readonly database: string | null; } type Yaml = Record | undefined; @@ -92,6 +123,28 @@ function variableOf( return typeof value === "string" && value ? value : null; } +/** Default target's postgres_branch / postgres_database variables; null without databricks.yml or binding. */ +export function readDeployTarget(root: string): DeployTarget | null { + const bundle = readBundle(root); + if (!bundle) return null; + const targets = record(bundle.targets) ?? {}; + const target = + Object.values(targets) + .map(record) + .find((candidate) => candidate?.default === true) ?? + record(targets.default); + + const branch = parseResourceName( + variableOf(bundle, target, "postgres_branch") ?? undefined, + )?.branch; + if (!branch) return null; + const database = + parseResourceName( + variableOf(bundle, target, "postgres_database") ?? undefined, + )?.database ?? null; + return { branch, database }; +} + /** * Every branch databricks.yml can deploy to: each target's postgres_branch and * the variable's default. Empty without databricks.yml or a postgres binding. diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts new file mode 100644 index 000000000..113e620db --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -0,0 +1,262 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { resolveEnvBranch, withBranchPool, writableEnvBranch } = vi.hoisted( + () => ({ + resolveEnvBranch: vi.fn(), + withBranchPool: vi.fn(), + writableEnvBranch: vi.fn(), + }), +); + +vi.mock("../guard", async (importOriginal) => ({ + ...(await importOriginal()), + resolveEnvBranch, + writableEnvBranch, +})); +vi.mock("../context", async (importOriginal) => ({ + ...(await importOriginal()), + withBranchPool, +})); + +import { deleteSessionBranch, previewClean, runClean } from "../clean"; +import { runSeed, SEED_FILE } from "../seed"; +import { cleanupTempApps, FakeLakebase, fakeContext, tempApp } from "./fakes"; + +const builder = path.resolve( + import.meta.dirname, + "../../schema-builder/index.ts", +); +const schemaFile = (schemaName: string) => + `import { defineSchema, id } from ${JSON.stringify(builder)}; + export const schema = defineSchema(({ table }) => ({ notes: table("notes", { id: id() }) }), { schemaName: ${JSON.stringify(schemaName)} });`; + +const DEPENDENTS = /pg_catalog\.pg_depend/; + +/** A pool whose one client records statements, can fail on one, and answers the dependents query. */ +function recordingPool( + options: { failOn?: RegExp; dependents?: string[] } = {}, +) { + const statements: string[] = []; + const client = { + released: undefined as { error: unknown } | undefined, + async query(text: string) { + statements.push(DEPENDENTS.test(text) ? "" : text); + if (options.failOn?.test(text)) throw new Error("boom"); + return { + rows: DEPENDENTS.test(text) + ? (options.dependents ?? []).map((label) => ({ label })) + : [], + }; + }, + release(error?: unknown) { + client.released = { error }; + }, + }; + const pool = { + connect: vi.fn(async () => client), + query: (text: string) => client.query(text), + }; + withBranchPool.mockImplementation((_ctx, fn: (p: unknown) => unknown) => + fn(pool), + ); + return { pool, client, statements }; +} + +const devBranch = { name: "projects/p/branches/dev-alice-3f9a2c" }; +const refusal = (action: string) => + new Error( + `Refusing to ${action}: production is not your dev or session branch (it is the project's default branch).`, + ); + +beforeEach(() => { + resolveEnvBranch.mockReset(); + withBranchPool.mockReset(); + writableEnvBranch.mockReset(); +}); +afterEach(cleanupTempApps); + +describe("runClean", () => { + test("drops the app schema in one transaction on your branch and reports what CASCADE removed outside it", async () => { + const ctx = fakeContext({ + root: tempApp({ "config/database/schema.ts": schemaFile("app") }), + }); + writableEnvBranch.mockResolvedValue(devBranch); + const { client, statements } = recordingPool({ + dependents: ["view reporting.recent"], + }); + + await expect(runClean(ctx)).resolves.toEqual({ + branch: devBranch.name, + schemaName: "app", + dependents: ["view reporting.recent"], + }); + expect(writableEnvBranch).toHaveBeenCalledWith(ctx, "clean"); + expect(statements).toEqual([ + "begin", + "", + `DROP SCHEMA IF EXISTS "app" CASCADE`, + "commit", + ]); + expect(client.released).toEqual({ error: undefined }); + }); + + test("without schema.ts it points to introspect before checking the branch", async () => { + const ctx = fakeContext({ root: tempApp() }); + + await expect(runClean(ctx)).rejects.toThrow( + "No config/database/schema.ts yet, so clean cannot tell which schema to drop. Run `appkit db introspect` to write it from the branch's tables, or create it.", + ); + expect(writableEnvBranch).not.toHaveBeenCalled(); + expect(withBranchPool).not.toHaveBeenCalled(); + }); + + test("refuses a branch that is not yours before connecting", async () => { + const ctx = fakeContext({ + root: tempApp({ "config/database/schema.ts": schemaFile("app") }), + }); + writableEnvBranch.mockRejectedValue(refusal("clean")); + + await expect(runClean(ctx)).rejects.toThrow(/^Refusing to clean: /); + expect(withBranchPool).not.toHaveBeenCalled(); + }); + + test("a failing statement rolls back and discards the connection", async () => { + const ctx = fakeContext({ + root: tempApp({ "config/database/schema.ts": schemaFile("app") }), + }); + writableEnvBranch.mockResolvedValue(devBranch); + const { client, statements } = recordingPool({ failOn: /DROP SCHEMA/ }); + + await expect(runClean(ctx)).rejects.toThrow("boom"); + expect(statements.slice(-1)).toEqual(["rollback"]); + expect(client.released?.error).toBeInstanceOf(Error); + }); +}); + +describe("previewClean", () => { + test("reads the dependents without opening a transaction or dropping anything", async () => { + const ctx = fakeContext({ + root: tempApp({ "config/database/schema.ts": schemaFile("app") }), + }); + writableEnvBranch.mockResolvedValue(devBranch); + const { statements } = recordingPool({ + dependents: ["constraint refs_fk on table reporting.refs"], + }); + + await expect(previewClean(ctx)).resolves.toEqual({ + branch: devBranch.name, + schemaName: "app", + dependents: ["constraint refs_fk on table reporting.refs"], + }); + expect(statements).toEqual([""]); + }); +}); + +describe("deleteSessionBranch", () => { + const session = { + branch: { name: "projects/p/branches/session-abc123-x1" }, + kind: "session", + }; + + test("deletes this checkout's session branch", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(session.branch.name); + resolveEnvBranch.mockResolvedValue(session); + + await expect( + deleteSessionBranch( + fakeContext({ root: tempApp(), api: lakebase.api() }), + ), + ).resolves.toEqual({ branch: session.branch.name }); + expect(lakebase.calls).toEqual([`deleteBranch ${session.branch.name}`]); + }); + + test("keeps your dev branch and says how to delete it", async () => { + resolveEnvBranch.mockResolvedValue({ branch: devBranch, kind: "dev" }); + + await expect( + deleteSessionBranch(fakeContext({ root: tempApp() })), + ).rejects.toThrow( + `Refusing to delete dev-alice-3f9a2c: --delete-branch deletes session branches only, and your dev branch stays for the next \`appkit db init\`. Delete it with \`databricks postgres delete-branch ${devBranch.name}\`.`, + ); + }); + + test("refuses any other branch, and a .env without one", async () => { + resolveEnvBranch.mockResolvedValueOnce({ + branch: { name: "projects/p/branches/production" }, + kind: "default", + reason: "it is the project's default branch", + }); + const ctx = fakeContext({ root: tempApp() }); + + await expect(deleteSessionBranch(ctx)).rejects.toThrow( + "Refusing to delete the branch: production is not your dev or session branch (it is the project's default branch).", + ); + resolveEnvBranch.mockResolvedValueOnce(null); + await expect(deleteSessionBranch(ctx)).rejects.toThrow( + /^Did not delete the branch: no branch is configured in \.env/, + ); + }); +}); + +describe("runSeed", () => { + test("runs config/database/seed.sql in one transaction on your branch, app schema first", async () => { + const sql = + "insert into app.notes default values;\ninsert into app.notes default values;\n"; + const root = tempApp({ [SEED_FILE]: sql }); + writableEnvBranch.mockResolvedValue(devBranch); + const { statements } = recordingPool(); + + await expect(runSeed(fakeContext({ root }))).resolves.toEqual({ + branch: devBranch.name, + file: path.join(root, SEED_FILE), + }); + expect(writableEnvBranch).toHaveBeenCalledWith(expect.anything(), "seed"); + expect(statements).toEqual([ + "begin", + 'SET LOCAL search_path TO "app", public', + sql, + "commit", + ]); + }); + + test.each([ + ["sales", 'SET LOCAL search_path TO "sales", public'], + ["public", "SET LOCAL search_path TO public"], + ])( + "with schema.ts on %s, unqualified names resolve there", + async (schemaName, searchPath) => { + const root = tempApp({ + [SEED_FILE]: "insert into notes default values;", + "config/database/schema.ts": schemaFile(schemaName), + }); + writableEnvBranch.mockResolvedValue(devBranch); + const { statements } = recordingPool(); + + await runSeed(fakeContext({ root })); + + expect(statements.slice(0, 2)).toEqual(["begin", searchPath]); + }, + ); + + test("a missing seed file is an error, before any API call", async () => { + await expect(runSeed(fakeContext({ root: tempApp() }))).rejects.toThrow( + "No seed file at config/database/seed.sql", + ); + expect(writableEnvBranch).not.toHaveBeenCalled(); + }); + + test("refuses a branch that is not yours before connecting", async () => { + const root = tempApp({ [SEED_FILE]: "select 1;" }); + writableEnvBranch.mockRejectedValue(refusal("seed")); + + await expect(runSeed(fakeContext({ root }))).rejects.toThrow( + /^Refusing to seed: /, + ); + expect(withBranchPool).not.toHaveBeenCalled(); + expect(fs.existsSync(path.join(root, SEED_FILE))).toBe(true); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/clean.pg.test.ts b/packages/appkit/src/database/tooling/tests/clean.pg.test.ts new file mode 100644 index 000000000..646502e92 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/clean.pg.test.ts @@ -0,0 +1,164 @@ +import { randomUUID } from "node:crypto"; + +import { Pool } from "pg"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; + +import { inTransaction } from "../../migrations/apply"; +import { cleanStatements, readCascadeDependents } from "../clean"; + +// The clean SQL against a real server, as a superuser that may create +// databases and roles, e.g. APPKIT_TEST_PG_URL=postgres://localhost:5432/postgres +const url = process.env.APPKIT_TEST_PG_URL; + +async function clean(pool: Pool, schemaName: string): Promise { + const client = await pool.connect(); + try { + return await inTransaction(client, async () => { + const dependents = await readCascadeDependents(client, schemaName); + for (const statement of cleanStatements(schemaName)) { + await client.query(statement); + } + return dependents; + }); + } finally { + client.release(); + } +} + +async function names(pool: Pool, sql: string): Promise { + const { rows } = await pool.query<{ name: string }>(sql); + return rows.map((row) => row.name); +} + +describe.skipIf(!url)("clean against Postgres", () => { + const suffix = randomUUID().slice(0, 8); + + describe("an app schema", () => { + const app = `appkit_clean_${suffix}`; + const other = `appkit_reporting_${suffix}`; + let pool: Pool; + + beforeAll(async () => { + pool = new Pool({ connectionString: url, max: 1 }); + await pool.query(` + create schema "${app}"; + create type "${app}".kind as enum ('a', 'b'); + create table "${app}".notes (id integer primary key, kind "${app}".kind); + create table "${app}".__drizzle_migrations (id serial primary key); + create schema "${other}"; + create view "${other}".recent as select id from "${app}".notes; + create table "${other}".refs (id integer primary key, note_id integer constraint refs_note_fk references "${app}".notes (id)); + create table "${other}".tagged (id integer primary key, kind "${app}".kind); + `); + }); + afterAll(async () => { + await pool.query(`drop schema if exists "${app}" cascade`); + await pool.query(`drop schema if exists "${other}" cascade`); + await pool.end(); + }); + + test("reports what CASCADE drops outside the schema, then drops the schema and only those", async () => { + const dependents = await clean(pool, app); + + expect(dependents).toEqual([ + `column kind of table ${other}.tagged`, + `constraint refs_note_fk on table ${other}.refs`, + `view ${other}.recent`, + ]); + expect( + await names( + pool, + `select nspname as name from pg_namespace where nspname = '${app}'`, + ), + ).toEqual([]); + expect( + await names( + pool, + `select relname as name from pg_class where relnamespace = '"${other}"'::regnamespace and relkind in ('r', 'v') order by 1`, + ), + ).toEqual(["refs", "tagged"]); + }); + }); + + describe("schema public", () => { + const database = `appkit_clean_${suffix}`; + const role = `appkit_other_${suffix}`; + let admin: Pool; + let pool: Pool; + + beforeAll(async () => { + admin = new Pool({ connectionString: url, max: 1 }); + await admin.query(`create database "${database}"`); + await admin.query(`create role "${role}"`); + const scratch = new URL(url as string); + scratch.pathname = `/${database}`; + pool = new Pool({ connectionString: scratch.toString(), max: 1 }); + await pool.query(` + create extension citext; + create extension tablefunc; + create type public.kind as enum ('a', 'b'); + create domain public.positive as integer check (value > 0); + create type public.pair as (a integer, b integer); + create table public.notes (id integer primary key, body citext, kind public.kind); + create table public.__drizzle_migrations (id serial primary key); + create function public.touch() returns integer language sql as 'select 1'; + create aggregate public.total(integer) (sfunc = int4pl, stype = integer); + create aggregate public.tally(*) (sfunc = int8inc, stype = bigint, initcond = '0'); + grant select on public.notes to "${role}"; + grant create on schema public to "${role}"; + set role "${role}"; + create view public.their_view as select id from public.notes; + reset role; + `); + }); + afterAll(async () => { + await pool.end(); + await admin.query(`drop database if exists "${database}"`); + await admin.query(`drop role if exists "${role}"`); + await admin.end(); + }); + + test("drops the role's own objects and keeps the extensions' and other roles' objects it does not depend on", async () => { + const extensionTypes = await names( + pool, + `select typname as name from pg_type t join pg_depend d on d.objid = t.oid and d.classid = 'pg_type'::regclass and d.deptype = 'e' order by 1`, + ); + expect(extensionTypes).toContain("citext"); + expect(extensionTypes).toContain("tablefunc_crosstab_2"); + + const dependents = await clean(pool, "public"); + + expect(dependents).toEqual(["view their_view"]); + expect( + await names( + pool, + `select relname as name from pg_class where relnamespace = 'public'::regnamespace and relkind in ('r', 'v', 'S')`, + ), + ).toEqual([]); + expect( + await names( + pool, + `select typname as name from pg_type where typnamespace = 'public'::regnamespace and typname in ('kind', 'positive', 'pair') `, + ), + ).toEqual([]); + expect( + await names( + pool, + `select proname as name from pg_proc where pronamespace = 'public'::regnamespace and proname in ('touch', 'total', 'tally')`, + ), + ).toEqual([]); + expect( + await names( + pool, + `select typname as name from pg_type where typnamespace = 'public'::regnamespace and typname in ('citext', 'tablefunc_crosstab_2') order by 1`, + ), + ).toEqual(["citext", "tablefunc_crosstab_2"]); + expect( + await names( + pool, + `select proname as name from pg_proc where pronamespace = 'public'::regnamespace and proname = 'crosstab' limit 1`, + ), + ).toEqual(["crosstab"]); + }); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/contract.test.ts b/packages/appkit/src/database/tooling/tests/contract.test.ts index 192305dcf..ed47a4f7a 100644 --- a/packages/appkit/src/database/tooling/tests/contract.test.ts +++ b/packages/appkit/src/database/tooling/tests/contract.test.ts @@ -10,8 +10,13 @@ const exports: DatabaseTooling = tooling; const contractKeys = { createDbContext: true, + deleteSessionBranch: true, + previewClean: true, + runClean: true, + runInit: true, runIntrospect: true, runMigrate: true, + runSeed: true, } satisfies Record; test("every function the CLI is typed with is exported", () => { diff --git a/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts b/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts new file mode 100644 index 000000000..6e3293f0c --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts @@ -0,0 +1,74 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { drizzleKitInstall, ensureDrizzleKit } from "../drizzle-kit-install"; +import { DRIZZLE_KIT_VERSION } from "../migrations"; +import { cleanupTempApps, tempApp } from "./fakes"; + +afterEach(cleanupTempApps); + +const SPEC = `drizzle-kit@${DRIZZLE_KIT_VERSION}`; + +describe("drizzleKitInstall", () => { + test.each([ + ["pnpm-lock.yaml", "pnpm", ["add", "-D", "-E", SPEC]], + ["yarn.lock", "yarn", ["add", "-D", "-E", SPEC]], + ["bun.lock", "bun", ["add", "-d", "--exact", SPEC]], + [ + "package-lock.json", + "npm", + ["install", "--save-dev", "--save-exact", SPEC], + ], + ])("%s installs with %s, pinned", (lockfile, command, args) => { + expect(drizzleKitInstall(tempApp({ [lockfile]: "" }))).toEqual({ + command, + args, + }); + }); + + test("a workspace member uses the lockfile of the workspace root", () => { + const root = tempApp({ + "pnpm-lock.yaml": "", + "apps/web/package.json": "{}", + }); + expect(drizzleKitInstall(path.join(root, "apps/web")).command).toBe("pnpm"); + }); +}); + +describe("ensureDrizzleKit", () => { + test("installs into the app when it cannot resolve drizzle-kit, and reports the command", () => { + const root = tempApp({ "package.json": "{}", "yarn.lock": "" }); + const run = vi.fn(); + const steps: string[] = []; + + expect(ensureDrizzleKit(root, run, (step) => steps.push(step))).toBe( + `yarn add -D -E ${SPEC}`, + ); + expect(run).toHaveBeenCalledWith("yarn", ["add", "-D", "-E", SPEC], root); + expect(steps).toEqual([ + `Installing drizzle-kit ${DRIZZLE_KIT_VERSION}, which writes migrations (yarn add -D -E ${SPEC})`, + ]); + }); + + test("does nothing when drizzle-kit resolves, or there is no package.json", () => { + const run = vi.fn(); + const installed = tempApp({ + "package.json": "{}", + "node_modules/drizzle-kit/package.json": JSON.stringify({ + name: "drizzle-kit", + version: "0.30.0", + main: "index.js", + }), + "node_modules/drizzle-kit/index.js": "", + }); + + expect(ensureDrizzleKit(installed, run, () => undefined)).toBeNull(); + expect(ensureDrizzleKit(tempApp(), run, () => undefined)).toBeNull(); + expect(run).not.toHaveBeenCalled(); + expect(fs.existsSync(path.join(installed, "package-lock.json"))).toBe( + false, + ); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/env-file.test.ts b/packages/appkit/src/database/tooling/tests/env-file.test.ts new file mode 100644 index 000000000..35bfee92d --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/env-file.test.ts @@ -0,0 +1,181 @@ +import fs from "node:fs"; +import path from "node:path"; + +import dotenv from "dotenv"; +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { updateEnvFile } from "../env-file"; +import { cleanupTempApps, tempApp } from "./fakes"; + +afterEach(cleanupTempApps); + +describe("updateEnvFile", () => { + test("replaces values in place, keeps comments and order, appends new keys", () => { + const root = tempApp({ + ".env": [ + "# Databricks", + "DATABRICKS_CONFIG_PROFILE=DEFAULT", + "PGHOST='old-host'", + "", + "# keep me", + "LAKEBASE_ENDPOINT=projects/p/branches/old/endpoints/primary", + "APPKIT_DB_SESSION=abc", + "PGHOST=duplicate", + ].join("\n"), + }); + const file = path.join(root, ".env"); + + updateEnvFile(file, { + PGHOST: "new-host.example.com", + LAKEBASE_ENDPOINT: "projects/p/branches/dev-a/endpoints/primary", + OTHER_KEY: "value", + }); + + expect(fs.readFileSync(file, "utf-8")).toBe( + [ + "# Databricks", + "DATABRICKS_CONFIG_PROFILE=DEFAULT", + "PGHOST=new-host.example.com", + "", + "# keep me", + "LAKEBASE_ENDPOINT=projects/p/branches/dev-a/endpoints/primary", + "APPKIT_DB_SESSION=abc", + "OTHER_KEY=value", + "", + ].join("\n"), + ); + expect(fs.statSync(file).mode & 0o777).toBe(0o600); + }); + + test("a missing .env gets only the given keys, never .env.example's placeholders", () => { + const root = tempApp({ + ".env.example": "DATABRICKS_HOST=https://your-workspace\nPGPORT=5432\n", + }); + const file = path.join(root, ".env"); + + updateEnvFile(file, { PGHOST: "h.example.com" }); + + expect(fs.readFileSync(file, "utf-8")).toBe("PGHOST=h.example.com\n"); + expect(fs.statSync(file).mode & 0o777).toBe(0o600); + }); + + test("a symbolic link is refused and its target left alone", () => { + const root = tempApp({ "shared.env": "PGHOST=old\n" }); + const file = path.join(root, ".env"); + fs.symlinkSync(path.join(root, "shared.env"), file); + + expect(() => updateEnvFile(file, { PGHOST: "new" })).toThrow( + `Refusing to rewrite ${file}: it is a symbolic link to ${path.join(root, "shared.env")}, and writing through it would change that file. Replace it with a regular file, then rerun.`, + ); + expect(fs.readFileSync(path.join(root, "shared.env"), "utf-8")).toBe( + "PGHOST=old\n", + ); + expect(fs.lstatSync(file).isSymbolicLink()).toBe(true); + }); + + test("a multi-line quoted value is one entry: replaced whole, or kept whole", () => { + const root = tempApp({ + ".env": [ + 'PGHOST="first', + "PGHOST=not-a-key", + 'still the value"', + 'CERT="-----BEGIN-----', + "PGPORT=1", + '-----END-----"', + "PGPORT=5432", + ].join("\n"), + }); + const file = path.join(root, ".env"); + + updateEnvFile(file, { PGHOST: "new.example.com", PGPORT: "6543" }); + + const text = fs.readFileSync(file, "utf-8"); + expect(text).toBe( + [ + "PGHOST=new.example.com", + 'CERT="-----BEGIN-----', + "PGPORT=1", + '-----END-----"', + "PGPORT=6543", + "", + ].join("\n"), + ); + expect(dotenv.parse(text)).toEqual({ + PGHOST: "new.example.com", + CERT: "-----BEGIN-----\nPGPORT=1\n-----END-----", + PGPORT: "6543", + }); + }); + + test("a value whose quote never closes is a single line, as dotenv reads it", () => { + const root = tempApp({ ".env": 'NOTE="open\nPGHOST=old\n' }); + const file = path.join(root, ".env"); + + updateEnvFile(file, { PGHOST: "new" }); + + expect(fs.readFileSync(file, "utf-8")).toBe('NOTE="open\nPGHOST=new\n'); + }); + + test("a failed write leaves the old file and no temporary file", () => { + const root = tempApp({ ".env": "PGHOST=old\n" }); + const file = path.join(root, ".env"); + const rename = vi.spyOn(fs, "renameSync").mockImplementation(() => { + throw new Error("disk full"); + }); + try { + expect(() => updateEnvFile(file, { PGHOST: "new" })).toThrow("disk full"); + } finally { + rename.mockRestore(); + } + + expect(fs.readFileSync(file, "utf-8")).toBe("PGHOST=old\n"); + expect(fs.readdirSync(root)).toEqual([".env"]); + }); + + test("quotes values that need it", () => { + const root = tempApp(); + const file = path.join(root, ".env"); + updateEnvFile(file, { A: "has space", B: "plain@example.com" }); + expect(fs.readFileSync(file, "utf-8")).toBe( + 'A="has space"\nB=plain@example.com\n', + ); + }); + + test("keeps export prefixes and CRLF line endings", () => { + const root = tempApp({ + ".env": "# keep\r\nexport PGHOST=old\r\nPGPORT=5432\r\n", + }); + const file = path.join(root, ".env"); + + updateEnvFile(file, { PGHOST: "new.example.com", PGUSER: "a@example.com" }); + + expect(fs.readFileSync(file, "utf-8")).toBe( + "# keep\r\nexport PGHOST=new.example.com\r\nPGPORT=5432\r\nPGUSER=a@example.com\r\n", + ); + }); + + test("every value stays on one line and reads back unchanged", () => { + const root = tempApp({ ".env": "KEEP=1\n" }); + const file = path.join(root, ".env"); + const values = { + NEWLINE: "line1\nline2\r\nINJECTED=1", + QUOTES: 'say "hi"', + BACKSLASH: "back\\slash", + }; + + updateEnvFile(file, values); + + const text = fs.readFileSync(file, "utf-8"); + expect(text.split("\n").filter(Boolean)).toHaveLength(4); + expect(dotenv.parse(text)).toEqual({ KEEP: "1", ...values }); + }); + + test("a value dotenv cannot read back unchanged is refused", () => { + const root = tempApp(); + const file = path.join(root, ".env"); + expect(() => updateEnvFile(file, { BAD: `it's "x"\ny` })).toThrow( + "Cannot write BAD to .env: its value mixes quotes, backslashes and line breaks.", + ); + expect(fs.existsSync(file)).toBe(false); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/fakes.ts b/packages/appkit/src/database/tooling/tests/fakes.ts index ceaf6006a..d7e829fa4 100644 --- a/packages/appkit/src/database/tooling/tests/fakes.ts +++ b/packages/appkit/src/database/tooling/tests/fakes.ts @@ -4,16 +4,27 @@ import path from "node:path"; import type { DbContext } from "../context"; import type { + BranchSpec, LakebaseApi, LakebaseBranch, + LakebaseDatabase, LakebaseEndpoint, + LakebaseRole, + RoleSpec, } from "../lakebase-api"; +import { LakebaseApiError } from "../lakebase-api"; -/** In-memory Lakebase: the branches the guard looks up, and their endpoints. */ +/** In-memory Lakebase with the semantics init relies on: forks copy roles, endpoints come with new forks. */ export class FakeLakebase { readonly branches = new Map(); readonly endpoints = new Map(); + readonly roles = new Map(); + readonly databases = new Map(); readonly calls: string[] = []; + /** New forks get a read-write `primary` endpoint, like Lakebase forks do. */ + autoEndpoint = true; + createBranchError?: Error; + deleteRoleError?: Error; addBranch( name: string, @@ -22,13 +33,29 @@ export class FakeLakebase { const branch = { name, status: { current_state: "READY", ...status } }; this.branches.set(name, branch); this.endpoints.set(name, [this.endpoint(name, "primary")]); + this.roles.set(name, []); return branch; } + addRole( + branch: string, + roleId: string, + postgresRole: string, + memberships: string[] = [], + ) { + const role: LakebaseRole = { + name: `${branch}/roles/${roleId}`, + status: { postgres_role: postgresRole, membership_roles: memberships }, + }; + this.roles.get(branch)?.push(role); + return role; + } + endpoint(branch: string, id: string): LakebaseEndpoint { return { name: `${branch}/endpoints/${id}`, status: { + endpoint_type: "ENDPOINT_TYPE_READ_WRITE", hosts: { host: `${id}.${branch.split("/").pop()}.example.com` }, }, }; @@ -50,11 +77,120 @@ export class FakeLakebase { ?.find((endpoint) => endpoint.name === name) ?? null ); }, + async listBranches(project: string) { + fake.calls.push(`listBranches ${project}`); + return [...fake.branches.values()].filter((b) => + b.name.startsWith(`${project}/`), + ); + }, + async createBranch(project: string, branchId: string, spec: BranchSpec) { + fake.calls.push(`createBranch ${branchId} ${JSON.stringify(spec)}`); + if (fake.createBranchError) throw fake.createBranchError; + const name = `${project}/branches/${branchId}`; + if (fake.branches.has(name)) { + throw new LakebaseApiError( + `create branch ${name}`, + "ALREADY_EXISTS", + { + statusCode: 409, + errorCode: "ALREADY_EXISTS", + }, + ); + } + const ttlSeconds = "ttl" in spec ? Number.parseInt(spec.ttl, 10) : 0; + const branch: LakebaseBranch = { + name, + status: { + current_state: "READY", + source_branch: spec.source_branch, + ...(ttlSeconds + ? { + expire_time: new Date( + Date.now() + ttlSeconds * 1000, + ).toISOString(), + } + : {}), + }, + }; + fake.branches.set(name, branch); + fake.endpoints.set( + name, + fake.autoEndpoint ? [fake.endpoint(name, "primary")] : [], + ); + // A fork copies the parent's roles. + fake.roles.set( + name, + (fake.roles.get(spec.source_branch) ?? []).map((role) => ({ + ...role, + name: `${name}/roles/${role.name.split("/").pop()}`, + })), + ); + return branch; + }, + async listEndpoints(branch: string) { + fake.calls.push(`listEndpoints ${branch}`); + return fake.endpoints.get(branch) ?? []; + }, + async createEndpoint( + branch: string, + endpointId: string, + options: { suspendTimeout: string }, + ) { + fake.calls.push( + `createEndpoint ${branch} ${endpointId} suspend=${options.suspendTimeout}`, + ); + const endpoint = fake.endpoint(branch, endpointId); + fake.endpoints.set(branch, [ + ...(fake.endpoints.get(branch) ?? []), + endpoint, + ]); + return endpoint; + }, + async getDatabase(name: string) { + fake.calls.push(`getDatabase ${name}`); + return fake.databases.get(name) ?? null; + }, + async listRoles(branch: string) { + fake.calls.push(`listRoles ${branch}`); + return [...(fake.roles.get(branch) ?? [])]; + }, + async createRole(branch: string, spec: RoleSpec) { + fake.calls.push(`createRole ${branch} ${JSON.stringify(spec)}`); + return fake.addRole(branch, "rol-generated", spec.postgres_role, [ + ...spec.membership_roles, + ]); + }, + async setRoleMemberships(role: string, memberships: string[]) { + fake.calls.push(`setRoleMemberships ${role} ${memberships.join(",")}`); + const branch = role.slice(0, role.indexOf("/roles/")); + const found = fake.roles.get(branch)?.find((r) => r.name === role); + if (!found?.status) throw new Error(`no role ${role}`); + found.status.membership_roles = [...memberships]; + return found; + }, + async deleteBranch(name: string) { + fake.calls.push(`deleteBranch ${name}`); + fake.branches.delete(name); + }, + async deleteRole(role: string, options: { reassignOwnedTo: string }) { + fake.calls.push(`deleteRole ${role} → ${options.reassignOwnedTo}`); + if (fake.deleteRoleError) throw fake.deleteRoleError; + const branch = role.slice(0, role.indexOf("/roles/")); + fake.roles.set( + branch, + (fake.roles.get(branch) ?? []).filter((r) => r.name !== role), + ); + }, }; return api as unknown as LakebaseApi; } } +export const forbidden = () => + new LakebaseApiError("create branch", "PERMISSION_DENIED", { + statusCode: 403, + }); + const roots: string[] = []; /** A temp app root with optional files (relative path → contents). */ @@ -78,6 +214,8 @@ export function fakeContext(options: { env?: NodeJS.ProcessEnv; userName?: string; api?: LakebaseApi; + /** The host the client resolved; empty when a test does not care. */ + host?: string; }): DbContext { const userName = options.userName ?? "alice@example.com"; return { @@ -88,6 +226,7 @@ export function fakeContext(options: { throw new Error("no raw API calls expected"); }, currentUser: { me: async () => ({ userName }) }, + getHost: async () => options.host ?? "", }), api: () => { if (!options.api) throw new Error("no Lakebase API calls expected"); diff --git a/packages/appkit/src/database/tooling/tests/guard.test.ts b/packages/appkit/src/database/tooling/tests/guard.test.ts index ee79cbf59..146ad1333 100644 --- a/packages/appkit/src/database/tooling/tests/guard.test.ts +++ b/packages/appkit/src/database/tooling/tests/guard.test.ts @@ -1,7 +1,12 @@ import { afterEach, describe, expect, test } from "vitest"; -import { classifyBranch, resolveEnvBranch, takesWrites } from "../guard"; -import { devBranchId } from "../naming"; +import { + classifyBranch, + resolveEnvBranch, + takesWrites, + writableEnvBranch, +} from "../guard"; +import { devBranchId, sessionBranchId } from "../naming"; import { cleanupTempApps, databricksYml, @@ -15,6 +20,7 @@ afterEach(cleanupTempApps); const USER = "alice@example.com"; const P = "projects/p"; const dev = `${P}/branches/${devBranchId(USER)}`; +const session = `${P}/branches/${sessionBranchId(USER, "k2x9q0ab")}`; function verdict( name: string, @@ -33,9 +39,7 @@ function verdict( describe("classifyBranch", () => { test("only this developer's dev branch and this checkout's session branch take writes", () => { expect(verdict(dev)).toEqual({ kind: "dev" }); - expect(verdict(`${P}/branches/session-k2x9q0ab`)).toEqual({ - kind: "session", - }); + expect(verdict(session)).toEqual({ kind: "session" }); expect(takesWrites("dev")).toBe(true); expect(takesWrites("session")).toBe(true); }); @@ -57,11 +61,14 @@ describe("classifyBranch", () => { verdict(`${P}/branches/${devBranchId("bob@example.com")}`).kind, ).toBe("other"); expect(verdict(`${P}/branches/session-other`).kind).toBe("other"); - expect(verdict(`${P}/branches/session-k2x9q0ab`, {}, null).kind).toBe( - "other", - ); - expect(verdict(`${P}/branches/staging`).reason).toContain( - devBranchId(USER), + expect(verdict(session, {}, null).kind).toBe("other"); + // Bob's .env copied into Alice's checkout names Bob's session branch. + expect( + verdict(`${P}/branches/${sessionBranchId("bob@example.com", "k2x9q0ab")}`) + .kind, + ).toBe("other"); + expect(verdict(`${P}/branches/staging`).reason).toBe( + `it is not your dev branch (${devBranchId(USER)}) or this checkout's session branch (${sessionBranchId(USER, "k2x9q0ab")})`, ); for (const kind of ["default", "protected", "deploy-target", "other"]) { expect(takesWrites(kind as "other")).toBe(false); @@ -170,3 +177,58 @@ describe("resolveEnvBranch", () => { ).rejects.toThrow(/does not exist.*appkit db init/); }); }); + +describe("writableEnvBranch", () => { + const envFor = (branch: string, sessionId?: string) => ({ + PGHOST: "primary.example.com", + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: `${branch}/endpoints/primary`, + ...(sessionId ? { APPKIT_DB_SESSION: sessionId } : {}), + }); + + test("returns your dev or session branch", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(dev); + lakebase.addBranch(session); + + await expect( + writableEnvBranch( + fakeContext({ root: tempApp(), env: envFor(dev), api: lakebase.api() }), + "seed", + ), + ).resolves.toMatchObject({ name: dev }); + await expect( + writableEnvBranch( + fakeContext({ + root: tempApp(), + env: envFor(session, "k2x9q0ab"), + api: lakebase.api(), + }), + "seed", + ), + ).resolves.toMatchObject({ name: session }); + }); + + test("refuses another branch, and says what to run without one", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(`${P}/branches/production`, { default: true }); + + await expect( + writableEnvBranch( + fakeContext({ + root: tempApp(), + env: envFor(`${P}/branches/production`), + api: lakebase.api(), + }), + "clean", + ), + ).rejects.toThrow( + "Refusing to clean: production is not your dev or session branch (it is the project's default branch).", + ); + await expect( + writableEnvBranch(fakeContext({ root: tempApp() }), "seed"), + ).rejects.toThrow( + "Did not seed: no branch is configured in .env (PGHOST, PGDATABASE and LAKEBASE_ENDPOINT); run `appkit db init`.", + ); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts b/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts new file mode 100644 index 000000000..5466c5465 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts @@ -0,0 +1,75 @@ +import { randomUUID } from "node:crypto"; + +import { Pool } from "pg"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; + +import { readRoleBlockers } from "../hand-off"; + +// The pg_shdepend query against a real server, as a superuser that may create +// databases and roles, e.g. APPKIT_TEST_PG_URL=postgres://localhost:5432/postgres +const url = process.env.APPKIT_TEST_PG_URL; + +function databaseUrl(database: string): string { + const next = new URL(url as string); + next.pathname = `/${database}`; + return next.toString(); +} + +describe.skipIf(!url)("readRoleBlockers against Postgres", () => { + const suffix = randomUUID().slice(0, 8); + const role = `appkit_sp_${suffix}`; + const main = `appkit_main_${suffix}`; + const other = `appkit_other_${suffix}`; + const owned = `appkit_owned_${suffix}`; + let admin: Pool; + let mainPool: Pool; + let otherPool: Pool; + + beforeAll(async () => { + admin = new Pool({ connectionString: url, max: 1 }); + await admin.query(`create role "${role}"`); + await admin.query(`create database "${main}"`); + await admin.query(`create database "${other}"`); + await admin.query(`create database "${owned}" owner "${role}"`); + mainPool = new Pool({ connectionString: databaseUrl(main), max: 1 }); + otherPool = new Pool({ connectionString: databaseUrl(other), max: 1 }); + await mainPool.query(` + create schema app authorization "${role}"; + create table app.notes (id integer primary key); + alter table app.notes owner to "${role}"; + create table public.shared (id integer); + grant select on public.shared to "${role}"; + `); + await otherPool.query(` + create table public.reports (id integer); + alter table public.reports owner to "${role}"; + `); + }); + afterAll(async () => { + await mainPool.end(); + await otherPool.end(); + for (const database of [main, other, owned]) { + await admin.query(`drop database if exists "${database}"`); + } + await admin.query(`drop role if exists "${role}"`); + await admin.end(); + }); + + test("lists what outlives a reassign in this database: other databases' objects, shared objects, and grants", async () => { + const blockers = await readRoleBlockers(mainPool, role); + + expect(blockers).toEqual( + [ + { database: "", count: 1 }, + { database: main, count: 1 }, + { database: other, count: 1 }, + ].sort((a, b) => a.database.localeCompare(b.database)), + ); + }); + + test("a role without dependencies has no blockers", async () => { + await expect( + readRoleBlockers(mainPool, `appkit_missing_${suffix}`), + ).resolves.toEqual([]); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/identity.test.ts b/packages/appkit/src/database/tooling/tests/identity.test.ts index cc49fcc56..ef76b6f3e 100644 --- a/packages/appkit/src/database/tooling/tests/identity.test.ts +++ b/packages/appkit/src/database/tooling/tests/identity.test.ts @@ -1,11 +1,18 @@ import { afterEach, describe, expect, test, vi } from "vitest"; -import { currentIdentity } from "../identity"; +import { currentIdentity, identityTypeOf } from "../identity"; import { cleanupTempApps, fakeContext, tempApp } from "./fakes"; afterEach(cleanupTempApps); describe("identity", () => { + test("an email is a USER, a client ID is a SERVICE_PRINCIPAL", () => { + expect(identityTypeOf("alice@example.com")).toBe("USER"); + expect(identityTypeOf("11111111-2222-3333-4444-555555555555")).toBe( + "SERVICE_PRINCIPAL", + ); + }); + test("currentUser.me() is called once per context", async () => { const ctx = fakeContext({ root: tempApp() }); const me = vi.fn(async (_request: object) => ({ @@ -16,6 +23,7 @@ describe("identity", () => { await expect(currentIdentity(counted)).resolves.toEqual({ userName: "alice@example.com", + identityType: "USER", }); await currentIdentity(counted); expect(me).toHaveBeenCalledOnce(); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts new file mode 100644 index 000000000..0f0bb38ba --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -0,0 +1,838 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { runClean, runIntrospect, runMigrate, withBranchPool } = vi.hoisted( + () => ({ + runClean: vi.fn(), + runIntrospect: vi.fn(), + runMigrate: vi.fn(), + withBranchPool: vi.fn(), + }), +); + +vi.mock("../context", async (importOriginal) => ({ + ...(await importOriginal()), + withBranchPool, +})); +vi.mock("../migrate", async (importOriginal) => ({ + ...(await importOriginal()), + runMigrate, +})); +vi.mock("../clean", () => ({ runClean })); +vi.mock("../introspect", () => ({ runIntrospect })); + +import type { DbContext } from "../context"; +import { type InitOptions, runInit } from "../init"; +import { LakebaseApiError } from "../lakebase-api"; +import { DRIZZLE_KIT_VERSION } from "../migrations"; +import { devBranchId, sessionBranchId } from "../naming"; +import { + cleanupTempApps, + databricksYml, + FakeLakebase, + fakeContext, + forbidden, + tempApp, +} from "./fakes"; + +const USER = "alice@example.com"; +const SP = "11111111-2222-3333-4444-555555555555"; +const P = "projects/p"; +const PRODUCTION = `${P}/branches/production`; +const DEV = `${P}/branches/${devBranchId(USER)}`; +const session = (id: string) => `${P}/branches/${sessionBranchId(USER, id)}`; +const migrateReport = { + generated: null, + applied: [], + typesFile: "/app/shared/appkit-types/database.d.ts", +}; + +/** What the hand-off reads on the branch: the app schema's owner, and what blocks deleting that role. */ +let schemaOwner: string | null; +let blockers: { database: string; count: number }[]; +const queries: string[] = []; +const pool = { + query: vi.fn(async (text: string) => { + queries.push(text); + if (text.includes("nspowner")) { + return { rows: [{ owner: schemaOwner, current_user: USER }] }; + } + if (text.includes("pg_shdepend")) return { rows: blockers }; + throw new Error(`unexpected query ${text}`); + }), +}; + +function project(): FakeLakebase { + const lakebase = new FakeLakebase(); + lakebase.addBranch(PRODUCTION, { default: true }); + lakebase.addRole(PRODUCTION, "alice", USER, ["DATABRICKS_SUPERUSER"]); + lakebase.addRole(PRODUCTION, `dbrx-apps-${SP}`, SP); + lakebase.addRole(PRODUCTION, "dbrx-apps-user-bob", "bob@example.com"); + return lakebase; +} + +/** An app that deploys to `deploy` (the default branch unless set), with .env pointing at the default branch. */ +function appOn( + lakebase: FakeLakebase, + env: Record = {}, + { + schema = true, + deploy = PRODUCTION, + files = {}, + }: { schema?: boolean; deploy?: string; files?: Record } = {}, +): DbContext { + const dotenv = { + DATABRICKS_CONFIG_PROFILE: "DEFAULT", + PGHOST: "primary.production.example.com", + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: `${PRODUCTION}/endpoints/primary`, + ...env, + }; + const root = tempApp({ + ".env": `# Lakebase\n${Object.entries(dotenv) + .map(([key, value]) => `${key}=${value}`) + .join("\n")}\n`, + "databricks.yml": databricksYml( + deploy, + `${deploy}/databases/databricks-postgres`, + ), + ...(schema ? { "config/database/schema.ts": schemaSource("app") } : {}), + ...files, + }); + return fakeContext({ + root, + env: dotenv, + userName: USER, + api: lakebase.api(), + }); +} + +const builder = path.resolve( + import.meta.dirname, + "../../schema-builder/index.ts", +); +function schemaSource(schemaName: string): string { + return `import { defineSchema, id } from ${JSON.stringify(builder)}; +export const schema = defineSchema(({ table }) => ({ notes: table("notes", { id: id() }) }), { schemaName: ${JSON.stringify(schemaName)} }); +`; +} + +function envFile(root: string): Record { + return Object.fromEntries( + fs + .readFileSync(path.join(root, ".env"), "utf-8") + .split("\n") + .filter((line) => line.includes("=")) + .map((line) => [ + line.slice(0, line.indexOf("=")), + line.slice(line.indexOf("=") + 1), + ]), + ); +} + +/** Run init, collecting its progress lines. */ +async function init(ctx: DbContext, options: InitOptions = {}) { + const steps: string[] = []; + const report = await runInit(ctx, { + ...options, + onStep: (step) => steps.push(step), + }); + return { report, steps }; +} + +function conflict(name: string): LakebaseApiError { + return new LakebaseApiError(`create branch ${name}`, "ALREADY_EXISTS", { + statusCode: 409, + errorCode: "ALREADY_EXISTS", + }); +} + +beforeEach(() => { + schemaOwner = SP; + blockers = []; + queries.length = 0; + pool.query.mockClear(); + withBranchPool + .mockReset() + .mockImplementation((_ctx, fn: (p: unknown) => unknown) => fn(pool)); + runMigrate.mockReset().mockResolvedValue(migrateReport); + runClean.mockReset().mockResolvedValue({ + branch: DEV, + schemaName: "app", + dependents: [], + }); + runIntrospect.mockReset().mockResolvedValue({ branch: DEV, tables: [] }); +}); +afterEach(cleanupTempApps); + +describe("runInit — dev branch", () => { + test("forks the default branch with no expiry, hands the app schema to you, rewrites .env, migrates", async () => { + const lakebase = project(); + const ctx = appOn(lakebase); + + const { report, steps } = await init(ctx); + + expect(lakebase.calls).toContain( + `createBranch ${devBranchId(USER)} ${JSON.stringify({ source_branch: PRODUCTION, no_expiry: true })}`, + ); + // Only the owner of the app schema is deleted; Bob's copied role stays. + expect( + lakebase.calls.filter((call) => call.startsWith("deleteRole")), + ).toEqual([`deleteRole ${DEV}/roles/dbrx-apps-${SP} → ${DEV}/roles/alice`]); + expect(report).toMatchObject({ + mode: "dev", + branch: DEV, + created: true, + sourceBranch: PRODUCTION, + expireTime: null, + endpoint: `${DEV}/endpoints/primary`, + endpointCreated: false, + host: `primary.${devBranchId(USER)}.example.com`, + database: "databricks_postgres", + user: USER, + role: { name: `${DEV}/roles/alice`, action: "kept" }, + handedOff: SP, + installed: null, + start: { kind: "migrate", migrate: migrateReport }, + }); + expect(steps).toEqual([ + `Creating ${devBranchId(USER)} from production`, + `Pointing .env at ${devBranchId(USER)}, database databricks_postgres`, + `Handing schema app in database databricks_postgres on ${devBranchId(USER)} to you: deleting this branch's copy of role ${SP}, which owns it, with its objects reassigned to you`, + `Migrating schema app on ${devBranchId(USER)}`, + ]); + + const written = envFile(ctx.root); + expect(written).toEqual({ + DATABRICKS_CONFIG_PROFILE: "DEFAULT", + LAKEBASE_PROJECT: P, + PGHOST: `primary.${devBranchId(USER)}.example.com`, + LAKEBASE_ENDPOINT: `${DEV}/endpoints/primary`, + PGDATABASE: "databricks_postgres", + PGUSER: USER, + PGPORT: "5432", + PGSSLMODE: "require", + }); + expect(fs.readFileSync(path.join(ctx.root, ".env"), "utf-8")).toMatch( + /^# Lakebase\n/, + ); + // Migrate runs against the new branch; the caller's environment is left alone. + const [migrateCtx, migrateOptions] = runMigrate.mock.calls[0] ?? []; + expect(migrateCtx.env.LAKEBASE_ENDPOINT).toBe(`${DEV}/endpoints/primary`); + expect(migrateOptions).toEqual({ interactive: false }); + expect(ctx.env.LAKEBASE_ENDPOINT).toBe(`${PRODUCTION}/endpoints/primary`); + }); + + test("a re-run reuses the dev branch; when you own the app schema there is no hand-off", async () => { + const lakebase = project(); + lakebase.addBranch(DEV); + lakebase.addRole(DEV, "alice", USER, ["DATABRICKS_SUPERUSER"]); + lakebase.addRole(DEV, `dbrx-apps-${SP}`, SP); + schemaOwner = USER; + + const { report, steps } = await init(appOn(lakebase), { schema: "none" }); + + expect(report).toMatchObject({ + created: false, + handedOff: null, + start: { kind: "none" }, + }); + expect(steps[0]).toBe(`Using ${devBranchId(USER)}`); + expect( + lakebase.calls.some((call) => + /^(createBranch|deleteRole|createRole|createEndpoint)/.test(call), + ), + ).toBe(false); + expect(queries.some((text) => text.includes("pg_shdepend"))).toBe(false); + }); + + test("the hand-off reads the schema schema.ts names", async () => { + const lakebase = project(); + const ctx = appOn(lakebase, {}, { schema: false }); + fs.mkdirSync(path.join(ctx.root, "config/database"), { recursive: true }); + fs.writeFileSync( + path.join(ctx.root, "config/database/schema.ts"), + schemaSource("sales"), + ); + + const { steps } = await init(ctx, { schema: "none" }); + + expect(pool.query).toHaveBeenCalledWith( + expect.stringContaining("nspowner"), + ["sales"], + ); + expect(steps).toContain( + `Handing schema sales in database databricks_postgres on ${devBranchId(USER)} to you: deleting this branch's copy of role ${SP}, which owns it, with its objects reassigned to you`, + ); + }); + + test("creates a read-write endpoint that scales to zero after 5 idle minutes when the branch has none", async () => { + const lakebase = project(); + lakebase.autoEndpoint = false; + + const { report, steps } = await init(appOn(lakebase), { schema: "none" }); + + expect(lakebase.calls).toContain( + `createEndpoint ${DEV} primary suspend=300s`, + ); + expect(report.endpointCreated).toBe(true); + expect(steps).toContain( + `Creating a read-write endpoint on ${devBranchId(USER)} that suspends after 5 idle minutes`, + ); + }); + + test("creates your role when missing, and adds the superuser membership to one without it", async () => { + schemaOwner = USER; + const lakebase = new FakeLakebase(); + lakebase.addBranch(PRODUCTION, { default: true }); + + const created = await init(appOn(lakebase), { schema: "none" }); + expect(created.report.role.action).toBe("created"); + expect(lakebase.calls).toContain( + `createRole ${DEV} ${JSON.stringify({ identity_type: "USER", postgres_role: USER, auth_method: "LAKEBASE_OAUTH_V1", membership_roles: ["DATABRICKS_SUPERUSER"] })}`, + ); + + const other = new FakeLakebase(); + other.addBranch(PRODUCTION, { default: true }); + other.addBranch(DEV); + other.addRole(DEV, "alice", USER, []); + const updated = await init(appOn(other), { schema: "none" }); + expect(updated.report.role.action).toBe("updated"); + expect(other.calls).toContain( + `setRoleMemberships ${DEV}/roles/alice DATABRICKS_SUPERUSER`, + ); + }); + + test("a 403 on branch creation names the CAN MANAGE requirement", async () => { + const lakebase = project(); + lakebase.createBranchError = forbidden(); + + await expect(init(appOn(lakebase))).rejects.toThrow( + `Creating ${devBranchId(USER)} needs CAN MANAGE on ${P}. Ask a project owner for it, then rerun \`appkit db init\`.`, + ); + }); + + test("when another run creates the dev branch first, the 409 reuses it", async () => { + const lakebase = project(); + const api = lakebase.api(); + const create = api.createBranch.bind(api); + api.createBranch = async (...args) => { + await create(...args); + throw conflict(DEV); + }; + const app = appOn(lakebase); + const ctx = fakeContext({ + root: app.root, + env: app.env, + userName: USER, + api, + }); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report).toMatchObject({ branch: DEV, created: false }); + }); + + test("a deleted dev branch, or a 409 for one that is gone, says so instead of forking again", async () => { + const deleted = project(); + deleted.addBranch(DEV, { current_state: "DELETED" }); + await expect(init(appOn(deleted))).rejects.toThrow( + `Your dev branch ${DEV} 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.`, + ); + + const held = project(); + held.createBranchError = conflict(DEV); + await expect(init(appOn(held))).rejects.toThrow( + `Your dev branch ${DEV} was deleted or expired.`, + ); + }); +}); + +describe("runInit — branch limit", () => { + test("stops before creating anything and lists your other branches with the delete command", async () => { + const lakebase = project(); + const old = session("old1"); + lakebase.addBranch(old, { expire_time: "2099-01-01T00:00:00Z" }); + lakebase.addBranch( + `${P}/branches/${sessionBranchId("bob@example.com", "b1")}`, + ); + lakebase.createBranchError = new LakebaseApiError( + "create branch", + "unarchived branches limit exceeded [TraceId: abc]", + { statusCode: 400, errorCode: "BAD_REQUEST" }, + ); + const ctx = appOn(lakebase); + const before = fs.readFileSync(path.join(ctx.root, ".env"), "utf-8"); + + await expect(init(ctx)).rejects.toThrow( + `Project ${P} is at its branch limit, so init created nothing. Delete one of your other branches, then rerun \`appkit db init\`:\n databricks postgres delete-branch ${old} # expires 2099-01-01T00:00:00Z`, + ); + expect(fs.readFileSync(path.join(ctx.root, ".env"), "utf-8")).toBe(before); + }); + + test("with none of your own, it says to ask a project owner", async () => { + const lakebase = project(); + lakebase.createBranchError = new LakebaseApiError( + "create branch", + "unarchived branches limit exceeded", + { statusCode: 400 }, + ); + + await expect(init(appOn(lakebase))).rejects.toThrow( + "none of its branches are yours. Ask a project owner to delete unused branches", + ); + }); +}); + +describe("runInit — session branch", () => { + test("creates session-- with a 7-day TTL and stores APPKIT_DB_SESSION", async () => { + const lakebase = project(); + const ctx = appOn(lakebase); + + const { report, steps } = await init(ctx, { + mode: "session", + schema: "none", + }); + + const id = envFile(ctx.root).APPKIT_DB_SESSION as string; + expect(id).toMatch(/^[0-9a-z]{8}$/); + expect(report).toMatchObject({ + mode: "session", + branch: session(id), + created: true, + }); + expect(report.expireTime).not.toBeNull(); + expect(lakebase.calls).toContain( + `createBranch ${sessionBranchId(USER, id)} ${JSON.stringify({ source_branch: PRODUCTION, ttl: "604800s" })}`, + ); + expect(steps[0]).toBe( + `Creating ${sessionBranchId(USER, id)} from production, expiring after 7 days`, + ); + }); + + test("--ttl sets a new session branch's TTL; a dev branch takes none, and a bad value fails before any call", async () => { + const lakebase = project(); + const { report } = await init(appOn(lakebase), { + mode: "session", + ttl: "1h", + schema: "none", + }); + expect(lakebase.calls).toContain( + `createBranch ${report.branch.split("/").pop()} ${JSON.stringify({ source_branch: PRODUCTION, ttl: "3600s" })}`, + ); + + const untouched = project(); + await expect(init(appOn(untouched), { ttl: "1h" })).rejects.toThrow( + "--ttl applies to session branches only; add --session.", + ); + await expect( + init(appOn(untouched), { mode: "session", ttl: "soon" }), + ).rejects.toThrow(/^Invalid --ttl "soon"/); + expect(untouched.calls).toEqual([]); + }); + + test("the session id is in .env before the branch is created, so a failed run's rerun reuses it", async () => { + const lakebase = project(); + lakebase.createBranchError = new Error("network down"); + const ctx = appOn(lakebase); + + await expect(init(ctx, { mode: "session" })).rejects.toThrow( + "network down", + ); + const id = envFile(ctx.root).APPKIT_DB_SESSION as string; + expect(id).toMatch(/^[0-9a-z]{8}$/); + + lakebase.createBranchError = undefined; + const rerun = fakeContext({ + root: ctx.root, + env: { ...ctx.env, APPKIT_DB_SESSION: id }, + userName: USER, + api: lakebase.api(), + }); + const { report } = await init(rerun, { mode: "session", schema: "none" }); + expect(report.branch).toBe(session(id)); + }); + + test("a rerun without --session keeps the session branch .env points at", async () => { + schemaOwner = USER; + const lakebase = project(); + lakebase.addBranch(session("k2x9q0ab"), { + expire_time: "2099-01-01T00:00:00Z", + }); + lakebase.addRole(session("k2x9q0ab"), "alice", USER, [ + "DATABRICKS_SUPERUSER", + ]); + const ctx = appOn(lakebase, { + APPKIT_DB_SESSION: "k2x9q0ab", + LAKEBASE_ENDPOINT: `${session("k2x9q0ab")}/endpoints/primary`, + }); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report).toMatchObject({ + mode: "session", + branch: session("k2x9q0ab"), + created: false, + expireTime: "2099-01-01T00:00:00Z", + }); + }); + + test("an expired session branch, or a 409 for one that is gone, gets a fresh session id", async () => { + const lakebase = project(); + lakebase.addBranch(session("k2x9q0ab"), { + expire_time: "2000-01-01T00:00:00Z", + }); + const ctx = appOn(lakebase, { APPKIT_DB_SESSION: "k2x9q0ab" }); + + const { report } = await init(ctx, { mode: "session", schema: "none" }); + + const id = envFile(ctx.root).APPKIT_DB_SESSION as string; + expect(id).not.toBe("k2x9q0ab"); + expect(report).toMatchObject({ branch: session(id), created: true }); + + const held = project(); + const api = held.api(); + const create = api.createBranch.bind(api); + let first = true; + api.createBranch = async (...args) => { + if (first) { + first = false; + throw conflict(args[1]); + } + return create(...args); + }; + const heldCtx = fakeContext({ + root: tempApp({ + "databricks.yml": databricksYml( + PRODUCTION, + `${PRODUCTION}/databases/db`, + ), + }), + env: { LAKEBASE_PROJECT: P, APPKIT_DB_SESSION: "k2x9q0ab" }, + userName: USER, + api, + }); + const retried = await init(heldCtx, { mode: "session", schema: "none" }); + expect(retried.report.branch).not.toBe(session("k2x9q0ab")); + expect(retried.report.created).toBe(true); + }); +}); + +describe("runInit — branches it never sets up", () => { + test("a dev branch databricks.yml deploys to is refused before any API call or .env write", async () => { + const lakebase = project(); + const ctx = appOn(lakebase, {}, { deploy: DEV }); + const before = fs.readFileSync(path.join(ctx.root, ".env"), "utf-8"); + + await expect(init(ctx)).rejects.toThrow( + `Refusing to set up ${devBranchId(USER)}: it is a branch databricks.yml deploys to, and the deployed app migrates it itself.`, + ); + expect(lakebase.calls).toEqual([]); + expect(fs.readFileSync(path.join(ctx.root, ".env"), "utf-8")).toBe(before); + }); + + test.each([ + [{ default: true }, "it is the project's default branch"], + [{ is_protected: true }, "it is a protected branch"], + ])( + "an existing dev branch that became %j is refused before any change", + async (status, reason) => { + const lakebase = project(); + lakebase.addBranch(DEV, status); + const ctx = appOn(lakebase); + const before = fs.readFileSync(path.join(ctx.root, ".env"), "utf-8"); + + await expect(init(ctx)).rejects.toThrow( + `Refusing to set up ${devBranchId(USER)}: ${reason}.`, + ); + expect(lakebase.calls).toEqual([`getBranch ${DEV}`]); + expect(fs.readFileSync(path.join(ctx.root, ".env"), "utf-8")).toBe( + before, + ); + }, + ); +}); + +describe("runInit — hand-off failures", () => { + test("an owner the role API does not manage is named, with the fix", async () => { + schemaOwner = "legacy_owner"; + + await expect(init(appOn(project()))).rejects.toThrow( + `Cannot hand schema app in database databricks_postgres on ${devBranchId(USER)} to you: it belongs to "legacy_owner", which is not a Lakebase-managed role. .env already points at the branch.`, + ); + }); + + test("a failed role delete lists what blocks it", async () => { + const lakebase = project(); + lakebase.deleteRoleError = new LakebaseApiError( + "delete role", + "INTERNAL_ERROR", + { statusCode: 500 }, + ); + blockers = [ + { database: "analytics", count: 3 }, + { database: "databricks_postgres", count: 1 }, + ]; + + await expect(init(appOn(lakebase))).rejects.toThrow( + `These objects and privileges of "${SP}" block the delete: database analytics (3), database databricks_postgres (1). .env already points at the branch. Drop them or reassign them to you, then rerun \`appkit db init\`.`, + ); + expect(pool.query).toHaveBeenCalledWith( + expect.stringContaining("pg_shdepend"), + [SP], + ); + }); + + test("without blockers it says to rerun", async () => { + const lakebase = project(); + lakebase.deleteRoleError = new Error("timeout"); + + await expect(init(appOn(lakebase))).rejects.toThrow( + `deleting role "${SP}" failed (timeout). .env already points at the branch; rerun \`appkit db init\` to retry.`, + ); + }); +}); + +describe("runInit — schema start", () => { + test("without schema.ts the default is introspect, which installs drizzle-kit first", async () => { + const lakebase = project(); + const ctx = appOn( + lakebase, + {}, + { + schema: false, + files: { "package.json": "{}", "pnpm-lock.yaml": "" }, + }, + ); + const runCommand = vi.fn(); + const steps: string[] = []; + + const report = await runInit(ctx, { + runCommand, + onStep: (step) => steps.push(step), + }); + + const install = ["add", "-D", "-E", `drizzle-kit@${DRIZZLE_KIT_VERSION}`]; + expect(runCommand).toHaveBeenCalledWith("pnpm", install, ctx.root); + expect(report.installed).toBe(`pnpm ${install.join(" ")}`); + expect(report.start).toEqual({ + kind: "introspect", + introspect: { branch: DEV, tables: [] }, + }); + expect(runIntrospect.mock.calls[0]?.[1]).toEqual({ interactive: false }); + expect( + steps.indexOf( + `Installing drizzle-kit ${DRIZZLE_KIT_VERSION}, which writes migrations (pnpm ${install.join(" ")})`, + ), + ).toBeLessThan( + steps.indexOf( + `Writing schema.ts from schema app on ${devBranchId(USER)}`, + ), + ); + }); + + test("a failed install says what to run", async () => { + const ctx = appOn( + project(), + {}, + { files: { "package.json": "{}", "package-lock.json": "{}" } }, + ); + + await expect( + runInit(ctx, { + runCommand: () => { + throw new Error("ENOTFOUND registry"); + }, + }), + ).rejects.toThrow( + `Installing drizzle-kit failed. Run \`npm install --save-dev --save-exact drizzle-kit@${DRIZZLE_KIT_VERSION}\`, then rerun \`appkit db init\`.`, + ); + }); + + test("clean drops the schema, then applies the committed migrations without generating; it needs no drizzle-kit", async () => { + const ctx = appOn(project(), {}, { files: { "package.json": "{}" } }); + const runCommand = vi.fn(); + + const { report } = await init(ctx, { schema: "clean", runCommand }); + + expect(runClean).toHaveBeenCalledOnce(); + expect(runMigrate.mock.calls[0]?.[1]).toEqual({ + interactive: false, + generate: false, + }); + expect(runClean.mock.invocationCallOrder[0]).toBeLessThan( + runMigrate.mock.invocationCallOrder[0] ?? 0, + ); + expect(runCommand).not.toHaveBeenCalled(); + expect(report.start).toEqual({ + kind: "clean", + clean: { branch: DEV, schemaName: "app", dependents: [] }, + migrate: migrateReport, + }); + }); + + test.each(["migrate", "clean"] as const)( + "%s without schema.ts fails before any change", + async (start) => { + const lakebase = project(); + const ctx = appOn(lakebase, {}, { schema: false }); + + await expect(init(ctx, { schema: start })).rejects.toThrow( + /^No config\/database\/schema\.ts yet/, + ); + expect(lakebase.calls).toEqual([]); + }, + ); +}); + +describe("runInit — .env", () => { + test("a missing .env gets the host init authenticated with, and never .env.example's placeholders", async () => { + const lakebase = project(); + const root = tempApp({ + ".env.example": + "DATABRICKS_HOST=https://your-workspace.cloud.databricks.com\nPGHOST=your_postgres_host\n", + "databricks.yml": databricksYml( + PRODUCTION, + `${PRODUCTION}/databases/databricks-postgres`, + ), + }); + lakebase.databases.set(`${DEV}/databases/databricks-postgres`, { + name: `${DEV}/databases/databricks-postgres`, + status: { postgres_database: "databricks_postgres" }, + }); + const ctx = fakeContext({ + root, + userName: USER, + api: lakebase.api(), + host: "https://real.cloud.databricks.com", + }); + + await init(ctx, { schema: "none" }); + + expect(envFile(root)).toEqual({ + LAKEBASE_PROJECT: P, + PGHOST: `primary.${devBranchId(USER)}.example.com`, + LAKEBASE_ENDPOINT: `${DEV}/endpoints/primary`, + PGDATABASE: "databricks_postgres", + PGUSER: USER, + PGPORT: "5432", + PGSSLMODE: "require", + DATABRICKS_HOST: "https://real.cloud.databricks.com", + }); + expect(lakebase.calls).toContain( + `getDatabase ${DEV}/databases/databricks-postgres`, + ); + expect(fs.statSync(path.join(root, ".env")).mode & 0o777).toBe(0o600); + }); + + test("the profile init authenticated with wins over the host", async () => { + const lakebase = project(); + const root = tempApp(); + const ctx = fakeContext({ + root, + env: { LAKEBASE_PROJECT: P, DATABRICKS_CONFIG_PROFILE: "staging" }, + userName: USER, + api: lakebase.api(), + host: "https://real.cloud.databricks.com", + }); + + await init(ctx, { schema: "none" }); + + expect(envFile(root).DATABRICKS_CONFIG_PROFILE).toBe("staging"); + expect(envFile(root).DATABRICKS_HOST).toBeUndefined(); + }); + + test("a symlinked .env is refused before any API call", async () => { + const lakebase = project(); + const ctx = appOn(lakebase, {}, { files: { "shared.env": "" } }); + fs.rmSync(path.join(ctx.root, ".env")); + fs.symlinkSync( + path.join(ctx.root, "shared.env"), + path.join(ctx.root, ".env"), + ); + + await expect(init(ctx)).rejects.toThrow( + /^Refusing to rewrite .*\.env: it is a symbolic link/, + ); + expect(lakebase.calls).toEqual([]); + }); +}); + +describe("runInit — project", () => { + test("no project anywhere is a clear error", async () => { + const ctx = fakeContext({ + root: tempApp(), + userName: USER, + api: project().api(), + }); + await expect(init(ctx, { schema: "none" })).rejects.toThrow( + /No Lakebase project configured\. Set LAKEBASE_PROJECT=projects\/ in \.env/, + ); + }); + + test.each([P, "p"])( + "a .env with only the profile and LAKEBASE_PROJECT=%s is enough", + async (value) => { + const lakebase = project(); + const root = tempApp({ + ".env": `DATABRICKS_CONFIG_PROFILE=DEFAULT\nLAKEBASE_PROJECT=${value}\n`, + }); + const ctx = fakeContext({ + root, + env: { DATABRICKS_CONFIG_PROFILE: "DEFAULT", LAKEBASE_PROJECT: value }, + userName: USER, + api: lakebase.api(), + }); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report).toMatchObject({ + branch: DEV, + created: true, + sourceBranch: PRODUCTION, + database: "databricks_postgres", + }); + expect(envFile(root)).toEqual({ + DATABRICKS_CONFIG_PROFILE: "DEFAULT", + LAKEBASE_PROJECT: P, + PGHOST: `primary.${devBranchId(USER)}.example.com`, + LAKEBASE_ENDPOINT: `${DEV}/endpoints/primary`, + PGDATABASE: "databricks_postgres", + PGUSER: USER, + PGPORT: "5432", + PGSSLMODE: "require", + }); + }, + ); + + test("LAKEBASE_PROJECT wins over LAKEBASE_ENDPOINT and databricks.yml; their values from another project are ignored", async () => { + schemaOwner = USER; + const lakebase = project(); + const otherProduction = "projects/q/branches/production"; + const otherDev = `projects/q/branches/${devBranchId(USER)}`; + lakebase.addBranch(otherProduction, { default: true }); + lakebase.addRole(otherProduction, "alice", USER, ["DATABRICKS_SUPERUSER"]); + const ctx = appOn(lakebase, { + LAKEBASE_PROJECT: "q", + PGDATABASE: "p_only_database", + }); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report).toMatchObject({ + branch: otherDev, + sourceBranch: otherProduction, + database: "databricks_postgres", + }); + expect(lakebase.calls.some((call) => call.includes("projects/p/"))).toBe( + false, + ); + expect(envFile(ctx.root)).toMatchObject({ + LAKEBASE_PROJECT: "projects/q", + LAKEBASE_ENDPOINT: `${otherDev}/endpoints/primary`, + PGDATABASE: "databricks_postgres", + }); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts index 139ee959a..3ce37d925 100644 --- a/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts +++ b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts @@ -1,7 +1,13 @@ import { describe, expect, test } from "vitest"; import type { WorkspaceRequest } from "../../../workspace-client"; -import { LakebaseApi, LakebaseApiError } from "../lakebase-api"; +import { + isAlreadyExists, + isBranchLimit, + isPermissionDenied, + LakebaseApi, + LakebaseApiError, +} from "../lakebase-api"; /** A request as LakebaseApi sent it, with its JSON body decoded. */ interface Sent { @@ -47,6 +53,8 @@ function client(replies: Reply[]) { const apiError = (statusCode: number, message: string) => Object.assign(new Error(message), { statusCode, errorCode: "X" }); +const fast = { pollIntervalMs: 1 }; + describe("LakebaseApi", () => { test("getBranch: GET /api/2.0/postgres/{name}; 404 → null; other errors keep their status", async () => { const branch = { @@ -58,7 +66,7 @@ describe("LakebaseApi", () => { apiError(404, "NOT_FOUND"), apiError(403, "PERMISSION_DENIED"), ]); - const api = new LakebaseApi(fake); + const api = new LakebaseApi(fake, fast); await expect(api.getBranch("projects/p/branches/b")).resolves.toEqual( branch, @@ -153,4 +161,270 @@ describe("LakebaseApi", () => { api.getEndpoint("projects/p/branches/b/endpoints/primary"), ).rejects.toThrow(/unexpected response \(name: /); }); + + test("lists follow next_page_token", async () => { + const fake = client([ + { branches: [{ name: "a" }], next_page_token: "t2" }, + { branches: [{ name: "b" }] }, + ]); + const branches = await new LakebaseApi(fake, fast).listBranches( + "projects/p", + ); + + expect(branches.map((b) => b.name)).toEqual(["a", "b"]); + expect(fake.requests.map((r) => [r.path, r.query])).toEqual([ + ["/api/2.0/postgres/projects/p/branches", undefined], + ["/api/2.0/postgres/projects/p/branches", { page_token: "t2" }], + ]); + }); + + test("createBranch: POST with branch_id and {spec}; a finished operation returns its response", async () => { + const fake = client([ + { + name: "projects/p/branches/dev-a/operations/1", + done: true, + response: { name: "projects/p/branches/dev-a" }, + }, + ]); + const branch = await new LakebaseApi(fake, fast).createBranch( + "projects/p", + "dev-a", + { + source_branch: "projects/p/branches/production", + no_expiry: true, + }, + ); + + expect(branch).toEqual({ name: "projects/p/branches/dev-a" }); + expect(fake.requests[0]).toMatchObject({ + path: "/api/2.0/postgres/projects/p/branches", + method: "POST", + query: { branch_id: "dev-a" }, + payload: { + spec: { + source_branch: "projects/p/branches/production", + no_expiry: true, + }, + }, + }); + expect(fake.requests[0]?.headers.get("Content-Type")).toBe( + "application/json", + ); + }); + + test("polls GET /api/2.0/postgres/{operation.name} until the operation is done", async () => { + const op = "projects/p/branches/b/operations/7"; + const fake = client([ + { name: op, done: false }, + { name: op, done: false }, + { + name: op, + done: true, + response: { name: "projects/p/branches/b/endpoints/primary" }, + }, + ]); + const endpoint = await new LakebaseApi(fake, fast).createEndpoint( + "projects/p/branches/b", + "primary", + { suspendTimeout: "300s" }, + ); + + expect(endpoint.name).toBe("projects/p/branches/b/endpoints/primary"); + expect(fake.requests[0]).toMatchObject({ + path: "/api/2.0/postgres/projects/p/branches/b/endpoints", + method: "POST", + query: { endpoint_id: "primary" }, + payload: { + spec: { + endpoint_type: "ENDPOINT_TYPE_READ_WRITE", + suspend_timeout_duration: "300s", + }, + }, + }); + expect(fake.requests.slice(1).map((r) => [r.method, r.path])).toEqual([ + ["GET", `/api/2.0/postgres/${op}`], + ["GET", `/api/2.0/postgres/${op}`], + ]); + }); + + test("a failed operation becomes a LakebaseApiError with the operation's message", async () => { + const fake = client([ + { + name: "op", + done: true, + error: { + error_code: "RESOURCE_EXHAUSTED", + message: "branch limit reached", + }, + }, + ]); + await expect( + new LakebaseApi(fake, fast).createBranch("projects/p", "dev-a", { + source_branch: "projects/p/branches/production", + no_expiry: true, + }), + ).rejects.toThrow( + "Lakebase: create branch projects/p/branches/dev-a failed: branch limit reached", + ); + }); + + test("an operation that never finishes times out", async () => { + const fake = client( + Array.from({ length: 50 }, () => ({ name: "op", done: false })), + ); + await expect( + new LakebaseApi(fake, { pollIntervalMs: 1, timeoutMs: 5 }).createEndpoint( + "projects/p/branches/b", + "primary", + { suspendTimeout: "300s" }, + ), + ).rejects.toThrow(/timed out/); + }); + + test("error codes from the call and from a failed operation classify the failure", async () => { + const create = (api: LakebaseApi) => + api + .createBranch("projects/p", "dev-a", { + source_branch: "projects/p/branches/production", + no_expiry: true, + }) + .catch((e: unknown) => e); + const conflict = await create( + new LakebaseApi( + client([ + { + name: "op", + done: true, + error: { error_code: "ALREADY_EXISTS", message: "exists" }, + }, + ]), + fast, + ), + ); + const denied = await create( + new LakebaseApi(client([apiError(403, "PERMISSION_DENIED")]), fast), + ); + const limit = await create( + new LakebaseApi( + client([ + Object.assign( + new Error("unarchived branches limit exceeded [TraceId: abc]"), + { statusCode: 400, errorCode: "BAD_REQUEST" }, + ), + ]), + fast, + ), + ); + + expect(conflict).toMatchObject({ errorCode: "ALREADY_EXISTS" }); + expect(isAlreadyExists(conflict)).toBe(true); + expect(isPermissionDenied(conflict)).toBe(false); + expect(isPermissionDenied(denied)).toBe(true); + expect(isAlreadyExists(denied)).toBe(false); + expect(limit).toMatchObject({ statusCode: 400, errorCode: "BAD_REQUEST" }); + expect(isBranchLimit(limit)).toBe(true); + expect(isBranchLimit(denied)).toBe(false); + }); + + test("deleteBranch: DELETE the branch; one that is already gone counts as deleted", async () => { + const fake = client([ + { name: "op", done: true }, + apiError(404, "NOT_FOUND"), + { + name: "op", + done: true, + error: { error_code: "RESOURCE_DOES_NOT_EXIST", message: "gone" }, + }, + apiError(403, "PERMISSION_DENIED"), + ]); + const api = new LakebaseApi(fake, fast); + const name = "projects/p/branches/session-abc123-x"; + + await api.deleteBranch(name); + await api.deleteBranch(name); + await api.deleteBranch(name); + await expect(api.deleteBranch(name)).rejects.toMatchObject({ + statusCode: 403, + }); + + expect(fake.requests[0]).toMatchObject({ + path: `/api/2.0/postgres/${name}`, + method: "DELETE", + }); + expect(fake.requests[0]?.query).toBeUndefined(); + }); + + test("createRole posts {spec} without a role_id", async () => { + const fake = client([ + { + name: "op", + done: true, + response: { name: "projects/p/branches/b/roles/r" }, + }, + ]); + await new LakebaseApi(fake, fast).createRole("projects/p/branches/b", { + identity_type: "USER", + postgres_role: "alice@example.com", + auth_method: "LAKEBASE_OAUTH_V1", + membership_roles: ["DATABRICKS_SUPERUSER"], + }); + + expect(fake.requests[0]).toEqual( + expect.objectContaining({ + path: "/api/2.0/postgres/projects/p/branches/b/roles", + method: "POST", + payload: { + spec: { + identity_type: "USER", + postgres_role: "alice@example.com", + auth_method: "LAKEBASE_OAUTH_V1", + membership_roles: ["DATABRICKS_SUPERUSER"], + }, + }, + }), + ); + expect(fake.requests[0]?.query).toBeUndefined(); + }); + + test("setRoleMemberships: PATCH with update_mask=spec.membership_roles", async () => { + const fake = client([ + { + name: "op", + done: true, + response: { name: "projects/p/branches/b/roles/r" }, + }, + ]); + await new LakebaseApi(fake, fast).setRoleMemberships( + "projects/p/branches/b/roles/r", + ["DATABRICKS_SUPERUSER"], + ); + + expect(fake.requests[0]).toMatchObject({ + path: "/api/2.0/postgres/projects/p/branches/b/roles/r", + method: "PATCH", + query: { update_mask: "spec.membership_roles" }, + payload: { spec: { membership_roles: ["DATABRICKS_SUPERUSER"] } }, + }); + }); + + test("deleteRole: DELETE with reassign_owned_to = the target role's resource name", async () => { + const fake = client([ + { name: "op", done: false }, + { name: "op", done: true }, + ]); + await new LakebaseApi(fake, fast).deleteRole( + "projects/p/branches/b/roles/sp", + { + reassignOwnedTo: "projects/p/branches/b/roles/alice", + }, + ); + + expect(fake.requests[0]).toMatchObject({ + path: "/api/2.0/postgres/projects/p/branches/b/roles/sp", + method: "DELETE", + query: { reassign_owned_to: "projects/p/branches/b/roles/alice" }, + }); + expect(fake.requests[0]?.payload).toBeUndefined(); + expect(fake.requests).toHaveLength(2); + }); }); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 15056e199..4246a7964 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -182,6 +182,29 @@ describe("runMigrate", () => { expect(fs.existsSync(report.typesFile)).toBe(true); }); + test("generate: false applies the committed migrations without writing new ones", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + resolveEnvBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + writeSchema(ctx.root, `notes: table("notes", { id: id(), body: text() })`); + + resolveEnvBranch.mockResolvedValue(devBranch); + applyPendingMigrations.mockResolvedValue({ + applied: ["0000_migration"], + adopted: [], + }); + const report = await runMigrate(ctx, { + interactive: false, + generate: false, + }); + + expect(report.generated).toBeNull(); + expect(report.applied).toEqual(["0000_migration"]); + expect( + fs.readdirSync(path.join(ctx.root, "config/database/migrations")), + ).toEqual(["0000_migration.sql", "meta"]); + }); + test("reports a baseline adopted without running it", async () => { const ctx = app(`notes: table("notes", { id: id() })`); resolveEnvBranch.mockResolvedValue(null); diff --git a/packages/appkit/src/database/tooling/tests/naming.test.ts b/packages/appkit/src/database/tooling/tests/naming.test.ts index 423f33ad0..b2ab9bb12 100644 --- a/packages/appkit/src/database/tooling/tests/naming.test.ts +++ b/packages/appkit/src/database/tooling/tests/naming.test.ts @@ -1,6 +1,14 @@ import { describe, expect, test } from "vitest"; -import { devBranchId, isValidSessionId, sessionBranchId } from "../naming"; +import { + devBranchId, + isUsersBranchId, + isValidSessionId, + newSessionId, + parseTtl, + SESSION_BRANCH_TTL, + sessionBranchId, +} from "../naming"; const BRANCH_ID = /^[a-z][a-z0-9-]{0,62}$/; @@ -31,9 +39,52 @@ describe("branch naming", () => { ); }); - test("session branches are session-; ids are lowercase base36", () => { - expect(sessionBranchId("k2x9q0ab")).toBe("session-k2x9q0ab"); + test("session branches are session--; ids are lowercase base36", () => { + const sessionId = newSessionId(); + expect(sessionId).toMatch(/^[0-9a-z]{8}$/); + const hash = devBranchId("alice@example.com").slice(-6); + expect(sessionBranchId("Alice@example.com", sessionId)).toBe( + `session-${hash}-${sessionId}`, + ); expect(isValidSessionId("Bad-Id")).toBe(false); - expect(() => sessionBranchId("Bad-Id")).toThrow(/APPKIT_DB_SESSION/); + expect(() => sessionBranchId("alice@example.com", "Bad-Id")).toThrow( + /APPKIT_DB_SESSION/, + ); + expect(SESSION_BRANCH_TTL).toBe("604800s"); + }); + + test("the longest session id still makes a valid branch ID", () => { + const id = sessionBranchId("alice@example.com", "a".repeat(48)); + expect(id).toHaveLength(63); + expect(id).toMatch(BRANCH_ID); + expect(isValidSessionId("a".repeat(49))).toBe(false); + }); + + test("a copied .env names a session branch only its creator owns", () => { + const alice = "alice@example.com"; + const bob = "bob@example.com"; + expect(sessionBranchId(alice, "abc")).not.toBe(sessionBranchId(bob, "abc")); + expect(isUsersBranchId(alice, sessionBranchId(alice, "abc"))).toBe(true); + expect(isUsersBranchId(alice, devBranchId(alice))).toBe(true); + expect(isUsersBranchId(alice, sessionBranchId(bob, "abc"))).toBe(false); + expect(isUsersBranchId(alice, devBranchId(bob))).toBe(false); + expect(isUsersBranchId(alice, "production")).toBe(false); + }); +}); + +describe("parseTtl", () => { + test.each([ + ["90s", "90s"], + ["30m", "1800s"], + [" 1h ", "3600s"], + ["7d", "604800s"], + ])("%s is %s", (value, expected) => { + expect(parseTtl(value)).toBe(expected); + }); + + test.each(["0h", "1w", "1.5h", "-1h", "h", ""])("refuses %j", (value) => { + expect(() => parseTtl(value)).toThrow( + `Invalid --ttl ${JSON.stringify(value)}: use a positive number of seconds, minutes, hours or days, e.g. 30m, 1h or 7d.`, + ); }); }); diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index ac159a7df..6be36190e 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -1,8 +1,10 @@ import { afterEach, describe, expect, test } from "vitest"; import { + parseProject, parseResourceName, readDeployBranches, + readDeployTarget, readLocalTarget, } from "../targets"; import { cleanupTempApps, databricksYml, tempApp } from "./fakes"; @@ -35,16 +37,35 @@ describe("parseResourceName", () => { }); }); +describe("parseProject", () => { + test("accepts projects/ or a bare , normalized to the resource name", () => { + expect(parseProject("projects/my-app")).toBe("projects/my-app"); + expect(parseProject(" my-app ")).toBe("projects/my-app"); + }); + + test("placeholders, branch paths and junk are null", () => { + expect(parseProject("your_postgres_project")).toBeNull(); + expect(parseProject("projects/p/branches/b")).toBeNull(); + expect(parseProject("")).toBeNull(); + expect(parseProject(undefined)).toBeNull(); + }); +}); + describe("readLocalTarget", () => { - test("reads the .env endpoint and this checkout's session", () => { + test("reads a real .env target", () => { expect( readLocalTarget({ + LAKEBASE_PROJECT: "p", LAKEBASE_ENDPOINT: "projects/p/branches/b/endpoints/primary", PGHOST: "ep.example.com", + PGDATABASE: "databricks_postgres", + PGUSER: "alice@example.com", APPKIT_DB_SESSION: "k2x9q0ab", }), ).toEqual({ + project: "projects/p", endpoint: "projects/p/branches/b/endpoints/primary", + database: "databricks_postgres", session: "k2x9q0ab", }); }); @@ -52,10 +73,18 @@ describe("readLocalTarget", () => { test("placeholders from .env.example read as not configured", () => { expect( readLocalTarget({ + LAKEBASE_PROJECT: "your_postgres_project", LAKEBASE_ENDPOINT: "your_postgres_endpointPath", + PGHOST: "your_postgres_host", + PGDATABASE: "your_postgres_databaseName", APPKIT_DB_SESSION: "NOT VALID", }), - ).toEqual({ endpoint: null, session: null }); + ).toEqual({ + project: null, + endpoint: null, + database: null, + session: null, + }); }); }); @@ -109,3 +138,41 @@ targets: ); }); }); + +describe("readDeployTarget", () => { + test("reads the default target's postgres variables", () => { + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/databricks-postgres", + ), + }); + expect(readDeployTarget(root)).toEqual({ + branch: "projects/p/branches/production", + database: "projects/p/branches/production/databases/databricks-postgres", + }); + }); + + test("falls back to top-level variable defaults", () => { + const root = tempApp({ + "databricks.yml": `variables: + postgres_branch: + default: projects/p/branches/main +targets: + dev: + default: true +`, + }); + expect(readDeployTarget(root)).toEqual({ + branch: "projects/p/branches/main", + database: null, + }); + }); + + test("null without databricks.yml or without a postgres binding", () => { + expect(readDeployTarget(tempApp())).toBeNull(); + expect( + readDeployTarget(tempApp({ "databricks.yml": "bundle:\n name: x\n" })), + ).toBeNull(); + }); +}); diff --git a/packages/shared/src/cli/commands/db/clean.ts b/packages/shared/src/cli/commands/db/clean.ts new file mode 100644 index 000000000..79a56f09e --- /dev/null +++ b/packages/shared/src/cli/commands/db/clean.ts @@ -0,0 +1,81 @@ +import { Command } from "commander"; + +import { loadDatabaseTooling } from "./load-tooling"; +import { + fail, + info, + isInteractive, + ok, + printCleanReport, + shortName, + warn, +} from "./output"; + +interface CleanFlags { + readonly yes?: boolean; + readonly deleteBranch?: boolean; +} + +async function runDbClean(flags: CleanFlags): Promise { + try { + const tooling = await loadDatabaseTooling(); + const ctx = tooling.createDbContext(); + if (flags.deleteBranch) { + const { branch } = await tooling.deleteSessionBranch(ctx); + ok(`Deleted ${shortName(branch)}`); + info("`appkit db init --session` creates a new one"); + return; + } + if (!flags.yes) { + if (!isInteractive()) { + throw new Error( + "Refusing to clean without confirmation in a non-interactive shell. Pass --yes.", + ); + } + const preview = await tooling.previewClean(ctx); + if (preview.dependents.length > 0) { + warn( + `Dropping schema ${preview.schemaName} also removes these objects outside it, which depend on it: ${preview.dependents.join(", ")}`, + ); + } + const { confirm, isCancel } = await import("@clack/prompts"); + const answer = await confirm({ + message: `Remove every object in schema ${preview.schemaName} on ${shortName(preview.branch)}, including the migration journal?`, + initialValue: false, + }); + if (isCancel(answer) || !answer) { + info("Cancelled"); + process.exitCode = 1; + return; + } + } + printCleanReport(await tooling.runClean(ctx)); + info("`appkit db migrate` recreates it from the committed migrations"); + } catch (error) { + fail(error); + } +} + +export const dbCleanCommand = new Command("clean") + .description( + "Remove every object in the app schema, including the migration journal, on your dev or session branch", + ) + .option("-y, --yes", "skip the confirmation") + .option( + "--delete-branch", + "delete this checkout's session branch instead, e.g. at the end of a CI job", + ) + .addHelpText( + "after", + ` +Only branches \`appkit db init\` created for you (dev-… or session-…) can be cleaned; +the default, protected and deploy branches are always refused. Objects outside +the schema that depend on it, such as a view in another schema, are dropped +with it and listed. --delete-branch deletes session branches only; your dev +branch stays. + +Examples: + $ appkit db clean + $ appkit db init --session --ttl 1h --yes && npm test && appkit db clean --delete-branch`, + ) + .action(runDbClean); diff --git a/packages/shared/src/cli/commands/db/index.ts b/packages/shared/src/cli/commands/db/index.ts index 35ff2f721..ed811c91c 100644 --- a/packages/shared/src/cli/commands/db/index.ts +++ b/packages/shared/src/cli/commands/db/index.ts @@ -1,7 +1,10 @@ import { Command } from "commander"; +import { dbCleanCommand } from "./clean"; +import { dbInitCommand } from "./init"; import { dbIntrospectCommand } from "./introspect"; import { dbMigrateCommand } from "./migrate"; +import { dbSeedCommand } from "./seed"; /** * Lakebase database lifecycle for the DatabasePlugin. The logic lives in @@ -9,5 +12,8 @@ import { dbMigrateCommand } from "./migrate"; */ export const dbCommand = new Command("db") .description("Lakebase database lifecycle") + .addCommand(dbInitCommand) .addCommand(dbMigrateCommand) - .addCommand(dbIntrospectCommand); + .addCommand(dbIntrospectCommand) + .addCommand(dbCleanCommand) + .addCommand(dbSeedCommand); diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts new file mode 100644 index 000000000..90dcdf53f --- /dev/null +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -0,0 +1,377 @@ +import { + afterEach, + beforeEach, + describe, + expect, + type MockInstance, + test, + vi, +} from "vitest"; + +const tooling = vi.hoisted(() => ({ + createDbContext: vi.fn(() => ({ root: "/app", env: {} })), + runInit: vi.fn(), + previewClean: vi.fn(), + runClean: vi.fn(), + deleteSessionBranch: vi.fn(), + runSeed: vi.fn(), +})); +const prompts = vi.hoisted(() => ({ + confirm: vi.fn(), + isCancel: vi.fn((value: unknown) => typeof value === "symbol"), +})); + +vi.mock("@databricks/appkit/database-tooling", () => tooling); +vi.mock("@clack/prompts", () => prompts); + +import { dbCommand } from "./index"; + +let log: MockInstance; +let error: MockInstance; +const output = (spy: MockInstance) => + spy.mock.calls.map((call) => call.join(" ")).join("\n"); + +function setTTY(value: boolean | undefined) { + Object.defineProperty(process.stdin, "isTTY", { value, configurable: true }); + Object.defineProperty(process.stdout, "isTTY", { value, configurable: true }); +} +const ttyBefore = { stdin: process.stdin.isTTY, stdout: process.stdout.isTTY }; + +const migrate = { + generated: null, + applied: ["0000_migration"], + typesFile: `${process.cwd()}/shared/appkit-types/database.d.ts`, +}; +const report = { + mode: "dev", + branch: "projects/p/branches/dev-alice-3f9a2c", + created: true, + sourceBranch: "projects/p/branches/production", + expireTime: null, + endpoint: "projects/p/branches/dev-alice-3f9a2c/endpoints/primary", + endpointCreated: false, + host: "ep-1.example.com", + database: "databricks_postgres", + user: "alice@example.com", + role: { + name: "projects/p/branches/dev-alice-3f9a2c/roles/alice", + action: "kept", + }, + handedOff: "11111111-2222-3333-4444-555555555555", + envFile: "/app/.env", + installed: null, + start: { kind: "migrate", migrate }, +}; + +/** Commander keeps parsed option values on the command; each test parses afresh. */ +function resetOptionValues() { + for (const command of dbCommand.commands) { + for (const option of command.options) { + command.setOptionValueWithSource( + option.attributeName(), + undefined, + "default", + ); + } + } +} + +const init = (...args: string[]) => + dbCommand.parseAsync(["init", ...args], { from: "user" }); +const clean = (...args: string[]) => + dbCommand.parseAsync(["clean", ...args], { from: "user" }); +const initOptions = () => tooling.runInit.mock.calls.at(-1)?.[1]; + +beforeEach(() => { + resetOptionValues(); + for (const mock of Object.values(tooling)) mock.mockReset(); + prompts.confirm.mockReset(); + tooling.createDbContext.mockReturnValue({ root: "/app", env: {} }); + tooling.runInit.mockResolvedValue(report); + log = vi.spyOn(console, "log").mockImplementation(() => undefined); + error = vi.spyOn(console, "error").mockImplementation(() => undefined); +}); + +afterEach(() => { + vi.restoreAllMocks(); + setTTY(undefined); + Object.defineProperty(process.stdin, "isTTY", { + value: ttyBefore.stdin, + configurable: true, + }); + Object.defineProperty(process.stdout, "isTTY", { + value: ttyBefore.stdout, + configurable: true, + }); + process.exitCode = undefined; +}); + +describe("appkit db init", () => { + test("registers init, migrate, introspect, clean and seed", () => { + expect(dbCommand.commands.map((c) => c.name())).toEqual([ + "init", + "migrate", + "introspect", + "clean", + "seed", + ]); + }); + + test("init only sets up a dev or session branch: there is no option to pick another one", () => { + const command = dbCommand.commands.find((c) => c.name() === "init"); + expect(command?.options.map((o) => o.long)).toEqual([ + "--session", + "--dev", + "--ttl", + "--schema", + "--yes", + ]); + }); + + test("asks nothing, even on a TTY: the tooling picks the mode and the start", async () => { + setTTY(true); + await init(); + + expect(prompts.confirm).not.toHaveBeenCalled(); + expect(tooling.runInit).toHaveBeenCalledWith( + { root: "/app", env: {} }, + { interactive: true, onStep: expect.any(Function) }, + ); + }); + + test("flags map to the options; --yes turns off the rename prompts", async () => { + await init("--session", "--ttl", "1h", "--schema", "none", "--yes"); + + expect(initOptions()).toEqual({ + mode: "session", + schema: "none", + ttl: "1h", + interactive: false, + onStep: expect.any(Function), + }); + + resetOptionValues(); + await init("--dev"); + expect(initOptions()).toMatchObject({ mode: "dev" }); + }); + + test("--session and --dev conflict", async () => { + vi.spyOn(process.stderr, "write").mockImplementation(() => true); + const exit = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("exit"); + }); + await expect(init("--session", "--dev")).rejects.toThrow("exit"); + expect(exit).toHaveBeenCalled(); + expect(tooling.runInit).not.toHaveBeenCalled(); + }); + + test("prints each step as it happens", async () => { + tooling.runInit.mockImplementation(async (_ctx, options) => { + options.onStep("Creating dev-alice-3f9a2c from production"); + return report; + }); + await init(); + expect(output(log)).toContain("Creating dev-alice-3f9a2c from production"); + }); + + test("prints what it did", async () => { + await init(); + + const printed = output(log); + expect(printed).toContain( + "Branch dev-alice-3f9a2c (created from production)", + ); + expect(printed).toContain("Endpoint primary: ep-1.example.com"); + expect(printed).toContain("Role alice@example.com (DATABRICKS_SUPERUSER)"); + expect(printed).toContain( + "The app schema is yours: it belonged to 11111111-2222-3333-4444-555555555555", + ); + expect(printed).toContain( + "Pointed .env at dev-alice-3f9a2c (database databricks_postgres)", + ); + expect(printed).toContain("Applied 0000_migration to the .env branch"); + expect(printed).not.toContain("Installed drizzle-kit"); + }); + + test("a session branch reports when it expires, and an install is reported", async () => { + tooling.runInit.mockResolvedValue({ + ...report, + mode: "session", + branch: "projects/p/branches/session-3f9a2c-k2x9", + created: false, + expireTime: "2026-10-26T12:00:00Z", + handedOff: null, + installed: "npm install --save-dev --save-exact drizzle-kit@0.31.10", + start: { kind: "none" }, + }); + await init(); + + const printed = output(log); + expect(printed).toContain( + "Branch session-3f9a2c-k2x9 (reused, expires 2026-10-26T12:00:00Z)", + ); + expect(printed).toContain( + "Installed drizzle-kit (npm install --save-dev --save-exact drizzle-kit@0.31.10)", + ); + expect(printed).toContain("Left the schema as it is"); + expect(printed).not.toContain("The app schema is yours"); + }); + + test("a clean start reports the drop, what it took along, then the migrations", async () => { + tooling.runInit.mockResolvedValue({ + ...report, + start: { + kind: "clean", + clean: { + branch: report.branch, + schemaName: "app", + dependents: ["view reports.summary"], + }, + migrate, + }, + }); + await init("--schema", "clean", "--yes"); + + const printed = output(log); + expect(printed).toContain("Dropped schema app on dev-alice-3f9a2c"); + expect(printed).toContain( + "Also removed, because they depended on it: view reports.summary", + ); + expect(printed).toContain("Applied 0000_migration to the .env branch"); + }); + + test("--schema clean without a TTY needs --yes, and stops before any API call", async () => { + await init("--schema", "clean"); + + expect(output(error)).toContain( + "Refusing to run `--schema clean` without confirmation in a non-interactive shell. Pass --yes.", + ); + expect(tooling.runInit).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + }); + + test("--schema clean on a TTY asks first; a no cancels with exit code 1", async () => { + setTTY(true); + prompts.confirm.mockResolvedValueOnce(false); + await init("--schema", "clean"); + + expect(prompts.confirm).toHaveBeenCalledOnce(); + expect(tooling.runInit).not.toHaveBeenCalled(); + expect(output(log)).toContain("Cancelled"); + expect(process.exitCode).toBe(1); + + process.exitCode = undefined; + resetOptionValues(); + prompts.confirm.mockResolvedValueOnce(true); + await init("--schema", "clean"); + expect(initOptions()).toMatchObject({ schema: "clean" }); + }); + + test("an error is printed and exits 1", async () => { + tooling.runInit.mockRejectedValue( + new Error( + "Creating dev-a needs CAN MANAGE on projects/p. Ask a project owner for it, then rerun `appkit db init`.", + ), + ); + await init("--yes"); + expect(output(error)).toContain("needs CAN MANAGE on projects/p"); + expect(process.exitCode).toBe(1); + }); +}); + +describe("appkit db clean", () => { + const cleaned = { + branch: "projects/p/branches/dev-a", + schemaName: "app", + dependents: [], + }; + + test("refuses without --yes when there is no TTY, before any API call", async () => { + await clean(); + + expect(output(error)).toContain( + "Refusing to clean without confirmation in a non-interactive shell. Pass --yes.", + ); + expect(tooling.previewClean).not.toHaveBeenCalled(); + expect(tooling.runClean).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + }); + + test("on a TTY it names the branch and what else goes, then asks; no cancels with exit code 1", async () => { + setTTY(true); + tooling.previewClean.mockResolvedValue({ + ...cleaned, + dependents: ["view reports.summary"], + }); + prompts.confirm.mockResolvedValueOnce(false); + await clean(); + + expect(output(log)).toContain( + "Dropping schema app also removes these objects outside it, which depend on it: view reports.summary", + ); + expect(prompts.confirm.mock.calls[0]?.[0].message).toBe( + "Remove every object in schema app on dev-a, including the migration journal?", + ); + expect(tooling.runClean).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + + process.exitCode = undefined; + prompts.confirm.mockResolvedValueOnce(true); + tooling.runClean.mockResolvedValue(cleaned); + await clean(); + expect(tooling.runClean).toHaveBeenCalledOnce(); + expect(output(log)).toContain("Dropped schema app on dev-a"); + }); + + test("--yes cleans without asking; public says only your objects went", async () => { + tooling.runClean.mockResolvedValue({ ...cleaned, schemaName: "public" }); + await clean("--yes"); + + expect(tooling.previewClean).not.toHaveBeenCalled(); + expect(prompts.confirm).not.toHaveBeenCalled(); + expect(output(log)).toContain( + "Removed your objects in schema public on dev-a", + ); + }); + + test("--delete-branch deletes this checkout's session branch without a prompt", async () => { + tooling.deleteSessionBranch.mockResolvedValue({ + branch: "projects/p/branches/session-3f9a2c-k2x9", + }); + await clean("--delete-branch"); + + expect(tooling.runClean).not.toHaveBeenCalled(); + expect(output(log)).toContain("Deleted session-3f9a2c-k2x9"); + expect(process.exitCode).toBeUndefined(); + }); + + test("the guard's refusal is printed and exits 1", async () => { + tooling.runClean.mockRejectedValue( + new Error( + "Refusing to clean production: it is the project's default branch.", + ), + ); + await clean("--yes"); + expect(output(error)).toContain("Refusing to clean production"); + expect(process.exitCode).toBe(1); + }); +}); + +describe("appkit db seed", () => { + test("prints the seed file and branch", async () => { + tooling.runSeed.mockResolvedValue({ + branch: "projects/p/branches/dev-a", + file: `${process.cwd()}/config/database/seed.sql`, + }); + await dbCommand.parseAsync(["seed"], { from: "user" }); + expect(output(log)).toContain("Ran config/database/seed.sql on dev-a"); + }); + + test("a missing seed file exits 1", async () => { + tooling.runSeed.mockRejectedValue( + new Error("No seed file at config/database/seed.sql."), + ); + await dbCommand.parseAsync(["seed"], { from: "user" }); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts new file mode 100644 index 000000000..a31838b8f --- /dev/null +++ b/packages/shared/src/cli/commands/db/init.ts @@ -0,0 +1,143 @@ +import { Command, Option } from "commander"; + +import { loadDatabaseTooling } from "./load-tooling"; +import { + fail, + info, + isInteractive, + ok, + printCleanReport, + printIntrospectReport, + printMigrateReport, + shortName, +} from "./output"; +import type { InitOptions, InitReport, SchemaStart } from "./tooling-contract"; + +interface InitFlags { + readonly session?: boolean; + readonly dev?: boolean; + readonly ttl?: string; + readonly schema?: SchemaStart; + readonly yes?: boolean; +} + +/** --schema clean drops data: a human confirms it, a script passes --yes. */ +async function confirmClean(flags: InitFlags): Promise { + if (flags.schema !== "clean" || flags.yes) return true; + if (!isInteractive()) { + throw new Error( + "Refusing to run `--schema clean` without confirmation in a non-interactive shell. Pass --yes.", + ); + } + const { confirm, isCancel } = await import("@clack/prompts"); + const answer = await confirm({ + message: + "Drop the app schema on your dev or session branch, with every table and row in it, then apply the committed migrations?", + initialValue: false, + }); + return !isCancel(answer) && answer; +} + +function printInitReport(report: InitReport): void { + const branch = shortName(report.branch); + const expires = report.expireTime ? `, expires ${report.expireTime}` : ""; + ok( + report.created + ? `Branch ${branch} (created from ${shortName(report.sourceBranch ?? "the default branch")}${expires})` + : `Branch ${branch} (reused${expires})`, + ); + ok( + `Endpoint ${shortName(report.endpoint)}${report.endpointCreated ? " (created)" : ""}: ${report.host}`, + ); + const role = { + created: "created", + updated: "added to DATABRICKS_SUPERUSER", + kept: "DATABRICKS_SUPERUSER", + }[report.role.action]; + ok(`Role ${report.user} (${role})`); + if (report.handedOff) { + ok(`The app schema is yours: it belonged to ${report.handedOff}`); + } + ok(`Pointed .env at ${branch} (database ${report.database})`); + if (report.installed) ok(`Installed drizzle-kit (${report.installed})`); + + const { start } = report; + if (start.kind === "introspect") printIntrospectReport(start.introspect); + else if (start.kind === "migrate") printMigrateReport(start.migrate); + else if (start.kind === "clean") { + printCleanReport(start.clean); + printMigrateReport(start.migrate); + } else info("Left the schema as it is"); +} + +async function runDbInit(flags: InitFlags): Promise { + try { + if (!(await confirmClean(flags))) { + info("Cancelled"); + process.exitCode = 1; + return; + } + const tooling = await loadDatabaseTooling(); + const mode = flags.session ? "session" : flags.dev ? "dev" : undefined; + const options: InitOptions = { + ...(mode ? { mode } : {}), + ...(flags.schema ? { schema: flags.schema } : {}), + ...(flags.ttl !== undefined ? { ttl: flags.ttl } : {}), + interactive: !flags.yes && isInteractive(), + onStep: info, + }; + printInitReport(await tooling.runInit(tooling.createDbContext(), options)); + } catch (error) { + fail(error); + } +} + +export const dbInitCommand = new Command("init") + .description( + "Set up your Lakebase dev or session branch for local development: create or reuse it, ensure an endpoint and your role, point .env at it, then set up the schema", + ) + .addOption( + new Option( + "--session", + "use this checkout's session branch, created with a TTL", + ).conflicts("dev"), + ) + .addOption( + new Option( + "--dev", + "use your dev branch, even when .env points at a session branch", + ), + ) + .option( + "--ttl ", + "TTL of a new session branch, e.g. 30m, 1h or 7d (default 7d)", + ) + .addOption( + new Option( + "--schema ", + "how the schema starts (default: migrate with schema.ts, introspect without)", + ).choices(["migrate", "introspect", "clean", "none"]), + ) + .option( + "-y, --yes", + "confirm --schema clean, and fail instead of prompting on an ambiguous rename", + ) + .addHelpText( + "after", + ` +init asks nothing. It keeps this checkout's session branch when .env points at +one, and otherwise uses your dev branch (dev--). New branches fork +the project's default branch, so they start with a copy of its rows, production +data included. init never changes the default branch, a protected branch or a +branch databricks.yml deploys to, and never edits databricks.yml. + +The project comes from LAKEBASE_PROJECT in .env (projects/ or ), else +from LAKEBASE_ENDPOINT, else from the bundle's postgres_branch variable. When +.env names neither DATABRICKS_CONFIG_PROFILE nor DATABRICKS_HOST, init adds the +one it authenticated with. + +Examples: + $ appkit db init + $ appkit db init --session --ttl 1h --schema clean --yes`, + ) + .action(runDbInit); diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index b73bbe163..72304f19d 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -3,7 +3,11 @@ import process from "node:process"; import pc from "picocolors"; -import type { IntrospectReport, MigrateReport } from "./tooling-contract"; +import type { + CleanReport, + IntrospectReport, + MigrateReport, +} from "./tooling-contract"; /** Prompts only when a human can answer them. */ export function isInteractive(): boolean { @@ -15,7 +19,7 @@ export function relative(file: string): string { } /** The last segment of a Lakebase resource name: projects/p/branches/dev-a → dev-a. */ -function shortName(name: string): string { +export function shortName(name: string): string { return name.slice(name.lastIndexOf("/") + 1); } @@ -79,6 +83,19 @@ export function printMigrateReport(report: MigrateReport): void { ok(`Generated ${relative(report.typesFile)}`); } +export function printCleanReport(report: CleanReport): void { + ok( + report.schemaName === "public" + ? `Removed your objects in schema public on ${shortName(report.branch)}` + : `Dropped schema ${report.schemaName} on ${shortName(report.branch)}`, + ); + if (report.dependents.length > 0) { + warn( + `Also removed, because they depended on it: ${report.dependents.join(", ")}`, + ); + } +} + export function printIntrospectReport(report: IntrospectReport): void { const count = report.tables.length; ok( diff --git a/packages/shared/src/cli/commands/db/seed.ts b/packages/shared/src/cli/commands/db/seed.ts new file mode 100644 index 000000000..72a7cf65e --- /dev/null +++ b/packages/shared/src/cli/commands/db/seed.ts @@ -0,0 +1,27 @@ +import { Command } from "commander"; + +import { loadDatabaseTooling } from "./load-tooling"; +import { fail, ok, relative, shortName } from "./output"; + +async function runDbSeed(): Promise { + try { + const tooling = await loadDatabaseTooling(); + const report = await tooling.runSeed(tooling.createDbContext()); + ok(`Ran ${relative(report.file)} on ${shortName(report.branch)}`); + } catch (error) { + fail(error); + } +} + +export const dbSeedCommand = new Command("seed") + .description( + "Run config/database/seed.sql in one transaction on your dev or session branch", + ) + .addHelpText( + "after", + ` +Unqualified names resolve to the app schema first (app, or the schemaName in +config/database/schema.ts), then public. The file already runs in one +transaction, so it must not contain BEGIN or COMMIT.`, + ) + .action(runDbSeed); diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index cb39f69b2..8298134b0 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -39,6 +39,55 @@ export interface IntrospectReport { readonly typesFile: string; } +export type BranchMode = "dev" | "session"; +export type SchemaStart = "migrate" | "introspect" | "clean" | "none"; + +export interface InitOptions { + readonly mode?: BranchMode; + readonly schema?: SchemaStart; + /** As `--ttl` takes it: 30m, 1h, 7d. */ + readonly ttl?: string; + readonly interactive?: boolean; + readonly onStep?: (message: string) => void; +} + +export interface CleanReport { + readonly branch: string; + readonly schemaName: string; + readonly dependents: readonly string[]; +} + +export type InitStart = + | { readonly kind: "none" } + | { readonly kind: "migrate"; readonly migrate: MigrateReport } + | { readonly kind: "introspect"; readonly introspect: IntrospectReport } + | { + readonly kind: "clean"; + readonly clean: CleanReport; + readonly migrate: MigrateReport; + }; + +export interface InitReport { + readonly mode: BranchMode; + readonly branch: string; + readonly created: boolean; + readonly sourceBranch?: string; + readonly expireTime: string | null; + readonly endpoint: string; + readonly endpointCreated: boolean; + readonly host: string; + readonly database: string; + readonly user: string; + readonly role: { + readonly name: string; + readonly action: "kept" | "created" | "updated"; + }; + readonly handedOff: string | null; + readonly envFile: string; + readonly installed: string | null; + readonly start: InitStart; +} + /** * The exports of `@databricks/appkit/database-tooling` the CLI calls. `shared` * must not depend on appkit, so the CLI imports the tooling dynamically and @@ -59,4 +108,13 @@ export interface DatabaseTooling { ctx: Ctx, options: { interactive: boolean; schemaName?: string }, ) => Promise; + readonly runInit: (ctx: Ctx, options?: InitOptions) => Promise; + readonly previewClean: (ctx: Ctx) => Promise; + readonly runClean: (ctx: Ctx) => Promise; + readonly deleteSessionBranch: ( + ctx: Ctx, + ) => Promise<{ readonly branch: string }>; + readonly runSeed: ( + ctx: Ctx, + ) => Promise<{ readonly branch: string; readonly file: string }>; } From 1b3bde79914d3411071f6bfdc78b01f77116b62b Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 12 Oct 2026 13:41:32 +0100 Subject: [PATCH 012/317] feat(appkit): add appkit db verify `appkit db verify` checks, read-only, that the branch .env points at has every table and column config/database/schema.ts declares and every committed migration. It also reports the migrations the migrator would never run there: merged out of order, edited after they ran, or run from a checkout that no longer commits them. With --deployed it checks a databricks.yml target's app through the Databricks API only: the app exists, its postgres resource names the target's branch and database with CAN_CONNECT_AND_CREATE, its service principal has a role there, it is running, and its active deployment has every committed migration. -t picks the target. Verify refuses when the target's workspace.host is not the workspace the shell is authenticated against. It reads no database, so it needs no role on the deploy branch. databricks.yml is read once for the guard, init and verify. The reader follows include:, resolves ${var.*}, ${bundle.target} and ${bundle.name}, reads the branch on an app's postgres resource, and lists every target. Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 3 + .../appkit/src/database/migrations/history.ts | 31 +- .../migrations/tests/apply.pg.test.ts | 2 + .../database/migrations/tests/history.test.ts | 15 + .../appkit/src/database/tooling/context.ts | 2 +- packages/appkit/src/database/tooling/index.ts | 1 + .../appkit/src/database/tooling/migrate.ts | 1 + .../appkit/src/database/tooling/targets.ts | 290 ++++-- .../database/tooling/tests/contract.test.ts | 1 + .../src/database/tooling/tests/fakes.ts | 6 + .../database/tooling/tests/targets.test.ts | 200 ++++- .../src/database/tooling/tests/verify.test.ts | 822 ++++++++++++++++++ .../appkit/src/database/tooling/verify.ts | 519 +++++++++++ .../src/plugins/database/schema-check.ts | 45 +- .../database/tests/schema-check.test.ts | 41 +- packages/shared/src/cli/commands/db/index.ts | 4 +- .../cli/commands/db/init-clean-seed.test.ts | 3 +- packages/shared/src/cli/commands/db/output.ts | 82 ++ .../src/cli/commands/db/tooling-contract.ts | 36 + .../shared/src/cli/commands/db/verify.test.ts | 297 +++++++ packages/shared/src/cli/commands/db/verify.ts | 63 ++ 21 files changed, 2385 insertions(+), 79 deletions(-) create mode 100644 packages/appkit/src/database/tooling/tests/verify.test.ts create mode 100644 packages/appkit/src/database/tooling/verify.ts create mode 100644 packages/shared/src/cli/commands/db/verify.test.ts create mode 100644 packages/shared/src/cli/commands/db/verify.ts diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 14d08800c..b87689325 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -582,6 +582,8 @@ interface MigrationDrift { readonly pending: readonly string[]; /** Committed, not recorded, older than the last recorded one. */ readonly stranded: readonly string[]; + /** Recorded, but the committed file changed since. */ + readonly edited: readonly string[]; /** Recorded rows no committed migration matches: the branch is ahead of the checkout. */ readonly unknown: number; } @@ -592,6 +594,7 @@ function driftOf( return { pending: tags(history.pending), stranded: tags(history.stranded), + edited: tags(history.edited), unknown: history.unknown.length, }; } diff --git a/packages/appkit/src/database/migrations/history.ts b/packages/appkit/src/database/migrations/history.ts index c7ca35cda..bf3583c57 100644 --- a/packages/appkit/src/database/migrations/history.ts +++ b/packages/appkit/src/database/migrations/history.ts @@ -32,29 +32,38 @@ interface MigrationHistory { /** * Match each committed migration with a recorded row by `when` = `created_at`, - * the pair drizzle-orm's migrator writes, then compare hashes. + * the pair drizzle-orm's migrator writes, then compare hashes. Two entries can + * share a `when` after a hand edit or a merge, so each `when` keeps every hash + * recorded at it. */ export function reconcileMigrations( files: readonly MigrationFile[], recorded: readonly RecordedMigration[], ): MigrationHistory { - const hashAt = new Map(); + const hashesAt = new Map>(); for (const row of recorded) { - if (row.createdAt !== null) hashAt.set(row.createdAt, row.hash); + if (row.createdAt === null) continue; + const hashes = hashesAt.get(row.createdAt) ?? new Set(); + hashes.add(row.hash); + hashesAt.set(row.createdAt, hashes); } - const lastRecorded = hashAt.size > 0 ? Math.max(...hashAt.keys()) : null; + const lastRecorded = hashesAt.size > 0 ? Math.max(...hashesAt.keys()) : null; const pending: MigrationFile[] = []; const stranded: MigrationFile[] = []; const edited: MigrationFile[] = []; for (const file of files) { - const hash = hashAt.get(file.when); - if (hash === undefined) { - if (lastRecorded === null || file.when > lastRecorded) pending.push(file); - else stranded.push(file); - } else if (hash !== file.hash) { - edited.push(file); - } + const hashes = hashesAt.get(file.when); + if (hashes?.has(file.hash)) continue; + // A row at this `when` that is another entry's: this one never ran. + const sibling = files.some( + (other) => + other !== file && other.when === file.when && hashes?.has(other.hash), + ); + if (hashes && !sibling) edited.push(file); + else if (lastRecorded === null || file.when > lastRecorded) { + pending.push(file); + } else stranded.push(file); } const committed = new Set(files.map((file) => file.when)); const unknown = recorded.filter( diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts index c3b2d7b99..faa758222 100644 --- a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -442,6 +442,7 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { expect(await readMigrationDrift(newPool(), options(folder))).toEqual({ pending: ["0000_notes", "0001_introspect"], stranded: [], + edited: [], unknown: 0, }); @@ -450,6 +451,7 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { expect(await readMigrationDrift(newPool(), options(folder))).toEqual({ pending: ["0001_introspect"], stranded: [], + edited: [], unknown: 1, }); }); diff --git a/packages/appkit/src/database/migrations/tests/history.test.ts b/packages/appkit/src/database/migrations/tests/history.test.ts index 04da4ac6e..367dd605a 100644 --- a/packages/appkit/src/database/migrations/tests/history.test.ts +++ b/packages/appkit/src/database/migrations/tests/history.test.ts @@ -72,4 +72,19 @@ describe("reconcileMigrations", () => { 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([]); + }); }); diff --git a/packages/appkit/src/database/tooling/context.ts b/packages/appkit/src/database/tooling/context.ts index 1f479f942..93daf4b2c 100644 --- a/packages/appkit/src/database/tooling/context.ts +++ b/packages/appkit/src/database/tooling/context.ts @@ -28,7 +28,7 @@ export interface ToolingWorkspaceClient { readonly currentUser: { me(request: { attributes?: string }): Promise<{ userName?: string }>; }; - /** The resolved workspace host, which init writes to a new .env. */ + /** The resolved workspace host, which init writes to a new .env and verify compares with a target's host. */ getHost(): Promise; } diff --git a/packages/appkit/src/database/tooling/index.ts b/packages/appkit/src/database/tooling/index.ts index c355b52c2..d4dd00b32 100644 --- a/packages/appkit/src/database/tooling/index.ts +++ b/packages/appkit/src/database/tooling/index.ts @@ -28,3 +28,4 @@ export { 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/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 985e1b147..a67c44ca5 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -35,6 +35,7 @@ export function hasSchemaFile(root: string): boolean { const WITHOUT_SCHEMA = { migrate: "there is nothing to migrate", clean: "clean cannot tell which schema to drop", + verify: "there is nothing to verify", } as const; /** Without schema.ts, point to introspect instead of a load error. */ diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index b359e9364..dac93e276 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -79,10 +79,37 @@ export function readLocalTarget(env: NodeJS.ProcessEnv): LocalTarget { }; } -/** The branch the bundle's default target deploys to. */ -export interface DeployTarget { - readonly branch: string; - readonly database: string | null; +/** An app one target of databricks.yml deploys. */ +export interface BundleApp { + /** Its key under resources.apps. */ + readonly key: string; + /** Its name as written; null when it has none. */ + readonly declaredName: string | null; + /** Its name with bundle references resolved; null when one needs a deploy to resolve. */ + readonly name: string | null; + /** Its postgres resource; null when it has none. */ + readonly postgres: { + readonly branch: string | null; + readonly database: string | null; + } | null; +} + +/** One target of databricks.yml, with what the files alone can resolve resolved. */ +export interface BundleTarget { + readonly name: string; + readonly isDefault: boolean; + /** workspace.host of the target, else of the bundle. */ + readonly host: string | null; + readonly apps: readonly BundleApp[]; + /** The target's postgres_branch and postgres_database variables. */ + readonly postgresBranch: string | null; + readonly postgresDatabase: string | null; +} + +interface Bundle { + /** databricks.yml or databricks.yaml. */ + readonly file: string; + readonly targets: readonly BundleTarget[]; } type Yaml = Record | undefined; @@ -93,12 +120,8 @@ function record(value: unknown): Yaml { : undefined; } -/** databricks.yml, parsed; null without one. Invalid YAML throws, so no check that reads it passes silently. */ -function readBundle(root: string): Record | null { - const file = ["databricks.yml", "databricks.yaml"] - .map((name) => path.join(root, name)) - .find((candidate) => fs.existsSync(candidate)); - if (!file) return null; +/** Invalid YAML throws, so no check that reads the bundle passes silently. */ +function parseYaml(file: string): Record { try { return record(yaml.load(fs.readFileSync(file, "utf-8"))) ?? {}; } catch (error) { @@ -110,59 +133,220 @@ function readBundle(root: string): Record | null { } } -/** A target's value for a bundle variable, else the variable's default. */ -function variableOf( +/** Files an `include:` pattern names. `*` and `?` match within one path segment, as in the Databricks CLI. */ +function includedFiles(root: string, pattern: string): string[] { + let paths = [root]; + for (const segment of pattern.split("/")) { + if (!segment || segment === ".") continue; + if (!/[*?]/.test(segment)) { + paths = paths.map((dir) => path.join(dir, segment)); + continue; + } + const matcher = new RegExp( + `^${segment + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\?/g, ".")}$`, + ); + paths = paths.flatMap((dir) => { + try { + return fs + .readdirSync(dir) + .filter((entry) => matcher.test(entry)) + .map((entry) => path.join(dir, entry)); + } catch { + return []; + } + }); + } + return paths.filter((file) => + fs.statSync(file, { throwIfNoEntry: false })?.isFile(), + ); +} + +/** Mappings merge key by key; lists of named entries (an app's resources) merge by name; anything else is replaced. */ +function merge(base: unknown, override: unknown): unknown { + const left = record(base); + const right = record(override); + if (left && right) { + const merged: Record = { ...left }; + for (const [key, value] of Object.entries(right)) { + merged[key] = key in left ? merge(left[key], value) : value; + } + return merged; + } + if (Array.isArray(base) && Array.isArray(override)) { + const named = (items: unknown[]) => + items.every((item) => typeof record(item)?.name === "string"); + if (named(base) && named(override)) { + const byName = new Map( + base.map((item) => [record(item)?.name as string, item]), + ); + for (const item of override) { + const name = record(item)?.name as string; + byName.set(name, merge(byName.get(name), item)); + } + return [...byName.values()]; + } + } + return override; +} + +const REFERENCE = /\$\{([^}]+)\}/g; +const MAX_REFERENCE_DEPTH = 10; + +/** Resolves `${var.*}`, `${bundle.target}` and `${bundle.name}` for one target; null when a reference needs a deploy to resolve. */ +function resolverFor( bundle: Record, target: Yaml, - name: string, -): string | null { - const value = - record(target?.variables)?.[name] ?? - record(record(bundle.variables)?.[name])?.default ?? - null; - return typeof value === "string" && value ? value : null; + targetName: string, +): (value: unknown) => string | null { + const variable = (name: string): unknown => { + const override = record(target?.variables)?.[name]; + if (override !== undefined) return record(override)?.default ?? override; + return record(record(bundle.variables)?.[name])?.default; + }; + const resolve = (value: unknown, depth: number): string | null => { + if (typeof value !== "string" || depth > MAX_REFERENCE_DEPTH) return null; + let unresolved = false; + const text = value.replace(REFERENCE, (_, reference: string) => { + const resolved = reference.startsWith("var.") + ? resolve(variable(reference.slice("var.".length)), depth + 1) + : reference === "bundle.target" + ? targetName + : reference === "bundle.name" + ? resolve(record(bundle.bundle)?.name, depth + 1) + : null; + if (resolved === null) unresolved = true; + return resolved ?? ""; + }); + return unresolved || !text ? null : text; + }; + return (value) => resolve(value, 0); +} + +function bundleApps( + apps: Record, + resolve: (value: unknown) => string | null, +): BundleApp[] { + return Object.entries(apps).map(([key, value]) => { + const app = record(value); + const declared = app?.name; + const resources = Array.isArray(app?.resources) ? app.resources : []; + const postgres = resources + .map((resource) => record(record(resource)?.postgres)) + .find((binding) => binding !== undefined); + return { + key, + declaredName: typeof declared === "string" && declared ? declared : null, + name: resolve(declared), + postgres: postgres + ? { + branch: + parseResourceName(resolve(postgres.branch) ?? undefined) + ?.branch ?? null, + database: + parseResourceName(resolve(postgres.database) ?? undefined) + ?.database ?? null, + } + : null, + }; + }); } -/** Default target's postgres_branch / postgres_database variables; null without databricks.yml or binding. */ +/** + * databricks.yml, with the files its `include:` names merged in, per target; + * null without one. Without `targets:` the bundle has one target, "default". + */ +export function readBundle(root: string): Bundle | null { + const file = ["databricks.yml", "databricks.yaml"] + .map((name) => path.join(root, name)) + .find((candidate) => fs.existsSync(candidate)); + if (!file) return null; + const main = parseYaml(file); + const includes = Array.isArray(main.include) ? main.include : []; + const bundle = record( + includes + .filter((pattern): pattern is string => typeof pattern === "string") + .flatMap((pattern) => includedFiles(root, pattern)) + .reduce( + (merged, included) => merge(merged, parseYaml(included)), + main, + ), + ) as Record; + + const declared = Object.entries(record(bundle.targets) ?? {}); + const targets: Array<[string, Yaml]> = + declared.length > 0 + ? declared.map(([name, target]) => [name, record(target)]) + : [["default", { default: true }]]; + return { + file: path.basename(file), + targets: targets.map(([name, target]) => { + const resolve = resolverFor(bundle, target, name); + const apps = record( + merge( + record(record(bundle.resources)?.apps) ?? {}, + record(record(target?.resources)?.apps) ?? {}, + ), + ); + const variable = (variableName: string) => + resolve(`\${var.${variableName}}`) ?? undefined; + return { + name, + isDefault: target?.default === true, + host: resolve( + record(target?.workspace)?.host ?? record(bundle.workspace)?.host, + ), + apps: bundleApps(apps ?? {}, resolve), + postgresBranch: + parseResourceName(variable("postgres_branch"))?.branch ?? null, + postgresDatabase: + parseResourceName(variable("postgres_database"))?.database ?? null, + }; + }), + }; +} + +/** The target `databricks bundle deploy` picks without -t: the one marked default, else the only one. */ +export function defaultBundleTarget(bundle: Bundle): BundleTarget | null { + return ( + bundle.targets.find((target) => target.isDefault) ?? + (bundle.targets.length === 1 ? (bundle.targets[0] ?? null) : null) + ); +} + +/** Every branch a target deploys to: its apps' postgres resources, and its postgres_branch variable. */ +function targetBranches(target: BundleTarget): string[] { + return [ + ...target.apps.map((app) => app.postgres?.branch), + target.postgresBranch, + ].filter((branch): branch is string => !!branch); +} + +/** The branch and database a target deploys to. */ +export interface DeployTarget { + readonly branch: string; + readonly database: string | null; +} + +/** The default target's branch and database; null without databricks.yml, a default target or a postgres binding. */ export function readDeployTarget(root: string): DeployTarget | null { const bundle = readBundle(root); - if (!bundle) return null; - const targets = record(bundle.targets) ?? {}; - const target = - Object.values(targets) - .map(record) - .find((candidate) => candidate?.default === true) ?? - record(targets.default); - - const branch = parseResourceName( - variableOf(bundle, target, "postgres_branch") ?? undefined, - )?.branch; + const target = bundle ? defaultBundleTarget(bundle) : null; + if (!target) return null; + const bound = target.apps.find((app) => app.postgres?.branch); + const branch = bound?.postgres?.branch ?? target.postgresBranch; if (!branch) return null; - const database = - parseResourceName( - variableOf(bundle, target, "postgres_database") ?? undefined, - )?.database ?? null; - return { branch, database }; + return { + branch, + database: bound?.postgres?.database ?? target.postgresDatabase, + }; } -/** - * Every branch databricks.yml can deploy to: each target's postgres_branch and - * the variable's default. Empty without databricks.yml or a postgres binding. - */ +/** Every branch databricks.yml can deploy to, across targets. Empty without databricks.yml or a postgres binding. */ export function readDeployBranches(root: string): string[] { const bundle = readBundle(root); if (!bundle) return []; - const targets = [ - undefined, - ...Object.values(record(bundle.targets) ?? {}).map(record), - ]; - const branches = targets - .map( - (target) => - parseResourceName( - variableOf(bundle, target, "postgres_branch") ?? undefined, - )?.branch, - ) - .filter((branch): branch is string => !!branch); - return [...new Set(branches)]; + return [...new Set(bundle.targets.flatMap(targetBranches))]; } diff --git a/packages/appkit/src/database/tooling/tests/contract.test.ts b/packages/appkit/src/database/tooling/tests/contract.test.ts index ed47a4f7a..fae9f6560 100644 --- a/packages/appkit/src/database/tooling/tests/contract.test.ts +++ b/packages/appkit/src/database/tooling/tests/contract.test.ts @@ -17,6 +17,7 @@ const contractKeys = { runIntrospect: true, runMigrate: true, runSeed: true, + runVerify: true, } satisfies Record; test("every function the CLI is typed with is exported", () => { diff --git a/packages/appkit/src/database/tooling/tests/fakes.ts b/packages/appkit/src/database/tooling/tests/fakes.ts index d7e829fa4..df31a19fc 100644 --- a/packages/appkit/src/database/tooling/tests/fakes.ts +++ b/packages/appkit/src/database/tooling/tests/fakes.ts @@ -249,6 +249,12 @@ resources: app: name: "my-app" source_code_path: ./ + resources: + - name: postgres + postgres: + branch: \${var.postgres_branch} + database: \${var.postgres_database} + permission: CAN_CONNECT_AND_CREATE targets: default: default: true diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index 6be36190e..ad24482f1 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -3,6 +3,7 @@ import { afterEach, describe, expect, test } from "vitest"; import { parseProject, parseResourceName, + readBundle, readDeployBranches, readDeployTarget, readLocalTarget, @@ -124,6 +125,24 @@ targets: ]); }); + test("a branch set on an app's postgres resource counts, in an included file too", () => { + const root = tempApp({ + "databricks.yml": "include:\n - resources/*.yml\n", + "resources/app.yml": `resources: + apps: + app: + name: shop + resources: + - name: postgres + postgres: + branch: projects/p/branches/production +`, + }); + expect(readDeployBranches(root)).toEqual([ + "projects/p/branches/production", + ]); + }); + test("empty without databricks.yml or without a postgres binding", () => { expect(readDeployBranches(tempApp())).toEqual([]); expect( @@ -140,7 +159,7 @@ targets: }); describe("readDeployTarget", () => { - test("reads the default target's postgres variables", () => { + test("reads the default target's postgres resource", () => { const root = tempApp({ "databricks.yml": databricksYml( "projects/p/branches/production", @@ -169,10 +188,187 @@ targets: }); }); - test("null without databricks.yml or without a postgres binding", () => { + test("null without databricks.yml, a default target or a postgres binding", () => { expect(readDeployTarget(tempApp())).toBeNull(); expect( readDeployTarget(tempApp({ "databricks.yml": "bundle:\n name: x\n" })), ).toBeNull(); + expect( + readDeployTarget( + tempApp({ + "databricks.yml": `variables: + postgres_branch: + default: projects/p/branches/main +targets: + dev: {} + prod: {} +`, + }), + ), + ).toBeNull(); + }); +}); + +describe("readBundle", () => { + test("resolves each target's app, postgres resource and host from its variables", () => { + const root = tempApp({ + "databricks.yml": `bundle: + name: shop +variables: + postgres_branch: + default: projects/p/branches/main + postgres_database: + default: projects/p/branches/main/databases/db + suffix: + default: dev +workspace: + host: https://dev.cloud.databricks.com +resources: + apps: + app: + name: \${bundle.name}-\${var.suffix} + resources: + - name: postgres + postgres: + branch: \${var.postgres_branch} + database: \${var.postgres_database} +targets: + default: + default: true + prod: + workspace: + host: https://prod.cloud.databricks.com + variables: + suffix: \${bundle.target} + postgres_branch: projects/p/branches/production + postgres_database: projects/p/branches/production/databases/db +`, + }); + + expect(readBundle(root)).toEqual({ + file: "databricks.yml", + targets: [ + { + name: "default", + isDefault: true, + host: "https://dev.cloud.databricks.com", + apps: [ + { + key: "app", + declaredName: "${bundle.name}-${var.suffix}", + name: "shop-dev", + postgres: { + branch: "projects/p/branches/main", + database: "projects/p/branches/main/databases/db", + }, + }, + ], + postgresBranch: "projects/p/branches/main", + postgresDatabase: "projects/p/branches/main/databases/db", + }, + { + name: "prod", + isDefault: false, + host: "https://prod.cloud.databricks.com", + apps: [ + { + key: "app", + declaredName: "${bundle.name}-${var.suffix}", + name: "shop-prod", + postgres: { + branch: "projects/p/branches/production", + database: "projects/p/branches/production/databases/db", + }, + }, + ], + postgresBranch: "projects/p/branches/production", + postgresDatabase: "projects/p/branches/production/databases/db", + }, + ], + }); + }); + + test("follows include:, and a target's app override merges resources by name", () => { + const root = tempApp({ + "databricks.yml": `include: + - resources/*.yml +targets: + default: + default: true + resources: + apps: + app: + resources: + - name: postgres + postgres: + branch: projects/p/branches/production +`, + "resources/app.yml": `resources: + apps: + app: + name: shop + resources: + - name: warehouse + sql_warehouse: + id: w + - name: postgres + postgres: + branch: projects/p/branches/main + database: projects/p/branches/main/databases/db +`, + "resources/notes.txt": "not yaml: [", + }); + + const [target] = readBundle(root)?.targets ?? []; + expect(target?.apps).toEqual([ + { + key: "app", + declaredName: "shop", + name: "shop", + postgres: { + branch: "projects/p/branches/production", + database: "projects/p/branches/main/databases/db", + }, + }, + ]); + }); + + test("a reference only a deploy resolves reads as null; no targets is one default target", () => { + const root = tempApp({ + "databricks.yml": `variables: + warehouse: + lookup: + warehouse: Shared +resources: + apps: + app: + name: shop-\${workspace.current_user.short_name} +`, + }); + expect(readBundle(root)?.targets).toEqual([ + { + name: "default", + isDefault: true, + host: null, + apps: [ + { + key: "app", + declaredName: "shop-${workspace.current_user.short_name}", + name: null, + postgres: null, + }, + ], + postgresBranch: null, + postgresDatabase: null, + }, + ]); + }); + + test("an invalid included file throws, naming it", () => { + const root = tempApp({ + "databricks.yml": "include:\n - resources/*.yml\n", + "resources/app.yml": "resources: [\n", + }); + expect(() => readBundle(root)).toThrow(/^Cannot read app\.yml, /); }); }); diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts new file mode 100644 index 000000000..70d57db23 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -0,0 +1,822 @@ +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { withBranchPool } = vi.hoisted(() => ({ withBranchPool: vi.fn() })); + +vi.mock("../context", async (importOriginal) => ({ + ...(await importOriginal()), + withBranchPool, +})); + +import type { WorkspaceRequest } from "../../../workspace-client"; +import type { DbContext } from "../context"; +import { runVerify, type VerifyOptions } from "../verify"; +import { databricksYml, FakeLakebase } from "./fakes"; + +const builder = path.resolve( + import.meta.dirname, + "../../schema-builder/index.ts", +); +const BRANCH = "projects/p/branches/dev-alice-3f9a2c"; +const ENV = { + PGHOST: "ep-1.example.com", + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: `${BRANCH}/endpoints/primary`, +}; +const MIGRATIONS = "config/database/migrations"; +const roots: string[] = []; + +type Migration = { tag: string; when: number }; + +function journal(migrations: Migration[]): string { + return JSON.stringify({ + version: "7", + dialect: "postgresql", + entries: migrations.map((m, idx) => ({ + idx, + version: "7", + when: m.when, + tag: m.tag, + breakpoints: true, + })), + }); +} + +/** An app whose schema.ts declares app.notes(id, body), with the given committed migrations. */ +function app( + migrations: Migration[] = [], + env: NodeJS.ProcessEnv = ENV, +): DbContext { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-db-verify-")); + roots.push(root); + const file = path.join(root, "config/database/schema.ts"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync( + file, + `import { defineSchema, id, text } from ${JSON.stringify(builder)}; + export const schema = defineSchema(({ table }) => ({ + notes: table("notes", { id: id(), body: text() }), + }));`, + ); + if (migrations.length > 0) { + const meta = path.join(root, MIGRATIONS, "meta"); + fs.mkdirSync(meta, { recursive: true }); + fs.writeFileSync(path.join(meta, "_journal.json"), journal(migrations)); + for (const m of migrations) { + fs.writeFileSync( + path.join(root, MIGRATIONS, `${m.tag}.sql`), + `-- ${m.tag}\nselect 1;\n`, + ); + } + } + return { + root, + env, + workspace: () => { + throw new Error("no workspace calls expected"); + }, + api: () => { + throw new Error("no Lakebase API calls expected"); + }, + }; +} + +/** Journal rows as the migrator writes them: the file's sha256 and the journal's `when`. */ +function recordedAs(ctx: DbContext, migrations: Migration[]) { + return migrations.map((m) => ({ + hash: createHash("sha256") + .update( + fs.readFileSync( + path.join(ctx.root, MIGRATIONS, `${m.tag}.sql`), + "utf-8", + ), + ) + .digest("hex"), + created_at: String(m.when), + })); +} + +/** + * A connection answering the catalog and journal queries; it records every + * statement. + */ +function branch(state: { + columns: Record; + /** The journal table's rows; "absent" without the table. */ + recorded: Array<{ hash: string; created_at: string }> | "absent"; + failOn?: RegExp; +}) { + const statements: string[] = []; + const client = { + query: vi.fn(async (text: string, values?: unknown[]) => { + statements.push(text); + if (state.failOn?.test(text)) throw new Error("connection reset"); + if (/pg_catalog\.pg_attribute/.test(text)) { + expect(values?.[0]).toBe("app"); + return { + rows: Object.entries(state.columns).flatMap(([table, columns]) => + columns.map((column) => ({ + table_name: table, + column_name: column, + relation_kind: "r", + })), + ), + }; + } + if (/from pg_catalog\.pg_class c\s+join/.test(text)) { + return { rows: state.recorded === "absent" ? [] : [{ "?column?": 1 }] }; + } + if (/select hash, created_at from/.test(text)) { + return { rows: state.recorded === "absent" ? [] : state.recorded }; + } + return { rows: [] }; + }), + release: vi.fn(), + }; + const pool = { + connect: vi.fn(async () => client), + end: vi.fn(async () => undefined), + }; + withBranchPool.mockImplementation(async (_ctx, fn) => { + try { + return await fn(pool); + } finally { + await pool.end(); + } + }); + return { statements, client, pool }; +} + +const WRITES = /\b(insert|update|delete|create|drop|alter|grant|truncate)\b/i; + +beforeEach(() => { + withBranchPool.mockReset(); +}); + +afterEach(() => { + for (const root of roots.splice(0)) { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +describe("runVerify", () => { + const two = [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_migration", when: 2000 }, + ]; + const clean = { + schemaProblems: [], + pendingMigrations: [], + strandedMigrations: [], + editedMigrations: [], + unknownMigrations: 0, + }; + + test("a branch that matches schema.ts and has every migration is ok", async () => { + const ctx = app(two); + const { pool } = branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + }); + + expect(await runVerify(ctx)).toEqual({ + kind: "local", + branch: BRANCH, + ...clean, + ok: true, + }); + expect(pool.end).toHaveBeenCalledOnce(); + }); + + test("reports schema problems and pending migrations separately", async () => { + const ctx = app(two); + branch({ + columns: { notes: ["id"] }, + recorded: recordedAs(ctx, two.slice(0, 1)), + }); + + expect(await runVerify(ctx)).toMatchObject({ + ...clean, + schemaProblems: ["table app.notes is missing column body"], + pendingMigrations: ["0001_migration"], + ok: false, + }); + }); + + test("without a journal table every committed migration is pending", async () => { + const ctx = app([{ tag: "0000_baseline", when: 1000 }]); + branch({ columns: {}, recorded: "absent" }); + + expect(await runVerify(ctx)).toMatchObject({ + schemaProblems: ["table app.notes does not exist"], + pendingMigrations: ["0000_baseline"], + ok: false, + }); + }); + + test("a migration merged out of order, older than the last one the branch ran, never runs", async () => { + const migrations = [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_parallel", when: 1500 }, + { tag: "0002_migration", when: 2000 }, + ]; + const ctx = app(migrations); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, [migrations[0], migrations[2]] as Migration[]), + }); + + expect(await runVerify(ctx)).toMatchObject({ + ...clean, + strandedMigrations: ["0001_parallel"], + ok: false, + }); + }); + + test("a migration edited after the branch ran it never runs again", async () => { + const ctx = app(two); + const recorded = recordedAs(ctx, two); + fs.appendFileSync( + path.join(ctx.root, MIGRATIONS, "0000_migration.sql"), + "select 2;\n", + ); + branch({ columns: { notes: ["id", "body"] }, recorded }); + + expect(await runVerify(ctx)).toMatchObject({ + ...clean, + editedMigrations: ["0000_migration"], + ok: false, + }); + }); + + test("a migration the branch ran that this checkout does not commit is reported", async () => { + const ctx = app(two); + branch({ + columns: { notes: ["id", "body"] }, + recorded: [ + ...recordedAs(ctx, two), + { hash: "from-another-git-branch", created_at: "3000" }, + ], + }); + + expect(await runVerify(ctx)).toMatchObject({ + ...clean, + unknownMigrations: 1, + ok: false, + }); + }); + + test("no committed migrations: only the schema is checked", async () => { + const ctx = app(); + branch({ columns: { notes: ["id", "body"] }, recorded: "absent" }); + + expect((await runVerify(ctx)).ok).toBe(true); + }); + + test("never writes: everything runs in a READ ONLY transaction that is rolled back", async () => { + const ctx = app([{ tag: "0000_migration", when: 1000 }]); + const { statements, client } = branch({ + columns: { notes: ["id"] }, + recorded: [], + }); + + await runVerify(ctx); + + expect(statements[0]).toBe("begin transaction read only"); + expect(statements.at(-1)).toBe("rollback"); + expect(statements.filter((s) => WRITES.test(s))).toEqual([]); + expect(client.release).toHaveBeenCalledOnce(); + }); + + test("a failing query rolls back, releases the connection and ends the pool", async () => { + const ctx = app([{ tag: "0000_migration", when: 1000 }]); + const { statements, client, pool } = branch({ + columns: {}, + recorded: [], + failOn: /select hash, created_at/, + }); + + await expect(runVerify(ctx)).rejects.toThrow("connection reset"); + expect(statements.at(-1)).toBe("rollback"); + expect(client.release).toHaveBeenCalledOnce(); + expect(pool.end).toHaveBeenCalledOnce(); + }); + + test("without a configured branch it points to init before connecting", async () => { + await expect(runVerify(app([], {}))).rejects.toThrow( + "Did not verify: no branch is configured in .env (PGHOST, PGDATABASE and LAKEBASE_ENDPOINT); run `appkit db init`.", + ); + expect(withBranchPool).not.toHaveBeenCalled(); + }); + + test("without schema.ts it points to introspect", async () => { + const ctx = app(); + fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); + + await expect(runVerify(ctx)).rejects.toThrow( + "No config/database/schema.ts yet, so there is nothing to verify. Run `appkit db introspect` to write it from the branch's tables, or create it.", + ); + expect(withBranchPool).not.toHaveBeenCalled(); + }); +}); + +const PRODUCTION = "projects/p/branches/production"; +const DATABASE = `${PRODUCTION}/databases/db-1`; +const SP = "11111111-2222-3333-4444-555555555555"; +const HOST = "https://acme.cloud.databricks.com"; +const SNAPSHOT = "/Workspace/Users/sp/src/01f0"; +const DEPLOYED_AT = "2026-10-01T12:00:00Z"; + +/** The app API's response for a deployed, running app bound to the deploy branch. */ +function runningApp(overrides: Record = {}) { + return { + name: "my-app", + service_principal_client_id: SP, + resources: [ + { + name: "postgres", + postgres: { + branch: PRODUCTION, + database: DATABASE, + permission: "CAN_CONNECT_AND_CREATE", + }, + }, + ], + app_status: { state: "RUNNING", message: "App is running." }, + compute_status: { state: "ACTIVE", message: "App compute is running." }, + active_deployment: { + create_time: DEPLOYED_AT, + deployment_artifacts: { source_code_path: SNAPSHOT }, + status: { state: "SUCCEEDED", message: "App started successfully" }, + }, + ...overrides, + }; +} + +/** databricks.yml with a workspace host on its default target. */ +function ymlWithHost(host = HOST): string { + return `${databricksYml(PRODUCTION, DATABASE)} workspace:\n host: ${host}\n`; +} + +/** + * An app that databricks.yml deploys to the deploy branch. The developer has + * no Postgres role there: --deployed must not need one. + */ +function deployedApp( + options: { + app?: Record | "missing" | Error; + yml?: string; + spRole?: boolean; + migrations?: Migration[]; + /** The deployed snapshot's journal; "unreadable" when export fails. */ + deployedJournal?: Migration[] | "unreadable"; + authenticatedHost?: string; + } = {}, +) { + const base = app(options.migrations ?? [], {}); + fs.writeFileSync( + path.join(base.root, "databricks.yml"), + options.yml ?? ymlWithHost(), + ); + const lakebase = new FakeLakebase(); + lakebase.addBranch(PRODUCTION, { default: true }); + if (options.spRole !== false) { + lakebase.addRole(PRODUCTION, `dbrx-apps-${SP}`, SP); + } + lakebase.databases.set(DATABASE, { + name: DATABASE, + status: { postgres_database: "appdb" }, + }); + const requests: string[] = []; + const ctx: DbContext = { + ...base, + workspace: () => ({ + request: async ({ method, path: apiPath, query }: WorkspaceRequest) => { + const appName = /^\/api\/2\.0\/apps\/([^/]+)$/.exec(apiPath)?.[1]; + if (method === "GET" && appName) { + requests.push(`apps.get ${decodeURIComponent(appName)}`); + const response = options.app ?? runningApp(); + if (response === "missing") { + throw Object.assign(new Error("App my-app does not exist."), { + statusCode: 404, + }); + } + if (response instanceof Error) throw response; + return Response.json(response); + } + if (method === "GET" && apiPath === "/api/2.0/workspace/export") { + expect(query?.format).toBe("AUTO"); + requests.push(`workspace.export ${query?.path}`); + const deployed = options.deployedJournal ?? options.migrations ?? []; + if (deployed === "unreadable") { + throw Object.assign(new Error("Permission denied"), { + statusCode: 403, + }); + } + return Response.json({ + content: Buffer.from(journal(deployed)).toString("base64"), + }); + } + throw new Error( + `--deployed only reads the app and its journal, not ${method} ${apiPath}`, + ); + }, + currentUser: { + me: async () => { + throw new Error("--deployed does not need the developer's identity"); + }, + }, + getHost: async () => options.authenticatedHost ?? HOST, + }), + api: () => lakebase.api(), + }; + return { ctx, lakebase, requests }; +} + +const DEPLOYED: VerifyOptions = { deployed: true }; + +/** --deployed's problems; fails when the report is not a deploy report. */ +async function deployProblems( + ctx: DbContext, + options: VerifyOptions = DEPLOYED, +): Promise { + const report = await runVerify(ctx, options); + if (report.kind !== "deploy") throw new Error("expected a deploy report"); + return report.problems; +} + +/** databricks.yml with the given resources block in place of the default app. */ +function ymlWithApps(apps: string): string { + return databricksYml(PRODUCTION, DATABASE).replace( + /resources:\n {2}apps:\n(?: {4}.*\n)+/, + apps, + ); +} + +describe("runVerify --deployed", () => { + test("a running app bound to the deploy branch with every committed migration is ok, with no database connection and no role of yours there", async () => { + const migrations = [{ tag: "0000_migration", when: 1000 }]; + const { ctx, lakebase, requests } = deployedApp({ migrations }); + + expect(await runVerify(ctx, DEPLOYED)).toEqual({ + kind: "deploy", + target: "default", + host: HOST, + branch: PRODUCTION, + app: "my-app", + migrations: { checked: "deployed code", missing: [] }, + problems: [], + ok: true, + }); + expect(requests).toEqual([ + "apps.get my-app", + `workspace.export ${SNAPSHOT}/config/database/migrations/meta/_journal.json`, + ]); + expect(withBranchPool).not.toHaveBeenCalled(); + expect(lakebase.calls.sort()).toEqual([ + `getBranch ${PRODUCTION}`, + `getDatabase ${DATABASE}`, + `listRoles ${PRODUCTION}`, + ]); + }); + + test("a committed migration the active deployment lacks fails it", async () => { + const migrations = [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_migration", when: 2000 }, + ]; + const { ctx } = deployedApp({ + migrations, + deployedJournal: migrations.slice(0, 1), + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { checked: "deployed code", missing: ["0001_migration"] }, + problems: [ + "app my-app's active deployment does not have 0001_migration, which this checkout commits: `databricks apps deploy` deploys it, and the app applies it on start", + ], + ok: false, + }); + }); + + test("when the deployed code cannot be read, migrations generated after the deployment fail it", async () => { + const deployedAt = Date.parse(DEPLOYED_AT); + const { ctx } = deployedApp({ + migrations: [ + { tag: "0000_migration", when: deployedAt - 1000 }, + { tag: "0001_migration", when: deployedAt + 1000 }, + ], + deployedJournal: "unreadable", + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { checked: "deploy time", missing: ["0001_migration"] }, + problems: [ + `0001_migration was generated after app my-app's active deployment (${DEPLOYED_AT}), so it does not have it: \`databricks apps deploy\` deploys it, and the app applies it on start`, + ], + }); + }); + + test("without committed migrations nothing is compared, and schema.ts is not needed", async () => { + const { ctx, requests } = deployedApp(); + fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: null, + ok: true, + }); + expect(requests).toEqual(["apps.get my-app"]); + }); + + test("--target checks that target's app, branch and host", async () => { + const staging = "projects/p/branches/staging"; + const { ctx, lakebase } = deployedApp({ + yml: `${ymlWithHost()} staging: + workspace: + host: ${HOST} + variables: + postgres_branch: ${staging} + postgres_database: ${staging}/databases/db-1 +`, + app: runningApp({ + resources: [ + { + postgres: { + branch: staging, + database: `${staging}/databases/db-1`, + permission: "CAN_CONNECT_AND_CREATE", + }, + }, + ], + }), + }); + lakebase.addBranch(staging); + lakebase.addRole(staging, `dbrx-apps-${SP}`, SP); + lakebase.databases.set(`${staging}/databases/db-1`, { + name: `${staging}/databases/db-1`, + status: { postgres_database: "appdb" }, + }); + + expect( + await runVerify(ctx, { deployed: true, target: "staging" }), + ).toMatchObject({ target: "staging", branch: staging, ok: true }); + }); + + test("an unknown target, or no default target, names the targets there are", async () => { + const { ctx } = deployedApp(); + await expect( + runVerify(ctx, { deployed: true, target: "prod" }), + ).rejects.toThrow( + "databricks.yml has no target prod; its targets are default.", + ); + + const twoTargets = deployedApp({ + yml: ymlWithHost().replace(" default: true\n", "") + " prod: {}\n", + }); + await expect(runVerify(twoTargets.ctx, DEPLOYED)).rejects.toThrow( + "databricks.yml has no default target; pass --target with one of default, prod.", + ); + }); + + test("a shell authenticated against another workspace is refused before any API call", async () => { + const { ctx, lakebase, requests } = deployedApp({ + authenticatedHost: "https://other.cloud.databricks.com", + }); + + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + `Target default deploys to ${HOST}, but this shell is authenticated against https://other.cloud.databricks.com. Set DATABRICKS_CONFIG_PROFILE to a profile for ${HOST}, then rerun.`, + ); + expect(requests).toEqual([]); + expect(lakebase.calls).toEqual([]); + }); + + test("a host written without a scheme or with a trailing slash matches", async () => { + const { ctx } = deployedApp({ + yml: ymlWithHost("acme.cloud.databricks.com/"), + }); + expect((await runVerify(ctx, DEPLOYED)).ok).toBe(true); + }); + + test("an app that does not exist yet: deploy it", async () => { + const { ctx, lakebase } = deployedApp({ app: "missing" }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + problems: [ + "app my-app is not deployed yet: `databricks apps deploy` creates it and gives it access to production", + ], + ok: false, + }); + expect(lakebase.calls).not.toContain(`listRoles ${PRODUCTION}`); + }); + + test.each([ + [ + "another branch", + [ + { + postgres: { + branch: "projects/p/branches/staging", + database: DATABASE, + permission: "CAN_CONNECT_AND_CREATE", + }, + }, + ], + `app my-app uses branch projects/p/branches/staging, not ${PRODUCTION} from databricks.yml: \`databricks apps deploy\` applies databricks.yml`, + ], + [ + "no postgres resource", + [{ sql_warehouse: { id: "w", permission: "CAN_USE" } }], + "app my-app has no postgres resource: `databricks apps deploy` adds the one databricks.yml declares", + ], + [ + "another database", + [ + { + postgres: { + branch: PRODUCTION, + database: `${PRODUCTION}/databases/other`, + permission: "CAN_CONNECT_AND_CREATE", + }, + }, + ], + `app my-app uses database ${PRODUCTION}/databases/other, not ${DATABASE} from databricks.yml: \`databricks apps deploy\` applies databricks.yml`, + ], + [ + "a permission that cannot create the schema", + [ + { + postgres: { + branch: PRODUCTION, + database: DATABASE, + permission: "CAN_CONNECT", + }, + }, + ], + "app my-app's postgres resource has permission CAN_CONNECT, but the app needs CAN_CONNECT_AND_CREATE to create its schema: set it in databricks.yml, then run `databricks apps deploy`", + ], + ])("a postgres resource with %s", async (_label, resources, problem) => { + const { ctx, lakebase } = deployedApp({ app: runningApp({ resources }) }); + + expect(await deployProblems(ctx)).toEqual([problem]); + expect(lakebase.calls).not.toContain(`listRoles ${PRODUCTION}`); + }); + + test("a service principal without a role on the branch", async () => { + const { ctx } = deployedApp({ spRole: false }); + + expect(await deployProblems(ctx)).toEqual([ + `the app's service principal ${SP} has no Postgres role on production: \`databricks apps deploy\` creates it from the app's postgres resource`, + ]); + }); + + test.each([ + [ + "crashed", + { + app_status: { state: "CRASHED", message: "App crashed unexpectedly." }, + }, + "app my-app is crashed: App crashed unexpectedly. `databricks apps logs` shows why; a migration that fails stops the app on start", + ], + [ + // As the API returns it: a stopped app has no active_deployment. + "stopped", + { + compute_status: { + state: "STOPPED", + message: "Start the app compute to deploy the app.", + }, + app_status: { + state: "UNAVAILABLE", + message: "App status is unavailable.", + }, + active_deployment: undefined, + }, + "app my-app is stopped: `databricks apps start` starts its last deployment, or `databricks apps deploy` deploys the current code; it migrates on start", + ], + [ + "starting", + { compute_status: { state: "STARTING" } }, + "app my-app's compute is starting", + ], + [ + "a failed deployment", + { + pending_deployment: { + status: { state: "FAILED", message: "Build failed." }, + }, + }, + "the last deployment of app my-app failed: Build failed. `databricks apps logs` shows why", + ], + [ + "a deployment in progress", + { pending_deployment: { status: { state: "IN_PROGRESS" } } }, + "a deployment of app my-app is in progress: run verify again when it finishes", + ], + [ + "no deployment", + { active_deployment: undefined, app_status: { state: "UNAVAILABLE" } }, + "app my-app has no deployment yet: `databricks apps deploy` deploys it", + ], + ])("an app that is %s", async (_label, overrides, problem) => { + const { ctx } = deployedApp({ app: runningApp(overrides) }); + + expect(await deployProblems(ctx)).toEqual([problem]); + }); + + test("a deploy branch or database that does not exist", async () => { + const { ctx, lakebase } = deployedApp(); + lakebase.databases.clear(); + expect(await deployProblems(ctx)).toEqual([ + `databricks.yml binds database ${DATABASE}, which does not exist on production`, + ]); + + lakebase.branches.clear(); + expect(await deployProblems(ctx)).toEqual([ + `databricks.yml deploys to ${PRODUCTION}, which does not exist`, + ]); + }); + + test("an app name with a reference only a deploy resolves is reported before any API call; ${bundle.target} resolves", async () => { + const unresolved = deployedApp({ + yml: ymlWithApps( + `resources:\n apps:\n app:\n name: "my-app-\${workspace.current_user.short_name}"\n resources:\n - name: postgres\n postgres:\n branch: \${var.postgres_branch}\n`, + ), + }); + expect(await deployProblems(unresolved.ctx)).toEqual([ + "databricks.yml names the app my-app-${workspace.current_user.short_name}, with a reference verify cannot resolve", + ]); + expect(unresolved.requests).toEqual([]); + expect(unresolved.lakebase.calls).toEqual([]); + + const perTarget = deployedApp({ + yml: ymlWithApps( + `resources:\n apps:\n app:\n name: "my-\${bundle.target}"\n resources:\n - name: postgres\n postgres:\n branch: \${var.postgres_branch}\n`, + ), + app: "missing", + }); + await runVerify(perTarget.ctx, DEPLOYED); + expect(perTarget.requests).toEqual(["apps.get my-default"]); + }); + + test("a target without an app, or with several apps on postgres, says so", async () => { + const none = deployedApp({ yml: ymlWithApps("") }); + expect(await runVerify(none.ctx, DEPLOYED)).toMatchObject({ + app: null, + problems: ["target default in databricks.yml declares no app"], + ok: false, + }); + expect(none.requests).toEqual([]); + + const postgres = + " resources:\n - name: postgres\n postgres:\n branch: ${var.postgres_branch}\n"; + const several = deployedApp({ + yml: ymlWithApps( + `resources:\n apps:\n web:\n name: web\n${postgres} worker:\n name: worker\n${postgres}`, + ), + }); + await expect(runVerify(several.ctx, DEPLOYED)).rejects.toThrow( + "Target default deploys 2 apps with a postgres resource (web, worker); verify checks one app per target.", + ); + }); + + test("an error other than 404 from the apps API names the app", async () => { + const { ctx } = deployedApp({ + app: Object.assign(new Error("Forbidden"), { statusCode: 403 }), + }); + + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + "Could not read app my-app: Forbidden", + ); + }); + + test("never writes and never connects to the database", async () => { + const { ctx, lakebase } = deployedApp({ spRole: false }); + + await runVerify(ctx, DEPLOYED); + + expect(withBranchPool).not.toHaveBeenCalled(); + expect(lakebase.calls.filter((c) => !/^(get|list)[A-Z]/.test(c))).toEqual( + [], + ); + }); + + test("without databricks.yml, or without a postgres binding in it, it says so", async () => { + const { ctx } = deployedApp(); + fs.writeFileSync( + path.join(ctx.root, "databricks.yml"), + "resources:\n apps:\n app:\n name: my-app\n", + ); + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + "No deploy branch: target default in databricks.yml declares no app with a postgres resource.", + ); + + fs.rmSync(path.join(ctx.root, "databricks.yml")); + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + "No databricks.yml, so there is no deployed app to verify.", + ); + }); +}); diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts new file mode 100644 index 000000000..3c436ff02 --- /dev/null +++ b/packages/appkit/src/database/tooling/verify.ts @@ -0,0 +1,519 @@ +import path from "node:path"; + +import type { PoolClient } from "pg"; + +import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +import { findSchemaProblems } from "../../plugins/database/schema-check"; +import { readMigrationDrift } from "../migrations/apply"; +import { + journalFile, + type JournalEntry, + migrationsFolder, + readJournal, +} from "../migrations/paths"; +import type { DataPath } from "../runtime"; +import { + type DbContext, + hasEnvBranch, + NO_ENV_BRANCH, + withBranchPool, +} from "./context"; +import { requireSchemaFile } from "./migrate"; +import { + type BundleTarget, + defaultBundleTarget, + parseResourceName, + readBundle, + resourceId, +} from "./targets"; + +export interface VerifyOptions { + /** Check the deployed app of a databricks.yml target instead of the `.env` branch. */ + readonly deployed?: boolean; + /** The target to check; the bundle's default target without one. */ + readonly target?: string; +} + +/** `appkit db verify`: the `.env` branch against schema.ts and the committed migrations. */ +interface LocalVerifyReport { + readonly kind: "local"; + readonly branch: string; + /** Declared tables or columns the branch lacks (the plugin's startup check). */ + readonly schemaProblems: readonly string[]; + /** Committed migrations the branch has not run yet, newer than every one it ran. */ + readonly pendingMigrations: readonly string[]; + /** Committed migrations older than one the branch ran, never run: merged out of order. */ + readonly strandedMigrations: readonly string[]; + /** Migrations the branch ran whose committed file changed since. */ + readonly editedMigrations: readonly string[]; + /** Migrations the branch ran that this checkout does not commit, e.g. from another git branch. */ + readonly unknownMigrations: number; + readonly ok: boolean; +} + +/** How the deployed migrations compare with the committed ones. */ +interface DeployedMigrations { + /** "deployed code": the deployment's journal; "deploy time": committed after the deployment was created. */ + readonly checked: "deployed code" | "deploy time"; + /** Committed migrations the active deployment does not have. */ + readonly missing: readonly string[]; +} + +/** `appkit db verify --deployed`: whether a target's deployed app runs on its branch with the committed migrations. */ +interface DeployVerifyReport { + readonly kind: "deploy"; + readonly target: string; + /** The target's workspace; null when databricks.yml names none. */ + readonly host: string | null; + readonly branch: string; + /** The app the target deploys; null when it declares none. */ + readonly app: string | null; + /** null when there are no committed migrations, or no deployment to compare with. */ + readonly migrations: DeployedMigrations | null; + /** What keeps the deployed app from using the branch, each with its fix. */ + readonly problems: readonly string[]; + readonly ok: boolean; +} + +export type VerifyReport = LocalVerifyReport | DeployVerifyReport; + +const DEPLOY = "`databricks apps deploy`"; +const LOGS = "`databricks apps logs`"; +/** What the app's postgres resource needs to create and own its schema. */ +const POSTGRES_PERMISSION = "CAN_CONNECT_AND_CREATE"; + +/** DataPath.raw over one connection: each interpolation becomes a $n parameter. */ +function rawOn(client: Pick): Pick { + return { + async raw(strings: TemplateStringsArray, ...values: unknown[]) { + const text = strings.reduce( + (sql, part, index) => `${sql}$${index}${part}`, + ); + const result = await client.query(text, values); + return result.rows as T[]; + }, + }; +} + +/** Read-only, as the developer, on the `.env` branch: one READ ONLY transaction, rolled back. */ +async function verifyLocal(ctx: DbContext): Promise { + requireSchemaFile(ctx.root, "verify"); + const branch = parseResourceName(ctx.env.LAKEBASE_ENDPOINT)?.branch; + if (!branch || !hasEnvBranch(ctx.env)) { + throw new Error(`Did not verify: ${NO_ENV_BRANCH}.`); + } + const schema = await loadDefaultDatabaseSchema(ctx.root, { + showImportError: true, + }); + return withBranchPool(ctx, async (pool) => { + const client = await pool.connect(); + try { + await client.query("begin transaction read only"); + const schemaProblems = await findSchemaProblems(rawOn(client), schema); + const drift = await readMigrationDrift(client, { + migrationsFolder: migrationsFolder(ctx.root), + schemaName: schema.$schemaName, + }); + return { + kind: "local", + branch, + schemaProblems, + pendingMigrations: drift.pending, + strandedMigrations: drift.stranded, + editedMigrations: drift.edited, + unknownMigrations: drift.unknown, + ok: + schemaProblems.length === 0 && + drift.pending.length === 0 && + drift.stranded.length === 0 && + drift.edited.length === 0 && + drift.unknown === 0, + }; + } finally { + await client.query("rollback").catch(() => undefined); + client.release(); + } + }); +} + +interface DeploymentStatus { + readonly state?: string; + readonly message?: string; +} + +interface Deployment { + readonly create_time?: string; + /** The snapshot of the source the deployment runs. */ + readonly deployment_artifacts?: { readonly source_code_path?: string }; + readonly status?: DeploymentStatus; +} + +/** The fields of GET /api/2.0/apps/{name} that verify reads, in the API's snake_case. */ +interface DeployedApp { + readonly service_principal_client_id?: string; + readonly resources?: ReadonlyArray<{ + readonly postgres?: { + readonly branch?: string; + readonly database?: string; + readonly permission?: string; + }; + }>; + readonly app_status?: DeploymentStatus; + readonly compute_status?: DeploymentStatus; + readonly active_deployment?: Deployment; + readonly pending_deployment?: Deployment; +} + +/** null when the app does not exist yet. */ +async function readApp( + ctx: DbContext, + name: string, +): Promise { + try { + const response = await ctx.workspace().request({ + method: "GET", + path: `/api/2.0/apps/${encodeURIComponent(name)}`, + }); + return (await response.json()) as DeployedApp; + } catch (error) { + if ((error as { statusCode?: unknown } | null)?.statusCode === 404) { + return null; + } + const message = error instanceof Error ? error.message : String(error); + throw new Error(`Could not read app ${name}: ${message}`, { + cause: error, + }); + } +} + +/** The tags in a deployed journal; null when it cannot be read, which includes a deployment without one. */ +async function readDeployedTags( + ctx: DbContext, + file: string, +): Promise | null> { + try { + const response = await ctx.workspace().request({ + method: "GET", + path: "/api/2.0/workspace/export", + query: { path: file, format: "AUTO" }, + }); + const { content } = (await response.json()) as { content?: string }; + if (!content) return null; + const journal = JSON.parse( + Buffer.from(content, "base64").toString("utf-8"), + ); + const entries: unknown[] = Array.isArray(journal?.entries) + ? journal.entries + : []; + return new Set( + entries + .map((entry) => (entry as { tag?: unknown } | null)?.tag) + .filter((tag): tag is string => typeof tag === "string"), + ); + } catch { + return null; + } +} + +/** + * Committed migrations the active deployment lacks: from the journal in the + * snapshot it runs when that is readable, else the ones generated after the + * deployment was created. + */ +async function deployedMigrations( + ctx: DbContext, + deployment: Deployment | undefined, + committed: readonly JournalEntry[], +): Promise { + if (!deployment || committed.length === 0) return null; + const snapshot = deployment.deployment_artifacts?.source_code_path; + if (snapshot) { + const relative = path + .relative(ctx.root, journalFile(migrationsFolder(ctx.root))) + .split(path.sep) + .join("/"); + const deployed = await readDeployedTags( + ctx, + `${snapshot.replace(/\/+$/, "")}/${relative}`, + ); + if (deployed) { + return { + checked: "deployed code", + missing: committed + .filter((entry) => !deployed.has(entry.tag)) + .map((entry) => entry.tag), + }; + } + } + const created = Date.parse(deployment.create_time ?? ""); + if (Number.isNaN(created)) return null; + return { + checked: "deploy time", + missing: committed + .filter((entry) => entry.when > created) + .map((entry) => entry.tag), + }; +} + +function migrationsProblem( + name: string, + migrations: DeployedMigrations, + deployment: Deployment | undefined, +): string | null { + const { missing } = migrations; + if (missing.length === 0) return null; + const them = missing.length === 1 ? "it" : "them"; + const fix = `${DEPLOY} deploys ${them}, and the app applies ${them} on start`; + return migrations.checked === "deployed code" + ? `app ${name}'s active deployment does not have ${missing.join(", ")}, which this checkout commits: ${fix}` + : `${missing.join(", ")} ${missing.length === 1 ? "was" : "were"} generated after app ${name}'s active deployment (${deployment?.create_time}), so it does not have ${them}: ${fix}`; +} + +/** The app's postgres resource against databricks.yml: same branch and database, and the permission to create its schema. */ +function bindingProblems( + app: DeployedApp, + name: string, + branch: string, + database: string | null, + file: string, +): string[] { + const bound = (app.resources ?? []).flatMap((resource) => + resource.postgres ? [resource.postgres] : [], + ); + const binding = bound.find((postgres) => postgres.branch === branch); + if (!binding) { + return [ + bound.length > 0 + ? `app ${name} uses branch ${bound.map((postgres) => postgres.branch).join(", ")}, not ${branch} from ${file}: ${DEPLOY} applies ${file}` + : `app ${name} has no postgres resource: ${DEPLOY} adds the one ${file} declares`, + ]; + } + const problems: string[] = []; + if (database && binding.database !== database) { + problems.push( + `app ${name} uses database ${binding.database ?? "(none)"}, not ${database} from ${file}: ${DEPLOY} applies ${file}`, + ); + } + if (binding.permission !== POSTGRES_PERMISSION) { + problems.push( + `app ${name}'s postgres resource has permission ${binding.permission ?? "(none)"}, but the app needs ${POSTGRES_PERMISSION} to create its schema: set it in ${file}, then run ${DEPLOY}`, + ); + } + return problems; +} + +/** ": " for an API status message, without its final period; "" without one. */ +function detail(message: string | undefined): string { + const text = message?.trim().replace(/\.+$/, ""); + return text ? `: ${text}` : ""; +} + +/** Whether the app is up: a running app has applied its migrations and checked its schema on start. */ +function runningProblems(app: DeployedApp, name: string): string[] { + const pending = app.pending_deployment?.status; + if (pending?.state === "IN_PROGRESS") { + return [ + `a deployment of app ${name} is in progress: run verify again when it finishes`, + ]; + } + const deployment = app.active_deployment?.status; + if (pending?.state === "FAILED" || deployment?.state === "FAILED") { + const failed = pending?.state === "FAILED" ? pending : deployment; + return [ + `the last deployment of app ${name} failed${detail(failed?.message)}. ${LOGS} shows why`, + ]; + } + const compute = app.compute_status; + // A stopped app's API response has no active_deployment, deployed before or not. + if (compute?.state === "STOPPED") { + return [ + `app ${name} is stopped: \`databricks apps start\` starts its last deployment, or ${DEPLOY} deploys the current code; it migrates on start`, + ]; + } + if (!app.active_deployment) { + return [`app ${name} has no deployment yet: ${DEPLOY} deploys it`]; + } + if (compute?.state && compute.state !== "ACTIVE") { + return [ + `app ${name}'s compute is ${compute.state.toLowerCase()}${detail(compute.message)}`, + ]; + } + const status = app.app_status; + if (status?.state === "RUNNING") return []; + return [ + `app ${name} is ${status?.state?.toLowerCase() ?? "not running"}${detail(status?.message)}. ${LOGS} shows why; a migration that fails stops the app on start`, + ]; +} + +/** "a.cloud.databricks.com" for "https://A.cloud.databricks.com/". */ +function hostOf(url: string): string { + try { + return new URL(/^[a-z]+:\/\//i.test(url) ? url : `https://${url}`).host; + } catch { + return url.toLowerCase(); + } +} + +/** The API calls go to the workspace this shell is authenticated against, which must be the target's. */ +async function assertTargetWorkspace( + ctx: DbContext, + target: BundleTarget, +): Promise { + if (!target.host) return; + const authenticated = await ctx.workspace().getHost(); + if (hostOf(authenticated) === hostOf(target.host)) return; + throw new Error( + `Target ${target.name} deploys to ${target.host}, but this shell is authenticated against ${authenticated}. Set DATABRICKS_CONFIG_PROFILE to a profile for ${target.host}, then rerun.`, + ); +} + +function selectTarget( + file: string, + targets: readonly BundleTarget[], + name: string | undefined, + fallback: BundleTarget | null, +): BundleTarget { + const names = targets.map((target) => target.name).join(", "); + if (name) { + const target = targets.find((candidate) => candidate.name === name); + if (!target) + throw new Error( + `${file} has no target ${name}; its targets are ${names}.`, + ); + return target; + } + if (!fallback) { + throw new Error( + `${file} has no default target; pass --target with one of ${names}.`, + ); + } + return fallback; +} + +/** + * --deployed, through the Databricks API only: no database connection, so no + * Postgres role on the deploy branch is needed. The target's app must exist, + * be bound to the branch and database databricks.yml names with + * CAN_CONNECT_AND_CREATE, have a role on the branch for its service + * principal, be running, and run code with every committed migration. + */ +async function verifyDeploy( + ctx: DbContext, + targetName: string | undefined, +): Promise { + const bundle = readBundle(ctx.root); + if (!bundle) { + throw new Error( + "No databricks.yml, so there is no deployed app to verify.", + ); + } + const { file } = bundle; + const target = selectTarget( + file, + bundle.targets, + targetName, + defaultBundleTarget(bundle), + ); + const bound = target.apps.filter((app) => app.postgres); + if (bound.length > 1) { + throw new Error( + `Target ${target.name} deploys ${bound.length} apps with a postgres resource (${bound.map((app) => app.key).join(", ")}); verify checks one app per target.`, + ); + } + const app = + bound[0] ?? (target.apps.length === 1 ? target.apps[0] : undefined); + const branch = app?.postgres?.branch ?? target.postgresBranch; + if (!branch) { + throw new Error( + app?.postgres + ? `No deploy branch: the postgres resource of app ${app.key} in target ${target.name} names its branch with a reference only a deploy resolves.` + : `No deploy branch: target ${target.name} in ${file} declares no app with a postgres resource.`, + ); + } + const database = app?.postgres?.database ?? target.postgresDatabase; + const report = ( + name: string | null, + problems: string[], + migrations: DeployedMigrations | null = null, + ): DeployVerifyReport => ({ + kind: "deploy", + target: target.name, + host: target.host, + branch, + app: name, + migrations, + problems, + ok: problems.length === 0, + }); + if (!app) { + return report(null, [`target ${target.name} in ${file} declares no app`]); + } + if (!app.name) { + return report(app.declaredName, [ + app.declaredName + ? `${file} names the app ${app.declaredName}, with a reference verify cannot resolve` + : `app ${app.key} in ${file} has no name`, + ]); + } + const name = app.name; + + await assertTargetWorkspace(ctx, target); + const api = ctx.api(); + const [branchFound, databaseFound, deployed] = await Promise.all([ + api.getBranch(branch), + database ? api.getDatabase(database) : null, + readApp(ctx, name), + ]); + const branchId = resourceId(branch); + if (!branchFound) { + return report(name, [`${file} deploys to ${branch}, which does not exist`]); + } + const problems: string[] = []; + if (database && !databaseFound) { + problems.push( + `${file} binds database ${database}, which does not exist on ${branchId}`, + ); + } + if (!deployed) { + problems.push( + `app ${name} is not deployed yet: ${DEPLOY} creates it and gives it access to ${branchId}`, + ); + return report(name, problems); + } + + const binding = bindingProblems(deployed, name, branch, database, file); + problems.push(...binding, ...runningProblems(deployed, name)); + const sp = deployed.service_principal_client_id; + const committed = readJournal(migrationsFolder(ctx.root))?.entries ?? []; + const [roles, migrations] = await Promise.all([ + // Only meaningful once the app is bound to this branch. + sp && binding.length === 0 ? api.listRoles(branch) : null, + deployedMigrations(ctx, deployed.active_deployment, committed), + ]); + if (roles && !roles.some((role) => role.status?.postgres_role === sp)) { + problems.push( + `the app's service principal ${sp} has no Postgres role on ${branchId}: ${DEPLOY} creates it from the app's postgres resource`, + ); + } + const missing = migrations + ? migrationsProblem(name, migrations, deployed.active_deployment) + : null; + if (missing) problems.push(missing); + return report(name, problems, migrations); +} + +/** + * `appkit db verify`: check the `.env` branch against schema.ts (the plugin's + * startup check) and the committed migrations, read-only. With `deployed`, + * check through the Databricks API that a target's deployed app runs on its + * branch with the committed migrations; that reads no database, so it needs + * no role on the deploy branch. Nothing is written or created either way. + */ +export async function runVerify( + ctx: DbContext, + options: VerifyOptions = {}, +): Promise { + return options.deployed + ? verifyDeploy(ctx, options.target) + : verifyLocal(ctx); +} diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index 1a9067e78..8e92c12fc 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -8,19 +8,31 @@ interface CatalogColumn { readonly relation_kind: string; } +interface SchemaCheck { + readonly problems: string[]; + /** Declared tables with no relation of that name in the schema. */ + readonly absent: string[]; +} + /** - * Confirm every declared table and column exists before routes are published. - * Even after a deployed app applies its migrations, drift would surface on each - * request as an undefined-table or undefined-column failure, so check up front. + * Every declared table or column the database lacks, and every declared table + * that is a view or another non-table relation, as human-readable problems. * pg_catalog is read rather than information_schema, which hides objects the * role cannot access and would report a privilege gap as a missing column. */ -export async function assertSchemaMatchesDatabase( - dataPath: DataPath, +export async function findSchemaProblems( + dataPath: Pick, schema: Schema, -): Promise { +): Promise { + return (await checkSchema(dataPath, schema)).problems; +} + +async function checkSchema( + dataPath: Pick, + schema: Schema, +): Promise { const tables = Object.values(schema.$tables); - if (tables.length === 0) return; + if (tables.length === 0) return { problems: [], absent: [] }; const schemaName = schema.$schemaName; const tableNames = tables.map((table) => table.$name); // Include non-tables so setup can report their kind instead of claiming they are absent. @@ -74,10 +86,25 @@ export async function assertSchemaMatchesDatabase( ); } } + return { + problems, + absent: tableNames.filter((name) => !found.has(name)), + }; +} + +/** + * Confirm every declared table and column exists before routes are published. + * Even after a deployed app applies its migrations, drift would surface on each + * request as an undefined-table or undefined-column failure, so check up front. + */ +export async function assertSchemaMatchesDatabase( + dataPath: DataPath, + schema: Schema, +): Promise { + const { problems, absent } = await checkSchema(dataPath, schema); if (problems.length > 0) { - const absent = tableNames.filter((name) => !found.has(name)); const advice = - (await inPublicInstead(dataPath, schemaName, absent)) ?? + (await inPublicInstead(dataPath, schema.$schemaName, absent)) ?? "Run `npx appkit db migrate` locally, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start."; throw databaseSetupFailed( `the declared schema does not match the database: ${problems.join("; ")}. ${advice}`, diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index 2abb3d26c..70640c7af 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -2,7 +2,10 @@ import { describe, expect, test, vi } from "vitest"; import type { DataPath } from "../../../database/runtime"; import { defineSchema, fk, id, text } from "../../../database/schema-builder"; -import { assertSchemaMatchesDatabase } from "../schema-check"; +import { + assertSchemaMatchesDatabase, + findSchemaProblems, +} from "../schema-check"; // Explicitly public: the assertions name the tables public.boards and public.notes. const schema = defineSchema( @@ -191,3 +194,39 @@ describe("assertSchemaMatchesDatabase", () => { expect(raw).not.toHaveBeenCalled(); }); }); + +describe("findSchemaProblems", () => { + test("returns every problem without throwing; the assert reports the same ones", async () => { + const { path } = catalog( + { boards: ["id", "title"], notes: ["id", "body"] }, + { boards: "v" }, + ); + + const problems = await findSchemaProblems(path, schema); + + expect(problems).toEqual([ + "table public.boards is a view, not a table", + "table public.notes is missing columns board_id, author_email", + ]); + await expect(assertSchemaMatchesDatabase(path, schema)).rejects.toThrow( + `the declared schema does not match the database: ${problems.join("; ")}.`, + ); + }); + + test("returns no problems for a matching database or an empty schema", async () => { + const { path } = catalog({ + boards: ["id", "title"], + notes: ["id", "board_id", "author_email", "body"], + }); + expect(await findSchemaProblems(path, schema)).toEqual([]); + + const empty = catalog({}); + expect( + await findSchemaProblems( + empty.path, + defineSchema(() => ({})), + ), + ).toEqual([]); + expect(empty.raw).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/shared/src/cli/commands/db/index.ts b/packages/shared/src/cli/commands/db/index.ts index ed811c91c..3c5bbcfdf 100644 --- a/packages/shared/src/cli/commands/db/index.ts +++ b/packages/shared/src/cli/commands/db/index.ts @@ -5,6 +5,7 @@ import { dbInitCommand } from "./init"; import { dbIntrospectCommand } from "./introspect"; import { dbMigrateCommand } from "./migrate"; import { dbSeedCommand } from "./seed"; +import { dbVerifyCommand } from "./verify"; /** * Lakebase database lifecycle for the DatabasePlugin. The logic lives in @@ -16,4 +17,5 @@ export const dbCommand = new Command("db") .addCommand(dbMigrateCommand) .addCommand(dbIntrospectCommand) .addCommand(dbCleanCommand) - .addCommand(dbSeedCommand); + .addCommand(dbSeedCommand) + .addCommand(dbVerifyCommand); diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index 90dcdf53f..872169aaa 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -107,13 +107,14 @@ afterEach(() => { }); describe("appkit db init", () => { - test("registers init, migrate, introspect, clean and seed", () => { + test("registers init, migrate, introspect, clean, seed and verify", () => { expect(dbCommand.commands.map((c) => c.name())).toEqual([ "init", "migrate", "introspect", "clean", "seed", + "verify", ]); }); diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 72304f19d..326091077 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -5,8 +5,11 @@ import pc from "picocolors"; import type { CleanReport, + DeployVerifyReport, IntrospectReport, + LocalVerifyReport, MigrateReport, + VerifyReport, } from "./tooling-contract"; /** Prompts only when a human can answer them. */ @@ -96,6 +99,85 @@ export function printCleanReport(report: CleanReport): void { } } +const REBUILD = + "`appkit db clean` and then `appkit db migrate` rebuild the branch from this checkout's migrations, in order"; + +/** The one next step for a failed local verify, most fundamental gap first. */ +function localVerifyHint(report: LocalVerifyReport): string { + if (report.editedMigrations.length > 0) { + return "Restore the edited migrations from version control, and put the change in a new migration."; + } + if (report.unknownMigrations > 0) { + return `${REBUILD}. If the branch ran migrations you have not pulled yet, pull them instead.`; + } + if (report.strandedMigrations.length > 0) return `${REBUILD}.`; + // Pending migrations explain the gap; without them, schema.ts changed or the branch was edited. + return report.pendingMigrations.length > 0 + ? "Run `appkit db migrate` to apply the pending migrations." + : "If you changed schema.ts, run `appkit db migrate`; if the branch was changed by hand, `appkit db clean` and then `appkit db migrate` rebuild it from the migrations."; +} + +function printLocalVerifyReport(report: LocalVerifyReport): void { + const branch = shortName(report.branch); + if (report.ok) { + ok( + `${branch} has every table and column config/database/schema.ts declares, and every committed migration`, + ); + return; + } + for (const problem of report.schemaProblems) warn(`Schema: ${problem}`); + if (report.pendingMigrations.length > 0) { + warn(`Pending migrations: ${report.pendingMigrations.join(", ")}`); + } + for (const tag of report.strandedMigrations) { + warn( + `Never runs: ${tag}: it is older than a migration the branch already ran (merged out of order); the deployed app skips it too once it ran a newer one`, + ); + } + for (const tag of report.editedMigrations) { + warn( + `Never runs: ${tag}: it changed after the branch ran it, and a branch that ran it keeps the old version`, + ); + } + if (report.unknownMigrations > 0) { + const one = report.unknownMigrations === 1; + warn( + `Not committed: the branch ran ${report.unknownMigrations} migration${one ? "" : "s"} this checkout does not have, for example from another git branch`, + ); + } + console.error( + `${pc.red("✖")} ${branch} does not match config/database/schema.ts and the committed migrations. ${localVerifyHint(report)}`, + ); +} + +function printDeployVerifyReport(report: DeployVerifyReport): void { + const where = `target ${report.target}${report.host ? ` on ${report.host}` : ""}`; + const app = report.app ? `app ${report.app}` : "The deployed app"; + const branch = shortName(report.branch); + if (report.ok) { + ok( + `${app} (${where}) is running, bound to ${branch} with CAN_CONNECT_AND_CREATE, and its service principal has a role there`, + ); + if (report.migrations?.checked === "deployed code") { + ok("Its active deployment has every committed migration"); + } else if (report.migrations) { + ok( + "Every committed migration was generated before its active deployment; its code could not be read, so verify compared times", + ); + } + return; + } + for (const problem of report.problems) warn(problem); + console.error( + `${pc.red("✖")} ${app} (${where}) cannot use ${branch} yet. Fix the above, then run \`appkit db verify --deployed -t ${report.target}\` again.`, + ); +} + +export function printVerifyReport(report: VerifyReport): void { + if (report.kind === "local") printLocalVerifyReport(report); + else printDeployVerifyReport(report); +} + export function printIntrospectReport(report: IntrospectReport): void { const count = report.tables.length; ok( diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 8298134b0..8bf01a291 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -67,6 +67,38 @@ export type InitStart = readonly migrate: MigrateReport; }; +export interface VerifyOptions { + readonly deployed?: boolean; + readonly target?: string; +} + +export interface LocalVerifyReport { + readonly kind: "local"; + readonly branch: string; + readonly schemaProblems: readonly string[]; + readonly pendingMigrations: readonly string[]; + readonly strandedMigrations: readonly string[]; + readonly editedMigrations: readonly string[]; + readonly unknownMigrations: number; + readonly ok: boolean; +} + +export interface DeployVerifyReport { + readonly kind: "deploy"; + readonly target: string; + readonly host: string | null; + readonly branch: string; + readonly app: string | null; + readonly migrations: { + readonly checked: "deployed code" | "deploy time"; + readonly missing: readonly string[]; + } | null; + readonly problems: readonly string[]; + readonly ok: boolean; +} + +export type VerifyReport = LocalVerifyReport | DeployVerifyReport; + export interface InitReport { readonly mode: BranchMode; readonly branch: string; @@ -117,4 +149,8 @@ export interface DatabaseTooling { readonly runSeed: ( ctx: Ctx, ) => Promise<{ readonly branch: string; readonly file: string }>; + readonly runVerify: ( + ctx: Ctx, + options?: VerifyOptions, + ) => Promise; } diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts new file mode 100644 index 000000000..2592175e6 --- /dev/null +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -0,0 +1,297 @@ +import { + afterEach, + beforeEach, + describe, + expect, + type MockInstance, + test, + vi, +} from "vitest"; + +const { createDbContext, runVerify } = vi.hoisted(() => ({ + createDbContext: vi.fn(() => ({ root: "/app", env: {} })), + runVerify: vi.fn(), +})); + +// The tooling is an ambient module loaded with a dynamic import; mock it so the +// command never touches a database. +vi.mock("@databricks/appkit/database-tooling", () => ({ + createDbContext, + runVerify, +})); + +import { dbCommand } from "./index"; + +let log: MockInstance; +let error: MockInstance; + +function output(spy: MockInstance): string { + return spy.mock.calls.map((call) => call.join(" ")).join("\n"); +} + +const local = { + kind: "local" as const, + branch: "projects/p/branches/dev-alice-3f9a2c", + schemaProblems: [], + pendingMigrations: [], + strandedMigrations: [], + editedMigrations: [], + unknownMigrations: 0, + ok: true, +}; + +/** Commander keeps parsed option values on the command; each test parses afresh. */ +function resetOptionValues() { + for (const command of dbCommand.commands) { + for (const option of command.options) { + command.setOptionValueWithSource( + option.attributeName(), + undefined, + "default", + ); + } + } +} + +beforeEach(() => { + resetOptionValues(); + runVerify.mockReset(); + log = vi.spyOn(console, "log").mockImplementation(() => undefined); + error = vi.spyOn(console, "error").mockImplementation(() => undefined); +}); + +afterEach(() => { + vi.restoreAllMocks(); + process.exitCode = undefined; +}); + +describe("appkit db verify", () => { + test("is registered under the db group", () => { + expect(dbCommand.commands.map((command) => command.name())).toContain( + "verify", + ); + }); + + test("a clean branch prints what was checked and exits 0", async () => { + runVerify.mockResolvedValue(local); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(runVerify).toHaveBeenCalledWith(expect.anything(), { + deployed: false, + }); + expect(output(log)).toContain( + "dev-alice-3f9a2c has every table and column config/database/schema.ts declares, and every committed migration", + ); + expect(error).not.toHaveBeenCalled(); + expect(process.exitCode).toBeUndefined(); + }); + + test("prints every schema problem and pending migration, and exits 1", async () => { + runVerify.mockResolvedValue({ + ...local, + schemaProblems: [ + "table app.notes is missing column body", + "table app.tags does not exist", + ], + pendingMigrations: ["0001_migration", "0002_migration"], + ok: false, + }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + const printed = output(log); + expect(printed).toContain("Schema: table app.notes is missing column body"); + expect(printed).toContain("Schema: table app.tags does not exist"); + expect(printed).toContain( + "Pending migrations: 0001_migration, 0002_migration", + ); + expect(output(error)).toContain( + "dev-alice-3f9a2c does not match config/database/schema.ts and the committed migrations. Run `appkit db migrate` to apply the pending migrations.", + ); + expect(process.exitCode).toBe(1); + }); + + test("schema problems without pending migrations point to migrate or clean", async () => { + runVerify.mockResolvedValue({ + ...local, + schemaProblems: ["table app.notes is missing column body"], + ok: false, + }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(error)).toContain( + "If you changed schema.ts, run `appkit db migrate`; if the branch was changed by hand, `appkit db clean` and then `appkit db migrate` rebuild it from the migrations.", + ); + expect(process.exitCode).toBe(1); + }); + + test("a migration merged out of order is named, with how to rebuild the branch", async () => { + runVerify.mockResolvedValue({ + ...local, + strandedMigrations: ["0001_parallel"], + ok: false, + }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(log)).toContain( + "Never runs: 0001_parallel: it is older than a migration the branch already ran (merged out of order); the deployed app skips it too once it ran a newer one", + ); + expect(output(error)).toContain( + "`appkit db clean` and then `appkit db migrate` rebuild the branch from this checkout's migrations, in order.", + ); + expect(process.exitCode).toBe(1); + }); + + test("an edited migration is restored, not rebuilt over", async () => { + runVerify.mockResolvedValue({ + ...local, + strandedMigrations: ["0001_parallel"], + editedMigrations: ["0000_migration"], + ok: false, + }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(log)).toContain( + "Never runs: 0000_migration: it changed after the branch ran it, and a branch that ran it keeps the old version", + ); + expect(output(error)).toContain( + "Restore the edited migrations from version control, and put the change in a new migration.", + ); + }); + + test("migrations the branch ran that this checkout does not commit", async () => { + runVerify.mockResolvedValue({ ...local, unknownMigrations: 2, ok: false }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(log)).toContain( + "Not committed: the branch ran 2 migrations this checkout does not have, for example from another git branch", + ); + expect(output(error)).toContain( + "rebuild the branch from this checkout's migrations, in order. If the branch ran migrations you have not pulled yet, pull them instead.", + ); + expect(process.exitCode).toBe(1); + }); + + describe("--deployed", () => { + const deploy = { + kind: "deploy" as const, + target: "prod", + host: "https://acme.cloud.databricks.com", + branch: "projects/p/branches/production", + app: "my-app", + migrations: { checked: "deployed code" as const, missing: [] }, + problems: [], + ok: true, + }; + + test("a ready app prints what was checked, target and host included, and exits 0", async () => { + runVerify.mockResolvedValue(deploy); + + await dbCommand.parseAsync(["verify", "--deployed", "-t", "prod"], { + from: "user", + }); + + expect(runVerify).toHaveBeenCalledWith(expect.anything(), { + deployed: true, + target: "prod", + }); + const printed = output(log); + expect(printed).toContain( + "app my-app (target prod on https://acme.cloud.databricks.com) is running, bound to production with CAN_CONNECT_AND_CREATE, and its service principal has a role there", + ); + expect(printed).toContain( + "Its active deployment has every committed migration", + ); + expect(error).not.toHaveBeenCalled(); + expect(process.exitCode).toBeUndefined(); + }); + + test("says when migrations were compared by deploy time", async () => { + runVerify.mockResolvedValue({ + ...deploy, + migrations: { checked: "deploy time", missing: [] }, + }); + + await dbCommand.parseAsync(["verify", "--deployed"], { from: "user" }); + + expect(runVerify).toHaveBeenCalledWith(expect.anything(), { + deployed: true, + }); + expect(output(log)).toContain( + "Every committed migration was generated before its active deployment; its code could not be read, so verify compared times", + ); + }); + + test("lists each problem with its fix, and exits 1", async () => { + runVerify.mockResolvedValue({ + ...deploy, + problems: [ + "app my-app has no postgres resource: `databricks apps deploy` adds the one databricks.yml declares", + "app my-app's active deployment does not have 0003_migration, which this checkout commits: `databricks apps deploy` deploys it, and the app applies it on start", + ], + ok: false, + }); + + await dbCommand.parseAsync(["verify", "--deployed", "-t", "prod"], { + from: "user", + }); + + const printed = output(log); + expect(printed).toContain( + "app my-app has no postgres resource: `databricks apps deploy` adds the one databricks.yml declares", + ); + expect(printed).toContain( + "app my-app's active deployment does not have 0003_migration", + ); + expect(output(error)).toContain( + "app my-app (target prod on https://acme.cloud.databricks.com) cannot use production yet. Fix the above, then run `appkit db verify --deployed -t prod` again.", + ); + expect(process.exitCode).toBe(1); + }); + + test("without an app in the target it names the deployed app generically", async () => { + runVerify.mockResolvedValue({ + ...deploy, + host: null, + app: null, + migrations: null, + problems: ["target prod in databricks.yml declares no app"], + ok: false, + }); + + await dbCommand.parseAsync(["verify", "--deployed"], { from: "user" }); + + expect(output(error)).toContain( + "The deployed app (target prod) cannot use production yet.", + ); + }); + }); + + test("--target without --deployed is refused before loading the tooling", async () => { + await dbCommand.parseAsync(["verify", "-t", "prod"], { from: "user" }); + + expect(output(error)).toContain( + "--target picks the databricks.yml target --deployed checks; pass --deployed with it.", + ); + expect(runVerify).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + }); + + test("an error is printed and exits 1", async () => { + runVerify.mockRejectedValue( + new Error( + "Did not verify: no branch is configured in .env (PGHOST, PGDATABASE and LAKEBASE_ENDPOINT); run `appkit db init`.", + ), + ); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(error)).toContain("Did not verify: no branch is configured"); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/packages/shared/src/cli/commands/db/verify.ts b/packages/shared/src/cli/commands/db/verify.ts new file mode 100644 index 000000000..3ffa1bece --- /dev/null +++ b/packages/shared/src/cli/commands/db/verify.ts @@ -0,0 +1,63 @@ +import { Command } from "commander"; + +import { loadDatabaseTooling } from "./load-tooling"; +import { fail, printVerifyReport } from "./output"; + +async function runDbVerify(options: { + deployed?: boolean; + target?: string; +}): Promise { + try { + if (options.target && !options.deployed) { + throw new Error( + "--target picks the databricks.yml target --deployed checks; pass --deployed with it.", + ); + } + const tooling = await loadDatabaseTooling(); + const report = await tooling.runVerify(tooling.createDbContext(), { + deployed: options.deployed === true, + ...(options.target ? { target: options.target } : {}), + }); + printVerifyReport(report); + if (!report.ok) process.exitCode = 1; + } catch (error) { + fail(error); + } +} + +export const dbVerifyCommand = new Command("verify") + .description( + "Check the .env branch against config/database/schema.ts and the committed migrations (read-only)", + ) + .option( + "--deployed", + "check instead the app a databricks.yml target deploys, and its branch", + ) + .option( + "-t, --target ", + "the databricks.yml target --deployed checks (default: the bundle's default target)", + ) + .addHelpText( + "after", + ` +Reports declared tables or columns the branch lacks (what the app checks on +start), committed migrations the branch has not applied, migrations it will +never run (merged out of order, or edited after they ran), and migrations it +ran that this checkout does not commit. + +--deployed reads only the Databricks API, so it needs no access to the deploy +branch's database. It checks that the target's app exists, that its postgres +resource names the branch and database in databricks.yml with +CAN_CONNECT_AND_CREATE, that its service principal has a role on the branch, +that the app is running, and that its active deployment has every committed +migration. It refuses when the target's workspace.host is not the workspace +this shell is authenticated against. + +Exits 1 on any finding. Nothing is written or created. + +Examples: + $ appkit db verify + $ appkit db verify --deployed + $ appkit db verify --deployed -t prod`, + ) + .action(runDbVerify); From 81e2e8f1134ff56570aa7d196ed95668ae886f41 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 12 Oct 2026 13:45:02 +0100 Subject: [PATCH 013/317] feat(appkit): offer the database plugin in databricks apps init The DatabasePlugin is no longer hidden from `databricks apps init`. The template ships config/database/schema.ts in the app schema, and app.yaml sets APPKIT_DB_MIGRATE_ON_START=true for apps that select the plugin, so the deployed app applies its committed migrations on start. The CLI manifest renders only valueFrom entries, so the literal lives in app.yaml.tmpl. drizzle-kit stays out of the template and its lockfiles: `appkit db init` installs the pinned version when the app lacks it, so apps without the plugin do not get it. `appkit db verify` warns when .env points at a branch `appkit db init` did not set up for you, such as the deploy branch the scaffolded .env names until `db init` runs. The template's server exits 1 when startup fails, so a failed migration stops the app instead of leaving it up without its routes. The owner-mismatch error names the recovery for an app recreated with a new service principal: `databricks postgres delete-role --reassign-owned-to`. The plugin docs and the template README describe the flow end to end: `appkit db init` once after scaffolding, `appkit db migrate` while you develop, migrations on deploy with their per-migration transactions and lock limits, two-step changes for tables in use, rollback, existing apps, `appkit db verify --deployed -t ` in CI, and one owner per branch. The Lakebase docs start local development on a dev branch. The template's .gitignore skips config/database/*.bak, the copy of schema.ts that `appkit db introspect` keeps. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 198 +++++++++++++++++- docs/docs/plugins/lakebase.md | 25 ++- packages/appkit/src/beta.ts | 1 - .../src/database/migrations/ownership.ts | 5 +- .../migrations/tests/ownership.test.ts | 3 + .../src/database/tooling/tests/verify.test.ts | 35 +++- .../appkit/src/database/tooling/verify.ts | 19 +- .../src/plugins/beta-exports.generated.ts | 1 + .../appkit/src/plugins/database/manifest.json | 2 +- packages/shared/src/cli/commands/db/output.ts | 5 + .../src/cli/commands/db/tooling-contract.ts | 1 + .../shared/src/cli/commands/db/verify.test.ts | 16 ++ packages/shared/src/cli/index.ts | 3 +- template/README.md.tmpl | 52 ++++- template/_gitignore | 3 + template/app.yaml.tmpl | 5 + template/appkit.plugins.json | 109 ++++++++++ template/config/database/schema.ts | 5 +- template/server/server.ts | 5 +- 19 files changed, 457 insertions(+), 36 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 1467dd10b..fde484b5e 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -21,10 +21,9 @@ not support OBO and does not apply per-user or per-row authorization. Every call who can reach the generated API can perform every enabled operation on every exposed row, including delete. -Restrict access to the app and grant its service principal only the database -permissions it needs. If users need different permissions or row ownership checks, -disable the relevant generated routes and implement authorization in custom -server routes. App admission alone does not provide row-level isolation. +Restrict access to the app. If users need different permissions or row ownership +checks, disable the relevant generated routes and implement authorization in +custom server routes. App admission alone does not provide row-level isolation. ::: ## Basic usage @@ -39,9 +38,11 @@ identifier-only messages for known missing-column or missing-table errors details, and hints are omitted because they may contain row values. 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 models when their PostgreSQL -tables are ready. +`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 @@ -112,6 +113,189 @@ 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 + +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--`. It creates the branch when + it does not exist yet. `--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, hands you the + app schema the fork copied, and points `.env` at the branch. +3. It sets up the schema. With `schema.ts` it applies the committed migrations; + without one, it writes `schema.ts` from the branch's tables (`introspect`). + `--schema clean` drops the app schema first, and `--schema none` leaves it as it + is. Without a terminal, `--schema clean` needs `--yes`. +4. When that needs drizzle-kit and the app does not have it, it installs the + version AppKit pins as a dev dependency. `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 default branch] +New branches fork the project's default branch, so they start with a copy of its +rows, production data included. 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 default 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, 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). | +| `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. | + +`migrate`, `clean` and `seed` change only branches `db init` created for you (your +dev branch, or this checkout's session branch). 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. + +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, with every committed migration +``` + +### Changing tables in use + +While a new release migrates on start, instances of the previous release keep +serving, so every migration must work with the code that is still running. A +change that drops or renames a table or column, changes a column's type, or makes +a column required breaks them, 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. + +### 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" +``` + +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. + +`.env` never sets the flag, so a local start (`npm run dev`, `npm start`) never +migrates: use `npx appkit db migrate`. An app pointed at a dev or session branch +does not migrate it on start either. + +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. + +### Existing apps + +- **Tables created by hand or by earlier code.** Without `schema.ts`, + `npx appkit db init` creates your dev branch from the project's default branch and + introspects it: it writes `schema.ts` from the tables there and a `0000_baseline` + migration. With a `schema.ts` already, run `npx appkit db introspect` on your + branch. Commit both files: the deployed app records the baseline without running + it, because the tables already exist on the deploy branch. +- **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. +- **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, applies nothing, and starts. The older code must work with the +newer schema, which [two-step changes](#changing-tables-in-use) guarantee. 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 them over to you. + +Do not apply migrations to the deploy branch yourself: you would own those objects, +and the app could no longer change them. If schema `app` on the deploy branch +already belongs to another role, the app cannot migrate it, and the server log +names both roles. Use another `schemaName` in `defineSchema()`, or have the owner +transfer the schema. + +An app that was deleted and created again has a new service principal, and the old +one still owns the schema. Someone with CAN MANAGE on the Lakebase project moves +the objects to the new one, which deletes the old role: + +```bash +# Both service principals' roles, by their client IDs +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, the app is running, and its active deployment has every committed +migration. `-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. 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. 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, is bound to another branch, or lacks a +committed migration. + ## Schema discovery and overrides `database()` and `database({})` use the same defaults. During setup, the plugin diff --git a/docs/docs/plugins/lakebase.md b/docs/docs/plugins/lakebase.md index c887073da..b581b5d74 100644 --- a/docs/docs/plugins/lakebase.md +++ b/docs/docs/plugins/lakebase.md @@ -143,7 +143,30 @@ When you create the app with the Lakebase resource using the [Getting started](# ### Local development -To develop locally against a deployed Lakebase database: +Develop against a Lakebase branch of your own, so local runs never write to the +branch the app deploys to: + +```bash +npx appkit db init --schema none +``` + +It creates your dev branch from the project's default branch, gives it an endpoint +and a Postgres role for your Databricks identity, and points `.env` at it. The role +is a member of `DATABRICKS_SUPERUSER`, so you read and write every table the branch +copied. Copied objects keep their owner, usually the app's Service Principal, so +changing them (DDL) needs that owner; what you create on your branch is yours. +`--schema none` leaves the branch's schemas as they are. Apps that use the +[Database plugin](./database.md#set-up-your-branch) drop it, so `db init` also sets +up the app schema. + +:::caution +A new branch starts with a copy of the default branch's rows, production data +included. See [Set up your branch](./database.md#set-up-your-branch). +::: + +#### Against the deployed branch + +To develop locally against the branch the app deploys to: 1. **Deploy the app first.** The Service Principal creates the database schema and tables on first deploy. Apps generated from `databricks apps init` handle this automatically - they check if tables exist on startup and skip creation if they do. diff --git a/packages/appkit/src/beta.ts b/packages/appkit/src/beta.ts index 03d574653..ca75d8272 100644 --- a/packages/appkit/src/beta.ts +++ b/packages/appkit/src/beta.ts @@ -121,7 +121,6 @@ export type { SearchResult, } from "./plugins/ai-search/types"; export * from "./plugins/beta-exports.generated"; -export { database } from "./plugins/database"; export type { DatabaseApiConfig, DatabaseApiWriteOperation, diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index 59a7be8d4..6f0951da1 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -63,8 +63,9 @@ export function ownershipHint( return ( `Schema "${ownership.schemaName}" is owned by "${ownership.owner}", but the app connects as "${ownership.currentUser}". ` + "This happens when the app's database resource was removed and added again, or the app was recreated with a new service principal: " + - `Lakebase hands the objects to another role. Have "${ownership.owner}" transfer the schema and its tables to "${ownership.currentUser}" ` + - "(ALTER … OWNER TO), or set another schemaName in schema.ts. " + + `Lakebase hands the objects to another role. If "${ownership.owner}" belonged to a deleted app, 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), which also deletes its role. ` + + `Otherwise have "${ownership.owner}" transfer the schema and its tables to "${ownership.currentUser}" (ALTER … OWNER TO), or set another schemaName in schema.ts. ` + "On your dev or session branch, rerun `appkit db init`, which hands you the schema." ); } diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index d1dda3838..c5977aa39 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -25,6 +25,9 @@ describe("ownership: one owner per branch", () => { expect(hint).toContain( "the app's database resource was removed and added again, or the app was recreated", ); + expect(hint).toContain( + `If "old-app-sp" belonged to a deleted app, someone with CAN MANAGE on the Lakebase project moves its objects with \`databricks postgres delete-role --reassign-owned-to \``, + ); expect(hint).toContain("set another schemaName in schema.ts"); expect(hint).toContain( "On your dev or session branch, rerun `appkit db init`, which hands you the schema.", diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 70d57db23..3f8cbb144 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -5,12 +5,19 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; -const { withBranchPool } = vi.hoisted(() => ({ withBranchPool: vi.fn() })); +const { withBranchPool, resolveEnvBranch } = vi.hoisted(() => ({ + withBranchPool: vi.fn(), + resolveEnvBranch: vi.fn(), +})); vi.mock("../context", async (importOriginal) => ({ ...(await importOriginal()), withBranchPool, })); +vi.mock("../guard", async (importOriginal) => ({ + ...(await importOriginal()), + resolveEnvBranch, +})); import type { WorkspaceRequest } from "../../../workspace-client"; import type { DbContext } from "../context"; @@ -155,6 +162,10 @@ const WRITES = /\b(insert|update|delete|create|drop|alter|grant|truncate)\b/i; beforeEach(() => { withBranchPool.mockReset(); + resolveEnvBranch.mockReset().mockResolvedValue({ + branch: { name: BRANCH }, + kind: "dev", + }); }); afterEach(() => { @@ -169,6 +180,7 @@ describe("runVerify", () => { { tag: "0001_migration", when: 2000 }, ]; const clean = { + notYours: null, schemaProblems: [], pendingMigrations: [], strandedMigrations: [], @@ -270,6 +282,25 @@ describe("runVerify", () => { }); }); + test("a branch that is not your dev or session branch is named, and still verified", async () => { + const ctx = app(two); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + }); + resolveEnvBranch.mockResolvedValue({ + branch: { name: "projects/p/branches/production" }, + kind: "default", + reason: "it is the project's default branch", + }); + + expect(await runVerify(ctx)).toMatchObject({ + branch: "projects/p/branches/production", + notYours: "it is the project's default branch", + ok: true, + }); + }); + test("no committed migrations: only the schema is checked", async () => { const ctx = app(); branch({ columns: { notes: ["id", "body"] }, recorded: "absent" }); @@ -307,6 +338,7 @@ describe("runVerify", () => { }); test("without a configured branch it points to init before connecting", async () => { + resolveEnvBranch.mockResolvedValue(null); await expect(runVerify(app([], {}))).rejects.toThrow( "Did not verify: no branch is configured in .env (PGHOST, PGDATABASE and LAKEBASE_ENDPOINT); run `appkit db init`.", ); @@ -477,6 +509,7 @@ describe("runVerify --deployed", () => { `workspace.export ${SNAPSHOT}/config/database/migrations/meta/_journal.json`, ]); expect(withBranchPool).not.toHaveBeenCalled(); + expect(resolveEnvBranch).not.toHaveBeenCalled(); expect(lakebase.calls.sort()).toEqual([ `getBranch ${PRODUCTION}`, `getDatabase ${DATABASE}`, diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 3c436ff02..1885e11c0 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -12,17 +12,12 @@ import { readJournal, } from "../migrations/paths"; import type { DataPath } from "../runtime"; -import { - type DbContext, - hasEnvBranch, - NO_ENV_BRANCH, - withBranchPool, -} from "./context"; +import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context"; +import { resolveEnvBranch, takesWrites } from "./guard"; import { requireSchemaFile } from "./migrate"; import { type BundleTarget, defaultBundleTarget, - parseResourceName, readBundle, resourceId, } from "./targets"; @@ -38,6 +33,8 @@ export interface VerifyOptions { interface LocalVerifyReport { readonly kind: "local"; readonly branch: string; + /** Why the branch is not your dev or session branch, e.g. "it is the project's default branch"; null when it is. */ + readonly notYours: string | null; /** Declared tables or columns the branch lacks (the plugin's startup check). */ readonly schemaProblems: readonly string[]; /** Committed migrations the branch has not run yet, newer than every one it ran. */ @@ -98,10 +95,9 @@ function rawOn(client: Pick): Pick { /** Read-only, as the developer, on the `.env` branch: one READ ONLY transaction, rolled back. */ async function verifyLocal(ctx: DbContext): Promise { requireSchemaFile(ctx.root, "verify"); - const branch = parseResourceName(ctx.env.LAKEBASE_ENDPOINT)?.branch; - if (!branch || !hasEnvBranch(ctx.env)) { - throw new Error(`Did not verify: ${NO_ENV_BRANCH}.`); - } + const env = await resolveEnvBranch(ctx); + if (!env) throw new Error(`Did not verify: ${NO_ENV_BRANCH}.`); + const branch = env.branch.name; const schema = await loadDefaultDatabaseSchema(ctx.root, { showImportError: true, }); @@ -117,6 +113,7 @@ async function verifyLocal(ctx: DbContext): Promise { return { kind: "local", branch, + notYours: takesWrites(env.kind) ? null : (env.reason ?? null), schemaProblems, pendingMigrations: drift.pending, strandedMigrations: drift.stranded, diff --git a/packages/appkit/src/plugins/beta-exports.generated.ts b/packages/appkit/src/plugins/beta-exports.generated.ts index 7e556ebd9..10982785b 100644 --- a/packages/appkit/src/plugins/beta-exports.generated.ts +++ b/packages/appkit/src/plugins/beta-exports.generated.ts @@ -7,3 +7,4 @@ export { agents } from "./agents"; export { aiSearch } from "./ai-search"; +export { database } from "./database"; diff --git a/packages/appkit/src/plugins/database/manifest.json b/packages/appkit/src/plugins/database/manifest.json index 111a7b6be..fc665fe97 100644 --- a/packages/appkit/src/plugins/database/manifest.json +++ b/packages/appkit/src/plugins/database/manifest.json @@ -4,7 +4,6 @@ "displayName": "Database (Beta)", "description": "Schema-driven typed access to Databricks Lakebase PostgreSQL", "stability": "beta", - "hidden": true, "resources": { "required": [ { @@ -17,6 +16,7 @@ "project": { "description": "Lakebase project resource name", "examples": ["projects/{project-id}"], + "bundleIgnore": true, "discovery": { "type": "kind", "resourceKind": "postgres_project", diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 326091077..18594ab27 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -119,6 +119,11 @@ function localVerifyHint(report: LocalVerifyReport): string { function printLocalVerifyReport(report: LocalVerifyReport): void { const branch = shortName(report.branch); + if (report.notYours) { + warn( + `.env points at ${branch}, not a branch \`appkit db init\` set up for you: ${report.notYours}. \`npx appkit db init\` points it at a branch of your own.`, + ); + } if (report.ok) { ok( `${branch} has every table and column config/database/schema.ts declares, and every committed migration`, diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 8bf01a291..80930202e 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -75,6 +75,7 @@ export interface VerifyOptions { export interface LocalVerifyReport { readonly kind: "local"; readonly branch: string; + readonly notYours: string | null; readonly schemaProblems: readonly string[]; readonly pendingMigrations: readonly string[]; readonly strandedMigrations: readonly string[]; diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index 2592175e6..3770284a0 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -32,6 +32,7 @@ function output(spy: MockInstance): string { const local = { kind: "local" as const, branch: "projects/p/branches/dev-alice-3f9a2c", + notYours: null, schemaProblems: [], pendingMigrations: [], strandedMigrations: [], @@ -87,6 +88,21 @@ describe("appkit db verify", () => { expect(process.exitCode).toBeUndefined(); }); + test("a .env branch that is not yours is named, with init as the way to your own", async () => { + runVerify.mockResolvedValue({ + ...local, + branch: "projects/p/branches/production", + notYours: "it is the project's default branch", + }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(log)).toContain( + ".env points at production, not a branch `appkit db init` set up for you: it is the project's default branch. `npx appkit db init` points it at a branch of your own.", + ); + expect(process.exitCode).toBeUndefined(); + }); + test("prints every schema problem and pending migration, and exits 1", async () => { runVerify.mockResolvedValue({ ...local, diff --git a/packages/shared/src/cli/index.ts b/packages/shared/src/cli/index.ts index 2fce08005..55bd50f9e 100644 --- a/packages/shared/src/cli/index.ts +++ b/packages/shared/src/cli/index.ts @@ -36,8 +36,7 @@ cmd.addCommand(docsCommand); cmd.addCommand(pluginCommand); cmd.addCommand(codemodCommand); cmd.addCommand(doctorCommand); -// Hidden from --help until the database plugin is offered by `databricks apps init`. -cmd.addCommand(dbCommand, { hidden: true }); +cmd.addCommand(dbCommand); // Registry commands are executable but hidden from --help while the feature // is still in development (registry + add work end-to-end but aren't announced). cmd.addCommand(registryCommand, { hidden: true }); diff --git a/template/README.md.tmpl b/template/README.md.tmpl index c21dc1cc0..24270e948 100644 --- a/template/README.md.tmpl +++ b/template/README.md.tmpl @@ -49,13 +49,38 @@ The Lakebase plugin requires additional environment variables for PostgreSQL con {{- if .plugins.database}} -#### Database schema +#### Database -`database()` loads `config/database/schema.ts`. The generated schema starts empty, -so initialization does not require sample tables or expose existing data. -Add your table declarations after creating the corresponding PostgreSQL tables; -AppKit does not create or migrate them. CRUD routes are enabled for declared tables -by default, and can be restricted with `api` in the plugin configuration. +`database()` loads `config/database/schema.ts`, whose tables live in the Postgres +schema `app`. CRUD routes are enabled for declared tables by default, and can be +restricted with `api` in the plugin configuration. + +Local development runs against a Lakebase branch of your own, never the deployed one. +Run `npx appkit db init` once after scaffolding, and again after cloning. It asks +nothing: it points `.env` at your branch and sets up its schema. + +```bash +npx appkit db init # your dev branch, forked from the project's default branch +npx appkit db init --session # a branch for this checkout that expires after 7 days +npx appkit db init --dev # back to your dev branch +``` + +A new branch starts with a copy of the default branch's rows, production data included. + +To change the schema, edit `config/database/schema.ts`, then: + +```bash +npx appkit db migrate # writes config/database/migrations/NNNN_migration.sql and applies it to your branch +npx appkit db verify # read-only check of your branch against schema.ts and the migrations +``` + +Commit the migrations. The deployed app applies them on start, because `app.yaml` +sets `APPKIT_DB_MIGRATE_ON_START=true`. To adopt tables that already exist, run +`npx appkit db introspect`: it writes `schema.ts` from the branch's tables, and a +`0000_baseline` migration (or `NNNN_introspect` when migrations already exist). +`npx appkit db clean` drops the app schema on your branch, and `npx appkit db seed` +runs `config/database/seed.sql` on it; both refuse any branch `db init` did not +create for you, such as the deployed one. {{- end}} ### CLI Authentication @@ -183,6 +208,14 @@ databricks apps deploy ```bash databricks apps deploy -t prod ``` +{{- if .plugins.database}} + +Then check that the deployed app runs with every committed migration: + +```bash +npx appkit db verify --deployed -t prod +``` +{{- end}} > **Restarting a stopped app:** apps stop after a period of inactivity. To start one again without redeploying, run `databricks apps start `. @@ -196,10 +229,15 @@ databricks apps deploy -t prod * server.ts # Server entry point * routes/ # Routes * shared/ # Shared types -{{- if .plugins.analytics}} +{{- if or .plugins.analytics .plugins.database}} * config/ # Configuration +{{- end}} +{{- if .plugins.analytics}} * queries/ # SQL query files {{- end}} +{{- if .plugins.database}} + * database/ # schema.ts and its migrations +{{- end}} * databricks.yml # Bundle configuration * app.yaml # App configuration * .env.example # Environment variables example diff --git a/template/_gitignore b/template/_gitignore index 29895e7c0..870cd2b9e 100644 --- a/template/_gitignore +++ b/template/_gitignore @@ -9,6 +9,9 @@ build/ test-results/ playwright-report/ +# `appkit db introspect` keeps the previous schema.ts here +config/database/*.bak + # Auto-generated types (endpoint-specific, varies per developer) shared/appkit-types/serving.d.ts diff --git a/template/app.yaml.tmpl b/template/app.yaml.tmpl index 845442fff..c0b909091 100644 --- a/template/app.yaml.tmpl +++ b/template/app.yaml.tmpl @@ -3,3 +3,8 @@ command: ['{{or .packageManager "pnpm"}}', 'run', 'start'] env: {{.appEnv}} {{- end}} +{{- if .plugins.database}} +{{- /* The plugin's postgres resource always renders LAKEBASE_ENDPOINT into .appEnv, so env: is open. */}} + - name: APPKIT_DB_MIGRATE_ON_START + value: "true" +{{- end}} diff --git a/template/appkit.plugins.json b/template/appkit.plugins.json index db53b96b7..a122753a5 100644 --- a/template/appkit.plugins.json +++ b/template/appkit.plugins.json @@ -196,6 +196,115 @@ } } }, + "database": { + "name": "database", + "displayName": "Database (Beta)", + "description": "Schema-driven typed access to Databricks Lakebase PostgreSQL", + "package": "@databricks/appkit", + "resources": { + "required": [ + { + "type": "postgres", + "alias": "Postgres", + "resourceKey": "postgres", + "description": "Lakebase Postgres database for persistent storage", + "permission": "CAN_CONNECT_AND_CREATE", + "fields": { + "project": { + "description": "Lakebase project resource name", + "bundleIgnore": true, + "examples": [ + "projects/{project-id}" + ], + "discovery": { + "type": "kind", + "resourceKind": "postgres_project", + "select": "name" + }, + "origin": "user" + }, + "branch": { + "description": "Lakebase branch resource name", + "examples": [ + "projects/{project-id}/branches/{branch-id}" + ], + "discovery": { + "type": "kind", + "resourceKind": "postgres_branch", + "select": "name", + "dependsOn": "project" + }, + "origin": "user" + }, + "database": { + "description": "Lakebase database resource name", + "examples": [ + "projects/{project-id}/branches/{branch-id}/databases/{database-id}" + ], + "discovery": { + "type": "kind", + "resourceKind": "postgres_database", + "select": "name", + "dependsOn": "branch" + }, + "origin": "user" + }, + "host": { + "env": "PGHOST", + "description": "Postgres host", + "localOnly": true, + "resolve": "postgres:host", + "origin": "platform" + }, + "databaseName": { + "env": "PGDATABASE", + "description": "Postgres database name", + "localOnly": true, + "resolve": "postgres:databaseName", + "origin": "platform" + }, + "endpointPath": { + "env": "LAKEBASE_ENDPOINT", + "description": "Lakebase endpoint resource name", + "bundleIgnore": true, + "resolve": "postgres:endpointPath", + "origin": "cli" + }, + "port": { + "env": "PGPORT", + "description": "Postgres port", + "localOnly": true, + "value": "5432", + "origin": "platform" + }, + "sslmode": { + "env": "PGSSLMODE", + "description": "Postgres SSL mode", + "localOnly": true, + "value": "require", + "origin": "platform" + } + }, + "appOnly": true, + "binding": { + "yamlKey": "postgres", + "varFields": [ + [ + "branch", + "branch" + ], + [ + "database", + "database" + ] + ] + } + } + ], + "optional": [] + }, + "stability": "beta" + }, "files": { "name": "files", "displayName": "Files Plugin", diff --git a/template/config/database/schema.ts b/template/config/database/schema.ts index c0f6dc1e3..19163eae6 100644 --- a/template/config/database/schema.ts +++ b/template/config/database/schema.ts @@ -1,7 +1,8 @@ {{if .plugins.database -}} import { defineSchema } from '@databricks/appkit/beta'; -// database() discovers this file automatically. Start with no exposed tables. -// Add declarations here after creating the corresponding PostgreSQL tables. +// database() discovers this file automatically. Edit tables here, then run +// `npx appkit db migrate` on your dev branch. The deployed app's service principal +// owns schema "app" and applies committed migrations on start. export const schema = defineSchema(() => ({})); {{- end}} diff --git a/template/server/server.ts b/template/server/server.ts index b33bb94d8..14af3fcca 100644 --- a/template/server/server.ts +++ b/template/server/server.ts @@ -27,4 +27,7 @@ createApp({ await setupSampleLakebaseRoutes(appkit); }, {{- end}} -}).catch(console.error); +}).catch((error) => { + console.error(error); + process.exit(1); +}); From 0d6a48a610e785cf607e2bd9b70e18e0ce32bd15 Mon Sep 17 00:00:00 2001 From: ditadi Date: Tue, 20 Oct 2026 11:35:29 +0200 Subject: [PATCH 014/317] feat(appkit): add appkit db check `appkit db check` checks the committed migrations against config/database/schema.ts without Databricks or Lakebase access, so CI can run it on every pull request. It fails when: - schema.ts changed and no committed migration has the change; - the journal lists a migration generated before the one ahead of it, which a branch that ran the newer one never runs, or an entry whose idx is not its position; - a snapshot does not follow the one before it, which happens when two migrations were generated from one snapshot on parallel git branches; - a migration's .sql or snapshot is not committed, or a .sql is not in the journal. Each finding names its fix. Parallel migrations are fixed by taking the base branch's migrations, then `appkit db clean` and `appkit db migrate`. The schema comparison reuses the diff `appkit db migrate` runs, so check fails exactly when migrate would write a migration, and an ambiguous rename counts as a change instead of prompting. The plugin docs' CI section runs `appkit db check` on every pull request, and the template README names it. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 29 +- packages/appkit/src/database/tooling/check.ts | 142 ++++++++++ packages/appkit/src/database/tooling/index.ts | 1 + .../appkit/src/database/tooling/migrate.ts | 1 + .../appkit/src/database/tooling/migrations.ts | 70 +++-- .../src/database/tooling/tests/check.test.ts | 263 ++++++++++++++++++ .../database/tooling/tests/contract.test.ts | 1 + .../shared/src/cli/commands/db/check.test.ts | 108 +++++++ packages/shared/src/cli/commands/db/check.ts | 37 +++ packages/shared/src/cli/commands/db/index.ts | 4 +- .../cli/commands/db/init-clean-seed.test.ts | 3 +- packages/shared/src/cli/commands/db/output.ts | 17 ++ .../src/cli/commands/db/tooling-contract.ts | 7 + template/README.md.tmpl | 4 + 14 files changed, 663 insertions(+), 24 deletions(-) create mode 100644 packages/appkit/src/database/tooling/check.ts create mode 100644 packages/appkit/src/database/tooling/tests/check.test.ts create mode 100644 packages/shared/src/cli/commands/db/check.test.ts create mode 100644 packages/shared/src/cli/commands/db/check.ts diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index fde484b5e..04f0614e9 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -164,6 +164,7 @@ project whose default branch holds only data every developer may see. | `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). On any other branch, including the @@ -285,8 +286,32 @@ access to the deploy branch's database and changes nothing. A failed check names ### CI -`appkit db init` sets up branches for developers, and CI does not need one. After -a deploy, check the deployed app with workspace credentials: +`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 reads only the checkout, so it needs no Databricks or Lakebase credentials. 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; +- a migration's `.sql` or snapshot is not committed, 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 the base branch's migrations instead: +merge the base branch, reset `config/database/migrations` to the base branch's, +then run `npx appkit db clean` and `npx appkit db migrate`. `migrate` writes your +change again after the base branch's migrations. + +After a deploy, check the deployed app with workspace credentials: ```bash databricks apps deploy -t prod diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts new file mode 100644 index 000000000..85ba2c61a --- /dev/null +++ b/packages/appkit/src/database/tooling/check.ts @@ -0,0 +1,142 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { + DEFAULT_SCHEMA_FILE, + loadDefaultDatabaseSchema, +} from "../../plugins/database/load-schema"; +import { + type JournalEntry, + migrationFile, + migrationsFolder, + readJournal, + readJsonFile, + snapshotFile, +} from "../migrations/paths"; +import type { DbContext } from "./context"; +import { requireSchemaFile } from "./migrate"; +import { hasUnmigratedChanges } 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; +} + +const REWRITE = + "Merge the base branch, reset the migrations to its own (for example `git restore --source origin/main --staged --worktree config/database/migrations`), then run `appkit db clean` and `appkit db migrate`: migrate writes your change again after the base branch's migrations, and applies them all to your rebuilt branch."; + +/** 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. ${REWRITE}`, + ); + } + const before = entries[index - 1]; + if (before && 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}. ${REWRITE}`, + ); + } + }); + return problems; +} + +/** The parts of a snapshot that chain it to the one before. */ +interface SnapshotLink { + readonly id: string; + readonly prevId: string; +} + +/** + * Each snapshot must follow the one before it. 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 = links[index - 1]; + if (!link || !before || link.prevId === before.id) return; + const parent = links.findIndex((other) => other?.id === link.prevId); + const after = + parent === -1 + ? "a snapshot that is not committed" + : (entries[parent]?.tag ?? "an earlier snapshot"); + problems.push( + `${entry.tag} was generated after ${after}, not after ${entries[index - 1]?.tag}: they were written on parallel branches, so ${entry.tag} lacks the other's changes. ${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 reads + * only files, so CI can run it without Databricks or Lakebase access. + */ +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) => { + const file = snapshotFile(folder, entry.idx); + if (fs.existsSync(file)) return readJsonFile(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; + }); + 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. ${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 loadDefaultDatabaseSchema(ctx.root, { + 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/index.ts b/packages/appkit/src/database/tooling/index.ts index d4dd00b32..61063273e 100644 --- a/packages/appkit/src/database/tooling/index.ts +++ b/packages/appkit/src/database/tooling/index.ts @@ -6,6 +6,7 @@ * 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, diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index a67c44ca5..dbaab8507 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -36,6 +36,7 @@ const WITHOUT_SCHEMA = { migrate: "there is nothing to migrate", clean: "clean cannot tell which schema to drop", verify: "there is nothing to verify", + check: "there is nothing to check", } as const; /** Without schema.ts, point to introspect instead of a load error. */ diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 2ed8488eb..d4058db95 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -309,6 +309,51 @@ function writeFileAtomic(file: string, content: string): void { } } +/** The SQL from the latest committed snapshot to the schema, and the schema's snapshot. */ +async function diffSchema( + folder: string, + journal: Journal | null, + schema: Schema, + interactive: boolean, +): Promise<{ cur: Snapshot; statements: string[] }> { + const { generateDrizzleJson, generateMigration } = await loadDrizzleKit(); + const prev = latestSnapshot(folder, journal); + const cur = generateDrizzleJson(drizzleKitImports(schema), prev.id, [ + schema.$schemaName, + ]) as unknown as Snapshot; + + if (!interactive) { + const ambiguity = findRenameAmbiguity(prev, cur, schema.$schemaName); + if (ambiguity) throw ambiguity; + } + + type KitSnapshot = Parameters[0]; + const statements = await generateMigration( + prev as unknown as KitSnapshot, + cur as unknown as KitSnapshot, + ); + return { cur, statements }; +} + +/** Whether `appkit db migrate` would write a migration for the schema. Writes nothing. */ +export async function hasUnmigratedChanges( + folder: string, + schema: Schema, +): Promise { + try { + const { statements } = await diffSchema( + folder, + readJournal(folder), + schema, + false, + ); + return statements.length > 0; + } catch (error) { + if (error instanceof MigrationRenameAmbiguityError) return true; + throw error; + } +} + /** * Diff the schema against the latest committed snapshot with drizzle-kit and * write the next v7 migration: `NNNN_.sql`, `meta/NNNN_snapshot.json`, @@ -323,27 +368,12 @@ export async function generateMigrationFiles( `Migration tag "${name}" must use lowercase letters, digits and underscores`, ); } - const { generateDrizzleJson, generateMigration } = await loadDrizzleKit(); - const journal = readJournal(options.folder); - const prev = latestSnapshot(options.folder, journal); - const cur = generateDrizzleJson(drizzleKitImports(options.schema), prev.id, [ - options.schema.$schemaName, - ]) as unknown as Snapshot; - - if (!options.interactive) { - const ambiguity = findRenameAmbiguity( - prev, - cur, - options.schema.$schemaName, - ); - if (ambiguity) throw ambiguity; - } - - type KitSnapshot = Parameters[0]; - const statements = await generateMigration( - prev as unknown as KitSnapshot, - cur as unknown as KitSnapshot, + const { cur, statements } = await diffSchema( + options.folder, + journal, + options.schema, + options.interactive, ); if (statements.length === 0) return null; options.beforeWrite?.(statements); diff --git a/packages/appkit/src/database/tooling/tests/check.test.ts b/packages/appkit/src/database/tooling/tests/check.test.ts new file mode 100644 index 000000000..c9faffc84 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/check.test.ts @@ -0,0 +1,263 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { type Journal, readJournal } from "../../migrations/paths"; +import { defineSchema, id, text } from "../../schema-builder"; +import { runCheck } from "../check"; +import type { DbContext } from "../context"; +import { generateMigrationFiles } from "../migrations"; + +const builder = path.resolve( + import.meta.dirname, + "../../schema-builder/index.ts", +); +const roots: string[] = []; + +type Columns = Record; +type Tables = Record; + +function writeSchema(root: string, tables: Tables): void { + const file = path.join(root, "config/database/schema.ts"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + const body = Object.entries(tables) + .map( + ([name, columns]) => + `${name}: table(${JSON.stringify(name)}, { ${Object.entries(columns) + .map(([column, type]) => `${column}: ${type}()`) + .join(", ")} })`, + ) + .join(", "); + fs.writeFileSync( + file, + `import { defineSchema, id, text } from ${JSON.stringify(builder)}; + export const schema = defineSchema(({ table }) => ({ ${body} }));`, + ); +} + +function schemaOf(tables: Tables) { + return defineSchema(({ table }) => + Object.fromEntries( + Object.entries(tables).map(([name, columns]) => [ + name, + table( + name, + Object.fromEntries( + Object.entries(columns).map(([column, type]) => [ + column, + type === "id" ? id() : text(), + ]), + ), + ), + ]), + ), + ); +} + +function app(tables: Tables): DbContext { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-db-check-")); + roots.push(root); + writeSchema(root, tables); + return { + root, + env: {}, + workspace: () => { + throw new Error("no workspace calls expected"); + }, + api: () => { + throw new Error("no Lakebase API calls expected"); + }, + }; +} + +function migrations(ctx: DbContext): string { + return path.join(ctx.root, "config/database/migrations"); +} + +function generate(folder: string, tables: Tables) { + return generateMigrationFiles({ + folder, + schema: schemaOf(tables), + interactive: false, + }); +} + +function editJournal(folder: string, edit: (journal: Journal) => void): void { + const journal = readJournal(folder); + if (!journal) throw new Error("no journal"); + edit(journal); + fs.writeFileSync( + path.join(folder, "meta/_journal.json"), + JSON.stringify(journal, null, 2), + ); +} + +const notes: Tables = { notes: { id: "id", body: "text" } }; +const withTags: Tables = { ...notes, tags: { id: "id", label: "text" } }; +const withLikes: Tables = { ...notes, likes: { id: "id" } }; + +afterEach(() => { + vi.useRealTimers(); + for (const root of roots.splice(0)) { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +describe("runCheck", () => { + test("passes when the migrations are in order and schema.ts has none pending", async () => { + const ctx = app(withTags); + await generate(migrations(ctx), notes); + await generate(migrations(ctx), withTags); + + expect(await runCheck(ctx)).toEqual({ + migrations: ["0000_migration", "0001_migration"], + problems: [], + ok: true, + }); + }); + + test("passes with no migrations while schema.ts declares no tables", async () => { + const ctx = app({}); + + expect(await runCheck(ctx)).toEqual({ + migrations: [], + problems: [], + ok: true, + }); + }); + + test("a schema.ts change without its migration fails", async () => { + const ctx = app(withTags); + await generate(migrations(ctx), notes); + + const report = await runCheck(ctx); + + expect(report.ok).toBe(false); + expect(report.problems).toEqual([ + "config/database/schema.ts changed since 0000_migration, so the deployed app would not get the change. Run `appkit db migrate` and commit the migration it writes.", + ]); + }); + + test("tables with no migration committed at all fail", async () => { + const ctx = app(notes); + + expect((await runCheck(ctx)).problems).toEqual([ + "config/database/schema.ts changed and no migration is committed, so the deployed app would not get the change. Run `appkit db migrate` and commit the migration it writes.", + ]); + }); + + test("a renamed column counts as a change, without prompting", async () => { + const ctx = app({ notes: { id: "id", text: "text" } }); + await generate(migrations(ctx), notes); + + expect((await runCheck(ctx)).problems).toEqual([ + expect.stringContaining( + "config/database/schema.ts changed since 0000_migration", + ), + ]); + }); + + test("two migrations generated from one snapshot on parallel branches fail", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + const ctx = app({ ...withTags, ...withLikes }); + const main = migrations(ctx); + const parallel = path.join(ctx.root, "parallel"); + vi.setSystemTime(new Date("2026-10-01T00:00:00Z")); + await generate(main, notes); + fs.cpSync(main, parallel, { recursive: true }); + vi.setSystemTime(new Date("2026-10-02T00:00:00Z")); + await generate(main, withTags); + vi.setSystemTime(new Date("2026-10-03T00:00:00Z")); + await generate(parallel, withLikes); + + // The merge keeps both, renumbering the parallel one after main's. + fs.copyFileSync( + path.join(parallel, "0001_migration.sql"), + path.join(main, "0002_migration.sql"), + ); + fs.copyFileSync( + path.join(parallel, "meta/0001_snapshot.json"), + path.join(main, "meta/0002_snapshot.json"), + ); + const merged = readJournal(parallel)?.entries.at(-1); + if (!merged) throw new Error("no parallel migration"); + editJournal(main, (journal) => { + journal.entries.push({ ...merged, idx: 2, tag: "0002_migration" }); + }); + + const report = await runCheck(ctx); + + expect(report.problems).toEqual([ + expect.stringContaining( + "0002_migration was generated after 0000_migration, not after 0001_migration: they were written on parallel branches, so 0002_migration lacks the other's changes. Merge the base branch, reset the migrations to its own", + ), + "config/database/schema.ts changed since 0002_migration, so the deployed app would not get the change. Run `appkit db migrate` and commit the migration it writes.", + ]); + }); + + test("a migration listed after a newer one fails, since a branch that ran the newer one skips it", async () => { + const ctx = app(withTags); + await generate(migrations(ctx), notes); + await generate(migrations(ctx), withTags); + editJournal(migrations(ctx), (journal) => { + const [first, second] = journal.entries; + if (first && second) second.when = first.when - 1; + }); + + expect((await runCheck(ctx)).problems).toEqual([ + expect.stringContaining( + "0001_migration is listed after 0000_migration but was generated before it, so a branch that ran 0000_migration never runs 0001_migration.", + ), + ]); + }); + + test("an entry whose idx is not its position fails", async () => { + const ctx = app(notes); + await generate(migrations(ctx), notes); + editJournal(migrations(ctx), (journal) => { + const [first] = journal.entries; + if (first) first.idx = 3; + }); + fs.renameSync( + path.join(migrations(ctx), "meta/0000_snapshot.json"), + path.join(migrations(ctx), "meta/0003_snapshot.json"), + ); + + expect((await runCheck(ctx)).problems).toEqual([ + expect.stringContaining( + "0000_migration is entry 0 of meta/_journal.json, but its idx is 3, so drizzle-kit reads another snapshot for it.", + ), + ]); + }); + + test("uncommitted and unlisted files fail, and the schema is not compared without the latest snapshot", async () => { + const ctx = app({ ...withTags, extra: { id: "id" } }); + await generate(migrations(ctx), notes); + await generate(migrations(ctx), withTags); + fs.rmSync(path.join(migrations(ctx), "0000_migration.sql")); + fs.rmSync(path.join(migrations(ctx), "meta/0001_snapshot.json")); + fs.writeFileSync( + path.join(migrations(ctx), "0001_parallel.sql"), + "CREATE TABLE x ();", + ); + + expect((await runCheck(ctx)).problems).toEqual([ + `${path.join("config/database/migrations/meta/0001_snapshot.json")}, the snapshot of 0001_migration, is not committed. Restore it from version control: the next migration is generated from it.`, + `${path.join("config/database/migrations/0000_migration.sql")} is listed in meta/_journal.json but not committed. Restore it from version control.`, + expect.stringContaining( + `${path.join("config/database/migrations/0001_parallel.sql")} is not in meta/_journal.json, so no deploy runs it.`, + ), + ]); + }); + + test("without schema.ts it points to introspect", async () => { + const ctx = app({}); + fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); + + await expect(runCheck(ctx)).rejects.toThrow( + "No config/database/schema.ts yet, so there is nothing to check.", + ); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/contract.test.ts b/packages/appkit/src/database/tooling/tests/contract.test.ts index fae9f6560..823c4d465 100644 --- a/packages/appkit/src/database/tooling/tests/contract.test.ts +++ b/packages/appkit/src/database/tooling/tests/contract.test.ts @@ -10,6 +10,7 @@ const exports: DatabaseTooling = tooling; const contractKeys = { createDbContext: true, + runCheck: true, deleteSessionBranch: true, previewClean: true, runClean: true, diff --git a/packages/shared/src/cli/commands/db/check.test.ts b/packages/shared/src/cli/commands/db/check.test.ts new file mode 100644 index 000000000..369636df5 --- /dev/null +++ b/packages/shared/src/cli/commands/db/check.test.ts @@ -0,0 +1,108 @@ +import { + afterEach, + beforeEach, + describe, + expect, + type MockInstance, + test, + vi, +} from "vitest"; + +const { createDbContext, runCheck } = vi.hoisted(() => ({ + createDbContext: vi.fn(() => ({ root: "/app", env: {} })), + runCheck: vi.fn(), +})); + +// The tooling is an ambient module loaded with a dynamic import. +vi.mock("@databricks/appkit/database-tooling", () => ({ + createDbContext, + runCheck, +})); + +import { dbCommand } from "./index"; + +let log: MockInstance; +let error: MockInstance; + +function output(spy: MockInstance): string { + return spy.mock.calls.map((call) => call.join(" ")).join("\n"); +} + +beforeEach(() => { + runCheck.mockReset(); + log = vi.spyOn(console, "log").mockImplementation(() => undefined); + error = vi.spyOn(console, "error").mockImplementation(() => undefined); +}); + +afterEach(() => { + vi.restoreAllMocks(); + process.exitCode = undefined; +}); + +describe("appkit db check", () => { + test("is registered under the db group", () => { + expect(dbCommand.commands.map((command) => command.name())).toContain( + "check", + ); + }); + + test("a sound history prints what was checked and exits 0", async () => { + runCheck.mockResolvedValue({ + migrations: ["0000_migration", "0001_migration"], + problems: [], + ok: true, + }); + + await dbCommand.parseAsync(["check"], { from: "user" }); + + expect(runCheck).toHaveBeenCalledWith({ root: "/app", env: {} }); + expect(output(log)).toContain( + "The 2 committed migrations are in order with every file, and config/database/schema.ts has no change without a migration", + ); + expect(error).not.toHaveBeenCalled(); + expect(process.exitCode).toBeUndefined(); + }); + + test("no migrations and no tables is a pass", async () => { + runCheck.mockResolvedValue({ migrations: [], problems: [], ok: true }); + + await dbCommand.parseAsync(["check"], { from: "user" }); + + expect(output(log)).toContain( + "config/database/schema.ts declares nothing a migration would create, and no migration is committed", + ); + }); + + test("lists each problem and exits 1", async () => { + runCheck.mockResolvedValue({ + migrations: ["0000_migration"], + problems: [ + "config/database/schema.ts changed since 0000_migration, so the deployed app would not get the change. Run `appkit db migrate` and commit the migration it writes.", + ], + ok: false, + }); + + await dbCommand.parseAsync(["check"], { from: "user" }); + + expect(output(log)).toContain( + "config/database/schema.ts changed since 0000_migration", + ); + expect(output(error)).toContain( + "The committed migrations are not ready to deploy. Fix the above, then run `appkit db check` again.", + ); + expect(process.exitCode).toBe(1); + }); + + test("an error is printed and exits 1", async () => { + runCheck.mockRejectedValue( + new Error( + "No config/database/schema.ts yet, so there is nothing to check.", + ), + ); + + await dbCommand.parseAsync(["check"], { from: "user" }); + + expect(output(error)).toContain("there is nothing to check"); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/packages/shared/src/cli/commands/db/check.ts b/packages/shared/src/cli/commands/db/check.ts new file mode 100644 index 000000000..943c808e5 --- /dev/null +++ b/packages/shared/src/cli/commands/db/check.ts @@ -0,0 +1,37 @@ +import { Command } from "commander"; + +import { loadDatabaseTooling } from "./load-tooling"; +import { fail, printCheckReport } from "./output"; + +async function runDbCheck(): Promise { + try { + const tooling = await loadDatabaseTooling(); + const report = await tooling.runCheck(tooling.createDbContext()); + printCheckReport(report); + if (!report.ok) process.exitCode = 1; + } catch (error) { + fail(error); + } +} + +export const dbCheckCommand = new Command("check") + .description( + "Check the committed migrations against config/database/schema.ts, offline (for CI)", + ) + .addHelpText( + "after", + ` +Reads only the checkout, so it needs no Databricks or Lakebase access, only +the app's installed dependencies (drizzle-kit included). It fails when: + - the journal lists a migration generated before the one listed ahead of it; + - two migrations were generated from the same snapshot on parallel branches; + - a migration's .sql or snapshot is not committed, or a .sql is not in the + journal; + - schema.ts changed and no committed migration has the change. + +Exits 1 on any finding. Nothing is written. + +Examples: + $ appkit db check`, + ) + .action(runDbCheck); diff --git a/packages/shared/src/cli/commands/db/index.ts b/packages/shared/src/cli/commands/db/index.ts index 3c5bbcfdf..3afb0e157 100644 --- a/packages/shared/src/cli/commands/db/index.ts +++ b/packages/shared/src/cli/commands/db/index.ts @@ -1,5 +1,6 @@ import { Command } from "commander"; +import { dbCheckCommand } from "./check"; import { dbCleanCommand } from "./clean"; import { dbInitCommand } from "./init"; import { dbIntrospectCommand } from "./introspect"; @@ -18,4 +19,5 @@ export const dbCommand = new Command("db") .addCommand(dbIntrospectCommand) .addCommand(dbCleanCommand) .addCommand(dbSeedCommand) - .addCommand(dbVerifyCommand); + .addCommand(dbVerifyCommand) + .addCommand(dbCheckCommand); diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index 872169aaa..9b3b2f75b 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -107,7 +107,7 @@ afterEach(() => { }); describe("appkit db init", () => { - test("registers init, migrate, introspect, clean, seed and verify", () => { + test("registers init, migrate, introspect, clean, seed, verify and check", () => { expect(dbCommand.commands.map((c) => c.name())).toEqual([ "init", "migrate", @@ -115,6 +115,7 @@ describe("appkit db init", () => { "clean", "seed", "verify", + "check", ]); }); diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 18594ab27..6ea5e8bfc 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -4,6 +4,7 @@ import process from "node:process"; import pc from "picocolors"; import type { + CheckReport, CleanReport, DeployVerifyReport, IntrospectReport, @@ -183,6 +184,22 @@ export function printVerifyReport(report: VerifyReport): void { else printDeployVerifyReport(report); } +export function printCheckReport(report: CheckReport): void { + if (report.ok) { + const count = report.migrations.length; + ok( + count === 0 + ? "config/database/schema.ts declares nothing a migration would create, and no migration is committed" + : `The ${count} committed migration${count === 1 ? " is" : "s are"} in order with every file, and config/database/schema.ts has no change without a migration`, + ); + return; + } + for (const problem of report.problems) warn(problem); + console.error( + `${pc.red("✖")} The committed migrations are not ready to deploy. Fix the above, then run \`appkit db check\` again.`, + ); +} + export function printIntrospectReport(report: IntrospectReport): void { const count = report.tables.length; ok( diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 80930202e..7db0fba0a 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -100,6 +100,12 @@ export interface DeployVerifyReport { export type VerifyReport = LocalVerifyReport | DeployVerifyReport; +export interface CheckReport { + readonly migrations: readonly string[]; + readonly problems: readonly string[]; + readonly ok: boolean; +} + export interface InitReport { readonly mode: BranchMode; readonly branch: string; @@ -154,4 +160,5 @@ export interface DatabaseTooling { ctx: Ctx, options?: VerifyOptions, ) => Promise; + readonly runCheck: (ctx: Ctx) => Promise; } diff --git a/template/README.md.tmpl b/template/README.md.tmpl index 24270e948..dc4f127b6 100644 --- a/template/README.md.tmpl +++ b/template/README.md.tmpl @@ -81,6 +81,10 @@ sets `APPKIT_DB_MIGRATE_ON_START=true`. To adopt tables that already exist, run `npx appkit db clean` drops the app schema on your branch, and `npx appkit db seed` runs `config/database/seed.sql` on it; both refuse any branch `db init` did not create for you, such as the deployed one. + +In CI, `npx appkit db check` fails a pull request whose `schema.ts` change has no +migration, or whose migrations are out of order or missing files. It reads only the +checkout, so it needs no Databricks credentials. {{- end}} ### CLI Authentication From c517b833f6b85958e281d976692d8098aa1843a3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 15:10:02 +0000 Subject: [PATCH 015/317] chore: declare tools and the appkit bin as knip entry points knip.json ignores tools/**, so knip reported esbuild, ora and zod as unused even though tools/bundle-size.ts, tools/generate-json-schema.ts and tools/playground/deploy-playground.ts import them. It also reported packages/appkit/bin/appkit.js as an unused file. Declare these as entry points so the pre-commit knip check passes without suppressing any finding. Signed-off-by: ditadi --- knip.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/knip.json b/knip.json index 8e2d0f8a1..566a07df1 100644 --- a/knip.json +++ b/knip.json @@ -7,7 +7,15 @@ "docs" ], "workspaces": { + ".": { + "entry": [ + "tools/bundle-size.ts", + "tools/generate-json-schema.ts", + "tools/playground/deploy-playground.ts" + ] + }, "packages/appkit": { + "entry": ["bin/appkit.js"], "ignoreDependencies": [ "vitest", "@databricks/sdk-apps", From 966a51a7e1c7820897553db53ffbf9f85ae25338 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 15:10:16 +0000 Subject: [PATCH 016/317] fix(appkit): strand unapplied migrations that share a recorded timestamp reconcileMigrations kept one recorded hash per created_at, so a committed migration whose journal entry shares a when with an applied sibling was reported as edited and never ran. Keep every recorded hash per when, and classify an entry whose sibling owns the recorded row as pending or stranded. Signed-off-by: ditadi --- .../appkit/src/database/migrations/history.ts | 31 ++++++++++++------- .../database/migrations/tests/history.test.ts | 15 +++++++++ 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/packages/appkit/src/database/migrations/history.ts b/packages/appkit/src/database/migrations/history.ts index c7ca35cda..bf3583c57 100644 --- a/packages/appkit/src/database/migrations/history.ts +++ b/packages/appkit/src/database/migrations/history.ts @@ -32,29 +32,38 @@ interface MigrationHistory { /** * Match each committed migration with a recorded row by `when` = `created_at`, - * the pair drizzle-orm's migrator writes, then compare hashes. + * the pair drizzle-orm's migrator writes, then compare hashes. Two entries can + * share a `when` after a hand edit or a merge, so each `when` keeps every hash + * recorded at it. */ export function reconcileMigrations( files: readonly MigrationFile[], recorded: readonly RecordedMigration[], ): MigrationHistory { - const hashAt = new Map(); + const hashesAt = new Map>(); for (const row of recorded) { - if (row.createdAt !== null) hashAt.set(row.createdAt, row.hash); + if (row.createdAt === null) continue; + const hashes = hashesAt.get(row.createdAt) ?? new Set(); + hashes.add(row.hash); + hashesAt.set(row.createdAt, hashes); } - const lastRecorded = hashAt.size > 0 ? Math.max(...hashAt.keys()) : null; + const lastRecorded = hashesAt.size > 0 ? Math.max(...hashesAt.keys()) : null; const pending: MigrationFile[] = []; const stranded: MigrationFile[] = []; const edited: MigrationFile[] = []; for (const file of files) { - const hash = hashAt.get(file.when); - if (hash === undefined) { - if (lastRecorded === null || file.when > lastRecorded) pending.push(file); - else stranded.push(file); - } else if (hash !== file.hash) { - edited.push(file); - } + const hashes = hashesAt.get(file.when); + if (hashes?.has(file.hash)) continue; + // A row at this `when` that is another entry's: this one never ran. + const sibling = files.some( + (other) => + other !== file && other.when === file.when && hashes?.has(other.hash), + ); + if (hashes && !sibling) edited.push(file); + else if (lastRecorded === null || file.when > lastRecorded) { + pending.push(file); + } else stranded.push(file); } const committed = new Set(files.map((file) => file.when)); const unknown = recorded.filter( diff --git a/packages/appkit/src/database/migrations/tests/history.test.ts b/packages/appkit/src/database/migrations/tests/history.test.ts index 04da4ac6e..367dd605a 100644 --- a/packages/appkit/src/database/migrations/tests/history.test.ts +++ b/packages/appkit/src/database/migrations/tests/history.test.ts @@ -72,4 +72,19 @@ describe("reconcileMigrations", () => { 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([]); + }); }); From fb984c32394a9fece7c3c0d0c5726fa23af17249 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 15:22:27 +0000 Subject: [PATCH 017/317] refactor(appkit): move database tooling to @databricks/appkit/beta/database-tooling The CLI-only tooling was exported as @databricks/appkit/database-tooling, outside the beta boundary. Export it only as @databricks/appkit/beta/database-tooling and drop the old subpath. Migrate the CLI loader, its ambient declaration, the runtime import restriction, the test mock and the comments that name the path. Signed-off-by: ditadi --- .oxlintrc.json | 2 +- packages/appkit/package.json | 4 ++-- packages/appkit/src/database/tooling/index.ts | 6 +++--- packages/shared/src/cli/commands/db/database-tooling.d.ts | 2 +- packages/shared/src/cli/commands/db/index.ts | 2 +- packages/shared/src/cli/commands/db/load-tooling.ts | 2 +- packages/shared/src/cli/commands/db/migrate.test.ts | 2 +- packages/shared/src/cli/commands/db/tooling-contract.ts | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index dce5b9c8e..f874def12 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -81,7 +81,7 @@ "group": [ "**/tooling", "**/tooling/**", - "@databricks/appkit/database-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." } diff --git a/packages/appkit/package.json b/packages/appkit/package.json index 8dbc988db..b1a75a8ee 100644 --- a/packages/appkit/package.json +++ b/packages/appkit/package.json @@ -42,7 +42,7 @@ "development": "./src/type-generator/index.ts", "default": "./dist/type-generator/index.js" }, - "./database-tooling": { + "./beta/database-tooling": { "types": "./dist/database/tooling/index.d.ts", "development": "./src/database/tooling/index.ts", "default": "./dist/database/tooling/index.js" @@ -171,7 +171,7 @@ "./beta": "./dist/beta.js", "./dist/shared/src/plugin": "./dist/shared/src/plugin.d.ts", "./type-generator": "./dist/type-generator/index.js", - "./database-tooling": "./dist/database/tooling/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/database/tooling/index.ts b/packages/appkit/src/database/tooling/index.ts index bbec5337a..13927dd5f 100644 --- a/packages/appkit/src/database/tooling/index.ts +++ b/packages/appkit/src/database/tooling/index.ts @@ -1,10 +1,10 @@ /** - * `@databricks/appkit/database-tooling` — CLI-only logic behind `appkit db`. + * `@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. * - * Internal to the AppKit CLI: it has no semver guarantee, and only the CLI of - * the same AppKit release should import 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 { createDbContext, type DbContext } from "./context"; export { type MigrateOptions, type MigrateReport, runMigrate } from "./migrate"; diff --git a/packages/shared/src/cli/commands/db/database-tooling.d.ts b/packages/shared/src/cli/commands/db/database-tooling.d.ts index b133e7871..d9d602314 100644 --- a/packages/shared/src/cli/commands/db/database-tooling.d.ts +++ b/packages/shared/src/cli/commands/db/database-tooling.d.ts @@ -1,4 +1,4 @@ // `shared` must not depend on `appkit`, so this only makes the dynamic import // resolve. Its type is DatabaseTooling in ./tooling-contract.ts, which appkit's // typecheck checks against the real exports. -declare module "@databricks/appkit/database-tooling"; +declare module "@databricks/appkit/beta/database-tooling"; diff --git a/packages/shared/src/cli/commands/db/index.ts b/packages/shared/src/cli/commands/db/index.ts index aca41b888..0ffbbd391 100644 --- a/packages/shared/src/cli/commands/db/index.ts +++ b/packages/shared/src/cli/commands/db/index.ts @@ -4,7 +4,7 @@ import { dbMigrateCommand } from "./migrate"; /** * Lakebase database lifecycle for the DatabasePlugin. The logic lives in - * `@databricks/appkit/database-tooling`; these commands only parse, prompt and print. + * `@databricks/appkit/beta/database-tooling`; these commands only parse, prompt and print. */ export const dbCommand = new Command("db") .description("Lakebase database lifecycle") diff --git a/packages/shared/src/cli/commands/db/load-tooling.ts b/packages/shared/src/cli/commands/db/load-tooling.ts index 870d1ad98..0efd8538e 100644 --- a/packages/shared/src/cli/commands/db/load-tooling.ts +++ b/packages/shared/src/cli/commands/db/load-tooling.ts @@ -2,5 +2,5 @@ import type { DatabaseTooling } from "./tooling-contract"; /** The appkit tooling, loaded on first use and typed by the checked contract. */ export function loadDatabaseTooling(): Promise { - return import("@databricks/appkit/database-tooling"); + return import("@databricks/appkit/beta/database-tooling"); } diff --git a/packages/shared/src/cli/commands/db/migrate.test.ts b/packages/shared/src/cli/commands/db/migrate.test.ts index d1fe7cd8c..1e0ca7463 100644 --- a/packages/shared/src/cli/commands/db/migrate.test.ts +++ b/packages/shared/src/cli/commands/db/migrate.test.ts @@ -17,7 +17,7 @@ const { createDbContext, runMigrate } = vi.hoisted(() => ({ // The tooling is an ambient module loaded with a dynamic import; mock it so the // command never touches drizzle-kit or a database. -vi.mock("@databricks/appkit/database-tooling", () => ({ +vi.mock("@databricks/appkit/beta/database-tooling", () => ({ createDbContext, runMigrate, })); diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 06e73e359..4e2f65af4 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -20,7 +20,7 @@ export interface MigrateReport { } /** - * The exports of `@databricks/appkit/database-tooling` the CLI calls. `shared` + * The exports of `@databricks/appkit/beta/database-tooling` the CLI calls. `shared` * must not depend on appkit, so the CLI imports the tooling dynamically and * types it with this interface, and appkit's typecheck checks its real exports * against it (`database/tooling/tests/contract.test.ts`). Function properties, From 5f2b04013976e87cd19dceb298f3f12d19c840a8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 15:24:13 +0000 Subject: [PATCH 018/317] fix(appkit): bind session branches to the developer A session branch was session-, and the guard accepted it for anyone whose .env carried that id, so a copied .env let another developer write to it. Name session branches session--, the hash dev branch names already use, so only the user who created the branch passes the guard. Signed-off-by: ditadi --- packages/appkit/src/database/tooling/guard.ts | 9 ++--- .../appkit/src/database/tooling/naming.ts | 39 ++++++++++++------- .../src/database/tooling/tests/guard.test.ts | 20 +++++----- .../src/database/tooling/tests/naming.test.ts | 24 ++++++++++-- 4 files changed, 61 insertions(+), 31 deletions(-) diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts index 994fe1fac..3dd1d66d4 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -46,15 +46,12 @@ export function classifyBranch(input: { } const id = resourceId(branch.name); if (id === devBranchId(userName)) return { kind: "dev" }; - if (sessionId && id === sessionBranchId(sessionId)) { - return { kind: "session" }; - } + 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)})${ - sessionId - ? ` or this checkout's session branch (${sessionBranchId(sessionId)})` - : "" + session ? ` or this checkout's session branch (${session})` : "" }`, }; } diff --git a/packages/appkit/src/database/tooling/naming.ts b/packages/appkit/src/database/tooling/naming.ts index aadaf374b..4417e3f8c 100644 --- a/packages/appkit/src/database/tooling/naming.ts +++ b/packages/appkit/src/database/tooling/naming.ts @@ -8,7 +8,9 @@ const DEV_PREFIX = "dev-"; const SESSION_PREFIX = "session-"; const HASH_LENGTH = 6; -const SESSION_ID = /^[a-z0-9]{1,55}$/; +const SESSION_ID_LENGTH = + MAX_BRANCH_ID - SESSION_PREFIX.length - HASH_LENGTH - 1; +const SESSION_ID = new RegExp(`^[a-z0-9]{1,${SESSION_ID_LENGTH}}$`); function slug(value: string): string { return value @@ -17,32 +19,43 @@ function slug(value: string): string { .replace(/^-+|-+$/g, ""); } +function normalized(userName: string): string { + return userName.trim().toLowerCase(); +} + +/** sha256(userName)[0:6]: the part of a branch name that says whose it is. */ +function userHash(userName: string): string { + return createHash("sha256") + .update(normalized(userName)) + .digest("hex") + .slice(0, HASH_LENGTH); +} + /** - * dev--. The hash keeps users who share - * a local part apart; the name is the same on every machine. + * dev--. The hash keeps users who share a local + * part apart; the name is the same on every machine. */ export function devBranchId(userName: string): string { - const normalized = userName.trim().toLowerCase(); - const hash = createHash("sha256") - .update(normalized) - .digest("hex") - .slice(0, HASH_LENGTH); const room = MAX_BRANCH_ID - DEV_PREFIX.length - 1 - HASH_LENGTH; - const local = slug(normalized.split("@")[0] ?? "") + const local = slug(normalized(userName).split("@")[0] ?? "") .slice(0, room) .replace(/-+$/, ""); - return `${DEV_PREFIX}${local || "user"}-${hash}`; + return `${DEV_PREFIX}${local || "user"}-${userHash(userName)}`; } export function isValidSessionId(sessionId: string): boolean { return SESSION_ID.test(sessionId); } -export function sessionBranchId(sessionId: string): string { +/** + * session--. The id lives in this checkout's .env; the + * hash makes a copied .env name a branch only its creator passes the guard on. + */ +export function sessionBranchId(userName: string, sessionId: string): string { if (!isValidSessionId(sessionId)) { throw new Error( - `Invalid APPKIT_DB_SESSION ${JSON.stringify(sessionId)}: use 1-55 lowercase letters or digits.`, + `Invalid APPKIT_DB_SESSION ${JSON.stringify(sessionId)}: use 1-${SESSION_ID_LENGTH} lowercase letters or digits.`, ); } - return `${SESSION_PREFIX}${sessionId}`; + return `${SESSION_PREFIX}${userHash(userName)}-${sessionId}`; } diff --git a/packages/appkit/src/database/tooling/tests/guard.test.ts b/packages/appkit/src/database/tooling/tests/guard.test.ts index ee79cbf59..07d92eae0 100644 --- a/packages/appkit/src/database/tooling/tests/guard.test.ts +++ b/packages/appkit/src/database/tooling/tests/guard.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, test } from "vitest"; import { classifyBranch, resolveEnvBranch, takesWrites } from "../guard"; -import { devBranchId } from "../naming"; +import { devBranchId, sessionBranchId } from "../naming"; import { cleanupTempApps, databricksYml, @@ -15,6 +15,7 @@ afterEach(cleanupTempApps); const USER = "alice@example.com"; const P = "projects/p"; const dev = `${P}/branches/${devBranchId(USER)}`; +const session = `${P}/branches/${sessionBranchId(USER, "k2x9q0ab")}`; function verdict( name: string, @@ -33,9 +34,7 @@ function verdict( describe("classifyBranch", () => { test("only this developer's dev branch and this checkout's session branch take writes", () => { expect(verdict(dev)).toEqual({ kind: "dev" }); - expect(verdict(`${P}/branches/session-k2x9q0ab`)).toEqual({ - kind: "session", - }); + expect(verdict(session)).toEqual({ kind: "session" }); expect(takesWrites("dev")).toBe(true); expect(takesWrites("session")).toBe(true); }); @@ -57,11 +56,14 @@ describe("classifyBranch", () => { verdict(`${P}/branches/${devBranchId("bob@example.com")}`).kind, ).toBe("other"); expect(verdict(`${P}/branches/session-other`).kind).toBe("other"); - expect(verdict(`${P}/branches/session-k2x9q0ab`, {}, null).kind).toBe( - "other", - ); - expect(verdict(`${P}/branches/staging`).reason).toContain( - devBranchId(USER), + expect(verdict(session, {}, null).kind).toBe("other"); + // Bob's .env copied into Alice's checkout names Bob's session branch. + expect( + verdict(`${P}/branches/${sessionBranchId("bob@example.com", "k2x9q0ab")}`) + .kind, + ).toBe("other"); + expect(verdict(`${P}/branches/staging`).reason).toBe( + `it is not your dev branch (${devBranchId(USER)}) or this checkout's session branch (${sessionBranchId(USER, "k2x9q0ab")})`, ); for (const kind of ["default", "protected", "deploy-target", "other"]) { expect(takesWrites(kind as "other")).toBe(false); diff --git a/packages/appkit/src/database/tooling/tests/naming.test.ts b/packages/appkit/src/database/tooling/tests/naming.test.ts index 423f33ad0..11d46db41 100644 --- a/packages/appkit/src/database/tooling/tests/naming.test.ts +++ b/packages/appkit/src/database/tooling/tests/naming.test.ts @@ -31,9 +31,27 @@ describe("branch naming", () => { ); }); - test("session branches are session-; ids are lowercase base36", () => { - expect(sessionBranchId("k2x9q0ab")).toBe("session-k2x9q0ab"); + test("session branches are session--; ids are lowercase base36", () => { + const hash = devBranchId("alice@example.com").slice(-6); + expect(sessionBranchId("Alice@example.com", "k2x9q0ab")).toBe( + `session-${hash}-k2x9q0ab`, + ); expect(isValidSessionId("Bad-Id")).toBe(false); - expect(() => sessionBranchId("Bad-Id")).toThrow(/APPKIT_DB_SESSION/); + expect(() => sessionBranchId("alice@example.com", "Bad-Id")).toThrow( + /APPKIT_DB_SESSION/, + ); + }); + + test("the longest session id still makes a valid branch ID", () => { + const id = sessionBranchId("alice@example.com", "a".repeat(48)); + expect(id).toHaveLength(63); + expect(id).toMatch(BRANCH_ID); + expect(isValidSessionId("a".repeat(49))).toBe(false); + }); + + test("a copied .env names a session branch only its creator owns", () => { + expect(sessionBranchId("alice@example.com", "abc")).not.toBe( + sessionBranchId("bob@example.com", "abc"), + ); }); }); From 1f2490e155704a0b28cfd3f2eb1c7b5e4fda158e Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 15:31:06 +0000 Subject: [PATCH 019/317] fix(appkit): refuse writes when databricks.yml binds a branch it does not name The guard read only each target's postgres_branch variable and dropped references it could not resolve, so a branch bound through an app's postgres resource, an included file or an unresolved reference could pass as a dev branch. Read every postgres binding of every app and target, including included files, into one deploy boundary that keeps unresolved branch and database references. While any reference is unresolved, no branch takes writes. Signed-off-by: ditadi --- packages/appkit/src/database/tooling/guard.ts | 42 ++- .../appkit/src/database/tooling/targets.ts | 297 ++++++++++++++++-- .../src/database/tooling/tests/fakes.ts | 6 + .../src/database/tooling/tests/guard.test.ts | 62 +++- .../database/tooling/tests/targets.test.ts | 127 +++++++- 5 files changed, 474 insertions(+), 60 deletions(-) diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts index 3dd1d66d4..c1b558531 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -3,8 +3,9 @@ import { currentIdentity } from "./identity"; import type { LakebaseBranch } from "./lakebase-api"; import { devBranchId, sessionBranchId } from "./naming"; import { + type DeployBoundary, parseResourceName, - readDeployBranches, + readDeployBoundary, readLocalTarget, resourceId, } from "./targets"; @@ -24,26 +25,44 @@ interface Classification { 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. + */ +function deployRefusal( + boundary: DeployBoundary, + branch: string, +): string | null { + if (boundary.unresolved.length > 0) { + const references = boundary.unresolved + .map( + ({ target, at, written }) => + `${at} in target ${target} (${written ? JSON.stringify(written) : "no value"})`, + ) + .join(", "); + return `databricks.yml may deploy to it: the files do not resolve ${references}; give ${boundary.unresolved.length > 1 ? "them values" : "it a value"} in databricks.yml`; + } + return boundary.branches.has(branch) + ? "it is a branch databricks.yml deploys to" + : null; +} + export function classifyBranch(input: { branch: LakebaseBranch; userName: string; sessionId: string | null; - /** Every branch databricks.yml deploys to; the deployed app migrates those itself. */ - deployBranches: readonly string[]; + /** What databricks.yml deploys to; the deployed app migrates those branches itself. */ + boundary: DeployBoundary; }): Classification { - const { branch, userName, sessionId, deployBranches } = input; + 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" }; } - if (deployBranches.includes(branch.name)) { - return { - kind: "deploy-target", - reason: "it is a branch databricks.yml deploys to", - }; - } + 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; @@ -84,6 +103,7 @@ export async function resolveEnvBranch( const local = readLocalTarget(ctx.env); const name = parseResourceName(local.endpoint ?? undefined)?.branch; if (!name || !hasEnvBranch(ctx.env)) return null; + const boundary = readDeployBoundary(ctx.root); const [branch, { userName }] = await Promise.all([ ctx.api().getBranch(name), currentIdentity(ctx), @@ -99,7 +119,7 @@ export async function resolveEnvBranch( branch, userName, sessionId: local.session, - deployBranches: readDeployBranches(ctx.root), + boundary, }), }; } diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index ff1cef3e8..51de32f13 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -62,12 +62,48 @@ function record(value: unknown): Yaml { : undefined; } -/** databricks.yml, parsed; null without one. Invalid YAML throws, so no check that reads it passes silently. */ -function readBundle(root: string): Record | null { - const file = ["databricks.yml", "databricks.yaml"] - .map((name) => path.join(root, name)) - .find((candidate) => fs.existsSync(candidate)); - if (!file) return null; +/** + * A branch or database databricks.yml names, as far as the checkout's files + * resolve it. A reference that is not declared at all has no value: the + * binding or variable that holds it is absent instead. + */ +type BundleValue = + /** A full resource name, e.g. "projects/p/branches/b". */ + | { readonly kind: "resolved"; readonly name: string } + /** As written: a `${…}` only a deploy resolves, no value, or not a resource name. */ + | { readonly kind: "unresolved"; readonly written: string }; + +/** One postgres resource of an app. */ +interface PostgresBinding { + /** Where it is in the merged bundle, e.g. "resources.apps.app.resources[0].postgres". */ + readonly at: string; + readonly branch: BundleValue; + /** null when the binding names no database. */ + readonly database: BundleValue | null; +} + +/** An app one target of databricks.yml deploys. */ +interface BundleApp { + /** Its key under resources.apps. */ + readonly key: string; + /** Every postgres resource it has. */ + readonly postgres: readonly PostgresBinding[]; +} + +/** One target of databricks.yml, with what the files alone can resolve resolved. */ +interface BundleTarget { + readonly name: string; + readonly apps: readonly BundleApp[]; + /** The target's postgres_branch variable; null when the bundle declares none. */ + readonly postgresBranch: BundleValue | null; +} + +interface Bundle { + readonly targets: readonly BundleTarget[]; +} + +/** Invalid YAML throws, so no check that reads the bundle passes silently. */ +function parseYaml(file: string): Record { try { return record(yaml.load(fs.readFileSync(file, "utf-8"))) ?? {}; } catch (error) { @@ -79,37 +115,238 @@ function readBundle(root: string): Record | null { } } +/** Files an `include:` pattern names. `*` and `?` match within one path segment, as in the Databricks CLI. */ +function includedFiles(root: string, pattern: string): string[] { + let paths = [root]; + for (const segment of pattern.split("/")) { + if (!segment || segment === ".") continue; + if (!/[*?]/.test(segment)) { + paths = paths.map((dir) => path.join(dir, segment)); + continue; + } + const matcher = new RegExp( + `^${segment + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\?/g, ".")}$`, + ); + paths = paths.flatMap((dir) => { + try { + return fs + .readdirSync(dir) + .filter((entry) => matcher.test(entry)) + .map((entry) => path.join(dir, entry)); + } catch { + return []; + } + }); + } + return paths.filter((file) => + fs.statSync(file, { throwIfNoEntry: false })?.isFile(), + ); +} + +/** Mappings merge key by key; lists of named entries (an app's resources) merge by name; anything else is replaced. */ +function merge(base: unknown, override: unknown): unknown { + const left = record(base); + const right = record(override); + if (left && right) { + const merged: Record = { ...left }; + for (const [key, value] of Object.entries(right)) { + merged[key] = key in left ? merge(left[key], value) : value; + } + return merged; + } + if (Array.isArray(base) && Array.isArray(override)) { + const named = (items: unknown[]) => + items.every((item) => typeof record(item)?.name === "string"); + if (named(base) && named(override)) { + const byName = new Map( + base.map((item) => [record(item)?.name as string, item]), + ); + for (const item of override) { + const name = record(item)?.name as string; + byName.set(name, merge(byName.get(name), item)); + } + return [...byName.values()]; + } + } + return override; +} + /** A target's value for a bundle variable, else the variable's default. */ function variableOf( bundle: Record, target: Yaml, name: string, -): string | null { - const value = - record(target?.variables)?.[name] ?? - record(record(bundle.variables)?.[name])?.default ?? - null; - return typeof value === "string" && value ? value : null; +): unknown { + const override = record(target?.variables)?.[name]; + if (override !== undefined) return record(override)?.default ?? override; + return record(record(bundle.variables)?.[name])?.default; +} + +const REFERENCE = /\$\{([^}]+)\}/g; +const MAX_REFERENCE_DEPTH = 10; + +/** Resolves `${var.*}`, `${bundle.target}` and `${bundle.name}` for one target; null when a reference needs a deploy to resolve. */ +function resolverFor( + bundle: Record, + target: Yaml, + targetName: string, +): (value: unknown) => string | null { + const resolve = (value: unknown, depth: number): string | null => { + if (typeof value !== "string" || depth > MAX_REFERENCE_DEPTH) return null; + let unresolved = false; + const text = value.replace(REFERENCE, (_, reference: string) => { + const resolved = reference.startsWith("var.") + ? resolve( + variableOf(bundle, target, reference.slice("var.".length)), + depth + 1, + ) + : reference === "bundle.target" + ? targetName + : reference === "bundle.name" + ? resolve(record(bundle.bundle)?.name, depth + 1) + : null; + if (resolved === null) unresolved = true; + return resolved ?? ""; + }); + return unresolved || !text ? null : text; + }; + return (value) => resolve(value, 0); +} + +function bundleValue( + written: unknown, + resolve: (value: unknown) => string | null, + kind: "branch" | "database", +): BundleValue { + const name = parseResourceName(resolve(written) ?? undefined)?.[kind]; + if (name) return { kind: "resolved", name }; + return { + kind: "unresolved", + written: typeof written === "string" ? written : "", + }; +} + +function bundleApps( + apps: Record, + resolve: (value: unknown) => string | null, +): BundleApp[] { + return Object.entries(apps).map(([key, value]) => { + const app = record(value); + const resources = Array.isArray(app?.resources) ? app.resources : []; + const postgres = resources.flatMap((resource, index): PostgresBinding[] => { + const binding = record(record(resource)?.postgres); + if (!binding) return []; + return [ + { + at: `resources.apps.${key}.resources[${index}].postgres`, + branch: bundleValue(binding.branch, resolve, "branch"), + database: + binding.database === undefined + ? null + : bundleValue(binding.database, resolve, "database"), + }, + ]; + }); + return { key, postgres }; + }); } /** - * Every branch databricks.yml can deploy to: each target's postgres_branch and - * the variable's default. Empty without databricks.yml or a postgres binding. + * databricks.yml, with the files its `include:` names merged in, per target; + * null without one. Without `targets:` the bundle has one target, "default". */ -export function readDeployBranches(root: string): string[] { - const bundle = readBundle(root); - if (!bundle) return []; - const targets = [ - undefined, - ...Object.values(record(bundle.targets) ?? {}).map(record), - ]; - const branches = targets - .map( - (target) => - parseResourceName( - variableOf(bundle, target, "postgres_branch") ?? undefined, - )?.branch, - ) - .filter((branch): branch is string => !!branch); - return [...new Set(branches)]; +function readBundle(root: string): Bundle | null { + const file = ["databricks.yml", "databricks.yaml"] + .map((name) => path.join(root, name)) + .find((candidate) => fs.existsSync(candidate)); + if (!file) return null; + const main = parseYaml(file); + const includes = Array.isArray(main.include) ? main.include : []; + const bundle = record( + includes + .filter((pattern): pattern is string => typeof pattern === "string") + .flatMap((pattern) => includedFiles(root, pattern)) + .reduce( + (merged, included) => merge(merged, parseYaml(included)), + main, + ), + ) as Record; + + const declared = Object.entries(record(bundle.targets) ?? {}); + const targets: Array<[string, Yaml]> = + declared.length > 0 + ? declared.map(([name, target]) => [name, record(target)]) + : [["default", { default: true }]]; + return { + targets: targets.map(([name, target]) => { + const resolve = resolverFor(bundle, target, name); + const apps = record( + merge( + record(record(bundle.resources)?.apps) ?? {}, + record(record(target?.resources)?.apps) ?? {}, + ), + ); + const declaresBranch = + "postgres_branch" in (record(bundle.variables) ?? {}) || + "postgres_branch" in (record(target?.variables) ?? {}); + return { + name, + apps: bundleApps(apps ?? {}, resolve), + postgresBranch: declaresBranch + ? bundleValue( + variableOf(bundle, target, "postgres_branch"), + resolve, + "branch", + ) + : null, + }; + }), + }; +} + +/** A reference in databricks.yml the checkout's files cannot resolve to a branch or database. */ +export interface UnresolvedBinding { + readonly target: string; + /** Where it is written, e.g. "resources.apps.app.resources[0].postgres.branch". */ + readonly at: string; + readonly written: string; +} + +/** What databricks.yml deploys to, read from this checkout's files only. */ +export interface DeployBoundary { + /** Every branch any target binds, through an app's postgres resources or its postgres_branch variable. */ + readonly branches: ReadonlySet; + /** While any exists, any branch may be one a target deploys to. */ + readonly unresolved: readonly UnresolvedBinding[]; +} + +/** + * Every branch databricks.yml can deploy to, across targets, and every + * reference it cannot resolve. Empty without databricks.yml or a postgres + * binding. A database counts for the branch it is on. + */ +export function readDeployBoundary(root: string): DeployBoundary { + const branches = new Set(); + const unresolved: UnresolvedBinding[] = []; + for (const target of readBundle(root)?.targets ?? []) { + const add = (at: string, value: BundleValue) => { + if (value.kind === "unresolved") { + unresolved.push({ target: target.name, at, written: value.written }); + return; + } + const branch = parseResourceName(value.name)?.branch; + if (branch) branches.add(branch); + }; + for (const binding of target.apps.flatMap((app) => app.postgres)) { + add(`${binding.at}.branch`, binding.branch); + if (binding.database) add(`${binding.at}.database`, binding.database); + } + if (target.postgresBranch) { + add("variables.postgres_branch", target.postgresBranch); + } + } + return { branches, unresolved }; } diff --git a/packages/appkit/src/database/tooling/tests/fakes.ts b/packages/appkit/src/database/tooling/tests/fakes.ts index ceaf6006a..e90bf0d0d 100644 --- a/packages/appkit/src/database/tooling/tests/fakes.ts +++ b/packages/appkit/src/database/tooling/tests/fakes.ts @@ -110,6 +110,12 @@ resources: app: name: "my-app" source_code_path: ./ + resources: + - name: postgres + postgres: + branch: \${var.postgres_branch} + database: \${var.postgres_database} + permission: CAN_CONNECT_AND_CREATE targets: default: default: true diff --git a/packages/appkit/src/database/tooling/tests/guard.test.ts b/packages/appkit/src/database/tooling/tests/guard.test.ts index 07d92eae0..97b0e69af 100644 --- a/packages/appkit/src/database/tooling/tests/guard.test.ts +++ b/packages/appkit/src/database/tooling/tests/guard.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, test } from "vitest"; import { classifyBranch, resolveEnvBranch, takesWrites } from "../guard"; import { devBranchId, sessionBranchId } from "../naming"; +import type { DeployBoundary } from "../targets"; import { cleanupTempApps, databricksYml, @@ -17,17 +18,19 @@ const P = "projects/p"; const dev = `${P}/branches/${devBranchId(USER)}`; const session = `${P}/branches/${sessionBranchId(USER, "k2x9q0ab")}`; +const NO_DEPLOYS: DeployBoundary = { branches: new Set(), unresolved: [] }; + function verdict( name: string, status = {}, sessionId: string | null = "k2x9q0ab", - deployBranches: string[] = [], + boundary: DeployBoundary = NO_DEPLOYS, ) { return classifyBranch({ branch: { name, status }, userName: USER, sessionId, - deployBranches, + boundary, }); } @@ -48,7 +51,12 @@ describe("classifyBranch", () => { kind: "protected", reason: "it is a protected branch", }); - expect(verdict(dev, {}, null, [`${P}/branches/staging`, dev])).toEqual({ + expect( + verdict(dev, {}, null, { + branches: new Set([`${P}/branches/staging`, dev]), + unresolved: [], + }), + ).toEqual({ kind: "deploy-target", reason: "it is a branch databricks.yml deploys to", }); @@ -69,6 +77,26 @@ describe("classifyBranch", () => { expect(takesWrites(kind as "other")).toBe(false); } }); + + test("while databricks.yml has a reference the files cannot resolve, no branch takes writes", () => { + const unresolved: DeployBoundary = { + branches: new Set(), + unresolved: [ + { + target: "prod", + at: "resources.apps.app.resources[0].postgres.branch", + written: "${var.postgres_branch}", + }, + ], + }; + for (const branch of [dev, session]) { + expect(verdict(branch, {}, "k2x9q0ab", unresolved)).toEqual({ + kind: "deploy-target", + reason: + 'databricks.yml may deploy to it: the files do not resolve resources.apps.app.resources[0].postgres.branch in target prod ("${var.postgres_branch}"); give it a value in databricks.yml', + }); + } + }); }); describe("resolveEnvBranch", () => { @@ -132,6 +160,7 @@ describe("resolveEnvBranch", () => { "databricks.yml": `${databricksYml(`${P}/branches/production`, `${P}/branches/production/databases/db`)} personal: variables: postgres_branch: ${dev} + postgres_database: ${dev}/databases/db `, }); const broken = tempApp({ "databricks.yml": "targets:\n default: [\n" }); @@ -143,7 +172,10 @@ describe("resolveEnvBranch", () => { api: lakebase.api(), }), ); - expect(env).toMatchObject({ kind: "deploy-target" }); + expect(env).toMatchObject({ + kind: "deploy-target", + reason: "it is a branch databricks.yml deploys to", + }); await expect( resolveEnvBranch( fakeContext({ root: broken, env: envFor(dev), api: lakebase.api() }), @@ -153,6 +185,28 @@ describe("resolveEnvBranch", () => { ); }); + test("a target whose branch the files cannot resolve keeps your own dev branch from taking writes", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(dev); + const root = tempApp({ + "databricks.yml": `${databricksYml(`${P}/branches/production`, `${P}/branches/production/databases/db`)} staging: + variables: + postgres_branch: \${var.staging_branch} + postgres_database: ${P}/branches/staging/databases/db +`, + }); + + const env = await resolveEnvBranch( + fakeContext({ root, env: envFor(dev), api: lakebase.api() }), + ); + + expect(env?.kind).toBe("deploy-target"); + expect(env && takesWrites(env.kind)).toBe(false); + expect(env?.reason).toContain( + 'resources.apps.app.resources[0].postgres.branch in target staging ("${var.postgres_branch}")', + ); + }); + test("null unless .env names a branch to connect to; a deleted branch points at init", async () => { const lakebase = new FakeLakebase(); await expect( diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index ac159a7df..24c6b47ae 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "vitest"; import { parseResourceName, - readDeployBranches, + readDeployBoundary, readLocalTarget, } from "../targets"; import { cleanupTempApps, databricksYml, tempApp } from "./fakes"; @@ -59,17 +59,18 @@ describe("readLocalTarget", () => { }); }); -describe("readDeployBranches", () => { - test("reads the default target's postgres_branch", () => { +describe("readDeployBoundary", () => { + test("reads the default target's postgres resource and postgres_branch", () => { const root = tempApp({ "databricks.yml": databricksYml( "projects/p/branches/production", "projects/p/branches/production/databases/databricks-postgres", ), }); - expect(readDeployBranches(root)).toEqual([ - "projects/p/branches/production", - ]); + expect(readDeployBoundary(root)).toEqual({ + branches: new Set(["projects/p/branches/production"]), + unresolved: [], + }); }); test("every target's branch counts, and the variable's default", () => { @@ -88,23 +89,119 @@ targets: postgres_branch: projects/p/branches/staging `, }); - expect(readDeployBranches(root)).toEqual([ - "projects/p/branches/main", - "projects/p/branches/dev-alice-1a2b3c", - "projects/p/branches/staging", - ]); + expect(readDeployBoundary(root).branches).toEqual( + new Set([ + "projects/p/branches/main", + "projects/p/branches/dev-alice-1a2b3c", + "projects/p/branches/staging", + ]), + ); + }); + + test("every postgres resource of every app counts, in an included file too", () => { + const root = tempApp({ + "databricks.yml": `include: + - resources/*.yml +resources: + apps: + app: + resources: + - name: postgres + postgres: + branch: projects/p/branches/production + - name: archive + postgres: + branch: projects/p/branches/archive +`, + "resources/reports.yml": `resources: + apps: + reports: + resources: + - name: postgres + postgres: + branch: projects/p/branches/reports + database: projects/p/branches/reports/databases/db +`, + }); + expect(readDeployBoundary(root)).toEqual({ + branches: new Set([ + "projects/p/branches/production", + "projects/p/branches/archive", + "projects/p/branches/reports", + ]), + unresolved: [], + }); + }); + + test("a target that gives a declared variable no value leaves its references unresolved", () => { + const root = tempApp({ + "databricks.yml": `${databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/db", + )} prod: {} +`, + }); + expect(readDeployBoundary(root)).toEqual({ + branches: new Set(["projects/p/branches/production"]), + unresolved: [ + { + target: "prod", + at: "resources.apps.app.resources[0].postgres.branch", + written: "${var.postgres_branch}", + }, + { + target: "prod", + at: "resources.apps.app.resources[0].postgres.database", + written: "${var.postgres_database}", + }, + { target: "prod", at: "variables.postgres_branch", written: "" }, + ], + }); + }); + + test("a reference only a deploy resolves, or a value that is not a branch, is unresolved", () => { + const root = tempApp({ + "databricks.yml": `resources: + apps: + app: + resources: + - name: postgres + postgres: + branch: projects/p/branches/dev-\${workspace.current_user.short_name} + - name: other + postgres: + branch: main +`, + }); + expect(readDeployBoundary(root)).toEqual({ + branches: new Set(), + unresolved: [ + { + target: "default", + at: "resources.apps.app.resources[0].postgres.branch", + written: + "projects/p/branches/dev-${workspace.current_user.short_name}", + }, + { + target: "default", + at: "resources.apps.app.resources[1].postgres.branch", + written: "main", + }, + ], + }); }); test("empty without databricks.yml or without a postgres binding", () => { - expect(readDeployBranches(tempApp())).toEqual([]); + const empty = { branches: new Set(), unresolved: [] }; + expect(readDeployBoundary(tempApp())).toEqual(empty); expect( - readDeployBranches(tempApp({ "databricks.yml": "bundle:\n name: x\n" })), - ).toEqual([]); + readDeployBoundary(tempApp({ "databricks.yml": "bundle:\n name: x\n" })), + ).toEqual(empty); }); test("an invalid databricks.yml throws instead of reading as no binding", () => { const root = tempApp({ "databricks.yml": "targets:\n default: [\n" }); - expect(() => readDeployBranches(root)).toThrow( + expect(() => readDeployBoundary(root)).toThrow( /^Cannot read databricks\.yml, so the branches it deploys to are unknown: .+\(\d+:\d+\)$/, ); }); From 5f0726753bb3f77a939d701c9096d1aa8d0a811f Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 15:39:23 +0000 Subject: [PATCH 020/317] fix(appkit): give one command at a time the checkout's migration history Generation read the journal, waited for drizzle-kit, then wrote the next SQL, snapshot and journal, and a failed apply restored the journal read before. Two commands in one checkout could overwrite or remove each other's migration. appkit db migrate now holds config/database/.appkit-db.lock, created exclusively, from before it reads the history until it finishes. Generation and discard take the held lock, and discard restores the journal that generation itself replaced. A lock left by a killed process is reported as stale with the manual recovery step, never taken over. Signed-off-by: ditadi --- .gitignore | 3 + .../src/database/tooling/history-lock.ts | 140 ++++++++++++++++++ .../appkit/src/database/tooling/migrate.ts | 33 ++--- .../appkit/src/database/tooling/migrations.ts | 39 +++-- .../tests/drizzle-kit-dependency.test.ts | 16 +- .../tooling/tests/history-lock.test.ts | 135 +++++++++++++++++ .../database/tooling/tests/migrate.test.ts | 38 +++++ .../database/tooling/tests/migrations.test.ts | 110 +++++++++----- template/_gitignore | 3 + 9 files changed, 441 insertions(+), 76 deletions(-) create mode 100644 packages/appkit/src/database/tooling/history-lock.ts create mode 100644 packages/appkit/src/database/tooling/tests/history-lock.test.ts 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/packages/appkit/src/database/tooling/history-lock.ts b/packages/appkit/src/database/tooling/history-lock.ts new file mode 100644 index 000000000..c92872035 --- /dev/null +++ b/packages/appkit/src/database/tooling/history-lock.ts @@ -0,0 +1,140 @@ +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"; + +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.`, + ); +} + +/** + * 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 or the process exits. A process killed by a signal + * 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); + if (readOwner(file)?.token === owner.token) + fs.rmSync(file, { force: true }); + }; + process.on("exit", release); + 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/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index ec2343450..0f5ea4c3c 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -13,13 +13,10 @@ import { applyPendingMigrations, MigrationApplyError, } from "../migrations/apply"; -import { - journalFile, - migrationsFolder, - readJournal, -} from "../migrations/paths"; +import { readJournal } from "../migrations/paths"; import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context"; import { notYourBranch, resolveEnvBranch, takesWrites } from "./guard"; +import { type HistoryLock, withHistoryLock } from "./history-lock"; import { breakingStatements, discardMigrationFiles, @@ -40,11 +37,6 @@ function requireSchemaFile(root: string): void { ); } -/** The journal's text before this run writes to it; null when there is none. */ -function readJournalText(folder: string): string | null { - const file = journalFile(folder); - return fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : null; -} const DATABASE_TYPES_PATH = path.join( "shared/appkit-types", DATABASE_TYPES_FILE, @@ -101,20 +93,27 @@ async function applyToEnvBranch( /** * `appkit db migrate`: generate a migration when schema.ts changed, regenerate * database.d.ts, and apply pending migrations to the `.env` branch (only AppKit - * dev/session branches). + * dev/session branches). One command at a time owns the checkout's history. */ export async function runMigrate( ctx: DbContext, options: MigrateOptions, ): Promise { requireSchemaFile(ctx.root); + return withHistoryLock(ctx.root, "migrate", (lock) => + migrateHolding(ctx, lock, options), + ); +} + +async function migrateHolding( + ctx: DbContext, + lock: HistoryLock, + options: MigrateOptions, +): Promise { const schema = await loadDefaultDatabaseSchema(ctx.root, { showImportError: true, }); - const folder = migrationsFolder(ctx.root); - const journalBefore = readJournalText(folder); - const generated = await generateMigrationFiles({ - folder, + const generated = await generateMigrationFiles(lock, { schema, interactive: options.interactive, }); @@ -125,7 +124,7 @@ export async function runMigrate( let outcome: ApplyOutcome; try { - outcome = await applyToEnvBranch(ctx, folder, schema.$schemaName); + outcome = await applyToEnvBranch(ctx, lock.folder, schema.$schemaName); } catch (error) { if (!generated) throw error; const file = path.relative(ctx.root, generated.file); @@ -136,7 +135,7 @@ export async function runMigrate( error.failed === generated.tag && error.code ) { - discardMigrationFiles(folder, generated, journalBefore); + discardMigrationFiles(lock, generated); throw new Error( `${error.message} Removed ${file}, so the next run writes it again from ${DEFAULT_SCHEMA_FILE}. Change ${DEFAULT_SCHEMA_FILE} or the branch's data, then rerun \`appkit db migrate\`.`, { cause: error }, diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 81786a253..a7a9e2b63 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -16,6 +16,7 @@ import { } from "../migrations/paths"; import type { Schema } from "../schema-builder"; import { drizzleKitImports } from "./drizzle-exports"; +import type { HistoryLock } from "./history-lock"; /** * The drizzle-kit release the snapshots and SQL are written for; the optional @@ -24,8 +25,6 @@ import { drizzleKitImports } from "./drizzle-exports"; export const DRIZZLE_KIT_VERSION = "0.31.10"; interface GenerateOptions { - /** Absolute migrations folder. */ - readonly folder: string; readonly schema: Schema; /** false: an ambiguous rename throws instead of prompting. */ readonly interactive: boolean; @@ -37,6 +36,8 @@ export interface GeneratedMigration { /** Absolute path of the written .sql file. */ readonly file: string; readonly statements: readonly string[]; + /** The journal's text this migration replaced; null when there was none. */ + readonly journalBefore: string | null; } /** @@ -294,12 +295,14 @@ function writeFileAtomic(file: string, content: string): void { * and the appended `meta/_journal.json`. null when nothing changed. */ export async function generateMigrationFiles( + lock: HistoryLock, options: GenerateOptions, ): Promise { const { generateDrizzleJson, generateMigration } = await loadDrizzleKit(); + const { folder } = lock; - const journal = readJournal(options.folder); - const prev = latestSnapshot(options.folder, journal); + const journal = readJournal(folder); + const prev = latestSnapshot(folder, journal); const cur = generateDrizzleJson(drizzleKitImports(options.schema), prev.id, [ options.schema.$schemaName, ]) as unknown as Snapshot; @@ -338,10 +341,15 @@ export async function generateMigrationFiles( entries: [...entries, entry], }; - const file = migrationFile(options.folder, tag); - fs.mkdirSync(metaFolder(options.folder), { recursive: true }); + lock.assertHeld(); + const file = migrationFile(folder, tag); + const journalPath = journalFile(folder); + const journalBefore = fs.existsSync(journalPath) + ? fs.readFileSync(journalPath, "utf-8") + : null; + fs.mkdirSync(metaFolder(folder), { recursive: true }); fs.writeFileSync( - snapshotFile(options.folder, idx), + snapshotFile(folder, idx), JSON.stringify( { ...cur, _meta: { columns: {}, schemas: {}, tables: {} } }, null, @@ -350,25 +358,26 @@ export async function generateMigrationFiles( ); fs.writeFileSync(file, statements.join(BREAKPOINT)); // The journal is written last: it is what makes the migration visible. - writeFileAtomic(journalFile(options.folder), JSON.stringify(next, null, 2)); - return { tag, file, statements }; + writeFileAtomic(journalPath, JSON.stringify(next, null, 2)); + return { tag, file, statements, journalBefore }; } /** - * Remove a migration generateMigrationFiles wrote and put back the journal it - * replaced (null: there was none, so the folders it created go too). + * Remove a migration generateMigrationFiles wrote under the same lock and put + * back the journal it replaced (none: the folders it created go too). */ export function discardMigrationFiles( - folder: string, + lock: HistoryLock, migration: GeneratedMigration, - journalBefore: string | null, ): void { + lock.assertHeld(); + const { folder } = lock; fs.rmSync(migration.file, { force: true }); fs.rmSync(snapshotFile(folder, Number.parseInt(migration.tag, 10)), { force: true, }); - if (journalBefore !== null) { - writeFileAtomic(journalFile(folder), journalBefore); + if (migration.journalBefore !== null) { + writeFileAtomic(journalFile(folder), migration.journalBefore); return; } fs.rmSync(journalFile(folder), { force: true }); diff --git a/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts b/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts index badf5ff76..6aa8a76ad 100644 --- a/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts +++ b/packages/appkit/src/database/tooling/tests/drizzle-kit-dependency.test.ts @@ -6,6 +6,7 @@ import { pathToFileURL } from "node:url"; import { afterEach, describe, expect, test, vi } from "vitest"; import { defineSchema, id } from "../../schema-builder"; +import { withHistoryLock } from "../history-lock"; const SRC = path.resolve(import.meta.dirname, "../../.."); const folders: string[] = []; @@ -41,13 +42,14 @@ function tempRoot(): string { } function generate(migrations: typeof import("../migrations")) { - return migrations.generateMigrationFiles({ - folder: path.join(tempRoot(), "migrations"), - schema: defineSchema(({ table }) => ({ - notes: table("notes", { id: id() }), - })), - interactive: false, - }); + return withHistoryLock(tempRoot(), "migrate", (lock) => + migrations.generateMigrationFiles(lock, { + schema: defineSchema(({ table }) => ({ + notes: table("notes", { id: id() }), + })), + interactive: false, + }), + ); } /** A file URL in an app whose node_modules holds these drizzle-kit and drizzle-orm versions. */ diff --git a/packages/appkit/src/database/tooling/tests/history-lock.test.ts b/packages/appkit/src/database/tooling/tests/history-lock.test.ts new file mode 100644 index 000000000..807ef9069 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/history-lock.test.ts @@ -0,0 +1,135 @@ +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, test } from "vitest"; + +import { withHistoryLock } from "../history-lock"; +import { cleanupTempApps, tempApp } from "./fakes"; + +afterEach(cleanupTempApps); + +const LOCK = "config/database/.appkit-db.lock"; + +function writeLock(root: string, contents: string): void { + fs.mkdirSync(path.dirname(path.join(root, LOCK)), { recursive: true }); + fs.writeFileSync(path.join(root, LOCK), contents); +} + +async function failure(promise: Promise): Promise { + return promise.then( + () => { + throw new Error("expected the lock to be refused"); + }, + (error: Error) => error, + ); +} + +describe("withHistoryLock", () => { + test("a second command in the checkout fails with who holds it, and the lock goes when the first finishes", async () => { + const root = tempApp(); + + const result = await withHistoryLock(root, "migrate", async () => { + const file = path.join(root, LOCK); + expect(fs.statSync(file).mode & 0o777).toBe(0o600); + const owner = JSON.parse(fs.readFileSync(file, "utf-8")); + expect(owner).toMatchObject({ + pid: process.pid, + host: os.hostname(), + command: "migrate", + }); + + const error = await failure( + withHistoryLock(root, "introspect", async () => "ran"), + ); + expect(error.message).toBe( + `Another \`appkit db migrate\` (pid ${process.pid} on ${os.hostname()}, since ${owner.startedAt}) is changing the migration history in config/database. Wait for it to finish, then rerun.`, + ); + return "done"; + }); + + expect(result).toBe("done"); + expect(fs.existsSync(path.join(root, LOCK))).toBe(false); + await expect( + withHistoryLock(root, "introspect", async () => "ran"), + ).resolves.toBe("ran"); + }); + + test("the lock goes when the command throws too", async () => { + const root = tempApp(); + const thrown = new Error("generation failed"); + + await expect( + withHistoryLock(root, "migrate", async () => { + throw thrown; + }), + ).rejects.toBe(thrown); + expect(fs.existsSync(path.join(root, LOCK))).toBe(false); + }); + + test("a lock left by a process that exited is reported stale and kept byte for byte", async () => { + const root = tempApp(); + const child = spawn(process.execPath, ["-e", ""]); + await new Promise((resolve) => child.once("exit", resolve)); + const stale = JSON.stringify({ + pid: child.pid, + host: os.hostname(), + command: "migrate", + startedAt: "2026-01-01T00:00:00.000Z", + token: "theirs", + }); + writeLock(root, stale); + + const error = await failure( + withHistoryLock(root, "migrate", async () => "ran"), + ); + + expect(error.message).toBe( + `\`appkit db migrate\` (pid ${child.pid}) stopped without releasing ${LOCK}. Make sure no appkit db command runs in this checkout, delete ${LOCK}, then rerun.`, + ); + expect(fs.readFileSync(path.join(root, LOCK), "utf-8")).toBe(stale); + }); + + test("a lock from another host, or one that cannot be read, is never taken over", async () => { + const root = tempApp(); + const elsewhere = JSON.stringify({ + pid: process.pid, + host: "build-agent-7", + command: "clean", + startedAt: "2026-01-01T00:00:00.000Z", + token: "theirs", + }); + + for (const [contents, holder] of [ + [elsewhere, " on build-agent-7"], + ["", ""], + ] as const) { + writeLock(root, contents); + const error = await failure( + withHistoryLock(root, "migrate", async () => "ran"), + ); + expect(error.message).toBe( + `${LOCK} says another appkit db command${holder} is changing the migration history. Make sure no appkit db command runs in this checkout, delete ${LOCK}, then rerun.`, + ); + expect(fs.readFileSync(path.join(root, LOCK), "utf-8")).toBe(contents); + } + }); + + test("releasing leaves a lock another holder wrote in its place", async () => { + const root = tempApp(); + const replaced = JSON.stringify({ + pid: process.pid, + host: os.hostname(), + command: "migrate", + startedAt: "2026-01-01T00:00:00.000Z", + token: "theirs", + }); + + await withHistoryLock(root, "migrate", async () => { + fs.writeFileSync(path.join(root, LOCK), replaced); + }); + + expect(fs.readFileSync(path.join(root, LOCK), "utf-8")).toBe(replaced); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 15056e199..32344c69d 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -341,4 +341,42 @@ describe("runMigrate", () => { ]); expect(report.breaking).toEqual(report.generated?.statements); }); + + test("a second migrate in the same checkout fails while the first runs, and writes nothing", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + let finishApply: (value: unknown) => void = () => undefined; + let applying: (value?: unknown) => void = () => undefined; + const started = new Promise((resolve) => { + applying = resolve; + }); + applyPendingMigrations.mockImplementation(() => { + applying(); + return new Promise((resolve) => { + finishApply = resolve; + }); + }); + const first = runMigrate(ctx, { interactive: false }); + await started; + + writeSchema(ctx.root, `notes: table("notes", { id: id(), body: text() })`); + const folder = path.join(ctx.root, "config/database/migrations"); + const filesBefore = fs.readdirSync(folder, { recursive: true }).sort(); + await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( + new RegExp( + `^Another \`appkit db migrate\` \\(pid ${process.pid} on .+\\) is changing the migration history in config/database\\. Wait for it to finish, then rerun\\.$`, + ), + ); + expect(fs.readdirSync(folder, { recursive: true }).sort()).toEqual( + filesBefore, + ); + + finishApply({ applied: ["0000_migration"], adopted: [] }); + await expect(first).resolves.toMatchObject({ + applied: ["0000_migration"], + }); + applyPendingMigrations.mockResolvedValue({ applied: [], adopted: [] }); + await expect( + runMigrate(ctx, { interactive: false }), + ).resolves.toMatchObject({ generated: { tag: "0001_migration" } }); + }); }); diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index edfdf0fb8..6afff74fe 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -18,6 +18,7 @@ import { timestamp, varchar, } from "../../schema-builder"; +import { withHistoryLock } from "../history-lock"; import { breakingStatements, discardMigrationFiles, @@ -33,6 +34,21 @@ function tempFolder(): string { return path.join(root, "config/database/migrations"); } +/** The checkout a tempFolder belongs to. */ +function rootOf(folder: string): string { + return path.resolve(folder, "../../.."); +} + +/** generateMigrationFiles under the checkout's history lock, as a command runs it. */ +function generate({ + folder, + ...options +}: Parameters[1] & { folder: string }) { + return withHistoryLock(rootOf(folder), "migrate", (lock) => + generateMigrationFiles(lock, options), + ); +} + /** Every file under a folder, relative, sorted — to prove nothing was written. */ function listFiles(folder: string): string[] { if (!fs.existsSync(folder)) return []; @@ -71,7 +87,7 @@ const blog = (extraPostColumns = {}) => describe("generateMigrationFiles", () => { test("writes a v7 migration from real drizzle-kit output for the builder's tables", async () => { const folder = tempFolder(); - const generated = await generateMigrationFiles({ + const generated = await generate({ folder, schema: blog(), interactive: false, @@ -127,7 +143,7 @@ describe("generateMigrationFiles", () => { test("returns null and writes nothing when the schema matches the latest snapshot", async () => { const folder = tempFolder(); - await generateMigrationFiles({ + await generate({ folder, schema: blog(), interactive: false, @@ -138,7 +154,7 @@ describe("generateMigrationFiles", () => { ]); await expect( - generateMigrationFiles({ folder, schema: blog(), interactive: false }), + generate({ folder, schema: blog(), interactive: false }), ).resolves.toBeNull(); expect( listFiles(folder).map((file) => [ @@ -152,14 +168,14 @@ describe("generateMigrationFiles", () => { vi.useFakeTimers({ toFake: ["Date"] }); vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); const folder = tempFolder(); - await generateMigrationFiles({ + await generate({ folder, schema: blog(), interactive: false, }); // A clock that did not move must still yield a newer journal entry. - const next = await generateMigrationFiles({ + const next = await generate({ folder, schema: blog({ views: integer().notNull().default(0) }), interactive: false, @@ -187,14 +203,14 @@ describe("generateMigrationFiles", () => { test("a non-interactive column rename throws instead of prompting, and writes nothing", async () => { const folder = tempFolder(); - await generateMigrationFiles({ + await generate({ folder, schema: blog({ summary: text() }), interactive: false, }); const before = listFiles(folder); - const error = await generateMigrationFiles({ + const error = await generate({ folder, schema: blog({ abstract: text() }), interactive: false, @@ -215,14 +231,14 @@ describe("generateMigrationFiles", () => { const folder = tempFolder(); const named = (name: string) => defineSchema(({ table }) => ({ [name]: table(name, { id: id() }) })); - await generateMigrationFiles({ + await generate({ folder, schema: named("notes"), interactive: false, }); await expect( - generateMigrationFiles({ + generate({ folder, schema: named("memos"), interactive: false, @@ -238,7 +254,7 @@ describe("generateMigrationFiles", () => { test("an empty schema with no history writes nothing", async () => { const folder = tempFolder(); await expect( - generateMigrationFiles({ + generate({ folder, schema: defineSchema(() => ({})), interactive: false, @@ -249,12 +265,12 @@ describe("generateMigrationFiles", () => { test("drizzle-orm's runtime migrator reads the written files", async () => { const folder = tempFolder(); - await generateMigrationFiles({ + await generate({ folder, schema: blog(), interactive: false, }); - await generateMigrationFiles({ + await generate({ folder, schema: blog({ views: integer() }), interactive: false, @@ -281,14 +297,14 @@ describe("generateMigrationFiles", () => { role: enumColumn(enumName, ["admin", "member"]), }), })); - await generateMigrationFiles({ + await generate({ folder, schema: roles("user_role"), interactive: false, }); const before = listFiles(folder); - const error = await generateMigrationFiles({ + const error = await generate({ folder, schema: roles("member_role"), interactive: false, @@ -305,14 +321,14 @@ describe("generateMigrationFiles", () => { test("refuses to diff when the latest snapshot is missing", async () => { const folder = tempFolder(); - await generateMigrationFiles({ + await generate({ folder, schema: blog(), interactive: false, }); fs.rmSync(path.join(folder, "meta/0000_snapshot.json")); await expect( - generateMigrationFiles({ + generate({ folder, schema: blog({ views: integer() }), interactive: false, @@ -322,7 +338,7 @@ describe("generateMigrationFiles", () => { test("a corrupt snapshot names the file and how to recover", async () => { const folder = tempFolder(); - await generateMigrationFiles({ + await generate({ folder, schema: blog(), interactive: false, @@ -331,7 +347,7 @@ describe("generateMigrationFiles", () => { fs.writeFileSync(snapshot, "{ not json"); await expect( - generateMigrationFiles({ + generate({ folder, schema: blog({ views: integer() }), interactive: false, @@ -373,38 +389,58 @@ describe("breakingStatements", () => { describe("discardMigrationFiles", () => { test("a first migration goes with the folders it created", async () => { const folder = tempFolder(); - const migration = await generateMigrationFiles({ - folder, - schema: blog(), - interactive: false, + await withHistoryLock(rootOf(folder), "migrate", async (lock) => { + const migration = await generateMigrationFiles(lock, { + schema: blog(), + interactive: false, + }); + expect(migration?.journalBefore).toBeNull(); + discardMigrationFiles(lock, migration as never); }); - discardMigrationFiles(folder, migration as never, null); - expect(fs.existsSync(folder)).toBe(false); }); - test("a later migration goes, and the previous journal comes back byte for byte", async () => { + test("a later migration goes, and the journal it replaced comes back byte for byte", async () => { const folder = tempFolder(); - await generateMigrationFiles({ - folder, - schema: blog(), - interactive: false, - }); + await generate({ folder, schema: blog(), interactive: false }); const journalFile = path.join(folder, "meta/_journal.json"); const journalBefore = `${fs.readFileSync(journalFile, "utf-8")}\n`; fs.writeFileSync(journalFile, journalBefore); const filesBefore = listFiles(folder); - const migration = await generateMigrationFiles({ - folder, - schema: blog({ summary: text() }), - interactive: false, - }); - expect(listFiles(folder)).not.toEqual(filesBefore); - discardMigrationFiles(folder, migration as never, journalBefore); + await withHistoryLock(rootOf(folder), "migrate", async (lock) => { + const migration = await generateMigrationFiles(lock, { + schema: blog({ summary: text() }), + interactive: false, + }); + expect(listFiles(folder)).not.toEqual(filesBefore); + discardMigrationFiles(lock, migration as never); + }); expect(listFiles(folder)).toEqual(filesBefore); expect(fs.readFileSync(journalFile, "utf-8")).toBe(journalBefore); }); + + test("a writer whose lock was released removes nothing", async () => { + const folder = tempFolder(); + let released: Parameters[0] | undefined; + const migration = await withHistoryLock( + rootOf(folder), + "migrate", + async (lock) => { + released = lock; + return generateMigrationFiles(lock, { + schema: blog(), + interactive: false, + }); + }, + ); + const filesBefore = listFiles(folder); + + expect(() => + discardMigrationFiles(released as never, migration as never), + ).toThrow(/lock .* was released/); + expect(listFiles(folder)).toEqual(filesBefore); + }); }); diff --git a/template/_gitignore b/template/_gitignore index 29895e7c0..f0faf4e16 100644 --- a/template/_gitignore +++ b/template/_gitignore @@ -9,6 +9,9 @@ build/ test-results/ playwright-report/ +# `appkit db` holds it while a command changes the migration history +config/database/.appkit-db.lock + # Auto-generated types (endpoint-specific, varies per developer) shared/appkit-types/serving.d.ts From 348022141a10daffd0f75f2ea009068f5d57fcd0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 15:40:43 +0000 Subject: [PATCH 021/317] docs(appkit): describe appkit db migrate guards and the history lock Document where the beta tooling lives, which branches migrate writes to, the refusal while databricks.yml has an unresolved branch or database reference, the file-only limits of that check, and how to recover from a stale config/database/.appkit-db.lock. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 1467dd10b..dd1a233c1 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -112,6 +112,54 @@ 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`. +## Generate and apply migrations locally + +:::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. +::: + +`npx appkit db migrate` compares `config/database/schema.ts` with the latest +committed snapshot. When they differ, it writes +`config/database/migrations/NNNN_migration.sql`. It regenerates +`shared/appkit-types/database.d.ts`, then applies pending migrations to the +branch `.env` names. Commit the migrations with `schema.ts`. + +`migrate` applies migrations only to your dev branch or to 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. + +### 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. + +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}`. While any such +reference exists, `migrate` applies migrations to no branch. The message names +the target and where the reference is. To continue, give the reference a value +in `databricks.yml`. + +The check reads only this checkout's files. It does not see values passed at +deploy time with `--var` or `BUNDLE_VAR_*`. It protects branches from the CLI, +and does not replace Lakebase permissions or protected branches. + +### One command at a time + +While `migrate` runs, it holds `config/database/.appkit-db.lock`. A second +`appkit db` command in the same checkout fails and names the process that holds +the lock. The lock goes when the command finishes or exits. + +A command stopped by a signal, such as SIGKILL, can leave the file behind. The +next command then reports that the holder stopped. To recover, make sure 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`. + ## Schema discovery and overrides `database()` and `database({})` use the same defaults. During setup, the plugin From e5a1ac4fa4cb473868d6216e3b46a4c271dab0e9 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:01:47 +0000 Subject: [PATCH 022/317] fix(appkit): count variable-overrides.json branches as deploy targets The Databricks CLI applies .databricks/bundle//variable-overrides.json ahead of a target's variables and their defaults, so an override could deploy the app to a developer's dev branch while the guard still classified it as dev. Read each target's override file and add its bindings to the deploy boundary next to databricks.yml's own. A value that is not a resolvable string is unresolved, and a file that is not a JSON object throws. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 14 +- packages/appkit/src/database/tooling/guard.ts | 9 +- .../appkit/src/database/tooling/targets.ts | 137 ++++++++++++++---- .../database/tooling/tests/targets.test.ts | 84 +++++++++++ 4 files changed, 210 insertions(+), 34 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index dd1a233c1..a3b089862 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -135,18 +135,24 @@ yours. `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. +`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}`. While any such reference exists, `migrate` applies migrations to no branch. The message names the target and where the reference is. To continue, give the reference a value -in `databricks.yml`. +in `databricks.yml`, or in the `variable-overrides.json` the message names. A +`variable-overrides.json` that is not a JSON object stops `migrate` too. The check reads only this checkout's files. It does not see values passed at -deploy time with `--var` or `BUNDLE_VAR_*`. It protects branches from the CLI, -and does not replace Lakebase permissions or protected branches. +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 diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts index c1b558531..ef19cb7aa 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -36,11 +36,14 @@ function deployRefusal( if (boundary.unresolved.length > 0) { const references = boundary.unresolved .map( - ({ target, at, written }) => - `${at} in target ${target} (${written ? JSON.stringify(written) : "no value"})`, + ({ target, at, written, file }) => + `${at} in target ${target}${file ? ` with ${file}` : ""} (${written ? JSON.stringify(written) : "no value"})`, ) .join(", "); - return `databricks.yml may deploy to it: the files do not resolve ${references}; give ${boundary.unresolved.length > 1 ? "them values" : "it a value"} in databricks.yml`; + const where = boundary.unresolved.some(({ file }) => file) + ? "databricks.yml or the variable-overrides.json named" + : "databricks.yml"; + return `databricks.yml may deploy to it: the files do not resolve ${references}; give ${boundary.unresolved.length > 1 ? "them values" : "it a value"} in ${where}`; } return boundary.branches.has(branch) ? "it is a branch databricks.yml deploys to" diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 51de32f13..a0edca74b 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -90,14 +90,24 @@ interface BundleApp { readonly postgres: readonly PostgresBinding[]; } -/** One target of databricks.yml, with what the files alone can resolve resolved. */ -interface BundleTarget { - readonly name: string; +/** What one target binds with one set of variable values. */ +interface TargetBindings { readonly apps: readonly BundleApp[]; /** The target's postgres_branch variable; null when the bundle declares none. */ readonly postgresBranch: BundleValue | null; } +/** One target of databricks.yml, with what the files alone can resolve resolved. */ +interface BundleTarget extends TargetBindings { + readonly name: string; + /** + * The same bindings with this checkout's variable-overrides.json applied, + * which a deploy from here uses ahead of the target's own values; null + * without the file. + */ + readonly overridden: (TargetBindings & { readonly file: string }) | null; +} + interface Bundle { readonly targets: readonly BundleTarget[]; } @@ -115,6 +125,42 @@ function parseYaml(file: string): Record { } } +/** + * The variable values `databricks bundle` keeps for a target in + * `.databricks/bundle//variable-overrides.json`; null without the + * file. Anything but a JSON object throws. + */ +function readVariableOverrides( + root: string, + target: string, +): { readonly file: string; readonly values: Record } | null { + const file = `.databricks/bundle/${target}/variable-overrides.json`; + const full = path.join( + root, + ".databricks", + "bundle", + target, + "variable-overrides.json", + ); + if (!fs.existsSync(full)) return null; + let values: Yaml; + try { + values = record(JSON.parse(fs.readFileSync(full, "utf-8"))); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw new Error( + `Cannot read ${file}, so the branches it deploys to are unknown: ${reason}`, + { cause: error }, + ); + } + if (!values) { + throw new Error( + `Cannot read ${file}, so the branches it deploys to are unknown: it is not a JSON object`, + ); + } + return { file, values }; +} + /** Files an `include:` pattern names. `*` and `?` match within one path segment, as in the Databricks CLI. */ function includedFiles(root: string, pattern: string): string[] { let paths = [root]; @@ -174,12 +220,17 @@ function merge(base: unknown, override: unknown): unknown { return override; } -/** A target's value for a bundle variable, else the variable's default. */ +/** + * A variable's value for one target: from variable-overrides.json when it has + * one, else the target's value, else the variable's default. + */ function variableOf( bundle: Record, target: Yaml, name: string, + overrides: Record | null, ): unknown { + if (overrides && Object.hasOwn(overrides, name)) return overrides[name]; const override = record(target?.variables)?.[name]; if (override !== undefined) return record(override)?.default ?? override; return record(record(bundle.variables)?.[name])?.default; @@ -193,6 +244,7 @@ function resolverFor( bundle: Record, target: Yaml, targetName: string, + overrides: Record | null, ): (value: unknown) => string | null { const resolve = (value: unknown, depth: number): string | null => { if (typeof value !== "string" || depth > MAX_REFERENCE_DEPTH) return null; @@ -200,7 +252,12 @@ function resolverFor( const text = value.replace(REFERENCE, (_, reference: string) => { const resolved = reference.startsWith("var.") ? resolve( - variableOf(bundle, target, reference.slice("var.".length)), + variableOf( + bundle, + target, + reference.slice("var.".length), + overrides, + ), depth + 1, ) : reference === "bundle.target" @@ -282,7 +339,6 @@ function readBundle(root: string): Bundle | null { : [["default", { default: true }]]; return { targets: targets.map(([name, target]) => { - const resolve = resolverFor(bundle, target, name); const apps = record( merge( record(record(bundle.resources)?.apps) ?? {}, @@ -292,15 +348,27 @@ function readBundle(root: string): Bundle | null { const declaresBranch = "postgres_branch" in (record(bundle.variables) ?? {}) || "postgres_branch" in (record(target?.variables) ?? {}); + const bindings = ( + overrides: Record | null, + ): TargetBindings => { + const resolve = resolverFor(bundle, target, name, overrides); + return { + apps: bundleApps(apps ?? {}, resolve), + postgresBranch: declaresBranch + ? bundleValue( + variableOf(bundle, target, "postgres_branch", overrides), + resolve, + "branch", + ) + : null, + }; + }; + const overrides = readVariableOverrides(root, name); return { name, - apps: bundleApps(apps ?? {}, resolve), - postgresBranch: declaresBranch - ? bundleValue( - variableOf(bundle, target, "postgres_branch"), - resolve, - "branch", - ) + ...bindings(null), + overridden: overrides + ? { file: overrides.file, ...bindings(overrides.values) } : null, }; }), @@ -313,9 +381,11 @@ export interface UnresolvedBinding { /** Where it is written, e.g. "resources.apps.app.resources[0].postgres.branch". */ readonly at: string; readonly written: string; + /** The variable-overrides.json whose values leave it unresolved; absent for databricks.yml's own values. */ + readonly file?: string; } -/** What databricks.yml deploys to, read from this checkout's files only. */ +/** What databricks.yml deploys to, read from this checkout's files only, variable-overrides.json included. */ export interface DeployBoundary { /** Every branch any target binds, through an app's postgres resources or its postgres_branch variable. */ readonly branches: ReadonlySet; @@ -332,20 +402,33 @@ export function readDeployBoundary(root: string): DeployBoundary { const branches = new Set(); const unresolved: UnresolvedBinding[] = []; for (const target of readBundle(root)?.targets ?? []) { - const add = (at: string, value: BundleValue) => { - if (value.kind === "unresolved") { - unresolved.push({ target: target.name, at, written: value.written }); - return; - } - const branch = parseResourceName(value.name)?.branch; - if (branch) branches.add(branch); - }; - for (const binding of target.apps.flatMap((app) => app.postgres)) { - add(`${binding.at}.branch`, binding.branch); - if (binding.database) add(`${binding.at}.database`, binding.database); + const views: Array<[TargetBindings, string | undefined]> = [ + [target, undefined], + ]; + if (target.overridden) { + views.push([target.overridden, target.overridden.file]); } - if (target.postgresBranch) { - add("variables.postgres_branch", target.postgresBranch); + for (const [bindings, file] of views) { + const add = (at: string, value: BundleValue) => { + if (value.kind === "unresolved") { + unresolved.push({ + target: target.name, + at, + written: value.written, + ...(file ? { file } : {}), + }); + return; + } + const branch = parseResourceName(value.name)?.branch; + if (branch) branches.add(branch); + }; + for (const binding of bindings.apps.flatMap((app) => app.postgres)) { + add(`${binding.at}.branch`, binding.branch); + if (binding.database) add(`${binding.at}.database`, binding.database); + } + if (bindings.postgresBranch) { + add("variables.postgres_branch", bindings.postgresBranch); + } } } return { branches, unresolved }; diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index 24c6b47ae..339433370 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -1,5 +1,7 @@ import { afterEach, describe, expect, test } from "vitest"; +import { classifyBranch } from "../guard"; +import { devBranchId } from "../naming"; import { parseResourceName, readDeployBoundary, @@ -191,6 +193,88 @@ resources: }); }); + test("a variable-overrides.json value binds its target too, so the dev branch it names is a deploy target", () => { + const dev = `projects/p/branches/${devBranchId("alice@example.com")}`; + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/db", + ), + ".databricks/bundle/default/variable-overrides.json": JSON.stringify({ + postgres_branch: dev, + postgres_database: `${dev}/databases/db`, + }), + }); + + const boundary = readDeployBoundary(root); + + expect(boundary).toEqual({ + branches: new Set(["projects/p/branches/production", dev]), + unresolved: [], + }); + expect( + classifyBranch({ + branch: { name: dev, status: {} }, + userName: "alice@example.com", + sessionId: null, + boundary, + }), + ).toEqual({ + kind: "deploy-target", + reason: "it is a branch databricks.yml deploys to", + }); + }); + + test("a variable-overrides.json value that is not a branch name is unresolved, and names the file", () => { + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/db", + ), + ".databricks/bundle/default/variable-overrides.json": JSON.stringify({ + postgres_branch: { lookup: { name: "dev" } }, + }), + }); + + expect(readDeployBoundary(root).unresolved).toEqual([ + { + target: "default", + at: "resources.apps.app.resources[0].postgres.branch", + written: "${var.postgres_branch}", + file: ".databricks/bundle/default/variable-overrides.json", + }, + { + target: "default", + at: "variables.postgres_branch", + written: "", + file: ".databricks/bundle/default/variable-overrides.json", + }, + ]); + }); + + test.each([ + [ + "{", + /^Cannot read \.databricks\/bundle\/default\/variable-overrides\.json, so the branches it deploys to are unknown: .+/, + ], + [ + "[]", + /^Cannot read \.databricks\/bundle\/default\/variable-overrides\.json, so the branches it deploys to are unknown: it is not a JSON object$/, + ], + ])( + "a variable-overrides.json of %s throws instead of reading as no override", + (contents, message) => { + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/db", + ), + ".databricks/bundle/default/variable-overrides.json": contents, + }); + expect(() => readDeployBoundary(root)).toThrow(message); + }, + ); + test("empty without databricks.yml or without a postgres binding", () => { const empty = { branches: new Set(), unresolved: [] }; expect(readDeployBoundary(tempApp())).toEqual(empty); From 8960476c606203a34ca3a5fab4f5eae494880e23 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:02:42 +0000 Subject: [PATCH 023/317] fix(appkit): refuse include patterns the deploy boundary cannot match includedFiles matched only * and ?, so an include: pattern with [, ] or \\ matched no file and the bindings in the files it named were left out of the deploy boundary. Throw "Cannot read include pattern ..." for such a segment instead. Signed-off-by: ditadi --- packages/appkit/src/database/tooling/targets.ts | 11 ++++++++++- .../src/database/tooling/tests/targets.test.ts | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index a0edca74b..2d487f2ea 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -161,10 +161,19 @@ function readVariableOverrides( return { file, values }; } -/** Files an `include:` pattern names. `*` and `?` match within one path segment, as in the Databricks CLI. */ +/** + * Files an `include:` pattern names. `*` and `?` match within one path + * segment, as in the Databricks CLI; a pattern with other glob syntax throws + * instead of matching nothing. + */ function includedFiles(root: string, pattern: string): string[] { let paths = [root]; for (const segment of pattern.split("/")) { + if (/[[\]\\]/.test(segment)) { + throw new Error( + `Cannot read include pattern ${JSON.stringify(pattern)}, so the branches it deploys to are unknown: only * and ? are supported, not [, ] or \\.`, + ); + } if (!segment || segment === ".") continue; if (!/[*?]/.test(segment)) { paths = paths.map((dir) => path.join(dir, segment)); diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index 339433370..9430bf88d 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -135,6 +135,23 @@ resources: }); }); + test("an include pattern with glob syntax beyond * and ? throws instead of matching nothing", () => { + const root = tempApp({ + "databricks.yml": "include:\n - resources/[ab]*.yml\n", + "resources/app.yml": `resources: + apps: + app: + resources: + - name: postgres + postgres: + branch: projects/p/branches/production +`, + }); + expect(() => readDeployBoundary(root)).toThrow( + 'Cannot read include pattern "resources/[ab]*.yml", so the branches it deploys to are unknown: only * and ? are supported, not [, ] or \\.', + ); + }); + test("a target that gives a declared variable no value leaves its references unresolved", () => { const root = tempApp({ "databricks.yml": `${databricksYml( From ed020756f4b4d73241c0b567c52a9b8b0692df0b Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:03:54 +0000 Subject: [PATCH 024/317] fix(appkit): give the busy history lock message its recovery step A lock whose pid runs on this host was reported only as busy, so a pid reused after a reboot left no way forward. End the message with the stale-lock recovery step, and say in the docs when each message appears. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 11 +++++++---- packages/appkit/src/database/tooling/history-lock.ts | 2 +- .../src/database/tooling/tests/history-lock.test.ts | 2 +- .../appkit/src/database/tooling/tests/migrate.test.ts | 2 +- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index a3b089862..01e79cdd8 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -161,10 +161,13 @@ While `migrate` runs, it holds `config/database/.appkit-db.lock`. A second the lock. The lock goes when the command finishes or exits. A command stopped by a signal, such as SIGKILL, can leave the file behind. The -next command then reports that the holder stopped. To recover, make sure 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`. +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`. ## Schema discovery and overrides diff --git a/packages/appkit/src/database/tooling/history-lock.ts b/packages/appkit/src/database/tooling/history-lock.ts index c92872035..f52a5eb0b 100644 --- a/packages/appkit/src/database/tooling/history-lock.ts +++ b/packages/appkit/src/database/tooling/history-lock.ts @@ -70,7 +70,7 @@ function heldError(root: string, file: string): Error { ); } 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.`, + `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}`, ); } diff --git a/packages/appkit/src/database/tooling/tests/history-lock.test.ts b/packages/appkit/src/database/tooling/tests/history-lock.test.ts index 807ef9069..90ce9bde2 100644 --- a/packages/appkit/src/database/tooling/tests/history-lock.test.ts +++ b/packages/appkit/src/database/tooling/tests/history-lock.test.ts @@ -44,7 +44,7 @@ describe("withHistoryLock", () => { withHistoryLock(root, "introspect", async () => "ran"), ); expect(error.message).toBe( - `Another \`appkit db migrate\` (pid ${process.pid} on ${os.hostname()}, since ${owner.startedAt}) is changing the migration history in config/database. Wait for it to finish, then rerun.`, + `Another \`appkit db migrate\` (pid ${process.pid} on ${os.hostname()}, since ${owner.startedAt}) is changing the migration history in config/database. Wait for it to finish, then rerun. If pid ${process.pid} is not an appkit db command, for example because a reboot reused it, the lock is stale. Make sure no appkit db command runs in this checkout, delete ${LOCK}, then rerun.`, ); return "done"; }); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 32344c69d..839141444 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -363,7 +363,7 @@ describe("runMigrate", () => { const filesBefore = fs.readdirSync(folder, { recursive: true }).sort(); await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( new RegExp( - `^Another \`appkit db migrate\` \\(pid ${process.pid} on .+\\) is changing the migration history in config/database\\. Wait for it to finish, then rerun\\.$`, + `^Another \`appkit db migrate\` \\(pid ${process.pid} on .+\\) is changing the migration history in config/database\\. Wait for it to finish, then rerun\\. If pid ${process.pid} is not an appkit db command, for example because a reboot reused it, the lock is stale\\. Make sure no appkit db command runs in this checkout, delete config/database/\\.appkit-db\\.lock, then rerun\\.$`, ), ); expect(fs.readdirSync(folder, { recursive: true }).sort()).toEqual( From 6f5eeb83c2062de7c1c59be53757d64ef7375567 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:05:57 +0000 Subject: [PATCH 025/317] chore(appkit): acknowledge db tooling bundle size growth Regenerated with pnpm clean && pnpm build && pnpm size:baseline. Against main's baseline the @databricks/appkit packed tarball grows from 1297373 to 1364290 bytes (+66917, +5.16%), over the 5% budget. The growth is the CLI-only @databricks/appkit/beta/database-tooling entry (28 KB gzipped) and the database tooling it ships. @databricks/appkit-ui is unchanged at 406741 bytes. Signed-off-by: ditadi --- bundle-size-baseline.json | 80 ++++++++++++++++++++++++--------------- 1 file changed, 49 insertions(+), 31 deletions(-) diff --git a/bundle-size-baseline.json b/bundle-size-baseline.json index dfbb5295c..6618e1e14 100644 --- a/bundle-size-baseline.json +++ b/bundle-size-baseline.json @@ -3,25 +3,25 @@ { "name": "@databricks/appkit", "tarball": { - "packed": 1297373, - "unpacked": 4453717 + "packed": 1364290, + "unpacked": 4666959 }, "dist": { "total": { - "raw": 4438327, - "gzip": 1520942 + "raw": 4651188, + "gzip": 1599394 }, "js": { - "raw": 1320443, - "gzip": 468638 + "raw": 1391995, + "gzip": 496182 }, "types": { - "raw": 474763, - "gzip": 172113 + "raw": 478827, + "gzip": 174184 }, "maps": { - "raw": 2632326, - "gzip": 876373 + "raw": 2769571, + "gzip": 925210 }, "css": { "raw": 0, @@ -31,22 +31,22 @@ "raw": 10795, "gzip": 3818 }, - "fileCount": 895 + "fileCount": 935 }, "entries": [ { "id": ".", "gzip": 111090, "composition": { - "initialGzip": 108517, - "lazyGzip": 2573, + "initialGzip": 108516, + "lazyGzip": 2574, "totalGzip": 111090, "own": 351738, "nodeModules": null, "chunks": [ { "label": "index.js", - "gzip": 103847, + "gzip": 103846, "kind": "initial" }, { @@ -56,7 +56,7 @@ }, { "label": "remote-tunnel-manager.js", - "gzip": 2573, + "gzip": 2574, "kind": "lazy" } ] @@ -64,17 +64,17 @@ }, { "id": "./beta", - "gzip": 105499, + "gzip": 110783, "composition": { - "initialGzip": 105014, + "initialGzip": 110298, "lazyGzip": 485, - "totalGzip": 105499, - "own": 316145, + "totalGzip": 110783, + "own": 331023, "nodeModules": null, "chunks": [ { "label": "beta.js", - "gzip": 84463, + "gzip": 89747, "kind": "initial" }, { @@ -125,13 +125,31 @@ ] } }, + { + "id": "./beta/database-tooling", + "gzip": 28557, + "composition": { + "initialGzip": 28557, + "lazyGzip": 0, + "totalGzip": 28557, + "own": 84002, + "nodeModules": null, + "chunks": [ + { + "label": "index.js", + "gzip": 28557, + "kind": "initial" + } + ] + } + }, { "id": "./testing", - "gzip": 79051, + "gzip": 79050, "composition": { - "initialGzip": 45993, - "lazyGzip": 33058, - "totalGzip": 79051, + "initialGzip": 45995, + "lazyGzip": 33055, + "totalGzip": 79050, "own": 228781, "nodeModules": null, "chunks": [ @@ -142,7 +160,7 @@ }, { "label": "index.js", - "gzip": 10286, + "gzip": 10288, "kind": "initial" }, { @@ -152,12 +170,12 @@ }, { "label": "index.js", - "gzip": 28625, + "gzip": 28624, "kind": "lazy" }, { "label": "remote-tunnel-manager.js", - "gzip": 2587, + "gzip": 2585, "kind": "lazy" }, { @@ -188,17 +206,17 @@ }, { "id": "./type-generator", - "gzip": 26634, + "gzip": 26635, "composition": { - "initialGzip": 26634, + "initialGzip": 26635, "lazyGzip": 0, - "totalGzip": 26634, + "totalGzip": 26635, "own": 76220, "nodeModules": null, "chunks": [ { "label": "index.js", - "gzip": 26634, + "gzip": 26635, "kind": "initial" } ] From bd4ff71e0e3201ebffb91b567f9ca3b62d7f0ed7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:10:44 +0000 Subject: [PATCH 026/317] fix(appkit): run appkit db introspect under the history lock Introspect writes and discards migration files too, so it now holds config/database/.appkit-db.lock for its whole run, like migrate. A second command refuses before the catalog is read and changes nothing. The shared CLI test mocks the beta/database-tooling path the CLI loads. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 7 +++-- .../src/database/tooling/introspect/index.ts | 28 +++++++++++-------- .../introspect/tests/introspect.test.ts | 25 +++++++++++++---- .../introspect/tests/roundtrip.test.ts | 16 +++++------ .../src/cli/commands/db/introspect.test.ts | 2 +- 5 files changed, 50 insertions(+), 28 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 01e79cdd8..95ad881b2 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -156,9 +156,10 @@ protected branches. ### One command at a time -While `migrate` runs, it holds `config/database/.appkit-db.lock`. A second -`appkit db` command in the same checkout fails and names the process that holds -the lock. The lock goes when the command finishes or exits. +While `migrate` or `introspect` runs, it holds +`config/database/.appkit-db.lock`. A second `appkit db` command in the same +checkout fails and names the process that holds the lock. The lock goes when +the command finishes or exits. 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 diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 66ce9bd7d..a790d9395 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -10,14 +10,11 @@ import { markMigrationsApplied, readMigrationDrift, } from "../../migrations/apply"; -import { - journalFile, - migrationsFolder, - readJournal, -} from "../../migrations/paths"; +import { readJournal } from "../../migrations/paths"; import { DEFAULT_SCHEMA_NAME } from "../../schema-builder/define-schema"; import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "../context"; import { notYourBranch, resolveEnvBranch, takesWrites } from "../guard"; +import { type HistoryLock, withHistoryLock } from "../history-lock"; import { DATABASE_TYPES_PATH } from "../migrate"; import { breakingStatements, @@ -142,16 +139,27 @@ function refuseDropsOfUnexpressed( * migration that brings history up to the database, and record it as applied. * 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, - * database.d.ts and the migrations folder. + * database.d.ts 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), + ); +} + +async function introspectHolding( + ctx: DbContext, + lock: HistoryLock, + options: IntrospectOptions, ): Promise { const schemaFile = path.join(ctx.root, DEFAULT_SCHEMA_FILE); // Introspect replaces schema.ts, so the current file (missing, empty or broken) is never read. const schemaName = options.schemaName || DEFAULT_SCHEMA_NAME; - const folder = migrationsFolder(ctx.root); + const { folder } = lock; const migrationOptions = { migrationsFolder: folder, schemaName }; const hasHistory = (readJournal(folder)?.entries.length ?? 0) > 0; @@ -228,7 +236,6 @@ export async function runIntrospect( const previousBackup = readIfExists(backupFile); const previousTypes = readIfExists(typesFile); const backsUp = previous !== null && previous !== rendered.source; - const journalBefore = readIfExists(journalFile(folder)); let migration: GeneratedMigration | null = null; let recorded: string[] = []; try { @@ -247,8 +254,7 @@ export async function runIntrospect( ); } - migration = await generateMigrationFiles({ - folder, + migration = await generateMigrationFiles(lock, { schema, tag: hasHistory ? "introspect" : "baseline", interactive: options.interactive, @@ -278,7 +284,7 @@ export async function runIntrospect( writeOrRemove(schemaFile, previous); if (backsUp) writeOrRemove(backupFile, previousBackup); writeOrRemove(typesFile, previousTypes); - if (migration) discardMigrationFiles(folder, migration, journalBefore); + if (migration) discardMigrationFiles(lock, migration); if (error instanceof IntrospectRefusedError) throw error; throw new Error( `Introspect changed nothing: ${error instanceof Error ? error.message : String(error)}`, diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index dc3fe1bb6..a2834a9dc 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -32,6 +32,7 @@ vi.mock("../../../../type-generator/database", async (importOriginal) => ({ import { loadDefaultDatabaseSchema } from "../../../../plugins/database/load-schema"; import { readJournal } from "../../../migrations/paths"; +import { withHistoryLock } from "../../history-lock"; import { generateMigrationFiles } from "../../migrations"; import { cleanupTempApps, fakeContext, tempApp } from "../../tests/fakes"; import type { ColumnRow, ConstraintRow, TableRow } from "../catalog"; @@ -149,11 +150,12 @@ const authorsOnly = ( /** Commit a migration of the current schema.ts; `applied`: the branch has recorded it. */ async function commitMigration(root: string, applied = true): Promise { - await generateMigrationFiles({ - folder: path.join(root, MIGRATIONS), - schema: await loadDefaultDatabaseSchema(root), - interactive: false, - }); + await withHistoryLock(root, "migrate", async (lock) => + generateMigrationFiles(lock, { + schema: await loadDefaultDatabaseSchema(root), + interactive: false, + }), + ); if (applied) recorded.push(lastWhen(root)); } @@ -473,6 +475,19 @@ describe("runIntrospect", () => { ); }); + 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); diff --git a/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts index f3d52d3c2..0819d24f3 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts @@ -7,6 +7,7 @@ import { afterEach, describe, expect, test } from "vitest"; import { loadDefaultDatabaseSchema } from "../../../../plugins/database/load-schema"; import { drizzleKitImports } from "../../drizzle-exports"; +import { withHistoryLock } from "../../history-lock"; import { generateMigrationFiles } from "../../migrations"; import type { IntrospectedTable } from "../catalog"; import { renderSchemaSource } from "../render"; @@ -123,14 +124,13 @@ describe("introspect round trip", () => { test("the baseline is generated from the empty snapshot: it creates every rendered table", async () => { const { root, schema } = await load(richTables); - const folder = path.join(root, "config/database/migrations"); - - const migration = await generateMigrationFiles({ - folder, - schema, - tag: "baseline", - interactive: false, - }); + 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") ?? ""; diff --git a/packages/shared/src/cli/commands/db/introspect.test.ts b/packages/shared/src/cli/commands/db/introspect.test.ts index 8c9e2e6c1..a0d9711cd 100644 --- a/packages/shared/src/cli/commands/db/introspect.test.ts +++ b/packages/shared/src/cli/commands/db/introspect.test.ts @@ -13,7 +13,7 @@ const tooling = vi.hoisted(() => ({ runIntrospect: vi.fn(), })); -vi.mock("@databricks/appkit/database-tooling", () => tooling); +vi.mock("@databricks/appkit/beta/database-tooling", () => tooling); import { dbCommand } from "./index"; From eb09576c0f2a2dbf567b581b881867b86d07462d Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:25:47 +0000 Subject: [PATCH 027/317] fix(appkit): keep schema.ts column privacy when introspect rewrites it Introspect replaced schema.ts without reading it, so every .private() column came back public and every catalog foreign key became an API include. It now loads the schema.ts it replaces first. A declared column keeps its privacy, and a column the file does not declare is written .private() and named in a warning. A foreign key the file does not declare refuses the run before anything is written, and so does a schema.ts that does not load. Without a schema.ts the first render is unchanged. Signed-off-by: ditadi --- .../src/database/tooling/introspect/index.ts | 39 +++- .../src/database/tooling/introspect/render.ts | 65 +++++- .../introspect/tests/introspect.test.ts | 108 +++++++--- .../tooling/introspect/tests/render.test.ts | 190 ++++++++++++++++-- .../introspect/tests/roundtrip.test.ts | 96 ++++++++- .../shared/src/cli/commands/db/introspect.ts | 4 + 6 files changed, 437 insertions(+), 65 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index a790d9395..388dd3da3 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -12,6 +12,7 @@ import { } 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 { notYourBranch, resolveEnvBranch, takesWrites } from "../guard"; import { type HistoryLock, withHistoryLock } from "../history-lock"; @@ -34,7 +35,7 @@ import { export interface IntrospectOptions { /** false: an ambiguous rename against existing history throws instead of prompting. */ readonly interactive: boolean; - /** Schema to read; defaults to DEFAULT_SCHEMA_NAME. The current schema.ts is never read. */ + /** Schema to read; defaults to DEFAULT_SCHEMA_NAME. */ readonly schemaName?: string; /** Module the written schema.ts imports the builder from. Default "@databricks/appkit/beta". */ readonly importSource?: string; @@ -61,8 +62,8 @@ export interface IntrospectReport { /** Introspect would record history the branch or the deployed app contradicts. */ export class IntrospectRefusedError extends Error { - constructor(message: string) { - super(message); + constructor(message: string, options?: ErrorOptions) { + super(message, options); this.name = "IntrospectRefusedError"; } } @@ -133,12 +134,31 @@ function refuseDropsOfUnexpressed( ); } +/** + * 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 loadDefaultDatabaseSchema(root, { 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, or move it out of config/database to start again from the catalog.`, + { cause: error }, + ); + } +} + /** * `appkit db introspect`: read the `.env` branch's app schema from pg_catalog, * 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. - * 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, + * Columns the previous schema.ts declares keep their privacy; new ones are + * written private, and a foreign key it does not declare is refused. 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, * database.d.ts and the migrations folder. One command at a time owns the * checkout's history. */ @@ -157,7 +177,7 @@ async function introspectHolding( options: IntrospectOptions, ): Promise { const schemaFile = path.join(ctx.root, DEFAULT_SCHEMA_FILE); - // Introspect replaces schema.ts, so the current file (missing, empty or broken) is never read. + const previousSchema = await readPreviousSchema(ctx.root); const schemaName = options.schemaName || DEFAULT_SCHEMA_NAME; const { folder } = lock; const migrationOptions = { migrationsFolder: folder, schemaName }; @@ -215,6 +235,7 @@ async function introspectHolding( 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. @@ -229,6 +250,12 @@ async function introspectHolding( `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.`, ); } + if (rendered.newRelations.length > 0) { + const one = rendered.newRelations.length === 1; + throw new IntrospectRefusedError( + `Refusing to replace ${DEFAULT_SCHEMA_FILE}: the branch has ${one ? "a foreign key" : "foreign keys"} it does not declare (${rendered.newRelations.join(", ")}). A foreign key lets the API include the related rows. Declare ${one ? "it" : "them"} with fk() in ${DEFAULT_SCHEMA_FILE}, then rerun, or move the file out of config/database to start again from the catalog.`, + ); + } const backupFile = `${schemaFile}.bak`; const typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index b8378f5e5..3b75fa4b4 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -3,6 +3,7 @@ import { isReservedColumnName, isReservedTableName, } from "../../schema-builder/define-schema"; +import type { AppKitTable, Schema } from "../../schema-builder/types"; import type { IntrospectedColumn, IntrospectedForeignKey, @@ -42,11 +43,22 @@ interface SchemaSource { readonly warnings: readonly string[]; /** What schema.ts declares differently from the database, which keeps it as it is. */ readonly approximated: readonly string[]; + /** + * Foreign keys schema.ts gets that `previous` does not declare, as + * "app.notes.author_id → app.users.id". Each one is an API include. + */ + readonly newRelations: 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 privacy; every + * other column renders `.private()`. Null renders nothing private. + */ + readonly previous: Schema | null; } /** Storage as the builder sees it; id/bigid are server-generated integer/bigint keys. */ @@ -303,12 +315,14 @@ function mirrored(target: BaseType): string { * Render pg_catalog tables as a `defineSchema` source the builder accepts. * What the builder cannot express is left out with an `// appkit: skipped …` * comment; what it declares differently (a timestamp without its precision, - * say) is listed in `approximated`. + * say) is listed in `approximated`. A refresh never widens the API of + * `previous`: what it does not declare renders private, and the foreign keys + * it does not declare are listed in `newRelations`. */ export function renderSchemaSource( tables: readonly IntrospectedTable[], schemaName: string, - options: RenderOptions = {}, + options: RenderOptions, ): SchemaSource { const skipped: Skip[] = []; const unexpressed: Unexpressed[] = []; @@ -317,6 +331,9 @@ export function renderSchemaSource( /** Constraints whose database name is not the one migrations use: "db (migrations)". */ const renamed: string[] = []; const tableComments: string[] = []; + /** Columns rendered private because `previous` does not declare them. */ + const privatized: string[] = []; + const newRelations: string[] = []; const qualified = (table: string, column?: string) => `${schemaName}.${table}${column ? `.${column}` : ""}`; const skipTable = (table: string, reason: string) => { @@ -325,6 +342,25 @@ export function renderSchemaSource( unexpressed.push({ kind: "table", name: table, reason }); tableComments.push(skipComment(skip)); }; + const { previous } = options; + // A declaration of another schema declares nothing in this one. + const previousTables = new Map( + previous?.$schemaName === schemaName + ? Object.values(previous.$tables).map((table): [string, AppKitTable] => [ + table.$name, + table, + ]) + : [], + ); + const isPrivate = (table: string, column: string): boolean => { + if (!previous) return false; + const declared = Object.values( + previousTables.get(table)?.$columns ?? {}, + ).find((meta) => meta.columnName === column); + if (declared) return declared.isPrivate; + privatized.push(qualified(table, column)); + return true; + }; // 1. Tables the builder can key: one primary-key column, a usable name. const names = new Set(tables.map((table) => table.name)); @@ -701,6 +737,21 @@ export function renderSchemaSource( const out = edges.get(plan.table.name) ?? new Set(); out.add(foreignKey.table); edges.set(plan.table.name, out); + // A toOne edge comes with its toMany reverse, so checking it covers both. + const declared = previousTables + .get(plan.table.name) + ?.$relations.some( + (relation) => + relation.cardinality === "toOne" && + relation.localColumn === sourceColumn.column.name && + relation.targetTable === foreignKey.table && + relation.targetColumn === targetColumn.column.name, + ); + if (previous && !declared) { + newRelations.push( + `${qualified(plan.table.name, sourceColumn.column.name)} → ${qualified(foreignKey.table, targetColumn.column.name)}`, + ); + } } } @@ -794,6 +845,7 @@ export function renderSchemaSource( unexpressed, warnings: warnings.map(shown), approximated: approximated.map(shown), + newRelations: newRelations.map(shown), }); if (ordered.length === 0) { lines.push(...tableComments); @@ -828,10 +880,19 @@ export function renderSchemaSource( 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(" });", ""); } + if (privatized.length > 0) { + const one = privatized.length === 1; + warnings.push( + `${list(privatized)} ${one ? "is" : "are"} new to schema.ts, so ${one ? "it is" : "they are"} private: the API does not return or accept ${one ? "it" : "them"} until you remove .private().`, + ); + } for (const comment of tableComments) body.push(` ${comment}`); if (tableComments.length > 0) body.push(""); const entries = ordered.map((plan) => diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index a2834a9dc..379f9639d 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -55,6 +55,18 @@ export const schema = defineSchema(({ table }) => ({ })); `; +/** 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 onDevBranch = { branch: { name: DEV }, kind: "dev" }; const onProduction = { branch: { name: PRODUCTION, status: { default: true } }, @@ -188,19 +200,27 @@ 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]: previousSchema }); + 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( - previousSchema, + 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 privacy; the rest is private. + expect(written).toContain( + "email: varchar(255).notNull().unique().private(),", + ); + expect(written).toContain( + "created_at: timestamp({ withTimezone: true }).notNull().defaultNow().private(),", + ); + expect(written).toContain("id: id(),"); expect(report).toMatchObject({ branch: DEV, schemaName: "app", @@ -219,6 +239,7 @@ describe("runIntrospect", () => { 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\)\./, ), + "app.authors.created_at, app.posts.status are new to schema.ts, so they are private: the API does not return or accept them until you remove .private().", ]); expect(report.approximated).toEqual([ "app.authors.id: a serial key is declared as id(), an identity generated BY DEFAULT", @@ -264,14 +285,14 @@ describe("runIntrospect", () => { ); test("with history: writes and records the next NNNN_introspect", async () => { - const root = tempApp({ [SCHEMA]: previousSchema }); + 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( - 'CREATE TABLE "app"."posts"', + 'ALTER TABLE "app"."posts" ADD COLUMN "status"', ); expect(report.recorded).toEqual(["0001_introspect"]); expect(markMigrationsApplied).toHaveBeenCalledWith( @@ -282,7 +303,7 @@ describe("runIntrospect", () => { }); test("a second run with no catalog change writes no migration and records nothing", async () => { - const root = tempApp({ [SCHEMA]: previousSchema }); + const root = tempApp({ [SCHEMA]: declaredSchema }); await introspect(root); markMigrationsApplied.mockClear(); @@ -294,7 +315,7 @@ describe("runIntrospect", () => { }); test("a migration an interrupted run wrote but did not record is recorded when the branch matches it", async () => { - const root = tempApp({ [SCHEMA]: previousSchema }); + const root = tempApp({ [SCHEMA]: declaredSchema }); await introspect(root); // The run stopped after writing 0000_baseline, before recording it. recorded = []; @@ -312,7 +333,7 @@ describe("runIntrospect", () => { }); test("an unrecorded introspect migration the branch no longer matches is refused, and nothing changes", async () => { - const root = tempApp({ [SCHEMA]: previousSchema }); + const root = tempApp({ [SCHEMA]: declaredSchema }); await introspect(root); recorded = []; catalog = authorsOnly(); @@ -371,27 +392,21 @@ describe("runIntrospect", () => { `import { defineSchema } from ${JSON.stringify(BUILDER)};\nexport const schema = defineSchema(({ table }) => ({ x: table("x", { id: id() }) }));\n`, ], ])( - "a schema.ts with %s is never read: it goes to .bak and is replaced from the app schema", + "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 report = await introspect(root); + const error = await refusal(root); - expect(catalog.calls.every((call) => call.values[0] === "app")).toBe( - true, - ); - expect(report).toMatchObject({ - schemaName: "app", - tables: ["authors", "posts"], - backupFile: path.join(root, `${SCHEMA}.bak`), - migration: { tag: "0000_baseline" }, - }); - expect(fs.readFileSync(path.join(root, `${SCHEMA}.bak`), "utf-8")).toBe( - broken, - ); - expect(fs.readFileSync(path.join(root, SCHEMA), "utf-8")).toMatch( - /from schema "app"\.[^]*export const schema = defineSchema\(\(\{ table[^}]*\}\) => \{/, + 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, or move it out of config/database to start again from the catalog.", ); + expect(resolveEnvBranch).not.toHaveBeenCalled(); + expect(catalog.calls).toEqual([]); + expect(tree(root)).toEqual(before); + expect(markMigrationsApplied).not.toHaveBeenCalled(); }, ); @@ -411,15 +426,48 @@ describe("runIntrospect", () => { expect((await loadDefaultDatabaseSchema(root)).$schemaName).toBe("public"); }); - test("the schema schema.ts declares does not change which schema is read", async () => { + test("the schema schema.ts declares does not change which schema is read, and declares nothing in it", async () => { const root = tempApp({ [SCHEMA]: previousSchema.replace("}));", '}), { schemaName: "sales" });'), }); + const before = tree(root); - const report = await introspect(root); + const error = await refusal(root); expect(catalog.calls.every((call) => call.values[0] === "app")).toBe(true); - expect(report.schemaName).toBe("app"); + expect(error).toBeInstanceOf(IntrospectRefusedError); + expect(error.message).toMatch( + /^Refusing to replace config\/database\/schema\.ts: the branch has a foreign key it does not declare \(app\.posts\.author_id → app\.authors\.id\)\./, + ); + expect(tree(root)).toEqual(before); + }); + + test("a foreign key the replaced schema.ts does not declare is refused, and nothing changes", async () => { + const undeclared = `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() }), +})); +`; + const root = tempApp({ + [SCHEMA]: undeclared, + [`${SCHEMA}.bak`]: "// an older backup\n", + [TYPES]: "// older types\n", + }); + await commitMigration(root); + const before = tree(root); + + const error = await refusal(root); + + expect(error).toBeInstanceOf(IntrospectRefusedError); + expect(error.message).toBe( + "Refusing to replace config/database/schema.ts: the branch has a foreign key it does not declare (app.posts.author_id → app.authors.id). A foreign key lets the API include the related rows. Declare it with fk() in config/database/schema.ts, then rerun, or move the file out of config/database to start again from the catalog.", + ); + expect(tree(root)).toEqual(before); + expect(fs.readFileSync(path.join(root, TYPES), "utf-8")).toBe( + "// older types\n", + ); + expect(markMigrationsApplied).not.toHaveBeenCalled(); }); test("an empty schema next to an existing schema.ts refuses before writing anything", async () => { @@ -683,7 +731,7 @@ describe("runIntrospect", () => { "when %s fails, schema.ts, its backup, database.d.ts and the migrations are put back, so a rerun records", async (_label, failOnce, message) => { const root = tempApp({ - [SCHEMA]: previousSchema, + [SCHEMA]: declaredSchema, [`${SCHEMA}.bak`]: "// an older backup\n", }); const before = tree(root); @@ -706,14 +754,14 @@ describe("runIntrospect", () => { ); test("a second run with the same catalog keeps the original .bak", async () => { - const root = tempApp({ [SCHEMA]: previousSchema }); + 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( - previousSchema, + declaredSchema, ); }); @@ -737,7 +785,7 @@ describe("runIntrospect", () => { }); 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]: previousSchema }); + const root = tempApp({ [SCHEMA]: declaredSchema }); const before = tree(root); const error = await rejection( diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index 1211a18a9..2179b937c 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -3,6 +3,13 @@ import path from "node:path"; import { describe, expect, test } from "vitest"; +import { + defineSchema, + fk as references, + id, + integer, + text, +} from "../../../schema-builder"; import type { IntrospectedForeignKey, IntrospectedTable } from "../catalog"; import { renderSchemaSource } from "../render"; import { col, richTables, tableOf, uniqueKey } from "./fixture"; @@ -48,9 +55,15 @@ const keyed = ( 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 = renderSchemaSource(richTables, "app"); + const out = firstRender(richTables, "app"); expect(out.source).toBe(golden("rich.schema.ts.txt")); expect(out.skipped).toEqual( @@ -87,7 +100,7 @@ describe("renderSchemaSource", () => { }); test("a skipped NOT NULL column without a default is a loud warning", () => { - const { warnings } = renderSchemaSource(richTables, "app"); + 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 the API will fail until it gets a default, becomes nullable, or is dropped.', ); @@ -108,12 +121,12 @@ describe("renderSchemaSource", () => { ])( "no tables in %s renders an empty schema, naming the schema only when it is not app", (schemaName, expected) => { - expect(body(renderSchemaSource([], schemaName).source)).toBe(expected); + expect(body(firstRender([], schemaName).source)).toBe(expected); }, ); test("tables in a schema other than app pass it to defineSchema", () => { - expect(body(renderSchemaSource([keyed("notes")], "public").source)).toBe( + expect(body(firstRender([keyed("notes")], "public").source)).toBe( [ "export const schema = defineSchema(", " ({ table }) => {", @@ -131,7 +144,7 @@ describe("renderSchemaSource", () => { }); test("declares FK targets first, whatever the catalog order", () => { - const { source } = renderSchemaSource( + const { source } = firstRender( [ keyed("c", [col("b_id", "integer")], [fk("b_id", "b")]), keyed("b", [col("a_id", "integer")], [fk("a_id", "a")]), @@ -245,7 +258,7 @@ describe("renderSchemaSource", () => { ], ]; for (const [tables, reason] of cases) { - const out = renderSchemaSource(tables, "app"); + const out = firstRender(tables, "app"); expect(out.source, reason).toContain(reason); const fkSkips = out.skipped.filter((skip) => skip.reason.startsWith("foreign key"), @@ -259,7 +272,7 @@ describe("renderSchemaSource", () => { }); test("an FK keeps NOT NULL, unique, a default and its actions", () => { - const { source } = renderSchemaSource( + const { source } = firstRender( [ keyed( "t", @@ -277,7 +290,7 @@ describe("renderSchemaSource", () => { }); test("a table whose primary key cannot be expressed is skipped whole", () => { - const out = renderSchemaSource( + const out = firstRender( [ tableOf({ name: "t", @@ -304,7 +317,7 @@ describe("renderSchemaSource", () => { }); test("names AppKit reserves are skipped; unusual names are quoted or renamed", () => { - const out = renderSchemaSource( + const out = firstRender( [ keyed("sql"), keyed("my-table", [ @@ -335,7 +348,7 @@ describe("renderSchemaSource", () => { }); test("unsupported defaults are dropped with a comment; nextval on a key becomes id()", () => { - const { source, skipped } = renderSchemaSource( + const { source, skipped } = firstRender( [ tableOf({ name: "t", @@ -366,7 +379,7 @@ describe("renderSchemaSource", () => { 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 } = renderSchemaSource( + const { source, skipped, warnings } = firstRender( [ keyed("t", [ col(evil, "numeric", { notNull: true }), @@ -393,7 +406,7 @@ describe("renderSchemaSource", () => { }); test("the schema name in the header comment is escaped too", () => { - const { source } = renderSchemaSource([keyed("t")], "a\nb"); + 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,', ); @@ -401,7 +414,7 @@ describe("renderSchemaSource", () => { }); test("returns the tables it wrote", () => { - expect(renderSchemaSource(richTables, "app").tables).toEqual([ + expect(firstRender(richTables, "app").tables).toEqual([ "authors", "posts", "default", @@ -409,7 +422,7 @@ describe("renderSchemaSource", () => { }); test("what schema.ts declares differently from the database is listed as approximated", () => { - const { approximated } = renderSchemaSource( + const { approximated } = firstRender( [ tableOf({ name: "a", @@ -450,14 +463,14 @@ describe("renderSchemaSource", () => { }); test("constraint names that differ from the ones migrations use are one warning", () => { - const { warnings } = renderSchemaSource(richTables, "app"); + 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 } = renderSchemaSource( + const { warnings } = firstRender( [ tableOf({ ...keyed("u", [col("email", "text")]), @@ -476,7 +489,7 @@ describe("renderSchemaSource", () => { test("migrations' constraint names are cut at 63 bytes, as Postgres cuts them", () => { const column = "ç".repeat(40); - const { warnings } = renderSchemaSource( + const { warnings } = firstRender( [ tableOf({ ...keyed("t", [col(column, "text")]), @@ -491,14 +504,14 @@ describe("renderSchemaSource", () => { test("bidi and line-separator characters are escaped in string literals", () => { const name = "t\u202e\u2066\u2028x"; - const { source } = renderSchemaSource([keyed(name)], "app"); + const { source } = firstRender([keyed(name)], "app"); expect(source).not.toMatch(/[\u2028\u202e\u2066]/); expect(source).toContain('table("t\\u202e\\u2066\\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 } = renderSchemaSource( + const { unexpressed } = firstRender( [ keyed( "t", @@ -560,7 +573,7 @@ describe("renderSchemaSource", () => { }); test("a uuid FK keeps the key and skips gen_random_uuid(), which fk() does not take", () => { - const { source, skipped, warnings } = renderSchemaSource( + const { source, skipped, warnings } = firstRender( [ tableOf({ name: "u", @@ -601,7 +614,7 @@ describe("renderSchemaSource", () => { }); test("SET DEFAULT needs a default fk() can take", () => { - const { skipped } = renderSchemaSource( + const { skipped } = firstRender( [ tableOf({ name: "u", @@ -621,3 +634,138 @@ describe("renderSchemaSource", () => { ]); }); }); + +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, + ); + + test("a declared column keeps its privacy; a new column and every column of a new table render private", () => { + 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().private(),", + " });", + "", + ' const tags = table("tags", {', + " id: id().private(),", + " label: text().private(),", + " });", + "", + " return { boards, notes, tags };", + "});", + "", + ].join("\n"), + ); + expect(out.warnings).toContain( + "app.notes.summary, app.tags.id, app.tags.label are new to schema.ts, so they are private: the API does not return or accept them until you remove .private().", + ); + expect(out.newRelations).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(),"); + expect(kept.newRelations).toEqual([]); + + const dropped = renderSchemaSource([boards, notes([], [])], "app", { + previous, + }); + expect(dropped.source).toContain("board_id: integer().notNull(),"); + expect(dropped.newRelations).toEqual([]); + }); + + test("a foreign key it does not declare is listed, on an existing table or a new 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(), + keyed("tags", [col("note_id", "integer")], [fk("note_id", "notes")]), + ], + "app", + { previous: plain }, + ); + + expect(out.newRelations).toEqual([ + "app.notes.board_id → app.boards.id", + "app.tags.note_id → app.notes.id", + ]); + }); + + test("a declaration of another schema keeps nothing: every column renders private and every foreign key is new", () => { + const out = renderSchemaSource( + [ + keyed("boards", [col("title", "text", { notNull: true })]), + notes([], [fk("board_id", "boards", { schema: "sales" })]), + ], + "sales", + { previous }, + ); + + expect(out.warnings).toContain( + "sales.boards.id, sales.boards.title, sales.notes.id, sales.notes.board_id, sales.notes.author_email, sales.notes.body are new to schema.ts, so they are private: the API does not return or accept them until you remove .private().", + ); + expect(out.newRelations).toEqual([ + "sales.notes.board_id → sales.boards.id", + ]); + }); + + test("without a schema.ts to replace, nothing is private and no foreign key is new", () => { + const out = firstRender([boards, notes()]); + + expect(out.source).not.toContain(".private()"); + expect(out.newRelations).toEqual([]); + }); +}); diff --git a/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts index 0819d24f3..bfdcd524f 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts @@ -5,7 +5,9 @@ import path from "node:path"; import { getTableConfig, type PgTable } from "drizzle-orm/pg-core"; import { afterEach, describe, expect, test } from "vitest"; +import { columnHttpCapabilities } from "../../../../plugins/database/crud/capabilities"; 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"; @@ -26,19 +28,38 @@ afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); -/** Write the rendered source as an app's schema.ts and load it the way the plugin does. */ -async function load(tables: IntrospectedTable[]) { +/** 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, - renderSchemaSource(tables, "app", { importSource: BUILDER }).source, - ); + 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, + ); + +/** What the generated API lets a caller do with a schema: per column, and per include. */ +const granted = (schema: Schema) => + Object.values(schema.$tables).flatMap((table) => [ + ...Object.values(table.$columns).flatMap((meta) => + Object.entries(columnHttpCapabilities(meta)) + .filter(([, allowed]) => allowed) + .map( + ([capability]) => `${table.$name}.${meta.columnName} ${capability}`, + ), + ), + ...table.$relations.map( + (relation) => `${table.$name} includes ${relation.name}`, + ), + ]); + interface KitColumn { name: string; type: string; @@ -365,4 +386,67 @@ describe("introspect round trip", () => { ), ).toEqual([[quote]]); }); + + test("a refresh over the schema.ts it replaces keeps exactly what the API could read, write or include", async () => { + const before = + await loadSource(`import { defineSchema, fk, id, text } from ${JSON.stringify(BUILDER)}; +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(), + }); + 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 })], + }), + tableOf({ + name: "notes", + primaryKey: ["id"], + foreignKeys: [ + foreignKey({ + name: "notes_board_id_boards_id_fk", + columns: ["board_id"], + schema: "app", + table: "boards", + refColumns: ["id"], + onDelete: "no action", + onUpdate: "no action", + }), + ], + columns: [ + key, + col("board_id", "integer", { notNull: true }), + col("author_email", "text"), + col("body", "text", { notNull: true }), + col("summary", "text"), + ], + }), + tableOf({ + name: "tags", + primaryKey: ["id"], + columns: [key, col("label", "text")], + }), + ]; + + const rendered = renderSchemaSource(catalog, "app", { + importSource: BUILDER, + previous: before.schema, + }); + const after = await loadSource(rendered.source); + + expect(rendered.newRelations).toEqual([]); + // The new column and the new table arrive private, so they grant nothing. + expect(after.schema.$tables.notes?.$columns.summary?.isPrivate).toBe(true); + expect(after.schema.$tables.tags?.$columns.label?.isPrivate).toBe(true); + expect(granted(after.schema)).toEqual(granted(before.schema)); + }); }); diff --git a/packages/shared/src/cli/commands/db/introspect.ts b/packages/shared/src/cli/commands/db/introspect.ts index 1d2b37031..9f3dae65e 100644 --- a/packages/shared/src/cli/commands/db/introspect.ts +++ b/packages/shared/src/cli/commands/db/introspect.ts @@ -28,6 +28,10 @@ The previous schema.ts is kept as schema.ts.bak. What the schema builder cannot express (composite keys, unsupported types or defaults, some foreign keys) is left out with an "// appkit: skipped …" comment. +Columns the previous schema.ts declares keep their .private(); columns it does +not declare are written private. A foreign key it does not declare, or a +schema.ts that does not load, stops introspect before it writes anything. + Without migration history this writes 0000_baseline; with history, the next NNNN_introspect, once the branch has applied every committed migration. The migration is recorded as applied, so introspect runs only on your dev or session From ab2e50f4734b8896606f908beabb80a02be45c90 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:33:52 +0000 Subject: [PATCH 028/317] fix(appkit): check init's branch against the whole deploy boundary init still checked its planned branch against the readDeployBranches list that the deploy boundary replaced. It now asks deployRefusal, like every other guard, so a binding the checkout's files cannot resolve refuses init before any API call or .env write. readDeployTarget reads the default target from the same bundle model: its first resolved app binding, else its postgres_branch and postgres_database variables. The shared CLI test mocks the beta tooling path. Signed-off-by: ditadi --- packages/appkit/src/database/tooling/guard.ts | 2 +- packages/appkit/src/database/tooling/init.ts | 18 ++--- .../appkit/src/database/tooling/targets.ts | 65 +++++++++++-------- .../src/database/tooling/tests/init.test.ts | 25 ++++++- .../cli/commands/db/init-clean-seed.test.ts | 2 +- 5 files changed, 75 insertions(+), 37 deletions(-) diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts index ae51a101d..d6a444b10 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -29,7 +29,7 @@ interface Classification { * 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. */ -function deployRefusal( +export function deployRefusal( boundary: DeployBoundary, branch: string, ): string | null { diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 6a5118980..68899b336 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -13,7 +13,7 @@ import { runCommand, } from "./drizzle-kit-install"; import { refuseSymlink, updateEnvFile } from "./env-file"; -import { classifyBranch, takesWrites } from "./guard"; +import { classifyBranch, deployRefusal, takesWrites } from "./guard"; import { handOffAppSchema } from "./hand-off"; import { currentIdentity, type Identity } from "./identity"; import { type IntrospectReport, runIntrospect } from "./introspect"; @@ -43,10 +43,11 @@ import { } from "./naming"; import { type BranchMode, + type DeployBoundary, type DeployTarget, type LocalTarget, parseResourceName, - readDeployBranches, + readDeployBoundary, readDeployTarget, readLocalTarget, resourceId, @@ -167,7 +168,7 @@ interface BranchRequest { readonly session: string | null; /** The API's duration ("3600s"), and how the developer wrote it. */ readonly ttl: { readonly api: string; readonly label: string }; - readonly deployBranches: readonly string[]; + readonly boundary: DeployBoundary; readonly envFile: string; readonly onStep: (message: string) => void; } @@ -210,7 +211,7 @@ async function findOrCreateBranch( ctx: DbContext, request: BranchRequest, ): Promise { - const { project, mode, identity, deployBranches, onStep } = request; + const { project, mode, identity, boundary, onStep } = request; const api = ctx.api(); let session = mode === "session" ? (request.session ?? newSessionId()) : null; let rotated = false; @@ -226,7 +227,7 @@ async function findOrCreateBranch( branch, userName: identity.userName, sessionId: session, - deployBranches, + boundary, }); if (!takesWrites(verdict.kind)) { throw new Error( @@ -253,9 +254,10 @@ async function findOrCreateBranch( for (;;) { const name = branchName(); - if (deployBranches.includes(name)) { + const refusal = deployRefusal(boundary, name); + if (refusal) { throw new Error( - `Refusing to set up ${resourceId(name)}: it is a branch databricks.yml deploys to, and the deployed app migrates it itself.`, + `Refusing to set up ${resourceId(name)}: ${refusal}. \`appkit db init\` only sets up your dev branch or this checkout's session branch.`, ); } const existing = await api.getBranch(name); @@ -475,7 +477,7 @@ export async function runInit( identity, session: local.session, ttl, - deployBranches: readDeployBranches(ctx.root), + boundary: readDeployBoundary(ctx.root), envFile, onStep, }); diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 51df757b0..1e751b5e8 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -126,11 +126,15 @@ interface TargetBindings { readonly apps: readonly BundleApp[]; /** The target's postgres_branch variable; null when the bundle declares none. */ readonly postgresBranch: BundleValue | null; + /** The target's postgres_database variable; null when the bundle declares none. */ + readonly postgresDatabase: BundleValue | null; } /** One target of databricks.yml, with what the files alone can resolve resolved. */ interface BundleTarget extends TargetBindings { readonly name: string; + /** `default: true`, or the one target of a bundle that declares none. */ + readonly isDefault: boolean; /** * The same bindings with this checkout's variable-overrides.json applied, * which a deploy from here uses ahead of the target's own values; null @@ -351,26 +355,28 @@ function bundleApps( }); } -/** Default target's postgres_branch / postgres_database variables; null without databricks.yml or binding. */ +/** + * The branch and database the default target deploys to: its first app + * binding the files resolve, else its postgres_branch and postgres_database + * variables. null without databricks.yml or a branch the files resolve. + */ export function readDeployTarget(root: string): DeployTarget | null { - const bundle = readBundle(root); - if (!bundle) return null; - const targets = record(bundle.targets) ?? {}; + const targets = readBundle(root)?.targets ?? []; const target = - Object.values(targets) - .map(record) - .find((candidate) => candidate?.default === true) ?? - record(targets.default); - - const branch = parseResourceName( - variableOf(bundle, target, "postgres_branch") ?? undefined, - )?.branch; + targets.find((candidate) => candidate.isDefault) ?? + targets.find((candidate) => candidate.name === "default"); + if (!target) return null; + const resolved = (value: BundleValue | null) => + value?.kind === "resolved" ? value.name : null; + const binding = target.apps + .flatMap((app) => app.postgres) + .find((candidate) => candidate.branch.kind === "resolved"); + const branch = resolved(binding?.branch ?? target.postgresBranch); if (!branch) return null; - const database = - parseResourceName( - variableOf(bundle, target, "postgres_database") ?? undefined, - )?.database ?? null; - return { branch, database }; + return { + branch, + database: resolved(binding ? binding.database : target.postgresDatabase), + }; } /** @@ -407,27 +413,34 @@ function readBundle(root: string): Bundle | null { record(record(target?.resources)?.apps) ?? {}, ), ); - const declaresBranch = - "postgres_branch" in (record(bundle.variables) ?? {}) || - "postgres_branch" in (record(target?.variables) ?? {}); + const declares = (variable: string) => + variable in (record(bundle.variables) ?? {}) || + variable in (record(target?.variables) ?? {}); const bindings = ( overrides: Record | null, ): TargetBindings => { const resolve = resolverFor(bundle, target, name, overrides); - return { - apps: bundleApps(apps ?? {}, resolve), - postgresBranch: declaresBranch + const variable = ( + variableName: string, + kind: "branch" | "database", + ): BundleValue | null => + declares(variableName) ? bundleValue( - variableOf(bundle, target, "postgres_branch", overrides), + variableOf(bundle, target, variableName, overrides), resolve, - "branch", + kind, ) - : null, + : null; + return { + apps: bundleApps(apps ?? {}, resolve), + postgresBranch: variable("postgres_branch", "branch"), + postgresDatabase: variable("postgres_database", "database"), }; }; const overrides = readVariableOverrides(root, name); return { name, + isDefault: target?.default === true, ...bindings(null), overridden: overrides ? { file: overrides.file, ...bindings(overrides.values) } diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 0f0bb38ba..f5a26bf55 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -527,7 +527,30 @@ describe("runInit — branches it never sets up", () => { const before = fs.readFileSync(path.join(ctx.root, ".env"), "utf-8"); await expect(init(ctx)).rejects.toThrow( - `Refusing to set up ${devBranchId(USER)}: it is a branch databricks.yml deploys to, and the deployed app migrates it itself.`, + `Refusing to set up ${devBranchId(USER)}: it is a branch databricks.yml deploys to. \`appkit db init\` only sets up your dev branch or this checkout's session branch.`, + ); + expect(lakebase.calls).toEqual([]); + expect(fs.readFileSync(path.join(ctx.root, ".env"), "utf-8")).toBe(before); + }); + + test("a databricks.yml binding the files cannot resolve refuses init before any API call or .env write", async () => { + const lakebase = project(); + const ctx = appOn( + lakebase, + {}, + { + files: { + "databricks.yml": databricksYml( + `\${resources.postgres_branches.main.name}`, + `${PRODUCTION}/databases/databricks-postgres`, + ), + }, + }, + ); + const before = fs.readFileSync(path.join(ctx.root, ".env"), "utf-8"); + + await expect(init(ctx)).rejects.toThrow( + `Refusing to set up ${devBranchId(USER)}: databricks.yml may deploy to it: the files do not resolve resources.apps.app.resources[0].postgres.branch in target default`, ); expect(lakebase.calls).toEqual([]); expect(fs.readFileSync(path.join(ctx.root, ".env"), "utf-8")).toBe(before); diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index 90dcdf53f..37907e275 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -21,7 +21,7 @@ const prompts = vi.hoisted(() => ({ isCancel: vi.fn((value: unknown) => typeof value === "symbol"), })); -vi.mock("@databricks/appkit/database-tooling", () => tooling); +vi.mock("@databricks/appkit/beta/database-tooling", () => tooling); vi.mock("@clack/prompts", () => prompts); import { dbCommand } from "./index"; From c10ef582d790ca7822111d0a214c3f122019ef9c Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:42:25 +0000 Subject: [PATCH 029/317] fix(appkit): let a declared foreign key keep its relation in introspect With two catalog foreign keys to one table, the one first in constraint name order took the relation, even when schema.ts declared the other. The refusal then asked for a declaration the builder rejects as ambiguous. Foreign keys schema.ts declares now go first. Signed-off-by: ditadi --- .../src/database/tooling/introspect/render.ts | 36 ++++++++++++------- .../tooling/introspect/tests/render.test.ts | 32 +++++++++++++++++ 2 files changed, 56 insertions(+), 12 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index 3b75fa4b4..9b2bfc9bf 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -352,6 +352,22 @@ export function renderSchemaSource( ]) : [], ); + /** 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); const isPrivate = (table: string, column: string): boolean => { if (!previous) return false; const declared = Object.values( @@ -635,7 +651,13 @@ export function renderSchemaSource( for (const plan of plans.values()) { const targets = new Set(); - for (const foreignKey of plan.table.foreignKeys) { + // 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], ); @@ -737,17 +759,7 @@ export function renderSchemaSource( const out = edges.get(plan.table.name) ?? new Set(); out.add(foreignKey.table); edges.set(plan.table.name, out); - // A toOne edge comes with its toMany reverse, so checking it covers both. - const declared = previousTables - .get(plan.table.name) - ?.$relations.some( - (relation) => - relation.cardinality === "toOne" && - relation.localColumn === sourceColumn.column.name && - relation.targetTable === foreignKey.table && - relation.targetColumn === targetColumn.column.name, - ); - if (previous && !declared) { + if (previous && !declaresForeignKey(plan.table.name, foreignKey)) { newRelations.push( `${qualified(plan.table.name, sourceColumn.column.name)} → ${qualified(foreignKey.table, targetColumn.column.name)}`, ); diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index 2179b937c..811d9ded5 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -744,6 +744,38 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { ]); }); + 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', + ); + expect(out.newRelations).toEqual([]); + }); + test("a declaration of another schema keeps nothing: every column renders private and every foreign key is new", () => { const out = renderSchemaSource( [ From 38eb6a12fe198c31d06f45404f7bcdb54b73f36d Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:43:53 +0000 Subject: [PATCH 030/317] fix(appkit): end introspect refusals with the fix and rerun step The refusals told developers to move schema.ts out of config/database, which discards its .private() declarations and makes the next introspect write every column public. A schema.ts that does not load now says to fix it and rerun. An undeclared foreign key says to declare it with fk() in schema.ts, and names the tables schema.ts does not declare yet. Signed-off-by: ditadi --- .../src/database/tooling/introspect/index.ts | 16 +++++- .../src/database/tooling/introspect/render.ts | 30 ++++++---- .../introspect/tests/introspect.test.ts | 57 ++++++++++++------- .../tooling/introspect/tests/render.test.ts | 24 ++++++-- 4 files changed, 88 insertions(+), 39 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 388dd3da3..c3c7ea0ad 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -145,7 +145,7 @@ async function readPreviousSchema(root: string): Promise { return await loadDefaultDatabaseSchema(root, { 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, or move it out of config/database to start again from the catalog.`, + `Refusing to introspect: ${DEFAULT_SCHEMA_FILE} does not load, so introspect cannot keep the columns it marks private. Fix it, then rerun.`, { cause: error }, ); } @@ -252,8 +252,20 @@ async function introspectHolding( } if (rendered.newRelations.length > 0) { const one = rendered.newRelations.length === 1; + const edges = rendered.newRelations.map((relation) => relation.edge); + const tables = [ + ...new Set( + rendered.newRelations.flatMap( + (relation) => relation.undeclaredTables, + ), + ), + ]; + const declareTables = + tables.length === 0 + ? "" + : ` and declare ${tables.length === 1 ? "the table" : "the tables"} ${tables.join(", ")}`; throw new IntrospectRefusedError( - `Refusing to replace ${DEFAULT_SCHEMA_FILE}: the branch has ${one ? "a foreign key" : "foreign keys"} it does not declare (${rendered.newRelations.join(", ")}). A foreign key lets the API include the related rows. Declare ${one ? "it" : "them"} with fk() in ${DEFAULT_SCHEMA_FILE}, then rerun, or move the file out of config/database to start again from the catalog.`, + `Refusing to replace ${DEFAULT_SCHEMA_FILE}: the branch has ${one ? "a foreign key" : "foreign keys"} it does not declare (${edges.join(", ")}). A foreign key lets the API include the related rows. Declare ${one ? "it" : "them"} with fk() in schema.ts${declareTables}, then rerun.`, ); } diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index 9b2bfc9bf..aa3ca9e81 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -33,6 +33,14 @@ export interface Unexpressed { readonly reason: string; } +/** A foreign key schema.ts gets that the schema.ts it replaces does not declare. */ +interface NewRelation { + /** e.g. "app.notes.author_id → app.users.id". */ + readonly edge: string; + /** Its tables the replaced schema.ts does not declare, e.g. "app.users". */ + readonly undeclaredTables: readonly string[]; +} + interface SchemaSource { readonly source: string; /** Tables written to schema.ts. */ @@ -43,11 +51,8 @@ interface SchemaSource { readonly warnings: readonly string[]; /** What schema.ts declares differently from the database, which keeps it as it is. */ readonly approximated: readonly string[]; - /** - * Foreign keys schema.ts gets that `previous` does not declare, as - * "app.notes.author_id → app.users.id". Each one is an API include. - */ - readonly newRelations: readonly string[]; + /** Kept foreign keys `previous` does not declare. Each one is an API include. */ + readonly newRelations: readonly NewRelation[]; } interface RenderOptions { @@ -333,7 +338,7 @@ export function renderSchemaSource( const tableComments: string[] = []; /** Columns rendered private because `previous` does not declare them. */ const privatized: string[] = []; - const newRelations: string[] = []; + const newRelations: NewRelation[] = []; const qualified = (table: string, column?: string) => `${schemaName}.${table}${column ? `.${column}` : ""}`; const skipTable = (table: string, reason: string) => { @@ -760,9 +765,14 @@ export function renderSchemaSource( out.add(foreignKey.table); edges.set(plan.table.name, out); if (previous && !declaresForeignKey(plan.table.name, foreignKey)) { - newRelations.push( - `${qualified(plan.table.name, sourceColumn.column.name)} → ${qualified(foreignKey.table, targetColumn.column.name)}`, - ); + newRelations.push({ + edge: shown( + `${qualified(plan.table.name, sourceColumn.column.name)} → ${qualified(foreignKey.table, targetColumn.column.name)}`, + ), + undeclaredTables: [plan.table.name, foreignKey.table] + .filter((table) => !previousTables.has(table)) + .map((table) => shown(qualified(table))), + }); } } } @@ -857,7 +867,7 @@ export function renderSchemaSource( unexpressed, warnings: warnings.map(shown), approximated: approximated.map(shown), - newRelations: newRelations.map(shown), + newRelations, }); if (ordered.length === 0) { lines.push(...tableComments); diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 379f9639d..66235fad8 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -401,7 +401,7 @@ describe("runIntrospect", () => { 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, or move it out of config/database to start again from the catalog.", + "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([]); @@ -442,33 +442,46 @@ describe("runIntrospect", () => { expect(tree(root)).toEqual(before); }); - test("a foreign key the replaced schema.ts does not declare is refused, and nothing changes", async () => { - const undeclared = `import { defineSchema, id, integer, text } from ${JSON.stringify(BUILDER)}; + test.each([ + [ + "both tables", + `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() }), })); -`; - const root = tempApp({ - [SCHEMA]: undeclared, - [`${SCHEMA}.bak`]: "// an older backup\n", - [TYPES]: "// older types\n", - }); - await commitMigration(root); - const before = tree(root); +`, + "Declare it with fk() in schema.ts, then rerun.", + ], + [ + "only the referenced table", + previousSchema, + "Declare it with fk() in schema.ts and declare the table app.posts, then rerun.", + ], + ])( + "a foreign key the replaced schema.ts does not declare, with %s declared, is refused, and nothing changes", + async (_label, undeclared, advice) => { + const root = tempApp({ + [SCHEMA]: undeclared, + [`${SCHEMA}.bak`]: "// an older backup\n", + [TYPES]: "// older types\n", + }); + await commitMigration(root); + const before = tree(root); - const error = await refusal(root); + const error = await refusal(root); - expect(error).toBeInstanceOf(IntrospectRefusedError); - expect(error.message).toBe( - "Refusing to replace config/database/schema.ts: the branch has a foreign key it does not declare (app.posts.author_id → app.authors.id). A foreign key lets the API include the related rows. Declare it with fk() in config/database/schema.ts, then rerun, or move the file out of config/database to start again from the catalog.", - ); - expect(tree(root)).toEqual(before); - expect(fs.readFileSync(path.join(root, TYPES), "utf-8")).toBe( - "// older types\n", - ); - expect(markMigrationsApplied).not.toHaveBeenCalled(); - }); + expect(error).toBeInstanceOf(IntrospectRefusedError); + expect(error.message).toBe( + `Refusing to replace config/database/schema.ts: the branch has a foreign key it does not declare (app.posts.author_id → app.authors.id). A foreign key lets the API include the related rows. ${advice}`, + ); + expect(tree(root)).toEqual(before); + expect(fs.readFileSync(path.join(root, TYPES), "utf-8")).toBe( + "// older types\n", + ); + expect(markMigrationsApplied).not.toHaveBeenCalled(); + }, + ); test("an empty schema next to an existing schema.ts refuses before writing anything", async () => { catalog = catalogResponder({ diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index 811d9ded5..a79511d10 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -717,7 +717,7 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { expect(dropped.newRelations).toEqual([]); }); - test("a foreign key it does not declare is listed, on an existing table or a new one", () => { + test("a foreign key it does not declare is listed with the tables it does not declare either", () => { const plain = defineSchema(({ table }) => ({ boards: table("boards", { id: id(), title: text().notNull() }), notes: table("notes", { @@ -731,7 +731,11 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { const out = renderSchemaSource( [ boards, - notes(), + 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", @@ -739,8 +743,15 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { ); expect(out.newRelations).toEqual([ - "app.notes.board_id → app.boards.id", - "app.tags.note_id → app.notes.id", + { edge: "app.notes.board_id → app.boards.id", undeclaredTables: [] }, + { + edge: "app.notes.reviewer_id → app.users.id", + undeclaredTables: ["app.users"], + }, + { + edge: "app.tags.note_id → app.notes.id", + undeclaredTables: ["app.tags"], + }, ]); }); @@ -790,7 +801,10 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { "sales.boards.id, sales.boards.title, sales.notes.id, sales.notes.board_id, sales.notes.author_email, sales.notes.body are new to schema.ts, so they are private: the API does not return or accept them until you remove .private().", ); expect(out.newRelations).toEqual([ - "sales.notes.board_id → sales.boards.id", + { + edge: "sales.notes.board_id → sales.boards.id", + undeclaredTables: ["sales.notes", "sales.boards"], + }, ]); }); From f4afc51a259b46e5ae55f02cd0b5320ed47b3d2b Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:45:11 +0000 Subject: [PATCH 031/317] fix(appkit): say when schema.ts declares another schema than introspect reads A schema.ts of another schema declares nothing in the one introspect reads, so every column renders private and every foreign key is refused. The privacy warning and the refusal now name the schema schema.ts declares, and say that --schema-name with it refreshes the file. Signed-off-by: ditadi --- .../appkit/src/database/tooling/introspect/index.ts | 7 ++++++- .../src/database/tooling/introspect/render.ts | 13 +++++++++++-- .../tooling/introspect/tests/introspect.test.ts | 4 ++-- .../tooling/introspect/tests/render.test.ts | 2 +- 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index c3c7ea0ad..7cf6c035b 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -26,6 +26,7 @@ import { import { resourceId } from "../targets"; import { readCatalog, readUnreadObjects } from "./catalog"; import { + otherSchemaHint, renderSchemaSource, type Skip, shown, @@ -264,8 +265,12 @@ async function introspectHolding( tables.length === 0 ? "" : ` and declare ${tables.length === 1 ? "the table" : "the tables"} ${tables.join(", ")}`; + const advice = + previousSchema && previousSchema.$schemaName !== schemaName + ? otherSchemaHint(previousSchema.$schemaName, schemaName) + : `Declare ${one ? "it" : "them"} with fk() in schema.ts${declareTables}, then rerun.`; throw new IntrospectRefusedError( - `Refusing to replace ${DEFAULT_SCHEMA_FILE}: the branch has ${one ? "a foreign key" : "foreign keys"} it does not declare (${edges.join(", ")}). A foreign key lets the API include the related rows. Declare ${one ? "it" : "them"} with fk() in schema.ts${declareTables}, then rerun.`, + `Refusing to replace ${DEFAULT_SCHEMA_FILE}: the branch has ${one ? "a foreign key" : "foreign keys"} it does not declare (${edges.join(", ")}). A foreign key lets the API include the related rows. ${advice}`, ); } diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index aa3ca9e81..4aa1c5789 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -55,6 +55,11 @@ interface SchemaSource { readonly newRelations: readonly NewRelation[]; } +/** Why a schema.ts of another schema keeps nothing in this one, and what refreshes it. */ +export function otherSchemaHint(declared: string, read: string): string { + return `schema.ts declares schema "${declared}", so it declares nothing in "${read}". \`--schema-name ${declared}\` refreshes it.`; +} + interface RenderOptions { /** Module the builder is imported from. Default "@databricks/appkit/beta". */ readonly importSource?: string; @@ -349,8 +354,12 @@ export function renderSchemaSource( }; const { previous } = options; // A declaration of another schema declares nothing in this one. + const otherSchema = + previous && previous.$schemaName !== schemaName + ? previous.$schemaName + : null; const previousTables = new Map( - previous?.$schemaName === schemaName + previous && !otherSchema ? Object.values(previous.$tables).map((table): [string, AppKitTable] => [ table.$name, table, @@ -912,7 +921,7 @@ export function renderSchemaSource( if (privatized.length > 0) { const one = privatized.length === 1; warnings.push( - `${list(privatized)} ${one ? "is" : "are"} new to schema.ts, so ${one ? "it is" : "they are"} private: the API does not return or accept ${one ? "it" : "them"} until you remove .private().`, + `${list(privatized)} ${one ? "is" : "are"} new to schema.ts, so ${one ? "it is" : "they are"} private: the API does not return or accept ${one ? "it" : "them"} until you remove .private().${otherSchema ? ` ${otherSchemaHint(otherSchema, schemaName)}` : ""}`, ); } for (const comment of tableComments) body.push(` ${comment}`); diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 66235fad8..9bfc2b4cb 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -436,8 +436,8 @@ describe("runIntrospect", () => { expect(catalog.calls.every((call) => call.values[0] === "app")).toBe(true); expect(error).toBeInstanceOf(IntrospectRefusedError); - expect(error.message).toMatch( - /^Refusing to replace config\/database\/schema\.ts: the branch has a foreign key it does not declare \(app\.posts\.author_id → app\.authors\.id\)\./, + expect(error.message).toBe( + 'Refusing to replace config/database/schema.ts: the branch has a foreign key it does not declare (app.posts.author_id → app.authors.id). A foreign key lets the API include the related rows. schema.ts declares schema "sales", so it declares nothing in "app". `--schema-name sales` refreshes it.', ); expect(tree(root)).toEqual(before); }); diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index a79511d10..ae4a210ed 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -798,7 +798,7 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { ); expect(out.warnings).toContain( - "sales.boards.id, sales.boards.title, sales.notes.id, sales.notes.board_id, sales.notes.author_email, sales.notes.body are new to schema.ts, so they are private: the API does not return or accept them until you remove .private().", + 'sales.boards.id, sales.boards.title, sales.notes.id, sales.notes.board_id, sales.notes.author_email, sales.notes.body are new to schema.ts, so they are private: the API does not return or accept them until you remove .private(). schema.ts declares schema "app", so it declares nothing in "sales". `--schema-name app` refreshes it.', ); expect(out.newRelations).toEqual([ { From d4c1de3b92cc296ea6b4cdde11a65cb7e6111da5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:45:32 +0000 Subject: [PATCH 032/317] docs(appkit): say what the introspect render does with the schema.ts it replaces The docstring claimed a refresh never widens the API of the replaced schema.ts. What render does is narrower: columns that file does not declare render private, and foreign keys it does not declare are listed for introspect to refuse. Signed-off-by: ditadi --- packages/appkit/src/database/tooling/introspect/render.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index 4aa1c5789..f03000c60 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -325,9 +325,9 @@ function mirrored(target: BaseType): string { * Render pg_catalog tables as a `defineSchema` source the builder accepts. * What the builder cannot express is left out with an `// appkit: skipped …` * comment; what it declares differently (a timestamp without its precision, - * say) is listed in `approximated`. A refresh never widens the API of - * `previous`: what it does not declare renders private, and the foreign keys - * it does not declare are listed in `newRelations`. + * say) is listed in `approximated`. Columns `previous` does not declare render + * private, and the foreign keys it does not declare are listed in + * `newRelations`, which introspect refuses. */ export function renderSchemaSource( tables: readonly IntrospectedTable[], From 61c0e498cbee29dfce8fb87aa5429d16c5b05c35 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:51:33 +0000 Subject: [PATCH 033/317] fix(appkit): hold one history lock across init and clean clean drops the branch's migration journal, and init runs clean, migrate or introspect after its own checks, so another appkit db command could run in between. runClean now holds the checkout's history lock, and init holds one lock for its whole run and hands it to cleanHolding, migrateHolding and introspectHolding. init --schema none changes no history, so it takes no lock and creates no config/database. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 6 +- packages/appkit/src/database/tooling/clean.ts | 13 +++- packages/appkit/src/database/tooling/init.ts | 43 ++++++++---- .../src/database/tooling/introspect/index.ts | 3 +- .../appkit/src/database/tooling/migrate.ts | 3 +- .../database/tooling/tests/clean-seed.test.ts | 14 ++++ .../src/database/tooling/tests/init.test.ts | 69 ++++++++++++++----- 7 files changed, 114 insertions(+), 37 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 95ad881b2..c1e588dd9 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -156,10 +156,12 @@ protected branches. ### One command at a time -While `migrate` or `introspect` runs, it holds +While `migrate`, `introspect`, `clean` or `init` runs, it holds `config/database/.appkit-db.lock`. A second `appkit db` command in the same checkout fails and names the process that holds the lock. The lock goes when -the command finishes or exits. +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 diff --git a/packages/appkit/src/database/tooling/clean.ts b/packages/appkit/src/database/tooling/clean.ts index ffba81e41..986de4ea7 100644 --- a/packages/appkit/src/database/tooling/clean.ts +++ b/packages/appkit/src/database/tooling/clean.ts @@ -5,6 +5,7 @@ import { quoteIdentifier } from "../migrations/apply"; 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 { requireSchemaFile } from "./migrate"; import { resourceId } from "./targets"; @@ -182,9 +183,19 @@ export async function previewClean(ctx: DbContext): Promise { /** * `appkit db clean`: remove every app-schema object, the migration journal * included, on your dev or session branch. Refuses any other branch before - * connecting. + * connecting. One command at a time owns the checkout's history. */ export async function runClean(ctx: DbContext): Promise { + 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); const dependents = await runInTransaction(ctx, async (client) => { const found = await readCascadeDependents(client, target.schemaName); diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 68899b336..83e5c50d9 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -5,7 +5,7 @@ import dotenv from "dotenv"; import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; import { DEFAULT_SCHEMA_NAME } from "../schema-builder/define-schema"; -import { type CleanReport, runClean } from "./clean"; +import { type CleanReport, cleanHolding } from "./clean"; import type { DbContext } from "./context"; import { ensureDrizzleKit, @@ -15,8 +15,9 @@ import { import { refuseSymlink, updateEnvFile } from "./env-file"; import { classifyBranch, deployRefusal, takesWrites } from "./guard"; import { handOffAppSchema } from "./hand-off"; +import { type HistoryLock, withHistoryLock } from "./history-lock"; import { currentIdentity, type Identity } from "./identity"; -import { type IntrospectReport, runIntrospect } from "./introspect"; +import { introspectHolding, type IntrospectReport } from "./introspect"; import { isAlreadyExists, isBranchLimit, @@ -30,8 +31,8 @@ import { import { hasSchemaFile, type MigrateReport, + migrateHolding, requireSchemaFile, - runMigrate, } from "./migrate"; import { devBranchId, @@ -428,10 +429,24 @@ function readEnvValues(file: string): Record { * start the schema. No prompts: every choice has a default. It refuses the * project's default branch, protected branches and branches databricks.yml * deploys to before changing anything, and never touches the deploy bundle. + * 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 { + if (options.schema === "none") return initHolding(ctx, null, options); + return withHistoryLock(ctx.root, "init", (lock) => + initHolding(ctx, lock, options), + ); +} + +async function initHolding( + ctx: DbContext, + lock: HistoryLock | null, + options: InitOptions, ): Promise { const onStep = options.onStep ?? (() => undefined); const interactive = options.interactive ?? false; @@ -527,31 +542,33 @@ export async function runInit( ? ensureDrizzleKit(ctx.root, options.runCommand ?? runCommand, onStep) : null; - let start: InitStart; + // Without a lock (--schema none) the schema stays as the fork has it. + let start: InitStart = { kind: "none" }; const on = `on ${resourceId(branch.name)}`; - if (startKind === "migrate") { + if (lock && startKind === "migrate") { onStep(`Migrating schema ${schemaName} ${on}`); start = { kind: "migrate", - migrate: await runMigrate(branchCtx, { interactive }), + migrate: await migrateHolding(branchCtx, lock, { interactive }), }; - } else if (startKind === "introspect") { + } else if (lock && startKind === "introspect") { onStep(`Writing schema.ts from schema ${schemaName} ${on}`); start = { kind: "introspect", - introspect: await runIntrospect(branchCtx, { interactive }), + introspect: await introspectHolding(branchCtx, lock, { interactive }), }; - } else if (startKind === "clean") { + } else if (lock && startKind === "clean") { onStep(`Dropping schema ${schemaName} ${on}`); - const clean = await runClean(branchCtx); + const clean = await cleanHolding(branchCtx, lock); // Recreate from the committed migrations, so the startup check passes. start = { kind: "clean", clean, - migrate: await runMigrate(branchCtx, { interactive, generate: false }), + migrate: await migrateHolding(branchCtx, lock, { + interactive, + generate: false, + }), }; - } else { - start = { kind: "none" }; } return { diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 7cf6c035b..91efadae6 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -172,7 +172,8 @@ export async function runIntrospect( ); } -async function introspectHolding( +/** runIntrospect for a caller that already holds the checkout's history lock. */ +export async function introspectHolding( ctx: DbContext, lock: HistoryLock, options: IntrospectOptions, diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 7a9098029..8452901b7 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -115,7 +115,8 @@ export async function runMigrate( ); } -async function migrateHolding( +/** runMigrate for a caller that already holds the checkout's history lock. */ +export async function migrateHolding( ctx: DbContext, lock: HistoryLock, options: MigrateOptions, diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index 113e620db..f2d70c682 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -22,6 +22,7 @@ vi.mock("../context", async (importOriginal) => ({ })); import { deleteSessionBranch, previewClean, runClean } from "../clean"; +import { withHistoryLock } from "../history-lock"; import { runSeed, SEED_FILE } from "../seed"; import { cleanupTempApps, FakeLakebase, fakeContext, tempApp } from "./fakes"; @@ -134,6 +135,19 @@ describe("runClean", () => { expect(statements.slice(-1)).toEqual(["rollback"]); expect(client.released?.error).toBeInstanceOf(Error); }); + + test("while another appkit db command changes the migration history, it refuses before checking the branch", async () => { + const root = tempApp({ "config/database/schema.ts": schemaFile("app") }); + const ctx = fakeContext({ root }); + + await withHistoryLock(root, "migrate", async () => { + await expect(runClean(ctx)).rejects.toThrow( + /^Another `appkit db migrate` \(pid \d+ on .+\) is changing the migration history in config\/database\. /, + ); + }); + expect(writableEnvBranch).not.toHaveBeenCalled(); + expect(withBranchPool).not.toHaveBeenCalled(); + }); }); describe("previewClean", () => { diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index f5a26bf55..e3bb38581 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -3,14 +3,13 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; -const { runClean, runIntrospect, runMigrate, withBranchPool } = vi.hoisted( - () => ({ - runClean: vi.fn(), - runIntrospect: vi.fn(), - runMigrate: vi.fn(), +const { cleanHolding, introspectHolding, migrateHolding, withBranchPool } = + vi.hoisted(() => ({ + cleanHolding: vi.fn(), + introspectHolding: vi.fn(), + migrateHolding: vi.fn(), withBranchPool: vi.fn(), - }), -); + })); vi.mock("../context", async (importOriginal) => ({ ...(await importOriginal()), @@ -18,14 +17,16 @@ vi.mock("../context", async (importOriginal) => ({ })); vi.mock("../migrate", async (importOriginal) => ({ ...(await importOriginal()), - runMigrate, + migrateHolding, })); -vi.mock("../clean", () => ({ runClean })); -vi.mock("../introspect", () => ({ runIntrospect })); +vi.mock("../clean", () => ({ cleanHolding })); +vi.mock("../introspect", () => ({ introspectHolding })); import type { DbContext } from "../context"; +import type { HistoryLock } from "../history-lock"; import { type InitOptions, runInit } from "../init"; import { LakebaseApiError } from "../lakebase-api"; +import { runMigrate } from "../migrate"; import { DRIZZLE_KIT_VERSION } from "../migrations"; import { devBranchId, sessionBranchId } from "../naming"; import { @@ -157,13 +158,13 @@ beforeEach(() => { withBranchPool .mockReset() .mockImplementation((_ctx, fn: (p: unknown) => unknown) => fn(pool)); - runMigrate.mockReset().mockResolvedValue(migrateReport); - runClean.mockReset().mockResolvedValue({ + migrateHolding.mockReset().mockResolvedValue(migrateReport); + cleanHolding.mockReset().mockResolvedValue({ branch: DEV, schemaName: "app", dependents: [], }); - runIntrospect.mockReset().mockResolvedValue({ branch: DEV, tables: [] }); + introspectHolding.mockReset().mockResolvedValue({ branch: DEV, tables: [] }); }); afterEach(cleanupTempApps); @@ -219,7 +220,7 @@ describe("runInit — dev branch", () => { /^# Lakebase\n/, ); // Migrate runs against the new branch; the caller's environment is left alone. - const [migrateCtx, migrateOptions] = runMigrate.mock.calls[0] ?? []; + const [migrateCtx, , migrateOptions] = migrateHolding.mock.calls[0] ?? []; expect(migrateCtx.env.LAKEBASE_ENDPOINT).toBe(`${DEV}/endpoints/primary`); expect(migrateOptions).toEqual({ interactive: false }); expect(ctx.env.LAKEBASE_ENDPOINT).toBe(`${PRODUCTION}/endpoints/primary`); @@ -644,7 +645,9 @@ describe("runInit — schema start", () => { kind: "introspect", introspect: { branch: DEV, tables: [] }, }); - expect(runIntrospect.mock.calls[0]?.[1]).toEqual({ interactive: false }); + expect(introspectHolding.mock.calls[0]?.[2]).toEqual({ + interactive: false, + }); expect( steps.indexOf( `Installing drizzle-kit ${DRIZZLE_KIT_VERSION}, which writes migrations (pnpm ${install.join(" ")})`, @@ -680,13 +683,13 @@ describe("runInit — schema start", () => { const { report } = await init(ctx, { schema: "clean", runCommand }); - expect(runClean).toHaveBeenCalledOnce(); - expect(runMigrate.mock.calls[0]?.[1]).toEqual({ + expect(cleanHolding).toHaveBeenCalledOnce(); + expect(migrateHolding.mock.calls[0]?.[2]).toEqual({ interactive: false, generate: false, }); - expect(runClean.mock.invocationCallOrder[0]).toBeLessThan( - runMigrate.mock.invocationCallOrder[0] ?? 0, + expect(cleanHolding.mock.invocationCallOrder[0]).toBeLessThan( + migrateHolding.mock.invocationCallOrder[0] ?? 0, ); expect(runCommand).not.toHaveBeenCalled(); expect(report.start).toEqual({ @@ -696,6 +699,34 @@ describe("runInit — schema start", () => { }); }); + test("one history lock covers init's clean and migrate: another command is refused meanwhile, and the lock goes at the end", async () => { + const ctx = appOn(project(), {}, { files: { "package.json": "{}" } }); + const lockFile = path.join(ctx.root, "config/database/.appkit-db.lock"); + cleanHolding.mockImplementationOnce(async (_ctx, lock: HistoryLock) => { + lock.assertHeld(); + expect(fs.existsSync(lockFile)).toBe(true); + await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( + /^Another `appkit db init` \(pid \d+ on .+\) is changing the migration history in config\/database\. /, + ); + return { branch: DEV, schemaName: "app", dependents: [] }; + }); + + await init(ctx, { schema: "clean" }); + + expect(migrateHolding.mock.calls[0]?.[1]).toBe( + cleanHolding.mock.calls[0]?.[1], + ); + expect(fs.existsSync(lockFile)).toBe(false); + }); + + test("--schema none takes no history lock, so an app without config/database still has none", async () => { + const ctx = appOn(project(), {}, { schema: false }); + + await init(ctx, { schema: "none" }); + + expect(fs.existsSync(path.join(ctx.root, "config/database"))).toBe(false); + }); + test.each(["migrate", "clean"] as const)( "%s without schema.ts fails before any change", async (start) => { From 086ccc09cfb01cd8bf9630142374a34ffaa66865 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:54:11 +0000 Subject: [PATCH 034/317] fix(appkit): leave schema ownership alone for --schema none and public init --schema none still handed the app schema to the developer, which deletes the branch copy of the role that owns it, in apps that may have no database schema contract at all. It now leaves the schema and its owner as the fork copied them. Schema public is never handed off either: it belongs to the database (pg_database_owner on PostgreSQL 15 and later, the bootstrap superuser before), so AppKit never deletes its owner or reassigns its objects. Signed-off-by: ditadi --- .../appkit/src/database/tooling/hand-off.ts | 5 +++ packages/appkit/src/database/tooling/init.ts | 34 ++++++++++++------- .../src/database/tooling/tests/init.test.ts | 32 ++++++++++++++++- packages/shared/src/cli/commands/db/init.ts | 4 +++ 4 files changed, 61 insertions(+), 14 deletions(-) diff --git a/packages/appkit/src/database/tooling/hand-off.ts b/packages/appkit/src/database/tooling/hand-off.ts index adb3d17ae..1421a917f 100644 --- a/packages/appkit/src/database/tooling/hand-off.ts +++ b/packages/appkit/src/database/tooling/hand-off.ts @@ -61,11 +61,16 @@ interface HandOff { * 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. Returns * that owner; 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, diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 83e5c50d9..d6d27c45f 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -98,7 +98,10 @@ export interface InitReport { 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 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 envFile: string; /** The drizzle-kit install init ran; null when it was installed. */ @@ -425,10 +428,11 @@ function readEnvValues(file: string): Record { /** * `appkit db init`: find or create your dev branch or this checkout's session * branch, ensure a read-write endpoint and your DATABRICKS_SUPERUSER role, - * point `.env` at the branch, hand the app schema the fork copied to you, then - * start the schema. No prompts: every choice has a default. It refuses the - * project's default branch, protected branches and branches databricks.yml - * deploys to before changing anything, and never touches the deploy bundle. + * point `.env` at the branch, hand the app schema the fork copied to you + * (except with `--schema none`), then start the schema. No prompts: every + * choice has a default. It refuses the project's default branch, protected + * branches and branches databricks.yml deploys to before changing anything, + * and never touches the deploy bundle. * 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. @@ -528,14 +532,18 @@ async function initHolding( updateEnvFile(envFile, values); const branchCtx: DbContext = { ...ctx, env: { ...ctx.env, ...values } }; - const handedOff = await handOffAppSchema(branchCtx, { - branch: branch.name, - database, - schemaName, - developer: role, - roles, - onStep, - }); + // --schema none leaves the schema as the fork has it, owner included. + const handedOff = + startKind === "none" + ? null + : await handOffAppSchema(branchCtx, { + branch: branch.name, + database, + schemaName, + developer: role, + roles, + onStep, + }); const installed = startKind === "migrate" || startKind === "introspect" diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index e3bb38581..a44b7a5af 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -258,7 +258,7 @@ describe("runInit — dev branch", () => { schemaSource("sales"), ); - const { steps } = await init(ctx, { schema: "none" }); + const { steps } = await init(ctx); expect(pool.query).toHaveBeenCalledWith( expect.stringContaining("nspowner"), @@ -269,6 +269,36 @@ describe("runInit — dev branch", () => { ); }); + test("--schema none leaves the schema's owner alone: no hand-off, no role deleted", async () => { + const lakebase = project(); + + const { report } = await init(appOn(lakebase), { schema: "none" }); + + expect(report.handedOff).toBeNull(); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + expect(pool.query).not.toHaveBeenCalled(); + }); + + test("schema public is never handed off: its owner belongs to the database, not to an app", async () => { + const lakebase = project(); + const ctx = appOn( + lakebase, + {}, + { files: { "config/database/schema.ts": schemaSource("public") } }, + ); + schemaOwner = "pg_database_owner"; + + const { report } = await init(ctx); + + expect(report.handedOff).toBeNull(); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + expect(pool.query).not.toHaveBeenCalled(); + }); + test("creates a read-write endpoint that scales to zero after 5 idle minutes when the branch has none", async () => { const lakebase = project(); lakebase.autoEndpoint = false; diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index a31838b8f..bc79f0f09 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -131,6 +131,10 @@ the project's default branch, so they start with a copy of its rows, production data included. init never changes the default branch, a protected branch or a branch databricks.yml deploys to, and never edits databricks.yml. +With --schema none, init only sets up the branch and .env: the schema and its +owner stay as the fork copied them. init never hands off schema public, which +belongs to the database rather than to an app. + The project comes from LAKEBASE_PROJECT in .env (projects/ or ), else from LAKEBASE_ENDPOINT, else from the bundle's postgres_branch variable. When .env names neither DATABRICKS_CONFIG_PROFILE nor DATABRICKS_HOST, init adds the From 4e8aea9911c57e9c0c79e727719c4943e6090d7b Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 16:55:52 +0000 Subject: [PATCH 035/317] chore(appkit): acknowledge db tooling bundle size growth Regenerated with pnpm clean && pnpm build && pnpm size:baseline. Against the previous baseline the @databricks/appkit packed tarball grows from 1364290 to 1448119 bytes (+83829, +6.14%), over the 5% budget. The growth is the CLI-only @databricks/appkit/beta/database-tooling entry (45 KB gzipped, from 28 KB) with the introspect fixes and init, clean and history lock code it ships. @databricks/appkit-ui is unchanged at 406741 bytes. Signed-off-by: ditadi --- bundle-size-baseline.json | 58 +++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/bundle-size-baseline.json b/bundle-size-baseline.json index 6618e1e14..e36d71e93 100644 --- a/bundle-size-baseline.json +++ b/bundle-size-baseline.json @@ -3,25 +3,25 @@ { "name": "@databricks/appkit", "tarball": { - "packed": 1364290, - "unpacked": 4666959 + "packed": 1448119, + "unpacked": 4951341 }, "dist": { "total": { - "raw": 4651188, - "gzip": 1599394 + "raw": 4935570, + "gzip": 1691147 }, "js": { - "raw": 1391995, - "gzip": 496182 + "raw": 1486963, + "gzip": 527492 }, "types": { - "raw": 478827, - "gzip": 174184 + "raw": 489843, + "gzip": 179005 }, "maps": { - "raw": 2769571, - "gzip": 925210 + "raw": 2947969, + "gzip": 980832 }, "css": { "raw": 0, @@ -31,7 +31,7 @@ "raw": 10795, "gzip": 3818 }, - "fileCount": 935 + "fileCount": 969 }, "entries": [ { @@ -64,17 +64,17 @@ }, { "id": "./beta", - "gzip": 110783, + "gzip": 110872, "composition": { - "initialGzip": 110298, + "initialGzip": 110387, "lazyGzip": 485, - "totalGzip": 110783, - "own": 331023, + "totalGzip": 110872, + "own": 331204, "nodeModules": null, "chunks": [ { "label": "beta.js", - "gzip": 89747, + "gzip": 89836, "kind": "initial" }, { @@ -127,17 +127,17 @@ }, { "id": "./beta/database-tooling", - "gzip": 28557, + "gzip": 45940, "composition": { - "initialGzip": 28557, + "initialGzip": 45940, "lazyGzip": 0, - "totalGzip": 28557, - "own": 84002, + "totalGzip": 45940, + "own": 136903, "nodeModules": null, "chunks": [ { "label": "index.js", - "gzip": 28557, + "gzip": 45940, "kind": "initial" } ] @@ -145,11 +145,11 @@ }, { "id": "./testing", - "gzip": 79050, + "gzip": 79052, "composition": { "initialGzip": 45995, - "lazyGzip": 33055, - "totalGzip": 79050, + "lazyGzip": 33057, + "totalGzip": 79052, "own": 228781, "nodeModules": null, "chunks": [ @@ -170,7 +170,7 @@ }, { "label": "index.js", - "gzip": 28624, + "gzip": 28626, "kind": "lazy" }, { @@ -206,17 +206,17 @@ }, { "id": "./type-generator", - "gzip": 26635, + "gzip": 26636, "composition": { - "initialGzip": 26635, + "initialGzip": 26636, "lazyGzip": 0, - "totalGzip": 26635, + "totalGzip": 26636, "own": 76220, "nodeModules": null, "chunks": [ { "label": "index.js", - "gzip": 26635, + "gzip": 26636, "kind": "initial" } ] From b5e868f748a01c597e4090ef66724e7d09588bd7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:06:25 +0000 Subject: [PATCH 036/317] test(appkit): cover init's hand-off when you already own the app schema The re-run test ran with --schema none, which skips the hand-off, so no test reached the check that keeps init from deleting your own role. It now runs the default migrate start and asserts that the owner query ran for schema app and no role was deleted. Signed-off-by: ditadi --- packages/appkit/src/database/tooling/tests/init.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index a44b7a5af..26f8e65ee 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -233,14 +233,18 @@ describe("runInit — dev branch", () => { lakebase.addRole(DEV, `dbrx-apps-${SP}`, SP); schemaOwner = USER; - const { report, steps } = await init(appOn(lakebase), { schema: "none" }); + const { report, steps } = await init(appOn(lakebase)); expect(report).toMatchObject({ created: false, handedOff: null, - start: { kind: "none" }, + start: { kind: "migrate", migrate: migrateReport }, }); expect(steps[0]).toBe(`Using ${devBranchId(USER)}`); + expect(pool.query).toHaveBeenCalledWith( + expect.stringContaining("nspowner"), + ["app"], + ); expect( lakebase.calls.some((call) => /^(createBranch|deleteRole|createRole|createEndpoint)/.test(call), From b94dfc32dcac249ec6b30983697a60e3683f73fd Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:08:56 +0000 Subject: [PATCH 037/317] fix(appkit): leave schema.ts unread for init --schema none init --schema none hands off no schema and starts none, but it still loaded schema.ts for the schema name, so a half-edited file stopped a branch-only init. It now loads schema.ts only when the hand-off and the start use it. Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 6 ++++-- .../appkit/src/database/tooling/tests/init.test.ts | 12 ++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index d6d27c45f..3d5846810 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -459,7 +459,9 @@ async function initHolding( ? { api: SESSION_BRANCH_TTL, label: "7 days" } : { api: parseTtl(options.ttl), label: options.ttl.trim() }; - // Before any change: a .env init may write, what the start needs, and the schema the hand-off is for. + // Before any change, check the .env init may write and what the start needs, + // and read the schema the hand-off and the start are for. --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); @@ -468,7 +470,7 @@ async function initHolding( requireSchemaFile(ctx.root, startKind); } const schemaName = - hasSchema && startKind !== "introspect" + hasSchema && startKind !== "introspect" && startKind !== "none" ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) .$schemaName : DEFAULT_SCHEMA_NAME; diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 26f8e65ee..64feba45c 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -761,6 +761,18 @@ describe("runInit — schema start", () => { expect(fs.existsSync(path.join(ctx.root, "config/database"))).toBe(false); }); + test("--schema none does not load schema.ts, so a half-edited one does not stop it", async () => { + const ctx = appOn( + project(), + {}, + { files: { "config/database/schema.ts": "export const schema = (" } }, + ); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report.start).toEqual({ kind: "none" }); + }); + test.each(["migrate", "clean"] as const)( "%s without schema.ts fails before any change", async (start) => { From 39c8c0baaa16bedab7f5f938506ab357b7949548 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:09:25 +0000 Subject: [PATCH 038/317] fix(appkit): refuse a missing schema.ts before init and clean take the lock withHistoryLock creates config/database for its lock file, and init and clean checked for schema.ts only after taking it, so a refused init or clean left an empty config/database behind. Both now check first, as runMigrate does. Signed-off-by: ditadi --- packages/appkit/src/database/tooling/clean.ts | 2 ++ packages/appkit/src/database/tooling/init.ts | 13 +++++++------ .../src/database/tooling/tests/clean-seed.test.ts | 1 + .../appkit/src/database/tooling/tests/init.test.ts | 1 + 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/appkit/src/database/tooling/clean.ts b/packages/appkit/src/database/tooling/clean.ts index 986de4ea7..ef5227c3e 100644 --- a/packages/appkit/src/database/tooling/clean.ts +++ b/packages/appkit/src/database/tooling/clean.ts @@ -186,6 +186,8 @@ export async function previewClean(ctx: DbContext): Promise { * 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)); } diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 3d5846810..fa75f2eac 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -442,6 +442,10 @@ export async function runInit( options: InitOptions = {}, ): Promise { if (options.schema === "none") return initHolding(ctx, null, options); + // Before the lock, which creates config/database. + if (options.schema === "migrate" || options.schema === "clean") { + requireSchemaFile(ctx.root, options.schema); + } return withHistoryLock(ctx.root, "init", (lock) => initHolding(ctx, lock, options), ); @@ -459,16 +463,13 @@ async function initHolding( ? { 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 what the start needs, - // and read the schema the hand-off and the start are for. --schema none does - // neither, so it reads no schema.ts. + // Before any change, check the .env init may write and read the schema the + // hand-off and the start are for. --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 startKind = options.schema ?? (hasSchema ? "migrate" : "introspect"); - if (startKind === "migrate" || startKind === "clean") { - requireSchemaFile(ctx.root, startKind); - } const schemaName = hasSchema && startKind !== "introspect" && startKind !== "none" ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index f2d70c682..a90605eee 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -112,6 +112,7 @@ describe("runClean", () => { ); expect(writableEnvBranch).not.toHaveBeenCalled(); expect(withBranchPool).not.toHaveBeenCalled(); + expect(fs.existsSync(path.join(ctx.root, "config/database"))).toBe(false); }); test("refuses a branch that is not yours before connecting", async () => { diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 64feba45c..83dc5fae7 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -783,6 +783,7 @@ describe("runInit — schema start", () => { /^No config\/database\/schema\.ts yet/, ); expect(lakebase.calls).toEqual([]); + expect(fs.existsSync(path.join(ctx.root, "config/database"))).toBe(false); }, ); }); From f1af073839c2fb544758bce0d096b5ec59069f55 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:21:35 +0000 Subject: [PATCH 039/317] fix(appkit): verify deployed migrations by their journal entries and SQL verify --deployed treated an unreadable deployed journal as a reason to compare the migrations' timestamps with the deployment's create time, and it matched migrations by tag only, so two checkouts with different SQL under the same 0001_migration tag passed. Now the only evidence is the source snapshot the active deployment runs. Each committed migration needs the same journal entry and byte-identical SQL there. The report says verified, differs (with the missing and changed tags) or unavailable (with the reason). An export, parse or snapshot failure is unavailable, and report.ok is false unless the migrations are verified or none are committed. The deployed journal goes through the same parseJournal check as the committed one. Signed-off-by: ditadi --- .../appkit/src/database/migrations/paths.ts | 19 +- .../src/database/tooling/tests/verify.test.ts | 156 +++++++++-- .../appkit/src/database/tooling/verify.ts | 248 ++++++++++++------ packages/shared/src/cli/commands/db/output.ts | 6 +- .../src/cli/commands/db/tooling-contract.ts | 13 +- .../shared/src/cli/commands/db/verify.test.ts | 16 +- packages/shared/src/cli/commands/db/verify.ts | 7 +- 7 files changed, 334 insertions(+), 131 deletions(-) diff --git a/packages/appkit/src/database/migrations/paths.ts b/packages/appkit/src/database/migrations/paths.ts index 63a8b7263..d4f669aa7 100644 --- a/packages/appkit/src/database/migrations/paths.ts +++ b/packages/appkit/src/database/migrations/paths.ts @@ -81,15 +81,20 @@ export function readJsonFile(file: string): T { } } -/** 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; - const parsed = readJsonFile>(file); - if (parsed.dialect !== "postgresql" || !Array.isArray(parsed.entries)) { +/** 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( - `${file} is not a drizzle-kit PostgreSQL migration journal`, + `${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/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 63e332449..be79e597f 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -329,7 +329,6 @@ const DATABASE = `${PRODUCTION}/databases/db-1`; const SP = "11111111-2222-3333-4444-555555555555"; const HOST = "https://acme.cloud.databricks.com"; const SNAPSHOT = "/Workspace/Users/sp/src/01f0"; -const DEPLOYED_AT = "2026-10-01T12:00:00Z"; /** The app API's response for a deployed, running app bound to the deploy branch. */ function runningApp(overrides: Record = {}) { @@ -349,7 +348,6 @@ function runningApp(overrides: Record = {}) { app_status: { state: "RUNNING", message: "App is running." }, compute_status: { state: "ACTIVE", message: "App compute is running." }, active_deployment: { - create_time: DEPLOYED_AT, deployment_artifacts: { source_code_path: SNAPSHOT }, status: { state: "SUCCEEDED", message: "App started successfully" }, }, @@ -372,8 +370,10 @@ function deployedApp( yml?: string; spRole?: boolean; migrations?: Migration[]; - /** The deployed snapshot's journal; "unreadable" when export fails. */ - deployedJournal?: Migration[] | "unreadable"; + /** The deployed snapshot's journal: its entries, its raw text, or "unreadable" when its export fails. */ + deployedJournal?: Migration[] | string; + /** The deployed SQL by tag, else the committed SQL; "unreadable" when its export fails. */ + deployedSql?: Record; authenticatedHost?: string; } = {}, ) { @@ -410,15 +410,24 @@ function deployedApp( } if (method === "GET" && apiPath === "/api/2.0/workspace/export") { expect(query?.format).toBe("AUTO"); - requests.push(`workspace.export ${query?.path}`); + const file = String(query?.path); + requests.push(`workspace.export ${file}`); + const relative = file.slice(`${SNAPSHOT}/${MIGRATIONS}/`.length); const deployed = options.deployedJournal ?? options.migrations ?? []; - if (deployed === "unreadable") { + const content = + relative === "meta/_journal.json" + ? typeof deployed === "string" + ? deployed + : journal(deployed) + : (options.deployedSql?.[relative.replace(/\.sql$/, "")] ?? + `-- ${relative.replace(/\.sql$/, "")}\nselect 1;\n`); + if (content === "unreadable") { throw Object.assign(new Error("Permission denied"), { statusCode: 403, }); } return Response.json({ - content: Buffer.from(journal(deployed)).toString("base64"), + content: Buffer.from(content).toString("base64"), }); } throw new Error( @@ -458,7 +467,7 @@ function ymlWithApps(apps: string): string { } describe("runVerify --deployed", () => { - test("a running app bound to the deploy branch with every committed migration is ok, with no database connection and no role of yours there", async () => { + test("a running app whose snapshot has every committed migration, with the same journal entry and SQL, is ok, with no database connection and no role of yours there", async () => { const migrations = [{ tag: "0000_migration", when: 1000 }]; const { ctx, lakebase, requests } = deployedApp({ migrations }); @@ -468,13 +477,14 @@ describe("runVerify --deployed", () => { host: HOST, branch: PRODUCTION, app: "my-app", - migrations: { checked: "deployed code", missing: [] }, + migrations: { evidence: "verified" }, problems: [], ok: true, }); expect(requests).toEqual([ "apps.get my-app", - `workspace.export ${SNAPSHOT}/config/database/migrations/meta/_journal.json`, + `workspace.export ${SNAPSHOT}/${MIGRATIONS}/meta/_journal.json`, + `workspace.export ${SNAPSHOT}/${MIGRATIONS}/0000_migration.sql`, ]); expect(withBranchPool).not.toHaveBeenCalled(); expect(lakebase.calls.sort()).toEqual([ @@ -495,7 +505,11 @@ describe("runVerify --deployed", () => { }); expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ - migrations: { checked: "deployed code", missing: ["0001_migration"] }, + migrations: { + evidence: "differs", + missing: ["0001_migration"], + changed: [], + }, problems: [ "app my-app's active deployment does not have 0001_migration, which this checkout commits: `databricks apps deploy` deploys it, and the app applies it on start", ], @@ -503,24 +517,126 @@ describe("runVerify --deployed", () => { }); }); - test("when the deployed code cannot be read, migrations generated after the deployment fail it", async () => { - const deployedAt = Date.parse(DEPLOYED_AT); - const { ctx } = deployedApp({ - migrations: [ - { tag: "0000_migration", when: deployedAt - 1000 }, - { tag: "0001_migration", when: deployedAt + 1000 }, + test("the same tag with other SQL, or with another journal entry, in the deployment fails it", async () => { + const migrations = [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_migration", when: 2000 }, + ]; + const { ctx, requests } = deployedApp({ + migrations, + deployedJournal: [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_migration", when: 3000 }, ], - deployedJournal: "unreadable", + deployedSql: { "0000_migration": "-- 0000_migration\nselect 2;\n" }, }); expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ - migrations: { checked: "deploy time", missing: ["0001_migration"] }, + migrations: { + evidence: "differs", + missing: [], + changed: ["0000_migration", "0001_migration"], + }, problems: [ - `0001_migration was generated after app my-app's active deployment (${DEPLOYED_AT}), so it does not have it: \`databricks apps deploy\` deploys it, and the app applies it on start`, + "app my-app's active deployment has 0000_migration, 0001_migration with another journal entry or other SQL than this checkout commits. A migration that ran never runs again: restore them to what was deployed, and put the change in a new migration", ], + ok: false, + }); + // Its journal entry already differs, so its SQL is not read. + expect(requests).not.toContain( + `workspace.export ${SNAPSHOT}/${MIGRATIONS}/0001_migration.sql`, + ); + }); + + const JOURNAL = `${SNAPSHOT}/${MIGRATIONS}/meta/_journal.json`; + test.each([ + [ + "its journal cannot be exported", + { deployedJournal: "unreadable" }, + `exporting ${JOURNAL} failed: Permission denied`, + ], + [ + "its journal is empty", + { deployedJournal: "" }, + `${JOURNAL} exported no content`, + ], + [ + "its journal is not JSON", + { deployedJournal: "{" }, + `${JOURNAL} is not JSON: `, + ], + [ + "its journal is not drizzle-kit's", + { + deployedJournal: JSON.stringify({ dialect: "mysql", entries: [] }), + }, + `${JOURNAL} is not a drizzle-kit PostgreSQL migration journal`, + ], + [ + "a migration's SQL cannot be exported", + { deployedSql: { "0000_migration": "unreadable" } }, + `exporting ${SNAPSHOT}/${MIGRATIONS}/0000_migration.sql failed: Permission denied`, + ], + [ + "the deployment names no source snapshot", + { + app: runningApp({ + active_deployment: { status: { state: "SUCCEEDED" } }, + }), + }, + "its active deployment names no source snapshot", + ], + ] as const)( + "when %s, the migrations are unavailable and verify fails", + async (_label, options, reason) => { + const { ctx } = deployedApp({ + migrations: [{ tag: "0000_migration", when: 1000 }], + ...options, + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { + evidence: "unavailable", + reason: expect.stringContaining(reason), + }, + problems: [ + expect.stringContaining( + `verify cannot tell whether app my-app's active deployment has the committed migrations: ${reason}`, + ), + ], + ok: false, + }); + }, + ); + + test("with committed migrations, a report that stops before reading the deployment leaves them unverified", async () => { + const { ctx } = deployedApp({ + migrations: [{ tag: "0000_migration", when: 1000 }], + app: "missing", + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { + evidence: "unavailable", + reason: "verify stopped before reading the app's deployment", + }, + ok: false, }); }); + test("a committed migration whose SQL file is missing fails before any API call", async () => { + const { ctx, lakebase, requests } = deployedApp({ + migrations: [{ tag: "0000_migration", when: 1000 }], + }); + fs.rmSync(path.join(ctx.root, MIGRATIONS, "0000_migration.sql")); + + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + /^Missing .*0000_migration\.sql, listed in meta\/_journal\.json\. Restore it from version control\.$/, + ); + expect(requests).toEqual([]); + expect(lakebase.calls).toEqual([]); + }); + test("without committed migrations nothing is compared, and schema.ts is not needed", async () => { const { ctx, requests } = deployedApp(); fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 84105ef0a..7cf005924 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -1,3 +1,4 @@ +import fs from "node:fs"; import path from "node:path"; import type { PoolClient } from "pg"; @@ -8,7 +9,10 @@ import { readMigrationDrift } from "../migrations/apply"; import { journalFile, type JournalEntry, + MigrationFilesError, + migrationFile, migrationsFolder, + parseJournal, readJournal, } from "../migrations/paths"; import type { DataPath } from "../runtime"; @@ -51,13 +55,19 @@ interface LocalVerifyReport { readonly ok: boolean; } -/** How the deployed migrations compare with the committed ones. */ -interface DeployedMigrations { - /** "deployed code": the deployment's journal; "deploy time": committed after the deployment was created. */ - readonly checked: "deployed code" | "deploy time"; - /** Committed migrations the active deployment does not have. */ - readonly missing: readonly string[]; -} +/** The committed migrations against the snapshot of the source the active deployment runs. */ +type DeployedMigrations = + /** The snapshot has every committed migration, with the same journal entry and SQL. */ + | { readonly evidence: "verified" } + | { + readonly evidence: "differs"; + /** Committed migrations the snapshot does not have. */ + readonly missing: readonly string[]; + /** Committed migrations the snapshot has with another journal entry or other SQL. */ + readonly changed: readonly string[]; + } + /** The snapshot could not be read, so whether it has them is unknown. */ + | { readonly evidence: "unavailable"; readonly reason: string }; /** `appkit db verify --deployed`: whether a target's deployed app runs on its branch with the committed migrations. */ interface DeployVerifyReport { @@ -68,10 +78,11 @@ interface DeployVerifyReport { readonly branch: string; /** The app the target deploys; null when it declares none. */ readonly app: string | null; - /** null when there are no committed migrations, or no deployment to compare with. */ + /** null only when this checkout commits no migration. */ readonly migrations: DeployedMigrations | null; /** What keeps the deployed app from using the branch, each with its fix. */ readonly problems: readonly string[]; + /** No problem, and the deployed migrations verified or none committed. */ readonly ok: boolean; } @@ -142,7 +153,6 @@ interface DeploymentStatus { } interface Deployment { - readonly create_time?: string; /** The snapshot of the source the deployment runs. */ readonly deployment_artifacts?: { readonly source_code_path?: string }; readonly status?: DeploymentStatus; @@ -186,87 +196,145 @@ async function readApp( } } -/** The tags in a deployed journal; null when it cannot be read, which includes a deployment without one. */ -async function readDeployedTags( - ctx: DbContext, - file: string, -): Promise | null> { +/** A workspace file's bytes; throws with the reason when the export fails or has no content. */ +async function exportFile(ctx: DbContext, file: string): Promise { + let content: string | undefined; try { const response = await ctx.workspace().request({ method: "GET", path: "/api/2.0/workspace/export", query: { path: file, format: "AUTO" }, }); - const { content } = (await response.json()) as { content?: string }; - if (!content) return null; - const journal = JSON.parse( - Buffer.from(content, "base64").toString("utf-8"), - ); - const entries: unknown[] = Array.isArray(journal?.entries) - ? journal.entries - : []; - return new Set( - entries - .map((entry) => (entry as { tag?: unknown } | null)?.tag) - .filter((tag): tag is string => typeof tag === "string"), - ); - } catch { - return null; + ({ content } = (await response.json()) as { content?: string }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`exporting ${file} failed: ${message}`, { cause: error }); } + if (!content) throw new Error(`${file} exported no content`); + return Buffer.from(content, "base64"); +} + +/** A committed migration's journal entry and the bytes of its SQL file. */ +interface CommittedMigration { + readonly entry: JournalEntry; + readonly sql: Buffer; +} + +function readCommitted(folder: string): CommittedMigration[] { + return (readJournal(folder)?.entries ?? []).map((entry) => { + 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.`, + ); + } + return { entry, sql: fs.readFileSync(file) }; + }); } /** - * Committed migrations the active deployment lacks: from the journal in the - * snapshot it runs when that is readable, else the ones generated after the - * deployment was created. + * The committed migrations against the snapshot of the source the active + * deployment runs: each needs the same journal entry (idx, when, + * breakpoints) and byte-identical SQL there. Only that snapshot is evidence. + * Anything verify cannot read in it makes the result unavailable, never a + * match. */ -async function deployedMigrations( +async function readDeployedMigrations( ctx: DbContext, deployment: Deployment | undefined, - committed: readonly JournalEntry[], + committed: readonly CommittedMigration[], ): Promise { - if (!deployment || committed.length === 0) return null; - const snapshot = deployment.deployment_artifacts?.source_code_path; - if (snapshot) { - const relative = path - .relative(ctx.root, journalFile(migrationsFolder(ctx.root))) - .split(path.sep) - .join("/"); - const deployed = await readDeployedTags( - ctx, - `${snapshot.replace(/\/+$/, "")}/${relative}`, - ); - if (deployed) { - return { - checked: "deployed code", - missing: committed - .filter((entry) => !deployed.has(entry.tag)) - .map((entry) => entry.tag), - }; + if (committed.length === 0) return null; + if (!deployment) { + return { + evidence: "unavailable", + reason: "the app has no active deployment", + }; + } + const snapshot = deployment.deployment_artifacts?.source_code_path?.replace( + /\/+$/, + "", + ); + if (!snapshot) { + return { + evidence: "unavailable", + reason: "its active deployment names no source snapshot", + }; + } + const folder = migrationsFolder(ctx.root); + const deployedPath = (file: string) => + `${snapshot}/${path.relative(ctx.root, file).split(path.sep).join("/")}`; + try { + const journalPath = deployedPath(journalFile(folder)); + const text = (await exportFile(ctx, journalPath)).toString("utf-8"); + let json: unknown; + try { + json = JSON.parse(text); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`${journalPath} is not JSON: ${message}`, { + cause: error, + }); } + const deployed = parseJournal(json, journalPath).entries; + const compared = await Promise.all( + committed.map(async ({ entry, sql }) => { + const found = deployed.find((other) => other?.tag === entry.tag); + if (!found) return "missing"; + if ( + found.idx !== entry.idx || + found.when !== entry.when || + found.breakpoints !== entry.breakpoints + ) { + return "changed"; + } + const file = deployedPath(migrationFile(folder, entry.tag)); + return (await exportFile(ctx, file)).equals(sql) ? "same" : "changed"; + }), + ); + const tags = (status: "missing" | "changed") => + committed + .filter((_, index) => compared[index] === status) + .map(({ entry }) => entry.tag); + const missing = tags("missing"); + const changed = tags("changed"); + return missing.length === 0 && changed.length === 0 + ? { evidence: "verified" } + : { evidence: "differs", missing, changed }; + } catch (error) { + return { + evidence: "unavailable", + reason: error instanceof Error ? error.message : String(error), + }; } - const created = Date.parse(deployment.create_time ?? ""); - if (Number.isNaN(created)) return null; - return { - checked: "deploy time", - missing: committed - .filter((entry) => entry.when > created) - .map((entry) => entry.tag), - }; } -function migrationsProblem( +/** Why the deployed migrations do not match the committed ones, each with its fix; empty when verified. */ +function migrationsProblems( name: string, migrations: DeployedMigrations, - deployment: Deployment | undefined, -): string | null { - const { missing } = migrations; - if (missing.length === 0) return null; - const them = missing.length === 1 ? "it" : "them"; - const fix = `${DEPLOY} deploys ${them}, and the app applies ${them} on start`; - return migrations.checked === "deployed code" - ? `app ${name}'s active deployment does not have ${missing.join(", ")}, which this checkout commits: ${fix}` - : `${missing.join(", ")} ${missing.length === 1 ? "was" : "were"} generated after app ${name}'s active deployment (${deployment?.create_time}), so it does not have ${them}: ${fix}`; +): string[] { + if (migrations.evidence === "verified") return []; + if (migrations.evidence === "unavailable") { + return [ + `verify cannot tell whether app ${name}'s active deployment has the committed migrations: ${migrations.reason}`, + ]; + } + const problems: string[] = []; + const { missing, changed } = migrations; + if (missing.length > 0) { + const them = missing.length === 1 ? "it" : "them"; + problems.push( + `app ${name}'s active deployment does not have ${missing.join(", ")}, which this checkout commits: ${DEPLOY} deploys ${them}, and the app applies ${them} on start`, + ); + } + if (changed.length > 0) { + const them = changed.length === 1 ? "it" : "them"; + problems.push( + `app ${name}'s active deployment has ${changed.join(", ")} with another journal entry or other SQL than this checkout commits. A migration that ran never runs again: restore ${them} to what was deployed, and put the change in a new migration`, + ); + } + return problems; } /** The app's postgres resource against databricks.yml: same branch and database, and the permission to create its schema. */ @@ -395,7 +463,8 @@ function selectTarget( * Postgres role on the deploy branch is needed. The target's app must exist, * be bound to the branch and database databricks.yml names with * CAN_CONNECT_AND_CREATE, have a role on the branch for its service - * principal, be running, and run code with every committed migration. + * principal, be running, and run a snapshot with the journal entry and SQL of + * every committed migration. */ async function verifyDeploy( ctx: DbContext, @@ -447,10 +516,11 @@ async function verifyDeploy( } const branch = branchValue.name; const database = databaseValue?.name ?? null; + const committed = readCommitted(migrationsFolder(ctx.root)); const report = ( name: string | null, problems: string[], - migrations: DeployedMigrations | null = null, + migrations: DeployedMigrations | null, ): DeployVerifyReport => ({ kind: "deploy", target: target.name, @@ -459,13 +529,27 @@ async function verifyDeploy( app: name, migrations, problems, - ok: problems.length === 0, + ok: + problems.length === 0 && + (migrations === null || migrations.evidence === "verified"), }); + /** A report from before verify reads the deployment; its problems say why. */ + const stopped = (name: string | null, problems: string[]) => + report( + name, + problems, + committed.length === 0 + ? null + : { + evidence: "unavailable", + reason: "verify stopped before reading the app's deployment", + }, + ); if (!app) { - return report(null, [`target ${target.name} in ${file} declares no app`]); + return stopped(null, [`target ${target.name} in ${file} declares no app`]); } if (!app.name) { - return report(app.declaredName, [ + return stopped(app.declaredName, [ app.declaredName ? `${file} names the app ${app.declaredName}, with a reference verify cannot resolve` : `app ${app.key} in ${file} has no name`, @@ -482,7 +566,9 @@ async function verifyDeploy( ]); const branchId = resourceId(branch); if (!branchFound) { - return report(name, [`${file} deploys to ${branch}, which does not exist`]); + return stopped(name, [ + `${file} deploys to ${branch}, which does not exist`, + ]); } const problems: string[] = []; if (database && !databaseFound) { @@ -494,27 +580,23 @@ async function verifyDeploy( problems.push( `app ${name} is not deployed yet: ${DEPLOY} creates it and gives it access to ${branchId}`, ); - return report(name, problems); + return stopped(name, problems); } const binding = bindingProblems(deployed, name, branch, database, file); problems.push(...binding, ...runningProblems(deployed, name)); const sp = deployed.service_principal_client_id; - const committed = readJournal(migrationsFolder(ctx.root))?.entries ?? []; const [roles, migrations] = await Promise.all([ // Only meaningful once the app is bound to this branch. sp && binding.length === 0 ? api.listRoles(branch) : null, - deployedMigrations(ctx, deployed.active_deployment, committed), + readDeployedMigrations(ctx, deployed.active_deployment, committed), ]); if (roles && !roles.some((role) => role.status?.postgres_role === sp)) { problems.push( `the app's service principal ${sp} has no Postgres role on ${branchId}: ${DEPLOY} creates it from the app's postgres resource`, ); } - const missing = migrations - ? migrationsProblem(name, migrations, deployed.active_deployment) - : null; - if (missing) problems.push(missing); + if (migrations) problems.push(...migrationsProblems(name, migrations)); return report(name, problems, migrations); } diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 326091077..ca814d8ad 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -158,11 +158,9 @@ function printDeployVerifyReport(report: DeployVerifyReport): void { ok( `${app} (${where}) is running, bound to ${branch} with CAN_CONNECT_AND_CREATE, and its service principal has a role there`, ); - if (report.migrations?.checked === "deployed code") { - ok("Its active deployment has every committed migration"); - } else if (report.migrations) { + if (report.migrations?.evidence === "verified") { ok( - "Every committed migration was generated before its active deployment; its code could not be read, so verify compared times", + "Its active deployment has every committed migration, with the same SQL", ); } return; diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 4813122b0..119809064 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -89,10 +89,15 @@ export interface DeployVerifyReport { readonly host: string | null; readonly branch: string; readonly app: string | null; - readonly migrations: { - readonly checked: "deployed code" | "deploy time"; - readonly missing: readonly string[]; - } | null; + readonly migrations: + | { readonly evidence: "verified" } + | { + readonly evidence: "differs"; + readonly missing: readonly string[]; + readonly changed: readonly string[]; + } + | { readonly evidence: "unavailable"; readonly reason: string } + | null; readonly problems: readonly string[]; readonly ok: boolean; } diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index cddcc11ab..e5436e0a0 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -184,7 +184,7 @@ describe("appkit db verify", () => { host: "https://acme.cloud.databricks.com", branch: "projects/p/branches/production", app: "my-app", - migrations: { checked: "deployed code" as const, missing: [] }, + migrations: { evidence: "verified" as const }, problems: [], ok: true, }; @@ -205,26 +205,22 @@ describe("appkit db verify", () => { "app my-app (target prod on https://acme.cloud.databricks.com) is running, bound to production with CAN_CONNECT_AND_CREATE, and its service principal has a role there", ); expect(printed).toContain( - "Its active deployment has every committed migration", + "Its active deployment has every committed migration, with the same SQL", ); expect(error).not.toHaveBeenCalled(); expect(process.exitCode).toBeUndefined(); }); - test("says when migrations were compared by deploy time", async () => { - runVerify.mockResolvedValue({ - ...deploy, - migrations: { checked: "deploy time", missing: [] }, - }); + test("claims nothing about migrations when the checkout commits none", async () => { + runVerify.mockResolvedValue({ ...deploy, migrations: null }); await dbCommand.parseAsync(["verify", "--deployed"], { from: "user" }); expect(runVerify).toHaveBeenCalledWith(expect.anything(), { deployed: true, }); - expect(output(log)).toContain( - "Every committed migration was generated before its active deployment; its code could not be read, so verify compared times", - ); + expect(output(log)).not.toContain("committed migration"); + expect(process.exitCode).toBeUndefined(); }); test("lists each problem with its fix, and exits 1", async () => { diff --git a/packages/shared/src/cli/commands/db/verify.ts b/packages/shared/src/cli/commands/db/verify.ts index 3ffa1bece..944a093cd 100644 --- a/packages/shared/src/cli/commands/db/verify.ts +++ b/packages/shared/src/cli/commands/db/verify.ts @@ -49,9 +49,10 @@ ran that this checkout does not commit. branch's database. It checks that the target's app exists, that its postgres resource names the branch and database in databricks.yml with CAN_CONNECT_AND_CREATE, that its service principal has a role on the branch, -that the app is running, and that its active deployment has every committed -migration. It refuses when the target's workspace.host is not the workspace -this shell is authenticated against. +that the app is running, and that the source its active deployment runs has +every committed migration, with the same journal entry and SQL. When verify +cannot read that source, it fails. It refuses when the target's +workspace.host is not the workspace this shell is authenticated against. Exits 1 on any finding. Nothing is written or created. From 3739d32b991bf7ac798b8f05b3e2246fadbd2ce5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:29:33 +0000 Subject: [PATCH 040/317] docs(appkit): drop the beta db tooling advice from the Lakebase guide The GA Lakebase guide told every Lakebase app to run the beta `npx appkit db init --schema none`, without saying it is beta, and said that copied objects keep their owner and that --schema none leaves the schemas as they are. The database development flow is beta and hidden, and it is documented on the Database plugin page, so the Lakebase guide goes back to its main text. Signed-off-by: ditadi --- docs/docs/plugins/lakebase.md | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/docs/docs/plugins/lakebase.md b/docs/docs/plugins/lakebase.md index b581b5d74..c887073da 100644 --- a/docs/docs/plugins/lakebase.md +++ b/docs/docs/plugins/lakebase.md @@ -143,30 +143,7 @@ When you create the app with the Lakebase resource using the [Getting started](# ### Local development -Develop against a Lakebase branch of your own, so local runs never write to the -branch the app deploys to: - -```bash -npx appkit db init --schema none -``` - -It creates your dev branch from the project's default branch, gives it an endpoint -and a Postgres role for your Databricks identity, and points `.env` at it. The role -is a member of `DATABRICKS_SUPERUSER`, so you read and write every table the branch -copied. Copied objects keep their owner, usually the app's Service Principal, so -changing them (DDL) needs that owner; what you create on your branch is yours. -`--schema none` leaves the branch's schemas as they are. Apps that use the -[Database plugin](./database.md#set-up-your-branch) drop it, so `db init` also sets -up the app schema. - -:::caution -A new branch starts with a copy of the default branch's rows, production data -included. See [Set up your branch](./database.md#set-up-your-branch). -::: - -#### Against the deployed branch - -To develop locally against the branch the app deploys to: +To develop locally against a deployed Lakebase database: 1. **Deploy the app first.** The Service Principal creates the database schema and tables on first deploy. Apps generated from `databricks apps init` handle this automatically - they check if tables exist on startup and skip creation if they do. From d3ed4b7781384c87effe596da1d39adf7169c6a2 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:31:29 +0000 Subject: [PATCH 041/317] fix(appkit): keep the database plugin and appkit db hidden PR675 removed hidden from the database manifest, so the generated beta barrel and the template manifest picked the plugin up, and showed appkit db in appkit --help. The database development flow stays hidden while it is beta: the manifest is hidden again, beta.ts exports database by hand because the generated barrel skips hidden plugins, the template manifest no longer offers the plugin, and appkit db is hidden from --help again. The project field keeps bundleIgnore. Signed-off-by: ditadi --- packages/appkit/src/beta.ts | 1 + .../src/plugins/beta-exports.generated.ts | 1 - .../appkit/src/plugins/database/manifest.json | 1 + packages/shared/src/cli/index.ts | 3 +- template/appkit.plugins.json | 109 ------------------ 5 files changed, 4 insertions(+), 111 deletions(-) diff --git a/packages/appkit/src/beta.ts b/packages/appkit/src/beta.ts index ca75d8272..03d574653 100644 --- a/packages/appkit/src/beta.ts +++ b/packages/appkit/src/beta.ts @@ -121,6 +121,7 @@ export type { SearchResult, } from "./plugins/ai-search/types"; export * from "./plugins/beta-exports.generated"; +export { database } from "./plugins/database"; export type { DatabaseApiConfig, DatabaseApiWriteOperation, diff --git a/packages/appkit/src/plugins/beta-exports.generated.ts b/packages/appkit/src/plugins/beta-exports.generated.ts index 10982785b..7e556ebd9 100644 --- a/packages/appkit/src/plugins/beta-exports.generated.ts +++ b/packages/appkit/src/plugins/beta-exports.generated.ts @@ -7,4 +7,3 @@ export { agents } from "./agents"; export { aiSearch } from "./ai-search"; -export { database } from "./database"; diff --git a/packages/appkit/src/plugins/database/manifest.json b/packages/appkit/src/plugins/database/manifest.json index fc665fe97..cc17d6a1b 100644 --- a/packages/appkit/src/plugins/database/manifest.json +++ b/packages/appkit/src/plugins/database/manifest.json @@ -4,6 +4,7 @@ "displayName": "Database (Beta)", "description": "Schema-driven typed access to Databricks Lakebase PostgreSQL", "stability": "beta", + "hidden": true, "resources": { "required": [ { diff --git a/packages/shared/src/cli/index.ts b/packages/shared/src/cli/index.ts index 55bd50f9e..2fce08005 100644 --- a/packages/shared/src/cli/index.ts +++ b/packages/shared/src/cli/index.ts @@ -36,7 +36,8 @@ cmd.addCommand(docsCommand); cmd.addCommand(pluginCommand); cmd.addCommand(codemodCommand); cmd.addCommand(doctorCommand); -cmd.addCommand(dbCommand); +// Hidden from --help until the database plugin is offered by `databricks apps init`. +cmd.addCommand(dbCommand, { hidden: true }); // Registry commands are executable but hidden from --help while the feature // is still in development (registry + add work end-to-end but aren't announced). cmd.addCommand(registryCommand, { hidden: true }); diff --git a/template/appkit.plugins.json b/template/appkit.plugins.json index a122753a5..db53b96b7 100644 --- a/template/appkit.plugins.json +++ b/template/appkit.plugins.json @@ -196,115 +196,6 @@ } } }, - "database": { - "name": "database", - "displayName": "Database (Beta)", - "description": "Schema-driven typed access to Databricks Lakebase PostgreSQL", - "package": "@databricks/appkit", - "resources": { - "required": [ - { - "type": "postgres", - "alias": "Postgres", - "resourceKey": "postgres", - "description": "Lakebase Postgres database for persistent storage", - "permission": "CAN_CONNECT_AND_CREATE", - "fields": { - "project": { - "description": "Lakebase project resource name", - "bundleIgnore": true, - "examples": [ - "projects/{project-id}" - ], - "discovery": { - "type": "kind", - "resourceKind": "postgres_project", - "select": "name" - }, - "origin": "user" - }, - "branch": { - "description": "Lakebase branch resource name", - "examples": [ - "projects/{project-id}/branches/{branch-id}" - ], - "discovery": { - "type": "kind", - "resourceKind": "postgres_branch", - "select": "name", - "dependsOn": "project" - }, - "origin": "user" - }, - "database": { - "description": "Lakebase database resource name", - "examples": [ - "projects/{project-id}/branches/{branch-id}/databases/{database-id}" - ], - "discovery": { - "type": "kind", - "resourceKind": "postgres_database", - "select": "name", - "dependsOn": "branch" - }, - "origin": "user" - }, - "host": { - "env": "PGHOST", - "description": "Postgres host", - "localOnly": true, - "resolve": "postgres:host", - "origin": "platform" - }, - "databaseName": { - "env": "PGDATABASE", - "description": "Postgres database name", - "localOnly": true, - "resolve": "postgres:databaseName", - "origin": "platform" - }, - "endpointPath": { - "env": "LAKEBASE_ENDPOINT", - "description": "Lakebase endpoint resource name", - "bundleIgnore": true, - "resolve": "postgres:endpointPath", - "origin": "cli" - }, - "port": { - "env": "PGPORT", - "description": "Postgres port", - "localOnly": true, - "value": "5432", - "origin": "platform" - }, - "sslmode": { - "env": "PGSSLMODE", - "description": "Postgres SSL mode", - "localOnly": true, - "value": "require", - "origin": "platform" - } - }, - "appOnly": true, - "binding": { - "yamlKey": "postgres", - "varFields": [ - [ - "branch", - "branch" - ], - [ - "database", - "database" - ] - ] - } - } - ], - "optional": [] - }, - "stability": "beta" - }, "files": { "name": "files", "displayName": "Files Plugin", From 4a480305e17188006660cb9eb6cc4512c421f56d Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:43:31 +0000 Subject: [PATCH 042/317] fix(appkit): read the deployed journal even when the checkout commits no migration verify --deployed returned no migration result before reading the snapshot when the checkout committed none, so running it from a bundle root whose app lives in a subfolder passed without looking at the deployment. It now always reads the snapshot's journal. With nothing committed, a snapshot without migrations passes and one with migrations is unavailable, naming them. With migrations committed, ones the snapshot has and the checkout does not commit fail too, as in local verify. A snapshot without a journal (a 404) has no migrations, so every committed one is missing and the fix is to deploy. Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 94 ++++++++++++++-- .../appkit/src/database/tooling/verify.ts | 101 ++++++++++++------ .../src/cli/commands/db/tooling-contract.ts | 1 + 3 files changed, 155 insertions(+), 41 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index be79e597f..d83420d82 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -370,9 +370,9 @@ function deployedApp( yml?: string; spRole?: boolean; migrations?: Migration[]; - /** The deployed snapshot's journal: its entries, its raw text, or "unreadable" when its export fails. */ + /** The deployed snapshot's journal: its entries, its raw text, "unreadable" when its export fails, or "missing" when it does not exist. */ deployedJournal?: Migration[] | string; - /** The deployed SQL by tag, else the committed SQL; "unreadable" when its export fails. */ + /** The deployed SQL by tag, else the committed SQL; "unreadable" or "missing" as for the journal. */ deployedSql?: Record; authenticatedHost?: string; } = {}, @@ -426,6 +426,11 @@ function deployedApp( statusCode: 403, }); } + if (content === "missing") { + throw Object.assign(new Error("Path does not exist."), { + statusCode: 404, + }); + } return Response.json({ content: Buffer.from(content).toString("base64"), }); @@ -637,15 +642,88 @@ describe("runVerify --deployed", () => { expect(lakebase.calls).toEqual([]); }); - test("without committed migrations nothing is compared, and schema.ts is not needed", async () => { - const { ctx, requests } = deployedApp(); - fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); + test.each([ + ["has no journal", "missing"], + ["has a journal without entries", []], + ] as const)( + "without committed migrations, a snapshot that %s passes, and schema.ts is not needed", + async (_label, deployedJournal) => { + const { ctx, requests } = deployedApp({ + deployedJournal: deployedJournal as Migration[] | string, + }); + fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: null, + ok: true, + }); + expect(requests).toEqual([ + "apps.get my-app", + `workspace.export ${JOURNAL}`, + ]); + }, + ); + + test("without committed migrations, a snapshot with migrations fails, naming them: verify ran outside the app's root, or the checkout is behind", async () => { + const { ctx } = deployedApp({ + deployedJournal: [{ tag: "0000_migration", when: 1000 }], + }); expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ - migrations: null, - ok: true, + migrations: { + evidence: "unavailable", + reason: + "the deployment has 0000_migration, and this checkout commits no migration: run verify from the app's root, or pull them", + }, + problems: [ + "verify cannot tell whether app my-app's active deployment has the committed migrations: the deployment has 0000_migration, and this checkout commits no migration: run verify from the app's root, or pull them", + ], + ok: false, + }); + }); + + test("a migration the deployment has and this checkout does not commit fails it", async () => { + const migrations = [{ tag: "0000_migration", when: 1000 }]; + const { ctx } = deployedApp({ + migrations, + deployedJournal: [...migrations, { tag: "0001_migration", when: 2000 }], + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { + evidence: "differs", + missing: [], + changed: [], + unknown: ["0001_migration"], + }, + problems: [ + "app my-app's active deployment has 0001_migration, which this checkout does not commit: pull it, then run verify again", + ], + ok: false, + }); + }); + + test("a snapshot without a journal lacks every committed migration: deploy them", async () => { + const { ctx } = deployedApp({ + migrations: [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_migration", when: 2000 }, + ], + deployedJournal: "missing", + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { + evidence: "differs", + missing: ["0000_migration", "0001_migration"], + changed: [], + unknown: [], + }, + problems: [ + "app my-app's active deployment does not have 0000_migration, 0001_migration, which this checkout commits: `databricks apps deploy` deploys them, and the app applies them on start", + ], + ok: false, }); - expect(requests).toEqual(["apps.get my-app"]); }); test("--target checks that target's app, branch and host", async () => { diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 7cf005924..9c24e3798 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -65,6 +65,8 @@ type DeployedMigrations = readonly missing: readonly string[]; /** Committed migrations the snapshot has with another journal entry or other SQL. */ readonly changed: readonly string[]; + /** Migrations the snapshot has that this checkout does not commit. */ + readonly unknown: readonly string[]; } /** The snapshot could not be read, so whether it has them is unknown. */ | { readonly evidence: "unavailable"; readonly reason: string }; @@ -78,11 +80,11 @@ interface DeployVerifyReport { readonly branch: string; /** The app the target deploys; null when it declares none. */ readonly app: string | null; - /** null only when this checkout commits no migration. */ + /** null only when neither this checkout nor the deployed snapshot has a migration. */ readonly migrations: DeployedMigrations | null; /** What keeps the deployed app from using the branch, each with its fix. */ readonly problems: readonly string[]; - /** No problem, and the deployed migrations verified or none committed. */ + /** No problem, and the deployed migrations verified or none on either side. */ readonly ok: boolean; } @@ -196,8 +198,11 @@ async function readApp( } } -/** A workspace file's bytes; throws with the reason when the export fails or has no content. */ -async function exportFile(ctx: DbContext, file: string): Promise { +/** A workspace file's bytes; null when it does not exist. Throws with the reason when the export fails otherwise or has no content. */ +async function exportFile( + ctx: DbContext, + file: string, +): Promise { let content: string | undefined; try { const response = await ctx.workspace().request({ @@ -207,6 +212,9 @@ async function exportFile(ctx: DbContext, file: string): Promise { }); ({ content } = (await response.json()) as { content?: string }); } catch (error) { + if ((error as { statusCode?: unknown } | null)?.statusCode === 404) { + return null; + } const message = error instanceof Error ? error.message : String(error); throw new Error(`exporting ${file} failed: ${message}`, { cause: error }); } @@ -235,16 +243,16 @@ function readCommitted(folder: string): CommittedMigration[] { /** * The committed migrations against the snapshot of the source the active * deployment runs: each needs the same journal entry (idx, when, - * breakpoints) and byte-identical SQL there. Only that snapshot is evidence. - * Anything verify cannot read in it makes the result unavailable, never a - * match. + * breakpoints) and byte-identical SQL there, and the snapshot may have no + * migration the checkout does not commit. A snapshot without a journal has no + * migration. Only that snapshot is evidence. Anything verify cannot read in it + * makes the result unavailable, never a match. */ async function readDeployedMigrations( ctx: DbContext, deployment: Deployment | undefined, committed: readonly CommittedMigration[], ): Promise { - if (committed.length === 0) return null; if (!deployment) { return { evidence: "unavailable", @@ -266,17 +274,34 @@ async function readDeployedMigrations( `${snapshot}/${path.relative(ctx.root, file).split(path.sep).join("/")}`; try { const journalPath = deployedPath(journalFile(folder)); - const text = (await exportFile(ctx, journalPath)).toString("utf-8"); - let json: unknown; - try { - json = JSON.parse(text); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - throw new Error(`${journalPath} is not JSON: ${message}`, { - cause: error, - }); + const journal = await exportFile(ctx, journalPath); + let deployed: JournalEntry[] = []; + // A snapshot without a journal has no migration. + if (journal) { + let json: unknown; + try { + json = JSON.parse(journal.toString("utf-8")); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`${journalPath} is not JSON: ${message}`, { + cause: error, + }); + } + deployed = parseJournal(json, journalPath).entries; + } + const committedTags = new Set(committed.map(({ entry }) => entry.tag)); + const unknown = deployed.flatMap((entry) => + typeof entry?.tag === "string" && !committedTags.has(entry.tag) + ? [entry.tag] + : [], + ); + if (committed.length === 0) { + if (deployed.length === 0) return null; + return { + evidence: "unavailable", + reason: `the deployment has ${unknown.join(", ")}, and this checkout commits no migration: run verify from the app's root, or pull them`, + }; } - const deployed = parseJournal(json, journalPath).entries; const compared = await Promise.all( committed.map(async ({ entry, sql }) => { const found = deployed.find((other) => other?.tag === entry.tag); @@ -289,7 +314,13 @@ async function readDeployedMigrations( return "changed"; } const file = deployedPath(migrationFile(folder, entry.tag)); - return (await exportFile(ctx, file)).equals(sql) ? "same" : "changed"; + const bytes = await exportFile(ctx, file); + if (!bytes) { + throw new Error( + `${file} is listed in the deployed journal but missing from the snapshot`, + ); + } + return bytes.equals(sql) ? "same" : "changed"; }), ); const tags = (status: "missing" | "changed") => @@ -298,9 +329,9 @@ async function readDeployedMigrations( .map(({ entry }) => entry.tag); const missing = tags("missing"); const changed = tags("changed"); - return missing.length === 0 && changed.length === 0 + return missing.length === 0 && changed.length === 0 && unknown.length === 0 ? { evidence: "verified" } - : { evidence: "differs", missing, changed }; + : { evidence: "differs", missing, changed, unknown }; } catch (error) { return { evidence: "unavailable", @@ -321,7 +352,7 @@ function migrationsProblems( ]; } const problems: string[] = []; - const { missing, changed } = migrations; + const { missing, changed, unknown } = migrations; if (missing.length > 0) { const them = missing.length === 1 ? "it" : "them"; problems.push( @@ -334,6 +365,12 @@ function migrationsProblems( `app ${name}'s active deployment has ${changed.join(", ")} with another journal entry or other SQL than this checkout commits. A migration that ran never runs again: restore ${them} to what was deployed, and put the change in a new migration`, ); } + if (unknown.length > 0) { + const them = unknown.length === 1 ? "it" : "them"; + problems.push( + `app ${name}'s active deployment has ${unknown.join(", ")}, which this checkout does not commit: pull ${them}, then run verify again`, + ); + } return problems; } @@ -535,16 +572,10 @@ async function verifyDeploy( }); /** A report from before verify reads the deployment; its problems say why. */ const stopped = (name: string | null, problems: string[]) => - report( - name, - problems, - committed.length === 0 - ? null - : { - evidence: "unavailable", - reason: "verify stopped before reading the app's deployment", - }, - ); + report(name, problems, { + evidence: "unavailable", + reason: "verify stopped before reading the app's deployment", + }); if (!app) { return stopped(null, [`target ${target.name} in ${file} declares no app`]); } @@ -596,7 +627,11 @@ async function verifyDeploy( `the app's service principal ${sp} has no Postgres role on ${branchId}: ${DEPLOY} creates it from the app's postgres resource`, ); } - if (migrations) problems.push(...migrationsProblems(name, migrations)); + // Without an active deployment, runningProblems already says why; the + // migrations stay unavailable, so the report is not ok either way. + if (migrations && deployed.active_deployment) { + problems.push(...migrationsProblems(name, migrations)); + } return report(name, problems, migrations); } diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 119809064..3c120d125 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -95,6 +95,7 @@ export interface DeployVerifyReport { readonly evidence: "differs"; readonly missing: readonly string[]; readonly changed: readonly string[]; + readonly unknown: readonly string[]; } | { readonly evidence: "unavailable"; readonly reason: string } | null; From 9466b830442689717aca1fadfbd42f00534ff060 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:44:03 +0000 Subject: [PATCH 043/317] test(appkit): prove verify never reads a deployment's live source folder The no-snapshot case gave the deployment no source_code_path at all, so a fallback to that live, mutable folder would have passed. The deployment now has one, and the test asserts the result is unavailable with no export. Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 33 ++++++++++++++----- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index d83420d82..485af5d50 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -582,15 +582,6 @@ describe("runVerify --deployed", () => { { deployedSql: { "0000_migration": "unreadable" } }, `exporting ${SNAPSHOT}/${MIGRATIONS}/0000_migration.sql failed: Permission denied`, ], - [ - "the deployment names no source snapshot", - { - app: runningApp({ - active_deployment: { status: { state: "SUCCEEDED" } }, - }), - }, - "its active deployment names no source snapshot", - ], ] as const)( "when %s, the migrations are unavailable and verify fails", async (_label, options, reason) => { @@ -614,6 +605,30 @@ describe("runVerify --deployed", () => { }, ); + test("a deployment that names no snapshot is unavailable, and its live source folder is never read", async () => { + const { ctx, requests } = deployedApp({ + migrations: [{ tag: "0000_migration", when: 1000 }], + app: runningApp({ + active_deployment: { + // The live folder the deployment came from, which can change after it. + source_code_path: "/Workspace/Users/alice@example.com/my-app", + status: { state: "SUCCEEDED" }, + }, + }), + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { + evidence: "unavailable", + reason: "its active deployment names no source snapshot", + }, + ok: false, + }); + expect( + requests.filter((request) => request.startsWith("workspace.export")), + ).toEqual([]); + }); + test("with committed migrations, a report that stops before reading the deployment leaves them unverified", async () => { const { ctx } = deployedApp({ migrations: [{ tag: "0000_migration", when: 1000 }], From 176d7a11c14d80f558c44e113d63af54d5ca6b6b Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:46:32 +0000 Subject: [PATCH 044/317] fix(appkit): resolve verify's target with variable-overrides.json verify --deployed read the target with databricks.yml's own values only, so a branch set only in .databricks/bundle//variable-overrides.json was refused as unresolved. It now reads the target as a deploy from this checkout does, and as the deploy guard already reads it: the overrides file's values when the file exists. The workspace host is resolved with the same values, and a refusal names the file. Signed-off-by: ditadi --- .../appkit/src/database/tooling/targets.ts | 13 +++----- .../src/database/tooling/tests/verify.test.ts | 31 +++++++++++++++++++ .../appkit/src/database/tooling/verify.ts | 29 ++++++++++------- 3 files changed, 53 insertions(+), 20 deletions(-) diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 5026a9522..9b555afeb 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -127,6 +127,8 @@ interface BundleApp { /** What one target binds with one set of variable values. */ interface TargetBindings { + /** workspace.host of the target, else of the bundle; null when neither names one the files resolve. */ + readonly host: string | null; readonly apps: readonly BundleApp[]; /** The target's postgres_branch variable; null when the bundle declares none. */ readonly postgresBranch: BundleValue | null; @@ -139,8 +141,6 @@ export interface BundleTarget extends TargetBindings { readonly name: string; /** `default: true`, or the one target of a bundle that declares none. */ readonly isDefault: boolean; - /** workspace.host of the target, else of the bundle; null when neither names one the files resolve. */ - readonly host: string | null; /** * The same bindings with this checkout's variable-overrides.json applied, * which a deploy from here uses ahead of the target's own values; null @@ -454,6 +454,9 @@ export function readBundle(root: string): Bundle | null { ) : null; return { + host: resolve( + record(target?.workspace)?.host ?? record(bundle.workspace)?.host, + ), apps: bundleApps(apps ?? {}, resolve), postgresBranch: variable("postgres_branch", "branch"), postgresDatabase: variable("postgres_database", "database"), @@ -463,12 +466,6 @@ export function readBundle(root: string): Bundle | null { return { name, isDefault: target?.default === true, - host: resolverFor( - bundle, - target, - name, - null, - )(record(target?.workspace)?.host ?? record(bundle.workspace)?.host), ...bindings(null), overridden: overrides ? { file: overrides.file, ...bindings(overrides.values) } diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 485af5d50..85a2aee09 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -803,6 +803,37 @@ describe("runVerify --deployed", () => { expect(lakebase.calls).toEqual([]); }); + test("a branch that only variable-overrides.json sets is the one verify checks, as a deploy from this checkout uses it", async () => { + // The target gives the variables no value; only the overrides file does. + const yml = `${databricksYml(PRODUCTION, DATABASE).replace( + / {4}variables:\n(?: {6}.*\n)+/, + "", + )} workspace:\n host: ${HOST}\n`; + const { ctx } = deployedApp({ yml }); + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + 'No deploy branch: resources.apps.app.resources[0].postgres.branch in target default is "${var.postgres_branch}", which this checkout\'s files do not resolve to a branch.', + ); + + const overrides = path.join( + ctx.root, + ".databricks/bundle/default/variable-overrides.json", + ); + fs.mkdirSync(path.dirname(overrides), { recursive: true }); + fs.writeFileSync( + overrides, + JSON.stringify({ + postgres_branch: PRODUCTION, + postgres_database: DATABASE, + }), + ); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + branch: PRODUCTION, + problems: [], + ok: true, + }); + }); + test("a host written without a scheme or with a trailing slash matches", async () => { const { ctx } = deployedApp({ yml: ymlWithHost("acme.cloud.databricks.com/"), diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 9c24e3798..1221ad020 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -462,13 +462,14 @@ function hostOf(url: string): string { /** The API calls go to the workspace this shell is authenticated against, which must be the target's. */ async function assertTargetWorkspace( ctx: DbContext, - target: BundleTarget, + target: string, + host: string | null, ): Promise { - if (!target.host) return; + if (!host) return; const authenticated = await ctx.workspace().getHost(); - if (hostOf(authenticated) === hostOf(target.host)) return; + if (hostOf(authenticated) === hostOf(host)) return; throw new Error( - `Target ${target.name} deploys to ${target.host}, but this shell is authenticated against ${authenticated}. Set DATABRICKS_CONFIG_PROFILE to a profile for ${target.host}, then rerun.`, + `Target ${target} deploys to ${host}, but this shell is authenticated against ${authenticated}. Set DATABRICKS_CONFIG_PROFILE to a profile for ${host}, then rerun.`, ); } @@ -520,21 +521,25 @@ async function verifyDeploy( targetName, defaultBundleTarget(bundle), ); - const bound = target.apps.filter((app) => app.postgres.length > 0); + // What a deploy from this checkout uses: variable-overrides.json's values + // when it has the file, as the deploy guard reads them. + const deploy = target.overridden ?? target; + const withFile = target.overridden ? ` with ${target.overridden.file}` : ""; + const bound = deploy.apps.filter((app) => app.postgres.length > 0); if (bound.length > 1) { throw new Error( `Target ${target.name} deploys ${bound.length} apps with a postgres resource (${bound.map((app) => app.key).join(", ")}); verify checks one app per target.`, ); } const app = - bound[0] ?? (target.apps.length === 1 ? target.apps[0] : undefined); + bound[0] ?? (deploy.apps.length === 1 ? deploy.apps[0] : undefined); if (app && app.postgres.length > 1) { throw new Error( `App ${app.key} in target ${target.name} has ${app.postgres.length} postgres resources (${app.postgres.map((binding) => binding.at).join(", ")}); verify checks one per app.`, ); } const declared = app?.postgres[0]; - const branchValue = declared ? declared.branch : target.postgresBranch; + const branchValue = declared ? declared.branch : deploy.postgresBranch; if (!branchValue) { throw new Error( `No deploy branch: target ${target.name} in ${file} declares no app with a postgres resource.`, @@ -542,13 +547,13 @@ async function verifyDeploy( } if (branchValue.kind === "unresolved") { throw new Error( - `No deploy branch: ${declared ? `${declared.at}.branch` : "variables.postgres_branch"} in target ${target.name} is "${branchValue.written}", which this checkout's files do not resolve to a branch.`, + `No deploy branch: ${declared ? `${declared.at}.branch` : "variables.postgres_branch"} in target ${target.name}${withFile} is "${branchValue.written}", which this checkout's files do not resolve to a branch.`, ); } - const databaseValue = declared ? declared.database : target.postgresDatabase; + const databaseValue = declared ? declared.database : deploy.postgresDatabase; if (databaseValue?.kind === "unresolved") { throw new Error( - `No deploy database: ${declared ? `${declared.at}.database` : "variables.postgres_database"} in target ${target.name} is "${databaseValue.written}", which this checkout's files do not resolve to a database.`, + `No deploy database: ${declared ? `${declared.at}.database` : "variables.postgres_database"} in target ${target.name}${withFile} is "${databaseValue.written}", which this checkout's files do not resolve to a database.`, ); } const branch = branchValue.name; @@ -561,7 +566,7 @@ async function verifyDeploy( ): DeployVerifyReport => ({ kind: "deploy", target: target.name, - host: target.host, + host: deploy.host, branch, app: name, migrations, @@ -588,7 +593,7 @@ async function verifyDeploy( } const name = app.name; - await assertTargetWorkspace(ctx, target); + await assertTargetWorkspace(ctx, target.name, deploy.host); const api = ctx.api(); const [branchFound, databaseFound, deployed] = await Promise.all([ api.getBranch(branch), From 3876ae5cb27bc69bbaf6b7dbe2232903a2560583 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:47:11 +0000 Subject: [PATCH 045/317] docs(appkit): say which db commands refuse and which take the history lock With an unresolved reference in databricks.yml, init, clean and seed refuse every branch, not only migrate. Only migrate, introspect, clean and init take the history lock; seed, verify and clean --delete-branch take none. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index c1e588dd9..c88947fd3 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -144,10 +144,11 @@ 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}`. While any such -reference exists, `migrate` applies migrations to no 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 `migrate` too. +reference exists, `migrate` applies migrations to no branch, and `init`, `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 @@ -157,11 +158,12 @@ protected branches. ### One command at a time While `migrate`, `introspect`, `clean` or `init` runs, it holds -`config/database/.appkit-db.lock`. A second `appkit db` command in the same -checkout fails and names the process that holds the 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. +`config/database/.appkit-db.lock`. Another of these commands in the same +checkout fails and names the process that holds the lock. `seed`, `verify` 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 From d49e2586585a2f205c918bc40de24bf40a04ea3e Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:51:00 +0000 Subject: [PATCH 046/317] fix(appkit): drop init advice from verify when every branch is refused With a reference databricks.yml leaves unresolved, every branch counts as a deploy target and init refuses too, so the local verify warning sent you to a command that cannot help. The report now says whether the refusal covers every branch, and the warning then says which commands refuse and leaves out init. Signed-off-by: ditadi --- packages/appkit/src/database/tooling/guard.ts | 4 +- .../src/database/tooling/tests/verify.test.ts | 39 +++++++++++++++++++ .../appkit/src/database/tooling/verify.ts | 6 +++ packages/shared/src/cli/commands/db/output.ts | 4 +- .../src/cli/commands/db/tooling-contract.ts | 1 + .../shared/src/cli/commands/db/verify.test.ts | 18 +++++++++ 6 files changed, 70 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts index d6a444b10..c1cce60f1 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -86,9 +86,10 @@ export function takesWrites(kind: BranchKind): boolean { return kind === "dev" || kind === "session"; } -/** The .env branch and what it is to this developer. */ +/** 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 branch. */ @@ -118,6 +119,7 @@ export async function resolveEnvBranch( } return { branch, + boundary, ...classifyBranch({ branch, userName, diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 87b2202de..3e766e9f5 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -160,10 +160,13 @@ function branch(state: { const WRITES = /\b(insert|update|delete|create|drop|alter|grant|truncate)\b/i; +const RESOLVED = { branches: new Set(), unresolved: [] }; + beforeEach(() => { withBranchPool.mockReset(); resolveEnvBranch.mockReset().mockResolvedValue({ branch: { name: BRANCH }, + boundary: RESOLVED, kind: "dev", }); }); @@ -181,6 +184,7 @@ describe("runVerify", () => { ]; const clean = { notYours: null, + refusesEveryBranch: false, schemaProblems: [], pendingMigrations: [], strandedMigrations: [], @@ -290,6 +294,7 @@ describe("runVerify", () => { }); resolveEnvBranch.mockResolvedValue({ branch: { name: "projects/p/branches/production" }, + boundary: RESOLVED, kind: "default", reason: "it is the project's default branch", }); @@ -297,6 +302,40 @@ describe("runVerify", () => { expect(await runVerify(ctx)).toMatchObject({ branch: "projects/p/branches/production", notYours: "it is the project's default branch", + refusesEveryBranch: false, + ok: true, + }); + }); + + test("a reference databricks.yml leaves unresolved refuses every branch, and the report says so", async () => { + const ctx = app(two); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + }); + const reason = + 'databricks.yml may deploy to it: the files do not resolve resources.apps.app.resources[0].postgres.branch in target default ("projects/p/branches/dev-${workspace.current_user.short_name}"); give it a value in databricks.yml'; + resolveEnvBranch.mockResolvedValue({ + branch: { name: BRANCH }, + boundary: { + branches: new Set(), + unresolved: [ + { + target: "default", + at: "resources.apps.app.resources[0].postgres.branch", + written: + "projects/p/branches/dev-${workspace.current_user.short_name}", + }, + ], + }, + kind: "deploy-target", + reason, + }); + + expect(await runVerify(ctx)).toMatchObject({ + branch: BRANCH, + notYours: reason, + refusesEveryBranch: true, ok: true, }); }); diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 725d7c660..fc56ebfb0 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -39,6 +39,11 @@ interface LocalVerifyReport { readonly branch: string; /** Why the branch is not your dev or session branch, e.g. "it is the project's default branch"; null when it is. */ readonly notYours: string | null; + /** + * databricks.yml has a reference this checkout's files do not resolve, so + * migrate, clean, seed and init refuse every branch until it has a value. + */ + readonly refusesEveryBranch: boolean; /** Declared tables or columns the branch lacks (the plugin's startup check). */ readonly schemaProblems: readonly string[]; /** Committed migrations the branch has not run yet, newer than every one it ran. */ @@ -127,6 +132,7 @@ async function verifyLocal(ctx: DbContext): Promise { kind: "local", branch, notYours: takesWrites(env.kind) ? null : (env.reason ?? null), + refusesEveryBranch: env.boundary.unresolved.length > 0, schemaProblems, pendingMigrations: drift.pending, strandedMigrations: drift.stranded, diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 8b9aa6ef8..bf6475fca 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -121,7 +121,9 @@ function printLocalVerifyReport(report: LocalVerifyReport): void { const branch = shortName(report.branch); if (report.notYours) { warn( - `.env points at ${branch}, not a branch \`appkit db init\` set up for you: ${report.notYours}. \`npx appkit db init\` points it at a branch of your own.`, + report.refusesEveryBranch + ? `${branch} takes no writes (${report.notYours}). Until databricks.yml's references have values, \`appkit db migrate\`, \`clean\`, \`seed\` and \`init\` refuse every branch.` + : `.env points at ${branch}, not a branch \`appkit db init\` set up for you: ${report.notYours}. \`npx appkit db init\` points it at a branch of your own.`, ); } if (report.ok) { diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index e768f599f..b5ba6f070 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -76,6 +76,7 @@ export interface LocalVerifyReport { readonly kind: "local"; readonly branch: string; readonly notYours: string | null; + readonly refusesEveryBranch: boolean; readonly schemaProblems: readonly string[]; readonly pendingMigrations: readonly string[]; readonly strandedMigrations: readonly string[]; diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index 0096fcf5c..fef6c161c 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -33,6 +33,7 @@ const local = { kind: "local" as const, branch: "projects/p/branches/dev-alice-3f9a2c", notYours: null, + refusesEveryBranch: false, schemaProblems: [], pendingMigrations: [], strandedMigrations: [], @@ -103,6 +104,23 @@ describe("appkit db verify", () => { expect(process.exitCode).toBeUndefined(); }); + test("while databricks.yml leaves a reference unresolved, the warning says every branch refuses writes, not to run init", async () => { + runVerify.mockResolvedValue({ + ...local, + notYours: + "databricks.yml may deploy to it: the files do not resolve variables.postgres_branch in target default (no value); give it a value in databricks.yml", + refusesEveryBranch: true, + }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(log)).toContain( + "dev-alice-3f9a2c takes no writes (databricks.yml may deploy to it: the files do not resolve variables.postgres_branch in target default (no value); give it a value in databricks.yml). Until databricks.yml's references have values, `appkit db migrate`, `clean`, `seed` and `init` refuse every branch.", + ); + expect(output(log)).not.toContain("npx appkit db init"); + expect(process.exitCode).toBeUndefined(); + }); + test("prints every schema problem and pending migration, and exits 1", async () => { runVerify.mockResolvedValue({ ...local, From af0afa2cb419f49a71ba4f7b7108ef92e0b71ff2 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:51:04 +0000 Subject: [PATCH 047/317] docs(appkit): say migrate regenerates database types and init generates a migration Signed-off-by: ditadi --- docs/docs/plugins/database.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 61d47a248..26ae458c9 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -141,8 +141,10 @@ you picked in its prompts, usually the branch the app deploys to, and 2. It makes sure the branch has an endpoint and your Postgres role, points `.env` at the branch, and hands you the app schema the fork copied (see [One owner per branch](#one-owner-per-branch)). -3. It sets up the schema. With `schema.ts` it applies the committed migrations; - without one, it writes `schema.ts` from the branch's tables (`introspect`). +3. It sets up the schema. With `schema.ts` it runs `migrate`: it writes a + migration when `schema.ts` changed since the last one, then applies the + committed migrations. Without `schema.ts`, it writes `schema.ts` from the + branch's tables (`introspect`). `--schema clean` drops the app schema first. Without a terminal, `--schema clean` needs `--yes`. `--schema none` only sets up the branch and `.env`: it reads no `schema.ts`, hands over no schema, and leaves the schema @@ -168,7 +170,7 @@ project whose default branch holds only data every developer may see. | 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, and applies pending migrations to your branch. | +| `npx appkit db migrate` | Writes `config/database/migrations/NNNN_migration.sql` when `schema.ts` changed, regenerates `shared/appkit-types/database.d.ts` from `schema.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). | | `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. | From b96d7a91815a36abb024ee17fa4f064fd1619aad Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 17:53:13 +0000 Subject: [PATCH 048/317] docs(appkit): list db check among the commands that take no history lock Signed-off-by: ditadi --- docs/docs/plugins/database.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 416ce17ac..3a50fbfc6 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -222,11 +222,11 @@ protected branches. 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` 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. +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 From bfde0741656f9ab74d9689279600e1c6eea98438 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 18:25:22 +0000 Subject: [PATCH 049/317] fix(appkit): give no init advice while every branch is refused While databricks.yml has a reference the checkout's files cannot resolve, migrate applies to no branch and init, introspect, clean and seed refuse every branch, yet introspect and migrate still pointed at init. One guard function now builds every refusal: it names the references and where to give them values, and gives the caller's advice only when some branch can take writes. The .env branch carries the boundary that classified it. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 10 +-- packages/appkit/src/database/tooling/guard.ts | 70 ++++++++++++++----- packages/appkit/src/database/tooling/init.ts | 15 +++- .../src/database/tooling/introspect/index.ts | 7 +- .../introspect/tests/introspect.test.ts | 35 +++++++++- .../appkit/src/database/tooling/migrate.ts | 5 +- .../database/tooling/tests/clean-seed.test.ts | 1 + .../src/database/tooling/tests/guard.test.ts | 56 ++++++++++++++- .../src/database/tooling/tests/init.test.ts | 6 +- .../database/tooling/tests/migrate.test.ts | 1 + 10 files changed, 174 insertions(+), 32 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index c88947fd3..a7efdeede 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -144,11 +144,11 @@ 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}`. While any such -reference exists, `migrate` applies migrations to no branch, and `init`, `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. +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 diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts index d6a444b10..35d76e995 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -27,29 +27,57 @@ interface Classification { /** * 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. + * 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) { - const references = boundary.unresolved - .map( - ({ target, at, written, file }) => - `${at} in target ${target}${file ? ` with ${file}` : ""} (${written ? JSON.stringify(written) : "no value"})`, - ) - .join(", "); - const where = boundary.unresolved.some(({ file }) => file) - ? "databricks.yml or the variable-overrides.json named" - : "databricks.yml"; - return `databricks.yml may deploy to it: the files do not resolve ${references}; give ${boundary.unresolved.length > 1 ? "them values" : "it a value"} in ${where}`; + 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 }) => + `${at} in target ${target}${file ? ` with ${file}` : ""} (${written ? JSON.stringify(written) : "no value"})`, + ) + .join(", "); + const where = boundary.unresolved.some(({ file }) => file) + ? "databricks.yml or the variable-overrides.json named" + : "databricks.yml"; + 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; @@ -86,14 +114,19 @@ export function takesWrites(kind: BranchKind): boolean { return kind === "dev" || kind === "session"; } -/** The .env branch and what it is to this developer. */ +/** 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 branch. */ -export function notYourBranch(env: EnvBranch): string { - return `${resourceId(env.branch.name)} is not your dev or session branch (${env.reason})`; +/** 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, + ); } /** @@ -113,11 +146,16 @@ export async function resolveEnvBranch( ]); if (!branch) { throw new Error( - `The .env branch ${name} does not exist (deleted or expired). Run \`appkit db init\` to create or pick one.`, + `${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, diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index fa75f2eac..90a08e4fe 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -13,7 +13,12 @@ import { runCommand, } from "./drizzle-kit-install"; import { refuseSymlink, updateEnvFile } from "./env-file"; -import { classifyBranch, deployRefusal, takesWrites } from "./guard"; +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"; @@ -205,6 +210,10 @@ function branchLimitError( 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"; + /** * Your dev branch or this checkout's session branch: found with one GET, or * forked from the project's default branch. The branch id is resolved and @@ -235,7 +244,7 @@ async function findOrCreateBranch( }); if (!takesWrites(verdict.kind)) { throw new Error( - `Refusing to set up ${resourceId(branch.name)}: ${verdict.reason}. \`appkit db init\` only sets up your dev branch or this checkout's session branch.`, + `Refusing to set up ${writeRefusal(`${resourceId(branch.name)}: ${verdict.reason}`, boundary, INIT_SETS_UP)}.`, ); } onStep(`Using ${resourceId(branch.name)}`); @@ -261,7 +270,7 @@ async function findOrCreateBranch( const refusal = deployRefusal(boundary, name); if (refusal) { throw new Error( - `Refusing to set up ${resourceId(name)}: ${refusal}. \`appkit db init\` only sets up your dev branch or this checkout's session branch.`, + `Refusing to set up ${writeRefusal(`${resourceId(name)}: ${refusal}`, boundary, INIT_SETS_UP)}.`, ); } const existing = await api.getBranch(name); diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 91efadae6..66e83086f 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -189,8 +189,11 @@ export async function introspectHolding( 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 project's default branch, and introspects it when there is no ${DEFAULT_SCHEMA_FILE}.`, + `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 project's default branch, and introspects it when there is no ${DEFAULT_SCHEMA_FILE}`, + )}.`, ); } const branchId = resourceId(env.branch.name); diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 9bfc2b4cb..7562f4a07 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -67,9 +67,11 @@ export const schema = defineSchema(({ table }) => { }); `; -const onDevBranch = { branch: { name: DEV }, kind: "dev" }; +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", }; @@ -284,6 +286,37 @@ describe("runIntrospect", () => { }, ); + 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); diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 4ad773d87..80af77786 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -79,7 +79,10 @@ async function applyBlocker(ctx: DbContext): Promise { const env = await resolveEnvBranch(ctx); if (!env) return NO_ENV_BRANCH; if (takesWrites(env.kind)) return undefined; - return `${notYourBranch(env)}. Migrations are applied only to branches \`appkit db init\` created for you; the deployed app applies committed migrations to its own branch`; + return notYourBranch( + env, + "Migrations are applied only to branches `appkit db init` created for you; the deployed app applies committed migrations to its own branch", + ); } /** Apply pending migrations to the `.env` branch, or say why they were not. */ diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index a90605eee..71a260bae 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -202,6 +202,7 @@ describe("deleteSessionBranch", () => { test("refuses any other branch, and a .env without one", async () => { resolveEnvBranch.mockResolvedValueOnce({ branch: { name: "projects/p/branches/production" }, + boundary: { branches: new Set(), unresolved: [] }, kind: "default", reason: "it is the project's default branch", }); diff --git a/packages/appkit/src/database/tooling/tests/guard.test.ts b/packages/appkit/src/database/tooling/tests/guard.test.ts index 15280dc4c..56bf00551 100644 --- a/packages/appkit/src/database/tooling/tests/guard.test.ts +++ b/packages/appkit/src/database/tooling/tests/guard.test.ts @@ -2,9 +2,11 @@ import { afterEach, describe, expect, test } from "vitest"; import { classifyBranch, + everyBranchRefusal, resolveEnvBranch, takesWrites, writableEnvBranch, + writeRefusal, } from "../guard"; import { devBranchId, sessionBranchId } from "../naming"; import type { DeployBoundary } from "../targets"; @@ -98,9 +100,34 @@ describe("classifyBranch", () => { expect(verdict(branch, {}, "k2x9q0ab", unresolved)).toEqual({ kind: "deploy-target", reason: - 'databricks.yml may deploy to it: the files do not resolve resources.apps.app.resources[0].postgres.branch in target prod ("${var.postgres_branch}"); give it a value in databricks.yml', + "databricks.yml may deploy to it through a reference this checkout's files do not resolve", }); } + expect(everyBranchRefusal(unresolved)).toBe( + 'The files do not resolve resources.apps.app.resources[0].postgres.branch in target prod ("${var.postgres_branch}"), 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(everyBranchRefusal(NO_DEPLOYS)).toBeNull(); + }); + + test("a refusal gives its advice only while some branch can take writes", () => { + const unresolved: DeployBoundary = { + branches: new Set(), + unresolved: [ + { + target: "dev", + at: "variables.postgres_branch", + written: "", + file: ".databricks/bundle/dev/variable-overrides.json", + }, + ], + }; + expect(writeRefusal("x is refused", NO_DEPLOYS, "Run init")).toBe( + "x is refused. Run init", + ); + expect(writeRefusal("x is refused", NO_DEPLOYS)).toBe("x is refused"); + expect(writeRefusal("x is refused", unresolved, "Run init")).toBe( + "x is refused. The files do not resolve variables.postgres_branch in target dev with .databricks/bundle/dev/variable-overrides.json (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 or the variable-overrides.json named", + ); }); }); @@ -207,7 +234,7 @@ describe("resolveEnvBranch", () => { expect(env?.kind).toBe("deploy-target"); expect(env && takesWrites(env.kind)).toBe(false); - expect(env?.reason).toContain( + expect(env && everyBranchRefusal(env.boundary)).toContain( 'resources.apps.app.resources[0].postgres.branch in target staging ("${var.postgres_branch}")', ); }); @@ -285,4 +312,29 @@ describe("writableEnvBranch", () => { "Did not seed: no branch is configured in .env (PGHOST, PGDATABASE and LAKEBASE_ENDPOINT); run `appkit db init`.", ); }); + + test("while a reference is unresolved, the refusal names it and gives no init advice, on the default branch too", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(`${P}/branches/production`, { default: true }); + const root = tempApp({ + "databricks.yml": `${databricksYml(`${P}/branches/production`, `${P}/branches/production/databases/db`)} staging: + variables: + postgres_branch: \${var.staging_branch} + postgres_database: ${P}/branches/staging/databases/db +`, + }); + + const refusal = writableEnvBranch( + fakeContext({ + root, + env: envFor(`${P}/branches/production`), + api: lakebase.api(), + }), + "seed", + ); + + await expect(refusal).rejects.toThrow( + `Refusing to seed: production is not your dev or session branch (it is the project's default branch). The files do not resolve resources.apps.app.resources[0].postgres.branch in target staging ("\${var.postgres_branch}"), variables.postgres_branch in target staging ("\${var.staging_branch}"), so \`appkit db migrate\` applies migrations to no branch, and \`init\`, \`introspect\`, \`clean\` and \`seed\` refuse every branch. Give them values in databricks.yml.`, + ); + }); }); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 83dc5fae7..7e0cbc4ff 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -584,9 +584,11 @@ describe("runInit — branches it never sets up", () => { ); const before = fs.readFileSync(path.join(ctx.root, ".env"), "utf-8"); - await expect(init(ctx)).rejects.toThrow( - `Refusing to set up ${devBranchId(USER)}: databricks.yml may deploy to it: the files do not resolve resources.apps.app.resources[0].postgres.branch in target default`, + const error: Error = await init(ctx).catch((caught) => caught); + expect(error.message).toContain( + `Refusing to set up ${devBranchId(USER)}: databricks.yml may deploy to it through a reference this checkout's files do not resolve. The files do not resolve resources.apps.app.resources[0].postgres.branch in target default`, ); + expect(error.message).not.toContain("only sets up"); expect(lakebase.calls).toEqual([]); expect(fs.readFileSync(path.join(ctx.root, ".env"), "utf-8")).toBe(before); }); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index a99bc3025..1ffe5c2cb 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -167,6 +167,7 @@ describe("runMigrate", () => { const ctx = app(`notes: table("notes", { id: id() })`); resolveEnvBranch.mockResolvedValue({ branch: { name: "projects/p/branches/production" }, + boundary: { branches: new Set(), unresolved: [] }, kind: "default", reason: "it is the project's default branch", }); From bcce3aabac9026258cb34cfc7c5534232fffdc72 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 18:25:36 +0000 Subject: [PATCH 050/317] fix(appkit): fail verify --deployed closed on a missing snapshot A journal 404 counted as "no migrations" even when the snapshot itself was gone, so a checkout without migrations passed on no evidence. A 404 now counts only after get-status shows the snapshot exists; otherwise the result is unavailable. Messages that credit databricks.yml with a branch or database now name variable-overrides.json when the value came from it, the no-commit advice no longer sends you to a directory verify cannot run from, and --help says verify fails on deployed migrations the checkout does not commit and reads the overrides file. Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 84 +++++++++++++++++-- .../appkit/src/database/tooling/verify.ts | 66 ++++++++++++--- packages/shared/src/cli/commands/db/verify.ts | 9 +- 3 files changed, 139 insertions(+), 20 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 85a2aee09..f79a12b9a 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -374,6 +374,8 @@ function deployedApp( deployedJournal?: Migration[] | string; /** The deployed SQL by tag, else the committed SQL; "unreadable" or "missing" as for the journal. */ deployedSql?: Record; + /** The deployed snapshot folder's status: "unreadable" or "missing" as for the journal; it exists otherwise. */ + snapshot?: "unreadable" | "missing"; authenticatedHost?: string; } = {}, ) { @@ -435,6 +437,21 @@ function deployedApp( content: Buffer.from(content).toString("base64"), }); } + if (method === "GET" && apiPath === "/api/2.0/workspace/get-status") { + const file = String(query?.path); + requests.push(`workspace.get-status ${file}`); + if (options.snapshot === "unreadable") { + throw Object.assign(new Error("Permission denied"), { + statusCode: 403, + }); + } + if (options.snapshot === "missing" || file !== SNAPSHOT) { + throw Object.assign(new Error("Path does not exist."), { + statusCode: 404, + }); + } + return Response.json({ object_type: "DIRECTORY", path: file }); + } throw new Error( `--deployed only reads the app and its journal, not ${method} ${apiPath}`, ); @@ -658,11 +675,11 @@ describe("runVerify --deployed", () => { }); test.each([ - ["has no journal", "missing"], - ["has a journal without entries", []], + ["has no journal", "missing", [`workspace.get-status ${SNAPSHOT}`]], + ["has a journal without entries", [], []], ] as const)( "without committed migrations, a snapshot that %s passes, and schema.ts is not needed", - async (_label, deployedJournal) => { + async (_label, deployedJournal, statusRequests) => { const { ctx, requests } = deployedApp({ deployedJournal: deployedJournal as Migration[] | string, }); @@ -675,11 +692,38 @@ describe("runVerify --deployed", () => { expect(requests).toEqual([ "apps.get my-app", `workspace.export ${JOURNAL}`, + ...statusRequests, ]); }, ); - test("without committed migrations, a snapshot with migrations fails, naming them: verify ran outside the app's root, or the checkout is behind", async () => { + test.each([ + [ + "does not exist", + "missing", + `the source snapshot ${SNAPSHOT} does not exist`, + ], + [ + "has a status verify cannot read", + "unreadable", + `reading the status of ${SNAPSHOT} failed: Permission denied`, + ], + ] as const)( + "without committed migrations, a journal 404 in a snapshot that %s is unavailable, not a pass", + async (_label, snapshot, reason) => { + const { ctx } = deployedApp({ deployedJournal: "missing", snapshot }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { evidence: "unavailable", reason }, + problems: [ + `verify cannot tell whether app my-app's active deployment has the committed migrations: ${reason}`, + ], + ok: false, + }); + }, + ); + + test("without committed migrations, a snapshot with migrations fails, naming them: the checkout is behind", async () => { const { ctx } = deployedApp({ deployedJournal: [{ tag: "0000_migration", when: 1000 }], }); @@ -688,10 +732,10 @@ describe("runVerify --deployed", () => { migrations: { evidence: "unavailable", reason: - "the deployment has 0000_migration, and this checkout commits no migration: run verify from the app's root, or pull them", + "the deployment has 0000_migration, and this checkout commits none in config/database/migrations next to databricks.yml: pull it, then run verify again", }, problems: [ - "verify cannot tell whether app my-app's active deployment has the committed migrations: the deployment has 0000_migration, and this checkout commits no migration: run verify from the app's root, or pull them", + "verify cannot tell whether app my-app's active deployment has the committed migrations: the deployment has 0000_migration, and this checkout commits none in config/database/migrations next to databricks.yml: pull it, then run verify again", ], ok: false, }); @@ -834,6 +878,34 @@ describe("runVerify --deployed", () => { }); }); + test("a branch variable-overrides.json sets is credited to that file when it is missing or the app is bound elsewhere", async () => { + const staging = "projects/p/branches/staging"; + const { ctx, lakebase } = deployedApp(); + const overrides = path.join( + ctx.root, + ".databricks/bundle/default/variable-overrides.json", + ); + fs.mkdirSync(path.dirname(overrides), { recursive: true }); + fs.writeFileSync(overrides, JSON.stringify({ postgres_branch: staging })); + const source = + "databricks.yml with .databricks/bundle/default/variable-overrides.json"; + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + branch: staging, + problems: [`${source} deploys to ${staging}, which does not exist`], + ok: false, + }); + + lakebase.addBranch(staging); + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + branch: staging, + problems: expect.arrayContaining([ + `app my-app uses branch ${PRODUCTION}, not ${staging} from ${source}: \`databricks apps deploy\` applies ${source}`, + ]), + ok: false, + }); + }); + test("a host written without a scheme or with a trailing slash matches", async () => { const { ctx } = deployedApp({ yml: ymlWithHost("acme.cloud.databricks.com/"), diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 1221ad020..4fb817927 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -222,6 +222,29 @@ async function exportFile( return Buffer.from(content, "base64"); } +/** Whether a workspace path exists. Throws with the reason when its status cannot be read. */ +async function workspacePathExists( + ctx: DbContext, + file: string, +): Promise { + try { + await ctx.workspace().request({ + method: "GET", + path: "/api/2.0/workspace/get-status", + query: { path: file }, + }); + return true; + } catch (error) { + if ((error as { statusCode?: unknown } | null)?.statusCode === 404) { + return false; + } + const message = error instanceof Error ? error.message : String(error); + throw new Error(`reading the status of ${file} failed: ${message}`, { + cause: error, + }); + } +} + /** A committed migration's journal entry and the bytes of its SQL file. */ interface CommittedMigration { readonly entry: JournalEntry; @@ -244,9 +267,10 @@ function readCommitted(folder: string): CommittedMigration[] { * The committed migrations against the snapshot of the source the active * deployment runs: each needs the same journal entry (idx, when, * breakpoints) and byte-identical SQL there, and the snapshot may have no - * migration the checkout does not commit. A snapshot without a journal has no - * migration. Only that snapshot is evidence. Anything verify cannot read in it - * makes the result unavailable, never a match. + * migration the checkout does not commit. A snapshot that exists without a + * journal has no migration. Only that snapshot is evidence. Anything verify + * cannot read in it, or a snapshot that does not exist, makes the result + * unavailable, never a match. */ async function readDeployedMigrations( ctx: DbContext, @@ -276,7 +300,11 @@ async function readDeployedMigrations( const journalPath = deployedPath(journalFile(folder)); const journal = await exportFile(ctx, journalPath); let deployed: JournalEntry[] = []; - // A snapshot without a journal has no migration. + // A snapshot without a journal has no migration, but a 404 proves that + // only for a snapshot that exists. + if (!journal && !(await workspacePathExists(ctx, snapshot))) { + throw new Error(`the source snapshot ${snapshot} does not exist`); + } if (journal) { let json: unknown; try { @@ -297,9 +325,10 @@ async function readDeployedMigrations( ); if (committed.length === 0) { if (deployed.length === 0) return null; + const them = unknown.length === 1 ? "it" : "them"; return { evidence: "unavailable", - reason: `the deployment has ${unknown.join(", ")}, and this checkout commits no migration: run verify from the app's root, or pull them`, + reason: `the deployment has ${unknown.join(", ")}, and this checkout commits none in config/database/migrations next to databricks.yml: pull ${them}, then run verify again`, }; } const compared = await Promise.all( @@ -374,13 +403,19 @@ function migrationsProblems( return problems; } -/** The app's postgres resource against databricks.yml: same branch and database, and the permission to create its schema. */ +/** + * The app's postgres resource against databricks.yml: same branch and + * database, and the permission to create its schema. `source` is where the + * branch and database come from: `file`, with variable-overrides.json when + * the checkout has one. + */ function bindingProblems( app: DeployedApp, name: string, branch: string, database: string | null, file: string, + source: string, ): string[] { const bound = (app.resources ?? []).flatMap((resource) => resource.postgres ? [resource.postgres] : [], @@ -389,14 +424,14 @@ function bindingProblems( if (!binding) { return [ bound.length > 0 - ? `app ${name} uses branch ${bound.map((postgres) => postgres.branch).join(", ")}, not ${branch} from ${file}: ${DEPLOY} applies ${file}` + ? `app ${name} uses branch ${bound.map((postgres) => postgres.branch).join(", ")}, not ${branch} from ${source}: ${DEPLOY} applies ${source}` : `app ${name} has no postgres resource: ${DEPLOY} adds the one ${file} declares`, ]; } const problems: string[] = []; if (database && binding.database !== database) { problems.push( - `app ${name} uses database ${binding.database ?? "(none)"}, not ${database} from ${file}: ${DEPLOY} applies ${file}`, + `app ${name} uses database ${binding.database ?? "(none)"}, not ${database} from ${source}: ${DEPLOY} applies ${source}`, ); } if (binding.permission !== POSTGRES_PERMISSION) { @@ -525,6 +560,8 @@ async function verifyDeploy( // when it has the file, as the deploy guard reads them. const deploy = target.overridden ?? target; const withFile = target.overridden ? ` with ${target.overridden.file}` : ""; + // Where the branch and database come from. + const source = `${file}${withFile}`; const bound = deploy.apps.filter((app) => app.postgres.length > 0); if (bound.length > 1) { throw new Error( @@ -603,13 +640,13 @@ async function verifyDeploy( const branchId = resourceId(branch); if (!branchFound) { return stopped(name, [ - `${file} deploys to ${branch}, which does not exist`, + `${source} deploys to ${branch}, which does not exist`, ]); } const problems: string[] = []; if (database && !databaseFound) { problems.push( - `${file} binds database ${database}, which does not exist on ${branchId}`, + `${source} binds database ${database}, which does not exist on ${branchId}`, ); } if (!deployed) { @@ -619,7 +656,14 @@ async function verifyDeploy( return stopped(name, problems); } - const binding = bindingProblems(deployed, name, branch, database, file); + const binding = bindingProblems( + deployed, + name, + branch, + database, + file, + source, + ); problems.push(...binding, ...runningProblems(deployed, name)); const sp = deployed.service_principal_client_id; const [roles, migrations] = await Promise.all([ diff --git a/packages/shared/src/cli/commands/db/verify.ts b/packages/shared/src/cli/commands/db/verify.ts index 944a093cd..1d9f0ab90 100644 --- a/packages/shared/src/cli/commands/db/verify.ts +++ b/packages/shared/src/cli/commands/db/verify.ts @@ -50,9 +50,12 @@ branch's database. It checks that the target's app exists, that its postgres resource names the branch and database in databricks.yml with CAN_CONNECT_AND_CREATE, that its service principal has a role on the branch, that the app is running, and that the source its active deployment runs has -every committed migration, with the same journal entry and SQL. When verify -cannot read that source, it fails. It refuses when the target's -workspace.host is not the workspace this shell is authenticated against. +every committed migration, with the same journal entry and SQL, and no +migration this checkout does not commit. When the checkout has +.databricks/bundle//variable-overrides.json, the branch and database +come from it, as a deploy from this checkout uses them. When verify cannot +read that source, it fails. It refuses when the target's workspace.host is +not the workspace this shell is authenticated against. Exits 1 on any finding. Nothing is written or created. From ea91fbf24ecacef1ead058cb432f9b93384752f5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 18:28:47 +0000 Subject: [PATCH 051/317] fix(appkit): name the unresolved reference in verify's warning on any branch refusesEveryBranch is now the guard's every-branch refusal text, not a flag. The warning prints it after the branch's own reason, so a .env on the default or a protected branch still names the reference and its file, and it lists introspect among the commands that refuse. Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 78 +++++++++++-------- .../appkit/src/database/tooling/verify.ts | 13 ++-- packages/shared/src/cli/commands/db/output.ts | 2 +- .../src/cli/commands/db/tooling-contract.ts | 2 +- .../shared/src/cli/commands/db/verify.test.ts | 46 +++++++---- 5 files changed, 87 insertions(+), 54 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 9008958c6..d0532c944 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -184,7 +184,7 @@ describe("runVerify", () => { ]; const clean = { notYours: null, - refusesEveryBranch: false, + refusesEveryBranch: null, schemaProblems: [], pendingMigrations: [], strandedMigrations: [], @@ -302,43 +302,57 @@ describe("runVerify", () => { expect(await runVerify(ctx)).toMatchObject({ branch: "projects/p/branches/production", notYours: "it is the project's default branch", - refusesEveryBranch: false, + refusesEveryBranch: null, ok: true, }); }); - test("a reference databricks.yml leaves unresolved refuses every branch, and the report says so", async () => { - const ctx = app(two); - branch({ - columns: { notes: ["id", "body"] }, - recorded: recordedAs(ctx, two), - }); - const reason = - 'databricks.yml may deploy to it: the files do not resolve resources.apps.app.resources[0].postgres.branch in target default ("projects/p/branches/dev-${workspace.current_user.short_name}"); give it a value in databricks.yml'; - resolveEnvBranch.mockResolvedValue({ - branch: { name: BRANCH }, - boundary: { - branches: new Set(), - unresolved: [ - { - target: "default", - at: "resources.apps.app.resources[0].postgres.branch", - written: - "projects/p/branches/dev-${workspace.current_user.short_name}", - }, - ], + test.each([ + [ + "your dev branch", + { + kind: "deploy-target", + reason: + "databricks.yml may deploy to it through a reference this checkout's files do not resolve", }, - kind: "deploy-target", - reason, - }); + ], + [ + "the default branch", + { kind: "default", reason: "it is the project's default branch" }, + ], + ] as const)( + "a reference databricks.yml leaves unresolved refuses every branch, and the report names it, on %s", + async (_label, classification) => { + const ctx = app(two); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + }); + resolveEnvBranch.mockResolvedValue({ + branch: { name: BRANCH }, + boundary: { + branches: new Set(), + unresolved: [ + { + target: "default", + at: "variables.postgres_branch", + written: "", + file: ".databricks/bundle/default/variable-overrides.json", + }, + ], + }, + ...classification, + }); - expect(await runVerify(ctx)).toMatchObject({ - branch: BRANCH, - notYours: reason, - refusesEveryBranch: true, - ok: true, - }); - }); + expect(await runVerify(ctx)).toMatchObject({ + branch: BRANCH, + notYours: classification.reason, + refusesEveryBranch: + "The files do not resolve variables.postgres_branch in target default with .databricks/bundle/default/variable-overrides.json (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 or the variable-overrides.json named", + ok: true, + }); + }, + ); test("no committed migrations: only the schema is checked", async () => { const ctx = app(); diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 13281a2e5..8ed4c840a 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -17,7 +17,7 @@ import { } from "../migrations/paths"; import type { DataPath } from "../runtime"; import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context"; -import { resolveEnvBranch, takesWrites } from "./guard"; +import { everyBranchRefusal, resolveEnvBranch, takesWrites } from "./guard"; import { requireSchemaFile } from "./migrate"; import { type BundleTarget, @@ -40,10 +40,13 @@ interface LocalVerifyReport { /** Why the branch is not your dev or session branch, e.g. "it is the project's default branch"; null when it is. */ readonly notYours: string | null; /** - * databricks.yml has a reference this checkout's files do not resolve, so - * migrate, clean, seed and init refuse every branch until it has a value. + * While databricks.yml has a reference this checkout's files do not + * resolve, `migrate` applies migrations to no branch, and `init`, + * `introspect`, `clean` and `seed` refuse every branch: this says so and + * names the references and where to give them values. null when every + * reference resolves. */ - readonly refusesEveryBranch: boolean; + readonly refusesEveryBranch: string | null; /** Declared tables or columns the branch lacks (the plugin's startup check). */ readonly schemaProblems: readonly string[]; /** Committed migrations the branch has not run yet, newer than every one it ran. */ @@ -132,7 +135,7 @@ async function verifyLocal(ctx: DbContext): Promise { kind: "local", branch, notYours: takesWrites(env.kind) ? null : (env.reason ?? null), - refusesEveryBranch: env.boundary.unresolved.length > 0, + refusesEveryBranch: everyBranchRefusal(env.boundary), schemaProblems, pendingMigrations: drift.pending, strandedMigrations: drift.stranded, diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index bf6475fca..5537627a3 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -122,7 +122,7 @@ function printLocalVerifyReport(report: LocalVerifyReport): void { if (report.notYours) { warn( report.refusesEveryBranch - ? `${branch} takes no writes (${report.notYours}). Until databricks.yml's references have values, \`appkit db migrate\`, \`clean\`, \`seed\` and \`init\` refuse every branch.` + ? `${branch} takes no writes (${report.notYours}). ${report.refusesEveryBranch}.` : `.env points at ${branch}, not a branch \`appkit db init\` set up for you: ${report.notYours}. \`npx appkit db init\` points it at a branch of your own.`, ); } diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index b5ba6f070..4973b3e78 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -76,7 +76,7 @@ export interface LocalVerifyReport { readonly kind: "local"; readonly branch: string; readonly notYours: string | null; - readonly refusesEveryBranch: boolean; + readonly refusesEveryBranch: string | null; readonly schemaProblems: readonly string[]; readonly pendingMigrations: readonly string[]; readonly strandedMigrations: readonly string[]; diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index fef6c161c..6c0fa057c 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -33,7 +33,7 @@ const local = { kind: "local" as const, branch: "projects/p/branches/dev-alice-3f9a2c", notYours: null, - refusesEveryBranch: false, + refusesEveryBranch: null, schemaProblems: [], pendingMigrations: [], strandedMigrations: [], @@ -104,22 +104,38 @@ describe("appkit db verify", () => { expect(process.exitCode).toBeUndefined(); }); - test("while databricks.yml leaves a reference unresolved, the warning says every branch refuses writes, not to run init", async () => { - runVerify.mockResolvedValue({ - ...local, - notYours: - "databricks.yml may deploy to it: the files do not resolve variables.postgres_branch in target default (no value); give it a value in databricks.yml", - refusesEveryBranch: true, - }); + test.each([ + [ + "dev-alice-3f9a2c", + "projects/p/branches/dev-alice-3f9a2c", + "databricks.yml may deploy to it through a reference this checkout's files do not resolve", + ], + [ + "production", + "projects/p/branches/production", + "it is the project's default branch", + ], + ])( + "while databricks.yml leaves a reference unresolved, the warning on %s names it and gives no init advice", + async (shown, branch, notYours) => { + const refusesEveryBranch = + "The files do not resolve variables.postgres_branch in target default with .databricks/bundle/default/variable-overrides.json (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 or the variable-overrides.json named"; + runVerify.mockResolvedValue({ + ...local, + branch, + notYours, + refusesEveryBranch, + }); - await dbCommand.parseAsync(["verify"], { from: "user" }); + await dbCommand.parseAsync(["verify"], { from: "user" }); - expect(output(log)).toContain( - "dev-alice-3f9a2c takes no writes (databricks.yml may deploy to it: the files do not resolve variables.postgres_branch in target default (no value); give it a value in databricks.yml). Until databricks.yml's references have values, `appkit db migrate`, `clean`, `seed` and `init` refuse every branch.", - ); - expect(output(log)).not.toContain("npx appkit db init"); - expect(process.exitCode).toBeUndefined(); - }); + expect(output(log)).toContain( + `${shown} takes no writes (${notYours}). ${refusesEveryBranch}.`, + ); + expect(output(log)).not.toContain("npx appkit db init"); + expect(process.exitCode).toBeUndefined(); + }, + ); test("prints every schema problem and pending migration, and exits 1", async () => { runVerify.mockResolvedValue({ From 63e8e9bbefff4a277a2cce1a5e4732baa8d27947 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 18:28:52 +0000 Subject: [PATCH 052/317] docs(appkit): describe verify --deployed's overrides and unknown-migration checks verify --deployed reads the branch from variable-overrides.json and fails on a deployed migration the checkout does not commit. On a branch that takes no writes, migrate also regenerates shared/appkit-types/database.d.ts. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 87eeeb048..b514aec9c 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -181,7 +181,8 @@ 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. +deploys to, `clean` and `seed` refuse, and `migrate` only writes the migration +files and `shared/appkit-types/database.d.ts`. A typical change: @@ -335,9 +336,13 @@ databricks postgres delete-role projects//branches//roles//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. When verify cannot read that source, it fails and +says 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. It needs no @@ -354,9 +359,9 @@ 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, and when +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. +same SQL, and when the deployment has a migration this checkout does not commit. ## Schema discovery and overrides From 17f9542c4a4fb2bcf9f73e75d5f43edc232cfa95 Mon Sep 17 00:00:00 2001 From: ditadi Date: Fri, 30 Oct 2026 18:31:32 +0000 Subject: [PATCH 053/317] fix(appkit): fail db check on a snapshot that is not drizzle-kit's A snapshot file holding null, or an object without id and prevId, was taken as no link, so check skipped the chain and the schema diff and could pass a schema.ts change without a migration. Check now accepts a snapshot only with string id and prevId, and otherwise reports it. --help and the docs also list the idx check. Signed-off-by: ditadi --- docs/docs/plugins/database.md | 5 ++-- packages/appkit/src/database/tooling/check.ts | 15 +++++++++--- .../src/database/tooling/tests/check.test.ts | 24 +++++++++++++++++++ packages/shared/src/cli/commands/db/check.ts | 5 ++-- 4 files changed, 42 insertions(+), 7 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 5b0c21a3c..2b7aba887 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -367,8 +367,9 @@ exits 1 when: - 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; -- a migration's `.sql` or snapshot is not committed, or a `.sql` is not in the - journal. +- an entry's `idx` is not its position in the journal; +- 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 diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts index 85ba2c61a..408bf4adc 100644 --- a/packages/appkit/src/database/tooling/check.ts +++ b/packages/appkit/src/database/tooling/check.ts @@ -91,11 +91,20 @@ export async function runCheck(ctx: DbContext): Promise { const entries = readJournal(folder)?.entries ?? []; const problems = orderProblems(entries); - const links = entries.map((entry) => { + const links = entries.map((entry): SnapshotLink | null => { const file = snapshotFile(folder, entry.idx); - if (fs.existsSync(file)) return readJsonFile(file); + 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 link = readJsonFile | null>(file); + if (typeof link?.id === "string" && typeof link.prevId === "string") { + return { id: link.id, prevId: link.prevId }; + } problems.push( - `${shown(file)}, the snapshot of ${entry.tag}, is not committed. Restore it from version control: the next migration is generated from it.`, + `${shown(file)}, the snapshot of ${entry.tag}, is not a drizzle-kit snapshot. Restore it from version control.`, ); return null; }); diff --git a/packages/appkit/src/database/tooling/tests/check.test.ts b/packages/appkit/src/database/tooling/tests/check.test.ts index 44d22596b..498fed14e 100644 --- a/packages/appkit/src/database/tooling/tests/check.test.ts +++ b/packages/appkit/src/database/tooling/tests/check.test.ts @@ -257,6 +257,30 @@ describe("runCheck", () => { ]); }); + test.each([ + ["null", "null"], + ["an object without id and prevId", "{}"], + ])( + "a latest snapshot that holds %s fails, and the schema is not compared from it", + async (_label, content) => { + // schema.ts has a change with no migration; check must not pass it. + const ctx = app({ ...notes, extra: { id: "id" } }); + await generate(migrations(ctx), notes); + await generate(migrations(ctx), withTags); + fs.writeFileSync( + path.join(migrations(ctx), "meta/0001_snapshot.json"), + content, + ); + + const report = await runCheck(ctx); + + expect(report.problems).toEqual([ + `${path.join("config/database/migrations/meta/0001_snapshot.json")}, the snapshot of 0001_migration, is not a drizzle-kit snapshot. Restore it from version control.`, + ]); + expect(report.ok).toBe(false); + }, + ); + test("without schema.ts it points to introspect", async () => { const ctx = app({}); fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); diff --git a/packages/shared/src/cli/commands/db/check.ts b/packages/shared/src/cli/commands/db/check.ts index 943c808e5..4b0094364 100644 --- a/packages/shared/src/cli/commands/db/check.ts +++ b/packages/shared/src/cli/commands/db/check.ts @@ -25,8 +25,9 @@ Reads only the checkout, so it needs no Databricks or Lakebase access, only the app's installed dependencies (drizzle-kit included). It fails when: - the journal lists a migration generated before the one listed ahead of it; - two migrations were generated from the same snapshot on parallel branches; - - a migration's .sql or snapshot is not committed, or a .sql is not in the - journal; + - an entry's idx is not its position in the journal; + - 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; - schema.ts changed and no committed migration has the change. Exits 1 on any finding. Nothing is written. From b1af872272c321dfe61b495c37f41a039400fd42 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:04:46 +0000 Subject: [PATCH 054/317] test(appkit): verify --deployed must fail when the app reports no service principal An app whose API response has no or an empty service_principal_client_id skipped the role check and could report ok. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index f79a12b9a..12406723f 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -985,6 +985,24 @@ describe("runVerify --deployed", () => { ]); }); + test.each([ + ["none", { service_principal_client_id: undefined }], + ["an empty one", { service_principal_client_id: "" }], + ])( + "an app whose API response has %s for a service principal fails: its role cannot be checked", + async (_label, overrides) => { + const { ctx, lakebase } = deployedApp({ app: runningApp(overrides) }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + problems: [ + "the API reports no service principal for app my-app, so verify cannot tell whether it has a Postgres role on production: `databricks apps get my-app` shows the app; run verify again once it has one", + ], + ok: false, + }); + expect(lakebase.calls).not.toContain(`listRoles ${PRODUCTION}`); + }, + ); + test.each([ [ "crashed", From 19c6f3cc5bd7c7a8c3fa6e51fbe9ac8b187bf27a Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:05:05 +0000 Subject: [PATCH 055/317] docs: limit the rollback promise to code that works with the current schema Redeploying an older commit applies nothing, and the startup check then fails when a table or column that commit declares is gone. A migration that drops or renames one ends rollbacks to the commits that need it, so the docs no longer promise that two-step changes keep every older commit starting. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index b514aec9c..9d347babb 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -295,10 +295,18 @@ only some of them exist, the app does not start, and nothing is changed. 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, applies nothing, and starts. The older code must work with the -newer schema, which [two-step changes](#changing-tables-in-use) guarantee. To undo -a schema change, commit a new migration that reverses it, and deploy it. +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. + +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 From 7fa3b013f939b37b67eb4e76b1fb683c4768f716 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:05:22 +0000 Subject: [PATCH 056/317] docs: describe init's rebuilt app schema and introspect's schema choice A branch db init creates now starts with the app schema rebuilt from the committed migrations, or from the baseline introspect writes, so it holds no copied rows. --schema migrate keeps them. Existing apps with a schema.ts adopt their tables with init --schema introspect, because a plain init on a new branch drops tables the migrations do not create. Introspect reads the schema that schema.ts declares. Without schema.ts, init and introspect read schema app, so an app on public runs init --schema none and then introspect --schema-name public. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 47 ++++++++++++++++++++++++----------- template/README.md.tmpl | 11 +++++--- 2 files changed, 41 insertions(+), 17 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 9d347babb..a37803b83 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -141,10 +141,16 @@ you picked in its prompts, usually the branch the app deploys to, and 2. It makes sure the branch has an endpoint and your Postgres role, points `.env` at the branch, and hands you the app schema the fork copied (see [One owner per branch](#one-owner-per-branch)). -3. It sets up the schema. With `schema.ts` it runs `migrate`: it writes a - migration when `schema.ts` changed since the last one, then applies the - committed migrations. Without `schema.ts`, it writes `schema.ts` from the - branch's tables (`introspect`). +3. It sets up the schema. On a branch it created in this run, it drops the app + schema the fork copied 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. In schema `public` it drops + only the tables you own, and lists the tables that keep their copied rows. + On a branch it reuses, it 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`. `--schema clean` drops the app schema first. Without a terminal, `--schema clean` needs `--yes`. `--schema none` only sets up the branch and `.env`: it reads no `schema.ts`, hands over no schema, and leaves the schema @@ -158,11 +164,13 @@ branch `databricks.yml` deploys to, and never edits `databricks.yml`. :::caution[A new branch copies the default branch] New branches fork the project's default branch, so they start with a copy of its -rows, production data included. 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 default branch holds only data every developer may see. +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 default branch holds only data every +developer may see. ::: ### Commands @@ -280,13 +288,24 @@ only some of them exist, the app does not start, and nothing is changed. - **Tables created by hand or by earlier code.** Without `schema.ts`, `npx appkit db init` creates your dev branch from the project's default branch and - introspects it: it writes `schema.ts` from the tables there and a `0000_baseline` - migration. With a `schema.ts` already, run `npx appkit db introspect` on your - branch. Commit both files: the deployed app records the baseline without running - it, because the tables already exist on the deploy branch. + introspects it. It writes `schema.ts` from the tables in schema `app` and a + `0000_baseline` migration. When init created the branch in this run, it then + rebuilds schema `app` 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. + 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. diff --git a/template/README.md.tmpl b/template/README.md.tmpl index 32b763e8b..6cf56ce89 100644 --- a/template/README.md.tmpl +++ b/template/README.md.tmpl @@ -65,7 +65,11 @@ npx appkit db init --session # a branch for this checkout that expires after 7 npx appkit db init --dev # back to your dev branch ``` -A new branch starts with a copy of the default branch's rows, production data included. +A new branch is a copy of the default branch, production data included. When +`db init` creates the branch, it rebuilds the app schema from the committed +migrations, so its tables start empty. Other schemas keep the copied rows. +To keep the copied rows in the app schema too, create the branch with +`npx appkit db init --schema migrate`. To change the schema, edit `config/database/schema.ts`, then: @@ -76,8 +80,9 @@ npx appkit db verify # read-only check of your branch against schema.ts and t Commit the migrations. The deployed app applies them on start, because `app.yaml` sets `APPKIT_DB_MIGRATE_ON_START=true`. To adopt tables that already exist, run -`npx appkit db introspect`: it writes `schema.ts` from the branch's tables, and a -`0000_baseline` migration (or `NNNN_introspect` when migrations already exist). +`npx appkit db init --schema introspect`. It writes `schema.ts` from the branch's +tables, and a `0000_baseline` migration (or `NNNN_introspect` when migrations +already exist). `npx appkit db clean` drops the app schema on your branch, and `npx appkit db seed` runs `config/database/seed.sql` on it; both refuse any branch `db init` did not create for you, such as the deployed one. From c0e96dc8f4b0145edfe385b52483a4c3e7acb65d Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:05:26 +0000 Subject: [PATCH 057/317] fix(appkit): fail verify --deployed closed when the app reports no service principal Without a service_principal_client_id the role check was skipped and the report could be ok. A missing id is now a problem that names what to check. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/verify.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 4fb817927..c8c75f856 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -666,6 +666,11 @@ async function verifyDeploy( ); problems.push(...binding, ...runningProblems(deployed, name)); const sp = deployed.service_principal_client_id; + if (!sp) { + problems.push( + `the API reports no service principal for app ${name}, so verify cannot tell whether it has a Postgres role on ${branchId}: \`databricks apps get ${name}\` shows the app; run verify again once it has one`, + ); + } const [roles, migrations] = await Promise.all([ // Only meaningful once the app is bound to this branch. sp && binding.length === 0 ? api.listRoles(branch) : null, From 99df0e4d4f75f9572736a85372f5f553cf783e6d Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:06:07 +0000 Subject: [PATCH 058/317] fix(lint): keep the modular SDK import ban in the appkit overrides The two no-restricted-imports overrides for packages/appkit/src and its database tooling replaced the base rule's options, which allowed direct @databricks/sdk-* imports anywhere in appkit. Each override now carries the base group and message alongside its own patterns. Co-authored-by: Isaac Signed-off-by: ditadi --- .oxlintrc.json | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index f874def12..09492ed41 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -67,11 +67,8 @@ { "patterns": [ { - "group": [ - "@databricks/sdk-experimental", - "@databricks/sdk-experimental/**" - ], - "message": "Import the Databricks SDK only through the wrapper in packages/shared/src/workspace-client. Add a re-export there if you need a new symbol." + "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/**"], @@ -98,11 +95,8 @@ { "patterns": [ { - "group": [ - "@databricks/sdk-experimental", - "@databricks/sdk-experimental/**" - ], - "message": "Import the Databricks SDK only through the wrapper in packages/shared/src/workspace-client. Add a re-export there if you need a new symbol." + "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." } ] } From a376662884e41fbb63485d94bb9fccb1ce9cf861 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:06:52 +0000 Subject: [PATCH 059/317] test(appkit): verify --deployed must refuse a workspace.host the files do not resolve An unresolved host read as null, so the check that the shell is on the target's workspace was skipped. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/targets.test.ts | 27 ++++++++++++++++--- .../src/database/tooling/tests/verify.test.ts | 24 +++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index ac742b2a3..bb925a78c 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -394,13 +394,15 @@ targets: }); describe("readBundle", () => { - test("resolves each target's app name and host; a name only a deploy resolves is null", () => { + test("resolves each target's app name and host; a name only a deploy resolves is null, and so is a host no file declares", () => { const root = tempApp({ "databricks.yml": `bundle: name: shop variables: suffix: default: dev + host: + description: workspace host, set per deploy workspace: host: https://dev.cloud.databricks.com resources: @@ -420,6 +422,9 @@ targets: apps: app: name: shop-\${workspace.current_user.short_name} + elsewhere: + workspace: + host: \${var.host} `, }); @@ -438,21 +443,21 @@ targets: ).toEqual([ { name: "default", - host: "https://dev.cloud.databricks.com", + host: { kind: "resolved", name: "https://dev.cloud.databricks.com" }, apps: [ { declaredName: "${bundle.name}-${var.suffix}", name: "shop-dev" }, ], }, { name: "prod", - host: "https://prod.cloud.databricks.com", + host: { kind: "resolved", name: "https://prod.cloud.databricks.com" }, apps: [ { declaredName: "${bundle.name}-${var.suffix}", name: "shop-prod" }, ], }, { name: "mine", - host: "https://dev.cloud.databricks.com", + host: { kind: "resolved", name: "https://dev.cloud.databricks.com" }, apps: [ { declaredName: "shop-${workspace.current_user.short_name}", @@ -460,6 +465,20 @@ targets: }, ], }, + { + name: "elsewhere", + host: { kind: "unresolved", written: "${var.host}" }, + apps: [ + { declaredName: "${bundle.name}-${var.suffix}", name: "shop-dev" }, + ], + }, + ]); + + const noHost = tempApp({ + "databricks.yml": "resources:\n apps:\n app:\n name: my-app\n", + }); + expect(readBundle(noHost)?.targets.map((target) => target.host)).toEqual([ + null, ]); }); }); diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 12406723f..73b7f04fa 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -906,6 +906,30 @@ describe("runVerify --deployed", () => { }); }); + test("a workspace.host the checkout's files do not resolve is refused before any API call, naming where to set it", async () => { + const { ctx, lakebase, requests } = deployedApp({ + yml: ymlWithHost("${var.host}"), + // Any check against this shell's workspace would pass here, so a pass would mean the check was skipped. + authenticatedHost: "https://other.cloud.databricks.com", + }); + + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + 'No target workspace: workspace.host in target default is "${var.host}", which this checkout\'s files do not resolve to a host. Give the variable it names a value in databricks.yml, or in .databricks/bundle/default/variable-overrides.json, then rerun.', + ); + expect(requests).toEqual([]); + expect(lakebase.calls).toEqual([]); + + const overrides = path.join( + ctx.root, + ".databricks/bundle/default/variable-overrides.json", + ); + fs.mkdirSync(path.dirname(overrides), { recursive: true }); + fs.writeFileSync(overrides, JSON.stringify({ host: HOST })); + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + `Target default deploys to ${HOST}, but this shell is authenticated against https://other.cloud.databricks.com.`, + ); + }); + test("a host written without a scheme or with a trailing slash matches", async () => { const { ctx } = deployedApp({ yml: ymlWithHost("acme.cloud.databricks.com/"), From 7c63f372ce8c9cf9433266b2a97ef8016a792b6c Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:07:06 +0000 Subject: [PATCH 060/317] test(appkit): pin that migrate-on-start refuses an app whose tables are still in public An app upgraded from a release that put tables in public, still on the default schema app, has public.notes with its rows and no app.notes. migrateOnStart applies the committed migrations before assertSchemaMatchesDatabase runs, so the first migration creates an empty app.notes, the check then passes, and the app serves the empty table. The advice about tables in public never shows. Pin the refusal: with the default schema, none of the declared tables in app and some in public, startup fails before anything is applied. An explicit schemaName "app", or a declared table already in app, still migrates. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tests/migrate-on-start.test.ts | 70 ++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index a1aaa09a3..cec09be78 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -25,7 +25,7 @@ const schema = defineSchema(({ table }) => ({ notes: table("notes", { id: id() }), })); const roots: string[] = []; -const pool = { connect: vi.fn() }; +const pool = { connect: vi.fn(), query: vi.fn() }; const deployEnv = { LAKEBASE_ENDPOINT: "projects/p/branches/production/endpoints/primary", PGHOST: "ep-abc.database.cloud.databricks.com", @@ -64,6 +64,9 @@ beforeEach(async () => { applyPendingMigrations.mockReset(); applyPendingMigrations.mockImplementation(actual.applyPendingMigrations); pool.connect.mockReset(); + pool.query.mockReset(); + // A fresh database: the catalog holds none of the declared tables anywhere. + pool.query.mockResolvedValue({ rows: [] }); }); afterEach(() => { @@ -257,3 +260,68 @@ describe("migrateOnStart", () => { ).rejects.toBe(raw); }); }); + +describe("migrateOnStart: tables an earlier release left in public", () => { + // An upgraded app: public.notes holds its rows, app.notes does not exist. + const notesInPublic = { + rows: [{ schema_name: "public", table_name: "notes" }], + }; + + test("the default schema and every declared table in public: refused, nothing applied", async () => { + pool.query.mockResolvedValue(notesInPublic); + applyPendingMigrations.mockResolvedValueOnce(nothingDone); + + const error = await migrateOnStart( + pool, + schema, + appRootWithMigrations(), + deployEnv, + ).catch((caught: unknown) => caught); + + expect(applyPendingMigrations).not.toHaveBeenCalled(); + expect(error).toBeInstanceOf(DatabasePluginError); + expect(error).toMatchObject({ category: "SETUP_FAILED", phase: "setup" }); + expect((error as Error).message).toContain("public has notes"); + expect((error as Error).message).toContain( + 'pass { schemaName: "public" } as the second argument of defineSchema()', + ); + }); + + test('schemaName "app" named explicitly is migrated, whatever public holds', async () => { + const explicit = defineSchema( + ({ table }) => ({ notes: table("notes", { id: id() }) }), + { schemaName: "app" }, + ); + pool.query.mockResolvedValue(notesInPublic); + applyPendingMigrations.mockResolvedValueOnce(nothingDone); + vi.spyOn(console, "log").mockImplementation(() => undefined); + + await migrateOnStart(pool, explicit, appRootWithMigrations(), deployEnv); + + expect(applyPendingMigrations).toHaveBeenCalledTimes(1); + }); + + test("a declared table already in app: migrated, whatever public holds", async () => { + pool.query.mockResolvedValue({ + rows: [ + { schema_name: "app", table_name: "notes" }, + { schema_name: "public", table_name: "notes" }, + ], + }); + applyPendingMigrations.mockResolvedValueOnce(nothingDone); + vi.spyOn(console, "log").mockImplementation(() => undefined); + + await migrateOnStart(pool, schema, appRootWithMigrations(), deployEnv); + + expect(applyPendingMigrations).toHaveBeenCalledTimes(1); + }); + + test("no committed journal: nothing to apply, so the catalog is not consulted", async () => { + vi.spyOn(console, "log").mockImplementation(() => undefined); + pool.query.mockResolvedValue(notesInPublic); + + await migrateOnStart(pool, schema, appRoot(), deployEnv); + + expect(pool.query).not.toHaveBeenCalled(); + }); +}); From 7962800a31aa77b491127218fd433e6601af9834 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:07:09 +0000 Subject: [PATCH 061/317] test(appkit): pin db check on when, the first snapshot's origin and gutted snapshots Failing first. check accepted a journal entry with no integer when, a first snapshot whose prevId is not drizzle-kit's empty starting snapshot, and an earlier snapshot holding only id and prevId. It also named a first migration merged in from a parallel branch as generated after an uncommitted snapshot. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/check.test.ts | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/check.test.ts b/packages/appkit/src/database/tooling/tests/check.test.ts index 498fed14e..3f1a854f3 100644 --- a/packages/appkit/src/database/tooling/tests/check.test.ts +++ b/packages/appkit/src/database/tooling/tests/check.test.ts @@ -19,6 +19,7 @@ const roots: string[] = []; type Columns = Record; type Tables = Record; +type Snapshot = Record; function writeSchema(root: string, tables: Tables): void { const file = path.join(root, "config/database/schema.ts"); @@ -281,6 +282,113 @@ describe("runCheck", () => { }, ); + const badWhen: [string, unknown, string][] = [ + ["missing", undefined, "missing"], + ["a date string", "2026-10-01T00:00:00Z", '"2026-10-01T00:00:00Z"'], + ["a fraction", 1.5, "1.5"], + ]; + test.each(badWhen)( + "a first entry whose when is %s fails, and the next entry is not ordered against it", + async (_label, when, shown) => { + const ctx = app(withTags); + await generate(migrations(ctx), notes); + await generate(migrations(ctx), withTags); + editJournal(migrations(ctx), (journal) => { + const [first] = journal.entries; + if (first) Object.assign(first, { when }); + }); + + expect((await runCheck(ctx)).problems).toEqual([ + expect.stringContaining( + `The when of 0000_migration in meta/_journal.json is ${shown}, not an integer timestamp, so the migrator never runs it.`, + ), + ]); + }, + ); + + test("a first migration not generated from an empty database fails, since the ones before it are missing", async () => { + const ctx = app(withTags); + const folder = migrations(ctx); + await generate(folder, notes); + await generate(folder, withTags); + // A truncated history: 0000 dropped and 0001 renumbered into its place. + fs.rmSync(path.join(folder, "0000_migration.sql")); + fs.rmSync(path.join(folder, "meta/0000_snapshot.json")); + fs.renameSync( + path.join(folder, "0001_migration.sql"), + path.join(folder, "0000_migration.sql"), + ); + fs.renameSync( + path.join(folder, "meta/0001_snapshot.json"), + path.join(folder, "meta/0000_snapshot.json"), + ); + editJournal(folder, (journal) => { + const second = journal.entries[1]; + if (!second) throw new Error("no second migration"); + journal.entries = [{ ...second, idx: 0, tag: "0000_migration" }]; + }); + + expect((await runCheck(ctx)).problems).toEqual([ + "0000_migration 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.", + ]); + }); + + test("a first migration merged in from a parallel branch is reported as generated from an empty database", async () => { + const ctx = app(withTags); + const main = migrations(ctx); + const parallel = path.join(ctx.root, "parallel/config/database/migrations"); + fs.mkdirSync(parallel, { recursive: true }); + await generate(main, notes); + await generate(parallel, withTags); + fs.copyFileSync( + path.join(parallel, "0000_migration.sql"), + path.join(main, "0001_migration.sql"), + ); + fs.copyFileSync( + path.join(parallel, "meta/0000_snapshot.json"), + path.join(main, "meta/0001_snapshot.json"), + ); + const merged = readJournal(parallel)?.entries[0]; + if (!merged) throw new Error("no parallel migration"); + editJournal(main, (journal) => { + const [first] = journal.entries; + if (!first) throw new Error("no first migration"); + journal.entries.push({ + ...merged, + idx: 1, + tag: "0001_migration", + when: first.when + 1, + }); + }); + + expect((await runCheck(ctx)).problems).toEqual([ + expect.stringContaining( + "0001_migration was generated from an empty database, not after 0000_migration: they were written on parallel branches, so 0001_migration lacks the other's changes.", + ), + ]); + }); + + const gutted: [string, (snapshot: Snapshot) => unknown][] = [ + ["only its id and prevId", ({ id, prevId }) => ({ id, prevId })], + ["version 6", (snapshot) => ({ ...snapshot, version: "6" })], + ["tables as a list", (snapshot) => ({ ...snapshot, tables: [] })], + ]; + test.each(gutted)( + "an earlier snapshot with %s fails as not drizzle-kit's", + async (_label, gut) => { + const ctx = app(withTags); + await generate(migrations(ctx), notes); + await generate(migrations(ctx), withTags); + const file = path.join(migrations(ctx), "meta/0000_snapshot.json"); + const snapshot: Snapshot = JSON.parse(fs.readFileSync(file, "utf-8")); + fs.writeFileSync(file, JSON.stringify(gut(snapshot))); + + expect((await runCheck(ctx)).problems).toEqual([ + `${path.join("config/database/migrations/meta/0000_snapshot.json")}, the snapshot of 0000_migration, is not a drizzle-kit snapshot. Restore it from version control.`, + ]); + }, + ); + test("without schema.ts it points to introspect", async () => { const ctx = app({}); fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); From a8e04209f776a6dc8a78a3e3f3c062c332f53fbf Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:07:15 +0000 Subject: [PATCH 062/317] test(appkit): a NOT NULL column added without a default breaks the previous release Instances still running the old code insert rows without the column, and a populated table rejects the migration. A default, a generated expression or an identity fills the column, so those additions stay safe. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/tests/migrations.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index 6afff74fe..d13675e38 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -371,10 +371,15 @@ describe("breakingStatements", () => { 'ALTER TABLE "app"."notes" ALTER COLUMN "title" SET NOT NULL;', 'DROP TYPE "app"."mood";', `ALTER TYPE "app"."mood" RENAME VALUE 'sad' TO 'blue';`, + // Old instances insert without it, and a populated table rejects it. + 'ALTER TABLE "app"."notes" ADD COLUMN "title" text NOT NULL;', ]; const safe = [ 'CREATE TABLE "app"."tags" ("id" serial PRIMARY KEY);', 'ALTER TABLE "app"."notes" ADD COLUMN "title" text;', + `ALTER TABLE "app"."notes" ADD COLUMN "title" text DEFAULT 'untitled' NOT NULL;`, + 'ALTER TABLE "app"."notes" ADD COLUMN "words" integer GENERATED ALWAYS AS (length("body")) STORED NOT NULL;', + 'ALTER TABLE "app"."notes" ADD COLUMN "seq" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY (sequence name "app"."notes_seq_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1);', 'ALTER TABLE "app"."notes" ALTER COLUMN "title" DROP NOT NULL;', 'ALTER TABLE "app"."notes" ALTER COLUMN "title" DROP DEFAULT;', 'ALTER TABLE "app"."notes" DROP CONSTRAINT "notes_tag_fk";', From d02267662b60d50d97e3c7ca99d39f6f0c193873 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:07:30 +0000 Subject: [PATCH 063/317] fix(appkit): refuse verify --deployed on a workspace.host the files do not resolve The bundle reader now tells a host no file declares (null) from one it cannot resolve (unresolved, as written). verify refuses the latter before any API call and says where to give the variable a value, so the check that the shell is on the target's workspace is never skipped. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/targets.ts | 29 ++++++++++++++----- .../appkit/src/database/tooling/verify.ts | 12 ++++++-- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 9b555afeb..41f3d2fdf 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -94,12 +94,12 @@ function record(value: unknown): Yaml { } /** - * A branch or database databricks.yml names, as far as the checkout's files - * resolve it. A reference that is not declared at all has no value: the - * binding or variable that holds it is absent instead. + * A branch, database or workspace host databricks.yml names, as far as the + * checkout's files resolve it. A reference that is not declared at all has no + * value: the binding, variable or host that holds it is absent instead. */ type BundleValue = - /** A full resource name, e.g. "projects/p/branches/b". */ + /** A full resource name, e.g. "projects/p/branches/b", or a workspace host. */ | { readonly kind: "resolved"; readonly name: string } /** As written: a `${…}` only a deploy resolves, no value, or not a resource name. */ | { readonly kind: "unresolved"; readonly written: string }; @@ -127,8 +127,8 @@ interface BundleApp { /** What one target binds with one set of variable values. */ interface TargetBindings { - /** workspace.host of the target, else of the bundle; null when neither names one the files resolve. */ - readonly host: string | null; + /** workspace.host of the target, else of the bundle; null when neither declares one. */ + readonly host: BundleValue | null; readonly apps: readonly BundleApp[]; /** The target's postgres_branch variable; null when the bundle declares none. */ readonly postgresBranch: BundleValue | null; @@ -338,6 +338,20 @@ function bundleValue( }; } +/** null when no host is declared; unresolved when one is declared and the files cannot resolve it. */ +function hostValue( + written: unknown, + resolve: (value: unknown) => string | null, +): BundleValue | null { + if (written === undefined) return null; + const name = resolve(written); + if (name) return { kind: "resolved", name }; + return { + kind: "unresolved", + written: typeof written === "string" ? written : "", + }; +} + function bundleApps( apps: Record, resolve: (value: unknown) => string | null, @@ -454,8 +468,9 @@ export function readBundle(root: string): Bundle | null { ) : null; return { - host: resolve( + host: hostValue( record(target?.workspace)?.host ?? record(bundle.workspace)?.host, + resolve, ), apps: bundleApps(apps ?? {}, resolve), postgresBranch: variable("postgres_branch", "branch"), diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index c8c75f856..3f1b40788 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -75,7 +75,7 @@ type DeployedMigrations = interface DeployVerifyReport { readonly kind: "deploy"; readonly target: string; - /** The target's workspace; null when databricks.yml names none. */ + /** The target's workspace; null when databricks.yml declares none. */ readonly host: string | null; readonly branch: string; /** The app the target deploys; null when it declares none. */ @@ -593,8 +593,14 @@ async function verifyDeploy( `No deploy database: ${declared ? `${declared.at}.database` : "variables.postgres_database"} in target ${target.name}${withFile} is "${databaseValue.written}", which this checkout's files do not resolve to a database.`, ); } + if (deploy.host?.kind === "unresolved") { + throw new Error( + `No target workspace: workspace.host in target ${target.name}${withFile} is "${deploy.host.written}", which this checkout's files do not resolve to a host. Give the variable it names a value in ${file}, or in .databricks/bundle/${target.name}/variable-overrides.json, then rerun.`, + ); + } const branch = branchValue.name; const database = databaseValue?.name ?? null; + const host = deploy.host?.name ?? null; const committed = readCommitted(migrationsFolder(ctx.root)); const report = ( name: string | null, @@ -603,7 +609,7 @@ async function verifyDeploy( ): DeployVerifyReport => ({ kind: "deploy", target: target.name, - host: deploy.host, + host, branch, app: name, migrations, @@ -630,7 +636,7 @@ async function verifyDeploy( } const name = app.name; - await assertTargetWorkspace(ctx, target.name, deploy.host); + await assertTargetWorkspace(ctx, target.name, host); const api = ctx.api(); const [branchFound, databaseFound, deployed] = await Promise.all([ api.getBranch(branch), From 29353855e4cb2971eb8db78838b85275040cb964 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:08:29 +0000 Subject: [PATCH 064/317] fix(appkit): flag a NOT NULL column added without a default as breaking BREAKS_PREVIOUS_RELEASE matched only drops, renames, type changes and SET NOT NULL. ADD COLUMN ... NOT NULL with no DEFAULT, generated expression or identity breaks the previous release the same way, so the rules are now predicates and that case is one of them. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrations.ts | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index a7a9e2b63..503578f29 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -254,12 +254,25 @@ async function loadDrizzleKit(): Promise { } } -const BREAKS_PREVIOUS_RELEASE = [ - /^DROP (TABLE|VIEW|MATERIALIZED VIEW|TYPE|SEQUENCE|SCHEMA)\b/i, - /\bDROP COLUMN\b/i, - /\bRENAME\b/i, - /\bSET DATA TYPE\b/i, - /\bSET NOT NULL\b/i, +const matches = (pattern: RegExp) => (statement: string) => + pattern.test(statement); + +/** A new column nothing fills: old instances insert without it, and existing rows have no value for it. */ +function addsRequiredColumn(statement: string): boolean { + return ( + /\bADD COLUMN\b/i.test(statement) && + /\bNOT NULL\b/i.test(statement) && + !/\b(DEFAULT|GENERATED)\b/i.test(statement) + ); +} + +const BREAKS_PREVIOUS_RELEASE: ReadonlyArray<(statement: string) => boolean> = [ + matches(/^DROP (TABLE|VIEW|MATERIALIZED VIEW|TYPE|SEQUENCE|SCHEMA)\b/i), + matches(/\bDROP COLUMN\b/i), + matches(/\bRENAME\b/i), + matches(/\bSET DATA TYPE\b/i), + matches(/\bSET NOT NULL\b/i), + addsRequiredColumn, ]; /** @@ -269,9 +282,7 @@ const BREAKS_PREVIOUS_RELEASE = [ */ export function breakingStatements(statements: readonly string[]): string[] { return statements.filter((statement) => - BREAKS_PREVIOUS_RELEASE.some((pattern) => - pattern.test(statement.trimStart()), - ), + BREAKS_PREVIOUS_RELEASE.some((breaks) => breaks(statement.trimStart())), ); } From 47e0ef6f5c0574582eb0e6cfaca2162616149d22 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:08:46 +0000 Subject: [PATCH 065/317] test(appkit): a deployed journal with duplicate, invalid or reordered entries must not verify Tag membership let [A, B, A], a {} entry and a reordered journal pass as verified. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 73b7f04fa..ee0ca3a11 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -762,6 +762,91 @@ describe("runVerify --deployed", () => { }); }); + test.each([ + [ + "lists a tag twice", + [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_migration", when: 2000 }, + { tag: "0000_migration", when: 1000 }, + ], + `${JOURNAL} lists 0000_migration twice`, + ], + [ + "has an entry that is not a migration", + JSON.stringify({ + version: "7", + dialect: "postgresql", + entries: [ + { idx: 0, version: "7", when: 1000, tag: "0000_migration" }, + { idx: 1, version: "7", when: 2000, tag: "0001_migration" }, + {}, + ], + }), + `entry 2 of ${JOURNAL} is not a migration journal entry`, + ], + ] as const)( + "a deployed journal that %s is unavailable, never a match", + async (_label, deployedJournal, reason) => { + const migrations = [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_migration", when: 2000 }, + ]; + const { ctx } = deployedApp({ + migrations, + deployedJournal: deployedJournal as Migration[] | string, + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { evidence: "unavailable", reason }, + problems: [ + `verify cannot tell whether app my-app's active deployment has the committed migrations: ${reason}`, + ], + ok: false, + }); + }, + ); + + test("the committed entries in another order in the deployed journal differ, even with the same idx and SQL", async () => { + const migrations = [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_migration", when: 2000 }, + ]; + const { ctx } = deployedApp({ + migrations, + deployedJournal: JSON.stringify({ + version: "7", + dialect: "postgresql", + entries: [ + { + idx: 1, + version: "7", + when: 2000, + tag: "0001_migration", + breakpoints: true, + }, + { + idx: 0, + version: "7", + when: 1000, + tag: "0000_migration", + breakpoints: true, + }, + ], + }), + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { + evidence: "differs", + missing: [], + changed: ["0000_migration", "0001_migration"], + unknown: [], + }, + ok: false, + }); + }); + test("a snapshot without a journal lacks every committed migration: deploy them", async () => { const { ctx } = deployedApp({ migrations: [ From 7ba6f5bf11214e889ef699c187c85fbe99a5c186 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:09:01 +0000 Subject: [PATCH 066/317] test(appkit): a discard killed mid-way never leaves a journal naming missing files Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/migrations.test.ts | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index d13675e38..75512194d 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -59,6 +59,7 @@ function listFiles(folder: string): string[] { afterEach(() => { vi.useRealTimers(); + vi.restoreAllMocks(); for (const folder of folders.splice(0)) { fs.rmSync(folder, { recursive: true, force: true }); } @@ -427,6 +428,46 @@ describe("discardMigrationFiles", () => { expect(fs.readFileSync(journalFile, "utf-8")).toBe(journalBefore); }); + /** Discard a migration, killed as it deletes the migration's SQL file. */ + async function discardKilledAtSql( + folder: string, + schema: Parameters[1]["schema"], + ): Promise { + await withHistoryLock(rootOf(folder), "migrate", async (lock) => { + const migration = await generateMigrationFiles(lock, { + schema, + interactive: false, + }); + const rm = fs.rmSync; + vi.spyOn(fs, "rmSync").mockImplementation((target, options) => { + if (target === migration?.file) throw new Error("killed"); + return rm(target, options); + }); + expect(() => discardMigrationFiles(lock, migration as never)).toThrow( + "killed", + ); + }); + } + + test("killed while deleting a later migration's files, it has already put the journal back", async () => { + const folder = tempFolder(); + await generate({ folder, schema: blog(), interactive: false }); + + await discardKilledAtSql(folder, blog({ summary: text() })); + + expect(readJournal(folder)?.entries.map((entry) => entry.tag)).toEqual([ + "0000_migration", + ]); + }); + + test("killed while deleting a first migration's files, it has already removed the journal", async () => { + const folder = tempFolder(); + + await discardKilledAtSql(folder, blog()); + + expect(readJournal(folder)).toBeNull(); + }); + test("a writer whose lock was released removes nothing", async () => { const folder = tempFolder(); let released: Parameters[0] | undefined; From 94fe291c7774fc3edd8fab0f9e833a784fa72053 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:09:21 +0000 Subject: [PATCH 067/317] test(appkit): pin one-to-one reconciliation of migrations sharing a timestamp Two committed migrations with one `when`, neither matching the row recorded at it, are both classified edited today, so the one that never ran is skipped with only a warning. A second recorded row at a committed `when` is reported as neither edited nor unknown. These tests expect each timestamp to be reconciled one to one, and the migrator to refuse when the pairing is ambiguous. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/migrations/tests/apply.test.ts | 24 ++++++ .../database/migrations/tests/history.test.ts | 82 +++++++++++++++++++ 2 files changed, 106 insertions(+) diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 6892e5df0..b065021c9 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -388,6 +388,30 @@ describe("applyPendingMigrations", () => { 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({ + ambiguous: ["0000_a", "0001_b"], + stranded: [], + }); + 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); diff --git a/packages/appkit/src/database/migrations/tests/history.test.ts b/packages/appkit/src/database/migrations/tests/history.test.ts index 367dd605a..8dddcd172 100644 --- a/packages/appkit/src/database/migrations/tests/history.test.ts +++ b/packages/appkit/src/database/migrations/tests/history.test.ts @@ -87,4 +87,86 @@ describe("reconcileMigrations", () => { 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([]); + }); }); From 96e88ae1e0ed5cc35bd2885ed32730fabab3b749 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:09:54 +0000 Subject: [PATCH 068/317] fix(appkit): compare the deployed journal entry by entry, after validating it Each deployed entry must be a migration with a tag, an idx and a when, and no tag may be listed twice; otherwise the journal is unavailable, never a match. When both sides list the same tags, each must also sit at the same place, since the app applies the journal in order. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/verify.ts | 71 +++++++++++++------ 1 file changed, 49 insertions(+), 22 deletions(-) diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 3f1b40788..4b0dcbed5 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -263,14 +263,48 @@ function readCommitted(folder: string): CommittedMigration[] { }); } +/** + * The deployed journal's entries: each a migration with a tag, an idx and a + * when, and no tag listed twice. A journal that breaks that is not evidence + * of anything, so it throws rather than matching. + */ +function parseDeployedJournal(bytes: Buffer, label: string): JournalEntry[] { + let json: unknown; + try { + json = JSON.parse(bytes.toString("utf-8")); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`${label} is not JSON: ${message}`, { cause: error }); + } + const entries = parseJournal(json, label).entries; + const seen = new Set(); + entries.forEach((entry, index) => { + if ( + typeof entry?.tag !== "string" || + !entry.tag || + typeof entry.idx !== "number" || + typeof entry.when !== "number" + ) { + throw new Error( + `entry ${index} of ${label} is not a migration journal entry`, + ); + } + if (seen.has(entry.tag)) { + throw new Error(`${label} lists ${entry.tag} twice`); + } + seen.add(entry.tag); + }); + return entries; +} + /** * The committed migrations against the snapshot of the source the active * deployment runs: each needs the same journal entry (idx, when, - * breakpoints) and byte-identical SQL there, and the snapshot may have no - * migration the checkout does not commit. A snapshot that exists without a - * journal has no migration. Only that snapshot is evidence. Anything verify - * cannot read in it, or a snapshot that does not exist, makes the result - * unavailable, never a match. + * breakpoints, and its place in the journal) and byte-identical SQL there, + * and the snapshot may have no migration the checkout does not commit. A + * snapshot that exists without a journal has no migration. Only that + * snapshot is evidence. Anything verify cannot read in it, or a snapshot + * that does not exist, makes the result unavailable, never a match. */ async function readDeployedMigrations( ctx: DbContext, @@ -305,23 +339,10 @@ async function readDeployedMigrations( if (!journal && !(await workspacePathExists(ctx, snapshot))) { throw new Error(`the source snapshot ${snapshot} does not exist`); } - if (journal) { - let json: unknown; - try { - json = JSON.parse(journal.toString("utf-8")); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - throw new Error(`${journalPath} is not JSON: ${message}`, { - cause: error, - }); - } - deployed = parseJournal(json, journalPath).entries; - } + if (journal) deployed = parseDeployedJournal(journal, journalPath); const committedTags = new Set(committed.map(({ entry }) => entry.tag)); const unknown = deployed.flatMap((entry) => - typeof entry?.tag === "string" && !committedTags.has(entry.tag) - ? [entry.tag] - : [], + committedTags.has(entry.tag) ? [] : [entry.tag], ); if (committed.length === 0) { if (deployed.length === 0) return null; @@ -331,11 +352,17 @@ async function readDeployedMigrations( reason: `the deployment has ${unknown.join(", ")}, and this checkout commits none in config/database/migrations next to databricks.yml: pull ${them}, then run verify again`, }; } + const deployedByTag = new Map(deployed.map((entry) => [entry.tag, entry])); + // The app applies the journal in order, so when both sides list the same + // tags each must also be at the same place. + const sameTags = + unknown.length === 0 && deployed.length === committed.length; const compared = await Promise.all( - committed.map(async ({ entry, sql }) => { - const found = deployed.find((other) => other?.tag === entry.tag); + committed.map(async ({ entry, sql }, index) => { + const found = deployedByTag.get(entry.tag); if (!found) return "missing"; if ( + (sameTags && deployed[index]?.tag !== entry.tag) || found.idx !== entry.idx || found.when !== entry.when || found.breakpoints !== entry.breakpoints From 968c8b71a06de86a0fcf5f04a1d3f2c5c2389cd1 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:10:16 +0000 Subject: [PATCH 069/317] fix(appkit): db check validates when, the first snapshot's origin and every snapshot's shape A journal entry with no integer when was never reported, and the first entry's when was never read, though the migrator orders entries by it and never runs one it cannot compare. The first snapshot's prevId was never compared to drizzle-kit's empty starting snapshot, so a truncated history passed. A snapshot holding only id and prevId passed as drizzle-kit's, so a gutted earlier snapshot went unnoticed. check now requires a safe-integer when on every entry, chains the first snapshot to the origin id, parses every snapshot against the v7 PostgreSQL shape, and names the empty database when a later migration was generated from it. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/check.ts | 62 +++++++++++++++---- .../appkit/src/database/tooling/migrations.ts | 3 +- 2 files changed, 51 insertions(+), 14 deletions(-) diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts index 408bf4adc..501a6cc38 100644 --- a/packages/appkit/src/database/tooling/check.ts +++ b/packages/appkit/src/database/tooling/check.ts @@ -1,6 +1,8 @@ import fs from "node:fs"; import path from "node:path"; +import { z } from "zod"; + import { DEFAULT_SCHEMA_FILE, loadDefaultDatabaseSchema, @@ -15,7 +17,7 @@ import { } from "../migrations/paths"; import type { DbContext } from "./context"; import { requireSchemaFile } from "./migrate"; -import { hasUnmigratedChanges } from "./migrations"; +import { hasUnmigratedChanges, ORIGIN_ID } from "./migrations"; export interface CheckReport { /** Committed migrations, in journal order. */ @@ -37,8 +39,19 @@ function orderProblems(entries: readonly JournalEntry[]): string[] { `${entry.tag} is entry ${index} of meta/_journal.json, but its idx is ${entry.idx}, so drizzle-kit reads another snapshot for it. ${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. ${REWRITE}`, + ); + return; + } const before = entries[index - 1]; - if (before && entry.when <= before.when) { + 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}. ${REWRITE}`, ); @@ -53,10 +66,25 @@ interface SnapshotLink { 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 empty database drizzle-kit diffs the first migration from. */ +const ORIGIN: SnapshotLink = { id: ORIGIN_ID, prevId: "" }; + /** - * Each snapshot must follow the one before it. 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. + * 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[], @@ -65,15 +93,23 @@ function chainProblems( const problems: string[] = []; entries.forEach((entry, index) => { const link = links[index]; - const before = links[index - 1]; + 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 = - parent === -1 - ? "a snapshot that is not committed" - : (entries[parent]?.tag ?? "an earlier snapshot"); + 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 ${after}, not after ${entries[index - 1]?.tag}: they were written on parallel branches, so ${entry.tag} lacks the other's changes. ${REWRITE}`, + `${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. ${REWRITE}`, ); }); return problems; @@ -99,9 +135,9 @@ export async function runCheck(ctx: DbContext): Promise { ); return null; } - const link = readJsonFile | null>(file); - if (typeof link?.id === "string" && typeof link.prevId === "string") { - return { id: link.id, prevId: link.prevId }; + const snapshot = snapshotShape.safeParse(readJsonFile(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.`, diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 1c59a92cd..9b9752c9b 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -77,7 +77,8 @@ export class MigrationRenameAmbiguityError extends Error { /** drizzle-kit's statement separator in v7 migration files. */ const BREAKPOINT = "--> statement-breakpoint\n"; -const ORIGIN_ID = "00000000-0000-0000-0000-000000000000"; +/** id of drizzle-kit's empty starting snapshot, so the prevId of every first migration. */ +export const ORIGIN_ID = "00000000-0000-0000-0000-000000000000"; const TAG_NAME = /^[a-z0-9_]+$/; /** The parts of a drizzle-kit PostgreSQL snapshot this module reads. */ From c63ced779c9246dcba8b3f23ac077fee50e4cfab Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:10:23 +0000 Subject: [PATCH 070/317] fix(appkit): put the journal back before deleting a discarded migration's files discardMigrationFiles deleted the SQL and snapshot first and restored the journal last, so a process killed in between left a journal naming files that no longer existed. The journal is restored (or removed) first, through the same atomic rename, and the unreferenced files go after it. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/migrations.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 503578f29..9302c3309 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -383,15 +383,18 @@ export function discardMigrationFiles( ): void { lock.assertHeld(); const { folder } = lock; + // The journal goes back first, as it is what names the migration: a crash + // after this point leaves files no journal names, never the reverse. + if (migration.journalBefore === null) { + fs.rmSync(journalFile(folder), { force: true }); + } else { + writeFileAtomic(journalFile(folder), migration.journalBefore); + } fs.rmSync(migration.file, { force: true }); fs.rmSync(snapshotFile(folder, Number.parseInt(migration.tag, 10)), { force: true, }); - if (migration.journalBefore !== null) { - writeFileAtomic(journalFile(folder), migration.journalBefore); - return; - } - fs.rmSync(journalFile(folder), { force: true }); + if (migration.journalBefore !== null) return; for (const dir of [metaFolder(folder), folder]) { if (fs.existsSync(dir) && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir); From 0165154ad8aa9283c56b19ca5e49e97f4bcd2616 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:10:46 +0000 Subject: [PATCH 071/317] test(shared): verify's out-of-order message must say the deployed app refuses that history The text said the deployed app skips the migration; deploy fails closed with MigrationHistoryError, and clean + migrate only fixes the local branch. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/shared/src/cli/commands/db/verify.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index e5436e0a0..4726fd728 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -127,7 +127,7 @@ describe("appkit db verify", () => { expect(process.exitCode).toBe(1); }); - test("a migration merged out of order is named, with how to rebuild the branch", async () => { + test("a migration merged out of order is named, with how to regenerate it after the recorded ones", async () => { runVerify.mockResolvedValue({ ...local, strandedMigrations: ["0001_parallel"], @@ -137,11 +137,12 @@ describe("appkit db verify", () => { await dbCommand.parseAsync(["verify"], { from: "user" }); expect(output(log)).toContain( - "Never runs: 0001_parallel: it is older than a migration the branch already ran (merged out of order); the deployed app skips it too once it ran a newer one", + "Never runs: 0001_parallel: it is older than a migration the branch already ran (merged out of order), and the deployed app refuses to start on that history", ); expect(output(error)).toContain( - "`appkit db clean` and then `appkit db migrate` rebuild the branch from this checkout's migrations, in order.", + "Delete its .sql file, snapshot and journal entry, then run `appkit db migrate` to generate the migration again from schema.ts, after the recorded ones.", ); + expect(output(error)).not.toContain("`appkit db clean`"); expect(process.exitCode).toBe(1); }); From c31ddb2578c7183adc6ead63f1ae623584851f11 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:10:57 +0000 Subject: [PATCH 072/317] test(appkit): expect db check's rewrite guidance to start with saving hand-written SQL Failing first. Resetting the migrations to the base branch's and regenerating discards SQL the developer wrote by hand in the conflicting migration, and the guidance did not say so. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/tests/check.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/tests/check.test.ts b/packages/appkit/src/database/tooling/tests/check.test.ts index 3f1a854f3..5a4336a82 100644 --- a/packages/appkit/src/database/tooling/tests/check.test.ts +++ b/packages/appkit/src/database/tooling/tests/check.test.ts @@ -197,7 +197,7 @@ describe("runCheck", () => { expect(report.problems).toEqual([ expect.stringContaining( - "0002_migration was generated after 0000_migration, not after 0001_migration: they were written on parallel branches, so 0002_migration lacks the other's changes. Merge the base branch, reset the migrations to its own", + "0002_migration was generated after 0000_migration, not after 0001_migration: they were written on parallel branches, so 0002_migration lacks the other's changes. Save any SQL you wrote by hand in your migration. Merge the base branch, reset the migrations to its own", ), "config/database/schema.ts changed since 0002_migration, so the deployed app would not get the change. Run `appkit db migrate` and commit the migration it writes.", ]); From 7dbab0487a12b38c13be8bbc5967ff8f9819e00b Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:11:34 +0000 Subject: [PATCH 073/317] fix(shared): say the deployed app refuses an out-of-order migration history verify said the deployed app skips a migration merged out of order, and pointed at clean + migrate, which only rebuilds the local branch. Deploy fails closed with MigrationHistoryError, so verify now gives that error's guidance: regenerate the migration after the recorded ones. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/shared/src/cli/commands/db/output.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index ca814d8ad..e613222b6 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -110,7 +110,12 @@ function localVerifyHint(report: LocalVerifyReport): string { if (report.unknownMigrations > 0) { return `${REBUILD}. If the branch ran migrations you have not pulled yet, pull them instead.`; } - if (report.strandedMigrations.length > 0) return `${REBUILD}.`; + // The same guidance the deployed app's MigrationHistoryError gives: the + // history itself is wrong, so rebuilding the local branch would not fix it. + if (report.strandedMigrations.length > 0) { + const its = report.strandedMigrations.length === 1 ? "its" : "their"; + return `Delete ${its} .sql file, snapshot and journal entry, then run \`appkit db migrate\` to generate the migration again from schema.ts, after the recorded ones.`; + } // Pending migrations explain the gap; without them, schema.ts changed or the branch was edited. return report.pendingMigrations.length > 0 ? "Run `appkit db migrate` to apply the pending migrations." @@ -131,7 +136,7 @@ function printLocalVerifyReport(report: LocalVerifyReport): void { } for (const tag of report.strandedMigrations) { warn( - `Never runs: ${tag}: it is older than a migration the branch already ran (merged out of order); the deployed app skips it too once it ran a newer one`, + `Never runs: ${tag}: it is older than a migration the branch already ran (merged out of order), and the deployed app refuses to start on that history`, ); } for (const tag of report.editedMigrations) { From bf9a8ec6545d2746c75653ea08496cb3ec1966ea Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:11:41 +0000 Subject: [PATCH 074/317] test: a migrate that fails after writing a migration still reports what it breaks Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/migrate.test.ts | 20 ++++++++++++ .../src/cli/commands/db/migrate.test.ts | 32 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 839141444..ed5c66139 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -342,6 +342,26 @@ describe("runMigrate", () => { expect(report.breaking).toEqual(report.generated?.statements); }); + test("a failure after generating still carries what the kept migration breaks", async () => { + const ctx = app(`notes: table("notes", { id: id(), body: text() })`); + resolveEnvBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + + writeSchema(ctx.root, `notes: table("notes", { id: id() })`); + resolveEnvBranch.mockRejectedValue(new Error("403 Forbidden")); + const error = await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + ); + + expect(error).toMatchObject({ + generated: { tag: "0001_migration" }, + breaking: ['ALTER TABLE "app"."notes" DROP COLUMN "body";'], + }); + expect((error as Error).message).toMatch( + /^Wrote .*0001_migration\.sql, but did not apply it: 403 Forbidden$/, + ); + }); + test("a second migrate in the same checkout fails while the first runs, and writes nothing", async () => { const ctx = app(`notes: table("notes", { id: id() })`); let finishApply: (value: unknown) => void = () => undefined; diff --git a/packages/shared/src/cli/commands/db/migrate.test.ts b/packages/shared/src/cli/commands/db/migrate.test.ts index 1e0ca7463..a48bee553 100644 --- a/packages/shared/src/cli/commands/db/migrate.test.ts +++ b/packages/shared/src/cli/commands/db/migrate.test.ts @@ -151,6 +151,38 @@ describe("appkit db migrate", () => { expect(process.exitCode).toBeUndefined(); }); + test("when applying fails after a migration was written, it still warns about what that migration breaks", async () => { + const drop = 'ALTER TABLE "app"."notes" DROP COLUMN "body";'; + runMigrate.mockRejectedValue( + Object.assign( + new Error( + "Wrote config/database/migrations/0002_migration.sql, but did not apply it: 403 Forbidden", + ), + { + generated: { + tag: "0002_migration", + file: path.join( + process.cwd(), + "config/database/migrations/0002_migration.sql", + ), + statements: [drop], + }, + breaking: [drop], + }, + ), + ); + + await dbCommand.parseAsync(["migrate"], { from: "user" }); + + expect(output(error)).toContain( + "Wrote config/database/migrations/0002_migration.sql, but did not apply it: 403 Forbidden", + ); + expect(output(log)).toContain( + `0002_migration breaks instances still running the previous release, which keep serving while the new one migrates on start: ${drop} Deploy code that works with both the old and the new schema first, then this change in a later deploy.`, + ); + expect(process.exitCode).toBe(1); + }); + test("prints the error and its root cause, and exits 1", async () => { const driverError = new Error('relation "notes" already exists'); const wrapped = new Error("Failed query: CREATE TABLE ...", { From 338fb4719efa7a43dda5c19db1c96aae7ccafe49 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:11:45 +0000 Subject: [PATCH 075/317] test(appkit): pin that introspect refuses a recorded migration whose file changed The drift introspect reads before rendering, and the check markMigrationsApplied repeats under the lock, both leave out migrations the branch recorded but whose committed file changed since. The introspect test mock now records the real file hash, so an edited file shows up the way it does on a branch. Co-authored-by: Isaac Signed-off-by: ditadi --- .../migrations/tests/apply.pg.test.ts | 27 ++++++++++- .../introspect/tests/introspect.test.ts | 48 +++++++++++++++---- 2 files changed, 66 insertions(+), 9 deletions(-) diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts index c3b2d7b99..a0e5da151 100644 --- a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -1,4 +1,6 @@ import { randomUUID } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; import { Pool, type PoolClient } from "pg"; import { @@ -437,11 +439,12 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { ); }; - test("the drift lists unrecorded committed migrations and recorded ones the checkout lacks", async () => { + 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, }); @@ -450,6 +453,16 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { 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, }); }); @@ -485,6 +498,18 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { ["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) => { diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 9bfc2b4cb..65dee7e6f 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -32,6 +32,7 @@ vi.mock("../../../../type-generator/database", async (importOriginal) => ({ 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 { cleanupTempApps, fakeContext, tempApp } from "../../tests/fakes"; @@ -75,10 +76,15 @@ const onProduction = { }; let catalog: ReturnType; -/** `when` of each migration the branch recorded; empty: no journal table. */ -let recorded: number[]; -const lastWhen = (root: string) => - readJournal(path.join(root, MIGRATIONS))?.entries.at(-1)?.when ?? 0; +/** The journal rows of the branch, as drizzle-orm records them; empty: no journal table. */ +let recorded: Array<{ when: number; hash: 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. @@ -87,7 +93,10 @@ const pool = { } if (text.includes("select hash, created_at")) { return { - rows: recorded.map((when) => ({ hash: "h", created_at: String(when) })), + rows: recorded.map(({ when, hash }) => ({ + hash, + created_at: String(when), + })), }; } return { rows: await catalog.respond(text, values) }; @@ -120,7 +129,10 @@ beforeEach(() => { ) => { const entries = readJournal(options.migrationsFolder)?.entries ?? []; for (const tag of tags) { - recorded.push(entries.find((entry) => entry.tag === tag)?.when ?? 0); + recorded.push({ + when: entries.find((entry) => entry.tag === tag)?.when ?? 0, + hash: hashOf(options.migrationsFolder, tag), + }); } }, ); @@ -168,7 +180,7 @@ async function commitMigration(root: string, applied = true): Promise { interactive: false, }), ); - if (applied) recorded.push(lastWhen(root)); + if (applied) recorded.push(lastCommitted(root)); } /** Every file under config/, with its contents. */ @@ -581,7 +593,7 @@ export const schema = defineSchema(({ table }) => ({ async (_label, history) => { const root = tempApp({ [SCHEMA]: previousSchema }); if (history) await commitMigration(root); - recorded.push(Date.now() + 60_000); + recorded.push({ when: Date.now() + 60_000, hash: "teammate" }); const before = tree(root); const error = await refusal(root); @@ -612,6 +624,26 @@ export const schema = defineSchema(({ table }) => ({ ); }); + 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 recreate the branch.', + ); + 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); From 8081abd116dcbb0e63432aeac04714332e6506b2 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:11:58 +0000 Subject: [PATCH 076/317] fix(appkit): db check tells the developer to keep hand-written SQL when regenerating Resetting the migrations to the base branch's and running migrate again regenerates the schema change but drops SQL written by hand into the conflicting migration, such as a backfill. The guidance and the docs now say to save it first, add it back to the regenerated migration, and review that migration's SQL before committing. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 10 ++++++---- packages/appkit/src/database/tooling/check.ts | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 2b7aba887..04f3866ed 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -373,10 +373,12 @@ exits 1 when: 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 the base branch's migrations instead: -merge the base branch, reset `config/database/migrations` to the base branch's, -then run `npx appkit db clean` and `npx appkit db migrate`. `migrate` writes your -change again after the base branch's migrations. +fails the check. Resolve the conflict with the base branch's migrations instead. +Save any SQL you wrote by hand in your migration, such as a backfill. Merge the +base branch, reset `config/database/migrations` to the base branch's, then run +`npx appkit db clean` and `npx appkit db migrate`. `migrate` writes your schema +change again after the base branch's migrations. Add the saved SQL back to the +regenerated migration and review its SQL before you commit. After a deploy, check the deployed app with workspace credentials: diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts index 501a6cc38..6df321e0a 100644 --- a/packages/appkit/src/database/tooling/check.ts +++ b/packages/appkit/src/database/tooling/check.ts @@ -28,7 +28,7 @@ export interface CheckReport { } const REWRITE = - "Merge the base branch, reset the migrations to its own (for example `git restore --source origin/main --staged --worktree config/database/migrations`), then run `appkit db clean` and `appkit db migrate`: migrate writes your change again after the base branch's migrations, and applies them all to your rebuilt branch."; + "Save any SQL you wrote by hand in your migration. Merge the base branch, reset the migrations to its own (for example `git restore --source origin/main --staged --worktree config/database/migrations`), then run `appkit db clean` and `appkit db migrate`, which writes your schema change again after the base branch's migrations and applies them all to your rebuilt branch. Add the saved SQL back to the regenerated migration and review its SQL before you commit."; /** Entries numbered or ordered in a way the migrator or drizzle-kit misreads. */ function orderProblems(entries: readonly JournalEntry[]): string[] { From 4c7122c60807c103f10e9b6a91eedf96c7398211 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:12:56 +0000 Subject: [PATCH 077/317] test(appkit): local verify must name declared tables left in public as the cause The plugin's startup check names that cause and says not to migrate; verify did not, and recommended migrate, which would create empty app tables. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 27 ++++++++++++++ .../database/tests/schema-check.test.ts | 37 ++++++++++++++----- .../shared/src/cli/commands/db/verify.test.ts | 23 ++++++++++++ 3 files changed, 78 insertions(+), 9 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index ee0ca3a11..84047b7ba 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -108,6 +108,8 @@ function branch(state: { columns: Record; /** The journal table's rows; "absent" without the table. */ recorded: Array<{ hash: string; created_at: string }> | "absent"; + /** Declared tables that exist in schema public instead. */ + inPublic?: string[]; failOn?: RegExp; }) { const statements: string[] = []; @@ -115,6 +117,11 @@ function branch(state: { query: vi.fn(async (text: string, values?: unknown[]) => { statements.push(text); if (state.failOn?.test(text)) throw new Error("connection reset"); + if (/n\.nspname = 'public'/.test(text)) { + return { + rows: (state.inPublic ?? []).map((table_name) => ({ table_name })), + }; + } if (/pg_catalog\.pg_attribute/.test(text)) { expect(values?.[0]).toBe("app"); return { @@ -170,6 +177,7 @@ describe("runVerify", () => { ]; const clean = { schemaProblems: [], + schemaAdvice: null, pendingMigrations: [], strandedMigrations: [], editedMigrations: [], @@ -213,11 +221,30 @@ describe("runVerify", () => { expect(await runVerify(ctx)).toMatchObject({ schemaProblems: ["table app.notes does not exist"], + schemaAdvice: null, pendingMigrations: ["0000_baseline"], ok: false, }); }); + test("declared tables that exist in public are named as the cause, as the app's startup check does", async () => { + const ctx = app(two); + branch({ + columns: {}, + recorded: recordedAs(ctx, two), + inPublic: ["notes"], + }); + + expect(await runVerify(ctx)).toMatchObject({ + ...clean, + schemaProblems: ["table app.notes does not exist"], + schemaAdvice: + `Schema public has that table, but defineSchema() puts tables in schema "app" unless told otherwise. ` + + 'To keep them in public, pass { schemaName: "public" } as the second argument of defineSchema() in config/database/schema.ts.', + ok: false, + }); + }); + test("a migration merged out of order, older than the last one the branch ran, never runs", async () => { const migrations = [ { tag: "0000_migration", when: 1000 }, diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index 70640c7af..f4a2c77aa 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -2,10 +2,7 @@ import { describe, expect, test, vi } from "vitest"; import type { DataPath } from "../../../database/runtime"; import { defineSchema, fk, id, text } from "../../../database/schema-builder"; -import { - assertSchemaMatchesDatabase, - findSchemaProblems, -} from "../schema-check"; +import { assertSchemaMatchesDatabase, diagnoseSchema } from "../schema-check"; // Explicitly public: the assertions name the tables public.boards and public.notes. const schema = defineSchema( @@ -195,38 +192,60 @@ describe("assertSchemaMatchesDatabase", () => { }); }); -describe("findSchemaProblems", () => { +describe("diagnoseSchema", () => { test("returns every problem without throwing; the assert reports the same ones", async () => { const { path } = catalog( { boards: ["id", "title"], notes: ["id", "body"] }, { boards: "v" }, ); - const problems = await findSchemaProblems(path, schema); + const { problems, advice } = await diagnoseSchema(path, schema); expect(problems).toEqual([ "table public.boards is a view, not a table", "table public.notes is missing columns board_id, author_email", ]); + expect(advice).toBeNull(); await expect(assertSchemaMatchesDatabase(path, schema)).rejects.toThrow( `the declared schema does not match the database: ${problems.join("; ")}.`, ); }); + test("names tables left in public as the cause, the same advice the assert gives", async () => { + const appSchema = defineSchema(({ table }) => ({ + notes: table("notes", { id: id() }), + })); + const { path } = catalog({}, {}, ["notes"]); + + const { problems, advice } = await diagnoseSchema(path, appSchema); + + expect(problems).toEqual(["table app.notes does not exist"]); + expect(advice).toBe( + `Schema public has that table, but defineSchema() puts tables in schema "app" unless told otherwise. ` + + 'To keep them in public, pass { schemaName: "public" } as the second argument of defineSchema() in config/database/schema.ts.', + ); + await expect(assertSchemaMatchesDatabase(path, appSchema)).rejects.toThrow( + advice as string, + ); + }); + test("returns no problems for a matching database or an empty schema", async () => { const { path } = catalog({ boards: ["id", "title"], notes: ["id", "board_id", "author_email", "body"], }); - expect(await findSchemaProblems(path, schema)).toEqual([]); + expect(await diagnoseSchema(path, schema)).toEqual({ + problems: [], + advice: null, + }); const empty = catalog({}); expect( - await findSchemaProblems( + await diagnoseSchema( empty.path, defineSchema(() => ({})), ), - ).toEqual([]); + ).toEqual({ problems: [], advice: null }); expect(empty.raw).not.toHaveBeenCalled(); }); }); diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index 4726fd728..44d7ae000 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -33,6 +33,7 @@ const local = { kind: "local" as const, branch: "projects/p/branches/dev-alice-3f9a2c", schemaProblems: [], + schemaAdvice: null, pendingMigrations: [], strandedMigrations: [], editedMigrations: [], @@ -127,6 +128,28 @@ describe("appkit db verify", () => { expect(process.exitCode).toBe(1); }); + test("tables left in public: the hint is that cause, before any other, never to migrate", async () => { + const advice = + 'Schema public has that table, but defineSchema() puts tables in schema "app" unless told otherwise. To keep them in public, pass { schemaName: "public" } as the second argument of defineSchema() in config/database/schema.ts.'; + runVerify.mockResolvedValue({ + ...local, + schemaProblems: ["table app.notes does not exist"], + schemaAdvice: advice, + editedMigrations: ["0000_migration"], + ok: false, + }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(log)).toContain("Schema: table app.notes does not exist"); + const printed = output(error); + expect(printed).toContain( + `dev-alice-3f9a2c does not match config/database/schema.ts and the committed migrations. ${advice}`, + ); + expect(printed).not.toContain("appkit db migrate"); + expect(process.exitCode).toBe(1); + }); + test("a migration merged out of order is named, with how to regenerate it after the recorded ones", async () => { runVerify.mockResolvedValue({ ...local, From 71b99815792bcec56bdbcaf9ffa2c29bc5ee73e1 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:13:04 +0000 Subject: [PATCH 078/317] fix(appkit): refuse to introspect a branch that ran an edited migration A migration the branch recorded, whose committed file changed since, ran in a version the snapshot does not describe, so the migration introspect diffs from that snapshot would be recorded against history the branch never had. The drift now carries these migrations: introspect refuses before reading the catalog, and markMigrationsApplied refuses again under the lock when the edit lands between the two reads. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/migrations/apply.ts | 9 +++++++++ .../appkit/src/database/tooling/introspect/index.ts | 10 +++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index b9f528640..096a80491 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -581,6 +581,8 @@ interface MigrationDrift { 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; } @@ -591,6 +593,7 @@ function driftOf( return { pending: tags(history.pending), stranded: tags(history.stranded), + edited: tags(history.edited), unknown: history.unknown.length, }; } @@ -613,6 +616,11 @@ export async function readMigrationDrift( ); } +/** 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, @@ -625,6 +633,7 @@ function driftReason( ? `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); diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 7cf6c035b..1f89affeb 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -7,6 +7,7 @@ import { } from "../../../plugins/database/load-schema"; import { writeDatabaseTypes } from "../../../type-generator/database"; import { + editedReason, markMigrationsApplied, readMigrationDrift, } from "../../migrations/apply"; @@ -197,7 +198,8 @@ async function introspectHolding( return withBranchPool(ctx, async (pool) => { // The diff starts from the latest committed snapshot, so the branch must // record exactly the committed migrations: one it lacks would come out - // reversed, and one the checkout lacks would come out again. + // 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); const refuse = (reason: string, advice: string) => new IntrospectRefusedError( @@ -215,6 +217,12 @@ async function introspectHolding( "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 recreate the branch.`, + ); + } // An interrupted run leaves its migration written but not recorded. const unrecorded = drift.pending.every((tag) => INTROSPECT_TAG.test(tag)) ? drift.pending From 2e2cc4dbb951cce7bf3f8b1d16e0e945c6622a3a Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:13:09 +0000 Subject: [PATCH 079/317] fix(appkit): reconcile migrations one to one per timestamp and refuse ambiguous history reconcileMigrations keyed each `when` on a set of recorded hashes, so two files sharing a timestamp with one recorded row were both called edited (the one that never ran was skipped with a warning), and a second recorded row at a committed `when` was neither edited nor unknown. Each `when` is now a bucket: exact hash matches are consumed first; one file left with one row left is edited; files left with no row are pending or stranded by lastRecorded; rows left with no file are unknown. Any other remainder is ambiguous, and the migrator refuses it with a MigrationHistoryError that names the timestamp, the files and the row count, before taking the lock. MigrationHistoryError takes the refusal as an object, with a `stranded` and an `ambiguous` field. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 78 ++++++++++--- .../appkit/src/database/migrations/history.ts | 108 ++++++++++++------ .../database/tests/migrate-on-start.test.ts | 5 +- 3 files changed, 145 insertions(+), 46 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index bc9a1f99d..cd298034e 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -8,6 +8,7 @@ import type { Pool, PoolClient } from "pg"; import { createLogger } from "../../logging/logger"; import { + type AmbiguousTimestamp, type MigrationFile, type RecordedMigration, reconcileMigrations, @@ -153,26 +154,67 @@ export class MigrationBaselineMismatchError extends Error { } } +/** 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 }; + /** - * Committed migrations are older than the last one the database recorded and - * were never applied, so they would never run. Nothing was applied. + * 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 { + /** Committed migrations older than the last recorded one that never ran. */ readonly stranded: readonly string[]; + /** Committed migrations whose timestamp the database recorded with hashes none of them has. */ + readonly ambiguous: readonly string[]; - constructor(schemaName: string, stranded: readonly string[], last: string) { - const many = stranded.length > 1; + constructor(schemaName: string, refusal: HistoryRefusal) { super( - `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. ` + - `Delete ${many ? "their" : "its"} .sql file, snapshot and journal entry, generate the migration again from schema.ts, and deploy again. ` + - "No migration was applied.", + "stranded" in refusal + ? strandedMessage(schemaName, refusal.stranded, refusal.last) + : ambiguousMessage(schemaName, refusal.ambiguous), ); this.name = "MigrationHistoryError"; - this.stranded = Object.freeze([...stranded]); + this.stranded = Object.freeze( + "stranded" in refusal ? [...refusal.stranded] : [], + ); + this.ambiguous = Object.freeze( + "ambiguous" in refusal ? tags(refusal.ambiguous.files) : [], + ); } } +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. ` + + `Delete ${many ? "their" : "its"} .sql file, snapshot and journal entry, generate the migration again from schema.ts, and deploy again. ` + + "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." + ); +} + /** The migration lock stayed taken past the wait limit. */ class MigrationLockWaitError extends Error { constructor(readonly holder: string | undefined) { @@ -588,8 +630,9 @@ function duration(ms: number): string { * 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. An applied migration whose file - * changed, and recorded migrations that are not committed, are logged. + * last recorded one but was never applied, or when the files and rows at one + * timestamp cannot be paired. An applied migration whose file changed, and + * recorded migrations that are not committed, are logged. * * 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 @@ -633,7 +676,11 @@ export async function applyPendingMigrations( await readRecordedMigrations(client, schemaName), ); let waitedMs = 0; - if (history.pending.length > 0 && history.stranded.length === 0) { + if ( + history.pending.length > 0 && + history.stranded.length === 0 && + history.ambiguous.length === 0 + ) { pending = tags(history.pending); step = "Waiting for the migration lock"; await prepareMigrationSession(client, reset); @@ -649,11 +696,16 @@ export async function applyPendingMigrations( ); } + const ambiguous = history.ambiguous[0]; + if (ambiguous) throw new MigrationHistoryError(schemaName, { ambiguous }); if (history.stranded.length > 0) { const last = files.find((file) => file.when === history.lastRecorded)?.tag ?? `the migration recorded at ${new Date(history.lastRecorded ?? 0).toISOString()}`; - throw new MigrationHistoryError(schemaName, tags(history.stranded), last); + throw new MigrationHistoryError(schemaName, { + stranded: tags(history.stranded), + last, + }); } if (history.edited.length > 0) { logger.warn( diff --git a/packages/appkit/src/database/migrations/history.ts b/packages/appkit/src/database/migrations/history.ts index bf3583c57..b6ec23c07 100644 --- a/packages/appkit/src/database/migrations/history.ts +++ b/packages/appkit/src/database/migrations/history.ts @@ -16,6 +16,19 @@ export interface RecordedMigration { 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. */ interface MigrationHistory { /** Not recorded and newer than every recorded migration: applied next, oldest first. */ @@ -24,50 +37,81 @@ interface MigrationHistory { 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 each committed migration with a recorded row by `when` = `created_at`, - * the pair drizzle-orm's migrator writes, then compare hashes. Two entries can - * share a `when` after a hand edit or a merge, so each `when` keeps every hash - * recorded at it. + * 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 hashesAt = new Map>(); - for (const row of recorded) { - if (row.createdAt === null) continue; - const hashes = hashesAt.get(row.createdAt) ?? new Set(); - hashes.add(row.hash); - hashesAt.set(row.createdAt, hashes); - } - const lastRecorded = hashesAt.size > 0 ? Math.max(...hashesAt.keys()) : null; + 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 pending: MigrationFile[] = []; - const stranded: MigrationFile[] = []; - const edited: MigrationFile[] = []; - for (const file of files) { - const hashes = hashesAt.get(file.when); - if (hashes?.has(file.hash)) continue; - // A row at this `when` that is another entry's: this one never ran. - const sibling = files.some( - (other) => - other !== file && other.when === file.when && hashes?.has(other.hash), - ); - if (hashes && !sibling) edited.push(file); - else if (lastRecorded === null || file.when > lastRecorded) { - pending.push(file); - } else stranded.push(file); + 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) => row.hash === file.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 committed = new Set(files.map((file) => file.when)); - const unknown = recorded.filter( - (row) => row.createdAt === null || !committed.has(row.createdAt), - ); - return { pending, stranded, edited, unknown, lastRecorded }; + + 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/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index 6d53bc5c4..11bdc7cad 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -209,7 +209,10 @@ describe("migrateOnStart", () => { ], [ "a stranded migration", - new apply.MigrationHistoryError("app", ["0001_parallel"], "0002_b"), + new apply.MigrationHistoryError("app", { + stranded: ["0001_parallel"], + last: "0002_b", + }), "Migration 0001_parallel is older than 0002_b", ], [ From 5ddcd47219c354436bd4beaab89ec66b74b2d3e7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:13:15 +0000 Subject: [PATCH 080/317] test(appkit): cover the KEY: value form dotenv reads when rewriting .env dotenv 16.6.1 reads `KEY: value` (a colon followed by whitespace) as an entry, and a later entry wins. updateEnvFile's parser only knows `KEY=`, so a later `PGHOST: old` outlives the rewrite and dotenv reads the old host. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/env-file.test.ts | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/env-file.test.ts b/packages/appkit/src/database/tooling/tests/env-file.test.ts index 35bfee92d..203e278c5 100644 --- a/packages/appkit/src/database/tooling/tests/env-file.test.ts +++ b/packages/appkit/src/database/tooling/tests/env-file.test.ts @@ -107,6 +107,31 @@ describe("updateEnvFile", () => { }); }); + test("a `KEY: value` entry, which dotenv reads, is replaced like `KEY=value`; `KEY:value` is not an entry", () => { + const root = tempApp({ + ".env": [ + "PGHOST=first", + "export PGHOST:\told", + "PGPORT: 1", + "KEEP:not-an-entry", + ].join("\n"), + }); + const file = path.join(root, ".env"); + + updateEnvFile(file, { PGHOST: "new.example.com", PGPORT: "6543" }); + + const text = fs.readFileSync(file, "utf-8"); + expect(text).toBe( + ["PGHOST=new.example.com", "PGPORT=6543", "KEEP:not-an-entry", ""].join( + "\n", + ), + ); + expect(dotenv.parse(text)).toEqual({ + PGHOST: "new.example.com", + PGPORT: "6543", + }); + }); + test("a value whose quote never closes is a single line, as dotenv reads it", () => { const root = tempApp({ ".env": 'NOTE="open\nPGHOST=old\n' }); const file = path.join(root, ".env"); From 05eb60ec73a02bfd881483ae0012095f8f03f0e3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:13:48 +0000 Subject: [PATCH 081/317] fix(appkit): rewrite the KEY: value entries dotenv reads in .env updateEnvFile only recognized `KEY=`. dotenv 16.6.1 also reads `KEY: value` when whitespace follows the colon, and its last entry wins, so a later `PGHOST: old` outlived the rewrite. The parser now treats that form as an entry too and writes it back as `KEY=`. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/env-file.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/env-file.ts b/packages/appkit/src/database/tooling/env-file.ts index 63eccdb18..33dc8bb41 100644 --- a/packages/appkit/src/database/tooling/env-file.ts +++ b/packages/appkit/src/database/tooling/env-file.ts @@ -2,8 +2,12 @@ import { randomBytes } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; -/** An entry's first line: indentation and `export ` (kept on rewrite), the key, the value. */ -const ENTRY = /^(\s*(?:export\s+)?)([\w.-]+)\s*=\s*(.*)$/; +/** + * 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_./:@+-]*$/; From ce46a8aff72987aeac88a289b94ff55c6b5a025b Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:13:52 +0000 Subject: [PATCH 082/317] fix: report what a kept migration breaks when migrate fails after writing it runMigrate computed the breaking statements only after a successful apply. When branch resolution or the connection failed (a 403, say) the migration stayed on disk, the warning was never printed, and the next run generated nothing to warn about. The statements are now computed right after generation; the failure throws UnappliedMigrationError carrying the kept migration and them, and the CLI prints the same warning it prints on success. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrate.ts | 33 ++++++++++++++++--- .../shared/src/cli/commands/db/migrate.ts | 19 ++++++++++- packages/shared/src/cli/commands/db/output.ts | 16 +++++---- .../src/cli/commands/db/tooling-contract.ts | 9 +++++ 4 files changed, 65 insertions(+), 12 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 0f5ea4c3c..a09144d52 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -63,6 +63,32 @@ export interface MigrateOptions { type ApplyOutcome = Pick; +/** + * The run wrote a migration and then failed before applying it. The file + * stays for the next run, which generates nothing new, so this is the only + * run that can report what the migration breaks. + */ +export class UnappliedMigrationError extends Error { + readonly generated: GeneratedMigration; + /** Statements of the kept migration that break instances still running the previous release. */ + readonly breaking: readonly string[]; + + constructor( + root: string, + generated: GeneratedMigration, + breaking: readonly string[], + cause: unknown, + ) { + super( + `Wrote ${path.relative(root, generated.file)}, but did not apply it: ${cause instanceof Error ? cause.message : String(cause)}`, + { cause }, + ); + this.name = "UnappliedMigrationError"; + this.generated = generated; + this.breaking = breaking; + } +} + /** Why migrations must not be applied to the `.env` branch; undefined when they may. */ async function applyBlocker(ctx: DbContext): Promise { const env = await resolveEnvBranch(ctx); @@ -117,6 +143,7 @@ async function migrateHolding( schema, interactive: options.interactive, }); + const breaking = breakingStatements(generated?.statements ?? []); // The types follow schema.ts alone, so they are current even if applying fails. const typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); @@ -141,12 +168,8 @@ async function migrateHolding( { cause: error }, ); } - throw new Error( - `Wrote ${file}, but did not apply it: ${error instanceof Error ? error.message : String(error)}`, - { cause: error }, - ); + throw new UnappliedMigrationError(ctx.root, generated, breaking, error); } - const breaking = breakingStatements(generated?.statements ?? []); return { generated, ...(breaking.length > 0 ? { breaking } : {}), diff --git a/packages/shared/src/cli/commands/db/migrate.ts b/packages/shared/src/cli/commands/db/migrate.ts index 7096022ba..a7f419e67 100644 --- a/packages/shared/src/cli/commands/db/migrate.ts +++ b/packages/shared/src/cli/commands/db/migrate.ts @@ -1,7 +1,22 @@ import { Command } from "commander"; import { loadDatabaseTooling } from "./load-tooling"; -import { fail, isInteractive, printMigrateReport } from "./output"; +import { + fail, + isInteractive, + printMigrateReport, + warnBreaking, +} from "./output"; +import type { UnappliedMigration } from "./tooling-contract"; + +/** The migration a failed run wrote and kept; null when it wrote none. */ +function unappliedMigration(error: unknown): UnappliedMigration | null { + const candidate = error as Partial | null; + return typeof candidate?.generated?.tag === "string" && + Array.isArray(candidate.breaking) + ? (candidate as UnappliedMigration) + : null; +} async function runDbMigrate(): Promise { try { @@ -12,6 +27,8 @@ async function runDbMigrate(): Promise { printMigrateReport(report); } catch (error) { fail(error); + const kept = unappliedMigration(error); + if (kept) warnBreaking(kept.generated.tag, kept.breaking); } } diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index f3dc540a4..b33a2c6d5 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -42,21 +42,25 @@ export function fail(error: unknown): void { process.exitCode = 1; } +/** Statements of a written migration that break instances still running the previous release. */ +export function warnBreaking(tag: string, breaking: readonly string[]): void { + if (breaking.length === 0) return; + warn( + `${tag} breaks instances still running the previous release, which keep serving while the new one migrates on start: ${breaking.join(" ")} ` + + "Deploy code that works with both the old and the new schema first, then this change in a later deploy.", + ); +} + export function printMigrateReport(report: MigrateReport): void { if (report.generated) { const count = report.generated.statements.length; ok( `Generated ${relative(report.generated.file)} (${count} statement${count === 1 ? "" : "s"})`, ); + warnBreaking(report.generated.tag, report.breaking ?? []); } else { info("No schema changes since the last migration"); } - if (report.generated && report.breaking?.length) { - warn( - `${report.generated.tag} breaks instances still running the previous release, which keep serving while the new one migrates on start: ${report.breaking.join(" ")} ` + - "Deploy code that works with both the old and the new schema first, then this change in a later deploy.", - ); - } if (report.adopted?.length) { ok( diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 4e2f65af4..f74f91678 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -19,6 +19,15 @@ export interface MigrateReport { readonly typesFile: string; } +/** + * What the error runMigrate throws after writing a migration carries. The + * file stays for the next run, which generates nothing new to warn about. + */ +export interface UnappliedMigration { + readonly generated: GeneratedMigration; + readonly breaking: readonly string[]; +} + /** * The exports of `@databricks/appkit/beta/database-tooling` the CLI calls. `shared` * must not depend on appkit, so the CLI imports the tooling dynamically and From 46a3379adbc8fa76ab42b78c1ac765d19099e6ee Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:14:11 +0000 Subject: [PATCH 083/317] fix(template): git-ignore the temporary file appkit db init writes .env through updateEnvFile writes `..env...tmp` and renames it over .env. A run killed between the two leaves the file, which holds the .env contents, and nothing ignored it. Co-authored-by: Isaac Signed-off-by: ditadi --- template/_gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/template/_gitignore b/template/_gitignore index f0faf4e16..bdffa9c50 100644 --- a/template/_gitignore +++ b/template/_gitignore @@ -11,6 +11,8 @@ playwright-report/ # `appkit db` holds it while a command changes the migration history config/database/.appkit-db.lock +# `appkit db init` writes .env through this file; a killed run can leave it, secrets included +..env.*.tmp # Auto-generated types (endpoint-specific, varies per developer) shared/appkit-types/serving.d.ts From 38d9a2e90af9bee7c7b0e690a935f0458d4e7823 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:14:12 +0000 Subject: [PATCH 084/317] docs(appkit): say db check imports schema.ts and what it does not compare "Reads only the checkout" read as a sandbox. check loads config/database/schema.ts through jiti, so it imports that file and everything it imports and runs the pull request's code; the docs, the template README and --help now say to run it in a CI job without secrets. They also narrow what check guarantees: it compares the snapshots and schema.ts and does not read the .sql files, so SQL edited by hand is not checked against its snapshot. The lists of what fails gain the integer when and first-snapshot checks. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 11 +++++++++-- packages/appkit/src/database/tooling/check.ts | 5 +++-- packages/shared/src/cli/commands/db/check.ts | 10 +++++++--- template/README.md.tmpl | 5 +++-- 4 files changed, 22 insertions(+), 9 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 04f3866ed..9ebde446f 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -360,14 +360,21 @@ dependencies: npx appkit db check ``` -It reads only the checkout, so it needs no Databricks or Lakebase credentials. It +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; -- an entry's `idx` is not its position in the journal; +- 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. diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts index 6df321e0a..fc2646468 100644 --- a/packages/appkit/src/database/tooling/check.ts +++ b/packages/appkit/src/database/tooling/check.ts @@ -117,8 +117,9 @@ function chainProblems( /** * `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 reads - * only files, so CI can run it without Databricks or Lakebase access. + * 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"); diff --git a/packages/shared/src/cli/commands/db/check.ts b/packages/shared/src/cli/commands/db/check.ts index 4b0094364..34f08ad12 100644 --- a/packages/shared/src/cli/commands/db/check.ts +++ b/packages/shared/src/cli/commands/db/check.ts @@ -21,11 +21,15 @@ export const dbCheckCommand = new Command("check") .addHelpText( "after", ` -Reads only the checkout, so it needs no Databricks or Lakebase access, only -the app's installed dependencies (drizzle-kit included). It fails when: +Needs no Databricks or Lakebase access, only the app's installed dependencies +(drizzle-kit included). It imports schema.ts, so give a CI job that runs it no +secrets. It compares the snapshots and schema.ts and does not read the .sql +files. It fails when: - the journal lists a migration generated before the one listed ahead of it; - two migrations were generated from the same snapshot on parallel branches; - - an entry's idx is not its position in the journal; + - the first migration was not generated from an empty database; + - 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; - schema.ts changed and no committed migration has the change. diff --git a/template/README.md.tmpl b/template/README.md.tmpl index 2fa4dc91b..6acdacf86 100644 --- a/template/README.md.tmpl +++ b/template/README.md.tmpl @@ -83,8 +83,9 @@ runs `config/database/seed.sql` on it; both refuse any branch `db init` did not create for you, such as the deployed one. In CI, `npx appkit db check` fails a pull request whose `schema.ts` change has no -migration, or whose migrations are out of order or missing files. It reads only the -checkout, so it needs no Databricks credentials. +migration, or whose migrations are out of order or missing files. It needs no +Databricks credentials, and it imports `schema.ts`, so give the job that runs it +no secrets. {{- end}} ### CLI Authentication From 7f39cd221b30e5e8dcb31b6b140cd7401dbb3f9a Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:14:27 +0000 Subject: [PATCH 085/317] fix(appkit): refuse migrate-on-start when the default schema would shadow tables in public An app upgraded from a release that put tables in public, left on the default schema app, has public.notes with its rows and no app.notes. migrateOnStart ran before assertSchemaMatchesDatabase, so the first committed migration created an empty app.notes, the check passed, and the app served the empty table. The "tables are in public" advice only showed when the check failed. Before applying anything, migrateOnStart now asks the catalog where the declared tables are. When defineSchema() was not told a schemaName, none of the tables exist in app and some exist in public, startup fails with the advice: keep them in public with { schemaName: "public" }, move them (ALTER TABLE ... SET SCHEMA), or name schemaName "app" explicitly when the tables in public are another app's. defineSchema() records whether schemaName was explicit as a symbol-keyed property; the public API is unchanged. The lookup and the advice live in database/migrations/tables-left-in-public.ts, exported as locateTables, detectTablesLeftInPublic, keepInPublicAdvice and the pg adapter catalogSqlOf, so the startup check and the CLI can share one query. assertSchemaMatchesDatabase's inPublicInstead now uses the same lookup. Co-authored-by: Isaac Signed-off-by: ditadi --- .../migrations/tables-left-in-public.ts | 100 +++++++++++ .../tests/tables-left-in-public.pg.test.ts | 75 +++++++++ .../tests/tables-left-in-public.test.ts | 155 ++++++++++++++++++ .../database/schema-builder/define-schema.ts | 21 ++- .../src/plugins/database/migrate-on-start.ts | 13 +- .../src/plugins/database/schema-check.ts | 22 +-- .../database/tests/schema-check.test.ts | 4 +- 7 files changed, 373 insertions(+), 17 deletions(-) create mode 100644 packages/appkit/src/database/migrations/tables-left-in-public.ts create mode 100644 packages/appkit/src/database/migrations/tests/tables-left-in-public.pg.test.ts create mode 100644 packages/appkit/src/database/migrations/tests/tables-left-in-public.test.ts 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/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..8931f1185 --- /dev/null +++ b/packages/appkit/src/database/migrations/tests/tables-left-in-public.pg.test.ts @@ -0,0 +1,75 @@ +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 app is refused; once app has it, it is not", async () => { + const table = unique(); + cleanup.push( + `drop table if exists public."${table}"`, + `drop table if exists app."${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); + await pool.query(`create schema if not exists app`); + await pool.query(`create table app."${table}" (id int)`); + const allowed = await detectTablesLeftInPublic(catalogSqlOf(pool), schema); + + expect(refused).toContain(`public has ${table}`); + expect(allowed).toBeUndefined(); + }); +}); 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/schema-builder/define-schema.ts b/packages/appkit/src/database/schema-builder/define-schema.ts index 5d8cf3d91..c21695d55 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", @@ -291,6 +296,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 +331,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 +348,11 @@ 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 @@ -373,5 +387,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/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index a350b3537..ad18a4502 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -14,6 +14,10 @@ import { MigrationFilesError, migrationsFolder, } from "../../database/migrations/paths"; +import { + catalogSqlOf, + detectTablesLeftInPublic, +} from "../../database/migrations/tables-left-in-public"; import type { Schema } from "../../database/schema-builder"; import { createLogger } from "../../logging/logger"; @@ -49,7 +53,7 @@ function endpointBranch(endpoint: string | undefined): string | undefined { * no-op. Every migration failure becomes a setup failure that names it. */ export async function migrateOnStart( - pool: Pick, + pool: Pick, schema: Schema, root: string = process.cwd(), env: NodeJS.ProcessEnv = process.env, @@ -74,6 +78,13 @@ export async function migrateOnStart( `PGHOST ${env.PGHOST} is a pooled endpoint, and migrations need a direct connection. Use the host without "-pooler".`, ); } + const leftInPublic = await detectTablesLeftInPublic( + catalogSqlOf(pool), + schema, + ); + if (leftInPublic) { + throw databaseSetupFailed(`not applying migrations: ${leftInPublic}`); + } const started = Date.now(); let result: Awaited>; diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index 69a6d575e..0c0a24f69 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -1,4 +1,8 @@ import { databaseSetupFailed } from "../../database/errors"; +import { + keepInPublicAdvice, + locateTables, +} from "../../database/migrations/tables-left-in-public"; import type { DataPath } from "../../database/runtime"; import type { Schema } from "../../database/schema-builder"; @@ -87,7 +91,8 @@ export async function assertSchemaMatchesDatabase( /** * Apps from before the default schema moved to `app` keep their tables in - * `public`. Name that case; migrating would create a second, empty copy. + * `public`. Name that case when every absent table is there; the migration + * guard in database/migrations/tables-left-in-public.ts refuses it up front. */ async function inPublicInstead( dataPath: DataPath, @@ -95,16 +100,7 @@ async function inPublicInstead( absent: readonly string[], ): Promise { if (schemaName === "public" || absent.length === 0) return undefined; - const rows = await dataPath.raw<{ table_name: string }>` - select 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 = 'public' - and c.relname::text = any(${absent}::text[]) - and c.relkind in ('r', 'p')`; - if (rows.length < absent.length) return undefined; - return ( - `Schema public has ${absent.length === 1 ? "that table" : "those tables"}, but 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.' - ); + const { inPublic } = await locateTables(dataPath.raw, schemaName, absent); + if (inPublic.length < absent.length) return undefined; + return `Schema public has ${absent.length === 1 ? "that table" : "those tables"}, but ${keepInPublicAdvice(schemaName)}`; } diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index 2abb3d26c..78345775a 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -48,8 +48,8 @@ function catalog( })), ); const raw = vi.fn(async (strings: TemplateStringsArray) => - strings.join("?").includes("n.nspname = 'public'") - ? inPublic.map((table_name) => ({ table_name })) + strings.join("?").includes("'public'") + ? inPublic.map((table_name) => ({ schema_name: "public", table_name })) : rows, ); return { raw, path: { raw } as unknown as DataPath }; From 5f564bbfbc58b57d38e33590e6bf502264ff1003 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:14:49 +0000 Subject: [PATCH 086/317] test(appkit): pin which of two foreign keys on one column introspect keeps Two foreign keys on the same column reach the render loop one after the other, and the second writes its fk() over the first with no skip. With identity keys the first rewrites the column's base type, so the second is skipped for a type reason that names the wrong cause. Co-authored-by: Isaac Signed-off-by: ditadi --- .../tooling/introspect/tests/render.test.ts | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index ae4a210ed..0aaecad0d 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -9,6 +9,7 @@ import { id, integer, text, + uuid, } from "../../../schema-builder"; import type { IntrospectedForeignKey, IntrospectedTable } from "../catalog"; import { renderSchemaSource } from "../render"; @@ -52,6 +53,19 @@ const keyed = ( ], }); +/** 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")); @@ -289,6 +303,37 @@ describe("renderSchemaSource", () => { ); }); + 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( [ @@ -787,6 +832,40 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { expect(out.newRelations).toEqual([]); }); + 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)", + ]); + expect(out.newRelations).toEqual([]); + }); + test("a declaration of another schema keeps nothing: every column renders private and every foreign key is new", () => { const out = renderSchemaSource( [ From e268364a56d40cc14c41024212b5f3114eb6b239 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:14:55 +0000 Subject: [PATCH 087/317] test(appkit): a variable reference in place of an app's resources is unresolved Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/targets.test.ts | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index 9430bf88d..31c52cea1 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -210,6 +210,64 @@ resources: }); }); + test("a ${var…} in place of an app's resources, one of them, or its postgres block is unresolved, not unbound", () => { + const root = tempApp({ + "databricks.yml": `variables: + app_resources: + type: complex + postgres_resource: + type: complex + postgres: + type: complex +resources: + apps: + app: + resources: \${var.app_resources} + reports: + resources: + - \${var.postgres_resource} + archive: + resources: + - name: postgres + postgres: \${var.postgres} +`, + }); + + const boundary = readDeployBoundary(root); + + expect(boundary).toEqual({ + branches: new Set(), + unresolved: [ + { + target: "default", + at: "resources.apps.app.resources", + written: "${var.app_resources}", + }, + { + target: "default", + at: "resources.apps.reports.resources[0]", + written: "${var.postgres_resource}", + }, + { + target: "default", + at: "resources.apps.archive.resources[0].postgres", + written: "${var.postgres}", + }, + ], + }); + expect( + classifyBranch({ + branch: { + name: `projects/p/branches/${devBranchId("alice@example.com")}`, + status: {}, + }, + userName: "alice@example.com", + sessionId: null, + boundary, + }).kind, + ).toBe("deploy-target"); + }); + test("a variable-overrides.json value binds its target too, so the dev branch it names is a deploy target", () => { const dev = `projects/p/branches/${devBranchId("alice@example.com")}`; const root = tempApp({ From 9c2a89d4b761d3ba04927a513988580d360864fe Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:15:17 +0000 Subject: [PATCH 088/317] test(appkit): cover init keeping a PGSSLMODE weaker than require Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 83dc5fae7..824542050 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -845,6 +845,25 @@ describe("runInit — .env", () => { expect(envFile(root).DATABRICKS_HOST).toBeUndefined(); }); + test.each(["prefer", "disable", "verify-full"])( + "PGSSLMODE=%s becomes require, and init says so; require stays", + async (weak) => { + const ctx = appOn(project(), { PGSSLMODE: weak }); + + const { steps } = await init(ctx, { schema: "none" }); + + expect(envFile(ctx.root).PGSSLMODE).toBe("require"); + expect(steps).toContain( + `Setting PGSSLMODE=require in .env: it was ${weak}, and only require makes every connection use TLS and check the server's certificate`, + ); + + const strict = appOn(project(), { PGSSLMODE: "require" }); + const kept = await init(strict, { schema: "none" }); + expect(envFile(strict.root).PGSSLMODE).toBe("require"); + expect(kept.steps.some((step) => step.includes("PGSSLMODE"))).toBe(false); + }, + ); + test("a symlinked .env is refused before any API call", async () => { const lakebase = project(); const ctx = appOn(lakebase, {}, { files: { "shared.env": "" } }); From 47c9e49b5443441b74d549371811195e6bf8b4cf Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:15:18 +0000 Subject: [PATCH 089/317] test(appkit): pin that the public-schema hint claims missing CREATE only when it is missing On SQLSTATE 42501 for schema public, ownershipHint said the app's role has no CREATE on public whenever another role owns public, which is always. An app that already holds CREATE and fails on a table another role owns got told to grant a privilege it has. Pin that with CREATE granted the hint names the object's owner as the fault and how to transfer it, and that without CREATE the grant advice stays. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/migrations/tests/ownership.test.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index 27acc56b5..67368d471 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -40,12 +40,13 @@ describe("ownership: one owner per branch", () => { ); }); - test("public, which the app never owns, gets the grant or the default schema", () => { + 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. ` + @@ -53,6 +54,20 @@ describe("ownership: one owner per branch", () => { ); }); + test("public with CREATE already granted: the failure is an object another role owns, not CREATE", () => { + const hint = ownershipHint("42501", { + schemaName: "public", + owner: "pg_database_owner", + currentUser: "app-sp", + canCreate: true, + }); + + expect(hint).not.toContain("has no CREATE"); + expect(hint).not.toContain("GRANT CREATE"); + expect(hint).toContain("belongs to another role"); + expect(hint).toContain(`OWNER TO "app-sp"`); + }); + test("any other failure gets no ownership hint", () => { expect(ownershipHint("42P07")).toBeUndefined(); expect(ownershipHint(undefined)).toBeUndefined(); From 72db9f57c72b4fc7fa423cc634f6cb4a811c9089 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:15:42 +0000 Subject: [PATCH 090/317] fix(appkit): keep one foreign key per column in introspect A column with two foreign keys keeps the first one the render loop reaches, and the other is skipped with that as its reason. Declared keys are sorted first, so a refresh keeps the one schema.ts declares. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/introspect/render.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index f03000c60..d2ea08863 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -617,6 +617,10 @@ export function renderSchemaSource( 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}"`; } From cf455dea07b582347cfcadf00c4fef4590a98153 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:15:56 +0000 Subject: [PATCH 091/317] fix(appkit): name tables left in public in local verify, before any other hint The startup check's diagnosis moves into diagnoseSchema, which verify now shares, so a branch whose declared tables sit in public gets the schemaName advice as its first hint instead of migrate, which would create empty app tables. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/verify.ts | 8 +++- .../src/plugins/database/schema-check.ts | 44 ++++++++++++++----- packages/shared/src/cli/commands/db/output.ts | 2 + .../src/cli/commands/db/tooling-contract.ts | 1 + 4 files changed, 41 insertions(+), 14 deletions(-) diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 4b0dcbed5..087e35992 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -4,7 +4,7 @@ import path from "node:path"; import type { PoolClient } from "pg"; import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; -import { findSchemaProblems } from "../../plugins/database/schema-check"; +import { diagnoseSchema } from "../../plugins/database/schema-check"; import { readMigrationDrift } from "../migrations/apply"; import { journalFile, @@ -44,6 +44,8 @@ interface LocalVerifyReport { readonly branch: string; /** Declared tables or columns the branch lacks (the plugin's startup check). */ readonly schemaProblems: readonly string[]; + /** The startup check's advice when every absent table is in public; null otherwise. */ + readonly schemaAdvice: string | null; /** Committed migrations the branch has not run yet, newer than every one it ran. */ readonly pendingMigrations: readonly string[]; /** Committed migrations older than one the branch ran, never run: merged out of order. */ @@ -122,7 +124,8 @@ async function verifyLocal(ctx: DbContext): Promise { const client = await pool.connect(); try { await client.query("begin transaction read only"); - const schemaProblems = await findSchemaProblems(rawOn(client), schema); + const { problems: schemaProblems, advice: schemaAdvice } = + await diagnoseSchema(rawOn(client), schema); const drift = await readMigrationDrift(client, { migrationsFolder: migrationsFolder(ctx.root), schemaName: schema.$schemaName, @@ -131,6 +134,7 @@ async function verifyLocal(ctx: DbContext): Promise { kind: "local", branch, schemaProblems, + schemaAdvice, pendingMigrations: drift.pending, strandedMigrations: drift.stranded, editedMigrations: drift.edited, diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index 8e92c12fc..515f94287 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -14,19 +14,39 @@ interface SchemaCheck { readonly absent: string[]; } +/** What the database lacks, and the one cause the check can name. */ +interface SchemaDiagnosis { + readonly problems: readonly string[]; + /** + * Every absent table is in schema public, with how to keep it there; + * migrating would create a second, empty copy. null when that is not the + * cause. + */ + readonly advice: string | null; +} + /** * Every declared table or column the database lacks, and every declared table - * that is a view or another non-table relation, as human-readable problems. - * pg_catalog is read rather than information_schema, which hides objects the - * role cannot access and would report a privilege gap as a missing column. + * that is a view or another non-table relation, as human-readable problems, + * with the advice for tables left in public. Setup and `appkit db verify` + * share it so both name that cause. */ -export async function findSchemaProblems( +export async function diagnoseSchema( dataPath: Pick, schema: Schema, -): Promise { - return (await checkSchema(dataPath, schema)).problems; +): Promise { + const { problems, absent } = await checkSchema(dataPath, schema); + return { + problems, + advice: + (await inPublicInstead(dataPath, schema.$schemaName, absent)) ?? null, + }; } +/** + * pg_catalog is read rather than information_schema, which hides objects the + * role cannot access and would report a privilege gap as a missing column. + */ async function checkSchema( dataPath: Pick, schema: Schema, @@ -101,13 +121,13 @@ export async function assertSchemaMatchesDatabase( dataPath: DataPath, schema: Schema, ): Promise { - const { problems, absent } = await checkSchema(dataPath, schema); + const { problems, advice } = await diagnoseSchema(dataPath, schema); if (problems.length > 0) { - const advice = - (await inPublicInstead(dataPath, schema.$schemaName, absent)) ?? - "Run `npx appkit db migrate` locally, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start."; throw databaseSetupFailed( - `the declared schema does not match the database: ${problems.join("; ")}. ${advice}`, + `the declared schema does not match the database: ${problems.join("; ")}. ${ + advice ?? + "Run `npx appkit db migrate` locally, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start." + }`, ); } } @@ -117,7 +137,7 @@ export async function assertSchemaMatchesDatabase( * `public`. Name that case; migrating would create a second, empty copy. */ async function inPublicInstead( - dataPath: DataPath, + dataPath: Pick, schemaName: string, absent: readonly string[], ): Promise { diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index e613222b6..ca4fd43c5 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -104,6 +104,8 @@ const REBUILD = /** The one next step for a failed local verify, most fundamental gap first. */ function localVerifyHint(report: LocalVerifyReport): string { + // Tables left in public: migrating would create empty copies in the app schema. + if (report.schemaAdvice) return report.schemaAdvice; if (report.editedMigrations.length > 0) { return "Restore the edited migrations from version control, and put the change in a new migration."; } diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 3c120d125..6d88e25f0 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -76,6 +76,7 @@ export interface LocalVerifyReport { readonly kind: "local"; readonly branch: string; readonly schemaProblems: readonly string[]; + readonly schemaAdvice: string | null; readonly pendingMigrations: readonly string[]; readonly strandedMigrations: readonly string[]; readonly editedMigrations: readonly string[]; From 245bde0e0f4eae800f174b75c0167db403a95f52 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:15:58 +0000 Subject: [PATCH 092/317] fix(appkit): write PGSSLMODE=require over a weaker or unsupported value init kept any existing PGSSLMODE. The Lakebase pool maps prefer to rejectUnauthorized: false, disable to no TLS, and rejects every other value, so only require gives a checked TLS connection. init now writes require over anything else and says what it replaced. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index fa75f2eac..cf8c76bbf 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -115,6 +115,12 @@ const DEFAULT_ENDPOINT_ID = "primary"; const SUSPEND_TIMEOUT = "300s"; /** 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( @@ -528,9 +534,14 @@ async function initHolding( PGUSER: identity.userName, ...(found.session === null ? {} : { APPKIT_DB_SESSION: found.session }), ...(before.PGPORT && /^\d+$/.test(before.PGPORT) ? {} : { PGPORT: "5432" }), - ...(before.PGSSLMODE ? {} : { PGSSLMODE: "require" }), + ...(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 ${database}`); updateEnvFile(envFile, values); const branchCtx: DbContext = { ...ctx, env: { ...ctx.env, ...values } }; From 2e6fb2fcb130dcda46d484ea7b78d1c74f49a468 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:15:58 +0000 Subject: [PATCH 093/317] fix(appkit): treat a variable reference in place of an app's resources as unresolved MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bundleApps read a `${var…}` string where an app's resources list, one of its entries, or a postgres block should be as "no postgres binding", so the deploy-branch guard assumed the app bound no branch. Such a reference is now an unresolved binding, and the guard refuses to apply until it has a value. The docs name the case. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 6 +- .../appkit/src/database/tooling/targets.ts | 93 +++++++++++++------ 2 files changed, 67 insertions(+), 32 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 01e79cdd8..198f2ce23 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -143,8 +143,10 @@ 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}`. While any such -reference exists, `migrate` applies migrations to no branch. The message names +`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. 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 `migrate` too. diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 2d487f2ea..b9bd8fe56 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -73,21 +73,22 @@ type BundleValue = /** As written: a `${…}` only a deploy resolves, no value, or not a resource name. */ | { readonly kind: "unresolved"; readonly written: string }; -/** One postgres resource of an app. */ -interface PostgresBinding { - /** Where it is in the merged bundle, e.g. "resources.apps.app.resources[0].postgres". */ +/** A value databricks.yml binds, and where it is written in the merged bundle. */ +interface BoundValue { + /** e.g. "resources.apps.app.resources[0].postgres.branch". */ readonly at: string; - readonly branch: BundleValue; - /** null when the binding names no database. */ - readonly database: BundleValue | null; + readonly value: BundleValue; } /** An app one target of databricks.yml deploys. */ interface BundleApp { /** Its key under resources.apps. */ readonly key: string; - /** Every postgres resource it has. */ - readonly postgres: readonly PostgresBinding[]; + /** + * The branch and database of each postgres resource it has, and any `${…}` + * standing where its resources, one of them, or a postgres block should be. + */ + readonly postgres: readonly BoundValue[]; } /** What one target binds with one set of variable values. */ @@ -295,29 +296,60 @@ function bundleValue( }; } +/** A `${…}` where only a deploy puts a structure: the files cannot say what it binds. */ +function unresolvedAt(at: string, written: unknown): BoundValue { + return { + at, + value: { + kind: "unresolved", + written: typeof written === "string" ? written : "", + }, + }; +} + +/** What an app's `resources:` binds; none when it is absent. */ +function appPostgres( + at: string, + resources: unknown, + resolve: (value: unknown) => string | null, +): BoundValue[] { + if (resources == null) return []; + if (!Array.isArray(resources)) return [unresolvedAt(at, resources)]; + return resources.flatMap((resource, index): BoundValue[] => { + const here = `${at}[${index}]`; + const item = record(resource); + if (!item) return [unresolvedAt(here, resource)]; + if (item.postgres == null) return []; + const binding = record(item.postgres); + if (!binding) return [unresolvedAt(`${here}.postgres`, item.postgres)]; + const bound: BoundValue[] = [ + { + at: `${here}.postgres.branch`, + value: bundleValue(binding.branch, resolve, "branch"), + }, + ]; + if (binding.database !== undefined) { + bound.push({ + at: `${here}.postgres.database`, + value: bundleValue(binding.database, resolve, "database"), + }); + } + return bound; + }); +} + function bundleApps( apps: Record, resolve: (value: unknown) => string | null, ): BundleApp[] { - return Object.entries(apps).map(([key, value]) => { - const app = record(value); - const resources = Array.isArray(app?.resources) ? app.resources : []; - const postgres = resources.flatMap((resource, index): PostgresBinding[] => { - const binding = record(record(resource)?.postgres); - if (!binding) return []; - return [ - { - at: `resources.apps.${key}.resources[${index}].postgres`, - branch: bundleValue(binding.branch, resolve, "branch"), - database: - binding.database === undefined - ? null - : bundleValue(binding.database, resolve, "database"), - }, - ]; - }); - return { key, postgres }; - }); + return Object.entries(apps).map(([key, value]) => ({ + key, + postgres: appPostgres( + `resources.apps.${key}.resources`, + record(value)?.resources, + resolve, + ), + })); } /** @@ -431,9 +463,10 @@ export function readDeployBoundary(root: string): DeployBoundary { const branch = parseResourceName(value.name)?.branch; if (branch) branches.add(branch); }; - for (const binding of bindings.apps.flatMap((app) => app.postgres)) { - add(`${binding.at}.branch`, binding.branch); - if (binding.database) add(`${binding.at}.database`, binding.database); + for (const { at, value } of bindings.apps.flatMap( + (app) => app.postgres, + )) { + add(at, value); } if (bindings.postgresBranch) { add("variables.postgres_branch", bindings.postgresBranch); From be65257e2cb562a3c75e594f66777cfdf3ca43d2 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:16:15 +0000 Subject: [PATCH 094/317] test(appkit): pin that introspect reads the schema schema.ts declares Without --schema-name, introspect reads the default app schema even when the schema.ts it refreshes declares another one, so an app on public has to pass the flag on every run. The explicit flag keeps overriding the declaration. Co-authored-by: Isaac Signed-off-by: ditadi --- .../introspect/tests/introspect.test.ts | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 65dee7e6f..386b1ac33 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -438,13 +438,39 @@ describe("runIntrospect", () => { expect((await loadDefaultDatabaseSchema(root)).$schemaName).toBe("public"); }); - test("the schema schema.ts declares does not change which schema is read, and declares nothing in it", async () => { + 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 root = tempApp({ [SCHEMA]: previousSchema.replace("}));", '}), { schemaName: "sales" });'), }); const before = tree(root); - const error = await refusal(root); + const error = await rejection( + runIntrospect(ctxFor(root), { + interactive: false, + importSource: BUILDER, + schemaName: "app", + }), + ); expect(catalog.calls.every((call) => call.values[0] === "app")).toBe(true); expect(error).toBeInstanceOf(IntrospectRefusedError); From 4c2d9c8b98910d682b35baa27b05f27cd22547c8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:16:33 +0000 Subject: [PATCH 095/317] test(appkit): cover readDeployTarget with a variable-overrides.json Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/targets.test.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index 9c8362087..d1dad905f 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -367,6 +367,38 @@ targets: }); }); + test("a variable-overrides.json value wins, as it does for a deploy from this checkout", () => { + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/db", + ), + ".databricks/bundle/default/variable-overrides.json": JSON.stringify({ + postgres_branch: "projects/q/branches/staging", + postgres_database: "projects/q/branches/staging/databases/staging-db", + }), + }); + + expect(readDeployTarget(root)).toEqual({ + branch: "projects/q/branches/staging", + database: "projects/q/branches/staging/databases/staging-db", + }); + }); + + test("a variable-overrides.json that leaves the branch unresolved gives no deploy target", () => { + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/db", + ), + ".databricks/bundle/default/variable-overrides.json": JSON.stringify({ + postgres_branch: { lookup: { name: "dev" } }, + }), + }); + + expect(readDeployTarget(root)).toBeNull(); + }); + test("null without databricks.yml or without a postgres binding", () => { expect(readDeployTarget(tempApp())).toBeNull(); expect( From a97babbd657f3005694dba02991649b96d9c6d6d Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:16:34 +0000 Subject: [PATCH 096/317] test(appkit): refuse a journal relation that is not the schema owner's table The migrator finds the journal by name in pg_class and then selects from and inserts into it, so a view or another role's table at that name would run as the migrator. These tests expect the catalog read to return the relation's kind and owner, the read and the write paths to refuse anything but an ordinary table owned by the schema's owner, the journal to be created only after that check and without IF NOT EXISTS, and the refusal to become a setup failure on start. Co-authored-by: Isaac Signed-off-by: ditadi --- .../migrations/tests/apply.pg.test.ts | 22 ++++++++ .../database/migrations/tests/apply.test.ts | 56 ++++++++++++++++++- .../database/tests/migrate-on-start.test.ts | 9 +++ 3 files changed, 84 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts index 7e4875576..70ea1f127 100644 --- a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -16,6 +16,7 @@ import { applyPendingMigrations, MigrationApplyError, MigrationHistoryError, + MigrationJournalError, migrationLockKey, } from "../apply"; import { hashOf, removeMigrationFolders, writeMigrations } from "./fixtures"; @@ -377,6 +378,27 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { } }); + 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 a table owned by "${role}", the owner of schema "${schema}".`, + ); + expect(await columns("notes")).toEqual([]); + }); + 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)`); diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index b065021c9..f992b4493 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -8,6 +8,7 @@ import { MigrationApplyError, MigrationBaselineMismatchError, MigrationHistoryError, + MigrationJournalError, migrationLockKey, } from "../apply"; import { MigrationFilesError } from "../paths"; @@ -38,6 +39,8 @@ interface FakeState { failCleanupOn?: RegExp; /** pg_catalog (table, column) pairs the baseline check sees. */ catalog?: Array<[string, string]>; + /** What pg_catalog holds at the journal's name; a table of the schema owner's when unset. */ + journal?: { relkind: string; owner: string; schema_owner?: string }; /** Another session holds the migration lock. */ lockHeld?: boolean; lockHolder?: { pid: number; application_name: string; state: string }; @@ -93,6 +96,13 @@ class RecordingClient { 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: [] }; + const journal = this.state.journal ?? { relkind: "r", owner: "app-sp" }; + return { + rows: [{ schema_owner: "app-sp", ...journal }], + }; + } if (text.includes("pg_get_userbyid")) { return { rows: [ @@ -172,6 +182,7 @@ function steps(statements: readonly string[]): string[] { 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?"; @@ -179,7 +190,7 @@ function steps(statements: readonly string[]): string[] { if (statement.startsWith("select hash, created_at")) return "recorded?"; if (statement.startsWith(`CREATE SCHEMA IF NOT EXISTS`)) return "create schema"; - if (statement.startsWith(`CREATE TABLE IF NOT EXISTS "app"."__drizzle`)) + if (statement.startsWith(`CREATE TABLE "app"."__drizzle_migrations"`)) return "create journal"; if (statement.startsWith(`insert into "app"."__drizzle_migrations"`)) return "record"; @@ -222,14 +233,14 @@ describe("applyPendingMigrations", () => { ...SESSION_SETUP, "journal table?", "begin", + "journal table?", "create schema", "create journal", `CREATE TABLE "app"."notes" ("id" integer);`, "record", "commit", "begin", - "create schema", - "create journal", + "journal table?", `ALTER TABLE "app"."notes" ADD COLUMN "body" text;`, `ALTER TABLE "app"."notes" ADD COLUMN "title" text;`, "record", @@ -571,6 +582,45 @@ describe("applyPendingMigrations", () => { ); }); + 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: "mallory" }, + }); + + const error = await applyPendingMigrations(pool, options(folder)).catch( + (caught: unknown) => caught, + ); + + expect(error).toBeInstanceOf(MigrationJournalError); + expect((error as Error).message).toBe( + `"app"."__drizzle_migrations" is a view owned by "mallory". The migrator reads and records applied migrations only in a table owned by "app-sp", the owner of schema "app". ` + + "Another role's view or table could run its code as the app. Drop or rename it, then deploy again. No migration was applied.", + ); + expect(steps(client.statements)).toEqual(["journal table?"]); + }); + + test("a journal table owned by a role other than the schema's owner is refused", async () => { + const folder = twoMigrations(); + const { pool, client } = fakePool({ + recorded: [], + 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 reads and records applied migrations only in a table owned by "app-sp"`, + ); + expect(client.statements).not.toContain( + `CREATE TABLE "app"."notes" ("id" integer);`, + ); + }); + test("a connection failure carries the system error code", async () => { const folder = twoMigrations(); const pool = { diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index 11bdc7cad..22c85fe6d 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -215,6 +215,15 @@ describe("migrateOnStart", () => { }), "Migration 0001_parallel is older than 0002_b", ], + [ + "a view at the journal's name", + new apply.MigrationJournalError("app", { + relkind: "v", + owner: "mallory", + schemaOwner: "app-sp", + }), + '"app"."__drizzle_migrations" is a view owned by "mallory"', + ], [ "a baseline that only partly matches", new apply.MigrationBaselineMismatchError("app", [ From 98510c475cb61e8e2cc6d8bf6095cdf296b2472a Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:17:06 +0000 Subject: [PATCH 097/317] fix(appkit): let init read the deploy target through variable-overrides.json readDeployTarget resolved the default target from databricks.yml alone, so init chose the project and database the yml names while a deploy from the checkout uses the values in .databricks/bundle//variable-overrides.json. It now reads the overridden bindings when the file exists. The deploy boundary keeps the union of both views. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/targets.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 1e751b5e8..13ecce031 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -356,9 +356,11 @@ function bundleApps( } /** - * The branch and database the default target deploys to: its first app - * binding the files resolve, else its postgres_branch and postgres_database - * variables. null without databricks.yml or a branch the files resolve. + * The branch and database the default target deploys to from this checkout: + * its first app binding the files resolve, else its postgres_branch and + * postgres_database variables, with the checkout's variable-overrides.json + * applied as a deploy would. null without databricks.yml or a branch the + * files resolve. */ export function readDeployTarget(root: string): DeployTarget | null { const targets = readBundle(root)?.targets ?? []; @@ -366,16 +368,17 @@ export function readDeployTarget(root: string): DeployTarget | null { targets.find((candidate) => candidate.isDefault) ?? targets.find((candidate) => candidate.name === "default"); if (!target) return null; + const bindings: TargetBindings = target.overridden ?? target; const resolved = (value: BundleValue | null) => value?.kind === "resolved" ? value.name : null; - const binding = target.apps + const binding = bindings.apps .flatMap((app) => app.postgres) .find((candidate) => candidate.branch.kind === "resolved"); - const branch = resolved(binding?.branch ?? target.postgresBranch); + const branch = resolved(binding?.branch ?? bindings.postgresBranch); if (!branch) return null; return { branch, - database: resolved(binding ? binding.database : target.postgresDatabase), + database: resolved(binding ? binding.database : bindings.postgresDatabase), }; } From d4cef2fb4a53cbbbd77a4758e938e6dfc58bbaf0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:18:01 +0000 Subject: [PATCH 098/317] docs: narrow what verify --deployed claims to the deployed source, bindings, state and role verify reads no database, so it cannot tell whether the migrations ran there. The help text, the pass line and the JSDoc now say what it checks instead: the snapshot's journal and SQL bytes, the postgres binding, the running state and the service principal's role. The help text also names the refusal of a workspace.host the files do not resolve. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/verify.ts | 23 ++++++++++++++----- packages/shared/src/cli/commands/db/output.ts | 2 +- .../shared/src/cli/commands/db/verify.test.ts | 2 +- packages/shared/src/cli/commands/db/verify.ts | 8 +++++-- 4 files changed, 25 insertions(+), 10 deletions(-) diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 087e35992..b4f48f570 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -73,7 +73,11 @@ type DeployedMigrations = /** The snapshot could not be read, so whether it has them is unknown. */ | { readonly evidence: "unavailable"; readonly reason: string }; -/** `appkit db verify --deployed`: whether a target's deployed app runs on its branch with the committed migrations. */ +/** + * `appkit db verify --deployed`: whether a target's deployed app is bound to + * its branch, running, and deployed from a source with the committed + * migrations. It reads no database, so not whether they ran there. + */ interface DeployVerifyReport { readonly kind: "deploy"; readonly target: string; @@ -479,7 +483,11 @@ function detail(message: string | undefined): string { return text ? `: ${text}` : ""; } -/** Whether the app is up: a running app has applied its migrations and checked its schema on start. */ +/** + * Whether the app is up. A running app passed its start, which checks its + * schema and, with APPKIT_DB_MIGRATE_ON_START=true, applies pending + * migrations; verify itself reads no database. + */ function runningProblems(app: DeployedApp, name: string): string[] { const pending = app.pending_deployment?.status; if (pending?.state === "IN_PROGRESS") { @@ -568,7 +576,8 @@ function selectTarget( * be bound to the branch and database databricks.yml names with * CAN_CONNECT_AND_CREATE, have a role on the branch for its service * principal, be running, and run a snapshot with the journal entry and SQL of - * every committed migration. + * every committed migration. That is the deployed source, not the database: + * whether the migrations ran there is not checked. */ async function verifyDeploy( ctx: DbContext, @@ -729,9 +738,11 @@ async function verifyDeploy( /** * `appkit db verify`: check the `.env` branch against schema.ts (the plugin's * startup check) and the committed migrations, read-only. With `deployed`, - * check through the Databricks API that a target's deployed app runs on its - * branch with the committed migrations; that reads no database, so it needs - * no role on the deploy branch. Nothing is written or created either way. + * check through the Databricks API that a target's deployed app is bound to + * its branch, running, and deployed from a source with the committed + * migrations; that reads no database, so it needs no role on the deploy + * branch and does not tell whether the migrations ran there. Nothing is + * written or created either way. */ export async function runVerify( ctx: DbContext, diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index ca4fd43c5..f3dd5d099 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -167,7 +167,7 @@ function printDeployVerifyReport(report: DeployVerifyReport): void { ); if (report.migrations?.evidence === "verified") { ok( - "Its active deployment has every committed migration, with the same SQL", + "Its deployed source has every committed migration, with the same journal entry and SQL", ); } return; diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index 44d7ae000..1d6b6e0fb 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -229,7 +229,7 @@ describe("appkit db verify", () => { "app my-app (target prod on https://acme.cloud.databricks.com) is running, bound to production with CAN_CONNECT_AND_CREATE, and its service principal has a role there", ); expect(printed).toContain( - "Its active deployment has every committed migration, with the same SQL", + "Its deployed source has every committed migration, with the same journal entry and SQL", ); expect(error).not.toHaveBeenCalled(); expect(process.exitCode).toBeUndefined(); diff --git a/packages/shared/src/cli/commands/db/verify.ts b/packages/shared/src/cli/commands/db/verify.ts index 1d9f0ab90..e96d06892 100644 --- a/packages/shared/src/cli/commands/db/verify.ts +++ b/packages/shared/src/cli/commands/db/verify.ts @@ -51,11 +51,15 @@ resource names the branch and database in databricks.yml with CAN_CONNECT_AND_CREATE, that its service principal has a role on the branch, that the app is running, and that the source its active deployment runs has every committed migration, with the same journal entry and SQL, and no -migration this checkout does not commit. When the checkout has +migration this checkout does not commit. It reads no database, so it does +not check that those migrations ran there. An app that sets +APPKIT_DB_MIGRATE_ON_START=true applies them on start, and a migration that +fails stops it; \`databricks apps logs\` shows why. When the checkout has .databricks/bundle//variable-overrides.json, the branch and database come from it, as a deploy from this checkout uses them. When verify cannot read that source, it fails. It refuses when the target's workspace.host is -not the workspace this shell is authenticated against. +not the workspace this shell is authenticated against, or when this +checkout's files do not resolve it. Exits 1 on any finding. Nothing is written or created. From 2189b315ddfd7bdd9e1a4709fd439f9e8961e8e6 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:18:08 +0000 Subject: [PATCH 099/317] fix(appkit): read the schema schema.ts declares when --schema-name is absent An app whose schema.ts declares another schema, public say, is refreshed where its tables live instead of in the default app schema. The explicit flag still overrides the declaration, and a schema.ts that does not load is still refused. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/introspect/index.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 1f89affeb..a87430d50 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -37,7 +37,7 @@ import { export interface IntrospectOptions { /** false: an ambiguous rename against existing history throws instead of prompting. */ readonly interactive: boolean; - /** Schema to read; defaults to DEFAULT_SCHEMA_NAME. */ + /** 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; @@ -154,9 +154,10 @@ async function readPreviousSchema(root: string): Promise { } /** - * `appkit db introspect`: read the `.env` branch's app schema from pg_catalog, - * 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. + * `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. * Columns the previous schema.ts declares keep their privacy; new ones are * written private, and a foreign key it does not declare is refused. Runs only * on your dev or session branch, and only when the branch records exactly the @@ -180,7 +181,8 @@ async function introspectHolding( ): Promise { const schemaFile = path.join(ctx.root, DEFAULT_SCHEMA_FILE); const previousSchema = await readPreviousSchema(ctx.root); - const schemaName = options.schemaName || DEFAULT_SCHEMA_NAME; + 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; From a3ad552b1ba4ba3c05cad733219107e8f44d70bb Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:18:09 +0000 Subject: [PATCH 100/317] test(appkit): cover init when the bound database is missing on the fork Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 824542050..53aec9c2c 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -828,6 +828,23 @@ describe("runInit — .env", () => { expect(fs.statSync(path.join(root, ".env")).mode & 0o777).toBe(0o600); }); + test("a database databricks.yml binds that the branch does not have is refused, naming both, before .env is written", async () => { + const lakebase = project(); + const root = tempApp({ + "databricks.yml": databricksYml( + PRODUCTION, + `${PRODUCTION}/databases/analytics`, + ), + }); + const ctx = fakeContext({ root, userName: USER, api: lakebase.api() }); + + await expect(init(ctx, { schema: "none" })).rejects.toThrow( + `Database analytics, which databricks.yml binds, is not on ${devBranchId(USER)}. Create it there (databricks postgres create-database ${DEV} --database-id analytics), or bind a database the project's branches have, then rerun \`appkit db init\`.`, + ); + expect(lakebase.calls).toContain(`getDatabase ${DEV}/databases/analytics`); + expect(fs.existsSync(path.join(root, ".env"))).toBe(false); + }); + test("the profile init authenticated with wins over the host", async () => { const lakebase = project(); const root = tempApp(); From e04a81637215de7f4c7192a1fd55edf23ca6e62b Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:18:24 +0000 Subject: [PATCH 101/317] fix(appkit): decide the public-schema ownership hint from the CREATE privilege On SQLSTATE 42501 for schema public, ownershipHint claimed the app's role has no CREATE on public whenever another role owns public, which is always the case. An app that already holds CREATE and failed on a table another role owns was told to grant a privilege it has. schemaOwnership now also reads has_schema_privilege(current_user, schema, 'CREATE') from pg_catalog, null when the schema does not exist. The hint claims missing CREATE only when it is missing; with CREATE granted it names an object another role owns as the fault and how to transfer it (ALTER TABLE ... OWNER TO). Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/migrations/ownership.ts | 21 +++++++++--- .../migrations/tests/apply.pg.test.ts | 33 +++++++++++++++++++ .../migrations/tests/ownership.test.ts | 2 ++ 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index 3136b0daa..4f54970e5 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -10,24 +10,29 @@ 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 is null when the schema does not exist. */ +/** 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. pg_catalog needs no privileges. */ +/** 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], ); @@ -35,6 +40,7 @@ export async function schemaOwnership( schemaName, owner: rows[0]?.owner ?? null, currentUser: rows[0]?.current_user ?? "", + canCreate: rows[0]?.can_create ?? null, }; } @@ -54,9 +60,16 @@ export function ownershipHint( 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 ( - `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.` + `Role "${ownership.currentUser}" can create in schema public, so an object this migration changes belongs to another role. ` + + `Have that role transfer it with ALTER TABLE public.
OWNER TO "${ownership.currentUser}", or drop schemaName from defineSchema() to use the default schema app, which the app creates and owns.` ); } if (ownership && ownership.owner !== ownership.currentUser) { diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts index 7e4875576..5a492ff07 100644 --- a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -18,6 +18,7 @@ import { MigrationHistoryError, migrationLockKey, } from "../apply"; +import { schemaOwnership } from "../ownership"; import { hashOf, removeMigrationFolders, writeMigrations } from "./fixtures"; // A real server, for what a fake cannot show: transactions, enum rules, locks @@ -377,6 +378,38 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { } }); + 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 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)`); diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index 67368d471..88015f4b9 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -18,6 +18,7 @@ describe("ownership: one owner per branch", () => { schemaName: "app", owner: "old-app-sp", currentUser: "new-app-sp", + canCreate: false, }); expect(hint).toContain( `Schema "app" is owned by "old-app-sp", but the app connects as "new-app-sp".`, @@ -34,6 +35,7 @@ describe("ownership: one owner per branch", () => { 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.`, From 15c2548f20482dfc375497777a466aaa3b94619d Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:18:29 +0000 Subject: [PATCH 102/317] docs: say startup refuses to migrate an app whose tables are still in public The "Apps with tables in public" section described the failing check but not the migrate-on-start refusal added for the implicit default schema. Describe when startup refuses, why, and the three ways out: schemaName "public", moving the tables with ALTER TABLE ... SET SCHEMA, or an explicit schemaName "app". Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 1467dd10b..d575ce05d 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -97,7 +97,11 @@ tables the first one owns. 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`. Keep them there with: +`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`. 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( @@ -108,6 +112,11 @@ export const schema = defineSchema( ); ``` +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 startup does not +refuse. + 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`. From 3983e74522ea678a7052b4dcbe6d6971ceeb5c41 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:18:37 +0000 Subject: [PATCH 103/317] fix(appkit): read and record the journal only through the schema owner's table readRecordedMigrations found the journal by name in pg_class and then selected from it, and ensureJournalTable created it with IF NOT EXISTS, so a view or another role's table at that name would have been read and written with the migrator's privileges. One check now fronts both paths. The catalog lookup returns the relation's kind, its owner and the schema's owner; anything but an ordinary table owned by the schema's owner is refused with a MigrationJournalError that names the relation, its kind and both owners. A missing table still means nothing recorded. The journal is created only after that check, without IF NOT EXISTS, so a relation that appears in between fails the transaction instead of receiving the record. migrateOnStart turns the refusal into a setup failure like the other migration errors. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 84 +++++++++++++++++-- .../database/migrations/tests/apply.test.ts | 6 +- .../src/plugins/database/migrate-on-start.ts | 2 + 3 files changed, 79 insertions(+), 13 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index cd298034e..40be14851 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -215,6 +215,43 @@ function ambiguousMessage( ); } +/** What pg_catalog holds at the journal's name. */ +interface JournalRelation { + readonly relkind: string; + readonly owner: string; + readonly schemaOwner: string; +} + +/** 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 journal's name is taken by something other than an ordinary table of + * the schema owner's. The migrator selects from and inserts into the journal + * as the app, so another role's view, or a table with its triggers, could + * run that role's code with the app's privileges. Nothing was applied. + */ +export class MigrationJournalError extends Error { + constructor(schemaName: string, relation: JournalRelation) { + const kind = + RELATION_KINDS[relation.relkind] ?? + `a relation of kind "${relation.relkind}"`; + super( + `${journalTable(schemaName)} is ${kind} owned by "${relation.owner}". ` + + `The migrator reads and records applied migrations only in a table owned by "${relation.schemaOwner}", the owner of schema "${schemaName}". ` + + "Another role's view or table could run its code as the app. Drop or rename it, then deploy again. No migration was applied.", + ); + this.name = "MigrationJournalError"; + } +} + /** The migration lock stayed taken past the wait limit. */ class MigrationLockWaitError extends Error { constructor(readonly holder: string | undefined) { @@ -296,19 +333,46 @@ function readMigrations(folder: string, journal: Journal): MigrationFile[] { }); } -/** The journal table's rows; none when the table does not exist yet. */ -async function readRecordedMigrations( +/** + * Whether the journal table exists. Every read of the journal and every + * record into it starts here, so anything else at its name is refused. + */ +async function journalTableExists( client: QueryClient, schemaName: string, -): Promise { +): Promise { // pg_catalog needs no privileges, so a missing grant is not mistaken for a missing table. - const table = await client.query( - `select 1 from pg_catalog.pg_class c + const { rows } = await client.query<{ + relkind: string; + owner: string; + schema_owner: string; + }>( + `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 + 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], ); - if (table.rows.length === 0) return []; + const found = rows[0]; + if (!found) return false; + if (found.relkind !== "r" || found.owner !== found.schema_owner) { + throw new MigrationJournalError(schemaName, { + relkind: found.relkind, + owner: found.owner, + schemaOwner: found.schema_owner, + }); + } + 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))) return []; const { rows } = await client.query<{ hash: string; created_at: string | number | null; @@ -427,11 +491,14 @@ async function ensureJournalTable( client: QueryClient, schemaName: string, ): Promise { + if (await journalTableExists(client, schemaName)) return; 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 IF NOT EXISTS ${journalTable(schemaName)} ( + `CREATE TABLE ${journalTable(schemaName)} ( id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint @@ -766,7 +833,8 @@ export async function applyPendingMigrations( if ( error instanceof MigrationBaselineMismatchError || error instanceof MigrationFilesError || - error instanceof MigrationHistoryError + error instanceof MigrationHistoryError || + error instanceof MigrationJournalError ) { throw error; } diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index f992b4493..715b31eb3 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -118,9 +118,6 @@ class RecordingClient { })), }; } - if (text.includes("pg_catalog.pg_class")) { - return { rows: this.state.recorded ? [{ one: 1 }] : [] }; - } if (text.startsWith("select hash, created_at")) { return { rows: this.state.recorded ?? [] }; } @@ -186,7 +183,6 @@ function steps(statements: readonly string[]): string[] { if (statement.includes("pg_get_userbyid")) return "schema owner?"; if (statement.includes("pg_catalog.pg_attribute")) return "baseline tables?"; - if (statement.includes("pg_catalog.pg_class")) return "journal table?"; if (statement.startsWith("select hash, created_at")) return "recorded?"; if (statement.startsWith(`CREATE SCHEMA IF NOT EXISTS`)) return "create schema"; @@ -844,7 +840,7 @@ describe("applyPendingMigrations — baseline adoption", () => { recorded: null, catalog: BASELINE_CATALOG, // The schema belongs to another role, so the journal table cannot be created in it. - failOn: /^CREATE TABLE IF NOT EXISTS "app"\."__drizzle_migrations"/, + failOn: /^CREATE TABLE "app"\."__drizzle_migrations"/, failCode: "42501", ownership: { owner: "someone-else", current_user: "app-sp" }, }); diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index a350b3537..76ec94b07 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -8,6 +8,7 @@ import { MigrationApplyError, MigrationBaselineMismatchError, MigrationHistoryError, + MigrationJournalError, } from "../../database/migrations/apply"; import { journalFile, @@ -87,6 +88,7 @@ export async function migrateOnStart( error instanceof MigrationApplyError || error instanceof MigrationBaselineMismatchError || error instanceof MigrationHistoryError || + error instanceof MigrationJournalError || error instanceof MigrationFilesError ) { throw databaseSetupFailed(error.message); From 3dd14f73e8fddaedf1ab28cc79e41ae81b599a13 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:18:43 +0000 Subject: [PATCH 104/317] fix(appkit): refuse a bound database the fork does not have instead of defaulting resolveDatabase fell back to databricks_postgres when the database databricks.yml binds was missing on the branch, so .env pointed the app at a database its deploy does not use. init now refuses, naming the database and the branch, with the command that creates it. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 28 ++++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index cf8c76bbf..af612daa9 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -395,22 +395,34 @@ async function ensureDeveloperRole( return { role: role?.name ? role : existing, action: "updated" }; } +/** + * The Postgres database .env names: the one it already names, else the one + * databricks.yml binds, read on the branch (a fork inherits its parent's + * databases), else the project's default database. A bound database the branch + * lacks is refused: pointing .env at the default one would run the app on a + * database its deploy does not use. + */ async function resolveDatabase( ctx: DbContext, branch: string, local: LocalTarget, deploy: DeployTarget | null, ): Promise { - // A real .env endpoint came with its database; forks inherit the parent's databases. if (local.database) return local.database; - if (deploy?.database) { - const database = await ctx - .api() - .getDatabase(`${branch}/databases/${resourceId(deploy.database)}`); - if (database?.status?.postgres_database) - return database.status.postgres_database; + if (!deploy?.database) return DEFAULT_DATABASE; + const id = resourceId(deploy.database); + const database = await ctx.api().getDatabase(`${branch}/databases/${id}`); + if (!database) { + throw new Error( + `Database ${id}, which databricks.yml binds, is not on ${resourceId(branch)}. 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 DEFAULT_DATABASE; + return database.status.postgres_database; } /** The profile or host init authenticated with, for a .env that names neither. */ From 4b190f9d6545c6b7db84391ec00b198ebfb35a73 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:19:10 +0000 Subject: [PATCH 105/317] test(appkit): warn when the connection check cannot be set while migrating statement_timeout is 0 for the migration session, and client_connection_check_interval is what lets the server cancel a statement whose instance died. When the server rejects that setting the migrator only logs at debug, so an operator never learns that a killed instance's statement keeps its locks until it ends. This test expects a warning that says so and names pg_terminate_backend. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/tests/apply.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 715b31eb3..13c49e2f7 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -524,8 +524,9 @@ describe("applyPendingMigrations", () => { ]); }); - test("a server that cannot check client connections still migrates", async () => { + 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/, @@ -538,6 +539,10 @@ describe("applyPendingMigrations", () => { 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 () => { From e6d5e5ce700a30e4c911b5e2ac91b1c01d09f188 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:19:11 +0000 Subject: [PATCH 106/317] fix(appkit): keep UnappliedMigrationError internal to the migrate tooling knip flags it as an unused export: the CLI reads its shape, not the class. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/migrate.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index a09144d52..cf6260d86 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -68,7 +68,7 @@ type ApplyOutcome = Pick; * stays for the next run, which generates nothing new, so this is the only * run that can report what the migration breaks. */ -export class UnappliedMigrationError extends Error { +class UnappliedMigrationError extends Error { readonly generated: GeneratedMigration; /** Statements of the kept migration that break instances still running the previous release. */ readonly breaking: readonly string[]; From f5b19fbdfe64f8e51f9fd6e9386118b930f2ec1e Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:19:14 +0000 Subject: [PATCH 107/317] test(appkit): pin introspect on empty enum labels and quoted type casts An enum label that is the empty string renders into schema.ts, which the builder then rejects, so the whole run fails instead of skipping the column. A literal default cast to a quoted type name, 'open'::app."order-status" as Postgres prints it, is dropped. The catalog test shows the shape pg_get_expr returns. Co-authored-by: Isaac Signed-off-by: ditadi --- .../introspect/tests/catalog.pg.test.ts | 16 ++++++ .../tooling/introspect/tests/render.test.ts | 56 +++++++++++++++++++ .../introspect/tests/roundtrip.test.ts | 3 + 3 files changed, 75 insertions(+) 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 index a7334f852..613cc5e35 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/catalog.pg.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/catalog.pg.test.ts @@ -41,6 +41,11 @@ describe.skipIf(!url)("readCatalog against Postgres", () => { 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 view ${s}.active_authors as select * from ${s}.authors; create materialized view ${s}.mv as select 1 as x; @@ -70,6 +75,7 @@ describe.skipIf(!url)("readCatalog against Postgres", () => { "base", "child", "events", + "orders", "parts", "posts", "refs", @@ -119,6 +125,16 @@ describe.skipIf(!url)("readCatalog against Postgres", () => { schema, values: ["open", "closed"], }); + // 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. diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index 0aaecad0d..a05e15e40 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -422,6 +422,62 @@ describe("renderSchemaSource", () => { 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( diff --git a/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts index bfdcd524f..15c90140b 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts @@ -199,6 +199,9 @@ describe("introspect round trip", () => { 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({ From 8a1ff2251095b5e16a2bc1f819e9d6639d9a3036 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:19:48 +0000 Subject: [PATCH 108/317] fix(appkit): warn about lock retention when the connection check is rejected The migration session runs with statement_timeout = 0 and relies on client_connection_check_interval for the server to cancel a statement whose instance died. When the server rejects that setting, the message was logged at debug only. It is now a warning that says a killed instance's statement keeps its locks until it ends, and how to end it with pg_terminate_backend on the pid found in pg_stat_activity. No statement deadline is added; migrations must still fit the start window. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/migrations/apply.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 40be14851..21073a952 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -398,10 +398,13 @@ async function prepareMigrationSession( ); reset.push("client_connection_check_interval"); } catch (error) { - // Postgres before 14, or a server that cannot poll sockets. - logger.debug( - "client_connection_check_interval not set: %s", + // 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, ); } } From 69da51e381084a37688de7999e76a6db4fa70b4c Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:19:50 +0000 Subject: [PATCH 109/317] fix(appkit): skip empty enum labels and parse quoted type casts in introspect An enum whose label is the empty string is skipped with that reason, since the builder rejects it and the whole run failed on the generated schema.ts. The literal-default parser takes the cast as pg_get_expr prints it, with quoted names such as app."order-status", so the default is kept. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/introspect/render.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index d2ea08863..a7f3b1916 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -181,6 +181,9 @@ function baseType( 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: "", @@ -239,6 +242,12 @@ function baseType( const isSequenceDefault = (expr: string | null) => !!expr && /^nextval\(/.test(expr); +/** + * 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, @@ -269,7 +278,7 @@ function defaultCall( case "text": case "varchar": case "enum": { - const match = /^'((?:[^']|'')*)'(?:::[\w." ]+)?$/.exec(expr); + const match = LITERAL_WITH_CAST.exec(expr); if (!match) return unsupported; const value = (match[1] ?? "").replace(/''/g, "'"); if ( From 33dbbedb24d9f4d7810a3bbea4f1407b22939fb5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:20:09 +0000 Subject: [PATCH 110/317] test(appkit): let the fake Lakebase fork copy the parent's databases A fork inherits its parent's databases, and init now refuses a bound database the fork lacks, so the fixture registers the bound database on the default branch and copies it on fork. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/tests/fakes.ts | 16 +++++++++++++++- .../src/database/tooling/tests/init.test.ts | 11 ++++++----- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/fakes.ts b/packages/appkit/src/database/tooling/tests/fakes.ts index df31a19fc..23999e80a 100644 --- a/packages/appkit/src/database/tooling/tests/fakes.ts +++ b/packages/appkit/src/database/tooling/tests/fakes.ts @@ -37,6 +37,14 @@ export class FakeLakebase { return branch; } + addDatabase(branch: string, databaseId: string, postgresDatabase: string) { + const name = `${branch}/databases/${databaseId}`; + this.databases.set(name, { + name, + status: { postgres_database: postgresDatabase }, + }); + } + addRole( branch: string, roleId: string, @@ -117,7 +125,7 @@ export class FakeLakebase { name, fake.autoEndpoint ? [fake.endpoint(name, "primary")] : [], ); - // A fork copies the parent's roles. + // A fork copies the parent's roles and databases. fake.roles.set( name, (fake.roles.get(spec.source_branch) ?? []).map((role) => ({ @@ -125,6 +133,12 @@ export class FakeLakebase { name: `${name}/roles/${role.name.split("/").pop()}`, })), ); + for (const database of fake.databases.values()) { + if (!database.name.startsWith(`${spec.source_branch}/databases/`)) + continue; + const copied = `${name}/databases/${database.name.split("/").pop()}`; + fake.databases.set(copied, { ...database, name: copied }); + } return branch; }, async listEndpoints(branch: string) { diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 53aec9c2c..679e5daa8 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -68,6 +68,11 @@ const pool = { function project(): FakeLakebase { const lakebase = new FakeLakebase(); lakebase.addBranch(PRODUCTION, { default: true }); + lakebase.addDatabase( + PRODUCTION, + "databricks-postgres", + "databricks_postgres", + ); lakebase.addRole(PRODUCTION, "alice", USER, ["DATABRICKS_SUPERUSER"]); lakebase.addRole(PRODUCTION, `dbrx-apps-${SP}`, SP); lakebase.addRole(PRODUCTION, "dbrx-apps-user-bob", "bob@example.com"); @@ -542,7 +547,7 @@ describe("runInit — session branch", () => { root: tempApp({ "databricks.yml": databricksYml( PRODUCTION, - `${PRODUCTION}/databases/db`, + `${PRODUCTION}/databases/databricks-postgres`, ), }), env: { LAKEBASE_PROJECT: P, APPKIT_DB_SESSION: "k2x9q0ab" }, @@ -799,10 +804,6 @@ describe("runInit — .env", () => { `${PRODUCTION}/databases/databricks-postgres`, ), }); - lakebase.databases.set(`${DEV}/databases/databricks-postgres`, { - name: `${DEV}/databases/databricks-postgres`, - status: { postgres_database: "databricks_postgres" }, - }); const ctx = fakeContext({ root, userName: USER, From a701f610095da67db34881fafdad3f69e790d2fc Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:20:48 +0000 Subject: [PATCH 111/317] test(appkit): keep the tables-in-public pg test from creating schema app The test proved the allowed case by creating schema app on the scratch database and left it there. The first pg test already finds a table in a real target schema, and the unit test covers a table already in app, so the pg test keeps only the refusal against a real catalog. Co-authored-by: Isaac Signed-off-by: ditadi --- .../tests/tables-left-in-public.pg.test.ts | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) 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 index 8931f1185..10a77e8ea 100644 --- 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 @@ -53,23 +53,17 @@ describe.skipIf(!url)("tables left in public, against Postgres", () => { expect(placement).toEqual({ inSchema: [here], inPublic: [there] }); }); - test("an app table still in public with nothing in app is refused; once app has it, it is not", async () => { + 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}"`, - `drop table if exists app."${table}"`, - ); + 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); - await pool.query(`create schema if not exists app`); - await pool.query(`create table app."${table}" (id int)`); - const allowed = await detectTablesLeftInPublic(catalogSqlOf(pool), schema); expect(refused).toContain(`public has ${table}`); - expect(allowed).toBeUndefined(); + expect(refused).toContain('pass { schemaName: "public" }'); }); }); From b4e2713c722a685c37c575a9adaa5d10d3c1a2fd Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:21:01 +0000 Subject: [PATCH 112/317] test(appkit): cover rerunning init after an interrupted session rotation Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 679e5daa8..8c156abdb 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -519,6 +519,47 @@ describe("runInit — session branch", () => { }); }); + test("a rerun without --session resumes a rotation that stopped before .env pointed at the new branch", async () => { + // The rotation wrote the new id, then stopped before or after the fork. + const beforeFork = project(); + beforeFork.addBranch(session("oldaaaaa"), { + expire_time: "2000-01-01T00:00:00Z", + }); + const pending = { + APPKIT_DB_SESSION: "newbbbbb", + LAKEBASE_ENDPOINT: `${session("oldaaaaa")}/endpoints/primary`, + }; + + const forked = await init(appOn(beforeFork, pending), { schema: "none" }); + + expect(forked.report).toMatchObject({ + mode: "session", + branch: session("newbbbbb"), + created: true, + }); + expect(beforeFork.branches.has(DEV)).toBe(false); + + const afterFork = project(); + afterFork.addBranch(session("oldaaaaa"), { + expire_time: "2000-01-01T00:00:00Z", + }); + afterFork.addBranch(session("newbbbbb"), { + expire_time: "2099-01-01T00:00:00Z", + }); + afterFork.addRole(session("newbbbbb"), "alice", USER, [ + "DATABRICKS_SUPERUSER", + ]); + + const resumed = await init(appOn(afterFork, pending), { schema: "none" }); + + expect(resumed.report).toMatchObject({ + mode: "session", + branch: session("newbbbbb"), + created: false, + }); + expect(afterFork.branches.has(DEV)).toBe(false); + }); + test("an expired session branch, or a 409 for one that is gone, gets a fresh session id", async () => { const lakebase = project(); lakebase.addBranch(session("k2x9q0ab"), { From 35cf0020bdc7f8e961b9ce1909379b8131b8ce10 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:21:58 +0000 Subject: [PATCH 113/317] fix(appkit): resume an interrupted session rotation on the next init A rotation writes the new session id to .env before forking. When the run stopped before .env pointed at the new branch, a rerun without --session saw an id that did not match the endpoint's branch and switched to dev mode, leaving the new id, and a fork made before the stop, unused. The default mode is now session whenever .env names a session id and points at one of your session branches; the guard still classifies the branch the run ends on. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 10 ++++++++-- packages/appkit/src/database/tooling/naming.ts | 10 +++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index af612daa9..263ca731f 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -37,6 +37,7 @@ import { import { devBranchId, isUsersBranchId, + isUsersSessionBranchId, newSessionId, parseTtl, SESSION_BRANCH_TTL, @@ -155,12 +156,17 @@ function scopeToProject( }; } -/** Session when .env points at this checkout's session branch; dev otherwise. */ +/** + * 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. Dev + * otherwise. + */ function defaultMode(local: LocalTarget, userName: string): BranchMode { const branch = parseResourceName(local.endpoint ?? undefined)?.branch; return local.session && branch && - resourceId(branch) === sessionBranchId(userName, local.session) + isUsersSessionBranchId(userName, resourceId(branch)) ? "session" : "dev"; } diff --git a/packages/appkit/src/database/tooling/naming.ts b/packages/appkit/src/database/tooling/naming.ts index d510517d7..22993d6db 100644 --- a/packages/appkit/src/database/tooling/naming.ts +++ b/packages/appkit/src/database/tooling/naming.ts @@ -62,11 +62,19 @@ export function sessionBranchId(userName: string, sessionId: string): string { return `${SESSION_PREFIX}${userHash(userName)}-${sessionId}`; } +/** Whether a branch id is one of this user's session branches, whatever its session id. */ +export function isUsersSessionBranchId( + userName: string, + branchId: string, +): boolean { + return branchId.startsWith(`${SESSION_PREFIX}${userHash(userName)}-`); +} + /** Whether a branch id is one of this user's dev or session branches. */ export function isUsersBranchId(userName: string, branchId: string): boolean { return ( branchId === devBranchId(userName) || - branchId.startsWith(`${SESSION_PREFIX}${userHash(userName)}-`) + isUsersSessionBranchId(userName, branchId) ); } From 77fdaba95978aa141662494b0b70f319d069f13d Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:23:25 +0000 Subject: [PATCH 114/317] test(appkit): pin introspect on deferrable unique keys and key sequence options A DEFERRABLE unique constraint renders as a plain .unique() with nothing in the report, unlike a deferrable foreign key. An identity or serial key whose sequence has other options (START WITH 100, say) renders as an exact id()/bigid(), which drizzle-kit writes with the defaults. The catalog test reads both from Postgres. Co-authored-by: Isaac Signed-off-by: ditadi --- .../introspect/tests/catalog.pg.test.ts | 35 +++++++++++++++ .../tooling/introspect/tests/catalog.test.ts | 29 +++++++++++- .../tooling/introspect/tests/render.test.ts | 44 ++++++++++++++++++- 3 files changed, 105 insertions(+), 3 deletions(-) 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 index 613cc5e35..610bdbb2c 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/catalog.pg.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/catalog.pg.test.ts @@ -46,6 +46,10 @@ describe.skipIf(!url)("readCatalog against Postgres", () => { 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; @@ -74,6 +78,7 @@ describe.skipIf(!url)("readCatalog against Postgres", () => { "authors", "base", "child", + "counters", "events", "orders", "parts", @@ -125,6 +130,36 @@ describe.skipIf(!url)("readCatalog against Postgres", () => { 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", diff --git a/packages/appkit/src/database/tooling/introspect/tests/catalog.test.ts b/packages/appkit/src/database/tooling/introspect/tests/catalog.test.ts index ca7f64170..29fd0f42a 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/catalog.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/catalog.test.ts @@ -12,7 +12,9 @@ describe("readCatalog", () => { name: "authors", partitioned: false, primaryKey: ["id"], - unique: [{ name: "authors_email_key", columns: ["email"] }], + unique: [ + { name: "authors_email_key", columns: ["email"], deferrable: false }, + ], foreignKeys: [], checks: [], indexes: [], @@ -70,7 +72,7 @@ describe("readCatalog", () => { }); test("partitioned tables, CHECK and EXCLUDE constraints, indexes, DEFERRABLE and MATCH FULL are kept for the report", () => { - const row = (kind: "c" | "x" | "f", name: string, extra = {}) => ({ + const row = (kind: "c" | "x" | "f" | "u", name: string, extra = {}) => ({ ...catalogRows.constraints[2], kind, name, @@ -86,6 +88,7 @@ describe("readCatalog", () => { deferrable: true, match_type: "f", }), + row("u", "posts_slug_key", { columns: ["slug"], deferrable: true }), ] as never, [ { table_name: "posts", name: "posts_status_idx" }, @@ -97,9 +100,31 @@ describe("readCatalog", () => { 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 }], diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index a05e15e40..3165e47bc 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -531,8 +531,20 @@ describe("renderSchemaSource", () => { 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" }), + 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"), ], @@ -553,7 +565,9 @@ describe("renderSchemaSource", () => { ); 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.a: CHECK or EXCLUDE constraint a_n_check is not declared", @@ -563,6 +577,34 @@ describe("renderSchemaSource", () => { ]); }); + 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( From 9dcc41d2e7c6aff728bb60a25c4828394b454584 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:23:31 +0000 Subject: [PATCH 115/317] test(appkit): cover init racing another run on the endpoint and the role Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 8c156abdb..059552acb 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -390,6 +390,103 @@ describe("runInit — dev branch", () => { }); }); +describe("runInit — a concurrent run on the same branch", () => { + /** The API that another run raced: it did `before` first, then this run's call returns 409. */ + function racedApi( + lakebase: FakeLakebase, + method: "createEndpoint" | "createRole", + ) { + const api = lakebase.api(); + const original = api[method].bind(api) as ( + ...args: unknown[] + ) => Promise; + (api as unknown as Record)[method] = async ( + ...args: unknown[] + ) => { + await original(...args); + throw conflict(method); + }; + return api; + } + + function withApi( + lakebase: FakeLakebase, + api: ReturnType, + ) { + const app = appOn(lakebase); + return fakeContext({ root: app.root, env: app.env, userName: USER, api }); + } + + test("a 409 on the endpoint reads the one the other run created", async () => { + const lakebase = project(); + lakebase.autoEndpoint = false; + const ctx = withApi(lakebase, racedApi(lakebase, "createEndpoint")); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report).toMatchObject({ + endpoint: `${DEV}/endpoints/primary`, + endpointCreated: false, + host: `primary.${devBranchId(USER)}.example.com`, + }); + expect( + lakebase.calls.filter((call) => call.startsWith("createEndpoint")), + ).toHaveLength(1); + }); + + test("a 409 on an endpoint still coming up waits for its host", async () => { + const lakebase = project(); + lakebase.autoEndpoint = false; + const api = racedApi(lakebase, "createEndpoint"); + const list = api.listEndpoints.bind(api); + let lists = 0; + api.listEndpoints = async (branch) => { + lists++; + const endpoints = await list(branch); + // The other run's endpoint has no host until the third look. + return lists < 3 + ? endpoints.map((endpoint) => ({ + ...endpoint, + status: { endpoint_type: endpoint.status?.endpoint_type }, + })) + : endpoints; + }; + const ctx = withApi(lakebase, api); + vi.useFakeTimers({ shouldAdvanceTime: true, advanceTimeDelta: 2_000 }); + try { + const { report, steps } = await init(ctx, { schema: "none" }); + + expect(report).toMatchObject({ + endpointCreated: false, + host: `primary.${devBranchId(USER)}.example.com`, + }); + expect(steps).toContain( + `Waiting for the read-write endpoint of ${devBranchId(USER)} to get a host`, + ); + expect(lists).toBe(3); + } finally { + vi.useRealTimers(); + } + }); + + test("a 409 on your role reads the one the other run created", async () => { + schemaOwner = USER; + const lakebase = new FakeLakebase(); + lakebase.addBranch(PRODUCTION, { default: true }); + const ctx = withApi(lakebase, racedApi(lakebase, "createRole")); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report.role).toEqual({ + name: `${DEV}/roles/rol-generated`, + action: "kept", + }); + expect( + lakebase.calls.filter((call) => call.startsWith("createRole")), + ).toHaveLength(1); + }); +}); + describe("runInit — branch limit", () => { test("stops before creating anything and lists your other branches with the delete command", async () => { const lakebase = project(); From 76d415ed7c1c92a02791b429546efffe244aa56f Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:24:39 +0000 Subject: [PATCH 116/317] fix(appkit): reconcile init's endpoint and role with a run that created them first ensureReadWriteEndpoint and ensureDeveloperRole checked, then created, and let a 409 from a concurrent init on the same branch surface as an error. On ALREADY_EXISTS they now reread the branch, as branch creation already does. An endpoint the other run is still bringing up is waited for until it has a host, up to 90 seconds, and the reread role gets the same membership check. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 88 ++++++++++++++------ 1 file changed, 64 insertions(+), 24 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 263ca731f..2b281348c 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -114,6 +114,8 @@ 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"; /** @@ -327,6 +329,14 @@ async function findOrCreateBranch( } } +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, @@ -342,16 +352,35 @@ async function ensureReadWriteEndpoint( onStep( `Creating a read-write endpoint on ${resourceId(branch)} that suspends after 5 idle minutes`, ); - endpoint = await api.createEndpoint(branch, DEFAULT_ENDPOINT_ID, { - suspendTimeout: SUSPEND_TIMEOUT, - }); - created = true; + 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 }, + ); + } + } } - let host = endpoint?.status?.hosts?.host; - if (!host) { + 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; - host = endpoint?.status?.hosts?.host; } + 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.`, @@ -360,6 +389,11 @@ async function ensureReadWriteEndpoint( 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, @@ -368,28 +402,34 @@ async function ensureDeveloperRole( onStep: (message: string) => void, ): Promise<{ role: LakebaseRole; action: RoleAction }> { const api = ctx.api(); - const existing = roles.find( - (r) => r.status?.postgres_role === identity.userName, - ); + 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}`, ); - const role = await api.createRole(branch, { - identity_type: identity.identityType, - postgres_role: identity.userName, - auth_method: "LAKEBASE_OAUTH_V1", - membership_roles: [SUPERUSER_MEMBERSHIP], - }); - if (role?.name) return { role, action: "created" }; - // The operation response normally carries the role; fall back to a lookup. - const found = (await api.listRoles(branch)).find( - (r) => r.status?.postgres_role === identity.userName, - ); - if (!found) { - throw new Error(`Creating your role on ${branch} did not return it.`); + 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\`.`, + ); } - return { role: found, action: "created" }; + if (created) return { role: existing, action: "created" }; } if (existing.status?.membership_roles?.includes(SUPERUSER_MEMBERSHIP)) { return { role: existing, action: "kept" }; From abba2272bd07b273cfec9dad4433c8832e9112b7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:26:41 +0000 Subject: [PATCH 117/317] fix(appkit): report deferrable unique keys and key sequence options as approximations The catalog reads DEFERRABLE on unique constraints and the options of the sequence a serial or identity column owns, as text so bigint bounds survive JSON. The render lists a deferrable unique key as declared without DEFERRABLE, as it already does for foreign keys, and a key whose sequence differs from the defaults id()/bigid() declare with the clauses on each side. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/introspect/catalog.ts | 38 +++++++++- .../src/database/tooling/introspect/render.ts | 76 ++++++++++++++++--- .../tooling/introspect/tests/fixture.ts | 6 +- .../tooling/introspect/tests/render.test.ts | 12 ++- 4 files changed, 116 insertions(+), 16 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/catalog.ts b/packages/appkit/src/database/tooling/introspect/catalog.ts index 07703b0aa..852a01633 100644 --- a/packages/appkit/src/database/tooling/introspect/catalog.ts +++ b/packages/appkit/src/database/tooling/introspect/catalog.ts @@ -13,6 +13,16 @@ export interface IntrospectedEnum { 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)". */ @@ -25,6 +35,8 @@ export interface IntrospectedColumn { /** 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 { @@ -43,6 +55,8 @@ export interface IntrospectedForeignKey { export interface IntrospectedUnique { readonly name: string; readonly columns: readonly string[]; + /** DEFERRABLE, which the builder does not declare. */ + readonly deferrable: boolean; } export interface IntrospectedTable { @@ -80,6 +94,7 @@ export interface ColumnRow { type_schema: string; type_name: string; enum_values: string[] | null; + sequence: IntrospectedSequence | null; } export interface TableRow { @@ -128,13 +143,27 @@ select c.relname::text as table_name, a.attname::text as 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 + 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`; @@ -256,6 +285,7 @@ function toColumn(row: ColumnRow): IntrospectedColumn { }, } : {}), + ...(row.sequence ? { sequence: row.sequence } : {}), }; } @@ -275,7 +305,11 @@ export function buildTables( primaryKey: own.find((row) => row.kind === "p")?.columns ?? [], unique: own .filter((row) => row.kind === "u") - .map((row) => ({ name: row.name, columns: row.columns })), + .map((row) => ({ + name: row.name, + columns: row.columns, + deferrable: row.deferrable === true, + })), foreignKeys: own .filter((row) => row.kind === "f" && row.ref_table) .map((row) => ({ diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index a7f3b1916..4313162fb 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -7,6 +7,7 @@ import type { AppKitTable, Schema } from "../../schema-builder/types"; import type { IntrospectedColumn, IntrospectedForeignKey, + IntrospectedSequence, IntrospectedTable, } from "./catalog"; @@ -242,6 +243,48 @@ function baseType( 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 `"`. @@ -442,11 +485,11 @@ export function renderSchemaSource( const tableApproximated: string[] = []; const tableRenamed: string[] = []; const columnReasons = new Map(); - /** Single-column unique constraints: column → constraint name. */ + /** 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.name]), + .map((unique) => [unique.columns[0] as string, unique]), ); const tableUnexpressed: Unexpressed[] = []; for (const unique of table.unique.filter((u) => u.columns.length > 1)) { @@ -516,10 +559,17 @@ export function renderSchemaSource( `${qualified(table.name, column.name)}: ${base.approximation}`, ); } - const uniqueName = singleUnique.get(column.name); + const unique = singleUnique.get(column.name); const migrationsUnique = pgName(`${table.name}_${column.name}_unique`); - if (columnPlan.isUnique && uniqueName !== migrationsUnique) { - tableRenamed.push(`${uniqueName} (${migrationsUnique})`); + if (columnPlan.isUnique && unique) { + if (unique.name !== migrationsUnique) { + tableRenamed.push(`${unique.name} (${migrationsUnique})`); + } + if (unique.deferrable) { + tableApproximated.push( + `${qualified(table.name, column.name)}: the unique constraint is declared without DEFERRABLE`, + ); + } } const generatesKey = column.identity !== "" || isSequenceDefault(column.defaultExpr); @@ -529,13 +579,19 @@ export function renderSchemaSource( (base.storage === "integer" || base.storage === "bigint") ) { // A serial or identity key is the builder's server-generated id()/bigid(). - columnPlan.base = - base.storage === "integer" - ? { call: "id()", importName: "id", storage: "id" } - : { call: "bigid()", importName: "bigid", storage: "bigid" }; + const serverKey = SERVER_KEYS[base.storage]; + columnPlan.base = serverKey.base; if (column.identity !== "d") { tableApproximated.push( - `${qualified(table.name, column.name)}: ${column.identity === "a" ? "GENERATED ALWAYS AS IDENTITY" : "a serial key"} is declared as ${columnPlan.base.call}, an identity generated BY DEFAULT`, + `${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) { + tableApproximated.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) { diff --git a/packages/appkit/src/database/tooling/introspect/tests/fixture.ts b/packages/appkit/src/database/tooling/introspect/tests/fixture.ts index 2f8b2f9ff..652e0a168 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/fixture.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/fixture.ts @@ -58,6 +58,7 @@ export const uniqueKey = ( ): IntrospectedUnique => ({ name: `${table}_${columns.join("_")}_key`, columns, + deferrable: false, }); const status = { @@ -171,6 +172,7 @@ export const columnRow = ( type_schema: "pg_catalog", type_name: type, enum_values: null, + sequence: null, ...extra, }); @@ -275,8 +277,8 @@ export function catalogResponder( values: readonly unknown[], ) => { calls.push({ text, values }); - // The unread and index queries mention what the others match on, so they go first. - const result = text.includes("pg_catalog.pg_depend") + // 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 diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index 3165e47bc..5559fac3b 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -617,7 +617,9 @@ describe("renderSchemaSource", () => { [ tableOf({ ...keyed("u", [col("email", "text")]), - unique: [{ name: "u_email_unique", columns: ["email"] }], + unique: [ + { name: "u_email_unique", columns: ["email"], deferrable: false }, + ], }), keyed( "t", @@ -637,7 +639,13 @@ describe("renderSchemaSource", () => { 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] }], + unique: [ + { + name: `t_${"ç".repeat(30)}`, + columns: [column], + deferrable: false, + }, + ], }), ], "app", From 70cf7659012f06cbf1824ddec501fec295450d9b Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:28:12 +0000 Subject: [PATCH 118/317] test(appkit): advance fake time for init's endpoint wait instead of sleeping Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/tests/init.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 059552acb..9a3467acf 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -452,9 +452,12 @@ describe("runInit — a concurrent run on the same branch", () => { : endpoints; }; const ctx = withApi(lakebase, api); - vi.useFakeTimers({ shouldAdvanceTime: true, advanceTimeDelta: 2_000 }); + vi.useFakeTimers(); try { - const { report, steps } = await init(ctx, { schema: "none" }); + const run = init(ctx, { schema: "none" }); + // init reaches its wait in microtasks; the async advance lets them run, then fires the wait's timer. + await vi.advanceTimersByTimeAsync(2_000); + const { report, steps } = await run; expect(report).toMatchObject({ endpointCreated: false, From fd45a8e8ccc760916f6d210236c92950d9ed6281 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:28:16 +0000 Subject: [PATCH 119/317] test(appkit): cover the packageManager field and the launcher in the drizzle-kit install Co-authored-by: Isaac Signed-off-by: ditadi --- .../tooling/tests/drizzle-kit-install.test.ts | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts b/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts index 6e3293f0c..c149a73c0 100644 --- a/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts +++ b/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts @@ -7,7 +7,10 @@ import { drizzleKitInstall, ensureDrizzleKit } from "../drizzle-kit-install"; import { DRIZZLE_KIT_VERSION } from "../migrations"; import { cleanupTempApps, tempApp } from "./fakes"; -afterEach(cleanupTempApps); +afterEach(() => { + cleanupTempApps(); + vi.unstubAllEnvs(); +}); const SPEC = `drizzle-kit@${DRIZZLE_KIT_VERSION}`; @@ -35,6 +38,35 @@ describe("drizzleKitInstall", () => { }); expect(drizzleKitInstall(path.join(root, "apps/web")).command).toBe("pnpm"); }); + + test("the packageManager field wins over a conflicting lockfile, in the app and in its workspace root", () => { + const declared = tempApp({ + "package.json": JSON.stringify({ packageManager: "yarn@4.0.0" }), + "package-lock.json": "{}", + }); + expect(drizzleKitInstall(declared).command).toBe("yarn"); + + const workspace = tempApp({ + "package.json": JSON.stringify({ packageManager: "bun@1.1.0" }), + "package-lock.json": "{}", + "apps/web/package.json": "{}", + }); + expect(drizzleKitInstall(path.join(workspace, "apps/web")).command).toBe( + "bun", + ); + }); + + test("without a field or lockfile anywhere, the launcher's manager is used, else npm", () => { + const root = tempApp({ "package.json": "{}" }); + vi.stubEnv("npm_config_user_agent", "yarn/4.0.0 npm/? node/v22"); + expect(drizzleKitInstall(root).command).toBe("yarn"); + + vi.stubEnv("npm_config_user_agent", undefined); + expect(drizzleKitInstall(root)).toEqual({ + command: "npm", + args: ["install", "--save-dev", "--save-exact", SPEC], + }); + }); }); describe("ensureDrizzleKit", () => { From 8a72c33592b68cd3220a7432ae867b5ca09a999b Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:28:20 +0000 Subject: [PATCH 120/317] test(appkit): cover clean's dependents through views over views and dropped columns Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/clean.pg.test.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/clean.pg.test.ts b/packages/appkit/src/database/tooling/tests/clean.pg.test.ts index 646502e92..7f40e011c 100644 --- a/packages/appkit/src/database/tooling/tests/clean.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean.pg.test.ts @@ -45,10 +45,15 @@ describe.skipIf(!url)("clean against Postgres", () => { create type "${app}".kind as enum ('a', 'b'); create table "${app}".notes (id integer primary key, kind "${app}".kind); create table "${app}".__drizzle_migrations (id serial primary key); + create view "${app}".ordered as select id from "${app}".notes order by id; create schema "${other}"; create view "${other}".recent as select id from "${app}".notes; + create view "${other}".recent_ids as select id from "${other}".recent; + create view "${other}".ordered_too as select id from "${app}".ordered; create table "${other}".refs (id integer primary key, note_id integer constraint refs_note_fk references "${app}".notes (id)); create table "${other}".tagged (id integer primary key, kind "${app}".kind); + create view "${other}".tagged_kinds as select kind from "${other}".tagged; + create view "${other}".tagged_ids as select id from "${other}".tagged; `); }); afterAll(async () => { @@ -57,13 +62,16 @@ describe.skipIf(!url)("clean against Postgres", () => { await pool.end(); }); - test("reports what CASCADE drops outside the schema, then drops the schema and only those", async () => { + test("reports everything CASCADE drops outside the schema, through views over views and dropped columns, then drops the schema and only those", async () => { const dependents = await clean(pool, app); expect(dependents).toEqual([ `column kind of table ${other}.tagged`, `constraint refs_note_fk on table ${other}.refs`, + `view ${other}.ordered_too`, `view ${other}.recent`, + `view ${other}.recent_ids`, + `view ${other}.tagged_kinds`, ]); expect( await names( @@ -76,7 +84,7 @@ describe.skipIf(!url)("clean against Postgres", () => { pool, `select relname as name from pg_class where relnamespace = '"${other}"'::regnamespace and relkind in ('r', 'v') order by 1`, ), - ).toEqual(["refs", "tagged"]); + ).toEqual(["refs", "tagged", "tagged_ids"]); }); }); From aba97d5f32581cd345e15839d4a490c314093ba1 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:29:17 +0000 Subject: [PATCH 121/317] test(appkit): pin that introspect refuses a symlinked schema.ts or .bak introspect writes schema.ts and schema.ts.bak with writeFileSync, which follows a symbolic link at either path and overwrites whatever it points at. Co-authored-by: Isaac Signed-off-by: ditadi --- .../introspect/tests/introspect.test.ts | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 386b1ac33..666f572b6 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -422,6 +422,39 @@ describe("runIntrospect", () => { }, ); + 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(); From 6213b0a521f7bdbb253c287c4ee36df1f1d0161b Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:31:06 +0000 Subject: [PATCH 122/317] test(appkit): accept the app's own journal in a schema another role owns journalTableExists refuses the journal unless its owner is the schema's owner. On `public` the schema belongs to the database owner (or to pg_database_owner on Postgres 15 and Lakebase) while the app's service principal creates and owns the journal there, so every app with schemaName "public" fails its second start, and local tooling reading an SP-owned journal in `public` fails with it. These tests expect the journal's owner to be trusted when the connecting role owns it or inherits it, or when it is the schema's owner. A table of an untrusted owner is still read when it has no row-level security, since a plain SELECT runs no code of its owner's, and it is refused when the migrator would record into it, naming both roles and the fix. Row-level security on such a table refuses the read. A view is refused as before. The Postgres test builds the `public` shape with real roles and expects two starts to read and record through the app's own journal. Co-authored-by: Isaac Signed-off-by: ditadi --- .../migrations/tests/apply.pg.test.ts | 41 +++++- .../database/migrations/tests/apply.test.ts | 121 +++++++++++++++--- 2 files changed, 146 insertions(+), 16 deletions(-) diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts index 70ea1f127..3fc33b582 100644 --- a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -378,6 +378,45 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { } }); + 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( @@ -394,7 +433,7 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { 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 a table owned by "${role}", the owner of schema "${schema}".`, + `"${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([]); }); diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 13c49e2f7..65420f20b 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -39,8 +39,13 @@ interface FakeState { failCleanupOn?: RegExp; /** pg_catalog (table, column) pairs the baseline check sees. */ catalog?: Array<[string, string]>; - /** What pg_catalog holds at the journal's name; a table of the schema owner's when unset. */ - journal?: { relkind: string; owner: string; schema_owner?: 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 }; @@ -98,9 +103,25 @@ class RecordingClient { } if (text.includes("c.relowner")) { if (this.state.recorded === null) return { rows: [] }; - const journal = this.state.journal ?? { relkind: "r", owner: "app-sp" }; + // 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: [{ schema_owner: "app-sp", ...journal }], + rows: [ + { + ...journal, + current_user: "app-sp", + trusted: + journal.owner === "app-sp" || + journal.owner === journal.schema_owner, + }, + ], }; } if (text.includes("pg_get_userbyid")) { @@ -583,11 +604,84 @@ describe("applyPendingMigrations", () => { ); }); - test("a view at the journal's name is refused before anything runs", async () => { + 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 transfer the table to "app-sp" (ALTER TABLE … OWNER TO), 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: "v", owner: "mallory" }, + journal: { + relkind: "r", + owner: "mallory", + schema_owner: "app-sp", + row_security: true, + }, }); const error = await applyPendingMigrations(pool, options(folder)).catch( @@ -595,18 +689,17 @@ describe("applyPendingMigrations", () => { ); expect(error).toBeInstanceOf(MigrationJournalError); - expect((error as Error).message).toBe( - `"app"."__drizzle_migrations" is a view owned by "mallory". The migrator reads and records applied migrations only in a table owned by "app-sp", the owner of schema "app". ` + - "Another role's view or table could run its code as the app. Drop or rename it, then deploy again. No migration was applied.", + 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(steps(client.statements)).toEqual(["journal table?"]); }); - test("a journal table owned by a role other than the schema's owner is refused", async () => { + test("a view at the journal's name is refused before anything runs", async () => { const folder = twoMigrations(); const { pool, client } = fakePool({ recorded: [], - journal: { relkind: "r", owner: "mallory", schema_owner: "app-sp" }, + journal: { relkind: "v", owner: "app-sp" }, }); const error = await applyPendingMigrations(pool, options(folder)).catch( @@ -615,11 +708,9 @@ describe("applyPendingMigrations", () => { expect(error).toBeInstanceOf(MigrationJournalError); expect((error as Error).message).toContain( - `"app"."__drizzle_migrations" is a table owned by "mallory". The migrator reads and records applied migrations only in a table owned by "app-sp"`, - ); - expect(client.statements).not.toContain( - `CREATE TABLE "app"."notes" ("id" integer);`, + `"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 () => { From c756912d62038d4c41af30762b448dd755d6e449 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:31:40 +0000 Subject: [PATCH 123/317] fix(appkit): refuse symlinked destinations and write schema.ts atomically A new tooling/files.ts holds refuseSymlink and writeFileAtomic: lstat the destination and refuse a link, then write a sibling temporary file and rename it over, so a crash leaves the old file or the new one. introspect refuses a symlinked schema.ts or schema.ts.bak before it reads anything, and writes and restores both through the helper. migrations.ts drops its own copy of the rename and writes the journal through the same helper. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/files.ts | 37 ++++++++++ .../src/database/tooling/introspect/index.ts | 22 +++++- .../appkit/src/database/tooling/migrations.ts | 16 +--- .../src/database/tooling/tests/files.test.ts | 74 +++++++++++++++++++ 4 files changed, 131 insertions(+), 18 deletions(-) create mode 100644 packages/appkit/src/database/tooling/files.ts create mode 100644 packages/appkit/src/database/tooling/tests/files.test.ts diff --git a/packages/appkit/src/database/tooling/files.ts b/packages/appkit/src/database/tooling/files.ts new file mode 100644 index 000000000..4329c09d8 --- /dev/null +++ b/packages/appkit/src/database/tooling/files.ts @@ -0,0 +1,37 @@ +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): void { + refuseSymlink(file); + const temporary = path.join( + path.dirname(file), + `.${path.basename(file)}.${randomUUID()}.tmp`, + ); + try { + fs.writeFileSync(temporary, content); + fs.renameSync(temporary, file); + } finally { + fs.rmSync(temporary, { force: true }); + } +} diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index a87430d50..e075c00da 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -15,6 +15,7 @@ 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 { DATABASE_TYPES_PATH } from "../migrate"; @@ -80,7 +81,20 @@ function readIfExists(file: string): string | null { function writeOrRemove(file: string, contents: string | null): void { if (contents === null) fs.rmSync(file, { force: true }); - else fs.writeFileSync(file, contents); + 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) => @@ -180,6 +194,8 @@ async function introspectHolding( 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; @@ -293,9 +309,9 @@ async function introspectHolding( let migration: GeneratedMigration | null = null; let recorded: string[] = []; try { - if (backsUp) fs.writeFileSync(backupFile, previous); + if (backsUp) writeFileAtomic(backupFile, previous); fs.mkdirSync(path.dirname(schemaFile), { recursive: true }); - fs.writeFileSync(schemaFile, rendered.source); + writeFileAtomic(schemaFile, rendered.source); let schema: Awaited>; try { schema = await loadDefaultDatabaseSchema(ctx.root, { diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 8af975372..b9b2d7bb5 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -1,4 +1,3 @@ -import { randomUUID } from "node:crypto"; import fs from "node:fs"; import { createRequire } from "node:module"; import path from "node:path"; @@ -16,6 +15,7 @@ import { } from "../migrations/paths"; import type { Schema } from "../schema-builder"; import { drizzleKitImports } from "./drizzle-exports"; +import { writeFileAtomic } from "./files"; import type { HistoryLock } from "./history-lock"; /** @@ -280,20 +280,6 @@ export function breakingStatements(statements: readonly string[]): string[] { ); } -/** Replace a file through a rename, so a crash never leaves it half written. */ -function writeFileAtomic(file: string, content: string): void { - const temporary = path.join( - path.dirname(file), - `.${path.basename(file)}.${randomUUID()}.tmp`, - ); - try { - fs.writeFileSync(temporary, content); - fs.renameSync(temporary, file); - } finally { - fs.rmSync(temporary, { force: true }); - } -} - /** * Diff the schema against the latest committed snapshot with drizzle-kit and * write the next v7 migration: `NNNN_.sql`, `meta/NNNN_snapshot.json`, diff --git a/packages/appkit/src/database/tooling/tests/files.test.ts b/packages/appkit/src/database/tooling/tests/files.test.ts new file mode 100644 index 000000000..61e73cda0 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/files.test.ts @@ -0,0 +1,74 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, test } from "vitest"; + +import { refuseSymlink, SymlinkRefusedError, writeFileAtomic } from "../files"; + +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) + fs.rmSync(dir, { recursive: true, force: true }); +}); +const tempDir = () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-files-")); + dirs.push(dir); + return dir; +}; + +describe("writeFileAtomic", () => { + test("creates the file, replaces it, and leaves no temporary file behind", () => { + const dir = tempDir(); + const file = path.join(dir, "a.txt"); + + writeFileAtomic(file, "one"); + expect(fs.readFileSync(file, "utf-8")).toBe("one"); + + writeFileAtomic(file, "two"); + expect(fs.readFileSync(file, "utf-8")).toBe("two"); + expect(fs.readdirSync(dir)).toEqual(["a.txt"]); + }); + + test("refuses a symbolic link and leaves the link and its target as they were", () => { + const dir = tempDir(); + const target = path.join(dir, "target.txt"); + fs.writeFileSync(target, "kept"); + const link = path.join(dir, "link.txt"); + fs.symlinkSync(target, link); + + expect(() => writeFileAtomic(link, "new")).toThrow(SymlinkRefusedError); + + expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); + expect(fs.readFileSync(target, "utf-8")).toBe("kept"); + expect(fs.readdirSync(dir).sort()).toEqual(["link.txt", "target.txt"]); + }); + + test("a write that fails leaves no temporary file behind", () => { + const dir = tempDir(); + + expect(() => + writeFileAtomic(path.join(dir, "missing", "a.txt"), "x"), + ).toThrow(); + + expect(fs.readdirSync(dir)).toEqual([]); + }); +}); + +describe("refuseSymlink", () => { + test("passes a missing file and a regular file", () => { + const dir = tempDir(); + fs.writeFileSync(path.join(dir, "plain"), ""); + + expect(() => refuseSymlink(path.join(dir, "none"))).not.toThrow(); + expect(() => refuseSymlink(path.join(dir, "plain"))).not.toThrow(); + }); + + test("refuses a dangling link too, naming it", () => { + const dir = tempDir(); + const link = path.join(dir, "link"); + fs.symlinkSync(path.join(dir, "none"), link); + + expect(() => refuseSymlink(link)).toThrow(new SymlinkRefusedError(link)); + }); +}); From 63f4d9319976ace49440704cb564c1b172cffd97 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:34:06 +0000 Subject: [PATCH 124/317] fix(appkit): pick drizzle-kit's installer with the shared package-manager detection drizzle-kit-install re-implemented package-manager detection from lockfiles alone, so an app whose package.json declares packageManager next to another manager's lockfile got the wrong installer. The lockfile and field policy now lives once, in shared's declaredPackageManager, which detectPackageManager also uses. The install keeps its walk to the nearest ancestor that declares a manager, for workspace members, and falls back to the launcher, then npm. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/drizzle-kit-install.ts | 44 ++++++++++--------- .../shared/src/cli/package-manager.test.ts | 36 ++++++++++++++- packages/shared/src/cli/package-manager.ts | 36 +++++++++------ 3 files changed, 82 insertions(+), 34 deletions(-) diff --git a/packages/appkit/src/database/tooling/drizzle-kit-install.ts b/packages/appkit/src/database/tooling/drizzle-kit-install.ts index 9fa9e9c36..7da9d5cb5 100644 --- a/packages/appkit/src/database/tooling/drizzle-kit-install.ts +++ b/packages/appkit/src/database/tooling/drizzle-kit-install.ts @@ -2,6 +2,11 @@ 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, hasDrizzleKit } from "./migrations"; /** Runs a command in `cwd`; throws when it fails. */ @@ -11,36 +16,35 @@ export type RunCommand = ( cwd: string, ) => void; -/** Exact dev-dependency installs, by the lockfile that names the package manager. */ -const MANAGERS: ReadonlyArray< - readonly [lockfile: string, command: string, args: readonly string[]] -> = [ - ["pnpm-lock.yaml", "pnpm", ["add", "-D", "-E"]], - ["yarn.lock", "yarn", ["add", "-D", "-E"]], - ["bun.lock", "bun", ["add", "-d", "--exact"]], - ["bun.lockb", "bun", ["add", "-d", "--exact"]], - ["package-lock.json", "npm", ["install", "--save-dev", "--save-exact"]], -]; +/** 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 package manager whose lockfile is nearest `root`; npm without one. */ +/** + * The install with the manager the app declares, by packageManager field or + * lockfile, in its own directory or the nearest ancestor's (a workspace member + * has neither; its root does). Without one, the manager that launched this + * command, else npm. + */ export function drizzleKitInstall(root: string): Install { - const spec = `drizzle-kit@${DRIZZLE_KIT_VERSION}`; + let manager: PackageManager | null = null; for (let dir = path.resolve(root); ; dir = path.dirname(dir)) { - for (const [lockfile, command, args] of MANAGERS) { - if (fs.existsSync(path.join(dir, lockfile))) { - return { command, args: [...args, spec] }; - } - } - if (dir === path.dirname(dir)) break; + manager = declaredPackageManager(dir); + if (manager || dir === path.dirname(dir)) break; } + const command = manager ?? detectPackageManager(root, "npm"); return { - command: "npm", - args: ["install", "--save-dev", "--save-exact", spec], + command, + args: [...INSTALL_ARGS[command], `drizzle-kit@${DRIZZLE_KIT_VERSION}`], }; } diff --git a/packages/shared/src/cli/package-manager.test.ts b/packages/shared/src/cli/package-manager.test.ts index 9741c792b..69725523c 100644 --- a/packages/shared/src/cli/package-manager.test.ts +++ b/packages/shared/src/cli/package-manager.test.ts @@ -4,9 +4,43 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { detectPackageManager, PM_COMMANDS } from "./package-manager"; +import { + declaredPackageManager, + detectPackageManager, + PM_COMMANDS, +} from "./package-manager"; describe("package-manager", () => { + describe("declaredPackageManager", () => { + let cwd: string; + + beforeEach(() => { + cwd = fs.mkdtempSync(path.join(os.tmpdir(), "pm-declared-")); + vi.stubEnv("npm_config_user_agent", "pnpm/11.0.8"); + }); + + afterEach(() => { + fs.rmSync(cwd, { recursive: true, force: true }); + vi.unstubAllEnvs(); + }); + + it("is null without a field or lockfile, whatever launched the command", () => { + expect(declaredPackageManager(cwd)).toBeNull(); + fs.writeFileSync(path.join(cwd, "package.json"), "{}"); + expect(declaredPackageManager(cwd)).toBeNull(); + }); + + it("prefers the packageManager field over a lockfile", () => { + fs.writeFileSync(path.join(cwd, "yarn.lock"), ""); + expect(declaredPackageManager(cwd)).toBe("yarn"); + fs.writeFileSync( + path.join(cwd, "package.json"), + JSON.stringify({ packageManager: "bun@1.1.0" }), + ); + expect(declaredPackageManager(cwd)).toBe("bun"); + }); + }); + describe("detectPackageManager", () => { let cwd: string; diff --git a/packages/shared/src/cli/package-manager.ts b/packages/shared/src/cli/package-manager.ts index 49b34335d..ad07bf0fb 100644 --- a/packages/shared/src/cli/package-manager.ts +++ b/packages/shared/src/cli/package-manager.ts @@ -10,16 +10,13 @@ function isPackageManager(value: string): value is PackageManager { } /** - * Prefers the project's packageManager field, then its lockfiles, then - * npm_config_user_agent. The launcher (e.g. npx) may use a different manager. + * The manager a directory's own files name: its package.json's packageManager + * field, else its lockfile. null when neither names one. */ -export function detectPackageManager( - cwd: string, - fallback: PackageManager = "pnpm", -): PackageManager { +export function declaredPackageManager(dir: string): PackageManager | null { try { const pkg = JSON.parse( - fs.readFileSync(path.join(cwd, "package.json"), "utf-8"), + fs.readFileSync(path.join(dir, "package.json"), "utf-8"), ) as { packageManager?: unknown } | null; if (typeof pkg?.packageManager === "string") { const name = pkg.packageManager.split("@")[0]; @@ -29,20 +26,33 @@ export function detectPackageManager( // A missing or unreadable manifest still permits lockfile detection. } - if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) return "pnpm"; - if (fs.existsSync(path.join(cwd, "yarn.lock"))) return "yarn"; + if (fs.existsSync(path.join(dir, "pnpm-lock.yaml"))) return "pnpm"; + if (fs.existsSync(path.join(dir, "yarn.lock"))) return "yarn"; if ( - fs.existsSync(path.join(cwd, "bun.lock")) || - fs.existsSync(path.join(cwd, "bun.lockb")) + fs.existsSync(path.join(dir, "bun.lock")) || + fs.existsSync(path.join(dir, "bun.lockb")) ) { return "bun"; } if ( - fs.existsSync(path.join(cwd, "package-lock.json")) || - fs.existsSync(path.join(cwd, "npm-shrinkwrap.json")) + fs.existsSync(path.join(dir, "package-lock.json")) || + fs.existsSync(path.join(dir, "npm-shrinkwrap.json")) ) { return "npm"; } + return null; +} + +/** + * Prefers the project's packageManager field, then its lockfiles, then + * npm_config_user_agent. The launcher (e.g. npx) may use a different manager. + */ +export function detectPackageManager( + cwd: string, + fallback: PackageManager = "pnpm", +): PackageManager { + const declared = declaredPackageManager(cwd); + if (declared) return declared; const userAgent = process.env.npm_config_user_agent; if (userAgent) { From 257e47a5bd0e8d3dba6868437bf1224f915dc109 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:34:11 +0000 Subject: [PATCH 125/317] fix(appkit): list every object clean's CASCADE removes, not only direct dependents The preview joined pg_depend once, so a view over a view in another schema, or a view over a column of a dropped type, was dropped without being listed, and a view's column stood in for the view. The query is now a recursive closure over normal, auto and internal dependencies, where a rewrite rule or a view column stands for its view, listing what a normal dependency reached, as DROP's own notice does. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/clean.ts | 70 ++++++++++++------- 1 file changed, 44 insertions(+), 26 deletions(-) diff --git a/packages/appkit/src/database/tooling/clean.ts b/packages/appkit/src/database/tooling/clean.ts index ef5227c3e..c137aeb5d 100644 --- a/packages/appkit/src/database/tooling/clean.ts +++ b/packages/appkit/src/database/tooling/clean.ts @@ -78,12 +78,17 @@ $appkit$`, } /** - * Objects outside what clean drops that depend on it, so CASCADE removes them - * too: a view in another schema, a foreign key into an app table, a column of - * an app type. For public, "outside" also means owned by another role. + * 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 target as ( +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 @@ -96,51 +101,64 @@ with target as ( 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 pg_catalog.pg_depend d - join dropped on d.refclassid = dropped.classid and d.refobjid = dropped.objid + from gone g cross join lateral ( select c.relnamespace as namespace, c.relowner as owner, - pg_catalog.pg_describe_object(d.classid, d.objid, d.objsubid) as label + pg_catalog.pg_describe_object(g.classid, g.objid, g.objsubid) as label from pg_catalog.pg_class c - where d.classid = 'pg_catalog.pg_class'::regclass and c.oid = d.objid - union all - select c.relnamespace, c.relowner, - pg_catalog.pg_describe_object('pg_catalog.pg_class'::regclass, c.oid, 0) - from pg_catalog.pg_rewrite r join pg_catalog.pg_class c on c.oid = r.ev_class - where d.classid = 'pg_catalog.pg_rewrite'::regclass and r.oid = d.objid + 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(d.classid, d.objid, 0) + 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 d.classid = 'pg_catalog.pg_constraint'::regclass and con.oid = d.objid + 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(d.classid, d.objid, 0) + select p.pronamespace, p.proowner, pg_catalog.pg_describe_object(g.classid, g.objid, 0) from pg_catalog.pg_proc p - where d.classid = 'pg_catalog.pg_proc'::regclass and p.oid = d.objid + 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(d.classid, d.objid, 0) + select t.typnamespace, t.typowner, pg_catalog.pg_describe_object(g.classid, g.objid, 0) from pg_catalog.pg_type t - where d.classid = 'pg_catalog.pg_type'::regclass and t.oid = d.objid + 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(d.classid, d.objid, 0) + 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 d.classid = 'pg_catalog.pg_trigger'::regclass and tg.oid = d.objid + 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(d.classid, d.objid, 0) + 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 d.classid = 'pg_catalog.pg_attrdef'::regclass and a.oid = d.objid + 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(d.classid, d.objid, 0) + 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 d.classid = 'pg_catalog.pg_policy'::regclass and pol.oid = d.objid + where g.classid = 'pg_catalog.pg_policy'::regclass and pol.oid = g.objid ) o cross join target cross join me - where d.deptype = 'n' + where g.listed and (o.namespace <> target.oid or ($2 and o.owner <> me.oid)) order by 1`; From 03fd6a019cf898a0626d3b79e1a9a5f380bff3c4 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:34:37 +0000 Subject: [PATCH 126/317] fix(appkit): trust the journal's owner by role, not by the schema's owner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit journalTableExists accepted the journal only when its owner was the schema's owner. On `public` that owner is the database owner (or pg_database_owner on Postgres 15 and Lakebase) while the app's service principal creates and owns the journal there, so every app with schemaName "public" failed its second start, and local tooling reading an SP-owned journal in `public` failed with it. The threat is a relation at the journal's name that another role controls and that runs code when the migrator reads or records: a view, a row-security policy, triggers, rules and column defaults. The catalog query now also returns whether the connecting role owns the relation or inherits its owner (pg_has_role with USAGE), or the owner is the schema's; either makes the owner trusted. Anything but an ordinary table is still refused. A trusted owner's table is read and recorded into. An untrusted owner's table is read when it has no row-level security, since a plain SELECT runs none of its owner's code, and refused for the read when it does; recording into it is refused, with a message that names the owner and the connecting role and says to have the owner run the migration or transfer the table with ALTER TABLE … OWNER TO. MigrationJournalError takes the refusal next to the relation. The missing-table path and the CREATE without IF NOT EXISTS are unchanged. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 124 ++++++++++++++---- .../database/tests/migrate-on-start.test.ts | 17 ++- 2 files changed, 111 insertions(+), 30 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 21073a952..2c8f9b756 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -215,11 +215,46 @@ function ambiguousMessage( ); } -/** What pg_catalog holds at the journal's name. */ +/** 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. */ +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. + */ +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. */ @@ -232,26 +267,54 @@ const RELATION_KINDS: Readonly> = { S: "a sequence", }; -/** - * The journal's name is taken by something other than an ordinary table of - * the schema owner's. The migrator selects from and inserts into the journal - * as the app, so another role's view, or a table with its triggers, could - * run that role's code with the app's privileges. Nothing was applied. - */ +/** 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) { - const kind = - RELATION_KINDS[relation.relkind] ?? - `a relation of kind "${relation.relkind}"`; + constructor( + schemaName: string, + relation: JournalRelation, + refusal: JournalRefusal, + ) { super( - `${journalTable(schemaName)} is ${kind} owned by "${relation.owner}". ` + - `The migrator reads and records applied migrations only in a table owned by "${relation.schemaOwner}", the owner of schema "${schemaName}". ` + - "Another role's view or table could run its code as the app. Drop or rename it, then deploy again. No migration was applied.", + `${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}"`; + const transfer = `transfer the table to "${relation.currentUser}" (ALTER TABLE … OWNER TO), 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) { @@ -335,21 +398,29 @@ function readMigrations(folder: string, journal: Journal): MigrationFile[] { /** * Whether the journal table exists. Every read of the journal and every - * record into it starts here, so anything else at its name is refused. + * 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 { // 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 + 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`, @@ -357,13 +428,16 @@ async function journalTableExists( ); const found = rows[0]; if (!found) return false; - if (found.relkind !== "r" || found.owner !== found.schema_owner) { - throw new MigrationJournalError(schemaName, { - relkind: found.relkind, - owner: found.owner, - schemaOwner: found.schema_owner, - }); - } + const relation: JournalRelation = { + relkind: found.relkind, + owner: found.owner, + schemaOwner: found.schema_owner, + currentUser: found.current_user, + rowSecurity: found.row_security, + trusted: found.trusted, + }; + const refusal = journalRefusal(relation, use); + if (refusal) throw new MigrationJournalError(schemaName, relation, refusal); return true; } @@ -372,7 +446,7 @@ async function readRecordedMigrations( client: QueryClient, schemaName: string, ): Promise { - if (!(await journalTableExists(client, schemaName))) return []; + if (!(await journalTableExists(client, schemaName, "read"))) return []; const { rows } = await client.query<{ hash: string; created_at: string | number | null; @@ -494,7 +568,7 @@ async function ensureJournalTable( client: QueryClient, schemaName: string, ): Promise { - if (await journalTableExists(client, schemaName)) return; + if (await journalTableExists(client, schemaName, "record")) return; await client.query( `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(schemaName)}`, ); diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index 22c85fe6d..e4795df78 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -217,11 +217,18 @@ describe("migrateOnStart", () => { ], [ "a view at the journal's name", - new apply.MigrationJournalError("app", { - relkind: "v", - owner: "mallory", - schemaOwner: "app-sp", - }), + new apply.MigrationJournalError( + "app", + { + relkind: "v", + owner: "mallory", + schemaOwner: "app-sp", + currentUser: "app-sp", + rowSecurity: false, + trusted: false, + }, + "kind", + ), '"app"."__drizzle_migrations" is a view owned by "mallory"', ], [ From 1f1c4d7af971978b7f48afdc809a90ac7b6d2ec9 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:35:36 +0000 Subject: [PATCH 127/317] test(appkit): cover the hand-off when the owner also owns objects outside the app schema Co-authored-by: Isaac Signed-off-by: ditadi --- .../tooling/tests/hand-off.pg.test.ts | 39 ++++++++++++++++++- .../src/database/tooling/tests/init.test.ts | 23 ++++++++++- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts b/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts index 5466c5465..cdcaa6679 100644 --- a/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts @@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto"; import { Pool } from "pg"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; -import { readRoleBlockers } from "../hand-off"; +import { readOwnedOutsideSchema, readRoleBlockers } from "../hand-off"; // The pg_shdepend query against a real server, as a superuser that may create // databases and roles, e.g. APPKIT_TEST_PG_URL=postgres://localhost:5432/postgres @@ -72,4 +72,41 @@ describe.skipIf(!url)("readRoleBlockers against Postgres", () => { readRoleBlockers(mainPool, `appkit_missing_${suffix}`), ).resolves.toEqual([]); }); + + test("what the role owns in this database outside the app schema: nothing while it only owns the schema and its tables", async () => { + await expect( + readOwnedOutsideSchema(mainPool, role, "app"), + ).resolves.toEqual([]); + }); + + test("lists the role's tables, types, routines and schemas elsewhere, not grants, system objects or other databases", async () => { + await mainPool.query(` + alter table public.shared owner to "${role}"; + create type public.shared_kind as enum ('a'); + alter type public.shared_kind owner to "${role}"; + create function public.shared_fn(integer) returns integer language sql as 'select $1'; + alter function public.shared_fn(integer) owner to "${role}"; + create schema reports authorization "${role}"; + create table reports.daily (id integer primary key); + alter table reports.daily owner to "${role}"; + `); + try { + await expect( + readOwnedOutsideSchema(mainPool, role, "app"), + ).resolves.toEqual([ + "function public.shared_fn(integer)", + "schema reports", + "table public.shared", + "table reports.daily", + "type public.shared_kind", + ]); + } finally { + await mainPool.query(` + drop schema reports cascade; + drop function public.shared_fn(integer); + drop type public.shared_kind; + alter table public.shared owner to current_user; + `); + } + }); }); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 9a3467acf..4aae1f4e2 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -50,8 +50,9 @@ const migrateReport = { typesFile: "/app/shared/appkit-types/database.d.ts", }; -/** What the hand-off reads on the branch: the app schema's owner, and what blocks deleting that role. */ +/** What the hand-off reads on the branch: the app schema's owner, what else that role owns here, and what blocks deleting it. */ let schemaOwner: string | null; +let ownedOutside: string[]; let blockers: { database: string; count: number }[]; const queries: string[] = []; const pool = { @@ -60,6 +61,9 @@ const pool = { if (text.includes("nspowner")) { return { rows: [{ owner: schemaOwner, current_user: USER }] }; } + if (text.includes("pg_identify_object")) { + return { rows: ownedOutside.map((label) => ({ label })) }; + } if (text.includes("pg_shdepend")) return { rows: blockers }; throw new Error(`unexpected query ${text}`); }), @@ -157,6 +161,7 @@ function conflict(name: string): LakebaseApiError { beforeEach(() => { schemaOwner = SP; + ownedOutside = []; blockers = []; queries.length = 0; pool.query.mockClear(); @@ -768,6 +773,22 @@ describe("runInit — hand-off failures", () => { ); }); + test("an owner that also owns objects outside the app schema is not deleted: the list and the manual command are given", async () => { + const lakebase = project(); + ownedOutside = ["schema reports", "table public.shared"]; + + await expect(init(appOn(lakebase))).rejects.toThrow( + `Refusing to hand schema app in database databricks_postgres on ${devBranchId(USER)} to you: deleting role "${SP}" would also give you what else it owns on this branch: schema reports, table public.shared. .env already points at the branch. Reassign or drop them, or take them all with \`databricks postgres delete-role ${DEV}/roles/dbrx-apps-${SP} --reassign-owned-to ${DEV}/roles/alice\`, then rerun \`appkit db init\`.`, + ); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + expect(pool.query).toHaveBeenCalledWith( + expect.stringContaining("pg_identify_object"), + [SP, "app"], + ); + }); + test("a failed role delete lists what blocks it", async () => { const lakebase = project(); lakebase.deleteRoleError = new LakebaseApiError( From 04e9adf202bb9eae6cdd4ac11f6ebdafec14e2cf Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:37:05 +0000 Subject: [PATCH 128/317] fix(appkit): refuse the schema hand-off when its owner owns objects outside the app schema Deleting the owner's role with reassign hands you everything it owns on the fork, not only the app schema. Before deleting, init now lists what the role owns in the database outside the app schema and the system schemas, hands off only when there is nothing, and otherwise refuses with the list and the delete-role command that takes it all on purpose. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/hand-off.ts | 52 +++++++++++++++++-- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/hand-off.ts b/packages/appkit/src/database/tooling/hand-off.ts index 1421a917f..220160998 100644 --- a/packages/appkit/src/database/tooling/hand-off.ts +++ b/packages/appkit/src/database/tooling/hand-off.ts @@ -35,6 +35,39 @@ export async function readRoleBlockers( return rows; } +/** + * 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) => row.label); +} + function describeBlockers(blockers: readonly RoleBlocker[]): string { return blockers .map( @@ -59,8 +92,10 @@ interface HandOff { * 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. Returns - * that owner; null when you already own the schema or it does not exist. + * 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. Returns + * the owner; 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 @@ -77,11 +112,15 @@ export async function handOffAppSchema( input.schemaName, ); if (!owner || owner === currentUser) return null; - return { owner, blockers: await readRoleBlockers(pool, owner) }; + return { + owner, + ownedOutside: await readOwnedOutsideSchema(pool, owner, input.schemaName), + blockers: await readRoleBlockers(pool, owner), + }; }); if (!found) return null; - const { owner, blockers } = found; + const { owner, ownedOutside, blockers } = found; const where = `schema ${input.schemaName} in database ${input.database} on ${resourceId(input.branch)}`; const role = input.roles.find((r) => r.status?.postgres_role === owner); if (!role) { @@ -89,6 +128,11 @@ export async function handOffAppSchema( `Cannot hand ${where} to you: it belongs to "${owner}", which is not a Lakebase-managed role. .env already points at the branch. Have "${owner}" transfer the schema and its objects to you (ALTER … OWNER TO), or 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 "${owner}" 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\`.`, + ); + } input.onStep( `Handing ${where} to you: deleting this branch's copy of role ${owner}, which owns it, with its objects reassigned to you`, ); From 2225d8bf6c59f8d4e218ddc537b3453f6149551a Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:38:51 +0000 Subject: [PATCH 129/317] test(appkit): cover removing a .env key and listing what clean keeps in public Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/clean.pg.test.ts | 23 ++++++++++++++----- .../database/tooling/tests/env-file.test.ts | 16 +++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/clean.pg.test.ts b/packages/appkit/src/database/tooling/tests/clean.pg.test.ts index 7f40e011c..7bac8fdf2 100644 --- a/packages/appkit/src/database/tooling/tests/clean.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean.pg.test.ts @@ -4,13 +4,20 @@ import { Pool } from "pg"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; import { inTransaction } from "../../migrations/apply"; -import { cleanStatements, readCascadeDependents } from "../clean"; +import { + cleanStatements, + readCascadeDependents, + readKeptObjects, +} from "../clean"; // The clean SQL against a real server, as a superuser that may create // databases and roles, e.g. APPKIT_TEST_PG_URL=postgres://localhost:5432/postgres const url = process.env.APPKIT_TEST_PG_URL; -async function clean(pool: Pool, schemaName: string): Promise { +async function clean( + pool: Pool, + schemaName: string, +): Promise<{ dependents: string[]; kept: string[] }> { const client = await pool.connect(); try { return await inTransaction(client, async () => { @@ -18,7 +25,7 @@ async function clean(pool: Pool, schemaName: string): Promise { for (const statement of cleanStatements(schemaName)) { await client.query(statement); } - return dependents; + return { dependents, kept: await readKeptObjects(client, schemaName) }; }); } finally { client.release(); @@ -63,8 +70,9 @@ describe.skipIf(!url)("clean against Postgres", () => { }); test("reports everything CASCADE drops outside the schema, through views over views and dropped columns, then drops the schema and only those", async () => { - const dependents = await clean(pool, app); + const { dependents, kept } = await clean(pool, app); + expect(kept).toEqual([]); expect(dependents).toEqual([ `column kind of table ${other}.tagged`, `constraint refs_note_fk on table ${other}.refs`, @@ -116,6 +124,7 @@ describe.skipIf(!url)("clean against Postgres", () => { grant create on schema public to "${role}"; set role "${role}"; create view public.their_view as select id from public.notes; + create table public.theirs (id integer primary key); reset role; `); }); @@ -134,15 +143,17 @@ describe.skipIf(!url)("clean against Postgres", () => { expect(extensionTypes).toContain("citext"); expect(extensionTypes).toContain("tablefunc_crosstab_2"); - const dependents = await clean(pool, "public"); + const { dependents, kept } = await clean(pool, "public"); expect(dependents).toEqual(["view their_view"]); + // The other role's table stays with its rows; the extensions' objects are not listed as kept. + expect(kept).toEqual(["table theirs"]); expect( await names( pool, `select relname as name from pg_class where relnamespace = 'public'::regnamespace and relkind in ('r', 'v', 'S')`, ), - ).toEqual([]); + ).toEqual(["theirs"]); expect( await names( pool, diff --git a/packages/appkit/src/database/tooling/tests/env-file.test.ts b/packages/appkit/src/database/tooling/tests/env-file.test.ts index 203e278c5..7abe3fe10 100644 --- a/packages/appkit/src/database/tooling/tests/env-file.test.ts +++ b/packages/appkit/src/database/tooling/tests/env-file.test.ts @@ -157,6 +157,22 @@ describe("updateEnvFile", () => { expect(fs.readdirSync(root)).toEqual([".env"]); }); + test("a null value removes the key, every duplicate included, and adds nothing", () => { + const root = tempApp({ + ".env": [ + "KEEP=1", + "APPKIT_DB_NEW_BRANCH=projects/p/branches/dev-a", + "PGHOST=h", + "APPKIT_DB_NEW_BRANCH=stale", + ].join("\n"), + }); + const file = path.join(root, ".env"); + + updateEnvFile(file, { APPKIT_DB_NEW_BRANCH: null, MISSING: null }); + + expect(fs.readFileSync(file, "utf-8")).toBe("KEEP=1\nPGHOST=h\n"); + }); + test("quotes values that need it", () => { const root = tempApp(); const file = path.join(root, ".env"); From 7e13884b8be53fb239fbd0f3fc9b9f834ee455de Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:39:18 +0000 Subject: [PATCH 130/317] test(appkit): appkit db migrate must not apply when tables are left in public Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/migrate.test.ts | 46 ++++++++++++++++--- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index ed5c66139..8fbb6aa74 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -4,18 +4,28 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; -const { applyPendingMigrations, resolveEnvBranch, withBranchPool } = vi.hoisted( - () => ({ - applyPendingMigrations: vi.fn(), - resolveEnvBranch: vi.fn(), - withBranchPool: vi.fn(), - }), -); +const { + applyPendingMigrations, + detectTablesLeftInPublic, + resolveEnvBranch, + withBranchPool, +} = vi.hoisted(() => ({ + applyPendingMigrations: vi.fn(), + detectTablesLeftInPublic: vi.fn(), + resolveEnvBranch: vi.fn(), + withBranchPool: vi.fn(), +})); vi.mock("../../migrations/apply", async (importOriginal) => ({ ...(await importOriginal()), applyPendingMigrations, })); +vi.mock("../../migrations/tables-left-in-public", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../migrations/tables-left-in-public") + >()), + detectTablesLeftInPublic, +})); vi.mock("../guard", async (importOriginal) => ({ ...(await importOriginal()), resolveEnvBranch, @@ -70,6 +80,8 @@ const pool = {}; beforeEach(() => { applyPendingMigrations.mockReset(); + detectTablesLeftInPublic.mockReset(); + detectTablesLeftInPublic.mockResolvedValue(undefined); withBranchPool .mockReset() .mockImplementation((_ctx, fn: (p: unknown) => unknown) => fn(pool)); @@ -112,6 +124,26 @@ describe("runMigrate", () => { expect(fs.existsSync(report.typesFile)).toBe(true); }); + test("does not apply when the implicit app schema would shadow tables left in public", async () => { + const ctx = app(`notes: table("notes", { id: id(), body: text() })`); + detectTablesLeftInPublic.mockResolvedValue( + 'none of the declared tables exist in schema "app", but public has notes.', + ); + + const error = await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + ); + + expect((error as Error).message).toContain( + 'none of the declared tables exist in schema "app", but public has notes.', + ); + expect(detectTablesLeftInPublic).toHaveBeenCalledWith( + expect.any(Function), + expect.objectContaining({ $schemaName: "app" }), + ); + expect(applyPendingMigrations).not.toHaveBeenCalled(); + }); + test("generates, regenerates types, and applies to the .env branch with the app schema", async () => { const ctx = app(`notes: table("notes", { id: id(), body: text() })`); applyPendingMigrations.mockResolvedValue({ From d66501886a8b9f805dcfba20a4435e1faea818c8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:40:00 +0000 Subject: [PATCH 131/317] fix(appkit): appkit db migrate refuses to apply when tables are left in public With the implicit app schema, applying would create empty copies of tables that still live in public; the deployed app already refuses this on start. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/migrate.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index cf6260d86..39d22e928 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -14,6 +14,11 @@ import { MigrationApplyError, } from "../migrations/apply"; import { readJournal } from "../migrations/paths"; +import { + catalogSqlOf, + detectTablesLeftInPublic, +} from "../migrations/tables-left-in-public"; +import type { Schema } from "../schema-builder"; import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context"; import { notYourBranch, resolveEnvBranch, takesWrites } from "./guard"; import { type HistoryLock, withHistoryLock } from "./history-lock"; @@ -101,16 +106,22 @@ async function applyBlocker(ctx: DbContext): Promise { async function applyToEnvBranch( ctx: DbContext, folder: string, - schemaName: string, + schema: Schema, ): Promise { const blocker = readJournal(folder) ? await applyBlocker(ctx) : "no migrations to apply — schema.ts declares no tables yet"; if (blocker) return { applied: [], notApplied: blocker }; return withBranchPool(ctx, async (pool) => { + // The deployed app refuses this case on start; refuse it here first. + const leftInPublic = await detectTablesLeftInPublic( + catalogSqlOf(pool), + schema, + ); + if (leftInPublic) throw new Error(`Did not apply: ${leftInPublic}`); const { applied, adopted } = await applyPendingMigrations(pool, { migrationsFolder: folder, - schemaName, + schemaName: schema.$schemaName, }); return { applied, ...(adopted.length > 0 ? { adopted } : {}) }; }); @@ -151,7 +162,7 @@ async function migrateHolding( let outcome: ApplyOutcome; try { - outcome = await applyToEnvBranch(ctx, lock.folder, schema.$schemaName); + outcome = await applyToEnvBranch(ctx, lock.folder, schema); } catch (error) { if (!generated) throw error; const file = path.relative(ctx.root, generated.file); From 7c74e2964a96e10d4b1e8758904108a9d2428a22 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:40:28 +0000 Subject: [PATCH 132/317] docs: say appkit db migrate also refuses when tables are left in public Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index b04de5e1a..71127f4ed 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -99,7 +99,8 @@ 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`. Otherwise the first +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: @@ -114,8 +115,8 @@ export const schema = defineSchema( 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 startup does not -refuse. +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 From 2bb9594a079eeb6d513a316d46c72bf136b05f5d Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:42:49 +0000 Subject: [PATCH 133/317] feat(appkit): let updateEnvFile remove a key A null value drops the key's entries from .env instead of writing one. init needs it for a marker that lives only while a branch awaits its first schema start. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/env-file.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/appkit/src/database/tooling/env-file.ts b/packages/appkit/src/database/tooling/env-file.ts index 33dc8bb41..febe417fb 100644 --- a/packages/appkit/src/database/tooling/env-file.ts +++ b/packages/appkit/src/database/tooling/env-file.ts @@ -94,13 +94,14 @@ function writeAtomically(file: string, contents: string): void { } /** - * Replace `KEY=…` entries and append missing keys. 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. + * 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>, + values: Readonly>, ): void { refuseSymlink(file); const text = fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : ""; @@ -116,13 +117,16 @@ export function updateEnvFile( out.push(...entry.lines); continue; } + const value = values[key]; // Later duplicates of a managed key are dropped, so the value is unambiguous. - if (written.has(key)) continue; + if (value === null || written.has(key)) continue; written.add(key); - out.push(`${entry.prefix}${key}=${formatValue(key, values[key] ?? "")}`); + out.push(`${entry.prefix}${key}=${formatValue(key, value ?? "")}`); } for (const [key, value] of Object.entries(values)) { - if (!written.has(key)) out.push(`${key}=${formatValue(key, value)}`); + if (value !== null && !written.has(key)) { + out.push(`${key}=${formatValue(key, value)}`); + } } writeAtomically(file, `${out.join(eol)}${eol}`); } From 3fe8fe5947c5a9ffcb8ca5fa278e4dd94143bc69 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:42:53 +0000 Subject: [PATCH 134/317] feat(appkit): report what clean leaves in schema public In public, clean drops only the objects the connected role owns; on a fresh fork of the deploy branch that is nothing, and the app's tables stay with the rows they copied. The clean report now lists the relations, types and routines other roles own in public, extension objects aside, and the CLI prints them as kept with their rows. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/clean.ts | 62 ++++++++++++++++--- .../database/tooling/tests/clean-seed.test.ts | 2 + .../src/database/tooling/tests/init.test.ts | 5 +- .../cli/commands/db/init-clean-seed.test.ts | 13 +++- packages/shared/src/cli/commands/db/output.ts | 5 ++ .../src/cli/commands/db/tooling-contract.ts | 2 + 6 files changed, 77 insertions(+), 12 deletions(-) diff --git a/packages/appkit/src/database/tooling/clean.ts b/packages/appkit/src/database/tooling/clean.ts index c137aeb5d..273b4aaa8 100644 --- a/packages/appkit/src/database/tooling/clean.ts +++ b/packages/appkit/src/database/tooling/clean.ts @@ -173,11 +173,53 @@ export async function readCascadeDependents( return rows.map((row) => 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) => 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) { @@ -192,10 +234,14 @@ async function cleanTarget(ctx: DbContext) { /** What `appkit db clean` would drop, read without changing anything. */ export async function previewClean(ctx: DbContext): Promise { const target = await cleanTarget(ctx); - const dependents = await withBranchPool(ctx, (pool) => - readCascadeDependents(pool, target.schemaName), - ); - return { ...target, dependents }; + return withBranchPool(ctx, async (pool) => { + 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 }; + }); } /** @@ -217,14 +263,14 @@ export async function cleanHolding( // Dropping the schema drops the branch's migration journal too. lock.assertHeld(); const target = await cleanTarget(ctx); - const dependents = await runInTransaction(ctx, async (client) => { - const found = await readCascadeDependents(client, target.schemaName); + return runInTransaction(ctx, async (client) => { + const dependents = await readCascadeDependents(client, target.schemaName); for (const statement of cleanStatements(target.schemaName)) { await client.query(statement); } - return found; + const kept = await readKeptObjects(client, target.schemaName); + return { ...target, dependents, kept }; }); - return { ...target, dependents }; } /** diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index a90605eee..c3fd60ea2 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -93,6 +93,7 @@ describe("runClean", () => { branch: devBranch.name, schemaName: "app", dependents: ["view reporting.recent"], + kept: [], }); expect(writableEnvBranch).toHaveBeenCalledWith(ctx, "clean"); expect(statements).toEqual([ @@ -165,6 +166,7 @@ describe("previewClean", () => { branch: devBranch.name, schemaName: "app", dependents: ["constraint refs_fk on table reporting.refs"], + kept: [], }); expect(statements).toEqual([""]); }); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 4aae1f4e2..6e5c9a593 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -173,6 +173,7 @@ beforeEach(() => { branch: DEV, schemaName: "app", dependents: [], + kept: [], }); introspectHolding.mockReset().mockResolvedValue({ branch: DEV, tables: [] }); }); @@ -895,7 +896,7 @@ describe("runInit — schema start", () => { expect(runCommand).not.toHaveBeenCalled(); expect(report.start).toEqual({ kind: "clean", - clean: { branch: DEV, schemaName: "app", dependents: [] }, + clean: { branch: DEV, schemaName: "app", dependents: [], kept: [] }, migrate: migrateReport, }); }); @@ -909,7 +910,7 @@ describe("runInit — schema start", () => { await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( /^Another `appkit db init` \(pid \d+ on .+\) is changing the migration history in config\/database\. /, ); - return { branch: DEV, schemaName: "app", dependents: [] }; + return { branch: DEV, schemaName: "app", dependents: [], kept: [] }; }); await init(ctx, { schema: "clean" }); diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index 37907e275..e53a5c797 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -226,6 +226,7 @@ describe("appkit db init", () => { branch: report.branch, schemaName: "app", dependents: ["view reports.summary"], + kept: [], }, migrate, }, @@ -284,6 +285,7 @@ describe("appkit db clean", () => { branch: "projects/p/branches/dev-a", schemaName: "app", dependents: [], + kept: [], }; test("refuses without --yes when there is no TTY, before any API call", async () => { @@ -323,8 +325,12 @@ describe("appkit db clean", () => { expect(output(log)).toContain("Dropped schema app on dev-a"); }); - test("--yes cleans without asking; public says only your objects went", async () => { - tooling.runClean.mockResolvedValue({ ...cleaned, schemaName: "public" }); + test("--yes cleans without asking; public says only your objects went, and what other roles' objects stayed", async () => { + tooling.runClean.mockResolvedValue({ + ...cleaned, + schemaName: "public", + kept: ["table notes", "table orders"], + }); await clean("--yes"); expect(tooling.previewClean).not.toHaveBeenCalled(); @@ -332,6 +338,9 @@ describe("appkit db clean", () => { expect(output(log)).toContain( "Removed your objects in schema public on dev-a", ); + expect(output(log)).toContain( + "Kept in schema public, with their rows, because other roles own them: table notes, table orders", + ); }); test("--delete-branch deletes this checkout's session branch without a prompt", async () => { diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 72304f19d..cc0dd8473 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -94,6 +94,11 @@ export function printCleanReport(report: CleanReport): void { `Also removed, because they depended on it: ${report.dependents.join(", ")}`, ); } + if (report.kept.length > 0) { + warn( + `Kept in schema public, with their rows, because other roles own them: ${report.kept.join(", ")}`, + ); + } } export function printIntrospectReport(report: IntrospectReport): void { diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 446396a93..782cff8f5 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -55,6 +55,8 @@ export interface CleanReport { readonly branch: string; readonly schemaName: string; readonly dependents: readonly string[]; + /** In schema public, the objects other roles own, which stay with their rows. */ + readonly kept: readonly string[]; } export type InitStart = From 2130e247237c7120b9e1d0d701a3bf3d5e48b2c5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:49:04 +0000 Subject: [PATCH 135/317] test(appkit): cover init giving a branch it forked a schema start without the copied rows Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 179 +++++++++++++++++- .../database/tooling/tests/targets.test.ts | 4 + 2 files changed, 176 insertions(+), 7 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 6e5c9a593..ed29c4470 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -20,11 +20,15 @@ vi.mock("../migrate", async (importOriginal) => ({ migrateHolding, })); vi.mock("../clean", () => ({ cleanHolding })); -vi.mock("../introspect", () => ({ introspectHolding })); +vi.mock("../introspect", async (importOriginal) => ({ + ...(await importOriginal()), + introspectHolding, +})); import type { DbContext } from "../context"; import type { HistoryLock } from "../history-lock"; import { type InitOptions, runInit } from "../init"; +import { IntrospectRefusedError } from "../introspect"; import { LakebaseApiError } from "../lakebase-api"; import { runMigrate } from "../migrate"; import { DRIZZLE_KIT_VERSION } from "../migrations"; @@ -180,7 +184,7 @@ beforeEach(() => { afterEach(cleanupTempApps); describe("runInit — dev branch", () => { - test("forks the default branch with no expiry, hands the app schema to you, rewrites .env, migrates", async () => { + test("forks the default branch with no expiry, hands the app schema to you, rewrites .env, rebuilds the app schema from the migrations", async () => { const lakebase = project(); const ctx = appOn(lakebase); @@ -207,15 +211,20 @@ describe("runInit — dev branch", () => { role: { name: `${DEV}/roles/alice`, action: "kept" }, handedOff: SP, installed: null, - start: { kind: "migrate", migrate: migrateReport }, + start: { + kind: "clean", + clean: { branch: DEV, schemaName: "app", dependents: [], kept: [] }, + migrate: migrateReport, + }, }); expect(steps).toEqual([ `Creating ${devBranchId(USER)} from production`, `Pointing .env at ${devBranchId(USER)}, database databricks_postgres`, `Handing schema app in database databricks_postgres on ${devBranchId(USER)} to you: deleting this branch's copy of role ${SP}, which owns it, with its objects reassigned to you`, - `Migrating schema app on ${devBranchId(USER)}`, + `Dropping schema app on ${devBranchId(USER)}: a branch init forked starts without the rows it copied, and the committed migrations recreate its tables`, ]); + // The marker that the branch awaits its first start is gone with the start. const written = envFile(ctx.root); expect(written).toEqual({ DATABRICKS_CONFIG_PROFILE: "DEFAULT", @@ -230,10 +239,13 @@ describe("runInit — dev branch", () => { expect(fs.readFileSync(path.join(ctx.root, ".env"), "utf-8")).toMatch( /^# Lakebase\n/, ); - // Migrate runs against the new branch; the caller's environment is left alone. + // Clean and migrate run against the new branch; the caller's environment is left alone. + expect(cleanHolding.mock.invocationCallOrder[0]).toBeLessThan( + migrateHolding.mock.invocationCallOrder[0] ?? 0, + ); const [migrateCtx, , migrateOptions] = migrateHolding.mock.calls[0] ?? []; expect(migrateCtx.env.LAKEBASE_ENDPOINT).toBe(`${DEV}/endpoints/primary`); - expect(migrateOptions).toEqual({ interactive: false }); + expect(migrateOptions).toEqual({ interactive: false, generate: false }); expect(ctx.env.LAKEBASE_ENDPOINT).toBe(`${PRODUCTION}/endpoints/primary`); }); @@ -822,7 +834,7 @@ describe("runInit — hand-off failures", () => { }); describe("runInit — schema start", () => { - test("without schema.ts the default is introspect, which installs drizzle-kit first", async () => { + test("without schema.ts the default on a new fork is introspect, which installs drizzle-kit first, then a rebuild from the migrations it wrote", async () => { const lakebase = project(); const ctx = appOn( lakebase, @@ -846,9 +858,24 @@ describe("runInit — schema start", () => { expect(report.start).toEqual({ kind: "introspect", introspect: { branch: DEV, tables: [] }, + rebuilt: { + clean: { branch: DEV, schemaName: "app", dependents: [], kept: [] }, + migrate: migrateReport, + }, }); expect(introspectHolding.mock.calls[0]?.[2]).toEqual({ interactive: false, + schemaName: "app", + }); + expect(introspectHolding.mock.invocationCallOrder[0]).toBeLessThan( + cleanHolding.mock.invocationCallOrder[0] ?? 0, + ); + expect(cleanHolding.mock.invocationCallOrder[0]).toBeLessThan( + migrateHolding.mock.invocationCallOrder[0] ?? 0, + ); + expect(migrateHolding.mock.calls[0]?.[2]).toEqual({ + interactive: false, + generate: false, }); expect( steps.indexOf( @@ -956,6 +983,144 @@ describe("runInit — schema start", () => { ); }); +describe("runInit — a branch init forked starts without its copied rows", () => { + const dropping = (schemaName = "app") => + `Dropping schema ${schemaName} on ${devBranchId(USER)}: a branch init forked starts without the rows it copied, and the committed migrations recreate its tables`; + + function existingDev(): FakeLakebase { + const lakebase = project(); + lakebase.addBranch(DEV); + lakebase.addRole(DEV, "alice", USER, ["DATABRICKS_SUPERUSER"]); + return lakebase; + } + + test("a reused branch keeps its rows: migrate with schema.ts, introspect alone without", async () => { + schemaOwner = USER; + const withSchema = await init(appOn(existingDev())); + expect(withSchema.report.start).toEqual({ + kind: "migrate", + migrate: migrateReport, + }); + + const withoutSchema = await init( + appOn(existingDev(), {}, { schema: false }), + ); + expect(withoutSchema.report.start).toEqual({ + kind: "introspect", + introspect: { branch: DEV, tables: [] }, + rebuilt: null, + }); + expect(cleanHolding).not.toHaveBeenCalled(); + }); + + test("--schema migrate or --schema introspect on a new fork keeps the copied rows", async () => { + const migrated = await init(appOn(project()), { schema: "migrate" }); + expect(migrated.report.start).toEqual({ + kind: "migrate", + migrate: migrateReport, + }); + + const introspected = await init(appOn(project(), {}, { schema: false }), { + schema: "introspect", + }); + expect(introspected.report.start).toEqual({ + kind: "introspect", + introspect: { branch: DEV, tables: [] }, + rebuilt: null, + }); + expect(cleanHolding).not.toHaveBeenCalled(); + }); + + test("a run that stopped after the fork leaves a marker in .env, and the next init rebuilds as if it had forked", async () => { + schemaOwner = USER; + const ctx = appOn(existingDev(), { APPKIT_DB_NEW_BRANCH: DEV }); + + const { report, steps } = await init(ctx); + + expect(report).toMatchObject({ created: false, start: { kind: "clean" } }); + expect(steps).toContain(dropping()); + expect(envFile(ctx.root).APPKIT_DB_NEW_BRANCH).toBeUndefined(); + }); + + test("a marker for another branch changes nothing, and stays", async () => { + schemaOwner = USER; + const other = session("k2x9q0ab"); + const ctx = appOn(existingDev(), { APPKIT_DB_NEW_BRANCH: other }); + + const { report } = await init(ctx); + + expect(report.start.kind).toBe("migrate"); + expect(envFile(ctx.root).APPKIT_DB_NEW_BRANCH).toBe(other); + }); + + test("the marker is written before the fork and removed when the fork is refused, so a stop during the fork is covered", async () => { + const stopped = project(); + stopped.createBranchError = new Error("network down"); + const stoppedCtx = appOn(stopped); + await expect(init(stoppedCtx)).rejects.toThrow("network down"); + expect(envFile(stoppedCtx.root).APPKIT_DB_NEW_BRANCH).toBe(DEV); + + const refused = project(); + refused.createBranchError = forbidden(); + const refusedCtx = appOn(refused); + await expect(init(refusedCtx)).rejects.toThrow("needs CAN MANAGE"); + expect(envFile(refusedCtx.root).APPKIT_DB_NEW_BRANCH).toBeUndefined(); + }); + + test("--schema none on a new fork completes its setup: the marker goes, and the next init migrates", async () => { + const lakebase = project(); + const ctx = appOn(lakebase); + + const first = await init(ctx, { schema: "none" }); + expect(first.report.start).toEqual({ kind: "none" }); + expect(envFile(ctx.root).APPKIT_DB_NEW_BRANCH).toBeUndefined(); + + schemaOwner = USER; + const rerun = fakeContext({ + root: ctx.root, + env: { ...ctx.env, ...envFile(ctx.root) }, + userName: USER, + api: lakebase.api(), + }); + const second = await init(rerun); + expect(second.report.start.kind).toBe("migrate"); + }); + + test("the hand-off and the introspect read the schema schema.ts declares", async () => { + const ctx = appOn( + project(), + {}, + { files: { "config/database/schema.ts": schemaSource("sales") } }, + ); + + const { steps } = await init(ctx, { schema: "introspect" }); + + expect(pool.query).toHaveBeenCalledWith( + expect.stringContaining("nspowner"), + ["sales"], + ); + expect(introspectHolding.mock.calls[0]?.[2]).toEqual({ + interactive: false, + schemaName: "sales", + }); + expect(steps).toContain( + `Writing schema.ts from schema sales on ${devBranchId(USER)}`, + ); + }); + + test("an introspect refusal that says to pass --schema-name names the introspect command, which has the flag", async () => { + introspectHolding.mockRejectedValue( + new IntrospectRefusedError( + `Schema "app" on ${devBranchId(USER)} has no tables, so introspect would replace config/database/schema.ts with an empty one. Pass --schema-name to read another schema.`, + ), + ); + + await expect(init(appOn(project(), {}, { schema: false }))).rejects.toThrow( + `Schema "app" on ${devBranchId(USER)} has no tables, so introspect would replace config/database/schema.ts with an empty one. Run \`appkit db introspect --schema-name \` to read another schema.`, + ); + }); +}); + describe("runInit — .env", () => { test("a missing .env gets the host init authenticated with, and never .env.example's placeholders", async () => { const lakebase = project(); diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index d1dad905f..52f19b8a8 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -63,12 +63,14 @@ describe("readLocalTarget", () => { PGDATABASE: "databricks_postgres", PGUSER: "alice@example.com", APPKIT_DB_SESSION: "k2x9q0ab", + APPKIT_DB_NEW_BRANCH: "projects/p/branches/dev-alice-3f9a2c", }), ).toEqual({ project: "projects/p", endpoint: "projects/p/branches/b/endpoints/primary", database: "databricks_postgres", session: "k2x9q0ab", + newBranch: "projects/p/branches/dev-alice-3f9a2c", }); }); @@ -80,12 +82,14 @@ describe("readLocalTarget", () => { PGHOST: "your_postgres_host", PGDATABASE: "your_postgres_databaseName", APPKIT_DB_SESSION: "NOT VALID", + APPKIT_DB_NEW_BRANCH: "dev-alice-3f9a2c", }), ).toEqual({ project: null, endpoint: null, database: null, session: null, + newBranch: null, }); }); }); From 62fd6d1641b6642caef8d89fcfc0cd1f734fc60c Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:55:31 +0000 Subject: [PATCH 136/317] feat(appkit): start a branch init forked without the rows it copied A fork of the deploy branch carries every row of its source, production data included, and init migrated it as it stood. Without --schema, a branch init forked in this run now gets clean as its start when schema.ts exists, and introspect followed by a rebuild from the baseline it wrote when it does not. A reused branch keeps its data: migrate, or introspect without schema.ts. --schema migrate, or --schema introspect, keeps the copied rows on a new fork. In public, clean removes only your objects, and the report lists what stayed. Before the fork, init writes APPKIT_DB_NEW_BRANCH= to .env and removes it when the start completes, so a run that stops during or after the fork is finished by its rerun instead of migrating the copied rows into place. A fork refused for permissions or the branch limit removes the marker again. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 128 +++++++++++++----- .../appkit/src/database/tooling/targets.ts | 7 + .../src/database/tooling/tests/init.test.ts | 4 +- .../src/cli/commands/db/tooling-contract.ts | 17 ++- 4 files changed, 115 insertions(+), 41 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 2b281348c..e8960c6f2 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -61,7 +61,11 @@ export type SchemaStart = "migrate" | "introspect" | "clean" | "none"; export interface InitOptions { /** Default: this checkout's session branch when .env points at it, else your dev branch. */ readonly mode?: BranchMode; - /** Default: migrate when schema.ts exists, introspect otherwise. */ + /** + * Default: on a branch init forked, clean with schema.ts, else introspect + * followed by a rebuild from the migrations it wrote; on a reused branch, + * migrate with schema.ts, else introspect. + */ readonly schema?: SchemaStart; /** A new session branch's TTL as `--ttl` takes it (30m, 1h, 7d); default seven days. */ readonly ttl?: string; @@ -75,15 +79,22 @@ export interface InitOptions { type RoleAction = "kept" | "created" | "updated"; +/** The app schema dropped, then recreated from the committed migrations. */ +interface Rebuild { + readonly clean: CleanReport; + readonly migrate: MigrateReport; +} + export type InitStart = | { readonly kind: "none" } | { readonly kind: "migrate"; readonly migrate: MigrateReport } - | { readonly kind: "introspect"; readonly introspect: IntrospectReport } | { - readonly kind: "clean"; - readonly clean: CleanReport; - readonly migrate: MigrateReport; - }; + readonly kind: "introspect"; + readonly introspect: IntrospectReport; + /** On a branch init forked: the schema introspect read, rebuilt from the migrations it wrote. */ + readonly rebuilt: Rebuild | null; + } + | ({ readonly kind: "clean" } & Rebuild); export interface InitReport { readonly mode: BranchMode; @@ -188,12 +199,20 @@ interface BranchRequest { readonly ttl: { readonly api: string; readonly label: string }; readonly boundary: DeployBoundary; readonly envFile: string; + /** The branch .env marks as forked but not started; see LocalTarget.newBranch. */ + readonly newBranch: string | null; readonly onStep: (message: string) => void; } interface FoundBranch { readonly branch: LakebaseBranch; + /** Forked by this run. */ readonly created: boolean; + /** + * Forked by init, in this run or in one that stopped before the schema + * start, so it still holds every row the fork copied. + */ + readonly fresh: boolean; readonly sourceBranch?: string; readonly session: string | null; } @@ -253,7 +272,12 @@ async function findOrCreateBranch( ); } onStep(`Using ${resourceId(branch.name)}`); - return { branch, created: false, session }; + return { + branch, + created: false, + fresh: branch.name === request.newBranch, + session, + }; }; const replaceGone = (name: string): void => { if (session === null) { @@ -290,10 +314,15 @@ async function findOrCreateBranch( if (!parent) { throw new Error(`Project ${project} has no default branch to fork from.`); } - if (session !== null && session !== request.session) { - // Written first, so a failed or interrupted run reuses this id instead of forking again. - updateEnvFile(request.envFile, { APPKIT_DB_SESSION: session }); - } + // Written before the fork, so a run that stops during or after it leaves + // its rerun what it needs: the session id, to reuse instead of forking + // again, and the branch name, to still give the fork its first start. + updateEnvFile(request.envFile, { + ...(session !== null && session !== request.session + ? { APPKIT_DB_SESSION: session } + : {}), + APPKIT_DB_NEW_BRANCH: name, + }); onStep( `Creating ${resourceId(name)} from ${resourceId(parent.name)}${session === null ? "" : `, expiring after ${request.ttl.label}`}`, ); @@ -307,10 +336,15 @@ async function findOrCreateBranch( return { branch: branch?.name ? branch : { name }, created: true, + fresh: true, sourceBranch: parent.name, session, }; } catch (error) { + // These refusals mean no fork happened; any other error may have left one. + if (isPermissionDenied(error) || isBranchLimit(error)) { + updateEnvFile(request.envFile, { APPKIT_DB_NEW_BRANCH: null }); + } 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\`.`, @@ -533,9 +567,8 @@ async function initHolding( const envFile = path.join(ctx.root, ENV_FILE); refuseSymlink(envFile); const hasSchema = hasSchemaFile(ctx.root); - const startKind = options.schema ?? (hasSchema ? "migrate" : "introspect"); const schemaName = - hasSchema && startKind !== "introspect" && startKind !== "none" + hasSchema && options.schema !== "introspect" && options.schema !== "none" ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) .$schemaName : DEFAULT_SCHEMA_NAME; @@ -565,9 +598,17 @@ async function initHolding( ttl, boundary: readDeployBoundary(ctx.root), envFile, + newBranch: local.newBranch, onStep, }); const { branch } = found; + // A branch init forked holds every row the fork copied until its first + // start. Without --schema, that start rebuilds the app schema from the + // migrations, so none of them stay; a reused branch keeps its data. + const rebuild = found.fresh && options.schema === undefined; + const startKind: SchemaStart = + options.schema ?? + (hasSchema ? (rebuild ? "clean" : "migrate") : "introspect"); const { endpoint, @@ -624,32 +665,49 @@ async function initHolding( // Without a lock (--schema none) the schema stays as the fork has it. let start: InitStart = { kind: "none" }; - const on = `on ${resourceId(branch.name)}`; - if (lock && startKind === "migrate") { - onStep(`Migrating schema ${schemaName} ${on}`); - start = { - kind: "migrate", - migrate: await migrateHolding(branchCtx, lock, { interactive }), - }; - } else if (lock && startKind === "introspect") { - onStep(`Writing schema.ts from schema ${schemaName} ${on}`); - start = { - kind: "introspect", - introspect: await introspectHolding(branchCtx, lock, { interactive }), - }; - } else if (lock && startKind === "clean") { - onStep(`Dropping schema ${schemaName} ${on}`); - const clean = await cleanHolding(branchCtx, lock); - // Recreate from the committed migrations, so the startup check passes. - start = { - kind: "clean", - clean, - migrate: await migrateHolding(branchCtx, lock, { + if (lock) { + const on = `on ${resourceId(branch.name)}`; + const rebuildSchema = async (): Promise => { + const why = rebuild + ? schemaName === "public" + ? ": a branch init forked starts without the rows it copied, as far as you own them; other roles' objects stay with theirs" + : ": a branch init forked starts without the rows it 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); + // Recreated from the committed migrations, so the startup check passes. + const migrate = await migrateHolding(branchCtx, lock, { interactive, generate: false, - }), + }); + return { clean, migrate }; }; + if (startKind === "migrate") { + onStep(`Migrating schema ${schemaName} ${on}`); + start = { + kind: "migrate", + migrate: await migrateHolding(branchCtx, lock, { interactive }), + }; + } else if (startKind === "introspect") { + onStep(`Writing schema.ts from schema ${schemaName} ${on}`); + const introspect = await introspectHolding(branchCtx, lock, { + interactive, + }); + start = { + kind: "introspect", + introspect, + rebuilt: rebuild ? await rebuildSchema() : null, + }; + } else if (startKind === "clean") { + start = { kind: "clean", ...(await rebuildSchema()) }; + } } + // Its start done, the branch no longer awaits one. + if (found.fresh) updateEnvFile(envFile, { APPKIT_DB_NEW_BRANCH: null }); return { mode, diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 13ecce031..d41e6eb64 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -62,6 +62,12 @@ export interface LocalTarget { readonly endpoint: string | null; readonly database: string | null; readonly session: string | null; + /** + * APPKIT_DB_NEW_BRANCH: a branch `appkit db init` forked whose schema it has + * not started yet, so it still holds every row the fork copied. init writes + * it before the fork and removes it when the start completes. + */ + readonly newBranch: string | null; } export function readLocalTarget(env: NodeJS.ProcessEnv): LocalTarget { @@ -76,6 +82,7 @@ export function readLocalTarget(env: NodeJS.ProcessEnv): LocalTarget { // Without a real endpoint PGDATABASE is a template placeholder too. database: endpoint ? env.PGDATABASE || null : null, session, + newBranch: parseResourceName(env.APPKIT_DB_NEW_BRANCH)?.branch ?? null, }; } diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index ed29c4470..31fce0a4f 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -897,6 +897,7 @@ describe("runInit — schema start", () => { await expect( runInit(ctx, { + schema: "migrate", runCommand: () => { throw new Error("ENOTFOUND registry"); }, @@ -1171,7 +1172,8 @@ describe("runInit — .env", () => { `Database analytics, which databricks.yml binds, is not on ${devBranchId(USER)}. Create it there (databricks postgres create-database ${DEV} --database-id analytics), or bind a database the project's branches have, then rerun \`appkit db init\`.`, ); expect(lakebase.calls).toContain(`getDatabase ${DEV}/databases/analytics`); - expect(fs.existsSync(path.join(root, ".env"))).toBe(false); + // The fork happened, so .env marks the branch for its first start and nothing else. + expect(envFile(root)).toEqual({ APPKIT_DB_NEW_BRANCH: DEV }); }); test("the profile init authenticated with wins over the host", async () => { diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 782cff8f5..0aa3c2d20 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -59,15 +59,22 @@ export interface CleanReport { readonly kept: readonly string[]; } +/** The app schema dropped, then recreated from the committed migrations. */ +export interface Rebuild { + readonly clean: CleanReport; + readonly migrate: MigrateReport; +} + export type InitStart = | { readonly kind: "none" } | { readonly kind: "migrate"; readonly migrate: MigrateReport } - | { readonly kind: "introspect"; readonly introspect: IntrospectReport } | { - readonly kind: "clean"; - readonly clean: CleanReport; - readonly migrate: MigrateReport; - }; + readonly kind: "introspect"; + readonly introspect: IntrospectReport; + /** On a branch init forked: the schema introspect read, rebuilt from the migrations it wrote. */ + readonly rebuilt: Rebuild | null; + } + | ({ readonly kind: "clean" } & Rebuild); export interface InitReport { readonly mode: BranchMode; From 3e2711b2fdc37bdd2632f4b4c2ddbc4e6f5dbc0d Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:56:13 +0000 Subject: [PATCH 137/317] fix(appkit): hand off and introspect the schema schema.ts declares For an introspect start, init read the hand-off's schema as the default name even when schema.ts declared another, and let introspect read the default too. Both now use the declared name whenever schema.ts exists; --schema none still reads no schema.ts. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index e8960c6f2..52769c8d2 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -562,13 +562,13 @@ async function initHolding( : { 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. --schema none does neither, so it reads no - // schema.ts. + // 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 && options.schema !== "introspect" && options.schema !== "none" + hasSchema && options.schema !== "none" ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) .$schemaName : DEFAULT_SCHEMA_NAME; @@ -696,6 +696,7 @@ async function initHolding( onStep(`Writing schema.ts from schema ${schemaName} ${on}`); const introspect = await introspectHolding(branchCtx, lock, { interactive, + schemaName, }); start = { kind: "introspect", From 468e67929e98d7c461ddf7c10c567bf64afd2c23 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:57:07 +0000 Subject: [PATCH 138/317] fix(appkit): name the introspect command in the refusal init relays introspect's refusal for a schema without tables says to pass --schema-name, a flag init does not have. When init relays it, the advice now says to run `appkit db introspect --schema-name `. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 36 ++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 52769c8d2..af6d98501 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -17,7 +17,12 @@ import { classifyBranch, deployRefusal, takesWrites } from "./guard"; import { handOffAppSchema } from "./hand-off"; import { type HistoryLock, withHistoryLock } from "./history-lock"; import { currentIdentity, type Identity } from "./identity"; -import { introspectHolding, type IntrospectReport } from "./introspect"; +import { + introspectHolding, + type IntrospectOptions, + type IntrospectReport, + IntrospectRefusedError, +} from "./introspect"; import { isAlreadyExists, isBranchLimit, @@ -505,6 +510,33 @@ async function resolveDatabase( return database.status.postgres_database; } +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, @@ -694,7 +726,7 @@ async function initHolding( }; } else if (startKind === "introspect") { onStep(`Writing schema.ts from schema ${schemaName} ${on}`); - const introspect = await introspectHolding(branchCtx, lock, { + const introspect = await introspectForInit(branchCtx, lock, { interactive, schemaName, }); From 3e07242f65fbbc4db07550f533ded7fad6185ed1 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:57:11 +0000 Subject: [PATCH 139/317] feat(cli): describe and print the rebuild appkit db init gives a new branch The help said a new branch starts with a copy of the default branch's rows. It now says init rebuilds the app schema from the migrations so the branch starts without them, how --schema migrate or introspect keeps them, and that a reused branch is migrated. The report prints why a default run dropped the schema, with the flag that keeps the rows, prints the introspect, drop and migrations of an introspect start with a rebuild, and no longer says a rebuilt branch keeps its approximated objects. Co-authored-by: Isaac Signed-off-by: ditadi --- .../cli/commands/db/init-clean-seed.test.ts | 88 +++++++++++++++++++ packages/shared/src/cli/commands/db/init.ts | 61 ++++++++++--- packages/shared/src/cli/commands/db/output.ts | 9 +- 3 files changed, 142 insertions(+), 16 deletions(-) diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index e53a5c797..d8f0768e3 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -241,6 +241,94 @@ describe("appkit db init", () => { expect(printed).toContain("Applied 0000_migration to the .env branch"); }); + test("a rebuild without --schema says the copied rows went and how to keep them; with --schema clean it does not", async () => { + const rebuilt = { + ...report, + start: { + kind: "clean", + clean: { + branch: report.branch, + schemaName: "app", + dependents: [], + kept: [], + }, + migrate, + }, + }; + tooling.runInit.mockResolvedValue(rebuilt); + await init(); + expect(output(log)).toContain( + "A branch init forked starts without the rows it copied: the app schema was rebuilt from the committed migrations. `appkit db init --schema migrate` keeps them.", + ); + + log.mockClear(); + resetOptionValues(); + await init("--schema", "clean", "--yes"); + expect(output(log)).toContain("Dropped schema app on dev-alice-3f9a2c"); + expect(output(log)).not.toContain("A branch init forked starts without"); + }); + + test("an introspect start with a rebuild prints what introspect wrote, the drop, the migrations, and names --schema introspect to keep the rows", async () => { + tooling.runInit.mockResolvedValue({ + ...report, + start: { + kind: "introspect", + introspect: { + branch: report.branch, + schemaName: "app", + tables: ["notes"], + schemaFile: `${process.cwd()}/config/database/schema.ts`, + backupFile: null, + skipped: [], + warnings: [], + approximated: ["notes.body: check constraint"], + migration: { + tag: "0000_baseline", + file: `${process.cwd()}/config/database/migrations/0000_baseline.sql`, + statements: ["CREATE TABLE"], + }, + recorded: ["0000_baseline"], + typesFile: migrate.typesFile, + }, + rebuilt: { + clean: { + branch: report.branch, + schemaName: "app", + dependents: [], + kept: [], + }, + migrate: { ...migrate, applied: ["0000_baseline"] }, + }, + }, + }); + await init(); + + const printed = output(log); + expect(printed).toContain( + "`appkit db init --schema introspect` keeps them", + ); + expect(printed).toContain( + "Wrote config/database/schema.ts from schema app", + ); + expect(printed).toContain( + "The rebuild gave this branch what schema.ts declares", + ); + expect(printed).not.toContain("This branch keeps the approximated objects"); + expect(printed).toContain("Dropped schema app on dev-alice-3f9a2c"); + expect(printed).toContain("Applied 0000_baseline to the .env branch"); + }); + + test("--schema's help says what the default does with a new and a reused branch", () => { + const command = dbCommand.commands.find((c) => c.name() === "init"); + const schema = command?.options.find((o) => o.long === "--schema"); + expect(schema?.description).toBe( + "how the schema starts (default: a new branch is rebuilt from the migrations, a reused one is migrated; introspect without schema.ts)", + ); + expect(command?.helpInformation()).not.toContain( + "start with a copy of its rows", + ); + }); + test("--schema clean without a TTY needs --yes, and stops before any API call", async () => { await init("--schema", "clean"); diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index bc79f0f09..b82559cbf 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -11,7 +11,12 @@ import { printMigrateReport, shortName, } from "./output"; -import type { InitOptions, InitReport, SchemaStart } from "./tooling-contract"; +import type { + InitOptions, + InitReport, + Rebuild, + SchemaStart, +} from "./tooling-contract"; interface InitFlags { readonly session?: boolean; @@ -38,7 +43,15 @@ async function confirmClean(flags: InitFlags): Promise { return !isCancel(answer) && answer; } -function printInitReport(report: InitReport): void { +function printRebuild(rebuild: Rebuild): void { + printCleanReport(rebuild.clean); + printMigrateReport(rebuild.migrate); +} + +function printInitReport( + report: InitReport, + schemaFlag: SchemaStart | undefined, +): void { const branch = shortName(report.branch); const expires = report.expireTime ? `, expires ${report.expireTime}` : ""; ok( @@ -62,12 +75,22 @@ function printInitReport(report: InitReport): void { if (report.installed) ok(`Installed drizzle-kit (${report.installed})`); const { start } = report; - if (start.kind === "introspect") printIntrospectReport(start.introspect); - else if (start.kind === "migrate") printMigrateReport(start.migrate); - else if (start.kind === "clean") { - printCleanReport(start.clean); - printMigrateReport(start.migrate); - } else info("Left the schema as it is"); + // Without --schema, only a branch init forked gets a rebuild. + const rebuilt = + start.kind === "clean" || (start.kind === "introspect" && start.rebuilt); + if (rebuilt && schemaFlag === undefined) { + info( + `A branch init forked starts without the rows it copied: the app schema was rebuilt from the committed migrations. \`appkit db init --schema ${start.kind === "introspect" ? "introspect" : "migrate"}\` keeps them.`, + ); + } + if (start.kind === "introspect") { + printIntrospectReport(start.introspect, { + rebuilt: start.rebuilt !== null, + }); + if (start.rebuilt) printRebuild(start.rebuilt); + } else if (start.kind === "migrate") printMigrateReport(start.migrate); + else if (start.kind === "clean") printRebuild(start); + else info("Left the schema as it is"); } async function runDbInit(flags: InitFlags): Promise { @@ -86,7 +109,10 @@ async function runDbInit(flags: InitFlags): Promise { interactive: !flags.yes && isInteractive(), onStep: info, }; - printInitReport(await tooling.runInit(tooling.createDbContext(), options)); + printInitReport( + await tooling.runInit(tooling.createDbContext(), options), + flags.schema, + ); } catch (error) { fail(error); } @@ -115,7 +141,7 @@ export const dbInitCommand = new Command("init") .addOption( new Option( "--schema ", - "how the schema starts (default: migrate with schema.ts, introspect without)", + "how the schema starts (default: a new branch is rebuilt from the migrations, a reused one is migrated; introspect without schema.ts)", ).choices(["migrate", "introspect", "clean", "none"]), ) .option( @@ -126,10 +152,16 @@ export const dbInitCommand = new Command("init") "after", ` init asks nothing. It keeps this checkout's session branch when .env points at -one, and otherwise uses your dev branch (dev--). New branches fork -the project's default branch, so they start with a copy of its rows, production -data included. init never changes the default branch, a protected branch or a -branch databricks.yml deploys to, and never edits databricks.yml. +one, and otherwise uses your dev branch (dev--). A new branch forks +the project's default branch, which copies its rows, production data included. +init then rebuilds the app schema from the committed migrations (written first +by introspect when there is no schema.ts), so the new branch starts without +them; a run that stops before that finishes rebuilds on its rerun. --schema +migrate, or --schema introspect without schema.ts, keeps the copied rows. A +reused branch keeps its data: init migrates it. In schema public only your own +objects go; what other roles own stays with its rows, and init lists it. init +never changes the default branch, a protected branch or a branch databricks.yml +deploys to, and never edits databricks.yml. With --schema none, init only sets up the branch and .env: the schema and its owner stay as the fork copied them. init never hands off schema public, which @@ -142,6 +174,7 @@ one it authenticated with. Examples: $ appkit db init + $ appkit db init --schema migrate $ appkit db init --session --ttl 1h --schema clean --yes`, ) .action(runDbInit); diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index cc0dd8473..83e4c2314 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -101,7 +101,10 @@ export function printCleanReport(report: CleanReport): void { } } -export function printIntrospectReport(report: IntrospectReport): void { +export function printIntrospectReport( + report: IntrospectReport, + options: { rebuilt?: boolean } = {}, +): void { const count = report.tables.length; ok( `Wrote ${relative(report.schemaFile)} from schema ${report.schemaName} on ${shortName(report.branch)} (${count} table${count === 1 ? "" : "s"})${report.backupFile ? `; the previous file is ${relative(report.backupFile)}` : ""}`, @@ -119,7 +122,9 @@ export function printIntrospectReport(report: IntrospectReport): void { } if (report.approximated.length > 0) { info( - "This branch keeps the approximated objects as they are; a database the migrations create gets what schema.ts declares.", + options.rebuilt + ? "The rebuild gave this branch what schema.ts declares, as a database the migrations create gets." + : "This branch keeps the approximated objects as they are; a database the migrations create gets what schema.ts declares.", ); } if (report.migration) { From 576cb38f3f3cf06fa65fffc2ac41ed8d95a81e08 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 13:57:15 +0000 Subject: [PATCH 140/317] docs: describe what appkit db init does with a new branch's rows Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index c1e588dd9..cbc8d9a3f 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -131,6 +131,28 @@ 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. +### 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 project's default branch, and points `.env` +at it. A fork copies every row of its source, production data included. A +branch `init` forked starts without them: `init` drops the app schema and +recreates it from the committed migrations. 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. Until the +rebuild has run, `.env` names the branch in `APPKIT_DB_NEW_BRANCH`, so a run +that stops early is finished by the next `init`. + +To keep the copied rows on a new branch, pass `--schema migrate`, or +`--schema introspect` without `schema.ts`. A branch `init` reuses keeps its +data: `init` migrates it, or introspects it without `schema.ts`. +`--schema clean` rebuilds a reused branch too, after a confirmation or with +`--yes`. + +In schema `public`, `init` and `clean` remove only the objects your role owns. +On a fork of the deploy branch the app's service principal owns the tables, so +they 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. From f5d8eb625f71d443b804e9463e9b39a5aedc9b36 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 14:03:01 +0000 Subject: [PATCH 141/317] refactor(appkit): write .env through the tooling's atomic file helper env-file kept its own temp-file-and-rename copy; it now uses files.ts with mode 0600, and its symlink refusal builds on the shared check. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/env-file.ts | 31 +++++++------------ packages/appkit/src/database/tooling/files.ts | 8 +++-- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/packages/appkit/src/database/tooling/env-file.ts b/packages/appkit/src/database/tooling/env-file.ts index febe417fb..35e9abea2 100644 --- a/packages/appkit/src/database/tooling/env-file.ts +++ b/packages/appkit/src/database/tooling/env-file.ts @@ -1,6 +1,10 @@ -import { randomBytes } from "node:crypto"; import fs from "node:fs"; -import path from "node:path"; + +import { + refuseSymlink as refuseLink, + SymlinkRefusedError, + writeFileAtomic, +} from "./files"; /** * An entry's first line: indentation and `export ` (kept on rewrite), the key, @@ -72,24 +76,13 @@ function entries(lines: readonly string[]): Entry[] { } export function refuseSymlink(file: string): void { - if (!fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) return; - 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.`, - ); -} - -/** A crash leaves the old file or the new one, never a truncated one. */ -function writeAtomically(file: string, contents: string): void { - const temp = path.join( - path.dirname(file), - `.${path.basename(file)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`, - ); try { - fs.writeFileSync(temp, contents, { mode: 0o600, flag: "wx" }); - fs.renameSync(temp, file); + refuseLink(file); } catch (error) { - fs.rmSync(temp, { force: true }); - throw 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.`, + ); } } @@ -128,5 +121,5 @@ export function updateEnvFile( out.push(`${key}=${formatValue(key, value)}`); } } - writeAtomically(file, `${out.join(eol)}${eol}`); + 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 index 4329c09d8..bc0a8c89c 100644 --- a/packages/appkit/src/database/tooling/files.ts +++ b/packages/appkit/src/database/tooling/files.ts @@ -22,14 +22,18 @@ export function refuseSymlink(file: string): void { * 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): void { +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); + fs.writeFileSync(temporary, content, { ...options, flag: "wx" }); fs.renameSync(temporary, file); } finally { fs.rmSync(temporary, { force: true }); From 162dc62849942a4d22b88b717a45f53228d84ebe Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 14:03:13 +0000 Subject: [PATCH 142/317] fix(appkit): point introspect's edited-migration refusal at appkit db clean Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/introspect/index.ts | 2 +- .../src/database/tooling/introspect/tests/introspect.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 313d287bb..9444d5c41 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -239,7 +239,7 @@ export async function introspectHolding( 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 recreate the branch.`, + `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. diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index cdef40ace..c95b41de3 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -705,7 +705,7 @@ export const schema = defineSchema(({ table }) => ({ 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 recreate the branch.', + '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); From 46a543aa3c19b4429b5785603c8c9bbf999414cb Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 14:05:22 +0000 Subject: [PATCH 143/317] refactor(appkit): keep one binding per postgres resource in the bundle reader MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fail-closed fix flattened each resource into separate branch and database values; keep one PostgresBinding per resource (with a whole marker for a ${…} standing in for the structure), which later readers that count an app's resources need. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/targets.ts | 58 +++++++++++-------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index b9bd8fe56..96cb51dfc 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -73,11 +73,18 @@ type BundleValue = /** As written: a `${…}` only a deploy resolves, no value, or not a resource name. */ | { readonly kind: "unresolved"; readonly written: string }; -/** A value databricks.yml binds, and where it is written in the merged bundle. */ -interface BoundValue { - /** e.g. "resources.apps.app.resources[0].postgres.branch". */ +/** One postgres resource of an app. */ +interface PostgresBinding { + /** + * Where it is in the merged bundle, e.g. "resources.apps.app.resources[0].postgres", + * or where a `${…}` stands in for the app's resources, one of them, or a postgres block. + */ readonly at: string; - readonly value: BundleValue; + readonly branch: BundleValue; + /** null when the binding names no database. */ + readonly database: BundleValue | null; + /** A `${…}` stands where the structure should be; `branch` holds it, unresolved. */ + readonly whole?: true; } /** An app one target of databricks.yml deploys. */ @@ -85,10 +92,10 @@ interface BundleApp { /** Its key under resources.apps. */ readonly key: string; /** - * The branch and database of each postgres resource it has, and any `${…}` - * standing where its resources, one of them, or a postgres block should be. + * Every postgres resource it has, and any `${…}` standing where its + * resources, one of them, or a postgres block should be. */ - readonly postgres: readonly BoundValue[]; + readonly postgres: readonly PostgresBinding[]; } /** What one target binds with one set of variable values. */ @@ -297,13 +304,15 @@ function bundleValue( } /** A `${…}` where only a deploy puts a structure: the files cannot say what it binds. */ -function unresolvedAt(at: string, written: unknown): BoundValue { +function unresolvedAt(at: string, written: unknown): PostgresBinding { return { at, - value: { + branch: { kind: "unresolved", written: typeof written === "string" ? written : "", }, + database: null, + whole: true, }; } @@ -312,29 +321,26 @@ function appPostgres( at: string, resources: unknown, resolve: (value: unknown) => string | null, -): BoundValue[] { +): PostgresBinding[] { if (resources == null) return []; if (!Array.isArray(resources)) return [unresolvedAt(at, resources)]; - return resources.flatMap((resource, index): BoundValue[] => { + return resources.flatMap((resource, index): PostgresBinding[] => { const here = `${at}[${index}]`; const item = record(resource); if (!item) return [unresolvedAt(here, resource)]; if (item.postgres == null) return []; const binding = record(item.postgres); if (!binding) return [unresolvedAt(`${here}.postgres`, item.postgres)]; - const bound: BoundValue[] = [ + return [ { - at: `${here}.postgres.branch`, - value: bundleValue(binding.branch, resolve, "branch"), + at: `${here}.postgres`, + branch: bundleValue(binding.branch, resolve, "branch"), + database: + binding.database === undefined + ? null + : bundleValue(binding.database, resolve, "database"), }, ]; - if (binding.database !== undefined) { - bound.push({ - at: `${here}.postgres.database`, - value: bundleValue(binding.database, resolve, "database"), - }); - } - return bound; }); } @@ -463,10 +469,12 @@ export function readDeployBoundary(root: string): DeployBoundary { const branch = parseResourceName(value.name)?.branch; if (branch) branches.add(branch); }; - for (const { at, value } of bindings.apps.flatMap( - (app) => app.postgres, - )) { - add(at, value); + for (const binding of bindings.apps.flatMap((app) => app.postgres)) { + add( + binding.whole ? binding.at : `${binding.at}.branch`, + binding.branch, + ); + if (binding.database) add(`${binding.at}.database`, binding.database); } if (bindings.postgresBranch) { add("variables.postgres_branch", bindings.postgresBranch); From 40a2abda2bc94e41f7d4db2c643ed7f0de1a2760 Mon Sep 17 00:00:00 2001 From: ditadi Date: Mon, 9 Nov 2026 14:11:23 +0000 Subject: [PATCH 144/317] docs: say verify --deployed checks the deployed source, not the applied migrations Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index cac73b1f5..cc8c0b10e 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -209,7 +209,7 @@ A typical change: 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, with every committed migration +npx appkit db verify --deployed # the app runs, and its source has every committed migration ``` ### Your branch's data @@ -402,11 +402,21 @@ on the branch, and the app is running. When the checkout has 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. When verify cannot read that source, it fails and +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. It needs no +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`. From 83bf6071431348754a3892f793bb7f5a8eba8006 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:01:19 +0000 Subject: [PATCH 145/317] test(appkit): pin that the public-schema hint stops advising ALTER OWNER On Lakebase no Postgres role can hand an object to the app's service principal, so the hint for a migration that trips on another role's object in public must say so and point at the default schema. Co-authored-by: Isaac Signed-off-by: ditadi --- .../migrations/tests/ownership.test.ts | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index 88015f4b9..ea6a5059e 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -56,18 +56,18 @@ describe("ownership: one owner per branch", () => { ); }); - test("public with CREATE already granted: the failure is an object another role owns, not CREATE", () => { - const hint = ownershipHint("42501", { - schemaName: "public", - owner: "pg_database_owner", - currentUser: "app-sp", - canCreate: true, - }); - - expect(hint).not.toContain("has no CREATE"); - expect(hint).not.toContain("GRANT CREATE"); - expect(hint).toContain("belongs to another role"); - expect(hint).toContain(`OWNER TO "app-sp"`); + 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", () => { From 205443673ef9c493e85d8056657ebbb7fe0ce5ae Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:02:20 +0000 Subject: [PATCH 146/317] fix(appkit): stop telling a role to hand its public table to the app Measured on Lakebase: ALTER ... OWNER TO fails with "must be able to SET ROLE", so no Postgres role can transfer an object to the app's service principal. The hint for a migration that trips on another role's object in public now says so and points at the default schema app, which the app creates and owns. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/migrations/ownership.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index 4f54970e5..0e9e58835 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -68,8 +68,8 @@ export function ownershipHint( ); } return ( - `Role "${ownership.currentUser}" can create in schema public, so an object this migration changes belongs to another role. ` + - `Have that role transfer it with ALTER TABLE public.
OWNER TO "${ownership.currentUser}", or drop schemaName from defineSchema() to use the default schema app, which the app creates and owns.` + `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) { From 8dabbb3a9410b14f8bb2399464a846b7ed57d981 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:05:16 +0000 Subject: [PATCH 147/317] test(appkit): pin the owner error to the two-apps case first and a Lakebase-only recovery The hint for a schema another role owns must say first that two apps on one database each need their own schemaName, then give the delete-role recovery for a recreated app or a re-added resource, with the warning that it moves every object the role owns. It must not suggest ALTER OWNER, which fails with "must be able to SET ROLE" on a Lakebase service principal role. Co-authored-by: Isaac Signed-off-by: ditadi --- .../migrations/tests/ownership.test.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index 99f136657..a5a48ab4f 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -13,23 +13,32 @@ describe("ownership: one owner per branch", () => { ); }); - test("a schema owned by another role names both roles and how that happens", () => { + 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( - "the app's database resource was removed and added again, or the app was recreated", + `No Postgres role can hand them back to "new-app-sp"; only Lakebase can move them.`, ); expect(hint).toContain( - `If "old-app-sp" belonged to a deleted app, someone with CAN MANAGE on the Lakebase project moves its objects with \`databricks postgres delete-role --reassign-owned-to \``, + "That moves every object the role owns on the branch, in every database, and deletes the role, so first check what it owns.", ); - expect(hint).toContain("set another schemaName in schema.ts"); + expect(hint).not.toContain("ALTER"); expect(hint).toContain( "On your dev or session branch, rerun `appkit db init`, which hands you the schema.", ); From 5b0b9a122b3b90b1ff62f295f1f4dbe0cf7390b1 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:06:24 +0000 Subject: [PATCH 148/317] fix(appkit): drop ALTER OWNER from the owner error and name the two-apps case first Schema "app" owned by another role has two causes, and the hint now orders them. Two apps on one database each need their own schemaName. Otherwise the app was recreated or its resource re-added, and Lakebase handed the objects to another role. No Postgres role can hand them back, because ALTER ... OWNER TO a service principal role fails with "must be able to SET ROLE", so the hint gives only the platform's delete-role --reassign-owned-to command, covers the re-add case where the owner is the remover's role, and warns that it moves every object the role owns and deletes the role. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/ownership.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index 50466c144..7c2d0e181 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -73,12 +73,17 @@ export function ownershipHint( ); } 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}". ` + - "This happens when the app's database resource was removed and added again, or the app was recreated with a new service principal: " + - `Lakebase hands the objects to another role. If "${ownership.owner}" belonged to a deleted app, 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), which also deletes its role. ` + - `Otherwise have "${ownership.owner}" transfer the schema and its tables to "${ownership.currentUser}" (ALTER … OWNER TO), or set another schemaName in schema.ts. ` + + "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, in every database, and deletes the role, so first check what it owns. " + "On your dev or session branch, rerun `appkit db init`, which hands you the schema." ); } From 573d680a4f099bcd8eba30103942eda14af28bb8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:12:36 +0000 Subject: [PATCH 149/317] test(appkit): a deploy start refuses an edited or diverged history, tolerating line endings A recorded migration whose committed file changed, or pending migrations next to recorded rows this checkout lacks, must stop a deploy start before anything runs. A file read back with the other line endings is the same migration. A pure code rollback and a CLI-style call keep warning. Co-authored-by: Isaac Signed-off-by: ditadi --- .../migrations/tests/apply.pg.test.ts | 45 ++++- .../database/migrations/tests/apply.test.ts | 173 +++++++++++++++++- .../src/database/migrations/tests/fixtures.ts | 20 +- .../database/migrations/tests/history.test.ts | 16 ++ .../database/tests/migrate-on-start.test.ts | 7 + 5 files changed, 252 insertions(+), 9 deletions(-) diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts index 3fc33b582..f2b3d6cd1 100644 --- a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -1,4 +1,6 @@ import { randomUUID } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; import { Pool, type PoolClient } from "pg"; import { @@ -228,7 +230,7 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { ); expect(error).toBeInstanceOf(MigrationHistoryError); - expect(error).toMatchObject({ stranded: ["0001_b"] }); + expect(error).toMatchObject({ refusal: { stranded: ["0001_b"] } }); expect(await recorded()).toHaveLength(2); expect(await columns("d")).toEqual([]); }); @@ -438,6 +440,47 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { 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)`); diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 65420f20b..abebc3386 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -389,7 +389,7 @@ describe("applyPendingMigrations", () => { ); expect(error).toBeInstanceOf(MigrationHistoryError); - expect(error).toMatchObject({ stranded: ["0001_parallel"] }); + expect(error).toMatchObject({ refusal: { stranded: ["0001_parallel"] } }); expect((error as Error).message).toMatch( /^Migration 0001_parallel is older than 0002_b, which schema "app" already recorded, and was never applied/, ); @@ -431,8 +431,16 @@ describe("applyPendingMigrations", () => { expect(error).toBeInstanceOf(MigrationHistoryError); expect(error).toMatchObject({ - ambiguous: ["0000_a", "0001_b"], - stranded: [], + 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\./, @@ -477,6 +485,165 @@ describe("applyPendingMigrations", () => { ); }); + 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: { + pending: ["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); + }); + + 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({ diff --git a/packages/appkit/src/database/migrations/tests/fixtures.ts b/packages/appkit/src/database/migrations/tests/fixtures.ts index 33d5d1baa..085b27da5 100644 --- a/packages/appkit/src/database/migrations/tests/fixtures.ts +++ b/packages/appkit/src/database/migrations/tests/fixtures.ts @@ -72,11 +72,21 @@ export function writeMigrations( return folder; } -/** The hash drizzle-orm's migrator records for a migration file. */ -export function hashOf(folder: string, tag: string): string { - return createHash("sha256") - .update(fs.readFileSync(path.join(folder, `${tag}.sql`), "utf-8")) - .digest("hex"); +/** + * The hash drizzle-orm's migrator records for a migration file: as written, + * or as a checkout with the given line endings reads it. + */ +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 { diff --git a/packages/appkit/src/database/migrations/tests/history.test.ts b/packages/appkit/src/database/migrations/tests/history.test.ts index 8dddcd172..63a8a8f61 100644 --- a/packages/appkit/src/database/migrations/tests/history.test.ts +++ b/packages/appkit/src/database/migrations/tests/history.test.ts @@ -6,11 +6,13 @@ const file = ( tag: string, when: number, hash = `hash-${tag}`, + hashes: readonly string[] = [hash], ): MigrationFile => ({ tag, idx: 0, when, hash, + hashes, statements: [], }); @@ -57,6 +59,20 @@ describe("reconcileMigrations", () => { 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 }; diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index e4795df78..701ea4961 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -134,9 +134,11 @@ describe("migrateOnStart", () => { await migrateOnStart(pool, schema, root, deployEnv); + // A deploy start refuses an edited or diverged history instead of warning. expect(applyPendingMigrations).toHaveBeenCalledWith(pool, { migrationsFolder: path.join(root, "config/database/migrations"), schemaName: "app", + onDrift: "refuse", }); const logged = log.mock.calls.map((call) => call.map(String).join(" ")); expect(logged).toEqual([ @@ -215,6 +217,11 @@ describe("migrateOnStart", () => { }), "Migration 0001_parallel is older than 0002_b", ], + [ + "an edited migration", + new apply.MigrationHistoryError("app", { edited: ["0001_migration"] }), + 'Migration 0001_migration changed after schema "app" applied it', + ], [ "a view at the journal's name", new apply.MigrationJournalError( From 9bd416fcb6101e2388f465a1f6b204082c0f4103 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:13:09 +0000 Subject: [PATCH 150/317] fix(appkit): refuse an edited or diverged history on a deploy start, across line endings applyPendingMigrations takes onDrift. "warn" is today's behavior, so a developer can still rework an unapplied migration and rerun. migrateOnStart passes "refuse": a recorded migration whose file changed, or pending migrations next to recorded rows this checkout lacks, throw MigrationHistoryError before anything runs. The error names each tag and the way back: restore the file and add a new migration, or repair rows on the deploy branch and redeploy the unchanged file; deploy a commit whose journal has the recorded migrations, or merge them into main unchanged first. A pure rollback (unknown rows, nothing pending) still only warns. Each file now carries the hashes of its LF and CRLF variants, so a checkout with core.autocrlf matches the row another checkout recorded. The as-is hash is still what gets recorded. MigrationHistoryError exposes the refusal union instead of parallel stranded and ambiguous arrays. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 161 ++++++++++++++---- .../appkit/src/database/migrations/history.ts | 11 +- .../src/plugins/database/migrate-on-start.ts | 2 + 3 files changed, 136 insertions(+), 38 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 2c8f9b756..41d25d20e 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -10,6 +10,7 @@ import { createLogger } from "../../logging/logger"; import { type AmbiguousTimestamp, type MigrationFile, + type MigrationHistory, type RecordedMigration, reconcileMigrations, } from "./history"; @@ -29,6 +30,16 @@ import { const logger = createLogger("database"); +/** + * What to do when the recorded history drifted from the committed one: a + * recorded migration whose file changed since, or pending migrations next to + * recorded ones this checkout lacks. "warn" logs and applies what is pending, + * so a developer can rework their own unapplied migration. "refuse" throws + * MigrationHistoryError before applying anything, as a deploy start must, + * since the deploy branch only ever runs merged files as they were merged. + */ +type DriftPolicy = "warn" | "refuse"; + interface ApplyMigrationsOptions { /** Absolute path of the committed migrations folder. */ readonly migrationsFolder: string; @@ -38,6 +49,8 @@ interface ApplyMigrationsOptions { readonly lockWaitMs?: number; /** Longest wait for each table lock a migration takes, in milliseconds. */ readonly lockTimeoutMs?: number; + /** Defaults to "warn". */ + readonly onDrift?: DriftPolicy; } interface ApplyMigrationsResult { @@ -159,34 +172,45 @@ 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 ambiguous: AmbiguousTimestamp } + /** Recorded migrations whose committed file changed since (onDrift "refuse"). */ + | { readonly edited: readonly string[] } + /** + * Committed migrations still pending while the database recorded migrations + * this checkout lacks (onDrift "refuse"): the two histories diverged. + */ + | { + readonly diverged: { + readonly pending: 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 { - /** Committed migrations older than the last recorded one that never ran. */ - readonly stranded: readonly string[]; - /** Committed migrations whose timestamp the database recorded with hashes none of them has. */ - readonly ambiguous: readonly string[]; - - constructor(schemaName: string, refusal: HistoryRefusal) { - super( - "stranded" in refusal - ? strandedMessage(schemaName, refusal.stranded, refusal.last) - : ambiguousMessage(schemaName, refusal.ambiguous), - ); + constructor( + schemaName: string, + readonly refusal: HistoryRefusal, + ) { + super(refusalMessage(schemaName, refusal)); this.name = "MigrationHistoryError"; - this.stranded = Object.freeze( - "stranded" in refusal ? [...refusal.stranded] : [], - ); - this.ambiguous = Object.freeze( - "ambiguous" in refusal ? tags(refusal.ambiguous.files) : [], - ); } } +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[], @@ -215,6 +239,40 @@ function ambiguousMessage( ); } +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, + { + pending, + unknown, + }: { pending: 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 ${pending.join(", ")} ${pending.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; @@ -367,6 +425,24 @@ export function migrationLockKey(schemaName: string): string { 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)])]; +} + /** 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) { @@ -391,11 +467,36 @@ function readMigrations(folder: string, journal: Journal): MigrationFile[] { idx: entry.idx, when: entry.when, hash: file.hash, + hashes: lineEndingHashes(file.sql.join(STATEMENT_BREAKPOINT), file.hash), statements: file.sql, }; }); } +/** Why the committed history cannot be applied over the recorded one; undefined when it can. */ +function historyRefusal( + history: MigrationHistory, + files: readonly MigrationFile[], + onDrift: DriftPolicy, +): HistoryRefusal | undefined { + const ambiguous = history.ambiguous[0]; + if (ambiguous) return { ambiguous }; + if (history.stranded.length > 0) { + 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 (history.pending.length > 0 && history.unknown.length > 0) { + return { + diverged: { pending: tags(history.pending), unknown: history.unknown }, + }; + } + return undefined; +} + /** * 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 @@ -776,7 +877,8 @@ function duration(ms: number): string { * 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. An applied migration whose file changed, and - * recorded migrations that are not committed, are logged. + * recorded migrations that are not committed, are logged, or refused too with + * `onDrift: "refuse"` (see DriftPolicy). * * 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 @@ -796,6 +898,7 @@ export async function applyPendingMigrations( 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 { @@ -819,12 +922,9 @@ export async function applyPendingMigrations( files, await readRecordedMigrations(client, schemaName), ); + let refusal = historyRefusal(history, files, onDrift); let waitedMs = 0; - if ( - history.pending.length > 0 && - history.stranded.length === 0 && - history.ambiguous.length === 0 - ) { + if (history.pending.length > 0 && !refusal) { pending = tags(history.pending); step = "Waiting for the migration lock"; await prepareMigrationSession(client, reset); @@ -838,19 +938,10 @@ export async function applyPendingMigrations( files, await readRecordedMigrations(client, schemaName), ); + refusal = historyRefusal(history, files, onDrift); } - const ambiguous = history.ambiguous[0]; - if (ambiguous) throw new MigrationHistoryError(schemaName, { ambiguous }); - if (history.stranded.length > 0) { - const last = - files.find((file) => file.when === history.lastRecorded)?.tag ?? - `the migration recorded at ${new Date(history.lastRecorded ?? 0).toISOString()}`; - throw new MigrationHistoryError(schemaName, { - stranded: tags(history.stranded), - last, - }); - } + 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.", diff --git a/packages/appkit/src/database/migrations/history.ts b/packages/appkit/src/database/migrations/history.ts index b6ec23c07..7c53d5566 100644 --- a/packages/appkit/src/database/migrations/history.ts +++ b/packages/appkit/src/database/migrations/history.ts @@ -4,8 +4,13 @@ export interface MigrationFile { readonly idx: number; /** The journal's `when`, recorded as `created_at`. */ readonly when: number; - /** sha256 of the .sql file, recorded as `hash`. */ + /** sha256 of the .sql file as checked out here, recorded as `hash`. */ readonly hash: string; + /** + * Every hash a checkout of this file records: as is, with CRLF read as LF, + * and with LF read as CRLF. A row with any of them is this file. + */ + readonly hashes: readonly string[]; /** The file split on `--> statement-breakpoint`. */ readonly statements: readonly string[]; } @@ -30,7 +35,7 @@ export interface AmbiguousTimestamp { } /** Committed migrations compared with what the database recorded. */ -interface MigrationHistory { +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. */ @@ -86,7 +91,7 @@ export function reconcileMigrations( const rows = [...(rowsAt.get(when) ?? [])]; const unmatched: MigrationFile[] = []; for (const file of bucket) { - const match = rows.findIndex((row) => row.hash === file.hash); + 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); } diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index 76ec94b07..3173d89b8 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -82,6 +82,8 @@ export async function migrateOnStart( result = await applyPendingMigrations(pool, { migrationsFolder: folder, schemaName: schema.$schemaName, + // The deploy branch only ever runs merged files as they were merged. + onDrift: "refuse", }); } catch (error) { if ( From 7462c42664581ce9acebab9acf63fcdb3c3db5d8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:14:10 +0000 Subject: [PATCH 151/317] test(appkit): the ownership hints stop suggesting ALTER OWNER Measured on Lakebase: ALTER ... OWNER TO the service principal's role fails with "must be able to SET ROLE", and nobody holds ADMIN or SET on an Apps service principal role. The hints name the shared-database case first and say only Lakebase can move objects between roles. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/migrations/tests/apply.test.ts | 5 ++- .../migrations/tests/ownership.test.ts | 38 +++++++++---------- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index abebc3386..521968a05 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -823,7 +823,7 @@ describe("applyPendingMigrations", () => { `"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 transfer the table to "app-sp" (ALTER TABLE … OWNER TO), then deploy again. No migration was applied.`, + `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?", @@ -859,6 +859,9 @@ describe("applyPendingMigrations", () => { 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?"]); }); diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index 4f93e59d7..5d66a07a4 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -3,29 +3,29 @@ 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", () => { - const hint = ownershipHint("42501"); - expect(hint).toContain( - "lacks a privilege this migration needs: CREATE on the database, or ownership of the app schema and its tables", - ); - expect(hint).toContain( - "On the deploy branch that role is the app's service principal: bind the database to the app with CAN_CONNECT_AND_CREATE", + 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 names both roles and how that happens", () => { - const hint = ownershipHint("42501", { - schemaName: "app", - owner: "old-app-sp", - currentUser: "new-app-sp", - }); - expect(hint).toContain( - `Schema "app" is owned by "old-app-sp", but the app connects as "new-app-sp".`, - ); - expect(hint).toContain( - "the app's database resource was removed and added again, or the app was recreated", + test("a schema owned by another role names both roles, the shared-database case first, and who can move the objects", () => { + // Measured on Lakebase: ALTER ... OWNER TO the service principal's role + // fails with "must be able to SET ROLE", and nobody holds ADMIN or SET on it. + expect( + ownershipHint("42501", { + schemaName: "app", + owner: "old-app-sp", + currentUser: "new-app-sp", + }), + ).toBe( + 'Schema "app" is owned by "old-app-sp", but the app connects as "new-app-sp". ' + + "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 "old-app-sp". No Postgres role can hand them back to "new-app-sp"; only Lakebase can move them.', ); - expect(hint).toContain("set another schemaName in schema.ts"); }); test("a schema that does not exist yet points at CREATE on the database", () => { From 5776d3f9154a6b478eebd7643bb7a1284d35c702 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:14:28 +0000 Subject: [PATCH 152/317] test(appkit): cover init forking the branch databricks.yml deploys to The fork's parent is the branch the default target binds when the project has it, else the project's default branch, and the step names which. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 57 ++++++++++++++++++- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 31fce0a4f..919ca7e49 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -218,7 +218,7 @@ describe("runInit — dev branch", () => { }, }); expect(steps).toEqual([ - `Creating ${devBranchId(USER)} from production`, + `Creating ${devBranchId(USER)} from production (the branch databricks.yml deploys to)`, `Pointing .env at ${devBranchId(USER)}, database databricks_postgres`, `Handing schema app in database databricks_postgres on ${devBranchId(USER)} to you: deleting this branch's copy of role ${SP}, which owns it, with its objects reassigned to you`, `Dropping schema app on ${devBranchId(USER)}: a branch init forked starts without the rows it copied, and the committed migrations recreate its tables`, @@ -408,6 +408,59 @@ describe("runInit — dev branch", () => { }); }); +describe("runInit — the fork's parent", () => { + const STAGING = `${P}/branches/staging`; + + test("forks the branch databricks.yml deploys to when the project has it, and says so", async () => { + const lakebase = project(); + lakebase.addBranch(STAGING); + lakebase.addDatabase(STAGING, "databricks-postgres", "databricks_postgres"); + lakebase.addRole(STAGING, "alice", USER, ["DATABRICKS_SUPERUSER"]); + const ctx = appOn(lakebase, {}, { deploy: STAGING }); + + const { report, steps } = await init(ctx, { schema: "none" }); + + expect(lakebase.calls).toContain( + `createBranch ${devBranchId(USER)} ${JSON.stringify({ source_branch: STAGING, no_expiry: true })}`, + ); + expect(report).toMatchObject({ created: true, sourceBranch: STAGING }); + expect(steps).toContain( + `Creating ${devBranchId(USER)} from staging (the branch databricks.yml deploys to)`, + ); + }); + + test.each([ + ["a branch the project does not have", `${P}/branches/missing`], + ["a branch of another project", "projects/q/branches/main"], + ])( + "falls back to the project's default branch when databricks.yml binds %s", + async (_case, deploy) => { + const lakebase = project(); + const ctx = appOn(lakebase, {}, { deploy }); + + const { report, steps } = await init(ctx, { schema: "none" }); + + expect(lakebase.calls).toContain( + `createBranch ${devBranchId(USER)} ${JSON.stringify({ source_branch: PRODUCTION, no_expiry: true })}`, + ); + expect(report).toMatchObject({ created: true, sourceBranch: PRODUCTION }); + expect(steps).toContain( + `Creating ${devBranchId(USER)} from production (the project's default branch)`, + ); + }, + ); + + test("a deleted branch databricks.yml deploys to is not forked", async () => { + const lakebase = project(); + lakebase.addBranch(STAGING, { current_state: "DELETED" }); + const ctx = appOn(lakebase, {}, { deploy: STAGING }); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report.sourceBranch).toBe(PRODUCTION); + }); +}); + describe("runInit — a concurrent run on the same branch", () => { /** The API that another run raced: it did `before` first, then this run's call returns 409. */ function racedApi( @@ -566,7 +619,7 @@ describe("runInit — session branch", () => { `createBranch ${sessionBranchId(USER, id)} ${JSON.stringify({ source_branch: PRODUCTION, ttl: "604800s" })}`, ); expect(steps[0]).toBe( - `Creating ${sessionBranchId(USER, id)} from production, expiring after 7 days`, + `Creating ${sessionBranchId(USER, id)} from production (the branch databricks.yml deploys to), expiring after 7 days`, ); }); From a726b885f3f5ac696de6fabae6501642507b30a4 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:14:34 +0000 Subject: [PATCH 153/317] fix(appkit): fork a new dev or session branch from the deploy target's branch init forked the project's default branch, but the branch databricks.yml deploys to is the one that holds the deployed migrations. When the default target binds a live branch of the same project, init forks that one and falls back to the project's default branch otherwise. The step and the report name the parent and which rule picked it. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index af6d98501..61f807861 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -204,6 +204,8 @@ interface BranchRequest { readonly ttl: { readonly api: string; readonly label: string }; readonly boundary: DeployBoundary; readonly envFile: string; + /** The branch of this project the default databricks.yml target deploys to, which a new fork comes from. */ + readonly deployBranch: string | null; /** The branch .env marks as forked but not started; see LocalTarget.newBranch. */ readonly newBranch: string | null; readonly onStep: (message: string) => void; @@ -245,9 +247,11 @@ function branchLimitError( /** * Your dev branch or this checkout's session branch: found with one GET, or - * forked from the project's default branch. The branch id is resolved and - * checked against databricks.yml before any API call or .env write. An expired - * session branch gets a new session id; an expired dev branch is an error. + * forked from the branch databricks.yml deploys to, which holds the deployed + * migrations, else from the project's default branch. The branch id is + * resolved and checked against databricks.yml before any API call or .env + * write. An expired session branch gets a new session id; an expired dev + * branch is an error. */ async function findOrCreateBranch( ctx: DbContext, @@ -315,7 +319,10 @@ async function findOrCreateBranch( } const branches = await api.listBranches(project); - const parent = branches.find((b) => b.status?.default); + const deployed = branches.find( + (b) => b.name === request.deployBranch && !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.`); } @@ -329,7 +336,7 @@ async function findOrCreateBranch( APPKIT_DB_NEW_BRANCH: name, }); onStep( - `Creating ${resourceId(name)} from ${resourceId(parent.name)}${session === null ? "" : `, expiring after ${request.ttl.label}`}`, + `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), { @@ -630,6 +637,7 @@ async function initHolding( ttl, boundary: readDeployBoundary(ctx.root), envFile, + deployBranch: deploy?.branch ?? null, newBranch: local.newBranch, onStep, }); From 4f1d8062293c2698143969d4e4ccebed018f7614 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:14:37 +0000 Subject: [PATCH 154/317] docs(appkit): describe deploy starts, failure runbooks and owner recovery for database Two apps on one database with the same schema are unsupported; each needs its own schemaName. A deploy succeeds 2 s after the process starts unless app.yaml declares a health_check, and then /health must answer within 300 s, which AppKit binds only after migrations. Classic compute stops the old process first, no-downtime compute keeps it serving, a crashed process is not restarted, and scale-to-zero apps rerun the start on every cold start. A start migrates only as the app's own service principal, so a local start or run-local never migrates, and a deploy start refuses an edited migration or a diverged history. A failed migration is repaired in the rows, never by editing the migration; a DATABRICKS_SUPERUSER role on the deploy branch reads and writes the service principal's rows, runs a batched backfill between an expand and a contract migration, and can cancel a stuck appkit-migrate session. The owner recovery drops ALTER OWNER, which fails with "must be able to SET ROLE", lists what the role owns first, and gives delete-role --reassign-owned-to. init decides from the branch's schema owner instead of APPKIT_DB_NEW_BRANCH, tags the copied journal until the rebuild finishes, and forks the branch the default databricks.yml target binds. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 277 +++++++++++++++++++++++++--------- 1 file changed, 206 insertions(+), 71 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index cc8c0b10e..495af8c2d 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -90,8 +90,9 @@ Tables live in the Postgres schema `app` unless the second argument of 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 schema. Two apps on one database and one schema share the -migration history, and the second app's service principal cannot change the +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` @@ -145,42 +146,50 @@ you picked in its prompts, usually the branch the app deploys to, and `db init` asks nothing: 1. It keeps this checkout's session branch when `.env` points at one, and - otherwise uses your dev branch, `dev--`. It creates the branch when - it does not exist yet. `--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, points `.env` - at the branch, and hands you the app schema the fork copied (see - [One owner per branch](#one-owner-per-branch)). -3. It sets up the schema. On a branch it created in this run, it drops the app - schema the fork copied 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. In schema `public` it drops - only the tables you own, and lists the tables that keep their copied rows. - On a branch it reuses, it 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`. - `--schema clean` drops the app schema first. Without a terminal, - `--schema clean` 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. -4. When that needs drizzle-kit and the app does not have it, it installs the - version AppKit pins as a dev dependency. `migrate` and `introspect` generate - migrations with it. + 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. 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 is already yours, `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. `--schema clean` drops the app schema first. + Without a terminal, `--schema clean` 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, so the + next plain `init` still rebuilds it. +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 default branch] -New branches fork the project's default branch, so they start 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 default branch holds only data every -developer may see. +:::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 @@ -215,20 +224,27 @@ npx appkit db verify --deployed # the app runs, and its source has every commit ### 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 project's default branch, and points `.env` -at it. A fork copies every row of its source, production data included. A -branch `init` forked starts without them: `init` drops the app schema and -recreates it from the committed migrations. 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. Until the -rebuild has run, `.env` names the branch in `APPKIT_DB_NEW_BRANCH`, so a run -that stops early is finished by the next `init`. +with `--session`, as a fork of the branch the app deploys to, and points `.env` +at it. A fork copies every row of its source, production data included, and +every object with its owner, so on a new fork the app schema still belongs to +the fork's copy of the app's service principal. That owner is how `init` tells +an untouched copy from a branch of yours. It keeps no record of it in `.env`. + +On an untouched copy, `init` tags the copied migration journal with one row, +hands you the schema, then drops the schema and rebuilds it from the committed +migrations. 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. Dropping the schema removes the tag. A run that stops after tagging +and before the rebuild leaves the tag in place, and the next `init`, from any +checkout, reads it and finishes the rebuild. `npx appkit db migrate` refuses a +branch that still carries the tag. Run `init` to finish the rebuild. To keep the copied rows on a new branch, pass `--schema migrate`, or -`--schema introspect` without `schema.ts`. A branch `init` reuses keeps its -data: `init` migrates it, or introspects it without `schema.ts`. -`--schema clean` rebuilds a reused branch too, after a confirmation or with -`--yes`. +`--schema introspect` without `schema.ts`, and `init` says that it kept them. A +branch whose app schema is already yours keeps its data. `init` migrates it, or +introspects it without `schema.ts`. `--schema clean` rebuilds such a branch +too, after a confirmation or with `--yes`. `--schema none` leaves the schema +and its owner as the fork copied them, so the next plain `init` still rebuilds. In schema `public`, `init` and `clean` remove only the objects your role owns. On a fork of the deploy branch the app's service principal owns the tables, so @@ -281,13 +297,24 @@ AppKit never deletes a lock it does not hold. Scaffolded apps list the file in ### Changing tables in use -While a new release migrates on start, instances of the previous release keep -serving, so every migration must work with the code that is still running. A -change that drops or renames a table or column, changes a column's type, or makes -a column required breaks them, 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. +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 @@ -302,6 +329,16 @@ env: value: "true" ``` +The flag alone does not migrate. A start migrates only when the process +connects as the deployed app's own service principal, which is when `PGUSER` +equals `DATABRICKS_CLIENT_ID`. Databricks Apps sets both for a bound database. +A local start (`npm run dev`, `npm start`) connects as you, so it does not +migrate, and `databricks apps run-local` does not migrate either, even with +exported M2M credentials. Both log 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 @@ -310,22 +347,101 @@ another one to finish migrating. A migration that waits more than 5 seconds for 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. -`.env` never sets the flag, so a local start (`npm run dev`, `npm start`) never -migrates: use `npx appkit db migrate`. An app pointed at a dev or session branch -does not migrate it on start either. +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 project's default branch and - introspects it. It writes `schema.ts` from the tables in schema `app` and a - `0000_baseline` migration. When init created the branch in this run, it then - rebuilds schema `app` from that baseline, so the tables start without the rows - the fork copied. With a `schema.ts` already, run + `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 @@ -350,7 +466,11 @@ Migrations only go forward. There are no down migrations, and the app never undo 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. +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 @@ -375,18 +495,33 @@ tables: `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 schema `app` on the deploy branch -already belongs to another role, the app cannot migrate it, and the server log -names both roles. Use another `schemaName` in `defineSchema()`, or have the owner -transfer the schema. +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. That moves every object the role owns on the +branch, in every database, and deletes the role, so first list what it owns, in +each database of the branch: + +```sql +select n.nspname, c.relname, c.relkind + from pg_class c + join pg_namespace n on n.oid = c.relnamespace + where pg_get_userbyid(c.relowner) = ''; +``` -An app that was deleted and created again has a new service principal, and the old -one still owns the schema. Someone with CAN MANAGE on the Lakebase project moves -the objects to the new one, which deletes the old role: +Then someone with CAN MANAGE on the Lakebase project moves the objects: ```bash -# Both service principals' roles, by their client IDs +# 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/ From 72dee7d49455dc398e277245263979025f3f78ae Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:14:40 +0000 Subject: [PATCH 155/317] docs(appkit): say what init forks, when the app migrates, and why app.yaml has health_check The template README no longer says init forks the project's default branch or that any new branch is rebuilt; init forks the branch the app deploys to and rebuilds the app schema when it still belongs to the copied service principal. It says the deployed app migrates only as its own service principal and that the deploy waits up to 300 s for /health. The app.yaml comment records why the health check is there, so nobody removes it and turns a failed migration into a deploy that passed. Co-authored-by: Isaac Signed-off-by: ditadi --- template/README.md.tmpl | 18 ++++++++++++------ template/app.yaml.tmpl | 3 +++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/template/README.md.tmpl b/template/README.md.tmpl index 6cf56ce89..d427dc3e3 100644 --- a/template/README.md.tmpl +++ b/template/README.md.tmpl @@ -60,15 +60,17 @@ Run `npx appkit db init` once after scaffolding, and again after cloning. It ask nothing: it points `.env` at your branch and sets up its schema. ```bash -npx appkit db init # your dev branch, forked from the project's default branch +npx appkit db init # your dev branch, a fork of the branch the app deploys to npx appkit db init --session # a branch for this checkout that expires after 7 days npx appkit db init --dev # back to your dev branch ``` -A new branch is a copy of the default branch, production data included. When -`db init` creates the branch, it rebuilds the app schema from the committed -migrations, so its tables start empty. Other schemas keep the copied rows. -To keep the copied rows in the app schema too, create the branch with +A new branch is a copy of its source, production data included. When the app +schema on the branch still belongs to the copied service principal, `db init` +hands it to you and rebuilds it from the committed migrations, so its tables +start empty. Other schemas keep the copied rows. A branch whose app schema is +already yours keeps its rows, and `db init` migrates it. To keep the copied +rows in the app schema on a new branch too, run `npx appkit db init --schema migrate`. To change the schema, edit `config/database/schema.ts`, then: @@ -79,7 +81,11 @@ npx appkit db verify # read-only check of your branch against schema.ts and t ``` Commit the migrations. The deployed app applies them on start, because `app.yaml` -sets `APPKIT_DB_MIGRATE_ON_START=true`. To adopt tables that already exist, run +sets `APPKIT_DB_MIGRATE_ON_START=true`, and only when it connects as its own +service principal, so a local start or `databricks apps run-local` never +migrates. The deploy waits for `/health`, which the app serves only after its +migrations, for up to 300 seconds, so a failed migration fails the deploy. +To adopt tables that already exist, run `npx appkit db init --schema introspect`. It writes `schema.ts` from the branch's tables, and a `0000_baseline` migration (or `NNNN_introspect` when migrations already exist). diff --git a/template/app.yaml.tmpl b/template/app.yaml.tmpl index e85391b63..3f0dd55ad 100644 --- a/template/app.yaml.tmpl +++ b/template/app.yaml.tmpl @@ -1,4 +1,7 @@ command: ['{{or .packageManager "pnpm"}}', 'run', 'start'] +# Databricks Apps counts the deploy as succeeded only once /health answers 2xx, +# within 300 s. AppKit serves /health after every plugin's setup, migrations +# included, so a failed start fails the deploy instead of passing after 2 s. health_check: path: /health {{- if .appEnv}} From 382383c6bc7646f519788ecb96d13f4e9cea1764 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:14:55 +0000 Subject: [PATCH 156/317] fix(appkit): the ownership hints stop suggesting ALTER OWNER Measured on Lakebase: ALTER ... OWNER TO the service principal's role fails with "must be able to SET ROLE", and nobody holds ADMIN or SET on an Apps service principal role. The schema hint now names the shared-database case first (give each app its own schemaName), then the recreated-app case, and says no Postgres role can hand the objects back; only Lakebase can move them. The generic hint and the journal-table messages say the same. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/migrations/apply.ts | 3 ++- packages/appkit/src/database/migrations/ownership.ts | 12 +++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 41d25d20e..3adce16be 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -346,7 +346,8 @@ function journalRefusalMessage( ): string { const table = journalTable(schemaName); const untrusted = `The migrator connects as "${relation.currentUser}", which neither owns it nor inherits "${relation.owner}"`; - const transfer = `transfer the table to "${relation.currentUser}" (ALTER TABLE … OWNER TO), then deploy again.`; + // 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 = diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index ec2dd75ac..75486aa06 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -50,17 +50,19 @@ export function ownershipHint( "On the deploy branch that role is the app's service principal: bind the database to the app with CAN_CONNECT_AND_CREATE." ); } + // ALTER ... OWNER TO the service principal's role fails on Lakebase with + // "must be able to SET ROLE": nobody holds ADMIN or SET on that role. if (ownership && ownership.owner !== ownership.currentUser) { return ( `Schema "${ownership.schemaName}" is owned by "${ownership.owner}", but the app connects as "${ownership.currentUser}". ` + - "This happens when the app's database resource was removed and added again, or the app was recreated with a new service principal: " + - `Lakebase hands the objects to another role. Have "${ownership.owner}" transfer the schema and its tables to "${ownership.currentUser}" ` + - "(ALTER … OWNER TO), or set another schemaName in schema.ts." + "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.` ); } 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, " + - "and if another role created an object the migration changes, have that role transfer it to the app's service principal." + "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." ); } From 5867ff0bee60807910f12221da260e972a894bc9 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:15:50 +0000 Subject: [PATCH 157/317] test(appkit): cover init installing drizzle-kit for every start except none Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 919ca7e49..1cdd27de5 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -960,11 +960,13 @@ describe("runInit — schema start", () => { ); }); - test("clean drops the schema, then applies the committed migrations without generating; it needs no drizzle-kit", async () => { + test("clean drops the schema, then applies the committed migrations without generating", async () => { const ctx = appOn(project(), {}, { files: { "package.json": "{}" } }); - const runCommand = vi.fn(); - const { report } = await init(ctx, { schema: "clean", runCommand }); + const { report } = await init(ctx, { + schema: "clean", + runCommand: vi.fn(), + }); expect(cleanHolding).toHaveBeenCalledOnce(); expect(migrateHolding.mock.calls[0]?.[2]).toEqual({ @@ -974,7 +976,6 @@ describe("runInit — schema start", () => { expect(cleanHolding.mock.invocationCallOrder[0]).toBeLessThan( migrateHolding.mock.invocationCallOrder[0] ?? 0, ); - expect(runCommand).not.toHaveBeenCalled(); expect(report.start).toEqual({ kind: "clean", clean: { branch: DEV, schemaName: "app", dependents: [], kept: [] }, @@ -982,6 +983,30 @@ describe("runInit — schema start", () => { }); }); + test.each(["clean", "migrate", "introspect", undefined] as const)( + "--schema %s installs drizzle-kit when the app lacks it, so the next migrate and check have it", + async (schema) => { + const ctx = appOn(project(), {}, { files: { "package.json": "{}" } }); + const runCommand = vi.fn(); + + const { report } = await init(ctx, { schema, runCommand }); + + const install = ["add", "-D", "-E", `drizzle-kit@${DRIZZLE_KIT_VERSION}`]; + expect(runCommand).toHaveBeenCalledWith("pnpm", install, ctx.root); + expect(report.installed).toBe(`pnpm ${install.join(" ")}`); + }, + ); + + test("--schema none installs nothing", async () => { + const ctx = appOn(project(), {}, { files: { "package.json": "{}" } }); + const runCommand = vi.fn(); + + const { report } = await init(ctx, { schema: "none", runCommand }); + + expect(runCommand).not.toHaveBeenCalled(); + expect(report.installed).toBeNull(); + }); + test("one history lock covers init's clean and migrate: another command is refused meanwhile, and the lock goes at the end", async () => { const ctx = appOn(project(), {}, { files: { "package.json": "{}" } }); const lockFile = path.join(ctx.root, "config/database/.appkit-db.lock"); From 3aaeb20f66ebbd7fc8483e1c07060c84a7ef402a Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:15:54 +0000 Subject: [PATCH 158/317] fix(appkit): install drizzle-kit for every init start except none init installed drizzle-kit only for the migrate and introspect starts. A new fork's default start is the rebuild, so it skipped the install, and the next `appkit db migrate` or `appkit db check` failed to load drizzle-kit. Every start except none leaves the branch for those commands, so every start except none installs it. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 61f807861..c922885e2 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -698,10 +698,12 @@ async function initHolding( onStep, }); + // Every start leaves the branch for `appkit db migrate` and `appkit db check`, + // which diff schema.ts with drizzle-kit, so every start except none installs it. const installed = - startKind === "migrate" || startKind === "introspect" - ? ensureDrizzleKit(ctx.root, options.runCommand ?? runCommand, onStep) - : null; + startKind === "none" + ? null + : ensureDrizzleKit(ctx.root, options.runCommand ?? runCommand, onStep); // Without a lock (--schema none) the schema stays as the fork has it. let start: InitStart = { kind: "none" }; From c663c3bb16c45ef932fc1dabf94511b745a9eb45 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:17:07 +0000 Subject: [PATCH 159/317] fix(appkit): stop claiming the role delete covers every database Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 4 ++-- packages/appkit/src/database/migrations/ownership.ts | 2 +- .../appkit/src/database/migrations/tests/ownership.test.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 495af8c2d..f7af04b2e 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -508,8 +508,8 @@ 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. That moves every object the role owns on the -branch, in every database, and deletes the role, so first list what it owns, in -each database of the branch: +branch and deletes the role, so first list what it owns, in each database of the +branch: ```sql select n.nspname, c.relname, c.relkind diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index 7c2d0e181..201fc7c30 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -83,7 +83,7 @@ export function ownershipHint( `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, in every database, and deletes the role, so first check what it owns. " + + "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." ); } diff --git a/packages/appkit/src/database/migrations/tests/ownership.test.ts b/packages/appkit/src/database/migrations/tests/ownership.test.ts index a5a48ab4f..2b6db63de 100644 --- a/packages/appkit/src/database/migrations/tests/ownership.test.ts +++ b/packages/appkit/src/database/migrations/tests/ownership.test.ts @@ -36,7 +36,7 @@ describe("ownership: one owner per branch", () => { `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, in every database, and deletes the role, so first check what it owns.", + "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( From 7ac125a6276a8c38080198da7a11b1c52418d1ea Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:17:36 +0000 Subject: [PATCH 160/317] test(appkit): migrate on start only as the app's own service principal The decision is a pure function of the environment: off without the flag, skipped with a reason when a credential is missing or PGUSER is not the app's client id, migrate otherwise. A skipped start warns once with that reason, and the schema check stops telling an operator to set a flag that is already set. A deployed app bound to a branch with the exact shape of a developer or agent session branch refuses to start instead of skipping silently; session-store and session-k3x9q2m7 do not have that shape. Co-authored-by: Isaac Signed-off-by: ditadi --- .../plugins/database/tests/lifecycle.test.ts | 56 +++++++++-- .../database/tests/migrate-on-start.test.ts | 94 +++++++++++++------ .../database/tests/schema-check.test.ts | 65 ++++++++++--- 3 files changed, 167 insertions(+), 48 deletions(-) diff --git a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts index 0401912f6..b0efd37b1 100644 --- a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts +++ b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts @@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => ({ createDrizzleDb: vi.fn(), createDrizzleDataPath: vi.fn(), assertSchemaMatchesDatabase: vi.fn(), - shouldMigrateOnStart: vi.fn(() => false), + decideMigrateOnStart: vi.fn(() => ({ kind: "off" })), migrateOnStart: vi.fn(async () => undefined), })); vi.mock("../../../connectors/lakebase", () => ({ @@ -25,7 +25,7 @@ vi.mock("../schema-check", () => ({ })); // The migrator has its own suite; here only its place in setup matters. vi.mock("../migrate-on-start", () => ({ - shouldMigrateOnStart: mocks.shouldMigrateOnStart, + decideMigrateOnStart: mocks.decideMigrateOnStart, migrateOnStart: mocks.migrateOnStart, })); @@ -104,7 +104,7 @@ function arrange(path = fakePath()) { beforeEach(() => { vi.clearAllMocks(); // clearAllMocks keeps implementations; a test that turns migration on must not leak it. - mocks.shouldMigrateOnStart.mockReturnValue(false); + mocks.decideMigrateOnStart.mockReturnValue({ kind: "off" }); }); afterEach(() => vi.restoreAllMocks()); @@ -240,7 +240,7 @@ describe("createDatabaseState", () => { order.push("pool"); return pool; }); - mocks.shouldMigrateOnStart.mockReturnValue(true); + mocks.decideMigrateOnStart.mockReturnValue({ kind: "migrate" }); mocks.migrateOnStart.mockImplementationOnce(async () => { order.push("migrate"); }); @@ -252,15 +252,53 @@ describe("createDatabaseState", () => { expect(order).toEqual(["pool", "migrate", "select 1", "catalog"]); expect(mocks.migrateOnStart).toHaveBeenCalledWith(pool, schema); + // The catalog check words its advice by whether this start migrated. + expect(mocks.assertSchemaMatchesDatabase).toHaveBeenCalledWith( + path, + schema, + { kind: "migrate" }, + ); }); - test("local runs never call the migrator", async () => { - const { execute } = arrange(); - mocks.shouldMigrateOnStart.mockReturnValue(false); + test("local runs never call the migrator, and say nothing", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + const { path, execute } = arrange(); + mocks.decideMigrateOnStart.mockReturnValue({ kind: "off" }); + + await createDatabaseState(schema, execute); + + expect(mocks.migrateOnStart).not.toHaveBeenCalled(); + expect(warn).not.toHaveBeenCalled(); + expect(mocks.assertSchemaMatchesDatabase).toHaveBeenCalledWith( + path, + schema, + { kind: "off" }, + ); + }); + + test("a start the flag asks to migrate but that is not the deployed app warns once with the reason, and migrates nothing", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + const { path, execute } = arrange(); + const decision = { + kind: "skipped", + reason: `PGUSER is "jane@example.com", not the app's client id in DATABRICKS_CLIENT_ID.`, + } as const; + mocks.decideMigrateOnStart.mockReturnValue(decision); await createDatabaseState(schema, execute); expect(mocks.migrateOnStart).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls.flat().map(String).join(" ")).toContain( + "APPKIT_DB_MIGRATE_ON_START is true, but this process is not the deployed app, so it did not migrate. " + + `PGUSER is "jane@example.com", not the app's client id in DATABRICKS_CLIENT_ID. ` + + "Databricks Apps sets DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET and PGUSER for the deployed app.", + ); + expect(mocks.assertSchemaMatchesDatabase).toHaveBeenCalledWith( + path, + schema, + decision, + ); }); test("a migration failure keeps its reason, ends the pool and publishes nothing", async () => { @@ -268,7 +306,7 @@ describe("createDatabaseState", () => { const errorLog = vi .spyOn(console, "error") .mockImplementation(() => undefined); - mocks.shouldMigrateOnStart.mockReturnValue(true); + mocks.decideMigrateOnStart.mockReturnValue({ kind: "migrate" }); const failure = new DatabasePluginError( "SETUP_FAILED", "setup", @@ -294,7 +332,7 @@ describe("createDatabaseState", () => { const errorLog = vi .spyOn(console, "error") .mockImplementation(() => undefined); - mocks.shouldMigrateOnStart.mockReturnValue(true); + mocks.decideMigrateOnStart.mockReturnValue({ kind: "migrate" }); mocks.migrateOnStart.mockRejectedValueOnce( new Error("secret connection string"), ); diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index 701ea4961..4cfb296ad 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -18,7 +18,7 @@ import { DatabasePluginError } from "../../../database/errors"; import * as apply from "../../../database/migrations/apply"; import { MigrationFilesError } from "../../../database/migrations/paths"; import { defineSchema, id } from "../../../database/schema-builder"; -import { migrateOnStart, shouldMigrateOnStart } from "../migrate-on-start"; +import { decideMigrateOnStart, migrateOnStart } from "../migrate-on-start"; const schema = defineSchema( ({ table }) => ({ notes: table("notes", { id: id() }) }), @@ -73,7 +73,7 @@ afterEach(() => { } }); -describe("shouldMigrateOnStart", () => { +describe("decideMigrateOnStart", () => { const credentials = { DATABRICKS_CLIENT_ID: "sp-client-id", DATABRICKS_CLIENT_SECRET: "secret", @@ -81,31 +81,52 @@ describe("shouldMigrateOnStart", () => { const optIn = { APPKIT_DB_MIGRATE_ON_START: "true" }; test.each([ - ["a deployed app that opts in", { ...optIn, ...credentials }, true], + ["a deployed app that opts in", { ...optIn, ...credentials }], + [ + "a deployed app with a bound database: Apps sets PGUSER to its client id", + { ...optIn, ...credentials, PGUSER: "sp-client-id" }, + ], + ] as const)("%s migrates", (_label, env) => { + expect(decideMigrateOnStart(env)).toEqual({ kind: "migrate" }); + }); + + test.each([ [ "a deployed app without the flag", { DATABRICKS_APP_NAME: "my-app", ...credentials }, - false, ], [ "a flag other than true", { APPKIT_DB_MIGRATE_ON_START: "1", ...credentials }, - false, ], + ["nothing set", {}], + ] as const)("%s: off, with nothing to say", (_label, env) => { + expect(decideMigrateOnStart(env)).toEqual({ kind: "off" }); + }); + + test.each([ [ "`databricks apps run-local`: the flag from app.yaml, no credentials", - { ...optIn, DATABRICKS_APP_NAME: "my-app" }, - false, + { ...optIn, DATABRICKS_APP_NAME: "app" }, + "DATABRICKS_CLIENT_ID is not set.", ], [ "no client secret (a developer's own credentials)", { ...optIn, DATABRICKS_CLIENT_ID: "x" }, - false, + "DATABRICKS_CLIENT_SECRET is not set.", ], - ["no client id", { ...optIn, DATABRICKS_CLIENT_SECRET: "x" }, false], - ["nothing set", {}, false], - ] as const)("%s → %s", (_label, env, expected) => { - expect(shouldMigrateOnStart(env)).toBe(expected); + [ + "no client id", + { ...optIn, DATABRICKS_CLIENT_SECRET: "x" }, + "DATABRICKS_CLIENT_ID is not set.", + ], + [ + "run-local with exported M2M credentials and the developer's .env", + { ...optIn, ...credentials, PGUSER: "jane@example.com" }, + `PGUSER is "jane@example.com", not the app's client id in DATABRICKS_CLIENT_ID.`, + ], + ] as const)("%s: skipped, naming the reason", (_label, env, reason) => { + expect(decideMigrateOnStart(env)).toEqual({ kind: "skipped", reason }); }); }); @@ -149,29 +170,48 @@ describe("migrateOnStart", () => { }); test.each([ - ["a developer branch", "dev-jane-a1b2c3"], - ["an agent session branch", "session-k3x9q2m7"], + ["a developer branch", "dev-jane-a1b2c3", "a developer"], + [ + "a developer branch with a dashed slug", + "dev-jane-doe-2-a1b2c3", + "a developer", + ], + ["an agent session branch", "session-a1b2c3-k3x9q2m7", "an agent session"], ])( - "%s is never migrated on start, even with committed migrations", - async (_label, branch) => { - const warn = vi - .spyOn(console, "warn") - .mockImplementation(() => undefined); - - await migrateOnStart(pool, schema, appRootWithMigrations(), { - ...deployEnv, - LAKEBASE_ENDPOINT: `projects/p/branches/${branch}/endpoints/primary`, - }); + "a deployed app bound to %s refuses to start, naming the branch and the fix", + async (_label, branch, kind) => { + const error = await migrateOnStart( + pool, + schema, + appRootWithMigrations(), + { + ...deployEnv, + LAKEBASE_ENDPOINT: `projects/p/branches/${branch}/endpoints/primary`, + }, + ).catch((caught: unknown) => caught); - expect(applyPendingMigrations).not.toHaveBeenCalled(); - expect(warn.mock.calls.flat().map(String).join(" ")).toContain( - `Not migrating branch ${branch} on start`, + expect(error).toBeInstanceOf(DatabasePluginError); + expect(error).toMatchObject({ category: "SETUP_FAILED", phase: "setup" }); + expect((error as Error).message).toContain( + `LAKEBASE_ENDPOINT points at branch "${branch}", whose name has the shape of ${kind} branch, and a deployed app migrates only its deploy branch. ` + + "Bind the app to its deploy branch. If this is the deploy branch, rename it so it does not look like a dev or session branch.", ); + expect(applyPendingMigrations).not.toHaveBeenCalled(); }, ); test.each([ ["a branch that only starts with dev-", "dev-environment"], + ["a dev- branch without the six hex characters", "dev-jane-a1b2c"], + [ + "a dev- shape longer than a branch id can be", + `dev-${"a".repeat(54)}-a1b2c3`, + ], + ["a session- branch that is not an agent session", "session-store"], + [ + "a session- branch whose id is not six hex characters", + "session-k3x9q2m7", + ], ["the production branch", "production"], ])("%s is migrated", async (_label, branch) => { vi.spyOn(console, "log").mockImplementation(() => undefined); diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index 6f10836a8..bae7d77df 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -21,6 +21,9 @@ type CatalogRow = { relation_kind: string; }; +/** A local start: APPKIT_DB_MIGRATE_ON_START is not set. */ +const OFF = { kind: "off" } as const; + /** Answer the catalog query with the given tables and columns. */ function catalog( tables: Record, @@ -53,7 +56,7 @@ describe("assertSchemaMatchesDatabase", () => { notes: ["id", "board_id", "author_email", "body"], }); await expect( - assertSchemaMatchesDatabase(path, schema), + assertSchemaMatchesDatabase(path, schema, OFF), ).resolves.toBeUndefined(); }); @@ -61,7 +64,7 @@ describe("assertSchemaMatchesDatabase", () => { // The shape a same-named table from another app leaves behind. const { path } = catalog({ notes: ["id", "case_id", "author", "content"] }); - const error = await assertSchemaMatchesDatabase(path, schema).catch( + const error = await assertSchemaMatchesDatabase(path, schema, OFF).catch( (caught) => caught, ); @@ -79,9 +82,9 @@ describe("assertSchemaMatchesDatabase", () => { boards: ["id", "title"], notes: ["id", "board_id", "body"], }); - await expect(assertSchemaMatchesDatabase(path, schema)).rejects.toThrow( - "table public.notes is missing column author_email", - ); + await expect( + assertSchemaMatchesDatabase(path, schema, OFF), + ).rejects.toThrow("table public.notes is missing column author_email"); }); test("reports a table with no readable columns as missing them all", async () => { @@ -89,9 +92,9 @@ describe("assertSchemaMatchesDatabase", () => { boards: [], notes: ["id", "board_id", "author_email", "body"], }); - await expect(assertSchemaMatchesDatabase(path, schema)).rejects.toThrow( - "table public.boards is missing columns id, title", - ); + await expect( + assertSchemaMatchesDatabase(path, schema, OFF), + ).rejects.toThrow("table public.boards is missing columns id, title"); }); test.each([ @@ -109,9 +112,9 @@ describe("assertSchemaMatchesDatabase", () => { { boards: kind }, ); - await expect(assertSchemaMatchesDatabase(path, schema)).rejects.toThrow( - `public.boards is a ${description}, not a table`, - ); + await expect( + assertSchemaMatchesDatabase(path, schema, OFF), + ).rejects.toThrow(`public.boards is a ${description}, not a table`); }, ); @@ -122,7 +125,7 @@ describe("assertSchemaMatchesDatabase", () => { ); const { raw, path } = catalog({ tags: ["id"] }); - await assertSchemaMatchesDatabase(path, scoped); + await assertSchemaMatchesDatabase(path, scoped, OFF); expect(raw).toHaveBeenCalledTimes(1); const [strings, ...values] = raw.mock.calls[0] as unknown as [ @@ -139,7 +142,45 @@ describe("assertSchemaMatchesDatabase", () => { await assertSchemaMatchesDatabase( path, defineSchema(() => ({})), + OFF, ); expect(raw).not.toHaveBeenCalled(); }); + + describe("the advice says how the missing objects get created", () => { + const missingColumn = () => + catalog({ boards: ["id", "title"], notes: ["id", "board_id", "body"] }) + .path; + + test("without the flag: create them, or commit migrations and set the flag", async () => { + await expect( + assertSchemaMatchesDatabase(missingColumn(), schema, OFF), + ).rejects.toThrow( + "Create them, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start.", + ); + }); + + test("with the flag, on a start that did not migrate: point at the startup warning, never at the flag", async () => { + const error = await assertSchemaMatchesDatabase(missingColumn(), schema, { + kind: "skipped", + reason: "DATABRICKS_CLIENT_ID is not set.", + }).catch((caught) => caught); + + expect(error.message).toContain( + "APPKIT_DB_MIGRATE_ON_START is true, but this process did not migrate on start. The warning logged before this error says why.", + ); + expect(error.message).not.toContain("set APPKIT_DB_MIGRATE_ON_START"); + }); + + test("after the start migrated: the committed migrations leave them missing", async () => { + const error = await assertSchemaMatchesDatabase(missingColumn(), schema, { + kind: "migrate", + }).catch((caught) => caught); + + expect(error.message).toContain( + "The committed migrations under config/database/migrations were applied on start and leave them missing. Commit a migration that creates them and deploy again.", + ); + expect(error.message).not.toContain("set APPKIT_DB_MIGRATE_ON_START"); + }); + }); }); From 1857d5b6e2b97558521202012ecc219bc8b08116 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:18:08 +0000 Subject: [PATCH 161/317] test(appkit): keep the init lock test off the real drizzle-kit install Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/tests/init.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 1cdd27de5..a9ae30fac 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1019,7 +1019,7 @@ describe("runInit — schema start", () => { return { branch: DEV, schemaName: "app", dependents: [], kept: [] }; }); - await init(ctx, { schema: "clean" }); + await init(ctx, { schema: "clean", runCommand: vi.fn() }); expect(migrateHolding.mock.calls[0]?.[1]).toBe( cleanHolding.mock.calls[0]?.[1], From 3e3e6e90955946d81cafa10ed9435fa8a70217d8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:18:48 +0000 Subject: [PATCH 162/317] test(appkit): appkit db migrate reports statements that may fail on existing rows A new dev branch has no rows, so SET NOT NULL, a required column, a new constraint, a unique index and a type change pass there and can fail on the deploy branch. The report and the CLI must carry them as their own class, apart from what breaks the previous release. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/migrate.test.ts | 32 ++++++++++- .../database/tooling/tests/migrations.test.ts | 56 +++++++++++++++++++ .../src/cli/commands/db/migrate.test.ts | 42 ++++++++++++-- 3 files changed, 122 insertions(+), 8 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 8fbb6aa74..19ee1517e 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -162,6 +162,7 @@ describe("runMigrate", () => { expect(report.applied).toEqual(["0000_migration"]); expect(report.notApplied).toBeUndefined(); expect(report.breaking).toBeUndefined(); + expect(report.dataDependent).toBeUndefined(); expect(fs.readFileSync(report.typesFile, "utf-8")).toContain("notes"); }); @@ -372,22 +373,47 @@ describe("runMigrate", () => { 'ALTER TABLE "app"."notes" DROP COLUMN "body";', ]); expect(report.breaking).toEqual(report.generated?.statements); + expect(report.dataDependent).toBeUndefined(); }); - test("a failure after generating still carries what the kept migration breaks", async () => { + test("reports the statements that may fail on rows the deploy branch has", async () => { const ctx = app(`notes: table("notes", { id: id(), body: text() })`); resolveEnvBranch.mockResolvedValue(null); await runMigrate(ctx, { interactive: false }); - writeSchema(ctx.root, `notes: table("notes", { id: id() })`); + writeSchema( + ctx.root, + `notes: table("notes", { id: id(), body: text().unique() })`, + ); + const report = await runMigrate(ctx, { interactive: false }); + + expect(report.generated?.statements).toEqual([ + 'ALTER TABLE "app"."notes" ADD CONSTRAINT "notes_body_unique" UNIQUE("body");', + ]); + expect(report.dataDependent).toEqual(report.generated?.statements); + expect(report.breaking).toBeUndefined(); + }); + + test("a failure after generating still carries what the kept migration warns about", async () => { + const ctx = app(`notes: table("notes", { id: id(), body: text() })`); + resolveEnvBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + + writeSchema( + ctx.root, + `notes: table("notes", { id: id(), body: text().notNull() })`, + ); resolveEnvBranch.mockRejectedValue(new Error("403 Forbidden")); const error = await runMigrate(ctx, { interactive: false }).catch( (caught: unknown) => caught, ); + const setNotNull = + 'ALTER TABLE "app"."notes" ALTER COLUMN "body" SET NOT NULL;'; expect(error).toMatchObject({ generated: { tag: "0001_migration" }, - breaking: ['ALTER TABLE "app"."notes" DROP COLUMN "body";'], + breaking: [setNotNull], + dataDependent: [setNotNull], }); expect((error as Error).message).toMatch( /^Wrote .*0001_migration\.sql, but did not apply it: 403 Forbidden$/, diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index 75512194d..85bdda9d2 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -21,6 +21,7 @@ import { import { withHistoryLock } from "../history-lock"; import { breakingStatements, + dataDependentStatements, discardMigrationFiles, generateMigrationFiles, MigrationRenameAmbiguityError, @@ -392,6 +393,61 @@ describe("breakingStatements", () => { }); }); +describe("dataDependentStatements", () => { + test("new constraints, unique indexes, type changes and new NOT NULLs; new tables, nullable columns, identity keys and drops pass", () => { + const dataDependent = [ + 'ALTER TABLE "app"."notes" ALTER COLUMN "title" SET NOT NULL;', + 'ALTER TABLE "app"."notes" ADD COLUMN "title" text NOT NULL;', + 'ALTER TABLE "app"."notes" ALTER COLUMN "n" SET DATA TYPE integer;', + 'ALTER TABLE "app"."authors" ADD CONSTRAINT "authors_email_unique" UNIQUE("email");', + 'ALTER TABLE "app"."notes" ADD CONSTRAINT "notes_id_pk" PRIMARY KEY("id");', + 'ALTER TABLE "app"."notes" ADD CONSTRAINT "notes_score_check" CHECK ("app"."notes"."score" >= 0);', + 'ALTER TABLE "app"."notes" ADD CONSTRAINT "notes_author_authors_id_fk" FOREIGN KEY ("author") REFERENCES "app"."authors"("id") ON DELETE no action ON UPDATE no action;', + 'ALTER TABLE "app"."bookings" ADD CONSTRAINT "bookings_room_during_excl" EXCLUDE USING gist ("room" WITH =, "during" WITH &&);', + 'ALTER TABLE "app"."notes" ADD COLUMN "slug" text UNIQUE;', + 'ALTER TABLE "app"."notes" ADD COLUMN "key" integer PRIMARY KEY;', + 'ALTER TABLE "app"."notes" ADD COLUMN "score" integer DEFAULT 0 CHECK ("score" > 0);', + `ALTER TABLE "app"."notes" ADD COLUMN "author" integer DEFAULT 1 REFERENCES "app"."authors"("id");`, + 'CREATE UNIQUE INDEX "notes_n_uidx" ON "app"."notes" USING btree ("n");', + ]; + const safe = [ + 'CREATE TABLE "app"."tags" ("id" serial PRIMARY KEY, "name" text NOT NULL, "slug" text UNIQUE, "parent" integer REFERENCES "app"."tags"("id"), CONSTRAINT "tags_name_check" CHECK (length("name") > 0));', + 'CREATE INDEX "notes_title_idx" ON "app"."notes" USING btree ("title");', + 'ALTER TABLE "app"."notes" ADD COLUMN "title" text;', + `ALTER TABLE "app"."notes" ADD COLUMN "title" text DEFAULT 'untitled' NOT NULL;`, + 'ALTER TABLE "app"."notes" ADD COLUMN "words" integer GENERATED ALWAYS AS (length("body")) STORED NOT NULL;', + 'ALTER TABLE "app"."notes" ADD COLUMN "seq" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY (sequence name "app"."notes_seq_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1);', + // What id() adds to an existing table; the identity fills every row. + 'ALTER TABLE "app"."notes" ADD COLUMN "id" integer PRIMARY KEY NOT NULL GENERATED BY DEFAULT AS IDENTITY (sequence name "app"."notes_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1);', + 'ALTER TABLE "app"."notes" ALTER COLUMN "title" DROP NOT NULL;', + `ALTER TABLE "app"."notes" ALTER COLUMN "title" SET DEFAULT 'untitled';`, + 'ALTER TABLE "app"."notes" DROP CONSTRAINT "notes_tag_fk";', + 'DROP INDEX "app"."notes_title_idx";', + 'ALTER TABLE "app"."notes" DROP COLUMN "body";', + 'ALTER TABLE "app"."notes" RENAME COLUMN "body" TO "text";', + 'DROP TABLE "app"."tags" CASCADE;', + `ALTER TYPE "app"."mood" ADD VALUE 'calm';`, + ]; + + expect(dataDependentStatements([...safe, ...dataDependent])).toEqual( + dataDependent, + ); + }); + + test("a statement can be in both classes, and each class keeps its own", () => { + const both = 'ALTER TABLE "app"."notes" ALTER COLUMN "title" SET NOT NULL;'; + const drop = 'ALTER TABLE "app"."notes" DROP COLUMN "body";'; + const unique = + 'ALTER TABLE "app"."notes" ADD CONSTRAINT "notes_title_unique" UNIQUE("title");'; + + expect(breakingStatements([both, drop, unique])).toEqual([both, drop]); + expect(dataDependentStatements([both, drop, unique])).toEqual([ + both, + unique, + ]); + }); +}); + describe("discardMigrationFiles", () => { test("a first migration goes with the folders it created", async () => { const folder = tempFolder(); diff --git a/packages/shared/src/cli/commands/db/migrate.test.ts b/packages/shared/src/cli/commands/db/migrate.test.ts index a48bee553..8d5621896 100644 --- a/packages/shared/src/cli/commands/db/migrate.test.ts +++ b/packages/shared/src/cli/commands/db/migrate.test.ts @@ -133,6 +133,33 @@ describe("appkit db migrate", () => { expect(output(log)).toContain( `0002_migration breaks instances still running the previous release, which keep serving while the new one migrates on start: ${drop} Deploy code that works with both the old and the new schema first, then this change in a later deploy.`, ); + expect(output(log)).not.toContain("may fail on rows"); + }); + + test("warns when the migration may fail on rows the deploy branch has", async () => { + const unique = + 'ALTER TABLE "app"."notes" ADD CONSTRAINT "notes_body_unique" UNIQUE("body");'; + runMigrate.mockResolvedValue({ + generated: { + tag: "0002_migration", + file: path.join( + process.cwd(), + "config/database/migrations/0002_migration.sql", + ), + statements: [unique], + }, + dataDependent: [unique], + applied: ["0002_migration"], + typesFile, + }); + + await dbCommand.parseAsync(["migrate"], { from: "user" }); + + expect(output(log)).toContain( + `0002_migration may fail on rows the deploy branch has and a new branch does not: ${unique} Test the migration on a branch that has a copy of the deploy branch's data before you deploy.`, + ); + expect(output(log)).not.toContain("breaks instances"); + expect(process.exitCode).toBeUndefined(); }); test("says why nothing was applied", async () => { @@ -151,8 +178,9 @@ describe("appkit db migrate", () => { expect(process.exitCode).toBeUndefined(); }); - test("when applying fails after a migration was written, it still warns about what that migration breaks", async () => { - const drop = 'ALTER TABLE "app"."notes" DROP COLUMN "body";'; + test("when applying fails after a migration was written, it still warns about that migration", async () => { + const setNotNull = + 'ALTER TABLE "app"."notes" ALTER COLUMN "body" SET NOT NULL;'; runMigrate.mockRejectedValue( Object.assign( new Error( @@ -165,9 +193,10 @@ describe("appkit db migrate", () => { process.cwd(), "config/database/migrations/0002_migration.sql", ), - statements: [drop], + statements: [setNotNull], }, - breaking: [drop], + breaking: [setNotNull], + dataDependent: [setNotNull], }, ), ); @@ -178,7 +207,10 @@ describe("appkit db migrate", () => { "Wrote config/database/migrations/0002_migration.sql, but did not apply it: 403 Forbidden", ); expect(output(log)).toContain( - `0002_migration breaks instances still running the previous release, which keep serving while the new one migrates on start: ${drop} Deploy code that works with both the old and the new schema first, then this change in a later deploy.`, + `0002_migration breaks instances still running the previous release, which keep serving while the new one migrates on start: ${setNotNull} Deploy code that works with both the old and the new schema first, then this change in a later deploy.`, + ); + expect(output(log)).toContain( + `0002_migration may fail on rows the deploy branch has and a new branch does not: ${setNotNull} Test the migration on a branch that has a copy of the deploy branch's data before you deploy.`, ); expect(process.exitCode).toBe(1); }); From 44968976ae2ed94385e10b2789adcd014f034023 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:18:54 +0000 Subject: [PATCH 163/317] fix(appkit): appkit db migrate warns when a migration may fail on existing rows Postgres checks SET NOT NULL, a NOT NULL column without a default, a new constraint, a unique index and a type cast against the rows already in the table. A new dev branch has none, so the migration passes there and can fail on deploy. Classify them as a second table of predicates next to BREAKS_PREVIOUS_RELEASE, carry them in the report and the kept-migration error under dataDependent, and print one warning per class. An identity column added inline with PRIMARY KEY is exempt: the identity fills every row, and it is what id() generates for an existing table. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrate.ts | 38 ++++++++++--- .../appkit/src/database/tooling/migrations.ts | 53 ++++++++++++++++--- .../shared/src/cli/commands/db/migrate.ts | 7 +-- packages/shared/src/cli/commands/db/output.ts | 26 ++++++--- .../src/cli/commands/db/tooling-contract.ts | 2 + 5 files changed, 101 insertions(+), 25 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 39d22e928..bc18e6dd2 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -24,6 +24,7 @@ import { notYourBranch, resolveEnvBranch, takesWrites } from "./guard"; import { type HistoryLock, withHistoryLock } from "./history-lock"; import { breakingStatements, + dataDependentStatements, discardMigrationFiles, type GeneratedMigration, generateMigrationFiles, @@ -56,6 +57,8 @@ export interface MigrateReport { readonly adopted?: readonly string[]; /** Statements of the generated migration that break instances still running the previous release. */ readonly breaking?: readonly string[]; + /** Statements of the generated migration that may fail on rows the deploy branch has and a new branch does not. */ + readonly dataDependent?: readonly string[]; /** Why nothing was applied, when applying was skipped. */ readonly notApplied?: string; readonly typesFile: string; @@ -68,20 +71,35 @@ export interface MigrateOptions { type ApplyOutcome = Pick; +/** What a generated migration's statements warn about; either list may be empty. */ +type MigrationWarnings = Required< + Pick +>; + +function migrationWarnings( + generated: GeneratedMigration | null, +): MigrationWarnings { + const statements = generated?.statements ?? []; + return { + breaking: breakingStatements(statements), + dataDependent: dataDependentStatements(statements), + }; +} + /** * The run wrote a migration and then failed before applying it. The file * stays for the next run, which generates nothing new, so this is the only - * run that can report what the migration breaks. + * run that can warn about the migration. */ -class UnappliedMigrationError extends Error { +class UnappliedMigrationError extends Error implements MigrationWarnings { readonly generated: GeneratedMigration; - /** Statements of the kept migration that break instances still running the previous release. */ readonly breaking: readonly string[]; + readonly dataDependent: readonly string[]; constructor( root: string, generated: GeneratedMigration, - breaking: readonly string[], + warnings: MigrationWarnings, cause: unknown, ) { super( @@ -90,7 +108,8 @@ class UnappliedMigrationError extends Error { ); this.name = "UnappliedMigrationError"; this.generated = generated; - this.breaking = breaking; + this.breaking = warnings.breaking; + this.dataDependent = warnings.dataDependent; } } @@ -154,7 +173,7 @@ async function migrateHolding( schema, interactive: options.interactive, }); - const breaking = breakingStatements(generated?.statements ?? []); + const warnings = migrationWarnings(generated); // The types follow schema.ts alone, so they are current even if applying fails. const typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); @@ -179,11 +198,14 @@ async function migrateHolding( { cause: error }, ); } - throw new UnappliedMigrationError(ctx.root, generated, breaking, error); + throw new UnappliedMigrationError(ctx.root, generated, warnings, error); } return { generated, - ...(breaking.length > 0 ? { breaking } : {}), + ...(warnings.breaking.length > 0 ? { breaking: warnings.breaking } : {}), + ...(warnings.dataDependent.length > 0 + ? { dataDependent: warnings.dataDependent } + : {}), ...outcome, typesFile, }; diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 9302c3309..36a56c2de 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -254,8 +254,12 @@ async function loadDrizzleKit(): Promise { } } -const matches = (pattern: RegExp) => (statement: string) => - pattern.test(statement); +type StatementPredicate = (statement: string) => boolean; + +const matches = + (pattern: RegExp): StatementPredicate => + (statement) => + pattern.test(statement); /** A new column nothing fills: old instances insert without it, and existing rows have no value for it. */ function addsRequiredColumn(statement: string): boolean { @@ -266,7 +270,16 @@ function addsRequiredColumn(statement: string): boolean { ); } -const BREAKS_PREVIOUS_RELEASE: ReadonlyArray<(statement: string) => boolean> = [ +/** A constraint declared on the new column itself. An identity fills every row with a distinct value, so its key holds. */ +function addsConstrainedColumn(statement: string): boolean { + return ( + /\bADD COLUMN\b/i.test(statement) && + /\b(UNIQUE|PRIMARY KEY|CHECK|REFERENCES)\b/i.test(statement) && + !/\bAS IDENTITY\b/i.test(statement) + ); +} + +const BREAKS_PREVIOUS_RELEASE: readonly StatementPredicate[] = [ matches(/^DROP (TABLE|VIEW|MATERIALIZED VIEW|TYPE|SEQUENCE|SCHEMA)\b/i), matches(/\bDROP COLUMN\b/i), matches(/\bRENAME\b/i), @@ -275,15 +288,43 @@ const BREAKS_PREVIOUS_RELEASE: ReadonlyArray<(statement: string) => boolean> = [ addsRequiredColumn, ]; +/** Postgres checks each of these against the rows already in the table, so a table with no rows never fails them. */ +const MAY_FAIL_ON_EXISTING_ROWS: readonly StatementPredicate[] = [ + matches(/\bSET NOT NULL\b/i), + matches(/\bSET DATA TYPE\b/i), + addsRequiredColumn, + matches(/\bADD CONSTRAINT\b/i), + addsConstrainedColumn, + matches(/^CREATE UNIQUE INDEX\b/i), +]; + +function statementsWhere( + predicates: readonly StatementPredicate[], + statements: readonly string[], +): string[] { + return statements.filter((statement) => + predicates.some((applies) => applies(statement.trimStart())), + ); +} + /** * Statements that break instances still running the previous release. Apps * keeps them serving while the new instance migrates on start, and a code * rollback cannot undo a migration. */ export function breakingStatements(statements: readonly string[]): string[] { - return statements.filter((statement) => - BREAKS_PREVIOUS_RELEASE.some((breaks) => breaks(statement.trimStart())), - ); + return statementsWhere(BREAKS_PREVIOUS_RELEASE, statements); +} + +/** + * Statements whose success depends on the rows already in the table. A new + * dev branch has none, so they pass there and can fail on the deploy branch. + * A statement can be in this class and in breakingStatements. + */ +export function dataDependentStatements( + statements: readonly string[], +): string[] { + return statementsWhere(MAY_FAIL_ON_EXISTING_ROWS, statements); } /** Replace a file through a rename, so a crash never leaves it half written. */ diff --git a/packages/shared/src/cli/commands/db/migrate.ts b/packages/shared/src/cli/commands/db/migrate.ts index a7f419e67..5ed58034a 100644 --- a/packages/shared/src/cli/commands/db/migrate.ts +++ b/packages/shared/src/cli/commands/db/migrate.ts @@ -5,7 +5,7 @@ import { fail, isInteractive, printMigrateReport, - warnBreaking, + warnMigration, } from "./output"; import type { UnappliedMigration } from "./tooling-contract"; @@ -13,7 +13,8 @@ import type { UnappliedMigration } from "./tooling-contract"; function unappliedMigration(error: unknown): UnappliedMigration | null { const candidate = error as Partial | null; return typeof candidate?.generated?.tag === "string" && - Array.isArray(candidate.breaking) + Array.isArray(candidate.breaking) && + Array.isArray(candidate.dataDependent) ? (candidate as UnappliedMigration) : null; } @@ -28,7 +29,7 @@ async function runDbMigrate(): Promise { } catch (error) { fail(error); const kept = unappliedMigration(error); - if (kept) warnBreaking(kept.generated.tag, kept.breaking); + if (kept) warnMigration(kept.generated.tag, kept); } } diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index b33a2c6d5..069e24f1a 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -42,13 +42,23 @@ export function fail(error: unknown): void { process.exitCode = 1; } -/** Statements of a written migration that break instances still running the previous release. */ -export function warnBreaking(tag: string, breaking: readonly string[]): void { - if (breaking.length === 0) return; - warn( - `${tag} breaks instances still running the previous release, which keep serving while the new one migrates on start: ${breaking.join(" ")} ` + - "Deploy code that works with both the old and the new schema first, then this change in a later deploy.", - ); +/** What a written migration's statements warn about; an absent list means none. */ +type MigrationWarnings = Pick; + +/** One warning per class of statement in a written migration. */ +export function warnMigration(tag: string, warnings: MigrationWarnings): void { + if (warnings.breaking?.length) { + warn( + `${tag} breaks instances still running the previous release, which keep serving while the new one migrates on start: ${warnings.breaking.join(" ")} ` + + "Deploy code that works with both the old and the new schema first, then this change in a later deploy.", + ); + } + if (warnings.dataDependent?.length) { + warn( + `${tag} may fail on rows the deploy branch has and a new branch does not: ${warnings.dataDependent.join(" ")} ` + + "Test the migration on a branch that has a copy of the deploy branch's data before you deploy.", + ); + } } export function printMigrateReport(report: MigrateReport): void { @@ -57,7 +67,7 @@ export function printMigrateReport(report: MigrateReport): void { ok( `Generated ${relative(report.generated.file)} (${count} statement${count === 1 ? "" : "s"})`, ); - warnBreaking(report.generated.tag, report.breaking ?? []); + warnMigration(report.generated.tag, report); } else { info("No schema changes since the last migration"); } diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index f74f91678..6a1e7597c 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -15,6 +15,7 @@ export interface MigrateReport { readonly applied: readonly string[]; readonly adopted?: readonly string[]; readonly breaking?: readonly string[]; + readonly dataDependent?: readonly string[]; readonly notApplied?: string; readonly typesFile: string; } @@ -26,6 +27,7 @@ export interface MigrateReport { export interface UnappliedMigration { readonly generated: GeneratedMigration; readonly breaking: readonly string[]; + readonly dataDependent: readonly string[]; } /** From aa5d364546a8cd5bb623259fa51af7cd41ef8f63 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:18:57 +0000 Subject: [PATCH 164/317] docs: describe the two warnings appkit db migrate prints Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 71127f4ed..5fc3e3490 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -136,6 +136,27 @@ committed snapshot. When they differ, it writes `shared/appkit-types/database.d.ts`, then applies pending migrations to the branch `.env` names. Commit the migrations with `schema.ts`. +### 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 keep serving 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. + `migrate` applies migrations only to your dev branch or to 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 From b1d982904cdd5590ccc3fa4be832ab6ba10837b3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:19:45 +0000 Subject: [PATCH 165/317] fix(appkit): migrate on start only as the app's own service principal decideMigrateOnStart replaces shouldMigrateOnStart with a pure decision: off without the flag, skipped with a reason when DATABRICKS_CLIENT_ID or DATABRICKS_CLIENT_SECRET is missing or PGUSER is not the app's client id, migrate otherwise. Databricks Apps sets PGUSER to the service principal's client id for a bound database, so a local start or `databricks apps run-local` with exported M2M credentials keeps the developer's PGUSER and no longer migrates as them. The lifecycle logs one warning with the reason when the flag is on but the start is skipped. The schema check takes the decision and words its advice by it: set the flag when it is off, read the startup warning when the start was skipped, commit a migration when the start migrated and the schema still differs. A deployed app bound to a branch whose id has the exact shape of a developer branch (dev--<6 hex>, at most 63 characters) or an agent session branch (session-<6 hex>-) fails its start with the branch name and the fix, instead of skipping silently; session-store and session-k3x9q2m7 do not match and migrate. The message no longer names a CLI command this layer does not ship. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/plugins/database/lifecycle.ts | 13 +++- .../src/plugins/database/migrate-on-start.ts | 70 ++++++++++++++----- .../src/plugins/database/schema-check.ts | 17 ++++- .../plugins/database/tests/lifecycle.test.ts | 1 + 4 files changed, 79 insertions(+), 22 deletions(-) diff --git a/packages/appkit/src/plugins/database/lifecycle.ts b/packages/appkit/src/plugins/database/lifecycle.ts index aff2abc08..7b4df7a95 100644 --- a/packages/appkit/src/plugins/database/lifecycle.ts +++ b/packages/appkit/src/plugins/database/lifecycle.ts @@ -23,7 +23,7 @@ import type { SqlTag, TransactionClient, } from "./entity-types"; -import { migrateOnStart, shouldMigrateOnStart } from "./migrate-on-start"; +import { decideMigrateOnStart, migrateOnStart } from "./migrate-on-start"; import { assertSchemaMatchesDatabase } from "./schema-check"; import { createMutationScope, type MutationScope } from "./scope"; import type { DatabaseHooks } from "./types"; @@ -191,7 +191,14 @@ export async function createDatabaseState( idle_in_transaction_session_timeout: IDLE_IN_TRANSACTION_TIMEOUT_MS, }); // A deployed app applies committed migrations as its own identity before the checks below. - if (shouldMigrateOnStart()) await migrateOnStart(pool, schema); + const migration = decideMigrateOnStart(); + if (migration.kind === "skipped") { + logger.warn( + "APPKIT_DB_MIGRATE_ON_START is true, but this process is not the deployed app, so it did not migrate. %s Databricks Apps sets DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET and PGUSER for the deployed app.", + migration.reason, + ); + } + if (migration.kind === "migrate") await migrateOnStart(pool, schema); const db = createDrizzleDb(pool, schema); const dataPath = createDrizzleDataPath(db, schema, { columnAccess: "trusted", @@ -208,7 +215,7 @@ export async function createDatabaseState( }); // Do not publish exports until an authenticated statement succeeds. await dataPath.raw`select 1`; - await assertSchemaMatchesDatabase(dataPath, schema); + await assertSchemaMatchesDatabase(dataPath, schema, migration); return { pool, exports, diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index 3173d89b8..230a2c5f2 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -20,23 +20,36 @@ import { createLogger } from "../../logging/logger"; const logger = createLogger("database"); -/** Branches `appkit db` creates for one developer or one agent session; only they migrate them. */ -const DEVELOPER_BRANCH = /^(dev-[a-z0-9-]+-[0-9a-f]{6}|session-[a-z0-9-]+)$/; +/** Whether this process applies the committed migrations when it starts. */ +export type MigrateOnStartDecision = + /** APPKIT_DB_MIGRATE_ON_START is not "true": a local start, or an app that never opted in. */ + | { readonly kind: "off" } + /** The flag is on, but this process does not run as the app's own service principal. */ + | { readonly kind: "skipped"; readonly reason: string } + | { readonly kind: "migrate" }; /** - * True when the app opts in with APPKIT_DB_MIGRATE_ON_START=true (app.yaml) - * and runs with service principal credentials, as Databricks Apps sets for - * every app. `.env` never carries the flag, so a local start does not migrate; - * `databricks apps run-local` reads app.yaml but sets no credentials. + * Migrate on start only when the app opted in with APPKIT_DB_MIGRATE_ON_START=true + * (app.yaml) and the process runs as the app's own service principal. Databricks + * Apps sets DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET and, for a bound + * database, PGUSER (the client id) for the deployed app. A local start, or + * `databricks apps run-local` with exported M2M credentials, has the developer's + * PGUSER from `.env`, and must not migrate as them. */ -export function shouldMigrateOnStart( +export function decideMigrateOnStart( env: NodeJS.ProcessEnv = process.env, -): boolean { - return ( - env.APPKIT_DB_MIGRATE_ON_START === "true" && - Boolean(env.DATABRICKS_CLIENT_ID) && - Boolean(env.DATABRICKS_CLIENT_SECRET) - ); +): MigrateOnStartDecision { + if (env.APPKIT_DB_MIGRATE_ON_START !== "true") return { kind: "off" }; + for (const name of ["DATABRICKS_CLIENT_ID", "DATABRICKS_CLIENT_SECRET"]) { + if (!env[name]) return { kind: "skipped", reason: `${name} is not set.` }; + } + if (env.PGUSER && env.PGUSER !== env.DATABRICKS_CLIENT_ID) { + return { + kind: "skipped", + reason: `PGUSER is "${env.PGUSER}", not the app's client id in DATABRICKS_CLIENT_ID.`, + }; + } + return { kind: "migrate" }; } /** The branch id in LAKEBASE_ENDPOINT (projects/

/branches//endpoints/). */ @@ -44,6 +57,27 @@ function endpointBranch(endpoint: string | undefined): string | undefined { return endpoint?.match(/\/branches\/([^/]+)\//)?.[1]; } +/** Lakebase branch ids are at most 63 characters. */ +const BRANCH_ID_MAX_LENGTH = 63; + +/** + * The exact shapes AppKit gives the branches of one developer + * (dev--<6 hex>) and of one agent session (session-<6 hex>-). Only + * they migrate those branches, so a deployed app bound to one is misconfigured. + */ +const DEVELOPMENT_BRANCH_SHAPES = { + "a developer": /^dev-[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{6}$/, + "an agent session": /^session-[0-9a-f]{6}-[a-z0-9]{1,48}$/, +}; + +/** Whose branch the id names, by its exact shape; undefined for any other id. */ +function developmentBranchOwner(branch: string): string | undefined { + if (branch.length > BRANCH_ID_MAX_LENGTH) return undefined; + return Object.entries(DEVELOPMENT_BRANCH_SHAPES).find(([, shape]) => + shape.test(branch), + )?.[0]; +} + /** * Apply pending committed migrations from /config/database/migrations as * the app's identity (see database/migrations/ownership.ts). No journal → @@ -57,12 +91,12 @@ export async function migrateOnStart( ): Promise { const folder = migrationsFolder(root); const branch = endpointBranch(env.LAKEBASE_ENDPOINT); - if (branch && DEVELOPER_BRANCH.test(branch)) { - logger.warn( - "Not migrating branch %s on start: it belongs to a developer or agent session, which migrates it with `appkit db migrate`.", - branch, + const owner = branch && developmentBranchOwner(branch); + if (owner) { + throw databaseSetupFailed( + `LAKEBASE_ENDPOINT points at branch "${branch}", whose name has the shape of ${owner} branch, and a deployed app migrates only its deploy branch. ` + + "Bind the app to its deploy branch. If this is the deploy branch, rename it so it does not look like a dev or session branch.", ); - return; } if (!fs.existsSync(journalFile(folder))) { logger.info("No committed migrations at %s; nothing to apply", folder); diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index bf206c427..a5d40316f 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -1,6 +1,7 @@ import { databaseSetupFailed } from "../../database/errors"; import type { DataPath } from "../../database/runtime"; import type { Schema } from "../../database/schema-builder"; +import type { MigrateOnStartDecision } from "./migrate-on-start"; interface CatalogColumn { readonly table_name: string; @@ -8,16 +9,30 @@ interface CatalogColumn { readonly relation_kind: string; } +/** How the missing tables and columns get created, given what this start did about migrations. */ +function migrationAdvice(migration: MigrateOnStartDecision): string { + switch (migration.kind) { + case "off": + return "Create them, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start."; + case "skipped": + return "APPKIT_DB_MIGRATE_ON_START is true, but this process did not migrate on start. The warning logged before this error says why."; + case "migrate": + return "The committed migrations under config/database/migrations were applied on start and leave them missing. Commit a migration that creates them and deploy again."; + } +} + /** * Confirm every declared table and column exists before routes are published. * Even after a deployed app applies its migrations, drift would surface on each * request as an undefined-table or undefined-column failure, so check up front. * pg_catalog is read rather than information_schema, which hides objects the * role cannot access and would report a privilege gap as a missing column. + * `migration` says what this start did about migrations, so the advice fits. */ export async function assertSchemaMatchesDatabase( dataPath: DataPath, schema: Schema, + migration: MigrateOnStartDecision, ): Promise { const tables = Object.values(schema.$tables); if (tables.length === 0) return; @@ -76,7 +91,7 @@ export async function assertSchemaMatchesDatabase( } if (problems.length > 0) { throw databaseSetupFailed( - `the declared schema does not match the database: ${problems.join("; ")}. Create them, or commit migrations under config/database/migrations and set APPKIT_DB_MIGRATE_ON_START=true in app.yaml so the deployed app applies them on start.`, + `the declared schema does not match the database: ${problems.join("; ")}. ${migrationAdvice(migration)}`, ); } } diff --git a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts index b0efd37b1..54333161b 100644 --- a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts +++ b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts @@ -221,6 +221,7 @@ describe("createDatabaseState", () => { expect(mocks.assertSchemaMatchesDatabase).toHaveBeenCalledWith( path, schema, + { kind: "off" }, ); expect(error).toBe(drift); expect(error.message).toContain("table public.tags does not exist"); From 7ff0d594b074b42612ee54743aa007175be111a0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:21:17 +0000 Subject: [PATCH 166/317] fix(appkit): say old instances can still serve during a migrate on start Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 2 +- packages/shared/src/cli/commands/db/migrate.test.ts | 4 ++-- packages/shared/src/cli/commands/db/output.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 5fc3e3490..ca0ca6dfa 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -144,7 +144,7 @@ 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 keep serving while the new one +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. diff --git a/packages/shared/src/cli/commands/db/migrate.test.ts b/packages/shared/src/cli/commands/db/migrate.test.ts index 8d5621896..440f1426f 100644 --- a/packages/shared/src/cli/commands/db/migrate.test.ts +++ b/packages/shared/src/cli/commands/db/migrate.test.ts @@ -131,7 +131,7 @@ describe("appkit db migrate", () => { await dbCommand.parseAsync(["migrate"], { from: "user" }); expect(output(log)).toContain( - `0002_migration breaks instances still running the previous release, which keep serving while the new one migrates on start: ${drop} Deploy code that works with both the old and the new schema first, then this change in a later deploy.`, + `0002_migration breaks instances still running the previous release, which can still serve while the new one migrates on start: ${drop} Deploy code that works with both the old and the new schema first, then this change in a later deploy.`, ); expect(output(log)).not.toContain("may fail on rows"); }); @@ -207,7 +207,7 @@ describe("appkit db migrate", () => { "Wrote config/database/migrations/0002_migration.sql, but did not apply it: 403 Forbidden", ); expect(output(log)).toContain( - `0002_migration breaks instances still running the previous release, which keep serving while the new one migrates on start: ${setNotNull} Deploy code that works with both the old and the new schema first, then this change in a later deploy.`, + `0002_migration breaks instances still running the previous release, which can still serve while the new one migrates on start: ${setNotNull} Deploy code that works with both the old and the new schema first, then this change in a later deploy.`, ); expect(output(log)).toContain( `0002_migration may fail on rows the deploy branch has and a new branch does not: ${setNotNull} Test the migration on a branch that has a copy of the deploy branch's data before you deploy.`, diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 069e24f1a..9ece2108f 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -49,7 +49,7 @@ type MigrationWarnings = Pick; export function warnMigration(tag: string, warnings: MigrationWarnings): void { if (warnings.breaking?.length) { warn( - `${tag} breaks instances still running the previous release, which keep serving while the new one migrates on start: ${warnings.breaking.join(" ")} ` + + `${tag} breaks instances still running the previous release, which can still serve while the new one migrates on start: ${warnings.breaking.join(" ")} ` + "Deploy code that works with both the old and the new schema first, then this change in a later deploy.", ); } From c269a03d8ec8b35544412bfb3315991d0564e42c Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:27:56 +0000 Subject: [PATCH 167/317] test(appkit): a deploy start refuses a stranded migration next to unknown rows as diverged When the branch deployed first carries the newer timestamp, main's own migration is stranded instead of pending, and today's stranded message tells the developer to delete and regenerate it. With rows this checkout lacks, the right way back is the diverged runbook. The same history keeps the stranded refusal without the option, as the CLI callers expect. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/migrations/tests/apply.test.ts | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 521968a05..777687299 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -600,6 +600,65 @@ describe("applyPendingMigrations", () => { expect(state.recorded).toHaveLength(2); }); + /** Main's new migration is older than the one a branch deployed first, so it is stranded, not pending. */ + 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 regenerate runbook", 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\. .*Delete its \.sql file, snapshot and journal entry, generate the migration again from schema\.ts/, + ); + }); + test("recorded migrations this checkout lacks with nothing pending (a code rollback) only warn", async () => { const folder = twoMigrations(); const warn = vi From 9a8fc903e96aa771269a3c5fd2473a5b0469f52a Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:31:20 +0000 Subject: [PATCH 168/317] fix(appkit): a deploy start refuses a stranded migration next to unknown rows as diverged Under onDrift "refuse", a history with stranded entries and recorded rows this checkout lacks is a divergence, not a merge mishap: the branch that deployed first carried the newer timestamp, so main's own migration lands behind it. The stranded message would tell the developer to delete and regenerate that migration, which is the wrong way back. The diverged refusal now covers it, with the same runbook: deploy a commit whose journal has the recorded migrations, or merge them into main unchanged first. Without the option the stranded refusal stays, so CLI callers see no change. The diverged refusal's tag list is renamed from pending to unrecorded, since it names every committed migration the database never recorded, stranded or pending, oldest first. Nothing outside apply.ts read the field. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 44 ++++++++++++------- .../database/migrations/tests/apply.test.ts | 2 +- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 3adce16be..7fec747e3 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -32,11 +32,12 @@ const logger = createLogger("database"); /** * What to do when the recorded history drifted from the committed one: a - * recorded migration whose file changed since, or pending migrations next to - * recorded ones this checkout lacks. "warn" logs and applies what is pending, - * so a developer can rework their own unapplied migration. "refuse" throws - * MigrationHistoryError before applying anything, as a deploy start must, - * since the deploy branch only ever runs merged files as they were merged. + * recorded migration whose file changed since, or committed migrations the + * database never recorded next to rows this checkout lacks. "warn" logs and + * applies what is pending, so a developer can rework their own unapplied + * migration. "refuse" throws MigrationHistoryError before applying anything, + * as a deploy start must, since the deploy branch only ever runs merged files + * as they were merged. */ type DriftPolicy = "warn" | "refuse"; @@ -176,12 +177,13 @@ type HistoryRefusal = /** Recorded migrations whose committed file changed since (onDrift "refuse"). */ | { readonly edited: readonly string[] } /** - * Committed migrations still pending while the database recorded migrations - * this checkout lacks (onDrift "refuse"): the two histories diverged. + * Committed migrations never recorded, pending or stranded, while the + * database recorded migrations this checkout lacks (onDrift "refuse"): the + * two histories diverged. */ | { readonly diverged: { - readonly pending: readonly string[]; + readonly unrecorded: readonly string[]; readonly unknown: readonly RecordedMigration[]; }; }; @@ -253,9 +255,9 @@ function editedMessage(schemaName: string, edited: readonly string[]): string { function divergedMessage( schemaName: string, { - pending, + unrecorded, unknown, - }: { pending: readonly string[]; unknown: readonly RecordedMigration[] }, + }: { unrecorded: readonly string[]; unknown: readonly RecordedMigration[] }, ): string { const created = unknown .map((row) => @@ -266,7 +268,7 @@ function divergedMessage( .join(", "); return ( `Schema "${schemaName}" recorded ${unknown.length} migration${unknown.length === 1 ? "" : "s"} this checkout does not have (created ${created}), ` + - `and ${pending.join(", ")} ${pending.length === 1 ? "is" : "are"} committed here but not applied. ` + + `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." @@ -482,7 +484,11 @@ function historyRefusal( ): HistoryRefusal | undefined { const ambiguous = history.ambiguous[0]; if (ambiguous) return { ambiguous }; + // Next to rows this checkout lacks, a stranded entry means a branch deployed + // first, so the way back is the diverged runbook, not regenerating it. + const diverged = onDrift === "refuse" && history.unknown.length > 0; 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()}`; @@ -490,14 +496,20 @@ function historyRefusal( } if (onDrift === "warn") return undefined; if (history.edited.length > 0) return { edited: tags(history.edited) }; - if (history.pending.length > 0 && history.unknown.length > 0) { - return { - diverged: { pending: tags(history.pending), unknown: history.unknown }, - }; - } + if (history.pending.length > 0 && diverged) return divergence(history); return undefined; } +/** Every committed migration the database never recorded, oldest first, next to the rows it has that this checkout lacks. */ +function divergence(history: MigrationHistory): HistoryRefusal { + return { + diverged: { + unrecorded: tags([...history.stranded, ...history.pending]), + unknown: history.unknown, + }, + }; +} + /** * 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 diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 777687299..6a009aa88 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -583,7 +583,7 @@ describe("applyPendingMigrations", () => { expect(error).toMatchObject({ refusal: { diverged: { - pending: ["0001_migration"], + unrecorded: ["0001_migration"], unknown: [ { hash: "from-a-branch-deployed-early", createdAt: 1500 }, ], From 91777028262bd250737812815542e842d004a1ca Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:41:39 +0000 Subject: [PATCH 169/317] fix(appkit): decide init's schema start from the branch itself, not a .env marker APPKIT_DB_NEW_BRANCH recorded in one checkout's .env that init forked a branch and had not finished its first start. It was checkout-local while the dev branch is per user, a stale one could drop a developer's work without a prompt, and --schema none, migrate or introspect cleared it while keeping every copied row. It is gone. init now reads the branch: the app schema is absent, the fork's untouched copy (the service principal owns it), a copy handed to you whose rebuild stopped (you own it and its journal carries the appkit:fork-copy row), or your working branch. One function maps that state and the --schema request to the start. A copy is tagged, handed off and rebuilt without a prompt. A tagged copy is rebuilt on any rerun, from any checkout, without another hand-off. Your working branch is migrated, and an explicit clean of it asks first through a confirmation the caller supplies. --schema migrate or introspect on a copy hands it off, removes the tag, keeps the rows and reports where they came from. --schema none touches nothing. public is never handed off or tagged: a new fork is migrated and the service principal's tables that kept their rows are reported. Without schema.ts, introspect writes the files before the tag and the hand-off, so a refusal leaves the copy as the fork made it, and records nothing on a branch the rebuild drops right after. appkit db migrate, introspect and seed refuse a branch whose journal carries the tag. Covered end to end against Postgres 17 with the Lakebase roles modelled. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/index.ts | 2 + packages/appkit/src/database/tooling/init.ts | 317 ++++++++----- .../src/database/tooling/introspect/index.ts | 17 +- .../introspect/tests/introspect.test.ts | 37 ++ .../appkit/src/database/tooling/migrate.ts | 35 +- .../src/database/tooling/schema-state.ts | 196 ++++++++ packages/appkit/src/database/tooling/seed.ts | 6 + .../appkit/src/database/tooling/targets.ts | 7 - .../database/tooling/tests/clean-seed.test.ts | 39 +- .../database/tooling/tests/env-file.test.ts | 6 +- .../database/tooling/tests/init.pg.test.ts | 421 ++++++++++++++++++ .../src/database/tooling/tests/init.test.ts | 254 ++++++++--- .../database/tooling/tests/migrate.test.ts | 3 +- .../tooling/tests/schema-state.pg.test.ts | 147 ++++++ .../tooling/tests/schema-state.test.ts | 100 +++++ .../database/tooling/tests/targets.test.ts | 4 - 16 files changed, 1383 insertions(+), 208 deletions(-) create mode 100644 packages/appkit/src/database/tooling/schema-state.ts create mode 100644 packages/appkit/src/database/tooling/tests/init.pg.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts create mode 100644 packages/appkit/src/database/tooling/tests/schema-state.test.ts diff --git a/packages/appkit/src/database/tooling/index.ts b/packages/appkit/src/database/tooling/index.ts index f003c5774..d2f9bd6f8 100644 --- a/packages/appkit/src/database/tooling/index.ts +++ b/packages/appkit/src/database/tooling/index.ts @@ -14,9 +14,11 @@ export { } from "./clean"; export { createDbContext, type DbContext } from "./context"; export { + InitCancelledError, type InitOptions, type InitReport, type InitStart, + type KeptCopy, runInit, type SchemaStart, } from "./init"; diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index c922885e2..279460412 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -2,11 +2,12 @@ import fs from "node:fs"; import path from "node:path"; import dotenv from "dotenv"; +import type { PoolClient } from "pg"; import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; import { DEFAULT_SCHEMA_NAME } from "../schema-builder/define-schema"; import { type CleanReport, cleanHolding } from "./clean"; -import type { DbContext } from "./context"; +import { type DbContext, withBranchPool } from "./context"; import { ensureDrizzleKit, type RunCommand, @@ -48,6 +49,15 @@ import { 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, @@ -60,18 +70,27 @@ import { resourceId, } from "./targets"; -/** How init leaves the schema; "none" leaves it as the fork has it. */ -export type SchemaStart = "migrate" | "introspect" | "clean" | "none"; +export type { SchemaStart } from "./schema-state"; export interface InitOptions { /** Default: this checkout's session branch when .env points at it, else your dev branch. */ readonly mode?: BranchMode; /** - * Default: on a branch init forked, clean with schema.ts, else introspect - * followed by a rebuild from the migrations it wrote; on a reused branch, - * migrate with schema.ts, else introspect. + * Default, read from the branch: a schema that still holds the fork's copy + * is rebuilt from the committed migrations (introspect writes schema.ts + * first when there is none); your working branch is migrated with + * schema.ts, else introspected. */ readonly schema?: SchemaStart; + /** + * Asked before an explicit --schema clean drops a schema that may hold your + * work: your working branch, or public. A copy's rebuild never asks. Absent, + * the clean proceeds. + */ + 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. */ @@ -96,11 +115,26 @@ export type InitStart = | { readonly kind: "introspect"; readonly introspect: IntrospectReport; - /** On a branch init forked: the schema introspect read, rebuilt from the migrations it wrote. */ + /** On a fork's copy: the schema introspect read, rebuilt from the migrations it wrote. */ readonly rebuilt: Rebuild | null; } | ({ readonly kind: "clean" } & Rebuild); +/** Rows the fork copied into the app schema that this run left in place, and why. */ +export type KeptCopy = + /** You asked for --schema migrate or --schema introspect on a copy. */ + | { readonly reason: "requested"; readonly from: string | null } + /** In schema public, what other roles own stays with its rows; init never removes it. */ + | { readonly reason: "public"; readonly objects: readonly string[] }; + +/** You answered no to the confirmation an explicit clean asks for. */ +export class InitCancelledError extends Error { + constructor(message: string) { + super(message); + this.name = "InitCancelledError"; + } +} + export interface InitReport { readonly mode: BranchMode; readonly branch: string; @@ -120,6 +154,7 @@ export interface InitReport { * 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; @@ -206,8 +241,6 @@ interface BranchRequest { readonly envFile: string; /** The branch of this project the default databricks.yml target deploys to, which a new fork comes from. */ readonly deployBranch: string | null; - /** The branch .env marks as forked but not started; see LocalTarget.newBranch. */ - readonly newBranch: string | null; readonly onStep: (message: string) => void; } @@ -215,11 +248,6 @@ interface FoundBranch { readonly branch: LakebaseBranch; /** Forked by this run. */ readonly created: boolean; - /** - * Forked by init, in this run or in one that stopped before the schema - * start, so it still holds every row the fork copied. - */ - readonly fresh: boolean; readonly sourceBranch?: string; readonly session: string | null; } @@ -281,12 +309,7 @@ async function findOrCreateBranch( ); } onStep(`Using ${resourceId(branch.name)}`); - return { - branch, - created: false, - fresh: branch.name === request.newBranch, - session, - }; + return { branch, created: false, session }; }; const replaceGone = (name: string): void => { if (session === null) { @@ -327,14 +350,10 @@ async function findOrCreateBranch( throw new Error(`Project ${project} has no default branch to fork from.`); } // Written before the fork, so a run that stops during or after it leaves - // its rerun what it needs: the session id, to reuse instead of forking - // again, and the branch name, to still give the fork its first start. - updateEnvFile(request.envFile, { - ...(session !== null && session !== request.session - ? { APPKIT_DB_SESSION: session } - : {}), - APPKIT_DB_NEW_BRANCH: name, - }); + // its rerun the session id, to reuse instead of forking again. + if (session !== null && session !== request.session) { + updateEnvFile(request.envFile, { APPKIT_DB_SESSION: 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}`}`, ); @@ -348,15 +367,10 @@ async function findOrCreateBranch( return { branch: branch?.name ? branch : { name }, created: true, - fresh: true, sourceBranch: parent.name, session, }; } catch (error) { - // These refusals mean no fork happened; any other error may have left one. - if (isPermissionDenied(error) || isBranchLimit(error)) { - updateEnvFile(request.envFile, { APPKIT_DB_NEW_BRANCH: null }); - } 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\`.`, @@ -565,11 +579,13 @@ function readEnvValues(file: string): Record { /** * `appkit db init`: find or create your dev branch or this checkout's session * branch, ensure a read-write endpoint and your DATABRICKS_SUPERUSER role, - * point `.env` at the branch, hand the app schema the fork copied to you - * (except with `--schema none`), then start the schema. No prompts: every - * choice has a default. It refuses the project's default branch, protected - * branches and branches databricks.yml deploys to before changing anything, - * and never touches the deploy bundle. + * point `.env` at the branch, then start the schema as its state on the branch + * calls for (see planStart): a fork's copy is handed to you and rebuilt, your + * working branch is migrated, and `--schema none` touches neither. It asks + * nothing but the confirmation an explicit clean of your work needs. It + * refuses the project's default branch, protected branches and branches + * databricks.yml deploys to before changing anything, and never touches the + * deploy bundle. * 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. @@ -578,19 +594,26 @@ export async function runInit( ctx: DbContext, options: InitOptions = {}, ): Promise { - if (options.schema === "none") return initHolding(ctx, null, options); + const requested = options.schema; + if (requested === "none") return initHolding(ctx, null, options); // Before the lock, which creates config/database. - if (options.schema === "migrate" || options.schema === "clean") { - requireSchemaFile(ctx.root, options.schema); + if (requested === "migrate" || requested === "clean") { + requireSchemaFile(ctx.root, requested); } return withHistoryLock(ctx.root, "init", (lock) => - initHolding(ctx, lock, options), + initHolding(ctx, { lock, requested }, options), ); } +/** A start under the checkout's history lock; null for `--schema none`, which takes none and starts nothing. */ +interface LockedStart { + readonly lock: HistoryLock; + readonly requested: Exclude | undefined; +} + async function initHolding( ctx: DbContext, - lock: HistoryLock | null, + locked: LockedStart | null, options: InitOptions, ): Promise { const onStep = options.onStep ?? (() => undefined); @@ -607,7 +630,7 @@ async function initHolding( refuseSymlink(envFile); const hasSchema = hasSchemaFile(ctx.root); const schemaName = - hasSchema && options.schema !== "none" + hasSchema && locked ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) .$schemaName : DEFAULT_SCHEMA_NAME; @@ -638,17 +661,9 @@ async function initHolding( boundary: readDeployBoundary(ctx.root), envFile, deployBranch: deploy?.branch ?? null, - newBranch: local.newBranch, onStep, }); const { branch } = found; - // A branch init forked holds every row the fork copied until its first - // start. Without --schema, that start rebuilds the app schema from the - // migrations, so none of them stay; a reused branch keeps its data. - const rebuild = found.fresh && options.schema === undefined; - const startKind: SchemaStart = - options.schema ?? - (hasSchema ? (rebuild ? "clean" : "migrate") : "introspect"); const { endpoint, @@ -685,74 +700,7 @@ async function initHolding( updateEnvFile(envFile, values); const branchCtx: DbContext = { ...ctx, env: { ...ctx.env, ...values } }; - // --schema none leaves the schema as the fork has it, owner included. - const handedOff = - startKind === "none" - ? null - : await handOffAppSchema(branchCtx, { - branch: branch.name, - database, - schemaName, - developer: role, - roles, - onStep, - }); - - // Every start leaves the branch for `appkit db migrate` and `appkit db check`, - // which diff schema.ts with drizzle-kit, so every start except none installs it. - const installed = - startKind === "none" - ? null - : ensureDrizzleKit(ctx.root, options.runCommand ?? runCommand, onStep); - - // Without a lock (--schema none) the schema stays as the fork has it. - let start: InitStart = { kind: "none" }; - if (lock) { - const on = `on ${resourceId(branch.name)}`; - const rebuildSchema = async (): Promise => { - const why = rebuild - ? schemaName === "public" - ? ": a branch init forked starts without the rows it copied, as far as you own them; other roles' objects stay with theirs" - : ": a branch init forked starts without the rows it 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); - // Recreated from the committed migrations, so the startup check passes. - const migrate = await migrateHolding(branchCtx, lock, { - interactive, - generate: false, - }); - return { clean, migrate }; - }; - if (startKind === "migrate") { - onStep(`Migrating schema ${schemaName} ${on}`); - start = { - kind: "migrate", - migrate: await migrateHolding(branchCtx, lock, { interactive }), - }; - } else if (startKind === "introspect") { - onStep(`Writing schema.ts from schema ${schemaName} ${on}`); - const introspect = await introspectForInit(branchCtx, lock, { - interactive, - schemaName, - }); - start = { - kind: "introspect", - introspect, - rebuilt: rebuild ? await rebuildSchema() : null, - }; - } else if (startKind === "clean") { - start = { kind: "clean", ...(await rebuildSchema()) }; - } - } - // Its start done, the branch no longer awaits one. - if (found.fresh) updateEnvFile(envFile, { APPKIT_DB_NEW_BRANCH: null }); - - return { + const base = { mode, branch: branch.name, created: found.created, @@ -764,9 +712,136 @@ async function initHolding( database, user: identity.userName, role: { name: role.name, action }, - handedOff, envFile, + }; + // --schema none reads nothing from the branch and leaves the schema as the + // fork has it, owner included. + if (!locked) { + return { + ...base, + handedOff: null, + keptCopy: null, + installed: null, + start: { kind: "none" }, + }; + } + const { lock, requested } = locked; + + const state = await withBranchPool(branchCtx, (pool) => + readSchemaState(pool, schemaName), + ); + const plan = planStart(state, requested, hasSchema); + const on = `on ${resourceId(branch.name)}`; + if ( + plan.confirm && + options.confirmClean && + !(await options.confirmClean({ branch: branch.name, schemaName })) + ) { + throw new InitCancelledError( + `Cancelled. Schema ${schemaName} ${on} is as it was, and .env points at the branch.`, + ); + } + // Every start leaves the branch for `appkit db migrate` and `appkit db check`, + // which diff schema.ts with drizzle-kit, so every start installs it. + const installed = ensureDrizzleKit( + ctx.root, + options.runCommand ?? runCommand, + onStep, + ); + const onBranch = ( + work: (client: Pick) => Promise, + ) => withBranchPool(branchCtx, work); + + const introspect = (record: boolean) => { + onStep(`Writing schema.ts from schema ${schemaName} ${on}`); + return introspectForInit(branchCtx, lock, { + interactive, + schemaName, + record, + }); + }; + // A rebuild without schema.ts introspects first, while the copy is untouched: + // introspect only writes files then, so a refusal leaves the branch as the + // fork made it. Introspect reads the journal as history, so a tag an earlier + // run left on the copy goes first and comes back right before the hand-off. + let introspected: IntrospectReport | null = null; + if (plan.kind === "introspect" && plan.rebuild) { + if (plan.tag) await onBranch((client) => untagForkCopy(client, schemaName)); + introspected = await introspect(false); + } + + if (plan.tag) await onBranch((client) => tagForkCopy(client, schemaName)); + 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 why = + requested === undefined + ? ": 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); + // Recreated from the committed migrations, so the startup check passes. + const migrate = await migrateHolding(branchCtx, lock, { + interactive, + generate: false, + }); + return { clean, migrate }; + }; + 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.sourceBranch ?? branch.status?.source_branch ?? null, + ), installed, start, }; } + +/** What of the fork's copy this run left in place. */ +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/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 9444d5c41..4869ae566 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -25,6 +25,7 @@ import { type GeneratedMigration, generateMigrationFiles, } from "../migrations"; +import { forkCopyRefusal, isForkCopy } from "../schema-state"; import { resourceId } from "../targets"; import { readCatalog, readUnreadObjects } from "./catalog"; import { @@ -42,6 +43,12 @@ export interface IntrospectOptions { readonly schemaName?: string; /** Module the written schema.ts imports the builder from. Default "@databricks/appkit/beta". */ readonly importSource?: string; + /** + * false: write schema.ts and its migration without recording the migration + * on the branch, for init's rebuild, which drops the schema right after. + * Default true. + */ + readonly record?: boolean; } export interface IntrospectReport { @@ -213,8 +220,14 @@ export async function introspectHolding( ); } const branchId = resourceId(env.branch.name); + const record = options.record ?? true; return withBranchPool(ctx, async (pool) => { + if (await isForkCopy(pool, schemaName)) { + throw new IntrospectRefusedError( + `Refusing to introspect: ${forkCopyRefusal(env.branch.name, schemaName, "introspect")}`, + ); + } // 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 @@ -347,7 +360,9 @@ export async function introspectHolding( } await writeDatabaseTypes(schema, typesFile); // The database already holds what the migrations describe; recording is the last step. - recorded = [...unrecorded, ...(migration ? [migration.tag] : [])]; + recorded = record + ? [...unrecorded, ...(migration ? [migration.tag] : [])] + : []; if (recorded.length > 0) { await markMigrationsApplied(pool, migrationOptions, recorded); } diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index c95b41de3..09ab0ae11 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -78,6 +78,8 @@ const onProduction = { 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 }>; +/** The journal carries init's fork-copy tag. */ +let tagged: boolean; /** The row the branch records for the last committed migration. */ const lastCommitted = (root: string) => { const folder = path.join(root, MIGRATIONS); @@ -100,6 +102,7 @@ const pool = { }; return { rows: recorded.length > 0 ? [journal] : [] }; } + if (text.includes("where hash = $1")) return { rows: tagged ? [{}] : [] }; if (text.includes("select hash, created_at")) { return { rows: recorded.map(({ when, hash }) => ({ @@ -116,6 +119,7 @@ const pool = { beforeEach(() => { catalog = catalogResponder(); recorded = []; + tagged = false; resolveEnvBranch.mockReset().mockResolvedValue(onDevBranch); withBranchPool .mockReset() @@ -335,6 +339,39 @@ describe("runIntrospect", () => { 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("record: 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, + record: 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); diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 3212184bc..4c05981f8 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -28,6 +28,7 @@ import { type GeneratedMigration, generateMigrationFiles, } from "./migrations"; +import { forkCopyRefusal, isForkCopy } from "./schema-state"; /** Whether the checkout has a config/database/schema.ts yet. */ export function hasSchemaFile(root: string): boolean { @@ -104,25 +105,35 @@ class UnappliedMigrationError extends Error { } } -/** Why migrations must not be applied to the `.env` branch; undefined when they may. */ -async function applyBlocker(ctx: DbContext): Promise { - const env = await resolveEnvBranch(ctx); - if (!env) return NO_ENV_BRANCH; - if (takesWrites(env.kind)) return undefined; - return `${notYourBranch(env)}. Migrations are applied only to branches \`appkit db init\` created for you; the deployed app applies committed migrations to its own branch`; -} - /** Apply pending migrations to the `.env` branch, or say why they were not. */ async function applyToEnvBranch( ctx: DbContext, folder: string, schema: Schema, ): Promise { - const blocker = readJournal(folder) - ? await applyBlocker(ctx) - : "no migrations to apply — schema.ts declares no tables yet"; - if (blocker) return { applied: [], notApplied: blocker }; + const notApplied = (reason: string): ApplyOutcome => ({ + applied: [], + notApplied: reason, + }); + if (!readJournal(folder)) { + return notApplied( + "no migrations to apply — schema.ts declares no tables yet", + ); + } + const env = await resolveEnvBranch(ctx); + if (!env) return notApplied(NO_ENV_BRANCH); + if (!takesWrites(env.kind)) { + return notApplied( + `${notYourBranch(env)}. Migrations are applied only to branches \`appkit db init\` created for you; the deployed app applies committed migrations to its own branch`, + ); + } return withBranchPool(ctx, async (pool) => { + // A migration on top of the fork's copy would make its rows yours to keep. + if (await isForkCopy(pool, schema.$schemaName)) { + throw new Error( + `Did not apply: ${forkCopyRefusal(env.branch.name, schema.$schemaName, "migrate")}`, + ); + } // The deployed app refuses this case on start; refuse it here first. const leftInPublic = await detectTablesLeftInPublic( catalogSqlOf(pool), diff --git a/packages/appkit/src/database/tooling/schema-state.ts b/packages/appkit/src/database/tooling/schema-state.ts new file mode 100644 index 000000000..f2cc9de43 --- /dev/null +++ b/packages/appkit/src/database/tooling/schema-state.ts @@ -0,0 +1,196 @@ +import type { PoolClient } from "pg"; + +import { quoteIdentifier } from "../migrations/apply"; +import { schemaOwnership } from "../migrations/ownership"; +import { MIGRATIONS_TABLE } from "../migrations/paths"; +import { readKeptObjects } from "./clean"; +import { resourceId } from "./targets"; + +/** How init leaves the schema; "none" leaves it as the fork has it. */ +export type SchemaStart = "migrate" | "introspect" | "clean" | "none"; + +/** + * The journal row init writes into a fork's copy of the app schema before it + * takes the schema over. The clean drops it with the schema, so a rerun from + * any checkout reads from the branch itself whether a rebuild is still due. + */ +export const FORK_COPY_TAG = "appkit:fork-copy"; + +/** What the app schema on the branch is, read from the branch itself. */ +export type SchemaState = + /** Nothing copied and nothing built yet. */ + | { readonly kind: "absent" } + /** The fork's untouched copy: another role, the app's service principal, owns it. */ + | { readonly kind: "copy"; readonly owner: string } + /** Handed to you and still tagged: a rebuild stopped before its clean. */ + | { readonly kind: "handed-off-copy" } + /** Your working branch. */ + | { readonly kind: "yours" } + /** + * Schema public belongs to the database, never to an app, so it is never + * handed off or tagged. What other roles own in it stays with its rows. + */ + | { readonly kind: "public"; readonly kept: readonly string[] }; + +type QueryClient = Pick; + +const journalTable = (schemaName: string) => + `${quoteIdentifier(schemaName)}.${quoteIdentifier(MIGRATIONS_TABLE)}`; + +/** + * Whether an ordinary table stands at the journal's name. Anything else there + * is left alone: the migrator refuses it with its own message. + */ +async function hasJournalTable( + client: QueryClient, + schemaName: string, +): Promise { + const { rows } = await client.query( + `select 1 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 and c.relkind = 'r'`, + [schemaName, MIGRATIONS_TABLE], + ); + return rows.length > 0; +} + +/** Whether the branch's journal carries the fork-copy tag. */ +export async function isForkCopy( + client: QueryClient, + schemaName: string, +): Promise { + if (!(await hasJournalTable(client, schemaName))) return false; + const { rows } = await client.query( + `select 1 from ${journalTable(schemaName)} where hash = $1 limit 1`, + [FORK_COPY_TAG], + ); + return rows.length > 0; +} + +/** + * Tag the copied journal. On Lakebase your role can insert into the service + * principal's tables before the hand-off. Returns false when the schema has no + * journal to tag, which leaves the hand-off and the clean unmarked between them. + */ +export async function tagForkCopy( + client: QueryClient, + schemaName: string, +): Promise { + if (!(await hasJournalTable(client, schemaName))) return false; + const journal = journalTable(schemaName); + await client.query( + `insert into ${journal} (hash, created_at) + select $1, 0 where not exists (select 1 from ${journal} where hash = $1)`, + [FORK_COPY_TAG], + ); + return true; +} + +export async function untagForkCopy( + client: QueryClient, + schemaName: string, +): Promise { + if (!(await hasJournalTable(client, schemaName))) return; + await client.query( + `delete from ${journalTable(schemaName)} where hash = $1`, + [FORK_COPY_TAG], + ); +} + +/** Read the app schema's state as the connected developer. */ +export async function readSchemaState( + client: QueryClient, + schemaName: string, +): Promise { + if (schemaName === "public") { + return { kind: "public", kept: await readKeptObjects(client, "public") }; + } + const { owner, currentUser } = await schemaOwnership(client, schemaName); + if (owner === null) return { kind: "absent" }; + if (owner !== currentUser) return { kind: "copy", owner }; + return (await isForkCopy(client, schemaName)) + ? { kind: "handed-off-copy" } + : { kind: "yours" }; +} + +/** What init does with the schema, decided once from its state and the request. */ +export interface StartPlan { + readonly kind: Exclude; + /** Drop the app schema, then apply the committed migrations, so a copy's rows go. */ + readonly rebuild: boolean; + /** Tag the copied journal before the hand-off, so a rerun from any checkout finishes the rebuild. */ + readonly tag: boolean; + /** Delete the copy's owner on this branch, with its objects reassigned to you. */ + readonly handOff: boolean; + /** You asked to keep a copy's rows: the tag goes and the rows stay. */ + readonly keepsCopy: boolean; + /** An explicit clean of what may be your work asks first. */ + readonly confirm: boolean; +} + +const NOTHING_ELSE = { + rebuild: false, + tag: false, + handOff: false, + keepsCopy: false, + confirm: false, +} as const; + +/** + * Without a request, a copy is rebuilt and your working branch is migrated, + * each with schema.ts, else introspected. A copy's rows stay only on request. + * A rebuild of a copy needs no confirmation: `appkit db migrate` refuses a + * tagged branch, so none of your work can be on it. + */ +export function planStart( + state: SchemaState, + requested: Exclude | undefined, + hasSchema: boolean, +): StartPlan { + switch (state.kind) { + case "copy": + case "handed-off-copy": { + const untouched = state.kind === "copy"; + if (requested === "migrate" || requested === "introspect") { + return { + ...NOTHING_ELSE, + kind: requested, + handOff: untouched, + keepsCopy: true, + }; + } + if (!untouched && !hasSchema && requested === undefined) { + throw new Error( + "The rebuild of the app schema on your branch stopped before it finished, and this checkout has no config/database/schema.ts to rebuild from. Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", + ); + } + return { + ...NOTHING_ELSE, + kind: requested ?? (hasSchema ? "clean" : "introspect"), + rebuild: true, + tag: untouched, + handOff: untouched, + }; + } + case "absent": + case "yours": + case "public": { + const kind = requested ?? (hasSchema ? "migrate" : "introspect"); + return { + ...NOTHING_ELSE, + kind, + rebuild: kind === "clean", + confirm: kind === "clean" && state.kind !== "absent", + }; + } + } +} + +/** Why a command that writes on the branch refuses one that still holds a fork's copy. */ +export function forkCopyRefusal( + branch: string, + schemaName: string, + keep: "migrate" | "introspect", +): string { + return `${resourceId(branch)} still holds the rows the fork copied into schema "${schemaName}", and its rebuild did not finish. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema ${keep}\` to keep them.`; +} diff --git a/packages/appkit/src/database/tooling/seed.ts b/packages/appkit/src/database/tooling/seed.ts index 6deaa2953..510dd2c44 100644 --- a/packages/appkit/src/database/tooling/seed.ts +++ b/packages/appkit/src/database/tooling/seed.ts @@ -8,6 +8,7 @@ import { runInTransaction } from "./branch-sql"; import type { DbContext } from "./context"; import { writableEnvBranch } from "./guard"; import { hasSchemaFile } from "./migrate"; +import { forkCopyRefusal, isForkCopy } from "./schema-state"; export const SEED_FILE = "config/database/seed.sql"; @@ -39,6 +40,11 @@ export async function runSeed(ctx: DbContext): Promise { : `${quoteIdentifier(schemaName)}, public`; const sql = fs.readFileSync(file, "utf-8"); await runInTransaction(ctx, async (client) => { + if (await isForkCopy(client, schemaName)) { + throw new Error( + `Refusing to seed: ${forkCopyRefusal(branch.name, schemaName, "migrate")}`, + ); + } await client.query(`SET LOCAL search_path TO ${searchPath}`); // One simple-protocol query: the file may hold several statements. await client.query(sql); diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 7d8414cda..d36019021 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -62,12 +62,6 @@ export interface LocalTarget { readonly endpoint: string | null; readonly database: string | null; readonly session: string | null; - /** - * APPKIT_DB_NEW_BRANCH: a branch `appkit db init` forked whose schema it has - * not started yet, so it still holds every row the fork copied. init writes - * it before the fork and removes it when the start completes. - */ - readonly newBranch: string | null; } export function readLocalTarget(env: NodeJS.ProcessEnv): LocalTarget { @@ -82,7 +76,6 @@ export function readLocalTarget(env: NodeJS.ProcessEnv): LocalTarget { // Without a real endpoint PGDATABASE is a template placeholder too. database: endpoint ? env.PGDATABASE || null : null, session, - newBranch: parseResourceName(env.APPKIT_DB_NEW_BRANCH)?.branch ?? null, }; } diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index c3fd60ea2..ca3b57485 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -35,21 +35,31 @@ const schemaFile = (schemaName: string) => export const schema = defineSchema(({ table }) => ({ notes: table("notes", { id: id() }) }), { schemaName: ${JSON.stringify(schemaName)} });`; const DEPENDENTS = /pg_catalog\.pg_depend/; +/** The journal check and the tag read of isForkCopy. */ +const FORK_COPY = /c\.relkind = 'r'|where hash = \$1/; /** A pool whose one client records statements, can fail on one, and answers the dependents query. */ function recordingPool( - options: { failOn?: RegExp; dependents?: string[] } = {}, + options: { failOn?: RegExp; dependents?: string[]; forkCopy?: boolean } = {}, ) { const statements: string[] = []; const client = { released: undefined as { error: unknown } | undefined, async query(text: string) { - statements.push(DEPENDENTS.test(text) ? "" : text); + statements.push( + DEPENDENTS.test(text) + ? "" + : FORK_COPY.test(text) + ? "" + : text, + ); if (options.failOn?.test(text)) throw new Error("boom"); return { rows: DEPENDENTS.test(text) ? (options.dependents ?? []).map((label) => ({ label })) - : [], + : FORK_COPY.test(text) && options.forkCopy + ? [{}] + : [], }; }, release(error?: unknown) { @@ -234,12 +244,29 @@ describe("runSeed", () => { expect(writableEnvBranch).toHaveBeenCalledWith(expect.anything(), "seed"); expect(statements).toEqual([ "begin", + "", 'SET LOCAL search_path TO "app", public', sql, "commit", ]); }); + test("refuses a branch that still holds a fork's copy, before running the file", async () => { + const root = tempApp({ [SEED_FILE]: "insert into notes default values;" }); + writableEnvBranch.mockResolvedValue(devBranch); + const { statements } = recordingPool({ forkCopy: true }); + + await expect(runSeed(fakeContext({ root }))).rejects.toThrow( + 'Refusing to seed: 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 migrate` to keep them.', + ); + expect(statements).toEqual([ + "begin", + "", + "", + "rollback", + ]); + }); + test.each([ ["sales", 'SET LOCAL search_path TO "sales", public'], ["public", "SET LOCAL search_path TO public"], @@ -255,7 +282,11 @@ describe("runSeed", () => { await runSeed(fakeContext({ root })); - expect(statements.slice(0, 2)).toEqual(["begin", searchPath]); + expect(statements.slice(0, 3)).toEqual([ + "begin", + "", + searchPath, + ]); }, ); diff --git a/packages/appkit/src/database/tooling/tests/env-file.test.ts b/packages/appkit/src/database/tooling/tests/env-file.test.ts index 7abe3fe10..925ff387b 100644 --- a/packages/appkit/src/database/tooling/tests/env-file.test.ts +++ b/packages/appkit/src/database/tooling/tests/env-file.test.ts @@ -161,14 +161,14 @@ describe("updateEnvFile", () => { const root = tempApp({ ".env": [ "KEEP=1", - "APPKIT_DB_NEW_BRANCH=projects/p/branches/dev-a", + "APPKIT_DB_SESSION=k2x9q0ab", "PGHOST=h", - "APPKIT_DB_NEW_BRANCH=stale", + "APPKIT_DB_SESSION=stale", ].join("\n"), }); const file = path.join(root, ".env"); - updateEnvFile(file, { APPKIT_DB_NEW_BRANCH: null, MISSING: null }); + updateEnvFile(file, { APPKIT_DB_SESSION: null, MISSING: null }); expect(fs.readFileSync(file, "utf-8")).toBe("KEEP=1\nPGHOST=h\n"); }); diff --git a/packages/appkit/src/database/tooling/tests/init.pg.test.ts b/packages/appkit/src/database/tooling/tests/init.pg.test.ts new file mode 100644 index 000000000..af23e115e --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/init.pg.test.ts @@ -0,0 +1,421 @@ +import { randomUUID } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; + +import { Pool } from "pg"; +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + test, + vi, +} from "vitest"; + +const { withBranchPool } = vi.hoisted(() => ({ withBranchPool: vi.fn() })); + +vi.mock("../context", async (importOriginal) => ({ + ...(await importOriginal()), + withBranchPool, +})); + +import { loadDefaultDatabaseSchema } from "../../../plugins/database/load-schema"; +import { applyPendingMigrations } from "../../migrations/apply"; +import { migrationsFolder } from "../../migrations/paths"; +import { hashOf } from "../../migrations/tests/fixtures"; +import type { DbContext } from "../context"; +import { withHistoryLock } from "../history-lock"; +import { type InitOptions, runInit } from "../init"; +import { IntrospectRefusedError, runIntrospect } from "../introspect"; +import type { LakebaseApi } from "../lakebase-api"; +import { runMigrate } from "../migrate"; +import { generateMigrationFiles } from "../migrations"; +import { devBranchId } from "../naming"; +import { FORK_COPY_TAG } from "../schema-state"; +import { runSeed, SEED_FILE } from "../seed"; +import { + cleanupTempApps, + databricksYml, + FakeLakebase, + fakeContext, + tempApp, +} from "./fakes"; + +// init end to end: the Lakebase API is the fake, every SQL step is real. The +// test database models a fork of the deploy branch: the app's service +// principal owns the app schema, and you connect as a role that inherits +// pg_read_all_data and pg_write_all_data, as a member of DATABRICKS_SUPERUSER +// does. APPKIT_TEST_PG_URL is a superuser URL that may create databases and +// roles, e.g. postgres://localhost:5432/postgres +const url = process.env.APPKIT_TEST_PG_URL; + +const USER = "alice@example.com"; +const P = "projects/p"; +const PRODUCTION = `${P}/branches/production`; +const DEV = `${P}/branches/${devBranchId(USER)}`; +const builder = path.resolve( + import.meta.dirname, + "../../schema-builder/index.ts", +); + +function schemaSource(schemaName: string, table: string): string { + return `import { defineSchema, id, text } from ${JSON.stringify(builder)}; +export const schema = defineSchema(({ table }) => ({ ${table}: table(${JSON.stringify(table)}, { id: id(), body: text() }) }), { schemaName: ${JSON.stringify(schemaName)} }); +`; +} + +describe.skipIf(!url)("runInit against Postgres", () => { + const suffix = randomUUID().slice(0, 8); + const database = `appkit_init_${suffix}`; + /** The app's service principal, as the Postgres role a fork copies. */ + const sp = `appkit_sp_${suffix}`; + const superuser = `appkit_dbx_${suffix}`; + const dev = `appkit_dev_${suffix}`; + const app = `app_${suffix}`; + let cluster: Pool; + let admin: Pool; + let asSp: Pool; + let asDev: Pool; + /** An app whose schema.ts declares `app`, with its migration generated. */ + let root: string; + /** An app whose schema.ts declares public. */ + let publicRoot: string; + let lakebase: FakeLakebase; + let api: LakebaseApi; + + const inDatabase = (role: string, password: string) => { + const next = new URL(url as string); + next.username = role; + next.password = password; + next.pathname = `/${database}`; + return next.toString(); + }; + const folder = (appRoot: string) => migrationsFolder(appRoot); + const rows = async (table: string) => + (await admin.query<{ body: string }>(`select body from ${table}`)).rows; + const journal = async (schema: string) => + ( + await admin.query<{ hash: string }>( + `select hash from "${schema}".__drizzle_migrations order by id`, + ) + ).rows.map((row) => row.hash); + const ownerOf = async (schema: string) => + ( + await admin.query<{ owner: string }>( + `select pg_get_userbyid(nspowner) as owner from pg_namespace where nspname = $1`, + [schema], + ) + ).rows[0]?.owner; + + async function generate(appRoot: string) { + const schema = await loadDefaultDatabaseSchema(appRoot, { + showImportError: true, + }); + await withHistoryLock(appRoot, "migrate", (lock) => + generateMigrationFiles(lock, { schema, interactive: false }), + ); + } + + /** The deploy branch as its service principal left it: migrated, with a row. */ + async function deployed(appRoot: string, schema: string, table: string) { + await applyPendingMigrations(asSp, { + migrationsFolder: folder(appRoot), + schemaName: schema, + }); + await asSp.query(`insert into ${table} (body) values ('copied')`); + } + + /** A project whose default branch is production; the fork copies its roles. */ + function project(): FakeLakebase { + const fake = new FakeLakebase(); + fake.addBranch(PRODUCTION, { default: true }); + fake.addDatabase(PRODUCTION, "databricks-postgres", database); + fake.addRole(PRODUCTION, "alice", USER, ["DATABRICKS_SUPERUSER"]); + fake.addRole(PRODUCTION, `dbrx-apps-${sp}`, sp); + return fake; + } + + /** Lakebase's delete-role with reassign, as Postgres does it. */ + function apiWithRealHandOff(fake: FakeLakebase): LakebaseApi { + const real = fake.api(); + const deleteRole = real.deleteRole.bind(real); + real.deleteRole = async (role, options) => { + await admin.query(`reassign owned by "${sp}" to "${dev}"`); + await deleteRole(role, options); + }; + return real; + } + + /** Your dev branch exists, with your role on it and the service principal's copy gone. */ + function existingDev(fake: FakeLakebase) { + fake.addBranch(DEV, { source_branch: PRODUCTION }); + fake.addRole(DEV, "alice", USER, ["DATABRICKS_SUPERUSER"]); + } + + function context(appRoot: string, env: Record = {}) { + const dotenv = { + DATABRICKS_CONFIG_PROFILE: "DEFAULT", + PGHOST: "primary.production.example.com", + PGDATABASE: database, + LAKEBASE_ENDPOINT: `${PRODUCTION}/endpoints/primary`, + ...env, + }; + fs.writeFileSync( + path.join(appRoot, ".env"), + `${Object.entries(dotenv) + .map(([key, value]) => `${key}=${value}`) + .join("\n")}\n`, + ); + return fakeContext({ root: appRoot, env: dotenv, userName: USER, api }); + } + + /** A context on your dev branch, as init leaves .env. */ + const onDev = (appRoot: string) => + context(appRoot, { + PGHOST: `primary.${devBranchId(USER)}.example.com`, + LAKEBASE_ENDPOINT: `${DEV}/endpoints/primary`, + PGUSER: USER, + }); + + async function init(ctx: DbContext, options: InitOptions = {}) { + const steps: string[] = []; + const report = await runInit(ctx, { + ...options, + onStep: (step) => steps.push(step), + }); + return { report, steps }; + } + + beforeAll(async () => { + cluster = new Pool({ connectionString: url, max: 1 }); + await cluster.query(`create database "${database}"`); + await cluster.query(` + create role "${sp}" login password 'appkit'; + create role "${superuser}" nologin; + grant pg_read_all_data, pg_write_all_data to "${superuser}"; + create role "${dev}" login password 'appkit'; + grant "${superuser}" to "${dev}"; + grant create on database "${database}" to "${sp}", "${dev}"; + `); + const adminUrl = new URL(url as string); + adminUrl.pathname = `/${database}`; + admin = new Pool({ connectionString: adminUrl.toString(), max: 1 }); + // What a deployed app on public needs too: CREATE on it, which Postgres 15 stopped granting to every role. + await admin.query(`grant create on schema public to "${sp}", "${dev}"`); + asSp = new Pool({ connectionString: inDatabase(sp, "appkit"), max: 1 }); + asDev = new Pool({ connectionString: inDatabase(dev, "appkit"), max: 2 }); + withBranchPool.mockImplementation( + (_ctx: unknown, fn: (pool: Pool) => Promise) => fn(asDev), + ); + + const bundle = { + "databricks.yml": databricksYml( + PRODUCTION, + `${PRODUCTION}/databases/databricks-postgres`, + ), + }; + root = tempApp({ + ...bundle, + "config/database/schema.ts": schemaSource(app, "notes"), + }); + publicRoot = tempApp({ + ...bundle, + "config/database/schema.ts": schemaSource("public", `notes_${suffix}`), + }); + await generate(root); + await generate(publicRoot); + }, 60_000); + + afterAll(async () => { + await asDev?.end(); + await asSp?.end(); + await admin?.end(); + await cluster.query(`drop database if exists "${database}" with (force)`); + await cluster.query(` + drop owned by "${sp}", "${dev}", "${superuser}"; + drop role if exists "${dev}"; + drop role if exists "${superuser}"; + drop role if exists "${sp}"; + `); + await cluster.end(); + cleanupTempApps(); + }); + + beforeEach(async () => { + await admin.query(`drop schema if exists "${app}" cascade`); + await admin.query(` + drop table if exists public."notes_${suffix}"; + drop table if exists public.__drizzle_migrations; + `); + lakebase = project(); + api = apiWithRealHandOff(lakebase); + }); + + test("a copy the service principal owns is handed to you and rebuilt: the copied rows go, the journal records the migrations", async () => { + await deployed(root, app, `"${app}".notes`); + + const { report, steps } = await init(context(root)); + + expect(report).toMatchObject({ + created: true, + sourceBranch: PRODUCTION, + handedOff: sp, + keptCopy: null, + start: { kind: "clean", migrate: { applied: ["0000_migration"] } }, + }); + expect(steps).toContain( + `Dropping schema ${app} on ${devBranchId(USER)}: the branch still holds the rows the fork copied, and the committed migrations recreate its tables`, + ); + expect(lakebase.calls).toContain( + `deleteRole ${DEV}/roles/dbrx-apps-${sp} → ${DEV}/roles/alice`, + ); + expect(await ownerOf(app)).toBe(dev); + expect(await rows(`"${app}".notes`)).toEqual([]); + expect(await journal(app)).toEqual([ + hashOf(folder(root), "0000_migration"), + ]); + }); + + test("a run that stopped after the hand-off is finished by the next init, which forks nothing", async () => { + await deployed(root, app, `"${app}".notes`); + // The earlier run tagged the journal and deleted the owner's role, then stopped. + await asDev.query( + `insert into "${app}".__drizzle_migrations (hash, created_at) values ($1, 0)`, + [FORK_COPY_TAG], + ); + await admin.query(`reassign owned by "${sp}" to "${dev}"`); + existingDev(lakebase); + + const { report } = await init(onDev(root)); + + expect(report).toMatchObject({ + created: false, + handedOff: null, + start: { kind: "clean", migrate: { applied: ["0000_migration"] } }, + }); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + expect(await rows(`"${app}".notes`)).toEqual([]); + expect(await journal(app)).toEqual([ + hashOf(folder(root), "0000_migration"), + ]); + }); + + test("your working branch keeps its rows: init migrates it", async () => { + await applyPendingMigrations(asDev, { + migrationsFolder: folder(root), + schemaName: app, + }); + await asDev.query(`insert into "${app}".notes (body) values ('mine')`); + existingDev(lakebase); + + const { report } = await init(onDev(root)); + + expect(report).toMatchObject({ + created: false, + handedOff: null, + keptCopy: null, + start: { kind: "migrate", migrate: { generated: null, applied: [] } }, + }); + expect(await rows(`"${app}".notes`)).toEqual([{ body: "mine" }]); + }); + + test("--schema none touches nothing, and the next plain init still rebuilds", async () => { + await deployed(root, app, `"${app}".notes`); + + const untouched = await init(context(root), { schema: "none" }); + expect(untouched.report).toMatchObject({ + created: true, + handedOff: null, + start: { kind: "none" }, + }); + expect(await ownerOf(app)).toBe(sp); + expect(await rows(`"${app}".notes`)).toEqual([{ body: "copied" }]); + + const rebuilt = await init(onDev(root)); + expect(rebuilt.report).toMatchObject({ + created: false, + handedOff: sp, + start: { kind: "clean" }, + }); + expect(await ownerOf(app)).toBe(dev); + expect(await rows(`"${app}".notes`)).toEqual([]); + }); + + test("--schema migrate on a copy keeps its rows, removes the tag and reports where they came from", async () => { + await deployed(root, app, `"${app}".notes`); + await asDev.query( + `insert into "${app}".__drizzle_migrations (hash, created_at) values ($1, 0)`, + [FORK_COPY_TAG], + ); + + const { report } = await init(context(root), { schema: "migrate" }); + + expect(report).toMatchObject({ + handedOff: sp, + keptCopy: { reason: "requested", from: PRODUCTION }, + start: { kind: "migrate", migrate: { generated: null, applied: [] } }, + }); + expect(await ownerOf(app)).toBe(dev); + expect(await rows(`"${app}".notes`)).toEqual([{ body: "copied" }]); + expect(await journal(app)).toEqual([ + hashOf(folder(root), "0000_migration"), + ]); + }); + + test("migrate, introspect and seed refuse a branch whose journal still carries the tag", async () => { + await deployed(root, app, `"${app}".notes`); + await asDev.query( + `insert into "${app}".__drizzle_migrations (hash, created_at) values ($1, 0)`, + [FORK_COPY_TAG], + ); + await admin.query(`reassign owned by "${sp}" to "${dev}"`); + existingDev(lakebase); + const ctx = onDev(root); + const refusal = `${devBranchId(USER)} 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`; + + await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( + `Did not apply: ${refusal} migrate\` to keep them.`, + ); + const introspect = runIntrospect(ctx, { interactive: false }); + await expect(introspect).rejects.toBeInstanceOf(IntrospectRefusedError); + await expect(introspect).rejects.toThrow( + `Refusing to introspect: ${refusal} introspect\` to keep them.`, + ); + fs.writeFileSync( + path.join(root, SEED_FILE), + `insert into notes (body) values ('seeded');`, + ); + try { + await expect(runSeed(ctx)).rejects.toThrow( + `Refusing to seed: ${refusal} migrate\` to keep them.`, + ); + } finally { + fs.rmSync(path.join(root, SEED_FILE)); + } + expect(await rows(`"${app}".notes`)).toEqual([{ body: "copied" }]); + }); + + test("schema public is migrated, never handed off, and the service principal's tables that kept their rows are reported", async () => { + const table = `public."notes_${suffix}"`; + await deployed(publicRoot, "public", table); + + const { report } = await init(context(publicRoot)); + + expect(report).toMatchObject({ + created: true, + handedOff: null, + start: { kind: "migrate", migrate: { generated: null, applied: [] } }, + }); + expect(report.keptCopy?.reason).toBe("public"); + expect( + report.keptCopy?.reason === "public" && report.keptCopy.objects, + ).toContain(`table notes_${suffix}`); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + expect(await rows(table)).toEqual([{ body: "copied" }]); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index a9ae30fac..c9a14c87f 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -19,7 +19,10 @@ vi.mock("../migrate", async (importOriginal) => ({ ...(await importOriginal()), migrateHolding, })); -vi.mock("../clean", () => ({ cleanHolding })); +vi.mock("../clean", async (importOriginal) => ({ + ...(await importOriginal()), + cleanHolding, +})); vi.mock("../introspect", async (importOriginal) => ({ ...(await importOriginal()), introspectHolding, @@ -27,7 +30,7 @@ vi.mock("../introspect", async (importOriginal) => ({ import type { DbContext } from "../context"; import type { HistoryLock } from "../history-lock"; -import { type InitOptions, runInit } from "../init"; +import { InitCancelledError, type InitOptions, runInit } from "../init"; import { IntrospectRefusedError } from "../introspect"; import { LakebaseApiError } from "../lakebase-api"; import { runMigrate } from "../migrate"; @@ -54,8 +57,15 @@ const migrateReport = { typesFile: "/app/shared/appkit-types/database.d.ts", }; -/** What the hand-off reads on the branch: the app schema's owner, what else that role owns here, and what blocks deleting it. */ +/** + * The branch as init reads it over SQL: the app schema's owner, whether its + * journal exists and carries the fork-copy tag, what other roles own in + * public, and what the hand-off reads about the owner. + */ let schemaOwner: string | null; +let journal: boolean; +let tagged: boolean; +let keptInPublic: string[]; let ownedOutside: string[]; let blockers: { database: string; count: number }[]; const queries: string[] = []; @@ -65,6 +75,15 @@ const pool = { if (text.includes("nspowner")) { return { rows: [{ owner: schemaOwner, current_user: USER }] }; } + if (text.includes("c.relkind = 'r'")) return { rows: journal ? [{}] : [] }; + if (text.includes("__drizzle_migrations")) { + if (text.startsWith("insert")) tagged = true; + else if (text.startsWith("delete")) tagged = false; + return { rows: text.startsWith("select") && tagged ? [{}] : [] }; + } + if (text.includes("pg_describe_object")) { + return { rows: keptInPublic.map((label) => ({ label })) }; + } if (text.includes("pg_identify_object")) { return { rows: ownedOutside.map((label) => ({ label })) }; } @@ -72,6 +91,14 @@ const pool = { throw new Error(`unexpected query ${text}`); }), }; +/** The writes to the journal's tag row, in order: "insert" tags, "delete" untags. */ +const tagWrites = () => + queries + .filter( + (text) => + text.includes("__drizzle_migrations") && !text.startsWith("select"), + ) + .map((text) => text.trim().split(" ")[0]); function project(): FakeLakebase { const lakebase = new FakeLakebase(); @@ -165,6 +192,9 @@ function conflict(name: string): LakebaseApiError { beforeEach(() => { schemaOwner = SP; + journal = true; + tagged = false; + keptInPublic = []; ownedOutside = []; blockers = []; queries.length = 0; @@ -221,10 +251,14 @@ describe("runInit — dev branch", () => { `Creating ${devBranchId(USER)} from production (the branch databricks.yml deploys to)`, `Pointing .env at ${devBranchId(USER)}, database databricks_postgres`, `Handing schema app in database databricks_postgres on ${devBranchId(USER)} to you: deleting this branch's copy of role ${SP}, which owns it, with its objects reassigned to you`, - `Dropping schema app on ${devBranchId(USER)}: a branch init forked starts without the rows it copied, and the committed migrations recreate its tables`, + `Dropping schema app on ${devBranchId(USER)}: the branch still holds the rows the fork copied, and the committed migrations recreate its tables`, ]); + // The copied journal is tagged before the hand-off, so a rerun from any checkout finishes the rebuild. + expect(tagWrites()).toEqual(["insert"]); + expect( + queries.indexOf(queries.find((text) => text.startsWith("insert")) ?? ""), + ).toBeLessThan(queries.findIndex((text) => text.includes("pg_shdepend"))); - // The marker that the branch awaits its first start is gone with the start. const written = envFile(ctx.root); expect(written).toEqual({ DATABRICKS_CONFIG_PROFILE: "DEFAULT", @@ -308,22 +342,30 @@ describe("runInit — dev branch", () => { expect(pool.query).not.toHaveBeenCalled(); }); - test("schema public is never handed off: its owner belongs to the database, not to an app", async () => { + test("schema public is never handed off or tagged: a new fork is migrated, and the service principal's tables that kept their rows are reported", async () => { const lakebase = project(); const ctx = appOn( lakebase, {}, { files: { "config/database/schema.ts": schemaSource("public") } }, ); - schemaOwner = "pg_database_owner"; + keptInPublic = ["table notes", "table orders"]; const { report } = await init(ctx); - expect(report.handedOff).toBeNull(); + expect(report).toMatchObject({ + handedOff: null, + keptCopy: { reason: "public", objects: ["table notes", "table orders"] }, + start: { kind: "migrate", migrate: migrateReport }, + }); expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( false, ); - expect(pool.query).not.toHaveBeenCalled(); + expect(queries.some((text) => text.includes("nspowner"))).toBe(false); + expect(queries.some((text) => text.includes("__drizzle_migrations"))).toBe( + false, + ); + expect(cleanHolding).not.toHaveBeenCalled(); }); test("creates a read-write endpoint that scales to zero after 5 idle minutes when the branch has none", async () => { @@ -916,13 +958,24 @@ describe("runInit — schema start", () => { migrate: migrateReport, }, }); + // Introspect writes the files while the copy is untouched and records nothing on it; the rebuild follows. expect(introspectHolding.mock.calls[0]?.[2]).toEqual({ interactive: false, schemaName: "app", + record: false, }); expect(introspectHolding.mock.invocationCallOrder[0]).toBeLessThan( cleanHolding.mock.invocationCallOrder[0] ?? 0, ); + const handOff = lakebase.calls.findIndex((call) => + call.startsWith("deleteRole"), + ); + expect(handOff).toBeGreaterThan(-1); + expect( + steps.indexOf( + `Writing schema.ts from schema app on ${devBranchId(USER)}`, + ), + ).toBeLessThan(steps.findIndex((step) => step.startsWith("Handing"))); expect(cleanHolding.mock.invocationCallOrder[0]).toBeLessThan( migrateHolding.mock.invocationCallOrder[0] ?? 0, ); @@ -1062,23 +1115,23 @@ describe("runInit — schema start", () => { ); }); -describe("runInit — a branch init forked starts without its copied rows", () => { +describe("runInit — the start follows the branch's own state", () => { const dropping = (schemaName = "app") => - `Dropping schema ${schemaName} on ${devBranchId(USER)}: a branch init forked starts without the rows it copied, and the committed migrations recreate its tables`; + `Dropping schema ${schemaName} on ${devBranchId(USER)}: the branch still holds the rows the fork copied, and the committed migrations recreate its tables`; function existingDev(): FakeLakebase { const lakebase = project(); - lakebase.addBranch(DEV); + lakebase.addBranch(DEV, { source_branch: PRODUCTION }); lakebase.addRole(DEV, "alice", USER, ["DATABRICKS_SUPERUSER"]); return lakebase; } - test("a reused branch keeps its rows: migrate with schema.ts, introspect alone without", async () => { + test("your working branch keeps its rows: migrate with schema.ts, introspect alone without", async () => { schemaOwner = USER; const withSchema = await init(appOn(existingDev())); - expect(withSchema.report.start).toEqual({ - kind: "migrate", - migrate: migrateReport, + expect(withSchema.report).toMatchObject({ + keptCopy: null, + start: { kind: "migrate", migrate: migrateReport }, }); const withoutSchema = await init( @@ -1089,72 +1142,158 @@ describe("runInit — a branch init forked starts without its copied rows", () = introspect: { branch: DEV, tables: [] }, rebuilt: null, }); + expect(introspectHolding.mock.calls[0]?.[2]).toMatchObject({ + record: true, + }); expect(cleanHolding).not.toHaveBeenCalled(); + expect(tagWrites()).toEqual([]); + }); + + test("a copy the service principal owns on an existing branch is rebuilt, from a run that forked nothing", async () => { + const lakebase = existingDev(); + lakebase.addRole(DEV, `dbrx-apps-${SP}`, SP); + + const { report, steps } = await init(appOn(lakebase)); + + expect(report).toMatchObject({ + created: false, + handedOff: SP, + start: { kind: "clean" }, + }); + expect(steps).toContain(dropping()); + expect(tagWrites()).toEqual(["insert"]); + }); + + test("a copy handed to you whose rebuild stopped is tagged: the next init rebuilds it without another hand-off", async () => { + schemaOwner = USER; + tagged = true; + const lakebase = existingDev(); + + const { report, steps } = await init(appOn(lakebase)); + + expect(report).toMatchObject({ + created: false, + handedOff: null, + start: { kind: "clean" }, + }); + expect(steps).toContain(dropping()); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + expect(tagWrites()).toEqual([]); }); - test("--schema migrate or --schema introspect on a new fork keeps the copied rows", async () => { + test("a handed-off copy without schema.ts says how to continue instead of guessing", async () => { + schemaOwner = USER; + tagged = true; + + await expect( + init(appOn(existingDev(), {}, { schema: false })), + ).rejects.toThrow( + "Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", + ); + expect(introspectHolding).not.toHaveBeenCalled(); + expect(cleanHolding).not.toHaveBeenCalled(); + }); + + test("a copy without a journal is rebuilt without a tag", async () => { + journal = false; + + const { report } = await init(appOn(project())); + + expect(report.start.kind).toBe("clean"); + expect(tagWrites()).toEqual([]); + }); + + test("--schema migrate or --schema introspect on a copy keeps the copied rows: handed off, untagged, and reported", async () => { + tagged = true; const migrated = await init(appOn(project()), { schema: "migrate" }); - expect(migrated.report.start).toEqual({ - kind: "migrate", - migrate: migrateReport, + expect(migrated.report).toMatchObject({ + handedOff: SP, + keptCopy: { reason: "requested", from: PRODUCTION }, + start: { kind: "migrate", migrate: migrateReport }, }); + expect(tagWrites()).toEqual(["delete"]); const introspected = await init(appOn(project(), {}, { schema: false }), { schema: "introspect", }); - expect(introspected.report.start).toEqual({ - kind: "introspect", - introspect: { branch: DEV, tables: [] }, - rebuilt: null, + expect(introspected.report).toMatchObject({ + handedOff: SP, + keptCopy: { reason: "requested", from: PRODUCTION }, + start: { + kind: "introspect", + introspect: { branch: DEV, tables: [] }, + rebuilt: null, + }, + }); + expect(introspectHolding.mock.calls[0]?.[2]).toMatchObject({ + record: true, }); expect(cleanHolding).not.toHaveBeenCalled(); }); - test("a run that stopped after the fork leaves a marker in .env, and the next init rebuilds as if it had forked", async () => { - schemaOwner = USER; - const ctx = appOn(existingDev(), { APPKIT_DB_NEW_BRANCH: DEV }); + test("--schema clean asks first only on your working branch; a copy's rebuild never asks", async () => { + const asked: { branch: string; schemaName: string }[] = []; + const confirmClean = async (target: { + branch: string; + schemaName: string; + }) => { + asked.push(target); + return true; + }; - const { report, steps } = await init(ctx); + await init(appOn(project()), { schema: "clean", confirmClean }); + expect(asked).toEqual([]); - expect(report).toMatchObject({ created: false, start: { kind: "clean" } }); - expect(steps).toContain(dropping()); - expect(envFile(ctx.root).APPKIT_DB_NEW_BRANCH).toBeUndefined(); + // Your working branch: the schema is yours and its journal carries no tag. + schemaOwner = USER; + tagged = false; + await init(appOn(existingDev()), { schema: "clean", confirmClean }); + expect(asked).toEqual([{ branch: DEV, schemaName: "app" }]); }); - test("a marker for another branch changes nothing, and stays", async () => { + test("a no to the confirmation stops before the drop, with .env already pointing at the branch", async () => { schemaOwner = USER; - const other = session("k2x9q0ab"); - const ctx = appOn(existingDev(), { APPKIT_DB_NEW_BRANCH: other }); - - const { report } = await init(ctx); + const ctx = appOn(existingDev()); - expect(report.start.kind).toBe("migrate"); - expect(envFile(ctx.root).APPKIT_DB_NEW_BRANCH).toBe(other); + const refused = init(ctx, { + schema: "clean", + confirmClean: async () => false, + }); + await expect(refused).rejects.toBeInstanceOf(InitCancelledError); + await expect(refused).rejects.toThrow( + `Cancelled. Schema app on ${devBranchId(USER)} is as it was, and .env points at the branch.`, + ); + expect(cleanHolding).not.toHaveBeenCalled(); + expect(envFile(ctx.root).LAKEBASE_ENDPOINT).toBe( + `${DEV}/endpoints/primary`, + ); }); - test("the marker is written before the fork and removed when the fork is refused, so a stop during the fork is covered", async () => { - const stopped = project(); - stopped.createBranchError = new Error("network down"); - const stoppedCtx = appOn(stopped); - await expect(init(stoppedCtx)).rejects.toThrow("network down"); - expect(envFile(stoppedCtx.root).APPKIT_DB_NEW_BRANCH).toBe(DEV); - + test("a fork refused at creation leaves .env as it was", async () => { const refused = project(); refused.createBranchError = forbidden(); - const refusedCtx = appOn(refused); - await expect(init(refusedCtx)).rejects.toThrow("needs CAN MANAGE"); - expect(envFile(refusedCtx.root).APPKIT_DB_NEW_BRANCH).toBeUndefined(); + const ctx = appOn(refused); + const before = fs.readFileSync(path.join(ctx.root, ".env"), "utf-8"); + + await expect(init(ctx)).rejects.toThrow("needs CAN MANAGE"); + + expect(fs.readFileSync(path.join(ctx.root, ".env"), "utf-8")).toBe(before); }); - test("--schema none on a new fork completes its setup: the marker goes, and the next init migrates", async () => { + test("--schema none touches nothing on a new fork, and the next plain init still rebuilds the copy", async () => { const lakebase = project(); const ctx = appOn(lakebase); const first = await init(ctx, { schema: "none" }); - expect(first.report.start).toEqual({ kind: "none" }); - expect(envFile(ctx.root).APPKIT_DB_NEW_BRANCH).toBeUndefined(); + expect(first.report).toMatchObject({ + handedOff: null, + keptCopy: null, + start: { kind: "none" }, + }); + expect(pool.query).not.toHaveBeenCalled(); - schemaOwner = USER; const rerun = fakeContext({ root: ctx.root, env: { ...ctx.env, ...envFile(ctx.root) }, @@ -1162,7 +1301,11 @@ describe("runInit — a branch init forked starts without its copied rows", () = api: lakebase.api(), }); const second = await init(rerun); - expect(second.report.start.kind).toBe("migrate"); + expect(second.report).toMatchObject({ + created: false, + handedOff: SP, + start: { kind: "clean" }, + }); }); test("the hand-off and the introspect read the schema schema.ts declares", async () => { @@ -1181,6 +1324,7 @@ describe("runInit — a branch init forked starts without its copied rows", () = expect(introspectHolding.mock.calls[0]?.[2]).toEqual({ interactive: false, schemaName: "sales", + record: true, }); expect(steps).toContain( `Writing schema.ts from schema sales on ${devBranchId(USER)}`, @@ -1250,8 +1394,8 @@ describe("runInit — .env", () => { `Database analytics, which databricks.yml binds, is not on ${devBranchId(USER)}. Create it there (databricks postgres create-database ${DEV} --database-id analytics), or bind a database the project's branches have, then rerun \`appkit db init\`.`, ); expect(lakebase.calls).toContain(`getDatabase ${DEV}/databases/analytics`); - // The fork happened, so .env marks the branch for its first start and nothing else. - expect(envFile(root)).toEqual({ APPKIT_DB_NEW_BRANCH: DEV }); + // The fork happened, and nothing was written: the next init finds the branch by its name. + expect(fs.existsSync(path.join(root, ".env"))).toBe(false); }); test("the profile init authenticated with wins over the host", async () => { diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 4a302c3ed..cbd959f15 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -76,7 +76,8 @@ const devBranch = { kind: "dev", }; -const pool = {}; +/** A branch whose journal is not an ordinary table, so it is no fork's copy. */ +const pool = { query: vi.fn(async () => ({ rows: [] })) }; beforeEach(() => { applyPendingMigrations.mockReset(); diff --git a/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts new file mode 100644 index 000000000..5d7057a36 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts @@ -0,0 +1,147 @@ +import { randomUUID } from "node:crypto"; + +import { Pool } from "pg"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; + +import { + FORK_COPY_TAG, + isForkCopy, + readSchemaState, + tagForkCopy, + untagForkCopy, +} from "../schema-state"; + +// The tag and the state read against a real server, with Lakebase's roles +// modelled: the app's service principal owns the fork's copy, and you connect +// as a role that inherits pg_read_all_data and pg_write_all_data, as a member +// of DATABRICKS_SUPERUSER does. APPKIT_TEST_PG_URL is a superuser URL, e.g. +// postgres://localhost:5432/postgres +const url = process.env.APPKIT_TEST_PG_URL; + +function asRole(role: string, password: string): string { + const next = new URL(url as string); + next.username = role; + next.password = password; + return next.toString(); +} + +describe.skipIf(!url)("the fork-copy tag against Postgres", () => { + const suffix = randomUUID().slice(0, 8); + const sp = `appkit_sp_${suffix}`; + const superuser = `appkit_dbx_${suffix}`; + const dev = `appkit_dev_${suffix}`; + const app = `app_${suffix}`; + const bare = `bare_${suffix}`; + const shared = `shared_${suffix}`; + let admin: Pool; + let me: Pool; + + const journalRows = async () => + ( + await admin.query<{ hash: string; created_at: string }>( + `select hash, created_at::text from "${app}".__drizzle_migrations order by id`, + ) + ).rows; + + beforeAll(async () => { + admin = new Pool({ connectionString: url, max: 1 }); + await admin.query(` + create role "${sp}" nologin; + create role "${superuser}" nologin; + grant pg_read_all_data, pg_write_all_data to "${superuser}"; + create role "${dev}" login password 'appkit'; + grant "${superuser}" to "${dev}"; + grant create on database ${(await admin.query("select current_database() as db")).rows[0]?.db} to "${sp}"; + create schema "${app}" authorization "${sp}"; + create schema "${bare}" authorization "${sp}"; + set role "${sp}"; + create table "${app}".notes (id integer primary key, body text); + insert into "${app}".notes values (1, 'copied'); + create table "${app}".__drizzle_migrations (id serial primary key, hash text not null, created_at bigint); + insert into "${app}".__drizzle_migrations (hash, created_at) values ('abc', 1700000000000); + create table "${bare}".notes (id integer primary key); + reset role; + create table public."${shared}" (id integer primary key); + alter table public."${shared}" owner to "${sp}"; + `); + me = new Pool({ connectionString: asRole(dev, "appkit"), max: 1 }); + }); + afterAll(async () => { + await me?.end(); + await admin.query(` + drop schema if exists "${app}" cascade; + drop schema if exists "${bare}" cascade; + drop table if exists public."${shared}"; + reassign owned by "${sp}" to current_user; + drop owned by "${sp}"; + drop owned by "${dev}"; + drop role if exists "${dev}"; + drop role if exists "${superuser}"; + drop role if exists "${sp}"; + `); + await admin.end(); + }); + + test("a schema that does not exist is absent", async () => { + await expect(readSchemaState(me, `missing_${suffix}`)).resolves.toEqual({ + kind: "absent", + }); + }); + + test("the service principal's copy reads as a copy, and you can tag its journal before any hand-off", async () => { + await expect(readSchemaState(me, app)).resolves.toEqual({ + kind: "copy", + owner: sp, + }); + await expect(isForkCopy(me, app)).resolves.toBe(false); + + await expect(tagForkCopy(me, app)).resolves.toBe(true); + await expect(tagForkCopy(me, app)).resolves.toBe(true); + + await expect(isForkCopy(me, app)).resolves.toBe(true); + expect(await journalRows()).toEqual([ + { hash: "abc", created_at: "1700000000000" }, + { hash: FORK_COPY_TAG, created_at: "0" }, + ]); + // The tag changes nothing else: the copy still reads as the other role's. + await expect(readSchemaState(me, app)).resolves.toEqual({ + kind: "copy", + owner: sp, + }); + }); + + test("once handed to you, a tagged schema reads as a handed-off copy, and untagging makes it yours", async () => { + await admin.query(` + alter schema "${app}" owner to "${dev}"; + alter table "${app}".notes owner to "${dev}"; + alter table "${app}".__drizzle_migrations owner to "${dev}"; + `); + + await expect(readSchemaState(me, app)).resolves.toEqual({ + kind: "handed-off-copy", + }); + + await untagForkCopy(me, app); + await expect(readSchemaState(me, app)).resolves.toEqual({ kind: "yours" }); + expect(await journalRows()).toEqual([ + { hash: "abc", created_at: "1700000000000" }, + ]); + await untagForkCopy(me, app); + }); + + test("a schema without a journal cannot be tagged, and reads as a copy all the same", async () => { + await expect(tagForkCopy(me, bare)).resolves.toBe(false); + await expect(isForkCopy(me, bare)).resolves.toBe(false); + await untagForkCopy(me, bare); + await expect(readSchemaState(me, bare)).resolves.toEqual({ + kind: "copy", + owner: sp, + }); + }); + + test("public is never a copy: it lists what other roles own there", async () => { + const state = await readSchemaState(me, "public"); + expect(state.kind).toBe("public"); + expect(state.kind === "public" && state.kept).toContain(`table ${shared}`); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/schema-state.test.ts b/packages/appkit/src/database/tooling/tests/schema-state.test.ts new file mode 100644 index 000000000..c33b25c67 --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/schema-state.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, test } from "vitest"; + +import { planStart, type SchemaState, type StartPlan } from "../schema-state"; + +const absent: SchemaState = { kind: "absent" }; +const copy: SchemaState = { kind: "copy", owner: "app-sp" }; +const handedOff: SchemaState = { kind: "handed-off-copy" }; +const yours: SchemaState = { kind: "yours" }; +const pub: SchemaState = { kind: "public", kept: ["table notes"] }; + +const only = (plan: Partial & Pick) => ({ + rebuild: false, + tag: false, + handOff: false, + keepsCopy: false, + confirm: false, + ...plan, +}); + +describe("planStart", () => { + test.each([ + [absent, "migrate"], + [yours, "migrate"], + [pub, "migrate"], + ] as const)( + "%j without a request migrates with schema.ts and introspects without", + (state, kind) => { + expect(planStart(state, undefined, true)).toEqual(only({ kind })); + expect(planStart(state, undefined, false)).toEqual( + only({ kind: "introspect" }), + ); + }, + ); + + test("a copy another role owns is tagged, handed off and rebuilt; introspect writes schema.ts first when there is none", () => { + const rebuilt = { rebuild: true, tag: true, handOff: true }; + expect(planStart(copy, undefined, true)).toEqual( + only({ kind: "clean", ...rebuilt }), + ); + expect(planStart(copy, undefined, false)).toEqual( + only({ kind: "introspect", ...rebuilt }), + ); + expect(planStart(copy, "clean", true)).toEqual( + only({ kind: "clean", ...rebuilt }), + ); + }); + + test("a handed-off copy is rebuilt without another hand-off or tag", () => { + expect(planStart(handedOff, undefined, true)).toEqual( + only({ kind: "clean", rebuild: true }), + ); + expect(planStart(handedOff, "clean", true)).toEqual( + only({ kind: "clean", rebuild: true }), + ); + }); + + test("a handed-off copy without schema.ts cannot be rebuilt by default: the message says how to continue", () => { + expect(() => planStart(handedOff, undefined, false)).toThrow( + "Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", + ); + }); + + test.each(["migrate", "introspect"] as const)( + "--schema %s on a copy keeps its rows: the untouched copy is handed off, neither is tagged", + (requested) => { + expect(planStart(copy, requested, true)).toEqual( + only({ kind: requested, handOff: true, keepsCopy: true }), + ); + expect(planStart(handedOff, requested, true)).toEqual( + only({ kind: requested, keepsCopy: true }), + ); + }, + ); + + test("an explicit clean asks first on your working branch and on public, not where nothing exists or on a copy", () => { + expect(planStart(yours, "clean", true)).toEqual( + only({ kind: "clean", rebuild: true, confirm: true }), + ); + expect(planStart(pub, "clean", true)).toEqual( + only({ kind: "clean", rebuild: true, confirm: true }), + ); + expect(planStart(absent, "clean", true)).toEqual( + only({ kind: "clean", rebuild: true }), + ); + expect(planStart(copy, "clean", true).confirm).toBe(false); + expect(planStart(handedOff, "clean", true).confirm).toBe(false); + }); + + test.each([absent, yours, pub] as const)( + "%j takes an explicit migrate or introspect as asked", + (state) => { + expect(planStart(state, "migrate", true)).toEqual( + only({ kind: "migrate" }), + ); + expect(planStart(state, "introspect", true)).toEqual( + only({ kind: "introspect" }), + ); + }, + ); +}); diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index f9acfa3ab..c06ae1fe9 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -63,14 +63,12 @@ describe("readLocalTarget", () => { PGDATABASE: "databricks_postgres", PGUSER: "alice@example.com", APPKIT_DB_SESSION: "k2x9q0ab", - APPKIT_DB_NEW_BRANCH: "projects/p/branches/dev-alice-3f9a2c", }), ).toEqual({ project: "projects/p", endpoint: "projects/p/branches/b/endpoints/primary", database: "databricks_postgres", session: "k2x9q0ab", - newBranch: "projects/p/branches/dev-alice-3f9a2c", }); }); @@ -82,14 +80,12 @@ describe("readLocalTarget", () => { PGHOST: "your_postgres_host", PGDATABASE: "your_postgres_databaseName", APPKIT_DB_SESSION: "NOT VALID", - APPKIT_DB_NEW_BRANCH: "dev-alice-3f9a2c", }), ).toEqual({ project: null, endpoint: null, database: null, session: null, - newBranch: null, }); }); }); From dfc80b34460680ee9057eaf50910d35b9320b40e Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:41:43 +0000 Subject: [PATCH 170/317] feat(cli): ask before a clean only when init says the schema is yours, and report kept copied rows The confirmation for --schema clean moves from before the run into a callback init calls once it has read the branch, so a fork's copy is rebuilt without a question and a non-interactive shell is refused only when there is one to ask. A no prints what init left and exits 1. init's report of rows the fork copied that stayed, on request or because other roles own them in public, is printed as a warning. The option and help text describe the rule the branch decides. Co-authored-by: Isaac Signed-off-by: ditadi --- .../cli/commands/db/init-clean-seed.test.ts | 91 +++++++++++++++++-- packages/shared/src/cli/commands/db/init.ts | 78 ++++++++++------ .../src/cli/commands/db/tooling-contract.ts | 17 ++++ 3 files changed, 150 insertions(+), 36 deletions(-) diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index d8f0768e3..ba5caa720 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -58,11 +58,31 @@ const report = { action: "kept", }, handedOff: "11111111-2222-3333-4444-555555555555", + keptCopy: null, envFile: "/app/.env", installed: null, start: { kind: "migrate", migrate }, }; +/** The tooling on your working branch: it asks the confirmation and stops on a no. */ +function toolingThatAsks(): void { + tooling.runInit.mockImplementation(async (_ctx, options) => { + const confirmed = await options.confirmClean?.({ + branch: report.branch, + schemaName: "app", + }); + if (confirmed === false) { + throw Object.assign( + new Error( + "Cancelled. Schema app on dev-alice-3f9a2c is as it was, and .env points at the branch.", + ), + { name: "InitCancelledError" }, + ); + } + return report; + }); +} + /** Commander keeps parsed option values on the command; each test parses afresh. */ function resetOptionValues() { for (const command of dbCommand.commands) { @@ -258,14 +278,42 @@ describe("appkit db init", () => { tooling.runInit.mockResolvedValue(rebuilt); await init(); expect(output(log)).toContain( - "A branch init forked starts without the rows it copied: the app schema was rebuilt from the committed migrations. `appkit db init --schema migrate` keeps them.", + "The branch still held the rows the fork copied: the app schema was rebuilt from the committed migrations. `appkit db init --schema migrate` keeps them.", ); log.mockClear(); resetOptionValues(); await init("--schema", "clean", "--yes"); expect(output(log)).toContain("Dropped schema app on dev-alice-3f9a2c"); - expect(output(log)).not.toContain("A branch init forked starts without"); + expect(output(log)).not.toContain("The branch still held the rows"); + }); + + test("copied rows kept on request are a warning that names their source and the flag", async () => { + tooling.runInit.mockResolvedValue({ + ...report, + keptCopy: { + reason: "requested", + from: "projects/p/branches/production", + }, + }); + await init("--schema", "migrate"); + + expect(output(log)).toContain( + "Kept the rows the fork copied from production, as --schema migrate asks. A plain `appkit db init` rebuilds the app schema from the committed migrations without them.", + ); + }); + + test("in schema public, the tables other roles own are listed as kept with their rows", async () => { + tooling.runInit.mockResolvedValue({ + ...report, + handedOff: null, + keptCopy: { reason: "public", objects: ["table notes", "table orders"] }, + }); + await init(); + + expect(output(log)).toContain( + "Kept in schema public, with their rows, because other roles own them: table notes, table orders", + ); }); test("an introspect start with a rebuild prints what introspect wrote, the drop, the migrations, and names --schema introspect to keep the rows", async () => { @@ -322,38 +370,61 @@ describe("appkit db init", () => { const command = dbCommand.commands.find((c) => c.name() === "init"); const schema = command?.options.find((o) => o.long === "--schema"); expect(schema?.description).toBe( - "how the schema starts (default: a new branch is rebuilt from the migrations, a reused one is migrated; introspect without schema.ts)", + "how the schema starts (default: a schema that still holds the fork's copy is rebuilt from the migrations, your working branch is migrated; introspect without schema.ts)", ); expect(command?.helpInformation()).not.toContain( "start with a copy of its rows", ); }); - test("--schema clean without a TTY needs --yes, and stops before any API call", async () => { + test("--schema clean hands the tooling a confirmation, which refuses without a TTY and says to pass --yes", async () => { + toolingThatAsks(); await init("--schema", "clean"); expect(output(error)).toContain( - "Refusing to run `--schema clean` without confirmation in a non-interactive shell. Pass --yes.", + "Refusing to drop schema app on dev-alice-3f9a2c, your working branch's, without confirmation in a non-interactive shell. Pass --yes. .env already points at the branch.", ); - expect(tooling.runInit).not.toHaveBeenCalled(); + expect(prompts.confirm).not.toHaveBeenCalled(); expect(process.exitCode).toBe(1); }); - test("--schema clean on a TTY asks first; a no cancels with exit code 1", async () => { + test("--schema clean on a TTY asks when the tooling says the schema is yours; a no cancels with exit code 1", async () => { setTTY(true); + toolingThatAsks(); prompts.confirm.mockResolvedValueOnce(false); await init("--schema", "clean"); - expect(prompts.confirm).toHaveBeenCalledOnce(); - expect(tooling.runInit).not.toHaveBeenCalled(); - expect(output(log)).toContain("Cancelled"); + expect(prompts.confirm.mock.calls[0]?.[0].message).toBe( + "Drop schema app on dev-alice-3f9a2c, with every table and row in it, then apply the committed migrations?", + ); + expect(output(log)).toContain( + "Cancelled. Schema app on dev-alice-3f9a2c is as it was, and .env points at the branch.", + ); expect(process.exitCode).toBe(1); process.exitCode = undefined; + log.mockClear(); resetOptionValues(); prompts.confirm.mockResolvedValueOnce(true); await init("--schema", "clean"); + expect(output(log)).toContain("Applied 0000_migration to the .env branch"); + expect(process.exitCode).toBeUndefined(); + }); + + test("--schema clean on a copy asks nothing: the tooling decides from the branch and never calls the confirmation", async () => { + setTTY(true); + await init("--schema", "clean"); + expect(initOptions()).toMatchObject({ schema: "clean" }); + expect(initOptions()?.confirmClean).toBeTypeOf("function"); + expect(prompts.confirm).not.toHaveBeenCalled(); + expect(process.exitCode).toBeUndefined(); + }); + + test("--yes passes no confirmation", async () => { + await init("--schema", "clean", "--yes"); + + expect(initOptions()?.confirmClean).toBeUndefined(); }); test("an error is printed and exits 1", async () => { diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index b82559cbf..b8b961426 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -10,6 +10,7 @@ import { printIntrospectReport, printMigrateReport, shortName, + warn, } from "./output"; import type { InitOptions, @@ -26,22 +27,31 @@ interface InitFlags { readonly yes?: boolean; } -/** --schema clean drops data: a human confirms it, a script passes --yes. */ -async function confirmClean(flags: InitFlags): Promise { - if (flags.schema !== "clean" || flags.yes) return true; +/** + * --schema clean on your working branch drops your data: a human confirms it, + * a script passes --yes. init asks only once it has read from the branch that + * the schema is yours, so a fork's copy is rebuilt without a question. + */ +const confirmClean: NonNullable = async ({ + branch, + schemaName, +}) => { + const where = `schema ${schemaName} on ${shortName(branch)}`; if (!isInteractive()) { throw new Error( - "Refusing to run `--schema clean` without confirmation in a non-interactive shell. Pass --yes.", + `Refusing to drop ${where}, your working branch's, without confirmation in a non-interactive shell. Pass --yes. .env already points at the branch.`, ); } const { confirm, isCancel } = await import("@clack/prompts"); const answer = await confirm({ message: - "Drop the app schema on your dev or session branch, with every table and row in it, then apply the committed migrations?", + schemaName === "public" + ? `Remove your objects in ${where}, with their rows, then apply the committed migrations?` + : `Drop ${where}, with every table and row in it, then apply the committed migrations?`, initialValue: false, }); return !isCancel(answer) && answer; -} +}; function printRebuild(rebuild: Rebuild): void { printCleanReport(rebuild.clean); @@ -74,13 +84,13 @@ function printInitReport( ok(`Pointed .env at ${branch} (database ${report.database})`); if (report.installed) ok(`Installed drizzle-kit (${report.installed})`); - const { start } = report; - // Without --schema, only a branch init forked gets a rebuild. + const { start, keptCopy } = report; + // Without --schema, only a schema that still held the fork's copy gets a rebuild. const rebuilt = start.kind === "clean" || (start.kind === "introspect" && start.rebuilt); if (rebuilt && schemaFlag === undefined) { info( - `A branch init forked starts without the rows it copied: the app schema was rebuilt from the committed migrations. \`appkit db init --schema ${start.kind === "introspect" ? "introspect" : "migrate"}\` keeps them.`, + `The branch still held the rows the fork copied: the app schema was rebuilt from the committed migrations. \`appkit db init --schema ${start.kind === "introspect" ? "introspect" : "migrate"}\` keeps them.`, ); } if (start.kind === "introspect") { @@ -91,21 +101,27 @@ function printInitReport( } else if (start.kind === "migrate") printMigrateReport(start.migrate); else if (start.kind === "clean") printRebuild(start); else info("Left the schema as it is"); + + if (keptCopy?.reason === "requested") { + warn( + `Kept the rows the fork copied${keptCopy.from ? ` from ${shortName(keptCopy.from)}` : ""}, as --schema ${schemaFlag} asks. A plain \`appkit db init\` rebuilds the app schema from the committed migrations without them.`, + ); + } else if (keptCopy?.reason === "public") { + warn( + `Kept in schema public, with their rows, because other roles own them: ${keptCopy.objects.join(", ")}`, + ); + } } async function runDbInit(flags: InitFlags): Promise { try { - if (!(await confirmClean(flags))) { - info("Cancelled"); - process.exitCode = 1; - return; - } const tooling = await loadDatabaseTooling(); const mode = flags.session ? "session" : flags.dev ? "dev" : undefined; const options: InitOptions = { ...(mode ? { mode } : {}), ...(flags.schema ? { schema: flags.schema } : {}), ...(flags.ttl !== undefined ? { ttl: flags.ttl } : {}), + ...(flags.schema === "clean" && !flags.yes ? { confirmClean } : {}), interactive: !flags.yes && isInteractive(), onStep: info, }; @@ -114,6 +130,11 @@ async function runDbInit(flags: InitFlags): Promise { flags.schema, ); } catch (error) { + if (error instanceof Error && error.name === "InitCancelledError") { + info(error.message); + process.exitCode = 1; + return; + } fail(error); } } @@ -141,7 +162,7 @@ export const dbInitCommand = new Command("init") .addOption( new Option( "--schema ", - "how the schema starts (default: a new branch is rebuilt from the migrations, a reused one is migrated; introspect without schema.ts)", + "how the schema starts (default: a schema that still holds the fork's copy is rebuilt from the migrations, your working branch is migrated; introspect without schema.ts)", ).choices(["migrate", "introspect", "clean", "none"]), ) .option( @@ -153,19 +174,24 @@ export const dbInitCommand = new Command("init") ` init asks nothing. It keeps this checkout's session branch when .env points at one, and otherwise uses your dev branch (dev--). A new branch forks -the project's default branch, which copies its rows, production data included. -init then rebuilds the app schema from the committed migrations (written first -by introspect when there is no schema.ts), so the new branch starts without -them; a run that stops before that finishes rebuilds on its rerun. --schema -migrate, or --schema introspect without schema.ts, keeps the copied rows. A -reused branch keeps its data: init migrates it. In schema public only your own -objects go; what other roles own stays with its rows, and init lists it. init -never changes the default branch, a protected branch or a branch databricks.yml -deploys to, and never edits databricks.yml. +the branch databricks.yml deploys to, else the project's default branch, which +copies its rows, production data included. init reads from the branch whether +the app schema is still that copy. If it is, init takes the schema over and +rebuilds it from the committed migrations (written first by introspect when +there is no schema.ts), so the branch starts without the copied rows. A run +that stops before the rebuild finishes is finished by the next init, from any +checkout. --schema migrate, or --schema introspect, keeps the copied rows and +says so. Your working branch keeps its data: init migrates it. --schema clean +rebuilds your working branch too, after a confirmation or with --yes; a copy's +rebuild asks nothing. In schema public only your own objects go; what other +roles own stays with its rows, and init lists it. init never changes the +default branch, a protected branch or a branch databricks.yml deploys to, and +never edits databricks.yml. With --schema none, init only sets up the branch and .env: the schema and its -owner stay as the fork copied them. init never hands off schema public, which -belongs to the database rather than to an app. +owner stay as the fork copied them, and the next plain init still rebuilds it. +init never hands off schema public, which belongs to the database rather than +to an app. The project comes from LAKEBASE_PROJECT in .env (projects/ or ), else from LAKEBASE_ENDPOINT, else from the bundle's postgres_branch variable. When diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 5963f828f..10f63264a 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -49,6 +49,15 @@ export interface InitOptions { readonly ttl?: string; readonly interactive?: boolean; readonly onStep?: (message: string) => void; + /** + * Asked before an explicit --schema clean drops a schema that may hold your + * work. init reads from the branch whether it does, and asks nothing for a + * fork's copy. A no makes init throw an error named InitCancelledError. + */ + readonly confirmClean?: (target: { + readonly branch: string; + readonly schemaName: string; + }) => Promise; } export interface CleanReport { @@ -65,6 +74,13 @@ export interface Rebuild { readonly migrate: MigrateReport; } +/** Rows the fork copied into the app schema that init left in place, and why. */ +export type KeptCopy = + /** You asked for --schema migrate or --schema introspect on a copy. */ + | { readonly reason: "requested"; readonly from: string | null } + /** In schema public, what other roles own stays with its rows; init never removes it. */ + | { readonly reason: "public"; readonly objects: readonly string[] }; + export type InitStart = | { readonly kind: "none" } | { readonly kind: "migrate"; readonly migrate: MigrateReport } @@ -92,6 +108,7 @@ export interface InitReport { readonly action: "kept" | "created" | "updated"; }; readonly handedOff: string | null; + readonly keptCopy: KeptCopy | null; readonly envFile: string; readonly installed: string | null; readonly start: InitStart; From 298927e9ee52222552173fa8f82328a92611861a Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:41:47 +0000 Subject: [PATCH 171/317] docs: describe how appkit db init tells a fork's copy from your working branch Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 48 ++++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 192436654..f13279fe1 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -144,24 +144,36 @@ yours. ### 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 project's default branch, and points `.env` -at it. A fork copies every row of its source, production data included. A -branch `init` forked starts without them: `init` drops the app schema and -recreates it from the committed migrations. 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. Until the -rebuild has run, `.env` names the branch in `APPKIT_DB_NEW_BRANCH`, so a run -that stops early is finished by the next `init`. - -To keep the copied rows on a new branch, pass `--schema migrate`, or -`--schema introspect` without `schema.ts`. A branch `init` reuses keeps its -data: `init` migrates it, or introspects it without `schema.ts`. -`--schema clean` rebuilds a reused branch too, after a confirmation or with -`--yes`. - -In schema `public`, `init` and `clean` remove only the objects your role owns. -On a fork of the deploy branch the app's service principal owns the tables, so -they stay with their rows, and the report lists them as kept. +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. +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. Dropping the schema removes it. +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. `appkit db migrate`, `appkit db introspect` and +`appkit db seed` refuse a branch whose journal carries it. + +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. A schema you own with no such row is your working branch. +`init` migrates it, or introspects it without `schema.ts`. `--schema clean` +rebuilds your working branch too, after a confirmation or with `--yes`. A +copy's rebuild asks nothing, because `migrate` refuses a copy, so none of your +work can be on it. `--schema none` touches nothing, and the next plain `init` +still rebuilds the copy. + +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 From 21ff2aa74e6d7bb53d9f6831db6e200c8c9bb20d Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:44:30 +0000 Subject: [PATCH 172/317] chore: write init's comments as plain sentences Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 10 +++++----- packages/appkit/src/database/tooling/schema-state.ts | 10 +++++----- .../appkit/src/database/tooling/tests/init.pg.test.ts | 6 +++--- .../appkit/src/database/tooling/tests/init.test.ts | 4 ++-- .../src/database/tooling/tests/schema-state.pg.test.ts | 4 ++-- .../shared/src/cli/commands/db/init-clean-seed.test.ts | 2 +- packages/shared/src/cli/commands/db/init.ts | 2 +- 7 files changed, 19 insertions(+), 19 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 279460412..965c1bda3 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -84,7 +84,7 @@ export interface InitOptions { readonly schema?: SchemaStart; /** * Asked before an explicit --schema clean drops a schema that may hold your - * work: your working branch, or public. A copy's rebuild never asks. Absent, + * work, your working branch or public. A copy's rebuild never asks. Absent, * the clean proceeds. */ readonly confirmClean?: (target: { @@ -760,10 +760,10 @@ async function initHolding( record, }); }; - // A rebuild without schema.ts introspects first, while the copy is untouched: - // introspect only writes files then, so a refusal leaves the branch as the - // fork made it. Introspect reads the journal as history, so a tag an earlier - // run left on the copy goes first and comes back right before the hand-off. + // A rebuild without schema.ts introspects first, while the copy is untouched. + // Introspect only writes files then, so a refusal leaves the branch as the + // fork made it. It reads the journal as history, so a tag an earlier run left + // on the copy goes first and comes back right before the hand-off. let introspected: IntrospectReport | null = null; if (plan.kind === "introspect" && plan.rebuild) { if (plan.tag) await onBranch((client) => untagForkCopy(client, schemaName)); diff --git a/packages/appkit/src/database/tooling/schema-state.ts b/packages/appkit/src/database/tooling/schema-state.ts index f2cc9de43..86caead78 100644 --- a/packages/appkit/src/database/tooling/schema-state.ts +++ b/packages/appkit/src/database/tooling/schema-state.ts @@ -20,9 +20,9 @@ export const FORK_COPY_TAG = "appkit:fork-copy"; export type SchemaState = /** Nothing copied and nothing built yet. */ | { readonly kind: "absent" } - /** The fork's untouched copy: another role, the app's service principal, owns it. */ + /** The fork's untouched copy. Another role, the app's service principal, owns it. */ | { readonly kind: "copy"; readonly owner: string } - /** Handed to you and still tagged: a rebuild stopped before its clean. */ + /** Handed to you and still tagged, so a rebuild stopped before its clean. */ | { readonly kind: "handed-off-copy" } /** Your working branch. */ | { readonly kind: "yours" } @@ -39,7 +39,7 @@ const journalTable = (schemaName: string) => /** * Whether an ordinary table stands at the journal's name. Anything else there - * is left alone: the migrator refuses it with its own message. + * is left alone. The migrator refuses it with its own message. */ async function hasJournalTable( client: QueryClient, @@ -122,7 +122,7 @@ export interface StartPlan { readonly tag: boolean; /** Delete the copy's owner on this branch, with its objects reassigned to you. */ readonly handOff: boolean; - /** You asked to keep a copy's rows: the tag goes and the rows stay. */ + /** You asked to keep a copy's rows. The tag goes and the rows stay. */ readonly keepsCopy: boolean; /** An explicit clean of what may be your work asks first. */ readonly confirm: boolean; @@ -139,7 +139,7 @@ const NOTHING_ELSE = { /** * Without a request, a copy is rebuilt and your working branch is migrated, * each with schema.ts, else introspected. A copy's rows stay only on request. - * A rebuild of a copy needs no confirmation: `appkit db migrate` refuses a + * A rebuild of a copy needs no confirmation, because `appkit db migrate` refuses a * tagged branch, so none of your work can be on it. */ export function planStart( diff --git a/packages/appkit/src/database/tooling/tests/init.pg.test.ts b/packages/appkit/src/database/tooling/tests/init.pg.test.ts index af23e115e..031a5fafe 100644 --- a/packages/appkit/src/database/tooling/tests/init.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.pg.test.ts @@ -42,8 +42,8 @@ import { tempApp, } from "./fakes"; -// init end to end: the Lakebase API is the fake, every SQL step is real. The -// test database models a fork of the deploy branch: the app's service +// init end to end. The Lakebase API is the fake, every SQL step is real. The +// test database models a fork of the deploy branch. The app's service // principal owns the app schema, and you connect as a role that inherits // pg_read_all_data and pg_write_all_data, as a member of DATABRICKS_SUPERUSER // does. APPKIT_TEST_PG_URL is a superuser URL that may create databases and @@ -117,7 +117,7 @@ describe.skipIf(!url)("runInit against Postgres", () => { ); } - /** The deploy branch as its service principal left it: migrated, with a row. */ + /** The deploy branch as its service principal left it, migrated and with a row. */ async function deployed(appRoot: string, schema: string, table: string) { await applyPendingMigrations(asSp, { migrationsFolder: folder(appRoot), diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index c9a14c87f..fcd0ec9e0 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1246,7 +1246,7 @@ describe("runInit — the start follows the branch's own state", () => { await init(appOn(project()), { schema: "clean", confirmClean }); expect(asked).toEqual([]); - // Your working branch: the schema is yours and its journal carries no tag. + // Your working branch, where the schema is yours and its journal carries no tag. schemaOwner = USER; tagged = false; await init(appOn(existingDev()), { schema: "clean", confirmClean }); @@ -1394,7 +1394,7 @@ describe("runInit — .env", () => { `Database analytics, which databricks.yml binds, is not on ${devBranchId(USER)}. Create it there (databricks postgres create-database ${DEV} --database-id analytics), or bind a database the project's branches have, then rerun \`appkit db init\`.`, ); expect(lakebase.calls).toContain(`getDatabase ${DEV}/databases/analytics`); - // The fork happened, and nothing was written: the next init finds the branch by its name. + // The fork happened, and nothing was written. The next init finds the branch by its name. expect(fs.existsSync(path.join(root, ".env"))).toBe(false); }); diff --git a/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts index 5d7057a36..f9bf68f48 100644 --- a/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts @@ -12,7 +12,7 @@ import { } from "../schema-state"; // The tag and the state read against a real server, with Lakebase's roles -// modelled: the app's service principal owns the fork's copy, and you connect +// modelled. The app's service principal owns the fork's copy, and you connect // as a role that inherits pg_read_all_data and pg_write_all_data, as a member // of DATABRICKS_SUPERUSER does. APPKIT_TEST_PG_URL is a superuser URL, e.g. // postgres://localhost:5432/postgres @@ -103,7 +103,7 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { { hash: "abc", created_at: "1700000000000" }, { hash: FORK_COPY_TAG, created_at: "0" }, ]); - // The tag changes nothing else: the copy still reads as the other role's. + // The tag changes nothing else. The copy still reads as the other role's. await expect(readSchemaState(me, app)).resolves.toEqual({ kind: "copy", owner: sp, diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index ba5caa720..f1a0eab3d 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -64,7 +64,7 @@ const report = { start: { kind: "migrate", migrate }, }; -/** The tooling on your working branch: it asks the confirmation and stops on a no. */ +/** The tooling on your working branch. It asks the confirmation and stops on a no. */ function toolingThatAsks(): void { tooling.runInit.mockImplementation(async (_ctx, options) => { const confirmed = await options.confirmClean?.({ diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index b8b961426..d34168cc5 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -28,7 +28,7 @@ interface InitFlags { } /** - * --schema clean on your working branch drops your data: a human confirms it, + * --schema clean on your working branch drops your data. A human confirms it, * a script passes --yes. init asks only once it has read from the branch that * the schema is yours, so a fork's copy is rebuilt without a question. */ From 20807f8cae8de9ce3791f884bb5c46c4548c4ec0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 20:47:23 +0000 Subject: [PATCH 173/317] fix(appkit): stop suggesting ALTER OWNER when init cannot hand off the schema Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/hand-off.ts | 2 +- packages/appkit/src/database/tooling/tests/init.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/hand-off.ts b/packages/appkit/src/database/tooling/hand-off.ts index 220160998..c18e41e3d 100644 --- a/packages/appkit/src/database/tooling/hand-off.ts +++ b/packages/appkit/src/database/tooling/hand-off.ts @@ -125,7 +125,7 @@ export async function handOffAppSchema( const role = input.roles.find((r) => r.status?.postgres_role === owner); if (!role) { throw new Error( - `Cannot hand ${where} to you: it belongs to "${owner}", which is not a Lakebase-managed role. .env already points at the branch. Have "${owner}" transfer the schema and its objects to you (ALTER … OWNER TO), or set another schemaName in schema.ts, then rerun \`appkit db init\`.`, + `Cannot hand ${where} to you: it belongs to "${owner}", 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) { diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index fcd0ec9e0..5fb5bb2f3 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -877,7 +877,7 @@ describe("runInit — hand-off failures", () => { schemaOwner = "legacy_owner"; await expect(init(appOn(project()))).rejects.toThrow( - `Cannot hand schema app in database databricks_postgres on ${devBranchId(USER)} to you: it belongs to "legacy_owner", which is not a Lakebase-managed role. .env already points at the branch.`, + `Cannot hand schema app in database databricks_postgres on ${devBranchId(USER)} to you: it belongs to "legacy_owner", 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\`.`, ); }); From e6ce5a7b18a0a192ec92a6623bc1788efea5f1db Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:03:51 +0000 Subject: [PATCH 174/317] test(appkit): local verify must report a fork copy awaiting its rebuild, not an unknown migration A branch init tagged with appkit:fork-copy reports forkCopy true and ok false, and the tag row is not counted in unknownMigrations. An untagged branch reports forkCopy false and nothing else changes. Against the fake branch and against Postgres. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/verify.pg.test.ts | 143 ++++++++++++++++++ .../src/database/tooling/tests/verify.test.ts | 44 ++++++ 2 files changed, 187 insertions(+) create mode 100644 packages/appkit/src/database/tooling/tests/verify.pg.test.ts diff --git a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts new file mode 100644 index 000000000..0fe403d5b --- /dev/null +++ b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts @@ -0,0 +1,143 @@ +import { createHash, randomUUID } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { Pool } from "pg"; +import { afterAll, beforeAll, describe, expect, test, vi } from "vitest"; + +const { withBranchPool } = vi.hoisted(() => ({ withBranchPool: vi.fn() })); + +vi.mock("../context", async (importOriginal) => ({ + ...(await importOriginal()), + withBranchPool, +})); + +import type { DbContext } from "../context"; +import { FORK_COPY_TAG } from "../schema-state"; +import { runVerify } from "../verify"; + +// Local verify against a real server: the Lakebase pool is replaced, nothing +// else. APPKIT_TEST_PG_URL points at a scratch database, e.g. +// postgres://localhost:5432/postgres +const url = process.env.APPKIT_TEST_PG_URL; +const builder = path.resolve( + import.meta.dirname, + "../../schema-builder/index.ts", +); +const BRANCH = "projects/p/branches/dev-alice-3f9a2c"; +const MIGRATION = { tag: "0000_migration", when: 1700000000000 }; + +describe.skipIf(!url)("runVerify against Postgres", () => { + const schema = `verify_${randomUUID().slice(0, 8)}`; + const journal = `"${schema}".__drizzle_migrations`; + let admin: Pool; + let ctx: DbContext; + + beforeAll(async () => { + admin = new Pool({ connectionString: url, max: 1 }); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-verify-pg-")); + const file = path.join(root, "config/database/schema.ts"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync( + file, + `import { defineSchema, id, text } from ${JSON.stringify(builder)}; + export const schema = defineSchema( + ({ table }) => ({ notes: table("notes", { id: id(), body: text() }) }), + { schemaName: ${JSON.stringify(schema)} }, + );`, + ); + const migrations = path.join(root, "config/database/migrations"); + fs.mkdirSync(path.join(migrations, "meta"), { recursive: true }); + const sql = `create table "${schema}".notes (id serial primary key, body text);\n`; + fs.writeFileSync(path.join(migrations, `${MIGRATION.tag}.sql`), sql); + fs.writeFileSync( + path.join(migrations, "meta/_journal.json"), + JSON.stringify({ + version: "7", + dialect: "postgresql", + entries: [ + { + idx: 0, + version: "7", + when: MIGRATION.when, + tag: MIGRATION.tag, + breakpoints: true, + }, + ], + }), + ); + // The branch as a fork copied it: the migration ran there and its journal records it. + await admin.query(` + create schema "${schema}"; + ${sql} + create table ${journal} (id serial primary key, hash text not null, created_at bigint); + `); + await admin.query( + `insert into ${journal} (hash, created_at) values ($1, $2)`, + [createHash("sha256").update(sql).digest("hex"), MIGRATION.when], + ); + ctx = { + root, + env: { + PGHOST: "ep-1.example.com", + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: `${BRANCH}/endpoints/primary`, + }, + workspace: () => { + throw new Error("no workspace calls expected"); + }, + api: () => { + throw new Error("no Lakebase API calls expected"); + }, + }; + withBranchPool.mockImplementation( + async (_ctx, fn: (pool: Pool) => Promise) => { + const pool = new Pool({ connectionString: url, max: 2 }); + try { + return await fn(pool); + } finally { + await pool.end(); + } + }, + ); + }); + + afterAll(async () => { + await admin.query(`drop schema if exists "${schema}" cascade`); + await admin.end(); + fs.rmSync(ctx.root, { recursive: true, force: true }); + }); + + test("tagged by init, the copy is reported as awaiting its rebuild, and the tag is not an unknown migration", async () => { + await admin.query( + `insert into ${journal} (hash, created_at) values ($1, 0)`, + [FORK_COPY_TAG], + ); + + expect(await runVerify(ctx)).toEqual({ + kind: "local", + branch: BRANCH, + schemaProblems: [], + schemaAdvice: null, + pendingMigrations: [], + strandedMigrations: [], + editedMigrations: [], + unknownMigrations: 0, + forkCopy: true, + ok: false, + }); + }); + + test("with the tag gone, the same branch verifies", async () => { + await admin.query(`delete from ${journal} where hash = $1`, [ + FORK_COPY_TAG, + ]); + + expect(await runVerify(ctx)).toMatchObject({ + unknownMigrations: 0, + forkCopy: false, + ok: true, + }); + }); +}); diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 6ee59a7bc..5b2da1447 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -14,6 +14,7 @@ vi.mock("../context", async (importOriginal) => ({ import type { WorkspaceRequest } from "../../../workspace-client"; import type { DbContext } from "../context"; +import { FORK_COPY_TAG } from "../schema-state"; import { runVerify, type VerifyOptions } from "../verify"; import { databricksYml, FakeLakebase } from "./fakes"; @@ -153,6 +154,11 @@ function branch(state: { if (/select hash, created_at from/.test(text)) { return { rows: state.recorded === "absent" ? [] : state.recorded }; } + // isForkCopy: whether the journal has the row init writes into a fork's copy. + if (/where hash = \$1 limit 1/.test(text)) { + const rows = state.recorded === "absent" ? [] : state.recorded; + return { rows: rows.filter((row) => row.hash === values?.[0]) }; + } return { rows: [] }; }), release: vi.fn(), @@ -195,6 +201,7 @@ describe("runVerify", () => { strandedMigrations: [], editedMigrations: [], unknownMigrations: 0, + forkCopy: false, }; test("a branch that matches schema.ts and has every migration is ok", async () => { @@ -293,6 +300,43 @@ describe("runVerify", () => { }); }); + test("a fork's copy whose rebuild did not finish is reported as one, and its tag is not an unknown migration", async () => { + const ctx = app(two); + branch({ + columns: { notes: ["id", "body"] }, + recorded: [ + ...recordedAs(ctx, two), + { hash: FORK_COPY_TAG, created_at: "0" }, + ], + }); + + expect(await runVerify(ctx)).toEqual({ + kind: "local", + branch: BRANCH, + ...clean, + forkCopy: true, + ok: false, + }); + }); + + test("on a fork's copy, a migration from another git branch still counts as unknown", async () => { + const ctx = app(two); + branch({ + columns: { notes: ["id", "body"] }, + recorded: [ + ...recordedAs(ctx, two), + { hash: FORK_COPY_TAG, created_at: "0" }, + { hash: "from-another-git-branch", created_at: "3000" }, + ], + }); + + expect(await runVerify(ctx)).toMatchObject({ + forkCopy: true, + unknownMigrations: 1, + ok: false, + }); + }); + test("a migration the branch ran that this checkout does not commit is reported", async () => { const ctx = app(two); branch({ From f3d58a02784a6938b39ac73bc0358e4a2dbee0fd Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:05:58 +0000 Subject: [PATCH 175/317] fix(appkit): report a fork copy awaiting its rebuild from local verify A branch that `appkit db init` forked keeps the tag row in its copied journal until the rebuild finishes. Local verify counted that row as a migration this checkout does not have, which pointed at clean and migrate, and migrate refuses such a branch. The report now reads the tag in the same read-only transaction, carries it as forkCopy, leaves it out of unknownMigrations, and is not ok while it stands. The shared tooling contract carries the field for the CLI. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/verify.ts | 16 ++++++++++++++-- .../src/cli/commands/db/tooling-contract.ts | 2 ++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index b4f48f570..cd0e83d21 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -23,6 +23,7 @@ import { withBranchPool, } from "./context"; import { requireSchemaFile } from "./migrate"; +import { isForkCopy } from "./schema-state"; import { type BundleTarget, defaultBundleTarget, @@ -54,6 +55,12 @@ interface LocalVerifyReport { readonly editedMigrations: readonly string[]; /** Migrations the branch ran that this checkout does not commit, e.g. from another git branch. */ readonly unknownMigrations: number; + /** + * The branch still holds the rows a fork copied into the app schema, tagged + * by `appkit db init`, and its rebuild did not finish. `appkit db migrate` + * refuses such a branch, so nothing on it is this checkout's work. + */ + readonly forkCopy: boolean; readonly ok: boolean; } @@ -130,10 +137,13 @@ async function verifyLocal(ctx: DbContext): Promise { await client.query("begin transaction read only"); const { problems: schemaProblems, advice: schemaAdvice } = await diagnoseSchema(rawOn(client), schema); + const forkCopy = await isForkCopy(client, schema.$schemaName); const drift = await readMigrationDrift(client, { migrationsFolder: migrationsFolder(ctx.root), schemaName: schema.$schemaName, }); + // The tag is one journal row no committed migration matches, so the drift counts it once. + const unknownMigrations = drift.unknown - (forkCopy ? 1 : 0); return { kind: "local", branch, @@ -142,13 +152,15 @@ async function verifyLocal(ctx: DbContext): Promise { pendingMigrations: drift.pending, strandedMigrations: drift.stranded, editedMigrations: drift.edited, - unknownMigrations: drift.unknown, + unknownMigrations, + forkCopy, ok: + !forkCopy && schemaProblems.length === 0 && drift.pending.length === 0 && drift.stranded.length === 0 && drift.edited.length === 0 && - drift.unknown === 0, + unknownMigrations === 0, }; } finally { await client.query("rollback").catch(() => undefined); diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 215024f2e..73bbaebe8 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -107,6 +107,8 @@ export interface LocalVerifyReport { readonly strandedMigrations: readonly string[]; readonly editedMigrations: readonly string[]; readonly unknownMigrations: number; + /** The branch still holds a fork's copy, tagged by `appkit db init`, and its rebuild did not finish. */ + readonly forkCopy: boolean; readonly ok: boolean; } From aab165eb889970d9eb568bc40e454c1636445cb9 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:07:16 +0000 Subject: [PATCH 176/317] test(shared): verify must tell a fork copy to rebuild with init, not to migrate With forkCopy set, the verdict line names the copied rows and the init advice migrate gives when it refuses, and no hint says migrate or clean. Co-authored-by: Isaac Signed-off-by: ditadi --- .../shared/src/cli/commands/db/verify.test.ts | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index 1d6b6e0fb..eb6e9dcaa 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -38,6 +38,7 @@ const local = { strandedMigrations: [], editedMigrations: [], unknownMigrations: 0, + forkCopy: false, ok: true, }; @@ -201,6 +202,34 @@ describe("appkit db verify", () => { expect(process.exitCode).toBe(1); }); + test("a fork's copy whose rebuild did not finish is told to rebuild with init, as migrate refuses it", async () => { + runVerify.mockResolvedValue({ ...local, forkCopy: true, ok: false }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(error)).toContain( + "dev-alice-3f9a2c still holds the rows the fork copied into the app schema, and its rebuild did not finish. Run `appkit db init` to rebuild it from the committed migrations, or `appkit db init --schema migrate` to keep them.", + ); + expect(output(error)).not.toContain("does not match"); + expect(process.exitCode).toBe(1); + }); + + test("on a fork's copy, pending migrations are listed, and the one next step is still init", async () => { + runVerify.mockResolvedValue({ + ...local, + pendingMigrations: ["0002_migration"], + forkCopy: true, + ok: false, + }); + + await dbCommand.parseAsync(["verify"], { from: "user" }); + + expect(output(log)).toContain("Pending migrations: 0002_migration"); + const printed = output(error); + expect(printed).toContain("Run `appkit db init` to rebuild it"); + expect(printed).not.toContain("`appkit db migrate`"); + }); + describe("--deployed", () => { const deploy = { kind: "deploy" as const, From be636e3d7bfdf61a597004f665ea6f9535752b04 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:08:27 +0000 Subject: [PATCH 177/317] fix(shared): tell a fork copy to rebuild with init from verify A copy can match schema.ts and the committed migrations and still not be yours, so its verdict line names the copied rows and the rebuild, with the same advice migrate gives when it refuses: `appkit db init`, or `appkit db init --schema migrate` to keep the rows. The other hints would point at migrate or clean, which refuse or lose the copy. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/shared/src/cli/commands/db/output.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index c41049381..469f70d84 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -171,6 +171,13 @@ function printLocalVerifyReport(report: LocalVerifyReport): void { `Not committed: the branch ran ${report.unknownMigrations} migration${one ? "" : "s"} this checkout does not have, for example from another git branch`, ); } + // A copy may match schema.ts and the journal; its rows are still not yours, and migrate refuses it. + if (report.forkCopy) { + console.error( + `${pc.red("✖")} ${branch} still holds the rows the fork copied into the app schema, and its rebuild did not finish. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema migrate\` to keep them.`, + ); + return; + } console.error( `${pc.red("✖")} ${branch} does not match config/database/schema.ts and the committed migrations. ${localVerifyHint(report)}`, ); From 61a3f76a92eab23a26f0701d75d2e8f158cab235 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:27:46 +0000 Subject: [PATCH 178/317] test(appkit): migrate on start needs PGUSER set to the app's client id Exported M2M credentials with no PGUSER skip instead of migrating. The Lakebase pool falls back to DATABRICKS_CLIENT_ID for the user, so a local process in that state would otherwise migrate as the service principal. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tests/migrate-on-start.test.ts | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index 4cfb296ad..1eee3f199 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -80,14 +80,14 @@ describe("decideMigrateOnStart", () => { }; const optIn = { APPKIT_DB_MIGRATE_ON_START: "true" }; - test.each([ - ["a deployed app that opts in", { ...optIn, ...credentials }], - [ - "a deployed app with a bound database: Apps sets PGUSER to its client id", - { ...optIn, ...credentials, PGUSER: "sp-client-id" }, - ], - ] as const)("%s migrates", (_label, env) => { - expect(decideMigrateOnStart(env)).toEqual({ kind: "migrate" }); + test("a deployed app with a bound database migrates. Apps sets PGUSER to its client id", () => { + expect( + decideMigrateOnStart({ + ...optIn, + ...credentials, + PGUSER: "sp-client-id", + }), + ).toEqual({ kind: "migrate" }); }); test.each([ @@ -125,6 +125,11 @@ describe("decideMigrateOnStart", () => { { ...optIn, ...credentials, PGUSER: "jane@example.com" }, `PGUSER is "jane@example.com", not the app's client id in DATABRICKS_CLIENT_ID.`, ], + [ + "exported M2M credentials and no PGUSER, where the pool would fall back to the service principal", + { ...optIn, ...credentials }, + "PGUSER is not set. The deployed app gets it from its database resource.", + ], ] as const)("%s: skipped, naming the reason", (_label, env, reason) => { expect(decideMigrateOnStart(env)).toEqual({ kind: "skipped", reason }); }); From f916f75aba83f283c8f1d8d82e23a67bfaf0d281 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:29:12 +0000 Subject: [PATCH 179/317] fix(appkit): migrate on start needs PGUSER set to the app's client id decideMigrateOnStart migrated when PGUSER was unset. The Lakebase pool then falls back to DATABRICKS_CLIENT_ID for the user, so a local process with exported M2M credentials and no PGUSER connected as the service principal and migrated. Databricks Apps sets PGUSER to the client id for every app with a bound database, so an unset PGUSER now skips with a reason that says where the deployed app gets it. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/plugins/database/migrate-on-start.ts | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index 230a2c5f2..5403b85eb 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -24,17 +24,19 @@ const logger = createLogger("database"); export type MigrateOnStartDecision = /** APPKIT_DB_MIGRATE_ON_START is not "true": a local start, or an app that never opted in. */ | { readonly kind: "off" } - /** The flag is on, but this process does not run as the app's own service principal. */ + /** The flag is on, but the environment is not the one Apps gives a deployed app with a bound database. */ | { readonly kind: "skipped"; readonly reason: string } | { readonly kind: "migrate" }; /** * Migrate on start only when the app opted in with APPKIT_DB_MIGRATE_ON_START=true - * (app.yaml) and the process runs as the app's own service principal. Databricks - * Apps sets DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET and, for a bound - * database, PGUSER (the client id) for the deployed app. A local start, or - * `databricks apps run-local` with exported M2M credentials, has the developer's - * PGUSER from `.env`, and must not migrate as them. + * (app.yaml) and the process has the identity Databricks Apps gives a deployed + * app with a bound database. That is DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET + * and PGUSER set to the client id. A local start, or `databricks apps run-local` + * with exported M2M credentials, has the developer's PGUSER from `.env` or none + * at all, and must not migrate. An unset PGUSER skips because the Lakebase pool + * then falls back to the client id, and a developer's process would migrate as + * the service principal. */ export function decideMigrateOnStart( env: NodeJS.ProcessEnv = process.env, @@ -43,7 +45,14 @@ export function decideMigrateOnStart( for (const name of ["DATABRICKS_CLIENT_ID", "DATABRICKS_CLIENT_SECRET"]) { if (!env[name]) return { kind: "skipped", reason: `${name} is not set.` }; } - if (env.PGUSER && env.PGUSER !== env.DATABRICKS_CLIENT_ID) { + if (!env.PGUSER) { + return { + kind: "skipped", + reason: + "PGUSER is not set. The deployed app gets it from its database resource.", + }; + } + if (env.PGUSER !== env.DATABRICKS_CLIENT_ID) { return { kind: "skipped", reason: `PGUSER is "${env.PGUSER}", not the app's client id in DATABRICKS_CLIENT_ID.`, From b6d9b02979fea25cf1e4cdfcc75ce4a22814dcd3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:31:50 +0000 Subject: [PATCH 180/317] docs(appkit): state migrate on start as the PGUSER identity rule A start migrates only when PGUSER is set and equals DATABRICKS_CLIENT_ID. The database plugin docs and the template README said a local start never migrates because it is not a deployment. Say it as the identity rule instead, and that db init writes the developer's PGUSER, so a local start or run-local connects as them and skips. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 14 ++++++++------ template/README.md.tmpl | 10 ++++++---- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 20b66df48..5e391cdf0 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -362,12 +362,14 @@ env: value: "true" ``` -The flag alone does not migrate. A start migrates only when the process -connects as the deployed app's own service principal, which is when `PGUSER` -equals `DATABRICKS_CLIENT_ID`. Databricks Apps sets both for a bound database. -A local start (`npm run dev`, `npm start`) connects as you, so it does not -migrate, and `databricks apps run-local` does not migrate either, even with -exported M2M credentials. Both log why. Use `npx appkit db migrate` on your +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. diff --git a/template/README.md.tmpl b/template/README.md.tmpl index d427dc3e3..c9a7b5e7b 100644 --- a/template/README.md.tmpl +++ b/template/README.md.tmpl @@ -81,10 +81,12 @@ npx appkit db verify # read-only check of your branch against schema.ts and t ``` Commit the migrations. The deployed app applies them on start, because `app.yaml` -sets `APPKIT_DB_MIGRATE_ON_START=true`, and only when it connects as its own -service principal, so a local start or `databricks apps run-local` never -migrates. The deploy waits for `/health`, which the app serves only after its -migrations, for up to 300 seconds, so a failed migration fails the deploy. +sets `APPKIT_DB_MIGRATE_ON_START=true`, and only when `PGUSER` is set and equals +`DATABRICKS_CLIENT_ID`, which Databricks Apps sets for the deployed app. `db init` +writes your user name to `PGUSER` in `.env`, so a local start, `databricks apps +run-local` included, connects as you and never migrates. The deploy waits for +`/health`, which the app serves only after its migrations, for up to 300 seconds, +so a failed migration fails the deploy. To adopt tables that already exist, run `npx appkit db init --schema introspect`. It writes `schema.ts` from the branch's tables, and a `0000_baseline` migration (or `NNNN_introspect` when migrations From 9f606192d0bdc85cf0d6c8b1b9b3c78ad860631f Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:32:21 +0000 Subject: [PATCH 181/317] docs(appkit): take the full ownership inventory before delete-role The one owner per branch runbook listed only pg_class objects before the role delete. Use the inventory db init takes before a hand-off instead: every object the role owns in the current database through pg_shdepend and pg_identify_object, run in each database, plus what it owns or is granted in other databases and shared objects. Say that the delete also drops the role's memberships and grants, and to resolve anything unrelated to the app first. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 36 ++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 5e391cdf0..609d191ca 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -542,17 +542,39 @@ 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. That moves every object the role owns on the -branch and deletes the role, so first list what it owns, in each database of the -branch: +and reassigning what it owns. The delete reassigns every object the role owns +in every database of the branch, drops the role's memberships and grants, and +removes the role. 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 n.nspname, c.relname, c.relkind - from pg_class c - join pg_namespace n on n.oid = c.relnamespace - where pg_get_userbyid(c.relowner) = ''; +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 From eee9a10cbc12e30586250fd519045675c96236de Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:33:48 +0000 Subject: [PATCH 182/317] docs(appkit): describe the created-branch rebuild, copy refusals and --schema clean after a keep Add three facts of the fork-copy rule to the database docs and the template README. A branch the same init run created is rebuilt even when its app schema was already yours. migrate, introspect and seed refuse an untouched copy as well as a tagged one. After keeping the copied rows, the schema is yours and appkit db init --schema clean removes them. Fold the two keep-copy paragraphs that the merge of the init layer left side by side into one. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 61 ++++++++++++++++++----------------- template/README.md.tmpl | 17 ++++++---- 2 files changed, 42 insertions(+), 36 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 609d191ca..9a2454d62 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -161,16 +161,20 @@ you picked in its prompts, usually the branch the app deploys to, and 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. 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 is already yours, `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. `--schema clean` drops the app schema first. - Without a terminal, `--schema clean` needs `--yes`. `--schema none` only - sets up the branch and `.env`. It reads no `schema.ts`, hands over no + 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, so the next plain `init` still rebuilds it. 4. Unless `--schema none`, it installs the drizzle-kit version AppKit pins as a @@ -256,27 +260,26 @@ On an untouched copy, `init` tags the copied migration journal with one row, hands you the schema, then drops the schema and rebuilds it from the committed migrations. 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. Dropping the schema removes the tag. A run that stops after tagging -and before the rebuild leaves the tag in place, and the next `init`, from any -checkout, reads it and finishes the rebuild. `npx appkit db migrate`, -`introspect` and `seed` refuse a branch that still carries the tag, and -`npx appkit db verify` reports it. Run `init` to finish the rebuild. +baseline. A branch this `init` run created is rebuilt the same way even when +its app schema was already yours, because every row on it is the fork's copy. +A rebuild asks nothing, because none of your work can be on a copy. Dropping +the schema removes the tag. A run that stops after tagging and before the +rebuild leaves the tag in place, and the next `init`, from any checkout, reads +it and finishes the rebuild. `npx appkit db migrate`, `introspect` and `seed` +refuse an untouched copy and a branch that still carries the tag, and tell you +to run `init`. `npx appkit db verify` reports a branch that still carries the +tag. To keep the copied rows on a new branch, pass `--schema migrate`, or -`--schema introspect` without `schema.ts`, and `init` says that it kept them. A -branch whose app schema is already yours keeps its data. `init` migrates it, or -introspects it without `schema.ts`. `--schema clean` rebuilds such a branch -too, after a confirmation or with `--yes`. `--schema none` leaves the schema -and its owner as the fork copied them, so the next plain `init` still rebuilds. - -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. A schema you own with no such row is your working branch. -`init` migrates it, or introspects it without `schema.ts`. `--schema clean` -rebuilds your working branch too, after a confirmation or with `--yes`. A -copy's rebuild asks nothing, because `migrate` refuses a copy, so none of your -work can be on it. `--schema none` touches nothing, and the next plain `init` -still rebuilds the copy. +`--schema introspect` without `schema.ts`. `init` then hands the schema to you, +keeps the rows, removes any tag, and says where the rows came from. The schema +is yours from then on. A later plain `init` migrates it and keeps the rows, and +`npx appkit db init --schema clean` removes them. It asks for a confirmation, or +needs `--yes`, and drops the app schema with everything in it. A branch whose +app schema was already yours before this run keeps its data the same way. +`init` migrates it, or introspects it without `schema.ts`. `--schema none` +leaves the schema and its owner as the fork copied them, so the next plain +`init` still rebuilds. 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 diff --git a/template/README.md.tmpl b/template/README.md.tmpl index c9a7b5e7b..a43dd0728 100644 --- a/template/README.md.tmpl +++ b/template/README.md.tmpl @@ -65,13 +65,16 @@ npx appkit db init --session # a branch for this checkout that expires after 7 npx appkit db init --dev # back to your dev branch ``` -A new branch is a copy of its source, production data included. When the app -schema on the branch still belongs to the copied service principal, `db init` -hands it to you and rebuilds it from the committed migrations, so its tables -start empty. Other schemas keep the copied rows. A branch whose app schema is -already yours keeps its rows, and `db init` migrates it. To keep the copied -rows in the app schema on a new branch too, run -`npx appkit db init --schema migrate`. +A new branch is a copy of its source, production data included. On a branch +`db init` just created, or whose app schema still belongs to the copied service +principal, `db init` hands the schema to you and rebuilds it from the committed +migrations, so its tables start empty. Other schemas keep the copied rows. A +branch whose app schema was already yours before that run keeps its rows, and +`db init` migrates it. To keep the copied rows in the app schema on a new branch +too, run `npx appkit db init --schema migrate`. The rows are yours from then on, +and `npx appkit db init --schema clean` removes them. `db migrate`, +`db introspect` and `db seed` refuse a copy until `db init` rebuilt it or kept +its rows. To change the schema, edit `config/database/schema.ts`, then: From a8c94cfff02ef0a88786e41865c53870c573bf10 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:37:49 +0000 Subject: [PATCH 183/317] test(appkit): pin how init, migrate, introspect and seed treat a fork's copy Four Postgres regressions from the review of design 001, failing before their fixes. The fork-copy tag must not be written into a journal owned by a role the migrator does not trust. A fork this run created is a copy even when you already owned the source schema, so init rebuilds it. migrate, introspect and seed refuse an untouched copy as well as a tagged one. After keeping the copied rows, a plain init keeps them and only --schema clean removes them, which the CLI warning now says. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/init.pg.test.ts | 75 +++++++++++++++++++ .../tooling/tests/schema-state.pg.test.ts | 42 ++++++++++- .../cli/commands/db/init-clean-seed.test.ts | 5 +- 3 files changed, 118 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/init.pg.test.ts b/packages/appkit/src/database/tooling/tests/init.pg.test.ts index 031a5fafe..d517f580d 100644 --- a/packages/appkit/src/database/tooling/tests/init.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.pg.test.ts @@ -322,6 +322,34 @@ describe.skipIf(!url)("runInit against Postgres", () => { expect(await rows(`"${app}".notes`)).toEqual([{ body: "mine" }]); }); + test("a fork of a source whose app schema you already owned is a copy too: rebuilt without a hand-off, so the copied rows go", async () => { + await applyPendingMigrations(asDev, { + migrationsFolder: folder(root), + schemaName: app, + }); + await asDev.query(`insert into "${app}".notes (body) values ('copied')`); + + const { report, steps } = await init(context(root)); + + expect(report).toMatchObject({ + created: true, + sourceBranch: PRODUCTION, + handedOff: null, + keptCopy: null, + start: { kind: "clean", migrate: { applied: ["0000_migration"] } }, + }); + expect(steps).toContain( + `Dropping schema ${app} on ${devBranchId(USER)}: the branch still holds the rows the fork copied, and the committed migrations recreate its tables`, + ); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + expect(await rows(`"${app}".notes`)).toEqual([]); + expect(await journal(app)).toEqual([ + hashOf(folder(root), "0000_migration"), + ]); + }); + test("--schema none touches nothing, and the next plain init still rebuilds", async () => { await deployed(root, app, `"${app}".notes`); @@ -363,6 +391,53 @@ describe.skipIf(!url)("runInit against Postgres", () => { expect(await journal(app)).toEqual([ hashOf(folder(root), "0000_migration"), ]); + + // The schema is yours now. A plain init keeps the rows; only --schema clean removes them, after asking. + const kept = await init(onDev(root)); + expect(kept.report.start.kind).toBe("migrate"); + expect(await rows(`"${app}".notes`)).toEqual([{ body: "copied" }]); + + const asked: string[] = []; + const cleaned = await init(onDev(root), { + schema: "clean", + confirmClean: async ({ schemaName }) => { + asked.push(schemaName); + return true; + }, + }); + expect(asked).toEqual([app]); + expect(cleaned.report.start.kind).toBe("clean"); + expect(await rows(`"${app}".notes`)).toEqual([]); + }); + + test("migrate, introspect and seed refuse an untouched copy the service principal still owns", async () => { + await deployed(root, app, `"${app}".notes`); + existingDev(lakebase); + lakebase.addRole(DEV, `dbrx-apps-${sp}`, sp); + const ctx = onDev(root); + const refusal = `${devBranchId(USER)} still holds the rows the fork copied into schema "${app}", which "${sp}" still owns. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema`; + + await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( + `Did not apply: ${refusal} migrate\` to keep them.`, + ); + const introspect = runIntrospect(ctx, { interactive: false }); + await expect(introspect).rejects.toBeInstanceOf(IntrospectRefusedError); + await expect(introspect).rejects.toThrow( + `Refusing to introspect: ${refusal} introspect\` to keep them.`, + ); + fs.writeFileSync( + path.join(root, SEED_FILE), + `insert into notes (body) values ('seeded');`, + ); + try { + await expect(runSeed(ctx)).rejects.toThrow( + `Refusing to seed: ${refusal} migrate\` to keep them.`, + ); + } finally { + fs.rmSync(path.join(root, SEED_FILE)); + } + expect(await ownerOf(app)).toBe(sp); + expect(await rows(`"${app}".notes`)).toEqual([{ body: "copied" }]); }); test("migrate, introspect and seed refuse a branch whose journal still carries the tag", async () => { diff --git a/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts index f9bf68f48..51a5da423 100644 --- a/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts @@ -33,13 +33,17 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { const app = `app_${suffix}`; const bare = `bare_${suffix}`; const shared = `shared_${suffix}`; + /** A role that is neither you, a role you inherit, nor the schema's owner. */ + const other = `appkit_other_${suffix}`; + /** The service principal's schema with a journal `other` owns. */ + const foreign = `foreign_${suffix}`; let admin: Pool; let me: Pool; - const journalRows = async () => + const journalRows = async (schema = app) => ( await admin.query<{ hash: string; created_at: string }>( - `select hash, created_at::text from "${app}".__drizzle_migrations order by id`, + `select hash, created_at::text from "${schema}".__drizzle_migrations order by id`, ) ).rows; @@ -47,6 +51,7 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { admin = new Pool({ connectionString: url, max: 1 }); await admin.query(` create role "${sp}" nologin; + create role "${other}" nologin; create role "${superuser}" nologin; grant pg_read_all_data, pg_write_all_data to "${superuser}"; create role "${dev}" login password 'appkit'; @@ -54,6 +59,10 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { grant create on database ${(await admin.query("select current_database() as db")).rows[0]?.db} to "${sp}"; create schema "${app}" authorization "${sp}"; create schema "${bare}" authorization "${sp}"; + create schema "${foreign}" authorization "${sp}"; + create table "${foreign}".__drizzle_migrations (id serial primary key, hash text not null, created_at bigint); + insert into "${foreign}".__drizzle_migrations (hash, created_at) values ('abc', 1700000000000); + alter table "${foreign}".__drizzle_migrations owner to "${other}"; set role "${sp}"; create table "${app}".notes (id integer primary key, body text); insert into "${app}".notes values (1, 'copied'); @@ -71,13 +80,16 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { await admin.query(` drop schema if exists "${app}" cascade; drop schema if exists "${bare}" cascade; + drop schema if exists "${foreign}" cascade; drop table if exists public."${shared}"; reassign owned by "${sp}" to current_user; drop owned by "${sp}"; + drop owned by "${other}"; drop owned by "${dev}"; drop role if exists "${dev}"; drop role if exists "${superuser}"; drop role if exists "${sp}"; + drop role if exists "${other}"; `); await admin.end(); }); @@ -139,6 +151,32 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { }); }); + test("a journal owned by a role you neither are nor inherit, and that does not own the schema, is never written", async () => { + // pg_write_all_data lets you insert there, so only the trust rule stops the write. + const before = await journalRows(foreign); + await expect(tagForkCopy(me, foreign)).resolves.toBe(false); + expect(await journalRows(foreign)).toEqual(before); + + await admin.query( + `insert into "${foreign}".__drizzle_migrations (hash, created_at) values ($1, 0)`, + [FORK_COPY_TAG], + ); + await untagForkCopy(me, foreign); + expect(await journalRows(foreign)).toEqual([ + ...before, + { hash: FORK_COPY_TAG, created_at: "0" }, + ]); + // Without row-level security a read runs no code of the owner's, so the tag is read. + await expect(isForkCopy(me, foreign)).resolves.toBe(true); + + // With it, a policy of the owner's would run on the read, so the journal is not read. + await admin.query(` + alter table "${foreign}".__drizzle_migrations enable row level security; + create policy everything on "${foreign}".__drizzle_migrations using (true); + `); + await expect(isForkCopy(me, foreign)).resolves.toBe(false); + }); + test("public is never a copy: it lists what other roles own there", async () => { const state = await readSchemaState(me, "public"); expect(state.kind).toBe("public"); diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index f1a0eab3d..617b9b650 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -288,7 +288,7 @@ describe("appkit db init", () => { expect(output(log)).not.toContain("The branch still held the rows"); }); - test("copied rows kept on request are a warning that names their source and the flag", async () => { + test("copied rows kept on request are a warning that names their source, the flag, and the clean that removes them", async () => { tooling.runInit.mockResolvedValue({ ...report, keptCopy: { @@ -298,8 +298,9 @@ describe("appkit db init", () => { }); await init("--schema", "migrate"); + // The schema is yours after a keep, so a plain init migrates it and keeps the rows. expect(output(log)).toContain( - "Kept the rows the fork copied from production, as --schema migrate asks. A plain `appkit db init` rebuilds the app schema from the committed migrations without them.", + "Kept the rows the fork copied from production, as --schema migrate asks. The app schema is yours now, so a plain `appkit db init` keeps them. `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.", ); }); From 89409844f49c9df43ad309b43ad9b8764083e2b0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:39:46 +0000 Subject: [PATCH 184/317] docs(appkit): drop comments that restate the migrate warning code Eight comments this round added or changed in appkit db migrate, its statement classes and the shared CLI output restate the name, type or body next to them, so they go. The note on addsConstrainedColumn stays. It records the Postgres semantics behind the AS IDENTITY exclusion, which the code cannot show. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/migrate.ts | 7 ------- packages/appkit/src/database/tooling/migrations.ts | 6 ------ .../appkit/src/database/tooling/tests/migrations.test.ts | 1 - packages/shared/src/cli/commands/db/output.ts | 2 -- 4 files changed, 16 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index bc18e6dd2..a97d85c49 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -57,7 +57,6 @@ export interface MigrateReport { readonly adopted?: readonly string[]; /** Statements of the generated migration that break instances still running the previous release. */ readonly breaking?: readonly string[]; - /** Statements of the generated migration that may fail on rows the deploy branch has and a new branch does not. */ readonly dataDependent?: readonly string[]; /** Why nothing was applied, when applying was skipped. */ readonly notApplied?: string; @@ -71,7 +70,6 @@ export interface MigrateOptions { type ApplyOutcome = Pick; -/** What a generated migration's statements warn about; either list may be empty. */ type MigrationWarnings = Required< Pick >; @@ -86,11 +84,6 @@ function migrationWarnings( }; } -/** - * The run wrote a migration and then failed before applying it. The file - * stays for the next run, which generates nothing new, so this is the only - * run that can warn about the migration. - */ class UnappliedMigrationError extends Error implements MigrationWarnings { readonly generated: GeneratedMigration; readonly breaking: readonly string[]; diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 36a56c2de..233525857 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -288,7 +288,6 @@ const BREAKS_PREVIOUS_RELEASE: readonly StatementPredicate[] = [ addsRequiredColumn, ]; -/** Postgres checks each of these against the rows already in the table, so a table with no rows never fails them. */ const MAY_FAIL_ON_EXISTING_ROWS: readonly StatementPredicate[] = [ matches(/\bSET NOT NULL\b/i), matches(/\bSET DATA TYPE\b/i), @@ -316,11 +315,6 @@ export function breakingStatements(statements: readonly string[]): string[] { return statementsWhere(BREAKS_PREVIOUS_RELEASE, statements); } -/** - * Statements whose success depends on the rows already in the table. A new - * dev branch has none, so they pass there and can fail on the deploy branch. - * A statement can be in this class and in breakingStatements. - */ export function dataDependentStatements( statements: readonly string[], ): string[] { diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index 85bdda9d2..89d8b0f2a 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -417,7 +417,6 @@ describe("dataDependentStatements", () => { `ALTER TABLE "app"."notes" ADD COLUMN "title" text DEFAULT 'untitled' NOT NULL;`, 'ALTER TABLE "app"."notes" ADD COLUMN "words" integer GENERATED ALWAYS AS (length("body")) STORED NOT NULL;', 'ALTER TABLE "app"."notes" ADD COLUMN "seq" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY (sequence name "app"."notes_seq_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1);', - // What id() adds to an existing table; the identity fills every row. 'ALTER TABLE "app"."notes" ADD COLUMN "id" integer PRIMARY KEY NOT NULL GENERATED BY DEFAULT AS IDENTITY (sequence name "app"."notes_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1);', 'ALTER TABLE "app"."notes" ALTER COLUMN "title" DROP NOT NULL;', `ALTER TABLE "app"."notes" ALTER COLUMN "title" SET DEFAULT 'untitled';`, diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 9ece2108f..ec23aa0a0 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -42,10 +42,8 @@ export function fail(error: unknown): void { process.exitCode = 1; } -/** What a written migration's statements warn about; an absent list means none. */ type MigrationWarnings = Pick; -/** One warning per class of statement in a written migration. */ export function warnMigration(tag: string, warnings: MigrationWarnings): void { if (warnings.breaking?.length) { warn( From 0082fbf00bbc0f036f1f55090629287dc2720354 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:41:29 +0000 Subject: [PATCH 185/317] fix(appkit): make migrate, introspect and seed refuse an untouched fork copy They checked only the fork-copy tag, so a copy the service principal still owned, with no tag yet, took writes. appkit db seed could add rows on top of the copy through DATABRICKS_SUPERUSER, and the next init dropped them. The three commands now read the schema's state and refuse a copy as well as a handed-off copy. The refusal names the owner for an untouched copy and the stopped rebuild for a tagged one, and gives the same advice for both. init's rebuild still reads a copy with record: false, since that writes nothing on the branch. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/introspect/index.ts | 20 +++-- .../introspect/tests/introspect.test.ts | 40 ++++++++++ .../appkit/src/database/tooling/migrate.ts | 15 ++-- .../src/database/tooling/schema-state.ts | 18 ++++- packages/appkit/src/database/tooling/seed.ts | 14 ++-- .../database/tooling/tests/clean-seed.test.ts | 80 ++++++++++++------- .../database/tooling/tests/migrate.test.ts | 28 ++++++- 7 files changed, 161 insertions(+), 54 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 4869ae566..6f5e6d6d5 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -25,7 +25,7 @@ import { type GeneratedMigration, generateMigrationFiles, } from "../migrations"; -import { forkCopyRefusal, isForkCopy } from "../schema-state"; +import { forkCopyRefusal, readSchemaState } from "../schema-state"; import { resourceId } from "../targets"; import { readCatalog, readUnreadObjects } from "./catalog"; import { @@ -45,8 +45,9 @@ export interface IntrospectOptions { readonly importSource?: string; /** * false: write schema.ts and its migration without recording the migration - * on the branch, for init's rebuild, which drops the schema right after. - * Default true. + * on the branch, for init's rebuild, which drops the schema right after. It + * is the one read of a fork's copy that is not refused, since it writes + * nothing on the branch. Default true. */ readonly record?: boolean; } @@ -223,10 +224,17 @@ export async function introspectHolding( const record = options.record ?? true; return withBranchPool(ctx, async (pool) => { - if (await isForkCopy(pool, schemaName)) { - throw new IntrospectRefusedError( - `Refusing to introspect: ${forkCopyRefusal(env.branch.name, schemaName, "introspect")}`, + // init's rebuild reads the copy without recording, then drops it. + if (record) { + 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 diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 09ab0ae11..46d792d1b 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -80,6 +80,8 @@ let catalog: ReturnType; let recorded: Array<{ when: number; hash: string }>; /** The journal carries init's fork-copy tag. */ let tagged: boolean; +/** Who owns the app schema; the connected role unless a test says otherwise. */ +let schemaOwner: string; /** The row the branch records for the last committed migration. */ const lastCommitted = (root: string) => { const folder = path.join(root, MIGRATIONS); @@ -103,6 +105,13 @@ const pool = { 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 }) => ({ @@ -120,6 +129,7 @@ beforeEach(() => { catalog = catalogResponder(); recorded = []; tagged = false; + schemaOwner = "app-sp"; resolveEnvBranch.mockReset().mockResolvedValue(onDevBranch); withBranchPool .mockReset() @@ -356,6 +366,36 @@ describe("runIntrospect", () => { 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("record: 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, + record: false, + }); + + expect(report.migration).toMatchObject({ tag: "0000_baseline" }); + expect(markMigrationsApplied).not.toHaveBeenCalled(); + }); + test("record: false writes schema.ts and the migration, and records nothing on the branch", async () => { const root = tempApp({ [SCHEMA]: declaredSchema }); diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 60a0c2c4d..5fcfecad1 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -29,7 +29,7 @@ import { type GeneratedMigration, generateMigrationFiles, } from "./migrations"; -import { forkCopyRefusal, isForkCopy } from "./schema-state"; +import { forkCopyRefusal, readSchemaState } from "./schema-state"; /** Whether the checkout has a config/database/schema.ts yet. */ export function hasSchemaFile(root: string): boolean { @@ -147,12 +147,13 @@ async function applyToEnvBranch( ); } return withBranchPool(ctx, async (pool) => { - // A migration on top of the fork's copy would make its rows yours to keep. - if (await isForkCopy(pool, schema.$schemaName)) { - throw new Error( - `Did not apply: ${forkCopyRefusal(env.branch.name, schema.$schemaName, "migrate")}`, - ); - } + const refusal = forkCopyRefusal( + env.branch.name, + schema.$schemaName, + await readSchemaState(pool, schema.$schemaName), + "migrate", + ); + if (refusal) throw new Error(`Did not apply: ${refusal}`); // The deployed app refuses this case on start; refuse it here first. const leftInPublic = await detectTablesLeftInPublic( catalogSqlOf(pool), diff --git a/packages/appkit/src/database/tooling/schema-state.ts b/packages/appkit/src/database/tooling/schema-state.ts index 86caead78..9f2716a58 100644 --- a/packages/appkit/src/database/tooling/schema-state.ts +++ b/packages/appkit/src/database/tooling/schema-state.ts @@ -186,11 +186,23 @@ export function planStart( } } -/** Why a command that writes on the branch refuses one that still holds a fork's copy. */ +/** + * Why a command that writes on the branch refuses a schema that still holds a + * fork's copy, untouched or handed off; undefined for any other state. A write + * on top of the copy would make its rows yours to keep. + */ export function forkCopyRefusal( branch: string, schemaName: string, + state: SchemaState, keep: "migrate" | "introspect", -): string { - return `${resourceId(branch)} still holds the rows the fork copied into schema "${schemaName}", and its rebuild did not finish. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema ${keep}\` to keep them.`; +): string | undefined { + if (state.kind !== "copy" && state.kind !== "handed-off-copy") { + return undefined; + } + const holds = + state.kind === "copy" + ? `which "${state.owner}" still owns` + : "and its rebuild did not finish"; + return `${resourceId(branch)} still holds the rows the fork copied into schema "${schemaName}", ${holds}. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema ${keep}\` to keep them.`; } diff --git a/packages/appkit/src/database/tooling/seed.ts b/packages/appkit/src/database/tooling/seed.ts index 510dd2c44..9d08c2a51 100644 --- a/packages/appkit/src/database/tooling/seed.ts +++ b/packages/appkit/src/database/tooling/seed.ts @@ -8,7 +8,7 @@ import { runInTransaction } from "./branch-sql"; import type { DbContext } from "./context"; import { writableEnvBranch } from "./guard"; import { hasSchemaFile } from "./migrate"; -import { forkCopyRefusal, isForkCopy } from "./schema-state"; +import { forkCopyRefusal, readSchemaState } from "./schema-state"; export const SEED_FILE = "config/database/seed.sql"; @@ -40,11 +40,13 @@ export async function runSeed(ctx: DbContext): Promise { : `${quoteIdentifier(schemaName)}, public`; const sql = fs.readFileSync(file, "utf-8"); await runInTransaction(ctx, async (client) => { - if (await isForkCopy(client, schemaName)) { - throw new Error( - `Refusing to seed: ${forkCopyRefusal(branch.name, schemaName, "migrate")}`, - ); - } + const refusal = forkCopyRefusal( + branch.name, + schemaName, + await readSchemaState(client, schemaName), + "migrate", + ); + if (refusal) throw new Error(`Refusing to seed: ${refusal}`); await client.query(`SET LOCAL search_path TO ${searchPath}`); // One simple-protocol query: the file may hold several statements. await client.query(sql); diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index ca3b57485..a5ac3dce6 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -35,31 +35,61 @@ const schemaFile = (schemaName: string) => export const schema = defineSchema(({ table }) => ({ notes: table("notes", { id: id() }) }), { schemaName: ${JSON.stringify(schemaName)} });`; const DEPENDENTS = /pg_catalog\.pg_depend/; -/** The journal check and the tag read of isForkCopy. */ -const FORK_COPY = /c\.relkind = 'r'|where hash = \$1/; - -/** A pool whose one client records statements, can fail on one, and answers the dependents query. */ +const ME = "alice@example.com"; +/** The reads of readSchemaState: the schema's owner, the journal, its tag, and what public keeps. */ +const SCHEMA_OWNER = /has_schema_privilege/; +const JOURNAL = /c\.relname = \$2/; +const TAG = /where hash = \$1/; +const KEPT_IN_PUBLIC = /nspname = 'public'/; + +/** + * A pool whose one client records statements, can fail on one, and answers + * the dependents query. The app schema is yours unless `schemaOwner` names + * another role. The reads of the schema's state are answered, not recorded. + */ function recordingPool( - options: { failOn?: RegExp; dependents?: string[]; forkCopy?: boolean } = {}, + options: { + failOn?: RegExp; + dependents?: string[]; + schemaOwner?: string; + } = {}, ) { const statements: string[] = []; const client = { released: undefined as { error: unknown } | undefined, async query(text: string) { - statements.push( - DEPENDENTS.test(text) - ? "" - : FORK_COPY.test(text) - ? "" - : text, - ); + if (SCHEMA_OWNER.test(text)) { + return { + rows: [ + { + owner: options.schemaOwner ?? ME, + can_create: true, + current_user: ME, + }, + ], + }; + } + if (JOURNAL.test(text)) { + return { + rows: [ + { + relkind: "r", + owner: ME, + schema_owner: ME, + current_user: ME, + row_security: false, + trusted: true, + }, + ], + }; + } + if (TAG.test(text) || KEPT_IN_PUBLIC.test(text)) return { rows: [] }; + statements.push(DEPENDENTS.test(text) ? "" : text); if (options.failOn?.test(text)) throw new Error("boom"); return { rows: DEPENDENTS.test(text) ? (options.dependents ?? []).map((label) => ({ label })) - : FORK_COPY.test(text) && options.forkCopy - ? [{}] - : [], + : [], }; }, release(error?: unknown) { @@ -244,27 +274,21 @@ describe("runSeed", () => { expect(writableEnvBranch).toHaveBeenCalledWith(expect.anything(), "seed"); expect(statements).toEqual([ "begin", - "", 'SET LOCAL search_path TO "app", public', sql, "commit", ]); }); - test("refuses a branch that still holds a fork's copy, before running the file", async () => { + test("refuses a branch whose app schema is still the fork's untouched copy, before running the file", async () => { const root = tempApp({ [SEED_FILE]: "insert into notes default values;" }); writableEnvBranch.mockResolvedValue(devBranch); - const { statements } = recordingPool({ forkCopy: true }); + const { statements } = recordingPool({ schemaOwner: "app-sp" }); await expect(runSeed(fakeContext({ root }))).rejects.toThrow( - 'Refusing to seed: 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 migrate` to keep them.', + 'Refusing to seed: dev-alice-3f9a2c still holds the rows the fork copied into schema "app", which "app-sp" still owns. Run `appkit db init` to rebuild it from the committed migrations, or `appkit db init --schema migrate` to keep them.', ); - expect(statements).toEqual([ - "begin", - "", - "", - "rollback", - ]); + expect(statements).toEqual(["begin", "rollback"]); }); test.each([ @@ -282,11 +306,7 @@ describe("runSeed", () => { await runSeed(fakeContext({ root })); - expect(statements.slice(0, 3)).toEqual([ - "begin", - "", - searchPath, - ]); + expect(statements.slice(0, 2)).toEqual(["begin", searchPath]); }, ); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 4393059ec..2e9390057 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -76,8 +76,10 @@ const devBranch = { kind: "dev", }; -/** A branch whose journal is not an ordinary table, so it is no fork's copy. */ -const pool = { query: vi.fn(async () => ({ rows: [] })) }; +/** A branch without the app schema yet, so it is no fork's copy. */ +const pool = { + query: vi.fn(async (_text: string) => ({ rows: [] as unknown[] })), +}; beforeEach(() => { applyPendingMigrations.mockReset(); @@ -125,6 +127,28 @@ describe("runMigrate", () => { expect(fs.existsSync(report.typesFile)).toBe(true); }); + test("does not apply on top of the fork's untouched copy, which another role still owns", async () => { + const ctx = app(`notes: table("notes", { id: id(), body: text() })`); + pool.query.mockImplementationOnce(async () => ({ + rows: [ + { + owner: "app-sp", + can_create: true, + current_user: "alice@example.com", + }, + ], + })); + + const error = await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + ); + + expect((error as Error).message).toContain( + 'Did not apply: dev-alice-3f9a2c still holds the rows the fork copied into schema "app", which "app-sp" still owns. Run `appkit db init` to rebuild it from the committed migrations, or `appkit db init --schema migrate` to keep them.', + ); + expect(applyPendingMigrations).not.toHaveBeenCalled(); + }); + test("does not apply when the implicit app schema would shadow tables left in public", async () => { const ctx = app(`notes: table("notes", { id: id(), body: text() })`); detectTablesLeftInPublic.mockResolvedValue( From 4f565a7e29f79bbce06efe89e98ad9a9142cd292 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:41:43 +0000 Subject: [PATCH 186/317] docs(appkit): drop comments that narrate the migration code The comment audit of this fix round flagged 24 comments in this layer that restate a name, a type, a body or a nearby message. They go. The kept comments each explain a foreign fact the code cannot show, such as drizzle's hashing and separator, git autocrlf, Lakebase's ALTER OWNER refusal, and the PGUSER that Databricks Apps sets. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 22 +------------------ .../appkit/src/database/migrations/history.ts | 5 ----- .../src/database/migrations/ownership.ts | 2 -- .../database/migrations/tests/apply.test.ts | 1 - .../src/database/migrations/tests/fixtures.ts | 4 ---- .../src/plugins/database/migrate-on-start.ts | 11 ---------- .../src/plugins/database/schema-check.ts | 2 -- .../plugins/database/tests/lifecycle.test.ts | 1 - .../database/tests/migrate-on-start.test.ts | 1 - .../database/tests/schema-check.test.ts | 1 - 10 files changed, 1 insertion(+), 49 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 7fec747e3..d1c652d2f 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -30,15 +30,6 @@ import { const logger = createLogger("database"); -/** - * What to do when the recorded history drifted from the committed one: a - * recorded migration whose file changed since, or committed migrations the - * database never recorded next to rows this checkout lacks. "warn" logs and - * applies what is pending, so a developer can rework their own unapplied - * migration. "refuse" throws MigrationHistoryError before applying anything, - * as a deploy start must, since the deploy branch only ever runs merged files - * as they were merged. - */ type DriftPolicy = "warn" | "refuse"; interface ApplyMigrationsOptions { @@ -50,7 +41,6 @@ interface ApplyMigrationsOptions { readonly lockWaitMs?: number; /** Longest wait for each table lock a migration takes, in milliseconds. */ readonly lockTimeoutMs?: number; - /** Defaults to "warn". */ readonly onDrift?: DriftPolicy; } @@ -174,13 +164,7 @@ type HistoryRefusal = | { readonly stranded: readonly string[]; readonly last: string } /** Files and rows at one timestamp that cannot be told apart. */ | { readonly ambiguous: AmbiguousTimestamp } - /** Recorded migrations whose committed file changed since (onDrift "refuse"). */ | { readonly edited: readonly string[] } - /** - * Committed migrations never recorded, pending or stranded, while the - * database recorded migrations this checkout lacks (onDrift "refuse"): the - * two histories diverged. - */ | { readonly diverged: { readonly unrecorded: readonly string[]; @@ -476,7 +460,6 @@ function readMigrations(folder: string, journal: Journal): MigrationFile[] { }); } -/** Why the committed history cannot be applied over the recorded one; undefined when it can. */ function historyRefusal( history: MigrationHistory, files: readonly MigrationFile[], @@ -500,7 +483,6 @@ function historyRefusal( return undefined; } -/** Every committed migration the database never recorded, oldest first, next to the rows it has that this checkout lacks. */ function divergence(history: MigrationHistory): HistoryRefusal { return { diverged: { @@ -889,9 +871,7 @@ function duration(ms: number): string { * * 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. An applied migration whose file changed, and - * recorded migrations that are not committed, are logged, or refused too with - * `onDrift: "refuse"` (see DriftPolicy). + * 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 diff --git a/packages/appkit/src/database/migrations/history.ts b/packages/appkit/src/database/migrations/history.ts index 7c53d5566..727383e87 100644 --- a/packages/appkit/src/database/migrations/history.ts +++ b/packages/appkit/src/database/migrations/history.ts @@ -4,12 +4,7 @@ export interface MigrationFile { readonly idx: number; /** The journal's `when`, recorded as `created_at`. */ readonly when: number; - /** sha256 of the .sql file as checked out here, recorded as `hash`. */ readonly hash: string; - /** - * Every hash a checkout of this file records: as is, with CRLF read as LF, - * and with LF read as CRLF. A row with any of them is this file. - */ readonly hashes: readonly string[]; /** The file split on `--> statement-breakpoint`. */ readonly statements: readonly string[]; diff --git a/packages/appkit/src/database/migrations/ownership.ts b/packages/appkit/src/database/migrations/ownership.ts index 75486aa06..c0226f29e 100644 --- a/packages/appkit/src/database/migrations/ownership.ts +++ b/packages/appkit/src/database/migrations/ownership.ts @@ -50,8 +50,6 @@ export function ownershipHint( "On the deploy branch that role is the app's service principal: bind the database to the app with CAN_CONNECT_AND_CREATE." ); } - // ALTER ... OWNER TO the service principal's role fails on Lakebase with - // "must be able to SET ROLE": nobody holds ADMIN or SET on that role. if (ownership && ownership.owner !== ownership.currentUser) { return ( `Schema "${ownership.schemaName}" is owned by "${ownership.owner}", but the app connects as "${ownership.currentUser}". ` + diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 6a009aa88..af02e0091 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -600,7 +600,6 @@ describe("applyPendingMigrations", () => { expect(state.recorded).toHaveLength(2); }); - /** Main's new migration is older than the one a branch deployed first, so it is stranded, not pending. */ const strandedBehindABranch = () => { const folder = migrations([ { tag: "0000_a", when: 1000, sql: [`SELECT 1;`] }, diff --git a/packages/appkit/src/database/migrations/tests/fixtures.ts b/packages/appkit/src/database/migrations/tests/fixtures.ts index 085b27da5..b2071b874 100644 --- a/packages/appkit/src/database/migrations/tests/fixtures.ts +++ b/packages/appkit/src/database/migrations/tests/fixtures.ts @@ -72,10 +72,6 @@ export function writeMigrations( return folder; } -/** - * The hash drizzle-orm's migrator records for a migration file: as written, - * or as a checkout with the given line endings reads it. - */ export function hashOf( folder: string, tag: string, diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index 5403b85eb..5e864f9c4 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -20,11 +20,8 @@ import { createLogger } from "../../logging/logger"; const logger = createLogger("database"); -/** Whether this process applies the committed migrations when it starts. */ export type MigrateOnStartDecision = - /** APPKIT_DB_MIGRATE_ON_START is not "true": a local start, or an app that never opted in. */ | { readonly kind: "off" } - /** The flag is on, but the environment is not the one Apps gives a deployed app with a bound database. */ | { readonly kind: "skipped"; readonly reason: string } | { readonly kind: "migrate" }; @@ -66,20 +63,13 @@ function endpointBranch(endpoint: string | undefined): string | undefined { return endpoint?.match(/\/branches\/([^/]+)\//)?.[1]; } -/** Lakebase branch ids are at most 63 characters. */ const BRANCH_ID_MAX_LENGTH = 63; -/** - * The exact shapes AppKit gives the branches of one developer - * (dev--<6 hex>) and of one agent session (session-<6 hex>-). Only - * they migrate those branches, so a deployed app bound to one is misconfigured. - */ const DEVELOPMENT_BRANCH_SHAPES = { "a developer": /^dev-[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{6}$/, "an agent session": /^session-[0-9a-f]{6}-[a-z0-9]{1,48}$/, }; -/** Whose branch the id names, by its exact shape; undefined for any other id. */ function developmentBranchOwner(branch: string): string | undefined { if (branch.length > BRANCH_ID_MAX_LENGTH) return undefined; return Object.entries(DEVELOPMENT_BRANCH_SHAPES).find(([, shape]) => @@ -125,7 +115,6 @@ export async function migrateOnStart( result = await applyPendingMigrations(pool, { migrationsFolder: folder, schemaName: schema.$schemaName, - // The deploy branch only ever runs merged files as they were merged. onDrift: "refuse", }); } catch (error) { diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index a5d40316f..7225d4f55 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -9,7 +9,6 @@ interface CatalogColumn { readonly relation_kind: string; } -/** How the missing tables and columns get created, given what this start did about migrations. */ function migrationAdvice(migration: MigrateOnStartDecision): string { switch (migration.kind) { case "off": @@ -27,7 +26,6 @@ function migrationAdvice(migration: MigrateOnStartDecision): string { * request as an undefined-table or undefined-column failure, so check up front. * pg_catalog is read rather than information_schema, which hides objects the * role cannot access and would report a privilege gap as a missing column. - * `migration` says what this start did about migrations, so the advice fits. */ export async function assertSchemaMatchesDatabase( dataPath: DataPath, diff --git a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts index 54333161b..736d9bc36 100644 --- a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts +++ b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts @@ -253,7 +253,6 @@ describe("createDatabaseState", () => { expect(order).toEqual(["pool", "migrate", "select 1", "catalog"]); expect(mocks.migrateOnStart).toHaveBeenCalledWith(pool, schema); - // The catalog check words its advice by whether this start migrated. expect(mocks.assertSchemaMatchesDatabase).toHaveBeenCalledWith( path, schema, diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index 1eee3f199..1b56e84a2 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -160,7 +160,6 @@ describe("migrateOnStart", () => { await migrateOnStart(pool, schema, root, deployEnv); - // A deploy start refuses an edited or diverged history instead of warning. expect(applyPendingMigrations).toHaveBeenCalledWith(pool, { migrationsFolder: path.join(root, "config/database/migrations"), schemaName: "app", diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index bae7d77df..4c3b76961 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -21,7 +21,6 @@ type CatalogRow = { relation_kind: string; }; -/** A local start: APPKIT_DB_MIGRATE_ON_START is not set. */ const OFF = { kind: "off" } as const; /** Answer the catalog query with the given tables and columns. */ From d3132ad3de1ebb0d77bad4a67d299e624d9a31ef Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:43:51 +0000 Subject: [PATCH 187/317] refactor(appkit): name the branch-deployed-first rule in historyRefusal A stranded migration next to rows this checkout lacks means a branch deployed first, and a deploy start refuses that as diverged rather than as stranded, so the fix is the diverged runbook and not a new timestamp. That rule lived in a comment over a bare boolean. It is now the predicate branchDeployedFirst, true when unrecorded migrations here sit next to recorded rows this checkout lacks, and the onDrift check stays at the call site. Behavior is unchanged. The migration tests pin the stranded, edited and diverged refusals. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/migrations/apply.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index d1c652d2f..3f2afe0f1 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -467,9 +467,7 @@ function historyRefusal( ): HistoryRefusal | undefined { const ambiguous = history.ambiguous[0]; if (ambiguous) return { ambiguous }; - // Next to rows this checkout lacks, a stranded entry means a branch deployed - // first, so the way back is the diverged runbook, not regenerating it. - const diverged = onDrift === "refuse" && history.unknown.length > 0; + const diverged = onDrift === "refuse" && branchDeployedFirst(history); if (history.stranded.length > 0) { if (diverged) return divergence(history); const last = @@ -479,10 +477,15 @@ function historyRefusal( } if (onDrift === "warn") return undefined; if (history.edited.length > 0) return { edited: tags(history.edited) }; - if (history.pending.length > 0 && diverged) return divergence(history); + 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: { From ec82d6ac9a7d2c6eb3c298e1a7582c5733c7d00b Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:44:15 +0000 Subject: [PATCH 188/317] fix(appkit): tag the fork copy only in a journal the migrator trusts tagForkCopy, untagForkCopy and isForkCopy checked only that an ordinary table stood at the journal's name. The migrator refuses to record into a journal owned by a role it does not trust, and to read one under row-level security, because a trigger, rule, default or policy there would run that role's code as the caller. The tag helpers now reuse that rule through readJournalRelation and journalRefusal, exported from migrations/apply with its behavior unchanged. A fork's untouched copy keeps the schema owner's journal, which the rule trusts, so the tag still works there. Where it does not, init rebuilds without a tag. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 33 +++++++++++------ .../src/database/tooling/schema-state.ts | 37 +++++++++++-------- .../src/database/tooling/tests/init.test.ts | 29 ++++++++++++++- 3 files changed, 71 insertions(+), 28 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 0a87da48c..b253e50a7 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -290,7 +290,7 @@ interface JournalRelation { } /** What the migrator is about to do with the journal. */ -type JournalUse = "read" | "record"; +export type JournalUse = "read" | "record"; /** Why the relation at the journal's name is refused for a use. */ type JournalRefusal = @@ -308,7 +308,7 @@ type JournalRefusal = * an ordinary table is used, and one of an untrusted owner's only for a read * without row-level security. */ -function journalRefusal( +export function journalRefusal( relation: JournalRelation, use: JournalUse, ): JournalRefusal | undefined { @@ -511,16 +511,11 @@ function divergence(history: MigrationHistory): HistoryRefusal { }; } -/** - * 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( +/** 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, - use: JournalUse, -): Promise { +): Promise { // pg_catalog needs no privileges, so a missing grant is not mistaken for a missing table. const { rows } = await client.query<{ relkind: string; @@ -542,8 +537,8 @@ async function journalTableExists( [schemaName, MIGRATIONS_TABLE], ); const found = rows[0]; - if (!found) return false; - const relation: JournalRelation = { + if (!found) return null; + return { relkind: found.relkind, owner: found.owner, schemaOwner: found.schema_owner, @@ -551,6 +546,20 @@ async function journalTableExists( 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; diff --git a/packages/appkit/src/database/tooling/schema-state.ts b/packages/appkit/src/database/tooling/schema-state.ts index 9f2716a58..a8d904832 100644 --- a/packages/appkit/src/database/tooling/schema-state.ts +++ b/packages/appkit/src/database/tooling/schema-state.ts @@ -1,6 +1,11 @@ import type { PoolClient } from "pg"; -import { quoteIdentifier } from "../migrations/apply"; +import { + journalRefusal, + type JournalUse, + quoteIdentifier, + readJournalRelation, +} from "../migrations/apply"; import { schemaOwnership } from "../migrations/ownership"; import { MIGRATIONS_TABLE } from "../migrations/paths"; import { readKeptObjects } from "./clean"; @@ -38,20 +43,21 @@ const journalTable = (schemaName: string) => `${quoteIdentifier(schemaName)}.${quoteIdentifier(MIGRATIONS_TABLE)}`; /** - * Whether an ordinary table stands at the journal's name. Anything else there - * is left alone. The migrator refuses it with its own message. + * Whether the journal is an ordinary table the migrator's trust rule lets your + * role use this way (journalRefusal in migrations/apply). A table another role + * owns could run that role's code as you through a trigger, rule, default or + * policy, so the tag is written and deleted only where the migrator would + * record, and read only where it would read. A fork's untouched copy keeps the + * schema owner's journal, which the rule trusts. Anything else at the + * journal's name is left alone; the migrator refuses it with its own message. */ -async function hasJournalTable( +async function journalUsable( client: QueryClient, schemaName: string, + use: JournalUse, ): Promise { - const { rows } = await client.query( - `select 1 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 and c.relkind = 'r'`, - [schemaName, MIGRATIONS_TABLE], - ); - return rows.length > 0; + const relation = await readJournalRelation(client, schemaName); + return relation !== null && journalRefusal(relation, use) === undefined; } /** Whether the branch's journal carries the fork-copy tag. */ @@ -59,7 +65,7 @@ export async function isForkCopy( client: QueryClient, schemaName: string, ): Promise { - if (!(await hasJournalTable(client, schemaName))) return false; + if (!(await journalUsable(client, schemaName, "read"))) return false; const { rows } = await client.query( `select 1 from ${journalTable(schemaName)} where hash = $1 limit 1`, [FORK_COPY_TAG], @@ -70,13 +76,14 @@ export async function isForkCopy( /** * Tag the copied journal. On Lakebase your role can insert into the service * principal's tables before the hand-off. Returns false when the schema has no - * journal to tag, which leaves the hand-off and the clean unmarked between them. + * journal the trust rule lets you write, which leaves the hand-off and the + * clean unmarked between them. */ export async function tagForkCopy( client: QueryClient, schemaName: string, ): Promise { - if (!(await hasJournalTable(client, schemaName))) return false; + if (!(await journalUsable(client, schemaName, "record"))) return false; const journal = journalTable(schemaName); await client.query( `insert into ${journal} (hash, created_at) @@ -90,7 +97,7 @@ export async function untagForkCopy( client: QueryClient, schemaName: string, ): Promise { - if (!(await hasJournalTable(client, schemaName))) return; + if (!(await journalUsable(client, schemaName, "record"))) return; await client.query( `delete from ${journalTable(schemaName)} where hash = $1`, [FORK_COPY_TAG], diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 5fb5bb2f3..02214d153 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -64,6 +64,8 @@ const migrateReport = { */ let schemaOwner: string | null; let journal: boolean; +/** The journal's owner is you, a role you inherit, or the schema's owner. */ +let journalTrusted: boolean; let tagged: boolean; let keptInPublic: string[]; let ownedOutside: string[]; @@ -72,10 +74,25 @@ const queries: string[] = []; const pool = { query: vi.fn(async (text: string) => { queries.push(text); + if (text.includes("c.relname = $2")) { + return { + rows: journal + ? [ + { + relkind: "r", + owner: journalTrusted ? schemaOwner : "someone-else", + schema_owner: schemaOwner, + current_user: USER, + row_security: false, + trusted: journalTrusted, + }, + ] + : [], + }; + } if (text.includes("nspowner")) { return { rows: [{ owner: schemaOwner, current_user: USER }] }; } - if (text.includes("c.relkind = 'r'")) return { rows: journal ? [{}] : [] }; if (text.includes("__drizzle_migrations")) { if (text.startsWith("insert")) tagged = true; else if (text.startsWith("delete")) tagged = false; @@ -193,6 +210,7 @@ function conflict(name: string): LakebaseApiError { beforeEach(() => { schemaOwner = SP; journal = true; + journalTrusted = true; tagged = false; keptInPublic = []; ownedOutside = []; @@ -1205,6 +1223,15 @@ describe("runInit — the start follows the branch's own state", () => { expect(tagWrites()).toEqual([]); }); + test("a copy whose journal a role you do not trust owns is rebuilt without a tag: a write there could run that role's code as you", async () => { + journalTrusted = false; + + const { report } = await init(appOn(project())); + + expect(report.start.kind).toBe("clean"); + expect(tagWrites()).toEqual([]); + }); + test("--schema migrate or --schema introspect on a copy keeps the copied rows: handed off, untagged, and reported", async () => { tagged = true; const migrated = await init(appOn(project()), { schema: "migrate" }); From 1950d1ab005d47a1ce2a78f6a2a6f10ea031c838 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:45:57 +0000 Subject: [PATCH 189/317] fix(appkit): rebuild a fresh fork's schema even when you already owned it on the source readSchemaState returned yours for an untagged schema you own, and planStart migrated it, so a new fork of a source whose app schema you already owned kept the copied rows silently. init knows it forked the branch in this run and now passes that to planStart. A schema on a fresh fork is the fork's copy whoever owns it: the default start tags it, rebuilds it from the committed migrations, and makes no hand-off, since the schema is yours already. Without schema.ts it introspects first, as for any copy. --schema migrate and --schema introspect keep the rows, as they do on a copy. A stop after the tag leaves a handed-off copy the next init finishes; a stop before it leaves a schema that looks like your working branch, the same window as a copy without a journal. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 2 +- .../src/database/tooling/schema-state.ts | 79 ++++++++++--------- .../src/database/tooling/tests/init.test.ts | 41 ++++++++++ .../tooling/tests/schema-state.test.ts | 37 +++++++++ 4 files changed, 120 insertions(+), 39 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 965c1bda3..ae76df5b2 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -730,7 +730,7 @@ async function initHolding( const state = await withBranchPool(branchCtx, (pool) => readSchemaState(pool, schemaName), ); - const plan = planStart(state, requested, hasSchema); + const plan = planStart(state, requested, hasSchema, found.created); const on = `on ${resourceId(branch.name)}`; if ( plan.confirm && diff --git a/packages/appkit/src/database/tooling/schema-state.ts b/packages/appkit/src/database/tooling/schema-state.ts index a8d904832..a34128307 100644 --- a/packages/appkit/src/database/tooling/schema-state.ts +++ b/packages/appkit/src/database/tooling/schema-state.ts @@ -146,51 +146,54 @@ const NOTHING_ELSE = { /** * Without a request, a copy is rebuilt and your working branch is migrated, * each with schema.ts, else introspected. A copy's rows stay only on request. - * A rebuild of a copy needs no confirmation, because `appkit db migrate` refuses a - * tagged branch, so none of your work can be on it. + * A schema on a branch this run forked came from the source whoever owns it, + * so one you already owned there is a copy too, tagged and rebuilt with no + * hand-off to make. A rebuild of a copy needs no confirmation, because + * `appkit db migrate` refuses a copy and a fresh fork holds only what it + * copied, so none of your work can be on it. */ export function planStart( state: SchemaState, requested: Exclude | undefined, hasSchema: boolean, + /** This run forked the branch. */ + created = false, ): StartPlan { - switch (state.kind) { - case "copy": - case "handed-off-copy": { - const untouched = state.kind === "copy"; - if (requested === "migrate" || requested === "introspect") { - return { - ...NOTHING_ELSE, - kind: requested, - handOff: untouched, - keepsCopy: true, - }; - } - if (!untouched && !hasSchema && requested === undefined) { - throw new Error( - "The rebuild of the app schema on your branch stopped before it finished, and this checkout has no config/database/schema.ts to rebuild from. Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", - ); - } - return { - ...NOTHING_ELSE, - kind: requested ?? (hasSchema ? "clean" : "introspect"), - rebuild: true, - tag: untouched, - handOff: untouched, - }; - } - case "absent": - case "yours": - case "public": { - const kind = requested ?? (hasSchema ? "migrate" : "introspect"); - return { - ...NOTHING_ELSE, - kind, - rebuild: kind === "clean", - confirm: kind === "clean" && state.kind !== "absent", - }; - } + const copied = + state.kind === "copy" || + state.kind === "handed-off-copy" || + (state.kind === "yours" && created); + if (!copied) { + const kind = requested ?? (hasSchema ? "migrate" : "introspect"); + return { + ...NOTHING_ELSE, + kind, + rebuild: kind === "clean", + confirm: kind === "clean" && state.kind !== "absent", + }; } + const untouched = state.kind === "copy"; + const tagged = state.kind === "handed-off-copy"; + if (requested === "migrate" || requested === "introspect") { + return { + ...NOTHING_ELSE, + kind: requested, + handOff: untouched, + keepsCopy: true, + }; + } + if (tagged && !hasSchema && requested === undefined) { + throw new Error( + "The rebuild of the app schema on your branch stopped before it finished, and this checkout has no config/database/schema.ts to rebuild from. Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", + ); + } + return { + ...NOTHING_ELSE, + kind: requested ?? (hasSchema ? "clean" : "introspect"), + rebuild: true, + tag: !tagged, + handOff: untouched, + }; } /** diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 02214d153..0caaedc1c 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1167,6 +1167,47 @@ describe("runInit — the start follows the branch's own state", () => { expect(tagWrites()).toEqual([]); }); + test("a fork this run created is a copy even when you already owned the source schema: tagged and rebuilt, with no hand-off and no question", async () => { + schemaOwner = USER; + const asked: unknown[] = []; + const confirmClean = async (target: unknown) => { + asked.push(target); + return true; + }; + + const lakebase = project(); + const { report, steps } = await init(appOn(lakebase)); + expect(report).toMatchObject({ + created: true, + handedOff: null, + keptCopy: null, + start: { kind: "clean" }, + }); + expect(steps).toContain(dropping()); + expect(tagWrites()).toEqual(["insert"]); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + + queries.length = 0; + const explicit = await init(appOn(project()), { + schema: "clean", + confirmClean, + }); + expect(explicit.report.start.kind).toBe("clean"); + expect(asked).toEqual([]); + + queries.length = 0; + const kept = await init(appOn(project()), { schema: "migrate" }); + expect(kept.report).toMatchObject({ + created: true, + handedOff: null, + keptCopy: { reason: "requested", from: PRODUCTION }, + start: { kind: "migrate" }, + }); + expect(tagWrites()).toEqual(["delete"]); + }); + test("a copy the service principal owns on an existing branch is rebuilt, from a run that forked nothing", async () => { const lakebase = existingDev(); lakebase.addRole(DEV, `dbrx-apps-${SP}`, SP); diff --git a/packages/appkit/src/database/tooling/tests/schema-state.test.ts b/packages/appkit/src/database/tooling/tests/schema-state.test.ts index c33b25c67..fdfce91a8 100644 --- a/packages/appkit/src/database/tooling/tests/schema-state.test.ts +++ b/packages/appkit/src/database/tooling/tests/schema-state.test.ts @@ -72,6 +72,43 @@ describe("planStart", () => { }, ); + test("on a branch this run forked, a schema you already owned is a copy too: tagged and rebuilt, with no hand-off and no question", () => { + const rebuilt = { rebuild: true, tag: true }; + expect(planStart(yours, undefined, true, true)).toEqual( + only({ kind: "clean", ...rebuilt }), + ); + expect(planStart(yours, undefined, false, true)).toEqual( + only({ kind: "introspect", ...rebuilt }), + ); + expect(planStart(yours, "clean", true, true)).toEqual( + only({ kind: "clean", ...rebuilt }), + ); + }); + + test.each(["migrate", "introspect"] as const)( + "--schema %s on a schema you owned before the fork keeps its rows, with no hand-off", + (requested) => { + expect(planStart(yours, requested, true, true)).toEqual( + only({ kind: requested, keepsCopy: true }), + ); + }, + ); + + test("the fork changes nothing where no schema exists, on public, or for a copy", () => { + expect(planStart(absent, undefined, true, true)).toEqual( + only({ kind: "migrate" }), + ); + expect(planStart(pub, undefined, true, true)).toEqual( + only({ kind: "migrate" }), + ); + expect(planStart(copy, undefined, true, true)).toEqual( + planStart(copy, undefined, true), + ); + expect(planStart(handedOff, undefined, true, true)).toEqual( + planStart(handedOff, undefined, true), + ); + }); + test("an explicit clean asks first on your working branch and on public, not where nothing exists or on a copy", () => { expect(planStart(yours, "clean", true)).toEqual( only({ kind: "clean", rebuild: true, confirm: true }), From 9631635ff806ba60c4c7740a46caf4dde479f565 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:47:59 +0000 Subject: [PATCH 190/317] fix(appkit): warn when init cannot mark a fork's copy before it rebuilds it The tag is what lets the next init finish a rebuild that stopped. When the copy has no journal table, or one owned by a role the migrator does not trust, init could not write it and said nothing, while the CLI help promised that the next init always finishes the rebuild. init now warns before the hand-off, through a new onWarning option that the CLI prints as a warning, and tells you to run appkit db init --schema clean if the run stops. The help text says when that promise holds. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 16 ++++++- .../src/database/tooling/tests/init.test.ts | 47 ++++++++++++++++--- .../cli/commands/db/init-clean-seed.test.ts | 21 ++++++++- packages/shared/src/cli/commands/db/init.ts | 13 +++-- .../src/cli/commands/db/tooling-contract.ts | 2 + 5 files changed, 86 insertions(+), 13 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index ae76df5b2..481f86c50 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -97,6 +97,12 @@ export interface InitOptions { readonly interactive?: boolean; /** One line per step that calls the Lakebase API or changes a file. */ readonly onStep?: (message: string) => void; + /** + * What a run should know before it goes on: a copy's rebuild that cannot be + * marked on the branch, so a stop would leave it looking like your working + * branch. Default: onStep. + */ + readonly onWarning?: (message: string) => void; /** Runs the drizzle-kit install. */ readonly runCommand?: RunCommand; } @@ -617,6 +623,7 @@ async function initHolding( options: InitOptions, ): Promise { const onStep = options.onStep ?? (() => undefined); + const onWarning = options.onWarning ?? onStep; const interactive = options.interactive ?? false; const ttl = options.ttl === undefined @@ -770,7 +777,14 @@ async function initHolding( introspected = await introspect(false); } - if (plan.tag) await onBranch((client) => tagForkCopy(client, schemaName)); + 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 handedOff = plan.handOff ? await handOffAppSchema(branchCtx, { branch: branch.name, diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 0caaedc1c..3e4efbe0a 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -190,16 +190,28 @@ function envFile(root: string): Record { ); } -/** Run init, collecting its progress lines. */ +/** Run init, collecting its progress lines and warnings, and both in the order they came. */ async function init(ctx: DbContext, options: InitOptions = {}) { const steps: string[] = []; + const warnings: string[] = []; + const events: string[] = []; const report = await runInit(ctx, { ...options, - onStep: (step) => steps.push(step), + onStep: (step) => { + steps.push(step); + events.push(step); + }, + onWarning: (warning) => { + warnings.push(warning); + events.push(warning); + }, }); - return { report, steps }; + return { report, steps, warnings, events }; } +const UNTAGGED = + /^Could not mark schema app 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\.$/; + function conflict(name: string): LakebaseApiError { return new LakebaseApiError(`create branch ${name}`, "ALREADY_EXISTS", { statusCode: 409, @@ -1255,22 +1267,43 @@ describe("runInit — the start follows the branch's own state", () => { expect(cleanHolding).not.toHaveBeenCalled(); }); - test("a copy without a journal is rebuilt without a tag", async () => { + test("a copy without a journal is rebuilt without a tag, with a warning before the hand-off that says what to do after a stop", async () => { journal = false; - const { report } = await init(appOn(project())); + const { report, warnings, events } = await init(appOn(project())); expect(report.start.kind).toBe("clean"); expect(tagWrites()).toEqual([]); + expect(warnings).toEqual([expect.stringMatching(UNTAGGED)]); + expect(events.findIndex((event) => UNTAGGED.test(event))).toBeLessThan( + events.findIndex((event) => event.startsWith("Handing schema app")), + ); }); - test("a copy whose journal a role you do not trust owns is rebuilt without a tag: a write there could run that role's code as you", async () => { + test("a copy whose journal a role you do not trust owns is rebuilt without a tag, with the same warning: a write there could run that role's code as you", async () => { journalTrusted = false; - const { report } = await init(appOn(project())); + const { report, warnings } = await init(appOn(project())); expect(report.start.kind).toBe("clean"); expect(tagWrites()).toEqual([]); + expect(warnings).toEqual([expect.stringMatching(UNTAGGED)]); + }); + + test("without an onWarning, the warning goes to onStep", async () => { + journal = false; + const steps: string[] = []; + + await runInit(appOn(project()), { onStep: (step) => steps.push(step) }); + + expect(steps).toContainEqual(expect.stringMatching(UNTAGGED)); + }); + + test("a tagged copy gets no warning", async () => { + const { warnings } = await init(appOn(project())); + + expect(tagWrites()).toEqual(["insert"]); + expect(warnings).toEqual([]); }); test("--schema migrate or --schema introspect on a copy keeps the copied rows: handed off, untagged, and reported", async () => { diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index 617b9b650..7360ff90a 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -155,7 +155,11 @@ describe("appkit db init", () => { expect(prompts.confirm).not.toHaveBeenCalled(); expect(tooling.runInit).toHaveBeenCalledWith( { root: "/app", env: {} }, - { interactive: true, onStep: expect.any(Function) }, + { + interactive: true, + onStep: expect.any(Function), + onWarning: expect.any(Function), + }, ); }); @@ -168,6 +172,7 @@ describe("appkit db init", () => { ttl: "1h", interactive: false, onStep: expect.any(Function), + onWarning: expect.any(Function), }); resetOptionValues(); @@ -304,6 +309,20 @@ describe("appkit db init", () => { ); }); + test("a warning from init prints as a warning while init runs", async () => { + tooling.runInit.mockImplementation(async (_ctx, options) => { + options.onWarning?.( + "Could not mark schema app on dev-alice-3f9a2c as the fork's copy.", + ); + return report; + }); + await init(); + + expect(output(log)).toContain( + "! Could not mark schema app on dev-alice-3f9a2c as the fork's copy.", + ); + }); + test("in schema public, the tables other roles own are listed as kept with their rows", async () => { tooling.runInit.mockResolvedValue({ ...report, diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index d34168cc5..7a81932cf 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -124,6 +124,7 @@ async function runDbInit(flags: InitFlags): Promise { ...(flags.schema === "clean" && !flags.yes ? { confirmClean } : {}), interactive: !flags.yes && isInteractive(), onStep: info, + onWarning: warn, }; printInitReport( await tooling.runInit(tooling.createDbContext(), options), @@ -178,10 +179,14 @@ the branch databricks.yml deploys to, else the project's default branch, which copies its rows, production data included. init reads from the branch whether the app schema is still that copy. If it is, init takes the schema over and rebuilds it from the committed migrations (written first by introspect when -there is no schema.ts), so the branch starts without the copied rows. A run -that stops before the rebuild finishes is finished by the next init, from any -checkout. --schema migrate, or --schema introspect, keeps the copied rows and -says so. Your working branch keeps its data: init migrates it. --schema clean +there is no schema.ts), so the branch starts without the copied rows. A branch +init forked in this run is rebuilt even when you already owned its schema on +the source. init marks the copy in its migration journal first, so a run that +stops before the rebuild finishes is finished by the next init, from any +checkout. When the copy has no journal init can write, init warns instead, +and after a stop you run --schema clean yourself. --schema migrate, or +--schema introspect, keeps the copied rows and says so. Your working branch +keeps its data: init migrates it. --schema clean rebuilds your working branch too, after a confirmation or with --yes; a copy's rebuild asks nothing. In schema public only your own objects go; what other roles own stays with its rows, and init lists it. init never changes the diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index ba6e6a448..41d3981eb 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -50,6 +50,8 @@ export interface InitOptions { readonly ttl?: string; readonly interactive?: boolean; readonly onStep?: (message: string) => void; + /** A copy's rebuild that cannot be marked on the branch, which a stop would leave looking like your working branch. */ + readonly onWarning?: (message: string) => void; /** * Asked before an explicit --schema clean drops a schema that may hold your * work. init reads from the branch whether it does, and asks nothing for a From 27c60b7a568b819fb5ebbfe744af3326b3f2c159 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:48:27 +0000 Subject: [PATCH 191/317] fix(shared): point a kept fork copy at --schema clean, which is what removes it After --schema migrate or --schema introspect on a copy, the warning said a plain appkit db init would rebuild the schema without the copied rows. It does not. The tag is gone and the schema is yours, so a plain init migrates it and keeps the rows. The warning now says so and names appkit db init --schema clean, which drops the app schema with everything in it after a confirmation, or with --yes. Signed-off-by: ditadi Co-authored-by: Isaac --- packages/shared/src/cli/commands/db/init.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index 7a81932cf..87cf71976 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -103,8 +103,9 @@ function printInitReport( else info("Left the schema as it is"); if (keptCopy?.reason === "requested") { + // The tag is gone and the schema is yours, so only an explicit clean removes the rows. warn( - `Kept the rows the fork copied${keptCopy.from ? ` from ${shortName(keptCopy.from)}` : ""}, as --schema ${schemaFlag} asks. A plain \`appkit db init\` rebuilds the app schema from the committed migrations without them.`, + `Kept the rows the fork copied${keptCopy.from ? ` from ${shortName(keptCopy.from)}` : ""}, as --schema ${schemaFlag} asks. The app schema is yours now, so a plain \`appkit db init\` keeps them. \`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.`, ); } else if (keptCopy?.reason === "public") { warn( From fea6a77f04ada4ab72db933649d24323cb3358eb Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 21:51:34 +0000 Subject: [PATCH 192/317] docs: describe the fork-copy rules this fix round changed The database plugin page and the init help now say that a branch init forked in this run is rebuilt even when you already owned its schema on the source, that the fork-copy row is written only into a journal the migrator trusts and that init warns and tells you to run --schema clean after a stop when it cannot write it, that migrate, introspect and seed refuse an untouched copy as well as a tagged one, and that after keeping the copied rows only --schema clean removes them. Signed-off-by: ditadi Co-authored-by: Isaac --- docs/docs/plugins/database.md | 49 +++++++++++++++------ packages/shared/src/cli/commands/db/init.ts | 4 +- 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 47a5a0239..37db44200 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -171,25 +171,46 @@ 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. -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. +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. Dropping the schema removes it. -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. `appkit db migrate`, `appkit db introspect` and -`appkit db seed` refuse a branch whose journal carries it. +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 +`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. + +`appkit db migrate`, `appkit db introspect` and `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 `appkit db init` to rebuild it, or `appkit db init --schema +migrate` (`introspect` for introspect) to keep the copied rows. Schema `public` +is never refused. 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. A schema you own with no such row is your working branch. -`init` migrates it, or introspects it without `schema.ts`. `--schema clean` -rebuilds your working branch too, after a confirmation or with `--yes`. A -copy's rebuild asks nothing, because `migrate` refuses a copy, so none of your -work can be on it. `--schema none` touches nothing, and the next plain `init` -still rebuilds the copy. +where it came from. From then on the schema is your working branch. A plain +`init` migrates it and keeps the rows. `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 `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 diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index 87cf71976..3be3c5c9b 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -195,7 +195,9 @@ default branch, a protected branch or a branch databricks.yml deploys to, and never edits databricks.yml. With --schema none, init only sets up the branch and .env: the schema and its -owner stay as the fork copied them, and the next plain init still rebuilds it. +owner stay as the fork copied them. 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 --schema clean then. init never hands off schema public, which belongs to the database rather than to an app. From 3058ddb85eada20fba498946d15790cd77a45397 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:12:34 +0000 Subject: [PATCH 193/317] chore: delete the comments the audit flagged in init, schema-state and the CLI The comment audit of the design 001 fixes flagged narration, type and field docs, and rationale for our own code in this layer's files. This deletes the 64 of them that remain and were written by this fix round, and 11 more the R2-05 unit added since the audit that narrate the same way: the onWarning docs, the record option's caller, test variable docs and comments that restate the assertion below them. The kept comments are the Lakebase why on tagForkCopy and the two Postgres test headers. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 52 ------------------- .../src/database/tooling/introspect/index.ts | 7 --- .../introspect/tests/introspect.test.ts | 2 - .../src/database/tooling/schema-state.ts | 47 ----------------- .../database/tooling/tests/clean-seed.test.ts | 1 - .../database/tooling/tests/init.pg.test.ts | 10 ---- .../src/database/tooling/tests/init.test.ts | 12 ----- .../database/tooling/tests/migrate.test.ts | 1 - .../tooling/tests/schema-state.pg.test.ts | 3 -- .../cli/commands/db/init-clean-seed.test.ts | 2 - packages/shared/src/cli/commands/db/init.ts | 7 --- .../src/cli/commands/db/tooling-contract.ts | 9 ---- 12 files changed, 153 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 481f86c50..8ae176da4 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -75,18 +75,7 @@ export type { SchemaStart } from "./schema-state"; export interface InitOptions { /** Default: this checkout's session branch when .env points at it, else your dev branch. */ readonly mode?: BranchMode; - /** - * Default, read from the branch: a schema that still holds the fork's copy - * is rebuilt from the committed migrations (introspect writes schema.ts - * first when there is none); your working branch is migrated with - * schema.ts, else introspected. - */ readonly schema?: SchemaStart; - /** - * Asked before an explicit --schema clean drops a schema that may hold your - * work, your working branch or public. A copy's rebuild never asks. Absent, - * the clean proceeds. - */ readonly confirmClean?: (target: { readonly branch: string; readonly schemaName: string; @@ -97,11 +86,6 @@ export interface InitOptions { readonly interactive?: boolean; /** One line per step that calls the Lakebase API or changes a file. */ readonly onStep?: (message: string) => void; - /** - * What a run should know before it goes on: a copy's rebuild that cannot be - * marked on the branch, so a stop would leave it looking like your working - * branch. Default: onStep. - */ readonly onWarning?: (message: string) => void; /** Runs the drizzle-kit install. */ readonly runCommand?: RunCommand; @@ -121,19 +105,14 @@ export type InitStart = | { readonly kind: "introspect"; readonly introspect: IntrospectReport; - /** On a fork's copy: the schema introspect read, rebuilt from the migrations it wrote. */ readonly rebuilt: Rebuild | null; } | ({ readonly kind: "clean" } & Rebuild); -/** Rows the fork copied into the app schema that this run left in place, and why. */ export type KeptCopy = - /** You asked for --schema migrate or --schema introspect on a copy. */ | { readonly reason: "requested"; readonly from: string | null } - /** In schema public, what other roles own stays with its rows; init never removes it. */ | { readonly reason: "public"; readonly objects: readonly string[] }; -/** You answered no to the confirmation an explicit clean asks for. */ export class InitCancelledError extends Error { constructor(message: string) { super(message); @@ -245,7 +224,6 @@ interface BranchRequest { readonly ttl: { readonly api: string; readonly label: string }; readonly boundary: DeployBoundary; readonly envFile: string; - /** The branch of this project the default databricks.yml target deploys to, which a new fork comes from. */ readonly deployBranch: string | null; readonly onStep: (message: string) => void; } @@ -279,14 +257,6 @@ function branchLimitError( return new Error(message, { cause }); } -/** - * Your dev branch or this checkout's session branch: found with one GET, or - * forked from the branch databricks.yml deploys to, which holds the deployed - * migrations, else from the project's default branch. The branch id is - * resolved and checked against databricks.yml before any API call or .env - * write. An expired session branch gets a new session id; an expired dev - * branch is an error. - */ async function findOrCreateBranch( ctx: DbContext, request: BranchRequest, @@ -355,8 +325,6 @@ async function findOrCreateBranch( if (!parent) { throw new Error(`Project ${project} has no default branch to fork from.`); } - // Written before the fork, so a run that stops during or after it leaves - // its rerun the session id, to reuse instead of forking again. if (session !== null && session !== request.session) { updateEnvFile(request.envFile, { APPKIT_DB_SESSION: session }); } @@ -583,15 +551,6 @@ function readEnvValues(file: string): Record { } /** - * `appkit db init`: find or create your dev branch or this checkout's session - * branch, ensure a read-write endpoint and your DATABRICKS_SUPERUSER role, - * point `.env` at the branch, then start the schema as its state on the branch - * calls for (see planStart): a fork's copy is handed to you and rebuilt, your - * working branch is migrated, and `--schema none` touches neither. It asks - * nothing but the confirmation an explicit clean of your work needs. It - * refuses the project's default branch, protected branches and branches - * databricks.yml deploys to before changing anything, and never touches the - * deploy bundle. * 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. @@ -611,7 +570,6 @@ export async function runInit( ); } -/** A start under the checkout's history lock; null for `--schema none`, which takes none and starts nothing. */ interface LockedStart { readonly lock: HistoryLock; readonly requested: Exclude | undefined; @@ -721,8 +679,6 @@ async function initHolding( role: { name: role.name, action }, envFile, }; - // --schema none reads nothing from the branch and leaves the schema as the - // fork has it, owner included. if (!locked) { return { ...base, @@ -748,8 +704,6 @@ async function initHolding( `Cancelled. Schema ${schemaName} ${on} is as it was, and .env points at the branch.`, ); } - // Every start leaves the branch for `appkit db migrate` and `appkit db check`, - // which diff schema.ts with drizzle-kit, so every start installs it. const installed = ensureDrizzleKit( ctx.root, options.runCommand ?? runCommand, @@ -767,10 +721,6 @@ async function initHolding( record, }); }; - // A rebuild without schema.ts introspects first, while the copy is untouched. - // Introspect only writes files then, so a refusal leaves the branch as the - // fork made it. It reads the journal as history, so a tag an earlier run left - // on the copy goes first and comes back right before the hand-off. let introspected: IntrospectReport | null = null; if (plan.kind === "introspect" && plan.rebuild) { if (plan.tag) await onBranch((client) => untagForkCopy(client, schemaName)); @@ -810,7 +760,6 @@ async function initHolding( : `Dropping schema ${schemaName} ${on}${why}`, ); const clean = await cleanHolding(branchCtx, lock); - // Recreated from the committed migrations, so the startup check passes. const migrate = await migrateHolding(branchCtx, lock, { interactive, generate: false, @@ -847,7 +796,6 @@ async function initHolding( }; } -/** What of the fork's copy this run left in place. */ function keptCopyOf( state: SchemaState, plan: StartPlan, diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 6f5e6d6d5..893af0010 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -43,12 +43,6 @@ export interface IntrospectOptions { readonly schemaName?: string; /** Module the written schema.ts imports the builder from. Default "@databricks/appkit/beta". */ readonly importSource?: string; - /** - * false: write schema.ts and its migration without recording the migration - * on the branch, for init's rebuild, which drops the schema right after. It - * is the one read of a fork's copy that is not refused, since it writes - * nothing on the branch. Default true. - */ readonly record?: boolean; } @@ -224,7 +218,6 @@ export async function introspectHolding( const record = options.record ?? true; return withBranchPool(ctx, async (pool) => { - // init's rebuild reads the copy without recording, then drops it. if (record) { const refusal = forkCopyRefusal( env.branch.name, diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 46d792d1b..ed3dcb46d 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -78,9 +78,7 @@ const onProduction = { 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 }>; -/** The journal carries init's fork-copy tag. */ let tagged: boolean; -/** Who owns the app schema; the connected role unless a test says otherwise. */ let schemaOwner: string; /** The row the branch records for the last committed migration. */ const lastCommitted = (root: string) => { diff --git a/packages/appkit/src/database/tooling/schema-state.ts b/packages/appkit/src/database/tooling/schema-state.ts index a34128307..92d43d341 100644 --- a/packages/appkit/src/database/tooling/schema-state.ts +++ b/packages/appkit/src/database/tooling/schema-state.ts @@ -11,30 +11,15 @@ import { MIGRATIONS_TABLE } from "../migrations/paths"; import { readKeptObjects } from "./clean"; import { resourceId } from "./targets"; -/** How init leaves the schema; "none" leaves it as the fork has it. */ export type SchemaStart = "migrate" | "introspect" | "clean" | "none"; -/** - * The journal row init writes into a fork's copy of the app schema before it - * takes the schema over. The clean drops it with the schema, so a rerun from - * any checkout reads from the branch itself whether a rebuild is still due. - */ export const FORK_COPY_TAG = "appkit:fork-copy"; -/** What the app schema on the branch is, read from the branch itself. */ export type SchemaState = - /** Nothing copied and nothing built yet. */ | { readonly kind: "absent" } - /** The fork's untouched copy. Another role, the app's service principal, owns it. */ | { readonly kind: "copy"; readonly owner: string } - /** Handed to you and still tagged, so a rebuild stopped before its clean. */ | { readonly kind: "handed-off-copy" } - /** Your working branch. */ | { readonly kind: "yours" } - /** - * Schema public belongs to the database, never to an app, so it is never - * handed off or tagged. What other roles own in it stays with its rows. - */ | { readonly kind: "public"; readonly kept: readonly string[] }; type QueryClient = Pick; @@ -42,15 +27,6 @@ type QueryClient = Pick; const journalTable = (schemaName: string) => `${quoteIdentifier(schemaName)}.${quoteIdentifier(MIGRATIONS_TABLE)}`; -/** - * Whether the journal is an ordinary table the migrator's trust rule lets your - * role use this way (journalRefusal in migrations/apply). A table another role - * owns could run that role's code as you through a trigger, rule, default or - * policy, so the tag is written and deleted only where the migrator would - * record, and read only where it would read. A fork's untouched copy keeps the - * schema owner's journal, which the rule trusts. Anything else at the - * journal's name is left alone; the migrator refuses it with its own message. - */ async function journalUsable( client: QueryClient, schemaName: string, @@ -60,7 +36,6 @@ async function journalUsable( return relation !== null && journalRefusal(relation, use) === undefined; } -/** Whether the branch's journal carries the fork-copy tag. */ export async function isForkCopy( client: QueryClient, schemaName: string, @@ -104,7 +79,6 @@ export async function untagForkCopy( ); } -/** Read the app schema's state as the connected developer. */ export async function readSchemaState( client: QueryClient, schemaName: string, @@ -120,18 +94,12 @@ export async function readSchemaState( : { kind: "yours" }; } -/** What init does with the schema, decided once from its state and the request. */ export interface StartPlan { readonly kind: Exclude; - /** Drop the app schema, then apply the committed migrations, so a copy's rows go. */ readonly rebuild: boolean; - /** Tag the copied journal before the hand-off, so a rerun from any checkout finishes the rebuild. */ readonly tag: boolean; - /** Delete the copy's owner on this branch, with its objects reassigned to you. */ readonly handOff: boolean; - /** You asked to keep a copy's rows. The tag goes and the rows stay. */ readonly keepsCopy: boolean; - /** An explicit clean of what may be your work asks first. */ readonly confirm: boolean; } @@ -143,20 +111,10 @@ const NOTHING_ELSE = { confirm: false, } as const; -/** - * Without a request, a copy is rebuilt and your working branch is migrated, - * each with schema.ts, else introspected. A copy's rows stay only on request. - * A schema on a branch this run forked came from the source whoever owns it, - * so one you already owned there is a copy too, tagged and rebuilt with no - * hand-off to make. A rebuild of a copy needs no confirmation, because - * `appkit db migrate` refuses a copy and a fresh fork holds only what it - * copied, so none of your work can be on it. - */ export function planStart( state: SchemaState, requested: Exclude | undefined, hasSchema: boolean, - /** This run forked the branch. */ created = false, ): StartPlan { const copied = @@ -196,11 +154,6 @@ export function planStart( }; } -/** - * Why a command that writes on the branch refuses a schema that still holds a - * fork's copy, untouched or handed off; undefined for any other state. A write - * on top of the copy would make its rows yours to keep. - */ export function forkCopyRefusal( branch: string, schemaName: string, diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index a5ac3dce6..e08713b1e 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -36,7 +36,6 @@ const schemaFile = (schemaName: string) => const DEPENDENTS = /pg_catalog\.pg_depend/; const ME = "alice@example.com"; -/** The reads of readSchemaState: the schema's owner, the journal, its tag, and what public keeps. */ const SCHEMA_OWNER = /has_schema_privilege/; const JOURNAL = /c\.relname = \$2/; const TAG = /where hash = \$1/; diff --git a/packages/appkit/src/database/tooling/tests/init.pg.test.ts b/packages/appkit/src/database/tooling/tests/init.pg.test.ts index d517f580d..b282e4201 100644 --- a/packages/appkit/src/database/tooling/tests/init.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.pg.test.ts @@ -68,7 +68,6 @@ export const schema = defineSchema(({ table }) => ({ ${table}: table(${JSON.stri describe.skipIf(!url)("runInit against Postgres", () => { const suffix = randomUUID().slice(0, 8); const database = `appkit_init_${suffix}`; - /** The app's service principal, as the Postgres role a fork copies. */ const sp = `appkit_sp_${suffix}`; const superuser = `appkit_dbx_${suffix}`; const dev = `appkit_dev_${suffix}`; @@ -77,9 +76,7 @@ describe.skipIf(!url)("runInit against Postgres", () => { let admin: Pool; let asSp: Pool; let asDev: Pool; - /** An app whose schema.ts declares `app`, with its migration generated. */ let root: string; - /** An app whose schema.ts declares public. */ let publicRoot: string; let lakebase: FakeLakebase; let api: LakebaseApi; @@ -117,7 +114,6 @@ describe.skipIf(!url)("runInit against Postgres", () => { ); } - /** The deploy branch as its service principal left it, migrated and with a row. */ async function deployed(appRoot: string, schema: string, table: string) { await applyPendingMigrations(asSp, { migrationsFolder: folder(appRoot), @@ -126,7 +122,6 @@ describe.skipIf(!url)("runInit against Postgres", () => { await asSp.query(`insert into ${table} (body) values ('copied')`); } - /** A project whose default branch is production; the fork copies its roles. */ function project(): FakeLakebase { const fake = new FakeLakebase(); fake.addBranch(PRODUCTION, { default: true }); @@ -136,7 +131,6 @@ describe.skipIf(!url)("runInit against Postgres", () => { return fake; } - /** Lakebase's delete-role with reassign, as Postgres does it. */ function apiWithRealHandOff(fake: FakeLakebase): LakebaseApi { const real = fake.api(); const deleteRole = real.deleteRole.bind(real); @@ -147,7 +141,6 @@ describe.skipIf(!url)("runInit against Postgres", () => { return real; } - /** Your dev branch exists, with your role on it and the service principal's copy gone. */ function existingDev(fake: FakeLakebase) { fake.addBranch(DEV, { source_branch: PRODUCTION }); fake.addRole(DEV, "alice", USER, ["DATABRICKS_SUPERUSER"]); @@ -170,7 +163,6 @@ describe.skipIf(!url)("runInit against Postgres", () => { return fakeContext({ root: appRoot, env: dotenv, userName: USER, api }); } - /** A context on your dev branch, as init leaves .env. */ const onDev = (appRoot: string) => context(appRoot, { PGHOST: `primary.${devBranchId(USER)}.example.com`, @@ -279,7 +271,6 @@ describe.skipIf(!url)("runInit against Postgres", () => { test("a run that stopped after the hand-off is finished by the next init, which forks nothing", async () => { await deployed(root, app, `"${app}".notes`); - // The earlier run tagged the journal and deleted the owner's role, then stopped. await asDev.query( `insert into "${app}".__drizzle_migrations (hash, created_at) values ($1, 0)`, [FORK_COPY_TAG], @@ -392,7 +383,6 @@ describe.skipIf(!url)("runInit against Postgres", () => { hashOf(folder(root), "0000_migration"), ]); - // The schema is yours now. A plain init keeps the rows; only --schema clean removes them, after asking. const kept = await init(onDev(root)); expect(kept.report.start.kind).toBe("migrate"); expect(await rows(`"${app}".notes`)).toEqual([{ body: "copied" }]); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 3e4efbe0a..4562b8819 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -57,14 +57,8 @@ const migrateReport = { typesFile: "/app/shared/appkit-types/database.d.ts", }; -/** - * The branch as init reads it over SQL: the app schema's owner, whether its - * journal exists and carries the fork-copy tag, what other roles own in - * public, and what the hand-off reads about the owner. - */ let schemaOwner: string | null; let journal: boolean; -/** The journal's owner is you, a role you inherit, or the schema's owner. */ let journalTrusted: boolean; let tagged: boolean; let keptInPublic: string[]; @@ -108,7 +102,6 @@ const pool = { throw new Error(`unexpected query ${text}`); }), }; -/** The writes to the journal's tag row, in order: "insert" tags, "delete" untags. */ const tagWrites = () => queries .filter( @@ -190,7 +183,6 @@ function envFile(root: string): Record { ); } -/** Run init, collecting its progress lines and warnings, and both in the order they came. */ async function init(ctx: DbContext, options: InitOptions = {}) { const steps: string[] = []; const warnings: string[] = []; @@ -283,7 +275,6 @@ describe("runInit — dev branch", () => { `Handing schema app in database databricks_postgres on ${devBranchId(USER)} to you: deleting this branch's copy of role ${SP}, which owns it, with its objects reassigned to you`, `Dropping schema app on ${devBranchId(USER)}: the branch still holds the rows the fork copied, and the committed migrations recreate its tables`, ]); - // The copied journal is tagged before the hand-off, so a rerun from any checkout finishes the rebuild. expect(tagWrites()).toEqual(["insert"]); expect( queries.indexOf(queries.find((text) => text.startsWith("insert")) ?? ""), @@ -988,7 +979,6 @@ describe("runInit — schema start", () => { migrate: migrateReport, }, }); - // Introspect writes the files while the copy is untouched and records nothing on it; the rebuild follows. expect(introspectHolding.mock.calls[0]?.[2]).toEqual({ interactive: false, schemaName: "app", @@ -1347,7 +1337,6 @@ describe("runInit — the start follows the branch's own state", () => { await init(appOn(project()), { schema: "clean", confirmClean }); expect(asked).toEqual([]); - // Your working branch, where the schema is yours and its journal carries no tag. schemaOwner = USER; tagged = false; await init(appOn(existingDev()), { schema: "clean", confirmClean }); @@ -1495,7 +1484,6 @@ describe("runInit — .env", () => { `Database analytics, which databricks.yml binds, is not on ${devBranchId(USER)}. Create it there (databricks postgres create-database ${DEV} --database-id analytics), or bind a database the project's branches have, then rerun \`appkit db init\`.`, ); expect(lakebase.calls).toContain(`getDatabase ${DEV}/databases/analytics`); - // The fork happened, and nothing was written. The next init finds the branch by its name. expect(fs.existsSync(path.join(root, ".env"))).toBe(false); }); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 2e9390057..6b62579cf 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -76,7 +76,6 @@ const devBranch = { kind: "dev", }; -/** A branch without the app schema yet, so it is no fork's copy. */ const pool = { query: vi.fn(async (_text: string) => ({ rows: [] as unknown[] })), }; diff --git a/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts index 51a5da423..0419ab4b6 100644 --- a/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts @@ -33,9 +33,7 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { const app = `app_${suffix}`; const bare = `bare_${suffix}`; const shared = `shared_${suffix}`; - /** A role that is neither you, a role you inherit, nor the schema's owner. */ const other = `appkit_other_${suffix}`; - /** The service principal's schema with a journal `other` owns. */ const foreign = `foreign_${suffix}`; let admin: Pool; let me: Pool; @@ -115,7 +113,6 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { { hash: "abc", created_at: "1700000000000" }, { hash: FORK_COPY_TAG, created_at: "0" }, ]); - // The tag changes nothing else. The copy still reads as the other role's. await expect(readSchemaState(me, app)).resolves.toEqual({ kind: "copy", owner: sp, diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index 7360ff90a..4c7ef3f29 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -64,7 +64,6 @@ const report = { start: { kind: "migrate", migrate }, }; -/** The tooling on your working branch. It asks the confirmation and stops on a no. */ function toolingThatAsks(): void { tooling.runInit.mockImplementation(async (_ctx, options) => { const confirmed = await options.confirmClean?.({ @@ -303,7 +302,6 @@ describe("appkit db init", () => { }); await init("--schema", "migrate"); - // The schema is yours after a keep, so a plain init migrates it and keeps the rows. expect(output(log)).toContain( "Kept the rows the fork copied from production, as --schema migrate asks. The app schema is yours now, so a plain `appkit db init` keeps them. `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.", ); diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index 3be3c5c9b..c85d11822 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -27,11 +27,6 @@ interface InitFlags { readonly yes?: boolean; } -/** - * --schema clean on your working branch drops your data. A human confirms it, - * a script passes --yes. init asks only once it has read from the branch that - * the schema is yours, so a fork's copy is rebuilt without a question. - */ const confirmClean: NonNullable = async ({ branch, schemaName, @@ -85,7 +80,6 @@ function printInitReport( if (report.installed) ok(`Installed drizzle-kit (${report.installed})`); const { start, keptCopy } = report; - // Without --schema, only a schema that still held the fork's copy gets a rebuild. const rebuilt = start.kind === "clean" || (start.kind === "introspect" && start.rebuilt); if (rebuilt && schemaFlag === undefined) { @@ -103,7 +97,6 @@ function printInitReport( else info("Left the schema as it is"); if (keptCopy?.reason === "requested") { - // The tag is gone and the schema is yours, so only an explicit clean removes the rows. warn( `Kept the rows the fork copied${keptCopy.from ? ` from ${shortName(keptCopy.from)}` : ""}, as --schema ${schemaFlag} asks. The app schema is yours now, so a plain \`appkit db init\` keeps them. \`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.`, ); diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 41d3981eb..13059c850 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -50,13 +50,7 @@ export interface InitOptions { readonly ttl?: string; readonly interactive?: boolean; readonly onStep?: (message: string) => void; - /** A copy's rebuild that cannot be marked on the branch, which a stop would leave looking like your working branch. */ readonly onWarning?: (message: string) => void; - /** - * Asked before an explicit --schema clean drops a schema that may hold your - * work. init reads from the branch whether it does, and asks nothing for a - * fork's copy. A no makes init throw an error named InitCancelledError. - */ readonly confirmClean?: (target: { readonly branch: string; readonly schemaName: string; @@ -77,11 +71,8 @@ export interface Rebuild { readonly migrate: MigrateReport; } -/** Rows the fork copied into the app schema that init left in place, and why. */ export type KeptCopy = - /** You asked for --schema migrate or --schema introspect on a copy. */ | { readonly reason: "requested"; readonly from: string | null } - /** In schema public, what other roles own stays with its rows; init never removes it. */ | { readonly reason: "public"; readonly objects: readonly string[] }; export type InitStart = From 8db8af1ccf83f598af987f5bdcaedc5a5029ff95 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:15:13 +0000 Subject: [PATCH 194/317] refactor(appkit): let the drift read ignore the fork-copy tag instead of untagging around introspect readMigrationDrift takes ignoreHashes, journal rows that are not migrations, and introspect passes the fork-copy tag. A copy an earlier init tagged before it stopped is then read for init's rebuild as it is, so init no longer deletes the tag before introspect and writes it back after. The behavior stays: introspect on a copy writes files only, and the tag is on the branch before the hand-off. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/migrations/apply.ts | 8 ++++++-- packages/appkit/src/database/tooling/init.ts | 1 - .../src/database/tooling/introspect/index.ts | 11 +++++++++-- .../tooling/introspect/tests/introspect.test.ts | 15 +++++++++++++++ .../src/database/tooling/tests/init.test.ts | 1 + 5 files changed, 31 insertions(+), 5 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index b253e50a7..1e280435a 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -916,12 +916,16 @@ function committedMigrations(folder: string): MigrationFile[] { /** Read without the lock; markMigrationsApplied checks again under it. */ export async function readMigrationDrift( client: QueryClient, - options: ApplyMigrationsOptions, + 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), - await readRecordedMigrations(client, options.schemaName), + recorded.filter((row) => !ignored.has(row.hash)), ), ); } diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 8ae176da4..f338e53b9 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -723,7 +723,6 @@ async function initHolding( }; let introspected: IntrospectReport | null = null; if (plan.kind === "introspect" && plan.rebuild) { - if (plan.tag) await onBranch((client) => untagForkCopy(client, schemaName)); introspected = await introspect(false); } diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 893af0010..ee5bbca55 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -25,7 +25,11 @@ import { type GeneratedMigration, generateMigrationFiles, } from "../migrations"; -import { forkCopyRefusal, readSchemaState } from "../schema-state"; +import { + FORK_COPY_TAG, + forkCopyRefusal, + readSchemaState, +} from "../schema-state"; import { resourceId } from "../targets"; import { readCatalog, readUnreadObjects } from "./catalog"; import { @@ -233,7 +237,10 @@ export async function introspectHolding( // 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); + 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}`, diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index ed3dcb46d..c40dc70c3 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -35,6 +35,7 @@ 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"; @@ -394,6 +395,20 @@ describe("runIntrospect", () => { expect(markMigrationsApplied).not.toHaveBeenCalled(); }); + test("record: 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, + record: false, + }); + + expect(report.migration).toMatchObject({ tag: "0000_baseline" }); + expect(markMigrationsApplied).not.toHaveBeenCalled(); + }); + test("record: false writes schema.ts and the migration, and records nothing on the branch", async () => { const root = tempApp({ [SCHEMA]: declaredSchema }); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 4562b8819..c2ef0f3d5 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -984,6 +984,7 @@ describe("runInit — schema start", () => { schemaName: "app", record: false, }); + expect(tagWrites()).toEqual(["insert"]); expect(introspectHolding.mock.invocationCallOrder[0]).toBeLessThan( cleanHolding.mock.invocationCallOrder[0] ?? 0, ); From d155391c67532843bfd5120802775e3796117796 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:16:15 +0000 Subject: [PATCH 195/317] refactor(appkit): name the .env write of the session id that happens before the fork The write of APPKIT_DB_SESSION ahead of createBranch is now persistSessionIdBeforeFork, so the order reads from the call instead of a comment: a run that stops during or after the fork leaves its rerun the session id to reuse. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index f338e53b9..cefeb715c 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -325,9 +325,7 @@ async function findOrCreateBranch( if (!parent) { throw new Error(`Project ${project} has no default branch to fork from.`); } - if (session !== null && session !== request.session) { - updateEnvFile(request.envFile, { APPKIT_DB_SESSION: session }); - } + 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}`}`, ); @@ -363,6 +361,15 @@ async function findOrCreateBranch( } } +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)); From 6fa11262766633789a2b590da60d4b0c95d24f13 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:17:10 +0000 Subject: [PATCH 196/317] refactor(appkit): give init's start under the lock a discriminated type instead of a null sentinel initHolding took LockedStart | null, where null meant --schema none. It now takes a StartRequest: { kind: "none" } for a run that takes no lock and starts nothing, or { kind: "locked", lock, requested }. The reads of schema.ts and of the branch narrow on the kind. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 23 +++++++++++--------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index cefeb715c..ebedf19b1 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -567,24 +567,27 @@ export async function runInit( options: InitOptions = {}, ): Promise { const requested = options.schema; - if (requested === "none") return initHolding(ctx, null, options); + 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, { lock, requested }, options), + initHolding(ctx, { kind: "locked", lock, requested }, options), ); } -interface LockedStart { - readonly lock: HistoryLock; - readonly requested: Exclude | undefined; -} +type StartRequest = + | { readonly kind: "none" } + | { + readonly kind: "locked"; + readonly lock: HistoryLock; + readonly requested: Exclude | undefined; + }; async function initHolding( ctx: DbContext, - locked: LockedStart | null, + request: StartRequest, options: InitOptions, ): Promise { const onStep = options.onStep ?? (() => undefined); @@ -602,7 +605,7 @@ async function initHolding( refuseSymlink(envFile); const hasSchema = hasSchemaFile(ctx.root); const schemaName = - hasSchema && locked + hasSchema && request.kind === "locked" ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) .$schemaName : DEFAULT_SCHEMA_NAME; @@ -686,7 +689,7 @@ async function initHolding( role: { name: role.name, action }, envFile, }; - if (!locked) { + if (request.kind === "none") { return { ...base, handedOff: null, @@ -695,7 +698,7 @@ async function initHolding( start: { kind: "none" }, }; } - const { lock, requested } = locked; + const { lock, requested } = request; const state = await withBranchPool(branchCtx, (pool) => readSchemaState(pool, schemaName), From bc31db9716139c750cd47df579020a267a1f91ec Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:18:25 +0000 Subject: [PATCH 197/317] refactor(appkit): rename introspect's record option to recordAsApplied The option says what false means: schema.ts and the migration are written, and the migration is not recorded on the branch as applied. init's rebuild passes false, since it drops the schema right after. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 4 ++-- .../appkit/src/database/tooling/introspect/index.ts | 8 ++++---- .../tooling/introspect/tests/introspect.test.ts | 12 ++++++------ .../appkit/src/database/tooling/tests/init.test.ts | 8 ++++---- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index ebedf19b1..b91ee0e06 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -723,12 +723,12 @@ async function initHolding( work: (client: Pick) => Promise, ) => withBranchPool(branchCtx, work); - const introspect = (record: boolean) => { + const introspect = (recordAsApplied: boolean) => { onStep(`Writing schema.ts from schema ${schemaName} ${on}`); return introspectForInit(branchCtx, lock, { interactive, schemaName, - record, + recordAsApplied, }); }; let introspected: IntrospectReport | null = null; diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index ee5bbca55..f2db00490 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -47,7 +47,7 @@ export interface IntrospectOptions { readonly schemaName?: string; /** Module the written schema.ts imports the builder from. Default "@databricks/appkit/beta". */ readonly importSource?: string; - readonly record?: boolean; + readonly recordAsApplied?: boolean; } export interface IntrospectReport { @@ -219,10 +219,10 @@ export async function introspectHolding( ); } const branchId = resourceId(env.branch.name); - const record = options.record ?? true; + const recordAsApplied = options.recordAsApplied ?? true; return withBranchPool(ctx, async (pool) => { - if (record) { + if (recordAsApplied) { const refusal = forkCopyRefusal( env.branch.name, schemaName, @@ -368,7 +368,7 @@ export async function introspectHolding( } await writeDatabaseTypes(schema, typesFile); // The database already holds what the migrations describe; recording is the last step. - recorded = record + recorded = recordAsApplied ? [...unrecorded, ...(migration ? [migration.tag] : [])] : []; if (recorded.length > 0) { diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index c40dc70c3..28e7e87d0 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -382,39 +382,39 @@ describe("runIntrospect", () => { expect(markMigrationsApplied).not.toHaveBeenCalled(); }); - test("record: false reads a copy for init's rebuild, since it writes nothing on the branch", async () => { + 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, - record: false, + recordAsApplied: false, }); expect(report.migration).toMatchObject({ tag: "0000_baseline" }); expect(markMigrationsApplied).not.toHaveBeenCalled(); }); - test("record: false reads a copy an earlier init tagged: the tag row in the journal is not a migration", async () => { + 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, - record: false, + recordAsApplied: false, }); expect(report.migration).toMatchObject({ tag: "0000_baseline" }); expect(markMigrationsApplied).not.toHaveBeenCalled(); }); - test("record: false writes schema.ts and the migration, and records nothing on the branch", async () => { + 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, - record: false, + recordAsApplied: false, }); expect(report.migration).toMatchObject({ tag: "0000_baseline" }); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index c2ef0f3d5..1e143dcec 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -982,7 +982,7 @@ describe("runInit — schema start", () => { expect(introspectHolding.mock.calls[0]?.[2]).toEqual({ interactive: false, schemaName: "app", - record: false, + recordAsApplied: false, }); expect(tagWrites()).toEqual(["insert"]); expect(introspectHolding.mock.invocationCallOrder[0]).toBeLessThan( @@ -1164,7 +1164,7 @@ describe("runInit — the start follows the branch's own state", () => { rebuilt: null, }); expect(introspectHolding.mock.calls[0]?.[2]).toMatchObject({ - record: true, + recordAsApplied: true, }); expect(cleanHolding).not.toHaveBeenCalled(); expect(tagWrites()).toEqual([]); @@ -1320,7 +1320,7 @@ describe("runInit — the start follows the branch's own state", () => { }, }); expect(introspectHolding.mock.calls[0]?.[2]).toMatchObject({ - record: true, + recordAsApplied: true, }); expect(cleanHolding).not.toHaveBeenCalled(); }); @@ -1415,7 +1415,7 @@ describe("runInit — the start follows the branch's own state", () => { expect(introspectHolding.mock.calls[0]?.[2]).toEqual({ interactive: false, schemaName: "sales", - record: true, + recordAsApplied: true, }); expect(steps).toContain( `Writing schema.ts from schema sales on ${devBranchId(USER)}`, From cf427f8f08075e7d2e8bd62b187898abe4c12fea Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:20:19 +0000 Subject: [PATCH 198/317] refactor(appkit): name the tagged state interrupted-rebuild and decide confirm through a predicate The schema state "handed-off-copy" meant a rebuild that stopped after the tag and before its clean, so it is now "interrupted-rebuild". planStart no longer gets confirm: false from a spread default: every start sets it, and an explicit clean asks only where mayHoldYourWork(state, forkedThisRun) holds, which holdsForkCopy defines as neither a copy, an interrupted rebuild, a schema on a branch this run forked, nor an absent one. The created parameter is named forkedThisRun, which is what it says. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/schema-state.ts | 37 ++++++++++++------- .../src/database/tooling/tests/init.test.ts | 2 +- .../tooling/tests/schema-state.pg.test.ts | 4 +- .../tooling/tests/schema-state.test.ts | 20 +++++----- 4 files changed, 36 insertions(+), 27 deletions(-) diff --git a/packages/appkit/src/database/tooling/schema-state.ts b/packages/appkit/src/database/tooling/schema-state.ts index 92d43d341..a91986771 100644 --- a/packages/appkit/src/database/tooling/schema-state.ts +++ b/packages/appkit/src/database/tooling/schema-state.ts @@ -18,7 +18,7 @@ export const FORK_COPY_TAG = "appkit:fork-copy"; export type SchemaState = | { readonly kind: "absent" } | { readonly kind: "copy"; readonly owner: string } - | { readonly kind: "handed-off-copy" } + | { readonly kind: "interrupted-rebuild" } | { readonly kind: "yours" } | { readonly kind: "public"; readonly kept: readonly string[] }; @@ -90,7 +90,7 @@ export async function readSchemaState( if (owner === null) return { kind: "absent" }; if (owner !== currentUser) return { kind: "copy", owner }; return (await isForkCopy(client, schemaName)) - ? { kind: "handed-off-copy" } + ? { kind: "interrupted-rebuild" } : { kind: "yours" }; } @@ -108,39 +108,47 @@ const NOTHING_ELSE = { tag: false, handOff: false, keepsCopy: false, - confirm: false, } as const; +function holdsForkCopy(state: SchemaState, forkedThisRun: boolean): boolean { + return ( + state.kind === "copy" || + state.kind === "interrupted-rebuild" || + (state.kind === "yours" && forkedThisRun) + ); +} + +function mayHoldYourWork(state: SchemaState, forkedThisRun: boolean): boolean { + return state.kind !== "absent" && !holdsForkCopy(state, forkedThisRun); +} + export function planStart( state: SchemaState, requested: Exclude | undefined, hasSchema: boolean, - created = false, + forkedThisRun = false, ): StartPlan { - const copied = - state.kind === "copy" || - state.kind === "handed-off-copy" || - (state.kind === "yours" && created); - if (!copied) { + if (!holdsForkCopy(state, forkedThisRun)) { const kind = requested ?? (hasSchema ? "migrate" : "introspect"); return { ...NOTHING_ELSE, kind, rebuild: kind === "clean", - confirm: kind === "clean" && state.kind !== "absent", + confirm: kind === "clean" && mayHoldYourWork(state, forkedThisRun), }; } const untouched = state.kind === "copy"; - const tagged = state.kind === "handed-off-copy"; + const interrupted = state.kind === "interrupted-rebuild"; if (requested === "migrate" || requested === "introspect") { return { ...NOTHING_ELSE, kind: requested, handOff: untouched, keepsCopy: true, + confirm: false, }; } - if (tagged && !hasSchema && requested === undefined) { + if (interrupted && !hasSchema && requested === undefined) { throw new Error( "The rebuild of the app schema on your branch stopped before it finished, and this checkout has no config/database/schema.ts to rebuild from. Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", ); @@ -149,8 +157,9 @@ export function planStart( ...NOTHING_ELSE, kind: requested ?? (hasSchema ? "clean" : "introspect"), rebuild: true, - tag: !tagged, + tag: !interrupted, handOff: untouched, + confirm: false, }; } @@ -160,7 +169,7 @@ export function forkCopyRefusal( state: SchemaState, keep: "migrate" | "introspect", ): string | undefined { - if (state.kind !== "copy" && state.kind !== "handed-off-copy") { + if (state.kind !== "copy" && state.kind !== "interrupted-rebuild") { return undefined; } const holds = diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 1e143dcec..567a0d215 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1245,7 +1245,7 @@ describe("runInit — the start follows the branch's own state", () => { expect(tagWrites()).toEqual([]); }); - test("a handed-off copy without schema.ts says how to continue instead of guessing", async () => { + test("an interrupted rebuild without schema.ts says how to continue instead of guessing", async () => { schemaOwner = USER; tagged = true; diff --git a/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts index 0419ab4b6..4a6ee3cee 100644 --- a/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/schema-state.pg.test.ts @@ -119,7 +119,7 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { }); }); - test("once handed to you, a tagged schema reads as a handed-off copy, and untagging makes it yours", async () => { + test("once handed to you, a tagged schema reads as an interrupted rebuild, and untagging makes it yours", async () => { await admin.query(` alter schema "${app}" owner to "${dev}"; alter table "${app}".notes owner to "${dev}"; @@ -127,7 +127,7 @@ describe.skipIf(!url)("the fork-copy tag against Postgres", () => { `); await expect(readSchemaState(me, app)).resolves.toEqual({ - kind: "handed-off-copy", + kind: "interrupted-rebuild", }); await untagForkCopy(me, app); diff --git a/packages/appkit/src/database/tooling/tests/schema-state.test.ts b/packages/appkit/src/database/tooling/tests/schema-state.test.ts index fdfce91a8..026f6cb20 100644 --- a/packages/appkit/src/database/tooling/tests/schema-state.test.ts +++ b/packages/appkit/src/database/tooling/tests/schema-state.test.ts @@ -4,7 +4,7 @@ import { planStart, type SchemaState, type StartPlan } from "../schema-state"; const absent: SchemaState = { kind: "absent" }; const copy: SchemaState = { kind: "copy", owner: "app-sp" }; -const handedOff: SchemaState = { kind: "handed-off-copy" }; +const interrupted: SchemaState = { kind: "interrupted-rebuild" }; const yours: SchemaState = { kind: "yours" }; const pub: SchemaState = { kind: "public", kept: ["table notes"] }; @@ -45,17 +45,17 @@ describe("planStart", () => { ); }); - test("a handed-off copy is rebuilt without another hand-off or tag", () => { - expect(planStart(handedOff, undefined, true)).toEqual( + test("an interrupted rebuild is finished without another hand-off or tag", () => { + expect(planStart(interrupted, undefined, true)).toEqual( only({ kind: "clean", rebuild: true }), ); - expect(planStart(handedOff, "clean", true)).toEqual( + expect(planStart(interrupted, "clean", true)).toEqual( only({ kind: "clean", rebuild: true }), ); }); - test("a handed-off copy without schema.ts cannot be rebuilt by default: the message says how to continue", () => { - expect(() => planStart(handedOff, undefined, false)).toThrow( + test("an interrupted rebuild without schema.ts cannot be finished by default: the message says how to continue", () => { + expect(() => planStart(interrupted, undefined, false)).toThrow( "Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", ); }); @@ -66,7 +66,7 @@ describe("planStart", () => { expect(planStart(copy, requested, true)).toEqual( only({ kind: requested, handOff: true, keepsCopy: true }), ); - expect(planStart(handedOff, requested, true)).toEqual( + expect(planStart(interrupted, requested, true)).toEqual( only({ kind: requested, keepsCopy: true }), ); }, @@ -104,8 +104,8 @@ describe("planStart", () => { expect(planStart(copy, undefined, true, true)).toEqual( planStart(copy, undefined, true), ); - expect(planStart(handedOff, undefined, true, true)).toEqual( - planStart(handedOff, undefined, true), + expect(planStart(interrupted, undefined, true, true)).toEqual( + planStart(interrupted, undefined, true), ); }); @@ -120,7 +120,7 @@ describe("planStart", () => { only({ kind: "clean", rebuild: true }), ); expect(planStart(copy, "clean", true).confirm).toBe(false); - expect(planStart(handedOff, "clean", true).confirm).toBe(false); + expect(planStart(interrupted, "clean", true).confirm).toBe(false); }); test.each([absent, yours, pub] as const)( From 775e0d096484f90798d7db53df1c1bca34d09cbe Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:22:46 +0000 Subject: [PATCH 199/317] refactor: report a cancelled clean as an init outcome instead of a named error A no to the confirmation an explicit --schema clean asks for is a normal result, not a failure, so runInit now returns start: { kind: "cancelled", schemaName } with the branch, endpoint, role and .env the run did set up. InitCancelledError and the CLI's match on its name go. The CLI prints the same line and exits with code 1 as before. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/index.ts | 1 - packages/appkit/src/database/tooling/init.ts | 18 ++++++++---------- .../src/database/tooling/tests/init.test.ts | 14 ++++++++------ .../cli/commands/db/init-clean-seed.test.ts | 7 +------ packages/shared/src/cli/commands/db/init.ts | 16 ++++++++-------- .../src/cli/commands/db/tooling-contract.ts | 1 + 6 files changed, 26 insertions(+), 31 deletions(-) diff --git a/packages/appkit/src/database/tooling/index.ts b/packages/appkit/src/database/tooling/index.ts index d2f9bd6f8..3f7e09603 100644 --- a/packages/appkit/src/database/tooling/index.ts +++ b/packages/appkit/src/database/tooling/index.ts @@ -14,7 +14,6 @@ export { } from "./clean"; export { createDbContext, type DbContext } from "./context"; export { - InitCancelledError, type InitOptions, type InitReport, type InitStart, diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index b91ee0e06..1c0ec8e02 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -101,6 +101,7 @@ interface Rebuild { export type InitStart = | { readonly kind: "none" } + | { readonly kind: "cancelled"; readonly schemaName: string } | { readonly kind: "migrate"; readonly migrate: MigrateReport } | { readonly kind: "introspect"; @@ -113,13 +114,6 @@ export type KeptCopy = | { readonly reason: "requested"; readonly from: string | null } | { readonly reason: "public"; readonly objects: readonly string[] }; -export class InitCancelledError extends Error { - constructor(message: string) { - super(message); - this.name = "InitCancelledError"; - } -} - export interface InitReport { readonly mode: BranchMode; readonly branch: string; @@ -710,9 +704,13 @@ async function initHolding( options.confirmClean && !(await options.confirmClean({ branch: branch.name, schemaName })) ) { - throw new InitCancelledError( - `Cancelled. Schema ${schemaName} ${on} is as it was, and .env points at the branch.`, - ); + return { + ...base, + handedOff: null, + keptCopy: null, + installed: null, + start: { kind: "cancelled", schemaName }, + }; } const installed = ensureDrizzleKit( ctx.root, diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 567a0d215..fc38578a5 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -30,7 +30,7 @@ vi.mock("../introspect", async (importOriginal) => ({ import type { DbContext } from "../context"; import type { HistoryLock } from "../history-lock"; -import { InitCancelledError, type InitOptions, runInit } from "../init"; +import { type InitOptions, runInit } from "../init"; import { IntrospectRefusedError } from "../introspect"; import { LakebaseApiError } from "../lakebase-api"; import { runMigrate } from "../migrate"; @@ -1348,14 +1348,16 @@ describe("runInit — the start follows the branch's own state", () => { schemaOwner = USER; const ctx = appOn(existingDev()); - const refused = init(ctx, { + const { report } = await init(ctx, { schema: "clean", confirmClean: async () => false, }); - await expect(refused).rejects.toBeInstanceOf(InitCancelledError); - await expect(refused).rejects.toThrow( - `Cancelled. Schema app on ${devBranchId(USER)} is as it was, and .env points at the branch.`, - ); + expect(report).toMatchObject({ + branch: DEV, + handedOff: null, + installed: null, + start: { kind: "cancelled", schemaName: "app" }, + }); expect(cleanHolding).not.toHaveBeenCalled(); expect(envFile(ctx.root).LAKEBASE_ENDPOINT).toBe( `${DEV}/endpoints/primary`, diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index 4c7ef3f29..d1e095a08 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -71,12 +71,7 @@ function toolingThatAsks(): void { schemaName: "app", }); if (confirmed === false) { - throw Object.assign( - new Error( - "Cancelled. Schema app on dev-alice-3f9a2c is as it was, and .env points at the branch.", - ), - { name: "InitCancelledError" }, - ); + return { ...report, start: { kind: "cancelled", schemaName: "app" } }; } return report; }); diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index c85d11822..9cffedf84 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -94,7 +94,7 @@ function printInitReport( if (start.rebuilt) printRebuild(start.rebuilt); } else if (start.kind === "migrate") printMigrateReport(start.migrate); else if (start.kind === "clean") printRebuild(start); - else info("Left the schema as it is"); + else if (start.kind === "none") info("Left the schema as it is"); if (keptCopy?.reason === "requested") { warn( @@ -120,16 +120,16 @@ async function runDbInit(flags: InitFlags): Promise { onStep: info, onWarning: warn, }; - printInitReport( - await tooling.runInit(tooling.createDbContext(), options), - flags.schema, - ); - } catch (error) { - if (error instanceof Error && error.name === "InitCancelledError") { - info(error.message); + const report = await tooling.runInit(tooling.createDbContext(), options); + if (report.start.kind === "cancelled") { + info( + `Cancelled. Schema ${report.start.schemaName} on ${shortName(report.branch)} is as it was, and .env points at the branch.`, + ); process.exitCode = 1; return; } + printInitReport(report, flags.schema); + } catch (error) { fail(error); } } diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 13059c850..49c8c908a 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -77,6 +77,7 @@ export type KeptCopy = export type InitStart = | { readonly kind: "none" } + | { readonly kind: "cancelled"; readonly schemaName: string } | { readonly kind: "migrate"; readonly migrate: MigrateReport } | { readonly kind: "introspect"; From 419afb28869755025e9149ca7f8d8b2823814008 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:24:53 +0000 Subject: [PATCH 200/317] refactor: let init's report say why it rebuilt the schema A Rebuild carries reason: "fork-copy" when the branch still held the rows the fork copied and nothing was requested, or "requested" for an explicit --schema clean. The CLI prints its hint about keeping the copied rows from that field instead of inferring it from the start kind and the absence of --schema. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 9 ++++++-- .../database/tooling/tests/init.pg.test.ts | 11 ++++++++-- .../src/database/tooling/tests/init.test.ts | 21 +++++++++++++++++-- .../cli/commands/db/init-clean-seed.test.ts | 10 ++++++--- packages/shared/src/cli/commands/db/init.ts | 11 +++++++--- .../src/cli/commands/db/tooling-contract.ts | 1 + 6 files changed, 51 insertions(+), 12 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 1c0ec8e02..866f4d92f 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -93,10 +93,13 @@ export interface InitOptions { 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 = @@ -757,8 +760,10 @@ async function initHolding( } const rebuildSchema = async (): Promise => { + const reason: RebuildReason = + requested === undefined ? "fork-copy" : "requested"; const why = - requested === undefined + reason === "fork-copy" ? ": the branch still holds the rows the fork copied, and the committed migrations recreate its tables" : ""; onStep( @@ -771,7 +776,7 @@ async function initHolding( interactive, generate: false, }); - return { clean, migrate }; + return { clean, migrate, reason }; }; let start: InitStart; if (plan.kind === "migrate") { diff --git a/packages/appkit/src/database/tooling/tests/init.pg.test.ts b/packages/appkit/src/database/tooling/tests/init.pg.test.ts index b282e4201..2210b24e3 100644 --- a/packages/appkit/src/database/tooling/tests/init.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.pg.test.ts @@ -254,7 +254,11 @@ describe.skipIf(!url)("runInit against Postgres", () => { sourceBranch: PRODUCTION, handedOff: sp, keptCopy: null, - start: { kind: "clean", migrate: { applied: ["0000_migration"] } }, + start: { + kind: "clean", + reason: "fork-copy", + migrate: { applied: ["0000_migration"] }, + }, }); expect(steps).toContain( `Dropping schema ${app} on ${devBranchId(USER)}: the branch still holds the rows the fork copied, and the committed migrations recreate its tables`, @@ -396,7 +400,10 @@ describe.skipIf(!url)("runInit against Postgres", () => { }, }); expect(asked).toEqual([app]); - expect(cleaned.report.start.kind).toBe("clean"); + expect(cleaned.report.start).toMatchObject({ + kind: "clean", + reason: "requested", + }); expect(await rows(`"${app}".notes`)).toEqual([]); }); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index fc38578a5..802116dcf 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -267,6 +267,7 @@ describe("runInit — dev branch", () => { kind: "clean", clean: { branch: DEV, schemaName: "app", dependents: [], kept: [] }, migrate: migrateReport, + reason: "fork-copy", }, }); expect(steps).toEqual([ @@ -977,6 +978,7 @@ describe("runInit — schema start", () => { rebuilt: { clean: { branch: DEV, schemaName: "app", dependents: [], kept: [] }, migrate: migrateReport, + reason: "fork-copy", }, }); expect(introspectHolding.mock.calls[0]?.[2]).toEqual({ @@ -1054,6 +1056,7 @@ describe("runInit — schema start", () => { kind: "clean", clean: { branch: DEV, schemaName: "app", dependents: [], kept: [] }, migrate: migrateReport, + reason: "requested", }); }); @@ -1335,13 +1338,27 @@ describe("runInit — the start follows the branch's own state", () => { return true; }; - await init(appOn(project()), { schema: "clean", confirmClean }); + const onCopy = await init(appOn(project()), { + schema: "clean", + confirmClean, + }); expect(asked).toEqual([]); + expect(onCopy.report.start).toMatchObject({ + kind: "clean", + reason: "requested", + }); schemaOwner = USER; tagged = false; - await init(appOn(existingDev()), { schema: "clean", confirmClean }); + const onYours = await init(appOn(existingDev()), { + schema: "clean", + confirmClean, + }); expect(asked).toEqual([{ branch: DEV, schemaName: "app" }]); + expect(onYours.report.start).toMatchObject({ + kind: "clean", + reason: "requested", + }); }); test("a no to the confirmation stops before the drop, with .env already pointing at the branch", async () => { diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index d1e095a08..792023ed2 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -248,6 +248,7 @@ describe("appkit db init", () => { kept: [], }, migrate, + reason: "requested", }, }); await init("--schema", "clean", "--yes"); @@ -261,7 +262,7 @@ describe("appkit db init", () => { }); test("a rebuild without --schema says the copied rows went and how to keep them; with --schema clean it does not", async () => { - const rebuilt = { + const rebuilt = (reason: "fork-copy" | "requested") => ({ ...report, start: { kind: "clean", @@ -272,9 +273,10 @@ describe("appkit db init", () => { kept: [], }, migrate, + reason, }, - }; - tooling.runInit.mockResolvedValue(rebuilt); + }); + tooling.runInit.mockResolvedValue(rebuilt("fork-copy")); await init(); expect(output(log)).toContain( "The branch still held the rows the fork copied: the app schema was rebuilt from the committed migrations. `appkit db init --schema migrate` keeps them.", @@ -282,6 +284,7 @@ describe("appkit db init", () => { log.mockClear(); resetOptionValues(); + tooling.runInit.mockResolvedValue(rebuilt("requested")); await init("--schema", "clean", "--yes"); expect(output(log)).toContain("Dropped schema app on dev-alice-3f9a2c"); expect(output(log)).not.toContain("The branch still held the rows"); @@ -359,6 +362,7 @@ describe("appkit db init", () => { kept: [], }, migrate: { ...migrate, applied: ["0000_baseline"] }, + reason: "fork-copy", }, }, }); diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index 9cffedf84..acd17dd51 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -15,6 +15,7 @@ import { import type { InitOptions, InitReport, + InitStart, Rebuild, SchemaStart, } from "./tooling-contract"; @@ -48,6 +49,12 @@ const confirmClean: NonNullable = async ({ return !isCancel(answer) && answer; }; +function rebuildOf(start: InitStart): Rebuild | null { + if (start.kind === "clean") return start; + if (start.kind === "introspect") return start.rebuilt; + return null; +} + function printRebuild(rebuild: Rebuild): void { printCleanReport(rebuild.clean); printMigrateReport(rebuild.migrate); @@ -80,9 +87,7 @@ function printInitReport( if (report.installed) ok(`Installed drizzle-kit (${report.installed})`); const { start, keptCopy } = report; - const rebuilt = - start.kind === "clean" || (start.kind === "introspect" && start.rebuilt); - if (rebuilt && schemaFlag === undefined) { + if (rebuildOf(start)?.reason === "fork-copy") { info( `The branch still held the rows the fork copied: the app schema was rebuilt from the committed migrations. \`appkit db init --schema ${start.kind === "introspect" ? "introspect" : "migrate"}\` keeps them.`, ); diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 49c8c908a..51a3a2328 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -69,6 +69,7 @@ export interface CleanReport { export interface Rebuild { readonly clean: CleanReport; readonly migrate: MigrateReport; + readonly reason: "fork-copy" | "requested"; } export type KeptCopy = From 89c258cea384342544b6a6c9b890911027a7f68c Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:39:49 +0000 Subject: [PATCH 201/317] test(appkit): local verify must report the fork's untouched copy too A copy the service principal still owns passes verify today: it has every table and every committed migration, so nothing says its rows are not yours. Verify must report it the way migrate does when it refuses, with the init advice for the state the branch is in, and must leave the fork-copy tag out of the unknown count without correcting it by hand. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/verify.pg.test.ts | 37 ++++++++++++++++--- .../src/database/tooling/tests/verify.test.ts | 37 +++++++++++++++++-- 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts index 0fe403d5b..e0b819984 100644 --- a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts @@ -29,7 +29,9 @@ const BRANCH = "projects/p/branches/dev-alice-3f9a2c"; const MIGRATION = { tag: "0000_migration", when: 1700000000000 }; describe.skipIf(!url)("runVerify against Postgres", () => { - const schema = `verify_${randomUUID().slice(0, 8)}`; + const suffix = randomUUID().slice(0, 8); + const schema = `verify_${suffix}`; + const sp = `verify_sp_${suffix}`; const journal = `"${schema}".__drizzle_migrations`; let admin: Pool; let ctx: DbContext; @@ -69,9 +71,12 @@ describe.skipIf(!url)("runVerify against Postgres", () => { ); // The branch as a fork copied it: the migration ran there and its journal records it. await admin.query(` - create schema "${schema}"; + create role "${sp}" nologin; + create schema "${schema}" authorization "${sp}"; + set role "${sp}"; ${sql} create table ${journal} (id serial primary key, hash text not null, created_at bigint); + reset role; `); await admin.query( `insert into ${journal} (hash, created_at) values ($1, $2)`, @@ -104,12 +109,32 @@ describe.skipIf(!url)("runVerify against Postgres", () => { }); afterAll(async () => { - await admin.query(`drop schema if exists "${schema}" cascade`); + await admin.query(` + drop schema if exists "${schema}" cascade; + drop owned by "${sp}"; + drop role if exists "${sp}"; + `); await admin.end(); fs.rmSync(ctx.root, { recursive: true, force: true }); }); - test("tagged by init, the copy is reported as awaiting its rebuild, and the tag is not an unknown migration", async () => { + test("the fork's untouched copy, which the service principal still owns, is reported with the init advice", async () => { + expect(await runVerify(ctx)).toEqual({ + kind: "local", + branch: BRANCH, + schemaProblems: [], + schemaAdvice: null, + pendingMigrations: [], + strandedMigrations: [], + editedMigrations: [], + unknownMigrations: 0, + forkCopy: `dev-alice-3f9a2c still holds the rows the fork copied into schema "${schema}", which "${sp}" still owns. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema migrate\` to keep them.`, + ok: false, + }); + }); + + test("handed to you and tagged by init, the copy is reported as awaiting its rebuild, and the tag is not an unknown migration", async () => { + await admin.query(`reassign owned by "${sp}" to current_user`); await admin.query( `insert into ${journal} (hash, created_at) values ($1, 0)`, [FORK_COPY_TAG], @@ -124,7 +149,7 @@ describe.skipIf(!url)("runVerify against Postgres", () => { strandedMigrations: [], editedMigrations: [], unknownMigrations: 0, - forkCopy: true, + forkCopy: `dev-alice-3f9a2c still holds the rows the fork copied into schema "${schema}", and its rebuild did not finish. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema migrate\` to keep them.`, ok: false, }); }); @@ -136,7 +161,7 @@ describe.skipIf(!url)("runVerify against Postgres", () => { expect(await runVerify(ctx)).toMatchObject({ unknownMigrations: 0, - forkCopy: false, + forkCopy: null, ok: true, }); }); diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 5b2da1447..1413d4185 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -111,6 +111,7 @@ function branch(state: { recorded: Array<{ hash: string; created_at: string }> | "absent"; /** Declared tables that exist in schema public instead. */ inPublic?: string[]; + schemaOwner?: string; failOn?: RegExp; }) { const statements: string[] = []; @@ -139,6 +140,17 @@ function branch(state: { ), }; } + if (/has_schema_privilege/.test(text)) { + return { + rows: [ + { + owner: state.schemaOwner ?? "app-sp", + can_create: true, + current_user: "app-sp", + }, + ], + }; + } if (/from pg_catalog\.pg_class c\s+join/.test(text)) { // The app's own journal: an ordinary table its role owns. const journalTable = { @@ -201,7 +213,7 @@ describe("runVerify", () => { strandedMigrations: [], editedMigrations: [], unknownMigrations: 0, - forkCopy: false, + forkCopy: null, }; test("a branch that matches schema.ts and has every migration is ok", async () => { @@ -300,6 +312,24 @@ describe("runVerify", () => { }); }); + test("the fork's untouched copy, which another role still owns, is reported with the init advice", async () => { + const ctx = app(two); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + schemaOwner: "deployed-sp", + }); + + expect(await runVerify(ctx)).toEqual({ + kind: "local", + branch: BRANCH, + ...clean, + forkCopy: + 'dev-alice-3f9a2c still holds the rows the fork copied into schema "app", which "deployed-sp" still owns. Run `appkit db init` to rebuild it from the committed migrations, or `appkit db init --schema migrate` to keep them.', + ok: false, + }); + }); + test("a fork's copy whose rebuild did not finish is reported as one, and its tag is not an unknown migration", async () => { const ctx = app(two); branch({ @@ -314,7 +344,8 @@ describe("runVerify", () => { kind: "local", branch: BRANCH, ...clean, - forkCopy: true, + forkCopy: + '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 migrate` to keep them.', ok: false, }); }); @@ -331,7 +362,7 @@ describe("runVerify", () => { }); expect(await runVerify(ctx)).toMatchObject({ - forkCopy: true, + forkCopy: expect.stringContaining("Run `appkit db init`"), unknownMigrations: 1, ok: false, }); From a452886d7f636e3c2412a75d10884fa3149a55d5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:42:16 +0000 Subject: [PATCH 202/317] fix(appkit): report both fork-copy states from local verify, with migrate's advice Local verify read only the tag, so a copy the service principal still owns passed. It now reads the schema state in the same read-only transaction and carries migrate's refusal text as the report's forkCopy, null when the schema is yours, absent or public. The drift read leaves the tag out through ignoreHashes instead of a hand correction of the unknown count. The never-writes guard now matches a statement's verb, as the ownership read names the CREATE privilege. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 2 +- .../appkit/src/database/tooling/verify.ts | 30 +++++++++++-------- .../src/cli/commands/db/tooling-contract.ts | 3 +- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 1413d4185..5fed95f76 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -189,7 +189,7 @@ function branch(state: { return { statements, client, pool }; } -const WRITES = /\b(insert|update|delete|create|drop|alter|grant|truncate)\b/i; +const WRITES = /^\s*(insert|update|delete|create|drop|alter|grant|truncate)\b/i; beforeEach(() => { withBranchPool.mockReset(); diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index cd0e83d21..cb617281c 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -23,7 +23,11 @@ import { withBranchPool, } from "./context"; import { requireSchemaFile } from "./migrate"; -import { isForkCopy } from "./schema-state"; +import { + FORK_COPY_TAG, + forkCopyRefusal, + readSchemaState, +} from "./schema-state"; import { type BundleTarget, defaultBundleTarget, @@ -55,12 +59,7 @@ interface LocalVerifyReport { readonly editedMigrations: readonly string[]; /** Migrations the branch ran that this checkout does not commit, e.g. from another git branch. */ readonly unknownMigrations: number; - /** - * The branch still holds the rows a fork copied into the app schema, tagged - * by `appkit db init`, and its rebuild did not finish. `appkit db migrate` - * refuses such a branch, so nothing on it is this checkout's work. - */ - readonly forkCopy: boolean; + readonly forkCopy: string | null; readonly ok: boolean; } @@ -137,13 +136,18 @@ async function verifyLocal(ctx: DbContext): Promise { await client.query("begin transaction read only"); const { problems: schemaProblems, advice: schemaAdvice } = await diagnoseSchema(rawOn(client), schema); - const forkCopy = await isForkCopy(client, schema.$schemaName); + const forkCopy = + forkCopyRefusal( + branch, + schema.$schemaName, + await readSchemaState(client, schema.$schemaName), + "migrate", + ) ?? null; const drift = await readMigrationDrift(client, { migrationsFolder: migrationsFolder(ctx.root), schemaName: schema.$schemaName, + ignoreHashes: [FORK_COPY_TAG], }); - // The tag is one journal row no committed migration matches, so the drift counts it once. - const unknownMigrations = drift.unknown - (forkCopy ? 1 : 0); return { kind: "local", branch, @@ -152,15 +156,15 @@ async function verifyLocal(ctx: DbContext): Promise { pendingMigrations: drift.pending, strandedMigrations: drift.stranded, editedMigrations: drift.edited, - unknownMigrations, + unknownMigrations: drift.unknown, forkCopy, ok: - !forkCopy && + forkCopy === null && schemaProblems.length === 0 && drift.pending.length === 0 && drift.stranded.length === 0 && drift.edited.length === 0 && - unknownMigrations === 0, + drift.unknown === 0, }; } finally { await client.query("rollback").catch(() => undefined); diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index fff657364..927ea818d 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -102,8 +102,7 @@ export interface LocalVerifyReport { readonly strandedMigrations: readonly string[]; readonly editedMigrations: readonly string[]; readonly unknownMigrations: number; - /** The branch still holds a fork's copy, tagged by `appkit db init`, and its rebuild did not finish. */ - readonly forkCopy: boolean; + readonly forkCopy: string | null; readonly ok: boolean; } From 3594e95040c64caf63266b700db7773cd62e17ae Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:43:17 +0000 Subject: [PATCH 203/317] test(shared): verify must print the fork-copy advice the tooling reports The tooling now reports forkCopy as the advice for the state the branch is in, an untouched copy or an interrupted rebuild. The CLI must print that line as the verdict, and no hint that says migrate or clean. Co-authored-by: Isaac Signed-off-by: ditadi --- .../shared/src/cli/commands/db/verify.test.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index eb6e9dcaa..f49fdcdd8 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -38,10 +38,13 @@ const local = { strandedMigrations: [], editedMigrations: [], unknownMigrations: 0, - forkCopy: false, + forkCopy: null, ok: true, }; +const FORK_COPY = + 'dev-alice-3f9a2c still holds the rows the fork copied into schema "app", which "app-sp" still owns. Run `appkit db init` to rebuild it from the committed migrations, or `appkit db init --schema migrate` to keep them.'; + /** Commander keeps parsed option values on the command; each test parses afresh. */ function resetOptionValues() { for (const command of dbCommand.commands) { @@ -202,14 +205,12 @@ describe("appkit db verify", () => { expect(process.exitCode).toBe(1); }); - test("a fork's copy whose rebuild did not finish is told to rebuild with init, as migrate refuses it", async () => { - runVerify.mockResolvedValue({ ...local, forkCopy: true, ok: false }); + test("a fork's copy is told to rebuild with init, as the tooling reports it and migrate refuses it", async () => { + runVerify.mockResolvedValue({ ...local, forkCopy: FORK_COPY, ok: false }); await dbCommand.parseAsync(["verify"], { from: "user" }); - expect(output(error)).toContain( - "dev-alice-3f9a2c still holds the rows the fork copied into the app schema, and its rebuild did not finish. Run `appkit db init` to rebuild it from the committed migrations, or `appkit db init --schema migrate` to keep them.", - ); + expect(output(error)).toContain(FORK_COPY); expect(output(error)).not.toContain("does not match"); expect(process.exitCode).toBe(1); }); @@ -218,7 +219,7 @@ describe("appkit db verify", () => { runVerify.mockResolvedValue({ ...local, pendingMigrations: ["0002_migration"], - forkCopy: true, + forkCopy: FORK_COPY, ok: false, }); From 967158515b104e34d3408fc250c14af47fcf466c Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:44:01 +0000 Subject: [PATCH 204/317] fix(shared): print the fork-copy advice the tooling reports from verify The tooling builds the line from the state it read, so the CLI prints it as the verdict instead of its own text, which only knew the interrupted rebuild. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/shared/src/cli/commands/db/output.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 88fc3b7c6..6dd51ad57 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -169,11 +169,8 @@ function printLocalVerifyReport(report: LocalVerifyReport): void { `Not committed: the branch ran ${report.unknownMigrations} migration${one ? "" : "s"} this checkout does not have, for example from another git branch`, ); } - // A copy may match schema.ts and the journal; its rows are still not yours, and migrate refuses it. if (report.forkCopy) { - console.error( - `${pc.red("✖")} ${branch} still holds the rows the fork copied into the app schema, and its rebuild did not finish. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema migrate\` to keep them.`, - ); + console.error(`${pc.red("✖")} ${report.forkCopy}`); return; } console.error( From 891be8be26cb3b38732f719f4a1ec12bac04bbc5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:44:52 +0000 Subject: [PATCH 205/317] test(appkit): drop the narration comments from verify's tests The comment audit of the stack killed them. The describe gate, the setup statements and the stub's regex say what they said. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/tests/verify.pg.test.ts | 4 ---- packages/appkit/src/database/tooling/tests/verify.test.ts | 1 - 2 files changed, 5 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts index e0b819984..159a0d52f 100644 --- a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts @@ -17,9 +17,6 @@ import type { DbContext } from "../context"; import { FORK_COPY_TAG } from "../schema-state"; import { runVerify } from "../verify"; -// Local verify against a real server: the Lakebase pool is replaced, nothing -// else. APPKIT_TEST_PG_URL points at a scratch database, e.g. -// postgres://localhost:5432/postgres const url = process.env.APPKIT_TEST_PG_URL; const builder = path.resolve( import.meta.dirname, @@ -69,7 +66,6 @@ describe.skipIf(!url)("runVerify against Postgres", () => { ], }), ); - // The branch as a fork copied it: the migration ran there and its journal records it. await admin.query(` create role "${sp}" nologin; create schema "${schema}" authorization "${sp}"; diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 5fed95f76..93c8930be 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -166,7 +166,6 @@ function branch(state: { if (/select hash, created_at from/.test(text)) { return { rows: state.recorded === "absent" ? [] : state.recorded }; } - // isForkCopy: whether the journal has the row init writes into a fork's copy. if (/where hash = \$1 limit 1/.test(text)) { const rows = state.recorded === "absent" ? [] : state.recorded; return { rows: rows.filter((row) => row.hash === values?.[0]) }; From d049149fd5328a61501eff44de481af77b038f01 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:54:03 +0000 Subject: [PATCH 206/317] docs(appkit): qualify what a plain init does after --schema none Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 68a6a6db9..fac82d11c 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -175,8 +175,10 @@ you picked in its prompts, usually the branch the app deploys to, 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, so the - next plain `init` still rebuilds it. + 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. From e030a1cf22dac1d043a3c25379f2a397526f74d8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 22:56:11 +0000 Subject: [PATCH 207/317] docs(appkit): stop claiming the role delete reassigns in every database Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index fac82d11c..da9a64e54 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -564,9 +564,10 @@ 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 every object the role owns -in every database of the branch, drops the role's memberships and grants, and -removes the role. So first take the inventory `db init` takes before it hands a +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 From 6d623e019f3ff5f31f0d6d962116b7b780e6715e Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 23:03:54 +0000 Subject: [PATCH 208/317] test(appkit): local verify must report a fork copy only on your own branch verify reads any .env branch, production included, where another role owning the app schema is the normal state. The tests now run on a branch id that a real user name hashes to, with that user in PGUSER, and add a deploy branch and another user's dev branch that must verify with no fork-copy report. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/verify.pg.test.ts | 30 +++++++- .../src/database/tooling/tests/verify.test.ts | 72 +++++++++++++++++-- 2 files changed, 94 insertions(+), 8 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts index 159a0d52f..2bc543bb9 100644 --- a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts @@ -14,6 +14,7 @@ vi.mock("../context", async (importOriginal) => ({ })); import type { DbContext } from "../context"; +import { devBranchId } from "../naming"; import { FORK_COPY_TAG } from "../schema-state"; import { runVerify } from "../verify"; @@ -22,7 +23,9 @@ const builder = path.resolve( import.meta.dirname, "../../schema-builder/index.ts", ); -const BRANCH = "projects/p/branches/dev-alice-3f9a2c"; +const USER = "alice@example.com"; +const BRANCH = `projects/p/branches/${devBranchId(USER)}`; +const PRODUCTION = "projects/p/branches/production"; const MIGRATION = { tag: "0000_migration", when: 1700000000000 }; describe.skipIf(!url)("runVerify against Postgres", () => { @@ -84,6 +87,7 @@ describe.skipIf(!url)("runVerify against Postgres", () => { PGHOST: "ep-1.example.com", PGDATABASE: "databricks_postgres", LAKEBASE_ENDPOINT: `${BRANCH}/endpoints/primary`, + PGUSER: USER, }, workspace: () => { throw new Error("no workspace calls expected"); @@ -114,6 +118,26 @@ describe.skipIf(!url)("runVerify against Postgres", () => { fs.rmSync(ctx.root, { recursive: true, force: true }); }); + test("on a deploy branch, the app schema its service principal owns is not a fork copy", async () => { + const deploy = { + ...ctx, + env: { ...ctx.env, LAKEBASE_ENDPOINT: `${PRODUCTION}/endpoints/primary` }, + }; + + expect(await runVerify(deploy)).toEqual({ + kind: "local", + branch: PRODUCTION, + schemaProblems: [], + schemaAdvice: null, + pendingMigrations: [], + strandedMigrations: [], + editedMigrations: [], + unknownMigrations: 0, + forkCopy: null, + ok: true, + }); + }); + test("the fork's untouched copy, which the service principal still owns, is reported with the init advice", async () => { expect(await runVerify(ctx)).toEqual({ kind: "local", @@ -124,7 +148,7 @@ describe.skipIf(!url)("runVerify against Postgres", () => { strandedMigrations: [], editedMigrations: [], unknownMigrations: 0, - forkCopy: `dev-alice-3f9a2c still holds the rows the fork copied into schema "${schema}", which "${sp}" still owns. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema migrate\` to keep them.`, + forkCopy: `${devBranchId(USER)} still holds the rows the fork copied into schema "${schema}", which "${sp}" still owns. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema migrate\` to keep them.`, ok: false, }); }); @@ -145,7 +169,7 @@ describe.skipIf(!url)("runVerify against Postgres", () => { strandedMigrations: [], editedMigrations: [], unknownMigrations: 0, - forkCopy: `dev-alice-3f9a2c still holds the rows the fork copied into schema "${schema}", and its rebuild did not finish. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema migrate\` to keep them.`, + forkCopy: `${devBranchId(USER)} still holds the rows the fork copied into schema "${schema}", and its rebuild did not finish. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema migrate\` to keep them.`, ok: false, }); }); diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 93c8930be..bfc054451 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -14,6 +14,7 @@ vi.mock("../context", async (importOriginal) => ({ import type { WorkspaceRequest } from "../../../workspace-client"; import type { DbContext } from "../context"; +import { devBranchId, sessionBranchId } from "../naming"; import { FORK_COPY_TAG } from "../schema-state"; import { runVerify, type VerifyOptions } from "../verify"; import { databricksYml, FakeLakebase } from "./fakes"; @@ -22,11 +23,13 @@ const builder = path.resolve( import.meta.dirname, "../../schema-builder/index.ts", ); -const BRANCH = "projects/p/branches/dev-alice-3f9a2c"; +const USER = "alice@example.com"; +const BRANCH = `projects/p/branches/${devBranchId(USER)}`; const ENV = { PGHOST: "ep-1.example.com", PGDATABASE: "databricks_postgres", LAKEBASE_ENDPOINT: `${BRANCH}/endpoints/primary`, + PGUSER: USER, }; const MIGRATIONS = "config/database/migrations"; const roots: string[] = []; @@ -323,8 +326,7 @@ describe("runVerify", () => { kind: "local", branch: BRANCH, ...clean, - forkCopy: - 'dev-alice-3f9a2c still holds the rows the fork copied into schema "app", which "deployed-sp" still owns. Run `appkit db init` to rebuild it from the committed migrations, or `appkit db init --schema migrate` to keep them.', + forkCopy: `${devBranchId(USER)} still holds the rows the fork copied into schema "app", which "deployed-sp" still owns. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema migrate\` to keep them.`, ok: false, }); }); @@ -343,8 +345,7 @@ describe("runVerify", () => { kind: "local", branch: BRANCH, ...clean, - forkCopy: - '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 migrate` to keep them.', + forkCopy: `${devBranchId(USER)} 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 migrate\` to keep them.`, ok: false, }); }); @@ -367,6 +368,67 @@ describe("runVerify", () => { }); }); + test("on your session branch, the fork's copy is reported as on your dev branch", async () => { + const session = `projects/p/branches/${sessionBranchId(USER, "abc12345")}`; + const ctx = app(two, { + ...ENV, + LAKEBASE_ENDPOINT: `${session}/endpoints/primary`, + }); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + schemaOwner: "deployed-sp", + }); + + expect(await runVerify(ctx)).toMatchObject({ + branch: session, + forkCopy: expect.stringContaining( + `${sessionBranchId(USER, "abc12345")} still holds the rows the fork copied`, + ), + ok: false, + }); + }); + + test("on a deploy branch, the app schema its service principal owns is not a fork copy", async () => { + const ctx = app(two, { + ...ENV, + LAKEBASE_ENDPOINT: `${PRODUCTION}/endpoints/primary`, + }); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + schemaOwner: "deployed-sp", + }); + + expect(await runVerify(ctx)).toEqual({ + kind: "local", + branch: PRODUCTION, + ...clean, + ok: true, + }); + }); + + test("on another user's dev branch, the schema they own is not a fork copy, and the other checks still decide", async () => { + const other = `projects/p/branches/${devBranchId("bob@example.com")}`; + const ctx = app(two, { + ...ENV, + LAKEBASE_ENDPOINT: `${other}/endpoints/primary`, + }); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two.slice(0, 1)), + schemaOwner: "bob", + }); + + expect(await runVerify(ctx)).toEqual({ + kind: "local", + branch: other, + ...clean, + pendingMigrations: ["0001_migration"], + ok: false, + }); + }); + test("a migration the branch ran that this checkout does not commit is reported", async () => { const ctx = app(two); branch({ From f22e777558467212cd05ef4e870f2c24209a24a7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 23:05:29 +0000 Subject: [PATCH 209/317] fix(appkit): report a fork copy from local verify only on your own branch verify reads whichever branch .env names, production included, and reported any app schema another role owns as the fork's copy, with advice to rebuild it. Only init forks a copy, onto the developer's own dev or session branch, so verify now reads the schema state only when PGUSER's branch id matches the branch, as init wrote both. On any other branch forkCopy is null and the other checks decide ok. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/verify.ts | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index cb617281c..bcb2b6989 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -23,6 +23,7 @@ import { withBranchPool, } from "./context"; import { requireSchemaFile } from "./migrate"; +import { isUsersBranchId } from "./naming"; import { FORK_COPY_TAG, forkCopyRefusal, @@ -59,6 +60,7 @@ interface LocalVerifyReport { readonly editedMigrations: readonly string[]; /** Migrations the branch ran that this checkout does not commit, e.g. from another git branch. */ readonly unknownMigrations: number; + /** On your own dev or session branch, the fork's copy init has not rebuilt yet, with its advice; null elsewhere. */ readonly forkCopy: string | null; readonly ok: boolean; } @@ -136,13 +138,19 @@ async function verifyLocal(ctx: DbContext): Promise { await client.query("begin transaction read only"); const { problems: schemaProblems, advice: schemaAdvice } = await diagnoseSchema(rawOn(client), schema); + // Only init forks a copy, onto the developer's own branch. Elsewhere, + // e.g. production, another owner is the normal state. init writes the + // user name it hashed into that branch id to PGUSER, so .env decides. + const user = ctx.env.PGUSER; const forkCopy = - forkCopyRefusal( - branch, - schema.$schemaName, - await readSchemaState(client, schema.$schemaName), - "migrate", - ) ?? null; + user && isUsersBranchId(user, resourceId(branch)) + ? (forkCopyRefusal( + branch, + schema.$schemaName, + await readSchemaState(client, schema.$schemaName), + "migrate", + ) ?? null) + : null; const drift = await readMigrationDrift(client, { migrationsFolder: migrationsFolder(ctx.root), schemaName: schema.$schemaName, From e2e5b75db3b9f07ba604559ce33e5cb43091185c Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 23:09:12 +0000 Subject: [PATCH 210/317] test(appkit): point the verify branch tests at their branch through init's resolver Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/verify.pg.test.ts | 8 ++++++++ .../src/database/tooling/tests/verify.test.ts | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts index 1ef2e08da..2985f1e12 100644 --- a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts @@ -135,10 +135,18 @@ describe.skipIf(!url)("runVerify against Postgres", () => { ...ctx, env: { ...ctx.env, LAKEBASE_ENDPOINT: `${PRODUCTION}/endpoints/primary` }, }; + resolveEnvBranch.mockResolvedValueOnce({ + branch: { name: PRODUCTION }, + boundary: { branches: new Set(), unresolved: [] }, + kind: "deploy-target", + reason: "databricks.yml deploys to it", + }); expect(await runVerify(deploy)).toEqual({ kind: "local", branch: PRODUCTION, + notYours: "databricks.yml deploys to it", + refusesEveryBranch: null, schemaProblems: [], schemaAdvice: null, pendingMigrations: [], diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 3d2c278f5..0b72dce44 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -395,6 +395,11 @@ describe("runVerify", () => { recorded: recordedAs(ctx, two), schemaOwner: "deployed-sp", }); + resolveEnvBranch.mockResolvedValueOnce({ + branch: { name: session }, + boundary: RESOLVED, + kind: "session", + }); expect(await runVerify(ctx)).toMatchObject({ branch: session, @@ -415,11 +420,18 @@ describe("runVerify", () => { recorded: recordedAs(ctx, two), schemaOwner: "deployed-sp", }); + resolveEnvBranch.mockResolvedValueOnce({ + branch: { name: PRODUCTION }, + boundary: RESOLVED, + kind: "deploy-target", + reason: "databricks.yml deploys to it", + }); expect(await runVerify(ctx)).toEqual({ kind: "local", branch: PRODUCTION, ...clean, + notYours: "databricks.yml deploys to it", ok: true, }); }); @@ -435,11 +447,18 @@ describe("runVerify", () => { recorded: recordedAs(ctx, two.slice(0, 1)), schemaOwner: "bob", }); + resolveEnvBranch.mockResolvedValueOnce({ + branch: { name: other }, + boundary: RESOLVED, + kind: "other", + reason: "it is another user's dev branch", + }); expect(await runVerify(ctx)).toEqual({ kind: "local", branch: other, ...clean, + notYours: "it is another user's dev branch", pendingMigrations: ["0001_migration"], ok: false, }); From 5b07d34624322bc1bc546239df30c047eb6e11c3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 23:26:32 +0000 Subject: [PATCH 211/317] test(appkit): let the init Postgres test's sessions close before it drops its database Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.pg.test.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/tests/init.pg.test.ts b/packages/appkit/src/database/tooling/tests/init.pg.test.ts index 2210b24e3..9721d1b34 100644 --- a/packages/appkit/src/database/tooling/tests/init.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.pg.test.ts @@ -223,7 +223,17 @@ describe.skipIf(!url)("runInit against Postgres", () => { await asDev?.end(); await asSp?.end(); await admin?.end(); - await cluster.query(`drop database if exists "${database}" with (force)`); + // pool.end() resolves before the server sees the clients leave; a forced + // drop then kills them mid-close and pg raises it as an uncaught error. + for (let tries = 0; tries < 50; tries++) { + const { rows } = await cluster.query<{ open: number }>( + "select count(*)::int as open from pg_stat_activity where datname = $1", + [database], + ); + if (rows[0]?.open === 0) break; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + await cluster.query(`drop database if exists "${database}"`); await cluster.query(` drop owned by "${sp}", "${dev}", "${superuser}"; drop role if exists "${dev}"; From eb7997d4035d526afaf7a25df1dfe5d7a24ebcdb Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 23:45:20 +0000 Subject: [PATCH 212/317] test(appkit): pin introspect on undeclared foreign keys and new columns AutoCRUD is replaced by named operations, so introspect no longer guards the generated HTTP surface. A foreign key the replaced schema.ts does not declare renders with fk() instead of refusing the run. A column it does not declare is written as the catalog has it, not .private(). A .private() the old file declares is kept. Warnings about NOT NULL columns and dropped defaults name app.database.

, which still inserts through schema.ts. The round-trip test asserts the schema itself survives a refresh, with no dependency on the crud capabilities. Co-authored-by: Isaac Signed-off-by: ditadi --- .../introspect/tests/introspect.test.ts | 97 ++++++----- .../tooling/introspect/tests/render.test.ts | 60 +++---- .../introspect/tests/roundtrip.test.ts | 155 ++++++++++++++---- 3 files changed, 193 insertions(+), 119 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index cdef40ace..e9027dd9d 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -234,12 +234,12 @@ describe("runIntrospect", () => { expect(written).toContain( 'author_id: fk(() => authors.id).notNull().onDelete("cascade"),', ); - // What the replaced schema.ts declares keeps its privacy; the rest is private. + // 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().private(),", + "created_at: timestamp({ withTimezone: true }).notNull().defaultNow(),", ); expect(written).toContain("id: id(),"); expect(report).toMatchObject({ @@ -260,7 +260,6 @@ describe("runIntrospect", () => { 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\)\./, ), - "app.authors.created_at, app.posts.status are new to schema.ts, so they are private: the API does not return or accept them until you remove .private().", ]); expect(report.approximated).toEqual([ "app.authors.id: a serial key is declared as id(), an identity generated BY DEFAULT", @@ -501,67 +500,63 @@ describe("runIntrospect", () => { }); test("--schema-name overrides the schema schema.ts declares, which then declares nothing in it", async () => { - const root = tempApp({ - [SCHEMA]: previousSchema.replace("}));", '}), { schemaName: "sales" });'), - }); - const before = tree(root); + const salesSchema = previousSchema + .replace("email: text()", "email: text().private()") + .replace("}));", '}), { schemaName: "sales" });'); + const root = tempApp({ [SCHEMA]: salesSchema }); - const error = await rejection( - runIntrospect(ctxFor(root), { - interactive: false, - importSource: BUILDER, - schemaName: "app", - }), - ); + const report = await runIntrospect(ctxFor(root), { + interactive: false, + importSource: BUILDER, + schemaName: "app", + }); expect(catalog.calls.every((call) => call.values[0] === "app")).toBe(true); - expect(error).toBeInstanceOf(IntrospectRefusedError); - expect(error.message).toBe( - 'Refusing to replace config/database/schema.ts: the branch has a foreign key it does not declare (app.posts.author_id → app.authors.id). A foreign key lets the API include the related rows. schema.ts declares schema "sales", so it declares nothing in "app". `--schema-name sales` refreshes it.', + 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(tree(root)).toEqual(before); + expect(fs.readFileSync(path.join(root, `${SCHEMA}.bak`), "utf-8")).toBe( + salesSchema, + ); + expect((await loadDefaultDatabaseSchema(root)).$schemaName).toBe("app"); }); - test.each([ - [ - "both tables", - `import { defineSchema, id, integer, text } from ${JSON.stringify(BUILDER)}; + 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() }), })); `, - "Declare it with fk() in schema.ts, then rerun.", - ], - [ - "only the referenced table", - previousSchema, - "Declare it with fk() in schema.ts and declare the table app.posts, then rerun.", - ], - ])( - "a foreign key the replaced schema.ts does not declare, with %s declared, is refused, and nothing changes", - async (_label, undeclared, advice) => { - const root = tempApp({ - [SCHEMA]: undeclared, - [`${SCHEMA}.bak`]: "// an older backup\n", - [TYPES]: "// older types\n", - }); - await commitMigration(root); - const before = tree(root); + }); + await commitMigration(root); - const error = await refusal(root); + const report = await introspect(root); - expect(error).toBeInstanceOf(IntrospectRefusedError); - expect(error.message).toBe( - `Refusing to replace config/database/schema.ts: the branch has a foreign key it does not declare (app.posts.author_id → app.authors.id). A foreign key lets the API include the related rows. ${advice}`, - ); - expect(tree(root)).toEqual(before); - expect(fs.readFileSync(path.join(root, TYPES), "utf-8")).toBe( - "// older types\n", - ); - expect(markMigrationsApplied).not.toHaveBeenCalled(); - }, - ); + 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({ diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index 5559fac3b..23f432b01 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -116,10 +116,10 @@ describe("renderSchemaSource", () => { 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 the API will fail until it gets a default, becomes nullable, or is dropped.', + '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 the API requires a value for it on insert.", + "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")), @@ -760,7 +760,7 @@ describe("renderSchemaSource", () => { }, ]); expect(warnings).toEqual([ - "app.t.u_id: its default gen_random_uuid() is not in schema.ts, so the API requires a value for it on insert.", + "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.", ]); }); @@ -813,7 +813,7 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { foreignKeys, ); - test("a declared column keeps its privacy; a new column and every column of a new table render private", () => { + test("a declared column keeps its .private(); a new column and a new table render as the catalog has them", () => { const out = renderSchemaSource( [ boards, @@ -837,12 +837,12 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { " board_id: fk(() => boards.id).notNull(),", " author_email: text().private(),", " body: text().notNull(),", - " summary: text().private(),", + " summary: text(),", " });", "", ' const tags = table("tags", {', - " id: id().private(),", - " label: text().private(),", + " id: id(),", + " label: text(),", " });", "", " return { boards, notes, tags };", @@ -850,25 +850,20 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { "", ].join("\n"), ); - expect(out.warnings).toContain( - "app.notes.summary, app.tags.id, app.tags.label are new to schema.ts, so they are private: the API does not return or accept them until you remove .private().", - ); - expect(out.newRelations).toEqual([]); + expect(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(),"); - expect(kept.newRelations).toEqual([]); const dropped = renderSchemaSource([boards, notes([], [])], "app", { previous, }); expect(dropped.source).toContain("board_id: integer().notNull(),"); - expect(dropped.newRelations).toEqual([]); }); - test("a foreign key it does not declare is listed with the tables it does not declare either", () => { + 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", { @@ -893,17 +888,12 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { { previous: plain }, ); - expect(out.newRelations).toEqual([ - { edge: "app.notes.board_id → app.boards.id", undeclaredTables: [] }, - { - edge: "app.notes.reviewer_id → app.users.id", - undeclaredTables: ["app.users"], - }, - { - edge: "app.tags.note_id → app.notes.id", - undeclaredTables: ["app.tags"], - }, - ]); + 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(out.warnings).toEqual([]); }); test("a declared foreign key keeps its relation when an undeclared one targets the same table", () => { @@ -935,7 +925,6 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { 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', ); - expect(out.newRelations).toEqual([]); }); test("of two foreign keys on one column, the one it declares is kept", () => { @@ -969,10 +958,9 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { 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)", ]); - expect(out.newRelations).toEqual([]); }); - test("a declaration of another schema keeps nothing: every column renders private and every foreign key is new", () => { + test("a declaration of another schema keeps nothing: its .private() does not carry over", () => { const out = renderSchemaSource( [ keyed("boards", [col("title", "text", { notNull: true })]), @@ -982,21 +970,15 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { { previous }, ); - expect(out.warnings).toContain( - 'sales.boards.id, sales.boards.title, sales.notes.id, sales.notes.board_id, sales.notes.author_email, sales.notes.body are new to schema.ts, so they are private: the API does not return or accept them until you remove .private(). schema.ts declares schema "app", so it declares nothing in "sales". `--schema-name app` refreshes it.', - ); - expect(out.newRelations).toEqual([ - { - edge: "sales.notes.board_id → sales.boards.id", - undeclaredTables: ["sales.notes", "sales.boards"], - }, - ]); + expect(out.source).toContain("author_email: text(),"); + expect(out.source).toContain("board_id: fk(() => boards.id).notNull(),"); + expect(out.source).not.toContain(".private()"); + expect(out.warnings).toEqual([]); }); - test("without a schema.ts to replace, nothing is private and no foreign key is new", () => { + test("without a schema.ts to replace, nothing is private", () => { const out = firstRender([boards, notes()]); expect(out.source).not.toContain(".private()"); - expect(out.newRelations).toEqual([]); }); }); diff --git a/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts index 15c90140b..a5d06f9ac 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/roundtrip.test.ts @@ -5,7 +5,6 @@ import path from "node:path"; import { getTableConfig, type PgTable } from "drizzle-orm/pg-core"; import { afterEach, describe, expect, test } from "vitest"; -import { columnHttpCapabilities } from "../../../../plugins/database/crud/capabilities"; import { loadDefaultDatabaseSchema } from "../../../../plugins/database/load-schema"; import type { Schema } from "../../../schema-builder/types"; import { drizzleKitImports } from "../../drizzle-exports"; @@ -45,21 +44,6 @@ const load = (tables: IntrospectedTable[]) => .source, ); -/** What the generated API lets a caller do with a schema: per column, and per include. */ -const granted = (schema: Schema) => - Object.values(schema.$tables).flatMap((table) => [ - ...Object.values(table.$columns).flatMap((meta) => - Object.entries(columnHttpCapabilities(meta)) - .filter(([, allowed]) => allowed) - .map( - ([capability]) => `${table.$name}.${meta.columnName} ${capability}`, - ), - ), - ...table.$relations.map( - (relation) => `${table.$name} includes ${relation.name}`, - ), - ]); - interface KitColumn { name: string; type: string; @@ -80,6 +64,50 @@ interface KitTable { 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", () => { @@ -390,16 +418,21 @@ describe("introspect round trip", () => { ).toEqual([[quote]]); }); - test("a refresh over the schema.ts it replaces keeps exactly what the API could read, write or include", async () => { + 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 } from ${JSON.stringify(BUILDER)}; + 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() }); + 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(), + board_id: fk(() => boards.id).notNull().onDelete("cascade"), + slug: text().unique(), author_email: text().private(), - body: text().notNull(), + body: text().notNull().default("-"), }); return { boards, notes }; }); @@ -409,11 +442,21 @@ export const schema = defineSchema(({ table }) => { tableOf({ name: "boards", primaryKey: ["id"], - columns: [key, col("title", "text", { notNull: true })], + 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", @@ -421,6 +464,15 @@ export const schema = defineSchema(({ table }) => { 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", }), @@ -428,13 +480,15 @@ export const schema = defineSchema(({ table }) => { columns: [ key, col("board_id", "integer", { notNull: true }), + col("slug", "text"), col("author_email", "text"), - col("body", "text", { notNull: true }), + col("body", "text", { notNull: true, defaultExpr: "'-'::text" }), col("summary", "text"), + col("reviewer_id", "integer"), ], }), tableOf({ - name: "tags", + name: "reviewers", primaryKey: ["id"], columns: [key, col("label", "text")], }), @@ -445,11 +499,54 @@ export const schema = defineSchema(({ table }) => { previous: before.schema, }); const after = await loadSource(rendered.source); + const was = await shape(before.schema); + const is = await shape(after.schema); - expect(rendered.newRelations).toEqual([]); - // The new column and the new table arrive private, so they grant nothing. - expect(after.schema.$tables.notes?.$columns.summary?.isPrivate).toBe(true); - expect(after.schema.$tables.tags?.$columns.label?.isPrivate).toBe(true); - expect(granted(after.schema)).toEqual(granted(before.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: [], + }); }); }); From c0ce5cd7b52d62dceb4d06ac49f8d6620f4bcd6d Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 23:50:14 +0000 Subject: [PATCH 213/317] fix(appkit): render undeclared foreign keys and keep only declared .private() in introspect Both policies existed for the generated HTTP routes, which named operations replace. A foreign key the replaced schema.ts does not declare is rendered with fk(), like a declared one; the refusal, the newRelations result and the other-schema hint go. A column the old file does not declare is written as the catalog has it. A .private() the old file declares is kept, so a schema.ts that does not load still refuses the run. The NOT NULL and default warnings name app.database.
, which still inserts through schema.ts. The render tests ignore the constraint-name warning the fixture's _fkey names raise. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/introspect/index.ts | 33 +-------- .../src/database/tooling/introspect/render.ts | 74 ++++--------------- .../tooling/introspect/tests/render.test.ts | 10 ++- 3 files changed, 27 insertions(+), 90 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index e075c00da..b1ab7117a 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -28,7 +28,6 @@ import { import { resourceId } from "../targets"; import { readCatalog, readUnreadObjects } from "./catalog"; import { - otherSchemaHint, renderSchemaSource, type Skip, shown, @@ -171,11 +170,10 @@ async function readPreviousSchema(root: string): Promise { * `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. - * Columns the previous schema.ts declares keep their privacy; new ones are - * written private, and a foreign key it does not declare is refused. 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, + * 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, * database.d.ts and the migrations folder. One command at a time owns the * checkout's history. */ @@ -277,29 +275,6 @@ async function introspectHolding( `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.`, ); } - if (rendered.newRelations.length > 0) { - const one = rendered.newRelations.length === 1; - const edges = rendered.newRelations.map((relation) => relation.edge); - const tables = [ - ...new Set( - rendered.newRelations.flatMap( - (relation) => relation.undeclaredTables, - ), - ), - ]; - const declareTables = - tables.length === 0 - ? "" - : ` and declare ${tables.length === 1 ? "the table" : "the tables"} ${tables.join(", ")}`; - const advice = - previousSchema && previousSchema.$schemaName !== schemaName - ? otherSchemaHint(previousSchema.$schemaName, schemaName) - : `Declare ${one ? "it" : "them"} with fk() in schema.ts${declareTables}, then rerun.`; - throw new IntrospectRefusedError( - `Refusing to replace ${DEFAULT_SCHEMA_FILE}: the branch has ${one ? "a foreign key" : "foreign keys"} it does not declare (${edges.join(", ")}). A foreign key lets the API include the related rows. ${advice}`, - ); - } - const backupFile = `${schemaFile}.bak`; const typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); const previous = readIfExists(schemaFile); diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index 4313162fb..bfc8b60a2 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -34,31 +34,16 @@ export interface Unexpressed { readonly reason: string; } -/** A foreign key schema.ts gets that the schema.ts it replaces does not declare. */ -interface NewRelation { - /** e.g. "app.notes.author_id → app.users.id". */ - readonly edge: string; - /** Its tables the replaced schema.ts does not declare, e.g. "app.users". */ - readonly undeclaredTables: readonly 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 the API can no longer fill. */ + /** 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[]; - /** Kept foreign keys `previous` does not declare. Each one is an API include. */ - readonly newRelations: readonly NewRelation[]; -} - -/** Why a schema.ts of another schema keeps nothing in this one, and what refreshes it. */ -export function otherSchemaHint(declared: string, read: string): string { - return `schema.ts declares schema "${declared}", so it declares nothing in "${read}". \`--schema-name ${declared}\` refreshes it.`; } interface RenderOptions { @@ -66,8 +51,8 @@ interface RenderOptions { 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 privacy; every - * other column renders `.private()`. Null renders nothing private. + * 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; } @@ -168,6 +153,8 @@ function pgName(name: string): string { 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( @@ -377,9 +364,8 @@ function mirrored(target: BaseType): string { * Render pg_catalog tables as a `defineSchema` source the builder accepts. * What the builder cannot express is left out with an `// appkit: skipped …` * comment; what it declares differently (a timestamp without its precision, - * say) is listed in `approximated`. Columns `previous` does not declare render - * private, and the foreign keys it does not declare are listed in - * `newRelations`, which introspect refuses. + * say) is listed in `approximated`. A column `previous` declares keeps its + * `.private()`. */ export function renderSchemaSource( tables: readonly IntrospectedTable[], @@ -393,9 +379,6 @@ export function renderSchemaSource( /** Constraints whose database name is not the one migrations use: "db (migrations)". */ const renamed: string[] = []; const tableComments: string[] = []; - /** Columns rendered private because `previous` does not declare them. */ - const privatized: string[] = []; - const newRelations: NewRelation[] = []; const qualified = (table: string, column?: string) => `${schemaName}.${table}${column ? `.${column}` : ""}`; const skipTable = (table: string, reason: string) => { @@ -406,12 +389,8 @@ export function renderSchemaSource( }; const { previous } = options; // A declaration of another schema declares nothing in this one. - const otherSchema = - previous && previous.$schemaName !== schemaName - ? previous.$schemaName - : null; const previousTables = new Map( - previous && !otherSchema + previous && previous.$schemaName === schemaName ? Object.values(previous.$tables).map((table): [string, AppKitTable] => [ table.$name, table, @@ -434,15 +413,11 @@ export function renderSchemaSource( relation.targetColumn === foreignKey.refColumns[0], ) ?? false); - const isPrivate = (table: string, column: string): boolean => { - if (!previous) return false; - const declared = Object.values( - previousTables.get(table)?.$columns ?? {}, - ).find((meta) => meta.columnName === column); - if (declared) return declared.isPrivate; - privatized.push(qualified(table, column)); - return true; - }; + /** 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)); @@ -521,7 +496,7 @@ export function renderSchemaSource( column.identity !== "" || column.generated || !!column.defaultExpr; if (column.notNull && !generatesValue) { tableWarnings.push( - `${qualified(table.name, column.name)} is NOT NULL with no default but is not in schema.ts (${reason}). Inserts through the API will fail until it gets a default, becomes nullable, or is dropped.`, + `${qualified(table.name, column.name)} is NOT NULL with no default but is not in schema.ts (${reason}). Inserts through ${client(table.name)} will fail until it gets a default, becomes nullable, or is dropped.`, ); } }; @@ -614,7 +589,7 @@ export function renderSchemaSource( columnPlan.comments.push(`// appkit: skipped ${skip.reason}`); if (column.notNull) { tableWarnings.push( - `${qualified(table.name, column.name)}: its ${parsed.skip.replace(/ is not supported$/, "")} is not in schema.ts, so the API requires a value for it on insert.`, + `${qualified(table.name, column.name)}: its ${parsed.skip.replace(/ is not supported$/, "")} is not in schema.ts, so ${client(table.name)} requires a value for it on insert.`, ); } } @@ -806,7 +781,7 @@ export function renderSchemaSource( delete sourceColumn.defaultCall; if (sourceColumn.column.notNull) { warnings.push( - `${qualified(plan.table.name, sourceColumn.column.name)}: its default ${sourceColumn.column.defaultExpr} is not in schema.ts, so the API requires a value for it on insert.`, + `${qualified(plan.table.name, sourceColumn.column.name)}: its default ${sourceColumn.column.defaultExpr} is not in schema.ts, so ${client(plan.table.name)} requires a value for it on insert.`, ); } } @@ -842,16 +817,6 @@ export function renderSchemaSource( const out = edges.get(plan.table.name) ?? new Set(); out.add(foreignKey.table); edges.set(plan.table.name, out); - if (previous && !declaresForeignKey(plan.table.name, foreignKey)) { - newRelations.push({ - edge: shown( - `${qualified(plan.table.name, sourceColumn.column.name)} → ${qualified(foreignKey.table, targetColumn.column.name)}`, - ), - undeclaredTables: [plan.table.name, foreignKey.table] - .filter((table) => !previousTables.has(table)) - .map((table) => shown(qualified(table))), - }); - } } } @@ -945,7 +910,6 @@ export function renderSchemaSource( unexpressed, warnings: warnings.map(shown), approximated: approximated.map(shown), - newRelations, }); if (ordered.length === 0) { lines.push(...tableComments); @@ -987,12 +951,6 @@ export function renderSchemaSource( } body.push(" });", ""); } - if (privatized.length > 0) { - const one = privatized.length === 1; - warnings.push( - `${list(privatized)} ${one ? "is" : "are"} new to schema.ts, so ${one ? "it is" : "they are"} private: the API does not return or accept ${one ? "it" : "them"} until you remove .private().${otherSchema ? ` ${otherSchemaHint(otherSchema, schemaName)}` : ""}`, - ); - } for (const comment of tableComments) body.push(` ${comment}`); if (tableComments.length > 0) body.push(""); const entries = ordered.map((plan) => diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index 23f432b01..9c8d7ac8c 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -813,6 +813,10 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { 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( [ @@ -850,7 +854,7 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { "", ].join("\n"), ); - expect(out.warnings).toEqual([]); + expect(otherWarnings(out.warnings)).toEqual([]); }); test("a foreign key it declares stays, and one the catalog dropped needs nothing", () => { @@ -893,7 +897,7 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { expect(out.source).toContain("note_id: fk(() => notes.id),"); expect(out.source).toContain("author_email: text().private(),"); expect(out.skipped).toEqual([]); - expect(out.warnings).toEqual([]); + expect(otherWarnings(out.warnings)).toEqual([]); }); test("a declared foreign key keeps its relation when an undeclared one targets the same table", () => { @@ -973,7 +977,7 @@ describe("renderSchemaSource over the schema.ts it replaces", () => { expect(out.source).toContain("author_email: text(),"); expect(out.source).toContain("board_id: fk(() => boards.id).notNull(),"); expect(out.source).not.toContain(".private()"); - expect(out.warnings).toEqual([]); + expect(otherWarnings(out.warnings)).toEqual([]); }); test("without a schema.ts to replace, nothing is private", () => { From a0233faa8abc3b01dd599b5830307355e6c4f112 Mon Sep 17 00:00:00 2001 From: ditadi Date: Sun, 15 Nov 2026 23:50:18 +0000 Subject: [PATCH 214/317] docs(appkit): say what appkit db introspect keeps from the schema.ts it replaces The help text described the private-by-default columns and the foreign key refusal that introspect no longer has. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/shared/src/cli/commands/db/introspect.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/cli/commands/db/introspect.ts b/packages/shared/src/cli/commands/db/introspect.ts index 9f3dae65e..11fb2e5a3 100644 --- a/packages/shared/src/cli/commands/db/introspect.ts +++ b/packages/shared/src/cli/commands/db/introspect.ts @@ -28,9 +28,9 @@ The previous schema.ts is kept as schema.ts.bak. What the schema builder cannot express (composite keys, unsupported types or defaults, some foreign keys) is left out with an "// appkit: skipped …" comment. -Columns the previous schema.ts declares keep their .private(); columns it does -not declare are written private. A foreign key it does not declare, or a -schema.ts that does not load, stops introspect before it writes anything. +Columns the previous schema.ts marks .private() stay private. Every other column +and every foreign key is written as the database has it. A schema.ts that does +not load stops introspect before it writes anything. Without migration history this writes 0000_baseline; with history, the next NNNN_introspect, once the branch has applied every committed migration. The From bc41ff7eb2a4ce975b58b0d77d0eea8abafe68ae Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 13:13:12 +0100 Subject: [PATCH 215/317] test(appkit): pin CHECK, EXCLUDE and index omissions as introspect warnings Co-authored-by: Isaac Signed-off-by: ditadi --- .../tooling/introspect/tests/introspect.test.ts | 2 +- .../database/tooling/introspect/tests/render.test.ts | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index e9027dd9d..0a3dd3d02 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -257,13 +257,13 @@ describe("runIntrospect", () => { ]); 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", - "app.posts: index posts_status_idx is not declared", ]); expect( fs.existsSync(path.join(root, MIGRATIONS, "0000_baseline.sql")), diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index 9c8d7ac8c..c825731f5 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -522,8 +522,8 @@ describe("renderSchemaSource", () => { ]); }); - test("what schema.ts declares differently from the database is listed as approximated", () => { - const { approximated } = firstRender( + 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", @@ -570,11 +570,15 @@ describe("renderSchemaSource", () => { "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.a: CHECK or EXCLUDE constraint a_n_check is not declared", - "app.a: indexes a_n_idx, a_m_idx are not declared", "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", () => { From 2859443231bdf32fb5128e0f2f9d4de0ecfae772 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 13:14:53 +0100 Subject: [PATCH 216/317] fix(appkit): warn about CHECK, EXCLUDE and indexes introspect leaves out schema.ts cannot declare them, so neither the baseline nor a branch rebuilt from the migrations has them. They were listed as approximated information; they are lost, so introspect now warns about them. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/introspect/render.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index bfc8b60a2..391156c0a 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -363,8 +363,9 @@ function mirrored(target: BaseType): string { /** * Render pg_catalog tables as a `defineSchema` source the builder accepts. * What the builder cannot express is left out with an `// appkit: skipped …` - * comment; what it declares differently (a timestamp without its precision, - * say) is listed in `approximated`. A column `previous` declares keeps its + * 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( @@ -623,8 +624,9 @@ export function renderSchemaSource( ["index", "indexes", table.indexes], ] as const) { if (names.length > 0) { - tableApproximated.push( - `${qualified(table.name)}: ${names.length === 1 ? `${one} ${names[0]} is` : `${many} ${list(names)} are`} not declared`, + 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"}.`, ); } } From 9d5feb99d539904cb25cbae060bc74e31f689449 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 15:50:01 +0100 Subject: [PATCH 217/317] test(appkit): show that db check aborts on a snapshot with merge conflict markers Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/check.test.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/check.test.ts b/packages/appkit/src/database/tooling/tests/check.test.ts index 5a4336a82..ae9565725 100644 --- a/packages/appkit/src/database/tooling/tests/check.test.ts +++ b/packages/appkit/src/database/tooling/tests/check.test.ts @@ -389,6 +389,29 @@ describe("runCheck", () => { }, ); + test("a snapshot left with merge conflict markers fails as not drizzle-kit's, and the other problems still show", async () => { + const ctx = app(withTags); + await generate(migrations(ctx), notes); + await generate(migrations(ctx), withTags); + const file = path.join(migrations(ctx), "meta/0000_snapshot.json"); + const snapshot = fs.readFileSync(file, "utf-8"); + fs.writeFileSync( + file, + `<<<<<<< HEAD\n${snapshot}\n=======\n${snapshot}\n>>>>>>> feature\n`, + ); + fs.writeFileSync( + path.join(migrations(ctx), "0001_parallel.sql"), + "CREATE TABLE x ();", + ); + + expect((await runCheck(ctx)).problems).toEqual([ + `${path.join("config/database/migrations/meta/0000_snapshot.json")}, the snapshot of 0000_migration, is not a drizzle-kit snapshot. Restore it from version control.`, + expect.stringContaining( + `${path.join("config/database/migrations/0001_parallel.sql")} is not in meta/_journal.json, so no deploy runs it.`, + ), + ]); + }); + test("without schema.ts it points to introspect", async () => { const ctx = app({}); fs.rmSync(path.join(ctx.root, "config/database/schema.ts")); From 78f2b1e0d343feb0e1fb2f07aca212d3c2887160 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 15:50:58 +0100 Subject: [PATCH 218/317] docs(template): describe database storage and migrations, not CRUD routes The scaffolded README promised generated CRUD routes and the `api` option. It now describes the schema and its committed migrations, and says HTTP access to the tables is configured separately, which holds with or without named operations. Co-authored-by: Isaac Signed-off-by: ditadi --- template/README.md.tmpl | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/template/README.md.tmpl b/template/README.md.tmpl index a43dd0728..83cd253ad 100644 --- a/template/README.md.tmpl +++ b/template/README.md.tmpl @@ -10,7 +10,7 @@ A Databricks App powered by [AppKit](https://developers.databricks.com/docs/appk - **Lakebase** -- Fully managed Postgres database for transactional (OLTP) workloads on Databricks {{- end}} {{- if .plugins.database}} -- **Database** -- Schema-driven PostgreSQL access with generated CRUD routes +- **Database** -- Schema-driven PostgreSQL tables with committed migrations {{- end}} {{- if .plugins.genie}} - **Genie** -- AI/BI Genie conversational interface for natural language data queries @@ -52,8 +52,10 @@ The Lakebase plugin requires additional environment variables for PostgreSQL con #### Database `database()` loads `config/database/schema.ts`, whose tables live in the Postgres -schema `app`. CRUD routes are enabled for declared tables by default, and can be -restricted with `api` in the plugin configuration. +schema `app`. Committed migrations in `config/database/migrations/` create and +change those tables, as the steps below show. HTTP access to the tables is +configured separately. See the +[Database plugin documentation](https://developers.databricks.com/docs/appkit/v0/plugins/database). Local development runs against a Lakebase branch of your own, never the deployed one. Run `npx appkit db init` once after scaffolding, and again after cloning. It asks From 786acb3e3f0ec3594b2e7cb4f2de67c72a5ce2d7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 15:51:35 +0100 Subject: [PATCH 219/317] fix(appkit): report a snapshot that is not JSON in db check instead of aborting A snapshot left with merge conflict markers threw out of runCheck, so none of the other problems printed. It is now the "not a drizzle-kit snapshot" finding for that file. Read errors still throw. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/check.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts index fc2646468..df7e72af3 100644 --- a/packages/appkit/src/database/tooling/check.ts +++ b/packages/appkit/src/database/tooling/check.ts @@ -9,6 +9,7 @@ import { } from "../../plugins/database/load-schema"; import { type JournalEntry, + MigrationFilesError, migrationFile, migrationsFolder, readJournal, @@ -77,6 +78,21 @@ const snapshotShape = z.object({ 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: "" }; @@ -136,7 +152,7 @@ export async function runCheck(ctx: DbContext): Promise { ); return null; } - const snapshot = snapshotShape.safeParse(readJsonFile(file)); + const snapshot = snapshotShape.safeParse(readSnapshotJson(file)); if (snapshot.success) { return { id: snapshot.data.id, prevId: snapshot.data.prevId }; } From e955850273ed86929a49ba0490125ae7c4a55fe9 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:17:16 +0100 Subject: [PATCH 220/317] test(appkit): an explicit schemaName gets no default-schema advice from the startup check Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tests/schema-check.test.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index 4364bae4e..2fa8a2684 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -78,6 +78,27 @@ describe("assertSchemaMatchesDatabase — tables left in public", () => { expect(error.message).not.toContain("commit migrations"); }); + test('schemaName "app" named explicitly: the usual advice, whatever public holds', async () => { + const explicit = defineSchema( + ({ table }) => ({ + boards: table("boards", { id: id() }), + notes: table("notes", { id: id() }), + }), + { schemaName: "app" }, + ); + const { path } = catalog({}, {}, ["boards", "notes"]); + + const error = await assertSchemaMatchesDatabase(path, explicit, OFF).catch( + (caught) => caught, + ); + + expect(error.message).toContain("table app.boards does not exist"); + expect(error.message).toContain( + "commit migrations under config/database/migrations", + ); + expect(error.message).not.toContain("unless told otherwise"); + }); + test("only some missing tables are in public: the usual advice", async () => { const { path } = catalog({}, {}, ["boards"]); From 730ea72d39e168813e984e77e7f3fdb7553612fa Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:17:47 +0100 Subject: [PATCH 221/317] fix(appkit): give the default-schema advice only when schemaName is implicit The startup check told an app that named its schema explicitly that defineSchema() picks that schema unless told otherwise, which it had been. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/plugins/database/schema-check.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index bbfdea8ae..e78896d1b 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -5,6 +5,7 @@ import { } from "../../database/migrations/tables-left-in-public"; import type { DataPath } from "../../database/runtime"; import type { Schema } from "../../database/schema-builder"; +import { schemaNameIsExplicit } from "../../database/schema-builder/define-schema"; import type { MigrateOnStartDecision } from "./migrate-on-start"; interface CatalogColumn { @@ -94,7 +95,7 @@ export async function assertSchemaMatchesDatabase( if (problems.length > 0) { const absent = tableNames.filter((name) => !found.has(name)); const advice = - (await inPublicInstead(dataPath, schemaName, absent)) ?? + (await inPublicInstead(dataPath, schema, absent)) ?? migrationAdvice(migration); throw databaseSetupFailed( `the declared schema does not match the database: ${problems.join("; ")}. ${advice}`, @@ -104,15 +105,17 @@ export async function assertSchemaMatchesDatabase( /** * Apps from before the default schema moved to `app` keep their tables in - * `public`. Name that case when every absent table is there; the migration - * guard in database/migrations/tables-left-in-public.ts refuses it up front. + * `public`. Name that case when the schema name is the default and every + * absent table is there; the migration guard in + * database/migrations/tables-left-in-public.ts refuses it up front. */ async function inPublicInstead( dataPath: DataPath, - schemaName: string, + schema: Schema, absent: readonly string[], ): Promise { - if (schemaName === "public" || absent.length === 0) return undefined; + if (schemaNameIsExplicit(schema) || absent.length === 0) return undefined; + const schemaName = schema.$schemaName; const { inPublic } = await locateTables(dataPath.raw, schemaName, absent); if (inPublic.length < absent.length) return undefined; return `Schema public has ${absent.length === 1 ? "that table" : "those tables"}, but ${keepInPublicAdvice(schemaName)}`; From 37ce6395a32f8f3d95444d1f7c7386e8c33308a0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:20:00 +0100 Subject: [PATCH 222/317] chore: move the knip entry points out of the migrations layer The tools and bin/appkit.js entry points belong with the appkit db CLI, which a later layer adds. This layer adds neither. Co-authored-by: Isaac Signed-off-by: ditadi --- knip.json | 8 -------- 1 file changed, 8 deletions(-) diff --git a/knip.json b/knip.json index 566a07df1..8e2d0f8a1 100644 --- a/knip.json +++ b/knip.json @@ -7,15 +7,7 @@ "docs" ], "workspaces": { - ".": { - "entry": [ - "tools/bundle-size.ts", - "tools/generate-json-schema.ts", - "tools/playground/deploy-playground.ts" - ] - }, "packages/appkit": { - "entry": ["bin/appkit.js"], "ignoreDependencies": [ "vitest", "@databricks/sdk-apps", From c883fc0f02adf59289335ff3233b2f10db3d4dcc Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:20:15 +0100 Subject: [PATCH 223/317] fix(template): open env: in app.yaml whenever the database flag renders The APPKIT_DB_MIGRATE_ON_START item relied on .appEnv being non-empty to open env:. With the database plugin and an empty .appEnv, the item landed under health_check. env: now opens on `or .appEnv .plugins.database`, and the smoke scaffold strips that `if or` block like the other conditionals, so its app.yaml still parses. Co-authored-by: Isaac Signed-off-by: ditadi --- template/app.yaml.tmpl | 5 +++-- tools/smoke-test-template.ts | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/template/app.yaml.tmpl b/template/app.yaml.tmpl index 3f0dd55ad..0e277a9ee 100644 --- a/template/app.yaml.tmpl +++ b/template/app.yaml.tmpl @@ -4,12 +4,13 @@ command: ['{{or .packageManager "pnpm"}}', 'run', 'start'] # included, so a failed start fails the deploy instead of passing after 2 s. health_check: path: /health -{{- if .appEnv}} +{{- if or .appEnv .plugins.database}} env: +{{- end}} +{{- if .appEnv}} {{.appEnv}} {{- end}} {{- if .plugins.database}} -{{- /* The plugin's postgres resource always renders LAKEBASE_ENDPOINT into .appEnv, so env: is open. */}} - name: APPKIT_DB_MIGRATE_ON_START value: "true" {{- end}} diff --git a/tools/smoke-test-template.ts b/tools/smoke-test-template.ts index 889ec6c2a..4a5aa1407 100644 --- a/tools/smoke-test-template.ts +++ b/tools/smoke-test-template.ts @@ -126,6 +126,18 @@ function processAllFiles(dir: string): void { } } + // Remove Go template conditionals: {{- if or .appEnv .plugins.*}} blocks + if (content.includes("{{") && content.includes("if or")) { + const beforeLen = content.length; + content = content.replace( + /{{-?\s*if\s+or(?:\s+\.(?:appEnv|plugins\.[a-zA-Z0-9_-]+))+\s*-?\s*}}[\s\S]*?{{-?\s*end\s*-?\s*}}/g, + "", + ); + if (beforeLen !== content.length) { + modified = true; + } + } + // Remove Go template conditionals: {{- if .appEnv}} blocks if (content.includes("{{") && content.includes(".appEnv")) { const beforeLen = content.length; From 837523ea7f294b60bb312b81f02ba25d233d552d Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:20:20 +0100 Subject: [PATCH 224/317] test(appkit): a current deploy branch skips the lookup of tables left in public Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/migrations/tests/apply.test.ts | 57 +++++++ .../database/tests/migrate-on-start.test.ts | 152 ++++++++++++++---- 2 files changed, 177 insertions(+), 32 deletions(-) diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index af02e0091..eec44f6f2 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -323,6 +323,63 @@ describe("applyPendingMigrations", () => { 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 }); diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index b2fe6ee70..6154ab35b 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -332,29 +333,121 @@ describe("migrateOnStart", () => { }); describe("migrateOnStart: tables an earlier release left in public", () => { + const NOTES_SQL = 'CREATE TABLE "app"."notes" ("id" integer);'; + const NOTES_WHEN = 1000; // An upgraded app: public.notes holds its rows, app.notes does not exist. - const notesInPublic = { - rows: [{ schema_name: "public", table_name: "notes" }], - }; + const notesInPublic = [{ schema_name: "public", table_name: "notes" }]; - test("the default schema and every declared table in public: refused, nothing applied", async () => { - pool.query.mockResolvedValue(notesInPublic); - applyPendingMigrations.mockResolvedValueOnce(nothingDone); + /** An app root whose one committed migration, 0000_notes, creates app.notes. */ + function appRootWithNotesMigration(): { root: string; hash: string } { + const root = appRoot(); + const folder = path.join(root, "config/database/migrations"); + fs.mkdirSync(path.join(folder, "meta"), { recursive: true }); + fs.writeFileSync( + path.join(folder, "meta/_journal.json"), + JSON.stringify({ + version: "7", + dialect: "postgresql", + entries: [ + { + idx: 0, + version: "7", + when: NOTES_WHEN, + tag: "0000_notes", + breakpoints: true, + }, + ], + }), + ); + fs.writeFileSync(path.join(folder, "0000_notes.sql"), NOTES_SQL); + return { + root, + hash: createHash("sha256").update(NOTES_SQL).digest("hex"), + }; + } - const error = await migrateOnStart( - pool, - schema, - appRootWithMigrations(), - deployEnv, - ).catch((caught: unknown) => caught); + /** + * The deploy branch's one connection. Its journal records `recorded`, and + * the catalog lookup of the declared tables in app and public finds `catalog`. + */ + function deployBranch( + recorded: readonly string[], + catalog: readonly { schema_name: string; table_name: string }[], + ) { + const statements: string[] = []; + const client = { + release: vi.fn(), + query: vi.fn(async (input: string) => { + const text = input.trim(); + statements.push(text); + if (text.includes("c.relowner")) { + 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.startsWith("select hash, created_at")) { + return { + rows: recorded.map((hash) => ({ hash, created_at: NOTES_WHEN })), + }; + } + if (text.includes("pg_try_advisory_lock(")) { + return { rows: [{ locked: true }] }; + } + if (text.includes("'public'")) return { rows: catalog }; + return { rows: [] }; + }), + }; + pool.connect.mockResolvedValue(client); + return { + statements, + lookedInPublic: () => + statements.some((text) => text.includes("'public'")), + }; + } + + beforeEach(() => { + vi.spyOn(console, "log").mockImplementation(() => undefined); + }); + + test("a current branch costs one connection and one read of the journal: public is not looked at", async () => { + const { root, hash } = appRootWithNotesMigration(); + const branch = deployBranch([hash], notesInPublic); + + await migrateOnStart(pool, schema, root, deployEnv); + + expect(pool.connect).toHaveBeenCalledTimes(1); + expect(pool.query).not.toHaveBeenCalled(); + expect(branch.lookedInPublic()).toBe(false); + expect(branch.statements).toEqual([ + expect.stringContaining("c.relowner"), + expect.stringMatching(/^select hash, created_at/), + ]); + }); + + test("a pending migration, the default schema and every declared table in public: refused, nothing applied", async () => { + const { root } = appRootWithNotesMigration(); + const branch = deployBranch([], notesInPublic); + + const error = await migrateOnStart(pool, schema, root, deployEnv).catch( + (caught: unknown) => caught, + ); - expect(applyPendingMigrations).not.toHaveBeenCalled(); expect(error).toBeInstanceOf(DatabasePluginError); expect(error).toMatchObject({ category: "SETUP_FAILED", phase: "setup" }); - expect((error as Error).message).toContain("public has notes"); + expect((error as Error).message).toContain( + 'not applying migrations: none of the declared tables exist in schema "app", but public has notes.', + ); expect((error as Error).message).toContain( 'pass { schemaName: "public" } as the second argument of defineSchema()', ); + expect(branch.statements).not.toContain(NOTES_SQL); + expect(branch.statements).not.toContain("begin"); }); test('schemaName "app" named explicitly is migrated, whatever public holds', async () => { @@ -362,36 +455,31 @@ describe("migrateOnStart: tables an earlier release left in public", () => { ({ table }) => ({ notes: table("notes", { id: id() }) }), { schemaName: "app" }, ); - pool.query.mockResolvedValue(notesInPublic); - applyPendingMigrations.mockResolvedValueOnce(nothingDone); - vi.spyOn(console, "log").mockImplementation(() => undefined); + const { root } = appRootWithNotesMigration(); + const branch = deployBranch([], notesInPublic); - await migrateOnStart(pool, explicit, appRootWithMigrations(), deployEnv); + await migrateOnStart(pool, explicit, root, deployEnv); - expect(applyPendingMigrations).toHaveBeenCalledTimes(1); + expect(branch.statements).toContain(NOTES_SQL); + expect(branch.lookedInPublic()).toBe(false); }); test("a declared table already in app: migrated, whatever public holds", async () => { - pool.query.mockResolvedValue({ - rows: [ - { schema_name: "app", table_name: "notes" }, - { schema_name: "public", table_name: "notes" }, - ], - }); - applyPendingMigrations.mockResolvedValueOnce(nothingDone); - vi.spyOn(console, "log").mockImplementation(() => undefined); + const { root } = appRootWithNotesMigration(); + const branch = deployBranch( + [], + [{ schema_name: "app", table_name: "notes" }, ...notesInPublic], + ); - await migrateOnStart(pool, schema, appRootWithMigrations(), deployEnv); + await migrateOnStart(pool, schema, root, deployEnv); - expect(applyPendingMigrations).toHaveBeenCalledTimes(1); + expect(branch.statements).toContain(NOTES_SQL); }); test("no committed journal: nothing to apply, so the catalog is not consulted", async () => { - vi.spyOn(console, "log").mockImplementation(() => undefined); - pool.query.mockResolvedValue(notesInPublic); - await migrateOnStart(pool, schema, appRoot(), deployEnv); + expect(pool.connect).not.toHaveBeenCalled(); expect(pool.query).not.toHaveBeenCalled(); }); }); From 72ab500ed97091902baef567f8f7f27c39229a80 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:20:57 +0100 Subject: [PATCH 225/317] test(appkit): pin the escaping of U+061C and of names in introspect's breaking-statement warning Co-authored-by: Isaac Signed-off-by: ditadi --- .../tooling/introspect/tests/introspect.test.ts | 14 ++++++++++++++ .../tooling/introspect/tests/render.test.ts | 6 +++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 0a3dd3d02..53963bea0 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -809,6 +809,20 @@ export const schema = defineSchema(({ table }) => ({ ]); }); + 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", diff --git a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts index c825731f5..a1003b3ad 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/render.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/render.test.ts @@ -658,10 +658,10 @@ describe("renderSchemaSource", () => { }); test("bidi and line-separator characters are escaped in string literals", () => { - const name = "t\u202e\u2066\u2028x"; + const name = "t\u202e\u2066\u061c\u2028x"; const { source } = firstRender([keyed(name)], "app"); - expect(source).not.toMatch(/[\u2028\u202e\u2066]/); - expect(source).toContain('table("t\\u202e\\u2066\\u2028x", {'); + 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", () => { From bc16fa893ef85434080fc0ead42cefa36fd30887 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:21:00 +0100 Subject: [PATCH 226/317] refactor(appkit): read the dev and session branch shapes from one runtime module The deploy-start refusal kept its own copy of the shapes `appkit db init` names branches with, so a change to the naming rules would switch the refusal off without an error. database/branch-names.ts now holds them outside tooling/, which runtime code may not import, for init's naming to share. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/branch-names.ts | 38 ++++++++++++++++++ .../src/database/tests/branch-names.test.ts | 40 +++++++++++++++++++ .../src/plugins/database/migrate-on-start.ts | 24 +++++------ 3 files changed, 88 insertions(+), 14 deletions(-) create mode 100644 packages/appkit/src/database/branch-names.ts create mode 100644 packages/appkit/src/database/tests/branch-names.test.ts diff --git a/packages/appkit/src/database/branch-names.ts b/packages/appkit/src/database/branch-names.ts new file mode 100644 index 000000000..d604e0db1 --- /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. */ +const MAX_BRANCH_ID = 63; +const DEV_PREFIX = "dev-"; +const SESSION_PREFIX = "session-"; +/** Hex characters of the user's name hash in both shapes. */ +const HASH_LENGTH = 6; +/** The longest session id that keeps session-- within MAX_BRANCH_ID. */ +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/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/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index 5e864f9c4..3e0baf537 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -2,6 +2,10 @@ import fs from "node:fs"; import type { Pool } from "pg"; +import { + type DevelopmentBranchKind, + developmentBranchKind, +} from "../../database/branch-names"; import { databaseSetupFailed } from "../../database/errors"; import { applyPendingMigrations, @@ -63,20 +67,11 @@ function endpointBranch(endpoint: string | undefined): string | undefined { return endpoint?.match(/\/branches\/([^/]+)\//)?.[1]; } -const BRANCH_ID_MAX_LENGTH = 63; - -const DEVELOPMENT_BRANCH_SHAPES = { - "a developer": /^dev-[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{6}$/, - "an agent session": /^session-[0-9a-f]{6}-[a-z0-9]{1,48}$/, +const DEVELOPMENT_BRANCH_OWNERS: Record = { + dev: "a developer", + session: "an agent session", }; -function developmentBranchOwner(branch: string): string | undefined { - if (branch.length > BRANCH_ID_MAX_LENGTH) return undefined; - return Object.entries(DEVELOPMENT_BRANCH_SHAPES).find(([, shape]) => - shape.test(branch), - )?.[0]; -} - /** * Apply pending committed migrations from /config/database/migrations as * the app's identity (see database/migrations/ownership.ts). No journal → @@ -90,8 +85,9 @@ export async function migrateOnStart( ): Promise { const folder = migrationsFolder(root); const branch = endpointBranch(env.LAKEBASE_ENDPOINT); - const owner = branch && developmentBranchOwner(branch); - if (owner) { + const kind = branch && developmentBranchKind(branch); + if (kind) { + const owner = DEVELOPMENT_BRANCH_OWNERS[kind]; throw databaseSetupFailed( `LAKEBASE_ENDPOINT points at branch "${branch}", whose name has the shape of ${owner} branch, and a deployed app migrates only its deploy branch. ` + "Bind the app to its deploy branch. If this is the deploy branch, rename it so it does not look like a dev or session branch.", From 08fcdfe24cdf66735571ef1daa3fc9234dd87f6c Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:21:07 +0100 Subject: [PATCH 227/317] docs(template): make the health-check promise conditional on Apps enforcing it Whether Databricks Apps enforces deployment health checks in production is an open question, so the README and the app.yaml comment now say a failed migration fails the deploy only when Apps enforces the health check, and what happens otherwise. The deployed-verify step says what it checks: the app's deployed source has every committed migration. Co-authored-by: Isaac Signed-off-by: ditadi --- template/README.md.tmpl | 10 ++++++---- template/app.yaml.tmpl | 7 ++++--- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/template/README.md.tmpl b/template/README.md.tmpl index 83cd253ad..ebf7c74c1 100644 --- a/template/README.md.tmpl +++ b/template/README.md.tmpl @@ -89,9 +89,11 @@ Commit the migrations. The deployed app applies them on start, because `app.yaml sets `APPKIT_DB_MIGRATE_ON_START=true`, and only when `PGUSER` is set and equals `DATABRICKS_CLIENT_ID`, which Databricks Apps sets for the deployed app. `db init` writes your user name to `PGUSER` in `.env`, so a local start, `databricks apps -run-local` included, connects as you and never migrates. The deploy waits for -`/health`, which the app serves only after its migrations, for up to 300 seconds, -so a failed migration fails the deploy. +run-local` included, connects as you and never migrates. The app serves `/health` +only after its migrations. When Databricks Apps enforces the `health_check` in +`app.yaml`, the deploy waits for `/health` for up to 300 seconds, so a failed +migration fails the deploy. Otherwise, the deploy succeeds once the app process +has lived 2 seconds, even while it is still migrating. To adopt tables that already exist, run `npx appkit db init --schema introspect`. It writes `schema.ts` from the branch's tables, and a `0000_baseline` migration (or `NNNN_introspect` when migrations @@ -228,7 +230,7 @@ databricks apps deploy -t prod ``` {{- if .plugins.database}} -Then check that the deployed app runs with every committed migration: +Then check that the app's deployed source has every committed migration: ```bash npx appkit db verify --deployed -t prod diff --git a/template/app.yaml.tmpl b/template/app.yaml.tmpl index 0e277a9ee..b14a63d8c 100644 --- a/template/app.yaml.tmpl +++ b/template/app.yaml.tmpl @@ -1,7 +1,8 @@ command: ['{{or .packageManager "pnpm"}}', 'run', 'start'] -# Databricks Apps counts the deploy as succeeded only once /health answers 2xx, -# within 300 s. AppKit serves /health after every plugin's setup, migrations -# included, so a failed start fails the deploy instead of passing after 2 s. +# Keep this health check. When Databricks Apps enforces it, a deploy succeeds only +# once /health answers 2xx, within 300 s. AppKit serves /health after every +# plugin's setup, migrations included, so a failed start fails the deploy. +# Otherwise, a deploy succeeds once the process has lived 2 s. health_check: path: /health {{- if or .appEnv .plugins.database}} From 74c6e4390ee1d4406490c340c689e9e5eb3ea605 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:21:08 +0100 Subject: [PATCH 228/317] fix(shared): give stranded migrations the history-rewrite recovery in verify A stranded migration is often main's own, so deleting it is never the fix. The local verify hint now gives the recovery the design names: save the hand-written SQL, merge main, reset the migrations to main's, clean and migrate, then add the SQL back. It is an exported constant the CLI can reuse. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/shared/src/cli/commands/db/output.ts | 14 ++++++++------ .../shared/src/cli/commands/db/verify.test.ts | 15 +++++++++++---- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 6dd51ad57..cde6053ce 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -119,6 +119,13 @@ export function printCleanReport(report: CleanReport): void { const REBUILD = "`appkit db clean` and then `appkit db migrate` rebuild the branch from this checkout's migrations, in order"; +/** + * The recovery for a migration history main cannot run in order: the + * stranded migration is often main's own, so deleting it is never the fix. + */ +export const REWRITE = + "Save any SQL you wrote by hand in your migration, such as a backfill. Merge main, reset config/database/migrations to main's (for example `git restore --source main --staged --worktree config/database/migrations`), then run `appkit db clean` and `appkit db migrate`, which 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."; + /** The one next step for a failed local verify, most fundamental gap first. */ function localVerifyHint(report: LocalVerifyReport): string { // Tables left in public: migrating would create empty copies in the app schema. @@ -129,12 +136,7 @@ function localVerifyHint(report: LocalVerifyReport): string { if (report.unknownMigrations > 0) { return `${REBUILD}. If the branch ran migrations you have not pulled yet, pull them instead.`; } - // The same guidance the deployed app's MigrationHistoryError gives: the - // history itself is wrong, so rebuilding the local branch would not fix it. - if (report.strandedMigrations.length > 0) { - const its = report.strandedMigrations.length === 1 ? "its" : "their"; - return `Delete ${its} .sql file, snapshot and journal entry, then run \`appkit db migrate\` to generate the migration again from schema.ts, after the recorded ones.`; - } + if (report.strandedMigrations.length > 0) return REWRITE; // Pending migrations explain the gap; without them, schema.ts changed or the branch was edited. return report.pendingMigrations.length > 0 ? "Run `appkit db migrate` to apply the pending migrations." diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index f49fdcdd8..494bddee6 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -21,6 +21,7 @@ vi.mock("@databricks/appkit/beta/database-tooling", () => ({ })); import { dbCommand } from "./index"; +import { REWRITE } from "./output"; let log: MockInstance; let error: MockInstance; @@ -154,7 +155,7 @@ describe("appkit db verify", () => { expect(process.exitCode).toBe(1); }); - test("a migration merged out of order is named, with how to regenerate it after the recorded ones", async () => { + test("a migration merged out of order is named, with the recovery that rewrites the branch's history on main's, never deleting a migration", async () => { runVerify.mockResolvedValue({ ...local, strandedMigrations: ["0001_parallel"], @@ -166,10 +167,16 @@ describe("appkit db verify", () => { expect(output(log)).toContain( "Never runs: 0001_parallel: it is older than a migration the branch already ran (merged out of order), and the deployed app refuses to start on that history", ); - expect(output(error)).toContain( - "Delete its .sql file, snapshot and journal entry, then run `appkit db migrate` to generate the migration again from schema.ts, after the recorded ones.", + const printed = output(error); + expect(printed).toContain( + `dev-alice-3f9a2c does not match config/database/schema.ts and the committed migrations. ${REWRITE}`, ); - expect(output(error)).not.toContain("`appkit db clean`"); + expect(REWRITE).toContain("Save any SQL you wrote by hand"); + expect(REWRITE).toContain("Merge main"); + expect(REWRITE).toContain("config/database/migrations"); + expect(REWRITE).toContain("`appkit db clean` and `appkit db migrate`"); + expect(REWRITE).toContain("Add the saved SQL back"); + expect(printed).not.toMatch(/delete/i); expect(process.exitCode).toBe(1); }); From 0e4d5463b1abc4163c4672f0e1e78d18390a61fa Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:21:26 +0100 Subject: [PATCH 229/317] fix(appkit): escape U+061C and catalog names in introspect's breaking-statement warning Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/introspect/index.ts | 2 +- packages/appkit/src/database/tooling/introspect/render.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index b1ab7117a..2359f0881 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -346,7 +346,7 @@ async function introspectHolding( 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.join(" ")}`, + `${migration.tag} breaks instances still running the previous release, which keep serving while the new one migrates on start: ${breaking.map(shown).join(" ")}`, ); } return { diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index 391156c0a..6d081e922 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -122,7 +122,7 @@ const INT32 = { min: -2147483648, max: 2147483647 }; * shows. JSON.stringify keeps both. */ const UNSAFE_IN_SOURCE = - /[\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]/g; + /[\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) => From 248c82ec5f759cdfde16d2abea87a6327323667e Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:21:51 +0100 Subject: [PATCH 230/317] fix(appkit): refuse to migrate on start when LAKEBASE_ENDPOINT names no branch The refusal of dev and session branches read the branch from LAKEBASE_ENDPOINT and skipped itself when the variable was unset or not an endpoint path, so a deployed app on an unknown branch migrated. Setup now fails and names the variable. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/plugins/database/migrate-on-start.ts | 11 +++++++- .../database/tests/migrate-on-start.test.ts | 27 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index 3e0baf537..4d59f18ae 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -85,7 +85,16 @@ export async function migrateOnStart( ): Promise { const folder = migrationsFolder(root); const branch = endpointBranch(env.LAKEBASE_ENDPOINT); - const kind = branch && developmentBranchKind(branch); + if (!branch) { + const value = env.LAKEBASE_ENDPOINT + ? `LAKEBASE_ENDPOINT is ${JSON.stringify(env.LAKEBASE_ENDPOINT)}` + : "LAKEBASE_ENDPOINT is not set"; + throw databaseSetupFailed( + `${value}, so migrate on start cannot tell which branch it would migrate. ` + + "Set it to the app's endpoint, projects//branches//endpoints/, as its database resource does.", + ); + } + const kind = developmentBranchKind(branch); if (kind) { const owner = DEVELOPMENT_BRANCH_OWNERS[kind]; throw databaseSetupFailed( diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index 1b56e84a2..a64250571 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -229,6 +229,33 @@ describe("migrateOnStart", () => { expect(applyPendingMigrations).toHaveBeenCalled(); }); + test.each([ + ["unset", undefined, "LAKEBASE_ENDPOINT is not set"], + [ + "not an endpoint path", + "ep-abc.database.cloud.databricks.com", + 'LAKEBASE_ENDPOINT is "ep-abc.database.cloud.databricks.com"', + ], + ])( + "a LAKEBASE_ENDPOINT that names no branch (%s) is refused: the branch cannot be checked", + async (_label, endpoint, named) => { + const error = await migrateOnStart( + pool, + schema, + appRootWithMigrations(), + { ...deployEnv, LAKEBASE_ENDPOINT: endpoint }, + ).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(DatabasePluginError); + expect(error).toMatchObject({ category: "SETUP_FAILED", phase: "setup" }); + expect((error as Error).message).toContain( + `${named}, so migrate on start cannot tell which branch it would migrate. ` + + "Set it to the app's endpoint, projects//branches//endpoints/, as its database resource does.", + ); + expect(applyPendingMigrations).not.toHaveBeenCalled(); + }, + ); + test("a pooled endpoint is refused: the migration lock would not hold", async () => { const error = await migrateOnStart(pool, schema, appRootWithMigrations(), { ...deployEnv, From 9defc8d8868116eab4e8acea2ce8e4972f0fee09 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:22:12 +0100 Subject: [PATCH 231/317] fix(appkit): leave the migration history unchanged when migrate refuses for tables in public The refusal ran after generating, so the migration that would create the empty copies stayed in the folder and the next run diffed schema.ts against it. Nothing ran, so the history now goes back to how the run found it. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrate.ts | 16 ++++++++- .../database/tooling/tests/migrate.test.ts | 35 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index a97d85c49..1bddc0e6a 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -106,6 +106,14 @@ class UnappliedMigrationError extends Error implements MigrationWarnings { } } +/** Applying was refused before anything ran: a migration would shadow tables left in public. */ +class TablesLeftInPublicError extends Error { + constructor(reason: string) { + super(`Did not apply: ${reason}`); + this.name = "TablesLeftInPublicError"; + } +} + /** Why migrations must not be applied to the `.env` branch; undefined when they may. */ async function applyBlocker(ctx: DbContext): Promise { const env = await resolveEnvBranch(ctx); @@ -130,7 +138,7 @@ async function applyToEnvBranch( catalogSqlOf(pool), schema, ); - if (leftInPublic) throw new Error(`Did not apply: ${leftInPublic}`); + if (leftInPublic) throw new TablesLeftInPublicError(leftInPublic); const { applied, adopted } = await applyPendingMigrations(pool, { migrationsFolder: folder, schemaName: schema.$schemaName, @@ -177,6 +185,12 @@ async function migrateHolding( outcome = await applyToEnvBranch(ctx, lock.folder, schema); } catch (error) { if (!generated) throw error; + // Nothing ran. A kept migration would create the empty copies the refusal + // warns about, and the next run would diff schema.ts against it. + if (error instanceof TablesLeftInPublicError) { + discardMigrationFiles(lock, generated); + throw error; + } const file = path.relative(ctx.root, generated.file); // A failed migration left in the journal runs first on every later try, so a // fix in schema.ts would stack behind it and never apply. diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 19ee1517e..682adbf71 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -55,6 +55,19 @@ function writeSchema(root: string, tables: string): void { ); } +/** Every file under the migrations folder, by relative path, with its contents. */ +function historyFiles(folder: string): Record { + return Object.fromEntries( + fs + .readdirSync(folder, { recursive: true, encoding: "utf-8" }) + .filter((entry) => fs.statSync(path.join(folder, entry)).isFile()) + .map((entry) => [ + entry, + fs.readFileSync(path.join(folder, entry), "utf-8"), + ]), + ); +} + function app(tables: string): DbContext { const root = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-db-migrate-")); roots.push(root); @@ -142,6 +155,28 @@ describe("runMigrate", () => { expect.objectContaining({ $schemaName: "app" }), ); expect(applyPendingMigrations).not.toHaveBeenCalled(); + expect( + fs.existsSync(path.join(ctx.root, "config/database/migrations")), + ).toBe(false); + }); + + test("refusing for tables left in public leaves the migration history as it was", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + resolveEnvBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + const folder = path.join(ctx.root, "config/database/migrations"); + const before = historyFiles(folder); + + writeSchema(ctx.root, `notes: table("notes", { id: id(), body: text() })`); + resolveEnvBranch.mockResolvedValue(devBranch); + detectTablesLeftInPublic.mockResolvedValue( + 'none of the declared tables exist in schema "app", but public has notes.', + ); + + await expect(runMigrate(ctx, { interactive: false })).rejects.toThrow( + /^Did not apply: none of the declared tables exist in schema "app", but public has notes\.$/, + ); + expect(historyFiles(folder)).toEqual(before); }); test("generates, regenerates types, and applies to the .env branch with the app schema", async () => { From b6dfe542a5a07537d7286ee6cd256468f95fee83 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:22:50 +0100 Subject: [PATCH 232/317] fix(appkit): warn that ADD PRIMARY KEY may fail on the deploy branch's rows drizzle-kit 0.31.10 writes `ALTER TABLE ... ADD PRIMARY KEY ("col");` when a column becomes the primary key, and duplicate or null values in it fail the migration like any new constraint. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/migrations.ts | 1 + packages/appkit/src/database/tooling/tests/migrations.test.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 233525857..86e0133ac 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -293,6 +293,7 @@ const MAY_FAIL_ON_EXISTING_ROWS: readonly StatementPredicate[] = [ matches(/\bSET DATA TYPE\b/i), addsRequiredColumn, matches(/\bADD CONSTRAINT\b/i), + matches(/\bADD PRIMARY KEY\b/i), addsConstrainedColumn, matches(/^CREATE UNIQUE INDEX\b/i), ]; diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index 89d8b0f2a..e934644c7 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -401,6 +401,7 @@ describe("dataDependentStatements", () => { 'ALTER TABLE "app"."notes" ALTER COLUMN "n" SET DATA TYPE integer;', 'ALTER TABLE "app"."authors" ADD CONSTRAINT "authors_email_unique" UNIQUE("email");', 'ALTER TABLE "app"."notes" ADD CONSTRAINT "notes_id_pk" PRIMARY KEY("id");', + 'ALTER TABLE "app"."notes" ADD PRIMARY KEY ("id");', 'ALTER TABLE "app"."notes" ADD CONSTRAINT "notes_score_check" CHECK ("app"."notes"."score" >= 0);', 'ALTER TABLE "app"."notes" ADD CONSTRAINT "notes_author_authors_id_fk" FOREIGN KEY ("author") REFERENCES "app"."authors"("id") ON DELETE no action ON UPDATE no action;', 'ALTER TABLE "app"."bookings" ADD CONSTRAINT "bookings_room_during_excl" EXCLUDE USING gist ("room" WITH =, "during" WITH &&);', From 8b1f8caeb7d4cc3a91317ca5a18194e2cd041d06 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:22:56 +0100 Subject: [PATCH 233/317] fix(appkit): say how to recover when a migration fails on existing rows A migration that failed with SQLSTATE class 22 or 23 named the code and nothing else, so a deploy start that met rows a NOT NULL or a retype cannot take gave no way forward. The error now says to repair the rows, on the deploy branch as a role with the DATABRICKS_SUPERUSER membership, and to deploy the same migration again. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 6 +++ .../migrations/tests/apply.pg.test.ts | 46 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 3f2afe0f1..40d882707 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -75,6 +75,8 @@ 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 @@ -1016,6 +1018,10 @@ export async function applyPendingMigrations( () => 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, diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts index f2b3d6cd1..88336c106 100644 --- a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -197,6 +197,52 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { 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", From 7d366ec1807d35a4d175eaeba321fe6a6e3e8e2c Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:23:14 +0100 Subject: [PATCH 234/317] test(appkit): pin introspect's drop refusal on a public enum and on foreign keys, by object Co-authored-by: Isaac Signed-off-by: ditadi --- .../introspect/tests/introspect.test.ts | 89 +++++++++++++++++-- 1 file changed, 82 insertions(+), 7 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 53963bea0..1f3d003db 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -165,7 +165,11 @@ const authorsPkey: ConstraintRow = { /** A catalog with authors(id) plus the given authors columns, and any extra tables. */ const authorsOnly = ( columns: ColumnRow[] = [], - extra: { tables: TableRow[]; columns: ColumnRow[] } = { + extra: { + tables: TableRow[]; + columns: ColumnRow[]; + constraints?: ConstraintRow[]; + } = { tables: [], columns: [], }, @@ -177,10 +181,45 @@ const authorsOnly = ( ...columns, ...extra.columns, ], - constraints: [authorsPkey], + 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) => @@ -733,7 +772,7 @@ export const schema = defineSchema(({ table }) => ({ "a column it cannot declare", previousSchema, authorsOnly([columnRow("authors", "email", "numeric")]), - 'ALTER TABLE "app"."authors" DROP COLUMN "email"; (type "numeric" is not supported)', + 'column app.authors.email (type "numeric" is not supported)', ], [ "a default it cannot declare", @@ -741,7 +780,7 @@ export const schema = defineSchema(({ table }) => ({ authorsOnly([ columnRow("authors", "email", "text", { default_expr: "lower('X')" }), ]), - `ALTER TABLE "app"."authors" ALTER COLUMN "email" DROP DEFAULT; (default lower('X') is not supported)`, + "the default of app.authors.email (default lower('X') is not supported)", ], [ "a table it cannot key", @@ -753,13 +792,49 @@ export const schema = defineSchema(({ table }) => ({ tables: [{ name: "tags", partitioned: false }], columns: [columnRow("tags", "id", "integer", { not_null: true })], }), - 'DROP TABLE "app"."tags" CASCADE; (it has no primary key)', + "table app.tags (it has no primary key)", ], [ "a column in the public schema", previousSchema.replace("}));", '}), { schemaName: "public" });'), authorsOnly([columnRow("authors", "email", "numeric")]), - 'ALTER TABLE "authors" DROP COLUMN "email"; (type "numeric" is not supported)', + '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", @@ -779,7 +854,7 @@ export const schema = defineSchema(({ table }) => ({ 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 run it on start.`, + `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(); From 0b8a933be692ce0b73e1a8afd059d87c91620b8e Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:23:20 +0100 Subject: [PATCH 235/317] fix(appkit): say that migrate skipped the public-tables check on a branch it does not write Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/migrate.ts | 2 +- packages/appkit/src/database/tooling/tests/migrate.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 1bddc0e6a..b784b24ab 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -119,7 +119,7 @@ async function applyBlocker(ctx: DbContext): Promise { const env = await resolveEnvBranch(ctx); if (!env) return NO_ENV_BRANCH; if (takesWrites(env.kind)) return undefined; - return `${notYourBranch(env)}. Migrations are applied only to branches \`appkit db init\` created for you; the deployed app applies committed migrations to its own branch`; + return `${notYourBranch(env)}. Migrations are applied only to branches \`appkit db init\` created for you; the deployed app applies committed migrations to its own branch. The check for tables left in public was skipped too; the deployed app runs it before it migrates`; } /** Apply pending migrations to the `.env` branch, or say why they were not. */ diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 682adbf71..cb2ffad09 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -245,7 +245,7 @@ describe("runMigrate", () => { expect(withBranchPool).not.toHaveBeenCalled(); expect(applyPendingMigrations).not.toHaveBeenCalled(); expect(report.notApplied).toBe( - "production is not your dev or session branch (it is the project's default branch). Migrations are applied only to branches `appkit db init` created for you; the deployed app applies committed migrations to its own branch", + "production is not your dev or session branch (it is the project's default branch). Migrations are applied only to branches `appkit db init` created for you; the deployed app applies committed migrations to its own branch. The check for tables left in public was skipped too; the deployed app runs it before it migrates", ); expect(fs.existsSync(report.typesFile)).toBe(true); }); From e390ea44e930e9d5afba2054991b39c764a1ae00 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:23:43 +0100 Subject: [PATCH 236/317] test(appkit): pin that a role delete's NOT_FOUND fails while the role still exists Co-authored-by: Isaac Signed-off-by: ditadi --- .../tooling/tests/lakebase-api.test.ts | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts index 3ce37d925..686c32584 100644 --- a/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts +++ b/packages/appkit/src/database/tooling/tests/lakebase-api.test.ts @@ -330,11 +330,13 @@ describe("LakebaseApi", () => { const fake = client([ { name: "op", done: true }, apiError(404, "NOT_FOUND"), + apiError(404, "NOT_FOUND"), { name: "op", done: true, error: { error_code: "RESOURCE_DOES_NOT_EXIST", message: "gone" }, }, + apiError(404, "NOT_FOUND"), apiError(403, "PERMISSION_DENIED"), ]); const api = new LakebaseApi(fake, fast); @@ -427,4 +429,33 @@ describe("LakebaseApi", () => { expect(fake.requests[0]?.payload).toBeUndefined(); expect(fake.requests).toHaveLength(2); }); + + test("deleteRole: a NOT_FOUND while the role still exists fails, e.g. a reassign target that is missing", async () => { + const role = "projects/p/branches/b/roles/sp"; + const fake = client([ + { + name: "op", + done: true, + error: { error_code: "NOT_FOUND", message: "role alice not found" }, + }, + { name: role }, + apiError(404, "role alice not found"), + { name: role }, + ]); + const api = new LakebaseApi(fake, fast); + const reassign = { reassignOwnedTo: "projects/p/branches/b/roles/alice" }; + + await expect(api.deleteRole(role, reassign)).rejects.toThrow( + `Lakebase: delete role ${role} failed: role alice not found`, + ); + await expect(api.deleteRole(role, reassign)).rejects.toThrow( + `Lakebase: delete role ${role} failed: role alice not found`, + ); + expect(fake.requests.map((r) => `${r.method} ${r.path}`)).toEqual([ + `DELETE /api/2.0/postgres/${role}`, + `GET /api/2.0/postgres/${role}`, + `DELETE /api/2.0/postgres/${role}`, + `GET /api/2.0/postgres/${role}`, + ]); + }); }); From ccfa8213719f572346a467a3d5fe343751e4b663 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:23:54 +0100 Subject: [PATCH 237/317] fix(appkit): detect the fork's copy in verify from the branch kind, not PGUSER verify decided whether the .env branch is yours from PGUSER, so a .env without it skipped the fork-copy check and one naming another user made their dev branch look like yours. It now classifies the branch through the API, as migrate does, and checks for the copy on your dev or session branch. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/verify.pg.test.ts | 21 ++++-- .../src/database/tooling/tests/verify.test.ts | 64 ++++++++++++++++--- .../appkit/src/database/tooling/verify.ts | 38 ++++------- 3 files changed, 84 insertions(+), 39 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts index 2bc543bb9..bce796d6f 100644 --- a/packages/appkit/src/database/tooling/tests/verify.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.pg.test.ts @@ -17,6 +17,7 @@ import type { DbContext } from "../context"; import { devBranchId } from "../naming"; import { FORK_COPY_TAG } from "../schema-state"; import { runVerify } from "../verify"; +import { FakeLakebase } from "./fakes"; const url = process.env.APPKIT_TEST_PG_URL; const builder = path.resolve( @@ -81,6 +82,10 @@ describe.skipIf(!url)("runVerify against Postgres", () => { `insert into ${journal} (hash, created_at) values ($1, $2)`, [createHash("sha256").update(sql).digest("hex"), MIGRATION.when], ); + // The .env branch is classified through the API, as you. + const lakebase = new FakeLakebase(); + lakebase.addBranch(BRANCH); + lakebase.addBranch(PRODUCTION, { default: true }); ctx = { root, env: { @@ -89,12 +94,16 @@ describe.skipIf(!url)("runVerify against Postgres", () => { LAKEBASE_ENDPOINT: `${BRANCH}/endpoints/primary`, PGUSER: USER, }, - workspace: () => { - throw new Error("no workspace calls expected"); - }, - api: () => { - throw new Error("no Lakebase API calls expected"); - }, + workspace: () => ({ + request: async () => { + throw new Error("no raw API calls expected"); + }, + currentUser: { me: async () => ({ userName: USER }) }, + getHost: async () => { + throw new Error("no host lookup expected"); + }, + }), + api: () => lakebase.api(), }; withBranchPool.mockImplementation( async (_ctx, fn: (pool: Pool) => Promise) => { diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index bfc054451..ee5fa014b 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -31,6 +31,9 @@ const ENV = { LAKEBASE_ENDPOINT: `${BRANCH}/endpoints/primary`, PGUSER: USER, }; +const SESSION = `projects/p/branches/${sessionBranchId(USER, "abc12345")}`; +const OTHER_USERS = `projects/p/branches/${devBranchId("bob@example.com")}`; +const PRODUCTION = "projects/p/branches/production"; const MIGRATIONS = "config/database/migrations"; const roots: string[] = []; @@ -77,15 +80,26 @@ function app( ); } } + // The .env branch is classified through the API, as you: your dev and + // session branches, another user's dev branch, and the default branch. + const lakebase = new FakeLakebase(); + lakebase.addBranch(BRANCH); + lakebase.addBranch(SESSION); + lakebase.addBranch(OTHER_USERS); + lakebase.addBranch(PRODUCTION, { default: true }); return { root, env, - workspace: () => { - throw new Error("no workspace calls expected"); - }, - api: () => { - throw new Error("no Lakebase API calls expected"); - }, + workspace: () => ({ + request: async () => { + throw new Error("no raw API calls expected"); + }, + currentUser: { me: async () => ({ userName: USER }) }, + getHost: async () => { + throw new Error("no host lookup expected"); + }, + }), + api: () => lakebase.api(), }; } @@ -350,6 +364,38 @@ describe("runVerify", () => { }); }); + test("your dev branch is yours by the identity you run as, not by PGUSER: without it the fork's copy is still reported", async () => { + const { PGUSER: _, ...withoutUser } = ENV; + const ctx = app(two, withoutUser); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + schemaOwner: "deployed-sp", + }); + + expect(await runVerify(ctx)).toMatchObject({ + forkCopy: expect.stringContaining( + `${devBranchId(USER)} still holds the rows the fork copied`, + ), + ok: false, + }); + }); + + test("a PGUSER naming another user does not make their dev branch yours", async () => { + const ctx = app(two, { + ...ENV, + LAKEBASE_ENDPOINT: `${OTHER_USERS}/endpoints/primary`, + PGUSER: "bob@example.com", + }); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + schemaOwner: "bob", + }); + + expect(await runVerify(ctx)).toMatchObject({ forkCopy: null, ok: true }); + }); + test("on a fork's copy, a migration from another git branch still counts as unknown", async () => { const ctx = app(two); branch({ @@ -369,10 +415,11 @@ describe("runVerify", () => { }); test("on your session branch, the fork's copy is reported as on your dev branch", async () => { - const session = `projects/p/branches/${sessionBranchId(USER, "abc12345")}`; + const session = SESSION; const ctx = app(two, { ...ENV, LAKEBASE_ENDPOINT: `${session}/endpoints/primary`, + APPKIT_DB_SESSION: "abc12345", }); branch({ columns: { notes: ["id", "body"] }, @@ -409,7 +456,7 @@ describe("runVerify", () => { }); test("on another user's dev branch, the schema they own is not a fork copy, and the other checks still decide", async () => { - const other = `projects/p/branches/${devBranchId("bob@example.com")}`; + const other = OTHER_USERS; const ctx = app(two, { ...ENV, LAKEBASE_ENDPOINT: `${other}/endpoints/primary`, @@ -500,7 +547,6 @@ describe("runVerify", () => { }); }); -const PRODUCTION = "projects/p/branches/production"; const DATABASE = `${PRODUCTION}/databases/db-1`; const SP = "11111111-2222-3333-4444-555555555555"; const HOST = "https://acme.cloud.databricks.com"; diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index bcb2b6989..f2328796d 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -16,14 +16,9 @@ import { readJournal, } from "../migrations/paths"; import type { DataPath } from "../runtime"; -import { - type DbContext, - hasEnvBranch, - NO_ENV_BRANCH, - withBranchPool, -} from "./context"; +import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context"; +import { resolveEnvBranch, takesWrites } from "./guard"; import { requireSchemaFile } from "./migrate"; -import { isUsersBranchId } from "./naming"; import { FORK_COPY_TAG, forkCopyRefusal, @@ -32,7 +27,6 @@ import { import { type BundleTarget, defaultBundleTarget, - parseResourceName, readBundle, resourceId, } from "./targets"; @@ -125,10 +119,9 @@ function rawOn(client: Pick): Pick { /** Read-only, as the developer, on the `.env` branch: one READ ONLY transaction, rolled back. */ async function verifyLocal(ctx: DbContext): Promise { requireSchemaFile(ctx.root, "verify"); - const branch = parseResourceName(ctx.env.LAKEBASE_ENDPOINT)?.branch; - if (!branch || !hasEnvBranch(ctx.env)) { - throw new Error(`Did not verify: ${NO_ENV_BRANCH}.`); - } + const env = await resolveEnvBranch(ctx); + if (!env) throw new Error(`Did not verify: ${NO_ENV_BRANCH}.`); + const branch = env.branch.name; const schema = await loadDefaultDatabaseSchema(ctx.root, { showImportError: true, }); @@ -139,18 +132,15 @@ async function verifyLocal(ctx: DbContext): Promise { const { problems: schemaProblems, advice: schemaAdvice } = await diagnoseSchema(rawOn(client), schema); // Only init forks a copy, onto the developer's own branch. Elsewhere, - // e.g. production, another owner is the normal state. init writes the - // user name it hashed into that branch id to PGUSER, so .env decides. - const user = ctx.env.PGUSER; - const forkCopy = - user && isUsersBranchId(user, resourceId(branch)) - ? (forkCopyRefusal( - branch, - schema.$schemaName, - await readSchemaState(client, schema.$schemaName), - "migrate", - ) ?? null) - : null; + // e.g. production, another owner is the normal state. + const forkCopy = takesWrites(env.kind) + ? (forkCopyRefusal( + branch, + schema.$schemaName, + await readSchemaState(client, schema.$schemaName), + "migrate", + ) ?? null) + : null; const drift = await readMigrationDrift(client, { migrationsFolder: migrationsFolder(ctx.root), schemaName: schema.$schemaName, From f91f244efe8bc1dcdfa670454a31977338e8beb4 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:24:07 +0100 Subject: [PATCH 238/317] fix(appkit): create the app schema only when it does not exist Postgres checks CREATE on the database before it looks at IF NOT EXISTS, so creating the journal in a schema the app already owned failed with 42501 for a role without that privilege. The migrator now reads pg_namespace first and runs CREATE SCHEMA only when the schema is absent. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 12 ++++++++++-- .../database/migrations/tests/apply.pg.test.ts | 18 ++++++++++++++++++ .../database/migrations/tests/apply.test.ts | 3 +++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 40d882707..d12921a38 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -670,9 +670,17 @@ async function ensureJournalTable( schemaName: string, ): Promise { if (await journalTableExists(client, schemaName, "record")) return; - await client.query( - `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(schemaName)}`, + // 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( diff --git a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts index 88336c106..7a9366123 100644 --- a/packages/appkit/src/database/migrations/tests/apply.pg.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.pg.test.ts @@ -426,6 +426,24 @@ describe.skipIf(!url)("applyPendingMigrations against Postgres", () => { } }); + 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 diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index af02e0091..412a7c636 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -205,6 +205,8 @@ function steps(statements: readonly string[]): string[] { 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"`)) @@ -251,6 +253,7 @@ describe("applyPendingMigrations", () => { "journal table?", "begin", "journal table?", + "schema?", "create schema", "create journal", `CREATE TABLE "app"."notes" ("id" integer);`, From f2c5da9dcce629bf781c025801bef2bbd2eaa1c3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:24:40 +0100 Subject: [PATCH 239/317] fix(appkit): keep the generated migration when a lock timeout or cancel fails it On SQLSTATE 55P03 or 57014 another session or a cancel made the migration fail, not schema.ts or the branch's data. migrate removed the file and said to change schema.ts or the data. It now keeps the file and reports the MigrationApplyError as is, with the hint it carries. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrate.ts | 9 +++- .../database/tooling/tests/migrate.test.ts | 45 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index b784b24ab..fb7662cd1 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -106,6 +106,12 @@ class UnappliedMigrationError extends Error implements MigrationWarnings { } } +/** + * SQLSTATEs where another session or a cancel, not the migration, made it fail: + * lock_not_available and query_canceled. The same migration can apply later. + */ +const RETRYABLE_AS_WRITTEN: ReadonlySet = new Set(["55P03", "57014"]); + /** Applying was refused before anything ran: a migration would shadow tables left in public. */ class TablesLeftInPublicError extends Error { constructor(reason: string) { @@ -197,7 +203,8 @@ async function migrateHolding( if ( error instanceof MigrationApplyError && error.failed === generated.tag && - error.code + error.code && + !RETRYABLE_AS_WRITTEN.has(error.code) ) { discardMigrationFiles(lock, generated); throw new Error( diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index cb2ffad09..667cd1d51 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -334,6 +334,51 @@ describe("runMigrate", () => { ).toBe(journal); }); + test.each([ + [ + "55P03", + "Another session held a lock on a table this migration changes for over 5s, 3 times. Deploy again once the long-running query or transaction finishes.", + ], + ["57014", undefined], + ])( + "when the migration this run wrote fails with SQLSTATE %s, neither schema.ts nor the data is at fault, so it stays", + async (code, hint) => { + const ctx = app(`notes: table("notes", { id: id() })`); + resolveEnvBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + writeSchema( + ctx.root, + `notes: table("notes", { id: id(), body: text() })`, + ); + resolveEnvBranch.mockResolvedValue(devBranch); + const failure = new MigrationApplyError({ + step: "Applying migrations", + failed: "0001_migration", + pending: ["0001_migration"], + hint, + cause: Object.assign(new Error("canceling statement"), { code }), + }); + applyPendingMigrations.mockRejectedValue(failure); + + const error = (await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + )) as Error; + + expect(error.message).toBe( + `Wrote ${path.join("config/database/migrations", "0001_migration.sql")}, but did not apply it: ${failure.message}`, + ); + expect(error.message).not.toContain("Change config/database/schema.ts"); + if (hint) expect(error.message).toContain(hint); + expect(error.cause).toBe(failure); + expect(error).toMatchObject({ generated: { tag: "0001_migration" } }); + expect( + fs.existsSync( + path.join(ctx.root, "config/database/migrations/0001_migration.sql"), + ), + ).toBe(true); + }, + ); + test("when an earlier migration fails, the one this run wrote stays for the next try", async () => { const ctx = app(`notes: table("notes", { id: id() })`); resolveEnvBranch.mockResolvedValue(null); From f0f0a5a0e2814743c7a3beb196c705e5bf6a3caa Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:25:07 +0100 Subject: [PATCH 240/317] fix(appkit): refuse introspect drops by the snapshot's objects, not by the SQL text drizzle-kit writes DROP TYPE "public"."mood" for an enum in public, which the text match missed, so the migration was recorded as applied. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/introspect/index.ts | 42 +++++------ .../src/database/tooling/introspect/render.ts | 12 +-- .../appkit/src/database/tooling/migrations.ts | 74 ++++++++++++++++++- .../database/tooling/tests/migrations.test.ts | 2 +- 4 files changed, 92 insertions(+), 38 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 2359f0881..602abc64c 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -24,6 +24,7 @@ import { discardMigrationFiles, type GeneratedMigration, generateMigrationFiles, + type PlannedMigration, } from "../migrations"; import { resourceId } from "../targets"; import { readCatalog, readUnreadObjects } from "./catalog"; @@ -99,24 +100,20 @@ function refuseSymlinkedDestination(root: string, file: string): void { const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`; -/** The statement drizzle-kit 0.31 writes to remove it. */ -function dropStatement(item: Unexpressed, schemaName: string): string { - // drizzle-kit leaves the public schema out of the name. - const named = - schemaName === "public" - ? `"${item.name}"` - : `"${schemaName}"."${item.name}"`; +/** How a refusal names it. */ +function described(item: Unexpressed, schemaName: string): string { + const table = `${schemaName}.${item.name}`; switch (item.kind) { case "table": - return `DROP TABLE ${named} CASCADE;`; + return `table ${table}`; case "column": - return `ALTER TABLE ${named} DROP COLUMN "${item.member}";`; + return `column ${table}.${item.member}`; case "default": - return `ALTER TABLE ${named} ALTER COLUMN "${item.member}" DROP DEFAULT;`; + return `the default of ${table}.${item.member}`; case "constraint": - return `ALTER TABLE ${named} DROP CONSTRAINT "${item.member}";`; + return `constraint ${item.member} of ${table}`; case "type": - return `DROP TYPE ${named};`; + return `type ${table}`; } } @@ -126,26 +123,21 @@ function dropStatement(item: Unexpressed, schemaName: string): string { * recorded falsely here, and would remove it from every deployed database. */ function refuseDropsOfUnexpressed( - statements: readonly string[], + migration: PlannedMigration, unexpressed: readonly Unexpressed[], schemaName: string, ): void { - const reasons = new Map( - unexpressed.map((item) => [dropStatement(item, schemaName), item.reason]), - ); - const refused = statements - .map((statement) => statement.trim()) - .filter((statement) => reasons.has(statement)); + 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( - (statement) => - `${shown(statement)} (${shown(reasons.get(statement) ?? "")})`, + (item) => + `${shown(described(item, schemaName))} (${shown(item.reason)})`, ) .join( - " ", - )}. The deployed app would run ${refused.length === 1 ? "it" : "them"} on start.`, + "; ", + )}. The deployed app would drop ${refused.length === 1 ? "it" : "them"} on start.`, ); } @@ -305,9 +297,9 @@ async function introspectHolding( interactive: options.interactive, ...(hasHistory ? { - beforeWrite: (statements: readonly string[]) => + beforeWrite: (planned: PlannedMigration) => refuseDropsOfUnexpressed( - statements, + planned, rendered.unexpressed, schemaName, ), diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index 6d081e922..ec86e2f94 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -4,6 +4,7 @@ import { isReservedTableName, } from "../../schema-builder/define-schema"; import type { AppKitTable, Schema } from "../../schema-builder/types"; +import type { SchemaObject } from "../migrations"; import type { IntrospectedColumn, IntrospectedForeignKey, @@ -22,15 +23,10 @@ export interface Skip { } /** - * Something the branch has that schema.ts leaves out, by raw catalog name. A - * migration that drops it must not be recorded as applied: the branch keeps it. + * 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 { - readonly kind: "table" | "column" | "default" | "constraint" | "type"; - /** The table, or the enum type for "type". */ - readonly name: string; - /** The column for "column" and "default", the constraint for "constraint". */ - readonly member?: string; +export interface Unexpressed extends SchemaObject { readonly reason: string; } diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index a90245d48..1d753455f 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -30,8 +30,24 @@ interface GenerateOptions { readonly tag?: string; /** false: an ambiguous rename throws instead of prompting. */ readonly interactive: boolean; - /** Sees the SQL before anything is written; throwing writes nothing. */ - readonly beforeWrite?: (statements: readonly string[]) => void; + /** Sees the migration before anything is written; throwing writes nothing. */ + readonly beforeWrite?: (migration: PlannedMigration) => void; +} + +/** An object of the app schema, by raw catalog name. */ +export interface SchemaObject { + readonly kind: "table" | "column" | "default" | "constraint" | "type"; + /** The table, or the enum type for "type". */ + readonly name: string; + /** The column for "column" and "default", the constraint for "constraint". */ + readonly member?: string; +} + +/** A migration generateMigrationFiles is about to write. */ +export interface PlannedMigration { + readonly statements: readonly string[]; + /** Whether it removes the object: the latest snapshot has it and the new one does not. */ + removes(object: SchemaObject): boolean; } export interface GeneratedMigration { @@ -83,11 +99,55 @@ const TAG_NAME = /^[a-z0-9_]+$/; /** The parts of a drizzle-kit PostgreSQL snapshot this module reads. */ interface Snapshot { id: string; - tables: Record }>; + /** Keyed ".
", public included. */ + tables: Record; + /** Keyed ".", public included. */ enums: Record; [key: string]: unknown; } +interface SnapshotTable { + columns: Record; + foreignKeys?: Record; + uniqueConstraints?: Record; + checkConstraints?: Record; + compositePrimaryKeys?: Record; +} + +function snapshotHas( + snapshot: Snapshot, + schemaName: string, + object: SchemaObject, +): boolean { + const key = `${schemaName}.${object.name}`; + if (object.kind === "type") return Object.hasOwn(snapshot.enums, key); + const table = Object.hasOwn(snapshot.tables, key) + ? snapshot.tables[key] + : undefined; + if (!table) return false; + const member = object.member ?? ""; + const column = Object.hasOwn(table.columns, member) + ? table.columns[member] + : undefined; + switch (object.kind) { + case "table": + return true; + case "column": + return column !== undefined; + case "default": + return column?.default !== undefined; + case "constraint": + return [ + table.foreignKeys, + table.uniqueConstraints, + table.checkConstraints, + table.compositePrimaryKeys, + ].some( + (constraints) => !!constraints && Object.hasOwn(constraints, member), + ); + } +} + /** drizzle-kit's empty starting snapshot (its `dryPg`). */ function originSnapshot(): Snapshot { return { @@ -365,7 +425,13 @@ export async function generateMigrationFiles( cur as unknown as KitSnapshot, ); if (statements.length === 0) return null; - options.beforeWrite?.(statements); + const schemaName = options.schema.$schemaName; + options.beforeWrite?.({ + statements, + removes: (object) => + snapshotHas(prev, schemaName, object) && + !snapshotHas(cur, schemaName, object), + }); const entries = journal?.entries ?? []; const last = entries.at(-1); diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index 52992235a..e11116c32 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -380,7 +380,7 @@ describe("generateMigrationFiles", () => { folder, schema: blog(), interactive: false, - beforeWrite: (statements) => { + beforeWrite: ({ statements }) => { seen.push([...statements]); throw new Error("refused"); }, From fe3bb7373b5c92d3093ebc5b6f0207ec2633d1b8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:25:09 +0100 Subject: [PATCH 241/317] fix(appkit): count a delete's NOT_FOUND as done only when the resource is gone A role delete whose reassign target is missing fails with NOT_FOUND too. The delete now reads the resource back and keeps the error while it still exists. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/lakebase-api.ts | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/packages/appkit/src/database/tooling/lakebase-api.ts b/packages/appkit/src/database/tooling/lakebase-api.ts index f4fc45fda..df1f45f92 100644 --- a/packages/appkit/src/database/tooling/lakebase-api.ts +++ b/packages/appkit/src/database/tooling/lakebase-api.ts @@ -258,9 +258,7 @@ export class LakebaseApi { /** A branch that is already gone counts as deleted. */ async deleteBranch(name: string): Promise { - await this.deleteResource(`delete branch ${name}`, { - path: `${API}/${name}`, - }); + await this.deleteResource(`delete branch ${name}`, name); } getDatabase(name: string): Promise { @@ -301,24 +299,30 @@ export class LakebaseApi { role: string, options: { reassignOwnedTo: string }, ): Promise { - await this.deleteResource(`delete role ${role}`, { - path: `${API}/${role}`, - query: { reassign_owned_to: options.reassignOwnedTo }, + 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, - request: { path: string; query?: ToolingRequest["query"] }, + name: string, + query?: ToolingRequest["query"], ): Promise { try { const op = await this.call(operation, { - ...request, + path: `${API}/${name}`, method: "DELETE", + ...(query ? { query } : {}), }); await this.wait(operation, op); } catch (error) { if (!isNotFound(error)) throw error; + if (await this.getOrNull(`get ${name}`, name)) throw error; } } From 53c4efb0d86281166e6e9f5e682f470d0c5dc1b0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:25:15 +0100 Subject: [PATCH 242/317] fix(appkit): look for tables left in public only when a migration is pending Migrate on start ran the catalog lookup on every start, so a current deploy branch paid a second query beyond the one read of the journal the design allows. applyPendingMigrations now takes a beforeApply hook that runs on the migrating connection, under the lock, once something is pending, and passes what it throws through unchanged. The deployed app's refusal runs there. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 13 +++++++++++++ .../src/plugins/database/migrate-on-start.ts | 19 ++++++++++--------- .../database/tests/migrate-on-start.test.ts | 1 + 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index 3f2afe0f1..dae45a264 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -42,6 +42,12 @@ interface ApplyMigrationsOptions { /** 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 { @@ -913,6 +919,7 @@ export async function applyPendingMigrations( let pending: string[] = []; let step = "Reading the recorded migrations"; let failed: string | undefined; + let inBeforeApply = false; try { let history = reconcileMigrations( files, @@ -955,6 +962,11 @@ export async function applyPendingMigrations( 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; @@ -995,6 +1007,7 @@ export async function applyPendingMigrations( }; } catch (error) { if ( + inBeforeApply || error instanceof MigrationBaselineMismatchError || error instanceof MigrationFilesError || error instanceof MigrationHistoryError || diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index c7464692b..1f95fbb21 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -87,7 +87,7 @@ function developmentBranchOwner(branch: string): string | undefined { * no-op. Every migration failure becomes a setup failure that names it. */ export async function migrateOnStart( - pool: Pick, + pool: Pick, schema: Schema, root: string = process.cwd(), env: NodeJS.ProcessEnv = process.env, @@ -112,14 +112,6 @@ export async function migrateOnStart( `PGHOST ${env.PGHOST} is a pooled endpoint, and migrations need a direct connection. Use the host without "-pooler".`, ); } - const leftInPublic = await detectTablesLeftInPublic( - catalogSqlOf(pool), - schema, - ); - if (leftInPublic) { - throw databaseSetupFailed(`not applying migrations: ${leftInPublic}`); - } - const started = Date.now(); let result: Awaited>; try { @@ -127,6 +119,15 @@ export async function migrateOnStart( migrationsFolder: folder, schemaName: schema.$schemaName, onDrift: "refuse", + beforeApply: async (client) => { + const leftInPublic = await detectTablesLeftInPublic( + catalogSqlOf(client), + schema, + ); + if (leftInPublic) { + throw databaseSetupFailed(`not applying migrations: ${leftInPublic}`); + } + }, }); } catch (error) { if ( diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index 6154ab35b..7c0e7a60d 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -168,6 +168,7 @@ describe("migrateOnStart", () => { migrationsFolder: path.join(root, "config/database/migrations"), schemaName: "app", onDrift: "refuse", + beforeApply: expect.any(Function), }); const logged = log.mock.calls.map((call) => call.map(String).join(" ")); expect(logged).toEqual([ From f92832e3f8886c0f41d6c3475acdf31815d65cac Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:25:16 +0100 Subject: [PATCH 243/317] fix(appkit): say when deployed SQL differs only in line endings verify --deployed still fails, since the design asks for byte-identical SQL, but a migration whose deployed SQL differs only in CRLF or LF is reported on its own: the app's start treats it as the same file, so the advice is to match the deployed line endings or deploy, not to restore it and write a new migration. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 32 +++++++++++++++++++ .../appkit/src/database/tooling/verify.ts | 28 +++++++++++++--- .../src/cli/commands/db/tooling-contract.ts | 1 + 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index ee5fa014b..192f3e9ef 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -792,6 +792,38 @@ describe("runVerify --deployed", () => { ); }); + test("SQL that differs only in line endings still fails, says so, and does not ask for a new migration", async () => { + const migrations = [ + { tag: "0000_migration", when: 1000 }, + { tag: "0001_migration", when: 2000 }, + ]; + const { ctx } = deployedApp({ + migrations, + deployedSql: { + "0000_migration": "-- 0000_migration\r\nselect 1;\r\n", + "0001_migration": "-- 0001_migration\r\nselect 2;\r\n", + }, + }); + + const report = await runVerify(ctx, DEPLOYED); + expect(report).toMatchObject({ + migrations: { + evidence: "differs", + missing: [], + changed: ["0001_migration"], + lineEndings: ["0000_migration"], + unknown: [], + }, + ok: false, + }); + if (report.kind !== "deploy") throw new Error("expected a deploy report"); + const [changed, lineEndings] = report.problems; + expect(changed).toContain("put the change in a new migration"); + expect(lineEndings).toBe( + "app my-app's active deployment has 0000_migration with the same SQL as this checkout commits, but other line endings (CRLF or LF). The app's start treats either line ending as the same file, but verify compares bytes: check it out with the line endings that were deployed, or run `databricks apps deploy` to deploy it as committed", + ); + }); + const JOURNAL = `${SNAPSHOT}/${MIGRATIONS}/meta/_journal.json`; test.each([ [ diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index f2328796d..6053f7853 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -69,6 +69,8 @@ type DeployedMigrations = readonly missing: readonly string[]; /** Committed migrations the snapshot has with another journal entry or other SQL. */ readonly changed: readonly string[]; + /** Committed migrations the snapshot has with the same SQL in other line endings. */ + readonly lineEndings: readonly string[]; /** Migrations the snapshot has that this checkout does not commit. */ readonly unknown: readonly string[]; } @@ -398,18 +400,23 @@ async function readDeployedMigrations( `${file} is listed in the deployed journal but missing from the snapshot`, ); } - return bytes.equals(sql) ? "same" : "changed"; + if (bytes.equals(sql)) return "same"; + return withLf(bytes) === withLf(sql) ? "lineEndings" : "changed"; }), ); - const tags = (status: "missing" | "changed") => + const tags = (status: "missing" | "changed" | "lineEndings") => committed .filter((_, index) => compared[index] === status) .map(({ entry }) => entry.tag); const missing = tags("missing"); const changed = tags("changed"); - return missing.length === 0 && changed.length === 0 && unknown.length === 0 + const lineEndings = tags("lineEndings"); + return missing.length === 0 && + changed.length === 0 && + lineEndings.length === 0 && + unknown.length === 0 ? { evidence: "verified" } - : { evidence: "differs", missing, changed, unknown }; + : { evidence: "differs", missing, changed, lineEndings, unknown }; } catch (error) { return { evidence: "unavailable", @@ -418,6 +425,9 @@ async function readDeployedMigrations( } } +const withLf = (bytes: Buffer) => + bytes.toString("utf-8").replace(/\r\n/g, "\n"); + /** Why the deployed migrations do not match the committed ones, each with its fix; empty when verified. */ function migrationsProblems( name: string, @@ -430,7 +440,7 @@ function migrationsProblems( ]; } const problems: string[] = []; - const { missing, changed, unknown } = migrations; + const { missing, changed, lineEndings, unknown } = migrations; if (missing.length > 0) { const them = missing.length === 1 ? "it" : "them"; problems.push( @@ -443,6 +453,14 @@ function migrationsProblems( `app ${name}'s active deployment has ${changed.join(", ")} with another journal entry or other SQL than this checkout commits. A migration that ran never runs again: restore ${them} to what was deployed, and put the change in a new migration`, ); } + // The app's start hashes either line ending as the same file, so a new + // migration would be wrong advice; verify still wants the deployed bytes. + if (lineEndings.length > 0) { + const it = lineEndings.length === 1 ? "it" : "them"; + problems.push( + `app ${name}'s active deployment has ${lineEndings.join(", ")} with the same SQL as this checkout commits, but other line endings (CRLF or LF). The app's start treats either line ending as the same file, but verify compares bytes: check ${it} out with the line endings that were deployed, or run ${DEPLOY} to deploy ${it} as committed`, + ); + } if (unknown.length > 0) { const them = unknown.length === 1 ? "it" : "them"; problems.push( diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 927ea818d..a479f1970 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -118,6 +118,7 @@ export interface DeployVerifyReport { readonly evidence: "differs"; readonly missing: readonly string[]; readonly changed: readonly string[]; + readonly lineEndings: readonly string[]; readonly unknown: readonly string[]; } | { readonly evidence: "unavailable"; readonly reason: string } From 73f97befcc878673e8932176a0a7bab40343e07d Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:25:37 +0100 Subject: [PATCH 244/317] fix(appkit): name the migration file that cannot be read drizzle-orm's reader turns any read failure, such as EACCES, into a plain Error that says the file is missing. Migrate on start passed that on as an unknown error, which setup replaces with a bare "Database setup failed". It now becomes a MigrationFilesError that names the file and the real reason. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/migrations/apply.ts | 35 +++++++++++++++++-- .../database/migrations/tests/apply.test.ts | 35 +++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index d12921a38..c6094d8d1 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -432,6 +432,32 @@ function lineEndingHashes(content: string, hash: string): string[] { 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 = path.join(folder, `${entry.tag}.sql`); + 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) { @@ -442,8 +468,13 @@ function readMigrations(folder: string, journal: Journal): MigrationFile[] { ); } } - // drizzle-orm's reader, so `hash` matches what drizzle-kit records. - const files = readMigrationFiles({ migrationsFolder: folder }); + 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) { diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 412a7c636..5ab6d3af6 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -1014,6 +1014,41 @@ describe("applyPendingMigrations", () => { 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", From 23cbf2fa120c91a6452b9d748c25d35637a08bab Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:25:40 +0100 Subject: [PATCH 245/317] test(appkit): pin introspect refusing an edited pending introspect migration Co-authored-by: Isaac Signed-off-by: ditadi --- .../introspect/tests/introspect.test.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 1f3d003db..91aaa2f8b 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -409,6 +409,29 @@ describe("runIntrospect", () => { 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(); From fdce6dafc5e6f4ba1cdb7d5f96fe0bbaf9c0acfd Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:25:47 +0100 Subject: [PATCH 246/317] fix(appkit): release the migration history lock on SIGINT and SIGTERM Ctrl+C during a migrate left .appkit-db.lock behind and the next command had to be unblocked by hand. The handlers release the lock only while it still holds this run's token, then re-raise the signal so the process ends as it would have. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/history-lock.ts | 18 +++++- .../tooling/tests/history-lock.test.ts | 60 +++++++++++++++++++ 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/tooling/history-lock.ts b/packages/appkit/src/database/tooling/history-lock.ts index f52a5eb0b..4ff70beb2 100644 --- a/packages/appkit/src/database/tooling/history-lock.ts +++ b/packages/appkit/src/database/tooling/history-lock.ts @@ -30,6 +30,9 @@ interface LockOwner { 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")); @@ -78,9 +81,9 @@ function heldError(root: string, file: string): Error { * 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 or the process exits. A process killed by a signal - * leaves the file behind: the next command reports it as stale, and it is - * deleted by hand, never taken over. + * Released when fn settles, the process exits, or SIGINT or SIGTERM arrives. + * A process killed 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, @@ -118,10 +121,19 @@ export async function withHistoryLock( 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 re-raise it once the lock + // is gone; when other listeners remain, ending the process is theirs. + const onSignal = (signal: NodeJS.Signals) => { + release(); + if (process.listenerCount(signal) === 0) process.kill(process.pid, signal); + }; process.on("exit", release); + for (const signal of RELEASE_SIGNALS) process.on(signal, onSignal); const lock = { folder, assertHeld() { diff --git a/packages/appkit/src/database/tooling/tests/history-lock.test.ts b/packages/appkit/src/database/tooling/tests/history-lock.test.ts index 90ce9bde2..c743183db 100644 --- a/packages/appkit/src/database/tooling/tests/history-lock.test.ts +++ b/packages/appkit/src/database/tooling/tests/history-lock.test.ts @@ -17,6 +17,34 @@ function writeLock(root: string, contents: string): void { fs.writeFileSync(path.join(root, LOCK), contents); } +/** + * Run a process that takes the lock in root and waits; resolves once it holds + * the lock, with a promise of the signal that ended it. + */ +async function holderProcess(root: string) { + const script = ` + const { withHistoryLock } = await import(${JSON.stringify(path.resolve(import.meta.dirname, "../history-lock.ts"))}); + await withHistoryLock(${JSON.stringify(root)}, "migrate", async () => { + process.stdout.write("held\\n"); + await new Promise(() => setInterval(() => undefined, 1000)); + });`; + const child = spawn( + process.execPath, + ["--import", "tsx", "--input-type=module", "-e", script], + { cwd: import.meta.dirname, stdio: ["ignore", "pipe", "inherit"] }, + ); + const ended = new Promise((resolve) => + child.once("exit", (_code, signal) => resolve(signal)), + ); + await new Promise((resolve, reject) => { + child.stdout.on("data", (chunk: Buffer) => { + if (chunk.toString().includes("held")) resolve(); + }); + ended.then(() => reject(new Error("the holder exited before holding"))); + }); + return { child, ended }; +} + async function failure(promise: Promise): Promise { return promise.then( () => { @@ -132,4 +160,36 @@ describe("withHistoryLock", () => { expect(fs.readFileSync(path.join(root, LOCK), "utf-8")).toBe(replaced); }); + + test.each(["SIGINT", "SIGTERM"] as const)( + "%s releases the lock, then ends the process with that signal", + async (signal) => { + const root = tempApp(); + const { child, ended } = await holderProcess(root); + expect(fs.existsSync(path.join(root, LOCK))).toBe(true); + + child.kill(signal); + + await expect(ended).resolves.toBe(signal); + expect(fs.existsSync(path.join(root, LOCK))).toBe(false); + }, + ); + + test("a signal leaves a lock another holder wrote in its place", async () => { + const root = tempApp(); + const { child, ended } = await holderProcess(root); + const replaced = JSON.stringify({ + pid: process.pid, + host: os.hostname(), + command: "introspect", + startedAt: "2026-01-01T00:00:00.000Z", + token: "theirs", + }); + fs.writeFileSync(path.join(root, LOCK), replaced); + + child.kill("SIGTERM"); + + await expect(ended).resolves.toBe("SIGTERM"); + expect(fs.readFileSync(path.join(root, LOCK), "utf-8")).toBe(replaced); + }); }); From bae65853ed523fd2a09c89500076b9fb84dee548 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:26:09 +0100 Subject: [PATCH 247/317] docs(appkit): match the branch response comment to the optional default and is_protected Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/lakebase-api.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/lakebase-api.ts b/packages/appkit/src/database/tooling/lakebase-api.ts index e020e28ca..f796f23ac 100644 --- a/packages/appkit/src/database/tooling/lakebase-api.ts +++ b/packages/appkit/src/database/tooling/lakebase-api.ts @@ -43,8 +43,9 @@ export class LakebaseApiError extends Error { const API = "/api/2.0/postgres"; -// The guard decides from these fields whether a command may write to a branch. -// A response without them must fail, not read as "not default, not protected". +// 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({ From 0f807958672fcdff152cda06ab127be8453c76a7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:26:11 +0100 Subject: [PATCH 248/317] test(appkit): pin that a failed drizzle-kit install leaves the fork's copy tagged Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/tests/init.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 802116dcf..e7bf17bbf 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1036,6 +1036,20 @@ describe("runInit — schema start", () => { ); }); + test("a failed install on a new fork leaves the copy tagged, so the next init rebuilds it", async () => { + const ctx = appOn(project(), {}, { files: { "package.json": "{}" } }); + + await expect( + runInit(ctx, { + runCommand: () => { + throw new Error("ENOTFOUND registry"); + }, + }), + ).rejects.toThrow(/^Installing drizzle-kit failed\./); + expect(tagWrites()).toEqual(["insert"]); + expect(cleanHolding).not.toHaveBeenCalled(); + }); + test("clean drops the schema, then applies the committed migrations without generating", async () => { const ctx = appOn(project(), {}, { files: { "package.json": "{}" } }); From 376323cef65386b431978a1578f41167a2f26ace Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:26:34 +0100 Subject: [PATCH 249/317] fix(appkit): record a pending introspect migration only when introspect would write the same SQL A teammate's committed 0001_introspect that was edited by hand matched the branch's tables, so introspect recorded it as applied and the edit never ran. Now introspect regenerates the SQL from the snapshot before it and refuses, pointing to appkit db migrate, when the file differs. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/introspect/index.ts | 27 +++++- .../appkit/src/database/tooling/migrations.ts | 94 ++++++++++++++----- 2 files changed, 92 insertions(+), 29 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 602abc64c..b63c96ff3 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -24,6 +24,7 @@ import { discardMigrationFiles, type GeneratedMigration, generateMigrationFiles, + generatesPending, type PlannedMigration, } from "../migrations"; import { resourceId } from "../targets"; @@ -71,7 +72,7 @@ export class IntrospectRefusedError extends Error { } } -/** Tags introspect writes. Pending ones match the branch when a fresh render adds nothing. */ +/** 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. */ @@ -306,10 +307,26 @@ async function introspectHolding( } : {}), }); - if (unrecorded.length > 0 && migration) { - throw notApplied( - `Its tables differ from what ${unrecorded.length === 1 ? "it describes" : "they describe"}.`, - ); + 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 writeDatabaseTypes(schema, typesFile); // The database already holds what the migrations describe; recording is the last step. diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 1d753455f..36ee7dafc 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -166,13 +166,16 @@ function originSnapshot(): Snapshot { }; } -function latestSnapshot(folder: string, journal: Journal | null): Snapshot { - const last = journal?.entries.at(-1); - if (!last) return originSnapshot(); - const file = snapshotFile(folder, last.idx); +/** The snapshot after `entry`; the origin before the first migration. */ +function snapshotAfter( + folder: string, + entry: JournalEntry | undefined, +): Snapshot { + if (!entry) return originSnapshot(); + const file = snapshotFile(folder, entry.idx); if (!fs.existsSync(file)) { throw new Error( - `Missing ${file} for migration ${last.tag}. Restore it from version control; it is the baseline for the next migration.`, + `Missing ${file} for migration ${entry.tag}. Restore it from version control; it is the baseline for the next migration.`, ); } return readJsonFile(file); @@ -386,6 +389,63 @@ export function dataDependentStatements( return statementsWhere(MAY_FAIL_ON_EXISTING_ROWS, statements); } +/** drizzle-kit's diff from `prev` to the schema: the new snapshot and its SQL. */ +async function diffSchema( + prev: Snapshot, + schema: Schema, + interactive: boolean, +): Promise<{ cur: Snapshot; statements: string[] }> { + const { generateDrizzleJson, generateMigration } = await loadDrizzleKit(); + const cur = generateDrizzleJson(drizzleKitImports(schema), prev.id, [ + schema.$schemaName, + ]) as unknown as Snapshot; + + if (!interactive) { + const ambiguity = findRenameAmbiguity(prev, cur, schema.$schemaName); + if (ambiguity) throw ambiguity; + } + + type KitSnapshot = Parameters[0]; + const statements = await generateMigration( + prev as unknown as KitSnapshot, + cur as unknown as KitSnapshot, + ); + return { cur, statements }; +} + +/** + * Whether the files of `tags`, the newest committed migrations, hold the SQL + * generation writes for the schema on top of the migrations before them. + */ +export async function generatesPending( + folder: string, + schema: Schema, + tags: readonly string[], + interactive: boolean, +): Promise { + const entries = readJournal(folder)?.entries ?? []; + const first = entries.findIndex((entry) => entry.tag === tags[0]); + if (first < 0) return false; + const { statements } = await diffSchema( + snapshotAfter(folder, entries[first - 1]), + schema, + interactive, + ); + const normalized = (text: string) => text.replace(/\r\n/g, "\n"); + const committed = tags.flatMap((tag) => + normalized(fs.readFileSync(migrationFile(folder, tag), "utf-8")).split( + BREAKPOINT, + ), + ); + return ( + committed.length === statements.length && + committed.every( + (statement, index) => + statement.trim() === normalized(statements[index] ?? "").trim(), + ) + ); +} + /** * Diff the schema against the latest committed snapshot with drizzle-kit and * write the next v7 migration: `NNNN_.sql`, `meta/NNNN_snapshot.json`, @@ -401,28 +461,14 @@ export async function generateMigrationFiles( `Migration tag "${name}" must use lowercase letters, digits and underscores`, ); } - const { generateDrizzleJson, generateMigration } = await loadDrizzleKit(); const { folder } = lock; const journal = readJournal(folder); - const prev = latestSnapshot(folder, journal); - const cur = generateDrizzleJson(drizzleKitImports(options.schema), prev.id, [ - options.schema.$schemaName, - ]) as unknown as Snapshot; - - if (!options.interactive) { - const ambiguity = findRenameAmbiguity( - prev, - cur, - options.schema.$schemaName, - ); - if (ambiguity) throw ambiguity; - } - - type KitSnapshot = Parameters[0]; - const statements = await generateMigration( - prev as unknown as KitSnapshot, - cur as unknown as KitSnapshot, + const prev = snapshotAfter(folder, journal?.entries.at(-1)); + const { cur, statements } = await diffSchema( + prev, + options.schema, + options.interactive, ); if (statements.length === 0) return null; const schemaName = options.schema.$schemaName; From 14683221a86ca7f5e11ba6c854110feed2caf011 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:26:44 +0100 Subject: [PATCH 250/317] fix(appkit): tag the fork's copy before init installs drizzle-kit The install can take a minute or fail. With the tag written first, a run that stops there leaves a copy the next init still rebuilds. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 22 ++++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 866f4d92f..dfea3ec0e 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -715,14 +715,22 @@ async function initHolding( 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 onBranch = ( - work: (client: Pick) => Promise, - ) => withBranchPool(branchCtx, work); const introspect = (recordAsApplied: boolean) => { onStep(`Writing schema.ts from schema ${schemaName} ${on}`); @@ -737,14 +745,6 @@ async function initHolding( introspected = await introspect(false); } - 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 handedOff = plan.handOff ? await handOffAppSchema(branchCtx, { branch: branch.name, From 991e9e3423360ce509d8b9d0c7d238a24acb7491 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:26:56 +0100 Subject: [PATCH 251/317] fix(appkit): fail setup when the app has no USAGE on its schema The startup schema check reads pg_catalog, which lists the tables of a schema the role cannot use. An app schema owned by another role without USAGE for the app passed setup, and every request then failed with 42501. Setup now fails with the ownership hint, which names the owner and the connecting role. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/plugins/database/schema-check.ts | 36 ++++++++ .../database/tests/schema-check.pg.test.ts | 83 +++++++++++++++++++ .../database/tests/schema-check.test.ts | 12 ++- 3 files changed, 127 insertions(+), 4 deletions(-) create mode 100644 packages/appkit/src/plugins/database/tests/schema-check.pg.test.ts diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index 7225d4f55..4cb06ee0f 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -1,4 +1,8 @@ import { databaseSetupFailed } from "../../database/errors"; +import { + INSUFFICIENT_PRIVILEGE, + ownershipHint, +} from "../../database/migrations/ownership"; import type { DataPath } from "../../database/runtime"; import type { Schema } from "../../database/schema-builder"; import type { MigrateOnStartDecision } from "./migrate-on-start"; @@ -9,6 +13,37 @@ interface CatalogColumn { readonly relation_kind: string; } +interface SchemaAccess { + readonly owner: string; + readonly current_user: string; + readonly usage: boolean; +} + +/** + * pg_catalog lists the tables of a schema the role has no USAGE on, so the + * check below would pass and every request would fail with 42501. + */ +async function assertSchemaUsable( + dataPath: DataPath, + schemaName: string, +): Promise { + const [access] = await dataPath.raw` + select pg_catalog.pg_get_userbyid(n.nspowner)::text as owner, + current_user::text as current_user, + pg_catalog.has_schema_privilege(n.oid, 'USAGE') as usage + from pg_catalog.pg_namespace n + where n.nspname::text = ${schemaName}`; + if (!access || access.usage) return; + const hint = ownershipHint(INSUFFICIENT_PRIVILEGE, { + schemaName, + owner: access.owner, + currentUser: access.current_user, + }); + throw databaseSetupFailed( + `role "${access.current_user}" has no USAGE on schema "${schemaName}". ${hint}`, + ); +} + function migrationAdvice(migration: MigrateOnStartDecision): string { switch (migration.kind) { case "off": @@ -35,6 +70,7 @@ export async function assertSchemaMatchesDatabase( const tables = Object.values(schema.$tables); if (tables.length === 0) return; const schemaName = schema.$schemaName; + await assertSchemaUsable(dataPath, schemaName); const tableNames = tables.map((table) => table.$name); // Include non-tables so setup can report their kind instead of claiming they are absent. const rows = await dataPath.raw` diff --git a/packages/appkit/src/plugins/database/tests/schema-check.pg.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.pg.test.ts new file mode 100644 index 000000000..869be8eb1 --- /dev/null +++ b/packages/appkit/src/plugins/database/tests/schema-check.pg.test.ts @@ -0,0 +1,83 @@ +import { randomUUID } from "node:crypto"; + +import { Pool } from "pg"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; + +import { + createDrizzleDataPath, + createDrizzleDb, +} from "../../../database/runtime/engine/drizzle-data-path"; +import { defineSchema, id, text } from "../../../database/schema-builder"; +import { assertSchemaMatchesDatabase } from "../schema-check"; + +// See database/migrations/tests/apply.pg.test.ts for APPKIT_TEST_PG_URL. +const url = process.env.APPKIT_TEST_PG_URL; +const ROLE_PASSWORD = "appkit-test"; + +describe.skipIf(!url)("assertSchemaMatchesDatabase against Postgres", () => { + let admin: Pool; + let app: Pool | undefined; + let schemaName: string; + let owner: string; + let appRole: string; + + beforeEach(async () => { + const suffix = randomUUID().slice(0, 8); + schemaName = `appkit_test_${suffix}`; + owner = `appkit_owner_${suffix}`; + appRole = `appkit_app_${suffix}`; + admin = new Pool({ connectionString: url, max: 1 }); + await admin.query(`create role "${owner}" nologin`); + await admin.query( + `create role "${appRole}" login password '${ROLE_PASSWORD}'`, + ); + await admin.query(`create schema "${schemaName}" authorization "${owner}"`); + await admin.query( + `create table "${schemaName}"."notes" (id serial primary key, body text)`, + ); + }); + + afterEach(async () => { + await app?.end(); + app = undefined; + await admin.query(`drop schema if exists "${schemaName}" cascade`); + await admin.query(`drop role "${appRole}"`); + await admin.query(`drop role "${owner}"`); + await admin.end(); + }); + + const check = () => { + const target = new URL(url ?? ""); + target.username = appRole; + target.password = ROLE_PASSWORD; + app = new Pool({ connectionString: target.toString(), max: 1 }); + const schema = defineSchema( + ({ table }) => ({ notes: table("notes", { id: id(), body: text() }) }), + { schemaName }, + ); + const dataPath = createDrizzleDataPath( + createDrizzleDb(app, schema), + schema, + { + columnAccess: "trusted", + }, + ); + return assertSchemaMatchesDatabase(dataPath, schema, { kind: "off" }); + }; + + test("every table exists, but the schema belongs to another role and the app has no USAGE: setup fails with the ownership hint", async () => { + const error = await check().catch((caught: unknown) => caught); + + expect(error).toMatchObject({ category: "SETUP_FAILED", phase: "setup" }); + expect((error as Error).message).toContain( + `role "${appRole}" has no USAGE on schema "${schemaName}". ` + + `Schema "${schemaName}" is owned by "${owner}", but the app connects as "${appRole}".`, + ); + }); + + test("USAGE granted on another role's schema passes", async () => { + await admin.query(`grant usage on schema "${schemaName}" to "${appRole}"`); + + await expect(check()).resolves.toBeUndefined(); + }); +}); diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index 4c3b76961..d6f93a134 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -23,7 +23,7 @@ type CatalogRow = { const OFF = { kind: "off" } as const; -/** Answer the catalog query with the given tables and columns. */ +/** Answer the catalog query with the given tables and columns, on a schema the role may use. */ function catalog( tables: Record, kinds: Record = {}, @@ -44,7 +44,11 @@ function catalog( relation_kind: kinds[name] ?? "r", })), ); - const raw = vi.fn(async () => rows); + const raw = vi.fn(async (strings: TemplateStringsArray) => + strings.join("?").includes("has_schema_privilege") + ? [{ owner: "app-sp", current_user: "app-sp", usage: true }] + : rows, + ); return { raw, path: { raw } as unknown as DataPath }; } @@ -126,8 +130,8 @@ describe("assertSchemaMatchesDatabase", () => { await assertSchemaMatchesDatabase(path, scoped, OFF); - expect(raw).toHaveBeenCalledTimes(1); - const [strings, ...values] = raw.mock.calls[0] as unknown as [ + expect(raw).toHaveBeenCalledTimes(2); + const [strings, ...values] = raw.mock.calls[1] as unknown as [ TemplateStringsArray, ...unknown[], ]; From cc9957003c5884341777dd41a58c9edb2ecedc74 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:27:15 +0100 Subject: [PATCH 252/317] test(appkit): pin the drizzle-kit install over another version and the repo-root stop Co-authored-by: Isaac Signed-off-by: ditadi --- .../tooling/tests/drizzle-kit-install.test.ts | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts b/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts index c149a73c0..b22a28351 100644 --- a/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts +++ b/packages/appkit/src/database/tooling/tests/drizzle-kit-install.test.ts @@ -56,6 +56,20 @@ describe("drizzleKitInstall", () => { ); }); + test("the lookup stops at the repository root: a lockfile above it belongs to another project", () => { + const home = tempApp({ + "yarn.lock": "", + "repo/.git/HEAD": "ref: refs/heads/main\n", + "repo/package.json": "{}", + "repo/apps/web/package.json": "{}", + }); + vi.stubEnv("npm_config_user_agent", undefined); + + expect(drizzleKitInstall(path.join(home, "repo/apps/web")).command).toBe( + "npm", + ); + }); + test("without a field or lockfile anywhere, the launcher's manager is used, else npm", () => { const root = tempApp({ "package.json": "{}" }); vi.stubEnv("npm_config_user_agent", "yarn/4.0.0 npm/? node/v22"); @@ -84,13 +98,30 @@ describe("ensureDrizzleKit", () => { ]); }); - test("does nothing when drizzle-kit resolves, or there is no package.json", () => { + test("installs over a drizzle-kit of another version", () => { + const root = tempApp({ + "package.json": "{}", + "pnpm-lock.yaml": "", + "node_modules/drizzle-kit/package.json": JSON.stringify({ + name: "drizzle-kit", + version: "0.30.0", + }), + }); + const run = vi.fn(); + + expect(ensureDrizzleKit(root, run, () => undefined)).toBe( + `pnpm add -D -E ${SPEC}`, + ); + expect(run).toHaveBeenCalledWith("pnpm", ["add", "-D", "-E", SPEC], root); + }); + + test("does nothing when the pinned drizzle-kit resolves, or there is no package.json", () => { const run = vi.fn(); const installed = tempApp({ "package.json": "{}", "node_modules/drizzle-kit/package.json": JSON.stringify({ name: "drizzle-kit", - version: "0.30.0", + version: DRIZZLE_KIT_VERSION, main: "index.js", }), "node_modules/drizzle-kit/index.js": "", From 78bffda92b195bc55efd4f9a4bd765f01b425a4b Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:27:30 +0100 Subject: [PATCH 253/317] fix(appkit): read the deployed migrations relative to the app's source_code_path verify --deployed mapped each local file to the snapshot by its path from the checkout's root. It now reads the app's source_code_path from databricks.yml, resolved against the file that declares it, and maps the journal and SQL relative to that folder. A source_code_path that leaves config/database/migrations out, or that the files cannot resolve, makes the deployed migrations unavailable with the reason. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/targets.ts | 61 ++++++++++++++++--- .../src/database/tooling/tests/verify.test.ts | 54 ++++++++++++++++ .../appkit/src/database/tooling/verify.ts | 43 ++++++++++++- 3 files changed, 147 insertions(+), 11 deletions(-) diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 411e3f27f..2d3a284ee 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -94,12 +94,13 @@ function record(value: unknown): Yaml { } /** - * A branch, database or workspace host databricks.yml names, as far as the - * checkout's files resolve it. A reference that is not declared at all has no - * value: the binding, variable or host that holds it is absent instead. + * A branch, database, workspace host or source path databricks.yml names, as + * far as the checkout's files resolve it. A reference that is not declared at + * all has no value: the binding, variable or host that holds it is absent + * instead. */ type BundleValue = - /** A full resource name, e.g. "projects/p/branches/b", or a workspace host. */ + /** A full resource name, e.g. "projects/p/branches/b", a workspace host, or a path. */ | { readonly kind: "resolved"; readonly name: string } /** As written: a `${…}` only a deploy resolves, no value, or not a resource name. */ | { readonly kind: "unresolved"; readonly written: string }; @@ -119,13 +120,15 @@ interface PostgresBinding { } /** An app one target of databricks.yml deploys. */ -interface BundleApp { +export interface BundleApp { /** Its key under resources.apps. */ readonly key: string; /** Its name as written; null when it has none. */ readonly declaredName: string | null; /** Its name with bundle references resolved; null when one needs a deploy to resolve. */ readonly name: string | null; + /** Its source_code_path, relative to databricks.yml's folder; null when it declares none. */ + readonly sourceCodePath: BundleValue | null; /** * Every postgres resource it has, and any `${…}` standing where its * resources, one of them, or a postgres block should be. @@ -346,8 +349,8 @@ function bundleValue( }; } -/** null when no host is declared; unresolved when one is declared and the files cannot resolve it. */ -function hostValue( +/** null when the value is not declared; unresolved when it is and the files cannot resolve it. */ +function declaredValue( written: unknown, resolve: (value: unknown) => string | null, ): BundleValue | null { @@ -412,6 +415,7 @@ function bundleApps( key, declaredName: typeof declared === "string" && declared ? declared : null, name: resolve(declared), + sourceCodePath: declaredValue(app?.source_code_path, resolve), postgres: appPostgres( `resources.apps.${key}.resources`, app?.resources, @@ -454,6 +458,38 @@ export function readDeployTarget(root: string): DeployTarget | null { }; } +/** + * An included file's app source_code_paths, made relative to databricks.yml's + * folder: the CLI resolves a path against the file that declares it. + */ +function rebaseSourcePaths( + file: Record, + folder: string, +): Record { + if (!folder) return file; + const rebase = (resources: unknown) => { + for (const app of Object.values(record(record(resources)?.apps) ?? {})) { + const declared = record(app); + const source = declared?.source_code_path; + if ( + declared && + typeof source === "string" && + !path.posix.isAbsolute(source) + ) { + declared.source_code_path = path.posix.join( + folder.split(path.sep).join("/"), + source, + ); + } + } + }; + rebase(file.resources); + for (const target of Object.values(record(file.targets) ?? {})) { + rebase(record(target)?.resources); + } + return file; +} + /** * databricks.yml, with the files its `include:` names merged in, per target; * null without one. Without `targets:` the bundle has one target, "default". @@ -470,7 +506,14 @@ export function readBundle(root: string): Bundle | null { .filter((pattern): pattern is string => typeof pattern === "string") .flatMap((pattern) => includedFiles(root, pattern)) .reduce( - (merged, included) => merge(merged, parseYaml(included)), + (merged, included) => + merge( + merged, + rebaseSourcePaths( + parseYaml(included), + path.relative(root, path.dirname(included)), + ), + ), main, ), ) as Record; @@ -508,7 +551,7 @@ export function readBundle(root: string): Bundle | null { ) : null; return { - host: hostValue( + host: declaredValue( record(target?.workspace)?.host ?? record(bundle.workspace)?.host, resolve, ), diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 192f3e9ef..5259a5d72 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -1124,6 +1124,60 @@ describe("runVerify --deployed", () => { }); }); + test("an app declared in an included file reads the deployed migrations relative to its source_code_path there", async () => { + const migrations = [{ tag: "0000_migration", when: 1000 }]; + const yml = ymlWithHost(); + const { ctx, requests } = deployedApp({ + migrations, + yml: yml.replace( + /resources:\n {2}apps:\n(?: {4}.*\n)+/, + "include:\n - resources/*.yml\n", + ), + }); + const app = /resources:\n {2}apps:\n(?: {4}.*\n)+/.exec(yml)?.[0] ?? ""; + fs.mkdirSync(path.join(ctx.root, "resources")); + fs.writeFileSync( + path.join(ctx.root, "resources/app.yml"), + app.replace("source_code_path: ./", "source_code_path: .."), + ); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { evidence: "verified" }, + ok: true, + }); + expect(requests).toContain( + `workspace.export ${SNAPSHOT}/${MIGRATIONS}/0000_migration.sql`, + ); + }); + + test.each([ + [ + "./server", + `${MIGRATIONS} is not inside source_code_path ./server of app my-app in databricks.yml, so no deployment of it has the committed migrations`, + ], + [ + "${var.app_source}", + 'source_code_path of app my-app in databricks.yml is "${var.app_source}", which this checkout\'s files do not resolve to a folder', + ], + ])( + "with source_code_path %s, the deployed migrations are unavailable and no snapshot file is read", + async (source, reason) => { + const { ctx, requests } = deployedApp({ + migrations: [{ tag: "0000_migration", when: 1000 }], + yml: ymlWithHost().replace( + "source_code_path: ./", + `source_code_path: ${source}`, + ), + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + migrations: { evidence: "unavailable", reason }, + ok: false, + }); + expect(requests.filter((r) => r.startsWith("workspace."))).toEqual([]); + }, + ); + test("--target checks that target's app, branch and host", async () => { const staging = "projects/p/branches/staging"; const { ctx, lakebase } = deployedApp({ diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 6053f7853..fc2a70306 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -25,6 +25,7 @@ import { readSchemaState, } from "./schema-state"; import { + type BundleApp, type BundleTarget, defaultBundleTarget, readBundle, @@ -321,6 +322,35 @@ function parseDeployedJournal(bytes: Buffer, label: string): JournalEntry[] { return entries; } +/** The local folder whose files an app's deployment carries, or why verify cannot tell. */ +type SourceFolder = { readonly folder: string } | { readonly reason: string }; + +/** + * The folder the app's source_code_path names, which must hold the + * migrations. Without one it is the checkout's root. + */ +function sourceFolder( + root: string, + file: string, + name: string, + declared: BundleApp["sourceCodePath"], +): SourceFolder { + if (!declared) return { folder: root }; + if (declared.kind === "unresolved") { + return { + reason: `source_code_path of app ${name} in ${file} is "${declared.written}", which this checkout's files do not resolve to a folder`, + }; + } + const folder = path.resolve(root, declared.name); + const migrations = path.relative(folder, migrationsFolder(root)); + if (migrations.startsWith("..") || path.isAbsolute(migrations)) { + return { + reason: `${path.relative(root, migrationsFolder(root)).split(path.sep).join("/")} is not inside source_code_path ${declared.name} of app ${name} in ${file}, so no deployment of it has the committed migrations`, + }; + } + return { folder }; +} + /** * The committed migrations against the snapshot of the source the active * deployment runs: each needs the same journal entry (idx, when, @@ -334,7 +364,11 @@ async function readDeployedMigrations( ctx: DbContext, deployment: Deployment | undefined, committed: readonly CommittedMigration[], + source: SourceFolder, ): Promise { + if ("reason" in source) { + return { evidence: "unavailable", reason: source.reason }; + } if (!deployment) { return { evidence: "unavailable", @@ -353,7 +387,7 @@ async function readDeployedMigrations( } const folder = migrationsFolder(ctx.root); const deployedPath = (file: string) => - `${snapshot}/${path.relative(ctx.root, file).split(path.sep).join("/")}`; + `${snapshot}/${path.relative(source.folder, file).split(path.sep).join("/")}`; try { const journalPath = deployedPath(journalFile(folder)); const journal = await exportFile(ctx, journalPath); @@ -752,7 +786,12 @@ async function verifyDeploy( const [roles, migrations] = await Promise.all([ // Only meaningful once the app is bound to this branch. sp && binding.length === 0 ? api.listRoles(branch) : null, - readDeployedMigrations(ctx, deployed.active_deployment, committed), + readDeployedMigrations( + ctx, + deployed.active_deployment, + committed, + sourceFolder(ctx.root, file, name, app.sourceCodePath), + ), ]); if (roles && !roles.some((role) => role.status?.postgres_role === sp)) { problems.push( From 153718d9b78240d79cf0a4bac42fbce3e2cb3bcb Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:27:35 +0100 Subject: [PATCH 254/317] test(appkit): pin migrate naming the recovery for a failed pending introspect migration Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/migrate.test.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 19ee1517e..dee56e399 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -325,6 +325,32 @@ describe("runMigrate", () => { ).toBe(true); }); + test("when a pending introspect migration fails, it says to rerun appkit db introspect", async () => { + const ctx = app(`notes: table("notes", { id: id() })`); + resolveEnvBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + + resolveEnvBranch.mockResolvedValue(devBranch); + const failure = new MigrationApplyError({ + step: "Applying migrations", + failed: "0001_introspect", + pending: ["0001_introspect"], + cause: Object.assign(new Error('relation "notes" already exists'), { + code: "42P07", + }), + }); + applyPendingMigrations.mockRejectedValue(failure); + + const error = (await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + )) as Error; + + expect(error.message).toBe( + `${failure.message} If an interrupted \`appkit db introspect\` wrote 0001_introspect, the branch already has what it does: rerun \`appkit db introspect\` to record it.`, + ); + expect(error.cause).toBe(failure); + }); + test("a guard failure after generating says so too, and never connects", async () => { const ctx = app(`notes: table("notes", { id: id() })`); resolveEnvBranch.mockRejectedValue( From 548c88121143baac1ce21e60ff70a27c96b7d1b8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:27:50 +0100 Subject: [PATCH 255/317] fix(appkit): say to rerun appkit db introspect when a pending introspect migration fails in migrate Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrate.ts | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 4f8733dc0..b76d1e4be 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -106,6 +106,24 @@ class UnappliedMigrationError extends Error implements MigrationWarnings { } } +/** + * An interrupted `appkit db introspect` leaves its migration written but not + * recorded, and running it fails on what the branch already has. + */ +function withIntrospectRecovery(error: unknown): unknown { + if ( + !(error instanceof MigrationApplyError) || + !error.failed || + !/^\d{4}_introspect$/.test(error.failed) + ) { + return error; + } + return new Error( + `${error.message} If an interrupted \`appkit db introspect\` wrote ${error.failed}, the branch already has what it does: rerun \`appkit db introspect\` to record it.`, + { cause: error }, + ); +} + /** Why migrations must not be applied to the `.env` branch; undefined when they may. */ async function applyBlocker(ctx: DbContext): Promise { const env = await resolveEnvBranch(ctx); @@ -176,7 +194,7 @@ async function migrateHolding( try { outcome = await applyToEnvBranch(ctx, lock.folder, schema); } catch (error) { - if (!generated) throw error; + if (!generated) throw withIntrospectRecovery(error); const file = path.relative(ctx.root, generated.file); // A failed migration left in the journal runs first on every later try, so a // fix in schema.ts would stack behind it and never apply. @@ -191,7 +209,12 @@ async function migrateHolding( { cause: error }, ); } - throw new UnappliedMigrationError(ctx.root, generated, warnings, error); + throw new UnappliedMigrationError( + ctx.root, + generated, + warnings, + withIntrospectRecovery(error), + ); } return { generated, From 16601d70201ba83920593bb4ff8fdae5d21d5d66 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:28:52 +0100 Subject: [PATCH 256/317] docs(appkit): say what appkit db introspect defaults to, writes, and where init forks from --schema-name defaults to the schemaName schema.ts declares, then app; only the foreign keys the builder can express are written; init forks the branch the default databricks.yml target binds, else the project default. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/introspect/index.ts | 2 +- .../introspect/tests/introspect.test.ts | 2 +- .../shared/src/cli/commands/db/introspect.ts | 18 +++++++++++------- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index b63c96ff3..ee54f616b 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -199,7 +199,7 @@ async function introspectHolding( 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 project's default branch, and introspects it when there is no ${DEFAULT_SCHEMA_FILE}.`, + `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); diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 91aaa2f8b..eb80c9d95 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -336,7 +336,7 @@ describe("runIntrospect", () => { 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 project's default branch, and introspects it when there is no config/database/schema.ts.", + "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); diff --git a/packages/shared/src/cli/commands/db/introspect.ts b/packages/shared/src/cli/commands/db/introspect.ts index 11fb2e5a3..2e783759e 100644 --- a/packages/shared/src/cli/commands/db/introspect.ts +++ b/packages/shared/src/cli/commands/db/introspect.ts @@ -20,7 +20,10 @@ export const dbIntrospectCommand = new Command("introspect") .description( "Write config/database/schema.ts from the .env branch's tables, plus the migration that brings history up to them", ) - .option("--schema-name ", "Postgres schema to read (default: app)") + .option( + "--schema-name ", + "Postgres schema to read (default: the schemaName schema.ts declares, else app)", + ) .addHelpText( "after", ` @@ -29,16 +32,17 @@ express (composite keys, unsupported types or defaults, some foreign keys) is le out with an "// appkit: skipped …" comment. Columns the previous schema.ts marks .private() stay private. Every other column -and every foreign key is written as the database has it. A schema.ts that does -not load stops introspect before it writes anything. +is written as the database has it, and so is each foreign key the builder can +express. A schema.ts that does not load stops introspect before it writes +anything. Without migration history this writes 0000_baseline; with history, the next NNNN_introspect, once the branch has applied every committed migration. The migration is recorded as applied, so introspect runs only on your dev or session -branch; \`appkit db init\` creates one from the project's default branch. The -deployed app adopts 0000_baseline on start when its tables already exist. If -anything fails, schema.ts, database.d.ts and the migrations are left as they -were. +branch; \`appkit db init\` creates one, forked from the branch the default +databricks.yml target binds, else the project's default branch. The deployed +app adopts 0000_baseline on start when its tables already exist. If anything +fails, schema.ts, database.d.ts and the migrations are left as they were. Examples: $ appkit db introspect From 4264584d4f147d8a9443bd4e5a76d81faf3e3f30 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:29:11 +0100 Subject: [PATCH 257/317] fix(appkit): install drizzle-kit over another version, and stop the manager lookup at the repo root init skipped the install when any drizzle-kit resolved, so migrate then refused the wrong version. A lockfile above the repository belongs to another project, so the package-manager lookup stops at the directory that holds .git. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/drizzle-kit-install.ts | 28 +++++++++++++------ .../appkit/src/database/tooling/migrations.ts | 18 ++++++------ 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/packages/appkit/src/database/tooling/drizzle-kit-install.ts b/packages/appkit/src/database/tooling/drizzle-kit-install.ts index 7da9d5cb5..980eefa4e 100644 --- a/packages/appkit/src/database/tooling/drizzle-kit-install.ts +++ b/packages/appkit/src/database/tooling/drizzle-kit-install.ts @@ -7,7 +7,7 @@ import { detectPackageManager, type PackageManager, } from "../../../../shared/src/cli/package-manager"; -import { DRIZZLE_KIT_VERSION, hasDrizzleKit } from "./migrations"; +import { DRIZZLE_KIT_VERSION, drizzleKitVersionAt } from "./migrations"; /** Runs a command in `cwd`; throws when it fails. */ export type RunCommand = ( @@ -31,15 +31,21 @@ interface Install { /** * The install with the manager the app declares, by packageManager field or - * lockfile, in its own directory or the nearest ancestor's (a workspace member - * has neither; its root does). Without one, the manager that launched this - * command, else npm. + * 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 || dir === path.dirname(dir)) break; + if ( + manager || + fs.existsSync(path.join(dir, ".git")) || + dir === path.dirname(dir) + ) { + break; + } } const command = manager ?? detectPackageManager(root, "npm"); return { @@ -67,21 +73,25 @@ export const runCommand: RunCommand = (command, args, cwd) => { /** * Install drizzle-kit as an exact dev dependency when the app cannot resolve - * it. Returns the command it ran; null when drizzle-kit was there, or there is - * no package.json to add it to. + * 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 { - if (hasDrizzleKit(root) || !fs.existsSync(path.join(root, "package.json"))) { + 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}, which writes migrations (${line})`, + `Installing drizzle-kit ${DRIZZLE_KIT_VERSION}${found ? ` in place of ${found}` : ""}, which writes migrations (${line})`, ); try { run(command, args, root); diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 14d114f00..105a0f9ed 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -220,18 +220,18 @@ function installedPackage(name: string, from: string): InstalledPackage | null { } /** - * Whether the app at `root` has drizzle-kit, at any version. The node_modules - * walk is what ESM resolution does; createRequire would also follow NODE_PATH, - * which `import("drizzle-kit/api")` ignores. + * The version of the drizzle-kit the app at `root` has; null when it has none. + * The node_modules walk is what ESM resolution does; createRequire would also + * follow NODE_PATH, which `import("drizzle-kit/api")` ignores. */ -export function hasDrizzleKit(root: string): boolean { +export function drizzleKitVersionAt(root: string): string | null { for (let dir = path.resolve(root); ; dir = path.dirname(dir)) { - if ( - fs.existsSync(path.join(dir, "node_modules/drizzle-kit/package.json")) - ) { - return true; + const file = path.join(dir, "node_modules/drizzle-kit/package.json"); + if (fs.existsSync(file)) { + const { version } = readJsonFile<{ version?: unknown }>(file); + return typeof version === "string" ? version : null; } - if (dir === path.dirname(dir)) return false; + if (dir === path.dirname(dir)) return null; } } From 2d49802ab6f032916e4876201decbb26cde402ef Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:29:47 +0100 Subject: [PATCH 258/317] fix(appkit): read BUNDLE_VAR_ variables as a third reading of databricks.yml `databricks bundle` takes variable values from BUNDLE_VAR_ ahead of variable-overrides.json, so a branch one names is a deploy target for a deploy from this shell. The guard now reads the command's env as a third view of each target. A set value that does not resolve to a branch refuses every branch, like the other readings, and the refusal names the variable. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/guard.ts | 22 ++-- .../appkit/src/database/tooling/targets.ts | 77 +++++++++++-- .../src/database/tooling/tests/guard.test.ts | 24 ++++ .../database/tooling/tests/targets.test.ts | 107 +++++++++++++++--- 4 files changed, 199 insertions(+), 31 deletions(-) diff --git a/packages/appkit/src/database/tooling/guard.ts b/packages/appkit/src/database/tooling/guard.ts index ef19cb7aa..95629fe56 100644 --- a/packages/appkit/src/database/tooling/guard.ts +++ b/packages/appkit/src/database/tooling/guard.ts @@ -35,14 +35,20 @@ function deployRefusal( ): string | null { if (boundary.unresolved.length > 0) { const references = boundary.unresolved - .map( - ({ target, at, written, file }) => - `${at} in target ${target}${file ? ` with ${file}` : ""} (${written ? JSON.stringify(written) : "no value"})`, - ) + .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 = boundary.unresolved.some(({ file }) => file) - ? "databricks.yml or the variable-overrides.json named" - : "databricks.yml"; + 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 `databricks.yml may deploy to it: the files do not resolve ${references}; give ${boundary.unresolved.length > 1 ? "them values" : "it a value"} in ${where}`; } return boundary.branches.has(branch) @@ -106,7 +112,7 @@ export async function resolveEnvBranch( const local = readLocalTarget(ctx.env); const name = parseResourceName(local.endpoint ?? undefined)?.branch; if (!name || !hasEnvBranch(ctx.env)) return null; - const boundary = readDeployBoundary(ctx.root); + const boundary = readDeployBoundary(ctx.root, ctx.env); const [branch, { userName }] = await Promise.all([ ctx.api().getBranch(name), currentIdentity(ctx), diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 96cb51dfc..8d0697dab 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -114,6 +114,19 @@ interface BundleTarget extends TargetBindings { * without the file. */ readonly overridden: (TargetBindings & { readonly file: string }) | null; + /** + * The same bindings with the command's BUNDLE_VAR_ variables applied ahead + * of variable-overrides.json, as a deploy from this shell would; null when + * none is set. + */ + readonly environment: + | (TargetBindings & { + /** The BUNDLE_VAR_ variables set, e.g. "BUNDLE_VAR_postgres_branch". */ + readonly variables: string; + /** The variable-overrides.json applied under them, if any. */ + readonly file?: string; + }) + | null; } interface Bundle { @@ -169,6 +182,30 @@ function readVariableOverrides( return { file, values }; } +const BUNDLE_VAR = "BUNDLE_VAR_"; + +/** The variable values `databricks bundle` takes from BUNDLE_VAR_; null when none is set. */ +function readBundleVariables(env: NodeJS.ProcessEnv): { + readonly variables: string; + readonly values: Record; +} | null { + const set = Object.entries(env) + .filter( + (entry): entry is [string, string] => + entry[0].startsWith(BUNDLE_VAR) && + entry[0].length > BUNDLE_VAR.length && + entry[1] !== undefined, + ) + .sort(([a], [b]) => a.localeCompare(b)); + if (set.length === 0) return null; + return { + variables: set.map(([key]) => key).join(", "), + values: Object.fromEntries( + set.map(([key, value]) => [key.slice(BUNDLE_VAR.length), value]), + ), + }; +} + /** * Files an `include:` pattern names. `*` and `?` match within one path * segment, as in the Databricks CLI; a pattern with other glob syntax throws @@ -361,8 +398,9 @@ function bundleApps( /** * databricks.yml, with the files its `include:` names merged in, per target; * null without one. Without `targets:` the bundle has one target, "default". + * env is the command's, for its BUNDLE_VAR_ variables. */ -function readBundle(root: string): Bundle | null { +function readBundle(root: string, env: NodeJS.ProcessEnv): Bundle | null { const file = ["databricks.yml", "databricks.yaml"] .map((name) => path.join(root, name)) .find((candidate) => fs.existsSync(candidate)); @@ -379,6 +417,7 @@ function readBundle(root: string): Bundle | null { ), ) as Record; + const fromEnv = readBundleVariables(env); const declared = Object.entries(record(bundle.targets) ?? {}); const targets: Array<[string, Yaml]> = declared.length > 0 @@ -417,6 +456,13 @@ function readBundle(root: string): Bundle | null { overridden: overrides ? { file: overrides.file, ...bindings(overrides.values) } : null, + environment: fromEnv + ? { + variables: fromEnv.variables, + ...(overrides ? { file: overrides.file } : {}), + ...bindings({ ...overrides?.values, ...fromEnv.values }), + } + : null, }; }), }; @@ -430,9 +476,11 @@ export interface UnresolvedBinding { readonly written: string; /** The variable-overrides.json whose values leave it unresolved; absent for databricks.yml's own values. */ readonly file?: string; + /** The BUNDLE_VAR_ variables whose values leave it unresolved; absent without them. */ + readonly environment?: string; } -/** What databricks.yml deploys to, read from this checkout's files only, variable-overrides.json included. */ +/** What databricks.yml deploys to, read from this checkout's files, variable-overrides.json included, and the command's BUNDLE_VAR_ variables. */ export interface DeployBoundary { /** Every branch any target binds, through an app's postgres resources or its postgres_branch variable. */ readonly branches: ReadonlySet; @@ -445,24 +493,33 @@ export interface DeployBoundary { * reference it cannot resolve. Empty without databricks.yml or a postgres * binding. A database counts for the branch it is on. */ -export function readDeployBoundary(root: string): DeployBoundary { +export function readDeployBoundary( + root: string, + env: NodeJS.ProcessEnv, +): DeployBoundary { const branches = new Set(); const unresolved: UnresolvedBinding[] = []; - for (const target of readBundle(root)?.targets ?? []) { - const views: Array<[TargetBindings, string | undefined]> = [ - [target, undefined], - ]; + for (const target of readBundle(root, env)?.targets ?? []) { + type Source = Pick; + const views: Array<[TargetBindings, Source]> = [[target, {}]]; if (target.overridden) { - views.push([target.overridden, target.overridden.file]); + views.push([target.overridden, { file: target.overridden.file }]); + } + if (target.environment) { + const { file, variables } = target.environment; + views.push([ + target.environment, + { ...(file ? { file } : {}), environment: variables }, + ]); } - for (const [bindings, file] of views) { + for (const [bindings, source] of views) { const add = (at: string, value: BundleValue) => { if (value.kind === "unresolved") { unresolved.push({ target: target.name, at, written: value.written, - ...(file ? { file } : {}), + ...source, }); return; } diff --git a/packages/appkit/src/database/tooling/tests/guard.test.ts b/packages/appkit/src/database/tooling/tests/guard.test.ts index 97b0e69af..82a992e27 100644 --- a/packages/appkit/src/database/tooling/tests/guard.test.ts +++ b/packages/appkit/src/database/tooling/tests/guard.test.ts @@ -185,6 +185,30 @@ describe("resolveEnvBranch", () => { ); }); + test("a branch a BUNDLE_VAR_ in the command's environment names is a deploy target", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(dev); + const root = tempApp({ + "databricks.yml": databricksYml( + `${P}/branches/production`, + `${P}/branches/production/databases/db`, + ), + }); + + const env = await resolveEnvBranch( + fakeContext({ + root, + env: { ...envFor(dev), BUNDLE_VAR_postgres_branch: dev }, + api: lakebase.api(), + }), + ); + + expect(env).toMatchObject({ + kind: "deploy-target", + reason: "it is a branch databricks.yml deploys to", + }); + }); + test("a target whose branch the files cannot resolve keeps your own dev branch from taking writes", async () => { const lakebase = new FakeLakebase(); lakebase.addBranch(dev); diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index 31c52cea1..55f0a12f8 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -69,7 +69,7 @@ describe("readDeployBoundary", () => { "projects/p/branches/production/databases/databricks-postgres", ), }); - expect(readDeployBoundary(root)).toEqual({ + expect(readDeployBoundary(root, {})).toEqual({ branches: new Set(["projects/p/branches/production"]), unresolved: [], }); @@ -91,7 +91,7 @@ targets: postgres_branch: projects/p/branches/staging `, }); - expect(readDeployBoundary(root).branches).toEqual( + expect(readDeployBoundary(root, {}).branches).toEqual( new Set([ "projects/p/branches/main", "projects/p/branches/dev-alice-1a2b3c", @@ -125,7 +125,7 @@ resources: database: projects/p/branches/reports/databases/db `, }); - expect(readDeployBoundary(root)).toEqual({ + expect(readDeployBoundary(root, {})).toEqual({ branches: new Set([ "projects/p/branches/production", "projects/p/branches/archive", @@ -147,7 +147,7 @@ resources: branch: projects/p/branches/production `, }); - expect(() => readDeployBoundary(root)).toThrow( + expect(() => readDeployBoundary(root, {})).toThrow( 'Cannot read include pattern "resources/[ab]*.yml", so the branches it deploys to are unknown: only * and ? are supported, not [, ] or \\.', ); }); @@ -160,7 +160,7 @@ resources: )} prod: {} `, }); - expect(readDeployBoundary(root)).toEqual({ + expect(readDeployBoundary(root, {})).toEqual({ branches: new Set(["projects/p/branches/production"]), unresolved: [ { @@ -192,7 +192,7 @@ resources: branch: main `, }); - expect(readDeployBoundary(root)).toEqual({ + expect(readDeployBoundary(root, {})).toEqual({ branches: new Set(), unresolved: [ { @@ -233,7 +233,7 @@ resources: `, }); - const boundary = readDeployBoundary(root); + const boundary = readDeployBoundary(root, {}); expect(boundary).toEqual({ branches: new Set(), @@ -281,7 +281,7 @@ resources: }), }); - const boundary = readDeployBoundary(root); + const boundary = readDeployBoundary(root, {}); expect(boundary).toEqual({ branches: new Set(["projects/p/branches/production", dev]), @@ -300,6 +300,84 @@ resources: }); }); + test("a BUNDLE_VAR_ value in the environment binds every target too, ahead of variable-overrides.json", () => { + const dev = `projects/p/branches/${devBranchId("alice@example.com")}`; + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/db", + ), + ".databricks/bundle/default/variable-overrides.json": JSON.stringify({ + postgres_branch: "projects/p/branches/staging", + }), + }); + + const boundary = readDeployBoundary(root, { + BUNDLE_VAR_postgres_branch: dev, + }); + + expect(boundary).toEqual({ + branches: new Set([ + "projects/p/branches/production", + "projects/p/branches/staging", + dev, + ]), + unresolved: [], + }); + expect( + classifyBranch({ + branch: { name: dev, status: {} }, + userName: "alice@example.com", + sessionId: null, + boundary, + }), + ).toEqual({ + kind: "deploy-target", + reason: "it is a branch databricks.yml deploys to", + }); + }); + + test("a set BUNDLE_VAR_ value that is not a branch name is unresolved, and names the variable", () => { + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/db", + ), + }); + + const boundary = readDeployBoundary(root, { + BUNDLE_VAR_postgres_branch: "", + }); + + expect(boundary.unresolved).toEqual([ + { + target: "default", + at: "resources.apps.app.resources[0].postgres.branch", + written: "${var.postgres_branch}", + environment: "BUNDLE_VAR_postgres_branch", + }, + { + target: "default", + at: "variables.postgres_branch", + written: "", + environment: "BUNDLE_VAR_postgres_branch", + }, + ]); + expect( + classifyBranch({ + branch: { + name: `projects/p/branches/${devBranchId("alice@example.com")}`, + status: {}, + }, + userName: "alice@example.com", + sessionId: null, + boundary, + }).reason, + ).toBe( + 'databricks.yml may deploy to it: the files do not resolve resources.apps.app.resources[0].postgres.branch in target default with BUNDLE_VAR_postgres_branch ("${var.postgres_branch}"), variables.postgres_branch in target default with BUNDLE_VAR_postgres_branch (no value); give them values in databricks.yml or the BUNDLE_VAR_ variable named', + ); + }); + test("a variable-overrides.json value that is not a branch name is unresolved, and names the file", () => { const root = tempApp({ "databricks.yml": databricksYml( @@ -311,7 +389,7 @@ resources: }), }); - expect(readDeployBoundary(root).unresolved).toEqual([ + expect(readDeployBoundary(root, {}).unresolved).toEqual([ { target: "default", at: "resources.apps.app.resources[0].postgres.branch", @@ -346,21 +424,24 @@ resources: ), ".databricks/bundle/default/variable-overrides.json": contents, }); - expect(() => readDeployBoundary(root)).toThrow(message); + expect(() => readDeployBoundary(root, {})).toThrow(message); }, ); test("empty without databricks.yml or without a postgres binding", () => { const empty = { branches: new Set(), unresolved: [] }; - expect(readDeployBoundary(tempApp())).toEqual(empty); + expect(readDeployBoundary(tempApp(), {})).toEqual(empty); expect( - readDeployBoundary(tempApp({ "databricks.yml": "bundle:\n name: x\n" })), + readDeployBoundary( + tempApp({ "databricks.yml": "bundle:\n name: x\n" }), + {}, + ), ).toEqual(empty); }); test("an invalid databricks.yml throws instead of reading as no binding", () => { const root = tempApp({ "databricks.yml": "targets:\n default: [\n" }); - expect(() => readDeployBoundary(root)).toThrow( + expect(() => readDeployBoundary(root, {})).toThrow( /^Cannot read databricks\.yml, so the branches it deploys to are unknown: .+\(\d+:\d+\)$/, ); }); From bebc569d045fc49384552e0de08a9f41fa0dcc9e Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:29:54 +0100 Subject: [PATCH 259/317] test(appkit): pin that an interrupted rebuild without schema.ts introspects, then rebuilds Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 24 +++++++++++++------ .../tooling/tests/schema-state.test.ts | 6 ++--- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index e7bf17bbf..8b3b0e8ae 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1262,17 +1262,27 @@ describe("runInit — the start follows the branch's own state", () => { expect(tagWrites()).toEqual([]); }); - test("an interrupted rebuild without schema.ts says how to continue instead of guessing", async () => { + test("an interrupted rebuild without schema.ts introspects the copy, then rebuilds it without another hand-off or tag", async () => { schemaOwner = USER; tagged = true; + const lakebase = existingDev(); - await expect( - init(appOn(existingDev(), {}, { schema: false })), - ).rejects.toThrow( - "Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", + const { report } = await init(appOn(lakebase, {}, { schema: false })); + + expect(report.start).toMatchObject({ + kind: "introspect", + rebuilt: { reason: "fork-copy" }, + }); + expect(introspectHolding.mock.calls[0]?.[2]).toMatchObject({ + recordAsApplied: false, + }); + expect(introspectHolding.mock.invocationCallOrder[0]).toBeLessThan( + cleanHolding.mock.invocationCallOrder[0] ?? 0, ); - expect(introspectHolding).not.toHaveBeenCalled(); - expect(cleanHolding).not.toHaveBeenCalled(); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + expect(tagWrites()).toEqual([]); }); test("a copy without a journal is rebuilt without a tag, with a warning before the hand-off that says what to do after a stop", async () => { diff --git a/packages/appkit/src/database/tooling/tests/schema-state.test.ts b/packages/appkit/src/database/tooling/tests/schema-state.test.ts index 026f6cb20..758b7d915 100644 --- a/packages/appkit/src/database/tooling/tests/schema-state.test.ts +++ b/packages/appkit/src/database/tooling/tests/schema-state.test.ts @@ -54,9 +54,9 @@ describe("planStart", () => { ); }); - test("an interrupted rebuild without schema.ts cannot be finished by default: the message says how to continue", () => { - expect(() => planStart(interrupted, undefined, false)).toThrow( - "Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", + test("an interrupted rebuild without schema.ts introspects the copy, then rebuilds", () => { + expect(planStart(interrupted, undefined, false)).toEqual( + only({ kind: "introspect", rebuild: true }), ); }); From 12d89ebfcb814a772ae8682edeb150359c61a74a Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:30:08 +0100 Subject: [PATCH 260/317] fix(appkit): finish an interrupted rebuild without schema.ts by introspecting first The design rebuilds a copy from the baseline introspect writes when there is no schema.ts. A tagged copy now takes that path too instead of refusing. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/schema-state.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/packages/appkit/src/database/tooling/schema-state.ts b/packages/appkit/src/database/tooling/schema-state.ts index a91986771..00e558ca4 100644 --- a/packages/appkit/src/database/tooling/schema-state.ts +++ b/packages/appkit/src/database/tooling/schema-state.ts @@ -148,11 +148,6 @@ export function planStart( confirm: false, }; } - if (interrupted && !hasSchema && requested === undefined) { - throw new Error( - "The rebuild of the app schema on your branch stopped before it finished, and this checkout has no config/database/schema.ts to rebuild from. Restore schema.ts, then rerun `appkit db init`. `appkit db init --schema introspect` writes schema.ts from the branch and keeps the rows the fork copied.", - ); - } return { ...NOTHING_ELSE, kind: requested ?? (hasSchema ? "clean" : "introspect"), From e8f657b40a967cdfb52d366532b84ace7356c331 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:30:18 +0100 Subject: [PATCH 261/317] fix(appkit): check a target's workspace.profile host in verify --deployed A target that names workspace.profile and no host skipped the workspace check, so verify could read another workspace's app of the same name. It now resolves that profile's host through the Databricks SDK config and refuses when this shell is authenticated elsewhere, or when the profile does not resolve. A target with neither keeps today's behavior, since a deploy uses this shell's auth too. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/context.ts | 8 +++ .../appkit/src/database/tooling/targets.ts | 17 ++++-- .../src/database/tooling/tests/verify.test.ts | 61 +++++++++++++++++++ .../appkit/src/database/tooling/verify.ts | 44 +++++++++++-- packages/shared/src/cli/commands/db/verify.ts | 6 +- 5 files changed, 122 insertions(+), 14 deletions(-) diff --git a/packages/appkit/src/database/tooling/context.ts b/packages/appkit/src/database/tooling/context.ts index 93daf4b2c..95d771947 100644 --- a/packages/appkit/src/database/tooling/context.ts +++ b/packages/appkit/src/database/tooling/context.ts @@ -70,6 +70,14 @@ export function createDbContext( 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 diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 2d3a284ee..a971de20c 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -94,13 +94,13 @@ function record(value: unknown): Yaml { } /** - * A branch, database, workspace host or source path databricks.yml names, as - * far as the checkout's files resolve it. A reference that is not declared at - * all has no value: the binding, variable or host that holds it is absent - * instead. + * A branch, database, workspace host or profile, or source path databricks.yml + * names, as far as the checkout's files resolve it. A reference that is not + * declared at all has no value: the binding, variable or host that holds it is + * absent instead. */ type BundleValue = - /** A full resource name, e.g. "projects/p/branches/b", a workspace host, or a path. */ + /** A full resource name, e.g. "projects/p/branches/b", a workspace host or profile, or a path. */ | { readonly kind: "resolved"; readonly name: string } /** As written: a `${…}` only a deploy resolves, no value, or not a resource name. */ | { readonly kind: "unresolved"; readonly written: string }; @@ -140,6 +140,8 @@ export interface BundleApp { interface TargetBindings { /** workspace.host of the target, else of the bundle; null when neither declares one. */ readonly host: BundleValue | null; + /** workspace.profile of the target, else of the bundle; null when neither declares one. */ + readonly profile: BundleValue | null; readonly apps: readonly BundleApp[]; /** The target's postgres_branch variable; null when the bundle declares none. */ readonly postgresBranch: BundleValue | null; @@ -555,6 +557,11 @@ export function readBundle(root: string): Bundle | null { record(target?.workspace)?.host ?? record(bundle.workspace)?.host, resolve, ), + profile: declaredValue( + record(target?.workspace)?.profile ?? + record(bundle.workspace)?.profile, + resolve, + ), apps: bundleApps(apps ?? {}, resolve), postgresBranch: variable("postgres_branch", "branch"), postgresDatabase: variable("postgres_database", "database"), diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 5259a5d72..5a0579353 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -1240,6 +1240,67 @@ describe("runVerify --deployed", () => { expect(lakebase.calls).toEqual([]); }); + describe("a target with workspace.profile and no host", () => { + const STAGING = "https://staging.cloud.databricks.com"; + const ymlWithProfile = (profile: string) => + `${databricksYml(PRODUCTION, DATABASE)} workspace:\n profile: ${profile}\n`; + + beforeEach(() => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "appkit-db-cfg-")); + roots.push(dir); + const config = path.join(dir, ".databrickscfg"); + fs.writeFileSync( + config, + `[acme]\nhost = ${HOST}\n\n[staging]\nhost = ${STAGING}/\n`, + ); + vi.stubEnv("DATABRICKS_CONFIG_FILE", config); + vi.stubEnv("DATABRICKS_HOST", ""); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + test("is checked against that profile's host from the Databricks config", async () => { + const { ctx } = deployedApp({ yml: ymlWithProfile("acme") }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ ok: true }); + }); + + test("is refused before any API call when this shell is authenticated against another workspace", async () => { + const { ctx, lakebase, requests } = deployedApp({ + yml: ymlWithProfile("staging"), + }); + + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + `Target default deploys with profile staging to ${STAGING}, but this shell is authenticated against ${HOST}. Set DATABRICKS_CONFIG_PROFILE=staging, then rerun.`, + ); + expect(requests).toEqual([]); + expect(lakebase.calls).toEqual([]); + }); + + test("is refused when the Databricks config has no such profile", async () => { + const { ctx, requests } = deployedApp({ yml: ymlWithProfile("gone") }); + + await expect(runVerify(ctx, DEPLOYED)).rejects.toThrow( + /^Target default deploys with profile gone, which this machine's Databricks config does not resolve to a workspace host: .*profile not found.*\. Add the profile, or set workspace\.host in target default, then rerun\.$/, + ); + expect(requests).toEqual([]); + }); + }); + + test("a target with neither workspace.host nor workspace.profile runs against this shell's workspace", async () => { + const { ctx } = deployedApp({ + yml: databricksYml(PRODUCTION, DATABASE), + authenticatedHost: "https://other.cloud.databricks.com", + }); + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + host: null, + ok: true, + }); + }); + test("a branch that only variable-overrides.json sets is the one verify checks, as a deploy from this checkout uses it", async () => { // The target gives the variables no value; only the overrides file does. const yml = `${databricksYml(PRODUCTION, DATABASE).replace( diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index fc2a70306..9790958b3 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -16,7 +16,12 @@ import { readJournal, } from "../migrations/paths"; import type { DataPath } from "../runtime"; -import { type DbContext, NO_ENV_BRANCH, withBranchPool } from "./context"; +import { + type DbContext, + NO_ENV_BRANCH, + profileHost, + withBranchPool, +} from "./context"; import { resolveEnvBranch, takesWrites } from "./guard"; import { requireSchemaFile } from "./migrate"; import { @@ -599,17 +604,37 @@ function hostOf(url: string): string { } } -/** The API calls go to the workspace this shell is authenticated against, which must be the target's. */ +/** + * The API calls go to the workspace this shell is authenticated against, which + * must be the target's: its workspace.host, else the host of its + * workspace.profile. With neither, a deploy uses this shell's auth too. + */ async function assertTargetWorkspace( ctx: DbContext, target: string, host: string | null, + profile: string | null, ): Promise { - if (!host) return; + if (!host && !profile) return; + let expected = host; + if (!expected && profile) { + try { + expected = await profileHost(profile); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error( + `Target ${target} deploys with profile ${profile}, which this machine's Databricks config does not resolve to a workspace host: ${message.replace(/\.+$/, "")}. Add the profile, or set workspace.host in target ${target}, then rerun.`, + { cause: error }, + ); + } + } + if (!expected) return; const authenticated = await ctx.workspace().getHost(); - if (hostOf(authenticated) === hostOf(host)) return; + if (hostOf(authenticated) === hostOf(expected)) return; throw new Error( - `Target ${target} deploys to ${host}, but this shell is authenticated against ${authenticated}. Set DATABRICKS_CONFIG_PROFILE to a profile for ${host}, then rerun.`, + host + ? `Target ${target} deploys to ${host}, but this shell is authenticated against ${authenticated}. Set DATABRICKS_CONFIG_PROFILE to a profile for ${host}, then rerun.` + : `Target ${target} deploys with profile ${profile} to ${expected}, but this shell is authenticated against ${authenticated}. Set DATABRICKS_CONFIG_PROFILE=${profile}, then rerun.`, ); } @@ -704,9 +729,16 @@ async function verifyDeploy( `No target workspace: workspace.host in target ${target.name}${withFile} is "${deploy.host.written}", which this checkout's files do not resolve to a host. Give the variable it names a value in ${file}, or in .databricks/bundle/${target.name}/variable-overrides.json, then rerun.`, ); } + if (!deploy.host && deploy.profile?.kind === "unresolved") { + throw new Error( + `No target workspace: workspace.profile in target ${target.name}${withFile} is "${deploy.profile.written}", which this checkout's files do not resolve to a profile. Give the variable it names a value in ${file}, or in .databricks/bundle/${target.name}/variable-overrides.json, then rerun.`, + ); + } const branch = branchValue.name; const database = databaseValue?.name ?? null; const host = deploy.host?.name ?? null; + const profile = + deploy.profile?.kind === "resolved" ? deploy.profile.name : null; const committed = readCommitted(migrationsFolder(ctx.root)); const report = ( name: string | null, @@ -742,7 +774,7 @@ async function verifyDeploy( } const name = app.name; - await assertTargetWorkspace(ctx, target.name, host); + await assertTargetWorkspace(ctx, target.name, host, profile); const api = ctx.api(); const [branchFound, databaseFound, deployed] = await Promise.all([ api.getBranch(branch), diff --git a/packages/shared/src/cli/commands/db/verify.ts b/packages/shared/src/cli/commands/db/verify.ts index e96d06892..80b637e59 100644 --- a/packages/shared/src/cli/commands/db/verify.ts +++ b/packages/shared/src/cli/commands/db/verify.ts @@ -57,9 +57,9 @@ APPKIT_DB_MIGRATE_ON_START=true applies them on start, and a migration that fails stops it; \`databricks apps logs\` shows why. When the checkout has .databricks/bundle//variable-overrides.json, the branch and database come from it, as a deploy from this checkout uses them. When verify cannot -read that source, it fails. It refuses when the target's workspace.host is -not the workspace this shell is authenticated against, or when this -checkout's files do not resolve it. +read that source, it fails. It refuses when the target's workspace.host, or +without one the host of its workspace.profile, is not the workspace this +shell is authenticated against, or when it cannot resolve either. Exits 1 on any finding. Nothing is written or created. From 51cedf23347f3ca881a929f9ffdca74aeca4ae5d Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:28:09 +0100 Subject: [PATCH 262/317] fix(appkit): warn when APPKIT_DB_MIGRATE_ON_START has a value other than true Only the exact value true turns migrate on start on. A deploy that set TRUE, 1 or yes started without migrating and without saying why. The flag stays strict, and setup now logs the value it ignored. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/plugins/database/lifecycle.ts | 6 ++++++ .../src/plugins/database/migrate-on-start.ts | 10 ++++++++-- .../plugins/database/tests/lifecycle.test.ts | 15 +++++++++++++++ .../database/tests/migrate-on-start.test.ts | 18 ++++++++++++++---- 4 files changed, 43 insertions(+), 6 deletions(-) diff --git a/packages/appkit/src/plugins/database/lifecycle.ts b/packages/appkit/src/plugins/database/lifecycle.ts index 7b4df7a95..d782070ca 100644 --- a/packages/appkit/src/plugins/database/lifecycle.ts +++ b/packages/appkit/src/plugins/database/lifecycle.ts @@ -192,6 +192,12 @@ export async function createDatabaseState( }); // A deployed app applies committed migrations as its own identity before the checks below. const migration = decideMigrateOnStart(); + if (migration.kind === "off" && migration.ignored !== undefined) { + logger.warn( + 'APPKIT_DB_MIGRATE_ON_START is %s, and only "true" turns migrate on start on, so this process ignored it and did not migrate.', + JSON.stringify(migration.ignored), + ); + } if (migration.kind === "skipped") { logger.warn( "APPKIT_DB_MIGRATE_ON_START is true, but this process is not the deployed app, so it did not migrate. %s Databricks Apps sets DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET and PGUSER for the deployed app.", diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index 4d59f18ae..851bf09f9 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -25,7 +25,11 @@ import { createLogger } from "../../logging/logger"; const logger = createLogger("database"); export type MigrateOnStartDecision = - | { readonly kind: "off" } + | { + readonly kind: "off"; + /** A non-empty flag value other than "true", which turns nothing on. */ + readonly ignored?: string; + } | { readonly kind: "skipped"; readonly reason: string } | { readonly kind: "migrate" }; @@ -42,7 +46,9 @@ export type MigrateOnStartDecision = export function decideMigrateOnStart( env: NodeJS.ProcessEnv = process.env, ): MigrateOnStartDecision { - if (env.APPKIT_DB_MIGRATE_ON_START !== "true") return { kind: "off" }; + const flag = env.APPKIT_DB_MIGRATE_ON_START; + if (flag !== "true") + return flag ? { kind: "off", ignored: flag } : { kind: "off" }; for (const name of ["DATABRICKS_CLIENT_ID", "DATABRICKS_CLIENT_SECRET"]) { if (!env[name]) return { kind: "skipped", reason: `${name} is not set.` }; } diff --git a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts index 736d9bc36..0ac63e4aa 100644 --- a/packages/appkit/src/plugins/database/tests/lifecycle.test.ts +++ b/packages/appkit/src/plugins/database/tests/lifecycle.test.ts @@ -276,6 +276,21 @@ describe("createDatabaseState", () => { ); }); + test("a flag other than true warns once that it was ignored, and migrates nothing", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + const { execute } = arrange(); + const decision = { kind: "off", ignored: "1" } as const; + mocks.decideMigrateOnStart.mockReturnValue(decision); + + await createDatabaseState(schema, execute); + + expect(mocks.migrateOnStart).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls.flat().map(String).join(" ")).toContain( + 'APPKIT_DB_MIGRATE_ON_START is "1", and only "true" turns migrate on start on, so this process ignored it and did not migrate.', + ); + }); + test("a start the flag asks to migrate but that is not the deployed app warns once with the reason, and migrates nothing", async () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); const { path, execute } = arrange(); diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index a64250571..afae1f367 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -95,15 +95,25 @@ describe("decideMigrateOnStart", () => { "a deployed app without the flag", { DATABRICKS_APP_NAME: "my-app", ...credentials }, ], - [ - "a flag other than true", - { APPKIT_DB_MIGRATE_ON_START: "1", ...credentials }, - ], + ["an empty flag", { APPKIT_DB_MIGRATE_ON_START: "", ...credentials }], ["nothing set", {}], ] as const)("%s: off, with nothing to say", (_label, env) => { expect(decideMigrateOnStart(env)).toEqual({ kind: "off" }); }); + test.each(["1", "TRUE", "true ", "yes"])( + "a flag of %j is not true: off, naming the value it ignored", + (value) => { + expect( + decideMigrateOnStart({ + APPKIT_DB_MIGRATE_ON_START: value, + ...credentials, + PGUSER: "sp-client-id", + }), + ).toEqual({ kind: "off", ignored: value }); + }, + ); + test.each([ [ "`databricks apps run-local`: the flag from app.yaml, no credentials", From 8f382fabbba3a5bc05daad76ff3320d3d6dc37f7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:30:40 +0100 Subject: [PATCH 263/317] test(shared): pin that the rebuild line says the copied rows went, without "keeps them" Co-authored-by: Isaac Signed-off-by: ditadi --- .../shared/src/cli/commands/db/init-clean-seed.test.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index 792023ed2..c826e7413 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -261,7 +261,7 @@ describe("appkit db init", () => { expect(printed).toContain("Applied 0000_migration to the .env branch"); }); - test("a rebuild without --schema says the copied rows went and how to keep them; with --schema clean it does not", async () => { + test("a rebuild without --schema says the copied rows went; with --schema clean it does not", async () => { const rebuilt = (reason: "fork-copy" | "requested") => ({ ...report, start: { @@ -279,8 +279,9 @@ describe("appkit db init", () => { tooling.runInit.mockResolvedValue(rebuilt("fork-copy")); await init(); expect(output(log)).toContain( - "The branch still held the rows the fork copied: the app schema was rebuilt from the committed migrations. `appkit db init --schema migrate` keeps them.", + "The branch still held the rows the fork copied, so the app schema was rebuilt from the committed migrations without them.", ); + expect(output(log)).not.toContain("keeps them"); log.mockClear(); resetOptionValues(); @@ -332,7 +333,7 @@ describe("appkit db init", () => { ); }); - test("an introspect start with a rebuild prints what introspect wrote, the drop, the migrations, and names --schema introspect to keep the rows", async () => { + test("an introspect start with a rebuild prints what introspect wrote, the drop, the migrations, and that the copied rows went", async () => { tooling.runInit.mockResolvedValue({ ...report, start: { @@ -370,8 +371,9 @@ describe("appkit db init", () => { const printed = output(log); expect(printed).toContain( - "`appkit db init --schema introspect` keeps them", + "The branch still held the rows the fork copied, so the app schema was rebuilt from the committed migrations without them.", ); + expect(printed).not.toContain("keeps them"); expect(printed).toContain( "Wrote config/database/schema.ts from schema app", ); From b90336e15db310ec5ef7b1128abce98cb3124932 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:30:54 +0100 Subject: [PATCH 264/317] fix(shared): stop telling a rebuilt branch that --schema migrate keeps the copied rows After the rebuild the rows are gone, so the flag cannot keep them on this branch. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/shared/src/cli/commands/db/init.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index acd17dd51..7626df529 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -89,7 +89,7 @@ function printInitReport( const { start, keptCopy } = report; if (rebuildOf(start)?.reason === "fork-copy") { info( - `The branch still held the rows the fork copied: the app schema was rebuilt from the committed migrations. \`appkit db init --schema ${start.kind === "introspect" ? "introspect" : "migrate"}\` keeps them.`, + "The branch still held the rows the fork copied, so the app schema was rebuilt from the committed migrations without them.", ); } if (start.kind === "introspect") { From 90680756991f05136fedb18b8f3394d04f305a3f Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:30:57 +0100 Subject: [PATCH 265/317] fix(appkit): require a verifying TLS mode for CLI connections to the branch An unset PGSSLMODE in the command's env let createLakebasePool fall back to the process's PGSSLMODE, so a `prefer` exported in the shell won over require. The branch pool now always passes require when PGSSLMODE is unset, and refuses prefer, disable and allow before any API call, naming the variable. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/context.ts | 27 +++++++++- .../database/tooling/tests/context.test.ts | 49 +++++++++++++++++++ 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/context.ts b/packages/appkit/src/database/tooling/context.ts index b417297da..ff25dd478 100644 --- a/packages/appkit/src/database/tooling/context.ts +++ b/packages/appkit/src/database/tooling/context.ts @@ -108,6 +108,29 @@ 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. @@ -117,19 +140,19 @@ async function openBranchPool(ctx: DbContext): Promise { 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; - const sslMode = ctx.env.PGSSLMODE as LakebasePoolConfig["sslMode"]; return createLakebasePool({ host: PGHOST, database: PGDATABASE, endpoint: LAKEBASE_ENDPOINT, user, ...(port ? { port } : {}), - ...(sslMode ? { sslMode } : {}), + sslMode, workspaceClient: ctx.workspace(), // One-shot CLI pools: a small cap, and no lingering idle connections. max: 2, diff --git a/packages/appkit/src/database/tooling/tests/context.test.ts b/packages/appkit/src/database/tooling/tests/context.test.ts index 3b57978aa..60637ebe8 100644 --- a/packages/appkit/src/database/tooling/tests/context.test.ts +++ b/packages/appkit/src/database/tooling/tests/context.test.ts @@ -148,6 +148,55 @@ describe("withBranchPool", () => { expect(createLakebasePool).not.toHaveBeenCalled(); }); + test("verifies the server's certificate: PGSSLMODE unset means require, even when the shell exports another mode", async () => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(BRANCH); + const env = { + PGHOST: HOST, + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: ENDPOINT, + PGUSER: "alice@example.com", + }; + vi.stubEnv("PGSSLMODE", "prefer"); + try { + await withBranchPool(contextFor(env, lakebase.api()), usePool); + await withBranchPool( + contextFor({ ...env, PGSSLMODE: "require" }, lakebase.api()), + usePool, + ); + } finally { + vi.unstubAllEnvs(); + } + + expect(createLakebasePool.mock.calls).toEqual([ + [expect.objectContaining({ sslMode: "require" })], + [expect.objectContaining({ sslMode: "require" })], + ]); + }); + + test.each(["prefer", "disable", "allow"])( + "refuses PGSSLMODE=%s before any API call, naming the variable", + async (mode) => { + const lakebase = new FakeLakebase(); + lakebase.addBranch(BRANCH); + const ctx = contextFor( + { + PGHOST: HOST, + PGDATABASE: "databricks_postgres", + LAKEBASE_ENDPOINT: ENDPOINT, + PGSSLMODE: mode, + }, + lakebase.api(), + ); + + await expect(withBranchPool(ctx, usePool)).rejects.toThrow( + `PGSSLMODE=${mode} does not verify the server's certificate, so it did not connect. Set PGSSLMODE to require, or unset it.`, + ); + expect(lakebase.calls).toEqual([]); + expect(createLakebasePool).not.toHaveBeenCalled(); + }, + ); + test("closes the pool when fn fails, and rethrows fn's error", async () => { const lakebase = new FakeLakebase(); lakebase.addBranch(BRANCH); From 288dbf709d67c6ef19c40206edbcbf7612cf99f9 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:31:27 +0100 Subject: [PATCH 266/317] test(appkit): pin that clean refuses the fork's untouched copy and names init Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/clean-seed.test.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index e08713b1e..5446e505b 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -191,6 +191,32 @@ describe("runClean", () => { }); }); +describe("clean on the fork's untouched copy", () => { + const untouched = + 'Refusing to clean: dev-alice-3f9a2c still holds the rows the fork copied into schema "app", which "app-sp" still owns, so your role cannot drop it. Run `appkit db init` to take it over and rebuild it from the committed migrations.'; + + test("runClean refuses before dropping anything, and says to run init", async () => { + const ctx = fakeContext({ + root: tempApp({ "config/database/schema.ts": schemaFile("app") }), + }); + writableEnvBranch.mockResolvedValue(devBranch); + const { statements } = recordingPool({ schemaOwner: "app-sp" }); + + await expect(runClean(ctx)).rejects.toThrow(untouched); + expect(statements.some((text) => text.includes("DROP"))).toBe(false); + }); + + test("previewClean refuses too, so the CLI does not ask first", async () => { + const ctx = fakeContext({ + root: tempApp({ "config/database/schema.ts": schemaFile("app") }), + }); + writableEnvBranch.mockResolvedValue(devBranch); + recordingPool({ schemaOwner: "app-sp" }); + + await expect(previewClean(ctx)).rejects.toThrow(untouched); + }); +}); + describe("previewClean", () => { test("reads the dependents without opening a transaction or dropping anything", async () => { const ctx = fakeContext({ From 2c5916717f3685040bba4349330d1e3e80a9ce56 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:32:05 +0100 Subject: [PATCH 267/317] fix(appkit): refuse appkit db clean on the fork's untouched copy, naming init Another role owns that schema, so the drop failed with Postgres's raw "must be owner". clean and its preview now refuse first and say that init takes the copy over and rebuilds it. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/clean.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/appkit/src/database/tooling/clean.ts b/packages/appkit/src/database/tooling/clean.ts index 273b4aaa8..db7713335 100644 --- a/packages/appkit/src/database/tooling/clean.ts +++ b/packages/appkit/src/database/tooling/clean.ts @@ -2,6 +2,7 @@ import type { PoolClient } from "pg"; import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; 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"; @@ -231,10 +232,30 @@ async function cleanTarget(ctx: DbContext) { 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 "${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( @@ -264,6 +285,7 @@ export async function cleanHolding( 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); From e995a482d2de00ef1d1809e0e171e122bf50c3f5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:32:24 +0100 Subject: [PATCH 268/317] fix(appkit): escape deployed and catalog text verify prints Tags from the deployed journal, the snapshot path and API texts in its reasons, the Apps API's binding and status fields, and the schema owner in the fork-copy refusal now go through shown(), so a control character in them cannot rewrite the terminal. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 35 +++++++++++++++++++ .../appkit/src/database/tooling/verify.ts | 34 ++++++++++-------- 2 files changed, 54 insertions(+), 15 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 5a0579353..63998b028 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -345,6 +345,19 @@ describe("runVerify", () => { }); }); + test("the owner the catalog reports for a fork's copy is printed with control characters escaped", async () => { + const ctx = app(two); + branch({ + columns: { notes: ["id", "body"] }, + recorded: recordedAs(ctx, two), + schemaOwner: "deployed\nsp", + }); + + expect(await runVerify(ctx)).toMatchObject({ + forkCopy: expect.stringContaining('which "deployed\\u000asp" still owns'), + }); + }); + test("a fork's copy whose rebuild did not finish is reported as one, and its tag is not an unknown migration", async () => { const ctx = app(two); branch({ @@ -1016,6 +1029,28 @@ describe("runVerify --deployed", () => { }); }); + test("tags and texts from the deployed journal and the apps API are printed with control characters escaped", async () => { + const migrations = [{ tag: "0000_migration", when: 1000 }]; + const { ctx } = deployedApp({ + migrations, + deployedJournal: [...migrations, { tag: "0001_\u001b[2Jx", when: 2000 }], + app: runningApp({ + app_status: { state: "CRASHED", message: "boom\nfake: line" }, + }), + }); + + const problems = await deployProblems(ctx); + expect(problems).toContain( + "app my-app's active deployment has 0001_\\u001b[2Jx, which this checkout does not commit: pull it, then run verify again", + ); + expect(problems).toContain( + "app my-app is crashed: boom\\u000afake: line. `databricks apps logs` shows why; a migration that fails stops the app on start", + ); + expect( + Array.from(problems.join("")).some((char) => char.charCodeAt(0) < 0x20), + ).toBe(false); + }); + test.each([ [ "lists a tag twice", diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 9790958b3..e5eb848b4 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -23,6 +23,7 @@ import { withBranchPool, } from "./context"; import { resolveEnvBranch, takesWrites } from "./guard"; +import { shown } from "./introspect/render"; import { requireSchemaFile } from "./migrate"; import { FORK_COPY_TAG, @@ -141,14 +142,16 @@ async function verifyLocal(ctx: DbContext): Promise { await diagnoseSchema(rawOn(client), schema); // Only init forks a copy, onto the developer's own branch. Elsewhere, // e.g. production, another owner is the normal state. - const forkCopy = takesWrites(env.kind) - ? (forkCopyRefusal( + const refusal = takesWrites(env.kind) + ? forkCopyRefusal( branch, schema.$schemaName, await readSchemaState(client, schema.$schemaName), "migrate", - ) ?? null) - : null; + ) + : undefined; + // It names the schema's owner as the catalog reports it. + const forkCopy = refusal ? shown(refusal) : null; const drift = await readMigrationDrift(client, { migrationsFolder: migrationsFolder(ctx.root), schemaName: schema.$schemaName, @@ -222,7 +225,7 @@ async function readApp( return null; } const message = error instanceof Error ? error.message : String(error); - throw new Error(`Could not read app ${name}: ${message}`, { + throw new Error(`Could not read app ${name}: ${shown(message)}`, { cause: error, }); } @@ -412,7 +415,7 @@ async function readDeployedMigrations( const them = unknown.length === 1 ? "it" : "them"; return { evidence: "unavailable", - reason: `the deployment has ${unknown.join(", ")}, and this checkout commits none in config/database/migrations next to databricks.yml: pull ${them}, then run verify again`, + reason: `the deployment has ${unknown.map(shown).join(", ")}, and this checkout commits none in config/database/migrations next to databricks.yml: pull ${them}, then run verify again`, }; } const deployedByTag = new Map(deployed.map((entry) => [entry.tag, entry])); @@ -457,9 +460,10 @@ async function readDeployedMigrations( ? { evidence: "verified" } : { evidence: "differs", missing, changed, lineEndings, unknown }; } catch (error) { + // The message can carry the snapshot's path and tags, or an API's text. return { evidence: "unavailable", - reason: error instanceof Error ? error.message : String(error), + reason: shown(error instanceof Error ? error.message : String(error)), }; } } @@ -503,7 +507,7 @@ function migrationsProblems( if (unknown.length > 0) { const them = unknown.length === 1 ? "it" : "them"; problems.push( - `app ${name}'s active deployment has ${unknown.join(", ")}, which this checkout does not commit: pull ${them}, then run verify again`, + `app ${name}'s active deployment has ${unknown.map(shown).join(", ")}, which this checkout does not commit: pull ${them}, then run verify again`, ); } return problems; @@ -530,19 +534,19 @@ function bindingProblems( if (!binding) { return [ bound.length > 0 - ? `app ${name} uses branch ${bound.map((postgres) => postgres.branch).join(", ")}, not ${branch} from ${source}: ${DEPLOY} applies ${source}` + ? `app ${name} uses branch ${bound.map((postgres) => shown(postgres.branch ?? "(none)")).join(", ")}, not ${branch} from ${source}: ${DEPLOY} applies ${source}` : `app ${name} has no postgres resource: ${DEPLOY} adds the one ${file} declares`, ]; } const problems: string[] = []; if (database && binding.database !== database) { problems.push( - `app ${name} uses database ${binding.database ?? "(none)"}, not ${database} from ${source}: ${DEPLOY} applies ${source}`, + `app ${name} uses database ${shown(binding.database ?? "(none)")}, not ${database} from ${source}: ${DEPLOY} applies ${source}`, ); } if (binding.permission !== POSTGRES_PERMISSION) { problems.push( - `app ${name}'s postgres resource has permission ${binding.permission ?? "(none)"}, but the app needs ${POSTGRES_PERMISSION} to create its schema: set it in ${file}, then run ${DEPLOY}`, + `app ${name}'s postgres resource has permission ${shown(binding.permission ?? "(none)")}, but the app needs ${POSTGRES_PERMISSION} to create its schema: set it in ${file}, then run ${DEPLOY}`, ); } return problems; @@ -551,7 +555,7 @@ function bindingProblems( /** ": " for an API status message, without its final period; "" without one. */ function detail(message: string | undefined): string { const text = message?.trim().replace(/\.+$/, ""); - return text ? `: ${text}` : ""; + return text ? `: ${shown(text)}` : ""; } /** @@ -585,13 +589,13 @@ function runningProblems(app: DeployedApp, name: string): string[] { } if (compute?.state && compute.state !== "ACTIVE") { return [ - `app ${name}'s compute is ${compute.state.toLowerCase()}${detail(compute.message)}`, + `app ${name}'s compute is ${shown(compute.state.toLowerCase())}${detail(compute.message)}`, ]; } const status = app.app_status; if (status?.state === "RUNNING") return []; return [ - `app ${name} is ${status?.state?.toLowerCase() ?? "not running"}${detail(status?.message)}. ${LOGS} shows why; a migration that fails stops the app on start`, + `app ${name} is ${shown(status?.state?.toLowerCase() ?? "not running")}${detail(status?.message)}. ${LOGS} shows why; a migration that fails stops the app on start`, ]; } @@ -827,7 +831,7 @@ async function verifyDeploy( ]); if (roles && !roles.some((role) => role.status?.postgres_role === sp)) { problems.push( - `the app's service principal ${sp} has no Postgres role on ${branchId}: ${DEPLOY} creates it from the app's postgres resource`, + `the app's service principal ${shown(sp ?? "")} has no Postgres role on ${branchId}: ${DEPLOY} creates it from the app's postgres resource`, ); } // Without an active deployment, runningProblems already says why; the From 02971105a8ac433f9d92796366b5168dc0caafc0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:32:50 +0100 Subject: [PATCH 269/317] test(appkit): pin that an invalid APPKIT_DB_SESSION is refused instead of replaced Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/tests/init.test.ts | 11 +++++++++++ .../appkit/src/database/tooling/tests/targets.test.ts | 8 +++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 8b3b0e8ae..8459348af 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -708,6 +708,17 @@ describe("runInit — session branch", () => { expect(untouched.calls).toEqual([]); }); + test("an invalid APPKIT_DB_SESSION is refused before any API call, and .env keeps it", async () => { + const lakebase = project(); + const ctx = appOn(lakebase, { APPKIT_DB_SESSION: "My-Session" }); + + await expect(init(ctx, { mode: "session" })).rejects.toThrow( + 'Invalid APPKIT_DB_SESSION "My-Session": use 1-48 lowercase letters or digits.', + ); + expect(lakebase.calls).toEqual([]); + expect(envFile(ctx.root).APPKIT_DB_SESSION).toBe("My-Session"); + }); + test("the session id is in .env before the branch is created, so a failed run's rerun reuses it", async () => { const lakebase = project(); lakebase.createBranchError = new Error("network down"); diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index c06ae1fe9..0f2465719 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -79,7 +79,6 @@ describe("readLocalTarget", () => { LAKEBASE_ENDPOINT: "your_postgres_endpointPath", PGHOST: "your_postgres_host", PGDATABASE: "your_postgres_databaseName", - APPKIT_DB_SESSION: "NOT VALID", }), ).toEqual({ project: null, @@ -88,6 +87,13 @@ describe("readLocalTarget", () => { session: null, }); }); + + test("an APPKIT_DB_SESSION set to an invalid id is refused, not read as unset", () => { + expect(() => readLocalTarget({ APPKIT_DB_SESSION: "NOT VALID" })).toThrow( + 'Invalid APPKIT_DB_SESSION "NOT VALID": use 1-48 lowercase letters or digits.', + ); + expect(readLocalTarget({ APPKIT_DB_SESSION: "" }).session).toBeNull(); + }); }); describe("readDeployBoundary", () => { From b23617c6034f990478c845f3bf7050bbd7b25e74 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:32:50 +0100 Subject: [PATCH 270/317] refactor(appkit): derive each introspect omission's four outputs from one record renderSchemaSource records what schema.ts leaves out as one Omission and derives its // appkit: skipped comment, Skipped line, Unexpressed entry and warning in one function. It checks the primary key before the columns, so the per-table buffers that waited on that check are gone. The render, introspect and roundtrip tests pass unchanged. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/introspect/render.ts | 342 ++++++++++-------- 1 file changed, 196 insertions(+), 146 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/render.ts b/packages/appkit/src/database/tooling/introspect/render.ts index ec86e2f94..f1cb85607 100644 --- a/packages/appkit/src/database/tooling/introspect/render.ts +++ b/packages/appkit/src/database/tooling/introspect/render.ts @@ -330,21 +330,38 @@ function importLine(names: readonly string[], source: string): string { return `import {\n${names.map((name) => ` ${name},`).join("\n")}\n} from ${q(source)};`; } -function makeSkip( - table: string, - column: string | undefined, - reason: string, -): Skip { - return { - table: shown(table), - ...(column === undefined ? {} : { column: shown(column) }), - reason: shown(reason), - }; -} - -function skipComment(skip: Skip): string { - return `// appkit: skipped ${skip.column ? `column "${skip.column}"` : `table "${skip.table}"`}: ${skip.reason}`; -} +/** 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()"]); @@ -378,11 +395,95 @@ export function renderSchemaSource( const tableComments: string[] = []; const qualified = (table: string, column?: string) => `${schemaName}.${table}${column ? `.${column}` : ""}`; - const skipTable = (table: string, reason: string) => { - const skip = makeSkip(table, undefined, reason); - skipped.push(skip); - unexpressed.push({ kind: "table", name: table, reason }); - tableComments.push(skipComment(skip)); + /** + * 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. @@ -451,70 +552,52 @@ export function renderSchemaSource( // 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]; - const tableSkips: Skip[] = []; - const tableWarnings: string[] = []; - const tableApproximated: string[] = []; - const tableRenamed: string[] = []; - const columnReasons = new Map(); + 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]), ); - const tableUnexpressed: Unexpressed[] = []; for (const unique of table.unique.filter((u) => u.columns.length > 1)) { - const reason = `unique constraint (${list(unique.columns)}) spans several columns, which is not supported`; - const skip = makeSkip(table.name, undefined, reason); - tableSkips.push(skip); - tableUnexpressed.push({ - kind: "constraint", - name: table.name, - member: unique.name, - reason, - }); - plan.comments.push(`// appkit: skipped ${skip.reason}`); + 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 skipColumn = (reason: string) => { - const skip = makeSkip(table.name, column.name, reason); - tableSkips.push(skip); - tableUnexpressed.push({ - kind: "column", - name: table.name, - member: column.name, - reason, - }); - columnReasons.set(column.name, reason); - plan.body.push(skipComment(skip)); + const isPrimaryKey = column.name === pk; + const base = columnBase(column, isPrimaryKey); + if (typeof base === "string") { const generatesValue = column.identity !== "" || column.generated || !!column.defaultExpr; - if (column.notNull && !generatesValue) { - tableWarnings.push( - `${qualified(table.name, column.name)} is NOT NULL with no default but is not in schema.ts (${reason}). Inserts through ${client(table.name)} will fail until it gets a default, becomes nullable, or is dropped.`, - ); - } - }; - - if (isReservedColumnName(column.name)) { - skipColumn(`the name "${column.name}" is reserved by AppKit`); - continue; - } - if (column.generated) { - skipColumn("generated columns are not supported"); - continue; - } - const base = baseType(column, schemaName); - if (typeof base === "string") { - skipColumn(base); - continue; - } - const isPrimaryKey = column.name === pk; - if (column.identity !== "" && !isPrimaryKey) { - skipColumn( - "identity columns other than the primary key are not supported", + omit( + { + kind: "column", + table: table.name, + column: column.name, + reason: base, + failsInserts: column.notNull && !generatesValue, + }, + plan.body, ); continue; } @@ -527,7 +610,7 @@ export function renderSchemaSource( comments: [], }; if (base.approximation) { - tableApproximated.push( + approximated.push( `${qualified(table.name, column.name)}: ${base.approximation}`, ); } @@ -535,10 +618,10 @@ export function renderSchemaSource( const migrationsUnique = pgName(`${table.name}_${column.name}_unique`); if (columnPlan.isUnique && unique) { if (unique.name !== migrationsUnique) { - tableRenamed.push(`${unique.name} (${migrationsUnique})`); + renamed.push(`${unique.name} (${migrationsUnique})`); } if (unique.deferrable) { - tableApproximated.push( + approximated.push( `${qualified(table.name, column.name)}: the unique constraint is declared without DEFERRABLE`, ); } @@ -554,7 +637,7 @@ export function renderSchemaSource( const serverKey = SERVER_KEYS[base.storage]; columnPlan.base = serverKey.base; if (column.identity !== "d") { - tableApproximated.push( + 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`, ); } @@ -562,7 +645,7 @@ export function renderSchemaSource( ? sequenceDifferences(column.sequence, serverKey.max) : null; if (differences) { - tableApproximated.push( + approximated.push( `${qualified(table.name, column.name)}: the key's sequence has ${differences.has}; ${serverKey.base.call} declares the defaults (${differences.declared})`, ); } @@ -575,39 +658,25 @@ export function renderSchemaSource( if ("call" in parsed) { columnPlan.defaultCall = parsed.call; } else { - const skip = makeSkip(table.name, column.name, parsed.skip); - tableSkips.push(skip); - tableUnexpressed.push({ - kind: "default", - name: table.name, - member: column.name, - reason: parsed.skip, - }); - columnPlan.comments.push(`// appkit: skipped ${skip.reason}`); - if (column.notNull) { - tableWarnings.push( - `${qualified(table.name, column.name)}: its ${parsed.skip.replace(/ is not supported$/, "")} is not in schema.ts, so ${client(table.name)} requires a value for it on insert.`, - ); - } + 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 (!plan.columns.some((c) => c.isPrimaryKey)) { - plans.delete(table.name); - skipTable( - table.name, - `its primary key column "${pk}" cannot be expressed (${columnReasons.get(pk as string) ?? "unsupported"})`, - ); - continue; - } - skipped.push(...tableSkips); - unexpressed.push(...tableUnexpressed); - warnings.push(...tableWarnings); if (table.partitioned) { - tableApproximated.push( + approximated.push( `${qualified(table.name)}: a partitioned table is declared as a plain table`, ); } @@ -626,8 +695,6 @@ export function renderSchemaSource( ); } } - approximated.push(...tableApproximated); - renamed.push(...tableRenamed); } // 3. Foreign keys the builder can express; the rest stay plain columns. @@ -719,36 +786,26 @@ export function renderSchemaSource( ); const problem = fkProblem(plan, foreignKey, source, targets); if (problem) { - const reason = `foreign key to ${foreignKey.table}(${list(foreignKey.refColumns)}) is not kept: ${problem}`; // Migrations name it after its column; a schema.ts that declared it gave it that name. - const constraintNames = [foreignKey.name]; + const names = [foreignKey.name]; if (foreignKey.columns.length === 1) { - constraintNames.push( + names.push( pgName( `${plan.table.name}_${foreignKey.columns[0]}_${foreignKey.table}_${foreignKey.refColumns[0]}_fk`, ), ); } - for (const member of new Set(constraintNames)) { - unexpressed.push({ + omit( + { kind: "constraint", - name: plan.table.name, - member, - reason, - }); - } - // A skipped column already carries its own comment. - if (source || foreignKey.columns.length > 1) { - const skip = makeSkip( - plan.table.name, - foreignKey.columns.join(", "), - reason, - ); - skipped.push(skip); - (source?.comments ?? plan.comments).push( - `// appkit: skipped ${skip.reason}`, - ); - } + 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; @@ -762,26 +819,19 @@ export function renderSchemaSource( TYPED_DEFAULTS.has(sourceColumn.defaultCall) ) { // fk() takes no defaultRandom()/defaultNow(); the key matters more than the default. - const reason = `default ${sourceColumn.column.defaultExpr} is not supported on a foreign key column`; - const skip = makeSkip( - plan.table.name, - sourceColumn.column.name, - reason, + 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, ); - skipped.push(skip); - unexpressed.push({ - kind: "default", - name: plan.table.name, - member: sourceColumn.column.name, - reason, - }); - sourceColumn.comments.push(`// appkit: skipped ${skip.reason}`); delete sourceColumn.defaultCall; - if (sourceColumn.column.notNull) { - warnings.push( - `${qualified(plan.table.name, sourceColumn.column.name)}: its default ${sourceColumn.column.defaultExpr} is not in schema.ts, so ${client(plan.table.name)} requires a value for it on insert.`, - ); - } } for (const [flag, what] of [ [foreignKey.deferrable, "DEFERRABLE"], @@ -836,7 +886,7 @@ export function renderSchemaSource( ), ); for (const name of undeclaredEnums) { - unexpressed.push({ + omit({ kind: "type", name, reason: "only what schema.ts leaves out uses it", From 571075673caa1c562192f88a8a1813f4c68625ab Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:33:11 +0100 Subject: [PATCH 271/317] fix(appkit): refuse an invalid APPKIT_DB_SESSION instead of replacing it .env read an invalid id as unset, so init generated a new one and overwrote the hand-set value. Every command now refuses it with naming.ts's message. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/naming.ts | 17 +++++++++++------ packages/appkit/src/database/tooling/targets.ts | 15 +++++++++------ 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/packages/appkit/src/database/tooling/naming.ts b/packages/appkit/src/database/tooling/naming.ts index 22993d6db..9915d20ac 100644 --- a/packages/appkit/src/database/tooling/naming.ts +++ b/packages/appkit/src/database/tooling/naming.ts @@ -49,17 +49,22 @@ export function isValidSessionId(sessionId: string): boolean { return SESSION_ID.test(sessionId); } -/** - * session--. The id lives in this checkout's .env; the - * hash makes a copied .env name a branch only its creator passes the guard on. - */ -export function sessionBranchId(userName: string, sessionId: string): string { +/** The session id as given; an invalid one throws. */ +export function parseSessionId(sessionId: string): string { if (!isValidSessionId(sessionId)) { throw new Error( `Invalid APPKIT_DB_SESSION ${JSON.stringify(sessionId)}: use 1-${SESSION_ID_LENGTH} lowercase letters or digits.`, ); } - return `${SESSION_PREFIX}${userHash(userName)}-${sessionId}`; + return sessionId; +} + +/** + * session--. The id lives in this checkout's .env; the + * hash makes a copied .env name a branch only its creator passes the guard on. + */ +export function sessionBranchId(userName: string, sessionId: string): string { + return `${SESSION_PREFIX}${userHash(userName)}-${parseSessionId(sessionId)}`; } /** Whether a branch id is one of this user's session branches, whatever its session id. */ diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index d36019021..b3ae251b8 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -3,7 +3,7 @@ import path from "node:path"; import yaml from "js-yaml"; -import { isValidSessionId } from "./naming"; +import { parseSessionId } from "./naming"; export type BranchMode = "dev" | "session"; @@ -55,7 +55,11 @@ export function parseProject(value: string | undefined): string | null { return PROJECT_ID.test(id) ? `projects/${id}` : null; } -/** What `.env` says about the local branch. Unparseable values (template placeholders) read as null. */ +/** + * What `.env` says about the local branch. Unparseable values (template + * placeholders) read as null. APPKIT_DB_SESSION has no placeholder, so an + * invalid one throws instead of being replaced. + */ export interface LocalTarget { /** LAKEBASE_PROJECT, normalized to "projects/". */ readonly project: string | null; @@ -66,10 +70,9 @@ export interface LocalTarget { export function readLocalTarget(env: NodeJS.ProcessEnv): LocalTarget { const endpoint = parseResourceName(env.LAKEBASE_ENDPOINT)?.endpoint ?? null; - const session = - env.APPKIT_DB_SESSION && isValidSessionId(env.APPKIT_DB_SESSION) - ? env.APPKIT_DB_SESSION - : null; + const session = env.APPKIT_DB_SESSION + ? parseSessionId(env.APPKIT_DB_SESSION) + : null; return { project: parseProject(env.LAKEBASE_PROJECT), endpoint, From 2c23e6a3f070a514ba721bae8e4113191bf89fbd Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:34:47 +0100 Subject: [PATCH 272/317] test(appkit): pin that a plain init resumes a stopped --session run A failed session run also names --session in its rerun advice. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 8459348af..f6b932f0f 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -806,6 +806,54 @@ describe("runInit — session branch", () => { expect(afterFork.branches.has(DEV)).toBe(false); }); + test("a --session run that stopped after the fork is resumed by a plain init, from a .env that still points elsewhere", async () => { + schemaOwner = USER; + const lakebase = project(); + lakebase.addBranch(session("k2x9q0ab"), { + expire_time: "2099-01-01T00:00:00Z", + }); + const ctx = appOn(lakebase, { APPKIT_DB_SESSION: "k2x9q0ab" }); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report).toMatchObject({ + mode: "session", + branch: session("k2x9q0ab"), + created: false, + }); + expect(lakebase.branches.has(DEV)).toBe(false); + }); + + test("a .env that points at your dev branch stays on it, even with a session id whose branch exists", async () => { + schemaOwner = USER; + const lakebase = project(); + lakebase.addBranch(DEV); + lakebase.addBranch(session("k2x9q0ab"), { + expire_time: "2099-01-01T00:00:00Z", + }); + const ctx = appOn(lakebase, { + APPKIT_DB_SESSION: "k2x9q0ab", + LAKEBASE_ENDPOINT: `${DEV}/endpoints/primary`, + }); + + const { report } = await init(ctx, { schema: "none" }); + + expect(report).toMatchObject({ mode: "dev", branch: DEV }); + }); + + test("a failed session run says to rerun with --session, since a plain rerun can pick the dev branch", async () => { + const lakebase = project(); + lakebase.createBranchError = forbidden(); + const ctx = appOn(lakebase); + + await expect(init(ctx, { mode: "session" })).rejects.toThrow( + `needs CAN MANAGE on ${P}. Ask a project owner for it, then rerun \`appkit db init --session\`.`, + ); + await expect(init(ctx)).rejects.toThrow( + `needs CAN MANAGE on ${P}. Ask a project owner for it, then rerun \`appkit db init\`.`, + ); + }); + test("an expired session branch, or a 409 for one that is gone, gets a fresh session id", async () => { const lakebase = project(); lakebase.addBranch(session("k2x9q0ab"), { From 4ed3c28ce7a65e86c2c23e5de6919b1d55cd5fc0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:35:36 +0100 Subject: [PATCH 273/317] fix(appkit): resume a stopped --session run from a plain init, and name --session in its advice A --session run writes APPKIT_DB_SESSION before the fork and points .env at the branch last. When it stopped in between, the next plain init went to the dev branch. It now picks the session when .env does not point at your dev branch and the session's branch exists, and a session run's rerun advice says `appkit db init --session`. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 398 ++++++++++--------- 1 file changed, 215 insertions(+), 183 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index dfea3ec0e..e1c997202 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -194,16 +194,41 @@ function scopeToProject( /** * 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. Dev - * otherwise. + * 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. */ -function defaultMode(local: LocalTarget, userName: string): BranchMode { +async function defaultMode( + ctx: DbContext, + project: string, + local: LocalTarget, + userName: string, +): Promise { + if (!local.session) return "dev"; const branch = parseResourceName(local.endpoint ?? undefined)?.branch; - return local.session && - branch && - isUsersSessionBranchId(userName, resourceId(branch)) - ? "session" - : "dev"; + 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 { @@ -618,194 +643,201 @@ async function initHolding( configured.deploy, ); const identity = await currentIdentity(ctx); - const mode = options.mode ?? defaultMode(local, identity.userName); + 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."); } - const before = readEnvValues(envFile); - - const found = await findOrCreateBranch(ctx, { - project, - mode, - identity, - session: local.session, - ttl, - boundary: readDeployBoundary(ctx.root), - envFile, - deployBranch: deploy?.branch ?? null, - 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 = await resolveDatabase(ctx, branch.name, local, deploy); - - 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`, + try { + const before = readEnvValues(envFile); + + const found = await findOrCreateBranch(ctx, { + project, + mode, + identity, + session: local.session, + ttl, + boundary: readDeployBoundary(ctx.root), + envFile, + deployBranch: deploy?.branch ?? null, + 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, ); - } - onStep(`Pointing .env at ${resourceId(branch.name)}, database ${database}`); - updateEnvFile(envFile, values); - const branchCtx: DbContext = { ...ctx, env: { ...ctx.env, ...values } }; - - const base = { - mode, - branch: branch.name, - created: found.created, - ...(found.sourceBranch ? { sourceBranch: found.sourceBranch } : {}), - expireTime: branch.status?.expire_time ?? null, - endpoint: endpoint.name, - endpointCreated, - host, - 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 database = await resolveDatabase(ctx, branch.name, local, deploy); + + 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)), }; - } - 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 }, + 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 ${database}`); + updateEnvFile(envFile, values); + const branchCtx: DbContext = { ...ctx, env: { ...ctx.env, ...values } }; + + const base = { + mode, + branch: branch.name, + created: found.created, + ...(found.sourceBranch ? { sourceBranch: found.sourceBranch } : {}), + expireTime: branch.status?.expire_time ?? null, + endpoint: endpoint.name, + endpointCreated, + host, + database, + user: identity.userName, + role: { name: role.name, action }, + envFile, }; - } - 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, - ); + if (request.kind === "none") { + return { + ...base, + handedOff: null, + keptCopy: null, + installed: null, + start: { kind: "none" }, + }; + } + const { lock, requested } = request; - 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 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 handedOff = plan.handOff - ? await handOffAppSchema(branchCtx, { - branch: branch.name, - database, + const introspect = (recordAsApplied: boolean) => { + onStep(`Writing schema.ts from schema ${schemaName} ${on}`); + return introspectForInit(branchCtx, lock, { + interactive, schemaName, - developer: role, - roles, - onStep, - }) - : null; - if (plan.keepsCopy) { - await onBranch((client) => untagForkCopy(client, schemaName)); - } + recordAsApplied, + }); + }; + let introspected: IntrospectReport | null = null; + if (plan.kind === "introspect" && plan.rebuild) { + introspected = await introspect(false); + } - 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 }), + 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 }; }; - } else if (plan.kind === "introspect") { - start = { - kind: "introspect", - introspect: introspected ?? (await introspect(true)), - rebuilt: plan.rebuild ? await rebuildSchema() : null, + 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.sourceBranch ?? branch.status?.source_branch ?? null, + ), + installed, + start, }; - } else { - start = { kind: "clean", ...(await rebuildSchema()) }; + } catch (error) { + throw mode === "session" ? withSessionRerun(error) : error; } - - return { - ...base, - handedOff, - keptCopy: keptCopyOf( - state, - plan, - found.sourceBranch ?? branch.status?.source_branch ?? null, - ), - installed, - start, - }; } function keptCopyOf( From bf6ee06ab9015b9448c0fd40c94ed0a741b342d0 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:36:38 +0100 Subject: [PATCH 274/317] test(appkit): pin init's check of the bound database before the fork, and its win over .env Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/init.test.ts | 42 ++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index f6b932f0f..2c234072b 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1573,7 +1573,7 @@ describe("runInit — .env", () => { expect(fs.statSync(path.join(root, ".env")).mode & 0o777).toBe(0o600); }); - test("a database databricks.yml binds that the branch does not have is refused, naming both, before .env is written", async () => { + test("a database databricks.yml binds that the source branch does not have is refused before the fork, naming both", async () => { const lakebase = project(); const root = tempApp({ "databricks.yml": databricksYml( @@ -1583,6 +1583,30 @@ describe("runInit — .env", () => { }); const ctx = fakeContext({ root, userName: USER, api: lakebase.api() }); + await expect(init(ctx, { schema: "none" })).rejects.toThrow( + `Database analytics, which databricks.yml binds, is not on production, the branch ${devBranchId(USER)} would fork from, so init created nothing. Create it there (databricks postgres create-database ${PRODUCTION} --database-id analytics), or bind a database the project's branches have, then rerun \`appkit db init\`.`, + ); + expect(lakebase.calls).toContain( + `getDatabase ${PRODUCTION}/databases/analytics`, + ); + expect(lakebase.calls.some((call) => call.startsWith("createBranch"))).toBe( + false, + ); + expect(fs.existsSync(path.join(root, ".env"))).toBe(false); + }); + + test("a reused branch without the database databricks.yml binds is refused, naming both, before .env is written", async () => { + const lakebase = project(); + lakebase.addBranch(DEV); + lakebase.addRole(DEV, "alice", USER, ["DATABRICKS_SUPERUSER"]); + const root = tempApp({ + "databricks.yml": databricksYml( + PRODUCTION, + `${PRODUCTION}/databases/analytics`, + ), + }); + const ctx = fakeContext({ root, userName: USER, api: lakebase.api() }); + await expect(init(ctx, { schema: "none" })).rejects.toThrow( `Database analytics, which databricks.yml binds, is not on ${devBranchId(USER)}. Create it there (databricks postgres create-database ${DEV} --database-id analytics), or bind a database the project's branches have, then rerun \`appkit db init\`.`, ); @@ -1590,6 +1614,22 @@ describe("runInit — .env", () => { expect(fs.existsSync(path.join(root, ".env"))).toBe(false); }); + test("the database databricks.yml binds wins over .env's PGDATABASE, and init says so when they differ", async () => { + const lakebase = project(); + const ctx = appOn(lakebase, { PGDATABASE: "scratch" }); + + const { report, warnings } = await init(ctx, { schema: "none" }); + + expect(report.database).toBe("databricks_postgres"); + expect(envFile(ctx.root).PGDATABASE).toBe("databricks_postgres"); + expect(warnings).toEqual([ + "Setting PGDATABASE=databricks_postgres in .env: it was scratch, and databricks.yml binds databricks_postgres", + ]); + + const same = await init(appOn(project()), { schema: "none" }); + expect(same.warnings).toEqual([]); + }); + test("the profile init authenticated with wins over the host", async () => { const lakebase = project(); const root = tempApp(); From b760c8763f3f089049f2c8b1706b6978481ac111 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:38:51 +0100 Subject: [PATCH 275/317] fix(appkit): check the bound database on the source before the fork, and let it win over .env init read the database databricks.yml binds only after the fork, so a missing one left a new branch with copied rows behind, and a PGDATABASE already in .env skipped the check. The create path now reads the binding on the source branch before createBranch. A reused branch is still checked after. The bound database replaces a different PGDATABASE, and init says so. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 82 ++++++++++++++----- .../src/database/tooling/tests/fakes.ts | 2 + .../src/database/tooling/tests/init.test.ts | 2 +- 3 files changed, 63 insertions(+), 23 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index e1c997202..b376f5b3d 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -246,17 +246,23 @@ interface BranchRequest { readonly ttl: { readonly api: string; readonly label: string }; readonly boundary: DeployBoundary; readonly envFile: string; - readonly deployBranch: string | null; + readonly deploy: DeployTarget | null; readonly onStep: (message: string) => void; } -interface FoundBranch { +type FoundBranch = { readonly branch: LakebaseBranch; - /** Forked by this run. */ - readonly created: boolean; - readonly sourceBranch?: string; 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, @@ -341,12 +347,19 @@ async function findOrCreateBranch( const branches = await api.listBranches(project); const deployed = branches.find( - (b) => b.name === request.deployBranch && !isGone(b), + (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}`}`, @@ -362,6 +375,7 @@ async function findOrCreateBranch( branch: branch?.name ? branch : { name }, created: true, sourceBranch: parent.name, + boundDatabase, session, }; } catch (error) { @@ -505,25 +519,26 @@ async function ensureDeveloperRole( } /** - * The Postgres database .env names: the one it already names, else the one - * databricks.yml binds, read on the branch (a fork inherits its parent's - * databases), else the project's default database. A bound database the branch - * lacks is refused: pointing .env at the default one would run the app on a - * database its deploy does not use. + * 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 resolveDatabase( +async function readBoundDatabase( ctx: DbContext, branch: string, - local: LocalTarget, deploy: DeployTarget | null, -): Promise { - if (local.database) return local.database; - if (!deploy?.database) return DEFAULT_DATABASE; + 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 ${resourceId(branch)}. 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\`.`, + `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) { @@ -534,6 +549,21 @@ async function resolveDatabase( 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=${bound} in .env: it was ${local.database}, and databricks.yml binds ${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. */ @@ -659,7 +689,7 @@ async function initHolding( ttl, boundary: readDeployBoundary(ctx.root), envFile, - deployBranch: deploy?.branch ?? null, + deploy, onStep, }); const { branch } = found; @@ -677,7 +707,13 @@ async function initHolding( roles, onStep, ); - const database = await resolveDatabase(ctx, branch.name, local, deploy); + const database = chooseDatabase( + found.created + ? found.boundDatabase + : await readBoundDatabase(ctx, branch.name, deploy), + local, + onWarning, + ); const values: Record = { LAKEBASE_PROJECT: project, @@ -705,7 +741,7 @@ async function initHolding( mode, branch: branch.name, created: found.created, - ...(found.sourceBranch ? { sourceBranch: found.sourceBranch } : {}), + ...(found.created ? { sourceBranch: found.sourceBranch } : {}), expireTime: branch.status?.expire_time ?? null, endpoint: endpoint.name, endpointCreated, @@ -830,7 +866,9 @@ async function initHolding( keptCopy: keptCopyOf( state, plan, - found.sourceBranch ?? branch.status?.source_branch ?? null, + found.created + ? found.sourceBranch + : (branch.status?.source_branch ?? null), ), installed, start, diff --git a/packages/appkit/src/database/tooling/tests/fakes.ts b/packages/appkit/src/database/tooling/tests/fakes.ts index 23999e80a..ce005c2b9 100644 --- a/packages/appkit/src/database/tooling/tests/fakes.ts +++ b/packages/appkit/src/database/tooling/tests/fakes.ts @@ -34,6 +34,8 @@ export class FakeLakebase { this.branches.set(name, branch); this.endpoints.set(name, [this.endpoint(name, "primary")]); this.roles.set(name, []); + // Every Lakebase branch has it. + this.addDatabase(name, "databricks-postgres", "databricks_postgres"); return branch; } diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 2c234072b..b4cc2c25c 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1568,7 +1568,7 @@ describe("runInit — .env", () => { DATABRICKS_HOST: "https://real.cloud.databricks.com", }); expect(lakebase.calls).toContain( - `getDatabase ${DEV}/databases/databricks-postgres`, + `getDatabase ${PRODUCTION}/databases/databricks-postgres`, ); expect(fs.statSync(path.join(root, ".env")).mode & 0o777).toBe(0o600); }); From 386fd898e895fddac810f27b11a4e84f32143970 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:42:01 +0100 Subject: [PATCH 276/317] fix(appkit): count only owned objects as hand-off blockers, and refuse other databases first The blocker count mixed privileges in with what the role owns, so the failure message called grants blocking objects. What the owner holds is now split: objects in other databases or shared ones, and privileges, each reported apart. Objects in another database of the branch, which the reassign cannot reach, are refused before the delete. An extension the owner has stays a refusal that names it and the manual delete-role command; a test pins it. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/hand-off.ts | 74 ++++++++++++++----- .../tooling/tests/hand-off.pg.test.ts | 41 ++++++---- .../src/database/tooling/tests/init.test.ts | 52 +++++++++++-- 3 files changed, 130 insertions(+), 37 deletions(-) diff --git a/packages/appkit/src/database/tooling/hand-off.ts b/packages/appkit/src/database/tooling/hand-off.ts index c18e41e3d..4f1d9a3b5 100644 --- a/packages/appkit/src/database/tooling/hand-off.ts +++ b/packages/appkit/src/database/tooling/hand-off.ts @@ -6,33 +6,46 @@ import type { LakebaseRole } from "./lakebase-api"; import { resourceId } from "./targets"; /** - * What keeps a role from being dropped once its objects in the current - * database are reassigned: objects it owns in other databases, shared objects + * 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 BLOCKERS_SQL = ` -select coalesce(d.datname, '') as database, count(*)::int as count +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 - order by 1`; + group by 1, 2 + order by 1, 2`; -interface RoleBlocker { +interface Dependents { /** Empty for shared objects. */ readonly database: string; readonly count: number; } -export async function readRoleBlockers( +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(BLOCKERS_SQL, [role]); - return rows; +): 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, count })); + return { owned: of("owned"), granted: of("granted") }; } /** @@ -68,8 +81,8 @@ export async function readOwnedOutsideSchema( return rows.map((row) => row.label); } -function describeBlockers(blockers: readonly RoleBlocker[]): string { - return blockers +function describe(dependents: readonly Dependents[]): string { + return dependents .map( ({ database, count }) => `${database ? `database ${database}` : "shared objects"} (${count})`, @@ -94,8 +107,10 @@ interface HandOff { * 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. Returns - * the owner; null when you already own the schema or it does not exist. + * 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; 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 @@ -115,12 +130,12 @@ export async function handOffAppSchema( return { owner, ownedOutside: await readOwnedOutsideSchema(pool, owner, input.schemaName), - blockers: await readRoleBlockers(pool, owner), + dependencies: await readRoleDependencies(pool, owner), }; }); if (!found) return null; - const { owner, ownedOutside, blockers } = found; + const { owner, ownedOutside, dependencies } = found; const where = `schema ${input.schemaName} in database ${input.database} on ${resourceId(input.branch)}`; const role = input.roles.find((r) => r.status?.postgres_role === owner); if (!role) { @@ -133,6 +148,12 @@ export async function handOffAppSchema( `Refusing to hand ${where} to you: deleting role "${owner}" 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 "${owner}" 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 ${owner}, which owns it, with its objects reassigned to you`, ); @@ -142,9 +163,24 @@ export async function handOffAppSchema( .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 + ? [`"${owner}" still owns ${describe(owned)}, which block the delete.`] + : []), + ...(granted.length > 0 + ? [`Privileges granted to "${owner}": ${describe(granted)}.`] + : []), + ]; throw new Error( - blockers.length > 0 - ? `Could not hand ${where} to you: deleting role "${owner}" failed (${reason}). These objects and privileges of "${owner}" block the delete: ${describeBlockers(blockers)}. .env already points at the branch. Drop them or reassign them to you, then rerun \`appkit db init\`.` + details.length > 0 + ? `Could not hand ${where} to you: deleting role "${owner}" failed (${reason}). ${details.join(" ")} .env already points at the branch. ${fix}, then rerun \`appkit db init\`.` : `Could not hand ${where} to you: deleting role "${owner}" failed (${reason}). .env already points at the branch; rerun \`appkit db init\` to retry.`, { cause: error }, ); diff --git a/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts b/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts index cdcaa6679..827c0bfa6 100644 --- a/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/hand-off.pg.test.ts @@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto"; import { Pool } from "pg"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; -import { readOwnedOutsideSchema, readRoleBlockers } from "../hand-off"; +import { readOwnedOutsideSchema, readRoleDependencies } from "../hand-off"; // The pg_shdepend query against a real server, as a superuser that may create // databases and roles, e.g. APPKIT_TEST_PG_URL=postgres://localhost:5432/postgres @@ -15,7 +15,7 @@ function databaseUrl(database: string): string { return next.toString(); } -describe.skipIf(!url)("readRoleBlockers against Postgres", () => { +describe.skipIf(!url)("readRoleDependencies against Postgres", () => { const suffix = randomUUID().slice(0, 8); const role = `appkit_sp_${suffix}`; const main = `appkit_main_${suffix}`; @@ -55,22 +55,20 @@ describe.skipIf(!url)("readRoleBlockers against Postgres", () => { await admin.end(); }); - test("lists what outlives a reassign in this database: other databases' objects, shared objects, and grants", async () => { - const blockers = await readRoleBlockers(mainPool, role); - - expect(blockers).toEqual( - [ + test("what outlives a reassign in this database: other databases' objects and shared objects it owns, apart from its grants", async () => { + await expect(readRoleDependencies(mainPool, role)).resolves.toEqual({ + owned: [ { database: "", count: 1 }, - { database: main, count: 1 }, { database: other, count: 1 }, - ].sort((a, b) => a.database.localeCompare(b.database)), - ); + ], + granted: [{ database: main, count: 1 }], + }); }); - test("a role without dependencies has no blockers", async () => { + test("a role without dependencies has none", async () => { await expect( - readRoleBlockers(mainPool, `appkit_missing_${suffix}`), - ).resolves.toEqual([]); + readRoleDependencies(mainPool, `appkit_missing_${suffix}`), + ).resolves.toEqual({ owned: [], granted: [] }); }); test("what the role owns in this database outside the app schema: nothing while it only owns the schema and its tables", async () => { @@ -109,4 +107,21 @@ describe.skipIf(!url)("readRoleBlockers against Postgres", () => { `); } }); + + test("lists an extension the role created, which has no schema", async () => { + await admin.query(`grant create on database "${main}" to "${role}"`); + await mainPool.query(` + set role "${role}"; + create extension pgcrypto schema app; + reset role; + `); + try { + await expect( + readOwnedOutsideSchema(mainPool, role, "app"), + ).resolves.toEqual(["extension pgcrypto"]); + } finally { + await mainPool.query("drop extension pgcrypto"); + await admin.query(`revoke create on database "${main}" from "${role}"`); + } + }); }); diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index b4cc2c25c..86565d18c 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -63,7 +63,11 @@ let journalTrusted: boolean; let tagged: boolean; let keptInPublic: string[]; let ownedOutside: string[]; -let blockers: { database: string; count: number }[]; +let blockers: { + kind: "owned" | "granted"; + database: string; + count: number; +}[]; const queries: string[] = []; const pool = { query: vi.fn(async (text: string) => { @@ -978,7 +982,34 @@ describe("runInit — hand-off failures", () => { ); }); - test("a failed role delete lists what blocks it", async () => { + test("an extension the owner has is named with the manual command, and nothing is deleted", async () => { + const lakebase = project(); + ownedOutside = ["extension pgcrypto"]; + + await expect(init(appOn(lakebase))).rejects.toThrow( + `what else it owns on this branch: extension pgcrypto. .env already points at the branch. Reassign or drop them, or take them all with \`databricks postgres delete-role ${DEV}/roles/dbrx-apps-${SP} --reassign-owned-to ${DEV}/roles/alice\`, then rerun \`appkit db init\`.`, + ); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + }); + + test("an owner with objects in another database is refused before the delete, which cannot reassign them", async () => { + const lakebase = project(); + blockers = [ + { kind: "owned", database: "analytics", count: 3 }, + { kind: "granted", database: "databricks_postgres", count: 2 }, + ]; + + await expect(init(appOn(lakebase))).rejects.toThrow( + `Refusing to hand schema app in database databricks_postgres on ${devBranchId(USER)} to you: role "${SP}" also owns objects in other databases on this branch, which deleting it cannot reassign: database analytics (3). .env already points at the branch. Reassign or drop them in those databases, then rerun \`appkit db init\`.`, + ); + expect(lakebase.calls.some((call) => call.startsWith("deleteRole"))).toBe( + false, + ); + }); + + test("a failed role delete lists the shared objects the owner has apart from its privileges", async () => { const lakebase = project(); lakebase.deleteRoleError = new LakebaseApiError( "delete role", @@ -986,12 +1017,13 @@ describe("runInit — hand-off failures", () => { { statusCode: 500 }, ); blockers = [ - { database: "analytics", count: 3 }, - { database: "databricks_postgres", count: 1 }, + { kind: "owned", database: "", count: 1 }, + { kind: "granted", database: "analytics", count: 2 }, + { kind: "granted", database: "databricks_postgres", count: 1 }, ]; await expect(init(appOn(lakebase))).rejects.toThrow( - `These objects and privileges of "${SP}" block the delete: database analytics (3), database databricks_postgres (1). .env already points at the branch. Drop them or reassign them to you, then rerun \`appkit db init\`.`, + `failed (Lakebase: delete role failed: INTERNAL_ERROR). "${SP}" still owns shared objects (1), which block the delete. Privileges granted to "${SP}": database analytics (2), database databricks_postgres (1). .env already points at the branch. Reassign or drop what it owns and revoke its privileges, then rerun \`appkit db init\`.`, ); expect(pool.query).toHaveBeenCalledWith( expect.stringContaining("pg_shdepend"), @@ -999,6 +1031,16 @@ describe("runInit — hand-off failures", () => { ); }); + test("a failed role delete with only privileges says to revoke them", async () => { + const lakebase = project(); + lakebase.deleteRoleError = new Error("timeout"); + blockers = [{ kind: "granted", database: "analytics", count: 2 }]; + + await expect(init(appOn(lakebase))).rejects.toThrow( + `failed (timeout). Privileges granted to "${SP}": database analytics (2). .env already points at the branch. Revoke its privileges, then rerun \`appkit db init\`.`, + ); + }); + test("without blockers it says to rerun", async () => { const lakebase = project(); lakebase.deleteRoleError = new Error("timeout"); From 8161928f5678570601a8a64c921b688219017f12 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:42:38 +0100 Subject: [PATCH 277/317] test(appkit): pin escaped catalog names in clean, seed and hand-off output Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/clean-seed.test.ts | 20 +++++++++++++++++++ .../src/database/tooling/tests/init.test.ts | 14 +++++++++++++ 2 files changed, 34 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index 5446e505b..089939c66 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -217,6 +217,26 @@ describe("clean on the fork's untouched copy", () => { }); }); +describe("catalog text in clean and seed", () => { + test("control characters in catalog names are escaped before they reach the terminal", async () => { + const ctx = fakeContext({ + root: tempApp({ "config/database/schema.ts": schemaFile("app") }), + }); + writableEnvBranch.mockResolvedValue(devBranch); + recordingPool({ dependents: ['view reporting."a\u001b[2Jb"'] }); + + await expect(runClean(ctx)).resolves.toMatchObject({ + dependents: ['view reporting."a\\u001b[2Jb"'], + }); + + const root = tempApp({ [SEED_FILE]: "select 1;" }); + recordingPool({ schemaOwner: "sp\nFAKE: done" }); + await expect(runSeed(fakeContext({ root }))).rejects.toThrow( + 'which "sp\\u000aFAKE: done" still owns', + ); + }); +}); + describe("previewClean", () => { test("reads the dependents without opening a transaction or dropping anything", async () => { const ctx = fakeContext({ diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 86565d18c..a011b5df9 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -982,6 +982,20 @@ describe("runInit — hand-off failures", () => { ); }); + test("catalog names in hand-off messages have their control characters escaped", async () => { + schemaOwner = "legacy\u001b[2J"; + + await expect(init(appOn(project()))).rejects.toThrow( + 'it belongs to "legacy\\u001b[2J", which is not a Lakebase-managed role', + ); + + schemaOwner = SP; + ownedOutside = ['table public."x\ny"']; + await expect(init(appOn(project()))).rejects.toThrow( + 'what else it owns on this branch: table public."x\\u000ay".', + ); + }); + test("an extension the owner has is named with the manual command, and nothing is deleted", async () => { const lakebase = project(); ownedOutside = ["extension pgcrypto"]; From c31495e2e7c2e82529e226271708f2b2ed4efa42 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:43:43 +0100 Subject: [PATCH 278/317] fix(appkit): escape catalog names that clean, seed and the hand-off print A quoted Postgres name can hold control characters that rewrite the terminal. The labels clean and the hand-off read, the owners their refusals name, and the copy's owner in migrate, introspect and seed refusals now go through introspect's shown(), so the CLI's output prints them escaped too. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/clean.ts | 7 +++-- .../appkit/src/database/tooling/hand-off.ts | 31 ++++++++++--------- .../src/database/tooling/schema-state.ts | 3 +- 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/packages/appkit/src/database/tooling/clean.ts b/packages/appkit/src/database/tooling/clean.ts index db7713335..a19bb4891 100644 --- a/packages/appkit/src/database/tooling/clean.ts +++ b/packages/appkit/src/database/tooling/clean.ts @@ -7,6 +7,7 @@ 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"; @@ -171,7 +172,7 @@ export async function readCascadeDependents( schemaName, schemaName === "public", ]); - return rows.map((row) => row.label); + return rows.map((row) => shown(row.label)); } /** @@ -211,7 +212,7 @@ export async function readKeptObjects( ): Promise { if (schemaName !== "public") return []; const { rows } = await client.query<{ label: string }>(KEPT_SQL); - return rows.map((row) => row.label); + return rows.map((row) => shown(row.label)); } export interface CleanReport { @@ -247,7 +248,7 @@ async function refuseUntouchedCopy( ); 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 "${owner}" still owns, so your role cannot drop it. Run \`appkit db init\` to take it over and rebuild it from the committed migrations.`, + `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.`, ); } diff --git a/packages/appkit/src/database/tooling/hand-off.ts b/packages/appkit/src/database/tooling/hand-off.ts index 4f1d9a3b5..7860dac6a 100644 --- a/packages/appkit/src/database/tooling/hand-off.ts +++ b/packages/appkit/src/database/tooling/hand-off.ts @@ -2,6 +2,7 @@ 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"; @@ -44,7 +45,7 @@ export async function readRoleDependencies( const of = (kind: "owned" | "granted") => rows .filter((row) => row.kind === kind) - .map(({ database, count }) => ({ database, count })); + .map(({ database, count }) => ({ database: shown(database), count })); return { owned: of("owned"), granted: of("granted") }; } @@ -78,7 +79,7 @@ export async function readOwnedOutsideSchema( role, schemaName, ]); - return rows.map((row) => row.label); + return rows.map((row) => shown(row.label)); } function describe(dependents: readonly Dependents[]): string { @@ -109,9 +110,8 @@ interface HandOff { * 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; null when you already own the - * schema or it does not exist. - * Schema public is never handed off: it belongs to the database + * 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. @@ -136,26 +136,27 @@ export async function handOffAppSchema( if (!found) return null; const { owner, ownedOutside, dependencies } = found; + const ownerName = shown(owner); const where = `schema ${input.schemaName} in database ${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 "${owner}", 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\`.`, + `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 "${owner}" 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\`.`, + `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 "${owner}" 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\`.`, + `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 ${owner}, which owns it, with its objects reassigned to you`, + `Handing ${where} to you: deleting this branch's copy of role ${ownerName}, which owns it, with its objects reassigned to you`, ); try { await ctx @@ -172,18 +173,20 @@ export async function handOffAppSchema( : "Revoke its privileges"; const details = [ ...(owned.length > 0 - ? [`"${owner}" still owns ${describe(owned)}, which block the delete.`] + ? [ + `"${ownerName}" still owns ${describe(owned)}, which block the delete.`, + ] : []), ...(granted.length > 0 - ? [`Privileges granted to "${owner}": ${describe(granted)}.`] + ? [`Privileges granted to "${ownerName}": ${describe(granted)}.`] : []), ]; throw new Error( details.length > 0 - ? `Could not hand ${where} to you: deleting role "${owner}" failed (${reason}). ${details.join(" ")} .env already points at the branch. ${fix}, then rerun \`appkit db init\`.` - : `Could not hand ${where} to you: deleting role "${owner}" failed (${reason}). .env already points at the branch; rerun \`appkit db init\` to retry.`, + ? `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 owner; + return ownerName; } diff --git a/packages/appkit/src/database/tooling/schema-state.ts b/packages/appkit/src/database/tooling/schema-state.ts index 00e558ca4..79201794f 100644 --- a/packages/appkit/src/database/tooling/schema-state.ts +++ b/packages/appkit/src/database/tooling/schema-state.ts @@ -9,6 +9,7 @@ import { import { schemaOwnership } from "../migrations/ownership"; import { MIGRATIONS_TABLE } from "../migrations/paths"; import { readKeptObjects } from "./clean"; +import { shown } from "./introspect/render"; import { resourceId } from "./targets"; export type SchemaStart = "migrate" | "introspect" | "clean" | "none"; @@ -169,7 +170,7 @@ export function forkCopyRefusal( } const holds = state.kind === "copy" - ? `which "${state.owner}" still owns` + ? `which "${shown(state.owner)}" still owns` : "and its rebuild did not finish"; return `${resourceId(branch)} still holds the rows the fork copied into schema "${schemaName}", ${holds}. Run \`appkit db init\` to rebuild it from the committed migrations, or \`appkit db init --schema ${keep}\` to keep them.`; } From 65180266e2b5d9e605efe81cef7c3486cc26a7e2 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:44:13 +0100 Subject: [PATCH 279/317] docs(appkit): say that init resumes a session branch a --session run left .env short of Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 5 ++++- packages/shared/src/cli/commands/db/init.ts | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index b376f5b3d..4349500cf 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -73,7 +73,10 @@ import { export type { SchemaStart } from "./schema-state"; export interface InitOptions { - /** Default: this checkout's session branch when .env points at it, else your dev branch. */ + /** + * 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: { diff --git a/packages/shared/src/cli/commands/db/init.ts b/packages/shared/src/cli/commands/db/init.ts index 7626df529..578223cec 100644 --- a/packages/shared/src/cli/commands/db/init.ts +++ b/packages/shared/src/cli/commands/db/init.ts @@ -173,7 +173,8 @@ export const dbInitCommand = new Command("init") "after", ` init asks nothing. It keeps this checkout's session branch when .env points at -one, and otherwise uses your dev branch (dev--). A new branch forks +one, or when a --session run stopped before .env did, and otherwise uses your +dev branch (dev--). A new branch forks the branch databricks.yml deploys to, else the project's default branch, which copies its rows, production data included. init reads from the branch whether the app schema is still that copy. If it is, init takes the schema over and From f451abd89bfbb5698d99314be74bfd6c39f5b013 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:52:04 +0100 Subject: [PATCH 280/317] fix(appkit): pass CREATE on the app schema to the USAGE refusal's hint Layer 02 made ownershipHint need whether the connecting role holds CREATE on the schema, and the USAGE check from layer 01 did not read it. The check now reads it in the same catalog query. The public lookup test counts the USAGE query that now precedes the catalog query. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/plugins/database/schema-check.ts | 5 ++++- .../appkit/src/plugins/database/tests/schema-check.test.ts | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/plugins/database/schema-check.ts b/packages/appkit/src/plugins/database/schema-check.ts index 7da959038..c2f43167b 100644 --- a/packages/appkit/src/plugins/database/schema-check.ts +++ b/packages/appkit/src/plugins/database/schema-check.ts @@ -22,6 +22,7 @@ interface SchemaAccess { readonly owner: string; readonly current_user: string; readonly usage: boolean; + readonly can_create: boolean; } /** @@ -35,7 +36,8 @@ async function assertSchemaUsable( const [access] = await dataPath.raw` select pg_catalog.pg_get_userbyid(n.nspowner)::text as owner, current_user::text as current_user, - pg_catalog.has_schema_privilege(n.oid, 'USAGE') as usage + pg_catalog.has_schema_privilege(n.oid, 'USAGE') as usage, + pg_catalog.has_schema_privilege(n.oid, 'CREATE') as can_create from pg_catalog.pg_namespace n where n.nspname::text = ${schemaName}`; if (!access || access.usage) return; @@ -43,6 +45,7 @@ async function assertSchemaUsable( schemaName, owner: access.owner, currentUser: access.current_user, + canCreate: access.can_create, }); throw databaseSetupFailed( `role "${access.current_user}" has no USAGE on schema "${schemaName}". ${hint}`, diff --git a/packages/appkit/src/plugins/database/tests/schema-check.test.ts b/packages/appkit/src/plugins/database/tests/schema-check.test.ts index f7258af96..a783629e5 100644 --- a/packages/appkit/src/plugins/database/tests/schema-check.test.ts +++ b/packages/appkit/src/plugins/database/tests/schema-check.test.ts @@ -115,7 +115,7 @@ describe("assertSchemaMatchesDatabase — tables left in public", () => { await expect( assertSchemaMatchesDatabase(path, schema, OFF), ).rejects.toThrow("commit migrations"); - expect(raw).toHaveBeenCalledTimes(1); + expect(raw).toHaveBeenCalledTimes(2); }); }); From 8b4289c1c9279d8736948d69fda7f513ad1fa50f Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:53:49 +0100 Subject: [PATCH 281/317] fix(appkit): name an unreadable migration file with migrationFile Layer 03 dropped the node:path import from apply.ts in favor of the paths helpers, and the unreadable-file error from layer 01 still joined the path itself. It now uses migrationFile. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/migrations/apply.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index a4b6bcdad..58088efe3 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -449,7 +449,7 @@ function unreadableMigrationError( error: unknown, ): MigrationFilesError { for (const entry of journal.entries) { - const file = path.join(folder, `${entry.tag}.sql`); + const file = migrationFile(folder, entry.tag); try { fs.readFileSync(file); } catch (cause) { From fa9cb1d948ba2b968f18fbed37624777a5b2c9b7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 16:55:37 +0100 Subject: [PATCH 282/317] refactor(appkit): build dev and session branch ids from the runtime shapes naming.ts kept its own copy of the branch id limit, prefixes and hash length that branch-names.ts uses to refuse a deploy bound to a dev or session branch. It now imports them, so the ids init generates and the shapes the deployed app refuses cannot drift apart. A test feeds every generated id to developmentBranchKind. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/branch-names.ts | 10 +++++----- packages/appkit/src/database/tooling/naming.ts | 15 ++++++++------- .../src/database/tooling/tests/naming.test.ts | 17 +++++++++++++++++ 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/packages/appkit/src/database/branch-names.ts b/packages/appkit/src/database/branch-names.ts index d604e0db1..1f318d8f1 100644 --- a/packages/appkit/src/database/branch-names.ts +++ b/packages/appkit/src/database/branch-names.ts @@ -3,13 +3,13 @@ // tooling/, which runtime code may not import. /** Lakebase's limit on a branch id. */ -const MAX_BRANCH_ID = 63; -const DEV_PREFIX = "dev-"; -const SESSION_PREFIX = "session-"; +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. */ -const HASH_LENGTH = 6; +export const HASH_LENGTH = 6; /** The longest session id that keeps session-- within MAX_BRANCH_ID. */ -const SESSION_ID_LENGTH = +export const SESSION_ID_LENGTH = MAX_BRANCH_ID - SESSION_PREFIX.length - HASH_LENGTH - 1; const DEVELOPMENT_BRANCH_SHAPES = { diff --git a/packages/appkit/src/database/tooling/naming.ts b/packages/appkit/src/database/tooling/naming.ts index 4417e3f8c..d40de4007 100644 --- a/packages/appkit/src/database/tooling/naming.ts +++ b/packages/appkit/src/database/tooling/naming.ts @@ -1,15 +1,16 @@ import { createHash } from "node:crypto"; +import { + DEV_PREFIX, + HASH_LENGTH, + MAX_BRANCH_ID, + SESSION_ID_LENGTH, + SESSION_PREFIX, +} from "../branch-names"; + // Branch names AppKit creates. Branch IDs: 1-63 chars, start with a // lowercase letter, lowercase letters, digits and hyphens only. -const MAX_BRANCH_ID = 63; -const DEV_PREFIX = "dev-"; -const SESSION_PREFIX = "session-"; -const HASH_LENGTH = 6; - -const SESSION_ID_LENGTH = - MAX_BRANCH_ID - SESSION_PREFIX.length - HASH_LENGTH - 1; const SESSION_ID = new RegExp(`^[a-z0-9]{1,${SESSION_ID_LENGTH}}$`); function slug(value: string): string { diff --git a/packages/appkit/src/database/tooling/tests/naming.test.ts b/packages/appkit/src/database/tooling/tests/naming.test.ts index 11d46db41..0c77fc14a 100644 --- a/packages/appkit/src/database/tooling/tests/naming.test.ts +++ b/packages/appkit/src/database/tooling/tests/naming.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from "vitest"; +import { developmentBranchKind } from "../../branch-names"; import { devBranchId, isValidSessionId, sessionBranchId } from "../naming"; const BRANCH_ID = /^[a-z][a-z0-9-]{0,62}$/; @@ -54,4 +55,20 @@ describe("branch naming", () => { sessionBranchId("bob@example.com", "abc"), ); }); + + test("the deployed app's refusal recognizes every id init generates", () => { + for (const user of [ + "Alice.Smith@example.com", + `${"x".repeat(80)}@example.com`, + "__@example.com", + "11111111-2222-3333-4444-555555555555", + ]) { + expect(developmentBranchKind(devBranchId(user))).toBe("dev"); + for (const session of ["a", "k2x9q0ab", "a".repeat(48)]) { + expect(developmentBranchKind(sessionBranchId(user, session))).toBe( + "session", + ); + } + } + }); }); From b262d25748e28100f86444e57bffd9ed6edf9651 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:01:04 +0100 Subject: [PATCH 283/317] fix(appkit): read BUNDLE_VAR_ variables where init reads databricks.yml Layer 03 made the databricks.yml reader take the command's environment, so a BUNDLE_VAR_ value counts the way a deploy from the shell counts it. init passed no environment to readDeployBoundary or to readDeployTarget, the reader of the branch it forks and the database it binds. Both now get ctx.env, and readDeployTarget applies the BUNDLE_VAR_ view ahead of variable-overrides.json. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/init.ts | 4 +- .../appkit/src/database/tooling/targets.ts | 16 +++++--- .../database/tooling/tests/targets.test.ts | 37 ++++++++++++++++--- 3 files changed, 43 insertions(+), 14 deletions(-) diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 4349500cf..ac0e18cba 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -667,7 +667,7 @@ async function initHolding( const configured = { local: readLocalTarget(ctx.env), - deploy: readDeployTarget(ctx.root), + deploy: readDeployTarget(ctx.root, ctx.env), }; const project = resolveProject(configured.local, configured.deploy); const { local, deploy } = scopeToProject( @@ -690,7 +690,7 @@ async function initHolding( identity, session: local.session, ttl, - boundary: readDeployBoundary(ctx.root), + boundary: readDeployBoundary(ctx.root, ctx.env), envFile, deploy, onStep, diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index c2e186760..108280bb9 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -436,17 +436,21 @@ function bundleApps( /** * The branch and database the default target deploys to from this checkout: * its first app binding the files resolve, else its postgres_branch and - * postgres_database variables, with the checkout's variable-overrides.json - * applied as a deploy would. null without databricks.yml or a branch the - * files resolve. + * postgres_database variables, with env's BUNDLE_VAR_ variables and the + * checkout's variable-overrides.json applied as a deploy would. null without + * databricks.yml or a branch the files resolve. */ -export function readDeployTarget(root: string): DeployTarget | null { - const targets = readBundle(root)?.targets ?? []; +export function readDeployTarget( + root: string, + env: NodeJS.ProcessEnv, +): DeployTarget | null { + const targets = readBundle(root, env)?.targets ?? []; const target = targets.find((candidate) => candidate.isDefault) ?? targets.find((candidate) => candidate.name === "default"); if (!target) return null; - const bindings: TargetBindings = target.overridden ?? target; + const bindings: TargetBindings = + target.environment ?? target.overridden ?? target; const resolved = (value: BundleValue | null) => value?.kind === "resolved" ? value.name : null; const binding = bindings.apps diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index 21e3ac9fa..6092e681a 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -490,7 +490,7 @@ describe("readDeployTarget", () => { "projects/p/branches/production/databases/databricks-postgres", ), }); - expect(readDeployTarget(root)).toEqual({ + expect(readDeployTarget(root, {})).toEqual({ branch: "projects/p/branches/production", database: "projects/p/branches/production/databases/databricks-postgres", }); @@ -506,7 +506,7 @@ targets: default: true `, }); - expect(readDeployTarget(root)).toEqual({ + expect(readDeployTarget(root, {})).toEqual({ branch: "projects/p/branches/main", database: null, }); @@ -524,12 +524,34 @@ targets: }), }); - expect(readDeployTarget(root)).toEqual({ + expect(readDeployTarget(root, {})).toEqual({ branch: "projects/q/branches/staging", database: "projects/q/branches/staging/databases/staging-db", }); }); + test("a BUNDLE_VAR_ value wins over variable-overrides.json, as it does for a deploy from this shell", () => { + const root = tempApp({ + "databricks.yml": databricksYml( + "projects/p/branches/production", + "projects/p/branches/production/databases/db", + ), + ".databricks/bundle/default/variable-overrides.json": JSON.stringify({ + postgres_branch: "projects/q/branches/staging", + postgres_database: "projects/q/branches/staging/databases/staging-db", + }), + }); + + expect( + readDeployTarget(root, { + BUNDLE_VAR_postgres_branch: "projects/q/branches/qa", + }), + ).toEqual({ + branch: "projects/q/branches/qa", + database: "projects/q/branches/staging/databases/staging-db", + }); + }); + test("a variable-overrides.json that leaves the branch unresolved gives no deploy target", () => { const root = tempApp({ "databricks.yml": databricksYml( @@ -541,13 +563,16 @@ targets: }), }); - expect(readDeployTarget(root)).toBeNull(); + expect(readDeployTarget(root, {})).toBeNull(); }); test("null without databricks.yml or without a postgres binding", () => { - expect(readDeployTarget(tempApp())).toBeNull(); + expect(readDeployTarget(tempApp(), {})).toBeNull(); expect( - readDeployTarget(tempApp({ "databricks.yml": "bundle:\n name: x\n" })), + readDeployTarget( + tempApp({ "databricks.yml": "bundle:\n name: x\n" }), + {}, + ), ).toBeNull(); }); }); From d0bafe9e5ba2db85dbb5a2d31be89b534955f015 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:07:01 +0100 Subject: [PATCH 284/317] fix(appkit): read BUNDLE_VAR_ variables in deployed verify Layer 03 made the databricks.yml reader take the command's environment. Deployed verify now passes ctx.env and checks the branch and database the BUNDLE_VAR_ view binds ahead of variable-overrides.json, crediting both where it names the source. This layer moved the unresolved references out of deployRefusal into everyBranchRefusal, where the merge carried layer 03's BUNDLE_VAR_ text, so the test layer 03 pinned on classifyBranch's reason now pins everyBranchRefusal. Co-authored-by: Isaac Signed-off-by: ditadi --- .../database/tooling/tests/targets.test.ts | 19 ++++++++------- .../src/database/tooling/tests/verify.test.ts | 23 ++++++++++++++++++ .../appkit/src/database/tooling/verify.ts | 24 +++++++++++-------- 3 files changed, 48 insertions(+), 18 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index d9651d9da..ef9ee5ff2 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, test } from "vitest"; -import { classifyBranch } from "../guard"; +import { classifyBranch, everyBranchRefusal } from "../guard"; import { devBranchId } from "../naming"; import { parseProject, @@ -408,9 +408,10 @@ resources: userName: "alice@example.com", sessionId: null, boundary, - }).reason, - ).toBe( - 'databricks.yml may deploy to it: the files do not resolve resources.apps.app.resources[0].postgres.branch in target default with BUNDLE_VAR_postgres_branch ("${var.postgres_branch}"), variables.postgres_branch in target default with BUNDLE_VAR_postgres_branch (no value); give them values in databricks.yml or the BUNDLE_VAR_ variable named', + }).kind, + ).toBe("deploy-target"); + expect(everyBranchRefusal(boundary)).toBe( + 'The files do not resolve resources.apps.app.resources[0].postgres.branch in target default with BUNDLE_VAR_postgres_branch ("${var.postgres_branch}"), variables.postgres_branch in target default with BUNDLE_VAR_postgres_branch (no value), so `appkit db migrate` applies migrations to no branch, and `init`, `introspect`, `clean` and `seed` refuse every branch. Give them values in databricks.yml or the BUNDLE_VAR_ variable named', ); }); @@ -585,11 +586,13 @@ targets: tempApp({ "databricks.yml": `${variables}targets:\n dev: {}\n prod: {}\n`, }), + {}, ), ).toBeNull(); expect( readDeployTarget( tempApp({ "databricks.yml": `${variables}targets:\n dev: {}\n` }), + {}, ), ).toEqual({ branch: "projects/p/branches/main", database: null }); }); @@ -630,7 +633,7 @@ targets: `, }); - const bundle = readBundle(root); + const bundle = readBundle(root, {}); expect(bundle?.file).toBe("databricks.yml"); expect( @@ -679,8 +682,8 @@ targets: const noHost = tempApp({ "databricks.yml": "resources:\n apps:\n app:\n name: my-app\n", }); - expect(readBundle(noHost)?.targets.map((target) => target.host)).toEqual([ - null, - ]); + expect( + readBundle(noHost, {})?.targets.map((target) => target.host), + ).toEqual([null]); }); }); diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 63998b028..029cd8768 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -1395,6 +1395,29 @@ describe("runVerify --deployed", () => { }); }); + test("a branch a BUNDLE_VAR_ variable sets wins over variable-overrides.json, as a deploy from this shell uses it", async () => { + const qa = "projects/p/branches/qa"; + const { ctx } = deployedApp(); + const overrides = path.join( + ctx.root, + ".databricks/bundle/default/variable-overrides.json", + ); + fs.mkdirSync(path.dirname(overrides), { recursive: true }); + fs.writeFileSync( + overrides, + JSON.stringify({ postgres_branch: "projects/p/branches/staging" }), + ); + ctx.env.BUNDLE_VAR_postgres_branch = qa; + const source = + "databricks.yml with .databricks/bundle/default/variable-overrides.json and BUNDLE_VAR_postgres_branch"; + + expect(await runVerify(ctx, DEPLOYED)).toMatchObject({ + branch: qa, + problems: [`${source} deploys to ${qa}, which does not exist`], + ok: false, + }); + }); + test("a workspace.host the checkout's files do not resolve is refused before any API call, naming where to set it", async () => { const { ctx, lakebase, requests } = deployedApp({ yml: ymlWithHost("${var.host}"), diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index e5eb848b4..a34a016fd 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -678,7 +678,7 @@ async function verifyDeploy( ctx: DbContext, targetName: string | undefined, ): Promise { - const bundle = readBundle(ctx.root); + const bundle = readBundle(ctx.root, ctx.env); if (!bundle) { throw new Error( "No databricks.yml, so there is no deployed app to verify.", @@ -691,12 +691,16 @@ async function verifyDeploy( targetName, defaultBundleTarget(bundle), ); - // What a deploy from this checkout uses: variable-overrides.json's values - // when it has the file, as the deploy guard reads them. - const deploy = target.overridden ?? target; - const withFile = target.overridden ? ` with ${target.overridden.file}` : ""; + // What a deploy from this shell uses: the BUNDLE_VAR_ variables, then + // variable-overrides.json's values, as the deploy guard reads them. + const deploy = target.environment ?? target.overridden ?? target; + const applied = target.environment + ? [target.environment.file, target.environment.variables] + : [target.overridden?.file]; + const values = applied.filter(Boolean).join(" and "); + const withValues = values ? ` with ${values}` : ""; // Where the branch and database come from. - const source = `${file}${withFile}`; + const source = `${file}${withValues}`; const bound = deploy.apps.filter((app) => app.postgres.length > 0); if (bound.length > 1) { throw new Error( @@ -719,23 +723,23 @@ async function verifyDeploy( } if (branchValue.kind === "unresolved") { throw new Error( - `No deploy branch: ${declared ? `${declared.at}.branch` : "variables.postgres_branch"} in target ${target.name}${withFile} is "${branchValue.written}", which this checkout's files do not resolve to a branch.`, + `No deploy branch: ${declared ? `${declared.at}.branch` : "variables.postgres_branch"} in target ${target.name}${withValues} is "${branchValue.written}", which this checkout's files do not resolve to a branch.`, ); } const databaseValue = declared ? declared.database : deploy.postgresDatabase; if (databaseValue?.kind === "unresolved") { throw new Error( - `No deploy database: ${declared ? `${declared.at}.database` : "variables.postgres_database"} in target ${target.name}${withFile} is "${databaseValue.written}", which this checkout's files do not resolve to a database.`, + `No deploy database: ${declared ? `${declared.at}.database` : "variables.postgres_database"} in target ${target.name}${withValues} is "${databaseValue.written}", which this checkout's files do not resolve to a database.`, ); } if (deploy.host?.kind === "unresolved") { throw new Error( - `No target workspace: workspace.host in target ${target.name}${withFile} is "${deploy.host.written}", which this checkout's files do not resolve to a host. Give the variable it names a value in ${file}, or in .databricks/bundle/${target.name}/variable-overrides.json, then rerun.`, + `No target workspace: workspace.host in target ${target.name}${withValues} is "${deploy.host.written}", which this checkout's files do not resolve to a host. Give the variable it names a value in ${file}, or in .databricks/bundle/${target.name}/variable-overrides.json, then rerun.`, ); } if (!deploy.host && deploy.profile?.kind === "unresolved") { throw new Error( - `No target workspace: workspace.profile in target ${target.name}${withFile} is "${deploy.profile.written}", which this checkout's files do not resolve to a profile. Give the variable it names a value in ${file}, or in .databricks/bundle/${target.name}/variable-overrides.json, then rerun.`, + `No target workspace: workspace.profile in target ${target.name}${withValues} is "${deploy.profile.written}", which this checkout's files do not resolve to a profile. Give the variable it names a value in ${file}, or in .databricks/bundle/${target.name}/variable-overrides.json, then rerun.`, ); } const branch = branchValue.name; From 012307377f7fd5a34655ac34cd764f6253820a46 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:10:12 +0100 Subject: [PATCH 285/317] test(appkit): classify the .env branch for real in verify's PGUSER tests Layer 06 checks for the fork's copy by the .env branch's kind, and its two tests prove PGUSER plays no part by classifying the branch through the fake API. This layer mocks resolveEnvBranch to a dev branch for every test, so those two now run the real classifier. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/tests/verify.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 0829aecb7..4d28e7eb3 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -225,6 +225,12 @@ beforeEach(() => { }); }); +/** Classify the next .env branch as resolveEnvBranch does, through the Lakebase API and current user app() fakes. */ +async function classifyThroughApi(): Promise { + const guard = await vi.importActual("../guard"); + resolveEnvBranch.mockImplementationOnce(guard.resolveEnvBranch); +} + afterEach(() => { for (const root of roots.splice(0)) { fs.rmSync(root, { recursive: true, force: true }); @@ -402,6 +408,8 @@ describe("runVerify", () => { schemaOwner: "deployed-sp", }); + await classifyThroughApi(); + expect(await runVerify(ctx)).toMatchObject({ forkCopy: expect.stringContaining( `${devBranchId(USER)} still holds the rows the fork copied`, @@ -422,6 +430,8 @@ describe("runVerify", () => { schemaOwner: "bob", }); + await classifyThroughApi(); + expect(await runVerify(ctx)).toMatchObject({ forkCopy: null, ok: true }); }); From 9eefea373fe1dc04887335d9501a94215b02d38c Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:14:33 +0100 Subject: [PATCH 286/317] refactor(appkit): give db verify and db check one history-rewrite advice db verify's advice for a stranded migration and db check's advice for a history out of order were two copies of the same recovery, one saying main and one saying the base branch. Both now import one text from shared, which appkit can import and the CLI already belongs to. It says main, as the design does, and the database guide's passage on the same recovery now says main too. Co-authored-by: Isaac Signed-off-by: ditadi --- docs/docs/plugins/database.md | 12 ++++++------ packages/appkit/src/database/tooling/check.ts | 14 ++++++-------- .../src/database/tooling/tests/check.test.ts | 5 ++--- packages/shared/src/cli/commands/db/output.ts | 10 ++-------- .../shared/src/cli/commands/db/verify.test.ts | 18 +++++++++++------- packages/shared/src/database/index.ts | 1 + .../shared/src/database/migration-history.ts | 7 +++++++ 7 files changed, 35 insertions(+), 32 deletions(-) create mode 100644 packages/shared/src/database/migration-history.ts diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 3c8909ee5..779311f42 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -666,12 +666,12 @@ exits 1 when: 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 the base branch's migrations instead. -Save any SQL you wrote by hand in your migration, such as a backfill. Merge the -base branch, reset `config/database/migrations` to the base branch's, then run -`npx appkit db clean` and `npx appkit db migrate`. `migrate` writes your schema -change again after the base branch's migrations. Add the saved SQL back to the -regenerated migration and review its SQL before you commit. +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: diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts index df7e72af3..7631a8742 100644 --- a/packages/appkit/src/database/tooling/check.ts +++ b/packages/appkit/src/database/tooling/check.ts @@ -1,6 +1,7 @@ import fs from "node:fs"; import path from "node:path"; +import { MIGRATION_HISTORY_REWRITE } from "shared"; import { z } from "zod"; import { @@ -28,22 +29,19 @@ export interface CheckReport { readonly ok: boolean; } -const REWRITE = - "Save any SQL you wrote by hand in your migration. Merge the base branch, reset the migrations to its own (for example `git restore --source origin/main --staged --worktree config/database/migrations`), then run `appkit db clean` and `appkit db migrate`, which writes your schema change again after the base branch's migrations and applies them all to your rebuilt branch. Add the saved SQL back to the regenerated migration and review its SQL before you commit."; - /** 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. ${REWRITE}`, + `${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. ${REWRITE}`, + `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; } @@ -54,7 +52,7 @@ function orderProblems(entries: readonly JournalEntry[]): string[] { 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}. ${REWRITE}`, + `${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}`, ); } }); @@ -125,7 +123,7 @@ function chainProblems( ? "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. ${REWRITE}`, + `${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; @@ -178,7 +176,7 @@ export async function runCheck(ctx: DbContext): Promise { : []; for (const name of unlisted) { problems.push( - `${shown(path.join(folder, name))} is not in meta/_journal.json, so no deploy runs it. ${REWRITE}`, + `${shown(path.join(folder, name))} is not in meta/_journal.json, so no deploy runs it. ${MIGRATION_HISTORY_REWRITE}`, ); } problems.push(...chainProblems(entries, links)); diff --git a/packages/appkit/src/database/tooling/tests/check.test.ts b/packages/appkit/src/database/tooling/tests/check.test.ts index ae9565725..e8cc78875 100644 --- a/packages/appkit/src/database/tooling/tests/check.test.ts +++ b/packages/appkit/src/database/tooling/tests/check.test.ts @@ -2,6 +2,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { MIGRATION_HISTORY_REWRITE } from "shared"; import { afterEach, describe, expect, test, vi } from "vitest"; import { type Journal, readJournal } from "../../migrations/paths"; @@ -196,9 +197,7 @@ describe("runCheck", () => { const report = await runCheck(ctx); expect(report.problems).toEqual([ - expect.stringContaining( - "0002_migration was generated after 0000_migration, not after 0001_migration: they were written on parallel branches, so 0002_migration lacks the other's changes. Save any SQL you wrote by hand in your migration. Merge the base branch, reset the migrations to its own", - ), + `0002_migration was generated after 0000_migration, not after 0001_migration: they were written on parallel branches, so 0002_migration lacks the other's changes. ${MIGRATION_HISTORY_REWRITE}`, "config/database/schema.ts changed since 0002_migration, so the deployed app would not get the change. Run `appkit db migrate` and commit the migration it writes.", ]); }); diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index 0f45ac7a9..95c698417 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -3,6 +3,7 @@ import process from "node:process"; import pc from "picocolors"; +import { MIGRATION_HISTORY_REWRITE } from "../../../database"; import type { CheckReport, CleanReport, @@ -120,13 +121,6 @@ export function printCleanReport(report: CleanReport): void { const REBUILD = "`appkit db clean` and then `appkit db migrate` rebuild the branch from this checkout's migrations, in order"; -/** - * The recovery for a migration history main cannot run in order: the - * stranded migration is often main's own, so deleting it is never the fix. - */ -export const REWRITE = - "Save any SQL you wrote by hand in your migration, such as a backfill. Merge main, reset config/database/migrations to main's (for example `git restore --source main --staged --worktree config/database/migrations`), then run `appkit db clean` and `appkit db migrate`, which 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."; - /** The one next step for a failed local verify, most fundamental gap first. */ function localVerifyHint(report: LocalVerifyReport): string { // Tables left in public: migrating would create empty copies in the app schema. @@ -137,7 +131,7 @@ function localVerifyHint(report: LocalVerifyReport): string { if (report.unknownMigrations > 0) { return `${REBUILD}. If the branch ran migrations you have not pulled yet, pull them instead.`; } - if (report.strandedMigrations.length > 0) return REWRITE; + if (report.strandedMigrations.length > 0) return MIGRATION_HISTORY_REWRITE; // Pending migrations explain the gap; without them, schema.ts changed or the branch was edited. return report.pendingMigrations.length > 0 ? "Run `appkit db migrate` to apply the pending migrations." diff --git a/packages/shared/src/cli/commands/db/verify.test.ts b/packages/shared/src/cli/commands/db/verify.test.ts index f21674a82..61679515b 100644 --- a/packages/shared/src/cli/commands/db/verify.test.ts +++ b/packages/shared/src/cli/commands/db/verify.test.ts @@ -20,8 +20,8 @@ vi.mock("@databricks/appkit/beta/database-tooling", () => ({ runVerify, })); +import { MIGRATION_HISTORY_REWRITE } from "../../../database"; import { dbCommand } from "./index"; -import { REWRITE } from "./output"; let log: MockInstance; let error: MockInstance; @@ -219,13 +219,17 @@ describe("appkit db verify", () => { ); const printed = output(error); expect(printed).toContain( - `dev-alice-3f9a2c does not match config/database/schema.ts and the committed migrations. ${REWRITE}`, + `dev-alice-3f9a2c does not match config/database/schema.ts and the committed migrations. ${MIGRATION_HISTORY_REWRITE}`, ); - expect(REWRITE).toContain("Save any SQL you wrote by hand"); - expect(REWRITE).toContain("Merge main"); - expect(REWRITE).toContain("config/database/migrations"); - expect(REWRITE).toContain("`appkit db clean` and `appkit db migrate`"); - expect(REWRITE).toContain("Add the saved SQL back"); + expect(MIGRATION_HISTORY_REWRITE).toContain( + "Save any SQL you wrote by hand", + ); + expect(MIGRATION_HISTORY_REWRITE).toContain("Merge main"); + expect(MIGRATION_HISTORY_REWRITE).toContain("config/database/migrations"); + expect(MIGRATION_HISTORY_REWRITE).toContain( + "`appkit db clean` and `appkit db migrate`", + ); + expect(MIGRATION_HISTORY_REWRITE).toContain("Add the saved SQL back"); expect(printed).not.toMatch(/delete/i); expect(process.exitCode).toBe(1); }); diff --git a/packages/shared/src/database/index.ts b/packages/shared/src/database/index.ts index a14429b93..05cfe3140 100644 --- a/packages/shared/src/database/index.ts +++ b/packages/shared/src/database/index.ts @@ -1,3 +1,4 @@ export * from "./api-types"; export * from "./errors"; +export * from "./migration-history"; export * from "./query-codec"; diff --git a/packages/shared/src/database/migration-history.ts b/packages/shared/src/database/migration-history.ts new file mode 100644 index 000000000..a0cd21d12 --- /dev/null +++ b/packages/shared/src/database/migration-history.ts @@ -0,0 +1,7 @@ +/** + * The recovery for a migration history that cannot run in order after main's, + * which `appkit db verify` and `appkit db check` both give. The migration out + * of order is often main's own, so deleting it is never the fix. + */ +export const MIGRATION_HISTORY_REWRITE = + "Save any SQL you wrote by hand in your migration, such as a backfill. Merge main, reset config/database/migrations to main's (for example `git restore --source main --staged --worktree config/database/migrations`), then run `appkit db clean` and `appkit db migrate`, which 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."; From 11c71e63d74ef586914035b6e7e59816948be459 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:22:52 +0100 Subject: [PATCH 287/317] fix(appkit): give a stranded migration the history rewrite instead of deleting it A stranded migration is often main's own, so deleting its files is the wrong fix. The runtime refusal now gives the same recovery as the design: save hand-written SQL, merge main, reset the migrations to main's, then clean and migrate. The text lives in shared so the CLI can reuse it. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/migrations/apply.ts | 4 ++-- .../src/database/migrations/tests/apply.test.ts | 13 +++++++++---- packages/shared/src/database/index.ts | 1 + packages/shared/src/database/migration-history.ts | 7 +++++++ 4 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 packages/shared/src/database/migration-history.ts diff --git a/packages/appkit/src/database/migrations/apply.ts b/packages/appkit/src/database/migrations/apply.ts index c6094d8d1..f9e93219c 100644 --- a/packages/appkit/src/database/migrations/apply.ts +++ b/packages/appkit/src/database/migrations/apply.ts @@ -5,6 +5,7 @@ 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 { @@ -208,8 +209,7 @@ function strandedMessage( 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. ` + - `Delete ${many ? "their" : "its"} .sql file, snapshot and journal entry, generate the migration again from schema.ts, and deploy again. ` + - "No migration was applied." + `${MIGRATION_HISTORY_REWRITE} No migration was applied.` ); } diff --git a/packages/appkit/src/database/migrations/tests/apply.test.ts b/packages/appkit/src/database/migrations/tests/apply.test.ts index 5ab6d3af6..dbdd55e4d 100644 --- a/packages/appkit/src/database/migrations/tests/apply.test.ts +++ b/packages/appkit/src/database/migrations/tests/apply.test.ts @@ -1,6 +1,7 @@ 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 { @@ -393,8 +394,10 @@ describe("applyPendingMigrations", () => { expect(error).toBeInstanceOf(MigrationHistoryError); expect(error).toMatchObject({ refusal: { stranded: ["0001_parallel"] } }); - expect((error as Error).message).toMatch( - /^Migration 0001_parallel is older than 0002_b, which schema "app" already recorded, and was never applied/, + 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?"]); }); @@ -646,7 +649,7 @@ describe("applyPendingMigrations", () => { expect(state.recorded).toHaveLength(2); }); - test("the same history without the option refuses as stranded, with the regenerate runbook", async () => { + 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 }); @@ -657,8 +660,10 @@ describe("applyPendingMigrations", () => { 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\. .*Delete its \.sql file, snapshot and journal entry, generate the migration again from schema\.ts/, + /^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 () => { diff --git a/packages/shared/src/database/index.ts b/packages/shared/src/database/index.ts index 22770d9d3..10500e6c8 100644 --- a/packages/shared/src/database/index.ts +++ b/packages/shared/src/database/index.ts @@ -1,3 +1,4 @@ export * from "./api-types"; export * from "./errors"; +export * from "./migration-history"; export * from "./operations"; diff --git a/packages/shared/src/database/migration-history.ts b/packages/shared/src/database/migration-history.ts new file mode 100644 index 000000000..ec85a92f1 --- /dev/null +++ b/packages/shared/src/database/migration-history.ts @@ -0,0 +1,7 @@ +/** + * The recovery for a migration history that cannot run in order after main's. + * The migration out of order is often main's own, so deleting it is never the + * fix. + */ +export const MIGRATION_HISTORY_REWRITE = + "Save any SQL you wrote by hand in your migration, such as a backfill. Merge main, reset config/database/migrations to main's (for example `git restore --source main --staged --worktree config/database/migrations`), then run `appkit db clean` and `appkit db migrate`, which 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."; From 5b0582dd3517de880bf86b86bddf447b6ea36491 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:24:39 +0100 Subject: [PATCH 288/317] docs: describe the ambiguous history and the deploy start checks The design now names the ambiguous reconcile state, the 10 s client_connection_check_interval the migrating session sets, and the DATABRICKS_CLIENT_SECRET that migrate on start requires. Co-authored-by: Isaac Signed-off-by: ditadi --- designs/001_DatabaseDevelopmentFlow.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/designs/001_DatabaseDevelopmentFlow.md b/designs/001_DatabaseDevelopmentFlow.md index e89eb661a..7b3c4ae52 100644 --- a/designs/001_DatabaseDevelopmentFlow.md +++ b/designs/001_DatabaseDevelopmentFlow.md @@ -225,7 +225,8 @@ 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 select the plugin, which `apps init` offers only after the reveal. Until then, an app that adds the plugin by hand adds @@ -343,11 +344,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 @@ -390,12 +391,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 From c119797b04f7134e9045b153f79bd086a4c536d5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:30:56 +0100 Subject: [PATCH 289/317] fix(appkit): export WorkspaceRequest from the workspace-client wrapper Main replaced the wrapper's `export type *` with an explicit list, which drops the request type the database tooling's client interface uses. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/workspace-client/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/appkit/src/workspace-client/index.ts b/packages/appkit/src/workspace-client/index.ts index ab73e7325..3620e08c4 100644 --- a/packages/appkit/src/workspace-client/index.ts +++ b/packages/appkit/src/workspace-client/index.ts @@ -30,4 +30,5 @@ export type { SubmitRunResponse, WorkspaceClient, WorkspaceClientOptions, + WorkspaceRequest, } from "shared/workspace-client"; From 357b56d85484c4c3abc0bd8eed40d6f99dfbc25c Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:37:49 +0100 Subject: [PATCH 290/317] refactor(appkit): load schema.ts and write the journal with main's typegen helpers appkit db migrate now loads schema.ts through loadDatabaseSchema and writes the migration journal through writeIfChanged, both from main's database typegen. The CLI-only branch of the runtime loader and the stack's own atomic writer are deleted. loadDatabaseSchema keeps the import error as the cause of its bounded message, so the CLI still prints where schema.ts failed. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrate.ts | 16 ++++++------- .../appkit/src/database/tooling/migrations.ts | 24 ++++--------------- .../database/tooling/tests/migrate.test.ts | 4 +++- .../database/tooling/tests/migrations.test.ts | 14 +++++------ .../src/plugins/database/load-schema.ts | 14 +---------- .../src/type-generator/database/generate.ts | 10 ++++++-- .../src/type-generator/database/index.ts | 2 ++ 7 files changed, 33 insertions(+), 51 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index fb7662cd1..b387af832 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -1,12 +1,10 @@ import fs from "node:fs"; import path from "node:path"; -import { - DEFAULT_SCHEMA_FILE, - loadDefaultDatabaseSchema, -} from "../../plugins/database/load-schema"; +import { DEFAULT_SCHEMA_FILE } from "../../plugins/database/load-schema"; import { DATABASE_TYPES_FILE, + loadDatabaseSchema, writeDatabaseTypes, } from "../../type-generator/database"; import { @@ -173,9 +171,9 @@ async function migrateHolding( lock: HistoryLock, options: MigrateOptions, ): Promise { - const schema = await loadDefaultDatabaseSchema(ctx.root, { - showImportError: true, - }); + const schema = await loadDatabaseSchema( + path.join(ctx.root, DEFAULT_SCHEMA_FILE), + ); const generated = await generateMigrationFiles(lock, { schema, interactive: options.interactive, @@ -194,7 +192,7 @@ async function migrateHolding( // Nothing ran. A kept migration would create the empty copies the refusal // warns about, and the next run would diff schema.ts against it. if (error instanceof TablesLeftInPublicError) { - discardMigrationFiles(lock, generated); + await discardMigrationFiles(lock, generated); throw error; } const file = path.relative(ctx.root, generated.file); @@ -206,7 +204,7 @@ async function migrateHolding( error.code && !RETRYABLE_AS_WRITTEN.has(error.code) ) { - discardMigrationFiles(lock, generated); + await discardMigrationFiles(lock, generated); throw new Error( `${error.message} Removed ${file}, so the next run writes it again from ${DEFAULT_SCHEMA_FILE}. Change ${DEFAULT_SCHEMA_FILE} or the branch's data, then rerun \`appkit db migrate\`.`, { cause: error }, diff --git a/packages/appkit/src/database/tooling/migrations.ts b/packages/appkit/src/database/tooling/migrations.ts index 86e0133ac..90f470c7a 100644 --- a/packages/appkit/src/database/tooling/migrations.ts +++ b/packages/appkit/src/database/tooling/migrations.ts @@ -1,8 +1,8 @@ -import { randomUUID } from "node:crypto"; import fs from "node:fs"; import { createRequire } from "node:module"; import path from "node:path"; +import { writeIfChanged } from "../../type-generator/database"; import { type Journal, type JournalEntry, @@ -322,20 +322,6 @@ export function dataDependentStatements( return statementsWhere(MAY_FAIL_ON_EXISTING_ROWS, statements); } -/** Replace a file through a rename, so a crash never leaves it half written. */ -function writeFileAtomic(file: string, content: string): void { - const temporary = path.join( - path.dirname(file), - `.${path.basename(file)}.${randomUUID()}.tmp`, - ); - try { - fs.writeFileSync(temporary, content); - fs.renameSync(temporary, file); - } finally { - fs.rmSync(temporary, { force: true }); - } -} - /** * Diff the schema against the latest committed snapshot with drizzle-kit and * write the next v7 migration: `NNNN_migration.sql`, `meta/NNNN_snapshot.json`, @@ -405,7 +391,7 @@ export async function generateMigrationFiles( ); fs.writeFileSync(file, statements.join(BREAKPOINT)); // The journal is written last: it is what makes the migration visible. - writeFileAtomic(journalPath, JSON.stringify(next, null, 2)); + await writeIfChanged(journalPath, JSON.stringify(next, null, 2)); return { tag, file, statements, journalBefore }; } @@ -413,10 +399,10 @@ export async function generateMigrationFiles( * Remove a migration generateMigrationFiles wrote under the same lock and put * back the journal it replaced (none: the folders it created go too). */ -export function discardMigrationFiles( +export async function discardMigrationFiles( lock: HistoryLock, migration: GeneratedMigration, -): void { +): Promise { lock.assertHeld(); const { folder } = lock; // The journal goes back first, as it is what names the migration: a crash @@ -424,7 +410,7 @@ export function discardMigrationFiles( if (migration.journalBefore === null) { fs.rmSync(journalFile(folder), { force: true }); } else { - writeFileAtomic(journalFile(folder), migration.journalBefore); + await writeIfChanged(journalFile(folder), migration.journalBefore); } fs.rmSync(migration.file, { force: true }); fs.rmSync(snapshotFile(folder, Number.parseInt(migration.tag, 10)), { diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 667cd1d51..9d71adaa7 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -436,7 +436,9 @@ describe("runMigrate", () => { (caught: unknown) => caught, )) as Error; - expect(error.message).toBe("Could not load config/database/schema.ts."); + expect(error.message).toMatch( + /^Database schema ".*config\/database\/schema\.ts" threw while loading$/, + ); expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); expect(resolveEnvBranch).not.toHaveBeenCalled(); }); diff --git a/packages/appkit/src/database/tooling/tests/migrations.test.ts b/packages/appkit/src/database/tooling/tests/migrations.test.ts index e934644c7..e1a7efaa2 100644 --- a/packages/appkit/src/database/tooling/tests/migrations.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrations.test.ts @@ -457,7 +457,7 @@ describe("discardMigrationFiles", () => { interactive: false, }); expect(migration?.journalBefore).toBeNull(); - discardMigrationFiles(lock, migration as never); + await discardMigrationFiles(lock, migration as never); }); expect(fs.existsSync(folder)).toBe(false); @@ -477,7 +477,7 @@ describe("discardMigrationFiles", () => { interactive: false, }); expect(listFiles(folder)).not.toEqual(filesBefore); - discardMigrationFiles(lock, migration as never); + await discardMigrationFiles(lock, migration as never); }); expect(listFiles(folder)).toEqual(filesBefore); @@ -499,9 +499,9 @@ describe("discardMigrationFiles", () => { if (target === migration?.file) throw new Error("killed"); return rm(target, options); }); - expect(() => discardMigrationFiles(lock, migration as never)).toThrow( - "killed", - ); + await expect( + discardMigrationFiles(lock, migration as never), + ).rejects.toThrow("killed"); }); } @@ -540,9 +540,9 @@ describe("discardMigrationFiles", () => { ); const filesBefore = listFiles(folder); - expect(() => + await expect( discardMigrationFiles(released as never, migration as never), - ).toThrow(/lock .* was released/); + ).rejects.toThrow(/lock .* was released/); expect(listFiles(folder)).toEqual(filesBefore); }); }); diff --git a/packages/appkit/src/plugins/database/load-schema.ts b/packages/appkit/src/plugins/database/load-schema.ts index a94438635..5c8775fc5 100644 --- a/packages/appkit/src/plugins/database/load-schema.ts +++ b/packages/appkit/src/plugins/database/load-schema.ts @@ -8,15 +8,9 @@ import { assertFinalizedSchema } from "../../database/schema-builder/define-sche /** Same application-relative convention used by appkit generate-types. */ export const DEFAULT_SCHEMA_FILE = "config/database/schema.ts"; -interface LoadSchemaOptions { - /** Report why the module failed to import. Only for local CLI runs: see the catch below. */ - readonly showImportError?: boolean; -} - /** Load application-owned declarations during setup, never during registration. */ export async function loadDefaultDatabaseSchema( root = process.cwd(), - options: LoadSchemaOptions = {}, ): Promise { const file = path.resolve(root, DEFAULT_SCHEMA_FILE); const label = JSON.stringify(file); @@ -40,14 +34,8 @@ export async function loadDefaultDatabaseSchema( module = await createJiti(import.meta.url, { moduleCache: false }).import( file, ); - } catch (error) { + } catch { // Import errors can contain credentials, row values, or application internals. - // A CLI run shows them to the developer who wrote the file; the runtime never does. - if (options.showImportError) { - throw new Error(`Could not load ${DEFAULT_SCHEMA_FILE}.`, { - cause: error, - }); - } throw databaseSetupFailed( `Could not load the default schema at ${label}. Check the module and its imports, or pass database({ schema }).`, ); diff --git a/packages/appkit/src/type-generator/database/generate.ts b/packages/appkit/src/type-generator/database/generate.ts index 072d64e95..2f37da3b8 100644 --- a/packages/appkit/src/type-generator/database/generate.ts +++ b/packages/appkit/src/type-generator/database/generate.ts @@ -9,8 +9,11 @@ import { walkSchema } from "./walk-schema"; /** Safe diagnostic raised when database declarations cannot be generated. */ export class DatabaseTypegenError extends Error { - constructor(message = "Database schema generation failed") { - super(message); + constructor( + message = "Database schema generation failed", + options?: ErrorOptions, + ) { + super(message, options); this.name = "DatabaseTypegenError"; } } @@ -137,8 +140,11 @@ export async function loadDatabaseSchema(schemaFile: string): Promise { try { module = await importSchema(schemaFile); } catch (error) { + // The message stays bounded; only a caller that prints causes, the local + // `appkit db` CLI, shows the import error to the developer. throw new DatabaseTypegenError( `Database schema "${schemaLabel(schemaFile)}" ${importFailureReason(error)}`, + { cause: error }, ); } if (typeof module !== "object" || module === null || !("schema" in module)) { diff --git a/packages/appkit/src/type-generator/database/index.ts b/packages/appkit/src/type-generator/database/index.ts index 5f90d3f51..3b186b655 100644 --- a/packages/appkit/src/type-generator/database/index.ts +++ b/packages/appkit/src/type-generator/database/index.ts @@ -2,7 +2,9 @@ export { DATABASE_TYPES_FILE, DatabaseTypegenError, generateDatabaseTypes, + loadDatabaseSchema, writeDatabaseTypes, + writeIfChanged, } from "./generate"; export { DATABASE_OPERATIONS_TYPES_FILE, From 98a4326b1d7172db841a4cfc6540ec280754a0fc Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:40:30 +0100 Subject: [PATCH 291/317] feat(appkit): regenerate database-operations.d.ts in appkit db migrate migrate now runs main's generateDatabaseOperations next to database.d.ts, so the operation contracts and routes.gen.ts follow a schema change without a separate appkit generate-types. The CLI prints the file it wrote. Co-authored-by: Isaac Signed-off-by: ditadi --- designs/001_DatabaseDevelopmentFlow.md | 3 +- docs/docs/plugins/database.md | 5 ++- .../appkit/src/database/tooling/migrate.ts | 28 +++++++++---- .../database/tooling/tests/migrate.test.ts | 39 +++++++++++++++++++ .../src/cli/commands/db/migrate.test.ts | 19 ++++++++- .../shared/src/cli/commands/db/migrate.ts | 2 +- packages/shared/src/cli/commands/db/output.ts | 1 + .../src/cli/commands/db/tooling-contract.ts | 1 + 8 files changed, 85 insertions(+), 13 deletions(-) diff --git a/designs/001_DatabaseDevelopmentFlow.md b/designs/001_DatabaseDevelopmentFlow.md index 7b3c4ae52..4baed2e6c 100644 --- a/designs/001_DatabaseDevelopmentFlow.md +++ b/designs/001_DatabaseDevelopmentFlow.md @@ -600,7 +600,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 diff --git a/docs/docs/plugins/database.md b/docs/docs/plugins/database.md index 4ca5e5483..4aab00ba6 100644 --- a/docs/docs/plugins/database.md +++ b/docs/docs/plugins/database.md @@ -135,8 +135,9 @@ only the AppKit CLI of the same release imports. It has no semver guarantee. `npx appkit db migrate` compares `config/database/schema.ts` with the latest committed snapshot. When they differ, it writes `config/database/migrations/NNNN_migration.sql`. It regenerates -`shared/appkit-types/database.d.ts`, then applies pending migrations to the -branch `.env` names. Commit the migrations with `schema.ts`. +`shared/appkit-types/database.d.ts` and +`shared/appkit-types/database-operations.d.ts`, then applies pending migrations +to the branch `.env` names. Commit the migrations with `schema.ts`. ### Warnings about a generated migration diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index b387af832..cf441e583 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -3,7 +3,9 @@ import path from "node:path"; import { DEFAULT_SCHEMA_FILE } from "../../plugins/database/load-schema"; import { + DATABASE_OPERATIONS_TYPES_FILE, DATABASE_TYPES_FILE, + generateDatabaseOperations, loadDatabaseSchema, writeDatabaseTypes, } from "../../type-generator/database"; @@ -41,10 +43,7 @@ function requireSchemaFile(root: string): void { ); } -const DATABASE_TYPES_PATH = path.join( - "shared/appkit-types", - DATABASE_TYPES_FILE, -); +const TYPES_DIR = "shared/appkit-types"; export interface MigrateReport { /** The migration written by this run; null when schema.ts matches the latest snapshot. */ @@ -59,6 +58,7 @@ export interface MigrateReport { /** Why nothing was applied, when applying was skipped. */ readonly notApplied?: string; readonly typesFile: string; + readonly operationsTypesFile: string; } export interface MigrateOptions { @@ -153,8 +153,9 @@ async function applyToEnvBranch( /** * `appkit db migrate`: generate a migration when schema.ts changed, regenerate - * database.d.ts, and apply pending migrations to the `.env` branch (only AppKit - * dev/session branches). One command at a time owns the checkout's history. + * database.d.ts and database-operations.d.ts, and apply pending migrations to + * the `.env` branch (only AppKit dev/session branches). One command at a time + * owns the checkout's history. */ export async function runMigrate( ctx: DbContext, @@ -180,9 +181,19 @@ async function migrateHolding( }); const warnings = migrationWarnings(generated); - // The types follow schema.ts alone, so they are current even if applying fails. - const typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); + // The types follow schema.ts and server/database/routes alone, so they are + // current even if applying fails. + const typesFile = path.join(ctx.root, TYPES_DIR, DATABASE_TYPES_FILE); await writeDatabaseTypes(schema, typesFile); + const operationsTypesFile = path.join( + ctx.root, + TYPES_DIR, + DATABASE_OPERATIONS_TYPES_FILE, + ); + await generateDatabaseOperations({ + appRoot: ctx.root, + outFile: operationsTypesFile, + }); let outcome: ApplyOutcome; try { @@ -220,5 +231,6 @@ async function migrateHolding( : {}), ...outcome, typesFile, + operationsTypesFile, }; } diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 9d71adaa7..7f082e410 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -1,4 +1,5 @@ import fs from "node:fs"; +import { createRequire } from "node:module"; import os from "node:os"; import path from "node:path"; @@ -43,6 +44,13 @@ const builder = path.resolve( import.meta.dirname, "../../schema-builder/index.ts", ); +const operationsModule = path.resolve( + import.meta.dirname, + "../../../plugins/database/operations.ts", +); +const zodPackage = path.dirname( + createRequire(import.meta.url).resolve("zod/package.json"), +); const roots: string[] = []; function writeSchema(root: string, tables: string): void { @@ -137,6 +145,37 @@ describe("runMigrate", () => { expect(fs.existsSync(report.typesFile)).toBe(true); }); + test("regenerates database-operations.d.ts from server/database/routes", async () => { + const ctx = app(`notes: table("notes", { id: id(), body: text() })`); + fs.mkdirSync(path.join(ctx.root, "node_modules")); + fs.symlinkSync(zodPackage, path.join(ctx.root, "node_modules/zod"), "dir"); + const routes = path.join(ctx.root, "server/database/routes"); + fs.mkdirSync(routes, { recursive: true }); + fs.writeFileSync( + path.join(routes, "notes.ts"), + `import { z } from "zod"; + import { defineOperation } from ${JSON.stringify(operationsModule)}; + export const getNote = defineOperation({ + name: "notes.get", + method: "GET", + input: z.object({ id: z.number() }), + output: z.object({ id: z.number(), body: z.string().nullable() }), + authorize: () => true, + execute: ({ input, db }) => db.notes.find(input.id), + });`, + ); + resolveEnvBranch.mockResolvedValue(null); + + const report = await runMigrate(ctx, { interactive: false }); + + expect(report.operationsTypesFile).toBe( + path.join(ctx.root, "shared/appkit-types/database-operations.d.ts"), + ); + expect(fs.readFileSync(report.operationsTypesFile, "utf-8")).toContain( + '"notes.get"', + ); + }); + test("does not apply when the implicit app schema would shadow tables left in public", async () => { const ctx = app(`notes: table("notes", { id: id(), body: text() })`); detectTablesLeftInPublic.mockResolvedValue( diff --git a/packages/shared/src/cli/commands/db/migrate.test.ts b/packages/shared/src/cli/commands/db/migrate.test.ts index 440f1426f..38c833b7f 100644 --- a/packages/shared/src/cli/commands/db/migrate.test.ts +++ b/packages/shared/src/cli/commands/db/migrate.test.ts @@ -44,6 +44,10 @@ afterEach(() => { }); const typesFile = path.join(process.cwd(), "shared/appkit-types/database.d.ts"); +const operationsTypesFile = path.join( + process.cwd(), + "shared/appkit-types/database-operations.d.ts", +); describe("appkit db migrate", () => { test("is registered under the db group", () => { @@ -64,6 +68,7 @@ describe("appkit db migrate", () => { }, applied: ["0001_migration"], typesFile, + operationsTypesFile, }); await dbCommand.parseAsync(["migrate"], { from: "user" }); @@ -82,11 +87,19 @@ describe("appkit db migrate", () => { expect(printed).toContain( `Generated ${path.join("shared/appkit-types/database.d.ts")}`, ); + expect(printed).toContain( + `Generated ${path.join("shared/appkit-types/database-operations.d.ts")}`, + ); expect(process.exitCode).toBeUndefined(); }); test("reports an unchanged schema and an up-to-date branch", async () => { - runMigrate.mockResolvedValue({ generated: null, applied: [], typesFile }); + runMigrate.mockResolvedValue({ + generated: null, + applied: [], + typesFile, + operationsTypesFile, + }); await dbCommand.parseAsync(["migrate"], { from: "user" }); @@ -101,6 +114,7 @@ describe("appkit db migrate", () => { applied: ["0001_migration"], adopted: ["0000_baseline"], typesFile, + operationsTypesFile, }); await dbCommand.parseAsync(["migrate"], { from: "user" }); @@ -126,6 +140,7 @@ describe("appkit db migrate", () => { breaking: [drop], applied: ["0002_migration"], typesFile, + operationsTypesFile, }); await dbCommand.parseAsync(["migrate"], { from: "user" }); @@ -151,6 +166,7 @@ describe("appkit db migrate", () => { dataDependent: [unique], applied: ["0002_migration"], typesFile, + operationsTypesFile, }); await dbCommand.parseAsync(["migrate"], { from: "user" }); @@ -168,6 +184,7 @@ describe("appkit db migrate", () => { applied: [], notApplied: "no branch configured — run appkit db init", typesFile, + operationsTypesFile, }); await dbCommand.parseAsync(["migrate"], { from: "user" }); diff --git a/packages/shared/src/cli/commands/db/migrate.ts b/packages/shared/src/cli/commands/db/migrate.ts index 5ed58034a..387dce011 100644 --- a/packages/shared/src/cli/commands/db/migrate.ts +++ b/packages/shared/src/cli/commands/db/migrate.ts @@ -35,7 +35,7 @@ async function runDbMigrate(): Promise { export const dbMigrateCommand = new Command("migrate") .description( - "Generate a migration from config/database/schema.ts, apply pending migrations to the .env branch, and regenerate database.d.ts", + "Generate a migration from config/database/schema.ts, apply pending migrations to the .env branch, and regenerate database.d.ts and database-operations.d.ts", ) .addHelpText( "after", diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index ec23aa0a0..53e525fe2 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -84,4 +84,5 @@ export function printMigrateReport(report: MigrateReport): void { } ok(`Generated ${relative(report.typesFile)}`); + ok(`Generated ${relative(report.operationsTypesFile)}`); } diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 6a1e7597c..3cbf8d0de 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -18,6 +18,7 @@ export interface MigrateReport { readonly dataDependent?: readonly string[]; readonly notApplied?: string; readonly typesFile: string; + readonly operationsTypesFile: string; } /** From a43a9b8d83e92d1d94d6324a271e762887ed5fe3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:41:34 +0100 Subject: [PATCH 292/317] docs: describe the CLI's PGSSLMODE refusal and when the history lock is left Co-authored-by: Isaac Signed-off-by: ditadi --- designs/001_DatabaseDevelopmentFlow.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/designs/001_DatabaseDevelopmentFlow.md b/designs/001_DatabaseDevelopmentFlow.md index 4baed2e6c..63c92ef14 100644 --- a/designs/001_DatabaseDevelopmentFlow.md +++ b/designs/001_DatabaseDevelopmentFlow.md @@ -369,8 +369,9 @@ 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, when it exits, and on SIGINT or SIGTERM. Only a kill the process cannot +catch, such as SIGKILL, 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 `appkit db` command runs in the checkout, the developer deletes the file and reruns the command. The template's `.gitignore` lists the file. @@ -747,6 +748,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. From 9ef6a79f1af62ed818f973fbf979922e72706d29 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:42:12 +0100 Subject: [PATCH 293/317] chore: measure the appkit bundle-size baseline after the post-main changes Co-authored-by: Isaac Signed-off-by: ditadi --- bundle-size-baseline.json | 74 +++++++++++++++++++-------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/bundle-size-baseline.json b/bundle-size-baseline.json index bb66203a1..f64beab17 100644 --- a/bundle-size-baseline.json +++ b/bundle-size-baseline.json @@ -3,25 +3,25 @@ { "name": "@databricks/appkit", "tarball": { - "packed": 1498992, - "unpacked": 5110002 + "packed": 1498790, + "unpacked": 5109808 }, "dist": { "total": { - "raw": 5094188, - "gzip": 1750148 + "raw": 5093994, + "gzip": 1749936 }, "js": { - "raw": 1538878, - "gzip": 549227 + "raw": 1538902, + "gzip": 549174 }, "types": { - "raw": 497627, - "gzip": 180019 + "raw": 497790, + "gzip": 180058 }, "maps": { - "raw": 3046888, - "gzip": 1017084 + "raw": 3046507, + "gzip": 1016886 }, "css": { "raw": 0, @@ -36,17 +36,17 @@ "entries": [ { "id": ".", - "gzip": 123604, + "gzip": 123615, "composition": { - "initialGzip": 121114, + "initialGzip": 121125, "lazyGzip": 2490, - "totalGzip": 123604, - "own": 387305, + "totalGzip": 123615, + "own": 387319, "nodeModules": null, "chunks": [ { "label": "index.js", - "gzip": 116438, + "gzip": 116449, "kind": "initial" }, { @@ -64,17 +64,17 @@ }, { "id": "./beta", - "gzip": 134562, + "gzip": 134528, "composition": { - "initialGzip": 129907, - "lazyGzip": 4655, - "totalGzip": 134562, - "own": 390164, + "initialGzip": 129864, + "lazyGzip": 4664, + "totalGzip": 134528, + "own": 390107, "nodeModules": null, "chunks": [ { "label": "beta.js", - "gzip": 102888, + "gzip": 102845, "kind": "initial" }, { @@ -119,7 +119,7 @@ }, { "label": "index.js", - "gzip": 4142, + "gzip": 4151, "kind": "lazy" }, { @@ -142,17 +142,17 @@ }, { "id": "./beta/database-tooling", - "gzip": 32727, + "gzip": 35240, "composition": { - "initialGzip": 32727, + "initialGzip": 35240, "lazyGzip": 0, - "totalGzip": 32727, - "own": 96378, + "totalGzip": 35240, + "own": 103755, "nodeModules": null, "chunks": [ { "label": "index.js", - "gzip": 32727, + "gzip": 35240, "kind": "initial" } ] @@ -160,12 +160,12 @@ }, { "id": "./testing", - "gzip": 86991, + "gzip": 87002, "composition": { "initialGzip": 47639, - "lazyGzip": 39352, - "totalGzip": 86991, - "own": 251648, + "lazyGzip": 39363, + "totalGzip": 87002, + "own": 251662, "nodeModules": null, "chunks": [ { @@ -185,7 +185,7 @@ }, { "label": "index.js", - "gzip": 35002, + "gzip": 35013, "kind": "lazy" }, { @@ -221,17 +221,17 @@ }, { "id": "./type-generator", - "gzip": 31764, + "gzip": 31777, "composition": { - "initialGzip": 31764, + "initialGzip": 31777, "lazyGzip": 0, - "totalGzip": 31764, - "own": 91490, + "totalGzip": 31777, + "own": 91504, "nodeModules": null, "chunks": [ { "label": "index.js", - "gzip": 31764, + "gzip": 31777, "kind": "initial" } ] From a3c49e92fd4a4660325b658a6f0163e4a3471ce8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:45:26 +0100 Subject: [PATCH 294/317] fix(appkit): load schema.ts in introspect with main's loader and await the discard The 03 merge removed the CLI option of the runtime loader and made discardMigrationFiles async. introspect now loads schema.ts through loadDatabaseSchema and waits for the discard before it reports the failure. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/introspect/index.ts | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index ee54f616b..7df4bd1a2 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -1,11 +1,11 @@ import fs from "node:fs"; import path from "node:path"; +import { DEFAULT_SCHEMA_FILE } from "../../../plugins/database/load-schema"; import { - DEFAULT_SCHEMA_FILE, - loadDefaultDatabaseSchema, -} from "../../../plugins/database/load-schema"; -import { writeDatabaseTypes } from "../../../type-generator/database"; + loadDatabaseSchema, + writeDatabaseTypes, +} from "../../../type-generator/database"; import { editedReason, markMigrationsApplied, @@ -150,7 +150,7 @@ function refuseDropsOfUnexpressed( async function readPreviousSchema(root: string): Promise { if (!fs.existsSync(path.join(root, DEFAULT_SCHEMA_FILE))) return null; try { - return await loadDefaultDatabaseSchema(root, { showImportError: true }); + return await loadDatabaseSchema(path.join(root, DEFAULT_SCHEMA_FILE)); } 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.`, @@ -280,11 +280,9 @@ async function introspectHolding( if (backsUp) writeFileAtomic(backupFile, previous); fs.mkdirSync(path.dirname(schemaFile), { recursive: true }); writeFileAtomic(schemaFile, rendered.source); - let schema: Awaited>; + let schema: Schema; try { - schema = await loadDefaultDatabaseSchema(ctx.root, { - showImportError: true, - }); + schema = await loadDatabaseSchema(schemaFile); } 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}".`, @@ -338,7 +336,7 @@ async function introspectHolding( writeOrRemove(schemaFile, previous); if (backsUp) writeOrRemove(backupFile, previousBackup); writeOrRemove(typesFile, previousTypes); - if (migration) discardMigrationFiles(lock, migration); + 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)}`, From 07ba7d73e73728211f5061767a66abb5a956118b Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:49:09 +0100 Subject: [PATCH 295/317] feat(appkit): regenerate database-operations.d.ts in appkit db introspect introspect and migrate now share writeGeneratedTypes, which writes database.d.ts and then runs main's operation generator. A failed introspect puts back both type files and routes.gen.ts with the rest of what it wrote. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/introspect/index.ts | 28 +++++------ .../introspect/tests/introspect.test.ts | 37 ++++++++++++++- .../appkit/src/database/tooling/migrate.ts | 46 +++++++++++++++---- .../database/generate-operations.ts | 2 +- .../src/cli/commands/db/introspect.test.ts | 4 ++ .../shared/src/cli/commands/db/introspect.ts | 5 +- packages/shared/src/cli/commands/db/output.ts | 1 + .../src/cli/commands/db/tooling-contract.ts | 1 + 8 files changed, 97 insertions(+), 27 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 7df4bd1a2..511ef551b 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -2,10 +2,7 @@ import fs from "node:fs"; import path from "node:path"; import { DEFAULT_SCHEMA_FILE } from "../../../plugins/database/load-schema"; -import { - loadDatabaseSchema, - writeDatabaseTypes, -} from "../../../type-generator/database"; +import { loadDatabaseSchema } from "../../../type-generator/database"; import { editedReason, markMigrationsApplied, @@ -18,7 +15,7 @@ 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 { DATABASE_TYPES_PATH } from "../migrate"; +import { generatedTypesOf, writeGeneratedTypes } from "../migrate"; import { breakingStatements, discardMigrationFiles, @@ -62,6 +59,7 @@ export interface IntrospectReport { /** 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. */ @@ -166,9 +164,8 @@ async function readPreviousSchema(root: string): Promise { * 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, - * database.d.ts and the migrations folder. One command at a time owns the - * checkout's history. + * 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, @@ -269,10 +266,12 @@ async function introspectHolding( ); } const backupFile = `${schemaFile}.bak`; - const typesFile = path.join(ctx.root, DATABASE_TYPES_PATH); + const generatedTypes = generatedTypesOf(ctx.root); const previous = readIfExists(schemaFile); const previousBackup = readIfExists(backupFile); - const previousTypes = readIfExists(typesFile); + 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[] = []; @@ -326,7 +325,7 @@ async function introspectHolding( ); } } - await writeDatabaseTypes(schema, typesFile); + await writeGeneratedTypes(ctx.root, schema); // The database already holds what the migrations describe; recording is the last step. recorded = [...unrecorded, ...(migration ? [migration.tag] : [])]; if (recorded.length > 0) { @@ -335,7 +334,9 @@ async function introspectHolding( } catch (error) { writeOrRemove(schemaFile, previous); if (backsUp) writeOrRemove(backupFile, previousBackup); - writeOrRemove(typesFile, previousTypes); + for (const [file, contents] of previousTypes) { + writeOrRemove(file, contents); + } if (migration) await discardMigrationFiles(lock, migration); if (error instanceof IntrospectRefusedError) throw error; throw new Error( @@ -367,7 +368,8 @@ async function introspectHolding( approximated: rendered.approximated, migration, recorded, - typesFile, + typesFile: generatedTypes.typesFile, + operationsTypesFile: generatedTypes.operationsTypesFile, }; }); } diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index eb80c9d95..8c4995ca4 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -1,4 +1,5 @@ import fs from "node:fs"; +import { createRequire } from "node:module"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; @@ -47,6 +48,14 @@ const { writeDatabaseTypes } = await vi.importActual< 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"; @@ -320,6 +329,31 @@ describe("runIntrospect", () => { }); }); + 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], @@ -948,7 +982,7 @@ export const schema = defineSchema( "disk full", ], ])( - "when %s fails, schema.ts, its backup, database.d.ts and the migrations are put back, so a rerun records", + "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, @@ -963,6 +997,7 @@ export const schema = defineSchema( 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); diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index db2d05974..1f6d7deb6 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -9,6 +9,7 @@ import { loadDatabaseSchema, writeDatabaseTypes, } from "../../type-generator/database"; +import { ROUTES_FILE } from "../../type-generator/database/generate-operations"; import { applyPendingMigrations, MigrationApplyError, @@ -45,7 +46,39 @@ function requireSchemaFile(root: string): void { const TYPES_DIR = "shared/appkit-types"; -export const DATABASE_TYPES_PATH = path.join(TYPES_DIR, DATABASE_TYPES_FILE); +/** What migrate and introspect regenerate from schema.ts and server/database/routes. */ +interface GeneratedTypes { + readonly typesFile: string; + readonly operationsTypesFile: string; + /** The routes registry main's operation generator writes next to the routes. */ + readonly routesFile: string; +} + +export function generatedTypesOf(root: string): GeneratedTypes { + return { + typesFile: path.join(root, TYPES_DIR, DATABASE_TYPES_FILE), + operationsTypesFile: path.join( + root, + TYPES_DIR, + DATABASE_OPERATIONS_TYPES_FILE, + ), + routesFile: path.join(root, ROUTES_FILE), + }; +} + +/** Regenerate database.d.ts, then the operation contracts, as `appkit generate-types` does. */ +export async function writeGeneratedTypes( + root: string, + schema: Schema, +): Promise { + const generated = generatedTypesOf(root); + await writeDatabaseTypes(schema, generated.typesFile); + await generateDatabaseOperations({ + appRoot: root, + outFile: generated.operationsTypesFile, + }); + return generated; +} export interface MigrateReport { /** The migration written by this run; null when schema.ts matches the latest snapshot. */ @@ -203,17 +236,10 @@ async function migrateHolding( // The types follow schema.ts and server/database/routes alone, so they are // current even if applying fails. - const typesFile = path.join(ctx.root, TYPES_DIR, DATABASE_TYPES_FILE); - await writeDatabaseTypes(schema, typesFile); - const operationsTypesFile = path.join( + const { typesFile, operationsTypesFile } = await writeGeneratedTypes( ctx.root, - TYPES_DIR, - DATABASE_OPERATIONS_TYPES_FILE, + schema, ); - await generateDatabaseOperations({ - appRoot: ctx.root, - outFile: operationsTypesFile, - }); let outcome: ApplyOutcome; try { diff --git a/packages/appkit/src/type-generator/database/generate-operations.ts b/packages/appkit/src/type-generator/database/generate-operations.ts index 92d5ae165..e4778d94f 100644 --- a/packages/appkit/src/type-generator/database/generate-operations.ts +++ b/packages/appkit/src/type-generator/database/generate-operations.ts @@ -23,7 +23,7 @@ export const DATABASE_OPERATIONS_TYPES_FILE = "database-operations.d.ts"; /** Application-relative POSIX paths of the operation conventions. */ const ROUTES_DIR = "server/database/routes"; -const ROUTES_FILE = "server/database/routes.gen.ts"; +export const ROUTES_FILE = "server/database/routes.gen.ts"; const SCHEMA_FILE = "config/database/schema.ts"; /** Fixed header shared by both generated files. */ diff --git a/packages/shared/src/cli/commands/db/introspect.test.ts b/packages/shared/src/cli/commands/db/introspect.test.ts index a0d9711cd..4435f332c 100644 --- a/packages/shared/src/cli/commands/db/introspect.test.ts +++ b/packages/shared/src/cli/commands/db/introspect.test.ts @@ -52,6 +52,7 @@ const report = { }, recorded: ["0000_baseline"], typesFile: `${process.cwd()}/shared/appkit-types/database.d.ts`, + operationsTypesFile: `${process.cwd()}/shared/appkit-types/database-operations.d.ts`, }; beforeEach(() => { @@ -106,6 +107,9 @@ describe("appkit db introspect", () => { "Recorded 0000_baseline as applied on dev-alice-3f9a2c: the branch already has what it describes", ); expect(printed).toContain("Generated shared/appkit-types/database.d.ts"); + expect(printed).toContain( + "Generated shared/appkit-types/database-operations.d.ts", + ); expect(process.exitCode).toBeUndefined(); }); diff --git a/packages/shared/src/cli/commands/db/introspect.ts b/packages/shared/src/cli/commands/db/introspect.ts index 2e783759e..948b3dc10 100644 --- a/packages/shared/src/cli/commands/db/introspect.ts +++ b/packages/shared/src/cli/commands/db/introspect.ts @@ -41,8 +41,9 @@ NNNN_introspect, once the branch has applied every committed migration. The migration is recorded as applied, so introspect runs only on your dev or session branch; \`appkit db init\` creates one, forked from the branch the default databricks.yml target binds, else the project's default branch. The deployed -app adopts 0000_baseline on start when its tables already exist. If anything -fails, schema.ts, database.d.ts and the migrations are left as they were. +app adopts 0000_baseline on start when its tables already exist. It also +regenerates database.d.ts and database-operations.d.ts. If anything fails, +schema.ts, the generated types and the migrations are left as they were. Examples: $ appkit db introspect diff --git a/packages/shared/src/cli/commands/db/output.ts b/packages/shared/src/cli/commands/db/output.ts index b0efccd00..4ab91e924 100644 --- a/packages/shared/src/cli/commands/db/output.ts +++ b/packages/shared/src/cli/commands/db/output.ts @@ -131,4 +131,5 @@ export function printIntrospectReport(report: IntrospectReport): void { ); } ok(`Generated ${relative(report.typesFile)}`); + ok(`Generated ${relative(report.operationsTypesFile)}`); } diff --git a/packages/shared/src/cli/commands/db/tooling-contract.ts b/packages/shared/src/cli/commands/db/tooling-contract.ts index 17c633f88..e90397e10 100644 --- a/packages/shared/src/cli/commands/db/tooling-contract.ts +++ b/packages/shared/src/cli/commands/db/tooling-contract.ts @@ -39,6 +39,7 @@ export interface IntrospectReport { readonly migration: GeneratedMigration | null; readonly recorded: readonly string[]; readonly typesFile: string; + readonly operationsTypesFile: string; } /** From 5b5509b7e75097af9a29869aec25ca94542f7381 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:49:39 +0100 Subject: [PATCH 296/317] docs: describe introspect's schema.ts.bak and its refusal to drop what it cannot express Co-authored-by: Isaac Signed-off-by: ditadi --- designs/001_DatabaseDevelopmentFlow.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/designs/001_DatabaseDevelopmentFlow.md b/designs/001_DatabaseDevelopmentFlow.md index 63c92ef14..b6acf3b73 100644 --- a/designs/001_DatabaseDevelopmentFlow.md +++ b/designs/001_DatabaseDevelopmentFlow.md @@ -564,6 +564,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 | From a2b6ffe4aafe2613701cb4a56ae4932f107e6df7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:54:13 +0100 Subject: [PATCH 297/317] fix(appkit): load schema.ts in init, clean and seed with main's loader The 03 merge removed the CLI option of the runtime loader, so init, clean and seed now load schema.ts through loadDatabaseSchema. The init test reports carry the operation types file migrate and introspect now return. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/clean.ts | 11 +++++++---- packages/appkit/src/database/tooling/init.ts | 5 +++-- packages/appkit/src/database/tooling/seed.ts | 5 +++-- .../appkit/src/database/tooling/tests/init.pg.test.ts | 9 +++++---- .../src/cli/commands/db/init-clean-seed.test.ts | 2 ++ 5 files changed, 20 insertions(+), 12 deletions(-) diff --git a/packages/appkit/src/database/tooling/clean.ts b/packages/appkit/src/database/tooling/clean.ts index a19bb4891..938635e79 100644 --- a/packages/appkit/src/database/tooling/clean.ts +++ b/packages/appkit/src/database/tooling/clean.ts @@ -1,6 +1,9 @@ +import path from "node:path"; + import type { PoolClient } from "pg"; -import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +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"; @@ -227,9 +230,9 @@ export interface CleanReport { async function cleanTarget(ctx: DbContext) { requireSchemaFile(ctx.root, "clean"); const branch = await writableEnvBranch(ctx, "clean"); - const schema = await loadDefaultDatabaseSchema(ctx.root, { - showImportError: true, - }); + const schema = await loadDatabaseSchema( + path.join(ctx.root, DEFAULT_SCHEMA_FILE), + ); return { branch: branch.name, schemaName: schema.$schemaName }; } diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index ac0e18cba..0b9cc16d0 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -4,7 +4,8 @@ import path from "node:path"; import dotenv from "dotenv"; import type { PoolClient } from "pg"; -import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +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"; @@ -661,7 +662,7 @@ async function initHolding( const hasSchema = hasSchemaFile(ctx.root); const schemaName = hasSchema && request.kind === "locked" - ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) + ? (await loadDatabaseSchema(path.join(ctx.root, DEFAULT_SCHEMA_FILE))) .$schemaName : DEFAULT_SCHEMA_NAME; diff --git a/packages/appkit/src/database/tooling/seed.ts b/packages/appkit/src/database/tooling/seed.ts index 9d08c2a51..94b03d0e0 100644 --- a/packages/appkit/src/database/tooling/seed.ts +++ b/packages/appkit/src/database/tooling/seed.ts @@ -1,7 +1,8 @@ import fs from "node:fs"; import path from "node:path"; -import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +import { DEFAULT_SCHEMA_FILE } from "../../plugins/database/load-schema"; +import { loadDatabaseSchema } from "../../type-generator/database"; import { quoteIdentifier } from "../migrations/apply"; import { DEFAULT_SCHEMA_NAME } from "../schema-builder/define-schema"; import { runInTransaction } from "./branch-sql"; @@ -31,7 +32,7 @@ export async function runSeed(ctx: DbContext): Promise { } const branch = await writableEnvBranch(ctx, "seed"); const schemaName = hasSchemaFile(ctx.root) - ? (await loadDefaultDatabaseSchema(ctx.root, { showImportError: true })) + ? (await loadDatabaseSchema(path.join(ctx.root, DEFAULT_SCHEMA_FILE))) .$schemaName : DEFAULT_SCHEMA_NAME; const searchPath = diff --git a/packages/appkit/src/database/tooling/tests/init.pg.test.ts b/packages/appkit/src/database/tooling/tests/init.pg.test.ts index 9721d1b34..fd0d60bcd 100644 --- a/packages/appkit/src/database/tooling/tests/init.pg.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.pg.test.ts @@ -20,7 +20,8 @@ vi.mock("../context", async (importOriginal) => ({ withBranchPool, })); -import { loadDefaultDatabaseSchema } from "../../../plugins/database/load-schema"; +import { DEFAULT_SCHEMA_FILE } from "../../../plugins/database/load-schema"; +import { loadDatabaseSchema } from "../../../type-generator/database"; import { applyPendingMigrations } from "../../migrations/apply"; import { migrationsFolder } from "../../migrations/paths"; import { hashOf } from "../../migrations/tests/fixtures"; @@ -106,9 +107,9 @@ describe.skipIf(!url)("runInit against Postgres", () => { ).rows[0]?.owner; async function generate(appRoot: string) { - const schema = await loadDefaultDatabaseSchema(appRoot, { - showImportError: true, - }); + const schema = await loadDatabaseSchema( + path.join(appRoot, DEFAULT_SCHEMA_FILE), + ); await withHistoryLock(appRoot, "migrate", (lock) => generateMigrationFiles(lock, { schema, interactive: false }), ); diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index c826e7413..5ce030e8a 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -41,6 +41,7 @@ const migrate = { generated: null, applied: ["0000_migration"], typesFile: `${process.cwd()}/shared/appkit-types/database.d.ts`, + operationsTypesFile: `${process.cwd()}/shared/appkit-types/database-operations.d.ts`, }; const report = { mode: "dev", @@ -354,6 +355,7 @@ describe("appkit db init", () => { }, recorded: ["0000_baseline"], typesFile: migrate.typesFile, + operationsTypesFile: migrate.operationsTypesFile, }, rebuilt: { clean: { From 2a377a133843af842862f4a89a34bcff87b1ae2a Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:55:05 +0100 Subject: [PATCH 298/317] chore: measure the appkit bundle-size baseline after the post-main changes Co-authored-by: Isaac Signed-off-by: ditadi --- bundle-size-baseline.json | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/bundle-size-baseline.json b/bundle-size-baseline.json index 7c4b831b5..5b202ed79 100644 --- a/bundle-size-baseline.json +++ b/bundle-size-baseline.json @@ -3,25 +3,25 @@ { "name": "@databricks/appkit", "tarball": { - "packed": 1605479, - "unpacked": 5475395 + "packed": 1605551, + "unpacked": 5476020 }, "dist": { "total": { - "raw": 5459581, - "gzip": 1866487 + "raw": 5460206, + "gzip": 1866593 }, "js": { - "raw": 1662190, - "gzip": 589471 + "raw": 1662583, + "gzip": 589547 }, "types": { "raw": 509717, "gzip": 185285 }, "maps": { - "raw": 3276879, - "gzip": 1087913 + "raw": 3277111, + "gzip": 1087943 }, "css": { "raw": 0, @@ -142,17 +142,17 @@ }, { "id": "./beta/database-tooling", - "gzip": 58066, + "gzip": 57006, "composition": { - "initialGzip": 58066, + "initialGzip": 57006, "lazyGzip": 0, - "totalGzip": 58066, - "own": 173766, + "totalGzip": 57006, + "own": 170568, "nodeModules": null, "chunks": [ { "label": "index.js", - "gzip": 58066, + "gzip": 57006, "kind": "initial" } ] From 93ab021fb822f12e5ac66e1e1b60f3564da7a4f1 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 17:56:42 +0100 Subject: [PATCH 299/317] fix(appkit): load schema.ts in db verify with main's loader The 03 merge removed the CLI option of the runtime loader. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/verify.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index a34a016fd..8d6a12792 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -3,8 +3,9 @@ import path from "node:path"; import type { PoolClient } from "pg"; -import { loadDefaultDatabaseSchema } from "../../plugins/database/load-schema"; +import { DEFAULT_SCHEMA_FILE } from "../../plugins/database/load-schema"; import { diagnoseSchema } from "../../plugins/database/schema-check"; +import { loadDatabaseSchema } from "../../type-generator/database"; import { readMigrationDrift } from "../migrations/apply"; import { journalFile, @@ -131,9 +132,9 @@ async function verifyLocal(ctx: DbContext): Promise { const env = await resolveEnvBranch(ctx); if (!env) throw new Error(`Did not verify: ${NO_ENV_BRANCH}.`); const branch = env.branch.name; - const schema = await loadDefaultDatabaseSchema(ctx.root, { - showImportError: true, - }); + const schema = await loadDatabaseSchema( + path.join(ctx.root, DEFAULT_SCHEMA_FILE), + ); return withBranchPool(ctx, async (pool) => { const client = await pool.connect(); try { From 65d1f0b11e8fc78cb22054e4207d5d534d159cbb Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:00:45 +0100 Subject: [PATCH 300/317] docs: state the template's exit 1 for every app and roll out on a scaffolded app Rollout step 4 now says the template's process.exit(1) on a failed start applies to every app it scaffolds. The done criteria of steps 2 to 4 use a throwaway app scaffolded from the template instead of the dev-playground. Co-authored-by: Isaac Signed-off-by: ditadi --- designs/001_DatabaseDevelopmentFlow.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/designs/001_DatabaseDevelopmentFlow.md b/designs/001_DatabaseDevelopmentFlow.md index b6acf3b73..6cf725e11 100644 --- a/designs/001_DatabaseDevelopmentFlow.md +++ b/designs/001_DatabaseDevelopmentFlow.md @@ -782,13 +782,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 From 2de072946b64ce982ac75a11dc86f52021db9863 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:02:29 +0100 Subject: [PATCH 301/317] fix(appkit): load schema.ts in db check with main's loader The 03 merge removed the CLI option of the runtime loader. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/check.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts index 7631a8742..c480b363d 100644 --- a/packages/appkit/src/database/tooling/check.ts +++ b/packages/appkit/src/database/tooling/check.ts @@ -4,10 +4,8 @@ import path from "node:path"; import { MIGRATION_HISTORY_REWRITE } from "shared"; import { z } from "zod"; -import { - DEFAULT_SCHEMA_FILE, - loadDefaultDatabaseSchema, -} from "../../plugins/database/load-schema"; +import { DEFAULT_SCHEMA_FILE } from "../../plugins/database/load-schema"; +import { loadDatabaseSchema } from "../../type-generator/database"; import { type JournalEntry, MigrationFilesError, @@ -183,9 +181,9 @@ export async function runCheck(ctx: DbContext): Promise { // drizzle-kit diffs from the latest snapshot, which must exist. if (entries.length === 0 || links.at(-1)) { - const schema = await loadDefaultDatabaseSchema(ctx.root, { - showImportError: true, - }); + const schema = await loadDatabaseSchema( + path.join(ctx.root, DEFAULT_SCHEMA_FILE), + ); if (await hasUnmigratedChanges(folder, schema)) { const last = entries.at(-1)?.tag; problems.push( From fc6bcb8e382ae851715b3ba0b06879a6c52b8a81 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:06:28 +0100 Subject: [PATCH 302/317] test: answer the schema USAGE check in the dev-playground database fake Setup now reads whether its role may use the app schema before the catalog check. The playground's in-memory edge answered every pg_catalog query with column rows, so setup read a missing USAGE and failed. Co-authored-by: Isaac Signed-off-by: ditadi --- .../server/testing/database-edges.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) 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"); From ed4dbb2a36e4b32b9a10fbfbccfc3abf7ed95420 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:31:29 +0100 Subject: [PATCH 303/317] fix(appkit): read the branch only from a whole LAKEBASE_ENDPOINT resource name A value with text around projects/

/branches//endpoints/ named a branch the refusal of dev and session branches then checked, though the value is not the app's endpoint. Anchor the match so such a value is refused as naming no branch. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/plugins/database/migrate-on-start.ts | 4 +++- .../database/tests/migrate-on-start.test.ts | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/appkit/src/plugins/database/migrate-on-start.ts b/packages/appkit/src/plugins/database/migrate-on-start.ts index 851bf09f9..548f8d484 100644 --- a/packages/appkit/src/plugins/database/migrate-on-start.ts +++ b/packages/appkit/src/plugins/database/migrate-on-start.ts @@ -70,7 +70,9 @@ export function decideMigrateOnStart( /** The branch id in LAKEBASE_ENDPOINT (projects/

/branches//endpoints/). */ function endpointBranch(endpoint: string | undefined): string | undefined { - return endpoint?.match(/\/branches\/([^/]+)\//)?.[1]; + return endpoint?.match( + /^projects\/[^/]+\/branches\/([^/]+)\/endpoints\/[^/]+$/, + )?.[1]; } const DEVELOPMENT_BRANCH_OWNERS: Record = { diff --git a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts index afae1f367..e16d4921b 100644 --- a/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts +++ b/packages/appkit/src/plugins/database/tests/migrate-on-start.test.ts @@ -246,6 +246,21 @@ describe("migrateOnStart", () => { "ep-abc.database.cloud.databricks.com", 'LAKEBASE_ENDPOINT is "ep-abc.database.cloud.databricks.com"', ], + [ + "an endpoint path inside other text", + "https://host/projects/p/branches/production/endpoints/primary", + 'LAKEBASE_ENDPOINT is "https://host/projects/p/branches/production/endpoints/primary"', + ], + [ + "an endpoint path with a suffix", + "projects/p/branches/production/endpoints/primary/extra", + 'LAKEBASE_ENDPOINT is "projects/p/branches/production/endpoints/primary/extra"', + ], + [ + "a branches segment without the project and endpoint", + "x/branches/production/y", + 'LAKEBASE_ENDPOINT is "x/branches/production/y"', + ], ])( "a LAKEBASE_ENDPOINT that names no branch (%s) is refused: the branch cannot be checked", async (_label, endpoint, named) => { From 0a9a68881c523cb10596219a9fb255993899112a Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:32:15 +0100 Subject: [PATCH 304/317] docs: say the dev branch refusal covers only a start that migrates Name the LAKEBASE_ENDPOINT resource name that migrate on start reads the branch from, and that a start without the flag or the app's identity skips the refusal with the migration. Co-authored-by: Isaac Signed-off-by: ditadi --- designs/001_DatabaseDevelopmentFlow.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/designs/001_DatabaseDevelopmentFlow.md b/designs/001_DatabaseDevelopmentFlow.md index 7b3c4ae52..8c928f4f6 100644 --- a/designs/001_DatabaseDevelopmentFlow.md +++ b/designs/001_DatabaseDevelopmentFlow.md @@ -228,7 +228,9 @@ runs only when `APPKIT_DB_MIGRATE_ON_START=true` and the process connects as the 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. @@ -241,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: From 0feae97ddbf69f930b1c62e9798ef801284edcb8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:35:54 +0100 Subject: [PATCH 305/317] fix(appkit): keep the history lock when another listener handles the signal On SIGINT or SIGTERM the lock was released even when another listener kept the process running, so the command went on writing the history after another command could take the lock. Release and re-raise only when the lock's handler is the one ending the process; otherwise the exit listener releases it. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/history-lock.ts | 15 ++++--- .../tooling/tests/history-lock.test.ts | 40 +++++++++++++++++-- 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/packages/appkit/src/database/tooling/history-lock.ts b/packages/appkit/src/database/tooling/history-lock.ts index 4ff70beb2..75c962e7a 100644 --- a/packages/appkit/src/database/tooling/history-lock.ts +++ b/packages/appkit/src/database/tooling/history-lock.ts @@ -81,9 +81,10 @@ function heldError(root: string, file: string): Error { * 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. - * A process killed otherwise leaves the file behind: the next command reports - * it as stale, and it is deleted by hand, never taken over. + * 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, @@ -126,11 +127,13 @@ export async function withHistoryLock( if (readOwner(file)?.token === owner.token) fs.rmSync(file, { force: true }); }; - // A listener replaces the signal's default exit, so re-raise it once the lock - // is gone; when other listeners remain, ending the process is theirs. + // 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(); - if (process.listenerCount(signal) === 0) process.kill(process.pid, signal); + process.kill(process.pid, signal); }; process.on("exit", release); for (const signal of RELEASE_SIGNALS) process.on(signal, onSignal); diff --git a/packages/appkit/src/database/tooling/tests/history-lock.test.ts b/packages/appkit/src/database/tooling/tests/history-lock.test.ts index c743183db..f9346c8b0 100644 --- a/packages/appkit/src/database/tooling/tests/history-lock.test.ts +++ b/packages/appkit/src/database/tooling/tests/history-lock.test.ts @@ -18,13 +18,14 @@ function writeLock(root: string, contents: string): void { } /** - * Run a process that takes the lock in root and waits; resolves once it holds - * the lock, with a promise of the signal that ended it. + * Run a process that takes the lock in root, runs whileHeld and waits; resolves + * once it holds the lock, with a promise of the signal that ended it. */ -async function holderProcess(root: string) { +async function holderProcess(root: string, whileHeld = "") { const script = ` const { withHistoryLock } = await import(${JSON.stringify(path.resolve(import.meta.dirname, "../history-lock.ts"))}); await withHistoryLock(${JSON.stringify(root)}, "migrate", async () => { + ${whileHeld} process.stdout.write("held\\n"); await new Promise(() => setInterval(() => undefined, 1000)); });`; @@ -42,7 +43,13 @@ async function holderProcess(root: string) { }); ended.then(() => reject(new Error("the holder exited before holding"))); }); - return { child, ended }; + const output = (text: string) => + new Promise((resolve) => { + child.stdout.on("data", (chunk: Buffer) => { + if (chunk.toString().includes(text)) resolve(); + }); + }); + return { child, ended, output }; } async function failure(promise: Promise): Promise { @@ -175,6 +182,31 @@ describe("withHistoryLock", () => { }, ); + test("a signal another listener handles keeps the lock while the process runs, and its exit releases it", async () => { + const root = tempApp(); + const { child, ended, output } = await holderProcess( + root, + `let signals = 0; + process.on("SIGINT", () => { + signals += 1; + if (signals === 2) process.exit(0); + process.stdout.write("handled\\n"); + });`, + ); + + const handled = output("handled"); + child.kill("SIGINT"); + await handled; + + expect(child.exitCode).toBeNull(); + expect(fs.existsSync(path.join(root, LOCK))).toBe(true); + + child.kill("SIGINT"); + await ended; + expect(child.exitCode).toBe(0); + expect(fs.existsSync(path.join(root, LOCK))).toBe(false); + }); + test("a signal leaves a lock another holder wrote in its place", async () => { const root = tempApp(); const { child, ended } = await holderProcess(root); From 9b674eadbdf3a60bb261f7ded3da760aa27e9b11 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:37:28 +0100 Subject: [PATCH 306/317] fix(appkit): regenerate the types before migrate writes a migration A route module that failed to load made migrate fail after it had written the new migration, without saying it kept the file or what the migration warns about. Write database.d.ts and database-operations.d.ts first, so that failure stops migrate before it writes anything; the types still follow schema.ts when applying fails. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrate.ts | 15 ++++---- .../database/tooling/tests/migrate.test.ts | 36 +++++++++++++++++++ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index cf441e583..912fc9776 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -175,14 +175,9 @@ async function migrateHolding( const schema = await loadDatabaseSchema( path.join(ctx.root, DEFAULT_SCHEMA_FILE), ); - const generated = await generateMigrationFiles(lock, { - schema, - interactive: options.interactive, - }); - const warnings = migrationWarnings(generated); - // The types follow schema.ts and server/database/routes alone, so they are - // current even if applying fails. + // current even if applying fails. Written first, so a route module that + // fails to load stops migrate before it writes a migration. const typesFile = path.join(ctx.root, TYPES_DIR, DATABASE_TYPES_FILE); await writeDatabaseTypes(schema, typesFile); const operationsTypesFile = path.join( @@ -195,6 +190,12 @@ async function migrateHolding( outFile: operationsTypesFile, }); + const generated = await generateMigrationFiles(lock, { + schema, + interactive: options.interactive, + }); + const warnings = migrationWarnings(generated); + let outcome: ApplyOutcome; try { outcome = await applyToEnvBranch(ctx, lock.folder, schema); diff --git a/packages/appkit/src/database/tooling/tests/migrate.test.ts b/packages/appkit/src/database/tooling/tests/migrate.test.ts index 7f082e410..99c462460 100644 --- a/packages/appkit/src/database/tooling/tests/migrate.test.ts +++ b/packages/appkit/src/database/tooling/tests/migrate.test.ts @@ -541,6 +541,42 @@ describe("runMigrate", () => { ); }); + test("a route module that fails to load stops migrate before it writes a migration", async () => { + const ctx = app(`notes: table("notes", { id: id(), body: text() })`); + resolveEnvBranch.mockResolvedValue(null); + await runMigrate(ctx, { interactive: false }); + const folder = path.join(ctx.root, "config/database/migrations"); + const before = historyFiles(folder); + + writeSchema( + ctx.root, + `notes: table("notes", { id: id(), body: text().notNull() })`, + ); + const routes = path.join(ctx.root, "server/database/routes"); + fs.mkdirSync(routes, { recursive: true }); + fs.writeFileSync( + path.join(routes, "notes.ts"), + `throw new Error("route module broke");`, + ); + const error = await runMigrate(ctx, { interactive: false }).catch( + (caught: unknown) => caught, + ); + + expect((error as Error).message).toMatch(/notes\.ts/); + expect(historyFiles(folder)).toEqual(before); + expect(applyPendingMigrations).not.toHaveBeenCalled(); + + fs.rmSync(path.join(routes, "notes.ts")); + const report = await runMigrate(ctx, { interactive: false }); + const setNotNull = + 'ALTER TABLE "app"."notes" ALTER COLUMN "body" SET NOT NULL;'; + expect(report).toMatchObject({ + generated: { tag: "0001_migration" }, + breaking: [setNotNull], + dataDependent: [setNotNull], + }); + }); + test("a second migrate in the same checkout fails while the first runs, and writes nothing", async () => { const ctx = app(`notes: table("notes", { id: id() })`); let finishApply: (value: unknown) => void = () => undefined; From 03c071dda55206dbb9fde9b80fdd1e286763a071 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:39:10 +0100 Subject: [PATCH 307/317] fix(appkit): keep the schema import error to the db CLI that asks for it loadDatabaseSchema kept the raw import error as the cause for every caller, including the development start that main keeps to a bounded message. The cause is now attached only when the caller passes showImportError, which only the db CLI does. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/migrate.ts | 1 + .../plugins/database/tests/load-routes.test.ts | 14 ++++++++++++++ .../src/type-generator/database/generate.ts | 18 ++++++++++++++---- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/migrate.ts b/packages/appkit/src/database/tooling/migrate.ts index 912fc9776..24804989c 100644 --- a/packages/appkit/src/database/tooling/migrate.ts +++ b/packages/appkit/src/database/tooling/migrate.ts @@ -174,6 +174,7 @@ async function migrateHolding( ): Promise { const schema = await loadDatabaseSchema( path.join(ctx.root, DEFAULT_SCHEMA_FILE), + { showImportError: true }, ); // The types follow schema.ts and server/database/routes alone, so they are // current even if applying fails. Written first, so a route module that diff --git a/packages/appkit/src/plugins/database/tests/load-routes.test.ts b/packages/appkit/src/plugins/database/tests/load-routes.test.ts index 445339146..82da93a3a 100644 --- a/packages/appkit/src/plugins/database/tests/load-routes.test.ts +++ b/packages/appkit/src/plugins/database/tests/load-routes.test.ts @@ -30,6 +30,7 @@ async function fixture(files: Record = {}) { afterEach(async () => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); await Promise.all( roots .splice(0) @@ -96,6 +97,19 @@ describe("default database routes", () => { ); }); + test("a schema that fails to load in development fails without its import error", async () => { + vi.stubEnv("NODE_ENV", "development"); + const root = await fixture({ + "config/database/schema.ts": 'throw new Error("private details");', + "server/database/routes/notes.ts": "export {};", + }); + const error = await loadDefaultDatabaseRoutes(root).catch( + (caught) => caught, + ); + expect(error.message).toMatch(/schema\.ts" threw while loading$/); + expect(error.cause).toBeUndefined(); + }); + test.each([ "export const databaseRoutes = {};", "export default {};", diff --git a/packages/appkit/src/type-generator/database/generate.ts b/packages/appkit/src/type-generator/database/generate.ts index 2f37da3b8..b697c87f7 100644 --- a/packages/appkit/src/type-generator/database/generate.ts +++ b/packages/appkit/src/type-generator/database/generate.ts @@ -134,17 +134,27 @@ async function importSchema(schemaFile: string): Promise { return createJiti(import.meta.url, { moduleCache: false }).import(schemaFile); } +interface LoadDatabaseSchemaOptions { + /** + * Keep the import error as the failure's `cause`. Only the local `appkit db` + * CLI sets it, to show the developer where schema.ts broke; every other + * caller gets the bounded message alone. + */ + readonly showImportError?: boolean; +} + /** Load the named, finalized `schema` export; every failure is a safe diagnostic. */ -export async function loadDatabaseSchema(schemaFile: string): Promise { +export async function loadDatabaseSchema( + schemaFile: string, + options: LoadDatabaseSchemaOptions = {}, +): Promise { let module: unknown; try { module = await importSchema(schemaFile); } catch (error) { - // The message stays bounded; only a caller that prints causes, the local - // `appkit db` CLI, shows the import error to the developer. throw new DatabaseTypegenError( `Database schema "${schemaLabel(schemaFile)}" ${importFailureReason(error)}`, - { cause: error }, + options.showImportError ? { cause: error } : undefined, ); } if (typeof module !== "object" || module === null || !("schema" in module)) { From 6edeb0375b0a97124588be99bc47bdcc1f8fb5f5 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:39:37 +0100 Subject: [PATCH 308/317] docs: say when a signal releases the history lock SIGINT and SIGTERM release it only when nothing else handles the signal, and any other way of ending can leave the file for the next command to report. Co-authored-by: Isaac Signed-off-by: ditadi --- designs/001_DatabaseDevelopmentFlow.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/designs/001_DatabaseDevelopmentFlow.md b/designs/001_DatabaseDevelopmentFlow.md index 034100e44..9207b1e25 100644 --- a/designs/001_DatabaseDevelopmentFlow.md +++ b/designs/001_DatabaseDevelopmentFlow.md @@ -372,9 +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 releases the lock when it finishes, when it exits, and on SIGINT or SIGTERM. Only a kill the process cannot -catch, such as SIGKILL, 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. From 56db876ab683f5a345cfd339f483cb7fa5a67ba8 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:42:21 +0100 Subject: [PATCH 309/317] fix(appkit): show the schema import error in appkit db introspect loadDatabaseSchema now keeps the import error only for a caller that asks, so introspect asks for it when it loads the schema.ts it replaces and the one it generates. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/introspect/index.ts | 8 ++++++-- .../tooling/introspect/tests/introspect.test.ts | 10 ++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/appkit/src/database/tooling/introspect/index.ts b/packages/appkit/src/database/tooling/introspect/index.ts index 511ef551b..1e7aa7f8c 100644 --- a/packages/appkit/src/database/tooling/introspect/index.ts +++ b/packages/appkit/src/database/tooling/introspect/index.ts @@ -148,7 +148,9 @@ function refuseDropsOfUnexpressed( 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)); + 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.`, @@ -281,7 +283,9 @@ async function introspectHolding( writeFileAtomic(schemaFile, rendered.source); let schema: Schema; try { - schema = await loadDatabaseSchema(schemaFile); + 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}".`, diff --git a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts index 8c4995ca4..c36de0c99 100644 --- a/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts +++ b/packages/appkit/src/database/tooling/introspect/tests/introspect.test.ts @@ -526,6 +526,16 @@ describe("runIntrospect", () => { }, ); + 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"], From 6d4b257a91236c638ec55aac3fdd6262066e06a7 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:44:52 +0100 Subject: [PATCH 310/317] fix(appkit): show the schema import error in appkit db init, clean and seed loadDatabaseSchema now keeps the import error only for a caller that asks, so the commands that read the app schema from schema.ts ask for it. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/clean.ts | 1 + packages/appkit/src/database/tooling/init.ts | 7 +++++-- packages/appkit/src/database/tooling/seed.ts | 7 +++++-- .../database/tooling/tests/clean-seed.test.ts | 20 +++++++++++++++++++ .../src/database/tooling/tests/init.test.ts | 12 +++++++++++ 5 files changed, 43 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/clean.ts b/packages/appkit/src/database/tooling/clean.ts index 938635e79..83ac19f66 100644 --- a/packages/appkit/src/database/tooling/clean.ts +++ b/packages/appkit/src/database/tooling/clean.ts @@ -232,6 +232,7 @@ async function cleanTarget(ctx: DbContext) { 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 }; } diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index 0b9cc16d0..e13882001 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -662,8 +662,11 @@ async function initHolding( const hasSchema = hasSchemaFile(ctx.root); const schemaName = hasSchema && request.kind === "locked" - ? (await loadDatabaseSchema(path.join(ctx.root, DEFAULT_SCHEMA_FILE))) - .$schemaName + ? ( + await loadDatabaseSchema(path.join(ctx.root, DEFAULT_SCHEMA_FILE), { + showImportError: true, + }) + ).$schemaName : DEFAULT_SCHEMA_NAME; const configured = { diff --git a/packages/appkit/src/database/tooling/seed.ts b/packages/appkit/src/database/tooling/seed.ts index 94b03d0e0..fad9eb9ae 100644 --- a/packages/appkit/src/database/tooling/seed.ts +++ b/packages/appkit/src/database/tooling/seed.ts @@ -32,8 +32,11 @@ export async function runSeed(ctx: DbContext): Promise { } const branch = await writableEnvBranch(ctx, "seed"); const schemaName = hasSchemaFile(ctx.root) - ? (await loadDatabaseSchema(path.join(ctx.root, DEFAULT_SCHEMA_FILE))) - .$schemaName + ? ( + await loadDatabaseSchema(path.join(ctx.root, DEFAULT_SCHEMA_FILE), { + showImportError: true, + }) + ).$schemaName : DEFAULT_SCHEMA_NAME; const searchPath = schemaName === "public" diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index 089939c66..3203e7419 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -304,6 +304,26 @@ describe("deleteSessionBranch", () => { }); }); +test.each([ + ["clean", runClean], + ["seed", runSeed], +])( + "%s keeps the import error of a schema.ts that fails to import, for the CLI to show", + async (_command, run) => { + const root = tempApp({ + [SEED_FILE]: "select 1;", + "config/database/schema.ts": "export const schema = (", + }); + writableEnvBranch.mockResolvedValue(devBranch); + + const error = await run(fakeContext({ root })).catch( + (caught: Error) => caught, + ); + + expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); + }, +); + describe("runSeed", () => { test("runs config/database/seed.sql in one transaction on your branch, app schema first", async () => { const sql = diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index a011b5df9..432e327ec 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1253,6 +1253,18 @@ describe("runInit — schema start", () => { expect(report.start).toEqual({ kind: "none" }); }); + test("a schema.ts that fails to import keeps the import error for the CLI to show", async () => { + const ctx = appOn( + project(), + {}, + { files: { "config/database/schema.ts": "export const schema = (" } }, + ); + + const error = await init(ctx).catch((caught: Error) => caught); + + expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); + }); + test.each(["migrate", "clean"] as const)( "%s without schema.ts fails before any change", async (start) => { From 2ab0fb9972e2ae6dd0a780ab282fb754e965eb6f Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:47:26 +0100 Subject: [PATCH 311/317] fix(appkit): escape the database name init prints The warning about the bound database, the step that points .env at the branch, the hand-off messages and the report the CLI prints carried the Postgres database name raw, so a name with a control character reached the terminal. Pass them through shown(); .env and the connections keep the raw name. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/hand-off.ts | 2 +- packages/appkit/src/database/tooling/init.ts | 10 +++++-- .../src/database/tooling/tests/init.test.ts | 30 +++++++++++++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/hand-off.ts b/packages/appkit/src/database/tooling/hand-off.ts index 7860dac6a..2370b0197 100644 --- a/packages/appkit/src/database/tooling/hand-off.ts +++ b/packages/appkit/src/database/tooling/hand-off.ts @@ -137,7 +137,7 @@ export async function handOffAppSchema( const { owner, ownedOutside, dependencies } = found; const ownerName = shown(owner); - const where = `schema ${input.schemaName} in database ${input.database} on ${resourceId(input.branch)}`; + 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( diff --git a/packages/appkit/src/database/tooling/init.ts b/packages/appkit/src/database/tooling/init.ts index e13882001..b40a032c3 100644 --- a/packages/appkit/src/database/tooling/init.ts +++ b/packages/appkit/src/database/tooling/init.ts @@ -25,6 +25,7 @@ import { type IntrospectReport, IntrospectRefusedError, } from "./introspect"; +import { shown } from "./introspect/render"; import { isAlreadyExists, isBranchLimit, @@ -132,6 +133,7 @@ export interface InitReport { 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 }; @@ -562,7 +564,7 @@ function chooseDatabase( if (bound === null) return local.database ?? DEFAULT_DATABASE; if (local.database && local.database !== bound) { onWarning( - `Setting PGDATABASE=${bound} in .env: it was ${local.database}, and databricks.yml binds ${bound}`, + `Setting PGDATABASE=${shown(bound)} in .env: it was ${shown(local.database)}, and databricks.yml binds ${shown(bound)}`, ); } return bound; @@ -740,7 +742,9 @@ async function initHolding( `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 ${database}`); + onStep( + `Pointing .env at ${resourceId(branch.name)}, database ${shown(database)}`, + ); updateEnvFile(envFile, values); const branchCtx: DbContext = { ...ctx, env: { ...ctx.env, ...values } }; @@ -753,7 +757,7 @@ async function initHolding( endpoint: endpoint.name, endpointCreated, host, - database, + database: shown(database), user: identity.userName, role: { name: role.name, action }, envFile, diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 432e327ec..371bf74a4 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1,6 +1,7 @@ import fs from "node:fs"; import path from "node:path"; +import dotenv from "dotenv"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; const { cleanHolding, introspectHolding, migrateHolding, withBranchPool } = @@ -32,6 +33,7 @@ import type { DbContext } from "../context"; import type { HistoryLock } from "../history-lock"; import { type InitOptions, runInit } from "../init"; import { IntrospectRefusedError } from "../introspect"; +import { shown } from "../introspect/render"; import { LakebaseApiError } from "../lakebase-api"; import { runMigrate } from "../migrate"; import { DRIZZLE_KIT_VERSION } from "../migrations"; @@ -1698,6 +1700,34 @@ describe("runInit — .env", () => { expect(same.warnings).toEqual([]); }); + test("a database name with a control character is escaped on the terminal and kept as is in .env", async () => { + const bound = "app\u001b[31mdb"; + const lakebase = project(); + lakebase.addDatabase(PRODUCTION, "databricks-postgres", bound); + const ctx = appOn(lakebase, { PGDATABASE: "scratch\u0007" }); + + const { report, events } = await init(ctx); + + expect(report.database).toBe(shown(bound)); + expect( + dotenv.parse(fs.readFileSync(path.join(ctx.root, ".env"))).PGDATABASE, + ).toBe(bound); + expect(events).toEqual( + expect.arrayContaining([ + `Setting PGDATABASE=${shown(bound)} in .env: it was ${shown("scratch\u0007")}, and databricks.yml binds ${shown(bound)}`, + `Pointing .env at ${devBranchId(USER)}, database ${shown(bound)}`, + expect.stringContaining( + `Handing schema app in database ${shown(bound)} on `, + ), + ]), + ); + expect( + events.filter( + (event) => event.includes("\u001b") || event.includes("\u0007"), + ), + ).toEqual([]); + }); + test("the profile init authenticated with wins over the host", async () => { const lakebase = project(); const root = tempApp(); From a930787380e632c9e71f40049b64c90a3d731874 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:49:32 +0100 Subject: [PATCH 312/317] test(appkit): type the import-error results in the init, clean and seed tests Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/tests/clean-seed.test.ts | 6 +++--- packages/appkit/src/database/tooling/tests/init.test.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts index 3203e7419..edbc6be2e 100644 --- a/packages/appkit/src/database/tooling/tests/clean-seed.test.ts +++ b/packages/appkit/src/database/tooling/tests/clean-seed.test.ts @@ -316,9 +316,9 @@ test.each([ }); writableEnvBranch.mockResolvedValue(devBranch); - const error = await run(fakeContext({ root })).catch( - (caught: Error) => caught, - ); + const error = (await run(fakeContext({ root })).catch( + (caught: unknown) => caught, + )) as Error; expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); }, diff --git a/packages/appkit/src/database/tooling/tests/init.test.ts b/packages/appkit/src/database/tooling/tests/init.test.ts index 371bf74a4..76c71b985 100644 --- a/packages/appkit/src/database/tooling/tests/init.test.ts +++ b/packages/appkit/src/database/tooling/tests/init.test.ts @@ -1262,7 +1262,7 @@ describe("runInit — schema start", () => { { files: { "config/database/schema.ts": "export const schema = (" } }, ); - const error = await init(ctx).catch((caught: Error) => caught); + const error = (await init(ctx).catch((caught: unknown) => caught)) as Error; expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); }); From fbb2e552a363ca8333d3128348a118009e859f3e Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:50:36 +0100 Subject: [PATCH 313/317] fix(appkit): show the schema import error in appkit db verify loadDatabaseSchema now keeps the import error only for a caller that asks, so verify asks for it when it reads schema.ts. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 15 +++++++++++++++ packages/appkit/src/database/tooling/verify.ts | 1 + 2 files changed, 16 insertions(+) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 029cd8768..908bac673 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -558,6 +558,21 @@ describe("runVerify", () => { ); expect(withBranchPool).not.toHaveBeenCalled(); }); + + test("a schema.ts that fails to import keeps the import error for the CLI to show", async () => { + const ctx = app(); + fs.writeFileSync( + path.join(ctx.root, "config/database/schema.ts"), + "export const schema = (", + ); + + const error = (await runVerify(ctx).catch( + (caught: unknown) => caught, + )) as Error; + + expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); + expect(withBranchPool).not.toHaveBeenCalled(); + }); }); const DATABASE = `${PRODUCTION}/databases/db-1`; diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 8d6a12792..687682a4e 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -134,6 +134,7 @@ async function verifyLocal(ctx: DbContext): Promise { const branch = env.branch.name; const schema = await loadDatabaseSchema( path.join(ctx.root, DEFAULT_SCHEMA_FILE), + { showImportError: true }, ); return withBranchPool(ctx, async (pool) => { const client = await pool.connect(); From 73bb33a6fa9749c49c2434be279f907617fae4f3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:52:54 +0100 Subject: [PATCH 314/317] fix(appkit): keep the raw apps API error out of the verify failure verify escaped the apps API message in its error but kept the raw error as the cause, and the CLI prints the innermost cause as is, so control characters in the API's text reached the terminal. Throw the escaped error alone. Co-authored-by: Isaac Signed-off-by: ditadi --- .../src/database/tooling/tests/verify.test.ts | 24 +++++++++++++++++++ .../appkit/src/database/tooling/verify.ts | 6 ++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/packages/appkit/src/database/tooling/tests/verify.test.ts b/packages/appkit/src/database/tooling/tests/verify.test.ts index 908bac673..0e69ff2f9 100644 --- a/packages/appkit/src/database/tooling/tests/verify.test.ts +++ b/packages/appkit/src/database/tooling/tests/verify.test.ts @@ -12,6 +12,7 @@ vi.mock("../context", async (importOriginal) => ({ withBranchPool, })); +import { fail } from "../../../../../shared/src/cli/commands/db/output"; import type { WorkspaceRequest } from "../../../workspace-client"; import type { DbContext } from "../context"; import { devBranchId, sessionBranchId } from "../naming"; @@ -1709,6 +1710,29 @@ describe("runVerify --deployed", () => { ); }); + test("the CLI prints an apps API error with its control characters escaped", async () => { + const { ctx } = deployedApp({ + app: Object.assign(new Error("Forbidden\u001b[2J"), { statusCode: 403 }), + }); + const caught = await runVerify(ctx, DEPLOYED).catch( + (thrown: unknown) => thrown, + ); + const printed = vi.spyOn(console, "error").mockImplementation(() => {}); + let printedLines: unknown[][]; + try { + fail(caught); + printedLines = printed.mock.calls; + } finally { + printed.mockRestore(); + process.exitCode = undefined; + } + + expect(printedLines).toHaveLength(1); + expect(String(printedLines[0])).toMatch( + /Could not read app my-app: Forbidden\\u001b\[2J$/, + ); + }); + test("never writes and never connects to the database", async () => { const { ctx, lakebase } = deployedApp({ spRole: false }); diff --git a/packages/appkit/src/database/tooling/verify.ts b/packages/appkit/src/database/tooling/verify.ts index 687682a4e..3b6fb6545 100644 --- a/packages/appkit/src/database/tooling/verify.ts +++ b/packages/appkit/src/database/tooling/verify.ts @@ -227,9 +227,9 @@ async function readApp( return null; } const message = error instanceof Error ? error.message : String(error); - throw new Error(`Could not read app ${name}: ${shown(message)}`, { - cause: error, - }); + // No cause: the CLI prints a cause's message as is, and this one is the + // API's raw text. + throw new Error(`Could not read app ${name}: ${shown(message)}`); } } From 67191fbd979c4aacc06e269805c90346d7844ec3 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:55:17 +0100 Subject: [PATCH 315/317] fix(appkit): resolve an included source_code_path before rebasing it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An included file's source_code_path was joined to the file's folder before its ${var.…} references resolved, so a variable naming an absolute path became resources/. Keep the path with its file's folder and rebase only a relative result once it resolves; an absolute one stays as it is and an unresolved one stays as written. Co-authored-by: Isaac Signed-off-by: ditadi --- .../appkit/src/database/tooling/targets.ts | 49 +++++++++++++++---- .../database/tooling/tests/targets.test.ts | 37 ++++++++++++++ 2 files changed, 76 insertions(+), 10 deletions(-) diff --git a/packages/appkit/src/database/tooling/targets.ts b/packages/appkit/src/database/tooling/targets.ts index 657067f60..7ff1ec612 100644 --- a/packages/appkit/src/database/tooling/targets.ts +++ b/packages/appkit/src/database/tooling/targets.ts @@ -90,8 +90,23 @@ export interface DeployTarget { type Yaml = Record | undefined; +/** + * An included file's source_code_path as written, with that file's folder + * relative to databricks.yml's: the CLI resolves the path against the file + * that declares it, after its references. Merged as a single value. + */ +class IncludedSourcePath { + constructor( + readonly folder: string, + readonly written: string, + ) {} +} + function record(value: unknown): Yaml { - return value && typeof value === "object" && !Array.isArray(value) + return value && + typeof value === "object" && + !Array.isArray(value) && + !(value instanceof IncludedSourcePath) ? (value as Record) : undefined; } @@ -405,6 +420,24 @@ function declaredValue( }; } +/** An app's source_code_path, relative to databricks.yml's folder once resolved; an absolute one stays as it is. */ +function sourcePathValue( + written: unknown, + resolve: (value: unknown) => string | null, +): BundleValue | null { + if (!(written instanceof IncludedSourcePath)) { + return declaredValue(written, resolve); + } + const value = declaredValue(written.written, resolve); + if (value?.kind !== "resolved" || path.posix.isAbsolute(value.name)) { + return value; + } + return { + kind: "resolved", + name: path.posix.join(written.folder, value.name), + }; +} + /** A `${…}` where only a deploy puts a structure: the files cannot say what it binds. */ function unresolvedAt(at: string, written: unknown): PostgresBinding { return { @@ -457,7 +490,7 @@ function bundleApps( key, declaredName: typeof declared === "string" && declared ? declared : null, name: resolve(declared), - sourceCodePath: declaredValue(app?.source_code_path, resolve), + sourceCodePath: sourcePathValue(app?.source_code_path, resolve), postgres: appPostgres( `resources.apps.${key}.resources`, app?.resources, @@ -505,8 +538,8 @@ export function readDeployTarget( } /** - * An included file's app source_code_paths, made relative to databricks.yml's - * folder: the CLI resolves a path against the file that declares it. + * An included file's app source_code_paths, kept with the file's folder so + * they resolve against it once their references are resolved. */ function rebaseSourcePaths( file: Record, @@ -517,12 +550,8 @@ function rebaseSourcePaths( for (const app of Object.values(record(record(resources)?.apps) ?? {})) { const declared = record(app); const source = declared?.source_code_path; - if ( - declared && - typeof source === "string" && - !path.posix.isAbsolute(source) - ) { - declared.source_code_path = path.posix.join( + if (declared && typeof source === "string") { + declared.source_code_path = new IncludedSourcePath( folder.split(path.sep).join("/"), source, ); diff --git a/packages/appkit/src/database/tooling/tests/targets.test.ts b/packages/appkit/src/database/tooling/tests/targets.test.ts index ef9ee5ff2..524110cc3 100644 --- a/packages/appkit/src/database/tooling/tests/targets.test.ts +++ b/packages/appkit/src/database/tooling/tests/targets.test.ts @@ -686,4 +686,41 @@ targets: readBundle(noHost, {})?.targets.map((target) => target.host), ).toEqual([null]); }); + + test.each([ + [ + "an absolute path, which stays as it is", + "/Workspace/Shared/shop", + { kind: "resolved", name: "/Workspace/Shared/shop" }, + ], + [ + "a relative path, which is relative to the included file", + "../app", + { kind: "resolved", name: "app" }, + ], + [ + "nothing, which stays unresolved as written", + undefined, + { kind: "unresolved", written: "${var.source}" }, + ], + ])( + "an included file's source_code_path whose variable resolves to %s", + (_label, source, expected) => { + const root = tempApp({ + "databricks.yml": `include: + - resources/*.yml +${source === undefined ? "" : `variables:\n source:\n default: ${source}\n`}`, + "resources/app.yml": `resources: + apps: + app: + name: shop + source_code_path: \${var.source} +`, + }); + + expect(readBundle(root, {})?.targets[0]?.apps[0]?.sourceCodePath).toEqual( + expected, + ); + }, + ); }); From 439544e62720d7746a3622507fa13a73ed09e602 Mon Sep 17 00:00:00 2001 From: ditadi Date: Wed, 25 Nov 2026 18:57:30 +0100 Subject: [PATCH 316/317] fix(appkit): show the schema import error in appkit db check loadDatabaseSchema now keeps the import error only for a caller that asks, so check asks for it when it compares schema.ts with the latest snapshot. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/appkit/src/database/tooling/check.ts | 1 + .../src/database/tooling/tests/check.test.ts | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/packages/appkit/src/database/tooling/check.ts b/packages/appkit/src/database/tooling/check.ts index c480b363d..008878441 100644 --- a/packages/appkit/src/database/tooling/check.ts +++ b/packages/appkit/src/database/tooling/check.ts @@ -183,6 +183,7 @@ export async function runCheck(ctx: DbContext): Promise { 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; diff --git a/packages/appkit/src/database/tooling/tests/check.test.ts b/packages/appkit/src/database/tooling/tests/check.test.ts index e8cc78875..410adcd42 100644 --- a/packages/appkit/src/database/tooling/tests/check.test.ts +++ b/packages/appkit/src/database/tooling/tests/check.test.ts @@ -419,4 +419,18 @@ describe("runCheck", () => { "No config/database/schema.ts yet, so there is nothing to check.", ); }); + + test("a schema.ts that fails to import keeps the import error for the CLI to show", async () => { + const ctx = app({}); + fs.writeFileSync( + path.join(ctx.root, "config/database/schema.ts"), + "export const schema = (", + ); + + const error = (await runCheck(ctx).catch( + (caught: unknown) => caught, + )) as Error; + + expect((error.cause as Error).message).toMatch(/schema\.ts:\d+:\d+/); + }); }); From 64864fc09602825dad99bad32f0ba8d6e9caa136 Mon Sep 17 00:00:00 2001 From: ditadi Date: Thu, 26 Nov 2026 13:43:13 +0100 Subject: [PATCH 317/317] test(shared): compare init's printed output without color codes CI sets CI, so picocolors colors the warning marker and the assertion on "! Could not mark ..." failed there while it passed in a local shell. Co-authored-by: Isaac Signed-off-by: ditadi --- packages/shared/src/cli/commands/db/init-clean-seed.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts index 5ce030e8a..453046261 100644 --- a/packages/shared/src/cli/commands/db/init-clean-seed.test.ts +++ b/packages/shared/src/cli/commands/db/init-clean-seed.test.ts @@ -1,3 +1,5 @@ +import { stripVTControlCharacters } from "node:util"; + import { afterEach, beforeEach, @@ -29,7 +31,9 @@ import { dbCommand } from "./index"; let log: MockInstance; let error: MockInstance; const output = (spy: MockInstance) => - spy.mock.calls.map((call) => call.join(" ")).join("\n"); + stripVTControlCharacters( + spy.mock.calls.map((call) => call.join(" ")).join("\n"), + ); function setTTY(value: boolean | undefined) { Object.defineProperty(process.stdin, "isTTY", { value, configurable: true });