Files
general-purpose-bot/core/db.js

62 lines
1.8 KiB
JavaScript

const fs = require("fs");
const Database = require("better-sqlite3");
const path = require("path");
const { open } = require('sqlite');
const filepath = "./data/minzbot.db";
async function createDbConnection() {
const dir = path.dirname(filepath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const db = new Database(filepath, { verbose: console.log });
initDB(db);
console.log("[DATABASE] Connection with better-sqlite3 established");
return db;
}
async function initDB(db) {
await db.exec(`
CREATE TABLE IF NOT EXISTS anniversaries (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(50) NOT NULL,
guild_id TEXT NOT NULL,
discord_id VARCHAR(50) NOT NULL,
last_anniversary_notification TEXT
);
`);
await db.exec(`
CREATE TABLE IF NOT EXISTS lastfm (
discord_id TEXT PRIMARY KEY NOT NULL,
lastfm_name TEXT
);
`);
await db.exec(`
CREATE TABLE IF NOT EXISTS bot_config (
id INTEGER PRIMARY KEY CHECK (id = 1),
weekly_budget REAL DEFAULT 0,
exchange_rate_eur_kr REAL DEFAULT 0,
last_budget_notification_date TEXT
);
`);
await db.exec(`
CREATE TABLE IF NOT EXISTS grocery_budgets (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
discord_id VARCHAR(50) NOT NULL,
budget_spent REAL,
total_spent REAL
);
`);
// Optional: Initialize the row if it doesn't exist yet
await db.exec(`
INSERT OR IGNORE INTO bot_config (id, weekly_budget, last_budget_notification_date)
VALUES (1, 0, NULL);
`);
console.log('[DATABASE] Created new DB table');
}
module.exports = createDbConnection;