#Anytype(?) schema type defination

1 messages · Page 1 of 1 (latest)

normal galleon
#

im trying to make a db library. how can i define schema type? so i can give the exact schema to developer later and type-checking if needed. (sorry for my bad english btw)

willow nest
#

what do you mean by defining schema type? just pass a type?

normal galleon
# willow nest what do you mean by defining schema type? just pass a `type`?

i wrote something. but it has some issues. (im very new in zig)

(i used typescript highlighting below)

const std = @import("std");
const Io = std.Io;

const keyvalues: type = undefined;

const Database = struct {
    const Self = @This();

    schema: type,
    pub fn init(io: Io, allocator: std.mem.Allocator, schema: type) !Self {
        _ = io;
        _ = allocator;

        // how can i change type dynamically?
        // keyvalues = schema
        return Database{ .schema = schema };
    }

    pub fn set(key: []u8, value: anytype) !void {
        if (Self.schema[key] == null) {
            std.debug.print("not defined the \"{}\" key in schema", .{key});
        }

        keyvalues[key] = value;
        return keyvalues[key];
    }
};

test "basic init and set" {
    const schema = struct { foo: []u8 };

    var db = try Database.init(std.testing.io, std.testing.allocator, schema);
    try std.testing.expect(std.mem.eql([]u8, try db.set("foo", "123"), "123"));
}
willow nest
#

you don't change the type dynamically, the type has to be specified at compile time

#

so best you can have is

fn Database(schema: type) type {
  return struct {
    const Self = @This();
    pub fn init(...) !Self {
      // create database from `schema`
    }
  };
}
normal galleon
#

i tried the code you gave me. im getting the tuple declarations cannot contain declarations error on const Self = @This(); line.

willow nest
#

yeah... Zig is being stupid here,

fn Database(schema: type) type {
  return struct {
    const Self = @This();
    _: void,
    pub fn init(...) !Self {
      // create database from `schema`
    }
  };
}
#

it's just a dummy field to tell Zig this is not a tuple, you can remove it when you have actual fields in there

elfin leaf
#

Or it's just master where that works, idk

sweet mica