utopia_query/ast/node.rs
1//! The nodes of the syntax tree.
2
3use super::Grammar;
4use crate::enums::{NullsPosition, OrderDirection};
5use crate::error::{Error, Result};
6use crate::value::Value;
7
8/// An expression: a column, a literal, an operation, a function call, a
9/// subquery.
10///
11/// PHP: the `Utopia\Query\AST\Expression` interface; each variant is one of
12/// its implementations.
13#[derive(Debug, Clone, PartialEq)]
14pub enum Expression {
15 /// A function call.
16 Func(Func),
17 /// An expression with an alias.
18 Aliased(Aliased),
19 /// `x [NOT] BETWEEN low AND high`.
20 Between(Between),
21 /// A binary operation.
22 Binary(Binary),
23 /// One `WHEN ... THEN ...` of a `CASE`, on its own (no serializer
24 /// writes it outside a [`Conditional`]).
25 CaseWhen(CaseWhen),
26 /// `CAST(x AS type)`.
27 Cast(Cast),
28 /// `CASE ... END`.
29 Conditional(Conditional),
30 /// `[NOT] EXISTS (subquery)`.
31 Exists(Exists),
32 /// `x [NOT] IN (...)`.
33 In(In),
34 /// A scalar subquery.
35 Subquery(Subquery),
36 /// A unary operation (prefix, or postfix like `IS NULL`).
37 Unary(Unary),
38 /// A window function call (`... OVER (...)`).
39 Window(Window),
40 /// A literal value.
41 Literal(Literal),
42 /// A bound parameter placeholder.
43 Placeholder(Placeholder),
44 /// SQL written as is.
45 Raw(Raw),
46 /// A column reference.
47 Column(Column),
48 /// `*` or `table.*`.
49 Star(Star),
50}
51
52impl Expression {
53 /// The PHP class of the node, relative to `Utopia\Query\AST\`.
54 pub const fn php_class(&self) -> &'static str {
55 match self {
56 Expression::Func(_) => "Call\\Func",
57 Expression::Aliased(_) => "Expression\\Aliased",
58 Expression::Between(_) => "Expression\\Between",
59 Expression::Binary(_) => "Expression\\Binary",
60 Expression::CaseWhen(_) => "Expression\\CaseWhen",
61 Expression::Cast(_) => "Expression\\Cast",
62 Expression::Conditional(_) => "Expression\\Conditional",
63 Expression::Exists(_) => "Expression\\Exists",
64 Expression::In(_) => "Expression\\In",
65 Expression::Subquery(_) => "Expression\\Subquery",
66 Expression::Unary(_) => "Expression\\Unary",
67 Expression::Window(_) => "Expression\\Window",
68 Expression::Literal(_) => "Literal",
69 Expression::Placeholder(_) => "Placeholder",
70 Expression::Raw(_) => "Raw",
71 Expression::Column(_) => "Reference\\Column",
72 Expression::Star(_) => "Star",
73 }
74 }
75}
76
77macro_rules! into_expression {
78 ($($ty:ident),*) => {$(
79 impl From<$ty> for Expression {
80 /// The node as an expression.
81 fn from(node: $ty) -> Self {
82 Expression::$ty(node)
83 }
84 }
85 )*};
86}
87
88into_expression!(
89 Func,
90 Aliased,
91 Between,
92 Binary,
93 CaseWhen,
94 Cast,
95 Conditional,
96 Exists,
97 In,
98 Subquery,
99 Unary,
100 Window,
101 Literal,
102 Placeholder,
103 Raw,
104 Column,
105 Star
106);
107
108fn boxed(expression: impl Into<Expression>) -> Box<Expression> {
109 Box::new(expression.into())
110}
111
112/// A function call: `NAME([DISTINCT] args) [FILTER (WHERE ...)]`.
113///
114/// PHP: `Utopia\Query\AST\Call\Func` (`name`, `arguments`, `distinct`, `filter`).
115#[derive(Debug, Clone, PartialEq)]
116pub struct Func {
117 /// The function name (the parser upper-cases it).
118 pub name: String,
119 /// The arguments.
120 pub arguments: Vec<Expression>,
121 /// Whether the arguments are `DISTINCT`.
122 pub distinct: bool,
123 /// The `FILTER (WHERE ...)` condition.
124 pub filter: Option<Box<Expression>>,
125}
126
127impl Func {
128 /// A call of `name` with `arguments`, `DISTINCT` when `distinct`, and an
129 /// optional `FILTER (WHERE ...)` condition.
130 ///
131 /// Fails when `name` is not a bare identifier ([`Grammar::is_identifier`]).
132 ///
133 /// PHP: `new Func($name, $arguments, $distinct, $filter)`.
134 pub fn new(
135 name: impl Into<String>,
136 arguments: Vec<Expression>,
137 distinct: bool,
138 filter: Option<Expression>,
139 ) -> Result<Self> {
140 let name = name.into();
141 if !Grammar::is_identifier(&name) {
142 return Err(Error::Validation(format!("Invalid function name: {name}")));
143 }
144 Ok(Func { name, arguments, distinct, filter: filter.map(Box::new) })
145 }
146}
147
148/// An expression with an alias: `expression AS alias`.
149///
150/// PHP: `Utopia\Query\AST\Expression\Aliased` (`expression`, `alias`).
151#[derive(Debug, Clone, PartialEq)]
152pub struct Aliased {
153 /// The expression.
154 pub expression: Box<Expression>,
155 /// The alias.
156 pub alias: String,
157}
158
159impl Aliased {
160 /// `expression AS alias`.
161 ///
162 /// PHP: `new Aliased($expression, $alias)`.
163 pub fn new(expression: impl Into<Expression>, alias: impl Into<String>) -> Self {
164 Aliased { expression: boxed(expression), alias: alias.into() }
165 }
166}
167
168/// `expression [NOT] BETWEEN low AND high`.
169///
170/// PHP: `Utopia\Query\AST\Expression\Between` (`expression`, `low`, `high`, `negated`).
171#[derive(Debug, Clone, PartialEq)]
172pub struct Between {
173 /// The tested expression.
174 pub expression: Box<Expression>,
175 /// The lower bound.
176 pub low: Box<Expression>,
177 /// The upper bound.
178 pub high: Box<Expression>,
179 /// `NOT BETWEEN`.
180 pub negated: bool,
181}
182
183impl Between {
184 /// `expression BETWEEN low AND high`, or `NOT BETWEEN` when `negated`.
185 ///
186 /// PHP: `new Between($expression, $low, $high, $negated)`.
187 pub fn new(
188 expression: impl Into<Expression>,
189 low: impl Into<Expression>,
190 high: impl Into<Expression>,
191 negated: bool,
192 ) -> Self {
193 Between { expression: boxed(expression), low: boxed(low), high: boxed(high), negated }
194 }
195}
196
197/// A binary operation: `left operator right`.
198///
199/// PHP: `Utopia\Query\AST\Expression\Binary` (`left`, `operator`, `right`).
200#[derive(Debug, Clone, PartialEq)]
201pub struct Binary {
202 /// The left operand.
203 pub left: Box<Expression>,
204 /// The operator (`=`, `AND`, `NOT LIKE`, `+`).
205 pub operator: String,
206 /// The right operand.
207 pub right: Box<Expression>,
208 /// What `ESCAPE` names after a `LIKE` pattern.
209 pub escape: Option<Box<Expression>>,
210}
211
212impl Binary {
213 /// `left operator right`.
214 ///
215 /// PHP: `new Binary($left, $operator, $right)`.
216 pub fn new(left: impl Into<Expression>, operator: impl Into<String>, right: impl Into<Expression>) -> Self {
217 Binary { left: boxed(left), operator: operator.into(), right: boxed(right), escape: None }
218 }
219
220 /// The comparison with `ESCAPE escape` after its pattern.
221 ///
222 /// PHP: the `$escape` argument.
223 #[must_use]
224 pub fn with_escape(mut self, escape: impl Into<Expression>) -> Self {
225 self.escape = Some(boxed(escape));
226 self
227 }
228}
229
230/// One `WHEN condition THEN result` of a `CASE`.
231///
232/// PHP: `Utopia\Query\AST\Expression\CaseWhen` (`condition`, `result`).
233#[derive(Debug, Clone, PartialEq)]
234pub struct CaseWhen {
235 /// The `WHEN` condition (or value, for a `CASE` with an operand).
236 pub condition: Box<Expression>,
237 /// The `THEN` result.
238 pub result: Box<Expression>,
239}
240
241impl CaseWhen {
242 /// `WHEN condition THEN result`.
243 ///
244 /// PHP: `new CaseWhen($condition, $result)`.
245 pub fn new(condition: impl Into<Expression>, result: impl Into<Expression>) -> Self {
246 CaseWhen { condition: boxed(condition), result: boxed(result) }
247 }
248}
249
250/// `CAST(expression AS type)` (or PostgreSQL's `expression::type`).
251///
252/// PHP: `Utopia\Query\AST\Expression\Cast` (`expression`, `type`).
253#[derive(Debug, Clone, PartialEq)]
254pub struct Cast {
255 /// The expression.
256 pub expression: Box<Expression>,
257 /// The target type.
258 ///
259 /// PHP: `$type`.
260 pub data_type: String,
261}
262
263impl Cast {
264 /// `CAST(expression AS data_type)`.
265 ///
266 /// Fails when `data_type` is not a type name ([`Grammar::is_type`]).
267 ///
268 /// PHP: `new Cast($expression, $type)`.
269 pub fn new(expression: impl Into<Expression>, data_type: impl Into<String>) -> Result<Self> {
270 let data_type = data_type.into();
271 if !Grammar::is_type(&data_type) {
272 return Err(Error::Validation(format!("Invalid cast type: {data_type}")));
273 }
274 Ok(Cast { expression: boxed(expression), data_type })
275 }
276}
277
278/// `CASE [operand] WHEN ... THEN ... [ELSE ...] END`.
279///
280/// PHP: `Utopia\Query\AST\Expression\Conditional` (`operand`, `whens`, `else`).
281#[derive(Debug, Clone, PartialEq)]
282pub struct Conditional {
283 /// The operand of a simple `CASE`.
284 pub operand: Option<Box<Expression>>,
285 /// The `WHEN` branches.
286 pub whens: Vec<CaseWhen>,
287 /// The `ELSE` result.
288 ///
289 /// PHP: `$else`.
290 pub else_result: Option<Box<Expression>>,
291}
292
293/// `[NOT] EXISTS (subquery)`.
294///
295/// PHP: `Utopia\Query\AST\Expression\Exists` (`subquery`, `negated`).
296#[derive(Debug, Clone, PartialEq)]
297pub struct Exists {
298 /// The subquery.
299 pub subquery: Box<Select>,
300 /// `NOT EXISTS`.
301 pub negated: bool,
302}
303
304impl Exists {
305 /// `EXISTS (subquery)`, or `NOT EXISTS` when `negated`.
306 ///
307 /// PHP: `new Exists($subquery, $negated)`.
308 pub fn new(subquery: Select, negated: bool) -> Self {
309 Exists { subquery: Box::new(subquery), negated }
310 }
311}
312
313/// What an `IN` tests against.
314///
315/// PHP: `In::$list`, `Expression[]|Select`.
316#[derive(Debug, Clone, PartialEq)]
317pub enum InList {
318 /// A list of expressions.
319 Values(Vec<Expression>),
320 /// A subquery.
321 Subquery(Box<Select>),
322}
323
324/// `expression [NOT] IN (list)`.
325///
326/// PHP: `Utopia\Query\AST\Expression\In` (`expression`, `list`, `negated`).
327#[derive(Debug, Clone, PartialEq)]
328pub struct In {
329 /// The tested expression.
330 pub expression: Box<Expression>,
331 /// The values or the subquery.
332 pub list: InList,
333 /// `NOT IN`.
334 pub negated: bool,
335}
336
337impl In {
338 /// `expression IN (list)`, or `NOT IN` when `negated`.
339 ///
340 /// PHP: `new In($expression, $list, $negated)`.
341 pub fn new(expression: impl Into<Expression>, list: InList, negated: bool) -> Self {
342 In { expression: boxed(expression), list, negated }
343 }
344}
345
346/// A scalar subquery: `(SELECT ...)`.
347///
348/// PHP: `Utopia\Query\AST\Expression\Subquery` (`query`).
349#[derive(Debug, Clone, PartialEq)]
350pub struct Subquery {
351 /// The query.
352 pub query: Box<Select>,
353}
354
355impl Subquery {
356 /// `(query)`.
357 ///
358 /// PHP: `new Subquery($query)`.
359 pub fn new(query: Select) -> Self {
360 Subquery { query: Box::new(query) }
361 }
362}
363
364/// A unary operation: `operator (operand)` when `prefix`, else
365/// `operand operator` (`IS NULL`, `IS NOT NULL`).
366///
367/// PHP: `Utopia\Query\AST\Expression\Unary` (`operator`, `operand`, `prefix`).
368#[derive(Debug, Clone, PartialEq)]
369pub struct Unary {
370 /// The operator.
371 pub operator: String,
372 /// The operand.
373 pub operand: Box<Expression>,
374 /// Whether the operator comes first.
375 pub prefix: bool,
376}
377
378impl Unary {
379 /// A prefix operation (`prefix` true) or a postfix one.
380 ///
381 /// PHP: `new Unary($operator, $operand, $prefix)`.
382 pub fn new(operator: impl Into<String>, operand: impl Into<Expression>, prefix: bool) -> Self {
383 Unary { operator: operator.into(), operand: boxed(operand), prefix }
384 }
385}
386
387/// A window function call: `function OVER name` or `function OVER (specification)`.
388///
389/// PHP: `Utopia\Query\AST\Expression\Window` (`function`, `windowName`, `specification`).
390#[derive(Debug, Clone, PartialEq)]
391pub struct Window {
392 /// The function.
393 pub function: Box<Expression>,
394 /// A named window (`OVER w`).
395 pub window_name: Option<String>,
396 /// An inline window (`OVER (...)`), boxed to keep [`Expression`] small.
397 pub specification: Option<Box<WindowSpecification>>,
398}
399
400/// A literal: a string, an integer, a float, a boolean or `NULL`.
401///
402/// PHP: `Utopia\Query\AST\Literal` (`value`, `string|int|float|bool|null`).
403#[derive(Debug, Clone, PartialEq)]
404pub struct Literal {
405 /// The value: a scalar or [`Value::Null`].
406 pub value: Value,
407}
408
409impl Literal {
410 /// A literal of `value` (a scalar).
411 ///
412 /// PHP: `new Literal($value)`.
413 pub fn new(value: impl Into<Value>) -> Self {
414 Literal { value: value.into() }
415 }
416}
417
418/// A bound parameter placeholder, written as is (`?`, `:name`, `$1`).
419///
420/// PHP: `Utopia\Query\AST\Placeholder` (`value`).
421#[derive(Debug, Clone, PartialEq)]
422pub struct Placeholder {
423 /// The placeholder text.
424 pub value: String,
425}
426
427impl Placeholder {
428 /// A placeholder.
429 ///
430 /// PHP: `new Placeholder($value)`.
431 pub fn new(value: impl Into<String>) -> Self {
432 Placeholder { value: value.into() }
433 }
434}
435
436/// SQL written as is.
437///
438/// PHP: `Utopia\Query\AST\Raw` (`sql`).
439#[derive(Debug, Clone, PartialEq)]
440pub struct Raw {
441 /// The SQL.
442 pub sql: String,
443}
444
445impl Raw {
446 /// Raw SQL.
447 ///
448 /// PHP: `new Raw($sql)`.
449 pub fn new(sql: impl Into<String>) -> Self {
450 Raw { sql: sql.into() }
451 }
452}
453
454/// A column reference: `[schema.][table.]name`.
455///
456/// PHP: `Utopia\Query\AST\Reference\Column` (`name`, `table`, `schema`).
457#[derive(Debug, Clone, PartialEq, Eq)]
458pub struct Column {
459 /// The column name.
460 pub name: String,
461 /// The table (or alias) qualifier.
462 pub table: Option<String>,
463 /// The schema qualifier.
464 pub schema: Option<String>,
465}
466
467impl Column {
468 /// An unqualified column.
469 ///
470 /// PHP: `new Column($name)`.
471 pub fn new(name: impl Into<String>) -> Self {
472 Column { name: name.into(), table: None, schema: None }
473 }
474
475 /// A column of `table`.
476 ///
477 /// PHP: `new Column($name, $table)`.
478 pub fn of(table: impl Into<String>, name: impl Into<String>) -> Self {
479 Column { name: name.into(), table: Some(table.into()), schema: None }
480 }
481}
482
483/// `*`, `table.*` or `schema.table.*`.
484///
485/// PHP: `Utopia\Query\AST\Star` (`table`, `schema`).
486#[derive(Debug, Clone, PartialEq, Eq, Default)]
487pub struct Star {
488 /// The table qualifier.
489 pub table: Option<String>,
490 /// The schema qualifier.
491 pub schema: Option<String>,
492}
493
494/// A table reference: `[schema.]name [AS alias]`.
495///
496/// PHP: `Utopia\Query\AST\Reference\Table` (`name`, `alias`, `schema`).
497#[derive(Debug, Clone, PartialEq, Eq)]
498pub struct Table {
499 /// The table name.
500 pub name: String,
501 /// The alias.
502 pub alias: Option<String>,
503 /// The schema qualifier.
504 pub schema: Option<String>,
505}
506
507impl Table {
508 /// A table without alias or schema.
509 ///
510 /// PHP: `new Table($name)`.
511 pub fn new(name: impl Into<String>) -> Self {
512 Table { name: name.into(), alias: None, schema: None }
513 }
514}
515
516/// A subquery used as a table: `(SELECT ...) AS alias`.
517///
518/// PHP: `Utopia\Query\AST\SubquerySource` (`query`, `alias`).
519#[derive(Debug, Clone, PartialEq)]
520pub struct SubquerySource {
521 /// The query.
522 pub query: Box<Select>,
523 /// The alias.
524 pub alias: String,
525}
526
527impl SubquerySource {
528 /// `(query) AS alias`.
529 ///
530 /// PHP: `new SubquerySource($query, $alias)`.
531 pub fn new(query: Select, alias: impl Into<String>) -> Self {
532 SubquerySource { query: Box::new(query), alias: alias.into() }
533 }
534}
535
536/// What a `FROM` or a join reads: a table or a subquery.
537///
538/// PHP: `Table|SubquerySource`.
539#[derive(Debug, Clone, PartialEq)]
540pub enum TableSource {
541 /// A table.
542 Table(Table),
543 /// A subquery.
544 Subquery(SubquerySource),
545}
546
547impl From<Table> for TableSource {
548 /// The table as a source.
549 fn from(table: Table) -> Self {
550 TableSource::Table(table)
551 }
552}
553
554impl From<SubquerySource> for TableSource {
555 /// The subquery as a source.
556 fn from(source: SubquerySource) -> Self {
557 TableSource::Subquery(source)
558 }
559}
560
561/// A join: `TYPE source [ON condition]`.
562///
563/// PHP: `Utopia\Query\AST\JoinClause` (`type`, `table`, `condition`).
564#[derive(Debug, Clone, PartialEq)]
565pub struct JoinClause {
566 /// The join keywords (`JOIN`, `LEFT JOIN`, `CROSS JOIN`).
567 ///
568 /// PHP: `$type`.
569 pub kind: String,
570 /// What is joined.
571 pub table: TableSource,
572 /// The `ON` condition.
573 pub condition: Option<Expression>,
574}
575
576impl JoinClause {
577 /// A join.
578 ///
579 /// PHP: `new JoinClause($type, $table, $condition)`.
580 pub fn new(kind: impl Into<String>, table: impl Into<TableSource>, condition: Option<Expression>) -> Self {
581 JoinClause { kind: kind.into(), table: table.into(), condition }
582 }
583}
584
585/// One `ORDER BY` item: `expression ASC|DESC [NULLS FIRST|LAST]`.
586///
587/// PHP: `Utopia\Query\AST\OrderByItem` (`expression`, `direction`, `nulls`).
588#[derive(Debug, Clone, PartialEq)]
589pub struct OrderByItem {
590 /// What is sorted.
591 pub expression: Expression,
592 /// The direction (`ASC` by default).
593 pub direction: OrderDirection,
594 /// Where `NULL`s go.
595 pub nulls: Option<NullsPosition>,
596}
597
598impl OrderByItem {
599 /// `expression direction`.
600 ///
601 /// PHP: `new OrderByItem($expression, $direction)`.
602 pub fn new(expression: impl Into<Expression>, direction: OrderDirection) -> Self {
603 OrderByItem { expression: expression.into(), direction, nulls: None }
604 }
605}
606
607/// A common table expression: `name [(columns)] AS (query)`.
608///
609/// PHP: `Utopia\Query\AST\Definition\Cte` (`name`, `query`, `columns`, `recursive`).
610#[derive(Debug, Clone, PartialEq)]
611pub struct Cte {
612 /// The name.
613 pub name: String,
614 /// The query.
615 pub query: Select,
616 /// The column names.
617 pub columns: Vec<String>,
618 /// Whether it is recursive (any recursive CTE makes the `WITH` recursive).
619 pub recursive: bool,
620}
621
622impl Cte {
623 /// `name AS (query)`.
624 ///
625 /// PHP: `new Cte($name, $query)`.
626 pub fn new(name: impl Into<String>, query: Select) -> Self {
627 Cte { name: name.into(), query, columns: Vec::new(), recursive: false }
628 }
629}
630
631/// A named window: `WINDOW name AS (specification)`.
632///
633/// PHP: `Utopia\Query\AST\Definition\Window` (`name`, `specification`).
634#[derive(Debug, Clone, PartialEq)]
635pub struct WindowDefinition {
636 /// The name.
637 pub name: String,
638 /// The window.
639 pub specification: WindowSpecification,
640}
641
642/// A window: `[PARTITION BY ...] [ORDER BY ...] [ROWS|RANGE frame]`.
643///
644/// PHP: `Utopia\Query\AST\Specification\Window` (`partitionBy`, `orderBy`,
645/// `frameType`, `frameStart`, `frameEnd`).
646#[derive(Debug, Clone, PartialEq, Default)]
647pub struct WindowSpecification {
648 /// `PARTITION BY` expressions.
649 pub partition_by: Vec<Expression>,
650 /// `ORDER BY` items.
651 pub order_by: Vec<OrderByItem>,
652 /// `ROWS` or `RANGE`.
653 pub frame_type: Option<String>,
654 /// The frame start (`UNBOUNDED PRECEDING`), or its only bound.
655 pub frame_start: Option<String>,
656 /// The frame end, for `BETWEEN start AND end`.
657 pub frame_end: Option<String>,
658}
659
660/// A `SELECT` statement.
661///
662/// The PHP class is immutable and copies itself with `with()`; here the
663/// fields are public, so a changed copy is struct update syntax
664/// (`Select { where_clause: Some(condition), ..select }`).
665///
666/// PHP: `Utopia\Query\AST\Statement\Select` (`columns`, `from`, `joins`,
667/// `where`, `groupBy`, `having`, `orderBy`, `limit`, `offset`, `distinct`,
668/// `ctes`, `windows`), and `Select::with()`.
669#[derive(Debug, Clone, PartialEq, Default)]
670pub struct Select {
671 /// The selected expressions.
672 pub columns: Vec<Expression>,
673 /// The `FROM` source.
674 pub from: Option<TableSource>,
675 /// The joins.
676 pub joins: Vec<JoinClause>,
677 /// The `WHERE` condition.
678 ///
679 /// PHP: `$where`.
680 pub where_clause: Option<Expression>,
681 /// The `GROUP BY` expressions.
682 pub group_by: Vec<Expression>,
683 /// The `HAVING` condition.
684 pub having: Option<Expression>,
685 /// The `ORDER BY` items.
686 pub order_by: Vec<OrderByItem>,
687 /// The `LIMIT`.
688 pub limit: Option<Expression>,
689 /// The `OFFSET`.
690 pub offset: Option<Expression>,
691 /// `SELECT DISTINCT`.
692 pub distinct: bool,
693 /// The `WITH` clauses.
694 pub ctes: Vec<Cte>,
695 /// The `WINDOW` definitions.
696 pub windows: Vec<WindowDefinition>,
697}