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)
评论列表
文章目录