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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Tiers, allowances, the per-translation report, and the refusal error.

use std::collections::BTreeSet;
use std::fmt;

/// How a target gives a construct. Order matters: a statement's tier is the maximum of its parts.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Tier {
    /// Same meaning by construction and by test.
    Exact,
    /// Target lacks it; an equivalent form exists, with a stated difference.
    Emulated,
    /// Same meaning only if the caller accepts a named assumption ([`Allowance`]).
    Conditional,
    /// No meaning-preserving equivalent. The writer returns [`Untranslatable`], never text.
    Refused,
}

impl Tier {
    pub fn name(self) -> &'static str {
        match self {
            Tier::Exact => "exact",
            Tier::Emulated => "emulated",
            Tier::Conditional => "conditional",
            Tier::Refused => "refused",
        }
    }
}

/// A named, explicit assumption a caller accepts for a Conditional construct.
/// There is **no** blanket "best effort" switch (DESIGN.md section 3).
///
/// **A name and the text above it are a contract.** Matrix files carry `<construct>.<allowance>` as a
/// leaf id, and `docs/LEAF-CONTRACTS.tsv` says that leaf means "the base leaf, with the divergence
/// this text describes accepted". Rewording a variant's doc is therefore a change of meaning: mint a
/// new variant (a new name) and leave the old one alone; ids are append-only.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Allowance {
    /// `now()` yields text (`YYYY-MM-DD HH:MM:SS`, UTC) rather than a timestamptz.
    NowAsText,
    /// A timestamp is text (`YYYY-MM-DD HH:MM:SS`) on the target and a field extracted from it is
    /// read from that text: it is the field of the stored text, in UTC.
    TimestampAsText,
    /// `EXTRACT(EPOCH FROM ts)` has no fractional seconds on the target: it is whole seconds.
    EpochWholeSeconds,
    /// A timestamp value has whole-second resolution on the target: a fraction of a second is dropped.
    TimestampWholeSeconds,
    /// A timestamp value has millisecond resolution on the target: digits beyond the third are 0.
    TimestampMillisecondResolution,
    /// `REPLACE INTO` is written as an upsert over every column of the table: the conflicting row is
    /// updated in place instead of deleted and re-inserted (DELETE triggers and `ON DELETE` actions
    /// do not fire; the new row keeps no value of the old one).
    ReplaceIsUpsert,
    /// The column's collation (from the caller's `Schema`) orders and compares text by locale rules
    /// (case- or accent-insensitive, language order); the target compares bytes, so the result may
    /// differ for the same data.
    SourceCollationNotBytewise,
    /// The source `||` is read as logical OR, which is MySQL's default `sql_mode`; under
    /// `PIPES_AS_CONCAT` the same text is string concatenation.
    PipesAsLogicalOr,
    /// The source `INSERT IGNORE` downgrades every error of the statement (a conversion, a NOT NULL,
    /// a unique conflict) to a warning; the target ignores unique-key conflicts only.
    IgnoreCoversOnlyUniqueConflicts,
    /// The source `SUBSTRING` start (and length) is assumed to be 1 (and 0) or more: a start of 0 or a
    /// negative start (counted from the end on MySQL) and a negative length are read differently by the
    /// target.
    SubstringStartAssumedPositive,
    /// `CURRENT_DATE` yields text (`YYYY-MM-DD`, the UTC date) rather than a date in the session time
    /// zone.
    DateAsText,
    /// `LIKE` case sensitivity is a *connection setting* on the target, not a property of the
    /// statement; the source's case-sensitive `LIKE` is exact only if that setting is on.
    LikeCaseSensitivityIsConnectionSetting,
    /// Case folding (`ILIKE`, `lower`, `upper`) is ASCII-only on the target.
    AsciiOnlyCaseFolding,
    /// A bad `CAST` that errors on the source silently yields 0 / a numeric prefix on the target.
    LenientCast,
    /// Division or modulo by zero is an error on the source and `NULL` on the target.
    DivisionByZeroIsNull,
    /// Text ordering and comparison use the target's collation; both engines must be configured
    /// alike (for example byte order on both) for results to match.
    TextCollation,
    /// Boolean values are stored and returned as integers 0/1.
    BooleanAsInteger,
    /// Timestamp arithmetic goes through text (`'YYYY-MM-DD HH:MM:SS'`, UTC, whole seconds).
    TimestampArithmeticAsText,
    /// JSON `->>` yields text on the source; on the target a scalar's type affinity can survive
    /// (a JSON `true` extracts as 1, not 'true').
    JsonScalarAffinity,
    /// JSON `->` yields a JSON value on the source; on the target it is its text representation, so
    /// comparison is textual (whitespace and key order are not normalised).
    JsonRepresentationAsText,
    /// The source `/` is exact (DECIMAL) division; the target divides as double precision.
    DecimalDivisionAsFloat,
    /// An array parameter used for membership: a `NULL` array, `NULL` elements or a `NULL` operand
    /// give an unknown result on the source but a definite true/false on the target.
    ArrayNullSemantics,
    /// `a / b` becomes integer division (`DIV`), valid only if both operands are integers.
    IntegerDivisionAssumed,
    /// An upsert fires on any unique key of the target, not only the stated conflict target.
    UpsertAnyUniqueKey,
    /// An aggregated string is silently truncated at a server setting (`group_concat_max_len`).
    AggregateStringTruncation,
    /// A regular expression is matched by the target's own engine: syntax beyond the common subset
    /// (classes, lookaround, `\\d`) and case sensitivity may differ from the source's.
    RegexpFlavor,
    /// A bitwise operator is applied to non-negative integers and a shift count is below the integer
    /// width: MySQL computes on unsigned 64-bit integers, PostgreSQL and SQLite on signed ones.
    BitwiseNonNegativeIntegers,
    /// A logical `XOR` is written as `<>`: exact only when both operands are booleans (or 0/1
    /// comparison results), not arbitrary numbers read by truthiness.
    XorOperandsBoolean,
    /// `EXTRACT(EPOCH FROM clock_timestamp())` is read once per statement on the target (SQLite's
    /// `'now'`), not once per call: two calls in one statement give the same instant. It needs
    /// SQLite 3.42 or later (`unixepoch(.., 'subsec')`).
    ClockIsStatementStart,
    /// `ON CONFLICT .. DO UPDATE .. WHERE cond` is written as `SET col = IF(cond, new, col)` for every
    /// column (MySQL's `ON DUPLICATE KEY UPDATE` has no `WHERE`). The affected-row count then differs:
    /// 1 for an inserted row, 2 for an updated one, and 0 both for a row the condition kept and for an
    /// update that changed nothing (MySQL counts changed rows only); under `CLIENT_FOUND_ROWS` the kept
    /// row counts 1, so a caller who tells "updated" from "kept" by the count must not set it.
    /// sqlx-mysql 0.9.0 always sets it (no option), so with sqlx the counts are 1 inserted, 2 updated and 1
    /// kept or unchanged: an insert cannot be told from a kept row.
    UpsertWhereAsIf,
    /// `column > now()` or `column <= now()` on a column declared [`Codec::EpochSeconds`] is written
    /// with SQLite's `unixepoch()` or MySQL/MariaDB's `UNIX_TIMESTAMP()`: the clock is read when
    /// the statement starts, where PostgreSQL's `now()` is the start of the transaction. SQLite
    /// needs 3.38 or later.
    EpochNowIsStatementStart,
}

impl Allowance {
    /// Every named allowance (what a caller who accepts all assumptions would grant).
    pub const ALL: &[Allowance] = &[
        Allowance::NowAsText,
        Allowance::TimestampAsText,
        Allowance::EpochWholeSeconds,
        Allowance::TimestampWholeSeconds,
        Allowance::TimestampMillisecondResolution,
        Allowance::ReplaceIsUpsert,
        Allowance::SourceCollationNotBytewise,
        Allowance::PipesAsLogicalOr,
        Allowance::IgnoreCoversOnlyUniqueConflicts,
        Allowance::SubstringStartAssumedPositive,
        Allowance::DateAsText,
        Allowance::LikeCaseSensitivityIsConnectionSetting,
        Allowance::AsciiOnlyCaseFolding,
        Allowance::LenientCast,
        Allowance::DivisionByZeroIsNull,
        Allowance::TextCollation,
        Allowance::BooleanAsInteger,
        Allowance::TimestampArithmeticAsText,
        Allowance::JsonScalarAffinity,
        Allowance::JsonRepresentationAsText,
        Allowance::IntegerDivisionAssumed,
        Allowance::UpsertAnyUniqueKey,
        Allowance::AggregateStringTruncation,
        Allowance::RegexpFlavor,
        Allowance::BitwiseNonNegativeIntegers,
        Allowance::XorOperandsBoolean,
        Allowance::ClockIsStatementStart,
        Allowance::ArrayNullSemantics,
        Allowance::DecimalDivisionAsFloat,
        Allowance::UpsertWhereAsIf,
        Allowance::EpochNowIsStatementStart,
    ];

    pub fn name(self) -> &'static str {
        match self {
            Allowance::NowAsText => "now_as_text",
            Allowance::TimestampAsText => "timestamp_as_text",
            Allowance::EpochWholeSeconds => "epoch_whole_seconds",
            Allowance::TimestampWholeSeconds => "timestamp_whole_seconds",
            Allowance::TimestampMillisecondResolution => "timestamp_millisecond_resolution",
            Allowance::ReplaceIsUpsert => "replace_is_upsert",
            Allowance::SourceCollationNotBytewise => "source_collation_not_bytewise",
            Allowance::PipesAsLogicalOr => "pipes_as_logical_or",
            Allowance::IgnoreCoversOnlyUniqueConflicts => "ignore_covers_only_unique_conflicts",
            Allowance::SubstringStartAssumedPositive => "substring_start_assumed_positive",
            Allowance::DateAsText => "date_as_text",
            Allowance::LikeCaseSensitivityIsConnectionSetting => {
                "like_case_sensitivity_is_connection_setting"
            }
            Allowance::AsciiOnlyCaseFolding => "ascii_only_case_folding",
            Allowance::LenientCast => "lenient_cast",
            Allowance::DivisionByZeroIsNull => "division_by_zero_is_null",
            Allowance::TextCollation => "text_collation",
            Allowance::BooleanAsInteger => "boolean_as_integer",
            Allowance::TimestampArithmeticAsText => "timestamp_arithmetic_as_text",
            Allowance::JsonScalarAffinity => "json_scalar_affinity",
            Allowance::JsonRepresentationAsText => "json_representation_as_text",
            Allowance::ArrayNullSemantics => "array_null_semantics",
            Allowance::DecimalDivisionAsFloat => "decimal_division_as_float",
            Allowance::IntegerDivisionAssumed => "integer_division_assumed",
            Allowance::UpsertAnyUniqueKey => "upsert_any_unique_key",
            Allowance::AggregateStringTruncation => "aggregate_string_truncation",
            Allowance::RegexpFlavor => "regexp_flavor",
            Allowance::BitwiseNonNegativeIntegers => "bitwise_non_negative_integers",
            Allowance::XorOperandsBoolean => "xor_operands_boolean",
            Allowance::ClockIsStatementStart => "clock_is_statement_start",
            Allowance::EpochNowIsStatementStart => "epoch_now_is_statement_start",
            Allowance::UpsertWhereAsIf => "upsert_where_as_if",
        }
    }
}

/// One line of the report: a construct used and how the target gave it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
    /// Stable construct id, e.g. `returning`, `upsert`, `ilike`, `fn:string_agg`.
    pub construct: String,
    pub tier: Tier,
    /// What differs, for Emulated/Conditional.
    pub note: String,
    pub allowance: Option<Allowance>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Report {
    pub entries: Vec<Entry>,
}

impl Report {
    pub fn push(&mut self, e: Entry) {
        if !self.entries.contains(&e) {
            self.entries.push(e);
        }
    }
    pub fn worst(&self) -> Tier {
        self.entries
            .iter()
            .map(|e| e.tier)
            .max()
            .unwrap_or(Tier::Exact)
    }
    pub fn constructs(&self) -> BTreeSet<&str> {
        self.entries.iter().map(|e| e.construct.as_str()).collect()
    }
    pub fn tier_of(&self, construct: &str) -> Option<Tier> {
        self.entries
            .iter()
            .filter(|e| e.construct == construct)
            .map(|e| e.tier)
            .max()
    }
}

/// How a column's values are stored on a target when that differs from the source's type. Declared
/// by the caller with [`Options::with_codec`]; a statement translator cannot see it in the text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Codec {
    /// A timestamp stored as integer unix seconds.
    EpochSeconds,
    /// A JSON document stored as text.
    JsonText,
}

impl Codec {
    /// The leaf id a refusal names.
    pub fn leaf(self) -> &'static str {
        match self {
            Codec::EpochSeconds => "codec.epoch_seconds",
            Codec::JsonText => "codec.json_text",
        }
    }
}

/// Everything a caller may relax, explicitly.
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct Options {
    pub allow: BTreeSet<Allowance>,
    /// What the caller knows about its base tables, if anything (see [`crate::schema`]).
    pub schema: Option<crate::schema::Schema>,
    /// Columns stored differently on the target, keyed by (table, column).
    pub codecs: std::collections::BTreeMap<(String, String), Codec>,
}

impl Options {
    /// Give the translator the classes of base-table columns; a comparison on a column that is not
    /// text then involves no text collation.
    pub fn with_schema(mut self, schema: crate::schema::Schema) -> Self {
        self.schema = Some(schema);
        self
    }

    /// Declare that `table.column` is stored with `codec` on the target. A translation to another
    /// dialect that reads or writes `table` is refused, naming the codec, instead of returning text
    /// that silently gives different results. The exceptions, for SQLite, MySQL and MariaDB: a plain PostgreSQL
    /// `INSERT .. VALUES`, `UPDATE .. SET` or `DELETE` of parameters and literals translates, where a
    /// `WHERE` only compares columns with parameters or literals (an epoch column only with a
    /// parameter), and a parameter for an
    /// [`Codec::EpochSeconds`] column is reported as [`ParamBinding::EpochSeconds`].
    ///
    /// `table` is matched against the last part of a table name, ignoring ASCII case.
    pub fn with_codec(mut self, table: &str, column: &str, codec: Codec) -> Self {
        self.codecs
            .insert((table.to_string(), column.to_string()), codec);
        self
    }

    pub fn with(mut self, a: Allowance) -> Self {
        self.allow.insert(a);
        self
    }
}

/// The only way a translation fails. Carries no SQL text (DESIGN.md section 3).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Untranslatable {
    pub construct: String,
    pub source: String,
    pub target: String,
    pub reason: String,
    /// What the caller could do instead, if anything.
    pub alternatives: Vec<String>,
}

impl Untranslatable {
    /// The leaf id a gate should look up for this refusal. A refusal names the form that cannot be
    /// translated (`cast.to_uuid`, `upsert.no_conflict_key`) or, where the whole construct is
    /// refused, the construct itself (`fn:md5`). A backend that refuses a leaf has no enabled row
    /// for it.
    pub fn subject(&self) -> String {
        self.construct.clone()
    }
}

impl fmt::Display for Untranslatable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "untranslatable `{}` ({} -> {}): {}",
            self.construct, self.source, self.target, self.reason
        )?;
        if !self.alternatives.is_empty() {
            write!(f, " [alternatives: {}]", self.alternatives.join("; "))?;
        }
        Ok(())
    }
}

impl std::error::Error for Untranslatable {}

/// Reading failed: the text is not valid for the source dialect, or uses a construct the IR does not
/// represent (which is an error, not a pass-through).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ReadError {
    Syntax(String),
    NotInIr { construct: String, detail: String },
}

impl fmt::Display for ReadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ReadError::Syntax(s) => write!(f, "syntax error: {s}"),
            ReadError::NotInIr { construct, detail } => {
                write!(f, "construct `{construct}` is not in the IR: {detail}")
            }
        }
    }
}

impl std::error::Error for ReadError {}

/// How the caller must bind one source parameter on the target. The *text* of a statement is not
/// enough when a parameter changes shape between engines (an array that SQLite and MySQL can only
/// take as JSON text).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ParamBinding {
    /// A single value, bound as it would be on the source.
    Scalar,
    /// A native array value (PostgreSQL `int4[]`, `text[]`, ...).
    NativeArray,
    /// A JSON array, bound as text: `[1,3]` or `["a","b"]`.
    JsonArrayText,
    /// A value for a [`Codec::EpochSeconds`] column: bind the timestamp as integer unix seconds, or
    /// `NULL`. A value with a fraction of a second has no verified binding: refuse it, do not round.
    EpochSeconds,
    /// A value for a [`Codec::JsonText`] column: bind one valid JSON document as text, or `NULL`.
    /// The target stores the text as given and does not validate it: refuse text that is not JSON.
    JsonText,
}

impl ParamBinding {
    pub fn name(self) -> &'static str {
        match self {
            ParamBinding::Scalar => "scalar",
            ParamBinding::NativeArray => "native_array",
            ParamBinding::JsonArrayText => "json_array_text",
            ParamBinding::EpochSeconds => "epoch_seconds",
            ParamBinding::JsonText => "json_text",
        }
    }
}

/// A successful translation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Translation {
    pub sql: String,
    /// Number of distinct source parameters (`$1..$n`).
    pub param_count: u32,
    /// Source parameter numbers in the order their placeholders appear in `sql`. A target with
    /// numbered placeholders (`$n`, `?n`) can ignore it; a target with positional `?` binds the
    /// values in exactly this order (a source parameter used twice appears twice).
    pub param_order: Vec<u32>,
    /// One entry per source parameter (index `n - 1` is `$n`): how to bind it on the target.
    pub param_bindings: Vec<ParamBinding>,
    /// Result columns (0-based, in order) that hold integer unix seconds on the target because the
    /// selected column has [`Codec::EpochSeconds`]: the caller must decode them to a timestamp.
    pub epoch_columns: Vec<usize>,
    /// Result columns (0-based, in order) that hold a JSON document as text on the target because
    /// the selected column has [`Codec::JsonText`]: the caller must parse them. The text keeps the
    /// key order and spacing it was stored with, which the source's `jsonb` does not.
    pub json_columns: Vec<usize>,
    pub report: Report,
}

/// An assumption the *source* text carries that the target must honour or refuse: for example a
/// SQLite `LIKE` is case-insensitive only while a connection setting is at its default. Recorded by
/// the reader and checked against [`Options`] like any Conditional construct.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReadNote {
    pub construct: String,
    pub note: String,
    pub allowance: Allowance,
}

/// A successful read.
#[derive(Clone, Debug, PartialEq)]
pub struct Read {
    pub stmt: crate::ast::Statement,
    pub notes: Vec<ReadNote>,
}