Skip to content

API Reference

Core Classes

SQLCrucibleBaseModel

sqlcrucible.SQLCrucibleBaseModel

Bases: BaseModel, SQLCrucibleEntity

__sqlalchemy_params__ = {'__abstract__': True} class-attribute instance-attribute

SQLCrucibleEntity

sqlcrucible.SQLCrucibleEntity

Base class for entities that auto-generate SQLAlchemy models.

Subclasses define their schema using type annotations with SQLAlchemy markers (mapped_column, relationship, etc.). The SQLAlchemy model is automatically generated and accessible via sqlalchemy_type.

Class Attributes

sqlalchemy_base: Optional custom DeclarativeBase for the SA model. sqlalchemy_params: SQLAlchemy configuration (tablename, etc.). converter_registry: Converter registry for field type conversion. sqlalchemy_automodel: The auto-generated SQLAlchemy model class. sqlalchemy_type: The SQLAlchemy model class to use (defaults to sqlalchemy_automodel).

Example
@dataclass
class User(SQLCrucibleEntity):
    __sqlalchemy_params__ = {"__tablename__": "users"}

    id: Annotated[int, mapped_column(Integer, primary_key=True)]
    name: Annotated[str, mapped_column(String(50))]
    email: Annotated[str | None, mapped_column(String(100))]


# Use the entity
user = User(id=1, name="Alice", email="alice@example.com")
sa_model = user.to_sa_model()  # Convert to SQLAlchemy

# Convert back
user2 = User.from_sa_model(sa_model)

__sqlalchemy_type__ = SQLAlchemyBase class-attribute

__sqlalchemy_params__ = {} class-attribute

to_sa_model()

Convert this entity to a SQLAlchemy model instance.

Creates a new SQLAlchemy model populated with data from this entity, applying any configured type converters for each field.

Returns:

Type Description
Any

A SQLAlchemy model instance ready to be added to a session.

from_sa_model(sa_model) classmethod

Create an entity instance from a SQLAlchemy model.

This method converts a SQLAlchemy model instance into the corresponding entity class. For polymorphic models, it automatically selects the most specific entity subclass that matches the model type.

Parameters:

Name Type Description Default
sa_model Any

A SQLAlchemy model instance to convert.

required

Returns:

Type Description
Self

An entity instance populated with data from the SQLAlchemy model.

Raises:

Type Description
TypeError

If sa_model is None.

ValueError

If sa_model is not compatible with this entity's SQLAlchemy type.

SAType

sqlcrucible.SAType

Utility to access an entity's SQLAlchemy type.

Provides a cleaner syntax for accessing an entity's SQLAlchemy type:

# Instead of:
select(Track.__sqlalchemy_type__).where(Track.__sqlalchemy_type__.length_seconds > 180)

# Write:
select(SAType[Track]).where(SAType[Track].length_seconds > 180)

With generated stubs, type checkers know the exact return type and can provide autocompletion for column names.

Annotations

SQLAlchemyField

sqlcrucible.entity.annotations.SQLAlchemyField dataclass

Configuration for mapping an entity field to SQLAlchemy.

This annotation can be used to customize how entity fields are mapped to SQLAlchemy columns or relationships.

Attributes:

Name Type Description
name str | None

The name to use for the mapped attribute (defaults to field name)

attr Mapped[Any] | None

A Mapped[] attribute to use directly

tp Any | None

The type to use for the mapped attribute

merge_all(*fields) classmethod

Merge multiple SQLAlchemyField annotations, with later values taking precedence.

ExcludeSAField

sqlcrucible.entity.annotations.ExcludeSAField dataclass

ConvertToSAWith

sqlcrucible.entity.annotations.ConvertToSAWith dataclass

Annotation specifying custom converter from entity to SQLAlchemy.

Use this annotation to provide a custom conversion function when saving entity values into SQLAlchemy models.

Example
from typing import Annotated


class MyEntity(SQLCrucibleEntity):
    created_at: Annotated[
        datetime, mapped_column(), ConvertToSAWith(lambda dt: dt.astimezone(timezone.utc))
    ]

converter property

Get the Converter instance for this function.

ConvertFromSAWith

sqlcrucible.entity.annotations.ConvertFromSAWith dataclass

Annotation specifying custom converter from SQLAlchemy to entity.

Use this annotation to provide a custom conversion function when loading values from SQLAlchemy models into entity instances.

Example
from typing import Annotated


class MyEntity(SQLCrucibleEntity):
    created_at: Annotated[
        datetime, mapped_column(), ConvertFromSAWith(lambda dt: dt.astimezone(timezone.utc))
    ]

converter property

Get the Converter instance for this function.

Fields

readonly_field

sqlcrucible.entity.fields.readonly_field

Descriptor for read-only fields populated from SQLAlchemy relationships.

This descriptor allows defining fields that are loaded from SQLAlchemy relationships but not included in the entity's constructor. The value is lazily loaded from the SQLAlchemy model when accessed.

Example
@dataclass
class Track(SQLCrucibleEntity):
    __sqlalchemy_params__ = {"__tablename__": "track"}

    id: Annotated[int, mapped_column(primary_key=True)]
    title: Annotated[str, mapped_column()]
    artist_id: Annotated[int, mapped_column(ForeignKey("artist.id"))]

    # Read-only field loaded from relationship
    artist = readonly_field(
        Artist, SQLAlchemyField(attr=relationship(Artist, back_populates="tracks"))
    )

Class Type Parameters:

Name Bound or Constraints Description Default
_T

The type of the field value

required
_O

The type of the owning entity class

required

sa_field_info property

Get the SQLAlchemy field definition for this descriptor.

This property resolves any forward references in the type, which requires all referenced classes to be defined. It's safe to call after class creation is complete.

Returns:

Type Description
SQLAlchemyFieldDefinition

The field definition with resolved types

Raises:

Type Description
RuntimeError

If accessed before the descriptor is assigned to a class

__init__(tp, sa_field=None)

Initialize a readonly field descriptor.

Parameters:

Name Type Description Default
tp Any

The type of the field value (can be a type, string forward ref, or parameterized type)

required
sa_field SQLAlchemyField | None

Optional SQLAlchemyField configuration for the mapped attribute

None

__set_name__(owner, name)

Called when the descriptor is assigned to a class attribute.

Registers the field definition with the entity class. Forward references in the type are resolved lazily when the field definition is actually accessed, not during class creation.

Parameters:

Name Type Description Default
owner type[_O]

The entity class owning this field

required
name str

The name of the field in the entity class

required

__get__(instance, owner)

__get__(instance: None, owner: type[_O]) -> Self
__get__(instance: _O, owner: type[_O]) -> _T

Get the field value from an entity instance.

When accessed on the class, returns the descriptor itself. When accessed on an instance, loads the value from the SQLAlchemy model.

Parameters:

Name Type Description Default
instance _O | None

The entity instance (or None if accessed on class)

required
owner type[_O]

The entity class

required

Returns:

Type Description
_T | Self

The descriptor (if accessed on class) or the field value (if on instance)

Raises:

Type Description
RuntimeError

If the entity instance is not backed by a SQLAlchemy model

Utilities

lazyproperty

sqlcrucible.utils.properties.lazyproperty(func)