4_grade
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
|
||||
def get_dsn():
|
||||
file_path = os.environ.get("DATABASE_URL_FILE")
|
||||
if file_path and os.path.exists(file_path):
|
||||
return Path(file_path).read_text().strip()
|
||||
return os.environ.get("DATABASE_URL")
|
||||
|
||||
def main():
|
||||
dsn = get_dsn()
|
||||
if not dsn:
|
||||
print("ERROR: DATABASE_URL or DATABASE_URL_FILE not set", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
for i in range(10):
|
||||
try:
|
||||
with psycopg.connect(dsn, autocommit=True) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
break
|
||||
except psycopg.OperationalError:
|
||||
print("Waiting for database...")
|
||||
time.sleep(2)
|
||||
else:
|
||||
print("ERROR: Database is not ready", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# ВАЖНО: путь к миграциям. Раз они лежат в src/migrations:
|
||||
migrations_dir = Path(__file__).parent.parent / "src" / "migrations"
|
||||
sql_files = sorted(migrations_dir.glob("*.sql"))
|
||||
|
||||
with psycopg.connect(dsn, autocommit=True) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz DEFAULT now()
|
||||
)
|
||||
""")
|
||||
|
||||
for sql_file in sql_files:
|
||||
version = sql_file.name
|
||||
cur.execute("SELECT 1 FROM schema_migrations WHERE version = %s", (version,))
|
||||
if cur.fetchone():
|
||||
continue
|
||||
|
||||
print(f"Applying {version}...")
|
||||
sql = sql_file.read_text(encoding="utf-8")
|
||||
cur.execute(sql)
|
||||
cur.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (version,))
|
||||
print(f"Applied {version}.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
echo "Restarting API and Postgres (preserving volumes)..."
|
||||
docker compose restart api1 api2 postgres
|
||||
echo "Waiting for Postgres to be healthy..."
|
||||
sleep 5
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
if [ "$TARGET_INSTANCE_ID" != "api-1" ] && [ "$TARGET_INSTANCE_ID" != "api-2" ]; then
|
||||
echo "Unknown instance: $TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
SERVICE_NAME="$TARGET_INSTANCE_ID"
|
||||
if [ "$SERVICE_NAME" = "api-1" ]; then SERVICE_NAME="api1"; fi
|
||||
if [ "$SERVICE_NAME" = "api-2" ]; then SERVICE_NAME="api2"; fi
|
||||
|
||||
echo "Stopping container for $SERVICE_NAME..."
|
||||
docker compose stop "$SERVICE_NAME"
|
||||
Reference in New Issue
Block a user