asyncpg.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  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. r"""
  9. .. dialect:: postgresql+asyncpg
  10. :name: asyncpg
  11. :dbapi: asyncpg
  12. :connectstring: postgresql+asyncpg://user:password@host:port/dbname[?key=value&key=value...]
  13. :url: https://magicstack.github.io/asyncpg/
  14. The asyncpg dialect is SQLAlchemy's first Python asyncio dialect.
  15. Using a special asyncio mediation layer, the asyncpg dialect is usable
  16. as the backend for the :ref:`SQLAlchemy asyncio <asyncio_toplevel>`
  17. extension package.
  18. This dialect should normally be used only with the
  19. :func:`_asyncio.create_async_engine` engine creation function::
  20. from sqlalchemy.ext.asyncio import create_async_engine
  21. engine = create_async_engine("postgresql+asyncpg://user:pass@hostname/dbname")
  22. .. versionadded:: 1.4
  23. .. note::
  24. By default asyncpg does not decode the ``json`` and ``jsonb`` types and
  25. returns them as strings. SQLAlchemy sets default type decoder for ``json``
  26. and ``jsonb`` types using the python builtin ``json.loads`` function.
  27. The json implementation used can be changed by setting the attribute
  28. ``json_deserializer`` when creating the engine with
  29. :func:`create_engine` or :func:`create_async_engine`.
  30. .. _asyncpg_multihost:
  31. Multihost Connections
  32. --------------------------
  33. The asyncpg dialect features support for multiple fallback hosts in the
  34. same way as that of the psycopg2 and psycopg dialects. The
  35. syntax is the same,
  36. using ``host=<host>:<port>`` combinations as additional query string arguments;
  37. however, there is no default port, so all hosts must have a complete port number
  38. present, otherwise an exception is raised::
  39. engine = create_async_engine(
  40. "postgresql+asyncpg://user:password@/dbname?host=HostA:5432&host=HostB:5432&host=HostC:5432"
  41. )
  42. For complete background on this syntax, see :ref:`psycopg2_multi_host`.
  43. .. versionadded:: 2.0.18
  44. .. seealso::
  45. :ref:`psycopg2_multi_host`
  46. .. _asyncpg_prepared_statement_cache:
  47. Prepared Statement Cache
  48. --------------------------
  49. The asyncpg SQLAlchemy dialect makes use of ``asyncpg.connection.prepare()``
  50. for all statements. The prepared statement objects are cached after
  51. construction which appears to grant a 10% or more performance improvement for
  52. statement invocation. The cache is on a per-DBAPI connection basis, which
  53. means that the primary storage for prepared statements is within DBAPI
  54. connections pooled within the connection pool. The size of this cache
  55. defaults to 100 statements per DBAPI connection and may be adjusted using the
  56. ``prepared_statement_cache_size`` DBAPI argument (note that while this argument
  57. is implemented by SQLAlchemy, it is part of the DBAPI emulation portion of the
  58. asyncpg dialect, therefore is handled as a DBAPI argument, not a dialect
  59. argument)::
  60. engine = create_async_engine("postgresql+asyncpg://user:pass@hostname/dbname?prepared_statement_cache_size=500")
  61. To disable the prepared statement cache, use a value of zero::
  62. engine = create_async_engine("postgresql+asyncpg://user:pass@hostname/dbname?prepared_statement_cache_size=0")
  63. .. versionadded:: 1.4.0b2 Added ``prepared_statement_cache_size`` for asyncpg.
  64. .. warning:: The ``asyncpg`` database driver necessarily uses caches for
  65. PostgreSQL type OIDs, which become stale when custom PostgreSQL datatypes
  66. such as ``ENUM`` objects are changed via DDL operations. Additionally,
  67. prepared statements themselves which are optionally cached by SQLAlchemy's
  68. driver as described above may also become "stale" when DDL has been emitted
  69. to the PostgreSQL database which modifies the tables or other objects
  70. involved in a particular prepared statement.
  71. The SQLAlchemy asyncpg dialect will invalidate these caches within its local
  72. process when statements that represent DDL are emitted on a local
  73. connection, but this is only controllable within a single Python process /
  74. database engine. If DDL changes are made from other database engines
  75. and/or processes, a running application may encounter asyncpg exceptions
  76. ``InvalidCachedStatementError`` and/or ``InternalServerError("cache lookup
  77. failed for type <oid>")`` if it refers to pooled database connections which
  78. operated upon the previous structures. The SQLAlchemy asyncpg dialect will
  79. recover from these error cases when the driver raises these exceptions by
  80. clearing its internal caches as well as those of the asyncpg driver in
  81. response to them, but cannot prevent them from being raised in the first
  82. place if the cached prepared statement or asyncpg type caches have gone
  83. stale, nor can it retry the statement as the PostgreSQL transaction is
  84. invalidated when these errors occur.
  85. .. _asyncpg_prepared_statement_name:
  86. Prepared Statement Name
  87. -----------------------
  88. By default, asyncpg enumerates prepared statements in numeric order, which
  89. can lead to errors if a name has already been taken for another prepared
  90. statement. This issue can arise if your application uses database proxies
  91. such as PgBouncer to handle connections. One possible workaround is to
  92. use dynamic prepared statement names, which asyncpg now supports through
  93. an optional ``name`` value for the statement name. This allows you to
  94. generate your own unique names that won't conflict with existing ones.
  95. To achieve this, you can provide a function that will be called every time
  96. a prepared statement is prepared::
  97. from uuid import uuid4
  98. engine = create_async_engine(
  99. "postgresql+asyncpg://user:pass@hostname/dbname",
  100. poolclass=NullPool,
  101. connect_args={
  102. 'prepared_statement_name_func': lambda: f'__asyncpg_{uuid4()}__',
  103. },
  104. )
  105. .. seealso::
  106. https://github.com/MagicStack/asyncpg/issues/837
  107. https://github.com/sqlalchemy/sqlalchemy/issues/6467
  108. .. warning:: To prevent a buildup of useless prepared statements in
  109. your application, it's important to use the :class:`.NullPool` pool
  110. class, and to configure PgBouncer to use `DISCARD <https://www.postgresql.org/docs/current/sql-discard.html>`_
  111. when returning connections. The DISCARD command is used to release resources held by the db connection,
  112. including prepared statements. Without proper setup, prepared statements can
  113. accumulate quickly and cause performance issues.
  114. Disabling the PostgreSQL JIT to improve ENUM datatype handling
  115. ---------------------------------------------------------------
  116. Asyncpg has an `issue <https://github.com/MagicStack/asyncpg/issues/727>`_ when
  117. using PostgreSQL ENUM datatypes, where upon the creation of new database
  118. connections, an expensive query may be emitted in order to retrieve metadata
  119. regarding custom types which has been shown to negatively affect performance.
  120. To mitigate this issue, the PostgreSQL "jit" setting may be disabled from the
  121. client using this setting passed to :func:`_asyncio.create_async_engine`::
  122. engine = create_async_engine(
  123. "postgresql+asyncpg://user:password@localhost/tmp",
  124. connect_args={"server_settings": {"jit": "off"}},
  125. )
  126. .. seealso::
  127. https://github.com/MagicStack/asyncpg/issues/727
  128. """ # noqa
  129. from __future__ import annotations
  130. import collections
  131. import decimal
  132. import json as _py_json
  133. import re
  134. import time
  135. from typing import cast
  136. from typing import TYPE_CHECKING
  137. from . import json
  138. from . import ranges
  139. from .array import ARRAY as PGARRAY
  140. from .base import _DECIMAL_TYPES
  141. from .base import _FLOAT_TYPES
  142. from .base import _INT_TYPES
  143. from .base import ENUM
  144. from .base import INTERVAL
  145. from .base import OID
  146. from .base import PGCompiler
  147. from .base import PGDialect
  148. from .base import PGExecutionContext
  149. from .base import PGIdentifierPreparer
  150. from .base import REGCLASS
  151. from .base import REGCONFIG
  152. from .types import BIT
  153. from .types import BYTEA
  154. from .types import CITEXT
  155. from ... import exc
  156. from ... import pool
  157. from ... import util
  158. from ...engine import AdaptedConnection
  159. from ...engine import processors
  160. from ...sql import sqltypes
  161. from ...util.concurrency import asyncio
  162. from ...util.concurrency import await_fallback
  163. from ...util.concurrency import await_only
  164. if TYPE_CHECKING:
  165. from typing import Iterable
  166. class AsyncpgARRAY(PGARRAY):
  167. render_bind_cast = True
  168. class AsyncpgString(sqltypes.String):
  169. render_bind_cast = True
  170. class AsyncpgREGCONFIG(REGCONFIG):
  171. render_bind_cast = True
  172. class AsyncpgTime(sqltypes.Time):
  173. render_bind_cast = True
  174. class AsyncpgBit(BIT):
  175. render_bind_cast = True
  176. class AsyncpgByteA(BYTEA):
  177. render_bind_cast = True
  178. class AsyncpgDate(sqltypes.Date):
  179. render_bind_cast = True
  180. class AsyncpgDateTime(sqltypes.DateTime):
  181. render_bind_cast = True
  182. class AsyncpgBoolean(sqltypes.Boolean):
  183. render_bind_cast = True
  184. class AsyncPgInterval(INTERVAL):
  185. render_bind_cast = True
  186. @classmethod
  187. def adapt_emulated_to_native(cls, interval, **kw):
  188. return AsyncPgInterval(precision=interval.second_precision)
  189. class AsyncPgEnum(ENUM):
  190. render_bind_cast = True
  191. class AsyncpgInteger(sqltypes.Integer):
  192. render_bind_cast = True
  193. class AsyncpgBigInteger(sqltypes.BigInteger):
  194. render_bind_cast = True
  195. class AsyncpgJSON(json.JSON):
  196. render_bind_cast = True
  197. def result_processor(self, dialect, coltype):
  198. return None
  199. class AsyncpgJSONB(json.JSONB):
  200. render_bind_cast = True
  201. def result_processor(self, dialect, coltype):
  202. return None
  203. class AsyncpgJSONIndexType(sqltypes.JSON.JSONIndexType):
  204. pass
  205. class AsyncpgJSONIntIndexType(sqltypes.JSON.JSONIntIndexType):
  206. __visit_name__ = "json_int_index"
  207. render_bind_cast = True
  208. class AsyncpgJSONStrIndexType(sqltypes.JSON.JSONStrIndexType):
  209. __visit_name__ = "json_str_index"
  210. render_bind_cast = True
  211. class AsyncpgJSONPathType(json.JSONPathType):
  212. def bind_processor(self, dialect):
  213. def process(value):
  214. if isinstance(value, str):
  215. # If it's already a string assume that it's in json path
  216. # format. This allows using cast with json paths literals
  217. return value
  218. elif value:
  219. tokens = [str(elem) for elem in value]
  220. return tokens
  221. else:
  222. return []
  223. return process
  224. class AsyncpgNumeric(sqltypes.Numeric):
  225. render_bind_cast = True
  226. def bind_processor(self, dialect):
  227. return None
  228. def result_processor(self, dialect, coltype):
  229. if self.asdecimal:
  230. if coltype in _FLOAT_TYPES:
  231. return processors.to_decimal_processor_factory(
  232. decimal.Decimal, self._effective_decimal_return_scale
  233. )
  234. elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES:
  235. # pg8000 returns Decimal natively for 1700
  236. return None
  237. else:
  238. raise exc.InvalidRequestError(
  239. "Unknown PG numeric type: %d" % coltype
  240. )
  241. else:
  242. if coltype in _FLOAT_TYPES:
  243. # pg8000 returns float natively for 701
  244. return None
  245. elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES:
  246. return processors.to_float
  247. else:
  248. raise exc.InvalidRequestError(
  249. "Unknown PG numeric type: %d" % coltype
  250. )
  251. class AsyncpgFloat(AsyncpgNumeric, sqltypes.Float):
  252. __visit_name__ = "float"
  253. render_bind_cast = True
  254. class AsyncpgREGCLASS(REGCLASS):
  255. render_bind_cast = True
  256. class AsyncpgOID(OID):
  257. render_bind_cast = True
  258. class AsyncpgCHAR(sqltypes.CHAR):
  259. render_bind_cast = True
  260. class _AsyncpgRange(ranges.AbstractRangeImpl):
  261. def bind_processor(self, dialect):
  262. asyncpg_Range = dialect.dbapi.asyncpg.Range
  263. def to_range(value):
  264. if isinstance(value, ranges.Range):
  265. value = asyncpg_Range(
  266. value.lower,
  267. value.upper,
  268. lower_inc=value.bounds[0] == "[",
  269. upper_inc=value.bounds[1] == "]",
  270. empty=value.empty,
  271. )
  272. return value
  273. return to_range
  274. def result_processor(self, dialect, coltype):
  275. def to_range(value):
  276. if value is not None:
  277. empty = value.isempty
  278. value = ranges.Range(
  279. value.lower,
  280. value.upper,
  281. bounds=f"{'[' if empty or value.lower_inc else '('}" # type: ignore # noqa: E501
  282. f"{']' if not empty and value.upper_inc else ')'}",
  283. empty=empty,
  284. )
  285. return value
  286. return to_range
  287. class _AsyncpgMultiRange(ranges.AbstractMultiRangeImpl):
  288. def bind_processor(self, dialect):
  289. asyncpg_Range = dialect.dbapi.asyncpg.Range
  290. NoneType = type(None)
  291. def to_range(value):
  292. if isinstance(value, (str, NoneType)):
  293. return value
  294. def to_range(value):
  295. if isinstance(value, ranges.Range):
  296. value = asyncpg_Range(
  297. value.lower,
  298. value.upper,
  299. lower_inc=value.bounds[0] == "[",
  300. upper_inc=value.bounds[1] == "]",
  301. empty=value.empty,
  302. )
  303. return value
  304. return [
  305. to_range(element)
  306. for element in cast("Iterable[ranges.Range]", value)
  307. ]
  308. return to_range
  309. def result_processor(self, dialect, coltype):
  310. def to_range_array(value):
  311. def to_range(rvalue):
  312. if rvalue is not None:
  313. empty = rvalue.isempty
  314. rvalue = ranges.Range(
  315. rvalue.lower,
  316. rvalue.upper,
  317. bounds=f"{'[' if empty or rvalue.lower_inc else '('}" # type: ignore # noqa: E501
  318. f"{']' if not empty and rvalue.upper_inc else ')'}",
  319. empty=empty,
  320. )
  321. return rvalue
  322. if value is not None:
  323. value = [to_range(elem) for elem in value]
  324. return value
  325. return to_range_array
  326. class PGExecutionContext_asyncpg(PGExecutionContext):
  327. def handle_dbapi_exception(self, e):
  328. if isinstance(
  329. e,
  330. (
  331. self.dialect.dbapi.InvalidCachedStatementError,
  332. self.dialect.dbapi.InternalServerError,
  333. ),
  334. ):
  335. self.dialect._invalidate_schema_cache()
  336. def pre_exec(self):
  337. if self.isddl:
  338. self.dialect._invalidate_schema_cache()
  339. self.cursor._invalidate_schema_cache_asof = (
  340. self.dialect._invalidate_schema_cache_asof
  341. )
  342. if not self.compiled:
  343. return
  344. def create_server_side_cursor(self):
  345. return self._dbapi_connection.cursor(server_side=True)
  346. class PGCompiler_asyncpg(PGCompiler):
  347. pass
  348. class PGIdentifierPreparer_asyncpg(PGIdentifierPreparer):
  349. pass
  350. class AsyncAdapt_asyncpg_cursor:
  351. __slots__ = (
  352. "_adapt_connection",
  353. "_connection",
  354. "_rows",
  355. "description",
  356. "arraysize",
  357. "rowcount",
  358. "_cursor",
  359. "_invalidate_schema_cache_asof",
  360. )
  361. server_side = False
  362. def __init__(self, adapt_connection):
  363. self._adapt_connection = adapt_connection
  364. self._connection = adapt_connection._connection
  365. self._rows = []
  366. self._cursor = None
  367. self.description = None
  368. self.arraysize = 1
  369. self.rowcount = -1
  370. self._invalidate_schema_cache_asof = 0
  371. def close(self):
  372. self._rows[:] = []
  373. def _handle_exception(self, error):
  374. self._adapt_connection._handle_exception(error)
  375. async def _prepare_and_execute(self, operation, parameters):
  376. adapt_connection = self._adapt_connection
  377. async with adapt_connection._execute_mutex:
  378. if not adapt_connection._started:
  379. await adapt_connection._start_transaction()
  380. if parameters is None:
  381. parameters = ()
  382. try:
  383. prepared_stmt, attributes = await adapt_connection._prepare(
  384. operation, self._invalidate_schema_cache_asof
  385. )
  386. if attributes:
  387. self.description = [
  388. (
  389. attr.name,
  390. attr.type.oid,
  391. None,
  392. None,
  393. None,
  394. None,
  395. None,
  396. )
  397. for attr in attributes
  398. ]
  399. else:
  400. self.description = None
  401. if self.server_side:
  402. self._cursor = await prepared_stmt.cursor(*parameters)
  403. self.rowcount = -1
  404. else:
  405. self._rows = await prepared_stmt.fetch(*parameters)
  406. status = prepared_stmt.get_statusmsg()
  407. reg = re.match(
  408. r"(?:SELECT|UPDATE|DELETE|INSERT \d+) (\d+)", status
  409. )
  410. if reg:
  411. self.rowcount = int(reg.group(1))
  412. else:
  413. self.rowcount = -1
  414. except Exception as error:
  415. self._handle_exception(error)
  416. async def _executemany(self, operation, seq_of_parameters):
  417. adapt_connection = self._adapt_connection
  418. self.description = None
  419. async with adapt_connection._execute_mutex:
  420. await adapt_connection._check_type_cache_invalidation(
  421. self._invalidate_schema_cache_asof
  422. )
  423. if not adapt_connection._started:
  424. await adapt_connection._start_transaction()
  425. try:
  426. return await self._connection.executemany(
  427. operation, seq_of_parameters
  428. )
  429. except Exception as error:
  430. self._handle_exception(error)
  431. def execute(self, operation, parameters=None):
  432. self._adapt_connection.await_(
  433. self._prepare_and_execute(operation, parameters)
  434. )
  435. def executemany(self, operation, seq_of_parameters):
  436. return self._adapt_connection.await_(
  437. self._executemany(operation, seq_of_parameters)
  438. )
  439. def setinputsizes(self, *inputsizes):
  440. raise NotImplementedError()
  441. def __iter__(self):
  442. while self._rows:
  443. yield self._rows.pop(0)
  444. def fetchone(self):
  445. if self._rows:
  446. return self._rows.pop(0)
  447. else:
  448. return None
  449. def fetchmany(self, size=None):
  450. if size is None:
  451. size = self.arraysize
  452. retval = self._rows[0:size]
  453. self._rows[:] = self._rows[size:]
  454. return retval
  455. def fetchall(self):
  456. retval = self._rows[:]
  457. self._rows[:] = []
  458. return retval
  459. class AsyncAdapt_asyncpg_ss_cursor(AsyncAdapt_asyncpg_cursor):
  460. server_side = True
  461. __slots__ = ("_rowbuffer",)
  462. def __init__(self, adapt_connection):
  463. super().__init__(adapt_connection)
  464. self._rowbuffer = None
  465. def close(self):
  466. self._cursor = None
  467. self._rowbuffer = None
  468. def _buffer_rows(self):
  469. new_rows = self._adapt_connection.await_(self._cursor.fetch(50))
  470. self._rowbuffer = collections.deque(new_rows)
  471. def __aiter__(self):
  472. return self
  473. async def __anext__(self):
  474. if not self._rowbuffer:
  475. self._buffer_rows()
  476. while True:
  477. while self._rowbuffer:
  478. yield self._rowbuffer.popleft()
  479. self._buffer_rows()
  480. if not self._rowbuffer:
  481. break
  482. def fetchone(self):
  483. if not self._rowbuffer:
  484. self._buffer_rows()
  485. if not self._rowbuffer:
  486. return None
  487. return self._rowbuffer.popleft()
  488. def fetchmany(self, size=None):
  489. if size is None:
  490. return self.fetchall()
  491. if not self._rowbuffer:
  492. self._buffer_rows()
  493. buf = list(self._rowbuffer)
  494. lb = len(buf)
  495. if size > lb:
  496. buf.extend(
  497. self._adapt_connection.await_(self._cursor.fetch(size - lb))
  498. )
  499. result = buf[0:size]
  500. self._rowbuffer = collections.deque(buf[size:])
  501. return result
  502. def fetchall(self):
  503. ret = list(self._rowbuffer) + list(
  504. self._adapt_connection.await_(self._all())
  505. )
  506. self._rowbuffer.clear()
  507. return ret
  508. async def _all(self):
  509. rows = []
  510. # TODO: looks like we have to hand-roll some kind of batching here.
  511. # hardcoding for the moment but this should be improved.
  512. while True:
  513. batch = await self._cursor.fetch(1000)
  514. if batch:
  515. rows.extend(batch)
  516. continue
  517. else:
  518. break
  519. return rows
  520. def executemany(self, operation, seq_of_parameters):
  521. raise NotImplementedError(
  522. "server side cursor doesn't support executemany yet"
  523. )
  524. class AsyncAdapt_asyncpg_connection(AdaptedConnection):
  525. __slots__ = (
  526. "dbapi",
  527. "isolation_level",
  528. "_isolation_setting",
  529. "readonly",
  530. "deferrable",
  531. "_transaction",
  532. "_started",
  533. "_prepared_statement_cache",
  534. "_prepared_statement_name_func",
  535. "_invalidate_schema_cache_asof",
  536. "_execute_mutex",
  537. )
  538. await_ = staticmethod(await_only)
  539. def __init__(
  540. self,
  541. dbapi,
  542. connection,
  543. prepared_statement_cache_size=100,
  544. prepared_statement_name_func=None,
  545. ):
  546. self.dbapi = dbapi
  547. self._connection = connection
  548. self.isolation_level = self._isolation_setting = "read_committed"
  549. self.readonly = False
  550. self.deferrable = False
  551. self._transaction = None
  552. self._started = False
  553. self._invalidate_schema_cache_asof = time.time()
  554. self._execute_mutex = asyncio.Lock()
  555. if prepared_statement_cache_size:
  556. self._prepared_statement_cache = util.LRUCache(
  557. prepared_statement_cache_size
  558. )
  559. else:
  560. self._prepared_statement_cache = None
  561. if prepared_statement_name_func:
  562. self._prepared_statement_name_func = prepared_statement_name_func
  563. else:
  564. self._prepared_statement_name_func = self._default_name_func
  565. async def _check_type_cache_invalidation(self, invalidate_timestamp):
  566. if invalidate_timestamp > self._invalidate_schema_cache_asof:
  567. await self._connection.reload_schema_state()
  568. self._invalidate_schema_cache_asof = invalidate_timestamp
  569. async def _prepare(self, operation, invalidate_timestamp):
  570. await self._check_type_cache_invalidation(invalidate_timestamp)
  571. cache = self._prepared_statement_cache
  572. if cache is None:
  573. prepared_stmt = await self._connection.prepare(
  574. operation, name=self._prepared_statement_name_func()
  575. )
  576. attributes = prepared_stmt.get_attributes()
  577. return prepared_stmt, attributes
  578. # asyncpg uses a type cache for the "attributes" which seems to go
  579. # stale independently of the PreparedStatement itself, so place that
  580. # collection in the cache as well.
  581. if operation in cache:
  582. prepared_stmt, attributes, cached_timestamp = cache[operation]
  583. # preparedstatements themselves also go stale for certain DDL
  584. # changes such as size of a VARCHAR changing, so there is also
  585. # a cross-connection invalidation timestamp
  586. if cached_timestamp > invalidate_timestamp:
  587. return prepared_stmt, attributes
  588. prepared_stmt = await self._connection.prepare(
  589. operation, name=self._prepared_statement_name_func()
  590. )
  591. attributes = prepared_stmt.get_attributes()
  592. cache[operation] = (prepared_stmt, attributes, time.time())
  593. return prepared_stmt, attributes
  594. def _handle_exception(self, error):
  595. if self._connection.is_closed():
  596. self._transaction = None
  597. self._started = False
  598. if not isinstance(error, AsyncAdapt_asyncpg_dbapi.Error):
  599. exception_mapping = self.dbapi._asyncpg_error_translate
  600. for super_ in type(error).__mro__:
  601. if super_ in exception_mapping:
  602. translated_error = exception_mapping[super_](
  603. "%s: %s" % (type(error), error)
  604. )
  605. translated_error.pgcode = (
  606. translated_error.sqlstate
  607. ) = getattr(error, "sqlstate", None)
  608. raise translated_error from error
  609. else:
  610. raise error
  611. else:
  612. raise error
  613. @property
  614. def autocommit(self):
  615. return self.isolation_level == "autocommit"
  616. @autocommit.setter
  617. def autocommit(self, value):
  618. if value:
  619. self.isolation_level = "autocommit"
  620. else:
  621. self.isolation_level = self._isolation_setting
  622. def ping(self):
  623. try:
  624. _ = self.await_(self._async_ping())
  625. except Exception as error:
  626. self._handle_exception(error)
  627. async def _async_ping(self):
  628. if self._transaction is None and self.isolation_level != "autocommit":
  629. # create a tranasction explicitly to support pgbouncer
  630. # transaction mode. See #10226
  631. tr = self._connection.transaction()
  632. await tr.start()
  633. try:
  634. await self._connection.fetchrow(";")
  635. finally:
  636. await tr.rollback()
  637. else:
  638. await self._connection.fetchrow(";")
  639. def set_isolation_level(self, level):
  640. if self._started:
  641. self.rollback()
  642. self.isolation_level = self._isolation_setting = level
  643. async def _start_transaction(self):
  644. if self.isolation_level == "autocommit":
  645. return
  646. try:
  647. self._transaction = self._connection.transaction(
  648. isolation=self.isolation_level,
  649. readonly=self.readonly,
  650. deferrable=self.deferrable,
  651. )
  652. await self._transaction.start()
  653. except Exception as error:
  654. self._handle_exception(error)
  655. else:
  656. self._started = True
  657. def cursor(self, server_side=False):
  658. if server_side:
  659. return AsyncAdapt_asyncpg_ss_cursor(self)
  660. else:
  661. return AsyncAdapt_asyncpg_cursor(self)
  662. def rollback(self):
  663. if self._started:
  664. try:
  665. self.await_(self._transaction.rollback())
  666. except Exception as error:
  667. self._handle_exception(error)
  668. finally:
  669. self._transaction = None
  670. self._started = False
  671. def commit(self):
  672. if self._started:
  673. try:
  674. self.await_(self._transaction.commit())
  675. except Exception as error:
  676. self._handle_exception(error)
  677. finally:
  678. self._transaction = None
  679. self._started = False
  680. def close(self):
  681. self.rollback()
  682. self.await_(self._connection.close())
  683. def terminate(self):
  684. if util.concurrency.in_greenlet():
  685. # in a greenlet; this is the connection was invalidated
  686. # case.
  687. try:
  688. # try to gracefully close; see #10717
  689. # timeout added in asyncpg 0.14.0 December 2017
  690. self.await_(self._connection.close(timeout=2))
  691. except asyncio.TimeoutError:
  692. # in the case where we are recycling an old connection
  693. # that may have already been disconnected, close() will
  694. # fail with the above timeout. in this case, terminate
  695. # the connection without any further waiting.
  696. # see issue #8419
  697. self._connection.terminate()
  698. else:
  699. # not in a greenlet; this is the gc cleanup case
  700. self._connection.terminate()
  701. self._started = False
  702. @staticmethod
  703. def _default_name_func():
  704. return None
  705. class AsyncAdaptFallback_asyncpg_connection(AsyncAdapt_asyncpg_connection):
  706. __slots__ = ()
  707. await_ = staticmethod(await_fallback)
  708. class AsyncAdapt_asyncpg_dbapi:
  709. def __init__(self, asyncpg):
  710. self.asyncpg = asyncpg
  711. self.paramstyle = "numeric_dollar"
  712. def connect(self, *arg, **kw):
  713. async_fallback = kw.pop("async_fallback", False)
  714. creator_fn = kw.pop("async_creator_fn", self.asyncpg.connect)
  715. prepared_statement_cache_size = kw.pop(
  716. "prepared_statement_cache_size", 100
  717. )
  718. prepared_statement_name_func = kw.pop(
  719. "prepared_statement_name_func", None
  720. )
  721. if util.asbool(async_fallback):
  722. return AsyncAdaptFallback_asyncpg_connection(
  723. self,
  724. await_fallback(creator_fn(*arg, **kw)),
  725. prepared_statement_cache_size=prepared_statement_cache_size,
  726. prepared_statement_name_func=prepared_statement_name_func,
  727. )
  728. else:
  729. return AsyncAdapt_asyncpg_connection(
  730. self,
  731. await_only(creator_fn(*arg, **kw)),
  732. prepared_statement_cache_size=prepared_statement_cache_size,
  733. prepared_statement_name_func=prepared_statement_name_func,
  734. )
  735. class Error(Exception):
  736. pass
  737. class Warning(Exception): # noqa
  738. pass
  739. class InterfaceError(Error):
  740. pass
  741. class DatabaseError(Error):
  742. pass
  743. class InternalError(DatabaseError):
  744. pass
  745. class OperationalError(DatabaseError):
  746. pass
  747. class ProgrammingError(DatabaseError):
  748. pass
  749. class IntegrityError(DatabaseError):
  750. pass
  751. class DataError(DatabaseError):
  752. pass
  753. class NotSupportedError(DatabaseError):
  754. pass
  755. class InternalServerError(InternalError):
  756. pass
  757. class InvalidCachedStatementError(NotSupportedError):
  758. def __init__(self, message):
  759. super().__init__(
  760. message + " (SQLAlchemy asyncpg dialect will now invalidate "
  761. "all prepared caches in response to this exception)",
  762. )
  763. # pep-249 datatype placeholders. As of SQLAlchemy 2.0 these aren't
  764. # used, however the test suite looks for these in a few cases.
  765. STRING = util.symbol("STRING")
  766. NUMBER = util.symbol("NUMBER")
  767. DATETIME = util.symbol("DATETIME")
  768. @util.memoized_property
  769. def _asyncpg_error_translate(self):
  770. import asyncpg
  771. return {
  772. asyncpg.exceptions.IntegrityConstraintViolationError: self.IntegrityError, # noqa: E501
  773. asyncpg.exceptions.PostgresError: self.Error,
  774. asyncpg.exceptions.SyntaxOrAccessError: self.ProgrammingError,
  775. asyncpg.exceptions.InterfaceError: self.InterfaceError,
  776. asyncpg.exceptions.InvalidCachedStatementError: self.InvalidCachedStatementError, # noqa: E501
  777. asyncpg.exceptions.InternalServerError: self.InternalServerError,
  778. }
  779. def Binary(self, value):
  780. return value
  781. class PGDialect_asyncpg(PGDialect):
  782. driver = "asyncpg"
  783. supports_statement_cache = True
  784. supports_server_side_cursors = True
  785. render_bind_cast = True
  786. has_terminate = True
  787. default_paramstyle = "numeric_dollar"
  788. supports_sane_multi_rowcount = False
  789. execution_ctx_cls = PGExecutionContext_asyncpg
  790. statement_compiler = PGCompiler_asyncpg
  791. preparer = PGIdentifierPreparer_asyncpg
  792. colspecs = util.update_copy(
  793. PGDialect.colspecs,
  794. {
  795. sqltypes.String: AsyncpgString,
  796. sqltypes.ARRAY: AsyncpgARRAY,
  797. BIT: AsyncpgBit,
  798. CITEXT: CITEXT,
  799. REGCONFIG: AsyncpgREGCONFIG,
  800. sqltypes.Time: AsyncpgTime,
  801. sqltypes.Date: AsyncpgDate,
  802. sqltypes.DateTime: AsyncpgDateTime,
  803. sqltypes.Interval: AsyncPgInterval,
  804. INTERVAL: AsyncPgInterval,
  805. sqltypes.Boolean: AsyncpgBoolean,
  806. sqltypes.Integer: AsyncpgInteger,
  807. sqltypes.BigInteger: AsyncpgBigInteger,
  808. sqltypes.Numeric: AsyncpgNumeric,
  809. sqltypes.Float: AsyncpgFloat,
  810. sqltypes.JSON: AsyncpgJSON,
  811. sqltypes.LargeBinary: AsyncpgByteA,
  812. json.JSONB: AsyncpgJSONB,
  813. sqltypes.JSON.JSONPathType: AsyncpgJSONPathType,
  814. sqltypes.JSON.JSONIndexType: AsyncpgJSONIndexType,
  815. sqltypes.JSON.JSONIntIndexType: AsyncpgJSONIntIndexType,
  816. sqltypes.JSON.JSONStrIndexType: AsyncpgJSONStrIndexType,
  817. sqltypes.Enum: AsyncPgEnum,
  818. OID: AsyncpgOID,
  819. REGCLASS: AsyncpgREGCLASS,
  820. sqltypes.CHAR: AsyncpgCHAR,
  821. ranges.AbstractRange: _AsyncpgRange,
  822. ranges.AbstractMultiRange: _AsyncpgMultiRange,
  823. },
  824. )
  825. is_async = True
  826. _invalidate_schema_cache_asof = 0
  827. def _invalidate_schema_cache(self):
  828. self._invalidate_schema_cache_asof = time.time()
  829. @util.memoized_property
  830. def _dbapi_version(self):
  831. if self.dbapi and hasattr(self.dbapi, "__version__"):
  832. return tuple(
  833. [
  834. int(x)
  835. for x in re.findall(
  836. r"(\d+)(?:[-\.]?|$)", self.dbapi.__version__
  837. )
  838. ]
  839. )
  840. else:
  841. return (99, 99, 99)
  842. @classmethod
  843. def import_dbapi(cls):
  844. return AsyncAdapt_asyncpg_dbapi(__import__("asyncpg"))
  845. @util.memoized_property
  846. def _isolation_lookup(self):
  847. return {
  848. "AUTOCOMMIT": "autocommit",
  849. "READ COMMITTED": "read_committed",
  850. "REPEATABLE READ": "repeatable_read",
  851. "SERIALIZABLE": "serializable",
  852. }
  853. def get_isolation_level_values(self, dbapi_connection):
  854. return list(self._isolation_lookup)
  855. def set_isolation_level(self, dbapi_connection, level):
  856. dbapi_connection.set_isolation_level(self._isolation_lookup[level])
  857. def set_readonly(self, connection, value):
  858. connection.readonly = value
  859. def get_readonly(self, connection):
  860. return connection.readonly
  861. def set_deferrable(self, connection, value):
  862. connection.deferrable = value
  863. def get_deferrable(self, connection):
  864. return connection.deferrable
  865. def do_terminate(self, dbapi_connection) -> None:
  866. dbapi_connection.terminate()
  867. def create_connect_args(self, url):
  868. opts = url.translate_connect_args(username="user")
  869. multihosts, multiports = self._split_multihost_from_url(url)
  870. opts.update(url.query)
  871. if multihosts:
  872. assert multiports
  873. if len(multihosts) == 1:
  874. opts["host"] = multihosts[0]
  875. if multiports[0] is not None:
  876. opts["port"] = multiports[0]
  877. elif not all(multihosts):
  878. raise exc.ArgumentError(
  879. "All hosts are required to be present"
  880. " for asyncpg multiple host URL"
  881. )
  882. elif not all(multiports):
  883. raise exc.ArgumentError(
  884. "All ports are required to be present"
  885. " for asyncpg multiple host URL"
  886. )
  887. else:
  888. opts["host"] = list(multihosts)
  889. opts["port"] = list(multiports)
  890. else:
  891. util.coerce_kw_type(opts, "port", int)
  892. util.coerce_kw_type(opts, "prepared_statement_cache_size", int)
  893. return ([], opts)
  894. def do_ping(self, dbapi_connection):
  895. dbapi_connection.ping()
  896. return True
  897. @classmethod
  898. def get_pool_class(cls, url):
  899. async_fallback = url.query.get("async_fallback", False)
  900. if util.asbool(async_fallback):
  901. return pool.FallbackAsyncAdaptedQueuePool
  902. else:
  903. return pool.AsyncAdaptedQueuePool
  904. def is_disconnect(self, e, connection, cursor):
  905. if connection:
  906. return connection._connection.is_closed()
  907. else:
  908. return isinstance(
  909. e, self.dbapi.InterfaceError
  910. ) and "connection is closed" in str(e)
  911. async def setup_asyncpg_json_codec(self, conn):
  912. """set up JSON codec for asyncpg.
  913. This occurs for all new connections and
  914. can be overridden by third party dialects.
  915. .. versionadded:: 1.4.27
  916. """
  917. asyncpg_connection = conn._connection
  918. deserializer = self._json_deserializer or _py_json.loads
  919. def _json_decoder(bin_value):
  920. return deserializer(bin_value.decode())
  921. await asyncpg_connection.set_type_codec(
  922. "json",
  923. encoder=str.encode,
  924. decoder=_json_decoder,
  925. schema="pg_catalog",
  926. format="binary",
  927. )
  928. async def setup_asyncpg_jsonb_codec(self, conn):
  929. """set up JSONB codec for asyncpg.
  930. This occurs for all new connections and
  931. can be overridden by third party dialects.
  932. .. versionadded:: 1.4.27
  933. """
  934. asyncpg_connection = conn._connection
  935. deserializer = self._json_deserializer or _py_json.loads
  936. def _jsonb_encoder(str_value):
  937. # \x01 is the prefix for jsonb used by PostgreSQL.
  938. # asyncpg requires it when format='binary'
  939. return b"\x01" + str_value.encode()
  940. deserializer = self._json_deserializer or _py_json.loads
  941. def _jsonb_decoder(bin_value):
  942. # the byte is the \x01 prefix for jsonb used by PostgreSQL.
  943. # asyncpg returns it when format='binary'
  944. return deserializer(bin_value[1:].decode())
  945. await asyncpg_connection.set_type_codec(
  946. "jsonb",
  947. encoder=_jsonb_encoder,
  948. decoder=_jsonb_decoder,
  949. schema="pg_catalog",
  950. format="binary",
  951. )
  952. async def _disable_asyncpg_inet_codecs(self, conn):
  953. asyncpg_connection = conn._connection
  954. await asyncpg_connection.set_type_codec(
  955. "inet",
  956. encoder=lambda s: s,
  957. decoder=lambda s: s,
  958. schema="pg_catalog",
  959. format="text",
  960. )
  961. await asyncpg_connection.set_type_codec(
  962. "cidr",
  963. encoder=lambda s: s,
  964. decoder=lambda s: s,
  965. schema="pg_catalog",
  966. format="text",
  967. )
  968. def on_connect(self):
  969. """on_connect for asyncpg
  970. A major component of this for asyncpg is to set up type decoders at the
  971. asyncpg level.
  972. See https://github.com/MagicStack/asyncpg/issues/623 for
  973. notes on JSON/JSONB implementation.
  974. """
  975. super_connect = super().on_connect()
  976. def connect(conn):
  977. conn.await_(self.setup_asyncpg_json_codec(conn))
  978. conn.await_(self.setup_asyncpg_jsonb_codec(conn))
  979. if self._native_inet_types is False:
  980. conn.await_(self._disable_asyncpg_inet_codecs(conn))
  981. if super_connect is not None:
  982. super_connect(conn)
  983. return connect
  984. def get_driver_connection(self, connection):
  985. return connection._connection
  986. dialect = PGDialect_asyncpg