U
    ad2l                     @   sX  d Z ddlZ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mZmZmZmZmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZ dd ZG dd de
Zdd ZG dd dZ G dd de Z!G dd de Z"G dd de Z#d,ddZ$d-d d!Z%d"d# Z&d$d% Z'G d&d' d'e(Z)G d(d) d)e(Z*G d*d+ d+Z+dS ).a  
      Title: Dumpscript management command
    Project: Hardytools (queryset-refactor version)
     Author: Will Hardy (http://willhardy.com.au)
       Date: June 2008
      Usage: python manage.py dumpscript appname > scripts/scriptname.py
  $Revision: 217 $

Description:
    Generates a Python script that will repopulate the database using objects.
    The advantage of this approach is that it is easy to understand, and more
    flexible than directly populating the database, or using XML.

    * It also allows for new defaults to take effect and only transfers what is
      needed.
    * If a new database schema has a NEW ATTRIBUTE, it is simply not
      populated (using a default value will make the transition smooth :)
    * If a new database schema REMOVES AN ATTRIBUTE, it is simply ignored
      and the data moves across safely (I'm assuming we don't want this
      attribute anymore.
    * Problems may only occur if there is a new model and is now a required
      ForeignKey for an existing model. But this is easy to fix by editing the
      populate script. Half of the job is already done as all ForeingKey
      lookups occur though the locate_object() function in the generated script.

Improvements:
    See TODOs and FIXMEs scattered throughout :-)

    N)apps)ContentType)ObjectDoesNotExist)BaseCommand)router)	AutoFieldBooleanField	DateFieldDateTimeField	FileField
ForeignKey)	Collector)timezone)	force_str	smart_str)signalcommandc           
      C   s   | j j}|}| j jj}|}t| |}t|drft|j drft|j jdrf|j j}|j jj}t||}q$t| j}|D ]j}|| }|dk	rtt|t	j	rt
|st
|}td|  ||< qtt|tttfsttd| ||< qtd||||||f }	|	S )z
    Is called every time an object that will not be exported is required.
    Where orm_obj is the referred object.
    We postpone the lookup to locate_object() which will be run on the generated script
    _metapknameNdateutil.parser.parse("%s")%sz5 importer.locate_object(%s, "%s", %s, "%s", %s, %s ) )r   object_namer   r   getattrhasattrmake_clean_dict__dict__
isinstancedatetimer   Zis_awareZ
make_awareStrToCodeChanger	isoformatstrintfloat)
Zorm_objZ	the_classZoriginal_classpk_nameZoriginal_pk_nameZpk_value
clean_dictkeyvoutput r(   T/tmp/pip-unpacked-wheel-portabvm/django_extensions/management/commands/dumpscript.pyorm_item_locator1   s8    

$



    r*   c                       s,   e Zd ZdZ fddZedd Z  ZS )Commandz-Dumps the data as a customised python script.c                    s2   t  | |jddd |jdddddd	 d S )
Nappname+)nargsz--autofieldstore_falseskip_autofieldTz#Include Autofields (like pk fields))actiondestdefaulthelp)superadd_argumentsadd_argument)selfparser	__class__r(   r)   r6   Z   s       zCommand.add_argumentsc                 O   sJ   |d }t |}i }t||| j| j|d}| jt| | jd d S )Nr,   )modelscontextstdoutstderroptions
)
get_modelsScriptr>   r?   writer    )r8   argsr@   
app_labelsr<   r=   scriptr(   r(   r)   handleb   s    zCommand.handle)__name__
__module____qualname__r4   r6   r   rH   __classcell__r(   r(   r:   r)   r+   W   s   r+   c                    s   t f g }| sBt D ]&}| fddt|j D 7 }q|S | D ]P}d|krv|dd\}}|t|| qF| fddt| D 7 }qF|S )z
    Get a list of models for the given app labels, with some exceptions.
    TODO: If a required model is referenced, it should also be included.
    Or at least discovered with a get_or_create() call.
    c                    s   g | ]}| kr|qS r(   r(   .0mZEXCLUDED_MODELSr(   r)   
<listcomp>   s    zget_models.<locals>.<listcomp>.   c                    s   g | ]}| kr|qS r(   r(   rM   rP   r(   r)   rQ      s    )	r   r   Zget_app_configsZget_app_configlabelrB   splitappendZ	get_model)rF   r<   Zapp	app_labelZ
model_namer(   rP   r)   rB   z   s    	$"rB   c                   @   s2   e Zd ZdZd
ddZdd Zdd	 ZeeZdS )Codez
    A snippet of python script.
    This keeps track of import statements and can be output to a string.
    In the future, other features such as custom indentation might be included
    in this class.
    Nc                 C   s*   |s
t j}|st j}|| _|| _|| _d S N)sysr>   r?   indent)r8   r\   r>   r?   r(   r(   r)   __init__   s    zCode.__init__c                 C   sN   | j r:| jt| j tdg| j dg | j | jdS t| j| jdS dS )z0 Return a string representation of this script.  num_indentsN)importsr?   rD   reprimport_linesflatten_blockslinesr\   r8   r(   r(   r)   __str__   s    "zCode.__str__c                 C   s"   | j rdd | j  D S g S dS )z4 Take the stored imports and converts them to lines c                 S   s   g | ]\}}d ||f qS )zfrom %s import %sr(   )rN   r%   valuer(   r(   r)   rQ      s     z)Code.get_import_lines.<locals>.<listcomp>N)ra   itemsrf   r(   r(   r)   get_import_lines   s    zCode.get_import_lines)rY   NN)	rI   rJ   rK   __doc__r]   rg   rj   propertyrc   r(   r(   r(   r)   rX      s
   
rX   c                       sB   e Zd ZdZd	 fdd	Zdd ZeeZdd ZeeZ	  Z
S )
	ModelCodezJ Produces a python script that can recreate data for a given model class. Nc                    s:   t  jd||d || _|d kr$i }|| _|| _g | _d S )Nr   r\   r>   r?   )r5   r]   modelr=   r@   	instances)r8   ro   r=   r>   r?   r@   r:   r(   r)   r]      s    zModelCode.__init__c                 C   s   | j jt| j jiS )zo
        Return a dictionary of import statements, with the variable being
        defined as the key.
        )ro   rI   r   rJ   rf   r(   r(   r)   get_imports   s    zModelCode.get_importsc              	   C   sz   g }t | jj D ]D\}}t||d | j| j| j| jd}| j	
| |jr||j7 }q| j	D ]}|jr`||j7 }q`|S )
        Return a list of lists or strings, representing the code body.
        Each list is a block, each string is a statement.
        rS   )instanceidr=   r>   r?   r@   )	enumeratero   Z_default_managerallInstanceCoder=   r>   r?   r@   rp   rV   waiting_listre   )r8   codecounteritemrs   r(   r(   r)   	get_lines   s     
zModelCode.get_lines)NNNN)rI   rJ   rK   rk   r]   rq   rl   ra   r|   re   rL   r(   r(   r:   r)   rm      s   	rm   c                       sX   e Zd ZdZd fdd	ZdddZeeZdd	 Zd
d Z	dddZ
dddZ  ZS )rw   zM Produces a python script that can recreate data for a given model instance. Nc              	      s   t  jd||d i | _|| _|| _| jj| _|dkr:i }|| _d| jjj	|f | _
d| _d| _t| jjj| _i | _| jjjD ]J}z|jjjjsW qW n tk
r   Y nX tt| j|j | j|< qdS )z, We need the instance in question and an id r   rn   N%s_%sF)r5   r]   ra   r@   rs   r;   ro   r=   r   Zdb_tablevariable_nameskip_meinstantiatedlistfieldsrx   many_to_many_waiting_listmany_to_manyremote_fieldZthroughZauto_createdAttributeErrorr   r   rv   )r8   rs   rt   r=   r>   r?   r@   fieldr:   r(   r)   r]      s(    
zInstanceCode.__init__Fc                 C   sj   g }|   rg S ||  7 }||  7 }|r<|| j|d7 }|rV|d| j| jf  || j|d7 }|S )ai  
        Return a list of lists or strings, representing the code body.
        Each list is a block, each string is a statement.

        force (True or False): if an attribute object cannot be included,
        it is usually skipped to be processed later. With 'force' set, there
        will be no waiting: a get_or_create() call is written instead.
        forcez!%s = importer.save_or_locate(%s)
)skipinstantiateget_waiting_listrV   r~   get_many_to_many_lines)r8   r   
code_linesr(   r(   r)   r|   
  s    	zInstanceCode.get_linesc                    s    j dk	r j S  jj}tj| jd}t|d}|j jgdd tdd |j	 D g }dd |D } fd	d|D 
d
dkr jjjj}d jjt j|f }d j|< d
 _ nd _  j S )a$  
        Determine whether or not this object should be skipped.
        If this model instance is a parent of a single subclassed
        instance, skip it. The subclassed instance will create this
        parent instance for us.

        TODO: Allow the user to force its creation?
        N)rs   )usingF)Zcollect_relatedc                 S   s   g | ]}t |qS r(   )r   )rN   ir(   r(   r)   rQ   @  s     z%InstanceCode.skip.<locals>.<listcomp>c                 S   s   g | ]}|j jqS r(   )r   parents)rN   sor(   r(   r)   rQ   A  s     c                    s   g | ]} j |kqS r(   )ro   )rN   prf   r(   r)   rQ   B  s     TrS   r}   )r   rs   r;   r   Zdb_for_writer   Zcollectsumdatavaluescountr   r   r   ro   rI   r   r=   )r8   clsr   	collectorZsub_objectsZsub_objects_parentsr#   r%   r(   rf   r)   r   0  s    	


zInstanceCode.skipc                 C   s\   g }| j sX|d| j| jjf  d| _ | jjjj}d| jjt	| j|f }| j| j
|< |S )z Write lines for instantiation z	%s = %s()Tr}   )r   rV   r~   ro   rI   rs   r   r   r   r   r=   )r8   r   r#   r%   r(   r(   r)   r   N  s    zInstanceCode.instantiatec              	   C   s   g }| j d }t| jD ]~}z>t| j|| j||d}|d| j|j|f  | j	| W q t
k
r~   | j	| Y qY q tk
r   Y qY qX q|S )z= Add lines for any waiting fields that can be completed now. r0   )r   r0   z
%s.%s = %s)r@   r   rx   get_attribute_valuers   r=   rV   r~   r   remove	SkipValueDoLater)r8   r   r   r0   r   rh   r(   r(   r)   r   ^  s    
zInstanceCode.get_waiting_listc           
      C   s   g }| j  D ]\}}t|D ]}zZ|jjj}d|jjt||f }d| j	|  }|
d| j|j|f  | j | | W q tk
r   |rt|}	|j| j	d |jj< |
d| j|j|	f  | j | | Y qX qq|r|
d |S )zF Generate lines that define many to many relations for this instance. r}   r   z%s.%s.add(%s)__extra_importsz%s.%s.add( %s )r^   )r   ri   r   r   r   r   r;   rI   r   r=   rV   r~   r   KeyErrorr*   rJ   r   )
r8   r   re   r   Z	rel_itemsZrel_itemr#   r%   rh   item_locatorr(   r(   r)   r   u  s$    

z#InstanceCode.get_many_to_many_lines)NNNN)F)F)F)rI   rJ   rK   rk   r]   r|   rl   re   r   r   r   r   rL   r(   r(   r:   r)   rw      s   
$
rw   c                       sJ   e Zd ZdZd fdd	Zdd Zdd ZeeZd	d
	e
j Z  ZS )rC   zN Produces a complete python script that can recreate data for the given apps. Nc                    sP   t  j||d i | _|| _|d kr(i }|| _t|| jd< i | jd< || _d S )N)r>   r?   __avaliable_modelsr   )r5   r]   ra   r<   r=   setr@   )r8   r<   r=   r>   r?   r@   r:   r(   r)   r]     s    
zScript.__init__c                    s   g }t |}|}|}|dkr|}|d}t|| d r^t| jjjd}	||	 n
|| t |}||kr|d8 }|dkr fdd|D }
||
7 }|
|dd< qq|}q|S )z
        Work an an appropriate ordering for the models.
        This isn't essential, but makes the script look nicer because
        more instances can be defined on their first try.
        r   r   ro   r=   r>   r?   r@   rS   c              	      s$   g | ]}t | jjjd qS )r   )rm   r>   r?   r@   rM   r=   r8   r(   r)   rQ     s     z(Script._queue_models.<locals>.<listcomp>N)lenpopcheck_dependenciesrm   r>   r?   r@   rV   )r8   r<   r=   model_queueZnumber_remaining_modelsZ
MAX_CYCLESZallowed_cyclesZ previous_number_remaining_modelsro   model_classZmissing_modelsr(   r   r)   _queue_models  s*    

zScript._queue_modelsc                 C   s   | j  g}| j| j| jdD ]T}d|jj|jjf }| j	| |
d|  |
|j |
d |
|j q| jD ]\}d|jj|jjf }| j	| |
d|  |jD ]"}|js|jr|
|jdd qqz|dd	 |d
d | jd  D ]\}}|d
d||f  q|S )rr   )r=   zProcessing model: %s.%s
z    # r^   zRe-processing model: %s.%s
Tr   rS   z    # Initial Imports   r   z    from %s import %s)FILE_HEADERstripr   r<   r=   ro   rJ   rI   r?   rD   rV   rc   re   rp   rx   r   r|   insertri   )r8   ry   r   msgro   rs   r%   rh   r(   r(   r)   r|     s(    


zScript.get_linesa  

#!/usr/bin/env python


# This file has been automatically generated.
# Instead of changing it, create a file called import_helper.py
# and put there a class called ImportHelper(object) in it.
#
# This class will be specially casted so that instead of extending object,
# it will actually extend the class BasicImportHelper()
#
# That means you just have to overload the methods you want to
# change, leaving the other ones intact.
#
# Something that you might want to do is use transactions, for example.
#
# Also, don't forget to add the necessary Django imports.
#
# This file was generated with the following command:
# %s
#
# to restore it, run
# manage.py runscript module_name.this_script_name
#
# example: if manage.py is at ./manage.py
# and the script is at ./some_folder/some_script.py
# you must make sure ./some_folder/__init__.py exists
# and run  ./manage.py runscript some_folder.some_script
import os, sys
from django.db import transaction

class BasicImportHelper:

    def pre_import(self):
        pass

    @transaction.atomic
    def run_import(self, import_data):
        import_data()

    def post_import(self):
        pass

    def locate_similar(self, current_object, search_data):
        # You will probably want to call this method from save_or_locate()
        # Example:
        #   new_obj = self.locate_similar(the_obj, {"national_id": the_obj.national_id } )

        the_obj = current_object.__class__.objects.get(**search_data)
        return the_obj

    def locate_object(self, original_class, original_pk_name, the_class, pk_name, pk_value, obj_content):
        # You may change this function to do specific lookup for specific objects
        #
        # original_class class of the django orm's object that needs to be located
        # original_pk_name the primary key of original_class
        # the_class      parent class of original_class which contains obj_content
        # pk_name        the primary key of original_class
        # pk_value       value of the primary_key
        # obj_content    content of the object which was not exported.
        #
        # You should use obj_content to locate the object on the target db
        #
        # An example where original_class and the_class are different is
        # when original_class is Farmer and the_class is Person. The table
        # may refer to a Farmer but you will actually need to locate Person
        # in order to instantiate that Farmer
        #
        # Example:
        #   if the_class == SurveyResultFormat or the_class == SurveyType or the_class == SurveyState:
        #       pk_name="name"
        #       pk_value=obj_content[pk_name]
        #   if the_class == StaffGroup:
        #       pk_value=8

        search_data = { pk_name: pk_value }
        the_obj = the_class.objects.get(**search_data)
        #print(the_obj)
        return the_obj


    def save_or_locate(self, the_obj):
        # Change this if you want to locate the object in the database
        try:
            the_obj.save()
        except:
            print("---------------")
            print("Error saving the following object:")
            print(the_obj.__class__)
            print(" ")
            print(the_obj.__dict__)
            print(" ")
            print(the_obj)
            print(" ")
            print("---------------")

            raise
        return the_obj


importer = None
try:
    import import_helper
    # We need this so ImportHelper can extend BasicImportHelper, although import_helper.py
    # has no knowlodge of this class
    importer = type("DynamicImportHelper", (import_helper.ImportHelper, BasicImportHelper ) , {} )()
except ImportError as e:
    # From Python 3.3 we can check e.name - string match is for backward compatibility.
    if 'import_helper' in str(e):
        importer = BasicImportHelper()
    else:
        raise

import datetime
from decimal import Decimal
from django.contrib.contenttypes.models import ContentType

try:
    import dateutil.parser
    from dateutil.tz import tzoffset
except ImportError:
    print("Please install python-dateutil")
    sys.exit(os.EX_USAGE)

def run():
    importer.pre_import()
    importer.run_import(import_data)
    importer.post_import()

def import_data():

 )NNNN)rI   rJ   rK   rk   r]   r   r|   rl   re   joinr[   argvr   rL   r(   r(   r:   r)   rC     s   -  
 rC   rY   c                    s:   d}| sdS t | tr"|  |  S d fdd| D S )zg
    Take a list (block) or string (statement) and flattens it into a string
    with indentation.
    z    r^   rA   c                    s   g | ]}t | d  qS )rS   )rd   )rN   liner_   r(   r)   rQ     s     z"flatten_blocks.<locals>.<listcomp>)r   r    r   )re   r`   ZINDENTATIONr(   r_   r)   rd   z  s    
rd   FTc           
      C   s  zt | |j}W n* tk
r:   td| jj|jf Y nX |rTt|trTt n*t|trr|dk	rrt	t
|S t|trt	t|S t|trP|dk	rP|jjtkrd|j|jf S |jjj}d|jjt ||f }||kr|| }|dk rt d| S |j|d ks|r8|j|d |jj< t|}	|	S td| jj|jf n.t|ttfrv|dk	rvd	|  S t	|S dS )
zI Get a string version of the given attribute's value, like repr() might. z+Could not find object for %s.%s, ignoring.
Nz3ContentType.objects.get(app_label="%s", model="%s")r}   r   r   r   z(FK) %s.%s
r   )r   r   r   r   r;   rI   r   r   r   rb   boolr   r   r   r   ro   r   rW   r   r   rJ   r   r*   r   r	   r
   r   )
r{   r   r=   r   r0   rh   r#   r%   r~   r   r(   r(   r)   r     s8    




r   c                 C   s   d| kr|   }|d= |S | S )N_state)copy)Zthe_dictr$   r(   r(   r)   r     s
    r   c                 C   s~   dd |D | j dg }| jjD ].}|js,q |jjj |kr |jj|krHq  dS q | jjD ] }|jsdqX|jjj |krX dS qXdS )zK Check that all the depenedencies for this model are already in the queue. c                 S   s   g | ]}|j jqS r(   )ro   rI   rM   r(   r(   r)   rQ     s     z&check_dependencies.<locals>.<listcomp>r   FT)rI   r   r   r   ro   r   )ro   r   Zavaliable_modelsZallowed_linksr   r(   r(   r)   r     s    r   c                   @   s   e Zd ZdZdS )r   8 Value could not be parsed or should simply be skipped. NrI   rJ   rK   rk   r(   r(   r(   r)   r     s   r   c                   @   s   e Zd ZdZdS )r   r   Nr   r(   r(   r(   r)   r     s   r   c                   @   s   e Zd Zdd Zdd ZdS )r   c                 C   s
   || _ d S rZ   rb   )r8   stringr(   r(   r)   r]     s    zStrToCodeChanger.__init__c                 C   s   | j S rZ   r   rf   r(   r(   r)   __repr__  s    zStrToCodeChanger.__repr__N)rI   rJ   rK   r]   r   r(   r(   r(   r)   r     s   r   )rY   )FT),rk   r   r[   Zdjango.appsr   Z"django.contrib.contenttypes.modelsr   Zdjango.core.exceptionsr   Zdjango.core.management.baser   Z	django.dbr   Zdjango.db.modelsr   r   r	   r
   r   r   Zdjango.db.models.deletionr   Zdjango.utilsr   Zdjango.utils.encodingr   r   Z"django_extensions.management.utilsr   r*   r+   rB   rX   rm   rw   rC   rd   r   r   r   	Exceptionr   r   r   r(   r(   r(   r)   <module>   s8    &#"$, $ l

9