Metadata-Version: 2.4
Name: spyddb
Version: 1.0.0
Summary: Python driver (SpydWire and HTTP/HTTPS, sync and asyncio) and ORM for SpydDB
Author: SpydDB Contributors
License-Expression: Apache-2.0
Project-URL: Homepage, https://gitlab.com/nayem.drmc/spyddb-sdk-python
Project-URL: Source, https://gitlab.com/nayem.drmc/spyddb-sdk-python
Project-URL: Docker, https://hub.docker.com/r/nayem7663/spyddb
Project-URL: Documentation, https://gitlab.com/spydotech-group/spyddb/-/blob/main/docs/PROTOCOL.md
Keywords: spyddb,database,driver,orm,spydwire,http
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Database
Classifier: Topic :: Database :: Front-Ends
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: numpy
Requires-Dist: numpy>=1.24; extra == "numpy"
Provides-Extra: arrow
Requires-Dist: pyarrow>=14.0; extra == "arrow"
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.2; extra == "langchain"
Provides-Extra: llamaindex
Requires-Dist: llama-index-core>=0.10; extra == "llamaindex"
Provides-Extra: ai
Requires-Dist: numpy>=1.24; extra == "ai"
Requires-Dist: pyarrow>=14.0; extra == "ai"
Provides-Extra: test
Requires-Dist: pytest<10,>=8; extra == "test"
Requires-Dist: numpy>=1.24; extra == "test"
Dynamic: license-file

# SpydDB Python driver and ORM

The official Python client for SpydDB. It has no runtime
dependencies: the frame layer, CRC-32C, SCRAM-SHA-256, TLS, the value codec,
the ORM, and migrations use only the standard library.

## Install

```sh
pip install spyddb
```

## Server Docker image

Run the SpydDB server container from Docker Hub ([`nayem7663/spyddb`](https://hub.docker.com/r/nayem7663/spyddb)):

```sh
docker pull nayem7663/spyddb:0.1.0
```

## Connect

```python
from spyddb import Client

with Client.connect(
    "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN"
) as client:
    result = client.execute(
        "users | where active == true | pick id, email | sort id | take 10"
    )
    for row in result.dicts:
        print(row)
```

SCRAM-SHA-256 is selected with `user` and `password` (or `password_env`)
instead of a token:

```python
client = Client.connect(
    "spydwire://db.internal:5433?user=alice&password_env=SPYD_PASSWORD"
    "&ca=/etc/spyd/ca.pem&server_name=db.internal"
)
```

Connection string parameters: `token`, `token_env`, `user`, `password`,
`password_env`, `ca`, `server_name`, `client_cert`, `client_key`, `tls`,
`timeout`, `connect_timeout`. Unknown parameters are refused. Plaintext is
only accepted by the server on a loopback address; supply `ca` (and the client
certificate for mTLS) elsewhere.

## Values

Parameters are positional (`$1`, `$2`, …) and may be written as Python values:

| Python | SpydWire |
| --- | --- |
| `None` | `"Null"` |
| `bool` | `{"Bool": ...}` |
| `int` | `{"U64": ...}` or `{"I64": ...}` |
| `float` | `{"F64": ...}` |
| `str` | `{"String": ...}` |
| `bytes` | `{"Bytes": [...]}` |
| `datetime` | `{"Timestamp": microseconds}` |
| `date` | `{"Date": days}` |
| `dict`, `list` | `{"Json": ...}` |
| `spyddb.Vector` | `{"Vector": [...]}` |
| `spyddb.GeoPoint` | `{"GeoPoint": {...}}` |
| `spyddb.Text`, `Float32`, `UInt`, `Int`, `EnumName` | forced variants |

Results are decoded to `int`, `float`, `str`, `bytes`, `datetime` (UTC),
`date`, `decimal.Decimal`, `list`, `dict`, `GeoPoint`, and the enum *variant
name* (resolved from the column type).

### Decimal parameters

The current SpydWire request decoder cannot carry `i128`, so a
`{"Decimal": ...}` parameter is rejected at the frame layer. Send the decimal
as text and cast it:

```python
client.execute(
    "orders | insert { id: $1, total: cast($2 as decimal(12, 2)) }",
    [1, "19.99"],
)
```

`spyddb.DecimalParam` carries the precision and scale for this purpose. The
ORM adds the cast automatically.

## Driver features

- **Sync + native `asyncio` (`AsyncClient`, `AsyncPool`)**: Zero external dependencies (`asyncio.open_connection` + stdlib `ssl`); same `SPD2` binary fast path with `SPD1` JSON compatibility, `TCP_NODELAY`, coalesced writes, and 64 KiB read buffering.
- `Client` / `AsyncClient`: serialized requests, `prepare()` / `execute_prepared()` / `close_prepared()` (with automatic re-prepare on DDL invalidation), `use_database()`, interactive transactions (`begin()`, `commit()`, `rollback()`, `transaction()`), query IDs, ping, and cancel.
- `Pool` / `AsyncPool`: bounded lazy pool (`asyncio.Semaphore` backpressure in `AsyncPool`), LIFO reuse, optional ping on checkout, discards broken connections.

## Async driver and ORM (`asyncio`)

```python
import asyncio
from decimal import Decimal
from spyddb import AsyncClient, AsyncPool
from spyddb.orm import AsyncDatabase, Bool, Model, String, UInt64

class User(Model):
    __collection__ = "users"
    id = UInt64(primary=True, auto_increment=True)
    email = String(160, unique=True, nullable=False)
    active = Bool(default=True)

async def main() -> None:
    async with AsyncDatabase.connect(
        "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN",
        models=[User],
    ) as db:
        await db.create_all()
        async with db.transaction():
            ada = await db.create(User, email="ada@example.test", active=True)

        rows = await db.query(User).where(User.active == True).order_by(User.id.asc()).all()
        print(ada.id, len(rows))

    # Raw async pool
    async with AsyncPool("spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN", max_size=16) as pool:
        res = await pool.execute("users | count")
        print(res.scalar())

asyncio.run(main())
```
- `Result`: `rows`, `dicts`, `first()`, `one()`, `scalar()`.
- Typed errors: `SpydAuthenticationError`, `SpydTypeError`,
  `SpydConstraintError`, `SpydConflictError`, `SpydPermissionError`,
  `SpydResourceError`, `SpydSchemaError`, `SpydCancelledError`, …
- `ConnectionOptions.parse` for `spydwire://` URLs.
- TLS 1.2/1.3 with a CA, SNI/server name, and optional client certificate.

## ORM

```python
from decimal import Decimal
from spyddb.orm import (
    Database, Model, UInt64, String, Decimal, Bool, Timestamp, Index,
)

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 = Decimal(12, 2, default=Decimal("0"))
    active = Bool(default=True)
    joined = Timestamp()

database = Database.connect(
    "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN",
    models=[User],
)
database.create_all()          # create collection + indexes
database.sync()                # additive changes; destructive needs a flag

user = User.create(email="ada@example.test", name="Ada")
user.balance = Decimal("12.50")
user.save()

adults = (
    User.where((User.active == True) & (User.name != ""))
    .order_by(User.name.asc())
    .limit(20)
    .all()
)
print(User.get(id=user.id), User.count())
print(
    User.query()
    .aggregate(sum(User.balance).as_("total"), count().as_("n"))
    .rows()
)
```

### Query builder

- Comparisons: `==`, `!=`, `<`, `<=`, `>`, `>=`; `None` becomes
  `is null` / `is not null`.
- `like`, `between`, `in_`, `not_in`, `is_null`, `is_not_null`.
- Boolean composition with `&`, `|`, `~`.
- Functions: `lower`, `upper`, `length`, `abs`, `round`, `coalesce`,
  `concat`, `contains`, `starts_with`, `ends_with`, `now`, and `func(name, …)`.
- Writes: `create`, `bulk_create`, `save`, `delete`, `upsert`.
- Query writes: `query.update(...)`, `query.delete()`.
- Aggregates: `count`, `sum`, `avg`, `min`, `max`, `.group_by(...)`,
  `.aggregate(...)`, `.rows()`.
- Paging: `.limit()`, `.offset()`, `.iterate(batch_size=...)`.
- `.explain()` for the plan.

SpydQL has no `LIMIT`, `OFFSET`, `SELECT *`, or `HAVING`; the builder emits
`take`, `skip`, explicit `pick`, and `where` after aggregation.

### Schema and migrations

The server has no schema introspection over SpydWire. The ORM records the
definition it applied in `_spyd_orm_schema` and compares that record with the
models. `create_all()` is idempotent: because it cannot inspect an existing
collection, a collection that has no record is adopted as matching the model
(the `if not exists` creation is a no-op and indexes are added). `sync()` applies additive changes (`add field`, `create index`).
Destructive changes (drop/change a field, drop an index, change the primary
key, change the storage layout) are refused unless
`allow_destructive=True`, and a layout change is always refused because it
needs a new collection and a copy.

```python
from spyddb.orm import Migration

database.migrate([
    Migration(
        "0001_create_users",
        ["create collection users { id: u64 primary, name: string(80) }"],
        ["drop collection if exists users"],
    ),
])
```

Applied migrations are recorded in `_spyd_orm_migrations` with a SHA-256
checksum; changing a migration after it ran is refused. Keep each migration small.

## Not supported by the server yet

- Schema introspection and `DESCRIBE`.
- Server-side pagination of one result: a response must fit the 8 MiB frame.
  Use `take`/`skip` and `iterate`.
- `pick *`.
- A write with `returning` carries values but **no column metadata**; use the
  row tuples or the ORM (it maps them by model field order).
- `cancel` is per connection. A synchronous caller cannot cancel its own
  in-flight statement; operator-side `ServerHandle::cancel` is the reliable
  path.
- Decimal parameters, as described above.
- Column type changes; drop and re-add creates a new field.

## Tests

```sh
python3 -m venv .venv
. .venv/bin/activate
python -m pip install '.[test]' build
python -m pytest
python -m build
```

The integration tests start the executable supplied by `SPYD_SERVER_BIN` on a loopback port
with a temporary data directory, token credentials, and a generated SCRAM
verifier. These tests skip if the server binary is unavailable.
The asyncio live test uses the server set by `SPYDDB_ADDRESS` and the
`SPYDDB_TOKEN`, `SPYDDB_TLS`, `SPYDDB_CA`, and `SPYDDB_SERVER_NAME`
connection variables. Point it at a disposable test database because it
creates and drops collections, including ORM metadata.

## Source

This repository was split from [`clients/python`](https://gitlab.com/spydotech-group/spyddb/-/tree/29b59618e60ac5a3205bc6650106a8b714f54cbc/clients/python) at SpydDB commit `29b59618`.

## Releasing

1. Set `version` in `pyproject.toml` to the new version and merge to `main`.
2. Tag that commit `vX.Y.Z` (the same version) and push the tag. Only maintainers can create `v*` tags.
3. The tag pipeline runs the checks, then publishes to PyPI (`spyddb`). It fails before publishing if the tag and the version differ.
