pythonsqlalchemyfastapialembicsqlmodel

How to get Alembic to recognise SQLModel database model?


Using SQLModel how to get alembic to recognise the below model?

from sqlmodel import Field, SQLModel

class Hero(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None

One approach I've been looking at is to import the SQLalchemy model for Alembic but looking through the source code I can't find how to do that.

How to make Alembic work with SQLModel models?


Solution

  • There should be info about that in Advanced user guide soon with better explanation than mine but here is how I made Alimbic migrations work.

    First of all run alembic init migrations in your console to generate migrations folder. Inside migrations folder should be empty versions subfolder,env.py file, script.py.mako file. In script.py.mako file we should add line import sqlmodel somewhere around these two lines

    #script.py.mako
    from alembic import op
    import sqlalchemy as sa
    import sqlmodel # added
    

    Then we should edit env.py file

    #env.py
    from logging.config import fileConfig
    
    from sqlalchemy import engine_from_config
    from sqlalchemy import pool
    
    from alembic import context
    
    from app.models import * # necessarily to import something from file where your models are stored
    
    # this is the Alembic Config object, which provides
    # access to the values within the .ini file in use.
    config = context.config
    
    # Interpret the config file for Python logging.
    # This line sets up loggers basically.
    fileConfig(config.config_file_name)
    
    # add your model's MetaData object here
    # for 'autogenerate' support
    # from myapp import mymodel
    # target_metadata = mymodel.Base.metadata
    target_metadata = None 
    # comment line above and instead of that write
    target_metadata = SQLModel.metadata
    

    While writing came up with an idea that you forgot to import something from your models.py (or anywhere else your models are stored). And that was the main problem

    Also, an important note would be saving changes in your models by pressing ctrl(CMD) + S - there are some issues with that.

    Finally,running

     alembic revision --autogenerate -m "your message"
    

    should generate a new .py file in versions folder with your changes. And

     alembic upgrade head  
    

    Applies your changes to DB.