Skip to content
NordBaseDocs

Search the docs

Find a page or a section of the NordBase docs

Connect

Python library

The nordbase package for Python: client, t-string SQL, the builder, Consistency, Document Databases and errors.

The nordbase package wraps psycopg 3 and the official MongoDB driver. It adds what NordBase needs: reading NORDBASE_URL, choosing a Region, Consistency, parameter-only SQL and the Document guard.

Install

bash
pip install nordbase
# or
uv add nordbase

Create a client

python
from nordbase import connect

db = connect()

connect() reads NORDBASE_URL, or the key file at NORDBASE_KEY_FILE when the URL is not set. On first use it picks the Region to serve Reads from, using NORDBASE_REGION or the fastest Endpoint. See Connection URL.

Options:

OptionDefaultWhat it does
consistency"nearest""strong" sends every Read from this client to the Primary
sticky_after_write_ms2000After a Write, this client's Reads go to the Primary for this many milliseconds
python
primary = connect(consistency="strong", sticky_after_write_ms=2000)

Create one client per process and reuse it. It holds a connection pool.

SQL

On Python 3.14 or newer, pass a t-string. Every {value} becomes a bind parameter, never SQL text.

python
from nordbase import connect, sql

db = connect()

customer_id = 1042
orders = db.sql(t"""
    select id, total, status
    from orders
    where customer_id = {customer_id}
    order by created_at desc
    limit 20
""")

On older Python, write named placeholders and pass the values as keyword arguments. The library parses the placeholders itself and never calls str.format:

python
orders = db.sql(
    "select id, total, status from orders where customer_id = {customer_id} order by created_at desc limit 20",
    customer_id=customer_id,
)

There the library cannot tell an f-string from a plain string, so never put f in front of a query. On Python 3.14 or newer an f-string is refused.

NeedWrite
A value{value}
A table or column name from a variable{sql.id(name)}
A list of values{sql.join(ids)}
An optional piece of SQLA nested fragment, sql(t"and status = {status}")
Raw text you wrote, with $1…$ndb.unsafe(text, params)
A multi-statement migration filedb.unsafe_script(text)

See Safe SQL.

The builder

from, in, is, not and or are reserved words in Python, so the builder spells them with a trailing underscore. A query runs when you call .execute().

python
latest = (
    db.from_("orders")
    .select("id, total, status")
    .eq("customer_id", 1042)
    .order("created_at", desc=True)
    .limit(20)
    .execute()
)

[created] = (
    db.from_("orders")
    .insert({"customer_id": 1042, "total": "3480.00", "status": "pending"})
    .returning("id")
    .execute()
)
db.from_("orders").update({"status": "paid"}).eq("id", created["id"]).execute()
db.from_("customers").upsert(rows, on_conflict="email").execute()

Rows are validated before sending, with Pydantic models. uv run nordbase gen types writes them from your live Database. See The builder.

Transactions

How a transaction behaves on NordBase is fixed:

  • A transaction that contains a Write runs on the Primary as a whole.
  • A transaction started read-only may use a Replica.
  • On port 5432, session state lasts for one transaction: use set local, not set.

The transaction API in the Python library is coming soon, and so is an async client. Until they are documented here, run a transaction with psycopg or your ORM over the same NORDBASE_URL; the Router applies the same rules.

Consistency

python
db = connect()                            # Reads from the nearest Instance
primary = connect(consistency="strong")   # Reads from the Primary

[account] = primary.sql(t"select balance from accounts where id = {account_id}")

After a Write, a client's own Reads go to the Primary for sticky_after_write_ms. Choosing Consistency for a single call is part of the library contract; its exact form is coming soon. See Replicas and Consistency.

Document Databases

The library wraps the official pymongo driver and adds the operator-injection guard: a value that arrives as a plain dict with a $ key is refused with UnsafeFilterError, and operators are written with helpers.

python
from nordbase import op

query = {"status": "paid", "total": op.gt(100)}

How you create the Document client, and the Python name of the in helper, are coming soon. Until then, connect with the official driver and check the types of request fields yourself before they reach a filter:

python
import os
from pymongo import MongoClient

client = MongoClient(os.environ["NORDBASE_URL"])
orders = client["shop"]["orders"]

number = str(payload["number"])  # a string, never a dict
order = orders.find_one({"number": number})

See Document Databases.

Errors

Import the module rather than the error names: PermissionError, TimeoutError and ConnectionError share their names with Python built-ins. A short alias keeps the names apart:

python
import nordbase as tk

db = tk.connect()

try:
    db.sql(t"insert into orders (number, customer_id, total) values ({number}, {customer_id}, {total})")
except tk.ReadOnlyLockError:
    ...  # Storage is full: show the order form as read-only and alert the team
except tk.PermissionError:
    ...  # The Credential may not write here: check nordbase.whoami()
except tk.ConnectionError:
    ...  # Unreachable after retries; the message says if the Write may have been applied
ErrorWhen
AuthenticationErrorWrong, revoked or expired Credential
PermissionErrorNot allowed by the Permission set
ReadOnlyLockErrorStorage is full; Writes are refused
TooManyConnectionsErrorEvery connection your Plan allows is in use
TimeoutErrorA statement ran over 30 seconds on port 5432
ConnectionErrorUnreachable after retries
UnsafeFilterErrorA Document filter or update contained an operator as data

Reads and transactions that never reached the Database are retried for up to 30 seconds. A Write whose outcome is unknown is never retried. See Errors.