unisql-core 0.26.0

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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! What a caller knows about its tables: the class (and collation) of base-table columns.
//!
//! A [`Schema`] is pure data: UniSQL does no I/O to get one. It is optional, and without it the
//! translator decides numeric-versus-text from syntax alone (a bare column or parameter is "unknown",
//! so a comparison involving it is treated as a possible text comparison). With it, a comparison
//! whose operand is a column of a class other than text involves no text collation, and the
//! assumption the caller would otherwise have to grant (`text_collation`) is not needed for it.
//!
//! Scope and alias resolution stay inside UniSQL, which parses the statement; the schema only supplies
//! facts about **base tables**. Columns of views, CTEs, derived tables, aliases and expressions are
//! never looked up, so they stay unknown.
//!
//! Names are matched exactly as the reader produces them (unquoted identifiers lower-cased, quoted
//! ones as written). A table registered as `users` matches `users` in a statement and not
//! `public.users`: UniSQL does not know the search path, so an unqualified/qualified mismatch is
//! "unknown", never a guess.

use std::collections::{BTreeMap, BTreeSet};

use crate::ast::{Expr, Name, TableRef};

/// The class of a column, as far as comparing it is concerned.
///
/// `Boolean` should be given only when the declared type says boolean (not a `tinyint(1)`); `Other`
/// covers dates, UUIDs, JSON, bytes and anything else without a text collation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ColumnClass {
    Text,
    Numeric,
    Boolean,
    Other,
    /// The column exists but its type is not one UniSQL classifies (a custom type, an array): it is
    /// recorded so that an unqualified reference cannot be taken for another table's column.
    Unknown,
}

/// One column: its class and, when the caller knows it, its collation (carried as given; UniSQL does
/// not interpret it yet), its declared type text, and whether it is nullable and has a default. The
/// last three are `None` when the caller does not know; a check that reads them must treat `None` as
/// unknown, never as "no".
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Column {
    pub class: ColumnClass,
    pub collation: Option<String>,
    /// The type as declared (`bigint`, `character varying(16)`), in the spelling the reader gives.
    #[cfg_attr(feature = "serde", serde(default))]
    pub declared_type: Option<String>,
    /// `Some(false)` for `NOT NULL`, a primary key, a serial or identity column.
    #[cfg_attr(feature = "serde", serde(default))]
    pub nullable: Option<bool>,
    /// `Some(true)` for a `DEFAULT`, a generated, serial, identity or auto-increment column.
    #[cfg_attr(feature = "serde", serde(default))]
    pub has_default: Option<bool>,
}

impl Column {
    pub fn new(class: ColumnClass) -> Self {
        Column {
            class,
            collation: None,
            declared_type: None,
            nullable: None,
            has_default: None,
        }
    }

    pub fn text() -> Self {
        Column::new(ColumnClass::Text)
    }

    pub fn numeric() -> Self {
        Column::new(ColumnClass::Numeric)
    }

    pub fn boolean() -> Self {
        Column::new(ColumnClass::Boolean)
    }

    pub fn other() -> Self {
        Column::new(ColumnClass::Other)
    }

    pub fn unknown() -> Self {
        Column::new(ColumnClass::Unknown)
    }

    pub fn with_collation(mut self, collation: impl Into<String>) -> Self {
        self.collation = Some(collation.into());
        self
    }

    pub fn with_declared_type(mut self, declared_type: impl Into<String>) -> Self {
        self.declared_type = Some(declared_type.into());
        self
    }

    pub fn with_nullable(mut self, nullable: bool) -> Self {
        self.nullable = Some(nullable);
        self
    }

    pub fn with_default(mut self, has_default: bool) -> Self {
        self.has_default = Some(has_default);
        self
    }
}

/// Base tables and their columns.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(
        from = "crate::snapshot::SchemaRepr",
        into = "crate::snapshot::SchemaRepr"
    )
)]
pub struct Schema {
    tables: BTreeMap<Vec<String>, BTreeMap<String, Column>>,
    /// Unique keys (primary or unique constraint, unique index) per table, columns in key order.
    keys: BTreeMap<Vec<String>, Vec<Vec<String>>>,
    /// Tables whose key list must not be trusted as complete (an index the reader could not
    /// interpret, such as a partial or expression index).
    keys_unreliable: BTreeSet<Vec<String>>,
    /// Tables whose column list is stated in full (read from a `CREATE TABLE`, or marked).
    columns_complete: BTreeSet<Vec<String>>,
}

impl Schema {
    pub fn new() -> Self {
        Schema::default()
    }

    /// Register `column` of the unqualified table `table`.
    pub fn with_column(self, table: &str, column: &str, c: Column) -> Self {
        self.with_qualified_column(&[table], column, c)
    }

    /// Register `column` of the table named by `table` (`["public", "users"]` for `public.users`).
    pub fn with_qualified_column(mut self, table: &[&str], column: &str, c: Column) -> Self {
        self.tables
            .entry(table.iter().map(|s| s.to_string()).collect())
            .or_default()
            .insert(column.to_string(), c);
        self
    }

    /// Register or replace a column (the mutating form of [`Schema::with_qualified_column`]).
    pub fn set_column(&mut self, table: Vec<String>, column: String, c: Column) {
        self.tables.entry(table).or_default().insert(column, c);
    }

    /// Forget one column (an `ALTER TABLE .. DROP COLUMN`); a key that used it goes with it.
    pub fn drop_column(&mut self, table: &Name, column: &str) {
        if let Some(t) = self.tables.get_mut(&table.0) {
            t.remove(column);
        }
        if let Some(ks) = self.keys.get_mut(&table.0) {
            ks.retain(|k| !k.iter().any(|c| c == column));
        }
    }

    /// Forget a table (a `DROP TABLE`).
    pub fn drop_table(&mut self, table: &Name) {
        self.tables.remove(&table.0);
        self.keys.remove(&table.0);
        self.keys_unreliable.remove(&table.0);
        self.columns_complete.remove(&table.0);
    }

    /// State one unique key (primary key, unique constraint or unique index, **not** a partial or
    /// expression index) of the unqualified table `table`, columns in key order. **State every unique
    /// key the table has**: the translator treats the stated keys as the complete list. A table with
    /// no stated key has unknown keys, not "no keys".
    pub fn with_unique_key(mut self, table: &str, columns: &[&str]) -> Self {
        self.add_unique_key(
            vec![table.to_string()],
            columns.iter().map(|c| c.to_string()).collect(),
        );
        self
    }

    /// The mutating form of [`Schema::with_unique_key`] (qualified table name, owned columns).
    pub fn add_unique_key(&mut self, table: Vec<String>, columns: Vec<String>) {
        let ks = self.keys.entry(table).or_default();
        if !ks.contains(&columns) {
            ks.push(columns);
        }
    }

    /// Say that this table has a unique index the reader could not express as a column list, so
    /// its key list is incomplete and no conflict key is derived from it.
    pub fn mark_keys_unreliable(&mut self, table: Vec<String>) {
        self.keys_unreliable.insert(table);
    }

    /// As [`Schema::mark_keys_unreliable`] for every table (a `DROP INDEX` names no table).
    pub fn mark_all_keys_unreliable(&mut self) {
        let all: Vec<Vec<String>> = self.keys.keys().cloned().collect();
        self.keys_unreliable.extend(all);
    }

    /// Say that the columns registered for `table` are all it has (a `REPLACE INTO` written as an
    /// upsert sets every column, so it needs the full list). `schema_from_ddl` does this for each
    /// `CREATE TABLE` it reads.
    pub fn mark_columns_complete(&mut self, table: Vec<String>) {
        self.columns_complete.insert(table);
    }

    /// All column names of `table`, when its column list is marked complete.
    pub fn complete_columns(&self, table: &Name) -> Option<Vec<&str>> {
        if !self.columns_complete.contains(&table.0) {
            return None;
        }
        Some(
            self.tables
                .get(&table.0)?
                .keys()
                .map(String::as_str)
                .collect(),
        )
    }

    /// Say whether `column` of `table` may be NULL (a table-level `PRIMARY KEY` makes its columns
    /// `NOT NULL`). Does nothing when the column is not registered.
    pub fn set_nullable(&mut self, table: &Name, column: &str, nullable: bool) {
        if let Some(c) = self
            .tables
            .get_mut(&table.0)
            .and_then(|t| t.get_mut(column))
        {
            c.nullable = Some(nullable);
        }
    }

    /// Say whether `column` of `table` has a default value. Does nothing when it is not registered.
    pub fn set_has_default(&mut self, table: &Name, column: &str, has_default: bool) {
        if let Some(c) = self
            .tables
            .get_mut(&table.0)
            .and_then(|t| t.get_mut(column))
        {
            c.has_default = Some(has_default);
        }
    }

    /// Every registered table, in name order, with what is known about it.
    pub fn tables(&self) -> impl Iterator<Item = TableView<'_>> {
        self.tables.iter().map(|(name, columns)| TableView {
            name,
            columns,
            unique_keys: self.keys.get(name).map(Vec::as_slice).unwrap_or(&[]),
            keys_unreliable: self.keys_unreliable.contains(name),
            columns_complete: self.columns_complete.contains(name),
        })
    }

    /// The stated unique keys of `table`; `None` when none were stated or the list is unreliable.
    pub fn unique_keys(&self, table: &Name) -> Option<&[Vec<String>]> {
        if self.keys_unreliable.contains(&table.0) {
            return None;
        }
        self.keys
            .get(&table.0)
            .map(Vec::as_slice)
            .filter(|k| !k.is_empty())
    }

    pub fn is_empty(&self) -> bool {
        self.tables.is_empty()
    }

    /// The column, when the table is registered and has it.
    pub fn get(&self, table: &Name, column: &str) -> Option<&Column> {
        self.tables.get(&table.0)?.get(column)
    }

    fn knows_table(&self, table: &Name) -> bool {
        self.tables.contains_key(&table.0)
    }
}

/// One registered table, as [`Schema::tables`] enumerates it.
#[derive(Clone, Copy, Debug)]
pub struct TableView<'a> {
    /// The table's name as registered (`["public", "users"]`).
    pub name: &'a [String],
    /// Its columns by name.
    pub columns: &'a BTreeMap<String, Column>,
    /// The stated unique keys, columns in key order (empty when none were stated).
    pub unique_keys: &'a [Vec<String>],
    /// The key list must not be trusted as complete.
    pub keys_unreliable: bool,
    /// The column list is stated in full.
    pub columns_complete: bool,
}

/// The tables a statement's expressions can refer to, innermost query last. Used by the printer and
/// by the needs walker, so both decide "is this operand a text column" the same way.
#[derive(Clone, Debug, Default)]
pub struct Scopes<'a> {
    schema: Option<&'a Schema>,
    /// Each scope: (binding name, the base table when it is one).
    stack: Vec<Vec<(String, Option<Name>)>>,
}

impl<'a> Scopes<'a> {
    pub fn new(schema: Option<&'a Schema>) -> Self {
        Scopes {
            schema,
            stack: Vec::new(),
        }
    }

    /// Enter a query whose FROM list is `from`.
    pub fn push_from(&mut self, from: &[TableRef]) {
        if self.schema.is_none() {
            return;
        }
        let mut scope = Vec::new();
        for t in from {
            collect(t, &mut scope);
        }
        self.stack.push(scope);
    }

    /// Enter an UPDATE/DELETE: the target table (with its alias) and any FROM/USING tables.
    pub fn push_target(&mut self, table: &Name, alias: Option<&str>, from: &[TableRef]) {
        if self.schema.is_none() {
            return;
        }
        let binding = alias
            .map(str::to_string)
            .unwrap_or_else(|| table.last().to_string());
        let mut scope = vec![(binding, Some(table.clone()))];
        for t in from {
            collect(t, &mut scope);
        }
        self.stack.push(scope);
    }

    /// Enter an upsert's `DO UPDATE`: the table under its own name and as `excluded`.
    pub fn push_upsert(&mut self, table: &Name) {
        if self.schema.is_none() {
            return;
        }
        self.stack.push(vec![
            (table.last().to_string(), Some(table.clone())),
            ("excluded".to_string(), Some(table.clone())),
        ]);
    }

    /// The stated unique keys of a base table (see [`Schema::unique_keys`]).
    pub fn unique_keys(&self, table: &Name) -> Option<&'a [Vec<String>]> {
        self.schema?.unique_keys(table)
    }

    /// The complete column list of a base table (see [`Schema::complete_columns`]).
    pub fn complete_columns(&self, table: &Name) -> Option<Vec<&'a str>> {
        self.schema?.complete_columns(table)
    }

    pub fn pop(&mut self) {
        if self.schema.is_some() {
            self.stack.pop();
        }
    }

    /// True when `e` is a (possibly parenthesised) column the schema says is not text.
    pub fn is_non_text_column(&self, e: &Expr) -> bool {
        self.column(e)
            .is_some_and(|c| !matches!(c.class, ColumnClass::Text | ColumnClass::Unknown))
    }

    /// The collation a text column states when it is **not** bytewise (`en_US`, `NOCASE`,
    /// `utf8mb4_0900_ai_ci`, ...). `None` for a column whose collation is unstated: an unstated
    /// collation is unknown, never the database default.
    pub fn non_bytewise_collation(&self, e: &Expr) -> Option<String> {
        let c = self.column(e)?;
        match (&c.class, &c.collation) {
            (ColumnClass::Text, Some(name)) if !is_bytewise_collation(name) => Some(name.clone()),
            _ => None,
        }
    }

    /// The column a (possibly parenthesised) column reference names, when the schema knows it.
    fn column(&self, e: &Expr) -> Option<&Column> {
        let schema = self.schema?;
        match e {
            Expr::Nested(x) => self.column(x),
            Expr::Column(name) => self.column_of(schema, name),
            _ => None,
        }
    }

    fn column_of<'s>(&self, schema: &'s Schema, name: &Name) -> Option<&'s Column> {
        match name.0.as_slice() {
            [col] => {
                for scope in self.stack.iter().rev() {
                    let mut found: Vec<&'s Column> = Vec::new();
                    let mut unknown = false;
                    for (_, table) in scope {
                        match table {
                            Some(t) if schema.knows_table(t) => {
                                if let Some(c) = schema.get(t, col) {
                                    found.push(c);
                                }
                            }
                            // A derived table or a table the schema does not list may have the column.
                            _ => unknown = true,
                        }
                    }
                    match (found.first(), unknown) {
                        (Some(first), false)
                            if found.iter().all(|c| {
                                c.class == first.class && c.collation == first.collation
                            }) =>
                        {
                            return Some(*first);
                        }
                        (None, false) => continue,
                        _ => return None,
                    }
                }
                None
            }
            [qual, col] => {
                for scope in self.stack.iter().rev() {
                    if let Some((_, table)) = scope.iter().find(|(b, _)| b == qual) {
                        return schema.get(table.as_ref()?, col);
                    }
                }
                None
            }
            [s, t, col] => schema.get(&Name(vec![s.clone(), t.clone()]), col),
            _ => None,
        }
    }
}

/// True for a collation that compares and orders text by bytes (code points): `C`, `POSIX`,
/// `ucs_basic`, SQLite's `BINARY`, MySQL/MariaDB `*_bin` and `binary`.
pub fn is_bytewise_collation(name: &str) -> bool {
    let n = name
        .trim()
        .trim_matches(['"', '`', '\''])
        .to_ascii_lowercase();
    matches!(n.as_str(), "c" | "posix" | "ucs_basic" | "binary") || n.ends_with("_bin")
}

fn collect(t: &TableRef, out: &mut Vec<(String, Option<Name>)>) {
    match t {
        TableRef::Table { name, alias } => out.push((
            alias.clone().unwrap_or_else(|| name.last().to_string()),
            Some(name.clone()),
        )),
        TableRef::Subquery { alias, .. } => out.push((alias.clone(), None)),
        TableRef::Function { name, alias, .. } => {
            out.push((alias.clone().unwrap_or_else(|| name.clone()), None))
        }
        TableRef::Join { left, right, .. } => {
            collect(left, out);
            collect(right, out);
        }
    }
}