pythonsqlalchemysqlalchemy-migrate

How to create a migration script with dialect types (HSTORE) in SQLAlchemy-Migrate?


How do you create a migration script that supports dialect data types?

Here's an example of a model:

db = SQLAlchemy()


class Event(db.Model):
    __tablename__ = 'event'

    id = db.Column(db.Integer, primary_key=True)
    created_at = db.Column(db.DateTime, server_default=text('NOW()'), primary_key=True)
    data = db.Column(HSTORE)

Here's the error:

Column('data', HSTORE), NameError: name 'HSTORE' is not defined

P.s. I'm using Flask-sqlalchemy too

Migration script:

def migrate(db):
    repo, uri = get_config(db)
    migration = repo + '/versions/%03d_migration.py' % (
        api.db_version(uri, repo) + 1)
    tmp_module = imp.new_module('old_model')
    old_model = api.create_model(uri, repo)
    exec old_model in tmp_module.__dict__
    script = api.make_update_script_for_model(uri, repo, tmp_module.meta, db.metadata)
    open(migration, "wt").write(script)
    api.upgrade(uri, repo)
    print 'New migration saved as ' + migration
    print 'Current database version: ' + str(api.db_version(uri, repo))

Solution

  • The migration script doesn't know where HSTORE comes from. You need to import it from the PostgreSQL dialect. At the top of your migration put:

    from sqlalchemy.dialects.postgresql import HSTORE