Python SDK & ORM
Zero-dependency sync & asyncio drivers, typed Vector/GeoPoint/DecimalParam values, Model ORM, and migrations.
2 min read Official SDKs (12 Languages)
The official Python driver and declarative ORM for SpydDB requires zero external runtime dependencies: SPD2 binary framing, CRC-32C checksums, SCRAM-SHA-256, TLS 1.2/1.3, connection pooling, asyncio support, schema diffing, and migrations are all implemented cleanly in standard-library Python.
1. Installation#
sh
pip install spyddb==0.1.22. Connecting (Token, SCRAM, TLS & mTLS)#
Synchronous Client & TLS Context Manager#
python
import os
from spyddb import Client
# Bearer token from environment with TLS CA verification
with Client.connect(
"spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN&tls=1&ca=docker/tls/ca.crt&server_name=localhost"
) as client:
res = client.execute(
"users | where active == $1 | pick id, email | sort id | take 10",
[True],
)
for row in res.dicts:
print(row["id"], row["email"])SCRAM-SHA-256 & Mutual TLS (mTLS)#
python
from spyddb import Client
with Client.connect(
"spydwire://db.internal:5433/analytics"
"?user=alice&password_env=SPYD_PASSWORD"
"&ca=/etc/spyd/ca.crt&server_name=db.internal"
"&client_cert=/etc/spyd/client.crt&client_key=/etc/spyd/client.key"
) as client:
client.ping()
print(client.execute("system | stats catalog").dicts)3. Parameter Binding & Typed Values#
Positional parameters ($1, $2, ...) preserve exact engine types across SPD2 binary encoding:
| Python Type | SpydDB Wire Type | Helper Class |
|---|---|---|
None | Null | — |
bool | Bool | — |
int | U64 / I64 | UInt(n, bits), Int(n, bits) |
float | F64 | Float32(x) |
str | String | Text(s) |
bytes | Bytes | — |
datetime / date | Timestamp / Date | — |
dict / list | Json | — |
spyddb.Vector | Vector | Vector([0.1, 0.2, 0.3]) |
spyddb.GeoPoint | GeoPoint | GeoPoint(lat=37.77, lng=-122.41) |
spyddb.EnumName | Enum | EnumName("paid") |
decimal.Decimal | Decimal (cast string on write) | DecimalParam("19.99", precision=12, scale=2) |
python
from datetime import datetime, timezone
from spyddb import Client, GeoPoint, Vector
with Client.connect("spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN") as client:
# Exact Decimal parameter binding
client.execute(
"orders | insert { id: $1, total: cast($2 as decimal(12, 2)), placed_at: $3 }",
[101, "19.99", datetime.now(timezone.utc)],
)
# Vector similarity + R-Tree geospatial query
hits = client.execute(
"places | where nearest(embedding, $1, 5) and geo_within(location, 37.6, -122.6, 37.9, -122.2) | pick id, name",
[Vector([0.12, 0.85, -0.33, 0.44])],
)
print(hits.dicts)4. Prepared Statements, Database Switching & Transactions#
python
from spyddb import Client, SpydConflictError
with Client.connect("spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN") as client:
client.use_database("default")
# Prepare once and execute repeatedly
stmt = client.prepare("orders | where status == $1 | pick id, total | take 25")
try:
paid = client.execute_prepared(stmt, ["paid"])
pending = client.execute_prepared(stmt, ["pending"])
print("Paid:", len(paid.rows), "Pending:", len(pending.rows))
finally:
client.close_prepared(stmt)
# Interactive ACID transaction with automatic commit/rollback
try:
with client.transaction():
client.execute("accounts | where id == $1 | set { balance: balance_delta(balance, 0, 100000, -50) }", [1])
client.execute("accounts | where id == $1 | set { balance: balance_delta(balance, 0, 100000, +50) }", [2])
except SpydConflictError:
print("Serialization conflict detected; safe to retry transaction.")5. Thread-Safe Connection Pool (Pool)#
python
from spyddb import Pool
pool = Pool(
"spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN&tls=1&ca=docker/tls/ca.crt",
max_size=16,
)
try:
with pool.acquire() as client:
res = client.execute("orders | agg count() as n")
print("Total orders:", res.scalar())
finally:
pool.close()6. Async Driver & Async ORM (asyncio)#
python
import asyncio
from decimal import Decimal
from spyddb import AsyncPool
from spyddb.orm import AsyncDatabase, Bool, Decimal as DecimalField, Model, String, UInt64
class Account(Model):
__collection__ = "accounts"
id = UInt64(primary=True, auto_increment=True)
email = String(160, unique=True, nullable=False)
balance = DecimalField(12, 2, default=Decimal("0.00"))
active = Bool(default=True)
async def main() -> None:
dsn = "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN"
# Async ORM
async with AsyncDatabase.connect(dsn, models=[Account]) as db:
await db.create_all()
async with db.transaction():
ada = await db.create(Account, email="ada@example.test", balance=Decimal("250.00"))
rows = (
await db.query(Account)
.where((Account.active == True) & (Account.balance >= Decimal("100.00")))
.order_by(Account.id.asc())
.limit(20)
.all()
)
print("Found:", len(rows), "Created ID:", ada.id)
# Raw bounded AsyncPool with semaphore backpressure
async with AsyncPool(dsn, max_size=16) as pool:
res = await pool.execute("accounts | agg count() as n")
print("Pool scalar:", res.scalar())
asyncio.run(main())7. Sync Declarative ORM, Aggregations & Migrations#
python
from decimal import Decimal
from spyddb.orm import (
Bool, Database, Decimal as DecimalField, Index, Migration, Model,
String, Timestamp, UInt64, count, sum,
)
class User(Model):
__collection__ = "users"
id = UInt64(primary=True, auto_increment=True)
email = String(160, unique=True, nullable=False)
name = String(80, nullable=False)
balance = DecimalField(12, 2, default=Decimal("0.00"))
active = Bool(default=True)
joined = Timestamp()
db = Database.connect("spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN", models=[User])
# Idempotent schema creation + additive evolution
db.create_all()
db.sync()
# CRUD & updates
user = User.create(email="grace@example.test", name="Grace Hopper")
user.balance = Decimal("42.50")
user.save()
# Composable query builder
active_users = (
User.where((User.active == True) & User.name.like("%Hopper%"))
.order_by(User.id.desc())
.limit(20)
.all()
)
# Server-side aggregates
stats = User.query().aggregate(sum(User.balance).as_("total"), count().as_("n")).rows()
# Batch keyset/cursor iteration & EXPLAIN plan
for batch in User.query().iterate(batch_size=500):
process(batch)
print(User.where(User.active == True).explain())
# Versioned checksummed migrations
db.migrate([
Migration(
"0001_add_region_index",
["alter collection users add field region string(32)"],
["alter collection users drop field region"],
),
])8. Typed Exception Reference#
Handle protocol, validation, security, and concurrency errors cleanly using spyddb subclasses of SpydError:
SpydConnectionError,SpydTimeoutError,SpydProtocolErrorSpydAuthenticationError,SpydPermissionError(RBAC / policy denial)SpydConflictError(SSI serialization conflict40001— safe to retry transaction)SpydConstraintError(unique, foreign key, exclusion, check violations)SpydSchemaError,SpydTypeError,SpydValueErrorSpydNoResultError(.one()on empty),SpydMultipleResultsError(.one()> 1 row)SpydResourceError,SpydCancelledError,SpydQueryError