1 module utile.db;
2 import std, utile.except;
3 
4 public import utile.db.mysql, utile.db.sqlite;
5 
6 alias Blob = const(ubyte)[];
7 
8 unittest
9 {
10 	{
11 		scope db = new SQLite(null);
12 
13 		{
14 			Blob arr = [1, 2, 3];
15 
16 			auto res = db.queryOne!Blob(`select ?;`, arr);
17 
18 			assert(res == arr);
19 		}
20 
21 		{
22 			auto res = db.query!(uint, string)(`select ?, ?;`, 123, `hello`).array;
23 
24 			assert(res.equal(tuple(123, `hello`).only));
25 		}
26 
27 		{
28 			auto res = db.queryOne!uint(`select ?;`, 123);
29 
30 			assert(res == 123);
31 		}
32 	}
33 
34 	version (Utile_Mysql)
35 	{
36 		MySQL db;
37 
38 		auto res = db.query!(uint, string)(`select ?, ?;`, 123, `hello`);
39 		auto res2 = db.queryOne!uint(`select ?;`, 123);
40 	}
41 }
42 
43 package:
44 
45 mixin template DbBase()
46 {
47 	template query(T...)
48 	{
49 		auto query(A...)(string sql, A args)
50 		{
51 			auto stmt = prepare(sql);
52 			bind(stmt, args);
53 
54 			static if (T.length)
55 				return process!T(stmt);
56 			else
57 			{
58 				process(stmt);
59 				return tuple!(`affected`, `lastId`)(affected(stmt), lastId(stmt));
60 			}
61 		}
62 	}
63 
64 	template queryOne(T...)
65 	{
66 		auto queryOne(A...)(string sql, A args)
67 		{
68 			auto res = query!T(sql, args);
69 			res.empty && throwError(`query returned no rows`);
70 
71 			auto e = res.front;
72 
73 			res.popFront;
74 			res.empty || throwError(`query returned multiple rows`);
75 
76 			return e;
77 		}
78 	}
79 }