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