1use 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
17pub struct Rules {
19 pub name: &'static str,
20 pub dialect: fn() -> Box<dyn Dialect>,
21 pub fold_quoted: bool,
23 pub nulls_smallest: bool,
25 pub question_placeholders: bool,
27 pub like_ci_default: bool,
29 pub like_default_escape: bool,
31 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
133pub 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 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
182fn 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#[derive(Clone, Debug, Default)]
226pub struct SchemaRead {
227 pub schema: Schema,
228 pub skipped: Vec<String>,
231}
232
233fn 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
288pub fn read_schema(ddl: &str, rules: &'static Rules) -> R<SchemaRead> {
292 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 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
456fn 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
466fn 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 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
537fn 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
569fn 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 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 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 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 mut group_by_rollup = false;
866 let group_by = match group_by {
867 sp::GroupByExpr::Expressions(es, mods) => {
868 match mods.as_slice() {
869 [] => {}
870 [sp::GroupByWithModifier::Rollup] if !es.is_empty() => group_by_rollup = true,
871 _ => return no("group_by_modifier", "CUBE/TOTALS/GROUPING SETS modifiers"),
872 }
873 es.into_iter().map(expr).collect::<R<Vec<_>>>()?
874 }
875 sp::GroupByExpr::All(_) => return no("group_by_all", "GROUP BY ALL"),
876 };
877 let mut proj = Vec::new();
878 for it in projection {
879 proj.push(select_item(it)?);
880 }
881 let mut from_refs = Vec::new();
882 for t in from {
883 from_refs.push(table_with_joins(t)?);
884 }
885 Ok(Select {
886 distinct,
887 projection: proj,
888 from: from_refs,
889 where_: selection.map(expr).transpose()?,
890 group_by,
891 group_by_rollup,
892 having: having.map(expr).transpose()?,
893 lock: None,
894 })
895}
896
897fn wildcard_plain(o: &sp::WildcardAdditionalOptions) -> R<()> {
898 let sp::WildcardAdditionalOptions {
899 wildcard_token: _,
900 opt_ilike,
901 opt_exclude,
902 opt_except,
903 opt_replace,
904 opt_rename,
905 opt_alias,
906 } = o;
907 if opt_ilike.is_some()
908 || opt_exclude.is_some()
909 || opt_except.is_some()
910 || opt_replace.is_some()
911 || opt_rename.is_some()
912 || opt_alias.is_some()
913 {
914 return no("wildcard_option", "EXCLUDE/EXCEPT/REPLACE/RENAME on *");
915 }
916 Ok(())
917}
918
919fn select_item(it: sp::SelectItem) -> R<SelectItem> {
920 match it {
921 sp::SelectItem::UnnamedExpr(e) => Ok(SelectItem::Expr {
922 expr: expr(e)?,
923 alias: None,
924 }),
925 sp::SelectItem::ExprWithAlias { expr: e, alias } => Ok(SelectItem::Expr {
926 expr: expr(e)?,
927 alias: Some(ident(&alias)),
928 }),
929 sp::SelectItem::Wildcard(o) => {
930 wildcard_plain(&o)?;
931 Ok(SelectItem::Wildcard)
932 }
933 sp::SelectItem::QualifiedWildcard(kind, o) => {
934 wildcard_plain(&o)?;
935 match kind {
936 sp::SelectItemQualifiedWildcardKind::ObjectName(n) => {
937 Ok(SelectItem::QualifiedWildcard(object_name(&n)?))
938 }
939 other => no("qualified_wildcard", &head(&other)),
940 }
941 }
942 other => no("select_item", &head(&other)),
943 }
944}
945
946fn alias_name(a: Option<sp::TableAlias>) -> R<Option<String>> {
947 match a {
948 None => Ok(None),
949 Some(sp::TableAlias {
950 explicit: _,
951 name,
952 columns,
953 at,
954 }) => {
955 if !columns.is_empty() || at.is_some() {
956 return no("table_alias_columns", "column list on a table alias");
957 }
958 Ok(Some(ident(&name)))
959 }
960 }
961}
962
963fn table_factor(t: sp::TableFactor) -> R<TableRef> {
964 match t {
965 sp::TableFactor::Table {
966 name,
967 alias,
968 args,
969 with_hints,
970 version,
971 with_ordinality,
972 partitions,
973 json_path,
974 sample,
975 index_hints,
976 } => {
977 if let Some(targs) = args {
979 let plain = with_hints.is_empty()
980 && version.is_none()
981 && !with_ordinality
982 && partitions.is_empty()
983 && json_path.is_none()
984 && sample.is_none()
985 && index_hints.is_empty()
986 && targs.settings.is_none();
987 let nm = object_name(&name)?;
988 if plain && nm.0.len() == 1 {
989 let mut out = Vec::new();
990 for a in targs.args {
991 match a {
992 sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Expr(e)) => {
993 out.push(expr(e)?)
994 }
995 _ => {
996 return no(
997 "table_function_arg",
998 "named or wildcard argument of a table function",
999 );
1000 }
1001 }
1002 }
1003 return Ok(TableRef::Function {
1004 name: nm.0[0].clone(),
1005 args: out,
1006 alias: alias_name(alias)?,
1007 });
1008 }
1009 return no(
1010 "table_option",
1011 "table function args/hints/version/sample/partitions",
1012 );
1013 }
1014 if !with_hints.is_empty()
1015 || version.is_some()
1016 || with_ordinality
1017 || !partitions.is_empty()
1018 || json_path.is_some()
1019 || sample.is_some()
1020 || !index_hints.is_empty()
1021 {
1022 return no(
1023 "table_option",
1024 "table function args/hints/version/sample/partitions",
1025 );
1026 }
1027 Ok(TableRef::Table {
1028 name: object_name(&name)?,
1029 alias: alias_name(alias)?,
1030 })
1031 }
1032 sp::TableFactor::Derived {
1033 lateral,
1034 subquery,
1035 alias,
1036 sample,
1037 } => {
1038 if lateral || sample.is_some() {
1039 return no("derived_option", "LATERAL / TABLESAMPLE");
1040 }
1041 let alias = alias_name(alias)?.ok_or_else(|| ReadError::NotInIr {
1042 construct: "unaliased_subquery".into(),
1043 detail: "PostgreSQL requires an alias on a FROM subquery".into(),
1044 })?;
1045 Ok(TableRef::Subquery {
1046 query: Box::new(query(*subquery)?),
1047 alias,
1048 })
1049 }
1050 other => no("table_factor", &head(&other)),
1051 }
1052}
1053
1054fn table_with_joins(t: sp::TableWithJoins) -> R<TableRef> {
1055 let sp::TableWithJoins { relation, joins } = t;
1056 let mut cur = table_factor(relation)?;
1057 for j in joins {
1058 let sp::Join {
1059 relation,
1060 global,
1061 join_operator,
1062 } = j;
1063 if global {
1064 return no("global_join", "GLOBAL JOIN");
1065 }
1066 let (kind, constraint) = match join_operator {
1067 sp::JoinOperator::Join(c) | sp::JoinOperator::Inner(c) => (JoinKind::Inner, c),
1068 sp::JoinOperator::Left(c) | sp::JoinOperator::LeftOuter(c) => (JoinKind::Left, c),
1069 sp::JoinOperator::Right(c) | sp::JoinOperator::RightOuter(c) => (JoinKind::Right, c),
1070 sp::JoinOperator::FullOuter(c) => (JoinKind::Full, c),
1071 sp::JoinOperator::CrossJoin(c) => (JoinKind::Cross, c),
1072 other => return no("join_kind", &head(&other)),
1073 };
1074 let (on, using, natural) = match constraint {
1075 sp::JoinConstraint::On(e) => (Some(expr(e)?), Vec::new(), false),
1076 sp::JoinConstraint::None => (None, Vec::new(), false),
1077 sp::JoinConstraint::Using(cols) => (
1078 None,
1079 cols.iter().map(single_name).collect::<R<Vec<_>>>()?,
1080 false,
1081 ),
1082 sp::JoinConstraint::Natural => (None, Vec::new(), true),
1083 };
1084 if natural && kind == JoinKind::Cross {
1085 return no("natural_join", "NATURAL CROSS JOIN");
1086 }
1087 cur = TableRef::Join {
1088 left: Box::new(cur),
1089 right: Box::new(table_factor(relation)?),
1090 kind,
1091 on,
1092 using,
1093 natural,
1094 };
1095 }
1096 Ok(cur)
1097}
1098
1099fn simple_table(t: sp::TableWithJoins) -> R<(Name, Option<String>)> {
1100 let sp::TableWithJoins { relation, joins } = t;
1101 if !joins.is_empty() {
1102 return no("dml_target_join", "joins in a DML target");
1103 }
1104 match table_factor(relation)? {
1105 TableRef::Table { name, alias } => Ok((name, alias)),
1106 _ => no("dml_target", "DML target is not a plain table"),
1107 }
1108}
1109
1110fn returning(r: Option<Vec<sp::SelectItem>>) -> R<Vec<SelectItem>> {
1111 r.unwrap_or_default().into_iter().map(select_item).collect()
1112}
1113
1114fn assignments(a: Vec<sp::Assignment>) -> R<Vec<Assignment>> {
1115 let mut out = Vec::new();
1116 for sp::Assignment { target, value } in a {
1117 let column = match target {
1118 sp::AssignmentTarget::ColumnName(n) => single_name(&n)?,
1119 sp::AssignmentTarget::Tuple(_) => return no("tuple_assignment", "SET (a, b) = ..."),
1120 };
1121 out.push(Assignment {
1122 column,
1123 value: expr(value)?,
1124 });
1125 }
1126 Ok(out)
1127}
1128
1129fn insert(i: sp::Insert) -> R<Statement> {
1130 let sp::Insert {
1131 insert_token: _,
1132 optimizer_hints,
1133 or,
1134 ignore,
1135 into: _,
1136 table,
1137 table_alias,
1138 columns,
1139 overwrite,
1140 source,
1141 assignments: asg,
1142 partitioned,
1143 after_columns,
1144 has_table_keyword: _,
1145 on,
1146 returning: ret,
1147 output,
1148 replace_into,
1149 priority,
1150 insert_alias,
1151 settings,
1152 format_clause,
1153 multi_table_insert_type,
1154 multi_table_into_clauses,
1155 multi_table_when_clauses,
1156 multi_table_else_clause,
1157 } = i;
1158 if !optimizer_hints.is_empty()
1159 || or.is_some()
1160 || table_alias.is_some()
1161 || overwrite
1162 || (!asg.is_empty() && (!columns.is_empty() || source.is_some()))
1163 || partitioned.is_some()
1164 || !after_columns.is_empty()
1165 || output.is_some()
1166 || priority.is_some()
1167 || insert_alias.is_some()
1168 || settings.is_some()
1169 || format_clause.is_some()
1170 || multi_table_insert_type.is_some()
1171 || !multi_table_into_clauses.is_empty()
1172 || !multi_table_when_clauses.is_empty()
1173 || multi_table_else_clause.is_some()
1174 {
1175 return no(
1176 "insert_option",
1177 "an INSERT form other than INSERT INTO t [(cols)] VALUES|query",
1178 );
1179 }
1180 let table = match table {
1181 sp::TableObject::TableName(n) => object_name(&n)?,
1182 other => return no("insert_target", &head(&other)),
1183 };
1184 let (columns, set_source) = if asg.is_empty() {
1186 (
1187 columns.iter().map(single_name).collect::<R<Vec<_>>>()?,
1188 None,
1189 )
1190 } else {
1191 let set = assignments(asg)?;
1192 let (cols, vals): (Vec<_>, Vec<_>) = set.into_iter().map(|a| (a.column, a.value)).unzip();
1193 (cols, Some(InsertSource::Values(vec![vals])))
1194 };
1195 let source = match source {
1196 None if set_source.is_some() => set_source.unwrap_or(InsertSource::DefaultValues),
1197 None => InsertSource::DefaultValues,
1198 Some(q) => {
1199 let q = *q;
1200 match *q.body {
1201 sp::SetExpr::Values(v)
1202 if q.with.is_none()
1203 && q.order_by.is_none()
1204 && q.limit_clause.is_none()
1205 && q.locks.is_empty() =>
1206 {
1207 let sp::Values {
1208 explicit_row,
1209 value_keyword: _,
1210 rows,
1211 } = v;
1212 if explicit_row {
1213 return no("explicit_row", "ROW(..) in VALUES");
1214 }
1215 let mut out = Vec::new();
1216 for r in rows {
1217 out.push(r.content.into_iter().map(expr).collect::<R<Vec<_>>>()?);
1218 }
1219 InsertSource::Values(out)
1220 }
1221 body => {
1222 let q2 = sp::Query {
1223 body: Box::new(body),
1224 ..q
1225 };
1226 InsertSource::Query(Box::new(query(q2)?))
1227 }
1228 }
1229 }
1230 };
1231 let on_conflict = match on {
1232 None => None,
1233 Some(sp::OnInsert::OnConflict(oc)) => {
1234 let sp::OnConflict {
1235 conflict_target,
1236 action,
1237 } = oc;
1238 let target = match conflict_target {
1239 None => Vec::new(),
1240 Some(sp::ConflictTarget::Columns(cols)) => cols.iter().map(ident).collect(),
1241 Some(sp::ConflictTarget::OnConstraint(_)) => {
1242 return no("on_conflict_constraint", "ON CONFLICT ON CONSTRAINT");
1243 }
1244 };
1245 let action = match action {
1246 sp::OnConflictAction::DoNothing => ConflictAction::DoNothing,
1247 sp::OnConflictAction::DoUpdate(sp::DoUpdate {
1248 assignments: a,
1249 selection,
1250 }) => ConflictAction::DoUpdate {
1251 set: assignments(a)?,
1252 where_: selection.map(expr).transpose()?,
1253 },
1254 };
1255 Some(OnConflict { target, action })
1256 }
1257 Some(sp::OnInsert::DuplicateKeyUpdate(a)) => {
1258 let set = assignments(a)?
1260 .into_iter()
1261 .map(|asg| Assignment {
1262 column: asg.column,
1263 value: excluded_refs(asg.value),
1264 })
1265 .collect();
1266 Some(OnConflict {
1267 target: vec![],
1268 action: ConflictAction::DoUpdate { set, where_: None },
1269 })
1270 }
1271 Some(other) => return no("on_insert", &head(&other)),
1272 };
1273 let on_conflict = if ignore {
1276 if on_conflict.is_some() {
1277 return no(
1278 "insert_option",
1279 "IGNORE together with ON DUPLICATE KEY UPDATE",
1280 );
1281 }
1282 add_note(
1283 "insert_ignore",
1284 "INSERT IGNORE downgrades every error of the statement to a warning; ON CONFLICT DO NOTHING \
1285 skips unique-key conflicts only",
1286 Allowance::IgnoreCoversOnlyUniqueConflicts,
1287 );
1288 Some(OnConflict {
1289 target: vec![],
1290 action: ConflictAction::DoNothing,
1291 })
1292 } else {
1293 on_conflict
1294 };
1295 Ok(Statement::Insert(Insert {
1296 table,
1297 replace: replace_into,
1298 columns,
1299 source,
1300 on_conflict,
1301 returning: returning(ret)?,
1302 }))
1303}
1304
1305fn update(u: sp::Update) -> R<Statement> {
1306 let sp::Update {
1307 update_token: _,
1308 optimizer_hints,
1309 table,
1310 assignments: asg,
1311 from,
1312 selection,
1313 returning: ret,
1314 output,
1315 or,
1316 order_by,
1317 limit,
1318 } = u;
1319 if !optimizer_hints.is_empty()
1320 || output.is_some()
1321 || or.is_some()
1322 || !order_by.is_empty()
1323 || limit.is_some()
1324 {
1325 return no(
1326 "update_option",
1327 "UPDATE with hints/OUTPUT/OR/ORDER BY/LIMIT",
1328 );
1329 }
1330 let (table, alias) = simple_table(table)?;
1331 if alias.is_some()
1334 && table.0.len() == 1
1335 && matches!(table.0[0].as_str(), "low_priority" | "ignore")
1336 {
1337 return no("update_option", "UPDATE LOW_PRIORITY / IGNORE");
1338 }
1339 let from = match from {
1340 None => Vec::new(),
1341 Some(sp::UpdateTableFromKind::AfterSet(ts)) => ts
1342 .into_iter()
1343 .map(table_with_joins)
1344 .collect::<R<Vec<_>>>()?,
1345 Some(other) => return no("update_from_position", &head(&other)),
1346 };
1347 Ok(Statement::Update(Update {
1348 table,
1349 alias,
1350 set: assignments(asg)?,
1351 from,
1352 where_: selection.map(expr).transpose()?,
1353 returning: returning(ret)?,
1354 }))
1355}
1356
1357fn delete(d: sp::Delete) -> R<Statement> {
1358 let sp::Delete {
1359 delete_token: _,
1360 optimizer_hints,
1361 tables,
1362 from,
1363 using,
1364 selection,
1365 returning: ret,
1366 output,
1367 order_by,
1368 limit,
1369 } = d;
1370 if !optimizer_hints.is_empty()
1371 || !tables.is_empty()
1372 || output.is_some()
1373 || !order_by.is_empty()
1374 || limit.is_some()
1375 {
1376 return no(
1377 "delete_option",
1378 "DELETE with hints/multi-table/OUTPUT/ORDER BY/LIMIT",
1379 );
1380 }
1381 let ts = match from {
1382 sp::FromTable::WithFromKeyword(ts) | sp::FromTable::WithoutKeyword(ts) => ts,
1383 };
1384 if ts.len() != 1 {
1385 return no("delete_multi_target", "DELETE FROM a, b");
1386 }
1387 let (table, alias) = simple_table(ts.into_iter().next().unwrap())?;
1388 let using = using
1389 .unwrap_or_default()
1390 .into_iter()
1391 .map(table_with_joins)
1392 .collect::<R<Vec<_>>>()?;
1393 Ok(Statement::Delete(Delete {
1394 table,
1395 alias,
1396 using,
1397 where_: selection.map(expr).transpose()?,
1398 returning: returning(ret)?,
1399 }))
1400}
1401
1402fn boxed(e: sp::Expr) -> R<Box<Expr>> {
1403 Ok(Box::new(expr(e)?))
1404}
1405
1406fn ceil_floor(name: &str, x: sp::Expr, field: sp::CeilFloorKind) -> R<Expr> {
1407 if !matches!(
1408 field,
1409 sp::CeilFloorKind::DateTimeField(sp::DateTimeField::NoDateTime)
1410 ) {
1411 return no("ceil_form", "CEIL/FLOOR(x TO unit) and the scale form");
1412 }
1413 Ok(Expr::Function(Function {
1414 name: name.to_string(),
1415 args: vec![FunctionArg::Expr(expr(x)?)],
1416 distinct: false,
1417 star: false,
1418 filter: None,
1419 over: None,
1420 order_by: vec![],
1421 }))
1422}
1423
1424fn is_bool(x: sp::Expr, value: bool, negated: bool) -> R<Expr> {
1425 Ok(Expr::IsBool {
1426 expr: boxed(x)?,
1427 value,
1428 negated,
1429 })
1430}
1431
1432fn expr(e: sp::Expr) -> R<Expr> {
1433 use sp::Expr as E;
1434 Ok(match e {
1435 E::Identifier(i) if i.quote_style.is_none() && i.value.eq_ignore_ascii_case("default") => {
1438 return no("default_value", "DEFAULT as a value is not in the IR");
1439 }
1440 E::Identifier(i) => Expr::Column(Name::simple(ident(&i))),
1441 E::CompoundIdentifier(parts) => Expr::Column(Name(parts.iter().map(ident).collect())),
1442 E::Value(v) => value(v.value)?,
1443 E::Nested(inner) => Expr::Nested(boxed(*inner)?),
1444 E::IsNull(x) => Expr::IsNull {
1445 expr: boxed(*x)?,
1446 negated: false,
1447 },
1448 E::IsNotNull(x) => Expr::IsNull {
1449 expr: boxed(*x)?,
1450 negated: true,
1451 },
1452 E::IsTrue(x) => is_bool(*x, true, false)?,
1453 E::IsNotTrue(x) => is_bool(*x, true, true)?,
1454 E::IsFalse(x) => is_bool(*x, false, false)?,
1455 E::IsNotFalse(x) => is_bool(*x, false, true)?,
1456 E::InList {
1457 expr: x,
1458 list,
1459 negated,
1460 } => Expr::InList {
1461 expr: boxed(*x)?,
1462 list: list.into_iter().map(expr).collect::<R<_>>()?,
1463 negated,
1464 },
1465 E::InSubquery {
1466 expr: x,
1467 subquery,
1468 negated,
1469 } => Expr::InSubquery {
1470 expr: boxed(*x)?,
1471 query: Box::new(query(*subquery)?),
1472 negated,
1473 },
1474 E::Between {
1475 expr: x,
1476 negated,
1477 low,
1478 high,
1479 } => Expr::Between {
1480 expr: boxed(*x)?,
1481 low: boxed(*low)?,
1482 high: boxed(*high)?,
1483 negated,
1484 },
1485 E::Like {
1486 negated,
1487 any,
1488 expr: x,
1489 pattern,
1490 escape_char,
1491 } => {
1492 if any {
1493 return no("like_option", "LIKE ANY");
1494 }
1495 let ci = rules().like_ci_default;
1496 if ci {
1497 add_note(
1498 "like",
1499 "the source LIKE is ASCII case-insensitive only while its connection setting is at the default",
1500 Allowance::LikeCaseSensitivityIsConnectionSetting,
1501 );
1502 }
1503 if rules().name == "mysql" {
1504 add_note(
1505 "like",
1506 "the source LIKE follows the column collation; read as case-sensitive (a binary collation)",
1507 Allowance::LikeCaseSensitivityIsConnectionSetting,
1508 );
1509 }
1510 like_expr(*x, *pattern, escape_char, negated, ci)?
1511 }
1512 E::RLike {
1513 negated,
1514 expr: x,
1515 pattern,
1516 ..
1517 } => Expr::Regexp {
1518 expr: boxed(*x)?,
1519 pattern: boxed(*pattern)?,
1520 negated,
1521 },
1522 E::ILike {
1523 negated,
1524 any,
1525 expr: x,
1526 pattern,
1527 escape_char,
1528 } => {
1529 if any {
1530 return no("like_option", "ILIKE ANY");
1531 }
1532 like_expr(*x, *pattern, escape_char, negated, true)?
1533 }
1534 E::UnaryOp { op, expr: x } => {
1535 let op = match op {
1536 sp::UnaryOperator::Not => UnaryOp::Not,
1537 sp::UnaryOperator::Minus => UnaryOp::Minus,
1538 sp::UnaryOperator::Plus => UnaryOp::Plus,
1539 sp::UnaryOperator::BitwiseNot => {
1541 return no(
1542 "bitwise_not",
1543 "`~x` differs in width and signedness per engine",
1544 );
1545 }
1546 other => return no("unary_operator", &head(&other)),
1547 };
1548 Expr::Unary {
1549 op,
1550 expr: boxed(*x)?,
1551 }
1552 }
1553 E::BinaryOp { left, op, right }
1554 if matches!(
1555 op,
1556 sp::BinaryOperator::PGRegexMatch | sp::BinaryOperator::PGRegexNotMatch
1557 ) =>
1558 {
1559 Expr::Regexp {
1560 expr: boxed(*left)?,
1561 pattern: boxed(*right)?,
1562 negated: matches!(op, sp::BinaryOperator::PGRegexNotMatch),
1563 }
1564 }
1565 E::BinaryOp { left, op, right } => {
1566 use sp::BinaryOperator as B;
1567 let op = match op {
1568 B::Eq => BinaryOp::Eq,
1569 B::NotEq => BinaryOp::NotEq,
1570 B::Lt => BinaryOp::Lt,
1571 B::LtEq => BinaryOp::LtEq,
1572 B::Gt => BinaryOp::Gt,
1573 B::GtEq => BinaryOp::GtEq,
1574 B::And => BinaryOp::And,
1575 B::Or => BinaryOp::Or,
1576 B::Plus => BinaryOp::Plus,
1577 B::Minus => BinaryOp::Minus,
1578 B::Multiply => BinaryOp::Multiply,
1579 B::Divide => BinaryOp::Divide,
1580 B::Modulo => BinaryOp::Modulo,
1581 B::StringConcat if rules().name == "mysql" => {
1585 return no(
1586 "pipes_operator",
1587 "MySQL `||` is logical OR (default sql_mode) but the parser gives it concatenation precedence; write OR, or CONCAT()",
1588 );
1589 }
1590 B::StringConcat => BinaryOp::Concat,
1591 B::MyIntegerDivide => BinaryOp::IntDivide,
1592 B::Spaceship => BinaryOp::NullSafeEq,
1593 B::BitwiseAnd => BinaryOp::BitAnd,
1594 B::BitwiseOr => BinaryOp::BitOr,
1595 B::BitwiseXor | B::PGBitwiseXor => BinaryOp::BitXor,
1596 B::PGBitwiseShiftLeft => BinaryOp::ShiftLeft,
1597 B::PGBitwiseShiftRight => BinaryOp::ShiftRight,
1598 B::Xor => BinaryOp::Xor,
1599 B::Arrow => BinaryOp::JsonGet,
1600 B::LongArrow => BinaryOp::JsonGetText,
1601 other => {
1602 return no(
1603 "binary_operator",
1604 &format!(
1605 "{} (JSON/array/regex/bitwise operators are not in the IR)",
1606 head(&other)
1607 ),
1608 );
1609 }
1610 };
1611 let is_hex = |e: &E| matches!(e, E::Value(v) if matches!(v.value, sp::Value::HexStringLiteral(_)));
1612 if (is_hex(&left) || is_hex(&right))
1613 && !matches!(
1614 op,
1615 BinaryOp::Eq
1616 | BinaryOp::NotEq
1617 | BinaryOp::Lt
1618 | BinaryOp::LtEq
1619 | BinaryOp::Gt
1620 | BinaryOp::GtEq
1621 | BinaryOp::NullSafeEq
1622 | BinaryOp::And
1623 | BinaryOp::Or
1624 | BinaryOp::Xor
1625 )
1626 {
1627 return no(
1628 "hex_literal_numeric",
1629 "a hex literal is a byte string; MySQL `0x41 + 1` reads it as the number 65, so arithmetic on it is not mapped",
1630 );
1631 }
1632 if op == BinaryOp::Divide && rules().name == "mysql" {
1633 add_note(
1634 "division",
1635 "the source `/` is exact (DECIMAL) division; the target divides as double precision",
1636 Allowance::DecimalDivisionAsFloat,
1637 );
1638 let l = Expr::Cast {
1639 expr: boxed(*left)?,
1640 ty: SqlType::Double,
1641 };
1642 return Ok(Expr::Binary {
1643 op,
1644 left: Box::new(l),
1645 right: boxed(*right)?,
1646 });
1647 }
1648 match (op, *left, *right) {
1652 (BinaryOp::Plus | BinaryOp::Minus, l, E::Interval(iv)) => Expr::Binary {
1653 op,
1654 left: boxed(l)?,
1655 right: Box::new(interval_call(iv)?),
1656 },
1657 (BinaryOp::Plus, E::Interval(iv), r) => Expr::Binary {
1658 op,
1659 left: boxed(r)?,
1660 right: Box::new(interval_call(iv)?),
1661 },
1662 (op, l, r) => Expr::Binary {
1663 op,
1664 left: boxed(l)?,
1665 right: boxed(r)?,
1666 },
1667 }
1668 }
1669 E::Case {
1670 case_token: _,
1671 end_token: _,
1672 operand,
1673 conditions,
1674 else_result,
1675 } => Expr::Case {
1676 operand: operand.map(|o| boxed(*o)).transpose()?,
1677 branches: conditions
1678 .into_iter()
1679 .map(|sp::CaseWhen { condition, result }| Ok((expr(condition)?, expr(result)?)))
1680 .collect::<R<_>>()?,
1681 else_: else_result.map(|o| boxed(*o)).transpose()?,
1682 },
1683 E::Cast {
1684 kind,
1685 expr: x,
1686 data_type,
1687 format,
1688 } => {
1689 if format.is_some() || !matches!(kind, sp::CastKind::Cast | sp::CastKind::DoubleColon) {
1690 return no("cast_form", "TRY_CAST / SAFE_CAST / CAST .. FORMAT");
1691 }
1692 Expr::Cast {
1693 expr: boxed(*x)?,
1694 ty: data_type_to_ir(&data_type)?,
1695 }
1696 }
1697 E::Convert {
1700 is_try: false,
1701 expr: x,
1702 data_type: Some(data_type),
1703 charset: None,
1704 target_before_value: false,
1705 styles,
1706 } if styles.is_empty() => Expr::Cast {
1707 expr: boxed(*x)?,
1708 ty: data_type_to_ir(&data_type)?,
1709 },
1710 E::Convert { .. } => {
1711 return no(
1712 "convert_form",
1713 "CONVERT(.. USING charset), TRY_CONVERT and the target-first (MSSQL) form",
1714 );
1715 }
1716 E::Ceil { expr: x, field } => ceil_floor("ceil", *x, field)?,
1718 E::Floor { expr: x, field } => ceil_floor("floor", *x, field)?,
1719 E::Position { expr: sub, r#in } => Expr::Function(Function {
1721 name: "strpos".to_string(),
1722 args: vec![
1723 FunctionArg::Expr(expr(*r#in)?),
1724 FunctionArg::Expr(expr(*sub)?),
1725 ],
1726 distinct: false,
1727 star: false,
1728 filter: None,
1729 over: None,
1730 order_by: vec![],
1731 }),
1732 E::Trim {
1733 trim_where,
1734 trim_what,
1735 expr: x,
1736 trim_characters,
1737 } => {
1738 let side = match trim_where {
1740 None | Some(sp::TrimWhereField::Both) => TrimSide::Both,
1741 Some(sp::TrimWhereField::Leading) => TrimSide::Leading,
1742 Some(sp::TrimWhereField::Trailing) => TrimSide::Trailing,
1743 };
1744 let chars = match (trim_what, trim_characters) {
1745 (Some(w), None) => Some(boxed(*w)?),
1746 (None, None) => None,
1747 (None, Some(mut cs)) if cs.len() == 1 => Some(boxed(cs.remove(0))?),
1748 _ => return no("trim_form", "TRIM with several character arguments"),
1749 };
1750 Expr::Trim {
1751 expr: boxed(*x)?,
1752 side,
1753 chars,
1754 }
1755 }
1756 E::Substring {
1757 expr: x,
1758 substring_from,
1759 substring_for,
1760 special: _,
1761 shorthand: _,
1762 } => {
1763 if rules().name == "mysql" {
1764 let positive = |e: &E, min: u64| {
1767 matches!(
1768 e,
1769 E::Value(v) if matches!(&v.value, sp::Value::Number(n, _)
1770 if n.parse::<u64>().is_ok_and(|x| x >= min))
1771 )
1772 };
1773 let start_ok = substring_from.as_deref().is_some_and(|f| positive(f, 1));
1774 let len_ok = substring_for.as_deref().is_none_or(|l| positive(l, 0));
1775 if !(start_ok && len_ok) {
1776 add_note(
1777 "fn:substr.start_position",
1778 "MySQL SUBSTRING counts a start of 0 as empty and a negative start from the end; \
1779 the target does not",
1780 Allowance::SubstringStartAssumedPositive,
1781 );
1782 }
1783 }
1784 let mut args = vec![FunctionArg::Expr(expr(*x)?)];
1786 match (substring_from, substring_for) {
1787 (Some(f), Some(l)) => {
1788 args.push(FunctionArg::Expr(expr(*f)?));
1789 args.push(FunctionArg::Expr(expr(*l)?));
1790 }
1791 (Some(f), None) => args.push(FunctionArg::Expr(expr(*f)?)),
1792 (None, Some(l)) => {
1793 args.push(FunctionArg::Expr(Expr::Literal(Literal::Number(
1795 "1".into(),
1796 ))));
1797 args.push(FunctionArg::Expr(expr(*l)?));
1798 }
1799 (None, None) => return no("substring_form", "SUBSTRING without FROM or FOR"),
1800 }
1801 Expr::Function(Function {
1802 name: "substr".into(),
1803 args,
1804 distinct: false,
1805 star: false,
1806 filter: None,
1807 over: None,
1808 order_by: vec![],
1809 })
1810 }
1811 E::AnyOp {
1812 left,
1813 compare_op,
1814 right,
1815 is_some: _,
1816 } => {
1817 if !matches!(compare_op, sp::BinaryOperator::Eq) {
1818 return no("any_operator", "only `= ANY(..)` is in the IR");
1819 }
1820 quantified(*left, *right, false)?
1821 }
1822 E::AllOp {
1823 left,
1824 compare_op,
1825 right,
1826 } => {
1827 if !matches!(compare_op, sp::BinaryOperator::NotEq) {
1828 return no("all_operator", "only `<> ALL(..)` is in the IR");
1829 }
1830 quantified(*left, *right, true)?
1831 }
1832 E::Exists { subquery, negated } => Expr::Exists {
1833 query: Box::new(query(*subquery)?),
1834 negated,
1835 },
1836 E::Subquery(q) => Expr::Subquery(Box::new(query(*q)?)),
1837 E::Extract {
1838 field,
1839 syntax: _,
1840 expr: x,
1841 } => Expr::Extract {
1842 field: field.to_string().to_ascii_lowercase(),
1843 expr: boxed(*x)?,
1844 },
1845 E::Array(arr) => Expr::ArrayLiteral(arr.elem.into_iter().map(expr).collect::<R<Vec<_>>>()?),
1846 E::AtTimeZone {
1847 timestamp,
1848 time_zone,
1849 } => Expr::AtTimeZone {
1850 expr: boxed(*timestamp)?,
1851 zone: boxed(*time_zone)?,
1852 },
1853 E::Function(f) => function(f)?,
1854 other => return no("expression", &head(&other)),
1855 })
1856}
1857
1858fn quantified(left: sp::Expr, right: sp::Expr, negated: bool) -> R<Expr> {
1860 let lhs = boxed(left)?;
1861 let mut right = right;
1863 if let sp::Expr::Cast {
1864 kind: sp::CastKind::Cast | sp::CastKind::DoubleColon,
1865 expr: inner,
1866 data_type: sp::DataType::Array(_),
1867 format: None,
1868 } = right.clone()
1869 {
1870 right = *inner;
1871 }
1872 match right {
1873 sp::Expr::Value(v) => match v.value {
1874 sp::Value::Placeholder(_) => match value(v.value)? {
1875 Expr::Param(n) => Ok(Expr::AnyParam {
1876 expr: lhs,
1877 param: n,
1878 negated,
1879 }),
1880 _ => no("array_param", "expected a numbered parameter"),
1881 },
1882 other => no("array_operand", &head(&other)),
1883 },
1884 sp::Expr::Array(sp::Array { elem, named: _ }) => Ok(Expr::InList {
1885 expr: lhs,
1886 list: elem.into_iter().map(expr).collect::<R<Vec<_>>>()?,
1887 negated,
1888 }),
1889 sp::Expr::Subquery(q) => Ok(Expr::InSubquery {
1890 expr: lhs,
1891 query: Box::new(query(*q)?),
1892 negated,
1893 }),
1894 other => no("array_operand", &head(&other)),
1895 }
1896}
1897
1898fn excluded_refs(e: Expr) -> Expr {
1900 match e {
1901 Expr::Function(f) if f.name == "values" && f.args.len() == 1 => {
1902 match f.args.into_iter().next() {
1903 Some(FunctionArg::Expr(Expr::Column(n))) => {
1904 Expr::Column(Name(vec!["excluded".to_string(), n.last().to_string()]))
1905 }
1906 other => Expr::Function(Function {
1907 name: "values".into(),
1908 args: other.into_iter().collect(),
1909 distinct: false,
1910 star: false,
1911 filter: None,
1912 over: None,
1913 order_by: vec![],
1914 }),
1915 }
1916 }
1917 Expr::Binary { op, left, right } => Expr::Binary {
1918 op,
1919 left: Box::new(excluded_refs(*left)),
1920 right: Box::new(excluded_refs(*right)),
1921 },
1922 Expr::Nested(x) => Expr::Nested(Box::new(excluded_refs(*x))),
1923 Expr::Unary { op, expr } => Expr::Unary {
1924 op,
1925 expr: Box::new(excluded_refs(*expr)),
1926 },
1927 other => other,
1928 }
1929}
1930
1931fn like_expr(
1932 x: sp::Expr,
1933 pattern: sp::Expr,
1934 escape_char: Option<Box<sp::Expr>>,
1935 negated: bool,
1936 case_insensitive: bool,
1937) -> R<Expr> {
1938 let escape = match escape_char {
1939 Some(e) => Some(boxed(*e)?),
1940 None if rules().like_default_escape => {
1941 Some(Box::new(Expr::Literal(Literal::String("\\".into()))))
1942 }
1943 None => None,
1944 };
1945 Ok(Expr::Like {
1946 expr: boxed(x)?,
1947 pattern: boxed(pattern)?,
1948 negated,
1949 case_insensitive,
1950 escape,
1951 })
1952}
1953
1954fn value(v: sp::Value) -> R<Expr> {
1955 Ok(match v {
1956 sp::Value::Number(n, long) => {
1957 if long {
1958 return no("numeric_suffix", "L suffix");
1959 }
1960 Expr::Literal(Literal::Number(n))
1961 }
1962 sp::Value::SingleQuotedString(s) => Expr::Literal(Literal::String(s)),
1963 sp::Value::EscapedStringLiteral(s) => Expr::Literal(Literal::String(s)),
1965 sp::Value::HexStringLiteral(h) if rules().name == "postgres" => {
1967 return no(
1968 "hex_literal",
1969 &format!("X'{h}' is a bit string on PostgreSQL; write '\\x{h}'::bytea"),
1970 );
1971 }
1972 sp::Value::HexStringLiteral(h) => {
1973 if h.is_empty() || h.len() % 2 != 0 || !h.bytes().all(|c| c.is_ascii_hexdigit()) {
1974 return no(
1975 "hex_literal",
1976 &format!("`{h}` is not an even-length run of hex digits"),
1977 );
1978 }
1979 let bytes = (0..h.len())
1980 .step_by(2)
1981 .map(|i| u8::from_str_radix(&h[i..i + 2], 16))
1982 .collect::<Result<Vec<u8>, _>>()
1983 .or_else(|_| no("hex_literal", "invalid hex digits"))?;
1984 Expr::Literal(Literal::Bytes(bytes))
1985 }
1986 sp::Value::SingleQuotedByteStringLiteral(b)
1988 | sp::Value::DoubleQuotedByteStringLiteral(b) => {
1989 return no(
1990 "bit_literal",
1991 &format!("B'{b}' reads differently on each engine"),
1992 );
1993 }
1994 sp::Value::Boolean(b) if rules().name == "mysql" => {
1995 Expr::Literal(Literal::Number(if b { "1" } else { "0" }.into()))
1997 }
1998 sp::Value::Boolean(b) => Expr::Literal(Literal::Bool(b)),
1999 sp::Value::Null => Expr::Literal(Literal::Null),
2000 sp::Value::Placeholder(p) => {
2001 let bad = || ReadError::NotInIr {
2002 construct: "placeholder".into(),
2003 detail: format!(
2004 "`{p}` is not a placeholder form of dialect `{}`",
2005 rules().name
2006 ),
2007 };
2008 if rules().question_placeholders {
2009 if p == "?" {
2010 Expr::Param(bump_param(None, None))
2011 } else if let Some(d) = p.strip_prefix('?') {
2012 let n = d.parse::<u32>().ok().filter(|n| *n >= 1).ok_or_else(bad)?;
2013 Expr::Param(bump_param(Some(n), None))
2014 } else if let Some(nm) = p.strip_prefix([':', '@', '$']) {
2015 Expr::Param(bump_param(None, Some(nm)))
2016 } else {
2017 return Err(bad());
2018 }
2019 } else {
2020 let n = p
2021 .strip_prefix('$')
2022 .and_then(|d| d.parse::<u32>().ok())
2023 .filter(|n| *n >= 1)
2024 .ok_or_else(bad)?;
2025 Expr::Param(n)
2026 }
2027 }
2028 other => return no("literal", &head(&other)),
2029 })
2030}
2031
2032fn function(f: sp::Function) -> R<Expr> {
2033 let sp::Function {
2034 name,
2035 uses_odbc_syntax,
2036 parameters,
2037 args,
2038 within_group,
2039 filter,
2040 null_treatment,
2041 over,
2042 } = f;
2043 if uses_odbc_syntax
2044 || !matches!(parameters, sp::FunctionArguments::None)
2045 || !within_group.is_empty()
2046 || null_treatment.is_some()
2047 {
2048 return no(
2049 "function_option",
2050 "ODBC syntax/parameters/WITHIN GROUP/FILTER/IGNORE NULLS",
2051 );
2052 }
2053 let over = match over {
2054 None => None,
2055 Some(sp::WindowType::NamedWindow(_)) => {
2056 return no(
2057 "named_window",
2058 "OVER w (a WINDOW clause) is not in the IR yet",
2059 );
2060 }
2061 Some(sp::WindowType::WindowSpec(spec)) => Some(window_spec(spec)?),
2062 };
2063 let filter = filter.map(|f| expr(*f).map(Box::new)).transpose()?;
2064 let name = object_name(&name)?;
2065 let base = name.last().to_string();
2066 if name.0.len() != 1 {
2067 return no("qualified_function", &name.0.join("."));
2068 }
2069 let args = match args {
2070 sp::FunctionArguments::None => {
2072 if base == "current_timestamp" {
2073 if rules().name == "sqlite" {
2074 add_note(
2075 "fn:now",
2076 "the source CURRENT_TIMESTAMP is text 'YYYY-MM-DD HH:MM:SS' (UTC), not a timestamptz",
2077 Allowance::NowAsText,
2078 );
2079 }
2080 return Ok(Expr::Function(Function {
2081 name: "now".to_string(),
2082 args: vec![],
2083 distinct: false,
2084 star: false,
2085 filter: None,
2086 over: None,
2087 order_by: vec![],
2088 }));
2089 }
2090 if matches!(
2092 base.as_str(),
2093 "current_user" | "session_user" | "current_role"
2094 ) {
2095 return Ok(Expr::Function(Function {
2096 name: base,
2097 args: vec![],
2098 distinct: false,
2099 star: false,
2100 filter: None,
2101 over: None,
2102 order_by: vec![],
2103 }));
2104 }
2105 if base == "current_date" {
2108 if rules().name == "sqlite" {
2109 add_note(
2110 "fn:current_date",
2111 "the source CURRENT_DATE is text 'YYYY-MM-DD' (the UTC date), not a date",
2112 Allowance::DateAsText,
2113 );
2114 }
2115 return Ok(Expr::Function(Function {
2116 name: "current_date".to_string(),
2117 args: vec![],
2118 distinct: false,
2119 star: false,
2120 filter: None,
2121 over: None,
2122 order_by: vec![],
2123 }));
2124 }
2125 return no("bare_function", &format!("`{base}` without parentheses"));
2126 }
2127 sp::FunctionArguments::Subquery(q) if base == "array" => {
2128 return Ok(Expr::ArraySubquery(Box::new(query(*q)?)));
2129 }
2130 sp::FunctionArguments::Subquery(_) => {
2131 return no("function_subquery", "function over a subquery");
2132 }
2133 sp::FunctionArguments::List(l) => l,
2134 };
2135 let sp::FunctionArgumentList {
2136 duplicate_treatment,
2137 args,
2138 clauses,
2139 } = args;
2140 let mut agg_order = Vec::new();
2141 let mut separator: Option<String> = None;
2142 for cl in clauses {
2143 match cl {
2144 sp::FunctionArgumentClause::OrderBy(items) => {
2145 for it in items {
2146 agg_order.push(order_item(it)?);
2147 }
2148 }
2149 sp::FunctionArgumentClause::Separator(v) => match v.value {
2150 sp::Value::SingleQuotedString(s) => separator = Some(s),
2151 other => return no("separator", &head(&other)),
2152 },
2153 other => {
2154 return no(
2155 "function_clause",
2156 &format!("{} inside a function call", head(&other)),
2157 );
2158 }
2159 }
2160 }
2161 let distinct = match duplicate_treatment {
2162 None | Some(sp::DuplicateTreatment::All) => false,
2163 Some(sp::DuplicateTreatment::Distinct) => true,
2164 };
2165 if rules().name == "mysql"
2169 && !distinct
2170 && agg_order.is_empty()
2171 && matches!(
2172 base.as_str(),
2173 "date_add" | "adddate" | "date_sub" | "subdate"
2174 )
2175 && args.len() == 2
2176 && matches!(
2177 args[1],
2178 sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Expr(sp::Expr::Interval(_)))
2179 )
2180 {
2181 let op = if matches!(base.as_str(), "date_add" | "adddate") {
2182 BinaryOp::Plus
2183 } else {
2184 BinaryOp::Minus
2185 };
2186 let mut it = args.into_iter();
2187 let (Some(sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Expr(l))), Some(second)) =
2188 (it.next(), it.next())
2189 else {
2190 return no("function_argument", "first argument of a date function");
2191 };
2192 let sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Expr(sp::Expr::Interval(iv))) = second
2193 else {
2194 unreachable!("matched above")
2195 };
2196 return Ok(Expr::Binary {
2197 op,
2198 left: Box::new(expr(l)?),
2199 right: Box::new(interval_call(iv)?),
2200 });
2201 }
2202 let mut out = Vec::new();
2203 let mut star = false;
2204 for a in args {
2205 match a {
2206 sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Expr(e)) => {
2207 out.push(FunctionArg::Expr(expr(e)?))
2208 }
2209 sp::FunctionArg::Unnamed(sp::FunctionArgExpr::Wildcard) => star = true,
2210 sp::FunctionArg::Named {
2211 name,
2212 arg: sp::FunctionArgExpr::Expr(e),
2213 operator: sp::FunctionArgOperator::RightArrow,
2214 } => out.push(FunctionArg::Named {
2215 name: ident(&name),
2216 value: expr(e)?,
2217 }),
2218 sp::FunctionArg::ExprNamed {
2220 name: sp::Expr::Identifier(name),
2221 arg: sp::FunctionArgExpr::Expr(e),
2222 operator: sp::FunctionArgOperator::RightArrow,
2223 } => out.push(FunctionArg::Named {
2224 name: ident(&name),
2225 value: expr(e)?,
2226 }),
2227 other => return no("function_argument", &head(&other)),
2228 }
2229 }
2230 let mut name = base;
2231 if name == "current_timestamp" {
2232 name = "now".to_string();
2233 }
2234 if name == "ceiling" {
2236 name = "ceil".to_string();
2237 }
2238 if name == "mod" && out.len() == 2 {
2239 let mut it = out.into_iter().map(|a| match a {
2240 FunctionArg::Expr(e) => e,
2241 FunctionArg::Named { value, .. } => value,
2242 });
2243 let (l, r) = (it.next().unwrap(), it.next().unwrap());
2244 return Ok(Expr::Binary {
2245 op: BinaryOp::Modulo,
2246 left: Box::new(l),
2247 right: Box::new(r),
2248 });
2249 }
2250 if rules().name == "mysql" {
2251 match name.as_str() {
2252 "ifnull" => name = "coalesce".to_string(),
2253 "curdate" if out.is_empty() => name = "current_date".to_string(),
2254 "group_concat" => {
2255 name = "string_agg".to_string();
2256 out.push(FunctionArg::Expr(Expr::Literal(Literal::String(
2257 separator.clone().unwrap_or_else(|| ",".to_string()),
2258 ))));
2259 add_note(
2260 "fn:string_agg",
2261 "the source GROUP_CONCAT truncates silently at group_concat_max_len",
2262 Allowance::AggregateStringTruncation,
2263 );
2264 }
2265 "length" => name = "octet_length".to_string(),
2267 "locate" | "instr" if out.len() == 2 => {
2270 if name == "locate" {
2271 out.swap(0, 1);
2272 }
2273 name = "strpos".to_string();
2274 add_note(
2275 "fn:strpos",
2276 "the source LOCATE/INSTR compare by the column collation (case-insensitive unless binary)",
2277 Allowance::TextCollation,
2278 );
2279 }
2280 "concat" if out.len() >= 2 => {
2281 let mut it = out.into_iter().map(|a| match a {
2282 FunctionArg::Expr(e) => e,
2283 FunctionArg::Named { value, .. } => value,
2284 });
2285 let first = it.next().expect("two arguments");
2286 let chain = it.fold(first, |l, r| Expr::Binary {
2287 op: BinaryOp::Concat,
2288 left: Box::new(l),
2289 right: Box::new(r),
2290 });
2291 return Ok(chain);
2292 }
2293 "if" if out.len() == 3 => {
2294 let mut it = out.into_iter().map(|a| match a {
2295 FunctionArg::Expr(e) => e,
2296 FunctionArg::Named { value, .. } => value,
2297 });
2298 let (c, t, f) = (it.next().unwrap(), it.next().unwrap(), it.next().unwrap());
2299 return Ok(Expr::Case {
2300 operand: None,
2301 branches: vec![(c, t)],
2302 else_: Some(Box::new(f)),
2303 });
2304 }
2305 _ => {}
2306 }
2307 }
2308 if rules().name == "sqlite" {
2309 match name.as_str() {
2310 "ifnull" => name = "coalesce".to_string(),
2311 "instr" if out.len() == 2 => name = "strpos".to_string(),
2312 "group_concat" => {
2313 name = "string_agg".to_string();
2314 if out.len() == 1 {
2315 out.push(FunctionArg::Expr(Expr::Literal(Literal::String(
2316 ",".into(),
2317 ))));
2318 }
2319 }
2320 _ => {}
2321 }
2322 }
2323 Ok(Expr::Function(Function {
2324 name,
2325 args: out,
2326 distinct,
2327 star,
2328 filter,
2329 over,
2330 order_by: agg_order,
2331 }))
2332}
2333
2334fn interval_call(iv: sp::Interval) -> R<Expr> {
2339 let sp::Interval {
2340 value,
2341 leading_field,
2342 leading_precision,
2343 last_field,
2344 fractional_seconds_precision,
2345 } = iv;
2346 if leading_precision.is_some() || last_field.is_some() || fractional_seconds_precision.is_some()
2347 {
2348 return no(
2349 "interval",
2350 "interval ranges and precisions are not in the IR",
2351 );
2352 }
2353 let (amount, unit) = match (*value, leading_field) {
2354 (sp::Expr::Value(v), Some(field)) => (
2356 match v.value {
2357 sp::Value::Number(n, _) => n,
2358 other => return no("interval", &head(&other)),
2359 },
2360 field.to_string(),
2361 ),
2362 (sp::Expr::Value(v), None) => match v.value {
2364 sp::Value::SingleQuotedString(s) => {
2365 let mut it = s.split_whitespace();
2366 match (it.next(), it.next(), it.next()) {
2367 (Some(a), Some(u), None) => (a.to_string(), u.to_string()),
2368 _ => {
2369 return no(
2370 "interval",
2371 "only a single `<number> <unit>` interval is in the IR",
2372 );
2373 }
2374 }
2375 }
2376 other => return no("interval", &head(&other)),
2377 },
2378 (other, _) => return no("interval", &head(&other)),
2379 };
2380 let numeric = !amount.is_empty()
2381 && amount
2382 .trim_start_matches('-')
2383 .chars()
2384 .all(|c| c.is_ascii_digit() || c == '.')
2385 && amount
2386 .trim_start_matches('-')
2387 .chars()
2388 .any(|c| c.is_ascii_digit());
2389 if !numeric {
2390 return no("interval", "the interval amount is not a plain number");
2391 }
2392 let unit = match unit.to_ascii_lowercase().trim_end_matches('s') {
2393 "second" | "sec" => "secs",
2394 "minute" | "min" => "mins",
2395 "hour" => "hours",
2396 "day" => "days",
2397 "week" => "weeks",
2398 "month" | "mon" => "months",
2399 "year" => "years",
2400 other => return no("interval", &format!("unit `{other}` is not in the IR")),
2401 };
2402 Ok(Expr::Function(Function {
2403 name: "make_interval".to_string(),
2404 args: vec![FunctionArg::Named {
2405 name: unit.to_string(),
2406 value: Expr::Literal(Literal::Number(amount)),
2407 }],
2408 distinct: false,
2409 star: false,
2410 filter: None,
2411 over: None,
2412 order_by: vec![],
2413 }))
2414}
2415
2416fn window_spec(w: sp::WindowSpec) -> R<Window> {
2417 let sp::WindowSpec {
2418 window_name,
2419 partition_by,
2420 order_by,
2421 window_frame,
2422 } = w;
2423 if window_name.is_some() {
2424 return no("named_window", "OVER (w ..) refinement of a named window");
2425 }
2426 let frame = match window_frame {
2427 None => None,
2428 Some(sp::WindowFrame {
2429 units,
2430 start_bound,
2431 end_bound,
2432 }) => {
2433 let bound = |b: sp::WindowFrameBound| -> R<FrameBound> {
2434 Ok(match b {
2435 sp::WindowFrameBound::CurrentRow => FrameBound::CurrentRow,
2436 sp::WindowFrameBound::Preceding(e) => {
2437 FrameBound::Preceding(e.map(|x| expr(*x).map(Box::new)).transpose()?)
2438 }
2439 sp::WindowFrameBound::Following(e) => {
2440 FrameBound::Following(e.map(|x| expr(*x).map(Box::new)).transpose()?)
2441 }
2442 })
2443 };
2444 Some(Frame {
2445 units: match units {
2446 sp::WindowFrameUnits::Rows => FrameUnits::Rows,
2447 sp::WindowFrameUnits::Range => FrameUnits::Range,
2448 sp::WindowFrameUnits::Groups => FrameUnits::Groups,
2449 },
2450 start: bound(start_bound)?,
2451 end: end_bound.map(bound).transpose()?,
2452 })
2453 }
2454 };
2455 Ok(Window {
2456 partition_by: partition_by.into_iter().map(expr).collect::<R<_>>()?,
2457 order_by: order_by.into_iter().map(order_item).collect::<R<_>>()?,
2458 frame,
2459 })
2460}
2461
2462fn data_type_to_ir(t: &sp::DataType) -> R<SqlType> {
2463 use sp::DataType as D;
2464 Ok(match t {
2465 D::SmallInt(_) | D::Int2(_) => SqlType::SmallInt,
2466 D::Int(_) | D::Integer(_) | D::Int4(_) => SqlType::Integer,
2467 D::BigInt(_) | D::Int8(_) => SqlType::BigInt,
2468 D::Real | D::Float4 => SqlType::Real,
2469 D::Double(_) | D::DoublePrecision | D::Float8 => SqlType::Double,
2470 D::Numeric(info) | D::Decimal(info) => match info {
2471 sp::ExactNumberInfo::None => SqlType::Numeric {
2472 precision: None,
2473 scale: None,
2474 },
2475 sp::ExactNumberInfo::Precision(p) => SqlType::Numeric {
2476 precision: Some(*p as u32),
2477 scale: None,
2478 },
2479 sp::ExactNumberInfo::PrecisionAndScale(p, s) => SqlType::Numeric {
2480 precision: Some(*p as u32),
2481 scale: Some(*s as u32),
2482 },
2483 },
2484 D::Text => SqlType::Text,
2485 D::Signed | D::SignedInteger | D::Unsigned | D::UnsignedInteger => SqlType::BigInt,
2486 D::Char(None) | D::Character(None) => SqlType::Text,
2487 D::Datetime(None) => SqlType::Timestamp { with_tz: false },
2488 D::Varchar(None) | D::CharVarying(None) => SqlType::Varchar(None),
2489 D::Varchar(Some(sp::CharacterLength::IntegerLength { length, unit: None }))
2490 | D::CharVarying(Some(sp::CharacterLength::IntegerLength { length, unit: None })) => {
2491 SqlType::Varchar(Some(*length as u32))
2492 }
2493 D::Boolean | D::Bool => SqlType::Boolean,
2494 D::Date => SqlType::Date,
2495 D::Timestamp(None, tz) => SqlType::Timestamp {
2496 with_tz: match tz {
2497 sp::TimezoneInfo::None | sp::TimezoneInfo::WithoutTimeZone => false,
2498 sp::TimezoneInfo::WithTimeZone | sp::TimezoneInfo::Tz => true,
2499 },
2500 },
2501 D::Uuid => SqlType::Uuid,
2502 D::Bytea => SqlType::Bytes,
2503 D::JSON => SqlType::Json,
2504 D::JSONB => SqlType::Jsonb,
2505 other => return no("data_type", &format!("{other}")),
2506 })
2507}