Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1929 lignes
66KB

  1. # engine/cursor.py
  2. # Copyright (C) 2005-2021 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: http://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._label
  631. and (key._label if self.case_sensitive else key._label.lower())
  632. in map_
  633. ):
  634. result = map_[
  635. key._label if self.case_sensitive else key._label.lower()
  636. ]
  637. elif (
  638. hasattr(key, "name")
  639. and (key.name if self.case_sensitive else key.name.lower())
  640. in map_
  641. ):
  642. # match is only on name.
  643. result = map_[
  644. key.name if self.case_sensitive else key.name.lower()
  645. ]
  646. # search extra hard to make sure this
  647. # isn't a column/label name overlap.
  648. # this check isn't currently available if the row
  649. # was unpickled.
  650. if result is not None and result[MD_OBJECTS] not in (
  651. None,
  652. _UNPICKLED,
  653. ):
  654. for obj in result[MD_OBJECTS]:
  655. if key._compare_name_for_result(obj):
  656. break
  657. else:
  658. result = None
  659. if result is not None:
  660. if result[MD_OBJECTS] is _UNPICKLED:
  661. util.warn_deprecated(
  662. "Retrieving row values using Column objects from a "
  663. "row that was unpickled is deprecated; adequate "
  664. "state cannot be pickled for this to be efficient. "
  665. "This usage will raise KeyError in a future release.",
  666. version="1.4",
  667. )
  668. else:
  669. util.warn_deprecated(
  670. "Retrieving row values using Column objects with only "
  671. "matching names as keys is deprecated, and will raise "
  672. "KeyError in a future release; only Column "
  673. "objects that are explicitly part of the statement "
  674. "object should be used.",
  675. version="1.4",
  676. )
  677. if result is None:
  678. if raiseerr:
  679. util.raise_(
  680. exc.NoSuchColumnError(
  681. "Could not locate column in row for column '%s'"
  682. % util.string_or_unprintable(key)
  683. ),
  684. replace_context=err,
  685. )
  686. else:
  687. return None
  688. else:
  689. map_[key] = result
  690. return result
  691. def _warn_for_nonint(self, key):
  692. util.warn_deprecated_20(
  693. "Using non-integer/slice indices on Row is deprecated and will "
  694. "be removed in version 2.0; please use row._mapping[<key>], or "
  695. "the mappings() accessor on the Result object.",
  696. stacklevel=4,
  697. )
  698. def _has_key(self, key):
  699. if key in self._keymap:
  700. return True
  701. else:
  702. return self._key_fallback(key, None, False) is not None
  703. class ResultFetchStrategy(object):
  704. """Define a fetching strategy for a result object.
  705. .. versionadded:: 1.4
  706. """
  707. __slots__ = ()
  708. alternate_cursor_description = None
  709. def soft_close(self, result, dbapi_cursor):
  710. raise NotImplementedError()
  711. def hard_close(self, result, dbapi_cursor):
  712. raise NotImplementedError()
  713. def yield_per(self, result, dbapi_cursor, num):
  714. return
  715. def fetchone(self, result, dbapi_cursor, hard_close=False):
  716. raise NotImplementedError()
  717. def fetchmany(self, result, dbapi_cursor, size=None):
  718. raise NotImplementedError()
  719. def fetchall(self, result):
  720. raise NotImplementedError()
  721. def handle_exception(self, result, dbapi_cursor, err):
  722. raise err
  723. class NoCursorFetchStrategy(ResultFetchStrategy):
  724. """Cursor strategy for a result that has no open cursor.
  725. There are two varieties of this strategy, one for DQL and one for
  726. DML (and also DDL), each of which represent a result that had a cursor
  727. but no longer has one.
  728. """
  729. __slots__ = ()
  730. def soft_close(self, result, dbapi_cursor):
  731. pass
  732. def hard_close(self, result, dbapi_cursor):
  733. pass
  734. def fetchone(self, result, dbapi_cursor, hard_close=False):
  735. return self._non_result(result, None)
  736. def fetchmany(self, result, dbapi_cursor, size=None):
  737. return self._non_result(result, [])
  738. def fetchall(self, result, dbapi_cursor):
  739. return self._non_result(result, [])
  740. def _non_result(self, result, default, err=None):
  741. raise NotImplementedError()
  742. class NoCursorDQLFetchStrategy(NoCursorFetchStrategy):
  743. """Cursor strategy for a DQL result that has no open cursor.
  744. This is a result set that can return rows, i.e. for a SELECT, or for an
  745. INSERT, UPDATE, DELETE that includes RETURNING. However it is in the state
  746. where the cursor is closed and no rows remain available. The owning result
  747. object may or may not be "hard closed", which determines if the fetch
  748. methods send empty results or raise for closed result.
  749. """
  750. __slots__ = ()
  751. def _non_result(self, result, default, err=None):
  752. if result.closed:
  753. util.raise_(
  754. exc.ResourceClosedError("This result object is closed."),
  755. replace_context=err,
  756. )
  757. else:
  758. return default
  759. _NO_CURSOR_DQL = NoCursorDQLFetchStrategy()
  760. class NoCursorDMLFetchStrategy(NoCursorFetchStrategy):
  761. """Cursor strategy for a DML result that has no open cursor.
  762. This is a result set that does not return rows, i.e. for an INSERT,
  763. UPDATE, DELETE that does not include RETURNING.
  764. """
  765. __slots__ = ()
  766. def _non_result(self, result, default, err=None):
  767. # we only expect to have a _NoResultMetaData() here right now.
  768. assert not result._metadata.returns_rows
  769. result._metadata._we_dont_return_rows(err)
  770. _NO_CURSOR_DML = NoCursorDMLFetchStrategy()
  771. class CursorFetchStrategy(ResultFetchStrategy):
  772. """Call fetch methods from a DBAPI cursor.
  773. Alternate versions of this class may instead buffer the rows from
  774. cursors or not use cursors at all.
  775. """
  776. __slots__ = ()
  777. def soft_close(self, result, dbapi_cursor):
  778. result.cursor_strategy = _NO_CURSOR_DQL
  779. def hard_close(self, result, dbapi_cursor):
  780. result.cursor_strategy = _NO_CURSOR_DQL
  781. def handle_exception(self, result, dbapi_cursor, err):
  782. result.connection._handle_dbapi_exception(
  783. err, None, None, dbapi_cursor, result.context
  784. )
  785. def yield_per(self, result, dbapi_cursor, num):
  786. result.cursor_strategy = BufferedRowCursorFetchStrategy(
  787. dbapi_cursor,
  788. {"max_row_buffer": num},
  789. initial_buffer=collections.deque(),
  790. growth_factor=0,
  791. )
  792. def fetchone(self, result, dbapi_cursor, hard_close=False):
  793. try:
  794. row = dbapi_cursor.fetchone()
  795. if row is None:
  796. result._soft_close(hard=hard_close)
  797. return row
  798. except BaseException as e:
  799. self.handle_exception(result, dbapi_cursor, e)
  800. def fetchmany(self, result, dbapi_cursor, size=None):
  801. try:
  802. if size is None:
  803. l = dbapi_cursor.fetchmany()
  804. else:
  805. l = dbapi_cursor.fetchmany(size)
  806. if not l:
  807. result._soft_close()
  808. return l
  809. except BaseException as e:
  810. self.handle_exception(result, dbapi_cursor, e)
  811. def fetchall(self, result, dbapi_cursor):
  812. try:
  813. rows = dbapi_cursor.fetchall()
  814. result._soft_close()
  815. return rows
  816. except BaseException as e:
  817. self.handle_exception(result, dbapi_cursor, e)
  818. _DEFAULT_FETCH = CursorFetchStrategy()
  819. class BufferedRowCursorFetchStrategy(CursorFetchStrategy):
  820. """A cursor fetch strategy with row buffering behavior.
  821. This strategy buffers the contents of a selection of rows
  822. before ``fetchone()`` is called. This is to allow the results of
  823. ``cursor.description`` to be available immediately, when
  824. interfacing with a DB-API that requires rows to be consumed before
  825. this information is available (currently psycopg2, when used with
  826. server-side cursors).
  827. The pre-fetching behavior fetches only one row initially, and then
  828. grows its buffer size by a fixed amount with each successive need
  829. for additional rows up the ``max_row_buffer`` size, which defaults
  830. to 1000::
  831. with psycopg2_engine.connect() as conn:
  832. result = conn.execution_options(
  833. stream_results=True, max_row_buffer=50
  834. ).execute(text("select * from table"))
  835. .. versionadded:: 1.4 ``max_row_buffer`` may now exceed 1000 rows.
  836. .. seealso::
  837. :ref:`psycopg2_execution_options`
  838. """
  839. __slots__ = ("_max_row_buffer", "_rowbuffer", "_bufsize", "_growth_factor")
  840. def __init__(
  841. self,
  842. dbapi_cursor,
  843. execution_options,
  844. growth_factor=5,
  845. initial_buffer=None,
  846. ):
  847. self._max_row_buffer = execution_options.get("max_row_buffer", 1000)
  848. if initial_buffer is not None:
  849. self._rowbuffer = initial_buffer
  850. else:
  851. self._rowbuffer = collections.deque(dbapi_cursor.fetchmany(1))
  852. self._growth_factor = growth_factor
  853. if growth_factor:
  854. self._bufsize = min(self._max_row_buffer, self._growth_factor)
  855. else:
  856. self._bufsize = self._max_row_buffer
  857. @classmethod
  858. def create(cls, result):
  859. return BufferedRowCursorFetchStrategy(
  860. result.cursor,
  861. result.context.execution_options,
  862. )
  863. def _buffer_rows(self, result, dbapi_cursor):
  864. size = self._bufsize
  865. try:
  866. if size < 1:
  867. new_rows = dbapi_cursor.fetchall()
  868. else:
  869. new_rows = dbapi_cursor.fetchmany(size)
  870. except BaseException as e:
  871. self.handle_exception(result, dbapi_cursor, e)
  872. if not new_rows:
  873. return
  874. self._rowbuffer = collections.deque(new_rows)
  875. if self._growth_factor and size < self._max_row_buffer:
  876. self._bufsize = min(
  877. self._max_row_buffer, size * self._growth_factor
  878. )
  879. def yield_per(self, result, dbapi_cursor, num):
  880. self._growth_factor = 0
  881. self._max_row_buffer = self._bufsize = num
  882. def soft_close(self, result, dbapi_cursor):
  883. self._rowbuffer.clear()
  884. super(BufferedRowCursorFetchStrategy, self).soft_close(
  885. result, dbapi_cursor
  886. )
  887. def hard_close(self, result, dbapi_cursor):
  888. self._rowbuffer.clear()
  889. super(BufferedRowCursorFetchStrategy, self).hard_close(
  890. result, dbapi_cursor
  891. )
  892. def fetchone(self, result, dbapi_cursor, hard_close=False):
  893. if not self._rowbuffer:
  894. self._buffer_rows(result, dbapi_cursor)
  895. if not self._rowbuffer:
  896. try:
  897. result._soft_close(hard=hard_close)
  898. except BaseException as e:
  899. self.handle_exception(result, dbapi_cursor, e)
  900. return None
  901. return self._rowbuffer.popleft()
  902. def fetchmany(self, result, dbapi_cursor, size=None):
  903. if size is None:
  904. return self.fetchall(result, dbapi_cursor)
  905. buf = list(self._rowbuffer)
  906. lb = len(buf)
  907. if size > lb:
  908. try:
  909. buf.extend(dbapi_cursor.fetchmany(size - lb))
  910. except BaseException as e:
  911. self.handle_exception(result, dbapi_cursor, e)
  912. result = buf[0:size]
  913. self._rowbuffer = collections.deque(buf[size:])
  914. return result
  915. def fetchall(self, result, dbapi_cursor):
  916. try:
  917. ret = list(self._rowbuffer) + list(dbapi_cursor.fetchall())
  918. self._rowbuffer.clear()
  919. result._soft_close()
  920. return ret
  921. except BaseException as e:
  922. self.handle_exception(result, dbapi_cursor, e)
  923. class FullyBufferedCursorFetchStrategy(CursorFetchStrategy):
  924. """A cursor strategy that buffers rows fully upon creation.
  925. Used for operations where a result is to be delivered
  926. after the database conversation can not be continued,
  927. such as MSSQL INSERT...OUTPUT after an autocommit.
  928. """
  929. __slots__ = ("_rowbuffer", "alternate_cursor_description")
  930. def __init__(
  931. self, dbapi_cursor, alternate_description=None, initial_buffer=None
  932. ):
  933. self.alternate_cursor_description = alternate_description
  934. if initial_buffer is not None:
  935. self._rowbuffer = collections.deque(initial_buffer)
  936. else:
  937. self._rowbuffer = collections.deque(dbapi_cursor.fetchall())
  938. def yield_per(self, result, dbapi_cursor, num):
  939. pass
  940. def soft_close(self, result, dbapi_cursor):
  941. self._rowbuffer.clear()
  942. super(FullyBufferedCursorFetchStrategy, self).soft_close(
  943. result, dbapi_cursor
  944. )
  945. def hard_close(self, result, dbapi_cursor):
  946. self._rowbuffer.clear()
  947. super(FullyBufferedCursorFetchStrategy, self).hard_close(
  948. result, dbapi_cursor
  949. )
  950. def fetchone(self, result, dbapi_cursor, hard_close=False):
  951. if self._rowbuffer:
  952. return self._rowbuffer.popleft()
  953. else:
  954. result._soft_close(hard=hard_close)
  955. return None
  956. def fetchmany(self, result, dbapi_cursor, size=None):
  957. if size is None:
  958. return self.fetchall(result, dbapi_cursor)
  959. buf = list(self._rowbuffer)
  960. rows = buf[0:size]
  961. self._rowbuffer = collections.deque(buf[size:])
  962. if not rows:
  963. result._soft_close()
  964. return rows
  965. def fetchall(self, result, dbapi_cursor):
  966. ret = self._rowbuffer
  967. self._rowbuffer = collections.deque()
  968. result._soft_close()
  969. return ret
  970. class _NoResultMetaData(ResultMetaData):
  971. __slots__ = ()
  972. returns_rows = False
  973. def _we_dont_return_rows(self, err=None):
  974. util.raise_(
  975. exc.ResourceClosedError(
  976. "This result object does not return rows. "
  977. "It has been closed automatically."
  978. ),
  979. replace_context=err,
  980. )
  981. def _index_for_key(self, keys, raiseerr):
  982. self._we_dont_return_rows()
  983. def _metadata_for_keys(self, key):
  984. self._we_dont_return_rows()
  985. def _reduce(self, keys):
  986. self._we_dont_return_rows()
  987. @property
  988. def _keymap(self):
  989. self._we_dont_return_rows()
  990. @property
  991. def keys(self):
  992. self._we_dont_return_rows()
  993. class _LegacyNoResultMetaData(_NoResultMetaData):
  994. @property
  995. def keys(self):
  996. util.warn_deprecated_20(
  997. "Calling the .keys() method on a result set that does not return "
  998. "rows is deprecated and will raise ResourceClosedError in "
  999. "SQLAlchemy 2.0.",
  1000. )
  1001. return []
  1002. _NO_RESULT_METADATA = _NoResultMetaData()
  1003. _LEGACY_NO_RESULT_METADATA = _LegacyNoResultMetaData()
  1004. class BaseCursorResult(object):
  1005. """Base class for database result objects."""
  1006. out_parameters = None
  1007. _metadata = None
  1008. _soft_closed = False
  1009. closed = False
  1010. def __init__(self, context, cursor_strategy, cursor_description):
  1011. self.context = context
  1012. self.dialect = context.dialect
  1013. self.cursor = context.cursor
  1014. self.cursor_strategy = cursor_strategy
  1015. self.connection = context.root_connection
  1016. self._echo = echo = (
  1017. self.connection._echo and context.engine._should_log_debug()
  1018. )
  1019. if cursor_description is not None:
  1020. # inline of Result._row_getter(), set up an initial row
  1021. # getter assuming no transformations will be called as this
  1022. # is the most common case
  1023. if echo:
  1024. log = self.context.connection._log_debug
  1025. def log_row(row):
  1026. log("Row %r", sql_util._repr_row(row))
  1027. return row
  1028. self._row_logging_fn = log_row
  1029. else:
  1030. log_row = None
  1031. metadata = self._init_metadata(context, cursor_description)
  1032. keymap = metadata._keymap
  1033. processors = metadata._processors
  1034. process_row = self._process_row
  1035. key_style = process_row._default_key_style
  1036. _make_row = functools.partial(
  1037. process_row, metadata, processors, keymap, key_style
  1038. )
  1039. if log_row:
  1040. def make_row(row):
  1041. made_row = _make_row(row)
  1042. log_row(made_row)
  1043. return made_row
  1044. else:
  1045. make_row = _make_row
  1046. self._set_memoized_attribute("_row_getter", make_row)
  1047. else:
  1048. self._metadata = self._no_result_metadata
  1049. def _init_metadata(self, context, cursor_description):
  1050. if context.compiled:
  1051. if context.compiled._cached_metadata:
  1052. metadata = self.context.compiled._cached_metadata
  1053. else:
  1054. metadata = self._cursor_metadata(self, cursor_description)
  1055. if metadata._safe_for_cache:
  1056. context.compiled._cached_metadata = metadata
  1057. # result rewrite/ adapt step. this is to suit the case
  1058. # when we are invoked against a cached Compiled object, we want
  1059. # to rewrite the ResultMetaData to reflect the Column objects
  1060. # that are in our current SQL statement object, not the one
  1061. # that is associated with the cached Compiled object.
  1062. # the Compiled object may also tell us to not
  1063. # actually do this step; this is to support the ORM where
  1064. # it is to produce a new Result object in any case, and will
  1065. # be using the cached Column objects against this database result
  1066. # so we don't want to rewrite them.
  1067. #
  1068. # Basically this step suits the use case where the end user
  1069. # is using Core SQL expressions and is accessing columns in the
  1070. # result row using row._mapping[table.c.column].
  1071. compiled = context.compiled
  1072. if (
  1073. compiled
  1074. and compiled._result_columns
  1075. and context.cache_hit is context.dialect.CACHE_HIT
  1076. and not context.execution_options.get(
  1077. "_result_disable_adapt_to_context", False
  1078. )
  1079. and compiled.statement is not context.invoked_statement
  1080. ):
  1081. metadata = metadata._adapt_to_context(context)
  1082. self._metadata = metadata
  1083. else:
  1084. self._metadata = metadata = self._cursor_metadata(
  1085. self, cursor_description
  1086. )
  1087. if self._echo:
  1088. context.connection._log_debug(
  1089. "Col %r", tuple(x[0] for x in cursor_description)
  1090. )
  1091. return metadata
  1092. def _soft_close(self, hard=False):
  1093. """Soft close this :class:`_engine.CursorResult`.
  1094. This releases all DBAPI cursor resources, but leaves the
  1095. CursorResult "open" from a semantic perspective, meaning the
  1096. fetchXXX() methods will continue to return empty results.
  1097. This method is called automatically when:
  1098. * all result rows are exhausted using the fetchXXX() methods.
  1099. * cursor.description is None.
  1100. This method is **not public**, but is documented in order to clarify
  1101. the "autoclose" process used.
  1102. .. versionadded:: 1.0.0
  1103. .. seealso::
  1104. :meth:`_engine.CursorResult.close`
  1105. """
  1106. if (not hard and self._soft_closed) or (hard and self.closed):
  1107. return
  1108. if hard:
  1109. self.closed = True
  1110. self.cursor_strategy.hard_close(self, self.cursor)
  1111. else:
  1112. self.cursor_strategy.soft_close(self, self.cursor)
  1113. if not self._soft_closed:
  1114. cursor = self.cursor
  1115. self.cursor = None
  1116. self.connection._safe_close_cursor(cursor)
  1117. self._soft_closed = True
  1118. @property
  1119. def inserted_primary_key_rows(self):
  1120. """Return the value of :attr:`_engine.CursorResult.inserted_primary_key`
  1121. as a row contained within a list; some dialects may support a
  1122. multiple row form as well.
  1123. .. note:: As indicated below, in current SQLAlchemy versions this
  1124. accessor is only useful beyond what's already supplied by
  1125. :attr:`_engine.CursorResult.inserted_primary_key` when using the
  1126. :ref:`postgresql_psycopg2` dialect. Future versions hope to
  1127. generalize this feature to more dialects.
  1128. This accessor is added to support dialects that offer the feature
  1129. that is currently implemented by the :ref:`psycopg2_executemany_mode`
  1130. feature, currently **only the psycopg2 dialect**, which provides
  1131. for many rows to be INSERTed at once while still retaining the
  1132. behavior of being able to return server-generated primary key values.
  1133. * **When using the psycopg2 dialect, or other dialects that may support
  1134. "fast executemany" style inserts in upcoming releases** : When
  1135. invoking an INSERT statement while passing a list of rows as the
  1136. second argument to :meth:`_engine.Connection.execute`, this accessor
  1137. will then provide a list of rows, where each row contains the primary
  1138. key value for each row that was INSERTed.
  1139. * **When using all other dialects / backends that don't yet support
  1140. this feature**: This accessor is only useful for **single row INSERT
  1141. statements**, and returns the same information as that of the
  1142. :attr:`_engine.CursorResult.inserted_primary_key` within a
  1143. single-element list. When an INSERT statement is executed in
  1144. conjunction with a list of rows to be INSERTed, the list will contain
  1145. one row per row inserted in the statement, however it will contain
  1146. ``None`` for any server-generated values.
  1147. Future releases of SQLAlchemy will further generalize the
  1148. "fast execution helper" feature of psycopg2 to suit other dialects,
  1149. thus allowing this accessor to be of more general use.
  1150. .. versionadded:: 1.4
  1151. .. seealso::
  1152. :attr:`_engine.CursorResult.inserted_primary_key`
  1153. """
  1154. if not self.context.compiled:
  1155. raise exc.InvalidRequestError(
  1156. "Statement is not a compiled " "expression construct."
  1157. )
  1158. elif not self.context.isinsert:
  1159. raise exc.InvalidRequestError(
  1160. "Statement is not an insert() " "expression construct."
  1161. )
  1162. elif self.context._is_explicit_returning:
  1163. raise exc.InvalidRequestError(
  1164. "Can't call inserted_primary_key "
  1165. "when returning() "
  1166. "is used."
  1167. )
  1168. return self.context.inserted_primary_key_rows
  1169. @property
  1170. def inserted_primary_key(self):
  1171. """Return the primary key for the row just inserted.
  1172. The return value is a :class:`_result.Row` object representing
  1173. a named tuple of primary key values in the order in which the
  1174. primary key columns are configured in the source
  1175. :class:`_schema.Table`.
  1176. .. versionchanged:: 1.4.8 - the
  1177. :attr:`_engine.CursorResult.inserted_primary_key`
  1178. value is now a named tuple via the :class:`_result.Row` class,
  1179. rather than a plain tuple.
  1180. This accessor only applies to single row :func:`_expression.insert`
  1181. constructs which did not explicitly specify
  1182. :meth:`_expression.Insert.returning`. Support for multirow inserts,
  1183. while not yet available for most backends, would be accessed using
  1184. the :attr:`_engine.CursorResult.inserted_primary_key_rows` accessor.
  1185. Note that primary key columns which specify a server_default clause, or
  1186. otherwise do not qualify as "autoincrement" columns (see the notes at
  1187. :class:`_schema.Column`), and were generated using the database-side
  1188. default, will appear in this list as ``None`` unless the backend
  1189. supports "returning" and the insert statement executed with the
  1190. "implicit returning" enabled.
  1191. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1192. statement is not a compiled expression construct
  1193. or is not an insert() construct.
  1194. """
  1195. if self.context.executemany:
  1196. raise exc.InvalidRequestError(
  1197. "This statement was an executemany call; if primary key "
  1198. "returning is supported, please "
  1199. "use .inserted_primary_key_rows."
  1200. )
  1201. ikp = self.inserted_primary_key_rows
  1202. if ikp:
  1203. return ikp[0]
  1204. else:
  1205. return None
  1206. def last_updated_params(self):
  1207. """Return the collection of updated parameters from this
  1208. execution.
  1209. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1210. statement is not a compiled expression construct
  1211. or is not an update() construct.
  1212. """
  1213. if not self.context.compiled:
  1214. raise exc.InvalidRequestError(
  1215. "Statement is not a compiled " "expression construct."
  1216. )
  1217. elif not self.context.isupdate:
  1218. raise exc.InvalidRequestError(
  1219. "Statement is not an update() " "expression construct."
  1220. )
  1221. elif self.context.executemany:
  1222. return self.context.compiled_parameters
  1223. else:
  1224. return self.context.compiled_parameters[0]
  1225. def last_inserted_params(self):
  1226. """Return the collection of inserted parameters from this
  1227. execution.
  1228. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1229. statement is not a compiled expression construct
  1230. or is not an insert() construct.
  1231. """
  1232. if not self.context.compiled:
  1233. raise exc.InvalidRequestError(
  1234. "Statement is not a compiled " "expression construct."
  1235. )
  1236. elif not self.context.isinsert:
  1237. raise exc.InvalidRequestError(
  1238. "Statement is not an insert() " "expression construct."
  1239. )
  1240. elif self.context.executemany:
  1241. return self.context.compiled_parameters
  1242. else:
  1243. return self.context.compiled_parameters[0]
  1244. @property
  1245. def returned_defaults_rows(self):
  1246. """Return a list of rows each containing the values of default
  1247. columns that were fetched using
  1248. the :meth:`.ValuesBase.return_defaults` feature.
  1249. The return value is a list of :class:`.Row` objects.
  1250. .. versionadded:: 1.4
  1251. """
  1252. return self.context.returned_default_rows
  1253. @property
  1254. def returned_defaults(self):
  1255. """Return the values of default columns that were fetched using
  1256. the :meth:`.ValuesBase.return_defaults` feature.
  1257. The value is an instance of :class:`.Row`, or ``None``
  1258. if :meth:`.ValuesBase.return_defaults` was not used or if the
  1259. backend does not support RETURNING.
  1260. .. versionadded:: 0.9.0
  1261. .. seealso::
  1262. :meth:`.ValuesBase.return_defaults`
  1263. """
  1264. if self.context.executemany:
  1265. raise exc.InvalidRequestError(
  1266. "This statement was an executemany call; if return defaults "
  1267. "is supported, please use .returned_defaults_rows."
  1268. )
  1269. rows = self.context.returned_default_rows
  1270. if rows:
  1271. return rows[0]
  1272. else:
  1273. return None
  1274. def lastrow_has_defaults(self):
  1275. """Return ``lastrow_has_defaults()`` from the underlying
  1276. :class:`.ExecutionContext`.
  1277. See :class:`.ExecutionContext` for details.
  1278. """
  1279. return self.context.lastrow_has_defaults()
  1280. def postfetch_cols(self):
  1281. """Return ``postfetch_cols()`` from the underlying
  1282. :class:`.ExecutionContext`.
  1283. See :class:`.ExecutionContext` for details.
  1284. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1285. statement is not a compiled expression construct
  1286. or is not an insert() or update() construct.
  1287. """
  1288. if not self.context.compiled:
  1289. raise exc.InvalidRequestError(
  1290. "Statement is not a compiled " "expression construct."
  1291. )
  1292. elif not self.context.isinsert and not self.context.isupdate:
  1293. raise exc.InvalidRequestError(
  1294. "Statement is not an insert() or update() "
  1295. "expression construct."
  1296. )
  1297. return self.context.postfetch_cols
  1298. def prefetch_cols(self):
  1299. """Return ``prefetch_cols()`` from the underlying
  1300. :class:`.ExecutionContext`.
  1301. See :class:`.ExecutionContext` for details.
  1302. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
  1303. statement is not a compiled expression construct
  1304. or is not an insert() or update() construct.
  1305. """
  1306. if not self.context.compiled:
  1307. raise exc.InvalidRequestError(
  1308. "Statement is not a compiled " "expression construct."
  1309. )
  1310. elif not self.context.isinsert and not self.context.isupdate:
  1311. raise exc.InvalidRequestError(
  1312. "Statement is not an insert() or update() "
  1313. "expression construct."
  1314. )
  1315. return self.context.prefetch_cols
  1316. def supports_sane_rowcount(self):
  1317. """Return ``supports_sane_rowcount`` from the dialect.
  1318. See :attr:`_engine.CursorResult.rowcount` for background.
  1319. """
  1320. return self.dialect.supports_sane_rowcount
  1321. def supports_sane_multi_rowcount(self):
  1322. """Return ``supports_sane_multi_rowcount`` from the dialect.
  1323. See :attr:`_engine.CursorResult.rowcount` for background.
  1324. """
  1325. return self.dialect.supports_sane_multi_rowcount
  1326. @util.memoized_property
  1327. def rowcount(self):
  1328. """Return the 'rowcount' for this result.
  1329. The 'rowcount' reports the number of rows *matched*
  1330. by the WHERE criterion of an UPDATE or DELETE statement.
  1331. .. note::
  1332. Notes regarding :attr:`_engine.CursorResult.rowcount`:
  1333. * This attribute returns the number of rows *matched*,
  1334. which is not necessarily the same as the number of rows
  1335. that were actually *modified* - an UPDATE statement, for example,
  1336. may have no net change on a given row if the SET values
  1337. given are the same as those present in the row already.
  1338. Such a row would be matched but not modified.
  1339. On backends that feature both styles, such as MySQL,
  1340. rowcount is configured by default to return the match
  1341. count in all cases.
  1342. * :attr:`_engine.CursorResult.rowcount`
  1343. is *only* useful in conjunction
  1344. with an UPDATE or DELETE statement. Contrary to what the Python
  1345. DBAPI says, it does *not* return the
  1346. number of rows available from the results of a SELECT statement
  1347. as DBAPIs cannot support this functionality when rows are
  1348. unbuffered.
  1349. * :attr:`_engine.CursorResult.rowcount`
  1350. may not be fully implemented by
  1351. all dialects. In particular, most DBAPIs do not support an
  1352. aggregate rowcount result from an executemany call.
  1353. The :meth:`_engine.CursorResult.supports_sane_rowcount` and
  1354. :meth:`_engine.CursorResult.supports_sane_multi_rowcount` methods
  1355. will report from the dialect if each usage is known to be
  1356. supported.
  1357. * Statements that use RETURNING may not return a correct
  1358. rowcount.
  1359. .. seealso::
  1360. :ref:`tutorial_update_delete_rowcount` - in the :ref:`unified_tutorial`
  1361. """ # noqa E501
  1362. try:
  1363. return self.context.rowcount
  1364. except BaseException as e:
  1365. self.cursor_strategy.handle_exception(self, self.cursor, e)
  1366. @property
  1367. def lastrowid(self):
  1368. """Return the 'lastrowid' accessor on the DBAPI cursor.
  1369. This is a DBAPI specific method and is only functional
  1370. for those backends which support it, for statements
  1371. where it is appropriate. It's behavior is not
  1372. consistent across backends.
  1373. Usage of this method is normally unnecessary when
  1374. using insert() expression constructs; the
  1375. :attr:`~CursorResult.inserted_primary_key` attribute provides a
  1376. tuple of primary key values for a newly inserted row,
  1377. regardless of database backend.
  1378. """
  1379. try:
  1380. return self.context.get_lastrowid()
  1381. except BaseException as e:
  1382. self.cursor_strategy.handle_exception(self, self.cursor, e)
  1383. @property
  1384. def returns_rows(self):
  1385. """True if this :class:`_engine.CursorResult` returns zero or more rows.
  1386. I.e. if it is legal to call the methods
  1387. :meth:`_engine.CursorResult.fetchone`,
  1388. :meth:`_engine.CursorResult.fetchmany`
  1389. :meth:`_engine.CursorResult.fetchall`.
  1390. Overall, the value of :attr:`_engine.CursorResult.returns_rows` should
  1391. always be synonymous with whether or not the DBAPI cursor had a
  1392. ``.description`` attribute, indicating the presence of result columns,
  1393. noting that a cursor that returns zero rows still has a
  1394. ``.description`` if a row-returning statement was emitted.
  1395. This attribute should be True for all results that are against
  1396. SELECT statements, as well as for DML statements INSERT/UPDATE/DELETE
  1397. that use RETURNING. For INSERT/UPDATE/DELETE statements that were
  1398. not using RETURNING, the value will usually be False, however
  1399. there are some dialect-specific exceptions to this, such as when
  1400. using the MSSQL / pyodbc dialect a SELECT is emitted inline in
  1401. order to retrieve an inserted primary key value.
  1402. """
  1403. return self._metadata.returns_rows
  1404. @property
  1405. def is_insert(self):
  1406. """True if this :class:`_engine.CursorResult` is the result
  1407. of a executing an expression language compiled
  1408. :func:`_expression.insert` construct.
  1409. When True, this implies that the
  1410. :attr:`inserted_primary_key` attribute is accessible,
  1411. assuming the statement did not include
  1412. a user defined "returning" construct.
  1413. """
  1414. return self.context.isinsert
  1415. class CursorResult(BaseCursorResult, Result):
  1416. """A Result that is representing state from a DBAPI cursor.
  1417. .. versionchanged:: 1.4 The :class:`.CursorResult` and
  1418. :class:`.LegacyCursorResult`
  1419. classes replace the previous :class:`.ResultProxy` interface.
  1420. These classes are based on the :class:`.Result` calling API
  1421. which provides an updated usage model and calling facade for
  1422. SQLAlchemy Core and SQLAlchemy ORM.
  1423. Returns database rows via the :class:`.Row` class, which provides
  1424. additional API features and behaviors on top of the raw data returned by
  1425. the DBAPI. Through the use of filters such as the :meth:`.Result.scalars`
  1426. method, other kinds of objects may also be returned.
  1427. Within the scope of the 1.x series of SQLAlchemy, Core SQL results in
  1428. version 1.4 return an instance of :class:`._engine.LegacyCursorResult`
  1429. which takes the place of the ``CursorResult`` class used for the 1.3 series
  1430. and previously. This object returns rows as :class:`.LegacyRow` objects,
  1431. which maintains Python mapping (i.e. dictionary) like behaviors upon the
  1432. object itself. Going forward, the :attr:`.Row._mapping` attribute should
  1433. be used for dictionary behaviors.
  1434. .. seealso::
  1435. :ref:`coretutorial_selecting` - introductory material for accessing
  1436. :class:`_engine.CursorResult` and :class:`.Row` objects.
  1437. """
  1438. _cursor_metadata = CursorResultMetaData
  1439. _cursor_strategy_cls = CursorFetchStrategy
  1440. _no_result_metadata = _NO_RESULT_METADATA
  1441. def _fetchiter_impl(self):
  1442. fetchone = self.cursor_strategy.fetchone
  1443. while True:
  1444. row = fetchone(self, self.cursor)
  1445. if row is None:
  1446. break
  1447. yield row
  1448. def _fetchone_impl(self, hard_close=False):
  1449. return self.cursor_strategy.fetchone(self, self.cursor, hard_close)
  1450. def _fetchall_impl(self):
  1451. return self.cursor_strategy.fetchall(self, self.cursor)
  1452. def _fetchmany_impl(self, size=None):
  1453. return self.cursor_strategy.fetchmany(self, self.cursor, size)
  1454. def _raw_row_iterator(self):
  1455. return self._fetchiter_impl()
  1456. def merge(self, *others):
  1457. merged_result = super(CursorResult, self).merge(*others)
  1458. setup_rowcounts = not self._metadata.returns_rows
  1459. if setup_rowcounts:
  1460. merged_result.rowcount = sum(
  1461. result.rowcount for result in (self,) + others
  1462. )
  1463. return merged_result
  1464. def close(self):
  1465. """Close this :class:`_engine.CursorResult`.
  1466. This closes out the underlying DBAPI cursor corresponding to the
  1467. statement execution, if one is still present. Note that the DBAPI
  1468. cursor is automatically released when the :class:`_engine.CursorResult`
  1469. exhausts all available rows. :meth:`_engine.CursorResult.close` is
  1470. generally an optional method except in the case when discarding a
  1471. :class:`_engine.CursorResult` that still has additional rows pending
  1472. for fetch.
  1473. After this method is called, it is no longer valid to call upon
  1474. the fetch methods, which will raise a :class:`.ResourceClosedError`
  1475. on subsequent use.
  1476. .. seealso::
  1477. :ref:`connections_toplevel`
  1478. """
  1479. self._soft_close(hard=True)
  1480. @_generative
  1481. def yield_per(self, num):
  1482. self._yield_per = num
  1483. self.cursor_strategy.yield_per(self, self.cursor, num)
  1484. class LegacyCursorResult(CursorResult):
  1485. """Legacy version of :class:`.CursorResult`.
  1486. This class includes connection "connection autoclose" behavior for use with
  1487. "connectionless" execution, as well as delivers rows using the
  1488. :class:`.LegacyRow` row implementation.
  1489. .. versionadded:: 1.4
  1490. """
  1491. _autoclose_connection = False
  1492. _process_row = LegacyRow
  1493. _cursor_metadata = LegacyCursorResultMetaData
  1494. _cursor_strategy_cls = CursorFetchStrategy
  1495. _no_result_metadata = _LEGACY_NO_RESULT_METADATA
  1496. def close(self):
  1497. """Close this :class:`_engine.LegacyCursorResult`.
  1498. This method has the same behavior as that of
  1499. :meth:`._engine.CursorResult`, but it also may close
  1500. the underlying :class:`.Connection` for the case of "connectionless"
  1501. execution.
  1502. .. deprecated:: 2.0 "connectionless" execution is deprecated and will
  1503. be removed in version 2.0. Version 2.0 will feature the
  1504. :class:`_future.Result`
  1505. object that will no longer affect the status
  1506. of the originating connection in any case.
  1507. After this method is called, it is no longer valid to call upon
  1508. the fetch methods, which will raise a :class:`.ResourceClosedError`
  1509. on subsequent use.
  1510. .. seealso::
  1511. :ref:`connections_toplevel`
  1512. :ref:`dbengine_implicit`
  1513. """
  1514. self._soft_close(hard=True)
  1515. def _soft_close(self, hard=False):
  1516. soft_closed = self._soft_closed
  1517. super(LegacyCursorResult, self)._soft_close(hard=hard)
  1518. if (
  1519. not soft_closed
  1520. and self._soft_closed
  1521. and self._autoclose_connection
  1522. ):
  1523. self.connection.close()
  1524. ResultProxy = LegacyCursorResult
  1525. class BufferedRowResultProxy(ResultProxy):
  1526. """A ResultProxy with row buffering behavior.
  1527. .. deprecated:: 1.4 this class is now supplied using a strategy object.
  1528. See :class:`.BufferedRowCursorFetchStrategy`.
  1529. """
  1530. _cursor_strategy_cls = BufferedRowCursorFetchStrategy
  1531. class FullyBufferedResultProxy(ResultProxy):
  1532. """A result proxy that buffers rows fully upon creation.
  1533. .. deprecated:: 1.4 this class is now supplied using a strategy object.
  1534. See :class:`.FullyBufferedCursorFetchStrategy`.
  1535. """
  1536. _cursor_strategy_cls = FullyBufferedCursorFetchStrategy
  1537. class BufferedColumnRow(LegacyRow):
  1538. """Row is now BufferedColumn in all cases"""
  1539. class BufferedColumnResultProxy(ResultProxy):
  1540. """A ResultProxy with column buffering behavior.
  1541. .. versionchanged:: 1.4 This is now the default behavior of the Row
  1542. and this class does not change behavior in any way.
  1543. """
  1544. _process_row = BufferedColumnRow