Skip to main content

uqa_sql/semantics/
cte_validation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! `PostgreSQL` statement ownership rules for data-modifying WITH definitions.
8
9use super::rules::RuleCatalog;
10use crate::plan::{
11    CommandPlan, CtePlan, CtePlanBody, QueryPlan, RelationalPlan, SourcePlan, UnifiedPlan,
12};
13use crate::SQLError;
14
15pub struct CteValidationContext<'a> {
16    pub catalog: &'a dyn RuleCatalog,
17}
18
19pub fn validate_plan(
20    context: &CteValidationContext<'_>,
21    plan: &UnifiedPlan,
22) -> Result<(), SQLError> {
23    match plan {
24        UnifiedPlan::Query(query) => validate_query(context, query, true),
25        UnifiedPlan::Command(command) => validate_command(context, command, true),
26    }
27}
28
29fn contains_command(ctes: &[CtePlan]) -> bool {
30    ctes.iter().any(|cte| cte.body.modifies_data())
31}
32
33fn validate_ctes(
34    context: &CteValidationContext<'_>,
35    ctes: &[CtePlan],
36    top_level: bool,
37) -> Result<(), SQLError> {
38    if !top_level && contains_command(ctes) {
39        return Err(SQLError::Unsupported(
40            "WITH clause containing a data-modifying statement must be at the top level".into(),
41        ));
42    }
43    for cte in ctes {
44        if cte.recursive
45            && cte.body.modifies_data()
46            && crate::semantics::cte_references_own_name(cte)
47        {
48            return Err(SQLError::Routine {
49                sqlstate: "42P19".into(),
50                message: format!(
51                    "recursive query \"{}\" must not contain data-modifying statements",
52                    cte.name
53                ),
54            });
55        }
56        match &cte.body {
57            CtePlanBody::Query(query) => validate_query(context, query, false)?,
58            CtePlanBody::Command(command) => {
59                validate_command(context, command, false)?;
60                validate_command_rules(context, command)?;
61            }
62        }
63    }
64    Ok(())
65}
66
67fn validate_query(
68    context: &CteValidationContext<'_>,
69    query: &QueryPlan,
70    top_level: bool,
71) -> Result<(), SQLError> {
72    validate_ctes(context, &query.ctes, top_level)?;
73    match &query.root {
74        RelationalPlan::QueryBlock(block) => {
75            if let Some(source) = &block.from {
76                validate_source(context, source)?;
77            }
78            for query in &block.subqueries {
79                validate_query(context, query, false)?;
80            }
81        }
82        RelationalPlan::SetOp {
83            left,
84            right,
85            subqueries,
86            ..
87        } => {
88            validate_query(context, left, false)?;
89            validate_query(context, right, false)?;
90            for query in subqueries {
91                validate_query(context, query, false)?;
92            }
93        }
94        RelationalPlan::Values { subqueries, .. } => {
95            for query in subqueries {
96                validate_query(context, query, false)?;
97            }
98        }
99    }
100    Ok(())
101}
102
103fn validate_source(
104    context: &CteValidationContext<'_>,
105    source: &SourcePlan,
106) -> Result<(), SQLError> {
107    match source {
108        crate::plan::SourcePlan::RetainedRows(_) => Ok(()),
109        SourcePlan::Subquery { body, .. } => validate_query(context, body, false),
110        SourcePlan::Join { left, right, .. } => {
111            validate_source(context, left)?;
112            validate_source(context, right)
113        }
114        SourcePlan::Table { .. }
115        | SourcePlan::Values { .. }
116        | SourcePlan::Function { .. }
117        | SourcePlan::FunctionGroup { .. } => Ok(()),
118    }
119}
120
121fn validate_command(
122    context: &CteValidationContext<'_>,
123    command: &CommandPlan,
124    top_level: bool,
125) -> Result<(), SQLError> {
126    validate_ctes(context, command.ctes(), top_level)?;
127    for query in command.query_inputs() {
128        validate_query(context, query, false)?;
129    }
130    if let Some(source) = command.source_input() {
131        validate_source(context, source)?;
132    }
133    match command {
134        CommandPlan::CreateView { query, .. } => validate_query_owner(
135            context,
136            query,
137            "views must not contain data-modifying statements in WITH",
138        ),
139        CommandPlan::CreateMaterializedView { query, .. } => validate_query_owner(
140            context,
141            query,
142            "materialized views must not use data-modifying statements in WITH",
143        ),
144        CommandPlan::DeclareCursor { query, .. } => validate_query_owner(
145            context,
146            query,
147            "DECLARE CURSOR must not contain data-modifying statements in WITH",
148        ),
149        CommandPlan::CreateTableAs { query, .. } => validate_query(context, query, true),
150        CommandPlan::Explain { body, .. } | CommandPlan::Prepare { body, .. } => {
151            validate_plan(context, body)
152        }
153        _ => Ok(()),
154    }
155}
156
157fn validate_query_owner(
158    context: &CteValidationContext<'_>,
159    query: &QueryPlan,
160    message: &str,
161) -> Result<(), SQLError> {
162    validate_query(context, query, true)?;
163    if contains_command(&query.ctes) {
164        return Err(SQLError::Unsupported(message.into()));
165    }
166    Ok(())
167}
168
169fn validate_command_rules(
170    context: &CteValidationContext<'_>,
171    command: &CommandPlan,
172) -> Result<(), SQLError> {
173    use crate::ast::RuleEvent;
174    let (table, bound, event) = match command {
175        CommandPlan::Insert(plan) => (
176            plan.table.as_str(),
177            plan.target_relation_bound,
178            RuleEvent::Insert,
179        ),
180        CommandPlan::Update(plan) => (
181            plan.table.as_str(),
182            plan.target_relation_bound,
183            RuleEvent::Update,
184        ),
185        CommandPlan::Delete(plan) => (
186            plan.table.as_str(),
187            plan.target_relation_bound,
188            RuleEvent::Delete,
189        ),
190        _ => return Ok(()),
191    };
192    let table = context.catalog.resolve_mutation_target(table, bound)?;
193    if crate::catalog::VirtualRelation::from_qualified_name(&table).is_some() {
194        // Virtual catalog relations have no entries in the stored rewrite-rule registry.
195        return Ok(());
196    }
197    let rules = context.catalog.rules_for(&table, event)?;
198    if rules.is_empty() {
199        return Ok(());
200    }
201    super::rules::validate_rule_returning_contract(
202        context.catalog,
203        &table,
204        event,
205        command
206            .returning()
207            .is_some_and(|returning| !returning.is_empty()),
208    )?;
209    for rule in rules {
210        let rule = &rule.definition;
211        let kind = if !rule.instead && !rule.actions.is_empty() {
212            Some("DO ALSO")
213        } else if rule.instead && rule.condition.is_some() {
214            Some("conditional DO INSTEAD")
215        } else if rule.instead && rule.actions.is_empty() {
216            Some("DO INSTEAD NOTHING")
217        } else if rule.instead && rule.actions.len() > 1 {
218            Some("multi-statement DO INSTEAD")
219        } else {
220            None
221        };
222        if let Some(kind) = kind {
223            return Err(SQLError::Unsupported(format!(
224                "{kind} rules are not supported for data-modifying statements in WITH"
225            )));
226        }
227    }
228    Ok(())
229}