B ®@`÷ã@sØdZddlmZddlmZmZmZddlmZddlZddl m Z m Z m Z m Z mZddlZddlZddlmmZddlmZmZmZddlmZdd lmZdd lmZmZdd l m!Z!dd l"m#Z#Gd d„de$ƒZ%Gdd„de&ƒZ'da(dd„Z)dd„Z*dd„Z+dQdd„Z,dd„Z-dRdd„Z.dSdd„Z/edTded œd!d"„ƒZ0edUe1e ed œd$d"„ƒZ0dVe e1e ee efd œd%d"„Z0edWded œd&d'„ƒZ2edXe1e ed œd(d'„ƒZ2dYe e1e ee efd œd)d'„Z2edZded œd*d+„ƒZ3ed[e1e ed œd,d+„ƒZ3d\e e1e ee efd œd-d+„Z3d]dd/œd0d1„Z4d^d2d3„Z5e5Z6d4d5„Z7d_d7d8„Z8Gd9d:„d:e!ƒZ9Gd;d<„d„d>e:ƒZ;d?d@dAdBdCdDdAdEœZdJZ?GdKdL„dLe9ƒZ@GdMdN„dNe:ƒZAd`dOdP„ZBdS)az| Collection of query wrappers / abstractions to both facilitate data retrieval and to reduce dependency on DB-specific API. é)Úcontextmanager)ÚdateÚdatetimeÚtime)ÚpartialN)ÚIteratorÚListÚOptionalÚUnionÚoverload)Úis_datetime64tz_dtypeÚ is_dict_likeÚ is_list_like)ÚDatetimeTZDtype)Úisna)Ú DataFrameÚSeries)Ú PandasObject)Ú to_datetimec@s eZdZdS)ÚSQLAlchemyRequiredN)Ú__name__Ú __module__Ú __qualname__©rrú1/tmp/pip-unpacked-wheel-q9tj5l6a/pandas/io/sql.pyrsrc@s eZdZdS)Ú DatabaseErrorN)rrrrrrrrsrcCsTtdkr2yddl}daWntk r0daYnXtrLddl}t||jjƒSdSdS)NrTF)Ú_SQLALCHEMY_INSTALLEDÚ sqlalchemyÚ ImportErrorÚ isinstanceÚengineZ Connectable)ÚconrrrrÚ_is_sqlalchemy_connectable(s r"cCs6|g}|dk r2t|dƒr$||g7}n|t|ƒg7}|S)z9Convert SQL and params args to DBAPI2.0 compliant format.NÚkeys)ÚhasattrÚlist)ÚsqlÚparamsÚargsrrrÚ_convert_params:s   r)cCs2|dks|dks|dkrg}nt|dƒs.|g}|S)z3Process parse_dates argument for read_sql functionsTNFÚ__iter__)r$)Ú parse_datesrrrÚ_process_parse_dates_argumentEs  r,cCsŒt|tƒrt|fddi|—ŽS|dkrJt|jjtjƒsFt|jjtjƒrJd}|dkrbt|d||d�St |jƒrxt|dd�St|d||d �SdS) NÚerrorsÚignoreÚs)ÚDÚdÚhÚmr/ÚmsÚusÚnsZcoerce)r-ÚunitÚutcT)r8)r-Úformatr8) rÚdictrÚ issubclassÚdtypeÚtypeÚnpÚfloatingÚintegerr )Úcolr8r9rrrÚ_handle_date_columnPs   rBc Csjt|ƒ}x\| ¡D]P\}}t|jƒs,||kry ||}Wntk rPd}YnXt||d�||<qW|S)zz Force non-datetime columns to be read as such. Supports both string formatted and integer timestamp columns. N)r9)r,Úitemsr r<Ú TypeErrorrB)Z data_framer+Úcol_nameÚdf_colÚfmtrrrÚ_parse_date_columnses  rHTcCs4tj|||d�}t||ƒ}|dk r0|j|dd�|S)z(Wrap result set of query in a DataFrame.)ÚcolumnsÚ coerce_floatNT)Úinplace)rÚ from_recordsrHÚ set_index)ÚdatarIÚ index_colrJr+ÚframerrrÚ _wrap_resultzs  rQcCs2|dkrt|ƒ}n t|dd�}t||ƒ}|j|ŽS)aY Execute the given SQL query using the provided connection object. Parameters ---------- sql : string SQL query to be executed. con : SQLAlchemy connectable(engine/connection) or sqlite3 connection Using SQLAlchemy makes it possible to use any DB supported by the library. If a DBAPI2 object, only sqlite3 is supported. cur : deprecated, cursor is obtained from connection, default: None params : list or tuple, optional, default: None List of parameters to pass to execute method. Returns ------- Results Iterable NT)Ú is_cursor)ÚpandasSQL_builderr)Úexecute)r&r!Úcurr'Ú pandas_sqlr(rrrrT†s    rT)Ú chunksizeÚreturncCsdS)Nr)Ú table_namer!ÚschemarOrJr+rIrWrrrÚread_sql_table¦s r[écCsdS)Nr)rYr!rZrOrJr+rIrWrrrr[´s c CsÊt|ƒ}t|ƒstdƒ‚ddl}ddlm} | ||d�} y| j|gdd�Wn8|jjk r„} zt d|›d �ƒ| ‚Wdd} ~ XYnXt || d �} | j ||||||d �} | dk r´| St d|›d �|ƒ‚dS) a~ Read SQL database table into a DataFrame. Given a table name and a SQLAlchemy connectable, returns a DataFrame. This function does not support DBAPI connections. Parameters ---------- table_name : str Name of SQL table in database. con : SQLAlchemy connectable or str A database URI could be provided as str. SQLite DBAPI connection mode not supported. schema : str, default None Name of SQL schema in database to query (if database flavor supports this). Uses default schema if None (default). index_col : str or list of str, optional, default: None Column(s) to set as index(MultiIndex). coerce_float : bool, default True Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Can result in loss of Precision. parse_dates : list or dict, default None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. columns : list, default None List of column names to select from SQL table. chunksize : int, default None If specified, returns an iterator where `chunksize` is the number of rows to include in each chunk. Returns ------- DataFrame or Iterator[DataFrame] A SQL table is returned as two-dimensional data structure with labeled axes. See Also -------- read_sql_query : Read SQL query into a DataFrame. read_sql : Read SQL query or database table into a DataFrame. Notes ----- Any datetime values with time zone information will be converted to UTC. Examples -------- >>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP z9read_sql_table only supported for SQLAlchemy connectable.rN)ÚMetaData)rZT)ÚonlyZviewszTable z not found)Úmeta)rOrJr+rIrW) Ú_engine_builderr"ÚNotImplementedErrorrÚsqlalchemy.schemar]ÚreflectÚexcZInvalidRequestErrorÚ ValueErrorÚ SQLDatabaseÚ read_table)rYr!rZrOrJr+rIrWrr]r_ÚerrrVÚtablerrrr[Âs,A  $ cCsdS)Nr)r&r!rOrJr'r+rWrrrÚread_sql_query!s rjcCsdS)Nr)r&r!rOrJr'r+rWrrrrj.s cCst|ƒ}|j||||||d�S)a7 Read SQL query into a DataFrame. Returns a DataFrame corresponding to the result set of the query string. Optionally provide an `index_col` parameter to use one of the columns as the index, otherwise default integer index will be used. Parameters ---------- sql : str SQL query or SQLAlchemy Selectable (select or text object) SQL query to be executed. con : SQLAlchemy connectable, str, or sqlite3 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. index_col : str or list of str, optional, default: None Column(s) to set as index(MultiIndex). coerce_float : bool, default True Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Useful for SQL result sets. params : list, tuple or dict, optional, default: None List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}. parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. Returns ------- DataFrame or Iterator[DataFrame] See Also -------- read_sql_table : Read SQL database table into a DataFrame. read_sql : Read SQL query or database table into a DataFrame. Notes ----- Any datetime values with time zone information parsed via the `parse_dates` parameter will be converted to UTC. )rOr'rJr+rW)rSÚ read_query)r&r!rOrJr'r+rWrVrrrrj;s=cCsdS)Nr)r&r!rOrJr'r+rIrWrrrÚread_sqlƒs rlcCsdS)Nr)r&r!rOrJr'r+rIrWrrrrl‘s c Cs”t|ƒ}t|tƒr(|j||||||d�Sy| |¡} Wntk rNd} YnX| rz|jj|gd�|j||||||d�S|j||||||d�SdS)a Read SQL query or database table into a DataFrame. This function is a convenience wrapper around ``read_sql_table`` and ``read_sql_query`` (for backward compatibility). 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 (select or text object) SQL query to be executed or a table name. con : SQLAlchemy connectable, str, or sqlite3 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. The user is responsible for engine disposal and connection closure for the SQLAlchemy connectable; str connections are closed automatically. See `here `_. index_col : str or list of str, optional, default: None Column(s) to set as index(MultiIndex). coerce_float : bool, default True Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets. params : list, tuple or dict, optional, default: None List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}. parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. columns : list, default: None List of column names to select from SQL table (only used when reading a table). chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. Returns ------- DataFrame or Iterator[DataFrame] See Also -------- read_sql_table : Read SQL database table into a DataFrame. read_sql_query : Read SQL query into a DataFrame. )rOr'rJr+rWF)r^)rOrJr+rIrWN) rSrÚSQLiteDatabaserkÚ has_tableÚ Exceptionr_rcrg) r&r!rOrJr'r+rIrWrVZ_is_table_namerrrrlŸs:B  Úfail)rXc Csj|dkrtd|›d�ƒ‚t||d�} t|tƒr8| ¡}nt|tƒsJtdƒ‚| j||||||||| d� dS)a; Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame, Series name : str Name of SQL table. con : SQLAlchemy connectable(engine/connection) or database string URI or sqlite3 DBAPI2 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. schema : str, optional Name of SQL schema in database to write to (if database flavor supports this). If None, use default schema (default). if_exists : {'fail', 'replace', 'append'}, default 'fail' - fail: If table exists, do nothing. - replace: If table exists, drop it, recreate it, and insert data. - append: If table exists, insert data. Create if does not exist. index : boolean, default True Write DataFrame index as a column. index_label : str or sequence, optional 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 fallback 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 `. .. versionadded:: 0.24.0 )rpÚreplaceÚappendú'z' is not valid for if_exists)rZz9'frame' argument should be either a Series or a DataFrame)Ú if_existsÚindexÚ index_labelrZrWr<ÚmethodN)rerSrrZto_framerraÚto_sql) rPÚnamer!rZrtrurvrWr<rwrVrrrrxs$:    rxcCst||d�}| |¡S)a- Check if DataBase has named table. Parameters ---------- table_name: string Name of SQL table. con: SQLAlchemy connectable(engine/connection) or sqlite3 DBAPI2 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If None, use default schema (default). Returns ------- boolean )rZ)rSrn)rYr!rZrVrrrrn[s rncCsBt|tƒr>y ddl}Wntk r.daYnX| |¡}|S|S)zw Returns a SQLAlchemy engine from a URI (if con is a string) else it just return con without modifying it. rNF)rÚstrrrrZ create_engine)r!rrrrr`vs    r`FcCsBt|ƒ}t|ƒrt|||d�St|tƒr2tdƒ‚n t||d�SdS)zm Convenience function to return the correct PandasSQL subclass based on the provided parameters. )rZr_z.Using URI string without sqlalchemy installed.)rRN)r`r"rfrrzrrm)r!rZr_rRrrrrSˆs   rSc@s¢eZdZdZd(dd„Zdd „Zd d „Zd d „Zdd„Zdd„Z dd„Z dd„Z d)dd„Z d*dd„Z d+dd„Zdd„Zdd„Zd d!„Zd,d"d#„Zd$d%„Zd&d'„ZdS)-ÚSQLTablezî For mapping Pandas tables to SQL tables. Uses fact that table is reflected by SQLAlchemy to do better type conversions. Also holds various flags needed to avoid having to pass them between functions all the time. NTrpÚpandasc Cs„||_||_||_||_| ||¡|_||_||_| |_| |_ |dk rR|  ¡|_ n|j  |j|j¡|_ |j dkr€t d|›d�ƒ‚dS)NzCould not init table 'rs)ryÚpd_sqlÚprefixrPÚ _index_namerurZrtr#r<Ú_create_table_setupriÚ get_tablere) ÚselfryZpandas_sql_enginerPrurtr~rvrZr#r<rrrÚ__init__£s   zSQLTable.__init__cCs|j |j|j¡S)N)r}rnryrZ)r‚rrrÚexistsÄszSQLTable.existscCs$ddlm}t||jƒ |jj¡ƒS)Nr)Ú CreateTable)rbr…rzriÚcompiler}Ú connectable)r‚r…rrrÚ sql_schemaÇs zSQLTable.sql_schemacCs |j |jj¡|_|j ¡dS)N)riZ tometadatar}r_Úcreate)r‚rrrÚ_execute_createÌszSQLTable._execute_createcCsx| ¡rl|jdkr&td|j›d�ƒ‚qt|jdkrL|j |j|j¡| ¡qt|jdkrXqttd|j›d�ƒ‚n| ¡dS)NrpzTable 'z' already exists.rqrrrsz' is not valid for if_exists)r„rtreryr}Ú drop_tablerZrŠ)r‚rrrr‰Ñs    zSQLTable.createcs(‡fdd„|Dƒ}| |j ¡|¡dS)a< Execute SQL statement inserting data Parameters ---------- conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection keys : list of str Column names data_iter : generator of list Each item contains a list of values to be inserted csg|]}ttˆ|ƒƒ‘qSr)r:Úzip)Ú.0Úrow)r#rrú ësz,SQLTable._execute_insert..N)rTriÚinsert)r‚Úconnr#Ú data_iterrNr)r#rÚ_execute_insertßs zSQLTable._execute_insertcs(‡fdd„|Dƒ}| |j |¡¡dS)a Alternative to _execute_insert for DBs support multivalue INSERT. Note: multi-value insert is usually faster for analytics DBs and tables containing a few columns but performance degrades quickly with increase of columns. csg|]}ttˆ|ƒƒ‘qSr)r:rŒ)r�rŽ)r#rrr�ösz2SQLTable._execute_insert_multi..N)rTrir�)r‚r‘r#r’rNr)r#rÚ_execute_insert_multiîszSQLTable._execute_insert_multic Cs0|jdk rd|j ¡}|j|j_y|jdd�Wqjtk r`}ztd|›�ƒ|‚Wdd}~XYqjXn|j}ttt|j ƒƒ}t |ƒ}dg|}xšt |  ¡ƒD]Š\}\}}|j } | jjdkrÂ|  ¡} n(| jjdkrà|  d¡ t¡} n |  t¡} t| tjƒ�stt| ƒƒ‚|j�rt| ƒ} d| | <| ||<qšW||fS)NT)rKz!duplicate name in index/columns: ÚMr3Úi8)rurPÚcopyÚnamesZ reset_indexrer%ÚmaprzrIÚlenÚ enumeraterCZ_valuesr<ÚkindZ to_pydatetimeÚviewÚastypeÚobjectrr>ZndarrayÚAssertionErrorr=Z _can_hold_nar) r‚ÚtemprhÚ column_namesZncolsÚ data_listÚiÚ_ZserÚvalsr1ÚmaskrrrÚ insert_dataùs0   $      zSQLTable.insert_datac s|dkr|j}n2|dkr |j}n"t|ƒr4t||ƒ}ntd|›�ƒ‚| ¡\}}t|jƒ}|dkrddS|dkrr|}n|dkr‚tdƒ‚t||ƒd}|j   ¡�`}xXt |ƒD]L} | |‰t | d||ƒ‰ˆˆkrÐPt ‡‡fdd„|DƒŽ} |||| ƒq¨WWdQRXdS)NZmultizInvalid parameter `method`: rz%chunksize argument should be non-zeror\csg|]}|ˆˆ…‘qSrr)r�Zarr)Úend_iÚstart_irrr�>sz#SQLTable.insert..)r“r”Úcallablerrer¨ršrPÚintr}Úrun_transactionÚrangeÚminrŒ) r‚rWrwZ exec_insertr#r£ZnrowsÚchunksr‘r¤Z chunk_iterr)r©rªrr�s0    zSQLTable.insertccs^xX| |¡}|sPqtj|||d�|_|j|d�|jdk rN|jj|jdd�|jVqWdS)z,Return generator through chunked result set.)rIrJ)r+NT)rK)Ú fetchmanyrrLrPÚ_harmonize_columnsrurM)r‚ÚresultrWrIrJr+rNrrrÚ_query_iteratorAs   zSQLTable._query_iteratorc sú|dk rtt|ƒdkrtddlm}‡fdd„|Dƒ}ˆjdk rjx,ˆjddd…D]}| dˆjj|¡qNW||ƒ}n ˆj ¡}ˆj |¡} |   ¡} |dk r®ˆj | || ||d�S|   ¡} t j | | |d�ˆ_ˆj|d�ˆjdk rðˆjjˆjd d �ˆjSdS) Nr)Úselectcsg|]}ˆjj|‘qSr)riÚc)r�Ún)r‚rrr�Zsz!SQLTable.read..éÿÿÿÿ)rJr+)rIrJ)r+T)rK)ršrrµrur�rir¶r}rTr#r´ÚfetchallrrLrPr²rM) r‚rJr+rIrWrµÚcolsÚidxZ sql_selectr³r¢rNr)r‚rÚreadUs0       z SQLTable.readcCs²|dkrŒ|jjj}|dk rJt|tƒs*|g}t|ƒ|krFtd|›�ƒ‚n|S|dkrrd|jjkrr|jjjdkrrdgSdd„t |jjj ƒDƒSn"t|t ƒrœ|gSt|tƒrª|SdSdS)NTz@Length of 'index_label' should match number of levels, which is r\rucSs&g|]\}}|dk r|nd|›�‘qS)NZlevel_r)r�r¤Úlrrrr�’sz(SQLTable._index_name..) rPruÚnlevelsrr%ršrerIryr›r˜rz)r‚rurvr¾rrrrzs(      zSQLTable._index_namecstg}ˆjdk rLx.) rur›rPZ_get_level_valuesrrrzr®ršrI)r‚r¿Úcolumn_names_and_typesr¤Z idx_labelZidx_typer)r¿r‚rÚ_get_column_names_and_typesžs  z$SQLTable._get_column_names_and_typesc s¶ddlm‰m}m}| |j¡}‡fdd„|Dƒ}|jdk rtt|jƒsP|jg}n|j}||d|jdiŽ}|  |¡|j p‚|j j j }ddl m}||j |d�} ||j| f|žd |iŽS) Nr)ÚColumnÚPrimaryKeyConstraintÚTablecs g|]\}}}ˆ|||d�‘qS))rur)r�ryÚtypÚis_index)rÂrrr�²sz0SQLTable._create_table_setup..ryZ_pk)r])rZrZ)rrÂrÃrÄrÁÚ_sqlalchemy_typer#rryrrrZr}r_rbr]) r‚rÃrÄrÀrIr#ZpkcrZr]r_r)rÂrr€¬s       zSQLTable._create_table_setupc Cs,t|ƒ}�x|jjD�]}|j}yì|j|}||krny ||}Wntk rXd}YnXt||d�|j|<w| |j¡}|t ks’|t ks’|t kr®|t k}t||d�|j|<n\|t krÌ|j |dd�|j|<n>t|ƒ| ¡k�r |t d¡ksö|tk�r |j |dd�|j|<Wqtk �r"YqXqWdS)a Make the DataFrame's column types align with the SQL table column types. Need to work around limited NA value support. Floats are always fine, ints must always be floats if there are Null values. Booleans are hard because converting bool column with None replaces all Nones with false. Therefore only convert bool if there are no NA values. Datetimes should already be converted to np.datetime64 if supported, but here we also force conversion if required. N)r9)r8F)r—Úint64)r,rirIryrPrDrBÚ _get_dtyper=rrrÚfloatržršÚcountr>r<ÚboolÚKeyError)r‚r+Zsql_colrErFrGÚcol_typer8rrrr²Ès2     zSQLTable._harmonize_columnsc Cs^|jpi}|j|kr |j|jStj|dd�}ddlm}m}m}m}m }m } m } m } m } |dksj|dkr¸y|jjdk r‚|dd�SWn.tk r²t|ddƒdk r®|dd�SYnX|S|d krÔtjd td d �|S|d k�rþ|jdkrò| dd�S| dd�Sn\|dk�r|jdk�r| S|Sn<|dk�r,|S|dk�r:|S|dk�rH| S|dk�rZtdƒ‚| S)NT)Úskipnar) Ú TIMESTAMPÚ BigIntegerÚBooleanÚDateÚDateTimeÚFloatÚIntegerÚTextÚTimeÚ datetime64r)ÚtimezoneÚtzÚ timedelta64zlthe 'timedelta' type is not supported, and will be written as integer values (ns frequency) to the database.é)Ú stacklevelr?Zfloat32é)Z precisioné5r@Zint32ÚbooleanrrÚcomplexzComplex datatypes not supported)r<ryÚlibÚ infer_dtypeÚsqlalchemy.typesrÐrÑrÒrÓrÔrÕrÖr×rØÚdtrÛÚAttributeErrorÚgetattrÚwarningsÚwarnÚ UserWarningre) r‚rAr<rÎrÐrÑrÒrÓrÔrÕrÖr×rØrrrrÇûsH   ,            zSQLTable._sqlalchemy_typecCsˆddlm}m}m}m}m}m}t||ƒr.tSt||ƒrBt   d¡St||ƒrZ|j sVt St St||ƒrht St||ƒrvtSt||ƒr„tStS)Nr)rÐrÒrÓrÔrÕrÖrÈ)rårÐrÒrÓrÔrÕrÖrrÊr>r<rÚrrrrÌrŸ)r‚ZsqltyperÐrÒrÓrÔrÕrÖrrrrÉ:s         zSQLTable._get_dtype)NTrpr|NNNN)NN)TN)TNNN)N)rrrÚ__doc__rƒr„rˆrŠr‰r“r”r¨r�r´r¼rrÁr€r²rÇrÉrrrrr{˜s2  $ %  %$ 3?r{c@s eZdZdZdd„Zdd„ZdS)Ú PandasSQLz7 Subclasses Should define read_sql and to_sql. cOs tdƒ‚dS)NzMPandasSQL must be created with an SQLAlchemy connectable or sqlite connection)re)r‚r(ÚkwargsrrrrlVszPandasSQL.read_sqlcOs tdƒ‚dS)NzMPandasSQL must be created with an SQLAlchemy connectable or sqlite connection)re)r‚r(rîrrrrx\szPandasSQL.to_sqlN)rrrrìrlrxrrrrríQsríc@s°eZdZdZddd„Zedd„ƒZdd„Zdd d „Ze d d d „ƒZ d!dd„Z e Z d"dd„Z edd„ƒZd#dd„Zd$dd„Zd%dd„Zd&eeeeeeeeedœdd„ZdS)'rfaÖ This class enables conversion between DataFrame and SQL databases using SQLAlchemy to handle DataBase abstraction. Parameters ---------- engine : SQLAlchemy connectable Connectable to connect with the database. Using SQLAlchemy makes it possible to use any DB supported by that library. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If None, use default schema (default). meta : SQLAlchemy MetaData object, default None If provided, this MetaData object is used instead of a newly created. This allows to specify database flavor specific arguments in the MetaData object. NcCs.||_|s$ddlm}||j|d�}||_dS)Nr)r])rZ)r‡rbr]r_)r‚r rZr_r]rrrrƒws  zSQLDatabase.__init__c cs4|j ¡� }t|dƒr|Vn|jVWdQRXdS)NrT)r‡Úbeginr$)r‚Ztxrrrr­€s  zSQLDatabase.run_transactioncOs|j ¡j||ŽS)z,Simple passthrough to SQLAlchemy connectable)r‡Zexecution_optionsrT)r‚r(rîrrrrTˆszSQLDatabase.executeTc Cs"t||||d�}|j||||d�S)a¤ Read SQL database table into a DataFrame. Parameters ---------- table_name : string Name of SQL table in database. index_col : string, optional, default: None Column to set as index. coerce_float : boolean, default True Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. This can result in loss of precision. parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg}``, where the arg corresponds to the keyword arguments of :func:`pandas.to_datetime`. Especially useful with databases without native Datetime support, such as SQLite. columns : list, default: None List of column names to select from SQL table. schema : string, default None Name of SQL schema in database to query (if database flavor supports this). If specified, this overwrites the default schema of the SQL database object. chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. Returns ------- DataFrame See Also -------- pandas.read_sql_table SQLDatabase.read_query )rurZ)rJr+rIrW)r{r¼) r‚rYrOrJr+rIrZrWrirrrrgŒs 4zSQLDatabase.read_tableccs0x*| |¡}|sPqt|||||d�VqWdS)z+Return generator through chunked result set)rOrJr+N)r±rQ)r³rWrIrOrJr+rNrrrr´Ès zSQLDatabase._query_iteratorc Cs\t||ƒ}|j|Ž}| ¡} |dk r:|j||| |||d�S| ¡} t| | |||d�} | SdS)a$ Read SQL query into a DataFrame. Parameters ---------- sql : string SQL query to be executed. index_col : string, optional, default: None Column name to use as index for the returned DataFrame object. coerce_float : boolean, default True Attempt to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets. params : list, tuple or dict, optional, default: None List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'} parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. Returns ------- DataFrame See Also -------- read_sql_table : Read SQL database table into a DataFrame. read_sql N)rOrJr+)r)rTr#r´r¹rQ) r‚r&rOrJr+r'rWr(r³rIrNrPrrrrkÚs&2  zSQLDatabase.read_queryrpc  shˆrtˆƒs‡fdd„|Dƒ‰ˆdk rjddlm} m} x2ˆ ¡D]&\} } t| | ƒ| ƒs@td| ›d�ƒ‚q@Wt|||||||ˆd�}| ¡dd l m }y|j || d �WnN|j k rö}z.d }t |jƒ}t ||¡râtd ƒ|‚n|‚Wdd}~XYnX| ¡�sd| ¡�sd|jj}|j ¡�}|j|�p0|jj|d �}WdQRX||k�rdd|›d�}t |t¡dS)aÎ Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame name : string Name of SQL table. if_exists : {'fail', 'replace', 'append'}, default 'fail' - fail: If table exists, do nothing. - replace: If table exists, drop it, recreate it, and insert data. - append: If table exists, insert data. Create if does not exist. index : boolean, default True Write DataFrame index as a column. 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. A sequence should be given if the DataFrame uses MultiIndex. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If specified, this overwrites the default schema of the SQLDatabase object. chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. dtype : single type or dict of column name to SQL type, default None Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type. If all columns are of the same type, one single value can be used. method : {None', 'multi', callable}, default None 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 `. .. versionadded:: 0.24.0 csi|] }ˆ|“qSrr)r�rE)r<rrú ]sz&SQLDatabase.to_sql..Nr)Ú TypeEngineÚ to_instancez The type of z is not a SQLAlchemy type)rPrurtrvrZr<)rd)rwz.(1054, "Unknown column 'inf' in 'field list'")zinf cannot be used with MySQL)rZÚ connectionzThe provided table name 'z—' is not found exactly as such in the database after writing the table, possibly due to case sensitivity issues. Consider using lower case table names.)r rårñròrCrrer{r‰rrdr�ZSQLAlchemyErrorrzÚorigÚreÚsearchÚisdigitÚislowerr‡r ÚconnectÚ table_namesr_rZrérêrë)r‚rPryrtrurvrZrWr<rwrñròrAÚmy_typerirdrhÚmsgZerr_textr r‘rúr)r<rrx'sD5        zSQLDatabase.to_sqlcCs|jjS)N)r_Útables)r‚rrrrý�szSQLDatabase.tablescCs|j |jjj||p|jj¡S)N)r‡Z run_callableÚdialectrnr_rZ)r‚ryrZrrrrn”szSQLDatabase.has_tablecCsl|p |jj}|r*|jj d ||g¡¡}n|jj |¡}ddlm}x"|jD]}t|j |ƒrLd|j _ qLW|S)NÚ.r)ÚNumericF) r_rZrýÚgetÚjoinrrrIrr=Z asdecimal)r‚rYrZZtblrÚcolumnrrrr�™s     zSQLDatabase.get_tablecCsH|p |jj}| ||¡rD|jj|g|d�| ||¡ ¡|j ¡dS)N)r^rZ)r_rZrnrcr�ZdropÚclear)r‚rYrZrrrr‹©s   zSQLDatabase.drop_table)rPrYr#r<rZc Cs"t|||d|||d�}t| ¡ƒS)NF)rPrur#r<rZ)r{rzrˆ)r‚rPrYr#r<rZrirrrÚ_create_sql_schema°szSQLDatabase._create_sql_schema)NN)NTNNNN)NTN)NTNNN)rpTNNNNN)N)N)N)NNN)rrrrìrƒrr­rTrgÚ staticmethodr´rkrlrxÚpropertyrýrnr�r‹rrzr rr:rrrrrrfcs@  4  D _    rfZTEXTZREALZINTEGERrÐZDATEZTIME)Ústringr?r@rrrrác CsTyt|ƒ dd¡ d¡}Wn4tk rN}ztd|›d�ƒ|‚Wdd}~XYnX|S)Nzutf-8Ústrictz%Cannot convert identifier to UTF-8: 'rs)rzÚencodeÚdecodeÚ UnicodeErrorre)ryÚunamerhrrrÚ_get_unicode_nameÒs $rcCsFt|ƒ}t|ƒstdƒ‚| d¡}|dkr2tdƒ‚d| dd¡dS)Nz$Empty table or column name specifiedúrz%SQLite identifier cannot contain NULsú"z"")rršreÚfindrq)ryr Z nul_indexrrrÚ_get_valid_sqlite_nameÚs rzvThe spaces in these column names will not be changed. In pandas versions < 0.14, spaces were converted to underscores.csXeZdZdZ‡fdd„Zdd„Zdd„Zdd „Zd d „Zd d „Z dd„Z dd„Z ‡Z S)Ú SQLiteTablezw Patch the SQLTable for fallback support. Instead of a table variable just use the Create Table statement. cs*ddl}| tdd„¡tƒj||ŽdS)NrcSs | d¡S)Nz %H:%M:%S.%f)Ústrftime)r¥rrrÚÿóz&SQLiteTable.__init__..)Úsqlite3Zregister_adapterrÚsuperrƒ)r‚r(rîr)Ú __class__rrrƒøszSQLiteTable.__init__cCstd |j¡ƒS)Nz; )rzrri)r‚rrrrˆszSQLiteTable.sql_schemac Cs4|j ¡� }x|jD]}| |¡qWWdQRXdS)N)r}r­rirT)r‚r‘ZstmtrrrrŠs  zSQLiteTable._execute_createc s¶ttt|jjƒƒ}d}t‰|jdk rJx$|jddd…D]}| d|¡q6W‡fdd„|Dƒ}d |¡}d |gt |ƒ¡‰d ‡fdd„t |ƒDƒ¡}d ˆ|j ƒ›d |›d |›�}|S) Nú?r¸rcsg|] }ˆ|ƒ‘qSrr)r�r)Úescaperrr�sz0SQLiteTable.insert_statement..ú,c3s|]}dˆ›d�VqdS)ú(ú)Nr)r�r¥)Ú row_wildcardsrrú sz/SQLiteTable.insert_statement..z INSERT INTO z (z ) VALUES ) r%r™rzrPrIrrur�rršr®ry) r‚Únum_rowsr˜Úwldr»Zbracketed_namesZ col_namesÚ wildcardsÚinsert_statementr)rrrr$ s  zSQLiteTable.insert_statementcCs t|ƒ}| |jdd�|¡dS)Nr\)r!)r%Z executemanyr$)r‚r‘r#r’r£rrrr“szSQLiteTable._execute_insertcCs2t|ƒ}dd„|Dƒ}| |jt|ƒd�|¡dS)NcSsg|]}|D]}|‘q qSrr)r�rŽÚxrrrr�#sz5SQLiteTable._execute_insert_multi..)r!)r%rTr$rš)r‚r‘r#r’r£Zflattened_datarrrr”!sz!SQLiteTable._execute_insert_multic sl| |j¡}t d¡}dd„|Dƒ}tt|j|ƒƒrBtjt dd�t ‰‡fdd„|Dƒ}|j dk r¸t |j ƒr¸t |j ƒs€|j g}n|j }d ‡fd d „|Dƒ¡}| d |j›d |›d �¡|jrÊ|jd}nd}d|ˆ|jƒdd |¡dg}dd„|Dƒ} t | ƒ�rhd | ¡} d ‡fdd „| Dƒ¡}| dˆd|jd| ƒdˆ|jƒd|d ¡|S)zá Return a list of SQL statements that creates a table reflecting the structure of a DataFrame. The first entry will be a CREATE TABLE statement while the rest will be CREATE INDEX statements. z\s+cSsg|]\}}}|‘qSrr)r�rEr¥rrrr�/sz3SQLiteTable._create_table_setup..é)rÞcs"g|]\}}}ˆ|ƒd|‘qS)ú r)r�ÚcnameÚctyper¥)rrrr�6sNz, c3s|]}ˆ|ƒVqdS)Nr)r�r¶)rrrr >sz2SQLiteTable._create_table_setup..z CONSTRAINT z_pk PRIMARY KEY (rrÿÚz CREATE TABLE z ( z, z )cSsg|]\}}}|r|‘qSrr)r�r(r¥rÆrrrr�Osr¥rc3s|]}ˆ|ƒVqdS)Nr)r�r¶)rrrr Rsz CREATE INDEX Zix_zON z ()rÁÚ_sql_type_namerõr†Úanyr™rörérêÚ_SAFE_NAMES_WARNINGrr#ršrrrrryrZ) r‚rÀÚpatr¢Zcreate_tbl_stmtsr#Z cnames_brZ schema_nameZ create_stmtsZix_colsZcnamesr)rrr€&s2     &  6zSQLiteTable._create_table_setupcCsŠ|jpi}|j|kr||jStj|dd�}|dkrJtjdtdd�d}n,|dkrXd }n|d krfd }n|d krvtd ƒ‚|tkr‚d }t|S)NT)rÏrÜzlthe 'timedelta' type is not supported, and will be written as integer values (ns frequency) to the database.rÝ)rÞr@rÙrÚemptyrrâzComplex datatypes not supported) r<ryrãrärérêrëreÚ _SQL_TYPES)r‚rAr<rÎrrrr+_s&   zSQLiteTable._sql_type_name) rrrrìrƒrˆrŠr$r“r”r€r+Ú __classcell__rr)rrròs 9rc@s€eZdZdZddd„Zedd„ƒZdd„Zedd d „ƒZ dd d„Z dd„Z ddd„Z d dd„Z d!dd„Zd"dd„Zd#dd„Zd S)$rmzÉ Version of SQLDatabase to support SQLite connections (fallback without SQLAlchemy). This should only be used internally. Parameters ---------- con : sqlite connection object FcCs||_||_dS)N)rRr!)r‚r!rRrrrrƒ‹szSQLiteDatabase.__init__ccsT|j ¡}z:y|V|j ¡Wn tk r@|j ¡‚YnXWd| ¡XdS)N)r!ÚcursorÚcommitroÚrollbackÚclose)r‚rUrrrr­�s   zSQLiteDatabase.run_transactionc OsÀ|jr|j}n |j ¡}y|j||Ž|Stk rº}zty|j ¡WnBtk rŠ}z$td|d›d|›d�ƒ}||‚Wdd}~XYnXtd|d›d|›�ƒ}||‚Wdd}~XYnXdS)NzExecution failed on sql: rÚ z unable to rollbackzExecution failed on sql 'z': )rRr!r2rTror4r)r‚r(rîrUrdZ inner_excÚexrrrrT›s  zSQLiteDatabase.executeNTccsLxF| |¡}t|ƒtkr t|ƒ}|s0| ¡Pqt|||||d�VqWdS)z+Return generator through chunked result set)rOrJr+N)r±r=Útupler%r5rQ)r2rWrIrOrJr+rNrrrr´¯s  zSQLiteDatabase._query_iteratorc Csnt||ƒ}|j|Ž}dd„|jDƒ} |dk rB|j||| |||d�S| |¡} | ¡t| | |||d�} | SdS)NcSsg|] }|d‘qS)rr)r�Zcol_descrrrr�Ðsz-SQLiteDatabase.read_query..)rOrJr+)r)rTÚ descriptionr´Ú_fetchall_as_listr5rQ) r‚r&rOrJr'r+rWr(r2rIrNrPrrrrkÄs(   zSQLiteDatabase.read_querycCs| ¡}t|tƒst|ƒ}|S)N)r¹rr%)r‚rUr³rrrr:ès z SQLiteDatabase._fetchall_as_listrpc sˆˆrtˆƒs‡fdd„|Dƒ‰ˆdk rZx2ˆ ¡D]&\} } t| tƒs0t| ›d| ›d�ƒ‚q0Wt||||||ˆd�} |  ¡|  || ¡dS)ai Write records stored in a DataFrame to a SQL database. Parameters ---------- frame: DataFrame name: string Name of SQL table. if_exists: {'fail', 'replace', 'append'}, default 'fail' fail: If table exists, do nothing. replace: If table exists, drop it, recreate it, and insert data. append: If table exists, insert data. Create if it does not exist. index : boolean, default True Write DataFrame index as a column 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. A sequence should be given if the DataFrame uses MultiIndex. schema : string, default None Ignored parameter included for compatibility with SQLAlchemy version of ``to_sql``. chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. dtype : single type or dict of column name to SQL type, default None Optional specifying the datatype for columns. The SQL type should be a string. If all columns are of the same type, one single value can be used. method : {None, 'multi', callable}, default None 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 `. .. versionadded:: 0.24.0 csi|] }ˆ|“qSrr)r�rE)r<rrrð#sz)SQLiteDatabase.to_sql..Nz (z) not a string)rPrurtrvr<)r rCrrzrerr‰r�) r‚rPryrtrurvrZrWr<rwrArûrir)r<rrxîs 4  zSQLiteDatabase.to_sqlcCs*d}d|›d�}t| ||g¡ ¡ƒdkS)Nrz;SELECT name FROM sqlite_master WHERE type='table' AND name=ú;r)ršrTr¹)r‚ryrZr"Úqueryrrrrn6s zSQLiteDatabase.has_tablecCsdS)Nr)r‚rYrZrrrr�@szSQLiteDatabase.get_tablecCsdt|ƒ›�}| |¡dS)Nz DROP TABLE )rrT)r‚ryrZZdrop_sqlrrrr‹CszSQLiteDatabase.drop_tablec Cs"t|||d|||d�}t| ¡ƒS)NF)rPrur#r<rZ)rrzrˆ)r‚rPrYr#r<rZrirrrrGsz!SQLiteDatabase._create_sql_schema)F)NTN)NTNNN)rpTNNNNN)N)N)N)NNN)rrrrìrƒrr­rTrr´rkr:rxrnr�r‹rrrrrrm€s.       >  rmcCst|d�}|j|||||d�S)a2 Get the SQL db table schema for the given frame. Parameters ---------- frame : DataFrame name : string name of SQL table keys : string or sequence, default: None columns to use a primary key con: an open SQL database connection object or a SQLAlchemy connectable Using SQLAlchemy makes it possible to use any DB supported by that library, default: None If a DBAPI2 object, only sqlite3 is supported. dtype : dict of column name to SQL type, default None Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type, or a string for sqlite3 fallback connection. schema: str, default: None Optional specifying the schema to be used in creating the table. .. versionadded:: 1.2.0 )r!)r#r<rZ)rSr)rPryr#r!r<rZrVrrrÚ get_schemaTs r=)NN)NTN)NN)NNTNNN)NNTNNr\)NNTNNN)NTNNN)NTNNr\)NTNNN)NTNNNN)NTNNNr\)NTNNNN)NrpTNNNN)N)NNF)NNNN)CrìÚ contextlibrrrrÚ functoolsrrõÚtypingrrr r r réZnumpyr>Zpandas._libs.libZ_libsrãZpandas.core.dtypes.commonr r rZpandas.core.dtypes.dtypesrZpandas.core.dtypes.missingrZpandas.core.apirrZpandas.core.baserZpandas.core.tools.datetimesrrrÚIOErrorrrr"r)r,rBrHrQrTr[r¬rjrlrxrnZ table_existsr`rSr{rírfr0rrr-rrmr=rrrrÚsú         V@dH  <gU