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