Skip to content

feat(postgrest): add column expressions and the filter tree - #2041

Merged
spydon merged 2 commits into
mainfrom
lukasklingsbo/sdk-2984-featpostgrest-add-column-expressions
Nov 12, 2026
Merged

spydon merged 2 commits into
mainfrom
lukasklingsbo/sdk-2984-featpostgrest-add-column-expressions

Conversation

@spydon

@spydon spydon commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Step 1 of SDK-2765 (SDK-2984): the typed column expressions and the filter tree that the typed query builder, the realtime bridge and the generator build on. A port of supabase-flutter #1793 with the typed internals of SDK-1753.

What

  • ColumnExpression[Row, Value] with Column, NullableColumn and ComputedField. Row and Value are invariant and default to Any through typing_extensions.TypeVar, so Column("deleted_at") works without generated code, while Books.id.eq("seven") and a filter from another table are type errors under mypy, pyright and pyrefly without plugins. Column and NullableColumn are siblings over a private base, so a later PartialRow.__getitem__ can overload on them without overlapping.
  • The comparison operators eq, neq, gt, gte, lt, lte, is_distinct, in_, text_search(query, type=, config=) and raw(operand). is_true() and is_false() take an explicit self: ColumnExpression[Row, bool]. is_null() exists on NullableColumn and ComputedField only.
  • Filter[Row], composed with &, | and ~, and FilterOperator carrying the wire tokens. Filter.comparison exposes a leaf as Comparison(column, operator, value, negated), which is what the realtime bridge will read. Filter.raw(column, operand) is the escape hatch for an expression no column can name.
  • Rendering happens when the request is built, by position: a top-level & as separate query parameters, | as or=(…), a nested & as and(…), a negated leaf in a group as id.not.eq.2, a negated group as not.and=(…), and a double negation collapsing. Operands go through the string builder's sanitize_param and _serialize_filter_value, so the output is the string builder's. _serialize_filter_value moves from request_builder.py to utils.py next to sanitize_param, and _TEXT_SEARCH_OPERATORS to types.py, so the filter module does not depend on the request builder.

Tests

  • test_filter.py ports the rendering tests of the Dart stack, including the group escaping cases, and asserts for every operator, operand and column name that the query parameters equal what BaseFilterRequestBuilder and SelectRequestBuilder.text_search() produce.
  • test_typecheck.py runs mypy, pyright and pyrefly on tests/typecheck/filters.py and asserts that each reports an error on exactly the lines marked # error:: a wrong operand type, a filter from another table, is_null() on a Column and is_true() on a column that is not boolean. mypy and pyright join the lints group of the package. The fixture directory is excluded from the package's own pyrefly run.

Compliance

The new symbols are listed under the top-level supporting_symbols of sdk-compliance.yaml, which covers them without claiming database.generated_types.typed_queries. The feature status changes in step 8.

Linear: SDK-2984

Step 1 of SDK-2765: Column, NullableColumn and ComputedField as
ColumnExpression[Row, Value] with Row and Value invariant and defaulting
to Any, the comparison operators, and Filter[Row] composed with &, | and
~ and rendered by position through the string builder's sanitize_param
and _serialize_filter_value. A type-check fixture is run by mypy, pyright
and pyrefly from the tests.

SDK-2984
@coderabbitai

coderabbitai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • New Features
    • Added typed column and computed-field expressions for building filters, including support for nullable fields and null checks.
    • Create filters using comparisons, membership, text search, boolean checks, and raw operands. Combine filters with AND, OR, and NOT.
    • Filter expressions preserve row types and provide access to comparison details.
  • Improvements
    • Added support for static type checking of filter expressions, helping identify incompatible operands and invalid combinations.

The PostgREST SDK adds typed column descriptors and filter expressions. Filters support comparisons, membership, text search, boolean checks, raw operands, composition, and negation, and render as query parameters. The package exports the new symbols. Shared serialization and text-search mappings are used by the new filter implementation and the existing request builder. Tests cover expression behavior, rendering parity, and static type-checker diagnostics.

Sequence Diagram(s)

sequenceDiagram
  participant ColumnExpression
  participant Filter
  participant Serializer
  participant QueryParameters
  ColumnExpression->>Filter: Construct typed filter expression
  Filter->>Serializer: Serialize filter operand
  Filter->>QueryParameters: Render filter parameters
Loading

Possibly related PRs

Change: Feature

Merge Risk: Minimal · up to 47ef3

This change adds new typed column and filter APIs along with tests. No actionable merge-blocking risk was identified.

- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 89696c8a-0928-4a39-bcd0-811365d3a3f4
Commits

Reviewing files that changed from the base of the PR and between bcd286a and 47ef3f5.

Files selected for processing: 4

  • pyrefly.toml
  • src/postgrest/pyproject.toml
  • src/postgrest/src/postgrest/filter.py
  • src/postgrest/tests/test_filter.py
Files with no reviewable changes: 1

  • src/postgrest/pyproject.toml

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 3 remain after this review.

Quote the column of ColumnExpression.raw() like every other operator,
reject one string passed to in_(), collapse a double negation when it is
built so Filter.comparison survives it, return NotImplemented when a
filter is composed with something else, and exclude the type-check
fixtures from pyrefly once at the root.
@spydon
spydon merged commit 82e2bb3 into main Nov 12, 2026
51 checks passed
@spydon
spydon deleted the lukasklingsbo/sdk-2984-featpostgrest-add-column-expressions branch November 12, 2026 13:40
spydon added a commit that referenced this pull request Nov 12, 2026
)

Step 2 of [SDK-2765](https://linear.app/supabase/issue/SDK-2765)
([SDK-2985](https://linear.app/supabase/issue/SDK-2985)): the operators
that step 1 left out and the orderings, on the column expressions and
the filter tree of #2041. A port of supabase-flutter #1794 with the
typed ranges of SDK-1755.

## What

- Text operators with `self: ColumnExpression[Row, str]`: `like`,
`ilike`, `match_regex`, `imatch_regex`, `like_all_of`, `like_any_of`,
`ilike_all_of`, `ilike_any_of`. The quantified forms take an iterable of
patterns and send it as the array literal `{a,b}`, with each member
escaped as that literal requires, where the string builder wraps one
comma-separated string in braces as given. One string in place of the
iterable raises `TypeError`, as `in_()` does.
- `contains`, `contained_by` and `overlaps` as overloads on the `self`
type, since the column type decides the shape of the operand: an array
column (`list[Element]`) takes an iterable of elements and sends
`{a,NULL}` through `_sanitize_array_param`; a range column
(`Range[Bound]`) takes a `Range[Bound]` and sends `[2,25)`, and
`contains()` also takes one `Bound` for `cs.21`; a JSON column
(`JsonValue`) takes a mapping and sends compact JSON. A JSON array or
scalar operand has no typed form and goes through `raw()`, as the
docstring says. jsonb has no `&&`, so `overlaps` has no JSON overload.
The range operators `range_lt`, `range_gt`, `range_gte`, `range_lte` and
`range_adjacent` exist on range columns only.
- `Range[Bound]`, a frozen dataclass shaped like psycopg's: `Range(2,
25)` is `[2,25)`, `bounds` picks the other three forms, `None` is an
unbounded side, and `str()` is the literal Postgres reads. Bounds render
as filter values and are quoted when they hold range syntax or are
empty. The parent issue leaves ranges as `str` or a typed range open;
the ticket's acceptance criterion, that a range operator on a non-range
column is a type error, needs a type that a text column does not have,
so `Range` it is. The generator keeps mapping ranges to `str` until step
10.
- `Ordering[Row]`, an interface with `order_key`, `asc()`, `desc()`,
`nulls_first()` and `nulls_last()`. A `ColumnExpression` is an
`Ordering` with no direction, so `order(Books.title)` will send
`order=title`, and each call returns a value holding only what was asked
for: `title.desc`, `published_on.nullsfirst`,
`published_on.desc.nullslast`. The string builder's `order()` always
sends a direction.
- `FilterOperator` gains the tokens of the new operators, and
`Comparison.value` carries the operand as given: a tuple for the array
operators, a `Range` for the range operators, a mapping for JSON.

## Tests

- `test_filter_operators.py` ports the Dart operator tests: wire
operators, array literal escaping, `NULL` members, range and JSON
operands quoted inside a group, negation, `Comparison` exposure, and
`TestEqualsTheStringBuilder`, which asserts for every new operator,
operand and negation that the query parameters equal what
`BaseFilterRequestBuilder` produces. Two comparisons are modulo
whitespace, since the string builder's `contains()` encodes JSON with a
space after each colon where its `eq()` is compact, and its
`like_all_of()` does not quote members.
- `test_ordering.py` covers the order keys, chaining in either order,
replacement, value semantics and equality with `order()` of the string
builder for every `desc` and `nullsfirst` combination. `test_range.py`
covers the literal forms, unbounded sides, bound rendering and quoting,
and the `bounds` validation.
- `tests/typecheck/operators.py` and `orderings.py` are run by
`test_typecheck.py` under mypy, pyright and pyrefly: `like()` on an
`int` and a `list` column, an array operator on an `int` and a `str`
column, a wrong element type, a JSON array or scalar operand,
`overlaps()` on a JSON column, a range operator on a `str`, `int` and
`list` column, a range with the wrong bound type, a range literal
string, an invalid `bounds` form, and an ordering from another table are
each an error on exactly the marked lines, while correct use type-checks
without ignores. A mapping passed to an array column cannot be rejected
statically, since a `dict` is an `Iterable` of its keys.
- The `builder` and `select_builder` fixtures of `test_filter.py` move
to a `conftest.py` so the new tests share them.

## Compliance

The new symbols are listed under the top-level `supporting_symbols` of
`sdk-compliance.yaml`, as in step 1; the feature status changes in step
8.

Linear: SDK-2985
spydon added a commit that referenced this pull request Nov 13, 2026
…executor (#2043)

Step 3 of [SDK-2765](https://linear.app/supabase/issue/SDK-2765)
([SDK-2986](https://linear.app/supabase/issue/SDK-2986)): the table
definition, the request value the typed builders of step 4 will collect,
and the executors that run it. A port of the `PostgrestTableRequest` and
`PostgrestTableExecutor` of supabase-flutter #1857, on the column
expressions, filters and orderings of #2041 and #2042. SDK-2711, the
interceptor seam, builds on it.

## What

- `Table[Row, Insert, Update](name, row_type, primary_key=,
computed_fields=, schema=)`: a frozen dataclass with the metadata of a
table, declared once per table as the last attribute of its namespace
class. `Insert` and `Update` are phantom here; the typed builder of step
4 uses them to accept only the table's write types, and `Never` makes
the write methods uncallable. `relations=` waits for step 6, which adds
the relation types it would hold.
- `TableRequest`: a frozen `kw_only` dataclass with the fields of Dart's
value: `table`, `operation`, `schema`, `columns`, `filter`, `orderings`,
`limit`, `offset`, `shape`, `count`, `payload`, `read_only`,
`on_conflict`, `ignore_duplicates`, `returning`, `max_affected`,
`strip_nulls`, `dry_run`, `explain` and `options`. No URL and no
headers, collections are tuples, and a changed copy is
`dataclasses.replace`. `schema=None` means the schema the table carries
and otherwise the client's; `filter=None` means every row, as in Dart,
with the typed builder of step 4 requiring `where()` or `all()` before
it builds such an update or delete. `embedded_scopes` waits for step 6
with the scope type. `TableResult(data, count)` carries `data` as plain
decoded JSON by shape. `TableOperation`, `ResultShape`, `ExplainOptions`
and `RequestOptions(headers, retry, timeout)` come with it.
- `TableExecutor` and `AsyncTableExecutor` protocols with
`execute(request)`. The async one returns `Awaitable[TableResult]`, so
both an `async def` and a method that forwards to another executor
satisfy it.
- `HttpTableExecutor(client)` and `AsyncHttpTableExecutor(client)` share
two Sans-IO functions. One renders a request through `pre_select`,
`pre_insert`, `pre_upsert`, `pre_update`, `pre_delete`, the new
`pre_rpc`, the `select` of a returning write and the `max_affected` of
the string builders into the `PostgrestRequest` they would have sent;
the other decodes the response by shape with their parsers. The
`RetryPolicy` and the request timeout of the client apply through
`communicate()`, and the headers of the client are read when a request
is sent, so `apikey` and the access token of that moment go on a request
built earlier. `X-Client-Info` lists `features=typed-api`, merged into
whatever header the client carries (the supabase client sets its own) by
the new `Headers.with_client_info_features()`;
`Headers.supabase_client_headers()` takes `features=` for the same
segment.
- `ValueError` before anything is sent: a filter on an insert or upsert,
anything but the filter, count method and options on a count, a filter
of an update, delete or count that names no rows of the table, a write
without a payload, a shape other than rows, none or explain on a write
that is not `returning` (a `HEAD` among them), and `strip_nulls` with
csv, geojson or explain. "Names no rows" is the string builder's
`_filters_embedded_resource` rule, every key an embedded resource key
such as `author.name`, since the relation `is_null()` filters arrive in
step 6.
- `RequestOptions.headers` replace the header of the same name, apart
from `Accept`, which the shape decides, and `Prefer`, whose `name=value`
preferences are merged into the rendered ones, each replacing the
preference of the same name.
- `pre_rpc` is extracted from `PostgrestClient.rpc`, `_select_returned`
from `QueryRequestBuilder.select`, and `_max_affected` and `_explain`
from their builder methods, so the executor renders through the same
code. No behavior change for the string builder.

Two defaults differ from the string builder, as in Dart: a write sends
`Prefer: return=minimal` unless `returning` is set, and a list payload
sends `missing=default` so that a key left out of some rows gets the
database default. One thing differs from Dart: the `columns` of a
function call make its `select` list whatever `returning` says, since a
function call returns its rows regardless and `returning` is a write
option.

Three things have no string builder counterpart. Several orderings go
into one `order=title.desc,id` parameter, since PostgREST keeps the
first `order` parameter only; the string builder sends one parameter per
`order()` call, which is worth its own look. `dry_run` sends `Prefer:
tx=rollback` as the Dart and JS builders do, and since PostgREST accepts
that preference whatever its `db-tx-end` setting and commits when the
setting does not allow the override, the executors check
`Preference-Applied` of the response and raise `APIError` when the
rollback was not applied, so that a committed dry run is loud rather
than silent. `handling=strict` would not help: PostgREST 13 accepts
`tx=rollback` under strict handling and still ignores it.
`ResultShape.GEOJSON` adds `ResponseShape.GEOJSON` to
`PostgrestRequest`, rendered as `Accept: application/geo+json` and
rejected with `strip_nulls` like csv.

## Tests

- `test_table_executor.py`: `TestRendersWhatTheStringBuilderSends`
finalizes the rendered request and the string builder's for 48 queries
over every operation and shape and compares method, path, query,
headers, content, timeout and retry, plus the schema of the table and of
the request, the preference merge and the `Accept` of the shape. Then
the pre-send `ValueError`s and the filters that do name rows, decoding
by shape (rows, single, `maybe_single` with its 406, none, head, csv,
geojson, explain as text and as json, value, count, a counted select,
silent and returning writes, an error status, a body in another shape),
the send path (`X-Client-Info` with and without a client-set header,
`apikey` and a token set after the executor was created, request
timeout, retries with the policy of the client and per request, schema),
the async executor, and a soft-delete executor wrapped around both
executors.
- `test_table_request.py`: value semantics, defaults and option
validation.
- `tests/typecheck/tables.py` under mypy, pyright and pyrefly: a row
type, primary key or computed field of another table and a nullable
primary key are errors on exactly the marked lines; `HttpTableExecutor`
satisfies `TableExecutor` and `AsyncHttpTableExecutor` satisfies
`AsyncTableExecutor`, each is rejected as the other, an async client is
rejected by the sync executor, and wrapping executors satisfy both.
- `test_headers.py`: the features segment and the merge.

## Compliance

The new symbols are listed under the top-level `supporting_symbols` of
`sdk-compliance.yaml`, as in steps 1 and 2; the feature status changes
in step 8.

## Found on the way

`PostgrestClient.schema()` builds the new client from
`dict(self.default_headers)`, which already holds `Accept-Profile:
public`, and the constructor appends to it with `set()`, so the request
carries `Accept-Profile: public, library`. Not fixed here; the parity
test for a schema uses a client created with `schema="library"` instead.

Linear: SDK-2986
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant