Add generic helper functions for models which have the same table definition.
This commit is contained in:
parent
cf3d0fbc2c
commit
5197cc1e9c
3 changed files with 33 additions and 2 deletions
29
src/helpers.zig
Normal file
29
src/helpers.zig
Normal 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;
|
||||
}
|
||||
};
|
||||
}
|
|
@ -17,3 +17,5 @@ pub const SqlParams = _sql.SqlParams;
|
|||
pub const conditions = @import("conditions.zig");
|
||||
|
||||
pub const errors = @import("errors.zig");
|
||||
|
||||
pub const helpers = @import("helpers.zig");
|
||||
|
|
|
@ -66,8 +66,8 @@ const CompositeModelRepository = zrm.Repository(CompositeModel, CompositeModelTa
|
|||
|
||||
.key = &[_][]const u8{"firstcol", "secondcol"},
|
||||
|
||||
.fromSql = &modelFromSql,
|
||||
.toSql = &modelToSql,
|
||||
.fromSql = &zrm.helpers.TableModel(CompositeModel, CompositeModelTable).copyTableToModel,
|
||||
.toSql = &zrm.helpers.TableModel(CompositeModel, CompositeModelTable).copyModelToTable,
|
||||
});
|
||||
|
||||
|
||||
|
|
Loading…
Reference in a new issue