Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to use Enums in custom DB schema #1146

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

KrilleGH
Copy link

I have a legacy DB which is receiving an API including new tables in a separate DB schema. The new code must not touch the existing objects in the public schema.

So all models derive from

class SchemaSQLModel(SQLModel):
    __table_args__ = {
        'schema': 'api',
    }

I have some fields which use Enums:

class HeroType(enum.StrEnum):
    normal = enum.auto()
    super = enum.auto()

class Hero(SchemaSQLModel):
    type: HeroType

The DB is PostgreSQL and I'm using the native Enum type (CREATE TYPE). Also these types reside in the custom schema.

When creating a new Hero the generated SQL has explicit casts to the types of the columns. However, for the type column only the plain name of the type is generated. Of course that doesn't work, as the Enum type isn't in the public schema.

The solution is to pass inherit_schema=True when instantiating SQLAlchemy's Enum class. I achived this by making a subclass and using that in get_sqlalchemy_type() instead of the plain one.

I'm aware this PR may not be in it's final form. Please advise what needs to be done to get it merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant