quill_sql/sql/parser/
mod.rs

1use crate::error::QuillSQLResult;
2use sqlparser::{
3    ast::{Statement, TransactionMode},
4    dialect::PostgreSqlDialect,
5    parser::Parser,
6};
7
8pub fn parse_sql(sql: &str) -> QuillSQLResult<Vec<Statement>> {
9    // Lightweight rewrite for unsupported SHOW syntax under Postgres dialect
10    // Maps to information_schema queries to keep planner/executor simple.
11    let normalized = sql.trim().trim_end_matches(';').trim();
12    let lower = normalized.to_ascii_lowercase();
13
14    let rewritten = if lower == "show databases" || lower == "show database" {
15        // List schemas (databases) from information_schema.schemas
16        Some("select schema from information_schema.schemas".to_string())
17    } else if lower == "show tables" {
18        // List all tables
19        Some("select table_name from information_schema.tables".to_string())
20    } else if lower.starts_with("set transaction") {
21        let rest = normalized["set transaction".len()..].trim_start();
22        Some(format!("SET TRANSACTION {}", rest))
23    } else if lower.starts_with("set session transaction") {
24        let rest = normalized["set session transaction".len()..].trim_start();
25        Some(format!(
26            "SET SESSION CHARACTERISTICS AS TRANSACTION {}",
27            rest
28        ))
29    } else {
30        None
31    };
32
33    let sql_to_parse = rewritten.as_deref().unwrap_or(normalized);
34    let stmts = Parser::parse_sql(&PostgreSqlDialect {}, sql_to_parse)?;
35    for stmt in &stmts {
36        match stmt {
37            Statement::StartTransaction { .. }
38            | Statement::Commit { .. }
39            | Statement::Rollback { .. }
40            | Statement::SetTransaction { .. } => {}
41            _ => {}
42        }
43    }
44    Ok(stmts)
45}
46
47#[cfg(test)]
48mod tests {
49
50    #[test]
51    pub fn test_parser() {
52        let sql = "select * from (select * from t1)";
53        let stmts = super::parse_sql(sql).unwrap();
54        println!("{:#?}", stmts[0]);
55    }
56}