From d07cd795608eb7de7897dd152971c8330344f979 Mon Sep 17 00:00:00 2001 From: phil Date: Sat, 28 Jun 2025 13:28:28 +0200 Subject: [PATCH] Fix create_db (on startup, for testing, CI) --- src/gisaf/database.py | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/src/gisaf/database.py b/src/gisaf/database.py index 0717c92..f1e8d63 100644 --- a/src/gisaf/database.py +++ b/src/gisaf/database.py @@ -166,9 +166,24 @@ async def create_db(drop=False): async with engine.begin() as conn: await create_schemas(conn) async with engine.begin() as conn: + # Import modules to populate the SQLModel metadata + from gisaf.models import admin + from gisaf.models import authentication + from gisaf.models import category + from gisaf.models import dashboard + from gisaf.models import geo_models_base + from gisaf.models import info + from gisaf.models import misc + from gisaf.models import project + from gisaf.models import raw_survey + from gisaf.models import reconcile + from gisaf.models import survey + from gisaf.models import tags + if drop: await conn.run_sync(SQLModel.metadata.drop_all) - await conn.run_sync(SQLModel.metadata.create_all) + resp = await conn.run_sync(SQLModel.metadata.create_all) + pass logger.debug(f"Connect to database with config: {conf.db}") while attempts > 0: @@ -186,9 +201,7 @@ async def create_db(drop=False): await populate_init_db() return else: - logger.warning( - f"Cannot connect to database after {CREATE_DB_TIMEOUT}, giving up." - ) + logger.warning(f"Cannot connect to database after {CREATE_DB_TIMEOUT}, giving up.") exit(1) @@ -196,6 +209,15 @@ async def is_fresh_install() -> bool: """Detect is the database is newly created, without data""" from gisaf.models.authentication import User + async with engine.begin() as conn: + has_table_query = """ + SELECT count(tablename) + FROM pg_catalog.pg_tables + WHERE schemaname = 'gisaf_admin' and tablename='user'""" + resp = await conn.execute(text(has_table_query)) + if resp.scalar() == 0: + return True + async with db_session() as session: nb_users = (await session.exec(select(func.count(col(User.username))))).one() return nb_users == 0 @@ -222,9 +244,7 @@ async def populate_init_db(): from gisaf.models.map_bases import BaseStyle logger.info("Populating initial database") - async with db_session() as session: - user = await create_user( session=session, username="admin",