3
g?                 @   s~   d dl Z d dlZd dlmZ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mZmZmZ d	ZG d
d dZdS )    N)import_modulereload)apps)settings)MigrationGraph)MigrationRecorder   )AmbiguityErrorBadMigrationErrorInconsistentMigrationHistoryNodeNotFoundErrorZ
migrationsc               @   s   e Zd ZdZdddZedd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zd ddZdd ZdS )!MigrationLoaderal  
    Load migration files from disk and their status from the database.

    Migration files are expected to live in the "migrations" directory of
    an app. Their names are entirely unimportant from a code perspective,
    but will probably follow the 1234_name.py convention.

    On initialization, this class will scan those directories, and open and
    read the Python files, looking for a class called Migration, which should
    inherit from django.db.migrations.Migration. See
    django.db.migrations.migration for what that looks like.

    Some migrations will be marked as "replacing" another set of migrations.
    These are loaded into a separate set of migrations away from the main ones.
    If all the migrations they replace are either unapplied or missing from
    disk, then they are injected into the main set, replacing the named migrations.
    Any dependency pointers to the replaced migrations are re-pointed to the
    new migration.

    This does mean that this class MUST also talk to the database as well as
    to disk, but this is probably fine. We're already not just operating
    in memory.
    TFc             C   s.   || _ d | _d | _|| _|| _|r*| j  d S )N)
connectiondisk_migrationsapplied_migrationsignore_no_migrationsreplace_migrationsbuild_graph)selfr   loadr   r    r   Y/var/www/tester-filtro-web/env/lib/python3.6/site-packages/django/db/migrations/loader.py__init__+   s    zMigrationLoader.__init__c             C   s8   |t jkrt j| dfS tj|j}d|tf dfS dS )z
        Return the path to the migrations module for the specified app_label
        and a boolean indicating if the module is specified in
        settings.MIGRATION_MODULE.
        Tz%s.%sFN)r   ZMIGRATION_MODULESr   Zget_app_confignameMIGRATIONS_MODULE_NAME)cls	app_labelZapp_package_namer   r   r   migrations_module7   s    
z!MigrationLoader.migrations_modulec          "   C   s  i | _ t | _t | _xtj D ]}| j|j\}}|dkrP| jj|j q"|t	j
k}yt|}W nT tk
r } z8|r| js| rt|jjdkr| jj|j w" W Y dd}~X nZX t|ds| jj|j q"t|dddkot|jt r| jj|j q"|rt| | jj|j dd tj|jD }x|D ]}d||f }	yt|	}
W nD tk
r } z&dt|krtd	|	 |n W Y dd}~X nX t|
d
std||jf |
j||j| j |j|f< q>W q"W dS )z6Load the migrations from all INSTALLED_APPS from disk.N.__path____file__c             S   s(   h | ] \}}}| r|d  dkr|qS )r   z_~r   ).0_r   Zis_pkgr   r   r   	<setcomp>l   s   z,MigrationLoader.load_disk.<locals>.<setcomp>z%s.%szbad magic numberz9Couldn't import %r as it appears to be a stale .pyc file.	Migrationz-Migration %s in app %s has no Migration class)r   setunmigrated_appsmigrated_appsr   Zget_app_configsr   labeladdsysmodulesr   ModuleNotFoundErrorr   r   r   splithasattrgetattr
isinstancer   listr   pkgutiliter_modulesImportErrorstrr
   r$   )r   Z
app_configmodule_nameexplicitZ
was_loadedmoduleeZmigration_namesmigration_nameZmigration_pathZmigration_moduler   r   r   	load_diskD   s\    



zMigrationLoader.load_diskc             C   s   | j j||f S )z6Return the named migration or raise NodeNotFoundError.)graphnodes)r   r   name_prefixr   r   r   get_migration   s    zMigrationLoader.get_migrationc             C   s~   g }x2| j D ](\}}||kr|j|r|j||f qW t|dkrVtd||f n$|sltd||f n| j |d  S dS )zZ
        Return the migration(s) which match the given app label and name_prefix.
        r   z>There is more than one migration for '%s' with the prefix '%s'z1There no migrations for '%s' with the prefix '%s'r   N)r   
startswithappendlenr	   KeyError)r   r   r>   resultsZmigration_app_labelr:   r   r   r   get_migration_by_prefix   s    z'MigrationLoader.get_migration_by_prefixc             C   s   |d dkr|d dks"|| j kr&|S |d |kr6d S |d | jkrHd S |d | jkry8|d dkrx| j j|d d S | j j|d d S W n. tk
r   | jrd S td|d  Y nX td|d  d S )Nr   	__first__Z
__latest__r   z(Dependency on app with no migrations: %szDependency on unknown app: %s)r<   r&   r'   Z
root_nodes
leaf_nodes
IndexErrorr   
ValueError)r   keyZcurrent_appr   r   r   	check_key   s     "zMigrationLoader.check_keyc             C   sD   x>|j D ]4}|d |d kr|d dkr| jj|||dd qW dS )z
        Internal dependencies need to be added first to ensure `__first__`
        dependencies find the correct root node.
        r   r   rF   T)skip_validationN)dependenciesr<   add_dependency)r   rJ   	migrationparentr   r   r   add_internal_dependencies   s    z)MigrationLoader.add_internal_dependenciesc             C   s   xL|j D ]B}|d |d krq| j||d }|d k	r| jj|||dd qW x:|jD ]0}| j||d }|d k	rV| jj|||dd qVW d S )Nr   T)rL   )rM   rK   r<   rN   Z
run_before)r   rJ   rO   rP   childr   r   r   add_external_dependencies   s    z)MigrationLoader.add_external_dependenciesc                sD   j    jdkri  _nt j}|j  _t  _i  _x4 jj D ]&\}} jj	|| |j
rH| j|< qHW x" jj D ]\}} j|| q~W x" jj D ]\}} j|| qW  jrHx jj D ]v\}} fdd|j
D }t|r| j|< n jj|d t|s"t| r4 jj||j
 qΈ jj||j
 qW y jj  W n tk
r4 } zi }x> jj D ]0\}}x$|j
D ]}|j|t j| qW qzW |j|kr"|j|jt }t fdd|D }	|	s"djdd |D }
tdj|j|jd	 |jd
 |
|j| W Y dd}~X nX  jj  dS )z
        Build a migration dependency graph using both the disk and database.
        You'll need to rebuild the graph if you apply migrations. This isn't
        usually a problem as generally migration stuff runs in a one-shot process.
        Nc                s   g | ]}| j kqS r   )r   )r!   target)r   r   r   
<listcomp>   s    z/MigrationLoader.build_graph.<locals>.<listcomp>c             3   s   | ]}| j jkV  qd S )N)r<   r=   )r!   	candidate)r   r   r   	<genexpr>  s    z.MigrationLoader.build_graph.<locals>.<genexpr>z, c             s   s   | ]}d | V  qdS )z%s.%sNr   )r!   cr   r   r   rW     s    zMigration {0} depends on nonexistent node ('{1}', '{2}'). Django tried to replace migration {1}.{2} with any of [{3}] but wasn't able to because some of the replaced migrations are already applied.r   r   )r;   r   r   r   r   r<   replacementsr   itemsadd_nodereplacesrQ   rS   r   allpopanyZremove_replaced_nodesZremove_replacement_nodeZvalidate_consistencyr   
setdefaultr%   r)   nodegetjoinformatoriginZensure_not_cyclic)r   recorderrJ   rO   Zapplied_statusesexcZreverse_replacementsZreplaced
candidatesZis_replacedtriesr   )r   r   r      sV    


 zMigrationLoader.build_graphc          	      s   t |}|j  x D ]}|| jjkr(qxp| jj| jD ]^}| kr8|| jkrnt fdd| j| jD rnq8t	dj
|d |d |d |d |jq8W qW dS )zs
        Raise InconsistentMigrationHistory if any applied migrations have
        unapplied dependencies.
        c             3   s   | ]}| kV  qd S )Nr   )r!   m)appliedr   r   rW   0  s    z;MigrationLoader.check_consistent_history.<locals>.<genexpr>zHMigration {}.{} is applied before its dependency {}.{} on database '{}'.r   r   N)r   r   r<   r=   Znode_mapparentsrY   r]   r\   r   rd   alias)r   r   rf   rO   rP   r   )rk   r   check_consistent_history   s    

z(MigrationLoader.check_consistent_historyc                sZ   i  t  }x<| jj D ].\}}| kr0|j|  j|t  j| qW  fdd|D S )z
        Look through the loaded graph and detect any conflicts - apps
        with more than one leaf migration. Return a dict of the app labels
        that conflict with the migration names that conflict.
        c                s   i | ]}t  | |qS r   )sorted)r!   r   )	seen_appsr   r   
<dictcomp>F  s    z4MigrationLoader.detect_conflicts.<locals>.<dictcomp>)r%   r<   rG   r)   r`   )r   Zconflicting_appsr   r:   r   )rp   r   detect_conflicts:  s    
z MigrationLoader.detect_conflictsNc             C   s   | j j||t| jdS )z
        Return a ProjectState object representing the most recent state
        that the loaded migrations represent.

        See graph.make_state() for the meaning of "nodes" and "at_end".
        )r=   at_endZ	real_apps)r<   Z
make_stater1   r&   )r   r=   rs   r   r   r   project_stateH  s    zMigrationLoader.project_statec             C   s   g }d}x~|D ]v\}}| j jd|jdJ}|dkrH| j|j|jfdd}|s^|j||dd}n|j||dd}W dQ R X |j|j	 qW |S )z
        Take a migration plan and return a list of collected SQL statements
        that represent the best-efforts version of that plan.
        NT)collect_sqlatomicF)rs   )ru   )
r   schema_editorrv   rt   r   r   applyZunapplyextendZcollected_sql)r   ZplanZ
statementsstaterO   Z	backwardsrw   r   r   r   ru   Q  s    zMigrationLoader.collect_sql)TFT)NT)__name__
__module____qualname____doc__r   classmethodr   r;   r?   rE   rK   rQ   rS   r   rn   rr   rt   ru   r   r   r   r   r      s    

B
Q
	r   )r2   r*   	importlibr   r   Zdjango.appsr   Zdjango.confr   Zdjango.db.migrations.graphr   Zdjango.db.migrations.recorderr   
exceptionsr	   r
   r   r   r   r   r   r   r   r   <module>   s   