File size: 2,526 Bytes
5b8470e 8327c52 5b8470e e2ad4e9 5b8470e 8327c52 e2ad4e9 5b8470e 8327c52 5b8470e 8327c52 5b8470e 8327c52 5b8470e e2ad4e9 5b8470e e2ad4e9 8327c52 e2ad4e9 8327c52 5b8470e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | import Database from 'better-sqlite3';
import fs from 'fs';
import path from 'path';
// CRITICAL: Point to the persistent mount in Hugging Face
const DATA_DIR = '/data';
const DB_PATH = path.join(DATA_DIR, 'campaign.db');
const IMG_DIR = path.join(DATA_DIR, 'images');
// --- THE FIX IS HERE ---
// We use { recursive: true } to prevent "EEXIST" errors during build
try {
if (!fs.existsSync(DATA_DIR)) {
// If /data (persistent) doesn't exist, fallback to local ./data
fs.mkdirSync('./data', { recursive: true });
} else {
// If /data exists, ensure the images folder exists
fs.mkdirSync(IMG_DIR, { recursive: true });
}
} catch (e) {
console.log("Directory creation warning (safe to ignore during build):", e);
}
// Select path based on environment
// Logic: If /data exists (HF Production), use it. Otherwise use local ./data
const finalDbPath = fs.existsSync(DATA_DIR) ? DB_PATH : './data/campaign.db';
const db = new Database(finalDbPath);
db.pragma('journal_mode = WAL');
// 1. Create Tables
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
password TEXT,
role TEXT DEFAULT 'player',
avatar_url TEXT
);
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
content TEXT,
is_secret INTEGER DEFAULT 0,
game_date TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS tech_tree (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
status TEXT DEFAULT 'locked',
progress INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS characters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
name TEXT,
class_type TEXT,
inventory TEXT,
appearance TEXT,
image_url TEXT,
FOREIGN KEY(user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS journal (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
title TEXT,
content TEXT,
is_public INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(user_id) REFERENCES users(id)
);
`);
// 2. SELF-HEALING: Add 'appearance' column if it's missing
try {
const columns = db.prepare("PRAGMA table_info(characters)").all() as any[];
const hasAppearance = columns.some(c => c.name === 'appearance');
if (!hasAppearance) {
db.prepare("ALTER TABLE characters ADD COLUMN appearance TEXT").run();
}
} catch (e) {
// Ignore migration errors during build
}
export default db; |