prax-schema 0.6.5

Schema parser and AST for the Prax ORM
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
//! Schema caching for improved performance.
//!
//! This module provides:
//! - Schema caching to avoid re-parsing
//! - String interning for documentation strings
//! - Lazy computed fields
//!
//! # Examples
//!
//! ```rust
//! use prax_schema::cache::{SchemaCache, DocString};
//!
//! // Cache parsed schemas
//! let mut cache = SchemaCache::new();
//!
//! let schema = cache.get_or_parse("model User { id Int @id }").unwrap();
//! let schema2 = cache.get_or_parse("model User { id Int @id }").unwrap();
//! // schema2 is the same Arc as schema (cached)
//!
//! // Intern documentation strings
//! let doc1 = DocString::intern("User profile information");
//! let doc2 = DocString::intern("User profile information");
//! // doc1 and doc2 share the same allocation
//! ```

use parking_lot::RwLock;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use crate::ast::Schema;
use crate::error::SchemaResult;
use crate::parser::parse_schema;

// ============================================================================
// Schema Cache
// ============================================================================

/// A cache for parsed schemas.
///
/// Caches parsed schemas by their source text hash to avoid re-parsing
/// identical schemas.
#[derive(Debug, Default)]
pub struct SchemaCache {
    cache: RwLock<HashMap<u64, Arc<Schema>>>,
    stats: RwLock<CacheStats>,
}

/// Statistics for the schema cache.
#[derive(Debug, Clone, Default)]
pub struct CacheStats {
    /// Number of cache hits.
    pub hits: u64,
    /// Number of cache misses.
    pub misses: u64,
    /// Number of schemas currently cached.
    pub cached_count: usize,
}

impl CacheStats {
    /// Get the cache hit rate.
    pub fn hit_rate(&self) -> f64 {
        let total = self.hits + self.misses;
        if total == 0 {
            0.0
        } else {
            self.hits as f64 / total as f64
        }
    }
}

impl SchemaCache {
    /// Create a new empty schema cache.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a cache with pre-allocated capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            cache: RwLock::new(HashMap::with_capacity(capacity)),
            stats: RwLock::default(),
        }
    }

    /// Get a cached schema or parse and cache a new one.
    ///
    /// Returns an `Arc<Schema>` which can be cloned cheaply.
    pub fn get_or_parse(&self, source: &str) -> SchemaResult<Arc<Schema>> {
        let hash = hash_source(source);

        // Try to get from cache first
        {
            let cache = self.cache.read();
            if let Some(schema) = cache.get(&hash) {
                self.stats.write().hits += 1;
                return Ok(Arc::clone(schema));
            }
        }

        // Parse and cache
        let schema = parse_schema(source)?;
        let schema = Arc::new(schema);

        {
            let mut cache = self.cache.write();
            cache.insert(hash, Arc::clone(&schema));
        }

        {
            let mut stats = self.stats.write();
            stats.misses += 1;
            stats.cached_count = self.cache.read().len();
        }

        Ok(schema)
    }

    /// Check if a schema is cached.
    pub fn contains(&self, source: &str) -> bool {
        let hash = hash_source(source);
        self.cache.read().contains_key(&hash)
    }

    /// Clear the cache.
    pub fn clear(&self) {
        self.cache.write().clear();
        self.stats.write().cached_count = 0;
    }

    /// Get cache statistics.
    pub fn stats(&self) -> CacheStats {
        let mut stats = self.stats.read().clone();
        stats.cached_count = self.cache.read().len();
        stats
    }

    /// Get the number of cached schemas.
    pub fn len(&self) -> usize {
        self.cache.read().len()
    }

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

    /// Remove a specific schema from the cache.
    pub fn remove(&self, source: &str) -> bool {
        let hash = hash_source(source);
        self.cache.write().remove(&hash).is_some()
    }
}

/// Hash a source string for caching.
fn hash_source(source: &str) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    let mut hasher = DefaultHasher::new();
    source.hash(&mut hasher);
    hasher.finish()
}

// ============================================================================
// Documentation String Interning
// ============================================================================

/// An interned documentation string.
///
/// Uses `Arc<str>` for efficient sharing of identical documentation strings.
/// Documentation comments are often duplicated across models (e.g., "id" field docs).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DocString(Arc<str>);

impl DocString {
    /// Create a new documentation string (not interned).
    pub fn new(s: impl AsRef<str>) -> Self {
        Self(Arc::from(s.as_ref()))
    }

    /// Intern a documentation string.
    ///
    /// Returns a shared reference to the string if it's already interned,
    /// or interns and returns a new reference.
    pub fn intern(s: impl AsRef<str>) -> Self {
        DOC_INTERNER.intern(s.as_ref())
    }

    /// Get the string as a slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Get the underlying Arc.
    pub fn as_arc(&self) -> &Arc<str> {
        &self.0
    }
}

impl AsRef<str> for DocString {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for DocString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<&str> for DocString {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

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

/// Global documentation string interner.
static DOC_INTERNER: std::sync::LazyLock<DocInterner> = std::sync::LazyLock::new(DocInterner::new);

/// Interner for documentation strings.
#[derive(Debug, Default)]
struct DocInterner {
    strings: RwLock<HashMap<u64, Arc<str>>>,
}

impl DocInterner {
    fn new() -> Self {
        Self::default()
    }

    fn intern(&self, s: &str) -> DocString {
        let hash = hash_source(s);

        // Check if already interned
        {
            let strings = self.strings.read();
            if let Some(arc) = strings.get(&hash) {
                return DocString(Arc::clone(arc));
            }
        }

        // Intern the string
        let arc: Arc<str> = Arc::from(s);
        {
            let mut strings = self.strings.write();
            strings.insert(hash, Arc::clone(&arc));
        }

        DocString(arc)
    }
}

// ============================================================================
// Lazy Field Attributes
// ============================================================================

/// Lazily computed field attributes.
///
/// Caches expensive attribute extraction to avoid repeated computation.
#[derive(Debug, Clone, Default)]
pub struct LazyFieldAttrs {
    computed: std::sync::OnceLock<FieldAttrsCache>,
}

/// Cached field attribute values.
#[derive(Debug, Clone, Default)]
pub struct FieldAttrsCache {
    /// Is this an ID field?
    pub is_id: bool,
    /// Is this an auto-generated field?
    pub is_auto: bool,
    /// Is this a unique field?
    pub is_unique: bool,
    /// Is this an indexed field?
    pub is_indexed: bool,
    /// Is this an updated_at field?
    pub is_updated_at: bool,
    /// Default value expression (if any).
    pub default_value: Option<String>,
    /// Mapped column name (if different from field name).
    pub mapped_name: Option<String>,
}

impl LazyFieldAttrs {
    /// Create new lazy field attributes.
    pub const fn new() -> Self {
        Self {
            computed: std::sync::OnceLock::new(),
        }
    }

    /// Get or compute the cached attributes.
    pub fn get_or_init<F>(&self, f: F) -> &FieldAttrsCache
    where
        F: FnOnce() -> FieldAttrsCache,
    {
        self.computed.get_or_init(f)
    }

    /// Check if attributes have been computed.
    pub fn is_computed(&self) -> bool {
        self.computed.get().is_some()
    }

    /// Clear the cached attributes (creates a new instance).
    pub fn reset(&mut self) {
        *self = Self::new();
    }
}

// ============================================================================
// Optimized Validation Type Pool
// ============================================================================

/// Pool of commonly used validation types.
///
/// Pre-allocates common validation type combinations to avoid repeated
/// allocation during schema parsing.
#[derive(Debug, Default)]
pub struct ValidationTypePool {
    /// String validation (email, url, etc.)
    pub string_validators: HashMap<&'static str, Arc<ValidatorDef>>,
    /// Numeric validation (min, max, etc.)
    pub numeric_validators: HashMap<&'static str, Arc<ValidatorDef>>,
}

/// A cached validator definition.
#[derive(Debug, Clone)]
pub struct ValidatorDef {
    /// Validator name.
    pub name: &'static str,
    /// Validator type.
    pub validator_type: ValidatorType,
}

/// Type of validator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidatorType {
    /// String format validator (email, url, uuid, etc.)
    StringFormat,
    /// String length validator.
    StringLength,
    /// Numeric range validator.
    NumericRange,
    /// Regex pattern validator.
    Pattern,
    /// Custom validator.
    Custom,
}

impl ValidationTypePool {
    /// Create a new pool with common validators pre-allocated.
    pub fn new() -> Self {
        let mut pool = Self::default();
        pool.init_common_validators();
        pool
    }

    fn init_common_validators(&mut self) {
        // Common string format validators
        let string_formats = [
            "email", "url", "uuid", "cuid", "cuid2", "nanoid", "ulid", "ipv4", "ipv6", "date",
            "datetime", "time",
        ];

        for name in string_formats {
            self.string_validators.insert(
                name,
                Arc::new(ValidatorDef {
                    name,
                    validator_type: ValidatorType::StringFormat,
                }),
            );
        }

        // Common numeric validators
        let numeric_validators = [
            "min",
            "max",
            "positive",
            "negative",
            "nonNegative",
            "nonPositive",
        ];
        for name in numeric_validators {
            self.numeric_validators.insert(
                name,
                Arc::new(ValidatorDef {
                    name,
                    validator_type: ValidatorType::NumericRange,
                }),
            );
        }
    }

    /// Get a string format validator.
    pub fn get_string_validator(&self, name: &str) -> Option<&Arc<ValidatorDef>> {
        self.string_validators.get(name)
    }

    /// Get a numeric validator.
    pub fn get_numeric_validator(&self, name: &str) -> Option<&Arc<ValidatorDef>> {
        self.numeric_validators.get(name)
    }
}

/// Global validation type pool.
pub static VALIDATION_POOL: std::sync::LazyLock<ValidationTypePool> =
    std::sync::LazyLock::new(ValidationTypePool::new);

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

    #[test]
    fn test_schema_cache_hit() {
        let cache = SchemaCache::new();

        let schema1 = cache.get_or_parse("model User { id Int @id }").unwrap();
        let schema2 = cache.get_or_parse("model User { id Int @id }").unwrap();

        // Should be the same Arc
        assert!(Arc::ptr_eq(&schema1, &schema2));

        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);
    }

    #[test]
    fn test_schema_cache_miss() {
        let cache = SchemaCache::new();

        let _ = cache.get_or_parse("model User { id Int @id }").unwrap();
        let _ = cache.get_or_parse("model Post { id Int @id }").unwrap();

        let stats = cache.stats();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 2);
    }

    #[test]
    fn test_schema_cache_clear() {
        let cache = SchemaCache::new();

        let _ = cache.get_or_parse("model User { id Int @id }").unwrap();
        assert_eq!(cache.len(), 1);

        cache.clear();
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_doc_string_interning() {
        let doc1 = DocString::intern("User profile information");
        let doc2 = DocString::intern("User profile information");

        // Should share the same Arc
        assert!(Arc::ptr_eq(doc1.as_arc(), doc2.as_arc()));
    }

    #[test]
    fn test_doc_string_different() {
        let doc1 = DocString::intern("User profile");
        let doc2 = DocString::intern("Post content");

        assert_ne!(doc1.as_str(), doc2.as_str());
    }

    #[test]
    fn test_lazy_field_attrs() {
        let lazy = LazyFieldAttrs::new();

        assert!(!lazy.is_computed());

        let attrs = lazy.get_or_init(|| FieldAttrsCache {
            is_id: true,
            is_auto: true,
            ..Default::default()
        });

        assert!(lazy.is_computed());
        assert!(attrs.is_id);
        assert!(attrs.is_auto);
    }

    #[test]
    fn test_validation_pool() {
        let pool = ValidationTypePool::new();

        assert!(pool.get_string_validator("email").is_some());
        assert!(pool.get_string_validator("url").is_some());
        assert!(pool.get_numeric_validator("min").is_some());
        assert!(pool.get_numeric_validator("max").is_some());
    }

    #[test]
    fn test_cache_stats_hit_rate() {
        let stats = CacheStats {
            hits: 8,
            misses: 2,
            cached_count: 5,
        };

        assert!((stats.hit_rate() - 0.8).abs() < 0.001);
    }

    #[test]
    fn test_cache_stats_zero() {
        let stats = CacheStats::default();
        assert_eq!(stats.hit_rate(), 0.0);
    }
}