https://t.me/RX1948
Server : Apache
System : Linux iad1-shared-b8-43 6.6.49-grsec-jammy+ #10 SMP Thu Sep 12 23:23:08 UTC 2024 x86_64
User : dh_edsupp ( 6597262)
PHP Version : 8.2.26
Disable Function : NONE
Directory :  /lib/python3/dist-packages/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //lib/python3/dist-packages/__pycache__/pg.cpython-310.pyc
o

���^<��@sXdZddlmZmZzddlTWnTeydddlZddlZejdkraej	dkraej
d�ej�D],Z
ej
�ej
�e
d��r^e�ej
�e
���ddlTWd�n1sWwYnq2�n�YnweZgd	�ZddlZddlZddlZdd
lmZmZmZmZmZddlmZddlm Z m!Z!dd
l"m#Z#ddl$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z,ddl-m.Z/m0Z1ddl2m3Z3ze4Wne5y�e6Z4Ynwze7Wn
e5y�e8e9fZ7Ynwzddl(m:Z:Wn/e�yddl(m;Z;zddl<m=Z=Wne�yGdd�d�Z=Ynwd�dd�Z:Ynwzddl"m>Z>Wne�y5e?Z>Gdd�de?�Z@Yn	wGdd�de>�Z@zdd lAmBZBWne�yZdd!lAmCZCd"d#�ZDYnwd$d#�ZDzdd%lmEZEWne�y�Gd&d'�d'e�ZEeEed�d(�eE_Fd)ZGYnwd*ZGe?d+d,d-d.d/d+d0d.d.d.d1�
ZHd2d3�ZId4d5�ZJd6d7�ZKGd8d9�d9e?�ZLeL�ZMd:d;�ZNGd<d=�d=eO�ZPGd>d?�d?e9�ZQGd@dA�dAe?�ZRGdBdC�dC�ZSGdDdE�dEe8�ZTGdFdG�dG�ZUdHdI�ZVdJdK�ZWdLdM�ZXdNdO�ZYdPdQ�ZZdRdS�Z[dTdU�Z\e,dV�Z]dWdX�Z^dYdZ�Z_d[d\�Z`e,d]�Zae,d^�Zbe,d_�Zce,d`�Zddadb�ZeGdcdd�dde?�Zfdedf�Zgdgdh�ZhGdidj�dje8�ZiGdkdl�dle?�Zje,dm�Zke:dndo�dpdq��aldrds�Zmdtdu�Zndvdw�Zodxdy�Zpdzd{�ZqGd|d}�d}�Zresfd~d�Ztd�d��Zud�d��Zvewe�exe/�eyeneoepeq�Gd�d��d�ez�Z{d�d��Z|Gd�d��d��Z}e~d�k�r�ed�e�ed��ee�dSdS)�aZPyGreSQL classic interface.

This pg module implements some basic database management stuff.
It includes the _pg module and builds on it, providing the higher
level wrapper class named DB with additional functionality.
This is known as the "classic" ("old style") PyGreSQL interface.
For a DB-API 2 compliant interface use the newer pgdb module.
�)�print_function�division)�*N�nt)���PATHz	libpq.dll)B�DB�Adapter�NotificationHandler�	Typecasts�Bytea�Hstore�Json�Literal�Error�Warning�	DataError�
DatabaseError�IntegrityError�InterfaceError�
InternalError�InvalidResultError�MultipleResultsError�
NoResultError�NotSupportedError�OperationalError�ProgrammingError�INV_READ�	INV_WRITE�SEEK_CUR�SEEK_END�SEEK_SET�TRANS_ACTIVE�
TRANS_IDLE�
TRANS_INERROR�
TRANS_INTRANS�
TRANS_UNKNOWN�
cast_array�cast_hstore�cast_record�connect�escape_bytea�
escape_string�unescape_bytea�	get_array�get_bool�get_bytea_escaped�
get_datestyle�get_decimal�get_decimal_point�get_defbase�get_defhost�
get_defopt�get_defport�get_defuser�get_jsondecode�	set_array�set_bool�set_bytea_escaped�
set_datestyle�set_decimal�set_decimal_point�set_defbase�set_defhost�
set_defopt�
set_defpasswd�set_defport�set_defuser�set_jsondecode�set_query_helpers�version�__version__)�date�time�datetime�	timedelta�tzinfo)�Decimal)�isnan�isinf��
namedtuple)�	iskeyword)�
itemgetter)�partial)�compile)�loads�dumps)�UUID)�	lru_cache)�update_wrapper)�RLockc@seZdZdd�Zdd�ZdS)r^cC�dS�N���selfrara�$/usr/lib/python3/dist-packages/pg.py�	__enter__h�zRLock.__enter__cCr_r`ra)rc�exctype�excinst�exctbrarard�__exit__jrfzRLock.__exit__N)�__name__�
__module__�__qualname__rerjrararardr^gsr^�cs�fdd�}|S)z:Simplified functools.lru_cache decorator for one argument.cs�t��i��j�t��g}|dg�||ddg|dd�<�dkr&�fdd�}n�dur4����fdd�}n������fdd�}�|_t|��S)NFrcs�|�}|Sr`ra��arg�res)�functionrard�wrapperzsz-lru_cache.<locals>.decorator.<locals>.wrappercs*�|��}|�ur|S�|�}|�|<|Sr`raro)�cacherr�get�sentinelrardrs�s
cs���?�|�}|dur:�d}|\}}}}||d<||d<|d}||d<|d<||d<||d<|Wd�SWd�n1sDwY�|�}��v�\}}|�vrYnT|r�|}	||	d<||	d<|	d}�d<|d}
|d}d|d<|d<�|
=|	�|<n8|d}||||g}||d<|d<�|<t���kr�d�d<Wd�|SWd�|SWd�|SWd�|S1s�wY|S)Nr��rT)�len)rp�link�root�prev�next�_argrq�last�full�oldroot�oldarg�oldres)rtrrru�lock�maxsize�	root_fullrardrs�s`��


��
��
��
��)�objectrur^�__wrapped__r])rrr{rs�r�)rtrrrur�r�rvrd�	decoratoros
$
zlru_cache.<locals>.decoratorra)r�r�rar�rdr\lsBr\)�OrderedDictc@sleZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
edd��ZdS)�AttrDict�@Simple read-only ordered dictionary for storing attribute names.cOs�t|�dks|r
t�|r|dng}t|t�rt�t|�}dd�|D�|_t�||�d|_|j}||_	|_
||_|_|_
dS)NrwrcS�g|]}|d�qS�rra)�.0�itemrarard�
<listcomp>��z%AttrDict.__init__.<locals>.<listcomp>T)ry�	TypeError�
isinstance�dict�list�_keys�__init__�
_read_only�_read_only_error�clear�update�pop�
setdefault�popitem)rc�args�kw�items�errorrarardr��s
�AttrDict.__init__cC� |jr|��t�|||�dSr`)r�r�r��__setitem__�rc�key�valuerarardr����AttrDict.__setitem__cC�|jr|��t�||�dSr`)r�r�r��__delitem__�rcr�rarardr����AttrDict.__delitem__cC�
t|j�Sr`)�iterr�rbrarard�__iter__��
zAttrDict.__iter__cCr�r`)r�r�rbrarard�keys�r�z
AttrDict.keysc��fdd��D�S)Ncsg|]}�|�qSrara�r�r�rbrardr��r�z#AttrDict.values.<locals>.<listcomp>rarbrarbrd�values��zAttrDict.valuescr�)Ncsg|]}|�|f�qSrarar�rbrardr���z"AttrDict.items.<locals>.<listcomp>rarbrarbrdr��r�zAttrDict.itemscCs|��Sr`)r�rbrarard�iterkeys�szAttrDict.iterkeyscC�t|���Sr`)r�r�rbrarard�
itervalues��zAttrDict.itervaluescCr�r`)r�r�rbrarard�	iteritems�r�zAttrDict.iteritemscO�td���NzThis object is read-only�r��r�r�rarardr����AttrDict._read_only_errorN)rkrlrm�__doc__r�r�r�r�r�r�r�r�r�r��staticmethodr�rararardr��sr�c@s4eZdZdZdd�Zdd�Zdd�Zedd	��Zd
S)r�r�cOsLd|_tj|g|�Ri|��d|_|j}||_|_||_|_|_dS)NFT)	r�r�r�r�r�r�r�r�r�)rcr�r�r�rarardr��sr�cCr�r`)r�r�r�r�r�rarardr��r�r�cCr�r`)r�r�r�r�r�rarardr�r�r�cOr�r�r�r�rarardr�r�r�N)	rkrlrmr�r�r�r�r�r�rararardr��s)�	signature)�
getargspeccCs
t|�jSr`)r�r���funcrarard�get_argsr�r�cCstt|�j�Sr`)r�r��
parametersr�rarardr��)�timezonec@s2eZdZdZddd�Zdd�Zdd�Zd	d
�ZdS)r�zSimple timezone implementation.NcCsf||_|s.|jjd|jjd}|dkr!t|d�\}}|}nt|d�\}}d||f}||_dS)Ni��<rz
UTC%+03d:%02d)�offset�days�seconds�divmod�name)rcr�r��minutes�hoursrarardr�s
ztimezone.__init__cC�|jSr`)r��rc�dtrarard�	utcoffset*�ztimezone.utcoffsetcCr�r`)r�r�rarard�tzname-r�ztimezone.tznamecCr_r`rar�rarard�dst0�ztimezone.dstr`)rkrlrmr�r�r�r�r�rararardr�s
r��UTCFTz+0100z+0200z-0500�+0000z-1000z-0700)
�CET�EET�EST�GMT�HST�MET�MST�UCTr��WETcCs6|�d�rt|�dkr|dS|�dd�St�|d�S)N)�+�-��00�:�r�)�
startswithry�replace�
_timezonesru)�tzrarard�_timezone_as_offset?s

r�cCsNt|�}dt|dd��t|dd��}|ddkr|}tt|d�|�S)Nr�rwrr�rr�)r�)r��intr�rN)r�r�rarard�
_get_timezoneGs
$r�cCsd|S)z Build oid key from a table name.zoid(%s)ra)�tablerarard�_oid_keyOr�r�c@s<eZdZdZdddddddd	d
ddd
�Zdd�Zdd�ZdS)�_SimpleTypesz6Dictionary mapping pg_type names to simple type names.�bool�byteaz?date interval time timetz timestamp timestamptz abstime reltimez
float4 float8zcid int2 int4 int8 oid xid�hstorez
json jsonb�uuid�numeric�moneyzbpchar char name text varchar)r�r�rK�floatr�r��jsonr��numr�textcCs>|j��D]\}}|��D]}|||<d||d|<q
qdS)N�%s[]�_%s)�_typesr��split)rc�typr�r�rarardr�as��z_SimpleTypes.__init__cC�dS)Nrrar�rarard�__missing__hr�z_SimpleTypes.__missing__N)rkrlrmr�rr�rrararardr�Ts�
r�cCs t|t�rd|vrd|fS|S)a#Quote parameter representing a qualified name.

    Puts a quote_ident() call around the give parameter unless
    the name contains a dot, in which case the name is ambiguous
    (could be a qualified name or just a name with a dot in it)
    and must be quoted manually by the caller.
    �.zquote_ident(%s))r��
basestring)�paramr�rarard�_quote_if_unqualifiedns
rc@seZdZdZddd�ZdS)�_ParameterListz0Helper class for building typed parameter lists.NcCs0|�||�}t|t�r
|S|�|�dt|�S)z�Typecast value with known database type and build parameter list.

        If this is a literal value, it will be returned as is.  Otherwise, a
        placeholder will be returned and the parameter list will be augmented.
        z$%d)�adaptr�r�appendry)rcr�r
rarard�add~s


z_ParameterList.addr`)rkrlrmr�rrararardr{src@�eZdZdZdS)r
z'Wrapper class for marking Bytea values.N�rkrlrmr�rararardr
��r
c@s,eZdZdZed�Zedd��Zdd�ZdS)rz(Wrapper class for marking hstore values.z^[Nn][Uu][Ll][Ll]$|[ ,=>]cCs8|durdS|s
dS|�dd�}|j�|�rd|}|S)N�NULL�""�"z\"�"%s")r��	_re_quote�search)�cls�srarard�_quote�sz
Hstore._quotecs"|j�d��fdd�|��D��S)N�,c3s(�|]\}}d�|��|�fVqdS)z%s=>%sNra)r��k�v��qrard�	<genexpr>�s�&z!Hstore.__str__.<locals>.<genexpr>)r �joinr�rbrar$rd�__str__�szHstore.__str__N)	rkrlrmr��regexr�classmethodr r(rararardr�s

rc@seZdZdZdd�ZdS)rz&Wrapper class for marking Json values.cCs
||_dSr`)�obj)rcr+rarardr��r�z
Json.__init__N)rkrlrmr�r�rararardr�src@r)rz-Wrapper class for marking literal SQL values.Nrrararardr�rrc@sneZdZdZed���Zed���Zed�Z	ed�Z
ed�ZZdd�Z
ed	d
��Zedd��Zed
d��ZeZZZdd�Zdd�Zedd��ZeZedd��Zedd��ZeZZZdd�Zdd�Z dd�Z!d:d d!�Z"ed"d#��Z#ed$d%��Z$ed&d'��Z%e&d(e'd)e(d)e)d*e*d+e+d+e,d,e-d-e.d.e/d.e0d.e1d.iZ2ed/d0��Z3ed1d2��Z4d;d4d5�Z5d6d7�Z6d<d8d9�Z7dS)=r
z@Class providing methods for adapting parameters to the database.zt true 1 y yes onzDcurrent_date current_time current_timestamp localtime localtimestampz[{},"\\\s]|^[Nn][Uu][Ll][Ll]$z[(,"\\]z(["\\])cCst�|�|_dSr`)�weakref�proxy�db�rcr.rarardr��szAdapter.__init__cCs,t|t�r|s	dS|��|jv}|rdSdS)zAdapt a boolean parameter.N�t�f)r�r�lower�_bool_true_values�rr#rarard�_adapt_bool�s

zAdapter._adapt_boolcCs,|sdSt|t�r|��|jvrt|�S|S)zAdapt a date parameter.N)r�rr2�_date_literalsrr4rarard�_adapt_date�s
zAdapter._adapt_datecCs|s|dkrdS|S)zAdapt a numeric parameter.rNra�r#rarard�
_adapt_num�szAdapter._adapt_numcC�|j�|�S)zAdapt a bytea parameter.)r.r,�rcr#rarard�_adapt_bytea��zAdapter._adapt_byteacCs"|sdSt|t�r|S|j�|�S)zAdapt a json parameter.N)r�rr.�encode_jsonr;rarard�_adapt_json�s

zAdapter._adapt_jsoncsjt|t�r|j�dd��fdd�|D��S|durdS|s dSt|�}|j�|�r3d|j�d	|�}|S)
z"Adapt a text type array parameter.�{%s}r!c3��|]}�|�VqdSr`ra�r�r#�rrardr&���z,Adapter._adapt_text_array.<locals>.<genexpr>N�nullrr�\\\1)	r�r��_adapt_text_arrayr'�str�_re_array_quoter�_re_array_escape�subr4rarCrdrG�s
zAdapter._adapt_text_arraycsdt|t�r|j�dd��fdd�|D��S|durdSt|t�r,|s%dS|��|jv}|r0dSdS)	z Adapt a boolean array parameter.r@r!c3rAr`rarBrCrardr&�rDz,Adapter._adapt_bool_array.<locals>.<genexpr>NrEr0r1)r�r��_adapt_bool_arrayr'rr2r3r4rarCrdrL�s

zAdapter._adapt_bool_arraycsDt|t�r|j�dd��fdd�|D��S|s|dkrdSt|�S)z Adapt a numeric array parameter.r@r!c3rAr`rarBrCrardr&	rDz+Adapter._adapt_num_array.<locals>.<genexpr>rrE)r�r��_adapt_num_arrayr'rHr4rarCrdrMs
zAdapter._adapt_num_arraycsJt|t�rdd��fdd�|D��dS|durdS�j�|��dd	�S)
zAdapt a bytea array parameter.�{�,c3s�|]}��|�VqdSr`)�_adapt_bytea_arrayrBrbrardr&s�

�z-Adapter._adapt_bytea_array.<locals>.<genexpr>�}Nsnull�\s\\)r�r�r'r.r,r�r;rarbrdrPs
��zAdapter._adapt_bytea_arraycslt|t�r|j�dd��fdd�|D��S|sdSt|t�s%|j�|�}|j�|�r4d|j	�
d|�}|S)zAdapt a json array parameter.r@r!c3rAr`rarBrCrardr&rDz,Adapter._adapt_json_array.<locals>.<genexpr>rErrF)r�r��_adapt_json_arrayr'rr.r>rIrrJrKr;rarCrdrSs

zAdapter._adapt_json_arraycCs�|�|���}t|�t|�krtd|��|j}g}t||�D]<\}}|||�}|dur/d}n'|s4d}n"t|t�rCtturB|�	d�}nt|�}|j
�|�rVd|j�
d|�}|�|�qdd	�|�S)
z)Adapt a record parameter with given type.z"Record parameter %s has wrong sizeNr�r�asciirrF�(%s)r!)�get_attnamesr�ryr�r�zipr��bytesrH�decode�_re_record_quoter�_re_record_escaperKrr')rcr#r
rr�r0rarard�
_adapt_record's(


�zAdapter._adapt_recordNcCs�|durdt|t�sd|r|�|�}n	|�|�pd}}t|dd�}|r&||�}|dkr-	|S|dkr>t|t�r<|�||�}|S|�d�rYt|t�rWt|d|dd��}||�}|St|d|�}||�}|S)	z'Adapt a value with known database type.Nr�
__pg_str__�recordz[]z_adapt_%s_array���z	_adapt_%s)	r�r�get_simple_name�guess_simple_type�getattr�tupler\�endswithr�)rcr�r
�simple�pg_strrrarardr?s,�

�
�z
Adapter.adaptcCst|�}||_|S)z9Create a simple database type with given attribute names.)�DbTypere)r�r
rarard�simple_typeWszAdapter.simple_typecCst|t�r|jSt|S)z'Get the simple name of a database type.)r�rgre�_simpletypes�r
rarardr`^s
zAdapter.get_simple_namecCst|t�r|jSiS)z5Get the attribute names of a composite database type.)r�rg�attnamesrjrarardrVes
zAdapter.get_attnamesr�rr�r�rrrKcs�z|jt��WStyYnwt�t�rdSt�t�r dSt�t�r'dSt�ttf�r0dSt�t	�r7dSt�t
�r>dSt�ttt
tf�rIdSt�t�rXd|���pUdfSt�t�rt|j�|j����fd	d
�}�d�}||_|SdS)
z5Try to guess which database type the given value has.r�rr�r�rrrKrcst��fdd�t��D��S)Nc3s,�|]\}}t|d���|��fVqdS)rwN�rH�r��nr#)�guessrhrardr&�s� �zBAdapter.guess_simple_type.<locals>.get_attnames.<locals>.<genexpr>)r��	enumeraterb�rorhr�rardrV�s�z/Adapter.guess_simple_type.<locals>.get_attnamesr^N)�_frequent_simple_types�type�KeyErrorr�r
rr�r��longrrPrKrLrMrNr��guess_simple_base_typercrhra�
_get_attnames)rr�rVr
rarqrdra{s:�






�zAdapter.guess_simple_typecCs:|D]}t|t�r|�|�}n|�|�}|r|SqdS)z,Try to guess the base type of a given array.N)r�r�rvra)rr�r#r
rarardrv�s

��zAdapter.guess_simple_base_typeFcs�|durdSt|t�r
|St|t�r"|j�|�}ttur!|�d�}n t|t�r5|j	r.|�	�S|j�
|�}n
t|ttt
tf�rBt|�}t|t�rQ|j�|�}d|St|t�r\|rZdSdSt|t�rut|�rm|dkrkdSd	St|�rsd
S|St|tttf�r|St|t�r�|j�|r�dnd}|d
��fdd�|D��St|t�r�|j�dd
��fdd�|D��St|dd�}|s�tdt|���|�}t|ttf�r�|�|�}|S)z>Adapt a value that is put into the SQL and needs to be quoted.NrrT�'%s'�true�falserz'-Infinity'z
'Infinity'z'NaN'z[%s]z	ARRAY[%s]r!c3s �|]}t�|dd��VqdS)T)�nestedNrlrBr$rardr&���z'Adapter.adapt_inline.<locals>.<genexpr>rUc3s�|]	}t�|��VqdSr`rlrBr$rardr&����__pg_repr__z Do not know how to adapt type %s)r�rr
r.r,rXrHrYr�encoder>rMrKrLrNrr-r�rrRrQr�rurPr��adapt_inliner'rcrbrrs)rcr�r{r�pg_reprrar$rdr��sX


�






�
zAdapter.adapt_inlinecCst�}|j|_|S)z�Return a parameter list for parameters with known database types.

        The list has an add(value, typ) method that will build up the
        list and return either the literal value or a placeholder.
        )rr�rc�paramsrarard�parameter_list�szAdapter.parameter_listc		s��s|gfS|r�rtd��|��}t�ttf�r`|r(|j��fdd��D�}n.|j��rMt�ttf�r<t��t��kr@td���fdd�t	���D�}n	�fdd��D�}|t|�;}||fSt�t
�r�i}t
��d�}�D]}||=z||Wnty��|||<Ynwd||<qo|�|r�|j�t
�fdd	���
�D��}n,|j��r�t�t
�s�td��t
���fd
d	�t��D��}nt
��fdd	�t��D��}||;}||fStd��)
z9Format a database query using the given values and types.z(Typed parameters must be sent separatelyc�g|]}�|��qSrara�r�r�rCrardr��r�z(Adapter.format_query.<locals>.<listcomp>z!The values and types do not matchcsg|]	\}}�||��qSrara)r�r�r
�rrardr��s�cr�rarar�r�rardr��r�r�c3s �|]\}}|�|�fVqdSr`ra)r�r�r�rCrardr&s��z'Adapter.format_query.<locals>.<genexpr>c3s(�|]}|��|��|��fVqdSr`)rur�)r�typesr�rardr&
s� �c3s �|]}|��|�fVqdSr`rar�)rr�rardr&s��z0The values must be passed as tuple, list or dict)�
ValueErrorr�r�r�rcr�rryr�rWr��fromkeysrtr��sorted)	rc�commandr�r��inliner��literals�used_valuesr�ra)rrr�r�rd�format_query�sd
�
��

�

���zAdapter.format_queryr`�F�NNF)8rkrlrmr��	frozensetr	r3r6r)rIrZrJr[r�r*r5r7r�r9�
_adapt_int�_adapt_float�_adapt_moneyr<r?rG�_adapt_date_arrayrLrM�_adapt_int_array�_adapt_float_array�_adapt_money_arrayrPrSr\rrhr`rVr
rHrXr�r�rurrPrKrLrMrNrrrarvr�r�r�rararardr
�st�







�	



�
#


-
r
cCst�s|S|ddkS)zCast a boolean value.rr0)r0�r�rarard�	cast_boolsr�cCst�}|s|S||�S)zCast a JSON value.)r:)r��castrarard�	cast_jsonsr�cCst�pt|�S)zCast a numeric value.)r3rr�rarard�cast_num'�r�cCsPt�}|s|S|dkr|�|d�}|�dd�}d�dd�|D��}t�p%t|�S)zCast a money value.r
�(r�r�css$�|]
}|��s|dvr|VqdS)z.-N)�isdigit)r��crarardr&4s�"zcast_money.<locals>.<genexpr>)r4r�r'r3r)r��pointrarard�
cast_money,sr�cCsdd�|��D�S)zCast an int2vector value.cS�g|]}t|��qSra�r�rBrarardr�:r�z#cast_int2vector.<locals>.<listcomp>)r	r�rarard�cast_int2vector8�r�cCsh|dkrtjS|dkrtjS|��}|ddkrtjS|d}t|�dkr(tjS|��}t�||���S)zCast a date value.�	-infinity�infinity����BCr�
)rK�min�maxr	ry�date_formatrM�strptime�r��
connection�fmtrarard�	cast_date=sr�cCs$t|�dkrdnd}t�||���S)zCast a time value.r�%H:%M:%S.%f�%H:%M:%S)ryrMr�rL)r�r�rarard�	cast_timeQsr�z(.*)([+-].*)cCsxt�|�}|r|��\}}nd}t|�dkrdnd}tr.|t|�7}|d7}t�||���St�||���j	t
|�d�S)zCast a timetz value.r�rr�r��%z�rO)�_re_timezone�match�groupsry�
_has_timezoner�rMr��timetzr�r�)r�r�r�rarard�cast_timetzZs
�r�cCs�|dkrtjS|dkrtjS|��}|ddkrtjS|��}|�d�rRt|�dkrR|dd�}t|d	�d
kr;tjS|�d�rBdnd
t|d�dkrMdnddg}nt|d�dkr]tjS|t|d�dkrhdndg}t�d�	|�d�	|��S)zCast a timestamp value.r�r�r�r��-%Yrxrwr�r��%d�%d %b�%b %drr�r��%Yrr�� )
rMr�r�r	r�rdryr�r�r'r�rarard�cast_timestampjs&�r�cCs�|dkrtjS|dkrtjS|��}|ddkrtjS|��}|�d�r]t|�dkr]|dd�}t|d	�d
kr;tjS|�d�rBdnd
t|d�dkrMdnddg}|dd�|d}}n>|�d�rwt�	|d�}|rt|�
�\|d<}nd}n|dd�|d}}t|d�dkr�tjS|t|d�dkr�dndg}tr�|�t
|��|�d�t�d�|�d�|��St�d�|�d�|��jt|�d�S)zCast a timestamptz value.r�r�r�r�r�rxrwNrr�r�r�r�rr�r�r�z%Y-r�rr�r�r�r�)rMr�r�r	r�rdryr�r�r�r�r�rr�r�r'r�r�)r�r�r�r�rarard�cast_timestamptz�s@�

�r�zm(?:([+-])?([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)?z�P(?:([+-]?[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�}|�d�dk}dd�|D�}|\}}}}}}}	|r/|}|	}	n�t�|�}|rsdd�|��dd�D�|�d	�}}
|�d�dk}|
rZd
d�|D�ndd�|D�}|\}}}}}}}	|rr|}|	}	n�t�|�}|r�t|���r�dd�|��D�}|�d
�dk}dd�|D�}|\}}}}}}}	|r�|}|}|}|	}	nQt�|�}|r�t|���r�dd�|��D�}|�d�dk}|�d
�dk}dd�|D�}|\}}}}}}}	|r�|}|}|r�|}|}|}|	}	nt	d|��|d|d|7}t
|||||	d�S)zCast an interval value.cS�g|]}|pd�qS��0ra�r��drarardr��r�z!cast_interval.<locals>.<listcomp>r�r�cSr�rar�r�rarardr��r�cSr�r�rar�rarardr��r�Nr�	cSsg|]}t|��qSrar�r�rarardr���cSr�rar�r�rarardr��r�cSr�r�rar�rarardr��r�rcSr�rar�r�rarardr��r�cSr�r�rar�rarardr��r�rcSr�rar�r�rarardr��r�zCannot parse interval: %sim�)r�r�r�r��microseconds)�_re_interval_iso_8601r�r�r��_re_interval_postgres_verbose�group�_re_interval_postgres�any�_re_interval_sql_standardr�rN)
r��m�secs_ago�years�monsr�r��mins�secs�usecs�ago�	hours_ago�	years_agorarard�
cast_interval�sj
�
& �
�
��r�c@seZdZdZide�de�de�de�de�de�de�d	e�d
e�de�de�d
e�de	�de
�de
�de�de�ee
eeeeeeeeeed��ZdZdd�Zedd��Zdd�Zd-dd�Zdd�Zd-dd �Z e!d!d"��Z"e!d#d$��Z#d%d&�Z$d'd(�Z%d)d*�Z&d+d,�Z'dS).ra�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.

    Note that the basic types are already handled by the C extension.
    They only need to be handled here as record or array components.
    �char�bpcharr�r�varcharr�r��int2�int4�serial�int8�oidr�r�jsonb�float4�float8)rrrK�intervalrLr��	timestamp�timestamptz�
int2vectorr��anyarrayr^Ncs�t|t�std|���j�|�}|r��|�}|�|<|S|�d�r8�|dd�}��|�}|r6|�|<|S��|�}|rU�fdd�|�	�D�}��
|||�}|�|<|S)z�Create 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�_rwNcsg|]}�|j�qSra)�pgtyperBrbrardr�/r�z)Typecasts.__missing__.<locals>.<listcomp>)r�rHr��defaultsru�_add_connectionr��create_array_castrVr��create_record_cast)rcr
r��	base_castrk�castsrarbrdrs&


�

�zTypecasts.__missing__c	Cs6zt|�}WnttfyYdSwd|dd�vS)z9Check if a typecast function needs a connection argument.Fr�rwN)r�r�r�)r�r�rarard�_needs_connection4s�zTypecasts._needs_connectioncCs"|jr|�|�s
|St||jd�S)z@Add a connection argument to the typecast function if necessary.)r�)r�r�rW)rcr�rarardr�>szTypecasts._add_connectioncCs||p|S�z6Get the typecast function for the given database type.ra)rcr
�defaultrarardruDr=z
Typecasts.getcCs~t|t�r|g}|dur!|D]}|�|d�|�d|d�qdSt|�s)td��|D]}|�|�||<|�d|d�q+dS)�;Set a typecast function for the specified database type(s).Nr�Cast parameter must be callable)r�rr��callabler�r�)rcr
r�r0rarard�setHs
��z
Typecasts.setcCs>|dur
|��dSt|t�r|g}|D]}|�|d�qdS)z�Reset the typecasts for the specified type(s) to their defaults.

        When no type is specified, all typecasts will be reset.
        N)r�r�rr�)rcr
r0rarard�resetWs
�zTypecasts.resetcCr:)z>Get the default typecast function for the given database type.)r�ru)rr
rarard�get_defaultdszTypecasts.get_defaultcCs~t|t�r|g}|j}|dur$|D]}|�|d�|�d|d�qdSt|�s,td��|D]}|||<|�d|d�q.dS)z?Set a default typecast function for the given database type(s).Nrr)r�rr�r�rr�)rr
r�r�r0rarard�set_defaultis
��zTypecasts.set_defaultcCsiS)z�Return the fields for the given record type.

        This method will be replaced with the get_attnames() method of DbTypes.
        ra�rcr
rarardrVz�zTypecasts.get_attnamescCr)zwReturn the current date format.

        This method will be replaced with the dateformat() method of DbTypes.
        z%Y-%m-%drarbrarard�
dateformat�rzTypecasts.dateformatcs|d���fdd�}|S)z1Create an array typecast for the given base cast.r�cs
�|��Sr`rar8��basecastr(rardr��r�z)Typecasts.create_array_cast.<locals>.castra)rcrr�rar
rdr��szTypecasts.create_array_castcs&|d�t||�����fdd�}|S)z>Create a named record typecast for the given fields and casts.r^cs��|���Sr`rar8�r*r�r^rardr��r�z*Typecasts.create_record_cast.<locals>.castrS)rcr��fieldsr�r�rarrdr��s
zTypecasts.create_record_castr`)(rkrlrmr�rHr�r.r�rur)r�rr�r�r�r�r�r�r�r�r�r[r(r*r�r�rr�r�r�rurrr*rrrVr	r�r�rararardr�sl
���������������

	



rcCs
t�|�S)z@Get the global typecast function for the given database type(s).)rrrjrarard�get_typecast��
rcCst�||�dS)z�Set 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 db.db_types.reset_typecast().
    N)rr)r
r�rarard�set_typecast�src@seZdZdZedd��ZdS)rgaOClass augmenting the simple type name with additional info.

    The following additional information is provided:

        oid: the PostgreSQL type OID
        pgtype: the internal PostgreSQL data type name
        regtype: the registered PostgreSQL data type name
        simple: the more coarse-grained PyGreSQL type name
        typtype: b = base type, c = composite type etc.
        category: A = Array, b = Boolean, C = Composite etc.
        delim: delimiter for array types
        relid: corresponding table for composite types
        attnames: attributes for composite types
    cCs
|�|�S)�6Get names and types of the fields of a composite type.)rwrbrarardrk�s
zDbType.attnamesN)rkrlrmr��propertyrkrararardrg�srgcspeZdZdZed���Z�fdd�Zdd�Zdd�Z	dd
d�Z
dd
�Zdd�Zdd�Z
ddd�Zdd�Z�ZS)�DbTypesz�Cache for PostgreSQL data types.

    This cache maps type OIDs and names to DbType objects containing
    information on the associated database type.
    z>int float num money int2 int4 int8 float4 float8 numeric moneycsZtt|���t�|�|_d|_t�|_|j	|j_	|j|j_
|jdkr(d|_dSd|_dS)z%Initialize type cache for connection.F�:z�SELECT oid, typname, typname::text::regtype, typtype, null as typcategory, typdelim, typrelid FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) %s::regtypez�SELECT oid, typname, typname::regtype, typtype, typcategory, typdelim, typrelid FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) %s::regtypeN)
�superrr�r,r-�_db�	_regtypesr�
_typecastsrVr��server_version�_query_pg_typer/��	__class__rardr��s


��zDbTypes.__init__c
Csn||vr||S|rdnt|}t|jr|n|�}	||	_||	_||	_||	_||	_||	_||	_	||	_
|j|	_|	S)z3Create a PostgreSQL type name with additional info.r^)
rirgrr�rer��regtype�typtype�category�delim�relidrVrw)
rcr�r�rrrr r!rer
rarardr�szDbTypes.addcCs|z|jtd|�f}|j�||f���}Wnty d}Ynw|s)td|��|d}|j|�}|||j<||j	<|S)z8Get the type info from the database if it is not cached.�$1NzType %s could not be foundr)
rrr�query�	getresultrrtrr�r�)rcr�r%rqr
rarardr�s�
zDbTypes.__missing__NcCs"z||WSty|YSw)z&Get the type even if it is not cached.)rt)rcr�r�rarardru�s

�zDbTypes.getcCs8t|t�s|�|�}|sdS|jsdS|jj|jdd�S)rNF)�with_oid)r�rgrur!rrVrrarardrVs

zDbTypes.get_attnamescCr:r�)rrurrarardr
r=zDbTypes.get_typecastcCs|j�||�dS)rN)rr)rcr
r�rarardrr�zDbTypes.set_typecastcCs|j�|�dS)z?Reset the typecast function for the specified database type(s).N)rrrrarard�reset_typecastszDbTypes.reset_typecastcCsT|durdSt|t�s|�|�}|r|j}|r|�|�nd}|r$|tur&|S||�S)z:Cast the given value according to the given database type.N)r�rgrur�rrH)rcr�r
r�rarard�typecasts

zDbTypes.typecastr`)rkrlrmr�r�r	�
_num_typesr�rrrurVrrr&r'�
__classcell__rararrdr�s�


rz^[A-Za-z][_a-zA-Z0-9]*$ir�cCs~z$z
td|dd�jWWSty$dd�t|�D�}td|�jYWSwty>dd�tt|��D�}td|�jYSw)z>Get a namedtuple factory for row results with the given names.�RowT)�renamecSs0g|]\}}t�|�rt|�s|nd|f�qS�z	column_%d)�
_re_fieldnamer�rUrmrarardr�6s
��z _row_factory.<locals>.<listcomp>cSsg|]}d|f�qSr,ra)r�rnrarardr�;r�)rT�_maker�rpr��rangery)�namesrarard�_row_factory/s���r1cCst|�tj�adS)zwChange the size of the namedtuple factory cache.

    If maxsize is set to None, the cache can grow without bound.
    N)r\r1r�r�rarard�set_row_factory_size?sr2ccs(�|��}|D]
}tt||��VqdS)z0Get query result as an iterator of dictionaries.N)�
listfieldsr�rW)r%r
�rrarard�	_dictiterJs
��r5ccs&�t|���}|D]}||�Vq	dS)z0Get query result as an iterator of named tuples.N)r1r3)r%�rowr4rarard�
_namediterQs
��r7cCst|���t|��S)z0Get next row from query result as a named tuple.)r1r3r}r$rarard�
_namednextXsr8ccs�|D]}|dVqdS)z1Get query result as an iterator of scalar values.rNra)r%r4rarard�_scalariter]s��r9c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�_MemoryQueryz)Class that embodies a given query result.cCs||_t|�|_dS)z4Create query from given result rows and field names.N)�resultrcr
)rcr;r
rarardr�fsz_MemoryQuery.__init__cCr�)z,Return the stored field names of this query.)r
rbrarardr3k�z_MemoryQuery.listfieldscCr�)z'Return the stored result of this query.)r;rbrarardr$or<z_MemoryQuery.getresultcCr�r`)r�r;rbrarardr�sr�z_MemoryQuery.__iter__N)rkrlrmr�r�r3r$r�rararardr:csr:cCs||�}d|_|S)z3Return DatabaseError with empty sqlstate attribute.N)�sqlstate)�msgrr�rarard�	_db_errorwsr?cC�
t|t�S)zReturn InternalError.)r?r�r>rarard�
_int_error~rrBcCr@)zReturn ProgrammingError.)r?rrArarard�
_prg_error�rrCc@sPeZdZdZ		ddd�Zdd�Zdd�Zd	d
�Zdd�Zddd�Z	dd�Z
dS)rz;A PostgreSQL client-side asynchronous notification handler.NcCsB||_||_|pd||_d|_||_|duri}||_||_dS)a�Initialize the notification handler.

        You must pass a PyGreSQL database connection, the name of an
        event (notification channel) to listen for and a callback function.

        You can also specify a dictionary arg_dict that will be passed as
        the single argument to the callback function, and a timeout value
        in seconds (a floating point number denotes fractions of seconds).
        If it is absent or None, the callers will never time out.  If the
        timeout is reached, the callback function will be called with a
        single argument that is None.  If you set the timeout to zero,
        the handler will poll notifications synchronously and return.

        You can specify the name of the event that will be used to signal
        the handler to stop listening as stop_event. By default, it will
        be the event name prefixed with 'stop_'.
        zstop_%sFN)r.�event�
stop_event�	listening�callback�arg_dict�timeout)rcr.rDrGrHrIrErarardr��s
zNotificationHandler.__init__cCs|��dSr`)�unlistenrbrarard�__del__�r�zNotificationHandler.__del__cCs&|jr|��|j��d|_dSdS)z(Stop listening and close the connection.N)r.rJ�closerbrarardrL�s


�zNotificationHandler.closecCs8|js|j�d|j�|j�d|j�d|_dSdS)z1Start listening for the event and the stop event.zlisten "%s"TN�rFr.r#rDrErbrarard�listen��

�zNotificationHandler.listencCs8|jr|j�d|j�|j�d|j�d|_dSdS)z0Stop listening for the event and the stop event.z
unlisten "%s"FNrMrbrarardrJ�rOzNotificationHandler.unlistenFcCsB|jr|s|j}d|r|jn|j}|r|d|7}|�|�SdS)a�Generate a notification.

        Optionally, you can pass a payload with the notification.

        If you set the stop flag, a stop notification will be sent that
        will cause the handler to stop listening.

        Note: If the notification handler is running in another thread, you
        must pass a different database connection since PyGreSQL database
        connections are not thread-safe.
        znotify "%s"z, '%s'N)rFr.rErDr#)rcr.�stop�payloadr%rarard�notify�s
�zNotificationHandler.notifycCs�|��|jdk}|s|j��g}|jrv|s!t�|gg|j�drh|jrc|j��}|s,n7|\}}}||j|jfvrH|�	�t
d|j|j|f��||jkrQ|�	�|jj|||d�|�
|j�|js$|rgdSn	|�	�|�
d�|jsdSdS)asInvoke the notification handler.

        The handler is a loop that listens for notifications on the event
        and stop event channels.  When either of these notifications are
        received, its associated 'pid', 'event' and 'extra' (the payload
        passed with the notification) are inserted into its arg_dict
        dictionary and the callback is invoked with this dictionary as
        a single argument.  When the handler receives a stop event, it
        stops listening to both events and return.

        In the special case that the timeout of the handler has been set
        to zero, the handler will poll all events synchronously and return.
        If will keep listening until it receives a stop event.

        Note: If you run this loop in another thread, don't use the same
        database connection for database operations in the main thread.
        rz1Listening for "%s" and "%s", but notified of "%s")�pidrD�extraN)rNrIr.�filenorF�select�	getnotifyrDrErJr?rHr�rG)rc�poll�rlist�noticerDrSrTrarard�__call__�s:


��
��
�zNotificationHandler.__call__)NNNN)NFN)rkrlrmr�r�rKrLrNrJrRr[rararardr�s
�
rcOstjdtdd�t|i|��S)z8Same as NotificationHandler, under the traditional name.z7pgnotify is deprecated, use NotificationHandler insteadrx)�
stacklevel)�warnings�warn�DeprecationWarningrr�rarard�pgnotify
s�r`c@s�eZdZdZdZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Ze
dd��Zdd�Ze
e�Zdd�Zdd�Zdd�Zdd�Zdd �Zd`d!d"�ZeZd#d$�ZeZd`d%d&�ZeZd'd(�Zd)d*�Zd+d,�Zdad.d/�Zd0d1�Z 	-dbd2d3�Z!d4d5�Z"d6d7�Z#d`d8d9�Z$d`d:d;�Z%dcd<d=�Z&d>d?�Z'dad@dA�Z(dddBdC�Z)dedEdF�Z*d`dGdH�Z+dfdJdK�Z,d`dLdM�Z-d`dNdO�Z.d`dPdQ�Z/d`dRdS�Z0d`dTdU�Z1d`dVdW�Z2dgdXdY�Z3		-dhdZd[�Z4		-did\d]�Z5	djd^d_�Z6dS)kr	z*Wrapper class for the _pg connection type.NcOs|st|�dkr|�d�}n|st|�dkr|d}nd}|r7t|t�r(|j}nz|j}Wn	ty6Ynw|rCt|d�rCt|d�sSt|i|��}||f|_	d|_
n||_	d|_
||_|j|_d|_i|_
i|_i|_t|�|_t|�|_|jdkrd	|_nd
|_|�|jj�d|_dS)z�Create a new connection

        You can pass either the connection parameters or an existing
        _pg or pgdb connection. This allows you to use the methods
        of the classic pg interface with a DB-API 2 pgdb connection.
        rwr.rNr#TFra=SELECT a.attname, t.oid, t.typname, t.typname::text::regtype, t.typtype, null as typcategory, t.typdelim, t.typrelid FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_type t ON t.oid OPERATOR(pg_catalog.=) a.atttypid WHERE a.attrelid OPERATOR(pg_catalog.=) %s::regclass AND %s AND NOT a.attisdropped ORDER BY a.attnuma1SELECT a.attname, t.oid, t.typname, t.typname::regtype, t.typtype, t.typcategory, t.typdelim, t.typrelid FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_type t ON t.oid OPERATOR(pg_catalog.=) a.atttypid WHERE a.attrelid OPERATOR(pg_catalog.=) %s::regclass AND %s AND NOT a.attisdropped ORDER BY a.attnum)ryrur�r	r.�_cnx�AttributeError�hasattrr+�_db_args�
_closeable�dbnamer�	_attnames�_pkeys�_privilegesr
�adapterr�dbtypesr�_query_attnames�
set_cast_hookr'�debug)rcr�r�r.rarardr�sD


�



�
�
zDB.__init__cCs|jr	t|j|�Std��)N�Connection is not valid)r.rbrB�rcr�rarard�__getattr__VszDB.__getattr__cCs0t|jj�}|�|j�|�t|j��t|�Sr`)rr�__dict__r��dirr.r�)rc�attrsrarard�__dir__]sz
DB.__dir__cCs|��|S)z9Enter the runtime context. This will start a transaction.)�beginrbrarardrefszDB.__enter__cCs0|dur|dur|dur|��dS|��dS)z8Exit the runtime context. This will end the transaction.N)�commit�rollback)rc�et�ev�tbrarardrjkszDB.__exit__cCszz|j}Wntyd}Ynw|r9z|�d�Wn	ty#Ynw|jr;z|��WdSty8YdSwdSdSr`)r.rbrmr�rerLrr/rarardrKrs&
����z
DB.__del__cGs�|jr>d�dd�|D��}t|jt�rt|j|�dSt|jd�r,|j�|d�dSt|j�r8|�|�dSt|�dSdS)zPrint a debug message�
css�|]}t|�VqdSr`rl)r�rprarardr&�rDzDB._do_debug.<locals>.<genexpr>�writeN)rnr'r�r�printrcr}r)rcr�rrarard�	_do_debug�s
�zDB._do_debugcCsd|vr	|�|�}|S)aEscape a qualified name.

        Escapes the name for use as an SQL identifier, unless the
        name contains a dot, in which case the name is ambiguous
        (could be a qualified name or just a name with a dot in it)
        and must be quoted manually by the caller.
        r
)�escape_identifier�rcrrarard�_escape_qualified_name�s
zDB._escape_qualified_namecCst�rt|�S|rdSdS)z%Get boolean value corresponding to d.r0r1)r0r�)r�rarard�
_make_bool�sz
DB._make_boolcCsd�dd�t|d�D��S)z'Create a human readable parameter list.�, css �|]\}}d||fVqdS)z$%d=%rNrarmrarardr&�r|z"DB._list_params.<locals>.<genexpr>rw)r'rpr�rarard�_list_params�szDB._list_paramscCst�pt|�S)z.Decode a JSON string coming from the database.)r:�
jsondecoder�rarard�decode_json�r�zDB.decode_jsoncCst|�S)z(Encode a JSON string for use within SQL.)�
jsonencode)rcr�rarardr>�r�zDB.encode_jsoncCsL|j}|r"z|�d�Wn	tyYnw|jr|��d|_dStd��)zClose the database connection.N�Connection already closed)r.rmr�rerLrBr/rarardrL�s�
zDB.closecCs|jr
|j��dStd��)z�Reset connection with current parameters.

        All derived queries and large objects derived from this connection
        will not be usable after this call.

        r�N)r.rrBrbrarardr�szDB.resetcCs`|jr*t|jdi|jd��}|jr|j�d�|j��|�|jj�||_dS|j|_dS)z�Reopen connection to the database.

        Used in case we need another connection to the same database.
        Note that we can still reopen a database that we have closed.

        rrwN)rer+rdr.rmrLrkr'r/rarard�reopen�s

z	DB.reopencC�d}|r
|d|7}|�|�S)zBegin a transaction.�BEGINr��r#)rc�mode�qstrrarardrv��
zDB.begincCs
|�d�S)zCommit the current transaction.�COMMITr�rbrarardrw�rz	DB.commitcCr�)z"Roll back the current transaction.�ROLLBACKz TO r�)rcr�r�rarardrx�r�zDB.rollbackcC�|�d|�S)z6Define a new savepoint within the current transaction.z
SAVEPOINT r�rprarard�	savepoint�r�zDB.savepointcCr�)z'Destroy a previously defined savepoint.zRELEASE r�rprarard�release�r�z
DB.releasecCsVt|t�r|g}d}n t|ttf�rg}nt|ttf�ri}nt|t�r'|}ntd��|s1td��t|t�r8ing}|D]>}t|t�rI|���	�nd}|sQtd��|dkrkd}|j
�|���}tdd�|D��}|St|t�ru|||<q<|�
|�q<|D]+}d	|f}|j
�|���d
d
}|dur�|}q}t|t�r�|�
|�q}||||<q}|S)a/Get the value of a run-time parameter.

        If the parameter is a string, the return value will also be a string
        that is the current setting of the run-time parameter with that name.

        You can get several parameters at once by passing a list, set or dict.
        When passing a list of parameter names, the return value will be a
        corresponding list of parameter settings.  When passing a set of
        parameter names, a new dict will be returned, mapping these parameter
        names to their settings.  Finally, if you pass a dict as parameter,
        its values will be set to the current parameter settings corresponding
        to its keys.

        By passing the special name 'all' as the parameter, you can get a dict
        of all existing configuration parameters.
        N�1The parameter must be a string, list, set or dict�No parameter has been specified�Invalid parameter�allzSHOW ALLcss�|]	}|dd�VqdS)Nrxrar�rarardr&)r}z#DB.get_parameter.<locals>.<genexpr>zSHOW %sr)r�rr�rcrr�r�r��stripr2r.r#r$r)rc�	parameterr�r�r�rr%r�rarard�
get_parametersR

���
�


zDB.get_parameterFcCs�t|t�r
||i}nat|ttf�r't|ttf�r tt||��}nKt�||�}nDt|ttf�rYt|ttttf�rEt|�}t	|�dkrE|�
�}|dusRt|t�sRtd��t�||�}nt|t�rg|durftd��ntd��|sqtd��i}|�
�D]-\}}t|t�r�|����nd}|s�td��|dkr�|dur�td	��ddi}n|||<qw|r�d
nd}|�
�D]!\}}|dur�d||f}nd
|||f}|�|�|j�|�q�dS)a�Set the value of a run-time parameter.

        If the parameter and the value are strings, the run-time parameter
        will be set to that value.  If no value or None is passed as a value,
        then the run-time parameter will be restored to its default value.

        You can set several parameters at once by passing a list of parameter
        names, together with a single value that all parameters should be
        set to or with a corresponding list of values.  You can also pass
        the parameters as a set if you only provide a single value.
        Finally, you can pass a dict with parameter names as keys.  In this
        case, you should not pass a value, since the values for the parameters
        will be taken from the dict.

        By passing the special name 'all' as the parameter, you can reset
        all existing settable run-time parameters to their default values.

        If you set local to True, then the command takes effect for only the
        current transaction.  After commit() or rollback(), the session-level
        setting takes effect again.  Setting local to True will appear to
        have no effect if it is executed outside a transaction, since the
        transaction will end immediately.
        rwNz8A single value must be specified when parameter is a setz<A value must not be specified when parameter is a dictionaryr�r�r�r�z4A value must ot be specified when parameter is 'all'z LOCALr�z
RESET%s %szSET%s %s TO %s)r�rr�rcr�rWr�rr�ryr�r�r�r�r�r2rr.r#)rcr�r��localr�r�rr%rarard�
set_parameter;s\


����

�zDB.set_parametercGsB|jstd��|r|�||�|j�||�S|�|�|j�|�S)a;Execute a SQL command string.

        This method simply sends a SQL query to the database.  If the query is
        an insert statement that inserted exactly one row into a table that
        has OIDs, the return value is the OID of the newly inserted row.
        If the query is an update or delete statement, or an insert statement
        that did not insert exactly one row in a table with OIDs, then the
        number of rows affected is returned as a string.  If it is a statement
        that returns rows as a result (usually a select statement, but maybe
        also an "insert/update ... returning" statement), this method returns
        a Query object that can be accessed via getresult() or dictresult()
        or simply printed.  Otherwise, it returns `None`.

        The query can contain numbered parameters of the form $1 in place
        of any data constant.  Arguments given after the query string will
        be substituted for the corresponding numbered parameter.  Parameter
        values can also be given as a single list or tuple argument.
        ro)r.rBrr#)rcr�r�rarardr#�s
zDB.querycCs|j|j�||||��S)aDExecute a formatted SQL command string.

        Similar to query, but using Python format placeholders of the form
        %s or %(names)s instead of PostgreSQL placeholders of the form $1.
        The parameters must be passed as a tuple, list or dict.  You can
        also pass a corresponding tuple, list or dict of database types in
        order to format the parameters properly in case there is ambiguity.

        If you set inline to True, the parameters will be sent to the database
        embedded in the SQL command, otherwise they will be sent separately.
        )r#rjr�)rcr�r�r�r�rarard�query_formatted�s

�zDB.query_formattedcGsR|jstd��|dur
d}|r|�d||�|j�||�S|�d|�|j�|�S)aExecute a prepared SQL statement.

        This works like the query() method, except that instead of passing
        the SQL command, you pass the name of a prepared statement.  If you
        pass an empty name, the unnamed statement will be executed.
        roNr��EXECUTE)r.rBr�query_prepared)rcr�r�rarardr��szDB.query_preparedcCs6|jstd��|dur
d}|�d||�|j�||�S)aoCreate a prepared SQL statement.

        This creates a prepared statement for the given command with the
        given name for later execution with the query_prepared() method.

        The name can be empty to create an unnamed statement, in which case
        any pre-existing unnamed statement is automatically replaced;
        otherwise it is an error if the statement name is already
        defined in the current database session. We recommend always using
        named queries, since unnamed queries have a limited lifetime and
        can be automatically replaced or destroyed by various operations.
        roNr��prepare)r.rBrr�)rcr�r�rarardr��s
z
DB.preparecCs|durd}|j�|�S)a
Describe a prepared SQL statement.

        This method returns a Query object describing the result columns of
        the prepared statement with the given name. If you omit the name,
        the unnamed statement will be described if you created one before.
        Nr�)r.�describe_preparedrprarardr��szDB.describe_preparedcCs$d|pdf}|�|�|j�|�S)a8Delete a prepared SQL statement

        This deallocates a previously prepared SQL statement with the given
        name, or deallocates all prepared statements if you do not specify a
        name. Note that prepared statements are also deallocated automatically
        when the current session ends.
        z
DEALLOCATE %s�ALL)rr.r#)rcr�r%rarard�delete_prepared�s
zDB.delete_preparedcs�|j}|r|��|�d�z||}WnMtyadtd|�f}|j�||f���}|s5td|��t|�dkrU|dd�t	|�fdd	�d
�}t
dd�|D��}n|dd}|||<Ynw|rlt|t
�sl|f}|S)
a�Get or set the primary key of a table.

        Single primary keys are returned as strings unless you
        set the composite flag.  Composite primary keys are always
        represented as tuples.  Note that this raises a KeyError
        if the table does not have a primary key.

        If flush is set then the internal cache for primary keys will
        be flushed.  This may be necessary after the database schema or
        the search path has been changed.
        zThe pkey cache has been flusheda1SELECT a.attname, a.attnum, i.indkey FROM pg_catalog.pg_index i JOIN pg_catalog.pg_attribute a ON a.attrelid OPERATOR(pg_catalog.=) i.indrelid AND a.attnum OPERATOR(pg_catalog.=) ANY(i.indkey) AND NOT a.attisdropped WHERE i.indrelid OPERATOR(pg_catalog.=) %s::regclass AND i.indisprimary ORDER BY a.attnumr"�Table %s has no primary keyrwrrxcs��|d�S)Nrw)�index�r6��indkeyrard�<lambda>
szDB.pkey.<locals>.<lambda>)r�css�|]}|dVqdS)rNra�r�r6rarardr&rDzDB.pkey.<locals>.<genexpr>)rhr�rrtrr.r#r$ryr�rcr�)rcr��	composite�flush�pkeys�pkeyr%rar�rdr��s0
��	�zDB.pkeycCsdd�|j�d���D�S)z$Get list of databases in the system.cSr�r�ra)r�rrarardr�r�z$DB.get_databases.<locals>.<listcomp>z*SELECT datname FROM pg_catalog.pg_database)r.r#r$rbrarard�
get_databasess��zDB.get_databasescCslg}|r|�dd�dd�|D���|s|�d�|r#dd�|�nd}d	|}d
d�|j�|���D�S)a`Get list of relations in connected database of specified kinds.

        If kinds is None or empty, all kinds of relations are returned.
        Otherwise kinds can be a string or sequence of type letters
        specifying which kind of relations you want to list.

        Set the system flag if you want to get the system relations as well.
        zr.relkind IN (%s)r!css�|]}d|VqdS)rxNra�r�r"rarardr&(rDz#DB.get_relations.<locals>.<genexpr>z?s.nspname NOT SIMILAR TO 'pg/_%|information/_schema' ESCAPE '/'z	 WHERE %s� AND r�aSELECT pg_catalog.quote_ident(s.nspname) OPERATOR(pg_catalog.||) '.' OPERATOR(pg_catalog.||) pg_catalog.quote_ident(r.relname) FROM pg_catalog.pg_class r JOIN pg_catalog.pg_namespace s ON s.oid OPERATOR(pg_catalog.=) r.relnamespace%s ORDER BY s.nspname, r.relnamecSr�r�ra)r�r4rarardr�3r�z$DB.get_relations.<locals>.<listcomp>)rr'r.r#r$)rc�kinds�system�wherer%rarard�
get_relationss	�
�zDB.get_relationscCs|�d|�S)z�Return list of tables in connected database.

        Set the system flag if you want to get the system tables as well.
        r4)r�)rcr�rarard�
get_tables5sz
DB.get_tablesTcs�|j}|r|��|�d�z||}W|StyOd}|r$d|}|jtd|�|f}|j�||f���}|j	��fdd�|D�}t
|�}|||<Y|Sw)atGiven the name of a table, dig out the set of attribute names.

        Returns a read-only dictionary of attribute names (the names are
        the keys, the values are the names of the attributes' types)
        with the column names in the proper order if you iterate over it.

        If flush is set, then the internal cache for attribute names will
        be flushed. This may be necessary after the database schema or
        the search path has been changed.

        By default, only a limited number of simple types will be returned.
        You can get the registered types after calling use_regtypes(True).
        z#The attnames cache has been flushedz!a.attnum OPERATOR(pg_catalog.>) 0z.(%s OR a.attname OPERATOR(pg_catalog.=) 'oid')r"c3s*�|]}|d�j|dd��fVqdS)rrwNr�)r�r��r�rardr&Ws�(z"DB.get_attnames.<locals>.<genexpr>)rgr�rrtrlrr.r#r$rkr�)rcr�r%r�rkr0r%rar�rdrV<s&

�
�zDB.get_attnamescCsD|dur|jjSt|�}||jjkr ||j_|j��|j��|S)z;Use registered type names instead of simplified type names.N)rkrr�rgr�)rc�regtypesrarard�use_regtypes\s

zDB.use_regtypesrVcCs�|j}|r|��|�d�|��}z	|||f}W|StyIdtd|�f}|j�|||f�}|��dd|�	d�k}||||f<Y|Sw)z�Check whether current user has specified table privilege.

        If flush is set, then the internal cache for table privileges will
        be flushed. This may be necessary after privileges have been changed.
        z%The privileges cache has been flushedz-SELECT pg_catalog.has_table_privilege(%s, $2)r"rT)
rir�rr2rtrr.r#r$r�)rcr��	privileger��
privileges�retr%rarard�has_table_privilegehs"
���zDB.has_table_privilegecs0|�d�r
|dd���}|�|��d�vrt|�nd}|r&t|t�r&|f}|r;t�t�r;|�vr;d�vr;�|�d<|s|z|�|d�}Wntyb|rZt�t�rZd�vrZd}nt	d|��Ynwt�t�r|t
|����s||rxd�vrxd}ntd��t�t�s�t�tt
f�s��g�t|�t��kr�td	��tt|����|j��}|j�|j�|r�d
nd}d�����fdd
�|D��}d�vr�|rʈd�|<�d=d||�|�|f}|�||�|j�||�}|��}	|	s�|�dd�}td|||�|�f��|	d��D]\}
}|�r|
dk�r|}
|�|
<�q�S)a�Get a row from a database table or view.

        This method is the basic mechanism to get a single row.  It assumes
        that the keyname specifies a unique row.  It must be the name of a
        single column or a tuple of column names.  If the keyname is not
        specified, then the primary key for the table is used.

        If row is a dictionary, then the value for the key is taken from it.
        Otherwise, the row must be a single value or a tuple of values
        corresponding to the passed keyname or primary key.  The fetched row
        from the table will be returned as a new dictionary or used to replace
        the existing values when row was passed as a dictionary.

        The OID is also put into the dictionary if the table has one, but
        in order to allow the caller to work with multiple tables, it is
        munged as "oid(table)" using the actual name of the table.
        rNr�r�T�r�r�z*Missing value in row for specified keynamez,Differing number of items in keyname and row�oid, *r�c3�.�|]}d�|���|�|�fVqdS�z%s OPERATOR(pg_catalog.=) %sNrar��rrk�colr6rardr&�����zDB.get.<locals>.<genexpr>z"SELECT %s FROM %s WHERE %s LIMIT 1zOPERATOR(pg_catalog.=)�=z%No such record in %s
where %s
with %sr)rd�rstriprVr�r�rr�r�rtrCr�issubsetrcr�ryrWrjr�rr�r'r�rr.r#�
dictresultr�r?r�r�)rcr�r6�keyname�qoidr��whatr�r%rqrnr�rar�rdru}st

���
�
���zDB.getcKsP|�d�r
|dd���}|duri}|�|�d|vr|d=|�|�}d|vr,t|�nd}|j��}|j}|j}gg}	}
|D]}||vrY|	�	||��|
�	|||||��q@|	s`t
d��d�|	�d�|
�}	}
|rodnd}d|�|�|	|
|f}
|�
|
|�|j�|
|�}
|
��}|r�|d	��D]\}}|r�|dkr�|}|||<q�|S)
adInsert a row into a database table.

        This method inserts a row into a table.  The name of the table must
        be passed as the first parameter.  The other parameters are used for
        providing the data of the row that shall be inserted into the table.
        If a dictionary is supplied as the second parameter, it starts with
        that.  Otherwise it uses a blank dictionary. Either way the dictionary
        is updated from the keywords.

        The dictionary is then reloaded with the values actually inserted in
        order to pick up values modified by rules, triggers, etc.
        rNr�r�z$No column found that can be insertedr�r�z,INSERT INTO %s (%s) VALUES (%s) RETURNING %sr)rdr�r�rVr�rjr�rr�rrCr'r�rr.r#r�r�)rcr�r6r�rkr�r�rr�r0r�rnr�r%rqr�rarard�insert�sD





��
z	DB.insertc	s�|�d�r
|dd���}|�|��d�vrt|�nd}�dur#i�nd�vr*�d=��|�|r?|�vr?d�vr?�|�d<|rHd�vrHd}n!z|�|d�}Wn
ty]td|��wt|��	��sitd��|j
��}|j�|j
�d	�����fd
d�|D��}d�vr�|r��d�|<�d=g}t|�}�D]}	|	�vr�|	|vr�|�d�|	���|	�|	�f�q�|s��Sd
�|�}|r�dnd}
d|�|�|||
f}|�||�|j�||�}|��}|r�|d��D]\}	}
|r�|	dkr�|}	|
�|	<q�S)a�Update an existing row in a database table.

        Similar to insert, but updates an existing row.  The update is based
        on the primary key of the table or the OID value as munged by get()
        or passed as keyword.  The OID will take precedence if provided, so
        that it is possible to update the primary key itself.

        The dictionary is then modified to reflect any changes caused by the
        update due to triggers, rules, default values, etc.
        rNr�r�r�Tr��$Missing value for primary key in rowr�c3r�r�rar�r�rardr&	r�zDB.update.<locals>.<genexpr>�%s = %sr�r�z&UPDATE %s SET %s WHERE %s RETURNING %sr)rdr�rVr�r�r�rtrCrr�rjr�rr�r'rr�rr.r#r�r�)rcr�r6r�r�r�r�r�r�rnr�r%rqr�rar�rdr��sh


�
�$�
�
z	DB.updatecs\|�d�r
|dd���}|duri}d|vr|d=d|vr!|d=|�|�}d|vr.t|�nd}|j��}|j}|j�ggg}}	}
|D]}||vr^|��|��|	�|||||��qEd�	|�d�	|	�}}	z|�
|d�}Wn
tytd|��wd�	�fdd	�|D��}
g}t
|�}|�d�|D]$}||vr�|�|d�}|r�t|t�s�d
�|�}|�d�|�|f�q�|	s�|S|r�dd�	|�nd
}|r�dnd}d|�|�||	|
||f}|�||�z	|j�||�}Wnt�y|jdk�rtd���w|��}|�r&|d��D]\}}|�r|dk�r|}|||<�q|S|�||�|S)a�Insert a row into a database table with conflict resolution

        This method inserts a row into a table, but instead of raising a
        ProgrammingError exception in case a row with the same primary key
        already exists, an update will be executed instead.  This will be
        performed as a single atomic operation on the database, so race
        conditions can be avoided.

        Like the insert method, the first parameter is the name of the
        table and the second parameter can be used to pass the values to
        be inserted as a dictionary.

        Unlike the insert und update statement, keyword parameters are not
        used to modify the dictionary, but to specify which columns shall
        be updated in case of a conflict, and in which way:

        A value of False or None means the column shall not be updated,
        a value of True means the column shall be updated with the value
        that has been proposed for insertion, i.e. has been passed as value
        in the dictionary.  Columns that are not specified by keywords but
        appear as keys in the dictionary are also updated like in the case
        keywords had been passed with the value True.

        So if in the case of a conflict you want to update every column that
        has been passed in the dictionary row, you would call upsert(table, row).
        If you don't want to do anything in case of a conflict, i.e. leave
        the existing row as it is, call upsert(table, row, **dict.fromkeys(row)).

        If you need more fine-grained control of what gets updated, you can
        also pass strings in the keyword parameters.  These strings will
        be used as SQL expressions for the update columns.  In these
        expressions you can refer to the value that already exists in
        the table by prefixing the column name with "included.", and to
        the value that has been proposed for insertion by prefixing the
        column name with the "excluded."

        The dictionary is modified in any case to reflect the values in
        the database after the operation has completed.

        Note: The method uses the PostgreSQL "upsert" feature which is
        only available since PostgreSQL 9.5.
        rNr�r�r�Tr�c3rAr`rar��r�rardr&x	rDzDB.upsert.<locals>.<genexpr>zexcluded.%sr�z
update set %s�nothingr�zOINSERT INTO %s AS included (%s) VALUES (%s) ON CONFLICT (%s) DO %s RETURNING %si�az7Upsert operation is not supported by PostgreSQL versionr)rdr�rVr�rjr�rr�rr'r�rtrCrrur�rr�rr.r#rrr�r�)rcr�r6r�rkr�r�rr0r��updatesrnr��targetr�r��dor�r%rqrar�rd�upsert6	s�
+

��

������z	DB.upsertcCsp|duri}|�|�}|��D]&\}}|dkrq|j}|tjvr%d||<q|dkr1|�d�||<qd||<q|S)ahClear all the attributes to values determined by the types.

        Numeric types are set to 0, Booleans are set to false, and everything
        else is set to the empty string.  If the row argument is present,
        it is used as the row dictionary and any entries matching attribute
        names are cleared with everything else left unchanged.
        Nr�rr�Fr�)rVr�rerr(r�)rcr�r6rkrnr0rarardr��	s	



zDB.clearc
sX|�d�r
|dd���}|�|��d�vrt|�nd}�dur#i�nd�vr*�d=��|�|r?|�vr?d�vr?�|�d<|rHd�vrHd}n!z|�|d�}Wn
ty]td|��wt|��	��sitd��|j
��}|j�|j
�d	�����fd
d�|D��}d�vr�|r��d�|<�d=d|�|�|f}|�||�|j�||�}	t|	�S)
a#Delete an existing row in a database table.

        This method deletes the row from a table.  It deletes based on the
        primary key of the table or the OID value as munged by get() or
        passed as keyword.  The OID will take precedence if provided.

        The return value is the number of deleted rows (i.e. 0 if the row
        did not exist and 1 if the row was deleted).

        Note that if the row cannot be deleted because e.g. it is still
        referenced by another table, this method raises a ProgrammingError.
        rNr�r�r�Tr�r�r�c3r�r�rar�r�rardr&�	r�zDB.delete.<locals>.<genexpr>zDELETE FROM %s WHERE %s)rdr�rVr�r�r�rtrCrr�rjr�rr�r'r�rr.r#r�)
rcr�r6r�r�r�r�r�r%rqrar�rd�delete�	sH



�
�
�z	DB.deletec	Cszt|t�r
||i}|g}n/t|ttf�r*t|ttf�r#tt||��}nt�||�}nt|ttf�r8t�||�}nt	d��|dusKt|t
tf�sKt	d��|dusZt|t
tf�sZt	d��g}|D]9}|�|�}|dustt|t
tf�stt	d��|�
d�r�|rtd��|dd���}|�|�}|r�d	|}|�|�q^d
d�|�g}|r�|�d�|r�|�d
�d�|�}|�|�|j�|�S)a�Empty a table or set of tables.

        This method quickly removes all rows from the given table or set
        of tables.  It has the same effect as an unqualified DELETE on each
        table, but since it does not actually scan the tables it is faster.
        Furthermore, it reclaims disk space immediately, rather than requiring
        a subsequent VACUUM operation. This is most useful on large tables.

        If restart is set to True, sequences owned by columns of the truncated
        table(s) are automatically restarted.  If cascade is set to True, it
        also truncates all tables that have foreign-key references to any of
        the named tables.  If the parameter only is not set to True, all the
        descendant tables (if any) will also be truncated. Optionally, a '*'
        can be specified after the table name to explicitly indicate that
        descendant tables are included.
        z'The table must be a string, list or setNz#Invalid type for the restart optionz#Invalid type for the cascade optionz Invalid type for the only optionrz)Contradictory table name and only optionsr�zONLY %s�TRUNCATEr�zRESTART IDENTITY�CASCADEr�)r�rr�rcr�rWr�rr�r�r�r�rurdr�r�r�rr'rr.r#)	rcr��restart�cascade�only�tablesr0�ur%rarard�truncate�	sJ


�




zDB.truncatec
Csl|std��|rt|ttf�rd�tt|��}|dur|}nd}d|d|g}|r>t|ttf�r7d�tt|��}|�d|g�|durkz|�|d	�}Wn t	t
fyjz	t|�|��}Wnt	t
fygYnwYnw|r�t|ttf�r|d�tt|��}|�d
|g�|r�|�d|�|r�|�d|�d
�|�}|�
|�|j�|�}|��}	|	r�|r�dd�|	D�}	|	S)a�Get a table as a list.

        This gets a convenient representation of the table as a list
        of named tuples in Python.  You only need to pass the name of
        the table (or any other SQL expression returning rows).  Note that
        by default this will return the full content of the table which
        can be huge and overflow your memory.  However, you can control
        the amount of data returned using the other optional parameters.

        The parameter 'what' can restrict the query to only return a
        subset of the table columns.  It can be a string, list or a tuple.
        The parameter 'where' can restrict the query to only return a
        subset of the table rows.  It can be a string, list or a tuple
        of SQL expressions that all need to be fulfilled.  The parameter
        'order' specifies the ordering of the rows.  It can also be a
        other string, list or a tuple.  If no ordering is specified,
        the result will be ordered by the primary key(s) or all columns
        if no primary key exists.  You can set 'order' to False if you
        don't care about the ordering.  The parameters 'limit' and 'offset'
        can be integers specifying the maximum number of rows returned
        and a number of rows skipped over.

        If you set the 'scalar' option to True, then instead of the
        named tuples you will get the first items of these tuples.
        This is useful if the result has only one column anyway.
        �The table name is missingr�Nr�SELECT�FROMr��WHERET�ORDER BY�LIMIT %d�	OFFSET %dr�cSr�r�rar�rarardr�]
r�z"DB.get_as_list.<locals>.<listcomp>)r�r�r�rcr'�maprH�extendr�rtrrVrrr.r#�namedresult)
rcr�r�r��order�limitr��scalarr%rqrarard�get_as_list
sP����

zDB.get_as_listc		s�|std��|s z|�|d�}Wnttfytd|��wt|t�r)|g}nt|ttf�s4td��|rLt|ttf�rEd�	t
t|��}|durK|}nd}d|d	|g}	|rlt|ttf�red
�	t
t|��}|	�d|g�|durr|}|r�t|ttf�r�d�	t
t|��}|	�d|g�|r�|	�
d
|�|r�|	�
d|�d�	|	�}	|�|	�|j�|	�}	|	��}
|r�tnt}|
s�|�St|��|	��}��|�s�td��gg}
�t|�D]\}}|�vr�|
n��
|�q�t|
�dk}t|
�}t
||
�}|r��dd��d}nt��dk}|�s|�rt��}n�d��fdd�}d}t
||
�}|�s'|�rD|�r1tt||��}|�rD�fdd�|D�}tt||��}|t||��S)a-Get a table as a dictionary.

        This method is similar to get_as_list(), but returns the table
        as a Python dict instead of a Python list, which can be even
        more convenient. The primary key column(s) of the table will
        be used as the keys of the dictionary, while the other column(s)
        will be the corresponding values.  The keys will be named tuples
        if the table has a composite primary key.  The rows will be also
        named tuples unless the 'scalar' option has been set to True.
        With the optional parameter 'keyname' you can specify an alternative
        set of columns to be used as the keys of the dictionary.  It must
        be set as a string, list or a tuple.

        If the Python version supports it, the dictionary will be an
        OrderedDict using the order specified with the 'order' parameter
        or the key column(s) if not specified.  You can set 'order' to False
        if you don't care about the ordering.  In this case the returned
        dictionary will be an ordinary one.
        r�Tr�z+The keyname must be a string, list or tupler�Nrr�r�r�r�r�r�r�r�zMissing keyname in rowrwFrcs
|�fSr`rar�)�rowindrardr��
s
z DB.get_as_dict.<locals>.<lambda>csg|]}|�vr|�qSrara)r�r1)�keysetrardr��
r�z"DB.get_as_dict.<locals>.<listcomp>)r�r�rtrrCr�rr�rcr'r�rHr�rrr.r#r$r�r�rr3r�rpryrVr7r:rW)rcr�r�r�r�r�r�r�r�r%rqrr
�keyind�ir1�keytuple�getkeyr��rowtuple�getrow�rowsra)r�r�rd�get_as_dict`
s��
�






zDB.get_as_dictcCst||||||�S)z:Get notification handler that will run the given callback.)r)rcrDrGrHrIrErarard�notification_handler�
s
�zDB.notification_handlerr`)NFr�)FFr�)TF)rVF)FFF)NNNNNF)NNNNNNF)NNN)7rkrlrmr�r.r�rqrurerjrKrr�r�r�r�r.r�r>rLrr�rv�startrw�endrx�abortr�r�r�r�r#r�r�r�r�r�r�r�r�r�rVr�r�rur�r�r�r�r�r�r�r�r�rararardr	sv>	




:G
�


,



 


M
.
>
g

18
�B
�\�r	�__main__zPyGreSQL versionr�)rn)�r��
__future__rr�_pg�ImportError�os�sysr��version_info�environr	�pathsep�path�existsr'�add_dll_directory�abspathrIrJ�__all__rVr]r,rMrKrLrNrO�decimalrP�mathrQrR�collectionsrT�keywordrU�operatorrV�	functoolsrW�rerXr)rrYr�rZr�r�r[ru�	NameErrorr�rrHrXr\r]�_threadr^r�r�r��inspectr�r�r�r��utcr�r�r�r�r�r�rirr�rr
rrrr
r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrgrr-r1r2r5r7r8r9r:rr?rBrCr?rGrHr�rr`r	rkr~rararard�<module>s<
	
���������T�:���
k%����	;	m
y	
:�

https://t.me/RX1948 - 2025