or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

data-types.mddatabase-engine.mdindex.mdmodel-definition.mdschema-definition.mdsession-management.mdsql-operations.md
tile.json

tessl/pypi-sqlmodel

SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/sqlmodel@0.0.x

To install, run

npx @tessl/cli install tessl/pypi-sqlmodel@0.0.0

index.mddocs/

SQLModel

SQLModel is a library for interacting with SQL databases from Python code, with Python objects. It is designed to be intuitive, easy to use, highly compatible, and robust. SQLModel is based on Python type annotations, and powered by Pydantic and SQLAlchemy.

The key innovation of SQLModel is that it allows you to define a single class that serves as both a SQLAlchemy table model and a Pydantic validation model, eliminating code duplication and ensuring consistency across database operations and API interfaces.

Package Information

  • Package Name: sqlmodel
  • Package Type: pypi
  • Language: Python
  • Installation: pip install sqlmodel
  • Dependencies: SQLAlchemy >=2.0.14,<2.1.0, pydantic >=1.10.13,<3.0.0

Core Imports

from sqlmodel import SQLModel, Field, Relationship, Session, create_engine, select

Additional commonly used imports:

# SQL operations and expressions
from sqlmodel import and_, or_, not_, func, text, Column, Index, ForeignKey

# Data types
from sqlmodel import String, Integer, Boolean, DateTime, Float, Text

# Engine and connection management
from sqlmodel import create_mock_engine, MetaData, inspect

Basic Usage

from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select

# Define a model that works as both SQLAlchemy table and Pydantic model
class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None

# Create database engine and tables
engine = create_engine("sqlite:///database.db")
SQLModel.metadata.create_all(engine)

# Create and save data
hero = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
with Session(engine) as session:
    session.add(hero)
    session.commit()

# Query data with type safety
with Session(engine) as session:
    statement = select(Hero).where(Hero.name == "Spider-Boy")
    result = session.exec(statement).first()
    print(result)  # Hero object with full type support

Architecture

SQLModel combines three key technologies:

  • Pydantic: Provides data validation, serialization, and JSON schema generation
  • SQLAlchemy: Handles database operations, ORM functionality, and SQL generation
  • Type Annotations: Enables editor support with autocompletion and type checking

The SQLModel class serves as a bridge between these systems, allowing a single model definition to work seamlessly with both database operations and API serialization, particularly in FastAPI applications.

Capabilities

Model Definition

Core functionality for defining database models that work with both SQLAlchemy and Pydantic, including field definitions and relationships.

class SQLModel(BaseModel, metaclass=SQLModelMetaclass): ...

def Field(
    default: Any = ...,
    *,
    primary_key: bool = False,
    foreign_key: Optional[str] = None,
    unique: bool = False,
    nullable: Optional[bool] = None,
    index: Optional[bool] = None,
    **kwargs
) -> Any: ...

def Relationship(
    *,
    back_populates: Optional[str] = None,
    cascade_delete: bool = False,
    **kwargs
) -> Any: ...

Model Definition

Session Management

Database session handling with enhanced typing support for better type inference with SQLModel objects.

class Session(SQLAlchemySession):
    def exec(self, statement: Select[T]) -> Result[T]: ...

Session Management

SQL Operations

Query building and execution with type-safe SELECT statements and SQL expression functions.

def select(*entities) -> Union[Select, SelectOfScalar]: ...

def and_(*clauses) -> BooleanClauseList: ...
def or_(*clauses) -> BooleanClauseList: ...
def not_(clause) -> UnaryExpression: ...

SQL Operations

Database Engine and Connection

Database engine creation and connection management, re-exported from SQLAlchemy with full compatibility.

def create_engine(url: str, **kwargs) -> Engine: ...
def create_mock_engine(dialect: str, executor: Callable) -> MockConnection: ...

Database Engine

Schema Definition

Database schema components including tables, columns, constraints, and indexes, providing full SQLAlchemy schema definition capabilities.

class MetaData: ...
class Table: ...
class Column: ...
class Index: ...
class ForeignKey: ...

Schema Definition

Data Types

Comprehensive SQL data type system with Python type mapping, including both SQLAlchemy standard types and SQLModel extensions.

class AutoString(TypeDecorator): ...

# Standard SQLAlchemy types
Integer: TypeEngine
String: TypeEngine
DateTime: TypeEngine
Boolean: TypeEngine

Data Types

Types

class FieldInfo(PydanticFieldInfo):
    primary_key: bool
    nullable: Optional[bool]
    foreign_key: Any
    unique: bool
    index: Optional[bool]
    sa_type: Any
    sa_column: Optional[Column]

class RelationshipInfo:
    back_populates: Optional[str]
    cascade_delete: bool
    passive_deletes: Union[bool, Literal["all"]]
    link_model: Optional[Any]

class SQLModelMetaclass(ModelMetaclass, DeclarativeMeta): ...