cursor.py 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  1. # engine/cursor.py
  2. # Copyright (C) 2005-2022 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:`.BaseCursorResult`, :class:`.CursorResult`."""
  9. import collections
  10. import functools
  11. from .result import Result
  12. from .result import ResultMetaData
  13. from .result import SimpleResultMetaData
  14. from .result import tuplegetter
  15. from .row import LegacyRow
  16. from .. import exc
  17. from .. import util
  18. from ..sql import expression
  19. from ..sql import sqltypes
  20. from ..sql import util as sql_util
  21. from ..sql.base import _generative
  22. from ..sql.compiler import RM_NAME
  23. from ..sql.compiler import RM_OBJECTS
  24. from ..sql.compiler import RM_RENDERED_NAME
  25. from ..sql.compiler import RM_TYPE
  26. _UNPICKLED = util.symbol("unpickled")
  27. # metadata entry tuple indexes.
  28. # using raw tuple is faster than namedtuple.
  29. MD_INDEX = 0 # integer index in cursor.description
  30. MD_RESULT_MAP_INDEX = 1 # integer index in compiled._result_columns
  31. MD_OBJECTS = 2 # other string keys and ColumnElement obj that can match
  32. MD_LOOKUP_KEY = 3 # string key we usually expect for key-based lookup
  33. MD_RENDERED_NAME = 4 # name that is usually in cursor.description
  34. MD_PROCESSOR = 5 # callable to process a result value into a row
  35. MD_UNTRANSLATED = 6 # raw name from cursor.description
  36. class CursorResultMetaData(ResultMetaData):
  37. """Result metadata for DBAPI cursors."""
  38. __slots__ = (
  39. "_keymap",
  40. "case_sensitive",
  41. "_processors",
  42. "_keys",
  43. "_keymap_by_result_column_idx",
  44. "_tuplefilter",
  45. "_translated_indexes",
  46. "_safe_for_cache"
  47. # don't need _unique_filters support here for now. Can be added
  48. # if a need arises.
  49. )
  50. returns_rows = True
  51. def _has_key(self, key):
  52. return key in self._keymap
  53. def _for_freeze(self):
  54. return SimpleResultMetaData(
  55. self._keys,
  56. extra=[self._keymap[key][MD_OBJECTS] for key in self._keys],
  57. )
  58. def _reduce(self, keys):
  59. recs = list(self._metadata_for_keys(keys))
  60. indexes = [rec[MD_INDEX] for rec in recs]
  61. new_keys = [rec[MD_LOOKUP_KEY] for rec in recs]
  62. if self._translated_indexes:
  63. indexes = [self._translated_indexes[idx] for idx in indexes]
  64. tup = tuplegetter(*indexes)
  65. new_metadata = self.__class__.__new__(self.__class__)
  66. new_metadata.case_sensitive = self.case_sensitive
  67. new_metadata._processors = self._processors
  68. new_metadata._keys = new_keys
  69. new_metadata._tuplefilter = tup
  70. new_metadata._translated_indexes = indexes
  71. new_recs = [
  72. (index,) + rec[1:]
  73. for index, rec in enumerate(self._metadata_for_keys(keys))
  74. ]
  75. new_metadata._keymap = {rec[MD_LOOKUP_KEY]: rec for rec in new_recs}
  76. # TODO: need unit test for:
  77. # result = connection.execute("raw sql, no columns").scalars()
  78. # without the "or ()" it's failing because MD_OBJECTS is None
  79. new_metadata._keymap.update(
  80. {
  81. e: new_rec
  82. for new_rec in new_recs
  83. for e in new_rec[MD_OBJECTS] or ()
  84. }
  85. )
  86. return new_metadata
  87. def _adapt_to_context(self, context):
  88. """When using a cached Compiled construct that has a _result_map,
  89. for a new statement that used the cached Compiled, we need to ensure
  90. the keymap has the Column objects from our new statement as keys.
  91. So here we rewrite keymap with new entries for the new columns
  92. as matched to those of the cached statement.
  93. """
  94. if not context.compiled._result_columns:
  95. return self
  96. compiled_statement = context.compiled.statement
  97. invoked_statement = context.invoked_statement
  98. if compiled_statement is invoked_statement:
  99. return self
  100. # make a copy and add the columns from the invoked statement
  101. # to the result map.
  102. md = self.__class__.__new__(self.__class__)
  103. md._keymap = dict(self._keymap)
  104. keymap_by_position = self._keymap_by_result_column_idx
  105. for idx, new in enumerate(invoked_statement._all_selected_columns):
  106. try:
  107. rec = keymap_by_position[idx]
  108. except KeyError:
  109. # this can happen when there are bogus column entries
  110. # in a TextualSelect
  111. pass
  112. else:
  113. md._keymap[new] = rec
  114. md.case_sensitive = self.case_sensitive
  115. md._processors = self._processors
  116. assert not self._tuplefilter
  117. md._tuplefilter = None
  118. md._translated_indexes = None
  119. md._keys = self._keys
  120. md._keymap_by_result_column_idx = self._keymap_by_result_column_idx
  121. md._safe_for_cache = self._safe_for_cache
  122. return md
  123. def __init__(self, parent, cursor_description):
  124. context = parent.context
  125. dialect = context.dialect
  126. self._tuplefilter = None
  127. self._translated_indexes = None
  128. self.case_sensitive = dialect.case_sensitive
  129. self._safe_for_cache = False
  130. if context.result_column_struct:
  131. (
  132. result_columns,
  133. cols_are_ordered,
  134. textual_ordered,
  135. loose_column_name_matching,
  136. ) = context.result_column_struct
  137. num_ctx_cols = len(result_columns)
  138. else:
  139. result_columns = (
  140. cols_are_ordered
  141. ) = (
  142. num_ctx_cols
  143. ) = loose_column_name_matching = textual_ordered = False
  144. # merge cursor.description with the column info
  145. # present in the compiled structure, if any
  146. raw = self._merge_cursor_description(
  147. context,
  148. cursor_description,
  149. result_columns,
  150. num_ctx_cols,
  151. cols_are_ordered,
  152. textual_ordered,
  153. loose_column_name_matching,
  154. )
  155. self._keymap = {}
  156. # processors in key order for certain per-row
  157. # views like __iter__ and slices
  158. self._processors = [
  159. metadata_entry[MD_PROCESSOR] for metadata_entry in raw
  160. ]
  161. if context.compiled:
  162. self._keymap_by_result_column_idx = {
  163. metadata_entry[MD_RESULT_MAP_INDEX]: metadata_entry
  164. for metadata_entry in raw
  165. }
  166. # keymap by primary string...
  167. by_key = dict(
  168. [
  169. (metadata_entry[MD_LOOKUP_KEY], metadata_entry)
  170. for metadata_entry in raw
  171. ]
  172. )
  173. # for compiled SQL constructs, copy additional lookup keys into
  174. # the key lookup map, such as Column objects, labels,
  175. # column keys and other names
  176. if num_ctx_cols:
  177. # if by-primary-string dictionary smaller (or bigger?!) than
  178. # number of columns, assume we have dupes, rewrite
  179. # dupe records with "None" for index which results in
  180. # ambiguous column exception when accessed.
  181. if len(by_key) != num_ctx_cols:
  182. # new in 1.4: get the complete set of all possible keys,
  183. # strings, objects, whatever, that are dupes across two
  184. # different records, first.
  185. index_by_key = {}
  186. dupes = set()
  187. for metadata_entry in raw:
  188. for key in (metadata_entry[MD_RENDERED_NAME],) + (
  189. metadata_entry[MD_OBJECTS] or ()
  190. ):
  191. if not self.case_sensitive and isinstance(
  192. key, util.string_types
  193. ):
  194. key = key.lower()
  195. idx = metadata_entry[MD_INDEX]
  196. # if this key has been associated with more than one
  197. # positional index, it's a dupe
  198. if index_by_key.setdefault(key, idx) != idx:
  199. dupes.add(key)
  200. # then put everything we have into the keymap excluding only
  201. # those keys that are dupes.
  202. self._keymap.update(
  203. [
  204. (obj_elem, metadata_entry)
  205. for metadata_entry in raw
  206. if metadata_entry[MD_OBJECTS]
  207. for obj_elem in metadata_entry[MD_OBJECTS]
  208. if obj_elem not in dupes
  209. ]
  210. )
  211. # then for the dupe keys, put the "ambiguous column"
  212. # record into by_key.
  213. by_key.update({key: (None, None, (), key) for key in dupes})
  214. else:
  215. # no dupes - copy secondary elements from compiled
  216. # columns into self._keymap
  217. self._keymap.update(
  218. [
  219. (obj_elem, metadata_entry)
  220. for metadata_entry in raw
  221. if metadata_entry[MD_OBJECTS]
  222. for obj_elem in metadata_entry[MD_OBJECTS]
  223. ]
  224. )
  225. # update keymap with primary string names taking
  226. # precedence
  227. self._keymap.update(by_key)
  228. # update keymap with "translated" names (sqlite-only thing)
  229. if not num_ctx_cols and context._translate_colname:
  230. self._keymap.update(
  231. [
  232. (
  233. metadata_entry[MD_UNTRANSLATED],
  234. self._keymap[metadata_entry[MD_LOOKUP_KEY]],
  235. )
  236. for metadata_entry in raw
  237. if metadata_entry[MD_UNTRANSLATED]
  238. ]
  239. )
  240. def _merge_cursor_description(
  241. self,
  242. context,
  243. cursor_description,
  244. result_columns,
  245. num_ctx_cols,
  246. cols_are_ordered,
  247. textual_ordered,
  248. loose_column_name_matching,
  249. ):
  250. """Merge a cursor.description with compiled result column information.
  251. There are at least four separate strategies used here, selected
  252. depending on the type of SQL construct used to start with.
  253. The most common case is that of the compiled SQL expression construct,
  254. which generated the column names present in the raw SQL string and
  255. which has the identical number of columns as were reported by
  256. cursor.description. In this case, we assume a 1-1 positional mapping
  257. between the entries in cursor.description and the compiled object.
  258. This is also the most performant case as we disregard extracting /
  259. decoding the column names present in cursor.description since we
  260. already have the desired name we generated in the compiled SQL
  261. construct.
  262. The next common case is that of the completely raw string SQL,
  263. such as passed to connection.execute(). In this case we have no
  264. compiled construct to work with, so we extract and decode the
  265. names from cursor.description and index those as the primary
  266. result row target keys.
  267. The remaining fairly common case is that of the textual SQL
  268. that includes at least partial column information; this is when
  269. we use a :class:`_expression.TextualSelect` construct.
  270. This construct may have
  271. unordered or ordered column information. In the ordered case, we
  272. merge the cursor.description and the compiled construct's information
  273. positionally, and warn if there are additional description names
  274. present, however we still decode the names in cursor.description
  275. as we don't have a guarantee that the names in the columns match
  276. on these. In the unordered case, we match names in cursor.description
  277. to that of the compiled construct based on name matching.
  278. In both of these cases, the cursor.description names and the column
  279. expression objects and names are indexed as result row target keys.
  280. The final case is much less common, where we have a compiled
  281. non-textual SQL expression construct, but the number of columns
  282. in cursor.description doesn't match what's in the compiled
  283. construct. We make the guess here that there might be textual
  284. column expressions in the compiled construct that themselves include
  285. a comma in them causing them to split. We do the same name-matching
  286. as with textual non-ordered columns.
  287. The name-matched system of merging is the same as that used by
  288. SQLAlchemy for all cases up through te 0.9 series. Positional
  289. matching for compiled SQL expressions was introduced in 1.0 as a
  290. major performance feature, and positional matching for textual
  291. :class:`_expression.TextualSelect` objects in 1.1.
  292. As name matching is no longer
  293. a common case, it was acceptable to factor it into smaller generator-
  294. oriented methods that are easier to understand, but incur slightly
  295. more performance overhead.
  296. """
  297. case_sensitive = context.dialect.case_sensitive
  298. if (
  299. num_ctx_cols
  300. and cols_are_ordered
  301. and not textual_ordered
  302. and num_ctx_cols == len(cursor_description)
  303. ):
  304. self._keys = [elem[0] for elem in result_columns]
  305. # pure positional 1-1 case; doesn't need to read
  306. # the names from cursor.description
  307. # this metadata is safe to cache because we are guaranteed
  308. # to have the columns in the same order for new executions
  309. self._safe_for_cache = True
  310. return [
  311. (
  312. idx,
  313. idx,
  314. rmap_entry[RM_OBJECTS],
  315. rmap_entry[RM_NAME].lower()
  316. if not case_sensitive
  317. else rmap_entry[RM_NAME],
  318. rmap_entry[RM_RENDERED_NAME],
  319. context.get_result_processor(
  320. rmap_entry[RM_TYPE],
  321. rmap_entry[RM_RENDERED_NAME],
  322. cursor_description[idx][1],
  323. ),
  324. None,
  325. )
  326. for idx, rmap_entry in enumerate(result_columns)
  327. ]
  328. else:
  329. # name-based or text-positional cases, where we need
  330. # to read cursor.description names
  331. if textual_ordered:
  332. self._safe_for_cache = True
  333. # textual positional case
  334. raw_iterator = self._merge_textual_cols_by_position(
  335. context, cursor_description, result_columns
  336. )
  337. elif num_ctx_cols:
  338. # compiled SQL with a mismatch of description cols
  339. # vs. compiled cols, or textual w/ unordered columns
  340. # the order of columns can change if the query is
  341. # against a "select *", so not safe to cache
  342. self._safe_for_cache = False
  343. raw_iterator = self._merge_cols_by_name(
  344. context,
  345. cursor_description,
  346. result_columns,
  347. loose_column_name_matching,
  348. )
  349. else:
  350. # no compiled SQL, just a raw string, order of columns
  351. # can change for "select *"
  352. self._safe_for_cache = False
  353. raw_iterator = self._merge_cols_by_none(
  354. context, cursor_description
  355. )
  356. return [
  357. (
  358. idx,
  359. ridx,
  360. obj,
  361. cursor_colname,
  362. cursor_colname,
  363. context.get_result_processor(
  364. mapped_type, cursor_colname, coltype
  365. ),
  366. untranslated,
  367. )
  368. for (
  369. idx,
  370. ridx,
  371. cursor_colname,
  372. mapped_type,
  373. coltype,
  374. obj,
  375. untranslated,
  376. ) in raw_iterator
  377. ]
  378. def _colnames_from_description(self, context, cursor_description):
  379. """Extract column names and data types from a cursor.description.
  380. Applies unicode decoding, column translation, "normalization",
  381. and case sensitivity rules to the names based on the dialect.
  382. """
  383. dialect = context.dialect
  384. case_sensitive = dialect.case_sensitive
  385. translate_colname = context._translate_colname
  386. description_decoder = (
  387. dialect._description_decoder
  388. if dialect.description_encoding
  389. else None
  390. )
  391. normalize_name = (
  392. dialect.normalize_name if dialect.requires_name_normalize else None
  393. )
  394. untranslated = None
  395. self._keys = []
  396. for idx, rec in enumerate(cursor_description):
  397. colname = rec[0]
  398. coltype = rec[1]
  399. if description_decoder:
  400. colname = description_decoder(colname)
  401. if translate_colname:
  402. colname, untranslated = translate_colname(colname)
  403. if normalize_name:
  404. colname = normalize_name(colname)
  405. self._keys.append(colname)
  406. if not case_sensitive:
  407. colname = colname.lower()
  408. yield idx, colname, untranslated, coltype
  409. def _merge_textual_cols_by_position(
  410. self, context, cursor_description, result_columns
  411. ):
  412. num_ctx_cols = len(result_columns) if result_columns else None
  413. if num_ctx_cols > len(cursor_description):
  414. util.warn(
  415. "Number of columns in textual SQL (%d) is "
  416. "smaller than number of columns requested (%d)"
  417. % (num_ctx_cols, len(cursor_description))
  418. )
  419. seen = set()
  420. for (
  421. idx,
  422. colname,
  423. untranslated,
  424. coltype,
  425. ) in self._colnames_from_description(context, cursor_description):
  426. if idx < num_ctx_cols:
  427. ctx_rec = result_columns[idx]
  428. obj = ctx_rec[RM_OBJECTS]
  429. ridx = idx
  430. mapped_type = ctx_rec[RM_TYPE]
  431. if obj[0] in seen:
  432. raise exc.InvalidRequestError(
  433. "Duplicate column expression requested "
  434. "in textual SQL: %r" % obj[0]
  435. )
  436. seen.add(obj[0])
  437. else:
  438. mapped_type = sqltypes.NULLTYPE
  439. obj = None
  440. ridx = None
  441. yield idx, ridx, colname, mapped_type, coltype, obj, untranslated
  442. def _merge_cols_by_name(
  443. self,
  444. context,
  445. cursor_description,
  446. result_columns,
  447. loose_column_name_matching,
  448. ):
  449. dialect = context.dialect
  450. case_sensitive = dialect.case_sensitive
  451. match_map = self._create_description_match_map(
  452. result_columns, case_sensitive, loose_column_name_matching
  453. )
  454. for (
  455. idx,
  456. colname,
  457. untranslated,
  458. coltype,
  459. ) in self._colnames_from_description(context, cursor_description):
  460. try:
  461. ctx_rec = match_map[colname]
  462. except KeyError:
  463. mapped_type = sqltypes.NULLTYPE
  464. obj = None
  465. result_columns_idx = None
  466. else:
  467. obj = ctx_rec[1]
  468. mapped_type = ctx_rec[2]
  469. result_columns_idx = ctx_rec[3]
  470. yield (
  471. idx,
  472. result_columns_idx,
  473. colname,
  474. mapped_type,
  475. coltype,
  476. obj,
  477. untranslated,
  478. )
  479. @classmethod
  480. def _create_description_match_map(
  481. cls,
  482. result_columns,
  483. case_sensitive=True,
  484. loose_column_name_matching=False,
  485. ):
  486. """when matching cursor.description to a set of names that are present
  487. in a Compiled object, as is the case with TextualSelect, get all the
  488. names we expect might match those in cursor.description.
  489. """
  490. d = {}
  491. for ridx, elem in enumerate(result_columns):
  492. key = elem[RM_RENDERED_NAME]
  493. if not case_sensitive:
  494. key = key.lower()
  495. if key in d:
  496. # conflicting keyname - just add the column-linked objects
  497. # to the existing record. if there is a duplicate column
  498. # name in the cursor description, this will allow all of those
  499. # objects to raise an ambiguous column error
  500. e_name, e_obj, e_type, e_ridx = d[key]
  501. d[key] = e_name, e_obj + elem[RM_OBJECTS], e_type, ridx
  502. else:
  503. d[key] = (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx)
  504. if loose_column_name_matching:
  505. # when using a textual statement with an unordered set
  506. # of columns that line up, we are expecting the user
  507. # to be using label names in the SQL that match to the column
  508. # expressions. Enable more liberal matching for this case;
  509. # duplicate keys that are ambiguous will be fixed later.
  510. for r_key in elem[RM_OBJECTS]:
  511. d.setdefault(
  512. r_key,
  513. (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx),
  514. )
  515. return d
  516. def _merge_cols_by_none(self, context, cursor_description):
  517. for (
  518. idx,
  519. colname,
  520. untranslated,
  521. coltype,
  522. ) in self._colnames_from_description(context, cursor_description):
  523. yield (
  524. idx,
  525. None,
  526. colname,
  527. sqltypes.NULLTYPE,
  528. coltype,
  529. None,
  530. untranslated,
  531. )
  532. def _key_fallback(self, key, err, raiseerr=True):
  533. if raiseerr:
  534. util.raise_(
  535. exc.NoSuchColumnError(
  536. "Could not locate column in row for column '%s'"
  537. % util.string_or_unprintable(key)
  538. ),
  539. replace_context=err,
  540. )
  541. else:
  542. return None
  543. def _raise_for_ambiguous_column_name(self, rec):
  544. raise exc.InvalidRequestError(
  545. "Ambiguous column name '%s' in "
  546. "result set column descriptions" % rec[MD_LOOKUP_KEY]
  547. )
  548. def _index_for_key(self, key, raiseerr=True):
  549. # TODO: can consider pre-loading ints and negative ints
  550. # into _keymap - also no coverage here
  551. if isinstance(key, int):
  552. key = self._keys[key]
  553. try:
  554. rec = self._keymap[key]
  555. except KeyError as ke:
  556. rec = self._key_fallback(key, ke, raiseerr)
  557. if rec is None:
  558. return None
  559. index = rec[0]
  560. if index is None:
  561. self._raise_for_ambiguous_column_name(rec)
  562. return index
  563. def _indexes_for_keys(self, keys):
  564. try:
  565. return [self._keymap[key][0] for key in keys]
  566. except KeyError as ke:
  567. # ensure it raises
  568. CursorResultMetaData._key_fallback(self, ke.args[0], ke)
  569. def _metadata_for_keys(self, keys):
  570. for key in keys:
  571. if int in key.__class__.__mro__:
  572. key = self._keys[key]
  573. try:
  574. rec = self._keymap[key]
  575. except KeyError as ke:
  576. # ensure it raises
  577. CursorResultMetaData._key_fallback(self, ke.args[0], ke)
  578. index = rec[0]
  579. if index is None:
  580. self._raise_for_ambiguous_column_name(rec)
  581. yield rec
  582. def __getstate__(self):
  583. return {
  584. "_keymap": {
  585. key: (rec[MD_INDEX], rec[MD_RESULT_MAP_INDEX], _UNPICKLED, key)
  586. for key, rec in self._keymap.items()
  587. if isinstance(key, util.string_types + util.int_types)
  588. },
  589. "_keys": self._keys,
  590. "case_sensitive": self.case_sensitive,
  591. "_translated_indexes": self._translated_indexes,
  592. "_tuplefilter": self._tuplefilter,
  593. }
  594. def __setstate__(self, state):
  595. self._processors = [None for _ in range(len(state["_keys"]))]
  596. self._keymap = state["_keymap"]
  597. self._keymap_by_result_column_idx = {
  598. rec[MD_RESULT_MAP_INDEX]: rec for rec in self._keymap.values()
  599. }
  600. self._keys = state["_keys"]
  601. self.case_sensitive = state["case_sensitive"]
  602. if state["_translated_indexes"]:
  603. self._translated_indexes = state["_translated_indexes"]
  604. self._tuplefilter = tuplegetter(*self._translated_indexes)
  605. else:
  606. self._translated_indexes = self._tuplefilter = None
  607. class LegacyCursorResultMetaData(CursorResultMetaData):
  608. __slots__ = ()
  609. def _contains(self, value, row):
  610. key = value
  611. if key in self._keymap:
  612. util.warn_deprecated_20(
  613. "Using the 'in' operator to test for string or column "
  614. "keys, or integer indexes, in a :class:`.Row` object is "
  615. "deprecated and will "
  616. "be removed in a future release. "
  617. "Use the `Row._fields` or `Row._mapping` attribute, i.e. "
  618. "'key in row._fields'",
  619. )
  620. return True
  621. else:
  622. return self._key_fallback(key, None, False) is not None
  623. def _key_fallback(self, key, err, raiseerr=True):
  624. map_ = self._keymap
  625. result = None
  626. if isinstance(key, util.string_types):
  627. result = map_.get(key if self.case_sensitive else key.lower())
  628. elif isinstance(key, expression.ColumnElement):
  629. if (
  630. key._tq_label
  631. and (
  632. key._tq_label
  633. if self.case_sensitive
  634. else key._tq_label.lower()
  635. )
  636. in map_
  637. ):
  638. result = map_[
  639. key._tq_label
  640. if self.case_sensitive
  641. else key._tq_label.lower()
  642. ]
  643. elif (
  644. hasattr(key, "name")
  645. and (key.name if self.case_sensitive else key.name.lower())
  646. in map_
  647. ):
  648. # match is only on name.
  649. result = map_[
  650. key.name if self.case_sensitive else key.name.lower()
  651. ]
  652. # search extra hard to make sure this
  653. # isn't a column/label name overlap.
  654. # this check isn't currently available if the row
  655. # was unpickled.
  656. if result is not None and result[MD_OBJECTS] not in (
  657. None,
  658. _UNPICKLED,
  659. ):
  660. for obj in result[MD_OBJECTS]:
  661. if key._compare_name_for_result(obj):
  662. break
  663. else:
  664. result = None
  665. if result is not None:
  666. if result[MD_OBJECTS] is _UNPICKLED:
  667. util.warn_deprecated(
  668. "Retrieving row values using Column objects from a "
  669. "row that was unpickled is deprecated; adequate "
  670. "state cannot be pickled for this to be efficient. "
  671. "This usage will raise KeyError in a future release.",
  672. version="1.4",
  673. )
  674. else:
  675. util.warn_deprecated(
  676. "Retrieving row values using Column objects with only "
  677. "matching names as keys is deprecated, and will raise "
  678. "KeyError in a future release; only Column "
  679. "objects that are explicitly part of the statement "
  680. "object should be used.",
  681. version="1.4",
  682. )
  683. if result is None:
  684. if raiseerr:
  685. util.raise_(
  686. exc.NoSuchColumnError(
  687. "Could not locate column in row for column '%s'"
  688. % util.string_or_unprintable(key)
  689. ),
  690. replace_context=err,
  691. )
  692. else:
  693. return None
  694. else:
  695. map_[key] = result
  696. return result
  697. def _warn_for_nonint(self, key):
  698. util.warn_deprecated_20(
  699. "Using non-integer/slice indices on Row is deprecated and will "
  700. "be removed in version 2.0; please use row._mapping[<key>], or "
  701. "the mappings() accessor on the Result object.",
  702. stacklevel=4,
  703. )
  704. def _has_key(self, key):
  705. if key in self._keymap:
  706. return True
  707. else:
  708. return self._key_fallback(key, None, False) is not None
  709. class ResultFetchStrategy(object):
  710. """Define a fetching strategy for a result object.
  711. .. versionadded:: 1.4
  712. """
  713. __slots__ = ()
  714. alternate_cursor_description = None
  715. def soft_close(self, result, dbapi_cursor):
  716. raise NotImplementedError()
  717. def hard_close(self, result, dbapi_cursor):
  718. raise NotImplementedError()
  719. def yield_per(self, result, dbapi_cursor, num):
  720. return
  721. def fetchone(self, result, dbapi_cursor, hard_close=False):
  722. raise NotImplementedError()
  723. def fetchmany(self, result, dbapi_cursor, size=None):
  724. raise NotImplementedError()
  725. def fetchall(self, result):
  726. raise NotImplementedError()
  727. def handle_exception(self, result, dbapi_cursor, err):
  728. raise err
  729. class NoCursorFetchStrategy(ResultFetchStrategy):
  730. """Cursor strategy for a result that has no open cursor.
  731. There are two varieties of this strategy, one for DQL and one for
  732. DML (and also DDL), each of which represent a result that had a cursor
  733. but no longer has one.
  734. """
  735. __slots__ = ()
  736. def soft_close(self, result, dbapi_cursor):
  737. pass
  738. def hard_close(self, result, dbapi_cursor):
  739. pass
  740. def fetchone(self, result, dbapi_cursor, hard_close=False):
  741. return self._non_result(result, None)
  742. def fetchmany(self, result, dbapi_cursor, size=None):
  743. return self._non_result(result, [])
  744. def fetchall(self, result, dbapi_cursor):
  745. return self._non_result(result, [])
  746. def _non_result(self, result, default, err=None):
  747. raise NotImplementedError()
  748. class NoCursorDQLFetchStrategy(NoCursorFetchStrategy):
  749. """Cursor strategy for a DQL result that has no open cursor.
  750. This is a result set that can return rows, i.e. for a SELECT, or for an
  751. INSERT, UPDATE, DELETE that includes RETURNING. However it is in the state
  752. where the cursor is closed and no rows remain available. The owning result
  753. object may or may not be "hard closed", which determines if the fetch
  754. methods send empty results or raise for closed result.
  755. """
  756. __slots__ = ()
  757. def _non_result(self, result, default, err=None):
  758. if result.closed:
  759. util.raise_(
  760. exc.ResourceClosedError("This result object is closed."),
  761. replace_context=err,
  762. )
  763. else:
  764. return default
  765. _NO_CURSOR_DQL = NoCursorDQLFetchStrategy()
  766. class NoCursorDMLFetchStrategy(NoCursorFetchStrategy):
  767. """Cursor strategy for a DML result that has no open cursor.
  768. This is a result set that does not return rows, i.e. for an INSERT,
  769. UPDATE, DELETE that does not include RETURNING.
  770. """
  771. __slots__ = ()
  772. def _non_result(self, result, default, err=None):
  773. # we only expect to have a _NoResultMetaData() here right now.
  774. assert not result._metadata.returns_rows
  775. result._metadata._we_dont_return_rows(err)
  776. _NO_CURSOR_DML = NoCursorDMLFetchStrategy()
  777. class CursorFetchStrategy(ResultFetchStrategy):
  778. """Call fetch methods from a DBAPI cursor.
  779. Alternate versions of this class may instead buffer the rows from
  780. cursors or not use cursors at all.
  781. """
  782. __slots__ = ()
  783. def soft_close(self, result, dbapi_cursor):
  784. result.cursor_strategy = _NO_CURSOR_DQL
  785. def hard_close(self, result, dbapi_cursor):
  786. result.cursor_strategy = _NO_CURSOR_DQL
  787. def handle_exception(self, result, dbapi_cursor, err):
  788. result.connection._handle_dbapi_exception(
  789. err, None, None, dbapi_cursor, result.context
  790. )
  791. def yield_per(self, result, dbapi_cursor, num):
  792. result.cursor_strategy = BufferedRowCursorFetchStrategy(
  793. dbapi_cursor,
  794. {"max_row_buffer": num},
  795. initial_buffer=collections.deque(),
  796. growth_factor=0,
  797. )
  798. def fetchone(self, result, dbapi_cursor, hard_close=False):
  799. try:
  800. row = dbapi_cursor.fetchone()
  801. if row is None:
  802. result._soft_close(hard=hard_close)
  803. return row
  804. except BaseException as e:
  805. self.handle_exception(result, dbapi_cursor, e)
  806. def fetchmany(self, result, dbapi_cursor, size=None):
  807. try:
  808. if size is None:
  809. l = dbapi_cursor.fetchmany()
  810. else:
  811. l = dbapi_cursor.fetchmany(size)
  812. if not l:
  813. result._soft_close()
  814. return l
  815. except BaseException as e:
  816. self.handle_exception(result, dbapi_cursor, e)
  817. def fetchall(self, result, dbapi_cursor):
  818. try:
  819. rows = dbapi_cursor.fetchall()
  820. result._soft_close()
  821. return rows
  822. except BaseException as e:
  823. self.handle_exception(result, dbapi_cursor, e)
  824. _DEFAULT_FETCH = CursorFetchStrategy()
  825. class BufferedRowCursorFetchStrategy(CursorFetchStrategy):
  826. """A cursor fetch strategy with row buffering behavior.
  827. This strategy buffers the contents of a selection of rows
  828. before ``fetchone()`` is called. This is to allow the results of
  829. ``cursor.description`` to be available immediately, when
  830. interfacing with a DB-API that requires rows to be consumed before
  831. this information is available (currently psycopg2, when used with
  832. server-side cursors).
  833. The pre-fetching behavior fetches only one row initially, and then
  834. grows its buffer size by a fixed amount with each successive need
  835. for additional rows up the ``max_row_buffer`` size, which defaults
  836. to 1000::
  837. with psycopg2_engine.connect() as conn:
  838. result = conn.execution_options(
  839. stream_results=True, max_row_buffer=50
  840. ).execute(text("select * from table"))
  841. .. versionadded:: 1.4 ``max_row_buffer`` may now exceed 1000 rows.
  842. .. seealso::
  843. :ref:`psycopg2_execution_options`
  844. """
  845. __slots__ = ("_max_row_buffer", "_rowbuffer", "_bufsize", "_growth_factor")
  846. def __init__(
  847. self,
  848. dbapi_cursor,
  849. execution_options,
  850. growth_factor=5,
  851. initial_buffer=None,
  852. ):
  853. self._max_row_buffer = execution_options.get("max_row_buffer", 1000)
  854. if initial_buffer is not None:
  855. self._rowbuffer = initial_buffer
  856. else:
  857. self._rowbuffer = collections.deque(dbapi_cursor.fetchmany(1))
  858. self._growth_factor = growth_factor
  859. if growth_factor:
  860. self._bufsize = min(self._max_row_buffer, self._growth_factor)
  861. else:
  862. self._bufsize = self._max_row_buffer
  863. @classmethod
  864. def create(cls, result):
  865. return BufferedRowCursorFetchStrategy(
  866. result.cursor,
  867. result.context.execution_options,
  868. )
  869. def _buffer_rows(self, result, dbapi_cursor):
  870. """this is currently used only by fetchone()."""
  871. size = self._bufsize
  872. try:
  873. if size < 1:
  874. new_rows = dbapi_cursor.fetchall()
  875. else:
  876. new_rows = dbapi_cursor.fetchmany(size)
  877. except BaseException as e:
  878. self.handle_exception(result, dbapi_cursor, e)
  879. if not new_rows:
  880. return
  881. self._rowbuffer = collections.deque(new_rows)
  882. if self._growth_factor and size < self._max_row_buffer:
  883. self._bufsize = min(
  884. self._max_row_buffer, size * self._growth_factor
  885. )
  886. def yield_per(self, result, dbapi_cursor, num):
  887. self._growth_factor = 0
  888. self._max_row_buffer = self._bufsize = num
  889. def soft_close(self, result, dbapi_cursor):
  890. self._rowbuffer.clear()
  891. super(BufferedRowCursorFetchStrategy, self).soft_close(
  892. result, dbapi_cursor
  893. )
  894. def hard_close(self, result, dbapi_cursor):
  895. self._rowbuffer.clear()
  896. super(BufferedRowCursorFetchStrategy, self).hard_close(
  897. result, dbapi_cursor
  898. )
  899. def fetchone(self, result, dbapi_cursor, hard_close=False):
  900. if not self._rowbuffer:
  901. self._buffer_rows(result, dbapi_cursor)
  902. if not self._rowbuffer:
  903. try:
  904. result._soft_close(hard=hard_close)
  905. except BaseException as e:
  906. self.handle_exception(result, dbapi_cursor, e)
  907. return None
  908. return self._rowbuffer.popleft()
  909. def fetchmany(self, result, dbapi_cursor, size=None):
  910. if size is None:
  911. return self.fetchall(result, dbapi_cursor)
  912. buf = list(self._rowbuffer)
  913. lb = len(buf)
  914. if size > lb:
  915. try:
  916. new = dbapi_cursor.fetchmany(size - lb)
  917. except BaseException as e:
  918. self.handle_exception(result, dbapi_cursor, e)
  919. else:
  920. if not new:
  921. result._soft_close()
  922. else:
  923. buf.extend(new)
  924. result = buf[0:size]
  925. self._rowbuffer = collections.deque(buf[size:])
  926. return result
  927. def fetchall(self, result, dbapi_cursor):
  928. try:
  929. ret = list(self._rowbuffer) + list(dbapi_cursor.fetchall())
  930. self._rowbuffer.clear()
  931. result._soft_close()
  932. return ret
  933. except BaseException as e:
  934. self.handle_exception(result, dbapi_cursor, e)
  935. class FullyBufferedCursorFetchStrategy(CursorFetchStrategy):
  936. """A cursor strategy that buffers rows fully upon creation.
  937. Used for operations where a result is to be delivered
  938. after the database conversation can not be continued,
  939. such as MSSQL INSERT...OUTPUT after an autocommit.
  940. """
  941. __slots__ = ("_rowbuffer", "alternate_cursor_description")
  942. def __init__(
  943. self, dbapi_cursor, alternate_description=None, initial_buffer=None
  944. ):
  945. self.alternate_cursor_description = alternate_description
  946. if initial_buffer is not None:
  947. self._rowbuffer = collections.deque(initial_buffer)
  948. else:
  949. self._rowbuffer = collections.deque(dbapi_cursor.fetchall())
  950. def yield_per(self, result, dbapi_cursor, num):
  951. pass
  952. def soft_close(self, result, dbapi_cursor):
  953. self._rowbuffer.clear()
  954. super(FullyBufferedCursorFetchStrategy, self).soft_close(
  955. result, dbapi_cursor
  956. )
  957. def hard_close(self, result, dbapi_cursor):
  958. self._rowbuffer.clear()
  959. super(FullyBufferedCursorFetchStrategy, self).hard_close(
  960. result, dbapi_cursor
  961. )
  962. def fetchone(self, result, dbapi_cursor, hard_close=False):
  963. if self._rowbuffer:
  964. return self._rowbuffer.popleft()
  965. else:
  966. result._soft_close(hard=hard_close)
  967. return None
  968. def fetchmany(self, result, dbapi_cursor, size=None):
  969. if size is None:
  970. return self.fetchall(result, dbapi_cursor)
  971. buf = list(self._rowbuffer)
  972. rows = buf[0:size]
  973. self._rowbuffer = collections.deque(buf[size:])
  974. if not rows:
  975. result._soft_close()
  976. return rows
  977. def fetchall(self, result, dbapi_cursor):
  978. ret = self._rowbuffer
  979. self._rowbuffer = collections.deque()
  980. result._soft_close()
  981. return ret
  982. class _NoResultMetaData(ResultMetaData):
  983. __slots__ = ()
  984. returns_rows = False
  985. def _we_dont_return_rows(self, err=None):
  986. util.raise_(
  987. exc.ResourceClosedError(
  988. "This result object does not return rows. "
  989. "It has been closed automatically."
  990. ),
  991. replace_context=err,
  992. )
  993. def _index_for_key(self, keys, raiseerr):
  994. self._we_dont_return_rows()
  995. def _metadata_for_keys(self, key):
  996. self._we_dont_return_rows()
  997. def _reduce(self, keys):
  998. self._we_dont_return_rows()
  999. @property
  1000. def _keymap(self):
  1001. self._we_dont_return_rows()
  1002. @property
  1003. def keys(self):
  1004. self._we_dont_return_rows()
  1005. class _LegacyNoResultMetaData(_NoResultMetaData):
  1006. @property
  1007. def keys(self):
  1008. util.warn_deprecated_20(
  1009. "Calling the .keys() method on a result set that does not return "
  1010. "rows is deprecated and will raise ResourceClosedError in "
  1011. "SQLAlchemy 2.0.",
  1012. )
  1013. return []
  1014. _NO_RESULT_METADATA = _NoResultMetaData()
  1015. _LEGACY_NO_RESULT_METADATA = _LegacyNoResultMetaData()
  1016. class BaseCursorResult(object):
  1017. """Base class for database result objects."""
  1018. out_parameters = None
  1019. _metadata = None
  1020. _soft_closed = False
  1021. closed = False
  1022. def __init__(self, context, cursor_strategy, cursor_description):
  1023. self.context = context
  1024. self.dialect = context.dialect
  1025. self.cursor = context.cursor
  1026. self.cursor_strategy = cursor_strategy
  1027. self.connection = context.root_connection
  1028. self._echo = echo = (
  1029. self.connection._echo and context.engine._should_log_debug()
  1030. )
  1031. if cursor_description is not None:
  1032. # inline of Result._row_getter(), set up an initial row
  1033. # getter assuming no transformations will be called as this
  1034. # is the most common case
  1035. if echo:
  1036. log = self.context.connection._log_debug
  1037. def log_row(row):
  1038. log("Row %r", sql_util._repr_row(row))
  1039. return row
  1040. self._row_logging_fn = log_row
  1041. else:
  1042. log_row = None
  1043. metadata = self._init_metadata(context, cursor_description)
  1044. keymap = metadata._keymap
  1045. processors = metadata._processors
  1046. process_row = self._process_row
  1047. key_style = process_row._default_key_style
  1048. _make_row = functools.partial(
  1049. process_row, metadata, processors, keymap, key_style
  1050. )
  1051. if log_row:
  1052. def make_row(row):
  1053. made_row = _make_row(row)
  1054. log_row(made_row)
  1055. return made_row
  1056. else:
  1057. make_row = _make_row
  1058. self._set_memoized_attribute("_row_getter", make_row)
  1059. else:
  1060. self._metadata = self._no_result_metadata
  1061. def _init_metadata(self, context, cursor_description):
  1062. if context.compiled:
  1063. if context.compiled._cached_metadata:
  1064. metadata = self.context.compiled._cached_metadata
  1065. else:
  1066. metadata = self._cursor_metadata(self, cursor_description)
  1067. if metadata._safe_for_cache:
  1068. context.compiled._cached_metadata = metadata
  1069. # result rewrite/ adapt step. this is to suit the case
  1070. # when we are invoked against a cached Compiled object, we want
  1071. # to rewrite the ResultMetaData to reflect the Column objects
  1072. # that are in our current SQL statement object, not the one
  1073. # that is associated with the cached Compiled object.
  1074. # the Compiled object may also tell us to not
  1075. # actually do this step; this is to support the ORM where
  1076. # it is to produce a new Result object in any case, and will
  1077. # be using the cached Column objects against this database result
  1078. # so we don't want to rewrite them.
  1079. #
  1080. # Basically this step suits the use case where the end user
  1081. # is using Core SQL expressions and is accessing columns in the
  1082. # result row using row._mapping[table.c.column].
  1083. compiled = context.compiled
  1084. if (
  1085. compiled
  1086. and compiled._result_columns
  1087. and context.cache_hit is context.dialect.CACHE_HIT
  1088. and not context.execution_options.get(
  1089. "_result_disable_adapt_to_context", False
  1090. )
  1091. and compiled.statement is not context.invoked_statement
  1092. ):
  1093. metadata = metadata._adapt_to_context(context)
  1094. self._metadata = metadata
  1095. else:
  1096. self._metadata = metadata = self._cursor_metadata(
  1097. self, cursor_description
  1098. )
  1099. if self._echo:
  1100. context.connection._log_debug(
  1101. "Col %r", tuple(x[0] for x in cursor_description)
  1102. )
  1103. return metadata
  1104. def _soft_close(self, hard=False):
  1105. """Soft close this :class:`_engine.CursorResult`.
  1106. This releases all DBAPI cursor resources, but leaves the
  1107. CursorResult "open" from a semantic perspective, meaning the
  1108. fetchXXX() methods will continue to return empty results.
  1109. This method is called automatically when:
  1110. * all result rows are exhausted using the fetchXXX() methods.
  1111. * cursor.description is None.
  1112. This method is **not public**, but is documented in order to clarify
  1113. the "autoclose" process used.
  1114. .. versionadded:: 1.0.0
  1115. .. seealso::
  1116. :meth:`_engine.CursorResult.close`
  1117. """
  1118. if (not hard and self._soft_closed) or (hard and self.closed):
  1119. return
  1120. if hard:
  1121. self.closed = True
  1122. self.cursor_strategy.hard_close(self, self.cursor)
  1123. else:
  1124. self.cursor_strategy.soft_close(self, self.cursor)
  1125. if not self._soft_closed:
  1126. cursor = self.cursor
  1127. self.cursor = None
  1128. self.connection._safe_close_cursor(cursor)
  1129. self._soft_closed = True
  1130. @property
  1131. def inserted_primary_key_rows(self):
  1132. """Return the value of :attr:`_engine.CursorResult.inserted_primary_key`
  1133. as a row contained within a list; some dialects may support a
  1134. multiple row form as well.
  1135. .. note:: As indicated below, in current SQLAlchemy versions this
  1136. accessor is only useful beyond what's already supplied by
  1137. :attr:`_engine.CursorResult.inserted_primary_key` when using the
  1138. :ref:`postgresql_psycopg2` dialect. Future versions hope to
  1139. generalize this feature to more dialects.
  1140. This accessor is added to support dialects that offer the feature
  1141. that is currently implemented by the :ref:`psycopg2_executemany_mode`
  1142. feature, currently **only the psycopg2 dialect**, which provides
  1143. for many rows to be INSERTed at once while still retaining the
  1144. behavior of being able to return server-generated primary key values.
  1145. * **When using the psycopg2 dialect, or other dialects that may support
  1146. "fast executemany" style inserts in upcoming releases** : When
  1147. invoking an INSERT statement while passing a list of rows as the
  1148. second argument to :meth:`_engine.Connection.execute`, this accessor
  1149. will then provide a list of rows, where each row contains the primary
  1150. key value for each row that was INSERTed.
  1151. * **When using all other dialects / backends that don't yet support
  1152. this feature**: This accessor is only useful for **single row INSERT
  1153. statements**, and returns the same information as that of the
  1154. :attr:`_engine.CursorResult.inserted_primary_key` within a
  1155. single-element list. When an INSERT statement is executed in
  1156. conjunction with a list of rows to be INSERTed, the list will contain
  1157. one row per row inserted in the statement, however it will contain
  1158. ``None`` for any server-generated values.
  1159. Future releases of SQLAlchemy will further generalize the
  1160. "fast execution helper" feature of psycopg2 to suit other dialects,
  1161. thus allowing this accessor to be of more general use.
  1162. .. versionadded:: 1.4
  1163. .. seealso::
  1164. :attr:`_engine.CursorResult.inserted_primary_key`
  1165. """
  1166. if not self.context.compiled:
  1167. raise exc.InvalidRequestError(
  1168. "Statement is not a compiled " "expression construct."
  1169. )
  1170. elif not self.context.isinsert:
  1171. raise exc.InvalidRequestError(
  1172. "Statement is not an insert() " "expression construct."
  1173. )
  1174. elif self.context._is_explicit_returning:
  1175. raise exc.InvalidRequestError(
  1176. "Can't call inserted_primary_key "
  1177. "when returning() "
  1178. "is used."
  1179. )
  1180. return self.context.inserted_primary_key_rows
  1181. @property
  1182. def inserted_primary_key(self):
  1183. """Return the primary key for the row just inserted.
  1184. The return value is a :class:`_result.Row` object representing
  1185. a named tuple of primary key values in the order in which the
  1186. primary key columns are configured in the source
  1187. :class:`_schema.Table`.
  1188. .. versionchanged:: 1.4.8 - the
  1189. :attr:`_engine.CursorResult.inserted_primary_key`
  1190. value is now a named tuple via the :class:`_result.Row` class,
  1191. rather than a plain tuple.
  1192. This accessor only applies to single row :func:`_expression.insert`
  1193. constructs which did not explicitly specify
  1194. :meth:`_expression.Insert.returning`. Support for multirow inserts,
  1195. while not yet available for most backends, would be accessed using
  1196. the :attr:`_engine.CursorResult.inserted_primary_key_rows` accessor.
  1197. Note that primary key columns which specify a server_default clause, or
  1198. otherwise do not qualify as "autoincrement" columns (see the notes at
  1199. :class:`_schema.Column`), and were generated using the database-side
  1200. default, will appear in this list as ``None`` unless the backend
  1201. supports "returning" and the insert statement executed with the
  1202. "implicit returning" enabled.
  1203. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1204. statement is not a compiled expression construct
  1205. or is not an insert() construct.
  1206. """
  1207. if self.context.executemany:
  1208. raise exc.InvalidRequestError(
  1209. "This statement was an executemany call; if primary key "
  1210. "returning is supported, please "
  1211. "use .inserted_primary_key_rows."
  1212. )
  1213. ikp = self.inserted_primary_key_rows
  1214. if ikp:
  1215. return ikp[0]
  1216. else:
  1217. return None
  1218. def last_updated_params(self):
  1219. """Return the collection of updated parameters from this
  1220. execution.
  1221. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1222. statement is not a compiled expression construct
  1223. or is not an update() construct.
  1224. """
  1225. if not self.context.compiled:
  1226. raise exc.InvalidRequestError(
  1227. "Statement is not a compiled " "expression construct."
  1228. )
  1229. elif not self.context.isupdate:
  1230. raise exc.InvalidRequestError(
  1231. "Statement is not an update() " "expression construct."
  1232. )
  1233. elif self.context.executemany:
  1234. return self.context.compiled_parameters
  1235. else:
  1236. return self.context.compiled_parameters[0]
  1237. def last_inserted_params(self):
  1238. """Return the collection of inserted parameters from this
  1239. execution.
  1240. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1241. statement is not a compiled expression construct
  1242. or is not an insert() construct.
  1243. """
  1244. if not self.context.compiled:
  1245. raise exc.InvalidRequestError(
  1246. "Statement is not a compiled " "expression construct."
  1247. )
  1248. elif not self.context.isinsert:
  1249. raise exc.InvalidRequestError(
  1250. "Statement is not an insert() " "expression construct."
  1251. )
  1252. elif self.context.executemany:
  1253. return self.context.compiled_parameters
  1254. else:
  1255. return self.context.compiled_parameters[0]
  1256. @property
  1257. def returned_defaults_rows(self):
  1258. """Return a list of rows each containing the values of default
  1259. columns that were fetched using
  1260. the :meth:`.ValuesBase.return_defaults` feature.
  1261. The return value is a list of :class:`.Row` objects.
  1262. .. versionadded:: 1.4
  1263. """
  1264. return self.context.returned_default_rows
  1265. @property
  1266. def returned_defaults(self):
  1267. """Return the values of default columns that were fetched using
  1268. the :meth:`.ValuesBase.return_defaults` feature.
  1269. The value is an instance of :class:`.Row`, or ``None``
  1270. if :meth:`.ValuesBase.return_defaults` was not used or if the
  1271. backend does not support RETURNING.
  1272. .. versionadded:: 0.9.0
  1273. .. seealso::
  1274. :meth:`.ValuesBase.return_defaults`
  1275. """
  1276. if self.context.executemany:
  1277. raise exc.InvalidRequestError(
  1278. "This statement was an executemany call; if return defaults "
  1279. "is supported, please use .returned_defaults_rows."
  1280. )
  1281. rows = self.context.returned_default_rows
  1282. if rows:
  1283. return rows[0]
  1284. else:
  1285. return None
  1286. def lastrow_has_defaults(self):
  1287. """Return ``lastrow_has_defaults()`` from the underlying
  1288. :class:`.ExecutionContext`.
  1289. See :class:`.ExecutionContext` for details.
  1290. """
  1291. return self.context.lastrow_has_defaults()
  1292. def postfetch_cols(self):
  1293. """Return ``postfetch_cols()`` from the underlying
  1294. :class:`.ExecutionContext`.
  1295. See :class:`.ExecutionContext` for details.
  1296. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1297. statement is not a compiled expression construct
  1298. or is not an insert() or update() construct.
  1299. """
  1300. if not self.context.compiled:
  1301. raise exc.InvalidRequestError(
  1302. "Statement is not a compiled " "expression construct."
  1303. )
  1304. elif not self.context.isinsert and not self.context.isupdate:
  1305. raise exc.InvalidRequestError(
  1306. "Statement is not an insert() or update() "
  1307. "expression construct."
  1308. )
  1309. return self.context.postfetch_cols
  1310. def prefetch_cols(self):
  1311. """Return ``prefetch_cols()`` from the underlying
  1312. :class:`.ExecutionContext`.
  1313. See :class:`.ExecutionContext` for details.
  1314. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1315. statement is not a compiled expression construct
  1316. or is not an insert() or update() construct.
  1317. """
  1318. if not self.context.compiled:
  1319. raise exc.InvalidRequestError(
  1320. "Statement is not a compiled " "expression construct."
  1321. )
  1322. elif not self.context.isinsert and not self.context.isupdate:
  1323. raise exc.InvalidRequestError(
  1324. "Statement is not an insert() or update() "
  1325. "expression construct."
  1326. )
  1327. return self.context.prefetch_cols
  1328. def supports_sane_rowcount(self):
  1329. """Return ``supports_sane_rowcount`` from the dialect.
  1330. See :attr:`_engine.CursorResult.rowcount` for background.
  1331. """
  1332. return self.dialect.supports_sane_rowcount
  1333. def supports_sane_multi_rowcount(self):
  1334. """Return ``supports_sane_multi_rowcount`` from the dialect.
  1335. See :attr:`_engine.CursorResult.rowcount` for background.
  1336. """
  1337. return self.dialect.supports_sane_multi_rowcount
  1338. @util.memoized_property
  1339. def rowcount(self):
  1340. """Return the 'rowcount' for this result.
  1341. The 'rowcount' reports the number of rows *matched*
  1342. by the WHERE criterion of an UPDATE or DELETE statement.
  1343. .. note::
  1344. Notes regarding :attr:`_engine.CursorResult.rowcount`:
  1345. * This attribute returns the number of rows *matched*,
  1346. which is not necessarily the same as the number of rows
  1347. that were actually *modified* - an UPDATE statement, for example,
  1348. may have no net change on a given row if the SET values
  1349. given are the same as those present in the row already.
  1350. Such a row would be matched but not modified.
  1351. On backends that feature both styles, such as MySQL,
  1352. rowcount is configured by default to return the match
  1353. count in all cases.
  1354. * :attr:`_engine.CursorResult.rowcount`
  1355. is *only* useful in conjunction
  1356. with an UPDATE or DELETE statement. Contrary to what the Python
  1357. DBAPI says, it does *not* return the
  1358. number of rows available from the results of a SELECT statement
  1359. as DBAPIs cannot support this functionality when rows are
  1360. unbuffered.
  1361. * :attr:`_engine.CursorResult.rowcount`
  1362. may not be fully implemented by
  1363. all dialects. In particular, most DBAPIs do not support an
  1364. aggregate rowcount result from an executemany call.
  1365. The :meth:`_engine.CursorResult.supports_sane_rowcount` and
  1366. :meth:`_engine.CursorResult.supports_sane_multi_rowcount` methods
  1367. will report from the dialect if each usage is known to be
  1368. supported.
  1369. * Statements that use RETURNING may not return a correct
  1370. rowcount.
  1371. .. seealso::
  1372. :ref:`tutorial_update_delete_rowcount` - in the :ref:`unified_tutorial`
  1373. """ # noqa E501
  1374. try:
  1375. return self.context.rowcount
  1376. except BaseException as e:
  1377. self.cursor_strategy.handle_exception(self, self.cursor, e)
  1378. @property
  1379. def lastrowid(self):
  1380. """Return the 'lastrowid' accessor on the DBAPI cursor.
  1381. This is a DBAPI specific method and is only functional
  1382. for those backends which support it, for statements
  1383. where it is appropriate. It's behavior is not
  1384. consistent across backends.
  1385. Usage of this method is normally unnecessary when
  1386. using insert() expression constructs; the
  1387. :attr:`~CursorResult.inserted_primary_key` attribute provides a
  1388. tuple of primary key values for a newly inserted row,
  1389. regardless of database backend.
  1390. """
  1391. try:
  1392. return self.context.get_lastrowid()
  1393. except BaseException as e:
  1394. self.cursor_strategy.handle_exception(self, self.cursor, e)
  1395. @property
  1396. def returns_rows(self):
  1397. """True if this :class:`_engine.CursorResult` returns zero or more rows.
  1398. I.e. if it is legal to call the methods
  1399. :meth:`_engine.CursorResult.fetchone`,
  1400. :meth:`_engine.CursorResult.fetchmany`
  1401. :meth:`_engine.CursorResult.fetchall`.
  1402. Overall, the value of :attr:`_engine.CursorResult.returns_rows` should
  1403. always be synonymous with whether or not the DBAPI cursor had a
  1404. ``.description`` attribute, indicating the presence of result columns,
  1405. noting that a cursor that returns zero rows still has a
  1406. ``.description`` if a row-returning statement was emitted.
  1407. This attribute should be True for all results that are against
  1408. SELECT statements, as well as for DML statements INSERT/UPDATE/DELETE
  1409. that use RETURNING. For INSERT/UPDATE/DELETE statements that were
  1410. not using RETURNING, the value will usually be False, however
  1411. there are some dialect-specific exceptions to this, such as when
  1412. using the MSSQL / pyodbc dialect a SELECT is emitted inline in
  1413. order to retrieve an inserted primary key value.
  1414. """
  1415. return self._metadata.returns_rows
  1416. @property
  1417. def is_insert(self):
  1418. """True if this :class:`_engine.CursorResult` is the result
  1419. of a executing an expression language compiled
  1420. :func:`_expression.insert` construct.
  1421. When True, this implies that the
  1422. :attr:`inserted_primary_key` attribute is accessible,
  1423. assuming the statement did not include
  1424. a user defined "returning" construct.
  1425. """
  1426. return self.context.isinsert
  1427. class CursorResult(BaseCursorResult, Result):
  1428. """A Result that is representing state from a DBAPI cursor.
  1429. .. versionchanged:: 1.4 The :class:`.CursorResult` and
  1430. :class:`.LegacyCursorResult`
  1431. classes replace the previous :class:`.ResultProxy` interface.
  1432. These classes are based on the :class:`.Result` calling API
  1433. which provides an updated usage model and calling facade for
  1434. SQLAlchemy Core and SQLAlchemy ORM.
  1435. Returns database rows via the :class:`.Row` class, which provides
  1436. additional API features and behaviors on top of the raw data returned by
  1437. the DBAPI. Through the use of filters such as the :meth:`.Result.scalars`
  1438. method, other kinds of objects may also be returned.
  1439. Within the scope of the 1.x series of SQLAlchemy, Core SQL results in
  1440. version 1.4 return an instance of :class:`._engine.LegacyCursorResult`
  1441. which takes the place of the ``CursorResult`` class used for the 1.3 series
  1442. and previously. This object returns rows as :class:`.LegacyRow` objects,
  1443. which maintains Python mapping (i.e. dictionary) like behaviors upon the
  1444. object itself. Going forward, the :attr:`.Row._mapping` attribute should
  1445. be used for dictionary behaviors.
  1446. .. seealso::
  1447. :ref:`coretutorial_selecting` - introductory material for accessing
  1448. :class:`_engine.CursorResult` and :class:`.Row` objects.
  1449. """
  1450. _cursor_metadata = CursorResultMetaData
  1451. _cursor_strategy_cls = CursorFetchStrategy
  1452. _no_result_metadata = _NO_RESULT_METADATA
  1453. def _fetchiter_impl(self):
  1454. fetchone = self.cursor_strategy.fetchone
  1455. while True:
  1456. row = fetchone(self, self.cursor)
  1457. if row is None:
  1458. break
  1459. yield row
  1460. def _fetchone_impl(self, hard_close=False):
  1461. return self.cursor_strategy.fetchone(self, self.cursor, hard_close)
  1462. def _fetchall_impl(self):
  1463. return self.cursor_strategy.fetchall(self, self.cursor)
  1464. def _fetchmany_impl(self, size=None):
  1465. return self.cursor_strategy.fetchmany(self, self.cursor, size)
  1466. def _raw_row_iterator(self):
  1467. return self._fetchiter_impl()
  1468. def merge(self, *others):
  1469. merged_result = super(CursorResult, self).merge(*others)
  1470. setup_rowcounts = not self._metadata.returns_rows
  1471. if setup_rowcounts:
  1472. merged_result.rowcount = sum(
  1473. result.rowcount for result in (self,) + others
  1474. )
  1475. return merged_result
  1476. def close(self):
  1477. """Close this :class:`_engine.CursorResult`.
  1478. This closes out the underlying DBAPI cursor corresponding to the
  1479. statement execution, if one is still present. Note that the DBAPI
  1480. cursor is automatically released when the :class:`_engine.CursorResult`
  1481. exhausts all available rows. :meth:`_engine.CursorResult.close` is
  1482. generally an optional method except in the case when discarding a
  1483. :class:`_engine.CursorResult` that still has additional rows pending
  1484. for fetch.
  1485. After this method is called, it is no longer valid to call upon
  1486. the fetch methods, which will raise a :class:`.ResourceClosedError`
  1487. on subsequent use.
  1488. .. seealso::
  1489. :ref:`connections_toplevel`
  1490. """
  1491. self._soft_close(hard=True)
  1492. @_generative
  1493. def yield_per(self, num):
  1494. self._yield_per = num
  1495. self.cursor_strategy.yield_per(self, self.cursor, num)
  1496. class LegacyCursorResult(CursorResult):
  1497. """Legacy version of :class:`.CursorResult`.
  1498. This class includes connection "connection autoclose" behavior for use with
  1499. "connectionless" execution, as well as delivers rows using the
  1500. :class:`.LegacyRow` row implementation.
  1501. .. versionadded:: 1.4
  1502. """
  1503. _autoclose_connection = False
  1504. _process_row = LegacyRow
  1505. _cursor_metadata = LegacyCursorResultMetaData
  1506. _cursor_strategy_cls = CursorFetchStrategy
  1507. _no_result_metadata = _LEGACY_NO_RESULT_METADATA
  1508. def close(self):
  1509. """Close this :class:`_engine.LegacyCursorResult`.
  1510. This method has the same behavior as that of
  1511. :meth:`._engine.CursorResult`, but it also may close
  1512. the underlying :class:`.Connection` for the case of "connectionless"
  1513. execution.
  1514. .. deprecated:: 2.0 "connectionless" execution is deprecated and will
  1515. be removed in version 2.0. Version 2.0 will feature the
  1516. :class:`_future.Result`
  1517. object that will no longer affect the status
  1518. of the originating connection in any case.
  1519. After this method is called, it is no longer valid to call upon
  1520. the fetch methods, which will raise a :class:`.ResourceClosedError`
  1521. on subsequent use.
  1522. .. seealso::
  1523. :ref:`connections_toplevel`
  1524. :ref:`dbengine_implicit`
  1525. """
  1526. self._soft_close(hard=True)
  1527. def _soft_close(self, hard=False):
  1528. soft_closed = self._soft_closed
  1529. super(LegacyCursorResult, self)._soft_close(hard=hard)
  1530. if (
  1531. not soft_closed
  1532. and self._soft_closed
  1533. and self._autoclose_connection
  1534. ):
  1535. self.connection.close()
  1536. ResultProxy = LegacyCursorResult
  1537. class BufferedRowResultProxy(ResultProxy):
  1538. """A ResultProxy with row buffering behavior.
  1539. .. deprecated:: 1.4 this class is now supplied using a strategy object.
  1540. See :class:`.BufferedRowCursorFetchStrategy`.
  1541. """
  1542. _cursor_strategy_cls = BufferedRowCursorFetchStrategy
  1543. class FullyBufferedResultProxy(ResultProxy):
  1544. """A result proxy that buffers rows fully upon creation.
  1545. .. deprecated:: 1.4 this class is now supplied using a strategy object.
  1546. See :class:`.FullyBufferedCursorFetchStrategy`.
  1547. """
  1548. _cursor_strategy_cls = FullyBufferedCursorFetchStrategy
  1549. class BufferedColumnRow(LegacyRow):
  1550. """Row is now BufferedColumn in all cases"""
  1551. class BufferedColumnResultProxy(ResultProxy):
  1552. """A ResultProxy with column buffering behavior.
  1553. .. versionchanged:: 1.4 This is now the default behavior of the Row
  1554. and this class does not change behavior in any way.
  1555. """
  1556. _process_row = BufferedColumnRow