Skip to main content

dsl_parse/
lib.rs

1//! SQL parser facade for duck-sqllsp.
2//!
3//! Wraps existing battle-tested SQL parsers (currently [`sqlparser`], with
4//! `pg_query` planned behind a feature flag) and normalises their output
5//! into a single small AST. Every downstream crate in this workspace
6//! depends only on this internal AST, so changing parser backends is a
7//! one-crate diff.
8//!
9//! Public surface:
10//!   - [`parse`] -- top-level entry point.
11//!   - [`Dialect`] -- which SQL flavour to use.
12//!   - The AST types in [`ast`] -- `Statement`, `SelectStmt`, etc.
13//!   - [`ParsedFile`], [`ParseError`] -- result envelopes.
14
15pub mod ast;
16pub mod dialect;
17pub mod error;
18pub mod parsed_file;
19pub mod plpgsql;
20pub mod split;
21
22pub mod backend;
23
24pub use ast::*;
25pub use dialect::Dialect;
26pub use error::ParseError;
27pub use parsed_file::ParsedFile;
28
29/// Parse a whole SQL document. Always succeeds; per-statement errors are
30/// collected into [`ParsedFile::errors`].
31///
32/// Backend dispatch:
33///   - `Dialect::Postgres` -- uses the libpg_query backend when compiled
34///     in (matches real PG semantics), otherwise the sqlparser-rs
35///     PostgreSqlDialect.
36///   - `Dialect::MySql` / `Dialect::SQLite` / `Dialect::Generic` -- always
37///     uses sqlparser-rs with the matching dialect. libpg_query is
38///     PG-only and would mis-parse these.
39pub fn parse(source: &str, dialect: Dialect) -> ParsedFile {
40  // Non-PG dialects always go through sqlparser-rs.
41  if !matches!(dialect, Dialect::Postgres) {
42    #[cfg(feature = "sqlparser")]
43    {
44      return backend::sqlparser::parse(source, dialect);
45    }
46    #[cfg(not(feature = "sqlparser"))]
47    {
48      let range = text_size::TextRange::up_to(text_size::TextSize::of(source));
49      return ParsedFile {
50        statements: vec![Statement { range, kind: StatementKind::Unknown { text: source.to_string() } }],
51        errors: vec![ParseError { range, message: format!("sqlparser backend disabled; cannot parse {:?}", dialect) }],
52      };
53    }
54  }
55  // Postgres path.
56  #[cfg(feature = "pg_query_backend")]
57  {
58    backend::pg_query::parse(source, dialect)
59  }
60  #[cfg(all(not(feature = "pg_query_backend"), feature = "sqlparser"))]
61  {
62    return backend::sqlparser::parse(source, dialect);
63  }
64  #[cfg(all(not(feature = "pg_query_backend"), not(feature = "sqlparser")))]
65  {
66    let range = text_size::TextRange::up_to(text_size::TextSize::of(source));
67    ParsedFile {
68      statements: vec![Statement { range, kind: StatementKind::Unknown { text: source.to_string() } }],
69      errors: vec![ParseError { range, message: "no parser backend enabled".into() }],
70    }
71  }
72}