refactor: migrate database layer to Prisma ORM

This commit is contained in:
2026-02-07 02:26:00 +08:00
parent 1eb8abb447
commit 2dc6bf16ec
15 changed files with 875 additions and 854 deletions

View File

@@ -1,91 +1,44 @@
import Database from 'better-sqlite3';
import bcrypt from 'bcryptjs';
import path from 'path';
import fs from 'fs';
import { PrismaClient } from "@prisma/client";
import bcrypt from "bcryptjs";
const dbPath = path.join(process.cwd(), 'data/database.sqlite');
const dbDir = path.dirname(dbPath);
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
const db = new Database(dbPath, { verbose: console.log });
const createTables = (): void => {
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
name TEXT NOT NULL,
email TEXT,
role TEXT DEFAULT 'user',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS companies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
company_name TEXT UNIQUE NOT NULL,
is_active BOOLEAN BOOLEAN DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS serials (
id INTEGER PRIMARY KEY AUTOINCREMENT,
serial_number TEXT UNIQUE NOT NULL,
company_name TEXT NOT NULL,
valid_until DATETIME,
is_active BOOLEAN DEFAULT 1,
created_by INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (created_by) REFERENCES users (id),
FOREIGN KEY (company_name) REFERENCES companies (company_name)
)
`);
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_companies ON companies (company_name)');
db.exec('CREATE INDEX IF NOT EXISTS idx_serial_number ON serials (serial_number)');
db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_serials ON serials (company_name)');
db.exec('CREATE INDEX IF NOT EXISTS idx_created_by ON serials (created_by)');
console.log('数据库表创建完成');
};
const prisma = new PrismaClient({
log: ["query", "error", "warn"],
});
const createDefaultUser = async (): Promise<void> => {
const username = 'admin';
const password = 'Beifan@2026';
const name = '系统管理员';
const username = "admin";
const password = "Beifan@2026";
const name = "系统管理员";
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
const user = await prisma.user.findUnique({
where: { username },
});
if (!user) {
const hashedPassword = await bcrypt.hash(password, 10);
db.prepare(
'INSERT INTO users (username, password, name, email, role) VALUES (?, ?, ?, ?, ?)'
).run(username, hashedPassword, name, 'admin@example.com', 'admin');
await prisma.user.create({
data: {
username,
password: hashedPassword,
name,
email: "admin@example.com",
role: "admin",
},
});
console.log('默认管理员用户创建完成:');
console.log('用户名:', username);
console.log('密码:', password);
console.log("默认管理员用户创建完成:");
console.log("用户名:", username);
console.log("密码:", password);
} else {
console.log('默认管理员用户已存在');
console.log("默认管理员用户已存在");
}
};
const initDatabase = async (): Promise<void> => {
createTables();
await createDefaultUser();
db.close();
console.log('数据库连接已关闭');
await prisma.$disconnect();
console.log("数据库连接已关闭");
};
initDatabase();