# UnQuery: Universal Query String Filter Specification

Version: 0.1.0 · Status: draft · License: Apache-2.0

Source: lingodata/unquery@865de91

## 0. Introduction

UnQuery (Universal Query String Filter Specification) defines how to write search filters for documents, in URLs and in JSON, independently of the data source. It is part of the **LingoData** family of specifications for data interoperability.

A filter is defined once, as an abstract model ([section 1](#1-query-model)), and can be written in two syntaxes: JSON ([section 2](#2-json-syntax)) and a restricted SQL predicate syntax ([section 3](#3-sql-syntax)). [Section 4](#4-query-string-mapping) maps both to URL query strings. Implementations translate filters to each data source, such as MongoDB, PostgreSQL, MySQL, Notion or Airtable, and never pass filter text to a data source.

Within the family, UnQuery operands are [ECSON](https://github.com/lingodata/ecson) values, and UnQuery is the search query format recommended by the CRUD API Base Specification.

### 0.1 Conventions

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)) when, and only when, they appear in all capitals, as shown here.

Normative rules are identified by a code (for example [`NULL_NE`](#NULL_NE)). Notes, examples and rationales are informative.

### 0.2 Terminology

- **Filter**: a tree of conditions and logical combinations ([section 1](#1-query-model)).
- **Condition**: a field path, an operator and an operand.
- **Field path**: the dot-separated path to a field in a document.
- **Operator set**: a named group of operators; the core set is mandatory, the others are optional.
- **Control parameter**: a query string key starting with `@` ([section 4.2](#42-keys)).
- **Provider**: the component that translates filters to a specific data source.

## 1. Query model

UnQuery defines an abstract **filter**: a tree of conditions over the fields of a document. The JSON syntax ([section 2](#2-json-syntax)) and the SQL syntax ([section 3](#3-sql-syntax)) are two ways of writing the same filter. Implementations translate the filter to each data source; neither syntax is passed to a data source as text.

### 1.1 Filters and conditions

A filter is one of:

- a **condition**: a field path, an operator and an operand, such as `age` `gte` `18`;
- a **logical combination**: `and` or `or` over a list of filters, `nor` over a list of filters, or `not` over a single filter.

<a id="MODEL_TRANSLATE"></a>**Rule `MODEL_TRANSLATE`**: MUST

An implementation MUST translate every filter, in any syntax, into the abstract filter model before evaluating it or translating it to a data source.

### 1.2 Field paths

A field path is a sequence of **segments** separated by `.`, one segment per nesting level. Each segment is a field name, written either plain or between double quotes, optionally followed by array indexes.

```abnf
path        = segment *( "." segment )
segment     = name *index
name        = plain / quoted
plain       = 1*( %x20-21 / %x23-2D / %x2F-5A / %x5C / %x5E-D7FF / %xE000-10FFFF )  ; any Unicode scalar value from U+0020, except ".", DQUOTE, "[" and "]"
quoted      = DQUOTE 1*( %x20-21 / %x23-D7FF / %xE000-10FFFF / DQUOTE DQUOTE ) DQUOTE  ; any Unicode scalar value from U+0020
index       = "[" ( "0" / %x31-39 *DIGIT ) "]"   ; zero-based, no leading zeros
```

<a id="PATH_DOT_NOTATION"></a>**Rule `PATH_DOT_NOTATION`**: MUST

A field path MUST follow the `path` grammar above. A plain name may contain any character from U+0020 except `.`, `"`, `[` and `]`; a quoted name may contain any character from U+0020, and represents a `"` as `""`. Control characters (U+0000 to U+001F) are not allowed in names.

<a id="PATH_RESERVED_START"></a>**Rule `PATH_RESERVED_START`**: MUST NOT

A field name (the `name` of a segment, after removing the quotes of a quoted name, without its indexes) MUST NOT start with `$` or `@`, which are reserved in the LingoData family for ECSON typed values and for operators and control parameters.

<a id="PATH_INDEX"></a>**Rule `PATH_INDEX`**: MUST

An index `[n]`, after a field name or after another index, MUST select the element at the zero-based position `n` of the array at that point of the path. When the value at that point is not an array, or the array has no element at that position, the field MUST be treated as missing.

<a id="PATH_NUMERIC_SEGMENT"></a>**Rule `PATH_NUMERIC_SEGMENT`**: MUST

A segment made only of digits, such as `0` in `items.0.price`, MUST be read as a field name, never as an array index.

<a id="PATH_ARRAYS"></a>**Rule `PATH_ARRAYS`**: MUST

When a segment of a field path resolves to an array and has no index, the rest of the path MUST be resolved in each element of the array, and the condition MUST match if it matches the value found in at least one element.

<a id="PATH_ARRAY_NESTED"></a>**Rule `PATH_ARRAY_NESTED`**: MUST

When the rest of the path is resolved in the elements of an array ([`PATH_ARRAYS`](#PATH_ARRAYS)), an element that is not a plain object, or that does not have the next field, MUST count as missing for that element. Arrays nested inside arrays MUST NOT be flattened.

<a id="PATH_INDEX_AS_IS"></a>**Rule `PATH_INDEX_AS_IS`**: MUST

A segment with an index MUST use the selected element as it is: when that element is an array, the next segment MUST NOT be resolved in its elements.

<a id="PATH_ARRAY_VALUE"></a>**Rule `PATH_ARRAY_VALUE`**: MUST

When the value at the end of the path is an array, a condition MUST match if it matches the whole array or at least one of its elements. This rule does not apply to the operators of the Array set ([section 1.5.2](#152-array-set)), which evaluate only the value at the end of the path.

<a id="PATH_ARRAY_COMPLEMENTS"></a>**Rule `PATH_ARRAY_COMPLEMENTS`**: MUST

The complements `ne`, `nin`, `not` and `nor` MUST match exactly when the condition they negate does not match ([`NULL_NE`](#NULL_NE)). The array rules of this section apply to the negated condition, never to the complement itself: `items.price` with `nin [5]` does not match `{ "items": [{ "price": 5 }, { "price": 6 }] }`, because `in [5]` does.

<a id="PATH_ARRAY_EMPTY"></a>**Rule `PATH_ARRAY_EMPTY`**: MUST

A path that continues past an empty array, such as `items.price` when `items` is `[]`, has no value and MUST be evaluated as a missing field ([section 1.3](#13-missing-fields-null-and-types)): `exists` with operand `false` and `eq` with operand `null` match, and conditions such as `gt` or `exists` with operand `true` do not. An empty array at the end of the path is a present value.

<a id="PATH_ARRAY_CONDITIONS"></a>**Rule `PATH_ARRAY_CONDITIONS`**: MUST

A condition on a field path MUST be evaluated independently of the other conditions on the same path, so different conditions MAY be satisfied by different elements of an array.

> **Note (non-normative)**
>
> To require that one element matches several conditions, a filter can use `@elemMatch` ([section 1.5.2](#152-array-set), optional Array set).

> **Caution (non-normative): Brackets in field names and query strings**
>
> `[` and `]` are reserved in plain names; a field name that contains them is written as a quoted name, such as `"tags[]"`. In query strings, RFC 3986 requires `[` and `]` to be percent-encoded (`%5B`, `%5D`), as the note on percent-encoding in [section 4.3](#43-values) says, but browsers and the WHATWG URL parser also send and accept them unencoded; [`QS_DECODE`](#QS_DECODE) ([section 4.1](#41-decoding)) reads both forms as the same key. Some web frameworks parse keys with brackets into arrays and nested objects (for example, [qs](https://github.com/ljharb/qs) reads `items[0]` as an array); implementations decode the query string as [`QS_DECODE`](#QS_DECODE) defines, not as such frameworks do.

> **Note (non-normative)**
>
> Field names may contain spaces, dots and other characters, as is common in spreadsheets and in tools such as Notion and Airtable. Names made only of `A` to `Z`, `a` to `z`, `0` to `9`, `_` and `-` are unreserved characters in [RFC 3986, section 2.3](https://www.rfc-editor.org/rfc/rfc3986#section-2.3) and need no percent-encoding in URLs; other names are percent-encoded ([section 4.1](#41-decoding)). Dot notation is also the notation used by the [CRUD API Base Specification](./crud/base.md#312-fields) for nested Fields.

> **Tip (non-normative): Example**
>
> | Path | Field |
> |---|---|
> | `address.city` | `city` inside `address` |
> | `Customer name` | `Customer name` |
> | `"Total.value"` | `Total.value`, a single level |
> | `order."Total.value"` | `Total.value` inside `order` |
> | `items[0].price` | `price` of the first element of the array `items` |
> | `items.0` | a field named `0` inside `items` |
> | `address.` | invalid: an empty segment after the dot |
>
> `address.city` matches `{ "address": { "city": "Recife" } }`. `items.price` with `gt 100` matches `{ "items": [{ "price": 50 }, { "price": 150 }] }`, because one element matches. `tags` with `eq "a"` matches `{ "tags": ["a", "b"] }` (an element), and with `eq ["a", "b"]` matches it too (the whole array). `items.price` with `gt 10` and `lt 20` matches `{ "items": [{ "price": 5 }, { "price": 25 }] }`, because each condition is matched by a different element.

### 1.3 Missing fields, null and types

Filters use two-valued logic: a condition either matches a document or does not, and the result of the rules in this section never depends on the data source. Two optional sets are the exceptions: `@regex` follows the dialect of each data source ([section 1.5.3](#153-regex-set)), and geospatial results may differ near the edges of large polygons ([section 1.5.1](#151-geospatial-set)).

<a id="NULL_EQ"></a>**Rule `NULL_EQ`**: MUST

`eq` with operand `null` MUST match documents where the field is `null` or missing.

<a id="NULL_EXISTS"></a>**Rule `NULL_EXISTS`**: MUST

`exists` with operand `false` MUST match only documents where the field is missing; with operand `true`, only documents where the field is present, including when its value is `null`.

<a id="NULL_UNDEFINED"></a>**Rule `NULL_UNDEFINED`**: MUST

A field whose value is `undefined` (ECSON `$undefined`) MUST be treated as missing.

<a id="NULL_UNDEFINED_OPERAND"></a>**Rule `NULL_UNDEFINED_OPERAND`**: MUST

`eq` with the operand `undefined` MUST match exactly the documents where the field is missing ([`NULL_UNDEFINED`](#NULL_UNDEFINED)), and MUST NOT match a field whose value is `null` or an array with an `undefined` element ([`NULL_UNDEFINED_ELEMENT`](#NULL_UNDEFINED_ELEMENT)). On a path through an array, it follows [`PATH_ARRAYS`](#PATH_ARRAYS), like `eq null`: it matches when the field is missing in at least one element. `in` with `undefined` in its list MUST match missing fields too.

<a id="NULL_UNDEFINED_IN_OPERAND"></a>**Rule `NULL_UNDEFINED_IN_OPERAND`**: MUST

An `undefined` inside an array, object, `$set` or `$map` operand, such as `eq [1, undefined]`, MUST make the filter fail, except when it is itself an element of the list of `in` or `nin`.

<a id="NULL_UNDEFINED_ELEMENT"></a>**Rule `NULL_UNDEFINED_ELEMENT`**: MUST

An `undefined` element inside an array of a document MUST be treated as `null`. This rule does not apply to operands ([`NULL_UNDEFINED_IN_OPERAND`](#NULL_UNDEFINED_IN_OPERAND)).

> **Note (non-normative): Rationale**
>
> The plain JSON form of ECSON omits members whose value is `undefined` ([ECSON section 5.3](./ecson.md#53-plain-json-form)), so treating them as missing gives the same result whether the document travels in ECSON or in plain JSON. Inside arrays, the plain JSON form turns `undefined` into `null`, so an operand such as `[1, undefined]` would become `[1, null]` and the result would depend on the envelope of the filter; the filter fails instead.

<a id="NULL_NE"></a>**Rule `NULL_NE`**: MUST

`ne` MUST match every document where `eq` with the same operand does not match, including documents where the field is `null` or missing. `nin` MUST likewise match every document where `in` does not.

<a id="NULL_RANGE"></a>**Rule `NULL_RANGE`**: MUST

`gt`, `gte`, `lt`, `lte` and `like` MUST NOT match documents where the field is `null` or missing.

<a id="NO_COERCION"></a>**Rule `NO_COERCION`**: MUST

Conditions MUST compare values without type conversion: a value matches only operands of the same type, and range operators MUST NOT match values of a different type than the operand.

> **Note (non-normative): For providers**
>
> Data sources disagree on these cases, so providers must translate them explicitly:
>
> | Filter | MongoDB | SQL (PostgreSQL) | Notion |
> |---|---|---|---|
> | `eq null` | `{ f: null }` (native: matches null and missing) | `f IS NULL` | property is empty |
> | `exists false` | `{ f: { $exists: false } }` | not expressible for columns that always exist: matches nothing; for JSON columns, `NOT (doc ? 'f')` | property not in the database: matches every row |
> | `ne v` | `{ f: { $ne: v } }` (native: matches null and missing) | `f IS DISTINCT FROM v` (plain `f <> v` would skip `NULL`) | property is empty or different from `v` |
> | `nin [a, b]` | `{ f: { $nin: [a, b] } }` | `f IS NULL OR f NOT IN (a, b)` | property is empty or not one of the values |
> | `gt v` | `{ f: { $gt: v } }` (native type bracketing) | `f > v`, with `v` bound to the column type; a type mismatch matches nothing | numeric or date property greater than `v` |
>
> SQL uses three-valued logic, where `f <> 'x'` is unknown, and therefore excluded, when `f` is `NULL`. UnQuery deliberately follows two-valued logic, so a filter with these operators returns the same documents from any provider.

<a id="PROVIDER_EXACT_OR_FAIL"></a>**Rule `PROVIDER_EXACT_OR_FAIL`**: MUST

A provider MUST fail on a condition that it cannot translate with the semantics of this specification, and MUST NOT approximate it. A provider MAY rely on an assumption about the stored data, such as the type of a field, only when it documents that assumption.

> **Note (non-normative): For providers**
>
> Other differences that providers must handle:
>
> - **MongoDB numbers**: MongoDB compares 32-bit and 64-bit integers, doubles and Decimal128 as one numeric family, while UnQuery never compares different types ([`NO_COERCION`](#NO_COERCION)). A provider documents the assumption that each field holds a single numeric type, or checks the type explicitly.
> - **MongoDB objects**: MongoDB compares embedded documents by key order, while UnQuery ignores key order ([`EQUALITY_VALUES`](#EQUALITY_VALUES)). A provider that cannot compare objects without key order fails on object operands with more than one key ([`PROVIDER_EXACT_OR_FAIL`](#PROVIDER_EXACT_OR_FAIL)).
> - **Notion**: the Notion API does not document whether text conditions are case-sensitive, whether `does_not_equal` includes empty properties, or how a date without time compares with a property that has time. For complements, providers include empty properties explicitly, and fail on conditions they cannot translate exactly instead of approximating them ([`PROVIDER_EXACT_OR_FAIL`](#PROVIDER_EXACT_OR_FAIL)).

#### 1.3.1 Equality and order

<a id="EQUALITY_VALUES"></a>**Rule `EQUALITY_VALUES`**: MUST

Equality MUST compare values by type and content: numbers by numeric value (`1` equals `1.0`), plain objects by their members without regard to order (a member whose value is `undefined` counts as missing, [`NULL_UNDEFINED`](#NULL_UNDEFINED)), and arrays element by element, in order. Values of different types, such as a JSON number and a `$bigint`, MUST NOT be equal.

<a id="EQUALITY_NUMBERS"></a>**Rule `EQUALITY_NUMBERS`**: MUST

JSON numbers and ECSON `$number` values MUST be compared as one type, number. Negative zero MUST be equal to zero, and `NaN` MUST be equal to `NaN`.

<a id="EQUALITY_ZONED"></a>**Rule `EQUALITY_ZONED`**: MUST

Two `$zoneddatetime` values MUST be equal only when their instant, time zone and calendar are equal.

> **Note (non-normative)**
>
> `$zoneddatetime` values are ordered by their instant alone ([`ORDER_TEMPORAL`](#ORDER_TEMPORAL)), so for this type `eq a` is not the same as `gte a` and `lte a`: the range also matches the same instant in other time zones. This follows `equals` and `compare` of `Temporal.ZonedDateTime`.

<a id="EQUALITY_DECIMAL"></a>**Rule `EQUALITY_DECIMAL`**: MUST

Values of the BSON `$numberDecimal` type MUST be compared by numeric value, for equality and for order (`1.0` equals `1.00`), and only with other `$numberDecimal` values.

<a id="ORDER_TYPES"></a>**Rule `ORDER_TYPES`**: MUST

The operand of a range operator (`gt`, `gte`, `lt`, `lte`) MUST be of an orderable type: a number (a JSON number or an ECSON `$number`), a string, a `$bigint`, a `$numberDecimal`, a `$date`, or a Temporal `$instant`, `$zoneddatetime`, `$plaindate`, `$plaindatetime`, `$plaintime`, `$plainyearmonth` or `$duration`. Any other operand, including `null`, booleans, arrays and objects, MUST make the filter fail. `-Infinity` and `Infinity` are the lowest and the highest numbers.

<a id="ORDER_TEMPORAL"></a>**Rule `ORDER_TEMPORAL`**: MUST

`$zoneddatetime` values MUST be ordered by their instant, whatever their time zone and calendar. `$duration` values MUST be ordered by their length, with days of 24 hours.

<a id="ORDER_UNORDERABLE"></a>**Rule `ORDER_UNORDERABLE`**: MUST

A `$duration` with years, months or weeks, a `NaN` number or decimal and an invalid `$date` are not orderable: as the operand of a range operator they MUST make the filter fail ([`ORDER_TYPES`](#ORDER_TYPES)), and as a field value they MUST NOT match a range operator.

<a id="TYPE_UNSUPPORTED_FAIL"></a>**Rule `TYPE_UNSUPPORTED_FAIL`**: MUST

An implementation that cannot compare values of a type as [section 1.3.1](#131-equality-and-order) requires MUST make the filter fail on a condition whose operand has that type, such as an implementation that reads `$numberDecimal` as an unknown tag ([ECSON section 7](./ecson.md#7-unknown-tags)) and cannot compare it by numeric value, or one that keeps Temporal values as opaque strings ([ECSON `TYPE_TEMPORAL_OPAQUE`](./ecson.md#TYPE_TEMPORAL_OPAQUE)) and cannot order them.

<a id="ORDER_STRINGS"></a>**Rule `ORDER_STRINGS`**: MUST

Range operators MUST order strings by Unicode code point, whatever the collation of the data source.

> **Note (non-normative)**
>
> Code point order is what MongoDB gives by default (binary comparison of UTF-8) and what PostgreSQL gives with the `"C"` collation in a `UTF8` database. Other data sources may need an explicit binary collation. It is not the alphabetical order of a language: `"Zé"` comes before `"Ágata"`.

> **Caution (non-normative): Strings in JavaScript**
>
> The JavaScript operators `<` and `>` compare strings by UTF-16 code units, not by code points: `"\u{1F600}" < "�"` is `true`, although U+1F600 is greater than U+FFFD. An implementation in JavaScript compares code points (for example, with `codePointAt`) to follow [`ORDER_STRINGS`](#ORDER_STRINGS) for characters above U+FFFF.

### 1.4 Core operators

<a id="OPS_CORE"></a>**Rule `OPS_CORE`**: MUST

Every implementation MUST support the core operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`, `exists` and `like`, and the logical combinations `and`, `or`, `not` and `nor`.

| Operator | JSON syntax ([section 2](#2-json-syntax)) | Matches when the field value |
|---|---|---|
| `eq` | `@eq` | equals the operand |
| `ne` | `@ne` | does not equal the operand |
| `gt`, `gte`, `lt`, `lte` | `@gt`, `@gte`, `@lt`, `@lte` | is greater than, greater than or equal to, less than, less than or equal to the operand |
| `in` | `@in` | equals one of the values in the operand list; `in [a, b]` is equivalent to `eq a` or `eq b`, so a `null` in the list also matches missing fields ([`NULL_EQ`](#NULL_EQ)) |
| `nin` | `@nin` | equals none of the values in the operand list; the exact complement of `in` |
| `exists` | `@exists` | exists (operand `true`) or does not exist (operand `false`) |
| `like` | `@like` | is a string matching the operand pattern, where `%` matches any sequence of characters and `_` matches exactly one character, case-sensitive |

<a id="LIKE_ESCAPE"></a>**Rule `LIKE_ESCAPE`**: MUST

In a `like` pattern, `\` followed by `%`, `_` or `\` MUST match that character literally. A `\` followed by any other character, or at the end of the pattern, MUST make the filter fail.

> **Tip (non-normative): Example**
>
> `50\%` matches the string `50%` only. In the JSON syntax, the backslash must also be escaped as JSON requires: `{ "discount": { "@like": "50\\%" } }`. In the SQL syntax: `discount LIKE '50\%'`.

### 1.5 Optional operator sets

<a id="OPS_SETS"></a>**Rule `OPS_SETS`**: MAY

An implementation MAY support any optional operator set, in whole. Partial support of a set is not compliant with that set.

| Set | Operators |
|---|---|
| Array | `@all` (the field is an array that contains every value in the operand list), `@size` (the field is an array with exactly the operand number of elements; each nested array counts as one element), `@elemMatch` (at least one element of the array field matches the operand, [section 1.5.2](#152-array-set)) |
| Regex | `@regex` (the string field matches a regular expression, given as a string or as an ECSON `$regexp` value, [section 1.5.3](#153-regex-set)) |
| Geospatial | `@geoWithin`, `@geoIntersects`, `@near`, with [GeoJSON](https://www.rfc-editor.org/rfc/rfc7946) operands ([section 1.5.1](#151-geospatial-set)) |

<a id="OPS_UNSUPPORTED_FAIL"></a>**Rule `OPS_UNSUPPORTED_FAIL`**: MUST

An implementation MUST fail when a filter uses an operator it does not support, and MUST NOT ignore the condition.

> **Note (non-normative): Rationale**
>
> Some MongoDB query operators, such as `$expr`, `$mod` and `$type` with BSON type names, cannot be implemented in general by providers such as PostgreSQL, MySQL, Notion or Airtable. The core set is what every data source can evaluate; the rest are optional sets. Ignoring an unsupported condition would silently return or modify more documents than requested, so it must fail.

#### 1.5.1 Geospatial set

<a id="GEO_GEOJSON"></a>**Rule `GEO_GEOJSON`**: MUST

Operands of the geospatial set MUST be GeoJSON geometry objects ([RFC 7946](https://www.rfc-editor.org/rfc/rfc7946)), with positions in WGS 84 as longitude, then latitude. Distances MUST be in meters.

<a id="GEO_GEOJSON_MEMBERS"></a>**Rule `GEO_GEOJSON_MEMBERS`**: MUST

Implementations MUST accept the `bbox` member and foreign members of GeoJSON objects and ignore them (RFC 7946, [section 5](https://www.rfc-editor.org/rfc/rfc7946#section-5) and [section 6.1](https://www.rfc-editor.org/rfc/rfc7946#section-6.1)).

<a id="GEO_GEOJSON_EMPTY"></a>**Rule `GEO_GEOJSON_EMPTY`**: MUST

A geometry whose `coordinates` is an empty array, or a `GeometryCollection` without geometries, MUST make the filter fail. A line with fewer than two positions or a ring with fewer than four is invalid GeoJSON ([`GEO_GEOJSON`](#GEO_GEOJSON)).

> **Note (non-normative)**
>
> [`GEO_GEOJSON_EMPTY`](#GEO_GEOJSON_EMPTY) is stricter than RFC 7946, which allows empty coordinates and empty `GeometryCollection` objects ([sections 3.1](https://www.rfc-editor.org/rfc/rfc7946#section-3.1) and [3.1.8](https://www.rfc-editor.org/rfc/rfc7946#section-3.1.8)): an empty geometry has no point to compare, so a condition on it would have no clear result.

<a id="GEO_FIELD"></a>**Rule `GEO_FIELD`**: MUST

A geospatial condition MUST match only documents whose field holds a GeoJSON geometry object. Missing fields, `null` and other values MUST NOT match.

| Operator | Operand | Matches when |
|---|---|---|
| `@geoWithin` | a `Polygon` or `MultiPolygon` | the geometry of the field lies entirely inside the operand |
| `@geoIntersects` | any geometry | the geometry of the field and the operand have at least one point in common |
| `@near` | `{ "point": <Point>, "maxDistance": <meters>, "minDistance": <meters> }`, with `maxDistance` required and `minDistance` optional (default `0`) | the distance between the geometry of the field and `point` is at least `minDistance` and at most `maxDistance` |

<a id="GEO_OPERATORS"></a>**Rule `GEO_OPERATORS`**: MUST

The geospatial operators MUST match as specified in the table above.

<a id="GEO_NEAR_NO_SORT"></a>**Rule `GEO_NEAR_NO_SORT`**: MUST NOT

`@near` MUST NOT change the order of the results: like every condition, it only decides whether a document matches.

<a id="GEO_DISTANCE"></a>**Rule `GEO_DISTANCE`**: MUST

Distances MUST be measured on the surface of the Earth, on a sphere or on the WGS 84 spheroid.

> **Tip (non-normative): Example**
>
> `{ "location": { "@near": { "point": { "type": "Point", "coordinates": [-46.6333, -23.5505] }, "maxDistance": 2000 } } }` matches documents whose `location` is at most 2 km from the center of São Paulo.

> **Note (non-normative)**
>
> Data sources compute edges of polygons differently: GeoJSON defines a line between two positions as a straight Cartesian line ([RFC 7946, section 3.1.1](https://www.rfc-editor.org/rfc/rfc7946#section-3.1.1)), MongoDB uses spherical geometry and PostGIS `geography` uses geodesic lines. Results may differ for geometries near the edges of large polygons. Sorting by distance is out of the scope of this version.

#### 1.5.2 Array set

<a id="ARRAY_SET_ARRAYS_ONLY"></a>**Rule `ARRAY_SET_ARRAYS_ONLY`**: MUST

`@all`, `@size` and `@elemMatch` MUST NOT match a field that is missing, `null` or not an array.

<a id="ELEM_MATCH"></a>**Rule `ELEM_MATCH`**: MUST

A field with `@elemMatch` MUST match when it holds an array with at least one element that matches the whole operand. When every key of the operand starts with `@`, the operand is a set of conditions applied to the element itself; otherwise the operand is a filter applied with the element as the document. [`ARRAY_SET_ARRAYS_ONLY`](#ARRAY_SET_ARRAYS_ONLY) covers fields that are not arrays.

<a id="ELEM_MATCH_FORMS"></a>**Rule `ELEM_MATCH_FORMS`**: MUST

In the form with only `@` keys, the operand is an operator object, as under a field path ([`JSON_OPERATOR_OBJECT`](#JSON_OPERATOR_OBJECT)): `@not` takes an operator object, and `@and`, `@or` and `@nor` MUST make the filter fail.

<a id="ELEM_MATCH_EMPTY"></a>**Rule `ELEM_MATCH_EMPTY`**: MUST

The operand `{}` belongs to the form with only `@` keys and MUST match every array with at least one element.

<a id="ELEM_MATCH_NON_OBJECT"></a>**Rule `ELEM_MATCH_NON_OBJECT`**: MUST

In the filter form, an element that is not a plain object MUST be treated as an object with no fields.

<a id="ELEM_MATCH_OPERAND"></a>**Rule `ELEM_MATCH_OPERAND`**: MUST

An operand of `@elemMatch` that is not an object MUST make the filter fail.

> **Tip (non-normative): Example**
>
> `{ "items": { "@elemMatch": { "price": { "@gt": 10, "@lt": 20 } } } }` matches `{ "items": [{ "price": 5 }, { "price": 15 }] }`, but not `{ "items": [{ "price": 5 }, { "price": 25 }] }`, because no single element has a price between 10 and 20. `{ "scores": { "@elemMatch": { "@gte": 80, "@lt": 85 } } }` matches `{ "scores": [82, 90] }`.

> **Note (non-normative)**
>
> The form depends only on the keys of the operand. `{ "@or": [...] }` has only `@` keys, so it is an operator object and fails; `{ "@or": [...], "x": 1 }` has a field key, so it is a filter ([`JSON_FILTER`](#JSON_FILTER)) and is valid. `@or` combines conditions on the fields of an element only in the filter form.

> **Note (non-normative)**
>
> `@elemMatch` follows the [MongoDB `$elemMatch` operator](https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/). Like the other operators of the Array set, it has no form in the SQL syntax.

#### 1.5.3 Regex set

<a id="REGEX_DIALECT"></a>**Rule `REGEX_DIALECT`**: MUST

An implementation that evaluates filters itself MUST interpret `@regex` patterns as ECMAScript regular expressions. A provider MUST apply the dialect of the regular expressions of its data source.

<a id="REGEX_PROVIDER_PASSTHROUGH"></a>**Rule `REGEX_PROVIDER_PASSTHROUGH`**: MUST

A provider MUST pass the pattern to the regular expression engine of its data source unchanged, as a bound value.

<a id="REGEX_UNSUPPORTED_FAIL"></a>**Rule `REGEX_UNSUPPORTED_FAIL`**: MUST

A provider MUST fail when its data source has no regular expressions, or cannot express a flag of the pattern that changes whether a string matches.

<a id="REGEX_FLAGS"></a>**Rule `REGEX_FLAGS`**: MUST

The flags `d` and `g` do not change whether a string matches and MUST be ignored: each string is matched from its start, as with `lastIndex` 0. The flag `y` MUST make the match start at the beginning of the string.

> **Tip (non-normative): Example**
>
> `/a/y` does not match `"ba"`, while `/a/` and `/a/g` do. A provider whose data source cannot anchor a pattern through an option fails on `y` ([`REGEX_UNSUPPORTED_FAIL`](#REGEX_UNSUPPORTED_FAIL)).

> **Caution (non-normative): Dialects differ**
>
> MongoDB uses [PCRE2](https://www.mongodb.com/docs/manual/reference/operator/query/regex/) (PCRE before version 6.1), PostgreSQL uses [POSIX regular expressions](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) and Notion has none. Simple patterns (literal ASCII text, `^`, `$`, `.`, `*`, `+`, `?` and bracket expressions such as `[a-z0-9]`) behave the same in strings without line breaks; patterns with other features, and any pattern on strings with line breaks, may match differently in each data source. For example, `$` in PCRE2 also matches before a final line feed, and `.` in PostgreSQL matches a line feed by default, while neither does in ECMAScript.

## 2. JSON syntax

The JSON syntax writes a filter as a JSON object. Its structure is inspired by MongoDB query documents, with one difference: operators start with `@` instead of `$`, because in the LingoData family `$` marks ECSON typed values.

### 2.1 Structure

<a id="JSON_FILTER"></a>**Rule `JSON_FILTER`**: MUST

A JSON filter MUST be a JSON object in which every key is either a field path (a condition on that field) or a logical operator: `@and`, `@or` and `@nor`, whose values are arrays of JSON filters, or `@not`, whose value is a JSON filter. Several keys in the same object are combined with `and`.

<a id="JSON_EMPTY_LISTS"></a>**Rule `JSON_EMPTY_LISTS`**: MUST

`@and`, `@or`, `@nor`, `@in`, `@nin` and `@all` with an empty array MUST make the filter fail.

<a id="JSON_EMPTY_FILTER"></a>**Rule `JSON_EMPTY_FILTER`**: MUST

The empty filter `{}` MUST match every document.

> **Note (non-normative): Rationale**
>
> An empty list is almost always a bug in the code that built the filter. Failing makes it visible instead of silently matching every document or none.

<a id="JSON_OPERATOR_OBJECT"></a>**Rule `JSON_OPERATOR_OBJECT`**: MUST

Under a field path, a JSON object whose keys all start with `@` MUST be interpreted as an operator object: each key is an operator applied to the field, and several operators are combined with `and`. `@not` under a field path takes an operator object and negates it. An object mixing keys that start with `@` and keys that do not MUST be rejected.

<a id="JSON_IMPLICIT_EQ"></a>**Rule `JSON_IMPLICIT_EQ`**: MUST

Under a field path, any other value MUST be interpreted as the operand of `eq`.

<a id="JSON_OPERANDS_ECSON"></a>**Rule `JSON_OPERANDS_ECSON`**: MUST

Operands MUST be decoded as ECSON values, so that typed values such as `{ "$date": "..." }` are compared as their types and escaped keys are restored.

<a id="JSON_OPERANDS_IN_MODEL"></a>**Rule `JSON_OPERANDS_IN_MODEL`**: MUST

An operand that is a value outside the ECSON model ([ECSON section 5.5](./ecson.md#55-values-outside-the-model)), such as a function, MUST make the filter fail, whether the filter is evaluated, translated or converted to another representation. It MUST NOT be replaced by `null` or omitted.

> **Note (non-normative): Rationale**
>
> Replacing such an operand with `null` would change the filter silently: `@eq null` matches missing fields, so the filter would return or modify more documents than requested. This differs from ECSON, which serializes values outside its model as `JSON.stringify` does ([`OUT_OF_MODEL_JSON`](./ecson.md#OUT_OF_MODEL_JSON)): an UnQuery implementation that uses an ECSON library checks operands before serializing them, and does not use that fallback.

> **Tip (non-normative): Example**
>
> ```json
> {
>   "status": { "@in": ["paid", "shipped"] },
>   "total": { "@gte": 100, "@lt": 1000 },
>   "createdAt": { "@gte": { "$date": "2024-01-01T00:00:00.000Z" } },
>   "address.city": "Recife",
>   "@or": [
>     { "coupon": { "@exists": true } },
>     { "customer.vip": true }
>   ]
> }
> ```
> This filter matches paid or shipped orders, with a total from 100 to less than 1000, created since 2024, delivered in Recife, and either with a coupon or from a VIP customer.

> **Tip (non-normative): Example: field names with spaces and dots**
>
> `{ "Customer name": "Ana", "\"Total.value\"": { "@gt": 10 } }`: the first key is a plain name with a space; the second is a quoted name, so its dot is part of the name.

> **Tip (non-normative): Example: comparing with an object**
>
> `{ "shipping": { "carrier": "acme" } }` compares the whole `shipping` field with the object `{ "carrier": "acme" }`. To compare with an object whose keys start with `@`, use an explicit operator: `{ "shipping": { "@eq": { "@id": 1 } } }`.

> **Note (non-normative): Rationale**
>
> MongoDB uses `$` for operator names. In the LingoData family, `$` already marks ECSON typed values (and ECSON must keep `$` to stay identical to MongoDB Extended JSON in its BSON type set). With `@` for operators, a reader can tell at a glance what is an operation and what is a type: in `{ "@gte": { "$date": "..." } }`, `@gte` is the operator and `$date` is the type of the operand. `@` plays the same role of reserved keyword in JSON-LD (`@id`, `@type`). MongoDB queries need `$` replaced by `@` to be reused as UnQuery filters.

## 3. SQL syntax

The SQL syntax lets filters be written as SQL `WHERE` predicates, which are compact and readable in URLs. It is a restricted grammar, not SQL: implementations parse it into the filter model ([section 1](#1-query-model)) and never send it to a database.

<a id="SQL_PARSE"></a>**Rule `SQL_PARSE`**: MUST

An implementation MUST parse SQL syntax with the grammar in this section and translate it into the filter model.

<a id="SQL_NO_PASSTHROUGH"></a>**Rule `SQL_NO_PASSTHROUGH`**: MUST NOT

An implementation MUST NOT pass SQL syntax text, in whole or in part, to a data source.

<a id="SQL_REJECT"></a>**Rule `SQL_REJECT`**: MUST

An implementation MUST fail on any input that does not match the grammar, including subqueries, function calls, comments and statements other than predicates.

### 3.1 Grammar

The grammar uses ABNF ([RFC 5234](https://www.rfc-editor.org/rfc/rfc5234)). Keywords are case-insensitive. Optional whitespace (`ws`: one or more spaces, tabs, carriage returns and line feeds) is allowed between tokens; the grammar shows `ws` only where it is required. Inside strings, `''` represents one `'`.

<a id="SQL_KEYWORD_BOUNDARY"></a>**Rule `SQL_KEYWORD_BOUNDARY`**: MUST NOT

A keyword MUST NOT be immediately preceded or followed by a letter, a digit, `_` or `-`: `a=1ORb=2` is invalid, while `a='x'OR b=2` is valid.

<a id="SQL_QUOTED_NAMES"></a>**Rule `SQL_QUOTED_NAMES`**: MUST

Field paths follow [`PATH_DOT_NOTATION`](#PATH_DOT_NOTATION) ([section 1.2](#12-field-paths)), except that a field name (the `name` of a segment, not counting its indexes) that contains characters other than letters, digits, `_` and `-`, or that is equal to a keyword (such as `AND` or `IN`), MUST be quoted: `"Customer name" = 'Ana'`, `items[0].price > 10`.

```abnf
filter       = or-expr
or-expr      = and-expr *( "OR" and-expr )
and-expr     = not-expr *( "AND" not-expr )
not-expr     = "NOT" not-expr / primary
primary      = "(" filter ")" / predicate
predicate    = field tail
tail         = comp-op literal
             / [ "NOT" ] "IN" "(" literal *( "," literal ) ")"
             / [ "NOT" ] "BETWEEN" literal "AND" literal
             / [ "NOT" ] "LIKE" string
             / "IS" [ "NOT" ] "NULL"
comp-op      = "=" / "!=" / "<>" / ">=" / ">" / "<=" / "<"
field        = sql-segment *( "." sql-segment )
sql-segment  = ( 1*( ALPHA / DIGIT / "_" / "-" ) / quoted ) *index   ; quoted, index: section 1.2
literal      = string / number / "TRUE" / "FALSE" / "NULL"
             / "TIMESTAMP" ws string / "DATE" ws string
string       = "'" *( %x20-26 / %x28-7E / "''" / non-ascii ) "'"
number       = [ "-" ] 1*DIGIT [ "." 1*DIGIT ] [ ( "e" / "E" ) [ "+" / "-" ] 1*DIGIT ]
non-ascii    = %x80-D7FF / %xE000-10FFFF   ; Unicode scalar values, encoded as UTF-8
ws           = 1*( WSP / CR / LF )
```

### 3.2 Mapping to the filter model

| SQL syntax | Filter model |
|---|---|
| `f = v`, `f != v`, `f <> v` | `eq`, `ne` |
| `f > v`, `f >= v`, `f < v`, `f <= v` | `gt`, `gte`, `lt`, `lte` |
| `f IN (a, b)`, `f NOT IN (a, b)` | `in`, `nin` |
| `f BETWEEN a AND b` | `and` of `gte a` and `lte b` |
| `f NOT BETWEEN a AND b` | `not` of the above |
| `f LIKE p`, `f NOT LIKE p` | `like`, `not` of `like` |
| `f IS NULL`, `f IS NOT NULL` | `eq null`, `ne null` |
| `f = NULL`, `f != NULL`, `f <> NULL` | `eq null`, `ne null` |
| `f > NULL` and other ranges with `NULL` | invalid ([`ORDER_TYPES`](#ORDER_TYPES)) |
| `AND`, `OR`, `NOT` | `and`, `or`, `not` |

### 3.3 Typed literals

<a id="SQL_TYPED_LITERALS"></a>**Rule `SQL_TYPED_LITERALS`**: MUST

`TIMESTAMP '<value>'` MUST be interpreted as an ECSON `$date` whose string form is `<value>` (RFC 3339), and `DATE '<value>'` as an ECSON `$plaindate` whose string form is `<value>`.

<a id="SQL_TYPED_LITERAL_INVALID"></a>**Rule `SQL_TYPED_LITERAL_INVALID`**: MUST

A typed literal whose value does not satisfy the ECSON type definition ([ECSON `TYPEDEF_VALIDATE`](./ecson.md#TYPEDEF_VALIDATE), with [`TYPE_DATE_READ_STRICT`](./ecson.md#TYPE_DATE_READ_STRICT) for `$date`) MUST make the filter fail.

> **Tip (non-normative): Example**
>
> `createdAt >= TIMESTAMP '2024-01-15T00:00:00.000Z'` compares dates; `createdAt >= '2024-01-15'` compares strings and, under [`NO_COERCION`](#NO_COERCION), does not match date values.

> **Tip (non-normative): Example**
>
> `status IN ('paid', 'shipped') AND total >= 100` is the filter `and( in(status, ["paid", "shipped"]), gte(total, 100) )`.

> **Note (non-normative): Rationale**
>
> Passing SQL expressions "as-is" to a database and protecting it against SQL injection cannot both hold, and operators such as `EXISTS`, `ANY`, `ALL` and `SOME` need subqueries. A closed grammar keeps the convenience of SQL predicates in URLs and removes injection by design, because no input text reaches a database.

## 4. Query string mapping

In a URL query string, keys starting with `@` are control parameters, and every other key is a condition on one field: the key is the field path and the value is the condition.

### 4.1 Decoding

<a id="QS_DECODE"></a>**Rule `QS_DECODE`**: MUST

Keys and values MUST be interpreted after decoding the query string with the `application/x-www-form-urlencoded` parser of the [WHATWG URL Standard](https://url.spec.whatwg.org/#application/x-www-form-urlencoded), so that `%40sort` and `@sort` are the same key and `+` is a space.

### 4.2 Keys

<a id="QS_CONTROL_PREFIX"></a>**Rule `QS_CONTROL_PREFIX`**: MUST

A key starting with `@` MUST be interpreted as a control parameter, never as a field condition. Control parameters are defined by this specification (`@q`) or by the specification of the protocol that uses UnQuery.

<a id="QS_CONTROL_UNKNOWN"></a>**Rule `QS_CONTROL_UNKNOWN`**: MUST

A key starting with `@` that is not a defined control parameter MUST NOT be interpreted as a condition. An implementation MUST report it as an error, unless the protocol specification that uses UnQuery defines another handling, such as reporting it as a warning.

<a id="QS_KEY_PATH"></a>**Rule `QS_KEY_PATH`**: MUST

Any other key MUST be a field path as defined in [`PATH_DOT_NOTATION`](#PATH_DOT_NOTATION), and an implementation MUST fail on keys that are not, except for keys in its ignore list ([`QS_IGNORE_LIST`](#QS_IGNORE_LIST)).

<a id="QS_IGNORE_LIST"></a>**Rule `QS_IGNORE_LIST`**: MAY

An implementation MAY exclude keys from filtering, either because it is configured with a list of keys to ignore (such as `utm_source`) or because the protocol specification that uses UnQuery assigns them another meaning (such as the parameters of a saved query). Excluded keys are neither conditions nor errors.

> **Note (non-normative): Rationale**
>
> Field paths never start with `@` ([`PATH_DOT_NOTATION`](#PATH_DOT_NOTATION)), so control parameters cannot collide with fields, without any list of reserved names. The same convention is used by the JSON syntax, where `@` marks operators, and across the LingoData family, where `@` marks operations and control and `$` marks types. OData follows the same pattern with `$` (`$filter`, `$orderby`). Reporting unknown `@` keys turns typos such as `@srot` into errors (or warnings, when the protocol prefers) instead of silently ignored parameters.

> **Tip (non-normative): Example**
>
> ```
> /orders?status=paid&total=>100&@sort=-createdAt&@limit=20
> ```
> `status` and `total` are conditions; `@sort` and `@limit` are control parameters defined by the protocol (for example, the CRUD API HTTP protocol).

### 4.3 Values

Values are interpreted by trying each syntax in order, so that common cases need no extra characters.

<a id="QS_VALUE_ORDER"></a>**Rule `QS_VALUE_ORDER`**: MUST

A query string value MUST be interpreted as the first of the following that parses successfully: (1) a JSON text (RFC 8259); (2) a SQL syntax predicate tail, that is, the `tail` rule of [section 3.1](#31-grammar) with the key as the field; (3) otherwise, a string literal. Forms (1) and (3) are conditions with the `eq` operator, unless the JSON text is an operator object ([section 2](#2-json-syntax)).

<a id="QS_VALUE_COMMITTED"></a>**Rule `QS_VALUE_COMMITTED`**: MUST

Once a value parses as a JSON text, or as a SQL syntax predicate tail, any later error, such as a mixed operator object, an unknown operator, an invalid ECSON value or an invalid typed literal, MUST make the filter fail. The value MUST NOT fall back to the next form.

> **Note (non-normative): Rationale**
>
> Falling back to a string literal would turn a mistyped condition into an equality with a text that matches nothing, or with something other than intended, without any error.

| Query string | Condition |
|---|---|
| `?age=30` | `eq(age, 30)`, a number |
| `?active=true` | `eq(active, true)`, a boolean |
| `?name=Ana` | `eq(name, "Ana")`, a string |
| `?zip="01234"` | `eq(zip, "01234")`, a string (quoted JSON) |
| `?zip=01234` | `eq(zip, "01234")`, a string (not valid JSON, not SQL) |
| `?age=BETWEEN 18 AND 30` | `and(gte(age, 18), lte(age, 30))` |
| `?status=IN ('paid', 'shipped')` | `in(status, ["paid", "shipped"])` |
| `?total={"@gte":100}` | `gte(total, 100)`, an operator object ([section 2](#2-json-syntax)) |
| `?deletedAt=null` | `eq(deletedAt, null)`: null or missing |
| `?address.city=Recife` | `eq(address.city, "Recife")` |
| `?Customer%20name=Ana` | `eq("Customer name", "Ana")` |
| `?%22Total.value%22=%3E10` | `gt("Total.value", 10)` |

> **Note (non-normative): Percent-encoding**
>
> `@` and `$` are allowed in query strings by RFC 3986, as are field names made of letters, digits, `_`, `-` and `.`. Characters such as spaces, `"`, `[`, `]`, `{` and `}` are not, so clients MUST percent-encode keys and values as required by [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986): `?total={"@gte":100}` is sent as `?total=%7B%22@gte%22:100%7D`, `?Customer name=Ana` as `?Customer%20name=Ana`, and `?"Total.value"=>10` as `?%22Total.value%22=%3E10`.

> **Caution (non-normative): Typed values from strings**
>
> Because JSON is tried first, `?zip=12345` is the number `12345`, while `?zip=01234` is the string `"01234"`. Under [`NO_COERCION`](#NO_COERCION), the number does not match a string stored as `"12345"`. Clients SHOULD quote values that must be strings and look like JSON scalars (numbers, `true`, `false`, `null`): `?zip="12345"`, `?name="null"`.

> **Note (non-normative): Rationale**
>
> Writing `?age=30` for a number is easier than any explicit marker. The cost is the case above, which only affects strings that look like numbers, booleans or `null`, and has an explicit solution (quoting). Typos that stop a value from parsing as JSON or as a SQL predicate tail fall back to a string literal; the failure mode is a filter that matches fewer documents, never more. Once a value parses, any later error fails the filter ([`QS_VALUE_COMMITTED`](#QS_VALUE_COMMITTED)).

### 4.4 Combining conditions

<a id="QS_COMBINE_AND"></a>**Rule `QS_COMBINE_AND`**: MUST

All conditions in a query string, including repeated keys and the filter in `@q`, MUST be combined with `and`.

> **Tip (non-normative): Example**
>
> `?age=>18&age=<30` is `and(gt(age, 18), lt(age, 30))`. Alternatives are written with `@in`, `IN` or `@or`, never with repeated keys.

> **Note (non-normative)**
>
> An empty value is a string literal: `?nickname=` is `eq(nickname, "")`.

### 4.5 Control parameter `@q`

`@q` carries a complete filter, for conditions that per-key parameters cannot express, such as `or` across fields, or fields whose names would need escaping.

<a id="QS_Q_FILTER"></a>**Rule `QS_Q_FILTER`**: MUST

The value of `@q` MUST be interpreted as the first of the following that parses successfully: (1) a JSON filter ([section 2](#2-json-syntax)); (2) a SQL syntax filter (the `filter` rule of [section 3.1](#31-grammar)). An implementation MUST fail if neither parses.

> **Tip (non-normative): Example**
>
> ```
> /orders?@q=status = 'paid' OR total > 100&createdAt=>= TIMESTAMP '2024-01-01T00:00:00.000Z'
> /orders?@q={"@or":[{"status":"paid"},{"total":{"@gt":100}}]}
> ```
> Both filters are combined with the other conditions with `and`.

> **Note (non-normative): Rationale**
>
> If `@q` took precedence over the other keys, they would be silently ignored and responses could include more documents than requested. Combining with `and` makes `@q` composable. Unlike per-key values, `@q` has no string-literal fallback, because a bare string is not a complete filter.

## 5. Security

Filters come from clients and must be treated as untrusted input.

### 5.1 Translation to data sources

<a id="SEC_BOUND_PARAMETERS"></a>**Rule `SEC_BOUND_PARAMETERS`**: MUST

When translating a filter to a query language, a provider MUST pass operands as bound parameters (or the equivalent mechanism of the data source) and MUST NOT concatenate operands into query text.

<a id="SEC_QUOTE_FIELDS"></a>**Rule `SEC_QUOTE_FIELDS`**: MUST

A provider MUST validate field paths with [`PATH_DOT_NOTATION`](#PATH_DOT_NOTATION) and quote them as identifiers of the target query language.

> **Tip (non-normative): Example**
>
> `eq(status, "paid")` becomes `WHERE "status" = $1` with `$1 = 'paid'` in PostgreSQL, never `WHERE status = 'paid'` built as text.

### 5.2 Resource limits

<a id="SEC_LIMITS"></a>**Rule `SEC_LIMITS`**: MAY

An implementation MAY limit the nesting depth of filters, the number of conditions, the size of `@in` and `@nin` lists and the complexity of regular expressions, measured for example by the length of the pattern or by nested quantifiers.

<a id="SEC_LIMITS_FAIL"></a>**Rule `SEC_LIMITS_FAIL`**: MUST

When a limit is exceeded, the implementation MUST fail and MUST NOT truncate or simplify the filter.

> **Note (non-normative): Rationale**
>
> Regular expressions with nested quantifiers can take exponential time to evaluate (ReDoS), and very large or deep filters can exhaust a data source. Truncating a filter would silently return documents that the client did not ask for.

### 5.3 Access to fields

<a id="SEC_HIDDEN_FIELDS"></a>**Rule `SEC_HIDDEN_FIELDS`**: SHOULD

A server SHOULD reject conditions on fields that the client is not allowed to read.

> **Note (non-normative): Rationale**
>
> Filtering reveals information even when a field is not returned: by counting the results of `salary > 10000`, `salary > 20000` and so on, a client can infer a hidden salary. Filters narrow results; they do not replace the access control of the server, which applies its own restrictions independently.

## 6. Conformance and media types

### 6.1 Conformance

| Level | Requirements |
|---|---|
| **Core** | All rules in sections 1 to 5, the JSON and SQL syntaxes, the query string mapping and the core operators |
| **Operator set** | Core, plus every operator of one optional set ([section 1.5](#15-optional-operator-sets)), for example "Core + Array" |

<a id="CONFORMANCE_DECLARE"></a>**Rule `CONFORMANCE_DECLARE`**: MUST

An implementation MUST state that it meets the core level and which optional operator sets it supports.

### 6.2 Media types

Protocols that negotiate the search query format, such as the CRUD API, identify UnQuery filters with these media types.

<a id="MEDIA_TYPES"></a>**Rule `MEDIA_TYPES`**: SHOULD

UnQuery filters exchanged over protocols that carry media types SHOULD be labeled `application/vnd.unquery+json` when written in the JSON syntax and `text/vnd.unquery.sql` when written in the SQL syntax.

> **Note (non-normative)**
>
> The `+json` suffix ([RFC 6839](https://www.rfc-editor.org/rfc/rfc6839)) tells generic clients that the content is JSON. The vendor tree (`vnd.`) does not require standardization.

### 6.3 Versioning

<a id="SPEC_SEMVER"></a>**Rule `SPEC_SEMVER`**: MUST

This specification MUST be versioned independently of the other specifications of the LingoData family, following [Semantic Versioning 2.0.0](https://semver.org/).

> **Note (non-normative)**
>
> While this specification is in a `0.x` version, any release may contain incompatible changes, as allowed by Semantic Versioning. Version `1.0.0` is reserved for when the reference implementation and the conformance test suite validate the specification.

## 7. References

### 7.1 Normative references

- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): requirement level key words (BCP 14)
- [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339): Date and Time on the Internet: Timestamps
- [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986): Uniform Resource Identifier (URI): Generic Syntax
- [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259): The JavaScript Object Notation (JSON) Data Interchange Format
- [RFC 5234](https://www.rfc-editor.org/rfc/rfc5234): Augmented BNF for Syntax Specifications (ABNF)
- [RFC 7946](https://www.rfc-editor.org/rfc/rfc7946): The GeoJSON Format
- [RFC 6839](https://www.rfc-editor.org/rfc/rfc6839): Additional Media Type Structured Syntax Suffixes
- [WHATWG URL Standard](https://url.spec.whatwg.org/): `application/x-www-form-urlencoded` parsing
- [ECSON](https://github.com/lingodata/ecson): ECMAScript Object Notation (LingoData)
- [ECMA-262](https://tc39.es/ecma262/): ECMAScript Language Specification, for regular expressions ([section 1.5.3](#153-regex-set))
- [The Unicode Standard](https://www.unicode.org/versions/latest/): code points and scalar values

### 7.2 Informative references

- [MongoDB query operators](https://www.mongodb.com/docs/manual/reference/operator/query/)
- [PCRE2 pattern syntax](https://www.pcre.org/current/doc/html/pcre2pattern.html) and [PostgreSQL POSIX regular expressions](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP): regular expression dialects of data sources
- [ISO/IEC 9075](https://www.iso.org/standard/63555.html): SQL
- [OData URL conventions](https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html): system query options with a reserved prefix
- [MongoDB geospatial query operators](https://www.mongodb.com/docs/manual/reference/operator/query-geospatial/) and [PostGIS `ST_DWithin`](https://postgis.net/docs/ST_DWithin.html): geospatial filters in data sources
- [MongoDB `$elemMatch`](https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/): conditions on one array element
- [qs](https://github.com/ljharb/qs): a query string parser that reads bracket keys as arrays and nested objects
