Duriin-API/intelligence/db.js

99 lines
2.7 KiB
JavaScript

const Database = require("better-sqlite3");
const sqliteVec = require("sqlite-vec");
let archiveDb = null;
let intelligenceDb = null;
function getArchiveDb(dbPath) {
if (!archiveDb) {
archiveDb = new Database(dbPath, { readonly: true });
sqliteVec.load(archiveDb);
archiveDb.pragma("journal_mode = WAL");
}
return archiveDb;
}
function getIntelligenceDb(dbPath) {
if (!intelligenceDb) {
intelligenceDb = new Database(dbPath);
intelligenceDb.pragma("journal_mode = WAL");
}
return intelligenceDb;
}
function runMigrations(db) {
db.exec(`
CREATE TABLE IF NOT EXISTS cursors (
key TEXT PRIMARY KEY,
value INTEGER
);
CREATE TABLE IF NOT EXISTS tracked_companies (
id INTEGER PRIMARY KEY,
name TEXT,
ticker TEXT,
aliases TEXT
);
CREATE TABLE IF NOT EXISTS article_queue (
id INTEGER PRIMARY KEY,
article_id INTEGER UNIQUE,
status TEXT DEFAULT 'pending',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME
);
CREATE TABLE IF NOT EXISTS event_knowledge (
id INTEGER PRIMARY KEY,
event_id INTEGER,
company_id INTEGER,
type TEXT,
data TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS company_embeddings (
company_id INTEGER PRIMARY KEY,
embedding BLOB NOT NULL,
model TEXT NOT NULL,
generated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS event_predictions (
id INTEGER PRIMARY KEY,
event_id INTEGER,
company_id INTEGER,
type TEXT,
direction TEXT,
magnitude TEXT,
timeframe TEXT,
rationale TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
`);
}
function seedCompanies(db) {
const count = db.prepare("SELECT COUNT(*) as c FROM tracked_companies").get().c;
if (count > 0) return;
const insert = db.prepare(
"INSERT INTO tracked_companies (name, ticker, aliases) VALUES (?, ?, ?)"
);
const companies = [
{ name: "NVIDIA", ticker: "NVDA", aliases: ["Nvidia Corporation", "NVDA"] },
{ name: "TSMC", ticker: "TSM", aliases: ["Taiwan Semiconductor", "Taiwan Semiconductor Manufacturing"] },
{ name: "ASML", ticker: "ASML", aliases: ["ASML Holding", "ASML Holdings"] },
{ name: "Intel", ticker: "INTC", aliases: ["Intel Corporation"] },
{ name: "Samsung", ticker: "005930.KS", aliases: ["Samsung Electronics", "Samsung Group"] },
];
for (const c of companies) {
insert.run(c.name, c.ticker, JSON.stringify(c.aliases));
}
console.log(`[db] seeded ${companies.length} tracked companies`);
}
module.exports = { getArchiveDb, getIntelligenceDb, runMigrations, seedCompanies };