qql-core 0.3.0

Parser, typed AST, validation, and transformations for the Qdrant Query Language
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
use super::ascii_equal_lower;
use crate::ast::{CollectionConfig, OptimizationThreads, Value};
use crate::error::QqlError;
use alloc::string::String;

pub fn config_value<'a>(config: &'a [(String, Value)], key: &str) -> Option<&'a Value> {
    for (k, v) in config {
        if ascii_equal_lower(k, key) {
            return Some(v);
        }
    }
    None
}

pub fn config_has_key(config: &[(String, Value)], key: &str) -> bool {
    config_value(config, key).is_some()
}

pub fn config_bool(config: &[(String, Value)], key: &str) -> Option<bool> {
    match config_value(config, key)? {
        Value::Bool(b) => Some(*b),
        _ => None,
    }
}

use crate::error::Span;

fn validation_err(
    message: impl Into<alloc::borrow::Cow<'static, str>>,
    position: usize,
) -> QqlError {
    QqlError::validation(
        "QQL-VALIDATION-CONFIG",
        message,
        Some(Span::point(position)),
    )
}

pub fn config_positive_u64(
    config: &[(String, Value)],
    key: &str,
    pos: usize,
) -> Result<Option<u64>, QqlError> {
    match config_value(config, key) {
        None => Ok(None),
        Some(Value::Int(n)) if *n > 0 => Ok(Some(*n as u64)),
        Some(Value::Float(n)) if *n > 0.0 && *n == (*n as u64) as f64 => Ok(Some(*n as u64)),
        _ => Err(validation_err(
            alloc::format!("{} must be a positive integer", key),
            pos,
        )),
    }
}

pub fn config_non_negative_u64(
    config: &[(String, Value)],
    key: &str,
    pos: usize,
) -> Result<Option<u64>, QqlError> {
    match config_value(config, key) {
        None => Ok(None),
        Some(Value::Int(n)) if *n >= 0 => Ok(Some(*n as u64)),
        Some(Value::Float(n)) if *n >= 0.0 && *n == (*n as u64) as f64 => Ok(Some(*n as u64)),
        _ => Err(validation_err(
            alloc::format!("{} must be a non-negative integer", key),
            pos,
        )),
    }
}

pub fn config_float_range(
    config: &[(String, Value)],
    key: &str,
    min: f64,
    max: f64,
) -> Option<f64> {
    match config_value(config, key)? {
        Value::Int(n) => {
            let f = *n as f64;
            if (min..=max).contains(&f) {
                Some(f)
            } else {
                None
            }
        }
        Value::Float(f) => {
            if (min..=max).contains(f) {
                Some(*f)
            } else {
                None
            }
        }
        _ => None,
    }
}

pub fn config_max_optimization_threads(
    config: &[(String, Value)],
    key: &str,
) -> Option<OptimizationThreads> {
    match config_value(config, key)? {
        Value::Int(n) if *n > 0 => Some(OptimizationThreads {
            auto_: false,
            value: *n as u64,
        }),
        Value::Str(s) if ascii_equal_lower(s, "auto") => Some(OptimizationThreads {
            auto_: true,
            value: 0,
        }),
        _ => None,
    }
}

pub fn is_integer_val(value: &Value) -> bool {
    match value {
        Value::Int(_) => true,
        Value::Float(f) => *f >= 0.0 && *f == (*f as u64) as f64,
        _ => false,
    }
}

pub fn validate_hnsw_value(key: &str, value: &Value, pos: usize) -> Result<(), QqlError> {
    let lower = key.to_ascii_lowercase();
    match lower.as_str() {
        "m" | "ef_construct" | "full_scan_threshold" | "max_indexing_threads" | "payload_m" => {
            if !is_integer_val(value) {
                return Err(validation_err(
                    alloc::format!("{} must be an integer", key),
                    pos,
                ));
            }
        }
        "on_disk" | "inline_storage" if !matches!(value, Value::Bool(_)) => {
            return Err(validation_err(
                alloc::format!("{} must be true or false", key),
                pos,
            ));
        }
        "memory" => validate_memory_value(key, value, pos, true)?,
        _ => {}
    }
    Ok(())
}

pub fn validate_vectors_value(key: &str, value: &Value, pos: usize) -> Result<(), QqlError> {
    let lower = key.to_ascii_lowercase();
    match lower.as_str() {
        "on_disk" if !matches!(value, Value::Bool(_)) => {
            return Err(validation_err(
                alloc::format!("{} must be true or false", key),
                pos,
            ));
        }
        "memory" => validate_memory_value(key, value, pos, true)?,
        "datatype" => match value {
            Value::Str(s) if crate::ast::VectorDatatype::parse(s).is_some() => {}
            Value::Str(_) => {
                return Err(validation_err(
                    alloc::format!("{key} must be float32, float16, uint8, or turbo4"),
                    pos,
                ));
            }
            _ => {
                return Err(validation_err(
                    alloc::format!("{key} must be a string (float32, float16, uint8, or turbo4)"),
                    pos,
                ));
            }
        },
        _ => {}
    }
    Ok(())
}

fn validate_memory_value(
    key: &str,
    value: &Value,
    pos: usize,
    allow_pinned: bool,
) -> Result<(), QqlError> {
    match value {
        Value::Str(s) => match crate::ast::MemoryPlacement::parse(s) {
            Some(crate::ast::MemoryPlacement::Pinned) if !allow_pinned => Err(validation_err(
                alloc::format!("{key} does not support 'pinned'"),
                pos,
            )),
            Some(_) => Ok(()),
            None => Err(validation_err(
                alloc::format!("{key} must be 'cold', 'cached', or 'pinned'"),
                pos,
            )),
        },
        _ => Err(validation_err(
            alloc::format!("{key} must be a string ('cold', 'cached', or 'pinned')"),
            pos,
        )),
    }
}

pub fn validate_optimizers_value(key: &str, value: &Value, pos: usize) -> Result<(), QqlError> {
    let lower = key.to_ascii_lowercase();
    match lower.as_str() {
        "deleted_threshold" => {
            if !matches!(value, Value::Int(_) | Value::Float(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be a number", key),
                    pos,
                ));
            }
        }
        "vacuum_min_vector_number"
        | "default_segment_number"
        | "max_segment_size"
        | "memmap_threshold"
        | "indexing_threshold"
        | "flush_interval_sec" => {
            if !is_integer_val(value) {
                return Err(validation_err(
                    alloc::format!("{} must be an integer", key),
                    pos,
                ));
            }
        }
        "max_optimization_threads" => {
            if !is_integer_val(value) && !matches!(value, Value::Str(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be a positive integer or 'auto'", key),
                    pos,
                ));
            }
        }
        "prevent_unoptimized" if !matches!(value, Value::Bool(_)) => {
            return Err(validation_err(
                alloc::format!("{} must be true or false", key),
                pos,
            ));
        }
        _ => {}
    }
    Ok(())
}

pub fn validate_params_value(key: &str, value: &Value, pos: usize) -> Result<(), QqlError> {
    let lower = key.to_ascii_lowercase();
    match lower.as_str() {
        "replication_factor"
        | "write_consistency_factor"
        | "read_fan_out_factor"
        | "read_fan_out_delay_ms"
        | "shard_number" => {
            if !matches!(value, Value::Int(_)) {
                return Err(validation_err(
                    alloc::format!("{} must be an integer", key),
                    pos,
                ));
            }
        }
        "on_disk_payload" if !matches!(value, Value::Bool(_)) => {
            return Err(validation_err(
                alloc::format!("{} must be true or false", key),
                pos,
            ));
        }
        "payload_memory" => validate_memory_value(key, value, pos, false)?,
        "sharding_method" => match value {
            Value::Str(s) if s.eq_ignore_ascii_case("auto") || s.eq_ignore_ascii_case("custom") => {
            }
            Value::Str(_) => {
                return Err(validation_err(
                    "sharding_method must be 'auto' or 'custom'",
                    pos,
                ));
            }
            _ => {
                return Err(validation_err(
                    "sharding_method must be a string ('auto' or 'custom')",
                    pos,
                ));
            }
        },
        "shard_keys" => match value {
            Value::List(items) if items.is_empty() => {
                return Err(validation_err(
                    "shard_keys must be a non-empty list of strings",
                    pos,
                ));
            }
            Value::List(items) => {
                for item in items {
                    if !matches!(item, Value::Str(_)) {
                        return Err(validation_err(
                            "shard_keys entries must all be strings",
                            pos,
                        ));
                    }
                }
            }
            _ => {
                return Err(validation_err("shard_keys must be a list of strings", pos));
            }
        },
        _ => {}
    }
    Ok(())
}

pub fn merge_collection_config(
    current: &mut CollectionConfig,
    new: CollectionConfig,
    pos: usize,
) -> Result<(), QqlError> {
    if new.vectors.is_some() {
        if current.vectors.is_some() {
            return Err(QqlError::syntax("VECTOR clause may only appear once", pos));
        }
        current.vectors = new.vectors;
    }
    if new.hnsw.is_some() {
        if current.hnsw.is_some() {
            return Err(QqlError::syntax("HNSW clause may only appear once", pos));
        }
        current.hnsw = new.hnsw;
    }
    if new.optimizers.is_some() {
        if current.optimizers.is_some() {
            return Err(QqlError::syntax(
                "OPTIMIZERS clause may only appear once",
                pos,
            ));
        }
        current.optimizers = new.optimizers;
    }
    if new.params.is_some() {
        if current.params.is_some() {
            return Err(QqlError::syntax("PARAMS clause may only appear once", pos));
        }
        current.params = new.params;
    }
    if new.quantization.is_some() {
        if current.quantization.is_some() {
            return Err(QqlError::syntax(
                "QUANTIZATION clause may only appear once",
                pos,
            ));
        }
        current.quantization = new.quantization;
    }
    if new.quantization_update.is_some() {
        if current.quantization_update.is_some() {
            return Err(QqlError::syntax(
                "QUANTIZATION clause may only appear once",
                pos,
            ));
        }
        current.quantization_update = new.quantization_update;
    }
    Ok(())
}

pub fn check_deleted_threshold(value: &Value, pos: usize) -> Result<(), QqlError> {
    match value {
        Value::Int(n) => {
            let f = *n as f64;
            if !(0.0..=1.0).contains(&f) {
                return Err(QqlError::syntax(
                    "deleted_threshold must be between 0.0 and 1.0",
                    pos,
                ));
            }
        }
        Value::Float(f) if !(0.0..=1.0).contains(f) => {
            return Err(QqlError::syntax(
                "deleted_threshold must be between 0.0 and 1.0",
                pos,
            ));
        }
        _ => {}
    }
    Ok(())
}

pub fn validate_index_options(options: &[(String, Value)], pos: usize) -> Result<(), QqlError> {
    for (k, v) in options {
        let lower = k.to_ascii_lowercase();
        match lower.as_str() {
            "is_tenant" | "on_disk" | "enable_hnsw" | "lowercase" | "ascii_folding"
            | "phrase_matching" | "lookup" | "range" | "is_principal" | "prefix" => {
                if !matches!(v, Value::Bool(_)) {
                    return Err(QqlError::syntax(
                        alloc::format!("{} must be true or false", k),
                        pos,
                    ));
                }
            }
            "min_token_len" | "max_token_len" => {
                if !matches!(v, Value::Int(n) if *n >= 0) {
                    return Err(QqlError::syntax(
                        alloc::format!("{} must be a non-negative integer", k),
                        pos,
                    ));
                }
            }
            "tokenizer" | "stemmer" => {
                if !matches!(v, Value::Str(_)) {
                    return Err(QqlError::syntax(
                        alloc::format!("{} must be a string", k),
                        pos,
                    ));
                }
            }
            "memory" => validate_memory_value(k, v, pos, true)?,
            "stopwords" => match v {
                Value::List(items) => {
                    for item in items {
                        if !matches!(item, Value::Str(_)) {
                            return Err(QqlError::syntax(
                                alloc::format!("{} must be a list of strings", k),
                                pos,
                            ));
                        }
                    }
                }
                _ => {
                    return Err(QqlError::syntax(
                        alloc::format!("{} must be a list of strings", k),
                        pos,
                    ));
                }
            },
            _ => {
                return Err(QqlError::syntax(
                    alloc::format!("unknown index option: {}", k),
                    pos,
                ));
            }
        }
    }
    Ok(())
}