uqa-sql 0.6.3

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! OLD/NEW reference analysis for rewrite-rule expressions and stored plans.

mod relation;
pub use relation::relation_rule_row_columns_with_control;

use std::collections::BTreeSet;

use crate::ast::{Expr, SelectStmt, Statement};
use crate::plan::ExpressionPlan;
use crate::plpgsql::{ResolvedVariable, VariableResolver};
use crate::SQLError;
use crate::ScalarExpr;

use super::{
    inspection,
    names::{self, Names},
};
use crate::catalog::events::RuleConditionBinding;
use uqa_core::memory::{OwnedProductionControl, Produced, ProductionControl, ProductionVec};

#[derive(Default)]
struct RuleRowReferenceDetector {
    qualifier: Option<&'static str>,
    whole_row: bool,
}

struct RuleRowColumnCollector {
    columns: Names,
    control: OwnedProductionControl,
    qualifier: Option<&'static str>,
    whole_row: bool,
}

impl Default for RuleRowColumnCollector {
    fn default() -> Self {
        Self::new(&ProductionControl::uncontrolled())
    }
}
impl RuleRowColumnCollector {
    fn new(control: &ProductionControl<'_>) -> Self {
        Self {
            columns: Names::new(),
            control: control.capture(),
            qualifier: None,
            whole_row: false,
        }
    }
    fn into_uncontrolled(self) -> BTreeSet<String> {
        self.columns
            .into_iter()
            .map(|name| name.into_uncontrolled().expect("ordinary rule reference"))
            .collect()
    }
    fn accepts(&self, qualifier: &str) -> bool {
        self.qualifier.map_or_else(
            || qualifier.eq_ignore_ascii_case("old") || qualifier.eq_ignore_ascii_case("new"),
            |selected| selected.eq_ignore_ascii_case(qualifier),
        )
    }
}

impl VariableResolver for RuleRowColumnCollector {
    fn resolve_name(&mut self, name: &str) -> Result<Option<ResolvedVariable>, SQLError> {
        self.whole_row |= self.accepts(name);
        Ok(None)
    }

    fn resolve_qualified(
        &mut self,
        qualifier: &str,
        column: &str,
    ) -> Result<Option<ResolvedVariable>, SQLError> {
        if self.accepts(qualifier) {
            names::insert_name(&mut self.columns, column, false, &self.control.control())?;
        }
        Ok(None)
    }

    fn resolve_param(&mut self, _index: usize) -> Result<Option<ResolvedVariable>, SQLError> {
        Ok(None)
    }

    fn rewrite_qualified_whole_row(&mut self, qualifier: &str) -> Result<Option<Expr>, SQLError> {
        self.whole_row |= self.accepts(qualifier);
        Ok(None)
    }
}

impl VariableResolver for RuleRowReferenceDetector {
    fn resolve_name(&mut self, name: &str) -> Result<Option<ResolvedVariable>, SQLError> {
        if name.eq_ignore_ascii_case("old") || name.eq_ignore_ascii_case("new") {
            self.observe(name, true);
        }
        Ok(None)
    }

    fn resolve_qualified(
        &mut self,
        qualifier: &str,
        _column: &str,
    ) -> Result<Option<ResolvedVariable>, SQLError> {
        self.observe(qualifier, false);
        Ok(None)
    }

    fn resolve_param(&mut self, _index: usize) -> Result<Option<ResolvedVariable>, SQLError> {
        Ok(None)
    }

    fn rewrite_qualified_whole_row(&mut self, qualifier: &str) -> Result<Option<Expr>, SQLError> {
        self.observe(qualifier, true);
        Ok(None)
    }
}

impl RuleRowReferenceDetector {
    fn observe(&mut self, qualifier: &str, whole_row: bool) {
        if qualifier.eq_ignore_ascii_case("old") || qualifier.eq_ignore_ascii_case("new") {
            if self.qualifier.is_none() {
                self.qualifier = Some(if qualifier.eq_ignore_ascii_case("old") {
                    "old"
                } else {
                    "new"
                });
            }
            self.whole_row |= whole_row;
        }
    }
}

pub fn rule_action_has_set_operation(action: &Statement) -> bool {
    match action {
        Statement::Select(select) => select.set_op.is_some(),
        Statement::Insert(insert) => insert
            .select_source
            .as_ref()
            .is_some_and(|select| select.set_op.is_some()),
        _ => false,
    }
}

pub fn first_rule_row_reference_in_expr(
    expr: &Expr,
    shadowed: &BTreeSet<String>,
) -> Option<String> {
    let mut detector = RuleRowReferenceDetector::default();
    let _ = inspection::expression(expr, &mut detector, shadowed);
    detector.qualifier.map(str::to_owned)
}

pub fn first_rule_row_reference_in_select(
    catalog: &dyn super::RuleSourceCatalog,
    select: &SelectStmt,
) -> Option<String> {
    let mut detector = RuleRowReferenceDetector::default();
    let _ = inspection::select(catalog, select, &mut detector);
    detector.qualifier.map(str::to_owned)
}

pub fn rule_expr_references_row(expr: &Expr) -> bool {
    first_rule_row_reference_in_expr(expr, &BTreeSet::new()).is_some()
}

fn rule_expr_references_row_with_control(
    expr: &Expr,
    control: &ProductionControl<'_>,
) -> Result<bool, SQLError> {
    let mut detector = RuleRowReferenceDetector::default();
    if let Err(error) =
        inspection::expression_with_control(expr, &mut detector, &BTreeSet::new(), control)
    {
        if matches!(error.sqlstate(), Some("53200" | "57014")) {
            return Err(error);
        }
    }
    Ok(detector.qualifier.is_some())
}

pub fn rule_expr_references_whole_row(expr: &Expr) -> bool {
    let mut detector = RuleRowReferenceDetector::default();
    let _ = inspection::expression(expr, &mut detector, &BTreeSet::new());
    detector.whole_row
}

pub fn first_rule_row_reference_in_statement(
    catalog: &dyn super::RuleSourceCatalog,
    statement: &Statement,
) -> Result<Option<String>, SQLError> {
    let target = match statement {
        Statement::Insert(plan) => Some(plan.table.as_str()),
        Statement::Update(plan) => Some(plan.table.as_str()),
        Statement::Delete(plan) => Some(plan.table.as_str()),
        Statement::Merge(plan) => Some(plan.target.as_str()),
        _ => None,
    };
    let columns = target
        .map(|table| catalog.query_source_columns(table, false))
        .transpose()?
        .flatten()
        .unwrap_or_default()
        .into_iter()
        .collect();
    let mut detector = RuleRowReferenceDetector::default();
    inspection::action(catalog, statement, &columns, &mut detector)?;
    Ok(detector.qualifier.map(str::to_owned))
}

pub fn rule_statement_references_row(
    catalog: &dyn super::RuleSourceCatalog,
    statement: &Statement,
    action_columns: &BTreeSet<String>,
) -> Result<bool, SQLError> {
    rule_statement_references_row_with_control(
        catalog,
        statement,
        action_columns,
        &ProductionControl::uncontrolled(),
    )
}

/// Whether an action or its unevaluated rule condition needs the event relation.
pub fn rule_action_references_row_with_control(
    catalog: &dyn super::RuleSourceCatalog,
    statement: &Statement,
    action_columns: &dyn super::ActionColumns,
    condition: Option<&Expr>,
    control: &ProductionControl<'_>,
) -> Result<bool, SQLError> {
    Ok(
        rule_statement_references_row_with_control(catalog, statement, action_columns, control)?
            || condition
                .map(|condition| rule_expr_references_row_with_control(condition, control))
                .transpose()?
                .unwrap_or(false),
    )
}

fn rule_statement_references_row_with_control(
    catalog: &dyn super::RuleSourceCatalog,
    statement: &Statement,
    action_columns: &dyn super::ActionColumns,
    control: &ProductionControl<'_>,
) -> Result<bool, SQLError> {
    let mut detector = RuleRowReferenceDetector::default();
    inspection::action_with_control(catalog, statement, action_columns, &mut detector, control)?;
    Ok(detector.qualifier.is_some())
}

pub fn rule_statement_references_whole_row(
    catalog: &dyn super::RuleSourceCatalog,
    statement: &Statement,
    action_columns: &BTreeSet<String>,
) -> Result<bool, SQLError> {
    let mut detector = RuleRowReferenceDetector::default();
    inspection::action(catalog, statement, action_columns, &mut detector)?;
    Ok(detector.whole_row)
}

pub fn rule_expr_row_columns(expr: &Expr) -> BTreeSet<String> {
    let mut collector = RuleRowColumnCollector::default();
    let _ = inspection::expression(expr, &mut collector, &BTreeSet::new());
    collector.into_uncontrolled()
}

fn collect_condition_plan_row_column(
    expression: &ScalarExpr,
    binding: &RuleConditionBinding,
    columns: &mut BTreeSet<String>,
) {
    if let ScalarExpr::InternalColumn(column) = expression {
        if let Some(name) = binding.column_name(*column) {
            columns.insert(name.to_string());
        }
    }
}

fn condition_plan_expression_references_whole_row(expression: &ScalarExpr) -> bool {
    matches!(
        expression,
        ScalarExpr::Column(qualifier) | ScalarExpr::QualifiedStar(qualifier)
            if qualifier.eq_ignore_ascii_case("old")
                || qualifier.eq_ignore_ascii_case("new")
    )
}

pub fn rule_condition_plan_references_whole_row(plan: &ExpressionPlan) -> bool {
    let mut referenced = false;
    plan.scalar.visit(&mut |expression| {
        referenced |= condition_plan_expression_references_whole_row(expression);
    });
    for subquery in &plan.subqueries {
        subquery.visit_scalar_expressions(&mut |root| {
            root.visit(&mut |expression| {
                referenced |= condition_plan_expression_references_whole_row(expression);
            });
        });
    }
    referenced
}

pub fn rule_condition_plan_row_columns(
    plan: &ExpressionPlan,
    binding: &RuleConditionBinding,
) -> BTreeSet<String> {
    let mut columns = BTreeSet::new();
    plan.scalar.visit(&mut |expression| {
        collect_condition_plan_row_column(expression, binding, &mut columns);
    });
    for subquery in &plan.subqueries {
        subquery.visit_scalar_expressions(&mut |root| {
            root.visit(&mut |expression| {
                collect_condition_plan_row_column(expression, binding, &mut columns);
            });
        });
    }
    columns
}

pub fn rule_statement_row_columns(
    catalog: &dyn super::RuleSourceCatalog,
    statement: &Statement,
    action_columns: &BTreeSet<String>,
) -> Result<BTreeSet<String>, SQLError> {
    let mut collector = RuleRowColumnCollector::default();
    inspection::action(catalog, statement, action_columns, &mut collector)?;
    Ok(collector.into_uncontrolled())
}

/// Input assignments contribute only NEW fields; OLD references require source rows but never the corresponding new assignment expression.
pub fn rule_new_row_columns(
    catalog: &dyn super::RuleSourceCatalog,
    rule: &crate::catalog::events::StoredRule,
) -> Result<Option<BTreeSet<String>>, SQLError> {
    Ok(
        rule_new_row_columns_with_control(catalog, rule, &ProductionControl::uncontrolled())?.map(
            |columns| {
                columns
                    .into_uncontrolled()
                    .expect("ordinary rule reference")
                    .into_iter()
                    .collect()
            },
        ),
    )
}

pub fn rule_new_row_columns_with_control(
    catalog: &dyn super::RuleSourceCatalog,
    rule: &crate::catalog::events::StoredRule,
    control: &ProductionControl<'_>,
) -> Result<Option<Produced<Vec<String>>>, SQLError> {
    control.check()?;
    let mut collector = RuleRowColumnCollector {
        qualifier: Some("new"),
        ..RuleRowColumnCollector::new(control)
    };
    if let Some(condition) = &rule.definition.condition {
        inspection::expression_with_control(condition, &mut collector, &BTreeSet::new(), control)?;
    }
    for action in &rule.definition.actions {
        control.check()?;
        let target = match action {
            Statement::Insert(statement) => Some(statement.table.as_str()),
            Statement::Update(statement) => Some(statement.table.as_str()),
            Statement::Delete(statement) => Some(statement.table.as_str()),
            _ => None,
        };
        let mut columns = Names::new();
        if let Some(target) = target {
            let selected = catalog.rule_relation_columns_with_control(target, control)?;
            for name in selected.iter() {
                names::insert_name(&mut columns, name, false, control)?;
            }
        }
        inspection::action_with_control(catalog, action, &columns, &mut collector, control)?;
    }
    if collector.whole_row {
        return Ok(None);
    }
    let mut output = ProductionVec::new(*control);
    for column in collector.columns {
        output.push_produced(column)?;
    }
    Ok(Some(output.finish()?))
}

/// Preserve action/condition inspection order while admitting selected names under the request.
pub fn rule_action_input_columns_with_control(
    catalog: &dyn super::RuleSourceCatalog,
    action: &Statement,
    condition: Option<&Expr>,
    action_columns: &dyn super::ActionColumns,
    control: &ProductionControl<'_>,
) -> Result<Option<Produced<Vec<String>>>, SQLError> {
    let mut collector = RuleRowColumnCollector::new(control);
    inspection::action_with_control(catalog, action, action_columns, &mut collector, control)?;
    if let Some(condition) = condition {
        inspection::expression_with_control(condition, &mut collector, &BTreeSet::new(), control)?;
    }
    let mut detector = RuleRowReferenceDetector::default();
    inspection::action_with_control(catalog, action, action_columns, &mut detector, control)?;
    if !detector.whole_row {
        if let Some(condition) = condition {
            inspection::expression_with_control(
                condition,
                &mut detector,
                &BTreeSet::new(),
                control,
            )?;
        }
    }
    if detector.whole_row {
        return Ok(None);
    }
    let mut output = ProductionVec::new(*control);
    for column in collector.columns {
        output.push_produced(column)?;
    }
    Ok(Some(output.finish()?))
}