or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

async.mdcore-engine.mddialects.mdindex.mdorm.mdschema.mdsql-expression.mdtypes.md
tile.json

tessl/pypi-sqlalchemy

Python SQL toolkit and Object Relational Mapper providing full power and flexibility of SQL

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/sqlalchemy@2.0.x

To install, run

npx @tessl/cli install tessl/pypi-sqlalchemy@2.0.0

index.mddocs/

SQLAlchemy

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

Package Information

  • Package Name: SQLAlchemy
  • Language: Python
  • Installation: pip install sqlalchemy
  • Documentation: https://docs.sqlalchemy.org

Core Imports

import sqlalchemy

Common patterns for Core (SQL Expression Language):

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, select, insert, update, delete

Common patterns for ORM:

from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker, Session, relationship

Modern ORM with 2.0 style:

from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped, Session

Basic Usage

Core SQL Expression Language

from 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}")

ORM Usage

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}")

Architecture

SQLAlchemy consists of two main layers:

  • Core: SQL expression language providing database abstraction, connection management, and SQL construction
  • ORM: Object-relational mapping layer built on Core, providing declarative mapping, session management, and relationship handling

Key components:

  • Engine: Database connection management and execution
  • MetaData: Schema definition and reflection
  • Session: ORM unit of work and identity map
  • Dialect: Database-specific SQL generation and behavior

Capabilities

Core Engine and Connectivity

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

Core Engine

SQL Expression Language

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

SQL Expression Language

Object Relational Mapping (ORM)

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

Object Relational Mapping

Schema Definition and Reflection

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

Schema Definition

Type System and Data Types

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

Type System

Database Dialects

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 JSON

Database Dialects

Async Support

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

Async Support

Extensions

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, dumps

Events System

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

Exception Handling

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

Inspection System

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

Types

Core Types

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 iterator

ORM Types

from typing import TypeVar, Type, List

# Generic mapped class type
_T = TypeVar('_T')
MappedClassType = Type[_T]

# Relationship types
RelationshipProperty = Any
MappedCollection = List[Any]