duck-sqllsp 3.0.0

duck-sqllsp: a modern SQL language server.
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
//! `duck-sqllsp` binary entry point.
//!
//! Defaults to `server` (LSP over stdio). Future subcommands (`lint`,
//! `format`, `introspect`, `version`) are sketched but not yet wired.

mod doctor;
mod server;

use clap::{Parser, Subcommand};

#[derive(Parser, Debug)]
#[command(name = "duck-sqllsp", version, about, long_about = None)]
struct Cli {
  #[command(subcommand)]
  cmd: Option<Cmd>,
}

#[derive(Subcommand, Debug)]
enum Cmd {
  /// Run the language server over stdio (default).
  Server {
    /// Accepted for compatibility with VS Code's
    /// vscode-languageclient (TransportKind.stdio appends `--stdio`
    /// to every command it spawns). We always use stdio anyway, so
    /// the flag is a no-op.
    #[arg(long, hide = true)]
    stdio: bool,
    /// Accepted for compatibility with editors that pass `--node-ipc`
    /// or `--socket=...`. Ignored.
    #[arg(long, hide = true)]
    node_ipc: bool,
    #[arg(long, hide = true)]
    socket: Option<String>,
  },
  /// Print version and capability info.
  Version,
  /// List every registered lint rule with its code, default severity,
  /// and one-line summary.
  Rules {
    /// Emit machine-readable JSON instead of the human table.
    #[arg(long)]
    json: bool,
    /// Only list rules with this default severity (error/warning/info/hint).
    #[arg(long)]
    severity: Option<String>,
    /// Only list rules whose code or summary contains this text
    /// (case-insensitive). With 700+ rules, this is usually how you
    /// find the one you saw in the editor.
    #[arg(long)]
    search: Option<String>,
  },
  /// Lint one or more .sql files; emit diagnostics to stdout.
  ///
  /// Exit status: 0 = no errors (warnings/hints OK); 1 = at least one
  /// error-level diagnostic; 2 = an input file could not be read.
  Lint {
    /// File paths to lint. Use `-` to read SQL from stdin.
    files: Vec<String>,
    /// Output format: text (human, default) or json (one row per diagnostic).
    #[arg(long, default_value = "text")]
    format: String,
    /// Treat warnings as errors (exit 1 if any warnings found).
    #[arg(long)]
    warnings_as_errors: bool,
    /// SQL dialect: postgres, mysql, sqlite, mssql, generic.
    ///
    /// Defaults to the `dialect` in `.duck-sqllsp.toml`, then postgres.
    #[arg(long)]
    dialect: Option<String>,
  },
  /// Format one or more .sql files in place (or to stdout with `-`).
  ///
  /// Uses the same external sql-formatter the LSP uses, with the
  /// project `.duck-sqllsp.toml` formatter style if present.
  Format {
    /// File paths to format. Use `-` to read from stdin and write to stdout.
    files: Vec<String>,
    /// Print the formatted result to stdout instead of overwriting the file.
    #[arg(long)]
    stdout: bool,
    /// Dialect for `sql-formatter -l`: postgresql (default), mysql, sqlite, transactsql.
    #[arg(long, default_value = "postgresql")]
    language: String,
  },
  /// Report what the server can actually see: formatter binary, config
  /// file, workspace root, offline catalog size, and connection health.
  ///
  /// Exit status: 0 when nothing is broken (warnings are fine), 1 when
  /// a check fails.
  Doctor {
    /// Directory to inspect. Defaults to the current directory.
    path: Option<String>,
  },
  /// Dump the live DB catalog (when a connection is configured) or the
  /// derived offline catalog (every CREATE TABLE / FUNCTION / TYPE in
  /// the supplied files) as JSON.
  Introspect {
    /// Source files to harvest tables/functions/types from when no DB
    /// connection is configured. Ignored when --url is supplied.
    files: Vec<String>,
    /// Database URL. When set, connects + dumps the live catalog.
    #[arg(long)]
    url: Option<String>,
    /// SQL dialect: postgres, mysql, sqlite, mssql, generic.
    ///
    /// Defaults to the `dialect` in `.duck-sqllsp.toml`, then postgres.
    /// Reading a SQLite schema as postgres yields nothing at all, because
    /// `[bracketed]` identifiers are a syntax error there.
    #[arg(long)]
    dialect: Option<String>,
  },
}

/// Die quietly when a pipe closes, the way every other CLI does.
///
/// Rust ignores SIGPIPE at startup, so `duck-sqllsp rules | head` does
/// not stop at `head` -- it keeps writing until the failed write panics:
///
///     thread 'main' panicked at library/std/src/io/stdio.rs:
///     failed printing to stdout: Broken pipe (os error 32)
///
/// Piping into `head`, `less`, or `grep -m1` is completely ordinary,
/// especially for `rules` (700+ lines) and `introspect`. Restoring the
/// default disposition turns that panic into a clean exit.
#[cfg(unix)]
fn restore_sigpipe() {
  // SAFETY: setting a signal disposition to SIG_DFL before any threads
  // are spawned. This is the documented way to undo Rust's startup
  // override.
  unsafe {
    libc::signal(libc::SIGPIPE, libc::SIG_DFL);
  }
}

#[cfg(not(unix))]
fn restore_sigpipe() {}

fn main() -> anyhow::Result<()> {
  restore_sigpipe();
  init_tracing();
  // Accept unknown flags gracefully so we never blow up on a transport
  // flag we didn't anticipate. clap's `Cli::parse` exits on unknown
  // args; try the strict parse first, fall back to "drop any --flag /
  // --flag=value the LSP client sent and re-parse the rest".
  //
  // Help / version are NOT unknown-flag errors -- clap raises distinct
  // `DisplayHelp` / `DisplayVersion` error kinds that print to stdout
  // and exit 0. Letting those propagate is what the user expects when
  // they run `duck-sqllsp --help`; only the genuine "weird arg" errors
  // (`UnknownArgument`, `InvalidValue`, etc.) should hit the fallback.
  let argv: Vec<String> = std::env::args().collect();
  let cli = match Cli::try_parse_from(&argv) {
    Ok(c) => c,
    Err(e) => {
      use clap::error::ErrorKind;
      match e.kind() {
        ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand | ErrorKind::DisplayVersion => {
          e.exit()
        },
        _ => {
          let filtered: Vec<String> =
            argv.into_iter().enumerate().filter(|(i, a)| *i == 0 || !a.starts_with("--")).map(|(_, a)| a).collect();
          Cli::try_parse_from(&filtered)
            .unwrap_or(Cli { cmd: Some(Cmd::Server { stdio: true, node_ipc: false, socket: None }) })
        },
      }
    },
  };
  match cli.cmd.unwrap_or(Cmd::Server { stdio: true, node_ipc: false, socket: None }) {
    Cmd::Server { .. } => server::run(),
    Cmd::Doctor { path } => doctor::run(path),
    Cmd::Version => {
      // The bug-report template asks people to paste this, so it should
      // be worth pasting: what this build can do, not just its number.
      println!("duck-sqllsp {}", env!("CARGO_PKG_VERSION"));
      println!();

      let mut by_sev: std::collections::BTreeMap<&str, usize> = Default::default();
      for rule in dsl_analysis::rules::all() {
        let sev = match rule.default_severity() {
          dsl_analysis::Severity::Error => "error",
          dsl_analysis::Severity::Warning => "warning",
          dsl_analysis::Severity::Info => "info",
          dsl_analysis::Severity::Hint => "hint",
        };
        *by_sev.entry(sev).or_insert(0) += 1;
      }
      let total: usize = by_sev.values().sum();
      let breakdown = by_sev.iter().map(|(s, n)| format!("{n} {s}")).collect::<Vec<_>>().join(", ");

      println!("{:<12} postgresql, mysql, sqlite, mssql", "dialects");
      println!("{:<12} {total} ({breakdown})", "lint rules");
      println!("{:<12} libpg_query for postgres, sqlparser for the rest", "parser");
      match dsl_format::external::locate_binary() {
        Some(p) => println!("{:<12} {p}", "formatter"),
        None => println!("{:<12} sql-formatter not on PATH (alignment pass only)", "formatter"),
      }
      println!();
      println!("`duck-sqllsp doctor` checks this against a specific project.");
      Ok(())
    },
    Cmd::Rules { json, severity, search } => {
      let filter = severity.as_deref().map(|s| s.to_ascii_lowercase());
      let needle = search.as_deref().map(|s| s.to_ascii_lowercase());
      let mut rules: Vec<(String, &'static str)> = dsl_analysis::rules::all()
        .into_iter()
        .map(|r| {
          (
            r.code().to_string(),
            match r.default_severity() {
              dsl_analysis::Severity::Error => "error",
              dsl_analysis::Severity::Warning => "warning",
              dsl_analysis::Severity::Info => "info",
              dsl_analysis::Severity::Hint => "hint",
            },
          )
        })
        .filter(|(_, sev)| filter.as_deref().is_none_or(|f| *sev == f))
        .filter(|(code, _)| {
          needle.as_deref().is_none_or(|n| {
            code.to_ascii_lowercase().contains(n)
              || dsl_analysis::rules::title(code).is_some_and(|t| t.to_ascii_lowercase().contains(n))
          })
        })
        .collect();
      rules.sort_by(|a, b| a.0.cmp(&b.0));
      if json {
        print!("[");
        for (i, (code, sev)) in rules.iter().enumerate() {
          if i > 0 {
            print!(",");
          }
          let title = dsl_analysis::rules::title(code).unwrap_or_default();
          let escaped = title.replace('\\', "\\\\").replace('"', "\\\"");
          print!("{{\"code\":\"{code}\",\"default_severity\":\"{sev}\",\"title\":\"{escaped}\"}}");
        }
        println!("]");
        return Ok(());
      }
      let mut by_sev: std::collections::BTreeMap<&str, usize> = Default::default();
      println!("{:6}  {:8}  summary", "code", "severity");
      for (code, sev) in &rules {
        // A code with no summary means `titles.rs` is stale; print the
        // code alone rather than eliding the row.
        println!("{:6}  {:8}  {}", code, sev, dsl_analysis::rules::title(code).unwrap_or(""));
        *by_sev.entry(sev).or_insert(0) += 1;
      }
      if rules.is_empty() {
        println!("no rules matched");
        return Ok(());
      }
      println!();
      println!("total: {} rules", rules.len());
      for (sev, n) in by_sev {
        println!("  {sev}: {n}");
      }
      Ok(())
    },
    Cmd::Lint { files, format, warnings_as_errors, dialect } => {
      // Read the project config, so `lint` in CI behaves like the
      // server in the editor. Without this, `[duck_sqllsp.rules]`
      // severity overrides -- which the docs present as the way to
      // silence a rule -- applied only inside the editor, and a rule
      // silenced for the repository still failed the build.
      let cfg = files
        .iter()
        .find(|f| *f != "-")
        .map(std::path::Path::new)
        .and_then(dsl_server::config::load_project_config)
        .unwrap_or_default();
      let dialect = resolve_dialect(dialect, &files);
      let json = matches!(format.as_str(), "json");
      let mut error_count = 0usize;
      let mut warning_count = 0usize;
      if json {
        print!("[");
      }
      let mut json_first = true;
      let inputs: Vec<String> = if files.is_empty() { vec!["-".to_string()] } else { files };
      for path in &inputs {
        let source = if path == "-" {
          use std::io::Read;
          let mut buf = String::new();
          std::io::stdin().read_to_string(&mut buf).map_err(|e| {
            eprintln!("error reading stdin: {e}");
            anyhow::anyhow!("stdin read failed")
          })?;
          buf
        } else {
          match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) => {
              eprintln!("error reading {path}: {e}");
              std::process::exit(2);
            },
          }
        };
        let parsed = dsl_parse::parse(&source, dialect);
        let scopes = dsl_resolve::resolve_with_source(&parsed.statements, &source);
        let mut catalog = dsl_completion::source_tables::from_source(&parsed, &source);
        // Enrich offline catalog with sibling *.sql files in the same
        // directory so cross-file references (a trigger in
        // triggers.sql calling a function in functions.sql) resolve.
        if path != "-"
          && let Some(parent) = std::path::Path::new(path).parent()
          && let Ok(rd) = std::fs::read_dir(parent)
        {
          for entry in rd.flatten() {
            let p = entry.path();
            if p.as_os_str() == std::ffi::OsStr::new(path) {
              continue;
            }
            let Some(ext) = p.extension().and_then(|s| s.to_str()) else { continue };
            if !matches!(ext.to_ascii_lowercase().as_str(), "sql" | "pgsql" | "psql") {
              continue;
            }
            let Ok(meta) = std::fs::metadata(&p) else { continue };
            if meta.len() > 4 * 1024 * 1024 {
              continue;
            }
            let Ok(text) = std::fs::read_to_string(&p) else { continue };
            let other = dsl_parse::parse(&text, dialect);
            let derived = dsl_completion::source_tables::from_source(&other, &text);
            catalog = dsl_completion::source_tables::merge(&catalog, &derived);
          }
        }
        let raw = dsl_analysis::run_with_dialect(&source, &parsed, &scopes, &catalog, dialect);
        // Apply `[duck_sqllsp.rules]` overrides, exactly as the server
        // does -- including dropping a rule set to off/ignore/none, so
        // a silenced rule cannot fail the build either.
        let diags: Vec<dsl_analysis::Diagnostic> = raw
          .into_iter()
          .filter_map(|mut d| {
            let Some(over) = cfg.rules.get(d.code) else { return Some(d) };
            d.severity = match over.to_ascii_lowercase().as_str() {
              "off" | "ignore" | "none" => return None,
              "error" => dsl_analysis::Severity::Error,
              "warning" | "warn" => dsl_analysis::Severity::Warning,
              "info" | "information" => dsl_analysis::Severity::Info,
              "hint" => dsl_analysis::Severity::Hint,
              _ => d.severity,
            };
            Some(d)
          })
          .collect();
        for d in &diags {
          let sev_str = match d.severity {
            dsl_analysis::Severity::Error => {
              error_count += 1;
              "error"
            },
            dsl_analysis::Severity::Warning => {
              warning_count += 1;
              "warning"
            },
            dsl_analysis::Severity::Info => "info",
            dsl_analysis::Severity::Hint => "hint",
          };
          let s: u32 = d.range.start().into();
          let e: u32 = d.range.end().into();
          let (line, col) = byte_to_line_col(&source, s as usize);
          if json {
            if !json_first {
              print!(",");
            }
            json_first = false;
            let msg_esc = d.message.replace('\\', "\\\\").replace('"', "\\\"");
            print!(
              "{{\"file\":\"{}\",\"line\":{},\"col\":{},\"start\":{},\"end\":{},\"severity\":\"{}\",\"code\":\"{}\",\"message\":\"{}\"}}",
              path,
              line + 1,
              col + 1,
              s,
              e,
              sev_str,
              d.code,
              msg_esc,
            );
          } else {
            println!("{path}:{}:{}: {sev_str} [{code}] {msg}", line + 1, col + 1, code = d.code, msg = d.message);
          }
        }
      }
      if json {
        println!("]");
      }
      if error_count > 0 || (warnings_as_errors && warning_count > 0) {
        std::process::exit(1);
      }
      Ok(())
    },
    Cmd::Format { files, stdout, language } => {
      let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
      let proj = dsl_server::config::load_project_config(&cwd).unwrap_or_default();
      let mut style = proj.style.formatter.clone();
      if language != "postgresql" || style.language.is_empty() {
        style.language = language;
      }
      let ct_style = proj.style.create_table.clone();
      let inputs: Vec<String> = if files.is_empty() { vec!["-".to_string()] } else { files };
      for path in &inputs {
        let original = if path == "-" {
          use std::io::Read;
          let mut buf = String::new();
          std::io::stdin().read_to_string(&mut buf).map_err(|e| anyhow::anyhow!("stdin: {e}"))?;
          buf
        } else {
          match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) => {
              eprintln!("error reading {path}: {e}");
              std::process::exit(2);
            },
          }
        };
        let formatted = dsl_format::format(&original, &style, &ct_style);
        if stdout || path == "-" {
          print!("{formatted}");
        } else if formatted != original
          && let Err(e) = std::fs::write(path, formatted)
        {
          eprintln!("error writing {path}: {e}");
          std::process::exit(2);
        }
      }
      Ok(())
    },
    Cmd::Introspect { files, url, dialect } => {
      if let Some(url) = url {
        // Live DB introspection: build driver, introspect, JSON-dump.
        let spec = dsl_conn::ConnectionSpec { name: "cli".into(), url };
        let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
          Ok(rt) => rt,
          Err(e) => {
            eprintln!("error: failed to build tokio runtime: {e}");
            std::process::exit(2);
          },
        };
        let cat = rt.block_on(async move {
          let driver = dsl_conn::build(&spec).map_err(|e| format!("build driver: {e}"))?;
          driver.introspect().await.map_err(|e| format!("introspect: {e}"))
        });
        match cat {
          Ok(c) => {
            println!("{}", serde_json::to_string_pretty(&c).map_err(|e| anyhow::anyhow!("json: {e}"))?);
            return Ok(());
          },
          Err(e) => {
            eprintln!("error: {e}");
            std::process::exit(2);
          },
        }
      }
      // Offline catalog: parse every file + merge derived catalogs.
      let mut acc = dsl_catalog::Catalog {
        version: dsl_catalog::CATALOG_VERSION,
        connection_id: "<cli-introspect>".into(),
        schemas: Vec::new(),
        functions: Vec::new(),
        types: Vec::new(),
        roles: Vec::new(),
        sequences: Vec::new(),
        extensions: Vec::new(),
      };
      let dialect = resolve_dialect(dialect, &files);
      for path in &files {
        let Ok(source) = std::fs::read_to_string(path) else {
          eprintln!("error reading {path}");
          std::process::exit(2);
        };
        let parsed = dsl_parse::parse(&source, dialect);
        let derived = dsl_completion::source_tables::from_source(&parsed, &source);
        acc = dsl_completion::source_tables::merge(&acc, &derived);
      }
      println!("{}", serde_json::to_string_pretty(&acc).map_err(|e| anyhow::anyhow!("json: {e}"))?);
      Ok(())
    },
  }
}

/// The dialect to parse in: the flag, else the project config, else postgres.
///
/// Shared by `lint` and `introspect` so the two cannot disagree about what a
/// file is. Exits 2 on a name that is not a dialect, rather than silently
/// falling back to postgres and reporting a file full of syntax errors.
fn resolve_dialect(explicit: Option<String>, files: &[String]) -> dsl_parse::Dialect {
  let cfg = files
    .iter()
    .find(|f| *f != "-")
    .map(std::path::Path::new)
    .and_then(dsl_server::config::load_project_config)
    .unwrap_or_default();

  let name = explicit.unwrap_or_else(|| match cfg.effective_dialect() {
    dsl_server::config::Dialect::Postgresql => "postgres".into(),
    dsl_server::config::Dialect::Mysql => "mysql".into(),
    dsl_server::config::Dialect::Sqlite => "sqlite".into(),
    dsl_server::config::Dialect::Mssql => "mssql".into(),
  });

  match name.to_ascii_lowercase().as_str() {
    "postgres" | "postgresql" | "pg" => dsl_parse::Dialect::Postgres,
    "mysql" | "mariadb" => dsl_parse::Dialect::MySql,
    "sqlite" => dsl_parse::Dialect::SQLite,
    "mssql" | "tsql" | "sqlserver" => dsl_parse::Dialect::MsSql,
    "generic" => dsl_parse::Dialect::Generic,
    other => {
      eprintln!("error: unknown dialect '{other}'; valid: postgres, mysql, sqlite, mssql, generic");
      std::process::exit(2);
    },
  }
}

fn byte_to_line_col(src: &str, off: usize) -> (usize, usize) {
  let mut line = 0usize;
  let mut col = 0usize;
  for (i, b) in src.bytes().enumerate() {
    if i >= off {
      break;
    }
    if b == b'\n' {
      line += 1;
      col = 0
    } else {
      col += 1
    }
  }
  (line, col)
}

fn init_tracing() {
  // Log to stderr so stdout stays clean for JSON-RPC.
  //
  // Default level is `warn`: anything noisier (INFO/DEBUG/TRACE) shows
  // up in nvim's lsp.log as an `[ERROR][... rpc ... stderr ...]` line
  // because nvim wraps any stderr output that way, regardless of the
  // actual record level. Per-handler INFO spam was creating thousands
  // of fake-error lines per session. Set DUCK_SQLLSP_LOG=info or =debug
  // to opt back in.
  use tracing_subscriber::EnvFilter;
  let _ = tracing_subscriber::fmt()
    .with_env_filter(EnvFilter::try_from_env("DUCK_SQLLSP_LOG").unwrap_or_else(|_| EnvFilter::new("warn")))
    .with_writer(std::io::stderr)
    .with_ansi(false)
    .try_init();
}