base.py 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953
  1. # dialects/sqlite/base.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. r'''
  9. .. dialect:: sqlite
  10. :name: SQLite
  11. :normal_support: 3.12+
  12. :best_effort: 3.7.16+
  13. .. _sqlite_datetime:
  14. Date and Time Types
  15. -------------------
  16. SQLite does not have built-in DATE, TIME, or DATETIME types, and pysqlite does
  17. not provide out of the box functionality for translating values between Python
  18. `datetime` objects and a SQLite-supported format. SQLAlchemy's own
  19. :class:`~sqlalchemy.types.DateTime` and related types provide date formatting
  20. and parsing functionality when SQLite is used. The implementation classes are
  21. :class:`_sqlite.DATETIME`, :class:`_sqlite.DATE` and :class:`_sqlite.TIME`.
  22. These types represent dates and times as ISO formatted strings, which also
  23. nicely support ordering. There's no reliance on typical "libc" internals for
  24. these functions so historical dates are fully supported.
  25. Ensuring Text affinity
  26. ^^^^^^^^^^^^^^^^^^^^^^
  27. The DDL rendered for these types is the standard ``DATE``, ``TIME``
  28. and ``DATETIME`` indicators. However, custom storage formats can also be
  29. applied to these types. When the
  30. storage format is detected as containing no alpha characters, the DDL for
  31. these types is rendered as ``DATE_CHAR``, ``TIME_CHAR``, and ``DATETIME_CHAR``,
  32. so that the column continues to have textual affinity.
  33. .. seealso::
  34. `Type Affinity <https://www.sqlite.org/datatype3.html#affinity>`_ -
  35. in the SQLite documentation
  36. .. _sqlite_autoincrement:
  37. SQLite Auto Incrementing Behavior
  38. ----------------------------------
  39. Background on SQLite's autoincrement is at: https://sqlite.org/autoinc.html
  40. Key concepts:
  41. * SQLite has an implicit "auto increment" feature that takes place for any
  42. non-composite primary-key column that is specifically created using
  43. "INTEGER PRIMARY KEY" for the type + primary key.
  44. * SQLite also has an explicit "AUTOINCREMENT" keyword, that is **not**
  45. equivalent to the implicit autoincrement feature; this keyword is not
  46. recommended for general use. SQLAlchemy does not render this keyword
  47. unless a special SQLite-specific directive is used (see below). However,
  48. it still requires that the column's type is named "INTEGER".
  49. Using the AUTOINCREMENT Keyword
  50. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  51. To specifically render the AUTOINCREMENT keyword on the primary key column
  52. when rendering DDL, add the flag ``sqlite_autoincrement=True`` to the Table
  53. construct::
  54. Table(
  55. "sometable",
  56. metadata,
  57. Column("id", Integer, primary_key=True),
  58. sqlite_autoincrement=True,
  59. )
  60. Allowing autoincrement behavior SQLAlchemy types other than Integer/INTEGER
  61. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  62. SQLite's typing model is based on naming conventions. Among other things, this
  63. means that any type name which contains the substring ``"INT"`` will be
  64. determined to be of "integer affinity". A type named ``"BIGINT"``,
  65. ``"SPECIAL_INT"`` or even ``"XYZINTQPR"``, will be considered by SQLite to be
  66. of "integer" affinity. However, **the SQLite autoincrement feature, whether
  67. implicitly or explicitly enabled, requires that the name of the column's type
  68. is exactly the string "INTEGER"**. Therefore, if an application uses a type
  69. like :class:`.BigInteger` for a primary key, on SQLite this type will need to
  70. be rendered as the name ``"INTEGER"`` when emitting the initial ``CREATE
  71. TABLE`` statement in order for the autoincrement behavior to be available.
  72. One approach to achieve this is to use :class:`.Integer` on SQLite
  73. only using :meth:`.TypeEngine.with_variant`::
  74. table = Table(
  75. "my_table",
  76. metadata,
  77. Column(
  78. "id",
  79. BigInteger().with_variant(Integer, "sqlite"),
  80. primary_key=True,
  81. ),
  82. )
  83. Another is to use a subclass of :class:`.BigInteger` that overrides its DDL
  84. name to be ``INTEGER`` when compiled against SQLite::
  85. from sqlalchemy import BigInteger
  86. from sqlalchemy.ext.compiler import compiles
  87. class SLBigInteger(BigInteger):
  88. pass
  89. @compiles(SLBigInteger, "sqlite")
  90. def bi_c(element, compiler, **kw):
  91. return "INTEGER"
  92. @compiles(SLBigInteger)
  93. def bi_c(element, compiler, **kw):
  94. return compiler.visit_BIGINT(element, **kw)
  95. table = Table(
  96. "my_table", metadata, Column("id", SLBigInteger(), primary_key=True)
  97. )
  98. .. seealso::
  99. :meth:`.TypeEngine.with_variant`
  100. :ref:`sqlalchemy.ext.compiler_toplevel`
  101. `Datatypes In SQLite Version 3 <https://sqlite.org/datatype3.html>`_
  102. .. _sqlite_transactions:
  103. Transactions with SQLite and the sqlite3 driver
  104. -----------------------------------------------
  105. As a file-based database, SQLite's approach to transactions differs from
  106. traditional databases in many ways. Additionally, the ``sqlite3`` driver
  107. standard with Python (as well as the async version ``aiosqlite`` which builds
  108. on top of it) has several quirks, workarounds, and API features in the
  109. area of transaction control, all of which generally need to be addressed when
  110. constructing a SQLAlchemy application that uses SQLite.
  111. Legacy Transaction Mode with the sqlite3 driver
  112. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  113. The most important aspect of transaction handling with the sqlite3 driver is
  114. that it defaults (which will continue through Python 3.15 before being
  115. removed in Python 3.16) to legacy transactional behavior which does
  116. not strictly follow :pep:`249`. The way in which the driver diverges from the
  117. PEP is that it does not "begin" a transaction automatically as dictated by
  118. :pep:`249` except in the case of DML statements, e.g. INSERT, UPDATE, and
  119. DELETE. Normally, :pep:`249` dictates that a BEGIN must be emitted upon
  120. the first SQL statement of any kind, so that all subsequent operations will
  121. be established within a transaction until ``connection.commit()`` has been
  122. called. The ``sqlite3`` driver, in an effort to be easier to use in
  123. highly concurrent environments, skips this step for DQL (e.g. SELECT) statements,
  124. and also skips it for DDL (e.g. CREATE TABLE etc.) statements for more legacy
  125. reasons. Statements such as SAVEPOINT are also skipped.
  126. In modern versions of the ``sqlite3`` driver as of Python 3.12, this legacy
  127. mode of operation is referred to as
  128. `"legacy transaction control" <https://docs.python.org/3/library/sqlite3.html#sqlite3-transaction-control-isolation-level>`_, and is in
  129. effect by default due to the ``Connection.autocommit`` parameter being set to
  130. the constant ``sqlite3.LEGACY_TRANSACTION_CONTROL``. Prior to Python 3.12,
  131. the ``Connection.autocommit`` attribute did not exist.
  132. The implications of legacy transaction mode include:
  133. * **Incorrect support for transactional DDL** - statements like CREATE TABLE, ALTER TABLE,
  134. CREATE INDEX etc. will not automatically BEGIN a transaction if one were not
  135. started already, leading to the changes by each statement being
  136. "autocommitted" immediately unless BEGIN were otherwise emitted first. Very
  137. old (pre Python 3.6) versions of SQLite would also force a COMMIT for these
  138. operations even if a transaction were present, however this is no longer the
  139. case.
  140. * **SERIALIZABLE behavior not fully functional** - SQLite's transaction isolation
  141. behavior is normally consistent with SERIALIZABLE isolation, as it is a file-
  142. based system that locks the database file entirely for write operations,
  143. preventing COMMIT until all reader transactions (and associated file locks)
  144. have completed. However, sqlite3's legacy transaction mode fails to emit BEGIN for SELECT
  145. statements, which causes these SELECT statements to no longer be "repeatable",
  146. failing one of the consistency guarantees of SERIALIZABLE.
  147. * **Incorrect behavior for SAVEPOINT** - as the SAVEPOINT statement does not
  148. imply a BEGIN, a new SAVEPOINT emitted before a BEGIN will function on its
  149. own but fails to participate in the enclosing transaction, meaning a ROLLBACK
  150. of the transaction will not rollback elements that were part of a released
  151. savepoint.
  152. Legacy transaction mode first existed in order to faciliate working around
  153. SQLite's file locks. Because SQLite relies upon whole-file locks, it is easy to
  154. get "database is locked" errors, particularly when newer features like "write
  155. ahead logging" are disabled. This is a key reason why ``sqlite3``'s legacy
  156. transaction mode is still the default mode of operation; disabling it will
  157. produce behavior that is more susceptible to locked database errors. However
  158. note that **legacy transaction mode will no longer be the default** in a future
  159. Python version (3.16 as of this writing).
  160. .. _sqlite_enabling_transactions:
  161. Enabling Non-Legacy SQLite Transactional Modes with the sqlite3 or aiosqlite driver
  162. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  163. Current SQLAlchemy support allows either for setting the
  164. ``.Connection.autocommit`` attribute, most directly by using a
  165. :func:`._sa.create_engine` parameter, or if on an older version of Python where
  166. the attribute is not available, using event hooks to control the behavior of
  167. BEGIN.
  168. * **Enabling modern sqlite3 transaction control via the autocommit connect parameter** (Python 3.12 and above)
  169. To use SQLite in the mode described at `Transaction control via the autocommit attribute <https://docs.python.org/3/library/sqlite3.html#transaction-control-via-the-autocommit-attribute>`_,
  170. the most straightforward approach is to set the attribute to its recommended value
  171. of ``False`` at the connect level using :paramref:`_sa.create_engine.connect_args``::
  172. from sqlalchemy import create_engine
  173. engine = create_engine(
  174. "sqlite:///myfile.db", connect_args={"autocommit": False}
  175. )
  176. This parameter is also passed through when using the aiosqlite driver::
  177. from sqlalchemy.ext.asyncio import create_async_engine
  178. engine = create_async_engine(
  179. "sqlite+aiosqlite:///myfile.db", connect_args={"autocommit": False}
  180. )
  181. The parameter can also be set at the attribute level using the :meth:`.PoolEvents.connect`
  182. event hook, however this will only work for sqlite3, as aiosqlite does not yet expose this
  183. attribute on its ``Connection`` object::
  184. from sqlalchemy import create_engine, event
  185. engine = create_engine("sqlite:///myfile.db")
  186. @event.listens_for(engine, "connect")
  187. def do_connect(dbapi_connection, connection_record):
  188. # enable autocommit=False mode
  189. dbapi_connection.autocommit = False
  190. * **Using SQLAlchemy to emit BEGIN in lieu of SQLite's transaction control** (all Python versions, sqlite3 and aiosqlite)
  191. For older versions of ``sqlite3`` or for cross-compatiblity with older and
  192. newer versions, SQLAlchemy can also take over the job of transaction control.
  193. This is achieved by using the :meth:`.ConnectionEvents.begin` hook
  194. to emit the "BEGIN" command directly, while also disabling SQLite's control
  195. of this command using the :meth:`.PoolEvents.connect` event hook to set the
  196. ``Connection.isolation_level`` attribute to ``None``::
  197. from sqlalchemy import create_engine, event
  198. engine = create_engine("sqlite:///myfile.db")
  199. @event.listens_for(engine, "connect")
  200. def do_connect(dbapi_connection, connection_record):
  201. # disable sqlite3's emitting of the BEGIN statement entirely.
  202. dbapi_connection.isolation_level = None
  203. @event.listens_for(engine, "begin")
  204. def do_begin(conn):
  205. # emit our own BEGIN. sqlite3 still emits COMMIT/ROLLBACK correctly
  206. conn.exec_driver_sql("BEGIN")
  207. When using the asyncio variant ``aiosqlite``, refer to ``engine.sync_engine``
  208. as in the example below::
  209. from sqlalchemy import create_engine, event
  210. from sqlalchemy.ext.asyncio import create_async_engine
  211. engine = create_async_engine("sqlite+aiosqlite:///myfile.db")
  212. @event.listens_for(engine.sync_engine, "connect")
  213. def do_connect(dbapi_connection, connection_record):
  214. # disable aiosqlite's emitting of the BEGIN statement entirely.
  215. dbapi_connection.isolation_level = None
  216. @event.listens_for(engine.sync_engine, "begin")
  217. def do_begin(conn):
  218. # emit our own BEGIN. aiosqlite still emits COMMIT/ROLLBACK correctly
  219. conn.exec_driver_sql("BEGIN")
  220. .. _sqlite_isolation_level:
  221. Using SQLAlchemy's Driver Level AUTOCOMMIT Feature with SQLite
  222. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  223. SQLAlchemy has a comprehensive database isolation feature with optional
  224. autocommit support that is introduced in the section :ref:`dbapi_autocommit`.
  225. For the ``sqlite3`` and ``aiosqlite`` drivers, SQLAlchemy only includes
  226. built-in support for "AUTOCOMMIT". Note that this mode is currently incompatible
  227. with the non-legacy isolation mode hooks documented in the previous
  228. section at :ref:`sqlite_enabling_transactions`.
  229. To use the ``sqlite3`` driver with SQLAlchemy driver-level autocommit,
  230. create an engine setting the :paramref:`_sa.create_engine.isolation_level`
  231. parameter to "AUTOCOMMIT"::
  232. eng = create_engine("sqlite:///myfile.db", isolation_level="AUTOCOMMIT")
  233. When using the above mode, any event hooks that set the sqlite3 ``Connection.autocommit``
  234. parameter away from its default of ``sqlite3.LEGACY_TRANSACTION_CONTROL``
  235. as well as hooks that emit ``BEGIN`` should be disabled.
  236. Additional Reading for SQLite / sqlite3 transaction control
  237. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  238. Links with important information on SQLite, the sqlite3 driver,
  239. as well as long historical conversations on how things got to their current state:
  240. * `Isolation in SQLite <https://www.sqlite.org/isolation.html>`_ - on the SQLite website
  241. * `Transaction control <https://docs.python.org/3/library/sqlite3.html#transaction-control>`_ - describes the sqlite3 autocommit attribute as well
  242. as the legacy isolation_level attribute.
  243. * `sqlite3 SELECT does not BEGIN a transaction, but should according to spec <https://github.com/python/cpython/issues/54133>`_ - imported Python standard library issue on github
  244. * `sqlite3 module breaks transactions and potentially corrupts data <https://github.com/python/cpython/issues/54949>`_ - imported Python standard library issue on github
  245. INSERT/UPDATE/DELETE...RETURNING
  246. ---------------------------------
  247. The SQLite dialect supports SQLite 3.35's ``INSERT|UPDATE|DELETE..RETURNING``
  248. syntax. ``INSERT..RETURNING`` may be used
  249. automatically in some cases in order to fetch newly generated identifiers in
  250. place of the traditional approach of using ``cursor.lastrowid``, however
  251. ``cursor.lastrowid`` is currently still preferred for simple single-statement
  252. cases for its better performance.
  253. To specify an explicit ``RETURNING`` clause, use the
  254. :meth:`._UpdateBase.returning` method on a per-statement basis::
  255. # INSERT..RETURNING
  256. result = connection.execute(
  257. table.insert().values(name="foo").returning(table.c.col1, table.c.col2)
  258. )
  259. print(result.all())
  260. # UPDATE..RETURNING
  261. result = connection.execute(
  262. table.update()
  263. .where(table.c.name == "foo")
  264. .values(name="bar")
  265. .returning(table.c.col1, table.c.col2)
  266. )
  267. print(result.all())
  268. # DELETE..RETURNING
  269. result = connection.execute(
  270. table.delete()
  271. .where(table.c.name == "foo")
  272. .returning(table.c.col1, table.c.col2)
  273. )
  274. print(result.all())
  275. .. versionadded:: 2.0 Added support for SQLite RETURNING
  276. .. _sqlite_foreign_keys:
  277. Foreign Key Support
  278. -------------------
  279. SQLite supports FOREIGN KEY syntax when emitting CREATE statements for tables,
  280. however by default these constraints have no effect on the operation of the
  281. table.
  282. Constraint checking on SQLite has three prerequisites:
  283. * At least version 3.6.19 of SQLite must be in use
  284. * The SQLite library must be compiled *without* the SQLITE_OMIT_FOREIGN_KEY
  285. or SQLITE_OMIT_TRIGGER symbols enabled.
  286. * The ``PRAGMA foreign_keys = ON`` statement must be emitted on all
  287. connections before use -- including the initial call to
  288. :meth:`sqlalchemy.schema.MetaData.create_all`.
  289. SQLAlchemy allows for the ``PRAGMA`` statement to be emitted automatically for
  290. new connections through the usage of events::
  291. from sqlalchemy.engine import Engine
  292. from sqlalchemy import event
  293. @event.listens_for(Engine, "connect")
  294. def set_sqlite_pragma(dbapi_connection, connection_record):
  295. # the sqlite3 driver will not set PRAGMA foreign_keys
  296. # if autocommit=False; set to True temporarily
  297. ac = dbapi_connection.autocommit
  298. dbapi_connection.autocommit = True
  299. cursor = dbapi_connection.cursor()
  300. cursor.execute("PRAGMA foreign_keys=ON")
  301. cursor.close()
  302. # restore previous autocommit setting
  303. dbapi_connection.autocommit = ac
  304. .. warning::
  305. When SQLite foreign keys are enabled, it is **not possible**
  306. to emit CREATE or DROP statements for tables that contain
  307. mutually-dependent foreign key constraints;
  308. to emit the DDL for these tables requires that ALTER TABLE be used to
  309. create or drop these constraints separately, for which SQLite has
  310. no support.
  311. .. seealso::
  312. `SQLite Foreign Key Support <https://www.sqlite.org/foreignkeys.html>`_
  313. - on the SQLite web site.
  314. :ref:`event_toplevel` - SQLAlchemy event API.
  315. :ref:`use_alter` - more information on SQLAlchemy's facilities for handling
  316. mutually-dependent foreign key constraints.
  317. .. _sqlite_on_conflict_ddl:
  318. ON CONFLICT support for constraints
  319. -----------------------------------
  320. .. seealso:: This section describes the :term:`DDL` version of "ON CONFLICT" for
  321. SQLite, which occurs within a CREATE TABLE statement. For "ON CONFLICT" as
  322. applied to an INSERT statement, see :ref:`sqlite_on_conflict_insert`.
  323. SQLite supports a non-standard DDL clause known as ON CONFLICT which can be applied
  324. to primary key, unique, check, and not null constraints. In DDL, it is
  325. rendered either within the "CONSTRAINT" clause or within the column definition
  326. itself depending on the location of the target constraint. To render this
  327. clause within DDL, the extension parameter ``sqlite_on_conflict`` can be
  328. specified with a string conflict resolution algorithm within the
  329. :class:`.PrimaryKeyConstraint`, :class:`.UniqueConstraint`,
  330. :class:`.CheckConstraint` objects. Within the :class:`_schema.Column` object,
  331. there
  332. are individual parameters ``sqlite_on_conflict_not_null``,
  333. ``sqlite_on_conflict_primary_key``, ``sqlite_on_conflict_unique`` which each
  334. correspond to the three types of relevant constraint types that can be
  335. indicated from a :class:`_schema.Column` object.
  336. .. seealso::
  337. `ON CONFLICT <https://www.sqlite.org/lang_conflict.html>`_ - in the SQLite
  338. documentation
  339. .. versionadded:: 1.3
  340. The ``sqlite_on_conflict`` parameters accept a string argument which is just
  341. the resolution name to be chosen, which on SQLite can be one of ROLLBACK,
  342. ABORT, FAIL, IGNORE, and REPLACE. For example, to add a UNIQUE constraint
  343. that specifies the IGNORE algorithm::
  344. some_table = Table(
  345. "some_table",
  346. metadata,
  347. Column("id", Integer, primary_key=True),
  348. Column("data", Integer),
  349. UniqueConstraint("id", "data", sqlite_on_conflict="IGNORE"),
  350. )
  351. The above renders CREATE TABLE DDL as:
  352. .. sourcecode:: sql
  353. CREATE TABLE some_table (
  354. id INTEGER NOT NULL,
  355. data INTEGER,
  356. PRIMARY KEY (id),
  357. UNIQUE (id, data) ON CONFLICT IGNORE
  358. )
  359. When using the :paramref:`_schema.Column.unique`
  360. flag to add a UNIQUE constraint
  361. to a single column, the ``sqlite_on_conflict_unique`` parameter can
  362. be added to the :class:`_schema.Column` as well, which will be added to the
  363. UNIQUE constraint in the DDL::
  364. some_table = Table(
  365. "some_table",
  366. metadata,
  367. Column("id", Integer, primary_key=True),
  368. Column(
  369. "data", Integer, unique=True, sqlite_on_conflict_unique="IGNORE"
  370. ),
  371. )
  372. rendering:
  373. .. sourcecode:: sql
  374. CREATE TABLE some_table (
  375. id INTEGER NOT NULL,
  376. data INTEGER,
  377. PRIMARY KEY (id),
  378. UNIQUE (data) ON CONFLICT IGNORE
  379. )
  380. To apply the FAIL algorithm for a NOT NULL constraint,
  381. ``sqlite_on_conflict_not_null`` is used::
  382. some_table = Table(
  383. "some_table",
  384. metadata,
  385. Column("id", Integer, primary_key=True),
  386. Column(
  387. "data", Integer, nullable=False, sqlite_on_conflict_not_null="FAIL"
  388. ),
  389. )
  390. this renders the column inline ON CONFLICT phrase:
  391. .. sourcecode:: sql
  392. CREATE TABLE some_table (
  393. id INTEGER NOT NULL,
  394. data INTEGER NOT NULL ON CONFLICT FAIL,
  395. PRIMARY KEY (id)
  396. )
  397. Similarly, for an inline primary key, use ``sqlite_on_conflict_primary_key``::
  398. some_table = Table(
  399. "some_table",
  400. metadata,
  401. Column(
  402. "id",
  403. Integer,
  404. primary_key=True,
  405. sqlite_on_conflict_primary_key="FAIL",
  406. ),
  407. )
  408. SQLAlchemy renders the PRIMARY KEY constraint separately, so the conflict
  409. resolution algorithm is applied to the constraint itself:
  410. .. sourcecode:: sql
  411. CREATE TABLE some_table (
  412. id INTEGER NOT NULL,
  413. PRIMARY KEY (id) ON CONFLICT FAIL
  414. )
  415. .. _sqlite_on_conflict_insert:
  416. INSERT...ON CONFLICT (Upsert)
  417. -----------------------------
  418. .. seealso:: This section describes the :term:`DML` version of "ON CONFLICT" for
  419. SQLite, which occurs within an INSERT statement. For "ON CONFLICT" as
  420. applied to a CREATE TABLE statement, see :ref:`sqlite_on_conflict_ddl`.
  421. From version 3.24.0 onwards, SQLite supports "upserts" (update or insert)
  422. of rows into a table via the ``ON CONFLICT`` clause of the ``INSERT``
  423. statement. A candidate row will only be inserted if that row does not violate
  424. any unique or primary key constraints. In the case of a unique constraint violation, a
  425. secondary action can occur which can be either "DO UPDATE", indicating that
  426. the data in the target row should be updated, or "DO NOTHING", which indicates
  427. to silently skip this row.
  428. Conflicts are determined using columns that are part of existing unique
  429. constraints and indexes. These constraints are identified by stating the
  430. columns and conditions that comprise the indexes.
  431. SQLAlchemy provides ``ON CONFLICT`` support via the SQLite-specific
  432. :func:`_sqlite.insert()` function, which provides
  433. the generative methods :meth:`_sqlite.Insert.on_conflict_do_update`
  434. and :meth:`_sqlite.Insert.on_conflict_do_nothing`:
  435. .. sourcecode:: pycon+sql
  436. >>> from sqlalchemy.dialects.sqlite import insert
  437. >>> insert_stmt = insert(my_table).values(
  438. ... id="some_existing_id", data="inserted value"
  439. ... )
  440. >>> do_update_stmt = insert_stmt.on_conflict_do_update(
  441. ... index_elements=["id"], set_=dict(data="updated value")
  442. ... )
  443. >>> print(do_update_stmt)
  444. {printsql}INSERT INTO my_table (id, data) VALUES (?, ?)
  445. ON CONFLICT (id) DO UPDATE SET data = ?{stop}
  446. >>> do_nothing_stmt = insert_stmt.on_conflict_do_nothing(index_elements=["id"])
  447. >>> print(do_nothing_stmt)
  448. {printsql}INSERT INTO my_table (id, data) VALUES (?, ?)
  449. ON CONFLICT (id) DO NOTHING
  450. .. versionadded:: 1.4
  451. .. seealso::
  452. `Upsert
  453. <https://sqlite.org/lang_UPSERT.html>`_
  454. - in the SQLite documentation.
  455. Specifying the Target
  456. ^^^^^^^^^^^^^^^^^^^^^
  457. Both methods supply the "target" of the conflict using column inference:
  458. * The :paramref:`_sqlite.Insert.on_conflict_do_update.index_elements` argument
  459. specifies a sequence containing string column names, :class:`_schema.Column`
  460. objects, and/or SQL expression elements, which would identify a unique index
  461. or unique constraint.
  462. * When using :paramref:`_sqlite.Insert.on_conflict_do_update.index_elements`
  463. to infer an index, a partial index can be inferred by also specifying the
  464. :paramref:`_sqlite.Insert.on_conflict_do_update.index_where` parameter:
  465. .. sourcecode:: pycon+sql
  466. >>> stmt = insert(my_table).values(user_email="a@b.com", data="inserted data")
  467. >>> do_update_stmt = stmt.on_conflict_do_update(
  468. ... index_elements=[my_table.c.user_email],
  469. ... index_where=my_table.c.user_email.like("%@gmail.com"),
  470. ... set_=dict(data=stmt.excluded.data),
  471. ... )
  472. >>> print(do_update_stmt)
  473. {printsql}INSERT INTO my_table (data, user_email) VALUES (?, ?)
  474. ON CONFLICT (user_email)
  475. WHERE user_email LIKE '%@gmail.com'
  476. DO UPDATE SET data = excluded.data
  477. The SET Clause
  478. ^^^^^^^^^^^^^^^
  479. ``ON CONFLICT...DO UPDATE`` is used to perform an update of the already
  480. existing row, using any combination of new values as well as values
  481. from the proposed insertion. These values are specified using the
  482. :paramref:`_sqlite.Insert.on_conflict_do_update.set_` parameter. This
  483. parameter accepts a dictionary which consists of direct values
  484. for UPDATE:
  485. .. sourcecode:: pycon+sql
  486. >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
  487. >>> do_update_stmt = stmt.on_conflict_do_update(
  488. ... index_elements=["id"], set_=dict(data="updated value")
  489. ... )
  490. >>> print(do_update_stmt)
  491. {printsql}INSERT INTO my_table (id, data) VALUES (?, ?)
  492. ON CONFLICT (id) DO UPDATE SET data = ?
  493. .. warning::
  494. The :meth:`_sqlite.Insert.on_conflict_do_update` method does **not** take
  495. into account Python-side default UPDATE values or generation functions,
  496. e.g. those specified using :paramref:`_schema.Column.onupdate`. These
  497. values will not be exercised for an ON CONFLICT style of UPDATE, unless
  498. they are manually specified in the
  499. :paramref:`_sqlite.Insert.on_conflict_do_update.set_` dictionary.
  500. Updating using the Excluded INSERT Values
  501. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  502. In order to refer to the proposed insertion row, the special alias
  503. :attr:`~.sqlite.Insert.excluded` is available as an attribute on
  504. the :class:`_sqlite.Insert` object; this object creates an "excluded." prefix
  505. on a column, that informs the DO UPDATE to update the row with the value that
  506. would have been inserted had the constraint not failed:
  507. .. sourcecode:: pycon+sql
  508. >>> stmt = insert(my_table).values(
  509. ... id="some_id", data="inserted value", author="jlh"
  510. ... )
  511. >>> do_update_stmt = stmt.on_conflict_do_update(
  512. ... index_elements=["id"],
  513. ... set_=dict(data="updated value", author=stmt.excluded.author),
  514. ... )
  515. >>> print(do_update_stmt)
  516. {printsql}INSERT INTO my_table (id, data, author) VALUES (?, ?, ?)
  517. ON CONFLICT (id) DO UPDATE SET data = ?, author = excluded.author
  518. Additional WHERE Criteria
  519. ^^^^^^^^^^^^^^^^^^^^^^^^^
  520. The :meth:`_sqlite.Insert.on_conflict_do_update` method also accepts
  521. a WHERE clause using the :paramref:`_sqlite.Insert.on_conflict_do_update.where`
  522. parameter, which will limit those rows which receive an UPDATE:
  523. .. sourcecode:: pycon+sql
  524. >>> stmt = insert(my_table).values(
  525. ... id="some_id", data="inserted value", author="jlh"
  526. ... )
  527. >>> on_update_stmt = stmt.on_conflict_do_update(
  528. ... index_elements=["id"],
  529. ... set_=dict(data="updated value", author=stmt.excluded.author),
  530. ... where=(my_table.c.status == 2),
  531. ... )
  532. >>> print(on_update_stmt)
  533. {printsql}INSERT INTO my_table (id, data, author) VALUES (?, ?, ?)
  534. ON CONFLICT (id) DO UPDATE SET data = ?, author = excluded.author
  535. WHERE my_table.status = ?
  536. Skipping Rows with DO NOTHING
  537. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  538. ``ON CONFLICT`` may be used to skip inserting a row entirely
  539. if any conflict with a unique constraint occurs; below this is illustrated
  540. using the :meth:`_sqlite.Insert.on_conflict_do_nothing` method:
  541. .. sourcecode:: pycon+sql
  542. >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
  543. >>> stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
  544. >>> print(stmt)
  545. {printsql}INSERT INTO my_table (id, data) VALUES (?, ?) ON CONFLICT (id) DO NOTHING
  546. If ``DO NOTHING`` is used without specifying any columns or constraint,
  547. it has the effect of skipping the INSERT for any unique violation which
  548. occurs:
  549. .. sourcecode:: pycon+sql
  550. >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
  551. >>> stmt = stmt.on_conflict_do_nothing()
  552. >>> print(stmt)
  553. {printsql}INSERT INTO my_table (id, data) VALUES (?, ?) ON CONFLICT DO NOTHING
  554. .. _sqlite_type_reflection:
  555. Type Reflection
  556. ---------------
  557. SQLite types are unlike those of most other database backends, in that
  558. the string name of the type usually does not correspond to a "type" in a
  559. one-to-one fashion. Instead, SQLite links per-column typing behavior
  560. to one of five so-called "type affinities" based on a string matching
  561. pattern for the type.
  562. SQLAlchemy's reflection process, when inspecting types, uses a simple
  563. lookup table to link the keywords returned to provided SQLAlchemy types.
  564. This lookup table is present within the SQLite dialect as it is for all
  565. other dialects. However, the SQLite dialect has a different "fallback"
  566. routine for when a particular type name is not located in the lookup map;
  567. it instead implements the SQLite "type affinity" scheme located at
  568. https://www.sqlite.org/datatype3.html section 2.1.
  569. The provided typemap will make direct associations from an exact string
  570. name match for the following types:
  571. :class:`_types.BIGINT`, :class:`_types.BLOB`,
  572. :class:`_types.BOOLEAN`, :class:`_types.BOOLEAN`,
  573. :class:`_types.CHAR`, :class:`_types.DATE`,
  574. :class:`_types.DATETIME`, :class:`_types.FLOAT`,
  575. :class:`_types.DECIMAL`, :class:`_types.FLOAT`,
  576. :class:`_types.INTEGER`, :class:`_types.INTEGER`,
  577. :class:`_types.NUMERIC`, :class:`_types.REAL`,
  578. :class:`_types.SMALLINT`, :class:`_types.TEXT`,
  579. :class:`_types.TIME`, :class:`_types.TIMESTAMP`,
  580. :class:`_types.VARCHAR`, :class:`_types.NVARCHAR`,
  581. :class:`_types.NCHAR`
  582. When a type name does not match one of the above types, the "type affinity"
  583. lookup is used instead:
  584. * :class:`_types.INTEGER` is returned if the type name includes the
  585. string ``INT``
  586. * :class:`_types.TEXT` is returned if the type name includes the
  587. string ``CHAR``, ``CLOB`` or ``TEXT``
  588. * :class:`_types.NullType` is returned if the type name includes the
  589. string ``BLOB``
  590. * :class:`_types.REAL` is returned if the type name includes the string
  591. ``REAL``, ``FLOA`` or ``DOUB``.
  592. * Otherwise, the :class:`_types.NUMERIC` type is used.
  593. .. _sqlite_partial_index:
  594. Partial Indexes
  595. ---------------
  596. A partial index, e.g. one which uses a WHERE clause, can be specified
  597. with the DDL system using the argument ``sqlite_where``::
  598. tbl = Table("testtbl", m, Column("data", Integer))
  599. idx = Index(
  600. "test_idx1",
  601. tbl.c.data,
  602. sqlite_where=and_(tbl.c.data > 5, tbl.c.data < 10),
  603. )
  604. The index will be rendered at create time as:
  605. .. sourcecode:: sql
  606. CREATE INDEX test_idx1 ON testtbl (data)
  607. WHERE data > 5 AND data < 10
  608. .. _sqlite_dotted_column_names:
  609. Dotted Column Names
  610. -------------------
  611. Using table or column names that explicitly have periods in them is
  612. **not recommended**. While this is generally a bad idea for relational
  613. databases in general, as the dot is a syntactically significant character,
  614. the SQLite driver up until version **3.10.0** of SQLite has a bug which
  615. requires that SQLAlchemy filter out these dots in result sets.
  616. The bug, entirely outside of SQLAlchemy, can be illustrated thusly::
  617. import sqlite3
  618. assert sqlite3.sqlite_version_info < (
  619. 3,
  620. 10,
  621. 0,
  622. ), "bug is fixed in this version"
  623. conn = sqlite3.connect(":memory:")
  624. cursor = conn.cursor()
  625. cursor.execute("create table x (a integer, b integer)")
  626. cursor.execute("insert into x (a, b) values (1, 1)")
  627. cursor.execute("insert into x (a, b) values (2, 2)")
  628. cursor.execute("select x.a, x.b from x")
  629. assert [c[0] for c in cursor.description] == ["a", "b"]
  630. cursor.execute(
  631. """
  632. select x.a, x.b from x where a=1
  633. union
  634. select x.a, x.b from x where a=2
  635. """
  636. )
  637. assert [c[0] for c in cursor.description] == ["a", "b"], [
  638. c[0] for c in cursor.description
  639. ]
  640. The second assertion fails:
  641. .. sourcecode:: text
  642. Traceback (most recent call last):
  643. File "test.py", line 19, in <module>
  644. [c[0] for c in cursor.description]
  645. AssertionError: ['x.a', 'x.b']
  646. Where above, the driver incorrectly reports the names of the columns
  647. including the name of the table, which is entirely inconsistent vs.
  648. when the UNION is not present.
  649. SQLAlchemy relies upon column names being predictable in how they match
  650. to the original statement, so the SQLAlchemy dialect has no choice but
  651. to filter these out::
  652. from sqlalchemy import create_engine
  653. eng = create_engine("sqlite://")
  654. conn = eng.connect()
  655. conn.exec_driver_sql("create table x (a integer, b integer)")
  656. conn.exec_driver_sql("insert into x (a, b) values (1, 1)")
  657. conn.exec_driver_sql("insert into x (a, b) values (2, 2)")
  658. result = conn.exec_driver_sql("select x.a, x.b from x")
  659. assert result.keys() == ["a", "b"]
  660. result = conn.exec_driver_sql(
  661. """
  662. select x.a, x.b from x where a=1
  663. union
  664. select x.a, x.b from x where a=2
  665. """
  666. )
  667. assert result.keys() == ["a", "b"]
  668. Note that above, even though SQLAlchemy filters out the dots, *both
  669. names are still addressable*::
  670. >>> row = result.first()
  671. >>> row["a"]
  672. 1
  673. >>> row["x.a"]
  674. 1
  675. >>> row["b"]
  676. 1
  677. >>> row["x.b"]
  678. 1
  679. Therefore, the workaround applied by SQLAlchemy only impacts
  680. :meth:`_engine.CursorResult.keys` and :meth:`.Row.keys()` in the public API. In
  681. the very specific case where an application is forced to use column names that
  682. contain dots, and the functionality of :meth:`_engine.CursorResult.keys` and
  683. :meth:`.Row.keys()` is required to return these dotted names unmodified,
  684. the ``sqlite_raw_colnames`` execution option may be provided, either on a
  685. per-:class:`_engine.Connection` basis::
  686. result = conn.execution_options(sqlite_raw_colnames=True).exec_driver_sql(
  687. """
  688. select x.a, x.b from x where a=1
  689. union
  690. select x.a, x.b from x where a=2
  691. """
  692. )
  693. assert result.keys() == ["x.a", "x.b"]
  694. or on a per-:class:`_engine.Engine` basis::
  695. engine = create_engine(
  696. "sqlite://", execution_options={"sqlite_raw_colnames": True}
  697. )
  698. When using the per-:class:`_engine.Engine` execution option, note that
  699. **Core and ORM queries that use UNION may not function properly**.
  700. SQLite-specific table options
  701. -----------------------------
  702. One option for CREATE TABLE is supported directly by the SQLite
  703. dialect in conjunction with the :class:`_schema.Table` construct:
  704. * ``WITHOUT ROWID``::
  705. Table("some_table", metadata, ..., sqlite_with_rowid=False)
  706. *
  707. ``STRICT``::
  708. Table("some_table", metadata, ..., sqlite_strict=True)
  709. .. versionadded:: 2.0.37
  710. .. seealso::
  711. `SQLite CREATE TABLE options
  712. <https://www.sqlite.org/lang_createtable.html>`_
  713. .. _sqlite_include_internal:
  714. Reflecting internal schema tables
  715. ----------------------------------
  716. Reflection methods that return lists of tables will omit so-called
  717. "SQLite internal schema object" names, which are considered by SQLite
  718. as any object name that is prefixed with ``sqlite_``. An example of
  719. such an object is the ``sqlite_sequence`` table that's generated when
  720. the ``AUTOINCREMENT`` column parameter is used. In order to return
  721. these objects, the parameter ``sqlite_include_internal=True`` may be
  722. passed to methods such as :meth:`_schema.MetaData.reflect` or
  723. :meth:`.Inspector.get_table_names`.
  724. .. versionadded:: 2.0 Added the ``sqlite_include_internal=True`` parameter.
  725. Previously, these tables were not ignored by SQLAlchemy reflection
  726. methods.
  727. .. note::
  728. The ``sqlite_include_internal`` parameter does not refer to the
  729. "system" tables that are present in schemas such as ``sqlite_master``.
  730. .. seealso::
  731. `SQLite Internal Schema Objects <https://www.sqlite.org/fileformat2.html#intschema>`_ - in the SQLite
  732. documentation.
  733. ''' # noqa
  734. from __future__ import annotations
  735. import datetime
  736. import numbers
  737. import re
  738. from typing import Optional
  739. from .json import JSON
  740. from .json import JSONIndexType
  741. from .json import JSONPathType
  742. from ... import exc
  743. from ... import schema as sa_schema
  744. from ... import sql
  745. from ... import text
  746. from ... import types as sqltypes
  747. from ... import util
  748. from ...engine import default
  749. from ...engine import processors
  750. from ...engine import reflection
  751. from ...engine.reflection import ReflectionDefaults
  752. from ...sql import coercions
  753. from ...sql import compiler
  754. from ...sql import elements
  755. from ...sql import roles
  756. from ...sql import schema
  757. from ...types import BLOB # noqa
  758. from ...types import BOOLEAN # noqa
  759. from ...types import CHAR # noqa
  760. from ...types import DECIMAL # noqa
  761. from ...types import FLOAT # noqa
  762. from ...types import INTEGER # noqa
  763. from ...types import NUMERIC # noqa
  764. from ...types import REAL # noqa
  765. from ...types import SMALLINT # noqa
  766. from ...types import TEXT # noqa
  767. from ...types import TIMESTAMP # noqa
  768. from ...types import VARCHAR # noqa
  769. class _SQliteJson(JSON):
  770. def result_processor(self, dialect, coltype):
  771. default_processor = super().result_processor(dialect, coltype)
  772. def process(value):
  773. try:
  774. return default_processor(value)
  775. except TypeError:
  776. if isinstance(value, numbers.Number):
  777. return value
  778. else:
  779. raise
  780. return process
  781. class _DateTimeMixin:
  782. _reg = None
  783. _storage_format = None
  784. def __init__(self, storage_format=None, regexp=None, **kw):
  785. super().__init__(**kw)
  786. if regexp is not None:
  787. self._reg = re.compile(regexp)
  788. if storage_format is not None:
  789. self._storage_format = storage_format
  790. @property
  791. def format_is_text_affinity(self):
  792. """return True if the storage format will automatically imply
  793. a TEXT affinity.
  794. If the storage format contains no non-numeric characters,
  795. it will imply a NUMERIC storage format on SQLite; in this case,
  796. the type will generate its DDL as DATE_CHAR, DATETIME_CHAR,
  797. TIME_CHAR.
  798. """
  799. spec = self._storage_format % {
  800. "year": 0,
  801. "month": 0,
  802. "day": 0,
  803. "hour": 0,
  804. "minute": 0,
  805. "second": 0,
  806. "microsecond": 0,
  807. }
  808. return bool(re.search(r"[^0-9]", spec))
  809. def adapt(self, cls, **kw):
  810. if issubclass(cls, _DateTimeMixin):
  811. if self._storage_format:
  812. kw["storage_format"] = self._storage_format
  813. if self._reg:
  814. kw["regexp"] = self._reg
  815. return super().adapt(cls, **kw)
  816. def literal_processor(self, dialect):
  817. bp = self.bind_processor(dialect)
  818. def process(value):
  819. return "'%s'" % bp(value)
  820. return process
  821. class DATETIME(_DateTimeMixin, sqltypes.DateTime):
  822. r"""Represent a Python datetime object in SQLite using a string.
  823. The default string storage format is::
  824. "%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  825. e.g.:
  826. .. sourcecode:: text
  827. 2021-03-15 12:05:57.105542
  828. The incoming storage format is by default parsed using the
  829. Python ``datetime.fromisoformat()`` function.
  830. .. versionchanged:: 2.0 ``datetime.fromisoformat()`` is used for default
  831. datetime string parsing.
  832. The storage format can be customized to some degree using the
  833. ``storage_format`` and ``regexp`` parameters, such as::
  834. import re
  835. from sqlalchemy.dialects.sqlite import DATETIME
  836. dt = DATETIME(
  837. storage_format=(
  838. "%(year)04d/%(month)02d/%(day)02d %(hour)02d:%(minute)02d:%(second)02d"
  839. ),
  840. regexp=r"(\d+)/(\d+)/(\d+) (\d+)-(\d+)-(\d+)",
  841. )
  842. :param truncate_microseconds: when ``True`` microseconds will be truncated
  843. from the datetime. Can't be specified together with ``storage_format``
  844. or ``regexp``.
  845. :param storage_format: format string which will be applied to the dict
  846. with keys year, month, day, hour, minute, second, and microsecond.
  847. :param regexp: regular expression which will be applied to incoming result
  848. rows, replacing the use of ``datetime.fromisoformat()`` to parse incoming
  849. strings. If the regexp contains named groups, the resulting match dict is
  850. applied to the Python datetime() constructor as keyword arguments.
  851. Otherwise, if positional groups are used, the datetime() constructor
  852. is called with positional arguments via
  853. ``*map(int, match_obj.groups(0))``.
  854. """ # noqa
  855. _storage_format = (
  856. "%(year)04d-%(month)02d-%(day)02d "
  857. "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  858. )
  859. def __init__(self, *args, **kwargs):
  860. truncate_microseconds = kwargs.pop("truncate_microseconds", False)
  861. super().__init__(*args, **kwargs)
  862. if truncate_microseconds:
  863. assert "storage_format" not in kwargs, (
  864. "You can specify only "
  865. "one of truncate_microseconds or storage_format."
  866. )
  867. assert "regexp" not in kwargs, (
  868. "You can specify only one of "
  869. "truncate_microseconds or regexp."
  870. )
  871. self._storage_format = (
  872. "%(year)04d-%(month)02d-%(day)02d "
  873. "%(hour)02d:%(minute)02d:%(second)02d"
  874. )
  875. def bind_processor(self, dialect):
  876. datetime_datetime = datetime.datetime
  877. datetime_date = datetime.date
  878. format_ = self._storage_format
  879. def process(value):
  880. if value is None:
  881. return None
  882. elif isinstance(value, datetime_datetime):
  883. return format_ % {
  884. "year": value.year,
  885. "month": value.month,
  886. "day": value.day,
  887. "hour": value.hour,
  888. "minute": value.minute,
  889. "second": value.second,
  890. "microsecond": value.microsecond,
  891. }
  892. elif isinstance(value, datetime_date):
  893. return format_ % {
  894. "year": value.year,
  895. "month": value.month,
  896. "day": value.day,
  897. "hour": 0,
  898. "minute": 0,
  899. "second": 0,
  900. "microsecond": 0,
  901. }
  902. else:
  903. raise TypeError(
  904. "SQLite DateTime type only accepts Python "
  905. "datetime and date objects as input."
  906. )
  907. return process
  908. def result_processor(self, dialect, coltype):
  909. if self._reg:
  910. return processors.str_to_datetime_processor_factory(
  911. self._reg, datetime.datetime
  912. )
  913. else:
  914. return processors.str_to_datetime
  915. class DATE(_DateTimeMixin, sqltypes.Date):
  916. r"""Represent a Python date object in SQLite using a string.
  917. The default string storage format is::
  918. "%(year)04d-%(month)02d-%(day)02d"
  919. e.g.:
  920. .. sourcecode:: text
  921. 2011-03-15
  922. The incoming storage format is by default parsed using the
  923. Python ``date.fromisoformat()`` function.
  924. .. versionchanged:: 2.0 ``date.fromisoformat()`` is used for default
  925. date string parsing.
  926. The storage format can be customized to some degree using the
  927. ``storage_format`` and ``regexp`` parameters, such as::
  928. import re
  929. from sqlalchemy.dialects.sqlite import DATE
  930. d = DATE(
  931. storage_format="%(month)02d/%(day)02d/%(year)04d",
  932. regexp=re.compile("(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)"),
  933. )
  934. :param storage_format: format string which will be applied to the
  935. dict with keys year, month, and day.
  936. :param regexp: regular expression which will be applied to
  937. incoming result rows, replacing the use of ``date.fromisoformat()`` to
  938. parse incoming strings. If the regexp contains named groups, the resulting
  939. match dict is applied to the Python date() constructor as keyword
  940. arguments. Otherwise, if positional groups are used, the date()
  941. constructor is called with positional arguments via
  942. ``*map(int, match_obj.groups(0))``.
  943. """
  944. _storage_format = "%(year)04d-%(month)02d-%(day)02d"
  945. def bind_processor(self, dialect):
  946. datetime_date = datetime.date
  947. format_ = self._storage_format
  948. def process(value):
  949. if value is None:
  950. return None
  951. elif isinstance(value, datetime_date):
  952. return format_ % {
  953. "year": value.year,
  954. "month": value.month,
  955. "day": value.day,
  956. }
  957. else:
  958. raise TypeError(
  959. "SQLite Date type only accepts Python "
  960. "date objects as input."
  961. )
  962. return process
  963. def result_processor(self, dialect, coltype):
  964. if self._reg:
  965. return processors.str_to_datetime_processor_factory(
  966. self._reg, datetime.date
  967. )
  968. else:
  969. return processors.str_to_date
  970. class TIME(_DateTimeMixin, sqltypes.Time):
  971. r"""Represent a Python time object in SQLite using a string.
  972. The default string storage format is::
  973. "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  974. e.g.:
  975. .. sourcecode:: text
  976. 12:05:57.10558
  977. The incoming storage format is by default parsed using the
  978. Python ``time.fromisoformat()`` function.
  979. .. versionchanged:: 2.0 ``time.fromisoformat()`` is used for default
  980. time string parsing.
  981. The storage format can be customized to some degree using the
  982. ``storage_format`` and ``regexp`` parameters, such as::
  983. import re
  984. from sqlalchemy.dialects.sqlite import TIME
  985. t = TIME(
  986. storage_format="%(hour)02d-%(minute)02d-%(second)02d-%(microsecond)06d",
  987. regexp=re.compile("(\d+)-(\d+)-(\d+)-(?:-(\d+))?"),
  988. )
  989. :param truncate_microseconds: when ``True`` microseconds will be truncated
  990. from the time. Can't be specified together with ``storage_format``
  991. or ``regexp``.
  992. :param storage_format: format string which will be applied to the dict
  993. with keys hour, minute, second, and microsecond.
  994. :param regexp: regular expression which will be applied to incoming result
  995. rows, replacing the use of ``datetime.fromisoformat()`` to parse incoming
  996. strings. If the regexp contains named groups, the resulting match dict is
  997. applied to the Python time() constructor as keyword arguments. Otherwise,
  998. if positional groups are used, the time() constructor is called with
  999. positional arguments via ``*map(int, match_obj.groups(0))``.
  1000. """
  1001. _storage_format = "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  1002. def __init__(self, *args, **kwargs):
  1003. truncate_microseconds = kwargs.pop("truncate_microseconds", False)
  1004. super().__init__(*args, **kwargs)
  1005. if truncate_microseconds:
  1006. assert "storage_format" not in kwargs, (
  1007. "You can specify only "
  1008. "one of truncate_microseconds or storage_format."
  1009. )
  1010. assert "regexp" not in kwargs, (
  1011. "You can specify only one of "
  1012. "truncate_microseconds or regexp."
  1013. )
  1014. self._storage_format = "%(hour)02d:%(minute)02d:%(second)02d"
  1015. def bind_processor(self, dialect):
  1016. datetime_time = datetime.time
  1017. format_ = self._storage_format
  1018. def process(value):
  1019. if value is None:
  1020. return None
  1021. elif isinstance(value, datetime_time):
  1022. return format_ % {
  1023. "hour": value.hour,
  1024. "minute": value.minute,
  1025. "second": value.second,
  1026. "microsecond": value.microsecond,
  1027. }
  1028. else:
  1029. raise TypeError(
  1030. "SQLite Time type only accepts Python "
  1031. "time objects as input."
  1032. )
  1033. return process
  1034. def result_processor(self, dialect, coltype):
  1035. if self._reg:
  1036. return processors.str_to_datetime_processor_factory(
  1037. self._reg, datetime.time
  1038. )
  1039. else:
  1040. return processors.str_to_time
  1041. colspecs = {
  1042. sqltypes.Date: DATE,
  1043. sqltypes.DateTime: DATETIME,
  1044. sqltypes.JSON: _SQliteJson,
  1045. sqltypes.JSON.JSONIndexType: JSONIndexType,
  1046. sqltypes.JSON.JSONPathType: JSONPathType,
  1047. sqltypes.Time: TIME,
  1048. }
  1049. ischema_names = {
  1050. "BIGINT": sqltypes.BIGINT,
  1051. "BLOB": sqltypes.BLOB,
  1052. "BOOL": sqltypes.BOOLEAN,
  1053. "BOOLEAN": sqltypes.BOOLEAN,
  1054. "CHAR": sqltypes.CHAR,
  1055. "DATE": sqltypes.DATE,
  1056. "DATE_CHAR": sqltypes.DATE,
  1057. "DATETIME": sqltypes.DATETIME,
  1058. "DATETIME_CHAR": sqltypes.DATETIME,
  1059. "DOUBLE": sqltypes.DOUBLE,
  1060. "DECIMAL": sqltypes.DECIMAL,
  1061. "FLOAT": sqltypes.FLOAT,
  1062. "INT": sqltypes.INTEGER,
  1063. "INTEGER": sqltypes.INTEGER,
  1064. "JSON": JSON,
  1065. "NUMERIC": sqltypes.NUMERIC,
  1066. "REAL": sqltypes.REAL,
  1067. "SMALLINT": sqltypes.SMALLINT,
  1068. "TEXT": sqltypes.TEXT,
  1069. "TIME": sqltypes.TIME,
  1070. "TIME_CHAR": sqltypes.TIME,
  1071. "TIMESTAMP": sqltypes.TIMESTAMP,
  1072. "VARCHAR": sqltypes.VARCHAR,
  1073. "NVARCHAR": sqltypes.NVARCHAR,
  1074. "NCHAR": sqltypes.NCHAR,
  1075. }
  1076. class SQLiteCompiler(compiler.SQLCompiler):
  1077. extract_map = util.update_copy(
  1078. compiler.SQLCompiler.extract_map,
  1079. {
  1080. "month": "%m",
  1081. "day": "%d",
  1082. "year": "%Y",
  1083. "second": "%S",
  1084. "hour": "%H",
  1085. "doy": "%j",
  1086. "minute": "%M",
  1087. "epoch": "%s",
  1088. "dow": "%w",
  1089. "week": "%W",
  1090. },
  1091. )
  1092. def visit_truediv_binary(self, binary, operator, **kw):
  1093. return (
  1094. self.process(binary.left, **kw)
  1095. + " / "
  1096. + "(%s + 0.0)" % self.process(binary.right, **kw)
  1097. )
  1098. def visit_now_func(self, fn, **kw):
  1099. return "CURRENT_TIMESTAMP"
  1100. def visit_localtimestamp_func(self, func, **kw):
  1101. return "DATETIME(CURRENT_TIMESTAMP, 'localtime')"
  1102. def visit_true(self, expr, **kw):
  1103. return "1"
  1104. def visit_false(self, expr, **kw):
  1105. return "0"
  1106. def visit_char_length_func(self, fn, **kw):
  1107. return "length%s" % self.function_argspec(fn)
  1108. def visit_aggregate_strings_func(self, fn, **kw):
  1109. return "group_concat%s" % self.function_argspec(fn)
  1110. def visit_cast(self, cast, **kwargs):
  1111. if self.dialect.supports_cast:
  1112. return super().visit_cast(cast, **kwargs)
  1113. else:
  1114. return self.process(cast.clause, **kwargs)
  1115. def visit_extract(self, extract, **kw):
  1116. try:
  1117. return "CAST(STRFTIME('%s', %s) AS INTEGER)" % (
  1118. self.extract_map[extract.field],
  1119. self.process(extract.expr, **kw),
  1120. )
  1121. except KeyError as err:
  1122. raise exc.CompileError(
  1123. "%s is not a valid extract argument." % extract.field
  1124. ) from err
  1125. def returning_clause(
  1126. self,
  1127. stmt,
  1128. returning_cols,
  1129. *,
  1130. populate_result_map,
  1131. **kw,
  1132. ):
  1133. kw["include_table"] = False
  1134. return super().returning_clause(
  1135. stmt, returning_cols, populate_result_map=populate_result_map, **kw
  1136. )
  1137. def limit_clause(self, select, **kw):
  1138. text = ""
  1139. if select._limit_clause is not None:
  1140. text += "\n LIMIT " + self.process(select._limit_clause, **kw)
  1141. if select._offset_clause is not None:
  1142. if select._limit_clause is None:
  1143. text += "\n LIMIT " + self.process(sql.literal(-1))
  1144. text += " OFFSET " + self.process(select._offset_clause, **kw)
  1145. else:
  1146. text += " OFFSET " + self.process(sql.literal(0), **kw)
  1147. return text
  1148. def for_update_clause(self, select, **kw):
  1149. # sqlite has no "FOR UPDATE" AFAICT
  1150. return ""
  1151. def update_from_clause(
  1152. self, update_stmt, from_table, extra_froms, from_hints, **kw
  1153. ):
  1154. kw["asfrom"] = True
  1155. return "FROM " + ", ".join(
  1156. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  1157. for t in extra_froms
  1158. )
  1159. def visit_is_distinct_from_binary(self, binary, operator, **kw):
  1160. return "%s IS NOT %s" % (
  1161. self.process(binary.left),
  1162. self.process(binary.right),
  1163. )
  1164. def visit_is_not_distinct_from_binary(self, binary, operator, **kw):
  1165. return "%s IS %s" % (
  1166. self.process(binary.left),
  1167. self.process(binary.right),
  1168. )
  1169. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  1170. if binary.type._type_affinity is sqltypes.JSON:
  1171. expr = "JSON_QUOTE(JSON_EXTRACT(%s, %s))"
  1172. else:
  1173. expr = "JSON_EXTRACT(%s, %s)"
  1174. return expr % (
  1175. self.process(binary.left, **kw),
  1176. self.process(binary.right, **kw),
  1177. )
  1178. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  1179. if binary.type._type_affinity is sqltypes.JSON:
  1180. expr = "JSON_QUOTE(JSON_EXTRACT(%s, %s))"
  1181. else:
  1182. expr = "JSON_EXTRACT(%s, %s)"
  1183. return expr % (
  1184. self.process(binary.left, **kw),
  1185. self.process(binary.right, **kw),
  1186. )
  1187. def visit_empty_set_op_expr(self, type_, expand_op, **kw):
  1188. # slightly old SQLite versions don't seem to be able to handle
  1189. # the empty set impl
  1190. return self.visit_empty_set_expr(type_)
  1191. def visit_empty_set_expr(self, element_types, **kw):
  1192. return "SELECT %s FROM (SELECT %s) WHERE 1!=1" % (
  1193. ", ".join("1" for type_ in element_types or [INTEGER()]),
  1194. ", ".join("1" for type_ in element_types or [INTEGER()]),
  1195. )
  1196. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  1197. return self._generate_generic_binary(binary, " REGEXP ", **kw)
  1198. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  1199. return self._generate_generic_binary(binary, " NOT REGEXP ", **kw)
  1200. def _on_conflict_target(self, clause, **kw):
  1201. if clause.inferred_target_elements is not None:
  1202. target_text = "(%s)" % ", ".join(
  1203. (
  1204. self.preparer.quote(c)
  1205. if isinstance(c, str)
  1206. else self.process(c, include_table=False, use_schema=False)
  1207. )
  1208. for c in clause.inferred_target_elements
  1209. )
  1210. if clause.inferred_target_whereclause is not None:
  1211. target_text += " WHERE %s" % self.process(
  1212. clause.inferred_target_whereclause,
  1213. include_table=False,
  1214. use_schema=False,
  1215. literal_execute=True,
  1216. )
  1217. else:
  1218. target_text = ""
  1219. return target_text
  1220. def visit_on_conflict_do_nothing(self, on_conflict, **kw):
  1221. target_text = self._on_conflict_target(on_conflict, **kw)
  1222. if target_text:
  1223. return "ON CONFLICT %s DO NOTHING" % target_text
  1224. else:
  1225. return "ON CONFLICT DO NOTHING"
  1226. def visit_on_conflict_do_update(self, on_conflict, **kw):
  1227. clause = on_conflict
  1228. target_text = self._on_conflict_target(on_conflict, **kw)
  1229. action_set_ops = []
  1230. set_parameters = dict(clause.update_values_to_set)
  1231. # create a list of column assignment clauses as tuples
  1232. insert_statement = self.stack[-1]["selectable"]
  1233. cols = insert_statement.table.c
  1234. for c in cols:
  1235. col_key = c.key
  1236. if col_key in set_parameters:
  1237. value = set_parameters.pop(col_key)
  1238. elif c in set_parameters:
  1239. value = set_parameters.pop(c)
  1240. else:
  1241. continue
  1242. if coercions._is_literal(value):
  1243. value = elements.BindParameter(None, value, type_=c.type)
  1244. else:
  1245. if (
  1246. isinstance(value, elements.BindParameter)
  1247. and value.type._isnull
  1248. ):
  1249. value = value._clone()
  1250. value.type = c.type
  1251. value_text = self.process(value.self_group(), use_schema=False)
  1252. key_text = self.preparer.quote(c.name)
  1253. action_set_ops.append("%s = %s" % (key_text, value_text))
  1254. # check for names that don't match columns
  1255. if set_parameters:
  1256. util.warn(
  1257. "Additional column names not matching "
  1258. "any column keys in table '%s': %s"
  1259. % (
  1260. self.current_executable.table.name,
  1261. (", ".join("'%s'" % c for c in set_parameters)),
  1262. )
  1263. )
  1264. for k, v in set_parameters.items():
  1265. key_text = (
  1266. self.preparer.quote(k)
  1267. if isinstance(k, str)
  1268. else self.process(k, use_schema=False)
  1269. )
  1270. value_text = self.process(
  1271. coercions.expect(roles.ExpressionElementRole, v),
  1272. use_schema=False,
  1273. )
  1274. action_set_ops.append("%s = %s" % (key_text, value_text))
  1275. action_text = ", ".join(action_set_ops)
  1276. if clause.update_whereclause is not None:
  1277. action_text += " WHERE %s" % self.process(
  1278. clause.update_whereclause, include_table=True, use_schema=False
  1279. )
  1280. return "ON CONFLICT %s DO UPDATE SET %s" % (target_text, action_text)
  1281. def visit_bitwise_xor_op_binary(self, binary, operator, **kw):
  1282. # sqlite has no xor. Use "a XOR b" = "(a | b) - (a & b)".
  1283. kw["eager_grouping"] = True
  1284. or_ = self._generate_generic_binary(binary, " | ", **kw)
  1285. and_ = self._generate_generic_binary(binary, " & ", **kw)
  1286. return f"({or_} - {and_})"
  1287. class SQLiteDDLCompiler(compiler.DDLCompiler):
  1288. def get_column_specification(self, column, **kwargs):
  1289. coltype = self.dialect.type_compiler_instance.process(
  1290. column.type, type_expression=column
  1291. )
  1292. colspec = self.preparer.format_column(column) + " " + coltype
  1293. default = self.get_column_default_string(column)
  1294. if default is not None:
  1295. if not re.match(r"""^\s*[\'\"\(]""", default) and re.match(
  1296. r".*\W.*", default
  1297. ):
  1298. colspec += f" DEFAULT ({default})"
  1299. else:
  1300. colspec += f" DEFAULT {default}"
  1301. if not column.nullable:
  1302. colspec += " NOT NULL"
  1303. on_conflict_clause = column.dialect_options["sqlite"][
  1304. "on_conflict_not_null"
  1305. ]
  1306. if on_conflict_clause is not None:
  1307. colspec += " ON CONFLICT " + on_conflict_clause
  1308. if column.primary_key:
  1309. if (
  1310. column.autoincrement is True
  1311. and len(column.table.primary_key.columns) != 1
  1312. ):
  1313. raise exc.CompileError(
  1314. "SQLite does not support autoincrement for "
  1315. "composite primary keys"
  1316. )
  1317. if (
  1318. column.table.dialect_options["sqlite"]["autoincrement"]
  1319. and len(column.table.primary_key.columns) == 1
  1320. and issubclass(column.type._type_affinity, sqltypes.Integer)
  1321. and not column.foreign_keys
  1322. ):
  1323. colspec += " PRIMARY KEY"
  1324. on_conflict_clause = column.dialect_options["sqlite"][
  1325. "on_conflict_primary_key"
  1326. ]
  1327. if on_conflict_clause is not None:
  1328. colspec += " ON CONFLICT " + on_conflict_clause
  1329. colspec += " AUTOINCREMENT"
  1330. if column.computed is not None:
  1331. colspec += " " + self.process(column.computed)
  1332. return colspec
  1333. def visit_primary_key_constraint(self, constraint, **kw):
  1334. # for columns with sqlite_autoincrement=True,
  1335. # the PRIMARY KEY constraint can only be inline
  1336. # with the column itself.
  1337. if len(constraint.columns) == 1:
  1338. c = list(constraint)[0]
  1339. if (
  1340. c.primary_key
  1341. and c.table.dialect_options["sqlite"]["autoincrement"]
  1342. and issubclass(c.type._type_affinity, sqltypes.Integer)
  1343. and not c.foreign_keys
  1344. ):
  1345. return None
  1346. text = super().visit_primary_key_constraint(constraint)
  1347. on_conflict_clause = constraint.dialect_options["sqlite"][
  1348. "on_conflict"
  1349. ]
  1350. if on_conflict_clause is None and len(constraint.columns) == 1:
  1351. on_conflict_clause = list(constraint)[0].dialect_options["sqlite"][
  1352. "on_conflict_primary_key"
  1353. ]
  1354. if on_conflict_clause is not None:
  1355. text += " ON CONFLICT " + on_conflict_clause
  1356. return text
  1357. def visit_unique_constraint(self, constraint, **kw):
  1358. text = super().visit_unique_constraint(constraint)
  1359. on_conflict_clause = constraint.dialect_options["sqlite"][
  1360. "on_conflict"
  1361. ]
  1362. if on_conflict_clause is None and len(constraint.columns) == 1:
  1363. col1 = list(constraint)[0]
  1364. if isinstance(col1, schema.SchemaItem):
  1365. on_conflict_clause = list(constraint)[0].dialect_options[
  1366. "sqlite"
  1367. ]["on_conflict_unique"]
  1368. if on_conflict_clause is not None:
  1369. text += " ON CONFLICT " + on_conflict_clause
  1370. return text
  1371. def visit_check_constraint(self, constraint, **kw):
  1372. text = super().visit_check_constraint(constraint)
  1373. on_conflict_clause = constraint.dialect_options["sqlite"][
  1374. "on_conflict"
  1375. ]
  1376. if on_conflict_clause is not None:
  1377. text += " ON CONFLICT " + on_conflict_clause
  1378. return text
  1379. def visit_column_check_constraint(self, constraint, **kw):
  1380. text = super().visit_column_check_constraint(constraint)
  1381. if constraint.dialect_options["sqlite"]["on_conflict"] is not None:
  1382. raise exc.CompileError(
  1383. "SQLite does not support on conflict clause for "
  1384. "column check constraint"
  1385. )
  1386. return text
  1387. def visit_foreign_key_constraint(self, constraint, **kw):
  1388. local_table = constraint.elements[0].parent.table
  1389. remote_table = constraint.elements[0].column.table
  1390. if local_table.schema != remote_table.schema:
  1391. return None
  1392. else:
  1393. return super().visit_foreign_key_constraint(constraint)
  1394. def define_constraint_remote_table(self, constraint, table, preparer):
  1395. """Format the remote table clause of a CREATE CONSTRAINT clause."""
  1396. return preparer.format_table(table, use_schema=False)
  1397. def visit_create_index(
  1398. self, create, include_schema=False, include_table_schema=True, **kw
  1399. ):
  1400. index = create.element
  1401. self._verify_index_table(index)
  1402. preparer = self.preparer
  1403. text = "CREATE "
  1404. if index.unique:
  1405. text += "UNIQUE "
  1406. text += "INDEX "
  1407. if create.if_not_exists:
  1408. text += "IF NOT EXISTS "
  1409. text += "%s ON %s (%s)" % (
  1410. self._prepared_index_name(index, include_schema=True),
  1411. preparer.format_table(index.table, use_schema=False),
  1412. ", ".join(
  1413. self.sql_compiler.process(
  1414. expr, include_table=False, literal_binds=True
  1415. )
  1416. for expr in index.expressions
  1417. ),
  1418. )
  1419. whereclause = index.dialect_options["sqlite"]["where"]
  1420. if whereclause is not None:
  1421. where_compiled = self.sql_compiler.process(
  1422. whereclause, include_table=False, literal_binds=True
  1423. )
  1424. text += " WHERE " + where_compiled
  1425. return text
  1426. def post_create_table(self, table):
  1427. table_options = []
  1428. if not table.dialect_options["sqlite"]["with_rowid"]:
  1429. table_options.append("WITHOUT ROWID")
  1430. if table.dialect_options["sqlite"]["strict"]:
  1431. table_options.append("STRICT")
  1432. if table_options:
  1433. return "\n " + ",\n ".join(table_options)
  1434. else:
  1435. return ""
  1436. class SQLiteTypeCompiler(compiler.GenericTypeCompiler):
  1437. def visit_large_binary(self, type_, **kw):
  1438. return self.visit_BLOB(type_)
  1439. def visit_DATETIME(self, type_, **kw):
  1440. if (
  1441. not isinstance(type_, _DateTimeMixin)
  1442. or type_.format_is_text_affinity
  1443. ):
  1444. return super().visit_DATETIME(type_)
  1445. else:
  1446. return "DATETIME_CHAR"
  1447. def visit_DATE(self, type_, **kw):
  1448. if (
  1449. not isinstance(type_, _DateTimeMixin)
  1450. or type_.format_is_text_affinity
  1451. ):
  1452. return super().visit_DATE(type_)
  1453. else:
  1454. return "DATE_CHAR"
  1455. def visit_TIME(self, type_, **kw):
  1456. if (
  1457. not isinstance(type_, _DateTimeMixin)
  1458. or type_.format_is_text_affinity
  1459. ):
  1460. return super().visit_TIME(type_)
  1461. else:
  1462. return "TIME_CHAR"
  1463. def visit_JSON(self, type_, **kw):
  1464. # note this name provides NUMERIC affinity, not TEXT.
  1465. # should not be an issue unless the JSON value consists of a single
  1466. # numeric value. JSONTEXT can be used if this case is required.
  1467. return "JSON"
  1468. class SQLiteIdentifierPreparer(compiler.IdentifierPreparer):
  1469. reserved_words = {
  1470. "add",
  1471. "after",
  1472. "all",
  1473. "alter",
  1474. "analyze",
  1475. "and",
  1476. "as",
  1477. "asc",
  1478. "attach",
  1479. "autoincrement",
  1480. "before",
  1481. "begin",
  1482. "between",
  1483. "by",
  1484. "cascade",
  1485. "case",
  1486. "cast",
  1487. "check",
  1488. "collate",
  1489. "column",
  1490. "commit",
  1491. "conflict",
  1492. "constraint",
  1493. "create",
  1494. "cross",
  1495. "current_date",
  1496. "current_time",
  1497. "current_timestamp",
  1498. "database",
  1499. "default",
  1500. "deferrable",
  1501. "deferred",
  1502. "delete",
  1503. "desc",
  1504. "detach",
  1505. "distinct",
  1506. "drop",
  1507. "each",
  1508. "else",
  1509. "end",
  1510. "escape",
  1511. "except",
  1512. "exclusive",
  1513. "exists",
  1514. "explain",
  1515. "false",
  1516. "fail",
  1517. "for",
  1518. "foreign",
  1519. "from",
  1520. "full",
  1521. "glob",
  1522. "group",
  1523. "having",
  1524. "if",
  1525. "ignore",
  1526. "immediate",
  1527. "in",
  1528. "index",
  1529. "indexed",
  1530. "initially",
  1531. "inner",
  1532. "insert",
  1533. "instead",
  1534. "intersect",
  1535. "into",
  1536. "is",
  1537. "isnull",
  1538. "join",
  1539. "key",
  1540. "left",
  1541. "like",
  1542. "limit",
  1543. "match",
  1544. "natural",
  1545. "not",
  1546. "notnull",
  1547. "null",
  1548. "of",
  1549. "offset",
  1550. "on",
  1551. "or",
  1552. "order",
  1553. "outer",
  1554. "plan",
  1555. "pragma",
  1556. "primary",
  1557. "query",
  1558. "raise",
  1559. "references",
  1560. "reindex",
  1561. "rename",
  1562. "replace",
  1563. "restrict",
  1564. "right",
  1565. "rollback",
  1566. "row",
  1567. "select",
  1568. "set",
  1569. "table",
  1570. "temp",
  1571. "temporary",
  1572. "then",
  1573. "to",
  1574. "transaction",
  1575. "trigger",
  1576. "true",
  1577. "union",
  1578. "unique",
  1579. "update",
  1580. "using",
  1581. "vacuum",
  1582. "values",
  1583. "view",
  1584. "virtual",
  1585. "when",
  1586. "where",
  1587. }
  1588. class SQLiteExecutionContext(default.DefaultExecutionContext):
  1589. @util.memoized_property
  1590. def _preserve_raw_colnames(self):
  1591. return (
  1592. not self.dialect._broken_dotted_colnames
  1593. or self.execution_options.get("sqlite_raw_colnames", False)
  1594. )
  1595. def _translate_colname(self, colname):
  1596. # TODO: detect SQLite version 3.10.0 or greater;
  1597. # see [ticket:3633]
  1598. # adjust for dotted column names. SQLite
  1599. # in the case of UNION may store col names as
  1600. # "tablename.colname", or if using an attached database,
  1601. # "database.tablename.colname", in cursor.description
  1602. if not self._preserve_raw_colnames and "." in colname:
  1603. return colname.split(".")[-1], colname
  1604. else:
  1605. return colname, None
  1606. class SQLiteDialect(default.DefaultDialect):
  1607. name = "sqlite"
  1608. supports_alter = False
  1609. # SQlite supports "DEFAULT VALUES" but *does not* support
  1610. # "VALUES (DEFAULT)"
  1611. supports_default_values = True
  1612. supports_default_metavalue = False
  1613. # sqlite issue:
  1614. # https://github.com/python/cpython/issues/93421
  1615. # note this parameter is no longer used by the ORM or default dialect
  1616. # see #9414
  1617. supports_sane_rowcount_returning = False
  1618. supports_empty_insert = False
  1619. supports_cast = True
  1620. supports_multivalues_insert = True
  1621. use_insertmanyvalues = True
  1622. tuple_in_values = True
  1623. supports_statement_cache = True
  1624. insert_null_pk_still_autoincrements = True
  1625. insert_returning = True
  1626. update_returning = True
  1627. update_returning_multifrom = True
  1628. delete_returning = True
  1629. update_returning_multifrom = True
  1630. supports_default_metavalue = True
  1631. """dialect supports INSERT... VALUES (DEFAULT) syntax"""
  1632. default_metavalue_token = "NULL"
  1633. """for INSERT... VALUES (DEFAULT) syntax, the token to put in the
  1634. parenthesis."""
  1635. default_paramstyle = "qmark"
  1636. execution_ctx_cls = SQLiteExecutionContext
  1637. statement_compiler = SQLiteCompiler
  1638. ddl_compiler = SQLiteDDLCompiler
  1639. type_compiler_cls = SQLiteTypeCompiler
  1640. preparer = SQLiteIdentifierPreparer
  1641. ischema_names = ischema_names
  1642. colspecs = colspecs
  1643. construct_arguments = [
  1644. (
  1645. sa_schema.Table,
  1646. {
  1647. "autoincrement": False,
  1648. "with_rowid": True,
  1649. "strict": False,
  1650. },
  1651. ),
  1652. (sa_schema.Index, {"where": None}),
  1653. (
  1654. sa_schema.Column,
  1655. {
  1656. "on_conflict_primary_key": None,
  1657. "on_conflict_not_null": None,
  1658. "on_conflict_unique": None,
  1659. },
  1660. ),
  1661. (sa_schema.Constraint, {"on_conflict": None}),
  1662. ]
  1663. _broken_fk_pragma_quotes = False
  1664. _broken_dotted_colnames = False
  1665. @util.deprecated_params(
  1666. _json_serializer=(
  1667. "1.3.7",
  1668. "The _json_serializer argument to the SQLite dialect has "
  1669. "been renamed to the correct name of json_serializer. The old "
  1670. "argument name will be removed in a future release.",
  1671. ),
  1672. _json_deserializer=(
  1673. "1.3.7",
  1674. "The _json_deserializer argument to the SQLite dialect has "
  1675. "been renamed to the correct name of json_deserializer. The old "
  1676. "argument name will be removed in a future release.",
  1677. ),
  1678. )
  1679. def __init__(
  1680. self,
  1681. native_datetime=False,
  1682. json_serializer=None,
  1683. json_deserializer=None,
  1684. _json_serializer=None,
  1685. _json_deserializer=None,
  1686. **kwargs,
  1687. ):
  1688. default.DefaultDialect.__init__(self, **kwargs)
  1689. if _json_serializer:
  1690. json_serializer = _json_serializer
  1691. if _json_deserializer:
  1692. json_deserializer = _json_deserializer
  1693. self._json_serializer = json_serializer
  1694. self._json_deserializer = json_deserializer
  1695. # this flag used by pysqlite dialect, and perhaps others in the
  1696. # future, to indicate the driver is handling date/timestamp
  1697. # conversions (and perhaps datetime/time as well on some hypothetical
  1698. # driver ?)
  1699. self.native_datetime = native_datetime
  1700. if self.dbapi is not None:
  1701. if self.dbapi.sqlite_version_info < (3, 7, 16):
  1702. util.warn(
  1703. "SQLite version %s is older than 3.7.16, and will not "
  1704. "support right nested joins, as are sometimes used in "
  1705. "more complex ORM scenarios. SQLAlchemy 1.4 and above "
  1706. "no longer tries to rewrite these joins."
  1707. % (self.dbapi.sqlite_version_info,)
  1708. )
  1709. # NOTE: python 3.7 on fedora for me has SQLite 3.34.1. These
  1710. # version checks are getting very stale.
  1711. self._broken_dotted_colnames = self.dbapi.sqlite_version_info < (
  1712. 3,
  1713. 10,
  1714. 0,
  1715. )
  1716. self.supports_default_values = self.dbapi.sqlite_version_info >= (
  1717. 3,
  1718. 3,
  1719. 8,
  1720. )
  1721. self.supports_cast = self.dbapi.sqlite_version_info >= (3, 2, 3)
  1722. self.supports_multivalues_insert = (
  1723. # https://www.sqlite.org/releaselog/3_7_11.html
  1724. self.dbapi.sqlite_version_info
  1725. >= (3, 7, 11)
  1726. )
  1727. # see https://www.sqlalchemy.org/trac/ticket/2568
  1728. # as well as https://www.sqlite.org/src/info/600482d161
  1729. self._broken_fk_pragma_quotes = self.dbapi.sqlite_version_info < (
  1730. 3,
  1731. 6,
  1732. 14,
  1733. )
  1734. if self.dbapi.sqlite_version_info < (3, 35) or util.pypy:
  1735. self.update_returning = self.delete_returning = (
  1736. self.insert_returning
  1737. ) = False
  1738. if self.dbapi.sqlite_version_info < (3, 32, 0):
  1739. # https://www.sqlite.org/limits.html
  1740. self.insertmanyvalues_max_parameters = 999
  1741. _isolation_lookup = util.immutabledict(
  1742. {"READ UNCOMMITTED": 1, "SERIALIZABLE": 0}
  1743. )
  1744. def get_isolation_level_values(self, dbapi_connection):
  1745. return list(self._isolation_lookup)
  1746. def set_isolation_level(self, dbapi_connection, level):
  1747. isolation_level = self._isolation_lookup[level]
  1748. cursor = dbapi_connection.cursor()
  1749. cursor.execute(f"PRAGMA read_uncommitted = {isolation_level}")
  1750. cursor.close()
  1751. def get_isolation_level(self, dbapi_connection):
  1752. cursor = dbapi_connection.cursor()
  1753. cursor.execute("PRAGMA read_uncommitted")
  1754. res = cursor.fetchone()
  1755. if res:
  1756. value = res[0]
  1757. else:
  1758. # https://www.sqlite.org/changes.html#version_3_3_3
  1759. # "Optional READ UNCOMMITTED isolation (instead of the
  1760. # default isolation level of SERIALIZABLE) and
  1761. # table level locking when database connections
  1762. # share a common cache.""
  1763. # pre-SQLite 3.3.0 default to 0
  1764. value = 0
  1765. cursor.close()
  1766. if value == 0:
  1767. return "SERIALIZABLE"
  1768. elif value == 1:
  1769. return "READ UNCOMMITTED"
  1770. else:
  1771. assert False, "Unknown isolation level %s" % value
  1772. @reflection.cache
  1773. def get_schema_names(self, connection, **kw):
  1774. s = "PRAGMA database_list"
  1775. dl = connection.exec_driver_sql(s)
  1776. return [db[1] for db in dl if db[1] != "temp"]
  1777. def _format_schema(self, schema, table_name):
  1778. if schema is not None:
  1779. qschema = self.identifier_preparer.quote_identifier(schema)
  1780. name = f"{qschema}.{table_name}"
  1781. else:
  1782. name = table_name
  1783. return name
  1784. def _sqlite_main_query(
  1785. self,
  1786. table: str,
  1787. type_: str,
  1788. schema: Optional[str],
  1789. sqlite_include_internal: bool,
  1790. ):
  1791. main = self._format_schema(schema, table)
  1792. if not sqlite_include_internal:
  1793. filter_table = " AND name NOT LIKE 'sqlite~_%' ESCAPE '~'"
  1794. else:
  1795. filter_table = ""
  1796. query = (
  1797. f"SELECT name FROM {main} "
  1798. f"WHERE type='{type_}'{filter_table} "
  1799. "ORDER BY name"
  1800. )
  1801. return query
  1802. @reflection.cache
  1803. def get_table_names(
  1804. self, connection, schema=None, sqlite_include_internal=False, **kw
  1805. ):
  1806. query = self._sqlite_main_query(
  1807. "sqlite_master", "table", schema, sqlite_include_internal
  1808. )
  1809. names = connection.exec_driver_sql(query).scalars().all()
  1810. return names
  1811. @reflection.cache
  1812. def get_temp_table_names(
  1813. self, connection, sqlite_include_internal=False, **kw
  1814. ):
  1815. query = self._sqlite_main_query(
  1816. "sqlite_temp_master", "table", None, sqlite_include_internal
  1817. )
  1818. names = connection.exec_driver_sql(query).scalars().all()
  1819. return names
  1820. @reflection.cache
  1821. def get_temp_view_names(
  1822. self, connection, sqlite_include_internal=False, **kw
  1823. ):
  1824. query = self._sqlite_main_query(
  1825. "sqlite_temp_master", "view", None, sqlite_include_internal
  1826. )
  1827. names = connection.exec_driver_sql(query).scalars().all()
  1828. return names
  1829. @reflection.cache
  1830. def has_table(self, connection, table_name, schema=None, **kw):
  1831. self._ensure_has_table_connection(connection)
  1832. if schema is not None and schema not in self.get_schema_names(
  1833. connection, **kw
  1834. ):
  1835. return False
  1836. info = self._get_table_pragma(
  1837. connection, "table_info", table_name, schema=schema
  1838. )
  1839. return bool(info)
  1840. def _get_default_schema_name(self, connection):
  1841. return "main"
  1842. @reflection.cache
  1843. def get_view_names(
  1844. self, connection, schema=None, sqlite_include_internal=False, **kw
  1845. ):
  1846. query = self._sqlite_main_query(
  1847. "sqlite_master", "view", schema, sqlite_include_internal
  1848. )
  1849. names = connection.exec_driver_sql(query).scalars().all()
  1850. return names
  1851. @reflection.cache
  1852. def get_view_definition(self, connection, view_name, schema=None, **kw):
  1853. if schema is not None:
  1854. qschema = self.identifier_preparer.quote_identifier(schema)
  1855. master = f"{qschema}.sqlite_master"
  1856. s = ("SELECT sql FROM %s WHERE name = ? AND type='view'") % (
  1857. master,
  1858. )
  1859. rs = connection.exec_driver_sql(s, (view_name,))
  1860. else:
  1861. try:
  1862. s = (
  1863. "SELECT sql FROM "
  1864. " (SELECT * FROM sqlite_master UNION ALL "
  1865. " SELECT * FROM sqlite_temp_master) "
  1866. "WHERE name = ? "
  1867. "AND type='view'"
  1868. )
  1869. rs = connection.exec_driver_sql(s, (view_name,))
  1870. except exc.DBAPIError:
  1871. s = (
  1872. "SELECT sql FROM sqlite_master WHERE name = ? "
  1873. "AND type='view'"
  1874. )
  1875. rs = connection.exec_driver_sql(s, (view_name,))
  1876. result = rs.fetchall()
  1877. if result:
  1878. return result[0].sql
  1879. else:
  1880. raise exc.NoSuchTableError(
  1881. f"{schema}.{view_name}" if schema else view_name
  1882. )
  1883. @reflection.cache
  1884. def get_columns(self, connection, table_name, schema=None, **kw):
  1885. pragma = "table_info"
  1886. # computed columns are threaded as hidden, they require table_xinfo
  1887. if self.server_version_info >= (3, 31):
  1888. pragma = "table_xinfo"
  1889. info = self._get_table_pragma(
  1890. connection, pragma, table_name, schema=schema
  1891. )
  1892. columns = []
  1893. tablesql = None
  1894. for row in info:
  1895. name = row[1]
  1896. type_ = row[2].upper()
  1897. nullable = not row[3]
  1898. default = row[4]
  1899. primary_key = row[5]
  1900. hidden = row[6] if pragma == "table_xinfo" else 0
  1901. # hidden has value 0 for normal columns, 1 for hidden columns,
  1902. # 2 for computed virtual columns and 3 for computed stored columns
  1903. # https://www.sqlite.org/src/info/069351b85f9a706f60d3e98fbc8aaf40c374356b967c0464aede30ead3d9d18b
  1904. if hidden == 1:
  1905. continue
  1906. generated = bool(hidden)
  1907. persisted = hidden == 3
  1908. if tablesql is None and generated:
  1909. tablesql = self._get_table_sql(
  1910. connection, table_name, schema, **kw
  1911. )
  1912. # remove create table
  1913. match = re.match(
  1914. r"create table .*?\((.*)\)$",
  1915. tablesql.strip(),
  1916. re.DOTALL | re.IGNORECASE,
  1917. )
  1918. assert match, f"create table not found in {tablesql}"
  1919. tablesql = match.group(1).strip()
  1920. columns.append(
  1921. self._get_column_info(
  1922. name,
  1923. type_,
  1924. nullable,
  1925. default,
  1926. primary_key,
  1927. generated,
  1928. persisted,
  1929. tablesql,
  1930. )
  1931. )
  1932. if columns:
  1933. return columns
  1934. elif not self.has_table(connection, table_name, schema):
  1935. raise exc.NoSuchTableError(
  1936. f"{schema}.{table_name}" if schema else table_name
  1937. )
  1938. else:
  1939. return ReflectionDefaults.columns()
  1940. def _get_column_info(
  1941. self,
  1942. name,
  1943. type_,
  1944. nullable,
  1945. default,
  1946. primary_key,
  1947. generated,
  1948. persisted,
  1949. tablesql,
  1950. ):
  1951. if generated:
  1952. # the type of a column "cc INTEGER GENERATED ALWAYS AS (1 + 42)"
  1953. # somehow is "INTEGER GENERATED ALWAYS"
  1954. type_ = re.sub("generated", "", type_, flags=re.IGNORECASE)
  1955. type_ = re.sub("always", "", type_, flags=re.IGNORECASE).strip()
  1956. coltype = self._resolve_type_affinity(type_)
  1957. if default is not None:
  1958. default = str(default)
  1959. colspec = {
  1960. "name": name,
  1961. "type": coltype,
  1962. "nullable": nullable,
  1963. "default": default,
  1964. "primary_key": primary_key,
  1965. }
  1966. if generated:
  1967. sqltext = ""
  1968. if tablesql:
  1969. pattern = (
  1970. r"[^,]*\s+GENERATED\s+ALWAYS\s+AS"
  1971. r"\s+\((.*)\)\s*(?:virtual|stored)?"
  1972. )
  1973. match = re.search(
  1974. re.escape(name) + pattern, tablesql, re.IGNORECASE
  1975. )
  1976. if match:
  1977. sqltext = match.group(1)
  1978. colspec["computed"] = {"sqltext": sqltext, "persisted": persisted}
  1979. return colspec
  1980. def _resolve_type_affinity(self, type_):
  1981. """Return a data type from a reflected column, using affinity rules.
  1982. SQLite's goal for universal compatibility introduces some complexity
  1983. during reflection, as a column's defined type might not actually be a
  1984. type that SQLite understands - or indeed, my not be defined *at all*.
  1985. Internally, SQLite handles this with a 'data type affinity' for each
  1986. column definition, mapping to one of 'TEXT', 'NUMERIC', 'INTEGER',
  1987. 'REAL', or 'NONE' (raw bits). The algorithm that determines this is
  1988. listed in https://www.sqlite.org/datatype3.html section 2.1.
  1989. This method allows SQLAlchemy to support that algorithm, while still
  1990. providing access to smarter reflection utilities by recognizing
  1991. column definitions that SQLite only supports through affinity (like
  1992. DATE and DOUBLE).
  1993. """
  1994. match = re.match(r"([\w ]+)(\(.*?\))?", type_)
  1995. if match:
  1996. coltype = match.group(1)
  1997. args = match.group(2)
  1998. else:
  1999. coltype = ""
  2000. args = ""
  2001. if coltype in self.ischema_names:
  2002. coltype = self.ischema_names[coltype]
  2003. elif "INT" in coltype:
  2004. coltype = sqltypes.INTEGER
  2005. elif "CHAR" in coltype or "CLOB" in coltype or "TEXT" in coltype:
  2006. coltype = sqltypes.TEXT
  2007. elif "BLOB" in coltype or not coltype:
  2008. coltype = sqltypes.NullType
  2009. elif "REAL" in coltype or "FLOA" in coltype or "DOUB" in coltype:
  2010. coltype = sqltypes.REAL
  2011. else:
  2012. coltype = sqltypes.NUMERIC
  2013. if args is not None:
  2014. args = re.findall(r"(\d+)", args)
  2015. try:
  2016. coltype = coltype(*[int(a) for a in args])
  2017. except TypeError:
  2018. util.warn(
  2019. "Could not instantiate type %s with "
  2020. "reflected arguments %s; using no arguments."
  2021. % (coltype, args)
  2022. )
  2023. coltype = coltype()
  2024. else:
  2025. coltype = coltype()
  2026. return coltype
  2027. @reflection.cache
  2028. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  2029. constraint_name = None
  2030. table_data = self._get_table_sql(connection, table_name, schema=schema)
  2031. if table_data:
  2032. PK_PATTERN = r"CONSTRAINT (\w+) PRIMARY KEY"
  2033. result = re.search(PK_PATTERN, table_data, re.I)
  2034. constraint_name = result.group(1) if result else None
  2035. cols = self.get_columns(connection, table_name, schema, **kw)
  2036. # consider only pk columns. This also avoids sorting the cached
  2037. # value returned by get_columns
  2038. cols = [col for col in cols if col.get("primary_key", 0) > 0]
  2039. cols.sort(key=lambda col: col.get("primary_key"))
  2040. pkeys = [col["name"] for col in cols]
  2041. if pkeys:
  2042. return {"constrained_columns": pkeys, "name": constraint_name}
  2043. else:
  2044. return ReflectionDefaults.pk_constraint()
  2045. @reflection.cache
  2046. def get_foreign_keys(self, connection, table_name, schema=None, **kw):
  2047. # sqlite makes this *extremely difficult*.
  2048. # First, use the pragma to get the actual FKs.
  2049. pragma_fks = self._get_table_pragma(
  2050. connection, "foreign_key_list", table_name, schema=schema
  2051. )
  2052. fks = {}
  2053. for row in pragma_fks:
  2054. (numerical_id, rtbl, lcol, rcol) = (row[0], row[2], row[3], row[4])
  2055. if not rcol:
  2056. # no referred column, which means it was not named in the
  2057. # original DDL. The referred columns of the foreign key
  2058. # constraint are therefore the primary key of the referred
  2059. # table.
  2060. try:
  2061. referred_pk = self.get_pk_constraint(
  2062. connection, rtbl, schema=schema, **kw
  2063. )
  2064. referred_columns = referred_pk["constrained_columns"]
  2065. except exc.NoSuchTableError:
  2066. # ignore not existing parents
  2067. referred_columns = []
  2068. else:
  2069. # note we use this list only if this is the first column
  2070. # in the constraint. for subsequent columns we ignore the
  2071. # list and append "rcol" if present.
  2072. referred_columns = []
  2073. if self._broken_fk_pragma_quotes:
  2074. rtbl = re.sub(r"^[\"\[`\']|[\"\]`\']$", "", rtbl)
  2075. if numerical_id in fks:
  2076. fk = fks[numerical_id]
  2077. else:
  2078. fk = fks[numerical_id] = {
  2079. "name": None,
  2080. "constrained_columns": [],
  2081. "referred_schema": schema,
  2082. "referred_table": rtbl,
  2083. "referred_columns": referred_columns,
  2084. "options": {},
  2085. }
  2086. fks[numerical_id] = fk
  2087. fk["constrained_columns"].append(lcol)
  2088. if rcol:
  2089. fk["referred_columns"].append(rcol)
  2090. def fk_sig(constrained_columns, referred_table, referred_columns):
  2091. return (
  2092. tuple(constrained_columns)
  2093. + (referred_table,)
  2094. + tuple(referred_columns)
  2095. )
  2096. # then, parse the actual SQL and attempt to find DDL that matches
  2097. # the names as well. SQLite saves the DDL in whatever format
  2098. # it was typed in as, so need to be liberal here.
  2099. keys_by_signature = {
  2100. fk_sig(
  2101. fk["constrained_columns"],
  2102. fk["referred_table"],
  2103. fk["referred_columns"],
  2104. ): fk
  2105. for fk in fks.values()
  2106. }
  2107. table_data = self._get_table_sql(connection, table_name, schema=schema)
  2108. def parse_fks():
  2109. if table_data is None:
  2110. # system tables, etc.
  2111. return
  2112. # note that we already have the FKs from PRAGMA above. This whole
  2113. # regexp thing is trying to locate additional detail about the
  2114. # FKs, namely the name of the constraint and other options.
  2115. # so parsing the columns is really about matching it up to what
  2116. # we already have.
  2117. FK_PATTERN = (
  2118. r"(?:CONSTRAINT (\w+) +)?"
  2119. r"FOREIGN KEY *\( *(.+?) *\) +"
  2120. r'REFERENCES +(?:(?:"(.+?)")|([a-z0-9_]+)) *\( *((?:(?:"[^"]+"|[a-z0-9_]+) *(?:, *)?)+)\) *' # noqa: E501
  2121. r"((?:ON (?:DELETE|UPDATE) "
  2122. r"(?:SET NULL|SET DEFAULT|CASCADE|RESTRICT|NO ACTION) *)*)"
  2123. r"((?:NOT +)?DEFERRABLE)?"
  2124. r"(?: +INITIALLY +(DEFERRED|IMMEDIATE))?"
  2125. )
  2126. for match in re.finditer(FK_PATTERN, table_data, re.I):
  2127. (
  2128. constraint_name,
  2129. constrained_columns,
  2130. referred_quoted_name,
  2131. referred_name,
  2132. referred_columns,
  2133. onupdatedelete,
  2134. deferrable,
  2135. initially,
  2136. ) = match.group(1, 2, 3, 4, 5, 6, 7, 8)
  2137. constrained_columns = list(
  2138. self._find_cols_in_sig(constrained_columns)
  2139. )
  2140. if not referred_columns:
  2141. referred_columns = constrained_columns
  2142. else:
  2143. referred_columns = list(
  2144. self._find_cols_in_sig(referred_columns)
  2145. )
  2146. referred_name = referred_quoted_name or referred_name
  2147. options = {}
  2148. for token in re.split(r" *\bON\b *", onupdatedelete.upper()):
  2149. if token.startswith("DELETE"):
  2150. ondelete = token[6:].strip()
  2151. if ondelete and ondelete != "NO ACTION":
  2152. options["ondelete"] = ondelete
  2153. elif token.startswith("UPDATE"):
  2154. onupdate = token[6:].strip()
  2155. if onupdate and onupdate != "NO ACTION":
  2156. options["onupdate"] = onupdate
  2157. if deferrable:
  2158. options["deferrable"] = "NOT" not in deferrable.upper()
  2159. if initially:
  2160. options["initially"] = initially.upper()
  2161. yield (
  2162. constraint_name,
  2163. constrained_columns,
  2164. referred_name,
  2165. referred_columns,
  2166. options,
  2167. )
  2168. fkeys = []
  2169. for (
  2170. constraint_name,
  2171. constrained_columns,
  2172. referred_name,
  2173. referred_columns,
  2174. options,
  2175. ) in parse_fks():
  2176. sig = fk_sig(constrained_columns, referred_name, referred_columns)
  2177. if sig not in keys_by_signature:
  2178. util.warn(
  2179. "WARNING: SQL-parsed foreign key constraint "
  2180. "'%s' could not be located in PRAGMA "
  2181. "foreign_keys for table %s" % (sig, table_name)
  2182. )
  2183. continue
  2184. key = keys_by_signature.pop(sig)
  2185. key["name"] = constraint_name
  2186. key["options"] = options
  2187. fkeys.append(key)
  2188. # assume the remainders are the unnamed, inline constraints, just
  2189. # use them as is as it's extremely difficult to parse inline
  2190. # constraints
  2191. fkeys.extend(keys_by_signature.values())
  2192. if fkeys:
  2193. return fkeys
  2194. else:
  2195. return ReflectionDefaults.foreign_keys()
  2196. def _find_cols_in_sig(self, sig):
  2197. for match in re.finditer(r'(?:"(.+?)")|([a-z0-9_]+)', sig, re.I):
  2198. yield match.group(1) or match.group(2)
  2199. @reflection.cache
  2200. def get_unique_constraints(
  2201. self, connection, table_name, schema=None, **kw
  2202. ):
  2203. auto_index_by_sig = {}
  2204. for idx in self.get_indexes(
  2205. connection,
  2206. table_name,
  2207. schema=schema,
  2208. include_auto_indexes=True,
  2209. **kw,
  2210. ):
  2211. if not idx["name"].startswith("sqlite_autoindex"):
  2212. continue
  2213. sig = tuple(idx["column_names"])
  2214. auto_index_by_sig[sig] = idx
  2215. table_data = self._get_table_sql(
  2216. connection, table_name, schema=schema, **kw
  2217. )
  2218. unique_constraints = []
  2219. def parse_uqs():
  2220. if table_data is None:
  2221. return
  2222. UNIQUE_PATTERN = r'(?:CONSTRAINT "?(.+?)"? +)?UNIQUE *\((.+?)\)'
  2223. INLINE_UNIQUE_PATTERN = (
  2224. r'(?:(".+?")|(?:[\[`])?([a-z0-9_]+)(?:[\]`])?)[\t ]'
  2225. r"+[a-z0-9_ ]+?[\t ]+UNIQUE"
  2226. )
  2227. for match in re.finditer(UNIQUE_PATTERN, table_data, re.I):
  2228. name, cols = match.group(1, 2)
  2229. yield name, list(self._find_cols_in_sig(cols))
  2230. # we need to match inlines as well, as we seek to differentiate
  2231. # a UNIQUE constraint from a UNIQUE INDEX, even though these
  2232. # are kind of the same thing :)
  2233. for match in re.finditer(INLINE_UNIQUE_PATTERN, table_data, re.I):
  2234. cols = list(
  2235. self._find_cols_in_sig(match.group(1) or match.group(2))
  2236. )
  2237. yield None, cols
  2238. for name, cols in parse_uqs():
  2239. sig = tuple(cols)
  2240. if sig in auto_index_by_sig:
  2241. auto_index_by_sig.pop(sig)
  2242. parsed_constraint = {"name": name, "column_names": cols}
  2243. unique_constraints.append(parsed_constraint)
  2244. # NOTE: auto_index_by_sig might not be empty here,
  2245. # the PRIMARY KEY may have an entry.
  2246. if unique_constraints:
  2247. return unique_constraints
  2248. else:
  2249. return ReflectionDefaults.unique_constraints()
  2250. @reflection.cache
  2251. def get_check_constraints(self, connection, table_name, schema=None, **kw):
  2252. table_data = self._get_table_sql(
  2253. connection, table_name, schema=schema, **kw
  2254. )
  2255. # NOTE NOTE NOTE
  2256. # DO NOT CHANGE THIS REGULAR EXPRESSION. There is no known way
  2257. # to parse CHECK constraints that contain newlines themselves using
  2258. # regular expressions, and the approach here relies upon each
  2259. # individual
  2260. # CHECK constraint being on a single line by itself. This
  2261. # necessarily makes assumptions as to how the CREATE TABLE
  2262. # was emitted. A more comprehensive DDL parsing solution would be
  2263. # needed to improve upon the current situation. See #11840 for
  2264. # background
  2265. CHECK_PATTERN = r"(?:CONSTRAINT (.+) +)?CHECK *\( *(.+) *\),? *"
  2266. cks = []
  2267. for match in re.finditer(CHECK_PATTERN, table_data or "", re.I):
  2268. name = match.group(1)
  2269. if name:
  2270. name = re.sub(r'^"|"$', "", name)
  2271. cks.append({"sqltext": match.group(2), "name": name})
  2272. cks.sort(key=lambda d: d["name"] or "~") # sort None as last
  2273. if cks:
  2274. return cks
  2275. else:
  2276. return ReflectionDefaults.check_constraints()
  2277. @reflection.cache
  2278. def get_indexes(self, connection, table_name, schema=None, **kw):
  2279. pragma_indexes = self._get_table_pragma(
  2280. connection, "index_list", table_name, schema=schema
  2281. )
  2282. indexes = []
  2283. # regular expression to extract the filter predicate of a partial
  2284. # index. this could fail to extract the predicate correctly on
  2285. # indexes created like
  2286. # CREATE INDEX i ON t (col || ') where') WHERE col <> ''
  2287. # but as this function does not support expression-based indexes
  2288. # this case does not occur.
  2289. partial_pred_re = re.compile(r"\)\s+where\s+(.+)", re.IGNORECASE)
  2290. if schema:
  2291. schema_expr = "%s." % self.identifier_preparer.quote_identifier(
  2292. schema
  2293. )
  2294. else:
  2295. schema_expr = ""
  2296. include_auto_indexes = kw.pop("include_auto_indexes", False)
  2297. for row in pragma_indexes:
  2298. # ignore implicit primary key index.
  2299. # https://www.mail-archive.com/sqlite-users@sqlite.org/msg30517.html
  2300. if not include_auto_indexes and row[1].startswith(
  2301. "sqlite_autoindex"
  2302. ):
  2303. continue
  2304. indexes.append(
  2305. dict(
  2306. name=row[1],
  2307. column_names=[],
  2308. unique=row[2],
  2309. dialect_options={},
  2310. )
  2311. )
  2312. # check partial indexes
  2313. if len(row) >= 5 and row[4]:
  2314. s = (
  2315. "SELECT sql FROM %(schema)ssqlite_master "
  2316. "WHERE name = ? "
  2317. "AND type = 'index'" % {"schema": schema_expr}
  2318. )
  2319. rs = connection.exec_driver_sql(s, (row[1],))
  2320. index_sql = rs.scalar()
  2321. predicate_match = partial_pred_re.search(index_sql)
  2322. if predicate_match is None:
  2323. # unless the regex is broken this case shouldn't happen
  2324. # because we know this is a partial index, so the
  2325. # definition sql should match the regex
  2326. util.warn(
  2327. "Failed to look up filter predicate of "
  2328. "partial index %s" % row[1]
  2329. )
  2330. else:
  2331. predicate = predicate_match.group(1)
  2332. indexes[-1]["dialect_options"]["sqlite_where"] = text(
  2333. predicate
  2334. )
  2335. # loop thru unique indexes to get the column names.
  2336. for idx in list(indexes):
  2337. pragma_index = self._get_table_pragma(
  2338. connection, "index_info", idx["name"], schema=schema
  2339. )
  2340. for row in pragma_index:
  2341. if row[2] is None:
  2342. util.warn(
  2343. "Skipped unsupported reflection of "
  2344. "expression-based index %s" % idx["name"]
  2345. )
  2346. indexes.remove(idx)
  2347. break
  2348. else:
  2349. idx["column_names"].append(row[2])
  2350. indexes.sort(key=lambda d: d["name"] or "~") # sort None as last
  2351. if indexes:
  2352. return indexes
  2353. elif not self.has_table(connection, table_name, schema):
  2354. raise exc.NoSuchTableError(
  2355. f"{schema}.{table_name}" if schema else table_name
  2356. )
  2357. else:
  2358. return ReflectionDefaults.indexes()
  2359. def _is_sys_table(self, table_name):
  2360. return table_name in {
  2361. "sqlite_schema",
  2362. "sqlite_master",
  2363. "sqlite_temp_schema",
  2364. "sqlite_temp_master",
  2365. }
  2366. @reflection.cache
  2367. def _get_table_sql(self, connection, table_name, schema=None, **kw):
  2368. if schema:
  2369. schema_expr = "%s." % (
  2370. self.identifier_preparer.quote_identifier(schema)
  2371. )
  2372. else:
  2373. schema_expr = ""
  2374. try:
  2375. s = (
  2376. "SELECT sql FROM "
  2377. " (SELECT * FROM %(schema)ssqlite_master UNION ALL "
  2378. " SELECT * FROM %(schema)ssqlite_temp_master) "
  2379. "WHERE name = ? "
  2380. "AND type in ('table', 'view')" % {"schema": schema_expr}
  2381. )
  2382. rs = connection.exec_driver_sql(s, (table_name,))
  2383. except exc.DBAPIError:
  2384. s = (
  2385. "SELECT sql FROM %(schema)ssqlite_master "
  2386. "WHERE name = ? "
  2387. "AND type in ('table', 'view')" % {"schema": schema_expr}
  2388. )
  2389. rs = connection.exec_driver_sql(s, (table_name,))
  2390. value = rs.scalar()
  2391. if value is None and not self._is_sys_table(table_name):
  2392. raise exc.NoSuchTableError(f"{schema_expr}{table_name}")
  2393. return value
  2394. def _get_table_pragma(self, connection, pragma, table_name, schema=None):
  2395. quote = self.identifier_preparer.quote_identifier
  2396. if schema is not None:
  2397. statements = [f"PRAGMA {quote(schema)}."]
  2398. else:
  2399. # because PRAGMA looks in all attached databases if no schema
  2400. # given, need to specify "main" schema, however since we want
  2401. # 'temp' tables in the same namespace as 'main', need to run
  2402. # the PRAGMA twice
  2403. statements = ["PRAGMA main.", "PRAGMA temp."]
  2404. qtable = quote(table_name)
  2405. for statement in statements:
  2406. statement = f"{statement}{pragma}({qtable})"
  2407. cursor = connection.exec_driver_sql(statement)
  2408. if not cursor._soft_closed:
  2409. # work around SQLite issue whereby cursor.description
  2410. # is blank when PRAGMA returns no rows:
  2411. # https://www.sqlite.org/cvstrac/tktview?tn=1884
  2412. result = cursor.fetchall()
  2413. else:
  2414. result = []
  2415. if result:
  2416. return result
  2417. else:
  2418. return []