1use crate::ast::{
4 Aliased, Between, Binary, Column, Cte, Expression, Func, In, InList, JoinClause, Literal, OrderByItem, Parser, Raw,
5 Select, Serializer, Star, Table, TableSource, Unary,
6};
7use crate::builder::AstDialect;
8use crate::builder::core::{Builder, Dialect, assert_join_on_predicate, first, on_parts};
9use crate::builder::steps::{Arg, Ret, Step};
10use crate::builder::types::{Condition, CteClause};
11use crate::enums::OrderDirection;
12use crate::error::{Error, Result};
13use crate::method::Method;
14use crate::query::{ParsedQuery, Query};
15use crate::value::{self, Array, Object, Value};
16
17fn serializer(dialect: AstDialect) -> Serializer {
21 match dialect {
22 AstDialect::Standard => Serializer::new(),
23 AstDialect::MySql => Serializer::mysql(),
24 AstDialect::MariaDb => Serializer::mariadb(),
25 AstDialect::ClickHouse => Serializer::clickhouse(),
26 AstDialect::PostgreSql => Serializer::postgresql(),
27 AstDialect::Sqlite => Serializer::sqlite(),
28 }
29}
30
31fn literal(value: Option<&Value>) -> Expression {
33 let value = match value {
34 None => Value::Null,
35 Some(v @ (Value::Null | Value::Str(_) | Value::Int(_) | Value::Float(_) | Value::Bool(_))) => v.clone(),
36 Some(other) => value::string(value::to_php_string(other)),
37 };
38 Literal { value }.into()
39}
40
41fn scalar(value: Option<&Value>) -> String {
43 match value {
44 Some(v @ (Value::Str(_) | Value::Int(_) | Value::Float(_) | Value::Bool(_))) => value::to_php_string(v),
45 _ => String::new(),
46 }
47}
48
49fn comparable(value: &Value) -> Value {
51 match value {
52 Value::Str(_) | Value::Int(_) | Value::Float(_) => value.clone(),
53 other => value::string(value::to_php_string(other)),
54 }
55}
56
57fn to_int(value: &Value) -> i64 {
59 match value {
60 Value::Int(i) => *i,
61 Value::Float(f) => php_std::format::dval_to_lval(*f),
62 Value::Bool(b) => i64::from(*b),
63 Value::Str(s) => php_std::format::str_to_int(s.as_bytes()),
64 _ => 0,
65 }
66}
67
68fn column(name: &str) -> Expression {
69 Column::new(name).into()
70}
71
72fn combine(mut expressions: Vec<Expression>, operator: &str) -> Expression {
73 let rest = expressions.split_off(1);
74 let mut result = expressions.pop().unwrap_or_else(|| Raw::new("1 = 1").into());
75 for expression in rest {
76 result = Binary::new(result, operator, expression).into();
77 }
78 result
79}
80
81fn column_string(reference: &Column) -> String {
83 let mut parts: Vec<&str> = Vec::with_capacity(3);
84 if let Some(schema) = &reference.schema {
85 parts.push(schema);
86 }
87 if let Some(table) = &reference.table {
88 parts.push(table);
89 }
90 parts.push(&reference.name);
91 parts.join(".")
92}
93
94struct Reading<'w> {
97 serializer: &'w dyn AstWriter,
98 implicit: Option<u8>,
100}
101
102impl Reading<'_> {
103 fn serialize(&self, statement: &Select) -> Result<String> {
104 self.serializer.serialize(statement)
105 }
106
107 fn serialize_expression(&self, expression: &Expression) -> Result<String> {
108 self.serializer.serialize_expression(expression)
109 }
110}
111
112pub trait AstWriter {
115 fn serialize(&self, statement: &Select) -> Result<String>;
117 fn serialize_expression(&self, expression: &Expression) -> Result<String>;
119}
120
121impl AstWriter for Serializer {
122 fn serialize(&self, statement: &Select) -> Result<String> {
123 Serializer::serialize(self, statement)
124 }
125
126 fn serialize_expression(&self, expression: &Expression) -> Result<String> {
127 Serializer::serialize_expression(self, expression)
128 }
129}
130
131fn escape_like(value: &str, escape: u8) -> String {
135 let escape = char::from(escape);
136 let mut out = String::with_capacity(value.len());
137 for character in value.chars() {
138 if character == escape || character == '%' || character == '_' {
139 out.push(escape);
140 }
141 out.push(character);
142 }
143 out
144}
145
146fn decode_like(pattern: &str, escape: Option<char>) -> Option<(bool, String, bool)> {
151 let characters: Vec<char> = pattern.chars().collect();
152 let leading = characters.first() == Some(&'%');
153 let mut value = String::new();
154 let mut trailing = false;
155 let mut index = usize::from(leading);
156 while index < characters.len() {
157 let character = characters[index];
158 if Some(character) == escape {
159 index += 1;
160 value.push(*characters.get(index)?);
161 } else if character == '%' && index == characters.len() - 1 {
162 trailing = true;
163 } else if character == '%' || character == '_' {
164 return None;
165 } else {
166 value.push(character);
167 }
168 index += 1;
169 }
170 (!value.is_empty()).then_some((leading, value, trailing))
171}
172
173fn like_to_query(
179 attribute: String,
180 pattern: &str,
181 escape: Option<&Expression>,
182 negated: bool,
183 reading: &Reading<'_>,
184) -> Result<Option<Query>> {
185 let character = match escape {
186 None => reading.implicit.map(char::from),
187 Some(Expression::Literal(Literal { value: Value::Str(text) })) if text.as_bytes().len() == 1 => {
188 Some(char::from(text.as_bytes()[0]))
189 }
190 Some(_) => return Ok(None),
191 };
192 if matches!(character, Some('%' | '_')) {
193 return Ok(None);
194 }
195 let Some((leading, value, trailing)) = decode_like(pattern, character).filter(|decoded| decoded.0 || decoded.2)
196 else {
197 let clause = match escape {
198 Some(escape) => format!(" ESCAPE {}", reading.serialize_expression(escape)?),
199 None => String::new(),
200 };
201 let keyword = if negated { " NOT LIKE ?" } else { " LIKE ?" };
202 return Ok(Some(Query::raw(
203 format!("{attribute}{keyword}{clause}"),
204 value::list(vec![value::string(pattern)]),
205 )));
206 };
207 Ok(Some(match (leading, trailing, negated) {
208 (true, true, _) => {
209 let method = if negated { Method::NotContains } else { Method::Contains };
210 Query::new(method, attribute, value::list(vec![value::string(value)]), "")
211 }
212 (_, true, true) => Query::not_starts_with(attribute, value),
213 (_, true, false) => Query::starts_with(attribute, value),
214 (_, false, true) => Query::not_ends_with(attribute, value),
215 (_, false, false) => Query::ends_with(attribute, value),
216 }))
217}
218
219impl<D: Dialect> Builder<D> {
220 pub fn to_ast(&mut self) -> Result<Select> {
226 let grouped = Query::group_by_type(&self.core.pending);
227 self.prepare_alias_qualification(&grouped);
228
229 let columns = self.ast_columns(&grouped);
230 let from = self.ast_from();
231 let joins = self.ast_joins(&grouped)?;
232 let where_clause = match grouped.filters.is_empty() {
233 true => None,
234 false => Some(combine(grouped.filters.iter().map(|f| self.query_to_ast(f)).collect::<Result<_>>()?, "AND")),
235 };
236 let column =
237 value::Param::method("Utopia\\Query\\Builder::columnNameToAstExpression", 1, "col", "Builder.php", 2316);
238 let group_by =
239 grouped.group_by.iter().map(|c| Ok(self.column_to_ast(&column.string(c)?))).collect::<Result<Vec<_>>>()?;
240 let having = self.ast_having(&grouped)?;
241 let order_by = self.ast_order_by();
242 let limit = grouped.limit.map(|l| Literal { value: Value::Int(l) }.into());
243 let offset = grouped.offset.map(|o| Literal { value: Value::Int(o) }.into());
244 let parser = Parser::new().with_literal(D::LITERAL);
245 let mut ctes = Vec::with_capacity(self.core.ctes.len());
246 for cte in self.core.ctes.clone() {
247 let query = match self.overrides(Step::CreateTokenizer) {
249 true => match self.step(Step::CreateTokenizer, &[Arg::Str(&cte.query)])? {
250 Ret::Select(read) => *read,
251 _ => parser.parse_sql(&cte.query)?,
252 },
253 false => parser.parse_sql(&cte.query)?,
254 };
255 ctes.push(Cte { name: cte.name, query, columns: cte.columns, recursive: cte.recursive });
256 }
257
258 Ok(Select {
259 columns,
260 from,
261 joins,
262 where_clause,
263 group_by,
264 having,
265 order_by,
266 limit,
267 offset,
268 distinct: grouped.distinct,
269 ctes,
270 windows: Vec::new(),
271 })
272 }
273
274 fn ast_columns(&self, grouped: &ParsedQuery) -> Vec<Expression> {
275 let mut columns = Vec::new();
276 for aggregate in &grouped.aggregations {
277 let method = aggregate.method();
278 let name = method.sql_function().map_or_else(|| method.as_str().to_ascii_uppercase(), str::to_owned);
279 let attribute = aggregate.attribute();
280 let argument: Expression =
281 if attribute == "*" || attribute.is_empty() { Star::default().into() } else { column(attribute) };
282 let call =
283 Func { name, arguments: vec![argument], distinct: method == Method::CountDistinct, filter: None };
284 columns.push(if aggregate.alias().is_empty() {
285 call.into()
286 } else {
287 Aliased::new(call, aggregate.alias()).into()
288 });
289 }
290 if let Some(selection) = grouped.selections.first() {
291 for value in selection.values().values() {
292 columns.push(self.column_to_ast(&value::to_php_string(value)));
293 }
294 }
295 if columns.is_empty() {
296 columns.push(Star::default().into());
297 }
298 columns
299 }
300
301 fn column_to_ast(&self, name: &str) -> Expression {
303 if name == "*" {
304 return Star::default().into();
305 }
306 if name.contains('.') {
307 let parts: Vec<&str> = name.splitn(3, '.').collect();
308 if let [schema, table, last] = parts[..] {
309 if last == "*" {
310 return Star { table: Some(table.into()), schema: Some(schema.into()) }.into();
311 }
312 return Column { name: last.into(), table: Some(table.into()), schema: Some(schema.into()) }.into();
313 }
314 if parts[1] == "*" {
315 return Star { table: Some(parts[0].into()), schema: None }.into();
316 }
317 return Column::of(parts[0], parts[1]).into();
318 }
319 if self.core.qualify && !self.core.aggregation_aliases.contains(name) {
320 return Column::of(self.core.alias.clone(), name).into();
321 }
322 column(name)
323 }
324
325 fn ast_from(&self) -> Option<TableSource> {
326 if self.core.tableless || self.core.table.is_empty() {
327 return None;
328 }
329 let alias = (!self.core.alias.is_empty()).then(|| self.core.alias.clone());
330 Some(Table { name: self.core.table.clone(), alias, schema: None }.into())
331 }
332
333 fn ast_joins(&self, grouped: &ParsedQuery) -> Result<Vec<JoinClause>> {
334 let mut joins = Vec::with_capacity(grouped.joins.len());
335 for join in &grouped.joins {
336 let kind = match join.method() {
337 Method::LeftJoin => "LEFT JOIN",
338 Method::RightJoin => "RIGHT JOIN",
339 Method::CrossJoin => "CROSS JOIN",
340 Method::FullOuterJoin => "FULL OUTER JOIN",
341 Method::NaturalJoin => "NATURAL JOIN",
342 _ => "JOIN",
343 };
344 let alias = (!join.alias().is_empty()).then(|| join.alias().to_owned());
345 let table = Table { name: join.attribute().to_owned(), alias, schema: None };
346 let on = join.join_on_queries();
347 let condition = if on.is_empty() {
348 None
349 } else {
350 let mut expressions = Vec::with_capacity(on.len());
351 for query in on {
352 assert_join_on_predicate(query)?;
353 expressions.push(self.query_to_ast(query)?);
354 }
355 Some(combine(expressions, "AND"))
356 };
357 joins.push(JoinClause { kind: kind.to_owned(), table: table.into(), condition });
358 }
359 Ok(joins)
360 }
361
362 fn query_to_ast(&self, query: &Query) -> Result<Expression> {
364 let attribute = query.attribute();
365 let values = query.values();
366 let at = |i: i64| values.get(&php_std::ArrayKey::Int(i)).filter(|v| !matches!(v, Value::Null));
367 let compare = |op: &str| Binary::new(column(attribute), op, literal(at(0))).into();
368 let like = |op: &str, text: String| self.like_to_ast(attribute, op, text).into();
369 let escaped = |value: Option<&Value>| escape_like(&scalar(value), D::LIKE_ESCAPE);
370 Ok(match query.method() {
371 Method::Equal => self.equal_to_ast(attribute, values, false),
372 Method::NotEqual => self.equal_to_ast(attribute, values, true),
373 Method::GreaterThan => compare(">"),
374 Method::GreaterThanEqual => compare(">="),
375 Method::LessThan => compare("<"),
376 Method::LessThanEqual => compare("<="),
377 Method::Between | Method::NotBetween => {
378 Between::new(column(attribute), literal(at(0)), literal(at(1)), query.method() == Method::NotBetween)
379 .into()
380 }
381 Method::IsNull => Unary::new("IS NULL", column(attribute), false).into(),
382 Method::IsNotNull => Unary::new("IS NOT NULL", column(attribute), false).into(),
383 Method::Contains | Method::ContainsAny => self.contains_to_ast(attribute, values, false),
384 Method::NotContains => self.contains_to_ast(attribute, values, true),
385 Method::StartsWith => like("LIKE", format!("{}%", escaped(at(0)))),
386 Method::NotStartsWith => like("NOT LIKE", format!("{}%", escaped(at(0)))),
387 Method::EndsWith => like("LIKE", format!("%{}", escaped(at(0)))),
388 Method::NotEndsWith => like("NOT LIKE", format!("%{}", escaped(at(0)))),
389 Method::And | Method::Or => {
390 let operator = if query.method() == Method::Or { "OR" } else { "AND" };
391 let parts = query.nested().map(|q| self.query_to_ast(q)).collect::<Result<Vec<_>>>()?;
392 if parts.is_empty() {
393 Literal { value: Value::Bool(operator != "OR") }.into()
394 } else {
395 combine(parts, operator)
396 }
397 }
398 Method::On => {
399 let (left, operator, right) = on_parts(query);
400 if left.is_empty() || right.is_empty() {
401 return Err(Error::Validation("Join ON requires left and right columns".into()));
402 }
403 if !["=", "!=", "<", ">", "<=", ">=", "<>"].contains(&operator.as_str()) {
404 return Err(Error::Validation(format!("Invalid join operator: {operator}")));
405 }
406 Binary::new(self.column_to_ast(&left), operator, self.column_to_ast(&right)).into()
407 }
408 Method::Raw => Raw::new(attribute).into(),
409 _ => return Err(Error::Unsupported(format!("Unsupported filter type: {}", query.method().as_str()))),
410 })
411 }
412
413 fn equal_to_ast(&self, attribute: &str, values: &Array, negated: bool) -> Expression {
414 if values.len() == 1 {
415 let value = first(values);
416 if matches!(value, Value::Null) {
417 let operator = if negated { "IS NOT NULL" } else { "IS NULL" };
418 return Unary::new(operator, column(attribute), false).into();
419 }
420 return Binary::new(column(attribute), if negated { "!=" } else { "=" }, literal(Some(&value))).into();
421 }
422 let items = values.values().map(|v| literal(Some(v))).collect();
423 In::new(column(attribute), InList::Values(items), negated).into()
424 }
425
426 fn like_to_ast(&self, attribute: &str, operator: &str, pattern: String) -> Binary {
430 let like = Binary::new(column(attribute), operator, Literal { value: value::string(pattern) });
431 if D::DECLARES_LIKE_ESCAPE {
432 like.with_escape(Literal { value: value::string(char::from(D::LIKE_ESCAPE).to_string()) })
433 } else {
434 like
435 }
436 }
437
438 fn contains_to_ast(&self, attribute: &str, values: &Array, negated: bool) -> Expression {
439 let operator = if negated { "NOT LIKE" } else { "LIKE" };
440 let pattern = |v: Option<&Value>| {
441 self.like_to_ast(attribute, operator, format!("%{}%", escape_like(&scalar(v), D::LIKE_ESCAPE)))
442 };
443 if values.len() == 1 {
444 return pattern(Some(&first(values))).into();
445 }
446 let parts = values.values().map(|v| pattern(Some(v)).into()).collect();
447 combine(parts, if negated { "AND" } else { "OR" })
448 }
449
450 fn ast_having(&self, grouped: &ParsedQuery) -> Result<Option<Expression>> {
451 let mut parts = Vec::new();
452 for having in &grouped.having {
453 for query in having.nested() {
454 parts.push(self.query_to_ast(query)?);
455 }
456 }
457 Ok((!parts.is_empty()).then(|| combine(parts, "AND")))
458 }
459
460 fn ast_order_by(&self) -> Vec<OrderByItem> {
461 Query::by_type(&self.core.pending, &[Method::OrderAsc, Method::OrderDesc, Method::OrderRandom])
462 .into_iter()
463 .map(|query| {
464 if query.method() == Method::OrderRandom {
465 return OrderByItem::new(Raw::new("RAND()"), OrderDirection::Asc);
466 }
467 let direction =
468 if query.method() == Method::OrderAsc { OrderDirection::Asc } else { OrderDirection::Desc };
469 let nulls = match query.value() {
470 Some(Value::Ext(Object::Nulls(n))) => Some(*n),
471 _ => None,
472 };
473 OrderByItem { expression: self.column_to_ast(query.attribute()), direction, nulls }
474 })
475 .collect()
476 }
477
478 pub fn from_ast(select: &Select) -> Result<Self> {
486 Self::from_ast_with(select, &serializer(D::ast_dialect()).with_literal(D::LITERAL))
487 }
488
489 pub fn from_ast_with(select: &Select, writer: &dyn AstWriter) -> Result<Self> {
493 let mut builder = Self::new();
494 let serializer = Reading { serializer: writer, implicit: D::IMPLICIT_LIKE_ESCAPE };
495
496 if let Some(TableSource::Table(table)) = &select.from {
497 builder.from(table.name.clone(), table.alias.clone().unwrap_or_default());
498 }
499 builder.apply_ast_columns(select, &serializer)?;
500 builder.apply_ast_joins(select, &serializer)?;
501 if let Some(condition) = &select.where_clause {
502 let queries = where_to_queries(condition, &serializer)?;
503 builder.core.pending.extend(queries);
504 }
505 let group_by: Vec<String> = select
506 .group_by
507 .iter()
508 .filter_map(|e| match e {
509 Expression::Column(c) => Some(column_string(c)),
510 _ => None,
511 })
512 .collect();
513 if !group_by.is_empty() {
514 builder.group_by(group_by);
515 }
516 if let Some(having) = &select.having {
517 let queries = where_to_queries(having, &serializer)?;
518 if !queries.is_empty() {
519 builder.having(queries);
520 }
521 }
522 for item in &select.order_by {
523 match &item.expression {
524 Expression::Column(c) => {
525 if item.direction == OrderDirection::Desc {
526 builder.sort_desc(column_string(c), item.nulls);
527 } else {
528 builder.sort_asc(column_string(c), item.nulls);
529 }
530 }
531 other => {
532 let direction = if item.direction == OrderDirection::Desc { " DESC" } else { " ASC" };
533 let sql = serializer.serialize_expression(other)?;
534 builder.core.raw_orders.push(Condition::new(sql + direction, Vec::new()));
535 }
536 }
537 }
538 if let Some(Expression::Literal(Literal { value })) = &select.limit
539 && !matches!(value, Value::Null)
540 {
541 builder.limit(to_int(value));
542 }
543 if let Some(Expression::Literal(Literal { value })) = &select.offset
544 && !matches!(value, Value::Null)
545 {
546 builder.offset(to_int(value));
547 }
548 for cte in &select.ctes {
549 let sql = serializer.serialize(&cte.query)?;
550 builder.core.ctes.push(CteClause::new(
551 cte.name.clone(),
552 sql,
553 Vec::new(),
554 cte.recursive,
555 cte.columns.clone(),
556 ));
557 }
558 if select.distinct {
559 builder.distinct();
560 }
561 Ok(builder)
562 }
563
564 fn apply_ast_columns(&mut self, select: &Select, serializer: &Reading<'_>) -> Result<()> {
565 let mut columns = Vec::new();
566 for expression in &select.columns {
567 match expression {
568 Expression::Star(Star { table: None, .. }) => {}
569 Expression::Aliased(a) if matches!(*a.expression, Expression::Func(_)) => {
570 let Expression::Func(f) = &*a.expression else { unreachable!() };
571 let name = f.name.to_ascii_uppercase();
572 let attribute = func_attribute(f);
573 if f.distinct && name == "COUNT" {
574 self.core.pending.push(Query::count_distinct(attribute, a.alias.clone()));
575 continue;
576 }
577 let method = match name.as_str() {
578 "COUNT" => Some(Method::Count),
579 "SUM" => Some(Method::Sum),
580 "AVG" => Some(Method::Avg),
581 "MIN" => Some(Method::Min),
582 "MAX" => Some(Method::Max),
583 "STDDEV" => Some(Method::Stddev),
584 "STDDEV_POP" => Some(Method::StddevPop),
585 "STDDEV_SAMP" => Some(Method::StddevSamp),
586 "VARIANCE" => Some(Method::Variance),
587 "VAR_POP" => Some(Method::VarPop),
588 "VAR_SAMP" => Some(Method::VarSamp),
589 "BIT_AND" => Some(Method::BitAnd),
590 "BIT_OR" => Some(Method::BitOr),
591 "BIT_XOR" => Some(Method::BitXor),
592 _ => None,
593 };
594 match method {
595 Some(m) => self.core.pending.push(Query::new(m, attribute, Array::default(), a.alias.clone())),
596 None => {
597 self.select_raw(serializer.serialize_expression(expression)?, Array::default());
598 }
599 }
600 }
601 Expression::Func(f) => {
602 let name = f.name.to_ascii_uppercase();
603 let attribute = func_attribute(f);
604 if f.distinct && name == "COUNT" {
605 self.core.pending.push(Query::count_distinct(attribute, ""));
606 continue;
607 }
608 let method = match name.as_str() {
609 "COUNT" => Some(Method::Count),
610 "SUM" => Some(Method::Sum),
611 "AVG" => Some(Method::Avg),
612 "MIN" => Some(Method::Min),
613 "MAX" => Some(Method::Max),
614 _ => None,
615 };
616 match method {
617 Some(m) => self.core.pending.push(Query::new(m, attribute, Array::default(), "")),
618 None => {
619 self.select_raw(serializer.serialize_expression(expression)?, Array::default());
620 }
621 }
622 }
623 Expression::Column(c) => columns.push(column_string(c)),
624 Expression::Star(s) => columns.push(format!("{}.*", s.table.as_deref().unwrap_or(""))),
625 Expression::Aliased(a) if matches!(*a.expression, Expression::Column(_)) => {
626 let Expression::Column(c) = &*a.expression else { unreachable!() };
627 let mut column = column_string(c);
628 if !a.alias.is_empty() {
629 column.push_str(" AS ");
630 column.push_str(&a.alias);
631 }
632 columns.push(column);
633 }
634 other => {
635 self.select_raw(serializer.serialize_expression(other)?, Array::default());
636 }
637 }
638 }
639 if !columns.is_empty() {
640 self.select(columns);
641 }
642 Ok(())
643 }
644
645 fn apply_ast_joins(&mut self, select: &Select, serializer: &Reading<'_>) -> Result<()> {
646 for join in &select.joins {
647 let TableSource::Table(table) = &join.table else { continue };
648 let method = match join.kind.to_ascii_uppercase().as_str() {
649 "CROSS JOIN" => Method::CrossJoin,
650 "NATURAL JOIN" => Method::NaturalJoin,
651 "LEFT JOIN" | "LEFT OUTER JOIN" => Method::LeftJoin,
652 "RIGHT JOIN" | "RIGHT OUTER JOIN" => Method::RightJoin,
653 "FULL OUTER JOIN" | "FULL JOIN" => Method::FullOuterJoin,
654 _ => Method::Join,
655 };
656 let unconditioned = method == Method::CrossJoin || method == Method::NaturalJoin;
657 let on = match &join.condition {
658 Some(condition) if !unconditioned => join_condition_to_queries(condition, serializer)?,
659 _ => Vec::new(),
660 };
661 let on = value::list(on.into_iter().map(Value::from).collect::<Vec<_>>());
662 self.core.pending.push(Query::new(method, table.name.clone(), on, table.alias.clone().unwrap_or_default()));
663 }
664 Ok(())
665 }
666}
667
668fn func_attribute(func: &Func) -> String {
670 match func.arguments.first() {
671 Some(Expression::Column(c)) => column_string(c),
672 _ => "*".to_owned(),
673 }
674}
675
676fn join_condition_to_queries(condition: &Expression, serializer: &Reading<'_>) -> Result<Vec<Query>> {
678 if let Expression::Binary(b) = condition {
679 let operator = b.operator.to_ascii_uppercase();
680 if operator == "AND" {
681 let mut queries = join_condition_to_queries(&b.left, serializer)?;
682 queries.extend(join_condition_to_queries(&b.right, serializer)?);
683 return Ok(queries);
684 }
685 if operator == "OR" {
686 return Ok(vec![Query::or([
687 join_condition_to_query(&b.left, serializer)?,
688 join_condition_to_query(&b.right, serializer)?,
689 ])]);
690 }
691 if let (Expression::Column(left), Expression::Column(right)) = (&*b.left, &*b.right) {
692 return Ok(vec![Query::on(column_string(left), column_string(right), b.operator.clone())]);
693 }
694 }
695 match expression_to_query(condition, serializer)? {
696 Some(query) if query.method().is_join_condition() => Ok(vec![query]),
697 _ => Err(Error::Validation(format!(
698 "Unsupported join ON condition: {}",
699 serializer.serialize_expression(condition)?
700 ))),
701 }
702}
703
704fn join_condition_to_query(condition: &Expression, serializer: &Reading<'_>) -> Result<Query> {
705 let mut queries = join_condition_to_queries(condition, serializer)?;
706 Ok(if queries.len() == 1 { queries.remove(0) } else { Query::and(queries) })
707}
708
709fn where_to_queries(expression: &Expression, serializer: &Reading<'_>) -> Result<Vec<Query>> {
711 if let Expression::Binary(b) = expression
712 && b.operator.eq_ignore_ascii_case("AND")
713 {
714 let mut queries = where_to_queries(&b.left, serializer)?;
715 queries.extend(where_to_queries(&b.right, serializer)?);
716 return Ok(queries);
717 }
718 if let Some(query) = expression_to_query(expression, serializer)? {
719 return Ok(vec![query]);
720 }
721 Ok(vec![Query::raw(serializer.serialize_expression(expression)?, Array::default())])
722}
723
724fn expression_to_query(expression: &Expression, serializer: &Reading<'_>) -> Result<Option<Query>> {
726 match expression {
727 Expression::Binary(b) => {
728 let operator = b.operator.to_ascii_uppercase();
729 if operator == "AND" {
730 let mut queries = where_to_queries(&b.left, serializer)?;
731 queries.extend(where_to_queries(&b.right, serializer)?);
732 return Ok(Some(Query::and(queries)));
733 }
734 if operator == "OR" {
735 let side = |side: &Expression| -> Result<Query> {
737 match expression_to_query(side, serializer)? {
738 Some(query) => Ok(query),
739 None => Ok(Query::raw(serializer.serialize_expression(side)?, Array::default())),
740 }
741 };
742 return Ok(Some(Query::or([side(&b.left)?, side(&b.right)?])));
743 }
744 if let (Expression::Column(left), Expression::Literal(Literal { value })) = (&*b.left, &*b.right) {
745 let attribute = column_string(left);
746 return Ok(match operator.as_str() {
747 "=" => Some(Query::equal(attribute, [value.clone()])),
748 "!=" | "<>" => Some(Query::not_equal(
749 attribute,
750 match value {
751 Value::Bool(v) => Value::Int(i64::from(*v)),
752 other => other.clone(),
753 },
754 )),
755 ">" => Some(Query::greater_than(attribute, comparable(value))),
756 ">=" => Some(Query::greater_than_equal(attribute, comparable(value))),
757 "<" => Some(Query::less_than(attribute, comparable(value))),
758 "<=" => Some(Query::less_than_equal(attribute, comparable(value))),
759 "LIKE" => {
760 like_to_query(attribute, &value::to_php_string(value), b.escape.as_deref(), false, serializer)?
761 }
762 "NOT LIKE" => {
763 like_to_query(attribute, &value::to_php_string(value), b.escape.as_deref(), true, serializer)?
764 }
765 _ => None,
766 });
767 }
768 Ok(None)
769 }
770 Expression::In(i) => {
771 let (Expression::Column(c), InList::Values(items)) = (&*i.expression, &i.list) else { return Ok(None) };
772 let attribute = column_string(c);
773 let values: Vec<Value> = items
774 .iter()
775 .map(|item| match item {
776 Expression::Literal(l) => l.value.clone(),
777 _ => Value::Null,
778 })
779 .collect();
780 Ok(Some(if i.negated {
781 Query::not_equal(attribute, Value::Array(value::list(values)))
782 } else {
783 Query::equal(attribute, values)
784 }))
785 }
786 Expression::Between(b) => {
787 let Expression::Column(c) = &*b.expression else { return Ok(None) };
788 let bound = |e: &Expression| match e {
789 Expression::Literal(l) => comparable(&l.value),
790 _ => Value::Int(0),
791 };
792 let attribute = column_string(c);
793 let (low, high) = (bound(&b.low), bound(&b.high));
794 Ok(Some(if b.negated {
795 Query::not_between(attribute, low, high)
796 } else {
797 Query::between(attribute, low, high)
798 }))
799 }
800 Expression::Unary(u) => {
801 let Expression::Column(c) = &*u.operand else { return Ok(None) };
802 Ok(match u.operator.to_ascii_uppercase().as_str() {
803 "IS NULL" => Some(Query::is_null(column_string(c))),
804 "IS NOT NULL" => Some(Query::is_not_null(column_string(c))),
805 _ => None,
806 })
807 }
808 _ => Ok(None),
809 }
810}