
    ChP<                         S SK r S SKJr  S SKJr  S SKrS SKrS SKrS SK	J
r
  \S 5       rSS jr       SS jrS rS	 rS
 rS rS r      SS jr\S 5       rg)    N)contextmanager)	lru_cache)GeoDataFramec              #   f  #    SSK JnJn  [        X5      (       a8  U R	                  5       (       d  U R                  5          U v   SSS5        gU v   g[        X5      (       a  U R                  5        nUv   SSS5        g[        SU  35      e! , (       d  f       g= f! , (       d  f       g= f7f)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       cC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\geopandas/io/sql.py	_get_connr      s     $ :.--,,..%%'$$ (' ! 	N	+	+!!#tJ $# 00@ABB ('
 $#s5   >B1 B.B13B 8B1
BB1 
B.*B1c                 \   X;  a  [        SU S35      eU R                  R                  5       R                  U5      S:  a  [        SU S35      eX   R	                  5       nUR
                  (       d  [        R                  R                  n S n[        UR                  S   [        5      (       a  UnOUnUR                  U5      =X'   nUc  [        R                  " UR                  S   5      nUS:w  aa   [        X85      n	U	R
                  (       d  U	S   R                  5       n
U
 S	U 3nO)S
U SU S3n[         R"                  " U[$        SS9  SU 3n [-        XUS9$ ! [&        R(                  R*                   a(    SU S3n[         R"                  " U[$        SS9  SU 3n NOf = f)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                 P    [         R                  R                  [        U 5      SS9$ )z!Load from binary encoded as text.T)hex)shapelywkbloadsstr)xs    r   load_geom_text$_df_to_geodf.<locals>.load_geom_textV   s     ;;$$SV$66    r   	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@   .   s   2 :8*AFGG	zz!!(+a/)( 4. .
 	

 L!E;;!++++(	7 eiilE**'I&I${{955u;##EIIaL1Dqy-)@)K& .33$6{$C$H$H$J	!*1TF3 34& 9++/&A $
 !k;1M %dVnh77+ yy.. )''+fO=  
 MM+{qI!$.C)s   ;E% %AF+*F+c	           
         ^^^ Uc&  [         R                  " U TUUUUUS9n	[        U	TTTS9$ [         R                  " U TUUUUUS9n
UUU4S jU
 5       $ )at  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
)	index_colcoerce_floatparse_datesparams	chunksizer8   r$   r9   c              3   <   >#    U  H  n[        UTTTS 9v   M     g7f)rG   N)r@   ).0r7   r9   r$   r8   s     r   	<genexpr> _read_postgis.<locals>.<genexpr>   s      
LXbLhCSALs   )r4   read_sqlr@   )sqlr9   r8   r$   rB   rC   rD   rE   rF   r7   df_generators    ```       r   _read_postgisrO   ~   sy    r [[%#
 BsDD {{%#

LX
 	
r   c                 h   [        U R                  R                  R                  5       5      nSnU H  nUc  M  SU;   d  M  SnM     [	        U5      S:X  a/  U(       a  SnO'US   c  [        S5      eUS   R                  5       nOSn[        U R                  R                  5      (       a  US	-  nXB4$ )
aG  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.
F
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_typera      s    ( cll,,3356JI:RI	  :!+!}$ !CDD#-a=#6#6#8 % 3<<C&&r   c                 f   SnSnU R                   bV   S HN  nU R                   R                  US9nUb    O2U R                   R                  SUS9nUc  M@  [        US   5      n  O    Uc  S
n[
        R                  " U[        SS	9  U$ ! [         a    [
        R                  " U[        SS	9   NGf = f)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   rf   r      r"   r   )r$   to_epsgto_authorityint	Exceptionr1   r2   r3   )r\   r=   r?   
confidence	auth_srids        r   _get_srid_from_crsro     s     DX  ww	B+
wwjA#GG00$Z 1 	 (y|,D , |k;1=K  	BMM+{qA	Bs"   "B	 B	 B	 %B	 	$B0/B0c                    ^ SSK Jm  U R                  S:H  nU R                  X!4   R	                  U4S j5      U R                  X!4'   U $ )Nr   )
LineStringrQ   c                    > T" U 5      $ )N )geomrq   s    r   <lambda>3_convert_linearring_to_linestring.<locals>.<lambda>)  s
    Z%r   )shapely.geometryrq   rV   locr-   )r\   	geom_namemaskrq   s      @r   !_convert_linearring_to_linestringr{   !  sF    +
 ==L(D"wwt7==% CGGDO Jr   c                     [         R                  " [         R                  " X   R                  R                  US9SSS9n[
        R                  " U SS9nX4U'   U$ )zConvert geometries to ewkb.)r=   T)r   include_sridF)copy)r   to_wkbset_sridvalues_datar4   	DataFrame)r\   ry   r=   r:   r7   s        r   _convert_to_ewkbr   .  sR    NN..444@E 
c	&ByMIr   c                    SS K nSS KnUR                  5       nUR                  U5      nUR	                  U5        UR                  S5        SR                  S U 5       5      nUR                  n	SU R                  R                   SU R                  R                   SU S3n
U	R                  5        n[        US5      (       aT  [        UR                  5      (       a:  UR                  U
5       nUR                  UR!                  5       5        S S S 5        OUR#                  X5        S S S 5        g ! , (       d  f       N= f! , (       d  f       g = f)	Nr   z, c              3   .   #    U  H  nS U S 3v   M     g7f)"Nrs   )rI   ks     r   rJ   $_psql_insert_copy.<locals>.<genexpr>G  s     /$Q!A3a$s   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_connrM   curr~   s                r   _psql_insert_copyr   >  s   KKMEZZF
Y	JJqMii/$//GJ
!!"#ciinn%5S	AVW  
			3HSXX$6$6#$

5::<(  OOC' 
	  
	s$   4=E1 D4E4
E	>E
Ec	                     SSK Jn	  SSKJn
  U R                  5       n U R                  R                  n[        U 5      n[        U 5      u  pUb	  U	" XS9X'   OX" XS90nU(       a  [        X5      n [        XU5      n Ub  UnOSnUS:X  a  [        U5       nUR                  R                  UX5      (       aL  UR                  U
" S	U S
U S
U S35      5      R!                  5       S   nUU:w  a  SU SU S3n[#        U5      eSSS5        [        U5       nU R%                  UUUUUUUU[&        S9	  SSS5        g! [         a    [	        S5      ef = f! , (       d  f       NW= f! , (       d  f       g= f)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appendzSELECT Find_SRID('z', 'z');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   ro   ra   r{   r   r   dialect	has_tableexecutefetchoner   to_sqlr   )r\   r   r9   r   r   r   r   rF   r   r   r   ry   r=   r   r^   schema_namer   target_sridmsgs                      r   _write_postgisr   V  s   jJ(# ((*C!!I c"D  2#6M #-KH=LM /? 34
0CHs^z!!++JEE(00-k]$tfDSVWX(*Q  $&<[M JFFJV2O  %S/)  
3:

#$ 	 
	
 
]  JHIIJ@ ^ 
s$   D< A.EE&<E
E#&
E4c                 8    SU 3n[         R                  " X 5      $ )Nz9SELECT srid, auth_name FROM spatial_ref_sys WHERE srid = )r4   rL   )r9   r=   spatial_ref_sys_sqls      r   r/   r/     s&     DD6J  ;;*00r   )rt   NN)rt   NNTNNN)NfailFNNN)r1   
contextlibr   	functoolsr   pandasr4   r   shapely.wkb	geopandasr   r   r@   rO   ra   ro   r{   r   r   r   r/   rs   r   r   <module>r      s     %     " C C@M8f S
l,'^<
 (8 

q
h 1 1r   