Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✅ test(database): restore a migrated PGlite snapshot instead of migrating per file (#22236)

YuTengjingea16267eaa83
diff --git a/packages/database/src/core/getTestDB.ts b/packages/database/src/core/getTestDB.ts
index b965fbcfe52..58c03763ec3 100644
--- a/packages/database/src/core/getTestDB.ts
+++ b/packages/database/src/core/getTestDB.ts
@@ -1,7 +1,3 @@
-import { join } from 'node:path';
-
-import { PGlite } from '@electric-sql/pglite';
-import { vector } from '@electric-sql/pglite/vector';
import { drizzle as nodeDrizzle } from 'drizzle-orm/node-postgres';
import { migrate as nodeMigrate } from 'drizzle-orm/node-postgres/migrator';
import { drizzle as pgliteDrizzle } from 'drizzle-orm/pglite';
@@ -12,8 +8,7 @@ import { serverDBEnv } from '@/config/db';
import * as schema from '../schemas';
import type { LobeChatDatabase } from '../type';
-
-const migrationsFolder = join(__dirname, '../../migrations');
+import { createPGlite, migrationsFolder, readPGliteSnapshot } from './pgliteSnapshot';
const isServerDBMode = process.env.TEST_SERVER_DB === '1';
@@ -42,11 +37,13 @@ export const getTestDB = async (): Promise<LobeChatDatabase> => {
// Client DB mode (PGlite)
if (testClientDB) return testClientDB as unknown as LobeChatDatabase;
- const pglite = new PGlite({ extensions: { vector } });
+ const snapshot = readPGliteSnapshot();
+ const pglite = createPGlite(snapshot);
testClientDB = pgliteDrizzle({ client: pglite, schema });
+ // The global setup's snapshot is already migrated; without it, migrate here.
// pg_search migrations skip themselves when the extension is unavailable, as in PGlite.
- await pgliteMigrate(testClientDB, { migrationsFolder });
+ if (!snapshot) await pgliteMigrate(testClientDB, { migrationsFolder });
return testClientDB as unknown as LobeChatDatabase;
};
diff --git a/packages/database/src/core/pgliteSnapshot.test.ts b/packages/database/src/core/pgliteSnapshot.test.ts
new file mode 100644
index 00000000000..a27b3579bdd
--- /dev/null
+++ b/packages/database/src/core/pgliteSnapshot.test.ts
@@ -0,0 +1,77 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { sql } from 'drizzle-orm';
+import type * as PGliteMigrator from 'drizzle-orm/pglite/migrator';
+import { migrate as pgliteMigrate } from 'drizzle-orm/pglite/migrator';
+import { describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from './getTestDB';
+import {
+ createPGlite,
+ migrationsFolder,
+ PGLITE_SNAPSHOT_ENV,
+ readPGliteSnapshot,
+} from './pgliteSnapshot';
+
+vi.mock('drizzle-orm/pglite/migrator', async (importOriginal) => ({
+ ...(await importOriginal<typeof PGliteMigrator>()),
+ migrate: vi.fn(),
+}));
+
+const journal = JSON.parse(
+ readFileSync(path.join(migrationsFolder, 'meta/_journal.json'), 'utf8'),
+) as {
+ entries: unknown[];
+};
+
+const tableExists = async (pglite: ReturnType<typeof createPGlite>, table: string) => {
+ const { rows } = await pglite.query<{ exists: boolean }>(
+ `select to_regclass($1) is not null as "exists"`,
+ [table],
+ );
+ return rows[0].exists;
+};
+
+// Server DB mode migrates a real Postgres and never uses the PGlite snapshot.
+describe.skipIf(process.env.TEST_SERVER_DB === '1')('PGlite migration snapshot', () => {
+ it('is provided by the global setup with every migration applied', async () => {
+ expect(process.env[PGLITE_SNAPSHOT_ENV]).toBeTruthy();
+
+ const pglite = createPGlite(readPGliteSnapshot());
+ try {
+ const { rows } = await pglite.query<{ count: number }>(
+ 'select count(*)::int as count from drizzle.__drizzle_migrations',
+ );
+ expect(rows[0].count).toBe(journal.entries.length);
+ } finally {
+ await pglite.close();
+ }
+ });
+
+ it('getTestDB restores the snapshot instead of rerunning migrations', async () => {
+ const db = await getTestDB();
+
+ // Compare the count: printing the mock's drizzle-client arguments on failure exhausts the heap.
+ expect(vi.mocked(pgliteMigrate).mock.calls.length).toBe(0);
+ const { rows } = await db.execute<{ exists: boolean }>(
+ sql`select to_regclass('public.users') is not null as "exists"`,
+ );
+ expect(rows[0].exists).toBe(true);
+ });
+
+ it('restores independent databases from the same snapshot', async () => {
+ const snapshot = readPGliteSnapshot();
+ const first = createPGlite(snapshot);
+ const second = createPGlite(snapshot);
+
+ try {
+ await first.exec('create table snapshot_isolation_probe (id int)');
+
+ expect(await tableExists(first, 'snapshot_isolation_probe')).toBe(true);
+ expect(await tableExists(second, 'snapshot_isolation_probe')).toBe(false);
+ } finally {
+ await Promise.all([first.close(), second.close()]);
+ }
+ });
+});
diff --git a/packages/database/src/core/pgliteSnapshot.ts b/packages/database/src/core/pgliteSnapshot.ts
new file mode 100644
index 00000000000..834eebd66aa
--- /dev/null
+++ b/packages/database/src/core/pgliteSnapshot.ts
@@ -0,0 +1,51 @@
+import { readFileSync } from 'node:fs';
+import { writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+
+import { PGlite } from '@electric-sql/pglite';
+import { vector } from '@electric-sql/pglite/vector';
+import { drizzle as pgliteDrizzle } from 'drizzle-orm/pglite';
+import { migrate as pgliteMigrate } from 'drizzle-orm/pglite/migrator';
+
+/**
+ * Env var holding the path of a fully migrated PGlite data dir dump.
+ *
+ * Set by `tests/pgliteSnapshot.globalSetup.ts` once per Vitest run and read by
+ * `getTestDB()` in every test file. Test files are isolated, so without the
+ * snapshot each file re-ran all migrations (~1.7s uncontended); under CI CPU
+ * contention that first `getTestDB()` call intermittently exceeded the 10s
+ * hook timeout. Restoring the dump takes ~0.2s.
+ */
+export const PGLITE_SNAPSHOT_ENV = 'LOBE_TEST_PGLITE_SNAPSHOT';
+
+export const migrationsFolder = join(__dirname, '../../migrations');
+
+export const createPGlite = (loadDataDir?: Blob) =>
+ new PGlite({ extensions: { vector }, loadDataDir });
+
+/**
+ * Run every migration on a fresh PGlite instance and write its data dir dump to `filePath`.
+ */
+export const writeMigratedPGliteSnapshot = async (filePath: string) => {
+ const pglite = createPGlite();
+
+ try {
+ // pg_search migrations skip themselves when the extension is unavailable, as in PGlite.
+ await pgliteMigrate(pgliteDrizzle({ client: pglite }), { migrationsFolder });
+ const dump = await pglite.dumpDataDir('none');
+ await writeFile(filePath, Buffer.from(await dump.arrayBuffer()));
+ } finally {
+ await pglite.close();
+ }
+};
+
+/**
+ * Read the snapshot announced by the global setup, or `undefined` when the
+ * current run has none (e.g. a Vitest config without the global setup).
+ */
+export const readPGliteSnapshot = (): Blob | undefined => {
+ const filePath = process.env[PGLITE_SNAPSHOT_ENV];
+ if (!filePath) return;
+
+ return new Blob([readFileSync(filePath)]);
+};
diff --git a/packages/database/tests/pgliteSnapshot.globalSetup.ts b/packages/database/tests/pgliteSnapshot.globalSetup.ts
new file mode 100644
index 00000000000..7994397760f
--- /dev/null
+++ b/packages/database/tests/pgliteSnapshot.globalSetup.ts
@@ -0,0 +1,32 @@
+import { existsSync } from 'node:fs';
+import { rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { PGLITE_SNAPSHOT_ENV, writeMigratedPGliteSnapshot } from '../src/core/pgliteSnapshot';
+
+/**
+ * Migrate a PGlite database once per Vitest run so `getTestDB()` can restore it
+ * in each test file instead of re-running every migration. Workers inherit the
+ * env var because they are spawned after global setup.
+ *
+ * Watch mode keeps the snapshot from startup: restart Vitest after editing a migration.
+ */
+export default async function setup() {
+ // Server DB mode migrates a real Postgres once per worker already.
+ if (process.env.TEST_SERVER_DB === '1') return;
+
+ // Global setup runs once per project; the root config's `app` and `server`
+ // projects share the snapshot built by whichever runs first.
+ const existing = process.env[PGLITE_SNAPSHOT_ENV];
+ if (existing && existsSync(existing)) return;
+
+ const filePath = join(tmpdir(), `lobe-pglite-snapshot-${process.pid}.tar`);
+ await writeMigratedPGliteSnapshot(filePath);
+ process.env[PGLITE_SNAPSHOT_ENV] = filePath;
+
+ return async () => {
+ delete process.env[PGLITE_SNAPSHOT_ENV];
+ await rm(filePath, { force: true });
+ };
+}
diff --git a/packages/database/vitest.config.mts b/packages/database/vitest.config.mts
index 482f4235540..c6d7fd24c2d 100644
--- a/packages/database/vitest.config.mts
+++ b/packages/database/vitest.config.mts
@@ -1,4 +1,5 @@
import { resolve } from 'node:path';
+
import { defineConfig } from 'vitest/config';
export default defineConfig({
@@ -29,7 +30,6 @@ export default defineConfig({
'@/server/services': resolve(__dirname, '../../apps/server/src/services'),
'@/server/modules': resolve(__dirname, '../../apps/server/src/modules'),
'@': resolve(__dirname, '../../src'),
-
},
coverage: {
exclude: [
@@ -64,6 +64,8 @@ export default defineConfig({
inline: ['vitest-canvas-mock'],
},
},
+ // Migrates PGlite once per run so each DB test file restores a snapshot.
+ globalSetup: './tests/pgliteSnapshot.globalSetup.ts',
setupFiles: './tests/setup-db.ts',
},
});
diff --git a/vitest.config.mts b/vitest.config.mts
index b1daea550a1..e17cacf7b8a 100644
--- a/vitest.config.mts
+++ b/vitest.config.mts
@@ -281,6 +281,8 @@ export default defineConfig({
],
},
},
+ // Migrates PGlite once per run so each DB test file restores a snapshot.
+ globalSetup: join(__dirname, './packages/database/tests/pgliteSnapshot.globalSetup.ts'),
setupFiles: join(__dirname, './tests/setup.ts'),
},
});