Created
January 27, 2025 16:13
-
-
Save mykappa/60d9faf2e5580cbcb8f8d16dc1124e1a to your computer and use it in GitHub Desktop.
Modify `SQLModel` to use snake case table names by default. [Credit @nuno-andre: https://github.com/fastapi/sqlmodel/issues/159#issuecomment-1142901416]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlmodel import SQLModel as _SQLModel | |
from sqlalchemy.orm import declared_attr | |
from functools import partial | |
import re | |
_snake_1 = partial(re.compile(r"(.)((?<![^A-Za-z])[A-Z][a-z]+)").sub, r"\1_\2") | |
_snake_2 = partial(re.compile(r"([a-z0-9])([A-Z])").sub, r"\1_\2") | |
def snake_case(string: str) -> str: | |
"""Convert PascalCaseString to a snake_case_string.""" | |
return _snake_2(_snake_1(string)).casefold() | |
class SQLModel(_SQLModel): | |
@declared_attr | |
def __tablename__(cls) -> str: | |
"""Return the snake_case version of the class name as the table name.""" | |
return snake_case(cls.__name__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment