
    Hwg_                         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y)    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    | j                   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    X/var/www/horilla/myenv/lib/python3.12/site-packages/django/db/backends/sqlite3/schema.pyr   zDatabaseSchemaEditor.__enter__   s7     ::<#1  w ""    c                     | j                   j                          t        |   |||       | j                   j	                          y N)r   check_constraintsr   __exit__enable_constraint_checking)r   exc_type	exc_value	tracebackr   s       r   r   zDatabaseSchemaEditor.__exit__'   s4    ))+9i8224r   c                    	 dd l }|j                  |      }t	        |t
              rt        t        |            S t	        |t        t        t        f      rt        |      S t	        |t              rd|j                  dd      z  S |yt	        |t        t        t        f      rd|j                         z  S t        d|dt!        |            # t        $ r Y j                  $ r Y w xY w)	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,   s    	MM%(E eT"s5z?"45u:s#EMM#t444]y*=> UYY[((@EtE{S '  	'' 		s   C 	C-C-,C-c                 $    | j                  |      S r   )r2   )r   r1   s     r   prepare_defaultz$DatabaseSchemaEditor.prepare_defaultK   s    &&r   c                    | j                   j                         5 }| j                   j                  j                  |      D ]t  }|r|j                  |k(  r| j                   j                  j                  ||j                        }|j                         D ]  \  }}||k(  s|||k(  s  ddd       y v 	 ddd       y# 1 sw Y   yxY w)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   s     __##% 	$#<<KKFS 
$;#3#3z#A OO99GGK,,	 <E;K;K;M $7%'7':5#+/@K/O#	$ 	$$
$	$ 	$ s   BC"C*C5CCc                 b   | j                   j                  j                  s}|r{| j                  |      rj| j                   j                  rt        d|z        | j                   j                          t        | !  |||       | j                   j                          y t        | !  |||       y )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J#44\B..'Y ##  OO668G"5,EOO779G"5,Er   c                 r   | j                  ||      sy |j                  }|j                  j                  }|j	                         \  }}|j                  |k7  r| j
                  j                  j                  s| j                  ||d      rq| j
                  j                  r&t        d|j                  j                  d|d      t        | j
                  j                        5  t        | 9  ||||       | j
                  j                         5 }	|	j!                  d      j#                         d   }
|	j!                  d	       d
|z  }|j	                         d   }||z  }||z  }|	j!                  d||f       |	j!                  d|
dz   z         |	j!                  d       |	j!                  d       d d d        d d d        | j
                  j                         5 }	|	j!                  d       d d d        y t        | 9  ||||       y # 1 sw Y   ZxY w# 1 sw Y   ^xY w# 1 sw Y   y xY w)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|   s   ,,Y	B"[[))
&99;?NNn,OO,,NN44O 5  ..' {{++^=  --. =#E9i#O __++- =%+^^4K%L%U%U%W&N NN#?@*E
*R'&/&B&B&DQ&GO0?BF"5"GKNNM- NN#?>TUCU#VWNN#?@ NN#;<%==4 '') )Vx() ) Gy)FK1= == =4) )s1   +.H!B#H<H!&H-H	H!!H*-H6c                     fd}j                   j                  D ci c]'  }|j                   ||      r|j                         n|) }}j                   j                  D ci c](  }|j                   j                  |j                        * }}i }	d}
|xs g }t        |dd      st        d |D              rit        |j                               D ]M  \  }|j                  st        fd|D              r(d|_
        |}
|j                  s>|= ||j                  = O |rT|||j                  <   |j                  s9|j                  r- j                   j                  |            ||j                  <   |D ]  }|\  }}|j!                  |j                  d       |j!                  |j                  d       |||j                  <   |j"                  r[|j"                  sOd j                  |j                         j                   j                  |            dz  }|||j                  <   n( j                  |j                        ||j                  <   |j                  |	|j                  <    |ru||j                  = ||j                  = |j                  rO|j$                  j&                  j                   j                  r% j)                  |j$                  j&                        S t+               }j                   j,                  D cg c]"  }|D cg c]  }|	j/                  ||       c}$ }}}j                   j0                  D cg c]"  }|D cg c]  }|	j/                  ||       c}$ }}}j                   j2                  }|r(|D cg c]  }|j                  |j4                  vs| }}t        j                   j6                        }t9        j:                  |      }j                   j<                  j                   j>                  |||||d	}tA        d
d|      }||d
<   jB                  |d<   tA        j                   jD                  jF                  |       t9        j:                  |      }j                   j<                  dtI        j                   j>                        z  |||||d	}tA        d
d|      }||d
<   jB                  |d<   tA        dj                   jD                  z  jF                  |      } jK                  |        jM                  d j                  |j                   j>                        ddjO                   fd|D              ddjO                  |jQ                               d j                  j                   j>                                j)                  d        jS                  ||j                   j>                  j                   j>                  d        jT                  D ]  } jM                  |        g  _*        |
rd|
_
        yyc c}w c c}w c c}w c c}}w c c}w c c}}w c c}w )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                 P    | j                   xr | j                  j                  u S r   )is_relationremote_fieldrI   )frI   s    r   is_self_referentialz?DatabaseSchemaEditor._remake_table.<locals>.is_self_referential   s!    ==BQ^^%9%9U%BBr   Nprimary_keyFc              3   <   K   | ]  \  }}t        |d d        yw)rj   FN)getattr).0r]   r[   s      r   	<genexpr>z5DatabaseSchemaEditor._remake_table.<locals>.<genexpr>   s"      >
9EIGI}e4>
s   c              3   B   K   | ]  \  }}|j                   k(    y wr   )r9   )rm   r]   r[   r9   s      r   rn   z5DatabaseSchemaEditor._remake_table.<locals>.<genexpr>   s(      1 %9 INN*1s   zcoalesce(%(col)s, %(default)s))coldefault)	app_labelrT   unique_togetherindex_togetherindexesconstraintsappsMeta 
__module__znew__%szNew%sINSERT INTO  (, c              3   @   K   | ]  }j                  |        y wr   )
quote_name)rm   xr   s     r   rn   z5DatabaseSchemaEditor._remake_table.<locals>.<genexpr>T  s     >$//!,>s   	) SELECT  FROM )handle_autom2m)rL   T)+rS   local_concrete_fieldsr9   clonecolumnr   rl   anylistitemsrj   auto_createdmany_to_manyconcreter4   effective_defaultpopnullrg   throughdelete_modelr   rs   getrt   ru   fieldsrv   copydeepcopyrr   rT   r0   rz   object_name	__bases__r   create_modelrX   joinr;   rH   deferred_sql)r   rI   create_fielddelete_fieldalter_fieldsri   rh   bodymappingrename_mappingrestore_pk_fieldfieldrW   rZ   r[   case_sqlrw   uniquenrs   indexrt   ru   rv   	body_copymeta_contentsmeta	new_modelsqlr9   s   ``                           @r   _remake_tablez"DatabaseSchemaEditor._remake_table   s   ,	C [[66
 FF!4Q!7AGGIQ>
 
 [[66
 HHdooahh//
 

   #)r<6# >
IU>
 ;
  $DJJL1 2e$$S 1 )5	1 . ).E%',$)) J#ELL12 &2D""#,,1F1F/3/C/C**<80++, ( 	<K#. IyHHY^^T*KK	(($/#,D ~~inn;??9+;+;<#33D4J4J94UV?  -5	((),0OOI<L<L,M	(()-6^^N9>>*	< \&&'++, )) --55;;HH(()B)B)J)JKKv  ++55
 066!^1%6
 
 33
 055!^1%5
 

 ++%%#*l.?.?u||.SG  5;;223
 MM$'	 ..,,.,&
 FB. 	&"'"2"2	,U[[$$eooyA MM$'	..!L1E1E$FF.,&
 FB. 	&"'"2"2	,5;;#:#::EOOYW	 	)$ 	 	 8 89		>g>>		'..*+ 4 45	
 	%6 	OO$$KK   %	 	 	
 $$ 	CLL	+/( 

@ 7
 6
sG   ,Y'-Y	YY5Y	YY8YY!:Y!YYc                    |rt         |   |       y | j                  | j                  d| j	                  |j
                  j                        iz         t        | j                        D ]T  }t        |t              s|j                  |j
                  j                        s:| j                  j                  |       V y )Ntable)r   r   rX   sql_delete_tabler   rS   rT   r   r   r%   r   references_tableremove)r   rI   r   r   r   s       r   r   z!DatabaseSchemaEditor.delete_modelm  s    G ' LL%%T__U[[-A-AB D--. 2c9-#2F2FKK((3 %%,,S1	2r   c                 p   |j                   rP|j                  j                  j                  j                  r&| j                  |j                  j                         y|j                  s)|j                  s|j                  r| j                  |      | j                  ||       yt        | 1  ||       y)zCreate a field on a model.N)r   )r   rg   r   rS   r   r   rj   r   r   r   r   r   	add_fieldr   rI   r   r   s      r   r   zDatabaseSchemaEditor.add_field  s     %"4"4"<"<"B"B"O"Oe00889 ||
 

%%e,8u59GeU+r   c                     |j                   rQ|j                  j                  j                  j                  r&| j                  |j                  j                         yy| j                  j                  j                  rM|j                  sA|j                  s5|j                  s)|j                  r|j                  st        | 9  ||       y|j                  | j                        d   y| j!                  ||       y)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_columnrj   r   db_indexdb_constraintr   remove_fielddb_parametersr   r   s      r   r   z!DatabaseSchemaEditor.remove_field  s     !!))//<<!!%"4"4"<"<= = OO$$@@ %%LLNN''E,?,?G . ""doo">vFNu59r   c	                    | j                   j                  j                  r|j                  |j                  k7  r| j	                  ||      | j	                  ||      k(  rg|j
                  r|j                  sO|j
                  r|j                  s7| j                  | j                  |j                  j                  |||            S | j                  |||fg       |j                  d      }	|j                  d      }
|j                  rn||k7  s|	|
k7  rbt               }|j                  j                  }|j                   D ]  }|j"                  |k(  r|j$                  s6|j&                  |j(                  k(  s9|j+                  |j"                         U|j,                  sb|j.                  j                  j0                  s|j+                  |j.                          |j,                  rq|j$                  D ]b  }|j"                  |k(  r|j
                  j.                  j                  j0                  s>|j+                  |j
                  j.                         d |D ]  }| j                  |        yyy)z3Perform a "physical" (non-ManyToMany) field update.r   	collationN)r   rE   can_alter_table_rename_columnr   
column_sqlrg   r   rX   _rename_field_sqlrS   rT   r   r   r   setrI   related_objectsrelated_modelr   
field_namer9   addrj   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  s$    OO$$BB  I$4$44y1T__UI5VV&&++))++ <<&&KK(()Y  	5I0F/GH%))+6%))+6 M]$B UN??((D $ 4 4 =--6#00#..)..@&**<+E+EF**|/C/C/I/I/V/V"&&|';';<= $$$($5$5 NL#11U: #0088>>KK&**<+D+D+L+LMN "0 2""=12) %C r   c                 F   |j                   j                  j                  j                  |j                   j                  j                  j                  k(  r| j	                  |j                   j                  |j                   j                  j                  j                  |j                               |j                   j                  j                  j                  |j                               f|j                   j                  j                  j                  |j                               |j                   j                  j                  j                  |j                               fg       y| j                  |j                   j                         | j                  d| j                  |j                   j                  j                  j                        ddj                  d|j                         |j                         g      ddj                  d|j                         |j                         g      d| j                  |j                   j                  j                  j                               | j                  |j                   j                         y)	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   r   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099%%--33<<=
 &&.. "..66<<FF%<<> "..66<<FF%<<>
 "..66<<FF%446 "..66<<FF%446
  6  	)00889 	 6 6 > > D D M MN		!113!224 		!113!224 	 6 6 > > D D M MN#	
, 	)00889r   c                     t        |t              rA|j                  s$|j                  s|j                  s|j
                  rt        |   ||       y | j                  |       y r   )	r%   r	   	conditioncontains_expressionsinclude
deferrabler   add_constraintr   r   rI   
constraintr   s      r   r   z#DatabaseSchemaEditor.add_constraint+  sO    j"23  ..!!$$G"5*5u%r   c                     t        |t              rA|j                  s$|j                  s|j                  s|j
                  rt        |   ||       y | j                  |       y r   )	r%   r	   r   r   r   r   r   remove_constraintr   r   s      r   r   z&DatabaseSchemaEditor.remove_constraint6  sO    j"23  ..!!$$G%eZ8u%r   c                     d|z   S )NzCOLLATE ry   )r   r   s     r   _collate_sqlz!DatabaseSchemaEditor._collate_sqlA  s    I%%r   )NF)T)F)NNN)__name__rz   __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
>' 9>0 FJF.3Ll IMz0x2$,*:J 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   ry   r   r   <module>r      s/      % ' C 7 1 - (u&3 u&r   