PageRenderTime 66ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/pandas/io/sql.py

http://github.com/wesm/pandas
Python | 1605 lines | 1290 code | 77 blank | 238 comment | 101 complexity | 369ee3096a0afbaa8a4e7af4c622ca33 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. # -*- coding: utf-8 -*-
  2. """
  3. Collection of query wrappers / abstractions to both facilitate data
  4. retrieval and to reduce dependency on DB-specific API.
  5. """
  6. from __future__ import division, print_function
  7. from contextlib import contextmanager
  8. from datetime import date, datetime, time
  9. from functools import partial
  10. import re
  11. import warnings
  12. import numpy as np
  13. import pandas._libs.lib as lib
  14. from pandas.compat import (
  15. map, raise_with_traceback, string_types, text_type, zip)
  16. from pandas.core.dtypes.common import (
  17. is_datetime64tz_dtype, is_dict_like, is_list_like)
  18. from pandas.core.dtypes.dtypes import DatetimeTZDtype
  19. from pandas.core.dtypes.missing import isna
  20. from pandas.core.api import DataFrame, Series
  21. from pandas.core.base import PandasObject
  22. from pandas.core.tools.datetimes import to_datetime
  23. class SQLAlchemyRequired(ImportError):
  24. pass
  25. class DatabaseError(IOError):
  26. pass
  27. # -----------------------------------------------------------------------------
  28. # -- Helper functions
  29. _SQLALCHEMY_INSTALLED = None
  30. def _is_sqlalchemy_connectable(con):
  31. global _SQLALCHEMY_INSTALLED
  32. if _SQLALCHEMY_INSTALLED is None:
  33. try:
  34. import sqlalchemy
  35. _SQLALCHEMY_INSTALLED = True
  36. from distutils.version import LooseVersion
  37. ver = sqlalchemy.__version__
  38. # For sqlalchemy versions < 0.8.2, the BIGINT type is recognized
  39. # for a sqlite engine, which results in a warning when trying to
  40. # read/write a DataFrame with int64 values. (GH7433)
  41. if LooseVersion(ver) < LooseVersion('0.8.2'):
  42. from sqlalchemy import BigInteger
  43. from sqlalchemy.ext.compiler import compiles
  44. @compiles(BigInteger, 'sqlite')
  45. def compile_big_int_sqlite(type_, compiler, **kw):
  46. return 'INTEGER'
  47. except ImportError:
  48. _SQLALCHEMY_INSTALLED = False
  49. if _SQLALCHEMY_INSTALLED:
  50. import sqlalchemy
  51. return isinstance(con, sqlalchemy.engine.Connectable)
  52. else:
  53. return False
  54. def _convert_params(sql, params):
  55. """Convert SQL and params args to DBAPI2.0 compliant format."""
  56. args = [sql]
  57. if params is not None:
  58. if hasattr(params, 'keys'): # test if params is a mapping
  59. args += [params]
  60. else:
  61. args += [list(params)]
  62. return args
  63. def _process_parse_dates_argument(parse_dates):
  64. """Process parse_dates argument for read_sql functions"""
  65. # handle non-list entries for parse_dates gracefully
  66. if parse_dates is True or parse_dates is None or parse_dates is False:
  67. parse_dates = []
  68. elif not hasattr(parse_dates, '__iter__'):
  69. parse_dates = [parse_dates]
  70. return parse_dates
  71. def _handle_date_column(col, utc=None, format=None):
  72. if isinstance(format, dict):
  73. return to_datetime(col, errors='ignore', **format)
  74. else:
  75. # Allow passing of formatting string for integers
  76. # GH17855
  77. if format is None and (issubclass(col.dtype.type, np.floating) or
  78. issubclass(col.dtype.type, np.integer)):
  79. format = 's'
  80. if format in ['D', 'd', 'h', 'm', 's', 'ms', 'us', 'ns']:
  81. return to_datetime(col, errors='coerce', unit=format, utc=utc)
  82. elif is_datetime64tz_dtype(col):
  83. # coerce to UTC timezone
  84. # GH11216
  85. return to_datetime(col, utc=True)
  86. else:
  87. return to_datetime(col, errors='coerce', format=format, utc=utc)
  88. def _parse_date_columns(data_frame, parse_dates):
  89. """
  90. Force non-datetime columns to be read as such.
  91. Supports both string formatted and integer timestamp columns.
  92. """
  93. parse_dates = _process_parse_dates_argument(parse_dates)
  94. # we want to coerce datetime64_tz dtypes for now to UTC
  95. # we could in theory do a 'nice' conversion from a FixedOffset tz
  96. # GH11216
  97. for col_name, df_col in data_frame.iteritems():
  98. if is_datetime64tz_dtype(df_col) or col_name in parse_dates:
  99. try:
  100. fmt = parse_dates[col_name]
  101. except TypeError:
  102. fmt = None
  103. data_frame[col_name] = _handle_date_column(df_col, format=fmt)
  104. return data_frame
  105. def _wrap_result(data, columns, index_col=None, coerce_float=True,
  106. parse_dates=None):
  107. """Wrap result set of query in a DataFrame."""
  108. frame = DataFrame.from_records(data, columns=columns,
  109. coerce_float=coerce_float)
  110. frame = _parse_date_columns(frame, parse_dates)
  111. if index_col is not None:
  112. frame.set_index(index_col, inplace=True)
  113. return frame
  114. def execute(sql, con, cur=None, params=None):
  115. """
  116. Execute the given SQL query using the provided connection object.
  117. Parameters
  118. ----------
  119. sql : string
  120. SQL query to be executed.
  121. con : SQLAlchemy connectable(engine/connection) or sqlite3 connection
  122. Using SQLAlchemy makes it possible to use any DB supported by the
  123. library.
  124. If a DBAPI2 object, only sqlite3 is supported.
  125. cur : deprecated, cursor is obtained from connection, default: None
  126. params : list or tuple, optional, default: None
  127. List of parameters to pass to execute method.
  128. Returns
  129. -------
  130. Results Iterable
  131. """
  132. if cur is None:
  133. pandas_sql = pandasSQL_builder(con)
  134. else:
  135. pandas_sql = pandasSQL_builder(cur, is_cursor=True)
  136. args = _convert_params(sql, params)
  137. return pandas_sql.execute(*args)
  138. # -----------------------------------------------------------------------------
  139. # -- Read and write to DataFrames
  140. def read_sql_table(table_name, con, schema=None, index_col=None,
  141. coerce_float=True, parse_dates=None, columns=None,
  142. chunksize=None):
  143. """
  144. Read SQL database table into a DataFrame.
  145. Given a table name and a SQLAlchemy connectable, returns a DataFrame.
  146. This function does not support DBAPI connections.
  147. Parameters
  148. ----------
  149. table_name : str
  150. Name of SQL table in database.
  151. con : SQLAlchemy connectable or str
  152. A database URI could be provided as as str.
  153. SQLite DBAPI connection mode not supported.
  154. schema : str, default None
  155. Name of SQL schema in database to query (if database flavor
  156. supports this). Uses default schema if None (default).
  157. index_col : str or list of str, optional, default: None
  158. Column(s) to set as index(MultiIndex).
  159. coerce_float : bool, default True
  160. Attempts to convert values of non-string, non-numeric objects (like
  161. decimal.Decimal) to floating point. Can result in loss of Precision.
  162. parse_dates : list or dict, default None
  163. The behavior is as follows:
  164. - List of column names to parse as dates.
  165. - Dict of ``{column_name: format string}`` where format string is
  166. strftime compatible in case of parsing string times or is one of
  167. (D, s, ns, ms, us) in case of parsing integer timestamps.
  168. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
  169. to the keyword arguments of :func:`pandas.to_datetime`
  170. Especially useful with databases without native Datetime support,
  171. such as SQLite.
  172. columns : list, default None
  173. List of column names to select from SQL table.
  174. chunksize : int, default None
  175. If specified, returns an iterator where `chunksize` is the number of
  176. rows to include in each chunk.
  177. Returns
  178. -------
  179. DataFrame
  180. A SQL table is returned as two-dimensional data structure with labeled
  181. axes.
  182. See Also
  183. --------
  184. read_sql_query : Read SQL query into a DataFrame.
  185. read_sql : Read SQL query or database table into a DataFrame.
  186. Notes
  187. -----
  188. Any datetime values with time zone information will be converted to UTC.
  189. Examples
  190. --------
  191. >>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP
  192. """
  193. con = _engine_builder(con)
  194. if not _is_sqlalchemy_connectable(con):
  195. raise NotImplementedError("read_sql_table only supported for "
  196. "SQLAlchemy connectable.")
  197. import sqlalchemy
  198. from sqlalchemy.schema import MetaData
  199. meta = MetaData(con, schema=schema)
  200. try:
  201. meta.reflect(only=[table_name], views=True)
  202. except sqlalchemy.exc.InvalidRequestError:
  203. raise ValueError("Table {name} not found".format(name=table_name))
  204. pandas_sql = SQLDatabase(con, meta=meta)
  205. table = pandas_sql.read_table(
  206. table_name, index_col=index_col, coerce_float=coerce_float,
  207. parse_dates=parse_dates, columns=columns, chunksize=chunksize)
  208. if table is not None:
  209. return table
  210. else:
  211. raise ValueError("Table {name} not found".format(name=table_name), con)
  212. def read_sql_query(sql, con, index_col=None, coerce_float=True, params=None,
  213. parse_dates=None, chunksize=None):
  214. """Read SQL query into a DataFrame.
  215. Returns a DataFrame corresponding to the result set of the query
  216. string. Optionally provide an `index_col` parameter to use one of the
  217. columns as the index, otherwise default integer index will be used.
  218. Parameters
  219. ----------
  220. sql : string SQL query or SQLAlchemy Selectable (select or text object)
  221. SQL query to be executed.
  222. con : SQLAlchemy connectable(engine/connection), database string URI,
  223. or sqlite3 DBAPI2 connection
  224. Using SQLAlchemy makes it possible to use any DB supported by that
  225. library.
  226. If a DBAPI2 object, only sqlite3 is supported.
  227. index_col : string or list of strings, optional, default: None
  228. Column(s) to set as index(MultiIndex).
  229. coerce_float : boolean, default True
  230. Attempts to convert values of non-string, non-numeric objects (like
  231. decimal.Decimal) to floating point. Useful for SQL result sets.
  232. params : list, tuple or dict, optional, default: None
  233. List of parameters to pass to execute method. The syntax used
  234. to pass parameters is database driver dependent. Check your
  235. database driver documentation for which of the five syntax styles,
  236. described in PEP 249's paramstyle, is supported.
  237. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
  238. parse_dates : list or dict, default: None
  239. - List of column names to parse as dates.
  240. - Dict of ``{column_name: format string}`` where format string is
  241. strftime compatible in case of parsing string times, or is one of
  242. (D, s, ns, ms, us) in case of parsing integer timestamps.
  243. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
  244. to the keyword arguments of :func:`pandas.to_datetime`
  245. Especially useful with databases without native Datetime support,
  246. such as SQLite.
  247. chunksize : int, default None
  248. If specified, return an iterator where `chunksize` is the number of
  249. rows to include in each chunk.
  250. Returns
  251. -------
  252. DataFrame
  253. See Also
  254. --------
  255. read_sql_table : Read SQL database table into a DataFrame.
  256. read_sql
  257. Notes
  258. -----
  259. Any datetime values with time zone information parsed via the `parse_dates`
  260. parameter will be converted to UTC.
  261. """
  262. pandas_sql = pandasSQL_builder(con)
  263. return pandas_sql.read_query(
  264. sql, index_col=index_col, params=params, coerce_float=coerce_float,
  265. parse_dates=parse_dates, chunksize=chunksize)
  266. def read_sql(sql, con, index_col=None, coerce_float=True, params=None,
  267. parse_dates=None, columns=None, chunksize=None):
  268. """
  269. Read SQL query or database table into a DataFrame.
  270. This function is a convenience wrapper around ``read_sql_table`` and
  271. ``read_sql_query`` (for backward compatibility). It will delegate
  272. to the specific function depending on the provided input. A SQL query
  273. will be routed to ``read_sql_query``, while a database table name will
  274. be routed to ``read_sql_table``. Note that the delegated function might
  275. have more specific notes about their functionality not listed here.
  276. Parameters
  277. ----------
  278. sql : string or SQLAlchemy Selectable (select or text object)
  279. SQL query to be executed or a table name.
  280. con : SQLAlchemy connectable (engine/connection) or database string URI
  281. or DBAPI2 connection (fallback mode)
  282. Using SQLAlchemy makes it possible to use any DB supported by that
  283. library. If a DBAPI2 object, only sqlite3 is supported.
  284. index_col : string or list of strings, optional, default: None
  285. Column(s) to set as index(MultiIndex).
  286. coerce_float : boolean, default True
  287. Attempts to convert values of non-string, non-numeric objects (like
  288. decimal.Decimal) to floating point, useful for SQL result sets.
  289. params : list, tuple or dict, optional, default: None
  290. List of parameters to pass to execute method. The syntax used
  291. to pass parameters is database driver dependent. Check your
  292. database driver documentation for which of the five syntax styles,
  293. described in PEP 249's paramstyle, is supported.
  294. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
  295. parse_dates : list or dict, default: None
  296. - List of column names to parse as dates.
  297. - Dict of ``{column_name: format string}`` where format string is
  298. strftime compatible in case of parsing string times, or is one of
  299. (D, s, ns, ms, us) in case of parsing integer timestamps.
  300. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
  301. to the keyword arguments of :func:`pandas.to_datetime`
  302. Especially useful with databases without native Datetime support,
  303. such as SQLite.
  304. columns : list, default: None
  305. List of column names to select from SQL table (only used when reading
  306. a table).
  307. chunksize : int, default None
  308. If specified, return an iterator where `chunksize` is the
  309. number of rows to include in each chunk.
  310. Returns
  311. -------
  312. DataFrame
  313. See Also
  314. --------
  315. read_sql_table : Read SQL database table into a DataFrame.
  316. read_sql_query : Read SQL query into a DataFrame.
  317. """
  318. pandas_sql = pandasSQL_builder(con)
  319. if isinstance(pandas_sql, SQLiteDatabase):
  320. return pandas_sql.read_query(
  321. sql, index_col=index_col, params=params,
  322. coerce_float=coerce_float, parse_dates=parse_dates,
  323. chunksize=chunksize)
  324. try:
  325. _is_table_name = pandas_sql.has_table(sql)
  326. except Exception:
  327. # using generic exception to catch errors from sql drivers (GH24988)
  328. _is_table_name = False
  329. if _is_table_name:
  330. pandas_sql.meta.reflect(only=[sql])
  331. return pandas_sql.read_table(
  332. sql, index_col=index_col, coerce_float=coerce_float,
  333. parse_dates=parse_dates, columns=columns, chunksize=chunksize)
  334. else:
  335. return pandas_sql.read_query(
  336. sql, index_col=index_col, params=params,
  337. coerce_float=coerce_float, parse_dates=parse_dates,
  338. chunksize=chunksize)
  339. def to_sql(frame, name, con, schema=None, if_exists='fail', index=True,
  340. index_label=None, chunksize=None, dtype=None, method=None):
  341. """
  342. Write records stored in a DataFrame to a SQL database.
  343. Parameters
  344. ----------
  345. frame : DataFrame, Series
  346. name : string
  347. Name of SQL table.
  348. con : SQLAlchemy connectable(engine/connection) or database string URI
  349. or sqlite3 DBAPI2 connection
  350. Using SQLAlchemy makes it possible to use any DB supported by that
  351. library.
  352. If a DBAPI2 object, only sqlite3 is supported.
  353. schema : string, default None
  354. Name of SQL schema in database to write to (if database flavor
  355. supports this). If None, use default schema (default).
  356. if_exists : {'fail', 'replace', 'append'}, default 'fail'
  357. - fail: If table exists, do nothing.
  358. - replace: If table exists, drop it, recreate it, and insert data.
  359. - append: If table exists, insert data. Create if does not exist.
  360. index : boolean, default True
  361. Write DataFrame index as a column.
  362. index_label : string or sequence, default None
  363. Column label for index column(s). If None is given (default) and
  364. `index` is True, then the index names are used.
  365. A sequence should be given if the DataFrame uses MultiIndex.
  366. chunksize : int, default None
  367. If not None, then rows will be written in batches of this size at a
  368. time. If None, all rows will be written at once.
  369. dtype : single SQLtype or dict of column name to SQL type, default None
  370. Optional specifying the datatype for columns. The SQL type should
  371. be a SQLAlchemy type, or a string for sqlite3 fallback connection.
  372. If all columns are of the same type, one single value can be used.
  373. method : {None, 'multi', callable}, default None
  374. Controls the SQL insertion clause used:
  375. - None : Uses standard SQL ``INSERT`` clause (one per row).
  376. - 'multi': Pass multiple values in a single ``INSERT`` clause.
  377. - callable with signature ``(pd_table, conn, keys, data_iter)``.
  378. Details and a sample callable implementation can be found in the
  379. section :ref:`insert method <io.sql.method>`.
  380. .. versionadded:: 0.24.0
  381. """
  382. if if_exists not in ('fail', 'replace', 'append'):
  383. raise ValueError("'{0}' is not valid for if_exists".format(if_exists))
  384. pandas_sql = pandasSQL_builder(con, schema=schema)
  385. if isinstance(frame, Series):
  386. frame = frame.to_frame()
  387. elif not isinstance(frame, DataFrame):
  388. raise NotImplementedError("'frame' argument should be either a "
  389. "Series or a DataFrame")
  390. pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index,
  391. index_label=index_label, schema=schema,
  392. chunksize=chunksize, dtype=dtype, method=method)
  393. def has_table(table_name, con, schema=None):
  394. """
  395. Check if DataBase has named table.
  396. Parameters
  397. ----------
  398. table_name: string
  399. Name of SQL table.
  400. con: SQLAlchemy connectable(engine/connection) or sqlite3 DBAPI2 connection
  401. Using SQLAlchemy makes it possible to use any DB supported by that
  402. library.
  403. If a DBAPI2 object, only sqlite3 is supported.
  404. schema : string, default None
  405. Name of SQL schema in database to write to (if database flavor supports
  406. this). If None, use default schema (default).
  407. Returns
  408. -------
  409. boolean
  410. """
  411. pandas_sql = pandasSQL_builder(con, schema=schema)
  412. return pandas_sql.has_table(table_name)
  413. table_exists = has_table
  414. def _engine_builder(con):
  415. """
  416. Returns a SQLAlchemy engine from a URI (if con is a string)
  417. else it just return con without modifying it.
  418. """
  419. global _SQLALCHEMY_INSTALLED
  420. if isinstance(con, string_types):
  421. try:
  422. import sqlalchemy
  423. except ImportError:
  424. _SQLALCHEMY_INSTALLED = False
  425. else:
  426. con = sqlalchemy.create_engine(con)
  427. return con
  428. return con
  429. def pandasSQL_builder(con, schema=None, meta=None,
  430. is_cursor=False):
  431. """
  432. Convenience function to return the correct PandasSQL subclass based on the
  433. provided parameters.
  434. """
  435. # When support for DBAPI connections is removed,
  436. # is_cursor should not be necessary.
  437. con = _engine_builder(con)
  438. if _is_sqlalchemy_connectable(con):
  439. return SQLDatabase(con, schema=schema, meta=meta)
  440. elif isinstance(con, string_types):
  441. raise ImportError("Using URI string without sqlalchemy installed.")
  442. else:
  443. return SQLiteDatabase(con, is_cursor=is_cursor)
  444. class SQLTable(PandasObject):
  445. """
  446. For mapping Pandas tables to SQL tables.
  447. Uses fact that table is reflected by SQLAlchemy to
  448. do better type conversions.
  449. Also holds various flags needed to avoid having to
  450. pass them between functions all the time.
  451. """
  452. # TODO: support for multiIndex
  453. def __init__(self, name, pandas_sql_engine, frame=None, index=True,
  454. if_exists='fail', prefix='pandas', index_label=None,
  455. schema=None, keys=None, dtype=None):
  456. self.name = name
  457. self.pd_sql = pandas_sql_engine
  458. self.prefix = prefix
  459. self.frame = frame
  460. self.index = self._index_name(index, index_label)
  461. self.schema = schema
  462. self.if_exists = if_exists
  463. self.keys = keys
  464. self.dtype = dtype
  465. if frame is not None:
  466. # We want to initialize based on a dataframe
  467. self.table = self._create_table_setup()
  468. else:
  469. # no data provided, read-only mode
  470. self.table = self.pd_sql.get_table(self.name, self.schema)
  471. if self.table is None:
  472. raise ValueError(
  473. "Could not init table '{name}'".format(name=name))
  474. def exists(self):
  475. return self.pd_sql.has_table(self.name, self.schema)
  476. def sql_schema(self):
  477. from sqlalchemy.schema import CreateTable
  478. return str(CreateTable(self.table).compile(self.pd_sql.connectable))
  479. def _execute_create(self):
  480. # Inserting table into database, add to MetaData object
  481. self.table = self.table.tometadata(self.pd_sql.meta)
  482. self.table.create()
  483. def create(self):
  484. if self.exists():
  485. if self.if_exists == 'fail':
  486. raise ValueError(
  487. "Table '{name}' already exists.".format(name=self.name))
  488. elif self.if_exists == 'replace':
  489. self.pd_sql.drop_table(self.name, self.schema)
  490. self._execute_create()
  491. elif self.if_exists == 'append':
  492. pass
  493. else:
  494. raise ValueError(
  495. "'{0}' is not valid for if_exists".format(self.if_exists))
  496. else:
  497. self._execute_create()
  498. def _execute_insert(self, conn, keys, data_iter):
  499. """Execute SQL statement inserting data
  500. Parameters
  501. ----------
  502. conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
  503. keys : list of str
  504. Column names
  505. data_iter : generator of list
  506. Each item contains a list of values to be inserted
  507. """
  508. data = [dict(zip(keys, row)) for row in data_iter]
  509. conn.execute(self.table.insert(), data)
  510. def _execute_insert_multi(self, conn, keys, data_iter):
  511. """Alternative to _execute_insert for DBs support multivalue INSERT.
  512. Note: multi-value insert is usually faster for analytics DBs
  513. and tables containing a few columns
  514. but performance degrades quickly with increase of columns.
  515. """
  516. data = [dict(zip(keys, row)) for row in data_iter]
  517. conn.execute(self.table.insert(data))
  518. def insert_data(self):
  519. if self.index is not None:
  520. temp = self.frame.copy()
  521. temp.index.names = self.index
  522. try:
  523. temp.reset_index(inplace=True)
  524. except ValueError as err:
  525. raise ValueError(
  526. "duplicate name in index/columns: {0}".format(err))
  527. else:
  528. temp = self.frame
  529. column_names = list(map(text_type, temp.columns))
  530. ncols = len(column_names)
  531. data_list = [None] * ncols
  532. blocks = temp._data.blocks
  533. for b in blocks:
  534. if b.is_datetime:
  535. # return datetime.datetime objects
  536. if b.is_datetimetz:
  537. # GH 9086: Ensure we return datetimes with timezone info
  538. # Need to return 2-D data; DatetimeIndex is 1D
  539. d = b.values.to_pydatetime()
  540. d = np.expand_dims(d, axis=0)
  541. else:
  542. # convert to microsecond resolution for datetime.datetime
  543. d = b.values.astype('M8[us]').astype(object)
  544. else:
  545. d = np.array(b.get_values(), dtype=object)
  546. # replace NaN with None
  547. if b._can_hold_na:
  548. mask = isna(d)
  549. d[mask] = None
  550. for col_loc, col in zip(b.mgr_locs, d):
  551. data_list[col_loc] = col
  552. return column_names, data_list
  553. def insert(self, chunksize=None, method=None):
  554. # set insert method
  555. if method is None:
  556. exec_insert = self._execute_insert
  557. elif method == 'multi':
  558. exec_insert = self._execute_insert_multi
  559. elif callable(method):
  560. exec_insert = partial(method, self)
  561. else:
  562. raise ValueError('Invalid parameter `method`: {}'.format(method))
  563. keys, data_list = self.insert_data()
  564. nrows = len(self.frame)
  565. if nrows == 0:
  566. return
  567. if chunksize is None:
  568. chunksize = nrows
  569. elif chunksize == 0:
  570. raise ValueError('chunksize argument should be non-zero')
  571. chunks = int(nrows / chunksize) + 1
  572. with self.pd_sql.run_transaction() as conn:
  573. for i in range(chunks):
  574. start_i = i * chunksize
  575. end_i = min((i + 1) * chunksize, nrows)
  576. if start_i >= end_i:
  577. break
  578. chunk_iter = zip(*[arr[start_i:end_i] for arr in data_list])
  579. exec_insert(conn, keys, chunk_iter)
  580. def _query_iterator(self, result, chunksize, columns, coerce_float=True,
  581. parse_dates=None):
  582. """Return generator through chunked result set."""
  583. while True:
  584. data = result.fetchmany(chunksize)
  585. if not data:
  586. break
  587. else:
  588. self.frame = DataFrame.from_records(
  589. data, columns=columns, coerce_float=coerce_float)
  590. self._harmonize_columns(parse_dates=parse_dates)
  591. if self.index is not None:
  592. self.frame.set_index(self.index, inplace=True)
  593. yield self.frame
  594. def read(self, coerce_float=True, parse_dates=None, columns=None,
  595. chunksize=None):
  596. if columns is not None and len(columns) > 0:
  597. from sqlalchemy import select
  598. cols = [self.table.c[n] for n in columns]
  599. if self.index is not None:
  600. [cols.insert(0, self.table.c[idx]) for idx in self.index[::-1]]
  601. sql_select = select(cols)
  602. else:
  603. sql_select = self.table.select()
  604. result = self.pd_sql.execute(sql_select)
  605. column_names = result.keys()
  606. if chunksize is not None:
  607. return self._query_iterator(result, chunksize, column_names,
  608. coerce_float=coerce_float,
  609. parse_dates=parse_dates)
  610. else:
  611. data = result.fetchall()
  612. self.frame = DataFrame.from_records(
  613. data, columns=column_names, coerce_float=coerce_float)
  614. self._harmonize_columns(parse_dates=parse_dates)
  615. if self.index is not None:
  616. self.frame.set_index(self.index, inplace=True)
  617. return self.frame
  618. def _index_name(self, index, index_label):
  619. # for writing: index=True to include index in sql table
  620. if index is True:
  621. nlevels = self.frame.index.nlevels
  622. # if index_label is specified, set this as index name(s)
  623. if index_label is not None:
  624. if not isinstance(index_label, list):
  625. index_label = [index_label]
  626. if len(index_label) != nlevels:
  627. raise ValueError(
  628. "Length of 'index_label' should match number of "
  629. "levels, which is {0}".format(nlevels))
  630. else:
  631. return index_label
  632. # return the used column labels for the index columns
  633. if (nlevels == 1 and 'index' not in self.frame.columns and
  634. self.frame.index.name is None):
  635. return ['index']
  636. else:
  637. return [l if l is not None else "level_{0}".format(i)
  638. for i, l in enumerate(self.frame.index.names)]
  639. # for reading: index=(list of) string to specify column to set as index
  640. elif isinstance(index, string_types):
  641. return [index]
  642. elif isinstance(index, list):
  643. return index
  644. else:
  645. return None
  646. def _get_column_names_and_types(self, dtype_mapper):
  647. column_names_and_types = []
  648. if self.index is not None:
  649. for i, idx_label in enumerate(self.index):
  650. idx_type = dtype_mapper(
  651. self.frame.index._get_level_values(i))
  652. column_names_and_types.append((text_type(idx_label),
  653. idx_type, True))
  654. column_names_and_types += [
  655. (text_type(self.frame.columns[i]),
  656. dtype_mapper(self.frame.iloc[:, i]),
  657. False)
  658. for i in range(len(self.frame.columns))
  659. ]
  660. return column_names_and_types
  661. def _create_table_setup(self):
  662. from sqlalchemy import Table, Column, PrimaryKeyConstraint
  663. column_names_and_types = self._get_column_names_and_types(
  664. self._sqlalchemy_type
  665. )
  666. columns = [Column(name, typ, index=is_index)
  667. for name, typ, is_index in column_names_and_types]
  668. if self.keys is not None:
  669. if not is_list_like(self.keys):
  670. keys = [self.keys]
  671. else:
  672. keys = self.keys
  673. pkc = PrimaryKeyConstraint(*keys, name=self.name + '_pk')
  674. columns.append(pkc)
  675. schema = self.schema or self.pd_sql.meta.schema
  676. # At this point, attach to new metadata, only attach to self.meta
  677. # once table is created.
  678. from sqlalchemy.schema import MetaData
  679. meta = MetaData(self.pd_sql, schema=schema)
  680. return Table(self.name, meta, *columns, schema=schema)
  681. def _harmonize_columns(self, parse_dates=None):
  682. """
  683. Make the DataFrame's column types align with the SQL table
  684. column types.
  685. Need to work around limited NA value support. Floats are always
  686. fine, ints must always be floats if there are Null values.
  687. Booleans are hard because converting bool column with None replaces
  688. all Nones with false. Therefore only convert bool if there are no
  689. NA values.
  690. Datetimes should already be converted to np.datetime64 if supported,
  691. but here we also force conversion if required.
  692. """
  693. parse_dates = _process_parse_dates_argument(parse_dates)
  694. for sql_col in self.table.columns:
  695. col_name = sql_col.name
  696. try:
  697. df_col = self.frame[col_name]
  698. # Handle date parsing upfront; don't try to convert columns
  699. # twice
  700. if col_name in parse_dates:
  701. try:
  702. fmt = parse_dates[col_name]
  703. except TypeError:
  704. fmt = None
  705. self.frame[col_name] = _handle_date_column(
  706. df_col, format=fmt)
  707. continue
  708. # the type the dataframe column should have
  709. col_type = self._get_dtype(sql_col.type)
  710. if (col_type is datetime or col_type is date or
  711. col_type is DatetimeTZDtype):
  712. # Convert tz-aware Datetime SQL columns to UTC
  713. utc = col_type is DatetimeTZDtype
  714. self.frame[col_name] = _handle_date_column(df_col, utc=utc)
  715. elif col_type is float:
  716. # floats support NA, can always convert!
  717. self.frame[col_name] = df_col.astype(col_type, copy=False)
  718. elif len(df_col) == df_col.count():
  719. # No NA values, can convert ints and bools
  720. if col_type is np.dtype('int64') or col_type is bool:
  721. self.frame[col_name] = df_col.astype(
  722. col_type, copy=False)
  723. except KeyError:
  724. pass # this column not in results
  725. def _sqlalchemy_type(self, col):
  726. dtype = self.dtype or {}
  727. if col.name in dtype:
  728. return self.dtype[col.name]
  729. # Infer type of column, while ignoring missing values.
  730. # Needed for inserting typed data containing NULLs, GH 8778.
  731. col_type = lib.infer_dtype(col, skipna=True)
  732. from sqlalchemy.types import (BigInteger, Integer, Float,
  733. Text, Boolean,
  734. DateTime, Date, Time, TIMESTAMP)
  735. if col_type == 'datetime64' or col_type == 'datetime':
  736. # GH 9086: TIMESTAMP is the suggested type if the column contains
  737. # timezone information
  738. try:
  739. if col.dt.tz is not None:
  740. return TIMESTAMP(timezone=True)
  741. except AttributeError:
  742. # The column is actually a DatetimeIndex
  743. if col.tz is not None:
  744. return TIMESTAMP(timezone=True)
  745. return DateTime
  746. if col_type == 'timedelta64':
  747. warnings.warn("the 'timedelta' type is not supported, and will be "
  748. "written as integer values (ns frequency) to the "
  749. "database.", UserWarning, stacklevel=8)
  750. return BigInteger
  751. elif col_type == 'floating':
  752. if col.dtype == 'float32':
  753. return Float(precision=23)
  754. else:
  755. return Float(precision=53)
  756. elif col_type == 'integer':
  757. if col.dtype == 'int32':
  758. return Integer
  759. else:
  760. return BigInteger
  761. elif col_type == 'boolean':
  762. return Boolean
  763. elif col_type == 'date':
  764. return Date
  765. elif col_type == 'time':
  766. return Time
  767. elif col_type == 'complex':
  768. raise ValueError('Complex datatypes not supported')
  769. return Text
  770. def _get_dtype(self, sqltype):
  771. from sqlalchemy.types import (Integer, Float, Boolean, DateTime,
  772. Date, TIMESTAMP)
  773. if isinstance(sqltype, Float):
  774. return float
  775. elif isinstance(sqltype, Integer):
  776. # TODO: Refine integer size.
  777. return np.dtype('int64')
  778. elif isinstance(sqltype, TIMESTAMP):
  779. # we have a timezone capable type
  780. if not sqltype.timezone:
  781. return datetime
  782. return DatetimeTZDtype
  783. elif isinstance(sqltype, DateTime):
  784. # Caution: np.datetime64 is also a subclass of np.number.
  785. return datetime
  786. elif isinstance(sqltype, Date):
  787. return date
  788. elif isinstance(sqltype, Boolean):
  789. return bool
  790. return object
  791. class PandasSQL(PandasObject):
  792. """
  793. Subclasses Should define read_sql and to_sql.
  794. """
  795. def read_sql(self, *args, **kwargs):
  796. raise ValueError("PandasSQL must be created with an SQLAlchemy "
  797. "connectable or sqlite connection")
  798. def to_sql(self, *args, **kwargs):
  799. raise ValueError("PandasSQL must be created with an SQLAlchemy "
  800. "connectable or sqlite connection")
  801. class SQLDatabase(PandasSQL):
  802. """
  803. This class enables conversion between DataFrame and SQL databases
  804. using SQLAlchemy to handle DataBase abstraction.
  805. Parameters
  806. ----------
  807. engine : SQLAlchemy connectable
  808. Connectable to connect with the database. Using SQLAlchemy makes it
  809. possible to use any DB supported by that library.
  810. schema : string, default None
  811. Name of SQL schema in database to write to (if database flavor
  812. supports this). If None, use default schema (default).
  813. meta : SQLAlchemy MetaData object, default None
  814. If provided, this MetaData object is used instead of a newly
  815. created. This allows to specify database flavor specific
  816. arguments in the MetaData object.
  817. """
  818. def __init__(self, engine, schema=None, meta=None):
  819. self.connectable = engine
  820. if not meta:
  821. from sqlalchemy.schema import MetaData
  822. meta = MetaData(self.connectable, schema=schema)
  823. self.meta = meta
  824. @contextmanager
  825. def run_transaction(self):
  826. with self.connectable.begin() as tx:
  827. if hasattr(tx, 'execute'):
  828. yield tx
  829. else:
  830. yield self.connectable
  831. def execute(self, *args, **kwargs):
  832. """Simple passthrough to SQLAlchemy connectable"""
  833. return self.connectable.execute(*args, **kwargs)
  834. def read_table(self, table_name, index_col=None, coerce_float=True,
  835. parse_dates=None, columns=None, schema=None,
  836. chunksize=None):
  837. """Read SQL database table into a DataFrame.
  838. Parameters
  839. ----------
  840. table_name : string
  841. Name of SQL table in database.
  842. index_col : string, optional, default: None
  843. Column to set as index.
  844. coerce_float : boolean, default True
  845. Attempts to convert values of non-string, non-numeric objects
  846. (like decimal.Decimal) to floating point. This can result in
  847. loss of precision.
  848. parse_dates : list or dict, default: None
  849. - List of column names to parse as dates.
  850. - Dict of ``{column_name: format string}`` where format string is
  851. strftime compatible in case of parsing string times, or is one of
  852. (D, s, ns, ms, us) in case of parsing integer timestamps.
  853. - Dict of ``{column_name: arg}``, where the arg corresponds
  854. to the keyword arguments of :func:`pandas.to_datetime`.
  855. Especially useful with databases without native Datetime support,
  856. such as SQLite.
  857. columns : list, default: None
  858. List of column names to select from SQL table.
  859. schema : string, default None
  860. Name of SQL schema in database to query (if database flavor
  861. supports this). If specified, this overwrites the default
  862. schema of the SQL database object.
  863. chunksize : int, default None
  864. If specified, return an iterator where `chunksize` is the number
  865. of rows to include in each chunk.
  866. Returns
  867. -------
  868. DataFrame
  869. See Also
  870. --------
  871. pandas.read_sql_table
  872. SQLDatabase.read_query
  873. """
  874. table = SQLTable(table_name, self, index=index_col, schema=schema)
  875. return table.read(coerce_float=coerce_float,
  876. parse_dates=parse_dates, columns=columns,
  877. chunksize=chunksize)
  878. @staticmethod
  879. def _query_iterator(result, chunksize, columns, index_col=None,
  880. coerce_float=True, parse_dates=None):
  881. """Return generator through chunked result set"""
  882. while True:
  883. data = result.fetchmany(chunksize)
  884. if not data:
  885. break
  886. else:
  887. yield _wrap_result(data, columns, index_col=index_col,
  888. coerce_float=coerce_float,
  889. parse_dates=parse_dates)
  890. def read_query(self, sql, index_col=None, coerce_float=True,
  891. parse_dates=None, params=None, chunksize=None):
  892. """Read SQL query into a DataFrame.
  893. Parameters
  894. ----------
  895. sql : string
  896. SQL query to be executed.
  897. index_col : string, optional, default: None
  898. Column name to use as index for the returned DataFrame object.
  899. coerce_float : boolean, default True
  900. Attempt to convert values of non-string, non-numeric objects (like
  901. decimal.Decimal) to floating point, useful for SQL result sets.
  902. params : list, tuple or dict, optional, default: None
  903. List of parameters to pass to execute method. The syntax used
  904. to pass parameters is database driver dependent. Check your
  905. database driver documentation for which of the five syntax styles,
  906. described in PEP 249's paramstyle, is supported.
  907. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
  908. parse_dates : list or dict, default: None
  909. - List of column names to parse as dates.
  910. - Dict of ``{column_name: format string}`` where format string is
  911. strftime compatible in case of parsing string times, or is one of
  912. (D, s, ns, ms, us) in case of parsing integer timestamps.
  913. - Dict of ``{column_name: arg dict}``, where the arg dict
  914. corresponds to the keyword arguments of
  915. :func:`pandas.to_datetime` Especially useful with databases
  916. without native Datetime support, such as SQLite.
  917. chunksize : int, default None
  918. If specified, return an iterator where `chunksize` is the number
  919. of rows to include in each chunk.
  920. Returns
  921. -------
  922. DataFrame
  923. See Also
  924. --------
  925. read_sql_table : Read SQL database table into a DataFrame.
  926. read_sql
  927. """
  928. args = _convert_params(sql, params)
  929. result = self.execute(*args)
  930. columns = result.keys()
  931. if chunksize is not None:
  932. return self._query_iterator(result, chunksize, columns,
  933. index_col=index_col,
  934. coerce_float=coerce_float,
  935. parse_dates=parse_dates)
  936. else:
  937. data = result.fetchall()
  938. frame = _wrap_result(data, columns, index_col=index_col,
  939. coerce_float=coerce_float,
  940. parse_dates=parse_dates)
  941. return frame
  942. read_sql = read_query
  943. def to_sql(self, frame, name, if_exists='fail', index=True,
  944. index_label=None, schema=None, chunksize=None, dtype=None,
  945. method=None):
  946. """
  947. Write records stored in a DataFrame to a SQL database.
  948. Parameters
  949. ----------
  950. frame : DataFrame
  951. name : string
  952. Name of SQL table.
  953. if_exists : {'fail', 'replace', 'append'}, default 'fail'
  954. - fail: If table exists, do nothing.
  955. - replace: If table exists, drop it, recreate it, and insert data.
  956. - append: If table exists, insert data. Create if does not exist.
  957. index : boolean, default True
  958. Write DataFrame index as a column.
  959. index_label : string or sequence, default None
  960. Column label for index column(s). If None is given (default) and
  961. `index` is True, then the index names are used.
  962. A sequence should be given if the DataFrame uses MultiIndex.
  963. schema : string, default None
  964. Name of SQL schema in database to write to (if database flavor
  965. supports this). If specified, this overwrites the default
  966. schema of the SQLDatabase object.
  967. chunksize : int, default None
  968. If not None, then rows will be written in batches of this size at a
  969. time. If None, all rows will be written at once.
  970. dtype : single type or dict of column name to SQL type, default None
  971. Optional specifying the datatype for columns. The SQL type should
  972. be a SQLAlchemy type. If all columns are of the same type, one
  973. single value can be used.
  974. method : {None', 'multi', callable}, default None
  975. Controls the SQL insertion clause used:
  976. * None : Uses standard SQL ``INSERT`` clause (one per row).
  977. * 'multi': Pass multiple values in a single ``INSERT`` clause.
  978. * callable with signature ``(pd_table, conn, keys, data_iter)``.
  979. Details and a sample callable implementation can be found in the
  980. section :ref:`insert method <io.sql.method>`.
  981. .. versionadded:: 0.24.0
  982. """
  983. if dtype and not is_dict_like(dtype):
  984. dtype = {col_name: dtype for col_name in frame}
  985. if dtype is not None:
  986. from sqlalchemy.types import to_instance, TypeEngine
  987. for col, my_type in dtype.items():
  988. if not isinstance(to_instance(my_type), TypeEngine):
  989. raise ValueError('The type of {column} is not a '
  990. 'SQLAlchemy type '.format(column=col))
  991. table = SQLTable(name, self, frame=frame, index=index,
  992. if_exists=if_exists, index_label=index_label,
  993. schema=schema, dtype=dtype)
  994. table.create()
  995. table.insert(chunksize, method=method)
  996. if (not name.isdigit() and not name.islower()):
  997. # check for potentially case sensitivity issues (GH7815)
  998. # Only check when name is not a number and name is not lower case
  999. engine = self.connectable.engine
  1000. with self.connectable.connect() as conn:
  1001. table_names = engine.table_names(
  1002. schema=schema or self.meta.schema,
  1003. connection=conn,
  1004. )
  1005. if name not in table_names:
  1006. msg = (
  1007. "The provided table name '{0}' is not found exactly as "
  1008. "such in the database after writing the table, possibly "
  1009. "due to case sensitivity issues. Consider using lower "
  1010. "case table names."
  1011. ).format(name)
  1012. warnings.warn(msg, UserWarning)
  1013. @property
  1014. def tables(self):
  1015. return self.meta.tables
  1016. def has_table(self, name, schema=None):
  1017. return self.connectable.run_callable(
  1018. self.connectable.dialect.has_table,
  1019. name,
  1020. schema or self.meta.schema,
  1021. )
  1022. def get_table(self, table_name, schema=None):
  1023. schema = schema or self.meta.schema
  1024. if schema:
  1025. tbl = self.meta.tables.get('.'.join([schema, table_name]))
  1026. else:
  1027. tbl = self.meta.tables.get(table_name)
  1028. # Avoid casting double-precision floats into decimals
  1029. from sqlalchemy import Numeric
  1030. for column in tbl.columns:
  1031. if isinstance(column.type, Numeric):
  1032. column.type.asdecimal = False
  1033. return tbl
  1034. def drop_table(self, table_name, schema=None):
  1035. schema = schema or self.meta.schema
  1036. if self.has_table(table_name, schema):
  1037. self.meta.reflect(only=[table_name], schema=schema)
  1038. self.get_table(table_name, schema).drop()
  1039. self.meta.clear()
  1040. def _create_sql_schema(self, frame, table_name, keys=None, dtype=None):
  1041. table = SQLTable(table_name, self, frame=frame, index=False, keys=keys,
  1042. dtype=dtype)
  1043. return str(table.sql_schema())
  1044. # ---- SQL without SQLAlchemy ---
  1045. # sqlite-specific sql strings and handler class
  1046. # dictionary used for readability purposes
  1047. _SQL_TYPES = {
  1048. 'string': 'TEXT',
  1049. 'floating': 'REAL',
  1050. 'integer': 'INTEGER',
  1051. 'datetime': 'TIMESTAMP',
  1052. 'date': 'DATE',
  1053. 'time': 'TIME',
  1054. 'boolean': 'INTEGER',
  1055. }
  1056. def _get_unicode_name(name):
  1057. try:
  1058. uname = text_type(name).encode("utf-8", "strict").decode("utf-8")
  1059. except UnicodeError:
  1060. raise ValueError(
  1061. "Cannot convert identifier to UTF-8: '{name}'".format(name=name))
  1062. return uname
  1063. def _get_valid_sqlite_name(name):
  1064. # See http://stackoverflow.com/questions/6514274/how-do-you-escape-strings\
  1065. # -for-sqlite-table-column-names-in-python
  1066. # Ensure the string can be encoded as UTF-8.
  1067. # Ensure the string does not include any NUL characters.
  1068. # Replace all " with "".
  1069. # Wrap the entire thing in double quotes.
  1070. uname = _get_unicode_name(name)
  1071. if not len(uname):
  1072. raise ValueError("Empty table or column name specified")
  1073. nul_index = uname.find("\x00")
  1074. if nul_index >= 0:
  1075. raise ValueError('SQLite identifier cannot contain NULs')
  1076. return '"' + uname.replace('"', '""') + '"'
  1077. _SAFE_NAMES_WARNING = ("The spaces in these column names will not be changed. "
  1078. "In pandas versions < 0.14, spaces were converted to "
  1079. "underscores.")
  1080. class SQLiteTable(SQLTable):
  1081. """
  1082. Patch the SQLTable for fallback support.
  1083. Instead of a table variable just use the Create Table statement.
  1084. """
  1085. def __init__(self, *args, **kwargs):
  1086. # GH 8341
  1087. # register an adapter callable for datetime.time object
  1088. import sqlite3
  1089. # this will transform time(12,34,56,789) into '12:34:56.000789'
  1090. # (this is what sqlalchemy does)
  1091. sqlite3.register_adapter(time, lambda _: _.strftime("%H:%M:%S.%f"))
  1092. super(SQLiteTable, self).__init__(*args, **kwargs)
  1093. def sql_schema(self):
  1094. return str(";\n".join(self.table))
  1095. def _execute_create(self):
  1096. with self.pd_sql.run_transaction() as conn:
  1097. for stmt in self.table:
  1098. conn.execute(stmt)
  1099. def insert_statement(self):
  1100. names = l

Large files files are truncated, but you can click here to view the full file