SQLAlchemy 2.0.36__cp313-cp313-win32.whl

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