添加数据库自动初始化功能

- 创建 db/init.ts 脚本,可自动创建数据库和表
- 更新 db/index.ts,应用启动时自动检查并创建表结构
- 添加 bun run init-db 命令用于初始化数据库
- 更新 README.md 添加数据库初始化说明
This commit is contained in:
ethan.chen
2026-01-08 14:58:04 +08:00
parent 02ebb4c648
commit d296108f67
4 changed files with 155 additions and 2 deletions

View File

@@ -5,6 +5,13 @@
* @FilePath: /my-score/honoback/db/index.ts
*/
import postgres from "postgres";
import { readFileSync } from "fs";
import { join, dirname } from "path";
// 获取当前文件所在目录
const __dirname = typeof import.meta.dir !== 'undefined'
? import.meta.dir
: dirname(new URL(import.meta.url).pathname);
// 从环境变量获取数据库连接信息
const DATABASE_URL =
@@ -18,6 +25,48 @@ const DATABASE_URL =
// 初始化 PostgreSQL 连接
const sql = postgres(DATABASE_URL);
// 自动初始化表结构(如果表不存在)
async function initTables() {
try {
// 检查 media 表是否存在
const tableExists = await sql`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'media'
)
`;
// 如果表不存在,创建表
if (!tableExists[0].exists) {
console.log("Initializing database tables...");
const schemaPath = join(__dirname, "schema.sql");
const schema = readFileSync(schemaPath, "utf-8");
await sql.unsafe(schema);
console.log("Database tables initialized successfully");
}
} catch (error: any) {
// 如果是因为数据库不存在,尝试创建数据库
if (
error.message?.includes("database") &&
error.message?.includes("does not exist")
) {
console.error("Database does not exist. Please create it first:");
console.error(" createdb media");
console.error(" or: psql -U postgres -c 'CREATE DATABASE media;'");
throw error;
}
// 其他错误也抛出
throw error;
}
}
// 在模块加载时初始化表(但不阻塞)
initTables().catch((error) => {
console.error("Failed to initialize tables:", error.message);
// 不抛出错误,让应用继续运行,但会在第一次查询时失败
});
// 将 SQLite 的 ? 占位符转换为 PostgreSQL 的 $1, $2, $3...
function convertQuery(query: string, params: any[]): [string, any[]] {
let pgQuery = query;