Add support for pglite

This commit is contained in:
Alex Gleason
2024-09-07 16:38:28 -05:00
parent 044708d49f
commit 69329674e1
6 changed files with 84 additions and 5 deletions

View File

@@ -82,7 +82,7 @@ class Conf {
* ```
*/
static get databaseUrl(): string {
return Deno.env.get('DATABASE_URL') ?? 'sqlite://data/db.sqlite3';
return Deno.env.get('DATABASE_URL') ?? 'pglite://data/pgdata';
}
static db = {
get url(): url.UrlWithStringQuery {
@@ -92,6 +92,7 @@ class Conf {
switch (Conf.db.url.protocol) {
case 'sqlite:':
return 'sqlite';
case 'pglite:':
case 'postgres:':
case 'postgresql:':
return 'postgres';

View File

@@ -5,6 +5,7 @@ import { NDatabaseSchema, NPostgresSchema } from '@nostrify/db';
import { FileMigrationProvider, Kysely, Migrator } from 'kysely';
import { Conf } from '@/config.ts';
import { DittoPglite } from '@/db/adapters/DittoPglite.ts';
import { DittoPostgres } from '@/db/adapters/DittoPostgres.ts';
import { DittoSQLite } from '@/db/adapters/DittoSQLite.ts';
import { DittoTables } from '@/db/DittoTables.ts';
@@ -30,12 +31,17 @@ export class DittoDB {
static async _getInstance(): Promise<DittoDatabase> {
const result = {} as DittoDatabase;
switch (Conf.db.dialect) {
case 'sqlite':
switch (Conf.db.url.protocol) {
case 'sqlite:':
result.dialect = 'sqlite';
result.kysely = await DittoSQLite.getInstance();
break;
case 'postgres':
case 'pglite:':
result.dialect = 'postgres';
result.kysely = await DittoPglite.getInstance();
break;
case 'postgres:':
case 'postgresql:':
result.dialect = 'postgres';
result.kysely = await DittoPostgres.getInstance();
break;

View File

@@ -0,0 +1,56 @@
import { PGlite } from '@electric-sql/pglite';
import { NPostgresSchema } from '@nostrify/db';
import { PgliteDialect } from '@soapbox/kysely-pglite';
import { Kysely } from 'kysely';
import { Conf } from '@/config.ts';
import { DittoTables } from '@/db/DittoTables.ts';
import { KyselyLogger } from '@/db/KyselyLogger.ts';
export class DittoPglite {
static db: Kysely<DittoTables> & Kysely<NPostgresSchema> | undefined;
// deno-lint-ignore require-await
static async getInstance(): Promise<Kysely<DittoTables> & Kysely<NPostgresSchema>> {
if (!this.db) {
this.db = new Kysely({
dialect: new PgliteDialect({
database: new PGlite(this.path),
}),
log: KyselyLogger,
}) as Kysely<DittoTables> & Kysely<NPostgresSchema>;
}
return this.db;
}
static get poolSize() {
return 1;
}
static get availableConnections(): number {
return 1;
}
/** Get the relative or absolute path based on the `DATABASE_URL`. */
static get path(): string | undefined {
if (Conf.databaseUrl === 'pglite://:memory:') {
return undefined;
}
const { host, pathname } = Conf.db.url;
if (!pathname) return '';
// Get relative path.
if (host === '') {
return pathname;
} else if (host === '.') {
return pathname;
} else if (host) {
return host + pathname;
}
return '';
}
}