File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1010import typing
1111import uuid
1212from uuid import UUID
13+ import sqlalchemy
1314from sqlalchemy .ext .asyncio import create_async_engine
1415from contextlib import asynccontextmanager
1516
@@ -70,6 +71,10 @@ async def init_engine(db: str, echo=False):
7071 f"Unsupported database dialect: { db } (must be sqlite:// or postgresql://)"
7172 )
7273
74+ if not sqlalchemy_utils .database_exists (db ):
75+ LOG .warning ("Database does not exist, trying to create it..." )
76+ sqlalchemy_utils .create_database (db )
77+
7378 async_engine = create_async_engine (db , echo = echo )
7479 AsyncSessionMaker = async_sessionmaker (async_engine , expire_on_commit = False )
7580
@@ -79,6 +84,12 @@ async def init_engine(db: str, echo=False):
7984 )
8085
8186 async with async_engine .begin () as conn :
87+
88+ if "postgres" in async_engine .url .drivername :
89+ rows = (await conn .execute (sqlalchemy .text ("SELECT datname FROM pg_database" ))).all ()
90+ if async_engine .url .database not in [row [0 ] for row in rows ]:
91+ await conn .execute (sqlalchemy .text (f"CREATE DATABASE { async_engine .url .database } ENCODING 'utf-8" ))
92+
8293 # Creating tables is not transactional in some databases, so we just try
8394 # our luck and if that fails, we sleep a couple of ms and try again.
8495 try :
You can’t perform that action at this time.
0 commit comments