U a@s6dZddlZddlZddlmZddlmZddlmZddlmZddlm Z d d l m Z d d l m Z d d l mZd d l mZd d l m Zd dlmZd dlmZd dlmZd dlmZd dlmZe dZdZdZd ZdZdZdZdZ GdddeZ!Gddde!Z"Gddde#Z$Gddde$Z%Gd d!d!e%Z&e&Z'Gd"d#d#e%Z(e(Z)Gd$d%d%e$Z*e*Z+Gd&d'd'e*Z,Gd(d)d)e*Z-Gd*d+d+eZ.Gd,d-d-e.Z/e.Z0e/Z1Gd.d/d/e#Z2Gd0d1d1e2eZ3Gd2d3d3e3Z4e4Z5Gd4d5d5e5Z6Gd6d7d7e5Z7Gd8d9d9e Z8Gd:d;d;e5Z9dS)Esz4CursorResultMetaData._for_freeze..)extra)rrr*r$r*r% _for_freezeBsz CursorResultMetaData._for_freezecst|}dd|D}dd|D}jrBfdd|D}t|}jj}j|_j|_||_||_ ||_ddt |D}dd|D|_ |j dd|D|S) NcSsg|] }|tqSr$)MD_INDEXr)recr$r$r%r+Ksz0CursorResultMetaData._reduce..cSsg|] }|tqSr$ MD_LOOKUP_KEYr/r$r$r%r+Lscsg|]}j|qSr$)r)r)idxr*r$r%r+OscSs"g|]\}}|f|ddqSrNr$)r)indexr0r$r$r%r+ZscSsi|]}|t|qSr$r1r/r$r$r% ^sz0CursorResultMetaData._reduce..cSs$i|]}|tpdD] }||qqS)r$r')r)Znew_recer$r$r%r6ds ) list_metadata_for_keysrr __class____new__rrrr enumeraterupdate)r"keysZrecsZindexesZnew_keystupZ new_metadataZnew_recsr$r*r%_reduceHs, zCursorResultMetaData._reducec Cs|jjs |S|jj}|j}||kr&|S|j|j}t|j|_|j}t |j D]4\}}z ||}Wnt k rxYqPX||j|<qP|j |_ |j |_ |jrtd|_d|_|j|_|j|_|j|_|S)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. N)compiled_result_columns statementinvoked_statementr;r<dictrrr=Z_all_selected_columnsKeyErrorrrrAssertionErrorrrr) r"contextZcompiled_statementrEZmdZkeymap_by_positionr3newr0r$r$r%_adapt_to_contextms0     z&CursorResultMetaData._adapt_to_contextc s|j}|j}d_d_|j_d_|jrD|j\}}}}t|} nd}}} }}|||| |||} i_ dd| D_ |j rdd| D_ t dd| D} | rvt| | kr`i} t| D]`} | tf| tpdD]D}js t|tjr |}| t}| |||kr|qqΈj fdd| D| d dDnj d d| Dj | | s|jrj fd d| DdS) NFcSsg|] }|tqSr$) MD_PROCESSORr)metadata_entryr$r$r%r+sz1CursorResultMetaData.__init__..cSsi|]}|t|qSr$MD_RESULT_MAP_INDEXrMr$r$r%r6sz1CursorResultMetaData.__init__..cSsg|]}|t|fqSr$r1rMr$r$r%r+sr$cs2g|]*}|tr|tD]}|kr||fqqSr$r7r)rNZobj_elem)dupesr$r%r+s  cSsi|]}|ddd|fqS)Nr$r$r(r$r$r%r6scSs*g|]"}|tr|tD] }||fqqSr$r7rQr$r$r%r+s  cs*g|]"}|tr|tj|tfqSr$)MD_UNTRANSLATEDrr2rMr*r$r%r+s  )rIdialectrrrrZresult_column_structlen_merge_cursor_descriptionrrrBrrFsetMD_RENDERED_NAMEr' isinstancer string_typeslowerr. setdefaultaddr>_translate_colname)r"parentcursor_descriptionrIrTresult_columnscols_are_orderedtextual_orderedloose_column_name_matching num_ctx_colsrawby_keyZ index_by_keyrNr#r3r$)rRr"r%__init__s         zCursorResultMetaData.__init__c sjj|rP|rP|sP|tkrPdd|D|_d|_fddt|DS|rjd|_||}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 te 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|] }|dqSrr$)r)elemr$r$r%r+gszBCursorResultMetaData._merge_cursor_description..Tc sXg|]P\}}|||ts&|tn|t|t|t|t|ddfqSr4)rrr[rget_result_processorr)r)r3Z rmap_entryrrIr`r$r%r+ns Fc s6g|].\}}}}}}}|||||||||fqSr$)rk)r)r3ridxZcursor_colname mapped_typecoltypeobj untranslated)rIr$r%r+s( N) rTrrUrrr=_merge_textual_cols_by_position_merge_cols_by_name_merge_cols_by_none) r"rIr`rarerbrcrdZ raw_iteratorr$rlr%rVsJA   z.CursorResultMetaData._merge_cursor_descriptionc cs|j}|j}|j}|jr|jnd}|jr.|jnd}d}g|_t|D]f\} } | d} | d} |rh|| } |rx|| \} }|r|| } |j | |s| } | | || fVqDdS)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) rTrr^Zdescription_encodingZ_description_decoderZrequires_name_normalizenormalize_namerr=appendr[) r"rIr`rTrZtranslate_colnameZdescription_decoderrurqr3r0colnameror$r$r%_colnames_from_descriptions0  z/CursorResultMetaData._colnames_from_descriptionccs|r t|nd}|t|kr2td|t|ft}|||D]\}}}} ||kr||} | t} |} | t} | d|krtd| d| | dnt j } d} d} || || | | |fVqDdS)NzVNumber of columns in textual SQL (%d) is smaller than number of columns requested (%d)rz8Duplicate column expression requested in textual SQL: %r) rUr warnrWrxrrr InvalidRequestErrorr]r NULLTYPE)r"rIr`rareseenr3rwrqroctx_recrprmrnr$r$r%rrs<    z4CursorResultMetaData._merge_textual_cols_by_positionc cs|j}|j}||||}|||D]h\}} } } z || } Wn"tk r`tj} d}d}YnX| d}| d} | d}||| | | || fVq&dS)Nrrr)rTr_create_description_match_maprxrGr r{)r"rIr`rardrTrZ match_mapr3rwrqror}rnrpZresult_columns_idxr$r$r%rss<   z(CursorResultMetaData._merge_cols_by_nameFc Csi}t|D]\}}|t}|s(|}||krZ||\}} } } || |t| |f||<n|t|t|t|f||<|r |tD]$} || |t|t|t|fqq |S)zwhen matching cursor.description to a set of names that are present in a Compiled object, as is the case with TextualSelect, get all the names we expect might match those in cursor.description. )r=rr[rrrr\) clsrarrddrmrjr#Ze_nameZe_obje_typeZe_ridxZr_keyr$r$r%r~)s  z2CursorResultMetaData._create_description_match_mapccs4|||D]"\}}}}|d|tj|d|fVq dSr)rxr r{)r"rIr`r3rwrqror$r$r%rtSs z(CursorResultMetaData._merge_cols_by_nonecCs,|r$tjtdt||dndSdS)N.Could not locate column in row for column '%s'Zreplace_context)r raise_r NoSuchColumnErrorstring_or_unprintable)r"r#errraiseerrr$r$r% _key_fallbackdsz"CursorResultMetaData._key_fallbackcCstd|tdS)Nz.r)rGrrargs)r"r?rr$r*r%_indexes_for_keyssz&CursorResultMetaData._indexes_for_keysc cs|D]}t|jjkr|j|}z|j|}Wn6tk rb}zt||jd|W5d}~XYnX|d}|dkr~| ||VqdSr) rr;__mro__rrrGrrrr)r"r?r#r0rr5r$r$r%r:s  & z'CursorResultMetaData._metadata_for_keyscCs(dd|jD|j|j|j|jdS)NcSs8i|]0\}}t|tjtjr||t|tt|fqSr$)rYr rZ int_typesr.rP _UNPICKLED)r)r#r0r$r$r%r6sz5CursorResultMetaData.__getstate__..)rrrrr)ritemsrrrrr*r$r$r% __getstate__sz!CursorResultMetaData.__getstate__cCsddtt|dD|_|d|_dd|jD|_|d|_|d|_|drp|d|_t |j|_ n d|_|_ dS) NcSsg|]}dqSrr$)r)_r$r$r%r+sz5CursorResultMetaData.__setstate__..rrcSsi|]}|t|qSr$rOr/r$r$r%r6sz5CursorResultMetaData.__setstate__..rr) rangerUrrvaluesrrrrrr)r"stater$r$r% __setstate__s    z!CursorResultMetaData.__setstate__N)TF)T)T)__name__ __module__ __qualname____doc__ __slots__ returns_rowsr&r-rArKrhrVrxrrrs classmethodr~rtrrrrr:rrr$r$r$r%r-s4 %.*#& )   rc@s2eZdZdZddZd ddZddZd d Zd S) LegacyCursorResultMetaDatar$cCs2|}||jkrtddS||dddk SdS)NzUsing the 'in' operator to test for string or column keys, or integer indexes, in a :class:`.Row` object is deprecated and will be removed in a future release. Use the `Row._fields` or `Row._mapping` attribute, i.e. 'key in row._fields'TF)rr warn_deprecated_20r)r"valuerowr#r$r$r% _containss z$LegacyCursorResultMetaData._containsTcCsh|j}d}t|tjr0||jr$|n|}nt|tjr&|j rz|jrP|j n|j |krz||jrl|j n|j }n>t |dr|jr|j n|j |kr||jr|j n|j }|dk r|t dt fkr|t D]}||rqqd}|dk r&|t t krtjdddntjddd|dkr\|rVtjtdt||dndSn|||<|S)NnamezRetrieving row values using Column objects from a row that was unpickled is deprecated; adequate state cannot be pickled for this to be efficient. This usage will raise KeyError in a future release.z1.4)versionzRetrieving row values using Column objects with only matching names as keys is deprecated, and will raise KeyError in a future release; only Column objects that are explicitly part of the statement object should be used.rr)rrYr rZgetrr[r Z ColumnElementZ _tq_labelhasattrrr'rZ_compare_name_for_resultZwarn_deprecatedrr rr)r"r#rrZmap_resultrpr$r$r%rst      z(LegacyCursorResultMetaData._key_fallbackcCstjddddS)NzUsing non-integer/slice indices on Row is deprecated and will be removed in version 2.0; please use row._mapping[], or the mappings() accessor on the Result object.r) stacklevelr rr!r$r$r%_warn_for_nonint sz+LegacyCursorResultMetaData._warn_for_nonintcCs$||jkrdS||dddk SdS)NTF)rrr!r$r$r%r&(s z#LegacyCursorResultMetaData._has_keyN)T)rrrrrrrr&r$r$r$r%rs  Mrc@sTeZdZdZdZdZddZddZdd Zdd d Z dd dZ ddZ ddZ dS)ResultFetchStrategyzQDefine a fetching strategy for a result object. .. versionadded:: 1.4 r$NcCs tdSrNotImplementedErrorr"r dbapi_cursorr$r$r% soft_close;szResultFetchStrategy.soft_closecCs tdSrrrr$r$r% hard_close>szResultFetchStrategy.hard_closecCsdSrr$r"rrnumr$r$r% yield_perAszResultFetchStrategy.yield_perFcCs tdSrrr"rrrr$r$r%fetchoneDszResultFetchStrategy.fetchonecCs tdSrrr"rrsizer$r$r% fetchmanyGszResultFetchStrategy.fetchmanycCs tdSrr)r"rr$r$r%fetchallJszResultFetchStrategy.fetchallcCs|dSrr$r"rrrr$r$r%handle_exceptionMsz$ResultFetchStrategy.handle_exception)F)N) rrrrralternate_cursor_descriptionrrrrrrrr$r$r$r%r/s  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. r$cCsdSrr$rr$r$r%r\sz NoCursorFetchStrategy.soft_closecCsdSrr$rr$r$r%r_sz NoCursorFetchStrategy.hard_closeFcCs ||dSr _non_resultrr$r$r%rbszNoCursorFetchStrategy.fetchoneNcCs ||gSrrrr$r$r%reszNoCursorFetchStrategy.fetchmanycCs ||gSrrrr$r$r%rhszNoCursorFetchStrategy.fetchallcCs tdSrrr"rdefaultrr$r$r%rksz!NoCursorFetchStrategy._non_result)F)N)N) rrrrrrrrrrrr$r$r$r%rQs  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. r$NcCs$|jrtjtd|dn|SdS)NzThis result object is closed.r)closedr rr ResourceClosedErrorrr$r$r%r|s z$NoCursorDQLFetchStrategy._non_result)Nrrrrrrr$r$r$r%ros 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. r$NcCs|jjr t|j|dSr) _metadatarrH_we_dont_return_rowsrr$r$r%rs z$NoCursorDMLFetchStrategy._non_result)Nrr$r$r$r%rsrc@sPeZdZdZdZddZddZddZd d Zdd d Z dddZ ddZ 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. r$cCs t|_dSr_NO_CURSOR_DQLcursor_strategyrr$r$r%rszCursorFetchStrategy.soft_closecCs t|_dSrrrr$r$r%rszCursorFetchStrategy.hard_closecCs|j|dd||jdSr) connectionZ_handle_dbapi_exceptionrIrr$r$r%rsz$CursorFetchStrategy.handle_exceptioncCst|d|itdd|_dS)Nmax_row_bufferr)initial_buffer growth_factor)BufferedRowCursorFetchStrategy collectionsdequerrr$r$r%rs zCursorFetchStrategy.yield_perFc CsXz"|}|dkr|j|d|WStk rR}z||||W5d}~XYnXdSNhard)r _soft_close BaseExceptionr)r"rrrrr8r$r$r%rs zCursorFetchStrategy.fetchoneNc Csdz.|dkr|}n ||}|s*||WStk r^}z||||W5d}~XYnXdSr)rrrr)r"rrrlr8r$r$r%rs  zCursorFetchStrategy.fetchmanyc CsLz|}||WStk rF}z||||W5d}~XYnXdSr)rrrr)r"rrrowsr8r$r$r%rs zCursorFetchStrategy.fetchall)F)N) rrrrrrrrrrrrr$r$r$r%rs rcsreZdZdZdZdddZeddZd d Zd d Z fd dZ fddZ dddZ dddZ ddZZS)raA 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_factorrNcCsX|dd|_|dk r||_nt|d|_||_|rLt|j|j|_n|j|_dS)Nrir) rrrrrrrminr)r"rexecution_optionsrrr$r$r%rhsz'BufferedRowCursorFetchStrategy.__init__cCst|j|jjSr)rcursorrIr)rrr$r$r%createsz%BufferedRowCursorFetchStrategy.createc Cs|j}z |dkr|}n ||}Wn0tk rV}z||||W5d}~XYnX|s`dSt||_|jr||j krt |j ||j|_dS)Nr) rrrrrrrrrrr)r"rrrZnew_rowsr8r$r$r% _buffer_rowss   z+BufferedRowCursorFetchStrategy._buffer_rowscCsd|_||_|_dSr)rrrrr$r$r%r'sz(BufferedRowCursorFetchStrategy.yield_percs |jtt|||dSr)rclearsuperrrrr;r$r%r+s   z)BufferedRowCursorFetchStrategy.soft_closecs |jtt|||dSr)rrrrrrrr$r%r1s   z)BufferedRowCursorFetchStrategy.hard_closeFc Csh|js^||||js^z|j|dWn0tk rX}z||||W5d}~XYnXdS|jSr)rrrrrpopleft)r"rrrr8r$r$r%r7s  z'BufferedRowCursorFetchStrategy.fetchonec Cs|dkr|||St|j}t|}||krxz||||Wn0tk rv}z||||W5d}~XYnX|d|}t ||d|_|Sr) rr9rrUextendrrrrr)r"rrrbufZlbr8r$r$r%rBs    z(BufferedRowCursorFetchStrategy.fetchmanyc Csdz.t|jt|}|j||WStk r^}z||||W5d}~XYnXdSr)r9rrrrrr)r"rrretr8r$r$r%rRs z'BufferedRowCursorFetchStrategy.fetchall)rN)F)N)rrrrrrhrrrrrrrrr __classcell__r$r$rr%rs     rcs^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||_dSr)rrrrr)r"rZalternate_descriptionrr$r$r%rhgsz)FullyBufferedCursorFetchStrategy.__init__cCsdSrr$rr$r$r%rpsz*FullyBufferedCursorFetchStrategy.yield_percs |jtt|||dSr)rrrrrrrr$r%rss   z+FullyBufferedCursorFetchStrategy.soft_closecs |jtt|||dSr)rrrrrrrr$r%rys   z+FullyBufferedCursorFetchStrategy.hard_closeFcCs$|jr|jS|j|ddSdSr)rrrrr$r$r%rs  z)FullyBufferedCursorFetchStrategy.fetchonecCsN|dkr|||St|j}|d|}t||d|_|sJ||Sr)rr9rrrr)r"rrrrrr$r$r%rs   z*FullyBufferedCursorFetchStrategy.fetchmanycCs|j}t|_||Sr)rrrr)r"rrrr$r$r%rs z)FullyBufferedCursorFetchStrategy.fetchall)NN)F)N) rrrrrrhrrrrrrrr$r$rr%r\s     rc@sNeZdZdZdZdddZddZdd Zd d Ze d d Z e ddZ dS)_NoResultMetaDatar$FNcCstjtd|ddS)NzJThis result object does not return rows. It has been closed automatically.r)r rr r)r"rr$r$r%rs z&_NoResultMetaData._we_dont_return_rowscCs |dSrr)r"r?rr$r$r%rsz _NoResultMetaData._index_for_keycCs |dSrrr!r$r$r%r:sz$_NoResultMetaData._metadata_for_keyscCs |dSrr)r"r?r$r$r%rAsz_NoResultMetaData._reducecCs |dSrrr*r$r$r%rsz_NoResultMetaData._keymapcCs |dSrrr*r$r$r%r?sz_NoResultMetaData.keys)N) rrrrrrrr:rApropertyrr?r$r$r$r%rs  rc@seZdZeddZdS)_LegacyNoResultMetaDatacCstdgS)NzCalling the .keys() method on a result set that does not return rows is deprecated and will raise ResourceClosedError in SQLAlchemy 2.0.rr*r$r$r%r?sz_LegacyNoResultMetaData.keysN)rrrrr?r$r$r$r%rsrc@seZdZdZdZdZdZdZddZddZ d(dd Z e d d Z e d d Z ddZddZe ddZe ddZddZddZddZddZddZejd d!Ze d"d#Ze d$d%Ze d&d'ZdS))BaseCursorResultz'Base class for database result objects.NFc s||_|j|_|j|_||_|j|_|jjo4|j|_}|dk r|rf|jjj fdd|_ nd| ||}|j }|j }|j}|j} t||||| rfdd} n} |d| n|j|_dS)Ncsdt||S)NzRow %r)sql_utilZ _repr_row)r)logr$r%log_rowsz*BaseCursorResult.__init__..log_rowcs|}||Srr$)rZmade_row) _make_rowrr$r%make_rowsz+BaseCursorResult.__init__..make_rowZ _row_getter)rIrTrrZroot_connectionr_echoZengineZ_should_log_debug _log_debugZ_row_logging_fn_init_metadatarr _process_rowZ_default_key_style functoolspartialZ_set_memoized_attribute_no_result_metadatar) r"rIrr`ZechometadataZkeymapZ processorsZ process_rowZ key_stylerr$)rrrr%rhs<   zBaseCursorResult.__init__cCs|jr~|jjr|jjj}n|||}|jr4||j_|j}|rv|jrv|j|jjkrv|j ddsv|j |j k rv| |}||_n||||_}|jr|jdtdd|D|S)NZ _result_disable_adapt_to_contextFzCol %rcss|]}|dVqdS)rNr$)r)xr$r$r% ,sz2BaseCursorResult._init_metadata..)rBZ_cached_metadatarI_cursor_metadatarrCZ cache_hitrTZ CACHE_HITrrrDrErKrrrrtuple)r"rIr`rrBr$r$r%rs@      zBaseCursorResult._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. .. versionadded:: 1.0.0 .. seealso:: :meth:`_engine.CursorResult.close` NT) _soft_closedrrrrrrZ_safe_close_cursor)r"rrr$r$r%r0s zBaseCursorResult._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.)rIrBr rzisinsertZ_is_explicit_returninginserted_primary_key_rowsr*r$r$r%r Ws-z*BaseCursorResult.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)rI executemanyr rzr )r"Zikpr$r$r%inserted_primary_keys!z%BaseCursorResult.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. r z2Statement is not an update() expression construct.rN)rIrBr rzisupdater compiled_parametersr*r$r$r%last_updated_paramss z$BaseCursorResult.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. r r rN)rIrBr rzr r rr*r$r$r%last_inserted_paramss z%BaseCursorResult.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 )rIreturned_default_rowsr*r$r$r%returned_defaults_rowss z'BaseCursorResult.returned_defaults_rowscCs.|jjrtd|jj}|r&|dSdSdS)aReturn 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. .. versionadded:: 0.9.0 .. seealso:: :meth:`.ValuesBase.return_defaults` zlThis statement was an executemany call; if return defaults is supported, please use .returned_defaults_rows.rN)rIr r rzr)r"rr$r$r%returned_defaultssz"BaseCursorResult.returned_defaultscCs |jS)zReturn ``lastrow_has_defaults()`` from the underlying :class:`.ExecutionContext`. See :class:`.ExecutionContext` for details. )rIlastrow_has_defaultsr*r$r$r%rsz%BaseCursorResult.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. r >Statement is not an insert() or update() expression construct.)rIrBr rzr rpostfetch_colsr*r$r$r%r"s zBaseCursorResult.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. r r)rIrBr rzr r prefetch_colsr*r$r$r%r9s zBaseCursorResult.prefetch_colscCs|jjS)zReturn ``supports_sane_rowcount`` from the dialect. See :attr:`_engine.CursorResult.rowcount` for background. )rTsupports_sane_rowcountr*r$r$r%rPsz'BaseCursorResult.supports_sane_rowcountcCs|jjS)zReturn ``supports_sane_multi_rowcount`` from the dialect. See :attr:`_engine.CursorResult.rowcount` for background. )rTsupports_sane_multi_rowcountr*r$r$r%rYsz-BaseCursorResult.supports_sane_multi_rowcountc CsDz |jjWStk r>}z|j||j|W5d}~XYnXdS)a~Return the 'rowcount' for this result. The 'rowcount' reports the number of rows *matched* by the WHERE criterion of an UPDATE or DELETE statement. .. 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* - an UPDATE statement, for example, 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 by default to return the match count in all cases. * :attr:`_engine.CursorResult.rowcount` is *only* useful in conjunction with an UPDATE or DELETE statement. Contrary to what the Python DBAPI says, it does *not* return the number of rows available from the results of a SELECT statement as DBAPIs cannot support this functionality when rows are unbuffered. * :attr:`_engine.CursorResult.rowcount` may not be fully implemented by all dialects. In particular, most DBAPIs do not support an aggregate rowcount result from an executemany call. The :meth:`_engine.CursorResult.supports_sane_rowcount` and :meth:`_engine.CursorResult.supports_sane_multi_rowcount` methods will report from the dialect if each usage is known to be supported. * Statements that use RETURNING may not return a correct rowcount. .. seealso:: :ref:`tutorial_update_delete_rowcount` - in the :ref:`unified_tutorial` N)rIrowcountrrrrr"r8r$r$r%rbs0 zBaseCursorResult.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)rIZ get_lastrowidrrrrrr$r$r% lastrowids zBaseCursorResult.lastrowidcCs|jjS)aiTrue 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. )rrr*r$r$r%rszBaseCursorResult.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. )rIr r*r$r$r% is_inserts zBaseCursorResult.is_insert)F)rrrrZout_parametersrrrrhrrrr rrrrrrrrrrr Zmemoized_propertyrrrrr$r$r$r%rs>10 ' < -      4  rcsleZdZdZeZeZeZ ddZ dddZ ddZ dd d Z d d ZfddZddZeddZZS) CursorResultaHA Result that is representing state from a DBAPI cursor. .. versionchanged:: 1.4 The :class:`.CursorResult` and :class:`.LegacyCursorResult` classes replace the previous :class:`.ResultProxy` interface. These 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. Within the scope of the 1.x series of SQLAlchemy, Core SQL results in version 1.4 return an instance of :class:`._engine.LegacyCursorResult` which takes the place of the ``CursorResult`` class used for the 1.3 series and previously. This object returns rows as :class:`.LegacyRow` objects, which maintains Python mapping (i.e. dictionary) like behaviors upon the object itself. Going forward, the :attr:`.Row._mapping` attribute should be used for dictionary behaviors. .. seealso:: :ref:`coretutorial_selecting` - introductory material for accessing :class:`_engine.CursorResult` and :class:`.Row` objects. ccs*|jj}|||j}|dkrq&|VqdSrrrr)r"rrr$r$r%_fetchiter_impls  zCursorResult._fetchiter_implFcCs|j||j|Srr!)r"rr$r$r%_fetchone_implszCursorResult._fetchone_implcCs|j||jSr)rrrr*r$r$r%_fetchall_implszCursorResult._fetchall_implNcCs|j||j|Sr)rrr)r"rr$r$r%_fetchmany_implszCursorResult._fetchmany_implcCs|Sr)r"r*r$r$r%_raw_row_iterator szCursorResult._raw_row_iteratorcs<tt|j|}|jj }|r8tdd|f|D|_|S)Ncss|] }|jVqdSr)r)r)rr$r$r%rsz%CursorResult.merge..)rr mergerrsumr)r"ZothersZ merged_resultZsetup_rowcountsrr$r%r' s  zCursorResult.mergecCs|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` TrNrr*r$r$r%closeszCursorResult.closecCs||_|j||j|dSr)Z _yield_perrrr)r"rr$r$r%r,szCursorResult.yield_per)F)N)rrrrrrr_cursor_strategy_cls_NO_RESULT_METADATArr"r#r$r%r&r'r*r rrr$r$rr%r s   r cs>eZdZdZdZeZeZe Z e Z ddZ dfdd ZZS)LegacyCursorResulta Legacy version of :class:`.CursorResult`. This class includes connection "connection autoclose" behavior for use with "connectionless" execution, as well as delivers rows using the :class:`.LegacyRow` row implementation. .. versionadded:: 1.4 FcCs|jdddS)aEClose this :class:`_engine.LegacyCursorResult`. This method has the same behavior as that of :meth:`._engine.CursorResult`, but it also may close the underlying :class:`.Connection` for the case of "connectionless" execution. .. deprecated:: 2.0 "connectionless" execution is deprecated and will be removed in version 2.0. Version 2.0 will feature the :class:`_future.Result` object that will no longer affect the status of the originating connection in any case. 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` :ref:`dbengine_implicit` TrNr)r*r$r$r%r*DszLegacyCursorResult.closecs6|j}tt|j|d|s2|jr2|jr2|jdSr)rrr-r_autoclose_connectionrr*)r"rZ soft_closedrr$r%r^szLegacyCursorResult._soft_close)F)rrrrr.rrrrrr+_LEGACY_NO_RESULT_METADATArr*rrr$r$rr%r-2s r-c@seZdZdZeZdS)BufferedRowResultProxyzA ResultProxy with row buffering behavior. .. deprecated:: 1.4 this class is now supplied using a strategy object. See :class:`.BufferedRowCursorFetchStrategy`. N)rrrrrr+r$r$r$r%r0lsr0c@seZdZdZeZdS)FullyBufferedResultProxyzA result proxy that buffers rows fully upon creation. .. deprecated:: 1.4 this class is now supplied using a strategy object. See :class:`.FullyBufferedCursorFetchStrategy`. N)rrrrrr+r$r$r$r%r1wsr1c@seZdZdZdS)BufferedColumnRowz&Row is now BufferedColumn in all casesN)rrrrr$r$r$r%r2sr2c@seZdZdZeZdS)BufferedColumnResultProxyzA ResultProxy with column buffering behavior. .. versionchanged:: 1.4 This is now the default behavior of the Row and this class does not change behavior in any way. N)rrrrr2rr$r$r$r%r3sr3):rrrrrrrrrrr r Zsqlr r rZsql.baser Z sql.compilerrrrrsymbolrr.rPr'r2rXrLrSrrobjectrrrrrZ_NO_CURSOR_DMLrZ_DEFAULT_FETCHrrrrr,r/rr r-Z ResultProxyr0r1r2r3r$r$r$r%sv                n"<<  \7