base.py 105 KB

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