/usr/local/lib64/python3.6/site-packages/pandas/io/__pycache__
NameSizeModeActions
api.cpython-36.pyc10960644editdlrm
clipboards.cpython-36.pyc33920644editdlrm
common.cpython-36.pyc140640644editdlrm
date_converters.cpython-36.pyc19470644editdlrm
feather_format.cpython-36.pyc29360644editdlrm
gbq.cpython-36.pyc74590644editdlrm
html.cpython-36.pyc319770644editdlrm
orc.cpython-36.pyc18020644editdlrm
parquet.cpython-36.pyc95000644editdlrm
parsers.cpython-36.pyc882000644editdlrm
pickle.cpython-36.pyc56790644editdlrm
pytables.cpython-36.pyc1308050644editdlrm
spss.cpython-36.pyc13280644editdlrm
sql.cpython-36.pyc522830644editdlrm
stata.cpython-36.pyc975630644editdlrm
__init__.cpython-36.pyc1450644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/pandas/io/__pycache__/sql.cpython-36.pyc (52283B)
3 :%Eg@sdZddlmZddlmZmZmZddlmZddlZddl m Z m Z m Z m Z ddlZddlZddljjZddlmZmZmZddlmZdd lmZdd lmZmZdd lm Z dd l!m"Z"Gd dde#Z$Gddde%Z&da'ddZ(ddZ)ddZ*dQddZ+ddZ,dRddZ-dSddZ.e dTded d!d"Z/e dUe0e ed d$d"Z/dVe e0e ee efd d%d"Z/e dWded d&d'Z1e dXe0e ed d(d'Z1dYe e0e ee efd d)d'Z1e dZded d*d+Z2e d[e0e ed d,d+Z2d\e e0e ee efd d-d+Z2d]dd/d0d1Z3d^d2d3Z4e4Z5d4d5Z6d_d7d8Z7Gd9d:d:e Z8Gd;d<dd>e9Z:d?d@dAdBdCdDdAdEZ;dFdGZGdKdLdLe8Z?GdMdNdNe9Z@d`dOdPZAdS)az| Collection of query wrappers / abstractions to both facilitate data retrieval and to reduce dependency on DB-specific API. )contextmanager)datedatetimetime)partialN)IteratorOptionalUnionoverload)is_datetime64tz_dtype is_dict_like is_list_like)DatetimeTZDtype)isna) DataFrameSeries) PandasObject) to_datetimec@s eZdZdS)SQLAlchemyRequiredN)__name__ __module__ __qualname__rr9/usr/local/lib64/python3.6/site-packages/pandas/io/sql.pyrsrc@s eZdZdS) DatabaseErrorN)rrrrrrrrsrc CsTtdkr2yddl}daWntk r0daYnXtrLddl}t||jjSdSdS)NrTF)_SQLALCHEMY_INSTALLED sqlalchemy ImportError isinstanceengineZ Connectable)conrrrr_is_sqlalchemy_connectable(s r!cCs6|g}|dk r2t|dr$||g7}n|t|g7}|S)z9Convert SQL and params args to DBAPI2.0 compliant format.Nkeys)hasattrlist)sqlparamsargsrrr_convert_params:s   r(cCs2|dks|dks|dkrg}nt|ds.|g}|S)z3Process parse_dates argument for read_sql functionsTNF__iter__)r#) parse_datesrrr_process_parse_dates_argumentEs  r+c Cst|trt|fddi|S|dkrJt|jjtjsFt|jjtjrJd}|dkrbt|d ||d St |jrxt|d dSt|d ||dSdS)NerrorsignoresDdhmmsusnsZcoerce)r,unitutcT)r7)r,formatr7)r/r0r1r2r.r3r4r5) rdictr issubclassdtypetypenpfloatingintegerr )colr7r8rrr_handle_date_columnPs   rAc Csjt|}x\|jD]P\}}t|js,||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)r8)r+itemsr r; TypeErrorrA)Z data_framer*col_namedf_colfmtrrr_parse_date_columnses  rGTcCs4tj|||d}t||}|dk r0|j|dd|S)z(Wrap result set of query in a DataFrame.)columns coerce_floatNT)inplace)r from_recordsrG set_index)datarH index_colrIr*framerrr _wrap_resultzs  rPcCs2|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'rrrrSs    rS) chunksizereturncCsdS)Nr) table_namer schemarNrIr*rHrVrrrread_sql_tables rZcCsdS)Nr)rXr rYrNrIr*rHrVrrrrZs cCst|}t|stdddl}ddlm} | ||d} y| j|gddWn8|jjk r} zt d|d | WYdd} ~ XnXt || 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 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)rYT)onlyZviewszTable z not found)meta)rNrIr*rHrV) _engine_builderr!NotImplementedErrorrsqlalchemy.schemar\reflectexcZInvalidRequestError ValueError SQLDatabase read_table)rXr rYrNrIr*rHrVrr\r^errrUtablerrrrZs,A  $ cCsdS)Nr)r%r rNrIr&r*rVrrrread_sql_query!s ricCsdS)Nr)r%r rNrIr&r*rVrrrri.s cCst|}|j||||||dS)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. )rNr&rIr*rV)rR read_query)r%r rNrIr&r*rVrUrrrri;s=cCsdS)Nr)r%r rNrIr&r*rHrVrrrread_sqls rkcCsdS)Nr)r%r rNrIr&r*rHrVrrrrks c Cst|}t|tr(|j||||||dSy|j|} Wntk rNd} YnX| rz|jj|gd|j||||||dS|j||||||dSdS)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. 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. )rNr&rIr*rVF)r])rNrIr*rHrVN) rRrSQLiteDatabaserj has_table Exceptionr^rbrf) r%r rNrIr&r*rHrVrUZ_is_table_namerrrrks:A  fail)rWc Csj|d krtd|dt||d} t|tr8|j}nt|tsJtd| j||||||||| d d S) 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 roreplaceappend'z' is not valid for if_exists)rYz9'frame' argument should be either a Series or a DataFrame) if_existsindex index_labelrYrVr;methodN)rorprq)rdrRrrZto_framerr`to_sql) rOnamer rYrsrtrurVr;rvrUrrrrws$:    rwcCst||d}|j|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 )rY)rRrm)rXr rYrUrrrrmZs rmc CsBt|tr>y ddl}Wntk r.daYnX|j|}|S|S)zw Returns a SQLAlchemy engine from a URI (if con is a string) else it just return con without modifying it. rNF)rstrrrrZ create_engine)r rrrrr_us    r_FcCsBt|}t|rt|||dSt|tr2tdn t||dSdS)zm Convenience function to return the correct PandasSQL subclass based on the provided parameters. )rYr^z.Using URI string without sqlalchemy installed.)rQN)r_r!rerryrrl)r rYr^rQrrrrRs   rRc@seZdZdZd(ddZdd Zd d Zd d ZddZddZ ddZ ddZ d)ddZ d*ddZ d+ddZddZddZd 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. NTropandasc Cs||_||_||_||_|j|||_||_||_| |_| |_ |dk rR|j |_ n|jj |j|j|_ |j dkrt d|ddS)NzCould not init table 'rr)rxpd_sqlprefixrO _index_namertrYrsr"r;_create_table_setuprh get_tablerd) selfrxZpandas_sql_enginerOrtrsr}rurYr"r;rrr__init__s   zSQLTable.__init__cCs|jj|j|jS)N)r|rmrxrY)rrrrexistsszSQLTable.existscCs$ddlm}t||jj|jjS)Nr) CreateTable)rarryrhcompiler| connectable)rrrrr sql_schemas zSQLTable.sql_schemacCs |jj|jj|_|jjdS)N)rhZ tometadatar|r^create)rrrr_execute_createszSQLTable._execute_createcCsx|jrl|jdkr&td|jdqt|jdkrL|jj|j|j|jqt|jdkrXqttd|jdn|jdS)NrozTable 'z' already exists.rprqrrz' is not valid for if_exists)rrsrdrxr| drop_tablerYr)rrrrrs    zSQLTable.createcs(fdd|D}|j|jj|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)r9zip).0row)r"rr sz,SQLTable._execute_insert..N)rSrhinsert)rconnr" data_iterrMr)r"r_execute_inserts zSQLTable._execute_insertcs(fdd|D}|j|jj|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)r9r)rr)r"rrrsz2SQLTable._execute_insert_multi..N)rSrhr)rrr"rrMr)r"r_execute_insert_multiszSQLTable._execute_insert_multic Cs0|jdk rd|jj}|j|j_y|jddWqjtk r`}ztd||WYdd}~XqjXn|j}ttt|j }t |}dg|}xt |j D]\}\}}|j } | jjdkr| j} n(| jjdkr| jdjt} n | jt} t| tjstt| |jrt| } d| | <| ||<qW||fS)NT)rJz!duplicate name in index/columns: Mr2i8)rtrOcopynamesZ reset_indexrdr$mapryrHlen enumeraterBZ_valuesr;kindZ to_pydatetimeviewastypeobjectrr=ZndarrayAssertionErrorr<Z _can_hold_nar) rtemprg column_namesZncols data_listi_Zservalsr0maskrrr insert_datas0   $      zSQLTable.insert_datac s|dkr|j}n2|dkr |j}n"t|r4t||}ntd||j\}}t|j}|dkrddS|dkrr|}n|dkrtdt||d}|j j `}xXt |D]L} | |t | d||krPt fdd|D} |||| qWWdQRXdS)NZmultizInvalid parameter `method`: rz%chunksize argument should be non-zeror[csg|]}|qSrr)rZarr)end_istart_irrr=sz#SQLTable.insert..)rrcallablerrdrrrOintr|run_transactionrangeminr) rrVrvZ exec_insertr"rZnrowschunksrrZ chunk_iterr)rrrrs0    zSQLTable.insertccs^xX|j|}|sPqtj|||d|_|j|d|jdk rN|jj|jdd|jVqWdS)z,Return generator through chunked result set.)rHrI)r*NT)rJ) fetchmanyrrKrO_harmonize_columnsrtrL)rresultrVrHrIr*rMrrr_query_iterator@s   zSQLTable._query_iteratorc s|dk rtt|dkrtddlm}fdd|D}jdk rjx,jddd D]}|jdjj|qNW||}n jj}jj|} | j } |dk rj | || ||dS| j } t j | | |d_j|djdk rjjjd d jSdS) Nr)selectcsg|]}jj|qSr)rhc)rn)rrrrYsz!SQLTable.read..r[)rIr*)rHrI)r*T)rJ)rrrrtrrhrr|rSr"rfetchallrrKrOrrL) rrIr*rHrVrcolsidxZ sql_selectrrrMr)rrreadTs0       z SQLTable.readcCs|dkr|jjj}|dk rJt|ts*|g}t||krFtd|n|S|dkrrd|jjkrr|jjjdkrrdgSddt |jjj DSn"t|t r|gSt|tr|SdSdS)NTz@Length of 'index_label' should match number of levels, which is r[rtcSs&g|]\}}|dk r|nd|qS)NZlevel_r)rrlrrrrsz(SQLTable._index_name..) rOrtnlevelsrr$rrdrHrxrrry)rrtrurrrrr~ys(      zSQLTable._index_namecstg}jdk rLx.) rtrrOZ_get_level_valuesrqryrrrH)rrcolumn_names_and_typesrZ idx_labelZidx_typer)rrr_get_column_names_and_typess  z$SQLTable._get_column_names_and_typesc sddlmm}m}|j|j}fdd|D}|jdk rtt|jsP|jg}n|j}||d|jdi}|j ||j p|j j j }ddl m}||j |d} ||j| f|d |iS) Nr)ColumnPrimaryKeyConstraintTablecs g|]\}}}|||dqS))rtr)rrxtypis_index)rrrrsz0SQLTable._create_table_setup..rxZ_pk)r\)rYrY)rrrrr_sqlalchemy_typer"r rxrqrYr|r^rar\) rrrrrHr"ZpkcrYr\r^r)rrrs       zSQLTable._create_table_setupcCs,t|}x|jjD]}|j}y|j|}||krny ||}Wntk rXd}YnXt||d|j|<w|j|j}|t ks|t ks|t kr|t k}t||d|j|<n\|t kr|j |dd|j|<n>t||jkr |tjdks|tkr |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)r8)r7F)rint64)r+rhrHrxrOrCrA _get_dtyper<rrrfloatrrcountr=r;boolKeyError)rr*Zsql_colrDrErFcol_typer7rrrrs2     zSQLTable._harmonize_columnsc Cs^|jpi}|j|kr |j|jStj|dd}ddlm}m}m}m}m }m } m } m } m } |dksj|dkry|jjdk r|ddSWn.tk rt|dddk r|ddSYnX|S|d krtjd td d |S|d kr|jdkr| ddS| ddSn\|dkr|jdkr| S|Sn<|dkr,|S|dkr:|S|dkrH| S|dkrZtd| S)NT)skipnar) TIMESTAMP BigIntegerBooleanDateDateTimeFloatIntegerTextTime datetime64r)timezonetz timedelta64zlthe 'timedelta' type is not supported, and will be written as integer values (ns frequency) to the database.) stacklevelr>Zfloat32)Z precision5r?Zint32booleanrrcomplexzComplex datatypes not supported)r;rxlib infer_dtypesqlalchemy.typesrrrrrrrrrdtrAttributeErrorgetattrwarningswarn UserWarningrd) rr@r;rrrrrrrrrrrrrrsH   ,            zSQLTable._sqlalchemy_typecCsddlm}m}m}m}m}m}t||r.tSt||rBt j dSt||rZ|j sVt St St||rht St||rvtSt||rtStS)Nr)rrrrrrr)rrrrrrrrrr=r;rrrrrr)rZsqltyperrrrrrrrrr9s         zSQLTable._get_dtype)NTror{NNNN)NN)TN)TNNN)N)rrr__doc__rrrrrrrrrrrr~rrrrrrrrrrzs2  $ %  %$ 3?rzc@s eZdZdZddZddZdS) PandasSQLz7 Subclasses Should define read_sql and to_sql. cOs tddS)NzMPandasSQL must be created with an SQLAlchemy connectable or sqlite connection)rd)rr'kwargsrrrrkUszPandasSQL.read_sqlcOs tddS)NzMPandasSQL must be created with an SQLAlchemy connectable or sqlite connection)rd)rr'rrrrrw[szPandasSQL.to_sqlN)rrrrrkrwrrrrrPsrc@seZdZdZdddZeddZddZdd d Ze dd d Z d ddZ e Z d!ddZ eddZd"ddZd#ddZd$ddZd%ddZdS)&rea 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\)rY)rrar\r^)rrrYr^r\rrrrvs  zSQLDatabase.__init__c cs4|jj }t|dr|Vn|jVWdQRXdS)NrS)rbeginr#)rZtxrrrrs  zSQLDatabase.run_transactioncOs|jjddj||S)z,Simple passthrough to SQLAlchemy connectableT)Z no_parameters)rZexecution_optionsrS)rr'rrrrrSszSQLDatabase.executeTc Cs"t||||d}|j||||dS)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 )rtrY)rIr*rHrV)rzr) rrXrNrIr*rHrYrVrhrrrrfs 4zSQLDatabase.read_tableccs0x*|j|}|sPqt|||||dVqWdS)z+Return generator through chunked result set)rNrIr*N)rrP)rrVrHrNrIr*rMrrrrs zSQLDatabase._query_iteratorc Cs\t||}|j|}|j} |dk r:|j||| |||dS|j} 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)rNrIr*)r(rSr"rrrP) rr%rNrIr*r&rVr'rrHrMrOrrrrjs&2  zSQLDatabase.read_queryroc snr t r fdd|Ddk rlddlm} m} x2jD]&\} } t| | | sBtd| dqBWt|||||||d}|jdd l m }y|j || d WnN|j k r}z0d }t |j}tj||rtd |n|WYdd}~XnX|j rj|j rj|jj}|jj}|j|p6|jj|d }WdQRX||krjd|d}tj|tdS)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)rrD)r;rr ^sz&SQLDatabase.to_sql..Nr) TypeEngine to_instancez The type of z is not a SQLAlchemy type)rOrtrsrurYr;)rc)rvz.(1054, "Unknown column 'inf' in 'field list'")zinf cannot be used with MySQL)rY 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 rrrrBrrdrzrrrcrZSQLAlchemyErrorryorigresearchisdigitislowerrrconnect table_namesr^rYrrr)rrOrxrsrtrurYrVr;rvrrr@my_typerhrcrgmsgZerr_textrrrr)r;rrw(sD5       zSQLDatabase.to_sqlcCs|jjS)N)r^tables)rrrrrszSQLDatabase.tablescCs|jj|jjj||p|jjS)N)rZ run_callabledialectrmr^rY)rrxrYrrrrmszSQLDatabase.has_tablecCsl|p |jj}|r*|jjjdj||g}n|jjj|}ddlm}x"|jD]}t|j |rLd|j _ qLW|S)N.r)NumericF) r^rYrgetjoinrrrHrr<Z asdecimal)rrXrYZtblrcolumnrrrrs     zSQLDatabase.get_tablecCsH|p |jj}|j||rD|jj|g|d|j||j|jjdS)N)r]rY)r^rYrmrbrZdropclear)rrXrYrrrrs   zSQLDatabase.drop_tablecCs t|||d||d}t|jS)NF)rOrtr"r;)rzryr)rrOrXr"r;rhrrr_create_sql_schemaszSQLDatabase._create_sql_schema)NN)NTNNNN)NTN)NTNNN)roTNNNNN)N)N)N)NN)rrrrrrrrSrf staticmethodrrjrkrwpropertyrrmrrrrrrrrebs<   4  D _    reZTEXTZREALZINTEGERrZDATEZTIME)stringr>r?rrrrcCsTyt|jddjd}Wn4tk rN}ztd|d|WYdd}~XnX|S)Nzutf-8strictz%Cannot convert identifier to UTF-8: 'rr)ryencodedecode UnicodeErrorrd)rxunamergrrr_get_unicode_names $r cCsFt|}t|std|jd}|dkr2tdd|jdddS)Nz$Empty table or column name specifiedrz%SQLite identifier cannot contain NULs"z"")r rrdfindrp)rxr Z nul_indexrrr_get_valid_sqlite_names rzvThe spaces in these column names will not be changed. In pandas versions < 0.14, spaces were converted to underscores.csXeZdZdZfddZddZddZdd Zd d Zd d Z ddZ ddZ Z S) SQLiteTablezw Patch the SQLTable for fallback support. Instead of a table variable just use the Create Table statement. cs*ddl}|jtddtj||dS)NrcSs |jdS)Nz %H:%M:%S.%f)strftime)rrrrsz&SQLiteTable.__init__..)sqlite3Zregister_adapterrsuperr)rr'rr) __class__rrrszSQLiteTable.__init__cCstdj|jS)Nz; )ryrrh)rrrrrszSQLiteTable.sql_schemac Cs4|jj }x|jD]}|j|qWWdQRXdS)N)r|rrhrS)rrstmtrrrrs  zSQLiteTable._execute_createc sttt|jj}d}t|jdk rJx$|jddd D]}|jd|q6Wfdd|D}dj|}dj|gt |djfddt |D}d |j d |d |}|S) N?r[rcsg|] }|qSrr)rr)escaperrrsz0SQLiteTable.insert_statement..,c3s|]}ddVqdS)()Nr)rr) row_wildcardsrr sz/SQLiteTable.insert_statement..z INSERT INTO z (z ) VALUES r) r$rryrOrHrrtrrrrrx) rnum_rowsrwldrZbracketed_namesZ col_names wildcardsinsert_statementr)rrrr#s  zSQLiteTable.insert_statementcCs t|}|j|jdd|dS)Nr[)r )r$Z executemanyr#)rrr"rrrrrrszSQLiteTable._execute_insertcCs2t|}dd|D}|j|jt|d|dS)NcSsg|]}|D]}|q qSrr)rrxrrrrsz5SQLiteTable._execute_insert_multi..)r )r$rSr#r)rrr"rrZflattened_datarrrrsz!SQLiteTable._execute_insert_multic sR|j|j}tjd}dd|D}tt|j|rBtjt ddt fdd|D}|j dk rt |j rt |j s|j g}n|j }djfd d |D}|jd |jd |d d|jddj|dg}dd|D}t |rNdj|} djfdd |D}|jdd|jd| d|jd|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)rrDrrrrr#sz3SQLiteTable._create_table_setup..)rcs"g|]\}}}|d|qS) r)rcnamectyper)rrrr*sNz, c3s|]}|VqdS)Nr)rr)rrrr2sz2SQLiteTable._create_table_setup..z CONSTRAINT z_pk PRIMARY KEY (rz CREATE TABLE z ( z, z )cSsg|]\}}}|r|qSrr)rr'rrrrrr?srrc3s|]}|VqdS)Nr)rr)rrrrBsz CREATE INDEX Zix_zON z ()r_sql_type_namerranyrrrr_SAFE_NAMES_WARNINGrr"rr rrqrx) rrpatrZcreate_tbl_stmtsr"Z cnames_brZ create_stmtsZix_colsZcnamesr)rrrs,    "  6zSQLiteTable._create_table_setupcCs|jpi}|j|kr||jStj|dd}|dkrJtjdtddd}n,|dkrXd }n|d krfd }n|d krvtd |tkrd }t|S)NT)rrzlthe 'timedelta' type is not supported, and will be written as integer values (ns frequency) to the database.r)rr?rremptyrrzComplex datatypes not supported) r;rxrrrrrrd _SQL_TYPES)rr@r;rrrrr)Os&   zSQLiteTable._sql_type_name) rrrrrrrr#rrrr) __classcell__rr)rrrs 5rc@seZdZdZdddZeddZddZedd d Z dd dZ ddZ dddZ d ddZ d!ddZd"ddZd#ddZd S)$rlz Version of SQLDatabase to support SQLite connections (fallback without SQLAlchemy). This should only be used internally. Parameters ---------- con : sqlite connection object FcCs||_||_dS)N)rQr )rr rQrrrr{szSQLiteDatabase.__init__ccsT|jj}z:y|V|jjWn tk r@|jjYnXWd|jXdS)N)r cursorcommitrnrollbackclose)rrTrrrrs   zSQLiteDatabase.run_transactioncOs|jr|j}n |jj}y|j|||Stk r}zvy|jjWnBtk r}z&td|dd|d}||WYdd}~XnXtd|dd|}||WYdd}~XnXdS)NzExecution failed on sql: r z unable to rollbackzExecution failed on sql 'z': )rQr r0rSrnr2r)rr'rrTrcZ inner_excexrrrrSs  zSQLiteDatabase.executeNTccsLxF|j|}t|tkr t|}|s0|jPqt|||||dVqWdS)z+Return generator through chunked result set)rNrIr*N)rr<tupler$r3rP)r0rVrHrNrIr*rMrrrrs  zSQLiteDatabase._query_iteratorc Csnt||}|j|}dd|jD} |dk rB|j||| |||dS|j|} |jt| | |||d} | SdS)NcSsg|] }|dqS)rr)rZcol_descrrrrsz-SQLiteDatabase.read_query..)rNrIr*)r(rS descriptionr_fetchall_as_listr3rP) rr%rNrIr&r*rVr'r0rHrMrOrrrrjs(   zSQLiteDatabase.read_querycCs|j}t|tst|}|S)N)rrr$)rrTrrrrr8s z SQLiteDatabase._fetchall_as_listroc sr t r fdd|Ddk r\x2jD]&\} } t| ts2t| d| dq2Wt||||||d} | j| j|| 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)rrD)r;rrrsz)SQLiteDatabase.to_sql..Nz (z) not a string)rOrtrsrur;)r rBrryrdrrr) rrOrxrsrtrurYrVr;rvr@rrhr)r;rrws 4 zSQLiteDatabase.to_sqlcCs*d}d|d}t|j||gjdkS)Nrz;SELECT name FROM sqlite_master WHERE type='table' AND name=;r)rrSr)rrxrYr!queryrrrrm&s zSQLiteDatabase.has_tablecCsdS)Nr)rrXrYrrrr0szSQLiteDatabase.get_tablecCsdt|}|j|dS)Nz DROP TABLE )rrS)rrxrYZdrop_sqlrrrr3szSQLiteDatabase.drop_tablecCs t|||d||d}t|jS)NF)rOrtr"r;)rryr)rrOrXr"r;rhrrrr7sz!SQLiteDatabase._create_sql_schema)F)NTN)NTNNN)roTNNNNN)N)N)N)NN)rrrrrrrrSrrrjr8rwrmrrrrrrrrlps.       >  rlcCst|d}|j||||dS)a 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. )r )r"r;)rRr)rOrxr"r r;rUrrr get_schema>s r;)NN)NTN)NN)NNTNNN)NNTNNr[)NNTNNN)NTNNN)NTNNr[)NTNNN)NTNNNN)NTNNNr[)NTNNNN)NroTNNNN)N)NNF)NNN)Br contextlibrrrr functoolsrrtypingrrr r rZnumpyr=Zpandas._libs.libZ_libsrZpandas.core.dtypes.commonr r r Zpandas.core.dtypes.dtypesrZpandas.core.dtypes.missingrZpandas.core.apirrZpandas.core.baserZpandas.core.tools.datetimesrrrIOErrorrrr!r(r+rArGrPrSrZrrirkrwrmZ table_existsr_rRrzrrer.r rr+rrlr;rrrrs          V@cH  <\ O