vibesql-server 0.1.3

Network server with PostgreSQL wire protocol for VibeSQL
Documentation
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Integration tests for PostgreSQL wire protocol
//!
//! Tests message serialization/deserialization, query handling,
//! and protocol compliance.

mod common;

use common::{parse_backend_messages, start_test_server, TestClient};

/// Test query message roundtrip with simple SELECT
#[tokio::test]
async fn test_simple_query_roundtrip() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    // Complete handshake
    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    // Send a simple query
    client.send_query("SELECT 1").await.expect("Failed to send query");

    // Read query response
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read query response");
    let messages = parse_backend_messages(&data);

    // Should have RowDescription, DataRow, CommandComplete, ReadyForQuery
    assert!(
        messages.iter().any(|m| m.is_row_description()),
        "Expected RowDescription for SELECT query"
    );
    assert!(messages.iter().any(|m| m.is_data_row()), "Expected DataRow for SELECT query");
    assert!(
        messages.iter().any(|m| m.is_command_complete()),
        "Expected CommandComplete for SELECT query"
    );
    assert!(messages.iter().any(|m| m.is_ready_for_query()), "Expected ReadyForQuery after query");

    // Verify command tag
    let cmd_complete = messages.iter().find(|m| m.is_command_complete()).unwrap();
    let tag = cmd_complete.get_command_tag().expect("Failed to get command tag");
    assert!(tag.starts_with("SELECT"), "Command tag should start with SELECT, got: {}", tag);

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test empty query response
#[tokio::test]
async fn test_empty_query() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    // Send empty query
    client.send_query("").await.expect("Failed to send empty query");

    let data = client.read_until_message_type(b'Z').await.expect("Failed to read response");
    let messages = parse_backend_messages(&data);

    // Should have EmptyQueryResponse and ReadyForQuery
    assert!(
        messages.iter().any(|m| m.is_empty_query_response()),
        "Expected EmptyQueryResponse for empty query"
    );
    assert!(
        messages.iter().any(|m| m.is_ready_for_query()),
        "Expected ReadyForQuery after empty query"
    );

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test whitespace-only query (treated as empty)
#[tokio::test]
async fn test_whitespace_query() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    // Send whitespace-only query
    client.send_query("   \t\n  ").await.expect("Failed to send whitespace query");

    let data = client.read_until_message_type(b'Z').await.expect("Failed to read response");
    let messages = parse_backend_messages(&data);

    // Should have EmptyQueryResponse
    assert!(
        messages.iter().any(|m| m.is_empty_query_response()),
        "Expected EmptyQueryResponse for whitespace query"
    );

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test CREATE TABLE and INSERT roundtrip
#[tokio::test]
async fn test_ddl_and_dml_roundtrip() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    // Create table
    client
        .send_query("CREATE TABLE test_table (id INT, name VARCHAR(100))")
        .await
        .expect("Failed to send CREATE TABLE");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read CREATE response");
    let messages = parse_backend_messages(&data);
    assert!(
        messages.iter().any(|m| m.is_command_complete()),
        "Expected CommandComplete for CREATE TABLE"
    );

    // Insert data
    client
        .send_query("INSERT INTO test_table VALUES (1, 'test')")
        .await
        .expect("Failed to send INSERT");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read INSERT response");
    let messages = parse_backend_messages(&data);

    let cmd_complete = messages.iter().find(|m| m.is_command_complete()).unwrap();
    let tag = cmd_complete.get_command_tag().expect("Failed to get command tag");
    assert!(tag.starts_with("INSERT"), "Command tag should be INSERT, got: {}", tag);

    // Select data back
    client.send_query("SELECT * FROM test_table").await.expect("Failed to send SELECT");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read SELECT response");
    let messages = parse_backend_messages(&data);

    assert!(messages.iter().any(|m| m.is_row_description()));
    assert!(messages.iter().any(|m| m.is_data_row()));

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test UPDATE command roundtrip
#[tokio::test]
async fn test_update_roundtrip() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    // Create and populate table
    client
        .send_query("CREATE TABLE update_test (id INT, value INT)")
        .await
        .expect("Failed to send CREATE TABLE");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read response");

    client
        .send_query("INSERT INTO update_test VALUES (1, 10)")
        .await
        .expect("Failed to send INSERT");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read response");

    // Update data
    client
        .send_query("UPDATE update_test SET value = 20 WHERE id = 1")
        .await
        .expect("Failed to send UPDATE");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read UPDATE response");
    let messages = parse_backend_messages(&data);

    let cmd_complete = messages.iter().find(|m| m.is_command_complete()).unwrap();
    let tag = cmd_complete.get_command_tag().expect("Failed to get command tag");
    assert!(tag.starts_with("UPDATE"), "Command tag should be UPDATE, got: {}", tag);

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test DELETE command roundtrip
#[tokio::test]
async fn test_delete_roundtrip() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    // Create and populate table
    client
        .send_query("CREATE TABLE delete_test (id INT)")
        .await
        .expect("Failed to send CREATE TABLE");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read response");

    client.send_query("INSERT INTO delete_test VALUES (1)").await.expect("Failed to send INSERT");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read response");

    // Delete data
    client.send_query("DELETE FROM delete_test WHERE id = 1").await.expect("Failed to send DELETE");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read DELETE response");
    let messages = parse_backend_messages(&data);

    let cmd_complete = messages.iter().find(|m| m.is_command_complete()).unwrap();
    let tag = cmd_complete.get_command_tag().expect("Failed to get command tag");
    assert!(tag.starts_with("DELETE"), "Command tag should be DELETE, got: {}", tag);

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test multiple queries in sequence
#[tokio::test]
async fn test_multiple_queries_sequence() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    // Execute multiple queries in sequence
    for i in 0..5 {
        client.send_query(&format!("SELECT {}", i)).await.expect("Failed to send query");
        let data = client.read_until_message_type(b'Z').await.expect("Failed to read response");
        let messages = parse_backend_messages(&data);
        assert!(
            messages.iter().any(|m| m.is_ready_for_query()),
            "Each query should complete with ReadyForQuery"
        );
    }

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test ParameterStatus messages have expected parameters
#[tokio::test]
async fn test_parameter_status_messages() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");
    let messages = parse_backend_messages(&data);

    // Count ParameterStatus messages
    let param_statuses: Vec<_> = messages.iter().filter(|m| m.is_parameter_status()).collect();

    // Should have several standard parameters
    assert!(
        param_statuses.len() >= 5,
        "Expected at least 5 ParameterStatus messages, got {}",
        param_statuses.len()
    );

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test BackendKeyData is sent during startup
#[tokio::test]
async fn test_backend_key_data() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");
    let messages = parse_backend_messages(&data);

    // Should have exactly one BackendKeyData
    let key_data_count = messages.iter().filter(|m| m.is_backend_key_data()).count();
    assert_eq!(key_data_count, 1, "Expected exactly one BackendKeyData message");

    // BackendKeyData should have process_id and secret_key (8 bytes payload)
    let key_data = messages.iter().find(|m| m.is_backend_key_data()).unwrap();
    assert_eq!(key_data.payload.len(), 8, "BackendKeyData should have 8 bytes payload");

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test ReadyForQuery status indicator
#[tokio::test]
async fn test_ready_for_query_status() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");
    let messages = parse_backend_messages(&data);

    // Check ReadyForQuery status byte
    let rfq = messages.iter().find(|m| m.is_ready_for_query()).unwrap();
    assert_eq!(rfq.payload.len(), 1, "ReadyForQuery should have 1 byte payload");
    assert_eq!(rfq.payload[0], b'I', "Status should be 'I' (idle) after startup");

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test that RowDescription has correct field count
#[tokio::test]
async fn test_row_description_fields() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    // Create table with known columns
    client
        .send_query("CREATE TABLE field_test (a INT, b INT, c INT)")
        .await
        .expect("Failed to send CREATE");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read response");

    client
        .send_query("INSERT INTO field_test VALUES (1, 2, 3)")
        .await
        .expect("Failed to send INSERT");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read response");

    // Select all columns
    client.send_query("SELECT * FROM field_test").await.expect("Failed to send SELECT");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read response");
    let messages = parse_backend_messages(&data);

    let row_desc = messages.iter().find(|m| m.is_row_description()).unwrap();
    // Field count is first 2 bytes as i16
    let field_count = i16::from_be_bytes([row_desc.payload[0], row_desc.payload[1]]);
    assert_eq!(field_count, 3, "Expected 3 fields in RowDescription");

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test DataRow has correct value count matching RowDescription
#[tokio::test]
async fn test_data_row_matches_row_description() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    client
        .send_query("CREATE TABLE match_test (x INT, y INT)")
        .await
        .expect("Failed to send CREATE");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read response");

    client
        .send_query("INSERT INTO match_test VALUES (10, 20)")
        .await
        .expect("Failed to send INSERT");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read response");

    client.send_query("SELECT * FROM match_test").await.expect("Failed to send SELECT");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read response");
    let messages = parse_backend_messages(&data);

    let row_desc = messages.iter().find(|m| m.is_row_description()).unwrap();
    let data_row = messages.iter().find(|m| m.is_data_row()).unwrap();

    // Get field counts
    let desc_fields = i16::from_be_bytes([row_desc.payload[0], row_desc.payload[1]]);
    let row_fields = i16::from_be_bytes([data_row.payload[0], data_row.payload[1]]);

    assert_eq!(desc_fields, row_fields, "DataRow field count should match RowDescription");

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}

/// Test SELECT with no rows returns RowDescription but no DataRow
#[tokio::test]
async fn test_select_no_rows() {
    let server = start_test_server().await;
    let mut client = TestClient::connect(server.addr()).await.expect("Failed to connect");

    client.send_startup("testuser", "testdb").await.expect("Failed to send startup");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read startup response");

    client.send_query("CREATE TABLE empty_test (id INT)").await.expect("Failed to send CREATE");
    let _ = client.read_until_message_type(b'Z').await.expect("Failed to read response");

    // Select from empty table
    client.send_query("SELECT * FROM empty_test").await.expect("Failed to send SELECT");
    let data = client.read_until_message_type(b'Z').await.expect("Failed to read response");
    let messages = parse_backend_messages(&data);

    // Should have RowDescription but no DataRow
    assert!(
        messages.iter().any(|m| m.is_row_description()),
        "Should have RowDescription even for empty result"
    );
    assert!(!messages.iter().any(|m| m.is_data_row()), "Should not have DataRow for empty result");

    // CommandComplete should say SELECT 0
    let cmd = messages.iter().find(|m| m.is_command_complete()).unwrap();
    let tag = cmd.get_command_tag().unwrap();
    assert_eq!(tag, "SELECT 0", "Command tag should be 'SELECT 0'");

    client.send_terminate().await.expect("Failed to send terminate");
    server.shutdown();
}