o
    tdn_                     @   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__ ID:\rfid_django\env\Lib\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''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_renamer3   in_atomic_blockr   r   r   alter_db_tabler   )r   modelZold_db_tableZnew_db_tabledisable_constraintsr   r   r   r7   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)r2   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   r4   r5   r3   r6   r   r	   aliasr   alter_fieldr.   executeZfetchone)r   r8   	old_field	new_fieldr:   Zold_field_namer1   _Zold_column_namer.   Zschema_versionZreferences_templateZnew_column_namesearchreplacementr   r   r   r?   z   sX   


"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_fieldr8   )f)r8   r   r   is_self_referential   s   z?DatabaseSchemaEditor._remake_table.<locals>.is_self_referentialc                    s$   i | ]}|j  |r| n|qS r   )r/   clone.0rG   )rH   r   r   
<dictcomp>   s    z6DatabaseSchemaEditor._remake_table.<locals>.<dictcomp>c                    s   i | ]
}|j  |j qS r   )column
quote_namerJ   r   r   r   rL      s    Nprimary_keyFc                 s   s     | ]\}}t |d dV  qdS )rO   FN)getattrrK   rC   rB   r   r   r   	<genexpr>   s    
z5DatabaseSchemaEditor._remake_table.<locals>.<genexpr>c                 3   s    | ]
\}} |j kV  qd S r   r/   rQ   rS   r   r   rR      s
    
zcoalesce(%(col)s, %(default)s))coldefaultc                       g | ]} fd d|D qS )c                       g | ]}  ||qS r   getrK   nrename_mappingr   r   
<listcomp>      ADatabaseSchemaEditor._remake_table.<locals>.<listcomp>.<listcomp>r   )rK   uniquer\   r   r   r^         z6DatabaseSchemaEditor._remake_table.<locals>.<listcomp>c                    rV   )c                    rW   r   rX   rZ   r\   r   r   r^     r_   r`   r   rK   indexr\   r   r   r^     rb   c                    s   g | ]
} j |jvr|qS r   )r/   fieldsrc   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   )rN   )rK   xr   r   r   rR   R  s    )handle_autom2m)r9   T)(r<   Zlocal_concrete_fieldsrP   anylistitemsrO   auto_createdrM   r/   many_to_manyZconcreter-   effective_defaultpopnullrN   rF   throughdelete_modelr   ri   rj   rk   rl   copydeepcopyrh   r=   r*   rn   Zobject_name	__bases__r   create_modelr@   joinr0   r7   deferred_sql)r   r8   create_fieldrg   alter_fieldsbodymappingZrestore_pk_fieldfieldr?   rA   rB   Zcase_sqlrm   ri   rj   rk   rl   Z	body_copyZmeta_contentsmetaZ	new_modelsqlr   )rg   rH   r8   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_tablerN   r<   r=   rt   r   r   r   Zreferences_tableremove)r   r8   rr   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   )rw   rF   r{   r<   rv   r   rO   ra   rz   rx   r   r   	add_fieldr   r8   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*   Nrf   )rw   rF   r{   r<   rv   r|   r   r4   Zcan_alter_table_drop_columnrO   ra   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   r4   Zcan_alter_table_rename_columnrM   Z
column_sqlrF   r   r@   Z_rename_field_sqlr<   r=   r   rY   ra   setr8   Zrelated_objectsrelated_modelrw   
field_namer/   addrO   r{   rv   )r   r8   rA   rB   Zold_typenew_typeZold_db_paramsZnew_db_paramsr:   Zold_collationZnew_collationZrelated_modelsoptsrF   rw   r   r   r   r   _alter_field  sd   






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   Nro   rp   id)rF   r{   r<   r=   r   	get_fieldZm2m_reverse_field_nameZm2m_field_namer   r@   rN   r   Zm2m_column_nameZm2m_reverse_namer|   )r   r8   rA   rB   r:   r   r   r   _alter_many_to_many  sX   





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   r8   
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__rn   __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-   r3   r7   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    