Skip to main content

unisql_sqlparser_adapter/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! sqlparser adapter: text -> IR for the dialects that sqlparser can parse. The per-dialect
3//! differences are the [`Rules`]; no parser type escapes this crate. **Anything the IR cannot represent is `ReadError::NotInIr`, never a pass-through.**
4//!
5//! `Query`, `Select`, `Insert`, `Update` and `Delete` are destructured with every field named and no
6//! `..`: a sqlparser upgrade that adds a field fails the build here, forcing a decision rather than
7//! silently dropping a construct.
8
9use std::cell::RefCell;
10
11use sqlparser::ast as sp;
12use sqlparser::dialect::Dialect;
13use sqlparser::parser::Parser;
14use unisql_core::ast::*;
15use unisql_core::{Allowance, Column, ColumnClass, Read, ReadError, ReadNote, Schema};
16
17/// What differs between source dialects at the AST-to-IR step.
18pub struct Rules {
19    pub name: &'static str,
20    pub dialect: fn() -> Box<dyn Dialect>,
21    /// Quoted identifiers are case-insensitive too (SQLite): fold everything to lower case.
22    pub fold_quoted: bool,
23    /// `NULL` sorts as the smallest value (SQLite) rather than the largest (PostgreSQL).
24    pub nulls_smallest: bool,
25    /// Parameters: `$n` (PostgreSQL) or `?`, `?n`, `:name`, `@name`, `$name` (SQLite).
26    pub question_placeholders: bool,
27    /// `LIKE` is case-insensitive by default (SQLite, ASCII only).
28    pub like_ci_default: bool,
29    /// `LIKE` has a default escape character (PostgreSQL: backslash); otherwise none.
30    pub like_default_escape: bool,
31    /// A negative `LIMIT` means no limit (SQLite).
32    pub negative_limit_unlimited: bool,
33}
34
35pub static POSTGRES: Rules = Rules {
36    name: "postgres",
37    dialect: || Box::new(sqlparser::dialect::PostgreSqlDialect {}),
38    fold_quoted: false,
39    nulls_smallest: false,
40    question_placeholders: false,
41    like_ci_default: false,
42    like_default_escape: true,
43    negative_limit_unlimited: false,
44};
45
46pub static MYSQL: Rules = Rules {
47    name: "mysql",
48    dialect: || Box::new(sqlparser::dialect::MySqlDialect {}),
49    fold_quoted: true,
50    nulls_smallest: true,
51    question_placeholders: true,
52    like_ci_default: false,
53    like_default_escape: true,
54    negative_limit_unlimited: false,
55};
56
57pub static SQLITE: Rules = Rules {
58    name: "sqlite",
59    dialect: || Box::new(sqlparser::dialect::SQLiteDialect {}),
60    fold_quoted: true,
61    nulls_smallest: true,
62    question_placeholders: true,
63    like_ci_default: true,
64    like_default_escape: false,
65    negative_limit_unlimited: true,
66};
67
68struct Cx {
69    rules: &'static Rules,
70    max_param: u32,
71    names: Vec<(String, u32)>,
72    notes: Vec<ReadNote>,
73}
74
75thread_local! {
76    static CX: RefCell<Option<Cx>> = const { RefCell::new(None) };
77}
78
79fn rules() -> &'static Rules {
80    CX.with(|c| c.borrow().as_ref().expect("reader context").rules)
81}
82
83fn add_note(construct: &str, note: &str, allowance: Allowance) {
84    CX.with(|c| {
85        let mut b = c.borrow_mut();
86        let cx = b.as_mut().expect("reader context");
87        let n = ReadNote {
88            construct: construct.into(),
89            note: note.into(),
90            allowance,
91        };
92        if !cx.notes.contains(&n) {
93            cx.notes.push(n);
94        }
95    });
96}
97
98fn bump_param(explicit: Option<u32>, name: Option<&str>) -> u32 {
99    CX.with(|c| {
100        let mut b = c.borrow_mut();
101        let cx = b.as_mut().expect("reader context");
102        match (explicit, name) {
103            (Some(n), _) => {
104                cx.max_param = cx.max_param.max(n);
105                n
106            }
107            (None, Some(nm)) => {
108                if let Some((_, n)) = cx.names.iter().find(|(k, _)| k == nm) {
109                    return *n;
110                }
111                cx.max_param += 1;
112                let n = cx.max_param;
113                cx.names.push((nm.to_string(), n));
114                n
115            }
116            (None, None) => {
117                cx.max_param += 1;
118                cx.max_param
119            }
120        }
121    })
122}
123
124type R<T> = Result<T, ReadError>;
125
126fn no<T>(construct: &str, detail: &str) -> R<T> {
127    Err(ReadError::NotInIr {
128        construct: construct.to_string(),
129        detail: detail.to_string(),
130    })
131}
132
133/// Read exactly one statement written in the dialect described by `rules`.
134pub fn read(sql: &str, rules: &'static Rules) -> R<Read> {
135    CX.with(|c| {
136        *c.borrow_mut() = Some(Cx {
137            rules,
138            max_param: 0,
139            names: vec![],
140            notes: vec![],
141        })
142    });
143    let out = (|| {
144        let d = (rules.dialect)();
145        // MySQL's default sql_mode makes `||` a logical OR with OR's precedence, but the parser
146        // gives it concatenation's. Rewrite the operator token in the text (by position, so nothing
147        // else is re-spelled) before parsing, and say so.
148        let rewritten;
149        let sql = if rules.name == "mysql" {
150            match pipes_to_or(sql, d.as_ref()) {
151                Some(s) => {
152                    add_note(
153                        "pipes_as_or",
154                        "MySQL `||` is logical OR in the default sql_mode; under PIPES_AS_CONCAT it is concatenation",
155                        Allowance::PipesAsLogicalOr,
156                    );
157                    rewritten = s;
158                    rewritten.as_str()
159                }
160                None => sql,
161            }
162        } else {
163            sql
164        };
165        let mut stmts =
166            Parser::parse_sql(d.as_ref(), sql).map_err(|e| ReadError::Syntax(e.to_string()))?;
167        if stmts.len() != 1 {
168            return no(
169                "multiple_statements",
170                &format!("expected one statement, found {}", stmts.len()),
171            );
172        }
173        statement(stmts.remove(0))
174    })();
175    let cx = CX.with(|c| c.borrow_mut().take()).expect("reader context");
176    out.map(|stmt| Read {
177        stmt,
178        notes: cx.notes,
179    })
180}
181
182/// `sql` with each `||` operator token replaced by ` OR `; `None` when there is none (or the text does
183/// not tokenize, which the parser then reports).
184fn pipes_to_or(sql: &str, dialect: &dyn sqlparser::dialect::Dialect) -> Option<String> {
185    use sqlparser::tokenizer::{Token, Tokenizer};
186    let tokens = Tokenizer::new(dialect, sql).tokenize_with_location().ok()?;
187    let line_starts: Vec<usize> = std::iter::once(0)
188        .chain(
189            sql.chars()
190                .enumerate()
191                .filter(|(_, c)| *c == '\n')
192                .map(|(i, _)| i + 1),
193        )
194        .collect();
195    let mut spots: Vec<usize> = tokens
196        .iter()
197        .filter(|t| t.token == Token::StringConcat)
198        .filter_map(|t| {
199            let line = usize::try_from(t.span.start.line).ok()?.checked_sub(1)?;
200            let col = usize::try_from(t.span.start.column).ok()?.checked_sub(1)?;
201            Some(line_starts.get(line)? + col)
202        })
203        .collect();
204    if spots.is_empty() {
205        return None;
206    }
207    spots.sort_unstable();
208    let chars: Vec<char> = sql.chars().collect();
209    let mut out = String::new();
210    let mut at = 0;
211    for s in spots {
212        if s < at || s + 2 > chars.len() || chars[s] != '|' || chars[s + 1] != '|' {
213            return None;
214        }
215        out.extend(&chars[at..s]);
216        out.push_str(" OR ");
217        at = s + 2;
218    }
219    out.extend(&chars[at..]);
220    Some(out)
221}
222
223/// The classes of the base-table columns a DDL script declares, read for types only: this is not DDL
224/// translation, and no statement of it is ever written out.
225#[derive(Clone, Debug, Default)]
226pub struct SchemaRead {
227    pub schema: Schema,
228    /// Statements the parser could not read (a function body, a `DO` block): each head and reason.
229    /// They are skipped, which can only leave a column unregistered (unknown).
230    pub skipped: Vec<String>,
231}
232
233/// Class of a declared type, from its spelling (`None`: a type UniSQL does not classify). MySQL's
234/// `tinyint(1)` is numeric; `boolean` is `Boolean` only because the declared type says so.
235fn class_of_type(dt: &sp::DataType) -> Option<ColumnClass> {
236    let t = dt.to_string().to_ascii_lowercase();
237    if t.ends_with("[]") || t.starts_with("array") {
238        return None;
239    }
240    let base: String = t
241        .chars()
242        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == ' ')
243        .collect();
244    let base = base.trim();
245    let first = base.split_whitespace().next().unwrap_or("");
246    Some(match base {
247        "character varying" | "character" | "national character varying" | "national character" => {
248            ColumnClass::Text
249        }
250        "double precision" => ColumnClass::Numeric,
251        b if b.starts_with("timestamp")
252            || b == "time"
253            || b.starts_with("time with")
254            || b.starts_with("time without") =>
255        {
256            ColumnClass::Other
257        }
258        _ => match first {
259            "text" | "varchar" | "char" | "nchar" | "nvarchar" | "tinytext" | "mediumtext"
260            | "longtext" | "string" | "bpchar" | "clob" => ColumnClass::Text,
261            "int" | "integer" | "smallint" | "bigint" | "tinyint" | "mediumint" | "int2"
262            | "int4" | "int8" | "serial" | "bigserial" | "smallserial" | "decimal" | "numeric"
263            | "dec" | "float" | "float4" | "float8" | "real" | "double" | "number" => {
264                ColumnClass::Numeric
265            }
266            "boolean" | "bool" => ColumnClass::Boolean,
267            "date" | "datetime" | "timestamptz" | "year" | "interval" | "uuid" | "json"
268            | "jsonb" | "bytea" | "blob" | "tinyblob" | "mediumblob" | "longblob" | "binary"
269            | "varbinary" | "bit" | "inet" | "cidr" | "macaddr" => ColumnClass::Other,
270            _ => return None,
271        },
272    })
273}
274
275fn column_from_def(c: &sp::ColumnDef) -> Column {
276    let class = class_of_type(&c.data_type);
277    let collation = c.options.iter().find_map(|o| match &o.option {
278        sp::ColumnOption::Collation(n) => {
279            Some(n.to_string().trim_matches(['"', '`', '\'']).to_string())
280        }
281        _ => None,
282    });
283    let mut col = Column::new(class.unwrap_or(ColumnClass::Unknown));
284    col.collation = collation;
285    col
286}
287
288/// Read `CREATE TABLE`, `ALTER TABLE .. ADD|DROP|ALTER COLUMN` and `DROP TABLE` out of a DDL script
289/// (a migration file) in the dialect described by `rules`. Statements are split on `;` tokens, so a
290/// dollar-quoted body does not split; a statement that does not parse is listed in `skipped`.
291pub fn read_schema(ddl: &str, rules: &'static Rules) -> R<SchemaRead> {
292    // `ident` consults the reader context for quoted-name folding, so one must be installed.
293    CX.with(|c| {
294        *c.borrow_mut() = Some(Cx {
295            rules,
296            max_param: 0,
297            names: vec![],
298            notes: vec![],
299        })
300    });
301    let out = read_schema_inner(ddl, rules);
302    CX.with(|c| c.borrow_mut().take());
303    out
304}
305
306fn read_schema_inner(ddl: &str, rules: &'static Rules) -> R<SchemaRead> {
307    use sqlparser::tokenizer::{Token, Tokenizer};
308    let d = (rules.dialect)();
309    let tokens = Tokenizer::new(d.as_ref(), ddl)
310        .tokenize_with_location()
311        .map_err(|e| ReadError::Syntax(e.to_string()))?;
312    let chars: Vec<char> = ddl.chars().collect();
313    let line_starts: Vec<usize> = std::iter::once(0)
314        .chain(
315            chars
316                .iter()
317                .enumerate()
318                .filter(|(_, c)| **c == '\n')
319                .map(|(i, _)| i + 1),
320        )
321        .collect();
322    let offset = |loc: sqlparser::tokenizer::Location| -> Option<usize> {
323        let line = usize::try_from(loc.line).ok()?.checked_sub(1)?;
324        let col = usize::try_from(loc.column).ok()?.checked_sub(1)?;
325        Some(line_starts.get(line)? + col)
326    };
327    let mut cuts: Vec<usize> = tokens
328        .iter()
329        .filter(|t| t.token == Token::SemiColon)
330        .filter_map(|t| offset(t.span.start))
331        .collect();
332    cuts.push(chars.len());
333    let mut out = SchemaRead::default();
334    let mut from = 0;
335    for cut in cuts {
336        if cut < from || cut > chars.len() {
337            continue;
338        }
339        let text: String = chars[from..cut].iter().collect();
340        from = (cut + 1).min(chars.len());
341        if text.trim().is_empty() {
342            continue;
343        }
344        let stmts = match Parser::parse_sql(d.as_ref(), &text) {
345            Ok(s) => s,
346            Err(e) => {
347                let head: String = text
348                    .split_whitespace()
349                    .take(4)
350                    .collect::<Vec<_>>()
351                    .join(" ");
352                out.skipped.push(format!("{head}: {e}"));
353                continue;
354            }
355        };
356        for st in stmts {
357            apply_ddl(&mut out.schema, st);
358        }
359    }
360    Ok(out)
361}
362
363fn apply_ddl(schema: &mut Schema, st: sp::Statement) {
364    match st {
365        sp::Statement::CreateTable(ct) => {
366            if ct.query.is_some() || ct.like.is_some() {
367                return;
368            }
369            let Ok(name) = object_name(&ct.name) else {
370                return;
371            };
372            schema.drop_table(&name);
373            schema.mark_columns_complete(name.0.clone());
374            for c in &ct.columns {
375                schema.set_column(name.0.clone(), ident(&c.name), column_from_def(c));
376                for o in &c.options {
377                    if matches!(
378                        o.option,
379                        sp::ColumnOption::PrimaryKey(_) | sp::ColumnOption::Unique(_)
380                    ) {
381                        schema.add_unique_key(name.0.clone(), vec![ident(&c.name)]);
382                    }
383                }
384            }
385            for con in &ct.constraints {
386                add_constraint_key(schema, &name, con);
387            }
388        }
389        sp::Statement::CreateIndex(ci) => {
390            let Ok(name) = object_name(&ci.table_name) else {
391                return;
392            };
393            if ci.unique {
394                match index_columns(&ci.columns) {
395                    Some(cols) if ci.predicate.is_none() => schema.add_unique_key(name.0, cols),
396                    _ => schema.mark_keys_unreliable(name.0),
397                }
398            }
399        }
400        sp::Statement::AlterTable(at) => {
401            let Ok(name) = object_name(&at.name) else {
402                return;
403            };
404            for op in at.operations {
405                match op {
406                    sp::AlterTableOperation::AddColumn { column_def, .. } => {
407                        schema.set_column(
408                            name.0.clone(),
409                            ident(&column_def.name),
410                            column_from_def(&column_def),
411                        );
412                    }
413                    sp::AlterTableOperation::AddConstraint { constraint, .. } => {
414                        add_constraint_key(schema, &name, &constraint);
415                    }
416                    sp::AlterTableOperation::DropPrimaryKey { .. }
417                    | sp::AlterTableOperation::DropConstraint { .. } => {
418                        schema.mark_keys_unreliable(name.0.clone());
419                    }
420                    sp::AlterTableOperation::DropColumn { column_names, .. } => {
421                        for c in &column_names {
422                            schema.drop_column(&name, &ident(c));
423                        }
424                    }
425                    sp::AlterTableOperation::AlterColumn {
426                        column_name,
427                        op: sp::AlterColumnOperation::SetDataType { data_type, .. },
428                    } => {
429                        let class = class_of_type(&data_type).unwrap_or(ColumnClass::Unknown);
430                        // A new type resets the collation unless the statement states one.
431                        schema.set_column(name.0.clone(), ident(&column_name), Column::new(class));
432                    }
433                    _ => {}
434                }
435            }
436        }
437        sp::Statement::Drop {
438            object_type: sp::ObjectType::Index,
439            ..
440        } => schema.mark_all_keys_unreliable(),
441        sp::Statement::Drop {
442            object_type: sp::ObjectType::Table,
443            names,
444            ..
445        } => {
446            for n in &names {
447                if let Ok(name) = object_name(n) {
448                    schema.drop_table(&name);
449                }
450            }
451        }
452        _ => {}
453    }
454}
455
456/// The column names of an index definition when every part is a plain column.
457fn index_columns(cols: &[sp::IndexColumn]) -> Option<Vec<String>> {
458    cols.iter()
459        .map(|c| match &c.column.expr {
460            sp::Expr::Identifier(i) => Some(ident(i)),
461            _ => None,
462        })
463        .collect()
464}
465
466/// A PRIMARY KEY or UNIQUE table constraint: its columns are a unique key (an index over an
467/// expression makes the table's key list unreliable).
468fn add_constraint_key(schema: &mut Schema, table: &Name, con: &sp::TableConstraint) {
469    let cols = match con {
470        sp::TableConstraint::PrimaryKey(p) => &p.columns,
471        sp::TableConstraint::Unique(u) => &u.columns,
472        _ => return,
473    };
474    match index_columns(cols) {
475        Some(c) => schema.add_unique_key(table.0.clone(), c),
476        None => schema.mark_keys_unreliable(table.0.clone()),
477    }
478}
479
480fn statement(s: sp::Statement) -> R<Statement> {
481    match s {
482        sp::Statement::Query(q)
483            if matches!(
484                &*q.body,
485                sp::SetExpr::Insert(_) | sp::SetExpr::Update(_) | sp::SetExpr::Delete(_)
486            ) =>
487        {
488            // `WITH .. INSERT|UPDATE|DELETE ..` is a query node in the parser's tree.
489            let mut q = *q;
490            let with = q.with.take();
491            if q.to_string() != q.body.to_string() {
492                return no(
493                    "query_clause",
494                    "clauses around a WITH .. INSERT/UPDATE/DELETE",
495                );
496            }
497            let inner = match *q.body {
498                sp::SetExpr::Insert(st) | sp::SetExpr::Update(st) | sp::SetExpr::Delete(st) => {
499                    statement(st)?
500                }
501                _ => unreachable!(),
502            };
503            match with {
504                None => Ok(inner),
505                Some(w) => {
506                    let (ctes, recursive) = read_ctes(w)?;
507                    Ok(Statement::With(WithStatement {
508                        recursive,
509                        ctes,
510                        stmt: Box::new(inner),
511                    }))
512                }
513            }
514        }
515        sp::Statement::Query(q) => Ok(Statement::Query(Box::new(query(*q)?))),
516        sp::Statement::Insert(i) => insert(i),
517        sp::Statement::Update(u) => update(u),
518        sp::Statement::Delete(d) => delete(d),
519        other => no(
520            "statement",
521            &format!(
522                "{} is not a DML statement the first slice reads",
523                head(&other)
524            ),
525        ),
526    }
527}
528
529fn head(x: &impl std::fmt::Debug) -> String {
530    let s = format!("{x:?}");
531    s.split(|c: char| !c.is_alphanumeric() && c != '_')
532        .next()
533        .unwrap_or("")
534        .to_string()
535}
536
537/// Identifier folding: unquoted identifiers fold to lower case; quoted ones are exact, except where
538/// the dialect treats quoted names case-insensitively too (SQLite).
539fn ident(i: &sp::Ident) -> String {
540    if i.quote_style.is_some() && !rules().fold_quoted {
541        i.value.clone()
542    } else {
543        i.value.to_lowercase()
544    }
545}
546
547fn object_name(n: &sp::ObjectName) -> R<Name> {
548    let mut parts = Vec::new();
549    for p in &n.0 {
550        match p {
551            sp::ObjectNamePart::Identifier(i) => parts.push(ident(i)),
552            other => return no("object_name_part", &head(other)),
553        }
554    }
555    Ok(Name(parts))
556}
557
558fn single_name(n: &sp::ObjectName) -> R<String> {
559    let nm = object_name(n)?;
560    if nm.0.len() != 1 {
561        return no(
562            "qualified_column_target",
563            "expected an unqualified column name",
564        );
565    }
566    Ok(nm.0.into_iter().next().unwrap())
567}
568
569/// The `WITH` list of a query or of a data-modifying statement.
570fn read_ctes(w: sp::With) -> R<(Vec<Cte>, bool)> {
571    let sp::With {
572        with_token: _,
573        recursive,
574        cte_tables,
575    } = w;
576    let mut ctes = Vec::new();
577    for c in cte_tables {
578        let sp::Cte {
579            alias,
580            query: cq,
581            from,
582            materialized,
583            closing_paren_token: _,
584        } = c;
585        if from.is_some() || materialized.is_some() {
586            return no("cte_option", "MATERIALIZED / FROM in a CTE");
587        }
588        let mut columns = Vec::new();
589        for col in &alias.columns {
590            if col.data_type.is_some() {
591                return no("cte_column_type", "typed CTE column");
592            }
593            columns.push(ident(&col.name));
594        }
595        let dml = matches!(
596            &*cq.body,
597            sp::SetExpr::Insert(_) | sp::SetExpr::Update(_) | sp::SetExpr::Delete(_)
598        );
599        let cte_body = if dml {
600            // Nothing but the statement itself: a WITH / ORDER BY / LIMIT around it would be
601            // dropped silently otherwise.
602            if cq.to_string() != cq.body.to_string() {
603                return no("cte_dml_clause", "clauses around a data-modifying CTE");
604            }
605            match *cq.body {
606                sp::SetExpr::Insert(st) | sp::SetExpr::Update(st) | sp::SetExpr::Delete(st) => {
607                    CteBody::Dml(Box::new(statement(st)?))
608                }
609                _ => unreachable!(),
610            }
611        } else {
612            CteBody::Query(Box::new(query(*cq)?))
613        };
614        ctes.push(Cte {
615            name: ident(&alias.name),
616            columns,
617            body: cte_body,
618        });
619    }
620    Ok((ctes, recursive))
621}
622
623fn query(q: sp::Query) -> R<Query> {
624    let sp::Query {
625        with,
626        body,
627        order_by,
628        limit_clause,
629        fetch,
630        locks,
631        for_clause,
632        settings,
633        format_clause,
634        pipe_operators,
635    } = q;
636    if fetch.is_some() {
637        return no("fetch_first", "FETCH FIRST is not in the IR (use LIMIT)");
638    }
639    if for_clause.is_some()
640        || settings.is_some()
641        || format_clause.is_some()
642        || !pipe_operators.is_empty()
643    {
644        return no("query_clause", "FOR/SETTINGS/FORMAT/pipe operators");
645    }
646    let mut ctes = Vec::new();
647    let mut recursive = false;
648    if let Some(w) = with {
649        (ctes, recursive) = read_ctes(w)?;
650    }
651    let mut body = set_expr(*body)?;
652    let mut lock = None;
653    match locks.len() {
654        0 => {}
655        1 => {
656            let sp::LockClause {
657                lock_type,
658                of,
659                nonblock,
660            } = locks.into_iter().next().unwrap();
661            lock = Some(RowLockClause {
662                strength: match lock_type {
663                    sp::LockType::Update => RowLock::Update,
664                    sp::LockType::Share => RowLock::Share,
665                },
666                of: match of {
667                    Some(n) => Some(object_name(&n)?),
668                    None => None,
669                },
670                wait: match nonblock {
671                    None => LockWait::Block,
672                    Some(sp::NonBlock::Nowait) => LockWait::NoWait,
673                    Some(sp::NonBlock::SkipLocked) => LockWait::SkipLocked,
674                },
675            });
676        }
677        _ => return no("row_lock_multiple", "several locking clauses"),
678    }
679    if let Some(l) = lock {
680        match &mut body {
681            SetExpr::Select(s) => s.lock = Some(l),
682            _ => return no("row_lock_on_set_op", "locking clause on a set operation"),
683        }
684    }
685    let mut order = Vec::new();
686    if let Some(ob) = order_by {
687        let sp::OrderBy { kind, interpolate } = ob;
688        if interpolate.is_some() {
689            return no("order_by_interpolate", "INTERPOLATE");
690        }
691        match kind {
692            sp::OrderByKind::Expressions(items) => {
693                for it in items {
694                    order.push(order_item(it)?);
695                }
696            }
697            sp::OrderByKind::All(_) => return no("order_by_all", "ORDER BY ALL"),
698        }
699    }
700    let (mut limit, mut offset) = (None, None);
701    match limit_clause {
702        None => {}
703        Some(sp::LimitClause::LimitOffset {
704            limit: l,
705            offset: o,
706            limit_by,
707        }) => {
708            if !limit_by.is_empty() {
709                return no("limit_by", "LIMIT .. BY");
710            }
711            limit = l.map(expr).transpose()?;
712            if rules().negative_limit_unlimited {
713                // SQLite: a negative LIMIT means "no limit".
714                let neg = matches!(&limit, Some(Expr::Unary { op: UnaryOp::Minus, expr })
715                    if matches!(**expr, Expr::Literal(Literal::Number(_))));
716                if neg {
717                    limit = None;
718                }
719            }
720            if let Some(o) = o {
721                let sp::Offset { value, rows } = o;
722                if !matches!(rows, sp::OffsetRows::None) {
723                    return no("offset_rows", "OFFSET .. ROWS");
724                }
725                offset = Some(expr(value)?);
726            }
727        }
728        Some(sp::LimitClause::OffsetCommaLimit {
729            offset: o,
730            limit: l,
731        }) => {
732            offset = Some(expr(o)?);
733            limit = Some(expr(l)?);
734        }
735    }
736    Ok(Query {
737        with: ctes,
738        recursive,
739        body,
740        order_by: order,
741        limit,
742        offset,
743    })
744}
745
746fn order_item(o: sp::OrderByExpr) -> R<OrderItem> {
747    let sp::OrderByExpr {
748        expr: e,
749        options,
750        with_fill,
751    } = o;
752    if with_fill.is_some() {
753        return no("order_by_with_fill", "WITH FILL");
754    }
755    let desc = matches!(options.sort, Some(sp::OrderBySort::Desc));
756    // The source's default NULL placement, made explicit so any target preserves it: NULL is the
757    // largest value on PostgreSQL (first when descending) and the smallest on SQLite (first ascending).
758    let default_first = if rules().nulls_smallest { !desc } else { desc };
759    let nulls_first = options.nulls_first.unwrap_or(default_first);
760    Ok(OrderItem {
761        expr: expr(e)?,
762        desc,
763        nulls_first: Some(nulls_first),
764    })
765}
766
767fn set_expr(s: sp::SetExpr) -> R<SetExpr> {
768    match s {
769        sp::SetExpr::Select(sel) => Ok(SetExpr::Select(Box::new(select(*sel)?))),
770        sp::SetExpr::SetOperation {
771            left,
772            op,
773            set_quantifier,
774            right,
775        } => {
776            let op = match op {
777                sp::SetOperator::Union => SetOp::Union,
778                sp::SetOperator::Intersect => SetOp::Intersect,
779                sp::SetOperator::Except => SetOp::Except,
780                sp::SetOperator::Minus => return no("minus", "MINUS is not PostgreSQL"),
781            };
782            let all = match set_quantifier {
783                sp::SetQuantifier::All => true,
784                sp::SetQuantifier::Distinct | sp::SetQuantifier::None => false,
785                other => return no("set_quantifier", &head(&other)),
786            };
787            Ok(SetExpr::SetOp {
788                op,
789                all,
790                left: Box::new(set_expr(*left)?),
791                right: Box::new(set_expr(*right)?),
792            })
793        }
794        sp::SetExpr::Query(q) => {
795            let q = query(*q)?;
796            if !q.with.is_empty()
797                || !q.order_by.is_empty()
798                || q.limit.is_some()
799                || q.offset.is_some()
800            {
801                return no(
802                    "parenthesised_query",
803                    "parenthesised query with WITH/ORDER/LIMIT as a set operand",
804                );
805            }
806            Ok(q.body)
807        }
808        sp::SetExpr::Values(_) => no("values_query", "a bare VALUES query outside INSERT"),
809        other => no("set_expr", &head(&other)),
810    }
811}
812
813fn select(s: sp::Select) -> R<Select> {
814    let sp::Select {
815        select_token: _,
816        optimizer_hints,
817        distinct,
818        select_modifiers,
819        top,
820        top_before_distinct: _,
821        projection,
822        exclude,
823        into,
824        from,
825        lateral_views,
826        prewhere,
827        selection,
828        connect_by,
829        group_by,
830        cluster_by,
831        distribute_by,
832        sort_by,
833        having,
834        named_window,
835        qualify,
836        window_before_qualify: _,
837        value_table_mode,
838        flavor: _,
839    } = s;
840    if !optimizer_hints.is_empty()
841        || select_modifiers.is_some()
842        || top.is_some()
843        || exclude.is_some()
844        || into.is_some()
845        || !lateral_views.is_empty()
846        || prewhere.is_some()
847        || !connect_by.is_empty()
848        || !cluster_by.is_empty()
849        || !distribute_by.is_empty()
850        || !sort_by.is_empty()
851        || !named_window.is_empty()
852        || qualify.is_some()
853        || value_table_mode.is_some()
854    {
855        return no(
856            "select_clause",
857            "a SELECT clause the IR does not represent (TOP/INTO/WINDOW/QUALIFY/hints/...)",
858        );
859    }
860    let distinct = match distinct {
861        None | Some(sp::Distinct::All) => Distinct::No,
862        Some(sp::Distinct::Distinct) => Distinct::Yes,
863        Some(sp::Distinct::On(es)) => Distinct::On(es.into_iter().map(expr).collect::<R<_>>()?),
864    };
865    let group_by = match group_by {
866        sp::GroupByExpr::Expressions(es, mods) => {
867            if !mods.is_empty() {
868                return no("group_by_modifier", "ROLLUP/CUBE/TOTALS modifiers");
869            }
870            es.into_iter().map(expr).collect::<R<Vec<_>>>()?
871        }
872        sp::GroupByExpr::All(_) => return no("group_by_all", "GROUP BY ALL"),
873    };
874    let mut proj = Vec::new();
875    for it in projection {
876        proj.push(select_item(it)?);
877    }
878    let mut from_refs = Vec::new();
879    for t in from {
880        from_refs.push(table_with_joins(t)?);
881    }
882    Ok(Select {
883        distinct,
884        projection: proj,
885        from: from_refs,
886        where_: selection.map(expr).transpose()?,
887        group_by,
888        having: having.map(expr).transpose()?,
889        lock: None,
890    })
891}
892
893fn wildcard_plain(o: &sp::WildcardAdditionalOptions) -> R<()> {
894    let sp::WildcardAdditionalOptions {
895        wildcard_token: _,
896        opt_ilike,
897        opt_exclude,
898        opt_except,
899        opt_replace,
900        opt_rename,
901        opt_alias,
902    } = o;
903    if opt_ilike.is_some()
904        || opt_exclude.is_some()
905        || opt_except.is_some()
906        || opt_replace.is_some()
907        || opt_rename.is_some()
908        || opt_alias.is_some()
909    {
910        return no("wildcard_option", "EXCLUDE/EXCEPT/REPLACE/RENAME on *");
911    }
912    Ok(())
913}
914
915fn select_item(it: sp::SelectItem) -> R<SelectItem> {
916    match it {
917        sp::SelectItem::UnnamedExpr(e) => Ok(SelectItem::Expr {
918            expr: expr(e)?,
919            alias: None,
920        }),
921        sp::SelectItem::ExprWithAlias { expr: e, alias } => Ok(SelectItem::Expr {
922            expr: expr(e)?,
923            alias: Some(ident(&alias)),
924        }),
925        sp::SelectItem::Wildcard(o) => {
926            wildcard_plain(&o)?;
927            Ok(SelectItem::Wildcard)
928        }
929        sp::SelectItem::QualifiedWildcard(kind, o) => {
930            wildcard_plain(&o)?;
931            match kind {
932                sp::SelectItemQualifiedWildcardKind::ObjectName(n) => {
933                    Ok(SelectItem::QualifiedWildcard(object_name(&n)?))
934                }
935                other => no("qualified_wildcard", &head(&other)),
936            }
937        }
938        other => no("select_item", &head(&other)),
939    }
940}
941
942fn alias_name(a: Option<sp::TableAlias>) -> R<Option<String>> {
943    match a {
944        None => Ok(None),
945        Some(sp::TableAlias {
946            explicit: _,
947            name,
948            columns,
949            at,
950        }) => {
951            if !columns.is_empty() || at.is_some() {
952                return no("table_alias_columns", "column list on a table alias");
953            }
954            Ok(Some(ident(&name)))
955        }
956    }
957}
958
959fn table_factor(t: sp::TableFactor) -> R<TableRef> {
960    match t {
961        sp::TableFactor::Table {
962            name,
963            alias,
964            args,
965            with_hints,
966            version,
967            with_ordinality,
968            partitions,
969            json_path,
970            sample,
971            index_hints,
972        } => {
973            // A table-valued function: positional expression arguments only.
974            if let Some(targs) = args {
975                let plain = with_hints.is_empty()
976                    && version.is_none()
977                    && !with_ordinality
978                    && partitions.is_empty()
979                    && json_path.is_none()
980                    && sample.is_none()
981                    && index_hints.is_empty()
982                    && targs.settings.is_none();
983                let nm = object_name(&name)?;
984                if plain && nm.0.len() == 1 {
985                    let mut out = Vec::new();
986                    for a in targs.args {
987                        match a {
988                            sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Expr(e)) => {
989                                out.push(expr(e)?)
990                            }
991                            _ => {
992                                return no(
993                                    "table_function_arg",
994                                    "named or wildcard argument of a table function",
995                                );
996                            }
997                        }
998                    }
999                    return Ok(TableRef::Function {
1000                        name: nm.0[0].clone(),
1001                        args: out,
1002                        alias: alias_name(alias)?,
1003                    });
1004                }
1005                return no(
1006                    "table_option",
1007                    "table function args/hints/version/sample/partitions",
1008                );
1009            }
1010            if !with_hints.is_empty()
1011                || version.is_some()
1012                || with_ordinality
1013                || !partitions.is_empty()
1014                || json_path.is_some()
1015                || sample.is_some()
1016                || !index_hints.is_empty()
1017            {
1018                return no(
1019                    "table_option",
1020                    "table function args/hints/version/sample/partitions",
1021                );
1022            }
1023            Ok(TableRef::Table {
1024                name: object_name(&name)?,
1025                alias: alias_name(alias)?,
1026            })
1027        }
1028        sp::TableFactor::Derived {
1029            lateral,
1030            subquery,
1031            alias,
1032            sample,
1033        } => {
1034            if lateral || sample.is_some() {
1035                return no("derived_option", "LATERAL / TABLESAMPLE");
1036            }
1037            let alias = alias_name(alias)?.ok_or_else(|| ReadError::NotInIr {
1038                construct: "unaliased_subquery".into(),
1039                detail: "PostgreSQL requires an alias on a FROM subquery".into(),
1040            })?;
1041            Ok(TableRef::Subquery {
1042                query: Box::new(query(*subquery)?),
1043                alias,
1044            })
1045        }
1046        other => no("table_factor", &head(&other)),
1047    }
1048}
1049
1050fn table_with_joins(t: sp::TableWithJoins) -> R<TableRef> {
1051    let sp::TableWithJoins { relation, joins } = t;
1052    let mut cur = table_factor(relation)?;
1053    for j in joins {
1054        let sp::Join {
1055            relation,
1056            global,
1057            join_operator,
1058        } = j;
1059        if global {
1060            return no("global_join", "GLOBAL JOIN");
1061        }
1062        let (kind, constraint) = match join_operator {
1063            sp::JoinOperator::Join(c) | sp::JoinOperator::Inner(c) => (JoinKind::Inner, c),
1064            sp::JoinOperator::Left(c) | sp::JoinOperator::LeftOuter(c) => (JoinKind::Left, c),
1065            sp::JoinOperator::Right(c) | sp::JoinOperator::RightOuter(c) => (JoinKind::Right, c),
1066            sp::JoinOperator::FullOuter(c) => (JoinKind::Full, c),
1067            sp::JoinOperator::CrossJoin(c) => (JoinKind::Cross, c),
1068            other => return no("join_kind", &head(&other)),
1069        };
1070        let (on, using, natural) = match constraint {
1071            sp::JoinConstraint::On(e) => (Some(expr(e)?), Vec::new(), false),
1072            sp::JoinConstraint::None => (None, Vec::new(), false),
1073            sp::JoinConstraint::Using(cols) => (
1074                None,
1075                cols.iter().map(single_name).collect::<R<Vec<_>>>()?,
1076                false,
1077            ),
1078            sp::JoinConstraint::Natural => (None, Vec::new(), true),
1079        };
1080        if natural && kind == JoinKind::Cross {
1081            return no("natural_join", "NATURAL CROSS JOIN");
1082        }
1083        cur = TableRef::Join {
1084            left: Box::new(cur),
1085            right: Box::new(table_factor(relation)?),
1086            kind,
1087            on,
1088            using,
1089            natural,
1090        };
1091    }
1092    Ok(cur)
1093}
1094
1095fn simple_table(t: sp::TableWithJoins) -> R<(Name, Option<String>)> {
1096    let sp::TableWithJoins { relation, joins } = t;
1097    if !joins.is_empty() {
1098        return no("dml_target_join", "joins in a DML target");
1099    }
1100    match table_factor(relation)? {
1101        TableRef::Table { name, alias } => Ok((name, alias)),
1102        _ => no("dml_target", "DML target is not a plain table"),
1103    }
1104}
1105
1106fn returning(r: Option<Vec<sp::SelectItem>>) -> R<Vec<SelectItem>> {
1107    r.unwrap_or_default().into_iter().map(select_item).collect()
1108}
1109
1110fn assignments(a: Vec<sp::Assignment>) -> R<Vec<Assignment>> {
1111    let mut out = Vec::new();
1112    for sp::Assignment { target, value } in a {
1113        let column = match target {
1114            sp::AssignmentTarget::ColumnName(n) => single_name(&n)?,
1115            sp::AssignmentTarget::Tuple(_) => return no("tuple_assignment", "SET (a, b) = ..."),
1116        };
1117        out.push(Assignment {
1118            column,
1119            value: expr(value)?,
1120        });
1121    }
1122    Ok(out)
1123}
1124
1125fn insert(i: sp::Insert) -> R<Statement> {
1126    let sp::Insert {
1127        insert_token: _,
1128        optimizer_hints,
1129        or,
1130        ignore,
1131        into: _,
1132        table,
1133        table_alias,
1134        columns,
1135        overwrite,
1136        source,
1137        assignments: asg,
1138        partitioned,
1139        after_columns,
1140        has_table_keyword: _,
1141        on,
1142        returning: ret,
1143        output,
1144        replace_into,
1145        priority,
1146        insert_alias,
1147        settings,
1148        format_clause,
1149        multi_table_insert_type,
1150        multi_table_into_clauses,
1151        multi_table_when_clauses,
1152        multi_table_else_clause,
1153    } = i;
1154    if !optimizer_hints.is_empty()
1155        || or.is_some()
1156        || table_alias.is_some()
1157        || overwrite
1158        || (!asg.is_empty() && (!columns.is_empty() || source.is_some()))
1159        || partitioned.is_some()
1160        || !after_columns.is_empty()
1161        || output.is_some()
1162        || priority.is_some()
1163        || insert_alias.is_some()
1164        || settings.is_some()
1165        || format_clause.is_some()
1166        || multi_table_insert_type.is_some()
1167        || !multi_table_into_clauses.is_empty()
1168        || !multi_table_when_clauses.is_empty()
1169        || multi_table_else_clause.is_some()
1170    {
1171        return no(
1172            "insert_option",
1173            "an INSERT form other than INSERT INTO t [(cols)] VALUES|query",
1174        );
1175    }
1176    let table = match table {
1177        sp::TableObject::TableName(n) => object_name(&n)?,
1178        other => return no("insert_target", &head(&other)),
1179    };
1180    // MySQL `INSERT INTO t SET a = 1, b = 2` is `INSERT INTO t (a, b) VALUES (1, 2)`.
1181    let (columns, set_source) = if asg.is_empty() {
1182        (
1183            columns.iter().map(single_name).collect::<R<Vec<_>>>()?,
1184            None,
1185        )
1186    } else {
1187        let set = assignments(asg)?;
1188        let (cols, vals): (Vec<_>, Vec<_>) = set.into_iter().map(|a| (a.column, a.value)).unzip();
1189        (cols, Some(InsertSource::Values(vec![vals])))
1190    };
1191    let source = match source {
1192        None if set_source.is_some() => set_source.unwrap_or(InsertSource::DefaultValues),
1193        None => InsertSource::DefaultValues,
1194        Some(q) => {
1195            let q = *q;
1196            match *q.body {
1197                sp::SetExpr::Values(v)
1198                    if q.with.is_none()
1199                        && q.order_by.is_none()
1200                        && q.limit_clause.is_none()
1201                        && q.locks.is_empty() =>
1202                {
1203                    let sp::Values {
1204                        explicit_row,
1205                        value_keyword: _,
1206                        rows,
1207                    } = v;
1208                    if explicit_row {
1209                        return no("explicit_row", "ROW(..) in VALUES");
1210                    }
1211                    let mut out = Vec::new();
1212                    for r in rows {
1213                        out.push(r.content.into_iter().map(expr).collect::<R<Vec<_>>>()?);
1214                    }
1215                    InsertSource::Values(out)
1216                }
1217                body => {
1218                    let q2 = sp::Query {
1219                        body: Box::new(body),
1220                        ..q
1221                    };
1222                    InsertSource::Query(Box::new(query(q2)?))
1223                }
1224            }
1225        }
1226    };
1227    let on_conflict = match on {
1228        None => None,
1229        Some(sp::OnInsert::OnConflict(oc)) => {
1230            let sp::OnConflict {
1231                conflict_target,
1232                action,
1233            } = oc;
1234            let target = match conflict_target {
1235                None => Vec::new(),
1236                Some(sp::ConflictTarget::Columns(cols)) => cols.iter().map(ident).collect(),
1237                Some(sp::ConflictTarget::OnConstraint(_)) => {
1238                    return no("on_conflict_constraint", "ON CONFLICT ON CONSTRAINT");
1239                }
1240            };
1241            let action = match action {
1242                sp::OnConflictAction::DoNothing => ConflictAction::DoNothing,
1243                sp::OnConflictAction::DoUpdate(sp::DoUpdate {
1244                    assignments: a,
1245                    selection,
1246                }) => ConflictAction::DoUpdate {
1247                    set: assignments(a)?,
1248                    where_: selection.map(expr).transpose()?,
1249                },
1250            };
1251            Some(OnConflict { target, action })
1252        }
1253        Some(sp::OnInsert::DuplicateKeyUpdate(a)) => {
1254            // No conflict target: MySQL fires on ANY unique key. `VALUES(c)` is `excluded.c`.
1255            let set = assignments(a)?
1256                .into_iter()
1257                .map(|asg| Assignment {
1258                    column: asg.column,
1259                    value: excluded_refs(asg.value),
1260                })
1261                .collect();
1262            Some(OnConflict {
1263                target: vec![],
1264                action: ConflictAction::DoUpdate { set, where_: None },
1265            })
1266        }
1267        Some(other) => return no("on_insert", &head(&other)),
1268    };
1269    // MySQL `INSERT IGNORE`: a unique-key conflict skips the row, as `ON CONFLICT DO NOTHING`
1270    // (with no target) does. IGNORE also downgrades other errors, hence the allowance.
1271    let on_conflict = if ignore {
1272        if on_conflict.is_some() {
1273            return no(
1274                "insert_option",
1275                "IGNORE together with ON DUPLICATE KEY UPDATE",
1276            );
1277        }
1278        add_note(
1279            "insert_ignore",
1280            "INSERT IGNORE downgrades every error of the statement to a warning; ON CONFLICT DO NOTHING \
1281             skips unique-key conflicts only",
1282            Allowance::IgnoreCoversOnlyUniqueConflicts,
1283        );
1284        Some(OnConflict {
1285            target: vec![],
1286            action: ConflictAction::DoNothing,
1287        })
1288    } else {
1289        on_conflict
1290    };
1291    Ok(Statement::Insert(Insert {
1292        table,
1293        replace: replace_into,
1294        columns,
1295        source,
1296        on_conflict,
1297        returning: returning(ret)?,
1298    }))
1299}
1300
1301fn update(u: sp::Update) -> R<Statement> {
1302    let sp::Update {
1303        update_token: _,
1304        optimizer_hints,
1305        table,
1306        assignments: asg,
1307        from,
1308        selection,
1309        returning: ret,
1310        output,
1311        or,
1312        order_by,
1313        limit,
1314    } = u;
1315    if !optimizer_hints.is_empty()
1316        || output.is_some()
1317        || or.is_some()
1318        || !order_by.is_empty()
1319        || limit.is_some()
1320    {
1321        return no(
1322            "update_option",
1323            "UPDATE with hints/OUTPUT/OR/ORDER BY/LIMIT",
1324        );
1325    }
1326    let (table, alias) = simple_table(table)?;
1327    // The parser does not know MySQL's `UPDATE LOW_PRIORITY|IGNORE t ...` and reads the modifier as
1328    // the table name and `t` as its alias: refuse rather than write another table's name.
1329    if alias.is_some()
1330        && table.0.len() == 1
1331        && matches!(table.0[0].as_str(), "low_priority" | "ignore")
1332    {
1333        return no("update_option", "UPDATE LOW_PRIORITY / IGNORE");
1334    }
1335    let from = match from {
1336        None => Vec::new(),
1337        Some(sp::UpdateTableFromKind::AfterSet(ts)) => ts
1338            .into_iter()
1339            .map(table_with_joins)
1340            .collect::<R<Vec<_>>>()?,
1341        Some(other) => return no("update_from_position", &head(&other)),
1342    };
1343    Ok(Statement::Update(Update {
1344        table,
1345        alias,
1346        set: assignments(asg)?,
1347        from,
1348        where_: selection.map(expr).transpose()?,
1349        returning: returning(ret)?,
1350    }))
1351}
1352
1353fn delete(d: sp::Delete) -> R<Statement> {
1354    let sp::Delete {
1355        delete_token: _,
1356        optimizer_hints,
1357        tables,
1358        from,
1359        using,
1360        selection,
1361        returning: ret,
1362        output,
1363        order_by,
1364        limit,
1365    } = d;
1366    if !optimizer_hints.is_empty()
1367        || !tables.is_empty()
1368        || output.is_some()
1369        || !order_by.is_empty()
1370        || limit.is_some()
1371    {
1372        return no(
1373            "delete_option",
1374            "DELETE with hints/multi-table/OUTPUT/ORDER BY/LIMIT",
1375        );
1376    }
1377    let ts = match from {
1378        sp::FromTable::WithFromKeyword(ts) | sp::FromTable::WithoutKeyword(ts) => ts,
1379    };
1380    if ts.len() != 1 {
1381        return no("delete_multi_target", "DELETE FROM a, b");
1382    }
1383    let (table, alias) = simple_table(ts.into_iter().next().unwrap())?;
1384    let using = using
1385        .unwrap_or_default()
1386        .into_iter()
1387        .map(table_with_joins)
1388        .collect::<R<Vec<_>>>()?;
1389    Ok(Statement::Delete(Delete {
1390        table,
1391        alias,
1392        using,
1393        where_: selection.map(expr).transpose()?,
1394        returning: returning(ret)?,
1395    }))
1396}
1397
1398fn boxed(e: sp::Expr) -> R<Box<Expr>> {
1399    Ok(Box::new(expr(e)?))
1400}
1401
1402fn is_bool(x: sp::Expr, value: bool, negated: bool) -> R<Expr> {
1403    Ok(Expr::IsBool {
1404        expr: boxed(x)?,
1405        value,
1406        negated,
1407    })
1408}
1409
1410fn expr(e: sp::Expr) -> R<Expr> {
1411    use sp::Expr as E;
1412    Ok(match e {
1413        // `DEFAULT` in VALUES / SET is parsed as an identifier; as a column it would be written
1414        // quoted and mean something else (PostgreSQL rejects it, MySQL would read a column).
1415        E::Identifier(i) if i.quote_style.is_none() && i.value.eq_ignore_ascii_case("default") => {
1416            return no("default_value", "DEFAULT as a value is not in the IR");
1417        }
1418        E::Identifier(i) => Expr::Column(Name::simple(ident(&i))),
1419        E::CompoundIdentifier(parts) => Expr::Column(Name(parts.iter().map(ident).collect())),
1420        E::Value(v) => value(v.value)?,
1421        E::Nested(inner) => Expr::Nested(boxed(*inner)?),
1422        E::IsNull(x) => Expr::IsNull {
1423            expr: boxed(*x)?,
1424            negated: false,
1425        },
1426        E::IsNotNull(x) => Expr::IsNull {
1427            expr: boxed(*x)?,
1428            negated: true,
1429        },
1430        E::IsTrue(x) => is_bool(*x, true, false)?,
1431        E::IsNotTrue(x) => is_bool(*x, true, true)?,
1432        E::IsFalse(x) => is_bool(*x, false, false)?,
1433        E::IsNotFalse(x) => is_bool(*x, false, true)?,
1434        E::InList {
1435            expr: x,
1436            list,
1437            negated,
1438        } => Expr::InList {
1439            expr: boxed(*x)?,
1440            list: list.into_iter().map(expr).collect::<R<_>>()?,
1441            negated,
1442        },
1443        E::InSubquery {
1444            expr: x,
1445            subquery,
1446            negated,
1447        } => Expr::InSubquery {
1448            expr: boxed(*x)?,
1449            query: Box::new(query(*subquery)?),
1450            negated,
1451        },
1452        E::Between {
1453            expr: x,
1454            negated,
1455            low,
1456            high,
1457        } => Expr::Between {
1458            expr: boxed(*x)?,
1459            low: boxed(*low)?,
1460            high: boxed(*high)?,
1461            negated,
1462        },
1463        E::Like {
1464            negated,
1465            any,
1466            expr: x,
1467            pattern,
1468            escape_char,
1469        } => {
1470            if any {
1471                return no("like_option", "LIKE ANY");
1472            }
1473            let ci = rules().like_ci_default;
1474            if ci {
1475                add_note(
1476                    "like",
1477                    "the source LIKE is ASCII case-insensitive only while its connection setting is at the default",
1478                    Allowance::LikeCaseSensitivityIsConnectionSetting,
1479                );
1480            }
1481            if rules().name == "mysql" {
1482                add_note(
1483                    "like",
1484                    "the source LIKE follows the column collation; read as case-sensitive (a binary collation)",
1485                    Allowance::LikeCaseSensitivityIsConnectionSetting,
1486                );
1487            }
1488            like_expr(*x, *pattern, escape_char, negated, ci)?
1489        }
1490        E::RLike {
1491            negated,
1492            expr: x,
1493            pattern,
1494            ..
1495        } => Expr::Regexp {
1496            expr: boxed(*x)?,
1497            pattern: boxed(*pattern)?,
1498            negated,
1499        },
1500        E::ILike {
1501            negated,
1502            any,
1503            expr: x,
1504            pattern,
1505            escape_char,
1506        } => {
1507            if any {
1508                return no("like_option", "ILIKE ANY");
1509            }
1510            like_expr(*x, *pattern, escape_char, negated, true)?
1511        }
1512        E::UnaryOp { op, expr: x } => {
1513            let op = match op {
1514                sp::UnaryOperator::Not => UnaryOp::Not,
1515                sp::UnaryOperator::Minus => UnaryOp::Minus,
1516                sp::UnaryOperator::Plus => UnaryOp::Plus,
1517                other => return no("unary_operator", &head(&other)),
1518            };
1519            Expr::Unary {
1520                op,
1521                expr: boxed(*x)?,
1522            }
1523        }
1524        E::BinaryOp { left, op, right }
1525            if matches!(
1526                op,
1527                sp::BinaryOperator::PGRegexMatch | sp::BinaryOperator::PGRegexNotMatch
1528            ) =>
1529        {
1530            Expr::Regexp {
1531                expr: boxed(*left)?,
1532                pattern: boxed(*right)?,
1533                negated: matches!(op, sp::BinaryOperator::PGRegexNotMatch),
1534            }
1535        }
1536        E::BinaryOp { left, op, right } => {
1537            use sp::BinaryOperator as B;
1538            let op = match op {
1539                B::Eq => BinaryOp::Eq,
1540                B::NotEq => BinaryOp::NotEq,
1541                B::Lt => BinaryOp::Lt,
1542                B::LtEq => BinaryOp::LtEq,
1543                B::Gt => BinaryOp::Gt,
1544                B::GtEq => BinaryOp::GtEq,
1545                B::And => BinaryOp::And,
1546                B::Or => BinaryOp::Or,
1547                B::Plus => BinaryOp::Plus,
1548                B::Minus => BinaryOp::Minus,
1549                B::Multiply => BinaryOp::Multiply,
1550                B::Divide => BinaryOp::Divide,
1551                B::Modulo => BinaryOp::Modulo,
1552                // MySQL's default sql_mode makes `||` a logical OR with OR's (lowest) precedence, but
1553                // sqlparser parses it as concatenation with concatenation's precedence, so the tree
1554                // is wrong either way: refuse instead of guessing.
1555                B::StringConcat if rules().name == "mysql" => {
1556                    return no(
1557                        "pipes_operator",
1558                        "MySQL `||` is logical OR (default sql_mode) but the parser gives it concatenation precedence; write OR, or CONCAT()",
1559                    );
1560                }
1561                B::StringConcat => BinaryOp::Concat,
1562                B::MyIntegerDivide => BinaryOp::IntDivide,
1563                B::Spaceship => BinaryOp::NullSafeEq,
1564                B::BitwiseAnd => BinaryOp::BitAnd,
1565                B::BitwiseOr => BinaryOp::BitOr,
1566                B::BitwiseXor | B::PGBitwiseXor => BinaryOp::BitXor,
1567                B::PGBitwiseShiftLeft => BinaryOp::ShiftLeft,
1568                B::PGBitwiseShiftRight => BinaryOp::ShiftRight,
1569                B::Xor => BinaryOp::Xor,
1570                B::Arrow => BinaryOp::JsonGet,
1571                B::LongArrow => BinaryOp::JsonGetText,
1572                other => {
1573                    return no(
1574                        "binary_operator",
1575                        &format!(
1576                            "{} (JSON/array/regex/bitwise operators are not in the IR)",
1577                            head(&other)
1578                        ),
1579                    );
1580                }
1581            };
1582            if op == BinaryOp::Divide && rules().name == "mysql" {
1583                add_note(
1584                    "division",
1585                    "the source `/` is exact (DECIMAL) division; the target divides as double precision",
1586                    Allowance::DecimalDivisionAsFloat,
1587                );
1588                let l = Expr::Cast {
1589                    expr: boxed(*left)?,
1590                    ty: SqlType::Double,
1591                };
1592                return Ok(Expr::Binary {
1593                    op,
1594                    left: Box::new(l),
1595                    right: boxed(*right)?,
1596                });
1597            }
1598            // `ts +/- INTERVAL 'n unit'` is the same statement as `ts +/- make_interval(unit => n)`:
1599            // one IR form, so every target's interval arithmetic (and its refusal of months/years)
1600            // applies unchanged. `INTERVAL 'n unit' + ts` commutes for `+` only.
1601            match (op, *left, *right) {
1602                (BinaryOp::Plus | BinaryOp::Minus, l, E::Interval(iv)) => Expr::Binary {
1603                    op,
1604                    left: boxed(l)?,
1605                    right: Box::new(interval_call(iv)?),
1606                },
1607                (BinaryOp::Plus, E::Interval(iv), r) => Expr::Binary {
1608                    op,
1609                    left: boxed(r)?,
1610                    right: Box::new(interval_call(iv)?),
1611                },
1612                (op, l, r) => Expr::Binary {
1613                    op,
1614                    left: boxed(l)?,
1615                    right: boxed(r)?,
1616                },
1617            }
1618        }
1619        E::Case {
1620            case_token: _,
1621            end_token: _,
1622            operand,
1623            conditions,
1624            else_result,
1625        } => Expr::Case {
1626            operand: operand.map(|o| boxed(*o)).transpose()?,
1627            branches: conditions
1628                .into_iter()
1629                .map(|sp::CaseWhen { condition, result }| Ok((expr(condition)?, expr(result)?)))
1630                .collect::<R<_>>()?,
1631            else_: else_result.map(|o| boxed(*o)).transpose()?,
1632        },
1633        E::Cast {
1634            kind,
1635            expr: x,
1636            data_type,
1637            format,
1638        } => {
1639            if format.is_some() || !matches!(kind, sp::CastKind::Cast | sp::CastKind::DoubleColon) {
1640                return no("cast_form", "TRY_CAST / SAFE_CAST / CAST .. FORMAT");
1641            }
1642            Expr::Cast {
1643                expr: boxed(*x)?,
1644                ty: data_type_to_ir(&data_type)?,
1645            }
1646        }
1647        E::Trim {
1648            trim_where,
1649            trim_what,
1650            expr: x,
1651            trim_characters,
1652        } => {
1653            // `trim(chars FROM x)` / `trim(BOTH chars FROM x)`; the comma form is `trim_characters`.
1654            let side = match trim_where {
1655                None | Some(sp::TrimWhereField::Both) => TrimSide::Both,
1656                Some(sp::TrimWhereField::Leading) => TrimSide::Leading,
1657                Some(sp::TrimWhereField::Trailing) => TrimSide::Trailing,
1658            };
1659            let chars = match (trim_what, trim_characters) {
1660                (Some(w), None) => Some(boxed(*w)?),
1661                (None, None) => None,
1662                (None, Some(mut cs)) if cs.len() == 1 => Some(boxed(cs.remove(0))?),
1663                _ => return no("trim_form", "TRIM with several character arguments"),
1664            };
1665            Expr::Trim {
1666                expr: boxed(*x)?,
1667                side,
1668                chars,
1669            }
1670        }
1671        E::Substring {
1672            expr: x,
1673            substring_from,
1674            substring_for,
1675            special: _,
1676            shorthand: _,
1677        } => {
1678            if rules().name == "mysql" {
1679                // From position 1 and a non-negative length the engines agree; any other start
1680                // (0, negative, an expression) or length is the caller's stated assumption.
1681                let positive = |e: &E, min: u64| {
1682                    matches!(
1683                        e,
1684                        E::Value(v) if matches!(&v.value, sp::Value::Number(n, _)
1685                            if n.parse::<u64>().is_ok_and(|x| x >= min))
1686                    )
1687                };
1688                let start_ok = substring_from.as_deref().is_some_and(|f| positive(f, 1));
1689                let len_ok = substring_for.as_deref().is_none_or(|l| positive(l, 0));
1690                if !(start_ok && len_ok) {
1691                    add_note(
1692                        "fn:substr.start_position",
1693                        "MySQL SUBSTRING counts a start of 0 as empty and a negative start from the end; \
1694                         the target does not",
1695                        Allowance::SubstringStartAssumedPositive,
1696                    );
1697                }
1698            }
1699            // `substring(x FROM a FOR b)` and `substring(x, a, b)` are `substr(x, a, b)`.
1700            let mut args = vec![FunctionArg::Expr(expr(*x)?)];
1701            match (substring_from, substring_for) {
1702                (Some(f), Some(l)) => {
1703                    args.push(FunctionArg::Expr(expr(*f)?));
1704                    args.push(FunctionArg::Expr(expr(*l)?));
1705                }
1706                (Some(f), None) => args.push(FunctionArg::Expr(expr(*f)?)),
1707                (None, Some(l)) => {
1708                    // FOR without FROM starts at position 1.
1709                    args.push(FunctionArg::Expr(Expr::Literal(Literal::Number(
1710                        "1".into(),
1711                    ))));
1712                    args.push(FunctionArg::Expr(expr(*l)?));
1713                }
1714                (None, None) => return no("substring_form", "SUBSTRING without FROM or FOR"),
1715            }
1716            Expr::Function(Function {
1717                name: "substr".into(),
1718                args,
1719                distinct: false,
1720                star: false,
1721                filter: None,
1722                over: None,
1723                order_by: vec![],
1724            })
1725        }
1726        E::AnyOp {
1727            left,
1728            compare_op,
1729            right,
1730            is_some: _,
1731        } => {
1732            if !matches!(compare_op, sp::BinaryOperator::Eq) {
1733                return no("any_operator", "only `= ANY(..)` is in the IR");
1734            }
1735            quantified(*left, *right, false)?
1736        }
1737        E::AllOp {
1738            left,
1739            compare_op,
1740            right,
1741        } => {
1742            if !matches!(compare_op, sp::BinaryOperator::NotEq) {
1743                return no("all_operator", "only `<> ALL(..)` is in the IR");
1744            }
1745            quantified(*left, *right, true)?
1746        }
1747        E::Exists { subquery, negated } => Expr::Exists {
1748            query: Box::new(query(*subquery)?),
1749            negated,
1750        },
1751        E::Subquery(q) => Expr::Subquery(Box::new(query(*q)?)),
1752        E::Extract {
1753            field,
1754            syntax: _,
1755            expr: x,
1756        } => Expr::Extract {
1757            field: field.to_string().to_ascii_lowercase(),
1758            expr: boxed(*x)?,
1759        },
1760        E::Array(arr) => Expr::ArrayLiteral(arr.elem.into_iter().map(expr).collect::<R<Vec<_>>>()?),
1761        E::AtTimeZone {
1762            timestamp,
1763            time_zone,
1764        } => Expr::AtTimeZone {
1765            expr: boxed(*timestamp)?,
1766            zone: boxed(*time_zone)?,
1767        },
1768        E::Function(f) => function(f)?,
1769        other => return no("expression", &head(&other)),
1770    })
1771}
1772
1773/// `x = ANY(rhs)` / `x <> ALL(rhs)`: an array parameter, an array literal, or a subquery.
1774fn quantified(left: sp::Expr, right: sp::Expr, negated: bool) -> R<Expr> {
1775    let lhs = boxed(left)?;
1776    // `$1::int[]` is only a type hint on the parameter.
1777    let mut right = right;
1778    if let sp::Expr::Cast {
1779        kind: sp::CastKind::Cast | sp::CastKind::DoubleColon,
1780        expr: inner,
1781        data_type: sp::DataType::Array(_),
1782        format: None,
1783    } = right.clone()
1784    {
1785        right = *inner;
1786    }
1787    match right {
1788        sp::Expr::Value(v) => match v.value {
1789            sp::Value::Placeholder(_) => match value(v.value)? {
1790                Expr::Param(n) => Ok(Expr::AnyParam {
1791                    expr: lhs,
1792                    param: n,
1793                    negated,
1794                }),
1795                _ => no("array_param", "expected a numbered parameter"),
1796            },
1797            other => no("array_operand", &head(&other)),
1798        },
1799        sp::Expr::Array(sp::Array { elem, named: _ }) => Ok(Expr::InList {
1800            expr: lhs,
1801            list: elem.into_iter().map(expr).collect::<R<Vec<_>>>()?,
1802            negated,
1803        }),
1804        sp::Expr::Subquery(q) => Ok(Expr::InSubquery {
1805            expr: lhs,
1806            query: Box::new(query(*q)?),
1807            negated,
1808        }),
1809        other => no("array_operand", &head(&other)),
1810    }
1811}
1812
1813/// MySQL's `VALUES(col)` inside `ON DUPLICATE KEY UPDATE` refers to the row proposed for insertion.
1814fn excluded_refs(e: Expr) -> Expr {
1815    match e {
1816        Expr::Function(f) if f.name == "values" && f.args.len() == 1 => {
1817            match f.args.into_iter().next() {
1818                Some(FunctionArg::Expr(Expr::Column(n))) => {
1819                    Expr::Column(Name(vec!["excluded".to_string(), n.last().to_string()]))
1820                }
1821                other => Expr::Function(Function {
1822                    name: "values".into(),
1823                    args: other.into_iter().collect(),
1824                    distinct: false,
1825                    star: false,
1826                    filter: None,
1827                    over: None,
1828                    order_by: vec![],
1829                }),
1830            }
1831        }
1832        Expr::Binary { op, left, right } => Expr::Binary {
1833            op,
1834            left: Box::new(excluded_refs(*left)),
1835            right: Box::new(excluded_refs(*right)),
1836        },
1837        Expr::Nested(x) => Expr::Nested(Box::new(excluded_refs(*x))),
1838        Expr::Unary { op, expr } => Expr::Unary {
1839            op,
1840            expr: Box::new(excluded_refs(*expr)),
1841        },
1842        other => other,
1843    }
1844}
1845
1846fn like_expr(
1847    x: sp::Expr,
1848    pattern: sp::Expr,
1849    escape_char: Option<Box<sp::Expr>>,
1850    negated: bool,
1851    case_insensitive: bool,
1852) -> R<Expr> {
1853    let escape = match escape_char {
1854        Some(e) => Some(boxed(*e)?),
1855        None if rules().like_default_escape => {
1856            Some(Box::new(Expr::Literal(Literal::String("\\".into()))))
1857        }
1858        None => None,
1859    };
1860    Ok(Expr::Like {
1861        expr: boxed(x)?,
1862        pattern: boxed(pattern)?,
1863        negated,
1864        case_insensitive,
1865        escape,
1866    })
1867}
1868
1869fn value(v: sp::Value) -> R<Expr> {
1870    Ok(match v {
1871        sp::Value::Number(n, long) => {
1872            if long {
1873                return no("numeric_suffix", "L suffix");
1874            }
1875            Expr::Literal(Literal::Number(n))
1876        }
1877        sp::Value::SingleQuotedString(s) => Expr::Literal(Literal::String(s)),
1878        // The tokenizer has already resolved the backslash escapes of `E'..'`.
1879        sp::Value::EscapedStringLiteral(s) => Expr::Literal(Literal::String(s)),
1880        sp::Value::Boolean(b) if rules().name == "mysql" => {
1881            // MySQL TRUE/FALSE are the integers 1 and 0.
1882            Expr::Literal(Literal::Number(if b { "1" } else { "0" }.into()))
1883        }
1884        sp::Value::Boolean(b) => Expr::Literal(Literal::Bool(b)),
1885        sp::Value::Null => Expr::Literal(Literal::Null),
1886        sp::Value::Placeholder(p) => {
1887            let bad = || ReadError::NotInIr {
1888                construct: "placeholder".into(),
1889                detail: format!(
1890                    "`{p}` is not a placeholder form of dialect `{}`",
1891                    rules().name
1892                ),
1893            };
1894            if rules().question_placeholders {
1895                if p == "?" {
1896                    Expr::Param(bump_param(None, None))
1897                } else if let Some(d) = p.strip_prefix('?') {
1898                    let n = d.parse::<u32>().ok().filter(|n| *n >= 1).ok_or_else(bad)?;
1899                    Expr::Param(bump_param(Some(n), None))
1900                } else if let Some(nm) = p.strip_prefix([':', '@', '$']) {
1901                    Expr::Param(bump_param(None, Some(nm)))
1902                } else {
1903                    return Err(bad());
1904                }
1905            } else {
1906                let n = p
1907                    .strip_prefix('$')
1908                    .and_then(|d| d.parse::<u32>().ok())
1909                    .filter(|n| *n >= 1)
1910                    .ok_or_else(bad)?;
1911                Expr::Param(n)
1912            }
1913        }
1914        other => return no("literal", &head(&other)),
1915    })
1916}
1917
1918fn function(f: sp::Function) -> R<Expr> {
1919    let sp::Function {
1920        name,
1921        uses_odbc_syntax,
1922        parameters,
1923        args,
1924        within_group,
1925        filter,
1926        null_treatment,
1927        over,
1928    } = f;
1929    if uses_odbc_syntax
1930        || !matches!(parameters, sp::FunctionArguments::None)
1931        || !within_group.is_empty()
1932        || null_treatment.is_some()
1933    {
1934        return no(
1935            "function_option",
1936            "ODBC syntax/parameters/WITHIN GROUP/FILTER/IGNORE NULLS",
1937        );
1938    }
1939    let over = match over {
1940        None => None,
1941        Some(sp::WindowType::NamedWindow(_)) => {
1942            return no(
1943                "named_window",
1944                "OVER w (a WINDOW clause) is not in the IR yet",
1945            );
1946        }
1947        Some(sp::WindowType::WindowSpec(spec)) => Some(window_spec(spec)?),
1948    };
1949    let filter = filter.map(|f| expr(*f).map(Box::new)).transpose()?;
1950    let name = object_name(&name)?;
1951    let base = name.last().to_string();
1952    if name.0.len() != 1 {
1953        return no("qualified_function", &name.0.join("."));
1954    }
1955    let args = match args {
1956        // `CURRENT_TIMESTAMP` is a function without parentheses.
1957        sp::FunctionArguments::None => {
1958            if base == "current_timestamp" {
1959                if rules().name == "sqlite" {
1960                    add_note(
1961                        "fn:now",
1962                        "the source CURRENT_TIMESTAMP is text 'YYYY-MM-DD HH:MM:SS' (UTC), not a timestamptz",
1963                        Allowance::NowAsText,
1964                    );
1965                }
1966                return Ok(Expr::Function(Function {
1967                    name: "now".to_string(),
1968                    args: vec![],
1969                    distinct: false,
1970                    star: false,
1971                    filter: None,
1972                    over: None,
1973                    order_by: vec![],
1974                }));
1975            }
1976            // The session identity keywords are zero-argument functions.
1977            if matches!(
1978                base.as_str(),
1979                "current_user" | "session_user" | "current_role"
1980            ) {
1981                return Ok(Expr::Function(Function {
1982                    name: base,
1983                    args: vec![],
1984                    distinct: false,
1985                    star: false,
1986                    filter: None,
1987                    over: None,
1988                    order_by: vec![],
1989                }));
1990            }
1991            // `CURRENT_DATE`: a date in the session time zone (PostgreSQL, MySQL), text of the UTC
1992            // date on SQLite.
1993            if base == "current_date" {
1994                if rules().name == "sqlite" {
1995                    add_note(
1996                        "fn:current_date",
1997                        "the source CURRENT_DATE is text 'YYYY-MM-DD' (the UTC date), not a date",
1998                        Allowance::DateAsText,
1999                    );
2000                }
2001                return Ok(Expr::Function(Function {
2002                    name: "current_date".to_string(),
2003                    args: vec![],
2004                    distinct: false,
2005                    star: false,
2006                    filter: None,
2007                    over: None,
2008                    order_by: vec![],
2009                }));
2010            }
2011            return no("bare_function", &format!("`{base}` without parentheses"));
2012        }
2013        sp::FunctionArguments::Subquery(q) if base == "array" => {
2014            return Ok(Expr::ArraySubquery(Box::new(query(*q)?)));
2015        }
2016        sp::FunctionArguments::Subquery(_) => {
2017            return no("function_subquery", "function over a subquery");
2018        }
2019        sp::FunctionArguments::List(l) => l,
2020    };
2021    let sp::FunctionArgumentList {
2022        duplicate_treatment,
2023        args,
2024        clauses,
2025    } = args;
2026    let mut agg_order = Vec::new();
2027    let mut separator: Option<String> = None;
2028    for cl in clauses {
2029        match cl {
2030            sp::FunctionArgumentClause::OrderBy(items) => {
2031                for it in items {
2032                    agg_order.push(order_item(it)?);
2033                }
2034            }
2035            sp::FunctionArgumentClause::Separator(v) => match v.value {
2036                sp::Value::SingleQuotedString(s) => separator = Some(s),
2037                other => return no("separator", &head(&other)),
2038            },
2039            other => {
2040                return no(
2041                    "function_clause",
2042                    &format!("{} inside a function call", head(&other)),
2043                );
2044            }
2045        }
2046    }
2047    let distinct = match duplicate_treatment {
2048        None | Some(sp::DuplicateTreatment::All) => false,
2049        Some(sp::DuplicateTreatment::Distinct) => true,
2050    };
2051    let mut out = Vec::new();
2052    let mut star = false;
2053    for a in args {
2054        match a {
2055            sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Expr(e)) => {
2056                out.push(FunctionArg::Expr(expr(e)?))
2057            }
2058            sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Wildcard) => star = true,
2059            sp::FunctionArg::Named {
2060                name,
2061                arg: sp::FunctionArgExpr::Expr(e),
2062                operator: sp::FunctionArgOperator::RightArrow,
2063            } => out.push(FunctionArg::Named {
2064                name: ident(&name),
2065                value: expr(e)?,
2066            }),
2067            // sqlparser produces `ExprNamed` when the name is parsed as an expression.
2068            sp::FunctionArg::ExprNamed {
2069                name: sp::Expr::Identifier(name),
2070                arg: sp::FunctionArgExpr::Expr(e),
2071                operator: sp::FunctionArgOperator::RightArrow,
2072            } => out.push(FunctionArg::Named {
2073                name: ident(&name),
2074                value: expr(e)?,
2075            }),
2076            other => return no("function_argument", &head(&other)),
2077        }
2078    }
2079    let mut name = base;
2080    if name == "current_timestamp" {
2081        name = "now".to_string();
2082    }
2083    if rules().name == "mysql" {
2084        match name.as_str() {
2085            "ifnull" => name = "coalesce".to_string(),
2086            "curdate" if out.is_empty() => name = "current_date".to_string(),
2087            "group_concat" => {
2088                name = "string_agg".to_string();
2089                out.push(FunctionArg::Expr(Expr::Literal(Literal::String(
2090                    separator.clone().unwrap_or_else(|| ",".to_string()),
2091                ))));
2092                add_note(
2093                    "fn:string_agg",
2094                    "the source GROUP_CONCAT truncates silently at group_concat_max_len",
2095                    Allowance::AggregateStringTruncation,
2096                );
2097            }
2098            // MySQL LENGTH() counts bytes.
2099            "length" => name = "octet_length".to_string(),
2100            "concat" if out.len() >= 2 => {
2101                let mut it = out.into_iter().map(|a| match a {
2102                    FunctionArg::Expr(e) => e,
2103                    FunctionArg::Named { value, .. } => value,
2104                });
2105                let first = it.next().expect("two arguments");
2106                let chain = it.fold(first, |l, r| Expr::Binary {
2107                    op: BinaryOp::Concat,
2108                    left: Box::new(l),
2109                    right: Box::new(r),
2110                });
2111                return Ok(chain);
2112            }
2113            "if" if out.len() == 3 => {
2114                let mut it = out.into_iter().map(|a| match a {
2115                    FunctionArg::Expr(e) => e,
2116                    FunctionArg::Named { value, .. } => value,
2117                });
2118                let (c, t, f) = (it.next().unwrap(), it.next().unwrap(), it.next().unwrap());
2119                return Ok(Expr::Case {
2120                    operand: None,
2121                    branches: vec![(c, t)],
2122                    else_: Some(Box::new(f)),
2123                });
2124            }
2125            _ => {}
2126        }
2127    }
2128    if rules().name == "sqlite" {
2129        match name.as_str() {
2130            "ifnull" => name = "coalesce".to_string(),
2131            "group_concat" => {
2132                name = "string_agg".to_string();
2133                if out.len() == 1 {
2134                    out.push(FunctionArg::Expr(Expr::Literal(Literal::String(
2135                        ",".into(),
2136                    ))));
2137                }
2138            }
2139            _ => {}
2140        }
2141    }
2142    Ok(Expr::Function(Function {
2143        name,
2144        args: out,
2145        distinct,
2146        star,
2147        filter,
2148        over,
2149        order_by: agg_order,
2150    }))
2151}
2152
2153/// `INTERVAL '3 days'` / `INTERVAL 3 DAY` as `make_interval(days => 3)`. Only a single `<number> <unit>`
2154/// is represented; compound intervals (`'1 day 2 hours'`), ranges (`DAY TO SECOND`) and unit-less
2155/// strings are not in the IR. Months and years are read (and then refused by the targets, whose
2156/// month arithmetic differs), not guessed.
2157fn interval_call(iv: sp::Interval) -> R<Expr> {
2158    let sp::Interval {
2159        value,
2160        leading_field,
2161        leading_precision,
2162        last_field,
2163        fractional_seconds_precision,
2164    } = iv;
2165    if leading_precision.is_some() || last_field.is_some() || fractional_seconds_precision.is_some()
2166    {
2167        return no(
2168            "interval",
2169            "interval ranges and precisions are not in the IR",
2170        );
2171    }
2172    let (amount, unit) = match (*value, leading_field) {
2173        // MySQL `INTERVAL 3 DAY`
2174        (sp::Expr::Value(v), Some(field)) => (
2175            match v.value {
2176                sp::Value::Number(n, _) => n,
2177                other => return no("interval", &head(&other)),
2178            },
2179            field.to_string(),
2180        ),
2181        // PostgreSQL / standard `INTERVAL '3 days'`
2182        (sp::Expr::Value(v), None) => match v.value {
2183            sp::Value::SingleQuotedString(s) => {
2184                let mut it = s.split_whitespace();
2185                match (it.next(), it.next(), it.next()) {
2186                    (Some(a), Some(u), None) => (a.to_string(), u.to_string()),
2187                    _ => {
2188                        return no(
2189                            "interval",
2190                            "only a single `<number> <unit>` interval is in the IR",
2191                        );
2192                    }
2193                }
2194            }
2195            other => return no("interval", &head(&other)),
2196        },
2197        (other, _) => return no("interval", &head(&other)),
2198    };
2199    let numeric = !amount.is_empty()
2200        && amount
2201            .trim_start_matches('-')
2202            .chars()
2203            .all(|c| c.is_ascii_digit() || c == '.')
2204        && amount
2205            .trim_start_matches('-')
2206            .chars()
2207            .any(|c| c.is_ascii_digit());
2208    if !numeric {
2209        return no("interval", "the interval amount is not a plain number");
2210    }
2211    let unit = match unit.to_ascii_lowercase().trim_end_matches('s') {
2212        "second" | "sec" => "secs",
2213        "minute" | "min" => "mins",
2214        "hour" => "hours",
2215        "day" => "days",
2216        "week" => "weeks",
2217        "month" | "mon" => "months",
2218        "year" => "years",
2219        other => return no("interval", &format!("unit `{other}` is not in the IR")),
2220    };
2221    Ok(Expr::Function(Function {
2222        name: "make_interval".to_string(),
2223        args: vec![FunctionArg::Named {
2224            name: unit.to_string(),
2225            value: Expr::Literal(Literal::Number(amount)),
2226        }],
2227        distinct: false,
2228        star: false,
2229        filter: None,
2230        over: None,
2231        order_by: vec![],
2232    }))
2233}
2234
2235fn window_spec(w: sp::WindowSpec) -> R<Window> {
2236    let sp::WindowSpec {
2237        window_name,
2238        partition_by,
2239        order_by,
2240        window_frame,
2241    } = w;
2242    if window_name.is_some() {
2243        return no("named_window", "OVER (w ..) refinement of a named window");
2244    }
2245    let frame = match window_frame {
2246        None => None,
2247        Some(sp::WindowFrame {
2248            units,
2249            start_bound,
2250            end_bound,
2251        }) => {
2252            let bound = |b: sp::WindowFrameBound| -> R<FrameBound> {
2253                Ok(match b {
2254                    sp::WindowFrameBound::CurrentRow => FrameBound::CurrentRow,
2255                    sp::WindowFrameBound::Preceding(e) => {
2256                        FrameBound::Preceding(e.map(|x| expr(*x).map(Box::new)).transpose()?)
2257                    }
2258                    sp::WindowFrameBound::Following(e) => {
2259                        FrameBound::Following(e.map(|x| expr(*x).map(Box::new)).transpose()?)
2260                    }
2261                })
2262            };
2263            Some(Frame {
2264                units: match units {
2265                    sp::WindowFrameUnits::Rows => FrameUnits::Rows,
2266                    sp::WindowFrameUnits::Range => FrameUnits::Range,
2267                    sp::WindowFrameUnits::Groups => FrameUnits::Groups,
2268                },
2269                start: bound(start_bound)?,
2270                end: end_bound.map(bound).transpose()?,
2271            })
2272        }
2273    };
2274    Ok(Window {
2275        partition_by: partition_by.into_iter().map(expr).collect::<R<_>>()?,
2276        order_by: order_by.into_iter().map(order_item).collect::<R<_>>()?,
2277        frame,
2278    })
2279}
2280
2281fn data_type_to_ir(t: &sp::DataType) -> R<SqlType> {
2282    use sp::DataType as D;
2283    Ok(match t {
2284        D::SmallInt(_) | D::Int2(_) => SqlType::SmallInt,
2285        D::Int(_) | D::Integer(_) | D::Int4(_) => SqlType::Integer,
2286        D::BigInt(_) | D::Int8(_) => SqlType::BigInt,
2287        D::Real | D::Float4 => SqlType::Real,
2288        D::Double(_) | D::DoublePrecision | D::Float8 => SqlType::Double,
2289        D::Numeric(info) | D::Decimal(info) => match info {
2290            sp::ExactNumberInfo::None => SqlType::Numeric {
2291                precision: None,
2292                scale: None,
2293            },
2294            sp::ExactNumberInfo::Precision(p) => SqlType::Numeric {
2295                precision: Some(*p as u32),
2296                scale: None,
2297            },
2298            sp::ExactNumberInfo::PrecisionAndScale(p, s) => SqlType::Numeric {
2299                precision: Some(*p as u32),
2300                scale: Some(*s as u32),
2301            },
2302        },
2303        D::Text => SqlType::Text,
2304        D::Signed | D::SignedInteger | D::Unsigned | D::UnsignedInteger => SqlType::BigInt,
2305        D::Char(None) | D::Character(None) => SqlType::Text,
2306        D::Datetime(None) => SqlType::Timestamp { with_tz: false },
2307        D::Varchar(None) | D::CharVarying(None) => SqlType::Varchar(None),
2308        D::Varchar(Some(sp::CharacterLength::IntegerLength { length, unit: None }))
2309        | D::CharVarying(Some(sp::CharacterLength::IntegerLength { length, unit: None })) => {
2310            SqlType::Varchar(Some(*length as u32))
2311        }
2312        D::Boolean | D::Bool => SqlType::Boolean,
2313        D::Date => SqlType::Date,
2314        D::Timestamp(None, tz) => SqlType::Timestamp {
2315            with_tz: match tz {
2316                sp::TimezoneInfo::None | sp::TimezoneInfo::WithoutTimeZone => false,
2317                sp::TimezoneInfo::WithTimeZone | sp::TimezoneInfo::Tz => true,
2318            },
2319        },
2320        D::Uuid => SqlType::Uuid,
2321        D::Bytea => SqlType::Bytes,
2322        D::JSON => SqlType::Json,
2323        D::JSONB => SqlType::Jsonb,
2324        other => return no("data_type", &format!("{other}")),
2325    })
2326}