B *]@sdZddlZddlZddlZddlmZm Z ddl Z ddl Z ddl m Zddl mZddl mZddl mZmZdd lmZmZmZdd lmZmZmZmZ m!Z!dd 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/m0Z0dd l1m2Z2GdddeZ3GdddeZ4Gddde3Z5Gddde6Z7GdddeZ8Gddde3Z9Gddde Z:GdddeZ;GdddeZe=e<_=Gd#d$d$eZ?Gd%d&d&eZ@Gd'd(d(e?ZAGd)d*d*e@ZBGd+d,d,eZCGd-d.d.eZDGd/d0d0eEZFGd1d2d2e ZGd3d4d4eGZHdQd5d6ZIGd7d8d8eGZJdRd9d:ZKd;d<ZLd=d>ZMGd?d@d@eGZNdSdBdCZOGdDdEdEeGZPdTdFdGZQdHdIZRdUdKdLZSdVdMdNZTdOdPZUdS)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)PY2PY3 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|kr|d}|d=ntdtt|j||d|_d|_||_dS)N row_factoryz;DictCursorBase can't be instantiated without a row factory.F)NotImplementedErrorsuperr __init___query_executed _prefetchr!)selfargskwargsr!) __class__B/opt/alt/python37/lib64/python3.7/site-packages/psycopg2/extras.pyr$CszDictCursorBase.__init__cs:|jrtt|}|jr"||js6tt|}|S)N)r&r#r fetchoner% _build_index)r'res)r*r+r,r-OszDictCursorBase.fetchoneNcs>|jrtt||}|jr$||js:tt||}|S)N)r&r#r fetchmanyr%r.)r'sizer/)r*r+r,r0XszDictCursorBase.fetchmanycs:|jrtt|}|jr"||js6tt|}|S)N)r&r#r fetchallr%r.)r'r/)r*r+r,r2aszDictCursorBase.fetchallc#szy`|jrtt|}t|}|jr,||jsHtt|}t|}|Vxt|VqPWWntk rtdSXdS)N)r&r#r __iter__nextr%r. StopIteration)r'r/first)r*r+r,r3jszDictCursorBase.__iter__)N) __name__ __module__ __qualname____doc__r$r-r0r2r3 __classcell__r+r+)r*r,r @s   r cs eZdZdZfddZZS)DictConnectionz2A connection that uses `DictCursor` automatically.cs|dttt|j||S)Ncursor_factory) setdefault DictCursorr#r<r)r'r(r))r*r+r,r~s zDictConnection.cursor)r7r8r9r:rr;r+r+)r*r,r<|sr<csDeZdZdZfddZd fdd Zd fdd Zd d ZZS) r?z index mappings.cs$t|d<tt|j||d|_dS)Nr!T)DictRowr#r?r$r&)r'r(r))r*r+r,r$szDictCursor.__init__Ncs t|_d|_tt|||S)NT)rindexr%r#r?execute)r'queryvars)r*r+r,rBszDictCursor.executecs t|_d|_tt|||S)NT)rrAr%r#r?callproc)r'procnamerD)r*r+r,rEszDictCursor.callproccCsB|jr>|jr>x*tt|jD]}||j|j|d<qWd|_dS)NrF)r% descriptionrangelenrA)r'ir+r+r,r.s zDictCursor._build_index)N)N) r7r8r9r:r$rBrEr.r;r+r+)r*r,r?s  r?cseZdZdZdZddZfddZfddZfd d Zd d Z fd dZ dddZ ddZ ddZ ddZddZere Ze ZeZe Zdd Z ddZ dd ZZS)r@z6A row object that allow by-column-name access to data.)_indexcCs$|j|_dgt|j|dd<dS)N)rArKrIrG)r'rr+r+r,r$szDictRow.__init__cs(t|ttfs|j|}tt||S)N) isinstanceintslicerKr#r@ __getitem__)r'x)r*r+r,rOs zDictRow.__getitem__cs.t|ttfs|j|}tt|||dS)N)rLrMrNrKr#r@ __setitem__)r'rPv)r*r+r,rQs zDictRow.__setitem__cs"ttjfddjDS)Nc3s |]}|j|fVqdS)N)rK).0n)gr'r+r, sz DictRow.items..)r#r@rOrK)r')r*)rUr'r,itemss z DictRow.itemscCs t|jS)N)iterrK)r'r+r+r,keyssz DictRow.keyscs"ttjfddjDS)Nc3s|]}j|VqdS)N)rK)rSrT)rUr'r+r,rVsz!DictRow.values..)r#r@rOrK)r')r*)rUr'r,valuess zDictRow.valuesNcCs"y||Stk r|SXdS)N) Exception)r'rPdefaultr+r+r,getsz DictRow.getcCs t|S)N)rrW)r'r+r+r,copysz DictRow.copycCs ||jkS)N)rK)r'rPr+r+r, __contains__szDictRow.__contains__cCs|dd|jfS)N)rKr^)r'r+r+r, __getstate__szDictRow.__getstate__cCs|d|dd<|d|_dS)Nrr)rK)r'datar+r+r, __setstate__szDictRow.__setstate__cCs t|S)N)listiterkeys)r'r+r+r,rYscCs t|S)N)tuple itervalues)r'r+r+r,rZscCs t|S)N)rc iteritems)r'r+r+r,rWs)N)r7r8r9r: __slots__r$rOrQrWrYrZr]r^r_r`rbr rdrfrgZhas_keyr;r+r+)r*r,r@s*     r@cs eZdZdZfddZZS)RealDictConnectionz6A connection that uses `RealDictCursor` automatically.cs|dttt|j||S)Nr=)r>RealDictCursorr#rir)r'r(r))r*r+r,rs zRealDictConnection.cursor)r7r8r9r:rr;r+r+)r*r,risricsDeZdZdZfddZd fdd Zd fdd Zd d ZZS) rjaQA 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<tt|j||dS)Nr!) RealDictRowr#rjr$)r'r(r))r*r+r,r$szRealDictCursor.__init__Ncsg|_d|_tt|||S)NT)column_mappingr%r#rjrB)r'rCrD)r*r+r,rBszRealDictCursor.executecsg|_d|_tt|||S)NT)rlr%r#rjrE)r'rFrD)r*r+r,rEszRealDictCursor.callproccCs(|jr$|jr$dd|jD|_d|_dS)NcSsg|] }|dqS)rr+)rSdr+r+r, sz/RealDictCursor._build_index..F)r%rGrl)r'r+r+r,r.s zRealDictCursor._build_index)N)N) r7r8r9r:r$rBrEr.r;r+r+)r*r,rjs  rjcs,eZdZdZfddZfddZZS)rkz.A `!dict` subclass representing a data record.csh|r(t|dtr(|d}|dd}nd}tt|j|||dk rd|jrZ|jsZ||j|t<dS)Nrr)rL_cursorr#rkr$rGrlr.)r'r(r)r)r*r+r,r$s zRealDictRow.__init__csVt|kr@|t}tt|||||t|dkr<|t=dStt|||dS)Nr)rkr#rQrI)r'keyvaluemapping)r*r+r,rQszRealDictRow.__setitem__)r7r8r9r:r$rQr;r+r+)r*r,rks rkcs eZdZdZfddZZS)NamedTupleConnectionz8A connection that uses `NamedTupleCursor` automatically.cs|dttt|j||S)Nr=)r>NamedTupleCursorr#rsr)r'r(r))r*r+r,r%s zNamedTupleConnection.cursor)r7r8r9r:rr;r+r+)r*r,rs#srscseZdZdZdZdZdfdd ZfddZdfdd Zfd d Z dfd d Z fddZ fddZ e de ddZddZeddZZS)rtaA 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|_tt|||S)N)Recordr#rtrB)r'rCrD)r*r+r,rB=szNamedTupleCursor.executecsd|_tt|||S)N)rur#rt executemany)r'rCrD)r*r+r,rvAszNamedTupleCursor.executemanycsd|_tt|||S)N)rur#rtrE)r'rFrD)r*r+r,rEEszNamedTupleCursor.callproccs@tt|}|dk r<|j}|dkr2|}|_||SdS)N)r#rtr-ru_make_nt_make)r'tnt)r*r+r,r-Is zNamedTupleCursor.fetchonecs<tt||}|j}|dkr,|}|_tt|j|S)N)r#rtr0rurwrcmaprx)r'r1tsrz)r*r+r,r0Qs zNamedTupleCursor.fetchmanycs:tt|}|j}|dkr*|}|_tt|j|S)N)r#rtr2rurwrcr{rx)r'r|rz)r*r+r,r2Xs zNamedTupleCursor.fetchallc#sryXtt|}t|}|j}|dkr4|}|_||Vx|t|VqBWWntk rldSXdS)N)r#rtr3r4rurwrxr5)r'itryrz)r*r+r,r3_s zNamedTupleCursor.__iter__[z !"#$%&'()*+,-./:;<=>?@[\]^`{|}~]cCs(|jrtdd|jDnd}||S)Ncss|]}|dVqdS)rNr+)rSrmr+r+r,rVtsz,NamedTupleCursor._make_nt..r+)rGre_cached_make_nt)r'rpr+r+r,rwsszNamedTupleCursor._make_ntcCshg}xT|D]L}|jd|}|ddksDd|dkr@dkrLnnd|}||q Wtd|}|S)N_r09fru) _re_cleansubappendr)clsrpZfieldssrzr+r+r, _do_make_ntws ( zNamedTupleCursor._do_make_nt)N)N)N)r7r8r9r:ruZ MAX_CACHErBrvrEr-r0r2r3_recompileescaperrw classmethodrr;r+r+)r*r,rt*s    rticCs ||S)N)r)rrpr+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 cCs,||_tr t|tjr |j|_n|j|_dS)zInitialize the connection to log to `!logobj`. The `!logobj` parameter can be an open file object or a Logger instance from the standard logging module. N)_logobj_loggingrLZLogger _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|||}|rDtr2t|tr2|tj|jd}|j |t j dS)Nreplace) rr rLbytesdecode_ext encodingsencodingrwrite_oslinesep)r'rrr+r+r,rs  zLoggingConnection._logtofilecCs |||}|r|j|dS)N)rrdebug)r'rrr+r+r,rs zLoggingConnection._logtologgercCst|ds|ddS)Nrz3LoggingConnection object has not been initialize()d)hasattrProgrammingError)r'r+r+r,_checks zLoggingConnection._checkcs&||dttt|j||S)Nr=)rr> LoggingCursorr#rr)r'r(r))r*r+r,rs zLoggingConnection.cursor) r7r8r9r:rrrrrrr;r+r+)r*r,rs  rcs0eZdZdZdfdd Zdfdd ZZS) rzCA cursor that logs queries using its connection logging facilities.Nc s*ztt|||S|j|j|XdS)N)r#rrBrrrC)r'rCrD)r*r+r,rBszLoggingCursor.executec s*ztt|||S|j|j|XdS)N)r#rrErrrC)r'rFrD)r*r+r,rEszLoggingCursor.callproc)N)N)r7r8r9r:rBrEr;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||||_dS)N)rr_mintime)r'rZmintimer+r+r,rs z#MinTimeLoggingConnection.initializecCsTt|jd}||jkrPtr>t|tr>|tj |j d}|t j d|SdS)Nirz (execution time: %d ms)) _timetime timestamprr rLrrrrrrr)r'rrryr+r+r,rs  zMinTimeLoggingConnection.filtercOs|dttj|f||S)Nr=)r>MinTimeLoggingCursorrr)r'r(r)r+r+r,rs zMinTimeLoggingConnection.cursorN)r)r7r8r9r:rrrr+r+r+r,rs  rc@s$eZdZdZdddZdddZdS) rz=The cursor sub-class companion to `MinTimeLoggingConnection`.NcCst|_t|||S)N)rrrrrB)r'rCrDr+r+r,rBs zMinTimeLoggingCursor.executecCst|_t|||S)N)rrrrrE)r'rFrDr+r+r,rEs zMinTimeLoggingCursor.callproc)N)N)r7r8r9r:rBrEr+r+r+r,rs rcseZdZfddZZS)LogicalReplicationConnectioncst|d<tt|j||dS)Nreplication_type)rr#rr$)r'r(r))r*r+r,r$sz%LogicalReplicationConnection.__init__)r7r8r9r$r;r+r+)r*r,rsrcseZdZfddZZS)PhysicalReplicationConnectioncst|d<tt|j||dS)Nr)r r#rr$)r'r(r))r*r+r,r$sz&PhysicalReplicationConnection.__init__)r7r8r9r$r;r+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)r7r8r9r:r+r+r+r,rsrc@s4eZdZdZdddZddZdd d Zd d ZdS)rz;A cursor used for communication on replication connections.NcCsdt||}|dkr|jj}|tkrL|dkr8td|dt||7}n6|tkrp|dk rftd|d7}ntdt|||dS)z"Create streaming replication slot.zCREATE_REPLICATION_SLOT %s NzAoutput plugin name is required to create logical replication slotz LOGICAL %szIcannot specify output plugin name when creating physical replication slotZPHYSICALz!unrecognized replication type: %s) r rrrpsycopg2rr reprrB)r' slot_name slot_typeZ output_plugincommandr+r+r,create_replication_slots  z)ReplicationCursor.create_replication_slotcCsdt||}||dS)z Drop streaming replication slot.zDROP_REPLICATION_SLOT %sN)r rB)r'rrr+r+r,drop_replication_slot3sz'ReplicationCursor.drop_replication_slotrF c Csd}|dkr|jj}|tkrH|r4|dt||7}n td|d7}n2|tkrh|rz|dt||7}ntdt|t|t kr| d} dt | d d t | d d f} nd|d ?d @|d @f} || 7}|d kr|tkrtd|d|7}|rl|tkrtd|d7}xH| D]<\} } | ds@|d7}|dt| |tt | f7}q$W|d7}|j|||ddS)zStart replication stream.zSTART_REPLICATION NzSLOT %s z-slot name is required for logical replicationzLOGICAL z!unrecognized replication type: %s/z%X/%08Xrr lz/cannot specify timeline for logical replicationz TIMELINE %dz=cannot specify output plugin options for physical replicationz ((z, z%s %s))rstatus_interval)rrrr rrr rtypestrsplitrMrWendswith_AZstart_replication_expert) r'rrZ start_lsnZtimelineZoptionsrrrZlsnkrRr+r+r,start_replication9sJ   "     $z#ReplicationCursor.start_replicationcCs |jS)N)rfileno)r'r+r+r,ruszReplicationCursor.fileno)NN)NNrrNFr)r7r8r9r: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 ||_dS)N)_uuid)r'uuidr+r+r,r$szUUID_adapter.__init__cCs|tjkr|SdS)N)r ISQLQuote)r'protor+r+r, __conform__s zUUID_adapter.__conform__cCsd|jdS)Nz '%s'::uuidutf8)rencode)r'r+r+r, getquotedszUUID_adapter.getquotedcCs d|jS)Nz '%s'::uuid)r)r'r+r+r,__str__szUUID_adapter.__str__N)r7r8r9r:r$rrrr+r+r+r,r{s 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|pdS)N)r)rar)rr+r,zregister_uuid..zUUID[]) rrLrcrernew_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 ||_dS)N)addr)r'rr+r+r,r$sz Inet.__init__cCsd|jj|jfS)Nz%s(%r))r*r7r)r'r+r+r,__repr__sz Inet.__repr__cCs ||_dS)N)_conn)r'connr+r+r,preparesz Inet.preparecCs,t|j}t|dr ||j|dS)Nrs::inet)rrrrrr)r'objr+r+r,rs   zInet.getquotedcCs|tjkr|SdS)N)rr)r'rr+r+r,rs zInet.__conform__cCs t|jS)N)rr)r'r+r+r,rsz Inet.__str__N) r7r8r9r: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|pdS)N)r)rarr+r+r,rrzregister_inet.. INETARRAY) warningswarnDeprecationWarningrLrcrerrrrrr)oidrrrrr+r+r, register_inets"    rcCsddl}ddlm}m}m}xyb|}||kr4PnJ||krR||gggn,||krp|g|ggn|d|Wqtk r| wYqXqWdS)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: %s) selectZpsycopg2.extensionsrrrZpollrZOperationalErrorKeyboardInterruptZcancel)rrrrrstater+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 providedrB)r=)rrrrrro)rrrr+r+r,_solve_conn_curss   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 ||_dS)N)wrapped)r'rr+r+r,r$szHstoreAdapter.__init__cCs||_|jjdkr|j|_dS)Ni_)rinfoserver_version _getquoted_8r)r'rr+r+r,r"s zHstoreAdapter.preparecCs|js dStj}g}xv|jD]h\}}||}||j|}|dk rj||}||j|}nd}|d|d|dq Wdd|dS)z*Use the operators available in PG pre-9.0.s ''::hstoreNsNULL(s => )s||) rrrrWrrrrjoin)r'rrvrrRr+r+r,r)s   zHstoreAdapter._getquoted_8cCsf|js dStt|j}||jtt|j}||jd|d|dS)z(Use the hstore(text[], text[]) function.s ''::hstoreshstore(s, r) rrrrcrYrrrZr)r'rrRr+r+r, _getquoted_9As  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}xv|j|D]f}|dks:||krHtd||d|d}|d}|dk rx|d|}|||<|}q"W|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 %dz\1rz1error parsing hstore: unparsed data after char %d) _re_hstorefinditerstartrInterfaceErrorrgroupendrI) r'rcurZ_bsdecrrmrrRr+r+r,parse[s$       zHstoreAdapter.parsecCs,|dkr dS|tj|jj}|||S)z2Parse an hstore returning unicode keys and values.N)rrrrrr)r'rrr+r+r, parse_unicode|szHstoreAdapter.parse_unicodec Cst|\}}|j}|jjdkr"dp$d}gg}}|d|x(|D] }||d||dqDW|tjkr|js| t |t |fS)zBReturn the lists of OID of the hstore and hstore[] types. i9typarrayNULLzlSELECT t.oid, %s FROM pg_type t JOIN pg_namespace ns ON typnamespace = ns.oid WHERE typname = 'hstore'; rr) rstatusrrrBrrSTATUS_IN_TRANSACTION autocommitrollbackre) r'rrr conn_statusr Zrv0Zrv1rr+r+r,get_oidss     zHstoreAdapter.get_oidsN)r7r8r9r:r$rrrrrrVERBOSErrrrrr+r+r+r,rs   rFcCs|dkr>t|}|dks"|ds.tdn|d}|d}t|trN|f}|dk rzt|trh|f}ntdd|D}tr|rtj}ntj }t |d|}t || r|pdt tt|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+)rSrPr+r+r,rnsz#register_hstore..HSTORE HSTOREARRAY)rrrrrLrMrer rrrrrrdictr)rgloballyZunicoder array_oidcastrrr+r+r,register_hstores,    rc@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 |_ |rxt |fd||j |_ nd|_ dS)NcSsg|] }|dqS)rr+)rSar+r+r,rnsz,CompositeCaster.__init__..cSsg|] }|dqS)rr+)rSrr+r+r,rnsz%sARRAY) nameschemarrattnamesatttypes _create_typerrr typecasterrarray_typecaster)r'rrZattrsrrr+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+)r)rSrtoken)rr+r,rn sz)CompositeCaster.parse..)tokenizerIrrZ DataErrorrzipmake)r'rrtokensrZr+)rr,rs  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'rZr+r+r,r%s zCompositeCaster.makez \(? ([,)]) # an empty token, representing NULL | \(? " ((?: [^"] | "")*) " [,)] # or a quoted string | \(? ([^",)]+) [,)] # or an unquoted string z (["\\])\1c Csg}x~|j|D]n}|dkr,td||ddk rF|dq|ddk rp||jd|dq||dqW|S)Nzcan't parse type: %rrrz\1) _re_tokenizerrrrr _re_undoubler)r'rrrr+r+r,r##s zCompositeCaster.tokenizecCst|||_|jj|_dS)N)rrrxr')r'rrr+r+r,r2s 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 S) z}Return a `CompositeCaster` instance for the type *name*. Raise `ProgrammingError` if the type is not found. .rZpublici9r 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 '%s' not foundrcSsg|]}|d|dfqS)rr(r+)rSrr+r+r,rncsz,CompositeCaster._from_db..)rr) rr rrrrBr2rr r rrr) r'rrrrrrZtnamer ZrecsZtype_oidrZ type_attrsr+r+r,_from_db6s*     zCompositeCaster._from_db)NN)r7r8r9r:r$rr%rrrr)r*rr#rr-r+r+r+r,rs     rcCsV|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)rr-rrr r!)rrrfactoryZcasterr+r+r,register_compositeis  r/ccsdg}t|}xRy.xt|D]}|t|qW|Vg}Wqtk rZ|rV|VdSXqWdS)zwConsume an iterable and return it in chunks. Every chunk is at most `page_size`. Never return an empty chunk. N)rXrHrr4r5)seq page_sizepager}rJr+r+r, _paginatesr3dcs>x8t||dD](}fdd|D}d|qWdS)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. )r1csg|]}|qSr+)mogrify)rSr()rsqlr+r,rnsz!execute_batch..;N)r3rBr)rr6argslistr1r2Zsqlsr+)rr6r, execute_batchsr9c Csddlm}t||r ||}t|ts>|tj|jj }t |\}}|rRgnd} xt ||dD]} |dkrdd dgt | dd}|dd} x(| D] } | ||| | dqW|| d d<|d | |rd| |qdW| 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) ComposableN)r1r,s%srr)Z psycopg2.sqlr:rLZ as_stringrrrrrr _split_sqlr3rrIrr5rBextendr2) rr6r8templater1Zfetchr:prepostresultr2partsr(r+r+r,execute_valuess&<          rDcCsg}}g}td|}x|D]}t|dks>|dddkrJ||q|dddkrr||krh|}qtdq|dddkr|dqtd|ddd d qW||krtd ||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)rrrIr ValueErrorr)r6Zcurrr@rAr&r"r+r+r,r=s&    r=)NN)NN)FFNN)FN)r4)Nr4F)Vr:osrrrrer collectionsrrZloggingrrrrrrorZ _connectionrrr compatr r r Zpsycopg2._psycopgr rrZ_replicationConnectionrZ_replicationCursorrZpsycopg2._jsonrrrrrZpsycopg2._rangerrrrrrrrZpsycopg2._ipaddressrr r<r?rcr@rirjrkrsrtrrrrrrrrr[robjectrrrrrrrrrr/r3r9rDr=r+r+r+r,sf   ( <A#\ 2  i " !  @   W