Skip to main content

dsl_parse/backend/pg_query/
mod.rs

1//! pg_query backend.
2//!
3//! Uses libpg_query (the real Postgres parser, exposed via FFI) so we
4//! get 100% PG syntax coverage including features that sqlparser-rs
5//! doesn't yet support (`ON DELETE SET NULL (col)`, MERGE, FETCH FIRST,
6//! lateral derived tables, ...). The conversion is intentionally
7//! lossy -- we only extract the slots the rest of the workspace cares
8//! about (CREATE TABLE columns, FROM tables, projections, WHERE, etc).
9//! Anything richer than that lands in `StatementKind::Unknown { text }`
10//! so downstream features still see the raw SQL.
11
12mod convert;
13
14use crate::ast::{Statement, StatementKind};
15use crate::dialect::Dialect;
16use crate::error::ParseError;
17use crate::parsed_file::ParsedFile;
18use crate::split::split_statements;
19
20pub fn parse(source: &str, _dialect: Dialect) -> ParsedFile {
21  let mut statements = Vec::new();
22  let mut errors = Vec::new();
23
24  for (chunk, range) in split_statements(source) {
25    match pg_query::parse(&chunk) {
26      Ok(result) => {
27        let chunk_owned = chunk.clone();
28        // pg_query reports cref.location etc relative to the chunk
29        // we parse. Track the chunk's start byte in the source so we
30        // can convert any chunk-local offsets into source offsets.
31        let mut emitted = false;
32        for raw in &result.protobuf.stmts {
33          if let Some(stmt_node) = raw.stmt.as_ref().and_then(|s| s.node.as_ref()) {
34            emitted = true;
35            let mut kind = convert::statement(stmt_node, &chunk_owned);
36            offset_ranges_in_kind(&mut kind, u32::from(range.start()));
37            statements.push(Statement { range, kind });
38          }
39        }
40        if !emitted {
41          // Empty parse (whitespace / comments only).
42          statements.push(Statement { range, kind: StatementKind::Unknown { text: chunk_owned } });
43        }
44      },
45      Err(e) => {
46        errors.push(ParseError { range, message: format!("pg_query: {e}") });
47        statements.push(Statement { range, kind: StatementKind::Unknown { text: chunk } });
48      },
49    }
50  }
51
52  ParsedFile { statements, errors }
53}
54
55/// Walk every range field inside the parsed AST and add `offset` so the
56/// chunk-relative byte positions emitted by pg_query become absolute
57/// positions in the source buffer. Without this, diagnostics for a
58/// column reference in the N-th statement display the line/column of
59/// the very first chunk (off by `range.start()` bytes).
60fn offset_ranges_in_kind(kind: &mut StatementKind, offset: u32) {
61  use crate::ast::{Expr, Projection};
62  fn fix_expr(e: &mut Expr, off: u32) {
63    match e {
64      Expr::Column { range, .. } if u32::from(range.len()) > 0 => {
65        let s = u32::from(range.start()) + off;
66        let en = u32::from(range.end()) + off;
67        *range = text_size::TextRange::new(s.into(), en.into());
68      },
69      Expr::BinaryOp { left, right, .. } => {
70        fix_expr(left, off);
71        fix_expr(right, off);
72      },
73      Expr::Call { args, .. } => {
74        for a in args {
75          fix_expr(a, off);
76        }
77      },
78      _ => {},
79    }
80  }
81  fn fix_select(s: &mut crate::ast::SelectStmt, off: u32) {
82    for p in &mut s.projections {
83      if let Projection::Expr { expr, .. } = p {
84        fix_expr(expr, off);
85      }
86    }
87    if let Some(w) = &mut s.where_clause {
88      fix_expr(w, off);
89    }
90    for j in &mut s.joins {
91      if let Some(on) = &mut j.on {
92        fix_expr(on, off);
93      }
94    }
95  }
96  match kind {
97    StatementKind::Select(s) => fix_select(s, offset),
98    StatementKind::Update(u) => {
99      if let Some(w) = &mut u.where_clause {
100        fix_expr(w, offset);
101      }
102      for (_t, e) in &mut u.assignments {
103        fix_expr(e, offset);
104      }
105    },
106    StatementKind::Delete(d) => {
107      if let Some(w) = &mut d.where_clause {
108        fix_expr(w, offset);
109      }
110    },
111    _ => {},
112  }
113}