Python: Database and documents
Run SQL with bound parameters, read and write documents, manage tables, migrations and transactions with the Python SDK.
Your project's Postgres database and its document collections. Calls run as the client's current user, so access policies and row-level security decide what each query may see and change.
result = await sovaria.sql_query(
"select id, title from books where author_id = $1 order by title limit $2",
params=[author_id, 20],
)
for row in result["rows"]:
print(row)#Methods
sovaria.add_column
Add a column to an existing table.
await sovaria.add_column(
table_name: str,
column_name: str,
data_type: str,
*, is_nullable: bool = True,
is_unique: bool = False,
default_value: str | int | float | bool | None = None,
) -> dict[str, Any]Parameters
table_namestrrequiredcolumn_namestrrequireddata_typestrrequiredis_nullablebooloptionaldefaultTrueis_uniquebooloptionaldefaultFalsedefault_valuestr | int | float | bool | NoneoptionaldefaultNone
Returns
dict[str, Any]
{
"status": "ok",
"table": "orders",
"column": "status",
"migration_version": "20261018101500123",
"reversible": true
}sovaria.add_foreign_key
Add a foreign-key relation.
await sovaria.add_foreign_key(
table_name: str,
column_name: str,
referenced_table: str,
referenced_column: str,
) -> dict[str, Any]Parameters
table_namestrrequiredcolumn_namestrrequiredreferenced_tablestrrequiredreferenced_columnstrrequired
Returns
dict[str, Any]
{
"status": "ok",
"table": "orders",
"column": "customer_id",
"referenced_table": "customers",
"referenced_column": "id",
"migration_version": "20261018101500123",
"reversible": true
}sovaria.batch
A write batch: every write committed together or none.
sovaria.batch() -> AnyReturns
Any
sovaria.begin_transaction
Start a table transaction and receive tx/snapshot IDs.
await sovaria.begin_transaction() -> dict[str, Any]Returns
dict[str, Any]
{
"txid": 81234,
"snapshot_txid": 81234
}sovaria.collection
A collection (or users/alice/posts subcollection) to query, add to and listen on.
sovaria.collection(path: str) -> AnyParameters
pathstrrequired
Returns
Any
sovaria.collection_group
Every collection named collection_id at any depth (comments, posts/p1/comments, …), to query.
sovaria.collection_group(collection_id: str) -> AnyParameters
collection_idstrrequired
Returns
Any
sovaria.collection_rules
Row policies on the document table that apply to this collection.
await sovaria.collection_rules(collection: str) -> dict[str, Any]Parameters
collectionstrrequired
Returns
dict[str, Any]
{
"collection": "orders",
"row_security": true,
"policies": [
{
"name": "orders_own",
"command": "ALL",
"roles": [
"public"
],
"using": "((collection = 'orders'::text) AND (owner_id = (auth.uid())::text))",
"with_check": "((collection = 'orders'::text) AND (owner_id = (auth.uid())::text))",
"permissive": "PERMISSIVE",
"platform": false
}
],
"all_collections": []
}sovaria.commit_documents
POST /api/v1/data/doc/_commit: all writes or none; reads make it a transaction.
await sovaria.commit_documents(
writes: list[dict[str, Any]],
*, reads: list[dict[str, Any]] | None = None,
) -> dict[str, Any]Parameters
writeslist[dict[str, Any]]requiredreadslist[dict[str, Any]] | NoneoptionaldefaultNone
Returns
dict[str, Any]
{
"commit_time": "2026-10-17T12:58:40.551Z",
"results": [
{
"path": "accounts/a",
"version": 13,
"update_time": "2026-10-17T12:58:40.551Z",
"exists": true
},
{
"path": "accounts/b",
"version": 8,
"update_time": "2026-10-17T12:58:40.551Z",
"exists": true,
"transform_results": [
110
]
}
]
}sovaria.commit_transaction
Commit a previously opened table transaction.
await sovaria.commit_transaction(txid: int) -> dict[str, Any]Parameters
txidintrequired
Returns
dict[str, Any]
{
"status": "ok",
"txid": 81234,
"committed": true
}sovaria.create_document_index
Composite index, e.g.
await sovaria.create_document_index(
collection: str,
fields: list[Any],
) -> dict[str, Any]["status", {"path": "total", "order": "desc"}] (built in the background).
Parameters
collectionstrrequiredfieldslist[Any]required
Returns
dict[str, Any]
{
"name": "sovidx_3f9a1c07e2b84d5a6c10",
"state": "building",
"created": true
}sovaria.create_table
Create a relational table.
await sovaria.create_table(
table_name: str,
columns: list[dict[str, Any]],
foreign_keys: list[dict[str, Any]] | None = None,
) -> dict[str, Any]Parameters
table_namestrrequiredcolumnslist[dict[str, Any]]requiredforeign_keyslist[dict[str, Any]] | NoneoptionaldefaultNone
Returns
dict[str, Any]
{
"status": "ok",
"table": "orders",
"migration_version": "20261018101500123",
"reversible": true
}sovaria.delete_plain_document
Delete a document from the document store.
await sovaria.delete_plain_document(
collection_id: str,
document_id: str,
) -> NoneParameters
collection_idstrrequireddocument_idstrrequired
Returns
None
sovaria.doc
A document reference, e.g.
sovaria.doc(path: str) -> Anysov.doc("users/alice").
Parameters
pathstrrequired
Returns
Any
sovaria.drop_column
Drop a column from a table.
await sovaria.drop_column(
table_name: str,
column_name: str,
) -> dict[str, Any]Parameters
table_namestrrequiredcolumn_namestrrequired
Returns
dict[str, Any]
{
"status": "ok",
"table": "orders",
"column": "note",
"data_restorable": true,
"migration_version": "20261018101500123",
"reversible": true
}sovaria.drop_document_index
Drop document index.
await sovaria.drop_document_index(name: str) -> NoneParameters
namestrrequired
Returns
None
sovaria.drop_foreign_key
Drop a foreign-key relation.
await sovaria.drop_foreign_key(
table_name: str,
column_name: str,
referenced_table: str,
referenced_column: str,
) -> dict[str, Any]Parameters
table_namestrrequiredcolumn_namestrrequiredreferenced_tablestrrequiredreferenced_columnstrrequired
Returns
dict[str, Any]
{
"status": "ok",
"table": "orders",
"column": "customer_id",
"referenced_table": "customers",
"referenced_column": "id"
}sovaria.drop_table
Drop a relational table.
await sovaria.drop_table(table_name: str) -> dict[str, Any]Parameters
table_namestrrequired
Returns
dict[str, Any]
{
"status": "ok",
"table": "orders_old",
"migration_version": "20261018101500123",
"reversible": true
}sovaria.get_document
Retrieve and decrypt a document from the document store. The gateway returns the stored ciphertext envelope.
await sovaria.get_document(
collection_id: str,
document_id: str,
password: str | None = None,
at_txid: int = 0,
txid: int | None = None,
) -> DocumentGetResponseDecryption happens entirely in-process here; plaintext never touches the wire.
Args: collection_id: Logical bucket name. document_id: Primary key. password: Required only when the session has no cached KEK. at_txid: Version-history time travel: return document as it was at this TXID. 0 = HEAD (latest version). txid: Deprecated alias for at_txid.
Returns: DocumentGetResponse with the decrypted plaintext bytes.
Parameters
collection_idstrrequireddocument_idstrrequiredpasswordstr | NoneoptionaldefaultNoneat_txidintoptionaldefault0txidint | NoneoptionaldefaultNone
Returns
DocumentGetResponse
sovaria.get_plain_document
Read a plain JSON document from the document store.
Snapshot reads use the at_txid query key.
await sovaria.get_plain_document(
collection_id: str,
document_id: str,
*, txid: int | None = None,
at_txid: int | None = None,
) -> dict[str, Any]txid is accepted as a deprecated alias.
Parameters
collection_idstrrequireddocument_idstrrequiredtxidint | NoneoptionaldefaultNoneat_txidint | NoneoptionaldefaultNone
Returns
dict[str, Any]
{
"id": "o_1001",
"path": "orders/o_1001",
"key": "orders:o_1001",
"data": {
"customer": "6e19c0a2-3f5b-4a8e-9b1d-0c7f2e8a4d51",
"status": "paid",
"total": 59.9,
"items": [
{
"sku": "tee-black-m",
"qty": 2
}
]
},
"version": 3,
"create_time": "2026-10-17T10:02:11.402Z",
"update_time": "2026-10-17T12:40:11.204Z",
"found": true
}sovaria.graphql
GraphQL on /graphql/v1 (pg_graphql style: { notesCollection { edges { node { id } } } }).
Runs as the signed-in user (row-level security applies) or with the anon key.
await sovaria.graphql(
query: str,
variables: dict[str, Any] | None = None,
*, operation_name: str | None = None,
) -> dict[str, Any]Returns {"data": ..., "errors": [...]}: mistakes in the query come back in errors; a refused request (no key, plan, rate limit) raises :class:SovariaError.
Parameters
querystrrequiredvariablesdict[str, Any] | NoneoptionaldefaultNoneoperation_namestr | NoneoptionaldefaultNone
Returns
dict[str, Any]
- HTTP
- POST /graphql/v1
{
"data": {
"ordersCollection": {
"edges": [
{
"node": {
"id": 1042,
"total": "59.90"
}
},
{
"node": {
"id": 1029,
"total": "18.00"
}
}
]
}
}
}sovaria.list_document_indexes
Document indexes with state (building/ready/failed) and the plan's cap.
await sovaria.list_document_indexes(
collection: str | None = None,
) -> dict[str, Any]Parameters
collectionstr | NoneoptionaldefaultNone
Returns
dict[str, Any]
{
"indexes": [
{
"name": "sovidx_3f9a1c07e2b84d5a6c10",
"collection": "orders",
"fields": [
{
"path": "status",
"order": "asc"
},
{
"path": "total",
"order": "desc"
}
],
"auto": false,
"state": "ready",
"bytes": 1327104,
"created_at": "2026-10-17T11:05:42Z"
}
],
"limit": 100,
"used": 1
}sovaria.list_migrations
List SQL migration history.
await sovaria.list_migrations(
*, table_name: str | None = None,
limit: int = 100,
offset: int = 0,
) -> dict[str, Any]Parameters
table_namestr | NoneoptionaldefaultNonelimitintoptionaldefault100offsetintoptionaldefault0
Returns
dict[str, Any]
{
"migrations": [
{
"version": "20261017143005000",
"name": "add orders status",
"up_sql": "alter table orders add column status text not null default 'pending';",
"down_sql": "alter table orders drop column status;",
"checksum": "9b2c…",
"status": "applied",
"source": "cli",
"applied_by": "6e19c0a2-…",
"applied_at": "2026-10-17T14:30:05.120000+00:00",
"rolled_back_at": null,
"rolled_back_by": null,
"duration_ms": 41,
"sql": "alter table orders add column status …",
"rollback_sql": "alter table orders drop column status;",
"reversible": true,
"timestamp": 1792247405.12,
"kind": "ALTER TABLE",
"seq": 20261017143005000
}
],
"total": 37
}sovaria.put_document
Encrypt a document client-side and write it to the document store. The plaintext NEVER leaves this device in readable form.
await sovaria.put_document(
collection_id: str,
document_id: str,
plaintext: bytes,
password: str | None = None,
) -> DocumentResponseThe gateway receives only the AES-GCM ciphertext envelope + the X-Payload-Hash integrity proof. Atlas stores the envelope verbatim (Zero-Knowledge).
Phase 2 Sprint 1 / Part 8 §1.3: - Uses the cached Argon2id KEK from login() if available. - password is required only if login() was pre-Phase-2 (no salt returned). Pass it explicitly in that case and it will be used to derive a fresh KEK (and discarded immediately).
Args: collection_id: Logical bucket name (e.g. "medical_records"). document_id: Primary key for this document. plaintext: Raw document bytes to encrypt. password: Only needed when the session has no cached KEK.
Returns: DocumentResponse with the TXID assigned by Atlas WAL.
Parameters
collection_idstrrequireddocument_idstrrequiredplaintextbytesrequiredpasswordstr | NoneoptionaldefaultNone
Returns
DocumentResponse
sovaria.put_plain_document
Write a plain JSON document to the document store.
await sovaria.put_plain_document(
collection_id: str,
document_id: str,
data: dict[str, Any],
) -> dict[str, Any]Parameters
collection_idstrrequireddocument_idstrrequireddatadict[str, Any]required
Returns
dict[str, Any]
{
"status": "ok",
"key": "orders:o_1001",
"storage": "postgres_jsonb",
"version": 3
}sovaria.rollback_transaction
Rollback transaction.
await sovaria.rollback_transaction(txid: int) -> dict[str, Any]Parameters
txidintrequired
Returns
dict[str, Any]
{
"status": "ok",
"txid": 81234,
"rolled_back": true
}sovaria.rpc
Call one of your Postgres functions: POST /rest/v1/rpc/{name} with the arguments by name.
A function that returns one value returns that value; one that returns rows returns a list of dicts.
sovaria.rpc(
name: str,
args: dict[str, Any] | None = None,
*, get: bool = False,
query: dict[str, Any] | None = None,
head: bool = False,
count: str | None = None,
) -> AnyApp users need an access policy that allows fn:<name>.
Parameters: name: The function's name. args: Arguments by name, as the function declares them. get: Call with GET and the arguments in the query string (functions that only read). query: PostgREST parameters for functions that return rows: select, order, limit, offset and filters such as {"status": "eq.open"}.
Errors raised by the function come back as :class:SovariaError with the database's code and message in the error text.
The result is a query (supabase-py's builder): await it, or chain filters first — await sov.rpc("top_posts", {"days": 7}).eq("status", "open").order("score", desc=True).limit(5) (.execute() works too). head=True, count="exact" only counts (.count).
Parameters
namestrrequired- The function's name.
argsdict[str, Any] | NoneoptionaldefaultNone- Arguments by name, as the function declares them.
getbooloptionaldefaultFalse- Call with GET and the arguments in the query string (functions that only read).
querydict[str, Any] | NoneoptionaldefaultNone- PostgREST parameters for functions that return rows:
select,order,limit,offset, filters such as{"status": "eq.open"}. headbooloptionaldefaultFalsecountstr | NoneoptionaldefaultNone
Returns
Any — The value for a function that returns one value, a list of dicts for one that returns rows, None for void.
- App users need an access policy that allows
fn:<name>— see Row-level security and access. - Also on the data facade:
DataClient(sovaria).rpc(...).
count = await sovaria.rpc("post_count", {"u": user_id})
await sovaria.rpc("transfer_points", {"from_user": a, "to_user": b, "amount": 50})
top = await sovaria.rpc("top_posts", {"days": 7}, get=True, query={"select": "id,title", "limit": 10})sovaria.run_transaction
Read-then-write atomically; retried when a document read meanwhile changes.
await sovaria.run_transaction(fn: Any, *, max_attempts: int = 5) -> AnyParameters
fnAnyrequiredmax_attemptsintoptionaldefault5
Returns
Any
sovaria.scan_documents
Run a key-prefix/range scan in the document store.
await sovaria.scan_documents(
*, prefix: str | None = None,
start_key: str | None = None,
end_key: str | None = None,
limit: int = 100,
) -> dict[str, Any]Parameters
prefixstr | NoneoptionaldefaultNonestart_keystr | NoneoptionaldefaultNoneend_keystr | NoneoptionaldefaultNonelimitintoptionaldefault100
Returns
dict[str, Any]
{
"documents": [
{
"key": "orders:o_0987",
"txid": 0,
"data": {
"status": "paid",
"total": 51.0
},
"found": true
},
{
"key": "orders:o_1001",
"txid": 0,
"data": {
"status": "paid",
"total": 59.9
},
"found": true
}
],
"count": 2,
"truncated": true
}sovaria.sql_query
Execute a SQL query against the project database. Parameters: sql: SQL statement to execute.
await sovaria.sql_query(
sql: str,
txid: int = 0,
params: list[Any] | None = None,
) -> dict[str, Any]Use $1, $2, … for values. params: Values for the placeholders, bound by the database (never spliced into SQL). txid: Optional explicit transaction ID for snapshot isolation. If 0 (default), uses the latest snapshot. If > 0, uses snapshot isolation at that TXID. The server requires txid >= 1 if provided explicitly.
Parameters
sqlstrrequired- One
SELECT,INSERT,UPDATE,DELETEorEXPLAIN. txidintoptionaldefault0- Run inside a transaction from
begin_transaction(). paramslist[Any] | NoneoptionaldefaultNone- Values for
$1,$2, … — always pass by name.
Returns
dict[str, Any] — columns, rows and row_count.
result = await sovaria.sql_query("insert into notes (body) values ($1) returning id", params=["Buy milk"])
note_id = result["rows"][0][0]Response
{
"columns": [
"id",
"total",
"status"
],
"rows": [
[
1042,
"59.90",
"paid"
],
[
1031,
"12.50",
"refunded"
]
],
"row_count": 2,
"txid": 0,
"simulated": false
}sovaria.table
The same as :meth:from_ (supabase-py's spelling): await sov.table("books").select("id,title").
sovaria.table(table: str) -> RestTableParameters
tablestrrequired
Returns
RestTable
#Ergonomic client
Dot-access helpers over SQL and documents: data = DataClient(sovaria) gives typed table and collection handles. sovaria.rpc(fn, args) returns a query you await (or .execute()) after optional filters, order, limit, range, single / maybe_single (head=True, count="exact" only counts). Calls run as the client's current user, so the same policies and row-level security apply as to hand-written SQL.
`DataClient`
data.get_cdc_capture
Whether the database records its own changes (direct-connection writes reach realtime and webhooks).
await data.get_cdc_capture() -> dict[str, Any]Returns
dict[str, Any]
data.set_cdc_capture
Turn change capture on or off; tables=None captures every table (project team or service key).
await data.set_cdc_capture(
enabled: bool,
tables: list[str] | None = None,
) -> dict[str, Any]Parameters
enabledboolrequiredtableslist[str] | NoneoptionaldefaultNone
Returns
dict[str, Any]
data.collection
Return a CollectionRef handle for the named document collection.
data.collection(name: str) -> CollectionRefParameters
namestrrequired
Returns
CollectionRef
data.table
Return a TableRef handle for the named SQL table (SQL helpers; apps prefer :meth:from_).
data.table(name: str) -> TableRefParameters
namestrrequired
Returns
TableRef
data.from_
The table through the REST API (/rest/v1): filters, related rows, insert returning the row, counts.
data.from_(name: str) -> RestTableParameters
namestrrequired
Returns
RestTable
data.rpc
Call one of your Postgres functions over REST (see :meth:SovariaClient.rpc).
await data.rpc(
name: str,
args: dict[str, Any] | None = None,
*, get: bool = False,
query: dict[str, Any] | None = None,
) -> AnyParameters
namestrrequired- The function's name.
argsdict[str, Any] | NoneoptionaldefaultNone- Arguments by name, as the function declares them.
getbooloptionaldefaultFalse- Call with GET and the arguments in the query string (functions that only read).
querydict[str, Any] | NoneoptionaldefaultNone- PostgREST parameters for functions that return rows:
select,order,limit,offset, filters such as{"status": "eq.open"}.
Returns
Any — The value for a function that returns one value, a list of dicts for one that returns rows, None for void.
- App users need an access policy that allows
fn:<name>— see Row-level security and access. - Also on the data facade:
DataClient(sovaria).rpc(...).
count = await sovaria.rpc("post_count", {"u": user_id})
await sovaria.rpc("transfer_points", {"from_user": a, "to_user": b, "amount": 50})
top = await sovaria.rpc("top_posts", {"days": 7}, get=True, query={"select": "id,title", "limit": 10})`TableRef`
table.query
Run a parameterised SQL statement and return rows as dicts.
params fill $1, $2, … and are bound by the database, never spliced into SQL: await table.query("SELECT * FROM books WHERE id = $1", [book_id]).
await table.query(
sql: str,
params: list[Any] | None = None,
) -> list[dict[str, Any]]Parameters
sqlstrrequiredparamslist[Any] | NoneoptionaldefaultNone
Returns
list[dict[str, Any]]
table.insert
Insert one row and return it as stored (with generated columns such as id).
Reading the row back needs a read rule on the table.
await table.insert(
row: dict[str, Any],
*, returning: bool = True,
) -> dict[str, Any]For a write-only table (an Insert-only rule: a contact form, a feedback box) pass returning=False: the row is inserted and {} is returned.
Parameters
rowdict[str, Any]requiredreturningbooloptionaldefaultTrue
Returns
dict[str, Any]
table.update
UPDATE rows whose columns equal *where* with *values*.
await table.update(where: dict[str, Any], values: dict[str, Any]) -> intReturns the number of rows changed.
Parameters
wheredict[str, Any]requiredvaluesdict[str, Any]required
Returns
int
table.delete
DELETE rows whose columns equal *where*.
await table.delete(where: dict[str, Any]) -> intReturns the number of rows deleted.
Parameters
wheredict[str, Any]required
Returns
int
`CollectionRef`
collection.insert
Insert a document via POST /api/v1/data/doc/{col}/{id} with {"data": ...}.
await collection.insert(
document: dict[str, Any],
document_id: str | None = None,
) -> dict[str, Any]Parameters
documentdict[str, Any]requireddocument_idstr | NoneoptionaldefaultNone
Returns
dict[str, Any]
collection.find
List documents in this collection via POST /api/v1/data/query/scan.
Parameters ---------- filter: Optional equality filters on top-level fields of each document's data.
await collection.find(
filter: dict[str, Any] | None = None,
limit: int = 100,
offset: int = 0,
) -> list[dict[str, Any]]Applied here, after the scan, so the result only contains matching documents. limit: Maximum number of results (default 100). offset: Number of matching documents to skip (default 0).
Parameters
filterdict[str, Any] | NoneoptionaldefaultNonelimitintoptionaldefault100offsetintoptionaldefault0
Returns
list[dict[str, Any]]
collection.get
Retrieve a single document by ID.
await collection.get(document_id: str) -> dict[str, Any]Parameters
document_idstrrequired
Returns
dict[str, Any]
collection.update
Replace patch's top-level fields in an existing document, in one atomic write (a missing document is an error).
await collection.update(
document_id: str,
patch: dict[str, Any],
) -> dict[str, Any]It used to read, merge here and write the whole document back, so two writers lost each other's changes (audit 2026-11-01).
Parameters
document_idstrrequiredpatchdict[str, Any]required
Returns
dict[str, Any]
collection.delete
Delete a document by ID.
await collection.delete(document_id: str) -> NoneParameters
document_idstrrequired
Returns
None
collection.count
Return the number of documents in this collection matching *filter* (up to 10,000).
await collection.count(filter: dict[str, Any] | None = None) -> intParameters
filterdict[str, Any] | NoneoptionaldefaultNone
Returns
int
`RpcQuery`
sovaria.rpc(...).select
The columns to return from a function that returns rows.
sovaria.rpc(...).select(columns: str = '*') -> RpcQueryParameters
columnsstroptionaldefault'*'
Returns
RpcQuery
sovaria.rpc(...).order
Sort the rows the function returns (call again for a second key).
sovaria.rpc(...).order(
column: str,
*, desc: bool = False,
nulls_first: bool | None = None,
) -> RpcQueryParameters
columnstrrequireddescbooloptionaldefaultFalsenulls_firstbool | NoneoptionaldefaultNone
Returns
RpcQuery
sovaria.rpc(...).limit
At most n rows.
sovaria.rpc(...).limit(n: int) -> RpcQueryParameters
nintrequired
Returns
RpcQuery
sovaria.rpc(...).range
Rows start..end inclusive, from 0.
sovaria.rpc(...).range(start: int, end: int) -> RpcQueryParameters
startintrequiredendintrequired
Returns
RpcQuery
sovaria.rpc(...).single
Exactly one row (404 when none, 409 when several).
sovaria.rpc(...).single() -> RpcQueryReturns
RpcQuery
sovaria.rpc(...).maybe_single
One row or None.
sovaria.rpc(...).maybe_single() -> RpcQueryReturns
RpcQuery
sovaria.rpc(...).execute
Execute.
await sovaria.rpc(...).execute() -> AnyReturns
Any