5

I'm trying to use flask, sqlalchemy, and flask_migrate...

But every time run manage.py migrate, alembic always detect my model as a new table.

I think that I put __table_args__ in my model to store table in a different postgres schema:

class Entry(db.Model):
    __table_args__ = {'schema': app.config['BASE_SCH']}
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    slug = db.Column(db.String(100), unique=True)
    body = db.Column(db.Text)
    status = db.Column(db.SmallInteger, default=STATUS_PUBLIC)
    created_timestamp = db.Column(db.DateTime, default=datetime.datetime.now)
    modified_timestamp = db.Column(db.DateTime, default=datetime.datetime.now,
                                   onupdate=datetime.datetime.now)

If I delete the __table_args__ line of my model, the flask migrate works properly. Storing my table in public postgres schema.

So, how can I use different postgres table schemas with flask?

3
  • Did you check the generated migration script? I assume it is missing the schema, maybe if you add it manually things will work for you. Commented Nov 14, 2016 at 5:00
  • Hi @Miguel, thank you for your comment... In the migration script there is a schema definition in the end of each create table block. I suspect that perhaps the alembic not be able to recognize during migration different table schemes (postgres). Commented Nov 14, 2016 at 12:52
  • I have the exact same issue - have a model that is not in the default schema, initial migration looks good (has the schema specified) and running it does create the table in the correct schema. But the next call to flask db migrate creates a new migration that's an exact duplicate of the first one, like Alembic is not seeing that the table already exists in the DB. Commented Nov 30, 2017 at 4:18

1 Answer 1

8

Finally figured this out: there is an include_schemas option in configure that you have to set to True to force Alembic to scan all schemas before generating the migration.

(Slightly) more details: http://alembic.zzzcomputing.com/en/latest/api/runtime.html#alembic.runtime.environment.EnvironmentContext.configure.params.include_schemas

It's not completely clear to me why Alembic/Flask-Migrate was generating the migrations for tables in non default schemas without this option set in the first place... or rather, the fact that it would create migrations for non default schemas but not discover these tables in the DB is a surprising behavior.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.