
    rbi<                         d dl Z d dlmZ d dlmZ d dlZd dlZd dlZd dl	m
Z
 ed             ZddZ	 	 	 	 	 	 	 dd	Zd
 Zd Zd Zd Zd Z	 	 	 	 	 	 ddZed             ZdS )    N)contextmanager)	lru_cache)GeoDataFramec              #   z  K   ddl m}m} t          | |          rM|                                 s3|                                 5  | V  ddd           dS # 1 swxY w Y   dS | V  dS t          | |          r3|                                 5 }|V  ddd           dS # 1 swxY w Y   dS t          d|            )a  
    Yield a connection within a transaction context.

    Engine.begin() returns a Connection with an implicit Transaction while
    Connection.begin() returns the Transaction. This helper will always return a
    Connection with an implicit (possibly nested) Transaction.

    Parameters
    ----------
    conn_or_engine : Connection or Engine
        A sqlalchemy Connection or Engine instance

    Returns
    -------
    Connection
    r   )
ConnectionEngineNzUnknown Connectable: )sqlalchemy.engine.baser   r   
isinstancein_transactionbegin
ValueError)conn_or_enginer   r   conns       `/var/www/html/mdtn/previsions/meteo_cartes/venv/lib/python3.11/site-packages/geopandas/io/sql.py	_get_connr      s     $ :9999999.*-- 
C,,.. 	!%%'' % %$$$$% % % % % % % % % % % % % % % % % % !     	NF	+	+ C!!## 	tJJJ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 AAABBBs$   AAABB"%B"geomc                 `   || vrt          d| d          | j                                                            |          dk    rt          d| d          | |                                         }|j        s!t          j        j        }	 d }t          |j
        d         t                    r|}n|}|                    |          x| |<   }|t          j        |j
        d                   }|dk    r	 t          ||          }	|	j        s"|	d	                                         }
|
 d
| }nld| d| d}t!          j        |t$          d           d| }nA# t&          j        j        $ r* d| d}t!          j        |t$          d           d| }Y nw xY wt-          | ||          S )a  Transform a pandas DataFrame into a GeoDataFrame.

    The column 'geom_col' must be a geometry column in WKB representation.
    To be used to convert df based on pd.read_sql to gdf.

    Parameters
    ----------
    df : DataFrame
        pandas DataFrame with geometry column in WKB representation.
    geom_col : string, default 'geom'
        column name to convert to shapely geometries
    crs : pyproj.CRS, optional
        CRS to use for the returned GeoDataFrame. The value can be anything accepted
        by :meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,
        such as an authority string (eg "EPSG:4326") or a WKT string.
        If not set, tries to determine CRS from the SRID associated with the
        first geometry in the database, and assigns that to all geometries.
    con : sqlalchemy.engine.Connection or sqlalchemy.engine.Engine
        Active connection to the database to query.

    Returns
    -------
    GeoDataFrame
    zQuery missing geometry column ''   zDuplicate geometry column 'zC' detected in SQL query output. Onlyone geometry column is allowed.c                 ^    t           j                            t          |           d          S )z!Load from binary encoded as text.T)hex)shapelywkbloadsstr)xs    r   load_geom_textz$_df_to_geodf.<locals>.load_geom_textV   s#    ;$$SVV$666    r   N	auth_name:zCould not find srid z+ in the spatial_ref_sys table. Trying epsg:z as a fallback.   
stacklevelzepsg:z[Could not find the spatial reference system table (spatial_ref_sys) in PostGIS.Trying epsg:)crsgeometry)r   columnsto_listcountdropnaemptyr   r   r   r
   iatbytesapplyget_srid_get_spatial_ref_sys_dfitemwarningswarnUserWarningpderrorsDatabaseErrorr   )dfgeom_colr$   congeomsload_geom_bytesr   	load_geomsridspatial_ref_sys_dfr   warning_msgs               r   _df_to_geodfr@   .   s7   2 rF8FFFGGG	z!!(++a//.( . . .
 
 	

 xL!!E; '-!++(	7 	7 	7 eilE** 	''II&I${{95558u;#EIaL11Dqyy-)@d)K)K& .3 
-$6{$C$H$H$J$J	!*33T33A4 A A+/A A A $
 !k;1MMMM,dnn' y. ) ) )='+= = =  
 M+{qIIII($..CCC)* h7777s   9E ;FFTc	           	          |.t          j        | |||||          }	t          |	          S t          j        | |||||          }
fd|
D             S )a  Return a GeoDataFrame corresponding to the result of the query
    string, which must contain a geometry column in WKB representation.

    It is also possible to use :meth:`~GeoDataFrame.read_file` to read from a database.
    Especially for file geodatabases like GeoPackage or SpatiaLite this can be easier.

    Parameters
    ----------
    sql : string
        SQL query to execute in selecting entries from database, or name
        of the table to read from the database.
    con : sqlalchemy.engine.Connection or sqlalchemy.engine.Engine
        Active connection to the database to query.
    geom_col : string, default 'geom'
        column name to convert to shapely geometries
    crs : dict or str, optional
        CRS to use for the returned GeoDataFrame; if not set, tries to
        determine CRS from the SRID associated with the first geometry in
        the database, and assigns that to all geometries.
    chunksize : int, default None
        If specified, return an iterator where chunksize is the number of rows to
        include in each chunk.

    See the documentation for pandas.read_sql for further explanation
    of the following parameters:
    index_col, coerce_float, parse_dates, params, chunksize

    Returns
    -------
    GeoDataFrame

    Examples
    --------
    PostGIS

    >>> from sqlalchemy import create_engine  # doctest: +SKIP
    >>> db_connection_url = "postgresql://myusername:mypassword@myhost:5432/mydatabase"
    >>> con = create_engine(db_connection_url)  # doctest: +SKIP
    >>> sql = "SELECT geom, highway FROM roads"
    >>> df = geopandas.read_postgis(sql, con)  # doctest: +SKIP

    SpatiaLite

    >>> sql = "SELECT ST_AsBinary(geom) AS geom, highway FROM roads"
    >>> df = geopandas.read_postgis(sql, con)  # doctest: +SKIP
    N)	index_colcoerce_floatparse_datesparams	chunksizer8   r$   r9   c              3   >   K   | ]}t          |           V  dS )rG   N)r@   ).0r7   r9   r$   r8   s     r   	<genexpr>z _read_postgis.<locals>.<genexpr>   sE       
 
FHLhCSAAA
 
 
 
 
 
r   )r4   read_sqlr@   )sqlr9   r8   r$   rB   rC   rD   rE   rF   r7   df_generators    ```       r   _read_postgisrN   ~   s    r [%#
 
 
 BsDDDD {%#
 
 

 
 
 
 
 
LX
 
 
 	
r   c                 T   t          | j        j                                                  }d}|D ]}|d|v rd}t	          |          dk    r7|rd}n4|d         t          d          |d                                         }nd	}t          | j        j                  r|d
z  }||fS )a  Get basic geometry type of a GeoDataFrame.

    See more info from:
    https://geoalchemy-2.readthedocs.io/en/latest/types.html#geoalchemy2.types._GISType

    Following rules apply:
     - if geometries all share the same geometry-type,
       geometries are inserted with the given GeometryType with following types:
        - Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon,
          GeometryCollection.
        - LinearRing geometries will be converted into LineString -objects.
     - in all other cases, geometries will be inserted with type GEOMETRY:
        - a mix of Polygons and MultiPolygons in GeoSeries
        - a mix of Points and LineStrings in GeoSeries
        - geometry is of type GeometryCollection,
          such as GeometryCollection([Point, LineStrings])
     - if any of the geometries has Z-coordinate, all records will
       be written with 3D.
    FN
LinearRingTr   
LINESTRINGr   z No valid geometries in the data.GEOMETRYZ)	listr%   	geom_typeuniquelenr   upperanyhas_z)gdf
geom_types	has_curvegttarget_geom_types        r   _get_geometry_typer`      s    ( cl,335566JI  :RI
:! 	9+!}$ !CDDD#-a=#6#6#8#8  % 3<  CY&&r   c                 j   d}d}| j         	 dD ]V}| j                             |          }| n6| j                             d|          }|t          |d                   } nWn,# t          $ r t          j        |t          d	           Y nw xY w|d
}t          j        |t          d	           |S )z6Get EPSG code from CRS if available. If not, return 0.NzNCould not parse CRS from the GeoDataFrame. Inserting data without defined CRS.)d   F      )min_confidenceESRI)r   re   r      r"   r   )r$   to_epsgto_authorityint	Exceptionr1   r2   r3   )r[   r=   r?   
confidence	auth_srids        r   _get_srid_from_crsrn     s     DX  w	B+ 	 	
wjAA#EG00$Z 1  	 (y|,,DE )  	B 	B 	BM+{qAAAAAA	B |k;1====Ks   AA' '&BBc                     ddl m | j        dk    }| j        ||f                             fd          | j        ||f<   | S )Nr   )
LineStringrP   c                      |           S )N )r   rp   s    r   <lambda>z3_convert_linearring_to_linestring.<locals>.<lambda>)  s    ZZ%% r   )shapely.geometryrp   rU   locr-   )r[   	geom_namemaskrp   s      @r   !_convert_linearring_to_linestringrx   !  sa    ++++++
 =L(D"wtY7==%%%%   CGD)O Jr   c                     t          j        t          j        | |         j        j        |          dd          }t          j        | d          }|||<   |S )zConvert geometries to ewkb.)r=   T)r   include_sridF)copy)r   to_wkbset_sridvalues_datar4   	DataFrame)r[   rv   r=   r:   r7   s        r   _convert_to_ewkbr   .  s_    NY.44@@@  E 
c	&	&	&BByMIr   c                    dd l }dd l}|                                }|                    |          }|                    |           |                    d           d                    d |D                       }|j        }	d| j        j	         d| j        j
         d| d}
|	                                5 }t          |d          rit          |j                  rU|                    |
          5 }|                    |                                           d d d            n# 1 swxY w Y   n|                    |
|           d d d            d S # 1 swxY w Y   d S )	Nr   z, c              3   "   K   | ]
}d | d V  dS )"Nrr   )rI   ks     r   rJ   z$_psql_insert_copy.<locals>.<genexpr>G  s*      //QA//////r   zCOPY "z"."z" (z) FROM STDIN WITH CSVr{   )csvioStringIOwriter	writerowsseekjoin
connectiontableschemanamecursorhasattrcallabler{   writereadcopy_expert)tblr   keys	data_iterr   r   s_bufr   r&   
dbapi_connrL   curr{   s                r   _psql_insert_copyr   >  s   JJJIIIKKMMEZZF
Y	JJqMMMii//$/////GJW!WWcinWWWWW  
				 (3 	(HSX$6$6 	(# )$

5::<<((() ) ) ) ) ) ) ) ) ) ) ) ) ) ) OOC'''( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (s6   6:E0(D$E$D(	(E+D(	,EEEfailFc	                 r   	 ddl m}	 ddlm}
 n# t          $ r t	          d          w xY w|                                 } | j        j        }t          |           }t          |           \  }}| |	||          ||<   n| |	||          i}|rt          | |          } t          | ||          } ||}nd}|dk    rt          |          5 }|j                            |||          rj|                     |
d	                              |||
                                                    d         }||k    rd| d| d}t%          |          ddd           n# 1 swxY w Y   t          |          5 }|                     ||||||||t(          	  	         ddd           dS # 1 swxY w Y   dS )a  
    Upload GeoDataFrame into PostGIS database.

    This method requires SQLAlchemy and GeoAlchemy2, and a PostgreSQL
    Python driver (e.g. psycopg2) to be installed.

    Parameters
    ----------
    name : str
        Name of the target table.
    con : sqlalchemy.engine.Connection or sqlalchemy.engine.Engine
        Active connection to the PostGIS database.
    if_exists : {'fail', 'replace', 'append'}, default 'fail'
        How to behave if the table already exists:

        - fail: Raise a ValueError.
        - replace: Drop the table before inserting new values.
        - append: Insert new values to the existing table.
    schema : string, optional
        Specify the schema. If None, use default schema: 'public'.
    index : bool, default True
        Write DataFrame index as a column.
        Uses *index_label* as the column name in the table.
    index_label : string or sequence, default None
        Column label for index column(s).
        If None is given (default) and index is True,
        then the index names are used.
    chunksize : int, optional
        Rows will be written in batches of this size at a time.
        By default, all rows will be written at once.
    dtype : dict of column name to SQL type, default None
        Specifying the datatype for columns.
        The keys should be the column names and the values
        should be the SQLAlchemy types.

    Examples
    --------
    >>> from sqlalchemy import create_engine  # doctest: +SKIP
    >>> engine = create_engine("postgresql://myusername:mypassword@myhost:5432/mydatabase";)  # doctest: +SKIP
    >>> gdf.to_postgis("my_table", engine)  # doctest: +SKIP
    r   )Geometry)textz,'to_postgis()' requires geoalchemy2 package.N)geometry_typer=   publicappendz2SELECT Find_SRID(:schema_name, :name, :geom_name);)schema_namer   rv   z"The CRS of the target table (EPSG:z5) differs from the CRS of current GeoDataFrame (EPSG:z).)r   	if_existsindexindex_labelrF   dtypemethod)geoalchemy2r   
sqlalchemyr   ImportErrorr{   r%   r   rn   r`   rx   r   r   dialect	has_tableexecute
bindparamsfetchoner   to_sqlr   )r[   r   r9   r   r   r   r   rF   r   r   r   rv   r=   r   r]   r   r   target_sridmsgs                      r   _write_postgisr   V  s   jJ((((((####### J J JHIIIJ ((**C!I c""D  2#66M9 #8-dKKKiHH=tLLLM  @/Y?? 3	4
0
0CHs^^ 	*z!++JfEE *(00DL  j$/di !    (**Q  $&&O[ O OFJO O O  %S//)!	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	*$ 
3 
:

#$ 	 
	
 
	
 
	

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s-    )BE!!E%(E%;$F,,F03F0c                 6    d| }t          j        ||           S )Nz9SELECT srid, auth_name FROM spatial_ref_sys WHERE srid = )r4   rK   )r9   r=   spatial_ref_sys_sqls      r   r/   r/     s*     	KDJJ  ;*C000r   )r   NN)r   NNTNNN)Nr   FNNN)r1   
contextlibr   	functoolsr   pandasr4   r   shapely.wkb	geopandasr   r   r@   rN   r`   rn   rx   r   r   r   r/   rr   r   r   <module>r      sk    % % % % % %                " " " " " " C C C@M8 M8 M8 M8f S
 S
 S
 S
l,' ,' ,'^  <
 
 
   ( ( (8 

u
 u
 u
 u
p 1 1 1 1 1r   