1use super::model::NoRegisteredAggregates;
10use super::query::{lower_assignments, lower_ctes, lower_merge_when, lower_targets};
11use super::rewrite::{rewrite_command_scalars, rewrite_query_scalars};
12use super::scalar::lower_scalar_expression;
13use super::{
14 AggregateClassifier, CommandPlan, ConflictActionPlan, ConflictPlan, DeletePlan, ExpressionPlan,
15 InsertPlan, MergePlan, ProjectionPlan, QueryPlan, RelationalPlan, ScalarExpr, SourcePlan,
16 Statement, UnifiedPlan, UpdatePlan,
17};
18
19impl UnifiedPlan {
20 #[must_use]
22 pub fn lower(statement: Statement) -> Self {
23 Self::lower_with(statement, &NoRegisteredAggregates)
24 }
25
26 #[must_use]
28 #[expect(
29 clippy::too_many_lines,
30 reason = "plan lowering preserves exhaustive variants and structural identities"
31 )]
32 pub fn lower_with(statement: Statement, aggregates: &dyn AggregateClassifier) -> Self {
33 match statement {
34 Statement::Empty => Self::Command(Box::new(CommandPlan::Empty)),
35 Statement::Select(query) => {
36 Self::Query(Box::new(QueryPlan::lower_with(*query, aggregates)))
37 }
38 Statement::Values { rows } => {
39 let mut subqueries = Vec::new();
40 let rows = rows
41 .into_iter()
42 .map(|row| {
43 row.into_iter()
44 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
45 .collect()
46 })
47 .collect();
48 Self::Query(Box::new(QueryPlan {
49 analyzed_output: None,
50 analyzed_source: None,
51 analyzed_grouping: None,
52 relation_privilege_subject: None,
53 relations_bound: false,
54 ctes: Vec::new(),
55 root: RelationalPlan::Values { rows, subqueries },
56 }))
57 }
58 Statement::CreateTable(value) => {
59 Self::Command(Box::new(CommandPlan::CreateTable(Box::new(value))))
60 }
61 Statement::CreateTableIfNotExists(value) => {
62 Self::Command(Box::new(CommandPlan::CreateTableIfNotExists(value)))
63 }
64 Statement::CreateIndex(value) => {
65 Self::Command(Box::new(CommandPlan::CreateIndex(value)))
66 }
67 Statement::RenameIndex(value) => {
68 Self::Command(Box::new(CommandPlan::RenameIndex(value)))
69 }
70 Statement::Insert(statement) => {
71 let ctes = lower_ctes(&statement.with, aggregates);
72 let source = statement
73 .select_source
74 .map(|query| Box::new(QueryPlan::lower_with(*query, aggregates)));
75 let mut subqueries = Vec::new();
76 let rows = statement
77 .rows
78 .into_iter()
79 .map(|row| {
80 row.into_iter()
81 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
82 .collect()
83 })
84 .collect();
85 let on_conflict = statement.on_conflict.map(|conflict| {
86 let action = match conflict.action {
87 crate::ast::OnConflictAction::Nothing => ConflictActionPlan::Nothing,
88 crate::ast::OnConflictAction::Update {
89 assignments,
90 r#where,
91 } => ConflictActionPlan::Update {
92 assignments: lower_assignments(
93 assignments,
94 aggregates,
95 &mut subqueries,
96 ),
97 predicate: r#where.map(|expr| {
98 Box::new(lower_scalar_expression(
99 *expr,
100 aggregates,
101 &mut subqueries,
102 ))
103 }),
104 },
105 };
106 ConflictPlan {
107 predicate: conflict.predicate.map(|expr| {
108 Box::new(lower_scalar_expression(*expr, aggregates, &mut subqueries))
109 }),
110 constraint: conflict.constraint,
111 conflict_columns: conflict.conflict_columns,
112 expressions: conflict
113 .expressions
114 .into_iter()
115 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
116 .collect(),
117 action,
118 }
119 });
120 let returning = statement
121 .returning
122 .into_iter()
123 .map(|projection| {
124 ProjectionPlan::lower_with(projection, aggregates, &mut subqueries)
125 })
126 .collect();
127 Self::Command(Box::new(CommandPlan::Insert(Box::new(InsertPlan {
128 table: statement.table,
129 target_relation_bound: statement.target_relation_bound,
130 relations_bound: false,
131 statement_privilege_subject: None,
132 target_privilege_subject: None,
133 target_qualifier: statement.target_qualifier,
134 target_alias: statement.target_alias,
135 include_descendants: statement.include_descendants,
136 columns: lower_targets(statement.columns, aggregates, &mut subqueries),
137 overriding: statement.overriding,
138 ctes,
139 rows,
140 source,
141 rule_values_input: None,
142 on_conflict,
143 returning,
144 returning_aliases: statement.returning_aliases,
145 subqueries,
146 view_checks: Vec::new(),
147 view_rule_relations: Vec::new(),
148 view_rule_insert_plans: Vec::new(),
149 view_rule_returning: None,
150 }))))
151 }
152 Statement::Update(statement) => {
153 let ctes = lower_ctes(&statement.with, aggregates);
154 let mut subqueries = Vec::new();
155 let source = statement
156 .from
157 .map(|from| SourcePlan::lower_with(from, aggregates, &mut subqueries));
158 let assignments =
159 lower_assignments(statement.assignments, aggregates, &mut subqueries);
160 let predicate = statement
161 .r#where
162 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries));
163 let returning = statement
164 .returning
165 .into_iter()
166 .map(|projection| {
167 ProjectionPlan::lower_with(projection, aggregates, &mut subqueries)
168 })
169 .collect();
170 Self::Command(Box::new(CommandPlan::Update(Box::new(UpdatePlan {
171 table: statement.table,
172 target_relation_bound: statement.target_relation_bound,
173 relations_bound: false,
174 statement_privilege_subject: None,
175 target_privilege_subject: None,
176 target_qualifier: statement.target_qualifier,
177 target_alias: statement.target_alias,
178 include_descendants: statement.include_descendants,
179 assignments,
180 predicate,
181 ctes,
182 source: source.map(Box::new),
183 returning,
184 returning_aliases: statement.returning_aliases,
185 subqueries,
186 view_checks: Vec::new(),
187 view_rule_relations: Vec::new(),
188 view_rule_update_plans: Vec::new(),
189 view_rule_returning: None,
190 }))))
191 }
192 Statement::Delete(statement) => {
193 let ctes = lower_ctes(&statement.with, aggregates);
194 let mut subqueries = Vec::new();
195 let source = statement
196 .using
197 .map(|from| SourcePlan::lower_with(from, aggregates, &mut subqueries));
198 let predicate = statement
199 .r#where
200 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries));
201 let returning = statement
202 .returning
203 .into_iter()
204 .map(|projection| {
205 ProjectionPlan::lower_with(projection, aggregates, &mut subqueries)
206 })
207 .collect();
208 Self::Command(Box::new(CommandPlan::Delete(Box::new(DeletePlan {
209 table: statement.table,
210 target_relation_bound: statement.target_relation_bound,
211 relations_bound: false,
212 statement_privilege_subject: None,
213 target_privilege_subject: None,
214 target_qualifier: statement.target_qualifier,
215 target_alias: statement.target_alias,
216 include_descendants: statement.include_descendants,
217 predicate,
218 ctes,
219 source: source.map(Box::new),
220 returning,
221 returning_aliases: statement.returning_aliases,
222 subqueries,
223 view_rule_relations: Vec::new(),
224 view_rule_returning: None,
225 }))))
226 }
227 Statement::Drop(value) => Self::Command(Box::new(CommandPlan::Drop(value))),
228 Statement::AlterTable(value) => {
229 Self::Command(Box::new(CommandPlan::AlterTable(Box::new(value))))
230 }
231 Statement::AlterForeignTable(value) => {
232 Self::Command(Box::new(CommandPlan::AlterForeignTable(value)))
233 }
234 Statement::AlterView(value) => Self::Command(Box::new(CommandPlan::AlterView(value))),
235 Statement::CreateView {
236 name,
237 column_names,
238 body,
239 or_replace,
240 persistence,
241 options,
242 } => {
243 let query = Box::new(QueryPlan::lower_with(*body, aggregates));
244 Self::Command(Box::new(CommandPlan::CreateView {
245 name,
246 column_names,
247 query,
248 or_replace,
249 persistence,
250 options,
251 }))
252 }
253 Statement::CreateMaterializedView {
254 name,
255 column_names,
256 if_not_exists,
257 with_no_data,
258 options,
259 body,
260 } => Self::Command(Box::new(CommandPlan::CreateMaterializedView {
261 name,
262 column_names,
263 if_not_exists,
264 with_no_data,
265 options,
266 query: Box::new(QueryPlan::lower_with(*body, aggregates)),
267 })),
268 Statement::RefreshMaterializedView {
269 name,
270 concurrently,
271 with_no_data,
272 } => Self::Command(Box::new(CommandPlan::RefreshMaterializedView {
273 name,
274 concurrently,
275 with_no_data,
276 })),
277 Statement::CreateSchema {
278 name,
279 if_not_exists,
280 authorization,
281 } => Self::Command(Box::new(CommandPlan::CreateSchema {
282 name,
283 if_not_exists,
284 authorization,
285 })),
286 Statement::AlterSchemaOwner { name, new_owner } => {
287 Self::Command(Box::new(CommandPlan::AlterSchemaOwner { name, new_owner }))
288 }
289 Statement::RenameSchema { name, new_name } => {
290 Self::Command(Box::new(CommandPlan::RenameSchema { name, new_name }))
291 }
292 Statement::Notify { channel, payload } => {
293 Self::Command(Box::new(CommandPlan::Notify { channel, payload }))
294 }
295 Statement::Listen { channel } => {
296 Self::Command(Box::new(CommandPlan::Listen { channel }))
297 }
298 Statement::Unlisten { channel } => {
299 Self::Command(Box::new(CommandPlan::Unlisten { channel }))
300 }
301 Statement::SetVariable {
302 name,
303 value,
304 local,
305 is_default,
306 } => Self::Command(Box::new(CommandPlan::SetVariable {
307 name,
308 value,
309 local,
310 is_default,
311 })),
312 Statement::ResetVariable { name } => {
313 Self::Command(Box::new(CommandPlan::ResetVariable { name }))
314 }
315 Statement::ResetAllVariables => Self::Command(Box::new(CommandPlan::ResetAllVariables)),
316 Statement::SetConstraints {
317 constraints,
318 deferred,
319 } => Self::Command(Box::new(CommandPlan::SetConstraints {
320 constraints,
321 deferred,
322 })),
323 Statement::ShowVariable { name } => {
324 Self::Command(Box::new(CommandPlan::ShowVariable { name }))
325 }
326 Statement::Discard { target } => {
327 Self::Command(Box::new(CommandPlan::Discard { target }))
328 }
329 Statement::Load { library } => Self::Command(Box::new(CommandPlan::Load { library })),
330 Statement::Explain { options, body } => Self::Command(Box::new(CommandPlan::Explain {
331 options,
332 body: Box::new(Self::lower_with(*body, aggregates)),
333 unbound_parameters: None,
334 })),
335 Statement::Analyze { table } => Self::Command(Box::new(CommandPlan::Analyze { table })),
336 Statement::Vacuum(vacuum) => Self::Command(Box::new(CommandPlan::Vacuum(vacuum))),
337 Statement::LockTable(lock) => Self::Command(Box::new(CommandPlan::LockTable(lock))),
338 Statement::Truncate {
339 tables,
340 cascade,
341 restart_identity,
342 } => Self::Command(Box::new(CommandPlan::Truncate {
343 tables,
344 cascade,
345 restart_identity,
346 })),
347 Statement::Transaction(value) => {
348 Self::Command(Box::new(CommandPlan::Transaction(value)))
349 }
350 Statement::DeclareCursor(cursor) => {
351 Self::Command(Box::new(CommandPlan::DeclareCursor {
352 name: cursor.name,
353 binary: cursor.binary,
354 scroll: cursor.scroll,
355 hold: cursor.hold,
356 query: Box::new(QueryPlan::lower_with(*cursor.query, aggregates)),
357 }))
358 }
359 Statement::FetchCursor(cursor) => {
360 Self::Command(Box::new(CommandPlan::FetchCursor(cursor)))
361 }
362 Statement::CloseCursor { name } => {
363 Self::Command(Box::new(CommandPlan::CloseCursor { name }))
364 }
365 Statement::CreateSequence(value) => {
366 Self::Command(Box::new(CommandPlan::CreateSequence(value)))
367 }
368 Statement::CommentType(value) => {
369 Self::Command(Box::new(CommandPlan::CommentType(value)))
370 }
371 Statement::CreateShellType(name) => {
372 Self::Command(Box::new(CommandPlan::CreateShellType(name)))
373 }
374 Statement::CreateEnum(value) => Self::Command(Box::new(CommandPlan::CreateEnum(value))),
375 Statement::CreateCompositeType(value) => {
376 Self::Command(Box::new(CommandPlan::CreateCompositeType(value)))
377 }
378 Statement::AlterEnum(value) => Self::Command(Box::new(CommandPlan::AlterEnum(value))),
379 Statement::AlterTypeObject(value) => {
380 Self::Command(Box::new(CommandPlan::AlterTypeObject(value)))
381 }
382 Statement::GrantType(value) => Self::Command(Box::new(CommandPlan::GrantType(value))),
383 Statement::CreateDomain(value) => {
384 Self::Command(Box::new(CommandPlan::CreateDomain(value)))
385 }
386 Statement::AlterDomain(value) => {
387 Self::Command(Box::new(CommandPlan::AlterDomain(value)))
388 }
389 Statement::AlterSequence(value) => {
390 Self::Command(Box::new(CommandPlan::AlterSequence(value)))
391 }
392 Statement::CreateTableAs {
393 name,
394 if_not_exists,
395 column_names,
396 with_no_data,
397 select_into,
398 persistence,
399 on_commit,
400 body,
401 } => Self::Command(Box::new(CommandPlan::CreateTableAs {
402 name,
403 if_not_exists,
404 column_names,
405 with_no_data,
406 select_into,
407 persistence,
408 on_commit,
409 query: Box::new(QueryPlan::lower_with(*body, aggregates)),
410 })),
411 Statement::Prepare {
412 name,
413 parameter_types,
414 body,
415 } => {
416 let body = Box::new(Self::lower_with(*body, aggregates));
417 Self::Command(Box::new(CommandPlan::Prepare {
418 name,
419 parameter_types,
420 body,
421 }))
422 }
423 Statement::Execute { name, params } => Self::Command(Box::new(CommandPlan::Execute {
424 name,
425 params: params
426 .into_iter()
427 .map(|expr| ExpressionPlan::lower_with(expr, aggregates))
428 .collect(),
429 })),
430 Statement::Deallocate { name } => {
431 Self::Command(Box::new(CommandPlan::Deallocate { name }))
432 }
433 Statement::CreateForeignWrapper(value) => {
434 Self::Command(Box::new(CommandPlan::CreateForeignWrapper(value)))
435 }
436 Statement::CreateForeignServer(value) => {
437 Self::Command(Box::new(CommandPlan::CreateForeignServer(value)))
438 }
439 Statement::CreateForeignTable(value) => {
440 Self::Command(Box::new(CommandPlan::CreateForeignTable(value)))
441 }
442 Statement::CreateForeignTableDefinition(value) => {
443 Self::Command(Box::new(CommandPlan::CreateForeignTableDefinition(value)))
444 }
445 Statement::Merge(statement) => {
446 let mut subqueries = Vec::new();
447 let source = SourcePlan::lower_with(statement.source, aggregates, &mut subqueries);
448 let join_condition =
449 lower_scalar_expression(statement.join_condition, aggregates, &mut subqueries);
450 let when_clauses = statement
451 .when_clauses
452 .into_iter()
453 .map(|clause| lower_merge_when(clause, aggregates, &mut subqueries))
454 .collect();
455 let returning = statement
456 .returning
457 .into_iter()
458 .map(|projection| {
459 ProjectionPlan::lower_with(projection, aggregates, &mut subqueries)
460 })
461 .collect();
462 Self::Command(Box::new(CommandPlan::Merge(Box::new(MergePlan {
463 ctes: lower_ctes(&statement.with, aggregates),
464 target: statement.target,
465 statement_privilege_subject: None,
466 target_privilege_subject: None,
467 target_qualifier: statement.target_qualifier,
468 target_alias: statement.target_alias,
469 include_descendants: statement.include_descendants,
470 target_predicate: None,
471 source: Box::new(source),
472 join_condition,
473 when_clauses,
474 returning,
475 returning_aliases: statement.returning_aliases,
476 subqueries,
477 view_checks: Vec::new(),
478 }))))
479 }
480 Statement::CreateFunction(value) => {
481 Self::Command(Box::new(CommandPlan::CreateFunction(value)))
482 }
483 Statement::DropFunction(value) => {
484 Self::Command(Box::new(CommandPlan::DropFunction(value)))
485 }
486 Statement::AlterRoutine(value) => {
487 Self::Command(Box::new(CommandPlan::AlterRoutine(value)))
488 }
489 Statement::AlterRoutineOwner(value) => {
490 Self::Command(Box::new(CommandPlan::AlterRoutineOwner(value)))
491 }
492 Statement::RenameRoutine(value) => {
493 Self::Command(Box::new(CommandPlan::RenameRoutine(value)))
494 }
495 Statement::GrantRoutine(value) => {
496 Self::Command(Box::new(CommandPlan::GrantRoutine(value)))
497 }
498 Statement::GrantTable(value) => Self::Command(Box::new(CommandPlan::GrantTable(value))),
499 Statement::GrantSequence(value) => {
500 Self::Command(Box::new(CommandPlan::GrantSequence(value)))
501 }
502 Statement::GrantDatabase(value) => {
503 Self::Command(Box::new(CommandPlan::GrantDatabase(value)))
504 }
505 Statement::GrantSchema(value) => {
506 Self::Command(Box::new(CommandPlan::GrantSchema(value)))
507 }
508 Statement::GrantRole(value) => Self::Command(Box::new(CommandPlan::GrantRole(value))),
509 Statement::CreateRole(value) => Self::Command(Box::new(CommandPlan::CreateRole(value))),
510 Statement::AlterRole(value) => Self::Command(Box::new(CommandPlan::AlterRole(value))),
511 Statement::RenameRole(value) => Self::Command(Box::new(CommandPlan::RenameRole(value))),
512 Statement::DropRole(value) => Self::Command(Box::new(CommandPlan::DropRole(value))),
513 Statement::CreateTrigger(value) => {
514 Self::Command(Box::new(CommandPlan::CreateTrigger(value)))
515 }
516 Statement::DropTrigger(value) => {
517 Self::Command(Box::new(CommandPlan::DropTrigger(value)))
518 }
519 Statement::CreateRule(value) => Self::Command(Box::new(CommandPlan::CreateRule(value))),
520 Statement::DropRule(value) => Self::Command(Box::new(CommandPlan::DropRule(value))),
521 Statement::DoBlock { language, body } => {
522 Self::Command(Box::new(CommandPlan::DoBlock { language, body }))
523 }
524 Statement::Call { name, args } => Self::Command(Box::new(CommandPlan::Call {
525 name,
526 args: args
527 .into_iter()
528 .map(|expr| ExpressionPlan::lower_with(expr, aggregates))
529 .collect(),
530 })),
531 }
532 }
533
534 #[must_use]
535 pub fn name(&self) -> &'static str {
536 match self {
537 Self::Query(_) => "Query",
538 Self::Command(command) => command.name(),
539 }
540 }
541
542 pub fn rewrite_scalar_expressions(&mut self, rewrite: &mut dyn FnMut(&mut ScalarExpr)) {
548 match self {
549 Self::Query(query) => rewrite_query_scalars(query, rewrite),
550 Self::Command(command) => rewrite_command_scalars(command, rewrite),
551 }
552 }
553}
554
555impl CommandPlan {
556 #[must_use]
557 pub fn name(&self) -> &'static str {
558 match self {
559 Self::CreateTable(_) => "CreateTable",
560 Self::CreateTableIfNotExists(_) => "CreateTableIfNotExists",
561 Self::CreateIndex(_) => "CreateIndex",
562 Self::RenameIndex(_) => "RenameIndex",
563 Self::Insert(_) => "Insert",
564 Self::Update(_) => "Update",
565 Self::Delete(_) => "Delete",
566 Self::Drop(_) => "Drop",
567 Self::AlterTable(_) => "AlterTable",
568 Self::AlterView(_) => "AlterView",
569 Self::CreateView { .. } => "CreateView",
570 Self::CreateMaterializedView { .. } => "CreateMaterializedView",
571 Self::RefreshMaterializedView { .. } => "RefreshMaterializedView",
572 Self::CreateSchema { .. } => "CreateSchema",
573 Self::AlterSchemaOwner { .. } => "AlterSchemaOwner",
574 Self::RenameSchema { .. } => "RenameSchema",
575 Self::Notify { .. } => "Notify",
576 Self::Listen { .. } => "Listen",
577 Self::Unlisten { .. } => "Unlisten",
578 Self::SetVariable { .. } => "SetVariable",
579 Self::ResetVariable { .. } => "ResetVariable",
580 Self::ResetAllVariables => "ResetAllVariables",
581 Self::SetConstraints { .. } => "SetConstraints",
582 Self::ShowVariable { .. } => "ShowVariable",
583 Self::Discard { .. } => "Discard",
584 Self::Load { .. } => "Load",
585 Self::Explain { .. } => "Explain",
586 Self::Analyze { .. } => "Analyze",
587 Self::Vacuum(_) => "Vacuum",
588 Self::LockTable(_) => "LockTable",
589 Self::Truncate { .. } => "Truncate",
590 Self::Transaction(_) => "Transaction",
591 Self::DeclareCursor { .. } => "DeclareCursor",
592 Self::FetchCursor(_) => "FetchCursor",
593 Self::CloseCursor { .. } => "CloseCursor",
594 Self::CreateSequence(_) => "CreateSequence",
595 Self::CreateDomain(_) => "CreateDomain",
596 Self::AlterDomain(_) => "AlterDomain",
597 Self::CreateShellType(_) => "CreateShellType",
598 Self::CommentType(_) => "CommentType",
599 Self::CreateEnum(_) => "CreateEnum",
600 Self::CreateCompositeType(_) => "CreateCompositeType",
601 Self::AlterEnum(_) => "AlterEnum",
602 Self::AlterTypeObject(_) => "AlterTypeObject",
603 Self::GrantType(_) => "GrantType",
604 Self::AlterSequence(_) => "AlterSequence",
605 Self::CreateTableAs { .. } => "CreateTableAs",
606 Self::Prepare { .. } => "Prepare",
607 Self::Execute { .. } => "Execute",
608 Self::Deallocate { .. } => "Deallocate",
609 Self::CreateForeignWrapper(_) => "CreateForeignWrapper",
610 Self::CreateForeignServer(_) => "CreateForeignServer",
611 Self::CreateForeignTable(_) => "CreateForeignTable",
612 Self::CreateForeignTableDefinition(_) => "CreateForeignTableDefinition",
613 Self::AlterForeignTable(_) => "AlterForeignTable",
614 Self::Merge(_) => "Merge",
615 Self::CreateFunction(_) => "CreateFunction",
616 Self::DropFunction(_) => "DropFunction",
617 Self::AlterRoutine(_) => "AlterRoutine",
618 Self::AlterRoutineOwner(_) => "AlterRoutineOwner",
619 Self::RenameRoutine(_) => "RenameRoutine",
620 Self::GrantRoutine(_) => "GrantRoutine",
621 Self::GrantTable(_) => "GrantTable",
622 Self::GrantSequence(_) => "GrantSequence",
623 Self::GrantDatabase(_) => "GrantDatabase",
624 Self::GrantSchema(_) => "GrantSchema",
625 Self::GrantRole(_) => "GrantRole",
626 Self::CreateRole(_) => "CreateRole",
627 Self::AlterRole(_) => "AlterRole",
628 Self::RenameRole(_) => "RenameRole",
629 Self::DropRole(_) => "DropRole",
630 Self::CreateTrigger(_) => "CreateTrigger",
631 Self::DropTrigger(_) => "DropTrigger",
632 Self::CreateRule(_) => "CreateRule",
633 Self::DropRule(_) => "DropRule",
634 Self::DoBlock { .. } => "DoBlock",
635 Self::Call { .. } => "Call",
636 Self::Empty => "Empty",
637 }
638 }
639}