o ^O @s$dZddlmZmZzddlTWnTeydddlZddlZejdkraej dkraej d ej D],Z ej ej e dr^eej e  ddlTWdn1sWwYnq2nYnweZgd Zdd lmZmZmZmZmZdd lmZdd lmadd lmZddl m!Z!m"Z"zddl#m$Z$Wneyddl%m$Z$Ynwddl%m&Z&ddl'm(Z(ddl)m*Z*ddl+m,Z-ddl.m/Z0m1Z2ze3Wn e4ye5Z3Ynwze6Wn e4ye7Z6Ynwze8Wn e4ye7e9fZ8Ynwzddl)m:Z:Wn/ey4ddl)m;Z;zddldZ?dZ@dZAzdd lBmCZCWneyYdd!lBmDZDd"d#ZEYnwd$d#ZEzdd%lmFZFWneyGd&d'd'eZFeFedd(eF_Gd)ZHYnwd*ZHeId+d,d-d.d/d+d0d.d.d.d1 ZJd2d3ZKd4d5ZLdd6d7ZMd8d9ZNd:d;ZOdd?ZQd@dAZRe-dBZSdCdDZTdEdFZUdGdHZVe-dIZWe-dJZXe-dKZYe-dLZZdMdNZ[GdOdPdPeIZ\e\Z]dQdRZ^dSdTZ_ddUdVZ`GdWdXdXe\ZaGdYdZdZe7Zbe&d[d\d]gZcGd^d_d_eIZdGd`dadaeIZeeffdbdcZgdddeZhe-dfZie:dgdhdidjajdkdlZkGdmdndnelZme&dogdpZnGdqdrdrelZoepZq   ddsdtZpGdudvdverZsGdwdxdxZtGdydzdzZuesd{Zvesd|Zwesd}Zxesd~ZyesdZzesdZ{esdZ|esdZ}esdZ~esdZesdZesdZesdZesdZesdZesdZesdZesdZesdZetZeuZddZdddZ  dddZddZddZddZGddde9ZdddZeZGdddeIZGdddZGdddZedkredeedeedSdS)aBpgdb - DB-API 2.0 compliant module for PyGreSQL. (c) 1999, Pascal Andre . See package documentation for further information on copyright. Inline documentation is sparse. See DB-API 2.0 specification for usage information: http://www.python.org/peps/pep-0249.html Basic usage: pgdb.connect(connect_string) # open a connection # connect_string = 'host:database:user:password:opt' # All parts are optional. You may also pass host through # password as keyword arguments. To pass a port, # pass it in the host keyword parameter: connection = pgdb.connect(host='localhost:5432') cursor = connection.cursor() # open a cursor cursor.execute(query[, params]) # Execute a query, binding params (a dictionary) if they are # passed. The binding syntax is the same as the % operator # for dictionaries, and no quoting is done. cursor.executemany(query, list of params) # Execute a query many times, binding each param dictionary # from the list. cursor.fetchone() # fetch one row, [value, value, ...] cursor.fetchall() # fetch all rows, [[value, value, ...], ...] cursor.fetchmany([size]) # returns size or cursor.arraysize number of rows, # [[value, value, ...], ...] from result set. # Default cursor.arraysize is 1. cursor.description # returns information about the columns # [(column_name, type_name, display_size, # internal_size, precision, scale, null_ok), ...] # Note that display_size, precision, scale and null_ok # are not implemented. cursor.rowcount # number of rows available in the result set # Available after a call to execute. connection.commit() # commit transaction connection.rollback() # or rollback transaction cursor.close() # close the cursor connection.close() # close the connection )print_functiondivision)*Nnt)PATHz libpq.dll)6 ConnectionCursorDateTime Timestamp DateFromTicks TimeFromTicksTimestampFromTicksBinaryIntervalUuidHstoreJsonLiteralTypeSTRINGBINARYNUMBERDATETIMEROWIDBOOLSMALLINTINTEGERLONGFLOATNUMERICMONEYDATETIME TIMESTAMPINTERVALUUIDHSTOREJSONARRAYRECORDErrorWarningInterfaceError DatabaseError DataErrorOperationalErrorIntegrityErrorProgrammingErrorNotSupportedErrorapilevelconnect paramstyle threadsafety get_typecast set_typecastreset_typecastversion __version__)datetimedatetime timedeltatzinfo) localtime)Decimal)r()isnanisinf)Iterable namedtuple) iskeyword)partial)compile)loadsdumps) lru_cache)update_wrapper)RLockc@seZdZddZddZdS)rRcCdSNselfrUrU&/usr/lib/python3/dist-packages/pgdb.py __enter__zRLock.__enter__cCrSrTrU)rWexctypeexcinstexctbrUrUrX__exit__rZzRLock.__exit__N)__name__ __module__ __qualname__rYr^rUrUrUrXrRs rRcsfdd}|S)z:Simplified functools.lru_cache decorator for one argument.cstijtg}|dg||ddg|dd<dkr&fdd}ndur4fdd}n fdd}|_t|S)NFrcs |}|SrTrUargres)functionrUrXwrappersz-lru_cache..decorator..wrappercs*|}|ur |S|}||<|SrTrUrc)cacherfgetsentinelrUrXrgs c s?|}|dur:d}|\}}}}||d<||d<|d}||d<|d<||d<||d<|WdSWdn1sDwY|}v\}}|vrYnT|r|} || d<|| d<| d}d<|d} |d} d|d<|d<| =| |<n8|d}||||g}||d<|d<|<tkrdd<Wd|SWd|SWd|SWd|S1swY|S)NrrTlen) rdlinkrootprevnext_argrelastfulloldrootoldargoldres)rhrfrilockmaxsize root_fullrUrXrgs`          )objectrirR __wrapped__rQ)rfrprgrz)rhrfriryr{rjrX decorators $ zlru_cache..decoratorrU)rzrrUr~rXrPs BrPz2.0rkpyformat) signature) getargspeccCs t|jSrT)rargsfuncrUrUrXget_args rcCstt|jSrT)listr parametersrrUrUrXr)timezonec@s2eZdZdZd ddZddZddZd d ZdS) rzSimple timezone implementation.NcCsf||_|s.|jjd|jjd}|dkr!t| d\}}| }nt|d\}}d||f}||_dS)Ni<rz UTC%+03d:%02d)offsetdayssecondsdivmodname)rWrrminuteshoursrUrUrX__init__s  ztimezone.__init__cC|jSrT)rrWdtrUrUrX utcoffset ztimezone.utcoffsetcCrrTrrrUrUrXtznamerztimezone.tznamecCrSrTrUrrUrUrXdstsz timezone.dstrT)r_r`ra__doc__rrrrrUrUrUrXrs    rUTCFTz+0100z+0200z-0500+0000z-1000z-0700) CETEETESTGMTHSTMETMSTUCTrWETcCs6|drt|dkr|dS|ddSt|dS)N)+-00:r) startswithrnreplace _timezonesri)tzrUrUrX_timezone_as_offset!s    rcCsNt|}dt|ddt|dd}|ddkr| }tt|d|S)Nrrkrrrr)r)rintrrB)rrrUrUrX _get_timezone)s $ rcCs|dur |atd|tS)zGet or set global type to be used for decimal values. Note that connections cache cast functions. To be sure a global change is picked up by a running connection, call con.type_cache.reset_typecast(). Nnumeric)rEr;) decimal_typerUrUrXr1s rcCs|r|ddvSdS)z.Cast boolean value in database format to bool.r)tTNrUvaluerUrUrX cast_bool>s rcCs,|r|dd}tddd|DSdS)z/Cast money value in database format to Decimal.(rrcss$|] }|s |dvr|VqdS)z.-N)isdigit).0crUrUrX H"zcast_money..N)rrEjoinrrUrUrX cast_moneyDs rcCsdd|DS)zCast an int2vector value.cSg|]}t|qSrUrrvrUrUrX Mz#cast_int2vector..)splitrrUrUrXcast_int2vectorKrcCsh|dkrtjS|dkrtjS|}|ddkrtjS|d}t|dkr(tjS|}t||S)zCast a date value. -infinityinfinityBCr )r?minmaxrrn date_formatrAstrptimer connectionfmtrUrUrX cast_datePs  rcCs$t|dkrdnd}t||S)zCast a time value.r %H:%M:%S.%f%H:%M:%S)rnrArr@)rrrUrUrX cast_timedsrz (.*)([+-].*)cCsxt|}|r|\}}nd}t|dkrdnd}tr.|t|7}|d7}t||St||j t |dS)zCast a timetz value.rrrr%zrC) _re_timezonematchgroupsrn _has_timezonerrArtimetzrr)rrrrUrUrX cast_timetzms  rcCs|dkrtjS|dkrtjS|}|ddkrtjS|}|drRt|dkrR|dd}t|d d kr;tjS|d rBd nd t|ddkrMdnddg}nt|ddkr]tjS|t|ddkrhdndg}td |d |S)zCast a timestamp value.rrrr-%Yrlrkrr%d%d %b%b %drrr%Yrr ) rArrrrendswithrnrrrrrUrUrXcast_timestamp}s&  rcCs|dkrtjS|dkrtjS|}|ddkrtjS|}|dr]t|dkr]|dd}t|d d kr;tjS|d rBd nd t|ddkrMdnddg}|dd|d}}n>|drwt |d}|rt| \|d<}nd}n |dd|d}}t|ddkrtjS|t|ddkrdndg}t r| t || dtd|d|Std|d|jt|dS)zCast a timestamptz value.rrrrrrlrkNrrrrrrrrrz%Y-rrrrrr)rArrrrrrnrrrrrappendrrrrr)rrrrrUrUrXcast_timestamptzs@    rzm(?:([+-])?([0-9]+)-([0-9]+) ?)?(?:([+-]?[0-9]+)(?!:) ?)?(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\.([0-9]+))?)?z(?:([+-]?[0-9]+) ?years? ?)?(?:([+-]?[0-9]+) ?mons? ?)?(?:([+-]?[0-9]+) ?days? ?)?(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\.([0-9]+))?)?z@ ?(?:([+-]?[0-9]+) ?years? ?)?(?:([+-]?[0-9]+) ?mons? ?)?(?:([+-]?[0-9]+) ?days? ?)?(?:([+-]?[0-9]+) ?hours? ?)?(?:([+-]?[0-9]+) ?mins? ?)?(?:([+-])?([0-9]+)(?:\.([0-9]+))? ?secs?)? ?(ago)?zP(?:([+-]?[0-9]+)Y)?(?:([+-]?[0-9]+)M)?(?:([+-]?[0-9]+)D)?(?:T(?:([+-]?[0-9]+)H)?(?:([+-]?[0-9]+)M)?(?:([+-])?([0-9]+)(?:\.([0-9]+))?S)?)?c Cs&t|}|r0dd|D}|ddk}dd|D}|\}}}}}}} |r/| }| } nt|}|rsdd|ddD|d }} |ddk}| rZd d|Dnd d|D}|\}}}}}}} |rr| }| } nt|}|rt|rd d|D}|d dk} dd|D}|\}}}}}}} | r| }| }| }| } nQt|}|rt|rdd|D}|ddk} |d dk} dd|D}|\}}}}}}} | r| }| }| r| }| }| }| } nt d||d|d|7}t ||||| dS)zCast an interval value.cSg|]}|pdqS0rUrdrUrUrXrrz!cast_interval..rrcSrrUrrrUrUrXrrcSrrrUrrUrUrXrrNr cSsg|]}t| qSrUrrrUrUrXrcSrrUrrrUrUrXrrcSrrrUrrUrUrXrrrcSrrUrrrUrUrXrrcSrrrUrrUrUrXrrrcSrrUrrrUrUrXrrzCannot parse interval: %simrrrr microseconds) _re_interval_iso_8601rrpop_re_interval_postgres_verbosegroup_re_interval_postgresany_re_interval_sql_standard ValueErrorrB) rmsecs_agoyearsmonsrrminssecsusecsago hours_ago years_agorUrUrX cast_intervalsj  &    r c@seZdZdZidededededededed ed ed ed ed ede de de de de e e eeeeeeeeeed ZdZddZeddZddZd%ddZddZd%dd Z d!d"Z!d#d$Z"dS)& Typecastsa@Dictionary mapping database types to typecast functions. The cast functions get passed the string representation of a value in the database which they need to convert to a Python object. The passed string will never be None since NULL values are already handled before the cast function is called. charbpcharrtextvarcharboolbyteaint2int4serialint8oidhstorejsonjsonbfloat4float8) rmoneyr?intervalr@r timestamp timestamptz int2vectoruuidanyarrayrecordNcCspt|ts td||j|}|r||}|||<|S|dr6||dd}||}|r6|||<|S)zCreate a cast function if it is not cached. Note that this class never raises a KeyError, but returns None when no special cast function exists. zInvalid type: %s_rkN) isinstancestr TypeErrordefaultsri_add_connectionrcreate_array_cast)rWtypcast base_castrUrUrX __missing__*s      zTypecasts.__missing__c Cs6zt|}Wn ttfyYdSwd|ddvS)z9Check if a typecast function needs a connection argument.FrrkN)rr*r)rrrUrUrX_needs_connection@s  zTypecasts._needs_connectioncCs"|jr||s |St||jdS)z@Add a connection argument to the typecast function if necessary.)r)rr2rL)rWr/rUrUrXr,JszTypecasts._add_connectioncCs ||p|Sz6Get the typecast function for the given database type.rU)rWr.defaultrUrUrXriP z Typecasts.getcCs~t|tr|g}|dur!|D]}||d|d|dqdSt|s)td|D]}||||<|d|dq+dS);Set a typecast function for the specified database type(s).N_%szCast parameter must be callable)r( basestringrcallabler*r,)rWr.r/rrUrUrXsetTs  z Typecasts.setcCs|j}|dur|||dSt|tr|g}|D]8}||}|rF||||<d|}||}|r?||||<q||dq||d|d|dqdS)zReset the typecasts for the specified type(s) to their defaults. When no type is specified, all typecasts will be reset. Nr7)r+clearupdater(r8rir,r)rWr.r+rr/rUrUrXresetcs$    zTypecasts.resetcs|dfdd}|S)z1Create an array typecast for the given base cast.r%cs |SrTrUrbasecast cast_arrayrUrXr/rz)Typecasts.create_array_cast..castrU)rWr@r/rUr?rXr-}szTypecasts.create_array_castcs&|dt||fdd}|S)z>Create a named record typecast for the given fields and casts.r&cs|SrTrUr> cast_recordcastsr&rUrXr/rz*Typecasts.create_record_cast..castrI)rWrfieldsrDr/rUrBrXcreate_record_casts zTypecasts.create_record_castrT)#r_r`rarr)runescape_bytearlong cast_hstore jsondecodefloatrErrr rrrrrrrArCr+rr1 staticmethodr2r,rir:r=r-rFrUrUrUrXrs`      rcCs t|S)z@Get the global typecast function for the given database type(s). _typecastsrir.rUrUrXr: r:cCst||dS)zSet a global typecast function for the given database type(s). Note that connections cache cast functions. To be sure a global change is picked up by a running connection, call con.type_cache.reset_typecast(). NrNr:)r.r/rUrUrXr;sr;cCst|dS)a Reset the global typecasts for the given type(s) to their default. When no type is specified, all typecasts will be reset. Note that connections cache cast functions. To be sure a global change is picked up by a running connection, call con.type_cache.reset_typecast(). NrNr=rOrUrUrXr<sr<c@s(eZdZdZeZdZddZddZdS)LocalTypecastszBMap typecasts, including local composite types, to cast functions.Ncs|dr|dd}|}|r||<|Sj|}|r-|}||<|S|}|rOfdd|D}dd|D}|||}||<|S)z+Create a cast function if it is not cached.r'rkNcsg|]}|jqSrU)typerfieldrVrUrXrrz.LocalTypecasts.__missing__..cSsg|]}|jqSrUrrUrUrUrXrs)rr-r+rir, get_fieldsrF)rWr.r0r/rErDrUrVrXr1s$     zLocalTypecasts.__missing__cCsgS)zReturn the fields for the given record type. This method will be replaced with a method that looks up the fields using the type cache of the connection. rUrWr.rUrUrXrWszLocalTypecasts.get_fields) r_r`rarrNr+rr1rWrUrUrUrXrSs  rSc@seZdZdZeddZdS)TypeCodezClass representing the type_code used by the DB-API 2.0. TypeCode objects are strings equal to the PostgreSQL type name, but carry some additional information. c Cs0||}||_||_||_||_||_||_|S)z.Create a type code for a PostgreSQL data type.)rrnrTcategorydelimrelid) clsrrrnrTrZr[r\rWrUrUrXcreateszTypeCode.createN)r_r`rar classmethodr^rUrUrUrXrYsrY FieldInforrTcs\eZdZdZfddZddZdddZd d Zd d Zd dZ dddZ ddZ Z S) TypeCachezCache for database types. This cache maps type OIDs and names to TypeCode strings containing important information on the associated database type. csXtt||j|_||_t|_|j |j_ ||j_ |j dkr'd|_ dSd|_ dS)z%Initialize type cache for connection.i:zSELECT oid, typname, typlen, typtype, null as typcategory, typdelim, typrelid FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) %szSELECT oid, typname, typlen, typtype, typcategory, typdelim, typrelid FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) %sN) superrar escape_string_escape_stringsource_srcrSrNrWrserver_version_query_pg_typerWcnx __class__rUrXrs     zTypeCache.__init__c Cst|tr|}nd|vrd|vrd|f}d||f}z |j|j|fWn ty4d}Ynw|jd}|sDtd|f|d}t t|d|dt|d |d |d |d t|d }|||j <|t |<|S)z8Get the type info from the database if it is not cached..""%s"z '%s'::regtypeNrkzType %s could not be foundrrlrrr) r(rrdrfexecuterhr4fetchKeyErrorrYr^rr))rWkeyrre type_coderUrUrXr1s&    &zTypeCache.__missing__NcCs"z||WSty|YSw)z&Get the type even if it is not cached.)rs)rWrtr4rUrUrXris   z TypeCache.getcsTt|ts|}|sdS|jsdSjd|jffddjdDS)z9Get the names and types of the fields of composite types.NzSELECT attname, atttypid FROM pg_catalog.pg_attribute WHERE attrelid OPERATOR(pg_catalog.=) %s AND attnum OPERATOR(pg_catalog.>) 0 AND NOT attisdropped ORDER BY attnumcs$g|]\}}t|t|qSrU)r`rir)rrrrVrUrXr'sz(TypeCache.get_fields..r)r(rYrir\rfrqrrrXrUrVrXrWs    zTypeCache.get_fieldscCs |j|Sr3rMrXrUrUrXr:*r5zTypeCache.get_typecastcCs|j||dS)r6NrQ)rWr.r/rUrUrXr;.rzTypeCache.set_typecastcCs|j|dS)z?Reset the typecast function for the specified database type(s).NrRrXrUrUrXr<2zTypeCache.reset_typecastcCs.|durdS||}|r|tur|S||S)z:Cast the given value according to the given database type.N)r:r))rWrr.r/rUrUrXtypecast6s   zTypeCache.typecastrT) r_r`rarrr1rirWr:r;r<rw __classcell__rUrUrkrXras   racs eZdZdZfddZZS) _quotedictzsDictionary with auto quoting of its items. The quote attribute must be set to the desired quote function. cs|tt||SrT)quoterbry __getitem__)rWrtrkrUrXr{Hsz_quotedict.__getitem__)r_r`rarr{rxrUrUrkrXryBsrycCs||}d|_|S)z3Return DatabaseError with empty sqlstate attribute.N)sqlstate)msgr]errorrUrUrX _db_errorNsrcCs t|tS)zReturn OperationalError.)rr2)r}rUrUrX _op_errorUrPrz^[A-Za-z][_a-zA-Z0-9]*$ir~cCs~z$z td|ddjWWSty$ddt|D}td|jYWSwty>ddtt|D}td|jYSw)z>Get a namedtuple factory for row results with the given names.RowT)renamecSs0g|]\}}t|rt|s|nd|fqSz column_%d) _re_fieldnamerrK)rnrrUrUrXris z _row_factory..cSsg|]}d|fqSrrU)rrrUrUrXrnr)rJ_maker* enumeraterrangern)namesrUrUrX _row_factorybs  rcCst|tjadS)zwChange the size of the namedtuple factory cache. If maxsize is set to None, the cache can grow without bound. N)rPrr}r~rUrUrXset_row_factory_sizersrc@seZdZdZddZddZddZdd Zd d Zd d Z ddZ e ddZ e ddZ e ddZddZd7ddZddZddZdd Zd8d"d#Zd7d$d%Z d9d&d'Z d9d(d)Zd*d+ZeZed,d-Zed.d/Zed:d1d2Zed3d4Zd5d6ZdS);r zCursor object.cCs^||_|_|j|_|j|_|j|_d|_|jtjur!d|_nd|_ d|_ d|_ d|_ dS)z3Create a cursor object for the database connection.Nrrk) r_dbcnx_cnx type_cachererf _description row_factoryr build_row_factoryrowcount arraysize lastrowid)rWdbcnxrUrUrXrs    zCursor.__init__cC|S)z1Make cursor compatible to the iteration protocol.rUrVrUrUrX__iter__zCursor.__iter__cCr)z0Enter the runtime context for the cursor object.rUrVrUrUrXrYrzCursor.__enter__cCs |dS)z/Exit the runtime context for the cursor object.N)closerWetevtbrUrUrXr^r5zCursor.__exit__c sT|durdSt|ttfrt|}t|tr6t|tr+|j|}ttur*| d}n|j |}d|fSt|t rOt |rG|dkrEdSdSt |rMdS|St|ttttfrZ|St|trl|jrgd |fSd |fSt|trvd |fSt|tr|jrd |fSd |St|trd|fSt|trd|fSt|tr|sdS|jzddfdd|DfWStyddfdd|DfYSwt|tr|jzddfdd|DfWStyddfdd|DfYSwz|}Wntytdt |fwt|ttfr(||}|S)z"Quote value depending on its type.NNULLascii'%s'rz '-Infinity'z 'Infinity'z'NaN'z'%s'::timestamptzz'%s'::timestampz '%s'::datez '%s'::timetzz '%s'::timez'%s'::intervalz '%s'::uuidz'{}'z ARRAY[%s],c3|] }t|VqdSrTr)rqrUrXrz Cursor._quote..c3rrTunicoderrrUrXrr(%s)c3rrTrrrrUrXrrc3rrTrrrrUrXrrz Do not know how to adapt type %s)!r(rrr)r8rr escape_byteabytesdecodercrKrGrFrrHrErrArCr?r@rBrr_quoterUnicodeEncodeErrortuple __pg_repr__AttributeErrorr/rT)rWrrUrrXrsx                     "  "   z Cursor._quotec Csd|sz|dWSttfy|YSwt|tr&t|}|j|_||Stt|j|}||S)zQuote parameters. This function works for both mappings and sequences. The function should be used even when there are no parameters, so that we have a consistent behavior regarding percent signs. rU) r*rr(dictryrrzrmap)rWstringrrUrUrX _quoteparamss  zCursor._quoteparamsc Cs|dd\}}}}|j|}|dkr|d8}|dkr'|d?|d@}}|}n|s,|j}|dkr2|}d}}t||d|||dS) z4Make the description tuple for the given field info.rkNrrrir)rsizeCursorDescription) rWinforr.rmodru precisionscalerUrUrX_make_descriptions  zCursor._make_descriptioncs8|j}|jdur|jfdd|jD}||_|S)z2Read-only attribute describing the result columns.Tcsg|]}|qSrUrU)rrmakerUrXrrz&Cursor.description..)rrrflistinfo)rWdescrrUrrX descriptions  zCursor.descriptioncCdd|jDS)z;Unofficial convenience method for getting the column names.cSg|]}|dqSrrUrrUrUrXrrz#Cursor.colnames..rrVrUrUrXcolnameszCursor.colnamescCr)z;Unofficial convenience method for getting the column types.cSr)rkrUrrUrUrXrrz#Cursor.coltypes..rrVrUrUrXcoltypesrzCursor.coltypescCs|jdS)zClose the cursor object.N)rfrrVrUrUrXrsz Cursor.closeNcsdr+ttr+tdkr+tddDr+tfddddDr+||S||gS)z.c3s$|] }t|tdkVqdS)rNrmrrrUrXr)rN)r(rrnall executemany)rW operationrrUrrXrq s  zCursor.executec CsT|sdSd|_d|_d}d}zF|jjs6|jjs6z|j|Wnty'ty1t dwd|j_|D]}|}| ||}|j|}|rO||7}q8d|_q8Wn/ty\t yp}z t d||ft d}~wty}zt d||fd}~ww|jjtkrd|_|jj|_d|_|jr||_|S||_|j|_|S) z>Prepare operation and execute it against a parameter sequence.NrrBEGINCan't start transactionTzError in '%s': '%s' zInternal error in '%s': %s)rrr_tnx autocommitrfrqr0 Exceptionrrr-rr/ resulttype RESULT_DQLntuplesrrr oidstatus)rWrseq_of_parametersrsqlrrowserrrUrUrXr/sZ           zCursor.executemanycCs,|dd}z|dWStyYdSw)z)Fetch the next row of a query result set.rkFrN) fetchmany IndexErrorrWrerUrUrXfetchone`s   zCursor.fetchonecCs |ddS)z-Fetch all (remaining) rows of a query result.rF)rrVrUrUrXfetchallhr5zCursor.fetchallFc sx|durj}|r |_zj|}Wntyty-}ztt|d}~wwjjfdd|DS)a>Fetch the next set of rows of a query result. The number of rows to fetch per call is specified by the size parameter. If it is not given, the cursor's arraysize determines the number of rows to be fetched. If you set the keep parameter to true, this is kept as new arraysize. Ncs,g|]}fddtj|DqS)csg|] \}}||qSrUrU)rr.r)rwrUrXrsz/Cursor.fetchmany...)rzipr)rrowrWrwrUrXrs   z$Cursor.fetchmany..) rrfrrr0r-rr)rrw)rWrkeepresultrrUrrXrls    zCursor.fetchmanycCs8|rt|pd}d|d|dgf}||||S)aCall a stored database procedure with the given name. The sequence of parameters must contain one entry for each input argument that the procedure expects. The result of the call is the same as this input sequence; replacement of output and input/output parameters in the return value is currently not supported. The procedure may also provide a result set as output. These can be requested through the standard fetch methods of the cursor. rzselect * from "%s"(%s)rz%s)rnrrq)rWprocnamerrqueryrUrUrXcallprocs  zCursor.callprocc s|dk}zjWn^tygrtd|rtdntdttrSts2tdf|sLttrCdsBd7n dsLd7fdd } nttrafd d } nt d Yn#wd urod n tt sxt ddkrfdd } nfdd } |rt|tst d| drtdd|f}d|fg} g} g} |d urt|tst d|dvrtd| d|f|d urt|tst d|dkrtdt|dkrtd| d| ||d urt|tst d | d!| ||r)t|ts!d"d#d$|D}| d%|f| d&| r<| d%d"| fd'| } |jj} || | z | D]}| |qOWntys}zd(|_| |WYd }~|Sd }~ww| d |_|S))aCopy data from an input stream to the specified table. The input stream can be a file-like object with a read() method or it can also be an iterable returning a row or multiple rows of input on each iteration. The format must be text, csv or binary. The sep option sets the column separator (delimiter) used in the non binary formats. The null option sets the textual representation of NULL in the input. The size option sets the size of the buffer used when reading data from file-like objects. The copy operation can be restricted to a subset of columns. If no columns are specified, all of them will be copied. binaryz+Size must only be set for file-like objectsz byte stringsstringszThe input must be %s  c3s VdSrTrUrU)streamrUrXchunkss z Cursor.copy_from..chunksc3s^D])}t|stdft|tr |ds|d7}n |ds)|d7}|VqdS)NzInput stream must consist of %srr)r(rr)r)chunk) input_typer type_namerUrXrs     z!Need an input stream to copy fromNi z"The size option must be an integerrc3s( }|V|rt|krdSqrTrm)buffer)readrrUrXrsc3sVdSrTrUrU)rrUrXrs Need a table to copy toselectz!Must specify a table, not a queryrocopy %sz%The format option must be be a stringrcsvrInvalid format format %sThe sep option must be a string0The sep option is not allowed with binary formatrk2The sep option must be a single one-byte character delimiter %s The null option must be a stringnull %srcs|]}d|fVqdSroNrUrcolrUrUrXrrz#Cursor.copy_from..rz from stdinrr)rrrrr8r(r)rrHr*rlowerrrrnrrfputdatarq BaseExceptionr)rWrtableformatsepnullrcolumns binary_formatrroptionsparamsrrr~rU)rrrrrrX copy_froms        +                    zCursor.copy_fromcs6|dk}|durz|j} Wn tytdw|r t|ts$td|dr7|r1tdd|f}nd|f}d |fg} g} g} |durct|tsStd |d vr[td | d |f|durt|tsptd|rvtdt |dkrtd| d| ||durt|tstd| d| |dur|dkrdnt t untt t fstdr|rtd|rt|tsddd|D}| d|f| d| r| dd| fd| } jj| | fdd} |dur| S| D]}| |qS)aCopy data from the specified table to an output stream. The output stream can be a file-like object with a write() method or it can also be None, in which case the method will return a generator yielding a row on each iteration. Output will be returned as byte strings unless you set decode to true. Note that you can also use a select query instead of the table name. The format must be text, csv or binary. The sep option sets the column separator (delimiter) used in the non binary formats. The null option sets the textual representation of NULL in the output. The copy operation can be restricted to a subset of columns. If no columns are specified, all of them will be copied. rNz Need an output stream to copy torrz&Columns must be specified in the queryrrorz"The format option must be a stringrrrrrrkrrrrFz#The decode option must be a booleanz3The decode option is not allowed with binary formatrcsrrrUrrUrUrXrcrz!Cursor.copy_to..z to stdoutrc3sFd_ }t|trj|kr|_dSjd7_|Vq)NrTrk)rr(rrrgetdatarWrUrXcopyns  zCursor.copy_to..copy)writerr*r(r8rrrrrnr)rrrrrfrrq)rWrr r r r rrrrrrrrrrUrrXcopy_tos                     zCursor.copy_tocCs|}|dur t|S)z9Return the next row (support for the iteration protocol).N)r StopIterationrrUrUrX__next__szCursor.__next__cCstd)Not supported.z%The nextset() method is not supported)r5rUrUrUrXnextsetszCursor.nextsetcCdSrNrU)sizesrUrUrX setinputsizeszCursor.setinputsizesrcCrrrU)rcolumnrUrUrX setoutputsizer!zCursor.setoutputsizecCst)aProcess rows before they are returned. You can overwrite this statically with a custom row factory, or you can build a row factory dynamically with build_row_factory(). For example, you can create a Cursor class that returns rows as Python dictionaries like this: class DictCursor(pgdb.Cursor): def row_factory(self, row): return {desc[0]: value for desc, value in zip(self.description, row)} cur = DictCursor(con) # get one DictCursor instance or con.cursor_type = DictCursor # always use DictCursor instances )NotImplementedErrorrrUrUrXrszCursor.row_factorycCs|j}|r tt|SdS)aBuild a row factory based on the current description. This implementation builds a row factory for creating named tuples. You can overwrite this method if you want to dynamically create different row factories whenever the column description changes. N)rrr)rWrrUrUrXrs zCursor.build_row_factoryrT)NFNNNNNr) r_r`rarrrrYr^rrrpropertyrrrrrqrrrrrrrrrrrLrr r#rrrUrUrUrXr }sLE    1    h      r r)rru display_size internal_sizerrnull_okc@seZdZdZeZeZeZeZeZe Z e Z e Z e Z e Z ddZddZddZdd Zed d Zd d ZddZddZerIdddZddZdSdS)r zConnection object.cCsJ||_d|_t||_t|_d|_z|jWdSty$t dw)z$Create a database connection object.FInvalid connectionN) rrrarr cursor_typerrerrrirUrUrXrs  zConnection.__init__cCsJ|jr#z |jdWntytytdwd|_|S)zEnter the runtime context for the connection object. The runtime context can be used for running transactions. This also starts a transaction in autocommit mode. rrT)rrrerqr0rrrrVrUrUrXrYs  zConnection.__enter__cCs0|dur|dur|dur|dS|dS)zExit the runtime context for the connection object. This does not close the connection, but it ends a transaction. N)commitrollbackrrUrUrXr^s  zConnection.__exit__cCsH|jr |jrz|Wn tyYnw|jd|_dStd)zClose the connection object.NConnection has been closed)rrr-r0rrrVrUrUrXrs    zConnection.closecCs,z |j p |jjdkWStyYdSw)z:Check whether the connection has been closed or is broken.rkT)rstatusr*rVrUrUrXclosed s  zConnection.closedcCZ|jr)|jr'd|_z |jdWdStyty&tdwdStd)z/Commit any pending transaction to the database.FCOMMITzCan't commit transactionr.Nrrrerqr0rrrVrUrUrXr,   zConnection.commitcCr1)z2Roll back to the start of any pending transaction.FROLLBACKzCan't rollback transactionr.Nr3rVrUrUrXr- r4zConnection.rollbackcCs2|jrz||WStytdwtd)z0Return a new cursor object using the connection.r*r.)rr+rrrVrUrUrXcursor.s  zConnection.cursorNcC|}||||S)z:Shortcut method to run an operation on an implicit cursor.)r6rq)rWrrr6rUrUrXrq: zConnection.executecCr7)z7Shortcut method to run an operation against a sequence.)r6r)rWr param_seqr6rUrUrXr@r8zConnection.executemanyrT)r_r`rarr-r.r/r0 InternalErrorr2r4r3r1r5rrYr^rr&r0r,r-r6shortcutmethodsrqrrUrUrUrXr s2     r c Ksd}d}d}d} d} d} z|d} | d}| d}| d} | d} | d} Wn tttfy3Ynw|d ur:|} |d ur@|} |d urF|}|d uriz|d} | d}t| d}Wn ttttfyhYnw|dkrod }| dkrud } |rt|}d |vr|g}n |dd |fg}|D]$\} }t |}|rd |vrd | dd ddf}| d| |fqd |}t |||| | | }t|S)zConnect to a database.rrrrrkrlrrN=dbnamerr'z\'\z\\z%s=%s)rrrr*rrritemsinsertr)rrr_connectr )dsnuserpasswordhostdatabasekwargsdbportdbhostr=dbuserdbpasswddboptrkwrrjrUrUrXr7Ksh       r7cs8eZdZdZfddZfddZfddZZS)rzType class for a couple of PostgreSQL data types. PostgreSQL is object-oriented: types are dynamic. We must thus use type names as internal type codes. cs$t|tr |}tt|||SrT)r(r8rrbr__new__)r]valuesrkrUrXrOs z Type.__new__cs8t|tr|dr|dd}||vStt||SNr'rk)r(r8rrbr__eq__rWotherrkrUrXrR   z Type.__eq__cs8t|tr|dr|dd}||vStt||SrQ)r(r8rrbr__ne__rSrkrUrXrVrUz Type.__ne__)r_r`rarrOrRrVrxrUrUrkrXrs   rc@ eZdZdZddZddZdS) ArrayTypez&Type class for PostgreSQL array types.cCst|tr |dSt|tSNr'r(r8rrXrSrUrUrXrRs   zArrayType.__eq__cCs"t|tr |d St|t SrYrZrSrUrUrXrVs   zArrayType.__ne__Nr_r`rarrRrVrUrUrUrXrXs rXc@rW) RecordTypez'Type class for PostgreSQL record types.cCs0t|tr |jdkSt|tr|dkSt|tSNrr&r(rYrTr8r\rSrUrUrXrRs    zRecordType.__eq__cCs2t|tr |jdkSt|tr|dkSt|t Sr]r^rSrUrUrXrVs    zRecordType.__ne__Nr[rUrUrUrXr\s r\zchar bpchar name text varcharrz1int2 int4 serial int8 float4 float8 numeric moneyz?date time timetz timestamp timestamptz interval abstime reltimerrrzint2 int4 int8 serialrz float4 float8rrr?z time timetzztimestamp timestamptzr r$rz json jsonbcCs t|||S)z)Construct an object holding a date value.)r?)yearmonthdayrUrUrXr r5r cCst|||||S)z)Construct an object holding a time value.)r@)hourminutesecond microsecondrCrUrUrXr rvr c Cst||||||||S)z/Construct an object holding a time stamp value.)rA)r_r`rarbrcrdrerCrUrUrXr sr cCtt|ddS)zDConstruct an object holding a date value from the given ticks value.Nr)r rDticksrUrUrXrrcCrf)zDConstruct an object holding a time value from the given ticks value.rrp)r rDrgrUrUrXrrircCrf)zDConstruct an object holding a time stamp from the given ticks value.Nrp)r rDrgrUrUrXr rirc@seZdZdZdS)rzDConstruct an object capable of holding a binary (long) string value.N)r_r`rarrUrUrUrXrsrcCst|||||dS)z2Construct an object holding a time interval value.)rrrr)rBrrUrUrXrs rc@s4eZdZdZedZedZeddZddZ dS) rz(Wrapper class for marking hstore values.z^[Nn][Uu][Ll][Ll]$|[ ,=>]z(["\\])cCs@|durdS|s dS|j|}|jd|}|rd|f}|S)Nrz""z\\\1ro) _re_quotesearch _re_escapesub)r]srzrUrUrXr's  z Hstore._quotecs"|jdfdd|DS)Nrc3s(|]\}}d||fVqdS)z%s=>%sNrU)rkrrrUrXr5s&z!Hstore.__str__..)rrr@rVrUrrX__str__3szHstore.__str__N) r_r`rarregexrjrlr_rrprUrUrUrXr!s  rc@s"eZdZdZdddZddZdS)rz?Construct a wrapper for holding an object serializable to JSON.NcCs||_|pt|_dSrT)obj jsonencodeencode)rWrrrtrUrUrXr;sz Json.__init__cCs|j}t|tr |S||SrT)rrr(r8rt)rWrrrUrUrXrp?s  z Json.__str__rT)r_r`rarrrprUrUrUrXr8s  rc@s$eZdZdZddZddZeZdS)rz5Construct a wrapper for holding a literal SQL string.cCs ||_dSrTr)rWrrUrUrXrIrzLiteral.__init__cCrrTrurVrUrUrXrpLrzLiteral.__str__N)r_r`rarrrprrUrUrUrXrFs r__main__zPyGreSQL versionr)rbrTr%)rrrN)rrrrN)rrrr)r __future__rr_pg ImportErrorossysr version_infoenvironrpathseppathexistsradd_dll_directoryabspathr=r>__all__rAr?r@rBrCrDdecimalrEr$r(rmathrFrGcollections.abcrH collectionsrJkeywordrK functoolsrLrerMrqrrNrJrOrsrH NameErrorrrr)r8rrPrQ_threadrRr6r9r8r;inspectrrrrutcrrrrrrrrrrrrrrrrrrrr rrNr:r;r<rSrYr`raryr0rrrrrr|r rr r7rB frozensetrrXr\rrrrrrrrr r!r"r#r$r%r&r'r)r*r+r,r r r rrrrrrrrr_printrUrUrUrXsr 8                U    % ;}  %^   F A