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.
Use it from your language
Section titled “Use it from your language”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.2import 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())[{'id': 1, 'name': 'planner'}]
readynpm install @particledb/sdknpm @particledb/sdk 0.2.1, ES moduleimport { ParticleDB } from '@particledb/sdk';
const db = await ParticleDB.connect(); // localhost:7173
await db.execute('CREATE TABLE agents (id BIGINT PRIMARY KEY, name TEXT)');
await db.execute('INSERT INTO agents VALUES ($1, $2)', [1, 'planner']);
console.log(await db.queryOne('SELECT id, name FROM agents WHERE id = $1', [1]));
await db.kv.set('agent:1:status', 'ready');
console.log(await db.kv.get('agent:1:status'));
await db.close();{ id: 1, name: 'planner' }
readyimplementation("ai.particledb:particledb-java-sdk:1.1.3")Gradle, from Maven Centralvar db = ParticleDB.connect(); // localhost:7173
db.execute("CREATE TABLE agents (id BIGINT PRIMARY KEY, name TEXT)");
db.execute("INSERT INTO agents VALUES (?, ?)", 1L, "planner");
System.out.println(db.queryOne("SELECT id, name FROM agents WHERE id = ?", 1L));
db.kv().set("agent:1:status", "ready");
System.out.println(db.kv().get("agent:1:status"));Row{id=1, name=planner}
readygo get github.com/particledb-ai/particledb-go@v0.2.2Go 1.26.10+ctx := context.Background()
db, _ := particledb.NewPool(ctx, "") // localhost:7173
db.Exec(ctx, "CREATE TABLE agents (id BIGINT PRIMARY KEY, name TEXT)")
db.Exec(ctx, "INSERT INTO agents VALUES ($1, $2)", 1, "planner")
var name string
db.QueryRow(ctx, "SELECT name FROM agents WHERE id = $1", 1).Scan(&name)
db.KVSet(ctx, []byte("agent:1:status"), []byte("ready"))
status, _ := db.KVGet(ctx, []byte("agent:1:status"))
fmt.Println(name, string(status))planner readycargo add particledb-sdkcrates.io particledb-sdk 0.2.1let db = ParticleDB::connect(Config::default())?; // localhost:7173
db.execute("CREATE TABLE agents (id BIGINT PRIMARY KEY, name TEXT)", &[])?;
db.execute("INSERT INTO agents VALUES ($1, $2)", &[Value::Int64(1), Value::String("planner".into())])?;
let row = db.query_one("SELECT name FROM agents WHERE id = $1", &[Value::Int64(1)])?.unwrap();
println!("{}", row.get_by_name::<String>("name")?);
db.kv().set("agent:1:status", "ready")?;
println!("{:?}", db.kv().get("agent:1:status")?);planner
Some("ready")particledb cliSQL client included with the serverCREATE TABLE agents (id BIGINT PRIMARY KEY, name TEXT);
INSERT INTO agents VALUES (1, 'planner');
SELECT id, name FROM agents WHERE id = 1;
SELECT KV_SET('agent:1:status', 'ready');
SELECT KV_GET('agent:1:status');1|planner
OK
readyCreate and populate a table
Section titled “Create and populate a table”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');Read only the records you need
Section titled “Read only the records you need”SELECT id, titleFROM work_itemsWHERE status = 'pending'ORDER BY id;Use bound parameters for values supplied by users. The placeholder syntax depends on the client; see your language guide.
Commit related changes together
Section titled “Commit related changes together”From a client, the transaction helper commits when the block finishes and rolls back on an error:
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"))[{'id': 1, 'balance': 70}, {'id': 2, 'balance': 30}]await db.execute('CREATE TABLE accounts (id BIGINT PRIMARY KEY, balance BIGINT)');
await db.execute('INSERT INTO accounts VALUES (1, 100), (2, 0)');
await db.transaction(async tx => { // commits on return, rolls back on throw
await tx.execute('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [30, 1]);
await tx.execute('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [30, 2]);
});
console.log((await db.query('SELECT id, balance FROM accounts ORDER BY id')).rows);[ { id: 1, balance: 70 }, { id: 2, balance: 30 } ]db.execute("CREATE TABLE accounts (id BIGINT PRIMARY KEY, balance BIGINT)");
db.execute("INSERT INTO accounts VALUES (1, 100), (2, 0)");
db.transaction(tx -> { // returns normally: commit; throws: rollback
tx.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", 30L, 1L);
tx.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", 30L, 2L);
return null;
});
System.out.println(db.query("SELECT id, balance FROM accounts ORDER BY id").getRows());[Row{id=1, balance=70}, Row{id=2, balance=30}]db.Exec(ctx, "CREATE TABLE accounts (id BIGINT PRIMARY KEY, balance BIGINT)")
db.Exec(ctx, "INSERT INTO accounts VALUES (1, 100), (2, 0)")
err := particledb.BeginFunc(ctx, db, particledb.TxOptions{}, func(tx *particledb.Tx) error {
if _, err := tx.Exec(ctx, "UPDATE accounts SET balance = balance - $1 WHERE id = $2", 30, 1); err != nil {
return err // an error rolls back
}
_, err := tx.Exec(ctx, "UPDATE accounts SET balance = balance + $1 WHERE id = $2", 30, 2)
return err // nil commits
})
rows, _ := db.Query(ctx, "SELECT id, balance FROM accounts ORDER BY id")
balances, _ := particledb.CollectRows(rows, particledb.RowToMap)
fmt.Println(balances, err)[map[balance:70 id:1] map[balance:30 id:2]] <nil>db.execute("CREATE TABLE accounts (id BIGINT PRIMARY KEY, balance BIGINT)", &[])?;
db.execute("INSERT INTO accounts VALUES (1, 100), (2, 0)", &[])?;
db.transaction(|tx| { // Ok commits, Err rolls back
tx.execute("UPDATE accounts SET balance = balance - 30 WHERE id = 1", &[])?;
tx.execute("UPDATE accounts SET balance = balance + 30 WHERE id = 2", &[])?;
Ok(())
})?;
for row in db.query("SELECT id, balance FROM accounts ORDER BY id", &[])?.rows {
println!("{:?}", row.values());
}[Int64(1), Int64(70)]
[Int64(2), Int64(30)]CREATE TABLE accounts (id BIGINT PRIMARY KEY, balance BIGINT);
INSERT INTO accounts VALUES (1, 100), (2, 0);
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;
SELECT id, balance FROM accounts ORDER BY id;1|70
2|30In 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.
Check the result
Section titled “Check the result”SELECT id, status FROM work_items ORDER BY id;The statuses are completed for record 1 and running for record 2.
Next steps
Section titled “Next steps”This site uses Google Analytics cookies to count visits. Privacy · License