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        // MySQL `CONVERT(expr, type)` is `CAST(expr AS type)`; `CONVERT(expr USING cs)` converts the
1648        // character set, which is not a cast.
1649        E::Convert {
1650            is_try: false,
1651            expr: x,
1652            data_type: Some(data_type),
1653            charset: None,
1654            target_before_value: false,
1655            styles,
1656        } if styles.is_empty() => Expr::Cast {
1657            expr: boxed(*x)?,
1658            ty: data_type_to_ir(&data_type)?,
1659        },
1660        E::Convert { .. } => {
1661            return no(
1662                "convert_form",
1663                "CONVERT(.. USING charset), TRY_CONVERT and the target-first (MSSQL) form",
1664            );
1665        }
1666        E::Trim {
1667            trim_where,
1668            trim_what,
1669            expr: x,
1670            trim_characters,
1671        } => {
1672            // `trim(chars FROM x)` / `trim(BOTH chars FROM x)`; the comma form is `trim_characters`.
1673            let side = match trim_where {
1674                None | Some(sp::TrimWhereField::Both) => TrimSide::Both,
1675                Some(sp::TrimWhereField::Leading) => TrimSide::Leading,
1676                Some(sp::TrimWhereField::Trailing) => TrimSide::Trailing,
1677            };
1678            let chars = match (trim_what, trim_characters) {
1679                (Some(w), None) => Some(boxed(*w)?),
1680                (None, None) => None,
1681                (None, Some(mut cs)) if cs.len() == 1 => Some(boxed(cs.remove(0))?),
1682                _ => return no("trim_form", "TRIM with several character arguments"),
1683            };
1684            Expr::Trim {
1685                expr: boxed(*x)?,
1686                side,
1687                chars,
1688            }
1689        }
1690        E::Substring {
1691            expr: x,
1692            substring_from,
1693            substring_for,
1694            special: _,
1695            shorthand: _,
1696        } => {
1697            if rules().name == "mysql" {
1698                // From position 1 and a non-negative length the engines agree; any other start
1699                // (0, negative, an expression) or length is the caller's stated assumption.
1700                let positive = |e: &E, min: u64| {
1701                    matches!(
1702                        e,
1703                        E::Value(v) if matches!(&v.value, sp::Value::Number(n, _)
1704                            if n.parse::<u64>().is_ok_and(|x| x >= min))
1705                    )
1706                };
1707                let start_ok = substring_from.as_deref().is_some_and(|f| positive(f, 1));
1708                let len_ok = substring_for.as_deref().is_none_or(|l| positive(l, 0));
1709                if !(start_ok && len_ok) {
1710                    add_note(
1711                        "fn:substr.start_position",
1712                        "MySQL SUBSTRING counts a start of 0 as empty and a negative start from the end; \
1713                         the target does not",
1714                        Allowance::SubstringStartAssumedPositive,
1715                    );
1716                }
1717            }
1718            // `substring(x FROM a FOR b)` and `substring(x, a, b)` are `substr(x, a, b)`.
1719            let mut args = vec![FunctionArg::Expr(expr(*x)?)];
1720            match (substring_from, substring_for) {
1721                (Some(f), Some(l)) => {
1722                    args.push(FunctionArg::Expr(expr(*f)?));
1723                    args.push(FunctionArg::Expr(expr(*l)?));
1724                }
1725                (Some(f), None) => args.push(FunctionArg::Expr(expr(*f)?)),
1726                (None, Some(l)) => {
1727                    // FOR without FROM starts at position 1.
1728                    args.push(FunctionArg::Expr(Expr::Literal(Literal::Number(
1729                        "1".into(),
1730                    ))));
1731                    args.push(FunctionArg::Expr(expr(*l)?));
1732                }
1733                (None, None) => return no("substring_form", "SUBSTRING without FROM or FOR"),
1734            }
1735            Expr::Function(Function {
1736                name: "substr".into(),
1737                args,
1738                distinct: false,
1739                star: false,
1740                filter: None,
1741                over: None,
1742                order_by: vec![],
1743            })
1744        }
1745        E::AnyOp {
1746            left,
1747            compare_op,
1748            right,
1749            is_some: _,
1750        } => {
1751            if !matches!(compare_op, sp::BinaryOperator::Eq) {
1752                return no("any_operator", "only `= ANY(..)` is in the IR");
1753            }
1754            quantified(*left, *right, false)?
1755        }
1756        E::AllOp {
1757            left,
1758            compare_op,
1759            right,
1760        } => {
1761            if !matches!(compare_op, sp::BinaryOperator::NotEq) {
1762                return no("all_operator", "only `<> ALL(..)` is in the IR");
1763            }
1764            quantified(*left, *right, true)?
1765        }
1766        E::Exists { subquery, negated } => Expr::Exists {
1767            query: Box::new(query(*subquery)?),
1768            negated,
1769        },
1770        E::Subquery(q) => Expr::Subquery(Box::new(query(*q)?)),
1771        E::Extract {
1772            field,
1773            syntax: _,
1774            expr: x,
1775        } => Expr::Extract {
1776            field: field.to_string().to_ascii_lowercase(),
1777            expr: boxed(*x)?,
1778        },
1779        E::Array(arr) => Expr::ArrayLiteral(arr.elem.into_iter().map(expr).collect::<R<Vec<_>>>()?),
1780        E::AtTimeZone {
1781            timestamp,
1782            time_zone,
1783        } => Expr::AtTimeZone {
1784            expr: boxed(*timestamp)?,
1785            zone: boxed(*time_zone)?,
1786        },
1787        E::Function(f) => function(f)?,
1788        other => return no("expression", &head(&other)),
1789    })
1790}
1791
1792/// `x = ANY(rhs)` / `x <> ALL(rhs)`: an array parameter, an array literal, or a subquery.
1793fn quantified(left: sp::Expr, right: sp::Expr, negated: bool) -> R<Expr> {
1794    let lhs = boxed(left)?;
1795    // `$1::int[]` is only a type hint on the parameter.
1796    let mut right = right;
1797    if let sp::Expr::Cast {
1798        kind: sp::CastKind::Cast | sp::CastKind::DoubleColon,
1799        expr: inner,
1800        data_type: sp::DataType::Array(_),
1801        format: None,
1802    } = right.clone()
1803    {
1804        right = *inner;
1805    }
1806    match right {
1807        sp::Expr::Value(v) => match v.value {
1808            sp::Value::Placeholder(_) => match value(v.value)? {
1809                Expr::Param(n) => Ok(Expr::AnyParam {
1810                    expr: lhs,
1811                    param: n,
1812                    negated,
1813                }),
1814                _ => no("array_param", "expected a numbered parameter"),
1815            },
1816            other => no("array_operand", &head(&other)),
1817        },
1818        sp::Expr::Array(sp::Array { elem, named: _ }) => Ok(Expr::InList {
1819            expr: lhs,
1820            list: elem.into_iter().map(expr).collect::<R<Vec<_>>>()?,
1821            negated,
1822        }),
1823        sp::Expr::Subquery(q) => Ok(Expr::InSubquery {
1824            expr: lhs,
1825            query: Box::new(query(*q)?),
1826            negated,
1827        }),
1828        other => no("array_operand", &head(&other)),
1829    }
1830}
1831
1832/// MySQL's `VALUES(col)` inside `ON DUPLICATE KEY UPDATE` refers to the row proposed for insertion.
1833fn excluded_refs(e: Expr) -> Expr {
1834    match e {
1835        Expr::Function(f) if f.name == "values" && f.args.len() == 1 => {
1836            match f.args.into_iter().next() {
1837                Some(FunctionArg::Expr(Expr::Column(n))) => {
1838                    Expr::Column(Name(vec!["excluded".to_string(), n.last().to_string()]))
1839                }
1840                other => Expr::Function(Function {
1841                    name: "values".into(),
1842                    args: other.into_iter().collect(),
1843                    distinct: false,
1844                    star: false,
1845                    filter: None,
1846                    over: None,
1847                    order_by: vec![],
1848                }),
1849            }
1850        }
1851        Expr::Binary { op, left, right } => Expr::Binary {
1852            op,
1853            left: Box::new(excluded_refs(*left)),
1854            right: Box::new(excluded_refs(*right)),
1855        },
1856        Expr::Nested(x) => Expr::Nested(Box::new(excluded_refs(*x))),
1857        Expr::Unary { op, expr } => Expr::Unary {
1858            op,
1859            expr: Box::new(excluded_refs(*expr)),
1860        },
1861        other => other,
1862    }
1863}
1864
1865fn like_expr(
1866    x: sp::Expr,
1867    pattern: sp::Expr,
1868    escape_char: Option<Box<sp::Expr>>,
1869    negated: bool,
1870    case_insensitive: bool,
1871) -> R<Expr> {
1872    let escape = match escape_char {
1873        Some(e) => Some(boxed(*e)?),
1874        None if rules().like_default_escape => {
1875            Some(Box::new(Expr::Literal(Literal::String("\\".into()))))
1876        }
1877        None => None,
1878    };
1879    Ok(Expr::Like {
1880        expr: boxed(x)?,
1881        pattern: boxed(pattern)?,
1882        negated,
1883        case_insensitive,
1884        escape,
1885    })
1886}
1887
1888fn value(v: sp::Value) -> R<Expr> {
1889    Ok(match v {
1890        sp::Value::Number(n, long) => {
1891            if long {
1892                return no("numeric_suffix", "L suffix");
1893            }
1894            Expr::Literal(Literal::Number(n))
1895        }
1896        sp::Value::SingleQuotedString(s) => Expr::Literal(Literal::String(s)),
1897        // The tokenizer has already resolved the backslash escapes of `E'..'`.
1898        sp::Value::EscapedStringLiteral(s) => Expr::Literal(Literal::String(s)),
1899        sp::Value::Boolean(b) if rules().name == "mysql" => {
1900            // MySQL TRUE/FALSE are the integers 1 and 0.
1901            Expr::Literal(Literal::Number(if b { "1" } else { "0" }.into()))
1902        }
1903        sp::Value::Boolean(b) => Expr::Literal(Literal::Bool(b)),
1904        sp::Value::Null => Expr::Literal(Literal::Null),
1905        sp::Value::Placeholder(p) => {
1906            let bad = || ReadError::NotInIr {
1907                construct: "placeholder".into(),
1908                detail: format!(
1909                    "`{p}` is not a placeholder form of dialect `{}`",
1910                    rules().name
1911                ),
1912            };
1913            if rules().question_placeholders {
1914                if p == "?" {
1915                    Expr::Param(bump_param(None, None))
1916                } else if let Some(d) = p.strip_prefix('?') {
1917                    let n = d.parse::<u32>().ok().filter(|n| *n >= 1).ok_or_else(bad)?;
1918                    Expr::Param(bump_param(Some(n), None))
1919                } else if let Some(nm) = p.strip_prefix([':', '@', '$']) {
1920                    Expr::Param(bump_param(None, Some(nm)))
1921                } else {
1922                    return Err(bad());
1923                }
1924            } else {
1925                let n = p
1926                    .strip_prefix('$')
1927                    .and_then(|d| d.parse::<u32>().ok())
1928                    .filter(|n| *n >= 1)
1929                    .ok_or_else(bad)?;
1930                Expr::Param(n)
1931            }
1932        }
1933        other => return no("literal", &head(&other)),
1934    })
1935}
1936
1937fn function(f: sp::Function) -> R<Expr> {
1938    let sp::Function {
1939        name,
1940        uses_odbc_syntax,
1941        parameters,
1942        args,
1943        within_group,
1944        filter,
1945        null_treatment,
1946        over,
1947    } = f;
1948    if uses_odbc_syntax
1949        || !matches!(parameters, sp::FunctionArguments::None)
1950        || !within_group.is_empty()
1951        || null_treatment.is_some()
1952    {
1953        return no(
1954            "function_option",
1955            "ODBC syntax/parameters/WITHIN GROUP/FILTER/IGNORE NULLS",
1956        );
1957    }
1958    let over = match over {
1959        None => None,
1960        Some(sp::WindowType::NamedWindow(_)) => {
1961            return no(
1962                "named_window",
1963                "OVER w (a WINDOW clause) is not in the IR yet",
1964            );
1965        }
1966        Some(sp::WindowType::WindowSpec(spec)) => Some(window_spec(spec)?),
1967    };
1968    let filter = filter.map(|f| expr(*f).map(Box::new)).transpose()?;
1969    let name = object_name(&name)?;
1970    let base = name.last().to_string();
1971    if name.0.len() != 1 {
1972        return no("qualified_function", &name.0.join("."));
1973    }
1974    let args = match args {
1975        // `CURRENT_TIMESTAMP` is a function without parentheses.
1976        sp::FunctionArguments::None => {
1977            if base == "current_timestamp" {
1978                if rules().name == "sqlite" {
1979                    add_note(
1980                        "fn:now",
1981                        "the source CURRENT_TIMESTAMP is text 'YYYY-MM-DD HH:MM:SS' (UTC), not a timestamptz",
1982                        Allowance::NowAsText,
1983                    );
1984                }
1985                return Ok(Expr::Function(Function {
1986                    name: "now".to_string(),
1987                    args: vec![],
1988                    distinct: false,
1989                    star: false,
1990                    filter: None,
1991                    over: None,
1992                    order_by: vec![],
1993                }));
1994            }
1995            // The session identity keywords are zero-argument functions.
1996            if matches!(
1997                base.as_str(),
1998                "current_user" | "session_user" | "current_role"
1999            ) {
2000                return Ok(Expr::Function(Function {
2001                    name: base,
2002                    args: vec![],
2003                    distinct: false,
2004                    star: false,
2005                    filter: None,
2006                    over: None,
2007                    order_by: vec![],
2008                }));
2009            }
2010            // `CURRENT_DATE`: a date in the session time zone (PostgreSQL, MySQL), text of the UTC
2011            // date on SQLite.
2012            if base == "current_date" {
2013                if rules().name == "sqlite" {
2014                    add_note(
2015                        "fn:current_date",
2016                        "the source CURRENT_DATE is text 'YYYY-MM-DD' (the UTC date), not a date",
2017                        Allowance::DateAsText,
2018                    );
2019                }
2020                return Ok(Expr::Function(Function {
2021                    name: "current_date".to_string(),
2022                    args: vec![],
2023                    distinct: false,
2024                    star: false,
2025                    filter: None,
2026                    over: None,
2027                    order_by: vec![],
2028                }));
2029            }
2030            return no("bare_function", &format!("`{base}` without parentheses"));
2031        }
2032        sp::FunctionArguments::Subquery(q) if base == "array" => {
2033            return Ok(Expr::ArraySubquery(Box::new(query(*q)?)));
2034        }
2035        sp::FunctionArguments::Subquery(_) => {
2036            return no("function_subquery", "function over a subquery");
2037        }
2038        sp::FunctionArguments::List(l) => l,
2039    };
2040    let sp::FunctionArgumentList {
2041        duplicate_treatment,
2042        args,
2043        clauses,
2044    } = args;
2045    let mut agg_order = Vec::new();
2046    let mut separator: Option<String> = None;
2047    for cl in clauses {
2048        match cl {
2049            sp::FunctionArgumentClause::OrderBy(items) => {
2050                for it in items {
2051                    agg_order.push(order_item(it)?);
2052                }
2053            }
2054            sp::FunctionArgumentClause::Separator(v) => match v.value {
2055                sp::Value::SingleQuotedString(s) => separator = Some(s),
2056                other => return no("separator", &head(&other)),
2057            },
2058            other => {
2059                return no(
2060                    "function_clause",
2061                    &format!("{} inside a function call", head(&other)),
2062                );
2063            }
2064        }
2065    }
2066    let distinct = match duplicate_treatment {
2067        None | Some(sp::DuplicateTreatment::All) => false,
2068        Some(sp::DuplicateTreatment::Distinct) => true,
2069    };
2070    let mut out = Vec::new();
2071    let mut star = false;
2072    for a in args {
2073        match a {
2074            sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Expr(e)) => {
2075                out.push(FunctionArg::Expr(expr(e)?))
2076            }
2077            sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Wildcard) => star = true,
2078            sp::FunctionArg::Named {
2079                name,
2080                arg: sp::FunctionArgExpr::Expr(e),
2081                operator: sp::FunctionArgOperator::RightArrow,
2082            } => out.push(FunctionArg::Named {
2083                name: ident(&name),
2084                value: expr(e)?,
2085            }),
2086            // sqlparser produces `ExprNamed` when the name is parsed as an expression.
2087            sp::FunctionArg::ExprNamed {
2088                name: sp::Expr::Identifier(name),
2089                arg: sp::FunctionArgExpr::Expr(e),
2090                operator: sp::FunctionArgOperator::RightArrow,
2091            } => out.push(FunctionArg::Named {
2092                name: ident(&name),
2093                value: expr(e)?,
2094            }),
2095            other => return no("function_argument", &head(&other)),
2096        }
2097    }
2098    let mut name = base;
2099    if name == "current_timestamp" {
2100        name = "now".to_string();
2101    }
2102    if rules().name == "mysql" {
2103        match name.as_str() {
2104            "ifnull" => name = "coalesce".to_string(),
2105            "curdate" if out.is_empty() => name = "current_date".to_string(),
2106            "group_concat" => {
2107                name = "string_agg".to_string();
2108                out.push(FunctionArg::Expr(Expr::Literal(Literal::String(
2109                    separator.clone().unwrap_or_else(|| ",".to_string()),
2110                ))));
2111                add_note(
2112                    "fn:string_agg",
2113                    "the source GROUP_CONCAT truncates silently at group_concat_max_len",
2114                    Allowance::AggregateStringTruncation,
2115                );
2116            }
2117            // MySQL LENGTH() counts bytes.
2118            "length" => name = "octet_length".to_string(),
2119            "concat" if out.len() >= 2 => {
2120                let mut it = out.into_iter().map(|a| match a {
2121                    FunctionArg::Expr(e) => e,
2122                    FunctionArg::Named { value, .. } => value,
2123                });
2124                let first = it.next().expect("two arguments");
2125                let chain = it.fold(first, |l, r| Expr::Binary {
2126                    op: BinaryOp::Concat,
2127                    left: Box::new(l),
2128                    right: Box::new(r),
2129                });
2130                return Ok(chain);
2131            }
2132            "if" if out.len() == 3 => {
2133                let mut it = out.into_iter().map(|a| match a {
2134                    FunctionArg::Expr(e) => e,
2135                    FunctionArg::Named { value, .. } => value,
2136                });
2137                let (c, t, f) = (it.next().unwrap(), it.next().unwrap(), it.next().unwrap());
2138                return Ok(Expr::Case {
2139                    operand: None,
2140                    branches: vec![(c, t)],
2141                    else_: Some(Box::new(f)),
2142                });
2143            }
2144            _ => {}
2145        }
2146    }
2147    if rules().name == "sqlite" {
2148        match name.as_str() {
2149            "ifnull" => name = "coalesce".to_string(),
2150            "group_concat" => {
2151                name = "string_agg".to_string();
2152                if out.len() == 1 {
2153                    out.push(FunctionArg::Expr(Expr::Literal(Literal::String(
2154                        ",".into(),
2155                    ))));
2156                }
2157            }
2158            _ => {}
2159        }
2160    }
2161    Ok(Expr::Function(Function {
2162        name,
2163        args: out,
2164        distinct,
2165        star,
2166        filter,
2167        over,
2168        order_by: agg_order,
2169    }))
2170}
2171
2172/// `INTERVAL '3 days'` / `INTERVAL 3 DAY` as `make_interval(days => 3)`. Only a single `<number> <unit>`
2173/// is represented; compound intervals (`'1 day 2 hours'`), ranges (`DAY TO SECOND`) and unit-less
2174/// strings are not in the IR. Months and years are read (and then refused by the targets, whose
2175/// month arithmetic differs), not guessed.
2176fn interval_call(iv: sp::Interval) -> R<Expr> {
2177    let sp::Interval {
2178        value,
2179        leading_field,
2180        leading_precision,
2181        last_field,
2182        fractional_seconds_precision,
2183    } = iv;
2184    if leading_precision.is_some() || last_field.is_some() || fractional_seconds_precision.is_some()
2185    {
2186        return no(
2187            "interval",
2188            "interval ranges and precisions are not in the IR",
2189        );
2190    }
2191    let (amount, unit) = match (*value, leading_field) {
2192        // MySQL `INTERVAL 3 DAY`
2193        (sp::Expr::Value(v), Some(field)) => (
2194            match v.value {
2195                sp::Value::Number(n, _) => n,
2196                other => return no("interval", &head(&other)),
2197            },
2198            field.to_string(),
2199        ),
2200        // PostgreSQL / standard `INTERVAL '3 days'`
2201        (sp::Expr::Value(v), None) => match v.value {
2202            sp::Value::SingleQuotedString(s) => {
2203                let mut it = s.split_whitespace();
2204                match (it.next(), it.next(), it.next()) {
2205                    (Some(a), Some(u), None) => (a.to_string(), u.to_string()),
2206                    _ => {
2207                        return no(
2208                            "interval",
2209                            "only a single `<number> <unit>` interval is in the IR",
2210                        );
2211                    }
2212                }
2213            }
2214            other => return no("interval", &head(&other)),
2215        },
2216        (other, _) => return no("interval", &head(&other)),
2217    };
2218    let numeric = !amount.is_empty()
2219        && amount
2220            .trim_start_matches('-')
2221            .chars()
2222            .all(|c| c.is_ascii_digit() || c == '.')
2223        && amount
2224            .trim_start_matches('-')
2225            .chars()
2226            .any(|c| c.is_ascii_digit());
2227    if !numeric {
2228        return no("interval", "the interval amount is not a plain number");
2229    }
2230    let unit = match unit.to_ascii_lowercase().trim_end_matches('s') {
2231        "second" | "sec" => "secs",
2232        "minute" | "min" => "mins",
2233        "hour" => "hours",
2234        "day" => "days",
2235        "week" => "weeks",
2236        "month" | "mon" => "months",
2237        "year" => "years",
2238        other => return no("interval", &format!("unit `{other}` is not in the IR")),
2239    };
2240    Ok(Expr::Function(Function {
2241        name: "make_interval".to_string(),
2242        args: vec![FunctionArg::Named {
2243            name: unit.to_string(),
2244            value: Expr::Literal(Literal::Number(amount)),
2245        }],
2246        distinct: false,
2247        star: false,
2248        filter: None,
2249        over: None,
2250        order_by: vec![],
2251    }))
2252}
2253
2254fn window_spec(w: sp::WindowSpec) -> R<Window> {
2255    let sp::WindowSpec {
2256        window_name,
2257        partition_by,
2258        order_by,
2259        window_frame,
2260    } = w;
2261    if window_name.is_some() {
2262        return no("named_window", "OVER (w ..) refinement of a named window");
2263    }
2264    let frame = match window_frame {
2265        None => None,
2266        Some(sp::WindowFrame {
2267            units,
2268            start_bound,
2269            end_bound,
2270        }) => {
2271            let bound = |b: sp::WindowFrameBound| -> R<FrameBound> {
2272                Ok(match b {
2273                    sp::WindowFrameBound::CurrentRow => FrameBound::CurrentRow,
2274                    sp::WindowFrameBound::Preceding(e) => {
2275                        FrameBound::Preceding(e.map(|x| expr(*x).map(Box::new)).transpose()?)
2276                    }
2277                    sp::WindowFrameBound::Following(e) => {
2278                        FrameBound::Following(e.map(|x| expr(*x).map(Box::new)).transpose()?)
2279                    }
2280                })
2281            };
2282            Some(Frame {
2283                units: match units {
2284                    sp::WindowFrameUnits::Rows => FrameUnits::Rows,
2285                    sp::WindowFrameUnits::Range => FrameUnits::Range,
2286                    sp::WindowFrameUnits::Groups => FrameUnits::Groups,
2287                },
2288                start: bound(start_bound)?,
2289                end: end_bound.map(bound).transpose()?,
2290            })
2291        }
2292    };
2293    Ok(Window {
2294        partition_by: partition_by.into_iter().map(expr).collect::<R<_>>()?,
2295        order_by: order_by.into_iter().map(order_item).collect::<R<_>>()?,
2296        frame,
2297    })
2298}
2299
2300fn data_type_to_ir(t: &sp::DataType) -> R<SqlType> {
2301    use sp::DataType as D;
2302    Ok(match t {
2303        D::SmallInt(_) | D::Int2(_) => SqlType::SmallInt,
2304        D::Int(_) | D::Integer(_) | D::Int4(_) => SqlType::Integer,
2305        D::BigInt(_) | D::Int8(_) => SqlType::BigInt,
2306        D::Real | D::Float4 => SqlType::Real,
2307        D::Double(_) | D::DoublePrecision | D::Float8 => SqlType::Double,
2308        D::Numeric(info) | D::Decimal(info) => match info {
2309            sp::ExactNumberInfo::None => SqlType::Numeric {
2310                precision: None,
2311                scale: None,
2312            },
2313            sp::ExactNumberInfo::Precision(p) => SqlType::Numeric {
2314                precision: Some(*p as u32),
2315                scale: None,
2316            },
2317            sp::ExactNumberInfo::PrecisionAndScale(p, s) => SqlType::Numeric {
2318                precision: Some(*p as u32),
2319                scale: Some(*s as u32),
2320            },
2321        },
2322        D::Text => SqlType::Text,
2323        D::Signed | D::SignedInteger | D::Unsigned | D::UnsignedInteger => SqlType::BigInt,
2324        D::Char(None) | D::Character(None) => SqlType::Text,
2325        D::Datetime(None) => SqlType::Timestamp { with_tz: false },
2326        D::Varchar(None) | D::CharVarying(None) => SqlType::Varchar(None),
2327        D::Varchar(Some(sp::CharacterLength::IntegerLength { length, unit: None }))
2328        | D::CharVarying(Some(sp::CharacterLength::IntegerLength { length, unit: None })) => {
2329            SqlType::Varchar(Some(*length as u32))
2330        }
2331        D::Boolean | D::Bool => SqlType::Boolean,
2332        D::Date => SqlType::Date,
2333        D::Timestamp(None, tz) => SqlType::Timestamp {
2334            with_tz: match tz {
2335                sp::TimezoneInfo::None | sp::TimezoneInfo::WithoutTimeZone => false,
2336                sp::TimezoneInfo::WithTimeZone | sp::TimezoneInfo::Tz => true,
2337            },
2338        },
2339        D::Uuid => SqlType::Uuid,
2340        D::Bytea => SqlType::Bytes,
2341        D::JSON => SqlType::Json,
2342        D::JSONB => SqlType::Jsonb,
2343        other => return no("data_type", &format!("{other}")),
2344    })
2345}