57 lines
1.7 KiB
JavaScript
57 lines
1.7 KiB
JavaScript
const duckdb = require('duckdb');
|
|
const path = require('path');
|
|
|
|
const dbPath = path.join(__dirname, 'data', 'chat.duckdb');
|
|
const db = new duckdb.Database(dbPath);
|
|
|
|
const con = db.connect();
|
|
|
|
// Initialize Schema
|
|
con.exec(`
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
wallet_address VARCHAR PRIMARY KEY,
|
|
username VARCHAR UNIQUE,
|
|
last_seen TIMESTAMP
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS messages (
|
|
id INTEGER PRIMARY KEY,
|
|
channel_id VARCHAR,
|
|
wallet_address VARCHAR,
|
|
content VARCHAR,
|
|
timestamp TIMESTAMP,
|
|
tx_id VARCHAR,
|
|
FOREIGN KEY (wallet_address) REFERENCES users(wallet_address)
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS reactions (
|
|
message_id INTEGER,
|
|
wallet_address VARCHAR,
|
|
emoji VARCHAR,
|
|
PRIMARY KEY (message_id, wallet_address, emoji),
|
|
FOREIGN KEY (wallet_address) REFERENCES users(wallet_address)
|
|
);
|
|
|
|
CREATE SEQUENCE IF NOT EXISTS seq_msg_id START 1;
|
|
|
|
-- Migration: Add tx_id to messages if it doesn't exist (for existing DBs)
|
|
PRAGMA table_info('messages');
|
|
`, (err) => {
|
|
if (err) return console.error('Schema error:', err);
|
|
|
|
// Check if tx_id exists, if not add it
|
|
con.all("PRAGMA table_info('messages')", (err, rows) => {
|
|
if (err) return;
|
|
const hasTxId = rows.some(r => r.name === 'tx_id');
|
|
if (!hasTxId) {
|
|
con.run("ALTER TABLE messages ADD COLUMN tx_id VARCHAR", (err) => {
|
|
if (err) console.error("Error adding tx_id column:", err);
|
|
else console.log("Added tx_id column to messages table");
|
|
});
|
|
}
|
|
});
|
|
console.log('Database initialized and cleared');
|
|
});
|
|
|
|
module.exports = { db, con };
|