Skip to content

How to serialize the query results into JSON? #5

@huaxk

Description

@huaxk

An error occurred when serializing the query results into JSON:

lib/std/json/stringify.zig:673:25: error: Unable to stringify type 'type'
                else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),

zig version is 0.14.0-dev.3062, the code is as follows:

const std = @import("std");
const jq = @import("jetquery");
const Schema = @import("Schema.zig");  // same as jetquery porject

const Repo = jq.Repo(.postgresql, Schema);

pub fn Query(comptime model: anytype) type {
    return jq.Query(.postgresql, Schema, model);
}

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer std.debug.assert(gpa.deinit() == .ok);
    const allocator = gpa.allocator();

    var repo = try Repo.loadConfig(
        allocator,
        .development,
        .{},
    );
    defer repo.deinit();

    const human = try Query(.Human).first(&repo);
    defer repo.free(human);

    const json = try std.json.stringifyAlloc(allocator, human, .{});
    defer allocator.free(json);
    std.debug.print("{s}", .{json});
}

The type of 'human' returned from query is: ?jetquery.Query.Statement(...).QueryResultType(), it should be an optional struct because QueryResultType() build a struct using the schema 'Human' model's fields.

@(typeInfo(@TypeOf(human)) return: @as(builtin.Type, .{ .optional = .{ .child = jetquery.Query.Statement(...).QueryResultType() } })

I don't know why it can't match the branche of '.optional' during the json serialization process.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions