base.py 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626
  1. # dialects/sqlite/base.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. r"""
  8. .. dialect:: sqlite
  9. :name: SQLite
  10. :full_support: 3.36.0
  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 text
  616. from ... import types as sqltypes
  617. from ... import util
  618. from ...engine import default
  619. from ...engine import reflection
  620. from ...sql import coercions
  621. from ...sql import ColumnElement
  622. from ...sql import compiler
  623. from ...sql import elements
  624. from ...sql import roles
  625. from ...sql import schema
  626. from ...types import BLOB # noqa
  627. from ...types import BOOLEAN # noqa
  628. from ...types import CHAR # noqa
  629. from ...types import DECIMAL # noqa
  630. from ...types import FLOAT # noqa
  631. from ...types import INTEGER # noqa
  632. from ...types import NUMERIC # noqa
  633. from ...types import REAL # noqa
  634. from ...types import SMALLINT # noqa
  635. from ...types import TEXT # noqa
  636. from ...types import TIMESTAMP # noqa
  637. from ...types import VARCHAR # noqa
  638. class _SQliteJson(JSON):
  639. def result_processor(self, dialect, coltype):
  640. default_processor = super(_SQliteJson, self).result_processor(
  641. dialect, coltype
  642. )
  643. def process(value):
  644. try:
  645. return default_processor(value)
  646. except TypeError:
  647. if isinstance(value, numbers.Number):
  648. return value
  649. else:
  650. raise
  651. return process
  652. class _DateTimeMixin(object):
  653. _reg = None
  654. _storage_format = None
  655. def __init__(self, storage_format=None, regexp=None, **kw):
  656. super(_DateTimeMixin, self).__init__(**kw)
  657. if regexp is not None:
  658. self._reg = re.compile(regexp)
  659. if storage_format is not None:
  660. self._storage_format = storage_format
  661. @property
  662. def format_is_text_affinity(self):
  663. """return True if the storage format will automatically imply
  664. a TEXT affinity.
  665. If the storage format contains no non-numeric characters,
  666. it will imply a NUMERIC storage format on SQLite; in this case,
  667. the type will generate its DDL as DATE_CHAR, DATETIME_CHAR,
  668. TIME_CHAR.
  669. .. versionadded:: 1.0.0
  670. """
  671. spec = self._storage_format % {
  672. "year": 0,
  673. "month": 0,
  674. "day": 0,
  675. "hour": 0,
  676. "minute": 0,
  677. "second": 0,
  678. "microsecond": 0,
  679. }
  680. return bool(re.search(r"[^0-9]", spec))
  681. def adapt(self, cls, **kw):
  682. if issubclass(cls, _DateTimeMixin):
  683. if self._storage_format:
  684. kw["storage_format"] = self._storage_format
  685. if self._reg:
  686. kw["regexp"] = self._reg
  687. return super(_DateTimeMixin, self).adapt(cls, **kw)
  688. def literal_processor(self, dialect):
  689. bp = self.bind_processor(dialect)
  690. def process(value):
  691. return "'%s'" % bp(value)
  692. return process
  693. class DATETIME(_DateTimeMixin, sqltypes.DateTime):
  694. r"""Represent a Python datetime object in SQLite using a string.
  695. The default string storage format is::
  696. "%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  697. e.g.::
  698. 2021-03-15 12:05:57.105542
  699. The storage format can be customized to some degree using the
  700. ``storage_format`` and ``regexp`` parameters, such as::
  701. import re
  702. from sqlalchemy.dialects.sqlite import DATETIME
  703. dt = DATETIME(storage_format="%(year)04d/%(month)02d/%(day)02d "
  704. "%(hour)02d:%(minute)02d:%(second)02d",
  705. regexp=r"(\d+)/(\d+)/(\d+) (\d+)-(\d+)-(\d+)"
  706. )
  707. :param storage_format: format string which will be applied to the dict
  708. with keys year, month, day, hour, minute, second, and microsecond.
  709. :param regexp: regular expression which will be applied to incoming result
  710. rows. If the regexp contains named groups, the resulting match dict is
  711. applied to the Python datetime() constructor as keyword arguments.
  712. Otherwise, if positional groups are used, the datetime() constructor
  713. is called with positional arguments via
  714. ``*map(int, match_obj.groups(0))``.
  715. """ # noqa
  716. _storage_format = (
  717. "%(year)04d-%(month)02d-%(day)02d "
  718. "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  719. )
  720. def __init__(self, *args, **kwargs):
  721. truncate_microseconds = kwargs.pop("truncate_microseconds", False)
  722. super(DATETIME, self).__init__(*args, **kwargs)
  723. if truncate_microseconds:
  724. assert "storage_format" not in kwargs, (
  725. "You can specify only "
  726. "one of truncate_microseconds or storage_format."
  727. )
  728. assert "regexp" not in kwargs, (
  729. "You can specify only one of "
  730. "truncate_microseconds or regexp."
  731. )
  732. self._storage_format = (
  733. "%(year)04d-%(month)02d-%(day)02d "
  734. "%(hour)02d:%(minute)02d:%(second)02d"
  735. )
  736. def bind_processor(self, dialect):
  737. datetime_datetime = datetime.datetime
  738. datetime_date = datetime.date
  739. format_ = self._storage_format
  740. def process(value):
  741. if value is None:
  742. return None
  743. elif isinstance(value, datetime_datetime):
  744. return format_ % {
  745. "year": value.year,
  746. "month": value.month,
  747. "day": value.day,
  748. "hour": value.hour,
  749. "minute": value.minute,
  750. "second": value.second,
  751. "microsecond": value.microsecond,
  752. }
  753. elif isinstance(value, datetime_date):
  754. return format_ % {
  755. "year": value.year,
  756. "month": value.month,
  757. "day": value.day,
  758. "hour": 0,
  759. "minute": 0,
  760. "second": 0,
  761. "microsecond": 0,
  762. }
  763. else:
  764. raise TypeError(
  765. "SQLite DateTime type only accepts Python "
  766. "datetime and date objects as input."
  767. )
  768. return process
  769. def result_processor(self, dialect, coltype):
  770. if self._reg:
  771. return processors.str_to_datetime_processor_factory(
  772. self._reg, datetime.datetime
  773. )
  774. else:
  775. return processors.str_to_datetime
  776. class DATE(_DateTimeMixin, sqltypes.Date):
  777. r"""Represent a Python date object in SQLite using a string.
  778. The default string storage format is::
  779. "%(year)04d-%(month)02d-%(day)02d"
  780. e.g.::
  781. 2011-03-15
  782. The storage format can be customized to some degree using the
  783. ``storage_format`` and ``regexp`` parameters, such as::
  784. import re
  785. from sqlalchemy.dialects.sqlite import DATE
  786. d = DATE(
  787. storage_format="%(month)02d/%(day)02d/%(year)04d",
  788. regexp=re.compile("(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)")
  789. )
  790. :param storage_format: format string which will be applied to the
  791. dict with keys year, month, and day.
  792. :param regexp: regular expression which will be applied to
  793. incoming result rows. If the regexp contains named groups, the
  794. resulting match dict is applied to the Python date() constructor
  795. as keyword arguments. Otherwise, if positional groups are used, the
  796. date() constructor is called with positional arguments via
  797. ``*map(int, match_obj.groups(0))``.
  798. """
  799. _storage_format = "%(year)04d-%(month)02d-%(day)02d"
  800. def bind_processor(self, dialect):
  801. datetime_date = datetime.date
  802. format_ = self._storage_format
  803. def process(value):
  804. if value is None:
  805. return None
  806. elif isinstance(value, datetime_date):
  807. return format_ % {
  808. "year": value.year,
  809. "month": value.month,
  810. "day": value.day,
  811. }
  812. else:
  813. raise TypeError(
  814. "SQLite Date type only accepts Python "
  815. "date objects as input."
  816. )
  817. return process
  818. def result_processor(self, dialect, coltype):
  819. if self._reg:
  820. return processors.str_to_datetime_processor_factory(
  821. self._reg, datetime.date
  822. )
  823. else:
  824. return processors.str_to_date
  825. class TIME(_DateTimeMixin, sqltypes.Time):
  826. r"""Represent a Python time object in SQLite using a string.
  827. The default string storage format is::
  828. "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  829. e.g.::
  830. 12:05:57.10558
  831. The storage format can be customized to some degree using the
  832. ``storage_format`` and ``regexp`` parameters, such as::
  833. import re
  834. from sqlalchemy.dialects.sqlite import TIME
  835. t = TIME(storage_format="%(hour)02d-%(minute)02d-"
  836. "%(second)02d-%(microsecond)06d",
  837. regexp=re.compile("(\d+)-(\d+)-(\d+)-(?:-(\d+))?")
  838. )
  839. :param storage_format: format string which will be applied to the dict
  840. with keys hour, minute, second, and microsecond.
  841. :param regexp: regular expression which will be applied to incoming result
  842. rows. If the regexp contains named groups, the resulting match dict is
  843. applied to the Python time() constructor as keyword arguments. Otherwise,
  844. if positional groups are used, the time() constructor is called with
  845. positional arguments via ``*map(int, match_obj.groups(0))``.
  846. """
  847. _storage_format = "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  848. def __init__(self, *args, **kwargs):
  849. truncate_microseconds = kwargs.pop("truncate_microseconds", False)
  850. super(TIME, self).__init__(*args, **kwargs)
  851. if truncate_microseconds:
  852. assert "storage_format" not in kwargs, (
  853. "You can specify only "
  854. "one of truncate_microseconds or storage_format."
  855. )
  856. assert "regexp" not in kwargs, (
  857. "You can specify only one of "
  858. "truncate_microseconds or regexp."
  859. )
  860. self._storage_format = "%(hour)02d:%(minute)02d:%(second)02d"
  861. def bind_processor(self, dialect):
  862. datetime_time = datetime.time
  863. format_ = self._storage_format
  864. def process(value):
  865. if value is None:
  866. return None
  867. elif isinstance(value, datetime_time):
  868. return format_ % {
  869. "hour": value.hour,
  870. "minute": value.minute,
  871. "second": value.second,
  872. "microsecond": value.microsecond,
  873. }
  874. else:
  875. raise TypeError(
  876. "SQLite Time type only accepts Python "
  877. "time objects as input."
  878. )
  879. return process
  880. def result_processor(self, dialect, coltype):
  881. if self._reg:
  882. return processors.str_to_datetime_processor_factory(
  883. self._reg, datetime.time
  884. )
  885. else:
  886. return processors.str_to_time
  887. colspecs = {
  888. sqltypes.Date: DATE,
  889. sqltypes.DateTime: DATETIME,
  890. sqltypes.JSON: _SQliteJson,
  891. sqltypes.JSON.JSONIndexType: JSONIndexType,
  892. sqltypes.JSON.JSONPathType: JSONPathType,
  893. sqltypes.Time: TIME,
  894. }
  895. ischema_names = {
  896. "BIGINT": sqltypes.BIGINT,
  897. "BLOB": sqltypes.BLOB,
  898. "BOOL": sqltypes.BOOLEAN,
  899. "BOOLEAN": sqltypes.BOOLEAN,
  900. "CHAR": sqltypes.CHAR,
  901. "DATE": sqltypes.DATE,
  902. "DATE_CHAR": sqltypes.DATE,
  903. "DATETIME": sqltypes.DATETIME,
  904. "DATETIME_CHAR": sqltypes.DATETIME,
  905. "DOUBLE": sqltypes.FLOAT,
  906. "DECIMAL": sqltypes.DECIMAL,
  907. "FLOAT": sqltypes.FLOAT,
  908. "INT": sqltypes.INTEGER,
  909. "INTEGER": sqltypes.INTEGER,
  910. "JSON": JSON,
  911. "NUMERIC": sqltypes.NUMERIC,
  912. "REAL": sqltypes.REAL,
  913. "SMALLINT": sqltypes.SMALLINT,
  914. "TEXT": sqltypes.TEXT,
  915. "TIME": sqltypes.TIME,
  916. "TIME_CHAR": sqltypes.TIME,
  917. "TIMESTAMP": sqltypes.TIMESTAMP,
  918. "VARCHAR": sqltypes.VARCHAR,
  919. "NVARCHAR": sqltypes.NVARCHAR,
  920. "NCHAR": sqltypes.NCHAR,
  921. }
  922. class SQLiteCompiler(compiler.SQLCompiler):
  923. extract_map = util.update_copy(
  924. compiler.SQLCompiler.extract_map,
  925. {
  926. "month": "%m",
  927. "day": "%d",
  928. "year": "%Y",
  929. "second": "%S",
  930. "hour": "%H",
  931. "doy": "%j",
  932. "minute": "%M",
  933. "epoch": "%s",
  934. "dow": "%w",
  935. "week": "%W",
  936. },
  937. )
  938. def visit_now_func(self, fn, **kw):
  939. return "CURRENT_TIMESTAMP"
  940. def visit_localtimestamp_func(self, func, **kw):
  941. return 'DATETIME(CURRENT_TIMESTAMP, "localtime")'
  942. def visit_true(self, expr, **kw):
  943. return "1"
  944. def visit_false(self, expr, **kw):
  945. return "0"
  946. def visit_char_length_func(self, fn, **kw):
  947. return "length%s" % self.function_argspec(fn)
  948. def visit_cast(self, cast, **kwargs):
  949. if self.dialect.supports_cast:
  950. return super(SQLiteCompiler, self).visit_cast(cast, **kwargs)
  951. else:
  952. return self.process(cast.clause, **kwargs)
  953. def visit_extract(self, extract, **kw):
  954. try:
  955. return "CAST(STRFTIME('%s', %s) AS INTEGER)" % (
  956. self.extract_map[extract.field],
  957. self.process(extract.expr, **kw),
  958. )
  959. except KeyError as err:
  960. util.raise_(
  961. exc.CompileError(
  962. "%s is not a valid extract argument." % extract.field
  963. ),
  964. replace_context=err,
  965. )
  966. def limit_clause(self, select, **kw):
  967. text = ""
  968. if select._limit_clause is not None:
  969. text += "\n LIMIT " + self.process(select._limit_clause, **kw)
  970. if select._offset_clause is not None:
  971. if select._limit_clause is None:
  972. text += "\n LIMIT " + self.process(sql.literal(-1))
  973. text += " OFFSET " + self.process(select._offset_clause, **kw)
  974. else:
  975. text += " OFFSET " + self.process(sql.literal(0), **kw)
  976. return text
  977. def for_update_clause(self, select, **kw):
  978. # sqlite has no "FOR UPDATE" AFAICT
  979. return ""
  980. def visit_is_distinct_from_binary(self, binary, operator, **kw):
  981. return "%s IS NOT %s" % (
  982. self.process(binary.left),
  983. self.process(binary.right),
  984. )
  985. def visit_is_not_distinct_from_binary(self, binary, operator, **kw):
  986. return "%s IS %s" % (
  987. self.process(binary.left),
  988. self.process(binary.right),
  989. )
  990. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  991. if binary.type._type_affinity is sqltypes.JSON:
  992. expr = "JSON_QUOTE(JSON_EXTRACT(%s, %s))"
  993. else:
  994. expr = "JSON_EXTRACT(%s, %s)"
  995. return expr % (
  996. self.process(binary.left, **kw),
  997. self.process(binary.right, **kw),
  998. )
  999. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  1000. if binary.type._type_affinity is sqltypes.JSON:
  1001. expr = "JSON_QUOTE(JSON_EXTRACT(%s, %s))"
  1002. else:
  1003. expr = "JSON_EXTRACT(%s, %s)"
  1004. return expr % (
  1005. self.process(binary.left, **kw),
  1006. self.process(binary.right, **kw),
  1007. )
  1008. def visit_empty_set_op_expr(self, type_, expand_op):
  1009. # slightly old SQLite versions don't seem to be able to handle
  1010. # the empty set impl
  1011. return self.visit_empty_set_expr(type_)
  1012. def visit_empty_set_expr(self, element_types):
  1013. return "SELECT %s FROM (SELECT %s) WHERE 1!=1" % (
  1014. ", ".join("1" for type_ in element_types or [INTEGER()]),
  1015. ", ".join("1" for type_ in element_types or [INTEGER()]),
  1016. )
  1017. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  1018. return self._generate_generic_binary(binary, " REGEXP ", **kw)
  1019. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  1020. return self._generate_generic_binary(binary, " NOT REGEXP ", **kw)
  1021. def _on_conflict_target(self, clause, **kw):
  1022. if clause.constraint_target is not None:
  1023. target_text = "(%s)" % clause.constraint_target
  1024. elif clause.inferred_target_elements is not None:
  1025. target_text = "(%s)" % ", ".join(
  1026. (
  1027. self.preparer.quote(c)
  1028. if isinstance(c, util.string_types)
  1029. else self.process(c, include_table=False, use_schema=False)
  1030. )
  1031. for c in clause.inferred_target_elements
  1032. )
  1033. if clause.inferred_target_whereclause is not None:
  1034. target_text += " WHERE %s" % self.process(
  1035. clause.inferred_target_whereclause,
  1036. include_table=False,
  1037. use_schema=False,
  1038. literal_binds=True,
  1039. )
  1040. else:
  1041. target_text = ""
  1042. return target_text
  1043. def visit_on_conflict_do_nothing(self, on_conflict, **kw):
  1044. target_text = self._on_conflict_target(on_conflict, **kw)
  1045. if target_text:
  1046. return "ON CONFLICT %s DO NOTHING" % target_text
  1047. else:
  1048. return "ON CONFLICT DO NOTHING"
  1049. def visit_on_conflict_do_update(self, on_conflict, **kw):
  1050. clause = on_conflict
  1051. target_text = self._on_conflict_target(on_conflict, **kw)
  1052. action_set_ops = []
  1053. set_parameters = dict(clause.update_values_to_set)
  1054. # create a list of column assignment clauses as tuples
  1055. insert_statement = self.stack[-1]["selectable"]
  1056. cols = insert_statement.table.c
  1057. for c in cols:
  1058. col_key = c.key
  1059. if col_key in set_parameters:
  1060. value = set_parameters.pop(col_key)
  1061. elif c in set_parameters:
  1062. value = set_parameters.pop(c)
  1063. else:
  1064. continue
  1065. if coercions._is_literal(value):
  1066. value = elements.BindParameter(None, value, type_=c.type)
  1067. else:
  1068. if (
  1069. isinstance(value, elements.BindParameter)
  1070. and value.type._isnull
  1071. ):
  1072. value = value._clone()
  1073. value.type = c.type
  1074. value_text = self.process(value.self_group(), use_schema=False)
  1075. key_text = self.preparer.quote(c.name)
  1076. action_set_ops.append("%s = %s" % (key_text, value_text))
  1077. # check for names that don't match columns
  1078. if set_parameters:
  1079. util.warn(
  1080. "Additional column names not matching "
  1081. "any column keys in table '%s': %s"
  1082. % (
  1083. self.current_executable.table.name,
  1084. (", ".join("'%s'" % c for c in set_parameters)),
  1085. )
  1086. )
  1087. for k, v in set_parameters.items():
  1088. key_text = (
  1089. self.preparer.quote(k)
  1090. if isinstance(k, util.string_types)
  1091. else self.process(k, use_schema=False)
  1092. )
  1093. value_text = self.process(
  1094. coercions.expect(roles.ExpressionElementRole, v),
  1095. use_schema=False,
  1096. )
  1097. action_set_ops.append("%s = %s" % (key_text, value_text))
  1098. action_text = ", ".join(action_set_ops)
  1099. if clause.update_whereclause is not None:
  1100. action_text += " WHERE %s" % self.process(
  1101. clause.update_whereclause, include_table=True, use_schema=False
  1102. )
  1103. return "ON CONFLICT %s DO UPDATE SET %s" % (target_text, action_text)
  1104. class SQLiteDDLCompiler(compiler.DDLCompiler):
  1105. def get_column_specification(self, column, **kwargs):
  1106. coltype = self.dialect.type_compiler.process(
  1107. column.type, type_expression=column
  1108. )
  1109. colspec = self.preparer.format_column(column) + " " + coltype
  1110. default = self.get_column_default_string(column)
  1111. if default is not None:
  1112. if isinstance(column.server_default.arg, ColumnElement):
  1113. default = "(" + default + ")"
  1114. colspec += " DEFAULT " + default
  1115. if not column.nullable:
  1116. colspec += " NOT NULL"
  1117. on_conflict_clause = column.dialect_options["sqlite"][
  1118. "on_conflict_not_null"
  1119. ]
  1120. if on_conflict_clause is not None:
  1121. colspec += " ON CONFLICT " + on_conflict_clause
  1122. if column.primary_key:
  1123. if (
  1124. column.autoincrement is True
  1125. and len(column.table.primary_key.columns) != 1
  1126. ):
  1127. raise exc.CompileError(
  1128. "SQLite does not support autoincrement for "
  1129. "composite primary keys"
  1130. )
  1131. if (
  1132. column.table.dialect_options["sqlite"]["autoincrement"]
  1133. and len(column.table.primary_key.columns) == 1
  1134. and issubclass(column.type._type_affinity, sqltypes.Integer)
  1135. and not column.foreign_keys
  1136. ):
  1137. colspec += " PRIMARY KEY"
  1138. on_conflict_clause = column.dialect_options["sqlite"][
  1139. "on_conflict_primary_key"
  1140. ]
  1141. if on_conflict_clause is not None:
  1142. colspec += " ON CONFLICT " + on_conflict_clause
  1143. colspec += " AUTOINCREMENT"
  1144. if column.computed is not None:
  1145. colspec += " " + self.process(column.computed)
  1146. return colspec
  1147. def visit_primary_key_constraint(self, constraint):
  1148. # for columns with sqlite_autoincrement=True,
  1149. # the PRIMARY KEY constraint can only be inline
  1150. # with the column itself.
  1151. if len(constraint.columns) == 1:
  1152. c = list(constraint)[0]
  1153. if (
  1154. c.primary_key
  1155. and c.table.dialect_options["sqlite"]["autoincrement"]
  1156. and issubclass(c.type._type_affinity, sqltypes.Integer)
  1157. and not c.foreign_keys
  1158. ):
  1159. return None
  1160. text = super(SQLiteDDLCompiler, self).visit_primary_key_constraint(
  1161. constraint
  1162. )
  1163. on_conflict_clause = constraint.dialect_options["sqlite"][
  1164. "on_conflict"
  1165. ]
  1166. if on_conflict_clause is None and len(constraint.columns) == 1:
  1167. on_conflict_clause = list(constraint)[0].dialect_options["sqlite"][
  1168. "on_conflict_primary_key"
  1169. ]
  1170. if on_conflict_clause is not None:
  1171. text += " ON CONFLICT " + on_conflict_clause
  1172. return text
  1173. def visit_unique_constraint(self, constraint):
  1174. text = super(SQLiteDDLCompiler, self).visit_unique_constraint(
  1175. constraint
  1176. )
  1177. on_conflict_clause = constraint.dialect_options["sqlite"][
  1178. "on_conflict"
  1179. ]
  1180. if on_conflict_clause is None and len(constraint.columns) == 1:
  1181. col1 = list(constraint)[0]
  1182. if isinstance(col1, schema.SchemaItem):
  1183. on_conflict_clause = list(constraint)[0].dialect_options[
  1184. "sqlite"
  1185. ]["on_conflict_unique"]
  1186. if on_conflict_clause is not None:
  1187. text += " ON CONFLICT " + on_conflict_clause
  1188. return text
  1189. def visit_check_constraint(self, constraint):
  1190. text = super(SQLiteDDLCompiler, self).visit_check_constraint(
  1191. constraint
  1192. )
  1193. on_conflict_clause = constraint.dialect_options["sqlite"][
  1194. "on_conflict"
  1195. ]
  1196. if on_conflict_clause is not None:
  1197. text += " ON CONFLICT " + on_conflict_clause
  1198. return text
  1199. def visit_column_check_constraint(self, constraint):
  1200. text = super(SQLiteDDLCompiler, self).visit_column_check_constraint(
  1201. constraint
  1202. )
  1203. if constraint.dialect_options["sqlite"]["on_conflict"] is not None:
  1204. raise exc.CompileError(
  1205. "SQLite does not support on conflict clause for "
  1206. "column check constraint"
  1207. )
  1208. return text
  1209. def visit_foreign_key_constraint(self, constraint):
  1210. local_table = constraint.elements[0].parent.table
  1211. remote_table = constraint.elements[0].column.table
  1212. if local_table.schema != remote_table.schema:
  1213. return None
  1214. else:
  1215. return super(SQLiteDDLCompiler, self).visit_foreign_key_constraint(
  1216. constraint
  1217. )
  1218. def define_constraint_remote_table(self, constraint, table, preparer):
  1219. """Format the remote table clause of a CREATE CONSTRAINT clause."""
  1220. return preparer.format_table(table, use_schema=False)
  1221. def visit_create_index(
  1222. self, create, include_schema=False, include_table_schema=True
  1223. ):
  1224. index = create.element
  1225. self._verify_index_table(index)
  1226. preparer = self.preparer
  1227. text = "CREATE "
  1228. if index.unique:
  1229. text += "UNIQUE "
  1230. text += "INDEX "
  1231. if create.if_not_exists:
  1232. text += "IF NOT EXISTS "
  1233. text += "%s ON %s (%s)" % (
  1234. self._prepared_index_name(index, include_schema=True),
  1235. preparer.format_table(index.table, use_schema=False),
  1236. ", ".join(
  1237. self.sql_compiler.process(
  1238. expr, include_table=False, literal_binds=True
  1239. )
  1240. for expr in index.expressions
  1241. ),
  1242. )
  1243. whereclause = index.dialect_options["sqlite"]["where"]
  1244. if whereclause is not None:
  1245. where_compiled = self.sql_compiler.process(
  1246. whereclause, include_table=False, literal_binds=True
  1247. )
  1248. text += " WHERE " + where_compiled
  1249. return text
  1250. def post_create_table(self, table):
  1251. if table.dialect_options["sqlite"]["with_rowid"] is False:
  1252. return "\n WITHOUT ROWID"
  1253. return ""
  1254. class SQLiteTypeCompiler(compiler.GenericTypeCompiler):
  1255. def visit_large_binary(self, type_, **kw):
  1256. return self.visit_BLOB(type_)
  1257. def visit_DATETIME(self, type_, **kw):
  1258. if (
  1259. not isinstance(type_, _DateTimeMixin)
  1260. or type_.format_is_text_affinity
  1261. ):
  1262. return super(SQLiteTypeCompiler, self).visit_DATETIME(type_)
  1263. else:
  1264. return "DATETIME_CHAR"
  1265. def visit_DATE(self, type_, **kw):
  1266. if (
  1267. not isinstance(type_, _DateTimeMixin)
  1268. or type_.format_is_text_affinity
  1269. ):
  1270. return super(SQLiteTypeCompiler, self).visit_DATE(type_)
  1271. else:
  1272. return "DATE_CHAR"
  1273. def visit_TIME(self, type_, **kw):
  1274. if (
  1275. not isinstance(type_, _DateTimeMixin)
  1276. or type_.format_is_text_affinity
  1277. ):
  1278. return super(SQLiteTypeCompiler, self).visit_TIME(type_)
  1279. else:
  1280. return "TIME_CHAR"
  1281. def visit_JSON(self, type_, **kw):
  1282. # note this name provides NUMERIC affinity, not TEXT.
  1283. # should not be an issue unless the JSON value consists of a single
  1284. # numeric value. JSONTEXT can be used if this case is required.
  1285. return "JSON"
  1286. class SQLiteIdentifierPreparer(compiler.IdentifierPreparer):
  1287. reserved_words = set(
  1288. [
  1289. "add",
  1290. "after",
  1291. "all",
  1292. "alter",
  1293. "analyze",
  1294. "and",
  1295. "as",
  1296. "asc",
  1297. "attach",
  1298. "autoincrement",
  1299. "before",
  1300. "begin",
  1301. "between",
  1302. "by",
  1303. "cascade",
  1304. "case",
  1305. "cast",
  1306. "check",
  1307. "collate",
  1308. "column",
  1309. "commit",
  1310. "conflict",
  1311. "constraint",
  1312. "create",
  1313. "cross",
  1314. "current_date",
  1315. "current_time",
  1316. "current_timestamp",
  1317. "database",
  1318. "default",
  1319. "deferrable",
  1320. "deferred",
  1321. "delete",
  1322. "desc",
  1323. "detach",
  1324. "distinct",
  1325. "drop",
  1326. "each",
  1327. "else",
  1328. "end",
  1329. "escape",
  1330. "except",
  1331. "exclusive",
  1332. "exists",
  1333. "explain",
  1334. "false",
  1335. "fail",
  1336. "for",
  1337. "foreign",
  1338. "from",
  1339. "full",
  1340. "glob",
  1341. "group",
  1342. "having",
  1343. "if",
  1344. "ignore",
  1345. "immediate",
  1346. "in",
  1347. "index",
  1348. "indexed",
  1349. "initially",
  1350. "inner",
  1351. "insert",
  1352. "instead",
  1353. "intersect",
  1354. "into",
  1355. "is",
  1356. "isnull",
  1357. "join",
  1358. "key",
  1359. "left",
  1360. "like",
  1361. "limit",
  1362. "match",
  1363. "natural",
  1364. "not",
  1365. "notnull",
  1366. "null",
  1367. "of",
  1368. "offset",
  1369. "on",
  1370. "or",
  1371. "order",
  1372. "outer",
  1373. "plan",
  1374. "pragma",
  1375. "primary",
  1376. "query",
  1377. "raise",
  1378. "references",
  1379. "reindex",
  1380. "rename",
  1381. "replace",
  1382. "restrict",
  1383. "right",
  1384. "rollback",
  1385. "row",
  1386. "select",
  1387. "set",
  1388. "table",
  1389. "temp",
  1390. "temporary",
  1391. "then",
  1392. "to",
  1393. "transaction",
  1394. "trigger",
  1395. "true",
  1396. "union",
  1397. "unique",
  1398. "update",
  1399. "using",
  1400. "vacuum",
  1401. "values",
  1402. "view",
  1403. "virtual",
  1404. "when",
  1405. "where",
  1406. ]
  1407. )
  1408. class SQLiteExecutionContext(default.DefaultExecutionContext):
  1409. @util.memoized_property
  1410. def _preserve_raw_colnames(self):
  1411. return (
  1412. not self.dialect._broken_dotted_colnames
  1413. or self.execution_options.get("sqlite_raw_colnames", False)
  1414. )
  1415. def _translate_colname(self, colname):
  1416. # TODO: detect SQLite version 3.10.0 or greater;
  1417. # see [ticket:3633]
  1418. # adjust for dotted column names. SQLite
  1419. # in the case of UNION may store col names as
  1420. # "tablename.colname", or if using an attached database,
  1421. # "database.tablename.colname", in cursor.description
  1422. if not self._preserve_raw_colnames and "." in colname:
  1423. return colname.split(".")[-1], colname
  1424. else:
  1425. return colname, None
  1426. class SQLiteDialect(default.DefaultDialect):
  1427. name = "sqlite"
  1428. supports_alter = False
  1429. supports_unicode_statements = True
  1430. supports_unicode_binds = True
  1431. # SQlite supports "DEFAULT VALUES" but *does not* support
  1432. # "VALUES (DEFAULT)"
  1433. supports_default_values = True
  1434. supports_default_metavalue = False
  1435. supports_empty_insert = False
  1436. supports_cast = True
  1437. supports_multivalues_insert = True
  1438. tuple_in_values = True
  1439. supports_statement_cache = True
  1440. default_paramstyle = "qmark"
  1441. execution_ctx_cls = SQLiteExecutionContext
  1442. statement_compiler = SQLiteCompiler
  1443. ddl_compiler = SQLiteDDLCompiler
  1444. type_compiler = SQLiteTypeCompiler
  1445. preparer = SQLiteIdentifierPreparer
  1446. ischema_names = ischema_names
  1447. colspecs = colspecs
  1448. isolation_level = None
  1449. construct_arguments = [
  1450. (
  1451. sa_schema.Table,
  1452. {
  1453. "autoincrement": False,
  1454. "with_rowid": True,
  1455. },
  1456. ),
  1457. (sa_schema.Index, {"where": None}),
  1458. (
  1459. sa_schema.Column,
  1460. {
  1461. "on_conflict_primary_key": None,
  1462. "on_conflict_not_null": None,
  1463. "on_conflict_unique": None,
  1464. },
  1465. ),
  1466. (sa_schema.Constraint, {"on_conflict": None}),
  1467. ]
  1468. _broken_fk_pragma_quotes = False
  1469. _broken_dotted_colnames = False
  1470. @util.deprecated_params(
  1471. _json_serializer=(
  1472. "1.3.7",
  1473. "The _json_serializer argument to the SQLite dialect has "
  1474. "been renamed to the correct name of json_serializer. The old "
  1475. "argument name will be removed in a future release.",
  1476. ),
  1477. _json_deserializer=(
  1478. "1.3.7",
  1479. "The _json_deserializer argument to the SQLite dialect has "
  1480. "been renamed to the correct name of json_deserializer. The old "
  1481. "argument name will be removed in a future release.",
  1482. ),
  1483. )
  1484. def __init__(
  1485. self,
  1486. isolation_level=None,
  1487. native_datetime=False,
  1488. json_serializer=None,
  1489. json_deserializer=None,
  1490. _json_serializer=None,
  1491. _json_deserializer=None,
  1492. **kwargs
  1493. ):
  1494. default.DefaultDialect.__init__(self, **kwargs)
  1495. self.isolation_level = isolation_level
  1496. if _json_serializer:
  1497. json_serializer = _json_serializer
  1498. if _json_deserializer:
  1499. json_deserializer = _json_deserializer
  1500. self._json_serializer = json_serializer
  1501. self._json_deserializer = json_deserializer
  1502. # this flag used by pysqlite dialect, and perhaps others in the
  1503. # future, to indicate the driver is handling date/timestamp
  1504. # conversions (and perhaps datetime/time as well on some hypothetical
  1505. # driver ?)
  1506. self.native_datetime = native_datetime
  1507. if self.dbapi is not None:
  1508. if self.dbapi.sqlite_version_info < (3, 7, 16):
  1509. util.warn(
  1510. "SQLite version %s is older than 3.7.16, and will not "
  1511. "support right nested joins, as are sometimes used in "
  1512. "more complex ORM scenarios. SQLAlchemy 1.4 and above "
  1513. "no longer tries to rewrite these joins."
  1514. % (self.dbapi.sqlite_version_info,)
  1515. )
  1516. self._broken_dotted_colnames = self.dbapi.sqlite_version_info < (
  1517. 3,
  1518. 10,
  1519. 0,
  1520. )
  1521. self.supports_default_values = self.dbapi.sqlite_version_info >= (
  1522. 3,
  1523. 3,
  1524. 8,
  1525. )
  1526. self.supports_cast = self.dbapi.sqlite_version_info >= (3, 2, 3)
  1527. self.supports_multivalues_insert = (
  1528. # https://www.sqlite.org/releaselog/3_7_11.html
  1529. self.dbapi.sqlite_version_info
  1530. >= (3, 7, 11)
  1531. )
  1532. # see https://www.sqlalchemy.org/trac/ticket/2568
  1533. # as well as https://www.sqlite.org/src/info/600482d161
  1534. self._broken_fk_pragma_quotes = self.dbapi.sqlite_version_info < (
  1535. 3,
  1536. 6,
  1537. 14,
  1538. )
  1539. _isolation_lookup = util.immutabledict(
  1540. {"READ UNCOMMITTED": 1, "SERIALIZABLE": 0}
  1541. )
  1542. def set_isolation_level(self, connection, level):
  1543. try:
  1544. isolation_level = self._isolation_lookup[level.replace("_", " ")]
  1545. except KeyError as err:
  1546. util.raise_(
  1547. exc.ArgumentError(
  1548. "Invalid value '%s' for isolation_level. "
  1549. "Valid isolation levels for %s are %s"
  1550. % (
  1551. level,
  1552. self.name,
  1553. ", ".join(self._isolation_lookup),
  1554. )
  1555. ),
  1556. replace_context=err,
  1557. )
  1558. cursor = connection.cursor()
  1559. cursor.execute("PRAGMA read_uncommitted = %d" % isolation_level)
  1560. cursor.close()
  1561. def get_isolation_level(self, connection):
  1562. cursor = connection.cursor()
  1563. cursor.execute("PRAGMA read_uncommitted")
  1564. res = cursor.fetchone()
  1565. if res:
  1566. value = res[0]
  1567. else:
  1568. # https://www.sqlite.org/changes.html#version_3_3_3
  1569. # "Optional READ UNCOMMITTED isolation (instead of the
  1570. # default isolation level of SERIALIZABLE) and
  1571. # table level locking when database connections
  1572. # share a common cache.""
  1573. # pre-SQLite 3.3.0 default to 0
  1574. value = 0
  1575. cursor.close()
  1576. if value == 0:
  1577. return "SERIALIZABLE"
  1578. elif value == 1:
  1579. return "READ UNCOMMITTED"
  1580. else:
  1581. assert False, "Unknown isolation level %s" % value
  1582. def on_connect(self):
  1583. if self.isolation_level is not None:
  1584. def connect(conn):
  1585. self.set_isolation_level(conn, self.isolation_level)
  1586. return connect
  1587. else:
  1588. return None
  1589. @reflection.cache
  1590. def get_schema_names(self, connection, **kw):
  1591. s = "PRAGMA database_list"
  1592. dl = connection.exec_driver_sql(s)
  1593. return [db[1] for db in dl if db[1] != "temp"]
  1594. @reflection.cache
  1595. def get_table_names(self, connection, schema=None, **kw):
  1596. if schema is not None:
  1597. qschema = self.identifier_preparer.quote_identifier(schema)
  1598. master = "%s.sqlite_master" % qschema
  1599. else:
  1600. master = "sqlite_master"
  1601. s = ("SELECT name FROM %s " "WHERE type='table' ORDER BY name") % (
  1602. master,
  1603. )
  1604. rs = connection.exec_driver_sql(s)
  1605. return [row[0] for row in rs]
  1606. @reflection.cache
  1607. def get_temp_table_names(self, connection, **kw):
  1608. s = (
  1609. "SELECT name FROM sqlite_temp_master "
  1610. "WHERE type='table' ORDER BY name "
  1611. )
  1612. rs = connection.exec_driver_sql(s)
  1613. return [row[0] for row in rs]
  1614. @reflection.cache
  1615. def get_temp_view_names(self, connection, **kw):
  1616. s = (
  1617. "SELECT name FROM sqlite_temp_master "
  1618. "WHERE type='view' ORDER BY name "
  1619. )
  1620. rs = connection.exec_driver_sql(s)
  1621. return [row[0] for row in rs]
  1622. def has_table(self, connection, table_name, schema=None):
  1623. self._ensure_has_table_connection(connection)
  1624. info = self._get_table_pragma(
  1625. connection, "table_info", table_name, schema=schema
  1626. )
  1627. return bool(info)
  1628. def _get_default_schema_name(self, connection):
  1629. return "main"
  1630. @reflection.cache
  1631. def get_view_names(self, connection, schema=None, **kw):
  1632. if schema is not None:
  1633. qschema = self.identifier_preparer.quote_identifier(schema)
  1634. master = "%s.sqlite_master" % qschema
  1635. else:
  1636. master = "sqlite_master"
  1637. s = ("SELECT name FROM %s " "WHERE type='view' ORDER BY name") % (
  1638. master,
  1639. )
  1640. rs = connection.exec_driver_sql(s)
  1641. return [row[0] for row in rs]
  1642. @reflection.cache
  1643. def get_view_definition(self, connection, view_name, schema=None, **kw):
  1644. if schema is not None:
  1645. qschema = self.identifier_preparer.quote_identifier(schema)
  1646. master = "%s.sqlite_master" % qschema
  1647. s = ("SELECT sql FROM %s WHERE name = ? AND type='view'") % (
  1648. master,
  1649. )
  1650. rs = connection.exec_driver_sql(s, (view_name,))
  1651. else:
  1652. try:
  1653. s = (
  1654. "SELECT sql FROM "
  1655. " (SELECT * FROM sqlite_master UNION ALL "
  1656. " SELECT * FROM sqlite_temp_master) "
  1657. "WHERE name = ? "
  1658. "AND type='view'"
  1659. )
  1660. rs = connection.exec_driver_sql(s, (view_name,))
  1661. except exc.DBAPIError:
  1662. s = (
  1663. "SELECT sql FROM sqlite_master WHERE name = ? "
  1664. "AND type='view'"
  1665. )
  1666. rs = connection.exec_driver_sql(s, (view_name,))
  1667. result = rs.fetchall()
  1668. if result:
  1669. return result[0].sql
  1670. @reflection.cache
  1671. def get_columns(self, connection, table_name, schema=None, **kw):
  1672. pragma = "table_info"
  1673. # computed columns are threaded as hidden, they require table_xinfo
  1674. if self.server_version_info >= (3, 31):
  1675. pragma = "table_xinfo"
  1676. info = self._get_table_pragma(
  1677. connection, pragma, table_name, schema=schema
  1678. )
  1679. columns = []
  1680. tablesql = None
  1681. for row in info:
  1682. name = row[1]
  1683. type_ = row[2].upper()
  1684. nullable = not row[3]
  1685. default = row[4]
  1686. primary_key = row[5]
  1687. hidden = row[6] if pragma == "table_xinfo" else 0
  1688. # hidden has value 0 for normal columns, 1 for hidden columns,
  1689. # 2 for computed virtual columns and 3 for computed stored columns
  1690. # https://www.sqlite.org/src/info/069351b85f9a706f60d3e98fbc8aaf40c374356b967c0464aede30ead3d9d18b
  1691. if hidden == 1:
  1692. continue
  1693. generated = bool(hidden)
  1694. persisted = hidden == 3
  1695. if tablesql is None and generated:
  1696. tablesql = self._get_table_sql(
  1697. connection, table_name, schema, **kw
  1698. )
  1699. # remove create table
  1700. match = re.match(
  1701. r"create table .*?\((.*)\)$",
  1702. tablesql.strip(),
  1703. re.DOTALL | re.IGNORECASE,
  1704. )
  1705. assert match, "create table not found in %s" % tablesql
  1706. tablesql = match.group(1).strip()
  1707. columns.append(
  1708. self._get_column_info(
  1709. name,
  1710. type_,
  1711. nullable,
  1712. default,
  1713. primary_key,
  1714. generated,
  1715. persisted,
  1716. tablesql,
  1717. )
  1718. )
  1719. return columns
  1720. def _get_column_info(
  1721. self,
  1722. name,
  1723. type_,
  1724. nullable,
  1725. default,
  1726. primary_key,
  1727. generated,
  1728. persisted,
  1729. tablesql,
  1730. ):
  1731. if generated:
  1732. # the type of a column "cc INTEGER GENERATED ALWAYS AS (1 + 42)"
  1733. # somehow is "INTEGER GENERATED ALWAYS"
  1734. type_ = re.sub("generated", "", type_, flags=re.IGNORECASE)
  1735. type_ = re.sub("always", "", type_, flags=re.IGNORECASE).strip()
  1736. coltype = self._resolve_type_affinity(type_)
  1737. if default is not None:
  1738. default = util.text_type(default)
  1739. colspec = {
  1740. "name": name,
  1741. "type": coltype,
  1742. "nullable": nullable,
  1743. "default": default,
  1744. "autoincrement": "auto",
  1745. "primary_key": primary_key,
  1746. }
  1747. if generated:
  1748. sqltext = ""
  1749. if tablesql:
  1750. pattern = (
  1751. r"[^,]*\s+GENERATED\s+ALWAYS\s+AS"
  1752. r"\s+\((.*)\)\s*(?:virtual|stored)?"
  1753. )
  1754. match = re.search(
  1755. re.escape(name) + pattern, tablesql, re.IGNORECASE
  1756. )
  1757. if match:
  1758. sqltext = match.group(1)
  1759. colspec["computed"] = {"sqltext": sqltext, "persisted": persisted}
  1760. return colspec
  1761. def _resolve_type_affinity(self, type_):
  1762. """Return a data type from a reflected column, using affinity rules.
  1763. SQLite's goal for universal compatibility introduces some complexity
  1764. during reflection, as a column's defined type might not actually be a
  1765. type that SQLite understands - or indeed, my not be defined *at all*.
  1766. Internally, SQLite handles this with a 'data type affinity' for each
  1767. column definition, mapping to one of 'TEXT', 'NUMERIC', 'INTEGER',
  1768. 'REAL', or 'NONE' (raw bits). The algorithm that determines this is
  1769. listed in https://www.sqlite.org/datatype3.html section 2.1.
  1770. This method allows SQLAlchemy to support that algorithm, while still
  1771. providing access to smarter reflection utilities by recognizing
  1772. column definitions that SQLite only supports through affinity (like
  1773. DATE and DOUBLE).
  1774. """
  1775. match = re.match(r"([\w ]+)(\(.*?\))?", type_)
  1776. if match:
  1777. coltype = match.group(1)
  1778. args = match.group(2)
  1779. else:
  1780. coltype = ""
  1781. args = ""
  1782. if coltype in self.ischema_names:
  1783. coltype = self.ischema_names[coltype]
  1784. elif "INT" in coltype:
  1785. coltype = sqltypes.INTEGER
  1786. elif "CHAR" in coltype or "CLOB" in coltype or "TEXT" in coltype:
  1787. coltype = sqltypes.TEXT
  1788. elif "BLOB" in coltype or not coltype:
  1789. coltype = sqltypes.NullType
  1790. elif "REAL" in coltype or "FLOA" in coltype or "DOUB" in coltype:
  1791. coltype = sqltypes.REAL
  1792. else:
  1793. coltype = sqltypes.NUMERIC
  1794. if args is not None:
  1795. args = re.findall(r"(\d+)", args)
  1796. try:
  1797. coltype = coltype(*[int(a) for a in args])
  1798. except TypeError:
  1799. util.warn(
  1800. "Could not instantiate type %s with "
  1801. "reflected arguments %s; using no arguments."
  1802. % (coltype, args)
  1803. )
  1804. coltype = coltype()
  1805. else:
  1806. coltype = coltype()
  1807. return coltype
  1808. @reflection.cache
  1809. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  1810. constraint_name = None
  1811. table_data = self._get_table_sql(connection, table_name, schema=schema)
  1812. if table_data:
  1813. PK_PATTERN = r"CONSTRAINT (\w+) PRIMARY KEY"
  1814. result = re.search(PK_PATTERN, table_data, re.I)
  1815. constraint_name = result.group(1) if result else None
  1816. cols = self.get_columns(connection, table_name, schema, **kw)
  1817. cols.sort(key=lambda col: col.get("primary_key"))
  1818. pkeys = []
  1819. for col in cols:
  1820. if col["primary_key"]:
  1821. pkeys.append(col["name"])
  1822. return {"constrained_columns": pkeys, "name": constraint_name}
  1823. @reflection.cache
  1824. def get_foreign_keys(self, connection, table_name, schema=None, **kw):
  1825. # sqlite makes this *extremely difficult*.
  1826. # First, use the pragma to get the actual FKs.
  1827. pragma_fks = self._get_table_pragma(
  1828. connection, "foreign_key_list", table_name, schema=schema
  1829. )
  1830. fks = {}
  1831. for row in pragma_fks:
  1832. (numerical_id, rtbl, lcol, rcol) = (row[0], row[2], row[3], row[4])
  1833. if not rcol:
  1834. # no referred column, which means it was not named in the
  1835. # original DDL. The referred columns of the foreign key
  1836. # constraint are therefore the primary key of the referred
  1837. # table.
  1838. referred_pk = self.get_pk_constraint(
  1839. connection, rtbl, schema=schema, **kw
  1840. )
  1841. # note that if table doesn't exist, we still get back a record,
  1842. # just it has no columns in it
  1843. referred_columns = referred_pk["constrained_columns"]
  1844. else:
  1845. # note we use this list only if this is the first column
  1846. # in the constraint. for subsequent columns we ignore the
  1847. # list and append "rcol" if present.
  1848. referred_columns = []
  1849. if self._broken_fk_pragma_quotes:
  1850. rtbl = re.sub(r"^[\"\[`\']|[\"\]`\']$", "", rtbl)
  1851. if numerical_id in fks:
  1852. fk = fks[numerical_id]
  1853. else:
  1854. fk = fks[numerical_id] = {
  1855. "name": None,
  1856. "constrained_columns": [],
  1857. "referred_schema": schema,
  1858. "referred_table": rtbl,
  1859. "referred_columns": referred_columns,
  1860. "options": {},
  1861. }
  1862. fks[numerical_id] = fk
  1863. fk["constrained_columns"].append(lcol)
  1864. if rcol:
  1865. fk["referred_columns"].append(rcol)
  1866. def fk_sig(constrained_columns, referred_table, referred_columns):
  1867. return (
  1868. tuple(constrained_columns)
  1869. + (referred_table,)
  1870. + tuple(referred_columns)
  1871. )
  1872. # then, parse the actual SQL and attempt to find DDL that matches
  1873. # the names as well. SQLite saves the DDL in whatever format
  1874. # it was typed in as, so need to be liberal here.
  1875. keys_by_signature = dict(
  1876. (
  1877. fk_sig(
  1878. fk["constrained_columns"],
  1879. fk["referred_table"],
  1880. fk["referred_columns"],
  1881. ),
  1882. fk,
  1883. )
  1884. for fk in fks.values()
  1885. )
  1886. table_data = self._get_table_sql(connection, table_name, schema=schema)
  1887. if table_data is None:
  1888. # system tables, etc.
  1889. return []
  1890. def parse_fks():
  1891. FK_PATTERN = (
  1892. r"(?:CONSTRAINT (\w+) +)?"
  1893. r"FOREIGN KEY *\( *(.+?) *\) +"
  1894. r'REFERENCES +(?:(?:"(.+?)")|([a-z0-9_]+)) *\((.+?)\) *'
  1895. r"((?:ON (?:DELETE|UPDATE) "
  1896. r"(?:SET NULL|SET DEFAULT|CASCADE|RESTRICT|NO ACTION) *)*)"
  1897. r"((?:NOT +)?DEFERRABLE)?"
  1898. r"(?: +INITIALLY +(DEFERRED|IMMEDIATE))?"
  1899. )
  1900. for match in re.finditer(FK_PATTERN, table_data, re.I):
  1901. (
  1902. constraint_name,
  1903. constrained_columns,
  1904. referred_quoted_name,
  1905. referred_name,
  1906. referred_columns,
  1907. onupdatedelete,
  1908. deferrable,
  1909. initially,
  1910. ) = match.group(1, 2, 3, 4, 5, 6, 7, 8)
  1911. constrained_columns = list(
  1912. self._find_cols_in_sig(constrained_columns)
  1913. )
  1914. if not referred_columns:
  1915. referred_columns = constrained_columns
  1916. else:
  1917. referred_columns = list(
  1918. self._find_cols_in_sig(referred_columns)
  1919. )
  1920. referred_name = referred_quoted_name or referred_name
  1921. options = {}
  1922. for token in re.split(r" *\bON\b *", onupdatedelete.upper()):
  1923. if token.startswith("DELETE"):
  1924. ondelete = token[6:].strip()
  1925. if ondelete and ondelete != "NO ACTION":
  1926. options["ondelete"] = ondelete
  1927. elif token.startswith("UPDATE"):
  1928. onupdate = token[6:].strip()
  1929. if onupdate and onupdate != "NO ACTION":
  1930. options["onupdate"] = onupdate
  1931. if deferrable:
  1932. options["deferrable"] = "NOT" not in deferrable.upper()
  1933. if initially:
  1934. options["initially"] = initially.upper()
  1935. yield (
  1936. constraint_name,
  1937. constrained_columns,
  1938. referred_name,
  1939. referred_columns,
  1940. options,
  1941. )
  1942. fkeys = []
  1943. for (
  1944. constraint_name,
  1945. constrained_columns,
  1946. referred_name,
  1947. referred_columns,
  1948. options,
  1949. ) in parse_fks():
  1950. sig = fk_sig(constrained_columns, referred_name, referred_columns)
  1951. if sig not in keys_by_signature:
  1952. util.warn(
  1953. "WARNING: SQL-parsed foreign key constraint "
  1954. "'%s' could not be located in PRAGMA "
  1955. "foreign_keys for table %s" % (sig, table_name)
  1956. )
  1957. continue
  1958. key = keys_by_signature.pop(sig)
  1959. key["name"] = constraint_name
  1960. key["options"] = options
  1961. fkeys.append(key)
  1962. # assume the remainders are the unnamed, inline constraints, just
  1963. # use them as is as it's extremely difficult to parse inline
  1964. # constraints
  1965. fkeys.extend(keys_by_signature.values())
  1966. return fkeys
  1967. def _find_cols_in_sig(self, sig):
  1968. for match in re.finditer(r'(?:"(.+?)")|([a-z0-9_]+)', sig, re.I):
  1969. yield match.group(1) or match.group(2)
  1970. @reflection.cache
  1971. def get_unique_constraints(
  1972. self, connection, table_name, schema=None, **kw
  1973. ):
  1974. auto_index_by_sig = {}
  1975. for idx in self.get_indexes(
  1976. connection,
  1977. table_name,
  1978. schema=schema,
  1979. include_auto_indexes=True,
  1980. **kw
  1981. ):
  1982. if not idx["name"].startswith("sqlite_autoindex"):
  1983. continue
  1984. sig = tuple(idx["column_names"])
  1985. auto_index_by_sig[sig] = idx
  1986. table_data = self._get_table_sql(
  1987. connection, table_name, schema=schema, **kw
  1988. )
  1989. if not table_data:
  1990. return []
  1991. unique_constraints = []
  1992. def parse_uqs():
  1993. UNIQUE_PATTERN = r'(?:CONSTRAINT "?(.+?)"? +)?UNIQUE *\((.+?)\)'
  1994. INLINE_UNIQUE_PATTERN = (
  1995. r'(?:(".+?")|(?:[\[`])?([a-z0-9_]+)(?:[\]`])?) '
  1996. r"+[a-z0-9_ ]+? +UNIQUE"
  1997. )
  1998. for match in re.finditer(UNIQUE_PATTERN, table_data, re.I):
  1999. name, cols = match.group(1, 2)
  2000. yield name, list(self._find_cols_in_sig(cols))
  2001. # we need to match inlines as well, as we seek to differentiate
  2002. # a UNIQUE constraint from a UNIQUE INDEX, even though these
  2003. # are kind of the same thing :)
  2004. for match in re.finditer(INLINE_UNIQUE_PATTERN, table_data, re.I):
  2005. cols = list(
  2006. self._find_cols_in_sig(match.group(1) or match.group(2))
  2007. )
  2008. yield None, cols
  2009. for name, cols in parse_uqs():
  2010. sig = tuple(cols)
  2011. if sig in auto_index_by_sig:
  2012. auto_index_by_sig.pop(sig)
  2013. parsed_constraint = {"name": name, "column_names": cols}
  2014. unique_constraints.append(parsed_constraint)
  2015. # NOTE: auto_index_by_sig might not be empty here,
  2016. # the PRIMARY KEY may have an entry.
  2017. return unique_constraints
  2018. @reflection.cache
  2019. def get_check_constraints(self, connection, table_name, schema=None, **kw):
  2020. table_data = self._get_table_sql(
  2021. connection, table_name, schema=schema, **kw
  2022. )
  2023. if not table_data:
  2024. return []
  2025. CHECK_PATTERN = r"(?:CONSTRAINT (.+) +)?" r"CHECK *\( *(.+) *\),? *"
  2026. check_constraints = []
  2027. # NOTE: we aren't using re.S here because we actually are
  2028. # taking advantage of each CHECK constraint being all on one
  2029. # line in the table definition in order to delineate. This
  2030. # necessarily makes assumptions as to how the CREATE TABLE
  2031. # was emitted.
  2032. for match in re.finditer(CHECK_PATTERN, table_data, re.I):
  2033. name = match.group(1)
  2034. if name:
  2035. name = re.sub(r'^"|"$', "", name)
  2036. check_constraints.append({"sqltext": match.group(2), "name": name})
  2037. return check_constraints
  2038. @reflection.cache
  2039. def get_indexes(self, connection, table_name, schema=None, **kw):
  2040. pragma_indexes = self._get_table_pragma(
  2041. connection, "index_list", table_name, schema=schema
  2042. )
  2043. indexes = []
  2044. # regular expression to extract the filter predicate of a partial
  2045. # index. this could fail to extract the predicate correctly on
  2046. # indexes created like
  2047. # CREATE INDEX i ON t (col || ') where') WHERE col <> ''
  2048. # but as this function does not support expression-based indexes
  2049. # this case does not occur.
  2050. partial_pred_re = re.compile(r"\)\s+where\s+(.+)", re.IGNORECASE)
  2051. if schema:
  2052. schema_expr = "%s." % self.identifier_preparer.quote_identifier(
  2053. schema
  2054. )
  2055. else:
  2056. schema_expr = ""
  2057. include_auto_indexes = kw.pop("include_auto_indexes", False)
  2058. for row in pragma_indexes:
  2059. # ignore implicit primary key index.
  2060. # https://www.mail-archive.com/sqlite-users@sqlite.org/msg30517.html
  2061. if not include_auto_indexes and row[1].startswith(
  2062. "sqlite_autoindex"
  2063. ):
  2064. continue
  2065. indexes.append(
  2066. dict(
  2067. name=row[1],
  2068. column_names=[],
  2069. unique=row[2],
  2070. dialect_options={},
  2071. )
  2072. )
  2073. # check partial indexes
  2074. if len(row) >= 5 and row[4]:
  2075. s = (
  2076. "SELECT sql FROM %(schema)ssqlite_master "
  2077. "WHERE name = ? "
  2078. "AND type = 'index'" % {"schema": schema_expr}
  2079. )
  2080. rs = connection.exec_driver_sql(s, (row[1],))
  2081. index_sql = rs.scalar()
  2082. predicate_match = partial_pred_re.search(index_sql)
  2083. if predicate_match is None:
  2084. # unless the regex is broken this case shouldn't happen
  2085. # because we know this is a partial index, so the
  2086. # definition sql should match the regex
  2087. util.warn(
  2088. "Failed to look up filter predicate of "
  2089. "partial index %s" % row[1]
  2090. )
  2091. else:
  2092. predicate = predicate_match.group(1)
  2093. indexes[-1]["dialect_options"]["sqlite_where"] = text(
  2094. predicate
  2095. )
  2096. # loop thru unique indexes to get the column names.
  2097. for idx in list(indexes):
  2098. pragma_index = self._get_table_pragma(
  2099. connection, "index_info", idx["name"], schema=schema
  2100. )
  2101. for row in pragma_index:
  2102. if row[2] is None:
  2103. util.warn(
  2104. "Skipped unsupported reflection of "
  2105. "expression-based index %s" % idx["name"]
  2106. )
  2107. indexes.remove(idx)
  2108. break
  2109. else:
  2110. idx["column_names"].append(row[2])
  2111. indexes.sort(key=lambda d: d["name"] or "~") # sort None as last
  2112. return indexes
  2113. @reflection.cache
  2114. def _get_table_sql(self, connection, table_name, schema=None, **kw):
  2115. if schema:
  2116. schema_expr = "%s." % (
  2117. self.identifier_preparer.quote_identifier(schema)
  2118. )
  2119. else:
  2120. schema_expr = ""
  2121. try:
  2122. s = (
  2123. "SELECT sql FROM "
  2124. " (SELECT * FROM %(schema)ssqlite_master UNION ALL "
  2125. " SELECT * FROM %(schema)ssqlite_temp_master) "
  2126. "WHERE name = ? "
  2127. "AND type = 'table'" % {"schema": schema_expr}
  2128. )
  2129. rs = connection.exec_driver_sql(s, (table_name,))
  2130. except exc.DBAPIError:
  2131. s = (
  2132. "SELECT sql FROM %(schema)ssqlite_master "
  2133. "WHERE name = ? "
  2134. "AND type = 'table'" % {"schema": schema_expr}
  2135. )
  2136. rs = connection.exec_driver_sql(s, (table_name,))
  2137. return rs.scalar()
  2138. def _get_table_pragma(self, connection, pragma, table_name, schema=None):
  2139. quote = self.identifier_preparer.quote_identifier
  2140. if schema is not None:
  2141. statements = ["PRAGMA %s." % quote(schema)]
  2142. else:
  2143. # because PRAGMA looks in all attached databases if no schema
  2144. # given, need to specify "main" schema, however since we want
  2145. # 'temp' tables in the same namespace as 'main', need to run
  2146. # the PRAGMA twice
  2147. statements = ["PRAGMA main.", "PRAGMA temp."]
  2148. qtable = quote(table_name)
  2149. for statement in statements:
  2150. statement = "%s%s(%s)" % (statement, pragma, qtable)
  2151. cursor = connection.exec_driver_sql(statement)
  2152. if not cursor._soft_closed:
  2153. # work around SQLite issue whereby cursor.description
  2154. # is blank when PRAGMA returns no rows:
  2155. # https://www.sqlite.org/cvstrac/tktview?tn=1884
  2156. result = cursor.fetchall()
  2157. else:
  2158. result = []
  2159. if result:
  2160. return result
  2161. else:
  2162. return []