Metadata-Version: 2.4
Name: Pyzzel
Version: 1.0.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: psycopg[binary,pool]>=3.2
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Dynamic: license-file

<p align="center">
  <h1 align="center">Pyzzel</h1>
  <p align="center">A small, explicit PostgreSQL ORM for Python.</p>
  <p align="center">
    <a href="https://pypi.org/project/Pyzzel/"><img src="https://img.shields.io/pypi/v/Pyzzel" alt="PyPI version"></a>
    <a href="https://pypi.org/project/Pyzzel/"><img src="https://img.shields.io/pypi/pyversions/Pyzzel" alt="Python versions"></a>
    <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT license"></a>
  </p>
</p>

Pyzzel is a lightweight Python ORM for PostgreSQL. It combines an Active Record model interface with explicit queries, short-lived pooled connections, and visible transaction boundaries.

Pyzzel maps Python model classes to PostgreSQL tables and provides an explicit query builder, pooled connections, transactions, and optional SQL migrations. It is designed around visible database operations: reads return rows unless you explicitly request model objects, and relations load only when requested.

> **Database support:** PostgreSQL only. Pyzzel requires Python 3.10 or newer.

## Contents

- [Why Pyzzel](#why-pyzzel)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Models and types](#models-and-types)
- [CRUD](#crud)
- [Queries](#queries)
- [Relationships and joins](#relationships-and-joins)
- [Bulk and conditional writes](#bulk-and-conditional-writes)
- [Connections and transactions](#connections-and-transactions)
- [Migrations](#migrations)
- [Pyzzel v1](#pyzzel-v1)
- [Performance and benchmarks](#performance-and-benchmarks)
- [Development](#development)
- [License](#license)

## Why Pyzzel

- **Explicit database work:** `select()` builds a query and runs only when you call `.all()`, `.first()`, or `.count()`.
- **PostgreSQL-native:** SQL generation, types, transactions, and migrations target PostgreSQL.
- **Small runtime dependency set:** Psycopg 3 and its pool are the runtime dependencies; pytest is an optional development dependency.
- **Controlled writes:** model updates track changed fields and use a managed version column for optimistic concurrency.
- **No hidden relation queries:** use `.with_(...)` to request one-level relationship loading explicitly.

## Installation

Install from PyPI:

```console
python -m pip install Pyzzel
```

Or install a checkout with development dependencies:

```console
python -m pip install -e ".[dev]"
```

Pyzzel requires Python 3.10+ and PostgreSQL. The package declares `psycopg[binary,pool]>=3.2`; pytest is included in the `dev` extra. PostgreSQL server minimum version is not declared in package metadata.

## Quick start

Create a model module, for example `models.py`:

```python
from pyzzel import Base, Column, Integer, String


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String(120), nullable=False)
    email = Column(String(255), unique=True)
```

Connect, create the registered tables, and use the model. `create_tables()` creates missing tables; it does not evolve existing schemas. For ongoing schema changes, use the migration workflow below.

```python
import os

from pyzzel import Base, connect, disconnect
from models import User

connect(os.environ["PYZZEL_DATABASE_URL"])
try:
    Base.create_tables()

    user = User.create(name="Ada", email="ada@example.com")
    loaded = User.get(user.id)
    print(loaded.name)

    loaded.name = "Ada Lovelace"
    loaded.save()
    loaded.delete()
finally:
    disconnect()
```

The pool is process-wide and supports one configured database per process. Close it with `disconnect()` during application shutdown.

## Models and types

Concrete models inherit from `Base`, define a unique `__tablename__`, and declare exactly one integer primary key. Supported column types include:

| Pyzzel type | PostgreSQL representation |
| --- | --- |
| `SmallInteger`, `Integer`, `BigInteger` | `SMALLINT`, `INTEGER`, `BIGINT` |
| `Float` | `DOUBLE PRECISION` |
| `Numeric(p, s)` | `NUMERIC` |
| `String(n)` / `String` | `VARCHAR(n)` / `TEXT` |
| `Boolean` | `BOOLEAN` |
| `Date`, `Time`, `DateTime` | `DATE`, `TIME`, `TIMESTAMP` or `TIMESTAMPTZ` |
| `UUID` | `UUID` |
| `JSON` | `JSONB` |
| `LargeBinary` | `BYTEA` |

`default=` is a Python-side default. Use a callable such as `default=list` for mutable defaults. `server_default=` inserts a trusted SQL expression into table DDL; only use expressions you control. Each table also has a hidden `version` column managed by Pyzzel.

```python
from pyzzel import Base, Column, Integer, Numeric, String


class Product(Base):
    __tablename__ = "products"

    id = Column(Integer, primary_key=True)
    name = Column(String(120), nullable=False)
    price = Column(Numeric(10, 2), nullable=False)
```

Changes to model fields are tracked for `save()`. Assigning the loaded value again clears a pending change. In-place mutation of JSON values is not detected; assign a replacement value instead.

## CRUD

```python
product = Product.create(name="Notebook", price=4.50)
same_product = Product.get(product.id)  # model instance or None

same_product.price = 5.00
same_product.save()                    # writes tracked fields
same_product.delete()
```

`Model.get(primary_key)` accepts a primary key or conditions. Multiple conditions are combined with AND. An update or delete against a stale version raises `VersionConflict`; if the row was removed, Pyzzel raises `NotFound`. PostgreSQL constraint errors are surfaced as Psycopg errors.

For SQL not represented by the ORM, `Base.execute(sql, params)` executes parameterized SQL and returns rows as tuples:

```python
rows = Base.execute(
    'SELECT "id", "name" FROM "users" WHERE "email" = %s',
    ("ada@example.com",),
)
```

Keep values in the parameter sequence; do not interpolate them into SQL strings.

## Queries

`select()` returns an immutable query builder. It executes only when evaluated:

```python
from pyzzel import and_

rows = (
    User.select(User.name, User.email)
    .where(and_(User.name != "", User.email.is_not_null()))
    .order_by(User.name)
    .limit(50)
    .all()
)
```

With no selected columns, `select()` returns the model's user-defined columns as row values—not model instances and not the hidden version field. Named fields are accessible as attributes and values by index.

| Method | Description |
| --- | --- |
| `.where(*conditions)` | Adds AND-combined filters. |
| `.order_by(*columns)` | Sorts by columns; use `.asc()` or `.desc()` for direction. |
| `.limit(n)`, `.offset(n)` | Applies paging. |
| `.all()`, `.first()`, `.count()` | Evaluates the query. |
| `.distinct()` | Requests distinct result rows. |
| `.unlimited()` | Disables the automatic `.all()` row guard. |
| `.to_sql()` | Returns the SQL statement and bound parameters without executing. |

The default `.all()` row guard is 10,000 rows and can be configured with `Base.max_rows` or `Model.max_rows`. If a query without an explicit limit exceeds the guard, Pyzzel raises `TooManyRowsError`.

Conditions support `==`, `!=`, `<`, `<=`, `>`, `>=`, `in_()`, `like()`, `ilike()`, `is_null()`, and `is_not_null()`. Use `and_()` / `or_()` or parenthesized conditions combined with `&` and `|`; Python's `and` and `or` cannot construct query conditions.

Aggregates use `func.count()`, `func.sum()`, `func.avg()`, `func.min()`, and `func.max()`. Grouped queries require every selected non-aggregate column to be included in `group_by()`, and aggregate filters belong in `having()`:

```python
from pyzzel import func

totals = (
    Order.select(
        Order.user_id,
        func.sum(Order.total).label("spent"),
        func.count().label("order_count"),
    )
    .group_by(Order.user_id)
    .having(func.sum(Order.total) > 100)
    .all()
)
```

## Relationships and joins

Declare a foreign key using `"table.column"`:

```python
class Order(Base):
    __tablename__ = "orders"

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, foreign_key="users.id", nullable=False)
    total = Column(Numeric(10, 2), nullable=False)
```

Use `.with_(...)` to explicitly load one level of related rows. It issues an additional query per requested relation; it is not lazy loading. Alternatively, joins return flat rows:

```python
orders = (
    User.select(User.name, Order.total)
    .join(Order)
    .where(Order.total > 100)
    .all()
)
```

`join()`, `left_join()`, `right_join()`, and `full_join()` are available. Foreign-key joins are inferred when unambiguous. Pass `on=` for other column comparisons or ambiguous links. Use `alias(Model, "name")` for self-joins or multiple joins to the same table. Joins cannot be combined with `.with_(...)`.

```python
from pyzzel import alias

Manager = alias(Employee, "manager")
reports = (
    Employee.select(Employee.name, Manager.name.label("manager_name"))
    .left_join(Manager, on=Employee.manager_id == Manager.id)
    .all()
)
```

Many-to-many queries can be expressed through two joins using an explicit link model. Use `.label("...")` if selected columns would otherwise have duplicate row field names.

## Bulk and conditional writes

`create_many()` inserts same-shape dictionaries atomically and returns generated primary keys in input order:

```python
ids = User.create_many([
    {"name": "Ada", "email": "ada@example.com"},
    {"name": "Grace", "email": "grace@example.com"},
])
```

Every dictionary must contain the same column keys; primary key and version cannot be supplied. `update_where()` and `delete_where()` issue conditional bulk writes and return affected-row counts. Both require at least one condition.

```python
changed = User.update_where(User.email.is_not_null(), name="Verified")
removed = User.delete_where(User.email.is_null())
```

## Connections and transactions

Configure the pool at application startup:

```python
connect(
    os.environ["PYZZEL_DATABASE_URL"],
    min_size=1,
    max_size=10,
    timeout=30.0,
)
```

`connect()` accepts `min_size`, `max_size`, `timeout`, `check`, and `prepare_threshold`. The pool uses autocommit for standalone statements; `check=True` checks a pooled connection before each operation and adds database work. Prepared statements are disabled by default. Psycopg imports are lazy, so importing `pyzzel` does not itself import the driver.

Use an explicit transaction when several statements must succeed or fail together. Nested transaction blocks use savepoints:

```python
with Base.transaction():
    debit.balance -= 10
    debit.save()
    credit.balance += 10
    credit.save()
```

An exception escaping the outer block rolls back the transaction. Optimistic version checks detect conflicting writes; they do not lock rows in advance.

## Migrations

The migration CLI is `python -m pyzzel.migrate`. Model discovery is **not automatic**: commands that compare the current models with a snapshot need your application to import the modules containing those models. The repeatable `--models MODULE` option performs those imports. For a file at `models.py`, the module name is `models`; for a package such as `myapp/models.py`, use `myapp.models`.

Set the connection URL for database commands. PowerShell:

```powershell
$env:PYZZEL_DATABASE_URL = "postgresql://user:password@localhost:5432/my_database"
```

Bash:

```bash
export PYZZEL_DATABASE_URL="postgresql://user:password@localhost:5432/my_database"
```

### Workflow

1. **Define and import models.** Put model classes in importable Python modules. There is no separate migration initialization command; the first generated migration creates the migration directory and snapshot.

2. **Generate a migration.** `NAME` is a descriptive migration name—not a model name, command, or table name. It must match `^[a-z][a-z0-9_]{0,50}$`.

   ```console
   python -m pyzzel.migrate generate create_users --models models
   ```

   This imports `models`, compares the registered models with `migrations/snapshot.json`, and writes a numbered SQL file such as `migrations/0001_create_users.sql`, then updates the snapshot. Generation is offline and does not connect to PostgreSQL. If there are no schema differences, it prints `No changes.`

   `--models` is a standard double-dash option, written once for each module to import. The CLI does not scan the project directory for model files. In particular, use `--models models`, not `-models models`.

3. **Review the SQL.** Open the generated `.sql` file and verify the operations, especially before applying destructive changes. Renames are not inferred as renames and may need a manual SQL edit.

4. **Apply pending migrations.** This reads numbered `.sql` files in order, applies each pending file in its own transaction, and records it in the default `pyzzel_migrations` history table.

   ```console
   python -m pyzzel.migrate apply
   ```

   Provide `--url URL` instead of the environment variable if preferred. Files marked `-- pyzzel:destructive` require `--allow-destructive`. `--dry-run` lists pending files without applying them.

5. **Check migration status.** Status compares files with the migration history table and reports each file as `pending`, `applied`, or `edited`; applied entries missing from disk are reported as `missing`.

   ```console
   python -m pyzzel.migrate status
   ```

6. **Check model/schema consistency.** `check` requires at least one model module and compares registered models, migration files, and database schema drift.

   ```console
   python -m pyzzel.migrate check --models models
   ```

### Options and other commands

Commands accept `--dir DIRECTORY` (default `migrations`) and `--history-table NAME` (default `pyzzel_migrations`). `apply`, `status`, `check`, and `pull` accept `--url URL`; otherwise they read `PYZZEL_DATABASE_URL`. `check` and `pull` accept repeatable `--ignore TABLE` options.

Create an empty, numbered migration for hand-written SQL:

```console
python -m pyzzel.migrate create backfill_user_names
```

Inspect the live database against the snapshot; add `--write` to replace `snapshot.json` with the introspected schema:

```console
python -m pyzzel.migrate pull
python -m pyzzel.migrate pull --write
```

`generate`, `create`, and `pull --write` may create or update files in the selected migration directory. Review generated files and preserve applied migrations. The tool has no down migrations and supports only a subset of PostgreSQL schema objects for drift comparison; see the [migration comparison limitations](#migration-comparison-limitations).

<details>
<summary>Migration comparison limitations</summary>

Schema comparison covers columns and types, nullability, defaults, primary keys, single-column unique constraints and foreign keys, and simple single-column indexes. Composite constraints, checks, triggers, views, sequences, arrays, enums, partial/expression indexes, and other objects are not fully compared; some produce warnings. Default normalization is best-effort. When migration files are pending, edited, or missing, `check` reports those issues and does not check database drift.

</details>

## Pyzzel v1

Pyzzel v1 introduces two query-building milestones while preserving the project's explicit PostgreSQL and parameterized-SQL model.

### Aggregates

Aggregate expressions are available through `func.count()`, `func.sum()`, `func.avg()`, `func.min()`, and `func.max()`. Queries support `.group_by()` and `.having()`, and selected aggregates can be named with `.label()`. Grouping rules are validated before execution. Aggregates return row values rather than model instances.

### Expanded joins

The join API adds right and full outer joins, validated model aliases through `alias()`, and column-to-column comparisons in join `on=` conditions and query filters. Aliases support self-joins and joining the same model more than once. Existing inner and left joins remain available. These additions do not introduce implicit relation loading; use explicit joins or `.with_(...)` as appropriate.

See [CHANGELOG.md](CHANGELOG.md) for the project change log and the query sections above for examples.

## Performance and benchmarks

The repository contains benchmark harnesses, reports, and historical archives. Current smoke runs cover Pyzzel, SQLAlchemy, Piccolo ORM, and raw Psycopg 3 across 23 workloads in normalized and idiomatic modes. Smoke results validate execution and correctness; they are **not** statistical performance results and should not be used to rank adapters.

Compare results only when workload, mode, runtime, database, pool, and telemetry configurations match. Historical results use a different adapter set and are retained as historical artifacts. Start with the [benchmark summary](docs/benchmark_summary.md), [comparison documentation](comparisons/README.md), and [workload coverage](comparisons/workload_coverage.json).

## Development

Install the development extra and run the test suite:

```console
python -m pip install -e ".[dev]"
python -m pytest -q
```

Database tests read `PYZZEL_TEST_DATABASE_URL` and skip when it is not configured. Point it only at a dedicated disposable PostgreSQL test database; tests create and drop tables prefixed `pyzzel_test_`.

The source is organized into `core/` for models and queries, `sql/` for statement construction, `pool.py` for connection and transaction management, and `migrate/` for optional schema migration tools. Local scripts live in `scripts/` and are not part of the installed package.

## License

Pyzzel is distributed under the [MIT License](LICENSE).
