JavaScript: Database and documents
Run SQL with bound parameters, manage documents in collections, tables, migrations and multi-request transactions with @sovaria/sdk.
sovaria.data is your project's Postgres database and its document collections. Every call runs as the client's current user, so access policies and row-level security decide what each query may see and change.
Apps read and write rows with sovaria.from(table) (see the client reference): select with filters and related rows, insert that resolves to the stored row, update, delete, count and subscribe. Keep data.sql for reports and scripts; its answer is { columns, rows } with each row as an array of values.
import { createClient } from '@sovaria/sdk'
const sovaria = createClient('https://<project-ref>.sovarias.in', '<anon-key>')
const { columns, rows } = await sovaria.data.sql(
'select id, title from books where author_id = $1 order by title limit $2',
[authorId, 20],
)#SQL and functions
sovaria.data.sql
Run one SQL statement.
sovaria.data.sql(
sql: string,
params?: JsonValue[] | number,
txid?: number = 0,
opts?: { readOnly?: boolean },
): Promise<JsonObject>Pass values for $1, $2, … as params — they are bound by the database, so user input never becomes SQL: sql('SELECT * FROM books WHERE id = $1', [id]). A number as the second argument is still read as txid (older signature).
{ readOnly: true } runs it in a read-only transaction (the server refuses writes, including through functions). The answer has truncated: true when it was cut at your plan's sql.max_rows.
Parameters
sqlstringrequired- One statement:
SELECT,INSERT,UPDATE,DELETEorEXPLAIN. Schema changes belong in migrations. paramsJsonValue[] | numberoptional- Values for
$1,$2, … in order. txidnumberoptionaldefault0- Run inside a transaction from
beginTransaction(). opts{ readOnly?: boolean }optional
Returns
Promise<JsonObject> — { columns, rows, row_count } — rows is an array of arrays in columns order.
- App code that sends
CREATE/ALTER/DROPgets400 SQL_ROUTE_VIOLATION. - A table without an access policy and without forced RLS answers
403 … NO_POLICY_DEFINED— see Row-level security and access.
const { rows: [[id]] } = await sovaria.data.sql(
'insert into notes (body) values ($1) returning id',
['Buy milk'],
)Response
{
"columns": [
"id",
"total",
"status"
],
"rows": [
[
1042,
"59.90",
"paid"
],
[
1031,
"12.50",
"refunded"
]
],
"row_count": 2,
"txid": 0,
"simulated": false
}sovaria.data.rpc
Call one of your Postgres functions: POST /rest/v1/rpc/{name} with the arguments by name.
sovaria.data.rpc(
name: string,
args?: JsonObject = {},
options?: RpcOptions = {},
): Promise<T>A function that returns one value resolves to that value; one that returns rows resolves to an array of objects. App users need an access policy that allows fn:<name>. When the function raises an error, the SovariaError's detail holds the database's code and message (and technicalMessage repeats it for logs); message stays one you can show users.
const n = await sovaria.data.rpc<number>('post_count', { u: userId }) const top = await sovaria.data.rpc('top_posts', { days: 7 }, { get: true, query: { limit: 10 } })
Parameters
namestringrequired- The function's name.
argsJsonObjectoptionaldefault{}- Arguments by name, as the function declares them (
{ from_user, to_user, amount }). optionsRpcOptionsoptionaldefault{}get: truecalls with GET and the arguments in the query string (functions that only read);queryadds PostgREST parameters for functions that return rows:select,order,limit,offsetand filters such as{ status: 'eq.open' }.
Returns
Promise<T> — The value, for a function that returns one value; an array of objects for one that returns rows; null for void.
- App users can call a function once an access policy allows
fn:<name>— see Row-level security and access. The function's own queries still run under row-level security unless it is a security definer (Database functions). - An error the function raises (
raise exception … using errcode = 'P0001') rejects with aSovariaErrorwhosedetailholds the database'scodeandmessage;messagestays one you can show users. - Create the client with your project URL:
/rest/v1is addressed by the project, likefunctions.call.
const count = await sovaria.data.rpc<number>('post_count', { u: userId })
await sovaria.data.rpc('transfer_points', { from_user: a, to_user: b, amount: 50 })
const top = await sovaria.data.rpc('top_posts', { days: 7 }, {
get: true,
query: { select: 'id,title', order: 'score.desc', limit: 10 },
})#Change capture (direct-connection writes reach realtime and webhooks)
sovaria.data.cdc.getCapture
Get capture.
sovaria.data.cdc.getCapture(): Promise<JsonObject>Returns
Promise<JsonObject>
sovaria.data.cdc.setCapture
tables: null (default) captures every table, including ones made later.
sovaria.data.cdc.setCapture(
enabled: boolean,
tables?: string[] | null = null,
): Promise<JsonObject>Parameters
enabledbooleanrequiredtablesstring[] | nulloptionaldefaultnull
Returns
Promise<JsonObject>
#Documents
sovaria.data.docPut
Doc put.
sovaria.data.docPut(
collection: string,
documentId: string,
data: JsonObject,
): Promise<JsonObject>Parameters
collectionstringrequired- Collection name (created on first write).
documentIdstringrequired- Your id for the document.
dataJsonObjectrequired- Any JSON object; replaces the whole document.
Returns
Promise<JsonObject>
- HTTP
POST /api/v1/data/doc/{…}/{…}
await sovaria.data.docPut('carts', userId, { items: [{ sku: 'B-12', qty: 2 }] })sovaria.data.docGet
Doc get.
sovaria.data.docGet(
collection: string,
documentId: string,
atTxid?: number,
): Promise<JsonObject>Parameters
collectionstringrequired- Collection name.
documentIdstringrequired- Document id.
atTxidnumberoptional- Read the document as it was at an earlier transaction id.
Returns
Promise<JsonObject> — The document, or a 404 SovariaError when it doesn't exist.
- HTTP
GET /api/v1/data/doc/{…}/{…}
sovaria.data.docList
List the documents in one collection (newest writes last): [{ id, data, txid }].
sovaria.data.docList(
collection: string,
options?: { limit?: number } = {},
): Promise<{ id: string; data: JsonObject; txid: number; }[]>Subcollections are not included — list collection/<docId>/<sub> for those.
Parameters
collectionstringrequired- Collection name.
options{ limit?: number }optionaldefault{}limit: how many to return.
Returns
Promise<{ id: string; data: JsonObject; txid: number; }[]> — [{ id, data }].
sovaria.data.docScan
Doc scan.
sovaria.data.docScan(
args: { prefix?: string start_key?: string end_key?: string limit?: number },
): Promise<JsonObject>Parameters
args{ prefix?: string start_key?: string end_key?: string limit?: number }required
Returns
Promise<JsonObject>
{
"documents": [
{
"key": "orders:o_0987",
"txid": 0,
"data": {
"status": "paid",
"total": 51
},
"found": true
},
{
"key": "orders:o_1001",
"txid": 0,
"data": {
"status": "paid",
"total": 59.9
},
"found": true
}
],
"count": 2,
"truncated": true
}sovaria.data.docDelete
Doc delete.
sovaria.data.docDelete(
collection: string,
documentId: string,
): Promise<JsonObject>Parameters
collectionstringrequired- Collection name.
documentIdstringrequired- Document id.
Returns
Promise<JsonObject>
sovaria.data.putDocumentE2ee
Encrypt client-side and write a Zero-Knowledge document envelope to the document store.
sovaria.data.putDocumentE2ee(
collection: string,
documentId: string,
plaintext: Uint8Array | string,
password?: string,
): Promise<JsonObject>Parameters
collectionstringrequireddocumentIdstringrequiredplaintextUint8Array | stringrequired- What to encrypt; it never leaves the device unencrypted.
passwordstringoptional- Encryption password; without it the key from the user's session is used.
Returns
Promise<JsonObject>
- Sovaria stores only the encrypted envelope. Losing the password means losing the data.
sovaria.data.getDocumentE2ee
Retrieve and decrypt a Zero-Knowledge document from the document store.
sovaria.data.getDocumentE2ee(
collection: string,
documentId: string,
password?: string,
atTxid?: number,
): Promise<{ plaintext: Uint8Array<ArrayBufferLike>; }>Parameters
collectionstringrequireddocumentIdstringrequiredpasswordstringoptionalatTxidnumberoptional
Returns
Promise<{ plaintext: Uint8Array<ArrayBufferLike>; }>
#Migrations
sovaria.data.tableMigrations
Table migrations.
sovaria.data.tableMigrations(
query?: { table_name?: string limit?: number offset?: number },
): Promise<JsonObject>Parameters
query{ table_name?: string limit?: number offset?: number }optional- Filter by
table_name; page withlimit/offset.
Returns
Promise<JsonObject>
{
"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.data.dryRunMigration
Run a migration inside a transaction and roll it back: reports whether it would apply.
sovaria.data.dryRunMigration(
migration: { name: string; upSql: string; downSql?: string },
): Promise<JsonObject>Parameters
migration{ name: string; upSql: string; downSql?: string }required
Returns
Promise<JsonObject> — Whether it would succeed, without changing anything (the transaction is rolled back).
{
"version": "20261018101500123",
"status": "dry_run_ok",
"duration_ms": 35
}sovaria.data.applyMigration
Apply a migration atomically and record it in the project's history.
sovaria.data.applyMigration(
migration: { name: string; upSql: string; downSql?: string; version?: string },
): Promise<JsonObject>downSql makes it reversible.
Parameters
migration{ name: string; upSql: string; downSql?: string; version?: string }requiredname(unique),upSql, optionaldownSql(needed to undo it), optionalversion.
Returns
Promise<JsonObject>
- With Staging first on, apply migrations in the staging environment and use Deploy to production — see Environments, staging and deploying to production.
const migration = {
name: '20261016_add_note',
upSql: 'alter table books add column note text',
downSql: 'alter table books drop column note',
}
const check = await sovaria.data.dryRunMigration(migration) // runs and rolls back
await sovaria.data.applyMigration(migration)Response
{
"version": "20261018101500123",
"name": "add orders status",
"status": "applied",
"duration_ms": 38,
"reversible": true
}sovaria.data.rollbackMigration
Undo the latest migration (or version with force) using its down SQL.
sovaria.data.rollbackMigration(
opts?: { version?: string; force?: boolean } = {},
): Promise<JsonObject>Parameters
opts{ version?: string; force?: boolean }optionaldefault{}versionto undo a specific migration (withforce); default the latest.
Returns
Promise<JsonObject>
- Needs the migration's down SQL.
{
"version": "20261018101500123",
"name": "add orders status",
"status": "rolled_back"
}#Tables
sovaria.data.tableCreate
Table create.
sovaria.data.tableCreate(payload: JsonObject): Promise<JsonObject>Parameters
payloadJsonObjectrequired
Returns
Promise<JsonObject>
{
"status": "ok",
"table": "orders",
"migration_version": "20261018101500123",
"reversible": true
}sovaria.data.tableDrop
Table drop.
sovaria.data.tableDrop(tableName: string): Promise<JsonObject>Parameters
tableNamestringrequired
Returns
Promise<JsonObject>
{
"status": "ok",
"table": "orders_old",
"migration_version": "20261018101500123",
"reversible": true
}sovaria.data.tableAddColumn
Table add column.
sovaria.data.tableAddColumn(payload: JsonObject): Promise<JsonObject>Parameters
payloadJsonObjectrequired
Returns
Promise<JsonObject>
{
"status": "ok",
"table": "orders",
"column": "status",
"migration_version": "20261018101500123",
"reversible": true
}sovaria.data.tableDropColumn
Table drop column.
sovaria.data.tableDropColumn(
tableName: string,
columnName: string,
): Promise<JsonObject>Parameters
tableNamestringrequiredcolumnNamestringrequired
Returns
Promise<JsonObject>
{
"status": "ok",
"table": "orders",
"column": "note",
"data_restorable": true,
"migration_version": "20261018101500123",
"reversible": true
}sovaria.data.tableAddForeignKey
Table add foreign key.
sovaria.data.tableAddForeignKey(
payload: JsonObject,
): Promise<JsonObject>Parameters
payloadJsonObjectrequired
Returns
Promise<JsonObject>
{
"status": "ok",
"table": "orders",
"column": "customer_id",
"referenced_table": "customers",
"referenced_column": "id",
"migration_version": "20261018101500123",
"reversible": true
}sovaria.data.tableDropForeignKey
Table drop foreign key.
sovaria.data.tableDropForeignKey(
payload: JsonObject,
): Promise<JsonObject>Parameters
payloadJsonObjectrequired
Returns
Promise<JsonObject>
{
"status": "ok",
"table": "orders",
"column": "customer_id",
"referenced_table": "customers",
"referenced_column": "id"
}#Transactions
sovaria.data.beginTransaction
Begin transaction.
sovaria.data.beginTransaction(): Promise<JsonObject>Returns
Promise<JsonObject> — { txid } to pass to sql(…, params, txid), then commitTransaction(txid) or rollbackTransaction(txid).
const { txid } = await sovaria.data.beginTransaction()
try {
await sovaria.data.sql('update accounts set balance = balance - $1 where id = $2', [10, from], txid)
await sovaria.data.sql('update accounts set balance = balance + $1 where id = $2', [10, to], txid)
await sovaria.data.commitTransaction(txid)
} catch (err) {
await sovaria.data.rollbackTransaction(txid)
throw err
}Response
{
"txid": 81234,
"snapshot_txid": 81234
}sovaria.data.commitTransaction
Commit transaction.
sovaria.data.commitTransaction(txid: number): Promise<JsonObject>Parameters
txidnumberrequired
Returns
Promise<JsonObject>
{
"status": "ok",
"txid": 81234,
"committed": true
}sovaria.data.rollbackTransaction
Rollback transaction.
sovaria.data.rollbackTransaction(txid: number): Promise<JsonObject>Parameters
txidnumberrequired
Returns
Promise<JsonObject>
{
"status": "ok",
"txid": 81234,
"rolled_back": true
}#More
sovaria.data.docQuery
Field query (where, order_by, limit, cursors) — see also sov.collection(...).
sovaria.data.docQuery(
collection: string,
query?: JsonObject = {},
): Promise<JsonObject>Parameters
collectionstringrequiredqueryJsonObjectoptionaldefault{}
Returns
Promise<JsonObject>
{
"documents": [
{
"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"
},
{
"id": "o_0987",
"path": "orders/o_0987",
"key": "orders:o_0987",
"data": {
"customer": "6e19c0a2-3f5b-4a8e-9b1d-0c7f2e8a4d51",
"status": "paid",
"total": 51,
"items": [
{
"sku": "tee-black-m",
"qty": 2
}
]
},
"version": 1,
"create_time": "2026-10-17T10:02:11.402Z",
"update_time": "2026-10-17T12:40:11.204Z"
}
],
"count": 2,
"has_more": true,
"next_cursor": {
"values": [
51
],
"key": "o_0987"
}
}sovaria.data.docCount
Doc count.
sovaria.data.docCount(
collection: string,
query?: JsonObject = {},
): Promise<JsonObject>Parameters
collectionstringrequiredqueryJsonObjectoptionaldefault{}
Returns
Promise<JsonObject>
{
"count": 1043
}sovaria.data.docCommit
Atomic commit: { op, path, data, merge, transforms, precondition } writes; reads make it a transaction.
sovaria.data.docCommit(
writes: JsonObject[],
reads?: JsonObject[] = [],
): Promise<JsonObject>Parameters
writesJsonObject[]requiredreadsJsonObject[]optionaldefault[]
Returns
Promise<JsonObject>
{
"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.data.docIndexes
Doc indexes.
sovaria.data.docIndexes(collection?: string): Promise<JsonObject>Parameters
collectionstringoptional
Returns
Promise<JsonObject>
{
"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.data.createDocIndex
Create doc index.
sovaria.data.createDocIndex(
collection: string,
fields: (string | { path: string; order?: 'asc' | 'desc' })[],
): Promise<JsonObject>Parameters
collectionstringrequiredfields(string | { path: string; order?: 'asc' | 'desc' })[]required
Returns
Promise<JsonObject>
{
"name": "sovidx_3f9a1c07e2b84d5a6c10",
"state": "building",
"created": true
}sovaria.data.dropDocIndex
Drop doc index.
sovaria.data.dropDocIndex(name: string): Promise<JsonObject>Parameters
namestringrequired
Returns
Promise<JsonObject>
sovaria.data.collectionRules
Collection rules.
sovaria.data.collectionRules(collection: string): Promise<JsonObject>Parameters
collectionstringrequired
Returns
Promise<JsonObject>
{
"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.data.schemaDigest
The schema as one short line per table: types, keys, →references, allowed values, indexes, owner-only rows.
sovaria.data.schemaDigest(
options?: { tables?: string[]; maxChars?: number; since?: string } = {},
): Promise<SchemaDigest>Parameters
options{ tables?: string[]; maxChars?: number; since?: string }optionaldefault{}
Returns
Promise<SchemaDigest>
{
"version": "79d083ae9b31",
"schema": "public",
"tables": 3,
"text": "# !=not null =default pk uniq →fk(table key) in()=allowed values idx()=index rls:owner(col)=owner-only rows updated_at:auto=kept current by a trigger\ncustomers(id uuid pk=gen_random_uuid(), email text! uniq, created_at timestamptz!=now()) ~1.2k rows\norders(id uuid pk=gen_random_uuid(), customer_id uuid →customers cascade, status text!='pending' in(pending|paid|shipped), total numeric(12,2)!, user_id uuid!=caller, created_at timestamptz!=now()) rls:owner(user_id) idx(customer_id) idx(user_id)\norder_items(id uuid pk=gen_random_uuid(), order_id uuid! →orders cascade, qty int!, created_at timestamptz!=now()) check(qty > 0) idx(order_id)"
}sovaria.data.applySchemaPlan
Create or extend tables from one declarative plan: checked first (a 422 lists every problem and nothing changes), then applied as one reversible migration and verified.
sovaria.data.applySchemaPlan(
plan: { tables: SchemaPlanTable[]; dryRun?: boolean; name?: string },
): Promise<SchemaPlanResult>dryRun returns the SQL instead.
Parameters
plan{ tables: SchemaPlanTable[]; dryRun?: boolean; name?: string }required
Returns
Promise<SchemaPlanResult>
{
"status": "applied",
"migration_version": "20261018111530412",
"reversible": true,
"created": [
"orders",
"order_items"
],
"altered": {},
"notes": [],
"digest": "orders(id uuid pk=gen_random_uuid(), customer_id uuid →customers cascade, status text!='pending' in(pending|paid|shipped), total numeric(12,2)!, created_at timestamptz!=now(), user_id uuid!=caller) check(total >= 0) rls:owner(user_id) idx(customer_id) idx(user_id)\norder_items(id uuid pk=gen_random_uuid(), order_id uuid →orders cascade, product_id uuid →products, qty int!, created_at timestamptz!=now()) uniq(order_id,product_id) check(qty > 0) idx(product_id)",
"version": "a41f0c2e9d77",
"verification": {
"ok": true,
"checks": [
{
"check": "table orders",
"ok": true
},
{
"check": "table order_items",
"ok": true
}
]
}
}sovaria.data.dryRunMigrations
Check several migrations the way they will be applied (what sov db migrations push --dry-run does): all run in order inside one transaction that is rolled back, so later ones see what earlier ones create.
sovaria.data.dryRunMigrations(
migrations: Array<{ name: string; upSql: string }>,
): Promise<MigrationSequenceResult>Up to 500 and 5 MB of SQL; failed.index is the first that fails. Nothing is kept.
Parameters
migrationsArray<{ name: string; upSql: string }>required
Returns
Promise<MigrationSequenceResult>
{
"status": "dry_run_ok",
"checked": 2,
"total": 2,
"duration_ms": 61
}