|
| 1 | +import duckdb |
| 2 | +import pandas as pd |
| 3 | +from typing import Optional, Dict, List, ContextManager |
| 4 | +import time |
| 5 | +from flask import session |
| 6 | +import tempfile |
| 7 | +import os |
| 8 | +from contextlib import contextmanager |
| 9 | + |
| 10 | +class DuckDBManager: |
| 11 | + def __init__(self): |
| 12 | + # Store session db file paths |
| 13 | + self._db_files: Dict[str, str] = {} |
| 14 | + |
| 15 | + @contextmanager |
| 16 | + def connection(self, session_id: str) -> ContextManager[duckdb.DuckDBPyConnection]: |
| 17 | + """Get a DuckDB connection as a context manager that will be closed when exiting the context""" |
| 18 | + conn = None |
| 19 | + try: |
| 20 | + conn = self._get_connection(session_id) |
| 21 | + yield conn |
| 22 | + finally: |
| 23 | + # Close the connection after use |
| 24 | + if conn: |
| 25 | + conn.close() |
| 26 | + |
| 27 | + def _get_connection(self, session_id: str) -> duckdb.DuckDBPyConnection: |
| 28 | + """Internal method to get or create a DuckDB connection for a session""" |
| 29 | + # Get or create the db file path for this session |
| 30 | + if session_id not in self._db_files: |
| 31 | + db_file = os.path.join(tempfile.gettempdir(), f"df_{session_id}.db") |
| 32 | + print(f"Creating new db file: {db_file}") |
| 33 | + self._db_files[session_id] = db_file |
| 34 | + else: |
| 35 | + print(f"Using existing db file: {self._db_files[session_id]}") |
| 36 | + db_file = self._db_files[session_id] |
| 37 | + |
| 38 | + # Create a fresh connection to the database file |
| 39 | + conn = duckdb.connect(database=db_file) |
| 40 | + return conn |
| 41 | + |
| 42 | + |
| 43 | +# Initialize the DB manager |
| 44 | +db_manager = DuckDBManager() |
0 commit comments