summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/ext/asyncio
diff options
context:
space:
mode:
Diffstat (limited to 'lib/sqlalchemy/ext/asyncio')
-rw-r--r--lib/sqlalchemy/ext/asyncio/base.py2
-rw-r--r--lib/sqlalchemy/ext/asyncio/engine.py72
-rw-r--r--lib/sqlalchemy/ext/asyncio/result.py42
-rw-r--r--lib/sqlalchemy/ext/asyncio/session.py42
4 files changed, 41 insertions, 117 deletions
diff --git a/lib/sqlalchemy/ext/asyncio/base.py b/lib/sqlalchemy/ext/asyncio/base.py
index d11b059fd..76a2fbbde 100644
--- a/lib/sqlalchemy/ext/asyncio/base.py
+++ b/lib/sqlalchemy/ext/asyncio/base.py
@@ -5,7 +5,7 @@ from . import exc as async_exc
class StartableContext(abc.ABC):
@abc.abstractmethod
- async def start(self, is_ctxmanager=False) -> "StartableContext":
+ async def start(self, is_ctxmanager=False):
pass
def __await__(self):
diff --git a/lib/sqlalchemy/ext/asyncio/engine.py b/lib/sqlalchemy/ext/asyncio/engine.py
index 17ddb614a..9cd3cb2f8 100644
--- a/lib/sqlalchemy/ext/asyncio/engine.py
+++ b/lib/sqlalchemy/ext/asyncio/engine.py
@@ -4,12 +4,6 @@
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-from typing import Any
-from typing import Callable
-from typing import Mapping
-from typing import Optional
-
from . import exc as async_exc
from .base import ProxyComparable
from .base import StartableContext
@@ -17,11 +11,8 @@ from .result import AsyncResult
from ... import exc
from ... import util
from ...engine import create_engine as _create_engine
-from ...engine import Result
-from ...engine import Transaction
from ...future import Connection
from ...future import Engine
-from ...sql import Executable
from ...util.concurrency import greenlet_spawn
@@ -92,11 +83,7 @@ class AsyncConnection(ProxyComparable, StartableContext, AsyncConnectable):
"sync_connection",
)
- def __init__(
- self,
- async_engine: "AsyncEngine",
- sync_connection: Optional[Connection] = None,
- ):
+ def __init__(self, async_engine, sync_connection=None):
self.engine = async_engine
self.sync_engine = async_engine.sync_engine
self.sync_connection = sync_connection
@@ -162,12 +149,12 @@ class AsyncConnection(ProxyComparable, StartableContext, AsyncConnectable):
self._raise_for_not_started()
return self.sync_connection
- def begin(self) -> "AsyncTransaction":
+ def begin(self):
"""Begin a transaction prior to autobegin occurring."""
self._sync_connection()
return AsyncTransaction(self)
- def begin_nested(self) -> "AsyncTransaction":
+ def begin_nested(self):
"""Begin a nested transaction and return a transaction handle."""
self._sync_connection()
return AsyncTransaction(self, nested=True)
@@ -316,10 +303,10 @@ class AsyncConnection(ProxyComparable, StartableContext, AsyncConnectable):
async def exec_driver_sql(
self,
- statement: Executable,
- parameters: Optional[Mapping] = None,
- execution_options: Mapping = util.EMPTY_DICT,
- ) -> Result:
+ statement,
+ parameters=None,
+ execution_options=util.EMPTY_DICT,
+ ):
r"""Executes a driver-level SQL string and return buffered
:class:`_engine.Result`.
@@ -346,10 +333,10 @@ class AsyncConnection(ProxyComparable, StartableContext, AsyncConnectable):
async def stream(
self,
- statement: Executable,
- parameters: Optional[Mapping] = None,
- execution_options: Mapping = util.EMPTY_DICT,
- ) -> AsyncResult:
+ statement,
+ parameters=None,
+ execution_options=util.EMPTY_DICT,
+ ):
"""Execute a statement and return a streaming
:class:`_asyncio.AsyncResult` object."""
@@ -371,10 +358,10 @@ class AsyncConnection(ProxyComparable, StartableContext, AsyncConnectable):
async def execute(
self,
- statement: Executable,
- parameters: Optional[Mapping] = None,
- execution_options: Mapping = util.EMPTY_DICT,
- ) -> Result:
+ statement,
+ parameters=None,
+ execution_options=util.EMPTY_DICT,
+ ):
r"""Executes a SQL statement construct and return a buffered
:class:`_engine.Result`.
@@ -426,10 +413,10 @@ class AsyncConnection(ProxyComparable, StartableContext, AsyncConnectable):
async def scalar(
self,
- statement: Executable,
- parameters: Optional[Mapping] = None,
- execution_options: Mapping = util.EMPTY_DICT,
- ) -> Any:
+ statement,
+ parameters=None,
+ execution_options=util.EMPTY_DICT,
+ ):
r"""Executes a SQL statement construct and returns a scalar object.
This method is shorthand for invoking the
@@ -443,7 +430,7 @@ class AsyncConnection(ProxyComparable, StartableContext, AsyncConnectable):
result = await self.execute(statement, parameters, execution_options)
return result.scalar()
- async def run_sync(self, fn: Callable, *arg, **kw) -> Any:
+ async def run_sync(self, fn, *arg, **kw):
"""Invoke the given sync callable passing self as the first argument.
This method maintains the asyncio event loop all the way through
@@ -529,7 +516,7 @@ class AsyncEngine(ProxyComparable, AsyncConnectable):
await self.transaction.__aexit__(type_, value, traceback)
await self.conn.close()
- def __init__(self, sync_engine: Engine):
+ def __init__(self, sync_engine):
if not sync_engine.dialect.is_async:
raise exc.InvalidRequestError(
"The asyncio extension requires an async driver to be used. "
@@ -555,7 +542,7 @@ class AsyncEngine(ProxyComparable, AsyncConnectable):
conn = self.connect()
return self._trans_ctx(conn)
- def connect(self) -> AsyncConnection:
+ def connect(self):
"""Return an :class:`_asyncio.AsyncConnection` object.
The :class:`_asyncio.AsyncConnection` will procure a database
@@ -573,7 +560,7 @@ class AsyncEngine(ProxyComparable, AsyncConnectable):
return self._connection_cls(self)
- async def raw_connection(self) -> Any:
+ async def raw_connection(self):
"""Return a "raw" DBAPI connection from the connection pool.
.. seealso::
@@ -617,17 +604,14 @@ class AsyncTransaction(ProxyComparable, StartableContext):
__slots__ = ("connection", "sync_transaction", "nested")
- def __init__(self, connection: AsyncConnection, nested: bool = False):
+ def __init__(self, connection, nested=False):
self.connection = connection
- self.sync_transaction: Optional[Transaction] = None
+ self.sync_transaction = None
self.nested = nested
@classmethod
def _from_existing_transaction(
- cls,
- connection: AsyncConnection,
- sync_transaction: Transaction,
- nested: bool = False,
+ cls, connection, sync_transaction, nested=False
):
obj = cls.__new__(cls)
obj.connection = connection
@@ -645,11 +629,11 @@ class AsyncTransaction(ProxyComparable, StartableContext):
return self.sync_transaction
@property
- def is_valid(self) -> bool:
+ def is_valid(self):
return self._sync_transaction().is_valid
@property
- def is_active(self) -> bool:
+ def is_active(self):
return self._sync_transaction().is_active
async def close(self):
diff --git a/lib/sqlalchemy/ext/asyncio/result.py b/lib/sqlalchemy/ext/asyncio/result.py
index 6899fe0a6..4781b3ead 100644
--- a/lib/sqlalchemy/ext/asyncio/result.py
+++ b/lib/sqlalchemy/ext/asyncio/result.py
@@ -7,23 +7,12 @@
import operator
-from ... import util
from ...engine.result import _NO_ROW
from ...engine.result import FilterResult
from ...engine.result import FrozenResult
from ...engine.result import MergedResult
from ...util.concurrency import greenlet_spawn
-if util.TYPE_CHECKING:
- from typing import Any
- from typing import Int
- from typing import Iterator
- from typing import List
- from typing import Mapping
- from typing import Optional
-
- from ...engine.result import Row
-
class AsyncCommon(FilterResult):
async def close(self):
@@ -77,7 +66,6 @@ class AsyncResult(AsyncCommon):
return self
def columns(self, *col_expressions):
- # type: (*object) -> AsyncResult
r"""Establish the columns that should be returned in each row.
Refer to :meth:`_engine.Result.columns` in the synchronous
@@ -88,7 +76,6 @@ class AsyncResult(AsyncCommon):
return self._column_slices(col_expressions)
async def partitions(self, size=None):
- # type: (Optional[Int]) -> Iterator[List[Any]]
"""Iterate through sub-lists of rows of the size given.
An async iterator is returned::
@@ -115,7 +102,6 @@ class AsyncResult(AsyncCommon):
break
async def fetchone(self):
- # type: () -> Row
"""Fetch one row.
When all rows are exhausted, returns None.
@@ -138,7 +124,6 @@ class AsyncResult(AsyncCommon):
return row
async def fetchmany(self, size=None):
- # type: (Optional[Int]) -> List[Row]
"""Fetch many rows.
When all rows are exhausted, returns an empty list.
@@ -160,7 +145,6 @@ class AsyncResult(AsyncCommon):
return await greenlet_spawn(self._manyrow_getter, self, size)
async def all(self):
- # type: () -> List[Row]
"""Return all rows in a list.
Closes the result set after invocation. Subsequent invocations
@@ -183,7 +167,6 @@ class AsyncResult(AsyncCommon):
return row
async def first(self):
- # type: () -> Row
"""Fetch the first row or None if no row is present.
Closes the result set and discards remaining rows.
@@ -207,7 +190,6 @@ class AsyncResult(AsyncCommon):
return await greenlet_spawn(self._only_one_row, False, False, False)
async def one_or_none(self):
- # type: () -> Optional[Row]
"""Return at most one result or raise an exception.
Returns ``None`` if the result has no rows.
@@ -230,7 +212,6 @@ class AsyncResult(AsyncCommon):
return await greenlet_spawn(self._only_one_row, True, False, False)
async def scalar_one(self):
- # type: () -> Any
"""Return exactly one scalar result or raise an exception.
This is equivalent to calling :meth:`_asyncio.AsyncResult.scalars` and
@@ -246,7 +227,6 @@ class AsyncResult(AsyncCommon):
return await greenlet_spawn(self._only_one_row, True, True, True)
async def scalar_one_or_none(self):
- # type: () -> Optional[Any]
"""Return exactly one or no scalar result.
This is equivalent to calling :meth:`_asyncio.AsyncResult.scalars` and
@@ -262,7 +242,6 @@ class AsyncResult(AsyncCommon):
return await greenlet_spawn(self._only_one_row, True, False, True)
async def one(self):
- # type: () -> Row
"""Return exactly one row or raise an exception.
Raises :class:`.NoResultFound` if the result returns no
@@ -294,7 +273,6 @@ class AsyncResult(AsyncCommon):
return await greenlet_spawn(self._only_one_row, True, True, False)
async def scalar(self):
- # type: () -> Optional[Any]
"""Fetch the first column of the first row, and close the result set.
Returns None if there are no rows to fetch.
@@ -350,7 +328,6 @@ class AsyncResult(AsyncCommon):
return MergedResult(self._metadata, (self,) + others)
def scalars(self, index=0):
- # type: (Int) -> AsyncScalarResult
"""Return an :class:`_asyncio.AsyncScalarResult` filtering object which
will return single elements rather than :class:`_row.Row` objects.
@@ -367,7 +344,6 @@ class AsyncResult(AsyncCommon):
return AsyncScalarResult(self._real_result, index)
def mappings(self):
- # type() -> AsyncMappingResult
"""Apply a mappings filter to returned rows, returning an instance of
:class:`_asyncio.AsyncMappingResult`.
@@ -414,7 +390,6 @@ class AsyncScalarResult(AsyncCommon):
self._unique_filter_state = real_result._unique_filter_state
def unique(self, strategy=None):
- # type: () -> AsyncScalarResult
"""Apply unique filtering to the objects returned by this
:class:`_asyncio.AsyncScalarResult`.
@@ -425,7 +400,6 @@ class AsyncScalarResult(AsyncCommon):
return self
async def partitions(self, size=None):
- # type: (Optional[Int]) -> Iterator[List[Any]]
"""Iterate through sub-lists of elements of the size given.
Equivalent to :meth:`_asyncio.AsyncResult.partitions` except that
@@ -444,13 +418,11 @@ class AsyncScalarResult(AsyncCommon):
break
async def fetchall(self):
- # type: () -> List[Any]
"""A synonym for the :meth:`_asyncio.AsyncScalarResult.all` method."""
return await greenlet_spawn(self._allrows)
async def fetchmany(self, size=None):
- # type: (Optional[Int]) -> List[Any]
"""Fetch many objects.
Equivalent to :meth:`_asyncio.AsyncResult.fetchmany` except that
@@ -461,7 +433,6 @@ class AsyncScalarResult(AsyncCommon):
return await greenlet_spawn(self._manyrow_getter, self, size)
async def all(self):
- # type: () -> List[Any]
"""Return all scalar values in a list.
Equivalent to :meth:`_asyncio.AsyncResult.all` except that
@@ -482,7 +453,6 @@ class AsyncScalarResult(AsyncCommon):
return row
async def first(self):
- # type: () -> Optional[Any]
"""Fetch the first object or None if no object is present.
Equivalent to :meth:`_asyncio.AsyncResult.first` except that
@@ -493,7 +463,6 @@ class AsyncScalarResult(AsyncCommon):
return await greenlet_spawn(self._only_one_row, False, False, False)
async def one_or_none(self):
- # type: () -> Optional[Any]
"""Return at most one object or raise an exception.
Equivalent to :meth:`_asyncio.AsyncResult.one_or_none` except that
@@ -504,7 +473,6 @@ class AsyncScalarResult(AsyncCommon):
return await greenlet_spawn(self._only_one_row, True, False, False)
async def one(self):
- # type: () -> Any
"""Return exactly one object or raise an exception.
Equivalent to :meth:`_asyncio.AsyncResult.one` except that
@@ -556,7 +524,6 @@ class AsyncMappingResult(AsyncCommon):
return self._metadata.keys
def unique(self, strategy=None):
- # type: () -> AsyncMappingResult
"""Apply unique filtering to the objects returned by this
:class:`_asyncio.AsyncMappingResult`.
@@ -567,12 +534,10 @@ class AsyncMappingResult(AsyncCommon):
return self
def columns(self, *col_expressions):
- # type: (*object) -> AsyncMappingResult
r"""Establish the columns that should be returned in each row."""
return self._column_slices(col_expressions)
async def partitions(self, size=None):
- # type: (Optional[Int]) -> Iterator[List[Mapping]]
"""Iterate through sub-lists of elements of the size given.
Equivalent to :meth:`_asyncio.AsyncResult.partitions` except that
@@ -591,13 +556,11 @@ class AsyncMappingResult(AsyncCommon):
break
async def fetchall(self):
- # type: () -> List[Mapping]
"""A synonym for the :meth:`_asyncio.AsyncMappingResult.all` method."""
return await greenlet_spawn(self._allrows)
async def fetchone(self):
- # type: () -> Mapping
"""Fetch one object.
Equivalent to :meth:`_asyncio.AsyncResult.fetchone` except that
@@ -613,7 +576,6 @@ class AsyncMappingResult(AsyncCommon):
return row
async def fetchmany(self, size=None):
- # type: (Optional[Int]) -> List[Mapping]
"""Fetch many objects.
Equivalent to :meth:`_asyncio.AsyncResult.fetchmany` except that
@@ -625,7 +587,6 @@ class AsyncMappingResult(AsyncCommon):
return await greenlet_spawn(self._manyrow_getter, self, size)
async def all(self):
- # type: () -> List[Mapping]
"""Return all scalar values in a list.
Equivalent to :meth:`_asyncio.AsyncResult.all` except that
@@ -647,7 +608,6 @@ class AsyncMappingResult(AsyncCommon):
return row
async def first(self):
- # type: () -> Optional[Mapping]
"""Fetch the first object or None if no object is present.
Equivalent to :meth:`_asyncio.AsyncResult.first` except that
@@ -659,7 +619,6 @@ class AsyncMappingResult(AsyncCommon):
return await greenlet_spawn(self._only_one_row, False, False, False)
async def one_or_none(self):
- # type: () -> Optional[Mapping]
"""Return at most one object or raise an exception.
Equivalent to :meth:`_asyncio.AsyncResult.one_or_none` except that
@@ -670,7 +629,6 @@ class AsyncMappingResult(AsyncCommon):
return await greenlet_spawn(self._only_one_row, True, False, False)
async def one(self):
- # type: () -> Mapping
"""Return exactly one object or raise an exception.
Equivalent to :meth:`_asyncio.AsyncResult.one` except that
diff --git a/lib/sqlalchemy/ext/asyncio/session.py b/lib/sqlalchemy/ext/asyncio/session.py
index 1b61d6ee3..8d19819b0 100644
--- a/lib/sqlalchemy/ext/asyncio/session.py
+++ b/lib/sqlalchemy/ext/asyncio/session.py
@@ -4,27 +4,14 @@
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-from typing import Any
-from typing import Callable
-from typing import Mapping
-from typing import Optional
-from typing import TypeVar
-
from . import engine
from . import result as _result
from .base import StartableContext
-from .engine import AsyncEngine
from ... import util
-from ...engine import Result
from ...orm import Session
-from ...sql import Executable
from ...util.concurrency import greenlet_spawn
-T = TypeVar("T")
-
-
@util.create_proxy_methods(
Session,
":class:`_orm.Session`",
@@ -72,12 +59,7 @@ class AsyncSession:
dispatch = None
- def __init__(
- self,
- bind: AsyncEngine = None,
- binds: Mapping[object, AsyncEngine] = None,
- **kw
- ):
+ def __init__(self, bind=None, binds=None, **kw):
kw["future"] = True
if bind:
self.bind = bind
@@ -114,7 +96,7 @@ class AsyncSession:
with_for_update=with_for_update,
)
- async def run_sync(self, fn: Callable[..., T], *arg, **kw) -> T:
+ async def run_sync(self, fn, *arg, **kw):
"""Invoke the given sync callable passing sync self as the first
argument.
@@ -143,12 +125,12 @@ class AsyncSession:
async def execute(
self,
- statement: Executable,
- params: Optional[Mapping] = None,
- execution_options: Mapping = util.EMPTY_DICT,
- bind_arguments: Optional[Mapping] = None,
+ statement,
+ params=None,
+ execution_options=util.EMPTY_DICT,
+ bind_arguments=None,
**kw
- ) -> Result:
+ ):
"""Execute a statement and return a buffered
:class:`_engine.Result` object."""
@@ -165,12 +147,12 @@ class AsyncSession:
async def scalar(
self,
- statement: Executable,
- params: Optional[Mapping] = None,
- execution_options: Mapping = util.EMPTY_DICT,
- bind_arguments: Optional[Mapping] = None,
+ statement,
+ params=None,
+ execution_options=util.EMPTY_DICT,
+ bind_arguments=None,
**kw
- ) -> Any:
+ ):
"""Execute a statement and return a scalar result."""
result = await self.execute(