sql.py 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916
  1. """
  2. Collection of query wrappers / abstractions to both facilitate data
  3. retrieval and to reduce dependency on DB-specific API.
  4. """
  5. from __future__ import annotations
  6. from abc import (
  7. ABC,
  8. abstractmethod,
  9. )
  10. from contextlib import (
  11. ExitStack,
  12. contextmanager,
  13. )
  14. from datetime import (
  15. date,
  16. datetime,
  17. time,
  18. )
  19. from functools import partial
  20. import re
  21. from typing import (
  22. TYPE_CHECKING,
  23. Any,
  24. Callable,
  25. Literal,
  26. cast,
  27. overload,
  28. )
  29. import warnings
  30. import numpy as np
  31. from pandas._config import using_string_dtype
  32. from pandas._libs import lib
  33. from pandas.compat._optional import import_optional_dependency
  34. from pandas.errors import (
  35. AbstractMethodError,
  36. DatabaseError,
  37. )
  38. from pandas.util._exceptions import find_stack_level
  39. from pandas.util._validators import check_dtype_backend
  40. from pandas.core.dtypes.common import (
  41. is_dict_like,
  42. is_list_like,
  43. is_object_dtype,
  44. is_string_dtype,
  45. )
  46. from pandas.core.dtypes.dtypes import DatetimeTZDtype
  47. from pandas.core.dtypes.missing import isna
  48. from pandas import get_option
  49. from pandas.core.api import (
  50. DataFrame,
  51. Series,
  52. )
  53. from pandas.core.arrays import ArrowExtensionArray
  54. from pandas.core.arrays.string_ import StringDtype
  55. from pandas.core.base import PandasObject
  56. import pandas.core.common as com
  57. from pandas.core.common import maybe_make_list
  58. from pandas.core.internals.construction import convert_object_array
  59. from pandas.core.tools.datetimes import to_datetime
  60. from pandas.io._util import arrow_table_to_pandas
  61. if TYPE_CHECKING:
  62. from collections.abc import (
  63. Iterator,
  64. Mapping,
  65. )
  66. from sqlalchemy import Table
  67. from sqlalchemy.sql.expression import (
  68. Select,
  69. TextClause,
  70. )
  71. from pandas._typing import (
  72. DateTimeErrorChoices,
  73. DtypeArg,
  74. DtypeBackend,
  75. IndexLabel,
  76. Self,
  77. )
  78. from pandas import Index
  79. # -----------------------------------------------------------------------------
  80. # -- Helper functions
  81. def _process_parse_dates_argument(parse_dates):
  82. """Process parse_dates argument for read_sql functions"""
  83. # handle non-list entries for parse_dates gracefully
  84. if parse_dates is True or parse_dates is None or parse_dates is False:
  85. parse_dates = []
  86. elif not hasattr(parse_dates, "__iter__"):
  87. parse_dates = [parse_dates]
  88. return parse_dates
  89. def _handle_date_column(
  90. col, utc: bool = False, format: str | dict[str, Any] | None = None
  91. ):
  92. if isinstance(format, dict):
  93. # GH35185 Allow custom error values in parse_dates argument of
  94. # read_sql like functions.
  95. # Format can take on custom to_datetime argument values such as
  96. # {"errors": "coerce"} or {"dayfirst": True}
  97. error: DateTimeErrorChoices = format.pop("errors", None) or "ignore"
  98. if error == "ignore":
  99. try:
  100. return to_datetime(col, **format)
  101. except (TypeError, ValueError):
  102. # TODO: not reached 2023-10-27; needed?
  103. return col
  104. return to_datetime(col, errors=error, **format)
  105. else:
  106. # Allow passing of formatting string for integers
  107. # GH17855
  108. if format is None and (
  109. issubclass(col.dtype.type, np.floating)
  110. or issubclass(col.dtype.type, np.integer)
  111. ):
  112. format = "s"
  113. if format in ["D", "d", "h", "m", "s", "ms", "us", "ns"]:
  114. return to_datetime(col, errors="coerce", unit=format, utc=utc)
  115. elif isinstance(col.dtype, DatetimeTZDtype):
  116. # coerce to UTC timezone
  117. # GH11216
  118. return to_datetime(col, utc=True)
  119. else:
  120. return to_datetime(col, errors="coerce", format=format, utc=utc)
  121. def _parse_date_columns(data_frame, parse_dates):
  122. """
  123. Force non-datetime columns to be read as such.
  124. Supports both string formatted and integer timestamp columns.
  125. """
  126. parse_dates = _process_parse_dates_argument(parse_dates)
  127. # we want to coerce datetime64_tz dtypes for now to UTC
  128. # we could in theory do a 'nice' conversion from a FixedOffset tz
  129. # GH11216
  130. for i, (col_name, df_col) in enumerate(data_frame.items()):
  131. if isinstance(df_col.dtype, DatetimeTZDtype) or col_name in parse_dates:
  132. try:
  133. fmt = parse_dates[col_name]
  134. except (KeyError, TypeError):
  135. fmt = None
  136. data_frame.isetitem(i, _handle_date_column(df_col, format=fmt))
  137. return data_frame
  138. def _convert_arrays_to_dataframe(
  139. data,
  140. columns,
  141. coerce_float: bool = True,
  142. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  143. ) -> DataFrame:
  144. content = lib.to_object_array_tuples(data)
  145. arrays = convert_object_array(
  146. list(content.T),
  147. dtype=None,
  148. coerce_float=coerce_float,
  149. dtype_backend=dtype_backend,
  150. )
  151. if dtype_backend == "pyarrow":
  152. pa = import_optional_dependency("pyarrow")
  153. result_arrays = []
  154. for arr in arrays:
  155. pa_array = pa.array(arr, from_pandas=True)
  156. if arr.dtype == "string":
  157. # TODO: Arrow still infers strings arrays as regular strings instead
  158. # of large_string, which is what we preserver everywhere else for
  159. # dtype_backend="pyarrow". We may want to reconsider this
  160. pa_array = pa_array.cast(pa.string())
  161. result_arrays.append(ArrowExtensionArray(pa_array))
  162. arrays = result_arrays # type: ignore[assignment]
  163. if arrays:
  164. df = DataFrame(dict(zip(list(range(len(columns))), arrays)))
  165. df.columns = columns
  166. return df
  167. else:
  168. return DataFrame(columns=columns)
  169. def _wrap_result(
  170. data,
  171. columns,
  172. index_col=None,
  173. coerce_float: bool = True,
  174. parse_dates=None,
  175. dtype: DtypeArg | None = None,
  176. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  177. ):
  178. """Wrap result set of a SQLAlchemy query in a DataFrame."""
  179. frame = _convert_arrays_to_dataframe(data, columns, coerce_float, dtype_backend)
  180. if dtype:
  181. frame = frame.astype(dtype)
  182. frame = _parse_date_columns(frame, parse_dates)
  183. if index_col is not None:
  184. frame = frame.set_index(index_col)
  185. return frame
  186. def _wrap_result_adbc(
  187. df: DataFrame,
  188. *,
  189. index_col=None,
  190. parse_dates=None,
  191. dtype: DtypeArg | None = None,
  192. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  193. ) -> DataFrame:
  194. """Wrap result set of a SQLAlchemy query in a DataFrame."""
  195. if dtype:
  196. df = df.astype(dtype)
  197. df = _parse_date_columns(df, parse_dates)
  198. if index_col is not None:
  199. df = df.set_index(index_col)
  200. return df
  201. def execute(sql, con, params=None):
  202. """
  203. Execute the given SQL query using the provided connection object.
  204. Parameters
  205. ----------
  206. sql : string
  207. SQL query to be executed.
  208. con : SQLAlchemy connection or sqlite3 connection
  209. If a DBAPI2 object, only sqlite3 is supported.
  210. params : list or tuple, optional, default: None
  211. List of parameters to pass to execute method.
  212. Returns
  213. -------
  214. Results Iterable
  215. """
  216. warnings.warn(
  217. "`pandas.io.sql.execute` is deprecated and "
  218. "will be removed in the future version.",
  219. FutureWarning,
  220. stacklevel=find_stack_level(),
  221. ) # GH50185
  222. sqlalchemy = import_optional_dependency("sqlalchemy", errors="ignore")
  223. if sqlalchemy is not None and isinstance(con, (str, sqlalchemy.engine.Engine)):
  224. raise TypeError("pandas.io.sql.execute requires a connection") # GH50185
  225. with pandasSQL_builder(con, need_transaction=True) as pandas_sql:
  226. return pandas_sql.execute(sql, params)
  227. # -----------------------------------------------------------------------------
  228. # -- Read and write to DataFrames
  229. @overload
  230. def read_sql_table(
  231. table_name: str,
  232. con,
  233. schema=...,
  234. index_col: str | list[str] | None = ...,
  235. coerce_float=...,
  236. parse_dates: list[str] | dict[str, str] | None = ...,
  237. columns: list[str] | None = ...,
  238. chunksize: None = ...,
  239. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  240. ) -> DataFrame:
  241. ...
  242. @overload
  243. def read_sql_table(
  244. table_name: str,
  245. con,
  246. schema=...,
  247. index_col: str | list[str] | None = ...,
  248. coerce_float=...,
  249. parse_dates: list[str] | dict[str, str] | None = ...,
  250. columns: list[str] | None = ...,
  251. chunksize: int = ...,
  252. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  253. ) -> Iterator[DataFrame]:
  254. ...
  255. def read_sql_table(
  256. table_name: str,
  257. con,
  258. schema: str | None = None,
  259. index_col: str | list[str] | None = None,
  260. coerce_float: bool = True,
  261. parse_dates: list[str] | dict[str, str] | None = None,
  262. columns: list[str] | None = None,
  263. chunksize: int | None = None,
  264. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  265. ) -> DataFrame | Iterator[DataFrame]:
  266. """
  267. Read SQL database table into a DataFrame.
  268. Given a table name and a SQLAlchemy connectable, returns a DataFrame.
  269. This function does not support DBAPI connections.
  270. Parameters
  271. ----------
  272. table_name : str
  273. Name of SQL table in database.
  274. con : SQLAlchemy connectable or str
  275. A database URI could be provided as str.
  276. SQLite DBAPI connection mode not supported.
  277. schema : str, default None
  278. Name of SQL schema in database to query (if database flavor
  279. supports this). Uses default schema if None (default).
  280. index_col : str or list of str, optional, default: None
  281. Column(s) to set as index(MultiIndex).
  282. coerce_float : bool, default True
  283. Attempts to convert values of non-string, non-numeric objects (like
  284. decimal.Decimal) to floating point. Can result in loss of Precision.
  285. parse_dates : list or dict, default None
  286. - List of column names to parse as dates.
  287. - Dict of ``{column_name: format string}`` where format string is
  288. strftime compatible in case of parsing string times or is one of
  289. (D, s, ns, ms, us) in case of parsing integer timestamps.
  290. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
  291. to the keyword arguments of :func:`pandas.to_datetime`
  292. Especially useful with databases without native Datetime support,
  293. such as SQLite.
  294. columns : list, default None
  295. List of column names to select from SQL table.
  296. chunksize : int, default None
  297. If specified, returns an iterator where `chunksize` is the number of
  298. rows to include in each chunk.
  299. dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable'
  300. Back-end data type applied to the resultant :class:`DataFrame`
  301. (still experimental). Behaviour is as follows:
  302. * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
  303. (default).
  304. * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
  305. DataFrame.
  306. .. versionadded:: 2.0
  307. Returns
  308. -------
  309. DataFrame or Iterator[DataFrame]
  310. A SQL table is returned as two-dimensional data structure with labeled
  311. axes.
  312. See Also
  313. --------
  314. read_sql_query : Read SQL query into a DataFrame.
  315. read_sql : Read SQL query or database table into a DataFrame.
  316. Notes
  317. -----
  318. Any datetime values with time zone information will be converted to UTC.
  319. Examples
  320. --------
  321. >>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP
  322. """
  323. check_dtype_backend(dtype_backend)
  324. if dtype_backend is lib.no_default:
  325. dtype_backend = "numpy" # type: ignore[assignment]
  326. assert dtype_backend is not lib.no_default
  327. with pandasSQL_builder(con, schema=schema, need_transaction=True) as pandas_sql:
  328. if not pandas_sql.has_table(table_name):
  329. raise ValueError(f"Table {table_name} not found")
  330. table = pandas_sql.read_table(
  331. table_name,
  332. index_col=index_col,
  333. coerce_float=coerce_float,
  334. parse_dates=parse_dates,
  335. columns=columns,
  336. chunksize=chunksize,
  337. dtype_backend=dtype_backend,
  338. )
  339. if table is not None:
  340. return table
  341. else:
  342. raise ValueError(f"Table {table_name} not found", con)
  343. @overload
  344. def read_sql_query(
  345. sql,
  346. con,
  347. index_col: str | list[str] | None = ...,
  348. coerce_float=...,
  349. params: list[Any] | Mapping[str, Any] | None = ...,
  350. parse_dates: list[str] | dict[str, str] | None = ...,
  351. chunksize: None = ...,
  352. dtype: DtypeArg | None = ...,
  353. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  354. ) -> DataFrame:
  355. ...
  356. @overload
  357. def read_sql_query(
  358. sql,
  359. con,
  360. index_col: str | list[str] | None = ...,
  361. coerce_float=...,
  362. params: list[Any] | Mapping[str, Any] | None = ...,
  363. parse_dates: list[str] | dict[str, str] | None = ...,
  364. chunksize: int = ...,
  365. dtype: DtypeArg | None = ...,
  366. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  367. ) -> Iterator[DataFrame]:
  368. ...
  369. def read_sql_query(
  370. sql,
  371. con,
  372. index_col: str | list[str] | None = None,
  373. coerce_float: bool = True,
  374. params: list[Any] | Mapping[str, Any] | None = None,
  375. parse_dates: list[str] | dict[str, str] | None = None,
  376. chunksize: int | None = None,
  377. dtype: DtypeArg | None = None,
  378. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  379. ) -> DataFrame | Iterator[DataFrame]:
  380. """
  381. Read SQL query into a DataFrame.
  382. Returns a DataFrame corresponding to the result set of the query
  383. string. Optionally provide an `index_col` parameter to use one of the
  384. columns as the index, otherwise default integer index will be used.
  385. Parameters
  386. ----------
  387. sql : str SQL query or SQLAlchemy Selectable (select or text object)
  388. SQL query to be executed.
  389. con : SQLAlchemy connectable, str, or sqlite3 connection
  390. Using SQLAlchemy makes it possible to use any DB supported by that
  391. library. If a DBAPI2 object, only sqlite3 is supported.
  392. index_col : str or list of str, optional, default: None
  393. Column(s) to set as index(MultiIndex).
  394. coerce_float : bool, default True
  395. Attempts to convert values of non-string, non-numeric objects (like
  396. decimal.Decimal) to floating point. Useful for SQL result sets.
  397. params : list, tuple or mapping, optional, default: None
  398. List of parameters to pass to execute method. The syntax used
  399. to pass parameters is database driver dependent. Check your
  400. database driver documentation for which of the five syntax styles,
  401. described in PEP 249's paramstyle, is supported.
  402. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}.
  403. parse_dates : list or dict, default: None
  404. - List of column names to parse as dates.
  405. - Dict of ``{column_name: format string}`` where format string is
  406. strftime compatible in case of parsing string times, or is one of
  407. (D, s, ns, ms, us) in case of parsing integer timestamps.
  408. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
  409. to the keyword arguments of :func:`pandas.to_datetime`
  410. Especially useful with databases without native Datetime support,
  411. such as SQLite.
  412. chunksize : int, default None
  413. If specified, return an iterator where `chunksize` is the number of
  414. rows to include in each chunk.
  415. dtype : Type name or dict of columns
  416. Data type for data or columns. E.g. np.float64 or
  417. {'a': np.float64, 'b': np.int32, 'c': 'Int64'}.
  418. .. versionadded:: 1.3.0
  419. dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable'
  420. Back-end data type applied to the resultant :class:`DataFrame`
  421. (still experimental). Behaviour is as follows:
  422. * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
  423. (default).
  424. * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
  425. DataFrame.
  426. .. versionadded:: 2.0
  427. Returns
  428. -------
  429. DataFrame or Iterator[DataFrame]
  430. See Also
  431. --------
  432. read_sql_table : Read SQL database table into a DataFrame.
  433. read_sql : Read SQL query or database table into a DataFrame.
  434. Notes
  435. -----
  436. Any datetime values with time zone information parsed via the `parse_dates`
  437. parameter will be converted to UTC.
  438. Examples
  439. --------
  440. >>> from sqlalchemy import create_engine # doctest: +SKIP
  441. >>> engine = create_engine("sqlite:///database.db") # doctest: +SKIP
  442. >>> with engine.connect() as conn, conn.begin(): # doctest: +SKIP
  443. ... data = pd.read_sql_table("data", conn) # doctest: +SKIP
  444. """
  445. check_dtype_backend(dtype_backend)
  446. if dtype_backend is lib.no_default:
  447. dtype_backend = "numpy" # type: ignore[assignment]
  448. assert dtype_backend is not lib.no_default
  449. with pandasSQL_builder(con) as pandas_sql:
  450. return pandas_sql.read_query(
  451. sql,
  452. index_col=index_col,
  453. params=params,
  454. coerce_float=coerce_float,
  455. parse_dates=parse_dates,
  456. chunksize=chunksize,
  457. dtype=dtype,
  458. dtype_backend=dtype_backend,
  459. )
  460. @overload
  461. def read_sql(
  462. sql,
  463. con,
  464. index_col: str | list[str] | None = ...,
  465. coerce_float=...,
  466. params=...,
  467. parse_dates=...,
  468. columns: list[str] = ...,
  469. chunksize: None = ...,
  470. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  471. dtype: DtypeArg | None = None,
  472. ) -> DataFrame:
  473. ...
  474. @overload
  475. def read_sql(
  476. sql,
  477. con,
  478. index_col: str | list[str] | None = ...,
  479. coerce_float=...,
  480. params=...,
  481. parse_dates=...,
  482. columns: list[str] = ...,
  483. chunksize: int = ...,
  484. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  485. dtype: DtypeArg | None = None,
  486. ) -> Iterator[DataFrame]:
  487. ...
  488. def read_sql(
  489. sql,
  490. con,
  491. index_col: str | list[str] | None = None,
  492. coerce_float: bool = True,
  493. params=None,
  494. parse_dates=None,
  495. columns: list[str] | None = None,
  496. chunksize: int | None = None,
  497. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  498. dtype: DtypeArg | None = None,
  499. ) -> DataFrame | Iterator[DataFrame]:
  500. """
  501. Read SQL query or database table into a DataFrame.
  502. This function is a convenience wrapper around ``read_sql_table`` and
  503. ``read_sql_query`` (for backward compatibility). It will delegate
  504. to the specific function depending on the provided input. A SQL query
  505. will be routed to ``read_sql_query``, while a database table name will
  506. be routed to ``read_sql_table``. Note that the delegated function might
  507. have more specific notes about their functionality not listed here.
  508. Parameters
  509. ----------
  510. sql : str or SQLAlchemy Selectable (select or text object)
  511. SQL query to be executed or a table name.
  512. con : ADBC Connection, SQLAlchemy connectable, str, or sqlite3 connection
  513. ADBC provides high performance I/O with native type support, where available.
  514. Using SQLAlchemy makes it possible to use any DB supported by that
  515. library. If a DBAPI2 object, only sqlite3 is supported. The user is responsible
  516. for engine disposal and connection closure for the ADBC connection and
  517. SQLAlchemy connectable; str connections are closed automatically. See
  518. `here <https://docs.sqlalchemy.org/en/20/core/connections.html>`_.
  519. index_col : str or list of str, optional, default: None
  520. Column(s) to set as index(MultiIndex).
  521. coerce_float : bool, default True
  522. Attempts to convert values of non-string, non-numeric objects (like
  523. decimal.Decimal) to floating point, useful for SQL result sets.
  524. params : list, tuple or dict, optional, default: None
  525. List of parameters to pass to execute method. The syntax used
  526. to pass parameters is database driver dependent. Check your
  527. database driver documentation for which of the five syntax styles,
  528. described in PEP 249's paramstyle, is supported.
  529. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}.
  530. parse_dates : list or dict, default: None
  531. - List of column names to parse as dates.
  532. - Dict of ``{column_name: format string}`` where format string is
  533. strftime compatible in case of parsing string times, or is one of
  534. (D, s, ns, ms, us) in case of parsing integer timestamps.
  535. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
  536. to the keyword arguments of :func:`pandas.to_datetime`
  537. Especially useful with databases without native Datetime support,
  538. such as SQLite.
  539. columns : list, default: None
  540. List of column names to select from SQL table (only used when reading
  541. a table).
  542. chunksize : int, default None
  543. If specified, return an iterator where `chunksize` is the
  544. number of rows to include in each chunk.
  545. dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable'
  546. Back-end data type applied to the resultant :class:`DataFrame`
  547. (still experimental). Behaviour is as follows:
  548. * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
  549. (default).
  550. * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
  551. DataFrame.
  552. .. versionadded:: 2.0
  553. dtype : Type name or dict of columns
  554. Data type for data or columns. E.g. np.float64 or
  555. {'a': np.float64, 'b': np.int32, 'c': 'Int64'}.
  556. The argument is ignored if a table is passed instead of a query.
  557. .. versionadded:: 2.0.0
  558. Returns
  559. -------
  560. DataFrame or Iterator[DataFrame]
  561. See Also
  562. --------
  563. read_sql_table : Read SQL database table into a DataFrame.
  564. read_sql_query : Read SQL query into a DataFrame.
  565. Examples
  566. --------
  567. Read data from SQL via either a SQL query or a SQL tablename.
  568. When using a SQLite database only SQL queries are accepted,
  569. providing only the SQL tablename will result in an error.
  570. >>> from sqlite3 import connect
  571. >>> conn = connect(':memory:')
  572. >>> df = pd.DataFrame(data=[[0, '10/11/12'], [1, '12/11/10']],
  573. ... columns=['int_column', 'date_column'])
  574. >>> df.to_sql(name='test_data', con=conn)
  575. 2
  576. >>> pd.read_sql('SELECT int_column, date_column FROM test_data', conn)
  577. int_column date_column
  578. 0 0 10/11/12
  579. 1 1 12/11/10
  580. >>> pd.read_sql('test_data', 'postgres:///db_name') # doctest:+SKIP
  581. Apply date parsing to columns through the ``parse_dates`` argument
  582. The ``parse_dates`` argument calls ``pd.to_datetime`` on the provided columns.
  583. Custom argument values for applying ``pd.to_datetime`` on a column are specified
  584. via a dictionary format:
  585. >>> pd.read_sql('SELECT int_column, date_column FROM test_data',
  586. ... conn,
  587. ... parse_dates={"date_column": {"format": "%d/%m/%y"}})
  588. int_column date_column
  589. 0 0 2012-11-10
  590. 1 1 2010-11-12
  591. .. versionadded:: 2.2.0
  592. pandas now supports reading via ADBC drivers
  593. >>> from adbc_driver_postgresql import dbapi # doctest:+SKIP
  594. >>> with dbapi.connect('postgres:///db_name') as conn: # doctest:+SKIP
  595. ... pd.read_sql('SELECT int_column FROM test_data', conn)
  596. int_column
  597. 0 0
  598. 1 1
  599. """
  600. check_dtype_backend(dtype_backend)
  601. if dtype_backend is lib.no_default:
  602. dtype_backend = "numpy" # type: ignore[assignment]
  603. assert dtype_backend is not lib.no_default
  604. with pandasSQL_builder(con) as pandas_sql:
  605. if isinstance(pandas_sql, SQLiteDatabase):
  606. return pandas_sql.read_query(
  607. sql,
  608. index_col=index_col,
  609. params=params,
  610. coerce_float=coerce_float,
  611. parse_dates=parse_dates,
  612. chunksize=chunksize,
  613. dtype_backend=dtype_backend,
  614. dtype=dtype,
  615. )
  616. try:
  617. _is_table_name = pandas_sql.has_table(sql)
  618. except Exception:
  619. # using generic exception to catch errors from sql drivers (GH24988)
  620. _is_table_name = False
  621. if _is_table_name:
  622. return pandas_sql.read_table(
  623. sql,
  624. index_col=index_col,
  625. coerce_float=coerce_float,
  626. parse_dates=parse_dates,
  627. columns=columns,
  628. chunksize=chunksize,
  629. dtype_backend=dtype_backend,
  630. )
  631. else:
  632. return pandas_sql.read_query(
  633. sql,
  634. index_col=index_col,
  635. params=params,
  636. coerce_float=coerce_float,
  637. parse_dates=parse_dates,
  638. chunksize=chunksize,
  639. dtype_backend=dtype_backend,
  640. dtype=dtype,
  641. )
  642. def to_sql(
  643. frame,
  644. name: str,
  645. con,
  646. schema: str | None = None,
  647. if_exists: Literal["fail", "replace", "append"] = "fail",
  648. index: bool = True,
  649. index_label: IndexLabel | None = None,
  650. chunksize: int | None = None,
  651. dtype: DtypeArg | None = None,
  652. method: Literal["multi"] | Callable | None = None,
  653. engine: str = "auto",
  654. **engine_kwargs,
  655. ) -> int | None:
  656. """
  657. Write records stored in a DataFrame to a SQL database.
  658. Parameters
  659. ----------
  660. frame : DataFrame, Series
  661. name : str
  662. Name of SQL table.
  663. con : ADBC Connection, SQLAlchemy connectable, str, or sqlite3 connection
  664. or sqlite3 DBAPI2 connection
  665. ADBC provides high performance I/O with native type support, where available.
  666. Using SQLAlchemy makes it possible to use any DB supported by that
  667. library.
  668. If a DBAPI2 object, only sqlite3 is supported.
  669. schema : str, optional
  670. Name of SQL schema in database to write to (if database flavor
  671. supports this). If None, use default schema (default).
  672. if_exists : {'fail', 'replace', 'append'}, default 'fail'
  673. - fail: If table exists, do nothing.
  674. - replace: If table exists, drop it, recreate it, and insert data.
  675. - append: If table exists, insert data. Create if does not exist.
  676. index : bool, default True
  677. Write DataFrame index as a column.
  678. index_label : str or sequence, optional
  679. Column label for index column(s). If None is given (default) and
  680. `index` is True, then the index names are used.
  681. A sequence should be given if the DataFrame uses MultiIndex.
  682. chunksize : int, optional
  683. Specify the number of rows in each batch to be written at a time.
  684. By default, all rows will be written at once.
  685. dtype : dict or scalar, optional
  686. Specifying the datatype for columns. If a dictionary is used, the
  687. keys should be the column names and the values should be the
  688. SQLAlchemy types or strings for the sqlite3 fallback mode. If a
  689. scalar is provided, it will be applied to all columns.
  690. method : {None, 'multi', callable}, optional
  691. Controls the SQL insertion clause used:
  692. - None : Uses standard SQL ``INSERT`` clause (one per row).
  693. - ``'multi'``: Pass multiple values in a single ``INSERT`` clause.
  694. - callable with signature ``(pd_table, conn, keys, data_iter) -> int | None``.
  695. Details and a sample callable implementation can be found in the
  696. section :ref:`insert method <io.sql.method>`.
  697. engine : {'auto', 'sqlalchemy'}, default 'auto'
  698. SQL engine library to use. If 'auto', then the option
  699. ``io.sql.engine`` is used. The default ``io.sql.engine``
  700. behavior is 'sqlalchemy'
  701. .. versionadded:: 1.3.0
  702. **engine_kwargs
  703. Any additional kwargs are passed to the engine.
  704. Returns
  705. -------
  706. None or int
  707. Number of rows affected by to_sql. None is returned if the callable
  708. passed into ``method`` does not return an integer number of rows.
  709. .. versionadded:: 1.4.0
  710. Notes
  711. -----
  712. The returned rows affected is the sum of the ``rowcount`` attribute of ``sqlite3.Cursor``
  713. or SQLAlchemy connectable. If using ADBC the returned rows are the result
  714. of ``Cursor.adbc_ingest``. The returned value may not reflect the exact number of written
  715. rows as stipulated in the
  716. `sqlite3 <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.rowcount>`__ or
  717. `SQLAlchemy <https://docs.sqlalchemy.org/en/14/core/connections.html#sqlalchemy.engine.BaseCursorResult.rowcount>`__
  718. """ # noqa: E501
  719. if if_exists not in ("fail", "replace", "append"):
  720. raise ValueError(f"'{if_exists}' is not valid for if_exists")
  721. if isinstance(frame, Series):
  722. frame = frame.to_frame()
  723. elif not isinstance(frame, DataFrame):
  724. raise NotImplementedError(
  725. "'frame' argument should be either a Series or a DataFrame"
  726. )
  727. with pandasSQL_builder(con, schema=schema, need_transaction=True) as pandas_sql:
  728. return pandas_sql.to_sql(
  729. frame,
  730. name,
  731. if_exists=if_exists,
  732. index=index,
  733. index_label=index_label,
  734. schema=schema,
  735. chunksize=chunksize,
  736. dtype=dtype,
  737. method=method,
  738. engine=engine,
  739. **engine_kwargs,
  740. )
  741. def has_table(table_name: str, con, schema: str | None = None) -> bool:
  742. """
  743. Check if DataBase has named table.
  744. Parameters
  745. ----------
  746. table_name: string
  747. Name of SQL table.
  748. con: ADBC Connection, SQLAlchemy connectable, str, or sqlite3 connection
  749. ADBC provides high performance I/O with native type support, where available.
  750. Using SQLAlchemy makes it possible to use any DB supported by that
  751. library.
  752. If a DBAPI2 object, only sqlite3 is supported.
  753. schema : string, default None
  754. Name of SQL schema in database to write to (if database flavor supports
  755. this). If None, use default schema (default).
  756. Returns
  757. -------
  758. boolean
  759. """
  760. with pandasSQL_builder(con, schema=schema) as pandas_sql:
  761. return pandas_sql.has_table(table_name)
  762. table_exists = has_table
  763. def pandasSQL_builder(
  764. con,
  765. schema: str | None = None,
  766. need_transaction: bool = False,
  767. ) -> PandasSQL:
  768. """
  769. Convenience function to return the correct PandasSQL subclass based on the
  770. provided parameters. Also creates a sqlalchemy connection and transaction
  771. if necessary.
  772. """
  773. import sqlite3
  774. if isinstance(con, sqlite3.Connection) or con is None:
  775. return SQLiteDatabase(con)
  776. sqlalchemy = import_optional_dependency("sqlalchemy", errors="ignore")
  777. if isinstance(con, str) and sqlalchemy is None:
  778. raise ImportError("Using URI string without sqlalchemy installed.")
  779. if sqlalchemy is not None and isinstance(con, (str, sqlalchemy.engine.Connectable)):
  780. return SQLDatabase(con, schema, need_transaction)
  781. adbc = import_optional_dependency("adbc_driver_manager.dbapi", errors="ignore")
  782. if adbc and isinstance(con, adbc.Connection):
  783. return ADBCDatabase(con)
  784. warnings.warn(
  785. "pandas only supports SQLAlchemy connectable (engine/connection) or "
  786. "database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 "
  787. "objects are not tested. Please consider using SQLAlchemy.",
  788. UserWarning,
  789. stacklevel=find_stack_level(),
  790. )
  791. return SQLiteDatabase(con)
  792. class SQLTable(PandasObject):
  793. """
  794. For mapping Pandas tables to SQL tables.
  795. Uses fact that table is reflected by SQLAlchemy to
  796. do better type conversions.
  797. Also holds various flags needed to avoid having to
  798. pass them between functions all the time.
  799. """
  800. # TODO: support for multiIndex
  801. def __init__(
  802. self,
  803. name: str,
  804. pandas_sql_engine,
  805. frame=None,
  806. index: bool | str | list[str] | None = True,
  807. if_exists: Literal["fail", "replace", "append"] = "fail",
  808. prefix: str = "pandas",
  809. index_label=None,
  810. schema=None,
  811. keys=None,
  812. dtype: DtypeArg | None = None,
  813. ) -> None:
  814. self.name = name
  815. self.pd_sql = pandas_sql_engine
  816. self.prefix = prefix
  817. self.frame = frame
  818. self.index = self._index_name(index, index_label)
  819. self.schema = schema
  820. self.if_exists = if_exists
  821. self.keys = keys
  822. self.dtype = dtype
  823. if frame is not None:
  824. # We want to initialize based on a dataframe
  825. self.table = self._create_table_setup()
  826. else:
  827. # no data provided, read-only mode
  828. self.table = self.pd_sql.get_table(self.name, self.schema)
  829. if self.table is None:
  830. raise ValueError(f"Could not init table '{name}'")
  831. if not len(self.name):
  832. raise ValueError("Empty table name specified")
  833. def exists(self):
  834. return self.pd_sql.has_table(self.name, self.schema)
  835. def sql_schema(self) -> str:
  836. from sqlalchemy.schema import CreateTable
  837. return str(CreateTable(self.table).compile(self.pd_sql.con))
  838. def _execute_create(self) -> None:
  839. # Inserting table into database, add to MetaData object
  840. self.table = self.table.to_metadata(self.pd_sql.meta)
  841. with self.pd_sql.run_transaction():
  842. self.table.create(bind=self.pd_sql.con)
  843. def create(self) -> None:
  844. if self.exists():
  845. if self.if_exists == "fail":
  846. raise ValueError(f"Table '{self.name}' already exists.")
  847. if self.if_exists == "replace":
  848. self.pd_sql.drop_table(self.name, self.schema)
  849. self._execute_create()
  850. elif self.if_exists == "append":
  851. pass
  852. else:
  853. raise ValueError(f"'{self.if_exists}' is not valid for if_exists")
  854. else:
  855. self._execute_create()
  856. def _execute_insert(self, conn, keys: list[str], data_iter) -> int:
  857. """
  858. Execute SQL statement inserting data
  859. Parameters
  860. ----------
  861. conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
  862. keys : list of str
  863. Column names
  864. data_iter : generator of list
  865. Each item contains a list of values to be inserted
  866. """
  867. data = [dict(zip(keys, row)) for row in data_iter]
  868. result = conn.execute(self.table.insert(), data)
  869. return result.rowcount
  870. def _execute_insert_multi(self, conn, keys: list[str], data_iter) -> int:
  871. """
  872. Alternative to _execute_insert for DBs support multi-value INSERT.
  873. Note: multi-value insert is usually faster for analytics DBs
  874. and tables containing a few columns
  875. but performance degrades quickly with increase of columns.
  876. """
  877. from sqlalchemy import insert
  878. data = [dict(zip(keys, row)) for row in data_iter]
  879. stmt = insert(self.table).values(data)
  880. result = conn.execute(stmt)
  881. return result.rowcount
  882. def insert_data(self) -> tuple[list[str], list[np.ndarray]]:
  883. if self.index is not None:
  884. temp = self.frame.copy()
  885. temp.index.names = self.index
  886. try:
  887. temp.reset_index(inplace=True)
  888. except ValueError as err:
  889. raise ValueError(f"duplicate name in index/columns: {err}") from err
  890. else:
  891. temp = self.frame
  892. column_names = list(map(str, temp.columns))
  893. ncols = len(column_names)
  894. # this just pre-allocates the list: None's will be replaced with ndarrays
  895. # error: List item 0 has incompatible type "None"; expected "ndarray"
  896. data_list: list[np.ndarray] = [None] * ncols # type: ignore[list-item]
  897. for i, (_, ser) in enumerate(temp.items()):
  898. if ser.dtype.kind == "M":
  899. if isinstance(ser._values, ArrowExtensionArray):
  900. import pyarrow as pa
  901. if pa.types.is_date(ser.dtype.pyarrow_dtype):
  902. # GH#53854 to_pydatetime not supported for pyarrow date dtypes
  903. d = ser._values.to_numpy(dtype=object)
  904. else:
  905. with warnings.catch_warnings():
  906. warnings.filterwarnings("ignore", category=FutureWarning)
  907. # GH#52459 to_pydatetime will return Index[object]
  908. d = np.asarray(ser.dt.to_pydatetime(), dtype=object)
  909. else:
  910. d = ser._values.to_pydatetime()
  911. elif ser.dtype.kind == "m":
  912. vals = ser._values
  913. if isinstance(vals, ArrowExtensionArray):
  914. vals = vals.to_numpy(dtype=np.dtype("m8[ns]"))
  915. # store as integers, see GH#6921, GH#7076
  916. d = vals.view("i8").astype(object)
  917. else:
  918. d = ser._values.astype(object)
  919. assert isinstance(d, np.ndarray), type(d)
  920. if ser._can_hold_na:
  921. # Note: this will miss timedeltas since they are converted to int
  922. mask = isna(d)
  923. d[mask] = None
  924. data_list[i] = d
  925. return column_names, data_list
  926. def insert(
  927. self,
  928. chunksize: int | None = None,
  929. method: Literal["multi"] | Callable | None = None,
  930. ) -> int | None:
  931. # set insert method
  932. if method is None:
  933. exec_insert = self._execute_insert
  934. elif method == "multi":
  935. exec_insert = self._execute_insert_multi
  936. elif callable(method):
  937. exec_insert = partial(method, self)
  938. else:
  939. raise ValueError(f"Invalid parameter `method`: {method}")
  940. keys, data_list = self.insert_data()
  941. nrows = len(self.frame)
  942. if nrows == 0:
  943. return 0
  944. if chunksize is None:
  945. chunksize = nrows
  946. elif chunksize == 0:
  947. raise ValueError("chunksize argument should be non-zero")
  948. chunks = (nrows // chunksize) + 1
  949. total_inserted = None
  950. with self.pd_sql.run_transaction() as conn:
  951. for i in range(chunks):
  952. start_i = i * chunksize
  953. end_i = min((i + 1) * chunksize, nrows)
  954. if start_i >= end_i:
  955. break
  956. chunk_iter = zip(*(arr[start_i:end_i] for arr in data_list))
  957. num_inserted = exec_insert(conn, keys, chunk_iter)
  958. # GH 46891
  959. if num_inserted is not None:
  960. if total_inserted is None:
  961. total_inserted = num_inserted
  962. else:
  963. total_inserted += num_inserted
  964. return total_inserted
  965. def _query_iterator(
  966. self,
  967. result,
  968. exit_stack: ExitStack,
  969. chunksize: int | None,
  970. columns,
  971. coerce_float: bool = True,
  972. parse_dates=None,
  973. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  974. ):
  975. """Return generator through chunked result set."""
  976. has_read_data = False
  977. with exit_stack:
  978. while True:
  979. data = result.fetchmany(chunksize)
  980. if not data:
  981. if not has_read_data:
  982. yield DataFrame.from_records(
  983. [], columns=columns, coerce_float=coerce_float
  984. )
  985. break
  986. has_read_data = True
  987. self.frame = _convert_arrays_to_dataframe(
  988. data, columns, coerce_float, dtype_backend
  989. )
  990. self._harmonize_columns(
  991. parse_dates=parse_dates, dtype_backend=dtype_backend
  992. )
  993. if self.index is not None:
  994. self.frame.set_index(self.index, inplace=True)
  995. yield self.frame
  996. def read(
  997. self,
  998. exit_stack: ExitStack,
  999. coerce_float: bool = True,
  1000. parse_dates=None,
  1001. columns=None,
  1002. chunksize: int | None = None,
  1003. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  1004. ) -> DataFrame | Iterator[DataFrame]:
  1005. from sqlalchemy import select
  1006. if columns is not None and len(columns) > 0:
  1007. cols = [self.table.c[n] for n in columns]
  1008. if self.index is not None:
  1009. for idx in self.index[::-1]:
  1010. cols.insert(0, self.table.c[idx])
  1011. sql_select = select(*cols)
  1012. else:
  1013. sql_select = select(self.table)
  1014. result = self.pd_sql.execute(sql_select)
  1015. column_names = result.keys()
  1016. if chunksize is not None:
  1017. return self._query_iterator(
  1018. result,
  1019. exit_stack,
  1020. chunksize,
  1021. column_names,
  1022. coerce_float=coerce_float,
  1023. parse_dates=parse_dates,
  1024. dtype_backend=dtype_backend,
  1025. )
  1026. else:
  1027. data = result.fetchall()
  1028. self.frame = _convert_arrays_to_dataframe(
  1029. data, column_names, coerce_float, dtype_backend
  1030. )
  1031. self._harmonize_columns(
  1032. parse_dates=parse_dates, dtype_backend=dtype_backend
  1033. )
  1034. if self.index is not None:
  1035. self.frame.set_index(self.index, inplace=True)
  1036. return self.frame
  1037. def _index_name(self, index, index_label):
  1038. # for writing: index=True to include index in sql table
  1039. if index is True:
  1040. nlevels = self.frame.index.nlevels
  1041. # if index_label is specified, set this as index name(s)
  1042. if index_label is not None:
  1043. if not isinstance(index_label, list):
  1044. index_label = [index_label]
  1045. if len(index_label) != nlevels:
  1046. raise ValueError(
  1047. "Length of 'index_label' should match number of "
  1048. f"levels, which is {nlevels}"
  1049. )
  1050. return index_label
  1051. # return the used column labels for the index columns
  1052. if (
  1053. nlevels == 1
  1054. and "index" not in self.frame.columns
  1055. and self.frame.index.name is None
  1056. ):
  1057. return ["index"]
  1058. else:
  1059. return com.fill_missing_names(self.frame.index.names)
  1060. # for reading: index=(list of) string to specify column to set as index
  1061. elif isinstance(index, str):
  1062. return [index]
  1063. elif isinstance(index, list):
  1064. return index
  1065. else:
  1066. return None
  1067. def _get_column_names_and_types(self, dtype_mapper):
  1068. column_names_and_types = []
  1069. if self.index is not None:
  1070. for i, idx_label in enumerate(self.index):
  1071. idx_type = dtype_mapper(self.frame.index._get_level_values(i))
  1072. column_names_and_types.append((str(idx_label), idx_type, True))
  1073. column_names_and_types += [
  1074. (str(self.frame.columns[i]), dtype_mapper(self.frame.iloc[:, i]), False)
  1075. for i in range(len(self.frame.columns))
  1076. ]
  1077. return column_names_and_types
  1078. def _create_table_setup(self):
  1079. from sqlalchemy import (
  1080. Column,
  1081. PrimaryKeyConstraint,
  1082. Table,
  1083. )
  1084. from sqlalchemy.schema import MetaData
  1085. column_names_and_types = self._get_column_names_and_types(self._sqlalchemy_type)
  1086. columns: list[Any] = [
  1087. Column(name, typ, index=is_index)
  1088. for name, typ, is_index in column_names_and_types
  1089. ]
  1090. if self.keys is not None:
  1091. if not is_list_like(self.keys):
  1092. keys = [self.keys]
  1093. else:
  1094. keys = self.keys
  1095. pkc = PrimaryKeyConstraint(*keys, name=self.name + "_pk")
  1096. columns.append(pkc)
  1097. schema = self.schema or self.pd_sql.meta.schema
  1098. # At this point, attach to new metadata, only attach to self.meta
  1099. # once table is created.
  1100. meta = MetaData()
  1101. return Table(self.name, meta, *columns, schema=schema)
  1102. def _harmonize_columns(
  1103. self,
  1104. parse_dates=None,
  1105. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  1106. ) -> None:
  1107. """
  1108. Make the DataFrame's column types align with the SQL table
  1109. column types.
  1110. Need to work around limited NA value support. Floats are always
  1111. fine, ints must always be floats if there are Null values.
  1112. Booleans are hard because converting bool column with None replaces
  1113. all Nones with false. Therefore only convert bool if there are no
  1114. NA values.
  1115. Datetimes should already be converted to np.datetime64 if supported,
  1116. but here we also force conversion if required.
  1117. """
  1118. parse_dates = _process_parse_dates_argument(parse_dates)
  1119. for sql_col in self.table.columns:
  1120. col_name = sql_col.name
  1121. try:
  1122. df_col = self.frame[col_name]
  1123. # Handle date parsing upfront; don't try to convert columns
  1124. # twice
  1125. if col_name in parse_dates:
  1126. try:
  1127. fmt = parse_dates[col_name]
  1128. except TypeError:
  1129. fmt = None
  1130. self.frame[col_name] = _handle_date_column(df_col, format=fmt)
  1131. continue
  1132. # the type the dataframe column should have
  1133. col_type = self._get_dtype(sql_col.type)
  1134. if (
  1135. col_type is datetime
  1136. or col_type is date
  1137. or col_type is DatetimeTZDtype
  1138. ):
  1139. # Convert tz-aware Datetime SQL columns to UTC
  1140. utc = col_type is DatetimeTZDtype
  1141. self.frame[col_name] = _handle_date_column(df_col, utc=utc)
  1142. elif dtype_backend == "numpy" and col_type is float:
  1143. # floats support NA, can always convert!
  1144. self.frame[col_name] = df_col.astype(col_type, copy=False)
  1145. elif (
  1146. using_string_dtype()
  1147. and is_string_dtype(col_type)
  1148. and is_object_dtype(self.frame[col_name])
  1149. ):
  1150. self.frame[col_name] = df_col.astype(col_type, copy=False)
  1151. elif dtype_backend == "numpy" and len(df_col) == df_col.count():
  1152. # No NA values, can convert ints and bools
  1153. if col_type is np.dtype("int64") or col_type is bool:
  1154. self.frame[col_name] = df_col.astype(col_type, copy=False)
  1155. except KeyError:
  1156. pass # this column not in results
  1157. def _sqlalchemy_type(self, col: Index | Series):
  1158. dtype: DtypeArg = self.dtype or {}
  1159. if is_dict_like(dtype):
  1160. dtype = cast(dict, dtype)
  1161. if col.name in dtype:
  1162. return dtype[col.name]
  1163. # Infer type of column, while ignoring missing values.
  1164. # Needed for inserting typed data containing NULLs, GH 8778.
  1165. col_type = lib.infer_dtype(col, skipna=True)
  1166. from sqlalchemy.types import (
  1167. TIMESTAMP,
  1168. BigInteger,
  1169. Boolean,
  1170. Date,
  1171. DateTime,
  1172. Float,
  1173. Integer,
  1174. SmallInteger,
  1175. Text,
  1176. Time,
  1177. )
  1178. if col_type in ("datetime64", "datetime"):
  1179. # GH 9086: TIMESTAMP is the suggested type if the column contains
  1180. # timezone information
  1181. try:
  1182. # error: Item "Index" of "Union[Index, Series]" has no attribute "dt"
  1183. if col.dt.tz is not None: # type: ignore[union-attr]
  1184. return TIMESTAMP(timezone=True)
  1185. except AttributeError:
  1186. # The column is actually a DatetimeIndex
  1187. # GH 26761 or an Index with date-like data e.g. 9999-01-01
  1188. if getattr(col, "tz", None) is not None:
  1189. return TIMESTAMP(timezone=True)
  1190. return DateTime
  1191. if col_type == "timedelta64":
  1192. warnings.warn(
  1193. "the 'timedelta' type is not supported, and will be "
  1194. "written as integer values (ns frequency) to the database.",
  1195. UserWarning,
  1196. stacklevel=find_stack_level(),
  1197. )
  1198. return BigInteger
  1199. elif col_type == "floating":
  1200. if col.dtype == "float32":
  1201. return Float(precision=23)
  1202. else:
  1203. return Float(precision=53)
  1204. elif col_type == "integer":
  1205. # GH35076 Map pandas integer to optimal SQLAlchemy integer type
  1206. if col.dtype.name.lower() in ("int8", "uint8", "int16"):
  1207. return SmallInteger
  1208. elif col.dtype.name.lower() in ("uint16", "int32"):
  1209. return Integer
  1210. elif col.dtype.name.lower() == "uint64":
  1211. raise ValueError("Unsigned 64 bit integer datatype is not supported")
  1212. else:
  1213. return BigInteger
  1214. elif col_type == "boolean":
  1215. return Boolean
  1216. elif col_type == "date":
  1217. return Date
  1218. elif col_type == "time":
  1219. return Time
  1220. elif col_type == "complex":
  1221. raise ValueError("Complex datatypes not supported")
  1222. return Text
  1223. def _get_dtype(self, sqltype):
  1224. from sqlalchemy.types import (
  1225. TIMESTAMP,
  1226. Boolean,
  1227. Date,
  1228. DateTime,
  1229. Float,
  1230. Integer,
  1231. String,
  1232. )
  1233. if isinstance(sqltype, Float):
  1234. return float
  1235. elif isinstance(sqltype, Integer):
  1236. # TODO: Refine integer size.
  1237. return np.dtype("int64")
  1238. elif isinstance(sqltype, TIMESTAMP):
  1239. # we have a timezone capable type
  1240. if not sqltype.timezone:
  1241. return datetime
  1242. return DatetimeTZDtype
  1243. elif isinstance(sqltype, DateTime):
  1244. # Caution: np.datetime64 is also a subclass of np.number.
  1245. return datetime
  1246. elif isinstance(sqltype, Date):
  1247. return date
  1248. elif isinstance(sqltype, Boolean):
  1249. return bool
  1250. elif isinstance(sqltype, String):
  1251. if using_string_dtype():
  1252. return StringDtype(na_value=np.nan)
  1253. return object
  1254. class PandasSQL(PandasObject, ABC):
  1255. """
  1256. Subclasses Should define read_query and to_sql.
  1257. """
  1258. def __enter__(self) -> Self:
  1259. return self
  1260. def __exit__(self, *args) -> None:
  1261. pass
  1262. def read_table(
  1263. self,
  1264. table_name: str,
  1265. index_col: str | list[str] | None = None,
  1266. coerce_float: bool = True,
  1267. parse_dates=None,
  1268. columns=None,
  1269. schema: str | None = None,
  1270. chunksize: int | None = None,
  1271. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  1272. ) -> DataFrame | Iterator[DataFrame]:
  1273. raise NotImplementedError
  1274. @abstractmethod
  1275. def read_query(
  1276. self,
  1277. sql: str,
  1278. index_col: str | list[str] | None = None,
  1279. coerce_float: bool = True,
  1280. parse_dates=None,
  1281. params=None,
  1282. chunksize: int | None = None,
  1283. dtype: DtypeArg | None = None,
  1284. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  1285. ) -> DataFrame | Iterator[DataFrame]:
  1286. pass
  1287. @abstractmethod
  1288. def to_sql(
  1289. self,
  1290. frame,
  1291. name: str,
  1292. if_exists: Literal["fail", "replace", "append"] = "fail",
  1293. index: bool = True,
  1294. index_label=None,
  1295. schema=None,
  1296. chunksize: int | None = None,
  1297. dtype: DtypeArg | None = None,
  1298. method: Literal["multi"] | Callable | None = None,
  1299. engine: str = "auto",
  1300. **engine_kwargs,
  1301. ) -> int | None:
  1302. pass
  1303. @abstractmethod
  1304. def execute(self, sql: str | Select | TextClause, params=None):
  1305. pass
  1306. @abstractmethod
  1307. def has_table(self, name: str, schema: str | None = None) -> bool:
  1308. pass
  1309. @abstractmethod
  1310. def _create_sql_schema(
  1311. self,
  1312. frame: DataFrame,
  1313. table_name: str,
  1314. keys: list[str] | None = None,
  1315. dtype: DtypeArg | None = None,
  1316. schema: str | None = None,
  1317. ) -> str:
  1318. pass
  1319. class BaseEngine:
  1320. def insert_records(
  1321. self,
  1322. table: SQLTable,
  1323. con,
  1324. frame,
  1325. name: str,
  1326. index: bool | str | list[str] | None = True,
  1327. schema=None,
  1328. chunksize: int | None = None,
  1329. method=None,
  1330. **engine_kwargs,
  1331. ) -> int | None:
  1332. """
  1333. Inserts data into already-prepared table
  1334. """
  1335. raise AbstractMethodError(self)
  1336. class SQLAlchemyEngine(BaseEngine):
  1337. def __init__(self) -> None:
  1338. import_optional_dependency(
  1339. "sqlalchemy", extra="sqlalchemy is required for SQL support."
  1340. )
  1341. def insert_records(
  1342. self,
  1343. table: SQLTable,
  1344. con,
  1345. frame,
  1346. name: str,
  1347. index: bool | str | list[str] | None = True,
  1348. schema=None,
  1349. chunksize: int | None = None,
  1350. method=None,
  1351. **engine_kwargs,
  1352. ) -> int | None:
  1353. from sqlalchemy import exc
  1354. try:
  1355. return table.insert(chunksize=chunksize, method=method)
  1356. except exc.StatementError as err:
  1357. # GH34431
  1358. # https://stackoverflow.com/a/67358288/6067848
  1359. msg = r"""(\(1054, "Unknown column 'inf(e0)?' in 'field list'"\))(?#
  1360. )|inf can not be used with MySQL"""
  1361. err_text = str(err.orig)
  1362. if re.search(msg, err_text):
  1363. raise ValueError("inf cannot be used with MySQL") from err
  1364. raise err
  1365. def get_engine(engine: str) -> BaseEngine:
  1366. """return our implementation"""
  1367. if engine == "auto":
  1368. engine = get_option("io.sql.engine")
  1369. if engine == "auto":
  1370. # try engines in this order
  1371. engine_classes = [SQLAlchemyEngine]
  1372. error_msgs = ""
  1373. for engine_class in engine_classes:
  1374. try:
  1375. return engine_class()
  1376. except ImportError as err:
  1377. error_msgs += "\n - " + str(err)
  1378. raise ImportError(
  1379. "Unable to find a usable engine; "
  1380. "tried using: 'sqlalchemy'.\n"
  1381. "A suitable version of "
  1382. "sqlalchemy is required for sql I/O "
  1383. "support.\n"
  1384. "Trying to import the above resulted in these errors:"
  1385. f"{error_msgs}"
  1386. )
  1387. if engine == "sqlalchemy":
  1388. return SQLAlchemyEngine()
  1389. raise ValueError("engine must be one of 'auto', 'sqlalchemy'")
  1390. class SQLDatabase(PandasSQL):
  1391. """
  1392. This class enables conversion between DataFrame and SQL databases
  1393. using SQLAlchemy to handle DataBase abstraction.
  1394. Parameters
  1395. ----------
  1396. con : SQLAlchemy Connectable or URI string.
  1397. Connectable to connect with the database. Using SQLAlchemy makes it
  1398. possible to use any DB supported by that library.
  1399. schema : string, default None
  1400. Name of SQL schema in database to write to (if database flavor
  1401. supports this). If None, use default schema (default).
  1402. need_transaction : bool, default False
  1403. If True, SQLDatabase will create a transaction.
  1404. """
  1405. def __init__(
  1406. self, con, schema: str | None = None, need_transaction: bool = False
  1407. ) -> None:
  1408. from sqlalchemy import create_engine
  1409. from sqlalchemy.engine import Engine
  1410. from sqlalchemy.schema import MetaData
  1411. # self.exit_stack cleans up the Engine and Connection and commits the
  1412. # transaction if any of those objects was created below.
  1413. # Cleanup happens either in self.__exit__ or at the end of the iterator
  1414. # returned by read_sql when chunksize is not None.
  1415. self.exit_stack = ExitStack()
  1416. if isinstance(con, str):
  1417. con = create_engine(con)
  1418. self.exit_stack.callback(con.dispose)
  1419. if isinstance(con, Engine):
  1420. con = self.exit_stack.enter_context(con.connect())
  1421. if need_transaction and not con.in_transaction():
  1422. self.exit_stack.enter_context(con.begin())
  1423. self.con = con
  1424. self.meta = MetaData(schema=schema)
  1425. self.returns_generator = False
  1426. def __exit__(self, *args) -> None:
  1427. if not self.returns_generator:
  1428. self.exit_stack.close()
  1429. @contextmanager
  1430. def run_transaction(self):
  1431. if not self.con.in_transaction():
  1432. with self.con.begin():
  1433. yield self.con
  1434. else:
  1435. yield self.con
  1436. def execute(self, sql: str | Select | TextClause, params=None):
  1437. """Simple passthrough to SQLAlchemy connectable"""
  1438. args = [] if params is None else [params]
  1439. if isinstance(sql, str):
  1440. return self.con.exec_driver_sql(sql, *args)
  1441. return self.con.execute(sql, *args)
  1442. def read_table(
  1443. self,
  1444. table_name: str,
  1445. index_col: str | list[str] | None = None,
  1446. coerce_float: bool = True,
  1447. parse_dates=None,
  1448. columns=None,
  1449. schema: str | None = None,
  1450. chunksize: int | None = None,
  1451. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  1452. ) -> DataFrame | Iterator[DataFrame]:
  1453. """
  1454. Read SQL database table into a DataFrame.
  1455. Parameters
  1456. ----------
  1457. table_name : str
  1458. Name of SQL table in database.
  1459. index_col : string, optional, default: None
  1460. Column to set as index.
  1461. coerce_float : bool, default True
  1462. Attempts to convert values of non-string, non-numeric objects
  1463. (like decimal.Decimal) to floating point. This can result in
  1464. loss of precision.
  1465. parse_dates : list or dict, default: None
  1466. - List of column names to parse as dates.
  1467. - Dict of ``{column_name: format string}`` where format string is
  1468. strftime compatible in case of parsing string times, or is one of
  1469. (D, s, ns, ms, us) in case of parsing integer timestamps.
  1470. - Dict of ``{column_name: arg}``, where the arg corresponds
  1471. to the keyword arguments of :func:`pandas.to_datetime`.
  1472. Especially useful with databases without native Datetime support,
  1473. such as SQLite.
  1474. columns : list, default: None
  1475. List of column names to select from SQL table.
  1476. schema : string, default None
  1477. Name of SQL schema in database to query (if database flavor
  1478. supports this). If specified, this overwrites the default
  1479. schema of the SQL database object.
  1480. chunksize : int, default None
  1481. If specified, return an iterator where `chunksize` is the number
  1482. of rows to include in each chunk.
  1483. dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable'
  1484. Back-end data type applied to the resultant :class:`DataFrame`
  1485. (still experimental). Behaviour is as follows:
  1486. * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
  1487. (default).
  1488. * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
  1489. DataFrame.
  1490. .. versionadded:: 2.0
  1491. Returns
  1492. -------
  1493. DataFrame
  1494. See Also
  1495. --------
  1496. pandas.read_sql_table
  1497. SQLDatabase.read_query
  1498. """
  1499. self.meta.reflect(bind=self.con, only=[table_name], views=True)
  1500. table = SQLTable(table_name, self, index=index_col, schema=schema)
  1501. if chunksize is not None:
  1502. self.returns_generator = True
  1503. return table.read(
  1504. self.exit_stack,
  1505. coerce_float=coerce_float,
  1506. parse_dates=parse_dates,
  1507. columns=columns,
  1508. chunksize=chunksize,
  1509. dtype_backend=dtype_backend,
  1510. )
  1511. @staticmethod
  1512. def _query_iterator(
  1513. result,
  1514. exit_stack: ExitStack,
  1515. chunksize: int,
  1516. columns,
  1517. index_col=None,
  1518. coerce_float: bool = True,
  1519. parse_dates=None,
  1520. dtype: DtypeArg | None = None,
  1521. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  1522. ):
  1523. """Return generator through chunked result set"""
  1524. has_read_data = False
  1525. with exit_stack:
  1526. while True:
  1527. data = result.fetchmany(chunksize)
  1528. if not data:
  1529. if not has_read_data:
  1530. yield _wrap_result(
  1531. [],
  1532. columns,
  1533. index_col=index_col,
  1534. coerce_float=coerce_float,
  1535. parse_dates=parse_dates,
  1536. dtype=dtype,
  1537. dtype_backend=dtype_backend,
  1538. )
  1539. break
  1540. has_read_data = True
  1541. yield _wrap_result(
  1542. data,
  1543. columns,
  1544. index_col=index_col,
  1545. coerce_float=coerce_float,
  1546. parse_dates=parse_dates,
  1547. dtype=dtype,
  1548. dtype_backend=dtype_backend,
  1549. )
  1550. def read_query(
  1551. self,
  1552. sql: str,
  1553. index_col: str | list[str] | None = None,
  1554. coerce_float: bool = True,
  1555. parse_dates=None,
  1556. params=None,
  1557. chunksize: int | None = None,
  1558. dtype: DtypeArg | None = None,
  1559. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  1560. ) -> DataFrame | Iterator[DataFrame]:
  1561. """
  1562. Read SQL query into a DataFrame.
  1563. Parameters
  1564. ----------
  1565. sql : str
  1566. SQL query to be executed.
  1567. index_col : string, optional, default: None
  1568. Column name to use as index for the returned DataFrame object.
  1569. coerce_float : bool, default True
  1570. Attempt to convert values of non-string, non-numeric objects (like
  1571. decimal.Decimal) to floating point, useful for SQL result sets.
  1572. params : list, tuple or dict, optional, default: None
  1573. List of parameters to pass to execute method. The syntax used
  1574. to pass parameters is database driver dependent. Check your
  1575. database driver documentation for which of the five syntax styles,
  1576. described in PEP 249's paramstyle, is supported.
  1577. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
  1578. parse_dates : list or dict, default: None
  1579. - List of column names to parse as dates.
  1580. - Dict of ``{column_name: format string}`` where format string is
  1581. strftime compatible in case of parsing string times, or is one of
  1582. (D, s, ns, ms, us) in case of parsing integer timestamps.
  1583. - Dict of ``{column_name: arg dict}``, where the arg dict
  1584. corresponds to the keyword arguments of
  1585. :func:`pandas.to_datetime` Especially useful with databases
  1586. without native Datetime support, such as SQLite.
  1587. chunksize : int, default None
  1588. If specified, return an iterator where `chunksize` is the number
  1589. of rows to include in each chunk.
  1590. dtype : Type name or dict of columns
  1591. Data type for data or columns. E.g. np.float64 or
  1592. {'a': np.float64, 'b': np.int32, 'c': 'Int64'}
  1593. .. versionadded:: 1.3.0
  1594. Returns
  1595. -------
  1596. DataFrame
  1597. See Also
  1598. --------
  1599. read_sql_table : Read SQL database table into a DataFrame.
  1600. read_sql
  1601. """
  1602. result = self.execute(sql, params)
  1603. columns = result.keys()
  1604. if chunksize is not None:
  1605. self.returns_generator = True
  1606. return self._query_iterator(
  1607. result,
  1608. self.exit_stack,
  1609. chunksize,
  1610. columns,
  1611. index_col=index_col,
  1612. coerce_float=coerce_float,
  1613. parse_dates=parse_dates,
  1614. dtype=dtype,
  1615. dtype_backend=dtype_backend,
  1616. )
  1617. else:
  1618. data = result.fetchall()
  1619. frame = _wrap_result(
  1620. data,
  1621. columns,
  1622. index_col=index_col,
  1623. coerce_float=coerce_float,
  1624. parse_dates=parse_dates,
  1625. dtype=dtype,
  1626. dtype_backend=dtype_backend,
  1627. )
  1628. return frame
  1629. read_sql = read_query
  1630. def prep_table(
  1631. self,
  1632. frame,
  1633. name: str,
  1634. if_exists: Literal["fail", "replace", "append"] = "fail",
  1635. index: bool | str | list[str] | None = True,
  1636. index_label=None,
  1637. schema=None,
  1638. dtype: DtypeArg | None = None,
  1639. ) -> SQLTable:
  1640. """
  1641. Prepares table in the database for data insertion. Creates it if needed, etc.
  1642. """
  1643. if dtype:
  1644. if not is_dict_like(dtype):
  1645. # error: Value expression in dictionary comprehension has incompatible
  1646. # type "Union[ExtensionDtype, str, dtype[Any], Type[object],
  1647. # Dict[Hashable, Union[ExtensionDtype, Union[str, dtype[Any]],
  1648. # Type[str], Type[float], Type[int], Type[complex], Type[bool],
  1649. # Type[object]]]]"; expected type "Union[ExtensionDtype, str,
  1650. # dtype[Any], Type[object]]"
  1651. dtype = {col_name: dtype for col_name in frame} # type: ignore[misc]
  1652. else:
  1653. dtype = cast(dict, dtype)
  1654. from sqlalchemy.types import TypeEngine
  1655. for col, my_type in dtype.items():
  1656. if isinstance(my_type, type) and issubclass(my_type, TypeEngine):
  1657. pass
  1658. elif isinstance(my_type, TypeEngine):
  1659. pass
  1660. else:
  1661. raise ValueError(f"The type of {col} is not a SQLAlchemy type")
  1662. table = SQLTable(
  1663. name,
  1664. self,
  1665. frame=frame,
  1666. index=index,
  1667. if_exists=if_exists,
  1668. index_label=index_label,
  1669. schema=schema,
  1670. dtype=dtype,
  1671. )
  1672. table.create()
  1673. return table
  1674. def check_case_sensitive(
  1675. self,
  1676. name: str,
  1677. schema: str | None,
  1678. ) -> None:
  1679. """
  1680. Checks table name for issues with case-sensitivity.
  1681. Method is called after data is inserted.
  1682. """
  1683. if not name.isdigit() and not name.islower():
  1684. # check for potentially case sensitivity issues (GH7815)
  1685. # Only check when name is not a number and name is not lower case
  1686. from sqlalchemy import inspect as sqlalchemy_inspect
  1687. insp = sqlalchemy_inspect(self.con)
  1688. table_names = insp.get_table_names(schema=schema or self.meta.schema)
  1689. if name not in table_names:
  1690. msg = (
  1691. f"The provided table name '{name}' is not found exactly as "
  1692. "such in the database after writing the table, possibly "
  1693. "due to case sensitivity issues. Consider using lower "
  1694. "case table names."
  1695. )
  1696. warnings.warn(
  1697. msg,
  1698. UserWarning,
  1699. stacklevel=find_stack_level(),
  1700. )
  1701. def to_sql(
  1702. self,
  1703. frame,
  1704. name: str,
  1705. if_exists: Literal["fail", "replace", "append"] = "fail",
  1706. index: bool = True,
  1707. index_label=None,
  1708. schema: str | None = None,
  1709. chunksize: int | None = None,
  1710. dtype: DtypeArg | None = None,
  1711. method: Literal["multi"] | Callable | None = None,
  1712. engine: str = "auto",
  1713. **engine_kwargs,
  1714. ) -> int | None:
  1715. """
  1716. Write records stored in a DataFrame to a SQL database.
  1717. Parameters
  1718. ----------
  1719. frame : DataFrame
  1720. name : string
  1721. Name of SQL table.
  1722. if_exists : {'fail', 'replace', 'append'}, default 'fail'
  1723. - fail: If table exists, do nothing.
  1724. - replace: If table exists, drop it, recreate it, and insert data.
  1725. - append: If table exists, insert data. Create if does not exist.
  1726. index : boolean, default True
  1727. Write DataFrame index as a column.
  1728. index_label : string or sequence, default None
  1729. Column label for index column(s). If None is given (default) and
  1730. `index` is True, then the index names are used.
  1731. A sequence should be given if the DataFrame uses MultiIndex.
  1732. schema : string, default None
  1733. Name of SQL schema in database to write to (if database flavor
  1734. supports this). If specified, this overwrites the default
  1735. schema of the SQLDatabase object.
  1736. chunksize : int, default None
  1737. If not None, then rows will be written in batches of this size at a
  1738. time. If None, all rows will be written at once.
  1739. dtype : single type or dict of column name to SQL type, default None
  1740. Optional specifying the datatype for columns. The SQL type should
  1741. be a SQLAlchemy type. If all columns are of the same type, one
  1742. single value can be used.
  1743. method : {None', 'multi', callable}, default None
  1744. Controls the SQL insertion clause used:
  1745. * None : Uses standard SQL ``INSERT`` clause (one per row).
  1746. * 'multi': Pass multiple values in a single ``INSERT`` clause.
  1747. * callable with signature ``(pd_table, conn, keys, data_iter)``.
  1748. Details and a sample callable implementation can be found in the
  1749. section :ref:`insert method <io.sql.method>`.
  1750. engine : {'auto', 'sqlalchemy'}, default 'auto'
  1751. SQL engine library to use. If 'auto', then the option
  1752. ``io.sql.engine`` is used. The default ``io.sql.engine``
  1753. behavior is 'sqlalchemy'
  1754. .. versionadded:: 1.3.0
  1755. **engine_kwargs
  1756. Any additional kwargs are passed to the engine.
  1757. """
  1758. sql_engine = get_engine(engine)
  1759. table = self.prep_table(
  1760. frame=frame,
  1761. name=name,
  1762. if_exists=if_exists,
  1763. index=index,
  1764. index_label=index_label,
  1765. schema=schema,
  1766. dtype=dtype,
  1767. )
  1768. total_inserted = sql_engine.insert_records(
  1769. table=table,
  1770. con=self.con,
  1771. frame=frame,
  1772. name=name,
  1773. index=index,
  1774. schema=schema,
  1775. chunksize=chunksize,
  1776. method=method,
  1777. **engine_kwargs,
  1778. )
  1779. self.check_case_sensitive(name=name, schema=schema)
  1780. return total_inserted
  1781. @property
  1782. def tables(self):
  1783. return self.meta.tables
  1784. def has_table(self, name: str, schema: str | None = None) -> bool:
  1785. from sqlalchemy import inspect as sqlalchemy_inspect
  1786. insp = sqlalchemy_inspect(self.con)
  1787. return insp.has_table(name, schema or self.meta.schema)
  1788. def get_table(self, table_name: str, schema: str | None = None) -> Table:
  1789. from sqlalchemy import (
  1790. Numeric,
  1791. Table,
  1792. )
  1793. schema = schema or self.meta.schema
  1794. tbl = Table(table_name, self.meta, autoload_with=self.con, schema=schema)
  1795. for column in tbl.columns:
  1796. if isinstance(column.type, Numeric):
  1797. column.type.asdecimal = False
  1798. return tbl
  1799. def drop_table(self, table_name: str, schema: str | None = None) -> None:
  1800. schema = schema or self.meta.schema
  1801. if self.has_table(table_name, schema):
  1802. self.meta.reflect(
  1803. bind=self.con, only=[table_name], schema=schema, views=True
  1804. )
  1805. with self.run_transaction():
  1806. self.get_table(table_name, schema).drop(bind=self.con)
  1807. self.meta.clear()
  1808. def _create_sql_schema(
  1809. self,
  1810. frame: DataFrame,
  1811. table_name: str,
  1812. keys: list[str] | None = None,
  1813. dtype: DtypeArg | None = None,
  1814. schema: str | None = None,
  1815. ) -> str:
  1816. table = SQLTable(
  1817. table_name,
  1818. self,
  1819. frame=frame,
  1820. index=False,
  1821. keys=keys,
  1822. dtype=dtype,
  1823. schema=schema,
  1824. )
  1825. return str(table.sql_schema())
  1826. # ---- SQL without SQLAlchemy ---
  1827. class ADBCDatabase(PandasSQL):
  1828. """
  1829. This class enables conversion between DataFrame and SQL databases
  1830. using ADBC to handle DataBase abstraction.
  1831. Parameters
  1832. ----------
  1833. con : adbc_driver_manager.dbapi.Connection
  1834. """
  1835. def __init__(self, con) -> None:
  1836. self.con = con
  1837. @contextmanager
  1838. def run_transaction(self):
  1839. with self.con.cursor() as cur:
  1840. try:
  1841. yield cur
  1842. except Exception:
  1843. self.con.rollback()
  1844. raise
  1845. self.con.commit()
  1846. def execute(self, sql: str | Select | TextClause, params=None):
  1847. if not isinstance(sql, str):
  1848. raise TypeError("Query must be a string unless using sqlalchemy.")
  1849. args = [] if params is None else [params]
  1850. cur = self.con.cursor()
  1851. try:
  1852. cur.execute(sql, *args)
  1853. return cur
  1854. except Exception as exc:
  1855. try:
  1856. self.con.rollback()
  1857. except Exception as inner_exc: # pragma: no cover
  1858. ex = DatabaseError(
  1859. f"Execution failed on sql: {sql}\n{exc}\nunable to rollback"
  1860. )
  1861. raise ex from inner_exc
  1862. ex = DatabaseError(f"Execution failed on sql '{sql}': {exc}")
  1863. raise ex from exc
  1864. def read_table(
  1865. self,
  1866. table_name: str,
  1867. index_col: str | list[str] | None = None,
  1868. coerce_float: bool = True,
  1869. parse_dates=None,
  1870. columns=None,
  1871. schema: str | None = None,
  1872. chunksize: int | None = None,
  1873. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  1874. ) -> DataFrame | Iterator[DataFrame]:
  1875. """
  1876. Read SQL database table into a DataFrame.
  1877. Parameters
  1878. ----------
  1879. table_name : str
  1880. Name of SQL table in database.
  1881. coerce_float : bool, default True
  1882. Raises NotImplementedError
  1883. parse_dates : list or dict, default: None
  1884. - List of column names to parse as dates.
  1885. - Dict of ``{column_name: format string}`` where format string is
  1886. strftime compatible in case of parsing string times, or is one of
  1887. (D, s, ns, ms, us) in case of parsing integer timestamps.
  1888. - Dict of ``{column_name: arg}``, where the arg corresponds
  1889. to the keyword arguments of :func:`pandas.to_datetime`.
  1890. Especially useful with databases without native Datetime support,
  1891. such as SQLite.
  1892. columns : list, default: None
  1893. List of column names to select from SQL table.
  1894. schema : string, default None
  1895. Name of SQL schema in database to query (if database flavor
  1896. supports this). If specified, this overwrites the default
  1897. schema of the SQL database object.
  1898. chunksize : int, default None
  1899. Raises NotImplementedError
  1900. dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable'
  1901. Back-end data type applied to the resultant :class:`DataFrame`
  1902. (still experimental). Behaviour is as follows:
  1903. * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
  1904. (default).
  1905. * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
  1906. DataFrame.
  1907. .. versionadded:: 2.0
  1908. Returns
  1909. -------
  1910. DataFrame
  1911. See Also
  1912. --------
  1913. pandas.read_sql_table
  1914. SQLDatabase.read_query
  1915. """
  1916. if coerce_float is not True:
  1917. raise NotImplementedError(
  1918. "'coerce_float' is not implemented for ADBC drivers"
  1919. )
  1920. if chunksize:
  1921. raise NotImplementedError("'chunksize' is not implemented for ADBC drivers")
  1922. if columns:
  1923. if index_col:
  1924. index_select = maybe_make_list(index_col)
  1925. else:
  1926. index_select = []
  1927. to_select = index_select + columns
  1928. select_list = ", ".join(f'"{x}"' for x in to_select)
  1929. else:
  1930. select_list = "*"
  1931. if schema:
  1932. stmt = f"SELECT {select_list} FROM {schema}.{table_name}"
  1933. else:
  1934. stmt = f"SELECT {select_list} FROM {table_name}"
  1935. with self.con.cursor() as cur:
  1936. cur.execute(stmt)
  1937. pa_table = cur.fetch_arrow_table()
  1938. df = arrow_table_to_pandas(pa_table, dtype_backend=dtype_backend)
  1939. return _wrap_result_adbc(
  1940. df,
  1941. index_col=index_col,
  1942. parse_dates=parse_dates,
  1943. )
  1944. def read_query(
  1945. self,
  1946. sql: str,
  1947. index_col: str | list[str] | None = None,
  1948. coerce_float: bool = True,
  1949. parse_dates=None,
  1950. params=None,
  1951. chunksize: int | None = None,
  1952. dtype: DtypeArg | None = None,
  1953. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  1954. ) -> DataFrame | Iterator[DataFrame]:
  1955. """
  1956. Read SQL query into a DataFrame.
  1957. Parameters
  1958. ----------
  1959. sql : str
  1960. SQL query to be executed.
  1961. index_col : string, optional, default: None
  1962. Column name to use as index for the returned DataFrame object.
  1963. coerce_float : bool, default True
  1964. Raises NotImplementedError
  1965. params : list, tuple or dict, optional, default: None
  1966. Raises NotImplementedError
  1967. parse_dates : list or dict, default: None
  1968. - List of column names to parse as dates.
  1969. - Dict of ``{column_name: format string}`` where format string is
  1970. strftime compatible in case of parsing string times, or is one of
  1971. (D, s, ns, ms, us) in case of parsing integer timestamps.
  1972. - Dict of ``{column_name: arg dict}``, where the arg dict
  1973. corresponds to the keyword arguments of
  1974. :func:`pandas.to_datetime` Especially useful with databases
  1975. without native Datetime support, such as SQLite.
  1976. chunksize : int, default None
  1977. Raises NotImplementedError
  1978. dtype : Type name or dict of columns
  1979. Data type for data or columns. E.g. np.float64 or
  1980. {'a': np.float64, 'b': np.int32, 'c': 'Int64'}
  1981. .. versionadded:: 1.3.0
  1982. Returns
  1983. -------
  1984. DataFrame
  1985. See Also
  1986. --------
  1987. read_sql_table : Read SQL database table into a DataFrame.
  1988. read_sql
  1989. """
  1990. if coerce_float is not True:
  1991. raise NotImplementedError(
  1992. "'coerce_float' is not implemented for ADBC drivers"
  1993. )
  1994. if params:
  1995. raise NotImplementedError("'params' is not implemented for ADBC drivers")
  1996. if chunksize:
  1997. raise NotImplementedError("'chunksize' is not implemented for ADBC drivers")
  1998. with self.con.cursor() as cur:
  1999. cur.execute(sql)
  2000. pa_table = cur.fetch_arrow_table()
  2001. df = arrow_table_to_pandas(pa_table, dtype_backend=dtype_backend)
  2002. return _wrap_result_adbc(
  2003. df,
  2004. index_col=index_col,
  2005. parse_dates=parse_dates,
  2006. dtype=dtype,
  2007. )
  2008. read_sql = read_query
  2009. def to_sql(
  2010. self,
  2011. frame,
  2012. name: str,
  2013. if_exists: Literal["fail", "replace", "append"] = "fail",
  2014. index: bool = True,
  2015. index_label=None,
  2016. schema: str | None = None,
  2017. chunksize: int | None = None,
  2018. dtype: DtypeArg | None = None,
  2019. method: Literal["multi"] | Callable | None = None,
  2020. engine: str = "auto",
  2021. **engine_kwargs,
  2022. ) -> int | None:
  2023. """
  2024. Write records stored in a DataFrame to a SQL database.
  2025. Parameters
  2026. ----------
  2027. frame : DataFrame
  2028. name : string
  2029. Name of SQL table.
  2030. if_exists : {'fail', 'replace', 'append'}, default 'fail'
  2031. - fail: If table exists, do nothing.
  2032. - replace: If table exists, drop it, recreate it, and insert data.
  2033. - append: If table exists, insert data. Create if does not exist.
  2034. index : boolean, default True
  2035. Write DataFrame index as a column.
  2036. index_label : string or sequence, default None
  2037. Raises NotImplementedError
  2038. schema : string, default None
  2039. Name of SQL schema in database to write to (if database flavor
  2040. supports this). If specified, this overwrites the default
  2041. schema of the SQLDatabase object.
  2042. chunksize : int, default None
  2043. Raises NotImplementedError
  2044. dtype : single type or dict of column name to SQL type, default None
  2045. Raises NotImplementedError
  2046. method : {None', 'multi', callable}, default None
  2047. Raises NotImplementedError
  2048. engine : {'auto', 'sqlalchemy'}, default 'auto'
  2049. Raises NotImplementedError if not set to 'auto'
  2050. """
  2051. if index_label:
  2052. raise NotImplementedError(
  2053. "'index_label' is not implemented for ADBC drivers"
  2054. )
  2055. if chunksize:
  2056. raise NotImplementedError("'chunksize' is not implemented for ADBC drivers")
  2057. if dtype:
  2058. raise NotImplementedError("'dtype' is not implemented for ADBC drivers")
  2059. if method:
  2060. raise NotImplementedError("'method' is not implemented for ADBC drivers")
  2061. if engine != "auto":
  2062. raise NotImplementedError(
  2063. "engine != 'auto' not implemented for ADBC drivers"
  2064. )
  2065. if schema:
  2066. table_name = f"{schema}.{name}"
  2067. else:
  2068. table_name = name
  2069. # pandas if_exists="append" will still create the
  2070. # table if it does not exist; ADBC is more explicit with append/create
  2071. # as applicable modes, so the semantics get blurred across
  2072. # the libraries
  2073. mode = "create"
  2074. if self.has_table(name, schema):
  2075. if if_exists == "fail":
  2076. raise ValueError(f"Table '{table_name}' already exists.")
  2077. elif if_exists == "replace":
  2078. with self.con.cursor() as cur:
  2079. cur.execute(f"DROP TABLE {table_name}")
  2080. elif if_exists == "append":
  2081. mode = "append"
  2082. import pyarrow as pa
  2083. try:
  2084. tbl = pa.Table.from_pandas(frame, preserve_index=index)
  2085. except pa.ArrowNotImplementedError as exc:
  2086. raise ValueError("datatypes not supported") from exc
  2087. with self.con.cursor() as cur:
  2088. total_inserted = cur.adbc_ingest(
  2089. table_name=name, data=tbl, mode=mode, db_schema_name=schema
  2090. )
  2091. self.con.commit()
  2092. return total_inserted
  2093. def has_table(self, name: str, schema: str | None = None) -> bool:
  2094. meta = self.con.adbc_get_objects(
  2095. db_schema_filter=schema, table_name_filter=name
  2096. ).read_all()
  2097. for catalog_schema in meta["catalog_db_schemas"].to_pylist():
  2098. if not catalog_schema:
  2099. continue
  2100. for schema_record in catalog_schema:
  2101. if not schema_record:
  2102. continue
  2103. for table_record in schema_record["db_schema_tables"]:
  2104. if table_record["table_name"] == name:
  2105. return True
  2106. return False
  2107. def _create_sql_schema(
  2108. self,
  2109. frame: DataFrame,
  2110. table_name: str,
  2111. keys: list[str] | None = None,
  2112. dtype: DtypeArg | None = None,
  2113. schema: str | None = None,
  2114. ) -> str:
  2115. raise NotImplementedError("not implemented for adbc")
  2116. # sqlite-specific sql strings and handler class
  2117. # dictionary used for readability purposes
  2118. _SQL_TYPES = {
  2119. "string": "TEXT",
  2120. "floating": "REAL",
  2121. "integer": "INTEGER",
  2122. "datetime": "TIMESTAMP",
  2123. "date": "DATE",
  2124. "time": "TIME",
  2125. "boolean": "INTEGER",
  2126. }
  2127. def _get_unicode_name(name: object):
  2128. try:
  2129. uname = str(name).encode("utf-8", "strict").decode("utf-8")
  2130. except UnicodeError as err:
  2131. raise ValueError(f"Cannot convert identifier to UTF-8: '{name}'") from err
  2132. return uname
  2133. def _get_valid_sqlite_name(name: object):
  2134. # See https://stackoverflow.com/questions/6514274/how-do-you-escape-strings\
  2135. # -for-sqlite-table-column-names-in-python
  2136. # Ensure the string can be encoded as UTF-8.
  2137. # Ensure the string does not include any NUL characters.
  2138. # Replace all " with "".
  2139. # Wrap the entire thing in double quotes.
  2140. uname = _get_unicode_name(name)
  2141. if not len(uname):
  2142. raise ValueError("Empty table or column name specified")
  2143. nul_index = uname.find("\x00")
  2144. if nul_index >= 0:
  2145. raise ValueError("SQLite identifier cannot contain NULs")
  2146. return '"' + uname.replace('"', '""') + '"'
  2147. class SQLiteTable(SQLTable):
  2148. """
  2149. Patch the SQLTable for fallback support.
  2150. Instead of a table variable just use the Create Table statement.
  2151. """
  2152. def __init__(self, *args, **kwargs) -> None:
  2153. super().__init__(*args, **kwargs)
  2154. self._register_date_adapters()
  2155. def _register_date_adapters(self) -> None:
  2156. # GH 8341
  2157. # register an adapter callable for datetime.time object
  2158. import sqlite3
  2159. # this will transform time(12,34,56,789) into '12:34:56.000789'
  2160. # (this is what sqlalchemy does)
  2161. def _adapt_time(t) -> str:
  2162. # This is faster than strftime
  2163. return f"{t.hour:02d}:{t.minute:02d}:{t.second:02d}.{t.microsecond:06d}"
  2164. # Also register adapters for date/datetime and co
  2165. # xref https://docs.python.org/3.12/library/sqlite3.html#adapter-and-converter-recipes
  2166. # Python 3.12+ doesn't auto-register adapters for us anymore
  2167. adapt_date_iso = lambda val: val.isoformat()
  2168. adapt_datetime_iso = lambda val: val.isoformat(" ")
  2169. sqlite3.register_adapter(time, _adapt_time)
  2170. sqlite3.register_adapter(date, adapt_date_iso)
  2171. sqlite3.register_adapter(datetime, adapt_datetime_iso)
  2172. convert_date = lambda val: date.fromisoformat(val.decode())
  2173. convert_timestamp = lambda val: datetime.fromisoformat(val.decode())
  2174. sqlite3.register_converter("date", convert_date)
  2175. sqlite3.register_converter("timestamp", convert_timestamp)
  2176. def sql_schema(self) -> str:
  2177. return str(";\n".join(self.table))
  2178. def _execute_create(self) -> None:
  2179. with self.pd_sql.run_transaction() as conn:
  2180. for stmt in self.table:
  2181. conn.execute(stmt)
  2182. def insert_statement(self, *, num_rows: int) -> str:
  2183. names = list(map(str, self.frame.columns))
  2184. wld = "?" # wildcard char
  2185. escape = _get_valid_sqlite_name
  2186. if self.index is not None:
  2187. for idx in self.index[::-1]:
  2188. names.insert(0, idx)
  2189. bracketed_names = [escape(column) for column in names]
  2190. col_names = ",".join(bracketed_names)
  2191. row_wildcards = ",".join([wld] * len(names))
  2192. wildcards = ",".join([f"({row_wildcards})" for _ in range(num_rows)])
  2193. insert_statement = (
  2194. f"INSERT INTO {escape(self.name)} ({col_names}) VALUES {wildcards}"
  2195. )
  2196. return insert_statement
  2197. def _execute_insert(self, conn, keys, data_iter) -> int:
  2198. data_list = list(data_iter)
  2199. conn.executemany(self.insert_statement(num_rows=1), data_list)
  2200. return conn.rowcount
  2201. def _execute_insert_multi(self, conn, keys, data_iter) -> int:
  2202. data_list = list(data_iter)
  2203. flattened_data = [x for row in data_list for x in row]
  2204. conn.execute(self.insert_statement(num_rows=len(data_list)), flattened_data)
  2205. return conn.rowcount
  2206. def _create_table_setup(self):
  2207. """
  2208. Return a list of SQL statements that creates a table reflecting the
  2209. structure of a DataFrame. The first entry will be a CREATE TABLE
  2210. statement while the rest will be CREATE INDEX statements.
  2211. """
  2212. column_names_and_types = self._get_column_names_and_types(self._sql_type_name)
  2213. escape = _get_valid_sqlite_name
  2214. create_tbl_stmts = [
  2215. escape(cname) + " " + ctype for cname, ctype, _ in column_names_and_types
  2216. ]
  2217. if self.keys is not None and len(self.keys):
  2218. if not is_list_like(self.keys):
  2219. keys = [self.keys]
  2220. else:
  2221. keys = self.keys
  2222. cnames_br = ", ".join([escape(c) for c in keys])
  2223. create_tbl_stmts.append(
  2224. f"CONSTRAINT {self.name}_pk PRIMARY KEY ({cnames_br})"
  2225. )
  2226. if self.schema:
  2227. schema_name = self.schema + "."
  2228. else:
  2229. schema_name = ""
  2230. create_stmts = [
  2231. "CREATE TABLE "
  2232. + schema_name
  2233. + escape(self.name)
  2234. + " (\n"
  2235. + ",\n ".join(create_tbl_stmts)
  2236. + "\n)"
  2237. ]
  2238. ix_cols = [cname for cname, _, is_index in column_names_and_types if is_index]
  2239. if len(ix_cols):
  2240. cnames = "_".join(ix_cols)
  2241. cnames_br = ",".join([escape(c) for c in ix_cols])
  2242. create_stmts.append(
  2243. "CREATE INDEX "
  2244. + escape("ix_" + self.name + "_" + cnames)
  2245. + "ON "
  2246. + escape(self.name)
  2247. + " ("
  2248. + cnames_br
  2249. + ")"
  2250. )
  2251. return create_stmts
  2252. def _sql_type_name(self, col):
  2253. dtype: DtypeArg = self.dtype or {}
  2254. if is_dict_like(dtype):
  2255. dtype = cast(dict, dtype)
  2256. if col.name in dtype:
  2257. return dtype[col.name]
  2258. # Infer type of column, while ignoring missing values.
  2259. # Needed for inserting typed data containing NULLs, GH 8778.
  2260. col_type = lib.infer_dtype(col, skipna=True)
  2261. if col_type == "timedelta64":
  2262. warnings.warn(
  2263. "the 'timedelta' type is not supported, and will be "
  2264. "written as integer values (ns frequency) to the database.",
  2265. UserWarning,
  2266. stacklevel=find_stack_level(),
  2267. )
  2268. col_type = "integer"
  2269. elif col_type == "datetime64":
  2270. col_type = "datetime"
  2271. elif col_type == "empty":
  2272. col_type = "string"
  2273. elif col_type == "complex":
  2274. raise ValueError("Complex datatypes not supported")
  2275. if col_type not in _SQL_TYPES:
  2276. col_type = "string"
  2277. return _SQL_TYPES[col_type]
  2278. class SQLiteDatabase(PandasSQL):
  2279. """
  2280. Version of SQLDatabase to support SQLite connections (fallback without
  2281. SQLAlchemy). This should only be used internally.
  2282. Parameters
  2283. ----------
  2284. con : sqlite connection object
  2285. """
  2286. def __init__(self, con) -> None:
  2287. self.con = con
  2288. @contextmanager
  2289. def run_transaction(self):
  2290. cur = self.con.cursor()
  2291. try:
  2292. yield cur
  2293. self.con.commit()
  2294. except Exception:
  2295. self.con.rollback()
  2296. raise
  2297. finally:
  2298. cur.close()
  2299. def execute(self, sql: str | Select | TextClause, params=None):
  2300. if not isinstance(sql, str):
  2301. raise TypeError("Query must be a string unless using sqlalchemy.")
  2302. args = [] if params is None else [params]
  2303. cur = self.con.cursor()
  2304. try:
  2305. cur.execute(sql, *args)
  2306. return cur
  2307. except Exception as exc:
  2308. try:
  2309. self.con.rollback()
  2310. except Exception as inner_exc: # pragma: no cover
  2311. ex = DatabaseError(
  2312. f"Execution failed on sql: {sql}\n{exc}\nunable to rollback"
  2313. )
  2314. raise ex from inner_exc
  2315. ex = DatabaseError(f"Execution failed on sql '{sql}': {exc}")
  2316. raise ex from exc
  2317. @staticmethod
  2318. def _query_iterator(
  2319. cursor,
  2320. chunksize: int,
  2321. columns,
  2322. index_col=None,
  2323. coerce_float: bool = True,
  2324. parse_dates=None,
  2325. dtype: DtypeArg | None = None,
  2326. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  2327. ):
  2328. """Return generator through chunked result set"""
  2329. has_read_data = False
  2330. while True:
  2331. data = cursor.fetchmany(chunksize)
  2332. if type(data) == tuple:
  2333. data = list(data)
  2334. if not data:
  2335. cursor.close()
  2336. if not has_read_data:
  2337. result = DataFrame.from_records(
  2338. [], columns=columns, coerce_float=coerce_float
  2339. )
  2340. if dtype:
  2341. result = result.astype(dtype)
  2342. yield result
  2343. break
  2344. has_read_data = True
  2345. yield _wrap_result(
  2346. data,
  2347. columns,
  2348. index_col=index_col,
  2349. coerce_float=coerce_float,
  2350. parse_dates=parse_dates,
  2351. dtype=dtype,
  2352. dtype_backend=dtype_backend,
  2353. )
  2354. def read_query(
  2355. self,
  2356. sql,
  2357. index_col=None,
  2358. coerce_float: bool = True,
  2359. parse_dates=None,
  2360. params=None,
  2361. chunksize: int | None = None,
  2362. dtype: DtypeArg | None = None,
  2363. dtype_backend: DtypeBackend | Literal["numpy"] = "numpy",
  2364. ) -> DataFrame | Iterator[DataFrame]:
  2365. cursor = self.execute(sql, params)
  2366. columns = [col_desc[0] for col_desc in cursor.description]
  2367. if chunksize is not None:
  2368. return self._query_iterator(
  2369. cursor,
  2370. chunksize,
  2371. columns,
  2372. index_col=index_col,
  2373. coerce_float=coerce_float,
  2374. parse_dates=parse_dates,
  2375. dtype=dtype,
  2376. dtype_backend=dtype_backend,
  2377. )
  2378. else:
  2379. data = self._fetchall_as_list(cursor)
  2380. cursor.close()
  2381. frame = _wrap_result(
  2382. data,
  2383. columns,
  2384. index_col=index_col,
  2385. coerce_float=coerce_float,
  2386. parse_dates=parse_dates,
  2387. dtype=dtype,
  2388. dtype_backend=dtype_backend,
  2389. )
  2390. return frame
  2391. def _fetchall_as_list(self, cur):
  2392. result = cur.fetchall()
  2393. if not isinstance(result, list):
  2394. result = list(result)
  2395. return result
  2396. def to_sql(
  2397. self,
  2398. frame,
  2399. name: str,
  2400. if_exists: str = "fail",
  2401. index: bool = True,
  2402. index_label=None,
  2403. schema=None,
  2404. chunksize: int | None = None,
  2405. dtype: DtypeArg | None = None,
  2406. method: Literal["multi"] | Callable | None = None,
  2407. engine: str = "auto",
  2408. **engine_kwargs,
  2409. ) -> int | None:
  2410. """
  2411. Write records stored in a DataFrame to a SQL database.
  2412. Parameters
  2413. ----------
  2414. frame: DataFrame
  2415. name: string
  2416. Name of SQL table.
  2417. if_exists: {'fail', 'replace', 'append'}, default 'fail'
  2418. fail: If table exists, do nothing.
  2419. replace: If table exists, drop it, recreate it, and insert data.
  2420. append: If table exists, insert data. Create if it does not exist.
  2421. index : bool, default True
  2422. Write DataFrame index as a column
  2423. index_label : string or sequence, default None
  2424. Column label for index column(s). If None is given (default) and
  2425. `index` is True, then the index names are used.
  2426. A sequence should be given if the DataFrame uses MultiIndex.
  2427. schema : string, default None
  2428. Ignored parameter included for compatibility with SQLAlchemy
  2429. version of ``to_sql``.
  2430. chunksize : int, default None
  2431. If not None, then rows will be written in batches of this
  2432. size at a time. If None, all rows will be written at once.
  2433. dtype : single type or dict of column name to SQL type, default None
  2434. Optional specifying the datatype for columns. The SQL type should
  2435. be a string. If all columns are of the same type, one single value
  2436. can be used.
  2437. method : {None, 'multi', callable}, default None
  2438. Controls the SQL insertion clause used:
  2439. * None : Uses standard SQL ``INSERT`` clause (one per row).
  2440. * 'multi': Pass multiple values in a single ``INSERT`` clause.
  2441. * callable with signature ``(pd_table, conn, keys, data_iter)``.
  2442. Details and a sample callable implementation can be found in the
  2443. section :ref:`insert method <io.sql.method>`.
  2444. """
  2445. if dtype:
  2446. if not is_dict_like(dtype):
  2447. # error: Value expression in dictionary comprehension has incompatible
  2448. # type "Union[ExtensionDtype, str, dtype[Any], Type[object],
  2449. # Dict[Hashable, Union[ExtensionDtype, Union[str, dtype[Any]],
  2450. # Type[str], Type[float], Type[int], Type[complex], Type[bool],
  2451. # Type[object]]]]"; expected type "Union[ExtensionDtype, str,
  2452. # dtype[Any], Type[object]]"
  2453. dtype = {col_name: dtype for col_name in frame} # type: ignore[misc]
  2454. else:
  2455. dtype = cast(dict, dtype)
  2456. for col, my_type in dtype.items():
  2457. if not isinstance(my_type, str):
  2458. raise ValueError(f"{col} ({my_type}) not a string")
  2459. table = SQLiteTable(
  2460. name,
  2461. self,
  2462. frame=frame,
  2463. index=index,
  2464. if_exists=if_exists,
  2465. index_label=index_label,
  2466. dtype=dtype,
  2467. )
  2468. table.create()
  2469. return table.insert(chunksize, method)
  2470. def has_table(self, name: str, schema: str | None = None) -> bool:
  2471. wld = "?"
  2472. query = f"""
  2473. SELECT
  2474. name
  2475. FROM
  2476. sqlite_master
  2477. WHERE
  2478. type IN ('table', 'view')
  2479. AND name={wld};
  2480. """
  2481. return len(self.execute(query, [name]).fetchall()) > 0
  2482. def get_table(self, table_name: str, schema: str | None = None) -> None:
  2483. return None # not supported in fallback mode
  2484. def drop_table(self, name: str, schema: str | None = None) -> None:
  2485. drop_sql = f"DROP TABLE {_get_valid_sqlite_name(name)}"
  2486. self.execute(drop_sql)
  2487. def _create_sql_schema(
  2488. self,
  2489. frame,
  2490. table_name: str,
  2491. keys=None,
  2492. dtype: DtypeArg | None = None,
  2493. schema: str | None = None,
  2494. ) -> str:
  2495. table = SQLiteTable(
  2496. table_name,
  2497. self,
  2498. frame=frame,
  2499. index=False,
  2500. keys=keys,
  2501. dtype=dtype,
  2502. schema=schema,
  2503. )
  2504. return str(table.sql_schema())
  2505. def get_schema(
  2506. frame,
  2507. name: str,
  2508. keys=None,
  2509. con=None,
  2510. dtype: DtypeArg | None = None,
  2511. schema: str | None = None,
  2512. ) -> str:
  2513. """
  2514. Get the SQL db table schema for the given frame.
  2515. Parameters
  2516. ----------
  2517. frame : DataFrame
  2518. name : str
  2519. name of SQL table
  2520. keys : string or sequence, default: None
  2521. columns to use a primary key
  2522. con: ADBC Connection, SQLAlchemy connectable, sqlite3 connection, default: None
  2523. ADBC provides high performance I/O with native type support, where available.
  2524. Using SQLAlchemy makes it possible to use any DB supported by that
  2525. library
  2526. If a DBAPI2 object, only sqlite3 is supported.
  2527. dtype : dict of column name to SQL type, default None
  2528. Optional specifying the datatype for columns. The SQL type should
  2529. be a SQLAlchemy type, or a string for sqlite3 fallback connection.
  2530. schema: str, default: None
  2531. Optional specifying the schema to be used in creating the table.
  2532. """
  2533. with pandasSQL_builder(con=con) as pandas_sql:
  2534. return pandas_sql._create_sql_schema(
  2535. frame, name, keys=keys, dtype=dtype, schema=schema
  2536. )