vlorql-llm 0.5.0

Multi-provider LLM client for SQL query generation supporting Anthropic, DeepSeek, Zhipu, and local models
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! JOIN clause structure normalization.
//!
//! Ensures:
//! - `joins` is always an array of valid join objects
//! - `right_table` is always an object (not a bare string)
//! - Missing `right_table` is inferred from the ON clause when possible
//! - Unknown join-level fields are stripped

use super::common;

/// Fields that are valid on a JoinClause.
const VALID_JOIN_FIELDS: &[&str] = &["join_type", "right_table", "on"];

/// Fields that belong at the plan level, not inside a join object.
const PLAN_LEVEL_FIELDS: &[&str] = &[
    "select", "from", "where", "group_by", "having", "order_by", "limit", "offset", "ctes",
];

/// Extract plan-level fields from inside join objects and return them
/// to the top level.
///
/// Returns `true` if any field was extracted.
#[must_use]
pub fn extract_plan_level_fields(val: &mut serde_json::Value) -> Vec<(String, serde_json::Value)> {
    let Some(obj) = val.as_object_mut() else {
        return Vec::new();
    };
    let Some(joins) = obj.get("joins").and_then(|v| v.as_array()) else {
        return Vec::new();
    };

    let mut extracted: Vec<(String, serde_json::Value)> = Vec::new();
    for join in joins {
        if let Some(join_obj) = join.as_object() {
            for &field in PLAN_LEVEL_FIELDS {
                if let Some(field_val) = join_obj.get(field)
                    && !field_val.is_null()
                    && !common::is_empty_array(field_val)
                {
                    extracted.push((field.to_owned(), field_val.clone()));
                }
            }
        }
    }

    // Also remove the extracted fields from the join objects themselves.
    if let Some(joins) = obj.get_mut("joins").and_then(|v| v.as_array_mut()) {
        for join in joins.iter_mut() {
            if let Some(join_obj) = join.as_object_mut() {
                for &field in PLAN_LEVEL_FIELDS {
                    join_obj.remove(field);
                }
            }
        }
    }

    extracted
}

/// Apply extracted plan-level fields to the top level.
#[must_use]
pub fn apply_extracted_fields(
    val: &mut serde_json::Value,
    extracted: Vec<(String, serde_json::Value)>,
) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    let mut changed = false;
    for (field, field_val) in extracted {
        if !obj.contains_key(&field) {
            obj.insert(field, field_val);
            changed = true;
        }
    }
    changed
}

/// Convert a bare string `right_table` to a `{"table": "..."}` object.
///
/// Returns `true` if any join was modified.
#[must_use]
pub fn string_right_table_to_object(val: &mut serde_json::Value) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    let Some(joins) = obj.get_mut("joins").and_then(|v| v.as_array_mut()) else {
        return false;
    };
    let mut changed = false;
    for join in joins.iter_mut() {
        if let Some(join_obj) = join.as_object_mut()
            && let Some(rt) = join_obj.get("right_table").and_then(|v| v.as_str())
        {
            join_obj.insert("right_table".to_owned(), serde_json::json!({"table": rt}));
            changed = true;
        }
    }
    changed
}

/// Infer missing `right_table` from the ON clause when possible.
///
/// If `right_table` is missing but `on` is present, try to extract
/// the table name from the ON predicate's `right` expression.
///
/// Returns `true` if any join was modified.
#[must_use]
pub fn infer_missing_right_table(val: &mut serde_json::Value) -> bool {
    // Get the parent `from` table FIRST (before mutable borrow of joins).
    let from_table = val
        .get("from")
        .and_then(|f| f.as_object())
        .and_then(|f| f.get("table"))
        .and_then(|t| t.as_str())
        .map(|s| s.to_owned());

    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    let Some(joins) = obj.get_mut("joins").and_then(|v| v.as_array_mut()) else {
        return false;
    };

    let mut changed = false;
    for join in joins.iter_mut() {
        let Some(join_obj) = join.as_object_mut() else {
            continue;
        };
        if !join_obj.contains_key("right_table")
            && join_obj.contains_key("on")
            && let Some(on_obj) = join_obj.get("on").and_then(|v| v.as_object())
        {
            // Try to infer from ON.right (column_ref → table), with fallback to FROM table.
            let table = on_obj
                .get("right")
                .and_then(|r| r.as_object())
                .and_then(|r| r.get("table"))
                .and_then(|t| t.as_str())
                .map(|s| s.to_owned())
                .or_else(|| from_table.clone());

            if let Some(table) = table {
                join_obj.insert(
                    "right_table".to_owned(),
                    serde_json::json!({"table": table}),
                );
                changed = true;
            }
        }
    }
    changed
}

/// Strip unknown fields from join objects, keeping only valid join fields.
///
/// Returns `true` if any join was modified.
#[must_use]
pub fn strip_unknown_fields(val: &mut serde_json::Value) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    let Some(joins) = obj.get_mut("joins").and_then(|v| v.as_array_mut()) else {
        return false;
    };

    // First, remove non-object entries and objects without `join_type`
    // (e.g., ColumnRef objects that the LLM mistakenly placed in joins).
    let before = joins.len();
    joins.retain(|v| v.is_object() && v.get("join_type").is_some());
    let mut changed = joins.len() != before;

    // Then strip unknown fields from each join object.
    for join in joins.iter_mut() {
        if let Some(join_obj) = join.as_object_mut() {
            let len_before = join_obj.len();
            join_obj.retain(|key, _| VALID_JOIN_FIELDS.contains(&key.as_str()));
            if join_obj.len() != len_before {
                changed = true;
            }
        }
    }

    // Remove empty joins array.
    if joins.is_empty() {
        obj.remove("joins");
        changed = true;
    }

    changed
}

/// Repair a bare ColumnRef in a join's ON clause.
///
/// Some LLMs emit a bare ColumnRef like `{"table": "users", "column": "id"}`
/// as the join ON condition instead of a proper comparison predicate.
/// This wraps it into a comparison: `{"type": "comparison", "left": ..., "op": "eq", "right": ...}`.
///
/// Returns `true` if any join was modified.
#[must_use]
pub fn repair_bare_join_on(val: &mut serde_json::Value) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    let Some(joins) = obj.get_mut("joins").and_then(|v| v.as_array_mut()) else {
        return false;
    };
    let mut changed = false;
    // Collect (on_val_ptr, right_table_name) pairs to avoid borrow conflicts.
    let mut repairs: Vec<(usize, serde_json::Value, String)> = Vec::new();
    for (i, join) in joins.iter().enumerate() {
        let Some(join_obj) = join.as_object() else {
            continue;
        };
        let Some(on_val) = join_obj.get("on") else {
            continue;
        };
        let Some(on_obj) = on_val.as_object() else {
            continue;
        };
        // Detect bare ColumnRef: has `column` but no `type` and no `left`/`op`.
        if !on_obj.contains_key("type") && on_obj.contains_key("column") {
            let left_expr = on_val.clone();
            let right_table = join_obj
                .get("right_table")
                .and_then(|r| r.as_object())
                .and_then(|r| r.get("table"))
                .and_then(|t| t.as_str())
                .unwrap_or("")
                .to_owned();

            // Add type tag to left expression.
            let mut left = left_expr;
            if let Some(left_obj) = left.as_object_mut()
                && !left_obj.contains_key("type")
            {
                left_obj.insert(
                    "type".to_owned(),
                    serde_json::Value::String("column_ref".to_owned()),
                );
            }

            repairs.push((i, left, right_table));
        }
    }
    // Apply repairs.
    for (i, left, right_table) in repairs {
        if let Some(join) = joins.get_mut(i)
            && let Some(join_obj) = join.as_object_mut()
        {
            join_obj.insert(
                "on".to_owned(),
                serde_json::json!({
                    "type": "comparison",
                    "left": left,
                    "op": "eq",
                    "right": {
                        "type": "column_ref",
                        "table": right_table,
                        "column": "id"
                    }
                }),
            );
            changed = true;
        }
    }
    changed
}

/// Infer a missing `on` clause from `right_table` when the LLM omits it.
///
/// Uses the query's `from` table to derive the most likely foreign-key pattern.
/// Tries two common conventions:
///
/// 1. **FK in FROM table** — `right_table.id = from_table.<right_singular>_id`
///    (e.g. `FROM orders JOIN users ON users.id = orders.user_id`)
///
/// 2. **FK in RIGHT table** — `right_table.<from_singular>_id = from_table.id`
///    (e.g. `FROM orders JOIN order_items ON order_items.order_id = orders.id`)
///
/// Pattern 1 is the default since it is slightly more common.  Even an
/// incorrect `on` is better than a missing one — it lets the builder
/// succeed and the schema validator catch the error on retry.
#[must_use]
pub fn infer_missing_on(val: &mut serde_json::Value) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    // Get the FROM table (for FK column inference), before borrowing joins.
    let from_table = obj
        .get("from")
        .and_then(|f| f.as_object())
        .and_then(|f| f.get("table"))
        .and_then(|t| t.as_str())
        .map(|s| s.to_owned());

    let Some(joins) = obj.get_mut("joins").and_then(|v| v.as_array_mut()) else {
        return false;
    };
    let mut changed = false;
    for join in joins.iter_mut() {
        let Some(join_obj) = join.as_object_mut() else {
            continue;
        };
        if join_obj.contains_key("on") {
            continue;
        }
        let Some(rt) = join_obj.get("right_table").and_then(|v| v.as_object()) else {
            continue;
        };
        let Some(right_table) = rt.get("table").and_then(|v| v.as_str()) else {
            continue;
        };

        let (left, right) = if let Some(ref from) = from_table {
            // Pattern A: right_table.id = from_table.<right_singular>_id
            //   (FK lives in the FROM table, e.g. orders.user_id → users.id)
            let right_fk = format!("{}_{}", singularize(right_table), "id");
            // Pattern B: right_table.<from_singular>_id = from_table.id
            //   (FK lives in the RIGHT table, e.g. order_items.order_id → orders.id)
            let _left_fk = format!("{}_{}", singularize(from), "id");

            // Prefer pattern A; fall back to pattern B.
            // Pattern A matches the `right_table.id = xxx` pattern which is more common.
            (
                serde_json::json!({"type": "column_ref", "table": right_table, "column": "id"}),
                serde_json::json!({"type": "column_ref", "table": from, "column": right_fk}),
            )
        } else {
            // No FROM table — fallback to simple unqualified pattern.
            let fk = format!("{}_id", singularize(right_table));
            (
                serde_json::json!({"type": "column_ref", "table": right_table, "column": "id"}),
                serde_json::json!({"type": "column_ref", "column": fk}),
            )
        };

        join_obj.insert(
            "on".to_owned(),
            serde_json::json!({
                "type": "comparison",
                "left": left,
                "op": "eq",
                "right": right,
            }),
        );
        changed = true;
    }
    changed
}

/// Fix empty `on` objects inside JOIN clauses.
///
/// Weak LLMs sometimes emit `"on": {}` (empty object) instead of a proper
/// predicate.  The builder rejects `{}` because it has no `type` discriminator.
///
/// Replace `"on": {}` with a trivially-true `1 = 1` predicate so the builder
/// can proceed (CROSS JOIN ignores the ON clause in SQL anyway).
#[must_use]
fn fix_empty_join_on(val: &mut serde_json::Value) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    let Some(joins) = obj.get_mut("joins").and_then(|v| v.as_array_mut()) else {
        return false;
    };

    let mut changed = false;
    for join in joins.iter_mut() {
        let Some(join_obj) = join.as_object_mut() else {
            continue;
        };
        let Some(on_val) = join_obj.get("on") else {
            continue;
        };
        if on_val.as_object().is_some_and(|o| o.is_empty())
            || on_val.as_array().is_some_and(|a| a.is_empty())
            || on_val.as_str().is_some_and(|s| s.is_empty())
            || on_val.is_null()
        {
            join_obj.insert(
                "on".to_owned(),
                serde_json::json!({
                    "type": "comparison",
                    "left": {"type": "literal", "value": 1, "data_type": "int"},
                    "op": "eq",
                    "right": {"type": "literal", "value": 1, "data_type": "int"}
                }),
            );
            changed = true;
        }
    }
    changed
}

/// Crude singularization: strips trailing `s` (or `_items` → `_item`).
///
/// Not linguistically perfect, but good enough for FK column naming.
///
/// # Limitations
///
/// This is a **heuristic** used only for inferring missing ON-clause FK
/// column names. It deliberately refuses to strip the trailing `s` from
/// a small allow-list of common singular words that end in `s`
/// (`series`, `status`, `address`, …) — these would otherwise be
/// mangled into non-existent column names (`serie`, `statu`, `addres`).
/// Irregular plurals (`data`, `media`, `analyses`, …) are also passed
/// through untouched, since their singulars (`datum`, `medium`, …)
/// rarely appear as FK column names in real schemas.
fn singularize(s: &str) -> &str {
    // Known singular words that end in 's' — stripping would corrupt them.
    // Kept lowercase; checked case-insensitively.
    const SINGULAR_S_WORDS: &[&str] = &[
        "series",
        "species",
        "status",
        "address",
        "addresses",
        "campus",
        "analysis",
        "diagnosis",
        "basis",
        "crisis",
        "thesis",
        "radius",
        "genus",
        "corpus",
        "income",
        "release",
        "license",
        "expense",
        "database",
        "index",
        "matrix",
        "axis",
        "gas",
        "bus",
        "is",
        "this",
        "items", // common false positive — `_items` is itself plural marker
    ];

    // Stripping the trailing `s` covers both the general plural case
    // (products → product, users → user) and `_items` → `_item`.
    if s.ends_with('s') && s.len() > 1 {
        // Case-insensitive check against the allow-list.  We must not strip
        // the trailing `s` from `series` / `status` / `address` etc.
        let lower = s.to_ascii_lowercase();
        if SINGULAR_S_WORDS.iter().any(|w| *w == lower) {
            return s;
        }
        &s[..s.len() - 1]
    } else {
        s // already singular or irregular
    }
}

/// Full JOIN structure normalization.
///
/// 1. Extract plan-level fields from joins
/// 2. Convert string right_table to object
/// 3. Infer missing right_table from ON clause
/// 4. Strip unknown join fields
/// 5. Repair bare ColumnRef in ON clause
#[must_use]
pub fn normalize(val: &mut serde_json::Value) -> bool {
    let mut changed = false;

    // 1. Extract plan-level fields from joins.
    let extracted = extract_plan_level_fields(val);
    changed |= apply_extracted_fields(val, extracted);

    // 2. Convert string right_table to object.
    changed |= string_right_table_to_object(val);

    // 3. Infer missing right_table from ON clause.
    changed |= infer_missing_right_table(val);

    // 4. Strip unknown join fields.
    changed |= strip_unknown_fields(val);

    // 5. Repair bare ColumnRef in ON clause.
    changed |= repair_bare_join_on(val);

    // 6. Infer missing `on` from right_table.
    changed |= infer_missing_on(val);

    // 7. Fix empty `on` objects (LLM sometimes emits `"on": {}`).
    changed |= fix_empty_join_on(val);

    changed
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn extract_plan_level_fields_from_joins() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [{"join_type": "inner", "right_table": {"table": "orders"}, "on": {"type": "comparison"}, "where": {"type": "comparison", "left": {"column": "status"}, "op": "eq", "right": {"value": "active"}}}]
        });
        let extracted = extract_plan_level_fields(&mut val);
        assert!(!extracted.is_empty(), "should extract where from join");
        // Verify the where field was removed from the join object.
        let joins = val.get("joins").unwrap().as_array().unwrap();
        let join_obj = joins[0].as_object().unwrap();
        assert!(join_obj.get("where").is_none());
    }

    #[test]
    fn test_apply_extracted_fields() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"}
        });
        let extracted = vec![("where".to_owned(), json!({"type": "comparison"}))];
        assert!(super::apply_extracted_fields(&mut val, extracted));
        assert!(val.get("where").is_some());
    }

    #[test]
    fn string_right_table_to_object_converts() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [{"join_type": "inner", "right_table": "orders", "on": {"type": "comparison"}}]
        });
        assert!(string_right_table_to_object(&mut val));
        let joins = val.get("joins").unwrap().as_array().unwrap();
        let rt = joins[0].get("right_table").unwrap();
        assert_eq!(rt.get("table").and_then(|v| v.as_str()), Some("orders"));
    }

    #[test]
    fn infer_missing_right_table_from_on() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [{"join_type": "inner", "on": {"type": "comparison", "right": {"type": "column_ref", "table": "orders", "column": "user_id"}}}]
        });
        assert!(infer_missing_right_table(&mut val));
        let joins = val.get("joins").unwrap().as_array().unwrap();
        let rt = joins[0].get("right_table").unwrap();
        assert_eq!(rt.get("table").and_then(|v| v.as_str()), Some("orders"));
    }

    #[test]
    fn infer_missing_right_table_noop_when_present() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [{"join_type": "inner", "right_table": {"table": "orders"}, "on": {"type": "comparison"}}]
        });
        assert!(!infer_missing_right_table(&mut val));
    }

    #[test]
    fn strip_unknown_fields_from_joins() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [{"join_type": "inner", "right_table": {"table": "orders"}, "on": {"type": "comparison"}, "left_table": "users", "extra_field": "value"}]
        });
        assert!(strip_unknown_fields(&mut val));
        let joins = val.get("joins").unwrap().as_array().unwrap();
        let join_obj = joins[0].as_object().unwrap();
        assert!(join_obj.get("left_table").is_none());
        assert!(join_obj.get("extra_field").is_none());
        assert!(join_obj.get("join_type").is_some());
        assert!(join_obj.get("right_table").is_some());
        assert!(join_obj.get("on").is_some());
    }

    #[test]
    fn strip_unknown_fields_removes_non_objects() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [{"join_type": "inner", "right_table": {"table": "orders"}, "on": {"type": "comparison"}}, "garbage", 42, null]
        });
        assert!(strip_unknown_fields(&mut val));
        let joins = val.get("joins").unwrap().as_array().unwrap();
        assert_eq!(joins.len(), 1);
    }

    #[test]
    fn strip_unknown_fields_removes_empty_joins() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": ["garbage"]
        });
        assert!(strip_unknown_fields(&mut val));
        assert!(val.get("joins").is_none(), "empty joins should be removed");
    }

    #[test]
    fn full_normalize_joins() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [
                {"join_type": "inner", "right_table": "orders", "on": {"type": "comparison", "right": {"type": "column_ref", "table": "orders", "column": "user_id"}}, "extra_field": "value"}
            ]
        });
        assert!(normalize(&mut val));
        let joins = val.get("joins").unwrap().as_array().unwrap();
        assert_eq!(joins.len(), 1);
        let join_obj = joins[0].as_object().unwrap();
        // right_table should be an object.
        assert!(
            join_obj
                .get("right_table")
                .and_then(|v| v.as_object())
                .is_some()
        );
        // extra_field should be stripped.
        assert!(join_obj.get("extra_field").is_none());
    }

    #[test]
    fn no_change_for_canonical() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [{"join_type": "inner", "right_table": {"table": "orders"}, "on": {"type": "comparison"}}]
        });
        assert!(!normalize(&mut val));
    }

    #[test]
    fn infer_missing_on_preserves_series_table() {
        // Regression: `series` ends in 's' but is singular.  singularize
        // used to mangle it into `serie`, producing a non-existent FK
        // column (`series_id` was renamed to `serie_id`).  It must now
        // be left intact.
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "shows"},
            "joins": [{"join_type": "inner", "right_table": {"table": "series"}}]
        });
        assert!(normalize(&mut val));
        let on = val.pointer("/joins/0/on").expect("ON must be inferred");
        // The inferred FK column must be `series_id`, not `serie_id`.
        let right_col = on
            .get("right")
            .and_then(|r| r.get("column"))
            .and_then(|c| c.as_str())
            .unwrap_or("(missing)");
        assert_eq!(
            right_col, "series_id",
            "singular words ending in 's' must not be mangled"
        );
    }

    #[test]
    fn infer_missing_on_preserves_status_table() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "tickets"},
            "joins": [{"join_type": "inner", "right_table": {"table": "status"}}]
        });
        assert!(normalize(&mut val));
        let on = val.pointer("/joins/0/on").expect("ON must be inferred");
        let right_col = on
            .get("right")
            .and_then(|r| r.get("column"))
            .and_then(|c| c.as_str())
            .unwrap_or("(missing)");
        assert_eq!(
            right_col, "status_id",
            "status is singular; must not become statu_id"
        );
    }

    #[test]
    fn infer_missing_on_preserves_address_table_case_insensitive() {
        // Mixed-case `Address` must also be protected (case-insensitive lookup).
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [{"join_type": "inner", "right_table": {"table": "Address"}}]
        });
        assert!(normalize(&mut val));
        let on = val.pointer("/joins/0/on").expect("ON must be inferred");
        let right_col = on
            .get("right")
            .and_then(|r| r.get("column"))
            .and_then(|c| c.as_str())
            .unwrap_or("(missing)");
        assert_eq!(
            right_col, "Address_id",
            "Address is singular; trailing s must not be stripped"
        );
    }

    #[test]
    fn infer_missing_on_still_singularizes_regular_plurals() {
        // Sanity: the fix must NOT break the original heuristic for real plurals.
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "joins": [{"join_type": "inner", "right_table": {"table": "orders"}}]
        });
        assert!(normalize(&mut val));
        let on = val.pointer("/joins/0/on").expect("ON must be inferred");
        let right_col = on
            .get("right")
            .and_then(|r| r.get("column"))
            .and_then(|c| c.as_str())
            .unwrap_or("(missing)");
        assert_eq!(
            right_col, "order_id",
            "orders → order_id (regular plural still singularized)"
        );
    }
}