Map rows to structs using Mapper
masterA Mapper is an optimized way to convert rows into a custom Zig struct T. It is significantly more efficient than using row.to with name-based mapping because it performs the name-to-index lookup only once.
Requirements:
- The query must be executed with
{.column_names = true}or thecolumn_namesbuild option must be set.
Mapping Rules:
- Columns with no matching field in the struct are ignored.
- Fields with no matching column are set to their default value. If no default is defined,
mapper.next()returnserror.FieldColumnMismatch.
Configuration Options (ToOpts):
dupe: Iftrue, string columns are duplicated using an internal arena. This allows non-scalar values to persist until therow/resultis deinitialized.allocator: An explicit allocator for duplicating non-scalar values. Setting this impliesdupe = true.map: Determines mapping strategy..ordinal(default) matches by position;.namematches by column name.
const User = struct {
id: i32,
name: []const u8,
};
var result = try conn.queryOpts("select id, name from users", .{}, .{.column_names = true});
defer result.deinit();
var mapper = result.mapper(User, .{});
while (try mapper.next()) |user| {
// use: user.id and user.name
}