Skip to main content

uqa_execution/mutation/views/commands/
checks.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Check the rows that a view's `INSTEAD OF` triggers return against the check options of the views a statement was rewritten through to reach it.
8
9use super::{target_row, CteScope, SQLError, SQLParam, Value, ViewDmlTarget};
10use crate::mutation::{
11    constraints::{trigger_view_check_violation, ConstraintContext},
12    expressions::eval_mutation_expr,
13    rows::context::MutationExpressionContext,
14};
15use uqa_sql::plan::ViewCheckPlan;
16
17/// A statement that automatically updatable views rewrote to `target`, a view whose `INSTEAD OF` triggers store its rows.
18pub struct TriggerViewChecks<'a, S: Clone + 'static> {
19    pub expressions: MutationExpressionContext<'a, S>,
20    /// The catalog and authority that describe a row a check option rejects.
21    pub constraints: ConstraintContext<'a>,
22    pub target: &'a ViewDmlTarget,
23    pub target_qualifier: &'a str,
24    /// The check options of the views the statement was rewritten through, inner views first.
25    pub checks: &'a [ViewCheckPlan],
26    /// The columns of `target` the statement inserts or updates.
27    pub supplied: &'a [String],
28    pub params: &'a [SQLParam],
29    pub scope: &'a CteScope<S>,
30}
31
32impl<S: Clone + 'static> TriggerViewChecks<'_, S> {
33    /// Check the row a trigger returned, which `ExecInsert` and `ExecUpdateEpilogue` pass to `ExecWithCheckOptions` after the trigger has stored it: a check that is not true rejects the row.
34    pub fn validate(&self, values: &[Value]) -> Result<(), SQLError> {
35        if self.checks.is_empty() {
36            return Ok(());
37        }
38        let row = target_row(self.target, self.target_qualifier, values)?;
39        for check in self.checks {
40            let value = eval_mutation_expr(
41                self.expressions,
42                self.scope,
43                &check.predicate,
44                Some(&row),
45                self.params,
46            )?;
47            if !uqa_sql::expr::truthy(&value) {
48                return Err(trigger_view_check_violation(
49                    self.constraints,
50                    &check.view,
51                    self.target,
52                    self.supplied,
53                    values,
54                ));
55            }
56        }
57        Ok(())
58    }
59}