o ao@sdZddlZddlZddlZddlmZm 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/m0Z0GdddeZ1GdddeZ2Gddde1Z3Gddde4Z5GdddeZ6Gddde1Z7Gddde Z8GdddeZ9GdddeZ:ed d!d"Z;eGd'd(d(e=Z?Gd)d*d*e>Z@Gd+d,d,eZAGd-d.d.eZBGd/d0d0eCZDGd1d2d2eZGd3d4d4ZEdQd5d6ZFGd7d8d8ZGdQd9d:ZHd;d<ZId=d>ZJGd?d@d@ZK A dRdBdCZLGdDdEdEZMdSdFdGZNdHdIZOdTdKdLZPdUdMdNZQdOdPZRdS)VzMiscellaneous 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_ipaddresscsReZdZdZfddZfddZd fdd Zfd d Zfd d ZZ S)DictCursorBasez%Base class for all dict-like cursors.csHd|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__1/usr/lib/python3/dist-packages/psycopg2/extras.pyr"Ds zDictCursorBase.__init__c2|jrt}|jr||jst}|SN)r$r!fetchoner# _build_indexr%resr(r*r+r.P  zDictCursorBase.fetchoneNcs6|jr t|}|jr||jst|}|Sr-)r$r! fetchmanyr#r/)r%sizer1r(r*r+r3Ys  zDictCursorBase.fetchmanycr,r-)r$r!fetchallr#r/r0r(r*r+r5br2zDictCursorBase.fetchallc#sjz)|jrt}t|}|jr||js!t}t|}|V t|Vq%ty4YdSwr-)r$r!__iter__nextr#r/ StopIteration)r%r1firstr(r*r+r6ks"    zDictCursorBase.__iter__r-) __name__ __module__ __qualname____doc__r"r.r3r5r6 __classcell__r*r*r(r+rAs    rc eZdZdZfddZZS)DictConnectionz2A connection that uses `DictCursor` automatically.c$|d|jpttj|i|SNcursor_factory) setdefaultrC DictCursorr!rr%r&r'r(r*r+rzDictConnection.cursorr:r;r<r=rr>r*r*r(r+r@}r@cDeZdZdZfddZd fdd Zd fdd Zd d ZZS) rEzA cursor that keeps a list of column name -> index mappings__. .. __: https://docs.python.org/glossary.html#term-mapping cs$t|d<tj|i|d|_dS)NrT)DictRowr!r"r$rFr(r*r+r"s zDictCursor.__init__Nct|_d|_t||SNT)rindexr#r!executer%queryvarsr(r*r+rOzDictCursor.executecrLrM)rrNr#r!callprocr%procnamerRr(r*r+rTrSzDictCursor.callproccCsF|jr|jr!tt|jD] }||j|j|d<q d|_dSdSdS)NrF)r# descriptionrangelenrN)r%ir*r*r+r/s  zDictCursor._build_indexr- r:r;r<r=r"rOrTr/r>r*r*r(r+rEs  rEcseZdZdZdZddZfddZfddZfd d Zd d Z fd dZ dddZ ddZ ddZ fddZddZddZZS)rKz6A row object that allow by-column-name access to data._indexcCs$|j|_dgt|j|dd<dSr-)rNr]rYrW)r%rr*r*r+r"szDictRow.__init__cs$t|ttfs |j|}t|Sr-) isinstanceintslicer]r! __getitem__r%xr(r*r+ras  zDictRow.__getitem__cs*t|ttfs |j|}t||dSr-)r^r_r`r]r! __setitem__)r%rcvr(r*r+rds zDictRow.__setitem__ctjfddjDS)Nc3s"|] }|j|fVqdSr-r\.0ngr%r*r+ s z DictRow.items..r!rar]r%r(rjr+itemsz DictRow.itemscC t|jSr-)iterr]rnr*r*r+keys z DictRow.keyscrf)Nc3s|] }j|VqdSr-r\rgrjr*r+rlsz!DictRow.values..rmrnr(rjr+valuesrpzDictRow.valuesNcCs"z||WSty|YSwr-) Exception)r%rcdefaultr*r*r+gets   z DictRow.getcCs t|Sr-)rrornr*r*r+copys z DictRow.copycCs ||jvSr-r\rbr*r*r+ __contains__rtzDictRow.__contains__cs tSr-)r! __reduce__rnr(r*r+r{ zDictRow.__reduce__cCs|dd|jfSr-)r]ryrnr*r*r+ __getstate__zDictRow.__getstate__cCs|d|dd<|d|_dSNrrr\)r%datar*r*r+ __setstate__szDictRow.__setstate__r-)r:r;r<r= __slots__r"rardrorsrurxryrzr{r}rr>r*r*r(r+rKs      rKcr?)RealDictConnectionz6A connection that uses `RealDictCursor` automatically.crArB)rDrCRealDictCursorr!rrFr(r*r+rrGzRealDictConnection.cursorrHr*r*r(r+rrIrcrJ) 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`. ct|d<tj|i|dS)Nr) RealDictRowr!r"rFr(r*r+r"rpzRealDictCursor.__init__Ncg|_d|_t||SrM)column_mappingr#r!rOrPr(r*r+rOzRealDictCursor.executecrrM)rr#r!rTrUr(r*r+rTrzRealDictCursor.callproccCs0|jr|jrdd|jD|_d|_dSdSdS)NcSg|]}|dqSrr*rhdr*r*r+ z/RealDictCursor._build_index..F)r#rWrrnr*r*r+r/s  zRealDictCursor._build_indexr-r[r*r*r(r+rs  rcs,eZdZdZfddZfddZZS)rz.A `!dict` subclass representing a data record.csl|rt|dtr|d}|dd}nd}tj|i||dur4|jr-|js-||j|t<dSdSr)r^_cursorr!r"rWrr/r)r%r&r'rr(r*r+r"s zRealDictRow.__init__csNt|vr|t}t||||t|dkr|t=dSt||dS)Nr)rr!rdrY)r%keyvaluemappingr(r*r+rdszRealDictRow.__setitem__)r:r;r<r=r"rdr>r*r*r(r+rs rcr?)NamedTupleConnectionz8A connection that uses `NamedTupleCursor` automatically.crArB)rDrCNamedTupleCursorr!rrFr(r*r+rrGzNamedTupleConnection.cursorrHr*r*r(r+rrIrcseZdZdZdZdZdfdd ZfddZdfdd Zfd d Z dfd d Z fddZ fddZ e de ddZddZeddZZS)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" Nicd|_t||Sr-)Recordr!rOrPr(r*r+rO6zNamedTupleCursor.executecrr-)rr! executemanyrPr(r*r+r:rzNamedTupleCursor.executemanycrr-)rr!rTrUr(r*r+rT>rzNamedTupleCursor.callproccs<t}|dur|j}|dur|}|_||SdSr-)r!r.r_make_nt_make)r%tntr(r*r+r.Bs  zNamedTupleCursor.fetchonecs8t|}|j}|dur|}|_tt|j|Sr-)r!r3rrlistmapr)r%r4tsrr(r*r+r3Js zNamedTupleCursor.fetchmanycs6t}|j}|dur|}|_tt|j|Sr-)r!r5rrrrr)r%rrr(r*r+r5Qs zNamedTupleCursor.fetchallc#sfz't}t|}|j}|dur|}|_||V |t|Vq ty2YdSwr-)r!r6r7rrrr8)r%itrrr(r*r+r6Xs   zNamedTupleCursor.__iter__[z !"#$%&'()*+,-./:;<=>?@[\]^`{|}~]cCs(|jr tdd|jDnd}||S)Ncss|]}|dVqdS)rNr*rr*r*r+rlmsz,NamedTupleCursor._make_nt..r*)rWtuple_cached_make_nt)r%rr*r*r+rls zNamedTupleCursor._make_ntcCsdg}|D]&}|jd|}|ddks!d|dkrdkr%nnd|}||qtd|}|S)N_r09fr) _re_cleansubappendr)clsrfieldssrr*r*r+ _do_make_ntps(  zNamedTupleCursor._do_make_ntr-)r:r;r<r=r MAX_CACHErOrrTr.r3r5r6_recompileescaperr classmethodrr>r*r*r(r+r#s"    ricC ||Sr-)r)rrr*r*r+rr|rcsHeZdZdZddZddZddZdd Zd d Zfd d Z Z S)LoggingConnectionz~A connection that logs all queries to a file or logger__ object. .. __: https://docs.python.org/library/logging.html cCs4||_trt|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_loggingr^Logger LoggerAdapter _logtologgerlog _logtofile)r%logobjr*r*r+ initializes    zLoggingConnection.initializecCs|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. r*r%msgcursr*r*r+filterszLoggingConnection.filtercCsH|||}|r"t|tr|tj|jd}|j|t j dSdS)Nreplace) rr^bytesdecode_ext encodingsencodingrwrite_oslineseprr*r*r+rs  zLoggingConnection._logtofilecCs$|||}|r|j|dSdSr-)rrdebugrr*r*r+rs zLoggingConnection._logtologgercCst|ds |ddS)Nrz3LoggingConnection object has not been initialize()d)hasattrProgrammingErrorrnr*r*r+_checks zLoggingConnection._checkcs,||d|jp ttj|i|SrB)rrDrC LoggingCursorr!rrFr(r*r+rszLoggingConnection.cursor) r:r;r<r=rrrrrrr>r*r*r(r+rs  rcs0eZdZdZdfdd Zdfdd ZZS)rzCA cursor that logs queries using its connection logging facilities.Nc 4zt||W|j|j|S|j|j|wr-)r!rOrrrQrPr(r*r+rO$zLoggingCursor.executec rr-)r!rTrrrQrUr(r*r+rTrzLoggingCursor.callprocr-)r:r;r<r=rOrTr>r*r*r(r+rsrc@s*eZdZdZd ddZddZddZd S) 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`. rcCst||||_dSr-)rr_mintime)r%rmintimer*r*r+rs  z#MinTimeLoggingConnection.initializecCsTt|jd}||jkr(t|tr|tj|j d}|t j d|dSdS)Nirz (execution time: z ms)) _timetime timestamprr^rrrrrrr)r%rrrr*r*r+rs   zMinTimeLoggingConnection.filtercOs*|d|jpttj|g|Ri|SrB)rDrCMinTimeLoggingCursorrrrFr*r*r+rszMinTimeLoggingConnection.cursorNr)r:r;r<r=rrrr*r*r*r+rs   rc@s$eZdZdZdddZdddZdS)rz=The cursor sub-class companion to `MinTimeLoggingConnection`.NcCt|_t|||Sr-)rrrrrOrPr*r*r+rO zMinTimeLoggingCursor.executecCrr-)rrrrrTrUr*r*r+rTrzMinTimeLoggingCursor.callprocr-)r:r;r<r=rOrTr*r*r*r+rs rceZdZfddZZS)LogicalReplicationConnectioncrNreplication_type)r r!r"rFr(r*r+r"rpz%LogicalReplicationConnection.__init__r:r;r<r"r>r*r*r(r+rrcr)PhysicalReplicationConnectioncrr)r r!r"rFr(r*r+r"rpz&PhysicalReplicationConnection.__init__rr*r*r(r+rrrc@seZdZdZdS)StopReplicationa  Exception used to break out of the endless loop in `~ReplicationCursor.consume_stream()`. Subclass of `~exceptions.Exception`. Intentionally *not* inherited from `~psycopg2.Error` as occurrence of this exception does not indicate an error. N)r:r;r<r=r*r*r*r+rsrc@s8eZdZdZdddZddZ  dd d Zd d ZdS)rz;A cursor used for communication on replication connections.NcCsdt||d}|dur|jj}|tkr)|durtd|dt||7}n|tkr;|dur6td|d7}n tdt|||dS) z"Create streaming replication slot.zCREATE_REPLICATION_SLOT  NzAoutput plugin name is required to create logical replication slotLOGICAL zIcannot specify output plugin name when creating physical replication slotPHYSICALunrecognized replication type: ) r rrr psycopg2rr reprrO)r% slot_name slot_type output_plugincommandr*r*r+create_replication_slots&  z)ReplicationCursor.create_replication_slotcCsdt||}||dS)z Drop streaming replication slot.zDROP_REPLICATION_SLOT N)r rO)r%rrr*r*r+drop_replication_slot/sz'ReplicationCursor.drop_replication_slotrF c Csd}|dur |jj}|tkr&|r|dt||d7}ntd|d7}n|tkr8|r7|dt||d7}n tdt|t|t ura| d} t | d d d dt | d d d } n|d?d@d d|d@d } || 7}|d kr|tkrtd|d|7}|r|tkrtd|d7}| D]\} } | ds|d7}|t| |dtt | 7}q|d7}|j|||ddS)zStart replication stream.zSTART_REPLICATION NzSLOT rz-slot name is required for logical replicationrr/rXr08X lz/cannot specify timeline for logical replicationz TIMELINE z=cannot specify output plugin options for physical replicationz ((z, ))rstatus_interval)rrr r rrr rtypestrsplitr_roendswith_Astart_replication_expert) r%rr start_lsntimelineoptionsrrrlsnkrer*r*r+start_replication5sT    ( " z#ReplicationCursor.start_replicationcCs |jSr-)rfilenornr*r*r+rprtzReplicationCursor.filenoNN)NNrrNFr)r:r;r<r=rrrrr*r*r*r+rs  ;rc@s0eZdZdZddZddZddZdd Zd S) 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 cC ||_dSr-_uuid)r%uuidr*r*r+r"}rtzUUID_adapter.__init__cC|tjur|SdSr-r ISQLQuoter%protor*r*r+ __conform__ zUUID_adapter.__conform__cCsd|jddS)N''::uuidutf8)r encodernr*r*r+ getquotedszUUID_adapter.getquotedcCsd|jdS)Nrrr rnr*r*r+__str__szUUID_adapter.__str__N)r:r;r<r=r"rrrr*r*r*r+r vs  r csddl|s d}d}nt|ttfr|\}}n|}d}t|fdfddt_t|fdtjt_t tj|t tj|t jt tjS) 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 UUIDcs|r|pdSr-)rrrr r*r+szregister_uuid..zUUID[]) r r^rrrnew_typernew_array_type UUIDARRAY register_typeregister_adapterr )oids conn_or_cursoid1oid2r*rr+ register_uuids     r(c@s@eZdZdZddZddZddZdd Zd d Zd d Z 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. cCr r-)addr)r%r*r*r*r+r"rtz Inet.__init__cCs|jjd|jdS)Nrr)r)r:r*rnr*r*r+__repr__r~z Inet.__repr__cCr r-)_connr%connr*r*r+preparertz Inet.preparecCs,t|j}t|dr||j|dS)Nr/s::inet)rr*rr/r,r)r%objr*r*r+rs    zInet.getquotedcCrr-rrr*r*r+rrzInet.__conform__cCrqr-)rr*rnr*r*r+rrtz Inet.__str__N) r:r;r<r=r"r+r/rrrr*r*r*r+r)s r)cCsddl}|dt|sd}d}nt|ttfr|\}}n|}d}t|fdddt_t |fd tjt_ t tj|t tj |tjS) 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 usefulieiINETcSs|rt|pdSr-)r)rr*r*r+rszregister_inet.. INETARRAY) warningswarnDeprecationWarningr^rrrrr1r r2r")oidr%r3r&r'r*r*r+ register_inets&   r7cCsddl}ddlm}m}m} z3|}||krWdS||kr*||gggn||kr9|g|ggn|d|Wn tyO| Yqwq)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.extensionsr8r9r:pollrOperationalErrorKeyboardInterruptcancel)r.r;r8r9r:stater*r*r+ wait_selects$ rBcCsN|dur tdt|dr|j}|jtd}||fS|}|jtd}||fS)zEReturn the connection and a DBAPI cursor from a connection or cursor.Nz no connection or cursor providedrO)rC)rrrrrr)r%r.rr*r*r+_solve_conn_curs s    rCc@speZdZdZddZddZddZdd ZeZe d e j Z e e d fd d Ze ddZe ddZdS) HstoreAdapterz)Adapt a Python dict to the hstore syntax.cCr r-)wrapped)r%rEr*r*r+r"rtzHstoreAdapter.__init__cCs"||_|jjdkr|j|_dSdS)Ni_)r.infoserver_version _getquoted_8rr-r*r*r+r/s  zHstoreAdapter.preparecCs|jsdStj}g}|jD]4\}}||}||j|}|dur4||}||j|}nd}|d|d|dqdd|dS)z*Use the operators available in PG pre-9.0. ''::hstoreNsNULL(s => )s||) rErrror/r.rrjoin)r%rrvrrer*r*r+rH$s   zHstoreAdapter._getquoted_8cCsf|jsdStt|j}||jtt|j}||jd|d|dS)z(Use the hstore(text[], text[]) function.rIshstore(s, rK) rErrrrsr/r.rur)r%rrer*r*r+ _getquoted_9<s  zHstoreAdapter._getquoted_9am # 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 Cs|durdSi}d}|j|D]4}|dus||kr$td||d|d}|d}|dur<|d|}|||<|}q|t|krStd||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_hstorefinditerstartrInterfaceErrorrgroupendrY) r%rcur_bsdecrMrSmrrer*r*r+parseVs(     zHstoreAdapter.parsecCs,|durdS|tj|jj}|||S)z2Parse an hstore returning unicode keys and values.N)rrrrrrZ)r%rrWr*r*r+ parse_unicodews zHstoreAdapter.parse_unicodec Cst|\}}|j}|jjdkrdpd}gg}}|d|d|D]}||d||dq#|tjkr@|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) rCstatusrFrGrOrrSTATUS_IN_TRANSACTION autocommitrollbackr) r%r%r.r conn_statusr]rv0rv1r$r*r*r+get_oidss   zHstoreAdapter.get_oidsN)r:r;r<r=r"r/rHrNrrrVERBOSErQrrZr[rfr*r*r*r+rDs     rDFcCs|durt|}|dus|dstd|d}|d}t|tr&|f}|dur`) 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' filercSsg|]}|r|qSr*r*)rhrcr*r*r+rrz#register_hstore..HSTORE HSTOREARRAY)rDrfrrr^r_rrrrZr"r#dictr )r%globallyunicoder6 array_oidrhrir*r*r+register_hstores*    rnc@sbeZdZdZdddZddZddZed ej Z ed Z e d d Z d dZe ddZdS)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 `). NcCs||_||_||_||_dd|D|_dd|D|_|||jt|f||j |_ |r>t |f|d|j |_ dSd|_ dS)NcSrrr*rhar*r*r+rrz,CompositeCaster.__init__..cSr)rr*rpr*r*r+rrARRAY) nameschemar6rmattnamesatttypes _create_typerrrZ typecasterr array_typecaster)r%rsr6attrsrmrtr*r*r+r"s zCompositeCaster.__init__csl|durdS||}t|t|jkr$tdt|j|jt|ffddt|j|D}||S)Nz9expecting %d components for the type %s, %d found insteadcsg|] \}}||qSr*)cast)rhr6tokenrr*r+rsz)CompositeCaster.parse..)tokenizerYrvr DataErrorrszipmake)r%rrtokensrur*r}r+rZs    zCompositeCaster.parsecCr)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%rur*r*r+rs zCompositeCaster.makez \(? ([,)]) # an empty token, representing NULL | \(? " ((?: [^"] | "")*) " [,)] # or a quoted string | \(? ([^",)]+) [,)] # or an unquoted string z (["\\])\1c Csg}|j|D]8}|durtd||ddur#|dq|ddur8||jd|dq||dq|S)Nzcan't parse type: rrPrO) _re_tokenizerRrrTrUr _re_undoubler)r%rrMrYr*r*r+r~s zCompositeCaster.tokenizecCst|||_|jj|_dSr-)rrrr)r%rsrur*r*r+rw's zCompositeCaster._create_typec Cst|\}}|j}d|vr|dd\}}n|}d}|jjdkr"dp#d}|d|||f|} |tjkr>|j s>| | sIt d|d | 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. .rpublicr\r]r^zSELECT 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; zPostgreSQL type 'z ' not foundrcSsg|] }|d|dfqS)rPrr*)rhrr*r*r+rXsz,CompositeCaster._from_db..)rmrt) rCr_rrFrGrOr5rr`rarbrr) r%rsr%r.rrcrttnamer]recstype_oidrm type_attrsr*r*r+_from_db+s6     zCompositeCaster._from_dbr)r:r;r<r=r"rZrrrrgrrrr~rwrr*r*r*r+ros    rocCsV|durt}|||}t|j| r|pd|jdur)t|j| r&|p'd|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)rorrr"rxry)rsr%rkfactorycasterr*r*r+register_composite^s  rccs\g}t|} zt|D] }|t|q |Vg}Wnty,|r)|VYdSwq)zwConsume an iterable and return it in chunks. Every chunk is at most `page_size`. Never return an empty chunk. TN)rrrXrr7r8)seq page_sizepagerrZr*r*r+ _paginatezs  rdcs:t||dD]}fdd|D}d|qdS)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. rcsg|]}|qSr*)mogrify)rhr&rWsqlr*r+rsz!execute_batch..;N)rrOrL)rWrargslistrrsqlsr*rr+ execute_batchsrc Csddlm}t||r||}t|ts|tj|jj }t |\}}|r)gnd} t ||dD]F} |durGdd dgt | dd}|dd} | D]} | ||| | dqO|| d d<|d | |rw| |q1| 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) ComposableNrrJ,s%srK) psycopg2.sqlrr^ as_stringrrrrrr _split_sqlrrLrYrrrOextendr5) rWrrtemplaterfetchrprepostresultrpartsr&r*r*r+execute_valuess( <         rcCsg}}g}td|}|D]D}t|dks|dddkr$||q|dddkr7||ur3|}qtd|dddkrE|dqtd|ddd d ||ur[td ||fS) zSplit *sql* on a single ``%s`` placeholder. Split on the %s, perform %% replacement and return pre, post lists of snippets. s(%.)rPNr%sz1the query contains more than one '%s' placeholderz"unsupported format character: '%s'asciirz.the query doesn't contain any '%s' placeholder)rrrYr ValueErrorr)rcurrrrrr|r*r*r+rs*   rr)FFNN)FN)r)NrF)Sr=osrrrrer collectionsrrloggingrrrrrrr _connectionrrr functoolsr psycopg2._psycopgr r r _replicationConnectionr_replicationCursorrpsycopg2._jsonrrrrrpsycopg2._rangerrrrrrrrpsycopg2._ipaddressrrr@rErrKrrrrrrrrrrrrrrvrr r(r)r7rBrCrDrnrorrrrrr*r*r*r+sl    ( <6#\  3  h " !  <    W