import { Global, Inject, Injectable, Module, type OnModuleDestroy } from '@nestjs/common'; import { openDrizzle, type AppDatabase, type AppSchema, type DrizzleHandle } from './drizzle/db'; // DI tokens. Repositories inject the live Drizzle db + the (dialect-matched) // schema object; they never import a dialect directly, so one implementation // serves both SQLite and Postgres. export const DRIZZLE = Symbol('DRIZZLE'); export const DRIZZLE_SCHEMA = Symbol('DRIZZLE_SCHEMA'); // The transaction + locking surface of the handle, injected where a repository // or service needs to run several writes atomically or hold a doc-scoped lock. export const DRIZZLE_TX = Symbol('DRIZZLE_TX'); export type DrizzleTx = Pick; // The opened handle (db + schema + close()); kept internal so shutdown can // release connections. const DRIZZLE_HANDLE = Symbol('DRIZZLE_HANDLE'); export type { AppDatabase, AppSchema } from './drizzle/db'; // Closes the underlying connection pool on app shutdown (no-op for SQLite). @Injectable() class DrizzleLifecycle implements OnModuleDestroy { constructor(@Inject(DRIZZLE_HANDLE) private readonly handle: DrizzleHandle) {} async onModuleDestroy(): Promise { await this.handle.close(); } } @Global() @Module({ providers: [ { // Opens the DB (runs migrations + data fixups) exactly once, app-wide. provide: DRIZZLE_HANDLE, useFactory: (): Promise => openDrizzle(), }, { provide: DRIZZLE, inject: [DRIZZLE_HANDLE], useFactory: (handle: DrizzleHandle): AppDatabase => handle.db, }, { provide: DRIZZLE_SCHEMA, inject: [DRIZZLE_HANDLE], useFactory: (handle: DrizzleHandle): AppSchema => handle.schema, }, { provide: DRIZZLE_TX, inject: [DRIZZLE_HANDLE], useFactory: (handle: DrizzleHandle): DrizzleTx => ({ runInTx: handle.runInTx, withDocLock: handle.withDocLock, dialect: handle.dialect, }), }, DrizzleLifecycle, ], exports: [DRIZZLE, DRIZZLE_SCHEMA, DRIZZLE_TX], }) export class DatabaseModule {}