-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlpp11dv2.d
executable file
·63 lines (58 loc) · 1.81 KB
/
sqlpp11dv2.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
#!/usr/bin/env tdmd
import std.array : join;
import std.conv : to;
import std.format : format;
import std.algorithm : canFind, startsWith;
import std.exception : assertThrown, enforce;
/// sqlpp11dv2 - query builder with some templates
unittest {
// same unittest as before
alias QueryBuilder = QueryBuilderWithTemplates;
assert(
QueryBuilder
.select("foo", "bar")
.from("bazTable")
.where_equal("foo", "42".to!string)
== "select foo, bar from bazTable where foo='42'"
);
assert(
QueryBuilder
.select("foo", "bar")
.from("bazTable")
.where_equal("foo", 42.to!int)
== "select foo, bar from bazTable where foo='42'"
);
assert(
QueryBuilder
.select("foo", "bar")
.from("bazTable")
.where_equal("foo", true.to!bool)
== "select foo, bar from bazTable where foo='true'"
);
assertThrown!Exception(
QueryBuilder
.select("foo", "bar")
.where_equal("foo", "abc")
);
}
struct QueryBuilderWithTemplates {
static auto select(string[] fields...) {
return typeof(this)(format!"select %s"(fields.join(", ")));
}
auto from(string table) {
return append(format!" from %s"(table));
}
// could even check if T has some features like to!string-able
auto where_equal(T)(string field, T value) {
enforce(this.query.canFind("from"), format!"from clause missing in '%s'"(this.query));
return append(format!" where %s='%s'"(field, value));
}
// private stuff
const query = "";
@disable this();
this(string query) { this.query = query; }
alias query this;
private typeof(this) append(string newStuff) {
return typeof(this)(this.query ~ newStuff);
}
}