26 lines
937 B
Python
26 lines
937 B
Python
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
import psycopg
|
||
|
|
|
||
|
|
from .config import settings
|
||
|
|
|
||
|
|
|
||
|
|
def main() -> None:
|
||
|
|
migration_dir = Path(__file__).resolve().parent.parent / "migrations"
|
||
|
|
with psycopg.connect(settings.database_url) as connection:
|
||
|
|
connection.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())")
|
||
|
|
connection.commit()
|
||
|
|
for path in sorted(migration_dir.glob("*.sql")):
|
||
|
|
version = path.name
|
||
|
|
applied = connection.execute("SELECT 1 FROM schema_migrations WHERE version = %s", (version,)).fetchone()
|
||
|
|
if applied:
|
||
|
|
continue
|
||
|
|
connection.execute(path.read_text(encoding="utf-8"))
|
||
|
|
connection.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (version,))
|
||
|
|
connection.commit()
|
||
|
|
print(f"applied {version}")
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
main()
|