import log from "@shared/utils/logger.ts"; import * as mariadb from "npm:mariadb"; import { getMessageFromError } from "@shared/utils/result.ts"; interface MariaDBConfig { user: string; password: string; host: string; port: number; database: string; } export function loadMariaDBConfigFromEnv(): MariaDBConfig { const requiredVars = [ "KBRG_MYSQL_USER", "KBRG_MYSQL_PASSWORD", "KBRG_MYSQL_DATABASE", ]; const missingVars = requiredVars.filter( (varName) => !Deno.env.has(varName), ); if (missingVars.length > 0) { log.critical( `Missing required environment variables: ${missingVars.join(", ")}`, ); Deno.exit(1); } const host = Deno.env.get("KBRG_MYSQL_HOST") || "localhost"; const user = Deno.env.get("KBRG_MYSQL_USER")!; const password = Deno.env.get("KBRG_MYSQL_PASSWORD")!; const database = Deno.env.get("KBRG_MYSQL_DATABASE")!; const port = parseInt(Deno.env.get("KBRG_MYSQL_PORT") || "3306"); if (isNaN(port)) { log.critical(`Invalid port number for KBRG_MYSQL_PORT: ${port}`); Deno.exit(1); } return { user, password, host, port, database }; } export async function createAndTestMariaDBPool( config: MariaDBConfig, ): Promise { const { user, password, host, port, database } = config; try { const pool = mariadb.createPool({ host, port, user, password, database, connectionLimit: 10, }); // Test Connection const connection = await pool.getConnection(); connection.release(); log.info("Successfully connected to MySQL"); return pool; } catch (e) { const errorMessage = getMessageFromError(e); log.critical(`Failed to create MySQL pool: ${errorMessage}`); Deno.exit(1); } }