manage.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:mybookshelf2 作者: izderadicka 项目源码 文件源码
def migrate_tables():
    import psycopg2
    print('This will migrate database to latest schema, you are advised to backup database before running this command')
    if prompt_bool('Do you want to continue?'):
        mdir = os.path.join(SQL_DIR, 'migration')
        version_obj=model.Version.query.one_or_none()

        if not version_obj:
                version_obj=model.Version(version=0, version_id=1)
                db.session.add(version_obj)
        old_version = version_obj.version
        if old_version == db_version:
            print('DB is at correct version %d'% old_version)
        scripts = []
        for script in os.listdir(mdir):
            m=re.match(r'v(\d+)\.sql', script)
            if m:
                version = int(m.group(1))
                if version <= db_version and version > old_version:
                    scripts.append((version, os.path.join(mdir,script)))

        scripts.sort()
        connection = psycopg2.connect(database=settings.DB_NAME,
                                      user = settings.DB_USER,
                                      password = settings.DB_PASSWORD,
                                      host = settings.DB_HOST,
                                      port = settings.DB_PORT)
        connection.autocommit = True
        #connection = db.engine.raw_connection()  # @UndefinedVariable
        try:
            c = connection.cursor()
            for v,fname in scripts:
                script = open(fname, 'rt', encoding='utf-8-sig').read()
                print('Upgrading database to version %d'% v)
                res = c.execute(script)
                version_obj.version = v
                db.session.commit()
                #connection.commit()
        finally:
            connection.close()
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号