
     h_                         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e          ZdS )    N)Decimal)Apps)NotSupportedError)BaseDatabaseSchemaEditor)	Statement)strip_quotes)UniqueConstraint)atomicc                        e Zd ZdZdZdZeZdZdZdZ	dZ
dZ fdZ fdZd	 Zd
 Z	 ddZ	 d fd	Zd fd	Z	 ddZd fd	Z fdZ fdZ	 ddZd Z fdZ fdZd Z x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                     | 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__s    `/var/www/surfInsights/venv3-11/lib/python3.11/site-packages/django/db/backends/sqlite3/schema.pyr   zDatabaseSchemaEditor.__enter__   sJ     ::<< 	#1   ww  """    c                     | j                                          t                                          |||           | j                                          d S N)r   check_constraintsr   __exit__enable_constraint_checking)r   exc_type	exc_value	tracebackr   s       r   r   zDatabaseSchemaEditor.__exit__'   sM    ))+++9i8882244444r   c                 L   	 dd l }|                    |          }n# t          $ r Y n|j        $ r Y nw xY wt	          |t
                    rt          t          |                    S t	          |t          t          t          f          rt          |          S t	          |t                    rd|
                    dd          z  S |dS t	          |t          t          t          f          rd|                                z  S t          d|dt!          |                    )	Nr   z'%s''z''NULLzX'%s'zCannot quote parameter value z	 of type )sqlite3adaptImportErrorProgrammingError
isinstanceboolstrintr   floatreplacebytes	bytearray
memoryviewhex
ValueErrortype)r   valuer!   s      r   quote_valuez DatabaseSchemaEditor.quote_value,   s3   	NNNMM%((EE 	 	 	D' 	 	 	D	 eT"" 	s5zz??"455 	u::s## 	EMM#t4444]6y*=>> 	 UYY[[((*@EtE{{{S  s    
4	44c                 ,    |                      |          S r   )r2   )r   r1   s     r   prepare_defaultz$DatabaseSchemaEditor.prepare_defaultK   s    &&&r   Fc                    | j                                         5 }| j         j                            |          D ]l}|r|j        |k    r| j         j                            ||j                  }|                                D ]"\  }}||k    r|||k    r  ddd           dS #m	 ddd           n# 1 swxY w 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_selfr6   other_table	relationsconstraint_columnconstraint_tables	            r   _is_referenced_by_fk_constraintz4DatabaseSchemaEditor._is_referenced_by_fk_constraintN   sF    _##%% 	$#<KKFSS 
$ 
$ ;#3z#A#A O9GGK, 	 <E;K;K;M;M $ $7%'7':55#+/@K/O/O#t	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$$
$	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ us   A>B4%B44B8;B8Tc                    | j         j        j        s|r|                     |          ru| j         j        rt          d|z            | 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_renamerC   in_atomic_blockr   r   r   alter_db_tabler   )r   modelold_db_tablenew_db_tabledisable_constraintsr   s        r   rH   z#DatabaseSchemaEditor.alter_db_tablee   s     (J	F#	F 44\BB	F
 . 'Y ##   O66888GG""5,EEEO7799999GG""5,EEEEEr   c                    |                      ||          sd S |j        }|j        j        }|                                \  }}|j        |k    r| j        j        j        s|                     ||d          r| j        j	        r t          d|j        j        d|d          t          | j        j                  5  t                                          ||||           | j                                        5 }	|	                    d                                          d         }
|	                    d	           d
|z  }|                                d         }||z  }||z  }|	                    d||f           |	                    d|
dz   z             |	                    d           |	                    d           d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   | j                                        5 }	|	                    d           d d d            d S # 1 swxY w Y   d S t                                          ||||           d S )NT)r>   zRenaming the .z 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_alteredr9   _metadb_tableget_attname_columnr   rE   rF   rC   rG   r   r
   aliasr   alter_fieldr6   executefetchone)r   rI   	old_field	new_fieldrO   old_field_namer<   _old_column_namer6   schema_versionreferences_templatenew_column_namesearchreplacementr   s                  r   rW   z DatabaseSchemaEditor.alter_field|   sE   ,,Y	BB 	F"[)
&99;;?Nn,,O,N -44O 5   - . '' {+++^^^=   -.. = =##E9i#OOO _++-- =%+^^4K%L%L%U%U%W%W&N NN#?@@@*E
*R'&/&B&B&D&DQ&GO0?BF"5"GKNNM-   NN#?>TUCU#VWWWNN#?@@@ NN#;<<<%= = = = = = = = = = = = = = == = = = = = = = = = = = = = =4 '')) )Vx((() ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) GGy)FKKKKKsI    ?G+?C	GG+G	G+G	G++G/2G/H22H69H6c                 	    fdfdj         j        D             } fdj         j        D             }i d}|pg }t          |dd          st          d |D                       rdt	          |                                          D ]B\  }|j        r6t          fd|D                       sd|_        |}|j        r|= ||j        = C|rH|||j	        <   |j
        s7|j        r0                                          |                    ||j        <   |D ]}	|	\  }
}|                    |
j	        d           |                    |
j        d           |||j	        <   |
j        rX|j        sQd	                     |
j                                                            |                    d
z  }|||j        <   n"                     |
j                  ||j        <   |j	        |
j	        <   ؉rL|j	        = |j        = j
        r5j        j        j         j        r                     j        j                  S t)                      }fdj         j        D             }fdj         j        D             }j         j        }rfd|D             }t	          j         j                  }t3          j        |          }j         j        j         j        |||||d}t;          dd|          }||d<   j        |d<   t;          j         j        j         |           t3          j        |          }j         j        dtC          j         j                  z  |||||d}t;          dd|          }||d<   j        |d<   t;          dj         j        z  j         |          } "                    |            #                    d                     |j         j                  dd$                     fd|D                       dd$                    |%                                          d                     j         j                                                  d            &                    ||j         j        j         j        d            j'        D ]} #                    |           g  _'        |r	d|_        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                 .    | j         o| j        j        u S r   )is_relationremote_fieldrI   )frI   s    r   is_self_referentialz?DatabaseSchemaEditor._remake_table.<locals>.is_self_referential   s    =BQ^%9U%BBr   c                 ^    i | ])}|j          |          r|                                n|*S  )r9   clone).0rh   ri   s     r   
<dictcomp>z6DatabaseSchemaEditor._remake_table.<locals>.<dictcomp>   sJ     
 
 
 F!4!4Q!7!7>AGGIIIQ
 
 
r   c                 P    i | ]"}|j                             |j                   #S rk   )column
quote_name)rm   rh   r   s     r   rn   z6DatabaseSchemaEditor._remake_table.<locals>.<dictcomp>   s;     
 
 
 Hdooah//
 
 
r   Nprimary_keyFc              3   >   K   | ]\  }}t          |d d          V  dS )rr   FN)getattr)rm   r]   r[   s      r   	<genexpr>z5DatabaseSchemaEditor._remake_table.<locals>.<genexpr>   sC       >
 >
9EIGI}e44>
 >
 >
 >
 >
 >
r   c              3   4   K   | ]\  }}|j         k    V  d S r   )r9   )rm   r]   r[   r9   s      r   ru   z5DatabaseSchemaEditor._remake_table.<locals>.<genexpr>   sD       1 1 %9 IN*1 1 1 1 1 1r   zcoalesce(%(col)s, %(default)s))coldefaultc                 ,    g | ]}fd |D             S )c                 <    g | ]}                     ||          S rk   getrm   nrename_mappings     r   
<listcomp>zADatabaseSchemaEditor._remake_table.<locals>.<listcomp>.<listcomp>  s)    666!^1%%666r   rk   )rm   uniquer   s     r   r   z6DatabaseSchemaEditor._remake_table.<locals>.<listcomp>  s=     
 
 
 7666v666
 
 
r   c                 ,    g | ]}fd |D             S )c                 <    g | ]}                     ||          S rk   r{   r}   s     r   r   zADatabaseSchemaEditor._remake_table.<locals>.<listcomp>.<listcomp>  s)    555!^1%%555r   rk   )rm   indexr   s     r   r   z6DatabaseSchemaEditor._remake_table.<locals>.<listcomp>  s=     
 
 
 6555u555
 
 
r   c                 0    g | ]}j         |j        v|S rk   )r9   fields)rm   r   delete_fields     r   r   z6DatabaseSchemaEditor._remake_table.<locals>.<listcomp>  s/       l.?u|.S.S.S.S.Sr   )	app_labelrT   unique_togetherindex_togetherindexesconstraintsappsMetark   
__module__znew__%szNew%sINSERT INTO  (, c              3   B   K   | ]}                     |          V  d S r   )rq   )rm   xr   s     r   ru   z5DatabaseSchemaEditor._remake_table.<locals>.<genexpr>T  s/      >>$//!,,>>>>>>r   	) SELECT  FROM )handle_autom2m)rL   T)(rS   local_concrete_fieldsrt   anylistitemsrr   auto_createdrp   r9   many_to_manyconcreter4   effective_defaultpopnullrq   rg   throughdelete_modelr   r   r   r   r   copydeepcopyr   rT   r0   r   object_name	__bases__r   create_modelrX   joinr;   rH   deferred_sql)r   rI   create_fieldr   alter_fieldsbodymappingrestore_pk_fieldfieldrW   rZ   r[   case_sqlr   r   r   r   r   	body_copymeta_contentsmeta	new_modelsqlri   r9   r   s   `` `                   @@@r   _remake_tablez"DatabaseSchemaEditor._remake_table   s*   ,	C 	C 	C 	C 	C
 
 
 
[6
 
 

 
 
 
[6
 
 

   #)r<66 	2# >
 >
IU>
 >
 >
 ;
 ;
 	2  $DJJLL11 2 2e$ 
2S 1 1 1 1 )5	1 1 1 . . 
2 ).E%',$) 2 J#EL1 	&2D"#, 1F /3/C/C**<880 0+, ( 	< 	<K#. IyHHY^T***KK	($///#,D ~ Nin N;??9+;<<#33D4J4J94U4UVV? ?  -5	()),0OOI<L,M,M	()-6^N9>** 	L\&'+, )L -5;HL (()B)JKKKvv
 
 
 
+5
 
 

 
 
 
3
 
 

 +% 	   #*  G 5;233
 M$''	 .,.,&
 
 FB.. 	&"'"2	,U[$eoyAAA M$''	.!L1E$F$FF.,&
 
 FB.. 	&"'"2	,5;#::EOYWW	 	)$$$ 	 	 89999		>>>>g>>>>>>>		'..**++++ 4555	
 	
 	
 	%666 	O$K  %	 	 	
 	
 	
 $ 	 	CLL 	0+/(((	0 	0r   c                    |r#t                                          |           d S |                     | j        d|                     |j        j                  iz             t          | j                  D ]P}t          |t                    r9|                    |j        j                  r| j                            |           Qd S )Ntable)r   r   rX   sql_delete_tablerq   rS   rT   r   r   r%   r   references_tableremove)r   rI   r   r   r   s       r   r   z!DatabaseSchemaEditor.delete_modelm  s     	2GG  ''''' LL%T__U[-ABB   D-.. 2 2c9-- 2#2F2FK(3 3 2 %,,S111	2 2r   c                 N   |j         r7|j        j        j        j        r!|                     |j        j                   dS |j        s#|j        s|j        r| 	                    |          | 
                    ||           dS t                                          ||           dS )zCreate a field on a model.N)r   )r   rg   r   rS   r   r   rr   r   r   r   r   r   	add_fieldr   rI   r   r   s      r   r   zDatabaseSchemaEditor.add_field  s      	,%"4"<"B"O 	,e0899999 	, |		, 
	, %%e,,8u599999GGeU+++++r   c                    |j         r9|j        j        j        j        r!|                     |j        j                   dS dS | j        j        j        rG|j	        s@|j
        s9|j        s2|j        r|j        s$t                                          ||           dS |                    | j                  d         dS |                     ||           dS )z
        Remove a field from a model. Usually involves deleting a column,
        but for M2Ms may involve deleting a table.
        )r   r0   N)r   )r   rg   r   rS   r   r   r   rE   can_alter_table_drop_columnrr   r   db_indexdb_constraintr   remove_fielddb_parametersr   r   s      r   r   z!DatabaseSchemaEditor.remove_field  s     	:!)/< >!!%"4"<=====> > O$@	: %		:
 L	: N	: '	: -2,?	: GG  ..... ""do">>vFNu599999r   c	                     | j         j        j        r|j        |j        k    r|                     ||          |                     ||          k    rQ|j        r|j        sC|j        r|j        s5|                     |                     |j	        j
        |||                    S |                     |||fg           |                    d          }	|                    d          }
|j        r||k    s|	|
k    rt                      }|j        j	        }|j        D ]r}|j        |k    r|j        s+|j        |j        k    r|                    |j                   @|j        r+|j        j	        j        r|                    |j                   s|j        rK|j        D ]C}|j        |k    r|j        j        j	        j        r|                    |j        j                   D|D ]}|                     |           dS dS dS )z3Perform a "physical" (non-ManyToMany) field update.r   	collationN)r   rE   can_alter_table_rename_columnrp   
column_sqlrg   r   rX   _rename_field_sqlrS   rT   r   r|   r   setrI   related_objectsrelated_modelr   
field_namer9   addrr   r   r   )r   rI   rZ   r[   old_typenew_typeold_db_paramsnew_db_paramsrO   old_collationnew_collationrelated_modelsoptsrg   r   r   s                   r   _alter_fieldz!DatabaseSchemaEditor._alter_field  sa    O$B	 I$444y11T__UI5V5VVV& W + W )	 W
 + W <<&&K()Y    	5I0F/GHHH%))+66%))+66 	2  M]$B$B UUN?(D $ 4 = =-66#0 =#.).@@&**<+EFFF* =|/C/I/V ="&&|';<<<$ N$($5 N NL#1U:: #08>K N&**<+D+LMMM!/ 2 2""=1111-	2 	2$B$B(2 2r   c                    |j         j        j        j        |j         j        j        j        k    r|                     |j         j        |j         j        j                            |                                          |j         j        j                            |                                          f|j         j        j                            |                                          |j         j        j                            |                                          fg           dS |                     |j         j                   | 	                    d| 
                    |j         j        j        j                  dd                    d|                                |                                g          dd                    d|                                |                                g          d| 
                    |j         j        j        j                             |                     |j         j                   dS )	z*Alter M2Ms to repoint their to= endpoints.r   Nr   r   r   idr   r   )rg   r   rS   rT   r   	get_fieldm2m_reverse_field_namem2m_field_namer   rX   rq   r   m2m_column_namem2m_reverse_namer   )r   rI   rZ   r[   rO   s        r   _alter_many_to_manyz(DatabaseSchemaEditor._alter_many_to_many  s@    "*09%-3<= =
 &. ".6<FF%<<>>  ".6<FF%<<>> 
 ".6<FF%4466  ".6<FF%4466 
    6 F 	)08999 	 6 > D MNNNN		!1133!2244    		!1133!2244    	 6 > D MNNN#	
 	
 	
, 	)0899999r   c                     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   rI   
constraintr   s      r   r   z#DatabaseSchemaEditor.add_constraint+  s    j"233 	& 	&.	& !	& $		& GG""5*55555u%%%%%r   c                     t          |t                    r@|j        s|j        s|j        s|j        r$t                                          ||           d S |                     |           d S r   )	r%   r	   r   r   r   r   r   remove_constraintr   r   s      r   r   z&DatabaseSchemaEditor.remove_constraint6  s    j"233 	& 	&.	& !	& $		& GG%%eZ88888u%%%%%r   c                     d|z   S )NzCOLLATE rk   )r   r   s     r   _collate_sqlz!DatabaseSchemaEditor._collate_sqlA  s    I%%r   )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_uniquesql_alter_table_commentsql_alter_column_commentr   r   r2   r4   rC   rH   rW   r   r   r   r   r   r   r   r   r   __classcell__)r   s   @r   r   r      s       -MO  #7FQ-"## # # # #5 5 5 5 5
  >' ' ' 9>   0 FJF F F F F F.3L 3L 3L 3L 3L 3Ll IMz0 z0 z0 z0x2 2 2 2 2 2$, , , , ,*: : : : :J 92 92 92 92v>: >: >:@	& 	& 	& 	& 	&	& 	& 	& 	& 	&& & & & & & &r   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   rk   r   r   <module>r     s           % % % % % % ' ' ' ' ' ' C C C C C C 7 7 7 7 7 7 1 1 1 1 1 1 - - - - - - ( ( ( ( ( (u& u& u& u& u&3 u& u& u& u& u&r   