diff --git a/dub.sdl b/dub.sdl index 5fee874..d931d62 100644 --- a/dub.sdl +++ b/dub.sdl @@ -5,5 +5,7 @@ copyright "Copyright © 2024, Marisa" license "MIT" dependency "slf4d" version="~>3.0.0" dependency "handy-httpd" version="~>8.2.0" -dependency "hibernated" version="~>0.4.0" dependency "requests" version="~>2.1.3" +dependency "ddbc" version="~>0.6.0" + +subConfiguration "ddbc" "PGSQL" diff --git a/dub.selections.json b/dub.selections.json index 54aa1f5..4f873f2 100644 --- a/dub.selections.json +++ b/dub.selections.json @@ -2,14 +2,22 @@ "fileVersion": 1, "versions": { "automem": "0.6.9", - "cachetools": "0.4.1", + "cachetools": "0.3.1", + "d-unit": "0.10.2", + "ddbc": "0.6.0", + "derelict-pq": "2.2.0", + "derelict-util": "2.0.6", "handy-httpd": "8.2.0", + "hibernated": "0.4.0", "httparsed": "1.2.1", + "mysql-native": "3.1.0", + "odbc": "1.0.0", "path-matcher": "1.1.3", "requests": "2.1.3", "slf4d": "3.0.0", "streams": "3.5.0", "test_allocator": "0.3.4", + "undead": "1.1.8", "unit-threaded": "0.10.8" } } diff --git a/source/db/db.d b/source/db/db.d new file mode 100644 index 0000000..399163e --- /dev/null +++ b/source/db/db.d @@ -0,0 +1,50 @@ +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; + + shared this(DBSettings settings) { + this.m_settings = settings; + } + + static shared(DB) getDB(DBSettings settings) { + switch (settings.connector) { + case DBConnector.DB_PGSQL: + import db.pgsql; + + debugF!"DB type is PostgreSQL"; + return new shared 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(); + } +} diff --git a/source/db/pgsql.d b/source/db/pgsql.d new file mode 100644 index 0000000..d10fb7b --- /dev/null +++ b/source/db/pgsql.d @@ -0,0 +1,27 @@ +module db.pgsql; + +import db.db; + +import ddbc.core; +import ddbc.common; + +class PostgresDB : DB { + shared this(Args...)(auto ref Args args) { + super(args); + } + + protected override DataSource getDataSource() { + import ddbc.drivers.pgsqlddbc; + + Driver driver = new PGSQLDriver(); + string url; + string[string] params; + + with (this.m_settings) { + url = PGSQLDriver.generateUrl(host, port, dbname); + params = PGSQLDriver.setUserAndPassword(username, password); + } + + return new ConnectionPoolDataSourceImpl(driver, url, params); + } +}