unisql-core 0.28.2

The UniSQL core: a dialect-neutral SQL IR, tiers and reports, a shared printer and the Target hooks.
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Target-free construct extraction: which constructs does a statement use?
//!
//! The ids are the same strings the writers record in a [`crate::Report`] (`like`, `fn:now`,
//! `upsert`, `join:left_join`, ...), so a gate can compare a statement's needs with a matrix row's
//! subject. This walker needs no target: it reads the IR shape, so it sees every construct even
//! where a particular target would stop at its first refusal.

use std::collections::BTreeSet;

use crate::ast::*;
use crate::print::is_numeric;
use crate::schema::{Schema, Scopes};

/// Every construct id the statement uses.
pub fn constructs(stmt: &Statement) -> BTreeSet<String> {
    constructs_with(stmt, None)
}

/// As [`constructs`], knowing the column classes of the caller's base tables: a comparison with a
/// column that is not text names no `text_comparison`, exactly as the writers do not record one.
pub fn constructs_with(stmt: &Statement, schema: Option<&Schema>) -> BTreeSet<String> {
    let mut w = Walk {
        out: BTreeSet::new(),
        tables: BTreeSet::new(),
        scopes: Scopes::new(schema),
    };
    w.statement(stmt);
    w.out
}

/// The last part, ASCII lower-cased, of every table name the statement reads or writes (a CTE
/// reference is included: callers use this to refuse, so too many is safe).
pub(crate) fn table_names(stmt: &Statement) -> BTreeSet<String> {
    let mut w = Walk {
        out: BTreeSet::new(),
        tables: BTreeSet::new(),
        scopes: Scopes::new(None),
    };
    w.statement(stmt);
    w.tables
}

struct Walk<'a> {
    out: BTreeSet<String>,
    tables: BTreeSet<String>,
    scopes: Scopes<'a>,
}

impl Walk<'_> {
    fn statement(&mut self, stmt: &Statement) {
        match stmt {
            Statement::With(w) => {
                self.add(match &*w.stmt {
                    Statement::Insert(_) => "with.insert",
                    Statement::Update(_) => "with.update",
                    _ => "with.delete",
                });
                if w.recursive {
                    self.add("recursive_cte");
                }
                for c in &w.ctes {
                    match &c.body {
                        CteBody::Query(q) => self.query(q),
                        CteBody::Dml(st) => {
                            self.add("cte.data_modifying");
                            self.statement(st);
                        }
                    }
                }
                self.statement(&w.stmt);
            }
            Statement::Query(q) => self.query(q),
            Statement::Insert(i) => {
                self.touch(&i.table);
                if i.replace {
                    self.add("replace_into");
                }
                match &i.source {
                    InsertSource::Query(q) => self.query(q),
                    InsertSource::Values(rows) => rows.iter().flatten().for_each(|e| self.expr(e)),
                    InsertSource::DefaultValues => {}
                }
                if let Some(oc) = &i.on_conflict {
                    match &oc.action {
                        ConflictAction::DoNothing => self.add("upsert"),
                        ConflictAction::DoUpdate { set, where_ } => {
                            self.add(if where_.is_some() {
                                "upsert_where"
                            } else {
                                "upsert"
                            });
                            // A target that needs the conflict key refuses this form.
                            if oc.target.is_empty() {
                                // With exactly one stated unique key the target can write it.
                                match self.scopes.unique_keys(&i.table) {
                                    Some([_]) => self.add("upsert.key_from_schema"),
                                    _ => self.add("upsert.no_conflict_key"),
                                }
                            }
                            self.scopes.push_upsert(&i.table);
                            set.iter().for_each(|a| self.expr(&a.value));
                            if let Some(e) = where_ {
                                self.expr(e);
                            }
                            self.scopes.pop();
                        }
                    }
                }
                self.returning(&i.returning);
            }
            Statement::Update(u) => {
                self.touch(&u.table);
                self.scopes
                    .push_target(&u.table, u.alias.as_deref(), &u.from);
                u.set.iter().for_each(|a| self.expr(&a.value));
                if !u.returning.is_empty() {
                    self.add("returning.update");
                }
                if !u.from.is_empty() {
                    self.add("update_from");
                    u.from.iter().for_each(|t| self.table(t));
                }
                if let Some(e) = &u.where_ {
                    self.expr(e);
                }
                if !u.order_by.is_empty() || u.limit.is_some() {
                    self.add("update_limit");
                    u.order_by.iter().for_each(|o| self.expr(&o.expr));
                    u.limit.iter().for_each(|e| self.expr(e));
                }
                self.returning(&u.returning);
                self.scopes.pop();
            }
            Statement::Delete(d) => {
                self.touch(&d.table);
                self.scopes
                    .push_target(&d.table, d.alias.as_deref(), &d.using);
                d.using.iter().for_each(|t| self.table(t));
                if let Some(e) = &d.where_ {
                    self.expr(e);
                }
                if !d.order_by.is_empty() || d.limit.is_some() {
                    self.add("delete_limit");
                    d.order_by.iter().for_each(|o| self.expr(&o.expr));
                    d.limit.iter().for_each(|e| self.expr(e));
                }
                self.returning(&d.returning);
                self.scopes.pop();
            }
        }
    }

    fn touch(&mut self, table: &Name) {
        self.tables.insert(table.last().to_ascii_lowercase());
    }

    fn add(&mut self, c: impl Into<String>) {
        self.out.insert(c.into());
    }

    /// `make_interval(months|years => ..)`: month arithmetic differs between engines, so it is its
    /// own leaf and a target may refuse it while giving the fixed-length units.
    fn month_year(&mut self, f: &Function) {
        if f.name == "make_interval"
            && f.args.iter().any(|a| {
                matches!(a, FunctionArg::Named { name, .. } if name == "months" || name == "years")
            })
        {
            self.add("fn:make_interval.month_year");
        }
    }

    fn returning(&mut self, items: &[SelectItem]) {
        if !items.is_empty() {
            self.add("returning");
            self.items(items);
        }
    }

    fn items(&mut self, items: &[SelectItem]) {
        for it in items {
            if let SelectItem::Expr { expr, .. } = it {
                self.expr(expr);
            }
        }
    }

    fn query(&mut self, q: &Query) {
        if q.recursive {
            self.add("recursive_cte");
        }
        for c in &q.with {
            match &c.body {
                CteBody::Query(q) => self.query(q),
                CteBody::Dml(st) => {
                    self.add("cte.data_modifying");
                    self.statement(st);
                }
            }
        }
        self.set_expr(&q.body);
        if !q.order_by.is_empty() {
            self.add("order_by");
            self.add("null_ordering");
            // The ORDER BY of a plain SELECT sees that SELECT's FROM tables, as the printer does.
            let from = match &q.body {
                SetExpr::Select(sel) => Some(&sel.from),
                SetExpr::SetOp { .. } => None,
            };
            if let Some(f) = from {
                self.scopes.push_from(f);
            }
            for o in &q.order_by {
                self.expr(&o.expr);
            }
            if from.is_some() {
                self.scopes.pop();
            }
        }
        if let Some(l) = &q.limit {
            self.add("limit");
            self.expr(l);
        }
        if let Some(o) = &q.offset {
            self.add("offset");
            self.expr(o);
        }
    }

    fn set_expr(&mut self, s: &SetExpr) {
        match s {
            SetExpr::Select(sel) => self.select(sel),
            SetExpr::SetOp { left, right, .. } => {
                self.set_expr(left);
                self.set_expr(right);
            }
        }
    }

    fn select(&mut self, s: &Select) {
        self.scopes.push_from(&s.from);
        self.select_in_scope(s);
        self.scopes.pop();
    }

    fn select_in_scope(&mut self, s: &Select) {
        if let Distinct::On(keys) = &s.distinct {
            self.add("distinct_on");
            if s.projection
                .iter()
                .any(|i| !matches!(i, SelectItem::Expr { .. }))
            {
                self.add("distinct_on.star_projection");
            }
            if s.lock.is_some() {
                self.add("distinct_on.row_lock");
            }
            // Targets without it emulate it with `row_number() OVER (PARTITION BY ..)`; that is a
            // dependency of the statement there, so it is named here (an over-approximation on
            // targets that have DISTINCT ON natively, where window functions exist anyway).
            self.add("fn:row_number");
            self.add("window_function");
            keys.iter().for_each(|e| self.expr(e));
        }
        self.items(&s.projection);
        s.from.iter().for_each(|t| self.table(t));
        if let Some(e) = &s.where_ {
            self.expr(e);
        }
        if s.group_by_rollup {
            self.add("group_by.rollup");
        }
        s.group_by.iter().for_each(|e| self.expr(e));
        if let Some(e) = &s.having {
            self.expr(e);
        }
        if let Some(l) = &s.lock {
            self.add(match l.strength {
                RowLock::Update => "row_lock",
                RowLock::Share => "row_lock.share",
            });
            if l.of.is_some() {
                self.add("row_lock.of");
            }
            match l.wait {
                LockWait::Block => {}
                LockWait::NoWait => self.add("row_lock.nowait"),
                LockWait::SkipLocked => self.add("row_lock.skip_locked"),
            }
        }
    }

    fn table(&mut self, t: &TableRef) {
        match t {
            TableRef::Table { name, .. } => self.touch(name),
            TableRef::Subquery { query, .. } => self.query(query),
            TableRef::Function { name, args, alias } => {
                self.add(format!("table_function.{name}"));
                if name.eq_ignore_ascii_case("generate_series") {
                    // Where it is written as a recursive CTE (SQLite, MySQL/MariaDB), and its refusals.
                    self.add("recursive_cte");
                    if alias.is_none() {
                        self.add("table_function.generate_series.alias");
                    }
                    if crate::ast::series_bounds(args).is_none() {
                        self.add("table_function.generate_series.args");
                    }
                }
                args.iter().for_each(|x| self.expr(x));
            }
            TableRef::Join {
                left,
                right,
                kind,
                on,
                using,
                natural,
            } => {
                if *natural {
                    self.add("join.natural");
                }
                if !using.is_empty() {
                    self.add("join.using");
                }
                self.add(match kind {
                    JoinKind::Inner => "join:inner_join",
                    JoinKind::Left => "join:left_join",
                    JoinKind::Right => "join:right_join",
                    JoinKind::Full => "join:full_join",
                    JoinKind::Cross => "join:cross_join",
                });
                self.table(left);
                self.table(right);
                if let Some(e) = on {
                    self.expr(e);
                }
            }
        }
    }

    /// Writers record `ordered_comparison` for every ordered comparison (Exact when an operand is
    /// numeric) and `text_comparison` for the ones that may compare text.
    fn compare(&mut self, numeric: bool, ordered: bool) {
        if ordered {
            self.add("ordered_comparison");
        }
        if !numeric {
            self.add("text_comparison");
        }
    }

    fn expr(&mut self, e: &Expr) {
        match e {
            Expr::Column(_) | Expr::Param(_) => {}
            Expr::Literal(l) => {
                if matches!(l, Literal::Bool(_)) {
                    self.add("boolean_literal");
                }
            }
            Expr::Nested(x) => self.expr(x),
            Expr::Unary { expr, .. } => self.expr(expr),
            Expr::Binary { op, left, right } => {
                if matches!(&**right, Expr::Function(f) if f.name == "make_interval")
                    && matches!(op, BinaryOp::Plus | BinaryOp::Minus)
                {
                    self.add("interval_arithmetic");
                    // PostgreSQL itself spells it as the named-argument call, so both are needs.
                    self.add("fn:make_interval");
                    if let Expr::Function(f) = &**right {
                        self.month_year(f);
                    }
                    self.expr(left);
                    if let Expr::Function(f) = &**right {
                        for a in &f.args {
                            if let FunctionArg::Named { value, .. } = a {
                                self.expr(value);
                            }
                        }
                    }
                    return;
                }
                let numeric = is_numeric(left)
                    || is_numeric(right)
                    || self.scopes.is_non_text_column(left)
                    || self.scopes.is_non_text_column(right);
                match op {
                    BinaryOp::Concat => self.add("concat"),
                    BinaryOp::Modulo => self.add("division"),
                    // An IR `/` has PostgreSQL's meaning (integer operands truncate), which a target
                    // with exact decimal division must spell as integer division.
                    BinaryOp::Divide => {
                        self.add("division");
                        self.add("division_integer");
                    }
                    BinaryOp::IntDivide => {
                        self.add("division");
                        self.add("division_integer");
                    }
                    BinaryOp::Eq | BinaryOp::NotEq => self.compare(numeric, false),
                    BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq => {
                        self.compare(numeric, true)
                    }
                    BinaryOp::NullSafeEq => self.add("null_safe_eq"),
                    BinaryOp::BitAnd
                    | BinaryOp::BitOr
                    | BinaryOp::BitXor
                    | BinaryOp::ShiftLeft
                    | BinaryOp::ShiftRight => self.add("bitwise"),
                    BinaryOp::Xor => self.add("xor"),
                    BinaryOp::JsonGet => self.add("json_get"),
                    BinaryOp::JsonGetText => self.add("json_get_text"),
                    BinaryOp::JsonPath => self.add("json_path"),
                    BinaryOp::JsonPathText => self.add("json_path_text"),
                    _ => {}
                }
                self.expr(left);
                self.expr(right);
            }
            Expr::IsNull { expr, .. } | Expr::IsBool { expr, .. } => self.expr(expr),
            Expr::InList { expr, list, .. } => {
                self.expr(expr);
                list.iter().for_each(|x| self.expr(x));
            }
            Expr::InSubquery { expr, query, .. } => {
                self.expr(expr);
                self.query(query);
            }
            Expr::Between {
                expr, low, high, ..
            } => {
                let numeric = is_numeric(low)
                    || is_numeric(high)
                    || is_numeric(expr)
                    || self.scopes.is_non_text_column(low)
                    || self.scopes.is_non_text_column(high)
                    || self.scopes.is_non_text_column(expr);
                self.compare(numeric, true);
                self.expr(expr);
                self.expr(low);
                self.expr(high);
            }
            Expr::Regexp { expr, pattern, .. } => {
                self.add("regexp");
                self.expr(expr);
                self.expr(pattern);
            }
            Expr::Like {
                expr,
                pattern,
                case_insensitive,
                escape,
                ..
            } => {
                self.add(if *case_insensitive { "ilike" } else { "like" });
                self.expr(expr);
                self.expr(pattern);
                if let Some(x) = escape {
                    self.expr(x);
                }
            }
            Expr::Case {
                operand,
                branches,
                else_,
            } => {
                if let Some(o) = operand {
                    self.expr(o);
                }
                for (w, t) in branches {
                    self.expr(w);
                    self.expr(t);
                }
                if let Some(x) = else_ {
                    self.expr(x);
                }
            }
            Expr::Cast { expr, ty, .. } => {
                self.add(format!("cast.to_{}", ty.leaf()));
                self.expr(expr);
            }
            Expr::Function(f) => {
                // date_trunc with a literal field is one leaf per field (a target maps a field only
                // once it is verified); the generic leaf is the dynamic-field form.
                match crate::target::date_trunc_field(f) {
                    Some(field) => self.add(format!("fn:date_trunc.{field}")),
                    None => self.add(format!("fn:{}", f.name)),
                }
                self.month_year(f);
                if f.name == "make_interval" {
                    // Outside `ts +/- make_interval(..)`: no target translates it on its own.
                    self.add("fn:make_interval.standalone");
                }
                for a in &f.args {
                    match a {
                        FunctionArg::Expr(x) => self.expr(x),
                        FunctionArg::Named { value, .. } => {
                            self.add("named_arg");
                            self.expr(value);
                        }
                    }
                }
                if let Some(x) = &f.filter {
                    self.add("filter_clause");
                    self.expr(x);
                }
                if let Some(w) = &f.over {
                    self.add("window_function");
                    w.partition_by.iter().for_each(|x| self.expr(x));
                    w.order_by.iter().for_each(|o| self.expr(&o.expr));
                    if !w.order_by.is_empty() {
                        self.add("order_by");
                        self.add("null_ordering");
                    }
                }
                if !f.order_by.is_empty() {
                    self.add("order_by");
                    self.add("null_ordering");
                    self.add(format!("fn:{}.order_by", f.name));
                }
                f.order_by.iter().for_each(|o| self.expr(&o.expr));
            }
            Expr::Subquery(q) => self.query(q),
            Expr::Exists { query, .. } => self.query(query),
            Expr::AnyParam { expr, .. } => {
                self.add("array_param");
                self.expr(expr);
            }
            Expr::Extract { field, expr } => {
                if field == "epoch" && crate::print::is_clock_call(expr) {
                    self.add("extract.epoch");
                    return;
                }
                self.add(crate::target::extract_leaf(
                    field,
                    crate::print::is_difference(expr),
                ));
                self.expr(expr);
            }
            Expr::ArrayLiteral(items) => {
                self.add("array_literal");
                items.iter().for_each(|x| self.expr(x));
            }
            Expr::AtTimeZone { expr, zone } => {
                self.add("at_time_zone");
                self.expr(expr);
                self.expr(zone);
            }
            Expr::ArraySubquery(q) => {
                self.add("array_subquery");
                self.query(q);
            }
            Expr::Trim { expr, chars, .. } => {
                self.add("trim");
                // MySQL removes a repeated string where PostgreSQL removes a set: they agree only
                // for one plain character, so anything else is its own leaf.
                let single = match chars.as_deref() {
                    None => true,
                    Some(Expr::Literal(Literal::String(s))) => {
                        s.chars().count() == 1 && s != "'" && s != "\\"
                    }
                    Some(_) => false,
                };
                if !single {
                    self.add("trim.multi_char");
                }
                self.expr(expr);
                if let Some(c) = chars {
                    self.expr(c);
                }
            }
        }
    }
}