如何创建支持方言数据类型的迁移脚本?
以下是模型的示例:
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)
这是错误:
Column('data', HSTORE), NameError: name 'HSTORE' is not defined
P.S。我也在使用Flask-sqlalchemy
迁移脚本:
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))
答案 0 :(得分:1)
迁移脚本不知道HSTORE的来源。您需要从PostgreSQL方言导入它。在您的迁移顶部放置:
from sqlalchemy.dialects.postgresql import HSTORE
答案 1 :(得分:1)
您需要导入HSTORE
。您可以通过执行以下操作将导入添加到生成的文件中:
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))