audb 0.1.11

AuDB - Compile-time database application framework with gold files
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
//! Schema system for AuDB
//!
//! This module provides schema definitions supporting multiple formats
//! (native, JSON Schema, TypeScript, etc.)

use crate::error::{Error, Result};
use std::collections::HashMap;

/// Schema definition
#[derive(Debug, Clone)]
pub struct Schema {
    /// Schema name
    pub name: String,

    /// Schema format
    pub format: SchemaFormat,

    /// Fields in the schema
    pub fields: Vec<Field>,

    /// Documentation comment
    pub doc_comment: Option<String>,

    /// Helper methods to generate
    pub methods: Vec<String>,

    /// Whether to auto-generate CRUD endpoints
    pub crud: bool,
}

impl Schema {
    /// Create a new schema
    pub fn new(name: String, format: SchemaFormat) -> Self {
        Self {
            name,
            format,
            fields: Vec::new(),
            doc_comment: None,
            methods: Vec::new(),
            crud: false,
        }
    }

    /// Add a field to the schema
    pub fn add_field(&mut self, field: Field) {
        self.fields.push(field);
    }

    /// Get a field by name
    pub fn get_field(&self, name: &str) -> Option<&Field> {
        self.fields.iter().find(|f| f.name == name)
    }

    /// Validate the schema
    pub fn validate(&self) -> Result<()> {
        // Check for duplicate field names
        let mut seen = HashMap::new();
        for field in &self.fields {
            if seen.insert(&field.name, ()).is_some() {
                return Err(Error::Schema {
                    schema_name: self.name.clone(),
                    message: format!("Duplicate field '{}'", field.name),
                });
            }
        }

        // Validate each field
        for field in &self.fields {
            field.validate()?;
        }

        Ok(())
    }
}

/// Schema format
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaFormat {
    /// Native Rust-like syntax (default)
    Native,

    /// JSON Schema
    JsonSchema,

    /// TypeScript interface
    TypeScript,

    /// Rust struct definition
    Rust,
}

impl SchemaFormat {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "native" => SchemaFormat::Native,
            "json_schema" | "jsonschema" => SchemaFormat::JsonSchema,
            "typescript" | "ts" => SchemaFormat::TypeScript,
            "rust" => SchemaFormat::Rust,
            _ => SchemaFormat::Native,
        }
    }
}

/// Schema field
#[derive(Debug, Clone)]
pub struct Field {
    /// Field name
    pub name: String,

    /// Field type
    pub field_type: Type,

    /// Whether the field is nullable
    pub nullable: bool,

    /// Default value
    pub default: Option<String>,

    /// Attributes (unique, validate, etc.)
    pub attributes: Vec<FieldAttribute>,

    /// Documentation comment
    pub doc_comment: Option<String>,

    /// Embedding configuration (if this field is a vector embedding)
    pub embedding_config: Option<EmbeddingConfig>,
}

impl Field {
    /// Create a new field
    pub fn new(name: String, field_type: Type) -> Self {
        Self {
            name,
            field_type,
            nullable: false,
            default: None,
            attributes: Vec::new(),
            doc_comment: None,
            embedding_config: None,
        }
    }

    /// Validate the field
    pub fn validate(&self) -> Result<()> {
        // Validate field type
        self.field_type.validate()?;

        // Check for conflicting attributes
        let mut has_unique = false;
        let mut has_private = false;

        for attr in &self.attributes {
            match attr {
                FieldAttribute::Unique => has_unique = true,
                FieldAttribute::Private => has_private = true,
                _ => {}
            }
        }

        // Private fields can't be unique (doesn't make sense)
        if has_unique && has_private {
            return Err(Error::Validation {
                message: format!("Field '{}' cannot be both unique and private", self.name),
                context: None,
            });
        }

        Ok(())
    }
}

/// Embedding configuration for vector fields
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmbeddingConfig {
    /// Model to use for generating embeddings (e.g., "bge-base-en-v1.5")
    pub model: String,

    /// Source field to generate embeddings from
    pub source_field: String,

    /// Optional dimension override (if not specified, queried from Tessera model registry)
    pub dimension: Option<usize>,

    /// Optional: Paradigm (dense, multi-vector, sparse, etc.)
    pub paradigm: Option<EmbeddingParadigm>,
}

impl EmbeddingConfig {
    /// Create a new embedding configuration
    pub fn new(model: String, source_field: String) -> Self {
        Self {
            model,
            source_field,
            dimension: None,
            paradigm: None,
        }
    }

    /// Create embedding configuration with explicit dimension
    pub fn with_dimension(model: String, source_field: String, dimension: usize) -> Self {
        Self {
            model,
            source_field,
            dimension: Some(dimension),
            paradigm: None,
        }
    }

    /// Set the embedding paradigm
    pub fn with_paradigm(mut self, paradigm: EmbeddingParadigm) -> Self {
        self.paradigm = Some(paradigm);
        self
    }

    /// Validate the embedding configuration
    pub fn validate(&self) -> Result<()> {
        if self.model.is_empty() {
            return Err(Error::Validation {
                message: "Embedding model cannot be empty".to_string(),
                context: None,
            });
        }

        if self.source_field.is_empty() {
            return Err(Error::Validation {
                message: "Embedding source_field cannot be empty".to_string(),
                context: None,
            });
        }

        if let Some(dim) = self.dimension {
            if dim == 0 {
                return Err(Error::Validation {
                    message: "Embedding dimension must be greater than 0".to_string(),
                    context: None,
                });
            }
        }

        Ok(())
    }
}

/// Embedding paradigm (dense, multi-vector, sparse, etc.)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EmbeddingParadigm {
    /// Dense single-vector embeddings (default)
    Dense,

    /// Multi-vector embeddings (ColBERT-style)
    MultiVector,

    /// Sparse embeddings (SPLADE-style)
    Sparse,

    /// Vision-language embeddings (ColPali)
    VisionLanguage,

    /// Time series forecasting
    TimeSeries,
}

impl EmbeddingParadigm {
    /// Parse paradigm from string
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "dense" => Some(EmbeddingParadigm::Dense),
            "multi-vector" | "multivector" | "colbert" => Some(EmbeddingParadigm::MultiVector),
            "sparse" | "splade" => Some(EmbeddingParadigm::Sparse),
            "vision-language" | "visionlanguage" | "colpali" => {
                Some(EmbeddingParadigm::VisionLanguage)
            }
            "timeseries" | "time-series" => Some(EmbeddingParadigm::TimeSeries),
            _ => None,
        }
    }
}

/// Field attribute (@unique, @private, etc.)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldAttribute {
    /// Field is unique
    Unique,

    /// Field is private (never exposed in API)
    Private,

    /// Field should be indexed
    Index,

    /// Field is auto-populated
    Auto,

    /// Field has a default value
    Default(String),

    /// Field has validation rules
    Validate(String),
}

/// Type system for schema fields
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Type {
    /// Primitive types
    String,
    Integer,
    Float,
    Boolean,
    Timestamp,

    /// Entity ID (UUID)
    EntityId,

    /// Enum type with variants
    Enum(Vec<String>),

    /// Optional type
    Option(Box<Type>),

    /// Vector/List type
    Vec(Box<Type>),

    /// Custom type (reference to another schema)
    Custom(String),

    /// Named type (reference to a schema by name)
    Named(String),

    /// JSON value (arbitrary JSON)
    JsonValue,

    /// Vector embedding type (dimension specified in EmbeddingConfig)
    Vector,

    /// Unit type (no value)
    Unit,
}

impl Type {
    /// Validate the type
    pub fn validate(&self) -> Result<()> {
        match self {
            Type::Enum(variants) if variants.is_empty() => Err(Error::Validation {
                message: "Enum type must have at least one variant".to_string(),
                context: None,
            }),
            Type::Option(inner) => inner.validate(),
            Type::Vec(inner) => inner.validate(),
            _ => Ok(()),
        }
    }

    /// Convert type to Rust type string
    pub fn to_rust_type(&self) -> String {
        match self {
            Type::String => "String".to_string(),
            Type::Integer => "i64".to_string(),
            Type::Float => "f64".to_string(),
            Type::Boolean => "bool".to_string(),
            Type::Timestamp => "u64".to_string(),
            Type::EntityId => "EntityId".to_string(),
            Type::Enum(variants) => {
                // Generate enum name from variants
                format!("Enum{}", variants.join(""))
            }
            Type::Option(inner) => format!("Option<{}>", inner.to_rust_type()),
            Type::Vec(inner) => format!("Vec<{}>", inner.to_rust_type()),
            Type::Custom(name) => name.clone(),
            Type::Named(name) => name.clone(),
            Type::JsonValue => "serde_json::Value".to_string(),
            Type::Vector => "Vec<f32>".to_string(),
            Type::Unit => "()".to_string(),
        }
    }

    /// Parse type from string (e.g., "String!", "Vec<Integer>", etc.)
    pub fn from_str(s: &str) -> Result<Self> {
        let s = s.trim();

        // Check for required (!) suffix
        if s.ends_with('!') {
            return Type::from_str(&s[..s.len() - 1]);
        }

        // Check for Vec<T>
        if s.starts_with("Vec<") && s.ends_with('>') {
            let inner = &s[4..s.len() - 1];
            return Ok(Type::Vec(Box::new(Type::from_str(inner)?)));
        }

        // Check for Option<T>
        if s.starts_with("Option<") && s.ends_with('>') {
            let inner = &s[7..s.len() - 1];
            return Ok(Type::Option(Box::new(Type::from_str(inner)?)));
        }

        // Check for Enum(...)
        if s.starts_with("Enum(") && s.ends_with(')') {
            let variants_str = &s[5..s.len() - 1];
            let variants: Vec<String> = variants_str
                .split(',')
                .map(|v| v.trim().trim_matches('"').to_string())
                .collect();
            return Ok(Type::Enum(variants));
        }

        // Primitive types
        match s {
            "String" => Ok(Type::String),
            "Integer" => Ok(Type::Integer),
            "Float" => Ok(Type::Float),
            "Boolean" => Ok(Type::Boolean),
            "Timestamp" => Ok(Type::Timestamp),
            "EntityId" => Ok(Type::EntityId),
            "JsonValue" => Ok(Type::JsonValue),
            "Vector" => Ok(Type::Vector),
            _ => Ok(Type::Custom(s.to_string())),
        }
    }
}

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

    #[test]
    fn test_schema_creation() {
        let mut schema = Schema::new("User".to_string(), SchemaFormat::Native);
        assert_eq!(schema.name, "User");
        assert_eq!(schema.fields.len(), 0);

        schema.add_field(Field::new("id".to_string(), Type::EntityId));
        assert_eq!(schema.fields.len(), 1);
    }

    #[test]
    fn test_schema_validation_duplicate_fields() {
        let mut schema = Schema::new("User".to_string(), SchemaFormat::Native);
        schema.add_field(Field::new("id".to_string(), Type::EntityId));
        schema.add_field(Field::new("id".to_string(), Type::String));

        assert!(schema.validate().is_err());
    }

    #[test]
    fn test_type_from_str() {
        assert_eq!(Type::from_str("String").unwrap(), Type::String);
        assert_eq!(Type::from_str("Integer").unwrap(), Type::Integer);
        assert_eq!(
            Type::from_str("Vec<String>").unwrap(),
            Type::Vec(Box::new(Type::String))
        );
        assert_eq!(
            Type::from_str("Option<Integer>").unwrap(),
            Type::Option(Box::new(Type::Integer))
        );
    }

    #[test]
    fn test_type_to_rust_type() {
        assert_eq!(Type::String.to_rust_type(), "String");
        assert_eq!(Type::Integer.to_rust_type(), "i64");
        assert_eq!(
            Type::Vec(Box::new(Type::String)).to_rust_type(),
            "Vec<String>"
        );
        assert_eq!(
            Type::Option(Box::new(Type::Integer)).to_rust_type(),
            "Option<i64>"
        );
    }

    #[test]
    fn test_enum_type_validation() {
        let empty_enum = Type::Enum(vec![]);
        assert!(empty_enum.validate().is_err());

        let valid_enum = Type::Enum(vec!["admin".to_string(), "user".to_string()]);
        assert!(valid_enum.validate().is_ok());
    }

    #[test]
    fn test_field_validation_conflicting_attributes() {
        let mut field = Field::new("password".to_string(), Type::String);
        field.attributes.push(FieldAttribute::Unique);
        field.attributes.push(FieldAttribute::Private);

        assert!(field.validate().is_err());
    }

    #[test]
    fn test_embedding_config_validation() {
        let valid_config =
            EmbeddingConfig::new("bge-base-en-v1.5".to_string(), "content".to_string());
        assert!(valid_config.validate().is_ok());

        let valid_with_dim = EmbeddingConfig::with_dimension(
            "bge-base-en-v1.5".to_string(),
            "content".to_string(),
            768,
        );
        assert!(valid_with_dim.validate().is_ok());

        let empty_model = EmbeddingConfig::new("".to_string(), "content".to_string());
        assert!(empty_model.validate().is_err());

        let empty_source = EmbeddingConfig::new("bge-base-en-v1.5".to_string(), "".to_string());
        assert!(empty_source.validate().is_err());

        let zero_dim = EmbeddingConfig::with_dimension(
            "bge-base-en-v1.5".to_string(),
            "content".to_string(),
            0,
        );
        assert!(zero_dim.validate().is_err());
    }

    #[test]
    fn test_embedding_paradigm_parsing() {
        assert_eq!(
            EmbeddingParadigm::from_str("dense"),
            Some(EmbeddingParadigm::Dense)
        );
        assert_eq!(
            EmbeddingParadigm::from_str("multi-vector"),
            Some(EmbeddingParadigm::MultiVector)
        );
        assert_eq!(
            EmbeddingParadigm::from_str("colbert"),
            Some(EmbeddingParadigm::MultiVector)
        );
        assert_eq!(
            EmbeddingParadigm::from_str("sparse"),
            Some(EmbeddingParadigm::Sparse)
        );
        assert_eq!(EmbeddingParadigm::from_str("invalid"), None);
    }

    #[test]
    fn test_vector_type() {
        assert_eq!(Type::Vector.to_rust_type(), "Vec<f32>");
        assert_eq!(Type::from_str("Vector").unwrap(), Type::Vector);
    }
}