Skip to main content

uqa_sql/prepared/
utility.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Session-owned utility descriptors and the distinction between analyzed and unplanned statements.
8
9use crate::{
10    plan::{CommandPlan, UnifiedPlan},
11    RowSchema, SQLError, Statement,
12};
13
14/// Read existing descriptors without executing a utility or advancing a portal.
15pub trait PreparedSessionMetadata {
16    fn show_result_schema(&self, name: &str) -> Result<RowSchema, SQLError>;
17    fn portal_result_schema(&self, name: &str) -> Option<RowSchema>;
18    fn prepared_result_schema(&self, name: &str) -> Option<RowSchema>;
19}
20
21/// Utilities whose bodies undergo parse analysis also require a planning snapshot and cache revalidation. Other utilities retain their original result descriptor even when the session object used at execution changes.
22pub fn requires_analysis(plan: &UnifiedPlan) -> bool {
23    match plan {
24        UnifiedPlan::Query(_) => true,
25        UnifiedPlan::Command(command) => matches!(
26            command.as_ref(),
27            CommandPlan::Insert(_)
28                | CommandPlan::Update(_)
29                | CommandPlan::Delete(_)
30                | CommandPlan::Merge(_)
31                | CommandPlan::Call { .. }
32                | CommandPlan::Explain { .. }
33                | CommandPlan::DeclareCursor { .. }
34                | CommandPlan::CreateTableAs { .. }
35                | CommandPlan::CreateMaterializedView { .. }
36        ),
37    }
38}
39
40pub fn statement_requires_analysis(statement: &Statement) -> bool {
41    matches!(
42        statement,
43        Statement::Select(_)
44            | Statement::Insert(_)
45            | Statement::Update(_)
46            | Statement::Delete(_)
47            | Statement::Merge(_)
48            | Statement::Call { .. }
49            | Statement::Explain { .. }
50            | Statement::DeclareCursor(_)
51            | Statement::CreateTableAs { .. }
52            | Statement::CreateMaterializedView { .. }
53    )
54}
55
56pub fn result_schema(
57    session: &dyn PreparedSessionMetadata,
58    plan: &UnifiedPlan,
59) -> Result<Option<RowSchema>, SQLError> {
60    let UnifiedPlan::Command(command) = plan else {
61        return Ok(None);
62    };
63    match command.as_ref() {
64        CommandPlan::ShowVariable { name } => session.show_result_schema(name).map(Some),
65        CommandPlan::FetchCursor(fetch) if !fetch.move_only => {
66            Ok(session.portal_result_schema(&fetch.name))
67        }
68        CommandPlan::Execute { name, .. } => Ok(session.prepared_result_schema(name)),
69        _ => Ok(None),
70    }
71}