Files
ActivityPubD/source/db/db.d
2024-02-06 21:14:23 -03:00

83 lines
1.7 KiB
D

module db.db;
import slf4d;
import ddbc.core;
import hibernated.core;
import db.types;
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 EntityMetaData m_schema;
protected DataSource m_ds;
protected SessionFactory m_factory;
protected Session m_session;
this(DBSettings settings) {
this.m_settings = settings;
this.m_schema = new SchemaInfoImpl!(User);
}
void connect() {
Driver driver;
string url;
string[string] params;
Dialect dialect;
switch (this.m_settings.connector) {
case DBConnector.DB_PGSQL:
debugF!"Using PGSQL driver";
import ddbc.drivers.pgsqlddbc;
driver = new PGSQLDriver();
with (this.m_settings) {
url = PGSQLDriver.generateUrl(host, port, dbname);
params = PGSQLDriver.setUserAndPassword(username, password);
}
dialect = new PGSQLDialect();
break;
default:
throw new Exception("Database connector not supported (yet)");
}
debugF!"Connecting to DB with URL: %s"(url);
this.m_ds = new ConnectionPoolDataSourceImpl(driver, url, params);
this.m_factory = new SessionFactoryImpl(this.m_schema, dialect, this.m_ds);
{ // Create schema if necessary
Connection conn = this.m_ds.getConnection();
scope (exit)
conn.close();
this.m_factory.getDBMetaData().updateDBSchema(conn, false, true);
}
}
void close() {
if (this.m_session && this.m_session.isOpen())
this.m_session.close();
if (this.m_factory && this.m_factory.isClosed() == false)
this.m_factory.close();
}
}