Database / SQL

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 the SBX_* variables.
    • TableDescriptor: describes a table (name, primary key, allowed columns, server-managed columns, model).
    • sb.tables.table("name"): returns the TableRepository with 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:

    1. Configuration: get_supabase() reads the SBX_* variables, validates everything at once and fails early, listing only the missing or invalid names.
    2. Registration: the tables declared in _table_descriptors() are registered when the integration is created.
    3. Repository: sb.tables.table("name") returns the table repository, as long as the table is registered and allowed.
    4. Validation: columns, filters and values are validated before the network (ValidationError, MappingError).
    5. Execution: the call goes through the resilience executor (budget timeout and retry with backoff, only on idempotent operations).
    6. Result: the row, list, page or batch result comes back as a dict (or as the descriptor's model); any failure becomes a domain exception (SupabaseIntegrationError and subclasses).

    #Configuration

    Configuration comes from the SBX_* environment variables. The ones used by tables are:

    VariableDescription
    SBX_URLhttps URL of the Supabase project (required)
    SBX_SECRET_KEYBackend secret key (required; never in the frontend)
    SBX_TABLES_ALLOWLISTAllowed tables, comma-separated (required in prod)
    SBX_DB_SCHEMAPostgres schema (default public)
    SBX_TABLES_DEFAULT_PAGE_SIZEDefault page size (50)
    SBX_TABLES_MAX_PAGE_SIZEPage size ceiling (default min(1000, server max rows))
    SBX_TABLES_BATCH_SIZESize of each chunk in batch operations (500)
    SBX_TABLES_SERVER_MAX_ROWSReal max-rows of the Supabase project (1000)
    SBX_TABLES_QUERY_TIMEOUT_SECONDSQuery timeout in seconds (10)
    SBX_TABLES_BATCH_TIMEOUT_SECONDSBatch 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 repository

    The 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

    FieldMeaning
    nameTable name. Must be in SBX_TABLES_ALLOWLIST if it exists.
    schemaPostgres schema (default public).
    primary_keyPrimary key column, used by get_by_id, update, delete and as the sort tie-breaker (default id).
    modelNone returns dict; also accepts a dataclass or a Pydantic-style class.
    server_managed_columnsColumns the server fills in (id, created_at). They are not sent on insert when None and are rejected on update.
    columnsColumn allowlist for filter, sort, write and select. None does not restrict. Must contain the primary key and the sort_key.
    sort_keyStable, 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).

    OperatorMeaningValue rule
    EQ, NEQ, GT, GTE, LT, LTEComparisonsNon-null scalar (use IS_NULL/NOT_NULL for nulls)
    INBelongs toList, tuple or set, up to 1000 items
    LIKE, ILIKEPattern with %Text
    IS_NULL, NOT_NULLNull / not nullThe value is ignored
    CONTAINS@> on jsonb or arrayList, 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)
    WhenShallow pages or jumping to page NScanning large tables and deep pages
    RequiresNothingsort_key in the descriptor and a compatible sort order
    CostGrows with the offsetConstant
    StabilityMay repeat or skip rows if the data changesStable
    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 page

    The 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 sets stopped_early=True if part of the batch is left.
    • BatchResult has items (a list of ItemOutcome with index, ok, entity, error), stopped_early and the properties total, succeeded, failed and all_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

    MethodReturnShort DescriptionAutomatic retry
    get_by_id(id)entityLooks up by primary key; RecordNotFoundError if it does not exist.Yes
    find(query=None)listAll matching rows, in memory; [] if nothing matches.Yes
    list(query=None, page=None)PageOne page, by offset or keyset.Yes
    iterate(query=None, page_size=None)iteratorLazy scan, one page at a time.Yes
    insert(entity)entityWrites one row and returns the stored row.No
    insert_many(entities, options=None)BatchResultWrites in batch, with a result per item.No
    update(id, changes)entityUpdates by primary key; RecordNotFoundError if it does not exist.Yes
    update_where(filter, changes)intUpdates by filter and returns the affected rows; an empty filter is rejected.Yes
    upsert(entity, on_conflict=None)entityInserts or updates; on_conflict defaults to the primary key.Yes
    upsert_many(entities, on_conflict=None, options=None)BatchResultBatch upsert.Yes
    delete(id)DeleteResultDeletes by primary key; idempotent.Yes
    delete_where(filter)DeleteResultDeletes 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__.

    ExceptionWhen
    ConfigurationErrorTable not registered or outside the allowlist; table or column missing in the database.
    ValidationErrorInvalid input, detected before the network (column outside the allowlist, empty filter, invalid value).
    MappingErrorFailed to convert a value or row; names the table and field, never the value.
    RecordNotFoundErrorget_by_id or update with no matching row.
    DuplicateRecordError, ReferenceViolationErrorUniqueness (23505) or foreign key (23503) violation.
    DataErrorType, not-null or check rejected by the database.
    PermissionDeniedError, AuthenticationErrorAn RLS policy denied access; invalid key or JWT.
    OperationTimeoutError, ServiceUnavailableError, RateLimitErrorTransient 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 by columns.
    • Protected secrets: the SBX_SECRET_KEY key is a Secret that never appears in repr, 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/

    Esc
    ↑↓navigate Enteropen