|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from typing import TYPE_CHECKING, Any, Dict, List, MutableMapping, Optional, Tuple, Union, cast |
| 5 | + |
| 6 | +from sqlalchemy.engine import AdaptedConnection |
| 7 | +from sqlalchemy.util.concurrency import await_only |
| 8 | + |
| 9 | +import pyathena |
| 10 | +from pyathena.aio.connection import AioConnection |
| 11 | +from pyathena.error import ( |
| 12 | + DatabaseError, |
| 13 | + DataError, |
| 14 | + Error, |
| 15 | + IntegrityError, |
| 16 | + InterfaceError, |
| 17 | + InternalError, |
| 18 | + NotSupportedError, |
| 19 | + OperationalError, |
| 20 | + ProgrammingError, |
| 21 | +) |
| 22 | +from pyathena.sqlalchemy.base import AthenaDialect |
| 23 | + |
| 24 | +if TYPE_CHECKING: |
| 25 | + from types import ModuleType |
| 26 | + |
| 27 | + from sqlalchemy import URL |
| 28 | + |
| 29 | + |
| 30 | +class AsyncAdaptPyathenaCursor: |
| 31 | + """Wraps any async PyAthena cursor with a sync DBAPI interface. |
| 32 | +
|
| 33 | + SQLAlchemy's async engine uses greenlet-based ``await_only()`` to call |
| 34 | + async methods from synchronous code running inside the greenlet context. |
| 35 | + This adapter wraps an ``AioCursor`` (or variant) so that the dialect can |
| 36 | + use a normal synchronous DBAPI interface while the underlying I/O is async. |
| 37 | + """ |
| 38 | + |
| 39 | + server_side = False |
| 40 | + __slots__ = ("_cursor",) |
| 41 | + |
| 42 | + def __init__(self, cursor: Any) -> None: |
| 43 | + self._cursor = cursor |
| 44 | + |
| 45 | + @property |
| 46 | + def description(self) -> Any: |
| 47 | + return self._cursor.description |
| 48 | + |
| 49 | + @property |
| 50 | + def rowcount(self) -> int: |
| 51 | + return self._cursor.rowcount # type: ignore[no-any-return] |
| 52 | + |
| 53 | + def close(self) -> None: |
| 54 | + self._cursor.close() |
| 55 | + |
| 56 | + def execute(self, operation: str, parameters: Any = None, **kwargs: Any) -> Any: |
| 57 | + return await_only(self._cursor.execute(operation, parameters, **kwargs)) |
| 58 | + |
| 59 | + def executemany( |
| 60 | + self, |
| 61 | + operation: str, |
| 62 | + seq_of_parameters: List[Optional[Union[Dict[str, Any], List[str]]]], |
| 63 | + **kwargs: Any, |
| 64 | + ) -> None: |
| 65 | + for parameters in seq_of_parameters: |
| 66 | + await_only(self._cursor.execute(operation, parameters, **kwargs)) |
| 67 | + |
| 68 | + def fetchone(self) -> Any: |
| 69 | + return await_only(self._cursor.fetchone()) |
| 70 | + |
| 71 | + def fetchmany(self, size: Optional[int] = None) -> Any: |
| 72 | + return await_only(self._cursor.fetchmany(size)) |
| 73 | + |
| 74 | + def fetchall(self) -> Any: |
| 75 | + return await_only(self._cursor.fetchall()) |
| 76 | + |
| 77 | + def setinputsizes(self, sizes: Any) -> None: |
| 78 | + self._cursor.setinputsizes(sizes) |
| 79 | + |
| 80 | + # PyAthena-specific methods used by AthenaDialect reflection |
| 81 | + def list_databases(self, *args: Any, **kwargs: Any) -> Any: |
| 82 | + return await_only(self._cursor.list_databases(*args, **kwargs)) |
| 83 | + |
| 84 | + def get_table_metadata(self, *args: Any, **kwargs: Any) -> Any: |
| 85 | + return await_only(self._cursor.get_table_metadata(*args, **kwargs)) |
| 86 | + |
| 87 | + def list_table_metadata(self, *args: Any, **kwargs: Any) -> Any: |
| 88 | + return await_only(self._cursor.list_table_metadata(*args, **kwargs)) |
| 89 | + |
| 90 | + def __enter__(self) -> "AsyncAdaptPyathenaCursor": |
| 91 | + return self |
| 92 | + |
| 93 | + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: |
| 94 | + self.close() |
| 95 | + |
| 96 | + |
| 97 | +class AsyncAdaptPyathenaConnection(AdaptedConnection): |
| 98 | + """Wraps ``AioConnection`` with a sync DBAPI interface. |
| 99 | +
|
| 100 | + This adapted connection delegates ``cursor()`` to the underlying |
| 101 | + ``AioConnection`` and wraps each returned async cursor with |
| 102 | + ``AsyncAdaptPyathenaCursor``. |
| 103 | + """ |
| 104 | + |
| 105 | + await_only_ = staticmethod(await_only) |
| 106 | + |
| 107 | + __slots__ = ("dbapi", "_connection") |
| 108 | + |
| 109 | + def __init__(self, dbapi: "AsyncAdaptPyathenaDbapi", connection: AioConnection) -> None: |
| 110 | + self.dbapi = dbapi |
| 111 | + self._connection = connection |
| 112 | + |
| 113 | + @property |
| 114 | + def driver_connection(self) -> AioConnection: |
| 115 | + return self._connection # type: ignore[no-any-return] |
| 116 | + |
| 117 | + @property |
| 118 | + def catalog_name(self) -> Optional[str]: |
| 119 | + return self._connection.catalog_name # type: ignore[no-any-return] |
| 120 | + |
| 121 | + @property |
| 122 | + def schema_name(self) -> Optional[str]: |
| 123 | + return self._connection.schema_name # type: ignore[no-any-return] |
| 124 | + |
| 125 | + def cursor(self) -> AsyncAdaptPyathenaCursor: |
| 126 | + raw_cursor = self._connection.cursor() |
| 127 | + return AsyncAdaptPyathenaCursor(raw_cursor) |
| 128 | + |
| 129 | + def close(self) -> None: |
| 130 | + self._connection.close() |
| 131 | + |
| 132 | + def commit(self) -> None: |
| 133 | + self._connection.commit() |
| 134 | + |
| 135 | + def rollback(self) -> None: |
| 136 | + pass |
| 137 | + |
| 138 | + |
| 139 | +class AsyncAdaptPyathenaDbapi: |
| 140 | + """Fake DBAPI module for the async SQLAlchemy engine. |
| 141 | +
|
| 142 | + SQLAlchemy expects ``import_dbapi()`` to return a module-like object |
| 143 | + with ``connect()``, ``paramstyle``, and the standard DBAPI exception |
| 144 | + hierarchy. This class fulfils that contract while routing connections |
| 145 | + through ``AioConnection``. |
| 146 | + """ |
| 147 | + |
| 148 | + paramstyle = "pyformat" |
| 149 | + |
| 150 | + # DBAPI exception hierarchy |
| 151 | + Error = Error |
| 152 | + Warning = pyathena.Warning |
| 153 | + InterfaceError = InterfaceError |
| 154 | + DatabaseError = DatabaseError |
| 155 | + InternalError = InternalError |
| 156 | + OperationalError = OperationalError |
| 157 | + ProgrammingError = ProgrammingError |
| 158 | + IntegrityError = IntegrityError |
| 159 | + DataError = DataError |
| 160 | + NotSupportedError = NotSupportedError |
| 161 | + |
| 162 | + def connect(self, **kwargs: Any) -> AsyncAdaptPyathenaConnection: |
| 163 | + connection = await_only(AioConnection.create(**kwargs)) |
| 164 | + return AsyncAdaptPyathenaConnection(self, connection) |
| 165 | + |
| 166 | + |
| 167 | +class AthenaAioDialect(AthenaDialect): |
| 168 | + """Base async SQLAlchemy dialect for Amazon Athena. |
| 169 | +
|
| 170 | + Extends the synchronous ``AthenaDialect`` with async capability |
| 171 | + by setting ``is_async = True`` and providing an adapted DBAPI module |
| 172 | + that wraps ``AioConnection`` and async cursors. |
| 173 | +
|
| 174 | + Connection URL Format: |
| 175 | + ``awsathena+aiorest://{access_key}:{secret_key}@athena.{region}.amazonaws.com/{schema}`` |
| 176 | +
|
| 177 | + Example: |
| 178 | + >>> from sqlalchemy.ext.asyncio import create_async_engine |
| 179 | + >>> engine = create_async_engine( |
| 180 | + ... "awsathena+aiorest://:@athena.us-west-2.amazonaws.com/default" |
| 181 | + ... "?s3_staging_dir=s3://my-bucket/athena-results/" |
| 182 | + ... ) |
| 183 | +
|
| 184 | + See Also: |
| 185 | + :class:`~pyathena.sqlalchemy.base.AthenaDialect`: Synchronous base dialect. |
| 186 | + :class:`~pyathena.aio.connection.AioConnection`: Native async connection. |
| 187 | + """ |
| 188 | + |
| 189 | + is_async = True |
| 190 | + supports_statement_cache = True |
| 191 | + |
| 192 | + @classmethod |
| 193 | + def import_dbapi(cls) -> "ModuleType": |
| 194 | + return AsyncAdaptPyathenaDbapi() # type: ignore[return-value] |
| 195 | + |
| 196 | + @classmethod |
| 197 | + def dbapi(cls) -> "ModuleType": # type: ignore[override] |
| 198 | + return AsyncAdaptPyathenaDbapi() # type: ignore[return-value] |
| 199 | + |
| 200 | + def create_connect_args(self, url: "URL") -> Tuple[Tuple[str], MutableMapping[str, Any]]: |
| 201 | + opts = self._create_connect_args(url) |
| 202 | + self._connect_options = opts |
| 203 | + return cast(Tuple[str], ()), opts |
| 204 | + |
| 205 | + def get_driver_connection(self, connection: Any) -> Any: |
| 206 | + return connection |
0 commit comments