Skip to main content

Pyzzel

A small, explicit PostgreSQL ORM for Python.

PyPI version Python versions MIT license

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

  • 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:

python -m pip install Pyzzel

Or install a checkout with development dependencies:

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:

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.

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.

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

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:

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:

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():

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":

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:

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_(...).

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:

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.

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:

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:

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:

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

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}$.

    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.

    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.

    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.

    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:

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:

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

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.

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 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, comparison documentation, and workload coverage.

Development

Install the development extra and run the test suite:

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.

Metadata

Release files for Pyzzel 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for Pyzzel 1.0.0
File Size Uploaded Provenance Actions
pyzzel-1.0.0.tar.gz 83.1 kB With provenance Details for pyzzel-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for Pyzzel 1.0.0
File Interpreter ABI Platform Actions
pyzzel-1.0.0-py3-none-any.whl Python 3 none any Details for pyzzel-1.0.0-py3-none-any.whl

Total release size: 128.4 kB

Release files / pyzzel-1.0.0.tar.gz

Download URL pyzzel-1.0.0.tar.gz
Size 83.1 kB
Tags Source
SHA-256 checksum
How to use checksums
bd4486cfce7296dcbe77d04ffa43a06b7d1f813311ab5d271607812f735b2812
BLAKE2b-256 checksum
How to use checksums
efe82c7c30cf566456160a51b4a95d6f2a2d5973f18bcc027385788118a6915c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / pyzzel-1.0.0-py3-none-any.whl

Download URL pyzzel-1.0.0-py3-none-any.whl
Size 45.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d960bfa5c4fe1528cb8a107ad66ee1ed79267f4d6ffbac94f81eb2eec1556400
BLAKE2b-256 checksum
How to use checksums
1ff8872c8471c69a16271a3d0b83207994b05ff16d830811a7e32156c7939e13
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for Pyzzel 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pyzzel-1.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page