cqlite-core 0.15.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
//! Comprehensive Schema Discovery and Validation System
//!
//! This module provides advanced schema discovery capabilities that can extract, parse,
//! validate, and export schema information from SSTable files across different Cassandra versions.
//! It supports all complex data types including UDTs, collections, frozen types, and indexes.

mod analysis;
mod exporter;
mod inference;
mod model;
mod validator;

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use tokio::sync::RwLock;

use crate::{
    parser::header::{CassandraVersion, SSTableHeader},
    platform::Platform,
    schema::UdtRegistry,
    types::Value,
    Config, Result,
};

use self::exporter::SchemaExporter;
use self::inference::TypeInferenceEngine;
use self::validator::SchemaValidator;

// Re-export the public data model unchanged.
pub use self::model::{
    CachingOptions, CollectionKind, CollectionType, ColumnDefinition, CompactionStrategy,
    CompressionOptions, ConsistencyResults, DiscoveryMethod, DiscoveryMetrics, FieldConflict,
    IndexDefinition, IndexType, SchemaDiscoveryConfig, SchemaInfo, SchemaMetadata, TableOptions,
    TypeInconsistency, TypeInfo, UDTDefinition, UdtConflict, UdtFieldDefinition, UdtFieldInfo,
    ValidationError, ValidationErrorType, ValidationResults, ValidationStatus, ValidationWarning,
    ValidationWarningType,
};

/// Main schema discovery engine
#[derive(Debug)]
pub struct SchemaDiscoveryEngine {
    /// Configuration
    config: SchemaDiscoveryConfig,
    /// Platform abstraction
    #[allow(dead_code)]
    platform: Arc<Platform>,
    /// Core configuration
    #[allow(dead_code)]
    core_config: Config,
    /// Schema cache
    schema_cache: Arc<RwLock<HashMap<String, (SchemaInfo, SystemTime)>>>,
    /// UDT registry for managing discovered UDTs
    #[allow(dead_code)]
    udt_registry: Arc<RwLock<UdtRegistry>>,
    /// Type inference engine
    #[allow(dead_code)]
    type_inference: Arc<TypeInferenceEngine>,
    /// Schema validator
    #[allow(dead_code)]
    validator: Arc<SchemaValidator>,
    /// Schema exporter
    exporter: Arc<SchemaExporter>,
}

impl SchemaDiscoveryEngine {
    /// Create a new schema discovery engine
    pub async fn new(
        config: SchemaDiscoveryConfig,
        platform: Arc<Platform>,
        core_config: Config,
    ) -> Result<Self> {
        let udt_registry = Arc::new(RwLock::new(UdtRegistry::new()));
        let type_inference = Arc::new(TypeInferenceEngine::new());
        let validator = Arc::new(SchemaValidator::new());
        let exporter = Arc::new(SchemaExporter::new());

        Ok(Self {
            config,
            platform,
            core_config,
            schema_cache: Arc::new(RwLock::new(HashMap::new())),
            udt_registry,
            type_inference,
            validator,
            exporter,
        })
    }

    /// Discover schema from a collection of SSTable files
    pub async fn discover_schema(
        &self,
        keyspace: &str,
        table: &str,
        sstable_files: &[PathBuf],
    ) -> Result<SchemaInfo> {
        let cache_key = format!("{}.{}", keyspace, table);
        let start_time = SystemTime::now();

        // Check cache first
        if self.config.enable_schema_cache {
            if let Some(cached_schema) = self.get_cached_schema(&cache_key).await {
                return Ok(cached_schema);
            }
        }

        // Perform comprehensive schema discovery
        let mut discovery_context = DiscoveryContext::new(keyspace, table, sstable_files);

        // Phase 1: Extract metadata from headers
        self.extract_header_metadata(&mut discovery_context).await?;

        // Phase 2: Sample data for type inference
        self.sample_data_for_inference(&mut discovery_context)
            .await?;

        // Phase 3: Discover UDTs and complex types
        if self.config.enable_udt_discovery {
            self.discover_udts(&mut discovery_context).await?;
        }

        // Phase 4: Analyze collections
        if self.config.enable_collection_analysis {
            self.analyze_collection_types(&mut discovery_context)
                .await?;
        }

        // Phase 5: Discover indexes
        if self.config.enable_index_discovery {
            self.discover_indexes(&mut discovery_context).await?;
        }

        // Phase 6: Infer complete schema
        let schema_info = self.build_schema_info(&mut discovery_context).await?;

        // Phase 7: Schema validation (disabled - unimplemented)
        let validated_schema = schema_info;

        // Calculate discovery metrics
        let discovery_time = start_time.elapsed().unwrap_or(Duration::ZERO);
        let final_schema =
            self.add_performance_metrics(validated_schema, discovery_time, &discovery_context);

        // Cache the result
        if self.config.enable_schema_cache {
            self.cache_schema(cache_key, final_schema.clone()).await;
        }

        Ok(final_schema)
    }

    /// Generate CQL CREATE TABLE statement from schema
    pub async fn generate_cql(&self, schema: &SchemaInfo) -> Result<String> {
        self.exporter.generate_cql(schema).await
    }

    /// Export schema as JSON
    #[cfg(feature = "experimental")]
    pub async fn export_json(&self, schema: &SchemaInfo) -> Result<String> {
        self.exporter.export_json(schema).await
    }

    #[cfg(not(feature = "experimental"))]
    pub async fn export_json(&self, _schema: &SchemaInfo) -> Result<String> {
        Err(crate::error::Error::unsupported_format(
            "JSON export requires experimental feature",
        ))
    }

    /// Export schema as JSON with custom configuration
    #[cfg(feature = "experimental")]
    pub async fn export_json_with_config(
        &self,
        schema: &SchemaInfo,
        config: &crate::schema::json_exporter::JsonExportConfig,
    ) -> Result<String> {
        self.exporter.export_json_with_config(schema, config).await
    }

    #[cfg(not(feature = "experimental"))]
    pub async fn export_json_with_config<T>(
        &self,
        _schema: &SchemaInfo,
        _config: &T,
    ) -> Result<String> {
        Err(crate::error::Error::unsupported_format(
            "JSON export requires experimental feature",
        ))
    }

    /// Generate schema comparison report
    pub async fn compare_schemas(
        &self,
        schema1: &SchemaInfo,
        schema2: &SchemaInfo,
    ) -> Result<String> {
        self.exporter
            .generate_comparison_report(schema1, schema2)
            .await
    }

    // Private implementation methods follow...

    async fn get_cached_schema(&self, cache_key: &str) -> Option<SchemaInfo> {
        let cache = self.schema_cache.read().await;
        if let Some((schema, cached_at)) = cache.get(cache_key) {
            let ttl = Duration::from_secs(self.config.cache_ttl_seconds);
            if cached_at.elapsed().unwrap_or(Duration::MAX) < ttl {
                return Some(schema.clone());
            }
        }
        None
    }

    async fn cache_schema(&self, cache_key: String, schema: SchemaInfo) {
        let mut cache = self.schema_cache.write().await;
        cache.insert(cache_key, (schema, SystemTime::now()));

        // Simple cache eviction
        if cache.len() > 100 {
            let oldest_key = cache
                .iter()
                .min_by_key(|(_, (_, time))| time)
                .map(|(key, _)| key.clone());

            if let Some(key) = oldest_key {
                cache.remove(&key);
            }
        }
    }

    fn add_performance_metrics(
        &self,
        mut schema: SchemaInfo,
        discovery_time: Duration,
        _context: &DiscoveryContext,
    ) -> SchemaInfo {
        schema.metadata.performance_metrics = DiscoveryMetrics {
            total_time_ms: discovery_time.as_millis() as u64,
            header_parsing_time_ms: 0, // TODO: Track individual phase times
            data_sampling_time_ms: 0,
            type_inference_time_ms: 0,
            validation_time_ms: 0,
            peak_memory_usage_bytes: 0, // TODO: Track memory usage
        };
        schema
    }
}

/// Context for schema discovery process
#[derive(Debug)]
struct DiscoveryContext {
    #[allow(dead_code)]
    keyspace: String,
    #[allow(dead_code)]
    table: String,
    #[allow(dead_code)]
    source_files: Vec<PathBuf>,
    #[allow(dead_code)]
    headers: Vec<SSTableHeader>,
    #[allow(dead_code)]
    column_samples: HashMap<String, Vec<Value>>,
    #[allow(dead_code)]
    discovered_udts: HashMap<String, UDTDefinition>,
    #[allow(dead_code)]
    collection_types: HashMap<String, CollectionType>,
    #[allow(dead_code)]
    indexes: Vec<IndexDefinition>,
    #[allow(dead_code)]
    table_options: TableOptions,
    #[allow(dead_code)]
    total_rows_sampled: usize,
    #[allow(dead_code)]
    cassandra_version: Option<CassandraVersion>,
}

impl DiscoveryContext {
    fn new(keyspace: &str, table: &str, files: &[PathBuf]) -> Self {
        Self {
            keyspace: keyspace.to_string(),
            table: table.to_string(),
            source_files: files.to_vec(),
            headers: Vec::new(),
            column_samples: HashMap::new(),
            discovered_udts: HashMap::new(),
            collection_types: HashMap::new(),
            indexes: Vec::new(),
            table_options: TableOptions {
                compaction: None,
                compression: None,
                caching: None,
                bloom_filter_fp_chance: None,
                gc_grace_seconds: None,
                default_time_to_live: None,
                memtable_flush_period_in_ms: None,
                additional_properties: HashMap::new(),
            },
            total_rows_sampled: 0,
            cassandra_version: None,
        }
    }
}

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

    #[tokio::test]
    async fn test_schema_discovery_engine_creation() {
        let config = SchemaDiscoveryConfig::default();
        let core_config = Config::default();
        let platform = Arc::new(Platform::new(&core_config).await.unwrap());

        let engine = SchemaDiscoveryEngine::new(config, platform, core_config)
            .await
            .unwrap();

        // Test basic functionality
        assert!(engine.schema_cache.read().await.is_empty());
    }

    #[test]
    fn test_discovery_context_creation() {
        let files = vec![PathBuf::from("test.sst")];
        let context = DiscoveryContext::new("test_ks", "test_table", &files);

        assert_eq!(context.keyspace, "test_ks");
        assert_eq!(context.table, "test_table");
        assert_eq!(context.source_files.len(), 1);
    }

    #[test]
    fn test_schema_info_serialization() {
        let schema_info = SchemaInfo {
            keyspace: "test".to_string(),
            table: "users".to_string(),
            partition_key: Vec::new(),
            clustering_keys: Vec::new(),
            regular_columns: Vec::new(),
            static_columns: Vec::new(),
            collection_types: HashMap::new(),
            user_defined_types: Vec::new(),
            indexes: Vec::new(),
            table_options: TableOptions {
                compaction: None,
                compression: None,
                caching: None,
                bloom_filter_fp_chance: None,
                gc_grace_seconds: None,
                default_time_to_live: None,
                memtable_flush_period_in_ms: None,
                additional_properties: HashMap::new(),
            },
            metadata: SchemaMetadata {
                discovered_at: std::time::UNIX_EPOCH,
                source_files: Vec::new(),
                total_rows_sampled: 0,
                cassandra_version: None,
                discovery_method: DiscoveryMethod::HeaderMetadata,
                version: 1,
                validation_results: ValidationResults {
                    status: ValidationStatus::Valid,
                    errors: Vec::new(),
                    warnings: Vec::new(),
                    consistency_results: ConsistencyResults {
                        files_analyzed: 0,
                        schema_mismatches: 0,
                        type_inconsistencies: Vec::new(),
                        udt_conflicts: Vec::new(),
                    },
                },
                performance_metrics: DiscoveryMetrics {
                    total_time_ms: 0,
                    header_parsing_time_ms: 0,
                    data_sampling_time_ms: 0,
                    type_inference_time_ms: 0,
                    validation_time_ms: 0,
                    peak_memory_usage_bytes: 0,
                },
            },
        };

        // Test that it can be serialized and deserialized
        let json = serde_json::to_string(&schema_info).unwrap();
        let deserialized: SchemaInfo = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.keyspace, "test");
        assert_eq!(deserialized.table, "users");
    }

    #[tokio::test]
    async fn test_extract_header_metadata_stub() {
        let config = SchemaDiscoveryConfig::default();
        let core_config = Config::default();
        let platform = Arc::new(Platform::new(&core_config).await.unwrap());

        let engine = SchemaDiscoveryEngine::new(config, platform, core_config)
            .await
            .unwrap();

        let mut context = DiscoveryContext::new("test_ks", "test_table", &[]);

        // Test that the stub method executes without panicking
        let result = engine.extract_header_metadata(&mut context).await;
        assert!(
            result.is_ok(),
            "extract_header_metadata stub should return Ok(())"
        );
    }

    #[tokio::test]
    async fn test_sample_data_for_inference_stub() {
        let config = SchemaDiscoveryConfig::default();
        let core_config = Config::default();
        let platform = Arc::new(Platform::new(&core_config).await.unwrap());

        let engine = SchemaDiscoveryEngine::new(config, platform, core_config)
            .await
            .unwrap();

        let mut context = DiscoveryContext::new("test_ks", "test_table", &[]);

        // Test that the stub method executes without panicking
        let result = engine.sample_data_for_inference(&mut context).await;
        assert!(
            result.is_ok(),
            "sample_data_for_inference stub should return Ok(())"
        );
    }
}