postrust_core/plan/call_plan.rs
1//! RPC (stored function) call planning.
2
3use crate::api_request::{ApiRequest, Payload, QualifiedIdentifier};
4use crate::error::{Error, Result};
5use crate::schema_cache::Routine;
6use serde::{Deserialize, Serialize};
7
8/// A plan for calling a stored function.
9#[derive(Clone, Debug, Serialize, Deserialize)]
10pub struct CallPlan {
11 /// Function identifier
12 pub function: QualifiedIdentifier,
13 /// Call parameters
14 pub params: CallParams,
15 /// Whether to return a scalar result
16 pub returns_scalar: bool,
17 /// The declared return type, as PostgreSQL spells it.
18 ///
19 /// Used to decide whether this process can decode the result or whether
20 /// the database should render it, exactly as for a table's columns.
21 #[serde(default)]
22 pub return_type: Option<String>,
23 /// Whether the function is set-returning
24 pub returns_set: bool,
25 /// Whether the function returns nothing at all.
26 ///
27 /// A `void` function has no result to report, which is 204 rather than a
28 /// body of `null` -- and `RetType::Void` has no type name, so asking for
29 /// one would never find it.
30 #[serde(default)]
31 pub returns_void: bool,
32 /// Whether the return type is composite (row type or `record`): its
33 /// columns are real output columns, never the function-name wrapper.
34 #[serde(default)]
35 pub returns_composite: bool,
36 /// Function volatility (for transaction handling)
37 pub volatility: String,
38 /// Declared parameter types, in the routine's own order, as
39 /// `(name, pg_type)`.
40 ///
41 /// Arguments arrive from the URL or a JSON body as strings. Binding them
42 /// as `text` leaves PostgreSQL unable to resolve any signature that isn't
43 /// text -- `add_them(a => text, b => text) does not exist` -- so each one
44 /// is cast to its declared type at call time.
45 ///
46 /// The type is the one an argument can be cast to without losing part of
47 /// itself: a `char(4)` parameter is stored as bare `character`, whose
48 /// length is one, and a parameter's length is not enforced anyway.
49 #[serde(default)]
50 pub param_types: Vec<(String, String)>,
51 /// The media type the function's value already is, where its return type
52 /// is a domain that says so.
53 ///
54 /// The result is that media type rather than something to serialise as
55 /// JSON, so it is returned verbatim -- but only where the client asked for
56 /// it, since a function whose value is a PNG is still a value a client may
57 /// want as JSON.
58 #[serde(default)]
59 pub media_type: Option<String>,
60 /// The type that domain is a domain over -- what says whether the value
61 /// is bytes or text.
62 #[serde(default)]
63 pub media_base_type: Option<String>,
64 /// The columns the result has, where the function declares its own.
65 ///
66 /// `RETURNS TABLE(a text, b colour)` has no table to read the result's
67 /// shape from, so `SELECT *` is all that can be asked for -- and a column
68 /// of a type this process cannot decode comes back null. Knowing the
69 /// columns is what lets the database render those instead.
70 #[serde(default)]
71 pub output_columns: Vec<(String, String)>,
72 /// The names of the parameters declared `VARIADIC`.
73 ///
74 /// Named notation spells one `VARIADIC v := ...`; `v => ...` finds no
75 /// function at all, because the array is the whole of the variadic tail
76 /// rather than one value of it.
77 #[serde(default)]
78 pub variadic_params: Vec<String>,
79}
80
81/// How parameters are passed to the function.
82#[derive(Clone, Debug, Serialize, Deserialize)]
83pub enum CallParams {
84 /// Named parameters from URL query or JSON body
85 Named(Vec<(String, String)>),
86 /// Positional parameters (from JSON array)
87 Positional(Vec<String>),
88 /// Single JSON object passed as first argument
89 SingleObject(bytes::Bytes),
90 /// The whole request body, as the one parameter the function does not name.
91 ///
92 /// `unnamed_json_param(json)` declares a parameter with no name, so no
93 /// argument can be addressed to it; what it takes is the body itself,
94 /// cast to the type it declares. An absent body is that parameter's
95 /// `NULL`, not a call with no arguments -- the function has one either
96 /// way.
97 SingleUnnamed {
98 /// The raw body, absent when the request had none.
99 body: Option<bytes::Bytes>,
100 /// The type the parameter declares, which the body is cast to.
101 pg_type: String,
102 },
103 /// No parameters
104 None,
105}
106
107impl CallPlan {
108 /// Create a call plan from an API request.
109 pub fn from_request(request: &ApiRequest, routine: &Routine) -> Result<Self> {
110 // PostgREST Plan.hs failMaxAffectedRpcReturnsSingle: counting affected
111 // rows needs a set to count.
112 if request.preferences.max_affected.is_some()
113 && request.preferences.handling == crate::api_request::PreferHandling::Strict
114 && !routine.return_type.is_set_returning()
115 {
116 return Err(crate::error::Error::MaxAffectedRpcViolation);
117 }
118
119 let qi = routine.qualified_identifier();
120
121 let params = extract_call_params(request, routine)?;
122
123 let returns_scalar = !routine.return_type.is_set_returning()
124 && routine
125 .return_type
126 .type_name()
127 .map(|t| !t.contains("record"))
128 .unwrap_or(true);
129
130 Ok(Self {
131 function: qi,
132 params,
133 returns_scalar,
134 return_type: routine.return_type.type_name().map(str::to_string),
135 returns_set: routine.return_type.is_set_returning(),
136 returns_void: matches!(routine.return_type, crate::schema_cache::RetType::Void),
137 returns_composite: routine.returns_composite,
138 volatility: format!("{:?}", routine.volatility),
139 param_types: routine
140 .params
141 .iter()
142 .map(|p| (p.name.clone(), p.type_max_length.clone()))
143 .collect(),
144 media_type: routine.media_type.clone(),
145 media_base_type: routine.media_base_type.clone(),
146 output_columns: routine.output_columns.clone(),
147 variadic_params: routine
148 .params
149 .iter()
150 .filter(|p| p.variadic)
151 .map(|p| p.name.clone())
152 .collect(),
153 })
154 }
155
156 /// Check if this call has parameters.
157 pub fn has_params(&self) -> bool {
158 !matches!(self.params, CallParams::None)
159 }
160}
161
162/// Extract call parameters from request.
163fn extract_call_params(request: &ApiRequest, routine: &Routine) -> Result<CallParams> {
164 // A parameter with no name cannot be given an argument by name. What such
165 // a function takes is the body itself, whatever the body says.
166 if let [param] = routine.params.as_slice() {
167 if param.name.is_empty() {
168 let body = match &request.payload {
169 Some(Payload::ProcessedJson { raw, .. })
170 | Some(Payload::RawJson(raw))
171 | Some(Payload::RawPayload(raw)) => Some(raw.clone()),
172 Some(Payload::ProcessedUrlEncoded { .. }) | None => None,
173 };
174 return Ok(CallParams::SingleUnnamed {
175 body,
176 pg_type: param.param_type.clone(),
177 });
178 }
179 }
180
181 // Check for JSON body first
182 if let Some(payload) = &request.payload {
183 match payload {
184 Payload::ProcessedJson { raw, .. } => {
185 // Check if it's an object or array
186 let value: serde_json::Value =
187 serde_json::from_slice(raw).map_err(|e| Error::InvalidBody(e.to_string()))?;
188
189 // A call takes one set of arguments. A body written as an
190 // array offers several, and PostgREST reads the first --
191 // `LIMIT 1` over the record set it makes of the body.
192 let value = match value {
193 serde_json::Value::Array(rows)
194 if rows.first().is_some_and(serde_json::Value::is_object) =>
195 {
196 rows.into_iter().next().unwrap_or(serde_json::Value::Null)
197 }
198 other => other,
199 };
200
201 match value {
202 serde_json::Value::Object(map) => {
203 // `?columns=` names which of the body's keys are
204 // arguments, and a key the function does not declare
205 // is not one -- the body may carry more than the call
206 // needs.
207 let map: serde_json::Map<String, serde_json::Value> = map
208 .into_iter()
209 .filter(|(name, _)| {
210 request
211 .query_params
212 .columns
213 .as_ref()
214 .map(|columns| columns.contains(name))
215 .unwrap_or(true)
216 && routine.params.iter().any(|p| &p.name == name)
217 })
218 .collect();
219
220 // Named parameters from JSON object
221 let params: Vec<(String, String)> = map
222 .into_iter()
223 .map(|(k, v)| {
224 // A `json` parameter takes the body's value as
225 // the body wrote it: a JSON string is a JSON
226 // string, and unquoting it first turns
227 // `"{\"key\": 3}"` into an object the caller
228 // did not pass -- or, for `"text"`, into
229 // something that is not JSON at all.
230 let takes_json = routine.params.iter().any(|p| {
231 p.name == k && matches!(p.param_type.as_str(), "json" | "jsonb")
232 });
233 // Extract string values without JSON quotes
234 let value = match v {
235 ref value if takes_json => value.to_string(),
236 serde_json::Value::String(s) => s,
237 serde_json::Value::Null => String::new(),
238 // A JSON array for a parameter the function
239 // declares as an array is that array, not a
240 // string spelled in JSON: `{"v":["a","b"]}`
241 // passes two values to a variadic. PostgreSQL
242 // reads `{...}`, not `[...]`.
243 serde_json::Value::Array(items)
244 if routine.params.iter().any(|p| {
245 p.name == k && p.param_type.ends_with("[]")
246 }) =>
247 {
248 array_literal(
249 &items
250 .iter()
251 .map(|item| match item {
252 serde_json::Value::String(s) => s.clone(),
253 other => other.to_string(),
254 })
255 .collect::<Vec<_>>(),
256 )
257 }
258 other => other.to_string(),
259 };
260 (k, value)
261 })
262 .collect();
263 return Ok(CallParams::Named(params));
264 }
265 serde_json::Value::Array(_) => {
266 // Pass entire JSON as single argument
267 return Ok(CallParams::SingleObject(raw.clone()));
268 }
269 _ => {
270 // Scalar value - pass as single argument
271 return Ok(CallParams::SingleObject(raw.clone()));
272 }
273 }
274 }
275 Payload::ProcessedUrlEncoded { data, .. } => {
276 // A form body is named arguments like any other, repeats and
277 // all: the same name twice is one variadic argument or the
278 // last of them, never two arguments.
279 return Ok(named_arguments(
280 data.iter()
281 .map(|(name, value)| (name.clone(), value.clone())),
282 routine,
283 ));
284 }
285 Payload::RawJson(raw) | Payload::RawPayload(raw) => {
286 return Ok(CallParams::SingleObject(raw.clone()));
287 }
288 }
289 }
290
291 // Fall back to query parameters. Only those naming a declared parameter
292 // are arguments -- the rest are filters on the function's result, which
293 // is how `/rpc/getallprojects?id=eq.1` filters rather than failing.
294 if !request.query_params.params.is_empty() {
295 let mut args: Vec<(String, Vec<String>)> = Vec::new();
296 for (name, value) in &request.query_params.params {
297 // A value carrying an operator filters the result; only a bare
298 // one is an argument. `?id=5&id=gt.2` is both at once.
299 if crate::api_request::value_is_filter(value) {
300 continue;
301 }
302 if !routine.params.iter().any(|p| &p.name == name) {
303 continue;
304 }
305 match args.iter_mut().find(|(existing, _)| existing == name) {
306 Some((_, values)) => values.push(value.clone()),
307 None => args.push((name.clone(), vec![value.clone()])),
308 }
309 }
310
311 // A name given more than once is one argument, not two: for a
312 // variadic parameter every value goes into the array it takes, and
313 // for any other the last one wins -- repeating it cannot mean asking
314 // for two values where the signature has room for one.
315 let args: Vec<(String, String)> = args
316 .into_iter()
317 .map(|(name, values)| {
318 let variadic = routine.params.iter().any(|p| p.name == name && p.variadic);
319 let value = match variadic {
320 true => array_literal(&values),
321 false => values.last().cloned().unwrap_or_default(),
322 };
323 (name, value)
324 })
325 .collect();
326
327 if !args.is_empty() {
328 return Ok(CallParams::Named(args));
329 }
330 }
331
332 // No parameters
333 Ok(CallParams::None)
334}
335
336/// Group named arguments, collapsing repeats the way a call must.
337///
338/// A name given more than once is one argument, not two: for a variadic
339/// parameter every value goes into the array it takes, and for any other the
340/// last one wins -- repeating it cannot mean asking for two values where the
341/// signature has room for one. Names the function does not declare are left
342/// out; the body may carry more than the call needs.
343fn named_arguments(
344 supplied: impl IntoIterator<Item = (String, String)>,
345 routine: &Routine,
346) -> CallParams {
347 let mut grouped: Vec<(String, Vec<String>)> = Vec::new();
348 for (name, value) in supplied {
349 if !routine.params.iter().any(|p| p.name == name) {
350 continue;
351 }
352 match grouped.iter_mut().find(|(existing, _)| *existing == name) {
353 Some((_, values)) => values.push(value),
354 None => grouped.push((name, vec![value])),
355 }
356 }
357
358 let args: Vec<(String, String)> = grouped
359 .into_iter()
360 .map(|(name, values)| {
361 let variadic = routine.params.iter().any(|p| p.name == name && p.variadic);
362 let value = match variadic {
363 true => array_literal(&values),
364 false => values.last().cloned().unwrap_or_default(),
365 };
366 (name, value)
367 })
368 .collect();
369
370 match args.is_empty() {
371 true => CallParams::None,
372 false => CallParams::Named(args),
373 }
374}
375
376/// Render values as a PostgreSQL array literal.
377///
378/// Every element is quoted, which is always valid and saves deciding which
379/// ones would otherwise need it -- an element containing a comma, a brace or a
380/// quote of its own would silently change the array's shape.
381fn array_literal(values: &[String]) -> String {
382 let elements: Vec<String> = values
383 .iter()
384 .map(|value| format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")))
385 .collect();
386 format!("{{{}}}", elements.join(","))
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392 use crate::schema_cache::{FuncVolatility, RetType};
393
394 fn make_routine() -> Routine {
395 Routine {
396 output_columns: Vec::new(),
397 media_type: None,
398 media_base_type: None,
399 schema: "public".into(),
400 name: "get_users".into(),
401 description: None,
402 params: vec![],
403 return_type: RetType::SetOf("users".into()),
404 returns_composite: true,
405 volatility: FuncVolatility::Stable,
406 has_variadic: false,
407 isolation_level: None,
408 settings: vec![],
409 is_procedure: false,
410 }
411 }
412
413 #[test]
414 fn test_call_plan_basic() {
415 let request = ApiRequest::default();
416 let routine = make_routine();
417
418 let plan = CallPlan::from_request(&request, &routine).unwrap();
419
420 assert_eq!(plan.function.name, "get_users");
421 assert!(plan.returns_set);
422 assert!(!plan.returns_scalar);
423 assert!(plan.returns_composite);
424 }
425
426 #[test]
427 fn test_call_plan_scalar_is_not_composite() {
428 let request = ApiRequest::default();
429 let routine = Routine {
430 return_type: RetType::Single("integer".into()),
431 returns_composite: false,
432 ..make_routine()
433 };
434
435 let plan = CallPlan::from_request(&request, &routine).unwrap();
436
437 assert!(plan.returns_scalar);
438 assert!(!plan.returns_set);
439 assert!(!plan.returns_composite);
440 }
441
442 #[test]
443 fn test_call_params_none() {
444 let request = ApiRequest::default();
445 let routine = make_routine();
446
447 let plan = CallPlan::from_request(&request, &routine).unwrap();
448 assert!(!plan.has_params());
449 }
450}