Skip to main content

postrust_core/query/
builder.rs

1//! Query builder implementation.
2
3use crate::error::Result;
4use crate::plan::{
5    CallParams, CallPlan, CoercibleFilter, CoercibleLogicTree, CoercibleOrderTerm,
6    CoercibleSelectField, MutatePlan, ReadPlan, ReadPlanTree,
7};
8use postrust_sql::{escape_ident, from_qi, OrderExpr, SelectBuilder, SqlFragment, SqlParam};
9
10/// Query builder for converting plans to SQL.
11pub struct QueryBuilder;
12
13impl QueryBuilder {
14    /// Build a SELECT query from a read plan tree.
15    pub fn build_read(tree: &ReadPlanTree) -> Result<SqlFragment> {
16        Self::build_read_plan(&tree.root)
17    }
18
19    /// Build a SELECT query from a read plan.
20    fn build_read_plan(plan: &ReadPlan) -> Result<SqlFragment> {
21        let mut builder = SelectBuilder::new();
22
23        // FROM clause
24        let qi = &plan.from;
25        if let Some(alias) = &plan.from_alias {
26            builder = builder.from_table_as(
27                &postrust_sql::identifier::QualifiedIdentifier::new(&qi.schema, &qi.name),
28                alias,
29            );
30        } else {
31            builder = builder.from_table(&postrust_sql::identifier::QualifiedIdentifier::new(
32                &qi.schema, &qi.name,
33            ));
34        }
35
36        // SELECT columns
37        for field in &plan.select {
38            let col_frag = Self::build_select_field(field)?;
39            builder = builder.column_raw(col_frag);
40        }
41
42        // WHERE clauses
43        for clause in &plan.where_clauses {
44            let expr = Self::build_logic_tree(clause)?;
45            builder = builder.where_raw(expr);
46        }
47
48        // GROUP BY. Selecting an aggregate alongside plain columns means one
49        // row per distinct combination of those columns, so every one of them
50        // has to be grouped -- PostgreSQL rejects the query otherwise.
51        if plan.select.iter().any(|f| f.aggregate.is_some()) {
52            for field in plan.select.iter().filter(|f| f.aggregate.is_none()) {
53                builder = builder.group_by(&field.field.name);
54            }
55        }
56
57        // ORDER BY
58        //
59        // A term naming an embedded resource is left for the caller: it orders
60        // by a column of another table, which this query has no way to reach.
61        for term in plan.order.iter().filter(|t| t.relation.is_none()) {
62            let order = Self::build_order_term(term);
63            builder = builder.order_by(order);
64        }
65
66        // LIMIT/OFFSET
67        if let Some(limit) = plan.range.limit {
68            builder = builder.limit(limit);
69        }
70        if plan.range.offset > 0 {
71            builder = builder.offset(plan.range.offset);
72        }
73
74        Ok(builder.build())
75    }
76
77    /// Build a SELECT field.
78    fn build_select_field(field: &CoercibleSelectField) -> Result<SqlFragment> {
79        let mut frag = SqlFragment::new();
80
81        // `*` reaches here only where the columns are not known ahead of time
82        // -- a function's result, where the plan has no table to expand it
83        // against. Quoting it would ask for a column literally named `*`.
84        if field.field.name == "*" && field.aggregate.is_none() && field.cast.is_none() {
85            frag.push("*");
86            return Ok(frag);
87        }
88
89        // Aggregate function
90        if let Some(agg) = &field.aggregate {
91            frag.push(agg.to_sql());
92            frag.push("(");
93        }
94
95        // `count()` counts rows rather than a column's non-null values.
96        if field.aggregate.is_some() && field.field.name.is_empty() {
97            frag.push("*)");
98            if let Some(cast) = &field.aggregate_cast {
99                frag.push("::");
100                frag.push(cast);
101            }
102            frag.push(" AS ");
103            frag.push(&escape_ident(field.alias.as_deref().unwrap_or("count")));
104            return Ok(frag);
105        }
106
107        // A type this process cannot decode is rendered by PostgreSQL instead.
108        //
109        // The row converter maps a fixed set of built-in types and falls back
110        // to reading a column as text, which fails outright for a type like a
111        // PostGIS geometry -- the column came back as null. `to_jsonb` gives
112        // the database's own rendering, which for a geometry is the GeoJSON
113        // PostgREST returns. PostgREST gets it for free by building its whole
114        // response in SQL; this is the same rendering, asked for by name.
115        //
116        // A column with a declared representation is already rendered by that
117        // -- the schema said how the value is written on the wire, and the
118        // generic fallback would render it some other way instead. A `bytea`
119        // with a base64 representation came out as `\x` and hex, which is
120        // PostgreSQL's rendering of bytes and not the schema's.
121        let render_as_json = field.aggregate.is_none()
122            && field.cast.is_none()
123            && field.field.transform.is_none()
124            && field.field.json_path.is_empty()
125            && !decodable_type(&field.field.ir_type);
126        if render_as_json {
127            let mut inner = SqlFragment::new();
128            push_field_ref(&mut inner, &field.field);
129            frag.push("to_jsonb(");
130            frag.push(inner.sql());
131            frag.push(") AS ");
132            frag.push(&escape_ident(
133                field.alias.as_deref().unwrap_or(&field.field.name),
134            ));
135            return Ok(frag);
136        }
137
138        // A cast to a type the row converter cannot read -- an array above
139        // all, `oid_array_col::_int4` -- would come back null for the same
140        // reason an unreadable column does, so the database renders the cast
141        // value: `to_jsonb(col::_int4)`.
142        let cast_as_json = field.aggregate.is_none()
143            && field
144                .cast
145                .as_deref()
146                .is_some_and(|cast| !decodable_cast(cast));
147        if cast_as_json {
148            frag.push("to_jsonb(");
149        }
150
151        // Column name with JSON path.
152        //
153        // `::` binds tighter than `->>`, so a cast over a JSON path has to be
154        // parenthesised: `settings ->> 'foo'::json` would cast the *key*
155        // rather than the extracted value.
156        let needs_parens = field.cast.is_some() && !field.field.json_path.is_empty();
157        if needs_parens {
158            frag.push("(");
159        }
160        // A transformer renders the column instead of this process: PostgREST
161        // uses it for a schema's declared data representations, and it is also
162        // how a value whose spelling depends on the session -- a `timestamptz`
163        // under `Prefer: timezone` -- gets rendered where the session is.
164        match &field.field.transform {
165            Some(function) => {
166                frag.push(function);
167                frag.push("(");
168                push_field_ref(&mut frag, &field.field);
169                frag.push(")");
170            }
171            None => push_field_ref(&mut frag, &field.field),
172        }
173        if needs_parens {
174            frag.push(")");
175        }
176
177        // Cast on the column, inside the aggregate.
178        if let Some(cast) = &field.cast {
179            frag.push("::");
180            frag.push(cast);
181        }
182
183        if cast_as_json {
184            frag.push(")");
185        }
186
187        // Close aggregate, then any cast applied to its result.
188        if let Some(agg) = &field.aggregate {
189            frag.push(")");
190            if let Some(cast) = &field.aggregate_cast {
191                frag.push("::");
192                frag.push(cast);
193            }
194            // An aggregate is an expression, so it needs a name. PostgREST
195            // uses the function's own, lowercased.
196            frag.push(" AS ");
197            frag.push(&escape_ident(
198                field
199                    .alias
200                    .as_deref()
201                    .unwrap_or(&agg.to_sql().to_lowercase()),
202            ));
203            return Ok(frag);
204        }
205
206        // Alias
207        //
208        // A JSON path always needs one: `data -> 'a' ->> 'b'` is an expression,
209        // and PostgreSQL would label the column `?column?`. PostgREST names it
210        // after the last key in the path, falling back to the column itself
211        // when the path ends in an array index.
212        let implicit_alias = if field.alias.is_some() {
213            None
214        } else if field.field.transform.is_some() {
215            Some(field.field.name.clone())
216        } else if !field.field.json_path.is_empty() {
217            Some(json_path_alias(&field.field.name, &field.field.json_path))
218        } else if cast_as_json {
219            // `to_jsonb(..)` would otherwise name the column after itself.
220            Some(field.field.name.clone())
221        } else if field.field.computed.is_some() {
222            // A call is an expression, and PostgreSQL would label it after the
223            // function -- which is the right name, but only by coincidence of
224            // the two agreeing. Naming it outright keeps a schema-qualified
225            // call from arriving under some other label.
226            Some(field.field.name.clone())
227        } else {
228            None
229        };
230
231        if let Some(alias) = field.alias.as_deref().or(implicit_alias.as_deref()) {
232            frag.push(" AS ");
233            frag.push(&escape_ident(alias));
234        }
235
236        Ok(frag)
237    }
238
239    /// Build a logic tree.
240    fn build_logic_tree(tree: &CoercibleLogicTree) -> Result<SqlFragment> {
241        Self::build_logic_tree_in(None, tree)
242    }
243
244    /// The same, with every column qualified by a relation.
245    ///
246    /// An `UPDATE ... FROM` has the body's columns in scope alongside the
247    /// table's, so a bare column name in the `WHERE` is ambiguous exactly
248    /// when the request filters on a column it is also writing.
249    fn build_logic_tree_in(
250        qualifier: Option<&str>,
251        tree: &CoercibleLogicTree,
252    ) -> Result<SqlFragment> {
253        match tree {
254            CoercibleLogicTree::Expr {
255                negated,
256                op,
257                children,
258            } => {
259                let sep = match op {
260                    crate::api_request::LogicOperator::And => " AND ",
261                    crate::api_request::LogicOperator::Or => " OR ",
262                };
263
264                let child_frags: Result<Vec<_>> = children
265                    .iter()
266                    .map(|child| Self::build_logic_tree_in(qualifier, child))
267                    .collect();
268
269                let mut combined = SqlFragment::join(sep, child_frags?).parens();
270
271                if *negated {
272                    let mut neg = SqlFragment::raw("NOT ");
273                    neg.append(combined);
274                    combined = neg;
275                }
276
277                Ok(combined)
278            }
279            CoercibleLogicTree::Stmt(filter) => Self::build_filter_in(qualifier, filter),
280            CoercibleLogicTree::NullEmbed {
281                negated,
282                field_name,
283            } => {
284                let mut frag = SqlFragment::new();
285                frag.push(&escape_ident(field_name));
286                if *negated {
287                    frag.push(" IS NOT NULL");
288                } else {
289                    frag.push(" IS NULL");
290                }
291                Ok(frag)
292            }
293        }
294    }
295
296    /// A column reference with its JSON path, as it appears in SQL.
297    ///
298    /// Exposed for ordering by an embedded resource's column, which is
299    /// assembled outside the read plan.
300    pub fn column_sql(field: &crate::plan::CoercibleField) -> String {
301        Self::qualified_column_sql(None, field)
302    }
303
304    /// The same, with the column qualified by a relation alias.
305    ///
306    /// The alias belongs to the column, not to the expression around it:
307    /// `to_jsonb(e2."settings")->'a'`, never `e2.to_jsonb(...)`, which reads
308    /// as a function in a schema called `e2`.
309    pub fn qualified_column_sql(
310        qualifier: Option<&str>,
311        field: &crate::plan::CoercibleField,
312    ) -> String {
313        let mut frag = SqlFragment::new();
314        push_qualified_field_ref(&mut frag, qualifier, field);
315        frag.sql().to_string()
316    }
317
318    /// Build the SQL for a single filter against a column of `pg_type`.
319    ///
320    /// Exposed for the embedding path, which applies filters inside a child
321    /// subquery it assembles itself rather than through a full plan. Column
322    /// names are left unqualified: inside the child's subselect the innermost
323    /// `FROM` wins, so a bare name binds to the child. The caller is
324    /// responsible for having checked the column exists there -- otherwise the
325    /// name would resolve outward to the correlated parent instead.
326    pub fn filter_sql(filter: &crate::api_request::Filter, pg_type: &str) -> Result<SqlFragment> {
327        Self::filter_sql_with(filter, pg_type, None)
328    }
329
330    /// [`filter_sql`](Self::filter_sql) for a column whose schema declared how
331    /// its values are written: `parser` reads the filter's value, as it does
332    /// for a filter at the top level.
333    pub fn filter_sql_with(
334        filter: &crate::api_request::Filter,
335        pg_type: &str,
336        parser: Option<&str>,
337    ) -> Result<SqlFragment> {
338        let mut coercible = CoercibleFilter::from_filter(filter, pg_type);
339        coercible.field.transform = parser.map(str::to_string);
340        Self::build_filter(&coercible)
341    }
342
343    /// Build the SQL for a logic tree against a table whose column types
344    /// `type_resolver` supplies.
345    ///
346    /// Exposed for the same reason as `filter_sql`: an embedded resource's
347    /// `and=`/`or=` is applied inside a subquery the embedding path assembles
348    /// itself, without going through a full plan.
349    pub fn logic_sql<F>(
350        tree: &crate::api_request::LogicTree,
351        type_resolver: F,
352    ) -> Result<SqlFragment>
353    where
354        F: Fn(&str) -> String + Copy,
355    {
356        Self::logic_sql_with(tree, type_resolver, |_| None)
357    }
358
359    /// [`logic_sql`](Self::logic_sql) where `parser` names, per column, the
360    /// function that reads a filter's value for it (see
361    /// [`filter_sql_with`](Self::filter_sql_with)).
362    pub fn logic_sql_with<F, P>(
363        tree: &crate::api_request::LogicTree,
364        type_resolver: F,
365        parser: P,
366    ) -> Result<SqlFragment>
367    where
368        F: Fn(&str) -> String + Copy,
369        P: Fn(&str) -> Option<String> + Copy,
370    {
371        fn attach<P: Fn(&str) -> Option<String> + Copy>(tree: &mut CoercibleLogicTree, parser: P) {
372            match tree {
373                CoercibleLogicTree::Expr { children, .. } => {
374                    children.iter_mut().for_each(|child| attach(child, parser))
375                }
376                CoercibleLogicTree::Stmt(filter) => {
377                    filter.field.transform = parser(&filter.field.name)
378                }
379                CoercibleLogicTree::NullEmbed { .. } => {}
380            }
381        }
382        let mut coercible = CoercibleLogicTree::from_logic_tree(tree, type_resolver);
383        attach(&mut coercible, parser);
384        Self::build_logic_tree(&coercible)
385    }
386
387    fn build_filter(filter: &CoercibleFilter) -> Result<SqlFragment> {
388        Self::build_filter_in(None, filter)
389    }
390
391    fn build_filter_in(qualifier: Option<&str>, filter: &CoercibleFilter) -> Result<SqlFragment> {
392        let mut frag = SqlFragment::new();
393
394        // Negation wraps the whole comparison. Placing `NOT` between the column
395        // and the operator only parses for a few operators -- `col NOT LIKE $1`
396        // is valid but `col NOT = $1` is a syntax error -- so the comparison is
397        // parenthesised instead, which is correct for every operator.
398        if filter.op_expr.negated {
399            frag.push("NOT (");
400        }
401
402        // Column name.
403        //
404        // A text-search operator wants a `tsvector` on the left. A column that
405        // is not already one is wrapped, so `text_search=fts.x` searches the
406        // text instead of failing to find an operator. A domain over tsvector
407        // is already one, hence the prefix test rather than an equality.
408        //
409        // The language belongs on both sides: `to_tsvector('french', col) @@
410        // to_tsquery('french', $1)`. Left off the left-hand side the column is
411        // lexed with the default configuration -- English -- and a French
412        // query then matches nothing, quietly and with a 200.
413        let to_tsvector = match &filter.op_expr.operation {
414            crate::api_request::Operation::Fts { language, .. }
415                if !filter.field.ir_type.starts_with("tsvector") =>
416            {
417                Some(language.clone())
418            }
419            _ => None,
420        };
421        if let Some(language) = &to_tsvector {
422            frag.push("to_tsvector(");
423            if let Some(language) = language {
424                frag.push_typed_param(language.clone(), "regconfig");
425                frag.push(", ");
426            }
427        }
428        push_qualified_field_ref(&mut frag, qualifier, &filter.field);
429        if to_tsvector.is_some() {
430            frag.push(")");
431        }
432
433        // Filter values are always bound as text, so a comparison against a
434        // non-text column needs an explicit cast on the placeholder -- without
435        // it PostgreSQL rejects the query with `operator does not exist:
436        // integer = text`. A JSON path already yields text, so it is left as-is.
437        let cast = if filter.field.json_path.is_empty() {
438            castable_type(&filter.field.ir_type)
439        } else {
440            // A JSON path leaves either `jsonb` (`->`) or `text` (`->>`) on the
441            // left. Text needs no cast, but `jsonb = $1` with the placeholder
442            // bound as text finds no operator, so the value is cast to match.
443            json_path_result_cast(&filter.field.json_path)
444        };
445
446        // `match` is `~`, and on an `ltree` the right-hand side of `~` is an
447        // `lquery` rather than another `ltree`: `path=match.*.Science` is a
448        // pattern, not a path. Casting it to the column's own type -- which is
449        // what every other operator wants -- finds no operator at all.
450        let cast = match (&filter.op_expr.operation, filter.field.ir_type.as_str()) {
451            (
452                crate::api_request::Operation::Quant {
453                    op:
454                        crate::api_request::QuantOperator::Match
455                        | crate::api_request::QuantOperator::IMatch,
456                    quantifier: None,
457                    ..
458                },
459                "ltree",
460            ) => Some("lquery"),
461            _ => cast,
462        };
463        // A schema that declared how one of its domains is written also
464        // declared how it is read: the cast parses the value the client sent,
465        // in its own spelling, rather than PostgreSQL's input function for the
466        // type underneath.
467        let parser = filter.field.transform.as_deref();
468        let push_value = |frag: &mut SqlFragment, value: String| {
469            if let Some(parser) = parser {
470                frag.push(parser);
471                frag.push("(");
472                frag.push_param(value);
473                frag.push(")");
474                return;
475            }
476            match cast {
477                Some(pg_type) => {
478                    frag.push_typed_param(value, pg_type);
479                }
480                None => {
481                    frag.push_param(value);
482                }
483            }
484        };
485
486        // Operation
487        match &filter.op_expr.operation {
488            crate::api_request::Operation::Simple { op, value } => {
489                frag.push(" ");
490                frag.push(op.to_sql());
491                frag.push(" ");
492                push_value(&mut frag, value.clone());
493            }
494            crate::api_request::Operation::Quant {
495                op,
496                quantifier,
497                value,
498            } => {
499                // PostgREST spells the LIKE wildcard `*` rather than `%`, and
500                // maps it unconditionally -- `*` is never a literal asterisk in
501                // a like/ilike operand. Other operators take the value as-is,
502                // so `match`/`imatch` regexes keep their own `*`.
503                let value = &match op {
504                    crate::api_request::QuantOperator::Like
505                    | crate::api_request::QuantOperator::ILike => value.replace('*', "%"),
506                    _ => value.clone(),
507                };
508                frag.push(" ");
509                frag.push(op.to_sql());
510                frag.push(" ");
511                // PostgREST writes a `like`/`ilike` operand as an untyped
512                // literal (`SqlFragment.hs`), so PostgreSQL resolves the
513                // operator from the column's type and what it makes of the
514                // text -- and says `color ~~* unknown` where there is none,
515                // rather than a type this side chose. It is neither parsed by
516                // a column's representation nor cast to the column's type.
517                // The literal is quoted by `quote_literal`: a bound parameter
518                // would carry the type `text`.
519                if matches!(
520                    op,
521                    crate::api_request::QuantOperator::Like
522                        | crate::api_request::QuantOperator::ILike
523                ) {
524                    match quantifier {
525                        Some(crate::api_request::OpQuantifier::Any) => {
526                            frag.push("ANY(");
527                        }
528                        Some(crate::api_request::OpQuantifier::All) => {
529                            frag.push("ALL(");
530                        }
531                        None => {}
532                    };
533                    frag.push(&postrust_sql::quote_literal(value));
534                    if quantifier.is_some() {
535                        frag.push(")");
536                    }
537                } else if let Some(q) = quantifier {
538                    match q {
539                        crate::api_request::OpQuantifier::Any => frag.push("ANY("),
540                        crate::api_request::OpQuantifier::All => frag.push("ALL("),
541                    };
542                    // A quantified comparison takes an array of the column's
543                    // type. Array-typed columns are already handled by the
544                    // element cast, so they are left alone.
545                    match cast.filter(|t| !t.starts_with('_')) {
546                        Some(pg_type) => {
547                            frag.push_typed_param(value.clone(), &format!("{}[]", pg_type));
548                        }
549                        None => {
550                            frag.push_param(value.clone());
551                        }
552                    }
553                    frag.push(")");
554                } else {
555                    push_value(&mut frag, value.clone());
556                }
557            }
558            crate::api_request::Operation::In(values) if values.is_empty() => {
559                // `IN ()` is a syntax error. The empty array says the same
560                // thing and is a single expression, so it needs no parentheses
561                // of its own wherever the filter ends up. It is false for
562                // every value, nulls included, which is what makes `not.in.()`
563                // match everything.
564                frag.push(" = ANY('{}')");
565            }
566            crate::api_request::Operation::In(values) => {
567                frag.push(" IN (");
568                for (i, v) in values.iter().enumerate() {
569                    if i > 0 {
570                        frag.push(", ");
571                    }
572                    push_value(&mut frag, v.clone());
573                }
574                frag.push(")");
575            }
576            crate::api_request::Operation::Is(is_val) => {
577                frag.push(" IS ");
578                frag.push(is_val.to_sql());
579            }
580            crate::api_request::Operation::IsDistinctFrom(value) => {
581                frag.push(" IS DISTINCT FROM ");
582                push_value(&mut frag, value.clone());
583            }
584            crate::api_request::Operation::Fts {
585                op,
586                language,
587                value,
588            } => {
589                frag.push(" @@ ");
590                frag.push(op.to_function());
591                frag.push("(");
592                if let Some(lang) = language {
593                    // The text-search functions take their configuration as a
594                    // `regconfig`, and there is no `to_tsquery(text, text)` to
595                    // fall back on -- bound as plain text the call resolves to
596                    // no function at all.
597                    frag.push_typed_param(lang.clone(), "regconfig");
598                    frag.push(", ");
599                }
600                // The query is text whatever the column holds, so it never
601                // takes the column's own cast.
602                frag.push_param(value.clone());
603                frag.push(")");
604            }
605        }
606
607        if filter.op_expr.negated {
608            frag.push(")");
609        }
610
611        Ok(frag)
612    }
613
614    /// Build an ORDER BY term.
615    fn build_order_term(term: &CoercibleOrderTerm) -> OrderExpr {
616        // A computed field is a call, not a column, and ordering by its name
617        // asks for a column the table does not have. Everything that reads a
618        // field reference has to go through the same place, or the ones that
619        // do not silently mean something else.
620        let mut order = if term.field.json_path.is_empty() && term.field.computed.is_none() {
621            OrderExpr::new(&term.field.name)
622        } else {
623            let mut frag = SqlFragment::new();
624            push_field_ref(&mut frag, &term.field);
625            // `OrderExpr` carries SQL and no parameters, so anything bound
626            // here would be dropped and every `$n` after it would be reading
627            // the wrong value -- silently, and only for the requests that take
628            // this branch. Nothing on this path binds today; this is what says
629            // so when something starts to.
630            debug_assert!(
631                frag.params().is_empty(),
632                "an ORDER BY term bound a parameter, which this discards: {}",
633                frag.sql()
634            );
635            OrderExpr::raw(frag.sql())
636        };
637
638        if let Some(dir) = &term.direction {
639            order = match dir {
640                crate::api_request::OrderDirection::Asc => order.asc(),
641                crate::api_request::OrderDirection::Desc => order.desc(),
642            };
643        }
644
645        if let Some(nulls) = &term.nulls {
646            order = match nulls {
647                crate::api_request::OrderNulls::First => order.nulls_first(),
648                crate::api_request::OrderNulls::Last => order.nulls_last(),
649            };
650        }
651
652        order
653    }
654
655    /// Build a mutation query.
656    pub fn build_mutate(plan: &MutatePlan) -> Result<SqlFragment> {
657        match plan {
658            MutatePlan::Insert {
659                target,
660                columns,
661                body,
662                on_conflict,
663                where_clauses,
664                returning,
665                reports_inserted,
666                counts_inserted,
667                apply_defaults,
668                ..
669            } => {
670                let qi = postrust_sql::identifier::QualifiedIdentifier::new(
671                    &target.schema,
672                    &target.name,
673                );
674
675                let mut frag = SqlFragment::new();
676                frag.push("INSERT INTO ");
677                frag.push(&from_qi(&qi));
678
679                let object = body
680                    .as_ref()
681                    .map(|body| String::from_utf8_lossy(body).trim_start().starts_with('{'))
682                    .unwrap_or(true);
683
684                match (body, columns.is_empty()) {
685                    // A body naming no columns inserts rows of defaults -- one
686                    // for `{}`, and one per element for an array, which is
687                    // none at all for `[]`. `SELECT` with no columns is what
688                    // says "a row, whatever the table's defaults are".
689                    (Some(body), true) if !object => {
690                        frag.push(" SELECT FROM (SELECT ");
691                        frag.push_param(String::from_utf8_lossy(body).into_owned());
692                        frag.push(
693                            "::json AS json_data) pgrst_payload, LATERAL \
694                             (SELECT FROM json_array_elements(pgrst_payload.json_data)) pgrst_body",
695                        );
696                    }
697                    (_, true) => {
698                        frag.push(" DEFAULT VALUES");
699                    }
700                    (Some(body), false) => {
701                        frag.push(" (");
702                        push_column_list(&mut frag, columns);
703                        frag.push(") SELECT ");
704                        for (i, column) in columns.iter().enumerate() {
705                            if i > 0 {
706                                frag.push(", ");
707                            }
708                            frag.push("pgrst_body.");
709                            frag.push(&escape_ident(&column.name));
710                        }
711                        frag.push(" ");
712                        push_json_body(&mut frag, columns, body, false, *apply_defaults);
713
714                        // PUT names the row in the URL as well as in the body,
715                        // and the two have to agree. The conditions are
716                        // written against the body, so a row naming another
717                        // key is left unwritten rather than writing the wrong
718                        // one -- and the count that comes back then says
719                        // whether the request meant exactly one row.
720                        let merging = matches!(
721                            on_conflict,
722                            Some((crate::api_request::PreferResolution::MergeDuplicates, _))
723                        );
724                        let count = *counts_inserted && merging;
725                        if !where_clauses.is_empty() || count {
726                            frag.push(" WHERE ");
727                            // First, so every candidate row is counted
728                            // whether or not the conditions then keep it.
729                            if count {
730                                frag.push(&inserted_counter(true));
731                                if !where_clauses.is_empty() {
732                                    frag.push(" AND ");
733                                }
734                            }
735                            for (i, clause) in where_clauses.iter().enumerate() {
736                                if i > 0 {
737                                    frag.push(" AND ");
738                                }
739                                frag.append(Self::build_logic_tree_in(Some("pgrst_body"), clause)?);
740                            }
741                        }
742                    }
743                    (None, false) => {
744                        frag.push(" DEFAULT VALUES");
745                    }
746                }
747
748                if let Some((resolution, conflict_cols)) = on_conflict {
749                    frag.push(" ON CONFLICT (");
750                    for (i, column) in conflict_cols.iter().enumerate() {
751                        if i > 0 {
752                            frag.push(", ");
753                        }
754                        frag.push(&escape_ident(column));
755                    }
756                    frag.push(") DO ");
757                    match resolution {
758                        crate::api_request::PreferResolution::IgnoreDuplicates => {
759                            frag.push("NOTHING");
760                        }
761                        crate::api_request::PreferResolution::MergeDuplicates
762                            if columns.is_empty() =>
763                        {
764                            frag.push("NOTHING");
765                        }
766                        crate::api_request::PreferResolution::MergeDuplicates => {
767                            frag.push("UPDATE SET ");
768                            for (i, column) in columns.iter().enumerate() {
769                                if i > 0 {
770                                    frag.push(", ");
771                                }
772                                frag.push(&escape_ident(&column.name));
773                                frag.push(" = EXCLUDED.");
774                                frag.push(&escape_ident(&column.name));
775                            }
776                            // A row that conflicted was not created after all.
777                            if *counts_inserted {
778                                frag.push(" WHERE ");
779                                frag.push(&inserted_counter(false));
780                            }
781                        }
782                    }
783                }
784
785                push_returning(&mut frag, &target.name, returning);
786
787                // Whether each row was inserted or merged into an existing
788                // one, which is the difference between 201 and 200 and is
789                // knowable only here: `xmax` is zero on a row this statement
790                // created and non-zero on one it updated.
791                if on_conflict.is_some() && *reports_inserted && !returning.is_empty() {
792                    if *counts_inserted {
793                        // The running count, read once the row has been
794                        // counted: above zero as soon as any row was created.
795                        frag.push(", (coalesce(nullif(current_setting('pgrst.inserted', true), '')::int, 0) > 0) AS ");
796                    } else {
797                        frag.push(", (xmax = 0) AS ");
798                    }
799                    frag.push(&escape_ident(INSERTED_COLUMN));
800                }
801
802                Ok(frag)
803            }
804
805            MutatePlan::Update {
806                target,
807                columns,
808                body,
809                where_clauses,
810                returning,
811                apply_defaults,
812                ..
813            } => {
814                let qi = postrust_sql::identifier::QualifiedIdentifier::new(
815                    &target.schema,
816                    &target.name,
817                );
818
819                // An update that assigns nothing is not valid SQL, and it is
820                // also not an error: `PATCH` with `{}` matches rows and
821                // changes none of them. Selecting no rows from the table gives
822                // the same answer with the same column names, which is what a
823                // `?select=` over the result needs.
824                if columns.is_empty() || body.is_none() {
825                    let mut frag = SqlFragment::new();
826                    frag.push("SELECT * FROM ");
827                    frag.push(&from_qi(&qi));
828                    frag.push(" WHERE false");
829                    return Ok(frag);
830                }
831
832                let body = body.as_ref().expect("checked above");
833                let mut frag = SqlFragment::new();
834                frag.push("UPDATE ");
835                frag.push(&from_qi(&qi));
836                frag.push(" SET ");
837                for (i, column) in columns.iter().enumerate() {
838                    if i > 0 {
839                        frag.push(", ");
840                    }
841                    frag.push(&escape_ident(&column.name));
842                    frag.push(" = pgrst_body.");
843                    frag.push(&escape_ident(&column.name));
844                }
845                frag.push(" ");
846                push_json_body(&mut frag, columns, body, true, *apply_defaults);
847
848                if !where_clauses.is_empty() {
849                    frag.push(" WHERE ");
850                    for (i, clause) in where_clauses.iter().enumerate() {
851                        if i > 0 {
852                            frag.push(" AND ");
853                        }
854                        frag.append(Self::build_logic_tree_in(Some(&target.name), clause)?);
855                    }
856                }
857
858                push_returning(&mut frag, &target.name, returning);
859                Ok(frag)
860            }
861
862            MutatePlan::Delete {
863                target,
864                where_clauses,
865                returning,
866            } => {
867                let qi = postrust_sql::identifier::QualifiedIdentifier::new(
868                    &target.schema,
869                    &target.name,
870                );
871
872                let mut frag = SqlFragment::new();
873                frag.push("DELETE FROM ");
874                frag.push(&from_qi(&qi));
875
876                if !where_clauses.is_empty() {
877                    frag.push(" WHERE ");
878                    for (i, clause) in where_clauses.iter().enumerate() {
879                        if i > 0 {
880                            frag.push(" AND ");
881                        }
882                        frag.append(Self::build_logic_tree(clause)?);
883                    }
884                }
885
886                push_returning(&mut frag, &target.name, returning);
887                Ok(frag)
888            }
889        }
890    }
891
892    /// Build an RPC call query.
893    pub fn build_call(plan: &CallPlan, read: Option<&ReadPlanTree>) -> Result<SqlFragment> {
894        let qi = postrust_sql::identifier::QualifiedIdentifier::new(
895            &plan.function.schema,
896            &plan.function.name,
897        );
898
899        // The call itself is the source of rows; the read plan, when there is
900        // one, shapes them exactly as it would shape a table's.
901        // A result this process cannot decode is rendered by the database,
902        // exactly as a column of such a type is. Without it a function
903        // returning `xml` or `bytea` answered null.
904        // A composite return -- OUT parameters, `RETURNS TABLE`, a row type --
905        // already expands to its own columns, and wrapping it would bury them
906        // under the function's name.
907        // A bare `record` is the other case: PostgreSQL will not put one in a
908        // `FROM` clause without being told its columns, but it will hand the
909        // value straight to `to_jsonb`, which reads the names off the record
910        // itself. That is where `returns_record()` gets `{"id": 1, ...}` from
911        // without anyone having declared what its columns are.
912        // A function whose return type is a media-type domain has already
913        // produced the response body. Wrapping it in JSON would make the
914        // response a JSON string *about* a PNG rather than the PNG.
915        let render_as_json = read.is_none()
916            && plan.media_type.is_none()
917            && !plan.returns_composite
918            && plan
919                .return_type
920                .as_deref()
921                .map(|t| !decodable_type(t) || t == "record")
922                .unwrap_or(false);
923
924        let mut frag = SqlFragment::new();
925        frag.push("SELECT ");
926        if render_as_json {
927            // Called in the select list rather than the `FROM`: a
928            // set-returning function there still yields a row per result, and
929            // a `record` needs no column list to be called this way.
930            frag.push("to_jsonb(pgrst_call.pgrst_scalar) AS ");
931            frag.push(&escape_ident(&plan.function.name));
932            frag.push(" FROM (SELECT ");
933            frag.push(&from_qi(&qi));
934            frag.push("(");
935        }
936        match read.filter(|tree| !tree.root.select.is_empty()) {
937            Some(tree) => {
938                for (i, field) in tree.root.select.iter().enumerate() {
939                    if i > 0 {
940                        frag.push(", ");
941                    }
942                    let column = Self::build_select_field(field)?;
943                    frag.append(column);
944                }
945            }
946            None if !render_as_json => push_declared_columns(&mut frag, plan),
947            None => {}
948        }
949        if !render_as_json {
950            frag.push(" FROM ");
951            frag.push(&from_qi(&qi));
952            frag.push("(");
953        }
954
955        // Arguments come off the wire as strings. Casting each one to the type
956        // the function actually declares is what lets PostgreSQL resolve the
957        // signature; binding everything as `text` only works for text-taking
958        // functions. An argument the schema cache doesn't know is left
959        // untyped, so PostgreSQL applies its own inference rather than failing.
960        let declared_type = |name: &str| {
961            plan.param_types
962                .iter()
963                .find(|(n, _)| n == name)
964                .map(|(_, t)| t.clone())
965        };
966
967        match &plan.params {
968            CallParams::Named(params) => {
969                for (i, (name, value)) in params.iter().enumerate() {
970                    if i > 0 {
971                        frag.push(", ");
972                    }
973                    // A variadic parameter is passed as the whole tail, which
974                    // is what `VARIADIC` says; `v => array[...]` finds no
975                    // function, since no signature takes an array there.
976                    if plan.variadic_params.iter().any(|v| v == name) {
977                        frag.push("VARIADIC ");
978                        frag.push(&escape_ident(name));
979                        frag.push(" := ");
980                    } else {
981                        frag.push(&escape_ident(name));
982                        frag.push(" => ");
983                    }
984                    match declared_type(name) {
985                        Some(pg_type) => {
986                            frag.push_typed_param(SqlParam::Text(value.clone()), &pg_type)
987                        }
988                        None => frag.push_param(SqlParam::Text(value.clone())),
989                    };
990                }
991            }
992            CallParams::Positional(values) => {
993                for (i, value) in values.iter().enumerate() {
994                    if i > 0 {
995                        frag.push(", ");
996                    }
997                    match plan.param_types.get(i) {
998                        Some((_, pg_type)) => {
999                            frag.push_typed_param(SqlParam::Text(value.clone()), pg_type)
1000                        }
1001                        None => frag.push_param(SqlParam::Text(value.clone())),
1002                    };
1003                }
1004            }
1005            CallParams::SingleObject(body) => {
1006                let body_str = String::from_utf8_lossy(body);
1007                frag.push_param(SqlParam::Text(body_str.to_string()));
1008            }
1009            CallParams::SingleUnnamed { body, pg_type } => {
1010                match body {
1011                    Some(body) => frag.push_typed_param(
1012                        SqlParam::Text(String::from_utf8_lossy(body).into_owned()),
1013                        pg_type,
1014                    ),
1015                    // No body is that parameter's null. Casting it is what
1016                    // tells PostgreSQL which signature is meant, where the
1017                    // name carries more than one.
1018                    None => frag.push(&format!("NULL::{}", pg_type)),
1019                };
1020            }
1021            CallParams::None => {}
1022        }
1023
1024        frag.push(")");
1025        if render_as_json {
1026            frag.push(" AS pgrst_scalar) pgrst_call");
1027        }
1028
1029        // A function returning a table's rows is aliased to that table.
1030        //
1031        // PostgreSQL names the range-table entry after the *function*, so
1032        // `FROM test.search(...)` puts `search` in scope and not `items`. An
1033        // unqualified column resolves either way, there being only one entry
1034        // to resolve against -- which is why filters and ordering always
1035        // worked and hid this. A computed column does not: it is a function of
1036        // the whole row, written `test.always_true(items)`, and naming the row
1037        // is the whole point of it. Unaliased, that is `column "items" does
1038        // not exist` for a field the same request answers over the table
1039        // itself.
1040        if let Some(alias) = read.map(|tree| tree.root.from.name.as_str()) {
1041            if !render_as_json && !alias.is_empty() {
1042                frag.push(" AS ");
1043                frag.push(&escape_ident(alias));
1044            }
1045        }
1046
1047        // Filters, ordering and paging over the returned rows.
1048        if let Some(tree) = read {
1049            for (i, clause) in tree.root.where_clauses.iter().enumerate() {
1050                frag.push(if i == 0 { " WHERE " } else { " AND " });
1051                let expr = Self::build_logic_tree(clause)?;
1052                frag.append(expr);
1053            }
1054
1055            for (i, term) in tree.root.order.iter().enumerate() {
1056                frag.push(if i == 0 { " ORDER BY " } else { ", " });
1057                let order = Self::build_order_term(term).into_fragment();
1058                frag.append(order);
1059            }
1060
1061            if let Some(limit) = tree.root.range.limit {
1062                frag.push(&format!(" LIMIT {}", limit));
1063            }
1064            if tree.root.range.offset > 0 {
1065                frag.push(&format!(" OFFSET {}", tree.root.range.offset));
1066            }
1067        }
1068
1069        Ok(frag)
1070    }
1071}
1072
1073/// Return the type to cast a bound filter value to, if it is safe to do so.
1074///
1075/// The type name is interpolated into SQL, so only bare type names are
1076/// accepted: anything else (an empty type, a parameterised type such as
1077/// `character varying(255)`, or the `ARRAY`/`USER-DEFINED` placeholders that
1078/// `information_schema` reports) yields `None` and the value is bound
1079/// uncast, preserving the previous behaviour.
1080/// The column that says whether a row was created or merged into.
1081pub const INSERTED_COLUMN: &str = "pgrst_inserted";
1082
1083/// PostgREST's `pgrst.inserted` counter (SqlFragment.hs addConfigPgrstInserted):
1084/// raised for each candidate row, lowered for each one that conflicted. The
1085/// comparison keeps the condition true -- it is evaluated only for its effect.
1086fn inserted_counter(add: bool) -> String {
1087    let (symbol, sentinel) = if add { ("+", "0") } else { ("-", "-1") };
1088    format!(
1089        "set_config('pgrst.inserted', (coalesce(nullif(current_setting('pgrst.inserted', true), '')::int, 0) {} 1)::text, true) <> '{}'",
1090        symbol, sentinel
1091    )
1092}
1093
1094/// The columns a mutation writes, as a comma-separated identifier list.
1095fn push_column_list(frag: &mut SqlFragment, columns: &[crate::plan::CoercibleField]) {
1096    for (i, column) in columns.iter().enumerate() {
1097        if i > 0 {
1098            frag.push(", ");
1099        }
1100        frag.push(&escape_ident(&column.name));
1101    }
1102}
1103
1104/// The `FROM` clause that turns a JSON body into rows of the table's columns.
1105///
1106/// The body is read as a record set of exactly the columns being written, each
1107/// typed as the column is -- or as `json`, where a data representation is going
1108/// to parse it -- so PostgreSQL does the conversion and this process never has
1109/// to guess at a literal's spelling.
1110///
1111/// `single` reads one object rather than an array, which is what a `PATCH`
1112/// body is.
1113fn push_json_body(
1114    frag: &mut SqlFragment,
1115    columns: &[crate::plan::CoercibleField],
1116    body: &bytes::Bytes,
1117    single: bool,
1118    apply_defaults: bool,
1119) {
1120    let body = String::from_utf8_lossy(body).into_owned();
1121    let object = body.trim_start().starts_with('{');
1122
1123    // `Prefer: missing=default` asks for a column the body left out to take
1124    // the value the table would have given it, rather than null. The defaults
1125    // are merged underneath the body, so anything the body did name still
1126    // wins -- which is why this is `defaults || body` and not the reverse.
1127    let defaults: Vec<&crate::plan::CoercibleField> = match apply_defaults {
1128        true => columns.iter().filter(|c| c.default.is_some()).collect(),
1129        false => Vec::new(),
1130    };
1131    let merged = !defaults.is_empty();
1132
1133    frag.push("FROM (SELECT ");
1134    frag.push_param(body);
1135    frag.push(match merged {
1136        true => "::jsonb AS json_data) pgrst_payload, ",
1137        false => "::json AS json_data) pgrst_payload, ",
1138    });
1139
1140    if merged {
1141        let mut pairs = String::new();
1142        for (i, column) in defaults.iter().enumerate() {
1143            if i > 0 {
1144                pairs.push_str(", ");
1145            }
1146            pairs.push_str(&format!(
1147                "{}, {}",
1148                postrust_sql::quote_literal(&column.name),
1149                column.default.as_deref().unwrap_or("NULL")
1150            ));
1151        }
1152        frag.push(match object {
1153            true => "LATERAL (SELECT jsonb_build_object(",
1154            false => "LATERAL (SELECT jsonb_agg(jsonb_build_object(",
1155        });
1156        frag.push(&pairs);
1157        frag.push(match object {
1158            true => ") || pgrst_payload.json_data AS val) pgrst_defaults, ",
1159            false => {
1160                ") || pgrst_element) AS val \
1161                 FROM jsonb_array_elements(pgrst_payload.json_data) pgrst_element) \
1162                 pgrst_defaults, "
1163            }
1164        });
1165    }
1166
1167    frag.push("LATERAL (SELECT ");
1168    for (i, column) in columns.iter().enumerate() {
1169        if i > 0 {
1170            frag.push(", ");
1171        }
1172        match &column.transform {
1173            Some(parser) => {
1174                frag.push(parser);
1175                frag.push("(");
1176                frag.push(&escape_ident(&column.name));
1177                frag.push(") AS ");
1178                frag.push(&escape_ident(&column.name));
1179            }
1180            None => {
1181                frag.push(&escape_ident(&column.name));
1182            }
1183        }
1184    }
1185    // `json_to_record` takes one object and `json_to_recordset` an array, and
1186    // which one the body is is the body's own business -- an update written
1187    // with a one-element array is still an update. What makes it single is the
1188    // `LIMIT 1` below, not a claim about the body's shape: reading an array
1189    // with `json_to_record` is an error about `populate_composite` that says
1190    // nothing to the client that sent it.
1191    frag.push(match (merged, object) {
1192        (false, true) => " FROM json_to_record(pgrst_payload.json_data) AS _(",
1193        (false, false) => " FROM json_to_recordset(pgrst_payload.json_data) AS _(",
1194        (true, true) => " FROM jsonb_to_record(pgrst_defaults.val) AS _(",
1195        (true, false) => " FROM jsonb_to_recordset(pgrst_defaults.val) AS _(",
1196    });
1197    for (i, column) in columns.iter().enumerate() {
1198        if i > 0 {
1199            frag.push(", ");
1200        }
1201        frag.push(&escape_ident(&column.name));
1202        frag.push(" ");
1203        frag.push(castable_type(&column.ir_type).unwrap_or("text"));
1204    }
1205    // One paren closes the column definition list; the `LIMIT 1` then applies
1206    // to the lateral subquery, whose own paren closes after it.
1207    //
1208    // An update writes one set of values however many the body offers, so it
1209    // takes the first. Without this an array body of two objects would update
1210    // every matching row twice over.
1211    frag.push(match single {
1212        true => ") LIMIT 1) pgrst_body",
1213        false => ")) pgrst_body",
1214    });
1215}
1216
1217/// The column a mutation returns when the response reads none of its own.
1218///
1219/// It exists to be counted, never to be read: the body is empty in every case
1220/// that produces it.
1221pub const AFFECTED_COLUMN: &str = "pgrst_affected";
1222
1223/// Column carrying the written row whole, for a computed relationship.
1224///
1225/// A computed relationship is a function of the parent row, and after a
1226/// mutation the parent is a CTE whose row type is anonymous -- `record`, which
1227/// PostgreSQL will not cast to the table's composite type. Inside the
1228/// statement the real table is still in scope, so the row is taken there,
1229/// where a bare reference to it yields the composite, and travels out through
1230/// `RETURNING` as an ordinary column. It is stripped from the response like
1231/// any other column added for embedding.
1232pub const PARENT_ROW_COLUMN: &str = "pgrst_parent_row";
1233
1234/// The `RETURNING` list, qualified by the relation being written.
1235///
1236/// `RETURNING` sees everything in the statement's scope, which for an
1237/// `UPDATE ... FROM` includes the body -- and a bare column name there is
1238/// ambiguous for every column the update writes.
1239fn push_returning(frag: &mut SqlFragment, relation: &str, returning: &[String]) {
1240    // A statement whose result nothing reads still has to say how many rows it
1241    // touched, and the count is the number of rows it returns. A constant is
1242    // what says "one row per row affected" without naming a column the caller
1243    // may not be allowed to read.
1244    if returning.is_empty() {
1245        frag.push(" RETURNING 1 AS ");
1246        frag.push(&escape_ident(AFFECTED_COLUMN));
1247        return;
1248    }
1249    frag.push(" RETURNING ");
1250    for (i, column) in returning.iter().enumerate() {
1251        if i > 0 {
1252            frag.push(", ");
1253        }
1254        // The row itself, not a column of it. A bare reference to the relation
1255        // is the whole row typed as the table's composite, which is the one
1256        // thing a computed relationship can be called with -- and this is the
1257        // only place it can be taken, because one level up the CTE has turned
1258        // it into a `record`.
1259        if column == PARENT_ROW_COLUMN {
1260            frag.push(&escape_ident(relation));
1261            frag.push(" AS ");
1262            frag.push(&escape_ident(PARENT_ROW_COLUMN));
1263            continue;
1264        }
1265        frag.push(&escape_ident(relation));
1266        frag.push(".");
1267        frag.push(&escape_ident(column));
1268    }
1269}
1270
1271/// A column reference, converted to JSON first where the path requires it.
1272fn push_field_ref(frag: &mut SqlFragment, field: &crate::plan::CoercibleField) {
1273    push_qualified_field_ref(frag, None, field)
1274}
1275
1276/// The same, with the column qualified by a relation alias.
1277fn push_qualified_field_ref(
1278    frag: &mut SqlFragment,
1279    qualifier: Option<&str>,
1280    field: &crate::plan::CoercibleField,
1281) {
1282    // A computed field is a function of the whole row. PostgreSQL would also
1283    // accept `items.always_true` and resolve it to the same call, but only
1284    // where the reference is qualified by the relation -- which a bare column
1285    // name here is not -- so the call is written out.
1286    let column = match &field.computed {
1287        Some(computed) => format!(
1288            "{}.{}({}::{}.{})",
1289            escape_ident(&computed.function.schema),
1290            escape_ident(&computed.function.name),
1291            escape_ident(&computed.relation),
1292            escape_ident(&computed.row_type.schema),
1293            escape_ident(&computed.row_type.name),
1294        ),
1295        None => match qualifier {
1296            Some(alias) => format!("{}.{}", escape_ident(alias), escape_ident(&field.name)),
1297            None => escape_ident(&field.name),
1298        },
1299    };
1300
1301    if field.to_json {
1302        frag.push("to_jsonb(");
1303        frag.push(&column);
1304        frag.push(")");
1305    } else {
1306        frag.push(&column);
1307    }
1308    push_json_path(frag, &field.json_path);
1309}
1310
1311/// Project the columns a function declares, rather than asking for `*`.
1312///
1313/// `*` is all a caller can write when the result has no table behind it, and
1314/// it leaves a column of a type this process cannot decode to arrive as null.
1315/// Naming the columns is what lets those be rendered by the database, exactly
1316/// as a table's are. A function that declares none still gets `*`: there is
1317/// nothing better to say.
1318fn push_declared_columns(frag: &mut SqlFragment, plan: &crate::plan::CallPlan) {
1319    if plan.output_columns.is_empty() {
1320        frag.push("*");
1321        return;
1322    }
1323
1324    for (i, (name, pg_type)) in plan.output_columns.iter().enumerate() {
1325        if i > 0 {
1326            frag.push(", ");
1327        }
1328        match decodable_type(pg_type) {
1329            true => {
1330                frag.push(&escape_ident(name));
1331            }
1332            false => {
1333                frag.push("to_jsonb(");
1334                frag.push(&escape_ident(name));
1335                frag.push(") AS ");
1336                frag.push(&escape_ident(name));
1337            }
1338        }
1339    }
1340}
1341
1342/// The type a JSON path leaves on the left of a comparison.
1343///
1344/// `None` for a path ending in `->>`, which is already text -- the type filter
1345/// values are bound as, so no cast is wanted.
1346fn json_path_result_cast(path: &crate::api_request::JsonPath) -> Option<&'static str> {
1347    use crate::api_request::JsonOperation;
1348    match path.last()? {
1349        JsonOperation::Arrow(_) => Some("jsonb"),
1350        JsonOperation::DoubleArrow(_) => None,
1351    }
1352}
1353
1354/// Append a JSON path to a column reference: `"data" -> 'a' ->> 'b'`.
1355///
1356/// Keys are emitted as string literals and indices as bare integers, which is
1357/// what distinguishes `data->'1'` from `data->1` in PostgreSQL. A key is
1358/// whatever the client wrote up to the next `,`, `(`, `)`, `:` or arrow --
1359/// quotes and backslashes included -- so it is written by `quote_literal`,
1360/// which keeps it one literal whatever `standard_conforming_strings` is.
1361fn push_json_path(frag: &mut SqlFragment, path: &crate::api_request::JsonPath) {
1362    use crate::api_request::{JsonOperand, JsonOperation};
1363
1364    for operation in path {
1365        let (arrow, operand) = match operation {
1366            JsonOperation::Arrow(operand) => ("->", operand),
1367            JsonOperation::DoubleArrow(operand) => ("->>", operand),
1368        };
1369
1370        frag.push(" ");
1371        frag.push(arrow);
1372        frag.push(" ");
1373
1374        match operand {
1375            JsonOperand::Key(key) => {
1376                frag.push(&postrust_sql::quote_literal(key));
1377            }
1378            JsonOperand::Idx(index) => {
1379                frag.push(&index.to_string());
1380            }
1381        }
1382    }
1383}
1384
1385/// The name PostgREST gives an unaliased JSON path expression.
1386///
1387/// The last key in the path wins -- `data->a->>b` is reported as `b`. A path
1388/// that ends in an array index has no name to take, so it keeps the column's.
1389fn json_path_alias(column: &str, path: &crate::api_request::JsonPath) -> String {
1390    use crate::api_request::{JsonOperand, JsonOperation};
1391
1392    path.iter()
1393        .rev()
1394        .find_map(|operation| match operation {
1395            JsonOperation::Arrow(JsonOperand::Key(key))
1396            | JsonOperation::DoubleArrow(JsonOperand::Key(key)) => Some(key.clone()),
1397            _ => None,
1398        })
1399        .unwrap_or_else(|| column.to_string())
1400}
1401
1402/// Whether this process can decode a column of this type.
1403///
1404/// The row converter maps a fixed set of types by name and otherwise reads the
1405/// column as text, which only works for what PostgreSQL will hand over as
1406/// text. Anything else -- `xml`, `bytea`, an array, a PostGIS geometry -- fails
1407/// to decode and the column comes back null, so it is rendered in the database
1408/// instead. An empty type is a field with no column behind it, such as
1409/// `count()`, and never reaches this.
1410fn decodable_type(data_type: &str) -> bool {
1411    matches!(
1412        data_type,
1413        "" | "smallint"
1414            | "integer"
1415            | "bigint"
1416            | "numeric"
1417            | "decimal"
1418            | "real"
1419            | "double precision"
1420            | "boolean"
1421            | "text"
1422            | "character varying"
1423            | "character"
1424            | "name"
1425            | "date"
1426            | "time"
1427            | "time without time zone"
1428            | "time with time zone"
1429            | "timestamp"
1430            | "timestamp without time zone"
1431            | "timestamp with time zone"
1432            | "uuid"
1433            | "json"
1434            | "jsonb"
1435    )
1436}
1437
1438/// Whether a column cast to `cast` comes back in a type the row converter
1439/// reads natively: what it maps by name, and what it reads as text.
1440fn decodable_cast(cast: &str) -> bool {
1441    if cast.starts_with('_') || cast.ends_with("[]") {
1442        return false;
1443    }
1444    matches!(
1445        cast.to_ascii_lowercase().as_str(),
1446        "smallint"
1447            | "int2"
1448            | "integer"
1449            | "int"
1450            | "int4"
1451            | "bigint"
1452            | "int8"
1453            | "real"
1454            | "float4"
1455            | "double precision"
1456            | "float8"
1457            | "numeric"
1458            | "decimal"
1459            | "boolean"
1460            | "bool"
1461            | "text"
1462            | "varchar"
1463            | "character varying"
1464            | "char"
1465            | "character"
1466            | "bpchar"
1467            | "name"
1468            | "citext"
1469            | "date"
1470            | "time"
1471            | "time without time zone"
1472            | "time with time zone"
1473            | "timestamp"
1474            | "timestamp without time zone"
1475            | "timestamp with time zone"
1476            | "timestamptz"
1477            | "uuid"
1478            | "json"
1479            | "jsonb"
1480    )
1481}
1482
1483fn castable_type(pg_type: &str) -> Option<&str> {
1484    if pg_type.is_empty() {
1485        return None;
1486    }
1487
1488    // `character` and `bit` name themselves without their length, and casting
1489    // to either truncates to one -- `'10101'::bit` is `bit(1)`. A value on its
1490    // way into a `bit(5)` column has to arrive whole; the column enforces its
1491    // own length when the row is written, which is where that belongs.
1492    let unbounded = match pg_type {
1493        "character" | "bpchar" => Some("varchar"),
1494        "bit" => Some("varbit"),
1495        "character[]" | "bpchar[]" | "_bpchar" => Some("_varchar"),
1496        "bit[]" | "_bit" => Some("_varbit"),
1497        _ => None,
1498    };
1499    if unbounded.is_some() {
1500        return unbounded;
1501    }
1502
1503    let is_bare_name = pg_type
1504        .chars()
1505        .all(|c| c.is_ascii_alphanumeric() || c == '_');
1506
1507    if is_bare_name {
1508        Some(pg_type)
1509    } else {
1510        None
1511    }
1512}
1513
1514#[cfg(test)]
1515mod tests {
1516    use super::*;
1517
1518    #[test]
1519    fn the_inserted_counter_is_raised_per_row_and_lowered_per_conflict() {
1520        assert!(inserted_counter(true).contains("+ 1)::text, true) <> '0'"));
1521        assert!(inserted_counter(false).contains("- 1)::text, true) <> '-1'"));
1522    }
1523
1524    #[test]
1525    fn castable_type_accepts_bare_type_names() {
1526        assert_eq!(castable_type("int4"), Some("int4"));
1527        assert_eq!(castable_type("timestamptz"), Some("timestamptz"));
1528        assert_eq!(castable_type("_text"), Some("_text"));
1529    }
1530
1531    /// A length these types do not carry, and would truncate to if cast.
1532    #[test]
1533    fn castable_type_gives_the_unbounded_spelling_of_a_measured_type() {
1534        assert_eq!(castable_type("character"), Some("varchar"));
1535        assert_eq!(castable_type("bit"), Some("varbit"));
1536        assert_eq!(castable_type("_bpchar"), Some("_varchar"));
1537    }
1538
1539    #[test]
1540    fn castable_type_rejects_unsafe_names() {
1541        assert_eq!(castable_type(""), None);
1542        assert_eq!(castable_type("character varying"), None);
1543        assert_eq!(castable_type("USER-DEFINED"), None);
1544        assert_eq!(castable_type("int4; DROP TABLE users"), None);
1545    }
1546
1547    /// Build the SQL for the single root filter in `query`.
1548    fn filter_sql_for(query: &str, pg_type: &str) -> (String, Vec<String>) {
1549        let params = crate::api_request::parse_query_params(query, false).unwrap();
1550        let frag = QueryBuilder::filter_sql(&params.filters_root[0], pg_type).unwrap();
1551        let bound = frag
1552            .params()
1553            .iter()
1554            .map(|p| format!("{:?}", p))
1555            .collect::<Vec<_>>();
1556        (frag.sql().to_string(), bound)
1557    }
1558
1559    #[test]
1560    fn quantified_comparison_binds_an_array() {
1561        let (sql, params) = filter_sql_for("id=eq(any).{1,2,3}", "int4");
1562        assert!(sql.contains("= ANY("), "got {sql}");
1563        assert!(sql.contains("int4[]"), "got {sql}");
1564        assert_eq!(params.len(), 1);
1565        assert!(params[0].contains("{1,2,3}"), "got {:?}", params[0]);
1566    }
1567
1568    #[test]
1569    fn quantified_all_renders_all() {
1570        let (sql, _) = filter_sql_for("id=lt(all).{4,5}", "int4");
1571        assert!(sql.contains("< ALL("), "got {sql}");
1572    }
1573
1574    #[test]
1575    fn quantified_like_maps_the_wildcard_inside_the_array() {
1576        let (sql, params) = filter_sql_for("name=like(any).{foo*,*bar}", "text");
1577        assert!(sql.contains("ANY('{foo%,%bar}')"), "got {sql}");
1578        assert!(params.is_empty(), "got {params:?}");
1579    }
1580
1581    /// A `like` operand is an untyped literal, as PostgREST writes it: no
1582    /// parameter, no cast to the column's type.
1583    #[test]
1584    fn like_operands_are_untyped_literals() {
1585        let (sql, params) = filter_sql_for("name=ilike.it's*$1", "integer");
1586        assert!(sql.contains("ILIKE 'it''s%$1'"), "got {sql}");
1587        assert!(!sql.contains("::"), "got {sql}");
1588        assert!(params.is_empty(), "got {params:?}");
1589
1590        let (sql, params) = filter_sql_for("name=not.like.a\\b", "text");
1591        assert!(sql.contains("LIKE E'a\\\\b'"), "got {sql}");
1592        assert!(params.is_empty());
1593
1594        // Other operators still bind.
1595        let (_, params) = filter_sql_for("name=eq.x", "text");
1596        assert_eq!(params.len(), 1);
1597    }
1598
1599    /// A cast to a type the row converter cannot read is rendered by the
1600    /// database; one it can read is left alone.
1601    #[test]
1602    fn a_cast_to_an_unreadable_type_is_rendered_as_json() {
1603        let render = |cast: &str| {
1604            let mut field = CoercibleSelectField::simple("nums", "integer");
1605            field.cast = Some(cast.to_string());
1606            QueryBuilder::build_select_field(&field)
1607                .unwrap()
1608                .sql()
1609                .to_string()
1610        };
1611        assert_eq!(render("_int4"), "to_jsonb(\"nums\"::_int4) AS \"nums\"");
1612        assert_eq!(render("int4[]"), "to_jsonb(\"nums\"::int4[]) AS \"nums\"");
1613        assert_eq!(render("int"), "\"nums\"::int");
1614        assert_eq!(render("text"), "\"nums\"::text");
1615    }
1616
1617    #[test]
1618    fn array_column_is_not_double_arrayed() {
1619        // An array-typed column already compares element-wise, so the cast is
1620        // left alone rather than becoming `_text[]`.
1621        let (sql, _) = filter_sql_for("tags=eq(any).{a,b}", "_text");
1622        assert!(sql.contains("= ANY("), "got {sql}");
1623        assert!(!sql.contains("_text[]"), "got {sql}");
1624    }
1625}