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 import std.algorithm : joiner; 15 auto ret = appender!string; 16 foreach (T; Types) 17 { 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 ret.put(fieldToCol!("",T)().joiner(",\n")); 24 ret.put(");\n"); 25 } 26 else static assert(0, "not supported non-struct type"); 27 } 28 return ret.data; 29 } 30 31 unittest 32 { 33 static struct Foo 34 { 35 ulong id; 36 float value; 37 ulong ts; 38 } 39 40 static struct Bar 41 { 42 ulong id; 43 string text; 44 ulong ts; 45 } 46 47 assert(buildSchema!(Foo, Bar) == 48 `CREATE TABLE IF NOT EXISTS Foo ( 49 'id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 50 'value' REAL, 51 'ts' INTEGER NOT NULL); 52 CREATE TABLE IF NOT EXISTS Bar ( 53 'id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 54 'text' TEXT, 55 'ts' INTEGER NOT NULL); 56 `); 57 }