cursor.py 67 KB

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