import knex, { type Knex } from 'knex'; import ClientPgLite from 'knex-pglite'; import { PGlite } from '@electric-sql/pglite'; import { vector } from '@electric-sql/pglite/vector'; import { destroy, type Services } from '../../utils/utils.services.js'; import { migrationSource } from './migrations/migrations.js'; class DatabaseService { #services: Services; #instance?: Promise; constructor(services: Services) { this.#services = services; } #setup = async () => { const pglite = new PGlite({ extensions: { vector }, }); const instance = knex({ client: ClientPgLite, dialect: 'postgres', connection: () => ({ pglite }) as object, }); await instance.raw(`CREATE EXTENSION IF NOT EXISTS vector`); await instance.migrate.latest({ migrationSource: migrationSource({ services: this.#services }), }); return instance; }; public getInstance = () => { if (!this.#instance) { this.#instance = this.#setup(); } return this.#instance; }; [destroy] = async () => { if (!this.#instance) { return; } const instance = await this.#instance; await instance.destroy(); }; } export { type TableRows, tableNames } from './migrations/migrations.js'; export { DatabaseService };