Skip to content

Commit

Permalink
Fix: initialise schools on launch
Browse files Browse the repository at this point in the history
  • Loading branch information
Rotheem committed Nov 19, 2024
1 parent 3e20d0d commit 455a01b
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
31 changes: 31 additions & 0 deletions app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from app.core.google_api.google_api import GoogleAPI
from app.core.groups.groups_type import GroupType
from app.core.log import LogConfig
from app.core.schools.schools_type import SchoolType
from app.dependencies import (
get_db,
get_redis_client,
Expand Down Expand Up @@ -185,6 +186,32 @@ def initialize_groups(
)


def initialize_schools(
sync_engine: Engine,
hyperion_error_logger: logging.Logger,
) -> None:
"""Add the necessary shools"""

hyperion_error_logger.info("Startup: Adding new groups to the database")
with Session(sync_engine) as db:
for school in SchoolType:
exists = initialization.get_school_by_id_sync(school_id=school, db=db)
# We don't want to recreate the groups if they already exist
if not exists:
db_school = models_core.CoreSchool(
id=school,
name=school.name,
email_regex=".*",
)

try:
initialization.create_school_sync(school=db_school, db=db)
except IntegrityError as error:
hyperion_error_logger.fatal(
f"Startup: Could not add group {db_school.name}<{db_school.id}> in the database: {error}",
)


def initialize_module_visibility(
sync_engine: Engine,
hyperion_error_logger: logging.Logger,
Expand Down Expand Up @@ -299,6 +326,10 @@ def init_db(
sync_engine=sync_engine,
hyperion_error_logger=hyperion_error_logger,
)
initialize_schools(
sync_engine=sync_engine,
hyperion_error_logger=hyperion_error_logger,
)
initialize_module_visibility(
sync_engine=sync_engine,
hyperion_error_logger=hyperion_error_logger,
Expand Down
27 changes: 27 additions & 0 deletions app/utils/initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,33 @@ def set_core_data_sync(
return core_data


def get_school_by_id_sync(school_id: str, db: Session) -> models_core.CoreSchool | None:
"""
Return group with id from database
"""
result = db.execute(
select(models_core.CoreSchool).where(models_core.CoreSchool.id == school_id),
)
return result.scalars().first()


def create_school_sync(
school: models_core.CoreSchool,
db: Session,
) -> models_core.CoreSchool:
"""
Create a new group in database and return it
"""
db.add(school)
try:
db.commit()
except IntegrityError:
db.rollback()
raise
else:
return school


def drop_db_sync(conn: Connection):
"""
Drop all tables in the database
Expand Down

0 comments on commit 455a01b

Please sign in to comment.