Construct QueryTables from model list

This commit is contained in:
jaina heartles 2022-08-03 22:08:32 -07:00
parent f28046bd79
commit ee4aa9e826

View file

@ -4,6 +4,22 @@ const util = @import("util");
const String = []const u8;
const comptimePrint = std.fmt.comptimePrint;
fn baseTypeName(comptime T: type) []const u8 {
comptime {
const name = @typeName(T);
const start = for (name) |_, i| {
if (name[name.len - i] == '.') break name.len - i;
} else 0;
return name[start..];
}
}
fn tableName(comptime T: type) String {
return util.case.pascalToSnake(baseTypeName(T));
}
// Represents a table bound to an identifier in a sql query
pub const QueryTable = struct {
Model: type,
as: String,
@ -15,6 +31,17 @@ pub const QueryTable = struct {
}
};
fn makeQueryTable(comptime Model: type, comptime table_index: usize) QueryTable {
return .{
.Model = Model,
.as = comptimePrint("{s}_{}", .{ tableName(Model), table_index }),
};
}
pub fn queryTables(comptime models: []const type) *const [models.len]QueryTable {
return map(type, QueryTable, models, makeQueryTable);
}
test "QueryTable.field" {
const tbl = QueryTable{
.Model = struct { id: i32 },
@ -24,6 +51,24 @@ test "QueryTable.field" {
try std.testing.expectEqualStrings("my_type.id", tbl.field(.id));
}
test "queryTables constructor" {
const MyTable = struct { id: i64 };
const MyOtherTable = struct { val: i64 };
const qt = queryTables(&.{ MyTable, MyOtherTable });
try std.testing.expectEqual(MyTable, qt[0].Model);
try std.testing.expectEqual(MyOtherTable, qt[1].Model);
try std.testing.expectEqualStrings("my_table_0", qt[0].as);
try std.testing.expectEqualStrings("my_other_table_1", qt[1].as);
}
fn map(comptime T: type, comptime R: type, comptime vals: []const T, comptime func: fn (T, usize) R) *const [vals.len]R {
var result: [vals.len]R = undefined;
for (vals) |v, i| result[i] = func(v, i);
return &result;
}
// Combines an array/tuple of strings into a single string, with a copy of
// joiner in between each one
fn join(comptime vals: []const String, comptime joiner: String) String {