Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/server/test-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,31 @@
*/
import "reflect-metadata";
import { AppDataSource } from "./data-source.js";
import { AddBetterAuthTables1775574200000 } from "./migrations/1775574200000-AddBetterAuthTables.js";
import { beforeAll, afterAll } from "vitest";

beforeAll(async () => {
if (!AppDataSource.isInitialized) {
await AppDataSource.initialize();

// synchronize creates schema for entities listed in data-source.ts but
// does NOT create migration-managed tables. Better Auth's session,
// account, and verification tables are created via a migration (they're
// not TypeORM entities). On a fresh DB (e.g., CI), those tables don't
// exist — any test path that touches Better Auth (admin invite flows,
// session writes) throws "relation does not exist", which can cascade
// into unhandled rejections that crash the vitest worker.
const qr = AppDataSource.createQueryRunner();
try {
const exists = await qr.query(
`SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'verification' LIMIT 1`
);
if (exists.length === 0) {
Comment on lines +25 to +28
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of executing raw SQL against information_schema, use the built-in queryRunner.hasTable() method. It is more idiomatic for TypeORM and automatically handles schema and dialect specifics.

      if (!(await qr.hasTable("verification"))) {

await new AddBetterAuthTables1775574200000().up(qr);
}
} finally {
await qr.release();
}
Comment on lines +23 to +33
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

This manual migration check is susceptible to race conditions when running tests in parallel (Vitest's default mode). Multiple worker processes may simultaneously detect the missing table and attempt to run the migration, leading to QueryFailedError: relation "session" already exists. To resolve this, consider moving the database initialization and migration logic to a Vitest globalSetup file, which runs exactly once before any test workers are started. Alternatively, wrap this logic in a database-level advisory lock.

}
});

Expand Down
Loading