Your IP : 216.73.216.213


Current Path : /opt/alt/python35/lib64/python3.5/site-packages/playhouse/__pycache__/
Upload File :
Current File : //opt/alt/python35/lib64/python3.5/site-packages/playhouse/__pycache__/migrate.cpython-35.pyc



R6�W�]�@sGdZddlmZddlZddlZddlTddlmZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZGdd�de�Z
d
d�ZGdd�de�ZGdd�de�Zd"ZGdd�dede��ZGdd�de�ZGdd�de�Zd d!�ZdS)#a�

Lightweight schema migrations.

NOTE: Currently tested with SQLite and Postgresql. MySQL may be missing some
features.

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'))
�)�
namedtupleN)�*)�CommaClause)�EnclosedClause)�Entity)�
Expression)�Node)�OPc@sReZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�	Operationz/Encapsulate a single schema altering operation.cOs(||_||_||_||_dS)N)�migrator�method�args�kwargs)�selfrrr
r�r�D/opt/alt/python35/lib64/python3.5/site-packages/playhouse/migrate.py�__init__us			zOperation.__init__cCs|jjj�}|j|�S)N)r�database�compiler�
parse_node)r�noderrrr�_parse_node{szOperation._parse_nodecCs/|j|�\}}|jjj||�dS)N)rrr�execute_sql)rr�sql�paramsrrr�executeszOperation.executecCsrt|t�r|j|�nOt|t�r;|j�n3t|ttf�rnx|D]}|j|�qWWdS)N)�
isinstancerrr
�run�list�tuple�_handle_result)r�result�itemrrrr �s

zOperation._handle_resultcCsE|jj�}d|d<|jt|j|j�|j|��dS)NT�generate)r�copyr �getattrrrr
)rrrrrr�s
z
Operation.runN)	�__name__�
__module__�__qualname__�__doc__rrrr rrrrrr
ss	r
cs%tj���fdd��}|S)Ncs>|jdd�}|r(�|||�St|�j||�S)Nr#F)�popr
r&)rr
rr#)�fnrr�inner�szoperation.<locals>.inner)�	functools�wraps)r+r,r)r+r�	operation�s!r/c@s0eZdZdZdZdd�Zedd��Zedd��Z	edd	��Z
d
d�Zedd
��Zedd��Z
edd��Zeddd��Zedd��Zdd�Zedd��Zedd��Zedd��Zeddd ��Zed!d"��Zd#S)$�SchemaMigratorFcCs
||_dS)N)r)rrrrrr�szSchemaMigrator.__init__cCs@t|t�rt|�St|t�r2t|�St|�SdS)N)r�PostgresqlDatabase�PostgresqlMigrator�
MySQLDatabase�
MySQLMigrator�SqliteMigrator)�clsrrrr�
from_database�s


zSchemaMigrator.from_databasec
Csm|j}t|�r|�}ttd�t|�td�tt|�tjt|j	|��dd��S)N�UPDATE�SET�flatT)
�default�callable�Clause�SQLrrr	�EQ�Param�db_value)r�table�column_name�fieldr;rrr�
apply_default�s						zSchemaMigrator.apply_defaultcCs�|jd}|_||_|_|jj�j|�}||_td�t|�td�|g}t|t	�r�|j
|j|��t|�S)NTzALTER TABLEz
ADD COLUMN)
�null�name�	db_columnrr�field_definitionr>rr�ForeignKeyField�extend�get_inline_fk_sqlr=)rrBrCrDZ
field_nullZfield_clause�partsrrr�alter_add_column�s					zSchemaMigrator.alter_add_columncCs4td�t|jjj�tt|jj��gS)N�
REFERENCES)r>r�	rel_model�_meta�db_tabler�to_fieldrH)rrDrrrrL�s	z SchemaMigrator.get_inline_fk_sqlcCs
t�dS)N)�NotImplementedError)rrBrCrDrrr�add_foreign_key_constraint�sz)SchemaMigrator.add_foreign_key_constraintcCs�|jr)|jdkr)td|��t|t�}|rT|jrTtd��|j|||�g}|js�|j|j|||�|j	||�g�|r�|j
r�|j|j|||j
jj|jj��|S)Nz!%s is not null but has no defaultz'Foreign keys must specify a `to_field`.)rFr;�
ValueErrorrrJrSrNrKrE�add_not_null�explicit_create_foreign_key�appendrUrPrQrRrH)rrBrCrD�is_foreign_key�
operationsrrr�
add_column�s$	zSchemaMigrator.add_columncCs
t�dS)N)rT)rrBrCrrr�drop_foreign_key_constraint�sz*SchemaMigrator.drop_foreign_key_constraintTcCs�td�t|�td�t|�g}|rC|jtd��t|�}dd�|jj|�D�}||kr�|jr�|j||�|gS|SdS)NzALTER TABLEzDROP COLUMN�CASCADEcSsg|]}|j�qSr)�column)�.0�foreign_keyrrr�
<listcomp>s	z.SchemaMigrator.drop_column.<locals>.<listcomp>)r>rrYr=r�get_foreign_keys�explicit_delete_foreign_keyr])rrBrC�cascade�nodesZdrop_column_nodeZ
fk_columnsrrr�drop_column�s				zSchemaMigrator.drop_columncCs=ttd�t|�td�t|�td�t|��S)NzALTER TABLEz
RENAME COLUMN�TO)r=r>r)rrB�old_name�new_namerrr�
rename_columns					zSchemaMigrator.rename_columncCs(td�t|�td�t|�gS)NzALTER TABLEzALTER COLUMN)r>r)rrBr_rrr�
_alter_columns			zSchemaMigrator._alter_columncCs/|j||�}|jtd��t|�S)NzSET NOT NULL)rlrYr>r=)rrBr_rfrrrrW"szSchemaMigrator.add_not_nullcCs/|j||�}|jtd��t|�S)Nz
DROP NOT NULL)rlrYr>r=)rrBr_rfrrr�
drop_not_null(szSchemaMigrator.drop_not_nullcCs+ttd�t|�td�t|��S)NzALTER TABLEz	RENAME TO)r=r>r)rrirjrrr�rename_table.s
			zSchemaMigrator.rename_tablecCsn|jj�}|rdnd}tt|�t|j||��td�t|�tdd�|D���S)NzCREATE UNIQUE INDEXzCREATE INDEX�ONcSsg|]}t|��qSr)r)r`r_rrrrb?s	z,SchemaMigrator.add_index.<locals>.<listcomp>)rrr=r>r�
index_namer)rrB�columns�uniquer�	statementrrr�	add_index6s			zSchemaMigrator.add_indexcCsttd�t|��S)Nz
DROP INDEX)r=r>r)rrBrprrr�
drop_indexAs	zSchemaMigrator.drop_indexN)r&r'r(rXrdr�classmethodr7r/rErNrLrUr\r]rgrkrlrWrmrnrtrurrrrr0�s(	"

r0cs4eZdZdd�Ze�fdd��Z�S)r2cCs3d}|jj||�}dd�|j�D�S)Nai
            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;
        cSsg|]}|d�qS)rr)r`�rowrrrrbUs	z;PostgresqlMigrator._primary_key_columns.<locals>.<listcomp>)rr�fetchall)rZtbl�query�cursorrrr�_primary_key_columnsIs
z'PostgresqlMigrator._primary_key_columnsc
s�|j|�}tt|�}|j||dd�g}t|�dkr�d||df}d}|jj||f�}t|j��r�d||df}	|j	|j||	dd��|S)Nr#T�z	%s_%s_seqrz�
                SELECT 1
                FROM information_schema.sequences
                WHERE LOWER(sequence_name) = LOWER(%s)
            )
r{�superr2rn�lenrr�bool�fetchonerY)
rrirjZpk_namesZParentClassr[Zseq_nameryrzZnew_seq_name)�	__class__rrrnWszPostgresqlMigrator.rename_table)r&r'r(r{r/rnrr)r�rr2Hsr2rG�
definitionrF�pkr;�extrac@sXeZdZedd��Zedd��Zedd��Zdddd	�ZdS)
�MySQLColumncCs
|jdkS)NZPRI)r�)rrrr�is_pkrszMySQLColumn.is_pkcCs
|jdkS)NZUNI)r�)rrrr�	is_uniquevszMySQLColumn.is_uniquecCs
|jdkS)N�YES)rF)rrrr�is_nullzszMySQLColumn.is_nullNcCs�|dkr|j}|dkr*|j}t|�t|j�g}|jra|jtd��|r}|jtd��n|jtd��|jr�|jtd��|jr�|jt|j��t	|�S)NZUNIQUE�NULLzNOT NULLzPRIMARY KEY)
r�rGrr>r�r�rYr�r�r=)rrCr�rMrrrr~s 						zMySQLColumn.sql)r&r'r(�propertyr�r�r�rrrrrr�qsr�Z_Columnc@s�eZdZdZdZedd��Zdd�Zedd��Zdd	�Z	ed
d��Z
dd
�Zedd��Zedd��Z
edd��Zedd��ZdS)r4TcCs+ttd�t|�td�t|��S)NzRENAME TABLErh)r=r>r)rrirjrrrrn�s
			zMySQLMigrator.rename_tablecCsV|jjd|�}|j�}x-|D]%}t|�}|j|kr)|Sq)WdS)NzDESCRIBE %s;F)rrrxr�rG)rrBrCrz�rowsrwr_rrr�_get_column_definition�s
z$MySQLMigrator._get_column_definitioncCswd|||f}ttd�t|�td�t|�td�tt|��td�t|�tt|���	S)Nzfk_%s_%s_refs_%szALTER TABLEzADD CONSTRAINTzFOREIGN KEYrO)r=r>rr)rrBrC�relZ
rel_column�
constraintrrrrU�s							z(MySQLMigrator.add_foreign_key_constraintcCsK|jjd||f�}|j�}|sCtd||f��|dS)Nz�SELECT constraint_name FROM information_schema.key_column_usage WHERE table_schema = DATABASE() AND table_name = %s AND column_name = %s;z=Unable to find foreign key constraint for "%s" on table "%s".r)rrr��AttributeError)rrBrCrzr!rrr�get_foreign_key_constraint�s	z(MySQLMigrator.get_foreign_key_constraintcCs7ttd�t|�td�t|j||���S)NzALTER TABLEzDROP FOREIGN KEY)r=r>rr�)rrBrCrrrr]�s
			z)MySQLMigrator.drop_foreign_key_constraintcCsgS)Nr)rrDrrrrL�szMySQLMigrator.get_inline_fk_sqlcCsC|j||�}ttd�t|�td�|jdd��S)NzALTER TABLE�MODIFYr�F)r�r=r>rr)rrBr_rrrrW�s			zMySQLMigrator.add_not_nullcCsX|j||�}|jr'td��ttd�t|�td�|jdd��S)NzPrimary keys can not be nullzALTER TABLEr�r�T)r�r�rVr=r>rr)rrBr_rrrrm�s				zMySQLMigrator.drop_not_nullc	Cs�tdd�|jj|�D��}||k}|j||�}ttd�t|�td�t|�|jd|��}|r�||}|j||�||j	|||j
|j�gS|SdS)Ncss|]}|j|fVqdS)N)r_)r`�fkrrr�	<genexpr>�sz.MySQLMigrator.rename_column.<locals>.<genexpr>zALTER TABLEZCHANGErC)�dictrrcr�r=r>rrr]rU�
dest_table�dest_column)	rrBrirjZ
fk_objectsrZr_Z
rename_clauseZfk_metadatarrrrk�s*					

zMySQLMigrator.rename_columncCs+ttd�t|�td�t|��S)Nz
DROP INDEXro)r=r>r)rrBrprrrrus
			zMySQLMigrator.drop_indexN)r&r'r(rXrdr/rnr�rUr�r]rLrWrmrkrurrrrr4�s		r4c@s�eZdZdZejd�Zejd�Zejd�Zejdej	�Z
dd�Zdd	�Ze
d
d��Zdd
�Ze
ddd��Ze
dd��Ze
dd��Ze
dd��ZdS)r5z�
    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+cCs*|jjd|�}dd�|jD�S)Nzselect * from "%s" limit 1cSsg|]}|d�qS)rr)r`r"rrrrbs	z4SqliteMigrator._get_column_names.<locals>.<listcomp>)rr�description)rrB�resrrr�_get_column_namessz SqliteMigrator._get_column_namescCs+|jjdd|j�g�}|j�S)NzBselect name, sql from sqlite_master where type=? and LOWER(name)=?rB)rr�lowerr�)rrBr�rrr�_get_create_tables	z SqliteMigrator._get_create_tablec	s>tdd��jj|�D��}|j�|krMtd||f���j|�\}}�jj|�}�jj|�tj	dd|�}�j
j|�j�\}}�j
j|�}	dd�|	D�}
g}g}g}
x�|
D]�}�jj|�j�\}||kr||||�}|r�|j|�|
j|��jj|�j�\}|j|�q�|j|�|j�jd�s�|j|�|
j|�q�Wtt|
|��}|j|��d
d�}�sdd�}n!�|kr"��fd
d�}g}xa|D]Y}�jj|�}|dk	ru|j�d|kru||�}|r/|j|�q/W|d}tjd|tj�}|j	d||�}dj|�}ttd�t|��td|j�|f�g}ttd�t|�tdd�|D��td�tdd�|
D��td�t|��}|j|�|jttd�t|���|j�j ||��x�t!dd�|�D]k}||j"kr�|jt|j#��q��r��j$|j#|��}|dk	r�|jt|��q�W|S)Ncss|]}|jj�VqdS)N)rGr�)r`r_rrrr� sz0SqliteMigrator._update_column.<locals>.<genexpr>z"Column "%s" does not exist on "%s"z\s+� cSsg|]}|j��qSr)�strip)r`�colrrrrb8s	z1SqliteMigrator._update_column.<locals>.<listcomp>�foreign�primarycSs|S)Nr)�
column_defrrr�<lambda>Ssz/SqliteMigrator._update_column.<locals>.<lambda>cSsdS)Nr)r�rrrr�Vscs�jjd�|�S)NzFOREIGN KEY ("%s") )�fk_re�sub)r�)�
new_columnrrrr�Ys	rZ__tmp__z
("?)%s("?)z\1%s\2z, zDROP TABLE IF EXISTSz%s (%s)zINSERT INTOcSsg|]}t|��qSr)r)r`r�rrrrbvs	�SELECTcSsg|]}t|��qSr)r)r`r�rrrrbxs	�FROMz
DROP TABLEcSs|jS)N)r)�idxrrrr��s)r�r�)%�setr�get_columnsr�rVr��get_indexesrc�rer��	column_re�search�groups�column_split_re�findall�column_name_re�matchrY�
startswithr��zip�getr��compile�I�joinr=r>rr�rrrn�filterrqr�
_fix_index)rrB�column_to_updater+rq�create_table�indexesZ
raw_createZraw_columnsZ
split_columnsZcolumn_defsZnew_column_defsZnew_column_namesZoriginal_column_namesr�rCZnew_column_defZoriginal_to_newZfk_filter_fnZcleaned_columnsr�Z
temp_tableZrgx�create�queriesZpopulate_table�indexrr)r�rr�_update_columns�


	


"
					
		zSqliteMigrator._update_columnc
Cs(|j|�}t|�dkr1|j||�S|jdd�\}}t|j|��dkr~d||j||�fS|jdd�djd�}dd	�|D�}g}xK|D]C}	tjd
||	�r�t|	t|�d�}	|j|	�q�Wd|djd
d�|D��fS)N��(r|z%s(%s�)r�,cSsg|]}|jd��qS)z"`[]' )r�)r`�partrrrrb�s	z-SqliteMigrator._fix_index.<locals>.<listcomp>z%s(?:['"`\]]?\s|$)z%s(%s)z, css|]}d|VqdS)z"%s"Nr)r`�crrrr��sz,SqliteMigrator._fix_index.<locals>.<genexpr>)	�splitr~�replace�rsplitr�r�Znew_columnerYr�)
rrr�r�rM�lhs�rhsrq�cleanr_rrrr��s
zSqliteMigrator._fix_indexTcCs|j||dd��S)NcSsdS)Nr)�a�brrrr��sz,SqliteMigrator.drop_column.<locals>.<lambda>)r�)rrBrCrerrrrg�szSqliteMigrator.drop_columncs%�fdd�}|j|||�S)Ncs|j|��S)N)r�)rCr�)rjrr�_rename�sz-SqliteMigrator.rename_column.<locals>._rename)r�)rrBrirjr�r)rjrrk�szSqliteMigrator.rename_columncCsdd�}|j|||�S)NcSs|dS)Nz	 NOT NULLr)rCr�rrr�
_add_not_null�sz2SqliteMigrator.add_not_null.<locals>._add_not_null)r�)rrBr_r�rrrrW�szSqliteMigrator.add_not_nullcCsdd�}|j|||�S)NcSs|jdd�S)NzNOT NULL�)r�)rCr�rrr�_drop_not_null�sz4SqliteMigrator.drop_not_null.<locals>._drop_not_null)r�)rrBr_r�rrrrm�szSqliteMigrator.drop_not_nullN)r&r'r(r)r�r�r�r�r�r�r�r�r�r/r�r�rgrkrWrmrrrrr5	sqr5cOsx|D]}|j�qWdS)N)r)r[rr/rrr�migrate�s
r�)rGr�rFr�r;r�)r)�collectionsrr-r��peeweerrrrrr	�objectr
r/r0r2Z_column_attributesr�r4r5r�rrrr�<module>es&
 	�'"v�