Skip to content

Commit 1194bf9

Browse files
committed
Create database if it does not exist
1 parent 6b2f34c commit 1194bf9

1 file changed

Lines changed: 11 additions & 0 deletions

File tree

bbblb/model.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import typing
1111
import uuid
1212
from uuid import UUID
13+
import sqlalchemy
1314
from sqlalchemy.ext.asyncio import create_async_engine
1415
from 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:

0 commit comments

Comments
 (0)