Skip to main content

postrust_core/plan/
mutate_plan.rs

1//! Mutation (INSERT/UPDATE/DELETE) query planning.
2
3use super::types::*;
4use crate::api_request::{ApiRequest, Mutation, Payload, PreferResolution, QualifiedIdentifier};
5use crate::error::{Error, Result};
6use crate::schema_cache::Table;
7use serde::{Deserialize, Serialize};
8
9/// A mutation plan.
10#[derive(Clone, Debug, Serialize, Deserialize)]
11pub enum MutatePlan {
12    /// INSERT operation
13    Insert {
14        /// Target table
15        target: QualifiedIdentifier,
16        /// Columns to insert
17        columns: Vec<CoercibleField>,
18        /// Request body (JSON)
19        body: Option<bytes::Bytes>,
20        /// ON CONFLICT handling
21        on_conflict: Option<(PreferResolution, Vec<String>)>,
22        /// WHERE clause (for filtered inserts)
23        where_clauses: Vec<CoercibleLogicTree>,
24        /// RETURNING columns
25        returning: Vec<String>,
26        /// Primary key columns
27        pk_cols: Vec<String>,
28        /// Apply defaults for missing columns
29        apply_defaults: bool,
30        /// Whether the statement can report which rows it created.
31        ///
32        /// On a plain table it asks PostgreSQL for `xmax`; on a view or a
33        /// partitioned table, which will not give that back, it keeps
34        /// PostgREST's own count instead (see `counts_inserted`).
35        #[serde(default)]
36        reports_inserted: bool,
37        /// Whether the count of created rows is kept by hand rather than read
38        /// from `xmax`: a view or a partitioned table. As PostgREST does
39        /// (`pgrst.inserted`, QueryBuilder.hs), a setting is raised once per
40        /// candidate row and lowered once per row that turned out to be an
41        /// update, so what is left is the number of rows created.
42        #[serde(default)]
43        counts_inserted: bool,
44    },
45    /// UPDATE operation
46    Update {
47        /// Target table
48        target: QualifiedIdentifier,
49        /// Columns to update
50        columns: Vec<CoercibleField>,
51        /// Request body (JSON)
52        body: Option<bytes::Bytes>,
53        /// WHERE clauses
54        where_clauses: Vec<CoercibleLogicTree>,
55        /// RETURNING columns
56        returning: Vec<String>,
57        /// Apply defaults for NULL columns
58        apply_defaults: bool,
59    },
60    /// DELETE operation
61    Delete {
62        /// Target table
63        target: QualifiedIdentifier,
64        /// WHERE clauses
65        where_clauses: Vec<CoercibleLogicTree>,
66        /// RETURNING columns
67        returning: Vec<String>,
68    },
69}
70
71impl MutatePlan {
72    /// Create a mutation plan from an API request.
73    pub fn from_request(
74        request: &ApiRequest,
75        table: &Table,
76        mutation: &Mutation,
77        schema_cache: &crate::schema_cache::SchemaCache,
78    ) -> Result<Self> {
79        let qi = table.qualified_identifier();
80
81        match mutation {
82            Mutation::Create => Self::create_insert(request, table, qi, schema_cache),
83            Mutation::Update => Self::create_update(request, table, qi, schema_cache),
84            Mutation::Delete => Self::create_delete(request, table, qi),
85            Mutation::SingleUpsert => Self::create_upsert(request, table, qi, schema_cache),
86        }
87    }
88
89    /// Create an INSERT plan.
90    fn create_insert(
91        request: &ApiRequest,
92        table: &Table,
93        qi: QualifiedIdentifier,
94        schema_cache: &crate::schema_cache::SchemaCache,
95    ) -> Result<Self> {
96        let columns = get_payload_columns(request, table, schema_cache)?;
97        let body = get_body_bytes(request)?;
98        let returning = get_returning_columns(request, table, true);
99        let apply_defaults = asked_for_defaults(request);
100
101        // `Prefer: resolution=` says what to do about a duplicate; `on_conflict=`
102        // says which columns make one. Without the latter the answer is the
103        // primary key, which is what "duplicate" means when nothing else is
104        // said -- and without a resolution there is nothing to do about one.
105        let on_conflict = request
106            .preferences
107            .resolution
108            .clone()
109            .and_then(|resolution| {
110                let columns = request
111                    .query_params
112                    .on_conflict
113                    .clone()
114                    .unwrap_or_else(|| table.pk_cols.clone());
115                match columns.is_empty() {
116                    true => None,
117                    false => Some((resolution, columns)),
118                }
119            });
120
121        Ok(Self::Insert {
122            target: qi,
123            columns,
124            body,
125            on_conflict,
126            where_clauses: vec![],
127            returning,
128            pk_cols: table.pk_cols.clone(),
129            apply_defaults,
130            reports_inserted: true,
131            counts_inserted: table.is_view || table.is_partitioned,
132        })
133    }
134
135    /// Create an UPDATE plan.
136    fn create_update(
137        request: &ApiRequest,
138        table: &Table,
139        qi: QualifiedIdentifier,
140        schema_cache: &crate::schema_cache::SchemaCache,
141    ) -> Result<Self> {
142        let columns = get_payload_columns(request, table, schema_cache)?;
143        let body = get_body_bytes(request)?;
144        let where_clauses = build_mutation_where(request, table)?;
145        let returning = get_returning_columns(request, table, false);
146        let apply_defaults = asked_for_defaults(request);
147
148        Ok(Self::Update {
149            target: qi,
150            columns,
151            body,
152            where_clauses,
153            returning,
154            apply_defaults,
155        })
156    }
157
158    /// Create a DELETE plan.
159    fn create_delete(request: &ApiRequest, table: &Table, qi: QualifiedIdentifier) -> Result<Self> {
160        let where_clauses = build_mutation_where(request, table)?;
161        let returning = get_returning_columns(request, table, false);
162
163        Ok(Self::Delete {
164            target: qi,
165            where_clauses,
166            returning,
167        })
168    }
169
170    /// Create a PUT (upsert) plan.
171    fn create_upsert(
172        request: &ApiRequest,
173        table: &Table,
174        qi: QualifiedIdentifier,
175        schema_cache: &crate::schema_cache::SchemaCache,
176    ) -> Result<Self> {
177        validate_put(request, table)?;
178
179        let columns = get_payload_columns(request, table, schema_cache)?;
180        let body = get_body_bytes(request)?;
181        let returning = get_returning_columns(request, table, true);
182
183        // Upsert uses PK for conflict
184        let on_conflict = Some((PreferResolution::MergeDuplicates, table.pk_cols.clone()));
185
186        // The URL's filters narrow the *body*, not the table: a `PUT` writes
187        // the row the URL names, so a body row naming a different one is left
188        // unwritten rather than rejected outright. Whether exactly one row
189        // came of it is checked afterwards.
190        let where_clauses = build_mutation_where(request, table)?;
191
192        Ok(Self::Insert {
193            target: qi,
194            columns,
195            body,
196            on_conflict,
197            where_clauses,
198            returning,
199            pk_cols: table.pk_cols.clone(),
200            apply_defaults: asked_for_defaults(request),
201            reports_inserted: true,
202            counts_inserted: table.is_view || table.is_partitioned,
203        })
204    }
205
206    /// Get the target table.
207    pub fn target(&self) -> &QualifiedIdentifier {
208        match self {
209            Self::Insert { target, .. } => target,
210            Self::Update { target, .. } => target,
211            Self::Delete { target, .. } => target,
212        }
213    }
214
215    /// Check if this mutation has a body.
216    pub fn has_body(&self) -> bool {
217        match self {
218            Self::Insert { body, .. } => body.is_some(),
219            Self::Update { body, .. } => body.is_some(),
220            Self::Delete { .. } => false,
221        }
222    }
223}
224
225/// Get columns from payload.
226fn get_payload_columns(
227    request: &ApiRequest,
228    table: &Table,
229    schema_cache: &crate::schema_cache::SchemaCache,
230) -> Result<Vec<CoercibleField>> {
231    let keys = match &request.payload {
232        Some(Payload::ProcessedJson { keys, .. }) => keys,
233        Some(Payload::ProcessedUrlEncoded { keys, .. }) => keys,
234        _ => return Ok(vec![]),
235    };
236
237    // `?columns=` names the columns to write and fixes their order, which is
238    // what makes a bulk insert of ragged rows well-defined. Without it the
239    // body's own keys are the columns.
240    let names: Vec<&String> = match &request.query_params.columns {
241        Some(columns) => columns.iter().collect(),
242        None => keys.iter().collect(),
243    };
244
245    let mut columns = Vec::new();
246
247    for key in names {
248        let column = table.get_column(key).ok_or_else(|| Error::UnknownColumn {
249            column: key.clone(),
250            relation: table.name.clone(),
251        })?;
252
253        let mut field = CoercibleField::simple(key, &column.nominal_type);
254        field.default = column.default.clone();
255        // A schema that declared how one of its domains is written in JSON
256        // also declared how one arrives: the value is read out of the body as
257        // JSON and handed to that cast, rather than to PostgreSQL's own input
258        // function for the type underneath.
259        if let Some(function) = schema_cache.representation("json", column.representation_type()) {
260            field.ir_type = "json".to_string();
261            field.transform = Some(function.to_string());
262        }
263        columns.push(field);
264    }
265
266    Ok(columns)
267}
268
269/// Whether the request asked for a column it left out to take its default.
270///
271/// Read from what was actually sent rather than from the parsed field, which
272/// cannot say whether `missing=default` was requested or is merely the value
273/// the field holds when nothing was.
274fn asked_for_defaults(request: &ApiRequest) -> bool {
275    request
276        .preferences
277        .applied
278        .iter()
279        .any(|pref| pref == "missing=default")
280}
281
282/// Check that a `PUT` names exactly one row, and that its body agrees.
283///
284/// `PUT` replaces the row the URL identifies, so the URL has to identify one:
285/// every primary key column, compared with `eq`, and nothing else. A page
286/// makes no sense on top of that, and a body naming a different row would
287/// write somewhere the client did not ask for.
288fn validate_put(request: &ApiRequest, table: &Table) -> Result<()> {
289    use crate::api_request::{Operation, QuantOperator};
290
291    if request
292        .query_params
293        .ranges
294        .values()
295        .any(|range| range.limit.is_some() || range.offset != 0)
296    {
297        return Err(Error::PutLimitNotAllowed);
298    }
299
300    let mut keyed: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();
301    for filter in &request.query_params.filters_root {
302        let Operation::Quant {
303            op: QuantOperator::Equal,
304            quantifier: None,
305            value,
306        } = &filter.op_expr.operation
307        else {
308            return Err(Error::InvalidPutFilters);
309        };
310        if filter.op_expr.negated {
311            return Err(Error::InvalidPutFilters);
312        }
313        keyed.insert(&filter.field.name, value);
314    }
315
316    // Anything else in the query string that filters -- a logic group, a
317    // filter on an embedded resource -- also fails to name exactly one row.
318    if !request.query_params.logic.is_empty() || !request.query_params.filters.is_empty() {
319        return Err(Error::InvalidPutFilters);
320    }
321
322    if table.pk_cols.is_empty()
323        || keyed.len() != table.pk_cols.len()
324        || !table
325            .pk_cols
326            .iter()
327            .all(|key| keyed.contains_key(key.as_str()))
328    {
329        return Err(Error::InvalidPutFilters);
330    }
331
332    // Whether the body agrees with the URL is not decided here: the filters
333    // are applied to the body itself, so a row naming another key is simply
334    // not written, and the count that comes back says whether exactly one was.
335
336    Ok(())
337}
338
339/// Get body as bytes.
340fn get_body_bytes(request: &ApiRequest) -> Result<Option<bytes::Bytes>> {
341    match &request.payload {
342        Some(Payload::ProcessedJson { raw, .. }) => Ok(Some(raw.clone())),
343        Some(Payload::RawJson(raw)) => Ok(Some(raw.clone())),
344        Some(Payload::RawPayload(raw)) => Ok(Some(raw.clone())),
345        Some(Payload::ProcessedUrlEncoded { data, .. }) => {
346            // Convert to JSON
347            let json = serde_json::to_vec(
348                &data
349                    .iter()
350                    .cloned()
351                    .collect::<std::collections::HashMap<_, _>>(),
352            )
353            .map_err(|e| Error::InvalidBody(e.to_string()))?;
354            Ok(Some(bytes::Bytes::from(json)))
355        }
356        None => Ok(None),
357    }
358}
359
360/// The columns a mutation has to return.
361///
362/// `RETURNING` runs with the caller's privileges, so asking for a column the
363/// role may write but not read fails the whole statement. A role granted
364/// `INSERT` on an audit table and nothing else is an ordinary arrangement, and
365/// returning every column made it impossible to insert into one.
366///
367/// So: only what the response will actually read. That is the selected
368/// columns, whatever the result is ordered by, and the key a `Location` header
369/// is built from. A caller wanting no representation reads nothing, and the
370/// list is then empty.
371///
372/// The exceptions return the whole row, because they need it: `*` says so, and
373/// a computed field is a function of the row rather than of any column.
374fn get_returning_columns(request: &ApiRequest, table: &Table, creates: bool) -> Vec<String> {
375    use crate::api_request::SelectItem;
376
377    let everything = || -> Vec<String> { table.column_names().map(str::to_string).collect() };
378
379    let mut wanted: Vec<String> = Vec::new();
380
381    // `headers-only` reads no columns but still needs the key.
382    if request.preferences.representation.needs_body() {
383        if request.query_params.select.is_empty() {
384            return everything();
385        }
386        for item in &request.query_params.select {
387            match item {
388                SelectItem::Field { field, .. } => {
389                    if field.name == "*"
390                        || table
391                            .get_computed_column(&field.name)
392                            .is_some_and(|c| !c.takes_arguments)
393                    {
394                        return everything();
395                    }
396                    wanted.push(field.name.clone());
397                }
398                // An embed joins on a column of this row, and that column was
399                // added to the selection before planning began.
400                SelectItem::Relation { .. } | SelectItem::SpreadRelation { .. } => {}
401            }
402        }
403        // Ordering the returned rows by a column means reading that column,
404        // whether or not the client asked to see it. A term naming an
405        // embedded resource orders by something this statement cannot return
406        // at all.
407        for (path, terms) in &request.query_params.order {
408            if !path.is_empty() {
409                continue;
410            }
411            for term in terms {
412                if let crate::api_request::OrderTerm::Field { field, .. } = term {
413                    wanted.push(field.name.clone());
414                }
415            }
416        }
417    }
418
419    // The created row's own address is built from its key, whether or not the
420    // client asked to see it.
421    if creates {
422        wanted.extend(table.pk_cols.iter().cloned());
423    }
424
425    // A name that is not a column of this table cannot be returned from it;
426    // where it is anything real -- a JSON path, an alias -- the read resolves
427    // it against what did come back.
428    wanted.retain(|name| table.get_column(name).is_some());
429    wanted.sort();
430    wanted.dedup();
431    wanted
432}
433
434/// Build WHERE clauses for mutations.
435fn build_mutation_where(request: &ApiRequest, table: &Table) -> Result<Vec<CoercibleLogicTree>> {
436    let type_resolver = |name: &str| -> String {
437        table
438            .get_column(name)
439            .map(|c| c.data_type.clone())
440            .unwrap_or_else(|| "text".to_string())
441    };
442
443    let mut clauses = Vec::new();
444
445    for filter in &request.query_params.filters_root {
446        let pg_type = type_resolver(&filter.field.name);
447        clauses.push(CoercibleLogicTree::Stmt(CoercibleFilter::from_filter(
448            filter, &pg_type,
449        )));
450    }
451
452    // `?or=(...)` names rows exactly as a plain filter does, and a mutation
453    // that reads only the plain ones has no `WHERE` at all -- so
454    // `DELETE /entities?or=(id.eq.1,id.eq.2)` deleted every row in the table.
455    // A request that names two rows must never touch a third.
456    for (path, tree) in &request.query_params.logic {
457        if path.is_empty() {
458            clauses.push(CoercibleLogicTree::from_logic_tree(tree, type_resolver));
459        }
460    }
461
462    Ok(clauses)
463}
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    #[test]
470    fn test_mutate_plan_target() {
471        let qi = QualifiedIdentifier::new("public", "users");
472        let plan = MutatePlan::Delete {
473            target: qi.clone(),
474            where_clauses: vec![],
475            returning: vec!["id".into()],
476        };
477
478        assert_eq!(plan.target().name, "users");
479    }
480
481    #[test]
482    fn test_mutate_plan_has_body() {
483        let qi = QualifiedIdentifier::new("public", "users");
484
485        let insert = MutatePlan::Insert {
486            target: qi.clone(),
487            columns: vec![],
488            body: Some(bytes::Bytes::from("{}".as_bytes())),
489            on_conflict: None,
490            where_clauses: vec![],
491            returning: vec![],
492            pk_cols: vec![],
493            apply_defaults: true,
494            reports_inserted: false,
495            counts_inserted: false,
496        };
497        assert!(insert.has_body());
498
499        let delete = MutatePlan::Delete {
500            target: qi,
501            where_clauses: vec![],
502            returning: vec![],
503        };
504        assert!(!delete.has_body());
505    }
506}