cqlite-core 0.11.0

Core engine for CQLite — read Apache Cassandra 5.0 SSTables locally without a cluster
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
//! Parser configuration and settings
//!
//! This module defines configuration options for the parser subsystem,
//! allowing fine-tuning of parser behavior and backend selection.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

/// Parser configuration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParserConfig {
    /// Backend to use for parsing
    pub backend: ParserBackend,

    /// Timeout for parsing operations
    pub timeout: Duration,

    /// Maximum depth for nested expressions
    pub max_expression_depth: u32,

    /// Maximum number of items in collections
    pub max_collection_size: u32,

    /// Maximum length for string literals
    pub max_string_length: u32,

    /// Maximum number of parameters in a statement
    pub max_parameters: u32,

    /// Whether to enable strict validation
    pub strict_validation: bool,

    /// Whether to allow experimental features
    pub allow_experimental: bool,

    /// Backend-specific options
    pub backend_options: HashMap<String, serde_json::Value>,

    /// Features to enable
    pub features: Vec<ParserFeature>,

    /// Memory limits
    pub memory_limits: MemoryLimits,

    /// Performance settings
    pub performance: PerformanceSettings,

    /// Error handling settings
    pub error_handling: ErrorHandlingSettings,

    /// Memory settings
    pub memory_settings: MemorySettings,

    /// Security settings
    pub security_settings: SecuritySettings,
}

/// Parser backend selection
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ParserBackend {
    /// Use nom parser (fast, streaming)
    Nom,

    /// Use ANTLR parser (full-featured, better error recovery)
    Antlr,

    /// Auto-select best backend based on input characteristics
    Auto,

    /// Custom backend (for extensions)
    Custom(String),
}

/// Parser features that can be enabled/disabled
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ParserFeature {
    /// Support for streaming/incremental parsing
    Streaming,

    /// Enhanced error recovery
    ErrorRecovery,

    /// Syntax highlighting support
    SyntaxHighlighting,

    /// Code completion support
    CodeCompletion,

    /// AST transformation support
    AstTransformation,

    /// Custom operator support
    CustomOperators,

    /// Parallel parsing support
    Parallel,

    /// Caching of parse results
    Caching,

    /// Validation during parsing
    OnlineValidation,

    /// Performance profiling
    Profiling,
}

/// Memory limit settings
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MemoryLimits {
    /// Maximum memory usage for AST construction (bytes)
    pub max_ast_size: u64,

    /// Maximum memory usage for temporary parsing data (bytes)
    pub max_temp_memory: u64,

    /// Maximum call stack depth
    pub max_stack_depth: u32,

    /// Maximum number of cached parse results
    pub max_cache_entries: u32,
}

/// Performance-related settings
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PerformanceSettings {
    /// Number of worker threads for parallel parsing
    pub worker_threads: u32,

    /// Buffer size for streaming parsing (bytes)
    pub stream_buffer_size: u32,

    /// Whether to enable parse result caching
    pub enable_caching: bool,

    /// Cache TTL for parse results
    pub cache_ttl: Duration,

    /// Whether to enable JIT compilation (if supported)
    pub enable_jit: bool,

    /// Optimization level (0-3)
    pub optimization_level: u8,
}

/// Error handling settings
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ErrorHandlingSettings {
    /// Maximum number of errors to collect before stopping
    pub max_errors: u32,

    /// Whether to continue parsing after recoverable errors
    pub continue_on_error: bool,

    /// Number of context lines to include in error messages
    pub error_context_lines: u32,

    /// Whether to include suggestions in error messages
    pub include_suggestions: bool,

    /// Whether to collect detailed error statistics
    pub collect_error_stats: bool,
}

/// Memory-specific settings for parser
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MemorySettings {
    /// Maximum memory usage for parser operations (bytes)
    pub max_parser_memory: u64,

    /// Memory allocation strategy
    pub allocation_strategy: MemoryAllocationStrategy,

    /// Whether to enable memory pooling
    pub enable_memory_pooling: bool,

    /// Pool size for memory allocations
    pub memory_pool_size: usize,
}

/// Memory allocation strategies
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MemoryAllocationStrategy {
    /// Standard allocation
    Standard,
    /// Pool-based allocation
    Pooled,
    /// Arena-based allocation
    Arena,
}

/// Security settings for parser
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SecuritySettings {
    /// Maximum query depth to prevent stack overflow
    pub max_query_depth: u32,

    /// Maximum number of tokens in a query
    pub max_token_count: u32,

    /// Whether to enable input sanitization
    pub enable_input_sanitization: bool,

    /// Whether to restrict dangerous operations
    pub restrict_dangerous_operations: bool,

    /// List of blocked keywords
    pub blocked_keywords: Vec<String>,
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            backend: ParserBackend::Auto,
            timeout: Duration::from_secs(30),
            max_expression_depth: 100,
            max_collection_size: 10_000,
            max_string_length: 1_000_000,
            max_parameters: 1000,
            strict_validation: true,
            allow_experimental: false,
            backend_options: HashMap::new(),
            features: vec![
                ParserFeature::ErrorRecovery,
                ParserFeature::OnlineValidation,
            ],
            memory_limits: MemoryLimits::default(),
            performance: PerformanceSettings::default(),
            error_handling: ErrorHandlingSettings::default(),
            memory_settings: MemorySettings::default(),
            security_settings: SecuritySettings::default(),
        }
    }
}

impl Default for MemoryLimits {
    fn default() -> Self {
        Self {
            max_ast_size: 100 * 1024 * 1024,   // 100 MB
            max_temp_memory: 50 * 1024 * 1024, // 50 MB
            max_stack_depth: 1000,
            max_cache_entries: 10_000,
        }
    }
}

impl Default for PerformanceSettings {
    fn default() -> Self {
        Self {
            worker_threads: num_cpus::get() as u32,
            stream_buffer_size: 64 * 1024, // 64 KB
            enable_caching: true,
            cache_ttl: Duration::from_secs(300), // 5 minutes
            enable_jit: false,
            optimization_level: 2,
        }
    }
}

impl Default for ErrorHandlingSettings {
    fn default() -> Self {
        Self {
            max_errors: 100,
            continue_on_error: true,
            error_context_lines: 3,
            include_suggestions: true,
            collect_error_stats: false,
        }
    }
}

impl Default for MemorySettings {
    fn default() -> Self {
        Self {
            max_parser_memory: 50 * 1024 * 1024, // 50 MB
            allocation_strategy: MemoryAllocationStrategy::Standard,
            enable_memory_pooling: false,
            memory_pool_size: 1024,
        }
    }
}

impl Default for SecuritySettings {
    fn default() -> Self {
        Self {
            max_query_depth: 100,
            max_token_count: 10_000,
            enable_input_sanitization: true,
            restrict_dangerous_operations: true,
            blocked_keywords: vec![],
        }
    }
}

impl ParserConfig {
    /// Create a new configuration with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a fast configuration optimized for performance
    ///
    /// Parallel parsing requires >=2 worker threads, so the thread count is
    /// set to `max(num_cpus, 2)` to stay valid even on single-core CI runners.
    pub fn fast() -> Self {
        Self {
            backend: ParserBackend::Nom,
            timeout: Duration::from_secs(10),
            strict_validation: false,
            features: vec![
                ParserFeature::Parallel,
                ParserFeature::Caching,
                ParserFeature::Streaming,
            ],
            performance: PerformanceSettings {
                optimization_level: 3,
                enable_jit: true,
                worker_threads: (num_cpus::get() as u32).max(2),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Create a strict configuration with maximum validation
    pub fn strict() -> Self {
        Self {
            backend: ParserBackend::Antlr,
            strict_validation: true,
            allow_experimental: false,
            features: vec![
                ParserFeature::ErrorRecovery,
                ParserFeature::OnlineValidation,
                ParserFeature::Profiling,
                ParserFeature::SyntaxHighlighting,
            ],
            error_handling: ErrorHandlingSettings {
                max_errors: 1,
                continue_on_error: false,
                include_suggestions: true,
                collect_error_stats: true,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Create a development configuration with debugging features
    pub fn development() -> Self {
        Self {
            backend: ParserBackend::Auto,
            allow_experimental: true,
            features: vec![
                ParserFeature::ErrorRecovery,
                ParserFeature::SyntaxHighlighting,
                ParserFeature::CodeCompletion,
                ParserFeature::AstTransformation,
                ParserFeature::OnlineValidation,
                ParserFeature::Profiling,
            ],
            error_handling: ErrorHandlingSettings {
                continue_on_error: true,
                include_suggestions: true,
                collect_error_stats: true,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Create a minimal configuration for embedded use
    pub fn minimal() -> Self {
        Self {
            backend: ParserBackend::Nom,
            timeout: Duration::from_secs(5),
            max_expression_depth: 50,
            max_collection_size: 1000,
            max_string_length: 10_000,
            max_parameters: 100,
            strict_validation: false,
            features: vec![],
            memory_limits: MemoryLimits {
                max_ast_size: 10 * 1024 * 1024,   // 10 MB
                max_temp_memory: 5 * 1024 * 1024, // 5 MB
                max_stack_depth: 100,
                max_cache_entries: 100,
            },
            performance: PerformanceSettings {
                worker_threads: 1,
                enable_caching: false,
                optimization_level: 1,
                ..Default::default()
            },
            error_handling: ErrorHandlingSettings {
                max_errors: 10,
                error_context_lines: 1,
                include_suggestions: false,
                collect_error_stats: false,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Set the parser backend
    pub fn with_backend(mut self, backend: ParserBackend) -> Self {
        self.backend = backend;
        self
    }

    /// Set the timeout
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Enable strict validation
    pub fn with_strict_validation(mut self, strict: bool) -> Self {
        self.strict_validation = strict;
        self
    }

    /// Add a feature (no-op if already present)
    pub fn with_feature(mut self, feature: ParserFeature) -> Self {
        if !self.features.contains(&feature) {
            self.features.push(feature);
        }
        self
    }

    /// Check if a feature is enabled
    pub fn has_feature(&self, feature: &ParserFeature) -> bool {
        self.features.contains(feature)
    }

    /// Validate the configuration
    pub fn validate(&self) -> Result<(), String> {
        if self.timeout.as_secs() == 0 {
            return Err("Timeout must be greater than 0".to_string());
        }
        if self.max_expression_depth == 0 {
            return Err("Max expression depth must be greater than 0".to_string());
        }
        if self.max_collection_size == 0 {
            return Err("Max collection size must be greater than 0".to_string());
        }
        if self.memory_limits.max_ast_size == 0 {
            return Err("Max AST size must be greater than 0".to_string());
        }
        if self.memory_limits.max_stack_depth == 0 {
            return Err("Max stack depth must be greater than 0".to_string());
        }
        if self.performance.worker_threads == 0 {
            return Err("Worker threads must be greater than 0".to_string());
        }
        if self.performance.stream_buffer_size < 1024 {
            return Err("Stream buffer size should be at least 1KB for efficiency".to_string());
        }
        if self.performance.optimization_level > 3 {
            return Err("Optimization level must be 0-3".to_string());
        }
        if self.error_handling.max_errors == 0 {
            return Err("Max errors must be greater than 0".to_string());
        }

        if self.has_feature(&ParserFeature::Parallel) && self.performance.worker_threads == 1 {
            return Err("Parallel parsing requires at least 2 worker threads. Use ParserConfig::fast() for automatic thread count adjustment.".to_string());
        }
        if self.has_feature(&ParserFeature::Streaming)
            && matches!(self.backend, ParserBackend::Antlr)
        {
            return Err("Streaming is not supported with ANTLR backend".to_string());
        }

        Ok(())
    }
}

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

    #[test]
    fn test_default_config() {
        let config = ParserConfig::default();
        assert!(matches!(config.backend, ParserBackend::Auto));
        assert!(config.strict_validation);
        assert!(!config.allow_experimental);
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_preset_configs() {
        let fast = ParserConfig::fast();
        assert!(matches!(fast.backend, ParserBackend::Nom));
        assert!(!fast.strict_validation);
        assert!(fast.validate().is_ok());

        let strict = ParserConfig::strict();
        assert!(matches!(strict.backend, ParserBackend::Antlr));
        assert!(strict.strict_validation);
        assert!(strict.validate().is_ok());

        let minimal = ParserConfig::minimal();
        assert_eq!(minimal.memory_limits.max_ast_size, 10 * 1024 * 1024);
        assert!(minimal.validate().is_ok());
    }

    #[test]
    fn test_config_validation() {
        let mut config = ParserConfig::default();
        assert!(config.validate().is_ok());

        config.timeout = Duration::from_secs(0);
        assert!(config.validate().is_err());

        config = ParserConfig::default();
        config.performance.optimization_level = 5;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_feature_management() {
        let mut config = ParserConfig::default();
        assert!(!config.has_feature(&ParserFeature::Streaming));

        config = config.with_feature(ParserFeature::Streaming);
        assert!(config.has_feature(&ParserFeature::Streaming));
    }

    #[test]
    fn test_parallel_requires_multiple_workers() {
        let mut config = ParserConfig::minimal().with_feature(ParserFeature::Parallel);
        config.performance.worker_threads = 1;
        let err = config
            .validate()
            .expect_err("parallel parsing should require >1 worker");
        assert!(err.contains("Parallel parsing requires at least 2 worker threads"));
    }

    #[test]
    fn test_streaming_not_allowed_with_antlr() {
        let config = ParserConfig::strict().with_feature(ParserFeature::Streaming);
        let err = config
            .validate()
            .expect_err("streaming should be incompatible with ANTLR backend");
        assert!(err.contains("Streaming is not supported with ANTLR backend"));
    }
}