lib / db.js
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.initializeConnection = initializeConnection;
exports.query = query;
exports.execute = execute;
exports.getSchema = getSchema;
exports.closeConnection = closeConnection;
const mysql = __importStar(require("mysql2/promise"));
const pg = __importStar(require("pg"));
let connectionPool = null;
let currentConfig = null;
async function initializeConnection(config) {
if (currentConfig && JSON.stringify(currentConfig) === JSON.stringify(config)) {
return; // Already connected with same config
}
// Close existing connection
if (connectionPool) {
try {
if (config.dbType === "mysql") {
await connectionPool.end();
}
else {
await connectionPool.end();
}
}
catch (error) {
console.error("Error closing previous connection:", error);
}
}
currentConfig = config;
if (config.dbType === "mysql") {
connectionPool = mysql.createPool({
host: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database,
waitForConnections: true,
connectionLimit: config.connectionPool || 10,
queueLimit: 0,
});
}
else {
connectionPool = new pg.Pool({
host: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database,
max: config.connectionPool || 10,
});
}
// Test the connection
try {
if (config.dbType === "mysql") {
const conn = await connectionPool.getConnection();
await conn.ping();
conn.release();
}
else {
const client = await connectionPool.connect();
await client.query("SELECT NOW()");
client.release();
}
}
catch (error) {
connectionPool = null;
currentConfig = null;
throw new Error(`Failed to connect to database: ${error}`);
}
}
async function query(sql, params = []) {
if (!connectionPool) {
throw new Error("Database connection not initialized");
}
try {
if (currentConfig?.dbType === "mysql") {
const [rows] = await connectionPool.execute(sql, params);
return rows;
}
else {
const result = await connectionPool.query(sql, params);
return result.rows;
}
}
catch (error) {
throw new Error(`Query execution failed: ${error}`);
}
}
async function execute(sql, params = []) {
if (!connectionPool) {
throw new Error("Database connection not initialized");
}
try {
if (currentConfig?.dbType === "mysql") {
const [result] = await connectionPool.execute(sql, params);
const mysqlResult = result;
return {
affectedRows: mysqlResult.affectedRows || 0,
lastInsertId: mysqlResult.insertId,
};
}
else {
const result = await connectionPool.query(sql, params);
return {
affectedRows: result.rowCount || 0,
};
}
}
catch (error) {
throw new Error(`Execute failed: ${error}`);
}
}
async function getSchema() {
if (!connectionPool || !currentConfig) {
throw new Error("Database connection not initialized");
}
try {
if (currentConfig.dbType === "mysql") {
return await getMySQLSchema();
}
else {
return await getPostgreSQLSchema();
}
}
catch (error) {
throw new Error(`Schema retrieval failed: ${error}`);
}
}
async function getMySQLSchema() {
const tablesResult = await query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ?", [currentConfig.database]);
const schema = {};
for (const tableRow of tablesResult) {
const tableName = tableRow.TABLE_NAME;
const columnsResult = await query("SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?", [currentConfig.database, tableName]);
schema[tableName] = columnsResult.map((col) => ({
name: col.COLUMN_NAME,
type: col.COLUMN_TYPE,
nullable: col.IS_NULLABLE === "YES",
key: col.COLUMN_KEY,
}));
}
return schema;
}
async function getPostgreSQLSchema() {
const tablesResult = await query(`SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'`);
const schema = {};
for (const tableRow of tablesResult) {
const tableName = tableRow.table_name;
const columnsResult = await query(`SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'public' AND table_name = $1`, [tableName]);
schema[tableName] = columnsResult.map((col) => ({
name: col.column_name,
type: col.data_type,
nullable: col.is_nullable === "YES",
}));
}
return schema;
}
async function closeConnection() {
if (connectionPool) {
try {
if (currentConfig?.dbType === "mysql") {
await connectionPool.end();
}
else {
await connectionPool.end();
}
}
catch (error) {
console.error("Error closing connection:", error);
}
connectionPool = null;
currentConfig = null;
}
}
//# sourceMappingURL=db.js.map