Skip to main content

uqa_sql/compiler/
dispatch.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Parser entry point and exhaustive statement-family dispatch.
8
9use super::administrative::{
10    compile_analyze, compile_explain, compile_set_constraints, compile_transaction,
11    compile_truncate, compile_variable_set, discard_target,
12};
13use super::cursors::{compile_close_cursor, compile_declare_cursor, compile_fetch_cursor};
14use super::dml::{compile_delete, compile_update};
15use super::drop_alter::{compile_alter_table, compile_drop, compile_rename};
16use super::events::{compile_create_rule, compile_create_trigger};
17use super::merge::compile_merge;
18use super::relations::{
19    compile_create_foreign_server, compile_create_schema, compile_create_table_as,
20    compile_create_view, compile_deallocate, compile_execute, compile_prepare,
21    compile_refresh_materialized_view, compile_top_level_select, defer_create_foreign_table,
22    defer_create_table,
23};
24use super::routines::{
25    compile_alter_role, compile_alter_routine, compile_alter_routine_owner, compile_call,
26    compile_create_function, compile_create_role, compile_do, compile_drop_role, compile_grant,
27    compile_grant_role,
28};
29use super::schema_moves::compile_alter_object_schema;
30use super::sequences::{compile_alter_sequence, compile_create_sequence};
31use super::type_lifecycle;
32use super::{
33    compile_create_index, compile_create_table, compile_insert, compile_values_lists, Node,
34    NodeEnum, Result, SQLError, Statement,
35};
36use pg_query::protobuf::SelectStmt;
37
38mod production;
39pub use production::parse_statements_with_control;
40
41/// A syntactically valid statement retaining its exact source slice. Compilation is separate so an execution boundary can analyze statements in order after preceding commands have completed.
42#[derive(Debug, Clone)]
43pub struct ParsedStatement<'sql> {
44    sql: &'sql str,
45    message: &'sql str,
46    positions: std::sync::Arc<super::source_positions::SourcePositions>,
47    node: Box<Node>,
48    settings: crate::parser::ParserSettings,
49}
50
51impl<'sql> ParsedStatement<'sql> {
52    /// Original SQL, without reconstructing or rewriting the parser tree.
53    pub const fn sql(&self) -> &'sql str {
54        self.sql
55    }
56
57    /// Identify a direct LISTEN or UNLISTEN without semantic compilation or inspecting strings and routine bodies. Nested commands must still be checked when executed.
58    pub fn is_notification_listener_command(&self) -> bool {
59        matches!(
60            self.node.node.as_ref(),
61            Some(NodeEnum::ListenStmt(_) | NodeEnum::UnlistenStmt(_))
62        )
63    }
64
65    /// Compile this statement into the engine's internal SQL representation.
66    pub fn compile(&self) -> Result<Statement> {
67        crate::parser::with_settings(self.settings, || {
68            let mut statement = super::source_positions::with_source(
69                std::sync::Arc::clone(&self.positions),
70                || compile_stmt(&self.node),
71            )?;
72            if let Statement::CreateFunction(definition) = &mut statement {
73                if let crate::ast::FunctionBody::Source(body) = &definition.body {
74                    definition.body_origin =
75                        crate::ast::RoutineBodyOrigin::capture(body, self.message);
76                }
77            }
78            if let Statement::CreateForeignServer(server) = &mut statement {
79                super::foreign_servers::retain_string_presence(self.sql, server)?;
80            }
81            Ok(statement)
82        })
83        .0
84    }
85}
86
87/// Parse an entire SQL message before exposing any statement for execution. `PostgreSQL` syntax errors reject the whole message; semantic compilation errors can be surfaced later, at the affected statement's boundary.
88pub fn parse_statements(sql: &str) -> Result<Vec<ParsedStatement<'_>>> {
89    parse_statements_with_control(sql, &uqa_core::memory::ProductionControl::uncontrolled()).map(
90        |statements| {
91            statements
92                .into_uncontrolled()
93                .expect("ordinary parsed statements")
94        },
95    )
96}
97
98pub fn compile(sql: &str) -> Result<Vec<Statement>> {
99    parse_statements(sql)?
100        .iter()
101        .map(ParsedStatement::compile)
102        .collect()
103}
104
105pub fn resolve_deferred_create_table(
106    deferred: &crate::ast::DeferredCreateTable,
107) -> Result<crate::ast::CreateTable> {
108    let parsed = crate::parser::parse(&deferred.definition_sql)?;
109    let [raw] = parsed.protobuf.stmts.as_slice() else {
110        return Err(SQLError::Internal(
111            "deferred CREATE TABLE did not contain exactly one statement".into(),
112        ));
113    };
114    let node = raw
115        .stmt
116        .as_deref()
117        .and_then(|node| node.node.as_ref())
118        .ok_or_else(|| SQLError::Internal("deferred CREATE TABLE is empty".into()))?;
119    let NodeEnum::CreateStmt(stmt) = node else {
120        return Err(SQLError::Internal(
121            "deferred CREATE TABLE changed statement kind".into(),
122        ));
123    };
124    let table = compile_create_table(stmt)?;
125    if !table.if_not_exists
126        || table.name != deferred.name
127        || table.persistence != deferred.persistence
128    {
129        return Err(SQLError::Internal(
130            "deferred CREATE TABLE changed target identity".into(),
131        ));
132    }
133    Ok(table)
134}
135
136fn compile_create_table_statement(statement: &pg_query::protobuf::CreateStmt) -> Result<Statement> {
137    if statement.if_not_exists {
138        defer_create_table(statement).map(Statement::CreateTableIfNotExists)
139    } else {
140        compile_create_table(statement).map(Statement::CreateTable)
141    }
142}
143
144fn compile_create_foreign_table_statement(
145    statement: &pg_query::protobuf::CreateForeignTableStmt,
146) -> Result<Statement> {
147    defer_create_foreign_table(statement).map(Statement::CreateForeignTableDefinition)
148}
149
150/// `ALTER TYPE | DOMAIN ... RENAME` changes a type object; other `RENAME` forms change relations, columns, constraints and routines.
151fn compile_rename_statement(statement: &pg_query::protobuf::RenameStmt) -> Result<Statement> {
152    match type_lifecycle::type_object_kind(statement.rename_type()) {
153        Some(kind) => type_lifecycle::compile_type_rename(statement, kind),
154        None => compile_rename(statement),
155    }
156}
157
158fn compile_alter_object_schema_statement(
159    statement: &pg_query::protobuf::AlterObjectSchemaStmt,
160) -> Result<Statement> {
161    match type_lifecycle::type_object_kind(statement.object_type()) {
162        Some(kind) => type_lifecycle::compile_type_set_schema(statement, kind),
163        None => compile_alter_object_schema(statement),
164    }
165}
166
167fn compile_alter_owner_statement(
168    statement: &pg_query::protobuf::AlterOwnerStmt,
169) -> Result<Statement> {
170    match type_lifecycle::type_object_kind(statement.object_type()) {
171        Some(kind) => type_lifecycle::compile_type_owner(statement, kind),
172        None => compile_alter_routine_owner(statement),
173    }
174}
175
176fn compile_grant_statement(statement: &pg_query::protobuf::GrantStmt) -> Result<Statement> {
177    match type_lifecycle::type_object_kind(statement.objtype()) {
178        Some(kind) => type_lifecycle::compile_grant_type(statement, kind),
179        None => compile_grant(statement),
180    }
181}
182
183pub(super) fn compile_stmt(node: &Node) -> Result<Statement> {
184    let Some(inner) = node.node.as_ref() else {
185        return Err(SQLError::Unsupported("empty statement".into()));
186    };
187    match inner {
188        NodeEnum::CreateStmt(stmt) => compile_create_table_statement(stmt),
189        NodeEnum::IndexStmt(stmt) => compile_create_index(stmt).map(Statement::CreateIndex),
190        NodeEnum::InsertStmt(stmt) => compile_insert(stmt).map(Statement::Insert),
191        NodeEnum::SelectStmt(stmt) => compile_select_statement(stmt),
192        NodeEnum::UpdateStmt(stmt) => compile_update(stmt).map(Statement::Update),
193        NodeEnum::DeleteStmt(stmt) => compile_delete(stmt).map(Statement::Delete),
194        NodeEnum::DropStmt(stmt) => compile_drop(stmt),
195        NodeEnum::CreateTrigStmt(stmt) => {
196            compile_create_trigger(stmt).map(Statement::CreateTrigger)
197        }
198        NodeEnum::RuleStmt(stmt) => compile_create_rule(stmt).map(Statement::CreateRule),
199        NodeEnum::AlterTableStmt(stmt) => compile_alter_table(stmt),
200        NodeEnum::RenameStmt(stmt) => compile_rename_statement(stmt),
201        NodeEnum::AlterObjectSchemaStmt(stmt) => compile_alter_object_schema_statement(stmt),
202        NodeEnum::ViewStmt(stmt) => compile_create_view(stmt),
203        NodeEnum::CreateSchemaStmt(stmt) => compile_create_schema(stmt),
204        NodeEnum::NotifyStmt(stmt) => Ok(Statement::Notify {
205            channel: stmt.conditionname.clone(),
206            payload: stmt.payload.clone(),
207        }),
208        NodeEnum::ListenStmt(stmt) => Ok(Statement::Listen {
209            channel: stmt.conditionname.clone(),
210        }),
211        NodeEnum::UnlistenStmt(stmt) => Ok(Statement::Unlisten {
212            channel: (!stmt.conditionname.is_empty()).then(|| stmt.conditionname.clone()),
213        }),
214        NodeEnum::ExplainStmt(stmt) => compile_explain(stmt),
215        NodeEnum::VacuumStmt(stmt) => compile_analyze(stmt),
216        NodeEnum::TruncateStmt(stmt) => compile_truncate(stmt),
217        NodeEnum::LockStmt(stmt) => super::locking::compile_lock_table(stmt),
218        NodeEnum::TransactionStmt(stmt) => compile_transaction(stmt),
219        NodeEnum::DeclareCursorStmt(stmt) => compile_declare_cursor(stmt),
220        NodeEnum::FetchStmt(stmt) => compile_fetch_cursor(stmt),
221        NodeEnum::ClosePortalStmt(stmt) => Ok(compile_close_cursor(stmt)),
222        NodeEnum::CreateSeqStmt(stmt) => {
223            compile_create_sequence(stmt).map(Statement::CreateSequence)
224        }
225        NodeEnum::AlterSeqStmt(stmt) => compile_alter_sequence(stmt).map(Statement::AlterSequence),
226        NodeEnum::CreateTableAsStmt(stmt) => compile_create_table_as(stmt),
227        NodeEnum::RefreshMatViewStmt(stmt) => compile_refresh_materialized_view(stmt),
228        NodeEnum::PrepareStmt(stmt) => compile_prepare(stmt),
229        NodeEnum::ExecuteStmt(stmt) => compile_execute(stmt),
230        NodeEnum::DeallocateStmt(stmt) => compile_deallocate(stmt),
231        NodeEnum::CreateFdwStmt(stmt) => {
232            super::foreign_wrappers::compile(stmt).map(Statement::CreateForeignWrapper)
233        }
234        NodeEnum::CreateForeignServerStmt(stmt) => {
235            compile_create_foreign_server(stmt).map(Statement::CreateForeignServer)
236        }
237        NodeEnum::CreateForeignTableStmt(stmt) => compile_create_foreign_table_statement(stmt),
238        NodeEnum::MergeStmt(stmt) => compile_merge(stmt).map(Statement::Merge),
239        NodeEnum::CreateDomainStmt(_)
240        | NodeEnum::AlterDomainStmt(_)
241        | NodeEnum::DefineStmt(_)
242        | NodeEnum::CommentStmt(_)
243        | NodeEnum::CreateEnumStmt(_)
244        | NodeEnum::CompositeTypeStmt(_)
245        | NodeEnum::AlterEnumStmt(_) => type_lifecycle::compile_type_statement(inner),
246        NodeEnum::CreateFunctionStmt(stmt) => {
247            compile_create_function(stmt).map(|f| Statement::CreateFunction(Box::new(f)))
248        }
249        NodeEnum::DoStmt(stmt) => compile_do(stmt),
250        NodeEnum::CallStmt(stmt) => compile_call(stmt),
251        NodeEnum::AlterFunctionStmt(stmt) => {
252            compile_alter_routine(stmt).map(Statement::AlterRoutine)
253        }
254        NodeEnum::AlterOwnerStmt(stmt) => compile_alter_owner_statement(stmt),
255        NodeEnum::GrantStmt(stmt) => compile_grant_statement(stmt),
256        NodeEnum::GrantRoleStmt(stmt) => compile_grant_role(stmt),
257        NodeEnum::CreateRoleStmt(stmt) => compile_create_role(stmt),
258        NodeEnum::AlterRoleStmt(stmt) => compile_alter_role(stmt),
259        NodeEnum::DropRoleStmt(stmt) => compile_drop_role(stmt),
260        NodeEnum::VariableSetStmt(stmt) => compile_variable_set(stmt),
261        NodeEnum::ConstraintsSetStmt(stmt) => compile_set_constraints(stmt),
262        NodeEnum::VariableShowStmt(stmt) => Ok(Statement::ShowVariable {
263            name: stmt.name.clone(),
264        }),
265        NodeEnum::DiscardStmt(stmt) => Ok(Statement::Discard {
266            target: discard_target(stmt.target)?,
267        }),
268        NodeEnum::LoadStmt(stmt) => Ok(Statement::Load {
269            library: stmt.filename.clone(),
270        }),
271        other => Err(SQLError::Unsupported(format!(
272            "{}",
273            other_node_label(other)
274        ))),
275    }
276}
277
278/// Standalone `VALUES (...) (...)` parses as a `SelectStmt` with an empty target list and populated values lists; it is a relation-producing statement of its own.
279fn compile_select_statement(stmt: &SelectStmt) -> Result<Statement> {
280    if stmt.target_list.is_empty()
281        && !stmt.values_lists.is_empty()
282        && stmt.locking_clause.is_empty()
283        && stmt.sort_clause.is_empty()
284        && stmt.limit_count.is_none()
285        && stmt.limit_offset.is_none()
286    {
287        let rows = compile_values_lists(&stmt.values_lists)?;
288        return Ok(Statement::Values { rows });
289    }
290    compile_top_level_select(stmt)
291}
292
293/// Statement label reported for a parser node that compilation does not support.
294pub(super) fn other_node_label(node: &NodeEnum) -> &'static str {
295    match node {
296        NodeEnum::ExplainStmt(_) => "EXPLAIN",
297        NodeEnum::ViewStmt(_) => "CREATE VIEW",
298        NodeEnum::TransactionStmt(_) => "BEGIN/COMMIT/ROLLBACK",
299        NodeEnum::DeclareCursorStmt(_) => "DECLARE CURSOR",
300        NodeEnum::FetchStmt(_) => "FETCH/MOVE",
301        NodeEnum::ClosePortalStmt(_) => "CLOSE CURSOR",
302        NodeEnum::PrepareStmt(_) | NodeEnum::ExecuteStmt(_) => "PREPARE/EXECUTE",
303        _ => "unknown statement",
304    }
305}
306
307// -------------------------------------------------------------------------
308// DROP TABLE / DROP INDEX [IF EXISTS] [CASCADE]
309// -------------------------------------------------------------------------
310
311/// Lower `DROP FUNCTION` / `DROP PROCEDURE`. Each target arrives as
312/// an `ObjectWithArgs`; the argument type list (when spelled) is
313/// preserved as a typed signature because routine identity includes
314/// `(schema, name, argument types)`.
315pub fn plan_only_for_test(sql: &str) -> Result<Vec<Statement>> {
316    compile(sql)
317}