o
    þÞhoq  ã                   @   s  d 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mZmZmZmZmZ ddlmZmZmZmZmZmZmZ dd	lmZmZ dd
lmZmZmZm Z  ddl!m"Z" G dd„ de#ƒZ$G dd„ de$ƒZ%G dd„ de$ƒZ&G dd„ de$ƒZ'G dd„ de$ƒZ(G dd„ dƒZ)dS )a  
The LayerMapping class provides a way to map the contents of OGR
vector files (e.g. SHP files) to Geographic-enabled Django models.

For more information, please consult the GeoDjango documentation:
  https://docs.djangoproject.com/en/dev/ref/contrib/gis/layermapping/
é    N)ÚDecimal)ÚInvalidOperation)ÚPath)ÚGeometryField)ÚCoordTransformÚ
DataSourceÚGDALExceptionÚOGRGeometryÚOGRGeomTypeÚSpatialReference)ÚOFTDateÚOFTDateTimeÚ
OFTIntegerÚOFTInteger64ÚOFTRealÚ	OFTStringÚOFTTime)ÚFieldDoesNotExistÚObjectDoesNotExist)ÚconnectionsÚmodelsÚrouterÚtransaction)Ú	force_strc                   @   ó   e Zd ZdS )ÚLayerMapErrorN©Ú__name__Ú
__module__Ú__qualname__© r    r    úe/var/www/html/premium_crap/venv/lib/python3.10/site-packages/django/contrib/gis/utils/layermapping.pyr   &   ó    r   c                   @   r   )ÚInvalidStringNr   r    r    r    r!   r#   *   r"   r#   c                   @   r   )ÚInvalidDecimalNr   r    r    r    r!   r$   .   r"   r$   c                   @   r   )ÚInvalidIntegerNr   r    r    r    r!   r%   2   r"   r%   c                   @   r   )ÚMissingForeignKeyNr   r    r    r    r!   r&   6   r"   r&   c                   @   sÂ  e Zd ZdZdedƒdedƒdedƒedƒjed	ƒed
ƒjedƒedƒjedƒiZi eje	“ej
e“eje	“eje	eef“eje	eef“eje	ef“eje“eje“eje“eje“eje	ef“eje“eje“eje“eje“eje“eje	eef“ej e	eefej!e	eefej"e	eefej#e	eefi¥Z$							d0d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(„ Z/d)d*„ Z0d+d,„ Z1d-d-d-d-d-e2j3d-fd.d/„Z4dS )1ÚLayerMappingz1A class that maps OGR Layers to GeoDjango Models.é   Ú
MultiPointé   ÚMultiLineStringé   ÚMultiPolygonÚPoint25DÚMultiPoint25DÚLineString25DÚMultiLineString25DÚ
Polygon25DÚMultiPolygon25Dr   Núutf-8Úcommit_on_successTc                 C   s&  t |ttfƒrt||d�| _n|| _| j| | _|
dur|
nt |¡| _t	| j }|j
| _|| _|| _|  ¡  |jjrA|  ¡ | _nd}|rQ|  |¡| _|  ¡ | _n|| _|rdddlm} ||ƒ || _nd| _|	rt|  |	¡ d}|	| _nd| _|| _|dkrƒd| _dS |dkr�tj| _dS t d| ƒ‚)	a  
        A LayerMapping object is initialized using the given Model (not an instance),
        a DataSource (or string path to an OGR-supported data file), and a mapping
        dictionary.  See the module level docstring for more details and keyword
        argument usage.
        )ÚencodingNFr   )ÚlookupÚ
autocommitr5   z!Unrecognized transaction mode: %s)!Ú
isinstanceÚstrr   r   ÚdsÚlayerr   Údb_for_writeÚusingr   ÚopsÚspatial_backendÚmappingÚmodelÚcheck_layerÚfeaturesÚsupports_transformÚgeometry_fieldÚ	geo_fieldÚ	check_srsÚ
source_srsÚcoord_transformÚ	transformÚcodecsr7   r6   Úcheck_uniqueÚuniqueÚtransaction_modeÚtransaction_decoratorr   Úatomicr   )ÚselfrB   ÚdatarA   r<   rI   r6   rO   rK   rN   r>   Ú
connectionr7   r    r    r!   Ú__init__`   sB   


zLayerMapping.__init__c                 C   s0   |rt |ttfƒrt|Ž S t |tƒr|S t‚dS )zCheck the `fid_range` keyword.N)r9   ÚtupleÚlistÚsliceÚ	TypeError)rR   Ú	fid_ranger    r    r!   Úcheck_fid_range³   s   
zLayerMapping.check_fid_rangec              
      sø  d| _ i | _| jj‰ | jj}‡ fdd„}| j ¡ D ]à\}}z	| jj |¡}W n t	y3   t
d| ƒ‚w |jj}t|tƒr�| j rDt
dƒ‚|j}z|dkrSt|d ƒ}nt|ƒ}W n tye   t
d| ƒ‚w | jj}	|	j |j¡s†|  |	|¡s†t
d	||dkr€d
nd|	f ƒ‚|| _ || _|}
net|tjƒrËt|tƒrÇ|jj}| ¡ D ]!\}}||ƒ}z|j |¡ W q¢ t	yÃ   t
d||jjf ƒ‚w |}
n-tdƒ‚|j| jvr×t
d| ƒ‚||ƒ}|| }t|| j|j ƒsòt
d||j|f ƒ‚|}
|
| j|< qdS )zÞ
        Check the Layer metadata and ensure that it's compatible with the
        mapping information and model. Unlike previous revisions, there is no
        need to increment through each feature in the Layer.
        Fc                    s,   zˆ   | ¡}W |S  ty   td|  ƒ‚w )Nz4Given mapping OGR field "%s" not found in OGR Layer.)ÚindexÚ
ValueErrorr   )Úogr_map_fldÚidx©Ú
ogr_fieldsr    r!   Úcheck_ogr_fldÑ   s   üÿÿz/LayerMapping.check_layer.<locals>.check_ogr_fldz3Given mapping field "%s" not in given Model fields.zDLayerMapping does not support more than one GeometryField per model.r,   Ú25Dz'Invalid mapping for GeometryField "%s".zDInvalid mapping geometry; model has %s%s, layer geometry type is %s.z(dim=3)Ú z/ForeignKey mapping field "%s" not in %s fields.z.ForeignKey mapping must be of dictionary type.z0Django field type "%s" has no OGR mapping (yet).z:OGR field "%s" (of type %s) cannot be mapped to Django %s.N)Ú
geom_fieldÚfieldsr<   Úfield_typesrA   ÚitemsrB   Ú_metaÚ	get_fieldr   r   Ú	__class__r   r9   r   Údimr
   r   Ú	geom_typeÚnameÚ
startswithÚ
make_multiÚ	coord_dimr   Ú
ForeignKeyÚdictÚremote_fieldrY   ÚFIELD_TYPESÚ
issubclass)rR   Úogr_field_typesrb   Ú
field_nameÚogr_nameÚmodel_fieldÚfld_namerq   ÚgtypeÚltypeÚ
fields_valÚ	rel_modelÚrel_nameÚ	ogr_fieldr_   r    r`   r!   rC   ¿   s”   	ÿÿ
ÿ€ÿÿÿ
þþÿ	

ÿÿÿÿ
ÿÿªzLayerMapping.check_layerc                 C   sX   t |tƒr|}nt || j ¡ ƒr|j}nt |ttfƒr t|ƒ}n| jj}|s*tdƒ‚|S )z>Check the compatibility of the given spatial reference object.z#No source reference system defined.)	r9   r   r@   Úspatial_ref_sysÚsrsÚintr:   r<   r   )rR   rI   Úsrr    r    r!   rH   4  s   

zLayerMapping.check_srsc                 C   sN   t |ttfƒr|D ]	}|| jvrt‚q	dS t |tƒr#|| jvr!t‚dS tdƒ‚)zDCheck the `unique` keyword parameter -- may be a sequence or string.zBUnique keyword argument must be set with a tuple, list, or string.N)r9   rW   rV   rA   r]   r:   rY   )rR   rN   Úattrr    r    r!   rM   F  s   
ÿÿ

ÿÿzLayerMapping.check_uniquec              	   C   s�   i }| j  ¡ D ]>\}}| j| }t|tƒr*z	|  |j|¡}W n" ty)   tdƒ‚w t|t	j
jƒr9|  |||¡}n|  || |¡}|||< q|S )z{
        Given an OGR Feature, return a dictionary of keyword arguments for
        constructing the mapped model.
        z)Could not retrieve geometry from feature.)rA   rh   rf   r9   r   Úverify_geomÚgeomr   r   r   ÚbaseÚ	ModelBaseÚ	verify_fkÚverify_ogr_field)rR   ÚfeatÚkwargsrx   ry   rz   Úvalr    r    r!   Úfeature_kwargsW  s   

ÿ
zLayerMapping.feature_kwargsc                    s0   t | jtƒr| jˆ | j iS ‡ fdd„| jD ƒS )z·
        Given the feature keyword arguments (from `feature_kwargs`), construct
        and return the uniqueness keyword arguments -- a subset of the feature
        kwargs.
        c                    s   i | ]}|ˆ | “qS r    r    )Ú.0Úfld©rŽ   r    r!   Ú
<dictcomp>�  s    z.LayerMapping.unique_kwargs.<locals>.<dictcomp>)r9   rN   r:   )rR   rŽ   r    r“   r!   Úunique_kwargsx  s   zLayerMapping.unique_kwargsc           
      C   s„  t |tƒr>t |tjtjfƒr>| jr|jdurt|j| jƒ}n|j}|jr<|dur<t	|ƒ|jkr<t
d|j|jt	|ƒf ƒ‚|S t |tƒr™t |tjƒr™z	tt|jƒƒ}W n ty`   td|j ƒ‚w | ¡ }|d }|d }|j|j }|dk r€t	|d|… ƒ}	nt	|ƒ| }	|	|kr•td|j|j|f ƒ‚|}|S t |ttfƒr½t |tjƒr½zt|jƒ}W |S  ty¼   td|j ƒ‚w |j}|S )	z£
        Verify if the OGR Field contents are acceptable to the model field. If
        they are, return the verified value, otherwise raise an exception.
        Nz@%s model field maximum string length is %s, given %s characters.z$Could not construct decimal from: %sr(   r*   r   zeA DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.z$Could not construct integer from: %s)r9   r   r   Ú	CharFieldÚ	TextFieldr6   Úvaluer   Ú
max_lengthÚlenr#   rn   r   ÚDecimalFieldr   r:   ÚDecimalInvalidOperationr$   Úas_tupleÚ
max_digitsÚdecimal_placesÚIntegerFieldr„   r]   r%   )
rR   r�   rz   r�   ÚdÚdtupÚdigitsÚd_idxÚmax_precÚn_precr    r    r!   rŒ   „  sl   ÿÿÿÿ3ÑÿÿÿþÿôÿúÿÿzLayerMapping.verify_ogr_fieldc                 C   sp   i }|  ¡ D ]\}}|  || |j |¡¡||< qz|j | j¡jdi |¤ŽW S  ty7   td|j	|f ƒ‚w )z”
        Given an OGR Feature, the related model and its dictionary mapping,
        retrieve the related model for the ForeignKey mapping.
        z7No ForeignKey %s model found with keyword arguments: %sNr    )
rh   rŒ   ri   rj   Úobjectsr>   Úgetr   r&   r   )rR   r�   r   Úrel_mappingÚ	fk_kwargsrx   ry   r    r    r!   r‹   Ì  s   

ÿÿÿÿzLayerMapping.verify_fkc                 C   sv   |j r| d¡ | jdkr|jr| d¡ |  |j|¡r-| j|jj }t	|ƒ}| 
|¡ n|}| jr8| | j¡ |jS )zØ
        Verify the geometry -- construct and return a GeometryCollection
        if necessary (for example if the model field is MultiPolygonField while
        the mapped shapefile only contains Polygons).
        Fr*   )Úis_measuredÚset_measuredrq   Úis_3dÚset_3drp   rm   ÚMULTI_TYPESÚnumr	   ÚaddrK   Úwkt)rR   rˆ   rz   Ú
multi_typeÚgr    r    r!   r‡   å  s   

zLayerMapping.verify_geomc              
   C   sX   | j  ¡ }z|j | j¡j| jjd�j}t| j	|ƒW S  t
y+ } ztdƒ|‚d}~ww )z,Return the coordinate transformation object.)Úsridz?Could not translate between the data source and model geometry.N)r@   r‚   r§   r>   r¨   rG   rµ   rƒ   r   rI   Ú	Exceptionr   )rR   ÚSpatialRefSysÚ
target_srsÚexcr    r    r!   rJ     s    
ÿýÿþ€ÿzLayerMapping.coord_transformc                 C   s   | j j}| | j¡S )zHReturn the GeometryField instance associated with the geographic column.)rB   ri   rj   re   )rR   Úoptsr    r    r!   rF     s   zLayerMapping.geometry_fieldc                 C   s   |j | jv o|jjd|j kS )z«
        Given the OGRGeomType for a geometry and its associated GeometryField,
        determine whether the geometry should be turned into a GeometryCollection.
        zMulti%s)r°   r¯   rk   r   Údjango)rR   rm   rz   r    r    r!   rp     s   þzLayerMapping.make_multiFc              	      s"  ˆ  |¡}ˆ rˆ du stˆ tƒsd‰nˆ ‰|ddf‡ ‡‡‡‡‡‡fdd„	}	ˆjdur/ˆ |	¡}	ˆjj}
|rŒt|tƒrŒ||
k rŒ|rDtdƒ‚d\}}}t||
|ƒ}t|ƒ}t	|ƒD ]2\}}|d	 |krgt
|dƒ}nt
||ƒ}z|	|||ƒ\}}|}W qW ty‰   ˆ d
d|f ¡ ‚ w dS |	ƒ  dS )a²  
        Save the contents from the OGR DataSource Layer into the database
        according to the mapping dictionary given at initialization.

        Keyword Parameters:
         verbose:
           If set, information will be printed subsequent to each model save
           executed on the database.

         fid_range:
           May be set with a slice or tuple of (begin, end) feature ID's to map
           from the data source.  In other words, this keyword enables the user
           to selectively import a subset range of features in the geographic
           data source.

         step:
           If set with an integer, transactions will occur at every step
           interval. For example, if step=1000, a commit would occur after
           the 1,000th feature, the 2,000th feature etc.

         progress:
           When this keyword is set, status information will be printed giving
           the number of features processed and successfully saved.  By default,
           progress information will pe printed every 1000 features processed,
           however, this default may be overridden by setting this keyword with an
           integer for the desired interval.

         stream:
           Status information will be written to this file handle.  Defaults to
           using `sys.stdout`, but any object with a `write` method is supported.

         silent:
           By default, non-fatal error notifications are printed to stdout, but
           this keyword may be set to disable these notifications.

         strict:
           Execution of the model mapping will cease upon the first error
           encountered.  The default behavior is to attempt to continue.
        Tiè  r   c                    s  | rˆj |  }nˆj }|D ]ò}|d7 }zˆ |¡}W n! ty; } zˆr%‚ ˆs1ˆ d|j|f ¡ W Y d }~n·d }~ww d}ˆjr˜zEˆ |¡}ˆjj 	ˆj	¡j
di |¤Ž}	d}t|	ˆjƒ}
|
d u rit|ˆj ƒ}n|
j}t|ˆj ƒ}|D ]}| |¡ qut|	ˆj|jƒ W n ty—   ˆjdi |¤Ž}	Y n	w ˆjdi |¤Ž}	z|	jˆj	d� |d7 }ˆr»ˆ d|rµdnd|	f ¡ W n1 tyí } z%ˆrØˆs×ˆ d	|j ¡ ˆ d
| ¡ ‚ ˆsãˆ d||f ¡ W Y d }~nd }~ww ˆ rÿ|ˆ dkrÿˆ d||f ¡ q||fS )Nr(   z#Ignoring Feature ID %s because: %s
FT)r>   z%s: %s
ÚUpdatedÚSavedzOFailed to save the feature (id: %s) into the model with the keyword arguments:
z%s
z"Failed to save %s:
 %s
Continuing
r   z$Processed %d features, saved %d ...
r    )r<   r�   r   ÚwriteÚfidrN   r•   rB   r§   r>   r¨   Úgetattrre   r	   Úogrr±   Úsetattrr²   r   Úsaver¶   )Ú
feat_rangeÚnum_featÚ	num_savedÚ
layer_iterr�   rŽ   ÚmsgÚ	is_updateÚu_kwargsÚmÚ
geom_valuerˆ   Únewr´   ©ÚprogressÚprogress_intervalrR   ÚsilentÚstreamÚstrictÚverboser    r!   Ú_savec  s€   ÿ€û

þÿ€ÿÿ
ÿ€õ
ÿ€z LayerMapping.save.<locals>._saveNzOThe `step` keyword may not be used in conjunction with the `fid_range` keyword.)r   r   r   r(   z%s
Failed to save slice: %s
z(=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-)r[   r9   r„   rP   r<   rÅ   r   Úrangerš   Ú	enumeraterX   r¶   r¾   )rR   rÔ   rZ   ÚsteprÏ   rÑ   rÒ   rÓ   Údefault_rangerÕ   ÚnfeatÚbegrÅ   rÆ   ÚindicesÚn_iÚiÚendÚ
step_slicer    rÎ   r!   rÃ   (  s@   
2 
T
ÿ


ÿüõ
zLayerMapping.save)r   Nr4   r5   TNN)5r   r   r   Ú__doc__r
   r°   r¯   r   Ú	AutoFieldr   ÚBigAutoFieldr   ÚSmallAutoFieldÚBooleanFieldr   r   r    Ú
FloatFieldÚ	DateFieldr   ÚDateTimeFieldr   Ú
EmailFieldÚ	TimeFieldr   r›   r–   Ú	SlugFieldr—   ÚURLFieldÚ	UUIDFieldÚBigIntegerFieldÚSmallIntegerFieldÚPositiveBigIntegerFieldÚPositiveIntegerFieldÚPositiveSmallIntegerFieldru   rU   r[   rC   rH   rM   r�   r•   rŒ   r‹   r‡   rJ   rF   rp   ÚsysÚstdoutrÃ   r    r    r    r!   r'   :   sš    ú
ÿþýüû
úùø	÷
ö
õôóòñðïë
õSu!H ør'   )*rá   ró   Údecimalr   r   rœ   Úpathlibr   Údjango.contrib.gis.db.modelsr   Údjango.contrib.gis.gdalr   r   r   r	   r
   r   Údjango.contrib.gis.gdal.fieldr   r   r   r   r   r   r   Údjango.core.exceptionsr   r   Ú	django.dbr   r   r   r   Údjango.utils.encodingr   r¶   r   r#   r$   r%   r&   r'   r    r    r    r!   Ú<module>   s"    $	