U kfh* @sUdZddlmZddlZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z dd lm Z dd lm Z dd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddl!m"Z"ddl!m#Z#ddl!m Z$ddl%m&Z&dd l'm(Z(dd!l'm)Z)dd"l'm*Z*dd#l'm+Z+dd$l'm,Z,dd%l-m.Z.dd&l m/Z/dd'l0m1Z1dd(l0m2Z2ejrdd)l3m4Z4dd*l5m6Z6dd+l7m8Z8dd,l7m9Z9dd-l7m:Z:dd.l7m;Z;dd/lmZ>dd2lm?Z?dd3lm@Z@dd4lmAZAdd5l-mBZBed6ed7ZCdZDd8eEd9<dZFd:eEd;<dZGdZHd?eEd@<dAZIdBeEdC<dDZJdEeEdF<dGZKdHeEdI<eeeLeLe eeMeMedJeeMfZNe dKeNfZOeeLeLe eeMeMedJeMfZPGdLdMdMeZQGdNdOdOZRGdPdQdQeRZSGdRdSdSeSZTeTZUGdTdUdUeSZVeVZWGdVdWdWeRZXeXZYGdXdYdYeXZZGdZd[d[eXZ[Gd\d]d]eZ\e\Z]d^d_d`daZ^GdbdcdceeCZ_e_Z`dS)dzNDefine cursor-specific result set constructs including :class:`.CursorResult`.) annotationsN)Any)cast)ClassVar)Dict)Iterator)List)Mapping)NoReturn)Optional)Sequence)Tuple) TYPE_CHECKING)TypeVar)Union)IteratorResult) MergedResult)Result)ResultMetaData)SimpleResultMetaData) tuplegetter)Row)exc)util)elements)sqltypes) _generative)ResultColumnsEntry)RM_NAME) RM_OBJECTS)RM_RENDERED_NAME)RM_TYPE) TypeEngine)compat)Literal)Self) Connection)DefaultExecutionContext)_DBAPICursorDescription) DBAPICursor)Dialect)ExecutionContext) _KeyIndexType)_KeyMapRecType) _KeyMapType)_KeyType)_ProcessorsType)_TupleGetterType)_ResultProcessorType_T)boundz Literal[0]MD_INDEXz Literal[1]MD_RESULT_MAP_INDEXz Literal[2] MD_OBJECTSz Literal[3] MD_LOOKUP_KEYz Literal[4]MD_RENDERED_NAMEz Literal[5] MD_PROCESSORz Literal[6]MD_UNTRANSLATEDz_ResultProcessorType[Any]r1c @s|eZdZUdZdZded<ded<ded<d ed <d ed <d ed <dZded<dd dddZddddZd ddddd d ddd ddZ dddd Z ddd!d"d#Z d$dd%d&d'Z d(dd)d*d+Z d,d-d.d/d0Zd1d2Zd3d4Zd5d6Zd7d8ZedWd:d d;d<d=d>Zd?d@Zes4dXddAd dBdCdDdEZdFdGZdYdd dHdIdJdKZdLdMZdNdOd%dPdQZdRdSZdTdUZdVS)ZCursorResultMetaDataz"Result metadata for DBAPI cursors.) _keymap _processors_keys_keymap_by_result_column_idx _tuplefilter_translated_indexes_safe_for_cache _unpickled _key_to_index_CursorKeyMapTyperCr2rDz#Optional[Dict[int, _KeyMapRecType]]rFboolrJrIzOptional[List[int]]rHTzClassVar[bool] returns_rowsr)keyreturncCs ||jkSNrCselfrOrUH/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/engine/cursor.py_has_keyszCursorResultMetaData._has_keyrrPcstjfddjDdS)Ncsg|]}j|tqSrU)rCr9.0rOrTrUrV sz4CursorResultMetaData._for_freeze..)extra)rrEr[rUr[rV _for_freezesz CursorResultMetaData._for_freezez Sequence[str]r0zOptional[_TupleGetterType]) unpickled processorskeyskeymap tuplefiltertranslated_indexessafe_for_cachekeymap_by_result_column_idxrPc CsP|j|j} || _|| _|| _|| _|| _|| _|| _|| _ | |t | _ | SrQ) __class____new__rJrDrErCrGrHrIrF_make_key_to_indexr7rK) rTr_r`rarbrcrdrerfZnew_objrUrUrV_make_new_metadatas z'CursorResultMetaData._make_new_metadatac CsH|jr t|j|jdgt|jdddd|jD|j|j |j dS)NcSs.i|]&\}}||ddd|ddqS)rr>rQr@NrUrZrOvaluerUrUrV sz;CursorResultMetaData._remove_processors..)r_r`rcrdrbrarerf) rGAssertionErrorrjrJlenrDrCitemsrErIrFr[rUrUrV_remove_processorss z'CursorResultMetaData._remove_processors)otherrPc sz|jr tt|jt|jfdd|jD|j|j |j |j dd|j|j|j dd DdS)NcsNi|]F\}}||ddk r.|kr.|dnd|df|ddqS)rNrrrUrkrboffsetrUrVrms    z=CursorResultMetaData._splice_horizontally..cSsi|]}|t|qSrUr8rZmetadata_entryrUrUrVrms)r_r`rcrdrarbrerf) rGrndictrCrorEupdaterprjrJrDrIvalues)rTrrrUrsrV_splice_horizontallys(      z)CursorResultMetaData._splice_horizontallyzSequence[_KeyIndexType])rarPc st|}dd|D}dd|D}jrBfdd|D}t|}ddt|D}dd|D}|dd |Djjj||||j j d S) NcSsg|] }|tqSrU)r7rZrecrUrUrVr\sz0CursorResultMetaData._reduce..cSsg|] }|tqSrUr;r|rUrUrVr\scsg|]}j|qSrU)rH)rZidxr[rUrVr\scSs"g|]\}}|f|ddqSrNrU)rZindexr}rUrUrVr\scSsi|]}|t|qSrUr~r|rUrUrVrmsz0CursorResultMetaData._reduce..css(|] }|tpdD]}||fVqqdS)rUNr9)rZZnew_recerUrUrV sz/CursorResultMetaData._reduce..)r_r`rarcrdrbrerf) list_metadata_for_keysrHr enumerateryrjrJrDrIrF)rTraZrecsZindexesZnew_keystupZnew_recsrbrUr[rV_reduces* zCursorResultMetaData._reducer-)contextrPc s|jr|jjs|S|jj}|j}tr4t|tjs4t||kr@|S|dk sLt|j dkrtdd|j D|_ |j r~t|j t|j fddt|jD|j|jdd|j|j|j dS)a[When using a cached Compiled construct that has a _result_map, for a new statement that used the cached Compiled, we need to ensure the keymap has the Column objects from our new statement as keys. So here we rewrite keymap with new entries for the new columns as matched to those of the cached statement. NcSsi|]}|t|qSrUrurvrUrUrVrmAsz:CursorResultMetaData._adapt_to_context..cs"i|]\}}|kr||qSrUrU)rZrnewZkeymap_by_positionrUrVrmJs)rbr_r`rcrdrarerf)compiled_result_columns statementinvoked_statementr isinstancerZ ClauseElementrnrFrCrzrGrjr%Z dict_unionrZ_all_selected_columnsrJrDrErI)rTrZcompiled_statementrrUrrV_adapt_to_contexts@      z&CursorResultMetaData._adapt_to_contextCursorResult[Any]r*)parentcursor_descriptionc s|j}d_d_d__|jr>|j\}}}}}t|} nd}}} }}}|||| ||||} dd| D_d_ | r@dd| D} t| | kr"i} t | D]B} | t f| t pdD]&}| t }| |||krΈ|qqfdd| D_| ddDnd d| D_j| nd d| D_| sx|jrxjfd d| Djt _dS) NFcSsg|] }|tqSrU)r?rvrUrUrVr\sz1CursorResultMetaData.__init__..cSsi|]}|t|qSrUr~rvrUrUrVrmsz1CursorResultMetaData.__init__..rUcs0i|](}|tr|tD]}|kr||qqSrUrrZrwZobj_elem)dupesrUrVrms c Ss i|]}|ddg||ddfqSrQrUrYrUrUrVrmscSs(i|] }|tr|tD] }||qqSrUrrrUrUrVrms  cSsi|]}|t|qSrUr~rvrUrUrVrmscs(i|] }|tr|tj|tqSrU)rArCr;rvr[rUrVrms )rrGrHrIrJZresult_column_structro_merge_cursor_descriptionrDrFsetr=r9r7 setdefaultaddrCry_translate_colnamerirK)rTrrrresult_columnscols_are_orderedtextual_orderedad_hoc_textualloose_column_name_matching num_ctx_colsrawby_keyZ index_by_keyrwrOrrU)rrTrV__init__[s           zCursorResultMetaData.__init__c s|rF|rF|sF|tkrFdd|D|_d|_fddt|DS|sZ|rpt|krpd|_||} n.|rd|_|||} nd|_|} fdd| DSdS)a# Merge a cursor.description with compiled result column information. There are at least four separate strategies used here, selected depending on the type of SQL construct used to start with. The most common case is that of the compiled SQL expression construct, which generated the column names present in the raw SQL string and which has the identical number of columns as were reported by cursor.description. In this case, we assume a 1-1 positional mapping between the entries in cursor.description and the compiled object. This is also the most performant case as we disregard extracting / decoding the column names present in cursor.description since we already have the desired name we generated in the compiled SQL construct. The next common case is that of the completely raw string SQL, such as passed to connection.execute(). In this case we have no compiled construct to work with, so we extract and decode the names from cursor.description and index those as the primary result row target keys. The remaining fairly common case is that of the textual SQL that includes at least partial column information; this is when we use a :class:`_expression.TextualSelect` construct. This construct may have unordered or ordered column information. In the ordered case, we merge the cursor.description and the compiled construct's information positionally, and warn if there are additional description names present, however we still decode the names in cursor.description as we don't have a guarantee that the names in the columns match on these. In the unordered case, we match names in cursor.description to that of the compiled construct based on name matching. In both of these cases, the cursor.description names and the column expression objects and names are indexed as result row target keys. The final case is much less common, where we have a compiled non-textual SQL expression construct, but the number of columns in cursor.description doesn't match what's in the compiled construct. We make the guess here that there might be textual column expressions in the compiled construct that themselves include a comma in them causing them to split. We do the same name-matching as with textual non-ordered columns. The name-matched system of merging is the same as that used by SQLAlchemy for all cases up through the 0.9 series. Positional matching for compiled SQL expressions was introduced in 1.0 as a major performance feature, and positional matching for textual :class:`_expression.TextualSelect` objects in 1.1. As name matching is no longer a common case, it was acceptable to factor it into smaller generator- oriented methods that are easier to understand, but incur slightly more performance overhead. cSsg|] }|dqSrrU)rZelemrUrUrVr\8szBCursorResultMetaData._merge_cursor_description..Tc sHg|]@\}}|||t|t|t|t|t|ddfqSr)r!r r"get_result_processorr#)rZrZ rmap_entryrrrUrVr\As Fc s6g|].\}}}}}}}|||||||||fqSrU)r)rZrridxZcursor_colname mapped_typecoltypeobj untranslated)rrUrVr\qs( N)rorErIr_merge_textual_cols_by_position_merge_cols_by_name_merge_cols_by_none) rTrrrrrrrrZ raw_iteratorrUrrVrsPC     z.CursorResultMetaData._merge_cursor_descriptionc cs|j}|j}|jr|jnd}d}g|_t|D]N\}}|d} |d} |rV|| \} }|rb|| } |j| || || fVq.dS)zExtract column names and data types from a cursor.description. Applies unicode decoding, column translation, "normalization", and case sensitivity rules to the names based on the dialect. Nrr)dialectrZrequires_name_normalizenormalize_namerErappend) rTrrrZtranslate_colnamerrrr}colnamerrUrUrV_colnames_from_descriptions  z/CursorResultMetaData._colnames_from_descriptionccst|}|t|kr*td|t|ft}|||D]\}}}} ||kr||} | t} |} | t} | d|krtd| d| | dnt j } d} d} || || | | |fVq.r)rrBrargs)rTrarrUr[rV_indexes_for_keysXsz&CursorResultMetaData._indexes_for_keysz Sequence[Any]z&Iterator[_NonAmbigCursorKeyMapRecType]c cs|D]}t|jjkr|j|}z|j|}Wn6tk rb}zt||jd|W5d}~XYnX|t }|dkr~| |t t |VqdSr) rrg__mro__rErCrrBrrr7rr_NonAmbigCursorKeyMapRecType)rTrarOr}rrrUrUrVr_s  & z'CursorResultMetaData._metadata_for_keyscCs dd|jD|j|jdS)Nc Ss>i|]6\}}t|ttfr||t|tg||tddfqSrQ)rstrrr7r8r=)rZrOr}rUrUrVrmvs z5CursorResultMetaData.__getstate__..)rCrErH)rCrprErHr[rUrUrV __getstate__ss   z!CursorResultMetaData.__getstate__cCsddtt|dD|_|d|_d|_||jt|_|d|_d|_ |drrt d|d|_ t |j |_ n d|_ |_ dS)NcSsg|]}dqSrQrUrZ_rUrUrVr\sz5CursorResultMetaData.__setstate__..rErCTrHz List[int])rangerorDrCrFrir7rKrErJrrHrrG)rTstaterUrUrV __setstate__s  z!CursorResultMetaData.__setstate__N)F)T)T)__name__ __module__ __qualname____doc__ __slots____annotations__rNrWr^rjrqr{rrrrrrr classmethodrrrrrrrrrrrUrUrUrVrBsH  $ >$&)rBc@seZdZUdZdZdZded<dddd d d Zdddd d d ZdddddddZ d$dddddddZ d%dddddddZ dddd ddZ dddd d!d"d#Z dS)&ResultFetchStrategyzQDefine a fetching strategy for a result object. .. versionadded:: 1.4 rUN!Optional[_DBAPICursorDescription]alternate_cursor_descriptionrOptional[DBAPICursor]Noneresult dbapi_cursorrPcCs tdSrQNotImplementedErrorrTrrrUrUrV soft_closeszResultFetchStrategy.soft_closecCs tdSrQrrrUrUrV hard_closeszResultFetchStrategy.hard_closerrrnumrPcCsdSrQrUrTrrrrUrUrV yield_perszResultFetchStrategy.yield_perFr+rMrrrrrPcCs tdSrQrrTrrrrUrUrVfetchoneszResultFetchStrategy.fetchonerrrsizerPcCs tdSrQrrTrrrrUrUrV fetchmanyszResultFetchStrategy.fetchmanycCs tdSrQrrrUrUrVfetchallszResultFetchStrategy.fetchall BaseExceptionr rrrrPcCs|dSrQrUrTrrrrUrUrVhandle_exceptionsz$ResultFetchStrategy.handle_exception)F)N)rrrrrrrrrrrrrrrUrUrUrVrs    rc@sJeZdZdZdZddZddZddd Zdd d Zd dZ dddZ d S)NoCursorFetchStrategyzCursor strategy for a result that has no open cursor. There are two varieties of this strategy, one for DQL and one for DML (and also DDL), each of which represent a result that had a cursor but no longer has one. rUcCsdSrQrUrrUrUrVrsz NoCursorFetchStrategy.soft_closecCsdSrQrUrrUrUrVrsz NoCursorFetchStrategy.hard_closeFcCs ||dSrQ _non_resultrrUrUrVrszNoCursorFetchStrategy.fetchoneNcCs ||gSrQrrrUrUrVrszNoCursorFetchStrategy.fetchmanycCs ||gSrQrrrUrUrVrszNoCursorFetchStrategy.fetchallcCs tdSrQrrTrdefaultrrUrUrVrsz!NoCursorFetchStrategy._non_result)F)N)N) rrrrrrrrrrrrUrUrUrVrs  rc@seZdZdZdZdddZdS)NoCursorDQLFetchStrategyaCursor strategy for a DQL result that has no open cursor. This is a result set that can return rows, i.e. for a SELECT, or for an INSERT, UPDATE, DELETE that includes RETURNING. However it is in the state where the cursor is closed and no rows remain available. The owning result object may or may not be "hard closed", which determines if the fetch methods send empty results or raise for closed result. rUNcCs|jrtd|n|SdS)NzThis result object is closed.)closedrResourceClosedErrorrrUrUrVrsz$NoCursorDQLFetchStrategy._non_result)NrrrrrrrUrUrUrVrs rc@seZdZdZdZdddZdS)NoCursorDMLFetchStrategyzCursor strategy for a DML result that has no open cursor. This is a result set that does not return rows, i.e. for an INSERT, UPDATE, DELETE that does not include RETURNING. rUNcCs|jjr t|j|dSrQ) _metadatarNrn_we_dont_return_rowsrrUrUrVrs z$NoCursorDMLFetchStrategy._non_result)NrrUrUrUrVr src@seZdZdZdZddddddZddddd d Zddd d d ddZdddddddZd"dddddddZ d#dddddddZ ddddd d!Z dS)$CursorFetchStrategyzCall fetch methods from a DBAPI cursor. Alternate versions of this class may instead buffer the rows from cursors or not use cursors at all. rUrrrrcCs t|_dSrQ_NO_CURSOR_DQLcursor_strategyrrUrUrVr)szCursorFetchStrategy.soft_closecCs t|_dSrQrrrUrUrVr.szCursorFetchStrategy.hard_closerr rcCs|j|dd||jdSrQ) connectionZ_handle_dbapi_exceptionrrrUrUrVr3sz$CursorFetchStrategy.handle_exceptionrrcCst|d|itdd|_dS)Nmax_row_bufferr)initial_buffer growth_factor)BufferedRowCursorFetchStrategy collectionsdequerrrUrUrVr=s zCursorFetchStrategy.yield_perFr+rMrrc CsXz"|}|dkr|j|d|WStk rR}z||||W5d}~XYnXdSNhard)r _soft_closerr)rTrrrrowrrUrUrVrJs zCursorFetchStrategy.fetchoneNrrc Csdz.|dkr|}n ||}|s*||WStk r^}z||||W5d}~XYnXdSrQ)rrrr)rTrrrlrrUrUrVrXs  zCursorFetchStrategy.fetchmanyc CsLz|}||WStk rF}z||||W5d}~XYnXdSrQ)rrrr)rTrrrowsrrUrUrVrjs zCursorFetchStrategy.fetchall)F)N) rrrrrrrrrrrrrUrUrUrVrs rcsreZdZdZdZdddZeddZd d Zd d Z fd dZ fddZ dddZ dddZ ddZZS)r aA cursor fetch strategy with row buffering behavior. This strategy buffers the contents of a selection of rows before ``fetchone()`` is called. This is to allow the results of ``cursor.description`` to be available immediately, when interfacing with a DB-API that requires rows to be consumed before this information is available (currently psycopg2, when used with server-side cursors). The pre-fetching behavior fetches only one row initially, and then grows its buffer size by a fixed amount with each successive need for additional rows up the ``max_row_buffer`` size, which defaults to 1000:: with psycopg2_engine.connect() as conn: result = conn.execution_options( stream_results=True, max_row_buffer=50 ).execute(text("select * from table")) .. versionadded:: 1.4 ``max_row_buffer`` may now exceed 1000 rows. .. seealso:: :ref:`psycopg2_execution_options` )_max_row_buffer _rowbuffer_bufsize_growth_factorr>NcCsX|dd|_|dk r||_nt|d|_||_|rLt|j|j|_n|j|_dS)Nr ir) getrrrrrrminr)rTrexecution_optionsr r rUrUrVrsz'BufferedRowCursorFetchStrategy.__init__cCst|j|jjSrQ)r cursorrr)rrrUrUrVcreatesz%BufferedRowCursorFetchStrategy.createc Cs|j}z |dkr|}n ||}Wn0tk rV}z||||W5d}~XYnX|s`dSt||_|jr||j krt |j ||j|_dS)z*this is currently used only by fetchone().rN) rrrrrrrrrrr)rTrrrZnew_rowsrrUrUrV _buffer_rowss   z+BufferedRowCursorFetchStrategy._buffer_rowscCsd|_||_|_dSr)rrrrrUrUrVrsz(BufferedRowCursorFetchStrategy.yield_percs|jt||dSrQrclearsuperrrrgrUrVrs z)BufferedRowCursorFetchStrategy.soft_closecs|jt||dSrQrr"r#rrr$rUrVrs z)BufferedRowCursorFetchStrategy.hard_closeFc Csh|js^||||js^z|j|dWn0tk rX}z||||W5d}~XYnXdS|jSr)rr rrrpopleft)rTrrrrrUrUrVrs  z'BufferedRowCursorFetchStrategy.fetchonec s|dkr|||S|jt}d}||krz|||}Wn0tk rp}z||||W5d}~XYnX|s|d}n |fddtt|tD}|r| |S)NFTcsg|] }qSrUr&rrbrUrVr\sz.) rrrorrrextendrrr) rTrrrZlbcloserrresrUr(rVrs"    z(BufferedRowCursorFetchStrategy.fetchmanyc Csdz.t|jt|}|j||WStk r^}z||||W5d}~XYnXdSrQ)rrrr"rrr)rTrrretrrUrUrVrs z'BufferedRowCursorFetchStrategy.fetchall)r>N)F)N)rrrrrrrrr rrrrrr __classcell__rUrUr$rVr zs     r cs^eZdZdZdZdddZddZfdd Zfd d Zdd dZ dddZ ddZ Z S) FullyBufferedCursorFetchStrategyzA cursor strategy that buffers rows fully upon creation. Used for operations where a result is to be delivered after the database conversation can not be continued, such as MSSQL INSERT...OUTPUT after an autocommit. )rrNcCs0||_|dk rt||_nt||_dSrQ)rrrrr)rTrZalternate_descriptionr rUrUrVr sz)FullyBufferedCursorFetchStrategy.__init__cCsdSrQrUrrUrUrVrsz*FullyBufferedCursorFetchStrategy.yield_percs|jt||dSrQr!rr$rUrVrs z+FullyBufferedCursorFetchStrategy.soft_closecs|jt||dSrQr%rr$rUrVrs z+FullyBufferedCursorFetchStrategy.hard_closeFcCs$|jr|jS|j|ddSdSr)rr&rrrUrUrVrs  z)FullyBufferedCursorFetchStrategy.fetchonecsJ|dkr|||S|jfddtt|tD}|sF||S)Ncsg|] }qSrUr'rr(rUrVr\+sz>FullyBufferedCursorFetchStrategy.fetchmany..)rrrrror)rTrrrrrUr(rVr&s  z*FullyBufferedCursorFetchStrategy.fetchmanycCs|j}t|_||SrQ)rrrr)rTrrr-rUrUrVr0s z)FullyBufferedCursorFetchStrategy.fetchall)NN)F)N) rrrrrrrrrrrrr.rUrUr$rVr/s     r/c@sfeZdZdZdZdddZddZdd Zd d Ze d d Z e ddZ e ddZ e ddZ dS)_NoResultMetaDatarUFNcCstd|dS)NzJThis result object does not return rows. It has been closed automatically.)rr)rTrrUrUrVr<s z&_NoResultMetaData._we_dont_return_rowscCs |dSrQr)rTrarrUrUrVrBsz _NoResultMetaData._index_for_keycCs |dSrQr1rSrUrUrVrEsz$_NoResultMetaData._metadata_for_keyscCs |dSrQr1)rTrarUrUrVrHsz_NoResultMetaData._reducecCs |dSrQr1r[rUrUrVrCKsz_NoResultMetaData._keymapcCs |dSrQr1r[rUrUrVrKOsz_NoResultMetaData._key_to_indexcCs |dSrQr1r[rUrUrVrDSsz_NoResultMetaData._processorscCs |dSrQr1r[rUrUrVraWsz_NoResultMetaData.keys)N)rrrrrNrrrrpropertyrCrKrDrarUrUrUrVr07s    r0zIteratorResult[Any]rXcCstttg}||SrQ)rr0iterr)itrUrUrVnull_dml_result_sr5cseZdZUdZdZded<eZdZded<dZ ded<d Z d ed <d ed <ded<ded<d dddddZ ddZ dWddZ eddZeddZddZd d!Zed"d#Zd$d%Zd&d'Zd(d)Zed*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zejd6d7d8d9Zed:d;Z edd?Z"d@dAZ#dXdBdCZ$dDdEZ%dYdGdHZ&dIdJZ'dKdLdMfdNdO Z(dPd7dQdRZ)e*d6dSdTdUdVZ+Z,S)Z CursorResulta+A Result that is representing state from a DBAPI cursor. .. versionchanged:: 1.4 The :class:`.CursorResult`` class replaces the previous :class:`.ResultProxy` interface. This classes are based on the :class:`.Result` calling API which provides an updated usage model and calling facade for SQLAlchemy Core and SQLAlchemy ORM. Returns database rows via the :class:`.Row` class, which provides additional API features and behaviors on top of the raw data returned by the DBAPI. Through the use of filters such as the :meth:`.Result.scalars` method, other kinds of objects may also be returned. .. seealso:: :ref:`tutorial_selecting_data` - introductory material for accessing :class:`_engine.CursorResult` and :class:`.Row` objects. )rrrr_echor z.Union[CursorResultMetaData, _NoResultMetaData]rFrM _soft_closedrTr)rr,rrrr(r r)rrrc s||_|j|_|j|_||_|j|_|jjo4|j|_}|dk r| ||}t t ||j |j|jrtt|j fdd}|n|r|jjjfdd|_fdd}|}n}|d|n|jdkst|j|_dS) Ncs |SrQrU)raw_data) _make_rowsentinel_filterrUrV _sliced_rowsz*CursorResult.__init__.._sliced_rowcsdt||S)NzRow %r)sql_utilZ _repr_rowr)logrUrV_log_rowsz'CursorResult.__init__.._log_rowcs |SrQrUr>)r@ sliced_rowrUrV _make_row_2sz*CursorResult.__init__.._make_row_2Z _row_getterr)rrrrZroot_connectionr r7ZengineZ_should_log_debug_init_metadata functoolspartialrZ_effective_processorsrKZ_num_sentinel_colsoperator itemgetterslice _log_debugZ_row_logging_fnZ_set_memoized_attributern_no_result_metadatar) rTrrrZechometadatar<rBZmake_rowrU)r@r:r?r;rArVrs@    zCursorResult.__init__cCs|jrp|j}|jr|j}nt||}|jr0||_|jddsh|jrh|j|jj krh|j |j k rh| |}||_ nt|||_ }|jr|jdtdd|D|S)NZ _result_disable_adapt_to_contextFzCol %rcss|]}|dVqdS)rNrU)rZrrUrUrVrsz.CursorResult._init_metadata..)rZ_cached_metadatarBrIrrrZ cache_hitrZ CACHE_HITrrrrr7r rItuple)rTrrrrKrUrUrVrCs<     zCursorResult._init_metadatacCsl|s |js|r|jrdS|r4d|_|j||jn|j||j|jsh|j}d|_|j|d|_dS)a\Soft close this :class:`_engine.CursorResult`. This releases all DBAPI cursor resources, but leaves the CursorResult "open" from a semantic perspective, meaning the fetchXXX() methods will continue to return empty results. This method is called automatically when: * all result rows are exhausted using the fetchXXX() methods. * cursor.description is None. This method is **not public**, but is documented in order to clarify the "autoclose" process used. .. seealso:: :meth:`_engine.CursorResult.close` NT)r8rrrrrr Z_safe_close_cursor)rTrrrUrUrVrs zCursorResult._soft_closecCsB|jjstdn&|jjs(tdn|jjr:td|jjS)aReturn the value of :attr:`_engine.CursorResult.inserted_primary_key` as a row contained within a list; some dialects may support a multiple row form as well. .. note:: As indicated below, in current SQLAlchemy versions this accessor is only useful beyond what's already supplied by :attr:`_engine.CursorResult.inserted_primary_key` when using the :ref:`postgresql_psycopg2` dialect. Future versions hope to generalize this feature to more dialects. This accessor is added to support dialects that offer the feature that is currently implemented by the :ref:`psycopg2_executemany_mode` feature, currently **only the psycopg2 dialect**, which provides for many rows to be INSERTed at once while still retaining the behavior of being able to return server-generated primary key values. * **When using the psycopg2 dialect, or other dialects that may support "fast executemany" style inserts in upcoming releases** : When invoking an INSERT statement while passing a list of rows as the second argument to :meth:`_engine.Connection.execute`, this accessor will then provide a list of rows, where each row contains the primary key value for each row that was INSERTed. * **When using all other dialects / backends that don't yet support this feature**: This accessor is only useful for **single row INSERT statements**, and returns the same information as that of the :attr:`_engine.CursorResult.inserted_primary_key` within a single-element list. When an INSERT statement is executed in conjunction with a list of rows to be INSERTed, the list will contain one row per row inserted in the statement, however it will contain ``None`` for any server-generated values. Future releases of SQLAlchemy will further generalize the "fast execution helper" feature of psycopg2 to suit other dialects, thus allowing this accessor to be of more general use. .. versionadded:: 1.4 .. seealso:: :attr:`_engine.CursorResult.inserted_primary_key` 1Statement is not a compiled expression construct.2Statement is not an insert() expression construct.z9Can't call inserted_primary_key when returning() is used.)rrrrisinsertZ_is_explicit_returninginserted_primary_key_rowsr[rUrUrVrP!s.z&CursorResult.inserted_primary_key_rowscCs,|jjrtd|j}|r$|dSdSdS)aReturn the primary key for the row just inserted. The return value is a :class:`_result.Row` object representing a named tuple of primary key values in the order in which the primary key columns are configured in the source :class:`_schema.Table`. .. versionchanged:: 1.4.8 - the :attr:`_engine.CursorResult.inserted_primary_key` value is now a named tuple via the :class:`_result.Row` class, rather than a plain tuple. This accessor only applies to single row :func:`_expression.insert` constructs which did not explicitly specify :meth:`_expression.Insert.returning`. Support for multirow inserts, while not yet available for most backends, would be accessed using the :attr:`_engine.CursorResult.inserted_primary_key_rows` accessor. Note that primary key columns which specify a server_default clause, or otherwise do not qualify as "autoincrement" columns (see the notes at :class:`_schema.Column`), and were generated using the database-side default, will appear in this list as ``None`` unless the backend supports "returning" and the insert statement executed with the "implicit returning" enabled. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an insert() construct. zuThis statement was an executemany call; if primary key returning is supported, please use .inserted_primary_key_rows.rN)r executemanyrrrP)rTZikprUrUrVinserted_primary_key_s!z!CursorResult.inserted_primary_keycCsH|jjstdn0|jjs(tdn|jjr8|jjS|jjdSdS)aReturn the collection of updated parameters from this execution. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an update() construct. rMz2Statement is not an update() expression construct.rN)rrrrisupdaterQcompiled_parametersr[rUrUrVlast_updated_paramss z CursorResult.last_updated_paramscCsH|jjstdn0|jjs(tdn|jjr8|jjS|jjdSdS)aReturn the collection of inserted parameters from this execution. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an insert() construct. rMrNrN)rrrrrOrQrTr[rUrUrVlast_inserted_paramss z!CursorResult.last_inserted_paramscCs|jjS)aReturn a list of rows each containing the values of default columns that were fetched using the :meth:`.ValuesBase.return_defaults` feature. The return value is a list of :class:`.Row` objects. .. versionadded:: 1.4 )rreturned_default_rowsr[rUrUrVreturned_defaults_rowss z#CursorResult.returned_defaults_rowscCsV|}ddtt|t|D}|j|j|_td|d|_||S)aReturn a new :class:`.CursorResult` that "horizontally splices" together the rows of this :class:`.CursorResult` with that of another :class:`.CursorResult`. .. tip:: This method is for the benefit of the SQLAlchemy ORM and is not intended for general use. "horizontally splices" means that for each row in the first and second result sets, a new row that concatenates the two rows together is produced, which then becomes the new row. The incoming :class:`.CursorResult` must have the identical number of rows. It is typically expected that the two result sets come from the same sort order as well, as the result rows are spliced together based on their position in the result. The expected use case here is so that multiple INSERT..RETURNING statements (which definitely need to be sorted) against different tables can produce a single result that looks like a JOIN of those two tables. E.g.:: r1 = connection.execute( users.insert().returning( users.c.user_name, users.c.user_id, sort_by_parameter_order=True ), user_values ) r2 = connection.execute( addresses.insert().returning( addresses.c.address_id, addresses.c.address, addresses.c.user_id, sort_by_parameter_order=True ), address_values ) rows = r1.splice_horizontally(r2).all() assert ( rows == [ ("john", 1, 1, "foo@bar.com", 1), ("jack", 2, 2, "bar@bat.com", 2), ] ) .. versionadded:: 2.0 .. seealso:: :meth:`.CursorResult.splice_vertically` cSs g|]\}}t|t|qSrU)rL)rZr1r2rUrUrVr\sz4CursorResult.splice_horizontally..Nr ) _generatezipr_raw_row_iteratorrr{r/r_reset_memoizationsrTrrcloneZ total_rowsrUrUrVsplice_horizontallys<  z CursorResult.splice_horizontallycCs:|}t|t|}td|d|_||S)aReturn a new :class:`.CursorResult` that "vertically splices", i.e. "extends", the rows of this :class:`.CursorResult` with that of another :class:`.CursorResult`. .. tip:: This method is for the benefit of the SQLAlchemy ORM and is not intended for general use. "vertically splices" means the rows of the given result are appended to the rows of this cursor result. The incoming :class:`.CursorResult` must have rows that represent the identical list of columns in the identical order as they are in this :class:`.CursorResult`. .. versionadded:: 2.0 .. seealso:: :meth:`.CursorResult.splice_horizontally` Nr[)r\rr^r/rr_r`rUrUrVsplice_verticallys zCursorResult.splice_verticallycCsF|jr|jjdt|tt|j|_t d|d|_ | |S)arewind this result back to the given rowset. this is used internally for the case where an :class:`.Insert` construct combines the use of :meth:`.Insert.return_defaults` along with the "supplemental columns" feature. zCursorResult rewound %d row(s)Nr[) r7rr rIrorrBrrqr/rr_rTrrUrUrV_rewind4s  zCursorResult._rewindcCs.|jjrtd|jj}|r&|dSdSdS)axReturn the values of default columns that were fetched using the :meth:`.ValuesBase.return_defaults` feature. The value is an instance of :class:`.Row`, or ``None`` if :meth:`.ValuesBase.return_defaults` was not used or if the backend does not support RETURNING. .. seealso:: :meth:`.ValuesBase.return_defaults` zlThis statement was an executemany call; if return defaults is supported, please use .returned_defaults_rows.rN)rrQrrrWrdrUrUrVreturned_defaultsTszCursorResult.returned_defaultscCs |jS)zReturn ``lastrow_has_defaults()`` from the underlying :class:`.ExecutionContext`. See :class:`.ExecutionContext` for details. )rlastrow_has_defaultsr[rUrUrVrgosz!CursorResult.lastrow_has_defaultscCs6|jjstdn|jjs.|jjs.td|jjS)aMReturn ``postfetch_cols()`` from the underlying :class:`.ExecutionContext`. See :class:`.ExecutionContext` for details. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an insert() or update() construct. rM>Statement is not an insert() or update() expression construct.)rrrrrOrSpostfetch_colsr[rUrUrVriys zCursorResult.postfetch_colscCs6|jjstdn|jjs.|jjs.td|jjS)aLReturn ``prefetch_cols()`` from the underlying :class:`.ExecutionContext`. See :class:`.ExecutionContext` for details. Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed statement is not a compiled expression construct or is not an insert() or update() construct. rMrh)rrrrrOrS prefetch_colsr[rUrUrVrjs zCursorResult.prefetch_colscCs|jjS)zReturn ``supports_sane_rowcount`` from the dialect. See :attr:`_engine.CursorResult.rowcount` for background. )rsupports_sane_rowcountr[rUrUrVrksz#CursorResult.supports_sane_rowcountcCs|jjS)zReturn ``supports_sane_multi_rowcount`` from the dialect. See :attr:`_engine.CursorResult.rowcount` for background. )rsupports_sane_multi_rowcountr[rUrUrVrlsz)CursorResult.supports_sane_multi_rowcountrrXc CsFz |jjWStk r@}z|j||j|W5d}~XYnXdS)aReturn the 'rowcount' for this result. The primary purpose of 'rowcount' is to report the number of rows matched by the WHERE criterion of an UPDATE or DELETE statement executed once (i.e. for a single parameter set), which may then be compared to the number of rows expected to be updated or deleted as a means of asserting data integrity. This attribute is transferred from the ``cursor.rowcount`` attribute of the DBAPI before the cursor is closed, to support DBAPIs that don't make this value available after cursor close. Some DBAPIs may offer meaningful values for other kinds of statements, such as INSERT and SELECT statements as well. In order to retrieve ``cursor.rowcount`` for these statements, set the :paramref:`.Connection.execution_options.preserve_rowcount` execution option to True, which will cause the ``cursor.rowcount`` value to be unconditionally memoized before any results are returned or the cursor is closed, regardless of statement type. For cases where the DBAPI does not support rowcount for a particular kind of statement and/or execution, the returned value will be ``-1``, which is delivered directly from the DBAPI and is part of :pep:`249`. All DBAPIs should support rowcount for single-parameter-set UPDATE and DELETE statements, however. .. note:: Notes regarding :attr:`_engine.CursorResult.rowcount`: * This attribute returns the number of rows *matched*, which is not necessarily the same as the number of rows that were actually *modified*. For example, an UPDATE statement may have no net change on a given row if the SET values given are the same as those present in the row already. Such a row would be matched but not modified. On backends that feature both styles, such as MySQL, rowcount is configured to return the match count in all cases. * :attr:`_engine.CursorResult.rowcount` in the default case is *only* useful in conjunction with an UPDATE or DELETE statement, and only with a single set of parameters. For other kinds of statements, SQLAlchemy will not attempt to pre-memoize the value unless the :paramref:`.Connection.execution_options.preserve_rowcount` execution option is used. Note that contrary to :pep:`249`, many DBAPIs do not support rowcount values for statements that are not UPDATE or DELETE, particularly when rows are being returned which are not fully pre-buffered. DBAPIs that dont support rowcount for a particular kind of statement should return the value ``-1`` for such statements. * :attr:`_engine.CursorResult.rowcount` may not be meaningful when executing a single statement with multiple parameter sets (i.e. an :term:`executemany`). Most DBAPIs do not sum "rowcount" values across multiple parameter sets and will return ``-1`` when accessed. * SQLAlchemy's :ref:`engine_insertmanyvalues` feature does support a correct population of :attr:`_engine.CursorResult.rowcount` when the :paramref:`.Connection.execution_options.preserve_rowcount` execution option is set to True. * Statements that use RETURNING may not support rowcount, returning a ``-1`` value instead. .. seealso:: :ref:`tutorial_update_delete_rowcount` - in the :ref:`unified_tutorial` :paramref:`.Connection.execution_options.preserve_rowcount` N)rrowcountrrrrrTrrUrUrVrms L zCursorResult.rowcountc CsFz |jWStk r@}z|j||j|W5d}~XYnXdS)a0Return the 'lastrowid' accessor on the DBAPI cursor. This is a DBAPI specific method and is only functional for those backends which support it, for statements where it is appropriate. It's behavior is not consistent across backends. Usage of this method is normally unnecessary when using insert() expression constructs; the :attr:`~CursorResult.inserted_primary_key` attribute provides a tuple of primary key values for a newly inserted row, regardless of database backend. N)rZ get_lastrowidrrrrrnrUrUrV lastrowid s zCursorResult.lastrowidcCs|jjS)aqTrue if this :class:`_engine.CursorResult` returns zero or more rows. I.e. if it is legal to call the methods :meth:`_engine.CursorResult.fetchone`, :meth:`_engine.CursorResult.fetchmany` :meth:`_engine.CursorResult.fetchall`. Overall, the value of :attr:`_engine.CursorResult.returns_rows` should always be synonymous with whether or not the DBAPI cursor had a ``.description`` attribute, indicating the presence of result columns, noting that a cursor that returns zero rows still has a ``.description`` if a row-returning statement was emitted. This attribute should be True for all results that are against SELECT statements, as well as for DML statements INSERT/UPDATE/DELETE that use RETURNING. For INSERT/UPDATE/DELETE statements that were not using RETURNING, the value will usually be False, however there are some dialect-specific exceptions to this, such as when using the MSSQL / pyodbc dialect a SELECT is emitted inline in order to retrieve an inserted primary key value. )rrNr[rUrUrVrN szCursorResult.returns_rowscCs|jjS)alTrue if this :class:`_engine.CursorResult` is the result of a executing an expression language compiled :func:`_expression.insert` construct. When True, this implies that the :attr:`inserted_primary_key` attribute is accessible, assuming the statement did not include a user defined "returning" construct. )rrOr[rUrUrV is_insert<s zCursorResult.is_insertccs*|jj}|||j}|dkrq&|VqdSrQrrr)rTrrrUrUrV_fetchiter_implJs  zCursorResult._fetchiter_implcCs|j||j|SrQrq)rTrrUrUrV_fetchone_implSszCursorResult._fetchone_implcCs|j||jSrQ)rrrr[rUrUrV_fetchall_implVszCursorResult._fetchall_implNcCs|j||j|SrQ)rrr)rTrrUrUrV_fetchmany_implYszCursorResult._fetchmany_implcCs|SrQ)rrr[rUrUrVr^\szCursorResult._raw_row_iteratorz Result[Any]zMergedResult[Any])othersrPcs2tj|}|jjr.tdd|f|D|_|S)Ncss|]}td|jVqdS)rN)rrm)rZrrUrUrVrbsz%CursorResult.merge..)r#mergerZ _has_rowcountsumrm)rTrvZ merged_resultr$rUrVrw_s   zCursorResult.mergercCs|jdddS)aClose this :class:`_engine.CursorResult`. This closes out the underlying DBAPI cursor corresponding to the statement execution, if one is still present. Note that the DBAPI cursor is automatically released when the :class:`_engine.CursorResult` exhausts all available rows. :meth:`_engine.CursorResult.close` is generally an optional method except in the case when discarding a :class:`_engine.CursorResult` that still has additional rows pending for fetch. After this method is called, it is no longer valid to call upon the fetch methods, which will raise a :class:`.ResourceClosedError` on subsequent use. .. seealso:: :ref:`connections_toplevel` TrN)rr[rUrUrVr+hszCursorResult.closer')rrPcCs||_|j||j||SrQ)Z _yield_perrrr)rTrrUrUrVr~szCursorResult.yield_per)F)F)N)-rrrrrr_NO_RESULT_METADATArJr8rZ _is_cursorrrCrr2rPrRrUrVrXrbrcrerfrgrirjrkrlrZmemoized_propertyrmrorNrprrrsrtrur^rwr+rrr.rUrUr$rVr6esb    ?/ % = - N      Q      r6)ar __future__rrrDrFtypingrrrrrrr r r r r rrrrrrrrrrrrrrsqlrrr=Zsql.baserZ sql.compilerrr r!r"r#Z sql.type_apir$r%Z util.typingr&r'baser(rr)Z interfacesr*r+r,r-r.r/r0r1r2r3r4r5r7rr8r9r;r=r?rArrZ_CursorKeyMapRecTyperLrrBrrrrrZ_NO_CURSOR_DMLrZ_DEFAULT_FETCHr r/r0ryr5r6Z ResultProxyrUrUrUrV s                                                            >X7%&