qail-pg 0.27.10

Rust PostgreSQL driver for typed AST queries with direct wire-protocol execution
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! PG Protocol Encoder Chaos Test
//!
//! Tests every Action variant in the AST encoder to ensure
//! none panic. Also tests edge-case ASTs with empty/huge columns,
//! deep filter chains, and boundary parameter counts.

use qail_core::ast::*;
use qail_pg::protocol::EncodeError;
use qail_pg::protocol::ast_encoder::AstEncoder;

#[allow(unused_variables, unused_assignments)]
fn main() {
    let mut pass = 0u32;
    let mut fail = 0u32;
    let panics = 0u32;

    println!("═══════════════════════════════════════════════════");
    println!("  🧪 PG ENCODER CHAOS TEST");
    println!("═══════════════════════════════════════════════════");

    // ═══════════════════════════════════════════════════
    // 1. All DML Actions — must not panic
    // ═══════════════════════════════════════════════════
    println!("\n── 1. DML Action Encoding (must not panic) ──");

    let dml_tests: Vec<(&str, Qail)> = vec![
        ("GET basic", Qail::get("users")),
        (
            "GET with columns",
            Qail::get("users").columns(vec!["id", "name"]),
        ),
        (
            "GET with filter",
            Qail::get("users").filter("id", Operator::Eq, Value::String("abc".into())),
        ),
        ("GET with limit", Qail::get("users").limit(10)),
        ("GET with offset", Qail::get("users").offset(20)),
        ("GET with limit 0", Qail::get("users").limit(0)),
        ("GET with huge limit", Qail::get("users").limit(999999999)),
        ("GET with sort", Qail::get("users").order_asc("name")),
        (
            "GET with sort desc",
            Qail::get("users").order_desc("created_at"),
        ),
        ("CNT basic", {
            let mut q = Qail::get("users");
            q.action = Action::Cnt;
            q
        }),
        ("CNT with filter", {
            let mut q = Qail::get("users").filter("active", Operator::Eq, Value::Bool(true));
            q.action = Action::Cnt;
            q
        }),
        (
            "ADD basic",
            Qail::add("users").set_value("name", Value::String("test".into())),
        ),
        ("ADD multiple values", {
            Qail::add("users")
                .set_value("name", Value::String("test".into()))
                .set_value("age", Value::Int(25))
                .set_value("active", Value::Bool(true))
        }),
        (
            "SET basic",
            Qail::set("users")
                .set_value("name", Value::String("updated".into()))
                .filter("id", Operator::Eq, Value::String("abc".into())),
        ),
        (
            "DEL basic",
            Qail::del("users").filter("id", Operator::Eq, Value::String("abc".into())),
        ),
        // Edge: empty columns (SELECT *)
        ("GET empty columns", Qail::get("users")),
        // Edge: many columns
        ("GET 100 columns", {
            let cols: Vec<&str> = (0..100).map(|_| "col").collect();
            Qail::get("users").columns(cols)
        }),
        // Edge: chained filters
        ("GET 10 filters", {
            let mut q = Qail::get("users");
            for i in 0..10 {
                q = q.filter(format!("f{}", i), Operator::Eq, Value::Int(i));
            }
            q
        }),
        // Edge: all operators
        (
            "GET filter Eq",
            Qail::get("t").filter("a", Operator::Eq, Value::Int(1)),
        ),
        (
            "GET filter Neq",
            Qail::get("t").filter("a", Operator::Ne, Value::Int(1)),
        ),
        (
            "GET filter Gt",
            Qail::get("t").filter("a", Operator::Gt, Value::Int(1)),
        ),
        (
            "GET filter Gte",
            Qail::get("t").filter("a", Operator::Gte, Value::Int(1)),
        ),
        (
            "GET filter Lt",
            Qail::get("t").filter("a", Operator::Lt, Value::Int(1)),
        ),
        (
            "GET filter Lte",
            Qail::get("t").filter("a", Operator::Lte, Value::Int(1)),
        ),
        (
            "GET filter IsNull",
            Qail::get("t").filter("a", Operator::IsNull, Value::Null),
        ),
        (
            "GET filter IsNotNull",
            Qail::get("t").filter("a", Operator::IsNotNull, Value::Null),
        ),
        (
            "GET filter Like",
            Qail::get("t").filter("a", Operator::Like, Value::String("%test%".into())),
        ),
        (
            "GET filter ILike",
            Qail::get("t").filter("a", Operator::ILike, Value::String("%test%".into())),
        ),
        (
            "GET filter In",
            Qail::get("t").filter("a", Operator::In, Value::String("1,2,3".into())),
        ),
        (
            "GET filter NotIn",
            Qail::get("t").filter("a", Operator::NotIn, Value::String("1,2,3".into())),
        ),
        // Edge: value types
        ("ADD with null", Qail::add("t").set_value("a", Value::Null)),
        (
            "ADD with bool true",
            Qail::add("t").set_value("a", Value::Bool(true)),
        ),
        (
            "ADD with bool false",
            Qail::add("t").set_value("a", Value::Bool(false)),
        ),
        (
            "ADD with float",
            Qail::add("t").set_value("a", Value::Float(9.87654)),
        ),
        (
            "ADD with negative int",
            Qail::add("t").set_value("a", Value::Int(-42)),
        ),
        (
            "ADD with i64 max",
            Qail::add("t").set_value("a", Value::Int(i64::MAX)),
        ),
        (
            "ADD with i64 min",
            Qail::add("t").set_value("a", Value::Int(i64::MIN)),
        ),
        (
            "ADD with empty string",
            Qail::add("t").set_value("a", Value::String("".into())),
        ),
        (
            "ADD with long string",
            Qail::add("t").set_value("a", Value::String("x".repeat(10000))),
        ),
        (
            "ADD with unicode",
            Qail::add("t").set_value("a", Value::String("中文🚀مرحبا".into())),
        ),
        (
            "ADD with single quotes",
            Qail::add("t").set_value("a", Value::String("it's a test".into())),
        ),
        (
            "ADD with backslash",
            Qail::add("t").set_value("a", Value::String("path\\to\\file".into())),
        ),
        // Edge: positional params
        (
            "GET with $1",
            Qail::get("t").filter("id", Operator::Eq, Value::Param(1)),
        ),
        (
            "GET with $0",
            Qail::get("t").filter("id", Operator::Eq, Value::Param(0)),
        ),
        (
            "GET with $9999",
            Qail::get("t").filter("id", Operator::Eq, Value::Param(9999)),
        ),
        // Edge: named params
        (
            "GET with :name",
            Qail::get("t").filter("id", Operator::Eq, Value::NamedParam("name".into())),
        ),
        // Edge: joins
        (
            "GET with INNER JOIN",
            Qail::get("users").join(JoinKind::Inner, "orders", "users.id", "orders.user_id"),
        ),
        (
            "GET with LEFT JOIN",
            Qail::get("users").join(JoinKind::Left, "orders", "users.id", "orders.user_id"),
        ),
        (
            "GET with RIGHT JOIN",
            Qail::get("users").join(JoinKind::Right, "orders", "users.id", "orders.user_id"),
        ),
        (
            "GET with FULL JOIN",
            Qail::get("users").join(JoinKind::Full, "orders", "users.id", "orders.user_id"),
        ),
        (
            "GET with CROSS JOIN",
            Qail::get("users").join(JoinKind::Cross, "orders", "users.id", "orders.user_id"),
        ),
        // Edge: aggregates
        ("GET with COUNT(*)", {
            let mut q = Qail::get("users");
            q.columns = vec![Expr::Aggregate {
                col: "*".to_string(),
                func: AggregateFunc::Count,
                distinct: false,
                filter: None,
                alias: None,
            }];
            q
        }),
        ("GET with SUM", {
            let mut q = Qail::get("users");
            q.columns = vec![Expr::Aggregate {
                col: "amount".to_string(),
                func: AggregateFunc::Sum,
                distinct: false,
                filter: None,
                alias: None,
            }];
            q
        }),
        ("GET with COUNT DISTINCT", {
            let mut q = Qail::get("users");
            q.columns = vec![Expr::Aggregate {
                col: "email".to_string(),
                func: AggregateFunc::Count,
                distinct: true,
                filter: None,
                alias: None,
            }];
            q
        }),
    ];

    for (label, cmd) in &dml_tests {
        // Test encode_cmd (wire protocol)
        match AstEncoder::encode_cmd(cmd) {
            Ok(_) => pass += 1,
            Err(e) => {
                println!("  ❌ encode_cmd Err on '{}': {}", label, e);
                fail += 1;
            }
        }

        // Test encode_cmd_sql (SQL string)
        match AstEncoder::encode_cmd_sql(cmd) {
            Ok(_) => pass += 1,
            Err(e) => {
                println!("  ❌ encode_cmd_sql Err on '{}': {}", label, e);
                fail += 1;
            }
        }
    }
    println!(
        "{}/{} DML encode tests passed (x2 for wire+sql)",
        pass,
        dml_tests.len() * 2
    );

    // ═══════════════════════════════════════════════════
    // 2. DDL Actions — must not panic
    // ═══════════════════════════════════════════════════
    println!("\n── 2. DDL Action Encoding ──");
    let ddl_start = pass;

    let ddl_tests: Vec<(&str, Qail)> = vec![
        ("MAKE table", {
            let mut q = Qail::get("users");
            q.action = Action::Make;
            q.columns = vec![Expr::Named("id".into()), Expr::Named("name".into())];
            q
        }),
        ("DROP table", {
            let mut q = Qail::get("users");
            q.action = Action::Drop;
            q
        }),
        ("INDEX", {
            let mut q = Qail::get("users");
            q.action = Action::Index;
            q.columns = vec![Expr::Named("email".into())];
            q
        }),
        ("DROP INDEX", {
            let mut q = Qail::get("users_email_idx");
            q.action = Action::DropIndex;
            q
        }),
        ("ALTER add column", {
            let mut q = Qail::get("users");
            q.action = Action::Alter;
            q.columns = vec![Expr::Named("phone".into())];
            q
        }),
        ("ALTER drop column", {
            let mut q = Qail::get("users");
            q.action = Action::AlterDrop;
            q.columns = vec![Expr::Named("phone".into())];
            q
        }),
        ("CREATE VIEW", {
            let mut q = Qail::get("active_users");
            q.action = Action::CreateView;
            q
        }),
        ("DROP VIEW", {
            let mut q = Qail::get("active_users");
            q.action = Action::DropView;
            q
        }),
    ];

    for (label, cmd) in &ddl_tests {
        match AstEncoder::encode_cmd(cmd) {
            Ok(_) | Err(_) => pass += 1, // DDL may be unsupported; both Ok and Err are fine
        }
    }
    println!(
        "{}/{} DDL encode tests passed",
        pass - ddl_start,
        ddl_tests.len()
    );

    // ═══════════════════════════════════════════════════
    // 3. Unsupported Actions — should not panic
    // ═══════════════════════════════════════════════════
    println!("\n── 3. Unsupported/Exotic Actions (should not panic) ──");
    let exotic_start = pass;

    let exotic_actions = vec![
        Action::Truncate,
        Action::Explain,
        Action::ExplainAnalyze,
        Action::Lock,
        Action::CreateMaterializedView,
        Action::RefreshMaterializedView,
        Action::DropMaterializedView,
        Action::Listen,
        Action::Notify,
        Action::Unlisten,
        Action::Savepoint,
        Action::ReleaseSavepoint,
        Action::RollbackToSavepoint,
        Action::Search,
        Action::Upsert,
        Action::Scroll,
        Action::CreateCollection,
        Action::DeleteCollection,
        Action::CreateFunction,
        Action::DropFunction,
        Action::CreateTrigger,
        Action::DropTrigger,
        Action::CreateExtension,
        Action::DropExtension,
        Action::CommentOn,
        Action::CreateSequence,
        Action::DropSequence,
        Action::CreateEnum,
        Action::DropEnum,
        Action::AlterEnumAddValue,
        Action::TxnStart,
        Action::TxnCommit,
        Action::TxnRollback,
    ];

    let mut exotic_errs = 0u32;
    for action in &exotic_actions {
        let mut q = Qail::get("test_table");
        q.action = *action;
        match AstEncoder::encode_cmd(&q) {
            Ok(_) => pass += 1,
            Err(EncodeError::UnsupportedAction(_)) => {
                exotic_errs += 1;
                pass += 1; // Expected: unsupported actions return Err, not panic
            }
            Err(e) => {
                println!("  ❌ Unexpected Err on {:?}: {}", action, e);
                fail += 1;
            }
        }
    }
    println!(
        "  {}/{} exotic actions return UnsupportedAction (no panic)",
        exotic_errs,
        exotic_actions.len()
    );

    // ═══════════════════════════════════════════════════
    // 4. SQL String Output Validation
    // ═══════════════════════════════════════════════════
    println!("\n── 4. SQL Output Validation ──");
    let sql_tests: Vec<(&str, Qail, &str)> = vec![
        ("Simple SELECT", Qail::get("users"), "SELECT"),
        (
            "COUNT",
            {
                let mut q = Qail::get("users");
                q.action = Action::Cnt;
                q
            },
            "COUNT",
        ),
        (
            "INSERT",
            Qail::add("t").set_value("name", Value::String("x".into())),
            "INSERT",
        ),
        (
            "UPDATE",
            Qail::set("t")
                .set_value("name", Value::String("x".into()))
                .filter("id", Operator::Eq, Value::Int(1)),
            "UPDATE",
        ),
        (
            "DELETE",
            Qail::del("t").filter("id", Operator::Eq, Value::Int(1)),
            "DELETE",
        ),
    ];

    let mut sql_pass = 0u32;
    for (label, cmd, expected_keyword) in &sql_tests {
        let (sql, _params) = match AstEncoder::encode_cmd_sql(cmd) {
            Ok(x) => x,
            Err(e) => {
                println!("  ❌ encode_cmd_sql Err on '{}': {}", label, e);
                fail += 1;
                continue;
            }
        };
        if sql.contains(expected_keyword) {
            sql_pass += 1;
            pass += 1;
        } else {
            println!(
                "{} — SQL missing '{}': {}",
                label,
                expected_keyword,
                &sql[..std::cmp::min(sql.len(), 100)]
            );
            fail += 1;
        }
    }
    println!(
        "{}/{} SQL outputs contain expected keywords",
        sql_pass,
        sql_tests.len()
    );

    // ═══════════════════════════════════════════════════
    // 5. Parse → Encode integration
    // ═══════════════════════════════════════════════════
    println!("\n── 5. Parse → Encode Integration ──");
    let integration_queries = vec![
        "get users",
        "get users fields id,name",
        "get users[active = true] limit 10",
        "count users",
        "count users[active = true]",
        "add users",
        "set users[id = $1]",
        "del users[id = $1]",
        "get users sort name:asc limit 50 offset 100",
        "get users fields count(id)",
        "get users fields sum(amount)",
    ];

    let mut integ_pass = 0u32;
    for query in &integration_queries {
        match qail_core::parser::parse(query) {
            Ok(ast) => {
                match AstEncoder::encode_cmd(&ast).and_then(|_| AstEncoder::encode_cmd_sql(&ast)) {
                    Ok(_) => {
                        integ_pass += 1;
                        pass += 1;
                    }
                    Err(e) => {
                        println!("  ❌ Encode Err on parse→encode '{}': {}", query, e);
                        fail += 1;
                    }
                }
            }
            Err(e) => {
                println!("  ❌ Parse failed (skipped encode): {}{:?}", query, e);
                fail += 1;
            }
        }
    }
    println!(
        "{}/{} parse→encode integrations passed",
        integ_pass,
        integration_queries.len()
    );

    // ═══════════════════════════════════════════════════
    // SUMMARY
    // ═══════════════════════════════════════════════════
    let total = pass + fail + panics;
    println!("\n═══════════════════════════════════════════════════");
    println!("  PG Encoder Chaos Results: {} total tests", total);
    println!("{} passed", pass);
    println!("{} failed", fail);
    println!("  💀 {} PANICS", panics);
    println!("═══════════════════════════════════════════════════");

    if panics > 0 {
        // Don't exit with error for exotic/unsupported actions panicking
        // Those are expected — only flag DML/DDL panics
        println!("\n  Note: Exotic action panics are expected (unsupported in binary encoder)");
    }
}