3 8\,J@sdZddlmZmZddlTeZddlmZm Z mZm Z m Z ddl m Z ddl maddlmZddlmZmZydd lmZWn ek rdd lmZYnXdd lmZdd lmZdd lmZdd lmZ ddl!m"Z#m$Z%ye&Wne'k re(Z&YnXye)Wne'k r(e*Z)YnXye+Wne'k rPe*e,fZ+YnXyddlm-Z-Wnbek rddlm.Z.yddl/m0Z0Wn$ek rGdddZ0YnXdddZ-YnXdZ1dZ2dZ3dZ4yddl5m6Z6Wn*ek rddl5m7Z7ddZ8Yn XddZ8yddlm9Z9Wn:ek rdGd d!d!e Z9e9e dd"e9_:d#Z;YnXd$Z;ed.d/Z?dd1d2Z@d3d4ZAd5d6ZBd7d8ZCd9d:ZDd;d<ZEe d=ZFd>d?ZGd@dAZHdBdCZIe dDZJe dEZKe dFZLe dGZMdHdIZNGdJdKdKe<ZOeOZPdLdMZQdNdOZRddPdQZSGdRdSdSeOZTGdTdUdUe*ZUedVdWdXgZVGdYdZdZe<ZWGd[d\d\e<ZXeYfd]d^ZZd_d`Z[e daZ\e-dbdcdddea]dfdgZ^Gdhdidie_Z`edjdWdkdldmdndodpgZaGdqdrdre_ZbecZdddsdtZcGdudvdveeZfGdwdxdxZgGdydzdzZhefd{Ziefd|Zjefd}Zkefd~ZlefdZmefdZnefdZoefdZpefdZqefdZrefdZsefdZtefdZuefdZvefdZwefdZxefdZefdZyefdZzegZ{ehZ|ddZ}dddZ~dddZddZddZddZGddde,ZdddZeZGddde<ZGdddZGdddZedkr|edeedeed0S)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)*)datetimedatetime timedeltatzinfo) localtime)Decimal)UUID)isnanisinf)Iterable) namedtuple) iskeyword)partial)compile)loadsdumps) lru_cache)update_wrapper)RLockc@seZdZddZddZdS)rcCsdS)N)selfrr%/tmp/tmpsg3uicd2/lib64/python/pgdb.py __enter__qszRLock.__enter__cCsdS)Nr)rexctypeexcinstexctbrrr__exit__sszRLock.__exit__N)__name__ __module__ __qualname__rr rrrrrpsrcsfdd}|S)z:Simplified functools.lru_cache decorator for one argument.cstijtg}|dg||ddg|dd<dkrLfdd}n2dkrhfdd}nfdd}|_t|S)NFrcs |}|S)Nr)argres)functionrrwrappersz-lru_cache..decorator..wrappercs*|}|k r|S|}||<|S)Nr)r%r&)cacher'getsentinelrrr(s  c s8f|}|dk rfd}|\}}}}||d<||d<|d}||d<|d<||d<||d<|SWdQRX|}\}}|krn|r|} || d<|| d<| d}d<|d} |d} d|d<|d<| =| |<nB|d}||||g}||d<|d<|<tkr*dd<WdQRX|S)NrT)len) r%linkrootprevnextZ_argr&lastfullZoldrootZoldargZoldres)r)r'r*lockmaxsize root_fullrrr(sB   )objectr*r __wrapped__r)r'r1r()r7)r)r'r*r6r8r+r decoratorxs $zlru_cache..decoratorr)r7r;r)r7rrus Brz2.0r,Zpyformat) signature) getargspeccCs t|jS)N)r=args)funcrrrget_argssr@cCstt|jS)N)listr< parameters)r?rrrr@s)timezonec@s2eZdZdZd ddZddZddZd d ZdS) rCzSimple timezone implementation.NcCsf||_|s\|jjd|jjd}|dkrBt| d\}}| }nt|d\}}d||f}||_dS)Ni<rz UTC%+03d:%02d)offsetdayssecondsdivmodname)rrErIminuteshoursrrr__init__s ztimezone.__init__cCs|jS)N)rE)rdtrrr utcoffsetsztimezone.utcoffsetcCs|jS)N)rI)rrMrrrtznamesztimezone.tznamecCsdS)Nr)rrMrrrdstsz timezone.dst)N)r!r"r#__doc__rLrNrOrPrrrrrCs  rCUTCFTz+0100z+0200z-0500z+0000z-1000z-0700) ZCETZEETESTGMTZHSTZMETMSTZUCTrRZWETcCs6|jdr*t|dkr|dS|jddStj|dS) N+-Z00:z+0000)rVrW) startswithr/replace _timezonesr*)tzrrr_timezone_as_offsets    r_cCsNt|}dt|ddt|dd}|ddkr>| }tt|d|S)NrDr,r.rXrrW)rJ)r_intrCr)r^rJrrr _get_timezone s $ raNcCs|dk r|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)r set_typecast) decimal_typerrrrds rdcCs|r|ddkSdS)z.Cast boolean value in database format to bool.rtTN)rerfr)valuerrr cast_bool srhcCs,|r(|jdd}tdjdd|DSdS)z/Cast money value in database format to Decimal.(rWrZcss"|]}|js|dkr|VqdS)z.-N)isdigit).0crrr *szcast_money..N)r\r join)rgrrr cast_money&s rocCsdd|jDS)zCast an int2vector value.cSsg|] }t|qSr)r`)rkvrrr /sz#cast_int2vector..)split)rgrrrcast_int2vector-srscCsh|dkrtjS|dkrtjS|j}|ddkr6tjS|d}t|dkrPtjS|j}tj||jS)zCast a date value.z -infinityinfinityr,BCr )rminmaxrrr/ date_formatrstrptime)rg connectionfmtrrr cast_date2s  r~cCs$t|dkrdnd}tj||jS)zCast a time value.z %H:%M:%S.%fz%H:%M:%S)r/rr{r)rgr}rrr cast_timeFsrz (.*)([+-].*)cCsxtj|}|r|j\}}nd}t|dkr0dnd}tr\|t|7}|d7}tj||jStj||jj t |dS)zCast a timetz value.z+0000rz %H:%M:%S.%fz%H:%M:%Sz%z)r ) _re_timezonematchgroupsr/ _has_timezoner_rr{timetzr\ra)rgr^r}rrr cast_timetzOs  rcCs|dkrtjS|dkrtjS|j}|ddkr6tjS|j}|jdrt|dkr|dd}t|dd krvtjS|jd rd nd t|dd krdnddg}n2t|ddkrtjS|t|dd krdndg}tjdj |dj |S)zCast a timestamp value.z -infinityrtr,ruz-%Yr-rXr.z%dz%d %bz%b %drz %H:%M:%S.%fz%H:%M:%Sz%Yrrv rw) rrxryrrrzendswithr/r[r{rn)rgr|r}rrrcast_timestamp_s$  rcCs|dkrtjS|dkrtjS|j}|ddkr6tjS|j}|jdrt|dkr|dd}t|dd krvtjS|jd rd nd t|dd krdnddg}|dd|d}}n|jdrtj |d}|r|j \|d<}nd}n|dd|d}}t|ddkrtjS|t|dd kr4dndg}t rp|j t ||j dtjdj|dj|Stjdj|dj|jt|dS)zCast a timestamptz value.z -infinityrtr,ruz-%Yr-Nr.rz%dz%d %bz%b %drz %H:%M:%S.%fz%H:%M:%Sz%Yz%Y-z+0000rrvz%zr)r rwrwrwrwrw)rrxryrrrzrr/r[rrrrappendr_r{rnr\ra)rgr|r}r^rrrcast_timestamptzvs<    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 Cs8tj|}|rbdd|jD}|jddk}dd|D}|\}}}}}}} |r^| }| } ntj|}|rdd|jddD|jd }} |jddk}| rd d|Dn d d|D}|\}}}}}}} |r| }| } n(tj|}|rht|jrhd d|jD}|jd dk} dd|D}|\}}}}}}} | r| }| }| }| } ntj|}|rt|jrdd|jD}|jddk} |jd dk} dd|D}|\}}}}}}} | r| }| }| r| }| }| }| } n t d||d|d|7}t ||||| dS)zCast an interval value.cSsg|] }|pdqS)0r)rkdrrrrqsz!cast_interval..rXrWcSsg|] }t|qSr)r`)rkrrrrrqscSsg|] }|pdqS)rr)rkrrrrrqsNr cSsg|]}t| qSr)r`)rkrrrrrqscSsg|] }t|qSr)r`)rkrrrrrqscSsg|] }|pdqS)rr)rkrrrrrqsr.cSsg|] }t|qSr)r`)rkrrrrrqscSsg|] }|pdqS)rr)rkrrrrrqsrcSsg|] }t|qSr)r`)rkrrrrrqszCannot parse interval: %sim)rFrKrJrG microseconds) _re_interval_iso_8601rrpop_re_interval_postgres_verbosegroup_re_interval_postgresany_re_interval_sql_standard ValueErrorr) rgmZsecs_agoZyearsZmonsrFrKZminsZsecsZusecsZagoZ hours_agoZ years_agorrr cast_intervals`   &     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. )charZbpcharrItextZvarcharboolbyteaint2Zint4serialint8oidhstorejsonZjsonbZfloat4Zfloat8rbmoneyrintervalrr timestampZ timestamptzZ int2vectoruuidanyarrayrecordNcCsnt|tstd||jj|}|r:|j|}|||<n0|jdrj||dd}|j|}|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_r,N) isinstancestr TypeErrordefaultsr*_add_connectionr[create_array_cast)rtypcast base_castrrr __missing__ s       zTypecasts.__missing__c Cs:y t|}Wnttfk r$dSXd|ddkSdS)z9Check if a typecast function needs a connection argument.Fr|r,N)r@rr)r?r>rrr_needs_connection"s  zTypecasts._needs_connectioncCs&|j s|j| r|St||jdS)z@Add a connection argument to the typecast function if necessary.)r|)r|rr)rrrrrr,szTypecasts._add_connectioncCs ||p |S)z6Get the typecast function for the given database type.r)rrdefaultrrrr*2sz Typecasts.getcCst|tr|g}|dkrDxf|D] }|j|d|jd|dqWn.castr)rrrr)rrrr_szTypecasts.create_array_castcs&|dt||fdd}|S)z>Create a named record typecast for the given fields and casts.rcs|S)Nr)rp) cast_recordcastsrrrrjsz*Typecasts.create_record_cast..cast)r)rrIfieldsrrr)rrrrcreate_record_castfs zTypecasts.create_record_cast)N)N)#r!r"r#rQrrhZunescape_bytear`longZ cast_hstore jsondecodefloatr ror~rrrrrrsUuidrrrr|r staticmethodrrr*rrrrrrrrrs,     rcCs tj|S)z@Get the global typecast function for the given database type(s).) _typecastsr*)rrrr get_typecastrsrcCstj||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(). N)rr)rrrrrrcwsrccCstj|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(). N)rr)rrrrreset_typecastsrc@s(eZdZdZeZdZddZddZdS)LocalTypecastszBMap typecasts, including local composite types, to cast functions.Ncs|jdr2|dd}j|}|r||<nhjj|}|rVj|}||<nDj|}|rfdd|D}dd|D}j|||}||<|S)z+Create a cast function if it is not cached.rr,Ncsg|]}|jqSr)type)rkfield)rrrrqsz.LocalTypecasts.__missing__..cSsg|] }|jqSr)rI)rkrrrrrqs)r[rrr*r get_fieldsr)rrrrrrr)rrrs        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. r)rrrrrrszLocalTypecasts.get_fields) r!r"r#rQrrr|rrrrrrrs rc@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.)rr/rcategorydelimrelid) clsrrIr/rrrrrrrrcreateszTypeCode.createN)r!r"r#rQ classmethodrrrrrrsr FieldInforIrcs\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. csVtt|j|j|_|j|_t|_|j |j_ ||j_ |j dkrLd|_ nd|_ dS)z%Initialize type cache for connection.i:zgSELECT oid, typname, typlen, typtype, null as typcategory, typdelim, typrelid FROM pg_type WHERE oid=%sz_SELECT oid, typname, typlen, typtype, typcategory, typdelim, typrelid FROM pg_type WHERE oid=%sN) superrrL escape_string_escape_stringsource_srcrrrr|Zserver_version_query_pg_type)rcnx) __class__rrrLs   zTypeCache.__init__cCst|tr|}n*d|kr*d|kr*d|f}d|j|f}y|jj|j|fWntk rjd}YnX|jjd}|std|f|d}t j t|d|dt|d |d |d |d t|d }|||j <|t |<|S)z8Get the type info from the database if it is not cached.."z"%s"z '%s'::regtypeNr,zType %s could not be foundrr-r.rrX) rr`rrexecuterProgrammingErrorfetchKeyErrorrrrr)rkeyrr& type_coderrrrs"    *zTypeCache.__missing__Nc Cs"y||Stk r|SXdS)z&Get the type even if it is not cached.N)r)rrrrrrr*sz TypeCache.getcsTt|tsj|}|sdS|js&dSjjd|jffddjjdDS)z9Get the names and types of the fields of composite types.NznSELECT attname, atttypid FROM pg_attribute WHERE attrelid=%s AND attnum>0 AND NOT attisdropped ORDER BY attnumcs$g|]\}}t|jt|qSr)rr*r`)rkrIr)rrrrqsz(TypeCache.get_fields..r,rw)rrr*rrrr)rrr)rrrs    zTypeCache.get_fieldscCs |jj|S)z6Get the typecast function for the given database type.)rr*)rrrrrr szTypeCache.get_typecastcCs|jj||dS)z;Set a typecast function for the specified database type(s).N)rr)rrrrrrrcszTypeCache.set_typecastcCs|jj|dS)z?Reset the typecast function for the specified database type(s).N)rr)rrrrrrszTypeCache.reset_typecastcCs0|dkr dS|j|}| s$|tkr(|S||S)z:Cast the given value according to the given database type.N)rr)rrgrrrrrtypecasts  zTypeCache.typecast)N)N) r!r"r#rQrLrr*rrrcrr __classcell__rr)rrrs   rcs eZdZdZfddZZS) _quotedictzsDictionary with auto quoting of its items. The quote attribute must be set to the desired quote function. cs|jtt|j|S)N)quoterr __getitem__)rr)rrrr(sz_quotedict.__getitem__)r!r"r#rQrrrr)rrr"srcCs||}d|_|S)z3Return DatabaseError with empty sqlstate attribute.N)Zsqlstate)msgrerrorrrr _db_error.srcCs t|tS)zReturn OperationalError.)rOperationalError)rrrr _op_error5srz^[A-Za-z][_a-zA-Z0-9]*$i)r7cCs|yDytd|ddjStk r@ddt|D}td|jSXWn2tk rvddtt|D}td|jSXdS)z>Get a namedtuple factory for row results with the given names.ZRowT)renamecSs2g|]*\}}tj|r$t| r$|nd|fqS)z column_%d) _re_fieldnamerr)rknrprrrrqIsz _row_factory..cSsg|]}d|fqS)z column_%dr)rkrrrrrqNsN)r_maker enumeraterranger/)namesrrr _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)rrr:)r7rrrset_row_factory_sizeRsrc@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|jyddjfdd|DfStk rddjfdd|DfSXt|tr |jyddjfdd|DfStk r ddjfdd|DfSXy |j}Wn(tk r@tdt |fYnXt|ttfr\|j|}|S)z"Quote value depending on its type.NNULLasciiz'%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|VqdS)N)r)rkrp)qrrrmsz Cursor._quote..c3s|]}t|VqdS)N)unicode)rkrp)rrrrmsz(%s)c3s|]}t|VqdS)N)r)rkrp)rrrrmsc3s|]}t|VqdS)N)r)rkrp)rrrrmsz Do not know how to adapt type %s)!rHstoreJsonrrBinaryrZ escape_byteabytesdecoderrrr r`rr Literalrr rrrrrA_quoternUnicodeEncodeErrortuple __pg_repr__AttributeErrorInterfaceErrorr)rrgr)rrr}sn                        z Cursor._quotec CsZ|s&y|fSttfk r$|SXt|trBt|}|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. ) rrrdictrrrrmap)rstringrBrrr _quoteparamss  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.r,Nrrrbirw)rsizeCursorDescription) rinforIrr$modr precisionscalerrr_make_descriptions zCursor._make_descriptioncs8|j}|jdkr4|jfdd|jjD}||_|S)z2Read-only attribute describing the result columns.Tcsg|] }|qSrr)rkr&)makerrrqsz&Cursor.description..)rr*rZlistinfo)rdescrr)r+r descriptions  zCursor.descriptioncCsdd|jDS)z;Unofficial convenience method for getting the column names.cSsg|] }|dqS)rr)rkrrrrrqsz#Cursor.colnames..)r-)rrrrcolnamesszCursor.colnamescCsdd|jDS)z;Unofficial convenience method for getting the column types.cSsg|] }|dqS)r,r)rkrrrrrqsz#Cursor.coltypes..)r-)rrrrcoltypesszCursor.coltypescCs|jjdS)zClose the cursor object.N)rr )rrrrr sz Cursor.closeNcshrVttrVtdkrVtddDrVtfddddDrV|j|S|j|gSdS)z.c3s"|]}t|tdkVqdS)rN)r/)rkr0)rBrrrm sN)rrAr/all executemany)r operationrBr)rBrrs   zCursor.executecCs|sdSd|_d |_d}d}y|jj r||jj r|y|jj|Wn0tk rXYn$tk rrt dYn Xd|j_x<|D]4}|}|j ||}|jj|}|r||7}qd |_qWWn|tk rYnht k r}zt d||ft WYdd}~Xn4tk r8}zt d||fWYdd}~XnX|jjtkrrd|_|jj|_d|_|jr|j|_n||_|jj|_|S) z>Prepare operation and execute it against a parameter sequence.Nr,rBEGINzCan't start transactionTzError in '%s': '%s' zInternal error in '%s': %srwrw)rrr_tnx autocommitrr DatabaseError Exceptionrr"ErrorrrZ resulttypeZ RESULT_DQLZntuplesrrrZ oidstatus)rr3Zseq_of_parametersrsqlrBZrowserrrrrr2sL     "   zCursor.executemanyc Cs.|jdd}y|dStk r(dSXdS)z)Fetch the next row of a query result set.r,FrN) fetchmany IndexError)rr&rrrfetchone@s  zCursor.fetchonecCs |jddS)z-Fetch all (remaining) rows of a query result.r,Frw)r<)rrrrfetchallHszCursor.fetchallFcs|dkrj}|r|_yjj|}WnBtk r>Yn.tk rj}ztt|WYdd}~XnXjjfdd|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|]$}jfddtj|DqS)csg|]\}}||qSrr)rkrrg)rrrrq_sz/Cursor.fetchmany...)rzipr/)rkrow)rrrrrq_sz$Cursor.fetchmany..) rrrr7r9rrrr)rr$Zkeepresultr;r)rrrr<Ls zCursor.fetchmanycCs8|r t|pd}d|dj|dgf}|j|||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)r/rnr)rZprocnamerBrqueryrrrcallprocbs  zCursor.callproccs|dk}y jWntk rr.td|r.chunksc3s`xZD]R}t|s"tdft|tr@|jdsR|d7}n|jdsR|d7}|VqWdS)NzInput stream must consist of %srGrH)rrrr)chunk) input_typerI type_namerrrJs       z!Need an input stream to copy fromNi z"The size option must be an integerrc3s,x&}|V| s"t|krPqWdS)N)r/)buffer)readr$rrrJs c3s VdS)Nrr)rOrrrJszNeed a table to copy toselectz!Must specify a table, not a queryz"%s"zcopy %sz$The frmat option must be be a stringrcsvzInvalid formatz format %szThe sep option must be a stringz0The sep option is not allowed with binary formatr,z2The sep option must be a single one-byte characterz delimiter %sz The null option must be a stringznull %srcss|]}d|fVqdS)z"%s"Nr)rkcolrrrrmsz#Cursor.copy_from..z(%s)z from stdinr)rrQrErw)rOrrrrrrrrrr`lowerr[rr/rnrputdatar BaseExceptionr)rrItableformatsepnullr$columns binary_formatrJr3optionsparamsrTrKrr)rLrOr$rIrMr copy_fromrs                                zCursor.copy_fromc s^|dk}|dk r8y |j} Wntk r6tdYnX| sJt|t rRtd|jjdrx|rltdd|f}n d|f}d |fg} g} g} |dk rt|tstd |d krtd | jd|f|dk r$t|tstd|rtdt |dkrtd| jd| j||dk rVt|tsBtd| jd| j|dkrz|dkrpdnt t kn,tt t fstdr|rtd|rt|tsdjdd|D}| jd|f| jd| r| jddj| fdj| } jjj| | fdd} |dkr@| Sx| D]}| |qHWS)!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. rENz Need an output stream to copy tozNeed a table to copy torPz&Columns must be specified in the queryz(%s)z"%s"zcopy %sz"The format option must be a stringrrQzInvalid formatz format %szThe sep option must be a stringz0The sep option is not allowed with binary formatr,z2The sep option must be a single one-byte characterz delimiter %sz The null option must be a stringznull %sFz#The decode option must be a booleanz3The decode option is not allowed with binary formatrcss|]}d|fVqdS)z"%s"Nr)rkrRrrrrmCsz!Cursor.copy_to..z to stdoutrc3sHd_x<}t|tr,j|kr*|_Pjd7_|VqWdS)Nrr,)rrr`)rA)rgetdatarrrcopyNs  zCursor.copy_to..copy)rrQrE)writerrrrrSr[rrr/rrr`rrnrr_r)rrIrVrWrXrYrrZr[rar3r\r]r`rAr)rr_rrcopy_tos~                       zCursor.copy_tocCs|j}|dkrt|S)z9Return the next row (support for the iteration protocol).N)r> StopIteration)rr&rrr__next__dszCursor.__next__cCs tddS)zNot supported.z%The nextset() method is not supportedN)NotSupportedErrorrrrrnextsetoszCursor.nextsetcCsdS)zNot supported.Nr)Zsizesrrr setinputsizestszCursor.setinputsizesrcCsdS)zNot supported.Nr)r$columnrrr setoutputsizeyszCursor.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)NotImplementedError)rArrrr~szCursor.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)r.rr)rrrrrrszCursor.build_row_factory)N)NF)N)NNNNN)NNNNN)r) r!r"r#rQrLr rr rr"r*propertyr-r.r/r rr2r>r?r<rDr^rbrdr3rrfrgrirrrrrrr]s:E   1    g     rr%rZ display_sizeZ internal_sizer(r)Znull_okc@seZdZdZeZeZeZeZeZe Z e Z e Z e Z e Z ddZddZddZdd Zed d Zd d ZddZddZerdddZddZdS) ConnectionzConnection object.c CsR||_d|_t||_t|_d|_y|jjWntk rLt dYnXdS)z$Create a database connection object.FzInvalid connectionN) rr5rrr cursor_typer6rr8r)rrrrrrLs zConnection.__init__c CsV|jrRy|jjjdWn0tk r0Yn"tk rJtdYnXd|_|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. r4zCan't start transactionT)r6rrrr7r8rr5)rrrrrszConnection.__enter__cCs.|dkr"|dkr"|dkr"|jn|jdS)zExit the runtime context for the connection object. This does not close the connection, but it ends a transaction. N)commitrollback)rr r r rrrr s zConnection.__exit__c CsL|jr@|jr.y |jWntk r,YnX|jjd|_ntddS)zClose the connection object.NzConnection has been closed)rr5ror7r r)rrrrr s  zConnection.closec Cs.y|j p|jjdkStk r(dSXdS)z:Check whether the connection has been closed or is broken.r,TN)rstatusr)rrrrclosedszConnection.closedc Csf|jrZ|jrbd|_y|jjjdWqbtk r<Yqbtk rVtdYqbXntddS)z/Commit any pending transaction to the database.FZCOMMITzCan't commit transactionzConnection has been closedN)rr5rrr7r8r)rrrrrnszConnection.commitc Csf|jrZ|jrbd|_y|jjjdWqbtk r<Yqbtk rVtdYqbXntddS)z2Roll back to the start of any pending transaction.FZROLLBACKzCan't rollback transactionzConnection has been closedN)rr5rrr7r8r)rrrrroszConnection.rollbackc Cs<|jr0y |j|Stk r,tdYq8XntddS)z0Return a new cursor object using the connection.zInvalid connectionzConnection has been closedN)rrmr8r)rrrrcursors  zConnection.cursorNcCs|j}|j|||S)z:Shortcut method to run an operation on an implicit cursor.)rrr)rr3r]rrrrrrs zConnection.executecCs|j}|j|||S)z7Shortcut method to run an operation against a sequence.)rrr2)rr3Z param_seqrrrrrr2 s zConnection.executemany)N)r!r"r#rQr9Warningrr7Z InternalErrorrrZIntegrityErrorZ DataErrorrerLrr r rkrqrnrorrshortcutmethodsrr2rrrrrls,     rlcKsd}d}d}d} d} d} y6|jd} | d}| d}| d} | d} | d} Wntttfk rhYnX|dk rv|} |dk r|} |dk r|}|dk ry"|jd} | d}t| d}Wnttttfk rYnX|dkrd}| dkrd} |rt|j}d |kr|g}n|jdd |fg}xX|D]P\} }t |}| sNd |krhd |j d dj ddf}|j d| |fq,Wd j |}t |||| | | }t|S)zConnect to a database.r,rZrYrr-r.rN=dbnamerz'%s''z\'\z\\z%s=%srw)rrrr=rr`rrAitemsinsertrr\rrn_connectrl)ZdsnuserpasswordhostZdatabasekwargsZdbportZdbhostrvZdbuserZdbpasswdZdboptr]kwrgrrrrconnect+s^      rcs8eZdZdZfddZfddZfddZZS)TypezType 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|j}tt|j||S)N)rrrrrr__new__)rvalues)rrrrss z Type.__new__cs<t|tr(|jdr |dd}||kStt|j|SdS)Nrr,)rrr[rr__eq__)rother)rrrrxs    z Type.__eq__cs<t|tr(|jdr |dd}||kStt|j|SdS)Nrr,)rrr[rr__ne__)rr)rrrrs    z Type.__ne__)r!r"r#rQrrrrrr)rrrls  rc@s eZdZdZddZddZdS) ArrayTypez&Type class for PostgreSQL array types.cCs"t|tr|jdSt|tSdS)Nr)rrr[r)rrrrrrs  zArrayType.__eq__cCs&t|tr|jd St|t SdS)Nr)rrr[r)rrrrrrs  zArrayType.__ne__N)r!r"r#rQrrrrrrrsrc@s eZdZdZddZddZdS) RecordTypez'Type class for PostgreSQL record types.cCs4t|tr|jdkSt|tr&|dkSt|tSdS)Nrlr)rrrrr)rrrrrrs    zRecordType.__eq__cCs6t|tr|jdkSt|tr&|dkSt|t SdS)Nrlr)rrrrr)rrrrrrs    zRecordType.__ne__N)r!r"r#rQrrrrrrrsrzchar bpchar name text varcharrz1int2 int4 serial int8 float4 float8 numeric moneyz?date time timetz timestamp timestamptz interval abstime reltimerrrzint2 int4 int8 serialrz float4 float8rbrrz time timetzztimestamp timestamptzrrrz json jsonbcCs t|||S)z)Construct an object holding a date value.)r)yearmonthdayrrrDatesrcCst|||||S)z)Construct an object holding a time value.)r)hourminutesecond microsecondr rrrTimesrc Cst||||||||S)z/Construct an object holding a time stamp value.)r)rrrrrrrr rrr TimestampsrcCstt|ddS)zDConstruct an object holding a date value from the given ticks value.Nr.)rr )ticksrrr DateFromTickssrcCstt|ddS)zDConstruct an object holding a time value from the given ticks value.r.r)rr )rrrr TimeFromTickssrcCstt|ddS)zDConstruct an object holding a time stamp from the given ticks value.Nr)rr )rrrrTimestampFromTickssrc@seZdZdZdS)rzDConstruct an object capable of holding a binary (long) string value.N)r!r"r#rQrrrrrsrcCst|||||dS)z2Construct an object holding a time inverval value.)rKrJrGr)r)rFrKrJrGrrrrIntervals rc@s4eZdZdZedZedZeddZddZ dS) rz(Wrapper class for marking hstore values.z^[Nn][Uu][Ll][Ll]$|[ ,=>]z(["\\])cCs@|dkr dS|sdS|jj|}|jjd|}|r%sNr)rkkrp)rrrrmsz!Hstore.__str__..)rrnry)rr)rr__str__szHstore.__str__N) r!r"r#rQregexrrrrrrrrrrs  rc@s"eZdZdZdddZddZdS)rz?Construct a wrapper for holding an object serializable to JSON.NcCs||_|p t|_dS)N)obj jsonencodeencode)rrrrrrrLsz Json.__init__cCs|j}t|tr|S|j|S)N)rrrr)rrrrrrs z Json.__str__)N)r!r"r#rQrLrrrrrrs rc@s$eZdZdZddZddZeZdS)rz5Construct a wrapper for holding a literal SQL string.cCs ||_dS)N)r:)rr:rrrrL)szLiteral.__init__cCs|jS)N)r:)rrrrr,szLiteral.__str__N)r!r"r#rQrLrrrrrrr&sr__main__zPyGreSQL versionrZ)r$)N)N)NNNNN)rrrN)rrrrN)rrrr)rQ __future__rr_pgversion __version__rrrrr r Zdecimalr rr rmathr rcollections.abcr ImportError collectionsrkeywordr functoolsrrerrrrrrrr NameErrorr`rrrrrr_threadrZapilevelZ threadsafetyZ paramstylertinspectr<r=r@rCutcrrr]r_rardrhrorsr~rrrrrrrrrrrrrrcrrrrrrr7rrrrrr9rr%rlrr{ frozensetrrrSTRINGZBINARYNUMBERZDATETIMEZROWIDZBOOLZSMALLINTZINTEGERLONGFLOATZNUMERICZMONEYZDATEZTIMEZ TIMESTAMPZINTERVALZHSTOREZJSONARRAYZRECORDrrrrrrrrrrrr!printrrrrCs*          K    %;} %\  F  ?