Skip to main content

utopia_query/builder/
postgresql.rs

1//! PostgreSQL: [`PostgreSql`], with `DISTINCT ON`, `MERGE`, `UPDATE ... FROM`,
2//! `DELETE ... USING`, `RETURNING`, pgvector ordering, JSONB filters and
3//! updates, `FILTER (WHERE ...)` aggregates and ordered-set aggregates.
4//!
5//! PHP: `Utopia\Query\Builder\PostgreSQL` and its `Trait\PostgreSQL\*` traits.
6
7use php_std::ArrayKey;
8use php_std::json::Flags;
9
10use crate::builder::AnyBuilder;
11use crate::builder::core::{Builder, Dialect, ExplainOptions, enclose, first, quote_bytes};
12use crate::builder::feature::{
13    BitwiseAggregates, ConditionalAggregates, CrossJoins, Cube, FullOuterJoins, FullTextSearch, InsertOrIgnore, Json,
14    LateralJoins, Locking, NegatedFullTextSearch, RawSql, Returning, Rollup, Sequences, Spatial, StatisticalAggregates,
15    StringAggregates, TableSampling, Transactions, Upsert, UpsertSelect,
16};
17use crate::builder::mysql::conflict_clause;
18use crate::builder::sql::{self, SqlDialect, distance_operator, wkt_of};
19use crate::builder::types::{Condition, LockMode, MergeClause, Statement, VectorMetric};
20use crate::error::{Error, Result};
21use crate::method::Method;
22use crate::query::Query;
23use crate::value::{self, Array, IntoValues, Param, Value};
24
25/// A PostgreSQL builder.
26///
27/// PHP: `Utopia\Query\Builder\PostgreSQL`.
28///
29/// ```
30/// use utopia_query::Query;
31/// use utopia_query::builder::PostgreSql;
32///
33/// let statement = PostgreSql::new()
34///     .from("users", "")
35///     .distinct_on(["email"])
36///     .filter([Query::starts_with("name", "Al")])
37///     .build()?;
38/// assert_eq!(statement.query, r#"SELECT DISTINCT ON ("email") * FROM "users" WHERE "name" ILIKE ?"#);
39/// # Ok::<(), utopia_query::Error>(())
40/// ```
41///
42/// ```php
43/// use Utopia\Query\Builder\PostgreSQL;
44/// use Utopia\Query\Query;
45///
46/// echo (new PostgreSQL())->from('users')->distinctOn(['email'])
47///     ->filter([Query::startsWith('name', 'Al')])->build()->query, "\n";
48/// // SELECT DISTINCT ON ("email") * FROM "users" WHERE "name" ILIKE ?
49/// ```
50pub type PostgreSql = Builder<PostgreSqlDialect>;
51
52/// The table joined by `UPDATE ... FROM`, with an extra condition.
53///
54/// PHP: `Utopia\Query\Builder\PostgreSQL\UpdateFrom`.
55#[derive(Debug, Clone, Default, PartialEq)]
56pub struct UpdateFrom {
57    /// The joined table.
58    pub table: String,
59    /// Its alias.
60    pub alias: String,
61    /// The extra `WHERE` condition, or empty.
62    pub condition: String,
63    /// The condition's bindings.
64    pub bindings: Vec<Value>,
65}
66
67/// The table of `DELETE ... USING`, with an extra condition.
68///
69/// PHP: `Utopia\Query\Builder\PostgreSQL\DeleteUsing`.
70#[derive(Debug, Clone, Default, PartialEq)]
71pub struct DeleteUsing {
72    /// The `USING` table.
73    pub table: String,
74    /// The extra `WHERE` condition, or empty.
75    pub condition: String,
76    /// The condition's bindings.
77    pub bindings: Vec<Value>,
78}
79
80/// The target, source and condition of a `MERGE`.
81///
82/// PHP: `Utopia\Query\Builder\PostgreSQL\MergeTarget`.
83#[derive(Clone, Default)]
84pub struct MergeTarget {
85    /// The table merged into.
86    pub target: String,
87    /// The source query.
88    pub source: Option<Box<dyn AnyBuilder>>,
89    /// The source's alias.
90    pub alias: String,
91    /// The `ON` condition.
92    pub condition: String,
93    /// The condition's bindings.
94    pub bindings: Vec<Value>,
95}
96
97#[derive(Clone)]
98struct VectorOrder {
99    attribute: String,
100    vector: Array,
101    metric: VectorMetric,
102}
103
104/// The PostgreSQL dialect and its own state.
105#[derive(Clone, Default)]
106pub struct PostgreSqlDialect {
107    vector_order: Option<VectorOrder>,
108    update_from: Option<UpdateFrom>,
109    delete_using: Option<DeleteUsing>,
110    merge_target: Option<MergeTarget>,
111    merge_clauses: Vec<MergeClause>,
112    distinct_on: Vec<String>,
113}
114
115/// `json_encode($value)` as a binding: the JSON string, or `false` when it fails.
116pub(crate) fn json_binding(value: &Value) -> Value {
117    match value::json_encode(value, Flags::NONE) {
118        Ok(json) => value::string(json),
119        Err(_) => Value::Bool(false),
120    }
121}
122
123/// `/^[a-zA-Z0-9_.\[\]]+$/D`.
124pub(crate) fn is_json_path(path: &str) -> bool {
125    let bytes = path.as_bytes();
126    !bytes.is_empty() && bytes.iter().all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'[' | b']'))
127}
128
129/// The value at `index` of a list (`$values[i]`, null when absent).
130pub(crate) fn at(values: &Array, index: i64) -> Value {
131    values.get(&ArrayKey::Int(index)).cloned().unwrap_or(Value::Null)
132}
133
134/// Validates the path and operator of a `jsonPath` filter and binds its value.
135pub(crate) fn json_path_parts<D: Dialect>(b: &mut Builder<D>, values: &Array) -> Result<(String, String)> {
136    const SUBJECT: Param<'static> = Param::internal("preg_match", 2, "subject");
137    let path = SUBJECT.string(&at(values, 0))?.into_owned();
138    if !is_json_path(&path) {
139        return Err(Error::Validation(format!("Invalid JSON path: {path}")));
140    }
141    let operator = match at(values, 1) {
142        Value::Str(s) if ["=", "!=", "<", ">", "<=", ">=", "<>"].iter().any(|o| o.as_bytes() == s.as_bytes()) => {
143            String::from_utf8_lossy(s.as_bytes()).into_owned()
144        }
145        other => {
146            return Err(Error::Validation(format!("Invalid JSON path operator: {}", value::concat(&other)?)));
147        }
148    };
149    b.add_binding(at(values, 2), None);
150    Ok((path, operator))
151}
152
153/// A full-text search term: `$values[0] ?? ''` as `str_ends_with()` takes it.
154pub(crate) fn search_term(values: &Array) -> Result<String> {
155    const HAYSTACK: Param<'static> = Param::internal("str_ends_with", 1, "haystack");
156    Ok(match values.get(&ArrayKey::Int(0)) {
157        None | Some(Value::Null) => String::new(),
158        Some(term) => HAYSTACK.string(term)?.into_owned(),
159    })
160}
161
162/// PHP's `trim()` default characters.
163const TRIM: [char; 6] = [' ', '\t', '\n', '\r', '\0', '\x0B'];
164
165fn is_pcre_space(c: char) -> bool {
166    matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0B' | '\x0C')
167}
168
169/// `ON CONFLICT (keys) DO UPDATE SET` (PostgreSQL and SQLite).
170pub(crate) fn on_conflict_header<D: Dialect>(b: &mut Builder<D>) -> Result<String> {
171    let keys = b.core.conflict_keys.clone();
172    let wrapped = keys.iter().map(|k| b.resolve_and_wrap(k)).collect::<Result<Vec<_>>>()?;
173    Ok(format!("ON CONFLICT ({}) DO UPDATE SET", wrapped.join(", ")))
174}
175
176fn search_expression(b: &mut Builder<PostgreSqlDialect>, attribute: &str, values: &Array, not: bool) -> Result<String> {
177    let term = search_term(values)?;
178    let exact = term.ends_with('"') && term.starts_with('"');
179    let mut collapsed = String::with_capacity(term.len());
180    let mut in_space = false;
181    for c in term.chars() {
182        let c =
183            if matches!(c, '@' | '+' | '-' | '*' | '.' | '\'' | '"' | ')' | '(' | '<' | '>' | '~') { ' ' } else { c };
184        if is_pcre_space(c) {
185            if !in_space {
186                collapsed.push(' ');
187            }
188            in_space = true;
189        } else {
190            collapsed.push(c);
191            in_space = false;
192        }
193    }
194    let sanitized = collapsed.trim_matches(TRIM);
195    if sanitized.is_empty() {
196        return Ok(if not { "1 = 1" } else { "1 = 0" }.into());
197    }
198    let sanitized = if exact { format!("\"{sanitized}\"") } else { sanitized.replace(' ', " or ") };
199    b.add_binding(value::string(sanitized), None);
200    let tsvector = format!("to_tsvector(regexp_replace({attribute}, '[^\\w]+', ' ', 'g'))");
201    Ok(if not {
202        format!("NOT ({tsvector} @@ websearch_to_tsquery(?))")
203    } else {
204        format!("{tsvector} @@ websearch_to_tsquery(?)")
205    })
206}
207
208/// A JSON array element of a `jsonb_set` path: plain when it is only
209/// letters, digits and `_` (and not `NULL`), else double-quoted.
210fn quote_array_element(element: &str) -> String {
211    let plain = !element.is_empty()
212        && element.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
213        && !element.eq_ignore_ascii_case("NULL");
214    if plain {
215        return element.to_owned();
216    }
217    format!("\"{}\"", element.replace('\\', "\\\\").replace('"', "\\\""))
218}
219
220/// A JSON key as a string literal (`E'...'` when it has a backslash).
221fn quote_json_key(key: &str) -> Result<String> {
222    if key.contains('\0') {
223        return Err(Error::Validation("JSON key contains a NUL byte".into()));
224    }
225    let escaped = key.replace('\'', "''");
226    if !key.contains('\\') {
227        return Ok(format!("'{escaped}'"));
228    }
229    Ok(format!("E'{}'", escaped.replace('\\', "\\\\")))
230}
231
232impl Builder<PostgreSqlDialect> {
233    /// `"col"->'a'->>'b'` for `col.a.b`.
234    fn jsonb_path(&mut self, path: &str) -> Result<String> {
235        self.step_string(crate::builder::Step::BuildJsonbPath, &[crate::builder::Arg::Str(path)])
236    }
237
238    /// The builder's own `buildJsonbPath()`.
239    fn base_jsonb_path(&mut self, path: &str) -> Result<String> {
240        let mut parts: Vec<&str> = path.split('.').collect();
241        if parts.len() == 1 {
242            return self.resolve_and_wrap(parts[0]);
243        }
244        let base = self.resolve_attribute(parts[0])?;
245        let mut chain = self.quote(&base)?;
246        let last = parts.pop().unwrap_or_default();
247        for key in &parts[1..] {
248            chain.push_str("->");
249            chain.push_str(&quote_json_key(key)?);
250        }
251        chain.push_str("->>");
252        chain.push_str(&quote_json_key(last)?);
253        Ok(chain)
254    }
255
256    fn jsonb_containment(&mut self, attribute: &str, values: &Array, not: bool, wrap_scalars: bool) -> Result<String> {
257        use crate::builder::{Arg, Step};
258        self.step_string(
259            Step::CompileJsonbContainment,
260            &[Arg::Str(attribute), Arg::Values(values), Arg::Bool(not), Arg::Bool(wrap_scalars)],
261        )
262    }
263
264    /// The builder's own `compileJsonbContainment()`.
265    fn base_jsonb_containment(&mut self, attribute: &str, values: &Array, not: bool, wrap_scalars: bool) -> String {
266        let mut conditions = Vec::with_capacity(values.len());
267        for value in values.values() {
268            let mut value = value.clone();
269            if wrap_scalars
270                && let Value::Array(object) = &mut value
271                && object.len() == 1
272            {
273                let entry = object.iter().next().map(|(k, v)| (k.to_owned(), v.clone()));
274                if let Some((key, inner)) = entry
275                    && !matches!(inner, Value::Array(_))
276                {
277                    object.set(key, Value::Array(value::list([inner])));
278                }
279            }
280            self.add_binding(json_binding(&value), None);
281            let fragment = format!("{attribute} @> ?::jsonb");
282            conditions.push(if not { format!("NOT ({fragment})") } else { fragment });
283        }
284        format!("({})", conditions.join(if not { " AND " } else { " OR " }))
285    }
286
287    fn object_filter(&mut self, query: &Query) -> Result<String> {
288        self.step_string(crate::builder::Step::CompileObjectFilter, &[crate::builder::Arg::Query(query)])
289    }
290
291    /// The builder's own `compileObjectFilter()`.
292    fn base_object_filter(&mut self, query: &Query) -> Result<String> {
293        let method = query.method();
294        let raw = query.attribute();
295        let values = query.values();
296        use Method::*;
297        if raw.contains('.') {
298            let attribute = self.jsonb_path(raw)?;
299            return match method {
300                Equal => self.compile_in(&attribute, values, None),
301                NotEqual => self.compile_not_in(&attribute, values, None),
302                LessThan => self.compile_comparison(&attribute, "<", values, None),
303                LessThanEqual => self.compile_comparison(&attribute, "<=", values, None),
304                GreaterThan => self.compile_comparison(&attribute, ">", values, None),
305                GreaterThanEqual => self.compile_comparison(&attribute, ">=", values, None),
306                StartsWith => PostgreSqlDialect::compile_like(self, &attribute, values, "", "%", false, None),
307                NotStartsWith => PostgreSqlDialect::compile_like(self, &attribute, values, "", "%", true, None),
308                EndsWith => PostgreSqlDialect::compile_like(self, &attribute, values, "%", "", false, None),
309                NotEndsWith => PostgreSqlDialect::compile_like(self, &attribute, values, "%", "", true, None),
310                Contains => PostgreSqlDialect::compile_like(self, &attribute, values, "%", "%", false, None),
311                NotContains => PostgreSqlDialect::compile_like(self, &attribute, values, "%", "%", true, None),
312                IsNull => Ok(format!("{attribute} IS NULL")),
313                IsNotNull => Ok(format!("{attribute} IS NOT NULL")),
314                _ => sql::sql_compile_filter(self, query),
315            };
316        }
317        let attribute = self.resolve_and_wrap(raw)?;
318        let text = format!("{attribute}::text");
319        match method {
320            Equal | NotEqual => self.jsonb_containment(&attribute, values, method == NotEqual, false),
321            Contains | ContainsAny | ContainsAll | NotContains => {
322                self.jsonb_containment(&attribute, values, method == NotContains, true)
323            }
324            StartsWith => PostgreSqlDialect::compile_like(self, &text, values, "", "%", false, None),
325            NotStartsWith => PostgreSqlDialect::compile_like(self, &text, values, "", "%", true, None),
326            EndsWith => PostgreSqlDialect::compile_like(self, &text, values, "%", "", false, None),
327            NotEndsWith => PostgreSqlDialect::compile_like(self, &text, values, "%", "", true, None),
328            IsNull => Ok(format!("{attribute} IS NULL")),
329            IsNotNull => Ok(format!("{attribute} IS NOT NULL")),
330            _ => sql::sql_compile_filter(self, query),
331        }
332    }
333
334    fn vector_filter(&mut self, method: Method, attribute: &str, query: &Query) -> String {
335        let operator = match method {
336            Method::VectorEuclidean => "<->",
337            Method::VectorDot => "<#>",
338            _ => "<=>",
339        };
340        self.add_binding(json_binding(&first(query.values())), None);
341        format!("({attribute} {operator} ?::vector)")
342    }
343
344    /// Appends `condition` to the trailing `WHERE` of `parts`, or adds one.
345    fn merge_into_where(parts: &mut Vec<String>, condition: String) {
346        match parts.last_mut() {
347            Some(last) if last.starts_with("WHERE ") => {
348                last.push_str(" AND ");
349                last.push_str(&condition);
350            }
351            _ => parts.push(format!("WHERE {condition}")),
352        }
353    }
354
355    fn build_update_from(&mut self) -> Result<Statement> {
356        self.core.bindings.clear();
357        self.validate_table()?;
358        let Some(from) = self.dialect.update_from.clone() else {
359            return Err(Error::Validation("No UPDATE FROM target specified.".into()));
360        };
361        let assignments = self.compile_assignments()?;
362        if assignments.is_empty() {
363            return Err(Error::Validation("No assignments for UPDATE. Call set() or setRaw() before update().".into()));
364        }
365        let mut from_clause = self.quote(&from.table)?;
366        if !from.alias.is_empty() {
367            from_clause.push_str(" AS ");
368            from_clause.push_str(&self.quote(&from.alias)?);
369        }
370        let mut parts = vec![format!(
371            "UPDATE {} SET {} FROM {from_clause}",
372            self.quote(&self.core.table.clone())?,
373            assignments.join(", ")
374        )];
375        self.compile_where_clauses(&mut parts, None)?;
376        if !from.condition.is_empty() {
377            Self::merge_into_where(&mut parts, enclose(&from.condition));
378            self.add_bindings(from.bindings);
379        }
380        Ok(self.statement(parts.join(" ")))
381    }
382
383    fn build_delete_using(&mut self) -> Result<Statement> {
384        self.core.bindings.clear();
385        self.validate_table()?;
386        let Some(using) = self.dialect.delete_using.clone() else {
387            return Err(Error::Validation("No DELETE USING target specified.".into()));
388        };
389        let mut parts =
390            vec![format!("DELETE FROM {} USING {}", self.quote(&self.core.table.clone())?, self.quote(&using.table)?)];
391        self.compile_where_clauses(&mut parts, None)?;
392        if !using.condition.is_empty() {
393            Self::merge_into_where(&mut parts, enclose(&using.condition));
394            self.add_bindings(using.bindings);
395        }
396        Ok(self.statement(parts.join(" ")))
397    }
398
399    /// `UPDATE table SET ... FROM other [AS alias]`; keeps a condition set by
400    /// [`Builder::update_from_where`].
401    ///
402    /// PHP: `updateFrom()`.
403    pub fn update_from(&mut self, table: impl Into<String>, alias: impl Into<String>) -> &mut Self {
404        let table = table.into();
405        self.defer_unbound(&format!("update from table '{table}'"));
406        let current = self.dialect.update_from.take().unwrap_or_default();
407        self.dialect.update_from = Some(UpdateFrom { table, alias: alias.into(), ..current });
408        self
409    }
410
411    /// The condition joining the `UPDATE ... FROM` table, with its bindings.
412    ///
413    /// PHP: `updateFromWhere()`.
414    pub fn update_from_where(&mut self, condition: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
415        let current = self.dialect.update_from.take().unwrap_or_default();
416        self.dialect.update_from = Some(UpdateFrom {
417            condition: condition.into(),
418            bindings: bindings.into_values().values().cloned().collect(),
419            ..current
420        });
421        self
422    }
423
424    /// `DELETE FROM table USING other WHERE condition`.
425    ///
426    /// PHP: `deleteUsing()`.
427    pub fn delete_using(
428        &mut self,
429        table: impl Into<String>,
430        condition: impl Into<String>,
431        bindings: impl IntoValues,
432    ) -> &mut Self {
433        let table = table.into();
434        self.defer_unbound(&format!("delete using table '{table}'"));
435        self.dialect.delete_using = Some(DeleteUsing {
436            table,
437            condition: condition.into(),
438            bindings: bindings.into_values().values().cloned().collect(),
439        });
440        self
441    }
442
443    /// `SELECT DISTINCT ON (columns)`.
444    ///
445    /// PHP: `distinctOn()`.
446    pub fn distinct_on<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
447        self.dialect.distinct_on = columns.into_iter().map(Into::into).collect();
448        self
449    }
450
451    /// `FOR UPDATE OF table`.
452    ///
453    /// PHP: `forUpdateOf()`.
454    pub fn for_update_of(&mut self, table: impl Into<String>) -> &mut Self {
455        self.core.lock_mode = Some(LockMode::ForUpdate);
456        self.core.lock_of_table = Some(table.into());
457        self
458    }
459
460    /// `FOR SHARE OF table`.
461    ///
462    /// PHP: `forShareOf()`.
463    pub fn for_share_of(&mut self, table: impl Into<String>) -> &mut Self {
464        self.core.lock_mode = Some(LockMode::ForShare);
465        self.core.lock_of_table = Some(table.into());
466        self
467    }
468
469    /// Orders by the pgvector distance of `attribute` to `vector` (nearest first).
470    ///
471    /// PHP: `orderByVectorDistance()`.
472    pub fn order_by_vector_distance(
473        &mut self,
474        attribute: impl Into<String>,
475        vector: impl IntoValues,
476        metric: VectorMetric,
477    ) -> &mut Self {
478        self.dialect.vector_order =
479            Some(VectorOrder { attribute: attribute.into(), vector: vector.into_values(), metric });
480        self
481    }
482
483    /// `aggregate FILTER (WHERE condition) [AS alias]` in the select list.
484    ///
485    /// PHP: `selectAggregateFilter()`.
486    pub fn select_aggregate_filter(
487        &mut self,
488        aggregate: &str,
489        condition: &str,
490        alias: &str,
491        bindings: impl IntoValues,
492    ) -> Result<&mut Self> {
493        let mut expression = format!("{aggregate} FILTER (WHERE {condition})");
494        if !alias.is_empty() {
495            expression.push_str(" AS ");
496            expression.push_str(&self.quote(alias)?);
497        }
498        Ok(self.select_raw(expression, bindings))
499    }
500
501    fn ordered_set(&mut self, expression: String, alias: &str, bindings: Vec<Value>) -> Result<&mut Self> {
502        let mut expression = expression;
503        if !alias.is_empty() {
504            expression.push_str(" AS ");
505            expression.push_str(&self.quote(alias)?);
506        }
507        Ok(self.select_raw(expression, bindings))
508    }
509
510    fn column_aggregate(&mut self, function: &str, column: &str, alias: &str) -> Result<&mut Self> {
511        let expression = format!("{function}({})", self.resolve_and_wrap(column)?);
512        self.ordered_set(expression, alias, Vec::new())
513    }
514
515    /// `ARRAY_AGG(column)`.
516    ///
517    /// PHP: `arrayAgg()`.
518    pub fn array_agg(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
519        self.column_aggregate("ARRAY_AGG", column, alias)
520    }
521
522    /// `BOOL_AND(column)`.
523    ///
524    /// PHP: `boolAnd()`.
525    pub fn bool_and(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
526        self.column_aggregate("BOOL_AND", column, alias)
527    }
528
529    /// `BOOL_OR(column)`.
530    ///
531    /// PHP: `boolOr()`.
532    pub fn bool_or(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
533        self.column_aggregate("BOOL_OR", column, alias)
534    }
535
536    /// `EVERY(column)`.
537    ///
538    /// PHP: `every()`.
539    pub fn every(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
540        self.column_aggregate("EVERY", column, alias)
541    }
542
543    /// `MODE() WITHIN GROUP (ORDER BY column)`.
544    ///
545    /// PHP: `mode()`.
546    pub fn mode(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
547        let expression = format!("MODE() WITHIN GROUP (ORDER BY {})", self.resolve_and_wrap(column)?);
548        self.ordered_set(expression, alias, Vec::new())
549    }
550
551    /// `PERCENTILE_CONT(fraction) WITHIN GROUP (ORDER BY column)`.
552    ///
553    /// PHP: `percentileCont()`.
554    pub fn percentile_cont(&mut self, fraction: f64, order_column: &str, alias: &str) -> Result<&mut Self> {
555        let expression = format!("PERCENTILE_CONT(?) WITHIN GROUP (ORDER BY {})", self.resolve_and_wrap(order_column)?);
556        self.ordered_set(expression, alias, vec![Value::Float(fraction)])
557    }
558
559    /// `PERCENTILE_DISC(fraction) WITHIN GROUP (ORDER BY column)`.
560    ///
561    /// PHP: `percentileDisc()`.
562    pub fn percentile_disc(&mut self, fraction: f64, order_column: &str, alias: &str) -> Result<&mut Self> {
563        let expression = format!("PERCENTILE_DISC(?) WITHIN GROUP (ORDER BY {})", self.resolve_and_wrap(order_column)?);
564        self.ordered_set(expression, alias, vec![Value::Float(fraction)])
565    }
566
567    /// The table a `MERGE` writes to.
568    ///
569    /// PHP: `mergeInto()`.
570    pub fn merge_into(&mut self, target: impl Into<String>) -> &mut Self {
571        let current = self.dialect.merge_target.take().unwrap_or_default();
572        self.dialect.merge_target = Some(MergeTarget { target: target.into(), ..current });
573        self
574    }
575
576    /// The source query of a `MERGE`, and its alias.
577    ///
578    /// PHP: `using()`.
579    pub fn using(&mut self, source: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
580        let current = self.dialect.merge_target.take().unwrap_or_default();
581        self.dialect.merge_target = Some(MergeTarget { source: Some(source), alias: alias.into(), ..current });
582        self
583    }
584
585    /// The `ON` condition of a `MERGE`, with its bindings.
586    ///
587    /// PHP: `on()`.
588    pub fn on(&mut self, condition: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
589        let current = self.dialect.merge_target.take().unwrap_or_default();
590        self.dialect.merge_target = Some(MergeTarget {
591            condition: condition.into(),
592            bindings: bindings.into_values().values().cloned().collect(),
593            ..current
594        });
595        self
596    }
597
598    /// `WHEN MATCHED THEN action`.
599    ///
600    /// PHP: `whenMatched()`.
601    pub fn when_matched(&mut self, action: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
602        self.dialect.merge_clauses.push(MergeClause::new(
603            action,
604            true,
605            bindings.into_values().values().cloned().collect(),
606        ));
607        self
608    }
609
610    /// `WHEN NOT MATCHED THEN action`.
611    ///
612    /// PHP: `whenNotMatched()`.
613    pub fn when_not_matched(&mut self, action: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
614        self.dialect.merge_clauses.push(MergeClause::new(
615            action,
616            false,
617            bindings.into_values().values().cloned().collect(),
618        ));
619        self
620    }
621
622    /// Compiles the `MERGE INTO target USING (source) AS alias ON condition WHEN ...`.
623    ///
624    /// PHP: `executeMerge()`.
625    pub fn execute_merge(&mut self) -> Result<Statement> {
626        let merge = match &self.dialect.merge_target {
627            Some(m) if !m.target.is_empty() => m.clone(),
628            _ => {
629                return Err(Error::Validation(
630                    "No merge target specified. Call mergeInto() before executeMerge().".into(),
631                ));
632            }
633        };
634        let Some(mut source) = merge.source else {
635            return Err(Error::Validation("No merge source specified. Call using() before executeMerge().".into()));
636        };
637        if merge.condition.is_empty() {
638            return Err(Error::Validation("No merge condition specified. Call on() before executeMerge().".into()));
639        }
640        self.core.bindings.clear();
641        let result = source.build()?;
642        self.add_bindings(result.bindings);
643        let mut sql = format!(
644            "MERGE INTO {} USING ({}) AS {} ON {}",
645            self.quote(&merge.target)?,
646            result.query,
647            self.quote(&merge.alias)?,
648            merge.condition
649        );
650        self.add_bindings(merge.bindings);
651        for clause in self.dialect.merge_clauses.clone() {
652            sql.push_str(if clause.matched { " WHEN MATCHED THEN " } else { " WHEN NOT MATCHED THEN " });
653            sql.push_str(&clause.action);
654            self.add_bindings(clause.bindings);
655        }
656        Ok(self.statement(sql))
657    }
658}
659
660/// `^SELECT(\s+DISTINCT)?`: the length of the select keyword (and `DISTINCT`) to replace.
661fn select_keyword_len(query: &str) -> Option<usize> {
662    let rest = query.strip_prefix("SELECT")?;
663    let space = rest.len() - rest.trim_start_matches(is_pcre_space).len();
664    if space > 0 && rest[space..].starts_with("DISTINCT") {
665        return Some(6 + space + 8);
666    }
667    Some(6)
668}
669
670impl Dialect for PostgreSqlDialect {
671    const CLASS: &'static str = "Utopia\\Query\\Builder\\PostgreSQL";
672    const WRAP: char = '"';
673    const LITERAL: crate::StringLiteral = crate::StringLiteral::Extended;
674
675    fn base_step(
676        b: &mut Builder<Self>,
677        step: crate::builder::Step,
678        arguments: &[crate::builder::Arg<'_>],
679    ) -> Option<Result<crate::builder::Ret>> {
680        sql::sql_base_step(b, step, arguments)
681            .or_else(|| crate::builder::feature::aggregates_base_step::<Self>(step, arguments))
682            .or_else(|| {
683                use crate::builder::{Arg, Ret, Step};
684                Some(match (step, arguments) {
685                    (Step::CompileObjectFilter, [Arg::Query(query)]) => b.base_object_filter(query).map(Ret::Str),
686                    (
687                        Step::CompileJsonbContainment,
688                        [Arg::Str(attribute), Arg::Values(values), Arg::Bool(not), Arg::Bool(wrap)],
689                    ) => Ok(Ret::Str(b.base_jsonb_containment(attribute, values, *not, *wrap))),
690                    (Step::BuildJsonbPath, [Arg::Str(path)]) => b.base_jsonb_path(path).map(Ret::Str),
691                    _ => return None,
692                })
693            })
694    }
695
696    fn quote_string(value: &[u8]) -> Vec<u8> {
697        quote_bytes(value, false)
698    }
699
700    fn compile_random(_b: &Builder<Self>) -> String {
701        "RANDOM()".into()
702    }
703
704    fn compile_regex(b: &mut Builder<Self>, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
705        b.add_binding(first(values), column);
706        Ok(format!("{attribute} ~ ?"))
707    }
708
709    fn compile_contains_all(
710        b: &mut Builder<Self>,
711        attribute: &str,
712        values: &Array,
713        column: Option<&str>,
714    ) -> Result<String> {
715        if let Some(sql) = b.flavored_contains_all(attribute, values, column) {
716            return Ok(sql);
717        }
718        b.base_compile_contains_all(attribute, values, column)
719    }
720
721    fn compile_filter(b: &mut Builder<Self>, query: &Query) -> Result<String> {
722        if query.attribute_type() == "object"
723            && query.attribute().contains('.')
724            && let Some(check) = b.core.flavor.object_path.clone()
725        {
726            check(query.attribute())?;
727        }
728        let method = query.method();
729        if method.is_vector() {
730            let attribute = b.resolve_and_wrap(query.attribute())?;
731            return Ok(b.vector_filter(method, &attribute, query));
732        }
733        if query.attribute_type() == "object" {
734            return b.object_filter(query);
735        }
736        sql::sql_compile_filter(b, query)
737    }
738
739    fn like_keyword(_b: &Builder<Self>) -> &'static str {
740        "ILIKE"
741    }
742
743    fn should_emit_offset(_b: &Builder<Self>, offset: Option<i64>, _limit: Option<i64>) -> Result<bool> {
744        Ok(offset.is_some())
745    }
746
747    fn compile_vector_order_expression(b: &mut Builder<Self>) -> Result<Option<Condition>> {
748        let Some(order) = b.dialect.vector_order.clone() else {
749            return Ok(None);
750        };
751        let attribute = b.resolve_and_wrap(&order.attribute)?;
752        Ok(Some(Condition::new(
753            format!("({attribute} {} ?::vector) ASC", order.metric.to_operator()),
754            vec![json_binding(&Value::Array(order.vector))],
755        )))
756    }
757
758    fn build(b: &mut Builder<Self>) -> Result<Statement> {
759        let result = b.base_build()?;
760        let mut query = result.query.clone();
761        let mut modified = false;
762        if !b.dialect.distinct_on.is_empty() {
763            let columns = b.dialect.distinct_on.clone();
764            let wrapped = columns.iter().map(|c| b.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
765            if let Some(len) = select_keyword_len(&query) {
766                query = format!("SELECT DISTINCT ON ({}){}", wrapped.join(", "), &query[len..]);
767            }
768            modified = true;
769        }
770        if let Some(modifier) = b.core.group_by_modifier.clone() {
771            if let Some(position) = query.find("GROUP BY ") {
772                let after = position + 9;
773                let end = ["HAVING ", "WINDOW ", "ORDER BY ", "LIMIT ", "OFFSET ", "FETCH ", "FOR "]
774                    .iter()
775                    .filter_map(|keyword| query[after..].find(keyword).map(|p| p + after))
776                    .min();
777                let columns = match end {
778                    Some(end) => query[after..end].trim_end_matches(TRIM),
779                    None => &query[after..],
780                };
781                let mut rebuilt = format!("{}GROUP BY {modifier}({columns})", &query[..position]);
782                if let Some(end) = end {
783                    rebuilt.push(' ');
784                    rebuilt.push_str(&query[end..]);
785                }
786                query = rebuilt;
787            }
788            modified = true;
789        }
790        if modified {
791            return Ok(Statement::with_parts(query, result.bindings, result.read_only, b.core.executor.clone(), None));
792        }
793        Ok(result)
794    }
795
796    fn insert(b: &mut Builder<Self>) -> Result<Statement> {
797        let result = b.base_insert()?;
798        b.append_returning(result)
799    }
800
801    fn insert_default_values(b: &mut Builder<Self>) -> Result<Statement> {
802        let result = b.base_insert_default_values()?;
803        b.append_returning(result)
804    }
805
806    fn update(b: &mut Builder<Self>) -> Result<Statement> {
807        for (column, condition) in b.core.json_sets.0.clone() {
808            b.core.raw_sets.set(column.clone(), condition.expression);
809            b.core.raw_set_bindings.set(column, condition.bindings);
810        }
811        let from = b.dialect.update_from.as_ref().is_some_and(|f| !f.table.is_empty());
812        let result = if from { b.build_update_from()? } else { b.base_update()? };
813        b.core.json_sets.clear();
814        b.append_returning(result)
815    }
816
817    fn delete(b: &mut Builder<Self>) -> Result<Statement> {
818        let using = b.dialect.delete_using.as_ref().is_some_and(|d| !d.table.is_empty());
819        let result = if using { b.build_delete_using()? } else { b.base_delete()? };
820        b.append_returning(result)
821    }
822
823    fn explain(b: &mut Builder<Self>, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
824        let format = options.format.to_ascii_uppercase();
825        if !["", "TEXT", "XML", "JSON", "YAML"].contains(&format.as_str()) {
826            return Err(Error::Validation(format!("Invalid EXPLAIN format: {}", options.format)));
827        }
828        let result = b.built()?;
829        let mut flags = Vec::new();
830        if analyze {
831            flags.push("ANALYZE".to_owned());
832        }
833        if options.verbose {
834            flags.push("VERBOSE".to_owned());
835        }
836        if options.buffers {
837            flags.push("BUFFERS".to_owned());
838        }
839        if !format.is_empty() {
840            flags.push(format!("FORMAT {format}"));
841        }
842        let prefix = if flags.is_empty() { "EXPLAIN".to_owned() } else { format!("EXPLAIN ({})", flags.join(", ")) };
843        Ok(Statement::with_parts(
844            format!("{prefix} {}", result.query),
845            result.bindings,
846            true,
847            b.core.executor.clone(),
848            None,
849        ))
850    }
851
852    fn reset(b: &mut Builder<Self>) {
853        b.core.json_sets.clear();
854        b.reset_returning();
855        b.reset_group_by_modifier();
856        b.dialect = PostgreSqlDialect::default();
857    }
858
859    fn ast_dialect() -> crate::builder::AstDialect {
860        crate::builder::AstDialect::PostgreSql
861    }
862}
863
864impl SqlDialect for PostgreSqlDialect {
865    fn compile_search_expression(b: &mut Builder<Self>, attribute: &str, values: &Array, not: bool) -> Result<String> {
866        match b.flavored_search_values(values) {
867            Some(values) => search_expression(b, attribute, &values, not),
868            None => search_expression(b, attribute, values, not),
869        }
870    }
871
872    fn compile_spatial_filter(b: &mut Builder<Self>, method: Method, attribute: &str, query: &Query) -> Result<String> {
873        if method == Method::DistanceLessThan
874            && let Some(srid) = b.core.flavor.indexed_distance
875        {
876            return b.indexed_distance(attribute, query, srid);
877        }
878        sql::sql_compile_spatial_filter(b, method, attribute, query)
879    }
880
881    fn compile_spatial_distance(
882        b: &mut Builder<Self>,
883        method: Method,
884        attribute: &str,
885        values: &Array,
886    ) -> Result<String> {
887        let filter = sql::distance_filter(values, "Builder/PostgreSQL.php", 815)?;
888        let operator = distance_operator(method);
889        let wkt = wkt_of(b, &filter.geometry)?;
890        b.add_binding(wkt, None);
891        b.add_binding(Value::Float(filter.distance), None);
892        if filter.meters {
893            return Ok(format!(
894                "ST_Distance(({attribute}::geography), ST_SetSRID(ST_GeomFromText(?), 4326)::geography) {operator} ?"
895            ));
896        }
897        Ok(format!("ST_Distance({attribute}, ST_GeomFromText(?, 4326)) {operator} ?"))
898    }
899
900    fn compile_spatial_predicate(
901        b: &mut Builder<Self>,
902        function: &str,
903        attribute: &str,
904        values: &Array,
905        not: bool,
906    ) -> Result<String> {
907        let wkt = sql::predicate_wkt(b, values, Self::CLASS, "Builder/PostgreSQL.php", 844)?;
908        b.add_binding(value::string(wkt), None);
909        let expression = format!("{function}({attribute}, ST_GeomFromText(?, 4326))");
910        Ok(if not { format!("NOT {expression}") } else { expression })
911    }
912
913    fn compile_spatial_covers_predicate(
914        b: &mut Builder<Self>,
915        attribute: &str,
916        values: &Array,
917        not: bool,
918    ) -> Result<String> {
919        // Through the step, so a subclass's compileSpatialPredicate() writes this one too.
920        b.step_string(
921            crate::builder::Step::CompileSpatialPredicate,
922            &[
923                crate::builder::Arg::Str("ST_Covers"),
924                crate::builder::Arg::Str(attribute),
925                crate::builder::Arg::Values(values),
926                crate::builder::Arg::Bool(not),
927            ],
928        )
929    }
930
931    fn compile_json_contains_expression(
932        b: &mut Builder<Self>,
933        attribute: &str,
934        values: &Array,
935        not: bool,
936    ) -> Result<String> {
937        b.add_binding(json_binding(&first(values)), None);
938        let expression = format!("{attribute} @> ?::jsonb");
939        Ok(if not { format!("NOT ({expression})") } else { expression })
940    }
941
942    fn compile_json_overlaps_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
943        let mut conditions = Vec::new();
944        // `foreach` walks an array or an object's properties, and skips anything else.
945        if let Value::Array(items) | Value::Object(items) = first(values) {
946            for item in items.values() {
947                b.add_binding(json_binding(item), None);
948                conditions.push(format!("{attribute} @> ?::jsonb"));
949            }
950        }
951        Ok(format!("({})", conditions.join(" OR ")))
952    }
953
954    fn compile_json_path_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
955        let (path, operator) = json_path_parts(b, values)?;
956        Ok(format!("{attribute}->>'{path}' {operator} ?"))
957    }
958
959    fn compile_conflict_header(b: &mut Builder<Self>) -> Result<String> {
960        on_conflict_header(b)
961    }
962
963    fn compile_conflict_assignment(wrapped: &str) -> String {
964        format!("EXCLUDED.{wrapped}")
965    }
966}
967
968impl Locking for PostgreSqlDialect {}
969impl Transactions for PostgreSqlDialect {}
970impl StatisticalAggregates for PostgreSqlDialect {}
971impl BitwiseAggregates for PostgreSqlDialect {}
972impl RawSql for PostgreSqlDialect {}
973impl CrossJoins for PostgreSqlDialect {}
974impl FullOuterJoins for PostgreSqlDialect {}
975impl LateralJoins for PostgreSqlDialect {}
976impl Spatial for PostgreSqlDialect {}
977impl FullTextSearch for PostgreSqlDialect {}
978impl NegatedFullTextSearch for PostgreSqlDialect {}
979impl Returning for PostgreSqlDialect {}
980
981impl ConditionalAggregates for PostgreSqlDialect {
982    /// `aggregate(column | *) FILTER (WHERE condition)`.
983    fn aggregate_filter(
984        b: &mut Builder<Self>,
985        aggregate: &str,
986        column: Option<&str>,
987        condition: &str,
988        alias: &str,
989    ) -> Result<String> {
990        let argument = match column {
991            None => "*".to_owned(),
992            Some(c) => b.resolve_and_wrap(c)?,
993        };
994        let mut expression = format!("{aggregate}({argument}) FILTER (WHERE {condition})");
995        if !alias.is_empty() {
996            expression.push_str(" AS ");
997            expression.push_str(&b.quote(alias)?);
998        }
999        Ok(expression)
1000    }
1001}
1002
1003impl StringAggregates for PostgreSqlDialect {
1004    fn group_concat_expr(column: &str, order_by: &str) -> String {
1005        if order_by.is_empty() {
1006            format!("STRING_AGG({column}, ?)")
1007        } else {
1008            format!("STRING_AGG({column}, ? {order_by})")
1009        }
1010    }
1011    fn json_array_agg_expr(column: &str) -> String {
1012        format!("JSON_AGG({column})")
1013    }
1014    fn json_object_agg_expr(key: &str, value: &str) -> String {
1015        format!("JSON_OBJECT_AGG({key}, {value})")
1016    }
1017}
1018
1019impl Rollup for PostgreSqlDialect {
1020    fn with_rollup(b: &mut Builder<Self>) {
1021        b.core.group_by_modifier = Some("ROLLUP".into());
1022    }
1023}
1024
1025impl Cube for PostgreSqlDialect {
1026    fn with_cube(b: &mut Builder<Self>) {
1027        b.core.group_by_modifier = Some("CUBE".into());
1028    }
1029}
1030
1031impl TableSampling for PostgreSqlDialect {
1032    fn tablesample(b: &mut Builder<Self>, percent: f64, method: &str) -> Result<()> {
1033        let normalized = method.to_ascii_uppercase();
1034        if normalized != "BERNOULLI" && normalized != "SYSTEM" {
1035            return Err(Error::Validation(format!("Invalid TABLESAMPLE method: {method}")));
1036        }
1037        b.core.sample = Some((percent, normalized));
1038        Ok(())
1039    }
1040}
1041
1042impl Sequences for PostgreSqlDialect {
1043    fn sequence_expression(_b: &mut Builder<Self>, next: bool, sequence: &str) -> Result<String> {
1044        Ok(format!("{}('{sequence}')", if next { "nextval" } else { "currval" }))
1045    }
1046}
1047
1048impl Upsert for PostgreSqlDialect {
1049    fn upsert(b: &mut Builder<Self>) -> Result<Statement> {
1050        let result = b.compile_upsert(conflict_clause)?;
1051        b.append_returning(result)
1052    }
1053}
1054
1055impl UpsertSelect for PostgreSqlDialect {
1056    fn upsert_select(b: &mut Builder<Self>) -> Result<Statement> {
1057        let result = b.compile_upsert_select(conflict_clause)?;
1058        b.append_returning(result)
1059    }
1060}
1061
1062impl InsertOrIgnore for PostgreSqlDialect {
1063    fn insert_or_ignore(b: &mut Builder<Self>) -> Result<Statement> {
1064        b.core.bindings.clear();
1065        let (sql, bindings) = b.compile_insert_body()?;
1066        b.add_bindings(bindings);
1067        let result = b.statement(format!("{sql} ON CONFLICT DO NOTHING"));
1068        b.append_returning(result)
1069    }
1070}
1071
1072impl Json for PostgreSqlDialect {
1073    fn set_json_append(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
1074        let wrapped = b.resolve_and_wrap(column)?;
1075        b.core.json_sets.set(
1076            column,
1077            Condition::new(
1078                format!("COALESCE({wrapped}, '[]'::jsonb) || ?::jsonb"),
1079                vec![json_binding(&Value::Array(values.clone()))],
1080            ),
1081        );
1082        Ok(())
1083    }
1084
1085    fn set_json_prepend(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
1086        let wrapped = b.resolve_and_wrap(column)?;
1087        b.core.json_sets.set(
1088            column,
1089            Condition::new(
1090                format!("?::jsonb || COALESCE({wrapped}, '[]'::jsonb)"),
1091                vec![json_binding(&Value::Array(values.clone()))],
1092            ),
1093        );
1094        Ok(())
1095    }
1096
1097    fn set_json_insert(b: &mut Builder<Self>, column: &str, index: i64, value: Value) -> Result<()> {
1098        let wrapped = b.resolve_and_wrap(column)?;
1099        b.core.json_sets.set(
1100            column,
1101            Condition::new(format!("jsonb_insert({wrapped}, '{{{index}}}', ?::jsonb)"), vec![json_binding(&value)]),
1102        );
1103        Ok(())
1104    }
1105
1106    fn set_json_remove(b: &mut Builder<Self>, column: &str, value: Value) -> Result<()> {
1107        let wrapped = b.resolve_and_wrap(column)?;
1108        b.core.json_sets.set(column, Condition::new(format!("{wrapped} - ?"), vec![json_binding(&value)]));
1109        Ok(())
1110    }
1111
1112    fn set_json_intersect(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
1113        let wrapped = b.resolve_and_wrap(column)?;
1114        b.set_raw(
1115            column,
1116            format!("(SELECT jsonb_agg(elem) FROM jsonb_array_elements({wrapped}) AS elem WHERE elem <@ ?::jsonb)"),
1117            vec![json_binding(&Value::Array(values.clone()))],
1118        );
1119        Ok(())
1120    }
1121
1122    fn set_json_diff(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
1123        let wrapped = b.resolve_and_wrap(column)?;
1124        b.set_raw(
1125            column,
1126            format!(
1127                "(SELECT COALESCE(jsonb_agg(elem), '[]'::jsonb) FROM jsonb_array_elements({wrapped}) AS elem WHERE NOT elem <@ ?::jsonb)"
1128            ),
1129            vec![json_binding(&Value::Array(values.clone()))],
1130        );
1131        Ok(())
1132    }
1133
1134    fn set_json_unique(b: &mut Builder<Self>, column: &str) -> Result<()> {
1135        let wrapped = b.resolve_and_wrap(column)?;
1136        b.set_raw(
1137            column,
1138            format!("(SELECT jsonb_agg(DISTINCT elem) FROM jsonb_array_elements({wrapped}) AS elem)"),
1139            Vec::<Value>::new(),
1140        );
1141        Ok(())
1142    }
1143
1144    fn set_json_path(b: &mut Builder<Self>, column: &str, path: &str, value: Value) -> Result<()> {
1145        let Some(rest) = path.strip_prefix('$') else {
1146            return Err(Error::Validation(format!("JSON path must start with '$': {path}")));
1147        };
1148        let trimmed = rest.trim_start_matches('.');
1149        if trimmed.is_empty() {
1150            return Err(Error::Validation(format!("JSON path must reference at least one key: {path}")));
1151        }
1152        let segments: Vec<&str> = trimmed.split('.').collect();
1153        if segments.iter().any(|s| s.is_empty()) {
1154            return Err(Error::Validation(format!("JSON path contains an empty segment: {path}")));
1155        }
1156        let array = format!("{{{}}}", segments.iter().map(|s| quote_array_element(s)).collect::<Vec<_>>().join(","));
1157        let wrapped = b.resolve_and_wrap(column)?;
1158        b.core.json_sets.set(
1159            column,
1160            Condition::new(
1161                format!("jsonb_set({wrapped}, ?, to_jsonb(?::text)::jsonb, true)"),
1162                vec![value::string(array), value],
1163            ),
1164        );
1165        Ok(())
1166    }
1167}