Files
gamer/server/db.js
T

93 lines
2.9 KiB
JavaScript
Raw Normal View History

2026-03-12 11:23:10 +08:00
const Database = require('better-sqlite3');
const bcrypt = require('bcryptjs');
const path = require('path');
const db = new Database(path.join(__dirname, '..', 'data.db'));
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
// 创建表
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
type TEXT NOT NULL CHECK(type IN ('income', 'expense')),
category TEXT NOT NULL,
amount REAL NOT NULL,
quantity INTEGER,
unit_price REAL,
boss TEXT,
partner TEXT,
source TEXT,
destination TEXT,
note TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS idx_records_user_id ON records(user_id);
CREATE INDEX IF NOT EXISTS idx_records_category ON records(category);
CREATE INDEX IF NOT EXISTS idx_records_created_at ON records(created_at);
CREATE INDEX IF NOT EXISTS idx_records_type ON records(type);
CREATE INDEX IF NOT EXISTS idx_records_boss ON records(boss);
CREATE INDEX IF NOT EXISTS idx_records_partner ON records(partner);
CREATE INDEX IF NOT EXISTS idx_records_source ON records(source);
2026-03-12 11:23:10 +08:00
`);
// 迁移:去掉 category 的 CHECK 约束
try {
const tableInfo = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='records'").get();
if (tableInfo && tableInfo.sql.includes("CHECK(category IN")) {
db.exec(`
CREATE TABLE records_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
type TEXT NOT NULL CHECK(type IN ('income', 'expense')),
category TEXT NOT NULL,
amount REAL NOT NULL,
quantity INTEGER,
unit_price REAL,
boss TEXT,
partner TEXT,
source TEXT,
destination TEXT,
note TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
INSERT INTO records_new SELECT * FROM records;
DROP TABLE records;
ALTER TABLE records_new RENAME TO records;
`);
}
} catch (e) {
console.log('Migration skipped:', e.message);
}
// 迁移:添加 rebate 列(派单返点)
try {
const cols = db.prepare("PRAGMA table_info(records)").all();
if (!cols.find(c => c.name === 'rebate')) {
db.exec("ALTER TABLE records ADD COLUMN rebate REAL");
}
} catch (e) {
console.log('Rebate migration skipped:', e.message);
}
// 初始化默认用户 lizhilun
const existingUser = db.prepare('SELECT id FROM users WHERE username = ?').get('lizhilun');
if (!existingUser) {
const hash = bcrypt.hashSync('lizhilun', 10);
db.prepare('INSERT INTO users (username, password) VALUES (?, ?)').run('lizhilun', hash);
}
module.exports = db;