Skip to main content

uqa_sql/semantics/view_rewrite/
validation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Public-view and mapped-target validation for automatic DML rewriting.
8
9use super::updatability::{non_writable_column, ColumnWrite, ViewCommand};
10pub(super) mod production;
11
12#[cfg(test)]
13use super::BTreeSet;
14use super::{
15    AutomaticViewLayer, ConflictActionPlan, ConflictPlan, DeletePlan, InsertPlan, MergePlan,
16    MergeWhenPlan, ReturningAliases, RowSchema, SQLError, ScalarExpr, TriggerEvent, UpdatePlan,
17    ViewColumn, ViewRewriteContext,
18};
19
20#[cfg(test)]
21mod tests;
22
23pub(super) fn layer_column<'a>(
24    layer: &'a AutomaticViewLayer,
25    name: &str,
26) -> Option<&'a ViewColumn> {
27    layer.columns.iter().find(|column| column.name == name)
28}
29
30fn unknown_view_column(layer: &AutomaticViewLayer, column: &str) -> SQLError {
31    SQLError::UnknownColumn(format!("{}.{column}", layer.canonical_name))
32}
33
34pub(super) fn duplicate_insert_column(column: &str) -> SQLError {
35    SQLError::Routine {
36        sqlstate: "42701".into(),
37        message: format!("column \"{column}\" specified more than once"),
38    }
39}
40
41pub(super) fn duplicate_assignment(column: &str) -> SQLError {
42    SQLError::Routine {
43        sqlstate: "42601".into(),
44        message: format!("multiple assignments to same column \"{column}\""),
45    }
46}
47
48fn ambiguous_column(column: &str) -> SQLError {
49    SQLError::Routine {
50        sqlstate: "42702".into(),
51        message: format!("column reference \"{column}\" is ambiguous"),
52    }
53}
54
55#[derive(Clone, Copy)]
56pub(super) struct ExpressionScope<'a> {
57    pub(super) target_qualifier: &'a str,
58    pub(super) returning_aliases: Option<&'a ReturningAliases>,
59    pub(super) source: Option<&'a RowSchema>,
60    pub(super) include_excluded: bool,
61}
62
63impl ExpressionScope<'_> {
64    pub(super) fn row_image_qualifier(self, qualifier: &str) -> bool {
65        self.returning_aliases.is_some_and(|aliases| {
66            [
67                (aliases.old.as_str(), aliases.old_explicit),
68                (aliases.new.as_str(), aliases.new_explicit),
69            ]
70            .into_iter()
71            .any(|(alias, explicit)| {
72                qualifier == alias
73                    && (explicit
74                        || !self
75                            .source
76                            .is_some_and(|source| source.has_qualifier(alias)))
77            })
78        })
79    }
80
81    pub(super) fn target_qualifier(self, qualifier: &str) -> bool {
82        qualifier == self.target_qualifier
83            || (self.include_excluded && qualifier == "excluded")
84            || self.row_image_qualifier(qualifier)
85    }
86}
87
88#[cfg(test)]
89pub(super) fn validate_view_expression(
90    expression: &ScalarExpr,
91    layer: &AutomaticViewLayer,
92    scope: ExpressionScope<'_>,
93) -> Result<(), SQLError> {
94    validate_reference_columns(
95        expression,
96        &|column| layer_column(layer, column).is_some(),
97        scope,
98    )
99}
100
101#[cfg(test)]
102fn validate_reference_columns(
103    expression: &ScalarExpr,
104    contains: &dyn Fn(&str) -> bool,
105    scope: ExpressionScope<'_>,
106) -> Result<(), SQLError> {
107    production::reference_columns(
108        expression,
109        contains,
110        scope,
111        &uqa_core::memory::ProductionControl::uncontrolled(),
112    )
113}
114
115#[cfg(test)]
116fn validate_public_view_expression(
117    expression: &ScalarExpr,
118    public_columns: &BTreeSet<String>,
119    scope: ExpressionScope<'_>,
120) -> Result<(), SQLError> {
121    validate_reference_columns(expression, &|column| public_columns.contains(column), scope)
122}
123
124pub fn validate_public_merge_contract(
125    services: ViewRewriteContext<'_>,
126    plan: &MergePlan,
127    source: &RowSchema,
128) -> Result<(), SQLError> {
129    production::validate_public_merge_contract(
130        services,
131        plan,
132        source,
133        &uqa_core::memory::ProductionControl::uncontrolled(),
134    )
135}
136
137pub fn validate_public_merge_targets(
138    services: ViewRewriteContext<'_>,
139    plan: &MergePlan,
140) -> Result<(), SQLError> {
141    super::commands::validate_public_merge_targets_with_control(
142        services,
143        plan,
144        &uqa_core::memory::ProductionControl::uncontrolled(),
145    )
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum MergeViewTargetPath {
150    AutomaticRewrite,
151    ViewTriggers,
152}
153
154/// Choose how a MERGE reaches view `plan.target`, as `RewriteQuery` and `rewriteTargetView` do: through the view's INSTEAD OF triggers when every action has one, and otherwise by rewriting the view onto its base relation, which its query must allow, with an updatable column when an action inserts or updates. When it does not, the first action in WHEN order without a trigger reports why; an automatically updatable view cannot mix the two paths.
155pub fn merge_view_target_path(
156    services: ViewRewriteContext<'_>,
157    plan: &MergePlan,
158) -> Result<MergeViewTargetPath, SQLError> {
159    super::commands::merge_view_target_path_with_control(
160        services,
161        plan,
162        &uqa_core::memory::ProductionControl::uncontrolled(),
163    )
164}
165
166/// The trigger event and the view command of a MERGE action that writes, or `None` for `DO NOTHING`.
167pub(super) fn merge_clause_command(clause: &MergeWhenPlan) -> Option<(TriggerEvent, ViewCommand)> {
168    match clause {
169        MergeWhenPlan::InsertNotMatched { .. } => {
170            Some((TriggerEvent::Insert, ViewCommand::MergeInsert))
171        }
172        MergeWhenPlan::UpdateMatched { .. } | MergeWhenPlan::UpdateNotMatchedBySource { .. } => {
173            Some((TriggerEvent::Update, ViewCommand::MergeUpdate))
174        }
175        MergeWhenPlan::DeleteMatched { .. } | MergeWhenPlan::DeleteNotMatchedBySource { .. } => {
176            Some((TriggerEvent::Delete, ViewCommand::MergeDelete))
177        }
178        MergeWhenPlan::NothingMatched { .. }
179        | MergeWhenPlan::NothingNotMatched { .. }
180        | MergeWhenPlan::NothingNotMatchedBySource { .. } => None,
181    }
182}