From fada72cd26ad31e1fc834788c1224ed05a78143b Mon Sep 17 00:00:00 2001 From: Martin Ashby Date: Fri, 29 Sep 2023 09:44:54 +0100 Subject: Generify ErrorResponse to allow for NoticeResponse which shares it's structure. Add a very basic test for running an actual query --- src/proto/proto.zig | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'src/proto/proto.zig') diff --git a/src/proto/proto.zig b/src/proto/proto.zig index 9025347..261ed9e 100644 --- a/src/proto/proto.zig +++ b/src/proto/proto.zig @@ -1,8 +1,11 @@ const std = @import("std"); +const ByteArrayList = std.ArrayList(u8); +const log = std.log.scoped(.pgz); pub const StartupMessage = @import("startup_message.zig"); pub const AuthenticationRequest = @import("authentication_request.zig"); pub const PasswordMessage = @import("password_message.zig"); -pub const ErrorResponse = @import("error_response.zig"); +pub const ErrorResponse = @import("error_response.zig").ErrorNoticeResponse('E'); +pub const NoticeResponse = @import("error_response.zig").ErrorNoticeResponse('N'); pub const ReadyForQuery = @import("ready_for_query.zig"); pub const ParameterStatus = @import("parameter_status.zig"); pub const BackendKeyData = @import("backend_key_data.zig"); @@ -20,6 +23,7 @@ const ProtocolError = @import("../main.zig").ProtocolError; pub const BackendMessage = union(enum) { AuthenticationRequest: AuthenticationRequest, ErrorResponse: ErrorResponse, + NoticeResponse: NoticeResponse, ReadyForQuery: ReadyForQuery, ParameterStatus: ParameterStatus, BackendKeyData: BackendKeyData, @@ -58,10 +62,27 @@ pub fn read_message(allocator: std.mem.Allocator, stream_reader: anytype) !Backe } } else { allocator.free(buf); + log.err("InvalidMessageType {c}", .{tag}); return ProtocolError.InvalidMessageType; } } +// Caller owns the resulting message. +// 'self' must be one of the message types above. +pub fn clone_message(self: anytype, a: std.mem.Allocator) !@TypeOf(self) { + var ba = ByteArrayList.init(a); + defer ba.deinit(); + try self.write(a, ba.writer()); + var fbs = std.io.fixedBufferStream(ba.items); + var reader = fbs.reader(); + _ = try reader.readByte(); + const len = try reader.readIntBig(u32); + var buf = try a.alloc(u8, len-4); + errdefer a.free(buf); + try reader.readNoEof(buf); + return try @TypeOf(self).read(a, buf); +} + test { _ = AuthenticationRequest; _ = PasswordMessage; -- cgit v1.2.3-ZIG