o
    Tin_                     @   s|   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 G d
d deZdS )    N)Decimal)Apps)NotSupportedError)BaseDatabaseSchemaEditor)	Statement)strip_quotes)UniqueConstraint)atomicc                       s   e Zd ZdZdZdZeZdZdZdZ	 fddZ
 fd	d
Zdd Zdd Z	d)ddZ	d* fdd	Zd+ fdd	Z	d,ddZd* fdd	Z fddZ fddZ	d+dd Zd!d" Z fd#d$Z fd%d&Zd'd( Z  ZS )-DatabaseSchemaEditorzDROP TABLE %(table)sNzEREFERENCES %(to_table)s (%(to_column)s) DEFERRABLE INITIALLY DEFERREDz,ALTER TABLE %(table)s DROP COLUMN %(column)sz7CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)zDROP INDEX %(name)sc                    s   | j  s	tdt  S )NzSQLite schema editor cannot be used while foreign key constraint checks are enabled. Make sure to disable them before entering a transaction.atomic() context because SQLite does not support disabling them in the middle of a multi-statement transaction.)
connectiondisable_constraint_checkingr   super	__enter__self	__class__ a/var/www/html/evchargy.com/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/schema.pyr      s
   

zDatabaseSchemaEditor.__enter__c                    s(   | j   t ||| | j   d S N)r   Zcheck_constraintsr   __exit__enable_constraint_checking)r   exc_type	exc_value	tracebackr   r   r   r   %   s   
zDatabaseSchemaEditor.__exit__c                 C   s   zdd l }||}W n ty   Y n
 |jy   Y nw t|tr)tt|S t|tt	tfr5t|S t|trBd|
dd S |d u rHdS t|tttfrVd|  S td|t|f )Nr   z'%s''z''ZNULLzX'%s'z*Cannot quote parameter value %r of type %s)sqlite3ZadaptImportErrorZProgrammingError
isinstanceboolstrintr   floatreplacebytes	bytearray
memoryviewhex
ValueErrortype)r   valuer   r   r   r   quote_value*   s*   

z DatabaseSchemaEditor.quote_valuec                 C   s
   |  |S r   )r+   )r   r*   r   r   r   prepare_defaultI   s   
z$DatabaseSchemaEditor.prepare_defaultFc           	      C   s   | j  C}| j j|D ]2}|r|j|krq| j j||j}| D ]\}}||kr>|du s4||kr>  W d   dS q$qW d   dS 1 sKw   Y  dS )a  
        Return whether or not the provided table name is referenced by another
        one. If `column_name` is specified, only references pointing to that
        column are considered. If `ignore_self` is True, self-referential
        constraints are ignored.
        NTF)r   cursorZintrospectionZget_table_listnameZget_relationsvalues)	r   
table_nameZcolumn_nameignore_selfr-   Zother_tableZ	relationsZconstraint_columnZconstraint_tabler   r   r   _is_referenced_by_fk_constraintL   s&   	
z4DatabaseSchemaEditor._is_referenced_by_fk_constraintTc                    sh   | j jjs*|r*| |r*| j jrtd| | j   t ||| | j 	  d S t ||| d S )NzRenaming the %r table while in a transaction is not supported on SQLite < 3.26 because it would break referential integrity. Try adding `atomic = False` to the Migration class.)
r   features!supports_atomic_references_renamer2   in_atomic_blockr   r   r   alter_db_tabler   )r   modelZold_db_tableZnew_db_tabledisable_constraintsr   r   r   r6   c   s    
z#DatabaseSchemaEditor.alter_db_tablec              	      s  |  ||sd S |j}|jj}| \}}|j|kr| jjjs| j||ddr| jj	r5t
d|jj|f t| jjb t j||||d | j C}	|	d d }
|	d d| }| d	 }|| }|| }|	d
||f |	d|
d	   |	d |	d W d    n1 sw   Y  W d    n1 sw   Y  | j }	|	d W d    d S 1 sw   Y  d S t j||||d d S )NT)r1   zRenaming the %r.%r column while in a transaction is not supported on SQLite < 3.26 because it would break referential integrity. Try adding `atomic = False` to the Migration class.)strictzPRAGMA schema_versionr   zPRAGMA writable_schema = 1z REFERENCES "%s" ("%%s")    z3UPDATE sqlite_master SET sql = replace(sql, %s, %s)zPRAGMA schema_version = %dzPRAGMA writable_schema = 0zPRAGMA integrity_checkZVACUUM)Z_field_should_be_alteredr.   _metadb_tableZget_attname_columnr   r3   r4   r2   r5   r   r	   aliasr   alter_fieldr-   executeZfetchone)r   r7   	old_field	new_fieldr9   Zold_field_namer0   _Zold_column_namer-   Zschema_versionZreferences_templateZnew_column_namesearchreplacementr   r   r   r>   z   sV   



"z DatabaseSchemaEditor.alter_fieldc              	      sj  fddfddj jD }fddj jD }i d}|p#g }t|dds3td	d
 |D r[t| D ]!\}|jrZtfdd
|D sZd|_|}|jrZ|= ||j= q9|rs|||j	< |j
ss|jrs|||j< |D ]E}	|	\}
}||
j	d ||
jd |||j	< |
jr|jsd|
j|d }|||j< n	|
j||j< |j	|
j	< qu r| j	= | j=  j
rՈ jjj jrՈ jjS t }fddj jD }fddj jD }j j} r fdd|D }tj j}t|}j jj j|||||d}tdd|}||d< j|d< tj jj | t|}j jdt!j j |||||d}tdd|}||d< j|d< tdj j j |}"| #d|j jd$fdd
|D d$|% j jf  jdd j&||j jj jdd j'D ]}#| qg _'|rd|_dS dS )a|  
        Shortcut to transform a model from old_model into new_model

        This follows the correct procedure to perform non-rename or column
        addition operations based on SQLite's documentation

        https://www.sqlite.org/lang_altertable.html#caution

        The essential steps are:
          1. Create a table with the updated definition called "new__app_model"
          2. Copy the data from the existing "app_model" table to the new table
          3. Drop the "app_model" table
          4. Rename the "new__app_model" table to "app_model"
          5. Restore any index of the previous "app_model" table.
        c                    s   | j o| jj u S r   )Zis_relationremote_fieldr7   )f)r7   r   r   is_self_referential   s   z?DatabaseSchemaEditor._remake_table.<locals>.is_self_referentialc                    s$   i | ]}|j  |r| n|qS r   )r.   clone.0rF   )rG   r   r   
<dictcomp>   s    z6DatabaseSchemaEditor._remake_table.<locals>.<dictcomp>c                    s   i | ]
}|j  |j qS r   )column
quote_namerI   r   r   r   rK      s    Nprimary_keyFc                 s   s     | ]\}}t |d dV  qdS )rN   FN)getattrrJ   rB   rA   r   r   r   	<genexpr>   s    
z5DatabaseSchemaEditor._remake_table.<locals>.<genexpr>c                 3   s    | ]
\}} |j kV  qd S r   r.   rP   rR   r   r   rQ      s
    
zcoalesce(%(col)s, %(default)s))coldefaultc                       g | ]} fd d|D qS )c                       g | ]}  ||qS r   getrJ   nrename_mappingr   r   
<listcomp>      ADatabaseSchemaEditor._remake_table.<locals>.<listcomp>.<listcomp>r   )rJ   uniquer[   r   r   r]         z6DatabaseSchemaEditor._remake_table.<locals>.<listcomp>c                    rU   )c                    rV   r   rW   rY   r[   r   r   r]     r^   r_   r   rJ   indexr[   r   r   r]     ra   c                    s   g | ]
} j |jvr|qS r   )r.   fieldsrb   delete_fieldr   r   r]     s    )	app_labelr<   unique_togetherindex_togetherindexesconstraintsappsZMetar   
__module__znew__%szNew%s%INSERT INTO %s (%s) SELECT %s FROM %s, c                 3   s    | ]}  |V  qd S r   )rM   )rJ   xr   r   r   rQ   R  s    )handle_autom2m)r8   T)(r;   Zlocal_concrete_fieldsrO   anylistitemsrN   auto_createdrL   r.   many_to_manyZconcreter,   effective_defaultpopnullrM   rE   throughdelete_modelr   rh   ri   rj   rk   copydeepcopyrg   r<   r)   rm   Zobject_name	__bases__r   create_modelr?   joinr/   r6   deferred_sql)r   r7   create_fieldrf   alter_fieldsbodymappingZrestore_pk_fieldfieldr>   r@   rA   Zcase_sqlrl   rh   ri   rj   rk   Z	body_copyZmeta_contentsmetaZ	new_modelsqlr   )rf   rG   r7   r.   r\   r   r   _remake_table   s   










	

	



z"DatabaseSchemaEditor._remake_tablec                    sj   |r
t  | d S | | jd| |jji  t| jD ]}t	|t
r2||jjr2| j| qd S )Ntable)r   r{   r?   sql_delete_tablerM   r;   r<   rs   r   r   r   Zreferences_tableremove)r   r7   rq   r   r   r   r   r{   k  s   z!DatabaseSchemaEditor.delete_modelc                    sh   |j r|jjjjr| |jj dS |js"|js"|jr"| 	|dur+| j
||d dS t || dS )zCreate a field on a model.N)r   )rv   rE   rz   r;   ru   r   rN   r`   ry   rw   r   r   	add_fieldr   r7   r   r   r   r   r   }  s   	
zDatabaseSchemaEditor.add_fieldc                    s   |j r|jjjjr| |jj dS dS | jjjr1|j	s1|j
s1|js1|jr(|js1t || dS |j| jdd du r>dS | j||d dS )z
        Remove a field from a model. Usually involves deleting a column,
        but for M2Ms may involve deleting a table.
        )r   r)   Nre   )rv   rE   rz   r;   ru   r{   r   r3   Zcan_alter_table_drop_columnrN   r`   Zdb_indexdb_constraintr   remove_fieldZdb_parametersr   r   r   r   r   r     s(   	z!DatabaseSchemaEditor.remove_fieldc	                 C   sX  | j jjr0|j|jkr0| ||| ||kr0|jr|js0|jr#|js0| | |j	j
|||S | j|||fgd |d}	|d}
|jr||ksO|	|
krt }|jj	}|jD ]&}|j|kraqY|jsq|j|jkrp||j qY|jr|jj	jr||j qY|jr|jD ]}|j|krq|jjj	jr||jj q|D ]}| | qdS dS dS )z3Perform a "physical" (non-ManyToMany) field update.r   	collationN)r   r3   Zcan_alter_table_rename_columnrL   Z
column_sqlrE   r   r?   Z_rename_field_sqlr;   r<   r   rX   r`   setr7   Zrelated_objectsrelated_modelrv   
field_namer.   addrN   rz   ru   )r   r7   r@   rA   Zold_typenew_typeZold_db_paramsZnew_db_paramsr9   Zold_collationZnew_collationZrelated_modelsoptsrE   rv   r   r   r   r   _alter_field  s\   





z!DatabaseSchemaEditor._alter_fieldc                 C   s   |j jjj|j jjjkr=| j|j j|j jj| |j jj| f|j jj| |j jj| fgd dS | |j j | 	d| 
|j jjjdd| | gdd| | g| 
|j jjjf  | |j j dS )z*Alter M2Ms to repoint their to= endpoints.r   Nrn   ro   id)rE   rz   r;   r<   r   	get_fieldZm2m_reverse_field_nameZm2m_field_namer   r?   rM   r   Zm2m_column_nameZm2m_reverse_namer{   )r   r7   r@   rA   r9   r   r   r   _alter_many_to_many  sV   





z(DatabaseSchemaEditor._alter_many_to_manyc                    B   t |tr|js|js|js|jrt || d S | | d S r   )	r   r   	conditioncontains_expressionsinclude
deferrabler   add_constraintr   r   r7   
constraintr   r   r   r   )     
z#DatabaseSchemaEditor.add_constraintc                    r   r   )	r   r   r   r   r   r   r   remove_constraintr   r   r   r   r   r   4  r   z&DatabaseSchemaEditor.remove_constraintc                 C   s   d| S )NzCOLLATE r   )r   r   r   r   r   _collate_sql?  s   z!DatabaseSchemaEditor._collate_sql)NF)T)F)NNN)__name__rm   __qualname__r   Zsql_create_fkZsql_create_inline_fkZsql_create_column_inline_fkZsql_delete_columnZsql_create_uniqueZsql_delete_uniquer   r   r+   r,   r2   r6   r>   r   r{   r   r   r   r   r   r   r   __classcell__r   r   r   r   r
      s<    
6
 =%
;@r
   )r|   decimalr   Zdjango.apps.registryr   Z	django.dbr   Zdjango.db.backends.base.schemar   Z!django.db.backends.ddl_referencesr   Zdjango.db.backends.utilsr   Zdjango.db.modelsr   Zdjango.db.transactionr	   r
   r   r   r   r   <module>   s    