Supabase Database
Documentation of the BetterAI integration with Supabase tables: how to get the integration, declare tables and run CRUD, queries, pagination and batch operations.
On this page
#Overview
Access to Supabase tables goes through a single integration, located in src/database/supabase_integration/. Project flows do not create supabase SDK clients or write SQL: they ask the composition point for the integration and work on table repositories.
get_supabase()(src/database/supabase_provider.py): returns the process-wide shared integration, created on the first call from theSBX_*variables.TableDescriptor: describes a table (name, primary key, allowed columns, server-managed columns, model).sb.tables.table("name"): returns theTableRepositorywith the CRUD, query, pagination and batch operations.Query,Condition,FilterGroup,Sort,PageRequest: query objects independent of the SDK.
The integration talks to Supabase through the REST API (PostgREST). There is no raw SQL execution: filters, sorting and writes are described with query objects and validated before going over the network.
#Execution Flow
A table operation follows these steps:
- Configuration:
get_supabase()reads theSBX_*variables, validates everything at once and fails early, listing only the missing or invalid names. - Registration: the tables declared in
_table_descriptors()are registered when the integration is created. - Repository:
sb.tables.table("name")returns the table repository, as long as the table is registered and allowed. - Validation: columns, filters and values are validated before the network (
ValidationError,MappingError). - Execution: the call goes through the resilience executor (budget timeout and retry with backoff, only on idempotent operations).
- Result: the row, list, page or batch result comes back as a
dict(or as the descriptor'smodel); any failure becomes a domain exception (SupabaseIntegrationErrorand subclasses).
#Configuration
Configuration comes from the SBX_* environment variables. The ones used by tables are:
| Variable | Description |
|---|---|
SBX_URL | https URL of the Supabase project (required) |
SBX_SECRET_KEY | Backend secret key (required; never in the frontend) |
SBX_TABLES_ALLOWLIST | Allowed tables, comma-separated (required in prod) |
SBX_DB_SCHEMA | Postgres schema (default public) |
SBX_TABLES_DEFAULT_PAGE_SIZE | Default page size (50) |
SBX_TABLES_MAX_PAGE_SIZE | Page size ceiling (default min(1000, server max rows)) |
SBX_TABLES_BATCH_SIZE | Size of each chunk in batch operations (500) |
SBX_TABLES_SERVER_MAX_ROWS | Real max-rows of the Supabase project (1000) |
SBX_TABLES_QUERY_TIMEOUT_SECONDS | Query timeout in seconds (10) |
SBX_TABLES_BATCH_TIMEOUT_SECONDS | Batch operation timeout in seconds (60) |
Environment rules. In homol and prod the .env file is forbidden (use the platform variables) and prod requires SBX_TABLES_ALLOWLIST. A new table needs a TableDescriptor and must be in the allowlist. The full list is in src/database/supabase_integration/.env.example.
#Getting the Integration
from src.database.supabase_provider import get_supabase
sb = get_supabase() # Shared integration of the process
items = sb.tables.table("sbx_test_items") # Table repositoryThe tables used by the flows are declared in _table_descriptors(), in src/database/supabase_provider.py. Adding a table means adding a descriptor, without editing any other existing code:
from src.database.supabase_integration import TableDescriptor
def _table_descriptors():
return (
TableDescriptor(
"sbx_test_items",
columns=("id", "name", "qty", "created_at"), # Column allowlist
server_managed_columns=("id", "created_at"), # Filled in by the server
sort_key="created_at", # Enables keyset pagination
),
)#TableDescriptor
| Field | Meaning |
|---|---|
name | Table name. Must be in SBX_TABLES_ALLOWLIST if it exists. |
schema | Postgres schema (default public). |
primary_key | Primary key column, used by get_by_id, update, delete and as the sort tie-breaker (default id). |
model | None returns dict; also accepts a dataclass or a Pydantic-style class. |
server_managed_columns | Columns the server fills in (id, created_at). They are not sent on insert when None and are rejected on update. |
columns | Column allowlist for filter, sort, write and select. None does not restrict. Must contain the primary key and the sort_key. |
sort_key | Stable, non-null column that enables keyset pagination (e.g. created_at). |
#Create
novo = items.insert({"name": "Ana", "qty": 1}) # Returns the stored row, already with id and created_at
print(novo["id"])
lote = items.insert_many( # Batch: one result per item
[{"name": f"item-{i}", "qty": i} for i in range(25)],
BatchOptions(batch_size=10, mode="continue"),
)
print(lote.total, lote.succeeded, lote.failed, lote.all_ok, lote.stopped_early)
for it in lote.items:
if not it.ok:
print("failed item", it.index, type(it.error).__name__)#Read
um = items.get_by_id(novo["id"]) # RecordNotFoundError if it does not exist
achados = items.find(Query.where(Condition("name", Op.ILIKE, "an%"))) # Empty list if nothing matches
iguais = items.find(Query.eq("qty", 5))
q = Query(
filter=FilterGroup(items=(
Condition("qty", Op.GTE, 5),
FilterGroup(items=(Condition("qty", Op.EQ, 7), Condition("qty", Op.EQ, 9)), logic="or"),
)), # qty >= 5 AND (qty = 7 OR qty = 9)
sorts=(Sort("name"),),
columns=("id", "name", "qty"), # Optional projection
)
pag = items.list(q, PageRequest(limit=10, offset=0, include_count=True))
print(pag.items, pag.total, pag.has_more)
for linha in items.iterate(q, page_size=100): # Large table scan, one page at a time
...find() loads every matching row into memory. For large tables use iterate().
#Update
atual = items.update(novo["id"], {"qty": 5}) # RecordNotFoundError if it does not exist
n = items.update_where(Condition("name", Op.LIKE, "item-%"), {"qty": 0}) # Returns the number of affected rows
items.upsert({"id": novo["id"], "name": "Ana", "qty": 999}, on_conflict="id") # Inserts or updates
items.upsert_many([{"id": 1, "name": "A"}, {"id": 2, "name": "B"}], on_conflict="id")#Delete
r = items.delete(novo["id"]) # Idempotent
print(r.removed, r.removed_count) # removed=False if it no longer existed
items.delete_where(Condition("name", Op.LIKE, "item-%")) # An empty filter is rejected (ValidationError)update_where and delete_where reject an empty filter (ValidationError). This is the protection against changing or deleting the whole table.
#Queries
Query has filter, sorts and columns. Shortcuts: Query.where(*conditions) (AND between the conditions) and Query.eq(column, value). A FilterGroup combines Condition or other groups with logic="and" or "or" (maximum depth 8).
| Operator | Meaning | Value rule |
|---|---|---|
EQ, NEQ, GT, GTE, LT, LTE | Comparisons | Non-null scalar (use IS_NULL/NOT_NULL for nulls) |
IN | Belongs to | List, tuple or set, up to 1000 items |
LIKE, ILIKE | Pattern with % | Text |
IS_NULL, NOT_NULL | Null / not null | The value is ignored |
CONTAINS | @> on jsonb or array | List, dict or text |
Values accepted on writes: str, int, bool, finite float, Decimal (sent as text), datetime with a timezone (converted to UTC), date, time, UUID, Enum, dict, list, tuple and set. Any other type raises MappingError.
#Pagination
PageRequest(limit=None, offset=0, cursor=None, include_count=False) asks for a page and Page returns items, limit, offset, next_cursor, total and has_more. Without limit, SBX_TABLES_DEFAULT_PAGE_SIZE applies; asking for more than the effective ceiling reduces the value with a warning, without an error.
| Offset (default) | Keyset (optional) | |
|---|---|---|
| When | Shallow pages or jumping to page N | Scanning large tables and deep pages |
| Requires | Nothing | sort_key in the descriptor and a compatible sort order |
| Cost | Grows with the offset | Constant |
| Stability | May repeat or skip rows if the data changes | Stable |
from src.database.supabase_integration.tables import KEYSET_START
cursor = KEYSET_START # Opens the page chain
while cursor:
pag = items.list(Query(), PageRequest(limit=100, cursor=cursor))
for linha in pag.items:
...
cursor = pag.next_cursor # None on the last pageThe cursor is opaque and signed by the query: using it with a different filter or sort direction raises ValidationError.
#Batch Operations
insert_many and upsert_many receive BatchOptions(batch_size=None, mode="continue"). Each chunk is one atomic request in Postgres; there is no atomicity across chunks. The whole batch is validated before anything is sent.
mode="continue": a chunk that fails because of data or a conflict is split in half until the bad items are isolated; the rest is written.mode="stop": stops at the first failing chunk and setsstopped_early=Trueif part of the batch is left.BatchResulthasitems(a list ofItemOutcomewithindex,ok,entity,error),stopped_earlyand the propertiestotal,succeeded,failedandall_ok.
#Typed Entities
By default rows are dict. To work with a dataclass or a Pydantic-style class, set model in the descriptor. insert and upsert accept the model or a dict; reads return the model; update(id, {...}) always receives a dict of changes.
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from uuid import UUID
@dataclass
class Item:
id: UUID
name: str
qty: int = 0
created_at: Optional[datetime] = None
TableDescriptor("sbx_test_items", model=Item, server_managed_columns=("id", "created_at"))
novo = items.insert(Item(id=None, name="Ana", qty=1)) # id=None is omitted (server column)
outro = items.get_by_id(novo.id) # Reads return Item#Method Table
| Method | Return | Short Description | Automatic retry |
|---|---|---|---|
get_by_id(id) | entity | Looks up by primary key; RecordNotFoundError if it does not exist. | Yes |
find(query=None) | list | All matching rows, in memory; [] if nothing matches. | Yes |
list(query=None, page=None) | Page | One page, by offset or keyset. | Yes |
iterate(query=None, page_size=None) | iterator | Lazy scan, one page at a time. | Yes |
insert(entity) | entity | Writes one row and returns the stored row. | No |
insert_many(entities, options=None) | BatchResult | Writes in batch, with a result per item. | No |
update(id, changes) | entity | Updates by primary key; RecordNotFoundError if it does not exist. | Yes |
update_where(filter, changes) | int | Updates by filter and returns the affected rows; an empty filter is rejected. | Yes |
upsert(entity, on_conflict=None) | entity | Inserts or updates; on_conflict defaults to the primary key. | Yes |
upsert_many(entities, on_conflict=None, options=None) | BatchResult | Batch upsert. | Yes |
delete(id) | DeleteResult | Deletes by primary key; idempotent. | Yes |
delete_where(filter) | DeleteResult | Deletes by filter; an empty filter is rejected. | Yes |
#Error Handling
No SDK exception (supabase, postgrest, httpx) reaches project code: everything becomes SupabaseIntegrationError or a subclass, with the original cause in __cause__.
| Exception | When |
|---|---|
ConfigurationError | Table not registered or outside the allowlist; table or column missing in the database. |
ValidationError | Invalid input, detected before the network (column outside the allowlist, empty filter, invalid value). |
MappingError | Failed to convert a value or row; names the table and field, never the value. |
RecordNotFoundError | get_by_id or update with no matching row. |
DuplicateRecordError, ReferenceViolationError | Uniqueness (23505) or foreign key (23503) violation. |
DataError | Type, not-null or check rejected by the database. |
PermissionDeniedError, AuthenticationError | An RLS policy denied access; invalid key or JWT. |
OperationTimeoutError, ServiceUnavailableError, RateLimitError | Transient failures (retryable=True). |
try:
items.get_by_id("00000000-0000-0000-0000-000000000000")
except RecordNotFoundError:
... # 404 in the endpoint
except ValidationError:
... # 422: invalid input
except SupabaseIntegrationError as e: # Any integration error
print(e.retryable, e.status, e.provider_code, e.attempts, e.outcome_unknown, e.correlation_id)insert and insert_many are never retried automatically (they are not idempotent). On a timeout the error carries outcome_unknown=True: check the database before trying again.
#Architecture and Insights
- Allowlist: the table must be registered and in
SBX_TABLES_ALLOWLIST; the filter, sort and write columns can be restricted bycolumns. - Protected secrets: the
SBX_SECRET_KEYkey is aSecretthat never appears inrepr, logs or error messages. - Resilience: only idempotent operations are retried, with backoff and jitter, within a time budget (
SBX_RETRY_*). - Without blocking the event loop: in FastAPI use
create_async_integration, which runs the calls in threads. - File and record together: to write a file and the record that points to it, with compensation on failure, see the Storage page.
Source: src/database/supabase_integration/tables/