2026-05-07 02:21:49 +08:00
|
|
|
import Database from 'better-sqlite3';
|
|
|
|
|
import path from 'path';
|
|
|
|
|
import fs from 'fs';
|
|
|
|
|
import { fileURLToPath } from 'url';
|
|
|
|
|
import { SCHEMA_SQL } from './schema';
|
|
|
|
|
|
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
|
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
|
const DB_PATH = path.resolve(__dirname, '..', '..', 'data', 'meitu-agent.db');
|
|
|
|
|
|
|
|
|
|
let db: Database.Database;
|
|
|
|
|
|
|
|
|
|
export function getDb(): Database.Database {
|
|
|
|
|
if (!db) {
|
|
|
|
|
const dir = path.dirname(DB_PATH);
|
|
|
|
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
|
|
|
db = new Database(DB_PATH);
|
|
|
|
|
db.pragma('journal_mode = WAL');
|
|
|
|
|
db.pragma('foreign_keys = ON');
|
|
|
|
|
}
|
|
|
|
|
return db;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-07 23:48:26 +08:00
|
|
|
// Ensure a column exists on a table, add it with DEFAULT if missing
|
|
|
|
|
function ensureColumn(d: Database.Database, table: string, column: string, definition: string) {
|
|
|
|
|
const cols = d.prepare(`PRAGMA table_info('${table}')`).all() as { name: string }[];
|
|
|
|
|
if (!cols.some((c) => c.name === column)) {
|
|
|
|
|
d.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-07 02:21:49 +08:00
|
|
|
export function initDb(): void {
|
|
|
|
|
const d = getDb();
|
|
|
|
|
d.exec(SCHEMA_SQL);
|
2026-05-07 23:48:26 +08:00
|
|
|
|
|
|
|
|
// Migrations for existing databases
|
|
|
|
|
ensureColumn(d, 'conversations', 'pinned', 'INTEGER NOT NULL DEFAULT 0');
|
2026-05-07 02:21:49 +08:00
|
|
|
}
|