velesdb-core 1.13.5

High-performance vector database engine written in Rust
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
//! Abstract Syntax Tree (AST) for VelesQL queries.
//!
//! This module defines the data structures representing parsed VelesQL queries.

mod admin;
mod aggregation;
pub(crate) mod condition;
mod ddl;
mod dml;
mod fusion;
mod introspection;
mod join;
mod select;
mod train;
mod values;
mod window;
mod with_clause;

use serde::{Deserialize, Serialize};

// Re-export all types for backward compatibility
pub use admin::{AdminStatement, FlushStatement};
pub use aggregation::{
    AggregateArg, AggregateFunction, AggregateType, GroupByClause, HavingClause, HavingCondition,
    LogicalOp,
};
pub use condition::{
    BetweenCondition, CompareOp, Comparison, Condition, ContainsCondition, ContainsMode,
    ContainsTextCondition, GeoBboxCondition, GeoDistanceCondition, GraphMatchPredicate,
    InCondition, IsNullCondition, LikeCondition, MatchCondition, SimilarityCondition,
    SparseVectorExpr, SparseVectorSearch, VectorFusedSearch, VectorSearch,
};
pub use ddl::{
    AlterCollectionStatement, AnalyzeStatement, CreateCollectionKind, CreateCollectionStatement,
    CreateIndexStatement, DdlStatement, DropCollectionStatement, DropIndexStatement,
    GraphCollectionParams, GraphSchemaMode, SchemaDefinition, TruncateStatement,
    VectorCollectionParams,
};
pub use dml::{
    DeleteEdgeStatement, DeleteStatement, DmlStatement, InsertEdgeStatement, InsertNodeStatement,
    InsertStatement, SelectEdgesStatement, UpdateAssignment, UpdateStatement,
};
pub use fusion::{FusionClause, FusionConfig, FusionStrategyType};
pub use introspection::{DescribeCollectionStatement, IntrospectionStatement};
pub use join::{ColumnRef, JoinClause, JoinCondition, JoinType};
pub use select::{
    ArithmeticExpr, ArithmeticOp, Column, DistinctMode, LetBinding, OrderByExpr, SelectColumns,
    SelectOrderBy, SelectStatement, SimilarityOrderBy, SimilarityScoreExpr,
};
pub use train::TrainStatement;
pub use values::{
    CorrelatedColumn, IntervalUnit, IntervalValue, Subquery, TemporalExpr, Value, VectorExpr,
};
pub use window::{OverClause, WindowFunction, WindowFunctionType, WindowOrderBy};
pub use with_clause::{QuantizationMode, WithClause, WithOption, WithValue};

/// A complete VelesQL query.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Query {
    /// Named score bindings defined by `LET` clauses (VelesQL v1.10 Phase 3).
    ///
    /// Bindings are evaluated in order before ORDER BY; each binding can
    /// reference earlier bindings, component scores, or literal values.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub let_bindings: Vec<LetBinding>,
    /// The SELECT statement.
    pub select: SelectStatement,
    /// Compound query (UNION/INTERSECT/EXCEPT) - EPIC-040 US-006.
    #[serde(default)]
    pub compound: Option<CompoundQuery>,
    /// MATCH clause for graph pattern matching (EPIC-045 US-001).
    #[serde(default)]
    pub match_clause: Option<crate::velesql::MatchClause>,
    /// Optional DML statement (INSERT/UPDATE/DELETE).
    #[serde(default)]
    pub dml: Option<DmlStatement>,
    /// Optional TRAIN statement (TRAIN QUANTIZER).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub train: Option<TrainStatement>,
    /// Optional DDL statement (CREATE/DROP COLLECTION) -- VelesQL v3.3.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ddl: Option<DdlStatement>,
    /// Optional introspection statement (SHOW/DESCRIBE/EXPLAIN) -- VelesQL v3.4.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introspection: Option<IntrospectionStatement>,
    /// Optional admin statement (FLUSH) -- VelesQL v3.6.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admin: Option<AdminStatement>,
}

impl Query {
    /// Returns true if this is a MATCH query.
    #[must_use]
    pub fn is_match_query(&self) -> bool {
        self.match_clause.is_some()
    }

    /// Returns true if this is a SELECT query.
    #[must_use]
    pub fn is_select_query(&self) -> bool {
        self.match_clause.is_none()
            && self.dml.is_none()
            && self.train.is_none()
            && self.ddl.is_none()
            && self.introspection.is_none()
            && self.admin.is_none()
    }

    /// Returns true if this is a DML query.
    #[must_use]
    pub fn is_dml_query(&self) -> bool {
        self.dml.is_some()
    }

    /// Returns true if this is a TRAIN statement.
    #[must_use]
    pub fn is_train(&self) -> bool {
        self.train.is_some()
    }

    /// Returns true if this is a DDL statement (CREATE/DROP COLLECTION).
    #[must_use]
    pub fn is_ddl_query(&self) -> bool {
        self.ddl.is_some()
    }

    /// Returns true if this is an introspection statement (SHOW/DESCRIBE/EXPLAIN).
    #[must_use]
    pub fn is_introspection_query(&self) -> bool {
        self.introspection.is_some()
    }

    /// Returns true if this is an admin statement (FLUSH).
    #[must_use]
    pub fn is_admin_query(&self) -> bool {
        self.admin.is_some()
    }

    /// Returns true if this is a SELECT EDGES query.
    #[must_use]
    pub fn is_select_edges_query(&self) -> bool {
        matches!(self.dml, Some(DmlStatement::SelectEdges(_)))
    }

    /// Returns true if this is an INSERT NODE query.
    #[must_use]
    pub fn is_insert_node_query(&self) -> bool {
        matches!(self.dml, Some(DmlStatement::InsertNode(_)))
    }

    /// Extracts the collection name from a DML statement, if present.
    #[must_use]
    pub fn dml_collection_name(&self) -> Option<&str> {
        let name = match self.dml.as_ref()? {
            DmlStatement::Insert(s) | DmlStatement::Upsert(s) => &s.table,
            DmlStatement::Update(s) => &s.table,
            DmlStatement::Delete(s) => &s.table,
            DmlStatement::InsertEdge(s) => &s.collection,
            DmlStatement::DeleteEdge(s) => &s.collection,
            DmlStatement::SelectEdges(s) => &s.collection,
            DmlStatement::InsertNode(s) => &s.collection,
        };
        if name.is_empty() {
            None
        } else {
            Some(name)
        }
    }

    /// Creates a new SELECT query.
    #[must_use]
    pub fn new_select(select: SelectStatement) -> Self {
        Self {
            let_bindings: Vec::new(),
            select,
            compound: None,
            match_clause: None,
            dml: None,
            train: None,
            ddl: None,
            introspection: None,
            admin: None,
        }
    }

    /// Creates a new MATCH query (EPIC-045).
    #[must_use]
    pub fn new_match(match_clause: crate::velesql::MatchClause) -> Self {
        let mut select = SelectStatement::empty();
        select.where_clause.clone_from(&match_clause.where_clause);
        select.limit = match_clause.return_clause.limit;
        Self {
            let_bindings: Vec::new(),
            select,
            compound: None,
            match_clause: Some(match_clause),
            dml: None,
            train: None,
            ddl: None,
            introspection: None,
            admin: None,
        }
    }

    /// Creates a new DML query.
    #[must_use]
    pub fn new_dml(dml: DmlStatement) -> Self {
        Self {
            let_bindings: Vec::new(),
            select: SelectStatement::empty(),
            compound: None,
            match_clause: None,
            dml: Some(dml),
            train: None,
            ddl: None,
            introspection: None,
            admin: None,
        }
    }

    /// Creates a new TRAIN query.
    #[must_use]
    pub fn new_train(train: TrainStatement) -> Self {
        Self {
            let_bindings: Vec::new(),
            select: SelectStatement::empty(),
            compound: None,
            match_clause: None,
            dml: None,
            train: Some(train),
            ddl: None,
            introspection: None,
            admin: None,
        }
    }

    /// Creates a new DDL query (CREATE/DROP COLLECTION).
    #[must_use]
    pub fn new_ddl(ddl: DdlStatement) -> Self {
        Self {
            let_bindings: Vec::new(),
            select: SelectStatement::empty(),
            compound: None,
            match_clause: None,
            dml: None,
            train: None,
            ddl: Some(ddl),
            introspection: None,
            admin: None,
        }
    }

    /// Creates a new introspection query (SHOW/DESCRIBE/EXPLAIN).
    #[must_use]
    pub fn new_introspection(stmt: IntrospectionStatement) -> Self {
        Self {
            let_bindings: Vec::new(),
            select: SelectStatement::empty(),
            compound: None,
            match_clause: None,
            dml: None,
            train: None,
            ddl: None,
            introspection: Some(stmt),
            admin: None,
        }
    }

    /// Creates a new admin query (FLUSH).
    #[must_use]
    pub fn new_admin(stmt: AdminStatement) -> Self {
        Self {
            let_bindings: Vec::new(),
            select: SelectStatement::empty(),
            compound: None,
            match_clause: None,
            dml: None,
            train: None,
            ddl: None,
            introspection: None,
            admin: Some(stmt),
        }
    }
}

/// SQL set operator for compound queries (EPIC-040 US-006).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum SetOperator {
    /// UNION - merge results, remove duplicates.
    Union,
    /// UNION ALL - merge results, keep duplicates.
    UnionAll,
    /// INTERSECT - keep only common results.
    Intersect,
    /// EXCEPT - subtract second query from first.
    Except,
}

/// Compound query combining queries with set operators (UNION/INTERSECT/EXCEPT).
///
/// Supports N-ary chaining: `SELECT ... UNION SELECT ... INTERSECT SELECT ...`
/// is represented as `operations: [(Union, B), (Intersect, C)]`, applied left-to-right.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompoundQuery {
    /// Chained set operations: `(operator, right_select)` pairs, applied left-to-right.
    pub operations: Vec<(SetOperator, SelectStatement)>,
}

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

    #[test]
    fn test_with_clause_new() {
        let clause = WithClause::new();
        assert!(clause.options.is_empty());
    }

    #[test]
    fn test_with_clause_with_option() {
        let clause = WithClause::new()
            .with_option("mode", WithValue::String("accurate".to_string()))
            .with_option("ef_search", WithValue::Integer(512));
        assert_eq!(clause.options.len(), 2);
    }

    #[test]
    fn test_with_clause_get() {
        let clause = WithClause::new().with_option("mode", WithValue::String("fast".to_string()));
        assert!(clause.get("mode").is_some());
        assert!(clause.get("MODE").is_some());
        assert!(clause.get("unknown").is_none());
    }

    #[test]
    fn test_with_clause_get_mode() {
        let clause =
            WithClause::new().with_option("mode", WithValue::String("accurate".to_string()));
        assert_eq!(clause.get_mode(), Some("accurate"));
    }

    #[test]
    fn test_with_value_as_str() {
        let v = WithValue::String("test".to_string());
        assert_eq!(v.as_str(), Some("test"));
    }

    #[test]
    fn test_with_value_as_integer() {
        let v = WithValue::Integer(100);
        assert_eq!(v.as_integer(), Some(100));
    }

    #[test]
    fn test_with_value_as_float() {
        let v = WithValue::Float(1.234);
        assert!((v.as_float().unwrap() - 1.234).abs() < 1e-5);
    }

    #[test]
    fn test_interval_to_seconds() {
        assert_eq!(
            IntervalValue {
                magnitude: 30,
                unit: IntervalUnit::Seconds
            }
            .to_seconds(),
            30
        );
        assert_eq!(
            IntervalValue {
                magnitude: 1,
                unit: IntervalUnit::Days
            }
            .to_seconds(),
            86400
        );
    }

    #[test]
    fn test_temporal_now() {
        let expr = TemporalExpr::Now;
        let epoch = expr.to_epoch_seconds();
        assert!(epoch > 1_577_836_800);
    }

    #[test]
    fn test_value_from_i64() {
        let v: Value = 42i64.into();
        assert_eq!(v, Value::Integer(42));
    }

    #[test]
    fn test_fusion_config_default() {
        let config = FusionConfig::default();
        assert_eq!(config.strategy, "rrf");
    }

    #[test]
    fn test_fusion_config_rrf() {
        let config = FusionConfig::rrf();
        assert_eq!(config.strategy, "rrf");
        assert!((config.params.get("k").unwrap() - 60.0).abs() < 1e-5);
    }

    #[test]
    fn test_fusion_clause_default() {
        let clause = FusionClause::default();
        assert_eq!(clause.strategy, FusionStrategyType::Rrf);
        assert_eq!(clause.k, Some(60));
    }

    #[test]
    fn test_group_by_clause_default() {
        let clause = GroupByClause::default();
        assert!(clause.columns.is_empty());
    }

    #[test]
    fn test_having_clause_default() {
        let clause = HavingClause::default();
        assert!(clause.conditions.is_empty());
    }
}