qql-core 0.4.1

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
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
use crate::ast::{PointId, PointVectors, Stmt};
use crate::parser::Parser;

#[test]
fn create_collection_dense() {
    let s = Parser::parse("CREATE COLLECTION docs (dense VECTOR(384, COSINE));").unwrap();
    assert!(matches!(s, Stmt::CreateCollection(_)));
}

#[test]
fn create_collection_vector_size_cap() {
    // VectorParams.size maximum in the Qdrant OpenAPI schema (qdrant#10324).
    assert!(Parser::parse("CREATE COLLECTION docs (d VECTOR(65536, COSINE));").is_ok());
    let err = Parser::parse("CREATE COLLECTION docs (d VECTOR(65537, COSINE));")
        .expect_err("size above the 65536 maximum must be rejected");
    assert_eq!(err.kind, crate::error::ErrorKind::Parse);
    assert_eq!(err.code, "QQL-PARSE-VECTOR-SIZE");
}

#[test]
fn create_collection_with_sparse() {
    let s =
        Parser::parse("CREATE COLLECTION docs (dense VECTOR(768, DOT), sparse SPARSE);").unwrap();
    assert!(matches!(s, Stmt::CreateCollection(_)));
}

#[test]
fn create_collection_explicit_dense_model() {
    let s = Parser::parse("CREATE COLLECTION docs USING DENSE MODEL 'all-minilm:l6-v2';").unwrap();
    assert!(matches!(s, Stmt::CreateCollection(_)));
}

#[test]
fn create_hybrid_with_arbitrary_vector_names() {
    let stmt = Parser::parse(
        "CREATE COLLECTION docs HYBRID \
         DENSE VECTOR semantic_v2 SPARSE VECTOR lexical_v2;",
    )
    .unwrap();
    let Stmt::CreateCollection(create) = stmt else {
        panic!("expected CREATE COLLECTION");
    };
    assert!(matches!(
        create.mode,
        crate::ast::CollectionMode::Hybrid {
            dense_vector: Some(ref dense),
            sparse_vector: Some(ref sparse),
        } if dense == "semantic_v2" && sparse == "lexical_v2"
    ));
}

#[test]
fn create_collection_with_hnsw() {
    let s = Parser::parse(
        "CREATE COLLECTION docs (d VECTOR(128, EUCLID)) WITH HNSW (m = 16, ef_construct = 100);",
    )
    .unwrap();
    assert!(matches!(s, Stmt::CreateCollection(_)));
}

#[test]
fn create_collection_with_params() {
    let s = Parser::parse(
        "CREATE COLLECTION docs (d VECTOR(4, DOT)) WITH PARAMS (replication_factor = 3, on_disk_payload = true);",
    ).unwrap();
    assert!(matches!(s, Stmt::CreateCollection(_)));
}

#[test]
fn create_collection_with_memory_and_datatype() {
    let stmt = Parser::parse(
        "CREATE COLLECTION docs \
         (dense VECTOR(4, COSINE) WITH VECTOR (memory = 'cached', datatype = 'turbo4') WITH HNSW (memory = 'cold')) \
         WITH PARAMS (payload_memory = 'cold') \
         WITH QUANTIZATION (type = 'scalar', memory = 'cached');",
    )
    .unwrap();
    let Stmt::CreateCollection(create) = stmt else {
        panic!("expected CREATE COLLECTION");
    };
    let dense = create
        .vectors
        .iter()
        .find(|v| v.name == "dense")
        .expect("dense vector");
    let vectors = dense.vectors.as_ref().expect("WITH VECTOR block");
    assert_eq!(vectors.memory, Some(crate::ast::MemoryPlacement::Cached));
    assert_eq!(vectors.datatype, Some(crate::ast::VectorDatatype::Turbo4));
    let hnsw = dense.hnsw.as_ref().expect("WITH HNSW block");
    assert_eq!(hnsw.memory, Some(crate::ast::MemoryPlacement::Cold));
    let params = create.config.as_ref().and_then(|c| c.params.as_ref());
    assert_eq!(
        params.unwrap().payload_memory,
        Some(crate::ast::MemoryPlacement::Cold)
    );
    let quant = create.config.as_ref().and_then(|c| c.quantization.as_ref());
    assert_eq!(
        quant.unwrap().memory,
        Some(crate::ast::MemoryPlacement::Cached)
    );
}

#[test]
fn create_collection_rejects_bad_memory_and_datatype() {
    assert!(Parser::parse(
        "CREATE COLLECTION docs (d VECTOR(4, COSINE)) WITH VECTOR (memory = 'hot');",
    )
    .is_err());
    assert!(
        Parser::parse(
            "CREATE COLLECTION docs (d VECTOR(4, COSINE)) WITH VECTOR (datatype = 'float64');",
        )
        .is_err()
    );
    assert!(
        Parser::parse(
            "CREATE COLLECTION docs (d VECTOR(4, COSINE)) WITH HNSW (memory = 'pinned');",
        )
        .is_ok()
    );
    assert!(
        Parser::parse(
            "CREATE COLLECTION docs (d VECTOR(4, COSINE)) WITH PARAMS (payload_memory = 'pinned');",
        )
        .is_err()
    );
}

#[test]
fn create_sparse_with_memory_roundtrips_fmt() {
    let stmt = Parser::parse(
        "CREATE COLLECTION docs (sparse SPARSE WITH SPARSE (modifier = 'idf', memory = 'cached'));",
    )
    .unwrap();
    let formatted = crate::fmt::format_stmt(&stmt);
    assert!(formatted.contains("memory = 'cached'"), "{formatted}");
    let reparsed = Parser::parse(&formatted).unwrap();
    assert_eq!(format_stmt_ast(&stmt), format_stmt_ast(&reparsed));
}

#[test]
fn show_quotas() {
    let s = Parser::parse("SHOW QUOTAS;").unwrap();
    assert!(matches!(s, Stmt::ShowQuotas));
}

#[test]
fn set_quota_parses_and_roundtrips_fmt() {
    let stmt = Parser::parse(
        "SET QUOTA (enabled = true, max_resident_memory_percent = 80, max_disk_usage_percent = 90, release_margin_percent = 5) WAIT true;",
    )
    .unwrap();
    match &stmt {
        Stmt::SetQuota(q) => {
            assert_eq!(q.wait, Some(true));
            assert_eq!(q.config.len(), 4);
        }
        other => panic!("expected SET QUOTA, got {other:?}"),
    }
    let formatted = crate::fmt::format_stmt(&stmt);
    assert!(formatted.contains("SET QUOTA ("), "{formatted}");
    assert!(formatted.contains("WAIT true"), "{formatted}");
    let reparsed = Parser::parse(&formatted).unwrap();
    assert_eq!(&stmt, &reparsed);

    // WAIT defaults to absent.
    let s = Parser::parse("SET QUOTA (enabled = true);").unwrap();
    match s {
        Stmt::SetQuota(q) => assert_eq!(q.wait, None),
        other => panic!("expected SET QUOTA, got {other:?}"),
    }
}

#[test]
fn set_quota_rejects_unknown_keys_and_bad_wait() {
    assert!(Parser::parse("SET QUOTA (bogus = 1);").is_ok()); // planner validates
    assert!(Parser::parse("SET QUOTA (enabled = true) WAIT maybe;").is_err());
}

fn format_stmt_ast(stmt: &Stmt) -> String {
    crate::fmt::format_stmt(stmt)
}

#[test]
fn alter_collection() {
    let s = Parser::parse("ALTER COLLECTION docs WITH VECTOR (on_disk = true) WITH HNSW (m = 32);")
        .unwrap();
    assert!(matches!(s, Stmt::AlterCollection(_)));
}

#[test]
fn alter_collection_named_vector_diffs_parse_and_round_trip() {
    let sources = [
        "ALTER COLLECTION docs WITH VECTOR dense (HNSW (m = 32, ef_construct = 100));",
        "ALTER COLLECTION docs WITH VECTOR dense (QUANTIZATION (type = 'binary', encoding = 'two_bits'));",
        "ALTER COLLECTION docs WITH VECTOR dense (QUANTIZATION (disabled = true));",
        "ALTER COLLECTION docs WITH VECTOR dense (VECTOR (on_disk = false, memory = 'cold'));",
        "ALTER COLLECTION docs WITH VECTOR dense (HNSW (m = 32), QUANTIZATION (type = 'scalar', always_ram = true), VECTOR (memory = 'cached'));",
        "ALTER COLLECTION docs WITH SPARSE bm25 (SPARSE (modifier = 'idf', full_scan_threshold = 5000, memory = 'pinned', datatype = 'float16'));",
        "ALTER COLLECTION docs WITH SPARSE bm25 (INDEX (modifier = 'none', on_disk = true));",
        "ALTER COLLECTION docs WITH VECTOR dense (HNSW (m = 16)) WITH SPARSE bm25 (SPARSE (modifier = 'idf')) WITH HNSW (ef_construct = 200);",
    ];
    for source in sources {
        let stmt = Parser::parse(source).unwrap_or_else(|e| panic!("{source}: {e}"));
        let Stmt::AlterCollection(alter) = &stmt else {
            panic!("{source}: expected ALTER COLLECTION");
        };
        assert!(alter.config.is_some(), "{source}");
        // Canonical formatting must reparse to the same AST.
        let formatted = crate::fmt::format_stmt(&stmt);
        let reparsed = Parser::parse(&formatted)
            .unwrap_or_else(|e| panic!("formatted '{formatted}' must parse: {e}"));
        assert_eq!(stmt, reparsed, "round-trip mismatch for: {formatted}");
    }
}

#[test]
fn alter_collection_named_vector_diff_preserves_fields() {
    let stmt = Parser::parse(
        "ALTER COLLECTION docs WITH VECTOR dense (HNSW (m = 32), QUANTIZATION (disabled = true), VECTOR (memory = 'cold'));",
    )
    .unwrap();
    let Stmt::AlterCollection(alter) = stmt else {
        panic!("expected ALTER COLLECTION");
    };
    let config = alter.config.expect("config");
    assert_eq!(config.vector_diffs.len(), 1);
    let diff = &config.vector_diffs[0];
    assert_eq!(diff.name, "dense");
    assert_eq!(diff.hnsw.as_ref().and_then(|h| h.m), Some(32));
    let update = diff.quantization.as_deref().expect("quantization update");
    assert!(update.disabled);
    assert!(update.config.is_none());
    assert_eq!(
        diff.vectors.as_deref().and_then(|v| v.memory),
        Some(crate::ast::MemoryPlacement::Cold)
    );
}

#[test]
fn alter_collection_named_vector_diff_rejections() {
    let cases = [
        // Empty diff body.
        "ALTER COLLECTION docs WITH VECTOR dense ();",
        // Empty nested blocks.
        "ALTER COLLECTION docs WITH VECTOR dense (HNSW ());",
        "ALTER COLLECTION docs WITH VECTOR dense (VECTOR ());",
        "ALTER COLLECTION docs WITH SPARSE bm25 (SPARSE ());",
        // Duplicate nested blocks.
        "ALTER COLLECTION docs WITH VECTOR dense (HNSW (m = 16), HNSW (m = 32));",
        "ALTER COLLECTION docs WITH VECTOR dense (VECTOR (on_disk = true), VECTOR (memory = 'cold'));",
        // Duplicate vector names across clauses.
        "ALTER COLLECTION docs WITH VECTOR dense (HNSW (m = 16)) WITH VECTOR dense (HNSW (m = 32));",
        "ALTER COLLECTION docs WITH SPARSE bm25 (SPARSE (modifier = 'idf')) WITH SPARSE bm25 (SPARSE (modifier = 'none'));",
        // Unknown nested block.
        "ALTER COLLECTION docs WITH VECTOR dense (MULTIVECTOR (comparator = 'max_sim'));",
        // datatype has no diff field on the wire.
        "ALTER COLLECTION docs WITH VECTOR dense (VECTOR (datatype = 'float16'));",
        // Sparse body requires SPARSE / INDEX.
        "ALTER COLLECTION docs WITH SPARSE bm25 (modifier = 'idf');",
        // Named diffs are ALTER-only; unknown keys in create stay rejected.
        "CREATE COLLECTION docs WITH SPARSE bm25 (SPARSE (modifier = 'idf'));",
    ];
    for source in cases {
        assert!(Parser::parse(source).is_err(), "must reject: {source}");
    }
    let err =
        Parser::parse("ALTER COLLECTION docs WITH VECTOR dense (VECTOR (datatype = 'float16'));")
            .unwrap_err();
    assert_eq!(err.code, "QQL-PARSE-VECTOR-DIFF");
    assert!(err.message.contains("datatype"), "{err}");
}

#[test]
fn drop_collection() {
    let s = Parser::parse("DROP COLLECTION docs;").unwrap();
    assert!(matches!(s, Stmt::DropCollection(_)));
}

#[test]
fn create_index() {
    let s = Parser::parse(
        "CREATE INDEX ON COLLECTION docs FOR title TYPE text WITH (lowercase = true, tokenizer = 'word');",
    ).unwrap();
    assert!(matches!(s, Stmt::CreateIndex(_)));
}

#[test]
fn create_index_numeric_options() {
    let s = Parser::parse(
        "CREATE INDEX ON COLLECTION docs FOR year TYPE integer \
         WITH (lookup = true, range = true, is_principal = true);",
    )
    .unwrap();
    assert!(matches!(s, Stmt::CreateIndex(_)));
}

#[test]
fn show_collections() {
    let s = Parser::parse("SHOW COLLECTIONS;").unwrap();
    assert!(matches!(s, Stmt::ShowCollections));
}

#[test]
fn show_collection() {
    let s = Parser::parse("SHOW COLLECTION docs;").unwrap();
    assert!(matches!(s, Stmt::ShowCollection(ref c) if c == "docs"));
}

#[test]
fn upsert_simple() {
    let s = Parser::parse("UPSERT INTO docs VALUES {id: 1, title: 'hello', vector: [0.1, 0.2]};")
        .unwrap();
    let Stmt::Upsert(u) = s else { panic!() };
    assert_eq!(u.points.len(), 1);
    assert_eq!(u.collection, "docs");
}

#[test]
fn upsert_with_sparse() {
    let s = Parser::parse(
        "UPSERT INTO docs VALUES {id: 'p1', title: 'doc', vector: {indices: [0, 3], values: [5.0, 8.0]}};",
    ).unwrap();
    assert!(matches!(s, Stmt::Upsert(_)));
}

#[test]
fn upsert_named_vectors() {
    let s = Parser::parse(
        "UPSERT INTO docs VALUES {id: 1, title: 'x', vector: {dense: [1.0, 2.0], sp: {indices: [7], values: [0.5]}}};",
    ).unwrap();
    assert!(matches!(s, Stmt::Upsert(_)));
}

#[test]
fn upsert_with_embedding() {
    let s =
        Parser::parse("UPSERT INTO docs VALUES {id: 1, text: 'hello'} USING DENSE MODEL 'nomic';")
            .unwrap();
    assert!(matches!(s, Stmt::Upsert(_)));
}

#[test]
fn upsert_embedding_targets_may_be_inferred() {
    for source in [
        "UPSERT INTO docs VALUES {id: 1, text: 'hello'} USING DENSE;",
        "UPSERT INTO docs VALUES {id: 1, text: 'hello'} USING SPARSE;",
        "UPSERT INTO docs VALUES {id: 1, text: 'hello'} USING HYBRID;",
    ] {
        assert!(matches!(Parser::parse(source), Ok(Stmt::Upsert(_))));
    }
}

#[test]
fn upsert_with_embed_directive() {
    let s = Parser::parse(
        "UPSERT INTO docs VALUES {id: 1, title: 'doc'} EMBED title INTO dense_vec USING MODEL 'embed';",
    ).unwrap();
    assert!(matches!(s, Stmt::Upsert(_)));
}

#[test]
fn embed_directive_accepts_explicit_dense_role_without_model() {
    let s = Parser::parse(
        "UPSERT INTO docs VALUES {id: 1, title: 'doc'} \
         EMBED title INTO semantic_v2 USING DENSE;",
    )
    .unwrap();
    assert!(matches!(s, Stmt::Upsert(_)));
}

#[test]
fn delete_by_id() {
    let s = Parser::parse("DELETE FROM docs WHERE id = 42;").unwrap();
    assert!(matches!(s, Stmt::Delete(_)));
}

#[test]
fn delete_by_filter() {
    let s = Parser::parse("DELETE FROM docs WHERE status = 'inactive';").unwrap();
    assert!(matches!(s, Stmt::Delete(_)));
}

#[test]
fn update_vector() {
    let s = Parser::parse("UPDATE docs SET VECTOR dense = [0.3, 0.7] WHERE id = 'p1';").unwrap();
    let Stmt::UpdateVector(u) = s else {
        panic!("expected UpdateVector");
    };
    assert_eq!(u.points.len(), 1);
    assert_eq!(u.points[0].id, PointId::String("p1".into()));
}

#[test]
fn update_vector_named_map_and_values() {
    let map = Parser::parse(
        "UPDATE docs SET VECTOR = {dense: [0.1], sparse: {indices: [1], values: [0.5]}} WHERE id = 1;",
    )
    .unwrap();
    let Stmt::UpdateVector(u) = map else {
        panic!("expected UpdateVector");
    };
    assert_eq!(u.points.len(), 1);
    match &u.points[0].vectors {
        PointVectors::Named(entries) => assert_eq!(entries.len(), 2),
        other => panic!("expected named map, got {other:?}"),
    }

    let batch = Parser::parse(
        "UPDATE docs SET VECTOR VALUES {id: 1, vector: [0.1]}, {id: 2, vector: {dense: [0.2]}};",
    )
    .unwrap();
    let Stmt::UpdateVector(u) = batch else {
        panic!("expected UpdateVector");
    };
    assert_eq!(u.points.len(), 2);
}

#[test]
fn update_payload() {
    let s =
        Parser::parse("UPDATE docs SET PAYLOAD = {status: 'active', priority: 5} WHERE id = 42;")
            .unwrap();
    assert!(matches!(s, Stmt::UpdatePayload(_)));
}

#[test]
fn scroll_basic() {
    let s = Parser::parse("SCROLL FROM docs LIMIT 50;").unwrap();
    let Stmt::Scroll(sc) = s else { panic!() };
    assert_eq!(sc.collection, "docs");
    assert_eq!(sc.limit, 50);
    assert!(sc.with_vector.is_none());
}

#[test]
fn scroll_with_filter() {
    let s = Parser::parse("SCROLL FROM docs WHERE active = true AFTER 10 LIMIT 20;").unwrap();
    assert!(matches!(s, Stmt::Scroll(_)));
}

#[test]
fn scroll_with_vector_all() {
    use crate::ast::VectorSelector;
    let s = Parser::parse("SCROLL FROM docs WITH VECTOR LIMIT 10;").unwrap();
    let Stmt::Scroll(sc) = s else { panic!() };
    assert_eq!(sc.with_vector, Some(VectorSelector::All));
}

#[test]
fn query_bare_with_vector_defaults_to_all() {
    use crate::ast::{QueryOutput, VectorSelector};
    let s = Parser::parse("QUERY 'hello' FROM docs WITH VECTOR LIMIT 10;").unwrap();
    let Stmt::Query(q) = s else { panic!() };
    assert_eq!(
        q.output,
        QueryOutput {
            payload: None,
            vectors: Some(VectorSelector::All),
        }
    );
}

#[test]
fn create_index_rejects_legacy_quoted_type() {
    let error =
        Parser::parse("CREATE INDEX ON COLLECTION docs FOR title TYPE 'text';").unwrap_err();
    assert_eq!(error.code, "QQL-PARSE-INDEX-TYPE");
}

#[test]
fn scroll_with_vector_true_and_after() {
    use crate::ast::{PointId, VectorSelector};
    let s = Parser::parse("SCROLL FROM docs AFTER 'abc-uuid' WITH VECTOR true LIMIT 5;").unwrap();
    let Stmt::Scroll(sc) = s else { panic!() };
    assert_eq!(sc.after, Some(PointId::String("abc-uuid".into())));
    assert_eq!(sc.with_vector, Some(VectorSelector::All));
}

#[test]
fn scroll_with_named_vectors() {
    use crate::ast::VectorSelector;
    let s = Parser::parse("SCROLL FROM docs WITH VECTOR (dense, sparse) LIMIT 3;").unwrap();
    let Stmt::Scroll(sc) = s else { panic!() };
    assert_eq!(
        sc.with_vector,
        Some(VectorSelector::Names(vec!["dense".into(), "sparse".into()]))
    );
}