base.py 100 KB

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