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
//! Parser factory for creating parser instances
//!
//! This module provides factory functions for creating parser instances
//! with different backends and configurations.

use crate::error::{Error, Result};
use std::sync::{Arc, Mutex, OnceLock};

use super::{
    antlr_backend::AntlrParser,
    config::{ParserBackend, ParserConfig},
    nom_backend::NomParser,
    traits::{CqlParser, CqlParserFactory, FactoryInfo, ParserBackendInfo},
};

/// Main parser factory
#[derive(Debug, Default)]
pub struct ParserFactory;

impl ParserFactory {
    /// Create a parser with the default configuration.
    pub fn create_default() -> Result<Arc<dyn CqlParser + Send + Sync>> {
        Self::create(ParserConfig::default())
    }

    /// Create a parser with the specified configuration.
    pub fn create(mut config: ParserConfig) -> Result<Arc<dyn CqlParser + Send + Sync>> {
        config.validate().map_err(Error::configuration)?;

        if matches!(config.backend, ParserBackend::Auto) {
            config.backend = Self::select_optimal_backend(&config);
        }

        match config.backend.clone() {
            ParserBackend::Nom => Ok(Arc::new(NomParser::new(config)?)),
            ParserBackend::Antlr => Ok(Arc::new(AntlrParser::new(config)?)),
            ParserBackend::Auto => unreachable!("Auto resolved above"),
            ParserBackend::Custom(name) => Err(Error::configuration(format!(
                "Custom parser '{}' not available",
                name
            ))),
        }
    }

    /// Select the best backend given the feature set in `config`.
    ///
    /// ANTLR is preferred when features require rich diagnostics or
    /// tooling support; otherwise nom is used.
    fn select_optimal_backend(config: &ParserConfig) -> ParserBackend {
        use super::config::ParserFeature;

        let needs_antlr = config.has_feature(&ParserFeature::ErrorRecovery)
            || config.has_feature(&ParserFeature::SyntaxHighlighting)
            || config.has_feature(&ParserFeature::CodeCompletion)
            || config.strict_validation;

        if needs_antlr {
            ParserBackend::Antlr
        } else {
            ParserBackend::Nom
        }
    }

    /// Get information about available backends.
    pub fn get_available_backends() -> Vec<ParserBackendInfo> {
        vec![NomParser::backend_info(), AntlrParser::backend_info()]
    }

    /// Check whether the given backend can be instantiated.
    pub fn is_backend_available(backend: &ParserBackend) -> bool {
        match backend {
            ParserBackend::Nom | ParserBackend::Antlr | ParserBackend::Auto => true,
            ParserBackend::Custom(_) => false,
        }
    }

    /// Recommend a backend for a high-level use case.
    pub fn recommend_backend(use_case: UseCase) -> ParserBackend {
        match use_case {
            UseCase::HighPerformance | UseCase::Embedded | UseCase::Batch => ParserBackend::Nom,
            UseCase::Development | UseCase::Interactive => ParserBackend::Antlr,
            UseCase::Production => ParserBackend::Auto,
        }
    }

    /// Create a parser optimized for a specific use case.
    pub fn create_for_use_case(use_case: UseCase) -> Result<Arc<dyn CqlParser + Send + Sync>> {
        let backend = Self::recommend_backend(use_case.clone());
        Self::create(Self::create_config_for_use_case(use_case, backend))
    }

    fn create_config_for_use_case(use_case: UseCase, backend: ParserBackend) -> ParserConfig {
        use super::config::ParserFeature;
        use std::time::Duration;

        match use_case {
            UseCase::HighPerformance => ParserConfig::fast().with_backend(backend),
            UseCase::Development => ParserConfig::development().with_backend(backend),
            UseCase::Production => ParserConfig::default().with_backend(backend),
            UseCase::Embedded => ParserConfig::minimal().with_backend(backend),
            UseCase::Interactive => ParserConfig::development()
                .with_backend(backend)
                .with_feature(ParserFeature::CodeCompletion)
                .with_feature(ParserFeature::SyntaxHighlighting)
                .with_timeout(Duration::from_millis(100)),
            UseCase::Batch => ParserConfig::fast()
                .with_backend(backend)
                .with_feature(ParserFeature::Parallel)
                .with_timeout(Duration::from_secs(300)),
        }
    }
}

impl CqlParserFactory for ParserFactory {
    fn create_parser(&self) -> Result<Box<dyn CqlParser>> {
        self.create_parser_with_config(ParserConfig::default())
    }

    fn create_parser_with_config(&self, config: ParserConfig) -> Result<Box<dyn CqlParser>> {
        Ok(Box::new(ParserWrapper {
            inner: Self::create(config)?,
        }))
    }

    fn factory_info(&self) -> FactoryInfo {
        FactoryInfo {
            name: "DefaultParserFactory".to_string(),
            supported_backends: vec!["nom".to_string(), "antlr".to_string()],
            default_backend: "auto".to_string(),
        }
    }
}

/// Adapter turning the shared `Arc<dyn CqlParser + Send + Sync>` returned by
/// [`ParserFactory::create`] into the `Box<dyn CqlParser>` required by
/// [`CqlParserFactory`].
#[derive(Debug)]
struct ParserWrapper {
    inner: Arc<dyn CqlParser + Send + Sync>,
}

#[async_trait::async_trait]
impl CqlParser for ParserWrapper {
    async fn parse(&self, input: &str) -> Result<super::ast::CqlStatement> {
        self.inner.parse(input).await
    }

    async fn parse_type(&self, input: &str) -> Result<super::ast::CqlDataType> {
        self.inner.parse_type(input).await
    }

    async fn parse_expression(&self, input: &str) -> Result<super::ast::CqlExpression> {
        self.inner.parse_expression(input).await
    }

    async fn parse_identifier(&self, input: &str) -> Result<super::ast::CqlIdentifier> {
        self.inner.parse_identifier(input).await
    }

    async fn parse_literal(&self, input: &str) -> Result<super::ast::CqlLiteral> {
        self.inner.parse_literal(input).await
    }

    async fn parse_column_definitions(&self, input: &str) -> Result<Vec<super::ast::CqlColumnDef>> {
        self.inner.parse_column_definitions(input).await
    }

    async fn parse_table_options(&self, input: &str) -> Result<super::ast::CqlTableOptions> {
        self.inner.parse_table_options(input).await
    }

    fn validate_syntax(&self, input: &str) -> bool {
        self.inner.validate_syntax(input)
    }

    fn backend_info(&self) -> super::traits::ParserBackendInfo {
        self.inner.backend_info()
    }
}

/// Use case categories for parser optimization.
#[derive(Debug, Clone, PartialEq)]
pub enum UseCase {
    /// High-performance parsing with minimal overhead.
    HighPerformance,
    /// Development environment with rich error messages and debugging.
    Development,
    /// Production environment with balanced performance and reliability.
    Production,
    /// Embedded systems with strict resource constraints.
    Embedded,
    /// Interactive environments requiring fast response times.
    Interactive,
    /// Batch processing with large volumes of queries.
    Batch,
}

/// Registry for custom parser backends.
#[derive(Debug, Default)]
pub struct ParserRegistry {
    custom_factories: std::collections::HashMap<String, Box<dyn CqlParserFactory + Send + Sync>>,
}

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

    pub fn register_factory(
        &mut self,
        name: String,
        factory: Box<dyn CqlParserFactory + Send + Sync>,
    ) {
        self.custom_factories.insert(name, factory);
    }

    pub fn get_factory(&self, name: &str) -> Option<&(dyn CqlParserFactory + Send + Sync)> {
        self.custom_factories.get(name).map(|f| f.as_ref())
    }

    pub fn list_factories(&self) -> Vec<&str> {
        self.custom_factories.keys().map(|s| s.as_str()).collect()
    }

    /// Create a parser using a registered factory.
    pub fn create_with_factory(
        &self,
        factory_name: &str,
        config: ParserConfig,
    ) -> Result<Box<dyn CqlParser>> {
        self.get_factory(factory_name)
            .ok_or_else(|| Error::configuration(format!("Factory '{}' not found", factory_name)))?
            .create_parser_with_config(config)
    }
}

static GLOBAL_REGISTRY: OnceLock<Mutex<ParserRegistry>> = OnceLock::new();

/// Register a factory in the process-wide registry.
pub fn register_global_factory(name: String, factory: Box<dyn CqlParserFactory + Send + Sync>) {
    let registry = GLOBAL_REGISTRY.get_or_init(|| Mutex::new(ParserRegistry::new()));
    let mut guard = registry.lock().unwrap_or_else(|e| e.into_inner());
    guard.register_factory(name, factory);
}

/// Benchmark helpers for comparing parser backends.
pub mod benchmarks {
    use super::*;
    use std::time::{Duration, Instant};

    #[derive(Debug, Clone)]
    pub struct BenchmarkResult {
        pub backend: String,
        pub avg_parse_time: Duration,
        pub min_parse_time: Duration,
        pub max_parse_time: Duration,
        pub success_rate: f64,
        pub errors: Vec<String>,
    }

    impl BenchmarkResult {
        fn failed(backend: &ParserBackend, error: String) -> Self {
            Self {
                backend: format!("{:?}", backend),
                avg_parse_time: Duration::ZERO,
                min_parse_time: Duration::ZERO,
                max_parse_time: Duration::ZERO,
                success_rate: 0.0,
                errors: vec![error],
            }
        }
    }

    #[derive(Debug, Clone)]
    pub struct BenchmarkConfig {
        pub iterations: u32,
        pub timeout: Duration,
        pub test_cases: Vec<String>,
    }

    impl Default for BenchmarkConfig {
        fn default() -> Self {
            Self {
                iterations: 100,
                timeout: Duration::from_secs(1),
                test_cases: vec![
                    "SELECT * FROM users".to_string(),
                    "INSERT INTO users (id, name) VALUES (?, ?)".to_string(),
                    "UPDATE users SET name = ? WHERE id = ?".to_string(),
                    "DELETE FROM users WHERE id = ?".to_string(),
                    "CREATE TABLE test (id UUID PRIMARY KEY, data TEXT)".to_string(),
                ],
            }
        }
    }

    /// Run benchmarks on all available parser backends.
    pub async fn benchmark_parsers(config: BenchmarkConfig) -> Vec<BenchmarkResult> {
        let mut results = Vec::new();
        for backend in [ParserBackend::Nom, ParserBackend::Antlr] {
            if ParserFactory::is_backend_available(&backend) {
                results.push(benchmark_backend(backend, &config).await);
            }
        }
        results
    }

    async fn benchmark_backend(
        backend: ParserBackend,
        config: &BenchmarkConfig,
    ) -> BenchmarkResult {
        let parser_config = ParserConfig::default().with_backend(backend.clone());
        let parser = match ParserFactory::create(parser_config) {
            Ok(p) => p,
            Err(e) => {
                return BenchmarkResult::failed(&backend, format!("Failed to create parser: {}", e))
            }
        };

        let mut times = Vec::new();
        let mut errors = Vec::new();
        let mut successes: u32 = 0;

        for _ in 0..config.iterations {
            for test_case in &config.test_cases {
                let start = Instant::now();
                match tokio::time::timeout(config.timeout, parser.parse(test_case)).await {
                    Ok(Ok(_)) => {
                        successes += 1;
                        times.push(start.elapsed());
                    }
                    Ok(Err(e)) => errors.push(format!("Parse error: {}", e)),
                    Err(_) => errors.push("Timeout".to_string()),
                }
            }
        }

        let total_attempts = config.iterations * config.test_cases.len() as u32;
        let success_rate = f64::from(successes) / f64::from(total_attempts);
        let avg_parse_time = if times.is_empty() {
            Duration::ZERO
        } else {
            times.iter().sum::<Duration>() / times.len() as u32
        };

        BenchmarkResult {
            backend: format!("{:?}", backend),
            avg_parse_time,
            min_parse_time: times.iter().min().copied().unwrap_or_default(),
            max_parse_time: times.iter().max().copied().unwrap_or_default(),
            success_rate,
            errors,
        }
    }
}

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

    #[test]
    fn test_factory_creation() {
        let factory = ParserFactory;
        let info = factory.factory_info();
        assert_eq!(info.name, "DefaultParserFactory");
        assert!(!info.supported_backends.is_empty());
    }

    #[test]
    fn test_backend_availability() {
        assert!(ParserFactory::is_backend_available(&ParserBackend::Nom));
        assert!(ParserFactory::is_backend_available(&ParserBackend::Auto));
        assert!(!ParserFactory::is_backend_available(
            &ParserBackend::Custom("unknown".to_string())
        ));
    }

    #[test]
    fn test_backend_recommendation() {
        assert_eq!(
            ParserFactory::recommend_backend(UseCase::HighPerformance),
            ParserBackend::Nom
        );
        assert_eq!(
            ParserFactory::recommend_backend(UseCase::Development),
            ParserBackend::Antlr
        );
    }

    #[test]
    fn test_auto_backend_selection() {
        let config = ParserConfig::fast();
        let backend = ParserFactory::select_optimal_backend(&config);
        assert_eq!(backend, ParserBackend::Nom);

        let config = ParserConfig::strict();
        let backend = ParserFactory::select_optimal_backend(&config);
        assert_eq!(backend, ParserBackend::Antlr);
    }

    #[test]
    fn test_parser_registry() {
        let registry = ParserRegistry::new();
        assert!(registry.list_factories().is_empty());
    }
}