o
    ˷e[                     @   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__ X/var/www/ideatree/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   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)sqlite3adaptImportError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_defaultJ   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   cursorintrospectionget_table_listnameget_relationsvalues)	r   
table_namecolumn_nameignore_selfr1   other_table	relationsconstraint_columnconstraint_tabler   r   r   _is_referenced_by_fk_constraintM   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_renamer>   in_atomic_blockr   r   r   alter_db_tabler   )r   modelold_db_tablenew_db_tabledisable_constraintsr   r   r   rB   d   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)r9   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_checkVACUUM)_field_should_be_alteredr4   _metadb_tableget_attname_columnr   r?   r@   r>   rA   r   r	   aliasr   alter_fieldr1   executefetchone)r   rC   	old_field	new_fieldrG   old_field_namer7   _old_column_namer1   schema_versionreferences_templatenew_column_namesearchreplacementr   r   r   rO   {   sV   



"z DatabaseSchemaEditor.alter_fieldc              	      sZ  fddfddj jD }fddj jD }i d}t|dds0|rVt|d	 ddrVt| D ]\}}	|	jrU|rF||d	 jksUd|	_|	}|	jrU||= ||	j= q6|rn|||j< |j	sn|j
rn|||j< |r|\}
}||
jd ||
jd |||j< |
jr|jsd
|
j|d }|||j< n	|
j||j< |j|
j<  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   )is_relationremote_fieldrC   )f)rC   r   r   is_self_referential   s   z?DatabaseSchemaEditor._remake_table.<locals>.is_self_referentialc                    s$   i | ]}|j  |r| n|qS r   )r4   clone.0r^   )r_   r   r   
<dictcomp>   s    z6DatabaseSchemaEditor._remake_table.<locals>.<dictcomp>c                    s   i | ]
}|j  |j qS r   )column
quote_namera   r   r   r   rc      s    Nprimary_keyFrH   zcoalesce(%(col)s, %(default)s))coldefaultc                       g | ]} fd d|D qS )c                       g | ]}  ||qS r   getrb   nrename_mappingr   r   
<listcomp>      ADatabaseSchemaEditor._remake_table.<locals>.<listcomp>.<listcomp>r   )rb   uniquero   r   r   rq         z6DatabaseSchemaEditor._remake_table.<locals>.<listcomp>c                    ri   )c                    rj   r   rk   rm   ro   r   r   rq     rr   rs   r   rb   indexro   r   r   rq     ru   c                    s   g | ]
} j |jvr|qS r   )r4   fieldsrv   delete_fieldr   r   rq     s    )	app_labelrL   unique_togetherindex_togetherindexesconstraintsappsMetar   
__module__znew__%szNew%s%INSERT INTO %s (%s) SELECT %s FROM %s, c                 3   s    | ]}  |V  qd S r   )re   )rb   xr   r   r   	<genexpr>Q  s    z5DatabaseSchemaEditor._remake_table.<locals>.<genexpr>)handle_autom2m)rF   T)'rK   local_concrete_fieldsgetattrlistitemsrf   r4   auto_createdrd   many_to_manyconcreter0   effective_defaultpopnullre   r]   throughdelete_modelr   r|   r}   r~   r   copydeepcopyr{   rL   r-   r   object_name	__bases__r   create_modelrP   joinr6   rB   deferred_sql)r   rC   create_fieldrz   rO   bodymappingrestore_pk_fieldr4   fieldrR   rS   case_sqlr   r|   r}   r~   r   	body_copymeta_contentsmeta	new_modelsqlr   )rz   r_   rC   rp   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   rP   sql_delete_tablere   rK   rL   r   r   r"   r   references_tableremove)r   rC   r   r   r   r   r   r   j  s   z!DatabaseSchemaEditor.delete_modelc                    sD   |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   )rf   rt   r   r   r   r   	add_fieldr   rC   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r.|j	s.|j
s.|jr%|js.t || 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-   Nry   )r   r]   r   rK   r   r   r   r?   can_alter_table_drop_columnrf   rt   db_constraintr   remove_fielddb_parametersr   r   r   r   r   r     s$   z!DatabaseSchemaEditor.remove_fieldc	                 C   sV  | j jjr0|j|jkr0| ||| ||kr0|jr|js0|jr#|js0| | |j	j
|||S | j|||fd |d}	|d}
|jr||ksN|	|
krt }|jj	}|jD ]&}|j|kr`qX|jsp|j|jkro||j qX|jr~|jj	jr~||j qX|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.rO   	collationN)r   r?   can_alter_table_rename_columnrd   
column_sqlr]   r   rP   _rename_field_sqlrK   rL   r   rl   rt   setrC   related_objectsrelated_modelr   
field_namer4   addrf   r   r   )r   rC   rR   rS   old_typenew_typeold_db_paramsnew_db_paramsrG   old_collationnew_collationrelated_modelsoptsr]   r   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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   Nr   r   id)r]   r   rK   rL   r   	get_fieldm2m_reverse_field_namer   rP   re   r   m2m_column_namem2m_reverse_namer   )r   rC   rR   rS   rG   r   r   r   _alter_many_to_many  sF   



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   rC   
constraintr   r   r   r        
z#DatabaseSchemaEditor.add_constraintc                    r   r   )	r"   r   r   r   r   r   r   remove_constraintr   r   r   r   r   r   #  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__r   __qualname__r   sql_create_fksql_create_inline_fksql_create_column_inline_fksql_delete_columnsql_create_uniquesql_delete_uniquer   r   r/   r0   r>   rB   rO   r   r   r   r   r   r   r   r   r   __classcell__r   r   r   r   r
      s<    
6
 ;$
;4r
   )r   decimalr   django.apps.registryr   	django.dbr   django.db.backends.base.schemar   !django.db.backends.ddl_referencesr   django.db.backends.utilsr   django.db.modelsr   django.db.transactionr	   r
   r   r   r   r   <module>   s    