|
| 1 | +""" |
| 2 | +Async DuckDB connection helpers. |
| 3 | +""" |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +import duckdb |
| 8 | +import duckdb_engine |
| 9 | +from sqlalchemy import text |
| 10 | +from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine |
| 11 | + |
| 12 | +from aloha.logger import LOG |
| 13 | + |
| 14 | +__all__ = ("DuckOperator",) |
| 15 | + |
| 16 | +LOG.debug("duckdb_aio version = %s, duckdb_engine = %s (async)", (duckdb.__version__, duckdb_engine.__version__)) |
| 17 | + |
| 18 | + |
| 19 | +class DuckOperator: |
| 20 | + """Create and use an async DuckDB connection through SQLAlchemy.""" |
| 21 | + |
| 22 | + def __init__(self, db_config, **kwargs): |
| 23 | + """Build an async DuckDB engine, creating the database file if necessary.""" |
| 24 | + """db_config example: |
| 25 | + { |
| 26 | + "path": "/path/to/db.duckdb", # file path of duckdb, use ":memory:" for in-memory mode |
| 27 | + "schema": "sales", # optional, 'main' by default |
| 28 | + "read_only": True, # optional, False by default, (will set to False if in in-memory mode) |
| 29 | + "config": {"memory_limit": "500mb"}, # optional, duckdb connection configs |
| 30 | + } |
| 31 | + """ |
| 32 | + self._config = { |
| 33 | + "path": db_config.get("path", ":memory:"), |
| 34 | + "schema": db_config.get("schema", "main"), |
| 35 | + "read_only": bool(db_config.get("read_only", False)), |
| 36 | + "config": db_config.get("config", {}), |
| 37 | + "auto_commit": db_config.get("auto_commit", True), |
| 38 | + } |
| 39 | + |
| 40 | + if not self._config["path"] or self._config["path"] == ":memory:": |
| 41 | + self._config["path"] = ":memory:" |
| 42 | + |
| 43 | + if self._config["read_only"]: |
| 44 | + LOG.warning("In-memory database cannot be read-only. Setting read_only=False.") |
| 45 | + self._config["read_only"] = False |
| 46 | + |
| 47 | + else: |
| 48 | + self._prepare_database() |
| 49 | + |
| 50 | + try: |
| 51 | + str_connection = f"duckdb+aioduckdb:///{self._config['path']}" |
| 52 | + self.engine: AsyncEngine = create_async_engine( |
| 53 | + str_connection, |
| 54 | + connect_args={"read_only": self._config["read_only"], "config": self._config["config"]}, |
| 55 | + **kwargs, |
| 56 | + ) |
| 57 | + |
| 58 | + LOG.debug("DuckDB (async) connected: {path} [schema={schema}, read_only={read_only}]".format(**self._config)) |
| 59 | + except Exception as e: |
| 60 | + LOG.exception(e) |
| 61 | + raise RuntimeError("Failed to connect to DuckDB (async)") from e |
| 62 | + |
| 63 | + def _prepare_database(self): |
| 64 | + """Prepare the database file and its parent directory.""" |
| 65 | + path = self._config["path"] |
| 66 | + path_obj = Path(path) |
| 67 | + |
| 68 | + parent_dir = path_obj.parent |
| 69 | + if not parent_dir.exists(): |
| 70 | + if self._config["read_only"]: |
| 71 | + raise RuntimeError(f"Directory '{parent_dir}' does not exist and read_only=True") |
| 72 | + try: |
| 73 | + parent_dir.mkdir(parents=True, exist_ok=True) |
| 74 | + LOG.debug(f"Created directory: {parent_dir}") |
| 75 | + except Exception as e: |
| 76 | + raise RuntimeError(f"Failed to create directory '{parent_dir}': {e}") from e |
| 77 | + |
| 78 | + if not path_obj.exists(): |
| 79 | + if self._config["read_only"]: |
| 80 | + raise RuntimeError(f"DuckDB file '{path}' does not exist and read_only=True") |
| 81 | + try: |
| 82 | + LOG.debug(f"Database file not found, creating: {path}") |
| 83 | + duckdb.connect(path).close() |
| 84 | + except Exception as e: |
| 85 | + raise RuntimeError(f"Failed to create database file '{path}': {e}") from e |
| 86 | + |
| 87 | + @property |
| 88 | + def connection(self): |
| 89 | + return self.engine |
| 90 | + |
| 91 | + @property |
| 92 | + def conn(self): |
| 93 | + """Alias for connection property.""" |
| 94 | + return self.engine |
| 95 | + |
| 96 | + async def execute_query(self, sql, *args, **kwargs): |
| 97 | + """Execute a SQL statement asynchronously and return the cursor result.""" |
| 98 | + async with self.engine.connect() as conn: |
| 99 | + cur = await conn.execute(text(sql), *args, **kwargs) |
| 100 | + if self._config.get("auto_commit", True): |
| 101 | + await conn.commit() |
| 102 | + return cur |
| 103 | + |
| 104 | + async def execute_query_scalars(self, sql, *args, **kwargs): |
| 105 | + """Execute a SQL statement and return all scalar results.""" |
| 106 | + async with self.engine.connect() as conn: |
| 107 | + cur = await conn.stream_scalars(text(sql), *args, **kwargs) |
| 108 | + async for row in cur: |
| 109 | + yield row |
| 110 | + |
| 111 | + @property |
| 112 | + def connection_str(self) -> str: |
| 113 | + """Return a human-readable connection string.""" |
| 114 | + return ( |
| 115 | + f"duckdb:///{self._config['path']} [schema={self._config['schema']}, read_only={self._config['read_only']}] (async)" |
| 116 | + ) |
| 117 | + |
| 118 | + async def close(self): |
| 119 | + """Close the async engine and all connections.""" |
| 120 | + await self.engine.dispose() |
| 121 | + |
| 122 | + async def __aenter__(self): |
| 123 | + """Async context manager entry.""" |
| 124 | + return self |
| 125 | + |
| 126 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 127 | + """Async context manager exit.""" |
| 128 | + await self.close() |
0 commit comments