From 466ac4c5e4d97bbdfbbea185c48b15aa3be9a370 Mon Sep 17 00:00:00 2001 From: Steffen Siering Date: Sat, 22 Jun 2024 19:54:39 +0200 Subject: [PATCH] pgsys module (#67) Requires: #65 With this change we split the C include and the `pgzx` into 2 modules: - `pgzx_pgsys`: C includes and some custom C helpers - `pgzx`: High level Zig utilities and abstractions. The split is to prepare for code generation support. When generating Zig code on the fly the generated code is imported as a module into `pgzx`, but we also want the generated code to depend on the C includes. By splitting out the C support we can have the generated module import `pgsys` as a module dependency itself. The change follows the pattern in https://github.com/ziglang/zig/blob/master/test/standalone/dep_triangle/build.zig We still re-export `pgsys` under `pgzx.c`. Within `pgzx` we replace `const c = @import(...)` with `const pg = @import("pgzx_pgsys");`. Now Postgres API usage is always prefixed with `pg.*` instead of `c.*`, which is also more consistent on how we use the namespaces ourselves and in the example extensions. --- build.zig | 43 +++++-- src/pgzx.zig | 2 +- src/pgzx/bgworker.zig | 27 ++--- src/pgzx/collections/dlist.zig | 68 ++++++------ src/pgzx/collections/htab.zig | 87 ++++++++------- src/pgzx/collections/list.zig | 108 +++++++++--------- src/pgzx/collections/slist.zig | 40 +++---- src/pgzx/datum.zig | 83 +++++++------- src/pgzx/elog.zig | 66 +++++------ src/pgzx/err.zig | 33 +++--- src/pgzx/fdw.zig | 3 +- src/pgzx/fmgr.zig | 25 +++-- src/pgzx/fmgr/args.zig | 24 ++-- src/pgzx/interrupts.zig | 35 +++--- src/pgzx/lwlock.zig | 8 +- src/pgzx/mem.zig | 96 ++++++++-------- src/pgzx/pq.zig | 197 +++++++++++++++++---------------- src/pgzx/pq/conv.zig | 30 ++--- src/pgzx/pq/params.zig | 2 +- src/pgzx/shmem.zig | 14 +-- src/pgzx/spi.zig | 57 +++++----- src/pgzx/testing.zig | 3 +- src/pgzx/utils/guc.zig | 36 +++--- src/pgzx/varatt.zig | 46 ++++---- 24 files changed, 583 insertions(+), 550 deletions(-) diff --git a/build.zig b/build.zig index 6e07942..31ad47d 100644 --- a/build.zig +++ b/build.zig @@ -18,17 +18,28 @@ pub fn build(b: *std.Build) void { docs.dependOn(&build_docs.step); } - // Reusable modules - const pgzx = blk: { - const module = b.addModule("pgzx", .{ - .root_source_file = b.path("./src/pgzx.zig"), + // pgzx_pgsys module: C bindings to Postgres + const pgzx_pgsys = blk: { + const module = b.addModule("pgzx_pgsys", .{ + .root_source_file = b.path("./src/pgzx/c.zig"), .target = target, .optimize = optimize, }); + + // Internal C headers module.addIncludePath(b.path("./src/pgzx/c/include/")); + + // Postgres Headers module.addIncludePath(.{ .cwd_relative = pgbuild.getIncludeServerDir(), }); + module.addIncludePath(.{ + .cwd_relative = pgbuild.getIncludeDir(), + }); + module.addLibraryPath(.{ + .cwd_relative = pgbuild.getLibDir(), + }); + // libpq support module.addCSourceFiles(.{ .files = &[_][]const u8{ @@ -39,17 +50,24 @@ pub fn build(b: *std.Build) void { "-I", pgbuild.getIncludeServerDir(), }, }); - module.addIncludePath(.{ - .cwd_relative = pgbuild.getIncludeDir(), - }); - module.addLibraryPath(.{ - .cwd_relative = pgbuild.getLibDir(), - }); module.linkSystemLibrary("pq", .{}); break :blk module; }; + // pgzx: main project module. + // This module re-exports pgzx_pgsys, other generated modules, and utility functions. + const pgzx = blk: { + const module = b.addModule("pgzx", .{ + .root_source_file = b.path("./src/pgzx.zig"), + .target = target, + .optimize = optimize, + }); + module.addImport("pgzx_pgsys", pgzx_pgsys); + + break :blk module; + }; + // Unit test extension const test_ext = blk: { const test_options = b.addOptions(); @@ -63,9 +81,12 @@ pub fn build(b: *std.Build) void { .link_libc = true, .link_allow_shlib_undefined = true, }); + tests.lib.root_module.addOptions("build_options", test_options); + tests.lib.root_module.addIncludePath(b.path("./src/pgzx/c/include/")); + + tests.lib.root_module.addImport("pgzx_pgsys", pgzx_pgsys); tests.lib.root_module.addImport("pgzx", pgzx); - tests.lib.root_module.addOptions("build_options", test_options); break :blk tests; }; diff --git a/src/pgzx.zig b/src/pgzx.zig index eef6eb1..19507b1 100644 --- a/src/pgzx.zig +++ b/src/pgzx.zig @@ -6,7 +6,7 @@ const std = @import("std"); // Export common set of postgres headers. -pub const c = @import("pgzx/c.zig"); +pub const c = @import("pgzx_pgsys"); // Utility functions for working with the PostgreSQL C API. pub const bgworker = @import("pgzx/bgworker.zig"); diff --git a/src/pgzx/bgworker.zig b/src/pgzx/bgworker.zig index 57befd6..9ecbfff 100644 --- a/src/pgzx/bgworker.zig +++ b/src/pgzx/bgworker.zig @@ -1,21 +1,22 @@ const std = @import("std"); const pgzx = @import("../pgzx.zig"); -const c = @import("c.zig"); +const pg = pgzx.c; + const elog = @import("elog.zig"); const err = @import("err.zig"); const lwlock = @import("lwlock.zig"); -pub const BackgroundWorker = c.BackgroundWorker; +pub const BackgroundWorker = pg.BackgroundWorker; pub const WorkerOptions = struct { flags: c_int, worker_type: ?[]const u8 = null, - start_time: c.BgWorkerStartTime = c.BgWorkerStart_RecoveryFinished, + start_time: pg.BgWorkerStartTime = pg.BgWorkerStart_RecoveryFinished, restart_time: c_int = 1, - main_arg: c.Datum = 0, + main_arg: pg.Datum = 0, extra: ?[]const u8 = null, - notify_pid: c.pid_t = 0, + notify_pid: pg.pid_t = 0, }; pub fn register( @@ -25,7 +26,7 @@ pub fn register( options: WorkerOptions, ) void { var bw = initBackgroundWorker(name, library_name, function_name, options); - c.RegisterBackgroundWorker(&bw); + pg.RegisterBackgroundWorker(&bw); } pub fn registerDynamic( @@ -33,7 +34,7 @@ pub fn registerDynamic( comptime library_name: []const u8, comptime function_name: []const u8, options: WorkerOptions, -) !*c.BackgroundWorkerHandle { +) !*pg.BackgroundWorkerHandle { std.log.debug("init background worker: {s} {s} {s}", .{ name, library_name, @@ -47,8 +48,8 @@ pub fn registerDynamic( library_name, function_name, }); - var handle: ?*c.BackgroundWorkerHandle = null; - const ok = c.RegisterDynamicBackgroundWorker(&bw, &handle); + var handle: ?*pg.BackgroundWorkerHandle = null; + const ok = pg.RegisterDynamicBackgroundWorker(&bw, &handle); if (!ok) { return err.PGError.FailStartBackgroundWorker; } @@ -66,8 +67,8 @@ fn initBackgroundWorker( comptime library_name: []const u8, comptime function_name: []const u8, options: WorkerOptions, -) c.BackgroundWorker { - var bw = std.mem.zeroInit(c.BackgroundWorker, .{ +) pg.BackgroundWorker { + var bw = std.mem.zeroInit(pg.BackgroundWorker, .{ .bgw_flags = options.flags, .bgw_start_time = options.start_time, .bgw_restart_time = options.restart_time, @@ -110,8 +111,8 @@ pub inline fn sigFlagHandler(sig: *pgzx.intr.Signal) fn (c_int) callconv(.C) voi pub fn finalizeSignal(arg: c_int) void { _ = arg; const save_errno = std.c._errno().*; - if (c.MyProc != null) { - c.SetLatch(&c.MyProc.*.procLatch); + if (pg.MyProc != null) { + pg.SetLatch(&pg.MyProc.*.procLatch); } std.c._errno().* = save_errno; } diff --git a/src/pgzx/collections/dlist.zig b/src/pgzx/collections/dlist.zig index a9ce2b1..4bb1af6 100644 --- a/src/pgzx/collections/dlist.zig +++ b/src/pgzx/collections/dlist.zig @@ -1,9 +1,9 @@ //! Postgres intrusive double linked list support. const std = @import("std"); -const c = @import("../c.zig"); +const pg = @import("pgzx_pgsys"); -fn initNode() c.dlist_node { +fn initNode() pg.dlist_node { return .{ .prev = null, .next = null }; } @@ -14,7 +14,7 @@ pub fn DList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type pub const Iterator = DListIter(T, node_field); pub const descr = DListDescr(T, node_field); - list: c.dlist_head, + list: pg.dlist_head, pub inline fn init() Self { return .{ .list = .{ .head = initNode() } }; @@ -22,7 +22,7 @@ pub fn DList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type inline fn ensureInit(self: *Self) void { if (self.list.head.next == null) { - c.dlist_init(&self.list); + pg.dlist_init(&self.list); } } @@ -42,7 +42,7 @@ pub fn DList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type // The elemenst in `other` must be of type T and the same member node // must have been used to insert the elements into `other`. // - pub inline fn appendFromDList(self: *Self, other: *c.dlist_head) void { + pub inline fn appendFromDList(self: *Self, other: *pg.dlist_head) void { appendDList(&self.list, other); } @@ -54,7 +54,7 @@ pub fn DList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type // // The `other` list must be compatible with the current list. The // element type and the node members must match the type of Self. - pub inline fn appendToDList(self: *const Self, other: *c.dlist_head) void { + pub inline fn appendToDList(self: *const Self, other: *pg.dlist_head) void { appendDList(other, &self.list); } @@ -69,7 +69,7 @@ pub fn DList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type } } - pub inline fn rawList(self: *Self) *c.dlist_head { + pub inline fn rawList(self: *Self) *pg.dlist_head { return &self.list; } @@ -81,14 +81,14 @@ pub fn DList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type } pub inline fn isEmpty(self: *const Self) bool { - return c.dlist_is_empty(&self.list); + return pg.dlist_is_empty(&self.list); } pub inline fn headNode(self: *const Self) *T { if (self.isEmpty()) { @panic("headNode on empty list"); } - const node = c.dlist_head_node(@constCast(&self.list)); + const node = pg.dlist_head_node(@constCast(&self.list)); return descr.nodeParentPtr(node.?); } @@ -96,48 +96,48 @@ pub fn DList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type if (self.isEmpty()) { @panic("tailNode on empty list"); } - const node = c.dlist_tail_node(@constCast(&self.list)); + const node = pg.dlist_tail_node(@constCast(&self.list)); return descr.nodeParentPtr(node.?); } pub inline fn pushHead(self: *Self, node: *T) void { - c.dlist_push_head(&self.list, descr.nodePtr(node)); + pg.dlist_push_head(&self.list, descr.nodePtr(node)); } pub inline fn pushTail(self: *Self, node: *T) void { - c.dlist_push_tail(&self.list, descr.nodePtr(node)); + pg.dlist_push_tail(&self.list, descr.nodePtr(node)); } pub inline fn popHead(self: *Self) *T { if (self.isEmpty()) { @panic("popHead on empty list"); } - return descr.nodeParentPtr(c.dlist_pop_head_node(&self.list)); + return descr.nodeParentPtr(pg.dlist_pop_head_node(&self.list)); } pub inline fn popTail(self: *Self) *T { if (self.isEmpty()) { @panic("popTail on empty list"); } - const tail = c.dlist_tail_node(&self.list); - c.dlist_delete(tail); + const tail = pg.dlist_tail_node(&self.list); + pg.dlist_delete(tail); return descr.nodeParentPtr(tail.?); } pub inline fn moveHead(self: *Self, node: *T) void { - c.dlist_move_head(&self.list, descr.nodePtr(node)); + pg.dlist_move_head(&self.list, descr.nodePtr(node)); } pub inline fn moveTail(self: *Self, node: *T) void { - c.dlist_move_tail(&self.list, descr.nodePtr(node)); + pg.dlist_move_tail(&self.list, descr.nodePtr(node)); } pub inline fn nextNode(self: *const Self, node: *T) *T { - return descr.nodeParentPtr(c.dlist_next_node(&self.list, descr.nodePtr(node))); + return descr.nodeParentPtr(pg.dlist_next_node(&self.list, descr.nodePtr(node))); } pub inline fn prevNode(self: *const Self, node: *T) *T { - return descr.nodeParentPtr(c.dlist_prev_node(&self.list, descr.nodePtr(node))); + return descr.nodeParentPtr(pg.dlist_prev_node(&self.list, descr.nodePtr(node))); } pub inline fn iterator(self: *const Self) Iterator { @@ -145,33 +145,33 @@ pub fn DList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type } pub inline fn insertAfter(node: *T, new_node: *T) void { - c.dlist_insert_after(descr.nodePtr(node), descr.nodePtr(new_node)); + pg.dlist_insert_after(descr.nodePtr(node), descr.nodePtr(new_node)); } pub inline fn insertBefore(node: *T, new_node: *T) void { - c.dlist_insert_before(descr.nodePtr(node), descr.nodePtr(new_node)); + pg.dlist_insert_before(descr.nodePtr(node), descr.nodePtr(new_node)); } pub inline fn delete(node: *T) void { - c.dlist_delete(descr.nodePtr(node)); + pg.dlist_delete(descr.nodePtr(node)); } pub inline fn deleteThorougly(node: *T) void { - c.dlist_delete_thoroughly(descr.nodePtr(node)); + pg.dlist_delete_thoroughly(descr.nodePtr(node)); } pub inline fn isDetached(node: *T) bool { - return c.dlist_is_detached(descr.nodePtr(node)); + return pg.dlist_is_detached(descr.nodePtr(node)); } }; } -fn appendDList(to: *c.dlist_head, from: *c.dlist_head) void { - if (c.dlist_is_empty(from)) { +fn appendDList(to: *pg.dlist_head, from: *pg.dlist_head) void { + if (pg.dlist_is_empty(from)) { return; } if (to.head.next == null) { - c.dlist_init(to); + pg.dlist_init(to); } to.*.head.prev.*.next = from.*.head.next; @@ -179,7 +179,7 @@ fn appendDList(to: *c.dlist_head, from: *c.dlist_head) void { from.*.head.prev.*.next = &to.*.head; to.*.head.prev = from.*.head.prev; - c.dlist_init(from); + pg.dlist_init(from); } fn DListIter(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type { @@ -188,9 +188,9 @@ fn DListIter(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type const descr = DListDescr(T, node_field); - iter: c.dlist_iter, + iter: pg.dlist_iter, - pub fn init(list: *const c.dlist_head) Self { + pub fn init(list: *const pg.dlist_head) Self { const end = &list.head; return .{ .iter = .{ @@ -216,15 +216,15 @@ pub fn DListDescr(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) return struct { const node = std.meta.fieldInfo(T, node_field).name; - pub inline fn nodePtr(v: *T) *c.dlist_node { + pub inline fn nodePtr(v: *T) *pg.dlist_node { return &@field(v, node); } - pub inline fn nodeParentPtr(n: *c.dlist_node) *T { + pub inline fn nodeParentPtr(n: *pg.dlist_node) *T { return @fieldParentPtr(node, n); } - pub inline fn optNodeParentPtr(n: ?*c.dlist_node) ?*T { + pub inline fn optNodeParentPtr(n: ?*pg.dlist_node) ?*T { return if (n) |p| nodeParentPtr(p) else null; } }; @@ -235,7 +235,7 @@ pub const TestSuite_DList = struct { const T = struct { value: u32, - node: c.dlist_node = initNode(), + node: pg.dlist_node = initNode(), }; pub fn testEmpty() !void { diff --git a/src/pgzx/collections/htab.zig b/src/pgzx/collections/htab.zig index 5773c90..ba0bbb0 100644 --- a/src/pgzx/collections/htab.zig +++ b/src/pgzx/collections/htab.zig @@ -6,7 +6,8 @@ const std = @import("std"); -const c = @import("../c.zig"); +const pg = @import("pgzx_pgsys"); + const err = @import("../err.zig"); const meta = @import("../meta.zig"); @@ -14,12 +15,12 @@ const meta = @import("../meta.zig"); const HashValueFunc = union(enum) { Strings, Blobs, - Func: c.HashValueFunc, + Func: pg.HashValueFunc, }; const DirConfig = struct { init_size: isize, // (initial) directory size - max_dsize: isize = c.NO_MAX_DSIZE, // limit to dsize if dir size is limited + max_dsize: isize = pg.NO_MAX_DSIZE, // limit to dsize if dir size is limited }; /// HTab is a type safe wrapper around the Postgres HTAB hash table API. @@ -27,7 +28,7 @@ const DirConfig = struct { /// Initialize the `keysize` to match the field size of your Entry's key type. pub fn HTab(comptime Context: type) type { return struct { - htab: *c.HTAB, + htab: *pg.HTAB, pub const Entry = Context.Entry; pub const Key = Context.Key; @@ -53,23 +54,23 @@ pub fn HTab(comptime Context: type) type { segment_size: ?usize = null, // # entries in a segment dir: ?DirConfig = null, // directory size and max size hash: HashValueFunc = Context.DefaultHash, // hash function - match: c.HashCompareFunc = null, // key comparison function - keycopy: c.HashCopyFunc = null, // key copying function - alloc: c.HashAllocFunc = null, // memory allocator - memctx: c.MemoryContext = null, // memory context to use for allocations + match: pg.HashCompareFunc = null, // key comparison function + keycopy: pg.HashCopyFunc = null, // key copying function + alloc: pg.HashAllocFunc = null, // memory allocator + memctx: pg.MemoryContext = null, // memory context to use for allocations pub fn getSharedSize(self: Options) usize { const hctl = self.initHashCtl(); const flags = self.initFlags(); - return c.hash_get_shared_size(&hctl, flags); + return pg.hash_get_shared_size(&hctl, flags); } - pub fn initHashCtl(self: Options) c.HASHCTL { + pub fn initHashCtl(self: Options) pg.HASHCTL { return .{ .num_partitions = @intCast(self.num_partitions orelse 0), .ssize = @intCast(self.segment_size orelse 0), .dsize = @intCast(if (self.dir) |d| d.init_size else 0), - .max_dsize = @intCast(if (self.dir) |d| d.max_dsize else c.NO_MAX_DSIZE), + .max_dsize = @intCast(if (self.dir) |d| d.max_dsize else pg.NO_MAX_DSIZE), .keysize = @intCast(if (self.keysize) |k| k else Context.keySize()), .entrysize = @intCast(if (self.entrysize) |e| e else Context.entrySize()), .hash = if (self.hash == .Func) self.hash.Func else null, @@ -82,19 +83,19 @@ pub fn HTab(comptime Context: type) type { } pub fn initFlags(self: Options) c_int { - var flags: c_int = c.HASH_ELEM; - flags |= if (self.num_partitions != null) c.HASH_PARTITION else 0; - flags |= if (self.segment_size != null) c.HASH_SEGMENT else 0; - flags |= if (self.dir != null) c.HASH_DIRSIZE else 0; + var flags: c_int = pg.HASH_ELEM; + flags |= if (self.num_partitions != null) pg.HASH_PARTITION else 0; + flags |= if (self.segment_size != null) pg.HASH_SEGMENT else 0; + flags |= if (self.dir != null) pg.HASH_DIRSIZE else 0; flags |= switch (self.hash) { - .Strings => c.HASH_STRINGS, - .Blobs => c.HASH_BLOBS, - .Func => c.HASH_FUNCTION, + .Strings => pg.HASH_STRINGS, + .Blobs => pg.HASH_BLOBS, + .Func => pg.HASH_FUNCTION, }; - flags |= if (self.match != null) c.HASH_COMPARE else 0; - flags |= if (self.keycopy != null) c.HASH_KEYCOPY else 0; - flags |= if (self.alloc != null) c.HASH_ALLOC else 0; - flags |= if (self.memctx != null) c.HASH_CONTEXT else 0; + flags |= if (self.match != null) pg.HASH_COMPARE else 0; + flags |= if (self.keycopy != null) pg.HASH_KEYCOPY else 0; + flags |= if (self.alloc != null) pg.HASH_ALLOC else 0; + flags |= if (self.memctx != null) pg.HASH_CONTEXT else 0; return flags; } }; @@ -103,7 +104,7 @@ pub fn HTab(comptime Context: type) type { const hctl = options.initHashCtl(); const flags = options.initFlags(); - const created = try err.wrap(c.hash_create, .{ name, @as(c_long, @intCast(nelem)), &hctl, flags }); + const created = try err.wrap(pg.hash_create, .{ name, @as(c_long, @intCast(nelem)), &hctl, flags }); return Self.initFrom(created.?); } @@ -113,7 +114,7 @@ pub fn HTab(comptime Context: type) type { pub inline fn initShmem(name: [:0]const u8, init_size: usize, max_size: usize, options: Options) !Self { const hctl = options.initHashCtl(); const flags = options.initFlags(); - const created = try err.wrap(c.ShmemInitHash, .{ + const created = try err.wrap(pg.ShmemInitHash, .{ name, @as(c_long, @intCast(init_size)), @as(c_long, @intCast(max_size)), @@ -124,37 +125,37 @@ pub fn HTab(comptime Context: type) type { } // Initialize from an existing hash table pointer. - pub inline fn initFrom(htable: *c.HTAB) Self { + pub inline fn initFrom(htable: *pg.HTAB) Self { return .{ .htab = htable }; } pub inline fn deinit(self: Self) void { - c.hash_destroy(self.htab); + pg.hash_destroy(self.htab); } - pub fn asPtr(self: Self) *c.HTAB { + pub fn asPtr(self: Self) *pg.HTAB { return self.htab; } pub fn freeze(self: Self) void { - c.hash_freeze(self.htab); + pg.hash_freeze(self.htab); } /// Compute the hash value for a given key. pub fn getHashValue(self: Self, key: ConstKeyPtr) u32 { - return c.get_hash_value(self.htab, key); + return pg.get_hash_value(self.htab, key); } pub fn count(self: Self) usize { - return @intCast(c.hash_get_num_entries(self.htab)); + return @intCast(pg.hash_get_num_entries(self.htab)); } pub fn getRawEntryPointer(self: Self, key: ?*const anyopaque, found: ?*bool) ?*anyopaque { - return c.hash_search(self.htab, key, c.HASH_FIND, found); + return pg.hash_search(self.htab, key, pg.HASH_FIND, found); } pub fn getOrPutRawEntryPointer(self: Self, key: ?*const anyopaque, found: ?*bool) error{OutOfMemory}!?*anyopaque { - const p = c.hash_search(self.htab, key, c.HASH_ENTER_NULL, found); + const p = pg.hash_search(self.htab, key, pg.HASH_ENTER_NULL, found); if (p == null) { return error.OutOfMemory; } @@ -191,7 +192,7 @@ pub fn HTab(comptime Context: type) type { pub fn remove(self: Self, key: ConstKeyPtr) bool { var found: bool = undefined; - _ = c.hash_search(self.htab, Self.keyPtr(key), c.HASH_REMOVE, &found); + _ = pg.hash_search(self.htab, Self.keyPtr(key), pg.HASH_REMOVE, &found); return found; } @@ -245,11 +246,11 @@ pub fn HTab(comptime Context: type) type { // In case the iteration is not full exhausted, it should be terminated with `term`. pub fn HTabIter(comptime Context: type) type { return struct { - status: c.HASH_SEQ_STATUS, + status: pg.HASH_SEQ_STATUS, const Self = @This(); - pub fn init(htab: *c.HTAB) Self { + pub fn init(htab: *pg.HTAB) Self { // SAFETY: // The status type is initialized by the hash_seq_init function only. // It only holds a pointer into HTAB but is not self referential @@ -257,8 +258,8 @@ pub fn HTabIter(comptime Context: type) type { // // It is safe to move the 'status', but it SHOULD NOT be copied. // If the hash table is not frozen Postgres keeps track - var status: c.HASH_SEQ_STATUS = undefined; - c.hash_seq_init(&status, htab); + var status: pg.HASH_SEQ_STATUS = undefined; + pg.hash_seq_init(&status, htab); return .{ .status = status }; } @@ -271,7 +272,7 @@ pub fn HTabIter(comptime Context: type) type { // scans in Postgres, which eventually resuls in an error being thrown // either now, or by some other iteration. pub fn term(self: *Self) void { - c.hash_seq_term(&self.status); + pg.hash_seq_term(&self.status); } // Get the pointer to the next entry in the hash table. @@ -279,7 +280,7 @@ pub fn HTabIter(comptime Context: type) type { // Returns null if the iteration is done. The iterator is automatically // terminated in this case and one must not use the `term` method. pub fn next(self: *Self) ?*Context.Entry { - const p = c.hash_seq_search(&self.status); + const p = pg.hash_seq_search(&self.status); if (p == null) { return null; } @@ -294,7 +295,7 @@ pub fn HTabValuesIter(comptime Context: type) type { pub const Self = @This(); - pub fn init(htab: *c.HTAB) Self { + pub fn init(htab: *pg.HTAB) Self { return .{ .iter = HTabIter(Context).init(htab) }; } @@ -310,7 +311,7 @@ pub fn HTabValuesIter(comptime Context: type) type { } pub const StringKeyOptions = struct { - max_str_len: usize = c.NAMEDATALEN, + max_str_len: usize = pg.NAMEDATALEN, }; // Create a hash table with string keys. The key is stored in a fixed size array in the hash table entry. Use `max_str_len` to configure the maximum supported string length. @@ -501,7 +502,7 @@ pub const TestSuite_HTab = struct { // std.log.debug("strcmp: a=({*})'{s}', b='{s}', sz={}", .{ a, str_a, str_b, sz }); // std.log.debug("strcmp: a={any}, b={any}", .{ str_a, str_b }); - return c.strncmp(str_a, str_b, sz); + return pg.strncmp(str_a, str_b, sz); } fn strcpy(to: ?*anyopaque, from: ?*const anyopaque, sz: usize) callconv(.C) ?*anyopaque { @@ -511,7 +512,7 @@ pub const TestSuite_HTab = struct { // const str_from = std.mem.span(char_ptr_from); // std.log.debug("strcpy: to={*}, from='{s}', sz={}", .{ to, str_from, sz }); - _ = c.strlcpy(char_ptr_to, char_ptr_from, @intCast(sz)); + _ = pg.strlcpy(char_ptr_to, char_ptr_from, @intCast(sz)); return to; } }; diff --git a/src/pgzx/collections/list.zig b/src/pgzx/collections/list.zig index 904bd04..cad7ee7 100644 --- a/src/pgzx/collections/list.zig +++ b/src/pgzx/collections/list.zig @@ -1,4 +1,4 @@ -const c = @import("../c.zig"); +const pg = @import("pgzx_pgsys"); // Wrapper for postgres lists. // @@ -12,15 +12,15 @@ pub fn PointerListOf(comptime T: type) type { const Iterator = IteratorOf(T); const ReverseIterator = ReverseIteratorOf(T); - list: ?*c.List, + list: ?*pg.List, pub fn init() Self { return Self.initFrom(null); } - pub fn initFrom(from: ?*c.List) Self { + pub fn initFrom(from: ?*pg.List) Self { if (from) |l| { - if (l.type != c.T_List) { + if (l.type != pg.T_List) { @panic("Expected a pointer list"); } } @@ -28,23 +28,23 @@ pub fn PointerListOf(comptime T: type) type { } pub fn init1(v: *T) Self { - return Self.initFrom(c.list_make1_impl( - c.T_List, + return Self.initFrom(pg.list_make1_impl( + pg.T_List, .{ .ptr_value = v }, )); } pub fn init2(v1: *T, v2: *T) Self { - return Self.initFrom(c.list_make2_impl( - c.T_List, + return Self.initFrom(pg.list_make2_impl( + pg.T_List, .{ .ptr_value = v1 }, .{ .ptr_value = v2 }, )); } pub fn init3(v1: *T, v2: *T, v3: *T) Self { - return Self.initFrom(c.list_make3_impl( - c.T_List, + return Self.initFrom(pg.list_make3_impl( + pg.T_List, .{ .ptr_value = v1 }, .{ .ptr_value = v2 }, .{ .ptr_value = v3 }, @@ -52,8 +52,8 @@ pub fn PointerListOf(comptime T: type) type { } pub fn init4(v1: *T, v2: *T, v3: *T, v4: *T) Self { - return Self.initFrom(c.list_make4_impl( - c.T_List, + return Self.initFrom(pg.list_make4_impl( + pg.T_List, .{ .ptr_value = v1 }, .{ .ptr_value = v2 }, .{ .ptr_value = v3 }, @@ -62,8 +62,8 @@ pub fn PointerListOf(comptime T: type) type { } pub fn init5(v1: *T, v2: *T, v3: *T, v4: *T, v5: *T) Self { - return Self.initFrom(c.list_make5_impl( - c.T_List, + return Self.initFrom(pg.list_make5_impl( + pg.T_List, .{ .ptr_value = v1 }, .{ .ptr_value = v2 }, .{ .ptr_value = v3 }, @@ -73,156 +73,156 @@ pub fn PointerListOf(comptime T: type) type { } pub fn deinit(self: Self) void { - c.list_free(self.list); + pg.list_free(self.list); } pub fn deinitDeep(self: Self) void { - c.list_free_deep(self.list); + pg.list_free_deep(self.list); } - pub fn rawList(self: Self) ?*c.List { + pub fn rawList(self: Self) ?*pg.List { return self.list; } pub fn copy(self: Self) Self { - return Self.initFrom(c.list_copy(self.list)); + return Self.initFrom(pg.list_copy(self.list)); } pub fn copyDeep(self: Self) Self { - return Self.initFrom(c.list_copy_deep(self.list)); + return Self.initFrom(pg.list_copy_deep(self.list)); } pub fn sort(self: Self, cmp: fn (?*T, ?*T) c_int) void { - c.list_sort(self.list, struct { - fn c_cmp(a: [*c]c.ListCell, b: [*c]c.ListCell) c_int { - const ptrA: ?*T = @ptrCast(@alignCast(c.lfirst(a))); - const ptrB: ?*T = @ptrCast(@alignCast(c.lfirst(b))); + pg.list_sort(self.list, struct { + fn c_cmp(a: [*c]pg.ListCell, b: [*c]pg.ListCell) c_int { + const ptrA: ?*T = @ptrCast(@alignCast(pg.lfirst(a))); + const ptrB: ?*T = @ptrCast(@alignCast(pg.lfirst(b))); return cmp(ptrA, ptrB); } }.c_cmp); } pub fn len(self: Self) usize { - return c.list_length(self.list); + return pg.list_length(self.list); } pub fn iterator(self: Self) Iterator { return Iterator.init(self.list); } - pub fn iteratorFrom(from: ?*c.List) Iterator { + pub fn iteratorFrom(from: ?*pg.List) Iterator { return Self.initFrom(from).iterator(); } pub fn append(self: *Self, value: *T) void { - var list: ?*c.List = self.list; - list = c.lappend(list, value); + var list: ?*pg.List = self.list; + list = pg.lappend(list, value); self.list = list; } pub fn concatUnique(self: *Self, other: Self) void { - self.list = c.list_concat_unique(self.list, other.list); + self.list = pg.list_concat_unique(self.list, other.list); } pub fn concatUniquePtr(self: *Self, other: Self) void { - self.list = c.list_concat_unique_ptr(self.list, other.list); + self.list = pg.list_concat_unique_ptr(self.list, other.list); } pub fn reverseIterator(self: Self) ReverseIterator { return ReverseIterator.init(self.list); } - pub fn reverseIteratorFrom(from: ?*c.List) ReverseIterator { + pub fn reverseIteratorFrom(from: ?*pg.List) ReverseIterator { return Self.initFrom(from).reverseIterator(); } pub fn member(self: Self, value: *T) bool { - return c.list_member(self.list, value); + return pg.list_member(self.list, value); } pub fn memberPtr(self: Self, value: *T) bool { - return c.list_member_ptr(self.list, value); + return pg.list_member_ptr(self.list, value); } pub fn deleteNth(self: *Self, n: usize) void { if (n >= self.len()) { @panic("Index out of bounds"); } - self.list = c.list_delete_nth(self.list, @intCast(n)); + self.list = pg.list_delete_nth(self.list, @intCast(n)); } pub fn deleteFirst(self: *Self) void { - self.list = c.list_delete_first(self.list); + self.list = pg.list_delete_first(self.list); } pub fn deleteFirstN(self: *Self, n: usize) void { - self.list = c.list_delete_first_n(self.list, @intCast(n)); + self.list = pg.list_delete_first_n(self.list, @intCast(n)); } pub fn deleteLast(self: *Self) void { - self.list = c.list_delete_last(self.list); + self.list = pg.list_delete_last(self.list); } pub fn delete(self: *Self, value: *T) void { - self.list = c.list_delete(self.list, value); + self.list = pg.list_delete(self.list, value); } pub fn deletePointer(self: *Self, value: *T) void { - self.list = c.list_delete_ptr(self.list, value); + self.list = pg.list_delete_ptr(self.list, value); } pub fn createUnion(self: Self, other: *Self) Self { - return Self.initFrom(c.list_union(self.list, other.list)); + return Self.initFrom(pg.list_union(self.list, other.list)); } pub fn createUnionPtr(self: Self, other: Self) Self { - return Self.initFrom(c.list_union_ptr(self.list, other.list)); + return Self.initFrom(pg.list_union_ptr(self.list, other.list)); } pub fn createIntersection(self: Self, other: Self) Self { - return Self.initFrom(c.list_intersection(self.list, other.list)); + return Self.initFrom(pg.list_intersection(self.list, other.list)); } pub fn createIntersectionPtr(self: Self, other: Self) Self { - return Self.initFrom(c.list_intersection_ptr(self.list, other.list)); + return Self.initFrom(pg.list_intersection_ptr(self.list, other.list)); } pub fn createDifference(self: Self, other: Self) Self { - return Self.initFrom(c.list_difference(self.list, other.list)); + return Self.initFrom(pg.list_difference(self.list, other.list)); } pub fn createDifferencePtr(self: Self, other: Self) Self { - return Self.initFrom(c.list_difference_ptr(self.list, other.list)); + return Self.initFrom(pg.list_difference_ptr(self.list, other.list)); } }; } pub fn IteratorOf(comptime T: type) type { - return IteratorOfWith(T, c.list_head, c.lnext); + return IteratorOfWith(T, pg.list_head, pg.lnext); } pub fn ReverseIteratorOf(comptime T: type) type { - return IteratorOfWith(T, c.list_last_cell, lprev); + return IteratorOfWith(T, pg.list_last_cell, lprev); } -fn lprev(list: *c.List, cell: *c.ListCell) ?*c.ListCell { - const idx = c.list_cell_number(list, cell); +fn lprev(list: *pg.List, cell: *pg.ListCell) ?*pg.ListCell { + const idx = pg.list_cell_number(list, cell); if (idx <= 0) { return null; } - return c.list_nth_cell(list, idx - 1); + return pg.list_nth_cell(list, idx - 1); } fn IteratorOfWith(comptime T: type, comptime fn_init: anytype, comptime fn_next: anytype) type { return struct { - list: *c.List, - cell: ?*c.ListCell, + list: *pg.List, + cell: ?*pg.ListCell, const Self = @This(); - pub fn init(list: ?*c.List) Self { + pub fn init(list: ?*pg.List) Self { if (list) |l| { - if (l.type != c.T_List) { + if (l.type != pg.T_List) { @panic("Expected a pointer list"); } return Self{ .list = l, .cell = fn_init(l) }; @@ -235,7 +235,7 @@ fn IteratorOfWith(comptime T: type, comptime fn_init: anytype, comptime fn_next: pub fn next(self: *Self) ??*T { if (self.cell) |cell| { self.cell = fn_next(self.list, cell); - const value: ?*T = @ptrCast(@alignCast(c.lfirst(cell))); + const value: ?*T = @ptrCast(@alignCast(pg.lfirst(cell))); return value; } return null; diff --git a/src/pgzx/collections/slist.zig b/src/pgzx/collections/slist.zig index d441ef9..fd42b35 100644 --- a/src/pgzx/collections/slist.zig +++ b/src/pgzx/collections/slist.zig @@ -2,9 +2,9 @@ const std = @import("std"); -const c = @import("../c.zig"); +const pg = @import("pgzx_pgsys"); -fn initNode() c.slist_node { +fn initNode() pg.slist_node { return .{ .next = null }; } @@ -15,15 +15,15 @@ pub fn SList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type usingnamespace SListMeta(T, node_field); - head: c.slist_head, + head: pg.slist_head, pub inline fn init() Self { var h = Self{ .head = undefined }; - c.slist_init(&h.head); + pg.slist_init(&h.head); return h; } - pub inline fn initWith(init_head: c.slist_head) Self { + pub inline fn initWith(init_head: pg.slist_head) Self { return Self{ .head = init_head }; } @@ -34,20 +34,20 @@ pub fn SList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type } pub inline fn isEmpty(self: Self) bool { - return c.slist_is_empty(&self.head); + return pg.slist_is_empty(&self.head); } pub inline fn pushHead(self: *Self, v: *T) void { - c.slist_push_head(&self.head, Self.nodePtr(v)); + pg.slist_push_head(&self.head, Self.nodePtr(v)); } pub inline fn popHead(self: *Self) ?*T { - const node_ptr = c.slist_pop_head_node(&self.head); + const node_ptr = pg.slist_pop_head_node(&self.head); return Self.optNodeParentPtr(node_ptr); } pub inline fn headNode(self: Self) ?*T { - const node_ptr = c.slist_head_node(@constCast(&self.head)); + const node_ptr = pg.slist_head_node(@constCast(&self.head)); return Self.optNodeParentPtr(node_ptr); } @@ -57,13 +57,13 @@ pub fn SList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type const next_ptr = self.head.head.next.*.next; if (next_ptr == null) return null; - var new_head: c.slist_head = undefined; + var new_head: pg.slist_head = undefined; new_head.head.next = next_ptr; return Self.initWith(new_head); } pub inline fn insertAfter(prev: *T, v: *T) void { - c.slist_insert_after(Self.nodePtr(prev), Self.nodePtr(v)); + pg.slist_insert_after(Self.nodePtr(prev), Self.nodePtr(v)); } pub inline fn hasNext(v: *T) bool { @@ -71,12 +71,12 @@ pub fn SList(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type } pub inline fn next(v: *T) ?*T { - const node_ptr = c.slist_next(Self.nodePtr(v)); + const node_ptr = pg.slist_next(Self.nodePtr(v)); return Self.optNodeParentPtr(node_ptr); } pub inline fn iterator(self: *Self) Iterator { - var i: c.slist_iter = undefined; + var i: pg.slist_iter = undefined; i.cur = self.head.head.next; return .{ .iter = i }; } @@ -88,7 +88,7 @@ pub fn SListIter(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) t const Self = @This(); usingnamespace SListMeta(T, node_field); - iter: c.slist_iter, + iter: pg.slist_iter, pub inline fn next(self: *Self) ?*T { if (self.iter.cur == null) return null; @@ -103,15 +103,15 @@ fn SListMeta(comptime T: type, comptime node_field: std.meta.FieldEnum(T)) type return struct { const node = std.meta.fieldInfo(T, node_field).name; - inline fn nodePtr(v: *T) *c.slist_node { + inline fn nodePtr(v: *T) *pg.slist_node { return &@field(v, node); } - inline fn nodeParentPtr(n: *c.slist_node) ?*T { + inline fn nodeParentPtr(n: *pg.slist_node) ?*T { return @fieldParentPtr(node, n); } - inline fn optNodeParentPtr(n: ?*c.slist_node) ?*T { + inline fn optNodeParentPtr(n: ?*pg.slist_node) ?*T { return if (n) |p| nodeParentPtr(p) else null; } }; @@ -121,7 +121,7 @@ pub const TestSuite_SList = struct { pub fn testEmpty() !void { const T = struct { value: u32, - node: c.slist_node, + node: pg.slist_node, }; const MyList = SList(T, .node); @@ -138,7 +138,7 @@ pub const TestSuite_SList = struct { pub fn testPush() !void { const T = struct { value: u32, - node: c.slist_node = .{ .next = null }, + node: pg.slist_node = .{ .next = null }, }; const MyListT = SList(T, .node); @@ -165,7 +165,7 @@ pub const TestSuite_SList = struct { pub fn testPop() !void { const T = struct { value: u32, - node: c.slist_node = .{ .next = null }, + node: pg.slist_node = .{ .next = null }, }; const MyListT = SList(T, .node); diff --git a/src/pgzx/datum.zig b/src/pgzx/datum.zig index 5d1bf6e..81177d4 100644 --- a/src/pgzx/datum.zig +++ b/src/pgzx/datum.zig @@ -1,6 +1,7 @@ const std = @import("std"); -const c = @import("c.zig"); +const pg = @import("pgzx_pgsys"); + const err = @import("err.zig"); const mem = @import("mem.zig"); const meta = @import("meta.zig"); @@ -9,13 +10,13 @@ const varatt = @import("varatt.zig"); pub fn Conv(comptime T: type, comptime from: anytype, comptime to: anytype) type { return struct { pub const Type = T; - pub fn fromNullableDatum(d: c.NullableDatum) !Type { + pub fn fromNullableDatum(d: pg.NullableDatum) !Type { if (d.isnull) { return err.PGError.UnexpectedNullValue; } return try from(d.value); } - pub fn toNullableDatum(v: Type) !c.NullableDatum { + pub fn toNullableDatum(v: Type) !pg.NullableDatum { return .{ .value = try to(v), .isnull = false, @@ -27,13 +28,13 @@ pub fn Conv(comptime T: type, comptime from: anytype, comptime to: anytype) type pub fn ConvNoFail(comptime T: type, comptime from: anytype, comptime to: anytype) type { return struct { pub const Type = T; - pub fn fromNullableDatum(d: c.NullableDatum) !T { + pub fn fromNullableDatum(d: pg.NullableDatum) !T { if (d.isnull) { return err.PGError.UnexpectedNullValue; } return from(d.value); } - pub fn toNullableDatum(v: T) !c.NullableDatum { + pub fn toNullableDatum(v: T) !pg.NullableDatum { return .{ .value = to(v), .isnull = false, @@ -46,13 +47,13 @@ pub fn ConvNoFail(comptime T: type, comptime from: anytype, comptime to: anytype pub fn OptConv(comptime C: anytype) type { return struct { pub const Type = ?C.Type; - pub fn fromNullableDatum(d: c.NullableDatum) !Type { + pub fn fromNullableDatum(d: pg.NullableDatum) !Type { if (d.isnull) { return null; } return try C.fromNullableDatum(d); } - pub fn toNullableDatum(v: Type) !c.NullableDatum { + pub fn toNullableDatum(v: Type) !pg.NullableDatum { if (v) |value| { return try C.toNullableDatum(value); } else { @@ -69,19 +70,19 @@ pub fn OptConv(comptime C: anytype) type { /// This allows us find to return pre-defined converters besides relying on /// reflection only. var directMappings = .{ - .{ c.Datum, PGDatum }, - .{ c.NullableDatum, PGNullableDatum }, + .{ pg.Datum, PGDatum }, + .{ pg.NullableDatum, PGNullableDatum }, }; -pub fn fromNullableDatum(comptime T: type, d: c.NullableDatum) !T { +pub fn fromNullableDatum(comptime T: type, d: pg.NullableDatum) !T { return findConv(T).fromNullableDatum(d); } -pub fn fromDatum(comptime T: type, d: c.Datum, is_null: bool) !T { +pub fn fromDatum(comptime T: type, d: pg.Datum, is_null: bool) !T { return findConv(T).fromNullableDatum(.{ .value = d, .isnull = is_null }); } -pub fn toNullableDatum(v: anytype) !c.NullableDatum { +pub fn toNullableDatum(v: anytype) !pg.NullableDatum { return findConv(@TypeOf(v)).toNullableDatum(v); } @@ -143,8 +144,8 @@ pub fn findConv(comptime T: type) type { inline fn isConv(comptime T: type) bool { // we require T to be a struct with the following fields: // Type: type - // fromDatum: fn(d: c.Datum) !Type - // toDatum: fn(v: Type) !c.Datum + // fromDatum: fn(d: pg.Datum) !Type + // toDatum: fn(v: Type) !pg.Datum if (@typeInfo(T) != .Struct) { return false; @@ -155,28 +156,28 @@ inline fn isConv(comptime T: type) bool { } pub const Void = ConvNoFail(void, idDatum, toVoid); -pub const Bool = ConvNoFail(bool, c.DatumGetBool, c.BoolGetDatum); -pub const Int8 = ConvNoFail(i8, datumGetInt8, c.Int8GetDatum); -pub const Int16 = ConvNoFail(i16, c.DatumGetInt16, c.Int16GetDatum); -pub const Int32 = ConvNoFail(i32, c.DatumGetInt32, c.Int32GetDatum); -pub const Int64 = ConvNoFail(i64, c.DatumGetInt64, c.Int64GetDatum); -pub const UInt8 = ConvNoFail(u8, c.DatumGetUInt8, c.UInt8GetDatum); -pub const UInt16 = ConvNoFail(u16, c.DatumGetUInt16, c.UInt16GetDatum); -pub const UInt32 = ConvNoFail(u32, c.DatumGetUInt32, c.UInt32GetDatum); -pub const UInt64 = ConvNoFail(u64, c.DatumGetUInt64, c.UInt64GetDatum); -pub const Float32 = ConvNoFail(f32, c.DatumGetFloat4, c.Float4GetDatum); -pub const Float64 = ConvNoFail(f64, c.DatumGetFloat8, c.Float8GetDatum); +pub const Bool = ConvNoFail(bool, pg.DatumGetBool, pg.BoolGetDatum); +pub const Int8 = ConvNoFail(i8, datumGetInt8, pg.Int8GetDatum); +pub const Int16 = ConvNoFail(i16, pg.DatumGetInt16, pg.Int16GetDatum); +pub const Int32 = ConvNoFail(i32, pg.DatumGetInt32, pg.Int32GetDatum); +pub const Int64 = ConvNoFail(i64, pg.DatumGetInt64, pg.Int64GetDatum); +pub const UInt8 = ConvNoFail(u8, pg.DatumGetUInt8, pg.UInt8GetDatum); +pub const UInt16 = ConvNoFail(u16, pg.DatumGetUInt16, pg.UInt16GetDatum); +pub const UInt32 = ConvNoFail(u32, pg.DatumGetUInt32, pg.UInt32GetDatum); +pub const UInt64 = ConvNoFail(u64, pg.DatumGetUInt64, pg.UInt64GetDatum); +pub const Float32 = ConvNoFail(f32, pg.DatumGetFloat4, pg.Float4GetDatum); +pub const Float64 = ConvNoFail(f64, pg.DatumGetFloat8, pg.Float8GetDatum); pub const SliceU8 = Conv([]const u8, getDatumTextSlice, sliceToDatumText); pub const SliceU8Z = Conv([:0]const u8, getDatumTextSliceZ, sliceToDatumTextZ); -pub const PGDatum = ConvNoFail(c.Datum, idDatum, idDatum); +pub const PGDatum = ConvNoFail(pg.Datum, idDatum, idDatum); const PGNullableDatum = struct { - pub const Type = c.NullableDatum; - pub fn fromNullableDatum(d: c.NullableDatum) !Type { + pub const Type = pg.NullableDatum; + pub fn fromNullableDatum(d: pg.NullableDatum) !Type { return d; } - pub fn toNullableDatum(v: Type) !c.NullableDatum { + pub fn toNullableDatum(v: Type) !pg.NullableDatum { return v; } }; @@ -185,47 +186,47 @@ const PGNullableDatum = struct { // TODO: conversion decorator for jsonb decoding/encoding types -fn idDatum(d: c.Datum) c.Datum { +fn idDatum(d: pg.Datum) pg.Datum { return d; } -fn toVoid(d: void) c.Datum { +fn toVoid(d: void) pg.Datum { _ = d; return 0; } -fn datumGetInt8(d: c.Datum) i8 { +fn datumGetInt8(d: pg.Datum) i8 { return @as(i8, @bitCast(@as(i8, @truncate(d)))); } /// Convert a datum to a TEXT slice. This function detoast the datum if necessary. /// All allocations will be performed in the Current Memory Context. -pub fn getDatumTextSlice(datum: c.Datum) ![]const u8 { +pub fn getDatumTextSlice(datum: pg.Datum) ![]const u8 { return getDatumTextSliceZ(datum); } /// Convert a datum to a TEXT slice. This function detoast the datum if necessary. /// All allocations will be performed in the Current Memory Context. /// -pub fn getDatumTextSliceZ(datum: c.Datum) ![:0]const u8 { - const ptr = c.DatumGetTextPP(datum); +pub fn getDatumTextSliceZ(datum: pg.Datum) ![:0]const u8 { + const ptr = pg.DatumGetTextPP(datum); - const unpacked = try err.wrap(c.pg_detoast_datum_packed, .{ptr}); + const unpacked = try err.wrap(pg.pg_detoast_datum_packed, .{ptr}); const len = varatt.VARSIZE_ANY_EXHDR(unpacked); var buffer = try mem.PGCurrentContextAllocator.alloc(u8, len + 1); std.mem.copyForwards(u8, buffer, varatt.VARDATA_ANY(unpacked)[0..len]); buffer[len] = 0; if (unpacked != ptr) { - c.pfree(unpacked); + pg.pfree(unpacked); } return buffer[0..len :0]; } -pub inline fn sliceToDatumText(slice: []const u8) !c.Datum { - const text = c.cstring_to_text_with_len(slice.ptr, @intCast(slice.len)); - return c.PointerGetDatum(text); +pub inline fn sliceToDatumText(slice: []const u8) !pg.Datum { + const text = pg.cstring_to_text_with_len(slice.ptr, @intCast(slice.len)); + return pg.PointerGetDatum(text); } -pub inline fn sliceToDatumTextZ(slice: [:0]const u8) !c.Datum { +pub inline fn sliceToDatumTextZ(slice: [:0]const u8) !pg.Datum { return sliceToDatumText(slice); } diff --git a/src/pgzx/elog.zig b/src/pgzx/elog.zig index 46d11dd..93bdae6 100644 --- a/src/pgzx/elog.zig +++ b/src/pgzx/elog.zig @@ -1,7 +1,9 @@ const std = @import("std"); + +const pg = @import("pgzx_pgsys"); + const err = @import("err.zig"); const mem = @import("mem.zig"); -const c = @import("c.zig"); const SourceLocation = std.builtin.SourceLocation; @@ -27,8 +29,8 @@ pub fn throwAsPostgresError(src: SourceLocation, e: anyerror) noreturn { switch (e) { errset.PGErrorStack => err.pgRethrow(), - errset.OutOfMemory => Report.init(src, c.ERROR).pgRaise(.{ - .code = c.ERRCODE_OUT_OF_MEMORY, + errset.OutOfMemory => Report.init(src, pg.ERROR).pgRaise(.{ + .code = pg.ERRCODE_OUT_OF_MEMORY, .message = "Not enough memory", }), else => |leftover_err| { @@ -36,8 +38,8 @@ pub fn throwAsPostgresError(src: SourceLocation, e: anyerror) noreturn { var buf: [1024]u8 = undefined; const msg = std.fmt.bufPrintZ(buf[0..], "Unexpected error: {s}", .{@errorName(leftover_err)}) catch unexpected; - Report.init(src, c.ERROR).pgRaise(.{ - .code = c.ERRCODE_INTERNAL_ERROR, + Report.init(src, pg.ERROR).pgRaise(.{ + .code = pg.ERRCODE_INTERNAL_ERROR, .message = msg, }); }, @@ -53,7 +55,7 @@ pub fn isPostgresError(e: anyerror) bool { /// Provide support to integrate std.log with Postgres elog. pub var options: struct { - postgresLogFnLeven: c_int = c.LOG_SERVER_ONLY, + postgresLogFnLeven: c_int = pg.LOG_SERVER_ONLY, } = .{}; pub fn logFn( @@ -75,7 +77,7 @@ pub fn logFn( const src = std.mem.zeroInit(SourceLocation, .{}); Report.init(src, options.postgresLogFnLeven).raise(.{ - .code = c.ERRCODE_INTERNAL_ERROR, + .code = pg.ERRCODE_INTERNAL_ERROR, .message = buf.items[0 .. buf.items.len - 1 :0], }) catch {}; } @@ -84,7 +86,7 @@ pub fn logFn( /// /// Messages using `LOG` are send to the server by default. pub fn Log(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { - sendElog(src, c.LOG, fmt, args); + sendElog(src, pg.LOG, fmt, args); } /// Use PostgreSQL elog to log a formatted message using the `LOG` level. @@ -92,14 +94,14 @@ pub fn Log(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { /// Append the error name to the error message or emit the top message from the /// error stack if cause == PGErrorStack. pub fn LogWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []const u8, args: anytype) void { - sendElogWithCause(src, c.LOG, cause, fmt, args); + sendElogWithCause(src, pg.LOG, cause, fmt, args); } /// Use PostgreSQL elog to log a formatted message using the `LOG` level. /// /// Similar to `Log`, but message is never send to clients. pub fn LogServerOnly(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { - sendElog(src, c.LOG_SERVER_ONLY, fmt, args); + sendElog(src, pg.LOG_SERVER_ONLY, fmt, args); } /// Use PostgreSQL elog to log a formatted message using the `LOG` level. @@ -109,12 +111,12 @@ pub fn LogServerOnly(src: SourceLocation, comptime fmt: []const u8, args: anytyp /// Append the error name to the error message or emit the top message from the /// error stack if cause == PGErrorStack. pub fn LogServerOnlyWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []const u8, args: anytype) void { - sendElogWithCause(src, c.LOG_SERVER_ONLY, cause, fmt, args); + sendElogWithCause(src, pg.LOG_SERVER_ONLY, cause, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Info` level. pub fn Info(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { - sendElog(src, c.INFO, fmt, args); + sendElog(src, pg.INFO, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Info` level. @@ -122,12 +124,12 @@ pub fn Info(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { /// Append the error name to the error message or emit the top message from the /// error stack if cause == PGErrorStack. pub fn InfoWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []const u8, args: anytype) void { - sendElogWithCause(src, c.INFO, cause, fmt, args); + sendElogWithCause(src, pg.INFO, cause, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Notice` level. pub fn Notice(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { - sendElog(src, c.NOTICE, fmt, args); + sendElog(src, pg.NOTICE, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Notice` level. @@ -135,12 +137,12 @@ pub fn Notice(src: SourceLocation, comptime fmt: []const u8, args: anytype) void /// Append the error name to the error message or emit the top message from the /// error stack if cause == PGErrorStack. pub fn NoticeWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []const u8, args: anytype) void { - sendElogWithCause(src, c.NOTICE, cause, fmt, args); + sendElogWithCause(src, pg.NOTICE, cause, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Warning` level. pub fn Warning(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { - sendElog(src, c.WARNING, fmt, args); + sendElog(src, pg.WARNING, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Warning` level. @@ -148,12 +150,12 @@ pub fn Warning(src: SourceLocation, comptime fmt: []const u8, args: anytype) voi /// Append the error name to the error message or emit the top message from the /// error stack if cause == PGErrorStack. pub fn WarningWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []const u8, args: anytype) void { - sendElogWithCause(src, c.WARNING, cause, fmt, args); + sendElogWithCause(src, pg.WARNING, cause, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `PGWARNING` level. pub fn PGWarning(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { - sendElog(src, c.PGWARNING, fmt, args); + sendElog(src, pg.PGWARNING, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `PGWARNING` level. @@ -161,7 +163,7 @@ pub fn PGWarning(src: SourceLocation, comptime fmt: []const u8, args: anytype) v /// Append the error name to the error message or emit the top message from the /// error stack if cause == PGErrorStack. pub fn PGWarningWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []const u8, args: anytype) void { - sendElogWithCause(src, c.PGWARNING, cause, fmt, args); + sendElogWithCause(src, pg.PGWARNING, cause, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Error` level. @@ -169,7 +171,7 @@ pub fn PGWarningWithCause(src: SourceLocation, cause: anyerror, comptime fmt: [] /// Warning: /// Using Error will cause Postgres to throw an error by using `longjump`. pub fn ErrorThrow(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { - sendElog(src, c.ERROR, fmt, args); + sendElog(src, pg.ERROR, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Error` level. @@ -180,7 +182,7 @@ pub fn ErrorThrow(src: SourceLocation, comptime fmt: []const u8, args: anytype) /// Warning: /// Using Error will cause Postgres to throw an error by using `longjump`. pub fn ErrorThrowWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []const u8, args: anytype) void { - sendElogWithCause(src, c.ERROR, cause, fmt, args); + sendElogWithCause(src, pg.ERROR, cause, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Error` level. @@ -192,7 +194,7 @@ pub fn Error(src: SourceLocation, comptime fmt: []const u8, args: anytype) error var errctx = err.Context.init(); defer errctx.pg_try_end(); if (errctx.pg_try()) { - sendElog(src, c.ERROR, fmt, args); + sendElog(src, pg.ERROR, fmt, args); unreachable; } else { return error.PGErrorStack; @@ -207,7 +209,7 @@ pub fn ErrorWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []cons var errctx = err.Context.init(); defer errctx.pg_try_end(); if (errctx.pg_try()) { - sendElogWithCause(src, c.ERROR, cause, fmt, args); + sendElogWithCause(src, pg.ERROR, cause, fmt, args); unreachable; } else { return error.PGErrorStack; @@ -217,7 +219,7 @@ pub fn ErrorWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []cons /// Use PostgreSQL elog to log a formatted message at `Fatal` level. /// This will cause Postgres to kill the current process. pub fn Fatal(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { - sendElog(src, c.FATAL, fmt, args); + sendElog(src, pg.FATAL, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `Fatal` level. @@ -226,14 +228,14 @@ pub fn Fatal(src: SourceLocation, comptime fmt: []const u8, args: anytype) void /// Append the error name to the error message or emit the top message from the /// error stack if cause == PGErrorStack. pub fn FatalWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []const u8, args: anytype) void { - sendElogWithCause(src, c.FATAL, cause, fmt, args); + sendElogWithCause(src, pg.FATAL, cause, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `PANIC` level. /// /// This will cause Postgres to stop the cluster. pub fn Panic(src: SourceLocation, comptime fmt: []const u8, args: anytype) void { - sendElog(src, c.PANIC, fmt, args); + sendElog(src, pg.PANIC, fmt, args); } /// Use PostgreSQL elog to log a formatted message at `PANIC` level. @@ -243,7 +245,7 @@ pub fn Panic(src: SourceLocation, comptime fmt: []const u8, args: anytype) void /// /// This will cause Postgres to stop the cluster. pub fn PanicWithCause(src: SourceLocation, cause: anyerror, comptime fmt: []const u8, args: anytype) void { - sendElogWithCause(src, c.PANIC, cause, fmt, args); + sendElogWithCause(src, pg.PANIC, cause, fmt, args); } /// Emit an error log. Returns the error as Zig error if the error level is @@ -263,7 +265,7 @@ pub fn pgRaise(src: SourceLocation, level: c_int, details: Details) void { pub fn emitIfPGError(e: anyerror) bool { if (e == error.PGErrorStack) { - c.EmitErrorReport(); + pg.EmitErrorReport(); return true; } return false; @@ -393,11 +395,11 @@ pub const Report = struct { /// the error must be rethrown (see [pgRethrow]) or cleaned up (see [FlushErrorState]). pub fn pgRaise(self: Self, details: Details) void { var data = self.init_err_data(details); - c.ThrowErrorData(&data); + pg.ThrowErrorData(&data); } - inline fn init_err_data(self: Self, details: Details) c.ErrorData { - return std.mem.zeroInit(c.ErrorData, .{ + inline fn init_err_data(self: Self, details: Details) pg.ErrorData { + return std.mem.zeroInit(pg.ErrorData, .{ .elevel = self.level, .sqlerrcode = details.code orelse 0, .message = if (details.message) |m| @constCast(m.ptr) else null, @@ -409,7 +411,7 @@ pub const Report = struct { .filename = self.src.file, .lineno = @as(c_int, @intCast(self.src.line)), .funcname = self.src.fn_name, - .assoc_context = c.CurrentMemoryContext, + .assoc_context = pg.CurrentMemoryContext, }); } }; diff --git a/src/pgzx/err.zig b/src/pgzx/err.zig index f028bf4..62d1860 100644 --- a/src/pgzx/err.zig +++ b/src/pgzx/err.zig @@ -1,6 +1,7 @@ const std = @import("std"); -const c = @import("c.zig"); +const pg = @import("pgzx_pgsys"); + const mem = @import("mem.zig"); pub const PGError = error{ @@ -43,8 +44,8 @@ pub fn pgRethrow() callconv(.C) void { // ErrorContext when calling longjmp. // Because we did restore the memory context we want to make sure that we // set it back to ErrorContext before we rethrow the error - _ = c.MemoryContextSwitchTo(c.ErrorContext); - c.PG_RE_THROW(); + _ = pg.MemoryContextSwitchTo(pg.ErrorContext); + pg.PG_RE_THROW(); } /// Capture the postgres error context when calling into postgres functions. @@ -97,17 +98,17 @@ pub fn pgRethrow() callconv(.C) void { /// } /// pub const Context = struct { - exception_stack: [*c]c.sigjmp_buf, - context_stack: [*c]c.ErrorContextCallback, - memory_context: c.MemoryContext, - local_sigjump_buf: c.sigjmp_buf, + exception_stack: [*c]pg.sigjmp_buf, + context_stack: [*c]pg.ErrorContextCallback, + memory_context: pg.MemoryContext, + local_sigjump_buf: pg.sigjmp_buf, const Self = @This(); pub fn init() Self { return .{ - .exception_stack = c.PG_exception_stack, - .context_stack = c.error_context_stack, - .memory_context = c.CurrentMemoryContext, + .exception_stack = pg.PG_exception_stack, + .context_stack = pg.error_context_stack, + .memory_context = pg.CurrentMemoryContext, .local_sigjump_buf = undefined, }; } @@ -123,8 +124,8 @@ pub const Context = struct { /// within a function as we do here. By forcing the function to be inline /// the `sigsetjmp` happens correctly within the stack context of the caller. pub inline fn pg_try(self: *Self) bool { - if (c.sigsetjmp(&self.local_sigjump_buf, 0) == 0) { - c.PG_exception_stack = &self.local_sigjump_buf; + if (pg.sigsetjmp(&self.local_sigjump_buf, 0) == 0) { + pg.PG_exception_stack = &self.local_sigjump_buf; return true; } else { return false; @@ -138,16 +139,16 @@ pub const Context = struct { /// Restore the error context to the state before `pg_try` was called. pub fn pg_try_end(self: *Self) void { - c.PG_exception_stack = self.exception_stack; - c.error_context_stack = self.context_stack; - _ = c.MemoryContextSwitchTo(self.memory_context); + pg.PG_exception_stack = self.exception_stack; + pg.error_context_stack = self.context_stack; + _ = pg.MemoryContextSwitchTo(self.memory_context); } /// Error handler to ignore the postgres error. /// The error stack with pending error messages will be cleaned up. pub fn ignore_err(self: *Self) void { _ = self; - c.FlushErrorState(); + pg.FlushErrorState(); } /// Turn a postgres longjmp based error into a zig error. diff --git a/src/pgzx/fdw.zig b/src/pgzx/fdw.zig index cdff08e..a0de082 100644 --- a/src/pgzx/fdw.zig +++ b/src/pgzx/fdw.zig @@ -1,9 +1,10 @@ const std = @import("std"); +const pg = @import("pgzx_pgsys"); + const elog = @import("elog.zig"); const mem = @import("mem.zig"); const collections = @import("collections.zig"); -const pg = @import("c.zig"); pub const DefElem = pg.DefElem; diff --git a/src/pgzx/fmgr.zig b/src/pgzx/fmgr.zig index d04d443..a7c5cb4 100644 --- a/src/pgzx/fmgr.zig +++ b/src/pgzx/fmgr.zig @@ -1,15 +1,16 @@ const std = @import("std"); -const c = @import("c.zig"); +const pg = @import("pgzx_pgsys"); + const elog = @import("elog.zig"); const datum = @import("datum.zig"); const meta = @import("meta.zig"); pub const args = @import("fmgr/args.zig"); -pub const varatt = c.varatt; +pub const varatt = pg.varatt; -pub const Pg_magic_struct = c.Pg_magic_struct; -pub const Pg_finfo_record = c.Pg_finfo_record; +pub const Pg_magic_struct = pg.Pg_magic_struct; +pub const Pg_finfo_record = pg.Pg_finfo_record; pub const MAGIC = [*c]const Pg_magic_struct; pub const FN_INFO_V1 = [*c]const Pg_finfo_record; @@ -18,11 +19,11 @@ pub const FN_INFO_V1 = [*c]const Pg_finfo_record; /// This value must be returned by a function named `Pg_magic_func`. pub const PG_MAGIC = Pg_magic_struct{ .len = @bitCast(@as(c_uint, @truncate(@sizeOf(Pg_magic_struct)))), - .version = @divTrunc(c.PG_VERSION_NUM, @as(c_int, 100)), - .funcmaxargs = c.FUNC_MAX_ARGS, - .indexmaxkeys = c.INDEX_MAX_KEYS, - .namedatalen = c.NAMEDATALEN, - .float8byval = c.FLOAT8PASSBYVAL, + .version = @divTrunc(pg.PG_VERSION_NUM, @as(c_int, 100)), + .funcmaxargs = pg.FUNC_MAX_ARGS, + .indexmaxkeys = pg.INDEX_MAX_KEYS, + .namedatalen = pg.NAMEDATALEN, + .float8byval = pg.FLOAT8PASSBYVAL, .abi_extra = [32]u8{ 'P', 'o', 's', 't', 'g', 'r', 'e', 'S', 'Q', 'L', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }; @@ -67,7 +68,7 @@ pub inline fn PG_FUNCTION_V1(comptime name: []const u8, comptime callback: anyty inline fn genFnCall(comptime f: anytype) type { return struct { const function: @TypeOf(f) = f; - fn call(fcinfo: c.FunctionCallInfo) callconv(.C) c.Datum { + fn call(fcinfo: pg.FunctionCallInfo) callconv(.C) pg.Datum { return pgCall(@src(), function, fcinfo); } }; @@ -79,8 +80,8 @@ pub const ArgType = args.ArgType; pub inline fn pgCall( comptime src: std.builtin.SourceLocation, comptime impl: anytype, - fcinfo: c.FunctionCallInfo, -) c.Datum { + fcinfo: pg.FunctionCallInfo, +) pg.Datum { const fnType = @TypeOf(impl); const funcArgType = std.meta.ArgsTuple(fnType); diff --git a/src/pgzx/fmgr/args.zig b/src/pgzx/fmgr/args.zig index 7fe24ef..db12b13 100644 --- a/src/pgzx/fmgr/args.zig +++ b/src/pgzx/fmgr/args.zig @@ -1,5 +1,5 @@ const std = @import("std"); -const c = @import("../c.zig"); +const pg = @import("pgzx_pgsys"); const datum = @import("../datum.zig"); /// Index function argument type. @@ -8,7 +8,7 @@ pub fn Arg(comptime T: type, comptime argNum: u32) type { const Self = @This(); /// Reads the argument from the PostgreSQL function call information. - pub inline fn read(fcinfo: c.FunctionCallInfo) !T { + pub inline fn read(fcinfo: pg.FunctionCallInfo) !T { return readArg(T, fcinfo, argNum); } @@ -31,7 +31,7 @@ pub fn ArgType(comptime T: type) type { } pub inline fn isCallInfo() bool { - return T == c.FunctionCallInfo; + return T == pg.FunctionCallInfo; } pub inline fn consumesArgument() bool { @@ -39,53 +39,53 @@ pub fn ArgType(comptime T: type) type { } /// Reads the indexed function argument. - pub inline fn read(fcinfo: c.FunctionCallInfo, argNum: u32) !T { + pub inline fn read(fcinfo: pg.FunctionCallInfo, argNum: u32) !T { return readArg(T, fcinfo, argNum); } }; } inline fn readArgType(comptime T: type) type { - if (T == c.FunctionCallInfo) { + if (T == pg.FunctionCallInfo) { return T; } return datum.findConv(T).Type; } /// Reads a postgres function call argument as a given type. -fn readArg(comptime T: type, fcinfo: c.FunctionCallInfo, argNum: u32) !readArgType(T) { - if (T == c.FunctionCallInfo) { +fn readArg(comptime T: type, fcinfo: pg.FunctionCallInfo, argNum: u32) !readArgType(T) { + if (T == pg.FunctionCallInfo) { return fcinfo; } const converter = comptime datum.findConv(T); return converter.fromNullableDatum(try mustGetArgNullable(fcinfo, argNum)); } -fn readOptionalArg(comptime T: type, fcinfo: c.FunctionCallInfo, argNum: u32) !?T { +fn readOptionalArg(comptime T: type, fcinfo: pg.FunctionCallInfo, argNum: u32) !?T { if (isNullArg(fcinfo, argNum)) { return null; } return readArg(T, fcinfo, argNum); } -pub inline fn mustGetArgNullable(fcinfo: c.FunctionCallInfo, argNum: u32) !c.NullableDatum { +pub inline fn mustGetArgNullable(fcinfo: pg.FunctionCallInfo, argNum: u32) !pg.NullableDatum { if (fcinfo.*.nargs < argNum) { return error.NotEnoughArguments; } return fcinfo.*.args()[argNum]; } -pub inline fn mustGetArgDatum(fcinfo: c.FunctionCallInfo, argNum: u32) !c.Datum { +pub inline fn mustGetArgDatum(fcinfo: pg.FunctionCallInfo, argNum: u32) !pg.Datum { if (isNullArg(fcinfo, argNum)) { return error.ArgumentIsNull; } return getArgDatum(fcinfo, argNum); } -pub inline fn getArgDatum(fcinfo: c.FunctionCallInfo, argNum: u32) c.Datum { +pub inline fn getArgDatum(fcinfo: pg.FunctionCallInfo, argNum: u32) pg.Datum { return fcinfo.*.args()[argNum].value; } -pub inline fn isNullArg(fcinfo: c.FunctionCallInfo, argNum: u32) bool { +pub inline fn isNullArg(fcinfo: pg.FunctionCallInfo, argNum: u32) bool { return fcinfo.*.args()[argNum].isnull; } diff --git a/src/pgzx/interrupts.zig b/src/pgzx/interrupts.zig index 579519d..6067e77 100644 --- a/src/pgzx/interrupts.zig +++ b/src/pgzx/interrupts.zig @@ -1,9 +1,10 @@ -const c = @import("c.zig"); +const pg = @import("pgzx_pgsys"); + const err = @import("err.zig"); /// Use Signal to create volatile variables that you can set in signal /// handlers. -pub const Signal = Volatile(c.sig_atomic_t); +pub const Signal = Volatile(pg.sig_atomic_t); /// Use SignalOf to create volatile variables based on existing C based /// `volatile sig_atomic_t` variables. @@ -12,7 +13,7 @@ pub const Signal = Volatile(c.sig_atomic_t); /// The zig translator does not translate support the C `volatile` keyword, /// because you can only mark pointers as volatile. For this reason we MUST /// wrap C based `volatile sig_atomic_t` variables. -pub const SignalOf = VolatilePtr(c.sig_atomic_t); +pub const SignalOf = VolatilePtr(pg.sig_atomic_t); pub fn VolatilePtr(comptime T: type) type { return struct { @@ -82,25 +83,25 @@ pub fn Volatile(comptime T: type) type { pub const Pending = struct { // signals - pub const Interrupt = SignalOf.create(&c.InterruptPending); - pub const QueryCancel = SignalOf.create(&c.QueryCancelPending); - pub const ProcDie = SignalOf.create(&c.ProcDiePending); - pub const CheckClientConnection = SignalOf.create(&c.CheckClientConnectionPending); - pub const ClientConnectionLost = SignalOf.create(&c.ClientConnectionLost); - pub const IdleInTransactionSessionTimeout = SignalOf.create(&c.IdleInTransactionSessionTimeoutPending); - pub const IdleSessionTimeout = SignalOf.create(&c.IdleSessionTimeoutPending); - pub const ProcSignalBarrier = SignalOf.create(&c.ProcSignalBarrierPending); - pub const LogMemoryContext = SignalOf.create(&c.LogMemoryContextPending); - pub const IdleStatsUpdateTimeout = SignalOf.create(&c.IdleStatsUpdateTimeoutPending); + pub const Interrupt = SignalOf.create(&pg.InterruptPending); + pub const QueryCancel = SignalOf.create(&pg.QueryCancelPending); + pub const ProcDie = SignalOf.create(&pg.ProcDiePending); + pub const CheckClientConnection = SignalOf.create(&pg.CheckClientConnectionPending); + pub const ClientConnectionLost = SignalOf.create(&pg.ClientConnectionLost); + pub const IdleInTransactionSessionTimeout = SignalOf.create(&pg.IdleInTransactionSessionTimeoutPending); + pub const IdleSessionTimeout = SignalOf.create(&pg.IdleSessionTimeoutPending); + pub const ProcSignalBarrier = SignalOf.create(&pg.ProcSignalBarrierPending); + pub const LogMemoryContext = SignalOf.create(&pg.LogMemoryContextPending); + pub const IdleStatsUpdateTimeout = SignalOf.create(&pg.IdleStatsUpdateTimeoutPending); // counts: - pub const InterruptHoldoffCount = VolatilePtr(u32).create(&c.InterruptHoldoffCount); - pub const QueryCancelHoldoffCount = VolatilePtr(u32).create(&c.QueryCancelHoldoffCount); - pub const CritSectionCount = VolatilePtr(u32).create(&c.CritSectionCount); + pub const InterruptHoldoffCount = VolatilePtr(u32).create(&pg.InterruptHoldoffCount); + pub const QueryCancelHoldoffCount = VolatilePtr(u32).create(&pg.QueryCancelHoldoffCount); + pub const CritSectionCount = VolatilePtr(u32).create(&pg.CritSectionCount); }; pub inline fn CheckForInterrupts() !void { if (Pending.Interrupt.read() != 0) { - try err.wrap(c.ProcessInterrupts, .{}); + try err.wrap(pg.ProcessInterrupts, .{}); } } diff --git a/src/pgzx/lwlock.zig b/src/pgzx/lwlock.zig index c2bf261..8715701 100644 --- a/src/pgzx/lwlock.zig +++ b/src/pgzx/lwlock.zig @@ -4,16 +4,16 @@ //! The global locks like `AddinShmemInitLock` are not directly accessible from //! the generated C bindings. We provide wrapper functions for them here. -const c = @import("c.zig"); +const pg = @import("pgzx_pgsys"); // access `MainLWLockArray`. // // We use a function because the Zig compiler currently complains that it can // access the ID only at runtime. -inline fn mainLock(id: usize) fn () *c.LWLock { +inline fn mainLock(id: usize) fn () *pg.LWLock { return struct { - fn call() *c.LWLock { - return &c.MainLWLockArray[id].lock; + fn call() *pg.LWLock { + return &pg.MainLWLockArray[id].lock; } }.call; } diff --git a/src/pgzx/mem.zig b/src/pgzx/mem.zig index ed62546..237bb77 100644 --- a/src/pgzx/mem.zig +++ b/src/pgzx/mem.zig @@ -5,7 +5,7 @@ const std = @import("std"); -const c = @import("c.zig"); +const pg = @import("pgzx_pgsys"); const meta = @import("meta.zig"); const err = @import("err.zig"); @@ -31,14 +31,14 @@ pub const PGCurrentContextAllocator: std.mem.Allocator = .{ fn pg_alloc(ctx: *anyopaque, len: usize, ptr_align: u8, ret_addr: usize) ?[*]u8 { _ = ret_addr; _ = ctx; - return @ptrCast(c.palloc_aligned(len, ptr_align, c.MCXT_ALLOC_NO_OOM)); + return @ptrCast(pg.palloc_aligned(len, ptr_align, pg.MCXT_ALLOC_NO_OOM)); } fn pg_free(ctx: *anyopaque, buf: []u8, buf_align: u8, ret_addr: usize) void { _ = ret_addr; _ = buf_align; _ = ctx; - c.pfree(@ptrCast(buf)); + pg.pfree(@ptrCast(buf)); } fn pg_resize(ctx: *anyopaque, buf: []u8, buf_align: u8, new_len: usize, ret_addr: usize) bool { @@ -55,20 +55,20 @@ fn pg_resize(ctx: *anyopaque, buf: []u8, buf_align: u8, new_len: usize, ret_addr } pub fn getErrorContext() MemoryContextAllocator { - return MemoryContextAllocator.init(c.ErrorContext, .{}); + return MemoryContextAllocator.init(pg.ErrorContext, .{}); } /// ErrorContext based memory context allocator. /// The allocator is configure to use PostgreSQL-throw (longjump) on OOM. pub fn getErrorContextThrowOOM() MemoryContextAllocator { - return MemoryContextAllocator.init(c.ErrorContext, .{ .flags = 0 }); + return MemoryContextAllocator.init(pg.ErrorContext, .{ .flags = 0 }); } pub const AllocSetOptions = struct { - parent: c.MemoryContext = null, - init_size: c.Size = @intCast(c.ALLOCSET_DEFAULT_INITSIZE), - min_size: c.Size = @intCast(c.ALLOCSET_DEFAULT_MINSIZE), - max_size: c.Size = @intCast(c.ALLOCSET_DEFAULT_MAXSIZE), + parent: pg.MemoryContext = null, + init_size: pg.Size = @intCast(pg.ALLOCSET_DEFAULT_INITSIZE), + min_size: pg.Size = @intCast(pg.ALLOCSET_DEFAULT_MINSIZE), + max_size: pg.Size = @intCast(pg.ALLOCSET_DEFAULT_MAXSIZE), flags: c_int = MemoryContextAllocator.DEFAULT_FLAGS, }; @@ -77,8 +77,8 @@ pub const AllocSetOptions = struct { /// /// If `parent` is null the TopLevel will be used. pub fn createAllocSetContext(comptime name: [:0]const u8, options: AllocSetOptions) error{PGErrorStack}!MemoryContextAllocator { - const ctx: c.MemoryContext = try err.wrap( - c.AllocSetContextCreateInternal, + const ctx: pg.MemoryContext = try err.wrap( + pg.AllocSetContextCreateInternal, .{ options.parent, name.ptr, options.init_size, options.min_size, options.max_size }, ); return MemoryContextAllocator.init(ctx, .{ @@ -94,16 +94,16 @@ pub fn createTempAllocSet(comptime name: [:0]const u8, options: AllocSetOptions) } const SlabContextOptions = struct { - parent: c.MemoryContext = null, - block_size: c.Size = @intCast(c.SLAB_DEFAULT_BLOCK_SIZE), - chunk_size: c.Size, + parent: pg.MemoryContext = null, + block_size: pg.Size = @intCast(pg.SLAB_DEFAULT_BLOCK_SIZE), + chunk_size: pg.Size, flags: c_int = MemoryContextAllocator.DEFAULT_FLAGS, }; pub fn createSlabContext(comptime name: [:0]const u8, options: SlabContextOptions) !MemoryContextAllocator { - const ctx: c.MemoryContext = try err.wrap( - c.SlabContextCreate, + const ctx: pg.MemoryContext = try err.wrap( + pg.SlabContextCreate, .{ options.parent, name.ptr, options.block_size, options.chunk_size }, ); return MemoryContextAllocator.init(ctx, .{ @@ -116,8 +116,8 @@ pub fn createTempSlab(comptime name: [:0]const u8, options: SlabContextOptions) } pub fn createGenerationContext(comptime name: [:0]const u8, options: AllocSetOptions) !MemoryContextAllocator { - const ctx: c.MemoryContext = try err.wrap( - c.GenerationContextCreate, + const ctx: pg.MemoryContext = try err.wrap( + pg.GenerationContextCreate, .{ options.parent, name.ptr, options.min_size, options.init_size, options.max_size }, ); return MemoryContextAllocator.init(ctx, .{ @@ -131,7 +131,7 @@ pub fn createTempGeneration(comptime name: [:0]const u8, options: AllocSetOption pub const TempMemoryContext = struct { current: MemoryContextAllocator, - old: c.MemoryContext, + old: pg.MemoryContext, const Self = @This(); @@ -142,13 +142,13 @@ pub const TempMemoryContext = struct { } pub fn deinit(self: *Self) void { - _ = c.MemoryContextSwitchTo(self.old); + _ = pg.MemoryContextSwitchTo(self.old); self.current.deinit(); } fn switchTo(self: *Self, ctx: MemoryContextAllocator) void { self.current = ctx; - self.old = c.MemoryContextSwitchTo(ctx.ctx); + self.old = pg.MemoryContextSwitchTo(ctx.ctx); } pub fn allocator(self: *Self) std.mem.Allocator { @@ -159,11 +159,11 @@ pub const TempMemoryContext = struct { self.current.reset(); } - pub fn registerResetCallback(self: *Self, cb: *c.MemoryContextCallback) void { + pub fn registerResetCallback(self: *Self, cb: *pg.MemoryContextCallback) void { self.current.registerResetCallback(cb); } - pub fn registerAllocResetCallbackFn(self: *Self, data: ?*anyopaque, f: c.MemoryContextCallbackFunction) !void { + pub fn registerAllocResetCallbackFn(self: *Self, data: ?*anyopaque, f: pg.MemoryContextCallbackFunction) !void { try self.current.registerAllocResetCallbackFn(data, f); } @@ -171,7 +171,7 @@ pub const TempMemoryContext = struct { try self.current.registerAllocResetCallback(data, f); } - pub fn context(self: *Self) c.MemoryContext { + pub fn context(self: *Self) pg.MemoryContext { return self.current.ctx; } }; @@ -180,7 +180,7 @@ pub const TempMemoryContext = struct { pub const MemoryContextAllocator = struct { // `MemoryContext` already is a pointer type. // We only capture the pointer to make sure that all allocation will happen on the chosen memory context. - ctx: c.MemoryContext, + ctx: pg.MemoryContext, flags: c_int, const Self = @This(); @@ -189,9 +189,9 @@ pub const MemoryContextAllocator = struct { flags: c_int = DEFAULT_FLAGS, }; - const DEFAULT_FLAGS: c_int = c.MCXT_ALLOC_NO_OOM; + const DEFAULT_FLAGS: c_int = pg.MCXT_ALLOC_NO_OOM; - pub fn init(ctx: c.MemoryContext, opts: Options) Self { + pub fn init(ctx: pg.MemoryContext, opts: Options) Self { var self: Self = undefined; self.setContext(ctx, opts); return self; @@ -200,42 +200,42 @@ pub const MemoryContextAllocator = struct { /// Delete the underlying memory context. Only use this function if you /// have created a temporary memory context yourself. pub fn deinit(self: *Self) void { - c.MemoryContextDelete(self.ctx); + pg.MemoryContextDelete(self.ctx); self.ctx = null; } /// init the allocator with the given context. /// The context given MUST NOT be null. - pub fn setContext(self: *Self, ctx: c.MemoryContext, opts: Options) void { + pub fn setContext(self: *Self, ctx: pg.MemoryContext, opts: Options) void { std.debug.assert(ctx != null); self.* = .{ .ctx = ctx, .flags = opts.flags }; } pub fn allocated(self: *Self, recurse: bool) usize { - return c.MemoryContextMemAllocated(self.ctx, recurse); + return pg.MemoryContextMemAllocated(self.ctx, recurse); } - pub fn stats(self: *Self) c.MemoryContextCounters { - var counters: c.MemoryContextCounters = undefined; + pub fn stats(self: *Self) pg.MemoryContextCounters { + var counters: pg.MemoryContextCounters = undefined; self.ctx.*.methods.*.stats.?(self.ctx, null, null, &counters, false); std.log.info("MemoryContextCounters: {}", .{counters}); return counters; } pub fn reset(self: *Self) void { - c.MemoryContextReset(self.ctx); + pg.MemoryContextReset(self.ctx); } - pub fn context(self: *Self) c.MemoryContext { + pub fn context(self: *Self) pg.MemoryContext { return self.ctx; } - pub fn registerResetCallback(self: *Self, cb: *c.MemoryContextCallback) void { - c.MemoryContextRegisterResetCallback(self.ctx, cb); + pub fn registerResetCallback(self: *Self, cb: *pg.MemoryContextCallback) void { + pg.MemoryContextRegisterResetCallback(self.ctx, cb); } - pub fn registerAllocResetCallbackFn(self: *Self, data: ?*anyopaque, f: c.MemoryContextCallbackFunction) !void { - const cb = try self.allocator().create(c.MemoryContextCallback); + pub fn registerAllocResetCallbackFn(self: *Self, data: ?*anyopaque, f: pg.MemoryContextCallbackFunction) !void { + const cb = try self.allocator().create(pg.MemoryContextCallback); cb.* = .{ .func = f, .arg = data }; self.registerResetCallback(cb); } @@ -275,7 +275,7 @@ pub const MemoryContextAllocator = struct { _ = ret_addr; const self: *MemoryContextAllocator = @ptrCast(@alignCast(ctx)); const memctx = self.ctx; - const ptr = c.MemoryContextAllocAligned(memctx, len, ptr_align, self.flags); + const ptr = pg.MemoryContextAllocAligned(memctx, len, ptr_align, self.flags); return @ptrCast(ptr); } }; @@ -304,15 +304,15 @@ pub const TestSuite_Mem = struct { } pub fn testAPI_createTempAllocSet() !void { - const old_current = c.CurrentMemoryContext; + const old_current = pg.CurrentMemoryContext; var temp = try createTempAllocSet("testTempAllocSet", .{}); errdefer temp.deinit(); - try std.testing.expect(c.CurrentMemoryContext == temp.context()); + try std.testing.expect(pg.CurrentMemoryContext == temp.context()); temp.deinit(); - try std.testing.expect(c.CurrentMemoryContext == old_current); + try std.testing.expect(pg.CurrentMemoryContext == old_current); } pub fn testAPI_creaetSlabContext() !void { @@ -323,17 +323,17 @@ pub const TestSuite_Mem = struct { } pub fn testAPI_createTempSlabContext() !void { - const old_current = c.CurrentMemoryContext; + const old_current = pg.CurrentMemoryContext; var temp = try createTempSlab("testTempSlab", .{ .chunk_size = 16, }); errdefer temp.deinit(); - try std.testing.expect(c.CurrentMemoryContext == temp.context()); + try std.testing.expect(pg.CurrentMemoryContext == temp.context()); temp.deinit(); - try std.testing.expect(c.CurrentMemoryContext == old_current); + try std.testing.expect(pg.CurrentMemoryContext == old_current); } pub fn testAPI_createGenerationContext() !void { @@ -342,15 +342,15 @@ pub const TestSuite_Mem = struct { } pub fn testAPI_createTempGenerationContext() !void { - const old_current = c.CurrentMemoryContext; + const old_current = pg.CurrentMemoryContext; var temp = try createTempGeneration("testTempGeneration", .{}); errdefer temp.deinit(); - try std.testing.expect(c.CurrentMemoryContext == temp.context()); + try std.testing.expect(pg.CurrentMemoryContext == temp.context()); temp.deinit(); - try std.testing.expect(c.CurrentMemoryContext == old_current); + try std.testing.expect(pg.CurrentMemoryContext == old_current); } pub fn testMemoryContext_allocator() !void { diff --git a/src/pgzx/pq.zig b/src/pgzx/pq.zig index aa0dab3..7377593 100644 --- a/src/pgzx/pq.zig +++ b/src/pgzx/pq.zig @@ -1,6 +1,7 @@ const std = @import("std"); -const c = @import("c.zig"); +const pg = @import("pgzx_pgsys"); + const intr = @import("interrupts.zig"); const elog = @import("elog.zig"); const err = @import("err.zig"); @@ -19,9 +20,9 @@ pub const Error = error{ pub const ConnParams = std.StringHashMap([]const u8); -pub const ConnStatus = c.ConnStatusType; -pub const PollingStatus = c.PostgresPollingStatusType; -pub const TransactionStatus = c.PGTransactionStatusType; +pub const ConnStatus = pg.ConnStatusType; +pub const PollingStatus = pg.PostgresPollingStatusType; +pub const TransactionStatus = pg.PGTransactionStatusType; // libpqsrv wrappers and extensions. const pqsrv = struct { @@ -30,13 +31,13 @@ const pqsrv = struct { var wait_event_connect: u32 = 0; var wait_event_command: u32 = 0; - pub fn connectAsync(conninfo: [:0]const u8) Error!*c.PGconn { - try err.wrap(c.pqsrv_connect_prepare, .{}); - return connOrErr(c.PQconnectStart(conninfo.ptr)); + pub fn connectAsync(conninfo: [:0]const u8) Error!*pg.PGconn { + try err.wrap(pg.pqsrv_connect_prepare, .{}); + return connOrErr(pg.PQconnectStart(conninfo.ptr)); } - pub fn connect(conninfo: [:0]const u8) Error!*c.PGconn { - const maybeConn: ?*c.PGconn = try err.wrap(c.pqsrv_connect, .{ conninfo.ptr, try get_wait_event_connect() }); + pub fn connect(conninfo: [:0]const u8) Error!*pg.PGconn { + const maybeConn: ?*pg.PGconn = try err.wrap(pg.pqsrv_connect, .{ conninfo.ptr, try get_wait_event_connect() }); return connOrErr(maybeConn); } @@ -44,26 +45,26 @@ const pqsrv = struct { keys: [*]const [*c]const u8, values: [*c]const [*c]const u8, expand_dbname: c_int, - ) Error!*c.PGconn { - try err.wrap(c.pqsrv_connect_prepare, .{}); - return connOrErr(c.PQconnectStartParams(keys, values, expand_dbname)); + ) Error!*pg.PGconn { + try err.wrap(pg.pqsrv_connect_prepare, .{}); + return connOrErr(pg.PQconnectStartParams(keys, values, expand_dbname)); } pub fn connectParams( keys: [*]const [*c]const u8, values: [*c]const [*c]const u8, expand_dbname: c_int, - ) Error!*c.PGconn { - const maybeConn = try err.wrap(c.pqsrv_connect_params, .{ keys, values, expand_dbname, try get_wait_event_connect() }); + ) Error!*pg.PGconn { + const maybeConn = try err.wrap(pg.pqsrv_connect_params, .{ keys, values, expand_dbname, try get_wait_event_connect() }); return connOrErr(@ptrCast(maybeConn)); } - pub fn waitConnected(conn: *c.PGconn) !void { - try err.wrap(c.pqsrv_wait_connected, .{ conn, try get_wait_event_connect() }); + pub fn waitConnected(conn: *pg.PGconn) !void { + try err.wrap(pg.pqsrv_wait_connected, .{ conn, try get_wait_event_connect() }); } inline fn get_wait_event_connect() Error!u32 { - return c.PG_WAIT_EXTENSION; + return pg.PG_WAIT_EXTENSION; // if (wait_event_connect == 0) { // wait_event_connect = try err.wrap(c.WaitEventExtensionNew, .{"pq_connect"}); // } @@ -71,14 +72,14 @@ const pqsrv = struct { } inline fn get_wait_event_command() Error!u32 { - return c.PG_WAIT_EXTENSION; + return pg.PG_WAIT_EXTENSION; // if (wait_event_command == 0) { // wait_event_command = try err.wrap(c.WaitEventExtensionNew, .{"pq_command"}); // } // return wait_event_command; } - fn connOrErr(maybe_conn: ?*c.PGconn) Error!*c.PGconn { + fn connOrErr(maybe_conn: ?*pg.PGconn) Error!*pg.PGconn { if (maybe_conn) |conn| { return conn; } @@ -89,7 +90,7 @@ const pqsrv = struct { pub const Conn = struct { const Self = @This(); - conn: *c.PGconn, + conn: *pg.PGconn, allocator: std.mem.Allocator, const Options = struct { @@ -97,7 +98,7 @@ pub const Conn = struct { check: bool = false, }; - pub fn init(allocator: std.mem.Allocator, conn: *c.PGconn) Self { + pub fn init(allocator: std.mem.Allocator, conn: *pg.PGconn) Self { return Self{ .conn = conn, .allocator = allocator }; } @@ -140,7 +141,7 @@ pub const Conn = struct { return; } - if (self.status() != c.CONNECTION_OK) { + if (self.status() != pg.CONNECTION_OK) { if (self.errorMessage()) |msg| { std.log.err("Connection error: {s}", .{msg}); } @@ -149,11 +150,11 @@ pub const Conn = struct { } pub fn connectPoll(self: *const Self) PollingStatus { - return c.PQconnectPoll(self.conn); + return pg.PQconnectPoll(self.conn); } pub fn reset(self: *const Self) bool { - return c.PQresetStart(self.conn) != 0; + return pg.PQresetStart(self.conn) != 0; } pub fn resetWait(self: *const Self) !void { @@ -164,18 +165,18 @@ pub const Conn = struct { } pub fn resetPoll(self: *const Self) PollingStatus { - return c.PQresetPoll(self.conn); + return pg.PQresetPoll(self.conn); } pub fn setNonBlocking(self: *const Self, arg: bool) !void { - const rs = c.PQsetnonblocking(self.conn, if (arg) 1 else 0); + const rs = pg.PQsetnonblocking(self.conn, if (arg) 1 else 0); if (rs < 0) { return error.OperationFailed; } } pub fn exec(self: *const Self, query: [:0]const u8) !Result { - const rc = c.PQsendQuery(self.conn, query); + const rc = pg.PQsendQuery(self.conn, query); if (rc == 0) { pqError(@src(), self.conn) catch |e| return e; return Error.SendFailed; @@ -198,7 +199,7 @@ pub const Conn = struct { } pub fn execParams(self: *const Self, command: [:0]const u8, params: PGQueryParams) !Result { - const rc = c.PQsendQueryParams( + const rc = pg.PQsendQueryParams( self.conn, command, @as(c_int, @intCast(params.values.len)), @@ -220,10 +221,10 @@ pub const Conn = struct { return try Self.initExecResult(self.conn, res); } - fn initExecResult(conn: ?*c.PGconn, pgres: ?*c.PGresult) !Result { - if (responseCodeFatal(c.PQresultStatus(pgres))) { - defer c.PQclear(pgres); - const raw_error = c.PQresultErrorMessage(pgres); + fn initExecResult(conn: ?*pg.PGconn, pgres: ?*pg.PGresult) !Result { + if (responseCodeFatal(pg.PQresultStatus(pgres))) { + defer pg.PQclear(pgres); + const raw_error = pg.PQresultErrorMessage(pgres); if (raw_error) |msg| { return elog.Error(@src(), "{s}", .{std.mem.span(msg)}); } @@ -279,7 +280,7 @@ pub const Conn = struct { } } - const rc = c.PQsendQueryParams( + const rc = pg.PQsendQueryParams( self.conn, query, @intCast(n), @@ -296,7 +297,7 @@ pub const Conn = struct { } pub fn sendQuery(self: *const Self, query: []const u8) !void { - const rc = c.PQsendQuery(self.conn, query); + const rc = pg.PQsendQuery(self.conn, query); if (rc == 0) { pqError(@src()) catch |e| return e; return Error.SendFailed; @@ -334,14 +335,14 @@ pub const Conn = struct { } return false; } - if (r.status() == c.PGRES_NONFATAL_ERROR) { // ignore NOTICE or WARNING + if (r.status() == pg.PGRES_NONFATAL_ERROR) { // ignore NOTICE or WARNING continue; } return switch (r.status()) { - c.PGRES_COMMAND_OK, - c.PGRES_TUPLES_OK, - c.PGRES_SINGLE_TUPLE, + pg.PGRES_COMMAND_OK, + pg.PGRES_TUPLES_OK, + pg.PGRES_SINGLE_TUPLE, => true, else => false, }; @@ -356,28 +357,28 @@ pub const Conn = struct { return if (res) |r| Result.init(r) else null; } - pub fn getRawResult(self: *const Self) !?*c.PGresult { + pub fn getRawResult(self: *const Self) !?*pg.PGresult { try self.waitReady(); - return c.PQgetResult(self.conn); + return pg.PQgetResult(self.conn); } - pub fn getRawResultLast(self: *const Self) !?*c.PGresult { - var last: ?*c.PGresult = null; + pub fn getRawResultLast(self: *const Self) !?*pg.PGresult { + var last: ?*pg.PGresult = null; errdefer { - if (last) |r| c.PQclear(r); + if (last) |r| pg.PQclear(r); } while (true) { const res = try self.getRawResult(); if (res == null) break; - if (last) |r| c.PQclear(r); + if (last) |r| pg.PQclear(r); last = res; - const stopLoop = switch (c.PQresultStatus(res)) { - c.PGRES_COPY_IN, - c.PGRES_COPY_OUT, - c.PGRES_COPY_BOTH, + const stopLoop = switch (pg.PQresultStatus(res)) { + pg.PGRES_COPY_IN, + pg.PGRES_COPY_OUT, + pg.PGRES_COPY_BOTH, => true, else => false, }; @@ -403,24 +404,24 @@ pub const Conn = struct { // sending pending messages that are still enqueued in memory only. const send_queue_empty = try self.flush(); if (!send_queue_empty) { - wait_flag = c.WL_SOCKET_WRITEABLE; + wait_flag = pg.WL_SOCKET_WRITEABLE; } try self.consumeInput(); if (self.isBusy()) { - wait_flag |= c.WL_SOCKET_READABLE; + wait_flag |= pg.WL_SOCKET_READABLE; } if (wait_flag == 0) { break; } - const rc = c.WaitLatchOrSocket(c.MyLatch, wait_flag, self.socket(), 0, c.PG_WAIT_EXTENSION); - if (checkFlag(c.WL_POSTMASTER_DEATH, rc)) { + const rc = pg.WaitLatchOrSocket(pg.MyLatch, wait_flag, self.socket(), 0, pg.PG_WAIT_EXTENSION); + if (checkFlag(pg.WL_POSTMASTER_DEATH, rc)) { return Error.PostmasterDied; } - if (checkFlag(c.WL_LATCH_SET, rc)) { - c.ResetLatch(c.MyLatch); + if (checkFlag(pg.WL_LATCH_SET, rc)) { + pg.ResetLatch(pg.MyLatch); try intr.CheckForInterrupts(); } } @@ -429,7 +430,7 @@ pub const Conn = struct { // Flush the send queue. Returns true if the all data has been sent or if the queue is empty. // Return false is the send queue is not send completely. pub fn flush(self: *const Self) !bool { - const rc = c.PQflush(self.conn); + const rc = pg.PQflush(self.conn); if (rc < 0) { pqError(@src(), self.conn) catch |e| return e; return error.OperationFailed; @@ -438,7 +439,7 @@ pub const Conn = struct { } pub fn consumeInput(self: *const Self) !void { - const rc = c.PQconsumeInput(self.conn); + const rc = pg.PQconsumeInput(self.conn); if (rc == 0) { pqError(@src(), self.conn) catch |e| return e; return error.OperationFailed; @@ -446,50 +447,50 @@ pub const Conn = struct { } pub fn finish(self: *const Self) void { - c.pqsrv_disconnect(self.conn); + pg.pqsrv_disconnect(self.conn); } pub fn status(self: *const Self) ConnStatus { - return c.PQstatus(self.conn); + return pg.PQstatus(self.conn); } pub fn transactionStatus(self: *const Self) TransactionStatus { - return c.PQtransactionStatus(self.conn); + return pg.PQtransactionStatus(self.conn); } pub fn serverVersion(self: *const Self) c_int { - return c.PQserverVersion(self.conn); + return pg.PQserverVersion(self.conn); } pub fn errorMessage(self: *const Self) ?[:0]const u8 { - if (c.PQerrorMessage(self.conn)) |msg| { + if (pg.PQerrorMessage(self.conn)) |msg| { return std.mem.span(msg); } return null; } pub fn socket(self: *const Self) c_int { - return c.PQsocket(self.conn); + return pg.PQsocket(self.conn); } pub fn backendPID(self: *const Self) c_int { - return c.PQbackendPID(self.conn); + return pg.PQbackendPID(self.conn); } pub fn host(self: *const Self) [:0]const u8 { - return std.mem.span(c.PQhost(self.conn)); + return std.mem.span(pg.PQhost(self.conn)); } pub fn port(self: *const Self) [:0]const u8 { - return std.mem.span(c.PQport(self.conn)); + return std.mem.span(pg.PQport(self.conn)); } pub fn dbname(self: *const Self) [:0]const u8 { - return std.mem.span(c.PQdb(self.conn)); + return std.mem.span(pg.PQdb(self.conn)); } pub fn isBusy(self: *const Self) bool { - return c.PQisBusy(self.conn) != 0; + return pg.PQisBusy(self.conn) != 0; } }; @@ -529,7 +530,7 @@ pub const StartupStatus = enum { }; pub const PollStartState = struct { - polltype: c.PostgresPollingStatusType, + polltype: pg.PostgresPollingStatusType, status: StartupStatus = StartupStatus.CONNECTING, const Self = @This(); @@ -548,8 +549,8 @@ pub const PollStartState = struct { pub fn update(self: *Self, conn: *const Conn) bool { const pq_status = conn.status(); var status_update = switch (pq_status) { - c.CONNECTION_OK => StartupStatus.CONNECTED, - c.CONNECTION_BAD => StartupStatus.ERROR, + pg.CONNECTION_OK => StartupStatus.CONNECTED, + pg.CONNECTION_BAD => StartupStatus.ERROR, else => StartupStatus.CONNECTING, }; @@ -562,8 +563,8 @@ pub const PollStartState = struct { // still connecting self.polltype = conn.connectPoll(); status_update = switch (self.polltype) { - c.PGRES_POLLING_FAILED => StartupStatus.ERROR, - c.PGRES_POLLING_OK => StartupStatus.CONNECTED, + pg.PGRES_POLLING_FAILED => StartupStatus.ERROR, + pg.PGRES_POLLING_OK => StartupStatus.CONNECTED, else => StartupStatus.CONNECTING, }; const changed = self.status != status_update; @@ -574,20 +575,20 @@ pub const PollStartState = struct { pub fn getEventMask(self: *const Self) u32 { if (self.status == StartupStatus.CONNECTING) { return switch (self.polltype) { - c.PGRES_POLLING_READING => c.WL_SOCKET_READABLE, - else => c.WL_SOCKET_WRITEABLE, + pg.PGRES_POLLING_READING => pg.WL_SOCKET_READABLE, + else => pg.WL_SOCKET_WRITEABLE, }; } return 0; } }; -fn responseCodeFatal(response_code: c.ExecStatusType) bool { +fn responseCodeFatal(response_code: pg.ExecStatusType) bool { return switch (response_code) { - c.PGRES_COMMAND_OK => false, - c.PGRES_TUPLES_OK => false, - c.PGRES_SINGLE_TUPLE => false, - c.PGRES_NONFATAL_ERROR => false, + pg.PGRES_COMMAND_OK => false, + pg.PGRES_TUPLES_OK => false, + pg.PGRES_SINGLE_TUPLE => false, + pg.PGRES_NONFATAL_ERROR => false, else => response_code > 0, }; } @@ -597,7 +598,7 @@ pub const PGQueryParams = struct { // Optional OID types of the values. Required for binary encodings. // In case of text encoding optional. - types: ?[]const c.Oid = null, + types: ?[]const pg.Oid = null, // byte length per value in case values are binary encoded. lengths: ?[]const c_int = null, @@ -641,7 +642,7 @@ pub fn buildParams( var value_indices = try local_allocator.alloc(i32, argsInfo.Struct.fields.len); const writer: std.ArrayList(u8).Writer = buffer.writer(); - var types = try allocator.alloc(c.Oid, argsInfo.Struct.fields.len); + var types = try allocator.alloc(pg.Oid, argsInfo.Struct.fields.len); inline for (argsInfo.Struct.fields, 0..) |field, idx| { const codec = conv.find(field.type); @@ -673,39 +674,39 @@ pub fn buildParams( } const Result = struct { - result: *c.PGresult, + result: *pg.PGresult, const Self = @This(); - fn init(result: *c.PGresult) Self { + fn init(result: *pg.PGresult) Self { return Result{ .result = result }; } pub fn deinit(self: Self) void { - c.PQclear(self.result); + pg.PQclear(self.result); } - pub fn status(self: Self) c.ExecStatusType { - return c.PQresultStatus(self.result); + pub fn status(self: Self) pg.ExecStatusType { + return pg.PQresultStatus(self.result); } pub fn isError(self: Self) bool { return switch (self.status()) { - c.PGRES_EMPTY_QUERY, - c.PGRES_COMMAND_OK, - c.PGRES_TUPLES_OK, - c.PGRES_COPY_OUT, - c.PGRES_COPY_IN, - c.PGRES_COPY_BOTH, - c.PGRES_SINGLE_TUPLE, - c.PGRES_NONFATAL_ERROR, // warning or notice, but no error + pg.PGRES_EMPTY_QUERY, + pg.PGRES_COMMAND_OK, + pg.PGRES_TUPLES_OK, + pg.PGRES_COPY_OUT, + pg.PGRES_COPY_IN, + pg.PGRES_COPY_BOTH, + pg.PGRES_SINGLE_TUPLE, + pg.PGRES_NONFATAL_ERROR, // warning or notice, but no error => false, else => true, }; } pub fn errorMessage(self: Self) ?[:0]const u8 { - if (c.PQresultErrorMessage(self.result)) |msg| { + if (pg.PQresultErrorMessage(self.result)) |msg| { return std.mem.span(msg); } return null; @@ -716,13 +717,13 @@ fn checkFlag(comptime pattern: anytype, value: @TypeOf(pattern)) bool { return (value & pattern) == pattern; } -fn pqError(src: std.builtin.SourceLocation, conn: ?*c.PGconn) error{PGErrorStack}!void { - const rawerr = c.PQerrorMessage(conn); +fn pqError(src: std.builtin.SourceLocation, conn: ?*pg.PGconn) error{PGErrorStack}!void { + const rawerr = pg.PQerrorMessage(conn); if (rawerr == null) { return; } - try elog.Report.init(src, c.ERROR).raise(.{ + try elog.Report.init(src, pg.ERROR).raise(.{ .message = std.mem.span(rawerr), }); unreachable; diff --git a/src/pgzx/pq/conv.zig b/src/pgzx/pq/conv.zig index a3048e5..6e3539c 100644 --- a/src/pgzx/pq/conv.zig +++ b/src/pgzx/pq/conv.zig @@ -1,6 +1,6 @@ const std = @import("std"); -const c = @import("../c.zig"); +const pg = @import("pgzx_pgsys"); const meta = @import("../meta.zig"); pub const Error = error{ @@ -88,7 +88,7 @@ fn optconv(comptime C: type) type { } const boolconv = struct { - pub const OID = c.BOOLOID; + pub const OID = pg.BOOLOID; pub const Type = bool; pub fn write(writer: anytype, value: bool) !void { @@ -112,14 +112,14 @@ const boolconv = struct { } }; -const i8conv = intconv(i8, c.INT2OID); -const i16conv = intconv(i16, c.INT2OID); -const i32conv = intconv(i32, c.INT4OID); -const i64conv = intconv(i64, c.INT8OID); -const u8conv = intconv(u8, c.INT2OID); -const u16conv = intconv(u16, c.INT4OID); -const u32conv = intconv(u32, c.INT8OID); -fn intconv(comptime T: type, comptime oid: c.Oid) type { +const i8conv = intconv(i8, pg.INT2OID); +const i16conv = intconv(i16, pg.INT2OID); +const i32conv = intconv(i32, pg.INT4OID); +const i64conv = intconv(i64, pg.INT8OID); +const u8conv = intconv(u8, pg.INT2OID); +const u16conv = intconv(u16, pg.INT4OID); +const u32conv = intconv(u32, pg.INT8OID); +fn intconv(comptime T: type, comptime oid: pg.Oid) type { return struct { pub const OID = oid; pub const Type = T; @@ -137,9 +137,9 @@ fn intconv(comptime T: type, comptime oid: c.Oid) type { }; } -const f32conv = floatconv(f32, c.FLOAT4OID); -const f64conv = floatconv(f64, c.FLOAT8OID); -fn floatconv(comptime T: type, comptime oid: c.Oid) type { +const f32conv = floatconv(f32, pg.FLOAT4OID); +const f64conv = floatconv(f64, pg.FLOAT8OID); +fn floatconv(comptime T: type, comptime oid: pg.Oid) type { return struct { pub const OID = oid; pub const Type = T; @@ -158,7 +158,7 @@ fn floatconv(comptime T: type, comptime oid: c.Oid) type { } const textconv = struct { - pub const OID = c.TEXTOID; + pub const OID = pg.TEXTOID; pub const Type = []const u8; pub fn write(writer: anytype, value: []const u8) !void { @@ -172,7 +172,7 @@ const textconv = struct { }; const textzconv = struct { - pub const OID = c.TEXTOID; + pub const OID = pg.TEXTOID; pub const Type = [:0]const u8; pub fn write(writer: anytype, value: [:0]const u8) !void { diff --git a/src/pgzx/pq/params.zig b/src/pgzx/pq/params.zig index efd3184..246d86f 100644 --- a/src/pgzx/pq/params.zig +++ b/src/pgzx/pq/params.zig @@ -1,6 +1,6 @@ // const std = @import("std"); // const conv = @import("conv.zig"); -// const c = @import("../c.zig"); +// const c = @import("pgzx_pgsys"); // // pub fn buildParams(allocator: std.mem.Allocator, params: anytype) !Params { // return Builder.new(allocator).build(params); diff --git a/src/pgzx/shmem.zig b/src/pgzx/shmem.zig index 022bb9a..4808acd 100644 --- a/src/pgzx/shmem.zig +++ b/src/pgzx/shmem.zig @@ -1,6 +1,6 @@ const std = @import("std"); -const c = @import("c.zig"); +const pg = @import("pgzx_pgsys"); pub inline fn registerHooks(comptime T: anytype) void { if (std.meta.hasFn(T, "requestHook")) { @@ -23,7 +23,7 @@ pub inline fn registerSharedState(comptime T: type, shared_state: **T) void { pub fn startupHook() void { var found = false; - const ptr = c.ShmemInitStruct(T.SHMEM_NAME, @sizeOf(T), &found); + const ptr = pg.ShmemInitStruct(T.SHMEM_NAME, @sizeOf(T), &found); shared_state.* = @ptrCast(@alignCast(ptr)); if (!found) { if (std.meta.hasFn(T, "init")) { @@ -37,11 +37,11 @@ pub inline fn registerSharedState(comptime T: type, shared_state: **T) void { } pub inline fn registerRequestHook(f: anytype) void { - registerHook(f, &c.shmem_request_hook); + registerHook(f, &pg.shmem_request_hook); } pub inline fn registerStartupHook(f: anytype) void { - registerHook(f, &c.shmem_startup_hook); + registerHook(f, &pg.shmem_startup_hook); } inline fn registerHook(f: anytype, hook: anytype) void { @@ -60,12 +60,12 @@ inline fn registerHook(f: anytype, hook: anytype) void { } pub inline fn requestSpaceFor(comptime T: type) void { - c.RequestAddinShmemSpace(@sizeOf(T)); + pg.RequestAddinShmemSpace(@sizeOf(T)); } pub inline fn createAndZero(comptime T: type) *T { var found = false; - const ptr = c.ShmemInitStruct(T.SHMEM_NAME, @sizeOf(T), &found); + const ptr = pg.ShmemInitStruct(T.SHMEM_NAME, @sizeOf(T), &found); const shared_state: *T = @ptrCast(@alignCast(ptr)); if (!found) { shared_state.* = std.mem.zeroes(T); @@ -77,7 +77,7 @@ pub inline fn createAndInit(comptime T: type) *T { // TODO: check that T implements init var found = false; - const ptr = c.ShmemInitStruct(T.SHMEM_NAME, @sizeOf(T), &found); + const ptr = pg.ShmemInitStruct(T.SHMEM_NAME, @sizeOf(T), &found); const shared_state: *T = @ptrCast(@alignCast(ptr)); if (!found) { shared_state.init(); diff --git a/src/pgzx/spi.zig b/src/pgzx/spi.zig index f7de0d3..163052d 100644 --- a/src/pgzx/spi.zig +++ b/src/pgzx/spi.zig @@ -1,28 +1,29 @@ const std = @import("std"); +const pg = @import("pgzx_pgsys"); + const mem = @import("mem.zig"); const err = @import("err.zig"); -const c = @import("c.zig"); const datum = @import("datum.zig"); pub fn connect() err.PGError!void { - const status = c.SPI_connect(); - if (status == c.SPI_ERROR_CONNECT) { + const status = pg.SPI_connect(); + if (status == pg.SPI_ERROR_CONNECT) { return err.PGError.SPIConnectFailed; } } pub fn connectNonAtomic() err.PGError!void { - const status = c.SPI_connect_ext(c.SPI_OPT_NONATOMIC); + const status = pg.SPI_connect_ext(pg.SPI_OPT_NONATOMIC); try checkStatus(status); } pub fn finish() void { - _ = c.SPI_finish(); + _ = pg.SPI_finish(); } pub const Args = struct { - types: []const c.Oid, - values: []const c.NullableDatum, + types: []const pg.Oid, + values: []const pg.NullableDatum, pub fn has_nulls(self: *const Args) bool { for (self.values) |value| { @@ -65,15 +66,15 @@ pub fn exec(sql: [:0]const u8, options: ExecOptions) SPIError!c_int { } }; - const values: [*c]c.Datum = blk: { - var buf = try allocator.alloc(c.Datum, n); + const values: [*c]pg.Datum = blk: { + var buf = try allocator.alloc(pg.Datum, n); for (args.values, 0..) |arg, i| { buf[i] = arg.value; } break :blk buf.ptr; }; - const status = c.SPI_execute_with_args( + const status = pg.SPI_execute_with_args( sql.ptr, @intCast(n), @constCast(args.types.ptr), @@ -85,7 +86,7 @@ pub fn exec(sql: [:0]const u8, options: ExecOptions) SPIError!c_int { try checkStatus(status); return status; } else { - const status = c.SPI_execute(sql.ptr, options.read_only, options.limit); + const status = pg.SPI_execute(sql.ptr, options.read_only, options.limit); try checkStatus(status); return status; } @@ -97,7 +98,7 @@ pub fn query(sql: [:0]const u8, options: ExecOptions) SPIError!Rows { } pub fn scanProcessed(row: usize, values: anytype) !void { - if (c.SPI_processed <= row) { + if (pg.SPI_processed <= row) { return err.PGError.SPIInvalidRowIndex; } @@ -125,7 +126,7 @@ fn scanField(comptime fieldType: type, to: anytype, row: usize, column: c_int) ! } return structColumn; } else { - const value = try convBinValue(childType, c.SPI_tuptable, row, column); + const value = try convBinValue(childType, pg.SPI_tuptable, row, column); to.* = value; return column + 1; } @@ -141,13 +142,13 @@ pub const Rows = struct { } pub fn deinit(self: *Self) void { - c.SPI_freetuptable(c.SPI_tuptable); + pg.SPI_freetuptable(pg.SPI_tuptable); self.row = -1; } pub fn next(self: *Self) bool { const next_idx = self.row + 1; - if (next_idx >= c.SPI_processed) { + if (next_idx >= pg.SPI_processed) { return false; } self.row = next_idx; @@ -188,30 +189,30 @@ pub fn RowsOf(comptime T: type) type { } pub fn convProcessed(comptime T: type, row: c_int, col: c_int) !T { - if (c.SPI_processed <= row) { + if (pg.SPI_processed <= row) { return err.PGError.SPIInvalidRowIndex; } - return convBinValue(T, c.SPI_tuptable, row, col); + return convBinValue(T, pg.SPI_tuptable, row, col); } -pub fn convBinValue(comptime T: type, table: *c.SPITupleTable, row: usize, col: c_int) !T { +pub fn convBinValue(comptime T: type, table: *pg.SPITupleTable, row: usize, col: c_int) !T { // TODO: check index? - var nd: c.NullableDatum = undefined; - nd.value = c.SPI_getbinval(table.*.vals[row], table.*.tupdesc, col, @ptrCast(&nd.isnull)); - try checkStatus(c.SPI_result); + var nd: pg.NullableDatum = undefined; + nd.value = pg.SPI_getbinval(table.*.vals[row], table.*.tupdesc, col, @ptrCast(&nd.isnull)); + try checkStatus(pg.SPI_result); return try datum.fromNullableDatum(T, nd); } fn checkStatus(st: c_int) err.PGError!void { switch (st) { - c.SPI_ERROR_CONNECT => return err.PGError.SPIConnectFailed, - c.SPI_ERROR_ARGUMENT => return err.PGError.SPIArgument, - c.SPI_ERROR_COPY => return err.PGError.SPICopy, - c.SPI_ERROR_TRANSACTION => return err.PGError.SPITransaction, - c.SPI_ERROR_OPUNKNOWN => return err.PGError.SPIOpUnknown, - c.SPI_ERROR_UNCONNECTED => return err.PGError.SPIUnconnected, - c.SPI_ERROR_NOATTRIBUTE => return err.PGError.SPINoAttribute, + pg.SPI_ERROR_CONNECT => return err.PGError.SPIConnectFailed, + pg.SPI_ERROR_ARGUMENT => return err.PGError.SPIArgument, + pg.SPI_ERROR_COPY => return err.PGError.SPICopy, + pg.SPI_ERROR_TRANSACTION => return err.PGError.SPITransaction, + pg.SPI_ERROR_OPUNKNOWN => return err.PGError.SPIOpUnknown, + pg.SPI_ERROR_UNCONNECTED => return err.PGError.SPIUnconnected, + pg.SPI_ERROR_NOATTRIBUTE => return err.PGError.SPINoAttribute, else => { if (st < 0) { return err.PGError.SPIError; diff --git a/src/pgzx/testing.zig b/src/pgzx/testing.zig index 0ab27ac..f153912 100644 --- a/src/pgzx/testing.zig +++ b/src/pgzx/testing.zig @@ -1,10 +1,11 @@ const std = @import("std"); +pub const pg = @import("pgzx_pgsys"); + pub const err = @import("err.zig"); pub const elog = @import("elog.zig"); pub const fmgr = @import("fmgr.zig"); pub const mem = @import("mem.zig"); -pub const pg = @import("c.zig"); pub const pgzx_err = @import("err.zig"); /// This function registers a set of test suites to be run inside the Postgres server. A `run_tests` function is diff --git a/src/pgzx/utils/guc.zig b/src/pgzx/utils/guc.zig index 559596f..35c54ea 100644 --- a/src/pgzx/utils/guc.zig +++ b/src/pgzx/utils/guc.zig @@ -1,6 +1,6 @@ const std = @import("std"); -const c = @import("../c.zig"); +const pg = @import("pgzx_pgsys"); pub const CustomBoolVariable = struct { value: bool, @@ -10,11 +10,11 @@ pub const CustomBoolVariable = struct { short_desc: ?[:0]const u8 = null, long_desc: ?[:0]const u8 = null, initial_value: bool = false, - context: c.GucContext = c.PGC_USERSET, + context: pg.GucContext = pg.PGC_USERSET, flags: c_int = 0, - check_hook: c.GucBoolCheckHook = null, - assign_hook: c.GucBoolAssignHook = null, - show_hook: c.GucShowHook = null, + check_hook: pg.GucBoolCheckHook = null, + assign_hook: pg.GucBoolAssignHook = null, + show_hook: pg.GucShowHook = null, }; pub fn registerValue(options: Options) void { @@ -27,7 +27,7 @@ pub const CustomBoolVariable = struct { } fn doRegister(value: ?*bool, options: Options) void { - c.DefineCustomBoolVariable( + pg.DefineCustomBoolVariable( options.name, optSliceCPtr(options.short_desc), optSliceCPtr(options.long_desc), @@ -52,11 +52,11 @@ pub const CustomIntVariable = struct { initial_value: ?c_int = 0, min_value: c_int = 0, max_value: c_int = std.math.maxInt(c_int), - context: c.GucContext = c.PGC_USERSET, + context: pg.GucContext = pg.PGC_USERSET, flags: c_int = 0, - check_hook: c.GucIntCheckHook = null, - assign_hook: c.GucIntAssignHook = null, - show_hook: c.GucShowHook = null, + check_hook: pg.GucIntCheckHook = null, + assign_hook: pg.GucIntAssignHook = null, + show_hook: pg.GucShowHook = null, }; pub fn registerValue(options: Options) void { @@ -72,7 +72,7 @@ pub const CustomIntVariable = struct { fn doRegister(value: ?*c_int, options: Options) void { const init_value = if (value) |v| v.* else options.initial_value orelse 0; - c.DefineCustomIntVariable( + pg.DefineCustomIntVariable( options.name, optSliceCPtr(options.short_desc), optSliceCPtr(options.long_desc), @@ -97,7 +97,7 @@ pub const CustomStringVariable = struct { short_desc: ?[:0]const u8 = null, long_desc: ?[:0]const u8 = null, initial_value: ?[:0]const u8 = null, - context: c.GucContext = c.PGC_USERSET, + context: pg.GucContext = pg.PGC_USERSET, flags: c_int = 0, }; @@ -108,7 +108,7 @@ pub const CustomStringVariable = struct { self._value = v.ptr; } - c.DefineCustomStringVariable( + pg.DefineCustomStringVariable( options.name, optSliceCPtr(options.short_desc), optSliceCPtr(options.long_desc), @@ -144,15 +144,15 @@ pub const CustomIntOptions = struct { boot_value: c_int = 0, min_value: c_int = 0, max_value: c_int = std.math.maxInt(c_int), - context: c.GucContext = c.PGC_USERSET, + context: pg.GucContext = pg.PGC_USERSET, flags: c_int = 0, - check_hook: c.GucIntCheckHook = null, - assign_hook: c.GucIntAssignHook = null, - show_hook: c.GucShowHook = null, + check_hook: pg.GucIntCheckHook = null, + assign_hook: pg.GucIntAssignHook = null, + show_hook: pg.GucShowHook = null, }; pub fn defineCustomInt(options: CustomIntOptions) void { - c.DefineCustomIntVariable( + pg.DefineCustomIntVariable( options.name, optSliceCPtr(options.short_desc), optSliceCPtr(options.long_desc), diff --git a/src/pgzx/varatt.zig b/src/pgzx/varatt.zig index 05d277c..60ead17 100644 --- a/src/pgzx/varatt.zig +++ b/src/pgzx/varatt.zig @@ -1,7 +1,7 @@ //! varatt replaces the VA<...> macros from utils/varattr.h that Zig didn't //! compile correctly. -const c = @import("c.zig"); +const pg = @import("pgzx_pgsys"); // WARNING: // Taken from translated C code and mostly untested. @@ -11,28 +11,28 @@ const c = @import("c.zig"); // We do not want to expose these directly, but we must make sure that we test // all variable conversions to make sure that code actually compiles. -pub const VARHDRSZ = c.VARHDRSZ; +pub const VARHDRSZ = pg.VARHDRSZ; pub const VARHDRSZ_SHORT = @sizeOf(varattrib_1b); pub const VARHDRSZ_EXTERNAL = @sizeOf(varattrib_1b_e); -pub const VARLENA_EXTSIZE_BITS = c.VARLENA_EXTSIZE_BITS; +pub const VARLENA_EXTSIZE_BITS = pg.VARLENA_EXTSIZE_BITS; -pub const VARTAG_EXPANDED_RO = c.VARTAG_EXPANDED_RO; -pub const VARTAG_EXPANDED_RW = c.VARTAG_EXPANDED_RW; -pub const VARTAG_INDIRECT = c.VARTAG_INDIRECT; -pub const VARTAG_ONDISK = c.VARTAG_ONDISK; +pub const VARTAG_EXPANDED_RO = pg.VARTAG_EXPANDED_RO; +pub const VARTAG_EXPANDED_RW = pg.VARTAG_EXPANDED_RW; +pub const VARTAG_INDIRECT = pg.VARTAG_INDIRECT; +pub const VARTAG_ONDISK = pg.VARTAG_ONDISK; -pub const SET_VARSIZE_4B = c.SET_VARSIZE_4B; -pub const SET_VARSIZE_1B = c.SET_VARSIZE_1B; -pub const SET_VARSIZE_4B_C = c.SET_VARSIZE_4B_C; -pub const SET_VARTAG_1B_E = c.SET_VARTAG_1B_E; +pub const SET_VARSIZE_4B = pg.SET_VARSIZE_4B; +pub const SET_VARSIZE_1B = pg.SET_VARSIZE_1B; +pub const SET_VARSIZE_4B_C = pg.SET_VARSIZE_4B_C; +pub const SET_VARTAG_1B_E = pg.SET_VARTAG_1B_E; -pub const varatt_indirect = c.varatt_indirect; -pub const varatt_expanded = c.varatt_expanded; -pub const varatt_external = c.varatt_external; -pub const varattrib_1b = c.varattrib_1b; -pub const varattrib_4b = c.varattrib_4b; -pub const varattrib_1b_e = c.varattrib_1b_e; +pub const varatt_indirect = pg.varatt_indirect; +pub const varatt_expanded = pg.varatt_expanded; +pub const varatt_external = pg.varatt_external; +pub const varattrib_1b = pg.varattrib_1b; +pub const varattrib_4b = pg.varattrib_4b; +pub const varattrib_1b_e = pg.varattrib_1b_e; pub const VARLENA_EXTSIZE_MASK = (@as(c_uint, 1) << VARLENA_EXTSIZE_BITS) - @as(c_int, 1); @@ -71,17 +71,17 @@ pub inline fn VARATT_IS_1B_E(PTR: anytype) @TypeOf(@import("std").zig.c_translat return @import("std").zig.c_translation.cast([*c]varattrib_1b, PTR).*.va_header == @as(c_int, 0x01); } -pub inline fn VARATT_NOT_PAD_BYTE(PTR: anytype) @TypeOf(@import("std").zig.c_translation.cast([*c]c.uint8, PTR).* != @as(c_int, 0)) { - return @import("std").zig.c_translation.cast([*c]c.uint8, PTR).* != @as(c_int, 0); +pub inline fn VARATT_NOT_PAD_BYTE(PTR: anytype) @TypeOf(@import("std").zig.c_translation.cast([*c]pg.uint8, PTR).* != @as(c_int, 0)) { + return @import("std").zig.c_translation.cast([*c]pg.uint8, PTR).* != @as(c_int, 0); } -pub inline fn VARSIZE_4B(PTR: anytype) @TypeOf((@import("std").zig.c_translation.cast([*c]varattrib_4b, PTR).*.va_4byte.va_header >> @as(c.uint32, 2)) & @import("std").zig.c_translation.promoteIntLiteral(c.uint32, 0x3FFFFFFF, .hex)) { +pub inline fn VARSIZE_4B(PTR: anytype) @TypeOf((@import("std").zig.c_translation.cast([*c]varattrib_4b, PTR).*.va_4byte.va_header >> @as(pg.uint32, 2)) & @import("std").zig.c_translation.promoteIntLiteral(pg.uint32, 0x3FFFFFFF, .hex)) { _ = &PTR; - return (@import("std").zig.c_translation.cast([*c]varattrib_4b, PTR).*.va_4byte.va_header >> @as(c.uint32, 2)) & @import("std").zig.c_translation.promoteIntLiteral(c.uint32, 0x3FFFFFFF, .hex); + return (@import("std").zig.c_translation.cast([*c]varattrib_4b, PTR).*.va_4byte.va_header >> @as(pg.uint32, 2)) & @import("std").zig.c_translation.promoteIntLiteral(pg.uint32, 0x3FFFFFFF, .hex); } -pub inline fn VARSIZE_1B(PTR: anytype) @TypeOf((@import("std").zig.c_translation.cast([*c]varattrib_1b, PTR).*.va_header >> @as(c.uint32, 1)) & @as(c.uint32, 0x7F)) { - return (@import("std").zig.c_translation.cast([*c]varattrib_1b, PTR).*.va_header >> @as(c.uint32, 1)) & @as(c.uint32, 0x7F); +pub inline fn VARSIZE_1B(PTR: anytype) @TypeOf((@import("std").zig.c_translation.cast([*c]varattrib_1b, PTR).*.va_header >> @as(pg.uint32, 1)) & @as(pg.uint32, 0x7F)) { + return (@import("std").zig.c_translation.cast([*c]varattrib_1b, PTR).*.va_header >> @as(pg.uint32, 1)) & @as(pg.uint32, 0x7F); } pub inline fn VARTAG_1B_E(PTR: anytype) @TypeOf(@import("std").zig.c_translation.cast([*c]varattrib_1b_e, PTR).*.va_tag) {