1use 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
19pub fn parse_query_params(query: &str, is_rpc: bool) -> Result<QueryParams> {
29 parse_query_params_with(query, is_rpc, false)
30}
31
32pub 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 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 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 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 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 let parsed = parse_filter_param(key, &decoded_value);
141 let (path, filter) = match parsed {
142 Ok(parsed) => parsed,
143 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 params.params.push((key.to_string(), decoded_value));
159 }
160 }
161 }
162
163 Ok(params)
164}
165
166fn 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 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 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
214pub 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 match parse_select_items(input) {
226 Ok(("", items)) => Ok(items),
227 Err(nom::Err::Failure(failure)) => Err(unreadable_json_operand(input, failure)),
230 _ => Err(Error::InvalidQueryParam(format!("select={}", input))),
231 }
232}
233
234pub 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
255fn 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
275const MAX_NESTING: usize = 64;
283
284fn 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 let (input, _) = nom::character::complete::space0(input)?;
327 alt((
328 parse_star,
329 parse_bare_aggregate,
332 parse_spread_relation,
333 parse_relation_select,
334 parse_field_select,
335 ))(input)
336}
337
338fn parse_star(input: &str) -> IResult<&str, SelectItem> {
344 let (input, _) = char('*')(input)?;
345 Ok((input, SelectItem::field("*")))
346}
347
348fn 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 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
371fn 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
385fn 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 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
408fn 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
446fn parse_relation_select(input: &str) -> IResult<&str, SelectItem> {
448 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 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
471fn parse_field_select(input: &str) -> IResult<&str, SelectItem> {
473 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 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
504fn 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
547fn parse_filter_param(key: &str, value: &str) -> Result<(EmbedPath, Filter)> {
553 let (path, field) = parse_filter_key(key)?;
555
556 let op_expr = parse_filter_value(value)?;
558
559 Ok((path, Filter::new(field, op_expr)))
560}
561
562fn 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
580fn 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
604fn 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
633pub fn value_is_filter(value: &str) -> bool {
640 parse_filter_value(value).is_ok()
641}
642
643fn 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 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
671fn 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
689fn parse_quantifier(modifier: &str) -> Option<OpQuantifier> {
691 match modifier {
692 "any" => Some(OpQuantifier::Any),
693 "all" => Some(OpQuantifier::All),
694 _ => None,
695 }
696}
697
698fn parse_operation(value: &str) -> Result<Operation> {
700 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 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 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 if let Some(rest) = value.strip_prefix("in.") {
787 let values = parse_in_list(rest)?;
788 return Ok(Operation::In(values));
789 }
790
791 if let Some(rest) = value.strip_prefix("is.") {
793 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 if let Some(rest) = value.strip_prefix("isdistinct.") {
809 return Ok(Operation::IsDistinctFrom(rest.to_string()));
810 }
811
812 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
829fn 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
859fn 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 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
895fn parse_in_list(value: &str) -> Result<Vec<String>> {
897 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 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 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
948fn 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
977fn parse_fts(op: FtsOperator, rest: &str) -> Result<Operation> {
979 if let Some(rest) = rest.strip_prefix('(') {
980 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
1001fn 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 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 other => return Err(unreadable_order(value, at, other)),
1039 }
1040 at += part.len() + 1;
1041 }
1042
1043 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
1063fn parse_logic_param(op: LogicOperator, negated: bool, value: &str) -> Result<LogicTree> {
1069 let trimmed = value.trim();
1076 let inner = balanced_group(trimmed).ok_or_else(|| Error::InvalidQueryParam(value.into()))?;
1077
1078 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
1118fn offset_within(whole: &str, part: &str) -> usize {
1124 (part.as_ptr() as usize).saturating_sub(whole.as_ptr() as usize)
1125}
1126
1127fn 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
1160fn 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
1197fn parse_logic_child(item: &str) -> Result<LogicTree> {
1199 let item = item.trim();
1200
1201 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
1225fn unquote_logic_operand(value: &str) -> String {
1233 let Some(open) = value.find('"') else {
1234 return value.to_string();
1235 };
1236 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
1260enum Modifier {
1262 Order,
1263 Limit,
1264 Offset,
1265 Logic(LogicOperator, bool),
1266}
1267
1268fn 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 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
1301const 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
1326fn 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
1363fn 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
1395fn 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 many0(alt((parse_double_arrow, parse_arrow)))(input)
1423}
1424
1425fn parse_json_operand(input: &str) -> IResult<&str, JsonOperand> {
1437 let mut end = input.len();
1438 for (idx, ch) in input.char_indices() {
1439 if matches!(ch, ',' | '(' | ')' | ':') || input[idx..].starts_with("->") {
1442 end = idx;
1443 break;
1444 }
1445 }
1446
1447 let (key, rest) = input.split_at(end);
1448 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 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 #[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 let quoted = format!("or=(name.eq.\"{}\")", "(".repeat(1_000));
1519 assert!(parse_query_params("ed, false).is_ok());
1520 }
1521
1522 #[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 #[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 assert_eq!(cast_of("at::timestamptz").as_deref(), Some("timestamptz"));
1611 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 ¶ms.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 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 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 ¶ms.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 ¶ms.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 ¶ms.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 ¶ms.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 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 let params = parse_query_params("body=fts(english).cat", false).unwrap();
1840 match ¶ms.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 ¶ms.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) = ¶ms.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 ¶ms.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 #[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 #[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 #[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 #[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 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 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}