a _K?b @svdZddlmZmZzddlTWney0ZzddlZdZej dkred7Zddl Z dd ej d  ej DZe jd kreD]jZeejeDz ddlTWneyYn0dZWdqWdq1s0Yqerd eZned 7ZeredeefWYdZ[n dZ[00eZgdZddlmZmZmZmZmZddlmZddlmZddlm Z!ddl"m#Z#m$Z$zddl%m&Z&Wn eyddl'm&Z&Yn0ddl'm(Z(ddl)m*Z*ddl+m,Z-ddl.m/Z0m1Z2eaze3Wne4ye5Z3Yn0ze6Wne4y:e7Z6Yn0ze8Wne4y`e7e9fZ8Yn0zddl)m:Z:Wn^eyddl)m;Z;zddld#Z?d$Z@d#ZAzdd%lBmCZCWn(eydd&lBmDZDd'd(ZEYn 0d)d(ZEzdd*lmFZFWn8eylGd+d,d,eZFeFedd-eF_Gd.ZHYn0d/ZHeId0d1d2d3d4d0d5d3d3d3d6 ZJd7d8ZKd9d:ZLdd;d<ZMd=d>ZNd?d@ZOdAdBZPdCdDZQdEdFZRe-dGZSdHdIZTdJdKZUdLdMZVe-dNZWe-dOZXe-dPZYe-dQZZdRdSZ[GdTdUdUeIZ\e\Z]dVdWZ^dXdYZ_ddZd[Z`Gd\d]d]e\ZaGd^d_d_e7Zbe(d`daZcGdbdcdceIZdGdddedeeIZeeffdfdgZgdhdiZhe-djZie:dkdldmdnajdodpZkGdqdrdrelZme(dsdtZnGdudvdvelZoepZqddwdxZpGdydzdzerZsGd{d|d|ZtGd}d~d~ZuesdZvesdZwesdZxesdZyesdZzesdZ{esdZ|esdZ}esdZ~esdZesdZesdZesdZesdZesdZesdZesdZ esdZesdZetZeuZddZdddZdddZddZddZddZGddde9ZdddZe!Z!GdddeIZGdddZGdddZedkrredeedeedS)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)*Nzlibpq.ntdllcCs&g|]}tjtj|tr|qS)ospathexistsjoinlibpq).0r rr+/tmp/pip-target-llefyurp/lib/python/pgdb.py MsrPATH)z compatible sozRCannot import shared library for PyGreSQL, probably because no %s is installed. %s)7 ConnectionCursorDateTime Timestamp DateFromTicks TimeFromTicksTimestampFromTicksBinaryIntervalUuidHstoreJsonLiteralTypeSTRINGBINARYNUMBERDATETIMEROWIDBOOLSMALLINTINTEGERLONGFLOATNUMERICMONEYDATETIME TIMESTAMPINTERVALUUIDHSTOREJSONARRAYRECORDErrorWarningInterfaceError DatabaseError DataErrorOperationalErrorIntegrityError InternalErrorProgrammingErrorNotSupportedErrorapilevelconnect paramstyle threadsafety get_typecast set_typecastreset_typecastversion __version__)datetimedatetime timedeltatzinfo) localtime)Decimal)r3)isnanisinf)Iterable namedtuple)partial)compile)loadsdumps) lru_cache)update_wrapper)RLockc@seZdZddZddZdS)r]cCsdSNrselfrrr __enter__szRLock.__enter__cCsdSr^r)r`exctypeexcinstexctbrrr__exit__szRLock.__exit__N)__name__ __module__ __qualname__rarerrrrr]sr]csfdd}|S)z:Simplified functools.lru_cache decorator for one argument.cstijtg}|dg||ddg|dd<dkrLfdd}n2durhfdd}nfdd}|_t|S)NFrcs |}|Sr^rargres)functionrrwrappersz-lru_cache..decorator..wrappercs*|}|ur|S|}||<|Sr^rrj)cachermgetsentinelrrrns  c sr~|}|durtd}|\}}}}||d<||d<|d}||d<|d<||d<||d<|WdSWdn1s0Y|}\}}|vrn|r |} || d<|| d<| d}d<|d} |d} d|d<|d<| =| |<nB|d}||||g}||d<|d<|<tkrNdd<Wdn1sd0Y|S)NrrTlen) rklinkrootZprvZnxtZ_argrllastfullZoldrootZoldargZoldres)rormrplockmaxsize root_fullrrrnsB 0  ()objectrpr] __wrapped__r\)rmrwrnr{)rormrprzr|rqr decorators $zlru_cache..decoratorr)r{rrrrr[s Br[z2.0rrZpyformat) signature) getargspeccCs t|jSr^)rargsfuncrrrget_argssrcCstt|jSr^)listr parametersrrrrrs)timezonec@s2eZdZdZd ddZddZddZd d ZdS) rzSimple timezone implementation.NcCsf||_|s\|jjd|jjd}|dkrBt| d\}}| }nt|d\}}d||f}||_dS)Ni<rz UTC%+03d:%02d)offsetdayssecondsdivmodname)r`rrminuteshoursrrr__init__s ztimezone.__init__cCs|jSr^)rr`dtrrr utcoffsetsztimezone.utcoffsetcCs|jSr^rrrrrtzname sztimezone.tznamecCsdSr^rrrrrdst#sz timezone.dst)N)rfrgrh__doc__rrrrrrrrrs  rUTCFTz+0100z+0200z-0500+0000z-1000z-0700) ZCETZEETESTGMTZHSTZMETMSTZUCTrZWETcCs6|dr*t|dkr|dS|ddSt|dS)N)+-Z00:r) startswithrureplace _timezonesrp)tzrrr_timezone_as_offset2s    rcCsNt|}dt|ddt|dd}|ddkr>| }tt|d|S)Nrrrrrrr)r)rintrrN)rrrrr _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)rQrG) decimal_typerrrrBs rcCs|r|ddvSdS)z.Cast boolean value in database format to bool.r)tTNrvaluerrr cast_boolOsrcCs,|r(|dd}tddd|DSdS)z/Cast money value in database format to Decimal.(rrcss"|]}|s|dvr|VqdS)z.-N)isdigit)r crrr Yzcast_money..N)rrQr rrrr cast_moneyUs rcCsdd|DS)zCast an int2vector value.cSsg|] }t|qSrrr vrrrr^rz#cast_int2vector..)splitrrrrcast_int2vector\srcCsh|dkrtjS|dkrtjS|}|ddkr6tjS|d}t|dkrPtjS|}t||S)zCast a date value. -infinityinfinityBCr )rKminmaxrru date_formatrMstrptimer connectionfmtrrr cast_dateas  rcCs$t|dkrdnd}t||S)zCast a time value.r %H:%M:%S.%f%H:%M:%S)rurMrrL)rrrrr cast_timeusrz (.*)([+-].*)cCsxt|}|r|\}}nd}t|dkr0dnd}tr\|t|7}|d7}t||St||j t |dS)zCast a timetz value.rrrr%zrO) _re_timezonematchgroupsru _has_timezonerrMrtimetzrr)rrrrrr cast_timetz~s  rcCs|dkrtjS|dkrtjS|}|ddkr6tjS|}|drt|dkr|dd}t|d d krvtjS|d rd nd t|ddkrdnddg}n2t|ddkrtjS|t|ddkrdndg}td |d |S)zCast a timestamp value.rrrr-%Yrsrrrr%d%d %b%b %drrr%Yrr ) rMrrrrendswithrurrr rrrrcast_timestamps&  rcCs|dkrtjS|dkrtjS|}|ddkr6tjS|}|drt|dkr|dd}t|d d krvtjS|d rd nd t|ddkrdnddg}|dd|d}}n|drt |d}|r| \|d<}nd}n|dd|d}}t|ddkrtjS|t|ddkr4dndg}t rp| t || dtd|d|Std|d|jt|dS)zCast a timestamptz value.rrrrrrsrrNrrrrrrrrrz%Y-rrrrrr)rMrrrrrrurrrrrappendrrr rr)rrrrrrrcast_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 Cs8t|}|rbdd|D}|ddk}dd|D}|\}}}}}}} |r^| }| } nt|}|rdd|ddD|d }} |ddk}| rd d|Dn d d|D}|\}}}}}}} |r| }| } n(t|}|rht|rhd d|D}|d dk} dd|D}|\}}}}}}} | r| }| }| }| } nt|}|rt|rdd|D}|ddk} |d dk} dd|D}|\}}}}}}} | r| }| }| r| }| }| }| } n t d||d|d|7}t ||||| dS)zCast an interval value.cSsg|] }|pdqS0rr drrrrrz!cast_interval..rrcSsg|] }t|qSrrrrrrrrcSsg|] }|pdqSrrrrrrrrNr cSsg|]}t| qSrrrrrrrrcSsg|] }t|qSrrrrrrrrcSsg|] }|pdqSrrrrrrrrrcSsg|] }t|qSrrrrrrrrcSsg|] }|pdqSrrrrrrr rrcSsg|] }t|qSrrrrrrrrzCannot parse interval: %simrrrr microseconds) _re_interval_iso_8601rrpop_re_interval_postgres_verbosegroup_re_interval_postgresany_re_interval_sql_standard ValueErrorrN) rmZsecs_agoZyearsZmonsrrZminsZsecsZusecsZagoZ hours_agoZ years_agorrr cast_intervalsb   &     rc@seZdZdZeeeeeeeeeeeee e e e e e e eeeeeeeeeedZdZddZeddZdd Zdd d Zd d ZdddZ ddZ!ddZ"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. )charZbpcharrtextZvarcharboolbyteaint2Zint4serialint8oidhstorejsonZjsonbZfloat4Zfloat8rmoneyrKintervalrLr timestampZ timestamptzZ int2vectoruuidanyarrayrecordNcCsnt|tstd||j|}|r:||}|||<n0|drj||dd}||}|rj|||<|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_rrN) isinstancestr TypeErrordefaultsrp_add_connectionrcreate_array_cast)r`typcast base_castrrr __missing__<s       zTypecasts.__missing__c Cs:z t|}Wnttfy$YdS0d|ddvSdS)z9Check if a typecast function needs a connection argument.FrrrN)rrr)rrrrr_needs_connectionRs  zTypecasts._needs_connectioncCs"|jr||s|St||jdS)z@Add a connection argument to the typecast function if necessary.)r)rrrW)r`r rrrr\szTypecasts._add_connectioncCs ||p |Sz6Get the typecast function for the given database type.r)r`r defaultrrrrpbsz Typecasts.getcCs|t|tr|g}|dur@|D] }||d|d|dqn8t|sPtd|D]"}||||<|d|dqTdS);Set a typecast function for the specified database type(s).N_%szCast parameter must be callable)r basestringrcallablerr)r`r r rrrrsetfs  z Typecasts.setcCs|j}|dur"|||nt|tr2|g}|D]p}||}|r||||<d|}||}|r|||||<q||dq6||d|d|dq6dS)zReset the typecasts for the specified type(s) to their defaults. When no type is specified, all typecasts will be reset. Nr)rclearupdaterrrprr)r`r rrr rrrresetus"     zTypecasts.resetcs|dfdd}|S)z1Create an array typecast for the given base cast.rcs |Sr^rrbasecast cast_arrayrrr sz)Typecasts.create_array_cast..castr)r`rr rrrr szTypecasts.create_array_castcs&|dt||fdd}|S)z>Create a named record typecast for the given fields and casts.rcs|Sr^rr cast_recordcastsrrrr sz*Typecasts.create_record_cast..castrU)r`rfieldsrr rrrcreate_record_casts zTypecasts.create_record_cast)N)N)#rfrgrhrrrZunescape_bytearlongZ cast_hstore jsondecodefloatrQrrrrrrrrrrrrrr  staticmethodrrrprrr r!rrrrr!s0     rcCs t|S)z@Get the global typecast function for the given database type(s).) _typecastsrpr rrrrFsrFcCst||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(). Nr&r)r r rrrrGsrGcCst|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(). Nr&rr'rrrrHsrHc@s(eZdZdZeZdZddZddZdS)LocalTypecastszBMap typecasts, including local composite types, to cast functions.Ncs|dr2|dd}|}|r||<nhj|}|rV|}||<nD|}|rfdd|D}dd|D}|||}||<|S)z+Create a cast function if it is not cached.rrrNcsg|]}|jqSr)typer fieldr_rrrrz.LocalTypecasts.__missing__..cSsg|] }|jqSrrr,rrrrr)rr rrpr get_fieldsr!)r`r r r r rrr_rr s        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. rr`r rrrr.szLocalTypecasts.get_fields) rfrgrhrr&rrr r.rrrrr*s r*c@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.)rrur+categorydelimrelid) clsrrrur+r1r2r3r`rrrcreateszTypeCode.createN)rfrgrhr classmethodr5rrrrr0sr0 FieldInfo)rr+csdeZdZdZfddZddZdddZd d Zd d Zd dZ dddZ ddZ 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. csVtt||j|_||_t|_|j |j_ ||j_ |j dkrLd|_ nd|_ 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) superr8r escape_string_escape_stringsource_srcr*r&r.rZserver_version_query_pg_typer`cnx __class__rrrs   zTypeCache.__init__c Cst|tr|}n*d|vr*d|vr*d|f}d||f}z|j|j|fWntyhd}Yn0|jd}|std|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'::pg_catalog.regtypeNrrzType %s could not be foundrrsrrr) rrr;r=executer>r@fetchKeyErrorr0r5rr)r`keyrrl type_coderrrr s&     zTypeCache.__missing__NcCs&z ||WSty |YS0dS)z&Get the type even if it is not cached.N)rI)r`rJrrrrrp/s  z TypeCache.getcsTt|ts|}|sdS|js&dSjd|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|qSr)r7rpr)r rrr_rrrDsz(TypeCache.get_fields..r)rr0rpr3r=rGrHr/rr_rr.6s    zTypeCache.get_fieldscCs |j|Srr&r/rrrrFGszTypeCache.get_typecastcCs|j||dS)rNr()r`r r rrrrGKszTypeCache.set_typecastcCs|j|dS)z?Reset the typecast function for the specified database type(s).Nr)r/rrrrHOszTypeCache.reset_typecastcCs2|dur dS|j|}|dus&|tur*|S||S)z:Cast the given value according to the given database type.N)r&r)r`rr r rrrtypecastSs  zTypeCache.typecastcs6|jfdd|DddDfdd}|S)z5Get a typecast function for a complete row of values.csg|] }|qSrr)r r ) typecastsrrrarz,TypeCache.get_row_caster..cSsg|]}|tur|ndqSr^r)r r rrrrbrcsddt|DS)NcSs,g|]$\}}|dus|dur |n||qSr^r)r r rrrrresz@TypeCache.get_row_caster..row_caster..ziprow)rrr row_casterdsz,TypeCache.get_row_caster..row_casterrL)r`typesrTr)rrNrget_row_caster^s  zTypeCache.get_row_caster)N)N)rfrgrhrrr rpr.rFrGrHrMrV __classcell__rrrArr8s    r8cs eZdZdZfddZZS) _quotedictzsDictionary with auto quoting of its items. The quote attribute must be set to the desired quote function. cs|tt||Sr^)quoter9rX __getitem__)r`rJrArrrZqsz_quotedict.__getitem__)rfrgrhrrZrWrrrArrXksrXcCs||}d|_|S)z3Return DatabaseError with empty sqlstate attribute.N)Zsqlstate)msgr4errorrrr _db_errorysr]cCs t|tS)zReturn OperationalError.)r]r=)r[rrr _op_errorsr^z^[A-Za-z][_a-zA-Z0-9]*$ircCsLztd|ddjWStyFddtt|D}td|jYS0dS)z>Get a namedtuple factory for row results with the given names.ZRowT)renamecSsg|]}d|fqS)z column_%dr)r nrrrrrz _row_factory..N)rV_makerrangeru)namesrrr _row_factorys  rdcCst|tjadS)zwChange the size of the namedtuple factory cache. If maxsize is set to None, the cache can grow without bound. N)r[rdr~rrrrset_row_factory_sizesrec@seZdZdZddZddZddZdd Zd d Zd d Z ddZ e ddZ e ddZ e ddZddZd7ddZddZddZdd Zd8d"d#Zd9d$d%Zd:d&d'Zd;d(d)Zd*d+ZeZed,d-Zed.d/Zedd|fSt|tr|sTdS|jz ddfdd|DfWStyddfdd|DfYS0t|tr|jz ddfdd|DfWStyddfdd|DfYS0z |}Wn&tyFtdt |fYn0t|ttfrb||}|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],c3s|]}t|VqdSr^rOrqrrrrz Cursor._quote..c3s|]}t|VqdSr^unicoderrxrrrr(%s)c3s|]}t|VqdSr^rOrrxrrrrc3s|]}t|VqdSr^rzrrxrrrrz Do not know how to adapt type %s)!rrr rrrrgZ escape_byteabytesdecoder:r$rSrRrr"rQr!rMrOrKrLrNrr_quoter UnicodeEncodeErrortuple __pg_repr__AttributeErrorr:r+)r`rrrxrrsp                    $  $   z Cursor._quotec Cs^|s*z |dWSttfy(|YS0t|trFt|}|j|_ntt|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. r) rrrdictrXrrYrmap)r`stringrrrr _quoteparams s    zCursor._quoteparamsc Cs|dd\}}}}|j|}|dkr.|d8}|dkrN|d?|d@}}|}n|sX|j}|dkrd|}d}}t||d|||dS) z4Make the description tuple for the given field info.rrNrrrir)rhsizeCursorDescription) r`inforr rmodrK precisionscalerrr_make_descriptions  zCursor._make_descriptioncs8|j}|jdur4|jfdd|jD}||_|S)z2Read-only attribute describing the result columns.Tcsg|] }|qSrr)r rmakerrr7rz&Cursor.description..)rirr=Zlistinfo)r`descrrrr description1s  zCursor.descriptioncCsdd|jDS)z;Unofficial convenience method for getting the column names.cSsg|] }|dqS)rrrrrrr>rz#Cursor.colnames..rr_rrrcolnames;szCursor.colnamescCsdd|jDS)z;Unofficial convenience method for getting the column types.cSsg|] }|dqS)rrrrrrrrCrz#Cursor.coltypes..rr_rrrcoltypes@szCursor.coltypescCs|jdS)zClose the cursor object.N)r=rpr_rrrrpEsz Cursor.closeNcshrVttrVtdkrVtddDrVtfddddDrV||S||gSdS)z.c3s"|]}t|tdkVqdS)rNrtrrrrrRrN)rrruall executemany)r` operationrrrrrGIs  zCursor.executec Cs||sdSd|_d|_d}d}z|jjst|jjstz|j|Wn,tyRYn"tyjt dYn 0d|j_|D]4}|}| ||}|j|}|r||7}qxd|_qxWn|tyYnjt y}zt d||ft WYd}~n>d}~0ty,}zt d||fWYd}~n d}~00|jjtkrfd|_|jj|_d|_|jrx||_n||_|j|_|S) z>Prepare operation and execute it against a parameter sequence.NrrBEGINCan't start transactionTzError in '%s': '%s' zInternal error in '%s': %s)rirlrf_tnx autocommitr=rGr; Exceptionr^rr8r]r:Z resulttypeZ RESULT_DQLZntuplesrnrkrjZ oidstatus)r`rZseq_of_parametersrlsqlrZrowserrrrrrXsN        &   zCursor.executemanycCs0|dd}z |dWSty*YdS0dS)z)Fetch the next row of a query result set.rrFrN) fetchmany IndexErrorr`rlrrrfetchones    zCursor.fetchonecCs |ddS)z-Fetch all (remaining) rows of a query result.rF)rr_rrrfetchallszCursor.fetchallFc s|dur|j}|r||_z|j|}WnBty<Yn0tyj}ztt|WYd}~n d}~00|j|jt |dkr|j fdd|DS|j j fdd|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. Nrcsg|]}|qSrrr rS)cast_rowrjrrrrz$Cursor.fetchmany..cs(g|] }fddt|DqS)csg|]\}}||qSrr)r r r) cast_valuerrrsz/Cursor.fetchmany...rPr)rrrjrrrs ) rmr=rHr;r8r]rrjrrurhrVrM)r`rZkeepresultrr)rrrrjrrs& "  zCursor.fetchmanycCs8|r t|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)rwz%s)rur rG)r`Zprocnamerr`queryrrrcallprocs  zCursor.callprocc s"|dk}z jWntyr,td|r:tdntdttrtsdtdf|sttrdsd7ndsd7fdd } n$ttr‡fd d } nt d YnH0d urd ntt st ddkr fdd } n fdd } |r(t|ts0t d| drJtdnd t|jjj|dd}d|fg} g} g} |d urt|tst d|dvrtd| d|f|d urt|tst d|dkrtdt|dkrtd| d| ||d urHt|ts4t d | d!| ||rt|tspd" t|jjj|}| d#|f| d$| r| d#d" | fd% | } |jj} || | z| D]}| |qWn4ty}zd&|_| |WYd }~nd }~00| 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 VdSr^rr)streamrrchunkssz Cursor.copy_from..chunksc3s\D]R}t|s tdft|tr>|dsP|d7}n|dsP|d7}|VqdS)NzInput stream must consist of %srr)rrrr)chunk) input_typer type_namerrrs     z!Need an input stream to copy fromNi z"The size option must be an integerrc3s&}|V|r"t|krq"qdSr^rt)buffer)readrrrr sc3s VdSr^rr)rrrrsNeed a table to copy toselect z!Must specify a table, not a queryrCrrcopy %sz%The format option must be be a stringrZcsvrInvalid format format %sThe sep option must be a string0The sep option is not allowed with binary format2The sep option must be a single one-byte character delimiter %s The null option must be a stringnull %srwr|z from stdinrr)rrrr}rrrrrTrrlowerrr rrrgescape_identifierrrrur=putdatarG BaseExceptionrl)r`rtableformatsepnullrcolumns binary_formatrroptionsparamsrrr\r)rrrrrr copy_froms                                 zCursor.copy_fromcsj|dk}|dur6z |j} Wnty4tdYn0|rDt|tsLtd|drr|rftdd|f}ndt j j j | dd }d |fg} g} g} |durt|tstd |d vrtd | d|f|dur2t|tstd|rtdt|d krtd| d| ||durdt|tsPtd| d| |dur|dkr~dnttun,tttfstdr|rtd|rt|tsdt j j j |}| d|f| d| r| dd| fd| } jj| | fdd} |durP| S| D]}| |qVS)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 queryr|rCrrrz"The format option must be a stringrrrrrrrrrFz#The decode option must be a booleanz3The decode option is not allowed with binary formatrwz to stdoutrc3sDd_}t|tr*j|kr@|_q@jd7_|VqdS)Nrrr)rlrrrRr~getdatar`rrcopys  zCursor.copy_to..copy)writerrrrrrrr rrrgrrrrurr{rrr=rrG)r`rrrrrr~rrrrrrrrSrrrcopy_toQs                         zCursor.copy_tocCs|}|durt|S)z9Return the next row (support for the iteration protocol).N)r StopIterationrrrr__next__szCursor.__next__cCs tddS)Not supported.z%The nextset() method is not supportedN)rArrrrnextsetszCursor.nextsetcCsdSrNr)sizesrrr setinputsizesszCursor.setinputsizesrcCsdSrr)rcolumnrrr setoutputsizeszCursor.setoutputsizecCstdS)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 N)NotImplementedErrorrRrrrrjszCursor.row_factorycCs|j}|rtt|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)rrdr)r`rcrrrrkszCursor.build_row_factory)N)NF)N)NNNNN)NNNNN)r) rfrgrhrrrorarerrrpropertyrrrrprGrrrrrrrrnextr%rrrrjrkrrrrrsJE    2    k     rr)rrKZ display_sizeZ internal_sizerrZnull_okc@seZdZdZeZeZeZeZeZe Z e Z e Z e Z e Z ddZddZddZdd Zed d Zd d ZddZddZerdddZddZdS)rzConnection object.cCsP||_d|_t||_t|_d|_z|jWntyJt dYn0dS)z$Create a database connection object.FInvalid connectionN) rgrr8rhr cursor_typerr<rr^r?rrrr s  zConnection.__init__cCsR|jrNz|jdWn,ty.Yn tyFtdYn0d|_|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)rrgr<rGr;rr^rr_rrrras  zConnection.__enter__cCs.|dur"|dur"|dur"|n|dS)zExit the runtime context for the connection object. This does not close the connection, but it ends a transaction. N)commitrollbackrqrrrre+s zConnection.__exit__cCsJ|jr>|jr,z |Wnty*Yn0|jd|_ntddS)zClose the connection object.NConnection has been closed)rgrrr;rpr^r_rrrrp5s   zConnection.closecCs0z|j p|jjdkWSty*YdS0dS)z:Check whether the connection has been closed or is broken.rrTN)rgstatusrr_rrrclosedBs zConnection.closedcCsb|jrV|jr^d|_z|jdWq^ty:Yq^tyRtdYq^0ntddS)z/Commit any pending transaction to the database.FZCOMMITzCan't commit transactionrNrgrr<rGr;rr^r_rrrrJs  zConnection.commitcCsb|jrV|jr^d|_z|jdWq^ty:Yq^tyRtdYq^0ntddS)z2Roll back to the start of any pending transaction.FZROLLBACKzCan't rollback transactionrNrr_rrrrXs  zConnection.rollbackcCs<|jr0z ||WSty,tdYq80ntddS)z0Return a new cursor object using the connection.rrN)rgrrr^r_rrrcursorfs   zConnection.cursorNcCs|}||||S)z:Shortcut method to run an operation on an implicit cursor.)rrG)r`rrrrrrrGrs zConnection.executecCs|}||||S)z7Shortcut method to run an operation against a sequence.)rr)r`rZ param_seqrrrrrxs zConnection.executemany)N)rfrgrhrr8r9r:r;r?r=r@r>r<rArrarerprrrrrshortcutmethodsrGrrrrrrs.      rc Ksd}d}d}d} d} d} z6|d} | d}| d}| d} | d} | d} WntttfyfYn0|d urt|} |d ur|} |d ur|}|d urz"|d} | d}t| d}WnttttfyYn0|dkrd }| dkrd } |r~t|}d |vr|g}n|dd |fg}|D]L\} }t |}|rFd |vr^d | dd dd}| d| |fq&d |}t |||| | | }t|S)zConnect to a database.rrrrrrrsrrN=dbnamerrv\z\\'z\'z%s=%s)rrrrrrritemsinsertrrrr _connectr)ZdsnuserpasswordhostZdatabasekwargsZdbportZdbhostrZdbuserZdbpasswdZdboptrkwrr@rrrrCsd       rCcs8eZdZdZfddZfddZfddZZS)r"zType 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|||Sr^)rrrr9r"__new__)r4valuesrArrrs z Type.__new__cs<t|tr(|dr |dd}||vStt||SdSNrrr)rrrr9r"__eq__r`otherrArrrs    z Type.__eq__cs<t|tr(|dr |dd}||vStt||SdSr)rrrr9r"__ne__rrArrrs    z Type.__ne__)rfrgrhrrrrrWrrrArr"s  r"c@s eZdZdZddZddZdS) ArrayTypez&Type class for PostgreSQL array types.cCs"t|tr|dSt|tSdSNrrrrrrrrrrs  zArrayType.__eq__cCs&t|tr|d St|t SdSrrrrrrrs  zArrayType.__ne__Nrfrgrhrrrrrrrrsrc@s eZdZdZddZddZdS) RecordTypez'Type class for PostgreSQL record types.cCs4t|tr|jdkSt|tr&|dkSt|tSdSNrrrr0r+rrrrrrrs    zRecordType.__eq__cCs6t|tr|jdkSt|tr&|dkSt|t SdSrrrrrrrs    zRecordType.__ne__Nrrrrrrs rzchar bpchar name text varcharrz1int2 int4 serial int8 float4 float8 numeric moneyz?date time timetz timestamp timestamptz interval abstime reltimerrrzint2 int4 int8 serialrz float4 float8rrrKz time timetzztimestamp timestamptzrrrz json jsonbcCs t|||S)z)Construct an object holding a date value.)rK)yearmonthdayrrrr.srcCst|||||S)z)Construct an object holding a time value.)rL)hourminutesecond microsecondrOrrrr3src Cst||||||||S)z/Construct an object holding a time stamp value.)rM)rr r r r r rrOrrrr8srcCstt|ddS)zDConstruct an object holding a date value from the given ticks value.Nr)rrPZticksrrrr?srcCstt|ddS)zDConstruct an object holding a time value from the given ticks value.rrF)rrPrrrrrDsrcCstt|ddS)zDConstruct an object holding a time stamp from the given ticks value.NrF)rrPrrrrrIsrc@seZdZdZdS)rzDConstruct an object capable of holding a binary (long) string value.N)rfrgrhrrrrrrNsrcCst|||||dS)z2Construct an object holding a time interval value.)rrrr)rNrrrrrTs rc@s4eZdZdZedZedZeddZddZ dS) rz(Wrapper class for marking hstore values.z^[Nn][Uu][Ll][Ll]$|[ ,=>]z(["\\])cCsR|dur dSt|tst|}|s&dS|j|}|jd|}|rNd|f}|S)Nrtz""z\\\1rE)rrr _re_quotesearch _re_escapesub)r4srYrrrrcs   z Hstore._quotecs"|jdfdd|DS)Nrwc3s&|]\}}d||fVqdS)z%s=>%sNr)r krrxrrrsrz!Hstore.__str__..)rr rr_rrxr__str__qszHstore.__str__N) rfrgrhrregexrrr6rrrrrrr]s  rc@s"eZdZdZdddZddZdS)r z?Construct a wrapper for holding an object serializable to JSON.NcCs||_|p t|_dSr^)obj jsonencodeencode)r`rrrrrrysz Json.__init__cCs|j}t|tr|S||Sr^)rrrr)r`rrrrr}s z Json.__str__)N)rfrgrhrrrrrrrr vs r c@s$eZdZdZddZddZeZdS)r!z5Construct a wrapper for holding a literal SQL string.cCs ||_dSr^r)r`rrrrrszLiteral.__init__cCs|jSr^rr_rrrrszLiteral.__str__N)rfrgrhrrrrrrrrr!sr!__main__zPyGreSQL versionr)ri)N)N)NNNNN)rrrN)rrrrN)rrrr)r __future__rr_pg ImportErrorerr rsysenvironrpathseppaths version_infor Zadd_dll_directoryabspathrIrJ__all__rMrKrLrNrOrPZdecimalrQZ StdDecimalrr3rmathrRrScollections.abcrT collectionsrV functoolsrWrerXrrrYr#rZrr" NameErrorrr{rrr}r[r\_threadr]rBrErDrinspectrrrrutcrrrrrrrrrrrrrrrrrrrrrr&rFrGrHr*r0r7r8rXr;r]r^Z _re_fieldnamerdrer}rrrrCr frozensetr"rrr#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r4r5r6r7rrrrrrrrrr r!rfprintrrrr sn8    0          K   % ; & o   U  A