2025-08-04 17:45:44 +02:00
|
|
|
import {
|
2025-08-28 18:27:07 +02:00
|
|
|
DeduplicateJoinsPlugin,
|
|
|
|
|
HandleEmptyInListsPlugin,
|
|
|
|
|
Kysely,
|
|
|
|
|
type LogEvent,
|
|
|
|
|
PostgresDialect,
|
|
|
|
|
replaceWithNoncontingentExpression,
|
|
|
|
|
type Transaction,
|
2025-08-04 17:45:44 +02:00
|
|
|
} from "kysely";
|
2025-08-28 18:27:07 +02:00
|
|
|
import { Pool } from "pg";
|
2025-08-04 17:45:44 +02:00
|
|
|
import { env } from "~/env.mjs";
|
|
|
|
|
import type Database from "~/schemas/Database";
|
|
|
|
|
import type PublicSchema from "~/schemas/public/PublicSchema";
|
2025-08-28 18:27:07 +02:00
|
|
|
|
2025-08-04 17:45:44 +02:00
|
|
|
/**
|
|
|
|
|
* The database connection pool.
|
|
|
|
|
*/
|
|
|
|
|
const pool = new Pool({
|
2025-08-28 18:27:07 +02:00
|
|
|
host: env.PGHOST,
|
|
|
|
|
user: env.POSTGRES_USER,
|
|
|
|
|
database: env.POSTGRES_DB,
|
|
|
|
|
password: env.POSTGRES_PASSWORD,
|
|
|
|
|
port: Number.parseInt(env.PGPORT),
|
|
|
|
|
max: 10,
|
|
|
|
|
idleTimeoutMillis: 30000,
|
|
|
|
|
connectionTimeoutMillis: 2000,
|
2025-08-04 17:45:44 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
type Db = typeof db;
|
|
|
|
|
|
|
|
|
|
type Trx = Transaction<PublicSchema>;
|
|
|
|
|
|
|
|
|
|
export type Querier = Db | Trx;
|
|
|
|
|
/**
|
|
|
|
|
* The database instance.
|
|
|
|
|
*/
|
|
|
|
|
export const db = new Kysely<Database>({
|
2025-08-28 18:27:07 +02:00
|
|
|
dialect: new PostgresDialect({
|
|
|
|
|
pool: pool,
|
|
|
|
|
}),
|
|
|
|
|
|
|
|
|
|
log: (_event) => {
|
|
|
|
|
//DbLogger(event);
|
|
|
|
|
},
|
2025-08-04 17:45:44 +02:00
|
|
|
|
2025-08-28 18:27:07 +02:00
|
|
|
//plugins: [new SerializePlugin()]
|
|
|
|
|
//plugins: [new CamelCasePlugin()],
|
|
|
|
|
plugins: [
|
|
|
|
|
new DeduplicateJoinsPlugin(),
|
|
|
|
|
new HandleEmptyInListsPlugin({
|
|
|
|
|
strategy: replaceWithNoncontingentExpression,
|
|
|
|
|
}),
|
|
|
|
|
],
|
2025-08-04 17:45:44 +02:00
|
|
|
});
|
|
|
|
|
|
2025-08-28 18:27:07 +02:00
|
|
|
const _DbLogger = (event: LogEvent) => {
|
|
|
|
|
if (event.level === "query") {
|
|
|
|
|
console.log("\x1b[33mquery:\x1b[0m", event.query.sql);
|
|
|
|
|
console.log("\x1b[36mparams:\x1b[0m", event.query.parameters);
|
|
|
|
|
console.log("\x1b[32mtaken:\x1b[0m", event.queryDurationMillis, "ms");
|
|
|
|
|
}
|
|
|
|
|
if (event.level === "error") {
|
|
|
|
|
console.error("\x1b[33mquery:\x1b[0m", event.query.sql);
|
|
|
|
|
console.error("\x1b[36mparams:\x1b[0m", event.query.parameters);
|
|
|
|
|
console.error("\x1b[31merror:\x1b[0m", event.error);
|
|
|
|
|
}
|
2025-08-04 17:45:44 +02:00
|
|
|
};
|