-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathschema.ts
45 lines (35 loc) · 1.33 KB
/
schema.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import BetterSqlite3 from 'better-sqlite3';
import { Singleton } from '@/utils/singleton';
import { SERVER_CONFIG } from '@/config/server';
import type { Database } from 'better-sqlite3';
const { databaseFilePath } = SERVER_CONFIG;
export class DbInstance {
private static createDatabase(): Database {
const db = new BetterSqlite3(databaseFilePath);
db.exec('PRAGMA foreign_keys = ON;');
db.exec(`
CREATE TABLE IF NOT EXISTS month (
name TEXT PRIMARY KEY, -- "YYYY-MM" format for uniqueness
threadId TEXT UNIQUE,
createdAtOriginal DATETIME,
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP, -- auto-populated
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP -- auto-populated on creation
);
CREATE TABLE IF NOT EXISTS company (
name TEXT,
monthName TEXT,
commentId TEXT UNIQUE,
createdAtOriginal DATETIME,
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (name, monthName),
FOREIGN KEY (monthName) REFERENCES month(name) ON DELETE CASCADE
);
`);
return db;
}
public static getDatabase(): Database {
return Singleton.getInstance<Database>('DbInstance', () => DbInstance.createDatabase());
}
}
export const getDb = DbInstance.getDatabase;