buggins/ddbc
Acerca de
DDBC is DB Connector for D language (similar to JDBC)
Datos y análisisCrecimiento de estrellas medido
- in 24h
- Recopilando historial
- in 7 days
- Recopilando historial
- in 15 days
- Recopilando historial
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
OriginalDDBC
DDBC is DB Connector for D language (similar to JDBC)
Currently supports MySQL, PostgreSQL (through libpq, or natively with the opt-in PGNATIVE configuration and the pure D postgresql-native client), SQLite, SQL Server (via ODBC, or natively with the opt-in MSSQL configuration and the pure D mssql-native client), Oracle (natively with the opt-in ORACLE configuration and the pure D oracle-native client, or via ODBC) and ClickHouse (opt-in ClickHouse configuration, via the pure D clickhoused client).
The project is hosted on github with documentation available on the wiki.
See also: hibernated - ORM for D language which uses DDBC.
NOTE: project has been moved from SourceForge to GitHub
Choosing drivers
ddbc's drivers are compiled in by dub configurations. An application picks one with subConfigurations in its
dub.json:
"dependencies": { "ddbc": "~>0.16.1" },
"subConfigurations": { "ddbc": "PGNATIVE" }
Without subConfigurations dub uses the first configuration, full. A build has exactly one ddbc configuration, so
the drivers of different configurations can't be combined (for example native Oracle with the libpq driver);
full-native has all the newer drivers together.
| Configuration | Drivers (version identifiers) | C libraries |
|---|---|---|
full (default) |
MySQL (USE_MYSQL), SQLite (USE_SQLITE), PostgreSQL via libpq (USE_PGSQL), ODBC (USE_ODBC): SQL Server and Oracle through ODBC |
sqlite3, libpq, ODBC |
full-native |
MySQL (USE_MYSQL), SQLite (USE_SQLITE), and the native ClickHouse (USE_CLICKHOUSE), SQL Server (USE_MSSQL), Oracle (USE_ORACLE) and PostgreSQL (USE_PGNATIVE) drivers |
sqlite3 |
MySQL, SQLite, PGSQL, ODBC |
that driver only | its library (none for MySQL) |
PGNATIVE |
PostgreSQL, pure D (postgresql-native, USE_PGNATIVE) |
none |
MSSQL |
SQL Server, pure D (mssql-native, USE_MSSQL) |
none |
ORACLE |
Oracle, pure D (oracle-native, USE_ORACLE) |
none |
ClickHouse |
ClickHouse, pure D (clickhoused, USE_CLICKHOUSE) |
none |
API |
none: the interfaces only | none |
full-omf and SQLite-omf are the Windows OMF variants; the test* configurations are for ddbc's own tests.
The URL scheme selects the driver among those compiled in:
| URL | Driver |
|---|---|
postgresql://, postgres:// |
libpq when PGSQL is compiled in (full, PGSQL), otherwise native |
pgnative:// |
native PostgreSQL |
sqlserver:// |
native in MSSQL and full-native, otherwise ODBC |
mssql:// |
native SQL Server |
oracle:// |
native in ORACLE and full-native, otherwise ODBC |
clickhouse://, mysql://, sqlite:, odbc:// |
that driver |
Threads or vibe.d (fiber mode)
The native drivers (PGNATIVE, MSSQL, ORACLE, ClickHouse, all in full-native) and MySQL work both with blocking sockets in
ordinary threads and with vibe.d sockets in vibe.d tasks. vibe.d support needs no ddbc configuration: it is compiled
in when the application depends on vibe-core (the client libraries have it as an optional dependency, and dub then
defines Have_vibe_core). The native clients accept vibe-core 1.22 to 2.x.
- Native drivers: each connection chooses when it is opened: vibe.d sockets inside a vibe.d task, blocking
sockets otherwise (including all programs built without vibe-core). A URL parameter forces one mode, the same in every native
driver:
io_mode=phobosorio_mode=vibe(iofor short;auto, the default, chooses as above). A fiber-mode connection must be used on the thread that opened it. - MySQL: mysql-native uses vibe.d sockets for every connection when vibe-core is part of the build, and blocking sockets otherwise.
- libpq (
PGSQL), ODBC and SQLite are C libraries and always block: inside a vibe.d task each call blocks the thread's event loop.
examples/pgnative_vibe runs the native PostgreSQL driver in vibe.d tasks.
Sample code
import ddbc;
import std.stdio;
import std.conv;
int main(string[] args) {
// provide URL for proper type of DB
string url = "postgresql://localhost:5432/ddbctestdb?user=ddbctest,password=ddbctestpass,ssl=true";
//string url = "mysql://localhost:3306/ddbctestdb?user=ddbctest,password=ddbctestpass";
//string url = "sqlite:testdb.sqlite";
// creating Connection
auto conn = createConnection(url);
scope(exit) conn.close();
// creating Statement
auto stmt = conn.createStatement();
scope(exit) stmt.close();
// execute simple queries to create and fill table
stmt.executeUpdate("DROP TABLE ddbct1");
stmt.executeUpdate("CREATE TABLE ddbct1
(id bigint not null primary key,
name varchar(250),
comment text,
ts datetime)");
stmt.executeUpdate("INSERT INTO ddbct1 (id, name, comment, ts) VALUES
(1, 'name1', 'comment for line 1', '2016/09/14 15:24:01')");
stmt.executeUpdate("INSERT INTO ddbct1 (id, name, comment) VALUES
(2, 'name2', 'comment for line 2 - can be very long')");
stmt.executeUpdate("INSERT INTO ddbct1 (id, name) values(3, 'name3')"); // comment is null here
// reading DB
auto rs = stmt.executeQuery("SELECT id, name name_alias, comment, ts FROM ddbct1 ORDER BY id");
while (rs.next())
writeln(to!string(rs.getLong(1)), "\t", rs.getString(2), "\t", rs.getString(3), "\t", rs.getString(4));
return 0;
}
NULL values
A NULL reads as the getter type's default (0, a null string or array, Decimal.init, SysTime.init,
DateTime.init, ...) with wasNull() true: check wasNull() (or isNull(column)) to tell a NULL from a real
value. Before ddbc 0.15, getSysTime and getDateTime returned the current time for a NULL in the MySQL, libpq,
ODBC and SQLite drivers (#86, #226).
Exact decimals
getDecimal and setDecimal read and write DECIMAL/NUMERIC values exactly, as a Decimal
(re-exported by ddbc.core; it comes from dbwire's dbwire:types,
a small pure-D package that ddbc depends on): up to 76 digits, with the column's scale, convertible to
and from text, double, long and BigInt. A NULL reads as zero, with wasNull() true.
auto ps = conn.prepareStatement("INSERT INTO payment (id, amount) VALUES (?, ?)");
ps.setLong(1, 1);
ps.setDecimal(2, Decimal.fromString("19.90"));
ps.executeUpdate();
auto rs = stmt.executeQuery("SELECT amount FROM payment");
while (rs.next())
writeln(rs.getDecimal(1).toFixedString()); // 19.90 (for a DECIMAL(10,2) column)
Every driver supports them: values are read from the database's own decimal type where the driver has
one (ClickHouse), else parsed from the text the database returns; parameters are sent as text (typed
Decimal(P, S) for ClickHouse). POD structs may have Decimal and Nullable!Decimal fields.
Module ddbc.pods implement SELECT support for POD structs (plain old data).
Instead of manual reading fields one by one, it's possible to put result set value to struct fields, and generate select statements automatically.
Sample of easy reading from DB using PODs support:
import ddbc;
import std.stdio;
// provide URL for proper type of DB
//string url = "postgresql://localhost:5432/ddbctestdb?user=ddbctest,password=ddbctestpass,ssl=true";
//string url = "mysql://localhost:3306/ddbctestdb?user=ddbctest,password=ddbctestpass";
string url = "sqlite:testdb.sqlite";
// creating Connection
auto conn = createConnection(url);
scope(exit) conn.close();
Statement stmt = conn.createStatement();
scope(exit) stmt.close();
// fill database with test data
stmt.executeUpdate(`DROP TABLE IF EXISTS user_data`);
stmt.executeUpdate(`CREATE TABLE user_data (id INTEGER PRIMARY KEY, name VARCHAR(255) NOT NULL, flags int null)`);
stmt.executeUpdate(`INSERT INTO user_data (id, name, flags) VALUES (1, 'John', 5), (2, 'Andrei', 2), (3, 'Walter', 2), (4, 'Rikki', 3), (5, 'Iain', 0), (6, 'Robert', 1)`);
// our POD object
struct User {
long id;
string name;
int flags;
}
writeln("reading all user table rows");
foreach(ref e; stmt.select!User) {
writeln("id:", e.id, " name:", e.name, " flags:", e.flags);
}
writeln("reading user table rows with where and order by");
foreach(ref e; stmt.select!User.where("id < 6").orderBy("name desc")) {
writeln("id:", e.id, " name:", e.name, " flags:", e.flags);
}
writeln("reading user table rows with where and order by with limit and offset");
foreach(e; stmt.select!User.where("id < 6").orderBy("name desc").limit(3).offset(1)) {
writeln("id:", e.id, " name:", e.name, " flags:", e.flags);
}
writeln("reading all user table rows, but fetching only id and name (you will see default value 0 in flags field)");
foreach(ref e; stmt.select!(User, "id", "name")) {
writeln("id:", e.id, " name:", e.name, " flags:", e.flags);
}
Errors
Every driver throws SQLException, with the client library's exception chained as next. getSQLState() gives the
SQLSTATE and getErrorCode() the database's own error code. Errors that generic code can act on, without knowing
the database, are thrown as subclasses (as in JDBC):
| Class | Meaning | What to do |
|---|---|---|
SQLTransactionRollbackException |
a deadlock or serialization failure (SQLSTATE class 40) | rollback(), then retry the whole transaction |
SQLTimeoutException |
a lock wait timeout or a statement timeout ran out | retry, or give up; the connection works (with MySQL the transaction is lost) |
SQLNonTransientConnectionException |
the connection is gone (killed, reset, the server shut down), couldn't be opened, or was closed (08003) | open another connection |
SQLTransactionRollbackException and SQLTimeoutException extend SQLTransientException. A cancel (PostgreSQL's
57014, ORA-01013, ClickHouse's 394, SQLite's SQLITE_INTERRUPT) is a plain SQLException with SQLSTATE 57014.
PostgreSQL reports its statement_timeout with the same 57014, so a statement_timeout set in SQL arrives as a
cancel, not as an SQLTimeoutException; the query timeout of a statement (see below) is reported as a timeout. When the driver finds that the server rolled back the transaction after an earlier error
("call rollback() to continue"), it throws a plain SQLException with SQLSTATE 25000: the earlier error, which may
not be worth a retry (e.g. a duplicate key), already had its class.
| Driver | SQLSTATE | Error code | Transaction rollback | Timeout | Connection |
|---|---|---|---|---|---|
| PGNATIVE, PGSQL | the server's | 0 | 40P01, 40001 | 55P03, the query timeout (HYT00) | FATAL errors, 57P01–57P03 |
| MySQL | the server's | the server's | 1213 | 1205, 3024, 1969 | class 08, 1927, network failures |
| MSSQL | 40001, HYT00, 08006 for the classified errors | error number | 1205, 3960 | 1222, command_timeout |
severity 20 or more (e.g. 596) |
| ORACLE | 40001, HYT00, 08006, 57014 for the classified errors | ORA number | 60, 8177 | 54, 2049, 30006, call_timeout |
ORA-00028, ORA-03113, ... |
| ClickHouse | HYT00, 57014 for the classified errors | exception code | – | 159 (max_execution_time) |
network failures |
| SQLite | 40001, HYT00, 57014 for the classified errors | extended result code | SQLITE_BUSY_SNAPSHOT |
SQLITE_BUSY |
– |
| ODBC | the driver's (HY008, operation canceled, becomes 57014) | native code | class 40 | HYT00, HYT01 (SQL Server's lock timeout 1222 arrives as 42000) | class 08 |
Network failures and failed connects are SQLNonTransientConnectionException in every driver (08006, 08001).
An Error from a client library (a failed assert, a range error) is not turned into an SQLException: it reaches
the caller unchanged (#269). The connection may then be in a broken state, so an application that catches the
Error and goes on must close that connection, not return it to a pool.
PostgreSQL, MySQL and SQL Server roll back (or abort) the whole transaction on a deadlock; Oracle rolls back only the
statement, so the transaction's earlier work stays until rollback().
Cancel and query timeout
As in JDBC, Statement.cancel() stops what a statement runs (its execution, or a fetch of its result set's rows) and
may be called from another thread or vibe.d task; setQueryTimeout(seconds) limits each execution and each fetch of
more rows (0, the default, keeps the connection's own setting, such as command_timeout in the URL):
Statement stmt = conn.createStatement();
stmt.setQueryTimeout(30);
try {
auto rs = stmt.executeQuery("SELECT slow_report()");
while (rs.next()) { ... }
} catch (SQLTimeoutException e) {
// SQLSTATE HYT00 (MySQL: the server's own); the connection works
}
// from another thread: the running call throws SQLException with SQLSTATE 57014
stmt.cancel();
The connection stays usable after both (MySQL: see the table). A statement that ended before the cancel reached the server keeps its result; PostgreSQL's protocol can't rule out that a cancel arriving that late hits the session's next statement. A connection in vibe.d's fiber mode (MSSQL, ORACLE, ClickHouse) takes a cancel from a task of its own thread; MSSQL and ORACLE ignore one from another thread.
| Driver | cancel() |
Query timeout |
|---|---|---|
| PGNATIVE | a CancelRequest | postgresql-native's commandTimeout: the time a request waits for the server, rows included |
| PGSQL | PQcancel |
the server's statement_timeout, set before a statement when it changes (one more round trip; a ROLLBACK TO SAVEPOINT undoes it unnoticed); it stays on the session until then, so commit() and metadata queries run under the last statement's timeout; a statement that names statement_timeout takes it over, and the pool resets it |
| MySQL | not supported: SQLFeatureNotSupportedException |
the session's max_statement_time (MariaDB, every statement) or max_execution_time (MySQL, read-only SELECTs only), set when it changes and kept on the session until then (on MariaDB commit() runs under it too; a statement that names the variable takes it over, and the pool resets it); mysql-native drops the session after the timeout's error, so an open transaction is lost |
| MSSQL | an attention request | mssql-native's commandTimeout: the time a request waits for the server, rows included |
| ORACLE | a break (the server can't interrupt DBMS_SESSION.SLEEP, nor a row-lock wait on 21c and later) |
oracle-native's callTimeout, for the execution and for each fetch |
| ClickHouse | a Cancel packet (an INSERT with data can't be cancelled: nothing happens; a cancelled executeUpdate returns normally, since the server ends it like a finished one and whether it took effect is unknown) |
the server's max_execution_time for the whole query |
| SQLite | sqlite3_interrupt (it stops every statement running on the connection, and an interrupted write rolls the transaction back; between two fetches nothing runs, so a cancel then does nothing) |
a progress handler that interrupts the statement at the deadline |
| ODBC | SQLCancel |
the statement's SQL_ATTR_QUERY_TIMEOUT, as the ODBC driver applies it |
Connections Strings
Connection strings should start with ddbc: followed by the driver type, eg: ddbc:mysql://localhost. However, the ddbc prefix is optional.
The overall format is typically [ddbc:]<DRIVER:>//[ HOSTNAME [ ,PORT ]] [ ? <PARAMS> }] except for SQLite
SQLite
SQLite can be configured for file based persistence or in-memory storage.
ddbc:sqlite:ddbc-test.sqlite
An in memory database can be configured by specifying :memory: instead of a filename:
ddbc:sqlite::memory:
busy_timeout sets how long (in milliseconds) a connection waits for another connection's lock before failing with
SQLITE_BUSY; the default is 0, failing at once:
ddbc:sqlite:ddbc-test.sqlite?busy_timeout=5000
With auto-commit off, SQLite may roll the transaction back by itself after some errors (SQLITE_FULL,
SQLITE_IOERR, SQLITE_NOMEM, SQLITE_INTERRUPT). The driver then refuses to start further statements, commit() and
setAutoCommit(true) until rollback(), instead of letting them run in auto-commit mode. The same happens when a
COMMIT or ROLLBACK statement run through a Statement ends the driver's transaction: with auto-commit off, end
transactions with commit() and rollback().
SQLite has no date or time types; the driver stores dates and times as text in the forms SQLite's date and time
functions understand: setDate writes YYYY-MM-DD, setDateTime YYYY-MM-DD HH:MM:SS, setTime HH:MM:SS.
Before ddbc 0.15, setDate wrote YYYYMMDD and setDateTime YYYYMMDDTHHMMSS (and before 0.14.2, setTime
wrote HHMMSS). The getters still read those forms as text, but SQLite compares text byte by byte, so a column
holding both forms doesn't match, sort or filter consistently. In a column with numeric or integer affinity
(declared DATE, TIME, DATETIME, INT, ...), SQLite stored the old date and time values as integers, and the
getters can't read those that lost a leading zero (011500 became 11500). Convert old values once, for each such
column (the statements expect the values stored as text or integers, and don't check that they are valid dates or
times: run them only on columns that ddbc wrote):
UPDATE t SET d = substr(printf('%08d', d), 1, 4) || '-' || substr(printf('%08d', d), 5, 2) || '-'
|| substr(printf('%08d', d), 7, 2)
WHERE (typeof(d) = 'integer' AND d BETWEEN 101 AND 99991231)
OR (typeof(d) = 'text' AND d GLOB '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]');
UPDATE t SET dt = substr(dt, 1, 4) || '-' || substr(dt, 5, 2) || '-' || substr(dt, 7, 2) || ' '
|| substr(dt, 10, 2) || ':' || substr(dt, 12, 2) || ':' || substr(dt, 14, 2)
WHERE dt GLOB '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]';
UPDATE t SET tm = substr(printf('%06d', tm), 1, 2) || ':' || substr(printf('%06d', tm), 3, 2) || ':'
|| substr(printf('%06d', tm), 5, 2)
WHERE (typeof(tm) = 'integer' AND tm BETWEEN 0 AND 235959)
OR (typeof(tm) = 'text' AND tm GLOB '[0-9][0-9][0-9][0-9][0-9][0-9]');
setSysTime and the SQL literals that ddbc.pods builds still write a T between the date and the time, and
setVariant with a SysTime writes its toString form (2019-Sep-15 15:18:51Z in UTC, with an offset for other
zones, no zone for local time; fractions when there are any). So don't mix them with setDateTime in one column
(#224 for pods, #225 for setSysTime and setVariant).
MySQL
ddbc:mysql://127.0.0.1:3306
PostgreSQL
ddbc:postgresql://127.0.0.1:5432
or
ddbc:postgresql://hostname:5432/dbname
The PostgreSQL driver loads the client library (libpq) at run time. On Linux and macOS, install the PostgreSQL client
package (e.g. libpq-dev or postgresql-libs). On Windows, install PostgreSQL (or just its command line tools) and add
its bin directory, e.g. C:\Program Files\PostgreSQL\17\bin, to PATH: libpq.dll needs the other DLLs in that
directory (OpenSSL, libintl, ...). ddbc no longer ships its own libpq.dll.
PostgreSQL (native)
Use the PGNATIVE configuration ("subConfigurations": { "ddbc": "PGNATIVE" }): the PostgreSQL protocol in pure D
through postgresql-native, no libpq or other C library at build
time; it works in threads and in vibe.d tasks (fiber mode, chosen automatically: see
Threads or vibe.d). PostgreSQL 13 and newer.
ddbc:postgresql://127.0.0.1:5432/dbname?user=app,password=secret
ddbc:postgresql://db1:5432,db2:5432/dbname?user=app,password=secret,sslmode=verify-full,sslrootcert=ca.pem
ddbc:pgnative://127.0.0.1/dbname?user=app,password=secret
The path is the database; the port defaults to 5432; several hosts fail over. Other parameters are libpq's
connection keywords: sslmode (default prefer), sslrootcert, sslcert, sslkey, application_name,
connect_timeout, target_session_attrs, require_auth, channel_binding, hostaddr, service, sslcrl,
sslcrldir, and postgresql-native's
statement_cache_size and io_mode; ssl=true/false as for the libpq driver; auto_commit=false starts with
auto-commit off. postgresql:// and postgres:// URLs use the native driver when the libpq driver (PGSQL) is not
compiled in; pgnative:// URLs always do.
Values arrive in binary and are read exactly: numeric with getDecimal (with its scale), integers, float4/float8,
text types, bytea, bool, date, time, timestamp (as UTC through getSysTime), timestamptz; getString
gives the server's text for every type (arrays, json, uuid, intervals, ...). Prepared statements take ? (or $1)
placeholders, values are sent for the types the server infers, and statements are parsed once (statement cache).
executeUpdate(sql, insertId) gives the first value a statement returns (INSERT ... RETURNING id); executeUpdate(sql)
without parameters may run several statements. With auto-commit off a transaction starts with the next statement;
setTransactionIsolation applies to the following transactions; the catalog is the database. Result sets are
forward-only and streamed. For COPY, LISTEN/NOTIFY, arrays and the other postgresql-native features, use
getNativeConnection().
ClickHouse
Use the ClickHouse configuration ("subConfigurations": { "ddbc": "ClickHouse" }). The default port is 9000 (the native protocol), or 9440 with TLS:
ddbc:clickhouse://127.0.0.1:9000/default?user=default,password=secret
or, with network compression and a ClickHouse setting:
ddbc:clickhouse://host1:9000,host2:9000/dbname?user=default,compress=lz4,max_threads=4
or over TLS (e.g. ClickHouse Cloud):
ddbc:clickhouse://abc123.eu-west-1.aws.clickhouse.cloud/default?user=default,password=secret,secure=true
TLS uses the system's OpenSSL library, loaded at run time only when a secure connection is made; see the clickhoused README for the TLS options (tls_ca_file, client certificates, ...) and where to get OpenSSL on each OS.
ClickHouse has no transactions (auto-commit only) and no auto-increment keys. Result sets are forward-only and streamed; prepared statement parameters are sent as typed server-side query parameters. String and byte parameters arrive unchanged since ddbc 0.15.1; before, the server decoded backslash sequences in them (\N, \t, \xFF) and refused a newline or tab (#233).
All column types of clickhoused 0.9 can be read: besides numbers, strings, dates and UUIDs also Decimal (reported as DECIMAL, with precision and scale), 128/256-bit integers (NUMERIC), BFloat16 (FLOAT), Time/Time64 (TIME; getTime for values from 00:00:00 to 23:59:59), LowCardinality, IPv4/IPv6, and Array, Tuple, Map, the geo types, Variant, Dynamic and JSON (OTHER, as text, e.g. [1,2], {'k':1}, (1.5,-2), {"a":1}; getVariant gives a Variant/Dynamic cell's value). JSON needs ClickHouse 24.10 or newer. For typed access to composite values, use getNativeConnection() and clickhoused's struct mapping. clickhoused 0.6 decodes strings, Bool/UUID/Nullable columns and LZ4-compressed results several times faster, and getString of floating-point values about 10–20 times faster.
Microsoft SQL Server (native)
Use the MSSQL configuration ("subConfigurations": { "ddbc": "MSSQL" }): the TDS protocol in pure D through
mssql-native, no ODBC driver or other C library at build time.
ddbc:mssql://127.0.0.1:1433/dbname?user=sa,password=secret,trust_server_certificate=true
With this configuration, sqlserver:// URLs use the native driver too, including the ODBC form
(ddbc:sqlserver://localhost,1433?user=sa,password=secret,encrypt=yes,trust_server_certificate=yes; driver is
ignored). Encryption is on by default with certificate verification; trust_server_certificate=true accepts the
self-signed certificate of a development server. TLS uses the system's OpenSSL library, loaded at run time. Other
parameters are the options of mssql-native connection strings (app_name, connect_timeout, receive_timeout,
packet_size, tls_ca_file, ...).
All common column types are read exactly: decimal/numeric/money with getDecimal, datetimeoffset with its
offset through getSysTime (datetime2, datetime and smalldatetime as UTC), varchar in the collation's code
page (also Japanese, Chinese, Korean), nvarchar, the (max) types, xml, uniqueidentifier, sql_variant.
Prepared statements use sp_prepexec/sp_execute; executeUpdate(sql, insertId) gives SCOPE_IDENTITY();
auto-commit off is SET IMPLICIT_TRANSACTIONS ON. Result sets are forward-only and streamed. For bulk inserts and
other features, use getNativeConnection().
Microsoft SQL Server (via ODBC)
ddbc:sqlserver://localhost,1433?user=sa,password=bbk4k77JKH88g54,driver=FreeTDS
or
ddbc:odbc://localhost,1433?user=sa,password=bbk4k77JKH88g54,driver=FreeTDS
Oracle (native)
Use the ORACLE configuration ("subConfigurations": { "ddbc": "ORACLE" }): Oracle Net (TNS/TTC) in pure D through
oracle-native, no Instant Client, OCI, ODBC or other C library at
build time. Oracle Database 12.1 and newer.
ddbc:oracle://127.0.0.1:1521/FREEPDB1?user=scott,password=tiger
The path is the service name (sid=... connects by SID instead); the port defaults to 1521. Other parameters are
the options of oracle-native connection strings: secure=true with tls_ca_file for TLS (the system's OpenSSL
library, loaded at run time) or wallet_location for a wallet, server=pooled for Database Resident Connection
Pooling (DRCP; pool_connection_class, pool_purity), proxy_client for proxy authentication, fetch_size,
statement_cache_size, time_zone, connect_timeout, ...; auto_commit=false starts with auto-commit off. With
this configuration oracle:// URLs use the native driver; without it, ODBC.
All common column types are read exactly: NUMBER with getDecimal (keeping the column's scale),
BINARY_FLOAT/BINARY_DOUBLE, VARCHAR2/NVARCHAR2/CHAR, RAW, DATE and TIMESTAMP (as UTC through
getSysTime), TIMESTAMP WITH TIME ZONE with its zone, CLOB/NCLOB/BLOB (through getString/getBytes),
LONG, ROWID. Prepared statements take ? (or :1, :name) placeholders and are parsed once (statement cache).
executeUpdate(sql, insertId) gives the value of a RETURNING id INTO ? clause, whose placeholder needs no value
(Oracle has no "last insert id"). Auto-commit commits after each statement that changes data; the isolation levels
are READ_COMMITTED and SERIALIZABLE; the catalog is the current schema. Empty strings are NULL in Oracle. Result
sets are forward-only and streamed. For LOB locators, array DML, PL/SQL OUT parameters and REF cursors, use
getNativeConnection().
Oracle (via ODBC) experimental
ddbc:oracle://localhost:1521?user=sa,password=bbk4k77JKH88g54,driver=FreeTDS
or
ddbc:odbc://localhost:1521?user=sa,password=bbk4k77JKH88g54,driver=FreeTDS
DSN connections for Microsoft SQL Server
The correct format to use for a dsn connection string is odbc://?dsn=<DSN name>.
Note that the server portion before the ? is empty, so the default server for
the DSN name will be used.
Contributing
pull requests are welcome. Please ensure your local branch is up to date and all tests are passing locally before making a pull request. A docker-compose file is included to help with local development. Use docker-compose up -d then run dub test --config=MySQL, dub test --config=PGSQL and dub test --config=ODBC. ClickHouse tests run with dub run --config=test-clickhouse, the native SQL Server tests with MSSQL_PORT=1433 dub run --config=test-mssql, the native Oracle tests with ORACLE_PORT=1521 ORACLE_SERVICE=FREEPDB1 ORACLE_USER=testuser ORACLE_PASSWORD=... dub run --config=test-oracle, the native PostgreSQL tests with POSTGRES_PORT=5432 dub run --config=test-pgnative (and dub run in examples/pgnative_vibe for fiber mode), and all new drivers in one build (full-native) with dub run --config=test-native and the environment variables of all of them (MYSQL_PORT, CLICKHOUSE_PORT, MSSQL_PORT, ORACLE_*, POSTGRES_PORT). See the .travis.yml file and individual driver code for details on creating the relevant databases for local testing.
The examples should also run, make sure to change to the example directory and run dub build then make sure that the compiled executable will run with each supported database (you'll need to install relevant libs and create databases and users with relevant permissions):
./ddbctest --connection=sqlite::memory:
./ddbctest --connection=mysql:127.0.0.1 --database=testdb --user=travis --password=bbk4k77JKH88g54
./ddbctest --connection=postgresql:127.0.0.1 --database=testdb --user=postgres
./ddbctest --connection=odbc://localhost --database=ddbctest --user=SA --password=bbk4k77JKH88g54 --driver="ODBC Driver 17 for SQL Server"
./ddbctest --connection=odbc://localhost --database=ddbctest --user=SA --password=bbk4k77JKH88g54 --driver=FreeTDS
In the case of the ODBC connection FreeTDS is just an example, if you have msodbcsql17 driver installed use that instead.
Also, you may want to only run a single database image at a time. In that case you can do docker-compose up <NAME>
Explorar proyectos relacionados
Cargando…