Add InsertableStruct to define insertShapes more easily.

This commit is contained in:
Madeorsk 2024-10-17 18:34:49 +02:00
parent 26c854a39c
commit 9d0cc13b65
Signed by: Madeorsk
GPG key ID: 677E51CA765BB79F
3 changed files with 35 additions and 4 deletions

View file

@ -14,6 +14,36 @@ pub fn Insertable(comptime ValueType: type) type {
}; };
} }
/// Build an insertable structure type from a normal structure.
pub fn InsertableStruct(comptime StructType: type) type {
// Get type info of the given structure.
const typeInfo = @typeInfo(StructType);
// Initialize fields of the insertable struct.
var newFields: [typeInfo.Struct.fields.len]std.builtin.Type.StructField = undefined;
for (typeInfo.Struct.fields, &newFields) |field, *newField| {
// Create a new field for each field of the given struct.
const newFieldType = Insertable(field.type);
newField.* = std.builtin.Type.StructField{
.name = field.name,
.type = newFieldType,
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(newFieldType),
};
}
// Return the insertable structure type.
return @Type(std.builtin.Type{
.Struct = .{
.layout = .auto,
.decls = &[0]std.builtin.Type.Declaration{},
.fields = &newFields,
.is_tuple = false,
},
});
}
/// Repository insert query configuration structure. /// Repository insert query configuration structure.
pub fn RepositoryInsertConfiguration(comptime InsertShape: type) type { pub fn RepositoryInsertConfiguration(comptime InsertShape: type) type {
return struct { return struct {

View file

@ -10,6 +10,7 @@ pub const RepositoryConfiguration = repository.RepositoryConfiguration;
pub const RepositoryResult = repository.RepositoryResult; pub const RepositoryResult = repository.RepositoryResult;
pub const Insertable = insert.Insertable; pub const Insertable = insert.Insertable;
pub const InsertableStruct = insert.InsertableStruct;
pub const QueryParameter = _sql.QueryParameter; pub const QueryParameter = _sql.QueryParameter;
pub const SqlParams = _sql.SqlParams; pub const SqlParams = _sql.SqlParams;

View file

@ -59,10 +59,10 @@ const CompositeModelRepository = zrm.Repository(CompositeModel, CompositeModelTa
.table = "composite_models", .table = "composite_models",
// Insert shape used by default for inserts in the repository. // Insert shape used by default for inserts in the repository.
.insertShape = struct { .insertShape = zrm.InsertableStruct(struct {
secondcol: zrm.Insertable([]const u8), secondcol: []const u8,
label: zrm.Insertable([]const u8), label: []const u8,
}, }),
.key = &[_][]const u8{"firstcol", "secondcol"}, .key = &[_][]const u8{"firstcol", "secondcol"},