sql-insight-cli 0.3.0

A CLI utility for SQL query analysis, formatting, and transformation.
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
use sql_insight::catalog::Catalog;
use sql_insight::diagnostic::TableLevelDiagnostic;
use sql_insight::error::Error;
use sql_insight::extractor::{
    extract_column_operations_with_options, extract_crud_tables_with_options,
    extract_table_operations_with_options, ColumnLineageKind, ColumnOperation, ColumnTarget,
    ExtractorOptions, TableOperation,
};
use sql_insight::formatter::FormatterOptions;
use sql_insight::normalizer::NormalizerOptions;
use sql_insight::sqlparser::dialect::{self, Dialect};
use sql_insight::{
    CaseRule, ColumnRead, ColumnWrite, IdentifierCasing, ResolutionKind, TableRead, TableWrite,
};

pub trait CliExecutable {
    fn execute(&self) -> Result<Vec<String>, Error>;
}

fn get_dialect(dialect_name: Option<&str>) -> Result<Box<dyn dialect::Dialect>, Error> {
    let dialect_name = dialect_name.unwrap_or("generic");
    dialect::dialect_from_str(dialect_name)
        .ok_or_else(|| Error::ArgumentError(format!("Dialect not found: {}", dialect_name)))
}

pub struct FormatExecutor {
    sql: String,
    dialect_name: Option<String>,
    options: FormatterOptions,
}

impl FormatExecutor {
    pub fn new(sql: String, dialect_name: Option<String>) -> Self {
        Self {
            sql,
            dialect_name,
            options: FormatterOptions::new(),
        }
    }

    pub fn with_options(mut self, options: FormatterOptions) -> Self {
        self.options = options;
        self
    }
}

impl CliExecutable for FormatExecutor {
    fn execute(&self) -> Result<Vec<String>, Error> {
        sql_insight::formatter::format_with_options(
            get_dialect(self.dialect_name.as_deref())?.as_ref(),
            self.sql.as_ref(),
            self.options.clone(),
        )
    }
}

pub struct NormalizeExecutor {
    sql: String,
    dialect_name: Option<String>,
    options: NormalizerOptions,
}

impl NormalizeExecutor {
    pub fn new(sql: String, dialect_name: Option<String>) -> Self {
        Self {
            sql,
            dialect_name,
            options: NormalizerOptions::new(),
        }
    }

    pub fn with_options(mut self, options: NormalizerOptions) -> Self {
        self.options = options;
        self
    }
}

impl CliExecutable for NormalizeExecutor {
    fn execute(&self) -> Result<Vec<String>, Error> {
        sql_insight::normalizer::normalize_with_options(
            get_dialect(self.dialect_name.as_deref())?.as_ref(),
            self.sql.as_ref(),
            self.options.clone(),
        )
    }
}

/// Which extraction surface an [`ExtractExecutor`] produces.
#[derive(Clone, Copy)]
pub enum ExtractKind {
    Crud,
    TableOps,
    ColumnOps,
}

/// Per-class identifier-casing overrides from the CLI. `all` is the
/// uniform base; the per-class fields patch individual classes on top.
/// All `None` = use the dialect default unchanged.
#[derive(Default)]
pub struct CasingOverride {
    pub all: Option<CaseRule>,
    pub table: Option<CaseRule>,
    pub table_alias: Option<CaseRule>,
    pub column: Option<CaseRule>,
}

impl CasingOverride {
    /// Resolve to an [`IdentifierCasing`], or `None` when no override was
    /// given (so the binder keeps the dialect default). Layering: dialect
    /// default → uniform `all` → per-class patches.
    fn resolve(&self, dialect: &dyn Dialect) -> Option<IdentifierCasing> {
        if self.all.is_none()
            && self.table.is_none()
            && self.table_alias.is_none()
            && self.column.is_none()
        {
            return None;
        }
        let mut casing = match self.all {
            Some(rule) => IdentifierCasing::uniform(rule),
            None => IdentifierCasing::for_dialect(dialect),
        };
        if let Some(rule) = self.table {
            casing.table = rule;
        }
        if let Some(rule) = self.table_alias {
            casing.table_alias = rule;
        }
        if let Some(rule) = self.column {
            casing.column = rule;
        }
        Some(casing)
    }
}

/// The single extractor entry point: builds the dialect, optional catalog
/// (from a DDL file), and casing override once, then dispatches on `kind`.
pub struct ExtractExecutor {
    pub kind: ExtractKind,
    pub sql: String,
    pub dialect_name: Option<String>,
    /// DDL file whose `CREATE TABLE`s populate the catalog.
    pub ddl_file: Option<String>,
    /// Query-side default schema / catalog (the search-path-style fill
    /// used before matching). Set only when the user asked — a fallback
    /// must not leak into query fill or it would break multi-schema
    /// right-anchored resolution. Also names unqualified DDL tables.
    pub default_schema: Option<String>,
    pub default_catalog: Option<String>,
    pub casing: CasingOverride,
    pub format: OutputFormat,
}

/// How an extract command renders its result.
#[derive(Clone, Copy, Default)]
pub enum OutputFormat {
    /// Human-readable text (the default).
    #[default]
    Text,
    /// One JSON array of the per-statement results (each an `Ok` value or
    /// an `{ "error": ... }` object), pretty-printed.
    Json,
}

impl CliExecutable for ExtractExecutor {
    fn execute(&self) -> Result<Vec<String>, Error> {
        let dialect = get_dialect(self.dialect_name.as_deref())?;
        let dialect = dialect.as_ref();
        // Resolve the casing override first: the catalog must be built with the
        // same casing the extraction uses, or a `--casing` override silently
        // breaks every catalog lookup (the stored identity wouldn't match what a
        // query reference folds to).
        let casing = self.casing.resolve(dialect);
        let catalog = self.load_catalog(dialect, casing)?;

        let mut options = ExtractorOptions::new();
        if let Some(catalog) = &catalog {
            options = options.with_catalog(catalog);
        }
        if let Some(casing) = casing {
            options = options.with_casing(casing);
        }

        let sql = self.sql.as_ref();
        match (self.kind, self.format) {
            (ExtractKind::Crud, OutputFormat::Text) => Ok(render_display(
                &extract_crud_tables_with_options(dialect, sql, options)?,
                |c| &c.diagnostics,
            )),
            (ExtractKind::TableOps, OutputFormat::Text) => Ok(render_statements(
                &extract_table_operations_with_options(dialect, sql, options)?,
                format_table_operation,
            )),
            (ExtractKind::ColumnOps, OutputFormat::Text) => Ok(render_statements(
                &extract_column_operations_with_options(dialect, sql, options)?,
                format_column_operation,
            )),
            (ExtractKind::Crud, OutputFormat::Json) => {
                render_json(&extract_crud_tables_with_options(dialect, sql, options)?)
            }
            (ExtractKind::TableOps, OutputFormat::Json) => render_json(
                &extract_table_operations_with_options(dialect, sql, options)?,
            ),
            (ExtractKind::ColumnOps, OutputFormat::Json) => render_json(
                &extract_column_operations_with_options(dialect, sql, options)?,
            ),
        }
    }
}

impl ExtractExecutor {
    /// Build the catalog from the `--ddl-file` (if any) plus query-side
    /// defaults. Returns `None` only when no catalog input was given at all
    /// — defaults alone still build a (table-less) catalog, so a bare ref
    /// qualifies to `--default-schema` even without a DDL file. Unqualified
    /// DDL tables register schema-less (no fabricated schema).
    fn load_catalog(
        &self,
        dialect: &dyn Dialect,
        casing: Option<IdentifierCasing>,
    ) -> Result<Option<Catalog>, Error> {
        if self.ddl_file.is_none()
            && self.default_schema.is_none()
            && self.default_catalog.is_none()
        {
            return Ok(None);
        }
        // Register identifiers with the same casing the extraction uses (the
        // `--casing` override, else the dialect default) so the catalog's
        // canonical form matches what a query reference folds to.
        let casing = casing.unwrap_or_else(|| IdentifierCasing::for_dialect(dialect));
        let mut catalog = match &self.ddl_file {
            Some(path) => {
                let ddl = std::fs::read_to_string(path).map_err(|e| {
                    Error::ArgumentError(format!("Failed to read DDL file {path}: {e}"))
                })?;
                // Prefix the DDL-file context so a parse error in the catalog
                // file isn't mistaken for one in the analysed query (whose own
                // errors surface per-statement, unprefixed).
                Catalog::from_ddl_with_casing(dialect, &ddl, casing).map_err(|e| {
                    Error::ArgumentError(format!("Failed to parse DDL file {path}: {e}"))
                })?
            }
            None => Catalog::new(),
        };
        if let Some(schema) = &self.default_schema {
            catalog = catalog.default_schema(schema.clone());
        }
        if let Some(cat) = &self.default_catalog {
            catalog = catalog.default_catalog(cat.clone());
        }
        Ok(Some(catalog))
    }
}

// ===== text rendering for the rich (operation) extractors =================
//
// One multi-line block per statement: `[N] <Kind>` header followed by the
// non-empty `reads` / `writes` / `lineage` surfaces and any diagnostics.
// Convention: a default is unmarked, a deviation is marked — `Inferred`
// resolution and `Passthrough` lineage carry no marker, so the common
// catalog-free SELECT stays clean while `(cataloged)` / `(ambiguous)` /
// `(unresolved)` and `[transform]` stand out.

/// Render each per-statement result, numbering from 1; an `Err` statement
/// becomes a one-line `[N] Error: ...` so one bad statement doesn't sink
/// the batch.
fn render_statements<T>(
    results: &[Result<T, Error>],
    format_one: impl Fn(usize, &T) -> String,
) -> Vec<String> {
    results
        .iter()
        .enumerate()
        .map(|(i, r)| match r {
            Ok(op) => format_one(i + 1, op),
            Err(e) => format!("[{}] Error: {}", i + 1, e),
        })
        .collect()
}

/// Serialize the per-statement results to one pretty JSON array. Each
/// element is the `Ok` value (the extractor's serde shape) or, for a failed
/// statement, an `{ "error": "<message>" }` object — so one bad statement
/// doesn't sink the batch and the array length still matches the input.
fn render_json<T: serde::Serialize>(results: &[Result<T, Error>]) -> Result<Vec<String>, Error> {
    let entries: Vec<serde_json::Value> = results
        .iter()
        .map(|r| match r {
            Ok(value) => serde_json::to_value(value)
                .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() })),
            Err(e) => serde_json::json!({ "error": e.to_string() }),
        })
        .collect();
    let json = serde_json::to_string_pretty(&entries)
        .map_err(|e| Error::AnalysisError(format!("failed to serialize result as JSON: {e}")))?;
    Ok(vec![json])
}

/// Render the `Display`-backed extractor (`crud`), one
/// statement per line, appending any diagnostics as `! <message>` lines
/// (the same marker the operation extractors use) so the text output never
/// silently drops an unsupported / over-qualified statement.
fn render_display<T: std::fmt::Display>(
    results: &[Result<T, Error>],
    diagnostics: impl Fn(&T) -> &[TableLevelDiagnostic],
) -> Vec<String> {
    results
        .iter()
        .map(|r| match r {
            Ok(value) => {
                let mut lines: Vec<String> = Vec::new();
                let body = value.to_string();
                if !body.is_empty() {
                    lines.push(body);
                }
                for d in diagnostics(value) {
                    lines.push(format!("  ! {}", d.message));
                }
                lines.join("\n")
            }
            Err(e) => format!("Error: {e}"),
        })
        .collect()
}

/// `  reads:    a, b` — labels pad to a fixed column so values align.
fn labeled(label: &str, value: String) -> String {
    format!("  {label:<8} {value}")
}

/// Marker for a non-default resolution; `Inferred` (the catalog-free
/// default) is unmarked.
fn resolution_marker(resolution: ResolutionKind) -> &'static str {
    match resolution {
        ResolutionKind::Inferred => "",
        ResolutionKind::Cataloged => " (cataloged)",
        ResolutionKind::Ambiguous => " (ambiguous)",
        ResolutionKind::Unresolved => " (unresolved)",
    }
}

fn table_read(read: &TableRead) -> String {
    format!("{}{}", read.reference, resolution_marker(read.resolution))
}

fn table_write(write: &TableWrite) -> String {
    format!("{}{}", write.reference, resolution_marker(write.resolution))
}

fn column_read(read: &ColumnRead) -> String {
    format!("{}{}", read.reference, resolution_marker(read.resolution))
}

fn column_write(write: &ColumnWrite) -> String {
    format!("{}{}", write.reference, resolution_marker(write.resolution))
}

fn column_target(target: &ColumnTarget) -> String {
    match target {
        ColumnTarget::Relation(write) => column_write(write),
        ColumnTarget::QueryOutput { name, position } => match name {
            Some(name) => name.value.clone(),
            None => format!("#{position}"),
        },
    }
}

/// Join `lineage` edges one per line, the first after the `lineage:` label
/// and the rest aligned under it.
fn lineage_block(edges: Vec<String>) -> String {
    let pad = " ".repeat(labeled("lineage:", String::new()).len());
    edges
        .iter()
        .enumerate()
        .map(|(i, edge)| {
            if i == 0 {
                labeled("lineage:", edge.clone())
            } else {
                format!("{pad}{edge}")
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn format_table_operation(n: usize, op: &TableOperation) -> String {
    let mut lines = vec![format!("[{n}] {:?}", op.statement_kind)];
    if !op.reads.is_empty() {
        let reads = op.reads.iter().map(table_read).collect::<Vec<_>>();
        lines.push(labeled("reads:", reads.join(", ")));
    }
    if !op.writes.is_empty() {
        let writes = op.writes.iter().map(table_write).collect::<Vec<_>>();
        lines.push(labeled("writes:", writes.join(", ")));
    }
    if !op.lineage.is_empty() {
        let edges = op
            .lineage
            .iter()
            .map(|e| format!("{} -> {}", table_read(&e.source), table_write(&e.target)))
            .collect();
        lines.push(lineage_block(edges));
    }
    for d in &op.diagnostics {
        lines.push(format!("  ! {}", d.message));
    }
    lines.join("\n")
}

fn format_column_operation(n: usize, op: &ColumnOperation) -> String {
    let mut lines = vec![format!("[{n}] {:?}", op.statement_kind)];
    if !op.reads.is_empty() {
        let reads = op.reads.iter().map(column_read).collect::<Vec<_>>();
        lines.push(labeled("reads:", reads.join(", ")));
    }
    if !op.writes.is_empty() {
        let writes = op.writes.iter().map(column_write).collect::<Vec<_>>();
        lines.push(labeled("writes:", writes.join(", ")));
    }
    if !op.lineage.is_empty() {
        let edges = op
            .lineage
            .iter()
            .map(|e| {
                let transform = match e.kind {
                    ColumnLineageKind::Transformation => " [transform]",
                    ColumnLineageKind::Passthrough => "",
                };
                format!(
                    "{} -> {}{transform}",
                    column_read(&e.source),
                    column_target(&e.target)
                )
            })
            .collect();
        lines.push(lineage_block(edges));
    }
    for d in &op.diagnostics {
        lines.push(format!("  ! {}", d.message));
    }
    lines.join("\n")
}