fix(db): refuse a Postgres boot that would leave a SQLite install behind

Setting TREK_DB_URL on an existing SQLite install booted a new, empty
instance beside its data. The Postgres bootstrap now refuses an empty
database, or a migrated one without a single account, while the data
directory's travel.db holds accounts, and names the move command. A file
that cannot be read counts as holding them. TREK_DB_IGNORE_SQLITE_FILE=true
starts anyway, with a warning; the file is opened read-only and only when
the database holds no TREK data.
This commit is contained in:
Maurice
2026-11-17 13:41:12 +01:00
parent c6f6dd2d57
commit 1ea08dcf0a
10 changed files with 426 additions and 10 deletions
+1
View File
@@ -57,6 +57,7 @@ DEMO_MODE=false # Demo mode: resets data hourly
# TREK_DB_POOL_MAX=10 # Most connections TREK opens to the Postgres database (1 to 100). Unused on SQLite. (default: 10)
# TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot.
# TREK_DB_PRE_MIGRATE_SNAPSHOT=true # Copy the database to data/pre-migrate-<schema>-<time>.db (a .pgdump made with pg_dump on Postgres) before a startup migrates it, so the previous image can run on the copy again. A copy that cannot be written stops the startup; false migrates without one.
# TREK_DB_IGNORE_SQLITE_FILE=false # With TREK_DB_URL set, TREK refuses to start on a Postgres database that holds no TREK data while data/travel.db holds an existing SQLite install, because it would come up as a new, empty instance beside it. Move the install with the move-to-postgres command instead (wiki: Database-Postgres). true starts on the empty database anyway. Unused on SQLite. (default: false)
# TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP=3 # How many pre-migrate copies to keep, newest first (1 to 100). (default: 3)
# TREK_DB_SYNCHRONOUS=NORMAL # How hard SQLite flushes to disk (OFF, NORMAL, FULL, EXTRA). Defaults to NORMAL under WAL and FULL under any other journal mode — leave it alone unless you know why you want otherwise. Both variables fall back to their default (with a warning in the log) if the value is not a mode SQLite knows.
+6 -1
View File
@@ -135,7 +135,12 @@ async function bootstrapBefore(url: string, before: readonly string[]): Promise<
migrations: { ...config.migrations, silent: true, migrationsList: await loadMigrations(before) },
});
try {
await bootstrapPostgresSchema(orm, { ...defaultPostgresBootstrapDeps(url), safetyNet: NO_SAFETY_NET });
await bootstrapPostgresSchema(orm, {
...defaultPostgresBootstrapDeps(url),
safetyNet: NO_SAFETY_NET,
// A scratch database of its own: a SQLite install in the developer's data directory is beside the point.
sqliteLeftBehind: () => null,
});
} finally {
await orm.close(true);
}
+1
View File
@@ -168,6 +168,7 @@ OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE,
ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL,
TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP) (read when a migration run starts; the
legacy-upgrade suites set it per file),
TREK_DB_IGNORE_SQLITE_FILE (read when a Postgres boot finds no TREK data),
ADMIN_PASSWORD, IDEMPOTENCY_TTL_SECONDS, MCP_RATE_LIMIT (request-path check),
LLM_TIMEOUT_MS, LLM_MAX_OUTPUT_TOKENS, NOMINATIM_URL, VAPID_* (resolved per use by the Web Push key
service, which the notification suites build without the container).
+5
View File
@@ -383,6 +383,11 @@ export function deriveDb(raw: RawEnv) {
preMigrateSnapshot: parseBool(raw.TREK_DB_PRE_MIGRATE_SNAPSHOT),
/** How many pre-migration snapshots stay in the data dir, newest first. */
preMigrateSnapshotKeep: Math.min(positiveIntOr(raw.TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP, 3), 100),
/**
* Start on Postgres although data/travel.db holds a SQLite install with
* accounts. Only an explicit true: anything else keeps the refusal.
*/
ignoreSqliteFile: parseBool(raw.TREK_DB_IGNORE_SQLITE_FILE) === true,
};
}
+4
View File
@@ -197,6 +197,10 @@ export const envSchema = z.object({
// or a misspelt "on" turn it off.
TREK_DB_PRE_MIGRATE_SNAPSHOT: boolStr,
TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP: integer(1, 100),
// Starts on an empty Postgres database although the data directory holds a
// SQLite install with accounts, which the boot otherwise refuses. Strict like
// the switch above: a misspelt value must not let the refusal through.
TREK_DB_IGNORE_SQLITE_FILE: boolStr,
TREK_WIKI_DIR: anyString,
TREK_PLACE_PHOTO_DIR: anyString,
BACKUP_UPLOAD_LIMIT_MB: positiveNumber,
@@ -5,14 +5,10 @@ import { knownMigrationNames } from '../../known-migrations';
import { migrationLabel, REFUSAL, refuseNewerDatabase, type MigrationSafetyNet } from '../../legacy-baseline';
import type { AnyOrm } from '../../orm';
import { listSnapshots, PREFIX, pruneSnapshots, stamp } from '../../pre-migrate-snapshot';
import { sqliteInstallHoldsAccounts } from '../sqlite/sqlite-source';
import { readPostgresBaseline, type PostgresBaseline } from './baseline';
import { pgDump } from './pg-tools';
import {
PRIVILEGED_ROLE_SQL,
PRIVILEGED_ROLE_WARNING,
refuseUnsupportedServer,
serverMajor,
} from './server-checks';
import { PRIVILEGED_ROLE_SQL, PRIVILEGED_ROLE_WARNING, refuseUnsupportedServer, serverMajor } from './server-checks';
import type { Connection } from '@mikro-orm/core';
import type { Migrator } from '@mikro-orm/migrations';
import { Logger } from '@nestjs/common';
@@ -30,6 +26,50 @@ export interface PostgresBootstrapDeps {
baseline: () => PostgresBaseline;
known: Set<string>;
safetyNet: MigrationSafetyNet;
/**
* The SQLite install a boot on a database without TREK data would leave
* behind: the path of a SQLite file in the data directory that holds
* accounts, or null when there is none (or the operator said to start
* anyway). Read only when the database holds no TREK data, so a boot on a
* database in use never opens the file.
*/
sqliteLeftBehind: () => string | null;
}
/** The command that moves a SQLite install into Postgres, as the refusal names it. */
const MOVE_COMMAND_HINT =
'docker compose run --rm --user node -w /app/server app node --require tsconfig-paths/register ' +
'dist/move-to-postgres.js (npm run db:move-to-postgres in server/ outside Docker)';
/**
* The refusal of a boot that would come up empty on Postgres while `file`
* holds the install's data.
*/
function leftBehindRefusal(file: string): string {
return (
`${REFUSAL} TREK_DB_URL points at a Postgres database that holds no TREK data, while ${file} holds an ` +
'existing SQLite install with accounts. Starting would bring up a new, empty TREK beside it. To move that ' +
`install to Postgres, stop TREK and run the move command: ${MOVE_COMMAND_HINT}. The wiki page ` +
'Database-Postgres ("Moving an existing install to Postgres") has the steps. To start on the empty ' +
'database on purpose, set TREK_DB_IGNORE_SQLITE_FILE=true; to keep running on SQLite, unset TREK_DB_URL.'
);
}
/**
* Whether the database holds an account. A database TREK created always does
* once its first boot finished; one without is what a move that stopped part
* of the way, or a first boot that died before seeding, leaves.
*/
async function holdsAccounts(connection: Connection, tables: readonly string[]): Promise<boolean> {
if (!tables.includes('users')) return false;
const rows: unknown[] = await connection.execute('select 1 as present from users limit 1');
return rows.length > 0;
}
/** Refuses the boot when `sqliteLeftBehind` names a SQLite install this boot would leave behind. */
function refuseLeavingSqliteBehind(deps: PostgresBootstrapDeps): void {
const file = deps.sqliteLeftBehind();
if (file !== null) throw new Error(leftBehindRefusal(file));
}
/**
@@ -147,9 +187,13 @@ export async function bootstrapPostgresSchema(orm: AnyOrm, deps: PostgresBootstr
const executed = tables.includes(historyTable) ? (await migrator.getExecuted()).map((row) => row.name) : [];
if (executed.length === 0) {
// An empty database (a database holding other tables is refused below, with its own message).
if (tables.every((table) => table === historyTable)) refuseLeavingSqliteBehind(deps);
await createFromBaseline(connection, migrator.getStorage(), tables, historyTable, deps.baseline);
} else {
await refuseNewerHistory(executed, deps);
// A schema without a single account holds no TREK data either; only then is the SQLite file looked at.
if (!(await holdsAccounts(connection, tables))) refuseLeavingSqliteBehind(deps);
}
const pending = await migrator.getPending();
@@ -229,7 +273,37 @@ export function postgresSafetyNet(
};
}
/** What a production boot passes: the committed baseline, the migrations on disk, the safety net above. */
export function defaultPostgresBootstrapDeps(url: string): PostgresBootstrapDeps {
return { baseline: readPostgresBaseline, known: knownMigrationNames(), safetyNet: postgresSafetyNet(url) };
/**
* The SQLite install a Postgres boot would leave behind (`PostgresBootstrapDeps.sqliteLeftBehind`):
* the SQLite file the data directory resolves to (`data/travel.db`), when it
* holds accounts. A file that cannot be read counts as holding them, so the
* check fails closed. `TREK_DB_IGNORE_SQLITE_FILE=true` lets the boot through
* with a warning. Off under NODE_ENV=test, where the data directory is the
* developer's own.
*/
export function sqliteLeftBehindCheck(
env: () => AppEnv = readEnv,
holdsAccounts: (file: string) => boolean = sqliteInstallHoldsAccounts,
): () => string | null {
return () => {
const current = env();
if (current.app.isTest) return null;
const file = resolveDataPaths(current).dbFile;
if (!holdsAccounts(file)) return null;
if (current.db.ignoreSqliteFile) {
logger.warn(`TREK_DB_IGNORE_SQLITE_FILE is set: starting on Postgres beside the SQLite install in ${file}`);
return null;
}
return file;
};
}
/** What a production boot passes: the committed baseline, the migrations on disk, the safety net and the check above. */
export function defaultPostgresBootstrapDeps(url: string): PostgresBootstrapDeps {
return {
baseline: readPostgresBaseline,
known: knownMigrationNames(),
safetyNet: postgresSafetyNet(url),
sqliteLeftBehind: sqliteLeftBehindCheck(),
};
}
@@ -0,0 +1,231 @@
import Database from 'better-sqlite3';
import fs from 'node:fs';
/**
* A SQLite file opened for reading only, for the move to Postgres and the
* Postgres boot's check for an install left behind. It never writes: the
* handle is read-only, and every read runs in one read transaction, so the
* whole move sees the file as it was at one moment.
*
* Integers come back as `bigint` (better-sqlite3's safe integers), so a value
* past 2^53 keeps every digit.
*/
/** A column as `pragma_table_info` describes it. */
export interface SqliteColumn {
name: string;
/** The declared type, as written in the CREATE TABLE (may be empty). */
declaredType: string;
notNull: boolean;
/** Its position in the primary key, from 1; 0 when it is not part of it. */
primaryKey: number;
/** The default as SQL text, or null. */
defaultSql: string | null;
}
/** An index of a table, as `pragma_index_list` and `pragma_index_info` describe it. */
export interface SqliteIndex {
name: string;
unique: boolean;
/** Where it comes from: `c` a CREATE INDEX, `u` a UNIQUE constraint, `pk` the primary key. */
origin: string;
partial: boolean;
/** The indexed columns in order; null when one of them is an expression. */
columns: string[] | null;
}
/** A row whose foreign key points at nothing, from `pragma_foreign_key_check`. */
interface OrphanRow {
table: string;
rowid: bigint | null;
parent: string;
}
/** `name` as a SQLite identifier. */
function quoteSqliteIdentifier(name: string): string {
return `"${name.replaceAll('"', '""')}"`;
}
export class SqliteSource {
private constructor(
private readonly db: Database.Database,
readonly file: string,
) {}
/**
* Opens `file` read-only and starts the read transaction. A file that does
* not exist is refused rather than created.
*/
static open(file: string): SqliteSource {
if (!fs.existsSync(file)) throw new Error(`There is no SQLite file at ${file}.`);
const db = new Database(file, { readonly: true, fileMustExist: true });
try {
db.defaultSafeIntegers(true);
db.exec('BEGIN');
return new SqliteSource(db, file);
} catch (err) {
db.close();
throw err;
}
}
close(): void {
if (!this.db.open) return;
if (this.db.inTransaction) this.db.exec('ROLLBACK');
this.db.close();
}
private names(sql: string, ...params: unknown[]): string[] {
return this.db
.prepare(sql)
.pluck()
.all(...params)
.map((value) => String(value));
}
/** The user tables, by name, without SQLite's own (`sqlite_*`). */
tables(): string[] {
return this.names(
"select name from sqlite_master where type = 'table' and name not like 'sqlite\\_%' escape '\\' order by name",
);
}
/** The views and triggers, which the move does not carry for a plugin's database. */
viewsAndTriggers(): Array<{ type: string; name: string }> {
return this.db
.prepare("select type, name from sqlite_master where type in ('view', 'trigger') order by type, name")
.all() as Array<{ type: string; name: string }>;
}
hasTable(name: string): boolean {
return this.names("select name from sqlite_master where type = 'table' and name = ?", name).length > 0;
}
/** The names TREK's migration history holds; null when the file has no history table. */
migrationNames(): string[] | null {
if (!this.hasTable('mikro_orm_migrations')) return null;
return this.names('select name from mikro_orm_migrations order by name');
}
columns(table: string): SqliteColumn[] {
const rows = this.db
.prepare('select name, type, "notnull", pk, dflt_value from pragma_table_info(?) order by cid')
.all(table) as Array<{
name: string;
type: string | null;
notnull: bigint;
pk: bigint;
dflt_value: string | null;
}>;
return rows.map((row) => ({
name: row.name,
declaredType: row.type ?? '',
notNull: row.notnull !== 0n,
primaryKey: Number(row.pk),
defaultSql: row.dflt_value,
}));
}
indexes(table: string): SqliteIndex[] {
const list = this.db
.prepare('select name, "unique", origin, partial from pragma_index_list(?)')
.all(table) as Array<{
name: string;
unique: bigint;
origin: string;
partial: bigint;
}>;
return list.map((index) => {
const keys = this.db
.prepare('select cid, name from pragma_index_info(?) order by seqno')
.all(index.name) as Array<{
cid: bigint;
name: string | null;
}>;
const columns = keys.every((key) => key.cid >= 0n && key.name !== null)
? keys.map((key) => String(key.name))
: null;
return {
name: index.name,
unique: index.unique !== 0n,
origin: index.origin,
partial: index.partial !== 0n,
columns,
};
});
}
hasRows(table: string): boolean {
return this.db.prepare(`select 1 from ${quoteSqliteIdentifier(table)} limit 1`).get() !== undefined;
}
count(table: string): number {
return Number(
this.db
.prepare(`select count(*) from ${quoteSqliteIdentifier(table)}`)
.pluck()
.get(),
);
}
/** What `typeof()` answers for the column's values that are not NULL: `integer`, `real`, `text`, `blob`. */
storageClasses(table: string, column: string): Set<string> {
const quoted = quoteSqliteIdentifier(column);
return new Set(
this.names(`select distinct typeof(${quoted}) from ${quoteSqliteIdentifier(table)} where ${quoted} is not null`),
);
}
/** The rows of `table`, one array of `columns` per row, read one at a time. */
rows(table: string, columns: readonly string[]): IterableIterator<unknown[]> {
const list = columns.map(quoteSqliteIdentifier).join(', ');
return this.db
.prepare(`select ${list} from ${quoteSqliteIdentifier(table)}`)
.raw(true)
.iterate() as IterableIterator<unknown[]>;
}
/** The highest id each AUTOINCREMENT table ever handed out, which can be above the largest id left. */
autoincrementSeen(): Map<string, bigint> {
if (!this.hasTable('sqlite_sequence')) return new Map();
const rows = this.db.prepare('select name, seq from sqlite_sequence').all() as Array<{ name: string; seq: bigint }>;
return new Map(rows.map((row) => [row.name, BigInt(row.seq)]));
}
/** Up to `limit` rows whose foreign key points at a row that does not exist. */
orphans(limit: number): OrphanRow[] {
const rows = this.db
.prepare('select "table", rowid, parent from pragma_foreign_key_check limit ?')
.all(limit) as Array<{
table: string;
rowid: bigint | null;
parent: string;
}>;
return rows;
}
}
/**
* Whether `file` is a SQLite install holding accounts: a `users` table with a
* row. A missing or empty file holds none. A file that cannot be read is
* reported as holding some, so a check built on this fails closed.
*/
export function sqliteInstallHoldsAccounts(file: string): boolean {
let size: number;
try {
size = fs.statSync(file).size;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;
return true;
}
if (size === 0) return false;
let source: SqliteSource | null = null;
try {
source = SqliteSource.open(file);
return source.hasTable('users') && source.hasRows('users');
} catch {
return true;
} finally {
source?.close();
}
}
@@ -396,6 +396,15 @@ describe('deriveDb: the pre-migration snapshot', () => {
});
});
describe('deriveDb: starting on Postgres beside a SQLite install', () => {
it('keeps the refusal unless TREK_DB_IGNORE_SQLITE_FILE is an explicit true', () => {
expect(deriveDb({}).ignoreSqliteFile).toBe(false);
expect(deriveDb({ TREK_DB_IGNORE_SQLITE_FILE: 'false' }).ignoreSqliteFile).toBe(false);
expect(deriveDb({ TREK_DB_IGNORE_SQLITE_FILE: 'yes' }).ignoreSqliteFile).toBe(true);
expect(deriveDb({ TREK_DB_IGNORE_SQLITE_FILE: 'true' }).ignoreSqliteFile).toBe(true);
});
});
describe('deriveDb: the engine', () => {
it('DB-ENGINE-001: SQLite unless TREK_DB_URL names a database', () => {
expect(deriveDb({})).toMatchObject({ engine: 'sqlite' });
@@ -342,6 +342,13 @@ describe('validateEnvAtBoot: the pre-migration snapshot switches', () => {
});
});
describe('validateEnvAtBoot: TREK_DB_IGNORE_SQLITE_FILE', () => {
it('refuses a misspelt value instead of letting the refusal through', () => {
expect(() => validateEnvAtBoot({ TREK_DB_IGNORE_SQLITE_FILE: 'true' })).not.toThrow();
expect(bootReport({ TREK_DB_IGNORE_SQLITE_FILE: 'ture' }).thrown).toMatch(/Invalid environment configuration/);
});
});
describe('validateEnvAtBoot: the database engine', () => {
afterEach(() => {
vi.restoreAllMocks();
@@ -7,6 +7,7 @@ import type { AppEnv } from '../../../../../src/app-config';
import {
bootstrapPostgresSchema,
postgresSafetyNet,
sqliteLeftBehindCheck,
type PostgresBootstrapDeps,
} from '../../../../../src/db/engine/postgres/schema-bootstrap';
import type { MigrationSafetyNet } from '../../../../../src/db/legacy-baseline';
@@ -38,11 +39,14 @@ interface FakeDb {
server: { schema: string | null; version: string; privileged: boolean };
/** The ORM's migrations option, which the bootstrap points at the current schema. */
migrations: { tableName?: string };
/** Whether the users table holds a row: a database in use does. */
accounts: boolean;
}
type FakeState = Pick<FakeDb, 'executed' | 'pending' | 'tables'> & {
history?: boolean;
server?: Partial<FakeDb['server']>;
accounts?: boolean;
};
function fakeOrm(state: FakeState): {
@@ -54,6 +58,7 @@ function fakeOrm(state: FakeState): {
server: { schema: 'public', version: '170004', privileged: false, ...state.server },
migrations: { tableName: 'mikro_orm_migrations' },
history: state.history ?? state.executed.length > 0,
accounts: state.accounts ?? true,
ensureTable: vi.fn(async () => {
db.history = true;
}),
@@ -66,6 +71,7 @@ function fakeOrm(state: FakeState): {
const connection = {
execute: vi.fn(async (sql: string, _params?: unknown[], _method?: string, ctx?: unknown) => {
if (sql.includes('server_version_num')) return [db.server];
if (sql.includes('from users')) return db.accounts ? [{ present: 1 }] : [];
if (sql.includes('information_schema.tables')) {
return [...db.tables, ...(db.history ? ['mikro_orm_migrations'] : [])].map((table_name) => ({ table_name }));
}
@@ -99,6 +105,7 @@ function fakeOrm(state: FakeState): {
function deps(
safetyNet: MigrationSafetyNet = { beforeMigrate: vi.fn(async () => undefined), restoreHint: async () => null },
sqliteLeftBehind: () => string | null = () => null,
) {
const value: PostgresBootstrapDeps = {
baseline: () => ({
@@ -108,6 +115,7 @@ function deps(
}),
known: new Set([M1, M2, M3]),
safetyNet,
sqliteLeftBehind,
};
return value;
}
@@ -227,6 +235,55 @@ describe('bootstrapPostgresSchema', () => {
expect(db.ensureTable).not.toHaveBeenCalled();
});
const LEFT_BEHIND = '/app/data/travel.db';
const noNet = () => ({ beforeMigrate: vi.fn(async () => undefined), restoreHint: async () => null });
it('PGBOOT-030: an empty database beside a SQLite install with accounts is refused before anything is written', async () => {
const { orm, db } = fakeOrm({ executed: [], pending: [M1, M2], tables: [] });
await expect(
bootstrapPostgresSchema(
orm,
deps(noNet(), () => LEFT_BEHIND),
),
).rejects.toThrow(
/Refusing to boot: TREK_DB_URL points at a Postgres database that holds no TREK data, while \/app\/data\/travel\.db .*move-to-postgres.*TREK_DB_IGNORE_SQLITE_FILE=true/s,
);
expect(db.sql).toEqual([]);
expect(db.ensureTable).not.toHaveBeenCalled();
});
it('PGBOOT-031: a schema without a single account (a move cut short) beside such an install is refused too', async () => {
const { orm, db } = fakeOrm({ executed: [M1, M2], pending: [M3], tables: ['users'], accounts: false });
const net = deps(noNet(), () => LEFT_BEHIND);
await expect(bootstrapPostgresSchema(orm, net)).rejects.toThrow(/holds no TREK data/);
expect(db.up).not.toHaveBeenCalled();
expect(net.safetyNet.beforeMigrate).not.toHaveBeenCalled();
});
it('PGBOOT-032: a database in use never looks at the SQLite file', async () => {
const { orm, db } = fakeOrm({ executed: [M1, M2, M3], pending: [], tables: ['users'] });
const leftBehind = vi.fn(() => LEFT_BEHIND);
await bootstrapPostgresSchema(orm, deps(noNet(), leftBehind));
expect(leftBehind).not.toHaveBeenCalled();
expect(db.up).not.toHaveBeenCalled();
});
it('PGBOOT-033: a database with foreign tables keeps its own refusal; without a SQLite install an empty one boots', async () => {
const foreign = fakeOrm({ executed: [], pending: [M1], tables: ['customers'] });
await expect(
bootstrapPostgresSchema(
foreign.orm,
deps(noNet(), () => LEFT_BEHIND),
),
).rejects.toThrow(/no TREK migration history/);
const empty = fakeOrm({ executed: [], pending: [M1, M2], tables: [] });
await bootstrapPostgresSchema(
empty.orm,
deps(noNet(), () => null),
);
expect(empty.db.logged).toEqual([M1, M2]);
});
it('PGBOOT-024: a role that could reach the database host boots with a warning', async () => {
const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
const { orm } = fakeOrm({ executed: [M1, M2, M3], pending: [], tables: ['users'], server: { privileged: true } });
@@ -235,6 +292,28 @@ describe('bootstrapPostgresSchema', () => {
});
});
describe('sqliteLeftBehindCheck', () => {
const envWith = (isTest: boolean, ignoreSqliteFile: boolean) => () =>
({ db: { trekDbFile: '/data/travel.db', ignoreSqliteFile }, app: { isTest } }) as unknown as AppEnv;
it('PGBOOT-034: names the SQLite file when it holds accounts, and nothing when it holds none', () => {
expect(sqliteLeftBehindCheck(envWith(false, false), () => true)()).toBe('/data/travel.db');
expect(sqliteLeftBehindCheck(envWith(false, false), () => false)()).toBeNull();
});
it('PGBOOT-035: TREK_DB_IGNORE_SQLITE_FILE lets the boot through with a warning', () => {
const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
expect(sqliteLeftBehindCheck(envWith(false, true), () => true)()).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('TREK_DB_IGNORE_SQLITE_FILE is set'));
});
it('PGBOOT-036: stays out of the way under test, without opening the file', () => {
const holds = vi.fn(() => true);
expect(sqliteLeftBehindCheck(envWith(true, false), holds)()).toBeNull();
expect(holds).not.toHaveBeenCalled();
});
});
describe('postgresSafetyNet', () => {
const URL = 'postgresql://trek:pw@db/trek';
const NOW = new Date('2026-11-02T13:05:09Z');