Files
ActivityPubD/source/db/db.d
2024-01-28 23:34:13 -03:00

89 lines
1.7 KiB
D

module db.db;
import slf4d;
import ddbc.core;
enum DBConnector {
DB_MYSQL,
DB_PGSQL,
DB_SQLITE,
}
struct DBSettings {
DBConnector connector;
string host;
ushort port;
string username;
string password;
string dbname;
}
class DB {
protected DBSettings m_settings;
protected DataSource m_ds;
protected Connection m_conn;
protected Statement m_stmt = null;
this(DBSettings settings) {
this.m_settings = settings;
}
static DB getDB(DBSettings settings) {
switch (settings.connector) {
case DBConnector.DB_PGSQL:
import db.pgsql;
debugF!"DB type is PostgreSQL";
return new PostgresDB(settings);
default:
throw new Exception("DB not supported");
}
}
protected abstract DataSource getDataSource();
void connect() {
this.m_ds = this.getDataSource();
this.m_conn = this.m_ds.getConnection();
this.m_conn.setAutoCommit(false);
}
int runUpdate(string statement) {
if (this.m_stmt is null)
this.m_stmt = this.m_conn.createStatement();
debugF!"Running update: %s"(statement);
return this.m_stmt.executeUpdate(statement);
}
ResultSet runQuery(string statement) {
if (this.m_stmt is null)
this.m_stmt = this.m_conn.createStatement();
debugF!"Running query: %s"(statement);
return this.m_stmt.executeQuery(statement);
}
void runMigrations() {
ResultSet rs = this.runQuery(
`select * from information_schema.tables where table_name = 'migrations';`,
);
bool exists = rs.next();
int ret = 0;
if (exists == false) {
ret |= this.runUpdate(
`create table migrations(
id serial,
name character varying
)`,
);
}
}
}