fix: harden migration command execution

Two problems in the migration commands: no timeouts, and SQL split on literal
bytes.

`migrations:plan` and `migrations:apply` constructed their connection with
neither a connection deadline nor an operation deadline — a real server reported
`statement_timeout = 0` on the migration connection. Both now default to 10
seconds for the connection deadline, the client query timeout, and PostgreSQL's
own statement_timeout, applied at the one shared construction boundary so a
future call site cannot silently omit them. History reads, advisory-lock
queries, transaction control, migration SQL, and history writes are all covered.
The existing lock-wait deadline, the Pass 2 TLS policy, and Doctor's and the
bootstrap CLI's own timeouts are untouched, and no environment variable or flag
was added.

Explicit client fields do not win under the pinned driver. [email protected].0 builds
parameters as `Object.assign({}, config, parse(config.connectionString))`, so
the URL overrides passed options — verified directly, where an explicit
statement_timeout of 10000 alongside `?statement_timeout=0` produced a
server-reported 0, while a clean URL produced 10s. A DATABASE_URL carrying
connect_timeout, query_timeout, statement_timeout, or an `options` value setting
statement_timeout is therefore refused with the existing fixed configuration
error, before any client is constructed and without echoing the URL, parameter,
or value. Unrelated parameters are left alone.

The runner split each migration on the literal `--> statement-breakpoint` bytes.
Those bytes inside a string literal, a dollar-quoted function body, a quoted
identifier, or a comment tore the migration into fragments that were no longer
valid SQL — each case verified to produce two fragments where one was required.
Each migration's exact SQL is now passed to the client once, with no values and
no prepared-statement name, inside the existing transaction, and its history row
inserted only after that batch succeeds. One transaction still spans all pending
migrations; advisory locking, checksum validation, approval preflight, ordering,
rollback, cleanup, and sanitized error identity are unchanged. The port method
is renamed executeStatement to executeMigrationSql so the contract says what it
receives.

PostgreSQL parses the batch because it owns the only correct parser. A homegrown
splitter would have to track single quotes, dollar quoting with arbitrary tags,
quoted identifiers, line comments, nested block comments, and escape syntax to
answer a question the server already answers, and a parser dependency would add
supply-chain surface for the same reason. Drizzle's marker lines are ordinary
`--` comments when the batch is sent whole. No custom SQL parser exists here.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
ekklesia
2026-07-26 23:13:52 -05:00
co-authored by Claude Opus 5
parent 490b85b07c
commit 2983789779
12 changed files with 721 additions and 38 deletions
+86 -23
View File
@@ -77,8 +77,72 @@ export class PostgresMigrationDatabaseError extends Error {
}
}
/**
* The platform's fixed migration connection deadline, applied when a caller does not narrow it.
* Lives here, at the one construction boundary every migration command shares, so a future CLI
* call site cannot silently omit it.
*/
export const MIGRATION_CONNECTION_TIMEOUT_MS = 10_000;
/**
* The platform's fixed migration operation deadline: both `pg`'s client-side `query_timeout` and
* PostgreSQL's own server-side `statement_timeout`. The client-side value bounds a query whose
* response never arrives; the server-side value bounds work the server is actually doing. Applied
* to every statement the session issues — history reads, advisory-lock queries, transaction
* control, migration SQL, and history writes.
*/
export const MIGRATION_OPERATION_TIMEOUT_MS = 10_000;
/**
* Connection-string parameters the pinned `[email protected]` would let silently override the timeouts
* selected above. Its `ConnectionParameters` merges as
* `Object.assign({}, config, parse(config.connectionString))`, so the **URL wins** over explicitly
* passed options — verified directly against the pinned driver, where an explicit
* `statement_timeout: 10000` alongside `?statement_timeout=0` produced a server-reported
* `statement_timeout` of `0`. Rejecting these is therefore not stylistic: without it the policy
* above is advisory.
*
* Deliberately narrow — only settings that actually conflict with the timeouts this boundary
* selects. `options` is included solely because it can carry `-c statement_timeout=...`, and is
* rejected only when it does.
*/
const CONFLICTING_TIMEOUT_PARAMETERS = Object.freeze([
"connect_timeout",
"query_timeout",
"statement_timeout",
]);
function assertNoConflictingTimeoutParameters(connectionString: string): void {
let search: URLSearchParams;
try {
search = new URL(connectionString).searchParams;
} catch {
throw databaseError(
"POSTGRES_MIGRATION_CONFIGURATION_INVALID",
"The PostgreSQL database URL is invalid.",
);
}
for (const [rawKey, rawValue] of search.entries()) {
const key = rawKey.toLowerCase();
if (CONFLICTING_TIMEOUT_PARAMETERS.includes(key)) {
throw databaseError(
"POSTGRES_MIGRATION_CONFIGURATION_INVALID",
"The PostgreSQL database URL must not set a connection or statement timeout.",
);
}
if (key === "options" && rawValue.toLowerCase().includes("statement_timeout")) {
throw databaseError(
"POSTGRES_MIGRATION_CONFIGURATION_INVALID",
"The PostgreSQL database URL must not set a connection or statement timeout.",
);
}
}
}
export interface PostgresMigrationDatabaseOptions {
/** Omitted means `MIGRATION_CONNECTION_TIMEOUT_MS`. Tests may narrow it; nothing disables it. */
readonly connectionTimeoutMs?: number;
/** Omitted means `MIGRATION_OPERATION_TIMEOUT_MS`. Tests may narrow it; nothing disables it. */
readonly operationTimeoutMs?: number;
/** The validated transport policy (`core/src/database/transport.js`). Every production executable
* that plans or applies migrations passes one; omitting it keeps the pre-existing plaintext
@@ -177,14 +241,17 @@ function createClientConfig(
throw invalidConfiguration("The PostgreSQL migration database options are invalid.");
}
const validatedConnectionTimeoutMs = validateTimeout(
connectionTimeoutMs,
"The PostgreSQL connection timeout is invalid.",
);
const validatedOperationTimeoutMs = validateTimeout(
operationTimeoutMs,
"The PostgreSQL operation timeout is invalid.",
);
// Defaults are applied here, at the shared construction boundary, so every migration command
// inherits a finite deadline without having to remember to ask for one.
const validatedConnectionTimeoutMs =
validateTimeout(connectionTimeoutMs, "The PostgreSQL connection timeout is invalid.") ??
MIGRATION_CONNECTION_TIMEOUT_MS;
const validatedOperationTimeoutMs =
validateTimeout(operationTimeoutMs, "The PostgreSQL operation timeout is invalid.") ??
MIGRATION_OPERATION_TIMEOUT_MS;
// The URL must not be able to weaken what was just selected.
assertNoConflictingTimeoutParameters(connectionString);
// Also rejects a URL carrying its own TLS parameters, so `pg`'s connection-string precedence
// can never silently replace this policy with a weaker one.
@@ -195,16 +262,10 @@ function createClientConfig(
return {
connectionString,
connectionTimeoutMillis: validatedConnectionTimeoutMs,
query_timeout: validatedOperationTimeoutMs,
...(ssl === undefined ? {} : { ssl }),
...(validatedConnectionTimeoutMs === undefined
? {}
: { connectionTimeoutMillis: validatedConnectionTimeoutMs }),
...(validatedOperationTimeoutMs === undefined
? {}
: {
query_timeout: validatedOperationTimeoutMs,
statement_timeout: validatedOperationTimeoutMs,
}),
statement_timeout: validatedOperationTimeoutMs,
};
}
@@ -402,7 +463,7 @@ class PostgresMigrationDatabaseSession implements MigrationDatabaseSession {
const transaction = Object.freeze<MigrationTransaction>({
ensureHistoryTable: async () => this.#ensureHistoryTable(),
executeStatement: async (sql) => this.#executeStatement(sql),
executeMigrationSql: async (sql) => this.#executeMigrationSql(sql),
insertAppliedMigration: async (migration) => this.#insertAppliedMigration(migration),
});
@@ -479,15 +540,17 @@ class PostgresMigrationDatabaseSession implements MigrationDatabaseSession {
}
}
async #executeStatement(sql: string): Promise<void> {
/**
* Sends one migration's complete SQL to PostgreSQL in a single simple-query call — no values, no
* prepared-statement name, no rewriting — so the server performs all SQL parsing and the packaged
* bytes are what actually execute.
*/
async #executeMigrationSql(sql: string): Promise<void> {
this.#assertTransactionActive("POSTGRES_MIGRATION_EXECUTION_FAILED");
try {
await this.#client.query(sql);
} catch {
throw databaseError(
"POSTGRES_MIGRATION_EXECUTION_FAILED",
"A module migration statement failed.",
);
throw databaseError("POSTGRES_MIGRATION_EXECUTION_FAILED", "A module migration failed.");
}
}
+14 -5
View File
@@ -4,7 +4,6 @@ import type {
} from "../modules/migration-discovery.js";
const DEFAULT_MIGRATION_LOCK_TIMEOUT_MS = 10_000;
const DRIZZLE_STATEMENT_BREAKPOINT = "--> statement-breakpoint";
export type MigrationRunnerErrorCode =
| "MIGRATION_APPROVAL_LOOKUP_FAILED"
@@ -40,7 +39,12 @@ export interface MigrationHistoryInsert {
export interface MigrationTransaction {
ensureHistoryTable(): Promise<void>;
executeStatement(sql: string): Promise<void>;
/**
* Executes one migration's **complete** SQL exactly as packaged, in a single call, inside the
* caller's transaction. Never a fragment: the runner does not split migration SQL, so the
* implementation must pass the string through to PostgreSQL unmodified.
*/
executeMigrationSql(sql: string): Promise<void>;
insertAppliedMigration(migration: MigrationHistoryInsert): Promise<void>;
}
@@ -484,9 +488,14 @@ export async function applyModuleMigrations(
await transaction.ensureHistoryTable();
for (const migration of pending) {
executingIdentity = migration.identity;
for (const statement of migration.sql.split(DRIZZLE_STATEMENT_BREAKPOINT)) {
await transaction.executeStatement(statement);
}
// PostgreSQL parses the batch, not this runner. Drizzle's `--> statement-breakpoint`
// lines are ordinary `--` comments to the server, so sending the migration whole keeps
// the marker's bytes meaningful wherever they legitimately appear — inside a string
// literal, a dollar-quoted function body, a quoted identifier, or a comment — while a
// literal `split` on those bytes tore such a migration into fragments that were no
// longer valid SQL. Deliberately not a homegrown SQL lexer and not a new parser
// dependency: the database already has the only correct parser.
await transaction.executeMigrationSql(migration.sql);
await transaction.insertAppliedMigration(freezeHistoryInsert(migration));
}
});