Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Carry foreign_table through apply-migrations --yes and refuse a foreign table missing a gbrain column

garrytan886882f6471e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index feeb4ba9a7..a9deab77ae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
-- **Schema setup refuses a table gbrain did not create, before changing anything.** Before the schema replay (`gbrain init`, every engine start that applies migrations) and before any migration in a run, gbrain checks that each OAuth table that already exists has the key column and the column types gbrain has always given it. When one does not, it stops with the new `foreign_table` error, which names the table, the column, the type it found, the type gbrain needs and the fix: give gbrain its own database, or move the other table with `ALTER TABLE <table> SET SCHEMA <other_schema>`, then run `gbrain apply-migrations --force-schema --yes`. A correctly shaped brain runs exactly as before, and v210 is unchanged. Guide: [foreign table](docs/guides/troubleshooting.md#foreign-table).
+- **Schema setup refuses a table gbrain did not create, before changing anything.** Before the schema replay (`gbrain init`, every engine start that applies migrations) and before any migration in a run, gbrain checks that each OAuth table that already exists has every column gbrain has always given it, with the same type. When one does not, it stops with the new `foreign_table` error, which names the table, the column, the type it found, the type gbrain needs and the fix: give gbrain its own database, or move the other table with `ALTER TABLE <table> SET SCHEMA <other_schema>`, then run `gbrain apply-migrations --force-schema --yes`. A correctly shaped brain runs exactly as before, and v210 is unchanged. Guide: [foreign table](docs/guides/troubleshooting.md#foreign-table).
- **`gbrain apply-migrations` replays the schema before the pending migrations on every path.** With the migration lease held (every PGLite brain, and every Postgres brain whose schema has the lease table) it ran the pending migrations without the schema replay, so a table the replay creates that was missing stayed missing and the next migration failed with `relation "<table>" does not exist`. It now goes through the same schema setup as `gbrain init --migrate-only` on every path. A brain an older release stopped at v210 recovers with `gbrain upgrade` and the steps the guide lists.
- Tests: `test/upgrade-foreign-oauth-table.test.ts` runs on PGLite and Postgres: the refusal on an upgrade (a foreign `oauth_tokens`) and on a fresh install (a foreign `oauth_codes` or `oauth_clients`), the rerun that recreates a missing table, and the full recovery of a brain stopped at v210.
diff --git a/docs/architecture/key-files/engines-2-continued.md b/docs/architecture/key-files/engines-2-continued.md
index 2a070ffb81..da32608aa2 100644
--- a/docs/architecture/key-files/engines-2-continued.md
+++ b/docs/architecture/key-files/engines-2-continued.md
@@ -8,5 +8,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/analyze-lock.ts` — #7083: `lockTableForAnalyze` takes a table's SHARE UPDATE EXCLUSIVE lock with NOWAIT before every ANALYZE gbrain runs on Postgres on its own (the projection and chunk refreshes, `repair planner-stats`, `analyzeAfterIndexBuild` through `analyzeYieldingToVacuum`), and `analyzeDeferred` recognizes its 55P03 refusal. An ANALYZE that waited `deadlock_timeout` on a running autovacuum made Postgres cancel it, so a refresh after every embed drain kept a 10M-chunk content_chunks from ever being vacuumed; a request that never waits never signals a vacuum, and the caller defers its ANALYZE. Doctor `planner_stats_stale` reports a hot table whose autovacuum stays starved (`readVacuumStarvation`). Test: `test/e2e/analyze-yields-to-autovacuum-postgres.test.ts`.
- `src/core/migration-preludes.ts` — #7108 runner-side preludes for published migrations whose SQL rewrites a large table in one transaction (published migration files never change; restamp refuses an edit). `runMigrationPrelude(engine, version)` runs right before that migration's SQL inside the runner's retry wrapper: `batchedUpdate` repeats the migration's own SET and predicate over id-ordered batches (5,000 rows, inlined so a generic prepared plan cannot scan the table per batch; `__setBackfillBatchRowsForTests`), each its own transaction with the migration statement budget and the schema lock timeout, so progress is the data itself and a rerun resumes; a column the migration adds first is added first, in the migration's column order (fresh and upgraded ordinals stay equal). Preludes: v011 legacy `links.link_source` (skipped below PG15, where the migration refuses), v028 chunk keyword vectors, v033 request-log agent names (NULL-token rows stay the migration's own), v116 code-edge `source_id`, v161 (Postgres) the partial pages index built concurrently under the budget on a reserved connection (the migration caps its own build at 30 s; another session's build or an invalid result stops the run), v221 `embedding_pending_since` (v221's active-column choice; the first stamping batch writes `embedding_pending_since_backfilled_at` in its transaction). Pinned by `test/e2e/migration-v221-batched-backfill-7108.test.ts`. Migrations that cannot be moved here are listed in docs/guides/troubleshooting.md#migration-statement-timeout.
- `src/core/migration-timeout.ts` — #7108 the migration statement budget (`migrationStatementTimeoutMs`, default 10 min; `setMigrationStatementTimeoutMs` from operator-only `gbrain apply-migrations --statement-timeout <minutes>`, restored when that run returns; 0 removes it) and the timed-out-migration record (config `schema_migration_timeout`: version, name, whether the run had a prelude, idle-in-transaction pids sampled at the failure): `runMigrations` writes it on a 57014 or a statement-timeout retry exhaustion and deletes it after a pass reaches head. A schema-graph leaf (no release version, so the PGLite snapshot hash stays stable). `migration-timeout-advice.ts` turns a record into the one fix both apply-migrations (`migrations_pending` still_behind) and doctor `schema_version` show: timed out unbatched and this release has a prelude → rerun; idle sessions open → ask_user, check `doctor --locks`, end the ones still open, rerun; none → ask_user, one run with `--statement-timeout 120`.
-- `src/core/owned-table-shapes.ts` — #9190 the shape check for tables gbrain owns by a generic name (`oauth_clients`, `oauth_tokens`, `oauth_codes`): one catalog query in `current_schema()` compares each existing table's key column and v32 column types with what gbrain has always created, and `assertOwnedTableShapes` throws `foreign_table` (table, column, type found, type needed, the `SET SCHEMA` fix) on the first mismatch. `applyForwardReferenceBootstrap` (engine-sql/bootstrap.ts) runs it before any DDL, so `initSchema` on both engines refuses before the schema replay, and `runMigrations` runs it before its repairs and the first pending migration. Pinned on both engines by `test/upgrade-foreign-oauth-table.test.ts`.
+- `src/core/owned-table-shapes.ts` — #9190 the shape check for tables gbrain owns by a generic name (`oauth_clients`, `oauth_tokens`, `oauth_codes`): one catalog query in `current_schema()` compares each existing table's v32 columns and their types with what gbrain has always created (a wrong type is named before a missing column), and `assertOwnedTableShapes` throws `foreign_table` (table, column, type found, type needed, the `SET SCHEMA` fix) on the first mismatch. `applyForwardReferenceBootstrap` (engine-sql/bootstrap.ts) runs it before any DDL, so `initSchema` on both engines refuses before the schema replay, and `runMigrations` runs it before its repairs and the first pending migration. Pinned on both engines by `test/upgrade-foreign-oauth-table.test.ts`.
- `src/core/derived-state-maintainers.ts` + `src/core/schema-migrations/v281-derived-state-maintainers-fail-closed.ts` — #7637: the eight derived-state maintainer triggers (page retrievals, atom scan state, tag revision, version trust and attribution, page search vector, projection queue, trust generation) stay SECURITY INVOKER and fail closed. `requireMaintainerPoliciesSql(table, commands)` is the PL/pgSQL each body runs before touching another table: when `row_security_active(table)` holds and no permissive `pg_policy` row for the caller (PUBLIC or a role it has USAGE of) covers a command, it raises `writer_coordinator_required` (`managed_writer_guard:unreadable_state`, DETAIL `state` = the table), so an empty read never counts as nothing to do. Each body lives with its schema (`TAG_REVISION_FUNCTION_SQL`, `SNAPSHOT_VERSION_FUNCTION`, `STAMP_VERSION_FUNCTION`, `BUMP_FUNCTION`, `PAGE_PROJECTION_QUEUE_FUNCTION_SQL`, `pageSearchVectorTriggerFnSql`); the page retrievals body is a schema blob fragment here. v281 replaces only the functions (the search vector under the configured FTS language), never the triggers. The policies a scoped writer needs are the ENGINES.md maintainer recipe (`test/derived-state-maintainers-7637.test.ts`, applied verbatim).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 16b63c85ac..8d6a62a3d7 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1944,7 +1944,7 @@ More: [docs/guides/shared-brain-skills.md#approve-publication-following-and-edit
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A table gbrain owns by name (an OAuth table) already exists in the brain's schema with a column type gbrain never gives it, so schema setup stopped before the schema replay or any migration changed anything; the message names the table, the column, the type found and the type gbrain needs. | gbrain creates its tables with CREATE TABLE IF NOT EXISTS, so without this check it adopted a same-named table another application created in the shared database, added its own columns to it and failed partway through an upgrade on the first statement that compared the wrong type (#9190). The table holds that application's data, so gbrain never moves, renames or drops it. | Ask the user: give gbrain its own database, or move the other table to a schema of its own (ALTER TABLE <table> SET SCHEMA <other_schema> takes its indexes and constraints along) and point that application there; then run gbrain apply-migrations --force-schema --yes. | user | `gbrain doctor --json` | 1 | no |
+| A table gbrain owns by name (an OAuth table) already exists in the brain's schema without a column gbrain always gives it, or with a type gbrain never gives it, so schema setup stopped before the schema replay or any migration changed anything; the message names the table, the column, the type found and the type gbrain needs. | gbrain creates its tables with CREATE TABLE IF NOT EXISTS, so without this check it adopted a same-named table another application created in the shared database, added its own columns to it and failed partway through an upgrade on the first statement that compared the wrong type (#9190). The table holds that application's data, so gbrain never moves, renames or drops it. | Ask the user: give gbrain its own database, or move the other table to a schema of its own (ALTER TABLE <table> SET SCHEMA <other_schema> takes its indexes and constraints along) and point that application there; then run gbrain apply-migrations --force-schema --yes. | user | `gbrain doctor --json` | 1 | no |
More: [docs/guides/troubleshooting.md#foreign-table](../../docs/guides/troubleshooting.md#foreign-table)
diff --git a/scripts/postgres-arm-weights-postgres-only.json b/scripts/postgres-arm-weights-postgres-only.json
index 484c90e40a..ff46fad67e 100644
--- a/scripts/postgres-arm-weights-postgres-only.json
+++ b/scripts/postgres-arm-weights-postgres-only.json
@@ -411,7 +411,7 @@
"test/trust-owner-actions.test.ts": 13580,
"test/unbound-source-6536.test.ts": 1896,
"test/unindexed-files.test.ts": 5892,
- "test/upgrade-foreign-oauth-table.test.ts": 4652,
+ "test/upgrade-foreign-oauth-table.test.ts": 5660,
"test/vector-manifest-probe-bound.test.ts": 23971,
"test/withdrawal-overlay-concurrency.test.ts": 4425,
"test/withdrawal-publication-file.test.ts": 9435,
diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.json
index 914fc2b4ff..dec4fad213 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -658,7 +658,7 @@
"test/unbound-source-6536.test.ts": 8163,
"test/unindexed-files-convergence-7149.test.ts": 15915,
"test/unindexed-files.test.ts": 20566,
- "test/upgrade-foreign-oauth-table.test.ts": 13356,
+ "test/upgrade-foreign-oauth-table.test.ts": 17000,
"test/url-source-origin.test.ts": 54860,
"test/v273-validate-timeouts.test.ts": 4976,
"test/valid-time-gbra217.test.ts": 28349,
diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index 651e08b9b7..5fdc386e58 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -641,14 +641,8 @@ async function runLockedMigrations(
): Promise<number | undefined> {
const { doc } = report;
const fail = (status: string, failure: OperationError): void => { doc.status = status; report.failure = failure; };
- // Schema work goes through initSchema(), lease or not: it takes the schema migration lock and replays the
- // idempotent schema blob before the pending migrations, so a blob-owned table that is missing is back first (#9191).
- const migrateSchema = async (eng: BrainEngine, from: number): Promise<{ applied: number; current: number }> => {
- await eng.initSchema();
- const current = parseInt(await eng.getConfig('version') || String(from), 10);
- const { MIGRATIONS } = await import('../core/migrate.ts');
- return { applied: MIGRATIONS.filter(m => m.version > from && m.version <= current).length, current };
- };
+ const refusal: SchemaRefusal = {};
+ const migrateSchema = (eng: BrainEngine, from: number) => migrateSchemaThroughInit(eng, from, refusal);
// Bug 3 — --force-retry: write an explicit reset marker for a wedged
// migration, then return. User re-runs `gbrain apply-migrations --yes`
// to actually re-attempt.
@@ -710,8 +704,7 @@ async function runLockedMigrations(
await eng.disconnect();
} catch (err) {
console.error(`--force-schema failed: ${(err as Error).message}`);
- if (err instanceof OperationError && err.code === 'foreign_table') { fail('failed', err); return 1; }
- fail('failed', opError('migration_failed', `--force-schema failed: ${(err as Error).message}`,
+ fail('failed', err instanceof OperationError && err.code === 'foreign_table' ? err : opError('migration_failed', `--force-schema failed: ${(err as Error).message}`,
'Fix the database error above, then run `gbrain apply-migrations --force-schema` again.', { reason: 'schema_failed' }));
return 1;
}
@@ -789,7 +782,7 @@ async function runLockedMigrations(
const pendingWork = [...plan.partial, ...plan.pending, ...plan.pending_fresh_install];
const authorized = cli.yes || cli.nonInteractive;
if (schemaBehind && pendingWork.length === 0 && dbProbe.status === 'connected') {
- return failSchemaBehind(report, args, await schemaBehindAtPreflight(dbProbe.schemaVer, authorized, schemaTimeout));
+ return failSchemaBehind(report, args, await schemaBehindAtPreflight(dbProbe.schemaVer, authorized, schemaTimeout), refusal.foreignTable);
}
const toRun: Migration[] = [...pendingWork, ...plan.applied.filter(migration => migration.reconcile)]
.sort((left, right) => compareVersions(left.version, right.version));
@@ -930,18 +923,39 @@ async function runLockedMigrations(
// #6089: an orchestrator may migrate the schema itself, so read it again.
return failSchemaBehind(report, args, await checkSchemaAfterOrchestrators({
cfg: loadConfig()!, authorized, preflightVersion: dbProbe.status === 'connected' ? dbProbe.schemaVer : null, apply: migrateSchema,
- }));
+ }), refusal.foreignTable);
}
/** #6089: the run leaves the schema behind → `migrations_pending`, exit 1; undefined (success) when it does not. */
-function failSchemaBehind(report: RunReport, args: readonly string[], pending: SchemaPending | null): number | undefined {
+/** #9190: a foreign_table refusal replaces the generic still_behind error, so its fix reaches the caller. */
+function failSchemaBehind(report: RunReport, args: readonly string[], pending: SchemaPending | null, foreignTable?: OperationError): number | undefined {
if (!pending) return failWedged(report);
report.doc.status = 'schema_behind';
report.doc.schema_pending = pending;
- report.failure = schemaPendingError(pending, rerunFix(args, 'Applies the pending schema migrations (no consent effect; it migrates the brain\'s own schema).', true));
+ report.failure = pending.reason === 'still_behind' && foreignTable ? foreignTable
+ : schemaPendingError(pending, rerunFix(args, 'Applies the pending schema migrations (no consent effect; it migrates the brain\'s own schema).', true));
return 1;
}
+interface SchemaRefusal { foreignTable?: OperationError }
+
+/**
+ * Schema work goes through initSchema(), lease or not: it takes the schema migration lock and replays the idempotent
+ * schema blob before the pending migrations, so a blob-owned table that is missing is back first (#9191). A
+ * `foreign_table` refusal (#9190) is kept for the run's failure.
+ */
+async function migrateSchemaThroughInit(eng: BrainEngine, from: number, refusal: SchemaRefusal): Promise<{ applied: number; current: number }> {
+ try {
+ await eng.initSchema();
+ } catch (err) {
+ if (err instanceof OperationError && err.code === 'foreign_table') refusal.foreignTable = err;
+ throw err;
+ }
+ const current = parseInt(await eng.getConfig('version') || String(from), 10);
+ const { MIGRATIONS } = await import('../core/migrate.ts');
+ return { applied: MIGRATIONS.filter(m => m.version > from && m.version <= current).length, current };
+}
+
/**
* Pre-flight for runLockedMigrations: detect schema migrations (migrate.ts)
* being behind and probe the database (moved out of runLockedMigrations to
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 6330b71b24..17eb9d67b1 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -354,7 +354,7 @@ export const CODES = {
file_wins_rewrite: { class: 'caller', retryable: false, actor: 'user', summary: "gbrain repair file-drift --prefer file refused a page because keeping its file would need a full re-render of the file, not only appended protected parts; nothing was written.", why: "File wins keeps the canonical file's bytes and adds only what reconcile's protections keep from the database: protected frontmatter keys the file lacks and database-only timeline rows, appended. A result that also changes a value, a tag, the title or the body would re-render the whole file (keys reordered, lists re-emitted, rules and headings rewritten), which is not the file winning.", docs: 'docs/guides/write-refusals.md#file_wins_rewrite', suggestion: 'Show the user the page\'s exceptions in the preview. Commit the database-only differences into the file through the door (`gbrain git commit-push`) and preview again, or preview `--prefer database` if the database copy should win.' },
file_too_large: { class: 'caller', summary: "The file is over the page size limit (24 MiB for a Markdown page, 5 MB for a code file), so it was not imported.", why: "Every page under the limit is stored, chunked and searchable whatever its size; the limit bounds what one page may hold in this release. The same bytes refuse on every retry. A smaller page refused by an MCP or HTTP transport is a different refusal.", docs: 'docs/guides/write-refusals.md#file_too_large', suggestion: 'Leave the file out of the source (sync.exclude), or, if it must be in the brain, split it into files under the limit; then sync or import again. Never split a page under the limit.' },
follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },
- foreign_table: { class: 'host_only', actor: 'user', retryable: false, summary: "A table gbrain owns by name (an OAuth table) already exists in the brain's schema with a column type gbrain never gives it, so schema setup stopped before the schema replay or any migration changed anything; the message names the table, the column, the type found and the type gbrain needs.", why: "gbrain creates its tables with CREATE TABLE IF NOT EXISTS, so without this check it adopted a same-named table another application created in the shared database, added its own columns to it and failed partway through an upgrade on the first statement that compared the wrong type (#9190). The table holds that application's data, so gbrain never moves, renames or drops it.", docs: 'docs/guides/troubleshooting.md#foreign-table', suggestion: 'Ask the user: give gbrain its own database, or move the other table to a schema of its own (ALTER TABLE <table> SET SCHEMA <other_schema> takes its indexes and constraints along) and point that application there; then run gbrain apply-migrations --force-schema --yes.' },
+ foreign_table: { class: 'host_only', actor: 'user', retryable: false, summary: "A table gbrain owns by name (an OAuth table) already exists in the brain's schema without a column gbrain always gives it, or with a type gbrain never gives it, so schema setup stopped before the schema replay or any migration changed anything; the message names the table, the column, the type found and the type gbrain needs.", why: "gbrain creates its tables with CREATE TABLE IF NOT EXISTS, so without this check it adopted a same-named table another application created in the shared database, added its own columns to it and failed partway through an upgrade on the first statement that compared the wrong type (#9190). The table holds that application's data, so gbrain never moves, renames or drops it.", docs: 'docs/guides/troubleshooting.md#foreign-table', suggestion: 'Ask the user: give gbrain its own database, or move the other table to a schema of its own (ALTER TABLE <table> SET SCHEMA <other_schema> takes its indexes and constraints along) and point that application there; then run gbrain apply-migrations --force-schema --yes.' },
forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },
reserved_frontmatter_key: { class: 'caller', summary: 'A remote page write tried to add or change a frontmatter key only a trusted derived writer sets (`retired_by`, `retired_at`, `retired_generation`); nothing was written.', why: 'Those keys mark a page a derived writer retired, which the purge holds for 30 days and the repairs treat as machine-owned. A remote caller that could set them could make a page look machine-retired. Carrying the stored value unchanged, or dropping the key, is allowed.', suggestion: 'Remove the key from the frontmatter (or keep the stored value) and write the page again.' },
generation_fenced: { class: 'retryable', exit: 11, reasons: ['stale_generation', 'pin_moved'], summary: 'A derived result was not published because the live generation or its input changed after the producer read them; nothing was written.', why: 'The generation primitive (GBRA-161) publishes a result only against the generation and input pin it was computed from. A concurrent run that published first (stale_generation), or an input edited since the read (pin_moved), would otherwise let an older result replace a newer one.', docs: 'docs/architecture/generations.md#publishing', suggestion: 'Run the producer again; it reads the current generation and input and recomputes.' },
diff --git a/src/core/owned-table-shapes.ts b/src/core/owned-table-shapes.ts
index 07140904d2..de178d5a40 100644
--- a/src/core/owned-table-shapes.ts
+++ b/src/core/owned-table-shapes.ts
@@ -3,13 +3,13 @@
* application created in the brain's schema was adopted silently; later migrations then added columns to it and an
* upgrade stopped midway on the first statement that compared the wrong type, naming neither table nor column.
* Before the schema blob replays (engine-sql/bootstrap.ts) and before a migration run (migrate.ts), every table here
- * that already exists must have the column types gbrain has given it since it first created the table (v32), its key
- * column included. Otherwise schema setup refuses with `foreign_table` and changes nothing: the table is another
+ * that already exists must have every column gbrain has given it since it first created the table (v32), with the
+ * same type. Otherwise schema setup refuses with `foreign_table` and changes nothing: the table is another
* application's data, so moving it is the user's decision.
*/
import { opError, type OperationError } from './ops/contract.ts';
-/** Columns and types each table has had since v32; the first is its key and must exist. */
+/** Columns and types each table has had since v32; every one must exist with its type. */
const OWNED_TABLE_COLUMNS: Record<string, ReadonlyArray<readonly [column: string, type: string]>> = {
oauth_clients: [
['client_id', 'text'], ['client_secret_hash', 'text'], ['client_name', 'text'], ['redirect_uris', 'text[]'],
@@ -28,19 +28,19 @@ const OWNED_TABLE_COLUMNS: Record<string, ReadonlyArray<readonly [column: string
};
const EXPECTED_ROWS = Object.entries(OWNED_TABLE_COLUMNS)
- .flatMap(([table, columns]) => columns.map(([column, type], i) => [table, column, type, i === 0] as const))
- .map(([table, column, type, isKey], ord) => `('${table}', '${column}', '${type}', ${isKey}, ${ord})`);
+ .flatMap(([table, columns]) => columns.map(([column, type]) => [table, column, type] as const))
+ .map(([table, column, type], ord) => `('${table}', '${column}', '${type}', ${ord})`);
-/** One row naming the first mismatch in the current schema, or none. */
-const SHAPE_PROBE_SQL = `WITH expected(table_name, column_name, expected_type, is_key, ord) AS (VALUES ${EXPECTED_ROWS.join(', ')})
+/** One row naming the first mismatch in the current schema (a wrong type before a missing column), or none. */
+const SHAPE_PROBE_SQL = `WITH expected(table_name, column_name, expected_type, ord) AS (VALUES ${EXPECTED_ROWS.join(', ')})
SELECT n.nspname AS schema_name, e.table_name, e.column_name, e.expected_type,
format_type(a.atttypid, a.atttypmod) AS found_type
FROM expected e
JOIN pg_class c ON c.relname = e.table_name
JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname = current_schema()
LEFT JOIN pg_attribute a ON a.attrelid = c.oid AND a.attname = e.column_name AND a.attnum > 0 AND NOT a.attisdropped
-WHERE (a.attname IS NULL AND e.is_key) OR (a.attname IS NOT NULL AND format_type(a.atttypid, a.atttypmod) <> e.expected_type)
-ORDER BY e.ord
+WHERE a.attname IS NULL OR format_type(a.atttypid, a.atttypmod) <> e.expected_type
+ORDER BY a.attname IS NULL, e.ord
LIMIT 1`;
interface ShapeMismatch { schema_name: string; table_name: string; column_name: string; expected_type: string; found_type: string | null }
diff --git a/test/upgrade-foreign-oauth-table.test.ts b/test/upgrade-foreign-oauth-table.test.ts
index 1e59f76180..d1584da603 100644
--- a/test/upgrade-foreign-oauth-table.test.ts
+++ b/test/upgrade-foreign-oauth-table.test.ts
@@ -85,11 +85,11 @@ for (const kind of testBackends()) {
} };
};
const close = async (engine: BrainEngine) => { await engine.disconnect(); engines.splice(engines.indexOf(engine), 1); };
- const forceSchema = async (b: Brain) => {
+ const applyMigrations = async (b: Brain, args: string[]) => {
const home = makeHome({ engine: 'pglite' });
homes.push(home);
writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(b.config));
- const r = await collect(spawnDriver(home, writeSchemaDriver(home, { migrations: ['noop'], args: FORCE_SCHEMA })));
+ const r = await collect(spawnDriver(home, writeSchemaDriver(home, { migrations: ['noop'], args })));
return { code: r.code, out: r.stderr + r.stdout };
};
const shapeOf = async (engine: BrainEngine, qualified: string) => (await engine.executeRaw<{ t: string | null }>(
@@ -112,10 +112,11 @@ for (const kind of testBackends()) {
expect(await engine.executeRaw('SELECT token_type FROM oauth_tokens')).toEqual([{ token_type: 'Bearer' }]);
}, 300_000);
- test('#9190: a fresh install refuses a foreign oauth_codes or oauth_clients before creating any gbrain table', async () => {
+ test('#9190: a fresh install refuses a foreign oauth_codes, oauth_clients or oauth_tokens before creating any gbrain table', async () => {
for (const [ddl, named] of [
['CREATE TABLE oauth_codes (code_hash text PRIMARY KEY, client_id text, expires_at timestamptz)', 'oauth_codes.expires_at is timestamp with time zone'],
['CREATE TABLE oauth_clients (client_id uuid PRIMARY KEY, client_name text)', 'oauth_clients.client_id is uuid'],
+ ['CREATE TABLE oauth_tokens (token_hash text PRIMARY KEY, token_type text, client_id text, scopes text[], resource text, created_at timestamptz)', 'oauth_tokens.expires_at is missing'],
] as const) {
const b = await brain(false);
const engine = await b.open();
@@ -133,7 +134,7 @@ for (const kind of testBackends()) {
await engine.executeRaw('DROP TABLE oauth_tokens');
await engine.setConfig('version', '209');
await close(engine);
- const run = await forceSchema(b);
+ const run = await applyMigrations(b, FORCE_SCHEMA);
expect(run.code, run.out).toBe(0);
const after = await b.open();
expect(await shapeOf(after, 'oauth_tokens')).toBe('bigint');
@@ -148,16 +149,18 @@ for (const kind of testBackends()) {
await engine.executeRaw(FOREIGN_ROW);
await engine.setConfig('version', '209');
await close(engine);
- const refused = await forceSchema(b);
- expect(refused.code, refused.out).toBe(1);
- expect(refused.out).toContain('[foreign_table]');
- expect(refused.out).toContain('oauth_tokens.expires_at is timestamp with time zone');
+ for (const args of [FORCE_SCHEMA, ['--yes', '--non-interactive', '--no-autopilot-install']]) {
+ const refused = await applyMigrations(b, args);
+ expect(refused.code, refused.out).toBe(1);
+ expect(refused.out).toContain('[foreign_table]');
+ expect(refused.out).toContain('oauth_tokens.expires_at is timestamp with time zone');
+ }
const moving = await b.open();
await moving.executeRaw('CREATE SCHEMA other_app_example');
await moving.executeRaw('ALTER TABLE oauth_tokens SET SCHEMA other_app_example');
await close(moving);
- const rerun = await forceSchema(b);
+ const rerun = await applyMigrations(b, FORCE_SCHEMA);
expect(rerun.code, rerun.out).toBe(0);
const after = await b.open();
expect(await shapeOf(after, 'oauth_tokens')).toBe('bigint');