SQLAlchemy 2.1.0b2__cp313-cp313t-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. sqlalchemy/__init__.py +298 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +30 -0
  8. sqlalchemy/dialects/mssql/__init__.py +89 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4166 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +220 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +698 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  21. sqlalchemy/dialects/mysql/base.py +3877 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3977 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1601 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +158 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +909 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +368 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +229 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1323 -0
  50. sqlalchemy/dialects/postgresql/base.py +5789 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +593 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +423 -0
  55. sqlalchemy/dialects/postgresql/json.py +408 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  57. sqlalchemy/dialects/postgresql/operators.py +130 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +670 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  60. sqlalchemy/dialects/postgresql/provision.py +184 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +799 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  68. sqlalchemy/dialects/sqlite/base.py +3063 -0
  69. sqlalchemy/dialects/sqlite/dml.py +279 -0
  70. sqlalchemy/dialects/sqlite/json.py +100 -0
  71. sqlalchemy/dialects/sqlite/provision.py +229 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +161 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp313t-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp313t-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +633 -0
  80. sqlalchemy/engine/_row_cy.cp313t-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp313t-win_arm64.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3354 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2421 -0
  88. sqlalchemy/engine/default.py +2402 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3495 -0
  91. sqlalchemy/engine/mock.py +134 -0
  92. sqlalchemy/engine/processors.py +82 -0
  93. sqlalchemy/engine/reflection.py +2100 -0
  94. sqlalchemy/engine/result.py +1966 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +156 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +674 -0
  102. sqlalchemy/event/base.py +472 -0
  103. sqlalchemy/event/legacy.py +258 -0
  104. sqlalchemy/event/registry.py +390 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +922 -0
  107. sqlalchemy/ext/__init__.py +11 -0
  108. sqlalchemy/ext/associationproxy.py +2072 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2007 -0
  116. sqlalchemy/ext/automap.py +1701 -0
  117. sqlalchemy/ext/baked.py +559 -0
  118. sqlalchemy/ext/compiler.py +600 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +560 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +439 -0
  127. sqlalchemy/ext/serializer.py +185 -0
  128. sqlalchemy/future/__init__.py +16 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +174 -0
  131. sqlalchemy/log.py +283 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +179 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +976 -0
  137. sqlalchemy/orm/bulk_persistence.py +2152 -0
  138. sqlalchemy/orm/clsregistry.py +582 -0
  139. sqlalchemy/orm/collections.py +1568 -0
  140. sqlalchemy/orm/context.py +3471 -0
  141. sqlalchemy/orm/decl_api.py +2280 -0
  142. sqlalchemy/orm/decl_base.py +2309 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +307 -0
  146. sqlalchemy/orm/evaluator.py +379 -0
  147. sqlalchemy/orm/events.py +3386 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +746 -0
  151. sqlalchemy/orm/interfaces.py +1589 -0
  152. sqlalchemy/orm/loading.py +1684 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4411 -0
  155. sqlalchemy/orm/path_registry.py +829 -0
  156. sqlalchemy/orm/persistence.py +1789 -0
  157. sqlalchemy/orm/properties.py +973 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3570 -0
  160. sqlalchemy/orm/scoping.py +2232 -0
  161. sqlalchemy/orm/session.py +5403 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3492 -0
  165. sqlalchemy/orm/strategy_options.py +2562 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +798 -0
  168. sqlalchemy/orm/util.py +2438 -0
  169. sqlalchemy/orm/writeonly.py +694 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1522 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +582 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +74 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +397 -0
  178. sqlalchemy/sql/_dml_constructors.py +132 -0
  179. sqlalchemy/sql/_elements_constructors.py +2164 -0
  180. sqlalchemy/sql/_orm_types.py +20 -0
  181. sqlalchemy/sql/_selectable_constructors.py +840 -0
  182. sqlalchemy/sql/_typing.py +487 -0
  183. sqlalchemy/sql/_util_cy.cp313t-win_arm64.pyd +0 -0
  184. sqlalchemy/sql/_util_cy.py +127 -0
  185. sqlalchemy/sql/annotation.py +590 -0
  186. sqlalchemy/sql/base.py +2699 -0
  187. sqlalchemy/sql/cache_key.py +1066 -0
  188. sqlalchemy/sql/coercions.py +1373 -0
  189. sqlalchemy/sql/compiler.py +8327 -0
  190. sqlalchemy/sql/crud.py +1815 -0
  191. sqlalchemy/sql/ddl.py +1928 -0
  192. sqlalchemy/sql/default_comparator.py +654 -0
  193. sqlalchemy/sql/dml.py +1977 -0
  194. sqlalchemy/sql/elements.py +6033 -0
  195. sqlalchemy/sql/events.py +458 -0
  196. sqlalchemy/sql/expression.py +172 -0
  197. sqlalchemy/sql/functions.py +2305 -0
  198. sqlalchemy/sql/lambdas.py +1443 -0
  199. sqlalchemy/sql/naming.py +209 -0
  200. sqlalchemy/sql/operators.py +2897 -0
  201. sqlalchemy/sql/roles.py +332 -0
  202. sqlalchemy/sql/schema.py +6703 -0
  203. sqlalchemy/sql/selectable.py +7553 -0
  204. sqlalchemy/sql/sqltypes.py +4093 -0
  205. sqlalchemy/sql/traversals.py +1042 -0
  206. sqlalchemy/sql/type_api.py +2446 -0
  207. sqlalchemy/sql/util.py +1495 -0
  208. sqlalchemy/sql/visitors.py +1157 -0
  209. sqlalchemy/testing/__init__.py +96 -0
  210. sqlalchemy/testing/assertions.py +1007 -0
  211. sqlalchemy/testing/assertsql.py +519 -0
  212. sqlalchemy/testing/asyncio.py +128 -0
  213. sqlalchemy/testing/config.py +440 -0
  214. sqlalchemy/testing/engines.py +483 -0
  215. sqlalchemy/testing/entities.py +117 -0
  216. sqlalchemy/testing/exclusions.py +476 -0
  217. sqlalchemy/testing/fixtures/__init__.py +30 -0
  218. sqlalchemy/testing/fixtures/base.py +384 -0
  219. sqlalchemy/testing/fixtures/mypy.py +247 -0
  220. sqlalchemy/testing/fixtures/orm.py +227 -0
  221. sqlalchemy/testing/fixtures/sql.py +538 -0
  222. sqlalchemy/testing/pickleable.py +155 -0
  223. sqlalchemy/testing/plugin/__init__.py +6 -0
  224. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  225. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  226. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  227. sqlalchemy/testing/profiling.py +329 -0
  228. sqlalchemy/testing/provision.py +613 -0
  229. sqlalchemy/testing/requirements.py +1978 -0
  230. sqlalchemy/testing/schema.py +198 -0
  231. sqlalchemy/testing/suite/__init__.py +19 -0
  232. sqlalchemy/testing/suite/test_cte.py +237 -0
  233. sqlalchemy/testing/suite/test_ddl.py +420 -0
  234. sqlalchemy/testing/suite/test_dialect.py +776 -0
  235. sqlalchemy/testing/suite/test_insert.py +630 -0
  236. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  237. sqlalchemy/testing/suite/test_results.py +660 -0
  238. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  239. sqlalchemy/testing/suite/test_select.py +2112 -0
  240. sqlalchemy/testing/suite/test_sequence.py +317 -0
  241. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  242. sqlalchemy/testing/suite/test_types.py +2271 -0
  243. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  244. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  245. sqlalchemy/testing/util.py +535 -0
  246. sqlalchemy/testing/warnings.py +52 -0
  247. sqlalchemy/types.py +76 -0
  248. sqlalchemy/util/__init__.py +158 -0
  249. sqlalchemy/util/_collections.py +688 -0
  250. sqlalchemy/util/_collections_cy.cp313t-win_arm64.pyd +0 -0
  251. sqlalchemy/util/_collections_cy.pxd +8 -0
  252. sqlalchemy/util/_collections_cy.py +516 -0
  253. sqlalchemy/util/_has_cython.py +46 -0
  254. sqlalchemy/util/_immutabledict_cy.cp313t-win_arm64.pyd +0 -0
  255. sqlalchemy/util/_immutabledict_cy.py +240 -0
  256. sqlalchemy/util/compat.py +299 -0
  257. sqlalchemy/util/concurrency.py +322 -0
  258. sqlalchemy/util/cython.py +79 -0
  259. sqlalchemy/util/deprecations.py +401 -0
  260. sqlalchemy/util/langhelpers.py +2320 -0
  261. sqlalchemy/util/preloaded.py +152 -0
  262. sqlalchemy/util/queue.py +304 -0
  263. sqlalchemy/util/tool_support.py +201 -0
  264. sqlalchemy/util/topological.py +120 -0
  265. sqlalchemy/util/typing.py +711 -0
  266. sqlalchemy-2.1.0b2.dist-info/METADATA +269 -0
  267. sqlalchemy-2.1.0b2.dist-info/RECORD +270 -0
  268. sqlalchemy-2.1.0b2.dist-info/WHEEL +5 -0
  269. sqlalchemy-2.1.0b2.dist-info/licenses/LICENSE +19 -0
  270. sqlalchemy-2.1.0b2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1323 @@
1
+ # dialects/postgresql/asyncpg.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors <see AUTHORS
3
+ # file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+ r"""
10
+ .. dialect:: postgresql+asyncpg
11
+ :name: asyncpg
12
+ :dbapi: asyncpg
13
+ :connectstring: postgresql+asyncpg://user:password@host:port/dbname[?key=value&key=value...]
14
+ :url: https://magicstack.github.io/asyncpg/
15
+
16
+ The asyncpg dialect is SQLAlchemy's first Python asyncio dialect.
17
+
18
+ Using a special asyncio mediation layer, the asyncpg dialect is usable
19
+ as the backend for the :ref:`SQLAlchemy asyncio <asyncio_toplevel>`
20
+ extension package.
21
+
22
+ This dialect should normally be used only with the
23
+ :func:`_asyncio.create_async_engine` engine creation function::
24
+
25
+ from sqlalchemy.ext.asyncio import create_async_engine
26
+
27
+ engine = create_async_engine(
28
+ "postgresql+asyncpg://user:pass@hostname/dbname"
29
+ )
30
+
31
+ .. versionadded:: 1.4
32
+
33
+ .. note::
34
+
35
+ By default asyncpg does not decode the ``json`` and ``jsonb`` types and
36
+ returns them as strings. SQLAlchemy sets default type decoder for ``json``
37
+ and ``jsonb`` types using the python builtin ``json.loads`` function.
38
+ The json implementation used can be changed by setting the attribute
39
+ ``json_deserializer`` when creating the engine with
40
+ :func:`create_engine` or :func:`create_async_engine`.
41
+
42
+ .. _asyncpg_multihost:
43
+
44
+ Multihost Connections
45
+ --------------------------
46
+
47
+ The asyncpg dialect features support for multiple fallback hosts in the
48
+ same way as that of the psycopg2 and psycopg dialects. The
49
+ syntax is the same,
50
+ using ``host=<host>:<port>`` combinations as additional query string arguments;
51
+ however, there is no default port, so all hosts must have a complete port number
52
+ present, otherwise an exception is raised::
53
+
54
+ engine = create_async_engine(
55
+ "postgresql+asyncpg://user:password@/dbname?host=HostA:5432&host=HostB:5432&host=HostC:5432"
56
+ )
57
+
58
+ For complete background on this syntax, see :ref:`psycopg2_multi_host`.
59
+
60
+ .. versionadded:: 2.0.18
61
+
62
+ .. seealso::
63
+
64
+ :ref:`psycopg2_multi_host`
65
+
66
+ .. _asyncpg_prepared_statement_cache:
67
+
68
+ Prepared Statement Cache
69
+ --------------------------
70
+
71
+ The asyncpg SQLAlchemy dialect makes use of ``asyncpg.connection.prepare()``
72
+ for all statements. The prepared statement objects are cached after
73
+ construction which appears to grant a 10% or more performance improvement for
74
+ statement invocation. The cache is on a per-DBAPI connection basis, which
75
+ means that the primary storage for prepared statements is within DBAPI
76
+ connections pooled within the connection pool. The size of this cache
77
+ defaults to 100 statements per DBAPI connection and may be adjusted using the
78
+ ``prepared_statement_cache_size`` DBAPI argument (note that while this argument
79
+ is implemented by SQLAlchemy, it is part of the DBAPI emulation portion of the
80
+ asyncpg dialect, therefore is handled as a DBAPI argument, not a dialect
81
+ argument)::
82
+
83
+
84
+ engine = create_async_engine(
85
+ "postgresql+asyncpg://user:pass@hostname/dbname?prepared_statement_cache_size=500"
86
+ )
87
+
88
+ To disable the prepared statement cache, use a value of zero::
89
+
90
+ engine = create_async_engine(
91
+ "postgresql+asyncpg://user:pass@hostname/dbname?prepared_statement_cache_size=0"
92
+ )
93
+
94
+ .. versionadded:: 1.4.0b2 Added ``prepared_statement_cache_size`` for asyncpg.
95
+
96
+
97
+ .. warning:: The ``asyncpg`` database driver necessarily uses caches for
98
+ PostgreSQL type OIDs, which become stale when custom PostgreSQL datatypes
99
+ such as ``ENUM`` objects are changed via DDL operations. Additionally,
100
+ prepared statements themselves which are optionally cached by SQLAlchemy's
101
+ driver as described above may also become "stale" when DDL has been emitted
102
+ to the PostgreSQL database which modifies the tables or other objects
103
+ involved in a particular prepared statement.
104
+
105
+ The SQLAlchemy asyncpg dialect will invalidate these caches within its local
106
+ process when statements that represent DDL are emitted on a local
107
+ connection, but this is only controllable within a single Python process /
108
+ database engine. If DDL changes are made from other database engines
109
+ and/or processes, a running application may encounter asyncpg exceptions
110
+ ``InvalidCachedStatementError`` and/or ``InternalServerError("cache lookup
111
+ failed for type <oid>")`` if it refers to pooled database connections which
112
+ operated upon the previous structures. The SQLAlchemy asyncpg dialect will
113
+ recover from these error cases when the driver raises these exceptions by
114
+ clearing its internal caches as well as those of the asyncpg driver in
115
+ response to them, but cannot prevent them from being raised in the first
116
+ place if the cached prepared statement or asyncpg type caches have gone
117
+ stale, nor can it retry the statement as the PostgreSQL transaction is
118
+ invalidated when these errors occur.
119
+
120
+ .. _asyncpg_prepared_statement_name:
121
+
122
+ Prepared Statement Name with PGBouncer
123
+ --------------------------------------
124
+
125
+ By default, asyncpg enumerates prepared statements in numeric order, which
126
+ can lead to errors if a name has already been taken for another prepared
127
+ statement. This issue can arise if your application uses database proxies
128
+ such as PgBouncer to handle connections. One possible workaround is to
129
+ use dynamic prepared statement names, which asyncpg now supports through
130
+ an optional ``name`` value for the statement name. This allows you to
131
+ generate your own unique names that won't conflict with existing ones.
132
+ To achieve this, you can provide a function that will be called every time
133
+ a prepared statement is prepared::
134
+
135
+ from uuid import uuid4
136
+
137
+ engine = create_async_engine(
138
+ "postgresql+asyncpg://user:pass@somepgbouncer/dbname",
139
+ poolclass=NullPool,
140
+ connect_args={
141
+ "prepared_statement_name_func": lambda: f"__asyncpg_{uuid4()}__",
142
+ },
143
+ )
144
+
145
+ .. seealso::
146
+
147
+ https://github.com/MagicStack/asyncpg/issues/837
148
+
149
+ https://github.com/sqlalchemy/sqlalchemy/issues/6467
150
+
151
+ .. warning:: When using PGBouncer, to prevent a buildup of useless prepared statements in
152
+ your application, it's important to use the :class:`.NullPool` pool
153
+ class, and to configure PgBouncer to use `DISCARD <https://www.postgresql.org/docs/current/sql-discard.html>`_
154
+ when returning connections. The DISCARD command is used to release resources held by the db connection,
155
+ including prepared statements. Without proper setup, prepared statements can
156
+ accumulate quickly and cause performance issues.
157
+
158
+ Disabling the PostgreSQL JIT to improve ENUM datatype handling
159
+ ---------------------------------------------------------------
160
+
161
+ Asyncpg has an `issue <https://github.com/MagicStack/asyncpg/issues/727>`_ when
162
+ using PostgreSQL ENUM datatypes, where upon the creation of new database
163
+ connections, an expensive query may be emitted in order to retrieve metadata
164
+ regarding custom types which has been shown to negatively affect performance.
165
+ To mitigate this issue, the PostgreSQL "jit" setting may be disabled from the
166
+ client using this setting passed to :func:`_asyncio.create_async_engine`::
167
+
168
+ engine = create_async_engine(
169
+ "postgresql+asyncpg://user:password@localhost/tmp",
170
+ connect_args={"server_settings": {"jit": "off"}},
171
+ )
172
+
173
+ .. seealso::
174
+
175
+ https://github.com/MagicStack/asyncpg/issues/727
176
+
177
+ """ # noqa
178
+
179
+ from __future__ import annotations
180
+
181
+ from collections import deque
182
+ import decimal
183
+ import json as _py_json
184
+ import re
185
+ import time
186
+ from types import NoneType
187
+ from typing import Any
188
+ from typing import Awaitable
189
+ from typing import Callable
190
+ from typing import NoReturn
191
+ from typing import Optional
192
+ from typing import Protocol
193
+ from typing import Sequence
194
+ from typing import Tuple
195
+ from typing import TYPE_CHECKING
196
+
197
+ from . import json
198
+ from . import ranges
199
+ from .array import ARRAY as PGARRAY
200
+ from .base import _DECIMAL_TYPES
201
+ from .base import _FLOAT_TYPES
202
+ from .base import _INT_TYPES
203
+ from .base import ENUM
204
+ from .base import INTERVAL
205
+ from .base import OID
206
+ from .base import PGCompiler
207
+ from .base import PGDialect
208
+ from .base import PGExecutionContext
209
+ from .base import PGIdentifierPreparer
210
+ from .base import REGCLASS
211
+ from .base import REGCONFIG
212
+ from .bitstring import BitString
213
+ from .types import BIT
214
+ from .types import BYTEA
215
+ from .types import CITEXT
216
+ from ... import exc
217
+ from ... import util
218
+ from ...connectors.asyncio import AsyncAdapt_dbapi_connection
219
+ from ...connectors.asyncio import AsyncAdapt_dbapi_cursor
220
+ from ...connectors.asyncio import AsyncAdapt_dbapi_module
221
+ from ...connectors.asyncio import AsyncAdapt_dbapi_ss_cursor
222
+ from ...connectors.asyncio import AsyncAdapt_Error
223
+ from ...connectors.asyncio import AsyncAdapt_terminate
224
+ from ...engine import processors
225
+ from ...sql import sqltypes
226
+ from ...util.concurrency import await_
227
+
228
+ if TYPE_CHECKING:
229
+ from ...engine.interfaces import _DBAPICursorDescription
230
+
231
+
232
+ class AsyncpgARRAY(PGARRAY):
233
+ render_bind_cast = True
234
+
235
+
236
+ class AsyncpgString(sqltypes.String):
237
+ render_bind_cast = True
238
+
239
+
240
+ class AsyncpgREGCONFIG(REGCONFIG):
241
+ render_bind_cast = True
242
+
243
+
244
+ class AsyncpgTime(sqltypes.Time):
245
+ render_bind_cast = True
246
+
247
+
248
+ class AsyncpgBit(BIT):
249
+ render_bind_cast = True
250
+
251
+ def bind_processor(self, dialect):
252
+ asyncpg_BitString = dialect.dbapi.asyncpg.BitString
253
+
254
+ def to_bind(value):
255
+ if isinstance(value, str):
256
+ value = BitString(value)
257
+ value = asyncpg_BitString.from_int(int(value), len(value))
258
+ return value
259
+
260
+ return to_bind
261
+
262
+ def result_processor(self, dialect, coltype):
263
+ def to_result(value):
264
+ if value is not None:
265
+ value = BitString.from_int(value.to_int(), length=len(value))
266
+ return value
267
+
268
+ return to_result
269
+
270
+
271
+ class AsyncpgByteA(BYTEA):
272
+ render_bind_cast = True
273
+
274
+
275
+ class AsyncpgDate(sqltypes.Date):
276
+ render_bind_cast = True
277
+
278
+
279
+ class AsyncpgDateTime(sqltypes.DateTime):
280
+ render_bind_cast = True
281
+
282
+
283
+ class AsyncpgBoolean(sqltypes.Boolean):
284
+ render_bind_cast = True
285
+
286
+
287
+ class AsyncPgInterval(INTERVAL):
288
+ render_bind_cast = True
289
+
290
+ @classmethod
291
+ def adapt_emulated_to_native(cls, interval, **kw):
292
+ return AsyncPgInterval(precision=interval.second_precision)
293
+
294
+
295
+ class AsyncPgEnum(ENUM):
296
+ render_bind_cast = True
297
+
298
+
299
+ class AsyncpgInteger(sqltypes.Integer):
300
+ render_bind_cast = True
301
+
302
+
303
+ class AsyncpgSmallInteger(sqltypes.SmallInteger):
304
+ render_bind_cast = True
305
+
306
+
307
+ class AsyncpgBigInteger(sqltypes.BigInteger):
308
+ render_bind_cast = True
309
+
310
+
311
+ class AsyncpgJSONIndexType(sqltypes.JSON.JSONIndexType):
312
+ pass
313
+
314
+
315
+ class AsyncpgJSONIntIndexType(sqltypes.JSON.JSONIntIndexType):
316
+ __visit_name__ = "json_int_index"
317
+
318
+ render_bind_cast = True
319
+
320
+
321
+ class AsyncpgJSONStrIndexType(sqltypes.JSON.JSONStrIndexType):
322
+ __visit_name__ = "json_str_index"
323
+
324
+ render_bind_cast = True
325
+
326
+
327
+ class AsyncpgJSONPathType(json.JSONPathType):
328
+ def bind_processor(self, dialect):
329
+ def process(value):
330
+ if isinstance(value, str):
331
+ # If it's already a string assume that it's in json path
332
+ # format. This allows using cast with json paths literals
333
+ return value
334
+ elif value:
335
+ tokens = [str(elem) for elem in value]
336
+ return tokens
337
+ else:
338
+ return []
339
+
340
+ return process
341
+
342
+
343
+ class _AsyncpgNumericCommon(sqltypes.NumericCommon):
344
+ render_bind_cast = True
345
+
346
+ def bind_processor(self, dialect):
347
+ return None
348
+
349
+ def result_processor(self, dialect, coltype):
350
+ if self.asdecimal:
351
+ if coltype in _FLOAT_TYPES:
352
+ return processors.to_decimal_processor_factory(
353
+ decimal.Decimal, self._effective_decimal_return_scale
354
+ )
355
+ elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES:
356
+ # pg8000 returns Decimal natively for 1700
357
+ return None
358
+ else:
359
+ raise exc.InvalidRequestError(
360
+ "Unknown PG numeric type: %d" % coltype
361
+ )
362
+ else:
363
+ if coltype in _FLOAT_TYPES:
364
+ # pg8000 returns float natively for 701
365
+ return None
366
+ elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES:
367
+ return processors.to_float
368
+ else:
369
+ raise exc.InvalidRequestError(
370
+ "Unknown PG numeric type: %d" % coltype
371
+ )
372
+
373
+
374
+ class AsyncpgNumeric(_AsyncpgNumericCommon, sqltypes.Numeric):
375
+ pass
376
+
377
+
378
+ class AsyncpgFloat(_AsyncpgNumericCommon, sqltypes.Float):
379
+ pass
380
+
381
+
382
+ class AsyncpgREGCLASS(REGCLASS):
383
+ render_bind_cast = True
384
+
385
+
386
+ class AsyncpgOID(OID):
387
+ render_bind_cast = True
388
+
389
+
390
+ class AsyncpgCHAR(sqltypes.CHAR):
391
+ render_bind_cast = True
392
+
393
+
394
+ class _AsyncpgRange(ranges.AbstractSingleRangeImpl):
395
+ def bind_processor(self, dialect):
396
+ asyncpg_Range = dialect.dbapi.asyncpg.Range
397
+
398
+ def to_range(value):
399
+ if isinstance(value, ranges.Range):
400
+ value = asyncpg_Range(
401
+ value.lower,
402
+ value.upper,
403
+ lower_inc=value.bounds[0] == "[",
404
+ upper_inc=value.bounds[1] == "]",
405
+ empty=value.empty,
406
+ )
407
+ return value
408
+
409
+ return to_range
410
+
411
+ def result_processor(self, dialect, coltype):
412
+ def to_range(value):
413
+ if value is not None:
414
+ empty = value.isempty
415
+ value = ranges.Range(
416
+ value.lower,
417
+ value.upper,
418
+ bounds=f"{'[' if empty or value.lower_inc else '('}" # type: ignore # noqa: E501
419
+ f"{']' if not empty and value.upper_inc else ')'}",
420
+ empty=empty,
421
+ )
422
+ return value
423
+
424
+ return to_range
425
+
426
+
427
+ class _AsyncpgMultiRange(ranges.AbstractMultiRangeImpl):
428
+ def bind_processor(self, dialect):
429
+ asyncpg_Range = dialect.dbapi.asyncpg.Range
430
+
431
+ def to_range(value):
432
+ if isinstance(value, (str, NoneType)):
433
+ return value
434
+
435
+ def to_range(value):
436
+ if isinstance(value, ranges.Range):
437
+ value = asyncpg_Range(
438
+ value.lower,
439
+ value.upper,
440
+ lower_inc=value.bounds[0] == "[",
441
+ upper_inc=value.bounds[1] == "]",
442
+ empty=value.empty,
443
+ )
444
+ return value
445
+
446
+ return [to_range(element) for element in value]
447
+
448
+ return to_range
449
+
450
+ def result_processor(self, dialect, coltype):
451
+ def to_range_array(value):
452
+ def to_range(rvalue):
453
+ if rvalue is not None:
454
+ empty = rvalue.isempty
455
+ rvalue = ranges.Range(
456
+ rvalue.lower,
457
+ rvalue.upper,
458
+ bounds=f"{'[' if empty or rvalue.lower_inc else '('}" # type: ignore # noqa: E501
459
+ f"{']' if not empty and rvalue.upper_inc else ')'}",
460
+ empty=empty,
461
+ )
462
+ return rvalue
463
+
464
+ if value is not None:
465
+ value = ranges.MultiRange(to_range(elem) for elem in value)
466
+
467
+ return value
468
+
469
+ return to_range_array
470
+
471
+
472
+ class PGExecutionContext_asyncpg(PGExecutionContext):
473
+ def handle_dbapi_exception(self, e):
474
+ if isinstance(
475
+ e,
476
+ (
477
+ self.dialect.dbapi.InvalidCachedStatementError,
478
+ self.dialect.dbapi.InternalServerError,
479
+ ),
480
+ ):
481
+ self.dialect._invalidate_schema_cache()
482
+
483
+ def pre_exec(self):
484
+ if self.isddl:
485
+ self.dialect._invalidate_schema_cache()
486
+
487
+ self.cursor._invalidate_schema_cache_asof = (
488
+ self.dialect._invalidate_schema_cache_asof
489
+ )
490
+
491
+ if not self.compiled:
492
+ return
493
+
494
+ def create_server_side_cursor(self):
495
+ return self._dbapi_connection.cursor(server_side=True)
496
+
497
+
498
+ class PGCompiler_asyncpg(PGCompiler):
499
+ pass
500
+
501
+
502
+ class PGIdentifierPreparer_asyncpg(PGIdentifierPreparer):
503
+ pass
504
+
505
+
506
+ class _AsyncpgTransaction(Protocol):
507
+ async def start(self) -> None: ...
508
+ async def commit(self) -> None: ...
509
+ async def rollback(self) -> None: ...
510
+
511
+
512
+ class _AsyncpgConnection(Protocol):
513
+ async def executemany(
514
+ self, operation: Any, seq_of_parameters: Sequence[Tuple[Any, ...]]
515
+ ) -> Any: ...
516
+
517
+ async def reload_schema_state(self) -> None: ...
518
+
519
+ async def prepare(
520
+ self, operation: Any, *, name: Optional[str] = None
521
+ ) -> Any: ...
522
+
523
+ def is_closed(self) -> bool: ...
524
+
525
+ def transaction(
526
+ self,
527
+ *,
528
+ isolation: Optional[str] = None,
529
+ readonly: bool = False,
530
+ deferrable: bool = False,
531
+ ) -> _AsyncpgTransaction: ...
532
+
533
+ def fetchrow(self, operation: str) -> Any: ...
534
+
535
+ async def close(self, timeout: int = ...) -> None: ...
536
+
537
+ def terminate(self) -> None: ...
538
+
539
+
540
+ class _AsyncpgCursor(Protocol):
541
+ def fetch(self, size: int) -> Any: ...
542
+
543
+
544
+ class AsyncAdapt_asyncpg_cursor(AsyncAdapt_dbapi_cursor):
545
+ __slots__ = (
546
+ "_description",
547
+ "_arraysize",
548
+ "_rowcount",
549
+ "_invalidate_schema_cache_asof",
550
+ )
551
+
552
+ _adapt_connection: AsyncAdapt_asyncpg_connection
553
+ _connection: _AsyncpgConnection
554
+ _cursor: Optional[_AsyncpgCursor]
555
+ _awaitable_cursor_close: bool = False
556
+
557
+ def __init__(self, adapt_connection: AsyncAdapt_asyncpg_connection):
558
+ self._adapt_connection = adapt_connection
559
+ self._connection = adapt_connection._connection
560
+ self._cursor = None
561
+ self._rows = deque()
562
+ self._description = None
563
+ self._arraysize = 1
564
+ self._rowcount = -1
565
+ self._invalidate_schema_cache_asof = 0
566
+
567
+ def _handle_exception(self, error):
568
+ self._adapt_connection._handle_exception(error)
569
+
570
+ async def _prepare_and_execute(self, operation, parameters):
571
+ adapt_connection = self._adapt_connection
572
+
573
+ async with adapt_connection._execute_mutex:
574
+ if adapt_connection._transaction is None:
575
+ await adapt_connection._start_transaction()
576
+
577
+ if parameters is None:
578
+ parameters = ()
579
+
580
+ try:
581
+ prepared_stmt, attributes = await adapt_connection._prepare(
582
+ operation, self._invalidate_schema_cache_asof
583
+ )
584
+
585
+ if attributes:
586
+ self._description = [
587
+ (
588
+ attr.name,
589
+ attr.type.oid,
590
+ None,
591
+ None,
592
+ None,
593
+ None,
594
+ None,
595
+ )
596
+ for attr in attributes
597
+ ]
598
+ else:
599
+ self._description = None
600
+
601
+ if self.server_side:
602
+ self._cursor = await prepared_stmt.cursor(*parameters)
603
+ self._rowcount = -1
604
+ else:
605
+ self._rows = deque(await prepared_stmt.fetch(*parameters))
606
+ status = prepared_stmt.get_statusmsg()
607
+
608
+ reg = re.match(
609
+ r"(?:SELECT|UPDATE|DELETE|INSERT \d+) (\d+)",
610
+ status or "",
611
+ )
612
+ if reg:
613
+ self._rowcount = int(reg.group(1))
614
+ else:
615
+ self._rowcount = -1
616
+
617
+ except Exception as error:
618
+ self._handle_exception(error)
619
+
620
+ @property
621
+ def description(self) -> Optional[_DBAPICursorDescription]:
622
+ return self._description
623
+
624
+ @property
625
+ def rowcount(self) -> int:
626
+ return self._rowcount
627
+
628
+ @property
629
+ def arraysize(self) -> int:
630
+ return self._arraysize
631
+
632
+ @arraysize.setter
633
+ def arraysize(self, value: int) -> None:
634
+ self._arraysize = value
635
+
636
+ async def _executemany(self, operation, seq_of_parameters):
637
+ adapt_connection = self._adapt_connection
638
+
639
+ self._description = None
640
+ async with adapt_connection._execute_mutex:
641
+ await adapt_connection._check_type_cache_invalidation(
642
+ self._invalidate_schema_cache_asof
643
+ )
644
+
645
+ if adapt_connection._transaction is None:
646
+ await adapt_connection._start_transaction()
647
+
648
+ try:
649
+ return await self._connection.executemany(
650
+ operation, seq_of_parameters
651
+ )
652
+ except Exception as error:
653
+ self._handle_exception(error)
654
+
655
+ def execute(self, operation, parameters=None):
656
+ await_(self._prepare_and_execute(operation, parameters))
657
+
658
+ def executemany(self, operation, seq_of_parameters):
659
+ return await_(self._executemany(operation, seq_of_parameters))
660
+
661
+ def setinputsizes(self, *inputsizes):
662
+ raise NotImplementedError()
663
+
664
+
665
+ class AsyncAdapt_asyncpg_ss_cursor(
666
+ AsyncAdapt_dbapi_ss_cursor, AsyncAdapt_asyncpg_cursor
667
+ ):
668
+ __slots__ = ("_rowbuffer",)
669
+
670
+ def __init__(self, adapt_connection):
671
+ super().__init__(adapt_connection)
672
+ self._rowbuffer = deque()
673
+
674
+ def close(self):
675
+ self._cursor = None
676
+ self._rowbuffer.clear()
677
+
678
+ def _buffer_rows(self):
679
+ assert self._cursor is not None
680
+ new_rows = await_(self._cursor.fetch(50))
681
+ self._rowbuffer.extend(new_rows)
682
+
683
+ def __aiter__(self):
684
+ return self
685
+
686
+ async def __anext__(self):
687
+ while True:
688
+ while self._rowbuffer:
689
+ yield self._rowbuffer.popleft()
690
+
691
+ self._buffer_rows()
692
+ if not self._rowbuffer:
693
+ break
694
+
695
+ def fetchone(self):
696
+ if not self._rowbuffer:
697
+ self._buffer_rows()
698
+ if not self._rowbuffer:
699
+ return None
700
+ return self._rowbuffer.popleft()
701
+
702
+ def fetchmany(self, size=None):
703
+ if size is None:
704
+ return self.fetchall()
705
+
706
+ if not self._rowbuffer:
707
+ self._buffer_rows()
708
+
709
+ assert self._cursor is not None
710
+ rb = self._rowbuffer
711
+ lb = len(rb)
712
+ if size > lb:
713
+ rb.extend(await_(self._cursor.fetch(size - lb)))
714
+
715
+ return [rb.popleft() for _ in range(min(size, len(rb)))]
716
+
717
+ def fetchall(self):
718
+ ret = list(self._rowbuffer)
719
+ ret.extend(await_(self._all()))
720
+ self._rowbuffer.clear()
721
+ return ret
722
+
723
+ async def _all(self):
724
+ rows = []
725
+
726
+ assert self._cursor is not None
727
+
728
+ # TODO: looks like we have to hand-roll some kind of batching here.
729
+ # hardcoding for the moment but this should be improved.
730
+ while True:
731
+ batch = await self._cursor.fetch(1000)
732
+ if batch:
733
+ rows.extend(batch)
734
+ continue
735
+ else:
736
+ break
737
+ return rows
738
+
739
+ def executemany(self, operation, seq_of_parameters):
740
+ raise NotImplementedError(
741
+ "server side cursor doesn't support executemany yet"
742
+ )
743
+
744
+
745
+ class AsyncAdapt_asyncpg_connection(
746
+ AsyncAdapt_terminate, AsyncAdapt_dbapi_connection
747
+ ):
748
+ _cursor_cls = AsyncAdapt_asyncpg_cursor
749
+ _ss_cursor_cls = AsyncAdapt_asyncpg_ss_cursor
750
+
751
+ _connection: _AsyncpgConnection
752
+ _transaction: Optional[_AsyncpgTransaction]
753
+
754
+ __slots__ = (
755
+ "isolation_level",
756
+ "_isolation_setting",
757
+ "readonly",
758
+ "deferrable",
759
+ "_transaction",
760
+ "_prepared_statement_cache",
761
+ "_prepared_statement_name_func",
762
+ "_invalidate_schema_cache_asof",
763
+ )
764
+
765
+ def __init__(
766
+ self,
767
+ dbapi,
768
+ connection,
769
+ prepared_statement_cache_size=100,
770
+ prepared_statement_name_func=None,
771
+ ):
772
+ super().__init__(dbapi, connection)
773
+ self.isolation_level = self._isolation_setting = None
774
+ self.readonly = False
775
+ self.deferrable = False
776
+ self._transaction = None
777
+ self._invalidate_schema_cache_asof = time.time()
778
+
779
+ if prepared_statement_cache_size:
780
+ self._prepared_statement_cache = util.LRUCache(
781
+ prepared_statement_cache_size
782
+ )
783
+ else:
784
+ self._prepared_statement_cache = None
785
+
786
+ if prepared_statement_name_func:
787
+ self._prepared_statement_name_func = prepared_statement_name_func
788
+ else:
789
+ self._prepared_statement_name_func = self._default_name_func
790
+
791
+ async def _check_type_cache_invalidation(self, invalidate_timestamp):
792
+ if invalidate_timestamp > self._invalidate_schema_cache_asof:
793
+ await self._connection.reload_schema_state()
794
+ self._invalidate_schema_cache_asof = invalidate_timestamp
795
+
796
+ async def _prepare(self, operation, invalidate_timestamp):
797
+ await self._check_type_cache_invalidation(invalidate_timestamp)
798
+
799
+ cache = self._prepared_statement_cache
800
+ if cache is None:
801
+ prepared_stmt = await self._connection.prepare(
802
+ operation, name=self._prepared_statement_name_func()
803
+ )
804
+ attributes = prepared_stmt.get_attributes()
805
+ return prepared_stmt, attributes
806
+
807
+ # asyncpg uses a type cache for the "attributes" which seems to go
808
+ # stale independently of the PreparedStatement itself, so place that
809
+ # collection in the cache as well.
810
+ if operation in cache:
811
+ prepared_stmt, attributes, cached_timestamp = cache[operation]
812
+
813
+ # preparedstatements themselves also go stale for certain DDL
814
+ # changes such as size of a VARCHAR changing, so there is also
815
+ # a cross-connection invalidation timestamp
816
+ if cached_timestamp > invalidate_timestamp:
817
+ return prepared_stmt, attributes
818
+
819
+ prepared_stmt = await self._connection.prepare(
820
+ operation, name=self._prepared_statement_name_func()
821
+ )
822
+ attributes = prepared_stmt.get_attributes()
823
+ cache[operation] = (prepared_stmt, attributes, time.time())
824
+
825
+ return prepared_stmt, attributes
826
+
827
+ @classmethod
828
+ def _handle_exception_no_connection(
829
+ cls, dbapi: Any, error: Exception
830
+ ) -> NoReturn:
831
+ if not isinstance(error, AsyncAdapt_asyncpg_dbapi.Error):
832
+ exception_mapping = dbapi._asyncpg_error_translate
833
+
834
+ for super_ in type(error).__mro__:
835
+ if super_ in exception_mapping:
836
+ message = error.args[0]
837
+ translated_error = exception_mapping[super_](
838
+ message, error
839
+ )
840
+ raise translated_error from error
841
+ super()._handle_exception_no_connection(dbapi, error)
842
+
843
+ def _handle_exception(self, error: Exception) -> NoReturn:
844
+ if self._connection.is_closed():
845
+ self._transaction = None
846
+
847
+ super()._handle_exception(error)
848
+
849
+ @property
850
+ def autocommit(self):
851
+ return self.isolation_level == "autocommit"
852
+
853
+ @autocommit.setter
854
+ def autocommit(self, value):
855
+ if value:
856
+ self.isolation_level = "autocommit"
857
+ else:
858
+ self.isolation_level = self._isolation_setting
859
+
860
+ def ping(self):
861
+ try:
862
+ _ = await_(self._async_ping())
863
+ except Exception as error:
864
+ self._handle_exception(error)
865
+
866
+ async def _async_ping(self):
867
+ if self._transaction is None and self.isolation_level != "autocommit":
868
+ # create a transaction explicitly to support pgbouncer
869
+ # transaction mode. See #10226
870
+ tr = self._connection.transaction()
871
+ await tr.start()
872
+ try:
873
+ await self._connection.fetchrow(";")
874
+ finally:
875
+ await tr.rollback()
876
+ else:
877
+ await self._connection.fetchrow(";")
878
+
879
+ def set_isolation_level(self, level):
880
+ self.rollback()
881
+ self.isolation_level = self._isolation_setting = level
882
+
883
+ async def _start_transaction(self):
884
+ if self.isolation_level == "autocommit":
885
+ return
886
+
887
+ assert self._transaction is None
888
+ try:
889
+ self._transaction = self._connection.transaction(
890
+ isolation=self.isolation_level,
891
+ readonly=self.readonly,
892
+ deferrable=self.deferrable,
893
+ )
894
+ await self._transaction.start()
895
+ except Exception as error:
896
+ self._handle_exception(error)
897
+
898
+ async def _call_and_discard(self, fn: Callable[[], Awaitable[Any]]):
899
+ try:
900
+ await fn()
901
+ finally:
902
+ # if asyncpg fn was actually called, then whether or
903
+ # not it raised or succeeded, the transaction is done, discard it
904
+ self._transaction = None
905
+
906
+ def rollback(self):
907
+ if self._transaction is not None:
908
+ try:
909
+ await_(self._call_and_discard(self._transaction.rollback))
910
+ except Exception as error:
911
+ # don't dereference asyncpg transaction if we didn't
912
+ # actually try to call rollback() on it
913
+ self._handle_exception(error)
914
+
915
+ def commit(self):
916
+ if self._transaction is not None:
917
+ try:
918
+ await_(self._call_and_discard(self._transaction.commit))
919
+ except Exception as error:
920
+ # don't dereference asyncpg transaction if we didn't
921
+ # actually try to call commit() on it
922
+ self._handle_exception(error)
923
+
924
+ def close(self):
925
+ self.rollback()
926
+
927
+ await_(self._connection.close())
928
+
929
+ def _terminate_handled_exceptions(self):
930
+ return super()._terminate_handled_exceptions() + (
931
+ self.dbapi.asyncpg.PostgresError,
932
+ )
933
+
934
+ async def _terminate_graceful_close(self) -> None:
935
+ # timeout added in asyncpg 0.14.0 December 2017
936
+ await self._connection.close(timeout=2)
937
+ self._transaction = None
938
+
939
+ def _terminate_force_close(self) -> None:
940
+ self._connection.terminate()
941
+ self._transaction = None
942
+
943
+ @staticmethod
944
+ def _default_name_func():
945
+ return None
946
+
947
+
948
+ class AsyncAdapt_asyncpg_dbapi(AsyncAdapt_dbapi_module):
949
+ def __init__(self, asyncpg):
950
+ super().__init__(asyncpg)
951
+ self.asyncpg = asyncpg
952
+ self.paramstyle = "numeric_dollar"
953
+
954
+ def connect(self, *arg, **kw):
955
+ creator_fn = kw.pop("async_creator_fn", self.asyncpg.connect)
956
+ prepared_statement_cache_size = kw.pop(
957
+ "prepared_statement_cache_size", 100
958
+ )
959
+ prepared_statement_name_func = kw.pop(
960
+ "prepared_statement_name_func", None
961
+ )
962
+
963
+ return await_(
964
+ AsyncAdapt_asyncpg_connection.create(
965
+ self,
966
+ creator_fn(*arg, **kw),
967
+ prepared_statement_cache_size=prepared_statement_cache_size,
968
+ prepared_statement_name_func=prepared_statement_name_func,
969
+ )
970
+ )
971
+
972
+ class Error(AsyncAdapt_Error):
973
+
974
+ pgcode: str | None
975
+
976
+ sqlstate: str | None
977
+
978
+ detail: str | None
979
+
980
+ def __init__(self, message, error=None):
981
+ super().__init__(message, error)
982
+ self.detail = getattr(error, "detail", None)
983
+ self.pgcode = self.sqlstate = getattr(error, "sqlstate", None)
984
+
985
+ class Warning(AsyncAdapt_Error): # noqa
986
+ pass
987
+
988
+ class InterfaceError(Error):
989
+ pass
990
+
991
+ class DatabaseError(Error):
992
+ pass
993
+
994
+ class InternalError(DatabaseError):
995
+ pass
996
+
997
+ class OperationalError(DatabaseError):
998
+ pass
999
+
1000
+ class ProgrammingError(DatabaseError):
1001
+ pass
1002
+
1003
+ class IntegrityError(DatabaseError):
1004
+ pass
1005
+
1006
+ class RestrictViolationError(IntegrityError):
1007
+ pass
1008
+
1009
+ class NotNullViolationError(IntegrityError):
1010
+ pass
1011
+
1012
+ class ForeignKeyViolationError(IntegrityError):
1013
+ pass
1014
+
1015
+ class UniqueViolationError(IntegrityError):
1016
+ pass
1017
+
1018
+ class CheckViolationError(IntegrityError):
1019
+ pass
1020
+
1021
+ class ExclusionViolationError(IntegrityError):
1022
+ pass
1023
+
1024
+ class DataError(DatabaseError):
1025
+ pass
1026
+
1027
+ class NotSupportedError(DatabaseError):
1028
+ pass
1029
+
1030
+ class InternalServerError(InternalError):
1031
+ pass
1032
+
1033
+ class InvalidCachedStatementError(NotSupportedError):
1034
+ def __init__(self, message, error=None):
1035
+ super().__init__(
1036
+ message + " (SQLAlchemy asyncpg dialect will now invalidate "
1037
+ "all prepared caches in response to this exception)",
1038
+ )
1039
+
1040
+ # pep-249 datatype placeholders. As of SQLAlchemy 2.0 these aren't
1041
+ # used, however the test suite looks for these in a few cases.
1042
+ STRING = util.symbol("STRING")
1043
+ NUMBER = util.symbol("NUMBER")
1044
+ DATETIME = util.symbol("DATETIME")
1045
+
1046
+ @util.memoized_property
1047
+ def _asyncpg_error_translate(self):
1048
+ import asyncpg
1049
+
1050
+ return {
1051
+ asyncpg.exceptions.IntegrityConstraintViolationError: self.IntegrityError, # noqa: E501
1052
+ asyncpg.exceptions.PostgresError: self.Error,
1053
+ asyncpg.exceptions.SyntaxOrAccessError: self.ProgrammingError,
1054
+ asyncpg.exceptions.InterfaceError: self.InterfaceError,
1055
+ asyncpg.exceptions.InvalidCachedStatementError: self.InvalidCachedStatementError, # noqa: E501
1056
+ asyncpg.exceptions.InternalServerError: self.InternalServerError,
1057
+ asyncpg.exceptions.RestrictViolationError: self.RestrictViolationError, # noqa: E501
1058
+ asyncpg.exceptions.NotNullViolationError: self.NotNullViolationError, # noqa: E501
1059
+ asyncpg.exceptions.ForeignKeyViolationError: self.ForeignKeyViolationError, # noqa: E501
1060
+ asyncpg.exceptions.UniqueViolationError: self.UniqueViolationError,
1061
+ asyncpg.exceptions.CheckViolationError: self.CheckViolationError,
1062
+ asyncpg.exceptions.ExclusionViolationError: self.ExclusionViolationError, # noqa: E501
1063
+ }
1064
+
1065
+ def Binary(self, value):
1066
+ return value
1067
+
1068
+
1069
+ class PGDialect_asyncpg(PGDialect):
1070
+ driver = "asyncpg"
1071
+ supports_statement_cache = True
1072
+
1073
+ supports_server_side_cursors = True
1074
+
1075
+ render_bind_cast = True
1076
+ has_terminate = True
1077
+
1078
+ default_paramstyle = "numeric_dollar"
1079
+ supports_sane_multi_rowcount = False
1080
+ execution_ctx_cls = PGExecutionContext_asyncpg
1081
+ statement_compiler = PGCompiler_asyncpg
1082
+ preparer = PGIdentifierPreparer_asyncpg
1083
+
1084
+ supports_native_json_serialization = False
1085
+ supports_native_json_deserialization = True
1086
+ dialect_injects_custom_json_deserializer = True
1087
+
1088
+ colspecs = util.update_copy(
1089
+ PGDialect.colspecs,
1090
+ {
1091
+ sqltypes.String: AsyncpgString,
1092
+ sqltypes.ARRAY: AsyncpgARRAY,
1093
+ BIT: AsyncpgBit,
1094
+ CITEXT: CITEXT,
1095
+ REGCONFIG: AsyncpgREGCONFIG,
1096
+ sqltypes.Time: AsyncpgTime,
1097
+ sqltypes.Date: AsyncpgDate,
1098
+ sqltypes.DateTime: AsyncpgDateTime,
1099
+ sqltypes.Interval: AsyncPgInterval,
1100
+ INTERVAL: AsyncPgInterval,
1101
+ sqltypes.Boolean: AsyncpgBoolean,
1102
+ sqltypes.Integer: AsyncpgInteger,
1103
+ sqltypes.SmallInteger: AsyncpgSmallInteger,
1104
+ sqltypes.BigInteger: AsyncpgBigInteger,
1105
+ sqltypes.Numeric: AsyncpgNumeric,
1106
+ sqltypes.Float: AsyncpgFloat,
1107
+ sqltypes.LargeBinary: AsyncpgByteA,
1108
+ sqltypes.JSON.JSONPathType: AsyncpgJSONPathType,
1109
+ sqltypes.JSON.JSONIndexType: AsyncpgJSONIndexType,
1110
+ sqltypes.JSON.JSONIntIndexType: AsyncpgJSONIntIndexType,
1111
+ sqltypes.JSON.JSONStrIndexType: AsyncpgJSONStrIndexType,
1112
+ sqltypes.Enum: AsyncPgEnum,
1113
+ OID: AsyncpgOID,
1114
+ REGCLASS: AsyncpgREGCLASS,
1115
+ sqltypes.CHAR: AsyncpgCHAR,
1116
+ ranges.AbstractSingleRange: _AsyncpgRange,
1117
+ ranges.AbstractMultiRange: _AsyncpgMultiRange,
1118
+ },
1119
+ )
1120
+ is_async = True
1121
+ _invalidate_schema_cache_asof = 0
1122
+
1123
+ def _invalidate_schema_cache(self):
1124
+ self._invalidate_schema_cache_asof = time.time()
1125
+
1126
+ @util.memoized_property
1127
+ def _dbapi_version(self):
1128
+ if self.dbapi and hasattr(self.dbapi, "__version__"):
1129
+ return tuple(
1130
+ [
1131
+ int(x)
1132
+ for x in re.findall(
1133
+ r"(\d+)(?:[-\.]?|$)", self.dbapi.__version__
1134
+ )
1135
+ ]
1136
+ )
1137
+ else:
1138
+ return (99, 99, 99)
1139
+
1140
+ @classmethod
1141
+ def import_dbapi(cls):
1142
+ return AsyncAdapt_asyncpg_dbapi(__import__("asyncpg"))
1143
+
1144
+ @util.memoized_property
1145
+ def _isolation_lookup(self):
1146
+ return {
1147
+ "AUTOCOMMIT": "autocommit",
1148
+ "READ COMMITTED": "read_committed",
1149
+ "REPEATABLE READ": "repeatable_read",
1150
+ "SERIALIZABLE": "serializable",
1151
+ }
1152
+
1153
+ def get_isolation_level_values(self, dbapi_connection):
1154
+ return list(self._isolation_lookup)
1155
+
1156
+ def set_isolation_level(self, dbapi_connection, level):
1157
+ dbapi_connection.set_isolation_level(self._isolation_lookup[level])
1158
+
1159
+ def detect_autocommit_setting(self, dbapi_conn) -> bool:
1160
+ return bool(dbapi_conn.autocommit)
1161
+
1162
+ def set_readonly(self, connection, value):
1163
+ connection.readonly = value
1164
+
1165
+ def get_readonly(self, connection):
1166
+ return connection.readonly
1167
+
1168
+ def set_deferrable(self, connection, value):
1169
+ connection.deferrable = value
1170
+
1171
+ def get_deferrable(self, connection):
1172
+ return connection.deferrable
1173
+
1174
+ def do_terminate(self, dbapi_connection) -> None:
1175
+ dbapi_connection.terminate()
1176
+
1177
+ def create_connect_args(self, url):
1178
+ opts = url.translate_connect_args(username="user")
1179
+ multihosts, multiports = self._split_multihost_from_url(url)
1180
+
1181
+ opts.update(url.query)
1182
+
1183
+ if multihosts:
1184
+ assert multiports
1185
+ if len(multihosts) == 1:
1186
+ opts["host"] = multihosts[0]
1187
+ if multiports[0] is not None:
1188
+ opts["port"] = multiports[0]
1189
+ elif not all(multihosts):
1190
+ raise exc.ArgumentError(
1191
+ "All hosts are required to be present"
1192
+ " for asyncpg multiple host URL"
1193
+ )
1194
+ elif not all(multiports):
1195
+ raise exc.ArgumentError(
1196
+ "All ports are required to be present"
1197
+ " for asyncpg multiple host URL"
1198
+ )
1199
+ else:
1200
+ opts["host"] = list(multihosts)
1201
+ opts["port"] = list(multiports)
1202
+ else:
1203
+ util.coerce_kw_type(opts, "port", int)
1204
+ util.coerce_kw_type(opts, "prepared_statement_cache_size", int)
1205
+ return ([], opts)
1206
+
1207
+ def do_ping(self, dbapi_connection):
1208
+ dbapi_connection.ping()
1209
+ return True
1210
+
1211
+ def is_disconnect(self, e, connection, cursor):
1212
+ if connection:
1213
+ return connection._connection.is_closed()
1214
+ else:
1215
+ return isinstance(
1216
+ e, self.dbapi.InterfaceError
1217
+ ) and "connection is closed" in str(e)
1218
+
1219
+ async def setup_asyncpg_json_codec(self, conn):
1220
+ """set up JSON codec for asyncpg.
1221
+
1222
+ This occurs for all new connections and
1223
+ can be overridden by third party dialects.
1224
+
1225
+ .. versionadded:: 1.4.27
1226
+
1227
+ """
1228
+
1229
+ asyncpg_connection = conn._connection
1230
+ deserializer = self._json_deserializer or _py_json.loads
1231
+
1232
+ def _json_decoder(bin_value):
1233
+ return deserializer(bin_value.decode())
1234
+
1235
+ await asyncpg_connection.set_type_codec(
1236
+ "json",
1237
+ encoder=str.encode,
1238
+ decoder=_json_decoder,
1239
+ schema="pg_catalog",
1240
+ format="binary",
1241
+ )
1242
+
1243
+ async def setup_asyncpg_jsonb_codec(self, conn):
1244
+ """set up JSONB codec for asyncpg.
1245
+
1246
+ This occurs for all new connections and
1247
+ can be overridden by third party dialects.
1248
+
1249
+ .. versionadded:: 1.4.27
1250
+
1251
+ """
1252
+
1253
+ asyncpg_connection = conn._connection
1254
+ deserializer = self._json_deserializer or _py_json.loads
1255
+
1256
+ def _jsonb_encoder(str_value):
1257
+ # \x01 is the prefix for jsonb used by PostgreSQL.
1258
+ # asyncpg requires it when format='binary'
1259
+ return b"\x01" + str_value.encode()
1260
+
1261
+ deserializer = self._json_deserializer or _py_json.loads
1262
+
1263
+ def _jsonb_decoder(bin_value):
1264
+ # the byte is the \x01 prefix for jsonb used by PostgreSQL.
1265
+ # asyncpg returns it when format='binary'
1266
+ return deserializer(bin_value[1:].decode())
1267
+
1268
+ await asyncpg_connection.set_type_codec(
1269
+ "jsonb",
1270
+ encoder=_jsonb_encoder,
1271
+ decoder=_jsonb_decoder,
1272
+ schema="pg_catalog",
1273
+ format="binary",
1274
+ )
1275
+
1276
+ async def _disable_asyncpg_inet_codecs(self, conn):
1277
+ asyncpg_connection = conn._connection
1278
+
1279
+ await asyncpg_connection.set_type_codec(
1280
+ "inet",
1281
+ encoder=lambda s: s,
1282
+ decoder=lambda s: s,
1283
+ schema="pg_catalog",
1284
+ format="text",
1285
+ )
1286
+
1287
+ await asyncpg_connection.set_type_codec(
1288
+ "cidr",
1289
+ encoder=lambda s: s,
1290
+ decoder=lambda s: s,
1291
+ schema="pg_catalog",
1292
+ format="text",
1293
+ )
1294
+
1295
+ def on_connect(self):
1296
+ """on_connect for asyncpg
1297
+
1298
+ A major component of this for asyncpg is to set up type decoders at the
1299
+ asyncpg level.
1300
+
1301
+ See https://github.com/MagicStack/asyncpg/issues/623 for
1302
+ notes on JSON/JSONB implementation.
1303
+
1304
+ """
1305
+
1306
+ super_connect = super().on_connect()
1307
+
1308
+ def connect(conn):
1309
+ await_(self.setup_asyncpg_json_codec(conn))
1310
+ await_(self.setup_asyncpg_jsonb_codec(conn))
1311
+
1312
+ if self._native_inet_types is False:
1313
+ await_(self._disable_asyncpg_inet_codecs(conn))
1314
+ if super_connect is not None:
1315
+ super_connect(conn)
1316
+
1317
+ return connect
1318
+
1319
+ def get_driver_connection(self, connection):
1320
+ return connection._connection
1321
+
1322
+
1323
+ dialect = PGDialect_asyncpg