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 expr(e: sp::Expr) -> R<Expr> {
1403    use sp::Expr as E;
1404    Ok(match e {
1405        // `DEFAULT` in VALUES / SET is parsed as an identifier; as a column it would be written
1406        // quoted and mean something else (PostgreSQL rejects it, MySQL would read a column).
1407        E::Identifier(i) if i.quote_style.is_none() && i.value.eq_ignore_ascii_case("default") => {
1408            return no("default_value", "DEFAULT as a value is not in the IR");
1409        }
1410        E::Identifier(i) => Expr::Column(Name::simple(ident(&i))),
1411        E::CompoundIdentifier(parts) => Expr::Column(Name(parts.iter().map(ident).collect())),
1412        E::Value(v) => value(v.value)?,
1413        E::Nested(inner) => Expr::Nested(boxed(*inner)?),
1414        E::IsNull(x) => Expr::IsNull {
1415            expr: boxed(*x)?,
1416            negated: false,
1417        },
1418        E::IsNotNull(x) => Expr::IsNull {
1419            expr: boxed(*x)?,
1420            negated: true,
1421        },
1422        E::InList {
1423            expr: x,
1424            list,
1425            negated,
1426        } => Expr::InList {
1427            expr: boxed(*x)?,
1428            list: list.into_iter().map(expr).collect::<R<_>>()?,
1429            negated,
1430        },
1431        E::InSubquery {
1432            expr: x,
1433            subquery,
1434            negated,
1435        } => Expr::InSubquery {
1436            expr: boxed(*x)?,
1437            query: Box::new(query(*subquery)?),
1438            negated,
1439        },
1440        E::Between {
1441            expr: x,
1442            negated,
1443            low,
1444            high,
1445        } => Expr::Between {
1446            expr: boxed(*x)?,
1447            low: boxed(*low)?,
1448            high: boxed(*high)?,
1449            negated,
1450        },
1451        E::Like {
1452            negated,
1453            any,
1454            expr: x,
1455            pattern,
1456            escape_char,
1457        } => {
1458            if any {
1459                return no("like_option", "LIKE ANY");
1460            }
1461            let ci = rules().like_ci_default;
1462            if ci {
1463                add_note(
1464                    "like",
1465                    "the source LIKE is ASCII case-insensitive only while its connection setting is at the default",
1466                    Allowance::LikeCaseSensitivityIsConnectionSetting,
1467                );
1468            }
1469            if rules().name == "mysql" {
1470                add_note(
1471                    "like",
1472                    "the source LIKE follows the column collation; read as case-sensitive (a binary collation)",
1473                    Allowance::LikeCaseSensitivityIsConnectionSetting,
1474                );
1475            }
1476            like_expr(*x, *pattern, escape_char, negated, ci)?
1477        }
1478        E::ILike {
1479            negated,
1480            any,
1481            expr: x,
1482            pattern,
1483            escape_char,
1484        } => {
1485            if any {
1486                return no("like_option", "ILIKE ANY");
1487            }
1488            like_expr(*x, *pattern, escape_char, negated, true)?
1489        }
1490        E::UnaryOp { op, expr: x } => {
1491            let op = match op {
1492                sp::UnaryOperator::Not => UnaryOp::Not,
1493                sp::UnaryOperator::Minus => UnaryOp::Minus,
1494                sp::UnaryOperator::Plus => UnaryOp::Plus,
1495                other => return no("unary_operator", &head(&other)),
1496            };
1497            Expr::Unary {
1498                op,
1499                expr: boxed(*x)?,
1500            }
1501        }
1502        E::BinaryOp { left, op, right } => {
1503            use sp::BinaryOperator as B;
1504            let op = match op {
1505                B::Eq => BinaryOp::Eq,
1506                B::NotEq => BinaryOp::NotEq,
1507                B::Lt => BinaryOp::Lt,
1508                B::LtEq => BinaryOp::LtEq,
1509                B::Gt => BinaryOp::Gt,
1510                B::GtEq => BinaryOp::GtEq,
1511                B::And => BinaryOp::And,
1512                B::Or => BinaryOp::Or,
1513                B::Plus => BinaryOp::Plus,
1514                B::Minus => BinaryOp::Minus,
1515                B::Multiply => BinaryOp::Multiply,
1516                B::Divide => BinaryOp::Divide,
1517                B::Modulo => BinaryOp::Modulo,
1518                // MySQL's default sql_mode makes `||` a logical OR with OR's (lowest) precedence, but
1519                // sqlparser parses it as concatenation with concatenation's precedence, so the tree
1520                // is wrong either way: refuse instead of guessing.
1521                B::StringConcat if rules().name == "mysql" => {
1522                    return no(
1523                        "pipes_operator",
1524                        "MySQL `||` is logical OR (default sql_mode) but the parser gives it concatenation precedence; write OR, or CONCAT()",
1525                    );
1526                }
1527                B::StringConcat => BinaryOp::Concat,
1528                B::MyIntegerDivide => BinaryOp::IntDivide,
1529                B::Spaceship => BinaryOp::NullSafeEq,
1530                B::Arrow => BinaryOp::JsonGet,
1531                B::LongArrow => BinaryOp::JsonGetText,
1532                other => {
1533                    return no(
1534                        "binary_operator",
1535                        &format!(
1536                            "{} (JSON/array/regex/bitwise operators are not in the IR)",
1537                            head(&other)
1538                        ),
1539                    );
1540                }
1541            };
1542            if op == BinaryOp::Divide && rules().name == "mysql" {
1543                add_note(
1544                    "division",
1545                    "the source `/` is exact (DECIMAL) division; the target divides as double precision",
1546                    Allowance::DecimalDivisionAsFloat,
1547                );
1548                let l = Expr::Cast {
1549                    expr: boxed(*left)?,
1550                    ty: SqlType::Double,
1551                };
1552                return Ok(Expr::Binary {
1553                    op,
1554                    left: Box::new(l),
1555                    right: boxed(*right)?,
1556                });
1557            }
1558            // `ts +/- INTERVAL 'n unit'` is the same statement as `ts +/- make_interval(unit => n)`:
1559            // one IR form, so every target's interval arithmetic (and its refusal of months/years)
1560            // applies unchanged. `INTERVAL 'n unit' + ts` commutes for `+` only.
1561            match (op, *left, *right) {
1562                (BinaryOp::Plus | BinaryOp::Minus, l, E::Interval(iv)) => Expr::Binary {
1563                    op,
1564                    left: boxed(l)?,
1565                    right: Box::new(interval_call(iv)?),
1566                },
1567                (BinaryOp::Plus, E::Interval(iv), r) => Expr::Binary {
1568                    op,
1569                    left: boxed(r)?,
1570                    right: Box::new(interval_call(iv)?),
1571                },
1572                (op, l, r) => Expr::Binary {
1573                    op,
1574                    left: boxed(l)?,
1575                    right: boxed(r)?,
1576                },
1577            }
1578        }
1579        E::Case {
1580            case_token: _,
1581            end_token: _,
1582            operand,
1583            conditions,
1584            else_result,
1585        } => Expr::Case {
1586            operand: operand.map(|o| boxed(*o)).transpose()?,
1587            branches: conditions
1588                .into_iter()
1589                .map(|sp::CaseWhen { condition, result }| Ok((expr(condition)?, expr(result)?)))
1590                .collect::<R<_>>()?,
1591            else_: else_result.map(|o| boxed(*o)).transpose()?,
1592        },
1593        E::Cast {
1594            kind,
1595            expr: x,
1596            data_type,
1597            format,
1598        } => {
1599            if format.is_some() || !matches!(kind, sp::CastKind::Cast | sp::CastKind::DoubleColon) {
1600                return no("cast_form", "TRY_CAST / SAFE_CAST / CAST .. FORMAT");
1601            }
1602            Expr::Cast {
1603                expr: boxed(*x)?,
1604                ty: data_type_to_ir(&data_type)?,
1605            }
1606        }
1607        E::Trim {
1608            trim_where,
1609            trim_what,
1610            expr: x,
1611            trim_characters,
1612        } => {
1613            // `trim(chars FROM x)` / `trim(BOTH chars FROM x)`; the comma form is `trim_characters`.
1614            let side = match trim_where {
1615                None | Some(sp::TrimWhereField::Both) => TrimSide::Both,
1616                Some(sp::TrimWhereField::Leading) => TrimSide::Leading,
1617                Some(sp::TrimWhereField::Trailing) => TrimSide::Trailing,
1618            };
1619            let chars = match (trim_what, trim_characters) {
1620                (Some(w), None) => Some(boxed(*w)?),
1621                (None, None) => None,
1622                (None, Some(mut cs)) if cs.len() == 1 => Some(boxed(cs.remove(0))?),
1623                _ => return no("trim_form", "TRIM with several character arguments"),
1624            };
1625            Expr::Trim {
1626                expr: boxed(*x)?,
1627                side,
1628                chars,
1629            }
1630        }
1631        E::Substring {
1632            expr: x,
1633            substring_from,
1634            substring_for,
1635            special: _,
1636            shorthand: _,
1637        } => {
1638            if rules().name == "mysql" {
1639                // From position 1 and a non-negative length the engines agree; any other start
1640                // (0, negative, an expression) or length is the caller's stated assumption.
1641                let positive = |e: &E, min: u64| {
1642                    matches!(
1643                        e,
1644                        E::Value(v) if matches!(&v.value, sp::Value::Number(n, _)
1645                            if n.parse::<u64>().is_ok_and(|x| x >= min))
1646                    )
1647                };
1648                let start_ok = substring_from.as_deref().is_some_and(|f| positive(f, 1));
1649                let len_ok = substring_for.as_deref().is_none_or(|l| positive(l, 0));
1650                if !(start_ok && len_ok) {
1651                    add_note(
1652                        "fn:substr.start_position",
1653                        "MySQL SUBSTRING counts a start of 0 as empty and a negative start from the end; \
1654                         the target does not",
1655                        Allowance::SubstringStartAssumedPositive,
1656                    );
1657                }
1658            }
1659            // `substring(x FROM a FOR b)` and `substring(x, a, b)` are `substr(x, a, b)`.
1660            let mut args = vec![FunctionArg::Expr(expr(*x)?)];
1661            match (substring_from, substring_for) {
1662                (Some(f), Some(l)) => {
1663                    args.push(FunctionArg::Expr(expr(*f)?));
1664                    args.push(FunctionArg::Expr(expr(*l)?));
1665                }
1666                (Some(f), None) => args.push(FunctionArg::Expr(expr(*f)?)),
1667                (None, Some(l)) => {
1668                    // FOR without FROM starts at position 1.
1669                    args.push(FunctionArg::Expr(Expr::Literal(Literal::Number(
1670                        "1".into(),
1671                    ))));
1672                    args.push(FunctionArg::Expr(expr(*l)?));
1673                }
1674                (None, None) => return no("substring_form", "SUBSTRING without FROM or FOR"),
1675            }
1676            Expr::Function(Function {
1677                name: "substr".into(),
1678                args,
1679                distinct: false,
1680                star: false,
1681                filter: None,
1682                over: None,
1683                order_by: vec![],
1684            })
1685        }
1686        E::AnyOp {
1687            left,
1688            compare_op,
1689            right,
1690            is_some: _,
1691        } => {
1692            if !matches!(compare_op, sp::BinaryOperator::Eq) {
1693                return no("any_operator", "only `= ANY(..)` is in the IR");
1694            }
1695            quantified(*left, *right, false)?
1696        }
1697        E::AllOp {
1698            left,
1699            compare_op,
1700            right,
1701        } => {
1702            if !matches!(compare_op, sp::BinaryOperator::NotEq) {
1703                return no("all_operator", "only `<> ALL(..)` is in the IR");
1704            }
1705            quantified(*left, *right, true)?
1706        }
1707        E::Exists { subquery, negated } => Expr::Exists {
1708            query: Box::new(query(*subquery)?),
1709            negated,
1710        },
1711        E::Subquery(q) => Expr::Subquery(Box::new(query(*q)?)),
1712        E::Extract {
1713            field,
1714            syntax: _,
1715            expr: x,
1716        } => Expr::Extract {
1717            field: field.to_string().to_ascii_lowercase(),
1718            expr: boxed(*x)?,
1719        },
1720        E::Array(arr) => Expr::ArrayLiteral(arr.elem.into_iter().map(expr).collect::<R<Vec<_>>>()?),
1721        E::AtTimeZone {
1722            timestamp,
1723            time_zone,
1724        } => Expr::AtTimeZone {
1725            expr: boxed(*timestamp)?,
1726            zone: boxed(*time_zone)?,
1727        },
1728        E::Function(f) => function(f)?,
1729        other => return no("expression", &head(&other)),
1730    })
1731}
1732
1733/// `x = ANY(rhs)` / `x <> ALL(rhs)`: an array parameter, an array literal, or a subquery.
1734fn quantified(left: sp::Expr, right: sp::Expr, negated: bool) -> R<Expr> {
1735    let lhs = boxed(left)?;
1736    // `$1::int[]` is only a type hint on the parameter.
1737    let mut right = right;
1738    if let sp::Expr::Cast {
1739        kind: sp::CastKind::Cast | sp::CastKind::DoubleColon,
1740        expr: inner,
1741        data_type: sp::DataType::Array(_),
1742        format: None,
1743    } = right.clone()
1744    {
1745        right = *inner;
1746    }
1747    match right {
1748        sp::Expr::Value(v) => match v.value {
1749            sp::Value::Placeholder(_) => match value(v.value)? {
1750                Expr::Param(n) => Ok(Expr::AnyParam {
1751                    expr: lhs,
1752                    param: n,
1753                    negated,
1754                }),
1755                _ => no("array_param", "expected a numbered parameter"),
1756            },
1757            other => no("array_operand", &head(&other)),
1758        },
1759        sp::Expr::Array(sp::Array { elem, named: _ }) => Ok(Expr::InList {
1760            expr: lhs,
1761            list: elem.into_iter().map(expr).collect::<R<Vec<_>>>()?,
1762            negated,
1763        }),
1764        sp::Expr::Subquery(q) => Ok(Expr::InSubquery {
1765            expr: lhs,
1766            query: Box::new(query(*q)?),
1767            negated,
1768        }),
1769        other => no("array_operand", &head(&other)),
1770    }
1771}
1772
1773/// MySQL's `VALUES(col)` inside `ON DUPLICATE KEY UPDATE` refers to the row proposed for insertion.
1774fn excluded_refs(e: Expr) -> Expr {
1775    match e {
1776        Expr::Function(f) if f.name == "values" && f.args.len() == 1 => {
1777            match f.args.into_iter().next() {
1778                Some(FunctionArg::Expr(Expr::Column(n))) => {
1779                    Expr::Column(Name(vec!["excluded".to_string(), n.last().to_string()]))
1780                }
1781                other => Expr::Function(Function {
1782                    name: "values".into(),
1783                    args: other.into_iter().collect(),
1784                    distinct: false,
1785                    star: false,
1786                    filter: None,
1787                    over: None,
1788                    order_by: vec![],
1789                }),
1790            }
1791        }
1792        Expr::Binary { op, left, right } => Expr::Binary {
1793            op,
1794            left: Box::new(excluded_refs(*left)),
1795            right: Box::new(excluded_refs(*right)),
1796        },
1797        Expr::Nested(x) => Expr::Nested(Box::new(excluded_refs(*x))),
1798        Expr::Unary { op, expr } => Expr::Unary {
1799            op,
1800            expr: Box::new(excluded_refs(*expr)),
1801        },
1802        other => other,
1803    }
1804}
1805
1806fn like_expr(
1807    x: sp::Expr,
1808    pattern: sp::Expr,
1809    escape_char: Option<Box<sp::Expr>>,
1810    negated: bool,
1811    case_insensitive: bool,
1812) -> R<Expr> {
1813    let escape = match escape_char {
1814        Some(e) => Some(boxed(*e)?),
1815        None if rules().like_default_escape => {
1816            Some(Box::new(Expr::Literal(Literal::String("\\".into()))))
1817        }
1818        None => None,
1819    };
1820    Ok(Expr::Like {
1821        expr: boxed(x)?,
1822        pattern: boxed(pattern)?,
1823        negated,
1824        case_insensitive,
1825        escape,
1826    })
1827}
1828
1829fn value(v: sp::Value) -> R<Expr> {
1830    Ok(match v {
1831        sp::Value::Number(n, long) => {
1832            if long {
1833                return no("numeric_suffix", "L suffix");
1834            }
1835            Expr::Literal(Literal::Number(n))
1836        }
1837        sp::Value::SingleQuotedString(s) => Expr::Literal(Literal::String(s)),
1838        // The tokenizer has already resolved the backslash escapes of `E'..'`.
1839        sp::Value::EscapedStringLiteral(s) => Expr::Literal(Literal::String(s)),
1840        sp::Value::Boolean(b) if rules().name == "mysql" => {
1841            // MySQL TRUE/FALSE are the integers 1 and 0.
1842            Expr::Literal(Literal::Number(if b { "1" } else { "0" }.into()))
1843        }
1844        sp::Value::Boolean(b) => Expr::Literal(Literal::Bool(b)),
1845        sp::Value::Null => Expr::Literal(Literal::Null),
1846        sp::Value::Placeholder(p) => {
1847            let bad = || ReadError::NotInIr {
1848                construct: "placeholder".into(),
1849                detail: format!(
1850                    "`{p}` is not a placeholder form of dialect `{}`",
1851                    rules().name
1852                ),
1853            };
1854            if rules().question_placeholders {
1855                if p == "?" {
1856                    Expr::Param(bump_param(None, None))
1857                } else if let Some(d) = p.strip_prefix('?') {
1858                    let n = d.parse::<u32>().ok().filter(|n| *n >= 1).ok_or_else(bad)?;
1859                    Expr::Param(bump_param(Some(n), None))
1860                } else if let Some(nm) = p.strip_prefix([':', '@', '$']) {
1861                    Expr::Param(bump_param(None, Some(nm)))
1862                } else {
1863                    return Err(bad());
1864                }
1865            } else {
1866                let n = p
1867                    .strip_prefix('$')
1868                    .and_then(|d| d.parse::<u32>().ok())
1869                    .filter(|n| *n >= 1)
1870                    .ok_or_else(bad)?;
1871                Expr::Param(n)
1872            }
1873        }
1874        other => return no("literal", &head(&other)),
1875    })
1876}
1877
1878fn function(f: sp::Function) -> R<Expr> {
1879    let sp::Function {
1880        name,
1881        uses_odbc_syntax,
1882        parameters,
1883        args,
1884        within_group,
1885        filter,
1886        null_treatment,
1887        over,
1888    } = f;
1889    if uses_odbc_syntax
1890        || !matches!(parameters, sp::FunctionArguments::None)
1891        || !within_group.is_empty()
1892        || null_treatment.is_some()
1893    {
1894        return no(
1895            "function_option",
1896            "ODBC syntax/parameters/WITHIN GROUP/FILTER/IGNORE NULLS",
1897        );
1898    }
1899    let over = match over {
1900        None => None,
1901        Some(sp::WindowType::NamedWindow(_)) => {
1902            return no(
1903                "named_window",
1904                "OVER w (a WINDOW clause) is not in the IR yet",
1905            );
1906        }
1907        Some(sp::WindowType::WindowSpec(spec)) => Some(window_spec(spec)?),
1908    };
1909    let filter = filter.map(|f| expr(*f).map(Box::new)).transpose()?;
1910    let name = object_name(&name)?;
1911    let base = name.last().to_string();
1912    if name.0.len() != 1 {
1913        return no("qualified_function", &name.0.join("."));
1914    }
1915    let args = match args {
1916        // `CURRENT_TIMESTAMP` is a function without parentheses.
1917        sp::FunctionArguments::None => {
1918            if base == "current_timestamp" {
1919                if rules().name == "sqlite" {
1920                    add_note(
1921                        "fn:now",
1922                        "the source CURRENT_TIMESTAMP is text 'YYYY-MM-DD HH:MM:SS' (UTC), not a timestamptz",
1923                        Allowance::NowAsText,
1924                    );
1925                }
1926                return Ok(Expr::Function(Function {
1927                    name: "now".to_string(),
1928                    args: vec![],
1929                    distinct: false,
1930                    star: false,
1931                    filter: None,
1932                    over: None,
1933                    order_by: vec![],
1934                }));
1935            }
1936            // The session identity keywords are zero-argument functions.
1937            if matches!(
1938                base.as_str(),
1939                "current_user" | "session_user" | "current_role"
1940            ) {
1941                return Ok(Expr::Function(Function {
1942                    name: base,
1943                    args: vec![],
1944                    distinct: false,
1945                    star: false,
1946                    filter: None,
1947                    over: None,
1948                    order_by: vec![],
1949                }));
1950            }
1951            // `CURRENT_DATE`: a date in the session time zone (PostgreSQL, MySQL), text of the UTC
1952            // date on SQLite.
1953            if base == "current_date" {
1954                if rules().name == "sqlite" {
1955                    add_note(
1956                        "fn:current_date",
1957                        "the source CURRENT_DATE is text 'YYYY-MM-DD' (the UTC date), not a date",
1958                        Allowance::DateAsText,
1959                    );
1960                }
1961                return Ok(Expr::Function(Function {
1962                    name: "current_date".to_string(),
1963                    args: vec![],
1964                    distinct: false,
1965                    star: false,
1966                    filter: None,
1967                    over: None,
1968                    order_by: vec![],
1969                }));
1970            }
1971            return no("bare_function", &format!("`{base}` without parentheses"));
1972        }
1973        sp::FunctionArguments::Subquery(q) if base == "array" => {
1974            return Ok(Expr::ArraySubquery(Box::new(query(*q)?)));
1975        }
1976        sp::FunctionArguments::Subquery(_) => {
1977            return no("function_subquery", "function over a subquery");
1978        }
1979        sp::FunctionArguments::List(l) => l,
1980    };
1981    let sp::FunctionArgumentList {
1982        duplicate_treatment,
1983        args,
1984        clauses,
1985    } = args;
1986    let mut agg_order = Vec::new();
1987    let mut separator: Option<String> = None;
1988    for cl in clauses {
1989        match cl {
1990            sp::FunctionArgumentClause::OrderBy(items) => {
1991                for it in items {
1992                    agg_order.push(order_item(it)?);
1993                }
1994            }
1995            sp::FunctionArgumentClause::Separator(v) => match v.value {
1996                sp::Value::SingleQuotedString(s) => separator = Some(s),
1997                other => return no("separator", &head(&other)),
1998            },
1999            other => {
2000                return no(
2001                    "function_clause",
2002                    &format!("{} inside a function call", head(&other)),
2003                );
2004            }
2005        }
2006    }
2007    let distinct = match duplicate_treatment {
2008        None | Some(sp::DuplicateTreatment::All) => false,
2009        Some(sp::DuplicateTreatment::Distinct) => true,
2010    };
2011    let mut out = Vec::new();
2012    let mut star = false;
2013    for a in args {
2014        match a {
2015            sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Expr(e)) => {
2016                out.push(FunctionArg::Expr(expr(e)?))
2017            }
2018            sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Wildcard) => star = true,
2019            sp::FunctionArg::Named {
2020                name,
2021                arg: sp::FunctionArgExpr::Expr(e),
2022                operator: sp::FunctionArgOperator::RightArrow,
2023            } => out.push(FunctionArg::Named {
2024                name: ident(&name),
2025                value: expr(e)?,
2026            }),
2027            // sqlparser produces `ExprNamed` when the name is parsed as an expression.
2028            sp::FunctionArg::ExprNamed {
2029                name: sp::Expr::Identifier(name),
2030                arg: sp::FunctionArgExpr::Expr(e),
2031                operator: sp::FunctionArgOperator::RightArrow,
2032            } => out.push(FunctionArg::Named {
2033                name: ident(&name),
2034                value: expr(e)?,
2035            }),
2036            other => return no("function_argument", &head(&other)),
2037        }
2038    }
2039    let mut name = base;
2040    if name == "current_timestamp" {
2041        name = "now".to_string();
2042    }
2043    if rules().name == "mysql" {
2044        match name.as_str() {
2045            "ifnull" => name = "coalesce".to_string(),
2046            "curdate" if out.is_empty() => name = "current_date".to_string(),
2047            "group_concat" => {
2048                name = "string_agg".to_string();
2049                out.push(FunctionArg::Expr(Expr::Literal(Literal::String(
2050                    separator.clone().unwrap_or_else(|| ",".to_string()),
2051                ))));
2052                add_note(
2053                    "fn:string_agg",
2054                    "the source GROUP_CONCAT truncates silently at group_concat_max_len",
2055                    Allowance::AggregateStringTruncation,
2056                );
2057            }
2058            // MySQL LENGTH() counts bytes.
2059            "length" => name = "octet_length".to_string(),
2060            "concat" if out.len() >= 2 => {
2061                let mut it = out.into_iter().map(|a| match a {
2062                    FunctionArg::Expr(e) => e,
2063                    FunctionArg::Named { value, .. } => value,
2064                });
2065                let first = it.next().expect("two arguments");
2066                let chain = it.fold(first, |l, r| Expr::Binary {
2067                    op: BinaryOp::Concat,
2068                    left: Box::new(l),
2069                    right: Box::new(r),
2070                });
2071                return Ok(chain);
2072            }
2073            "if" if out.len() == 3 => {
2074                let mut it = out.into_iter().map(|a| match a {
2075                    FunctionArg::Expr(e) => e,
2076                    FunctionArg::Named { value, .. } => value,
2077                });
2078                let (c, t, f) = (it.next().unwrap(), it.next().unwrap(), it.next().unwrap());
2079                return Ok(Expr::Case {
2080                    operand: None,
2081                    branches: vec![(c, t)],
2082                    else_: Some(Box::new(f)),
2083                });
2084            }
2085            _ => {}
2086        }
2087    }
2088    if rules().name == "sqlite" {
2089        match name.as_str() {
2090            "ifnull" => name = "coalesce".to_string(),
2091            "group_concat" => {
2092                name = "string_agg".to_string();
2093                if out.len() == 1 {
2094                    out.push(FunctionArg::Expr(Expr::Literal(Literal::String(
2095                        ",".into(),
2096                    ))));
2097                }
2098            }
2099            _ => {}
2100        }
2101    }
2102    Ok(Expr::Function(Function {
2103        name,
2104        args: out,
2105        distinct,
2106        star,
2107        filter,
2108        over,
2109        order_by: agg_order,
2110    }))
2111}
2112
2113/// `INTERVAL '3 days'` / `INTERVAL 3 DAY` as `make_interval(days => 3)`. Only a single `<number> <unit>`
2114/// is represented; compound intervals (`'1 day 2 hours'`), ranges (`DAY TO SECOND`) and unit-less
2115/// strings are not in the IR. Months and years are read (and then refused by the targets, whose
2116/// month arithmetic differs), not guessed.
2117fn interval_call(iv: sp::Interval) -> R<Expr> {
2118    let sp::Interval {
2119        value,
2120        leading_field,
2121        leading_precision,
2122        last_field,
2123        fractional_seconds_precision,
2124    } = iv;
2125    if leading_precision.is_some() || last_field.is_some() || fractional_seconds_precision.is_some()
2126    {
2127        return no(
2128            "interval",
2129            "interval ranges and precisions are not in the IR",
2130        );
2131    }
2132    let (amount, unit) = match (*value, leading_field) {
2133        // MySQL `INTERVAL 3 DAY`
2134        (sp::Expr::Value(v), Some(field)) => (
2135            match v.value {
2136                sp::Value::Number(n, _) => n,
2137                other => return no("interval", &head(&other)),
2138            },
2139            field.to_string(),
2140        ),
2141        // PostgreSQL / standard `INTERVAL '3 days'`
2142        (sp::Expr::Value(v), None) => match v.value {
2143            sp::Value::SingleQuotedString(s) => {
2144                let mut it = s.split_whitespace();
2145                match (it.next(), it.next(), it.next()) {
2146                    (Some(a), Some(u), None) => (a.to_string(), u.to_string()),
2147                    _ => {
2148                        return no(
2149                            "interval",
2150                            "only a single `<number> <unit>` interval is in the IR",
2151                        );
2152                    }
2153                }
2154            }
2155            other => return no("interval", &head(&other)),
2156        },
2157        (other, _) => return no("interval", &head(&other)),
2158    };
2159    let numeric = !amount.is_empty()
2160        && amount
2161            .trim_start_matches('-')
2162            .chars()
2163            .all(|c| c.is_ascii_digit() || c == '.')
2164        && amount
2165            .trim_start_matches('-')
2166            .chars()
2167            .any(|c| c.is_ascii_digit());
2168    if !numeric {
2169        return no("interval", "the interval amount is not a plain number");
2170    }
2171    let unit = match unit.to_ascii_lowercase().trim_end_matches('s') {
2172        "second" | "sec" => "secs",
2173        "minute" | "min" => "mins",
2174        "hour" => "hours",
2175        "day" => "days",
2176        "week" => "weeks",
2177        "month" | "mon" => "months",
2178        "year" => "years",
2179        other => return no("interval", &format!("unit `{other}` is not in the IR")),
2180    };
2181    Ok(Expr::Function(Function {
2182        name: "make_interval".to_string(),
2183        args: vec![FunctionArg::Named {
2184            name: unit.to_string(),
2185            value: Expr::Literal(Literal::Number(amount)),
2186        }],
2187        distinct: false,
2188        star: false,
2189        filter: None,
2190        over: None,
2191        order_by: vec![],
2192    }))
2193}
2194
2195fn window_spec(w: sp::WindowSpec) -> R<Window> {
2196    let sp::WindowSpec {
2197        window_name,
2198        partition_by,
2199        order_by,
2200        window_frame,
2201    } = w;
2202    if window_name.is_some() {
2203        return no("named_window", "OVER (w ..) refinement of a named window");
2204    }
2205    let frame = match window_frame {
2206        None => None,
2207        Some(sp::WindowFrame {
2208            units,
2209            start_bound,
2210            end_bound,
2211        }) => {
2212            let bound = |b: sp::WindowFrameBound| -> R<FrameBound> {
2213                Ok(match b {
2214                    sp::WindowFrameBound::CurrentRow => FrameBound::CurrentRow,
2215                    sp::WindowFrameBound::Preceding(e) => {
2216                        FrameBound::Preceding(e.map(|x| expr(*x).map(Box::new)).transpose()?)
2217                    }
2218                    sp::WindowFrameBound::Following(e) => {
2219                        FrameBound::Following(e.map(|x| expr(*x).map(Box::new)).transpose()?)
2220                    }
2221                })
2222            };
2223            Some(Frame {
2224                units: match units {
2225                    sp::WindowFrameUnits::Rows => FrameUnits::Rows,
2226                    sp::WindowFrameUnits::Range => FrameUnits::Range,
2227                    sp::WindowFrameUnits::Groups => FrameUnits::Groups,
2228                },
2229                start: bound(start_bound)?,
2230                end: end_bound.map(bound).transpose()?,
2231            })
2232        }
2233    };
2234    Ok(Window {
2235        partition_by: partition_by.into_iter().map(expr).collect::<R<_>>()?,
2236        order_by: order_by.into_iter().map(order_item).collect::<R<_>>()?,
2237        frame,
2238    })
2239}
2240
2241fn data_type_to_ir(t: &sp::DataType) -> R<SqlType> {
2242    use sp::DataType as D;
2243    Ok(match t {
2244        D::SmallInt(_) | D::Int2(_) => SqlType::SmallInt,
2245        D::Int(_) | D::Integer(_) | D::Int4(_) => SqlType::Integer,
2246        D::BigInt(_) | D::Int8(_) => SqlType::BigInt,
2247        D::Real | D::Float4 => SqlType::Real,
2248        D::Double(_) | D::DoublePrecision | D::Float8 => SqlType::Double,
2249        D::Numeric(info) | D::Decimal(info) => match info {
2250            sp::ExactNumberInfo::None => SqlType::Numeric {
2251                precision: None,
2252                scale: None,
2253            },
2254            sp::ExactNumberInfo::Precision(p) => SqlType::Numeric {
2255                precision: Some(*p as u32),
2256                scale: None,
2257            },
2258            sp::ExactNumberInfo::PrecisionAndScale(p, s) => SqlType::Numeric {
2259                precision: Some(*p as u32),
2260                scale: Some(*s as u32),
2261            },
2262        },
2263        D::Text => SqlType::Text,
2264        D::Signed | D::SignedInteger | D::Unsigned | D::UnsignedInteger => SqlType::BigInt,
2265        D::Char(None) | D::Character(None) => SqlType::Text,
2266        D::Datetime(None) => SqlType::Timestamp { with_tz: false },
2267        D::Varchar(None) | D::CharVarying(None) => SqlType::Varchar(None),
2268        D::Varchar(Some(sp::CharacterLength::IntegerLength { length, unit: None }))
2269        | D::CharVarying(Some(sp::CharacterLength::IntegerLength { length, unit: None })) => {
2270            SqlType::Varchar(Some(*length as u32))
2271        }
2272        D::Boolean | D::Bool => SqlType::Boolean,
2273        D::Date => SqlType::Date,
2274        D::Timestamp(None, tz) => SqlType::Timestamp {
2275            with_tz: match tz {
2276                sp::TimezoneInfo::None | sp::TimezoneInfo::WithoutTimeZone => false,
2277                sp::TimezoneInfo::WithTimeZone | sp::TimezoneInfo::Tz => true,
2278            },
2279        },
2280        D::Uuid => SqlType::Uuid,
2281        D::Bytea => SqlType::Bytes,
2282        D::JSON => SqlType::Json,
2283        D::JSONB => SqlType::Jsonb,
2284        other => return no("data_type", &format!("{other}")),
2285    })
2286}