migrations.py 文件源码

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

项目:Enibar 作者: ENIB 项目源码 文件源码
def apply_migrations():
    # Get the latest applied migration
    with database.Cursor() as cursor:
        cursor.prepare("SELECT version FROM __migrations ORDER BY version DESC LIMIT 1")
        cursor.exec_()
        last_applied = -1
        if cursor.next():
            last_applied = cursor.value("version")

    migration_file, migration_name = tempfile.mkstemp()

    should_apply = False
    nb = 0
    for migration in sorted(os.listdir("../migrations")):
        nb = int(migration.split("_")[0])
        if nb <= last_applied:
            continue
        should_apply = True
        print(f"Applying {migration}")
        with open(os.path.join("../migrations", migration, "up.sql")) as fd:
            os.write(migration_file, fd.read().encode())

    if not should_apply:
        print("Nothing to do")
        sys.exit(1)

    os.write(migration_file, f"INSERT INTO __migrations(version) VALUES({nb});\n".encode())

    # Execute the generated file.
    execute_sql_file(migration_name)

    # Since mkstemp doesn't handle automatically the file deletion, do it
    # ourselves
    os.remove(migration_name)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号