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
//! Schema format parsers
//!
//! This module provides parsers for converting external schema formats
//! (JSON Schema, TypeScript) into AuDB's internal Schema representation.

use crate::error::{Error, Result};
use crate::schema::types::{Field, Schema, SchemaFormat, Type};

/// Parse JSON Schema format into AuDB Schema
///
/// Supports basic JSON Schema properties. Complex features like
/// $ref, allOf, anyOf are not fully supported yet.
///
/// ## Example
///
/// ```ignore
/// let json = r#"{
///   "type": "object",
///   "properties": {
///     "id": {"type": "string"},
///     "name": {"type": "string"},
///     "age": {"type": "integer"}
///   },
///   "required": ["id", "name"]
/// }"#;
///
/// let schema = parse_json_schema("User", json)?;
/// ```
pub fn parse_json_schema(name: &str, content: &str) -> Result<Schema> {
    let json: serde_json::Value = serde_json::from_str(content).map_err(|e| Error::Schema {
        schema_name: name.to_string(),
        message: format!("Failed to parse JSON Schema: {}", e),
    })?;

    let mut schema = Schema::new(name.to_string(), SchemaFormat::JsonSchema);

    // Get properties object
    let properties = json
        .get("properties")
        .and_then(|p| p.as_object())
        .ok_or_else(|| Error::Schema {
            schema_name: name.to_string(),
            message: "JSON Schema missing 'properties' object".to_string(),
        })?;

    // Get required fields list
    let required: Vec<String> = json
        .get("required")
        .and_then(|r| r.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default();

    // Parse each property
    for (field_name, field_spec) in properties {
        let field_type = parse_json_schema_type(field_spec)?;
        let is_required = required.contains(field_name);

        let mut field = Field::new(field_name.clone(), field_type);
        field.nullable = !is_required;

        // Parse description as doc comment
        if let Some(desc) = field_spec.get("description").and_then(|d| d.as_str()) {
            field.doc_comment = Some(desc.to_string());
        }

        schema.add_field(field);
    }

    Ok(schema)
}

/// Parse JSON Schema type into AuDB Type
fn parse_json_schema_type(spec: &serde_json::Value) -> Result<Type> {
    let type_str = spec
        .get("type")
        .and_then(|t| t.as_str())
        .ok_or_else(|| Error::Validation {
            message: "JSON Schema field missing 'type'".to_string(),
            context: Some("parse_json_schema_type".to_string()),
        })?;

    match type_str {
        "string" => {
            // Check for enum
            if let Some(enum_values) = spec.get("enum").and_then(|e| e.as_array()) {
                let variants: Vec<String> = enum_values
                    .iter()
                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
                    .collect();
                return Ok(Type::Enum(variants));
            }
            Ok(Type::String)
        }
        "integer" | "number" => {
            // Determine if it's integer or float based on format
            if let Some(format) = spec.get("format").and_then(|f| f.as_str()) {
                match format {
                    "float" | "double" => Ok(Type::Float),
                    _ => Ok(Type::Integer),
                }
            } else if type_str == "number" {
                Ok(Type::Float)
            } else {
                Ok(Type::Integer)
            }
        }
        "boolean" => Ok(Type::Boolean),
        "array" => {
            // Parse array items type
            if let Some(items) = spec.get("items") {
                let item_type = parse_json_schema_type(items)?;
                Ok(Type::Vec(Box::new(item_type)))
            } else {
                Ok(Type::JsonValue)
            }
        }
        "object" => Ok(Type::JsonValue),
        "null" => Ok(Type::String), // Default to String for null
        _ => Ok(Type::Custom(type_str.to_string())),
    }
}

/// Parse TypeScript interface into AuDB Schema
///
/// Supports basic TypeScript interface syntax. Complex features like
/// extends, generics, union types are simplified or not supported.
///
/// ## Example
///
/// ```ignore
/// let ts = r#"
/// interface User {
///   id: string;
///   name: string;
///   age: number;
///   email?: string;
/// }
/// "#;
///
/// let schema = parse_typescript("User", ts)?;
/// ```
pub fn parse_typescript(name: &str, content: &str) -> Result<Schema> {
    let mut schema = Schema::new(name.to_string(), SchemaFormat::TypeScript);

    // Find interface definition
    let interface_start = content.find("interface").ok_or_else(|| Error::Schema {
        schema_name: name.to_string(),
        message: "TypeScript content missing 'interface' keyword".to_string(),
    })?;

    // Find opening brace
    let body_start = content[interface_start..]
        .find('{')
        .ok_or_else(|| Error::Schema {
            schema_name: name.to_string(),
            message: "TypeScript interface missing opening '{'".to_string(),
        })?
        + interface_start;

    // Find closing brace
    let body_end = content[body_start..]
        .rfind('}')
        .ok_or_else(|| Error::Schema {
            schema_name: name.to_string(),
            message: "TypeScript interface missing closing '}'".to_string(),
        })?
        + body_start;

    let body = &content[body_start + 1..body_end];

    // Parse each field (line by line)
    for line in body.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with("//") {
            continue;
        }

        // Parse field: name?: type; or name: type;
        if let Some(colon_pos) = line.find(':') {
            let name_part = line[..colon_pos].trim();
            let type_part = line[colon_pos + 1..].trim().trim_end_matches(';').trim();

            // Check if optional (has ?)
            let (field_name, is_optional) = if name_part.ends_with('?') {
                (name_part.trim_end_matches('?').trim(), true)
            } else {
                (name_part, false)
            };

            if field_name.is_empty() {
                continue;
            }

            let field_type = parse_typescript_type(type_part)?;
            let mut field = Field::new(field_name.to_string(), field_type);
            field.nullable = is_optional;

            schema.add_field(field);
        }
    }

    Ok(schema)
}

/// Parse TypeScript type into AuDB Type
fn parse_typescript_type(type_str: &str) -> Result<Type> {
    let type_str = type_str.trim();

    match type_str {
        "string" => Ok(Type::String),
        "number" => Ok(Type::Float),
        "boolean" => Ok(Type::Boolean),
        "Date" => Ok(Type::Timestamp),
        "any" | "unknown" => Ok(Type::JsonValue),
        _ => {
            // Check for array types
            if type_str.ends_with("[]") {
                let element_type = type_str.trim_end_matches("[]").trim();
                let inner_type = parse_typescript_type(element_type)?;
                return Ok(Type::Vec(Box::new(inner_type)));
            }

            // Check for Array<T> syntax
            if type_str.starts_with("Array<") && type_str.ends_with('>') {
                let element_type = &type_str[6..type_str.len() - 1];
                let inner_type = parse_typescript_type(element_type)?;
                return Ok(Type::Vec(Box::new(inner_type)));
            }

            // Check for union types (simplified - just take first type)
            if type_str.contains('|') {
                let first_type = type_str.split('|').next().unwrap().trim();
                return parse_typescript_type(first_type);
            }

            // Otherwise treat as custom type
            Ok(Type::Custom(type_str.to_string()))
        }
    }
}

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

    #[test]
    fn test_parse_json_schema_simple() {
        let json = r#"{
            "type": "object",
            "properties": {
                "id": {"type": "string"},
                "name": {"type": "string"},
                "age": {"type": "integer"}
            },
            "required": ["id", "name"]
        }"#;

        let schema = parse_json_schema("User", json).unwrap();
        assert_eq!(schema.name, "User");
        assert_eq!(schema.fields.len(), 3);
        assert_eq!(schema.format, SchemaFormat::JsonSchema);

        let id_field = schema.get_field("id").unwrap();
        assert!(!id_field.nullable);

        let age_field = schema.get_field("age").unwrap();
        assert!(age_field.nullable); // Not in required list
    }

    #[test]
    fn test_parse_json_schema_types() {
        let json = r#"{
            "type": "object",
            "properties": {
                "str": {"type": "string"},
                "num": {"type": "integer"},
                "float": {"type": "number"},
                "bool": {"type": "boolean"},
                "arr": {"type": "array", "items": {"type": "string"}}
            }
        }"#;

        let schema = parse_json_schema("Types", json).unwrap();
        assert_eq!(schema.fields.len(), 5);

        assert!(matches!(
            schema.get_field("str").unwrap().field_type,
            Type::String
        ));
        assert!(matches!(
            schema.get_field("num").unwrap().field_type,
            Type::Integer
        ));
        assert!(matches!(
            schema.get_field("float").unwrap().field_type,
            Type::Float
        ));
        assert!(matches!(
            schema.get_field("bool").unwrap().field_type,
            Type::Boolean
        ));
    }

    #[test]
    fn test_parse_json_schema_enum() {
        let json = r#"{
            "type": "object",
            "properties": {
                "status": {
                    "type": "string",
                    "enum": ["active", "inactive", "pending"]
                }
            }
        }"#;

        let schema = parse_json_schema("Model", json).unwrap();
        let status_field = schema.get_field("status").unwrap();

        if let Type::Enum(variants) = &status_field.field_type {
            assert_eq!(variants.len(), 3);
            assert!(variants.contains(&"active".to_string()));
        } else {
            panic!("Expected Enum type");
        }
    }

    #[test]
    fn test_parse_typescript_simple() {
        let ts = r#"
        interface User {
            id: string;
            name: string;
            age: number;
        }
        "#;

        let schema = parse_typescript("User", ts).unwrap();
        assert_eq!(schema.name, "User");
        assert_eq!(schema.fields.len(), 3);
        assert_eq!(schema.format, SchemaFormat::TypeScript);
    }

    #[test]
    fn test_parse_typescript_optional() {
        let ts = r#"
        interface User {
            id: string;
            email?: string;
        }
        "#;

        let schema = parse_typescript("User", ts).unwrap();
        let id_field = schema.get_field("id").unwrap();
        let email_field = schema.get_field("email").unwrap();

        assert!(!id_field.nullable);
        assert!(email_field.nullable);
    }

    #[test]
    fn test_parse_typescript_types() {
        let ts = r#"
        interface Types {
            str: string;
            num: number;
            bool: boolean;
            date: Date;
            arr: string[];
            arr2: Array<number>;
        }
        "#;

        let schema = parse_typescript("Types", ts).unwrap();
        assert_eq!(schema.fields.len(), 6);

        assert!(matches!(
            schema.get_field("str").unwrap().field_type,
            Type::String
        ));
        assert!(matches!(
            schema.get_field("num").unwrap().field_type,
            Type::Float
        ));
        assert!(matches!(
            schema.get_field("bool").unwrap().field_type,
            Type::Boolean
        ));
        assert!(matches!(
            schema.get_field("date").unwrap().field_type,
            Type::Timestamp
        ));

        // Check array types
        if let Type::Vec(inner) = &schema.get_field("arr").unwrap().field_type {
            assert!(matches!(**inner, Type::String));
        } else {
            panic!("Expected Vec type");
        }
    }

    #[test]
    fn test_parse_typescript_custom_type() {
        let ts = r#"
        interface Post {
            id: string;
            author: User;
        }
        "#;

        let schema = parse_typescript("Post", ts).unwrap();
        let author_field = schema.get_field("author").unwrap();

        if let Type::Custom(name) = &author_field.field_type {
            assert_eq!(name, "User");
        } else {
            panic!("Expected Custom type");
        }
    }

    #[test]
    fn test_parse_json_schema_invalid() {
        let json = r#"{"invalid": "json"}"#;
        let result = parse_json_schema("Test", json);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_typescript_no_interface() {
        let ts = "const x = 5;";
        let result = parse_typescript("Test", ts);
        assert!(result.is_err());
    }
}