base.py 95 KB

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