Python SQL toolkit and Object Relational Mapper providing full power and flexibility of SQL
npx @tessl/cli install tessl/pypi-sqlalchemy@2.0.0SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. It provides an industrial-strength ORM built on the identity map, unit of work, and data mapper patterns for transparent object persistence using declarative configuration.
pip install sqlalchemyimport sqlalchemyCommon patterns for Core (SQL Expression Language):
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, select, insert, update, deleteCommon patterns for ORM:
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker, Session, relationshipModern ORM with 2.0 style:
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped, Sessionfrom sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, select
# Create engine and define table
engine = create_engine("sqlite:///example.db")
metadata = MetaData()
users = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50)),
Column('email', String(100))
)
# Create table
metadata.create_all(engine)
# Execute queries
with engine.connect() as conn:
# Insert data
result = conn.execute(
users.insert().values(name='John Doe', email='john@example.com')
)
# Select data
result = conn.execute(select(users).where(users.c.name == 'John Doe'))
row = result.fetchone()
print(f"User: {row.name}, Email: {row.email}")from sqlalchemy import create_engine, String, Integer
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
# Define base and model
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = 'users'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50))
email: Mapped[str] = mapped_column(String(100))
# Create engine and tables
engine = create_engine("sqlite:///example.db")
Base.metadata.create_all(engine)
# Use session for ORM operations
with Session(engine) as session:
# Create and add new user
new_user = User(name="Jane Smith", email="jane@example.com")
session.add(new_user)
session.commit()
# Query users
users = session.query(User).filter(User.name.like('%Jane%')).all()
for user in users:
print(f"User: {user.name}, Email: {user.email}")SQLAlchemy consists of two main layers:
Key components:
Database engine creation, connection management, URL handling, connection pooling, and transaction management. The foundation for all SQLAlchemy database operations.
def create_engine(url, **kwargs): ...
def make_url(name_or_url): ...
class Engine:
def connect(self): ...
def execute(self, statement, parameters=None): ...
class Connection:
def execute(self, statement, parameters=None): ...
def begin(self): ...
def commit(self): ...
def rollback(self): ...Programmatic SQL construction with Python expressions, including SELECT, INSERT, UPDATE, DELETE statements, joins, subqueries, functions, and complex query composition.
def select(*columns): ...
def insert(table): ...
def update(table): ...
def delete(table): ...
def and_(*clauses): ...
def or_(*clauses): ...
def not_(clause): ...
class Select:
def where(self, *criteria): ...
def join(self, target, onclause=None): ...
def order_by(self, *clauses): ...
def group_by(self, *clauses): ...Declarative mapping, session management, relationship definitions, query API, and advanced ORM features including inheritance, polymorphism, and events.
class DeclarativeBase: ...
def declarative_base(): ...
class Session:
def add(self, instance): ...
def query(self, *entities): ...
def commit(self): ...
def rollback(self): ...
def relationship(argument, **kwargs): ...
def mapped_column(*args, **kwargs): ...Table, column, and constraint definition, database schema reflection, index management, and DDL generation for database structure management.
class MetaData:
def create_all(self, bind): ...
def reflect(self, bind): ...
class Table:
def __init__(self, name, metadata, *args, **kwargs): ...
class Column:
def __init__(self, *args, **kwargs): ...
class Index:
def __init__(self, name, *expressions, **kwargs): ...SQL data type system including numeric, string, date/time, binary, and specialized types with database-specific variants and custom type creation.
class Integer: ...
class String: ...
class DateTime: ...
class Boolean: ...
class JSON: ...
class TypeDecorator:
def process_bind_param(self, value, dialect): ...
def process_result_value(self, value, dialect): ...Database-specific implementations for PostgreSQL, MySQL, SQLite, Oracle, SQL Server with specialized types, functions, and features for each database.
# PostgreSQL
from sqlalchemy.dialects.postgresql import ARRAY, JSON, UUID
# MySQL
from sqlalchemy.dialects.mysql import MEDIUMINT, SET
# SQLite
from sqlalchemy.dialects.sqlite import JSONAsynchronous database operations with async engines, connections, sessions, and ORM support for modern async Python applications.
async def create_async_engine(url, **kwargs): ...
class AsyncEngine:
async def connect(self): ...
class AsyncSession:
async def commit(self): ...
async def execute(self, statement): ...SQLAlchemy extensions providing additional functionality for association proxies, hybrid properties, mutable tracking, automap, and other advanced features.
# Association proxy for simplified relationship access
from sqlalchemy.ext.associationproxy import association_proxy
# Hybrid properties for computed attributes
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
# Mutable tracking for container types
from sqlalchemy.ext.mutable import Mutable, MutableDict, MutableList, MutableSet
# Automap for automatic class generation from schema
from sqlalchemy.ext.automap import automap_base
# Compiler extensions for custom SQL constructs
from sqlalchemy.ext.compiler import compiles, deregister
# Horizontal sharding support
from sqlalchemy.ext.horizontal_shard import ShardedQuery, ShardedSession
# Other utilities
from sqlalchemy.ext.indexable import index_property
from sqlalchemy.ext.orderinglist import ordering_list
from sqlalchemy.ext.serializer import loads, dumpsComprehensive event system for hooking into SQLAlchemy operations at various points in the lifecycle.
from sqlalchemy import event
# Event registration
def listen(target, identifier, fn, **kwargs): ...
def listens_for(target, identifier, **kwargs): ... # decorator
def remove(target, identifier, fn): ...
def contains(target, identifier, fn): ...
# Engine and connection events
class PoolEvents:
def connect(self, dbapi_connection, connection_record): ...
def first_connect(self, dbapi_connection, connection_record): ...
def checkout(self, dbapi_connection, connection_record, connection_proxy): ...
def checkin(self, dbapi_connection, connection_record): ...
def close(self, dbapi_connection, connection_record): ...
class ConnectionEvents:
def before_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): ...
def after_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): ...
def begin(self, conn): ...
def commit(self, conn): ...
def rollback(self, conn): ...
# ORM events
class SessionEvents:
def before_commit(self, session): ...
def after_commit(self, session): ...
def after_transaction_create(self, session, transaction): ...
def before_flush(self, session, flush_context, instances): ...
def after_flush(self, session, flush_context): ...
class MapperEvents:
def before_insert(self, mapper, connection, target): ...
def after_insert(self, mapper, connection, target): ...
def before_update(self, mapper, connection, target): ...
def after_update(self, mapper, connection, target): ...
def before_delete(self, mapper, connection, target): ...
def after_delete(self, mapper, connection, target): ...
class AttributeEvents:
def set(self, target, value, oldvalue, initiator): ...
def append(self, target, value, initiator): ...
def remove(self, target, value, initiator): ...Comprehensive exception hierarchy for error handling and debugging in database operations.
# Base exceptions
class SQLAlchemyError(Exception): ...
class ArgumentError(SQLAlchemyError): ...
class InvalidRequestError(SQLAlchemyError): ...
class CompileError(SQLAlchemyError): ...
# Database API errors
class DBAPIError(SQLAlchemyError): ...
class IntegrityError(DBAPIError): ...
class OperationalError(DBAPIError): ...
class ProgrammingError(DBAPIError): ...
class DataError(DBAPIError): ...
class InterfaceError(DBAPIError): ...
class DatabaseError(DBAPIError): ...
class InternalError(DBAPIError): ...
class NotSupportedError(DBAPIError): ...Database and ORM introspection capabilities for examining database schemas and ORM configurations.
def inspect(subject):
"""
Provide an inspection interface for various SQLAlchemy objects.
Parameters:
- subject: Object to inspect (Engine, Connection, mapped class, etc.)
Returns:
Inspector or other inspection interface for the subject
"""from typing import Any, Optional, Union, Dict
# URL and connectivity
class URL:
def __init__(self, drivername: str, **kwargs): ...
# Engine types
EngineType = Union[Engine, AsyncEngine]
ConnectArgs = Dict[str, Any]
# Result types
Row = Any # Row-like object with column access
Result = Any # Query result iteratorfrom typing import TypeVar, Type, List
# Generic mapped class type
_T = TypeVar('_T')
MappedClassType = Type[_T]
# Relationship types
RelationshipProperty = Any
MappedCollection = List[Any]