Skip to content

adapters

Per-driver adapters for native statement execution.

Only the drivers listed in ADAPTERS run natively; any other driver (e.g. aiomysql, aiopg) keeps running every statement through SQLAlchemy.

DriverAdapter

Bases: ABC

Runs bound statements on one driver and returns results in the shape the SQLAlchemy path returns them (rows keyed by label, inserted pk, row count).

Every method takes raw, the pooled connection that SQLAlchemy's connection is using, so native statements share its transaction. It exposes two objects::

Text Only
1
2
3
4
5
# the driver's own connection, e.g. an asyncpg Connection
raw.driver_connection
# SQLAlchemy's wrapper around it, with the execution lock and the
# mapping of driver errors
raw.dbapi_connection

driver_errors lists the exceptions the driver raises, so the executor knows which ones to translate into SQLAlchemy exceptions.

Source code in ormar/databases/native/adapters/base.py
Python
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
class DriverAdapter(abc.ABC):
    """
    Runs bound statements on one driver and returns results in the shape the
    SQLAlchemy path returns them (rows keyed by label, inserted pk, row count).

    Every method takes ``raw``, the pooled connection that SQLAlchemy's
    connection is using, so native statements share its transaction. It
    exposes two objects::

        # the driver's own connection, e.g. an asyncpg Connection
        raw.driver_connection
        # SQLAlchemy's wrapper around it, with the execution lock and the
        # mapping of driver errors
        raw.dbapi_connection

    ``driver_errors`` lists the exceptions the driver raises, so the executor
    knows which ones to translate into SQLAlchemy exceptions.
    """

    driver_errors: Tuple[Type[BaseException], ...]
    # True when the driver's executemany is all-or-nothing even outside a
    # transaction, so a single-batch bulk_create can skip opening one
    atomic_execute_many = False

    def __init__(self, dialect: Dialect) -> None:
        """
        :param dialect: dialect of the connected database
        :type dialect: Dialect
        """
        self.dialect = dialect

    @abc.abstractmethod
    async def fetch_all(
        self, raw: Any, bound: BoundStatement, as_tuples: bool = False
    ) -> List[Any]:
        """
        Run a statement and return all its rows keyed by result label, or as
        tuples of values in select order with ``as_tuples``::

            fetch_all(raw, bind(select(users.c.id, users.c.name)))
            # -> [{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]
            fetch_all(raw, bind(select(users.c.id, users.c.name)), as_tuples=True)
            # -> [(1, "a"), (2, "b")]

        :param raw: pooled raw connection
        :type raw: Any
        :param bound: statement to execute
        :type bound: BoundStatement
        :param as_tuples: return tuples of values in select order instead
        :type as_tuples: bool
        :return: rows
        :rtype: List[Any]
        """

    @abc.abstractmethod
    async def execute(self, raw: Any, bound: BoundStatement) -> Any:
        """
        Run an INSERT, UPDATE or DELETE and return what SQLAlchemy's path would:
        the primary key of an inserted row, otherwise the number of rows changed::

            execute(raw, bind(users.insert().values(name="a")))  # -> 7 (new id)
            execute(raw, bind(users.delete()))  # -> 3 (rows deleted)

        :param raw: pooled raw connection
        :type raw: Any
        :param bound: statement to execute
        :type bound: BoundStatement
        :return: inserted primary key for INSERT, row count otherwise
        :rtype: Any
        """

    @abc.abstractmethod
    async def execute_many(self, raw: Any, batch: BoundBatch) -> None:
        """
        Run one statement once per row of arguments with the driver's
        ``executemany``, used by ``bulk_update``::

            stmt = users.update().where(users.c.id == bindparam("new_id"))
            stmt = stmt.values(name=bindparam("new_name"))
            rows = [{"new_id": 1, "new_name": "a"}, {"new_id": 2, "new_name": "b"}]
            execute_many(raw, bind_many(stmt, rows))

        :param raw: pooled raw connection
        :type raw: Any
        :param batch: statement and arguments per row
        :type batch: BoundBatch
        """

    @abc.abstractmethod
    def stream(
        self, raw: Any, bound: BoundStatement, batch_size: int
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """
        Yield the rows of a statement one by one while fetching ``batch_size``
        rows per round trip, so ``QuerySet.iterate()`` never holds the whole
        result in memory.

        :param raw: pooled raw connection
        :type raw: Any
        :param bound: statement to execute
        :type bound: BoundStatement
        :param batch_size: rows fetched per round trip
        :type batch_size: int
        :return: rows keyed by result label
        :rtype: AsyncGenerator[Dict[str, Any], None]
        """

    async def start_transaction(self, sa_connection: AsyncConnection) -> None:
        """
        Make sure the transaction SQLAlchemy began is really open on the driver
        connection before native statements run on it.

        Some SQLAlchemy adapters only send ``BEGIN`` lazily with their own first
        statement; native statements bypass that, so without this they would run
        outside the transaction. No-op for drivers that start it on their own.

        :param sa_connection: connection the transaction was begun on
        :type sa_connection: AsyncConnection
        """

    def translate_error(
        self, error: BaseException, dbapi_connection: Any
    ) -> BaseException:
        """
        Return the exception SQLAlchemy's driver wrapper would raise for this
        driver error, which ``sqlalchemy.exc.DBAPIError.instance`` then wraps.

        SQLAlchemy maps driver exceptions to standard DBAPI classes before
        wrapping them, so users catch the same exception on both paths::

            asyncpg.UniqueViolationError -> IntegrityError
            # -> raised to the user as sqlalchemy.exc.IntegrityError

        Drivers that already raise DBAPI classes return the error unchanged.

        :param error: exception raised by the driver
        :type error: BaseException
        :param dbapi_connection: SQLAlchemy's adapted DBAPI connection
        :type dbapi_connection: Any
        :return: DBAPI-level exception
        :rtype: BaseException
        """
        return error

    def resolve_processors(self, bound: BoundStatement, coltypes: List[Any]) -> None:
        """
        Look up the plan's result processors on its first execution, once the
        driver has reported the result column types (see
        ``resolve_result_processors`` for what they are). Later executions reuse
        them.

        :param bound: executed statement
        :type bound: BoundStatement
        :param coltypes: driver-reported column types
        :type coltypes: List[Any]
        """
        if bound.plan.result_processors is None:
            resolve_result_processors(
                plan=bound.plan, dialect=self.dialect, coltypes=coltypes
            )

__init__(dialect)

Parameters:

Name Type Description Default
dialect Dialect

dialect of the connected database

required
Source code in ormar/databases/native/adapters/base.py
Python
62
63
64
65
66
67
def __init__(self, dialect: Dialect) -> None:
    """
    :param dialect: dialect of the connected database
    :type dialect: Dialect
    """
    self.dialect = dialect

execute(raw, bound) abstractmethod async

Run an INSERT, UPDATE or DELETE and return what SQLAlchemy's path would: the primary key of an inserted row, otherwise the number of rows changed::

Text Only
1
2
execute(raw, bind(users.insert().values(name="a")))  # -> 7 (new id)
execute(raw, bind(users.delete()))  # -> 3 (rows deleted)

Parameters:

Name Type Description Default
raw Any

pooled raw connection

required
bound BoundStatement

statement to execute

required

Returns:

Type Description
Any

inserted primary key for INSERT, row count otherwise

Source code in ormar/databases/native/adapters/base.py
Python
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@abc.abstractmethod
async def execute(self, raw: Any, bound: BoundStatement) -> Any:
    """
    Run an INSERT, UPDATE or DELETE and return what SQLAlchemy's path would:
    the primary key of an inserted row, otherwise the number of rows changed::

        execute(raw, bind(users.insert().values(name="a")))  # -> 7 (new id)
        execute(raw, bind(users.delete()))  # -> 3 (rows deleted)

    :param raw: pooled raw connection
    :type raw: Any
    :param bound: statement to execute
    :type bound: BoundStatement
    :return: inserted primary key for INSERT, row count otherwise
    :rtype: Any
    """

execute_many(raw, batch) abstractmethod async

Run one statement once per row of arguments with the driver's executemany, used by bulk_update::

Text Only
1
2
3
4
stmt = users.update().where(users.c.id == bindparam("new_id"))
stmt = stmt.values(name=bindparam("new_name"))
rows = [{"new_id": 1, "new_name": "a"}, {"new_id": 2, "new_name": "b"}]
execute_many(raw, bind_many(stmt, rows))

Parameters:

Name Type Description Default
raw Any

pooled raw connection

required
batch BoundBatch

statement and arguments per row

required
Source code in ormar/databases/native/adapters/base.py
Python
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
@abc.abstractmethod
async def execute_many(self, raw: Any, batch: BoundBatch) -> None:
    """
    Run one statement once per row of arguments with the driver's
    ``executemany``, used by ``bulk_update``::

        stmt = users.update().where(users.c.id == bindparam("new_id"))
        stmt = stmt.values(name=bindparam("new_name"))
        rows = [{"new_id": 1, "new_name": "a"}, {"new_id": 2, "new_name": "b"}]
        execute_many(raw, bind_many(stmt, rows))

    :param raw: pooled raw connection
    :type raw: Any
    :param batch: statement and arguments per row
    :type batch: BoundBatch
    """

fetch_all(raw, bound, as_tuples=False) abstractmethod async

Run a statement and return all its rows keyed by result label, or as tuples of values in select order with as_tuples::

Text Only
1
2
3
4
fetch_all(raw, bind(select(users.c.id, users.c.name)))
# -> [{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]
fetch_all(raw, bind(select(users.c.id, users.c.name)), as_tuples=True)
# -> [(1, "a"), (2, "b")]

Parameters:

Name Type Description Default
raw Any

pooled raw connection

required
bound BoundStatement

statement to execute

required
as_tuples bool

return tuples of values in select order instead

False

Returns:

Type Description
List[Any]

rows

Source code in ormar/databases/native/adapters/base.py
Python
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
@abc.abstractmethod
async def fetch_all(
    self, raw: Any, bound: BoundStatement, as_tuples: bool = False
) -> List[Any]:
    """
    Run a statement and return all its rows keyed by result label, or as
    tuples of values in select order with ``as_tuples``::

        fetch_all(raw, bind(select(users.c.id, users.c.name)))
        # -> [{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]
        fetch_all(raw, bind(select(users.c.id, users.c.name)), as_tuples=True)
        # -> [(1, "a"), (2, "b")]

    :param raw: pooled raw connection
    :type raw: Any
    :param bound: statement to execute
    :type bound: BoundStatement
    :param as_tuples: return tuples of values in select order instead
    :type as_tuples: bool
    :return: rows
    :rtype: List[Any]
    """

resolve_processors(bound, coltypes)

Look up the plan's result processors on its first execution, once the driver has reported the result column types (see resolve_result_processors for what they are). Later executions reuse them.

Parameters:

Name Type Description Default
bound BoundStatement

executed statement

required
coltypes List[Any]

driver-reported column types

required
Source code in ormar/databases/native/adapters/base.py
Python
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def resolve_processors(self, bound: BoundStatement, coltypes: List[Any]) -> None:
    """
    Look up the plan's result processors on its first execution, once the
    driver has reported the result column types (see
    ``resolve_result_processors`` for what they are). Later executions reuse
    them.

    :param bound: executed statement
    :type bound: BoundStatement
    :param coltypes: driver-reported column types
    :type coltypes: List[Any]
    """
    if bound.plan.result_processors is None:
        resolve_result_processors(
            plan=bound.plan, dialect=self.dialect, coltypes=coltypes
        )

start_transaction(sa_connection) async

Make sure the transaction SQLAlchemy began is really open on the driver connection before native statements run on it.

Some SQLAlchemy adapters only send BEGIN lazily with their own first statement; native statements bypass that, so without this they would run outside the transaction. No-op for drivers that start it on their own.

Parameters:

Name Type Description Default
sa_connection AsyncConnection

connection the transaction was begun on

required
Source code in ormar/databases/native/adapters/base.py
Python
145
146
147
148
149
150
151
152
153
154
155
156
async def start_transaction(self, sa_connection: AsyncConnection) -> None:
    """
    Make sure the transaction SQLAlchemy began is really open on the driver
    connection before native statements run on it.

    Some SQLAlchemy adapters only send ``BEGIN`` lazily with their own first
    statement; native statements bypass that, so without this they would run
    outside the transaction. No-op for drivers that start it on their own.

    :param sa_connection: connection the transaction was begun on
    :type sa_connection: AsyncConnection
    """

stream(raw, bound, batch_size) abstractmethod

Yield the rows of a statement one by one while fetching batch_size rows per round trip, so QuerySet.iterate() never holds the whole result in memory.

Parameters:

Name Type Description Default
raw Any

pooled raw connection

required
bound BoundStatement

statement to execute

required
batch_size int

rows fetched per round trip

required

Returns:

Type Description
AsyncGenerator[Dict[str, Any], None]

rows keyed by result label

Source code in ormar/databases/native/adapters/base.py
Python
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
@abc.abstractmethod
def stream(
    self, raw: Any, bound: BoundStatement, batch_size: int
) -> AsyncGenerator[Dict[str, Any], None]:
    """
    Yield the rows of a statement one by one while fetching ``batch_size``
    rows per round trip, so ``QuerySet.iterate()`` never holds the whole
    result in memory.

    :param raw: pooled raw connection
    :type raw: Any
    :param bound: statement to execute
    :type bound: BoundStatement
    :param batch_size: rows fetched per round trip
    :type batch_size: int
    :return: rows keyed by result label
    :rtype: AsyncGenerator[Dict[str, Any], None]
    """

translate_error(error, dbapi_connection)

Return the exception SQLAlchemy's driver wrapper would raise for this driver error, which sqlalchemy.exc.DBAPIError.instance then wraps.

SQLAlchemy maps driver exceptions to standard DBAPI classes before wrapping them, so users catch the same exception on both paths::

Text Only
1
2
asyncpg.UniqueViolationError -> IntegrityError
# -> raised to the user as sqlalchemy.exc.IntegrityError

Drivers that already raise DBAPI classes return the error unchanged.

Parameters:

Name Type Description Default
error BaseException

exception raised by the driver

required
dbapi_connection Any

SQLAlchemy's adapted DBAPI connection

required

Returns:

Type Description
BaseException

DBAPI-level exception

Source code in ormar/databases/native/adapters/base.py
Python
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def translate_error(
    self, error: BaseException, dbapi_connection: Any
) -> BaseException:
    """
    Return the exception SQLAlchemy's driver wrapper would raise for this
    driver error, which ``sqlalchemy.exc.DBAPIError.instance`` then wraps.

    SQLAlchemy maps driver exceptions to standard DBAPI classes before
    wrapping them, so users catch the same exception on both paths::

        asyncpg.UniqueViolationError -> IntegrityError
        # -> raised to the user as sqlalchemy.exc.IntegrityError

    Drivers that already raise DBAPI classes return the error unchanged.

    :param error: exception raised by the driver
    :type error: BaseException
    :param dbapi_connection: SQLAlchemy's adapted DBAPI connection
    :type dbapi_connection: Any
    :return: DBAPI-level exception
    :rtype: BaseException
    """
    return error

select_adapter(dialect)

Return the native adapter for the dialect's driver, or None when the driver has none and statements run through SQLAlchemy::

Text Only
1
2
3
4
select_adapter(create_async_engine("postgresql+asyncpg://...").dialect)
# -> AsyncpgAdapter
select_adapter(create_async_engine("mysql+aiomysql://...").dialect)
# -> None

Parameters:

Name Type Description Default
dialect Dialect

dialect of the connected database

required

Returns:

Type Description
Optional[DriverAdapter]

adapter instance or None

Source code in ormar/databases/native/adapters/__init__.py
Python
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def select_adapter(dialect: Dialect) -> Optional[DriverAdapter]:
    """
    Return the native adapter for the dialect's driver, or None when the driver
    has none and statements run through SQLAlchemy::

        select_adapter(create_async_engine("postgresql+asyncpg://...").dialect)
        # -> AsyncpgAdapter
        select_adapter(create_async_engine("mysql+aiomysql://...").dialect)
        # -> None

    :param dialect: dialect of the connected database
    :type dialect: Dialect
    :return: adapter instance or None
    :rtype: Optional[DriverAdapter]
    """
    adapter_cls = ADAPTERS.get(dialect.driver)
    return adapter_cls(dialect=dialect) if adapter_cls is not None else None