Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy + alembic: create schema migration

I'm not sure how to define a create schema foo migration? My Model looks like this (I'm using Flask-Migrate):

class MyTable(db.Model):
    __tablename__ = "my_table"
    __table_args__ = {"schema": "foo"}

    id = ColumnPrimKey()
    name = Column(Text, unique=True, nullable=False)

When I execute mange db upgrade I get a failure because the schema "foo" does not exist. How can I add a migration for the schema with SQLAlchemy and Alembic?

like image 245
s5s Avatar asked Mar 30 '18 22:03

s5s


People also ask

How do I create a schema in SQLAlchemy?

You can also import the method as such: from sqlalchemy. schema import CreateSchema . And use it directly with engine. execute(CreateSchema(schema_name)) .

How do I get rid of migration in alembic?

There's currently no command to delete migrations from your versions directory, so if you want to completely wipe away all trace of your bad migration, you'll need to delete the version file (like 4c009570237e_add_widget_table.py ) manually.


1 Answers

I accomplished this by modifying the migration upgrade command to first run:

op.execute("create schema foo")

And in the downgrade function

op.execute("drop schema foo")

So the whole migration file looks something like:

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '6c82c972c61e'
down_revision = '553260b3e828'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("create schema foo")
    ...

def downgrade():
    ...
    op.execute("drop schema foo")
like image 162
buck Avatar answered Sep 21 '22 01:09

buck