13

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?

Greg
  • 8,175
  • 16
  • 72
  • 125

2 Answers2

20

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    As mentioned at [TestDriven.io Post](https://testdriven.io/blog/fastapi-sqlmodel/) too. – Doren Nov 29 '21 at 16:15
  • Three is a PR for this here, you can look in the comments and see the instructions there too: https://github.com/tiangolo/sqlmodel/pull/512 – GuySoft May 19 '23 at 08:03
0

Here you can find a fastapi-alembic and SQLmodel integration with async PostgreSQL database https://github.com/jonra1993/fastapi-sqlmodel-alembic

Jonathan Vargas
  • 256
  • 1
  • 4
  • 8