audb-runtime 0.1.11

Runtime library for AuDB database applications with Manifold backend
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
//! Runtime type definitions
//!
//! This module defines the core types used for query results and data representation.

use crate::error::{QueryError, Result};
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use uuid::Uuid;

/// Result of a query execution
///
/// Contains the rows returned by the query and metadata about the execution.
#[derive(Debug, Clone)]
pub struct QueryResult {
    /// Rows returned by the query
    pub rows: Vec<Row>,

    /// Number of rows affected by the query (for INSERT, UPDATE, DELETE)
    pub affected_rows: usize,
}

impl QueryResult {
    /// Create a new empty query result
    pub fn new() -> Self {
        Self {
            rows: Vec::new(),
            affected_rows: 0,
        }
    }

    /// Create a new query result with rows
    pub fn with_rows(rows: Vec<Row>) -> Self {
        Self {
            rows,
            affected_rows: 0,
        }
    }

    /// Create a new query result for a modification query
    pub fn with_affected_rows(affected_rows: usize) -> Self {
        Self {
            rows: Vec::new(),
            affected_rows,
        }
    }

    /// Get the number of rows returned
    pub fn len(&self) -> usize {
        self.rows.len()
    }

    /// Check if the result is empty
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    /// Get a single row, returning an error if zero or multiple rows exist
    pub fn one(self) -> Result<Row> {
        match self.rows.len() {
            0 => Err(QueryError::RowNotFound),
            1 => Ok(self.rows.into_iter().next().unwrap()),
            n => Err(QueryError::MultipleRowsFound { count: n }),
        }
    }

    /// Get an optional single row, returning None if zero rows, error if multiple
    pub fn optional(self) -> Result<Option<Row>> {
        match self.rows.len() {
            0 => Ok(None),
            1 => Ok(Some(self.rows.into_iter().next().unwrap())),
            n => Err(QueryError::MultipleRowsFound { count: n }),
        }
    }

    /// Get all rows as a Vec
    pub fn all(self) -> Vec<Row> {
        self.rows
    }

    /// Iterate over rows
    pub fn iter(&self) -> impl Iterator<Item = &Row> {
        self.rows.iter()
    }
}

impl Default for QueryResult {
    fn default() -> Self {
        Self::new()
    }
}

impl IntoIterator for QueryResult {
    type Item = Row;
    type IntoIter = std::vec::IntoIter<Row>;

    fn into_iter(self) -> Self::IntoIter {
        self.rows.into_iter()
    }
}

/// A single row from a query result
///
/// Rows are represented as maps from column names to values.
#[derive(Debug, Clone, PartialEq)]
pub struct Row {
    /// Column values
    columns: HashMap<String, Value>,
}

impl Row {
    /// Create a new empty row
    pub fn new() -> Self {
        Self {
            columns: HashMap::new(),
        }
    }

    /// Create a row from a map of columns
    pub fn from_map(columns: HashMap<String, Value>) -> Self {
        Self { columns }
    }

    /// Get a value by column name
    pub fn get(&self, column: &str) -> Option<&Value> {
        self.columns.get(column)
    }

    /// Get a required value by column name
    pub fn get_required(&self, column: &str) -> Result<&Value> {
        self.columns
            .get(column)
            .ok_or_else(|| QueryError::missing_field(column))
    }

    /// Set a column value
    pub fn insert(&mut self, column: String, value: Value) {
        self.columns.insert(column, value);
    }

    /// Check if a column exists
    pub fn has_column(&self, column: &str) -> bool {
        self.columns.contains_key(column)
    }

    /// Get all column names
    pub fn columns(&self) -> Vec<&str> {
        self.columns.keys().map(|s| s.as_str()).collect()
    }

    /// Get the number of columns
    pub fn len(&self) -> usize {
        self.columns.len()
    }

    /// Check if the row is empty
    pub fn is_empty(&self) -> bool {
        self.columns.is_empty()
    }
}

impl Default for Row {
    fn default() -> Self {
        Self::new()
    }
}

/// A value that can be stored in a database
///
/// This enum represents all possible value types in AuDB.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// Null value
    Null,

    /// Boolean value
    Bool(bool),

    /// Integer value (i64)
    Integer(i64),

    /// Float value (f64)
    Float(f64),

    /// String value
    String(String),

    /// UUID value (entity ID)
    Uuid(Uuid),

    /// Timestamp value
    Timestamp(DateTime<Utc>),

    /// Binary data
    Bytes(Vec<u8>),

    /// Array of values
    Array(Vec<Value>),

    /// Object (key-value pairs)
    Object(HashMap<String, Value>),
}

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

    /// Try to convert to a boolean
    pub fn as_bool(&self) -> Result<bool> {
        match self {
            Value::Bool(b) => Ok(*b),
            _ => Err(QueryError::type_mismatch("Bool", self.type_name())),
        }
    }

    /// Try to convert to an integer
    pub fn as_i64(&self) -> Result<i64> {
        match self {
            Value::Integer(i) => Ok(*i),
            _ => Err(QueryError::type_mismatch("Integer", self.type_name())),
        }
    }

    /// Try to convert to a float
    pub fn as_f64(&self) -> Result<f64> {
        match self {
            Value::Float(f) => Ok(*f),
            Value::Integer(i) => Ok(*i as f64),
            _ => Err(QueryError::type_mismatch("Float", self.type_name())),
        }
    }

    /// Try to convert to a string
    pub fn as_str(&self) -> Result<&str> {
        match self {
            Value::String(s) => Ok(s.as_str()),
            _ => Err(QueryError::type_mismatch("String", self.type_name())),
        }
    }

    /// Try to convert to a UUID
    pub fn as_uuid(&self) -> Result<Uuid> {
        match self {
            Value::Uuid(u) => Ok(*u),
            _ => Err(QueryError::type_mismatch("Uuid", self.type_name())),
        }
    }

    /// Try to convert to a timestamp
    pub fn as_timestamp(&self) -> Result<DateTime<Utc>> {
        match self {
            Value::Timestamp(t) => Ok(*t),
            _ => Err(QueryError::type_mismatch("Timestamp", self.type_name())),
        }
    }

    /// Try to convert to bytes
    pub fn as_bytes(&self) -> Result<&Vec<u8>> {
        match self {
            Value::Bytes(b) => Ok(b),
            _ => Err(QueryError::type_mismatch("Bytes", self.type_name())),
        }
    }

    /// Try to convert to an array
    pub fn as_array(&self) -> Result<&Vec<Value>> {
        match self {
            Value::Array(a) => Ok(a),
            _ => Err(QueryError::type_mismatch("Array", self.type_name())),
        }
    }

    /// Try to convert to an object
    pub fn as_object(&self) -> Result<&HashMap<String, Value>> {
        match self {
            Value::Object(o) => Ok(o),
            _ => Err(QueryError::type_mismatch("Object", self.type_name())),
        }
    }

    /// Get the type name as a string
    pub fn type_name(&self) -> &str {
        match self {
            Value::Null => "Null",
            Value::Bool(_) => "Bool",
            Value::Integer(_) => "Integer",
            Value::Float(_) => "Float",
            Value::String(_) => "String",
            Value::Bytes(_) => "Bytes",
            Value::Uuid(_) => "Uuid",
            Value::Timestamp(_) => "Timestamp",
            Value::Array(_) => "Array",
            Value::Object(_) => "Object",
        }
    }
}

// Conversions from Rust types to Value

impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Value::Bool(b)
    }
}

impl From<i64> for Value {
    fn from(i: i64) -> Self {
        Value::Integer(i)
    }
}

impl From<i32> for Value {
    fn from(i: i32) -> Self {
        Value::Integer(i as i64)
    }
}

impl From<f64> for Value {
    fn from(f: f64) -> Self {
        Value::Float(f)
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Value::String(s)
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Value::String(s.to_string())
    }
}

impl From<Uuid> for Value {
    fn from(u: Uuid) -> Self {
        Value::Uuid(u)
    }
}

impl From<DateTime<Utc>> for Value {
    fn from(t: DateTime<Utc>) -> Self {
        Value::Timestamp(t)
    }
}

impl From<Vec<u8>> for Value {
    fn from(b: Vec<u8>) -> Self {
        Value::Bytes(b)
    }
}

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

    #[test]
    fn test_query_result_new() {
        let result = QueryResult::new();
        assert!(result.is_empty());
        assert_eq!(result.len(), 0);
        assert_eq!(result.affected_rows, 0);
    }

    #[test]
    fn test_query_result_with_rows() {
        let rows = vec![Row::new(), Row::new()];
        let result = QueryResult::with_rows(rows);
        assert_eq!(result.len(), 2);
        assert!(!result.is_empty());
    }

    #[test]
    fn test_query_result_one() {
        let result = QueryResult::with_rows(vec![Row::new()]);
        assert!(result.one().is_ok());

        let empty = QueryResult::new();
        assert!(empty.one().is_err());

        let multiple = QueryResult::with_rows(vec![Row::new(), Row::new()]);
        assert!(multiple.one().is_err());
    }

    #[test]
    fn test_query_result_optional() {
        let result = QueryResult::new();
        assert_eq!(result.optional().unwrap(), None);

        let one = QueryResult::with_rows(vec![Row::new()]);
        assert!(one.optional().unwrap().is_some());

        let multiple = QueryResult::with_rows(vec![Row::new(), Row::new()]);
        assert!(multiple.optional().is_err());
    }

    #[test]
    fn test_row_operations() {
        let mut row = Row::new();
        assert!(row.is_empty());

        row.insert("id".to_string(), Value::Integer(1));
        row.insert("name".to_string(), Value::String("Alice".to_string()));

        assert_eq!(row.len(), 2);
        assert!(row.get("id").is_some());
        assert!(row.get("name").is_some());
        assert!(row.get("missing").is_none());
    }

    #[test]
    fn test_row_get_required() {
        let mut row = Row::new();
        row.insert("id".to_string(), Value::Integer(1));

        assert!(row.get_required("id").is_ok());
        assert!(row.get_required("missing").is_err());
    }

    #[test]
    fn test_value_types() {
        assert!(Value::Null.is_null());
        assert!(!Value::Bool(true).is_null());

        let bool_val = Value::Bool(true);
        assert_eq!(bool_val.as_bool().unwrap(), true);

        let int_val = Value::Integer(42);
        assert_eq!(int_val.as_i64().unwrap(), 42);

        let float_val = Value::Float(3.14);
        assert!((float_val.as_f64().unwrap() - 3.14).abs() < 0.01);

        let str_val = Value::String("hello".to_string());
        assert_eq!(str_val.as_str().unwrap(), "hello");
    }

    #[test]
    fn test_value_type_mismatch() {
        let int_val = Value::Integer(42);
        assert!(int_val.as_bool().is_err());
        assert!(int_val.as_str().is_err());

        let str_val = Value::String("hello".to_string());
        assert!(str_val.as_i64().is_err());
    }

    #[test]
    fn test_value_type_name() {
        assert_eq!(Value::Null.type_name(), "Null");
        assert_eq!(Value::Bool(true).type_name(), "Bool");
        assert_eq!(Value::Integer(1).type_name(), "Integer");
        assert_eq!(Value::Float(1.0).type_name(), "Float");
        assert_eq!(Value::String("".to_string()).type_name(), "String");
        assert_eq!(Value::Uuid(Uuid::new_v4()).type_name(), "Uuid");
    }

    #[test]
    fn test_value_conversions() {
        let bool_val: Value = true.into();
        assert!(matches!(bool_val, Value::Bool(true)));

        let int_val: Value = 42i64.into();
        assert!(matches!(int_val, Value::Integer(42)));

        let str_val: Value = "hello".into();
        assert!(matches!(str_val, Value::String(_)));

        let uuid = Uuid::new_v4();
        let uuid_val: Value = uuid.into();
        assert!(matches!(uuid_val, Value::Uuid(_)));
    }

    #[test]
    fn test_value_float_from_int() {
        let int_val = Value::Integer(42);
        assert_eq!(int_val.as_f64().unwrap(), 42.0);
    }

    #[test]
    fn test_value_array() {
        let arr = Value::Array(vec![Value::Integer(1), Value::Integer(2)]);
        let arr_ref = arr.as_array().unwrap();
        assert_eq!(arr_ref.len(), 2);
    }

    #[test]
    fn test_value_object() {
        let mut map = HashMap::new();
        map.insert("key".to_string(), Value::String("value".to_string()));
        let obj = Value::Object(map);
        let obj_ref = obj.as_object().unwrap();
        assert_eq!(obj_ref.len(), 1);
    }
}