c\gdZddlZddlZddlZddlmZm Z ddl Z ddl Z ddl m Zddl mZddl mZddl mZmZdd lmZdd lmZmZmZmZmZdd l m!Z!m"Z"m#Z#m$Z$m%Z%dd l&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.dd l/m0Z0GddeZ1GddeZ2Gdde1Z3Gdde4Z5GddeZ6Gdde1Z7Gdde Z8GddeZ9GddeZ:ed d!Z;eGd&d'e=Z?Gd(d)e>Z@Gd*d+eZAGd,d-eZBGd.d/eCZDGd0d1eZGd2d3ZEdId4ZFGd5d6ZGdId7ZHd8ZId9ZJGd:d;ZK dJd=ZLGd>d?ZMdKd@ZNdAZOdLdCZPdMdDZQdEZRejSdFejTdGzdHzZUdS)NzMiscellaneous goodies for psycopg2 This module is a generic place used to hold little helper functions and classes until a better place in the distribution is found. N) namedtuple OrderedDict) extensions)cursor) connection)adapt quote_ident) lru_cache)REPLICATION_PHYSICALREPLICATION_LOGICALReplicationConnectionReplicationCursorReplicationMessage)jsonJson register_jsonregister_default_jsonregister_default_jsonb)Range NumericRange DateRange DateTimeRangeDateTimeTZRangeregister_range RangeAdapter RangeCaster)register_ipaddresscLeZdZdZfdZfdZdfd ZfdZfdZxZ S) DictCursorBasez%Base class for all dict-like cursors.cd|vr |d}|d=ntdtj|i|d|_d|_||_dS)N row_factoryz;DictCursorBase can't be instantiated without a row factory.F)NotImplementedErrorsuper__init___query_executed _prefetchr")selfargskwargsr" __class__s [/var/lib/jenkins/jobs/Dev/workspace/my-venv/lib/python3.11/site-packages/psycopg2/extras.pyr%zDictCursorBase.__init__Dst F " " /K}%%%MOO O$)&)))$&c|jr t}|jr||js t}|SN)r'r$fetchoner& _build_indexr(resr+s r,r0zDictCursorBase.fetchonePc > %''""$$C        ~ %''""$$C r-Nc|jr!t|}|jr||js!t|}|Sr/)r'r$ fetchmanyr&r1)r(sizer3r+s r,r6zDictCursorBase.fetchmanyYsg > *''##D))C        ~ *''##D))C r-c|jr t}|jr||js t}|Sr/)r'r$fetchallr&r1r2s r,r9zDictCursorBase.fetchallbr4r-c#hK |jr/t}t|}|jr||js/t}t|}|V t|V#t $rYdSwxYwr/)r'r$__iter__nextr&r1 StopIteration)r(r3firstr+s r,r;zDictCursorBase.__iter__ks ~ "gg&&((S # $!!###> "gg&&((S KKK 3ii     FF sBB## B10B1r/) __name__ __module__ __qualname____doc__r%r0r6r9r; __classcell__r+s@r,r r As// ' ' ' ' 'r-r c"eZdZdZfdZxZS)DictConnectionz2A connection that uses `DictCursor` automatically.cz|d|jpttj|i|SNcursor_factory) setdefaultrI DictCursorr$rr(r)r*r+s r,rzDictConnection.cursors=*D,?,M:NNNuww~t.v...r-r?r@rArBrrCrDs@r,rFrF}s><</////////r-rFc@eZdZdZfdZdfd Zdfd ZdZxZS)rKzA cursor that keeps a list of column name -> index mappings__. .. __: https://docs.python.org/glossary.html#term-mapping c\t|d<tj|i|d|_dS)Nr"T)DictRowr$r%r'rLs r,r%zDictCursor.__init__s4 '}$)&)))r-Nc|t|_d|_t||SNT)rindexr&r$executer(queryvarsr+s r,rTzDictCursor.executes. ]] #wwud+++r-c|t|_d|_t||SrR)rrSr&r$callprocr(procnamerWr+s r,rYzDictCursor.callprocs0 ]] #ww$///r-c|jrO|jrJtt|jD]}||j|j|d<d|_dSdSdS)NrF)r& descriptionrangelenrS)r(is r,r1zDictCursor._build_indexsw   )D$4 )3t/0011 7 756 4+A.q122#(D  ) ) ) )r-r/ r?r@rArBr%rTrYr1rCrDs@r,rKrKs  ,,,,,, 000000 )))))))r-rKczeZdZdZdZdZfdZfdZfdZdZ fdZ dd Z d Z d Z fd ZdZdZxZS)rPz6A row object that allow by-column-name access to data._indexcX|j|_dgt|jz|dd<dSr/)rSrdr_r])r(rs r,r%zDictRow.__init__s.l &3v1222QQQr-ct|ttfs |j|}t |Sr/) isinstanceintslicerdr$ __getitem__)r(xr+s r,rjzDictRow.__getitem__s<!c5\**  AAww""1%%%r-ct|ttfs |j|}t ||dSr/)rgrhrirdr$ __setitem__)r(rkvr+s r,rmzDictRow.__setitem__sD!c5\**  AA Aq!!!!!r-cVtjfdjDS)Nc3HK|]}|j|fVdSr/rc.0ngr(s r, z DictRow.items..s8<<1AAdk!n%%&<<<<<.s377a$+a.!!777777r-rvrws`@r,valueszDictRow.valuess0 GG 777774;7777r-Nc8 ||S#t$r|cYSwxYwr/) Exception)r(rkdefaults r,getz DictRow.gets4 7N   NNN s  cDt|Sr/)rrxr{s r,copyz DictRow.copys4::<<(((r-c||jvSr/rc)r(rks r, __contains__zDictRow.__contains__sDKr-cDtSr/)r$ __reduce__)r(r+s r,rzDictRow.__reduce__sww!!###r-cH|dd|jfSr/)rdrr{s r, __getstate__zDictRow.__getstate__s#AAAw ((****r-c:|d|dd<|d|_dSNrrrc)r(datas r, __setstate__zDictRow.__setstate__s"q'QQQ1g r-r/)r?r@rArB __slots__r%rjrmrxr|rrrrrrrrCrDs@r,rPrPs@@I333&&&&& """"" =====!!!88888 )))   $$$$$+++r-rPc"eZdZdZfdZxZS)RealDictConnectionz6A connection that uses `RealDictCursor` automatically.cz|d|jpttj|i|SrH)rJrIRealDictCursorr$rrLs r,rzRealDictConnection.cursors=*D,?,Q>RRRuww~t.v...r-rMrDs@r,rrs>@@/////////r-rc@eZdZdZfdZdfd Zdfd ZdZxZS)raQA cursor that uses a real dict as the base type for rows. Note that this cursor is extremely specialized and does not allow the normal access (using integer indices) to fetched data. If you need to access database rows both as a dictionary and a list, then use the generic `DictCursor` instead of `!RealDictCursor`. cNt|d<tj|i|dS)Nr") RealDictRowr$r%rLs r,r%zRealDictCursor.__init__s/ +}$)&)))))r-Ncdg|_d|_t||SrR)column_mappingr&r$rTrUs r,rTzRealDictCursor.executes+ #wwud+++r-cdg|_d|_t||SrR)rr&r$rYrZs r,rYzRealDictCursor.callprocs- #ww$///r-cd|jr&|jr!d|jD|_d|_dSdSdS)Ncg|] }|d Srrrds r, z/RealDictCursor._build_index..s"B"B"BA1Q4"B"B"Br-F)r&r]rr{s r,r1zRealDictCursor._build_indexsR   )D$4 )"B"B1A"B"B"BD #(D  ) ) ) )r-r/rarDs@r,rrs*****,,,,,, 000000 )))))))r-rc,eZdZdZfdZfdZxZS)rz.A `!dict` subclass representing a data record.c|r.t|dtr|d}|dd}nd}tj|i||3|jr|js||j|t<dSdSr)rg_cursorr$r%r]rr1r)r(r)r*rr+s r,r%zRealDictRow.__init__s  JtAw00 !WF8DDF$)&)))  ! &&*? &##%%% !' 5D     r-ct|vrU|t}t||||t|dz kr|t=dSt||dS)Nr)rr$rmr_)r(keyvaluemappingr+s r,rmzRealDictRow.__setitem__sy $  ;'G GG   e 4 4 4c'llQ&&&% F C'''''r-)r?r@rArBr%rmrCrDs@r,rrsW8866666& ( ( ( ( ( ( ( ( (r-rc"eZdZdZfdZxZS)NamedTupleConnectionz8A connection that uses `NamedTupleCursor` automatically.cz|d|jpttj|i|SrH)rJrINamedTupleCursorr$rrLs r,rzNamedTupleConnection.cursors>*D,?,SCSTTTuww~t.v...r-rMrDs@r,rrs>BB/////////r-rceZdZdZdZdZd fd ZfdZd fd ZfdZ d fd Z fd Z fd Z d Z ed ZxZS)raA cursor that generates results as `~collections.namedtuple`. `!fetch*()` methods will return named tuples instead of regular tuples, so their elements can be accessed both as regular numeric items as well as attributes. >>> nt_cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) >>> rec = nt_cur.fetchone() >>> rec Record(id=1, num=100, data="abc'def") >>> rec[1] 100 >>> rec.data "abc'def" NicVd|_t||Sr/)Recordr$rTrUs r,rTzNamedTupleCursor.execute6s" wwud+++r-cVd|_t||Sr/)rr$ executemanyrUs r,rzNamedTupleCursor.executemany:s$ ww""5$///r-cVd|_t||Sr/)rr$rYrZs r,rYzNamedTupleCursor.callproc>s$ ww$///r-ct}|9|j}||x}|_||SdSr/)r$r0r_make_nt_make)r(tntr+s r,r0zNamedTupleCursor.fetchoneBsT GG     =Bz#'==??2T[88A;;  =r-ct|}|j}||x}|_t t |j|Sr/)r$r6rrlistmapr)r(r7tsrr+s r,r6zNamedTupleCursor.fetchmanyJsT WW  t $ $ [ :#}} .BC"%%&&&r-ct}|j}||x}|_t t |j|Sr/)r$r9rrrrr)r(rrr+s r,r9zNamedTupleCursor.fetchallQsR WW     [ :#}} .BC"%%&&&r-c#LK t}t|}|j}||x}|_||V |t|V%#t $rYdSwxYwr/)r$r;r<rrrr=)r(itrrr+s r,r;zNamedTupleCursor.__iter__Xs !!##BRABz#'==??2T[((1++    )hhtBxx((((( )    FF sBB B#"B#cz|jrtd|jDnd}||S)Nc3&K|] }|dV dS)rNrrs r,ruz,NamedTupleCursor._make_nt..is&33QAaD333333r-r)r]tuple_cached_make_nt)r(rs r,rzNamedTupleCursor._make_nthsB7;7GOe33$"2333333R##C(((r-cg}|D]Y}td|}|ddksd|dcxkrdkrnnd|z}||Ztd|}|S)N_r09fr) _re_cleansubappendr)clsrfieldssrs r, _do_make_ntzNamedTupleCursor._do_make_ntls  A c1%%Ats{{cQqT0000S00000!G MM!     & ) ) r-r/)r?r@rArBr MAX_CACHErTrrYr0r6r9r;r classmethodrrCrDs@r,rr#sFI,,,,,,00000000000''''''''''' )))  [     r-ric,||Sr/)r)rrs r,rr{s ??3  r-c@eZdZdZdZdZdZdZdZfdZ xZ S)LoggingConnectionz~A connection that logs all queries to a file or logger__ object. .. __: https://docs.python.org/library/logging.html c||_tr4t|tjtjfr|j|_dS|j|_dS)zInitialize the connection to log to `!logobj`. The `!logobj` parameter can be an open file object or a Logger/LoggerAdapter instance from the standard logging module. N)_logobj_loggingrgLogger LoggerAdapter _logtologgerlog _logtofile)r(logobjs r, initializezLoggingConnection.initializesP   ' (*@ACC '(DHHHDHHHr-c|S)zFilter the query before logging it. This is the method to overwrite to filter unwanted queries out of the log or to add some extra data to the output. The default implementation just does nothing. rr(msgcurss r,filterzLoggingConnection.filters  r-c|||}|rit|tr+|tj|jd}|j|tj zdSdS)Nreplace) rrgbytesdecode_ext encodingsencodingrwrite_oslineseprs r,rzLoggingConnection._logtofilesykk#t$$  2#u%% Kjj !> JJ L  sS[0 1 1 1 1 1 2 2r-cn|||}|r|j|dSdSr/)rrdebugrs r,rzLoggingConnection._logtologgersCkk#t$$  $ L  s # # # # # $ $r-cPt|ds|ddS)Nrz3LoggingConnection object has not been initialize()d)hasattrProgrammingErrorr{s r,_checkzLoggingConnection._checks?tY'' G''EGG G G Gr-c||d|jptt j|i|SrH)rrJrI LoggingCursorr$rrLs r,rzLoggingConnection.cursorsJ *D,?,P=QQQuww~t.v...r-) r?r@rArBrrrrrrrCrDs@r,rrs ' ' '222$$$ GGG /////////r-rc0eZdZdZdfd Zdfd ZxZS)rzCA cursor that logs queries using its connection logging facilities.Nc t|||j|j|S#|j|j|wxYwr/)r$rTrrrVrUs r,rTzLoggingCursor.executesZ 277??5$// O   D 1 1 1 1DO   D 1 1 1 1 !A"A'c t|||j|j|S#|j|j|wxYwr/)r$rYrrrVrZs r,rYzLoggingCursor.callprocs\ 277##Hd33 O   D 1 1 1 1DO   D 1 1 1 1rr/)r?r@rArBrTrYrCrDs@r,rrsaMM222222 2222222222r-rc&eZdZdZddZdZdZdS)MinTimeLoggingConnectionaA connection that logs queries based on execution time. This is just an example of how to sub-class `LoggingConnection` to provide some extra filtering for the logged queries. Both the `initialize()` and `filter()` methods are overwritten to make sure that only queries executing for more than ``mintime`` ms are logged. Note that this connection uses the specialized cursor `MinTimeLoggingCursor`. rcJt||||_dSr/)rr_mintime)r(rmintimes r,rz#MinTimeLoggingConnection.initializes#$$T6222 r-ctj|jz dz}||jkrTt |t r+|tj|j d}|tj d|dSdS)Nirz (execution time: z ms)) _timetime timestamprrgrrrrrrr)r(rrrs r,rzMinTimeLoggingConnection.filters{ Z\\DN *d 2 t}  #u%% Kjj !> JJB3;BB1BBB B  r-cp|d|jpttj|g|Ri|SrH)rJrIMinTimeLoggingCursorrr)r(r)r*s r,rzMinTimeLoggingConnection.cursorsJ*   7#7 9 9 9 '>t>>>v>>>r-Nr)r?r@rArBrrrrr-r,rrsS      CCC?????r-rc"eZdZdZddZddZdS)rz=The cursor sub-class companion to `MinTimeLoggingConnection`.Ncjtj|_t|||Sr/)rrrrrT)r(rVrWs r,rTzMinTimeLoggingCursor.executes'$$T5$777r-cjtj|_t|||Sr/)rrrrrY)r(r[rWs r,rYzMinTimeLoggingCursor.callprocs'%%dHd;;;r-r/)r?r@rArBrTrYrr-r,rrsBGG8888<<<<<>>SVR>>>CC"_z1RRRi*6LRRRC3 q==////EGGG .H.. .G  000/SUUU tOG  B B1'',,$tOGk!T22AARAZZAAA sNG %% FO & E E E E Er-c4|jSr/)rfilenor{s r,r9zReplicationCursor.filenols%%'''r-NN)NNrrNFr")r?r@rArBrr!r7r9rr-r,rr smEE<=>DF8E8E8E8Ev(((((r-rc*eZdZdZdZdZdZdZdS) UUID_adapterzAdapt Python's uuid.UUID__ type to PostgreSQL's uuid__. .. __: https://docs.python.org/library/uuid.html .. __: https://www.postgresql.org/docs/current/static/datatype-uuid.html c||_dSr/_uuid)r(uuids r,r%zUUID_adapter.__init__y  r-c&|tjur|SdSr/r ISQLQuoter(protos r, __conform__zUUID_adapter.__conform__| DN " "K # "r-c>d|jddS)N''::uuidutf8)r?encoder{s r, getquotedzUUID_adapter.getquoteds#'DJ'''//777r-cd|jdS)NrJrKr>r{s r,__str__zUUID_adapter.__str__s&4:&&&&r-N)r?r@rArBr%rGrNrPrr-r,r<r<rsZ 888'''''r-r<cddl|sd}d}n&t|ttfr|\}}n|}d}t j|fdfdt_t j|fdtjt_t j tj|t j tj|t j jttjS)aRCreate the UUID type and an uuid.UUID adapter. :param oids: oid for the PostgreSQL :sql:`uuid` type, or 2-items sequence with oids of the type and the array. If not specified, use PostgreSQL standard oids. :param conn_or_curs: where to register the typecaster. If not specified, register it globally. rNi i UUIDc6|r|pdSr/)rR)rrr@s r,zregister_uuid..s!9$))D//!ATr-zUUID[]) r@rgrrrnew_typerRnew_array_type UUIDARRAY register_typeregister_adapterr<)oids conn_or_cursoid1oid2r@s @r, register_uuidr^sKKK  D4- ( ( dd th A A A ACCDI($(DIFFDNty,///t~|444$)\222 9r-c6eZdZdZdZdZdZdZdZdZ dS) InetaCWrap a string to allow for correct SQL-quoting of inet values. Note that this adapter does NOT check the passed value to make sure it really is an inet-compatible address but DOES call adapt() on it to make sure it is impossible to execute an SQL-injection by passing an evil value to the initializer. c||_dSr/)addr)r(rbs r,r%z Inet.__init__s  r-c0|jjd|jdS)Nr)r*)r+r?rbr{s r,__repr__z Inet.__repr__s .)::DI::::r-c||_dSr/)_connr(conns r,preparez Inet.preparerAr-ct|j}t|dr||j|dzS)Nris::inet)r0rbrrirfrN)r(objs r,rNzInet.getquotedsHmm 3 " " $ KK # # #}}**r-c&|tjur|SdSr/rCrEs r,rGzInet.__conform__rHr-c*t|jSr/)r-rbr{s r,rPz Inet.__str__s49~~r-N) r?r@rArBr%rdrirNrGrPrr-r,r`r`sx;;;+++ r-r`cddl}|dt|sd}d}n&t|tt fr|\}}n|}d}t j|fddt _t j |fdt jt _ t j t j|t j t j |t jS) aLCreate the INET type and an Inet adapter. :param oid: oid for the PostgreSQL :sql:`inet` type, or 2-items sequence with oids of the type and the array. If not specified, use PostgreSQL standard oids. :param conn_or_curs: where to register the typecaster. If not specified, register it globally. rNz4the inet adapter is deprecated, it's not very usefulieiINETc(|rt|pdSr/)r`)rrs r,rTzregister_inet..s!4$t**!<r- INETARRAY) warningswarnDeprecationWarningrgrrrrUrorVrqrX)oidr[rrr\r]s r, register_inetrvsOOO MM>  C$ ' ' dd th < <>>DI($; JJDNty,///t~|444 9r-cddl}ddlm}m}m} |}||krdS||kr+||gggnI||kr+|g|ggn|d|n$#t$r| YwxYw)aRWait until a connection or cursor has data available. The function is an example of a wait callback to be registered with `~psycopg2.extensions.set_wait_callback()`. This function uses :py:func:`~select.select()` to wait for data to become available, and therefore is able to handle/receive SIGINT/KeyboardInterrupt. rN)POLL_OK POLL_READ POLL_WRITETzbad state from poll: ) selectpsycopg2.extensionsrxryrzpollr9OperationalErrorKeyboardInterruptcancel)rhr{rxryrzstates r, wait_selectrsMMMBBBBBBBBBB IIKKE)## t{{}}or26666*$$ b4;;==/26666++,KE,K,KLLL     KKMMM H sB(A:B((C C c|tjdt|dr#|j}|t }n|}|t }||fS)zEReturn the connection and a DBAPI cursor from a connection or cursor.Nz no connection or cursor providedrT)rI)rrrrrr)r[rhrs r,_solve_conn_cursrsk'(JKKK|Y''3&{{'{22{{'{22 :r-ceZdZdZdZdZdZdZeZe j de j Z e e j dfdZe d Ze d Zd S) HstoreAdapterz)Adapt a Python dict to the hstore syntax.c||_dSr/)wrapped)r(rs r,r%zHstoreAdapter.__init__s  r-cP||_|jjdkr|j|_dSdS)Ni_)rhinfoserver_version _getquoted_8rNrgs r,rizHstoreAdapter.prepares1  9 #e + +!.DNNN , +r-c|jsdStj}g}|jD]\}}||}||j|}|:||}||j|}nd}|d|zdz|zdzdd|zdzS)z*Use the operators available in PG pre-9.0. ''::hstoreNsNULL(s => )s||) rrr rxrirhrNrjoin)r(r rvr6rns r,rzHstoreAdapter._getquoted_8 s| ! =  L&&(( 5 5DAqaA IIdi  A}E!HH $)$$$KKMM IIdQh(1,t3 4 4 4 4ejjnn$t++r-c|jsdStjt|j}||jtjt|j}||jd|zdz|zdzS)z(Use the hstore(text[], text[]) function.rshstore(s, r) rrr rr|rirhrrN)r(r6rns r, _getquoted_9zHstoreAdapter._getquoted_98s| ! = JtDL--//00 1 1 $) JtDL//1122 3 3 $)AKKMM)E1AKKMMADHHr-am # hstore key: # a string of normal or escaped chars "((?: [^"\\] | \\. )*)" \s*=>\s* # hstore value (?: NULL # the value can be null - not catched # or a quoted string like the key | "((?: [^"\\] | \\. )*)" ) (?:\s*,\s*|$) # pairs separated by comma or end of string. z\\(.)c|dSi}d}|j|D]}|||krtjd||d|d}|d}||d|}|||<|}|t|krtjd||S)zParse an hstore representation in a Python string. The hstore is represented as something like:: "a"=>"1", "b"=>"2" with backslash-escaped strings. Nrz"error parsing hstore pair at char \1rz/error parsing hstore: unparsed data after char ) _re_hstorefinditerstartrInterfaceErrorrgroupendr_) r(rcur_bsdecrrmr6rns r,parsezHstoreAdapter.parseRs 94 ))!,,  AyAGGII..-@@@BBB 5!''!**--A A}JJua((BqEEEGGEE 3q66>>)I%IIKK K r-c|dS|tj|jj}|||S)z2Parse an hstore returning unicode keys and values.N)rrrrrr)r(rrs r, parse_unicodezHstoreAdapter.parse_unicodess? 94 HHT^CN$;< = =zz!S!!!r-ct|\}}|j}|jjdkrdpd}gg}}|d|d|D]8}||d||d9|t jkr|js| t|t|fS)zBReturn the lists of OID of the hstore and hstore[] types. 9typarrayNULLzSELECT t.oid, z\ FROM pg_type t JOIN pg_namespace ns ON typnamespace = ns.oid WHERE typname = 'hstore'; rr) rstatusrrrTrrSTATUS_IN_TRANSACTION autocommitrollbackr) r(r[rhr conn_statusrrv0rv1rZs r,get_oidszHstoreAdapter.get_oids|s&l33 dk 9+u4CMvrS       D JJtAw    JJtAw     45 5 5 6 MMOOOSzz5::%%r-N)r?r@rArBr%rirrrN_recompileVERBOSErrrrrrr-r,rrs33///,,,0 I I II    J#.3;x#8#8[@""["&&[&&&r-rFcL|Ht|}||dstjd|d}|d}t |t r|f}|2t |t r|f}nt d|D}tj|dtj }tj || r|pdtj tt|r2tj |d|}tj || r|pddSdS)aRegister adapter and typecaster for `!dict`\-\ |hstore| conversions. :param conn_or_curs: a connection or cursor: the typecaster will be registered only on this object unless *globally* is set to `!True` :param globally: register the adapter globally, not only on *conn_or_curs* :param unicode: if `!True`, keys and values returned from the database will be `!unicode` instead of `!str`. The option is not available on Python 3 :param oid: the OID of the |hstore| type if known. If not, it will be queried on *conn_or_curs*. :param array_oid: the OID of the |hstore| array type if known. If not, it will be queried on *conn_or_curs*. The connection or cursor passed to the function will be used to query the database and look for the OID of the |hstore| type (which may be different across databases). If querying is not desirable (e.g. with :ref:`asynchronous connections `) you may specify it in the *oid* parameter, which can be found using a query such as :sql:`SELECT 'hstore'::regtype::oid`. Analogously you can obtain a value for *array_oid* using a query such as :sql:`SELECT 'hstore[]'::regtype::oid`. Note that, when passing a dictionary from Python to the database, both strings and unicode keys and values are supported. Dictionaries returned from the database have keys/values according to the *unicode* parameter. The |hstore| contrib module must be already installed in the database (executing the ``hstore.sql`` script in your ``contrib`` directory). Raise `~psycopg2.ProgrammingError` if the type is not found. Nrz\hstore type not found in the database. please install it from your 'contrib/hstore.sql' filercg|]}||Srr)rrrks r,rz#register_hstore..s999Qq9q999r-HSTORE HSTOREARRAY)rrrrrgrhrrrUrrXrYdictrV)r[globallyunicoderu array_oidrrs r,register_hstorersI> {$$\22 ;c!f;+HII IAIa&C#sf i % % ;" II99)999::I]3-*= > >Fv8|< DEEE$ ...O))]FKK  ;H (E(MNNNNNOOr-ceZdZdZd dZdZdZejdej Z ejdZ e dZ d Ze d ZdS) CompositeCasteramHelps conversion of a PostgreSQL composite type into a Python object. The class is usually created by the `register_composite()` function. You may want to create and register manually instances of the class if querying the database at registration time is not desirable (such as when using an :ref:`asynchronous connections `). NcX||_||_||_||_d|D|_d|D|_|||jtj|f||j |_ |r&tj |f|d|j |_ dSd|_ dS)Ncg|] }|d Srrrras r,rz,CompositeCaster.__init__..---!1---r-cg|] }|d S)rrrs r,rz,CompositeCaster.__init__..rr-ARRAY) nameschemarurattnamesatttypes _create_typerrUr typecasterrVarray_typecaster)r(rruattrsrrs r,r%zCompositeCaster.__init__s  "--u--- --u---  $ ...-djAA  )$($7 nnndo%?%?D ! ! !%)D ! ! !r-ch|dS||}t|t|jkr>tjdt|j|jt|fzfdt |j|D}||S)Nz9expecting %d components for the type %s, %d found insteadcBg|]\}}||Sr)cast)rrrutokenrs r,rz)CompositeCaster.parse..s;:::U))C'':::r-)tokenizer_rr DataErrorrzipmake)r(rrtokensrs ` r,rzCompositeCaster.parses 94q!! v;;#dm,, , ,$KT]##TYF <=>> >::::!$-88:::yy   r-c,||S)aReturn a new Python object representing the data being casted. *values* is the list of attributes, already casted into their Python representation. You can subclass this method to :ref:`customize the composite cast `. )_ctor)r(rs r,rzCompositeCaster.makeszz&!!!r-z \(? ([,)]) # an empty token, representing NULL | \(? " ((?: [^"] | "")*) " [,)] # or a quoted string | \(? ([^",)]+) [,)] # or an unquoted string z (["\\])\1c g}|j|D]}|tjd||d|dF|dB||jd|d||d|S)Nzcan't parse type: rrr) _re_tokenizerrrrr _re_undoubler)r(rrrs r,rzCompositeCaster.tokenizes "++A.. & &Ay-.H1.H.HIIIwwqzz% $' $+//qwwqzzBBCCCC !''!**%%%% r-ctd|}t|||_|jj|_dS)Nr)rrrr,rr)r(rrs r,rzCompositeCaster._create_type#s5}}S$''tX.. Y_ r-ct|\}}|j}d|vr|dd\}}n|}d}|jjdkrdpd}|d|z||f|} | s d} |jtjkr|d d } |d |z|f|} | r| d d }| d d}n#tj $rYnwxYw| r|dn#| r|dwwxYw|tjkr|j s| | stj d|d| d d } | d d} d| D} ||| | | |S)z}Return a `CompositeCaster` instance for the type *name*. Raise `ProgrammingError` if the type is not found. .rpublicrrrzSELECT t.oid, %s, attname, atttypid FROM pg_type t JOIN pg_namespace ns ON typnamespace = ns.oid JOIN pg_attribute a ON attrelid = typrelid WHERE typname = %%s AND nspname = %%s AND attnum > 0 AND NOT attisdropped ORDER BY attnum; FzSAVEPOINT register_typeTzSELECT t.oid, %s, attname, atttypid, typname, nspname FROM pg_type t JOIN pg_namespace ns ON typnamespace = ns.oid JOIN pg_attribute a ON attrelid = typrelid WHERE t.oid = %%s::regtype AND attnum > 0 AND NOT attisdropped ORDER BY attnum; rz#ROLLBACK TO SAVEPOINT register_typezPostgreSQL type 'z ' not foundc.g|]}|d|dfS)rrr)rrrs r,rz,CompositeCaster._from_db..us$111qqtQqTl111r-)rr) rrr.rrrTr9rrrrrr)r(rr[rhrrrtnamerrecs savepointtype_oidr type_attrss r,_from_dbzCompositeCaster._from_db(sS &l33 dk  $;; JJsA..MFEEEF9+u4CMv  ! ! !}} H H! ;$"<<<LL!:;;; $I }}( GAJE!!WQZF ,    HLL!FGGGHLL!FGGGGH $4 4 4T_ 4 MMOOO 7+5D55577 771:GAJ 11D111 tE8Z000 0s+AC= 3D*=D D*DD**Er:)r?r@rArBr%rrrrrrrrrrrrr-r,rrs)))) ! ! ! " " "3;   L 3;|,,L  [ %%% O0O0[O0O0O0r-rc|t}|||}tj|j| r|pd|jtj|j| r|pd|S)aRegister a typecaster to convert a composite type into a tuple. :param name: the name of a PostgreSQL composite type, e.g. created using the |CREATE TYPE|_ command :param conn_or_curs: a connection or cursor used to find the type oid and components; the typecaster is registered in a scope limited to this object, unless *globally* is set to `!True` :param globally: if `!False` (default) register the typecaster only on *conn_or_curs*, otherwise register it globally :param factory: if specified it should be a `CompositeCaster` subclass: use it to :ref:`customize how to cast composite types ` :return: the registered `CompositeCaster` or *factory* instance responsible for the conversion N)rrrrXrr)rr[rfactorycasters r,register_compositer{s!   dL 1 1Fv(h,*G<*O4PPP *   #\%Bl%Jd L L L Mr-c#Kg}t|} t|D]$}|t|%|Vg}n#t$r |r|VYdSwxYwT)zwConsume an iterable and return it in chunks. Every chunk is at most `page_size`. Never return an empty chunk. TN)rzr^rr<r=)seq page_sizepagerr`s r, _paginaters D cB  9%% & & DHH%%%%JJJDD     FF  s:AA%$A%dct||D]9}fd|D}d|:dS)aExecute groups of statements in fewer server roundtrips. Execute *sql* several times, against all parameters set (sequences or mappings) found in *argslist*. The function is semantically similar to .. parsed-literal:: *cur*\.\ `~cursor.executemany`\ (\ *sql*\ , *argslist*\ ) but has a different implementation: Psycopg will join the statements into fewer multi-statement commands, each one containing at most *page_size* statements, resulting in a reduced number of server roundtrips. After the execution of the function the `cursor.rowcount` property will **not** contain a total result. rc<g|]}|Sr)mogrify)rrr)rsqls r,rz!execute_batch..s'8884 C&&888r-;N)rrTr)rrargslistrrsqlss`` r, execute_batchrsg((i888%%888884888 DIIdOO$$$$%%r-c ddlm}t||r||}t|ts/|t j|jj }t|\}}|rgnd} t||D]} |2dd dgt| dzzdz}|dd} | D]@} | ||| | dA|| d d<|d | |r'| || S) aA Execute a statement using :sql:`VALUES` with a sequence of parameters. :param cur: the cursor to use to execute the query. :param sql: the query to execute. It must contain a single ``%s`` placeholder, which will be replaced by a `VALUES list`__. Example: ``"INSERT INTO mytable (id, f1, f2) VALUES %s"``. :param argslist: sequence of sequences or dictionaries with the arguments to send to the query. The type and content must be consistent with *template*. :param template: the snippet to merge to every item in *argslist* to compose the query. - If the *argslist* items are sequences it should contain positional placeholders (e.g. ``"(%s, %s, %s)"``, or ``"(%s, %s, 42)``" if there are constants value...). - If the *argslist* items are mappings it should contain named placeholders (e.g. ``"(%(id)s, %(f1)s, 42)"``). If not specified, assume the arguments are sequence and use a simple positional template (i.e. ``(%s, %s, ...)``), with the number of placeholders sniffed by the first element in *argslist*. :param page_size: maximum number of *argslist* items to include in every statement. If there are more items the function will execute more than one statement. :param fetch: if `!True` return the query results into a list (like in a `~cursor.fetchall()`). Useful for queries with :sql:`RETURNING` clause. .. __: https://www.postgresql.org/docs/current/static/queries-values.html After the execution of the function the `cursor.rowcount` property will **not** contain a total result. While :sql:`INSERT` is an obvious candidate for this function it is possible to use it with other statements, for example:: >>> cur.execute( ... "create table test (id int primary key, v1 int, v2 int)") >>> execute_values(cur, ... "INSERT INTO test (id, v1, v2) VALUES %s", ... [(1, 2, 3), (4, 5, 6), (7, 8, 9)]) >>> execute_values(cur, ... """UPDATE test SET v1 = data.v1 FROM (VALUES %s) AS data (id, v1) ... WHERE test.id = data.id""", ... [(1, 20), (4, 50)]) >>> cur.execute("select * from test order by id") >>> cur.fetchall() [(1, 20, 3), (4, 50, 6), (7, 8, 9)]) r) ComposableNrr,s%srr-) psycopg2.sqlrrg as_stringrrMrrrr _split_sqlrrr_rrrTextendr9) rrrtemplaterfetchrprepostresultrpartsr)s r,execute_valuesr syx('''''#z""!mmC   c5 ! !Bjj(?@AA3IC "RRdF(i888 * *  dii#d1g,,(>???$FHAAA  D LLXt44 5 5 5 LL    bcc  CHHUOO$$$  * MM#,,.. ) ) ) Mr-cgx}}g}tjd|}|D]}t|dks|dddkr||9|dddkr||ur|}Nt d|dddkr|dt d|ddd d z||urt d ||fS) zSplit *sql* on a single ``%s`` placeholder. Split on the %s, perform %% replacement and return pre, post lists of snippets. s(%.)rNr%sz1the query contains more than one '%s' placeholderz"unsupported format character: '%s'asciirz.the query doesn't contain any '%s' placeholder)rr.r_r ValueErrorr)rcurrrrrrs r,rrs$ OD3 D Yx % %F88 u::??eBQBi4// KK     9  s{{ GIII 122Y$   KK    A)""7I66788 8 s{{IJJJ 9r-[z !"#$%&'()*+,-./:;<=>?@[\]^`{|}~]r:)FFNN)FN)r)NrF)VrBosrrrrer collectionsrrloggingrrrrrrr _connectionr r0r functoolsr psycopg2._psycopgr r r_replicationConnectionr_replicationCursorrpsycopg2._jsonrrrrrpsycopg2._rangerrrrrrrrpsycopg2._ipaddressrr rFrKrrPrrrrrrrrrrrrrrrr<r^r`rvrrrrrrrrr rrescaperrr-r,r!s8////////''''''))))))11111100000000NNNNNNNNNNNNNN //////////////////// 32222299999W999x/////[///))))))))833333d333l////////)))))^)))8 ( ( ( ( (+ ( ( (F/////;///UUUUUwUUUp 3   $/;#?#? 0/0/0/0/0/ 0/0/0/f 2 2 2 2 2G 2 2 2 ?????0???8 < < < < <= < < <*****#9********$:***      i    c(c(c(c(c(*c(c(c(P''''''''*D>B8   E&E&E&E&E&E&E&E&P;@(,9O9O9O9Ox`0`0`0`0`0`0`0`0F8&%%%%2TTTTnB CK*#*9 : ::S@ B B r-