1 module microrm.schema;
2 
3 import microrm.util;
4 
5 /++ Create SQL for creating tables if not exists
6     Params:
7     Types = types of structs which will be a tables
8             name of struct -> name of table
9             name of field -> name of column
10  +/
11 auto buildSchema(Types...)()
12 {
13     import std.array : appender;
14     auto ret = appender!string;
15     foreach (T; Types)
16     {
17         T t;
18         static if (is(T == struct))
19         {
20             ret.put("CREATE TABLE IF NOT EXISTS ");
21             ret.put(tableName!T);
22             ret.put(" (\n");
23             foreach (i, f; t.tupleof)
24             {
25                 fieldToCol!(__traits(identifier, t.tupleof[i]),
26                           typeof(f))(ret);
27                 static if (i != t.tupleof.length-1)
28                     ret.put(",\n");
29             }
30             ret.put(");\n");
31         }
32         else static assert(0, "not supported non-struct type");
33     }
34     return ret.data;
35 }
36 
37 unittest
38 {
39     static struct Foo
40     {
41         ulong id;
42         float value;
43         ulong ts;
44     }
45 
46     static struct Bar
47     {
48         ulong id;
49         string text;
50         ulong ts;
51     }
52 
53     assert(buildSchema!(Foo, Bar) ==
54 `CREATE TABLE IF NOT EXISTS Foo (
55 id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
56 value REAL,
57 ts INTEGER NOT NULL);
58 CREATE TABLE IF NOT EXISTS Bar (
59 id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
60 text TEXT,
61 ts INTEGER NOT NULL);
62 `);
63 }