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::Select(query) => {
35 Self::Query(Box::new(QueryPlan::lower_with(*query, aggregates)))
36 }
37 Statement::Values { rows } => {
38 let mut subqueries = Vec::new();
39 let rows = rows
40 .into_iter()
41 .map(|row| {
42 row.into_iter()
43 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
44 .collect()
45 })
46 .collect();
47 Self::Query(Box::new(QueryPlan {
48 relations_bound: false,
49 ctes: Vec::new(),
50 root: RelationalPlan::Values { rows, subqueries },
51 }))
52 }
53 Statement::CreateTable(value) => {
54 Self::Command(Box::new(CommandPlan::CreateTable(Box::new(value))))
55 }
56 Statement::CreateTableIfNotExists(value) => {
57 Self::Command(Box::new(CommandPlan::CreateTableIfNotExists(value)))
58 }
59 Statement::CreateIndex(value) => {
60 Self::Command(Box::new(CommandPlan::CreateIndex(value)))
61 }
62 Statement::RenameIndex(value) => {
63 Self::Command(Box::new(CommandPlan::RenameIndex(value)))
64 }
65 Statement::Insert(statement) => {
66 let ctes = lower_ctes(&statement.with, aggregates);
67 let source = statement
68 .select_source
69 .map(|query| Box::new(QueryPlan::lower_with(*query, aggregates)));
70 let mut subqueries = Vec::new();
71 let rows = statement
72 .rows
73 .into_iter()
74 .map(|row| {
75 row.into_iter()
76 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
77 .collect()
78 })
79 .collect();
80 let on_conflict = statement.on_conflict.map(|conflict| {
81 let action = match conflict.action {
82 crate::ast::OnConflictAction::Nothing => ConflictActionPlan::Nothing,
83 crate::ast::OnConflictAction::Update {
84 assignments,
85 r#where,
86 } => ConflictActionPlan::Update {
87 assignments: lower_assignments(
88 assignments,
89 aggregates,
90 &mut subqueries,
91 ),
92 predicate: r#where.map(|expr| {
93 Box::new(lower_scalar_expression(
94 *expr,
95 aggregates,
96 &mut subqueries,
97 ))
98 }),
99 },
100 };
101 ConflictPlan {
102 predicate: conflict.predicate.map(|expr| {
103 Box::new(lower_scalar_expression(*expr, aggregates, &mut subqueries))
104 }),
105 constraint: conflict.constraint,
106 conflict_columns: conflict.conflict_columns,
107 expressions: conflict
108 .expressions
109 .into_iter()
110 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
111 .collect(),
112 action,
113 }
114 });
115 let returning = statement
116 .returning
117 .into_iter()
118 .map(|projection| {
119 ProjectionPlan::lower_with(projection, aggregates, &mut subqueries)
120 })
121 .collect();
122 Self::Command(Box::new(CommandPlan::Insert(Box::new(InsertPlan {
123 table: statement.table,
124 target_relation_bound: statement.target_relation_bound,
125 relations_bound: false,
126 statement_privilege_subject: None,
127 target_privilege_subject: None,
128 target_qualifier: statement.target_qualifier,
129 target_alias: statement.target_alias,
130 include_descendants: statement.include_descendants,
131 columns: lower_targets(statement.columns, aggregates, &mut subqueries),
132 overriding: statement.overriding,
133 ctes,
134 rows,
135 source,
136 on_conflict,
137 returning,
138 returning_aliases: statement.returning_aliases,
139 subqueries,
140 view_checks: Vec::new(),
141 view_rule_relations: Vec::new(),
142 view_rule_insert_plans: Vec::new(),
143 view_rule_returning: None,
144 }))))
145 }
146 Statement::Update(statement) => {
147 let ctes = lower_ctes(&statement.with, aggregates);
148 let mut subqueries = Vec::new();
149 let source = statement
150 .from
151 .map(|from| SourcePlan::lower_with(from, aggregates, &mut subqueries));
152 let assignments =
153 lower_assignments(statement.assignments, aggregates, &mut subqueries);
154 let predicate = statement
155 .r#where
156 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries));
157 let returning = statement
158 .returning
159 .into_iter()
160 .map(|projection| {
161 ProjectionPlan::lower_with(projection, aggregates, &mut subqueries)
162 })
163 .collect();
164 Self::Command(Box::new(CommandPlan::Update(Box::new(UpdatePlan {
165 table: statement.table,
166 target_relation_bound: statement.target_relation_bound,
167 relations_bound: false,
168 statement_privilege_subject: None,
169 target_privilege_subject: None,
170 target_qualifier: statement.target_qualifier,
171 target_alias: statement.target_alias,
172 include_descendants: statement.include_descendants,
173 assignments,
174 predicate,
175 ctes,
176 source: source.map(Box::new),
177 returning,
178 returning_aliases: statement.returning_aliases,
179 subqueries,
180 view_checks: Vec::new(),
181 view_rule_relations: Vec::new(),
182 view_rule_update_plans: Vec::new(),
183 view_rule_returning: None,
184 }))))
185 }
186 Statement::Delete(statement) => {
187 let ctes = lower_ctes(&statement.with, aggregates);
188 let mut subqueries = Vec::new();
189 let source = statement
190 .using
191 .map(|from| SourcePlan::lower_with(from, aggregates, &mut subqueries));
192 let predicate = statement
193 .r#where
194 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries));
195 let returning = statement
196 .returning
197 .into_iter()
198 .map(|projection| {
199 ProjectionPlan::lower_with(projection, aggregates, &mut subqueries)
200 })
201 .collect();
202 Self::Command(Box::new(CommandPlan::Delete(Box::new(DeletePlan {
203 table: statement.table,
204 target_relation_bound: statement.target_relation_bound,
205 relations_bound: false,
206 statement_privilege_subject: None,
207 target_privilege_subject: None,
208 target_qualifier: statement.target_qualifier,
209 target_alias: statement.target_alias,
210 include_descendants: statement.include_descendants,
211 predicate,
212 ctes,
213 source: source.map(Box::new),
214 returning,
215 returning_aliases: statement.returning_aliases,
216 subqueries,
217 view_rule_relations: Vec::new(),
218 view_rule_returning: None,
219 }))))
220 }
221 Statement::Drop(value) => Self::Command(Box::new(CommandPlan::Drop(value))),
222 Statement::AlterTable(value) => {
223 Self::Command(Box::new(CommandPlan::AlterTable(Box::new(value))))
224 }
225 Statement::AlterForeignTable(value) => {
226 Self::Command(Box::new(CommandPlan::AlterForeignTable(value)))
227 }
228 Statement::AlterView(value) => Self::Command(Box::new(CommandPlan::AlterView(value))),
229 Statement::CreateView {
230 name,
231 column_names,
232 body,
233 or_replace,
234 persistence,
235 options,
236 } => {
237 let query = Box::new(QueryPlan::lower_with(*body, aggregates));
238 Self::Command(Box::new(CommandPlan::CreateView {
239 name,
240 column_names,
241 query,
242 or_replace,
243 persistence,
244 options,
245 }))
246 }
247 Statement::CreateMaterializedView {
248 name,
249 column_names,
250 if_not_exists,
251 with_no_data,
252 options,
253 body,
254 } => Self::Command(Box::new(CommandPlan::CreateMaterializedView {
255 name,
256 column_names,
257 if_not_exists,
258 with_no_data,
259 options,
260 query: Box::new(QueryPlan::lower_with(*body, aggregates)),
261 })),
262 Statement::RefreshMaterializedView {
263 name,
264 concurrently,
265 with_no_data,
266 } => Self::Command(Box::new(CommandPlan::RefreshMaterializedView {
267 name,
268 concurrently,
269 with_no_data,
270 })),
271 Statement::CreateSchema {
272 name,
273 if_not_exists,
274 authorization,
275 } => Self::Command(Box::new(CommandPlan::CreateSchema {
276 name,
277 if_not_exists,
278 authorization,
279 })),
280 Statement::AlterSchemaOwner { name, new_owner } => {
281 Self::Command(Box::new(CommandPlan::AlterSchemaOwner { name, new_owner }))
282 }
283 Statement::RenameSchema { name, new_name } => {
284 Self::Command(Box::new(CommandPlan::RenameSchema { name, new_name }))
285 }
286 Statement::Notify { channel, payload } => {
287 Self::Command(Box::new(CommandPlan::Notify { channel, payload }))
288 }
289 Statement::Listen { channel } => {
290 Self::Command(Box::new(CommandPlan::Listen { channel }))
291 }
292 Statement::Unlisten { channel } => {
293 Self::Command(Box::new(CommandPlan::Unlisten { channel }))
294 }
295 Statement::SetVariable {
296 name,
297 value,
298 local,
299 is_default,
300 } => Self::Command(Box::new(CommandPlan::SetVariable {
301 name,
302 value,
303 local,
304 is_default,
305 })),
306 Statement::ResetVariable { name } => {
307 Self::Command(Box::new(CommandPlan::ResetVariable { name }))
308 }
309 Statement::ResetAllVariables => Self::Command(Box::new(CommandPlan::ResetAllVariables)),
310 Statement::SetConstraints {
311 constraints,
312 deferred,
313 } => Self::Command(Box::new(CommandPlan::SetConstraints {
314 constraints,
315 deferred,
316 })),
317 Statement::ShowVariable { name } => {
318 Self::Command(Box::new(CommandPlan::ShowVariable { name }))
319 }
320 Statement::Discard { target } => {
321 Self::Command(Box::new(CommandPlan::Discard { target }))
322 }
323 Statement::Load { library } => Self::Command(Box::new(CommandPlan::Load { library })),
324 Statement::Explain {
325 analyze,
326 verbose,
327 format,
328 body,
329 } => Self::Command(Box::new(CommandPlan::Explain {
330 analyze,
331 verbose,
332 format,
333 body: Box::new(Self::lower_with(*body, aggregates)),
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 }
637 }
638}