ditto/src/db.ts

110 lines
2.3 KiB
TypeScript
Raw Normal View History

2023-08-07 06:45:02 +00:00
import fs from 'node:fs/promises';
import path from 'node:path';
2023-12-01 23:57:01 +00:00
import { DenoSqlite3, DenoSqlite3Dialect, FileMigrationProvider, Kysely, Migrator } from '@/deps.ts';
2023-08-10 18:37:56 +00:00
import { Conf } from '@/config.ts';
import { getPragma, setPragma } from '@/pragma.ts';
2023-07-09 16:47:19 +00:00
interface DittoDB {
events: EventRow;
2023-08-30 17:04:45 +00:00
events_fts: EventFTSRow;
tags: TagRow;
users: UserRow;
relays: RelayRow;
unattached_media: UnattachedMediaRow;
}
interface EventRow {
id: string;
kind: number;
2023-08-06 17:54:00 +00:00
pubkey: string;
content: string;
created_at: number;
tags: string;
sig: string;
2023-08-06 17:54:00 +00:00
}
2023-07-09 16:47:19 +00:00
2023-08-30 17:04:45 +00:00
interface EventFTSRow {
id: string;
content: string;
}
interface TagRow {
tag: string;
value: string;
event_id: string;
}
2023-07-09 16:47:19 +00:00
interface UserRow {
pubkey: string;
username: string;
inserted_at: Date;
2023-09-03 23:49:45 +00:00
admin: 0 | 1;
}
interface RelayRow {
url: string;
2023-08-16 00:07:26 +00:00
domain: string;
active: boolean;
}
interface UnattachedMediaRow {
id: string;
pubkey: string;
2023-09-09 23:12:54 +00:00
url: string;
data: string;
uploaded_at: Date;
}
const db = new Kysely<DittoDB>({
2023-12-01 23:57:01 +00:00
dialect: new DenoSqlite3Dialect({
2023-10-12 04:34:59 +00:00
database: new DenoSqlite3(Conf.dbPath),
2023-08-07 06:45:02 +00:00
}),
});
// Set PRAGMA values.
2023-10-12 04:34:59 +00:00
await Promise.all([
setPragma(db, 'synchronous', 'normal'),
setPragma(db, 'temp_store', 'memory'),
setPragma(db, 'mmap_size', Conf.sqlite.mmapSize),
]);
// Log out PRAGMA values for debugging.
['journal_mode', 'synchronous', 'temp_store', 'mmap_size'].forEach(async (pragma) => {
const value = await getPragma(db, pragma);
console.log(`PRAGMA ${pragma} = ${value};`);
});
2023-10-12 04:03:56 +00:00
2023-08-07 06:45:02 +00:00
const migrator = new Migrator({
db,
provider: new FileMigrationProvider({
fs,
path,
migrationFolder: new URL(import.meta.resolve('./db/migrations')).pathname,
}),
});
2023-08-07 01:14:11 +00:00
/** Migrate the database to the latest version. */
async function migrate() {
console.log('Running migrations...');
const results = await migrator.migrateToLatest();
if (results.error) {
console.error(results.error);
Deno.exit(1);
} else {
if (!results.results?.length) {
console.log('Everything up-to-date.');
} else {
console.log('Migrations finished!');
for (const { migrationName, status } of results.results) {
console.log(` - ${migrationName}: ${status}`);
}
}
}
}
await migrate();
2023-08-07 06:45:02 +00:00
export { db, type DittoDB, type EventRow, type TagRow, type UserRow };