tapirus 1.2.1

Embedded multi-model database with SQL, vector search and local AI memory
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Core database API traits and Value/Row representations.
//!
//! Provides the public interfaces for querying, executing statements,
//! and converting typed relational and vector values.

use crate::error::{Error, Result};
use crate::vector::DistanceMetric;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// A dynamic SQL/Document value in TapirusDB
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Value {
    /// NULL
    Null,
    /// 64-bit signed integer
    Integer(i64),
    /// 64-bit IEEE floating point
    Real(f64),
    /// UTF-8 string
    Text(String),
    /// Raw binary blob
    Blob(Vec<u8>),
    /// Dense float embedding vector
    Vector(Vec<f32>),
}

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Null => write!(f, "NULL"),
            Value::Integer(i) => write!(f, "{i}"),
            Value::Real(r) => write!(f, "{r}"),
            Value::Text(s) => write!(f, "{s}"),
            Value::Blob(b) => write!(f, "<BLOB {} B>", b.len()),
            Value::Vector(v) => {
                if v.len() <= 4 {
                    write!(f, "{:?}", v)
                } else {
                    write!(f, "[{:.4}, {:.4}, ... ({} dims)]", v[0], v[1], v.len())
                }
            }
        }
    }
}

impl Value {
    /// Decode an HTTP/SDK bound parameter without interpolating SQL text.
    pub fn from_json_parameter(value: &serde_json::Value) -> Result<Self> {
        match value {
            serde_json::Value::Null => Ok(Self::Null),
            serde_json::Value::Bool(value) => Ok(Self::Integer(i64::from(*value))),
            serde_json::Value::Number(value) => {
                if let Some(integer) = value.as_i64() {
                    Ok(Self::Integer(integer))
                } else if value.is_u64() {
                    Err(Error::ConstraintViolation(
                        "Integer parameter exceeds i64 range".into(),
                    ))
                } else {
                    value
                        .as_f64()
                        .filter(|number| number.is_finite())
                        .map(Self::Real)
                        .ok_or_else(|| {
                            Error::ConstraintViolation("Non-finite numeric parameter".into())
                        })
                }
            }
            serde_json::Value::String(value) => Ok(Self::Text(value.clone())),
            serde_json::Value::Array(values) => {
                let vector = values
                    .iter()
                    .map(|value| {
                        value
                            .as_f64()
                            .map(|number| number as f32)
                            .filter(|number| number.is_finite())
                            .ok_or_else(|| {
                                Error::ConstraintViolation(
                                    "Vector parameter requires finite numbers".into(),
                                )
                            })
                    })
                    .collect::<Result<Vec<_>>>()?;
                Ok(Self::Vector(vector))
            }
            serde_json::Value::Object(value)
                if value.len() == 1 && value.contains_key("$integer") =>
            {
                value["$integer"]
                    .as_str()
                    .and_then(|number| number.parse::<i64>().ok())
                    .map(Self::Integer)
                    .ok_or_else(|| Error::ConstraintViolation("Invalid i64 parameter".into()))
            }
            serde_json::Value::Object(value) if value.len() == 1 && value.contains_key("$blob") => {
                let array = value["$blob"].as_array().ok_or_else(|| {
                    Error::ConstraintViolation("Blob parameter requires a byte array".into())
                })?;
                Ok(Self::Blob(
                    array
                        .iter()
                        .map(|value| {
                            value
                                .as_u64()
                                .and_then(|number| u8::try_from(number).ok())
                                .ok_or_else(|| {
                                    Error::ConstraintViolation("Invalid blob byte".into())
                                })
                        })
                        .collect::<Result<Vec<_>>>()?,
                ))
            }
            serde_json::Value::Object(_) => Ok(Self::Text(value.to_string())),
        }
    }

    /// Check if the value is NULL
    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// Compare two values for SQL sorting (ORDER BY)
    pub fn compare(&self, other: &Self) -> std::cmp::Ordering {
        match (self, other) {
            (Value::Null, Value::Null) => std::cmp::Ordering::Equal,
            (Value::Null, _) => std::cmp::Ordering::Less,
            (_, Value::Null) => std::cmp::Ordering::Greater,
            (Value::Integer(a), Value::Integer(b)) => a.cmp(b),
            (Value::Integer(a), Value::Real(b)) => (*a as f64).total_cmp(b),
            (Value::Real(a), Value::Integer(b)) => a.total_cmp(&(*b as f64)),
            (Value::Real(a), Value::Real(b)) => a.total_cmp(b),
            (Value::Text(a), Value::Text(b)) => a.cmp(b),
            (Value::Blob(a), Value::Blob(b)) => a.cmp(b),
            (Value::Vector(a), Value::Vector(b)) => a.len().cmp(&b.len()),
            _ => std::cmp::Ordering::Equal,
        }
    }

    /// Convert this `Value` into a normalized hashable key
    pub fn to_hashable(&self) -> HashableValue {
        HashableValue::from(self)
    }
}

/// A normalized hashable representation of a SQL `Value` for O(1) hash joins,
/// O(1) hash aggregation (GROUP BY), and hash set deduplication (DISTINCT).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum HashableValue {
    /// NULL representation
    Null,
    /// 64-bit integer
    Integer(i64),
    /// Canonical IEEE-754 bit pattern for float (normalizing -0.0 and NaNs)
    Real(u64),
    /// String key
    Text(String),
    /// Raw byte sequence
    Blob(Vec<u8>),
    /// Vector of canonicalized float bit patterns
    Vector(Vec<u32>),
}

impl From<&Value> for HashableValue {
    fn from(v: &Value) -> Self {
        match v {
            Value::Null => HashableValue::Null,
            Value::Integer(i) => HashableValue::Integer(*i),
            Value::Real(r) => {
                let bits = if r.is_nan() {
                    0x7ff8_0000_0000_0000u64
                } else if *r == 0.0 {
                    0u64
                } else {
                    r.to_bits()
                };
                HashableValue::Real(bits)
            }
            Value::Text(s) => HashableValue::Text(s.clone()),
            Value::Blob(b) => HashableValue::Blob(b.clone()),
            Value::Vector(vec) => {
                let bits = vec
                    .iter()
                    .map(|f| {
                        if f.is_nan() {
                            0x7fc0_0000u32
                        } else if *f == 0.0 {
                            0u32
                        } else {
                            f.to_bits()
                        }
                    })
                    .collect();
                HashableValue::Vector(bits)
            }
        }
    }
}

/// A relational row returned from a query
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Row {
    columns: Arc<Vec<String>>,
    values: Vec<Value>,
}

/// Check if a stored column name matches the requested column target (handling optional table qualifiers)
pub fn col_name_matches(stored: &str, target: &str) -> bool {
    if stored.eq_ignore_ascii_case(target) {
        return true;
    }
    if let Some(pos) = stored.rfind('.')
        && stored[pos + 1..].eq_ignore_ascii_case(target)
    {
        return true;
    }
    if let Some(pos) = target.rfind('.')
        && target[pos + 1..].eq_ignore_ascii_case(stored)
    {
        return true;
    }
    false
}

fn extract_json_path_value(json_str: &str, raw_path: &str) -> Option<Value> {
    let clean_path = raw_path
        .trim_matches(|c| c == '\'' || c == '"')
        .trim_start_matches('$')
        .trim_start_matches('.');

    let parsed: serde_json::Value = serde_json::from_str(json_str).ok()?;
    if clean_path.is_empty() {
        return Some(json_value_to_db_value(&parsed));
    }

    let mut current = &parsed;
    for segment in clean_path.split('.') {
        if segment.is_empty() {
            continue;
        }
        match current {
            serde_json::Value::Object(map) => {
                current = map.get(segment)?;
            }
            serde_json::Value::Array(arr) => {
                let idx: usize = segment.parse().ok()?;
                current = arr.get(idx)?;
            }
            _ => return None,
        }
    }

    Some(json_value_to_db_value(current))
}

fn json_value_to_db_value(val: &serde_json::Value) -> Value {
    match val {
        serde_json::Value::Null => Value::Null,
        serde_json::Value::Bool(b) => Value::Integer(if *b { 1 } else { 0 }),
        serde_json::Value::Number(num) => {
            if let Some(i) = num.as_i64() {
                Value::Integer(i)
            } else if let Some(f) = num.as_f64() {
                Value::Real(f)
            } else {
                Value::Null
            }
        }
        serde_json::Value::String(s) => Value::Text(s.clone()),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => Value::Text(val.to_string()),
    }
}

impl Row {
    /// Create a new Row from column names and values
    pub fn new(columns: Vec<String>, values: Vec<Value>) -> Self {
        Self {
            columns: Arc::new(columns),
            values,
        }
    }

    /// Create a new Row with shared column names Arc (zero-allocation schema sharing)
    pub fn with_shared_columns(columns: Arc<Vec<String>>, values: Vec<Value>) -> Self {
        Self { columns, values }
    }

    /// Return reference to shared column names Arc
    pub fn shared_columns(&self) -> &Arc<Vec<String>> {
        &self.columns
    }

    /// Push or overwrite a column value in the row
    pub fn push_column(&mut self, col_name: String, val: Value) {
        let cols = Arc::make_mut(&mut self.columns);
        if let Some(pos) = cols.iter().position(|c| col_name_matches(c, &col_name)) {
            self.values[pos] = val;
        } else {
            cols.push(col_name);
            self.values.push(val);
        }
    }

    /// Extract a typed column by name (supports both qualified "table.col" and unqualified "col")
    pub fn get<T: FromValue>(&self, col_name: &str) -> Result<T> {
        let idx = self
            .columns
            .iter()
            .position(|c| col_name_matches(c, col_name))
            .ok_or_else(|| Error::Corrupted(format!("Column '{col_name}' not found in row")))?;
        T::from_value(&self.values[idx])
    }

    /// Extract raw Value reference by column name
    pub fn get_value(&self, col_name: &str) -> Option<&Value> {
        let idx = self
            .columns
            .iter()
            .position(|c| col_name_matches(c, col_name))?;
        self.values.get(idx)
    }

    /// Extract a Value reference or evaluate a nested JSON path expression (e.g. `doc.address.city` or `JSON_EXTRACT(doc, '$.city')`)
    pub fn get_field_or_json_path(&self, col_expr: &str) -> Option<Value> {
        // 1. Direct match on column name
        if let Some(val) = self.get_value(col_expr) {
            return Some(val.clone());
        }

        // 2. Function syntax: JSON_EXTRACT(col, '$.path')
        let trimmed = col_expr.trim();
        if trimmed.to_ascii_uppercase().starts_with("JSON_EXTRACT(") && trimmed.ends_with(')') {
            let inner = &trimmed[13..trimmed.len() - 1];
            if let Some(comma_pos) = inner.find(',') {
                let col = inner[..comma_pos].trim();
                let path = inner[comma_pos + 1..].trim();
                if let Some(Value::Text(json_str)) = self.get_value(col) {
                    return extract_json_path_value(json_str, path);
                }
            }
        }

        // 3. Dotted path syntax: base_col.field.subfield
        if let Some(dot_pos) = col_expr.find('.') {
            let base = &col_expr[..dot_pos];
            let path = &col_expr[dot_pos + 1..];

            // Check if base matches any column in the row
            if let Some(Value::Text(json_str)) = self.get_value(base) {
                return extract_json_path_value(json_str, path);
            }
        }

        None
    }

    /// Extract a typed column by index (0-based)
    pub fn get_idx<T: FromValue>(&self, idx: usize) -> Result<T> {
        let val = self.values.get(idx).ok_or_else(|| {
            Error::Corrupted(format!(
                "Column index {idx} out of bounds (len: {})",
                self.values.len()
            ))
        })?;
        T::from_value(val)
    }

    /// Column names
    pub fn columns(&self) -> &[String] {
        &self.columns
    }

    /// Column values
    pub fn values(&self) -> &[Value] {
        &self.values
    }
}

/// Conversion trait from a TapirusDB `Value` into a native Rust type
pub trait FromValue: Sized {
    /// Convert from value reference
    fn from_value(value: &Value) -> Result<Self>;
}

impl FromValue for i64 {
    fn from_value(value: &Value) -> Result<Self> {
        match value {
            Value::Integer(i) => Ok(*i),
            _ => Err(Error::Corrupted("Type mismatch: expected Integer".into())),
        }
    }
}

impl FromValue for i32 {
    fn from_value(value: &Value) -> Result<Self> {
        match value {
            Value::Integer(i) => Ok(*i as i32),
            _ => Err(Error::Corrupted("Type mismatch: expected Integer".into())),
        }
    }
}

impl FromValue for u64 {
    fn from_value(value: &Value) -> Result<Self> {
        match value {
            Value::Integer(i) if *i >= 0 => Ok(*i as u64),
            _ => Err(Error::Corrupted(
                "Type mismatch: expected non-negative Integer for u64".into(),
            )),
        }
    }
}

impl FromValue for usize {
    fn from_value(value: &Value) -> Result<Self> {
        match value {
            Value::Integer(i) if *i >= 0 => Ok(*i as usize),
            _ => Err(Error::Corrupted(
                "Type mismatch: expected non-negative Integer for usize".into(),
            )),
        }
    }
}

impl FromValue for bool {
    fn from_value(value: &Value) -> Result<Self> {
        match value {
            Value::Integer(i) => Ok(*i != 0),
            Value::Text(s) => match s.to_lowercase().as_str() {
                "true" | "t" | "1" | "yes" => Ok(true),
                "false" | "f" | "0" | "no" => Ok(false),
                _ => Err(Error::Corrupted(format!(
                    "Invalid boolean text representation: {s}"
                ))),
            },
            _ => Err(Error::Corrupted(
                "Type mismatch: expected Boolean (Integer or Text)".into(),
            )),
        }
    }
}

impl FromValue for f64 {
    fn from_value(value: &Value) -> Result<Self> {
        match value {
            Value::Real(r) => Ok(*r),
            Value::Integer(i) => Ok(*i as f64),
            _ => Err(Error::Corrupted("Type mismatch: expected Real".into())),
        }
    }
}

impl FromValue for String {
    fn from_value(value: &Value) -> Result<Self> {
        match value {
            Value::Text(s) => Ok(s.clone()),
            _ => Err(Error::Corrupted("Type mismatch: expected Text".into())),
        }
    }
}

impl FromValue for Vec<u8> {
    fn from_value(value: &Value) -> Result<Self> {
        match value {
            Value::Blob(b) => Ok(b.clone()),
            _ => Err(Error::Corrupted("Type mismatch: expected Blob".into())),
        }
    }
}

impl FromValue for Vec<f32> {
    fn from_value(value: &Value) -> Result<Self> {
        match value {
            Value::Vector(v) => Ok(v.clone()),
            _ => Err(Error::Corrupted("Type mismatch: expected Vector".into())),
        }
    }
}

impl FromValue for Value {
    fn from_value(value: &Value) -> Result<Self> {
        Ok(value.clone())
    }
}

impl<T: FromValue> FromValue for Option<T> {
    fn from_value(value: &Value) -> Result<Self> {
        if value.is_null() {
            Ok(None)
        } else {
            T::from_value(value).map(Some)
        }
    }
}

/// Abstract Vector Index Engine trait for native ANN search
pub trait VectorIndexEngine {
    /// Insert a vector into the index with an associated record ID
    fn insert_vector(&mut self, id: u64, vector: &[f32]) -> Result<()>;

    /// Search K-nearest neighbors for a query vector
    fn search_knn(
        &self,
        query: &[f32],
        k: usize,
        metric: DistanceMetric,
    ) -> Result<Vec<(u64, f32)>>;
}

/// Public Database Connection Trait
pub trait DatabaseConnection {
    /// Execute a SQL DDL or DML statement
    fn execute(&self, sql: &str) -> Result<usize>;

    /// Execute a SQL query returning multiple rows
    fn query(&self, sql: &str) -> Result<Vec<Row>>;

    /// Execute a parameterized non-query SQL command
    fn execute_with_params(&self, sql: &str, params: &[Value]) -> Result<usize> {
        let _ = (sql, params);
        Err(Error::Corrupted(
            "Parameterized execution is not supported by this connection implementation".into(),
        ))
    }

    /// Execute a parameterized SQL query returning multiple rows
    fn query_with_params(&self, sql: &str, params: &[Value]) -> Result<Vec<Row>> {
        let _ = (sql, params);
        Err(Error::Corrupted(
            "Parameterized queries are not supported by this connection implementation".into(),
        ))
    }
}

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

    #[test]
    fn test_row_extraction() {
        let cols = vec![
            "id".into(),
            "name".into(),
            "score".into(),
            "embedding".into(),
        ];
        let vals = vec![
            Value::Integer(1),
            Value::Text("Alex".into()),
            Value::Real(99.5),
            Value::Vector(vec![0.1, 0.2, 0.3]),
        ];

        let row = Row::new(cols, vals);
        let id: i64 = row.get("id").expect("Failed to get id");
        let name: String = row.get("name").expect("Failed to get name");
        let score: f64 = row.get("score").expect("Failed to get score");
        let embedding: Vec<f32> = row.get("embedding").expect("Failed to get embedding");

        assert_eq!(id, 1);
        assert_eq!(name, "Alex");
        assert!((score - 99.5).abs() < 1e-4);
        assert_eq!(embedding.len(), 3);
    }
}