Skip to content
ParticleDB
Release candidateParticleDB 1.1.19-rc.17 is not yet GA or ready for production data.Release status →

Store application data

The SQL sections below use a small work queue stored as an ordinary SQL table. Run them in a connected SQL client or the SQL editor.

Connect, write a row, read it back and use a key on the same connection. Start a local server with the quickstart command first; the clients connect to localhost:7173 by default. See your language guide for authentication, pooling and error handling.

pip install particledbPyPI particledb 0.2.2

import particledb

db = particledb.connect()  # localhost:7173
db.execute("CREATE TABLE agents (id BIGINT PRIMARY KEY, name TEXT)")
db.execute("INSERT INTO agents VALUES ($1, $2)", [1, "planner"])
print(db.query("SELECT id, name FROM agents WHERE id = $1", [1]))
db.kv_set("agent:1:status", "ready")
print(db.kv_get("agent:1:status").decode())
Output
[{'id': 1, 'name': 'planner'}]
ready
CREATE TABLE work_items (
id BIGINT PRIMARY KEY,
title TEXT NOT NULL,
status TEXT NOT NULL
);
INSERT INTO work_items VALUES
(1, 'Review request', 'pending'),
(2, 'Send response', 'pending');
SELECT id, title
FROM work_items
WHERE status = 'pending'
ORDER BY id;

Use bound parameters for values supplied by users. The placeholder syntax depends on the client; see your language guide.

From a client, the transaction helper commits when the block finishes and rolls back on an error:

Uses db from the connect example.

db.execute("CREATE TABLE accounts (id BIGINT PRIMARY KEY, balance BIGINT)")
db.execute("INSERT INTO accounts VALUES (1, 100), (2, 0)")
with db.transaction() as tx:  # commits on exit, rolls back on error
    tx.execute("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [30, 1])
    tx.execute("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [30, 2])
print(db.query("SELECT id, balance FROM accounts ORDER BY id"))
Output
[{'id': 1, 'balance': 70}, {'id': 2, 'balance': 30}]

In SQL, use one connection for the transaction:

BEGIN;
UPDATE work_items SET status = 'completed' WHERE id = 1;
UPDATE work_items SET status = 'running' WHERE id = 2;
COMMIT;

If a statement fails, roll back before reusing the connection. Retry from BEGIN when a transaction fails with a retryable conflict.

SELECT id, status FROM work_items ORDER BY id;

The statuses are completed for record 1 and running for record 2.

Transactions · Data types · Indexes and queries