def rollback_migrations():
lower = -1
upper = -1
with database.Cursor() as cursor:
cursor.prepare("SELECT version FROM __migrations ORDER BY version DESC LIMIT 2")
cursor.exec_()
if cursor.next():
upper = int(cursor.value("version"))
if cursor.next():
lower = int(cursor.value("version"))
should_apply = False
migration_file, migration_name = tempfile.mkstemp()
for migration in sorted(os.listdir("../migrations"), reverse=True):
nb = int(migration.split("_")[0])
if lower < nb <= upper:
should_apply = True
print(f"Rollback {migration}")
with open(os.path.join("../migrations", migration, "down.sql")) as fd:
os.write(migration_file, fd.read().encode())
os.write(migration_file, f"DELETE FROM __migrations WHERE version={upper};\n".encode())
if should_apply:
execute_sql_file(migration_name)
else:
print("Nothing to do")
os.remove(migration_name)
评论列表
文章目录