Skip to main content

dsl_parse/
plpgsql.rs

1//! PL/pgSQL function body parser.
2//!
3//! Wraps `pg_query::parse_plpgsql` (libpg_query FFI). Returns a typed
4//! `PlpgsqlBody` so downstream rules can walk the statement list
5//! without re-parsing the JSON. Falls back to `Err` on parse failure
6//! or when the `pg_query_backend` feature is off -- callers must be
7//! tolerant of that.
8//!
9//! The JSON shape libpg_query emits is documented in
10//! `pl_funcs.c::dump_block`; we mirror the subset most rules care
11//! about (statement kind + line + body-relative byte offset) and
12//! drop the rest into `raw` for opaque inspection.
13
14/// One statement inside a PL/pgSQL function body.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct PlpgsqlStmt {
17  pub kind: PlpgsqlStmtKind,
18  /// 1-based source line where the statement starts. None when
19  /// libpg_query didn't emit a location.
20  pub lineno: Option<u32>,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum PlpgsqlStmtKind {
25  Block,
26  Assign,
27  If,
28  Case,
29  Loop,
30  While,
31  For,
32  ForEach,
33  Exit,
34  Return,
35  ReturnNext,
36  ReturnQuery,
37  Raise,
38  Assert,
39  Perform,
40  ExecSql,
41  ExecuteSql,
42  GetDiag,
43  Open,
44  Fetch,
45  Close,
46  Commit,
47  Rollback,
48  Call,
49  Other(String),
50}
51
52#[derive(Debug, Clone, Default)]
53pub struct PlpgsqlBody {
54  pub statements: Vec<PlpgsqlStmt>,
55}
56
57/// Parse a `CREATE FUNCTION ... LANGUAGE plpgsql AS $$ ... $$` body.
58/// Pass the full CREATE FUNCTION text -- libpg_query expects the
59/// surrounding DDL because the function header drives parameter +
60/// return-type wiring.
61#[cfg(feature = "pg_query_backend")]
62pub fn parse(create_function_text: &str) -> Result<PlpgsqlBody, String> {
63  let json = pg_query::parse_plpgsql(create_function_text).map_err(|e| e.to_string())?;
64  Ok(walk_top(&json))
65}
66
67#[cfg(not(feature = "pg_query_backend"))]
68pub fn parse(_: &str) -> Result<PlpgsqlBody, String> {
69  Err("pg_query_backend feature is disabled -- rebuild with default-features".to_string())
70}
71
72#[cfg(feature = "pg_query_backend")]
73fn walk_top(value: &serde_json::Value) -> PlpgsqlBody {
74  let mut out = PlpgsqlBody::default();
75  // Top level is an array of function objects: [{"PLpgSQL_function": { action: {...} }}]
76  let Some(arr) = value.as_array() else { return out };
77  for func in arr {
78    let Some(action) = func.get("PLpgSQL_function").and_then(|f| f.get("action")) else { continue };
79    walk_stmt(action, &mut out.statements);
80  }
81  out
82}
83
84#[cfg(feature = "pg_query_backend")]
85fn walk_stmt(node: &serde_json::Value, out: &mut Vec<PlpgsqlStmt>) {
86  let Some(obj) = node.as_object() else { return };
87  // Each wrapper has exactly one key naming the stmt kind.
88  for (kind_key, body) in obj {
89    let kind = classify(kind_key);
90    let lineno = body.get("lineno").and_then(|n| n.as_u64()).map(|n| n as u32);
91    out.push(PlpgsqlStmt { kind: kind.clone(), lineno });
92    // Recurse into structural children that hold nested statements.
93    if let Some(b) = body.get("body").and_then(|b| b.as_array()) {
94      for child in b {
95        walk_stmt(child, out);
96      }
97    }
98    if let Some(b) = body.get("then_body").and_then(|b| b.as_array()) {
99      for child in b {
100        walk_stmt(child, out);
101      }
102    }
103    if let Some(b) = body.get("else_body").and_then(|b| b.as_array()) {
104      for child in b {
105        walk_stmt(child, out);
106      }
107    }
108    if let Some(arms) = body.get("elsif_list").and_then(|a| a.as_array()) {
109      for arm in arms {
110        if let Some(stmts) = arm.get("stmts").and_then(|s| s.as_array()) {
111          for child in stmts {
112            walk_stmt(child, out);
113          }
114        }
115      }
116    }
117    if let Some(arms) = body.get("case_when_list").and_then(|a| a.as_array()) {
118      for arm in arms {
119        if let Some(stmts) = arm.get("stmts").and_then(|s| s.as_array()) {
120          for child in stmts {
121            walk_stmt(child, out);
122          }
123        }
124      }
125    }
126    if let Some(handlers) = body
127      .get("exceptions")
128      .and_then(|e| e.get("PLpgSQL_exception_block"))
129      .and_then(|b| b.get("exc_list"))
130      .and_then(|l| l.as_array())
131    {
132      for handler in handlers {
133        let Some(exc) = handler.get("PLpgSQL_exception") else { continue };
134        if let Some(stmts) = exc.get("action").and_then(|s| s.as_array()) {
135          for child in stmts {
136            walk_stmt(child, out);
137          }
138        }
139      }
140    }
141  }
142}
143
144#[cfg(feature = "pg_query_backend")]
145fn classify(key: &str) -> PlpgsqlStmtKind {
146  match key {
147    "PLpgSQL_stmt_block" => PlpgsqlStmtKind::Block,
148    "PLpgSQL_stmt_assign" => PlpgsqlStmtKind::Assign,
149    "PLpgSQL_stmt_if" => PlpgsqlStmtKind::If,
150    "PLpgSQL_stmt_case" => PlpgsqlStmtKind::Case,
151    "PLpgSQL_stmt_loop" => PlpgsqlStmtKind::Loop,
152    "PLpgSQL_stmt_while" => PlpgsqlStmtKind::While,
153    "PLpgSQL_stmt_fors" | "PLpgSQL_stmt_fori" | "PLpgSQL_stmt_forq" => PlpgsqlStmtKind::For,
154    "PLpgSQL_stmt_foreach_a" => PlpgsqlStmtKind::ForEach,
155    "PLpgSQL_stmt_exit" => PlpgsqlStmtKind::Exit,
156    "PLpgSQL_stmt_return" => PlpgsqlStmtKind::Return,
157    "PLpgSQL_stmt_return_next" => PlpgsqlStmtKind::ReturnNext,
158    "PLpgSQL_stmt_return_query" => PlpgsqlStmtKind::ReturnQuery,
159    "PLpgSQL_stmt_raise" => PlpgsqlStmtKind::Raise,
160    "PLpgSQL_stmt_assert" => PlpgsqlStmtKind::Assert,
161    "PLpgSQL_stmt_perform" => PlpgsqlStmtKind::Perform,
162    "PLpgSQL_stmt_execsql" => PlpgsqlStmtKind::ExecSql,
163    "PLpgSQL_stmt_dynexecute" => PlpgsqlStmtKind::ExecuteSql,
164    "PLpgSQL_stmt_getdiag" => PlpgsqlStmtKind::GetDiag,
165    "PLpgSQL_stmt_open" => PlpgsqlStmtKind::Open,
166    "PLpgSQL_stmt_fetch" => PlpgsqlStmtKind::Fetch,
167    "PLpgSQL_stmt_close" => PlpgsqlStmtKind::Close,
168    "PLpgSQL_stmt_commit" => PlpgsqlStmtKind::Commit,
169    "PLpgSQL_stmt_rollback" => PlpgsqlStmtKind::Rollback,
170    "PLpgSQL_stmt_call" => PlpgsqlStmtKind::Call,
171    other => PlpgsqlStmtKind::Other(other.to_string()),
172  }
173}
174
175#[cfg(test)]
176#[cfg(feature = "pg_query_backend")]
177mod tests {
178  use super::*;
179
180  fn has(body: &PlpgsqlBody, k: PlpgsqlStmtKind) -> bool {
181    body.statements.iter().any(|s| s.kind == k)
182  }
183
184  fn count_of(body: &PlpgsqlBody, k: PlpgsqlStmtKind) -> usize {
185    body.statements.iter().filter(|s| s.kind == k).count()
186  }
187
188  #[test]
189  fn parses_trivial_body() {
190    let body = parse(
191      "CREATE FUNCTION f() RETURNS int AS $$
192       BEGIN
193         RETURN 42;
194       END $$ LANGUAGE plpgsql;",
195    )
196    .expect("parse");
197    assert!(has(&body, PlpgsqlStmtKind::Block));
198    assert!(has(&body, PlpgsqlStmtKind::Return));
199  }
200
201  #[test]
202  fn walks_nested_if_branches() {
203    let body = parse(
204      "CREATE FUNCTION g(x int) RETURNS int AS $$
205       BEGIN
206         IF x > 0 THEN
207           RAISE NOTICE 'pos';
208         ELSE
209           RAISE EXCEPTION 'neg';
210         END IF;
211         RETURN x;
212       END $$ LANGUAGE plpgsql;",
213    )
214    .expect("parse");
215    assert_eq!(count_of(&body, PlpgsqlStmtKind::Raise), 2, "both RAISE arms must be visited");
216    assert!(has(&body, PlpgsqlStmtKind::If));
217  }
218
219  #[test]
220  fn captures_loop_body() {
221    let body = parse(
222      "CREATE FUNCTION h() RETURNS int AS $$
223       DECLARE i int := 0;
224       BEGIN
225         LOOP
226           i := i + 1;
227           EXIT WHEN i > 3;
228         END LOOP;
229         RETURN i;
230       END $$ LANGUAGE plpgsql;",
231    )
232    .expect("parse");
233    assert!(has(&body, PlpgsqlStmtKind::Loop));
234    assert!(has(&body, PlpgsqlStmtKind::Assign));
235    assert!(has(&body, PlpgsqlStmtKind::Exit));
236  }
237
238  #[test]
239  fn captures_exception_handlers() {
240    let body = parse(
241      "CREATE FUNCTION e() RETURNS void AS $$
242       BEGIN
243         RAISE EXCEPTION 'boom';
244       EXCEPTION WHEN OTHERS THEN
245         RAISE NOTICE 'caught';
246       END $$ LANGUAGE plpgsql;",
247    )
248    .expect("parse");
249    let raise_count = body.statements.iter().filter(|s| s.kind == PlpgsqlStmtKind::Raise).count();
250    assert_eq!(raise_count, 2, "main + handler RAISE must both appear");
251  }
252}