1use 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
38#[derive(Debug, Clone)]
40pub struct ParsedStatement<'sql> {
41 sql: &'sql str,
42 message: &'sql str,
43 positions: std::sync::Arc<super::source_positions::SourcePositions>,
44 node: Box<Node>,
45 settings: crate::parser::ParserSettings,
46}
47
48impl<'sql> ParsedStatement<'sql> {
49 pub const fn sql(&self) -> &'sql str {
51 self.sql
52 }
53
54 pub fn is_notification_listener_command(&self) -> bool {
56 matches!(
57 self.node.node.as_ref(),
58 Some(NodeEnum::ListenStmt(_) | NodeEnum::UnlistenStmt(_))
59 )
60 }
61
62 pub fn compile(&self) -> Result<Statement> {
64 crate::parser::with_settings(self.settings, || {
65 let mut statement = super::source_positions::with_source(
66 std::sync::Arc::clone(&self.positions),
67 || compile_stmt(&self.node),
68 )?;
69 if let Statement::CreateFunction(definition) = &mut statement {
70 if let crate::ast::FunctionBody::Source(body) = &definition.body {
71 definition.body_origin =
72 crate::ast::RoutineBodyOrigin::capture(body, self.message);
73 }
74 }
75 if let Statement::CreateForeignServer(server) = &mut statement {
76 super::foreign_servers::retain_string_presence(self.sql, server)?;
77 }
78 Ok(statement)
79 })
80 .0
81 }
82}
83
84pub fn parse_statements(sql: &str) -> Result<Vec<ParsedStatement<'_>>> {
86 let parsed = crate::parser::parse(sql)?;
87 let mut out = Vec::with_capacity(parsed.protobuf.stmts.len());
88 let positions = std::sync::Arc::new(super::source_positions::SourcePositions::new(sql));
89 for raw in parsed.protobuf.stmts {
90 let node = raw
91 .stmt
92 .ok_or_else(|| SQLError::Internal("parser returned an empty statement".into()))?;
93 let start = usize::try_from(raw.stmt_location).map_err(|_| {
94 SQLError::Internal("parser returned a negative statement offset".into())
95 })?;
96 let end = if raw.stmt_len == 0 {
97 sql.len()
98 } else {
99 let len = usize::try_from(raw.stmt_len).map_err(|_| {
100 SQLError::Internal("parser returned a negative statement length".into())
101 })?;
102 start
103 .checked_add(len)
104 .ok_or_else(|| SQLError::Internal("parser statement offset overflow".into()))?
105 };
106 let source = sql.get(start..end).ok_or_else(|| {
107 SQLError::Internal("parser statement bounds do not match SQL text".into())
108 })?;
109 out.push(ParsedStatement {
110 sql: source,
111 message: sql,
112 positions: std::sync::Arc::clone(&positions),
113 node,
114 settings: crate::parser::settings(),
115 });
116 }
117 Ok(out)
118}
119
120pub fn compile(sql: &str) -> Result<Vec<Statement>> {
121 parse_statements(sql)?
122 .iter()
123 .map(ParsedStatement::compile)
124 .collect()
125}
126
127pub fn resolve_deferred_create_table(
128 deferred: &crate::ast::DeferredCreateTable,
129) -> Result<crate::ast::CreateTable> {
130 let parsed = crate::parser::parse(&deferred.definition_sql)?;
131 let [raw] = parsed.protobuf.stmts.as_slice() else {
132 return Err(SQLError::Internal(
133 "deferred CREATE TABLE did not contain exactly one statement".into(),
134 ));
135 };
136 let node = raw
137 .stmt
138 .as_deref()
139 .and_then(|node| node.node.as_ref())
140 .ok_or_else(|| SQLError::Internal("deferred CREATE TABLE is empty".into()))?;
141 let NodeEnum::CreateStmt(stmt) = node else {
142 return Err(SQLError::Internal(
143 "deferred CREATE TABLE changed statement kind".into(),
144 ));
145 };
146 let table = compile_create_table(stmt)?;
147 if !table.if_not_exists
148 || table.name != deferred.name
149 || table.persistence != deferred.persistence
150 {
151 return Err(SQLError::Internal(
152 "deferred CREATE TABLE changed target identity".into(),
153 ));
154 }
155 Ok(table)
156}
157
158fn compile_create_table_statement(statement: &pg_query::protobuf::CreateStmt) -> Result<Statement> {
159 if statement.if_not_exists {
160 defer_create_table(statement).map(Statement::CreateTableIfNotExists)
161 } else {
162 compile_create_table(statement).map(Statement::CreateTable)
163 }
164}
165
166fn compile_create_foreign_table_statement(
167 statement: &pg_query::protobuf::CreateForeignTableStmt,
168) -> Result<Statement> {
169 defer_create_foreign_table(statement).map(Statement::CreateForeignTableDefinition)
170}
171
172fn compile_rename_statement(statement: &pg_query::protobuf::RenameStmt) -> Result<Statement> {
174 match type_lifecycle::type_object_kind(statement.rename_type()) {
175 Some(kind) => type_lifecycle::compile_type_rename(statement, kind),
176 None => compile_rename(statement),
177 }
178}
179
180fn compile_alter_object_schema_statement(
181 statement: &pg_query::protobuf::AlterObjectSchemaStmt,
182) -> Result<Statement> {
183 match type_lifecycle::type_object_kind(statement.object_type()) {
184 Some(kind) => type_lifecycle::compile_type_set_schema(statement, kind),
185 None => compile_alter_object_schema(statement),
186 }
187}
188
189fn compile_alter_owner_statement(
190 statement: &pg_query::protobuf::AlterOwnerStmt,
191) -> Result<Statement> {
192 match type_lifecycle::type_object_kind(statement.object_type()) {
193 Some(kind) => type_lifecycle::compile_type_owner(statement, kind),
194 None => compile_alter_routine_owner(statement),
195 }
196}
197
198fn compile_grant_statement(statement: &pg_query::protobuf::GrantStmt) -> Result<Statement> {
199 match type_lifecycle::type_object_kind(statement.objtype()) {
200 Some(kind) => type_lifecycle::compile_grant_type(statement, kind),
201 None => compile_grant(statement),
202 }
203}
204
205pub(super) fn compile_stmt(node: &Node) -> Result<Statement> {
206 let Some(inner) = node.node.as_ref() else {
207 return Err(SQLError::Unsupported("empty statement".into()));
208 };
209 match inner {
210 NodeEnum::CreateStmt(stmt) => compile_create_table_statement(stmt),
211 NodeEnum::IndexStmt(stmt) => compile_create_index(stmt).map(Statement::CreateIndex),
212 NodeEnum::InsertStmt(stmt) => compile_insert(stmt).map(Statement::Insert),
213 NodeEnum::SelectStmt(stmt) => compile_select_statement(stmt),
214 NodeEnum::UpdateStmt(stmt) => compile_update(stmt).map(Statement::Update),
215 NodeEnum::DeleteStmt(stmt) => compile_delete(stmt).map(Statement::Delete),
216 NodeEnum::DropStmt(stmt) => compile_drop(stmt),
217 NodeEnum::CreateTrigStmt(stmt) => {
218 compile_create_trigger(stmt).map(Statement::CreateTrigger)
219 }
220 NodeEnum::RuleStmt(stmt) => compile_create_rule(stmt).map(Statement::CreateRule),
221 NodeEnum::AlterTableStmt(stmt) => compile_alter_table(stmt),
222 NodeEnum::RenameStmt(stmt) => compile_rename_statement(stmt),
223 NodeEnum::AlterObjectSchemaStmt(stmt) => compile_alter_object_schema_statement(stmt),
224 NodeEnum::ViewStmt(stmt) => compile_create_view(stmt),
225 NodeEnum::CreateSchemaStmt(stmt) => compile_create_schema(stmt),
226 NodeEnum::NotifyStmt(stmt) => Ok(Statement::Notify {
227 channel: stmt.conditionname.clone(),
228 payload: stmt.payload.clone(),
229 }),
230 NodeEnum::ListenStmt(stmt) => Ok(Statement::Listen {
231 channel: stmt.conditionname.clone(),
232 }),
233 NodeEnum::UnlistenStmt(stmt) => Ok(Statement::Unlisten {
234 channel: (!stmt.conditionname.is_empty()).then(|| stmt.conditionname.clone()),
235 }),
236 NodeEnum::ExplainStmt(stmt) => compile_explain(stmt),
237 NodeEnum::VacuumStmt(stmt) => compile_analyze(stmt),
238 NodeEnum::TruncateStmt(stmt) => compile_truncate(stmt),
239 NodeEnum::LockStmt(stmt) => super::locking::compile_lock_table(stmt),
240 NodeEnum::TransactionStmt(stmt) => compile_transaction(stmt),
241 NodeEnum::DeclareCursorStmt(stmt) => compile_declare_cursor(stmt),
242 NodeEnum::FetchStmt(stmt) => compile_fetch_cursor(stmt),
243 NodeEnum::ClosePortalStmt(stmt) => Ok(compile_close_cursor(stmt)),
244 NodeEnum::CreateSeqStmt(stmt) => {
245 compile_create_sequence(stmt).map(Statement::CreateSequence)
246 }
247 NodeEnum::AlterSeqStmt(stmt) => compile_alter_sequence(stmt).map(Statement::AlterSequence),
248 NodeEnum::CreateTableAsStmt(stmt) => compile_create_table_as(stmt),
249 NodeEnum::RefreshMatViewStmt(stmt) => compile_refresh_materialized_view(stmt),
250 NodeEnum::PrepareStmt(stmt) => compile_prepare(stmt),
251 NodeEnum::ExecuteStmt(stmt) => compile_execute(stmt),
252 NodeEnum::DeallocateStmt(stmt) => compile_deallocate(stmt),
253 NodeEnum::CreateFdwStmt(stmt) => {
254 super::foreign_wrappers::compile(stmt).map(Statement::CreateForeignWrapper)
255 }
256 NodeEnum::CreateForeignServerStmt(stmt) => {
257 compile_create_foreign_server(stmt).map(Statement::CreateForeignServer)
258 }
259 NodeEnum::CreateForeignTableStmt(stmt) => compile_create_foreign_table_statement(stmt),
260 NodeEnum::MergeStmt(stmt) => compile_merge(stmt).map(Statement::Merge),
261 NodeEnum::CreateDomainStmt(_)
262 | NodeEnum::AlterDomainStmt(_)
263 | NodeEnum::DefineStmt(_)
264 | NodeEnum::CommentStmt(_)
265 | NodeEnum::CreateEnumStmt(_)
266 | NodeEnum::CompositeTypeStmt(_)
267 | NodeEnum::AlterEnumStmt(_) => type_lifecycle::compile_type_statement(inner),
268 NodeEnum::CreateFunctionStmt(stmt) => {
269 compile_create_function(stmt).map(|f| Statement::CreateFunction(Box::new(f)))
270 }
271 NodeEnum::DoStmt(stmt) => compile_do(stmt),
272 NodeEnum::CallStmt(stmt) => compile_call(stmt),
273 NodeEnum::AlterFunctionStmt(stmt) => {
274 compile_alter_routine(stmt).map(Statement::AlterRoutine)
275 }
276 NodeEnum::AlterOwnerStmt(stmt) => compile_alter_owner_statement(stmt),
277 NodeEnum::GrantStmt(stmt) => compile_grant_statement(stmt),
278 NodeEnum::GrantRoleStmt(stmt) => compile_grant_role(stmt),
279 NodeEnum::CreateRoleStmt(stmt) => compile_create_role(stmt),
280 NodeEnum::AlterRoleStmt(stmt) => compile_alter_role(stmt),
281 NodeEnum::DropRoleStmt(stmt) => compile_drop_role(stmt),
282 NodeEnum::VariableSetStmt(stmt) => compile_variable_set(stmt),
283 NodeEnum::ConstraintsSetStmt(stmt) => compile_set_constraints(stmt),
284 NodeEnum::VariableShowStmt(stmt) => Ok(Statement::ShowVariable {
285 name: stmt.name.clone(),
286 }),
287 NodeEnum::DiscardStmt(stmt) => Ok(Statement::Discard {
288 target: discard_target(stmt.target)?,
289 }),
290 NodeEnum::LoadStmt(stmt) => Ok(Statement::Load {
291 library: stmt.filename.clone(),
292 }),
293 other => Err(SQLError::Unsupported(format!(
294 "{}",
295 other_node_label(other)
296 ))),
297 }
298}
299
300fn compile_select_statement(stmt: &SelectStmt) -> Result<Statement> {
302 if stmt.target_list.is_empty()
303 && !stmt.values_lists.is_empty()
304 && stmt.locking_clause.is_empty()
305 && stmt.sort_clause.is_empty()
306 && stmt.limit_count.is_none()
307 && stmt.limit_offset.is_none()
308 {
309 let rows = compile_values_lists(&stmt.values_lists)?;
310 return Ok(Statement::Values { rows });
311 }
312 compile_top_level_select(stmt)
313}
314
315pub(super) fn other_node_label(node: &NodeEnum) -> &'static str {
317 match node {
318 NodeEnum::ExplainStmt(_) => "EXPLAIN",
319 NodeEnum::ViewStmt(_) => "CREATE VIEW",
320 NodeEnum::TransactionStmt(_) => "BEGIN/COMMIT/ROLLBACK",
321 NodeEnum::DeclareCursorStmt(_) => "DECLARE CURSOR",
322 NodeEnum::FetchStmt(_) => "FETCH/MOVE",
323 NodeEnum::ClosePortalStmt(_) => "CLOSE CURSOR",
324 NodeEnum::PrepareStmt(_) | NodeEnum::ExecuteStmt(_) => "PREPARE/EXECUTE",
325 _ => "unknown statement",
326 }
327}
328
329pub fn plan_only_for_test(sql: &str) -> Result<Vec<Statement>> {
338 compile(sql)
339}