Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🤖 Enhance Database Initialization with Logging and Prevent Re-initialization #1606

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/seer/db.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import contextlib
import datetime
import json
import logging
from enum import StrEnum
from typing import Any, List, Optional


import sqlalchemy
from flask import Flask
from flask_migrate import Migrate
Expand Down Expand Up @@ -35,20 +37,32 @@
from seer.configuration import AppConfig
from seer.dependency_injection import inject, injected

logger = logging.getLogger(__name__)
_db_initialized = False

@inject
def initialize_database(
config: AppConfig = injected,
app: Flask = injected,
):
global _db_initialized

if _db_initialized and hasattr(app, 'extensions') and 'sqlalchemy' in app.extensions:
logger.debug("SQLAlchemy already initialized for this Flask app instance")
return

logger.debug("Initializing SQLAlchemy for Flask app")
app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URL
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"connect_args": {"prepare_threshold": None}}


db.init_app(app)
migrate.init_app(app, db)


with app.app_context():
Session.configure(bind=db.engine)
_db_initialized = True


class Base(DeclarativeBase):
Expand Down
Loading