aboutsummaryrefslogtreecommitdiff
path: root/src/conn/conn.zig
blob: fbde06c8e397c2e40ec159b531332800fca50df0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
const std = @import("std");
const log = std.log.scoped(.pgz);
const SSHashMap = std.StringHashMap([]const u8);
const Config = @import("config.zig");
const proto = @import("../proto/proto.zig");
const StartupMessage = proto.StartupMessage;
const PasswordMessage = proto.PasswordMessage;
const BackendMessage = proto.BackendMessage;
const RowDescription = proto.RowDescription;
const read_message = proto.read_message;
const ProtocolError = @import("../main.zig").ProtocolError;
const ServerError = @import("../main.zig").ServerError;
const ClientError = @import("../main.zig").ClientError;
const diagnosticReader = @import("../main.zig").diagnosticReader;

const Conn = @This();

const ConnStatus = enum {
    connStatusUninitialized,
    connStatusConnecting,
    connStatusClosed,
    connStatusIdle,
    connStatusBusy,
};

allocator: std.mem.Allocator,
stream: std.net.Stream,
config: Config,
status: ConnStatus = .connStatusUninitialized,

pub fn connect(config: Config) !Conn {
    const allocator = config.allocator;
    var stream = switch (config.address) {
        .net => |addr| try std.net.tcpConnectToAddress(addr),
        .unix => |path| try std.net.connectUnixSocket(path),
    };
    var res = Conn{
        .allocator = allocator,
        .stream = stream,
        .config = config,
    };
    errdefer res.deinit();
    var writer = stream.writer();
    var dr = diagnosticReader(100, stream.reader());
    var reader = dr.reader();
    _ = reader;
    var params = SSHashMap.init(allocator);
    try params.put("user", config.user);
    if (config.database) |database| try params.put("database", database);
    var sm = StartupMessage{
        .parameters = params,
    };
    defer sm.deinit(allocator);
    try sm.write(allocator, writer);
    lp: while (true) {
        var anymsg = try res.receive_message();
        defer anymsg.deinit(allocator);
        switch (anymsg) {
            .ReadyForQuery => {
                break :lp;
            },
            .AuthenticationRequest => |ar| {
                switch (ar.inner_type) {
                    .AuthRequestTypeOk => {},
                    .AuthRequestTypeCleartextPassword => {
                        if (config.password) |password| {
                            const pm = PasswordMessage{ .password = password };
                            try pm.write(allocator, writer);
                        } else {
                            return ClientError.NoPasswordSupplied;
                        }
                    },
                }
            },
            else => {
                // deliberately do nothing, we must wait for ready before the connection can be used.
            },
        }
    }
    return res;
}

// Messages should always be received through this function.
// this'll handle generic stuff that should happen on the connection
fn receive_message(self: *Conn) !BackendMessage {
    var anymsg = try read_message(self.allocator, self.stream.reader());
    errdefer anymsg.deinit(self.allocator);
    switch (anymsg) {
        .ReadyForQuery => {
            // TODO handle TxStatus
        },
        .ParameterStatus => {
            // TODO handle parameter status
        },
        .ErrorResponse => |err| {
            if (std.mem.eql(u8, err.severity, "FATAL")) {
                self.status = .connStatusClosed;
                // TODO close the connection here? But it should really be the caller's responsiblilty
                return ServerError.ErrorResponse;
            }
        },
        // .NoticeResponse => {
        //     // TODO handle notice response
        // },
        // .NotificationResponse => {
        //     // TODO handle notificationResponse
        // },
        .BackendKeyData => {
            // TODO handle backend key data
        },
        else => {
            // deliberately do nothing, caller can presumably handle them.
        },
    }
    return anymsg;
}

pub fn deinit(self: *Conn) void {
    self.stream.close();
}

pub const ResultIterator = struct {
    conn: *Conn,
    multi_iterator: ?*MultiResultIterator = null,
    row_description: ?proto.RowDescription = null,
    current_datarow: ?proto.DataRow = null,
    command_complete: ?proto.CommandComplete = null,
    pub fn deinit(self: *ResultIterator) void {
        if (self.row_description != null) self.row_description.?.deinit(self.conn.allocator);
        if (self.current_datarow != null) self.current_datarow.?.deinit(self.conn.allocator);
        if (self.command_complete != null) self.command_complete.?.deinit(self.conn.allocator);
    }
    // NextRow advances the ResultIterator to the next row and returns true if a row is available.
    pub fn next_row(self: *ResultIterator) !bool {
        while (self.command_complete == null) {
            var msg = try self.conn.receive_message();
            switch (msg) {
                .DataRow => |dr| {
                    if (self.row_description != null) self.row_description.?.deinit(self.conn.allocator);
                    self.current_datarow = dr;
                    return true;
                },
                .RowDescription => |rd| {
                    if (self.row_description != null) return ProtocolError.UnexpectedMessage;
                    self.row_description = rd;
                },
                .CommandComplete => |cc| {
                    if (self.command_complete != null) return ProtocolError.UnexpectedMessage;
                    self.command_complete = cc;
                },
                else => {
                    msg.deinit(self.conn.allocator);
                },
            }
        }
        return false;
    }
    // row returns the current row data
    pub fn row(self: ResultIterator) ?[][]const u8 {
        return if (self.current_datarow) |dr| dr.columns else null;
    }
};

pub const MultiResultIterator = struct {
    conn: *Conn,
    cri: ?*ResultIterator = null,

    pub fn next_result(self: *MultiResultIterator) !bool {
        if ()
    }

    pub fn result(self: MultiResultIterator) ?*ResultIterator {
        return self.cri;
    }
    fn receive_message(self: *MultiResultIterator) !BackendMessage {
        _ = self;
        return error.NotImplemented;
    }
};

// pub fn exec(self: *Conn) {

// }

test "connect unix" {
    // must have a local postgres runnning
    // TODO maybe use docker to start one?
    const allocator = std.testing.allocator;
    const cfg = Config{
        .allocator = allocator,
        .address = .{ .unix = "/run/postgresql/.s.PGSQL.5432" },
        .database = "martin",
        .user = "martin",
    };
    var conn = try Conn.connect(cfg);
    defer conn.deinit();
}

test "connect tcp with password" {
    const allocator = std.testing.allocator;
    const cfg = Config{
        .allocator = allocator,
        .address = .{ .net = std.net.Address{ .in = std.net.Ip4Address.init([4]u8{ 127, 0, 0, 1 }, 5432) } },
        .database = "martin",
        .user = "martin",
        .password = "martin",
    };
    var conn = try Conn.connect(cfg);
    defer conn.deinit();
}

test "connect tcp with wrong password" {
    // TODO how to disable failing tests on error log
    // const allocator = std.testing.allocator;
    // const cfg = Config{
    //     .allocator = allocator,
    //     .address = .{ .net = std.net.Address{ .in = std.net.Ip4Address.init([4]u8{ 127, 0, 0, 1 }, 5432) } },
    //     .database = "martin",
    //     .user = "martin",
    //     .password = "foobar",
    // };
    // try std.testing.expectError(ServerError.ErrorResponse, Conn.connect(cfg));
}