motedb 0.7.5

AI-native embedded multimodal database for embodied intelligence (robots, AR glasses, industrial arms).
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
/// Abstract Syntax Tree for SQL statements
use crate::types::Value;

/// Top-level SQL statement
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum Statement {
    Select {
        stmt: SelectStmt,
        /// WITH clause common table expressions (empty if no WITH).
        /// Visible to `stmt` (including all UNION branches when `stmt` is the
        /// left side of a top-level SetOp assembled by the parser).
        ctes: Vec<CteDef>,
    },
    /// UNION / UNION ALL / INTERSECT / EXCEPT
    SetOp {
        /// Left operand — either a SelectStmt or a nested SetOp (for chaining).
        left: Box<Statement>,
        /// Right operand — either a SelectStmt or a nested SetOp (e.g. an
        /// INTERSECT chain, which binds tighter than UNION/EXCEPT).
        right: Box<Statement>,
        op: SetOp,
        all: bool,
        /// WITH clause CTEs — visible to both `left` and `right`.
        ctes: Vec<CteDef>,
        /// Trailing ORDER BY / LIMIT / OFFSET that apply to the entire set
        /// result (only on the outermost SetOp). Per SQL standard these clauses
        /// belong to the whole query, not to the rightmost SELECT.
        order_by: Option<Vec<OrderByExpr>>,
        limit: Option<usize>,
        offset: Option<usize>,
    },
    Insert(InsertStmt),
    Update(UpdateStmt),
    Delete(DeleteStmt),
    CreateTable(CreateTableStmt),
    CreateIndex(CreateIndexStmt),
    DropTable(DropTableStmt),
    DropIndex(DropIndexStmt),
    AlterTable(AlterTableStmt),
    ShowTables,
    DescribeTable(String), // table name
    BeginTransaction,
    CommitTransaction,
    RollbackTransaction,
}

/// Common Table Expression definition (`WITH name [(cols)] AS ( SELECT ... )`).
///
/// Non-recursive in v1. The body is a `SelectStmt`; subsequent CTEs and the
/// main query may reference `name` in their FROM clause.
#[derive(Debug, Clone)]
pub struct CteDef {
    pub name: String,
    /// Optional explicit column aliases: `WITH x(a, b) AS (...)`.
    /// When present, overrides the body's projected column names.
    pub columns: Option<Vec<String>>,
    pub query: SelectStmt,
}

/// Set operations for combining query results.
#[derive(Debug, Clone, PartialEq)]
pub enum SetOp {
    Union,
    Intersect,
    Except,
}

/// SELECT statement
#[derive(Debug, Clone)]
pub struct SelectStmt {
    pub distinct: bool, // SELECT DISTINCT
    pub columns: Vec<SelectColumn>,
    pub from: Option<TableRef>, // Optional FROM clause (for SELECT without tables)
    pub where_clause: Option<Expr>,
    pub group_by: Option<Vec<String>>, // GROUP BY column_list
    pub having: Option<Expr>,          // HAVING condition
    pub order_by: Option<Vec<OrderByExpr>>,
    pub limit: Option<usize>,
    pub offset: Option<usize>,
    pub latest_by: Option<Vec<String>>, // LATEST BY column_list
}

/// Table reference in FROM clause (supports JOINs and subqueries)
#[derive(Debug, Clone)]
pub enum TableRef {
    /// Single table: table_name [AS alias]
    Table { name: String, alias: Option<String> },
    /// JOIN: left_table JOIN_TYPE right_table ON condition
    Join {
        left: Box<TableRef>,
        right: Box<TableRef>,
        join_type: JoinType,
        on_condition: Expr,
    },
    /// Subquery in FROM: (SELECT ...) AS alias
    ///
    /// Example: FROM (SELECT id, name FROM users WHERE age > 18) AS adults
    Subquery {
        query: Box<SelectStmt>,
        alias: String, // Alias is required for subqueries in FROM
    },
}

/// JOIN types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoinType {
    Inner,
    Left,
    Right,
    Full,
}

#[derive(Debug, Clone)]
pub enum SelectColumn {
    Star,                            // *
    Column(String),                  // column_name
    ColumnWithAlias(String, String), // column_name AS alias
    Expr(Expr, Option<String>),      // expression [AS alias]
}

#[derive(Debug, Clone)]
pub struct OrderByExpr {
    pub expr: Expr,
    pub asc: bool, // true = ASC, false = DESC
}

/// INSERT statement
#[derive(Debug, Clone)]
pub struct InsertStmt {
    pub table: String,
    pub columns: Option<Vec<String>>, // None means all columns
    pub values: Vec<Vec<Expr>>,       // Multiple rows
}

/// UPDATE statement
#[derive(Debug, Clone)]
pub struct UpdateStmt {
    pub table: String,
    pub assignments: Vec<(String, Expr)>, // column = expr
    pub where_clause: Option<Expr>,
}

/// DELETE statement
#[derive(Debug, Clone)]
pub struct DeleteStmt {
    pub table: String,
    pub where_clause: Option<Expr>,
}

/// CREATE TABLE statement
#[derive(Debug, Clone)]
pub struct CreateTableStmt {
    pub table: String,
    pub columns: Vec<ColumnDef>,
    /// Table type: Standard or TimeSeries
    pub table_type: crate::types::TableType,
    /// Designated timestamp column for TimeSeries tables
    pub timeseries_column: Option<String>,
    /// TTL retention policy
    pub ttl: Option<crate::types::TTLDuration>,
    /// 🆕 `CREATE TABLE IF NOT EXISTS` — if true, silently no-op when the
    /// table already exists instead of erroring.
    pub if_not_exists: bool,
}

#[derive(Debug, Clone)]
pub struct ColumnDef {
    pub name: String,
    pub data_type: DataType,
    pub nullable: bool,
    pub primary_key: bool,
    /// 🚀 AUTO_INCREMENT flag
    pub auto_increment: bool,
    /// 🚀 Phase 5: AUTO_INCREMENT starting value (e.g., AUTO_INCREMENT = 100)
    pub auto_increment_start: Option<i64>,
    /// DEFAULT value for the column (CREATE TABLE / ALTER TABLE).
    pub default_value: Option<crate::types::Value>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum DataType {
    Integer,
    /// 🚀 Phase 4: BIGINT for 64-bit integers (supports up to i64::MAX)
    BigInt,
    Float,
    Text,
    Boolean,
    Timestamp,
    Vector(Option<usize>), // Vector dimension
    Geometry,
}

/// CREATE INDEX statement
#[derive(Debug, Clone)]
pub struct CreateIndexStmt {
    pub index_name: String,
    pub table: String,
    pub column: String,
    pub index_type: IndexType,
    /// Distance metric for vector indexes ("l2" or "cosine")
    pub metric: Option<String>,
}

#[derive(Debug, Clone)]
pub enum IndexType {
    BTree,
    Column, // 🆕 Column value index (same as BTree but explicit name)
    Text,
    Vector,
    Octree, // i-Octree for 3D point cloud (embodied intelligence)
    Timestamp,
}

/// DROP TABLE statement
#[derive(Debug, Clone)]
pub struct DropTableStmt {
    pub table: String,
    pub if_exists: bool,
}

/// DROP INDEX statement
#[derive(Debug, Clone)]
pub struct DropIndexStmt {
    pub index_name: String,
}

/// 🆕 ALTER TABLE statement
#[derive(Debug, Clone)]
pub struct AlterTableStmt {
    pub table: String,
    pub action: AlterTableAction,
}

/// 🆕 ALTER TABLE actions
#[derive(Debug, Clone)]
pub enum AlterTableAction {
    /// ALTER TABLE table_name AUTO_INCREMENT = value
    SetAutoIncrement(i64),
    /// ALTER TABLE table_name ADD COLUMN name type [DEFAULT value] [NOT NULL]
    AddColumn {
        name: String,
        data_type: super::ast::DataType,
        default_value: Option<crate::types::Value>,
        nullable: bool,
    },
}

/// Expression
#[derive(Debug, Clone)]
pub enum Expr {
    /// Column reference
    Column(String),

    /// Literal value
    Literal(Value),

    /// Bind variable (? or ?1, ?2, ...)
    Parameter(usize),

    /// Binary operation
    BinaryOp {
        left: Box<Expr>,
        op: BinaryOperator,
        right: Box<Expr>,
    },

    /// Unary operation
    UnaryOp { op: UnaryOperator, expr: Box<Expr> },

    /// Function call
    FunctionCall {
        name: String,
        args: Vec<Expr>,
        distinct: bool, // For COUNT(DISTINCT column)
    },

    /// 🆕 Window function call
    ///
    /// Syntax: function_name(args) OVER ([PARTITION BY ...] [ORDER BY ...])
    ///
    /// Examples:
    /// - ROW_NUMBER() OVER (ORDER BY id)
    /// - RANK() OVER (PARTITION BY category ORDER BY score DESC)
    /// - LAG(price, 1) OVER (PARTITION BY product_id ORDER BY date)
    WindowFunction {
        func: WindowFunc,
        partition_by: Option<Vec<String>>,  // PARTITION BY columns
        order_by: Option<Vec<OrderByExpr>>, // ORDER BY in window
    },

    /// IN expression: column IN (val1, val2, ...) or column IN (SELECT ...)
    ///
    /// Examples:
    /// - WHERE id IN (1, 2, 3)  -> list contains literal expressions
    /// - WHERE id IN (SELECT user_id FROM orders)  -> list contains a single Subquery expression
    In {
        expr: Box<Expr>,
        list: Vec<Expr>, // Either multiple literals OR a single Subquery
        negated: bool,
    },

    /// IN with a pre-built HashSet (from subquery materialization).
    ///
    /// Produced by `materialize_subqueries` when an IN-subquery is resolved.
    /// Carries the pre-built `HashSet<Value>` end-to-end so every consumer
    /// does O(1) per-row lookup instead of rebuilding the set from a
    /// `Vec<Expr::Literal>` and/or iterating the full list per row.
    ///
    /// Without this, `WHERE x IN (SELECT ...)` over 300K rows × 100K-element
    /// list took 25.5s (the Vec→HashSet round-trip + O(list_len) per row).
    InHashset {
        expr: Box<Expr>,
        set: std::collections::HashSet<crate::types::Value>,
        negated: bool,
        /// True if the subquery result contained any NULL. Per SQL standard,
        /// `x NOT IN (subquery)` returns no rows when the subquery has a NULL.
        has_null: bool,
    },

    /// BETWEEN expression: column BETWEEN low AND high
    Between {
        expr: Box<Expr>,
        low: Box<Expr>,
        high: Box<Expr>,
        negated: bool,
    },

    /// LIKE expression: column LIKE pattern
    Like {
        expr: Box<Expr>,
        pattern: Box<Expr>,
        negated: bool,
    },

    /// IS NULL expression
    IsNull { expr: Box<Expr>, negated: bool },

    /// Subquery expression
    ///
    /// Used in multiple contexts:
    /// - WHERE x IN (SELECT ...)
    /// - WHERE x = (SELECT ...)  (scalar subquery)
    /// - SELECT (SELECT ...) AS col (scalar subquery in projection)
    Subquery(Box<SelectStmt>),

    /// MATCH...AGAINST full-text search
    ///
    /// Syntax: MATCH(column) AGAINST(query_string)
    /// Returns: BM25 relevance score (Float)
    ///
    /// Examples:
    /// - WHERE MATCH(content) AGAINST('rust database')
    /// - ORDER BY MATCH(content) AGAINST('search query') DESC
    /// - SELECT MATCH(content) AGAINST('keyword') AS score
    Match {
        column: String,
        query: String,
        /// If true, the query is an exact phrase (wrapped in double quotes)
        phrase: bool,
    },

    /// KNN_SEARCH vector similarity search
    ///
    /// Syntax: KNN_SEARCH(vector_column, query_vector, k)
    /// Returns: Bool (true if in top-k results)
    ///
    /// Examples:
    /// - WHERE KNN_SEARCH(embedding, [0.1, 0.2], 10)
    /// - Used with KNN_DISTANCE() for scoring
    KnnSearch {
        column: String,
        query_vector: crate::types::ArcVec,
        k: usize,
    },

    /// KNN_DISTANCE vector distance function
    ///
    /// Syntax: KNN_DISTANCE(vector_column, query_vector)
    /// Returns: Float (distance/similarity score)
    ///
    /// Examples:
    /// - SELECT KNN_DISTANCE(embedding, [0.1, 0.2]) AS distance
    /// - ORDER BY KNN_DISTANCE(embedding, [0.1, 0.2])
    KnnDistance {
        column: String,
        query_vector: crate::types::ArcVec,
    },

    // ---- 3D Spatial expressions (i-Octree) ----
    /// ST_WITHIN_3D: 3D bounding box range query
    /// Syntax: WHERE ST_WITHIN_3D(column, min_x, min_y, min_z, max_x, max_y, max_z)
    StWithin3D {
        column: String,
        min_x: f64,
        min_y: f64,
        min_z: f64,
        max_x: f64,
        max_y: f64,
        max_z: f64,
    },

    /// ST_DISTANCE_3D: 3D Euclidean distance
    /// Syntax: ST_DISTANCE_3D(column, x, y, z)
    StDistance3D {
        column: String,
        x: f64,
        y: f64,
        z: f64,
    },

    /// ST_KNN_3D: 3D k-nearest neighbors
    /// Syntax: WHERE ST_KNN_3D(column, x, y, z, k)
    StKnn3D {
        column: String,
        x: f64,
        y: f64,
        z: f64,
        k: usize,
    },

    /// ST_RADIUS_3D: 3D radius search
    /// Syntax: WHERE ST_RADIUS_3D(column, x, y, z, radius)
    StRadius3D {
        column: String,
        x: f64,
        y: f64,
        z: f64,
        radius: f64,
    },

    /// CASE WHEN expression
    /// Syntax: CASE WHEN cond1 THEN val1 [WHEN cond2 THEN val2 ...] [ELSE default] END
    Case {
        whens: Vec<(Expr, Expr)>, // (condition, result)
        else_expr: Option<Box<Expr>>,
    },
}

#[derive(Debug, Clone, PartialEq)]
pub enum BinaryOperator {
    // Comparison
    Eq, // =
    Ne, // !=
    Lt, // <
    Gt, // >
    Le, // <=
    Ge, // >=

    // Logical
    And,
    Or,

    // Arithmetic
    Add, // +
    Sub, // -
    Mul, // *
    Div, // /
    Mod, // %
    /// String concatenation `||` (SQL standard).
    Concat,

    // E-SQL Vector Distance Operators
    L2Distance,     // <-> (Euclidean distance)
    CosineDistance, // <=> (Cosine distance)
    DotProduct,     // <#> (Inner product)
}

#[derive(Debug, Clone, PartialEq)]
pub enum UnaryOperator {
    Not,
    Minus,
    Plus,
}

impl BinaryOperator {
    /// Get operator precedence (higher = tighter binding)
    pub fn precedence(&self) -> u8 {
        match self {
            BinaryOperator::Or => 1,
            BinaryOperator::And => 2,
            BinaryOperator::Eq
            | BinaryOperator::Ne
            | BinaryOperator::Lt
            | BinaryOperator::Gt
            | BinaryOperator::Le
            | BinaryOperator::Ge => 3,
            // Vector distance operators have same precedence as comparison
            BinaryOperator::L2Distance
            | BinaryOperator::CosineDistance
            | BinaryOperator::DotProduct => 3,
            BinaryOperator::Add | BinaryOperator::Sub => 4,
            BinaryOperator::Mul | BinaryOperator::Div | BinaryOperator::Mod => 5,
            // 🔑 || concatenation binds tighter than comparison (3) so
            // `a || b = 'xy'` parses as `(a || b) = 'xy'`.
            BinaryOperator::Concat => 5,
        }
    }
}

/// 🆕 Window function types
#[derive(Debug, Clone)]
pub enum WindowFunc {
    /// ROW_NUMBER() - sequential number of row within partition
    RowNumber,
    /// RANK() - rank with gaps for ties
    Rank,
    /// DENSE_RANK() - rank without gaps for ties
    DenseRank,
    /// LAG(expr, offset, default) - value from previous row
    Lag {
        expr: Box<Expr>,
        offset: Option<usize>,      // Default: 1
        default: Option<Box<Expr>>, // Default: NULL
    },
    /// LEAD(expr, offset, default) - value from next row
    Lead {
        expr: Box<Expr>,
        offset: Option<usize>,      // Default: 1
        default: Option<Box<Expr>>, // Default: NULL
    },
}