-
Notifications
You must be signed in to change notification settings - Fork 128
/
database.d
1815 lines (1438 loc) · 42 KB
/
database.d
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 {
/// 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);
/// query to start a transaction, only here because sqlite is apparently different in syntax...
void startTransaction();
/// 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) {
import arsd.core;
Variant[] vargs;
string sql;
foreach(arg; args) {
static if(is(typeof(arg) == InterpolatedLiteral!str, string str)) {
sql ~= str;
} else static if(is(typeof(arg) == InterpolatedExpression!str, string str)) {
// intentionally blank
} else static if(is(typeof(arg) == InterpolationHeader) || is(typeof(arg) == InterpolationFooter)) {
static assert(0, "Nested interpolations not allowed at this time");
} else {
sql ~= "?";
vargs ~= Variant(arg);
}
}
return queryImpl(sql, vargs);
}
/// 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);
/// Prepared statement api
/*
PreparedStatement prepareStatement(string sql, int numberOfArguments);
*/
}
import std.stdio;
// 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; }
}
/++
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; }
}
class DatabaseException : Exception {
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;
string[] joins;
string[] wheres;
string[] orderBys;
string[] groupBys;
int limit;
int limitStart;
Variant[string] vars;
void setVariable(T)(string name, T value) {
assert(name.length);
if(name[0] == '?')
name = name[1 .. $];
vars[name] = Variant(value);
}
Database db;
this(Database db = null) {
this.db = db;
}
/*
It would be nice to put variables right here in the builder
?name
will prolly be the syntax, and we'll do a Variant[string] of them.
Anything not translated here will of course be in the ending string too
*/
SelectBuilder cloned() {
auto s = new SelectBuilder(this.db);
s.fields = this.fields.dup;
s.table = this.table;
s.joins = this.joins.dup;
s.wheres = this.wheres.dup;
s.orderBys = this.orderBys.dup;
s.groupBys = this.groupBys.dup;
s.limit = this.limit;
s.limitStart = this.limitStart;
foreach(k, v; this.vars)
s.vars[k] = v;
return s;
}
override string toString() {
string sql = "SELECT ";
// the fields first
{
bool outputted = false;
foreach(field; fields) {
if(outputted)
sql ~= ", ";
else
outputted = true;
sql ~= field; // "`" ~ field ~ "`";
}
}
sql ~= " FROM " ~ table;
if(joins.length) {
foreach(join; joins)
sql ~= " " ~ join;
}
if(wheres.length) {
bool outputted = false;
sql ~= " WHERE ";
foreach(w; wheres) {
if(outputted)
sql ~= " AND ";
else
outputted = true;
sql ~= "(" ~ w ~ ")";
}
}
if(groupBys.length) {
bool outputted = false;
sql ~= " GROUP BY ";
foreach(o; groupBys) {
if(outputted)
sql ~= ", ";
else
outputted = true;
sql ~= o;
}
}
if(orderBys.length) {
bool outputted = false;
sql ~= " ORDER BY ";
foreach(o; orderBys) {
if(outputted)
sql ~= ", ";
else
outputted = true;
sql ~= o;
}
}
if(limit) {
sql ~= " LIMIT ";
if(limitStart)
sql ~= to!string(limitStart) ~ ", ";
sql ~= to!string(limit);
}
if(db is null)
return sql;
return escapedVariants(db, sql, vars);
}
}
// /////////////////////sql//////////////////////////////////
package string tohexsql(const(ubyte)[] b) {
char[] x;
x.length = b.length * 2 + 3;
int pos = 0;
x[pos++] = 'x';
x[pos++] = '\'';
char tohex(ubyte a) {
if(a < 10)
return cast(char)(a + '0');
else
return cast(char)(a - 10 + 'A');
}
foreach(item; b) {
x[pos++] = tohex(item >> 4);
x[pos++] = tohex(item & 0x0f);
}
x[pos++] = '\'';
return cast(string) x;
}
// used in the internal placeholder thing
string toSql(Database db, Variant a) {
string binary(const(ubyte)[] b) {
if(b is null)
return "NULL";
else
return db.escapeBinaryString(b);
}
auto v = a.peek!(void*);
if(v && (*v is null)) {
return "NULL";
} else if(auto t = a.peek!(SysTime)) {
return db.sysTimeToValue(*t);
} else if(auto t = a.peek!(DateTime)) {
// FIXME: this might be broken cuz of timezones!
return db.sysTimeToValue(cast(SysTime) *t);
} else if(auto t = a.peek!(ubyte[])) {
return binary(*t);
} else if(auto t = a.peek!(immutable(ubyte)[])) {
return binary(*t);
} else if(auto t = a.peek!string) {
auto str = *t;
if(str is null)
return "NULL";
else
return '\'' ~ db.escape(str) ~ '\'';
} else {
string str = to!string(a);
return '\'' ~ db.escape(str) ~ '\'';
}
assert(0);
}
// just for convenience; "str".toSql(db);
string toSql(string s, Database db) {
//if(s is null)
//return "NULL";
return '\'' ~ db.escape(s) ~ '\'';
}
string toSql(long s, Database db) {
return to!string(s);
}
string escapedVariants(Database db, in string sql, Variant[string] t) {
if(t.keys.length <= 0 || sql.indexOf("?") == -1) {
return sql;
}
string fixedup;
int currentStart = 0;
// FIXME: let's make ?? render as ? so we have some escaping capability
foreach(i, dchar c; sql) {
if(c == '?') {
fixedup ~= sql[currentStart .. i];
int idxStart = cast(int) i + 1;
int idxLength;
bool isFirst = true;
while(idxStart + idxLength < sql.length) {
char C = sql[idxStart + idxLength];
if((C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z') || C == '_' || (!isFirst && C >= '0' && C <= '9'))
idxLength++;
else
break;
isFirst = false;
}
auto idx = sql[idxStart .. idxStart + idxLength];
if(idx in t) {
fixedup ~= toSql(db, t[idx]);
currentStart = idxStart + idxLength;
} else {
// just leave it there, it might be done on another layer
currentStart = cast(int) i;
}
}
}
fixedup ~= sql[currentStart .. $];
return fixedup;
}
/// Note: ?n params are zero based!
string escapedVariants(Database db, in string sql, Variant[] t) {
// FIXME: let's make ?? render as ? so we have some escaping capability
// if nothing to escape or nothing to escape with, don't bother
if(t.length > 0 && sql.indexOf("?") != -1) {
string fixedup;
int currentIndex;
int currentStart = 0;
foreach(i, dchar c; sql) {
if(c == '?') {
fixedup ~= sql[currentStart .. i];
int idx = -1;
currentStart = cast(int) i + 1;
if((i + 1) < sql.length) {
auto n = sql[i + 1];
if(n >= '0' && n <= '9') {
currentStart = cast(int) i + 2;
idx = n - '0';
}
}
if(idx == -1) {
idx = currentIndex;
currentIndex++;
}
if(idx < 0 || idx >= t.length)
throw new Exception("SQL Parameter index is out of bounds: " ~ to!string(idx) ~ " at `"~sql[0 .. i]~"`");
fixedup ~= toSql(db, t[idx]);
}
}
fixedup ~= sql[currentStart .. $];
return fixedup;
/*
string fixedup;
int pos = 0;
void escAndAdd(string str, int q) {
fixedup ~= sql[pos..q] ~ '\'' ~ db.escape(str) ~ '\'';
}
foreach(a; t) {
int q = sql[pos..$].indexOf("?");
if(q == -1)
break;
q += pos;
auto v = a.peek!(void*);
if(v && (*v is null))
fixedup ~= sql[pos..q] ~ "NULL";
else {
string str = to!string(a);
escAndAdd(str, q);
}
pos = q+1;
}
fixedup ~= sql[pos..$];
sql = fixedup;
*/
}
return sql;
}
enum UpdateOrInsertMode {
CheckForMe,
AlwaysUpdate,
AlwaysInsert
}
// BIG FIXME: this should really use prepared statements
int updateOrInsert(Database db, string table, string[string] values, string where, UpdateOrInsertMode mode = UpdateOrInsertMode.CheckForMe, string key = "id") {
string identifierQuote = "";
bool insert = false;
final switch(mode) {
case UpdateOrInsertMode.CheckForMe:
auto res = db.query("SELECT "~key~" FROM "~identifierQuote~db.escape(table)~identifierQuote~" WHERE " ~ where);
insert = res.empty;
break;
case UpdateOrInsertMode.AlwaysInsert:
insert = true;
break;
case UpdateOrInsertMode.AlwaysUpdate:
insert = false;
break;
}
if(insert) {
string insertSql = "INSERT INTO " ~identifierQuote ~ db.escape(table) ~ identifierQuote ~ " ";
bool outputted = false;
string vs, cs;
foreach(column, value; values) {
if(column is null)
continue;
if(outputted) {
vs ~= ", ";
cs ~= ", ";
} else
outputted = true;
//cs ~= "`" ~ db.escape(column) ~ "`";
cs ~= identifierQuote ~ column ~ identifierQuote; // FIXME: possible insecure
if(value is null)
vs ~= "NULL";
else
vs ~= "'" ~ db.escape(value) ~ "'";
}
if(!outputted)
return 0;
insertSql ~= "(" ~ cs ~ ")";
insertSql ~= " VALUES ";
insertSql ~= "(" ~ vs ~ ")";
db.query(insertSql);
return 0; // db.lastInsertId;
} else {
string updateSql = "UPDATE "~identifierQuote~db.escape(table)~identifierQuote~" SET ";
bool outputted = false;
foreach(column, value; values) {
if(column is null)
continue;
if(outputted)
updateSql ~= ", ";
else
outputted = true;
if(value is null)
updateSql ~= identifierQuote ~ db.escape(column) ~ identifierQuote ~ " = NULL";
else
updateSql ~= identifierQuote ~ db.escape(column) ~ identifierQuote ~ " = '" ~ db.escape(value) ~ "'";
}
if(!outputted)
return 0;
updateSql ~= " WHERE " ~ where;
db.query(updateSql);
return 0;
}
}
string fixupSqlForDataObjectUse(string sql, string[string] keyMapping = null) {
string[] tableNames;
string piece = sql;
sizediff_t idx;
while((idx = piece.indexOf("JOIN")) != -1) {
auto start = idx + 5;
auto i = start;
while(piece[i] != ' ' && piece[i] != '\n' && piece[i] != '\t' && piece[i] != ',')
i++;
auto end = i;
tableNames ~= strip(piece[start..end]);
piece = piece[end..$];
}
idx = sql.indexOf("FROM");
if(idx != -1) {
auto start = idx + 5;
auto i = start;
start = i;
while(i < sql.length && !(sql[i] > 'A' && sql[i] <= 'Z')) // if not uppercase, except for A (for AS) to avoid SQL keywords (hack)
i++;
auto from = sql[start..i];
auto pieces = from.split(",");
foreach(p; pieces) {
p = p.strip();
start = 0;
i = 0;
while(i < p.length && p[i] != ' ' && p[i] != '\n' && p[i] != '\t' && p[i] != ',')
i++;
tableNames ~= strip(p[start..i]);
}
string sqlToAdd;
foreach(tbl; tableNames) {
if(tbl.length) {
string keyName = "id";
if(tbl in keyMapping)
keyName = keyMapping[tbl];
sqlToAdd ~= ", " ~ tbl ~ "." ~ keyName ~ " AS " ~ "id_from_" ~ tbl;
}
}
sqlToAdd ~= " ";
sql = sql[0..idx] ~ sqlToAdd ~ sql[idx..$];
}
return sql;
}
/*
This is like a result set
DataObject res = [...];
res.name = "Something";
res.commit; // runs the actual update or insert
res = new DataObject(fields, tables
when doing a select, we need to figure out all the tables and modify the query to include the ids we need
search for FROM and JOIN
the next token is the table name
right before the FROM, add the ids of each table
given:
SELECT name, phone FROM customers LEFT JOIN phones ON customer.id = phones.cust_id
we want:
SELECT name, phone, customers.id AS id_from_customers, phones.id AS id_from_phones FROM customers LEFT JOIN phones ON customer.id[...];
*/
mixin template DataObjectConstructors() {
this(Database db, string[string] res, Tuple!(string, string)[string] mappings) {
super(db, res, mappings);
}
}
private string yield(string what) { return `if(auto result = dg(`~what~`)) return result;`; }
import std.typecons;
import std.json; // for json value making
class DataObject {
// lets you just free-form set fields, assuming they all come from the given table
// note it doesn't try to handle joins for new rows. you've gotta do that yourself
this(Database db, string table, UpdateOrInsertMode mode = UpdateOrInsertMode.CheckForMe) {
assert(db !is null);
this.db = db;
this.table = table;
this.mode = mode;
}
JSONValue makeJsonValue() {
JSONValue val;
JSONValue[string] valo;
//val.type = JSON_TYPE.OBJECT;
foreach(k, v; fields) {
JSONValue s;
//s.type = JSON_TYPE.STRING;
s.str = v;
valo[k] = s;
}
val = valo;
return val;
}
this(Database db, string[string] res, Tuple!(string, string)[string] mappings) {
this.db = db;
this.mappings = mappings;
this.fields = res;
mode = UpdateOrInsertMode.AlwaysUpdate;
}
string table;
// table, column [alias]
Tuple!(string, string)[string] mappings;
// value [field] [table]
string[string][string] multiTableKeys; // note this is not set internally tight now
// but it can be set manually to do multi table mappings for automatic update
string opDispatch(string field, string file = __FILE__, size_t line = __LINE__)()
if((field.length < 8 || field[0..8] != "id_from_") && field != "popFront")
{
if(field !in fields)
throw new Exception("no such field " ~ field, file, line);
return fields[field];
}
string opDispatch(string field, T)(T t)
if((field.length < 8 || field[0..8] != "id_from_") && field != "popFront")
{
static if(__traits(compiles, t is null)) {
if(t is null)
setImpl(field, null);
else
setImpl(field, to!string(t));
} else
setImpl(field, to!string(t));
return fields[field];
}