cursor.py 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298
  1. # engine/cursor.py
  2. # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
  3. # <see AUTHORS 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. """Define cursor-specific result set constructs including
  8. :class:`.CursorResult`."""
  9. from __future__ import annotations
  10. import collections
  11. import functools
  12. import operator
  13. import typing
  14. from typing import Any
  15. from typing import cast
  16. from typing import ClassVar
  17. from typing import Deque
  18. from typing import Dict
  19. from typing import Iterable
  20. from typing import Iterator
  21. from typing import List
  22. from typing import Mapping
  23. from typing import NoReturn
  24. from typing import Optional
  25. from typing import Sequence
  26. from typing import Tuple
  27. from typing import TYPE_CHECKING
  28. from typing import TypeVar
  29. from typing import Union
  30. from .result import IteratorResult
  31. from .result import MergedResult
  32. from .result import Result
  33. from .result import ResultMetaData
  34. from .result import SimpleResultMetaData
  35. from .result import tuplegetter
  36. from .row import Row
  37. from .. import exc
  38. from .. import util
  39. from ..sql import elements
  40. from ..sql import sqltypes
  41. from ..sql import util as sql_util
  42. from ..sql.base import _generative
  43. from ..sql.compiler import ResultColumnsEntry
  44. from ..sql.compiler import RM_NAME
  45. from ..sql.compiler import RM_OBJECTS
  46. from ..sql.compiler import RM_RENDERED_NAME
  47. from ..sql.compiler import RM_TYPE
  48. from ..sql.type_api import TypeEngine
  49. from ..util import compat
  50. from ..util.typing import Final
  51. from ..util.typing import Literal
  52. from ..util.typing import Self
  53. if typing.TYPE_CHECKING:
  54. from .base import Connection
  55. from .default import DefaultExecutionContext
  56. from .interfaces import _DBAPICursorDescription
  57. from .interfaces import _MutableCoreSingleExecuteParams
  58. from .interfaces import CoreExecuteOptionsParameter
  59. from .interfaces import DBAPICursor
  60. from .interfaces import DBAPIType
  61. from .interfaces import Dialect
  62. from .interfaces import ExecutionContext
  63. from .result import _KeyIndexType
  64. from .result import _KeyMapRecType
  65. from .result import _KeyMapType
  66. from .result import _KeyType
  67. from .result import _ProcessorsType
  68. from .result import _TupleGetterType
  69. from ..sql.schema import Column
  70. from ..sql.type_api import _ResultProcessorType
  71. _T = TypeVar("_T", bound=Any)
  72. TupleAny = Tuple[Any, ...]
  73. # metadata entry tuple indexes.
  74. # using raw tuple is faster than namedtuple.
  75. # these match up to the positions in
  76. # _CursorKeyMapRecType
  77. MD_INDEX: Final[Literal[0]] = 0
  78. """integer index in cursor.description
  79. """
  80. MD_RESULT_MAP_INDEX: Final[Literal[1]] = 1
  81. """integer index in compiled._result_columns"""
  82. MD_OBJECTS: Final[Literal[2]] = 2
  83. """other string keys and ColumnElement obj that can match.
  84. This comes from compiler.RM_OBJECTS / compiler.ResultColumnsEntry.objects
  85. """
  86. MD_LOOKUP_KEY: Final[Literal[3]] = 3
  87. """string key we usually expect for key-based lookup
  88. this comes from compiler.RM_NAME / compiler.ResultColumnsEntry.name
  89. """
  90. MD_RENDERED_NAME: Final[Literal[4]] = 4
  91. """name that is usually in cursor.description
  92. this comes from compiler.RENDERED_NAME / compiler.ResultColumnsEntry.keyname
  93. """
  94. MD_PROCESSOR: Final[Literal[5]] = 5
  95. """callable to process a result value into a row"""
  96. MD_UNTRANSLATED: Final[Literal[6]] = 6
  97. """raw name from cursor.description"""
  98. _CursorKeyMapRecType = Tuple[
  99. Optional[int], # MD_INDEX, None means the record is ambiguously named
  100. int, # MD_RESULT_MAP_INDEX, -1 if MD_INDEX is None
  101. TupleAny, # MD_OBJECTS
  102. str, # MD_LOOKUP_KEY
  103. str, # MD_RENDERED_NAME
  104. Optional["_ResultProcessorType[Any]"], # MD_PROCESSOR
  105. Optional[str], # MD_UNTRANSLATED
  106. ]
  107. _CursorKeyMapType = Mapping["_KeyType", _CursorKeyMapRecType]
  108. # same as _CursorKeyMapRecType except the MD_INDEX value is definitely
  109. # not None
  110. _NonAmbigCursorKeyMapRecType = Tuple[
  111. int,
  112. int,
  113. List[Any],
  114. str,
  115. str,
  116. Optional["_ResultProcessorType[Any]"],
  117. str,
  118. ]
  119. _MergeColTuple = Tuple[
  120. int,
  121. Optional[int],
  122. str,
  123. TypeEngine[Any],
  124. "DBAPIType",
  125. Optional[TupleAny],
  126. Optional[str],
  127. ]
  128. class CursorResultMetaData(ResultMetaData):
  129. """Result metadata for DBAPI cursors."""
  130. __slots__ = (
  131. "_keymap",
  132. "_processors",
  133. "_keys",
  134. "_keymap_by_result_column_idx",
  135. "_tuplefilter",
  136. "_translated_indexes",
  137. "_safe_for_cache",
  138. "_unpickled",
  139. "_key_to_index",
  140. # don't need _unique_filters support here for now. Can be added
  141. # if a need arises.
  142. )
  143. _keymap: _CursorKeyMapType
  144. _processors: _ProcessorsType
  145. _keymap_by_result_column_idx: Optional[Dict[int, _KeyMapRecType]]
  146. _unpickled: bool
  147. _safe_for_cache: bool
  148. _translated_indexes: Optional[List[int]]
  149. returns_rows: ClassVar[bool] = True
  150. def _has_key(self, key: Any) -> bool:
  151. return key in self._keymap
  152. def _for_freeze(self) -> ResultMetaData:
  153. return SimpleResultMetaData(
  154. self._keys,
  155. extra=[self._keymap[key][MD_OBJECTS] for key in self._keys],
  156. )
  157. def _make_new_metadata(
  158. self,
  159. *,
  160. unpickled: bool,
  161. processors: _ProcessorsType,
  162. keys: Sequence[str],
  163. keymap: _KeyMapType,
  164. tuplefilter: Optional[_TupleGetterType],
  165. translated_indexes: Optional[List[int]],
  166. safe_for_cache: bool,
  167. keymap_by_result_column_idx: Any,
  168. ) -> CursorResultMetaData:
  169. new_obj = self.__class__.__new__(self.__class__)
  170. new_obj._unpickled = unpickled
  171. new_obj._processors = processors
  172. new_obj._keys = keys
  173. new_obj._keymap = keymap
  174. new_obj._tuplefilter = tuplefilter
  175. new_obj._translated_indexes = translated_indexes
  176. new_obj._safe_for_cache = safe_for_cache
  177. new_obj._keymap_by_result_column_idx = keymap_by_result_column_idx
  178. new_obj._key_to_index = self._make_key_to_index(keymap, MD_INDEX)
  179. return new_obj
  180. def _remove_processors(self) -> CursorResultMetaData:
  181. assert not self._tuplefilter
  182. return self._make_new_metadata(
  183. unpickled=self._unpickled,
  184. processors=[None] * len(self._processors),
  185. tuplefilter=None,
  186. translated_indexes=None,
  187. keymap={
  188. key: value[0:5] + (None,) + value[6:]
  189. for key, value in self._keymap.items()
  190. },
  191. keys=self._keys,
  192. safe_for_cache=self._safe_for_cache,
  193. keymap_by_result_column_idx=self._keymap_by_result_column_idx,
  194. )
  195. def _splice_horizontally(
  196. self, other: CursorResultMetaData
  197. ) -> CursorResultMetaData:
  198. assert not self._tuplefilter
  199. keymap = dict(self._keymap)
  200. offset = len(self._keys)
  201. for key, value in other._keymap.items():
  202. # int index should be None for ambiguous key
  203. if value[MD_INDEX] is not None and key not in keymap:
  204. md_index = value[MD_INDEX] + offset
  205. md_object = value[MD_RESULT_MAP_INDEX] + offset
  206. else:
  207. md_index = None
  208. md_object = -1
  209. keymap[key] = (md_index, md_object, *value[2:])
  210. return self._make_new_metadata(
  211. unpickled=self._unpickled,
  212. processors=self._processors + other._processors, # type: ignore
  213. tuplefilter=None,
  214. translated_indexes=None,
  215. keys=self._keys + other._keys, # type: ignore
  216. keymap=keymap,
  217. safe_for_cache=self._safe_for_cache,
  218. keymap_by_result_column_idx={
  219. metadata_entry[MD_RESULT_MAP_INDEX]: metadata_entry
  220. for metadata_entry in keymap.values()
  221. },
  222. )
  223. def _reduce(self, keys: Sequence[_KeyIndexType]) -> ResultMetaData:
  224. recs = list(self._metadata_for_keys(keys))
  225. indexes = [rec[MD_INDEX] for rec in recs]
  226. new_keys: List[str] = [rec[MD_LOOKUP_KEY] for rec in recs]
  227. if self._translated_indexes:
  228. indexes = [self._translated_indexes[idx] for idx in indexes]
  229. tup = tuplegetter(*indexes)
  230. new_recs = [(index,) + rec[1:] for index, rec in enumerate(recs)]
  231. keymap = {rec[MD_LOOKUP_KEY]: rec for rec in new_recs}
  232. # TODO: need unit test for:
  233. # result = connection.execute("raw sql, no columns").scalars()
  234. # without the "or ()" it's failing because MD_OBJECTS is None
  235. keymap.update(
  236. (e, new_rec)
  237. for new_rec in new_recs
  238. for e in new_rec[MD_OBJECTS] or ()
  239. )
  240. return self._make_new_metadata(
  241. unpickled=self._unpickled,
  242. processors=self._processors,
  243. keys=new_keys,
  244. tuplefilter=tup,
  245. translated_indexes=indexes,
  246. keymap=keymap, # type: ignore[arg-type]
  247. safe_for_cache=self._safe_for_cache,
  248. keymap_by_result_column_idx=self._keymap_by_result_column_idx,
  249. )
  250. def _adapt_to_context(self, context: ExecutionContext) -> ResultMetaData:
  251. """When using a cached Compiled construct that has a _result_map,
  252. for a new statement that used the cached Compiled, we need to ensure
  253. the keymap has the Column objects from our new statement as keys.
  254. So here we rewrite keymap with new entries for the new columns
  255. as matched to those of the cached statement.
  256. """
  257. if not context.compiled or not context.compiled._result_columns:
  258. return self
  259. compiled_statement = context.compiled.statement
  260. invoked_statement = context.invoked_statement
  261. if TYPE_CHECKING:
  262. assert isinstance(invoked_statement, elements.ClauseElement)
  263. if compiled_statement is invoked_statement:
  264. return self
  265. assert invoked_statement is not None
  266. # this is the most common path for Core statements when
  267. # caching is used. In ORM use, this codepath is not really used
  268. # as the _result_disable_adapt_to_context execution option is
  269. # set by the ORM.
  270. # make a copy and add the columns from the invoked statement
  271. # to the result map.
  272. keymap_by_position = self._keymap_by_result_column_idx
  273. if keymap_by_position is None:
  274. # first retrieval from cache, this map will not be set up yet,
  275. # initialize lazily
  276. keymap_by_position = self._keymap_by_result_column_idx = {
  277. metadata_entry[MD_RESULT_MAP_INDEX]: metadata_entry
  278. for metadata_entry in self._keymap.values()
  279. }
  280. assert not self._tuplefilter
  281. return self._make_new_metadata(
  282. keymap=compat.dict_union(
  283. self._keymap,
  284. {
  285. new: keymap_by_position[idx]
  286. for idx, new in enumerate(
  287. invoked_statement._all_selected_columns
  288. )
  289. if idx in keymap_by_position
  290. },
  291. ),
  292. unpickled=self._unpickled,
  293. processors=self._processors,
  294. tuplefilter=None,
  295. translated_indexes=None,
  296. keys=self._keys,
  297. safe_for_cache=self._safe_for_cache,
  298. keymap_by_result_column_idx=self._keymap_by_result_column_idx,
  299. )
  300. def __init__(
  301. self,
  302. parent: CursorResult[Any],
  303. cursor_description: _DBAPICursorDescription,
  304. ):
  305. context = parent.context
  306. self._tuplefilter = None
  307. self._translated_indexes = None
  308. self._safe_for_cache = self._unpickled = False
  309. if context.result_column_struct:
  310. (
  311. result_columns,
  312. cols_are_ordered,
  313. textual_ordered,
  314. ad_hoc_textual,
  315. loose_column_name_matching,
  316. ) = context.result_column_struct
  317. num_ctx_cols = len(result_columns)
  318. else:
  319. result_columns = cols_are_ordered = ( # type: ignore
  320. num_ctx_cols
  321. ) = ad_hoc_textual = loose_column_name_matching = (
  322. textual_ordered
  323. ) = False
  324. # merge cursor.description with the column info
  325. # present in the compiled structure, if any
  326. raw = self._merge_cursor_description(
  327. context,
  328. cursor_description,
  329. result_columns,
  330. num_ctx_cols,
  331. cols_are_ordered,
  332. textual_ordered,
  333. ad_hoc_textual,
  334. loose_column_name_matching,
  335. )
  336. # processors in key order which are used when building up
  337. # a row
  338. self._processors = [
  339. metadata_entry[MD_PROCESSOR] for metadata_entry in raw
  340. ]
  341. # this is used when using this ResultMetaData in a Core-only cache
  342. # retrieval context. it's initialized on first cache retrieval
  343. # when the _result_disable_adapt_to_context execution option
  344. # (which the ORM generally sets) is not set.
  345. self._keymap_by_result_column_idx = None
  346. # for compiled SQL constructs, copy additional lookup keys into
  347. # the key lookup map, such as Column objects, labels,
  348. # column keys and other names
  349. if num_ctx_cols:
  350. # keymap by primary string...
  351. by_key: Dict[_KeyType, _CursorKeyMapRecType] = {
  352. metadata_entry[MD_LOOKUP_KEY]: metadata_entry
  353. for metadata_entry in raw
  354. }
  355. if len(by_key) != num_ctx_cols:
  356. # if by-primary-string dictionary smaller than
  357. # number of columns, assume we have dupes; (this check
  358. # is also in place if string dictionary is bigger, as
  359. # can occur when '*' was used as one of the compiled columns,
  360. # which may or may not be suggestive of dupes), rewrite
  361. # dupe records with "None" for index which results in
  362. # ambiguous column exception when accessed.
  363. #
  364. # this is considered to be the less common case as it is not
  365. # common to have dupe column keys in a SELECT statement.
  366. #
  367. # new in 1.4: get the complete set of all possible keys,
  368. # strings, objects, whatever, that are dupes across two
  369. # different records, first.
  370. index_by_key: Dict[Any, Any] = {}
  371. dupes = set()
  372. for metadata_entry in raw:
  373. for key in (metadata_entry[MD_RENDERED_NAME],) + (
  374. metadata_entry[MD_OBJECTS] or ()
  375. ):
  376. idx = metadata_entry[MD_INDEX]
  377. # if this key has been associated with more than one
  378. # positional index, it's a dupe
  379. if index_by_key.setdefault(key, idx) != idx:
  380. dupes.add(key)
  381. # then put everything we have into the keymap excluding only
  382. # those keys that are dupes.
  383. self._keymap = {
  384. obj_elem: metadata_entry
  385. for metadata_entry in raw
  386. if metadata_entry[MD_OBJECTS]
  387. for obj_elem in metadata_entry[MD_OBJECTS]
  388. if obj_elem not in dupes
  389. }
  390. # then for the dupe keys, put the "ambiguous column"
  391. # record into by_key.
  392. by_key.update(
  393. {
  394. key: (None, -1, (), key, key, None, None)
  395. for key in dupes
  396. }
  397. )
  398. else:
  399. # no dupes - copy secondary elements from compiled
  400. # columns into self._keymap. this is the most common
  401. # codepath for Core / ORM statement executions before the
  402. # result metadata is cached
  403. self._keymap = {
  404. obj_elem: metadata_entry
  405. for metadata_entry in raw
  406. if metadata_entry[MD_OBJECTS]
  407. for obj_elem in metadata_entry[MD_OBJECTS]
  408. }
  409. # update keymap with primary string names taking
  410. # precedence
  411. self._keymap.update(by_key)
  412. else:
  413. # no compiled objects to map, just create keymap by primary string
  414. self._keymap = {
  415. metadata_entry[MD_LOOKUP_KEY]: metadata_entry
  416. for metadata_entry in raw
  417. }
  418. # update keymap with "translated" names. In SQLAlchemy this is a
  419. # sqlite only thing, and in fact impacting only extremely old SQLite
  420. # versions unlikely to be present in modern Python versions.
  421. # however, the pyhive third party dialect is
  422. # also using this hook, which means others still might use it as well.
  423. # I dislike having this awkward hook here but as long as we need
  424. # to use names in cursor.description in some cases we need to have
  425. # some hook to accomplish this.
  426. if not num_ctx_cols and context._translate_colname:
  427. self._keymap.update(
  428. {
  429. metadata_entry[MD_UNTRANSLATED]: self._keymap[
  430. metadata_entry[MD_LOOKUP_KEY]
  431. ]
  432. for metadata_entry in raw
  433. if metadata_entry[MD_UNTRANSLATED]
  434. }
  435. )
  436. self._key_to_index = self._make_key_to_index(self._keymap, MD_INDEX)
  437. def _merge_cursor_description(
  438. self,
  439. context: DefaultExecutionContext,
  440. cursor_description: _DBAPICursorDescription,
  441. result_columns: Sequence[ResultColumnsEntry],
  442. num_ctx_cols: int,
  443. cols_are_ordered: bool,
  444. textual_ordered: bool,
  445. ad_hoc_textual: bool,
  446. loose_column_name_matching: bool,
  447. ) -> List[_CursorKeyMapRecType]:
  448. """Merge a cursor.description with compiled result column information.
  449. There are at least four separate strategies used here, selected
  450. depending on the type of SQL construct used to start with.
  451. The most common case is that of the compiled SQL expression construct,
  452. which generated the column names present in the raw SQL string and
  453. which has the identical number of columns as were reported by
  454. cursor.description. In this case, we assume a 1-1 positional mapping
  455. between the entries in cursor.description and the compiled object.
  456. This is also the most performant case as we disregard extracting /
  457. decoding the column names present in cursor.description since we
  458. already have the desired name we generated in the compiled SQL
  459. construct.
  460. The next common case is that of the completely raw string SQL,
  461. such as passed to connection.execute(). In this case we have no
  462. compiled construct to work with, so we extract and decode the
  463. names from cursor.description and index those as the primary
  464. result row target keys.
  465. The remaining fairly common case is that of the textual SQL
  466. that includes at least partial column information; this is when
  467. we use a :class:`_expression.TextualSelect` construct.
  468. This construct may have
  469. unordered or ordered column information. In the ordered case, we
  470. merge the cursor.description and the compiled construct's information
  471. positionally, and warn if there are additional description names
  472. present, however we still decode the names in cursor.description
  473. as we don't have a guarantee that the names in the columns match
  474. on these. In the unordered case, we match names in cursor.description
  475. to that of the compiled construct based on name matching.
  476. In both of these cases, the cursor.description names and the column
  477. expression objects and names are indexed as result row target keys.
  478. The final case is much less common, where we have a compiled
  479. non-textual SQL expression construct, but the number of columns
  480. in cursor.description doesn't match what's in the compiled
  481. construct. We make the guess here that there might be textual
  482. column expressions in the compiled construct that themselves include
  483. a comma in them causing them to split. We do the same name-matching
  484. as with textual non-ordered columns.
  485. The name-matched system of merging is the same as that used by
  486. SQLAlchemy for all cases up through the 0.9 series. Positional
  487. matching for compiled SQL expressions was introduced in 1.0 as a
  488. major performance feature, and positional matching for textual
  489. :class:`_expression.TextualSelect` objects in 1.1.
  490. As name matching is no longer
  491. a common case, it was acceptable to factor it into smaller generator-
  492. oriented methods that are easier to understand, but incur slightly
  493. more performance overhead.
  494. """
  495. if (
  496. num_ctx_cols
  497. and cols_are_ordered
  498. and not textual_ordered
  499. and num_ctx_cols == len(cursor_description)
  500. ):
  501. self._keys = [elem[0] for elem in result_columns]
  502. # pure positional 1-1 case; doesn't need to read
  503. # the names from cursor.description
  504. # most common case for Core and ORM
  505. # this metadata is safe to cache because we are guaranteed
  506. # to have the columns in the same order for new executions
  507. self._safe_for_cache = True
  508. return [
  509. (
  510. idx,
  511. idx,
  512. rmap_entry[RM_OBJECTS],
  513. rmap_entry[RM_NAME],
  514. rmap_entry[RM_RENDERED_NAME],
  515. context.get_result_processor(
  516. rmap_entry[RM_TYPE],
  517. rmap_entry[RM_RENDERED_NAME],
  518. cursor_description[idx][1],
  519. ),
  520. None,
  521. )
  522. for idx, rmap_entry in enumerate(result_columns)
  523. ]
  524. else:
  525. # name-based or text-positional cases, where we need
  526. # to read cursor.description names
  527. if textual_ordered or (
  528. ad_hoc_textual and len(cursor_description) == num_ctx_cols
  529. ):
  530. self._safe_for_cache = True
  531. # textual positional case
  532. raw_iterator = self._merge_textual_cols_by_position(
  533. context, cursor_description, result_columns
  534. )
  535. elif num_ctx_cols:
  536. # compiled SQL with a mismatch of description cols
  537. # vs. compiled cols, or textual w/ unordered columns
  538. # the order of columns can change if the query is
  539. # against a "select *", so not safe to cache
  540. self._safe_for_cache = False
  541. raw_iterator = self._merge_cols_by_name(
  542. context,
  543. cursor_description,
  544. result_columns,
  545. loose_column_name_matching,
  546. )
  547. else:
  548. # no compiled SQL, just a raw string, order of columns
  549. # can change for "select *"
  550. self._safe_for_cache = False
  551. raw_iterator = self._merge_cols_by_none(
  552. context, cursor_description
  553. )
  554. return [
  555. (
  556. idx,
  557. ridx,
  558. obj,
  559. cursor_colname,
  560. cursor_colname,
  561. context.get_result_processor(
  562. mapped_type, cursor_colname, coltype
  563. ),
  564. untranslated,
  565. ) # type: ignore[misc]
  566. for (
  567. idx,
  568. ridx,
  569. cursor_colname,
  570. mapped_type,
  571. coltype,
  572. obj,
  573. untranslated,
  574. ) in raw_iterator
  575. ]
  576. def _colnames_from_description(
  577. self,
  578. context: DefaultExecutionContext,
  579. cursor_description: _DBAPICursorDescription,
  580. ) -> Iterator[Tuple[int, str, Optional[str], DBAPIType]]:
  581. """Extract column names and data types from a cursor.description.
  582. Applies unicode decoding, column translation, "normalization",
  583. and case sensitivity rules to the names based on the dialect.
  584. """
  585. dialect = context.dialect
  586. translate_colname = context._translate_colname
  587. normalize_name = (
  588. dialect.normalize_name if dialect.requires_name_normalize else None
  589. )
  590. untranslated = None
  591. self._keys = []
  592. for idx, rec in enumerate(cursor_description):
  593. colname = rec[0]
  594. coltype = rec[1]
  595. if translate_colname:
  596. colname, untranslated = translate_colname(colname)
  597. if normalize_name:
  598. colname = normalize_name(colname)
  599. self._keys.append(colname)
  600. yield idx, colname, untranslated, coltype
  601. def _merge_textual_cols_by_position(
  602. self,
  603. context: DefaultExecutionContext,
  604. cursor_description: _DBAPICursorDescription,
  605. result_columns: Sequence[ResultColumnsEntry],
  606. ) -> Iterator[_MergeColTuple]:
  607. num_ctx_cols = len(result_columns)
  608. if num_ctx_cols > len(cursor_description):
  609. util.warn(
  610. "Number of columns in textual SQL (%d) is "
  611. "smaller than number of columns requested (%d)"
  612. % (num_ctx_cols, len(cursor_description))
  613. )
  614. seen = set()
  615. for (
  616. idx,
  617. colname,
  618. untranslated,
  619. coltype,
  620. ) in self._colnames_from_description(context, cursor_description):
  621. if idx < num_ctx_cols:
  622. ctx_rec = result_columns[idx]
  623. obj = ctx_rec[RM_OBJECTS]
  624. ridx = idx
  625. mapped_type = ctx_rec[RM_TYPE]
  626. if obj[0] in seen:
  627. raise exc.InvalidRequestError(
  628. "Duplicate column expression requested "
  629. "in textual SQL: %r" % obj[0]
  630. )
  631. seen.add(obj[0])
  632. else:
  633. mapped_type = sqltypes.NULLTYPE
  634. obj = None
  635. ridx = None
  636. yield idx, ridx, colname, mapped_type, coltype, obj, untranslated
  637. def _merge_cols_by_name(
  638. self,
  639. context: DefaultExecutionContext,
  640. cursor_description: _DBAPICursorDescription,
  641. result_columns: Sequence[ResultColumnsEntry],
  642. loose_column_name_matching: bool,
  643. ) -> Iterator[_MergeColTuple]:
  644. match_map = self._create_description_match_map(
  645. result_columns, loose_column_name_matching
  646. )
  647. mapped_type: TypeEngine[Any]
  648. for (
  649. idx,
  650. colname,
  651. untranslated,
  652. coltype,
  653. ) in self._colnames_from_description(context, cursor_description):
  654. try:
  655. ctx_rec = match_map[colname]
  656. except KeyError:
  657. mapped_type = sqltypes.NULLTYPE
  658. obj = None
  659. result_columns_idx = None
  660. else:
  661. obj = ctx_rec[1]
  662. mapped_type = ctx_rec[2]
  663. result_columns_idx = ctx_rec[3]
  664. yield (
  665. idx,
  666. result_columns_idx,
  667. colname,
  668. mapped_type,
  669. coltype,
  670. obj,
  671. untranslated,
  672. )
  673. @classmethod
  674. def _create_description_match_map(
  675. cls,
  676. result_columns: Sequence[ResultColumnsEntry],
  677. loose_column_name_matching: bool = False,
  678. ) -> Dict[Union[str, object], Tuple[str, TupleAny, TypeEngine[Any], int]]:
  679. """when matching cursor.description to a set of names that are present
  680. in a Compiled object, as is the case with TextualSelect, get all the
  681. names we expect might match those in cursor.description.
  682. """
  683. d: Dict[
  684. Union[str, object],
  685. Tuple[str, TupleAny, TypeEngine[Any], int],
  686. ] = {}
  687. for ridx, elem in enumerate(result_columns):
  688. key = elem[RM_RENDERED_NAME]
  689. if key in d:
  690. # conflicting keyname - just add the column-linked objects
  691. # to the existing record. if there is a duplicate column
  692. # name in the cursor description, this will allow all of those
  693. # objects to raise an ambiguous column error
  694. e_name, e_obj, e_type, e_ridx = d[key]
  695. d[key] = e_name, e_obj + elem[RM_OBJECTS], e_type, ridx
  696. else:
  697. d[key] = (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx)
  698. if loose_column_name_matching:
  699. # when using a textual statement with an unordered set
  700. # of columns that line up, we are expecting the user
  701. # to be using label names in the SQL that match to the column
  702. # expressions. Enable more liberal matching for this case;
  703. # duplicate keys that are ambiguous will be fixed later.
  704. for r_key in elem[RM_OBJECTS]:
  705. d.setdefault(
  706. r_key,
  707. (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx),
  708. )
  709. return d
  710. def _merge_cols_by_none(
  711. self,
  712. context: DefaultExecutionContext,
  713. cursor_description: _DBAPICursorDescription,
  714. ) -> Iterator[_MergeColTuple]:
  715. self._keys = []
  716. for (
  717. idx,
  718. colname,
  719. untranslated,
  720. coltype,
  721. ) in self._colnames_from_description(context, cursor_description):
  722. yield (
  723. idx,
  724. None,
  725. colname,
  726. sqltypes.NULLTYPE,
  727. coltype,
  728. None,
  729. untranslated,
  730. )
  731. if not TYPE_CHECKING:
  732. def _key_fallback(
  733. self, key: Any, err: Optional[Exception], raiseerr: bool = True
  734. ) -> Optional[NoReturn]:
  735. if raiseerr:
  736. if self._unpickled and isinstance(key, elements.ColumnElement):
  737. raise exc.NoSuchColumnError(
  738. "Row was unpickled; lookup by ColumnElement "
  739. "is unsupported"
  740. ) from err
  741. else:
  742. raise exc.NoSuchColumnError(
  743. "Could not locate column in row for column '%s'"
  744. % util.string_or_unprintable(key)
  745. ) from err
  746. else:
  747. return None
  748. def _raise_for_ambiguous_column_name(
  749. self, rec: _KeyMapRecType
  750. ) -> NoReturn:
  751. raise exc.InvalidRequestError(
  752. "Ambiguous column name '%s' in "
  753. "result set column descriptions" % rec[MD_LOOKUP_KEY]
  754. )
  755. def _index_for_key(
  756. self, key: _KeyIndexType, raiseerr: bool = True
  757. ) -> Optional[int]:
  758. # TODO: can consider pre-loading ints and negative ints
  759. # into _keymap - also no coverage here
  760. if isinstance(key, int):
  761. key = self._keys[key]
  762. try:
  763. rec = self._keymap[key]
  764. except KeyError as ke:
  765. x = self._key_fallback(key, ke, raiseerr)
  766. assert x is None
  767. return None
  768. index = rec[0]
  769. if index is None:
  770. self._raise_for_ambiguous_column_name(rec)
  771. return index
  772. def _indexes_for_keys(
  773. self, keys: Sequence[_KeyIndexType]
  774. ) -> Sequence[int]:
  775. try:
  776. return [self._keymap[key][0] for key in keys] # type: ignore[index,misc] # noqa: E501
  777. except KeyError as ke:
  778. # ensure it raises
  779. CursorResultMetaData._key_fallback(self, ke.args[0], ke)
  780. def _metadata_for_keys(
  781. self, keys: Sequence[_KeyIndexType]
  782. ) -> Iterator[_NonAmbigCursorKeyMapRecType]:
  783. for key in keys:
  784. if int in key.__class__.__mro__:
  785. key = self._keys[key] # type: ignore[index]
  786. try:
  787. rec = self._keymap[key] # type: ignore[index]
  788. except KeyError as ke:
  789. # ensure it raises
  790. CursorResultMetaData._key_fallback(self, ke.args[0], ke)
  791. index = rec[MD_INDEX]
  792. if index is None:
  793. self._raise_for_ambiguous_column_name(rec)
  794. yield cast(_NonAmbigCursorKeyMapRecType, rec)
  795. def __getstate__(self) -> Dict[str, Any]:
  796. # TODO: consider serializing this as SimpleResultMetaData
  797. return {
  798. "_keymap": {
  799. key: (
  800. rec[MD_INDEX],
  801. rec[MD_RESULT_MAP_INDEX],
  802. [],
  803. key,
  804. rec[MD_RENDERED_NAME],
  805. None,
  806. None,
  807. )
  808. for key, rec in self._keymap.items()
  809. if isinstance(key, (str, int))
  810. },
  811. "_keys": self._keys,
  812. "_translated_indexes": self._translated_indexes,
  813. }
  814. def __setstate__(self, state: Dict[str, Any]) -> None:
  815. self._processors = [None for _ in range(len(state["_keys"]))]
  816. self._keymap = state["_keymap"]
  817. self._keymap_by_result_column_idx = None
  818. self._key_to_index = self._make_key_to_index(self._keymap, MD_INDEX)
  819. self._keys = state["_keys"]
  820. self._unpickled = True
  821. if state["_translated_indexes"]:
  822. self._translated_indexes = cast(
  823. "List[int]", state["_translated_indexes"]
  824. )
  825. self._tuplefilter = tuplegetter(*self._translated_indexes)
  826. else:
  827. self._translated_indexes = self._tuplefilter = None
  828. class ResultFetchStrategy:
  829. """Define a fetching strategy for a result object.
  830. .. versionadded:: 1.4
  831. """
  832. __slots__ = ()
  833. alternate_cursor_description: Optional[_DBAPICursorDescription] = None
  834. def soft_close(
  835. self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
  836. ) -> None:
  837. raise NotImplementedError()
  838. def hard_close(
  839. self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
  840. ) -> None:
  841. raise NotImplementedError()
  842. def yield_per(
  843. self,
  844. result: CursorResult[Any],
  845. dbapi_cursor: DBAPICursor,
  846. num: int,
  847. ) -> None:
  848. return
  849. def fetchone(
  850. self,
  851. result: CursorResult[Any],
  852. dbapi_cursor: DBAPICursor,
  853. hard_close: bool = False,
  854. ) -> Any:
  855. raise NotImplementedError()
  856. def fetchmany(
  857. self,
  858. result: CursorResult[Any],
  859. dbapi_cursor: DBAPICursor,
  860. size: Optional[int] = None,
  861. ) -> Any:
  862. raise NotImplementedError()
  863. def fetchall(
  864. self,
  865. result: CursorResult[Any],
  866. dbapi_cursor: DBAPICursor,
  867. ) -> Any:
  868. raise NotImplementedError()
  869. def handle_exception(
  870. self,
  871. result: CursorResult[Any],
  872. dbapi_cursor: Optional[DBAPICursor],
  873. err: BaseException,
  874. ) -> NoReturn:
  875. raise err
  876. class NoCursorFetchStrategy(ResultFetchStrategy):
  877. """Cursor strategy for a result that has no open cursor.
  878. There are two varieties of this strategy, one for DQL and one for
  879. DML (and also DDL), each of which represent a result that had a cursor
  880. but no longer has one.
  881. """
  882. __slots__ = ()
  883. def soft_close(
  884. self,
  885. result: CursorResult[Any],
  886. dbapi_cursor: Optional[DBAPICursor],
  887. ) -> None:
  888. pass
  889. def hard_close(
  890. self,
  891. result: CursorResult[Any],
  892. dbapi_cursor: Optional[DBAPICursor],
  893. ) -> None:
  894. pass
  895. def fetchone(
  896. self,
  897. result: CursorResult[Any],
  898. dbapi_cursor: DBAPICursor,
  899. hard_close: bool = False,
  900. ) -> Any:
  901. return self._non_result(result, None)
  902. def fetchmany(
  903. self,
  904. result: CursorResult[Any],
  905. dbapi_cursor: DBAPICursor,
  906. size: Optional[int] = None,
  907. ) -> Any:
  908. return self._non_result(result, [])
  909. def fetchall(
  910. self, result: CursorResult[Any], dbapi_cursor: DBAPICursor
  911. ) -> Any:
  912. return self._non_result(result, [])
  913. def _non_result(
  914. self,
  915. result: CursorResult[Any],
  916. default: Any,
  917. err: Optional[BaseException] = None,
  918. ) -> Any:
  919. raise NotImplementedError()
  920. class NoCursorDQLFetchStrategy(NoCursorFetchStrategy):
  921. """Cursor strategy for a DQL result that has no open cursor.
  922. This is a result set that can return rows, i.e. for a SELECT, or for an
  923. INSERT, UPDATE, DELETE that includes RETURNING. However it is in the state
  924. where the cursor is closed and no rows remain available. The owning result
  925. object may or may not be "hard closed", which determines if the fetch
  926. methods send empty results or raise for closed result.
  927. """
  928. __slots__ = ()
  929. def _non_result(
  930. self,
  931. result: CursorResult[Any],
  932. default: Any,
  933. err: Optional[BaseException] = None,
  934. ) -> Any:
  935. if result.closed:
  936. raise exc.ResourceClosedError(
  937. "This result object is closed."
  938. ) from err
  939. else:
  940. return default
  941. _NO_CURSOR_DQL = NoCursorDQLFetchStrategy()
  942. class NoCursorDMLFetchStrategy(NoCursorFetchStrategy):
  943. """Cursor strategy for a DML result that has no open cursor.
  944. This is a result set that does not return rows, i.e. for an INSERT,
  945. UPDATE, DELETE that does not include RETURNING.
  946. """
  947. __slots__ = ()
  948. def _non_result(
  949. self,
  950. result: CursorResult[Any],
  951. default: Any,
  952. err: Optional[BaseException] = None,
  953. ) -> Any:
  954. # we only expect to have a _NoResultMetaData() here right now.
  955. assert not result._metadata.returns_rows
  956. result._metadata._we_dont_return_rows(err) # type: ignore[union-attr]
  957. _NO_CURSOR_DML = NoCursorDMLFetchStrategy()
  958. class CursorFetchStrategy(ResultFetchStrategy):
  959. """Call fetch methods from a DBAPI cursor.
  960. Alternate versions of this class may instead buffer the rows from
  961. cursors or not use cursors at all.
  962. """
  963. __slots__ = ()
  964. def soft_close(
  965. self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
  966. ) -> None:
  967. result.cursor_strategy = _NO_CURSOR_DQL
  968. def hard_close(
  969. self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
  970. ) -> None:
  971. result.cursor_strategy = _NO_CURSOR_DQL
  972. def handle_exception(
  973. self,
  974. result: CursorResult[Any],
  975. dbapi_cursor: Optional[DBAPICursor],
  976. err: BaseException,
  977. ) -> NoReturn:
  978. result.connection._handle_dbapi_exception(
  979. err, None, None, dbapi_cursor, result.context
  980. )
  981. def yield_per(
  982. self, result: CursorResult[Any], dbapi_cursor: DBAPICursor, num: int
  983. ) -> None:
  984. result.cursor_strategy = BufferedRowCursorFetchStrategy(
  985. dbapi_cursor,
  986. {"max_row_buffer": num},
  987. initial_buffer=collections.deque(),
  988. growth_factor=0,
  989. )
  990. def fetchone(
  991. self,
  992. result: CursorResult[Any],
  993. dbapi_cursor: DBAPICursor,
  994. hard_close: bool = False,
  995. ) -> Any:
  996. try:
  997. row = dbapi_cursor.fetchone()
  998. if row is None:
  999. result._soft_close(hard=hard_close)
  1000. return row
  1001. except BaseException as e:
  1002. self.handle_exception(result, dbapi_cursor, e)
  1003. def fetchmany(
  1004. self,
  1005. result: CursorResult[Any],
  1006. dbapi_cursor: DBAPICursor,
  1007. size: Optional[int] = None,
  1008. ) -> Any:
  1009. try:
  1010. if size is None:
  1011. l = dbapi_cursor.fetchmany()
  1012. else:
  1013. l = dbapi_cursor.fetchmany(size)
  1014. if not l:
  1015. result._soft_close()
  1016. return l
  1017. except BaseException as e:
  1018. self.handle_exception(result, dbapi_cursor, e)
  1019. def fetchall(
  1020. self,
  1021. result: CursorResult[Any],
  1022. dbapi_cursor: DBAPICursor,
  1023. ) -> Any:
  1024. try:
  1025. rows = dbapi_cursor.fetchall()
  1026. result._soft_close()
  1027. return rows
  1028. except BaseException as e:
  1029. self.handle_exception(result, dbapi_cursor, e)
  1030. _DEFAULT_FETCH = CursorFetchStrategy()
  1031. class BufferedRowCursorFetchStrategy(CursorFetchStrategy):
  1032. """A cursor fetch strategy with row buffering behavior.
  1033. This strategy buffers the contents of a selection of rows
  1034. before ``fetchone()`` is called. This is to allow the results of
  1035. ``cursor.description`` to be available immediately, when
  1036. interfacing with a DB-API that requires rows to be consumed before
  1037. this information is available (currently psycopg2, when used with
  1038. server-side cursors).
  1039. The pre-fetching behavior fetches only one row initially, and then
  1040. grows its buffer size by a fixed amount with each successive need
  1041. for additional rows up the ``max_row_buffer`` size, which defaults
  1042. to 1000::
  1043. with psycopg2_engine.connect() as conn:
  1044. result = conn.execution_options(
  1045. stream_results=True, max_row_buffer=50
  1046. ).execute(text("select * from table"))
  1047. .. versionadded:: 1.4 ``max_row_buffer`` may now exceed 1000 rows.
  1048. .. seealso::
  1049. :ref:`psycopg2_execution_options`
  1050. """
  1051. __slots__ = ("_max_row_buffer", "_rowbuffer", "_bufsize", "_growth_factor")
  1052. def __init__(
  1053. self,
  1054. dbapi_cursor: DBAPICursor,
  1055. execution_options: CoreExecuteOptionsParameter,
  1056. growth_factor: int = 5,
  1057. initial_buffer: Optional[Deque[Any]] = None,
  1058. ) -> None:
  1059. self._max_row_buffer = execution_options.get("max_row_buffer", 1000)
  1060. if initial_buffer is not None:
  1061. self._rowbuffer = initial_buffer
  1062. else:
  1063. self._rowbuffer = collections.deque(dbapi_cursor.fetchmany(1))
  1064. self._growth_factor = growth_factor
  1065. if growth_factor:
  1066. self._bufsize = min(self._max_row_buffer, self._growth_factor)
  1067. else:
  1068. self._bufsize = self._max_row_buffer
  1069. @classmethod
  1070. def create(
  1071. cls, result: CursorResult[Any]
  1072. ) -> BufferedRowCursorFetchStrategy:
  1073. return BufferedRowCursorFetchStrategy(
  1074. result.cursor,
  1075. result.context.execution_options,
  1076. )
  1077. def _buffer_rows(
  1078. self, result: CursorResult[Any], dbapi_cursor: DBAPICursor
  1079. ) -> None:
  1080. """this is currently used only by fetchone()."""
  1081. size = self._bufsize
  1082. try:
  1083. if size < 1:
  1084. new_rows = dbapi_cursor.fetchall()
  1085. else:
  1086. new_rows = dbapi_cursor.fetchmany(size)
  1087. except BaseException as e:
  1088. self.handle_exception(result, dbapi_cursor, e)
  1089. if not new_rows:
  1090. return
  1091. self._rowbuffer = collections.deque(new_rows)
  1092. if self._growth_factor and size < self._max_row_buffer:
  1093. self._bufsize = min(
  1094. self._max_row_buffer, size * self._growth_factor
  1095. )
  1096. def yield_per(
  1097. self, result: CursorResult[Any], dbapi_cursor: DBAPICursor, num: int
  1098. ) -> None:
  1099. self._growth_factor = 0
  1100. self._max_row_buffer = self._bufsize = num
  1101. def soft_close(
  1102. self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
  1103. ) -> None:
  1104. self._rowbuffer.clear()
  1105. super().soft_close(result, dbapi_cursor)
  1106. def hard_close(
  1107. self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
  1108. ) -> None:
  1109. self._rowbuffer.clear()
  1110. super().hard_close(result, dbapi_cursor)
  1111. def fetchone(
  1112. self,
  1113. result: CursorResult[Any],
  1114. dbapi_cursor: DBAPICursor,
  1115. hard_close: bool = False,
  1116. ) -> Any:
  1117. if not self._rowbuffer:
  1118. self._buffer_rows(result, dbapi_cursor)
  1119. if not self._rowbuffer:
  1120. try:
  1121. result._soft_close(hard=hard_close)
  1122. except BaseException as e:
  1123. self.handle_exception(result, dbapi_cursor, e)
  1124. return None
  1125. return self._rowbuffer.popleft()
  1126. def fetchmany(
  1127. self,
  1128. result: CursorResult[Any],
  1129. dbapi_cursor: DBAPICursor,
  1130. size: Optional[int] = None,
  1131. ) -> Any:
  1132. if size is None:
  1133. return self.fetchall(result, dbapi_cursor)
  1134. rb = self._rowbuffer
  1135. lb = len(rb)
  1136. close = False
  1137. if size > lb:
  1138. try:
  1139. new = dbapi_cursor.fetchmany(size - lb)
  1140. except BaseException as e:
  1141. self.handle_exception(result, dbapi_cursor, e)
  1142. else:
  1143. if not new:
  1144. # defer closing since it may clear the row buffer
  1145. close = True
  1146. else:
  1147. rb.extend(new)
  1148. res = [rb.popleft() for _ in range(min(size, len(rb)))]
  1149. if close:
  1150. result._soft_close()
  1151. return res
  1152. def fetchall(
  1153. self, result: CursorResult[Any], dbapi_cursor: DBAPICursor
  1154. ) -> Any:
  1155. try:
  1156. ret = list(self._rowbuffer) + list(dbapi_cursor.fetchall())
  1157. self._rowbuffer.clear()
  1158. result._soft_close()
  1159. return ret
  1160. except BaseException as e:
  1161. self.handle_exception(result, dbapi_cursor, e)
  1162. class FullyBufferedCursorFetchStrategy(CursorFetchStrategy):
  1163. """A cursor strategy that buffers rows fully upon creation.
  1164. Used for operations where a result is to be delivered
  1165. after the database conversation can not be continued,
  1166. such as MSSQL INSERT...OUTPUT after an autocommit.
  1167. """
  1168. __slots__ = ("_rowbuffer", "alternate_cursor_description")
  1169. def __init__(
  1170. self,
  1171. dbapi_cursor: Optional[DBAPICursor],
  1172. alternate_description: Optional[_DBAPICursorDescription] = None,
  1173. initial_buffer: Optional[Iterable[Any]] = None,
  1174. ):
  1175. self.alternate_cursor_description = alternate_description
  1176. if initial_buffer is not None:
  1177. self._rowbuffer = collections.deque(initial_buffer)
  1178. else:
  1179. assert dbapi_cursor is not None
  1180. self._rowbuffer = collections.deque(dbapi_cursor.fetchall())
  1181. def yield_per(
  1182. self, result: CursorResult[Any], dbapi_cursor: DBAPICursor, num: int
  1183. ) -> Any:
  1184. pass
  1185. def soft_close(
  1186. self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
  1187. ) -> None:
  1188. self._rowbuffer.clear()
  1189. super().soft_close(result, dbapi_cursor)
  1190. def hard_close(
  1191. self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
  1192. ) -> None:
  1193. self._rowbuffer.clear()
  1194. super().hard_close(result, dbapi_cursor)
  1195. def fetchone(
  1196. self,
  1197. result: CursorResult[Any],
  1198. dbapi_cursor: DBAPICursor,
  1199. hard_close: bool = False,
  1200. ) -> Any:
  1201. if self._rowbuffer:
  1202. return self._rowbuffer.popleft()
  1203. else:
  1204. result._soft_close(hard=hard_close)
  1205. return None
  1206. def fetchmany(
  1207. self,
  1208. result: CursorResult[Any],
  1209. dbapi_cursor: DBAPICursor,
  1210. size: Optional[int] = None,
  1211. ) -> Any:
  1212. if size is None:
  1213. return self.fetchall(result, dbapi_cursor)
  1214. rb = self._rowbuffer
  1215. rows = [rb.popleft() for _ in range(min(size, len(rb)))]
  1216. if not rows:
  1217. result._soft_close()
  1218. return rows
  1219. def fetchall(
  1220. self, result: CursorResult[Any], dbapi_cursor: DBAPICursor
  1221. ) -> Any:
  1222. ret = self._rowbuffer
  1223. self._rowbuffer = collections.deque()
  1224. result._soft_close()
  1225. return ret
  1226. class _NoResultMetaData(ResultMetaData):
  1227. __slots__ = ()
  1228. returns_rows = False
  1229. def _we_dont_return_rows(
  1230. self, err: Optional[BaseException] = None
  1231. ) -> NoReturn:
  1232. raise exc.ResourceClosedError(
  1233. "This result object does not return rows. "
  1234. "It has been closed automatically."
  1235. ) from err
  1236. def _index_for_key(self, keys: _KeyIndexType, raiseerr: bool) -> NoReturn:
  1237. self._we_dont_return_rows()
  1238. def _metadata_for_keys(self, keys: Sequence[_KeyIndexType]) -> NoReturn:
  1239. self._we_dont_return_rows()
  1240. def _reduce(self, keys: Sequence[_KeyIndexType]) -> NoReturn:
  1241. self._we_dont_return_rows()
  1242. @property
  1243. def _keymap(self) -> NoReturn: # type: ignore[override]
  1244. self._we_dont_return_rows()
  1245. @property
  1246. def _key_to_index(self) -> NoReturn: # type: ignore[override]
  1247. self._we_dont_return_rows()
  1248. @property
  1249. def _processors(self) -> NoReturn: # type: ignore[override]
  1250. self._we_dont_return_rows()
  1251. @property
  1252. def keys(self) -> NoReturn:
  1253. self._we_dont_return_rows()
  1254. _NO_RESULT_METADATA = _NoResultMetaData()
  1255. def null_dml_result() -> IteratorResult[Any]:
  1256. it: IteratorResult[Any] = IteratorResult(_NoResultMetaData(), iter([]))
  1257. it._soft_close()
  1258. return it
  1259. class CursorResult(Result[_T]):
  1260. """A Result that is representing state from a DBAPI cursor.
  1261. .. versionchanged:: 1.4 The :class:`.CursorResult``
  1262. class replaces the previous :class:`.ResultProxy` interface.
  1263. This classes are based on the :class:`.Result` calling API
  1264. which provides an updated usage model and calling facade for
  1265. SQLAlchemy Core and SQLAlchemy ORM.
  1266. Returns database rows via the :class:`.Row` class, which provides
  1267. additional API features and behaviors on top of the raw data returned by
  1268. the DBAPI. Through the use of filters such as the :meth:`.Result.scalars`
  1269. method, other kinds of objects may also be returned.
  1270. .. seealso::
  1271. :ref:`tutorial_selecting_data` - introductory material for accessing
  1272. :class:`_engine.CursorResult` and :class:`.Row` objects.
  1273. """
  1274. __slots__ = (
  1275. "context",
  1276. "dialect",
  1277. "cursor",
  1278. "cursor_strategy",
  1279. "_echo",
  1280. "connection",
  1281. )
  1282. _metadata: Union[CursorResultMetaData, _NoResultMetaData]
  1283. _no_result_metadata = _NO_RESULT_METADATA
  1284. _soft_closed: bool = False
  1285. closed: bool = False
  1286. _is_cursor = True
  1287. context: DefaultExecutionContext
  1288. dialect: Dialect
  1289. cursor_strategy: ResultFetchStrategy
  1290. connection: Connection
  1291. def __init__(
  1292. self,
  1293. context: DefaultExecutionContext,
  1294. cursor_strategy: ResultFetchStrategy,
  1295. cursor_description: Optional[_DBAPICursorDescription],
  1296. ):
  1297. self.context = context
  1298. self.dialect = context.dialect
  1299. self.cursor = context.cursor
  1300. self.cursor_strategy = cursor_strategy
  1301. self.connection = context.root_connection
  1302. self._echo = echo = (
  1303. self.connection._echo and context.engine._should_log_debug()
  1304. )
  1305. if cursor_description is not None:
  1306. # inline of Result._row_getter(), set up an initial row
  1307. # getter assuming no transformations will be called as this
  1308. # is the most common case
  1309. metadata = self._init_metadata(context, cursor_description)
  1310. _make_row: Any
  1311. _make_row = functools.partial(
  1312. Row,
  1313. metadata,
  1314. metadata._effective_processors,
  1315. metadata._key_to_index,
  1316. )
  1317. if context._num_sentinel_cols:
  1318. sentinel_filter = operator.itemgetter(
  1319. slice(-context._num_sentinel_cols)
  1320. )
  1321. def _sliced_row(raw_data: Any) -> Any:
  1322. return _make_row(sentinel_filter(raw_data))
  1323. sliced_row = _sliced_row
  1324. else:
  1325. sliced_row = _make_row
  1326. if echo:
  1327. log = self.context.connection._log_debug
  1328. def _log_row(row: Any) -> Any:
  1329. log("Row %r", sql_util._repr_row(row))
  1330. return row
  1331. self._row_logging_fn = _log_row
  1332. def _make_row_2(row: Any) -> Any:
  1333. return _log_row(sliced_row(row))
  1334. make_row = _make_row_2
  1335. else:
  1336. make_row = sliced_row # type: ignore[assignment]
  1337. self._set_memoized_attribute("_row_getter", make_row)
  1338. else:
  1339. assert context._num_sentinel_cols == 0
  1340. self._metadata = self._no_result_metadata
  1341. def _init_metadata(
  1342. self,
  1343. context: DefaultExecutionContext,
  1344. cursor_description: _DBAPICursorDescription,
  1345. ) -> CursorResultMetaData:
  1346. if context.compiled:
  1347. compiled = context.compiled
  1348. if compiled._cached_metadata:
  1349. metadata = compiled._cached_metadata
  1350. else:
  1351. metadata = CursorResultMetaData(self, cursor_description)
  1352. if metadata._safe_for_cache:
  1353. compiled._cached_metadata = metadata
  1354. # result rewrite/ adapt step. this is to suit the case
  1355. # when we are invoked against a cached Compiled object, we want
  1356. # to rewrite the ResultMetaData to reflect the Column objects
  1357. # that are in our current SQL statement object, not the one
  1358. # that is associated with the cached Compiled object.
  1359. # the Compiled object may also tell us to not
  1360. # actually do this step; this is to support the ORM where
  1361. # it is to produce a new Result object in any case, and will
  1362. # be using the cached Column objects against this database result
  1363. # so we don't want to rewrite them.
  1364. #
  1365. # Basically this step suits the use case where the end user
  1366. # is using Core SQL expressions and is accessing columns in the
  1367. # result row using row._mapping[table.c.column].
  1368. if (
  1369. not context.execution_options.get(
  1370. "_result_disable_adapt_to_context", False
  1371. )
  1372. and compiled._result_columns
  1373. and context.cache_hit is context.dialect.CACHE_HIT
  1374. and compiled.statement is not context.invoked_statement # type: ignore[comparison-overlap] # noqa: E501
  1375. ):
  1376. metadata = metadata._adapt_to_context(context) # type: ignore[assignment] # noqa: E501
  1377. self._metadata = metadata
  1378. else:
  1379. self._metadata = metadata = CursorResultMetaData(
  1380. self, cursor_description
  1381. )
  1382. if self._echo:
  1383. context.connection._log_debug(
  1384. "Col %r", tuple(x[0] for x in cursor_description)
  1385. )
  1386. return metadata
  1387. def _soft_close(self, hard: bool = False) -> None:
  1388. """Soft close this :class:`_engine.CursorResult`.
  1389. This releases all DBAPI cursor resources, but leaves the
  1390. CursorResult "open" from a semantic perspective, meaning the
  1391. fetchXXX() methods will continue to return empty results.
  1392. This method is called automatically when:
  1393. * all result rows are exhausted using the fetchXXX() methods.
  1394. * cursor.description is None.
  1395. This method is **not public**, but is documented in order to clarify
  1396. the "autoclose" process used.
  1397. .. seealso::
  1398. :meth:`_engine.CursorResult.close`
  1399. """
  1400. if (not hard and self._soft_closed) or (hard and self.closed):
  1401. return
  1402. if hard:
  1403. self.closed = True
  1404. self.cursor_strategy.hard_close(self, self.cursor)
  1405. else:
  1406. self.cursor_strategy.soft_close(self, self.cursor)
  1407. if not self._soft_closed:
  1408. cursor = self.cursor
  1409. self.cursor = None # type: ignore
  1410. self.connection._safe_close_cursor(cursor)
  1411. self._soft_closed = True
  1412. @property
  1413. def inserted_primary_key_rows(self) -> List[Optional[Any]]:
  1414. """Return the value of
  1415. :attr:`_engine.CursorResult.inserted_primary_key`
  1416. as a row contained within a list; some dialects may support a
  1417. multiple row form as well.
  1418. .. note:: As indicated below, in current SQLAlchemy versions this
  1419. accessor is only useful beyond what's already supplied by
  1420. :attr:`_engine.CursorResult.inserted_primary_key` when using the
  1421. :ref:`postgresql_psycopg2` dialect. Future versions hope to
  1422. generalize this feature to more dialects.
  1423. This accessor is added to support dialects that offer the feature
  1424. that is currently implemented by the :ref:`psycopg2_executemany_mode`
  1425. feature, currently **only the psycopg2 dialect**, which provides
  1426. for many rows to be INSERTed at once while still retaining the
  1427. behavior of being able to return server-generated primary key values.
  1428. * **When using the psycopg2 dialect, or other dialects that may support
  1429. "fast executemany" style inserts in upcoming releases** : When
  1430. invoking an INSERT statement while passing a list of rows as the
  1431. second argument to :meth:`_engine.Connection.execute`, this accessor
  1432. will then provide a list of rows, where each row contains the primary
  1433. key value for each row that was INSERTed.
  1434. * **When using all other dialects / backends that don't yet support
  1435. this feature**: This accessor is only useful for **single row INSERT
  1436. statements**, and returns the same information as that of the
  1437. :attr:`_engine.CursorResult.inserted_primary_key` within a
  1438. single-element list. When an INSERT statement is executed in
  1439. conjunction with a list of rows to be INSERTed, the list will contain
  1440. one row per row inserted in the statement, however it will contain
  1441. ``None`` for any server-generated values.
  1442. Future releases of SQLAlchemy will further generalize the
  1443. "fast execution helper" feature of psycopg2 to suit other dialects,
  1444. thus allowing this accessor to be of more general use.
  1445. .. versionadded:: 1.4
  1446. .. seealso::
  1447. :attr:`_engine.CursorResult.inserted_primary_key`
  1448. """
  1449. if not self.context.compiled:
  1450. raise exc.InvalidRequestError(
  1451. "Statement is not a compiled expression construct."
  1452. )
  1453. elif not self.context.isinsert:
  1454. raise exc.InvalidRequestError(
  1455. "Statement is not an insert() expression construct."
  1456. )
  1457. elif self.context._is_explicit_returning:
  1458. raise exc.InvalidRequestError(
  1459. "Can't call inserted_primary_key "
  1460. "when returning() "
  1461. "is used."
  1462. )
  1463. return self.context.inserted_primary_key_rows # type: ignore[no-any-return] # noqa: E501
  1464. @property
  1465. def inserted_primary_key(self) -> Optional[Any]:
  1466. """Return the primary key for the row just inserted.
  1467. The return value is a :class:`_result.Row` object representing
  1468. a named tuple of primary key values in the order in which the
  1469. primary key columns are configured in the source
  1470. :class:`_schema.Table`.
  1471. .. versionchanged:: 1.4.8 - the
  1472. :attr:`_engine.CursorResult.inserted_primary_key`
  1473. value is now a named tuple via the :class:`_result.Row` class,
  1474. rather than a plain tuple.
  1475. This accessor only applies to single row :func:`_expression.insert`
  1476. constructs which did not explicitly specify
  1477. :meth:`_expression.Insert.returning`. Support for multirow inserts,
  1478. while not yet available for most backends, would be accessed using
  1479. the :attr:`_engine.CursorResult.inserted_primary_key_rows` accessor.
  1480. Note that primary key columns which specify a server_default clause, or
  1481. otherwise do not qualify as "autoincrement" columns (see the notes at
  1482. :class:`_schema.Column`), and were generated using the database-side
  1483. default, will appear in this list as ``None`` unless the backend
  1484. supports "returning" and the insert statement executed with the
  1485. "implicit returning" enabled.
  1486. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1487. statement is not a compiled expression construct
  1488. or is not an insert() construct.
  1489. """
  1490. if self.context.executemany:
  1491. raise exc.InvalidRequestError(
  1492. "This statement was an executemany call; if primary key "
  1493. "returning is supported, please "
  1494. "use .inserted_primary_key_rows."
  1495. )
  1496. ikp = self.inserted_primary_key_rows
  1497. if ikp:
  1498. return ikp[0]
  1499. else:
  1500. return None
  1501. def last_updated_params(
  1502. self,
  1503. ) -> Union[
  1504. List[_MutableCoreSingleExecuteParams], _MutableCoreSingleExecuteParams
  1505. ]:
  1506. """Return the collection of updated parameters from this
  1507. execution.
  1508. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1509. statement is not a compiled expression construct
  1510. or is not an update() construct.
  1511. """
  1512. if not self.context.compiled:
  1513. raise exc.InvalidRequestError(
  1514. "Statement is not a compiled expression construct."
  1515. )
  1516. elif not self.context.isupdate:
  1517. raise exc.InvalidRequestError(
  1518. "Statement is not an update() expression construct."
  1519. )
  1520. elif self.context.executemany:
  1521. return self.context.compiled_parameters
  1522. else:
  1523. return self.context.compiled_parameters[0]
  1524. def last_inserted_params(
  1525. self,
  1526. ) -> Union[
  1527. List[_MutableCoreSingleExecuteParams], _MutableCoreSingleExecuteParams
  1528. ]:
  1529. """Return the collection of inserted parameters from this
  1530. execution.
  1531. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1532. statement is not a compiled expression construct
  1533. or is not an insert() construct.
  1534. """
  1535. if not self.context.compiled:
  1536. raise exc.InvalidRequestError(
  1537. "Statement is not a compiled expression construct."
  1538. )
  1539. elif not self.context.isinsert:
  1540. raise exc.InvalidRequestError(
  1541. "Statement is not an insert() expression construct."
  1542. )
  1543. elif self.context.executemany:
  1544. return self.context.compiled_parameters
  1545. else:
  1546. return self.context.compiled_parameters[0]
  1547. @property
  1548. def returned_defaults_rows(
  1549. self,
  1550. ) -> Optional[Sequence[Row[Any]]]:
  1551. """Return a list of rows each containing the values of default
  1552. columns that were fetched using
  1553. the :meth:`.ValuesBase.return_defaults` feature.
  1554. The return value is a list of :class:`.Row` objects.
  1555. .. versionadded:: 1.4
  1556. """
  1557. return self.context.returned_default_rows
  1558. def splice_horizontally(self, other: CursorResult[Any]) -> Self:
  1559. """Return a new :class:`.CursorResult` that "horizontally splices"
  1560. together the rows of this :class:`.CursorResult` with that of another
  1561. :class:`.CursorResult`.
  1562. .. tip:: This method is for the benefit of the SQLAlchemy ORM and is
  1563. not intended for general use.
  1564. "horizontally splices" means that for each row in the first and second
  1565. result sets, a new row that concatenates the two rows together is
  1566. produced, which then becomes the new row. The incoming
  1567. :class:`.CursorResult` must have the identical number of rows. It is
  1568. typically expected that the two result sets come from the same sort
  1569. order as well, as the result rows are spliced together based on their
  1570. position in the result.
  1571. The expected use case here is so that multiple INSERT..RETURNING
  1572. statements (which definitely need to be sorted) against different
  1573. tables can produce a single result that looks like a JOIN of those two
  1574. tables.
  1575. E.g.::
  1576. r1 = connection.execute(
  1577. users.insert().returning(
  1578. users.c.user_name, users.c.user_id, sort_by_parameter_order=True
  1579. ),
  1580. user_values,
  1581. )
  1582. r2 = connection.execute(
  1583. addresses.insert().returning(
  1584. addresses.c.address_id,
  1585. addresses.c.address,
  1586. addresses.c.user_id,
  1587. sort_by_parameter_order=True,
  1588. ),
  1589. address_values,
  1590. )
  1591. rows = r1.splice_horizontally(r2).all()
  1592. assert rows == [
  1593. ("john", 1, 1, "foo@bar.com", 1),
  1594. ("jack", 2, 2, "bar@bat.com", 2),
  1595. ]
  1596. .. versionadded:: 2.0
  1597. .. seealso::
  1598. :meth:`.CursorResult.splice_vertically`
  1599. """ # noqa: E501
  1600. clone = self._generate()
  1601. total_rows = [
  1602. tuple(r1) + tuple(r2)
  1603. for r1, r2 in zip(
  1604. list(self._raw_row_iterator()),
  1605. list(other._raw_row_iterator()),
  1606. )
  1607. ]
  1608. clone._metadata = clone._metadata._splice_horizontally(other._metadata) # type: ignore[union-attr, arg-type] # noqa: E501
  1609. clone.cursor_strategy = FullyBufferedCursorFetchStrategy(
  1610. None,
  1611. initial_buffer=total_rows,
  1612. )
  1613. clone._reset_memoizations()
  1614. return clone
  1615. def splice_vertically(self, other: CursorResult[Any]) -> Self:
  1616. """Return a new :class:`.CursorResult` that "vertically splices",
  1617. i.e. "extends", the rows of this :class:`.CursorResult` with that of
  1618. another :class:`.CursorResult`.
  1619. .. tip:: This method is for the benefit of the SQLAlchemy ORM and is
  1620. not intended for general use.
  1621. "vertically splices" means the rows of the given result are appended to
  1622. the rows of this cursor result. The incoming :class:`.CursorResult`
  1623. must have rows that represent the identical list of columns in the
  1624. identical order as they are in this :class:`.CursorResult`.
  1625. .. versionadded:: 2.0
  1626. .. seealso::
  1627. :meth:`.CursorResult.splice_horizontally`
  1628. """
  1629. clone = self._generate()
  1630. total_rows = list(self._raw_row_iterator()) + list(
  1631. other._raw_row_iterator()
  1632. )
  1633. clone.cursor_strategy = FullyBufferedCursorFetchStrategy(
  1634. None,
  1635. initial_buffer=total_rows,
  1636. )
  1637. clone._reset_memoizations()
  1638. return clone
  1639. def _rewind(self, rows: Any) -> Self:
  1640. """rewind this result back to the given rowset.
  1641. this is used internally for the case where an :class:`.Insert`
  1642. construct combines the use of
  1643. :meth:`.Insert.return_defaults` along with the
  1644. "supplemental columns" feature.
  1645. """
  1646. if self._echo:
  1647. self.context.connection._log_debug(
  1648. "CursorResult rewound %d row(s)", len(rows)
  1649. )
  1650. # the rows given are expected to be Row objects, so we
  1651. # have to clear out processors which have already run on these
  1652. # rows
  1653. self._metadata = cast(
  1654. CursorResultMetaData, self._metadata
  1655. )._remove_processors()
  1656. self.cursor_strategy = FullyBufferedCursorFetchStrategy(
  1657. None,
  1658. # TODO: if these are Row objects, can we save on not having to
  1659. # re-make new Row objects out of them a second time? is that
  1660. # what's actually happening right now? maybe look into this
  1661. initial_buffer=rows,
  1662. )
  1663. self._reset_memoizations()
  1664. return self
  1665. @property
  1666. def returned_defaults(self) -> Optional[Row[Any]]:
  1667. """Return the values of default columns that were fetched using
  1668. the :meth:`.ValuesBase.return_defaults` feature.
  1669. The value is an instance of :class:`.Row`, or ``None``
  1670. if :meth:`.ValuesBase.return_defaults` was not used or if the
  1671. backend does not support RETURNING.
  1672. .. seealso::
  1673. :meth:`.ValuesBase.return_defaults`
  1674. """
  1675. if self.context.executemany:
  1676. raise exc.InvalidRequestError(
  1677. "This statement was an executemany call; if return defaults "
  1678. "is supported, please use .returned_defaults_rows."
  1679. )
  1680. rows = self.context.returned_default_rows
  1681. if rows:
  1682. return rows[0]
  1683. else:
  1684. return None
  1685. def lastrow_has_defaults(self) -> bool:
  1686. """Return ``lastrow_has_defaults()`` from the underlying
  1687. :class:`.ExecutionContext`.
  1688. See :class:`.ExecutionContext` for details.
  1689. """
  1690. return self.context.lastrow_has_defaults()
  1691. def postfetch_cols(self) -> Optional[Sequence[Column[Any]]]:
  1692. """Return ``postfetch_cols()`` from the underlying
  1693. :class:`.ExecutionContext`.
  1694. See :class:`.ExecutionContext` for details.
  1695. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1696. statement is not a compiled expression construct
  1697. or is not an insert() or update() construct.
  1698. """
  1699. if not self.context.compiled:
  1700. raise exc.InvalidRequestError(
  1701. "Statement is not a compiled expression construct."
  1702. )
  1703. elif not self.context.isinsert and not self.context.isupdate:
  1704. raise exc.InvalidRequestError(
  1705. "Statement is not an insert() or update() "
  1706. "expression construct."
  1707. )
  1708. return self.context.postfetch_cols
  1709. def prefetch_cols(self) -> Optional[Sequence[Column[Any]]]:
  1710. """Return ``prefetch_cols()`` from the underlying
  1711. :class:`.ExecutionContext`.
  1712. See :class:`.ExecutionContext` for details.
  1713. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1714. statement is not a compiled expression construct
  1715. or is not an insert() or update() construct.
  1716. """
  1717. if not self.context.compiled:
  1718. raise exc.InvalidRequestError(
  1719. "Statement is not a compiled expression construct."
  1720. )
  1721. elif not self.context.isinsert and not self.context.isupdate:
  1722. raise exc.InvalidRequestError(
  1723. "Statement is not an insert() or update() "
  1724. "expression construct."
  1725. )
  1726. return self.context.prefetch_cols
  1727. def supports_sane_rowcount(self) -> bool:
  1728. """Return ``supports_sane_rowcount`` from the dialect.
  1729. See :attr:`_engine.CursorResult.rowcount` for background.
  1730. """
  1731. return self.dialect.supports_sane_rowcount
  1732. def supports_sane_multi_rowcount(self) -> bool:
  1733. """Return ``supports_sane_multi_rowcount`` from the dialect.
  1734. See :attr:`_engine.CursorResult.rowcount` for background.
  1735. """
  1736. return self.dialect.supports_sane_multi_rowcount
  1737. @util.memoized_property
  1738. def rowcount(self) -> int:
  1739. """Return the 'rowcount' for this result.
  1740. The primary purpose of 'rowcount' is to report the number of rows
  1741. matched by the WHERE criterion of an UPDATE or DELETE statement
  1742. executed once (i.e. for a single parameter set), which may then be
  1743. compared to the number of rows expected to be updated or deleted as a
  1744. means of asserting data integrity.
  1745. This attribute is transferred from the ``cursor.rowcount`` attribute
  1746. of the DBAPI before the cursor is closed, to support DBAPIs that
  1747. don't make this value available after cursor close. Some DBAPIs may
  1748. offer meaningful values for other kinds of statements, such as INSERT
  1749. and SELECT statements as well. In order to retrieve ``cursor.rowcount``
  1750. for these statements, set the
  1751. :paramref:`.Connection.execution_options.preserve_rowcount`
  1752. execution option to True, which will cause the ``cursor.rowcount``
  1753. value to be unconditionally memoized before any results are returned
  1754. or the cursor is closed, regardless of statement type.
  1755. For cases where the DBAPI does not support rowcount for a particular
  1756. kind of statement and/or execution, the returned value will be ``-1``,
  1757. which is delivered directly from the DBAPI and is part of :pep:`249`.
  1758. All DBAPIs should support rowcount for single-parameter-set
  1759. UPDATE and DELETE statements, however.
  1760. .. note::
  1761. Notes regarding :attr:`_engine.CursorResult.rowcount`:
  1762. * This attribute returns the number of rows *matched*,
  1763. which is not necessarily the same as the number of rows
  1764. that were actually *modified*. For example, an UPDATE statement
  1765. may have no net change on a given row if the SET values
  1766. given are the same as those present in the row already.
  1767. Such a row would be matched but not modified.
  1768. On backends that feature both styles, such as MySQL,
  1769. rowcount is configured to return the match
  1770. count in all cases.
  1771. * :attr:`_engine.CursorResult.rowcount` in the default case is
  1772. *only* useful in conjunction with an UPDATE or DELETE statement,
  1773. and only with a single set of parameters. For other kinds of
  1774. statements, SQLAlchemy will not attempt to pre-memoize the value
  1775. unless the
  1776. :paramref:`.Connection.execution_options.preserve_rowcount`
  1777. execution option is used. Note that contrary to :pep:`249`, many
  1778. DBAPIs do not support rowcount values for statements that are not
  1779. UPDATE or DELETE, particularly when rows are being returned which
  1780. are not fully pre-buffered. DBAPIs that dont support rowcount
  1781. for a particular kind of statement should return the value ``-1``
  1782. for such statements.
  1783. * :attr:`_engine.CursorResult.rowcount` may not be meaningful
  1784. when executing a single statement with multiple parameter sets
  1785. (i.e. an :term:`executemany`). Most DBAPIs do not sum "rowcount"
  1786. values across multiple parameter sets and will return ``-1``
  1787. when accessed.
  1788. * SQLAlchemy's :ref:`engine_insertmanyvalues` feature does support
  1789. a correct population of :attr:`_engine.CursorResult.rowcount`
  1790. when the :paramref:`.Connection.execution_options.preserve_rowcount`
  1791. execution option is set to True.
  1792. * Statements that use RETURNING may not support rowcount, returning
  1793. a ``-1`` value instead.
  1794. .. seealso::
  1795. :ref:`tutorial_update_delete_rowcount` - in the :ref:`unified_tutorial`
  1796. :paramref:`.Connection.execution_options.preserve_rowcount`
  1797. """ # noqa: E501
  1798. try:
  1799. return self.context.rowcount
  1800. except BaseException as e:
  1801. self.cursor_strategy.handle_exception(self, self.cursor, e)
  1802. raise # not called
  1803. @property
  1804. def lastrowid(self) -> int:
  1805. """Return the 'lastrowid' accessor on the DBAPI cursor.
  1806. This is a DBAPI specific method and is only functional
  1807. for those backends which support it, for statements
  1808. where it is appropriate. It's behavior is not
  1809. consistent across backends.
  1810. Usage of this method is normally unnecessary when
  1811. using insert() expression constructs; the
  1812. :attr:`~CursorResult.inserted_primary_key` attribute provides a
  1813. tuple of primary key values for a newly inserted row,
  1814. regardless of database backend.
  1815. """
  1816. try:
  1817. return self.context.get_lastrowid()
  1818. except BaseException as e:
  1819. self.cursor_strategy.handle_exception(self, self.cursor, e)
  1820. @property
  1821. def returns_rows(self) -> bool:
  1822. """True if this :class:`_engine.CursorResult` returns zero or more
  1823. rows.
  1824. I.e. if it is legal to call the methods
  1825. :meth:`_engine.CursorResult.fetchone`,
  1826. :meth:`_engine.CursorResult.fetchmany`
  1827. :meth:`_engine.CursorResult.fetchall`.
  1828. Overall, the value of :attr:`_engine.CursorResult.returns_rows` should
  1829. always be synonymous with whether or not the DBAPI cursor had a
  1830. ``.description`` attribute, indicating the presence of result columns,
  1831. noting that a cursor that returns zero rows still has a
  1832. ``.description`` if a row-returning statement was emitted.
  1833. This attribute should be True for all results that are against
  1834. SELECT statements, as well as for DML statements INSERT/UPDATE/DELETE
  1835. that use RETURNING. For INSERT/UPDATE/DELETE statements that were
  1836. not using RETURNING, the value will usually be False, however
  1837. there are some dialect-specific exceptions to this, such as when
  1838. using the MSSQL / pyodbc dialect a SELECT is emitted inline in
  1839. order to retrieve an inserted primary key value.
  1840. """
  1841. return self._metadata.returns_rows
  1842. @property
  1843. def is_insert(self) -> bool:
  1844. """True if this :class:`_engine.CursorResult` is the result
  1845. of a executing an expression language compiled
  1846. :func:`_expression.insert` construct.
  1847. When True, this implies that the
  1848. :attr:`inserted_primary_key` attribute is accessible,
  1849. assuming the statement did not include
  1850. a user defined "returning" construct.
  1851. """
  1852. return self.context.isinsert
  1853. def _fetchiter_impl(self) -> Iterator[Any]:
  1854. fetchone = self.cursor_strategy.fetchone
  1855. while True:
  1856. row = fetchone(self, self.cursor)
  1857. if row is None:
  1858. break
  1859. yield row
  1860. def _fetchone_impl(self, hard_close: bool = False) -> Any:
  1861. return self.cursor_strategy.fetchone(self, self.cursor, hard_close)
  1862. def _fetchall_impl(self) -> Any:
  1863. return self.cursor_strategy.fetchall(self, self.cursor)
  1864. def _fetchmany_impl(self, size: Optional[int] = None) -> Any:
  1865. return self.cursor_strategy.fetchmany(self, self.cursor, size)
  1866. def _raw_row_iterator(self) -> Any:
  1867. return self._fetchiter_impl()
  1868. def merge(self, *others: Result[Any]) -> MergedResult[Any]:
  1869. merged_result = super().merge(*others)
  1870. if self.context._has_rowcount:
  1871. merged_result.rowcount = sum(
  1872. cast("CursorResult[Any]", result).rowcount
  1873. for result in (self,) + others
  1874. )
  1875. return merged_result
  1876. def close(self) -> None:
  1877. """Close this :class:`_engine.CursorResult`.
  1878. This closes out the underlying DBAPI cursor corresponding to the
  1879. statement execution, if one is still present. Note that the DBAPI
  1880. cursor is automatically released when the :class:`_engine.CursorResult`
  1881. exhausts all available rows. :meth:`_engine.CursorResult.close` is
  1882. generally an optional method except in the case when discarding a
  1883. :class:`_engine.CursorResult` that still has additional rows pending
  1884. for fetch.
  1885. After this method is called, it is no longer valid to call upon
  1886. the fetch methods, which will raise a :class:`.ResourceClosedError`
  1887. on subsequent use.
  1888. .. seealso::
  1889. :ref:`connections_toplevel`
  1890. """
  1891. self._soft_close(hard=True)
  1892. @_generative
  1893. def yield_per(self, num: int) -> Self:
  1894. self._yield_per = num
  1895. self.cursor_strategy.yield_per(self, self.cursor, num)
  1896. return self
  1897. ResultProxy = CursorResult