Files
plexus/server/db.js

81 lines
2.6 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,
bio VARCHAR DEFAULT '',
banner_color VARCHAR DEFAULT '#6366f1',
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 TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY,
wallet_address VARCHAR,
content VARCHAR,
timestamp TIMESTAMP,
FOREIGN KEY (wallet_address) REFERENCES users(wallet_address)
);
CREATE SEQUENCE IF NOT EXISTS seq_msg_id START 1;
CREATE SEQUENCE IF NOT EXISTS seq_post_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);
});
}
});
// Migration: Add bio and banner_color to users
con.all("PRAGMA table_info('users')", (err, rows) => {
if (err) return;
const hasBio = rows.some(r => r.name === 'bio');
if (!hasBio) {
con.run("ALTER TABLE users ADD COLUMN bio VARCHAR DEFAULT ''", (err) => {
if (err) console.error("Error adding bio column:", err);
});
con.run("ALTER TABLE users ADD COLUMN banner_color VARCHAR DEFAULT '#6366f1'", (err) => {
if (err) console.error("Error adding banner_color column:", err);
});
}
});
console.log('Database initialized and cleared');
});
module.exports = { db, con };