From ea9f199b29423de1dcb520c5c7fc7ad0793efdf1 Mon Sep 17 00:00:00 2001 From: "Adam D. Ruppe" Date: Sat, 15 Oct 2022 13:50:01 -0400 Subject: [PATCH] implement DBName override for table names only --- database_generation.d | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/database_generation.d b/database_generation.d index 0c80c65..729e05a 100644 --- a/database_generation.d +++ b/database_generation.d @@ -91,7 +91,7 @@ struct Serial { string generateCreateTableFor(alias O)() { - enum tableName = toTableName(O.stringof); + enum tableName = tableNameFor!O(toTableName(O.stringof)); string sql = "CREATE TABLE " ~ tableName ~ " ("; string postSql; bool outputtedPostSql = false; @@ -198,7 +198,7 @@ string generateCreateTableFor(alias O)() { } else addPostSql("PRIMARY KEY(" ~ memberName ~ ")"); } else static if(is(attr == ForeignKey!(to, sqlPolicy), alias to, string sqlPolicy)) { - string refTable = toTableName(__traits(parent, to).stringof); + string refTable = tableNameFor!(__traits(parent, to))(toTableName(__traits(parent, to).stringof)); string refField = to.stringof; addPostSql("FOREIGN KEY(" ~ memberName ~ ") REFERENCES "~refTable~"("~refField~(sqlPolicy.length ? ") " : ")") ~ sqlPolicy); } @@ -218,6 +218,13 @@ string generateCreateTableFor(alias O)() { return sql; } +string tableNameFor(T)(string def) { + foreach(attr; __traits(getAttributes, T)) + static if(is(typeof(attr) == DBName)) + def = attr.name; + return def; +} + string toTableName(string t) { return plural(50, beautify(t, '_', true)); } @@ -299,7 +306,7 @@ void save(O)(ref O t, Database db) { +/ void insert(O)(ref O t, Database db) { auto builder = new InsertBuilder; - builder.setTable(toTableName(O.stringof)); + builder.setTable(tableNameFor!O(toTableName(O.stringof))); static foreach(memberName; __traits(allMembers, O)) {{ alias member = __traits(getMember, O, memberName); @@ -338,7 +345,7 @@ void insert(O)(ref O t, Database db) { import std.conv; version(dbgenerate_sqlite) { builder.execute(db); - foreach(row; db.query("SELECT max(id) FROM " ~ toTableName(O.stringof))) + foreach(row; db.query("SELECT max(id) FROM " ~ tableNameFor!O(toTableName(O.stringof)))) t.id.value = to!int(row[0]); } else { static if (__traits(hasMember, O, "id")) @@ -382,7 +389,7 @@ auto find(alias T)(Database db, int id) { // if it is unique, return an individual item. // if not, return the array - foreach(record; db.query("SELECT * FROM " ~ toTableName(T.stringof) ~ " WHERE id = ?", id)) { + foreach(record; db.query("SELECT * FROM " ~ tableNameFor!T(toTableName(T.stringof)) ~ " WHERE id = ?", id)) { T t; populateFromDbRow(t, record); @@ -609,7 +616,7 @@ struct QueryBuilderHelper(T) { } QueryBuilderHelper!(T[]) from(T)() { - return QueryBuilderHelper!(T[])(toTableName(T.stringof)); + return QueryBuilderHelper!(T[])(tableNameFor!T(toTableName(T.stringof))); } /// ditto