Add generic helper functions for models which have the same table definition.

This commit is contained in:
Madeorsk 2024-10-17 19:08:39 +02:00
parent e2bce7e7a1
commit 650d2515be
Signed by: Madeorsk
GPG key ID: 677E51CA765BB79F
3 changed files with 33 additions and 2 deletions

29
src/helpers.zig Normal file
View file

@ -0,0 +1,29 @@
const std = @import("std");
/// Simple ModelFromSql and ModelToSql functions for models which have the same table definition.
pub fn TableModel(comptime Model: type, comptime TableShape: type) type {
// Get fields of the model, which must be the same as the table shape.
const fields = std.meta.fields(Model);
return struct {
/// Simply copy all fields from model to table.
pub fn copyModelToTable(_model: Model) !TableShape {
var _table: TableShape = undefined;
inline for (fields) |modelField| {
// Copy each field of the model to the table.
@field(_table, modelField.name) = @field(_model, modelField.name);
}
return _table;
}
/// Simply copy all fields from table to model.
pub fn copyTableToModel(_table: TableShape) !Model {
var _model: Model = undefined;
inline for (fields) |tableField| {
// Copy each field of the table to the model.
@field(_model, tableField.name) = @field(_table, tableField.name);
}
return _model;
}
};
}

View file

@ -17,3 +17,5 @@ pub const SqlParams = _sql.SqlParams;
pub const conditions = @import("conditions.zig"); pub const conditions = @import("conditions.zig");
pub const errors = @import("errors.zig"); pub const errors = @import("errors.zig");
pub const helpers = @import("helpers.zig");

View file

@ -66,8 +66,8 @@ const CompositeModelRepository = zrm.Repository(CompositeModel, CompositeModelTa
.key = &[_][]const u8{"firstcol", "secondcol"}, .key = &[_][]const u8{"firstcol", "secondcol"},
.fromSql = &modelFromSql, .fromSql = &zrm.helpers.TableModel(CompositeModel, CompositeModelTable).copyTableToModel,
.toSql = &modelToSql, .toSql = &zrm.helpers.TableModel(CompositeModel, CompositeModelTable).copyModelToTable,
}); });