base.py 89 KB

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