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
//! Query-level structure normalization.
//!
//! Handles top-level structural fixes:
//! - Strips unknown top-level fields that serde would reject
//! - Wraps top-level `descending` + `expr` into `order_by`

/// Fields that are valid on a QueryPlan (used for stripping and lifting).
const PLAN_FIELDS: &[&str] = &[
    "select",
    "from",
    "where",
    "group_by",
    "having",
    "order_by",
    "limit",
    "offset",
    "joins",
    "ctes",
    "distinct",
    "distinct_on",
    "set_operation",
];

/// Fields that belong at the QueryPlan top level but the LLM sometimes
/// nests inside `where`.
const PLAN_LEVEL_FIELDS: &[&str] = &[
    "joins", "group_by", "having", "order_by", "limit", "offset", "ctes",
];

/// Strip unknown top-level fields that `QueryPlan` rejects.
///
/// `QueryPlan` uses `#[serde(deny_unknown_fields)]`, so fields like
/// `right`, `left`, `op`, `child`, `expr` at the plan level cause an
/// immediate deserialization error.  Remove them so the pipeline can
/// at least attempt to make `where` valid.
///
/// Returns `true` if any field was removed.
#[must_use]
pub fn strip_unknown_fields(val: &mut serde_json::Value) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    let before = obj.len();
    obj.retain(|key, _| PLAN_FIELDS.contains(&key.as_str()));
    obj.len() != before
}

/// Wrap top-level `descending` + `expr` into an `order_by` array.
///
/// The LLM sometimes emits `descending` and `expr` at the top level
/// of the QueryPlan instead of inside an `OrderByTerm` within the
/// `order_by` array.
///
/// Returns `true` if any change was made.
#[must_use]
pub fn wrap_descending_expr(val: &mut serde_json::Value) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };

    if obj.contains_key("order_by") {
        return false;
    }

    if let (Some(expr), Some(descending)) = (obj.remove("expr"), obj.remove("descending"))
        && descending.is_boolean()
    {
        let term = serde_json::json!({
            "expr": expr,
            "descending": descending,
        });
        obj.insert("order_by".to_owned(), serde_json::json!([term]));
        return true;
    }

    false
}

/// Convert string-formatted `limit` / `offset` values to numbers.
///
/// Some LLMs emit `"limit": "10"` (string) instead of `"limit": 10` (number).
/// The builder's `as_u64()` call would return `None` for a string, silently
/// dropping the limit.  This function converts string values to numbers.
///
/// Returns `true` if any field was converted.
#[must_use]
pub fn normalize_limit_offset(val: &mut serde_json::Value) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    let mut changed = false;
    for field in &["limit", "offset"] {
        if let Some(str_val) = obj.get(*field).and_then(|v| v.as_str())
            && let Ok(num) = str_val.parse::<u64>()
        {
            obj.insert(field.to_string(), serde_json::Value::Number(num.into()));
            changed = true;
        }
    }
    changed
}

/// Lift plan-level fields (joins, group_by, having, order_by, limit, offset, ctes)
/// out of a nested `where` object back to the top level.
///
/// Weak LLMs sometimes put everything inside `where`:
///   `{"where": {"type": "left", "child": ..., "joins": [...], "limit": 10, ...}}`
/// instead of keeping them as top-level siblings.
///
/// Returns `true` if any field was lifted.
#[must_use]
fn lift_nested_plan_fields(val: &mut serde_json::Value) -> bool {
    // Collect fields to lift first, with their values.
    let (lifted, type_left) = {
        let Some(obj) = val.as_object() else {
            return false;
        };
        let Some(where_obj) = obj.get("where").and_then(|v| v.as_object()) else {
            return false;
        };

        let lifted: Vec<(String, serde_json::Value)> = PLAN_LEVEL_FIELDS
            .iter()
            .filter_map(|field| {
                if !obj.contains_key(*field) {
                    where_obj
                        .get(*field)
                        .map(|v| (field.to_string(), v.clone()))
                } else {
                    None
                }
            })
            .collect();

        let type_left = where_obj.get("type").and_then(|t| t.as_str()) == Some("left")
            && where_obj.contains_key("child");

        (lifted, type_left)
    };

    if lifted.is_empty() && !type_left {
        return false;
    }

    let Some(obj) = val.as_object_mut() else {
        return false;
    };

    let mut changed = false;
    for (field, value) in lifted {
        obj.insert(field.clone(), value);
        // Remove the lifted field from `where`
        if let Some(where_obj) = obj.get_mut("where").and_then(|v| v.as_object_mut()) {
            where_obj.remove(&field);
        }
        changed = true;
    }

    // Fix `"type": "left"` → `"type": "not"` inside `where`.
    if type_left && let Some(where_obj) = obj.get_mut("where").and_then(|v| v.as_object_mut()) {
        where_obj.insert(
            "type".to_owned(),
            serde_json::Value::String("not".to_owned()),
        );
        changed = true;
    }

    changed
}

/// Remove null entries from array fields (order_by, group_by, having).
///
/// Weak LLMs sometimes emit `"order_by": [null]` or `"group_by": [null]`
/// which the builder rejects because it expects objects.
///
/// Also strips invalid predicates from `having`: entries whose `type`
/// is not a valid Predicate variant (e.g. `"order"`, `"count"`, `"sum"`,
/// `"avg"`, `"min"`, `"max"`, `"string_agg"`, `"array_agg"`).
///
/// Returns `true` if any null entries were removed.
#[must_use]
fn sanitize_null_array_entries(val: &mut serde_json::Value) -> bool {
    let Some(obj) = val.as_object_mut() else {
        return false;
    };
    let mut changed = false;
    // Aggregate function names that are NOT valid Predicate variants.
    const AGG_NAMES: &[&str] = &[
        "count",
        "sum",
        "avg",
        "min",
        "max",
        "string_agg",
        "array_agg",
        "jsonb_agg",
        "json_agg",
    ];
    // Expression types that are NOT valid Predicate variants.
    const EXPR_TYPES: &[&str] = &[
        "string",
        "integer",
        "number",
        "float",
        "boolean",
        "null",
        "literal",
        "column_ref",
        "function_call",
        "binary_op",
        "star",
        "subquery",
        "case",
        "window_function",
        "expr",
    ];
    for field in &["order_by", "group_by", "having"] {
        if let Some(arr) = obj.get_mut(*field).and_then(|v| v.as_array_mut()) {
            let before = arr.len();
            arr.retain(|v| !v.is_null());
            if arr.len() != before {
                changed = true;
            }
            // Also strip invalid predicate types from having.
            if *field == "having" {
                let before = arr.len();
                arr.retain(|v| {
                    v.as_object()
                        .and_then(|o| o.get("type").and_then(|t| t.as_str()))
                        .is_none_or(|t| {
                            t != "order" && !AGG_NAMES.contains(&t) && !EXPR_TYPES.contains(&t)
                        })
                });
                if arr.len() != before {
                    changed = true;
                }
            }
            // Strip aggregate function calls from group_by — they are not
            // valid GROUP BY expressions.
            if *field == "group_by" {
                let before = arr.len();
                arr.retain(|v| {
                    v.as_object()
                        .and_then(|o| o.get("name").and_then(|n| n.as_str()))
                        .is_none_or(|name| !AGG_NAMES.contains(&name))
                });
                if arr.len() != before {
                    changed = true;
                }
            }
        }
        // Handle the case where `having`/`where` is a direct object with an
        // invalid predicate type (not inside an array).
        // Uses a whitelist of valid Predicate variants — anything else is
        // an LLM hallucination and should be stripped.
        const VALID_PRED_TYPES: &[&str] = &[
            "comparison",
            "and",
            "or",
            "not",
            "between",
            "in",
            "like",
            "is_null",
            "exists",
            "true",
            "false",
        ];
        if *field == "having" || *field == "where" {
            let field_key = *field;
            if let Some(val) = obj.get_mut(field_key)
                && let Some(o) = val.as_object()
                && let Some(type_str) = o.get("type").and_then(|t| t.as_str())
                && !VALID_PRED_TYPES.contains(&type_str)
            {
                obj.remove(field_key);
                changed = true;
            }
        }
    }
    changed
}

/// Sanitize string values that contain JSON syntax residuals from
/// corrupted LLM output (e.g. `"type':'column_ref'}]}};{"` inside a
/// column name). Removes characters that have no place in a natural
/// language identifier.
///
/// Scans the entire Value tree recursively.
#[must_use]
pub fn sanitize_strings(val: &mut serde_json::Value) -> bool {
    let mut changed = false;
    sanitize_strings_impl(val, &mut changed);
    changed
}

fn sanitize_strings_impl(val: &mut serde_json::Value, changed: &mut bool) {
    match val {
        serde_json::Value::String(s) => {
            // 1. Strip single quotes and backticks (JSON syntax residuals).
            let cleaned: String = s.chars().filter(|&c| c != '\'' && c != '`').collect();
            if cleaned.len() != s.len() {
                *s = cleaned;
                *changed = true;
            }
            // 2. Try to parse strings that look like inline JSON objects
            //    (e.g. `{table:orders,column:user_id}` or `{'table':'orders'}`)
            //    and convert them to proper JSON Values.
            if s.starts_with('{') && s.contains(':') {
                // Replace single quotes with double quotes for valid JSON.
                let fixed: String = s
                    .replace('\'', "\"")
                    .replace("None", "null")
                    .replace("True", "true")
                    .replace("False", "false");
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&fixed)
                    && (parsed.is_object() || parsed.is_array())
                {
                    *val = parsed;
                    *changed = true;
                }
            }
        }
        serde_json::Value::Object(map) => {
            for v in map.values_mut() {
                sanitize_strings_impl(v, changed);
            }
        }
        serde_json::Value::Array(arr) => {
            for v in arr.iter_mut() {
                sanitize_strings_impl(v, changed);
            }
        }
        _ => {}
    }
}

/// Full query-level structure normalization.
///
/// 1. Sanitize garbled strings in the entire tree.
/// 2. Wrap top-level `descending` + `expr` into `order_by` (must run
///    before `strip_unknown_fields` so these fields are preserved).
/// 3. Lift nested plan fields from `where` back to top level.
/// 4. Strip unknown top-level fields.
/// 5. Remove null entries from array fields.
/// 6. Normalize string limit/offset to numbers.
#[must_use]
pub fn normalize(val: &mut serde_json::Value) -> bool {
    let mut changed = false;
    // Sanitize garbled strings first, before any structural normalizations.
    changed |= sanitize_strings(val);
    // Wrap first: expr + descending → order_by, before they get stripped.
    changed |= wrap_descending_expr(val);
    // Lift plan fields from within `where` before stripping.
    changed |= lift_nested_plan_fields(val);
    // Then strip remaining unknown fields.
    changed |= strip_unknown_fields(val);
    // Remove null entries from array fields.
    changed |= sanitize_null_array_entries(val);
    // Normalize string limit/offset to numbers.
    changed |= normalize_limit_offset(val);
    changed
}

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

    #[test]
    fn strip_unknown_fields_removes_extra() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "right": {"column": "id"},
            "left": {"column": "name"},
            "op": "eq"
        });
        assert!(strip_unknown_fields(&mut val));
        assert!(val.get("select").is_some());
        assert!(val.get("from").is_some());
        assert!(val.get("right").is_none());
        assert!(val.get("left").is_none());
        assert!(val.get("op").is_none());
    }

    #[test]
    fn strip_unknown_fields_noop_when_clean() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"}
        });
        assert!(!strip_unknown_fields(&mut val));
    }

    #[test]
    fn wrap_descending_expr_into_order_by() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "expr": {"column": "name"},
            "descending": true
        });
        assert!(wrap_descending_expr(&mut val));
        assert!(val.get("order_by").is_some());
        assert!(val.get("expr").is_none());
        assert!(val.get("descending").is_none());
        let order_by = val.get("order_by").unwrap().as_array().unwrap();
        assert_eq!(order_by.len(), 1);
        assert_eq!(
            order_by[0]
                .get("expr")
                .and_then(|v| v.get("column"))
                .and_then(|v| v.as_str()),
            Some("name")
        );
        assert_eq!(
            order_by[0].get("descending").and_then(|v| v.as_bool()),
            Some(true)
        );
    }

    #[test]
    fn wrap_descending_expr_noop_when_order_by_exists() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "order_by": [{"expr": {"column": "name"}, "descending": true}],
            "expr": {"column": "name"},
            "descending": true
        });
        assert!(!wrap_descending_expr(&mut val));
    }

    #[test]
    fn wrap_descending_expr_noop_when_missing_fields() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"}
        });
        assert!(!wrap_descending_expr(&mut val));
    }

    #[test]
    fn full_normalize() {
        let mut val = json!({
            "select": [{"type": "star"}],
            "from": {"table": "users"},
            "right": {"column": "id"},
            "expr": {"column": "name"},
            "descending": true
        });
        assert!(normalize(&mut val));
        // Unknown fields stripped.
        assert!(val.get("right").is_none());
        // expr + descending wrapped into order_by.
        assert!(val.get("order_by").is_some());
        assert!(val.get("expr").is_none());
        assert!(val.get("descending").is_none());
    }

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