or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

aggregations-helpers.mdattributes-relationships.mddata-types.mddatabase-entities.mddebugging-utilities.mdexception-handling.mdframework-integrations.mdindex.mdquery-operations.mdsecurity-permissions.mdsession-management.md
tile.json

tessl/pypi-pony

Pony Object-Relational Mapper for Python with Pythonic query syntax using generator expressions

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pony@0.7.x

To install, run

npx @tessl/cli install tessl/pypi-pony@0.7.0

index.mddocs/

Pony ORM

Pony 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.

Package Information

  • Package Name: pony
  • Language: Python
  • Installation: pip install pony
  • Documentation: https://docs.ponyorm.org
  • License: Apache 2.0

Core Imports

from 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, avg

Flask integration:

from pony.flask import Pony

Basic Usage

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

Architecture

Pony ORM follows a distinctive architecture centered on generator expression translation:

  • Database: Central registry that manages entity definitions and database connections
  • Entity: Base metaclass for defining database-mapped classes with attributes and relationships
  • Attribute Types: Required, Optional, Set, PrimaryKey define column types and relationships
  • Query Translation: Python generator expressions are parsed and translated to optimized SQL
  • Session Management: db_session decorator manages transactions and database connections
  • Identity Map: Ensures object identity and manages entity lifecycle within sessions

This design enables writing database queries in pure Python while automatically generating efficient SQL, making database operations feel native to the language.

Capabilities

Database and Entity Management

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

Database and Entities

Entity Attributes and Relationships

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

Attributes and Relationships

Data Types and Custom Types

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

Data Types

Query Operations

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

Query Operations

Aggregation and Query Helpers

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

Aggregations and Helpers

Session Management

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

Session Management

Debugging and Utilities

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

Debugging and Utilities

Exception Handling

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

Exception Handling

Security and Permissions

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

Security and Permissions

Framework Integrations

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

Framework Integrations

Types

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'