DiogoNeves
DiogoNeves

Reputation: 1777

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))

Upvotes: 0

Views: 422

Answers (2)

Alexis Benoist
Alexis Benoist

Reputation: 2410

You need to import HSTORE. You can add the import to the generated file by doing:

def migrate(db):
    extra_imports = 'from sqlalchemy.dialects.postgresql import HSTORE\n'  # your imports
    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 = extra_imports + api.make_update_script_for_model(uri, repo, tmp_module.meta, db.metadata)  # just add the imports at the top of the migration script.

    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))

Upvotes: 1

davidism
davidism

Reputation: 127410

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

Upvotes: 1

Related Questions