From 650d2515be2756453d112c40bf81a4007f083d04 Mon Sep 17 00:00:00 2001 From: Madeorsk Date: Thu, 17 Oct 2024 19:08:39 +0200 Subject: [PATCH] Add generic helper functions for models which have the same table definition. --- src/helpers.zig | 29 +++++++++++++++++++++++++++++ src/root.zig | 2 ++ tests/composite.zig | 4 ++-- 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 src/helpers.zig diff --git a/src/helpers.zig b/src/helpers.zig new file mode 100644 index 0000000..3167db1 --- /dev/null +++ b/src/helpers.zig @@ -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; + } + }; +} diff --git a/src/root.zig b/src/root.zig index ba51afe..12e42c0 100644 --- a/src/root.zig +++ b/src/root.zig @@ -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"); diff --git a/tests/composite.zig b/tests/composite.zig index c1c316a..f5479f8 100644 --- a/tests/composite.zig +++ b/tests/composite.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, });