L i+ UdZddlmZddlZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z dd lm Z dd lm Z dd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!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'l!m0Z0dd(l1m2Z2dd)l1m3Z3ej&rNdd*l4m5Z5dd+l6m7Z7dd,l8m9Z9dd-l8m:Z:dd.l8m;Z;dd/l8mZ>dd2lm?Z?dd3lm@Z@dd4lmAZAdd5lmBZBdd6l.mCZCed7e8ZDdZEd9eFd:< dZGd;eFd<< dZHd=eFd>< d?ZId@eFdA< dBZJdCeFdD< dEZKdFeFdG< dHZLdIeFdJ< eeeMeMe eeNeNedKeeNfZOedLeOfZPeeMeMe eeNeNedKeNfZQGdMdNeZRGdOdPZSGdQdReSZTGdSdTeTZUeUZVGdUdVeTZWeWZXGdWdXeSZYeYZZGdYdZeYZ[Gd[d\eYZ\Gd]d^eZ]e]Z^dbd_Z_Gd`daeeDZ`e`Zay)czNDefine cursor-specific result set constructs including :class:`.CursorResult`.) annotationsN)Any)cast)ClassVar)Dict)Iterable)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]r3cbeZdZUdZdZded<ded<ded<d ed <d ed <d ed <dZded<d'dZd(dZ d)dZ d*dZ d+dZ d,dZ d-dZ d.dZdZdZdZdZe d/ d0dZdZes d1 d2dZd Zd1d3d!Zd"Z d4d#Zd$Zd%Zy&)5CursorResultMetaDataz"Result metadata for DBAPI cursors.) _keymap _processors_keys_keymap_by_result_column_idx _tuplefilter_translated_indexes_safe_for_cache _unpickled _key_to_index_CursorKeyMapTyperFr4rGz#Optional[Dict[int, _KeyMapRecType]]rIboolrMrLOptional[List[int]]rKTzClassVar[bool] returns_rowsc||jvSN)rFselfkeys ^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py_has_keyzCursorResultMetaData._has_keysdll""ct|j|jDcgc]}|j|tc}Scc}w)N)extra)rrHrFr;rUs rX _for_freezez CursorResultMetaData._for_freezes9# JJ<@JJGS4<<$Z0G  GsA c|jj|j} || _|| _|| _|| _|| _|| _|| _|| _ |j|t| _ | SrT) __class____new__rMrGrHrFrJrKrLrI_make_key_to_indexr9rN) rV unpickled processorskeyskeymap tuplefiltertranslated_indexessafe_for_cachekeymap_by_result_column_idxnew_objs rX_make_new_metadataz'CursorResultMetaData._make_new_metadatast..((8&(  *&8#"0/J, $ 7 7 IrZcJ|jrJ|j|jdgt|jzdd|j j Dcic]\}}||dddz|ddzc}}|j|j|jScc}}w)Nrr@rTrB)rbrcrfrgrerdrhri) rJrkrMlenrGrFitemsrHrLrI)rVrWvalues rX_remove_processorsz'CursorResultMetaData._remove_processorss$$$$&&oovD$4$4 55##',,"4"4"6CU1QZ')E!"I55//(,(I(I'  sBc>|jrJt|j}t|j}|j |jj Dcic]'\}}||d ||vr|d|znd|d|zg|dd)c}}|j|j|j|jzdd|j|jz||j|jDcic] }|t|c}Scc}}wcc}w)Nrrr)rbrcrfrgrdrerhri) rJdictrFrmrHupdaternrkrMrGrLvaluesr:)rVotherreoffsetrWrometadata_entrys rX_splice_horizontallyz)CursorResultMetaData._splice_horizontallys9$$$$dll#TZZ #(--"5"5"7 C!8/Cv4Ea6)!!Hv% 12Y    &&oo''%*;*;;#ekk)//'-mmo)"23^C)'   ,)s !,D ;Dc Jt|j|}|Dcgc] }|t }}|Dcgc] }|t }}|jr|Dcgc]}|j|}}t |}t |Dcgc]\}}|f|ddz} }}| Dcic] }|t|} }| jd| D|j|j|j|||| |j|jScc}wcc}wcc}wcc}}wcc}w)Nrc3HK|]}|txsdD]}||f yw)N)r;).0new_reces rX z/CursorResultMetaData._reduce.. s; Z(.B L   ")rbrcrdrfrgrerhri) list_metadata_for_keysr9r=rKr enumeratersrkrMrGrLrI) rVrdrecsrecindexesnew_keysidxtupindexnew_recsres rX_reducezCursorResultMetaData._reduces3D++D12,01S3x=11=ABcs=1BB  # #@GHt//4HGH7#9B4I:5#UHs12w&II5=>c#m$c)>>   #  &&oo''&//(,(I(I'  %2BII>sD DDDD c |jr|jjs|S|jj}|j}trt |t jsJ||ur|S|J|j}|7|jjDcic] }|t|c}x}|_|jrJ|jtj|jt!|j"Dcic]\}}||vr|||c}}|j$|j&dd|j(|j*|jScc}wcc}}w)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)rerbrcrfrgrdrhri)compiled_result_columns statementinvoked_statementr isinstancer ClauseElementrIrFrtr:rJrkr' dict_unionr_all_selected_columnsrMrGrHrL)rVcontextcompiled_statementrkeymap_by_positionrwrnews rX_adapt_to_contextz&CursorResultMetaData._adapt_to_contextsw'7'7'G'GK$--77#55 /1G1GH HH !2 2K ,,,">>  % '+ll&9&9&;F"23^CF  !B $$$$&&$$ %.)??% S00 +C00 oo''#//(,(I(I#'  Fs EE"c |j}d|_d|_dx|_|_|j r|j \}}}}}t |} n dx}x}x} x}x}}|j|||| ||||} | D cgc] } | t c} |_ d|_ | r+| D cic] } | t| } } t | | k7ri} t}| D]O} | tf| txsdzD]2}| t}| j!|||k7s"|j#|4Q| D cic] } | tr| tD] }||vr||  "c}} |_| j'|Dcic] }|ddg||ddfc}n/| D cic]} | tr| tD]}|| c}} |_|j$j'| n| D cic] } | t| c} |_| sZ|j(rN|j$j'| D cic])} | t*r| t*|j$| t+c} |j-|j$t|_ycc} wcc} wcc}} wcc}wcc}} wcc} wcc} w)NFr{)rrJrKrLrMresult_column_structrm_merge_cursor_descriptionrArGrIr=setr?r;r9 setdefaultaddrFrs_translate_colnamerCrarN)rVparentcursor_descriptionrresult_columnscols_are_orderedtextual_orderedad_hoc_textualloose_column_name_matching num_ctx_colsrawrwby_key index_by_keydupesrWrobj_elems rX__init__zCursorResultMetaData.__init__\s3 .. #' 166t  ' ',,   *~.L   N -   !; ,,        &  @C -;N< ( -1) '*"}-~=F 6{l*02 &)+N ./? @B&z28b +-X6(223<C!IIcN+++. &%j1$2:$>  !u, n,    $)dD"c3dCC+. &%j1$2:$>  !n,    LL   ' '*"}-~=DL : : LL   +. '%o6 #?3T\\&}56 "44T\\8LU D  s*;I'!I,'%I1$I7!I< J .Jc |r|r|s|t|k(r~|D cgc]} | d c} |_d|_t|D cgc]H\} } | | | t| t | t |j| t| t || ddfJc} } S|s|r)t||k(rd|_|j|||} n7|rd|_|j||||} nd|_|j||} | D cgc]$\} } }}}}}| | ||||j||||f&c}}}}}} } Scc} wcc} } wcc}}}}}} } w)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. rTrNF) rmrHrLrr#r"r$get_result_processorr%_merge_textual_cols_by_position_merge_cols_by_name_merge_cols_by_none)rVrrrrrrrrelemr rmap_entry raw_iteratorridxcursor_colname mapped_typecoltypeobj untranslateds rXrz.CursorResultMetaData._merge_cursor_descriptionsF  #$6 77.<=d$q'=DJ$(D (1'@$Cz*w'/000"7+"#34*3/2   (3'9#:l#J'+$#CC/   (-$#77&".   (-$#77/  0")" #""00#^W!  s>`s D3A D8)D>c#0K|j}|j}|jr |jnd}d}g|_t |D]I\}}|d} |d} |r || \} }|r|| } |jj | || || fKyw)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)dialectrrequires_name_normalizenormalize_namerHrappend) rVrrrtranslate_colnamerrrrcolnamers rX_colnames_from_descriptionz/CursorResultMetaData._colnames_from_descriptions//#66&-&E&EG " "4   !"45 6HC!fG!fG (9'(B%(1 JJ  g &w g5 5 6sBBc#Kt|}|t|kDr#tjd|t|fzt}|j ||D]{\}}}} ||krP||} | t } |} | t } | d|vrtjd| dz|j| dntj} d} d} || || | | |f}yw)NzVNumber of columns in textual SQL (%d) is smaller than number of columns requested (%d)rz8Duplicate column expression requested in textual SQL: %r) rmrwarnrrr#r%rInvalidRequestErrorrrNULLTYPE)rVrrrrseenrrrrctx_recrrrs rXrz4CursorResultMetaData._merge_textual_cols_by_positions>* #01 1 II@%7!89:  u , ,W6H I  N    \!(-j)%g. q6T>11-/21v6Q &// tWk7CM M+ NsCCc#K|j||}|j||D]'\}}}} ||} | d} | d} | d} || || | | |f)y#t$rtj} d} d} Y-wxYww)Nrrr<)_create_description_match_maprKeyErrorrr)rVrrrr match_maprrrrrrrresult_columns_idxs rXrz(CursorResultMetaData._merge_cols_by_names66 6  , ,W6H I       0#G, aj%aj %,QZ"" !  *&// %)" *s'-A5AA5A2/A51A22A5c :i}t|D]\}}|t}||vr||\}}} } |||tz| |f||<n|t|t|t|f||<|sR|tD]-} |j | |t|t|t|f/|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. )rr$r#r"r%r) clsrrdrrrWe_namee_obje_typee_ridxr_keys rXrz2CursorResultMetaData._create_description_match_maps  $N3 JD$'(Cax 12#-vvj)9!964G#w-j)94=$O#) "*-ELLgZ(8$w-N% .rZc#vK|j||D] \}}}}|d|tj|d|f"ywrT)rrr)rVrrrrrrs rXrz(CursorResultMetaData._merge_cols_by_nones[  , ,W6H I      !!   s79c|rh|jr0t|tjrt j d|t j dt j|z|y)Nz9Row was unpickled; lookup by ColumnElement is unsupportedz.Could not locate column in row for column '%s')rMrr ColumnElementrNoSuchColumnErrorrstring_or_unprintable)rVrWerrraiseerrs rX _key_fallbackz"CursorResultMetaData._key_fallback/so??z#x7M7M'N//) //H44S9: rZc@tjd|tz)Nz"NH$L,1'0'%)'  ''R" HL  !4 @D   " &E:!: /:( ( @rZrEceZdZUdZdZdZded< d dZ d dZ ddZ d dd Z d dd Z dd Z dd Z y)ResultFetchStrategyzQDefine a fetching strategy for a result object. .. versionadded:: 1.4 r{N!Optional[_DBAPICursorDescription]alternate_cursor_descriptionctrTNotImplementedErrorrVresult dbapi_cursors rX soft_closezResultFetchStrategy.soft_close "##rZctrTrr s rX hard_closezResultFetchStrategy.hard_closer rZcyrTr{rVr r nums rX yield_perzResultFetchStrategy.yield_pers rZctrTrrVr r rs rXfetchonezResultFetchStrategy.fetchone "##rZctrTrrVr r sizes rX fetchmanyzResultFetchStrategy.fetchmanyrrZctrTrr s rXfetchallzResultFetchStrategy.fetchalls "##rZc|rTr{rVr r rs rXhandle_exceptionz$ResultFetchStrategy.handle_exceptions  rZr rr Optional[DBAPICursor]rNoner rr r"rrrr#rr rr r-rrPrrrTr rr r-rrrrr rr r-rrr rr r"r BaseExceptionrr )rrrrrrrr rrrrrr r{rZrXrrs+IFJ "CJ$'$7L$ $ $'$7L$ $ !,   ! $!$"$ $ $# $!$"$ $ $$!$"$ $!,   rZrc>eZdZdZdZdZdZd dZd dZdZ d d Z y) 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{cyrTr{r s rXr z NoCursorFetchStrategy.soft_close rZcyrTr{r s rXrz NoCursorFetchStrategy.hard_closer-rZc&|j|dSrT _non_resultrs rXrzNoCursorFetchStrategy.fetchones--rZNc&|j|gSrTr0rs rXrzNoCursorFetchStrategy.fetchmany++rZc&|j|gSrTr0r s rXrzNoCursorFetchStrategy.fetchallr3rZctrTrrVr defaultrs rXr1z!NoCursorFetchStrategy._non_results !##rZrrT) rrrrrr rrrrr1r{rZrXr+r+s,I  .,,$rZr+ceZdZdZdZddZy)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{NcJ|jrtjd||S)NzThis result object is closed.)closedrResourceClosedErrorr6s rXr1z$NoCursorDQLFetchStrategy._non_results) ==))/ NrZrTrrrrrr1r{rZrXr9r9sIrZr9ceZdZdZdZddZy)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{Ncj|jjrJ|jj|yrT) _metadatarR_we_dont_return_rowsr6s rXr1z$NoCursorDMLFetchStrategy._non_results+##0000--c2rZrTr=r{rZrXr?r? sI3rZr?ceZdZdZdZ d dZ d dZ d dZ d dZ d ddZ d dd Z dd Z y)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{ct|_yrT_NO_CURSOR_DQLcursor_strategyr s rXr zCursorFetchStrategy.soft_close* "0rZct|_yrTrFr s rXrzCursorFetchStrategy.hard_close/rIrZcV|jj|dd||jyrT) connection_handle_dbapi_exceptionrrs rXr z$CursorFetchStrategy.handle_exception4s' 11 t\6>> rZcTt|d|itjd|_y)Nmax_row_bufferr)initial_buffer growth_factor)BufferedRowCursorFetchStrategy collectionsdequerHrs rXrzCursorFetchStrategy.yield_per>s, "@  s #&,,. " rZc |j}||j||S#t$r}|j|||Yd}~yd}~wwxYwNhard)r _soft_closer)r )rVr r rrowr~s rXrzCursorFetchStrategy.fetchoneKsU  ;'')C{"" "3J ;  ! !&, : : ;s%( AA  ANc ||j}n|j|}|s|j|S#t$r}|j|||Yd}~yd}~wwxYwrT)rrYr)r )rVr r rlr~s rXrzCursorFetchStrategy.fetchmanyYsc ;| **, **40""$H ;  ! !&, : : ;s7: A AA c |j}|j|S#t$r}|j|||Yd}~yd}~wwxYwrT)rrYr)r )rVr r rowsr~s rXrzCursorFetchStrategy.fetchallksK  ;((*D    K ;  ! !&, : : ;s!$ A AA r!r(r$rr%rTr&r') rrrrrr rr rrrrr{rZrXrDrD sI0'07L0 0 0'07L0 0  ! ,       !  ,      "! ;! ;" ; ; ;$# ;!;"; ; ;$ ;! ;" ; ;rZrDcneZdZdZdZ d dZedZdZdZ fdZ fdZ d d Z dd Z d ZxZS)rRaA 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_factorc|jdd|_|||_n)tj|j d|_||_|r&t|j|j |_y|j|_y)NrOir) getr`rarSrTrrcminrb)rVr execution_optionsrQrPs rXrz'BufferedRowCursorFetchStrategy.__init__sv 1445EtL  %,DO)// 0F0Fq0IJDO+  4 4d6I6IJDM 00DMrZcVt|j|jjSrT)rRcursorrrg)rr s rXcreatez%BufferedRowCursorFetchStrategy.creates#- MM NN , ,  rZc|j} |dkr|j}n|j|}syt j ||_|jr9||jkr)t|j||jz|_yyy#t$r}|j |||Yd}~d}~wwxYw)z*this is currently used only by fetchone().rN) rbrrr)r rSrTrarcr`rf)rVr r rnew_rowsr~s rX _buffer_rowsz+BufferedRowCursorFetchStrategy._buffer_rowss}} ;ax'002'11$7 %++H5   4$*>*>#>$$dT-@-@&@DM$?   ;  ! !&, : : ;s'B B>!B99B>c.d|_|x|_|_yr)rcr`rbrs rXrz(BufferedRowCursorFetchStrategy.yield_pers/22t}rZcZ|jjt| ||yrTraclearsuperr rVr r r_s rXr z)BufferedRowCursorFetchStrategy.soft_close"  6<0rZcZ|jjt| ||yrTrarqrrrrss rXrz)BufferedRowCursorFetchStrategy.hard_closertrZc|js2|j|||js |j|y|jj S#t$r}|j |||Yd}~yd}~wwxYwrV)rarmrYr)r popleft)rVr r rr~s rXrz'BufferedRowCursorFetchStrategy.fetchones{   fl 3??C&&J&7&&((%C))&,BBCsA A?"A::A?c||j||S|j}t|}d}||kDr, |j||z }|sd}n|j | tt|t|D cgc]} |j} } |r|j| S#t $r}|j |||Yd}~nd}~wwxYwcc} w)NFT) rrarmrextendr)r rrfrxrY) rVr r rrblbcloserr~rress rXrz(BufferedRowCursorFetchStrategy.fetchmanys <==6 6 __ W "9 #",,TBY7 EIIcN%*3tSW+=%>?rzz|??      ! ?%%flA>> ?@sB,?C, C5C  Cc  t|jt|jz}|jj|j |S#t $r}|j |||Yd}~yd}~wwxYwrT)rrarrqrYr)r )rVr r retr~s rXrz'BufferedRowCursorFetchStrategy.fetchallsn ;t'$|/D/D/F*GGC OO ! ! #    J ;  ! !&, : : ;sAA B&A>>B)r@NrrT)rrrrrrrrjrmrr rrrr __classcell__r_s@rXrRrR{sT6PI  1(  (311 )0;rZrRcdeZdZdZdZ d d dZdZfdZfdZd dZ d dZ d Z xZ 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. )rarc||_|tj||_y|Jtj|j |_yrT)rrSrTrar)rVr alternate_descriptionrPs rXrz)FullyBufferedCursorFetchStrategy.__init__ sL -B)  %)//?DO+ ++)// 0E0E0GHDOrZcyrTr{rs rXrz*FullyBufferedCursorFetchStrategy.yield_perr-rZcZ|jjt| ||yrTrprss rXr z+FullyBufferedCursorFetchStrategy.soft_closertrZcZ|jjt| ||yrTrvrss rXrz+FullyBufferedCursorFetchStrategy.hard_close rtrZct|jr|jjS|j|yrV)rarxrYrs rXrz)FullyBufferedCursorFetchStrategy.fetchone$s0 ????**, ,   J  /rZc||j||S|j}tt|t |Dcgc]}|j }}|s|j |Scc}wrT)rrarrfrmrxrY)rVr r rr{rr^s rXrz*FullyBufferedCursorFetchStrategy.fetchmany+sd <==6 6 __&+Cc"g,>&?@ @@     AsA.cp|j}tj|_|j|SrT)rarSrTrY)rVr r rs rXrz)FullyBufferedCursorFetchStrategy.fetchall5s,oo%++- rZ)NN)r r"rrrPzOptional[Iterable[Any]]rrT) rrrrrrrr rrrrrrs@rXrrs]?I DH26 I+ I A I0 I 11rZrcneZdZdZdZd dZdZdZdZe dZ e d Z e d Z e d Z y) _NoResultMetaDatar{FNc.tjd|)NzJThis result object does not return rows. It has been closed automatically.)rr<)rVrs rXrBz&_NoResultMetaData._we_dont_return_rowsAs%% 0  rZc$|jyrTrB)rVrdrs rXrz _NoResultMetaData._index_for_keyG !!#rZc$|jyrTrrUs rXrz$_NoResultMetaData._metadata_for_keysJrrZc$|jyrTr)rVrds rXrz_NoResultMetaData._reduceMrrZc$|jyrTrrVs rXrFz_NoResultMetaData._keymapP !!#rZc$|jyrTrrs rXrNz_NoResultMetaData._key_to_indexTrrZc$|jyrTrrs rXrGz_NoResultMetaData._processorsXrrZc$|jyrTrrs rXrdz_NoResultMetaData.keys\rrZrT)rrrrrRrBrrrpropertyrFrNrGrdr{rZrXrr<spIL $$$$$$$$$$$rZrc`tttg}|j|SrT)rriterrY)its rXnull_dml_resultrds%,->-@$r(KBNN IrZceZdZUdZdZded<eZdZded<dZ ded<d Z d ed <d ed <ded<ded< d/dZ dZ d0dZ edZedZdZdZedZdZdZdZedZdZdZd Zd!Zd"Zej<d1d#Zed$Z ed%Z!ed&Z"d'Z#d0d(Z$d)Z%d2d*Z&d+Z'd3fd, Z(d4d-Z)e*d5d.Z+xZ,S)6 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. )rrrirH_echorLz.Union[CursorResultMetaData, _NoResultMetaData]rAFrP _soft_closedr;Tr+rr.rrrHr*rLc ||_|j|_|j|_||_|j|_|j j xr|jjx|_}||j||}tjt||j|j |jr2t!j"t%|j  fd}| n |r5|jj j& fd |_ fd}|}n }|j+d|y|jdk(sJ|j,|_y)Nc |SrTr{)raw_data _make_rowsentinel_filters rX _sliced_rowz*CursorResult.__init__.._sliced_rows$_X%>??rZc@dtj||S)NzRow %r)sql_util _repr_row)rZlogs rX_log_rowz'CursorResult.__init__.._log_rows("4"4S"9:JrZc |SrTr{)rZr sliced_rows rX _make_row_2z*CursorResult.__init__.._make_row_2s#JsO44rZ _row_getterr)rrrirHroot_connectionrLrengine_should_log_debug_init_metadata functoolspartialr_effective_processorsrN_num_sentinel_colsoperator itemgetterslice _log_debug_row_logging_fn_set_memoized_attribute_no_result_metadatarA)rVrrHrechometadatarrmake_rowrrrrrs @@@@@rXrzCursorResult.__init__sQ   nn .!11 OO ! ! Hgnn&F&F&H  T  ) **74FGH"))..&& I))"*"5"575556#@) & ll--88(0$5'%  ( ( A--2 22!55DNrZc2|jr|j}|jr |j}nt||}|jr||_|jj ddsW|j rK|j|jjur)|j|jur|j|}||_ nt||x|_ }|jr,|jj!dt#d|D|S)N _result_disable_adapt_to_contextFzCol %rc3&K|] }|d yw)rNr{)r|rs rXrz.CursorResult._init_metadata..sA!As)r_cached_metadatarErLrgrer cache_hitr CACHE_HITrrrrArrLrtuple)rVrrrrs rXrzCursorResult._init_metadatas   ''H((#44/6HI++08H-"--116,,%%)B)BB&&g.G.GG#55g>%DN)=() DNX ::    ) )%A.@AA rZcn|s |js|r |jry|r.d|_|jj||jn&|jj ||j|js6|j}d|_|j j|d|_yy)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)rr;rHrrir rL_safe_close_cursor)rVrXris rXrYzCursorResult._soft_closes,**  DK  + +D$++ >  + +D$++ >  [[FDK OO . .v 6 $D  !rZc0|jjstjd|jjstjd|jj rtjd|jj S)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.)rrrrisinsert_is_explicit_returninginserted_primary_key_rowsrs rXrz&CursorResult.inserted_primary_key_rows&s\||$$))C &&))D \\ 0 0))  ||555rZc|jjrtjd|j}|r|dSy)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 executemanyrrr)rVikps rXinserted_primary_keyz!CursorResult.inserted_primary_keydsFB << # #))2  ,, q6MrZc8|jjstjd|jjstjd|jj r|jj S|jj dS)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. rz2Statement is not an update() expression construct.r)rrrrisupdatercompiled_parametersrs rXlast_updated_paramsz CursorResult.last_updated_params||$$))C &&))D \\ % %<<33 3<<33A6 6rZc8|jjstjd|jjstjd|jj r|jj S|jj dS)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. rrr)rrrrrrrrs rXlast_inserted_paramsz!CursorResult.last_inserted_paramsrrZc.|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_rowsrs rXreturned_defaults_rowsz#CursorResult.returned_defaults_rowss||111rZc|j}tt|jt|jDcgc]\}}t |t |z}}}|j j |j |_td||_|j|Scc}}w)akReturn 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` NrP) _generatezipr_raw_row_iteratorrrArxrrH_reset_memoizations)rVrucloner1r2 total_rowss rXsplice_horizontallyz CursorResult.splice_horizontallysn T++-.U,,./ B "Ib !   //>>uO @ %!  !!#  s!Cc|j}t|jt|jz}td||_|j |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)rrrrrHr)rVrurrs rXsplice_verticallyzCursorResult.splice_verticallysd( $0023d  # # %7  !A %!  !!# rZc|jr/|jjjdt |t t |jj|_td||_ |j|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) rrrLrrmrrErArprrHrrVr^s rX_rewindzCursorResult._rewind4sz :: LL # # . .0#d)  $..     @      " rZc|jjrtjd|jj}|r|dSy)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)rrrrrrs rXreturned_defaultszCursorResult.returned_defaultsTsJ << # #))D  ||11 7NrZc6|jjS)zReturn ``lastrow_has_defaults()`` from the underlying :class:`.ExecutionContext`. See :class:`.ExecutionContext` for details. )rlastrow_has_defaultsrs rXrz!CursorResult.lastrow_has_defaultsos||0022rZc|jjstjd|jjs+|jj stjd|jj S)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.)rrrrrrpostfetch_colsrs rXrzCursorResult.postfetch_colsysl||$$))C &&t||/D/D))( ||***rZc|jjstjd|jjs+|jj stjd|jj S)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. rr)rrrrrr prefetch_colsrs rXrzCursorResult.prefetch_colssl||$$))C &&t||/D/D))( ||)))rZc.|jjS)zReturn ``supports_sane_rowcount`` from the dialect. See :attr:`_engine.CursorResult.rowcount` for background. )rsupports_sane_rowcountrs rXrz#CursorResult.supports_sane_rowcounts||222rZc.|jjS)zReturn ``supports_sane_multi_rowcount`` from the dialect. See :attr:`_engine.CursorResult.rowcount` for background. )rsupports_sane_multi_rowcountrs rXrz)CursorResult.supports_sane_multi_rowcounts||888rZc |jjS#t$r-}|jj ||j |d}~wwxYw)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)rrowcountr)rHr rirVr~s rXrzCursorResult.rowcountsGX <<(( (   1 1$ Q G  s A(A  Ac |jjS#t$r1}|jj ||j |Yd}~yd}~wwxYw)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)r get_lastrowidr)rHr rirs rX lastrowidzCursorResult.lastrowid sL  H<<--/ / H  1 1$ Q G G Hs A'AAc.|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. )rArRrs rXrRzCursorResult.returns_rows s4~~***rZc.|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. )rrrs rX is_insertzCursorResult.is_insert<s||$$$rZc#nK|jj} |||j}|y|wrTrHrri)rVrrZs rX_fetchiter_implzCursorResult._fetchiter_implJs<''004-C{I s35cP|jj||j|SrTr )rVrs rX_fetchone_implzCursorResult._fetchone_implSs!##,,T4;; KKrZcN|jj||jSrT)rHrrirs rX_fetchall_implzCursorResult._fetchall_implVs##,,T4;;??rZcP|jj||j|SrT)rHrri)rVrs rX_fetchmany_implzCursorResult._fetchmany_implYs!##--dDKKFFrZc"|jSrT)r rs rXrzCursorResult._raw_row_iterator\s##%%rZct||}|jjrt d|f|zD|_|S)Nc3HK|]}td|jyw)rN)rr)r|r s rXrz%CursorResult.merge..bs&)(&1::)r)rrmerger _has_rowcountsumr)rVothers merged_resultr_s rXrzCursorResult.merge_sG v. << % %%()#g.)&M "rZc(|jdy)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` TrWN)rYrs rXr}zCursorResult.closehs( d#rZcb||_|jj||j||SrT) _yield_perrHrri)rVrs rXrzCursorResult.yield_per~s* &&tT[[#> rZ)rr+rHrrrr)rrrT)rz Result[Any]rzMergedResult[Any])rr)rrrr))-rrrrrr_NO_RESULT_METADATArrr; _is_cursorrrrYrrrrrrrrrrrrrrrrmemoized_propertyrrrRrr r rrrrr}r rrrs@rXrrjs(I>=-L$FDJ $$ ((=6(=6-=6> =6~-^#%J;6;6z++Z7,7, 2 2GR@@43+.*.39 OObHH(++6 % %L@G&$,rZr)rzIteratorResult[Any])br __future__rrSrrtypingrrrrrr r r r r rrrrrr rrrrrrrZrrrsqlrrrsql.baser sql.compilerr!r"r#r$r% sql.type_apir&r' util.typingr(r)baser*r7r+ interfacesr,r-r.r/r0r1r2r3r4r5r6r7r9rr:r;r=r?rArCrr_CursorKeyMapRecTyperOrrErr+r9rGr?_NO_CURSOR_DMLrD_DEFAULT_FETCHrRrrrrr ResultProxyr{rZrXr-s|#  " "(""-"%+"%!  03'#,%&# '(3 T*#$Z#/ J  z !*   j3& SMI () SM J(<<= %I ()   F @>F @R;;|$/$<4,*+ 34 3 *+U;-U;p%&C;%8C;L8':8v"$"$J() X 6":X v rZ