(Feat-Fix): Lots of fixes done, reporting system fixed, stricter types
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { createPool, Pool } from "mysql2/promise";
|
||||
import { createPool, Pool, PoolConnection } from "mysql2/promise";
|
||||
import { load } from "@std/dotenv";
|
||||
|
||||
// Load environment variables
|
||||
@@ -33,14 +33,17 @@ class Database {
|
||||
async connect(): Promise<Pool> {
|
||||
if (!this.pool) {
|
||||
this.pool = createPool(config);
|
||||
|
||||
|
||||
// Test connection
|
||||
try {
|
||||
const connection = await this.pool.getConnection();
|
||||
console.log("✅ Database connected successfully");
|
||||
connection.release();
|
||||
} catch (error) {
|
||||
console.error("❌ Database connection failed:", (error as Error).message);
|
||||
console.error(
|
||||
"❌ Database connection failed:",
|
||||
(error as Error).message,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -60,12 +63,39 @@ class Database {
|
||||
return rows as T;
|
||||
}
|
||||
|
||||
async execute(sql: string, params?: unknown[]): Promise<{ insertId: number; affectedRows: number }> {
|
||||
async execute(
|
||||
sql: string,
|
||||
params?: unknown[],
|
||||
): Promise<{ insertId: number; affectedRows: number }> {
|
||||
const pool = await this.getPool();
|
||||
const [result] = await pool.execute(sql, params);
|
||||
return result as { insertId: number; affectedRows: number };
|
||||
}
|
||||
|
||||
// Get a connection for transaction support
|
||||
async getConnection(): Promise<PoolConnection> {
|
||||
const pool = await this.getPool();
|
||||
return await pool.getConnection();
|
||||
}
|
||||
|
||||
// Execute within a transaction
|
||||
async transaction<T>(
|
||||
callback: (connection: PoolConnection) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const connection = await this.getConnection();
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
const result = await callback(connection);
|
||||
await connection.commit();
|
||||
return result;
|
||||
} catch (error) {
|
||||
await connection.rollback();
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.pool) {
|
||||
await this.pool.end();
|
||||
|
||||
Reference in New Issue
Block a user