o
    `ZhG                     @   s  d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZ ddl
mZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ zzddlZW n eyd   ddlZY nw W n eyq   e	dw dd Ze dk re	dej  de   krdk rn ne	dej  ddl!m"Z"m#Z# e#rddlm$Z$m%Z% ddl&m'Z' ddl!m(Z(m)Z) e$j*d j+Z,n)ddl-Zddl.Zej/0eej/j1 ej23  dZ4ej/5e4fdej/j6Z7ej/8e7 ddl9m:Z: ddl;m<Z< dd l=m>Z> dd!l?m@Z@ dd"lAmBZB dd#lCmDZD d$d% ZEG d&d' d'eZFe#r@G d(d) d)ZGG d*d+ d+eGejHZIG d,d- d-eGejJZHG d.d/ d/eZdS ej/jKZHG d0d/ d/eZdS )1zY
PostgreSQL database backend for Django.

Requires psycopg2 >= 2.8.4 or psycopg >= 3.1.8
    N)contextmanager)settings)ImproperlyConfigured)DatabaseError)connections)BaseDatabaseWrapperCursorDebugWrapper)async_unsafe)cached_property)
SafeString)get_version_tuplez(Error loading psycopg2 or psycopg modulec                  C   s   t jddd } t| S )N    r   )Database__version__splitr   )version r   Y/var/www/html/lang_env/lib/python3.10/site-packages/django/db/backends/postgresql/base.pypsycopg_version    s   r   )         z6psycopg2 version 2.8.4 or newer is required; you have )   )r   r   r   z5psycopg version 3.1.8 or newer is required; you have r   )IsolationLevelis_psycopg3)adapterssql)Format)get_adapters_templateregister_tzloaderZtimestamptzi  	INETARRAY)DatabaseClient)DatabaseCreation)DatabaseFeatures)DatabaseIntrospection)DatabaseOperations)DatabaseSchemaEditorc                 C   s   | d d u rdS d|  S )N
max_lengthZvarcharvarchar(%(max_length)s)r   )datar   r   r   _get_varchar_columnS   s   r,   c                       s  e Zd ZdZdZi ddddddd	d
dedddddddddddddddddddddddddddd dd d d!d"d#d$
Zd%d%d%d&Zd'd'd'd(Zd)d*d+d,d-d.d/d0d1d2d+d+d,d,d3Z	d4Z
d5d6d7d8d9d:d;ZeZeZeZeZeZeZeZd<Zd=d> Zd?d@ ZedAdB ZdCdD ZdEdF Z fdGdHZ ed\dJdKZ!dLdM Z"edNdO Z#dPdQ Z$d\dRdSZ%dTdU Z&e' fdVdWZ(e)dXdY Z*dZd[ Z+  Z,S )]DatabaseWrapper
postgresqlZ
PostgreSQL	AutoFieldintegerBigAutoFieldZbigintZBinaryFieldZbyteaZBooleanFieldbooleanZ	CharFieldZ	DateFielddateZDateTimeFieldztimestamp with time zoneZDecimalFieldz+numeric(%(max_digits)s, %(decimal_places)s)ZDurationFieldintervalZ	FileFieldr*   ZFilePathFieldZ
FloatFieldzdouble precisionZIntegerFieldZBigIntegerFieldZIPAddressFieldZinetZGenericIPAddressFieldZ	JSONFieldZjsonbZsmallinttexttimeuuid)
ZOneToOneFieldPositiveBigIntegerFieldPositiveIntegerFieldPositiveSmallIntegerFieldZ	SlugFieldSmallAutoFieldZSmallIntegerFieldZ	TextFieldZ	TimeFieldZ	UUIDFieldz"%(column)s" >= 0)r8   r9   r:   z GENERATED BY DEFAULT AS IDENTITY)r/   r1   r;   z= %sz= UPPER(%s)zLIKE %szLIKE UPPER(%s)z~ %sz~* %sz> %sz>= %sz< %sz<= %s)exactZiexactcontains	icontainsregexZiregexgtZgteltZlte
startswithendswithistartswith	iendswithzKREPLACE(REPLACE(REPLACE({}, E'\\', E'\\\\'), E'%%', E'\\%%'), E'_', E'\\_')zLIKE '%%' || {} || '%%'zLIKE '%%' || UPPER({}) || '%%'zLIKE {} || '%%'zLIKE UPPER({}) || '%%'zLIKE '%%' || {}zLIKE '%%' || UPPER({}))r=   r>   rB   rD   rC   rE   r   c                 C   s   t | jdS )zo
        Return a tuple of the database's version.
        E.g. for pg_version 120004, return (12, 4).
        i'  )divmod
pg_versionselfr   r   r   get_database_version   s   z$DatabaseWrapper.get_database_versionc                 C   s  | j }|d dkr|di dstdt|d pd| j kr5td|d t|d | j f |d rDd|d i|d }n|d d u r]|di dd  ddi|d }ni |d }d	|d
< |dd  |dd  |dd }|dtr|du rt	nt
 |d r|d |d< |d r|d |d< |d r|d |d< |d r|d |d< trttj| j|d< |dd |d< |S )NNAME OPTIONSZservicez`settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value.zThe database name '%s' (%d characters) is longer than PostgreSQL's limit of %d characters. Supply a shorter NAME in settings.DATABASES.ZdbnamepostgresUTF8Zclient_encodingassume_roleisolation_levelserver_side_bindingZcursor_factoryTUSERuserZPASSWORDpasswordZHOSThostZPORTportcontextZprepare_threshold)settings_dictgetr   lenopsZmax_name_lengthpop
setdefaultr   ServerBindingCursorCursorr    r   USE_TZtimezone)rI   rY   conn_paramsrR   r   r   r   get_connection_params   sj   

z%DatabaseWrapper.get_connection_paramsc                 C   s   | j d }d}z|d }W n ty   tj| _Y nw z	t|| _d}W n ty3   td| dw | jjd
i |}|rC| j|_t	sOt
jj|dd d	 |S )NrM   FrQ   Tz$Invalid transaction isolation level z9 specified. Use one of the psycopg.IsolationLevel values.c                 S   s   | S Nr   )xr   r   r   <lambda>  s    z4DatabaseWrapper.get_new_connection.<locals>.<lambda>)Zconn_or_cursloadsr   )rY   KeyErrorr   ZREAD_COMMITTEDrQ   
ValueErrorr   r   connectr   psycopg2extrasZregister_default_jsonb)rI   rc   optionsZset_isolation_levelZisolation_level_value
connectionr   r   r   get_new_connection   s.   


z"DatabaseWrapper.get_new_connectionc                 C   sv   | j d u rdS | j jd}| j}|r9||kr9| j  }|| j |g W d    dS 1 s2w   Y  dS dS )NFZTimeZoneT)ro   infoZparameter_statustimezone_namecursorexecuter\   Zset_time_zone_sql)rI   Zconn_timezone_namerr   rs   r   r   r   ensure_timezone  s   

zDatabaseWrapper.ensure_timezonec                 C   st   | j d u rdS | jdi d }r8| j  }| jd|g}|| W d    dS 1 s1w   Y  dS dS )NFrM   rP   zSET ROLE %sT)ro   rY   rZ   rs   r\   Zcompose_sqlrt   )rI   Znew_rolers   r   r   r   r   ensure_role*  s   

zDatabaseWrapper.ensure_rolec                    s@   t    |  }|  }|s|r|  s| j  d S d S d S re   )superinit_connection_stateru   rv   Zget_autocommitro   commit)rI   Z	commit_tzZcommit_role	__class__r   r   rx   4  s   
z%DatabaseWrapper.init_connection_stateNc                 C   sn   |r| j j|d| j jd}n| j  }tr,| j jttj}| j	|j	kr*t
| j	| |S tjr2| jnd |_|S )NF)Z
scrollableZwithhold)ro   rs   
autocommitr   r   
get_loaderTIMESTAMPTZ_OIDr   ZTEXTrb   r!   r   ra   tzinfo_factory)rI   namers   Ztzloaderr   r   r   create_cursorA  s   

zDatabaseWrapper.create_cursorc                 C   s   | j S re   )rb   )rI   offsetr   r   r   r   V  s   zDatabaseWrapper.tzinfo_factoryc                 C   sf   |  j d7  _ zt }W n ty   d }Y nw |r"tt|}nd}| jdt j	|| j f dS )Nr   syncz_django_curs_%d_%s_%d)r   )
_named_cursor_idxasynciocurrent_taskRuntimeErrorstridZ_cursor	threadingcurrent_threadident)rI   r   Z
task_identr   r   r   chunked_cursorY  s"   zDatabaseWrapper.chunked_cursorc                 C   s4   | j  || j_W d    d S 1 sw   Y  d S re   )Zwrap_database_errorsro   r|   )rI   r|   r   r   r   _set_autocommitu  s   
"zDatabaseWrapper._set_autocommitc                 C   sB   |   }|d |d W d   dS 1 sw   Y  dS )zl
        Check constraints by setting them to immediate. Return them to deferred
        afterward.
        zSET CONSTRAINTS ALL IMMEDIATEzSET CONSTRAINTS ALL DEFERREDN)rs   rt   )rI   Ztable_namesrs   r   r   r   check_constraintsy  s   

"z!DatabaseWrapper.check_constraintsc                 C   sV   z| j  }|d W d    W dS 1 sw   Y  W dS  tjy*   Y dS w )NzSELECT 1FT)ro   rs   rt   r   ErrorrI   rs   r   r   r   	is_usable  s   zDatabaseWrapper.is_usablec                 #   s   d }zt   }|V  W d    W d S 1 sw   Y  W d S  tjtfy   |d ur/ tdt t	 D ]G}|j
dkr|jd dkr| ji | jd|jd i| jd}z| }|V  W d    n1 slw   Y  W |  n|  w  Y d S q9 w )Na8  Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead.r.   rK   rN   )alias)rw   _nodb_cursorr   r   WrappedDatabaseErrorwarningswarnRuntimeWarningr   allvendorrY   r{   r   rs   close)rI   rs   ro   connrz   r   r   r     sD   &


zDatabaseWrapper._nodb_cursorc                 C   s6   |    | jjjW  d    S 1 sw   Y  d S re   )Ztemporary_connectionro   rq   Zserver_versionrH   r   r   r   rG     s   
$zDatabaseWrapper.pg_versionc                 C   s
   t || S re   r   r   r   r   r   make_debug_cursor  s   
z!DatabaseWrapper.make_debug_cursorre   )-__name__
__module____qualname__r   Zdisplay_namer,   
data_typesZdata_type_check_constraintsZdata_types_suffix	operatorsZpattern_escZpattern_opsr   r(   ZSchemaEditorClassr#   Zclient_classr$   Zcreation_classr%   Zfeatures_classr&   Zintrospection_classr'   Z	ops_classr   rJ   rd   r
   rp   ru   rv   rx   r   r   r   r   r   r   r   r   r   rG   r   __classcell__r   r   rz   r   r-   Y   s    	
	>
"


	
%
r-   c                   @   s   e Zd ZdZdddZdS )CursorMixinzE
        A subclass of psycopg cursor implementing callproc.
        Nc                 C   s   t |tjst|}td|tdg}|r0|D ]}|t| |td q|d= |td t|}| | |S )NzSELECT * FROM (,))
isinstancer   Z
IdentifierSQLappendLiteralZComposedrt   )rI   r   argsZqpartsitemstmtr   r   r   callproc  s   


zCursorMixin.callprocre   )r   r   r   __doc__r   r   r   r   r   r     s    r   c                   @      e Zd ZdS )r_   Nr   r   r   r   r   r   r   r_         r_   c                   @   r   )r`   Nr   r   r   r   r   r`     r   r`   c                   @   s   e Zd Zdd ZdS )r	   c                 C   s:   |  | | j|W  d    S 1 sw   Y  d S re   )	debug_sqlrs   copy)rI   Z	statementr   r   r   r     s   
$zCursorDebugWrapper.copyN)r   r   r   r   r   r   r   r   r	     s    r	   c                   @   s   e Zd Zdd Zdd ZdS )r	   c                 G   sD   |  | | jj||g|R  W  d    S 1 sw   Y  d S re   )r   rs   copy_expert)rI   r   filer   r   r   r   r     s   $zCursorDebugWrapper.copy_expertc                 O   sP   | j d| d | jj||g|R i |W  d    S 1 s!w   Y  d S )NzCOPY %s TO STDOUT)r   )r   rs   copy_to)rI   r   tabler   kwargsr   r   r   r     s   $zCursorDebugWrapper.copy_toN)r   r   r   r   r   r   r   r   r   r	     s    )Lr   r   r   r   
contextlibr   Zdjango.confr   Zdjango.core.exceptionsr   Z	django.dbr   r   r   Zdjango.db.backends.base.baser   Zdjango.db.backends.utilsr	   ZBaseCursorDebugWrapperZdjango.utils.asyncior
   Zdjango.utils.functionalr   Zdjango.utils.safestringr   Zdjango.utils.versionr   Zpsycopgr   ImportErrorrl   r   r   Zpsycopg_anyr   r   r   r   Z
psycopg.pqr   r    r!   typesoidr~   Zpsycopg2.extensionsZpsycopg2.extras
extensionsZregister_adapterQuotedStringrm   Zregister_uuidZINETARRAY_OIDZnew_array_typeUNICODEr"   Zregister_typeclientr#   Zcreationr$   featuresr%   Zintrospectionr&   
operationsr'   Zschemar(   r,   r-   r   r`   r_   ZClientCursorrs   r   r   r   r   <module>   s    



  d