Pony Object-Relational Mapper for Python with Pythonic query syntax using generator expressions
npx @tessl/cli install tessl/pypi-pony@0.7.0Pony ORM is an advanced Object-Relational Mapper for Python that allows developers to write database queries using Python generator expressions and lambda functions. These expressions are automatically analyzed and translated into optimized SQL queries, providing an intuitive and Pythonic way to work with databases.
pip install ponyfrom pony.orm import *Selective imports for common functionality:
from pony.orm import Database, Required, Optional, Set, PrimaryKey
from pony.orm import db_session, commit, rollback, select, get
from pony.orm import LongStr, Json, count, sum, min, max, avgFlask integration:
from pony.flask import Ponyfrom pony.orm import *
# Define the database and entities
db = Database()
class Person(db.Entity):
name = Required(str)
age = Optional(int)
orders = Set('Order')
class Order(db.Entity):
date = Required(datetime)
person = Required(Person)
total = Required(float)
db.generate_mapping(create_tables=True)
# Use database session for queries and operations
with db_session:
# Create entities
person = Person(name="John", age=30)
order = Order(date=datetime.now(), person=person, total=99.99)
# Query using generator expressions
adults = select(p for p in Person if p.age >= 18)
# Query with joins and aggregations
big_spenders = select(p for p in Person
if sum(p.orders.total) > 1000)
# Get single entity
john = Person.get(name="John")
# Commit changes
commit()Pony ORM follows a distinctive architecture centered on generator expression translation:
This design enables writing database queries in pure Python while automatically generating efficient SQL, making database operations feel native to the language.
Core classes for defining database schemas and entity relationships. The Database class serves as the central registry, while Entity provides the base for all ORM-mapped classes.
class Database:
def __init__(self, provider=None, **kwargs): ...
def bind(self, provider, **kwargs): ...
def generate_mapping(self, check_tables=True, create_tables=False): ...
def create_tables(self): ...
def drop_all_tables(self, with_all_data=False): ...
class Entity:
def __init__(self, **kwargs): ...
def delete(self): ...
def flush(self): ...
def get_pk(self): ...
def set(**kwargs): ...Attribute types for defining entity properties, primary keys, and relationships between entities. These classes define the schema structure and constraints.
class Required:
def __init__(self, py_type, **kwargs): ...
class Optional:
def __init__(self, py_type, **kwargs): ...
class PrimaryKey:
def __init__(self, py_type, **kwargs): ...
class Set:
def __init__(self, py_type, **kwargs): ...
def composite_key(*attrs): ...
def composite_index(*attrs): ...Specialized data types for storing large text, JSON data, and array types. These extend Python's basic types for database-specific storage needs.
class LongStr(str): ...
class Json: ...
class IntArray: ...
class StrArray: ...
class FloatArray: ...Functions for querying the database using Pony's signature generator expression syntax. These provide the main interface for data retrieval and manipulation.
def select(gen): ...
def get(gen): ...
def exists(gen): ...
def delete(gen): ...
def left_join(gen): ...Aggregation functions and helper utilities for complex queries including mathematical operations, sorting, and SQL function access.
def count(gen=None): ...
def sum(gen): ...
def min(gen): ...
def max(gen): ...
def avg(gen): ...
def group_concat(gen, sep=','): ...
def distinct(gen): ...
def desc(attr): ...
def between(x, a, b): ...
def concat(*args): ...
def coalesce(*args): ...Database session and transaction management functions. These control the lifecycle of database operations and ensure data consistency.
@db_session
def your_function(): ...
def flush(): ...
def commit(): ...
def rollback(): ...
def make_proxy(entity_instance): ...Tools for debugging SQL queries, inspecting schemas, and configuring runtime behavior. Essential for development and troubleshooting.
def set_sql_debug(debug=True, show_values=None): ...
def show(entity_or_query): ...Comprehensive exception hierarchy covering database errors, ORM-specific errors, query errors, and transaction errors. Proper exception handling is crucial for robust applications.
class OrmError(Exception): ...
class ObjectNotFound(OrmError): ...
class MultipleObjectsFoundError(OrmError): ...
class TransactionError(OrmError): ...
class DatabaseError(Exception): ...
class IntegrityError(DatabaseError): ...Optional security framework for implementing row-level security and user-based access control in database operations.
def set_current_user(user): ...
def get_current_user(): ...
def has_perm(entity, permission): ...
def perm(permission_name): ...Integrations with popular Python web frameworks for automatic session management and simplified database operations in web applications.
class Pony:
def __init__(self, app=None): ...
def init_app(self, app): ...from typing import Any, Optional, Union, List, Dict
from datetime import datetime, date, time, timedelta
from decimal import Decimal
# Core types used across the API
EntityType = type # Entity class type
AttributeType = Union[Required, Optional, PrimaryKey, Set]
QueryType = Any # Generator expression or Query object
DatabaseProvider = str # 'sqlite', 'mysql', 'postgresql', 'oracle', 'cockroach'