Skip to main content

postrust_core/api_request/
query_params.rs

1//! Query parameter parsing using nom.
2//!
3//! Parses URL query strings into structured filter, select, order, and range data.
4//! Mirrors PostgREST's QueryParams.hs parsing logic.
5
6use super::types::*;
7use crate::error::{Error, Result};
8use nom::{
9    branch::alt,
10    bytes::complete::{tag, take_while, take_while1},
11    character::complete::{char, satisfy},
12    combinator::{opt, recognize, value},
13    multi::{many0, separated_list0},
14    sequence::{pair, preceded},
15    IResult,
16};
17use percent_encoding::percent_decode_str;
18
19/// Parse a query string into QueryParams.
20///
21/// `is_rpc` changes what an unrecognized key means. On a table, `a=2` is a
22/// malformed filter and an error, because a filter value must carry an
23/// operator. On a function, it is an argument -- so every such key is also
24/// recorded as a candidate argument, and one that fails to parse as a filter
25/// is no longer fatal. Which candidates are really arguments is settled at
26/// plan time, against the parameters the routine actually declares; a
27/// well-formed filter such as `id=eq.1` stays available to filter the result.
28pub fn parse_query_params(query: &str, is_rpc: bool) -> Result<QueryParams> {
29    parse_query_params_with(query, is_rpc, false)
30}
31
32/// [`parse_query_params`], optionally reading `select` the way PostgREST does
33/// when text is left over after its last item: `lenient_select` drops that
34/// tail (see [`parse_select_lenient`]).
35pub fn parse_query_params_with(
36    query: &str,
37    is_rpc: bool,
38    lenient_select: bool,
39) -> Result<QueryParams> {
40    let mut params = QueryParams::default();
41
42    if query.is_empty() {
43        return Ok(params);
44    }
45
46    // Sort parameters for canonical form
47    let mut pairs: Vec<(&str, &str)> = query
48        .split('&')
49        .filter_map(|pair| {
50            let mut parts = pair.splitn(2, '=');
51            Some((parts.next()?, parts.next().unwrap_or("")))
52        })
53        .collect();
54    pairs.sort_by_key(|(k, _)| *k);
55    params.canonical = pairs
56        .iter()
57        .map(|(k, v)| format!("{}={}", k, v))
58        .collect::<Vec<_>>()
59        .join("&");
60
61    for (key, value) in pairs {
62        let decoded_value = percent_decode_str(value)
63            .decode_utf8()
64            .map_err(|_| Error::InvalidQueryParam(key.into()))?
65            .to_string();
66
67        // The key is decoded as well as the value. A filter on a JSON path
68        // arrives as `data-%3E%3Eb` from any client that escapes `>`, and
69        // would otherwise be looked up as a column of that literal name.
70        let decoded_key = percent_decode_str(key)
71            .decode_utf8()
72            .map_err(|_| Error::InvalidQueryParam(key.into()))?
73            .to_string();
74        let key: &str = &decoded_key;
75
76        // Modifiers come before filters, since both are dotted: `clients.order`
77        // orders an embedded resource while `clients.name` filters one.
78        if let Some((path, modifier)) = parse_modifier_key(key) {
79            match modifier {
80                Modifier::Order => {
81                    let (_, terms) = parse_order_param(&decoded_value)?;
82                    params.order.push((path, terms));
83                }
84                Modifier::Limit => {
85                    let limit: i64 = decoded_value
86                        .parse()
87                        .map_err(|_| Error::InvalidQueryParam("limit".into()))?;
88                    // Caught here rather than left to `LIMIT -1`, which
89                    // PostgreSQL rejects with a message about SQL syntax for
90                    // what is a plainly out-of-range request.
91                    if limit < 0 {
92                        return Err(Error::InvalidRange(
93                            "Limit should be greater than or equal to zero.".into(),
94                        ));
95                    }
96                    params.ranges.entry(path.join(".")).or_default().limit = Some(limit);
97                }
98                Modifier::Offset => {
99                    let offset: i64 = decoded_value
100                        .parse()
101                        .map_err(|_| Error::InvalidQueryParam("offset".into()))?;
102                    let range = params.ranges.entry(path.join(".")).or_default();
103                    range.offset = offset;
104                    range.offset_explicit = true;
105                }
106                Modifier::Logic(op, negated) => {
107                    check_nesting(&decoded_value)?;
108                    params
109                        .logic
110                        .push((path, parse_logic_param(op, negated, &decoded_value)?));
111                }
112            }
113            continue;
114        }
115
116        match key {
117            "select" => {
118                params.select = match lenient_select {
119                    true => parse_select_lenient(&decoded_value)?,
120                    false => parse_select(&decoded_value)?,
121                };
122            }
123            "columns" => {
124                params.columns = Some(parse_columns(&decoded_value)?.into_iter().collect());
125            }
126            "on_conflict" => {
127                params.on_conflict = Some(
128                    decoded_value
129                        .split(',')
130                        .map(|s| s.trim().to_string())
131                        .collect(),
132                );
133            }
134            key if !key.starts_with('_') => {
135                if is_rpc {
136                    params.params.push((key.to_string(), decoded_value.clone()));
137                }
138
139                // Filter parameter
140                let parsed = parse_filter_param(key, &decoded_value);
141                let (path, filter) = match parsed {
142                    Ok(parsed) => parsed,
143                    // On a function, a key that isn't a filter is just an
144                    // argument, which was recorded above.
145                    Err(_) if is_rpc => continue,
146                    Err(e) => return Err(e),
147                };
148
149                if path.is_empty() {
150                    params.filter_fields.insert(filter.field.name.clone());
151                    params.filters_root.push(filter);
152                } else {
153                    params.filters.push((path, filter));
154                }
155            }
156            _ => {
157                // RPC parameters (anything else)
158                params.params.push((key.to_string(), decoded_value));
159            }
160        }
161    }
162
163    Ok(params)
164}
165
166// ============================================================================
167// Select Parsing
168// ============================================================================
169
170/// Parse the `columns` parameter value.
171///
172/// A list of field names and nothing else, so the only thing that can go wrong
173/// is a name that is not there -- `?columns=` names none, and `?columns=a,,b`
174/// leaves a gap in the middle. Both were read as a field whose name is the
175/// empty string, which got as far as the schema cache and came back as
176/// "Could not find the '' column", describing a lookup the client never asked
177/// for rather than the parameter it actually wrote.
178fn parse_columns(input: &str) -> Result<Vec<String>> {
179    const EXPECTED: &str = "expecting field name (* or [a..z0..9_$])";
180
181    let mut columns = Vec::new();
182    let mut at = 0usize;
183
184    for (index, field) in input.split(',').enumerate() {
185        if index > 0 {
186            // The comma that separated this field from the last one.
187            at += 1;
188        }
189        let trimmed = field.trim();
190        if trimmed.is_empty() {
191            return Err(Error::UnparsableQuery {
192                kind: "columns parameter",
193                text: input.to_string(),
194                // Counting from one, at the character that should have begun
195                // the name -- the end of the input where there is none left.
196                column: at + 1,
197                expected: match at >= input.len() {
198                    true => format!("unexpected end of input {}", EXPECTED),
199                    false => format!(
200                        "unexpected {:?} {}",
201                        input[at..].chars().next().unwrap_or_default(),
202                        EXPECTED
203                    ),
204                },
205            });
206        }
207        columns.push(trimmed.to_string());
208        at += field.len();
209    }
210
211    Ok(columns)
212}
213
214/// Parse the `select` parameter value.
215pub fn parse_select(input: &str) -> Result<Vec<SelectItem>> {
216    if input.is_empty() {
217        return Ok(vec![]);
218    }
219
220    check_nesting(input)?;
221
222    // Anything left over is a parse failure, not something to ignore. Left
223    // ignored, one unparsable item silently discarded every item after it --
224    // `select=id, name, billing(address)` returned the id alone.
225    match parse_select_items(input) {
226        Ok(("", items)) => Ok(items),
227        // A JSON path that began (`->` or `->>` was read) and then went wrong
228        // is reported where it went wrong, as PostgREST's parser does.
229        Err(nom::Err::Failure(failure)) => Err(unreadable_json_operand(input, failure)),
230        _ => Err(Error::InvalidQueryParam(format!("select={}", input))),
231    }
232}
233
234/// [`parse_select`] for compatibility mode.
235///
236/// PostgREST parses `select` without requiring that all of it was read, so a
237/// tail it cannot make sense of at the top level -- the `'` in
238/// `select=name,projects(count)'`, one `)` too many -- is dropped rather than
239/// refused. A tail that begins with `,` is still an error there: the comma was
240/// consumed as a separator, and the item that should follow it is missing.
241pub fn parse_select_lenient(input: &str) -> Result<Vec<SelectItem>> {
242    if input.is_empty() {
243        return Ok(vec![]);
244    }
245
246    check_nesting(input)?;
247
248    match parse_select_items(input) {
249        Ok((rest, items)) if rest.is_empty() || !rest.starts_with(',') => Ok(items),
250        Err(nom::Err::Failure(failure)) => Err(unreadable_json_operand(input, failure)),
251        _ => Err(Error::InvalidQueryParam(format!("select={}", input))),
252    }
253}
254
255/// The error for a JSON path operand that could not be read, with the column
256/// it stopped at and what would have been accepted there.
257fn unreadable_json_operand(whole: &str, failure: nom::error::Error<&str>) -> Error {
258    let column = whole.chars().count() - failure.input.chars().count() + 1;
259    let found = match failure.input.chars().next() {
260        Some(ch) => format!("\"{}\"", ch),
261        None => "end of input".to_string(),
262    };
263    let expected = match failure.code {
264        nom::error::ErrorKind::Digit => "digit",
265        _ => "\"-\", digit or any non reserved character different from: .,>()",
266    };
267    Error::UnparsableQuery {
268        kind: "select parameter",
269        text: whole.to_string(),
270        column,
271        expected: format!("unexpected {} expecting {}", found, expected),
272    }
273}
274
275/// How deeply a `select` or a logic tree may nest its parentheses.
276///
277/// Both are parsed by recursion, one level per parenthesis, and so are the
278/// plans and statements built from them. Unbounded, a few thousand levels --
279/// some 15 KB of query string -- overflowed a worker thread's stack, and a
280/// stack overflow aborts the process rather than failing the request. No
281/// embedding or condition a client means to send comes near this.
282const MAX_NESTING: usize = 64;
283
284/// Refuse a value nested deeper than [`MAX_NESTING`], before parsing it.
285///
286/// Parentheses inside a double-quoted value are the value's, not structure,
287/// and are not counted: `or=(name.eq."((((")` nests once.
288fn check_nesting(input: &str) -> Result<()> {
289    let mut depth = 0usize;
290    let mut quoted = false;
291    let mut escaped = false;
292    for ch in input.chars() {
293        if quoted {
294            match ch {
295                _ if escaped => escaped = false,
296                '\\' => escaped = true,
297                '"' => quoted = false,
298                _ => {}
299            }
300            continue;
301        }
302        match ch {
303            '"' => quoted = true,
304            '(' => {
305                depth += 1;
306                if depth > MAX_NESTING {
307                    return Err(Error::InvalidQueryParam(format!(
308                        "nested more than {MAX_NESTING} levels deep"
309                    )));
310                }
311            }
312            ')' => depth = depth.saturating_sub(1),
313            _ => {}
314        }
315    }
316    Ok(())
317}
318
319fn parse_select_items(input: &str) -> IResult<&str, Vec<SelectItem>> {
320    separated_list0(char(','), parse_select_item)(input)
321}
322
323fn parse_select_item(input: &str) -> IResult<&str, SelectItem> {
324    // A space after a comma is ordinary in a hand-written URL, and PostgREST
325    // accepts it.
326    let (input, _) = nom::character::complete::space0(input)?;
327    alt((
328        parse_star,
329        // Before relations: `count()` is spelled exactly like an embed of a
330        // relation named `count` with an empty selection.
331        parse_bare_aggregate,
332        parse_spread_relation,
333        parse_relation_select,
334        parse_field_select,
335    ))(input)
336}
337
338/// Parse `*`, which names every column.
339///
340/// It is a select item like any other, so it composes: `*,clients(id)` asks
341/// for every column of this table and an embed besides, and `clients(*)` asks
342/// for every column of the embedded one.
343fn parse_star(input: &str) -> IResult<&str, SelectItem> {
344    let (input, _) = char('*')(input)?;
345    Ok((input, SelectItem::field("*")))
346}
347
348/// Parse a field-less aggregate: `count()`, `cnt:count()`, `count()::text`.
349///
350/// Only `count` is meaningful without a field -- the others have nothing to
351/// sum -- which is also what keeps this from swallowing embeds.
352fn parse_bare_aggregate(input: &str) -> IResult<&str, SelectItem> {
353    let (input, alias) = opt(parse_alias_prefix)(input)?;
354    let (input, _) = tag("count()")(input)?;
355    let (input, cast) = opt(preceded(tag("::"), parse_cast_type))(input)?;
356
357    Ok((
358        input,
359        SelectItem::Field {
360            // An empty name marks the `COUNT(*)` form: there is no column to
361            // resolve, and nothing to group by.
362            field: Field::simple(""),
363            aggregate: Some(AggregateFunction::Count),
364            aggregate_cast: cast.map(|s| s.to_string()),
365            cast: None,
366            alias: alias.map(|s| s.to_string()),
367        },
368    ))
369}
370
371/// Parse an aggregate applied to a field: the `.sum()` of `amount.sum()`.
372fn parse_aggregate_suffix(input: &str) -> IResult<&str, AggregateFunction> {
373    let (input, _) = char('.')(input)?;
374    let (input, function) = alt((
375        value(AggregateFunction::Sum, tag("sum")),
376        value(AggregateFunction::Avg, tag("avg")),
377        value(AggregateFunction::Max, tag("max")),
378        value(AggregateFunction::Min, tag("min")),
379        value(AggregateFunction::Count, tag("count")),
380    ))(input)?;
381    let (input, _) = tag("()")(input)?;
382    Ok((input, function))
383}
384
385/// Parse spread relation: `...relation(cols)`
386fn parse_spread_relation(input: &str) -> IResult<&str, SelectItem> {
387    let (input, _) = tag("...")(input)?;
388    let (input, relation) = parse_field_name(input)?;
389    let (input, (hint, join_type)) = parse_relation_modifiers(input)?;
390    // The parentheses are as much a part of the syntax here as they are for a
391    // plain embed. Leaving them for the caller to trip over meant the column
392    // list was silently discarded along with the rest of the select.
393    let (input, _) = char('(')(input)?;
394    let (input, nested) = parse_nested_select(input)?;
395    let (input, _) = char(')')(input)?;
396
397    Ok((
398        input,
399        SelectItem::SpreadRelation {
400            relation,
401            hint,
402            join_type,
403            select: nested,
404        },
405    ))
406}
407
408/// Parse the contents of a relation's parentheses.
409///
410/// Scans to the parenthesis that closes the group -- tracking nesting, so
411/// `books(chapters(id))` is not truncated at the first `)` -- then parses the
412/// contents as a select list.
413fn parse_nested_select(input: &str) -> IResult<&str, Vec<SelectItem>> {
414    let mut depth = 0usize;
415    let mut end = input.len();
416
417    for (idx, ch) in input.char_indices() {
418        match ch {
419            '(' => depth += 1,
420            ')' => {
421                if depth == 0 {
422                    end = idx;
423                    break;
424                }
425                depth -= 1;
426            }
427            _ => {}
428        }
429    }
430
431    let (body, rest) = input.split_at(end);
432
433    if body.is_empty() {
434        return Ok((rest, Vec::new()));
435    }
436
437    match parse_select_items(body) {
438        Ok(("", items)) => Ok((rest, items)),
439        _ => Err(nom::Err::Error(nom::error::Error::new(
440            input,
441            nom::error::ErrorKind::Verify,
442        ))),
443    }
444}
445
446/// Parse relation with embedded select: `relation(select_items)`
447fn parse_relation_select(input: &str) -> IResult<&str, SelectItem> {
448    // As with fields, the alias precedes what it names: `c:clients(*)`.
449    let (input, alias) = opt(parse_alias_prefix)(input)?;
450    let (input, name) = parse_field_name(input)?;
451    let (input, (hint, join_type)) = parse_relation_modifiers(input)?;
452    // The nested selection is parsed rather than skipped: it says which
453    // columns of the related resource to return, and may embed further
454    // relations of its own.
455    let (input, _) = char('(')(input)?;
456    let (input, nested) = parse_nested_select(input)?;
457    let (input, _) = char(')')(input)?;
458
459    Ok((
460        input,
461        SelectItem::Relation {
462            relation: name,
463            alias,
464            hint,
465            join_type,
466            select: nested,
467        },
468    ))
469}
470
471/// Parse field select: `field`, `field::cast`, `field:alias`, `agg(field)`
472fn parse_field_select(input: &str) -> IResult<&str, SelectItem> {
473    // `alias:expression` -- the alias comes first, as in `myId:id` or
474    // `total:sum(amount)`. Only a name immediately followed by `:` is one;
475    // anything else backtracks and is read as the expression itself.
476    let (input, alias) = opt(parse_alias_prefix)(input)?;
477
478    let (input, name) = parse_field_name(input)?;
479    let (input, json_path) = parse_json_path(input)?;
480
481    // A cast on the column binds before the aggregate: `key::integer.sum()`
482    // sums integers, where `.sum()::text` renders the sum as text.
483    let (input, cast) = opt(preceded(tag("::"), parse_cast_type))(input)?;
484    let (input, aggregate) = opt(parse_aggregate_suffix)(input)?;
485    let (input, aggregate_cast) = if aggregate.is_some() {
486        let (input, cast) = opt(preceded(tag("::"), parse_cast_type))(input)?;
487        (input, cast.map(|s| s.to_string()))
488    } else {
489        (input, None)
490    };
491
492    Ok((
493        input,
494        SelectItem::Field {
495            field: Field { name, json_path },
496            aggregate,
497            aggregate_cast,
498            cast: cast.map(|s| s.to_string()),
499            alias: alias.map(|s| s.to_string()),
500        },
501    ))
502}
503
504/// Parse the `!`-prefixed modifiers on an embedded relation.
505///
506/// A relation may carry a disambiguating hint, a join type, or both, in either
507/// order: `books!author(*)`, `books!inner(*)`, `books!author!inner(*)`. They
508/// cannot be told apart by position, only by spelling -- `inner` and `left`
509/// are join types and anything else names a foreign key or table -- so each
510/// modifier is read in turn and classified.
511/// An `alias:` prefix, distinguished from the `::` of a cast.
512///
513/// `myId:id` names the column; `id::text` casts it. Both start with an
514/// identifier followed by a colon, so the second colon is what tells them
515/// apart -- without this check `id::text` would be read as an alias `id`
516/// applied to nothing.
517fn parse_alias_prefix(input: &str) -> IResult<&str, String> {
518    let (rest, name) = parse_field_name(input)?;
519    let (rest, _) = char(':')(rest)?;
520
521    if rest.starts_with(':') {
522        return Err(nom::Err::Error(nom::error::Error::new(
523            input,
524            nom::error::ErrorKind::Verify,
525        )));
526    }
527
528    Ok((rest, name))
529}
530
531fn parse_relation_modifiers(input: &str) -> IResult<&str, (Option<String>, Option<JoinType>)> {
532    let (input, modifiers) = many0(preceded(char('!'), parse_identifier))(input)?;
533
534    let mut hint = None;
535    let mut join_type = None;
536    for modifier in modifiers {
537        match modifier {
538            "inner" => join_type = Some(JoinType::Inner),
539            "left" => join_type = Some(JoinType::Left),
540            other => hint = Some(other.to_string()),
541        }
542    }
543
544    Ok((input, (hint, join_type)))
545}
546
547// ============================================================================
548// Filter Parsing
549// ============================================================================
550
551/// Parse a filter parameter (key=value where key is a field name).
552fn parse_filter_param(key: &str, value: &str) -> Result<(EmbedPath, Filter)> {
553    // Parse the key for embedded path: rel.field or field
554    let (path, field) = parse_filter_key(key)?;
555
556    // Parse the value for operator and operand
557    let op_expr = parse_filter_value(value)?;
558
559    Ok((path, Filter::new(field, op_expr)))
560}
561
562/// Split a reference like `data->a->>b` into its column and JSON path.
563///
564/// A name with no arrows is returned unchanged, so this is safe to apply to
565/// every field reference. A trailing fragment that does not parse as a path is
566/// left attached to the column name rather than silently dropped -- the column
567/// then fails to resolve, which is the honest outcome.
568fn split_json_path(reference: &str) -> Field {
569    let Some(arrow) = reference.find("->") else {
570        return Field::simple(reference);
571    };
572
573    let (column, rest) = reference.split_at(arrow);
574    match parse_json_path(rest) {
575        Ok(("", json_path)) if !json_path.is_empty() => Field::with_json_path(column, json_path),
576        _ => Field::simple(reference),
577    }
578}
579
580/// Parse a filter key into the embedded path and the field it names.
581///
582/// The key is a run of field names separated by `.`, optionally followed by a
583/// JSON path: `clients.id`, `data->>a`, `"a.dotted.column"`. Splitting on `.`
584/// alone would cut a quoted name in half, and would take the dot of
585/// `id.something` for a path separator, so the names are parsed rather than
586/// split.
587///
588/// A key the grammar cannot account for falls back to the plain split, which
589/// leaves whatever it produced to fail at column resolution -- an honest
590/// outcome, and the one this had before.
591fn parse_filter_key(key: &str) -> Result<(EmbedPath, Field)> {
592    if let Some(parsed) = parse_field_reference(key) {
593        return Ok(parsed);
594    }
595
596    let mut parts: Vec<&str> = key.split('.').collect();
597    let field = parts
598        .pop()
599        .ok_or_else(|| Error::InvalidQueryParam(key.into()))?;
600    let path = parts.into_iter().map(String::from).collect();
601    Ok((path, split_json_path(field)))
602}
603
604/// A dotted path of field names followed by an optional JSON path.
605///
606/// `None` when the whole key was not consumed, which is the caller's signal
607/// that this grammar does not describe it.
608fn parse_field_reference(key: &str) -> Option<(EmbedPath, Field)> {
609    let mut names = Vec::new();
610    let mut rest = key;
611
612    loop {
613        let (remainder, name) = parse_field_name(rest).ok()?;
614        names.push(name);
615        match remainder.strip_prefix('.') {
616            Some(after) => rest = after,
617            None => {
618                rest = remainder;
619                break;
620            }
621        }
622    }
623
624    let (rest, json_path) = parse_json_path(rest).ok()?;
625    if !rest.is_empty() {
626        return None;
627    }
628
629    let field = names.pop()?;
630    Some((names, Field::with_json_path(field, json_path)))
631}
632
633/// Whether a query parameter reads as a filter rather than a function argument.
634///
635/// On `/rpc/f?id=5&id=gt.2` the same name is both: `5` is the argument the
636/// function takes and `gt.2` filters what it returned. What tells them apart
637/// is the value -- an operator prefix means a filter -- so the classification
638/// has to look at the value rather than the name.
639pub fn value_is_filter(value: &str) -> bool {
640    parse_filter_value(value).is_ok()
641}
642
643/// Parse filter value: `operator.value` or `not.operator.value`
644fn parse_filter_value(value: &str) -> Result<OpExpr> {
645    let whole = value;
646    let (value, negated) = if let Some(rest) = value.strip_prefix("not.") {
647        (rest, true)
648    } else {
649        (value, false)
650    };
651
652    let operation = parse_operation(value).map_err(|error| match error {
653        // Nothing in the value named an operator, so reading stopped at its
654        // first character -- and what a filter may begin with is a short,
655        // published list. Any other failure got further in and has more to say
656        // about where.
657        Error::InvalidQueryParam(_) => Error::UnparsableQuery {
658            kind: "filter",
659            text: whole.to_string(),
660            column: 1,
661            expected: format!(
662                "unexpected \"{}\" expecting \"not\" or operator (eq, gt, ...)",
663                whole.chars().next().unwrap_or_default()
664            ),
665        },
666        other => other,
667    })?;
668    Ok(OpExpr { negated, operation })
669}
670
671/// Map an operator name to its comparison operator, if it is one.
672///
673/// These are exactly the operators that accept an `any`/`all` quantifier.
674fn quant_operator(name: &str) -> Option<QuantOperator> {
675    Some(match name {
676        "eq" => QuantOperator::Equal,
677        "gt" => QuantOperator::GreaterThan,
678        "gte" => QuantOperator::GreaterThanEqual,
679        "lt" => QuantOperator::LessThan,
680        "lte" => QuantOperator::LessThanEqual,
681        "like" => QuantOperator::Like,
682        "ilike" => QuantOperator::ILike,
683        "match" => QuantOperator::Match,
684        "imatch" => QuantOperator::IMatch,
685        _ => return None,
686    })
687}
688
689/// Parse the parenthesised modifier of a quantified comparison.
690fn parse_quantifier(modifier: &str) -> Option<OpQuantifier> {
691    match modifier {
692        "any" => Some(OpQuantifier::Any),
693        "all" => Some(OpQuantifier::All),
694        _ => None,
695    }
696}
697
698/// Parse an operation: `eq.value`, `in.(a,b,c)`, `is.null`, etc.
699fn parse_operation(value: &str) -> Result<Operation> {
700    // A quantified comparison spells the quantifier in parentheses after the
701    // operator name: `col=like(any).{foo,bar}`. Full-text search borrows the
702    // same shape for its language, so the operator name decides the reading.
703    if let Some((name, rest)) = value.split_once('(') {
704        if let Some((modifier, operand)) = rest.split_once(").") {
705            if let (Some(op), Some(quantifier)) = (quant_operator(name), parse_quantifier(modifier))
706            {
707                return Ok(Operation::Quant {
708                    op,
709                    quantifier: Some(quantifier),
710                    value: operand.to_string(),
711                });
712            }
713        }
714    }
715
716    // Comparison operators. Every one of these accepts a quantifier, so they
717    // share the lookup above rather than repeating the name-to-operator map.
718    if let Some((name, rest)) = value.split_once('.') {
719        if let Some(op) = quant_operator(name) {
720            return Ok(Operation::Quant {
721                op,
722                quantifier: None,
723                value: rest.to_string(),
724            });
725        }
726    }
727
728    if let Some(rest) = value.strip_prefix("neq.") {
729        return Ok(Operation::Simple {
730            op: SimpleOperator::NotEqual,
731            value: rest.to_string(),
732        });
733    }
734
735    // Array/Range operators
736    if let Some(rest) = value.strip_prefix("cs.") {
737        return Ok(Operation::Simple {
738            op: SimpleOperator::Contains,
739            value: rest.to_string(),
740        });
741    }
742    if let Some(rest) = value.strip_prefix("cd.") {
743        return Ok(Operation::Simple {
744            op: SimpleOperator::Contained,
745            value: rest.to_string(),
746        });
747    }
748    if let Some(rest) = value.strip_prefix("ov.") {
749        return Ok(Operation::Simple {
750            op: SimpleOperator::Overlap,
751            value: rest.to_string(),
752        });
753    }
754    if let Some(rest) = value.strip_prefix("sl.") {
755        return Ok(Operation::Simple {
756            op: SimpleOperator::StrictlyLeft,
757            value: rest.to_string(),
758        });
759    }
760    if let Some(rest) = value.strip_prefix("sr.") {
761        return Ok(Operation::Simple {
762            op: SimpleOperator::StrictlyRight,
763            value: rest.to_string(),
764        });
765    }
766    if let Some(rest) = value.strip_prefix("nxr.") {
767        return Ok(Operation::Simple {
768            op: SimpleOperator::NotExtendsRight,
769            value: rest.to_string(),
770        });
771    }
772    if let Some(rest) = value.strip_prefix("nxl.") {
773        return Ok(Operation::Simple {
774            op: SimpleOperator::NotExtendsLeft,
775            value: rest.to_string(),
776        });
777    }
778    if let Some(rest) = value.strip_prefix("adj.") {
779        return Ok(Operation::Simple {
780            op: SimpleOperator::Adjacent,
781            value: rest.to_string(),
782        });
783    }
784
785    // IN operator
786    if let Some(rest) = value.strip_prefix("in.") {
787        let values = parse_in_list(rest)?;
788        return Ok(Operation::In(values));
789    }
790
791    // IS operator
792    if let Some(rest) = value.strip_prefix("is.") {
793        // These are the only case-insensitive operands in the grammar, and
794        // `not_null` has no operator of its own -- `is.not_null` is the only
795        // spelling of `IS NOT NULL`.
796        let is_val = match rest.to_ascii_lowercase().as_str() {
797            "null" => IsValue::Null,
798            "not_null" => IsValue::NotNull,
799            "true" => IsValue::True,
800            "false" => IsValue::False,
801            "unknown" => IsValue::Unknown,
802            _ => return Err(unreadable_is_value(rest)),
803        };
804        return Ok(Operation::Is(is_val));
805    }
806
807    // IS DISTINCT FROM
808    if let Some(rest) = value.strip_prefix("isdistinct.") {
809        return Ok(Operation::IsDistinctFrom(rest.to_string()));
810    }
811
812    // Full-text search
813    if let Some(rest) = value.strip_prefix("fts") {
814        return parse_fts(FtsOperator::Fts, rest);
815    }
816    if let Some(rest) = value.strip_prefix("plfts") {
817        return parse_fts(FtsOperator::Plain, rest);
818    }
819    if let Some(rest) = value.strip_prefix("phfts") {
820        return parse_fts(FtsOperator::Phrase, rest);
821    }
822    if let Some(rest) = value.strip_prefix("wfts") {
823        return parse_fts(FtsOperator::Websearch, rest);
824    }
825
826    Err(Error::InvalidQueryParam(value.into()))
827}
828
829/// The four modifiers an order term accepts, and where reading one stopped.
830///
831/// Reading gets as far as the word still could be one of them and reports the
832/// character that ruled the last one out, so `nullslasttt` fails on the tenth
833/// character rather than on the word.
834fn unreadable_order(term: &str, at: usize, part: &str) -> Error {
835    const MODIFIERS: [&str; 4] = ["asc", "desc", "nullsfirst", "nullslast"];
836
837    let read = MODIFIERS
838        .iter()
839        .map(|modifier| {
840            part.chars()
841                .zip(modifier.chars())
842                .take_while(|(a, b)| a == b)
843                .count()
844        })
845        .max()
846        .unwrap_or(0);
847
848    Error::UnparsableQuery {
849        kind: "order",
850        text: term.to_string(),
851        column: at + read + 1,
852        expected: format!(
853            "unexpected {:?} expecting \",\" or end of input",
854            part.chars().nth(read).unwrap_or_default()
855        ),
856    }
857}
858
859/// The five things `is.` accepts, and where reading one stopped.
860///
861/// Reading gets as far as the operand still could be one of them and reports
862/// the character that ruled the last one out -- `is.nil` fails on the `i`,
863/// having read `n` as the start of `null`, while `is.ok` fails on the `o`.
864/// That is where a client has to look, and it is the difference between a
865/// message about a typo and one about the whole request.
866fn unreadable_is_value(rest: &str) -> Error {
867    const VALUES: [&str; 5] = ["null", "not_null", "true", "false", "unknown"];
868
869    let lowered = rest.to_ascii_lowercase();
870    let read = VALUES
871        .iter()
872        .map(|value| {
873            lowered
874                .chars()
875                .zip(value.chars())
876                .take_while(|(a, b)| a == b)
877                .count()
878        })
879        .max()
880        .unwrap_or(0);
881
882    Error::UnparsableQuery {
883        kind: "filter",
884        text: format!("is.{}", rest),
885        // Counting from one, past the `is.` that was read before this.
886        column: 4 + read,
887        expected: format!(
888            "unexpected \"{}\" expecting isVal: ({})",
889            rest.chars().nth(read).unwrap_or_default(),
890            VALUES.join(", ")
891        ),
892    }
893}
894
895/// Parse IN list: `(a,b,c)` -> vec!["a", "b", "c"]
896fn parse_in_list(value: &str) -> Result<Vec<String>> {
897    // Whitespace immediately inside the parentheses is not part of the first
898    // or last element: `in.(    )` is the empty list, while `in.( ,3,4)` has
899    // an empty first element and is a type error the database reports.
900    let inner = value
901        .trim()
902        .strip_prefix('(')
903        .and_then(|s| s.strip_suffix(')'))
904        .map(|inner| {
905            inner
906                .trim_start_matches([' ', '\t'])
907                .trim_end_matches([' ', '\t'])
908        })
909        .ok_or_else(|| Error::InvalidQueryParam(format!("in.{}", value)))?;
910
911    // `in.()` names no values at all, which is not the same as naming one
912    // empty value -- and is what `?id=in.()` returning nothing means.
913    if inner.is_empty() {
914        return Ok(Vec::new());
915    }
916
917    let mut values = Vec::new();
918    let mut rest = inner;
919
920    loop {
921        // Quoting is what lets a value contain the comma that would otherwise
922        // end it, so it counts only when it spans the whole element: in
923        // `Double"Quote"McGraw"` the quotes are part of the name, and taking
924        // them for syntax would silently change what was asked for.
925        let element = match quoted_element(rest) {
926            Some((unquoted, remainder)) => {
927                rest = remainder;
928                unquoted
929            }
930            None => {
931                let end = rest.find(',').unwrap_or(rest.len());
932                let (element, remainder) = rest.split_at(end);
933                rest = remainder;
934                element.to_string()
935            }
936        };
937        values.push(element);
938
939        match rest.strip_prefix(',') {
940            Some(remainder) => rest = remainder,
941            None => break,
942        }
943    }
944
945    Ok(values)
946}
947
948/// A complete double-quoted element at the head of `input`.
949///
950/// `None` unless the closing quote ends the element -- what follows it has to
951/// be the comma that separates elements, or nothing at all.
952fn quoted_element(input: &str) -> Option<(String, &str)> {
953    let body = input.strip_prefix('"')?;
954
955    let mut value = String::new();
956    let mut chars = body.char_indices();
957    while let Some((index, ch)) = chars.next() {
958        match ch {
959            '\\' => {
960                let (_, escaped) = chars.next()?;
961                value.push(escaped);
962            }
963            '"' => {
964                let rest = &body[index + 1..];
965                return match rest.is_empty() || rest.starts_with(',') {
966                    true => Some((value, rest)),
967                    false => None,
968                };
969            }
970            other => value.push(other),
971        }
972    }
973
974    None
975}
976
977/// Parse FTS operation: `(language).query` or `.query`
978fn parse_fts(op: FtsOperator, rest: &str) -> Result<Operation> {
979    if let Some(rest) = rest.strip_prefix('(') {
980        // Has language specifier
981        let (lang, query) = rest
982            .split_once(").")
983            .ok_or_else(|| Error::InvalidQueryParam(format!("fts{}", rest)))?;
984        return Ok(Operation::Fts {
985            op,
986            language: Some(lang.to_string()),
987            value: query.to_string(),
988        });
989    }
990
991    let query = rest
992        .strip_prefix('.')
993        .ok_or_else(|| Error::InvalidQueryParam(format!("fts{}", rest)))?;
994    Ok(Operation::Fts {
995        op,
996        language: None,
997        value: query.to_string(),
998    })
999}
1000
1001// ============================================================================
1002// Order Parsing
1003// ============================================================================
1004
1005/// Parse order parameter: `col.desc.nullsfirst,col2.asc`
1006fn parse_order_param(value: &str) -> Result<(EmbedPath, Vec<OrderTerm>)> {
1007    let terms: Vec<OrderTerm> = value
1008        .split(',')
1009        .map(|s| parse_order_term(s.trim()))
1010        .collect::<Result<Vec<_>>>()?;
1011    Ok((vec![], terms))
1012}
1013
1014fn parse_order_term(value: &str) -> Result<OrderTerm> {
1015    let parts: Vec<&str> = value.split('.').collect();
1016    if parts.is_empty() {
1017        return Err(Error::InvalidQueryParam("order".into()));
1018    }
1019
1020    let field_name = parts[0];
1021    let field = split_json_path(field_name);
1022    let mut direction = None;
1023    let mut nulls = None;
1024
1025    // Where each modifier starts within the term, so a word that is not one
1026    // can be reported at the character that made it not one.
1027    let mut at = field_name.len() + 1;
1028    for part in &parts[1..] {
1029        match *part {
1030            "asc" => direction = Some(OrderDirection::Asc),
1031            "desc" => direction = Some(OrderDirection::Desc),
1032            "nullsfirst" => nulls = Some(OrderNulls::First),
1033            "nullslast" => nulls = Some(OrderNulls::Last),
1034            // Not one of the four. Ignoring it answered a request nobody made:
1035            // `order=id.asc.nullslasttt` was read as `id.asc` and the typo
1036            // silently changed nothing, so a client asking for nulls last got
1037            // whatever the table happened to give it.
1038            other => return Err(unreadable_order(value, at, other)),
1039        }
1040        at += part.len() + 1;
1041    }
1042
1043    // `clients(name)` orders by a column of an embedded resource rather than
1044    // by one of this table's own.
1045    if let Some((relation, rest)) = field_name.split_once('(') {
1046        if let Some(column) = rest.strip_suffix(')') {
1047            return Ok(OrderTerm::Relation {
1048                relation: relation.to_string(),
1049                field: split_json_path(column),
1050                direction,
1051                nulls,
1052            });
1053        }
1054    }
1055
1056    Ok(OrderTerm::Field {
1057        field,
1058        direction,
1059        nulls,
1060    })
1061}
1062
1063// ============================================================================
1064// Logic Tree Parsing
1065// ============================================================================
1066
1067/// Parse `and` or `or` parameter: `(filter1,filter2)`
1068fn parse_logic_param(op: LogicOperator, negated: bool, value: &str) -> Result<LogicTree> {
1069    // Whitespace around the group and around each member is insignificant, as
1070    // it is in PostgREST: `and=( a.eq.1 , b.eq.2 )` is the same request as
1071    // `and=(a.eq.1,b.eq.2)`.
1072    // The group ends at the parenthesis that closes it, not at the last one in
1073    // the string: `and=(a.eq.1,b.eq.2))` is a well-formed group with a stray
1074    // character after it, and PostgREST reads it as one.
1075    let trimmed = value.trim();
1076    let inner = balanced_group(trimmed).ok_or_else(|| Error::InvalidQueryParam(value.into()))?;
1077
1078    // Where a member is empty there is nothing to hand the filter parser, and
1079    // "Invalid request" says only that something in a URL the client wrote is
1080    // wrong. PostgREST names the character and what would have been accepted
1081    // there, counting from the start of the tree as it spells it -- `or=(...)`
1082    // is read as `or(...)`, so the `=` is not a column and the operator's own
1083    // name is.
1084    let members = split_top_level(inner);
1085    for member in &members {
1086        if !member.trim().is_empty() {
1087            continue;
1088        }
1089        let at = offset_within(trimmed, member);
1090        return Err(Error::UnparsableQuery {
1091            kind: "logic tree",
1092            text: trimmed.to_string(),
1093            column: negated as usize * "not.".len()
1094                + match op {
1095                    LogicOperator::And => 3,
1096                    LogicOperator::Or => 2,
1097                }
1098                + at
1099                + 1,
1100            expected: format!(
1101                "unexpected \"{}\" expecting field name (* or [a..z0..9_$]), \
1102                 negation operator (not) or logic operator (and, or)",
1103                trimmed[at..].chars().next().unwrap_or_default()
1104            ),
1105        });
1106    }
1107
1108    Ok(LogicTree::Expr {
1109        negated,
1110        op,
1111        children: members
1112            .into_iter()
1113            .map(parse_logic_child)
1114            .collect::<Result<Vec<_>>>()?,
1115    })
1116}
1117
1118/// Where `part` begins inside `whole`, which it is a subslice of.
1119///
1120/// The split loses the positions and the message needs them; taking them from
1121/// the pointers is exact where searching for the text would find the wrong
1122/// occurrence of a repeated member.
1123fn offset_within(whole: &str, part: &str) -> usize {
1124    (part.as_ptr() as usize).saturating_sub(whole.as_ptr() as usize)
1125}
1126
1127/// The contents of a parenthesised group at the head of `input`.
1128///
1129/// Anything after the closing parenthesis is not part of the group and is
1130/// discarded, which is what a parser that does not demand end-of-input does.
1131fn balanced_group(input: &str) -> Option<&str> {
1132    let body = input.strip_prefix('(')?;
1133
1134    let mut depth = 0usize;
1135    let mut quoted = false;
1136    let mut escaped = false;
1137
1138    for (idx, ch) in body.char_indices() {
1139        if quoted {
1140            match ch {
1141                _ if escaped => escaped = false,
1142                '\\' => escaped = true,
1143                '"' => quoted = false,
1144                _ => {}
1145            }
1146            continue;
1147        }
1148        match ch {
1149            '"' => quoted = true,
1150            '(' => depth += 1,
1151            ')' if depth == 0 => return Some(&body[..idx]),
1152            ')' => depth -= 1,
1153            _ => {}
1154        }
1155    }
1156
1157    None
1158}
1159
1160/// Split a comma-separated list on its top-level commas only.
1161///
1162/// A logic list holds whole conditions, and a condition may contain commas of
1163/// its own -- `id.in.(1,2)`, `arr.cs.{1,2}`, a nested `and(...)`, or a quoted
1164/// value. Splitting on every comma tears those apart.
1165fn split_top_level(input: &str) -> Vec<&str> {
1166    let mut parts = Vec::new();
1167    let mut depth = 0usize;
1168    let mut quoted = false;
1169    let mut escaped = false;
1170    let mut start = 0usize;
1171
1172    for (idx, ch) in input.char_indices() {
1173        if quoted {
1174            match ch {
1175                _ if escaped => escaped = false,
1176                '\\' => escaped = true,
1177                '"' => quoted = false,
1178                _ => {}
1179            }
1180            continue;
1181        }
1182        match ch {
1183            '"' => quoted = true,
1184            '(' | '{' | '[' => depth += 1,
1185            ')' | '}' | ']' => depth = depth.saturating_sub(1),
1186            ',' if depth == 0 => {
1187                parts.push(&input[start..idx]);
1188                start = idx + ch.len_utf8();
1189            }
1190            _ => {}
1191        }
1192    }
1193    parts.push(&input[start..]);
1194    parts
1195}
1196
1197/// Parse one member of a logic list: either a nested group or a condition.
1198fn parse_logic_child(item: &str) -> Result<LogicTree> {
1199    let item = item.trim();
1200
1201    // `not.and(...)` negates the group. A leading `not.` on anything else
1202    // belongs to the condition's operator (`arr.not.cs.{1,2}`), so it is left
1203    // in place for the filter parser to deal with.
1204    let (body, negated) = match item.strip_prefix("not.") {
1205        Some(rest) if rest.starts_with("and(") || rest.starts_with("or(") => (rest, true),
1206        _ => (item, false),
1207    };
1208
1209    for (name, op) in [("and", LogicOperator::And), ("or", LogicOperator::Or)] {
1210        if let Some(rest) = body.strip_prefix(name) {
1211            let rest = rest.trim_start();
1212            if rest.starts_with('(') && rest.ends_with(')') {
1213                return parse_logic_param(op, negated, rest);
1214            }
1215        }
1216    }
1217
1218    let (key, val) = body
1219        .split_once('.')
1220        .ok_or_else(|| Error::InvalidQueryParam(item.into()))?;
1221    let (_, filter) = parse_filter_param(key, &unquote_logic_operand(val))?;
1222    Ok(LogicTree::Stmt(filter))
1223}
1224
1225/// Strip the quotes from a logic-tree operand.
1226///
1227/// Inside `or=(...)` a value may be quoted so that it can contain the comma
1228/// that would otherwise end it -- `name.eq."(grandchild,entity,4)"` -- and the
1229/// quotes are then syntax rather than part of the value. Outside a logic tree
1230/// there is nothing to protect the value from, so a quote there is a
1231/// character like any other and is left alone.
1232fn unquote_logic_operand(value: &str) -> String {
1233    let Some(open) = value.find('"') else {
1234        return value.to_string();
1235    };
1236    // The quote has to open the operand rather than sit inside one: `id.in.(
1237    // "a","b")` is a list, which does its own unquoting element by element.
1238    if open != 0 && !value[..open].ends_with('.') {
1239        return value.to_string();
1240    }
1241    if !value.ends_with('"') || value.len() < open + 2 {
1242        return value.to_string();
1243    }
1244
1245    let mut unquoted = String::from(&value[..open]);
1246    let mut chars = value[open + 1..value.len() - 1].chars();
1247    while let Some(ch) = chars.next() {
1248        match ch {
1249            '\\' => {
1250                if let Some(escaped) = chars.next() {
1251                    unquoted.push(escaped);
1252                }
1253            }
1254            other => unquoted.push(other),
1255        }
1256    }
1257    unquoted
1258}
1259
1260/// A query parameter that modifies a resource rather than filtering it.
1261enum Modifier {
1262    Order,
1263    Limit,
1264    Offset,
1265    Logic(LogicOperator, bool),
1266}
1267
1268/// Recognise a modifier key and the embedded resource it addresses.
1269///
1270/// Every modifier may be aimed at an embedded resource by prefixing it with
1271/// the path to that resource: `clients.order=name` orders the embedded
1272/// clients, `clients.limit=1` pages them, `clients.or=(...)` filters them. The
1273/// bare forms are the same thing with an empty path.
1274fn parse_modifier_key(key: &str) -> Option<(EmbedPath, Modifier)> {
1275    let mut parts: Vec<&str> = key.split('.').collect();
1276    let last = parts.pop()?;
1277
1278    let modifier = match last {
1279        "order" => Modifier::Order,
1280        "limit" => Modifier::Limit,
1281        "offset" => Modifier::Offset,
1282        "and" | "or" => {
1283            let op = if last == "and" {
1284                LogicOperator::And
1285            } else {
1286                LogicOperator::Or
1287            };
1288            // `not.or=(...)` negates the whole group.
1289            let negated = parts.last() == Some(&"not");
1290            if negated {
1291                parts.pop();
1292            }
1293            Modifier::Logic(op, negated)
1294        }
1295        _ => return None,
1296    };
1297
1298    Some((parts.into_iter().map(String::from).collect(), modifier))
1299}
1300
1301// ============================================================================
1302// Helper Parsers
1303// ============================================================================
1304
1305/// The characters a bare identifier is made of.
1306///
1307/// PostgREST's set exactly: letters, digits, `_`, `$` and the space, with the
1308/// result trimmed. A space is allowed because a column may genuinely have one
1309/// -- `?select=Just A Server Model` -- and trimming is what keeps
1310/// `?select=id, name` from asking for a column called `name ` .
1311/// The SQL standard's type names that are more than one word.
1312///
1313/// Longest first, so that `time with time zone` is not read as `time` with
1314/// something left over. Each is written into the statement in this spelling,
1315/// never in the client's.
1316const MULTI_WORD_TYPES: &[&str] = &[
1317    "timestamp without time zone",
1318    "timestamp with time zone",
1319    "time without time zone",
1320    "time with time zone",
1321    "character varying",
1322    "double precision",
1323    "bit varying",
1324];
1325
1326/// Parse the type a value is cast to: `id::text`, `amount::double precision`.
1327///
1328/// The type is written into the statement as it is -- a type name is not a
1329/// value, so it cannot be bound, and quoting it would change its meaning
1330/// (`::"int"` names no type). So this is the whole of what keeps a cast from
1331/// carrying SQL of the client's into the statement: one type name, an
1332/// identifier of letters, digits, `_` and `$` that does not start with a
1333/// digit, or one of the standard's few multi-word names. Anything else after
1334/// `::` is not a cast, and the select it is in is refused as unparsable.
1335///
1336/// It used to be [`parse_identifier`], which admits spaces -- so that a column
1337/// name may contain one -- and with them `id::text as rolname` and any other
1338/// run of words.
1339fn parse_cast_type(input: &str) -> IResult<&str, &str> {
1340    for name in MULTI_WORD_TYPES {
1341        let Some(head) = input.get(..name.len()) else {
1342            continue;
1343        };
1344        let rest = &input[name.len()..];
1345        let ends_there =
1346            !rest.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$');
1347        if head.eq_ignore_ascii_case(name) && ends_there {
1348            return Ok((rest, name));
1349        }
1350    }
1351    recognize(pair(
1352        satisfy(|c| c.is_ascii_alphabetic() || c == '_'),
1353        take_while(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$'),
1354    ))(input)
1355}
1356
1357fn parse_identifier(input: &str) -> IResult<&str, &str> {
1358    let (rest, matched) =
1359        take_while1(|c: char| c.is_alphanumeric() || c == '_' || c == '$' || c == ' ')(input)?;
1360    Ok((rest, matched.trim()))
1361}
1362
1363/// Parse a field name: a quoted name, or dash-joined identifiers.
1364///
1365/// Quoting is how a client names a column the bare grammar cannot spell --
1366/// `"a.dotted.column"`, `"(inside,parens)"` -- and a backslash escapes the
1367/// next character inside it.
1368///
1369/// Unquoted, a `-` joins identifiers into one name, so `field-with_sep` is a
1370/// single column. A `-` that starts `->` is not a join: that is a JSON path,
1371/// and it belongs to whatever comes after the name.
1372fn parse_field_name(input: &str) -> IResult<&str, String> {
1373    if let Ok(quoted) = parse_quoted_name(input) {
1374        return Ok(quoted);
1375    }
1376
1377    let (mut rest, first) = parse_identifier(input)?;
1378    let mut name = first.to_string();
1379
1380    while let Some(after_dash) = rest.strip_prefix('-') {
1381        if after_dash.starts_with('>') {
1382            break;
1383        }
1384        let Ok((next, segment)) = parse_identifier(after_dash) else {
1385            break;
1386        };
1387        name.push('-');
1388        name.push_str(segment);
1389        rest = next;
1390    }
1391
1392    Ok((rest, name))
1393}
1394
1395/// Parse a double-quoted name, honouring backslash escapes.
1396fn parse_quoted_name(input: &str) -> IResult<&str, String> {
1397    let (rest, _) = char('"')(input)?;
1398
1399    let mut name = String::new();
1400    let mut chars = rest.char_indices();
1401    while let Some((index, ch)) = chars.next() {
1402        match ch {
1403            '\\' => {
1404                if let Some((_, escaped)) = chars.next() {
1405                    name.push(escaped);
1406                }
1407            }
1408            '"' => return Ok((&rest[index + 1..], name)),
1409            other => name.push(other),
1410        }
1411    }
1412
1413    Err(nom::Err::Error(nom::error::Error::new(
1414        input,
1415        nom::error::ErrorKind::Verify,
1416    )))
1417}
1418
1419fn parse_json_path(input: &str) -> IResult<&str, JsonPath> {
1420    // `->>` first: it starts with `->`, so trying the shorter one first would
1421    // match it and leave the second `>` at the head of the key.
1422    many0(alt((parse_double_arrow, parse_arrow)))(input)
1423}
1424
1425/// Parse one step of a JSON path.
1426///
1427/// A JSON object key can be very nearly anything, and PostgREST's grammar says
1428/// so: everything up to the next thing the select grammar itself reserves is
1429/// the key. `data->>!@#$%^&*_e` and `data->23-xy-45` are ordinary keys, not
1430/// syntax errors, and reading a key as alphanumeric-only silently truncated
1431/// the path and returned the whole column instead.
1432///
1433/// A key made entirely of digits is an array index, which is why this decides
1434/// between the two only once the whole key has been read: `data->0xy1` steps
1435/// into the key `0xy1`, not into element 0 of an array.
1436fn parse_json_operand(input: &str) -> IResult<&str, JsonOperand> {
1437    let mut end = input.len();
1438    for (idx, ch) in input.char_indices() {
1439        // `,` ends the select item, `(` and `)` bound an embedding, `:` starts
1440        // a cast or an alias, and `->` starts the next step.
1441        if matches!(ch, ',' | '(' | ')' | ':') || input[idx..].starts_with("->") {
1442            end = idx;
1443            break;
1444        }
1445    }
1446
1447    let (key, rest) = input.split_at(end);
1448    // The arrow has been read, so an empty key is a failure of the path, not
1449    // a step some other rule might match instead.
1450    if key.is_empty() {
1451        return Err(nom::Err::Failure(nom::error::Error::new(
1452            input,
1453            nom::error::ErrorKind::TakeWhile1,
1454        )));
1455    }
1456
1457    let operand = match key.parse::<i32>() {
1458        Ok(index) => JsonOperand::Idx(index),
1459        // A leading `-` begins an array index counted from the end, so what
1460        // follows it has to be a number. `data->>--34` was read as a key
1461        // literally named `--34` and answered 200 with nulls, where the
1462        // grammar has no such key in it and PostgREST says so.
1463        // A `Failure` rather than an `Error`: the arrow has already been read,
1464        // so this is not a step that some other rule might match instead.
1465        // Reported as a recoverable error, `alt` backtracked from `->>` to
1466        // `->` and read the rest as a key beginning with `>`, which turned a
1467        // malformed index into an ordinary lookup that answered 200.
1468        Err(_) if key.starts_with('-') => {
1469            return Err(nom::Err::Failure(nom::error::Error::new(
1470                &input[1..],
1471                nom::error::ErrorKind::Digit,
1472            )))
1473        }
1474        Err(_) => JsonOperand::Key(key.to_string()),
1475    };
1476    Ok((rest, operand))
1477}
1478
1479fn parse_arrow(input: &str) -> IResult<&str, JsonOperation> {
1480    let (input, _) = tag("->")(input)?;
1481    let (input, operand) = parse_json_operand(input)?;
1482    Ok((input, JsonOperation::Arrow(operand)))
1483}
1484
1485fn parse_double_arrow(input: &str) -> IResult<&str, JsonOperation> {
1486    let (input, _) = tag("->>")(input)?;
1487    let (input, operand) = parse_json_operand(input)?;
1488    Ok((input, JsonOperation::DoubleArrow(operand)))
1489}
1490
1491#[cfg(test)]
1492mod tests {
1493
1494    /// A cast is one type name. Words after it are not part of the type, and
1495    /// a select that carries them is refused rather than written into the
1496    /// statement.
1497    /// Nesting is bounded before anything recurses over it, so a deep
1498    /// `select` or logic tree is refused rather than overflowing the stack.
1499    #[test]
1500    fn nesting_is_bounded() {
1501        let select = |depth: usize| format!("{}id{}", "a(".repeat(depth), ")".repeat(depth));
1502        let or = |depth: usize| format!("or=({}a.eq.1{})", "or(".repeat(depth), ")".repeat(depth));
1503
1504        assert!(parse_select(&select(MAX_NESTING)).is_ok());
1505        assert!(parse_query_params(&or(MAX_NESTING - 1), false).is_ok());
1506        for depth in [MAX_NESTING + 1, 100_000] {
1507            assert!(matches!(
1508                parse_select(&select(depth)),
1509                Err(Error::InvalidQueryParam(_))
1510            ));
1511            assert!(matches!(
1512                parse_query_params(&or(depth), false),
1513                Err(Error::InvalidQueryParam(_))
1514            ));
1515        }
1516
1517        // A quoted value's parentheses are its own.
1518        let quoted = format!("or=(name.eq.\"{}\")", "(".repeat(1_000));
1519        assert!(parse_query_params(&quoted, false).is_ok());
1520    }
1521
1522    /// A JSON path that fails after its arrow is reported where it failed.
1523    #[test]
1524    fn a_bad_json_operand_is_reported_with_its_column() {
1525        let explain = |select: &str| match parse_select(select) {
1526            Err(Error::UnparsableQuery {
1527                kind,
1528                text,
1529                column,
1530                expected,
1531            }) => (kind, text, column, expected),
1532            other => panic!("{select:?}: {other:?}"),
1533        };
1534        let (kind, text, column, expected) = explain("data->>--34");
1535        assert_eq!(kind, "select parameter");
1536        assert_eq!(text, "data->>--34");
1537        assert_eq!(column, 9);
1538        assert_eq!(expected, "unexpected \"-\" expecting digit");
1539
1540        let (_, _, column, expected) = explain("data->(x");
1541        assert_eq!(column, 7);
1542        assert_eq!(
1543            expected,
1544            "unexpected \"(\" expecting \"-\", digit or any non reserved character different from: .,>()"
1545        );
1546    }
1547
1548    /// Compatibility mode drops an unreadable tail of `select`, as PostgREST
1549    /// does; the default refuses it. A dangling comma is an error in both.
1550    #[test]
1551    fn a_select_tail_is_dropped_only_in_compat_mode() {
1552        for select in ["name,projects(count)'", "id,clients(id))", "id,name!"] {
1553            assert!(parse_select(select).is_err(), "{select:?}");
1554            assert!(parse_select_lenient(select).is_ok(), "{select:?}");
1555        }
1556        assert_eq!(parse_select_lenient("name,projects(id))").unwrap().len(), 2);
1557        for select in ["id,", "id,,name", "id,'"] {
1558            assert!(parse_select_lenient(select).is_err(), "{select:?}");
1559        }
1560        let params = parse_query_params_with("select=name,projects(id))", false, true).unwrap();
1561        assert_eq!(params.select.len(), 2);
1562        assert!(parse_query_params_with("select=name,projects(id))", false, false).is_err());
1563    }
1564
1565    #[test]
1566    fn a_cast_is_a_type_name_and_nothing_more() {
1567        for select in [
1568            "id::text as rolname",
1569            "id::text from pg_roles where true or true",
1570            "id::int4 union select",
1571            "count()::text as x",
1572            "amount.sum()::numeric as x",
1573            "id::1text",
1574            "id::",
1575            "id::text;",
1576        ] {
1577            assert!(parse_select(select).is_err(), "{select:?} was accepted");
1578        }
1579    }
1580
1581    #[test]
1582    fn a_cast_names_a_bare_type_or_a_standard_multi_word_one() {
1583        let cast_of = |select: &str| match &parse_select(select).unwrap()[0] {
1584            SelectItem::Field {
1585                cast,
1586                aggregate_cast,
1587                ..
1588            } => cast.clone().or_else(|| aggregate_cast.clone()),
1589            other => panic!("{other:?}"),
1590        };
1591        assert_eq!(cast_of("id::text").as_deref(), Some("text"));
1592        assert_eq!(cast_of("id::int4").as_deref(), Some("int4"));
1593        assert_eq!(cast_of("id::_text").as_deref(), Some("_text"));
1594        assert_eq!(cast_of("id::my$type").as_deref(), Some("my$type"));
1595        assert_eq!(cast_of("count()::text").as_deref(), Some("text"));
1596        assert_eq!(
1597            cast_of("amount::Double Precision").as_deref(),
1598            Some("double precision"),
1599            "written in the standard's spelling, not the client's"
1600        );
1601        assert_eq!(
1602            cast_of("at::timestamp with time zone").as_deref(),
1603            Some("timestamp with time zone")
1604        );
1605        assert_eq!(
1606            cast_of("at::time with time zone").as_deref(),
1607            Some("time with time zone")
1608        );
1609        // `timestamptz` is one word, and not `timestamp` with `tz` left over.
1610        assert_eq!(cast_of("at::timestamptz").as_deref(), Some("timestamptz"));
1611        // A multi-word name followed by another item.
1612        assert_eq!(
1613            parse_select("amount::double precision,id").unwrap().len(),
1614            2
1615        );
1616    }
1617
1618    use super::*;
1619
1620    #[test]
1621    fn test_parse_simple_filter() {
1622        let params = parse_query_params("name=eq.John", false).unwrap();
1623        assert_eq!(params.filters_root.len(), 1);
1624        assert_eq!(params.filters_root[0].field.name, "name");
1625    }
1626
1627    #[test]
1628    fn test_parse_negated_filter() {
1629        let params = parse_query_params("status=not.eq.active", false).unwrap();
1630        assert!(params.filters_root[0].op_expr.negated);
1631    }
1632
1633    #[test]
1634    fn test_parse_in_filter() {
1635        let params = parse_query_params("id=in.(1,2,3)", false).unwrap();
1636        match &params.filters_root[0].op_expr.operation {
1637            Operation::In(values) => {
1638                assert_eq!(values, &vec!["1", "2", "3"]);
1639            }
1640            _ => panic!("Expected In operation"),
1641        }
1642    }
1643
1644    #[test]
1645    fn test_json_path_double_arrow_wins_over_single() {
1646        let items = parse_select("settings->foo->>bar").unwrap();
1647        match &items[0] {
1648            SelectItem::Field { field, .. } => {
1649                assert_eq!(
1650                    field.json_path,
1651                    vec![
1652                        JsonOperation::Arrow(JsonOperand::Key("foo".into())),
1653                        JsonOperation::DoubleArrow(JsonOperand::Key("bar".into())),
1654                    ]
1655                );
1656            }
1657            other => panic!("expected a field, got {:?}", other),
1658        }
1659    }
1660
1661    #[test]
1662    fn test_json_path_accepts_awkward_keys() {
1663        // PostgREST reserves only what its own grammar needs, so a key may
1664        // hold punctuation and hyphens.
1665        let items = parse_select("data->23-xy-45->>!@#$%^&*_e").unwrap();
1666        match &items[0] {
1667            SelectItem::Field { field, .. } => {
1668                assert_eq!(
1669                    field.json_path,
1670                    vec![
1671                        JsonOperation::Arrow(JsonOperand::Key("23-xy-45".into())),
1672                        JsonOperation::DoubleArrow(JsonOperand::Key("!@#$%^&*_e".into())),
1673                    ]
1674                );
1675            }
1676            other => panic!("expected a field, got {:?}", other),
1677        }
1678    }
1679
1680    #[test]
1681    fn test_json_path_digits_are_an_index_but_only_when_whole() {
1682        let items = parse_select("data->0,other->0xy1").unwrap();
1683        let paths: Vec<_> = items
1684            .iter()
1685            .map(|i| match i {
1686                SelectItem::Field { field, .. } => field.json_path.clone(),
1687                other => panic!("expected a field, got {:?}", other),
1688            })
1689            .collect();
1690        assert_eq!(paths[0], vec![JsonOperation::Arrow(JsonOperand::Idx(0))]);
1691        assert_eq!(
1692            paths[1],
1693            vec![JsonOperation::Arrow(JsonOperand::Key("0xy1".into()))]
1694        );
1695    }
1696
1697    #[test]
1698    fn test_json_path_stops_at_a_cast() {
1699        let items = parse_select("settings->>foo::json").unwrap();
1700        match &items[0] {
1701            SelectItem::Field { field, cast, .. } => {
1702                assert_eq!(
1703                    field.json_path,
1704                    vec![JsonOperation::DoubleArrow(JsonOperand::Key("foo".into()))]
1705                );
1706                assert_eq!(cast.as_deref(), Some("json"));
1707            }
1708            other => panic!("expected a field, got {:?}", other),
1709        }
1710    }
1711
1712    #[test]
1713    fn test_parse_spread_relation_keeps_its_columns() {
1714        let items = parse_select("title,...directors(first_name,last_name)").unwrap();
1715        assert_eq!(items.len(), 2);
1716        match &items[1] {
1717            SelectItem::SpreadRelation {
1718                relation, select, ..
1719            } => {
1720                assert_eq!(relation, "directors");
1721                let names: Vec<_> = select
1722                    .iter()
1723                    .map(|item| match item {
1724                        SelectItem::Field { field, .. } => field.name.clone(),
1725                        other => panic!("expected a field, got {:?}", other),
1726                    })
1727                    .collect();
1728                assert_eq!(names, vec!["first_name", "last_name"]);
1729            }
1730            other => panic!("expected a spread relation, got {:?}", other),
1731        }
1732    }
1733
1734    #[test]
1735    fn test_parse_spread_relation_does_not_swallow_later_items() {
1736        // The column list used to be left unconsumed, which silently truncated
1737        // everything after it.
1738        let items = parse_select("...directors(name),year").unwrap();
1739        assert_eq!(items.len(), 2);
1740        assert!(matches!(items[0], SelectItem::SpreadRelation { .. }));
1741        match &items[1] {
1742            SelectItem::Field { field, .. } => assert_eq!(field.name, "year"),
1743            other => panic!("expected a field, got {:?}", other),
1744        }
1745    }
1746
1747    #[test]
1748    fn test_parse_nested_spread_relation() {
1749        let items = parse_select("id,films(title,...directors(name))").unwrap();
1750        match &items[1] {
1751            SelectItem::Relation { select, .. } => {
1752                assert_eq!(select.len(), 2);
1753                assert!(matches!(select[1], SelectItem::SpreadRelation { .. }));
1754            }
1755            other => panic!("expected a relation, got {:?}", other),
1756        }
1757    }
1758
1759    #[test]
1760    fn test_parse_in_filter_with_quoted_commas() {
1761        let params = parse_query_params(r#"name=in.("hi,there","yes,you")"#, false).unwrap();
1762        match &params.filters_root[0].op_expr.operation {
1763            Operation::In(values) => {
1764                assert_eq!(values, &vec!["hi,there".to_string(), "yes,you".to_string()]);
1765            }
1766            other => panic!("expected an In operation, got {:?}", other),
1767        }
1768    }
1769
1770    #[test]
1771    fn test_parse_in_filter_with_escapes() {
1772        let params = parse_query_params(r#"name=in.("a\"b","c\\d")"#, false).unwrap();
1773        match &params.filters_root[0].op_expr.operation {
1774            Operation::In(values) => {
1775                assert_eq!(values, &vec![r#"a"b"#.to_string(), r#"c\d"#.to_string()]);
1776            }
1777            other => panic!("expected an In operation, got {:?}", other),
1778        }
1779    }
1780
1781    #[test]
1782    fn test_parse_quantified_filter() {
1783        for (query, expected) in [
1784            ("id=eq(any).{1,2,3}", OpQuantifier::Any),
1785            ("id=eq(all).{1,2,3}", OpQuantifier::All),
1786        ] {
1787            let params = parse_query_params(query, false).unwrap();
1788            match &params.filters_root[0].op_expr.operation {
1789                Operation::Quant {
1790                    op,
1791                    quantifier,
1792                    value,
1793                } => {
1794                    assert_eq!(op, &QuantOperator::Equal);
1795                    assert_eq!(quantifier.as_ref(), Some(&expected));
1796                    assert_eq!(value, "{1,2,3}");
1797                }
1798                other => panic!("expected a quantified operation, got {:?}", other),
1799            }
1800        }
1801    }
1802
1803    #[test]
1804    fn test_parse_quantified_like_keeps_array_literal() {
1805        let params = parse_query_params("name=like(any).{foo*,bar*}", false).unwrap();
1806        match &params.filters_root[0].op_expr.operation {
1807            Operation::Quant {
1808                op,
1809                quantifier,
1810                value,
1811            } => {
1812                assert_eq!(op, &QuantOperator::Like);
1813                assert_eq!(quantifier.as_ref(), Some(&OpQuantifier::Any));
1814                // The `*`-to-`%` mapping belongs to SQL generation, so the
1815                // parsed operand is still the literal the client sent.
1816                assert_eq!(value, "{foo*,bar*}");
1817            }
1818            other => panic!("expected a quantified operation, got {:?}", other),
1819        }
1820    }
1821
1822    #[test]
1823    fn test_parse_negated_quantified_filter() {
1824        let params = parse_query_params("id=not.eq(any).{1,2}", false).unwrap();
1825        assert!(params.filters_root[0].op_expr.negated);
1826        assert!(matches!(
1827            params.filters_root[0].op_expr.operation,
1828            Operation::Quant {
1829                quantifier: Some(OpQuantifier::Any),
1830                ..
1831            }
1832        ));
1833    }
1834
1835    #[test]
1836    fn test_quantifier_form_does_not_capture_fts_language() {
1837        // `fts(english).x` has the same shape but is not a quantified
1838        // comparison; the operator name is what tells the two apart.
1839        let params = parse_query_params("body=fts(english).cat", false).unwrap();
1840        match &params.filters_root[0].op_expr.operation {
1841            Operation::Fts { language, .. } => {
1842                assert_eq!(language.as_deref(), Some("english"));
1843            }
1844            other => panic!("expected an fts operation, got {:?}", other),
1845        }
1846    }
1847
1848    #[test]
1849    fn test_parse_is_null() {
1850        let params = parse_query_params("deleted_at=is.null", false).unwrap();
1851        match &params.filters_root[0].op_expr.operation {
1852            Operation::Is(IsValue::Null) => {}
1853            _ => panic!("Expected Is Null"),
1854        }
1855    }
1856
1857    #[test]
1858    fn test_parse_order() {
1859        let params = parse_query_params("order=name.asc,age.desc.nullslast", false).unwrap();
1860        assert_eq!(params.order.len(), 1);
1861        let (_, terms) = &params.order[0];
1862        assert_eq!(terms.len(), 2);
1863    }
1864
1865    #[test]
1866    fn test_parse_limit_offset() {
1867        let params = parse_query_params("limit=10&offset=20", false).unwrap();
1868        let range = params.ranges.get("").unwrap();
1869        assert_eq!(range.limit, Some(10));
1870        assert_eq!(range.offset, 20);
1871    }
1872
1873    #[test]
1874    fn test_parse_select() {
1875        let items = parse_select("id,name,orders(id,amount)").unwrap();
1876        assert_eq!(items.len(), 3);
1877    }
1878
1879    #[test]
1880    fn test_parse_fts() {
1881        let params = parse_query_params("content=fts(english).search+term", false).unwrap();
1882        match &params.filters_root[0].op_expr.operation {
1883            Operation::Fts {
1884                op,
1885                language,
1886                value,
1887            } => {
1888                assert_eq!(*op, FtsOperator::Fts);
1889                assert_eq!(language.as_deref(), Some("english"));
1890                assert_eq!(value, "search+term");
1891            }
1892            _ => panic!("Expected FTS operation"),
1893        }
1894    }
1895    /// `?columns=` names no field, and is reported as the parameter it is.
1896    #[test]
1897    fn an_empty_columns_parameter_is_a_parse_error() {
1898        let error = parse_columns("").unwrap_err();
1899        assert_eq!(
1900            error.to_string(),
1901            "\"failed to parse columns parameter ()\" (line 1, column 1)"
1902        );
1903        match error {
1904            Error::UnparsableQuery { expected, .. } => assert_eq!(
1905                expected,
1906                "unexpected end of input expecting field name (* or [a..z0..9_$])"
1907            ),
1908            other => panic!("wrong variant: {:?}", other),
1909        }
1910    }
1911
1912    /// A gap in the middle is reported where the gap is, not at the end.
1913    #[test]
1914    fn a_missing_field_in_columns_is_reported_where_it_is() {
1915        let error = parse_columns("a,,b").unwrap_err();
1916        assert_eq!(
1917            error.to_string(),
1918            "\"failed to parse columns parameter (a,,b)\" (line 1, column 3)"
1919        );
1920    }
1921
1922    #[test]
1923    fn columns_parses_a_plain_list() {
1924        assert_eq!(
1925            parse_columns("a, b ,c").unwrap(),
1926            vec!["a".to_string(), "b".to_string(), "c".to_string()]
1927        );
1928    }
1929
1930    /// A `-` inside a JSON path begins an index, so a non-number after it is
1931    /// not a key by another name.
1932    #[test]
1933    fn a_json_path_index_that_is_not_a_number_is_refused() {
1934        assert!(parse_select("data->>--34").is_err());
1935        assert!(parse_select("data->>-34").is_ok());
1936        assert!(parse_select("data->>34").is_ok());
1937        assert!(parse_select("data->>key").is_ok());
1938    }
1939    /// An empty member of a logic tree is reported the way PostgREST reports
1940    /// it, which counts from the tree as it spells it: `or=(...)` is read as
1941    /// `or(...)`, so the `=` is not a column and the operator's name is.
1942    #[test]
1943    fn an_empty_logic_tree_member_names_the_character_and_the_column() {
1944        let error = parse_logic_param(LogicOperator::Or, false, "()").unwrap_err();
1945        assert_eq!(
1946            error.to_string(),
1947            "\"failed to parse logic tree (())\" (line 1, column 4)"
1948        );
1949        match &error {
1950            Error::UnparsableQuery { expected, .. } => assert_eq!(
1951                expected,
1952                "unexpected \")\" expecting field name (* or [a..z0..9_$]), \
1953                 negation operator (not) or logic operator (and, or)"
1954            ),
1955            other => panic!("wrong variant: {:?}", other),
1956        }
1957
1958        // `and` is a longer name, so the same shape reports one column later.
1959        let error = parse_logic_param(LogicOperator::And, false, "()").unwrap_err();
1960        assert_eq!(
1961            error.to_string(),
1962            "\"failed to parse logic tree (())\" (line 1, column 5)"
1963        );
1964
1965        // A gap between two members is reported where the gap is.
1966        let error = parse_logic_param(LogicOperator::Or, false, "(,)").unwrap_err();
1967        assert_eq!(
1968            error.to_string(),
1969            "\"failed to parse logic tree ((,))\" (line 1, column 4)"
1970        );
1971    }
1972}