Skip to content

Commit

Permalink
work on db connection stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
targoninc-alex committed Oct 3, 2024
1 parent ed350c8 commit cd89f85
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
24 changes: 15 additions & 9 deletions src/features/database/mariaDbDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,37 +22,47 @@ export class MariaDbDatabase {
private readonly password: string;
private readonly database: string;
private pool: mariadb.Pool | null = null;
private conn: mariadb.Connection | null = null;

constructor(host: string | null = null, user: string | null = null, password: string | null = null, port: number | null = null) {
this.host = host || process.env.MYSQL_HOST || 'localhost';
this.port = port || (process.env.MYSQL_PORT ? parseInt(process.env.MYSQL_PORT) : null) || 3306;
this.user = user || process.env.MYSQL_USER || 'root';
this.password = password || process.env.MYSQL_PASSWORD || '';
this.database = process.env.MYSQL_DATABASE || 'venel';
this.conn = null;
CLI.info(`Connecting to MariaDB at ${this.host}:${this.port} with user ${this.user} and database venel.`);
}

connect() {
async connect() {
this.pool = mariadb.createPool({
host: this.host,
port: this.port,
user: this.user,
password: this.password,
database: this.database
database: this.database,
connectionLimit: 10,
});
if (!this.pool) {
throw new Error("Could not create DB connection pool.");
}
this.conn = await this.pool.getConnection();
if (!this.conn) {
throw new Error("Could not connect to database.");
}
await this.conn.query("SET NAMES utf8mb4");
CLI.success(`DB connected.`);
}

async query(sql: string, params: unknown[] = []) {
if (!this.pool) {
this.connect();
await this.connect();
}
let conn;
let conn = this.conn;
try {
conn = await this.pool!.getConnection();
if (!conn) {
conn = await this.pool!.getConnection();
}
return await conn.query({
sql,
bigIntAsNumber: true
Expand All @@ -62,10 +72,6 @@ export class MariaDbDatabase {
await this.handleUnknownColumnError(sql, e);
}
throw e;
} finally {
if (conn) {
await conn.end();
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/features/databaseFeature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {Reaction, ReactionGroup} from "./database/models";
export class DatabaseFeature {
static async enable(__dirname: string) {
const db = new MariaDbDatabase();
db.connect();
await db.connect();
await DatabaseFeature.checkDatabaseIntegrity(db, __dirname);
return db;
}
Expand Down

0 comments on commit cd89f85

Please sign in to comment.