Complete lab
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine, func, insert, select
|
||||
from sqlalchemy.engine import URL, make_url
|
||||
|
||||
from .models import SchemaMigration
|
||||
|
||||
|
||||
def database_url():
|
||||
if os.getenv('DATABASE_URL'):
|
||||
url = make_url(os.environ['DATABASE_URL'])
|
||||
if url.drivername in ('postgres', 'postgresql'):
|
||||
url = url.set(drivername='postgresql+psycopg')
|
||||
if url.drivername != 'postgresql+psycopg':
|
||||
raise ValueError('DATABASE_URL must use PostgreSQL with psycopg')
|
||||
return url
|
||||
return URL.create(
|
||||
'postgresql+psycopg', host=os.getenv('POSTGRES_HOST', 'postgres'),
|
||||
database=os.getenv('POSTGRES_DB', 'messenger'),
|
||||
username=os.getenv('POSTGRES_USER', 'messenger'),
|
||||
password=os.environ['POSTGRES_PASSWORD'],
|
||||
)
|
||||
|
||||
|
||||
def create_db_engine():
|
||||
return create_engine(
|
||||
database_url(), pool_size=10, max_overflow=0, pool_timeout=2, pool_pre_ping=True,
|
||||
connect_args={'connect_timeout': 2,
|
||||
'options': '-c statement_timeout=3000 -c lock_timeout=2000'},
|
||||
)
|
||||
|
||||
|
||||
def migrate(engine):
|
||||
with engine.begin() as conn:
|
||||
conn.execute(select(func.pg_advisory_xact_lock(202602)))
|
||||
SchemaMigration.__table__.create(conn, checkfirst=True)
|
||||
applied = set(conn.scalars(select(SchemaMigration.version)))
|
||||
for path in sorted((Path(__file__).resolve().parents[1] / 'migrations').glob('*.sql')):
|
||||
if path.name not in applied:
|
||||
conn.exec_driver_sql(path.read_text(encoding='utf-8'))
|
||||
conn.execute(insert(SchemaMigration).values(version=path.name))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
engine = create_db_engine()
|
||||
try:
|
||||
migrate(engine)
|
||||
print('Migrations applied')
|
||||
finally:
|
||||
engine.dispose()
|
||||
Reference in New Issue
Block a user