Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

2545 řádky
86KB

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