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



R6W]@sGdZddlmZddlZddlZddlTddlmZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZGdddeZ
d
dZGdddeZGdddeZd"ZGdddedeZGdddeZGdddeZd 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@sReZdZdZddZddZddZdd	Zd
dZdS)
	Operationz/Encapsulate a single schema altering operation.cOs(||_||_||_||_dS)N)migratormethodargskwargs)selfrrr
rr/migrate.py__init__us			zOperation.__init__cCs|jjj}|j|S)N)rdatabasecompilerZ
parse_node)rnoderrrr_parse_node{szOperation._parse_nodecCs/|j|\}}|jjj||dS)N)rrrexecute_sql)rrsqlZparamsrrrexecuteszOperation.executecCsrt|tr|j|nOt|tr;|jn3t|ttfrnx|D]}|j|qWWdS)N)
isinstancerrr
runlisttuple_handle_result)rresultitemrrrrs

zOperation._handle_resultcCsE|jj}d|d<|jt|j|j|j|dS)NTgenerate)rcopyrgetattrrrr
)rrrrrrs
z
Operation.runN)	__name__
__module____qualname____doc__rrrrrrrrrr
ss	r
cs%tjfdd}|S)Ncs>|jdd}|r(|||St|j||S)Nr!F)popr
r$)rr
rr!)fnrrinnerszoperation.<locals>.inner)	functoolswraps)r)r*r)r)r	operations!r-c@s0eZdZdZdZddZeddZeddZ	edd	Z
d
dZedd
ZeddZ
eddZedddZeddZddZeddZeddZeddZeddd Zed!d"Zd#S)$SchemaMigratorFcCs
||_dS)N)r)rrrrrrszSchemaMigrator.__init__cCs@t|trt|St|tr2t|St|SdS)N)rZPostgresqlDatabasePostgresqlMigratorZ
MySQLDatabase
MySQLMigratorSqliteMigrator)clsrrrr
from_databases


zSchemaMigrator.from_databasec
Csm|j}t|r|}ttdt|tdtt|tjt|j	|ddS)NZUPDATEZSETZflatT)
defaultcallableClauseSQLrrr	ZEQZParamZdb_value)rtablecolumn_namefieldr4rrr
apply_defaults						zSchemaMigrator.apply_defaultcCs|jd}|_||_|_|jjj|}||_tdt|td|g}t|t	r|j
|j|t|S)NTzALTER TABLEz
ADD COLUMN)
nullname	db_columnrrZfield_definitionr7rrForeignKeyFieldextendget_inline_fk_sqlr6)rr8r9r:Z
field_nullZfield_clausepartsrrralter_add_columns					zSchemaMigrator.alter_add_columncCs4tdt|jjjtt|jjgS)N
REFERENCES)r7r	rel_model_metadb_tablerto_fieldr>)rr:rrrrAs	z SchemaMigrator.get_inline_fk_sqlcCs
tdS)N)NotImplementedError)rr8r9r:rrradd_foreign_key_constraintsz)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`.)r<r4
ValueErrorrr?rHrCr@r;add_not_nullexplicit_create_foreign_keyappendrJrErFrGr>)rr8r9r:is_foreign_key
operationsrrr
add_columns$	zSchemaMigrator.add_columncCs
tdS)N)rI)rr8r9rrrdrop_foreign_key_constraintsz*SchemaMigrator.drop_foreign_key_constraintTcCstdt|tdt|g}|rC|jtdt|}dd|jj|D}||kr|jr|j|||gS|SdS)NzALTER TABLEzDROP COLUMNZCASCADEcSsg|]}|jqSr)column).0Zforeign_keyrrr
<listcomp>s	z.SchemaMigrator.drop_column.<locals>.<listcomp>)r7rrNr6rget_foreign_keysexplicit_delete_foreign_keyrR)rr8r9cascadenodesZdrop_column_nodeZ
fk_columnsrrrdrop_columns				zSchemaMigrator.drop_columncCs=ttdt|tdt|tdt|S)NzALTER TABLEz
RENAME COLUMNTO)r6r7r)rr8old_namenew_namerrr
rename_columns					zSchemaMigrator.rename_columncCs(tdt|tdt|gS)NzALTER TABLEzALTER COLUMN)r7r)rr8rSrrr
_alter_columns			zSchemaMigrator._alter_columncCs/|j||}|jtdt|S)NzSET NOT NULL)r_rNr7r6)rr8rSrYrrrrL"szSchemaMigrator.add_not_nullcCs/|j||}|jtdt|S)Nz
DROP NOT NULL)r_rNr7r6)rr8rSrYrrr
drop_not_null(szSchemaMigrator.drop_not_nullcCs+ttdt|tdt|S)NzALTER TABLEz	RENAME TO)r6r7r)rr\r]rrrrename_table.s
			zSchemaMigrator.rename_tablecCsn|jj}|rdnd}tt|t|j||tdt|tdd|DS)NzCREATE UNIQUE INDEXzCREATE INDEXONcSsg|]}t|qSr)r)rTrSrrrrU?s	z,SchemaMigrator.add_index.<locals>.<listcomp>)rrr6r7r
index_namer)rr8columnsuniquerZ	statementrrr	add_index6s			zSchemaMigrator.add_indexcCsttdt|S)Nz
DROP INDEX)r6r7r)rr8rcrrr
drop_indexAs	zSchemaMigrator.drop_indexN)r$r%r&rMrWrclassmethodr3r-r;rCrArJrQrRrZr^r_rLr`rarfrgrrrrr.s(	"

r.cs4eZdZddZefddZS)r/cCs3d}|jj||}dd|jDS)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|]}|dqS)rr)rTrowrrrrUUs	z;PostgresqlMigrator._primary_key_columns.<locals>.<listcomp>)rrfetchall)rZtblquerycursorrrr_primary_key_columnsIs
z'PostgresqlMigrator._primary_key_columnsc
s|j|}tt|}|j||ddg}t|dkrd||df}d}|jj||f}t|jrd||df}	|j	|j||	dd|S)Nr!Tz	%s_%s_seqrz
                SELECT 1
                FROM information_schema.sequences
                WHERE LOWER(sequence_name) = LOWER(%s)
            )
rmsuperr/ralenrrboolfetchonerN)
rr\r]Zpk_namesZParentClassrPZseq_namerkrlZnew_seq_name)	__class__rrraWszPostgresqlMigrator.rename_table)r$r%r&rmr-rarr)rsrr/Hsr/r=
definitionr<pkr4extrac@sXeZdZeddZeddZeddZdddd	ZdS)
MySQLColumncCs
|jdkS)NZPRI)ru)rrrris_pkrszMySQLColumn.is_pkcCs
|jdkS)NZUNI)ru)rrrr	is_uniquevszMySQLColumn.is_uniquecCs
|jdkS)NZYES)r<)rrrris_nullzszMySQLColumn.is_nullNcCs|dkr|j}|dkr*|j}t|t|jg}|jra|jtd|r}|jtdn|jtd|jr|jtd|jr|jt|jt	|S)NZUNIQUEZNULLzNOT NULLzPRIMARY KEY)
rzr=rr7rtryrNrxrvr6)rr9rzrBrrrr~s 						zMySQLColumn.sql)r$r%r&propertyrxryrzrrrrrrwqsrwZ_Columnc@seZdZdZdZeddZddZeddZdd	Z	ed
dZ
dd
ZeddZeddZ
eddZeddZdS)r0TcCs+ttdt|tdt|S)NzRENAME TABLEr[)r6r7r)rr\r]rrrras
			zMySQLMigrator.rename_tablecCsV|jjd|}|j}x-|D]%}t|}|j|kr)|Sq)WdS)NzDESCRIBE %s;F)rrrjrwr=)rr8r9rlZrowsrirSrrr_get_column_definitions
z$MySQLMigrator._get_column_definitioncCswd|||f}ttdt|tdt|tdtt|tdt|tt|	S)Nzfk_%s_%s_refs_%szALTER TABLEzADD CONSTRAINTzFOREIGN KEYrD)r6r7rr)rr8r9ZrelZ
rel_columnZ
constraintrrrrJs							z(MySQLMigrator.add_foreign_key_constraintcCsK|jjd||f}|j}|sCtd||f|dS)NzSELECT 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)rrrrAttributeError)rr8r9rlrrrrget_foreign_key_constraints	z(MySQLMigrator.get_foreign_key_constraintcCs7ttdt|tdt|j||S)NzALTER TABLEzDROP FOREIGN KEY)r6r7rr~)rr8r9rrrrRs
			z)MySQLMigrator.drop_foreign_key_constraintcCsgS)Nr)rr:rrrrAszMySQLMigrator.get_inline_fk_sqlcCsC|j||}ttdt|td|jddS)NzALTER TABLEMODIFYrzF)r|r6r7rr)rr8rSrrrrLs			zMySQLMigrator.add_not_nullcCsX|j||}|jr'tdttdt|td|jddS)NzPrimary keys can not be nullzALTER TABLErrzT)r|rxrKr6r7rr)rr8rSrrrr`s				zMySQLMigrator.drop_not_nullc	Cstdd|jj|D}||k}|j||}ttdt|tdt||jd|}|r||}|j||||j	|||j
|jgS|SdS)Ncss|]}|j|fVqdS)N)rS)rTZfkrrr	<genexpr>sz.MySQLMigrator.rename_column.<locals>.<genexpr>zALTER TABLEZCHANGEr9)dictrrVr|r6r7rrrRrJZ
dest_tableZdest_column)	rr8r\r]Z
fk_objectsrOrSZ
rename_clauseZfk_metadatarrrr^s*					

zMySQLMigrator.rename_columncCs+ttdt|tdt|S)Nz
DROP INDEXrb)r6r7r)rr8rcrrrrgs
			zMySQLMigrator.drop_indexN)r$r%r&rMrWr-rar|rJr~rRrArLr`r^rgrrrrr0s		r0c@seZdZdZejdZejdZejdZejdej	Z
ddZdd	Ze
d
dZdd
Ze
dddZe
ddZe
ddZe
ddZdS)r1z
    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|jDS)Nzselect * from "%s" limit 1cSsg|]}|dqS)rr)rTr rrrrUs	z4SqliteMigrator._get_column_names.<locals>.<listcomp>)rrdescription)rr8resrrr_get_column_namessz SqliteMigrator._get_column_namescCs+|jjdd|jg}|jS)NzBselect name, sql from sqlite_master where type=? and LOWER(name)=?r8)rrlowerrr)rr8rrrr_get_create_tables	z SqliteMigrator._get_create_tablec	s>tddjj|D}|j|krMtd||fj|\}}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||jjds|j||
j|qWtt|
|}|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|}ttdt|td|j|fg}ttdt|tdd|Dtdtdd|
Dtdt|}|j||jttdt||jj ||xt!dd|D]k}||j"kr|jt|j#qrj$|j#|}|dk	r|jt|qW|S)Ncss|]}|jjVqdS)N)r=r)rTrSrrrr sz0SqliteMigrator._update_column.<locals>.<genexpr>z"Column "%s" does not exist on "%s"z\s+ cSsg|]}|jqSr)strip)rTcolrrrrU8s	z1SqliteMigrator._update_column.<locals>.<listcomp>foreignprimarycSs|S)Nr)
column_defrrr<lambda>Ssz/SqliteMigrator._update_column.<locals>.<lambda>cSsdS)Nr)rrrrrVscsjjd|S)NzFOREIGN KEY ("%s") )fk_resub)r)
new_columnrrrrYs	rZ__tmp__z
("?)%s("?)z\1%s\2z, zDROP TABLE IF EXISTSz%s (%s)zINSERT INTOcSsg|]}t|qSr)r)rTrrrrrUvs	ZSELECTcSsg|]}t|qSr)r)rTrrrrrUxs	ZFROMz
DROP TABLEcSs|jS)N)r)idxrrrrs)rr)%setrZget_columnsrrKrZget_indexesrVrer	column_researchgroupscolumn_split_refindallcolumn_name_rematchrN
startswithrzipgetrcompileIjoinr6r7rrrrrafilterrdr
_fix_index)rr8column_to_updater)rdZcreate_tableZindexesZ
raw_createZraw_columnsZ
split_columnsZcolumn_defsZnew_column_defsZnew_column_namesZoriginal_column_namesrr9Znew_column_defZoriginal_to_newZfk_filter_fnZcleaned_columnsrZ
temp_tableZrgxZcreateZqueriesZpopulate_tableindexrr)rrr_update_columns


	


"
					
		zSqliteMigrator._update_columnc
Cs(|j|}t|dkr1|j||S|jdd\}}t|j|dkr~d||j||fS|jdddjd}dd	|D}g}xK|D]C}	tjd
||	rt|	t|d}	|j|	qWd|djd
d|DfS)N(rnz%s(%s)r,cSsg|]}|jdqS)z"`[]' )r)rTpartrrrrUs	z-SqliteMigrator._fix_index.<locals>.<listcomp>z%s(?:['"`\]]?\s|$)z%s(%s)z, css|]}d|VqdS)z"%s"Nr)rTcrrrrsz,SqliteMigrator._fix_index.<locals>.<genexpr>)	splitrpreplacersplitrrZnew_columnerNr)
rrrrrBZlhsZrhsrdZcleanrSrrrrs
zSqliteMigrator._fix_indexTcCs|j||ddS)NcSsdS)Nr)abrrrrsz,SqliteMigrator.drop_column.<locals>.<lambda>)r)rr8r9rXrrrrZszSqliteMigrator.drop_columncs%fdd}|j|||S)Ncs|j|S)N)r)r9r)r]rr_renamesz-SqliteMigrator.rename_column.<locals>._rename)r)rr8r\r]rr)r]rr^szSqliteMigrator.rename_columncCsdd}|j|||S)NcSs|dS)Nz	 NOT NULLr)r9rrrr
_add_not_nullsz2SqliteMigrator.add_not_null.<locals>._add_not_null)r)rr8rSrrrrrLszSqliteMigrator.add_not_nullcCsdd}|j|||S)NcSs|jddS)NzNOT NULL)r)r9rrrr_drop_not_nullsz4SqliteMigrator.drop_not_null.<locals>._drop_not_null)r)rr8rSrrrrr`szSqliteMigrator.drop_not_nullN)r$r%r&r'rrrrrrrrrr-rrrZr^rLr`rrrrr1	sqr1cOsx|D]}|jqWdS)N)r)rPrr-rrrmigrates
r)r=rtr<rur4rv)r'collectionsrr+rZpeeweerrrrrr	objectr
r-r.r/Z_column_attributesrwr0r1rrrrr<module>es&
 	'"v
Back to Directory File Manager