Skip to content

fix(postgrest)!: parse responses with json.loads and return scalar RPC results - #2049

Merged
spydon merged 3 commits into
mainfrom
lukasklingsbo/sdk-2826-postgrest-json-loads
Nov 13, 2026
Merged

spydon merged 3 commits into
mainfrom
lukasklingsbo/sdk-2826-postgrest-json-loads

Conversation

@spydon

@spydon spydon commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

What

Postgrest responses are now parsed with json.loads plus a shape check instead of a pydantic TypeAdapter, and rpc().execute() returns whatever JSON value the function produced.

Why

  • The TypeAdapter(list[dict[str, JSON]]) parse was slow. On 10,000 rows it took 21.2 ms against 3.7 ms for json.loads with the shape check. v2 made the same switch in perf(postgrest): speed up JSON parsing by 22x using json.loads #1571.
  • An RPC returning a scalar (body 1 or "text") or a single row (body {...}) failed validation and raised APIError with code "200", even though the call succeeded.

Changes

  • New private module postgrest/_parsing.py with parse_json, parse_rows and parse_object. They decode with json.loads and raise InvalidResponseBodyError when the body is not JSON (including bodies nested too deeply for json.loads) or not in the expected shape.
  • APIResponse, SingleAPIResponse and the table executor use these helpers. Callers catch InvalidResponseBodyError instead of pydantic's ValidationError and turn it into APIError as before. Other errors, such as a malformed Content-Range, are not swallowed.
  • New RPCResponse dataclass with data: JSON and count. RPCFilterRequestBuilder.execute() returns it instead of APIResponse. An empty body gives data=None, and csv() on an RPC gives the text, where it used to fail on JSON parsing.
  • RPCResponse is exported from postgrest, exported from supabase as PostgrestRPCResponse, and registered in sdk-compliance.yaml under database.query.rpc.
  • MIGRATION.md documents the RPCResponse change.
  • The test schema gets three new functions: count_stored_countries (bigint), country_iso (text) and stored_country (a single row).

Behavior change

rpc(...).execute() now returns RPCResponse rather than APIResponse. At runtime data is the same for set returning functions. For type checkers, data is JSON instead of list[dict[str, JSON]]. A void function now gives data=None instead of [].

Tests

  • Unit tests for RPCResponse with sync and async clients: numbers, strings, booleans, null, objects, rows, arrays of scalars and empty bodies. A non JSON success body still raises APIError. csv() on an RPC returns the text.
  • Table executor tests for bodies in the wrong shape (rows as an object or scalar, a list of scalars, single getting an array, invalid JSON).
  • Integration tests for RPCs returning a number, text and a single row.

SDK-2826
Fixes SDK-2975

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • New Features
    • RPC calls now support responses containing numbers, text, booleans, null values, objects, arrays, and single rows.
    • Added a public response type for RPC results, including optional counts. CSV RPC results are returned as text.
    • Added database functions for counting stored countries and looking up a country’s ISO code or row.
  • Bug Fixes
    • Invalid or unexpected response formats now produce consistent API errors.
  • Documentation
    • Added migration guidance for the updated RPC response type and result shapes.

RPC execution now returns RPCResponse, which supports arbitrary JSON data, an optional count, empty bodies, and CSV text. Shared parsing helpers validate JSON and response shapes for RPC and table responses. The change exports the response type through PostgREST and Supabase and adds SQL functions, tests, migration documentation, and compliance metadata.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant RPCFilterRequestBuilder
  participant HTTPServer
  participant RPCResponse
  participant parse_json
  Caller->>RPCFilterRequestBuilder: execute RPC request
  RPCFilterRequestBuilder->>HTTPServer: send request
  HTTPServer-->>RPCFilterRequestBuilder: return HTTP response
  RPCFilterRequestBuilder->>RPCResponse: parse response
  RPCResponse->>parse_json: decode nonempty JSON body
  parse_json-->>RPCResponse: return JSON value
  RPCResponse-->>Caller: return data and count
Loading

Change: Bug fix

Merge Risk: Minimal · up to 87c3d

This change swaps response parsing to json.loads and makes RPC calls return RPCResponse, which supports scalar and single-row results. No merge-blocking risk was identified, and the breaking return-type change is documented in the migration guide.

- [ ] 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: ded8faba-b80a-441b-b58d-683b1ebdb750
Commits

Reviewing files that changed from the base of the PR and between f80e732 and 87c3da4.

Files selected for processing: 13

  • MIGRATION.md
  • sdk-compliance.yaml
  • src/postgrest/infra/supabase/migrations/20240101000000_init.sql
  • src/postgrest/src/postgrest/__init__.py
  • src/postgrest/src/postgrest/_parsing.py
  • src/postgrest/src/postgrest/request_builder.py
  • src/postgrest/src/postgrest/table_executor.py
  • src/postgrest/tests/_async/test_filter_request_builder_integration.py
  • src/postgrest/tests/_sync/test_filter_request_builder_integration.py
  • src/postgrest/tests/test_rpc_query_params.py
  • src/postgrest/tests/test_table_executor.py
  • src/supabase/src/supabase/__init__.py
  • src/supabase/src/supabase/client.py

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

@spydon spydon changed the title fix(postgrest): parse responses with json.loads and return scalar RPC results fix(postgrest)!: parse responses with json.loads and return scalar RPC results Nov 13, 2026
@spydon
spydon force-pushed the lukasklingsbo/sdk-2826-postgrest-json-loads branch from adbd05e to 87c3da4 Compare November 13, 2026 13:52
@spydon
spydon merged commit d5ead1f into main Nov 13, 2026
28 checks passed
@spydon
spydon deleted the lukasklingsbo/sdk-2826-postgrest-json-loads branch November 13, 2026 16:09
spydon added a commit that referenced this pull request Nov 13, 2026
## What

`csv()` results now have their own response type, `TextAPIResponse`,
instead of being forced into `APIResponse.data` (typed as a list of
rows) or returned as a bare `str`.

- `TextAPIResponse` holds the CSV body as a `str` in `data` and the row
count in `count` when the query asked for one. It is exported from
`postgrest`.
- `TextRequestBuilder.execute()` returns `TextAPIResponse`. Before, it
returned a bare `str` and dropped the count from `Content-Range`.
- `rpc(...).csv()` returns the same `TextRequestBuilder` as `csv()` on a
table. Since #2049 it returned the text in `RPCResponse.data`, typed as
`JSON`. That special case in `RPCFilterRequestBuilder.execute()` is
removed, and the `RPCResponse` docstring and `MIGRATION.md` now point to
`TextAPIResponse`.
- `csv()` moved from `BaseRPCRequestBuilder` to
`RPCFilterRequestBuilder`, and `sdk-compliance.yaml` now lists the new
symbols.
- A CSV body that is not valid UTF-8 raises `APIError` with the
response, like an invalid JSON body does.
- Two `rpc()` overloads now return the builder `rpc()` actually returns.
`count=..., head=True` returns `RPCCountRequestBuilder` (it claimed
`RPCFilterRequestBuilder`), and `count=..., get=False` returns
`RPCFilterRequestBuilder` (it claimed a union with
`RPCCountRequestBuilder`). Without this, `.csv()` after those calls
would have been accepted by the type checker and failed at runtime, or
rejected although it works.

## Breaking changes

- `.csv().execute()` returns `TextAPIResponse` instead of `str`. Read
the text from `response.data`.
- Filters, modifiers and `strip_nulls()` can no longer follow
`rpc(...).csv()`. They go before `csv()`, as they already did on a
table. `strip_nulls()` after `csv()` already raised `ValueError`.

`MIGRATION.md` has a new section with a type-checked example.

## Tests

- New `tests/test_text_response.py` covers table `csv()` with a count,
sync and async RPC `csv()`, a non-UTF-8 body, and the corrected `rpc()`
overload types (with `assert_type`) against a mock transport.
- Added `TextAPIResponse.from_http_request_response` unit tests to the
sync and async request builder tests.
- The CSV integration tests now assert on `res.data`.
- Removed the RPC `csv()` then `strip_nulls()` test, since that chain no
longer type-checks. The `PostgrestRequest` test still covers the
`ValueError`.

Linear: SDK-1706
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