|
1 | | -import weakref |
2 | 1 | from typing import Optional |
3 | 2 |
|
4 | 3 | import duckdb |
|
7 | 6 |
|
8 | 7 |
|
9 | 8 | class DuckDBConnectionManager: |
10 | | - _instance = None |
11 | | - |
12 | | - def __new__(cls): |
13 | | - if cls._instance is None: |
14 | | - cls._instance = super(DuckDBConnectionManager, cls).__new__(cls) |
15 | | - cls._instance._init_connection() |
16 | | - weakref.finalize(cls._instance, cls._close_connection) |
17 | | - return cls._instance |
18 | | - |
19 | | - def _init_connection(self): |
| 9 | + def __init__(self): |
20 | 10 | """Initialize a DuckDB connection.""" |
21 | 11 | self.connection = duckdb.connect() |
22 | 12 | self._registered_tables = set() |
23 | 13 |
|
24 | | - @classmethod |
25 | | - def _close_connection(cls): |
26 | | - """Closes the DuckDB connection when the instance is deleted.""" |
27 | | - if cls._instance and hasattr(cls._instance, "connection"): |
28 | | - cls._instance.connection.close() |
29 | | - cls._instance = None |
| 14 | + def __del__(self): |
| 15 | + """Destructor to ensure the DuckDB connection is closed.""" |
| 16 | + self.close() |
30 | 17 |
|
31 | 18 | def register(self, name: str, df): |
32 | 19 | """Registers a DataFrame as a DuckDB table.""" |
33 | 20 | self.connection.register(name, df) |
34 | 21 | self._registered_tables.add(name) |
35 | 22 |
|
| 23 | + def unregister(self, name: str): |
| 24 | + """Unregister a previously registered DuckDB table.""" |
| 25 | + if name in self._registered_tables: |
| 26 | + self.connection.unregister(name) |
| 27 | + self._registered_tables.remove(name) |
| 28 | + |
36 | 29 | def sql(self, query: str, params: Optional[list] = None): |
37 | 30 | """Executes an SQL query and returns the result as a Pandas DataFrame.""" |
38 | 31 | query = SQLParser.transpile_sql_dialect(query, to_dialect="duckdb") |
39 | 32 | return self.connection.sql(query, params=params) |
40 | 33 |
|
41 | 34 | def close(self): |
42 | | - """Manually close the connection if needed.""" |
43 | | - self._close_connection() |
| 35 | + """Closes the DuckDB connection.""" |
| 36 | + if hasattr(self, "connection") and self.connection: |
| 37 | + self.connection.close() |
| 38 | + self.connection = None |
| 39 | + self._registered_tables.clear() |
0 commit comments