|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from sqlite3 import OperationalError |
| 3 | + |
| 4 | +from sqlalchemy import create_engine |
| 5 | +from sqlalchemy.orm import sessionmaker |
| 6 | + |
| 7 | +from jupyter_scheduler.orm import Base as DefaultBase |
| 8 | +from jupyter_scheduler.orm import update_db_schema |
| 9 | + |
| 10 | + |
| 11 | +class DatabaseManager(ABC): |
| 12 | + """Base class for database managers. |
| 13 | +
|
| 14 | + Database managers handle database operations for jupyter-scheduler. |
| 15 | + Subclasses can implement custom storage backends (K8s, Redis, etc.) |
| 16 | + while maintaining compatibility with the scheduler's session interface. |
| 17 | + """ |
| 18 | + |
| 19 | + @abstractmethod |
| 20 | + def create_session(self, db_url: str): |
| 21 | + """Create a database session. |
| 22 | +
|
| 23 | + Args: |
| 24 | + db_url: Database URL (e.g., "k8s://namespace", "redis://localhost") |
| 25 | +
|
| 26 | + Returns: |
| 27 | + Session object compatible with SQLAlchemy session interface |
| 28 | + """ |
| 29 | + pass |
| 30 | + |
| 31 | + @abstractmethod |
| 32 | + def create_tables(self, db_url: str, drop_tables: bool = False, Base=None): |
| 33 | + """Create database tables/schema. |
| 34 | +
|
| 35 | + Args: |
| 36 | + db_url: Database URL |
| 37 | + drop_tables: Whether to drop existing tables first |
| 38 | + Base: SQLAlchemy Base for custom schemas (tests) |
| 39 | + """ |
| 40 | + pass |
| 41 | + |
| 42 | + |
| 43 | +class SQLAlchemyDatabaseManager(DatabaseManager): |
| 44 | + """Default database manager using SQLAlchemy.""" |
| 45 | + |
| 46 | + def create_session(self, db_url: str): |
| 47 | + """Create SQLAlchemy session factory.""" |
| 48 | + engine = create_engine(db_url, echo=False) |
| 49 | + Session = sessionmaker(bind=engine) |
| 50 | + return Session |
| 51 | + |
| 52 | + def create_tables(self, db_url: str, drop_tables: bool = False, Base=None): |
| 53 | + """Create database tables using SQLAlchemy.""" |
| 54 | + if Base is None: |
| 55 | + Base = DefaultBase |
| 56 | + |
| 57 | + engine = create_engine(db_url) |
| 58 | + update_db_schema(engine, Base) |
| 59 | + |
| 60 | + try: |
| 61 | + if drop_tables: |
| 62 | + Base.metadata.drop_all(engine) |
| 63 | + except OperationalError: |
| 64 | + pass |
| 65 | + finally: |
| 66 | + Base.metadata.create_all(engine) |
0 commit comments