2024-04-17 01:45:36 +09:00
|
|
|
import { Kysely, ParseJSONResultsPlugin, SqliteDialect } from "kysely";
|
|
|
|
import SqliteDatabase from "better-sqlite3";
|
2024-10-06 00:32:05 +09:00
|
|
|
import type { db } from "dbtype";
|
|
|
|
|
|
|
|
type DB = db.DB;
|
2024-04-17 01:45:36 +09:00
|
|
|
|
|
|
|
export function createSqliteDialect() {
|
|
|
|
const url = process.env.DATABASE_URL;
|
|
|
|
if (!url) {
|
|
|
|
throw new Error("DATABASE_URL is not set");
|
|
|
|
}
|
|
|
|
const db = new SqliteDatabase(url);
|
|
|
|
return new SqliteDialect({
|
|
|
|
database: db,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create a new Kysely instance with a new SqliteDatabase instance
|
|
|
|
let kysely: Kysely<DB> | null = null;
|
|
|
|
export function getKysely() {
|
|
|
|
if (!kysely) {
|
|
|
|
kysely = new Kysely<DB>({
|
|
|
|
dialect: createSqliteDialect(),
|
|
|
|
// plugins: [new ParseJSONResultsPlugin()],
|
2024-11-07 05:18:01 +09:00
|
|
|
log: (event) => {
|
|
|
|
if (event.level === "error") {
|
|
|
|
console.error("Query failed : ", {
|
2024-12-27 18:37:06 +09:00
|
|
|
durationMs: event.queryDurationMillis,
|
|
|
|
error: event.error,
|
|
|
|
sql: event.query.sql,
|
|
|
|
params: event.query.parameters,
|
|
|
|
});
|
2024-11-07 05:18:01 +09:00
|
|
|
}
|
|
|
|
}
|
2024-04-17 01:45:36 +09:00
|
|
|
});
|
|
|
|
}
|
|
|
|
return kysely;
|
2024-11-07 05:18:01 +09:00
|
|
|
}
|