-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathdatabase.d
More file actions
2398 lines (1913 loc) · 55.7 KB
/
database.d
File metadata and controls
2398 lines (1913 loc) · 55.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/++
Generic interface for RDBMS access. Use with one of the implementations in [arsd.mysql], [arsd.sqlite], [arsd.postgres], or [arsd.mssql]. I'm sorry the docs are not good, but a little bit goes a long way:
---
auto db = new Sqlite("file.db"); // see the implementations for constructors
// then the interface, for any impl can be as simple as:
foreach(row; db.query("SELECT id, name FROM people")) {
string id = row[0];
string name = row[1];
}
db.query("INSERT INTO people (id, name) VALUES (?, ?)", 5, "Adam");
---
To convert to other types, just use [std.conv.to] since everything comes out of this as simple strings with the exception of binary data,
which you'll want to cast to const(ubyte)[].
History:
Originally written prior to 2011.
On August 2, 2022, the behavior of BLOB (or BYTEA in postgres) changed significantly.
Before, it would convert to strings with `to!string(bytes)` on insert and platform specific
on query. It didn't really work at all.
It now actually stores ubyte[] as a blob and retrieves it without modification. Note you need to
cast it.
This is potentially breaking, but since it didn't work much before I doubt anyone was using it successfully
but this might be a problem. I advise you to retest.
Be aware I don't like this string interface much anymore and want to change it significantly but idk
how to work it in without breaking a decade of code.
On June 7, 2023 (dub 11.0), I started the process of moving away from strings as the inner storage unit. This is a potentially breaking change, but you can use `.toString` to convert as needed and `alias this` will try to do this automatically in many situations. See [DatabaseDatum] for details. This transition is not yet complete.
Notably, passing it to some std.string functions will cause errors referencing DatabaseDatum like:
$(CONSOLE
Error: template `std.array.replace` cannot deduce function from argument types `!()(string, string, DatabaseDatum)`
path/phobos/std/array.d(2459): Candidates are: `replace(E, R1, R2)(E[] subject, R1 from, R2 to)`
with `E = immutable(char),
R1 = string,
R2 = DatabaseDatum`
)
Because templates do not trigger alias this - you will need to call `.toString()` yourself at the usage site.
+/
module arsd.database;
// FIXME: add some kind of connection pool thing we can easily use
// I should do a prepared statement as a template string arg
public import std.variant;
import std.string;
public import std.datetime;
static import arsd.core;
private import arsd.core : LimitedVariant;
/*
Database 2.0 plan, WIP:
// Do I want to do some kind of RAII?
auto database = Database(new MySql("connection info"));
* Prepared statement support
* Queries with separate args whenever we can with consistent interface
* Query returns some typed info when we can.
* ....?
PreparedStatement prepareStatement(string sql);
Might be worth looking at doing the preparations in static ctors
so they are always done once per program...
*/
///
interface Database {
/// Just executes a query. It supports placeholders for parameters
final ResultSet query(T...)(string sql, T t) {
Variant[] args;
foreach(arg; t) {
Variant a;
static if(__traits(compiles, a = arg))
a = arg;
else
a = to!string(t);
args ~= a;
}
return queryImpl(sql, args);
}
final ResultSet query(Args...)(arsd.core.InterpolationHeader header, Args args, arsd.core.InterpolationFooter footer) {
return queryImpl(sqlFromInterpolatedArgs!Args, variantsFromInterpolatedArgs(args));
}
final void withTransaction(scope void delegate() dg) {
this.startTransaction();
scope(success)
this.query("COMMIT");
scope(failure)
this.query("ROLLBACK");
dg();
}
/// query to start a transaction, only here because sqlite is apparently different in syntax...
void startTransaction();
/// Actually implements the query for the database. The query() method
/// below might be easier to use.
ResultSet queryImpl(string sql, Variant[] args...);
/// Escapes data for inclusion into an sql string literal
string escape(string sqlData);
/// Escapes binary data for inclusion into a sql string. Note that unlike `escape`, the returned string here SHOULD include the quotes.
string escapeBinaryString(const(ubyte)[] sqlData);
/// turns a systime into a value understandable by the target database as a timestamp to be concated into a query. so it should be quoted and escaped etc as necessary
string sysTimeToValue(SysTime);
// see test/dbis.d
/++
Return true if the connection appears to be alive
History:
Added October 30, 2025
+/
bool isAlive();
/// Prepared statement api
/*
PreparedStatement prepareStatement(string sql, int numberOfArguments);
*/
}
// Added Oct 26, 2021
Row queryOneRow(string file = __FILE__, size_t line = __LINE__, T...)(Database db, string sql, T t) {
auto res = db.query(sql, t);
import arsd.core;
if(res.empty)
throw ArsdException!("no row in result")(sql, t, file, line);
auto row = res.front;
return row;
}
Ret queryOneColumn(Ret, string file = __FILE__, size_t line = __LINE__, T...)(Database db, string sql, T t) {
auto row = queryOneRow(db, sql, t);
return to!Ret(row[0]);
}
struct Query {
ResultSet result;
this(T...)(Database db, string sql, T t) if(T.length!=1 || !is(T[0]==Variant[])) {
result = db.query(sql, t);
}
// Version for dynamic generation of args: (Needs to be a template for coexistence with other constructor.
this(T...)(Database db, string sql, T args) if (T.length==1 && is(T[0] == Variant[])) {
result = db.queryImpl(sql, args);
}
int opApply(T)(T dg) if(is(T == delegate)) {
import std.traits;
foreach(row; result) {
ParameterTypeTuple!dg tuple;
foreach(i, item; tuple) {
tuple[i] = to!(typeof(item))(row[i]);
}
if(auto result = dg(tuple))
return result;
}
return 0;
}
}
/++
Represents a single item in a result. A row is a set of these `DatabaseDatum`s.
History:
Added June 2, 2023 (dub v11.0). Prior to this, it would always use `string`. This has `alias toString this` to try to maintain compatibility.
+/
struct DatabaseDatum {
int platformSpecificTag;
LimitedVariant storage;
/++
These are normally constructed by the library, so you shouldn't need these constructors. If you're writing a new database implementation though, here it is.
+/
package this(string s) {
storage = s;
}
/++
Returns `true` if the item was `NULL` in the database.
+/
bool isNull() {
return storage.contains == LimitedVariant.Contains.null_;
}
/++
Converts the datum to a string in a format specified by the database.
+/
string toString() {
if(isNull())
return null;
return storage.toString();
}
/++
For compatibility with earlier versions of the api, all data can easily convert to string implicitly and opCast keeps to!x(this) working.
The toArsdJsVar one is in particular subject to change.
+/
alias toString this;
/// ditto
T opCast(T)() {
import std.conv;
return to!T(this.toString);
}
/// ditto
string toArsdJsVar() { return this.toString; }
/++
Explicit indicator that you want a NULL value for the database.
History:
Added December 8, 2025
+/
static DatabaseDatum NULL() {
return DatabaseDatum();
}
}
unittest {
// tbh this is more of a phobos test but rvaluerefparam has messed it up before
auto db = DatabaseDatum("1234567");
assert(to!int(db) == 1234567);
assert(to!long(db) == 1234567);
assert(to!int(DatabaseDatum("1234567")) == 1234567);
assert(to!long(DatabaseDatum("1234567")) == 1234567);
assert(DatabaseDatum.NULL.isNull());
}
/++
A row in a result set from a query.
You can access this as either an array or associative array:
---
foreach(Row row; db.query("SELECT id, name FROM mytable")) {
// can access by index or by name
row[0] == row["id"];
row[1] == row["name"];
// can also iterate over the results
foreach(name, data; row) {
// will send name = "id", data = the thing
// and then next loop will be name = "name", data = the thing
}
}
---
+/
struct Row {
package DatabaseDatum[] row;
package ResultSet resultSet;
/++
Allows for access by index or column name.
+/
DatabaseDatum opIndex(size_t idx, string file = __FILE__, int line = __LINE__) {
if(idx >= row.length)
throw new Exception(text("index ", idx, " is out of bounds on result"), file, line);
return row[idx];
}
/// ditto
DatabaseDatum opIndex(string name, string file = __FILE__, int line = __LINE__) {
auto idx = resultSet.getFieldIndex(name);
if(idx >= row.length)
throw new Exception(text("no field ", name, " in result"), file, line);
return row[idx];
}
/++
Provides a string representation of the row, for quick eyeball debugging. You probably won't want the format this prints in (and don't rely upon it, as it is subject to change at any time without notice!), but it might be useful for use with `writeln`.
+/
string toString() {
return to!string(row);
}
/++
Allows iteration over the columns with the `foreach` statement.
History:
Prior to June 11, 2023 (dub v11.0), the order of iteration was undefined. It is now guaranteed to be in the same order as it was returned by the database (which is determined by your original query). Additionally, prior to this date, the datum was typed `string`. `DatabaseDatum` should implicitly convert to string, so your code is unlikely to break, but if you did specify the type explicitly you may need to update your code.
The overload with one argument, having just the datum without the name, was also added on June 11, 2023 (dub v11.0).
+/
int opApply(int delegate(string, DatabaseDatum) dg) {
string[] fn = resultSet.fieldNames();
foreach(idx, item; row)
mixin(yield("fn[idx], item"));
return 0;
}
/// ditto
int opApply(int delegate(DatabaseDatum) dg) {
foreach(item; row)
mixin(yield("item"));
return 0;
}
/++
Hacky conversion to simpler types.
I'd recommend against using these in new code. I wrote them back around 2011 as a hack for something I was doing back then. Among the downsides of these is type information loss in both functions (since strings discard the information tag) and column order loss in `toAA` (since D associative arrays do not maintain any defined order). Additionally, they to make an additional copy of the result row, which you may be able to avoid by looping over it directly.
I may formally deprecate them in a future release.
+/
string[] toStringArray() {
string[] row;
foreach(item; this.row)
row ~= item;
return row;
}
/// ditto
string[string] toAA() {
string[string] a;
string[] fn = resultSet.fieldNames();
foreach(i, r; row)
a[fn[i]] = r;
return a;
}
}
import std.conv;
interface ResultSet {
// name for associative array to result index
int getFieldIndex(string field);
string[] fieldNames();
// this is a range that can offer other ranges to access it
bool empty() @property;
Row front() @property;
void popFront() ;
size_t length() @property;
/* deprecated */ final ResultSet byAssoc() { return this; }
}
/++
Converts a database result set to a html table, using [arsd.dom].
History:
Added October 29, 2025
+/
auto resultSetToHtmlTable()(ResultSet resultSet) {
import arsd.dom;
Table table = cast(Table) Element.make("table");
table.appendHeaderRow(resultSet.fieldNames);
foreach(row; resultSet) {
table.appendRow(row.toStringArray());
}
return table;
}
abstract class ConnectionPoolBase : arsd.core.SynchronizableObject {
protected struct DatabaseListItem {
Database db;
DatabaseListItem* nextAvailable;
}
private DatabaseListItem* firstAvailable;
// FIXME: add a connection count limit and some kind of wait mechanism for one to become available
final protected void makeAvailable(DatabaseListItem* what) {
synchronized(this) {
auto keep = this.firstAvailable;
what.nextAvailable = keep;
this.firstAvailable = what;
}
}
final protected DatabaseListItem* getNext() {
DatabaseListItem* toUse;
synchronized(this) {
if(this.firstAvailable !is null) {
toUse = this.firstAvailable;
this.firstAvailable = this.firstAvailable.nextAvailable;
}
}
return toUse;
}
}
/++
PooledConnection is an RAII holder for a database connection that is automatically recycled to the pool it came from (unless you [discard] it).
History:
Added October 29, 2025
+/
struct PooledConnection(ConnectionPoolType) {
private ConnectionPoolType.DatabaseListItem* dli;
private ConnectionPoolType pool;
private bool discarded;
private this(ConnectionPoolType.DatabaseListItem* dli, ConnectionPoolType pool) {
this.dli = dli;
this.pool = pool;
}
@disable this(this);
/++
Indicates you want the connection discarded instead of returned to the pool when you're finished with it.
You should call this if you know the connection is dead.
+/
void discard() {
this.discarded = true;
}
~this() {
import core.memory;
if(GC.inFinalizer)
return;
if(!discarded && dli.db.isAlive) {
// FIXME: a connection must not be returned to the pool unless it is both alive and idle; any pending query work would screw up the next user
// it is the user's responsibility to live with other state though like prepared statements or whatever saved per-connection.
pool.makeAvailable(dli);
}
}
/++
+/
ConnectionPoolType.DriverType borrow() @system return {
return cast(ConnectionPoolType.DriverType) dli.db; // static_cast
}
/++
+/
ResultSet rtQuery(T...)(T t) {
return dli.db.query(t);
}
/++
+/
template query(string file = __FILE__, size_t line = __LINE__, Args...) {
enum asSql = sqlFromInterpolatedArgs!(Args);
__gshared queryMetadata = new QueryMetadata!(asSql, file, line);
@(arsd.core.standalone) @system shared static this() {
ConnectionPoolType.registeredQueries_ ~= queryMetadata;
}
auto query(arsd.core.InterpolationHeader ihead, Args args, arsd.core.InterpolationFooter ifoot) {
return new QueryResult!queryMetadata(dli.db.queryImpl(asSql, variantsFromInterpolatedArgs(args)));
}
}
}
/++
+/
unittest {
import arsd.database;
shared dbPool = new shared ConnectionPool!(() => new MockDatabase())();
void main() {
auto db = dbPool.get();
foreach(row; db.query(i"SELECT * FROM test")) {
if(row.id.isNull)
continue;
auto id = row.id.get!int;
}
}
main(); // remove from docs
}
private Variant[] variantsFromInterpolatedArgs(Args...)(Args args) {
Variant[] ret;
import arsd.core;
foreach(arg; args) {
static if(is(typeof(arg) == InterpolationHeader))
{}
else
static if(is(typeof(arg) == InterpolationFooter))
{}
else
static if(is(typeof(arg) == InterpolatedLiteral!sql, string sql))
{}
else
static if(is(typeof(arg) == InterpolatedExpression!code, string code))
{}
else
static if(is(typeof(arg) == AdHocBuiltStruct!(tag, names, Values), string tag, string[] names, Values...)) {
static if(tag == "VALUES") {
foreach(value; arg.values) {
static if(is(value == sql_!code, string code)) {
// intentionally blank
} else {
ret ~= Variant(value);
}
}
} else static assert(0);
}
// FIXME: iraw and sql!"" too and VALUES
else
ret ~= Variant(arg);
}
return ret;
}
private string sqlFromInterpolatedArgs(Args...)() {
string ret;
import arsd.core;
foreach(arg; Args) {
static if(is(arg == InterpolationHeader))
{}
else
static if(is(arg == InterpolationFooter))
{}
else
static if(is(arg == InterpolatedLiteral!sql, string sql))
ret ~= sql;
else
static if(is(arg == InterpolatedExpression!code, string code))
{}
else
static if(is(arg == AdHocBuiltStruct!(tag, names, values), string tag, string[] names, values...)) {
static if(tag == "VALUES") {
ret ~= "(";
foreach(idx, name; names) {
if(idx) ret ~= ", ";
ret ~= name;
}
ret ~= ") VALUES (";
foreach(idx, value; values) {
if(idx) ret ~= ", ";
static if(is(value == sql_!code, string code)) {
ret ~= code;
} else {
ret ~= "?";
}
}
ret ~= ")";
}
else static assert(0);
}
// FIXME: iraw and sql_!"" too
else
ret ~= "?";
}
return ret;
}
/+
+/
struct AssociatedDatabaseDatum(alias queryMetadata, string name, string file, size_t line) {
@(arsd.core.standalone) @system shared static this() {
queryMetadata.registerName(name, file, line);
}
template get(T, string file = __FILE__, size_t line = __LINE__) {
shared static this() {
// FIXME: empty string and null must be distinguishable in arsd.core
static if(is(T == string))
T t = "sample";
else
T t = T.init;
queryMetadata.registerType(name, LimitedVariant(t), T.stringof, file, line);
}
T get() {
import std.conv;
return datum.toString().to!T;
}
}
DatabaseDatum datum;
bool isNull() {
return datum.isNull();
}
string toString() {
if(isNull)
return null;
else
return datum.toString();
}
alias toString this;
}
private abstract class QueryResultBase {
}
class QueryResult(alias queryMetadata) : QueryResultBase {
private ResultSet resultSet;
this(ResultSet resultSet) {
this.resultSet = resultSet;
}
QueryResultRow!queryMetadata front() {
return new QueryResultRow!queryMetadata(resultSet.front);
}
bool empty() {
return resultSet.empty;
}
void popFront() {
resultSet.popFront();
}
}
class QueryResultRow(alias queryMetadata) {
Row row;
this(Row row) {
this.row = row;
}
AssociatedDatabaseDatum!(queryMetadata, name, file, line) opDispatch(string name, string file = __FILE__, size_t line = __LINE__)() if(name != "__dtor") {
return typeof(return)(row[name]);
}
// i could support an opSlice. maybe opIndex tho it won't be CT bound checked w/o a ct!0 thing
// also want opApply which discards type check prolly and just gives you the datum.
int opApply(int delegate(string, DatabaseDatum) dg) {
string[] fn = row.resultSet.fieldNames();
foreach(idx, item; row.row)
mixin(yield("fn[idx], item"));
return 0;
}
/// ditto
int opApply(int delegate(DatabaseDatum) dg) {
foreach(item; row.row)
mixin(yield("item"));
return 0;
}
}
struct ReferencedColumn {
string name;
LimitedVariant sampleData;
string assumedType;
string actualType;
string file;
size_t line;
}
class QueryMetadataBase {
ReferencedColumn[] names;
void registerName(string name, string file, size_t line) {
names ~= ReferencedColumn(name, LimitedVariant.init, null, null, file, line);
}
void registerType(string name, LimitedVariant sample, string type, string file, size_t line) {
foreach(ref n; names)
if(n.name == name) {
if(n.assumedType.length && type.length) {
n.actualType = type;
}
n.assumedType = type;
n.sampleData = sample;
n.file = file;
n.line = line;
return;
}
names ~= ReferencedColumn(name, sample, type, type, file, line);
}
abstract string sql() const;
abstract string file() const;
abstract size_t line() const;
}
class QueryMetadata(string q, string file_, size_t line_) : QueryMetadataBase {
override string sql() const { return q; }
override string file() const { return file_; }
override size_t line() const { return line_; }
}
version(unittest)
class MockDatabase : Database {
void startTransaction() {}
string sysTimeToValue(SysTime s) { return null; }
bool isAlive() { return true; }
ResultSet queryImpl(string sql, Variant[] args...) {
return new PredefinedResultSet(null, null);
}
string escape(string sqlData) {
return null;
}
string escapeBinaryString(const(ubyte)[] sqlData) {
return null;
}
}
/++
Helpers for interpolated queries.
History:
Added October 31, 2025
See_Also:
[arsd.core.iraw]
+/
auto VALUES() {
import arsd.core;
return AdHocBuiltStruct!"VALUES"();
}
/// ditto
auto sql(string s)() {
return sql_!s();
}
private struct sql_(string s) { }
/++
A ConnectionPool manages a set of shared connections to a database.
Create one like this:
---
// at top level
shared dbPool = new shared ConnectionPool!(() => new PostgreSql("dbname=me"))();
void main() {
auto db = dbPool.get(); // in the function, get it and use it temporarily
}
---
History:
Added October 29, 2025
+/
class ConnectionPool(alias connectionFactory) : ConnectionPoolBase {
private alias unsharedThis = ConnectionPool!connectionFactory;
static if(is(typeof(connectionFactory) DriverType == return)) {
static if(!is(DriverType : Database))
static assert(0, "unusable connectionFactory - it needs to return an instance of Database");
} else {
static assert(0, "unusable connectionFactory - it needs to be a function");
}
private __gshared QueryMetadataBase[] registeredQueries_;
immutable(QueryMetadataBase[]) registeredQueries() shared {
return cast(immutable(QueryMetadataBase[])) registeredQueries_;
}
bool checkQueries()(DriverType db) shared {
bool succeeded = true;
import arsd.postgres; // FIXME is this really postgres only? looks like sqlite has no similar function... maybe make a view then sqlite3_table_column_metadata ?
static assert(is(DriverType == PostgreSql), "Only implemented for postgres right now");
int count;
import arsd.core;
import arsd.conv;
foreach(q; registeredQueries) {
//writeln(q.file, ":", q.line, " ", q.sql);
try {
try {
string dbSpecificSql;
int placeholderNumber = 1;
size_t lastCopied = 0;
foreach(idx, ch; q.sql) {
if(ch == '?') {
dbSpecificSql ~= q.sql[lastCopied .. idx];
lastCopied = idx + 1;
dbSpecificSql ~= "$" ~ to!string(placeholderNumber);
placeholderNumber++;
}
}
dbSpecificSql ~= q.sql[lastCopied .. $];
// FIXME: pipeline this
db.query("PREPARE thing_"~to!string(++count)~" AS " ~ dbSpecificSql);
} catch(Exception e) {
e.file = q.file;
e.line = q.line;
throw e;
// continue;
}
// this mysql function looks about right: https://dev.mysql.com/doc/c-api/8.0/en/mysql-stmt-result-metadata.html
// could maybe emulate by trying it in a rolled back transaction though.
auto desca = describePrepared(db,"thing_"~arsd.conv.to!string(count));
LimitedVariant[string] byName;
foreach(col; desca.result) {
byName[col.fieldName] = col.type.storage;
}
foreach(name; q.names) {
if(name.name !in byName)
throw ArsdException!"you reference unknown field"(name.name, name.file, name.line);
if(name.assumedType.length == 0)
continue;
if(byName[name.name].contains != name.sampleData.contains)
throw ArsdException!"type mismatch"(
name.name,
arsd.conv.to!string(byName[name.name].contains),
arsd.conv.to!string(name.sampleData.contains),
name.file,
name.line,
);
// i think this is redundant
if(name.assumedType.length && name.actualType.length && name.actualType != name.assumedType) {
throw ArsdException!"usage mismatch"(name.assumedType, name.actualType, name.file, name.line);
}
}
} catch(Exception e) {
writeln(e.toString());
succeeded = false;
}
}
if(!succeeded)
writeln("db check failed.");
return succeeded;
}
/++
+/
public PooledConnection!(unsharedThis) get() shared {
auto toUse = (cast(unsharedThis) this).getNext();
if(toUse is null)
toUse = new DatabaseListItem(connectionFactory());
return PooledConnection!(unsharedThis)(toUse, cast(unsharedThis) this);
}
}
/++
Parent class of various forms of errors you can get when using the database.d library. It may be thrown generically when other details are not provided by a driver.
See_Also:
[DatabaseConnectionException], [SqlException], [DataUsageException]
History:
Added prior to July 2011.
+/
class DatabaseException : Exception {
this(string msg, string file = __FILE__, size_t line = __LINE__) {
super(msg, file, line);
}
}
/++
Thrown when something is wrong with your connection to the database server.
History:
Added December 11, 2025
+/
class DatabaseConnectionException : DatabaseException {
this(string msg, string file = __FILE__, size_t line = __LINE__) {
super(msg, file, line);
}
}
/++
Thrown when your sql query has reached the database server, but failed to run there for some reason.
It is possible for this to be thrown on a connection problem in a query too, if the driver didn't differentiate the cause.
History:
Added December 11, 2025
+/
class SqlException : DatabaseException {
this(string msg, string file = __FILE__, size_t line = __LINE__) {
super(msg, file, line);
}
}
/++
Thrown when you use result data incorrectly. These almost always are preventable, but may be the result of a schema change and a `select *` query too.
History:
Added December 11, 2025
+/
class DataUsageException : DatabaseException {
this(string msg, string file = __FILE__, size_t line = __LINE__) {
super(msg, file, line);
}
}
abstract class SqlBuilder { }
class InsertBuilder : SqlBuilder {
private string table;
private string[] fields;
private string[] fieldsSetSql;
private Variant[] values;
///
void setTable(string table) {
this.table = table;
}
/// same as adding the arr as values one by one. assumes DB column name matches AA key.
void addVariablesFromAssociativeArray(in string[string] arr, string[] names...) {
foreach(name; names) {
fields ~= name;
if(name in arr) {
fieldsSetSql ~= "?";
values ~= Variant(arr[name]);
} else {
fieldsSetSql ~= "null";
}
}
}
///
void addVariable(T)(string name, T value) {
fields ~= name;
fieldsSetSql ~= "?";
values ~= Variant(value);
}
/// if you use a placeholder, be sure to [addValueForHandWrittenPlaceholder] immediately
void addFieldWithSql(string name, string sql) {
fields ~= name;
fieldsSetSql ~= sql;
}
/// for addFieldWithSql that includes a placeholder
void addValueForHandWrittenPlaceholder(T)(T value) {
values ~= Variant(value);
}
/// executes the query
auto execute(Database db, string supplementalSql = null) {
return db.queryImpl(this.toSql() ~ supplementalSql, values);
}
string toSql() {
string sql = "INSERT INTO\n";
sql ~= "\t" ~ table ~ " (\n";
foreach(idx, field; fields) {
sql ~= "\t\t" ~ field ~ ((idx != fields.length - 1) ? ",\n" : "\n");
}
sql ~= "\t) VALUES (\n";
foreach(idx, field; fieldsSetSql) {
sql ~= "\t\t" ~ field ~ ((idx != fieldsSetSql.length - 1) ? ",\n" : "\n");
}
sql ~= "\t)\n";
return sql;
}
}
/// WARNING: this is as susceptible to SQL injections as you would be writing it out by hand
class SelectBuilder : SqlBuilder {
string[] fields;
string table;