sql-cli 1.73.1

SQL query tool for CSV/JSON with both interactive TUI and non-interactive CLI modes - perfect for exploration and automation
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
//! Query preprocessing pipeline
//!
//! This module provides a structured, extensible pipeline for transforming SQL ASTs
//! before execution. Transformers are applied in a defined order, with logging and
//! debugging support.

use crate::sql::parser::ast::SelectStatement;
use anyhow::Result;
use std::time::Instant;
use tracing::{debug, info};

/// Trait for AST transformers that can be added to the preprocessing pipeline
pub trait ASTTransformer: Send + Sync {
    /// Name of this transformer (for logging and debugging)
    fn name(&self) -> &str;

    /// Description of what this transformer does
    fn description(&self) -> &str {
        "No description provided"
    }

    /// Whether this transformer is enabled
    fn enabled(&self) -> bool {
        true
    }

    /// Transform the AST, returning the modified statement
    ///
    /// Transformers should be idempotent where possible and should not
    /// modify the semantic meaning of the query.
    fn transform(&mut self, stmt: SelectStatement) -> Result<SelectStatement>;

    /// Called before transformation starts (for initialization)
    fn begin(&mut self) -> Result<()> {
        Ok(())
    }

    /// Called after transformation completes (for cleanup)
    fn end(&mut self) -> Result<()> {
        Ok(())
    }
}

/// Statistics about a single transformation
#[derive(Debug, Clone)]
pub struct TransformStats {
    pub transformer_name: String,
    pub duration_micros: u64,
    pub applied: bool,
    pub modifications: usize,
}

/// Complete preprocessing statistics
#[derive(Debug, Clone, Default)]
pub struct PreprocessingStats {
    pub transformations: Vec<TransformStats>,
    pub total_duration_micros: u64,
    pub transformers_applied: usize,
}

impl PreprocessingStats {
    pub fn add_transform(&mut self, stats: TransformStats) {
        self.total_duration_micros += stats.duration_micros;
        if stats.applied {
            self.transformers_applied += 1;
        }
        self.transformations.push(stats);
    }

    pub fn summary(&self) -> String {
        format!(
            "{} transformer(s) applied in {:.2}ms",
            self.transformers_applied,
            self.total_duration_micros as f64 / 1000.0
        )
    }

    /// Returns true if any transformer actually modified the AST
    pub fn has_modifications(&self) -> bool {
        self.transformations
            .iter()
            .any(|stats| stats.modifications > 0)
    }
}

/// Configuration for the preprocessing pipeline
#[derive(Debug, Clone)]
pub struct PipelineConfig {
    /// Whether to enable preprocessing at all
    pub enabled: bool,

    /// Whether to log each transformation
    pub verbose_logging: bool,

    /// Whether to collect detailed statistics
    pub collect_stats: bool,

    /// Whether to show the AST before/after each transformation (Rust Debug format)
    pub debug_ast_changes: bool,

    /// Whether to show SQL before/after each transformation (formatted SQL)
    pub show_sql_transformations: bool,
}

impl Default for PipelineConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            verbose_logging: false,
            collect_stats: true,
            debug_ast_changes: false,
            show_sql_transformations: false,
        }
    }
}

/// The main preprocessing pipeline
///
/// Orchestrates the application of multiple AST transformers in sequence.
/// Provides logging, debugging, and statistics collection.
///
/// # Example
///
/// ```ignore
/// use sql_cli::query_plan::{PreprocessingPipeline, PipelineConfig};
/// use sql_cli::query_plan::{CTEHoister, ExpressionLifter};
///
/// let mut pipeline = PreprocessingPipeline::new(PipelineConfig::default());
/// pipeline.add_transformer(Box::new(CTEHoister::new()));
/// pipeline.add_transformer(Box::new(ExpressionLifter::new()));
///
/// let transformed = pipeline.process(statement)?;
/// ```
pub struct PreprocessingPipeline {
    transformers: Vec<Box<dyn ASTTransformer>>,
    config: PipelineConfig,
    stats: PreprocessingStats,
}

impl PreprocessingPipeline {
    /// Create a new empty pipeline with the given configuration
    pub fn new(config: PipelineConfig) -> Self {
        Self {
            transformers: Vec::new(),
            config,
            stats: PreprocessingStats::default(),
        }
    }

    /// Add a transformer to the pipeline
    ///
    /// Transformers are applied in the order they are added.
    pub fn add_transformer(&mut self, transformer: Box<dyn ASTTransformer>) {
        self.transformers.push(transformer);
    }

    /// Get the collected statistics
    pub fn stats(&self) -> &PreprocessingStats {
        &self.stats
    }

    /// Reset statistics
    pub fn reset_stats(&mut self) {
        self.stats = PreprocessingStats::default();
    }

    /// Process a SQL statement through the pipeline
    ///
    /// Applies each enabled transformer in sequence, collecting statistics
    /// and logging as configured.
    pub fn process(&mut self, mut stmt: SelectStatement) -> Result<SelectStatement> {
        if !self.config.enabled {
            debug!("Preprocessing pipeline is disabled");
            return Ok(stmt);
        }

        let pipeline_start = Instant::now();
        self.reset_stats();

        info!(
            "Starting preprocessing pipeline with {} transformer(s)",
            self.transformers.len()
        );

        for transformer in &mut self.transformers {
            if !transformer.enabled() {
                debug!("Transformer '{}' is disabled, skipping", transformer.name());
                continue;
            }

            let transform_start = Instant::now();

            if self.config.verbose_logging {
                info!(
                    "Applying transformer: {} - {}",
                    transformer.name(),
                    transformer.description()
                );
            }

            // Store original for comparison if debugging
            let original_ast = if self.config.debug_ast_changes {
                Some(format!("{:#?}", stmt))
            } else {
                None
            };

            // Store original SQL for comparison if showing transformations
            let original_sql = if self.config.show_sql_transformations {
                Some(crate::sql::parser::ast_formatter::format_select_statement(
                    &stmt,
                ))
            } else {
                None
            };

            // Call begin hook
            transformer.begin()?;

            // Apply transformation
            let transformed = transformer.transform(stmt)?;

            // Call end hook
            transformer.end()?;

            let duration = transform_start.elapsed();

            // Check if anything changed (AST debug format)
            let mut modifications = 0;
            if let Some(original_ast_str) = original_ast {
                let new_ast_str = format!("{:#?}", transformed);
                if original_ast_str != new_ast_str {
                    if self.config.debug_ast_changes {
                        debug!("AST changed by '{}'", transformer.name());
                        debug!("Before:\n{}", original_ast_str);
                        debug!("After:\n{}", new_ast_str);
                    }
                    modifications = 1;
                }
            }

            // Show SQL transformations if enabled
            if let Some(original_sql_str) = original_sql {
                let new_sql_str =
                    crate::sql::parser::ast_formatter::format_select_statement(&transformed);
                if original_sql_str != new_sql_str {
                    eprintln!(
                        "\n╔════════════════════════════════════════════════════════════════╗"
                    );
                    eprintln!("║ Transformer: {:<51} ║", transformer.name());
                    eprintln!("╠════════════════════════════════════════════════════════════════╣");
                    eprintln!("║ BEFORE:                                                        ║");
                    eprintln!("╠════════════════════════════════════════════════════════════════╣");
                    for line in original_sql_str.lines() {
                        eprintln!("  {}", line);
                    }
                    eprintln!("╠════════════════════════════════════════════════════════════════╣");
                    eprintln!("║ AFTER:                                                         ║");
                    eprintln!("╠════════════════════════════════════════════════════════════════╣");
                    for line in new_sql_str.lines() {
                        eprintln!("  {}", line);
                    }
                    eprintln!(
                        "╚════════════════════════════════════════════════════════════════╝\n"
                    );
                    modifications = 1;
                }
            }

            // Record statistics
            let stats = TransformStats {
                transformer_name: transformer.name().to_string(),
                duration_micros: duration.as_micros() as u64,
                applied: true,
                modifications,
            };

            self.stats.add_transform(stats);

            stmt = transformed;
        }

        let total_duration = pipeline_start.elapsed();
        self.stats.total_duration_micros = total_duration.as_micros() as u64;

        if self.config.verbose_logging {
            info!("Preprocessing complete: {}", self.stats.summary());
        }

        Ok(stmt)
    }

    /// Get a summary of what transformers are in the pipeline
    pub fn transformer_summary(&self) -> String {
        let enabled_count = self.transformers.iter().filter(|t| t.enabled()).count();
        let total_count = self.transformers.len();

        let names: Vec<String> = self
            .transformers
            .iter()
            .map(|t| {
                let status = if t.enabled() { "" } else { "" };
                format!("{} {}", status, t.name())
            })
            .collect();

        format!(
            "{}/{} transformers enabled:\n{}",
            enabled_count,
            total_count,
            names.join("\n")
        )
    }
}

impl Default for PreprocessingPipeline {
    fn default() -> Self {
        Self::new(PipelineConfig::default())
    }
}

/// Builder for creating a preprocessing pipeline with common transformers
pub struct PipelineBuilder {
    pipeline: PreprocessingPipeline,
}

impl PipelineBuilder {
    /// Start building a new pipeline
    pub fn new() -> Self {
        Self {
            pipeline: PreprocessingPipeline::default(),
        }
    }

    /// Start with a specific configuration
    pub fn with_config(config: PipelineConfig) -> Self {
        Self {
            pipeline: PreprocessingPipeline::new(config),
        }
    }

    /// Enable verbose logging
    pub fn verbose(mut self) -> Self {
        self.pipeline.config.verbose_logging = true;
        self
    }

    /// Enable AST change debugging
    pub fn debug_ast(mut self) -> Self {
        self.pipeline.config.debug_ast_changes = true;
        self
    }

    /// Add a custom transformer to the pipeline
    pub fn with_transformer(mut self, transformer: Box<dyn ASTTransformer>) -> Self {
        self.pipeline.add_transformer(transformer);
        self
    }

    /// Build the final pipeline
    pub fn build(self) -> PreprocessingPipeline {
        self.pipeline
    }
}

impl Default for PipelineBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sql::parser::ast::SelectStatement;

    // Mock transformer for testing
    struct NoOpTransformer {
        name: String,
        enabled: bool,
    }

    impl ASTTransformer for NoOpTransformer {
        fn name(&self) -> &str {
            &self.name
        }

        fn description(&self) -> &str {
            "Test transformer that does nothing"
        }

        fn enabled(&self) -> bool {
            self.enabled
        }

        fn transform(&mut self, stmt: SelectStatement) -> Result<SelectStatement> {
            Ok(stmt)
        }
    }

    #[test]
    fn test_empty_pipeline() {
        let mut pipeline = PreprocessingPipeline::default();
        let stmt = SelectStatement::default();
        let result = pipeline.process(stmt);
        assert!(result.is_ok());
    }

    #[test]
    fn test_disabled_pipeline() {
        let mut config = PipelineConfig::default();
        config.enabled = false;

        let mut pipeline = PreprocessingPipeline::new(config);
        pipeline.add_transformer(Box::new(NoOpTransformer {
            name: "test".to_string(),
            enabled: true,
        }));

        let stmt = SelectStatement::default();
        let result = pipeline.process(stmt);
        assert!(result.is_ok());
        assert_eq!(pipeline.stats().transformers_applied, 0);
    }

    #[test]
    fn test_disabled_transformer() {
        let mut pipeline = PreprocessingPipeline::default();
        pipeline.add_transformer(Box::new(NoOpTransformer {
            name: "disabled".to_string(),
            enabled: false,
        }));

        let stmt = SelectStatement::default();
        let result = pipeline.process(stmt);
        assert!(result.is_ok());
        assert_eq!(pipeline.stats().transformers_applied, 0);
    }

    #[test]
    fn test_stats_collection() {
        let mut pipeline = PreprocessingPipeline::default();
        pipeline.add_transformer(Box::new(NoOpTransformer {
            name: "test1".to_string(),
            enabled: true,
        }));
        pipeline.add_transformer(Box::new(NoOpTransformer {
            name: "test2".to_string(),
            enabled: true,
        }));

        let stmt = SelectStatement::default();
        let result = pipeline.process(stmt);
        assert!(result.is_ok());
        assert_eq!(pipeline.stats().transformers_applied, 2);
        assert_eq!(pipeline.stats().transformations.len(), 2);
    }

    #[test]
    fn test_builder() {
        let pipeline = PipelineBuilder::new()
            .verbose()
            .debug_ast()
            .with_transformer(Box::new(NoOpTransformer {
                name: "test".to_string(),
                enabled: true,
            }))
            .build();

        assert!(pipeline.config.verbose_logging);
        assert!(pipeline.config.debug_ast_changes);
        assert_eq!(pipeline.transformers.len(), 1);
    }
}