Skip to content

SQLAlchemy#

Let's explore the integration options of SQLAlchemy with textcase.

Table Name Autogeneration#

Typically, table names are specified manually:

base.py
1
2
3
4
5
from sqlalchemy.orm import DeclarativeBase


class User(DeclarativeBase):
    __tablename__ = "user"

To avoid duplicating __tablename__ in every model, you can create a base class:

textcase.py
from typing import Any

from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import DeclarativeBase

from textcase import snake


class Base(DeclarativeBase):
    @declared_attr
    @classmethod
    def __tablename__(cls) -> Any:  # noqa: ANN401
        return snake(cls.__name__)


class User(Base): ...

If you have Pydantic in your project, you can achieve this without the extra library by using pydantic.alias_generators.to_snake. This function works similarly and also handles acronyms, but it has a larger footprint.

pydantic.py
from typing import Any

from pydantic.alias_generators import to_snake
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import DeclarativeBase


class Base(DeclarativeBase):
    @declared_attr
    @classmethod
    def __tablename__(cls) -> Any:  # noqa: ANN401
        return to_snake(cls.__name__)


class User(Base): ...

Use this option if Pydantic is already present in your project and you only need this specific feature. In all other cases, textcase is preferable due to its smaller footprint.