
    B>qj~                        d Z ddlmZ ddlZddlZddlZddl 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 ddlmZ ddlmZ 	 ddlmZ  G d de      Zd Zd Z G d de      Z G d de      Z G d de      Z G d d edd            Z G d de      Z G d  d!e      Zd" Zy# e$ r dZY gw xY w)#ah  
Lightweight schema migrations.

Example Usage
-------------

Instantiate a migrator:

    # Postgres example:
    my_db = PostgresqlDatabase(...)
    migrator = PostgresqlMigrator(my_db)

    # SQLite example:
    my_db = SqliteDatabase('my_database.db')
    migrator = SqliteMigrator(my_db)

Then you will use the `migrate` function to run various `Operation`s which
are generated by the migrator:

    migrate(
        migrator.add_column('some_table', 'column_name', CharField(default=''))
    )

Migrations are not run inside a transaction, so if you wish the migration to
run in a transaction you will need to wrap the call to `migrate` in a
transaction block, e.g.:

    with my_db.transaction():
        migrate(...)

Supported Operations
--------------------

Add new field(s) to an existing model:

    # Create your field instances. For non-null fields you must specify a
    # default value.
    pubdate_field = DateTimeField(null=True)
    comment_field = TextField(default='')

    # Run the migration, specifying the database table, field name and field.
    migrate(
        migrator.add_column('comment_tbl', 'pub_date', pubdate_field),
        migrator.add_column('comment_tbl', 'comment', comment_field),
    )

Renaming a field:

    # Specify the table, original name of the column, and its new name.
    migrate(
        migrator.rename_column('story', 'pub_date', 'publish_date'),
        migrator.rename_column('story', 'mod_date', 'modified_date'),
    )

Dropping a field:

    migrate(
        migrator.drop_column('story', 'some_old_field'),
    )

Making a field nullable or not nullable:

    # Note that when making a field not null that field must not have any
    # NULL values present.
    migrate(
        # Make `pub_date` allow NULL values.
        migrator.drop_not_null('story', 'pub_date'),

        # Prevent `modified_date` from containing NULL values.
        migrator.add_not_null('story', 'modified_date'),
    )

Renaming a table:

    migrate(
        migrator.rename_table('story', 'stories_tbl'),
    )

Adding an index:

    # Specify the table, column names, and whether the index should be
    # UNIQUE or not.
    migrate(
        # Create an index on the `pub_date` column.
        migrator.add_index('story', ('pub_date',), False),

        # Create a multi-column index on the `pub_date` and `status` fields.
        migrator.add_index('story', ('pub_date', 'status'), False),

        # Create a unique index on the category and title fields.
        migrator.add_index('story', ('category_id', 'title'), True),
    )

Dropping an index:

    # Specify the index name.
    migrate(migrator.drop_index('story', 'story_pub_date_status'))

Adding or dropping table constraints:

.. code-block:: python

    # Add a CHECK() constraint to enforce the price cannot be negative.
    migrate(migrator.add_constraint(
        'products',
        'price_check',
        Check('price >= 0')))

    # Remove the price check constraint.
    migrate(migrator.drop_constraint('products', 'price_check'))

    # Add a UNIQUE constraint on the first and last names.
    migrate(migrator.add_unique('person', 'first_name', 'last_name'))
    )
namedtupleN)*)CommaNodeList)EnclosedNodeList)Entity)
Expression)Node)NodeList)OP)	callable_)sqlite3)_truncate_constraint_name)CockroachDatabasec                   (    e Zd ZdZd Zd Zd Zd Zy)	Operationz/Encapsulate a single schema altering operation.c                 <    || _         || _        || _        || _        y N)migratormethodargskwargs)selfr   r   r   r   s        P/opt/rentech/trading_bot/.venv/lib/python3.12/site-packages/playhouse/migrate.py__init__zOperation.__init__   s     	    c                 N    | j                   j                  j                  |       y r   )r   databaseexecute)r   nodes     r   r   zOperation.execute   s    &&t,r   c                     t        |t        t        f      r| j                  |       y t        |t              r|j                          y t        |t        t        f      r|D ]  }| j                  |        y y r   )	
isinstancer	   Contextr   r   runlisttuple_handle_result)r   resultitems      r   r&   zOperation._handle_result   s_    ftWo.LL 	*JJLu. *##D)* /r   c                     | j                   j                         }d|d<   t        | j                  | j                        }| j                   || j                  i |       y )NTwith_context)r   copygetattrr   r   r&   r   )r   r   r   s      r   r#   zOperation.run   sN    !!#!%~4FDII889r   N)__name__
__module____qualname____doc__r   r   r&   r#    r   r   r   r      s    9-*:r   r   c                 B     t        j                          fd       }|S )Nc                 x    |j                  dd      }|r | g|i |S t        | j                  g|i |S )Nr*   F)popr   r-   )r   r   r   r*   fns       r   innerzoperation.<locals>.inner   sF    zz.%8d,T,V,,r{{<T<V<<r   )	functoolswraps)r5   r6   s   ` r   	operationr9      s%    __R= =
 Lr   c                     dj                  | ft        |      z         }t        |      dkD  r?t        j                  |j                  d            j                         }|d d d|d d }|S )N_@   zutf-83      )joinr%   lenhashlibmd5encode	hexdigest)
table_namecolumns
index_name
index_hashs       r   make_index_namerI      se    :-%.89J
:[[!2!27!;<FFH
 *3BCRA
r   c                   x   e Zd ZdZdZdZd Zd Zed        Z	e
d        Zd Zd Ze
d	        Ze
d
        Ze
d        Ze
d        Zd Ze
	 	 dd       Ze
d        Zd Ze
d        Ze
dd       Ze
d        Ze
d        Ze
d        Ze
d        Ze
d        Ze
dd       Ze
d        Ze
d d       Ze
d        Z y)!SchemaMigratorFTc                     || _         y r   )r   )r   r   s     r   r   zSchemaMigrator.__init__   s	     r   c                 6    | j                   j                         S r   )r   get_sql_contextr   s    r   make_contextzSchemaMigrator.make_context   s    }},,..r   c                    t         rt        |t               rt        |      S t        |t              rt	        |      S t        |t
              rt        |      S t        |t              rt        |      S t        d|z        )NzUnsupported database: %s)
r   r!   CockroachDBMigratorPostgresqlDatabasePostgresqlMigratorMySQLDatabaseMySQLMigratorSqliteDatabaseSqliteMigrator
ValueError)clsr   s     r   from_databasezSchemaMigrator.from_database   sk    H6G!H&x00"45%h//-0 **.1!(++3h>??r   c           	      N   |j                   }t        |      r |       }| j                         j                  d      j	                  t        |            j                  d      j	                  t        t        |      t        j                  |j                  |      d            S )NzUPDATE z SET T)flat)
defaultr   rP   literalsqlr   r   r   EQdb_value)r   tablecolumn_namefieldr^   s        r   apply_defaultzSchemaMigrator.apply_default   s|    --WiG!!##VE]#!Z;'EENN7+	  		!r   c                 T    |j                  d      j                  t        |            S )NALTER TABLE )r_   r`   r   )r   ctxrc   s      r   _alter_tablezSchemaMigrator._alter_table   s     {{>*..ve}==r   c                 t    | j                  ||      j                  d      j                  t        |            S )N ALTER COLUMN rj   r_   r`   r   r   ri   rc   columns       r   _alter_columnzSchemaMigrator._alter_column   s/    c5))*VF^$	&r   c                 X   | j                         }|j                  dc}|_        |j                  |k7  r|x|_        |_        | j	                  ||      j                  d      j                  |j                  |             ||_        t        |t              r| j                  ||       |S )NTz ADD COLUMN )rP   nullrd   namerj   r_   r`   ddlr!   ForeignKeyFieldadd_inline_fk_sql)r   rc   rd   re   ri   
field_nulls         r   alter_add_columnzSchemaMigrator.alter_add_column   s     !!&T
EJ +-88EJ*	
,sE
"
'.
!
#eiin

e_-""3.
r   c                     | j                  | j                         |      j                  d      j                  t	        |            j                  d      j                  |      S )N ADD CONSTRAINT  rj   rP   r_   r`   r   r   rc   rs   
constraints       r   add_constraintzSchemaMigrator.add_constraint   sJ    d//159+,VD\"Z	"r   c                     ddj                  |      z  }t        t        d      t        |D cg c]  }t	        |       c}      f      }| j                  |||      S c c}w )Nzuniq_%sr;   UNIQUE)r?   r
   SQLr   r   r   )r   rc   column_namesconstraint_namero   r~   s         r   
add_uniquezSchemaMigrator.add_unique  sa    #chh|&<<M<HfVnHIK L
 ""5/:FF Is   Ac                     | j                  | j                         |      j                  d      j                  t	        |            S Nz DROP CONSTRAINT r|   r   rc   rs   s      r   drop_constraintzSchemaMigrator.drop_constraint  s8    d//159,-VD\"	$r   c                    |j                  d      j                  t        |j                  j                  j
                              j                  d      j                  t        t        |j                  j                        f            }|j                  |j                  d|j                  z        }|j                  |j                  d|j                  z        }|S )N REFERENCES r{    ON DELETE %s ON UPDATE %s)r_   r`   r   	rel_model_metarE   r   	rel_fieldrd   	on_delete	on_updater   ri   re   s      r   rv   z SchemaMigrator.add_inline_fk_sql  s    'F5??00;;<=$fU__-H-H&I%KLM	 	
 ??&++o?@C??&++o?@C
r   Nc                 f   |xs d|d|d|}| j                         j                  d      j                  t        |            j                  d      j                  t        t	        |                  j                  d      j                  t        t        |      f            j                  d      j                  t        |            j                  d      j                  t        |            j                  d	      }	||	j                  d
|z        }	||	j                  d|z        }	|	S )Nfk_r;   _refs_rh   rz   z FOREIGN KEY r    ()r   r   )rP   r_   r`   r   r   r   )
r   rc   rd   rel
rel_columnr   r   r   r~   ri   s
             r   add_foreign_key_constraintz)SchemaMigrator.add_foreign_key_constraint  s     % Ce>I>A)C
 'F5M"*+F4Z@AB($f[&9%;<='F3K F:&' 	  ++o	9:C ++o	9:C
r   c           
         |j                   s|j                  t        d|z        t        |t              }|r|j
                  st        d      | j                  |||      g}|j                   s4|j                  | j                  |||      | j                  ||      g       |rw| j                  rk|j                  | j                  |||j                  j                  j                  |j
                  j                   |j"                  |j$                               |j&                  s|j(                  r;t+        |dd       }|j                  | j-                  ||f|j(                  |             |S )Nz!%s is not null but has no defaultz$Foreign keys must specify a `field`.
index_type)rr   r^   rY   r!   ru   r   rx   extendrf   add_not_nullexplicit_create_foreign_keyappendr   r   r   rE   rd   r   r   indexuniquer,   	add_index)r   rc   rd   re   is_foreign_key
operationsusings          r   
add_columnzSchemaMigrator.add_column9  sG    zzemm3@;NOO#E?;%//CDD++E;FG
 zz""5+u=!!%57 8 d>>//OO))44OO//OOOO%& ;;%,,E<6EdnnU[N-2\\5B C r   c                     | j                   j                  |      D ],  }|j                  |k(  s|j                  s |j                  c S  t	        d|d|d      )Nz+Unable to find foreign key constraint for "z" on table "z".)r   get_foreign_keysro   rs   AttributeError)r   rc   rd   fks       r   get_foreign_key_constraintz)SchemaMigrator.get_foreign_key_constraint`  sT    --007 	ByyK'BGGww	 %0%9: 	:r   c                     t         r   NotImplementedError)r   rc   rd   s      r   drop_foreign_key_constraintz*SchemaMigrator.drop_foreign_key_constrainth      !!r   c                 t   | j                         }| j                  ||      j                  d      j                  t	        |             |r|j                  d       | j
                  j                  |      D cg c]  }|j                   }}||v r | j                  r| j                  ||      |gS |S c c}w )N DROP COLUMN  CASCADE)
rP   rj   r_   r`   r   r   r   ro   explicit_delete_foreign_keyr   )r   rc   rd   cascaderi   foreign_key
fk_columnss          r   drop_columnzSchemaMigrator.drop_columnl  s    !			3	&
'/
"
#f[!
"KK
#  $}}==eDF F
 F *$)I)I44UKH#NN
Fs   :B5c                     | j                  | j                         |      j                  d      j                  t	        |            j                  d      j                  t	        |            S )N RENAME COLUMN  TO r|   )r   rc   old_namenew_names       r   rename_columnzSchemaMigrator.rename_column~  sQ    d//159*+VH%&VH%&	(r   c                 b    | j                  | j                         ||      j                  d      S )Nz SET NOT NULLrp   rP   r_   r   rc   ro   s      r   r   zSchemaMigrator.add_not_null  s+    t002E6B)	+r   c                 b    | j                  | j                         ||      j                  d      S )Nz DROP NOT NULLr   r   s      r   drop_not_nullzSchemaMigrator.drop_not_null  s,    t002E6B)*	,r   c                 b   |t        d      t        |      r |       }t        |t              r|j	                  d      rt        |      }| j                  | j                         |      j                  d      j                  t        |            j                  d      j                  |      S )N `default` must be not None/NULL.r   'rl   z SET DEFAULT )rY   r   r!   strendswithr   rj   rP   r_   r`   r   )r   rc   ro   r^   s       r   add_column_defaultz!SchemaMigrator.add_column_default  s    ??@@WiG gs#(8(8(D'lGd//159)*VF^$)W	r   c                     | j                  | j                         |      j                  d      j                  t	        |            j                  d      S )Nrl   z DROP DEFAULTr|   r   s      r   drop_column_defaultz"SchemaMigrator.drop_column_default  sB    d//159)*VF^$)		+r   c                     | j                         }| j                  |||      j                  d      j                  |j	                  |            }|;t        |t              st        |      }|j                  d      j                  |      }|S )Nz TYPE z USING )rP   rp   r_   r`   ddl_datatyper!   r	   r   r   rc   ro   re   castri   s         r   alter_column_typez SchemaMigrator.alter_column_type  s     !c5&1!E&&s+, 	 dD)4y++i(,,T2C
r   c                     | j                  | j                         |      j                  d      j                  t	        |            S )Nz RENAME TO r|   r   r   r   s      r   rename_tablezSchemaMigrator.rename_table  s8    d//18<'VH%&	(r   c                     | j                         }t        ||      }t        |      }|D cg c]  }t        |j                  |       }	}t        |||	||      }
|j                  |
      S c c}w )N)r   r   )rP   rI   Tabler,   cIndexr`   )r   rc   rF   r   r   ri   rG   	table_objro   colsr   s              r   r   zSchemaMigrator.add_index  si    !$UG4
%L	;BC	V,CCj)T&Nwwu~ Ds   A,c                 p    | j                         j                  d      j                  t        |            S )NDROP INDEX rP   r_   r`   r   r   rc   rG   s      r   
drop_indexzSchemaMigrator.drop_index  s*    'VJ'(	*r   )NNN)Tr   )FN)!r-   r.   r/   r   r   transactional_ddlr   rP   classmethodr[   r9   rf   rj   rp   rx   r   r   r   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r1   r   r   rK   rK      s   "'"'!/ 	@ 	@ ! !>&  ( " " G G $ $
 =A37 2 $ $L: " "  " ( ( + +
 , ,
  " + +   ( (   * *r   rK   c                   N     e Zd Zd Zed        Ze fd       Zed        Z xZS )rT   c                     d}| j                   j                  ||f      }|j                         D cg c]  }|d   	 c}S c c}w )Nag  
            SELECT pg_attribute.attname
            FROM pg_index, pg_class, pg_attribute
            WHERE
                pg_class.oid = %s::regclass AND
                indrelid = pg_class.oid AND
                pg_attribute.attrelid = pg_class.oid AND
                pg_attribute.attnum = any(pg_index.indkey) AND
                indisprimary;
        r   )r   execute_sqlfetchall)r   tblquerycursorrows        r   _primary_key_columnsz'PostgresqlMigrator._primary_key_columns  sB    	 **53&9"(//"343A444s   Ac                 p    | j                         j                  d      j                  t        |            S )NzSET search_path TO r   )r   schema_names     r   set_search_pathz"PostgresqlMigrator.set_search_path  s+    ./VK()	+r   c                 n   | j                  |      }t        t        |       }|j                  ||d      g}t	        |      dk(  ro|d|d   d}d}| j
                  j                  ||f      }t        |j                               r,|d|d   d}	|j                  |j                  ||	             |S )NT)r*      r;   r   _seqz
                SELECT 1
                FROM information_schema.sequences
                WHERE LOWER(sequence_name) = LOWER(%s)
            )
r   superrT   r   r@   r   r   boolfetchoner   )r   r   r   pk_namesParentClassr   seq_namer   r   new_seq_name	__class__s             r   r   zPostgresqlMigrator.rename_table  s    ,,X6.5 $$Xxd$KM
 x=A&.<HE
 ]]..uxkBFFOO%&.6D!!+":":l#, - r   c                     | j                  ||      }| j                  | j                         |      j                  d      j	                  t        |            S r   r   rj   rP   r_   r`   r   r   rc   rd   fk_constraints       r   r   z.PostgresqlMigrator.drop_foreign_key_constraint  sK    77{Kd//159,-VM*+	-r   )	r-   r.   r/   r   r9   r   r   r   __classcell__)r   s   @r   rT   rT     sD    5 + +  . - -r   rT   c                   *    e Zd ZdZdZd Zed        Zy)rR   TFc                      y r   r1   r   s      r   rv   z%CockroachDBMigrator.add_inline_fk_sql      r   c                     | j                         j                  d      j                  t        |            j                  d      S )Nr   r   r   r   s      r   r   zCockroachDBMigrator.drop_index  s4    'VJ'($		&r   N)r-   r.   r/   r   r   rv   r9   r   r1   r   r   rR   rR   
  s'    "& & &r   rR   c                   D    e Zd Zed        Zed        Zed        ZddZy)MySQLColumnc                      | j                   dk(  S )NPRIpkrO   s    r   is_pkzMySQLColumn.is_pk      ww%r   c                      | j                   dk(  S )NUNIr  rO   s    r   	is_uniquezMySQLColumn.is_unique   r  r   c                      | j                   dk(  S )NYES)rr   rO   s    r   is_nullzMySQLColumn.is_null$  s    yyE!!r   Nc                    || j                   }|| j                  }t        |      t        | j                        g}| j
                  r|j                  t        d             |r|j                  t        d             n|j                  t        d             | j                  r|j                  t        d             | j                  r$|j                  t        | j                               t        |      S )Nr   NULLNOT NULLzPRIMARY KEY)
r  rs   r   r   
definitionr  r   r
  extrar
   )r   rd   r  partss       r   r`   zMySQLColumn.sql(  s    ?llG))K; " >>LLX'LLV%LLZ)::LL]+,::LLTZZ)r   NN)r-   r.   r/   propertyr
  r  r  r`   r1   r   r   r  r    sA            " "r   r  _Column)rs   r  rr   r	  r^   r  c                       e Zd ZdZdZdZd Zed        Zd Z	ed        Z
d Zed        Zed	        Zed
        Zedd       Zed        Zy)rV   TFc                 t    | j                  ||      j                  d      j                  t        |            S )N MODIFY rm   rn   s       r   rp   zMySQLMigrator._alter_columnB  s.    c5)$VF^$	&r   c                     | j                         j                  d      j                  t        |            j                  d      j                  t        |            S )NzRENAME TABLE r   r   r   s      r   r   zMySQLMigrator.rename_tableH  sB    )VH%&VH%&	(r   c                     |j                  dd      }| j                  j                  d|z        }|j                         }|D ]  }t	        | }|j
                  |k(  s|c S  y)N`z``zDESCRIBE `%s`;F)replacer   r   r   r  rs   )r   rc   rd   
table_safer   rowsr   ro   s           r   _get_column_definitionz$MySQLMigrator._get_column_definitionQ  sg    ]]3-
**+;j+HI  	C #&F{{k)	 r   c                     | j                  ||      }| j                  | j                         |      j                  d      j	                  t        |            S )Nz DROP FOREIGN KEY r   r   s       r   r   z)MySQLMigrator.drop_foreign_key_constraint[  sK    77{Kd//159-.VM*+	-r   c                      y r   r1   r   s      r   rv   zMySQLMigrator.add_inline_fk_sqlc  r  r   c           
         | j                  ||      }| j                  | j                         |      j                  d      j	                  |j	                  d            }t        d | j                  j                  |      D              }||vr|S ||   }| j                  ||      || j                  |||j                  |j                  |j                  |j                        fS )Nr  Fr  c              3   8   K   | ]  }|j                   |f  y wr   ro   .0r   s     r   	<genexpr>z-MySQLMigrator.add_not_null.<locals>.<genexpr>n         = YYO=   )r$  rj   rP   r_   r`   dictr   r   r   r   
dest_tabledest_columnr   r   )r   rc   ro   
column_defr   
fk_objectsfk_metadatas          r   r   zMySQLMigrator.add_not_nullf  s    00?
%d&7&7&95A ,Z^^E^:; 	
  =mm44U;= =
 # (00?//**++))))+, 	,r   c                     | j                  ||      }|j                  rt        d      | j                  | j	                         |      j                  d      j                  |j                  d            S )NzPrimary keys can not be nullr  Tr(  )r$  r
  rY   rj   rP   r_   r`   )r   rc   ro   r3  s       r   r   zMySQLMigrator.drop_not_null  se    00?
;<<d//159$Z^^D^12	4r   c           
      "   t        d | j                  j                  |      D              }||v }| j                  ||      }| j	                  | j                         |      j                  d      j                  t        |            j                  d      j                  |j                  |            }|rV||   }| j                  ||      || j                  |||j                  |j                  |j                  |j                        gS |S )Nc              3   8   K   | ]  }|j                   |f  y wr   r*  r+  s     r   r-  z.MySQLMigrator.rename_column.<locals>.<genexpr>  r.  r/  z CHANGE r{   )rd   )r0  r   r   r$  rj   rP   r_   r`   r   r   r   r1  r2  r   r   )	r   rc   r   r   r4  r   ro   
rename_ctxr5  s	            r   r   zMySQLMigrator.rename_column  s    =mm44U;= =
 "Z/,,UH=#|D$5$5$7?wz*s6(+,ws|s6::(:;< 	 $X.K00A//**++))))+
 
 r   Nc                    |t        d      | j                         }| j                  ||      j                  d      j	                  t        |            j                  d      j	                  |j                  |            S )Nz5alter_column_type() does not support cast with MySQL.r  r{   )rY   rP   rj   r_   r`   r   rt   r   s         r   r   zMySQLMigrator.alter_column_type  so     & ' '!c5)$VF^$UYYs^$	&r   c                     | j                         j                  d      j                  t        |            j                  d      j                  t        |            S )Nr   z ON r   r   s      r   r   zMySQLMigrator.drop_index  sA    'VJ'(VE]#	%r   r   )r-   r.   r/   r   r   r   rp   r9   r   r$  r   rv   r   r   r   r   r   r1   r   r   rV   rV   =  s    "&"&& ( ( - - , ,0 4 4  : 
& 
& % %r   rV   c                   |   e Zd ZdZ ej
                  d      Z ej
                  d      Z ej
                  d      Z ej
                  dej                        Z
d Zed        Zd Zedd	       Zedd
       Zed        Zed        Zed        Zed        Zedd       Zed        Zed        Ze	 dd       Zy)rX   z
    SQLite supports a subset of ALTER TABLE queries, view the docs for the
    full details http://sqlite.org/lang_altertable.html
    z(.+?)\((.+)\)z(?:[^,(]|\([^)]*\))+z["`']?([\w]+)z FOREIGN KEY\s+\("?([\w]+)"?\)\s+c                 z    | j                   j                  dd|j                         g      }|j                         S )NzBselect name, sql from sqlite_master where type=? and LOWER(name)=?rc   )r   r   lowerr   )r   rc   ress      r   _get_create_tablez SqliteMigrator._get_create_table  s7    mm''.ekkm$& ||~r   c                     t        d  j                  j                  |      D              }|j                         |vrt	        d|d|d       j                  |      \  }} j                  j                  |      }t        j                  dd|      } j                  j                  |      j                         \  }} j                  j                  |      }	|	D 
cg c]  }
|
j                          }}
g }g }g }d}|D ]  } j                  j!                  |      j                         \  }||k(  rk |||      }|s?|j#                  |       |j#                  |        j                  j!                  |      j                         \  }|j#                  |       |j#                  |       |j                         j%                  |      r|j#                  |       |j#                  |        t'        t)        ||            }|j+                  |      d }sd	 }n|k7  r fd
}g }|D ]Q  } j,                  j!                  |      }||j                         d   |k(  r ||      }|sA|j#                  |       S |dz   }t        j.                  dt        j0                  |      z  t        j2                        }|j                  d|z  |      }dj5                  |      }t7        t9        d      t;        |      g      t9        |j                         d|d      g}t7        t9        d      t;        |      t=        |D 
cg c]  }
t;        |
       c}
      t9        d      t?        |D 
cg c]  }
t;        |
       c}
      t9        d      t;        |      f      }t7        t9        d      t;        |      g      }||| jA                  ||      gz  }tC        d |      D ]r  }||jD                  vr%|j#                  t9        |jF                               6s9 jI                  |jF                  |      }|Y|j#                  t9        |             t |S c c}
w c c}
w c c}
w )Nc              3   P   K   | ]  }|j                   j                            y wr   )rs   r>  )r,  ro   s     r   r-  z0SqliteMigrator._update_column.<locals>.<genexpr>  s'      F  kk'') Fs   $&zColumn "z" does not exist on ""z\s+r{   )zforeign zprimary zconstraint zcheck zunique c                     | S r   r1   r3  s    r   <lambda>z/SqliteMigrator._update_column.<locals>.<lambda>  s    * r   c                      y r   r1   rE  s    r   rF  z/SqliteMigrator._update_column.<locals>.<lambda>      r   c                 B    j                   j                  dz  |       S )NzFOREIGN KEY ("%s") )fk_resub)r3  
new_columnr   s    r   rF  z/SqliteMigrator._update_column.<locals>.<lambda>  s    djjnn%
2/ r   r   __tmp__z("?)%s("?)\s*$z\1%s\2, zDROP TABLE IF EXISTSr   r   zINSERT INTOSELECTFROMz
DROP TABLEc                     | j                   S r   )r`   )idxs    r   rF  z/SqliteMigrator._update_column.<locals>.<lambda>7  s
     r   )%setr   get_columnsr>  rY   r@  get_indexesrerK  	column_researchgroupscolumn_split_refindallstripcolumn_name_rematchr   
startswithr0  zipgetrJ  compileescapeIr?   r
   r   r   r   r   r   filterrF   r`   
_fix_index) r   rc   column_to_updater5   rF   create_tableindexes
raw_createraw_columnssplit_columnscolcolumn_defsnew_column_defsnew_column_namesoriginal_column_namesconstraint_termsr3  rd   new_column_deforiginal_to_newfk_filter_fncleaned_columnsr^  
temp_tablergxcreatequeriespopulate_tabledrop_originalr   r`   rL  s    `                              @r   _update_columnzSqliteMigrator._update_column  s1    F$(MM$=$=e$DF F!!#72.7 8 8 #44U;| --++E2 vvfc<8 #'.."7"7"E"L"L"N
K ,,44[A.;<ssyy{<< "' & 	>J..44Z@GGILK..!#K!<!#**>:)00=#'#6#6#<#<&$((. !K$++K8&&z2 "'')445EF$++K8)00=#	>( s#8:JKL$(()9:
42L++L ) 	3JJJ$$Z0E U\\^A%6:J%J)*5
&&z2	3 Y&
jj*RYYu-==rttD
"
 ))O,c016*3EFGV\\^W568
 ":5EFcfSkFGM2GH36#;HIK5M#  !#l"3VE]!CD 	j%02 	2 /9 	-Eu}}4s599~.ooeii1A:N?NN3s8,	- s =D GHs   #Q(Q-;Q2c                 n   |j                  |      }t        |      dk(  r|j                  ||      S |j                  dd      \  }}t        |j                  |            dk(  r|d|j                  ||      S |j                  dd      d   j                  d      }|D cg c]  }|j	                  d       }}g }	|D ]P  }
t        j                  dt        j                  |      z  |
      r||
t        |      d  z   }
|	j                  |
       R |dd	j                  d
 |	D              dS c c}w )N   (r   r   r   ,z"`[]' z%s(?:[\'"`\]]?\s|$)rN  c              3   &   K   | ]	  }d |z    yw)z"%s"Nr1   )r,  r   s     r   r-  z,SqliteMigrator._fix_index.<locals>.<genexpr>_  s     )D&1*)Ds   )
splitr@   r!  rsplitr\  rV  r^  rc  r   r?   )r   r`   rg  rL  r  lhsrhspartrF   cleanro   s              r   rf  zSqliteMigrator._fix_indexA  s0    		*+u:?;;/<< ::c1%S syy)*+q0!3;;/?#LMM 

3"1%++C05:;T4::i(;;
  	!Fxx.;K1LL #fS1A-B-C&DDLL 		! 		)De)D DEE <s   #D2c                     t         j                  dk\  rM|sK| j                         }| j                  ||      j	                  d      j                  t        |             |S | j                  ||d       S )N)   #   r   r   c                      y r   r1   )abs     r   rF  z,SqliteMigrator.drop_column.<locals>.<lambda>i  rH  r   )r   sqlite_version_inforP   rj   r_   r`   r   r}  )r   rc   rd   r   legacyri   s         r   r   zSqliteMigrator.drop_columna  sd    &&*4V##%CsE*go&c&%&J""5+7HIIr   c                 :   t         j                  dk\  rp|sn| j                  | j                         |      j	                  d      j                  t        |            j	                  d      j                  t                    S fd}| j                  |||      S )N)r     r   r   r   c                 h    t        j                  dt        j                  |       z  dz  |d      S )Nz(["\'`]?)%s\1z	\g<1>%s\1r   )count)rV  rK  rc  )rd   r3  r   s     r   _renamez-SqliteMigrator.rename_column.<locals>._renamet  s5     66 299[#99x'	 r   )r   r  rj   rP   r_   r`   r   r}  )r   rc   r   r   r  r  s      `  r   r   zSqliteMigrator.rename_columnk  s~    &&*4V!\$"3"3"5u=W./S)*WV_S)*,	 ""5(G<<r   c                 .    d }| j                  |||      S )Nc                     |dz   S )Nz	 NOT NULLr1   rd   r3  s     r   _add_not_nullz2SqliteMigrator.add_not_null.<locals>._add_not_null  s    ++r   r}  )r   rc   ro   r  s       r   r   zSqliteMigrator.add_not_null  s    	,""5&-@@r   c                 .    d }| j                  |||      S )Nc                 &    |j                  dd      S )Nr   )r!  r  s     r   _drop_not_nullz4SqliteMigrator.drop_not_null.<locals>._drop_not_null  s    %%j"55r   r  )r   rc   ro   r  s       r   r   zSqliteMigrator.drop_not_null  s    	6""5&.AAr   c                     t        d      t              r        t        t              r6j	                  d      s%j                         sdj                  dd      z  fd}| j                  |||      S )Nr   r   z'%s'r   z''c                     |dz  z   S )Nz DEFAULT %sr1   )rd   r3  r^   s     r   _add_defaultz7SqliteMigrator.add_column_default.<locals>._add_default  s     777r   )rY   r   r!   r   r   isdigitr!  r}  )r   rc   ro   r^   r  s      ` r   r   z!SqliteMigrator.add_column_default  su    ??@@WiGw$W-=-=j-IOO%wsD99G	8 ""5&,??r   c                 .    d }| j                  |||      S )Nc                 p    t        j                  dd|t         j                        }|j                         S )NzDEFAULT\s+[\w"\'\(\)]+(\s|$)r  )flags)rV  rK  rd  r\  )rd   r3  rm  s      r   _drop_defaultz9SqliteMigrator.drop_column_default.<locals>._drop_default  s*    &&8"j!tt%C99;r   r  )r   rc   ro   r  s       r   r   z"SqliteMigrator.drop_column_default  s    	 ""5&-@@r   Nc                 v    |t        d      | j                         fd}| j                  ||      S )Nz6alter_column_type() does not support cast with Sqlite.c                     j                        }j                  t                    j                  |      j                         \  }}|S r   )rt   r`   r   r   )rd   r3  	node_listr`   r;   ro   ri   re   s        r   _alter_column_typez<SqliteMigrator.alter_column_type.<locals>._alter_column_type  s?    		#IWWVF^,00;AACFCJr   )rY   rP   r}  )r   rc   ro   re   r   r  ri   s     ``  @r   r   z SqliteMigrator.alter_column_type  sF     ' ( (!	 ""5&2DEEr   c                     t         r   r   r}   s       r   r   zSqliteMigrator.add_constraint  r   r   c                     t         r   r   r   s      r   r   zSqliteMigrator.drop_constraint  r   r   c                     t         r   r   )r   rc   rd   re   r   r   s         r   r   z)SqliteMigrator.add_foreign_key_constraint  s
     "!r   )TF)Fr   r  )r-   r.   r/   r0   rV  rb  rW  rZ  r]  rd  rJ  r@  r9   r}  rf  r   r   r   r   r   r   r   r   r   r   r1   r   r   rX   rX     sM    

+,I bjj!89ORZZ 45NBJJ:BDDAE o obF@ J J = =& A A
 B B
 @ @ A A 	F 	F " " " " =A" "r   rX   c                  2    | D ]  }|j                           y r   )r#   )r   r   r9   s      r   migrater    s     	r   )r0   collectionsr   r7   rA   rV  peeweer   r   r   r   r	   r
   r   r   r   r   playhouse.cockroachdbr   ImportErrorobjectr   r9   rI   rK   rT   rR   r  rV   rX   r  r1   r   r   <module>r     s   qd #   	    #        ,7
: :6Z*V Z*z4- 4-n&, &  *Y )= >  F~%N ~%Bz"^ z"zm  s   B; ;CC