U 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/d0d0eCZDGd1d2d2eZGd3d4d4ZEdQd5d6ZFGd7d8d8ZGdRd9d:ZHd;d<ZId=d>ZJGd?d@d@ZKdSdBdCZLGdDdEdEZMdTdFdGZNdHdIZOdUdKdLZPdVdMdNZQdOdPZRdS)WzMiscellaneous 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.csDd|kr|d}|d=ntdtj||d|_d|_||_dS)N row_factoryz;DictCursorBase can't be instantiated without a row factory.F)NotImplementedErrorsuper__init___query_executed _prefetchr)selfargskwargsr __class__PC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-8c51wohf\psycopg2\extras.pyr"DszDictCursorBase.__init__cs2|jrt}|jr||js.t}|SN)r$r!fetchoner# _build_indexr%resr(r*r+r-Ps  zDictCursorBase.fetchoneNcs6|jrt|}|jr ||js2t|}|Sr,)r$r! fetchmanyr#r.)r%sizer0r(r*r+r1Ys  zDictCursorBase.fetchmanycs2|jrt}|jr||js.t}|Sr,)r$r!fetchallr#r.r/r(r*r+r3bs  zDictCursorBase.fetchallc#spzT|jrt}t|}|jr(||js@t}t|}|Vt|VqFWntk rjYdSXdSr,)r$r!__iter__nextr#r. StopIteration)r%r0firstr(r*r+r4ks  zDictCursorBase.__iter__)N) __name__ __module__ __qualname____doc__r"r-r1r3r4 __classcell__r*r*r(r+rAs   rcs eZdZdZfddZZS)DictConnectionz2A connection that uses `DictCursor` automatically.cs |d|jpttj||SNcursor_factory) setdefaultr? DictCursorr!rr%r&r'r(r*r+rszDictConnection.cursorr8r9r:r;rr<r*r*r(r+r=}sr=csDeZdZdZfddZd fdd Zd fdd Zd d ZZS) rAzA cursor that keeps a list of column name -> index mappings__. .. __: https://docs.python.org/glossary.html#term-mapping cs t|d<tj||d|_dS)NrT)DictRowr!r"r$rBr(r*r+r"szDictCursor.__init__Ncst|_d|_t||SNT)rindexr#r!executer%queryvarsr(r*r+rGszDictCursor.executecst|_d|_t||SrE)rrFr#r!callprocr%ZprocnamerJr(r*r+rKszDictCursor.callproccCs>|jr:|jr:tt|jD]}||j|j|d<qd|_dS)NrF)r# descriptionrangelenrF)r%ir*r*r+r.s zDictCursor._build_index)N)N r8r9r:r;r"rGrKr.r<r*r*r(r+rAs  rAcseZdZdZdZddZfddZfddZfd d Zd d Z fd dZ dddZ ddZ ddZ fddZddZddZZS)rDz6A row object that allow by-column-name access to data._indexcCs$|j|_dgt|j|dd<dSr,)rFrSrOrM)r%rr*r*r+r"szDictRow.__init__cs$t|ttfs|j|}t|Sr,) isinstanceintslicerSr! __getitem__r%xr(r*r+rWs zDictRow.__getitem__cs*t|ttfs|j|}t||dSr,)rTrUrVrSr! __setitem__)r%rYvr(r*r+rZs zDictRow.__setitem__cstjfddjDS)Nc3s |]}|j|fVqdSr,rR.0ngr%r*r+ sz DictRow.items..r!rWrSr%r(r_r+itemssz DictRow.itemscCs t|jSr,)iterrSrcr*r*r+keyssz DictRow.keyscstjfddjDS)Nc3s|]}j|VqdSr,rRr\r_r*r+rasz!DictRow.values..rbrcr(r_r+valuesszDictRow.valuesNcCs(z ||WStk r"|YSXdSr,) Exception)r%rYdefaultr*r*r+gets z DictRow.getcCs t|Sr,)rrdrcr*r*r+copysz DictRow.copycCs ||jkSr,rRrXr*r*r+ __contains__szDictRow.__contains__cs tSr,)r! __reduce__rcr(r*r+rmszDictRow.__reduce__cCs|dd|jfSr,)rSrkrcr*r*r+ __getstate__szDictRow.__getstate__cCs|d|dd<|d|_dSNrrrR)r%datar*r*r+ __setstate__szDictRow.__setstate__)N)r8r9r:r; __slots__r"rWrZrdrfrgrjrkrlrmrnrqr<r*r*r(r+rDs      rDcs eZdZdZfddZZS)RealDictConnectionz6A connection that uses `RealDictCursor` automatically.cs |d|jpttj||Sr>)r@r?RealDictCursorr!rrBr(r*r+rszRealDictConnection.cursorrCr*r*r(r+rssrscsDeZdZdZfddZd fdd Zd fdd Zd d ZZS) rtaQA 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`. cst|d<tj||dS)Nr) RealDictRowr!r"rBr(r*r+r"szRealDictCursor.__init__Ncsg|_d|_t||SrE)column_mappingr#r!rGrHr(r*r+rGszRealDictCursor.executecsg|_d|_t||SrE)rvr#r!rKrLr(r*r+rKszRealDictCursor.callproccCs(|jr$|jr$dd|jD|_d|_dS)NcSsg|] }|dqSrr*r]dr*r*r+ sz/RealDictCursor._build_index..F)r#rMrvrcr*r*r+r.s zRealDictCursor._build_index)N)NrQr*r*r(r+rts  rtcs,eZdZdZfddZfddZZS)ruz.A `!dict` subclass representing a data record.csd|r(t|dtr(|d}|dd}nd}tj|||dk r`|jrV|jsV||j|t<dSro)rT_cursorr!r"rMrvr.ru)r%r&r'rr(r*r+r"s zRealDictRow.__init__csNt|kr<|t}t||||t|dkr8|t=dSt||dS)Nr)rur!rZrO)r%keyvaluemappingr(r*r+rZszRealDictRow.__setitem__)r8r9r:r;r"rZr<r*r*r(r+rus rucs eZdZdZfddZZS)NamedTupleConnectionz8A connection that uses `NamedTupleCursor` automatically.cs |d|jpttj||Sr>)r@r?NamedTupleCursorr!rrBr(r*r+rszNamedTupleConnection.cursorrCr*r*r(r+rsrcseZdZdZdZdZdfdd 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" Nicsd|_t||Sr,)Recordr!rGrHr(r*r+rG6szNamedTupleCursor.executecsd|_t||Sr,)rr! executemanyrHr(r*r+r:szNamedTupleCursor.executemanycsd|_t||Sr,)rr!rKrLr(r*r+rK>szNamedTupleCursor.callproccs<t}|dk r8|j}|dkr.|}|_||SdSr,)r!r-r_make_nt_make)r%tntr(r*r+r-Bs  zNamedTupleCursor.fetchonecs8t|}|j}|dkr(|}|_tt|j|Sr,)r!r1rrlistmapr)r%r2tsrr(r*r+r1Js  zNamedTupleCursor.fetchmanycs6t}|j}|dkr&|}|_tt|j|Sr,)r!r3rrrrr)r%rrr(r*r+r3Qs  zNamedTupleCursor.fetchallc#slzPt}t|}|j}|dkr0|}|_||V|t|Vq?@[\]^`{|}~]cCs(|jrtdd|jDnd}||S)Ncss|]}|dVqdS)rNr*rxr*r*r+ramsz,NamedTupleCursor._make_nt..r*)rMtuple_cached_make_nt)r%r|r*r*r+rlszNamedTupleCursor._make_ntcCsdg}|D]L}|jd|}|ddksBd|dkr>dkrJnnd|}||qtd|}|S)N_r09fr) _re_cleansubappendr)clsr|fieldssrr*r*r+ _do_make_ntps(  zNamedTupleCursor._do_make_nt)N)N)N)r8r9r:r;rZ MAX_CACHErGrrKr-r1r3r4_recompileescaperr classmethodrr<r*r*r(r+r#s     ricCs ||Sr,)r)rr|r*r*r+rsrcsHeZdZdZddZddZddZdd 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 cCs2||_tr&t|tjtjfr&|j|_n|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_loggingrTLogger 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.filtercCsD|||}|r@t|tr.|tj|jd}|j|t j dS)Nreplace) rrTbytesdecode_ext encodingsencodingrwrite_oslineseprr*r*r+rs   zLoggingConnection._logtofilecCs |||}|r|j|dSr,)rrdebugrr*r*r+rs zLoggingConnection._logtologgercCst|ds|ddS)Nrz3LoggingConnection object has not been initialize()d)hasattrProgrammingErrorrcr*r*r+_checks zLoggingConnection._checkcs(||d|jpttj||Sr>)rr@r? LoggingCursorr!rrBr(r*r+rszLoggingConnection.cursor) r8r9r:r;rrrrrrr<r*r*r(r+rs  rcs0eZdZdZdfdd Zdfdd ZZS) rzCA cursor that logs queries using its connection logging facilities.Nc s*zt||WS|j|j|XdSr,)rrrIr!rGrHr(r*r+rGszLoggingCursor.executec s*zt||WS|j|j|XdSr,)rrrIr!rKrLr(r*r+rKszLoggingCursor.callproc)N)N)r8r9r:r;rGrKr<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%rZmintimer*r*r+rs z#MinTimeLoggingConnection.initializecCsTt|jd}||jkrPt|tr:|tj|j d}|t j d|dSdS)Nirz (execution time: z ms)) _timetime timestamprrTrrrrrrr)r%rrrr*r*r+rs   zMinTimeLoggingConnection.filtercOs$|d|jpttj|f||Sr>)r@r?MinTimeLoggingCursorrrrBr*r*r+rszMinTimeLoggingConnection.cursorN)r)r8r9r:r;rrrr*r*r*r+rs rc@s$eZdZdZdddZdddZdS) rz=The cursor sub-class companion to `MinTimeLoggingConnection`.NcCst|_t|||Sr,)rrrrrGrHr*r*r+rGs zMinTimeLoggingCursor.executecCst|_t|||Sr,)rrrrrKrLr*r*r+rKs zMinTimeLoggingCursor.callproc)N)N)r8r9r:r;rGrKr*r*r*r+rs rcseZdZfddZZS)LogicalReplicationConnectioncst|d<tj||dSNreplication_type)r r!r"rBr(r*r+r"sz%LogicalReplicationConnection.__init__r8r9r:r"r<r*r*r(r+rsrcseZdZfddZZS)PhysicalReplicationConnectioncst|d<tj||dSr)r r!r"rBr(r*r+r"sz&PhysicalReplicationConnection.__init__rr*r*r(r+rsrc@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)r8r9r:r;r*r*r*r+rsrc@s4eZdZdZdddZddZdd d Zd d ZdS)rz;A cursor used for communication on replication connections.NcCsdt||d}|dkr"|jj}|tkrR|dkr\} } | dsZ|d7}|t| |dtt | 7}q>|d7}|j|||ddS)zStart replication stream.zSTART_REPLICATION NzSLOT rz-slot name is required for logical replicationrr/rXrZ08X lz/cannot specify timeline for logical replicationz TIMELINE z=cannot specify output plugin options for physical replicationz ((z, ))rstatus_interval)rrr r rrr rtypestrsplitrUrdendswith_AZstart_replication_expert) r%rrZ start_lsnZtimelineoptionsrrrZlsnkr[r*r*r+start_replication5sV    (    $z#ReplicationCursor.start_replicationcCs |jSr,)rfilenorcr*r*r+rpszReplicationCursor.fileno)NN)NNrrNFr)r8r9r: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 cCs ||_dSr,_uuid)r%uuidr*r*r+r"}szUUID_adapter.__init__cCs|tjkr|SdSr,rZ ISQLQuoter%protor*r*r+ __conform__s zUUID_adapter.__conform__cCsd|jddS)N''::uuidutf8)rencodercr*r*r+ getquotedszUUID_adapter.getquotedcCsd|jdS)Nrrrrcr*r*r+__str__szUUID_adapter.__str__N)r8r9r:r;r"rrrr*r*r*r+rvs rcsddl|sd}d}n t|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,)rrprrr*r+zregister_uuid..zUUID[]) rrTrrrnew_typernew_array_typeZ UUIDARRAY register_typeregister_adapterr)oids conn_or_cursoid1oid2r*rr+ register_uuids    rc@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. cCs ||_dSr,)addr)r%rr*r*r+r"sz Inet.__init__cCs|jjd|jdS)Nrr)r)r8rrcr*r*r+__repr__sz Inet.__repr__cCs ||_dSr,)_connr%connr*r*r+preparesz Inet.preparecCs,t|j}t|dr ||j|dS)Nrs::inet)rrrrrr)r%objr*r*r+rs   zInet.getquotedcCs|tjkr|SdSr,rrr*r*r+rs zInet.__conform__cCs t|jSr,)rrrcr*r*r+rsz Inet.__str__N) r8r9r:r;r"rrrrrr*r*r*r+rsrcCsddl}|dt|s"d}d}n t|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|r t|pdSr,)rrr*r*r+rrzregister_inet.. INETARRAY) warningswarnDeprecationWarningrTrrrrrrrr)oidrrrrr*r*r+ register_inets&   r cCsddl}ddlm}m}m}zf|}||kr4WqnL||krR||gggn.||krp|g|ggn|d|Wqtk r| YqYqXqdS)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_WRITEzbad state from poll: ) selectZpsycopg2.extensionsr r rpollrZOperationalErrorKeyboardInterruptcancel)rrr r rstater*r*r+ wait_selectsrcCsH|dkrtdt|dr0|j}|jtd}n|}|jtd}||fS)zEReturn the connection and a DBAPI cursor from a connection or cursor.Nz no connection or cursor providedrG)r?)rrrrrr{)rrrr*r*r+_solve_conn_curs s   rc@speZdZdZddZddZddZdd ZeZe d e j Z e e d fd d Ze ddZe ddZdS) HstoreAdapterz)Adapt a Python dict to the hstore syntax.cCs ||_dSr,)wrapped)r%rr*r*r+r"szHstoreAdapter.__init__cCs||_|jjdkr|j|_dS)Ni_)rinfoserver_version _getquoted_8rrr*r*r+rs zHstoreAdapter.preparecCs|js dStj}g}|jD]h\}}||}||j|}|dk rh||}||j|}nd}|d|d|dqdd|dS)z*Use the operators available in PG pre-9.0. ''::hstoreNsNULL(s => )s||) rrrrdrrrrjoin)r%rrvrr[r*r*r+r$s   zHstoreAdapter._getquoted_8cCsf|js dStt|j}||jtt|j}||jd|d|dS)z(Use the hstore(text[], text[]) function.rshstore(s, r) rrrrrfrrrgr)r%rr[r*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|dkr dSi}d}|j|D]h}|dks8||krHtd||d|d}|d}|dk rx|d|}|||<|}q |t|krtd||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_hstorefinditerstartrInterfaceErrorrgroupendrO) r%rcurZ_bsdecrr%mrr[r*r*r+parseVs(     zHstoreAdapter.parsecCs,|dkr dS|tj|jj}|||S)z2Parse an hstore returning unicode keys and values.N)rrrrrr+)r%rr)r*r*r+ parse_unicodewszHstoreAdapter.parse_unicodec Cst|\}}|j}|jjdkr"dp$d}gg}}|d|d|D] }||d||dqF|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) rstatusrrrGrrSTATUS_IN_TRANSACTION autocommitrollbackr) r%rrr conn_statusr.Zrv0Zrv1rr*r*r+get_oidss   zHstoreAdapter.get_oidsN)r8r9r:r;r"rrr rrrVERBOSEr#rr+r,r5r*r*r*r+rs     rFcCs|dkr>t|}|dks"|ds.tdn|d}|d}t|trN|f}|dk rzt|trh|f}ntdd|D}t|dtj }t || r|pdt t t|rt |d|}t || r|pddS) 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' filercSsg|] }|r|qSr*r*)r]rYr*r*r+rzsz#register_hstore..HSTORE HSTOREARRAY)rr5rrrTrUrrrr+rrdictr)rgloballyunicoder  array_oidr7r8r*r*r+register_hstores(    r=c@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 |_ |rzt |f|d|j |_ nd|_ dS)NcSsg|] }|dqSrwr*r]ar*r*r+rzsz,CompositeCaster.__init__..cSsg|] }|dqS)rr*r?r*r*r+rzsARRAY) nameschemar r<attnamesatttypes _create_typerrr+ typecasterrarray_typecaster)r%rBr attrsr<rCr*r*r+r"szCompositeCaster.__init__csl|dkr dS||}t|t|jkrHtdt|j|jt|ffddt|j|D}||S)Nz9expecting %d components for the type %s, %d found insteadcsg|]\}}||qSr*)cast)r]r tokenrr*r+rzsz)CompositeCaster.parse..)tokenizerOrErZ DataErrorrBzipmake)r%rrtokensrgr*rLr+r+s   zCompositeCaster.parsecCs ||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%rgr*r*r+rOs zCompositeCaster.makez \(? ([,)]) # an empty token, representing NULL | \(? " ((?: [^"] | "")*) " [,)] # or a quoted string | \(? ([^",)]+) [,)] # or an unquoted string z (["\\])\1c Csg}|j|D]p}|dkr,td||ddk rF|dq|ddk rp||jd|dq||dq|S)Nzcan't parse type: rr"r!) _re_tokenizer$rr&r'r _re_undoubler)r%rrr*r*r*r+rMs zCompositeCaster.tokenizecCst|||_|jj|_dSr,)rrrrQ)r%rBrDr*r*r+rF's zCompositeCaster._create_typec Cst|\}}|j}d|kr,|dd\}}n|}d}|jjdkrDdpFd}|d|||f|} |tjkr||j s|| | st 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)r"rRr*)r]rr*r*r+rzXsz,CompositeCaster._from_db..)r<rC) rr0rrrrGr3rr1r2r3rr) r%rBrrrr4rCZtnamer.ZrecsZtype_oidr<Z type_attrsr*r*r+_from_db+s8      zCompositeCaster._from_db)NN)r8r9r:r;r"r+rOrrr6rSrTrrMrFrXr*r*r*r+r>s    r>cCsV|dkr t}|||}t|j| r*|p,d|jdk rRt|j| rL|pNd|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)r>rXrrrGrH)rBrr:factoryZcasterr*r*r+register_composite^s   rZccs^g}t|}z*t|D]}|t|q|Vg}Wq tk rV|rP|VYdSXq dS)zwConsume an iterable and return it in chunks. Every chunk is at most `page_size`. Never return an empty chunk. N)rerNrr5r6)seq page_sizepagerrPr*r*r+ _paginatezs r^dcs:t||dD](}fdd|D}d|q 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. r\csg|]}|qSr*)mogrify)r]r&r)sqlr*r+rzsz!execute_batch..;N)r^rGr)r)rcargslistr\r]Zsqlsr*rbr+ execute_batchsrfc Csddlm}t||r ||}t|ts>|tj|jj }t |\}}|rRgnd} t ||dD]} |dkrdd dgt | dd}|dd} | D] } | ||| | dq|| d d<|d | |rb| |qb| 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) ComposableNr`r,s%srr)Z psycopg2.sqlrgrT as_stringrrrrrr _split_sqlr^rrOrrarGextendr3) r)rcretemplater\fetchrgprepostresultr]partsr&r*r*r+execute_valuess&<          rscCsg}}g}td|}|D]}t|dks<|dddkrH||q|dddkrp||krf|}qtdq|dddkr|dqtd|ddd d q||krtd ||fS) zSplit *sql* on a single ``%s`` placeholder. Split on the %s, perform %% replacement and return pre, post lists of snippets. s(%.)r"Nr%sz1the query contains more than one '%s' placeholderz"unsupported format character: '%s'asciirz.the query doesn't contain any '%s' placeholder)rrrOr ValueErrorr)rccurrrorprPrKr*r*r+rks*   rk)NN)NN)FFNN)FN)r_)Nr_F)Sr;osrrrrer collectionsrrloggingrrrrrr{r _connectionrrr functoolsr Zpsycopg2._psycopgr r r Z_replicationConnectionrZ_replicationCursorrZpsycopg2._jsonrrrrrZpsycopg2._rangerrrrrrrrZpsycopg2._ipaddressrrr=rArrDrsrtrurrrrrrrrrrrhrrrrr rrrr=r>rZr^rfrsrkr*r*r*r+sl    ( <6#\  3  h " !  <   W