Skip to content

Custom Backends and Raw SQL

Two jobs live on this page: keeping your bot's own data beside what CascadeUI saves, and writing a backend of your own. A bot that saves only its panels and slots needs neither, since the built-in backends cover those.

Your Own Data

Your data Where it goes
Unrelated to the panels: orders, accounts, match history a database of your own (Pattern A)
Small values you look up by a key the backend's key-value table (Pattern B)
Rows you query, in the database CascadeUI already uses tables of your own, through raw SQL (Pattern C)

Patterns B and C use the backend persistence was set up with:

from cascadeui import get_store

backend = get_store().persistence_manager.application.backend

It is None when the application namespace is turned off (application=ApplicationPersistence(backend=None)).

Open your own connection and keep your own schema. Your tables and their upgrades stay yours, and nothing the library does at a start or an upgrade reaches them.

import json

await backend.kv_write("ticket_threads", "guild:42:thread:99", json.dumps(data).encode())
raw = await backend.kv_read("ticket_threads", "guild:42:thread:99")  # bytes, or None
async for key, value in backend.kv_scan("ticket_threads", prefix="guild:42:"):
    ...

Values are bytes, and the first argument is a namespace name of your choosing: the library never reads or writes this table. All three built-in backends have it, so the same code runs on each. A write goes straight to the database, outside the store: it is not batched, not undone, and no subscriber hears it.

Pattern C: Raw SQL

SQLite and PostgreSQL run SQL you write, on tables you create. Code that may meet InMemoryBackend checks first:

from cascadeui import Capability

if Capability.RAW_SQL not in backend.capabilities:
    raise RuntimeError("this backend runs no SQL")

The engines write parameters differently, and backend.placeholder_style says which: "qmark" (?) on SQLite, "numeric" ($1, $2) on PostgreSQL.

import time

ph = backend.placeholder_style

await backend.execute("""
    CREATE TABLE IF NOT EXISTS tickets (
        id INTEGER PRIMARY KEY,
        user_id BIGINT NOT NULL,
        content TEXT NOT NULL,
        created_at BIGINT NOT NULL
    )
""")
await backend.execute(
    "INSERT INTO tickets VALUES (?, ?, ?, ?)" if ph == "qmark"
    else "INSERT INTO tickets VALUES ($1, $2, $3, $4)",
    1, user_id, content, int(time.time()),
)
rows = await backend.fetch(
    "SELECT * FROM tickets WHERE user_id = ?" if ph == "qmark"
    else "SELECT * FROM tickets WHERE user_id = $1",
    user_id,
)

fetch() returns a list of dicts and fetch_one() one dict or None; a statement that writes, such as INSERT ... RETURNING id, is committed by the time either returns. executemany(sql, rows) runs the statement once for each tuple in rows.

The SQL reaches the database as written, untranslated. Code meant for both engines keeps to what they share (INTEGER, BIGINT, TEXT, the usual comparisons, and functions such as COUNT and COALESCE) and stores a time as an epoch integer, since the date functions differ. Code for one engine uses that engine's features freely.

Transactions

async with backend.transaction():
    await backend.execute(...)
    await backend.execute(...)
# Both committed, or, when the block raised, neither.

A transaction() opened inside another is a savepoint: when the inner block raises, only its own statements are rolled back, and the outer block carries on.

What joins a transaction depends on the engine, because SQLite has one connection and PostgreSQL a pool:

Diagram: one transaction that raises, on each engine, and what became of each write. SQLite has one connection, and everything goes through it: the block's own SQL and a task the block starts are rolled back, a row_select made in the block sees the block's rows, another task's SQL waits for the block and is then kept, and a kv_write or row_upsert made in the block raises RuntimeError. PostgreSQL has a pool: the block holds one connection, where its own SQL and the task it starts are rolled back. Another task's SQL runs at once on a second connection and is kept. A kv_write or row_upsert made in the block commits on a third and is kept, and a row_select there does not see the block's rows. On both, another backend's SQL is its own and is kept.

In or beside a transaction() block SQLite PostgreSQL
the block's own raw SQL in it in it
a task the block starts, while the block is open in it in it
another task's raw SQL waits for the block, then runs on its own runs at once, on its own
another backend's raw SQL on its own on its own
row_upsert(), kv_write(), and the other writes, from the block raise RuntimeError commit at once, on their own
row_select(), kv_read(), and the other reads, from the block see the block's rows do not see them

A write on its own is kept when the block rolls back. A task the block starts cannot open a transaction() of its own while the block is open (RuntimeError), and on PostgreSQL the block and that task share one connection, which runs one statement at a time: await the task from the block rather than running statements in both at once. Keep a block short. It holds its connection until it ends, and on SQLite every other command's database calls wait for it.

When Raw SQL Is the Wrong Tool

The panel and slot tables (cascadeui_persistent_views, cascadeui_application_slots) belong to the library. It holds their rows in memory while the bot runs, so a row changed past it is not seen until the next start, and the library's next save of that row writes over the change. Read and change them through persistence's own calls (Saving Data, Migrations, Pruning, and Observability).

InMemoryBackend runs no SQL (its raw-SQL methods raise NotImplementedError), so a test of code that uses Pattern C runs against a SQLite file in a temporary folder, or a PostgreSQL container.

Writing a Backend

A backend is any class with the methods its capabilities name. It needs no base class:

from cascadeui import Capability


class MyBackend:
    capabilities = Capability.RELATIONAL | Capability.SCHEMA_META | Capability.OPEN_ROWS

    async def initialize(self) -> None: ...
    async def close(self) -> None: ...

    async def row_upsert(self, namespace, row, key_columns): ...
    async def row_select(self, namespace, where=None): ...
    async def row_delete(self, namespace, where): ...

    async def get_schema_version(self, table): ...
    async def set_schema_version(self, table, version): ...

That is every method the library calls for these three flags, and the backend is passed as any other is: PersistenceMiddleware(backend=MyBackend()). A namespace names one of the library's tables, and a row is a dict of column names to values. row_upsert() replaces the row whose key_columns match, and row_select() and row_delete() take the rows whose columns equal every value in where (row_select() with no where takes all).

These methods come from the PersistenceBackend Protocol, imported from cascadeui. It is runtime-checkable, but isinstance() answers True only for a class with every member, the raw-SQL ones included, and the library never asks.

The library relies on five things beyond the methods' shapes. InMemoryBackend does all five and is the shortest backend to read:

  1. row_upsert() keeps a copy of the row it is given, and row_select() returns copies: changing either dict afterwards changes nothing stored.
  2. row_delete_where_lt() never deletes a row whose column is None, as SQL's NULL < value is never true.
  3. kv_scan() reads its rows before it yields the first, so a write made inside the loop neither raises nor waits.
  4. row_delete() matches a where built from the values row_select() returned (the library deletes a panel's row by the key and message ids it read), and a None in a where matches no row in either call, as SQL's = NULL never does.
  5. initialize() works again after close(): a bot closed and started again in one process reopens the backend it had.

The repository's tests/test_backends.py runs these and the rest of the Protocol on each built-in backend through its backend fixture, and a branch there for your class runs them on yours.

Persistence reads back a saved slot another process changed only on PostgresBackend and its subclasses, which hear PostgreSQL's notifications. A custom backend, including one that wraps a PostgresBackend, serves the copy each process read at its start, as SQLite does: with several processes on one database, a later save of a slot writes over another process's change (Several Processes).

Capability Flags

Flag Methods The library needs it
RELATIONAL row_upsert, row_select, row_delete always
SCHEMA_META get_schema_version, set_schema_version always
TTL_INDEX row_delete_where_lt when a saved slot's SlotPolicy has ttl_days, in slots= or register_slot_policy()
KV kv_read, kv_write, kv_delete, kv_scan never: only your code calls them (Pattern B)
RAW_SQL execute, fetch, fetch_one, executemany, transaction, placeholder_style for Pattern C, or an upgrade
OPEN_ROWS none: a promise about rows for an upgrade

A backend missing a flag the library needs is refused with PersistenceConfigError naming the flag, before any of its methods runs: when RegistryPersistence(backend=...) or ApplicationPersistence(backend=...) is built, or, for PersistenceMiddleware(backend=...), when setup_middleware() runs. InMemoryBackend declares every flag but RAW_SQL, and the two SQL backends every flag but OPEN_ROWS. An optional row_upsert_many(namespace, rows, key_columns) saves a batch in one call. Without it the library calls row_upsert() once per row.

Upgrades

A release now and then adds a column to a table the library owns: the panels table's version 2 added first_unreachable_at. At a start, an empty table is recorded at the current version and needs nothing. A table an older release filled is brought up to date, and the backend says how.

OPEN_ROWS promises that row_upsert() keeps columns it has not seen before and row_select() returns them, with None for one a row lacks, so the new column needs no statement. RAW_SQL lets the library add it with ALTER TABLE. A backend declaring neither stops the start with PersistenceConfigError naming both.

A backend that creates fixed columns creates the current set, which the SQLite statements in cascadeui.persistence.schema list (DDL_PERSISTENT_VIEWS, DDL_APPLICATION_SLOTS).

The library's own SQL is written for SQLite and PostgreSQL. On a RAW_SQL backend whose placeholder_style is neither "qmark" nor "numeric", it sends only that ALTER TABLE ... ADD COLUMN and a SELECT that looks for the column first, writes everything else through row_upsert(), and leaves tables under older names as they are.