Skip to main content

uqa_sql/catalog/events/
validation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Trigger condition and rule pseudo-relation validation over SQL metadata.
8
9use crate::{
10    ast::{
11        ColumnType, CreateTrigger, Expr, FromClause, OnConflictAction, RuleEvent, SelectStmt,
12        Statement, TableHierarchy, TriggerEvent, TriggerTiming, TriggerTransitionRelation,
13    },
14    plpgsql::{ResolvedVariable, VariableResolver},
15    semantics::rules::action_binding::{
16        first_rule_row_reference_in_expr, first_rule_row_reference_in_select, RuleSourceCatalog,
17    },
18    SQLError,
19};
20use uqa_core::Value;
21
22pub struct TriggerConditionTypeResolver<'a> {
23    pub columns: &'a [crate::ast::ColumnDef],
24}
25
26pub struct RuleRowTypeResolver<'a> {
27    pub columns: &'a [crate::ast::ColumnDef],
28    pub event: RuleEvent,
29    condition: bool,
30    referenced_rows: (bool, bool),
31}
32
33pub struct RuleConditionNameResolver<'a> {
34    pub columns: &'a [crate::ast::ColumnDef],
35    pub event: RuleEvent,
36}
37
38impl VariableResolver for RuleConditionNameResolver<'_> {
39    fn resolve_name(&mut self, _name: &str) -> Result<Option<ResolvedVariable>, SQLError> {
40        Ok(None)
41    }
42
43    fn resolve_qualified(
44        &mut self,
45        _qualifier: &str,
46        _column: &str,
47    ) -> Result<Option<ResolvedVariable>, SQLError> {
48        Ok(None)
49    }
50
51    fn resolve_param(&mut self, _index: usize) -> Result<Option<ResolvedVariable>, SQLError> {
52        Ok(None)
53    }
54
55    fn rewrite_name(&mut self, name: &str) -> Result<Option<Expr>, SQLError> {
56        if !self.columns.iter().any(|column| column.name == name) {
57            if name.eq_ignore_ascii_case("old") || name.eq_ignore_ascii_case("new") {
58                return Ok(None);
59            }
60            return Err(SQLError::UnknownColumn(name.to_string()));
61        }
62        let qualifier = match self.event {
63            RuleEvent::Insert => "new",
64            RuleEvent::Delete => "old",
65            RuleEvent::Update => return Err(SQLError::AmbiguousColumn(name.to_string())),
66            RuleEvent::Select => return Ok(None),
67        };
68        Ok(Some(Expr::qualified_column(qualifier, name)))
69    }
70}
71
72pub(crate) fn unavailable_rule_row(event: RuleEvent, qualifier: &str) -> bool {
73    match qualifier {
74        "old" => matches!(event, RuleEvent::Insert | RuleEvent::Select),
75        "new" => matches!(event, RuleEvent::Delete | RuleEvent::Select),
76        _ => false,
77    }
78}
79
80impl<'a> RuleRowTypeResolver<'a> {
81    pub fn for_condition(columns: &'a [crate::ast::ColumnDef], event: RuleEvent) -> Self {
82        Self {
83            columns,
84            event,
85            condition: true,
86            referenced_rows: (false, false),
87        }
88    }
89
90    pub fn for_action(columns: &'a [crate::ast::ColumnDef], event: RuleEvent) -> Self {
91        Self {
92            condition: false,
93            ..Self::for_condition(columns, event)
94        }
95    }
96
97    pub fn validate_event_references(&self) -> Result<(), SQLError> {
98        let (old, new) = self.referenced_rows;
99        for (referenced, qualifier) in [(old, "old"), (new, "new")] {
100            if referenced && unavailable_rule_row(self.event, qualifier) {
101                return Err(SQLError::Routine {
102                    sqlstate: "42P17".into(),
103                    message: format!(
104                        "ON {} rule cannot use {}",
105                        rule_event_name(self.event),
106                        qualifier.to_ascii_uppercase()
107                    ),
108                });
109            }
110        }
111        Ok(())
112    }
113
114    fn validate_row_qualifier(&mut self, qualifier: &str) -> Result<bool, SQLError> {
115        if !matches!(qualifier, "old" | "new") {
116            return Ok(false);
117        }
118        if self.condition && unavailable_rule_row(self.event, qualifier) {
119            return Err(
120                crate::semantics::rules::action_binding::invalid_rule_relation_reference(qualifier),
121            );
122        }
123        self.referenced_rows.0 |= qualifier == "old";
124        self.referenced_rows.1 |= qualifier == "new";
125        Ok(true)
126    }
127
128    fn record_definition(
129        &mut self,
130        qualifier: &str,
131        column: &str,
132    ) -> Result<Option<&crate::ast::ColumnDef>, SQLError> {
133        if !self.validate_row_qualifier(qualifier)? {
134            return Ok(None);
135        }
136        let definition = self
137            .columns
138            .iter()
139            .find(|definition| definition.name == column)
140            .ok_or_else(|| SQLError::unknown_qualified_column(qualifier, column))?;
141        Ok(Some(definition))
142    }
143}
144
145impl VariableResolver for RuleRowTypeResolver<'_> {
146    fn resolve_name(&mut self, name: &str) -> Result<Option<ResolvedVariable>, SQLError> {
147        if self.condition && unavailable_rule_row(self.event, name) {
148            return Err(SQLError::UnknownColumn(name.into()));
149        }
150        Ok(self
151            .validate_row_qualifier(name)?
152            .then(|| ResolvedVariable::untyped(Value::Record(Vec::new().into()))))
153    }
154
155    fn resolve_qualified(
156        &mut self,
157        qualifier: &str,
158        column: &str,
159    ) -> Result<Option<ResolvedVariable>, SQLError> {
160        Ok(self
161            .record_definition(qualifier, column)?
162            .map(|definition| ResolvedVariable {
163                collation_oid: definition.collation_oid,
164                value: Value::Null,
165                declared_type: Some(definition.ty.catalog_name()),
166            }))
167    }
168
169    fn resolve_param(&mut self, _index: usize) -> Result<Option<ResolvedVariable>, SQLError> {
170        Ok(None)
171    }
172
173    fn rewrite_qualified_whole_row(&mut self, qualifier: &str) -> Result<Option<Expr>, SQLError> {
174        Ok(self
175            .validate_row_qualifier(qualifier)?
176            .then(|| Expr::Literal(Value::Record(Vec::new().into()))))
177    }
178}
179
180const fn rule_event_name(event: RuleEvent) -> &'static str {
181    match event {
182        RuleEvent::Select => "SELECT",
183        RuleEvent::Insert => "INSERT",
184        RuleEvent::Update => "UPDATE",
185        RuleEvent::Delete => "DELETE",
186    }
187}
188
189impl VariableResolver for TriggerConditionTypeResolver<'_> {
190    fn resolve_name(&mut self, _name: &str) -> Result<Option<ResolvedVariable>, SQLError> {
191        Ok(None)
192    }
193
194    fn resolve_qualified(
195        &mut self,
196        qualifier: &str,
197        column: &str,
198    ) -> Result<Option<ResolvedVariable>, SQLError> {
199        if !qualifier.eq_ignore_ascii_case("old") && !qualifier.eq_ignore_ascii_case("new") {
200            return Ok(None);
201        }
202        Ok(self
203            .columns
204            .iter()
205            .find(|definition| definition.name == column)
206            .map(|definition| ResolvedVariable {
207                collation_oid: definition.collation_oid,
208                value: Value::Null,
209                declared_type: Some(definition.ty.catalog_name()),
210            }))
211    }
212
213    fn resolve_param(&mut self, _index: usize) -> Result<Option<ResolvedVariable>, SQLError> {
214        Ok(None)
215    }
216}
217
218pub fn is_boolean_type(ty: &ColumnType) -> bool {
219    match ty {
220        ColumnType::Boolean => true,
221        ColumnType::Domain { base, .. } => is_boolean_type(base),
222        _ => false,
223    }
224}
225
226pub fn rule_action_has_returning(action: &Statement) -> bool {
227    match action {
228        Statement::Insert(statement) => !statement.returning.is_empty(),
229        Statement::Update(statement) => !statement.returning.is_empty(),
230        Statement::Delete(statement) => !statement.returning.is_empty(),
231        _ => false,
232    }
233}
234
235fn same_rule_returning_type_with_different_modifier(
236    actual: &ColumnType,
237    expected: &ColumnType,
238) -> bool {
239    match (actual, expected) {
240        (ColumnType::Varchar(_), ColumnType::Varchar(_))
241        | (ColumnType::Character(_), ColumnType::Character(_))
242        | (ColumnType::Numeric { .. }, ColumnType::Numeric { .. })
243        | (ColumnType::Vector(_), ColumnType::Vector(_))
244        | (ColumnType::Tensor(_), ColumnType::Tensor(_)) => true,
245        (ColumnType::Array(actual), ColumnType::Array(expected)) => {
246            same_rule_returning_type_with_different_modifier(actual, expected)
247        }
248        _ => false,
249    }
250}
251
252pub fn validate_rule_returning_shape(
253    schema: &crate::RowSchema,
254    columns: &[(String, ColumnType)],
255) -> Result<(), SQLError> {
256    if schema.len() < columns.len() {
257        return Err(SQLError::Routine {
258            sqlstate: "42P17".into(),
259            message: "RETURNING list has too few entries".into(),
260        });
261    }
262    if schema.len() > columns.len() {
263        return Err(SQLError::Routine {
264            sqlstate: "42P17".into(),
265            message: "RETURNING list has too many entries".into(),
266        });
267    }
268    for (position, (column, expected)) in columns.iter().enumerate() {
269        let Some(actual) = schema.column_type(position) else {
270            // PostgreSQL resolves an unknown literal against the event row's
271            // declared type when the rule target list is installed.
272            continue;
273        };
274        if actual == expected {
275            continue;
276        }
277        let difference = if same_rule_returning_type_with_different_modifier(actual, expected) {
278            "size"
279        } else {
280            "type"
281        };
282        return Err(SQLError::Diagnostic {
283            sqlstate: "42P17".into(),
284            message: format!(
285                "RETURNING list's entry {} has different {difference} from column \"{column}\"",
286                position + 1
287            ),
288            detail: Some(format!(
289                "RETURNING list entry has type {}, but column has type {}.",
290                actual.sql_name(),
291                expected.sql_name()
292            )),
293            hint: None,
294        });
295    }
296    Ok(())
297}
298
299/// Reject the references `PostgreSQL` reports while it analyzes a trigger WHEN condition: subqueries, unqualified columns and names that are not columns of OLD or NEW.
300pub fn validate_trigger_condition_names(
301    columns: &[crate::ast::ColumnDef],
302    condition: &Expr,
303) -> Result<(), SQLError> {
304    if condition.any_node(&|node| {
305        matches!(
306            node,
307            Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. }
308        )
309    }) {
310        return Err(SQLError::Routine {
311            sqlstate: "0A000".into(),
312            message: "cannot use subquery in trigger WHEN condition".into(),
313        });
314    }
315    if condition.any_node(&|node| matches!(node, Expr::Column(_))) {
316        return Err(SQLError::Routine {
317            sqlstate: "42P01".into(),
318            message: "trigger WHEN condition must qualify row columns with OLD or NEW".into(),
319        });
320    }
321    let invalid_qualified_reference = std::cell::RefCell::new(None);
322    let _ = condition.any_node(&|node| {
323        let Expr::QualifiedColumn { qualifier, column } = node else {
324            return false;
325        };
326        if !qualifier.eq_ignore_ascii_case("old") && !qualifier.eq_ignore_ascii_case("new") {
327            *invalid_qualified_reference.borrow_mut() = Some(format!("{qualifier}.{column}"));
328            return true;
329        }
330        if !columns.iter().any(|definition| definition.name == *column) {
331            *invalid_qualified_reference.borrow_mut() = Some(column.to_string());
332            return true;
333        }
334        false
335    });
336    if let Some(reference) = invalid_qualified_reference.into_inner() {
337        return Err(SQLError::UnknownColumn(reference));
338    }
339    Ok(())
340}
341
342/// Reject the OLD and NEW references a trigger cannot supply, which `PostgreSQL` checks after it has analyzed the whole WHEN condition.
343pub fn validate_trigger_condition_rows(
344    definition: &CreateTrigger,
345    columns: &[crate::ast::ColumnDef],
346    condition: &Expr,
347) -> Result<(), SQLError> {
348    let references_old = condition.any_node(&|node| {
349        matches!(node, Expr::QualifiedColumn { qualifier, .. } if qualifier.eq_ignore_ascii_case("old"))
350    });
351    let references_new = condition.any_node(&|node| {
352        matches!(node, Expr::QualifiedColumn { qualifier, .. } if qualifier.eq_ignore_ascii_case("new"))
353    });
354    if !definition.row && (references_old || references_new) {
355        return Err(SQLError::Routine {
356            sqlstate: "42P17".into(),
357            message: "statement trigger's WHEN condition cannot reference column values".into(),
358        });
359    }
360    if references_old && definition.events.contains(&TriggerEvent::Insert) {
361        return Err(SQLError::Routine {
362            sqlstate: "42P17".into(),
363            message: "INSERT trigger's WHEN condition cannot reference OLD values".into(),
364        });
365    }
366    if references_new && definition.events.contains(&TriggerEvent::Delete) {
367        return Err(SQLError::Routine {
368            sqlstate: "42P17".into(),
369            message: "DELETE trigger's WHEN condition cannot reference NEW values".into(),
370        });
371    }
372    if definition.timing == TriggerTiming::Before && references_new {
373        let generated = columns
374            .iter()
375            .filter(|column| column.generated.is_some())
376            .map(|column| column.name.as_str())
377            .collect::<std::collections::BTreeSet<_>>();
378        if condition.any_node(&|node| {
379            matches!(
380                node,
381                Expr::QualifiedColumn { qualifier, column }
382                    if qualifier.eq_ignore_ascii_case("new")
383                        && generated.contains(column.as_str())
384            )
385        }) {
386            return Err(SQLError::Routine {
387                sqlstate: "42P17".into(),
388                message: "BEFORE trigger's WHEN condition cannot reference NEW generated columns"
389                    .into(),
390            });
391        }
392    }
393    Ok(())
394}
395
396pub fn first_invalid_rule_condition_qualifier(condition: &Expr) -> Option<String> {
397    let invalid = std::cell::RefCell::new(None);
398    let _ = condition.any_node(&|node| {
399        let Expr::QualifiedColumn { qualifier, .. } = node else {
400            return false;
401        };
402        if qualifier.eq_ignore_ascii_case("old") || qualifier.eq_ignore_ascii_case("new") {
403            return false;
404        }
405        *invalid.borrow_mut() = Some(qualifier.clone());
406        true
407    });
408    invalid.into_inner()
409}
410
411fn invalid_rule_cte_reference(qualifier: &str) -> SQLError {
412    SQLError::Routine {
413        sqlstate: "0A000".into(),
414        message: format!(
415            "cannot refer to {} within WITH query",
416            qualifier.to_ascii_uppercase()
417        ),
418    }
419}
420
421fn invalid_rule_set_operation_reference() -> SQLError {
422    SQLError::Routine {
423        sqlstate: "42P10".into(),
424        message:
425            "UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"
426                .into(),
427    }
428}
429
430pub(super) use crate::semantics::rules::action_binding::invalid_rule_relation_reference;
431
432fn ambiguous_rule_pseudo_relation(qualifier: &str) -> SQLError {
433    SQLError::Routine {
434        sqlstate: "42P09".into(),
435        message: format!("table reference \"{qualifier}\" is ambiguous"),
436    }
437}
438
439fn duplicate_rule_pseudo_relation(qualifier: &str) -> SQLError {
440    SQLError::Routine {
441        sqlstate: "42712".into(),
442        message: format!("table name \"{qualifier}\" specified more than once"),
443    }
444}
445
446fn rule_pseudo_relation_name(name: &str) -> Option<String> {
447    (name.eq_ignore_ascii_case("old") || name.eq_ignore_ascii_case("new"))
448        .then(|| name.to_ascii_lowercase())
449}
450
451fn first_rule_pseudo_relation_in_from(from: &FromClause) -> Option<String> {
452    match from {
453        crate::ast::FromClause::RetainedRows(_) => None,
454        FromClause::Table {
455            name,
456            qualifier,
457            alias,
458            ..
459        } => alias
460            .as_deref()
461            .and_then(rule_pseudo_relation_name)
462            .or_else(|| rule_pseudo_relation_name(qualifier))
463            .or_else(|| rule_pseudo_relation_name(name))
464            .or_else(|| {
465                name.rsplit_once('.')
466                    .and_then(|(_, local)| rule_pseudo_relation_name(local.trim_matches('"')))
467            }),
468        FromClause::Join {
469            left, right, alias, ..
470        } => alias
471            .as_deref()
472            .and_then(rule_pseudo_relation_name)
473            .or_else(|| first_rule_pseudo_relation_in_from(left))
474            .or_else(|| first_rule_pseudo_relation_in_from(right)),
475        FromClause::Values { alias, .. } | FromClause::Subquery { alias, .. } => {
476            alias.as_deref().and_then(rule_pseudo_relation_name)
477        }
478        FromClause::Function {
479            output_name, alias, ..
480        } => rule_pseudo_relation_name(alias.as_deref().unwrap_or(output_name)),
481        FromClause::FunctionGroup {
482            functions, alias, ..
483        } => alias
484            .as_deref()
485            .and_then(rule_pseudo_relation_name)
486            .or_else(|| {
487                functions
488                    .iter()
489                    .find_map(|function| rule_pseudo_relation_name(&function.output_name))
490            }),
491    }
492}
493
494fn validate_rule_action_select_namespace(select: &SelectStmt) -> Result<(), SQLError> {
495    let duplicate = select
496        .with
497        .iter()
498        .find_map(|cte| rule_pseudo_relation_name(&cte.name))
499        .or_else(|| {
500            select
501                .from
502                .as_ref()
503                .and_then(first_rule_pseudo_relation_in_from)
504        });
505    if let Some(qualifier) = duplicate {
506        return Err(duplicate_rule_pseudo_relation(&qualifier));
507    }
508    Ok(())
509}
510
511fn validate_rule_action_namespace(
512    catalog: &dyn RuleSourceCatalog,
513    action: &Statement,
514) -> Result<(), SQLError> {
515    let (ctes, source) = match action {
516        Statement::Select(select) => return validate_rule_action_select_namespace(select),
517        Statement::Insert(insert) => (insert.with.as_slice(), insert.select_source.as_deref()),
518        Statement::Update(update) => {
519            if let Some(qualifier) = update
520                .from
521                .as_ref()
522                .and_then(first_rule_pseudo_relation_in_from)
523            {
524                return Err(duplicate_rule_pseudo_relation(&qualifier));
525            }
526            if let Some(qualifier) = rule_pseudo_relation_name(&update.target_qualifier) {
527                if crate::semantics::rules::action_binding::action_target_qualifier_referenced(
528                    catalog, action, &qualifier,
529                ) {
530                    return Err(ambiguous_rule_pseudo_relation(&qualifier));
531                }
532            }
533            (update.with.as_slice(), None)
534        }
535        Statement::Delete(delete) => {
536            if let Some(qualifier) = delete
537                .using
538                .as_ref()
539                .and_then(first_rule_pseudo_relation_in_from)
540            {
541                return Err(duplicate_rule_pseudo_relation(&qualifier));
542            }
543            if let Some(qualifier) = rule_pseudo_relation_name(&delete.target_qualifier) {
544                if crate::semantics::rules::action_binding::action_target_qualifier_referenced(
545                    catalog, action, &qualifier,
546                ) {
547                    return Err(ambiguous_rule_pseudo_relation(&qualifier));
548                }
549            }
550            (delete.with.as_slice(), None)
551        }
552        _ => return Ok(()),
553    };
554    if let Some(qualifier) = ctes
555        .iter()
556        .find_map(|cte| rule_pseudo_relation_name(&cte.name))
557    {
558        return Err(duplicate_rule_pseudo_relation(&qualifier));
559    }
560    if let Some(select) = source {
561        validate_rule_action_select_namespace(select)?;
562    }
563    Ok(())
564}
565
566fn validate_rule_ctes(
567    catalog: &dyn RuleSourceCatalog,
568    ctes: &[crate::ast::CTE],
569) -> Result<(), SQLError> {
570    for cte in ctes {
571        let statement = cte.body.clone().into_statement();
572        if let Some(qualifier) =
573            crate::semantics::rules::action_binding::first_rule_row_reference_in_statement(
574                catalog, &statement,
575            )?
576        {
577            return Err(invalid_rule_cte_reference(&qualifier));
578        }
579        validate_rule_action_reference_scopes(catalog, &statement)?;
580    }
581    Ok(())
582}
583
584fn validate_rule_select_scopes(
585    catalog: &dyn RuleSourceCatalog,
586    select: &SelectStmt,
587) -> Result<(), SQLError> {
588    validate_rule_ctes(catalog, &select.with)?;
589    if let Some(set_op) = &select.set_op {
590        let member_references_rule_row = set_op
591            .left
592            .as_deref()
593            .and_then(|left| first_rule_row_reference_in_select(catalog, left))
594            .or_else(|| first_rule_row_reference_in_select(catalog, &set_op.right));
595        if member_references_rule_row.is_some() {
596            return Err(invalid_rule_set_operation_reference());
597        }
598        if let Some(left) = set_op.left.as_deref() {
599            validate_rule_select_scopes(catalog, left)?;
600        }
601        validate_rule_select_scopes(catalog, &set_op.right)?;
602        for order in &set_op.combined_order_by {
603            validate_rule_expr_scopes(catalog, &order.expr)?;
604        }
605        if let Some(limit) = &set_op.combined_limit {
606            validate_rule_expr_scopes(catalog, limit)?;
607        }
608        if let Some(offset) = &set_op.combined_offset {
609            validate_rule_expr_scopes(catalog, offset)?;
610        }
611    }
612    for projection in &select.projections {
613        validate_rule_expr_scopes(catalog, &projection.expr)?;
614    }
615    for expr in select.values.iter().flatten() {
616        validate_rule_expr_scopes(catalog, expr)?;
617    }
618    if let Some(from) = &select.from {
619        validate_rule_from_scopes(catalog, from)?;
620    }
621    for expr in select
622        .r#where
623        .iter()
624        .chain(select.group_by.iter())
625        .chain(select.grouping_sets.iter().flatten())
626        .chain(select.having.iter())
627        .chain(select.order_by.iter().map(|order| &order.expr))
628        .chain(select.limit.iter())
629        .chain(select.offset.iter())
630        .chain(select.distinct_on.iter())
631    {
632        validate_rule_expr_scopes(catalog, expr)?;
633    }
634    Ok(())
635}
636
637fn validate_rule_from_scopes(
638    catalog: &dyn RuleSourceCatalog,
639    from: &FromClause,
640) -> Result<(), SQLError> {
641    match from {
642        crate::ast::FromClause::RetainedRows(_) => {}
643        FromClause::Table { .. } => {}
644        FromClause::Join {
645            left, right, on, ..
646        } => {
647            validate_rule_from_scopes(catalog, left)?;
648            validate_rule_from_scopes(catalog, right)?;
649            if let Some(on) = on {
650                validate_rule_expr_scopes(catalog, on)?;
651            }
652        }
653        FromClause::Values { rows, .. } => {
654            for expr in rows.iter().flatten() {
655                validate_rule_expr_scopes(catalog, expr)?;
656            }
657        }
658        FromClause::Function { args, .. } => {
659            for expr in args {
660                validate_rule_expr_scopes(catalog, expr)?;
661            }
662        }
663        FromClause::FunctionGroup { functions, .. } => {
664            for expr in functions.iter().flat_map(|function| &function.args) {
665                validate_rule_expr_scopes(catalog, expr)?;
666            }
667        }
668        FromClause::Subquery { body, .. } => validate_rule_select_scopes(catalog, body)?,
669    }
670    Ok(())
671}
672
673fn validate_rule_expr_scopes(catalog: &dyn RuleSourceCatalog, expr: &Expr) -> Result<(), SQLError> {
674    match expr {
675        Expr::Func {
676            args,
677            order_by,
678            filter,
679            ..
680        } => {
681            for expr in args {
682                validate_rule_expr_scopes(catalog, expr)?;
683            }
684            for order in order_by {
685                validate_rule_expr_scopes(catalog, &order.expr)?;
686            }
687            if let Some(filter) = filter {
688                validate_rule_expr_scopes(catalog, filter)?;
689            }
690        }
691        Expr::Array(items)
692        | Expr::Row(items)
693        | Expr::CompositeRow { items, .. }
694        | Expr::And(items)
695        | Expr::Or(items) => {
696            for expr in items {
697                validate_rule_expr_scopes(catalog, expr)?;
698            }
699        }
700        Expr::Binary { lhs, rhs, .. } => {
701            validate_rule_expr_scopes(catalog, lhs)?;
702            validate_rule_expr_scopes(catalog, rhs)?;
703        }
704        Expr::UnaryMinus(expr)
705        | Expr::Not(expr)
706        | Expr::IsNull { expr, .. }
707        | Expr::Cast { expr, .. } => validate_rule_expr_scopes(catalog, expr)?,
708        Expr::Between { expr, low, high } => {
709            validate_rule_expr_scopes(catalog, expr)?;
710            validate_rule_expr_scopes(catalog, low)?;
711            validate_rule_expr_scopes(catalog, high)?;
712        }
713        Expr::InList { expr, list, .. } => {
714            validate_rule_expr_scopes(catalog, expr)?;
715            for item in list {
716                validate_rule_expr_scopes(catalog, item)?;
717            }
718        }
719        Expr::WindowCall {
720            args, spec, filter, ..
721        } => {
722            for expr in args
723                .iter()
724                .chain(filter.iter().map(AsRef::as_ref))
725                .chain(spec.partition_by.iter())
726            {
727                validate_rule_expr_scopes(catalog, expr)?;
728            }
729            for order in &spec.order_by {
730                validate_rule_expr_scopes(catalog, &order.expr)?;
731            }
732        }
733        Expr::Case {
734            base,
735            when,
736            else_branch,
737        } => {
738            if let Some(base) = base {
739                validate_rule_expr_scopes(catalog, base)?;
740            }
741            for (condition, result) in when {
742                validate_rule_expr_scopes(catalog, condition)?;
743                validate_rule_expr_scopes(catalog, result)?;
744            }
745            if let Some(else_branch) = else_branch {
746                validate_rule_expr_scopes(catalog, else_branch)?;
747            }
748        }
749        Expr::ScalarSubquery(body) | Expr::Exists { body, .. } => {
750            validate_rule_select_scopes(catalog, body)?;
751        }
752        Expr::InSubquery { expr, body, .. } => {
753            validate_rule_expr_scopes(catalog, expr)?;
754            validate_rule_select_scopes(catalog, body)?;
755        }
756        Expr::Default
757        | Expr::Literal(_)
758        | Expr::TypedLiteral { .. }
759        | Expr::RetainedLiteral(_)
760        | Expr::Star
761        | Expr::QualifiedStar(_)
762        | Expr::Column(_)
763        | Expr::QualifiedColumn { .. }
764        | Expr::InternalColumn(_)
765        | Expr::Param(_) => {}
766    }
767    Ok(())
768}
769
770pub fn validate_rule_action_reference_scopes(
771    catalog: &dyn RuleSourceCatalog,
772    action: &Statement,
773) -> Result<(), SQLError> {
774    validate_rule_action_namespace(catalog, action)?;
775    match action {
776        Statement::Select(select) => validate_rule_select_scopes(catalog, select),
777        Statement::Insert(insert) => {
778            validate_rule_ctes(catalog, &insert.with)?;
779            for expr in insert
780                .columns
781                .iter()
782                .flat_map(crate::ast::AssignmentTarget::expressions)
783                .chain(insert.rows.iter().flatten())
784            {
785                validate_rule_expr_scopes(catalog, expr)?;
786            }
787            if let Some(select) = &insert.select_source {
788                validate_rule_select_scopes(catalog, select)?;
789            }
790            if let Some(conflict) = &insert.on_conflict {
791                for expression in &conflict.expressions {
792                    validate_rule_expr_scopes(catalog, expression)?;
793                }
794                if let Some(predicate) = conflict.predicate.as_deref() {
795                    validate_rule_expr_scopes(catalog, predicate)?;
796                }
797                if let OnConflictAction::Update {
798                    assignments,
799                    r#where,
800                } = &conflict.action
801                {
802                    let reference = assignments
803                        .iter()
804                        .flat_map(|(target, value)| {
805                            target.expressions().chain(std::iter::once(value))
806                        })
807                        .find_map(|expr| {
808                            let mut shadowed = std::collections::BTreeSet::new();
809                            shadowed.insert(insert.target_qualifier.to_ascii_lowercase());
810                            first_rule_row_reference_in_expr(expr, &shadowed)
811                        })
812                        .or_else(|| {
813                            r#where.as_ref().and_then(|expr| {
814                                let mut shadowed = std::collections::BTreeSet::new();
815                                shadowed.insert(insert.target_qualifier.to_ascii_lowercase());
816                                first_rule_row_reference_in_expr(expr, &shadowed)
817                            })
818                        });
819                    if let Some(qualifier) = reference {
820                        return Err(invalid_rule_relation_reference(&qualifier));
821                    }
822                    for expr in assignments.iter().flat_map(|(target, value)| {
823                        target.expressions().chain(std::iter::once(value))
824                    }) {
825                        validate_rule_expr_scopes(catalog, expr)?;
826                    }
827                    if let Some(r#where) = r#where {
828                        validate_rule_expr_scopes(catalog, r#where)?;
829                    }
830                }
831            }
832            for projection in &insert.returning {
833                validate_rule_expr_scopes(catalog, &projection.expr)?;
834            }
835            Ok(())
836        }
837        Statement::Update(update) => {
838            validate_rule_ctes(catalog, &update.with)?;
839            if let Some(from) = &update.from {
840                validate_rule_from_scopes(catalog, from)?;
841            }
842            for expr in update
843                .assignments
844                .iter()
845                .flat_map(|(target, value)| target.expressions().chain(std::iter::once(value)))
846                .chain(update.r#where.iter())
847                .chain(update.returning.iter().map(|projection| &projection.expr))
848            {
849                validate_rule_expr_scopes(catalog, expr)?;
850            }
851            Ok(())
852        }
853        Statement::Delete(delete) => {
854            validate_rule_ctes(catalog, &delete.with)?;
855            if let Some(using) = &delete.using {
856                validate_rule_from_scopes(catalog, using)?;
857            }
858            for expr in delete
859                .r#where
860                .iter()
861                .chain(delete.returning.iter().map(|projection| &projection.expr))
862            {
863                validate_rule_expr_scopes(catalog, expr)?;
864            }
865            Ok(())
866        }
867        _ => Ok(()),
868    }
869}
870
871pub fn validate_trigger_transition_relation(
872    definition: &CreateTrigger,
873    hierarchy: &TableHierarchy,
874    transition: &TriggerTransitionRelation,
875) -> Result<(), SQLError> {
876    if !transition.is_table {
877        return Err(SQLError::Routine {
878            sqlstate: "0A000".into(),
879            message: "ROW variable naming in the REFERENCING clause is not supported".into(),
880        });
881    }
882    if definition.row && !hierarchy.parents.is_empty() {
883        return Err(SQLError::Routine {
884            sqlstate: "0A000".into(),
885            message: if hierarchy.partition_bound.is_some() {
886                "ROW triggers with transition tables are not supported on partitions".into()
887            } else {
888                "ROW triggers with transition tables are not supported on inheritance children"
889                    .into()
890            },
891        });
892    }
893    if definition.timing != TriggerTiming::After {
894        return Err(SQLError::Routine {
895            sqlstate: "42P17".into(),
896            message: "transition table name can only be specified for an AFTER trigger".into(),
897        });
898    }
899    if definition.events.contains(&TriggerEvent::Truncate) {
900        return Err(SQLError::Routine {
901            sqlstate: "0A000".into(),
902            message: "TRUNCATE triggers with transition tables are not supported".into(),
903        });
904    }
905    let mutation_events = definition
906        .events
907        .iter()
908        .filter(|event| {
909            matches!(
910                event,
911                TriggerEvent::Insert | TriggerEvent::Update | TriggerEvent::Delete
912            )
913        })
914        .count();
915    if mutation_events != 1 {
916        return Err(SQLError::Routine {
917            sqlstate: "0A000".into(),
918            message: "transition tables cannot be specified for triggers with more than one event"
919                .into(),
920        });
921    }
922    if !definition.update_columns.is_empty() {
923        return Err(SQLError::Routine {
924            sqlstate: "0A000".into(),
925            message: "transition tables cannot be specified for triggers with column lists".into(),
926        });
927    }
928    let valid_event = definition.events.iter().any(|event| {
929        if transition.is_new {
930            matches!(event, TriggerEvent::Insert | TriggerEvent::Update)
931        } else {
932            matches!(event, TriggerEvent::Delete | TriggerEvent::Update)
933        }
934    });
935    if !valid_event {
936        return Err(SQLError::Routine {
937            sqlstate: "42P17".into(),
938            message: format!(
939                "{} TABLE can only be specified for {} trigger",
940                if transition.is_new { "NEW" } else { "OLD" },
941                if transition.is_new {
942                    "an INSERT or UPDATE"
943                } else {
944                    "a DELETE or UPDATE"
945                }
946            ),
947        });
948    }
949    Ok(())
950}
951
952#[cfg(test)]
953mod tests;