|
| 1 | +from collections.abc import Mapping |
| 2 | +from contextlib import contextmanager |
| 3 | +from typing import Any, Generator |
| 4 | + |
| 5 | +from adbc_driver_manager import dbapi |
| 6 | +from dagster import ConfigurableResource |
| 7 | +from pydantic import Field |
| 8 | + |
| 9 | + |
| 10 | +class ADBCResource(ConfigurableResource): |
| 11 | + """Resource for interacting with a database via ADBC. |
| 12 | + Wraps an underlying adbc_driver_manager.dbapi connection. |
| 13 | +
|
| 14 | + Examples: |
| 15 | + .. code-block:: python |
| 16 | + from dagster import Definitions, EnvVar, asset |
| 17 | + from dagster_adbc import ADBCResource |
| 18 | +
|
| 19 | +
|
| 20 | + @asset |
| 21 | + def my_table(dremio: ADBCResource) -> None: |
| 22 | + with dremio.get_connection() as connection, connection.cursor() as cursor: |
| 23 | + cursor.execute("SELECT * FROM my_table") |
| 24 | + table = cursor.fetch_arrow_table() |
| 25 | +
|
| 26 | +
|
| 27 | + defs = Definitions( |
| 28 | + assets=[my_table], |
| 29 | + resources={ |
| 30 | + "dremio": ADBCResource( |
| 31 | + driver="flightsql", |
| 32 | + uri="grpc+tcp://localhost:32010", |
| 33 | + db_kwargs={"username": "admin", "password": EnvVar("DREMIO_PASSWORD")}, |
| 34 | + ) |
| 35 | + }, |
| 36 | + ) |
| 37 | + """ |
| 38 | + |
| 39 | + driver: str | None = Field(default=None, description="The driver to use.") |
| 40 | + uri: str | None = Field( |
| 41 | + default=None, description='The "uri" parameter to the database (if applicable).' |
| 42 | + ) |
| 43 | + profile: str | None = Field(default=None, description="A connection profile to load.") |
| 44 | + entrypoint: str | None = Field( |
| 45 | + default=None, |
| 46 | + description="The driver-specific entrypoint, if different than the default.", |
| 47 | + ) |
| 48 | + db_kwargs: Mapping[str, str] | None = Field( |
| 49 | + default=None, |
| 50 | + description="Key-value parameters to pass to the driver to initialize the database.", |
| 51 | + ) |
| 52 | + conn_kwargs: Mapping[str, str] | None = Field( |
| 53 | + default=None, |
| 54 | + description="Key-value parameters to pass to the driver to initialize the connection.", |
| 55 | + ) |
| 56 | + autocommit: bool = Field(default=False, description="Whether to enable autocommit.") |
| 57 | + |
| 58 | + @classmethod |
| 59 | + def _is_dagster_mainatained(cls) -> bool: |
| 60 | + return False |
| 61 | + |
| 62 | + @contextmanager |
| 63 | + def get_connection(self) -> Generator[dbapi.Connection, Any, None]: |
| 64 | + connection = dbapi.connect( |
| 65 | + driver=self.driver, |
| 66 | + uri=self.uri, |
| 67 | + profile=self.profile, |
| 68 | + entrypoint=self.entrypoint, |
| 69 | + db_kwargs=self.db_kwargs, |
| 70 | + conn_kwargs=self.conn_kwargs, |
| 71 | + autocommit=self.autocommit, |
| 72 | + ) |
| 73 | + try: |
| 74 | + yield connection |
| 75 | + finally: |
| 76 | + connection.close() |
0 commit comments