U
    /eP                  
   @   s   d dl Z d dlZd dlZd dlmZ d dlm	Z	 d dl
mZmZ d dlmZmZ d dlmZ dd	d
ZdddZdd ZdddZdddZd eeeedddZeddddZdS )!    N)compute)methods)from_delayedfrom_pandas)delayedtokenize)parse_bytes256 MiB   c
                 K   s`  ddl }t|ts*tdtt| d |dkr:tdt|t|j|jjj	fsftdtt| |dks|dkr~td|dkr|dkrtd|r|rtd	|	dkri n|	}	|j
|f|	}t|tr||n||j|j}|j|
d
< |dkr^| |}tj||f|
}t|dkr0t|ddS |jddd | }|dkr^|jdd }|dkr|dkr|j|jj||jj|g|  }t||}|jd \}}|jd }n|\}}t|j}|dkr8|j|jj|g|  }t||d d }tt|| t | p6d}|j!dkr|t"#tj$||d|| % |  d}||d< ||d< n6|j!dkrt&j'|||d |d# }ntd(|g }|dd |dd  }}t)t*||D ]j\}\}}|t|d kr||kn||k }| +|j,||k|}|-t.t/|||fd|	i|
 q|0  t1|||dS )ar	  
    Read SQL query into a DataFrame.

    If neither ``divisions`` or ``npartitions`` is given, the memory footprint of the
    first few rows will be determined, and partitions of size ~256MB will
    be used.

    Parameters
    ----------
    sql : SQLAlchemy Selectable
        SQL query to be executed. TextClause is not supported
    con : str
        Full sqlalchemy URI for the database connection
    index_col : str
        Column which becomes the index, and defines the partitioning. Should
        be a indexed column in the SQL server, and any orderable type. If the
        type is number or time, then partition boundaries can be inferred from
        ``npartitions`` or ``bytes_per_chunk``; otherwise must supply explicit
        ``divisions``.
    divisions: sequence
        Values of the index column to split the table by. If given, this will
        override ``npartitions`` and ``bytes_per_chunk``. The divisions are the value
        boundaries of the index column used to define the partitions. For
        example, ``divisions=list('acegikmoqsuwz')`` could be used to partition
        a string column lexographically into 12 partitions, with the implicit
        assumption that each partition contains similar numbers of records.
    npartitions : int
        Number of partitions, if ``divisions`` is not given. Will split the values
        of the index column linearly between ``limits``, if given, or the column
        max/min. The index column must be numeric or time for this to work
    limits: 2-tuple or None
        Manually give upper and lower range of values for use with ``npartitions``;
        if None, first fetches max/min from the DB. Upper limit, if
        given, is inclusive.
    bytes_per_chunk : str or int
        If both ``divisions`` and ``npartitions`` is None, this is the target size of
        each partition, in bytes
    head_rows : int
        How many rows to load for inferring the data-types, and memory per row
    meta : empty DataFrame or None
        If provided, do not attempt to infer dtypes, but use these, coercing
        all chunks on load
    engine_kwargs : dict or None
        Specific db engine parameters for sqlalchemy
    kwargs : dict
        Additional parameters to pass to `pd.read_sql()`

    Returns
    -------
    dask.dataframe

    See Also
    --------
    read_sql_table : Read SQL database table into a DataFrame.
    r   Nz'con' must be of type str, not 8Note: Dask does not support SQLAlchemy connectables herez)Must specify index column to partition onz2'index_col' must be of type str or sa.Column, not z'Must provide 'meta' if 'head_rows' is 0z=Must provide 'divisions' or 'npartitions' if 'head_rows' is 0z9Must supply either 'divisions' or 'npartitions', not both	index_col   )npartitionsT)deepindexZmax_1Zcount_1Mz%iS)startendfreq)iuf)dtypezwProvided index column is of type "{}".  If divisions is not provided the index column type must be numeric or datetime.engine_kwargs)	divisions)2
sqlalchemy
isinstancestr	TypeErrortype
ValueErrorColumnsqlelementsZColumnClausecreate_enginenamelimitpdread_sqllenr   Zmemory_usagesumZilocselectfuncmaxminselect_fromZsubquerydtypesZSeriesr   countintroundr   kindr   tolistZ
date_rangetotal_secondsnpZlinspaceformat	enumeratezipwhereand_appendr   _read_sql_chunkdisposer   )r#   conr   r   r   limitsbytes_per_chunk	head_rowsmetar   kwargssaenginer   qheadZbytes_per_rowZminmaxZmaxiZminir   r2   partsZlowersZuppersr   lowerupperZcond rN   9/tmp/pip-unpacked-wheel-dbjnr7gq/dask/dataframe/io/sql.pyread_sql_query   s    D








"
"  rP   c                    s  ddl  ddl m} d|kr2tdt |dd|krPtdt |d}ttsntdtt	 |dk	r|D ](}t| j
tfsztd	tt	| qzt|tstd
tt	| d |dkri n|} j|f|}  }ttr j|d||	dntdtt	 |  |rD fdd|D n fddjD }t|trx 
|j| j	n 
|j|j	}|jdd |D kr|| ||}tf |||||||||
|d
|S )a  
    Read SQL database table into a DataFrame.

    If neither ``divisions`` or ``npartitions`` is given, the memory footprint of the
    first few rows will be determined, and partitions of size ~256MB will
    be used.

    Parameters
    ----------
    table_name : str
        Name of SQL table in database.
    con : str
        Full sqlalchemy URI for the database connection
    index_col : str
        Column which becomes the index, and defines the partitioning. Should
        be a indexed column in the SQL server, and any orderable type. If the
        type is number or time, then partition boundaries can be inferred from
        ``npartitions`` or ``bytes_per_chunk``; otherwise must supply explicit
        ``divisions``.
    columns : sequence of str or SqlAlchemy column or None
        Which columns to select; if None, gets all. Note can be a mix of str and SqlAlchemy columns
    schema : str or None
        Pass this to sqlalchemy to select which DB schema to use within the
        URI connection
    divisions: sequence
        Values of the index column to split the table by. If given, this will
        override ``npartitions`` and ``bytes_per_chunk``. The divisions are the value
        boundaries of the index column used to define the partitions. For
        example, ``divisions=list('acegikmoqsuwz')`` could be used to partition
        a string column lexographically into 12 partitions, with the implicit
        assumption that each partition contains similar numbers of records.
    npartitions : int
        Number of partitions, if ``divisions`` is not given. Will split the values
        of the index column linearly between ``limits``, if given, or the column
        max/min. The index column must be numeric or time for this to work
    limits: 2-tuple or None
        Manually give upper and lower range of values for use with ``npartitions``;
        if None, first fetches max/min from the DB. Upper limit, if
        given, is inclusive.
    bytes_per_chunk : str or int
        If both ``divisions`` and ``npartitions`` is None, this is the target size of
        each partition, in bytes
    head_rows : int
        How many rows to load for inferring the data-types, and memory per row
    meta : empty DataFrame or None
        If provided, do not attempt to infer dtypes, but use these, coercing
        all chunks on load
    engine_kwargs : dict or None
        Specific db engine parameters for sqlalchemy
    kwargs : dict
        Additional parameters to pass to `pd.read_sql()`

    Returns
    -------
    dask.dataframe

    See Also
    --------
    read_sql_query : Read SQL query into a DataFrame.

    Examples
    --------
    >>> df = dd.read_sql_table('accounts', 'sqlite:///path/to/bank.db',
    ...                  npartitions=10, index_col='id')  # doctest: +SKIP
    r   N)r#   tablezWThe `table` keyword has been replaced by `table_name`. Please use `table_name` instead.urizGThe `uri` keyword has been replaced by `con`. Please use `con` instead.z&`table_name` must be of type str, not z8`columns` must be of type List[str], and cannot contain z`con` must be of type str, not r   T)ZautoloadZautoload_withschemac                    s:   g | ]2}t |tr& |j| jn |j|jqS rN   )r   r   r"   columnsr    r&   .0crG   
table_namerN   rO   
<listcomp>7  s   z"read_sql_table.<locals>.<listcomp>c                    s   g | ]}  |j|jqS rN   )r"   r&   r    rU   )rG   rN   rO   rZ   @  s     c                 S   s   g | ]
}|j qS rN   )r&   rU   rN   rN   rO   rZ   H  s     )
r#   rA   r   r   r   rB   rC   rD   rE   r   )r   r#   warningswarnDeprecationWarningpopr   r   r   r    r"   r%   ZMetaDataZTabler@   rT   r&   r>   r,   r0   rP   )rY   rA   r   r   r   rB   rT   rC   rD   rS   rE   r   rF   r#   colrH   mr   queryrN   rX   rO   read_sql_table   s    P





    	
rb   c                 K   s.   t | trt| ||f|S t| ||f|S dS )a  
    Read SQL query or database table into a DataFrame.

    This function is a convenience wrapper around ``read_sql_table`` and
    ``read_sql_query``. It will delegate to the specific function depending
    on the provided input. A SQL query will be routed to ``read_sql_query``,
    while a database table name will be routed to ``read_sql_table``.
    Note that the delegated function might have more specific notes about
    their functionality not listed here.

    Parameters
    ----------
    sql : str or SQLAlchemy Selectable
        Name of SQL table in database or SQL query to be executed. TextClause is not supported
    con : str
        Full sqlalchemy URI for the database connection
    index_col : str
        Column which becomes the index, and defines the partitioning. Should
        be a indexed column in the SQL server, and any orderable type. If the
        type is number or time, then partition boundaries can be inferred from
        ``npartitions`` or ``bytes_per_chunk``; otherwise must supply explicit
        ``divisions``.

    Returns
    -------
    dask.dataframe

    See Also
    --------
    read_sql_table : Read SQL database table into a DataFrame.
    read_sql_query : Read SQL query into a DataFrame.
    N)r   r   rb   rP   )r#   rA   r   rF   rN   rN   rO   r)   \  s    !
r)   c                 K   st   dd l }|pi }|j|f|}tj| |f|}|  t|dkrF|S t|j dkr\|S |j|j ddS d S )Nr   F)copy)	r   r%   r(   r)   r@   r*   r1   Zto_dictZastype)rI   rR   rE   r   rF   rG   rH   dfrN   rN   rO   r?     s    r?   c                 K   s>   dd l }|pi }|j|f|}| jf d|i|}|  |S )Nr   rA   )r   r%   to_sqlr@   )drR   r   rF   rG   rH   rI   rN   rN   rO   _to_sql_chunk  s    rg   failTF)r&   rR   	if_existsr   c                    s   t |tstdt| dt||||||||||	d
}tt| jf| t|dd|rv fdd|  D }nLg } }|  D ]:}|	t
t|fd|id	d
t|f i |d }qt|}|
rt| n|S dS )a  Store Dask Dataframe to a SQL table

    An empty table is created based on the "meta" DataFrame (and conforming to the caller's "if_exists" preference), and
    then each block calls pd.DataFrame.to_sql (with `if_exists="append"`).

    Databases supported by SQLAlchemy [1]_ are supported. Tables can be
    newly created, appended to, or overwritten.

    Parameters
    ----------
    name : str
        Name of SQL table.
    uri : string
        Full sqlalchemy URI for the database connection
    schema : str, optional
        Specify the schema (if database flavor supports this). If None, use
        default schema.
    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.

    index : bool, default True
        Write DataFrame index as a column. Uses `index_label` as the column
        name in the table.
    index_label : str 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.
        A sequence should be given if the DataFrame uses MultiIndex.
    chunksize : int, optional
        Specify the number of rows in each batch to be written at a time.
        By default, all rows will be written at once.
    dtype : dict or scalar, optional
        Specifying the datatype for columns. If a dictionary is used, the
        keys should be the column names and the values should be the
        SQLAlchemy types or strings for the sqlite3 legacy mode. If a
        scalar is provided, it will be applied to all columns.
    method : {None, 'multi', callable}, optional
        Controls the SQL insertion clause used:

        * None : Uses standard SQL ``INSERT`` clause (one per row).
        * 'multi': Pass multiple values in a single ``INSERT`` clause.
        * callable with signature ``(pd_table, conn, keys, data_iter)``.

        Details and a sample callable implementation can be found in the
        section :ref:`insert method <io.sql.method>`.
    compute : bool, default True
        When true, call dask.compute and perform the load into SQL; otherwise, return a Dask object (or array of
        per-block objects when parallel=True)
    parallel : bool, default False
        When true, have each block append itself to the DB table concurrently. This can result in DB rows being in a
        different order than the source DataFrame's corresponding rows. When false, load each block into the SQL DB in
        sequence.
    engine_kwargs : dict or None
        Specific db engine parameters for sqlalchemy

    Raises
    ------
    ValueError
        When the table already exists and `if_exists` is 'fail' (the
        default).

    See Also
    --------
    read_sql : Read a DataFrame from a table.

    Notes
    -----
    Timezone aware datetime columns will be written as
    ``Timestamp with timezone`` type with SQLAlchemy if supported by the
    database. Otherwise, the datetimes will be stored as timezone unaware
    timestamps local to the original timezone.

    .. versionadded:: 0.24.0

    References
    ----------
    .. [1] https://docs.sqlalchemy.org
    .. [2] https://www.python.org/dev/peps/pep-0249/

    Examples
    --------
    Create a table from scratch with 4 rows.

    >>> import pandas as pd
    >>> import dask.dataframe as dd
    >>> df = pd.DataFrame([ {'i':i, 's':str(i)*2 } for i in range(4) ])
    >>> ddf = dd.from_pandas(df, npartitions=2)
    >>> ddf  # doctest: +SKIP
    Dask DataFrame Structure:
                       i       s
    npartitions=2
    0              int64  object
    2                ...     ...
    3                ...     ...
    Dask Name: from_pandas, 2 tasks

    >>> from dask.utils import tmpfile
    >>> from sqlalchemy import create_engine
    >>> with tmpfile() as f:
    ...     db = 'sqlite:///%s' %f
    ...     ddf.to_sql('test', db)
    ...     engine = create_engine(db, echo=False)
    ...     result = engine.execute("SELECT * FROM test").fetchall()
    >>> result
    [(0, 0, '00'), (1, 1, '11'), (2, 2, '22'), (3, 3, '33')]
    z!Expected URI to be a string, got .)
r&   rR   r   rS   ri   r   index_label	chunksizer   methodr>   )ri   c                    s4   g | ],}t t|fd  iddt|f iqS )extrasdask_key_name	to_sql-%s)_extra_depsrg   r   )rV   rf   Z	meta_taskZworker_kwargsrN   rO   rZ   4  s   zto_sql.<locals>.<listcomp>rn   ro   rp   r   N)r   r   r!   r    dictr   rg   Z_metaZ
to_delayedr>   rq   r   dask_compute)rd   r&   rR   rS   ri   r   rk   rl   r   rm   r   parallelr   rF   resultlastrf   rN   rr   rO   re     sP    |
	

re   )rn   c                O   s
   | ||S )NrN   )r-   rn   argsrF   rN   rN   rO   rq   U  s    rq   )NNNr	   r
   NN)	NNNNr	   r
   NNN)N)N)
Nrh   TNNNNTFN)r[   Znumpyr8   Zpandasr(   Z	dask.baser   rt   Zdask.dataframer   Zdask.dataframe.io.ior   r   Zdask.delayedr   r   Z
dask.utilsr   rP   rb   r)   r?   rg   r   boolre   rq   rN   rN   rN   rO   <module>   sb          
 .         
 ''

           6