base.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  1. # sqlite/base.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. r"""
  8. .. dialect:: sqlite
  9. :name: SQLite
  10. .. _sqlite_datetime:
  11. Date and Time Types
  12. -------------------
  13. SQLite does not have built-in DATE, TIME, or DATETIME types, and pysqlite does
  14. not provide out of the box functionality for translating values between Python
  15. `datetime` objects and a SQLite-supported format. SQLAlchemy's own
  16. :class:`~sqlalchemy.types.DateTime` and related types provide date formatting
  17. and parsing functionality when SQlite is used. The implementation classes are
  18. :class:`~.sqlite.DATETIME`, :class:`~.sqlite.DATE` and :class:`~.sqlite.TIME`.
  19. These types represent dates and times as ISO formatted strings, which also
  20. nicely support ordering. There's no reliance on typical "libc" internals for
  21. these functions so historical dates are fully supported.
  22. Ensuring Text affinity
  23. ^^^^^^^^^^^^^^^^^^^^^^
  24. The DDL rendered for these types is the standard ``DATE``, ``TIME``
  25. and ``DATETIME`` indicators. However, custom storage formats can also be
  26. applied to these types. When the
  27. storage format is detected as containing no alpha characters, the DDL for
  28. these types is rendered as ``DATE_CHAR``, ``TIME_CHAR``, and ``DATETIME_CHAR``,
  29. so that the column continues to have textual affinity.
  30. .. seealso::
  31. `Type Affinity <http://www.sqlite.org/datatype3.html#affinity>`_ - in the SQLite documentation
  32. .. _sqlite_autoincrement:
  33. SQLite Auto Incrementing Behavior
  34. ----------------------------------
  35. Background on SQLite's autoincrement is at: http://sqlite.org/autoinc.html
  36. Key concepts:
  37. * SQLite has an implicit "auto increment" feature that takes place for any
  38. non-composite primary-key column that is specifically created using
  39. "INTEGER PRIMARY KEY" for the type + primary key.
  40. * SQLite also has an explicit "AUTOINCREMENT" keyword, that is **not**
  41. equivalent to the implicit autoincrement feature; this keyword is not
  42. recommended for general use. SQLAlchemy does not render this keyword
  43. unless a special SQLite-specific directive is used (see below). However,
  44. it still requires that the column's type is named "INTEGER".
  45. Using the AUTOINCREMENT Keyword
  46. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  47. To specifically render the AUTOINCREMENT keyword on the primary key column
  48. when rendering DDL, add the flag ``sqlite_autoincrement=True`` to the Table
  49. construct::
  50. Table('sometable', metadata,
  51. Column('id', Integer, primary_key=True),
  52. sqlite_autoincrement=True)
  53. Allowing autoincrement behavior SQLAlchemy types other than Integer/INTEGER
  54. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  55. SQLite's typing model is based on naming conventions. Among
  56. other things, this means that any type name which contains the
  57. substring ``"INT"`` will be determined to be of "integer affinity". A
  58. type named ``"BIGINT"``, ``"SPECIAL_INT"`` or even ``"XYZINTQPR"``, will be considered by
  59. SQLite to be of "integer" affinity. However, **the SQLite
  60. autoincrement feature, whether implicitly or explicitly enabled,
  61. requires that the name of the column's type
  62. is exactly the string "INTEGER"**. Therefore, if an
  63. application uses a type like :class:`.BigInteger` for a primary key, on
  64. SQLite this type will need to be rendered as the name ``"INTEGER"`` when
  65. emitting the initial ``CREATE TABLE`` statement in order for the autoincrement
  66. behavior to be available.
  67. One approach to achieve this is to use :class:`.Integer` on SQLite
  68. only using :meth:`.TypeEngine.with_variant`::
  69. table = Table(
  70. "my_table", metadata,
  71. Column("id", BigInteger().with_variant(Integer, "sqlite"), primary_key=True)
  72. )
  73. Another is to use a subclass of :class:`.BigInteger` that overrides its DDL name
  74. to be ``INTEGER`` when compiled against SQLite::
  75. from sqlalchemy import BigInteger
  76. from sqlalchemy.ext.compiler import compiles
  77. class SLBigInteger(BigInteger):
  78. pass
  79. @compiles(SLBigInteger, 'sqlite')
  80. def bi_c(element, compiler, **kw):
  81. return "INTEGER"
  82. @compiles(SLBigInteger)
  83. def bi_c(element, compiler, **kw):
  84. return compiler.visit_BIGINT(element, **kw)
  85. table = Table(
  86. "my_table", metadata,
  87. Column("id", SLBigInteger(), primary_key=True)
  88. )
  89. .. seealso::
  90. :meth:`.TypeEngine.with_variant`
  91. :ref:`sqlalchemy.ext.compiler_toplevel`
  92. `Datatypes In SQLite Version 3 <http://sqlite.org/datatype3.html>`_
  93. .. _sqlite_concurrency:
  94. Database Locking Behavior / Concurrency
  95. ---------------------------------------
  96. SQLite is not designed for a high level of write concurrency. The database
  97. itself, being a file, is locked completely during write operations within
  98. transactions, meaning exactly one "connection" (in reality a file handle)
  99. has exclusive access to the database during this period - all other
  100. "connections" will be blocked during this time.
  101. The Python DBAPI specification also calls for a connection model that is
  102. always in a transaction; there is no ``connection.begin()`` method,
  103. only ``connection.commit()`` and ``connection.rollback()``, upon which a
  104. new transaction is to be begun immediately. This may seem to imply
  105. that the SQLite driver would in theory allow only a single filehandle on a
  106. particular database file at any time; however, there are several
  107. factors both within SQlite itself as well as within the pysqlite driver
  108. which loosen this restriction significantly.
  109. However, no matter what locking modes are used, SQLite will still always
  110. lock the database file once a transaction is started and DML (e.g. INSERT,
  111. UPDATE, DELETE) has at least been emitted, and this will block
  112. other transactions at least at the point that they also attempt to emit DML.
  113. By default, the length of time on this block is very short before it times out
  114. with an error.
  115. This behavior becomes more critical when used in conjunction with the
  116. SQLAlchemy ORM. SQLAlchemy's :class:`.Session` object by default runs
  117. within a transaction, and with its autoflush model, may emit DML preceding
  118. any SELECT statement. This may lead to a SQLite database that locks
  119. more quickly than is expected. The locking mode of SQLite and the pysqlite
  120. driver can be manipulated to some degree, however it should be noted that
  121. achieving a high degree of write-concurrency with SQLite is a losing battle.
  122. For more information on SQLite's lack of write concurrency by design, please
  123. see
  124. `Situations Where Another RDBMS May Work Better - High Concurrency
  125. <http://www.sqlite.org/whentouse.html>`_ near the bottom of the page.
  126. The following subsections introduce areas that are impacted by SQLite's
  127. file-based architecture and additionally will usually require workarounds to
  128. work when using the pysqlite driver.
  129. .. _sqlite_isolation_level:
  130. Transaction Isolation Level
  131. ----------------------------
  132. SQLite supports "transaction isolation" in a non-standard way, along two
  133. axes. One is that of the `PRAGMA read_uncommitted <http://www.sqlite.org/pragma.html#pragma_read_uncommitted>`_
  134. instruction. This setting can essentially switch SQLite between its
  135. default mode of ``SERIALIZABLE`` isolation, and a "dirty read" isolation
  136. mode normally referred to as ``READ UNCOMMITTED``.
  137. SQLAlchemy ties into this PRAGMA statement using the
  138. :paramref:`.create_engine.isolation_level` parameter of :func:`.create_engine`.
  139. Valid values for this parameter when used with SQLite are ``"SERIALIZABLE"``
  140. and ``"READ UNCOMMITTED"`` corresponding to a value of 0 and 1, respectively.
  141. SQLite defaults to ``SERIALIZABLE``, however its behavior is impacted by
  142. the pysqlite driver's default behavior.
  143. The other axis along which SQLite's transactional locking is impacted is
  144. via the nature of the ``BEGIN`` statement used. The three varieties
  145. are "deferred", "immediate", and "exclusive", as described at
  146. `BEGIN TRANSACTION <http://sqlite.org/lang_transaction.html>`_. A straight
  147. ``BEGIN`` statement uses the "deferred" mode, where the the database file is
  148. not locked until the first read or write operation, and read access remains
  149. open to other transactions until the first write operation. But again,
  150. it is critical to note that the pysqlite driver interferes with this behavior
  151. by *not even emitting BEGIN* until the first write operation.
  152. .. warning::
  153. SQLite's transactional scope is impacted by unresolved
  154. issues in the pysqlite driver, which defers BEGIN statements to a greater
  155. degree than is often feasible. See the section :ref:`pysqlite_serializable`
  156. for techniques to work around this behavior.
  157. SAVEPOINT Support
  158. ----------------------------
  159. SQLite supports SAVEPOINTs, which only function once a transaction is
  160. begun. SQLAlchemy's SAVEPOINT support is available using the
  161. :meth:`.Connection.begin_nested` method at the Core level, and
  162. :meth:`.Session.begin_nested` at the ORM level. However, SAVEPOINTs
  163. won't work at all with pysqlite unless workarounds are taken.
  164. .. warning::
  165. SQLite's SAVEPOINT feature is impacted by unresolved
  166. issues in the pysqlite driver, which defers BEGIN statements to a greater
  167. degree than is often feasible. See the section :ref:`pysqlite_serializable`
  168. for techniques to work around this behavior.
  169. Transactional DDL
  170. ----------------------------
  171. The SQLite database supports transactional :term:`DDL` as well.
  172. In this case, the pysqlite driver is not only failing to start transactions,
  173. it also is ending any existing transction when DDL is detected, so again,
  174. workarounds are required.
  175. .. warning::
  176. SQLite's transactional DDL is impacted by unresolved issues
  177. in the pysqlite driver, which fails to emit BEGIN and additionally
  178. forces a COMMIT to cancel any transaction when DDL is encountered.
  179. See the section :ref:`pysqlite_serializable`
  180. for techniques to work around this behavior.
  181. .. _sqlite_foreign_keys:
  182. Foreign Key Support
  183. -------------------
  184. SQLite supports FOREIGN KEY syntax when emitting CREATE statements for tables,
  185. however by default these constraints have no effect on the operation of the
  186. table.
  187. Constraint checking on SQLite has three prerequisites:
  188. * At least version 3.6.19 of SQLite must be in use
  189. * The SQLite library must be compiled *without* the SQLITE_OMIT_FOREIGN_KEY
  190. or SQLITE_OMIT_TRIGGER symbols enabled.
  191. * The ``PRAGMA foreign_keys = ON`` statement must be emitted on all
  192. connections before use.
  193. SQLAlchemy allows for the ``PRAGMA`` statement to be emitted automatically for
  194. new connections through the usage of events::
  195. from sqlalchemy.engine import Engine
  196. from sqlalchemy import event
  197. @event.listens_for(Engine, "connect")
  198. def set_sqlite_pragma(dbapi_connection, connection_record):
  199. cursor = dbapi_connection.cursor()
  200. cursor.execute("PRAGMA foreign_keys=ON")
  201. cursor.close()
  202. .. warning::
  203. When SQLite foreign keys are enabled, it is **not possible**
  204. to emit CREATE or DROP statements for tables that contain
  205. mutually-dependent foreign key constraints;
  206. to emit the DDL for these tables requires that ALTER TABLE be used to
  207. create or drop these constraints separately, for which SQLite has
  208. no support.
  209. .. seealso::
  210. `SQLite Foreign Key Support <http://www.sqlite.org/foreignkeys.html>`_
  211. - on the SQLite web site.
  212. :ref:`event_toplevel` - SQLAlchemy event API.
  213. :ref:`use_alter` - more information on SQLAlchemy's facilities for handling
  214. mutually-dependent foreign key constraints.
  215. .. _sqlite_type_reflection:
  216. Type Reflection
  217. ---------------
  218. SQLite types are unlike those of most other database backends, in that
  219. the string name of the type usually does not correspond to a "type" in a
  220. one-to-one fashion. Instead, SQLite links per-column typing behavior
  221. to one of five so-called "type affinities" based on a string matching
  222. pattern for the type.
  223. SQLAlchemy's reflection process, when inspecting types, uses a simple
  224. lookup table to link the keywords returned to provided SQLAlchemy types.
  225. This lookup table is present within the SQLite dialect as it is for all
  226. other dialects. However, the SQLite dialect has a different "fallback"
  227. routine for when a particular type name is not located in the lookup map;
  228. it instead implements the SQLite "type affinity" scheme located at
  229. http://www.sqlite.org/datatype3.html section 2.1.
  230. The provided typemap will make direct associations from an exact string
  231. name match for the following types:
  232. :class:`~.types.BIGINT`, :class:`~.types.BLOB`,
  233. :class:`~.types.BOOLEAN`, :class:`~.types.BOOLEAN`,
  234. :class:`~.types.CHAR`, :class:`~.types.DATE`,
  235. :class:`~.types.DATETIME`, :class:`~.types.FLOAT`,
  236. :class:`~.types.DECIMAL`, :class:`~.types.FLOAT`,
  237. :class:`~.types.INTEGER`, :class:`~.types.INTEGER`,
  238. :class:`~.types.NUMERIC`, :class:`~.types.REAL`,
  239. :class:`~.types.SMALLINT`, :class:`~.types.TEXT`,
  240. :class:`~.types.TIME`, :class:`~.types.TIMESTAMP`,
  241. :class:`~.types.VARCHAR`, :class:`~.types.NVARCHAR`,
  242. :class:`~.types.NCHAR`
  243. When a type name does not match one of the above types, the "type affinity"
  244. lookup is used instead:
  245. * :class:`~.types.INTEGER` is returned if the type name includes the
  246. string ``INT``
  247. * :class:`~.types.TEXT` is returned if the type name includes the
  248. string ``CHAR``, ``CLOB`` or ``TEXT``
  249. * :class:`~.types.NullType` is returned if the type name includes the
  250. string ``BLOB``
  251. * :class:`~.types.REAL` is returned if the type name includes the string
  252. ``REAL``, ``FLOA`` or ``DOUB``.
  253. * Otherwise, the :class:`~.types.NUMERIC` type is used.
  254. .. versionadded:: 0.9.3 Support for SQLite type affinity rules when reflecting
  255. columns.
  256. .. _sqlite_partial_index:
  257. Partial Indexes
  258. ---------------
  259. A partial index, e.g. one which uses a WHERE clause, can be specified
  260. with the DDL system using the argument ``sqlite_where``::
  261. tbl = Table('testtbl', m, Column('data', Integer))
  262. idx = Index('test_idx1', tbl.c.data,
  263. sqlite_where=and_(tbl.c.data > 5, tbl.c.data < 10))
  264. The index will be rendered at create time as::
  265. CREATE INDEX test_idx1 ON testtbl (data)
  266. WHERE data > 5 AND data < 10
  267. .. versionadded:: 0.9.9
  268. .. _sqlite_dotted_column_names:
  269. Dotted Column Names
  270. -------------------
  271. Using table or column names that explicitly have periods in them is
  272. **not recommended**. While this is generally a bad idea for relational
  273. databases in general, as the dot is a syntactically significant character,
  274. the SQLite driver up until version **3.10.0** of SQLite has a bug which
  275. requires that SQLAlchemy filter out these dots in result sets.
  276. .. versionchanged:: 1.1
  277. The following SQLite issue has been resolved as of version 3.10.0
  278. of SQLite. SQLAlchemy as of **1.1** automatically disables its internal
  279. workarounds based on detection of this version.
  280. The bug, entirely outside of SQLAlchemy, can be illustrated thusly::
  281. import sqlite3
  282. assert sqlite3.sqlite_version_info < (3, 10, 0), "bug is fixed in this version"
  283. conn = sqlite3.connect(":memory:")
  284. cursor = conn.cursor()
  285. cursor.execute("create table x (a integer, b integer)")
  286. cursor.execute("insert into x (a, b) values (1, 1)")
  287. cursor.execute("insert into x (a, b) values (2, 2)")
  288. cursor.execute("select x.a, x.b from x")
  289. assert [c[0] for c in cursor.description] == ['a', 'b']
  290. cursor.execute('''
  291. select x.a, x.b from x where a=1
  292. union
  293. select x.a, x.b from x where a=2
  294. ''')
  295. assert [c[0] for c in cursor.description] == ['a', 'b'], \
  296. [c[0] for c in cursor.description]
  297. The second assertion fails::
  298. Traceback (most recent call last):
  299. File "test.py", line 19, in <module>
  300. [c[0] for c in cursor.description]
  301. AssertionError: ['x.a', 'x.b']
  302. Where above, the driver incorrectly reports the names of the columns
  303. including the name of the table, which is entirely inconsistent vs.
  304. when the UNION is not present.
  305. SQLAlchemy relies upon column names being predictable in how they match
  306. to the original statement, so the SQLAlchemy dialect has no choice but
  307. to filter these out::
  308. from sqlalchemy import create_engine
  309. eng = create_engine("sqlite://")
  310. conn = eng.connect()
  311. conn.execute("create table x (a integer, b integer)")
  312. conn.execute("insert into x (a, b) values (1, 1)")
  313. conn.execute("insert into x (a, b) values (2, 2)")
  314. result = conn.execute("select x.a, x.b from x")
  315. assert result.keys() == ["a", "b"]
  316. result = conn.execute('''
  317. select x.a, x.b from x where a=1
  318. union
  319. select x.a, x.b from x where a=2
  320. ''')
  321. assert result.keys() == ["a", "b"]
  322. Note that above, even though SQLAlchemy filters out the dots, *both
  323. names are still addressable*::
  324. >>> row = result.first()
  325. >>> row["a"]
  326. 1
  327. >>> row["x.a"]
  328. 1
  329. >>> row["b"]
  330. 1
  331. >>> row["x.b"]
  332. 1
  333. Therefore, the workaround applied by SQLAlchemy only impacts
  334. :meth:`.ResultProxy.keys` and :meth:`.RowProxy.keys()` in the public API.
  335. In the very specific case where
  336. an application is forced to use column names that contain dots, and the
  337. functionality of :meth:`.ResultProxy.keys` and :meth:`.RowProxy.keys()`
  338. is required to return these dotted names unmodified, the ``sqlite_raw_colnames``
  339. execution option may be provided, either on a per-:class:`.Connection` basis::
  340. result = conn.execution_options(sqlite_raw_colnames=True).execute('''
  341. select x.a, x.b from x where a=1
  342. union
  343. select x.a, x.b from x where a=2
  344. ''')
  345. assert result.keys() == ["x.a", "x.b"]
  346. or on a per-:class:`.Engine` basis::
  347. engine = create_engine("sqlite://", execution_options={"sqlite_raw_colnames": True})
  348. When using the per-:class:`.Engine` execution option, note that
  349. **Core and ORM queries that use UNION may not function properly**.
  350. """
  351. import datetime
  352. import re
  353. from ... import processors
  354. from ... import sql, exc
  355. from ... import types as sqltypes, schema as sa_schema
  356. from ... import util
  357. from ...engine import default, reflection
  358. from ...sql import compiler
  359. from ...types import (BLOB, BOOLEAN, CHAR, DECIMAL, FLOAT,
  360. INTEGER, REAL, NUMERIC, SMALLINT, TEXT,
  361. TIMESTAMP, VARCHAR)
  362. class _DateTimeMixin(object):
  363. _reg = None
  364. _storage_format = None
  365. def __init__(self, storage_format=None, regexp=None, **kw):
  366. super(_DateTimeMixin, self).__init__(**kw)
  367. if regexp is not None:
  368. self._reg = re.compile(regexp)
  369. if storage_format is not None:
  370. self._storage_format = storage_format
  371. @property
  372. def format_is_text_affinity(self):
  373. """return True if the storage format will automatically imply
  374. a TEXT affinity.
  375. If the storage format contains no non-numeric characters,
  376. it will imply a NUMERIC storage format on SQLite; in this case,
  377. the type will generate its DDL as DATE_CHAR, DATETIME_CHAR,
  378. TIME_CHAR.
  379. .. versionadded:: 1.0.0
  380. """
  381. spec = self._storage_format % {
  382. "year": 0, "month": 0, "day": 0, "hour": 0,
  383. "minute": 0, "second": 0, "microsecond": 0
  384. }
  385. return bool(re.search(r'[^0-9]', spec))
  386. def adapt(self, cls, **kw):
  387. if issubclass(cls, _DateTimeMixin):
  388. if self._storage_format:
  389. kw["storage_format"] = self._storage_format
  390. if self._reg:
  391. kw["regexp"] = self._reg
  392. return super(_DateTimeMixin, self).adapt(cls, **kw)
  393. def literal_processor(self, dialect):
  394. bp = self.bind_processor(dialect)
  395. def process(value):
  396. return "'%s'" % bp(value)
  397. return process
  398. class DATETIME(_DateTimeMixin, sqltypes.DateTime):
  399. r"""Represent a Python datetime object in SQLite using a string.
  400. The default string storage format is::
  401. "%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(min)02d:\
  402. %(second)02d.%(microsecond)06d"
  403. e.g.::
  404. 2011-03-15 12:05:57.10558
  405. The storage format can be customized to some degree using the
  406. ``storage_format`` and ``regexp`` parameters, such as::
  407. import re
  408. from sqlalchemy.dialects.sqlite import DATETIME
  409. dt = DATETIME(storage_format="%(year)04d/%(month)02d/%(day)02d "
  410. "%(hour)02d:%(min)02d:%(second)02d",
  411. regexp=r"(\d+)/(\d+)/(\d+) (\d+)-(\d+)-(\d+)"
  412. )
  413. :param storage_format: format string which will be applied to the dict
  414. with keys year, month, day, hour, minute, second, and microsecond.
  415. :param regexp: regular expression which will be applied to incoming result
  416. rows. If the regexp contains named groups, the resulting match dict is
  417. applied to the Python datetime() constructor as keyword arguments.
  418. Otherwise, if positional groups are used, the datetime() constructor
  419. is called with positional arguments via
  420. ``*map(int, match_obj.groups(0))``.
  421. """
  422. _storage_format = (
  423. "%(year)04d-%(month)02d-%(day)02d "
  424. "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  425. )
  426. def __init__(self, *args, **kwargs):
  427. truncate_microseconds = kwargs.pop('truncate_microseconds', False)
  428. super(DATETIME, self).__init__(*args, **kwargs)
  429. if truncate_microseconds:
  430. assert 'storage_format' not in kwargs, "You can specify only "\
  431. "one of truncate_microseconds or storage_format."
  432. assert 'regexp' not in kwargs, "You can specify only one of "\
  433. "truncate_microseconds or regexp."
  434. self._storage_format = (
  435. "%(year)04d-%(month)02d-%(day)02d "
  436. "%(hour)02d:%(minute)02d:%(second)02d"
  437. )
  438. def bind_processor(self, dialect):
  439. datetime_datetime = datetime.datetime
  440. datetime_date = datetime.date
  441. format = self._storage_format
  442. def process(value):
  443. if value is None:
  444. return None
  445. elif isinstance(value, datetime_datetime):
  446. return format % {
  447. 'year': value.year,
  448. 'month': value.month,
  449. 'day': value.day,
  450. 'hour': value.hour,
  451. 'minute': value.minute,
  452. 'second': value.second,
  453. 'microsecond': value.microsecond,
  454. }
  455. elif isinstance(value, datetime_date):
  456. return format % {
  457. 'year': value.year,
  458. 'month': value.month,
  459. 'day': value.day,
  460. 'hour': 0,
  461. 'minute': 0,
  462. 'second': 0,
  463. 'microsecond': 0,
  464. }
  465. else:
  466. raise TypeError("SQLite DateTime type only accepts Python "
  467. "datetime and date objects as input.")
  468. return process
  469. def result_processor(self, dialect, coltype):
  470. if self._reg:
  471. return processors.str_to_datetime_processor_factory(
  472. self._reg, datetime.datetime)
  473. else:
  474. return processors.str_to_datetime
  475. class DATE(_DateTimeMixin, sqltypes.Date):
  476. r"""Represent a Python date object in SQLite using a string.
  477. The default string storage format is::
  478. "%(year)04d-%(month)02d-%(day)02d"
  479. e.g.::
  480. 2011-03-15
  481. The storage format can be customized to some degree using the
  482. ``storage_format`` and ``regexp`` parameters, such as::
  483. import re
  484. from sqlalchemy.dialects.sqlite import DATE
  485. d = DATE(
  486. storage_format="%(month)02d/%(day)02d/%(year)04d",
  487. regexp=re.compile("(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)")
  488. )
  489. :param storage_format: format string which will be applied to the
  490. dict with keys year, month, and day.
  491. :param regexp: regular expression which will be applied to
  492. incoming result rows. If the regexp contains named groups, the
  493. resulting match dict is applied to the Python date() constructor
  494. as keyword arguments. Otherwise, if positional groups are used, the
  495. date() constructor is called with positional arguments via
  496. ``*map(int, match_obj.groups(0))``.
  497. """
  498. _storage_format = "%(year)04d-%(month)02d-%(day)02d"
  499. def bind_processor(self, dialect):
  500. datetime_date = datetime.date
  501. format = self._storage_format
  502. def process(value):
  503. if value is None:
  504. return None
  505. elif isinstance(value, datetime_date):
  506. return format % {
  507. 'year': value.year,
  508. 'month': value.month,
  509. 'day': value.day,
  510. }
  511. else:
  512. raise TypeError("SQLite Date type only accepts Python "
  513. "date objects as input.")
  514. return process
  515. def result_processor(self, dialect, coltype):
  516. if self._reg:
  517. return processors.str_to_datetime_processor_factory(
  518. self._reg, datetime.date)
  519. else:
  520. return processors.str_to_date
  521. class TIME(_DateTimeMixin, sqltypes.Time):
  522. r"""Represent a Python time object in SQLite using a string.
  523. The default string storage format is::
  524. "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  525. e.g.::
  526. 12:05:57.10558
  527. The storage format can be customized to some degree using the
  528. ``storage_format`` and ``regexp`` parameters, such as::
  529. import re
  530. from sqlalchemy.dialects.sqlite import TIME
  531. t = TIME(storage_format="%(hour)02d-%(minute)02d-"
  532. "%(second)02d-%(microsecond)06d",
  533. regexp=re.compile("(\d+)-(\d+)-(\d+)-(?:-(\d+))?")
  534. )
  535. :param storage_format: format string which will be applied to the dict
  536. with keys hour, minute, second, and microsecond.
  537. :param regexp: regular expression which will be applied to incoming result
  538. rows. If the regexp contains named groups, the resulting match dict is
  539. applied to the Python time() constructor as keyword arguments. Otherwise,
  540. if positional groups are used, the time() constructor is called with
  541. positional arguments via ``*map(int, match_obj.groups(0))``.
  542. """
  543. _storage_format = "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
  544. def __init__(self, *args, **kwargs):
  545. truncate_microseconds = kwargs.pop('truncate_microseconds', False)
  546. super(TIME, self).__init__(*args, **kwargs)
  547. if truncate_microseconds:
  548. assert 'storage_format' not in kwargs, "You can specify only "\
  549. "one of truncate_microseconds or storage_format."
  550. assert 'regexp' not in kwargs, "You can specify only one of "\
  551. "truncate_microseconds or regexp."
  552. self._storage_format = "%(hour)02d:%(minute)02d:%(second)02d"
  553. def bind_processor(self, dialect):
  554. datetime_time = datetime.time
  555. format = self._storage_format
  556. def process(value):
  557. if value is None:
  558. return None
  559. elif isinstance(value, datetime_time):
  560. return format % {
  561. 'hour': value.hour,
  562. 'minute': value.minute,
  563. 'second': value.second,
  564. 'microsecond': value.microsecond,
  565. }
  566. else:
  567. raise TypeError("SQLite Time type only accepts Python "
  568. "time objects as input.")
  569. return process
  570. def result_processor(self, dialect, coltype):
  571. if self._reg:
  572. return processors.str_to_datetime_processor_factory(
  573. self._reg, datetime.time)
  574. else:
  575. return processors.str_to_time
  576. colspecs = {
  577. sqltypes.Date: DATE,
  578. sqltypes.DateTime: DATETIME,
  579. sqltypes.Time: TIME,
  580. }
  581. ischema_names = {
  582. 'BIGINT': sqltypes.BIGINT,
  583. 'BLOB': sqltypes.BLOB,
  584. 'BOOL': sqltypes.BOOLEAN,
  585. 'BOOLEAN': sqltypes.BOOLEAN,
  586. 'CHAR': sqltypes.CHAR,
  587. 'DATE': sqltypes.DATE,
  588. 'DATE_CHAR': sqltypes.DATE,
  589. 'DATETIME': sqltypes.DATETIME,
  590. 'DATETIME_CHAR': sqltypes.DATETIME,
  591. 'DOUBLE': sqltypes.FLOAT,
  592. 'DECIMAL': sqltypes.DECIMAL,
  593. 'FLOAT': sqltypes.FLOAT,
  594. 'INT': sqltypes.INTEGER,
  595. 'INTEGER': sqltypes.INTEGER,
  596. 'NUMERIC': sqltypes.NUMERIC,
  597. 'REAL': sqltypes.REAL,
  598. 'SMALLINT': sqltypes.SMALLINT,
  599. 'TEXT': sqltypes.TEXT,
  600. 'TIME': sqltypes.TIME,
  601. 'TIME_CHAR': sqltypes.TIME,
  602. 'TIMESTAMP': sqltypes.TIMESTAMP,
  603. 'VARCHAR': sqltypes.VARCHAR,
  604. 'NVARCHAR': sqltypes.NVARCHAR,
  605. 'NCHAR': sqltypes.NCHAR,
  606. }
  607. class SQLiteCompiler(compiler.SQLCompiler):
  608. extract_map = util.update_copy(
  609. compiler.SQLCompiler.extract_map,
  610. {
  611. 'month': '%m',
  612. 'day': '%d',
  613. 'year': '%Y',
  614. 'second': '%S',
  615. 'hour': '%H',
  616. 'doy': '%j',
  617. 'minute': '%M',
  618. 'epoch': '%s',
  619. 'dow': '%w',
  620. 'week': '%W',
  621. })
  622. def visit_now_func(self, fn, **kw):
  623. return "CURRENT_TIMESTAMP"
  624. def visit_localtimestamp_func(self, func, **kw):
  625. return 'DATETIME(CURRENT_TIMESTAMP, "localtime")'
  626. def visit_true(self, expr, **kw):
  627. return '1'
  628. def visit_false(self, expr, **kw):
  629. return '0'
  630. def visit_char_length_func(self, fn, **kw):
  631. return "length%s" % self.function_argspec(fn)
  632. def visit_cast(self, cast, **kwargs):
  633. if self.dialect.supports_cast:
  634. return super(SQLiteCompiler, self).visit_cast(cast, **kwargs)
  635. else:
  636. return self.process(cast.clause, **kwargs)
  637. def visit_extract(self, extract, **kw):
  638. try:
  639. return "CAST(STRFTIME('%s', %s) AS INTEGER)" % (
  640. self.extract_map[extract.field],
  641. self.process(extract.expr, **kw)
  642. )
  643. except KeyError:
  644. raise exc.CompileError(
  645. "%s is not a valid extract argument." % extract.field)
  646. def limit_clause(self, select, **kw):
  647. text = ""
  648. if select._limit_clause is not None:
  649. text += "\n LIMIT " + self.process(select._limit_clause, **kw)
  650. if select._offset_clause is not None:
  651. if select._limit_clause is None:
  652. text += "\n LIMIT " + self.process(sql.literal(-1))
  653. text += " OFFSET " + self.process(select._offset_clause, **kw)
  654. else:
  655. text += " OFFSET " + self.process(sql.literal(0), **kw)
  656. return text
  657. def for_update_clause(self, select, **kw):
  658. # sqlite has no "FOR UPDATE" AFAICT
  659. return ''
  660. def visit_is_distinct_from_binary(self, binary, operator, **kw):
  661. return "%s IS NOT %s" % (self.process(binary.left),
  662. self.process(binary.right))
  663. def visit_isnot_distinct_from_binary(self, binary, operator, **kw):
  664. return "%s IS %s" % (self.process(binary.left),
  665. self.process(binary.right))
  666. class SQLiteDDLCompiler(compiler.DDLCompiler):
  667. def get_column_specification(self, column, **kwargs):
  668. coltype = self.dialect.type_compiler.process(
  669. column.type, type_expression=column)
  670. colspec = self.preparer.format_column(column) + " " + coltype
  671. default = self.get_column_default_string(column)
  672. if default is not None:
  673. colspec += " DEFAULT " + default
  674. if not column.nullable:
  675. colspec += " NOT NULL"
  676. if column.primary_key:
  677. if (
  678. column.autoincrement is True and
  679. len(column.table.primary_key.columns) != 1
  680. ):
  681. raise exc.CompileError(
  682. "SQLite does not support autoincrement for "
  683. "composite primary keys")
  684. if (column.table.dialect_options['sqlite']['autoincrement'] and
  685. len(column.table.primary_key.columns) == 1 and
  686. issubclass(column.type._type_affinity, sqltypes.Integer) and
  687. not column.foreign_keys):
  688. colspec += " PRIMARY KEY AUTOINCREMENT"
  689. return colspec
  690. def visit_primary_key_constraint(self, constraint):
  691. # for columns with sqlite_autoincrement=True,
  692. # the PRIMARY KEY constraint can only be inline
  693. # with the column itself.
  694. if len(constraint.columns) == 1:
  695. c = list(constraint)[0]
  696. if (c.primary_key and
  697. c.table.dialect_options['sqlite']['autoincrement'] and
  698. issubclass(c.type._type_affinity, sqltypes.Integer) and
  699. not c.foreign_keys):
  700. return None
  701. return super(SQLiteDDLCompiler, self).visit_primary_key_constraint(
  702. constraint)
  703. def visit_foreign_key_constraint(self, constraint):
  704. local_table = constraint.elements[0].parent.table
  705. remote_table = constraint.elements[0].column.table
  706. if local_table.schema != remote_table.schema:
  707. return None
  708. else:
  709. return super(
  710. SQLiteDDLCompiler,
  711. self).visit_foreign_key_constraint(constraint)
  712. def define_constraint_remote_table(self, constraint, table, preparer):
  713. """Format the remote table clause of a CREATE CONSTRAINT clause."""
  714. return preparer.format_table(table, use_schema=False)
  715. def visit_create_index(self, create, include_schema=False,
  716. include_table_schema=True):
  717. index = create.element
  718. self._verify_index_table(index)
  719. preparer = self.preparer
  720. text = "CREATE "
  721. if index.unique:
  722. text += "UNIQUE "
  723. text += "INDEX %s ON %s (%s)" \
  724. % (
  725. self._prepared_index_name(index,
  726. include_schema=True),
  727. preparer.format_table(index.table,
  728. use_schema=False),
  729. ', '.join(
  730. self.sql_compiler.process(
  731. expr, include_table=False, literal_binds=True) for
  732. expr in index.expressions)
  733. )
  734. whereclause = index.dialect_options["sqlite"]["where"]
  735. if whereclause is not None:
  736. where_compiled = self.sql_compiler.process(
  737. whereclause, include_table=False,
  738. literal_binds=True)
  739. text += " WHERE " + where_compiled
  740. return text
  741. class SQLiteTypeCompiler(compiler.GenericTypeCompiler):
  742. def visit_large_binary(self, type_, **kw):
  743. return self.visit_BLOB(type_)
  744. def visit_DATETIME(self, type_, **kw):
  745. if not isinstance(type_, _DateTimeMixin) or \
  746. type_.format_is_text_affinity:
  747. return super(SQLiteTypeCompiler, self).visit_DATETIME(type_)
  748. else:
  749. return "DATETIME_CHAR"
  750. def visit_DATE(self, type_, **kw):
  751. if not isinstance(type_, _DateTimeMixin) or \
  752. type_.format_is_text_affinity:
  753. return super(SQLiteTypeCompiler, self).visit_DATE(type_)
  754. else:
  755. return "DATE_CHAR"
  756. def visit_TIME(self, type_, **kw):
  757. if not isinstance(type_, _DateTimeMixin) or \
  758. type_.format_is_text_affinity:
  759. return super(SQLiteTypeCompiler, self).visit_TIME(type_)
  760. else:
  761. return "TIME_CHAR"
  762. class SQLiteIdentifierPreparer(compiler.IdentifierPreparer):
  763. reserved_words = set([
  764. 'add', 'after', 'all', 'alter', 'analyze', 'and', 'as', 'asc',
  765. 'attach', 'autoincrement', 'before', 'begin', 'between', 'by',
  766. 'cascade', 'case', 'cast', 'check', 'collate', 'column', 'commit',
  767. 'conflict', 'constraint', 'create', 'cross', 'current_date',
  768. 'current_time', 'current_timestamp', 'database', 'default',
  769. 'deferrable', 'deferred', 'delete', 'desc', 'detach', 'distinct',
  770. 'drop', 'each', 'else', 'end', 'escape', 'except', 'exclusive',
  771. 'explain', 'false', 'fail', 'for', 'foreign', 'from', 'full', 'glob',
  772. 'group', 'having', 'if', 'ignore', 'immediate', 'in', 'index',
  773. 'indexed', 'initially', 'inner', 'insert', 'instead', 'intersect',
  774. 'into', 'is', 'isnull', 'join', 'key', 'left', 'like', 'limit',
  775. 'match', 'natural', 'not', 'notnull', 'null', 'of', 'offset', 'on',
  776. 'or', 'order', 'outer', 'plan', 'pragma', 'primary', 'query',
  777. 'raise', 'references', 'reindex', 'rename', 'replace', 'restrict',
  778. 'right', 'rollback', 'row', 'select', 'set', 'table', 'temp',
  779. 'temporary', 'then', 'to', 'transaction', 'trigger', 'true', 'union',
  780. 'unique', 'update', 'using', 'vacuum', 'values', 'view', 'virtual',
  781. 'when', 'where',
  782. ])
  783. def format_index(self, index, use_schema=True, name=None):
  784. """Prepare a quoted index and schema name."""
  785. if name is None:
  786. name = index.name
  787. result = self.quote(name, index.quote)
  788. if (not self.omit_schema and
  789. use_schema and
  790. getattr(index.table, "schema", None)):
  791. result = self.quote_schema(
  792. index.table.schema, index.table.quote_schema) + "." + result
  793. return result
  794. class SQLiteExecutionContext(default.DefaultExecutionContext):
  795. @util.memoized_property
  796. def _preserve_raw_colnames(self):
  797. return not self.dialect._broken_dotted_colnames or \
  798. self.execution_options.get("sqlite_raw_colnames", False)
  799. def _translate_colname(self, colname):
  800. # TODO: detect SQLite version 3.10.0 or greater;
  801. # see [ticket:3633]
  802. # adjust for dotted column names. SQLite
  803. # in the case of UNION may store col names as
  804. # "tablename.colname", or if using an attached database,
  805. # "database.tablename.colname", in cursor.description
  806. if not self._preserve_raw_colnames and "." in colname:
  807. return colname.split(".")[-1], colname
  808. else:
  809. return colname, None
  810. class SQLiteDialect(default.DefaultDialect):
  811. name = 'sqlite'
  812. supports_alter = False
  813. supports_unicode_statements = True
  814. supports_unicode_binds = True
  815. supports_default_values = True
  816. supports_empty_insert = False
  817. supports_cast = True
  818. supports_multivalues_insert = True
  819. default_paramstyle = 'qmark'
  820. execution_ctx_cls = SQLiteExecutionContext
  821. statement_compiler = SQLiteCompiler
  822. ddl_compiler = SQLiteDDLCompiler
  823. type_compiler = SQLiteTypeCompiler
  824. preparer = SQLiteIdentifierPreparer
  825. ischema_names = ischema_names
  826. colspecs = colspecs
  827. isolation_level = None
  828. supports_cast = True
  829. supports_default_values = True
  830. construct_arguments = [
  831. (sa_schema.Table, {
  832. "autoincrement": False
  833. }),
  834. (sa_schema.Index, {
  835. "where": None,
  836. }),
  837. ]
  838. _broken_fk_pragma_quotes = False
  839. _broken_dotted_colnames = False
  840. def __init__(self, isolation_level=None, native_datetime=False, **kwargs):
  841. default.DefaultDialect.__init__(self, **kwargs)
  842. self.isolation_level = isolation_level
  843. # this flag used by pysqlite dialect, and perhaps others in the
  844. # future, to indicate the driver is handling date/timestamp
  845. # conversions (and perhaps datetime/time as well on some hypothetical
  846. # driver ?)
  847. self.native_datetime = native_datetime
  848. if self.dbapi is not None:
  849. self.supports_right_nested_joins = (
  850. self.dbapi.sqlite_version_info >= (3, 7, 16))
  851. self._broken_dotted_colnames = (
  852. self.dbapi.sqlite_version_info < (3, 10, 0)
  853. )
  854. self.supports_default_values = (
  855. self.dbapi.sqlite_version_info >= (3, 3, 8))
  856. self.supports_cast = (
  857. self.dbapi.sqlite_version_info >= (3, 2, 3))
  858. self.supports_multivalues_insert = (
  859. # http://www.sqlite.org/releaselog/3_7_11.html
  860. self.dbapi.sqlite_version_info >= (3, 7, 11))
  861. # see http://www.sqlalchemy.org/trac/ticket/2568
  862. # as well as http://www.sqlite.org/src/info/600482d161
  863. self._broken_fk_pragma_quotes = (
  864. self.dbapi.sqlite_version_info < (3, 6, 14))
  865. _isolation_lookup = {
  866. 'READ UNCOMMITTED': 1,
  867. 'SERIALIZABLE': 0,
  868. }
  869. def set_isolation_level(self, connection, level):
  870. try:
  871. isolation_level = self._isolation_lookup[level.replace('_', ' ')]
  872. except KeyError:
  873. raise exc.ArgumentError(
  874. "Invalid value '%s' for isolation_level. "
  875. "Valid isolation levels for %s are %s" %
  876. (level, self.name, ", ".join(self._isolation_lookup))
  877. )
  878. cursor = connection.cursor()
  879. cursor.execute("PRAGMA read_uncommitted = %d" % isolation_level)
  880. cursor.close()
  881. def get_isolation_level(self, connection):
  882. cursor = connection.cursor()
  883. cursor.execute('PRAGMA read_uncommitted')
  884. res = cursor.fetchone()
  885. if res:
  886. value = res[0]
  887. else:
  888. # http://www.sqlite.org/changes.html#version_3_3_3
  889. # "Optional READ UNCOMMITTED isolation (instead of the
  890. # default isolation level of SERIALIZABLE) and
  891. # table level locking when database connections
  892. # share a common cache.""
  893. # pre-SQLite 3.3.0 default to 0
  894. value = 0
  895. cursor.close()
  896. if value == 0:
  897. return "SERIALIZABLE"
  898. elif value == 1:
  899. return "READ UNCOMMITTED"
  900. else:
  901. assert False, "Unknown isolation level %s" % value
  902. def on_connect(self):
  903. if self.isolation_level is not None:
  904. def connect(conn):
  905. self.set_isolation_level(conn, self.isolation_level)
  906. return connect
  907. else:
  908. return None
  909. @reflection.cache
  910. def get_schema_names(self, connection, **kw):
  911. s = "PRAGMA database_list"
  912. dl = connection.execute(s)
  913. return [db[1] for db in dl if db[1] != "temp"]
  914. @reflection.cache
  915. def get_table_names(self, connection, schema=None, **kw):
  916. if schema is not None:
  917. qschema = self.identifier_preparer.quote_identifier(schema)
  918. master = '%s.sqlite_master' % qschema
  919. else:
  920. master = "sqlite_master"
  921. s = ("SELECT name FROM %s "
  922. "WHERE type='table' ORDER BY name") % (master,)
  923. rs = connection.execute(s)
  924. return [row[0] for row in rs]
  925. @reflection.cache
  926. def get_temp_table_names(self, connection, **kw):
  927. s = "SELECT name FROM sqlite_temp_master "\
  928. "WHERE type='table' ORDER BY name "
  929. rs = connection.execute(s)
  930. return [row[0] for row in rs]
  931. @reflection.cache
  932. def get_temp_view_names(self, connection, **kw):
  933. s = "SELECT name FROM sqlite_temp_master "\
  934. "WHERE type='view' ORDER BY name "
  935. rs = connection.execute(s)
  936. return [row[0] for row in rs]
  937. def has_table(self, connection, table_name, schema=None):
  938. info = self._get_table_pragma(
  939. connection, "table_info", table_name, schema=schema)
  940. return bool(info)
  941. @reflection.cache
  942. def get_view_names(self, connection, schema=None, **kw):
  943. if schema is not None:
  944. qschema = self.identifier_preparer.quote_identifier(schema)
  945. master = '%s.sqlite_master' % qschema
  946. else:
  947. master = "sqlite_master"
  948. s = ("SELECT name FROM %s "
  949. "WHERE type='view' ORDER BY name") % (master,)
  950. rs = connection.execute(s)
  951. return [row[0] for row in rs]
  952. @reflection.cache
  953. def get_view_definition(self, connection, view_name, schema=None, **kw):
  954. if schema is not None:
  955. qschema = self.identifier_preparer.quote_identifier(schema)
  956. master = '%s.sqlite_master' % qschema
  957. s = ("SELECT sql FROM %s WHERE name = '%s'"
  958. "AND type='view'") % (master, view_name)
  959. rs = connection.execute(s)
  960. else:
  961. try:
  962. s = ("SELECT sql FROM "
  963. " (SELECT * FROM sqlite_master UNION ALL "
  964. " SELECT * FROM sqlite_temp_master) "
  965. "WHERE name = '%s' "
  966. "AND type='view'") % view_name
  967. rs = connection.execute(s)
  968. except exc.DBAPIError:
  969. s = ("SELECT sql FROM sqlite_master WHERE name = '%s' "
  970. "AND type='view'") % view_name
  971. rs = connection.execute(s)
  972. result = rs.fetchall()
  973. if result:
  974. return result[0].sql
  975. @reflection.cache
  976. def get_columns(self, connection, table_name, schema=None, **kw):
  977. info = self._get_table_pragma(
  978. connection, "table_info", table_name, schema=schema)
  979. columns = []
  980. for row in info:
  981. (name, type_, nullable, default, primary_key) = (
  982. row[1], row[2].upper(), not row[3], row[4], row[5])
  983. columns.append(self._get_column_info(name, type_, nullable,
  984. default, primary_key))
  985. return columns
  986. def _get_column_info(self, name, type_, nullable, default, primary_key):
  987. coltype = self._resolve_type_affinity(type_)
  988. if default is not None:
  989. default = util.text_type(default)
  990. return {
  991. 'name': name,
  992. 'type': coltype,
  993. 'nullable': nullable,
  994. 'default': default,
  995. 'autoincrement': 'auto',
  996. 'primary_key': primary_key,
  997. }
  998. def _resolve_type_affinity(self, type_):
  999. """Return a data type from a reflected column, using affinity tules.
  1000. SQLite's goal for universal compatibility introduces some complexity
  1001. during reflection, as a column's defined type might not actually be a
  1002. type that SQLite understands - or indeed, my not be defined *at all*.
  1003. Internally, SQLite handles this with a 'data type affinity' for each
  1004. column definition, mapping to one of 'TEXT', 'NUMERIC', 'INTEGER',
  1005. 'REAL', or 'NONE' (raw bits). The algorithm that determines this is
  1006. listed in http://www.sqlite.org/datatype3.html section 2.1.
  1007. This method allows SQLAlchemy to support that algorithm, while still
  1008. providing access to smarter reflection utilities by regcognizing
  1009. column definitions that SQLite only supports through affinity (like
  1010. DATE and DOUBLE).
  1011. """
  1012. match = re.match(r'([\w ]+)(\(.*?\))?', type_)
  1013. if match:
  1014. coltype = match.group(1)
  1015. args = match.group(2)
  1016. else:
  1017. coltype = ''
  1018. args = ''
  1019. if coltype in self.ischema_names:
  1020. coltype = self.ischema_names[coltype]
  1021. elif 'INT' in coltype:
  1022. coltype = sqltypes.INTEGER
  1023. elif 'CHAR' in coltype or 'CLOB' in coltype or 'TEXT' in coltype:
  1024. coltype = sqltypes.TEXT
  1025. elif 'BLOB' in coltype or not coltype:
  1026. coltype = sqltypes.NullType
  1027. elif 'REAL' in coltype or 'FLOA' in coltype or 'DOUB' in coltype:
  1028. coltype = sqltypes.REAL
  1029. else:
  1030. coltype = sqltypes.NUMERIC
  1031. if args is not None:
  1032. args = re.findall(r'(\d+)', args)
  1033. try:
  1034. coltype = coltype(*[int(a) for a in args])
  1035. except TypeError:
  1036. util.warn(
  1037. "Could not instantiate type %s with "
  1038. "reflected arguments %s; using no arguments." %
  1039. (coltype, args))
  1040. coltype = coltype()
  1041. else:
  1042. coltype = coltype()
  1043. return coltype
  1044. @reflection.cache
  1045. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  1046. constraint_name = None
  1047. table_data = self._get_table_sql(connection, table_name, schema=schema)
  1048. if table_data:
  1049. PK_PATTERN = r'CONSTRAINT (\w+) PRIMARY KEY'
  1050. result = re.search(PK_PATTERN, table_data, re.I)
  1051. constraint_name = result.group(1) if result else None
  1052. cols = self.get_columns(connection, table_name, schema, **kw)
  1053. pkeys = []
  1054. for col in cols:
  1055. if col['primary_key']:
  1056. pkeys.append(col['name'])
  1057. return {'constrained_columns': pkeys, 'name': constraint_name}
  1058. @reflection.cache
  1059. def get_foreign_keys(self, connection, table_name, schema=None, **kw):
  1060. # sqlite makes this *extremely difficult*.
  1061. # First, use the pragma to get the actual FKs.
  1062. pragma_fks = self._get_table_pragma(
  1063. connection, "foreign_key_list",
  1064. table_name, schema=schema
  1065. )
  1066. fks = {}
  1067. for row in pragma_fks:
  1068. (numerical_id, rtbl, lcol, rcol) = (
  1069. row[0], row[2], row[3], row[4])
  1070. if rcol is None:
  1071. rcol = lcol
  1072. if self._broken_fk_pragma_quotes:
  1073. rtbl = re.sub(r'^[\"\[`\']|[\"\]`\']$', '', rtbl)
  1074. if numerical_id in fks:
  1075. fk = fks[numerical_id]
  1076. else:
  1077. fk = fks[numerical_id] = {
  1078. 'name': None,
  1079. 'constrained_columns': [],
  1080. 'referred_schema': schema,
  1081. 'referred_table': rtbl,
  1082. 'referred_columns': [],
  1083. 'options': {}
  1084. }
  1085. fks[numerical_id] = fk
  1086. fk['constrained_columns'].append(lcol)
  1087. fk['referred_columns'].append(rcol)
  1088. def fk_sig(constrained_columns, referred_table, referred_columns):
  1089. return tuple(constrained_columns) + (referred_table,) + \
  1090. tuple(referred_columns)
  1091. # then, parse the actual SQL and attempt to find DDL that matches
  1092. # the names as well. SQLite saves the DDL in whatever format
  1093. # it was typed in as, so need to be liberal here.
  1094. keys_by_signature = dict(
  1095. (
  1096. fk_sig(
  1097. fk['constrained_columns'],
  1098. fk['referred_table'], fk['referred_columns']),
  1099. fk
  1100. ) for fk in fks.values()
  1101. )
  1102. table_data = self._get_table_sql(connection, table_name, schema=schema)
  1103. if table_data is None:
  1104. # system tables, etc.
  1105. return []
  1106. def parse_fks():
  1107. FK_PATTERN = (
  1108. r'(?:CONSTRAINT (\w+) +)?'
  1109. r'FOREIGN KEY *\( *(.+?) *\) +'
  1110. r'REFERENCES +(?:(?:"(.+?)")|([a-z0-9_]+)) *\((.+?)\) *'
  1111. r'((?:ON (?:DELETE|UPDATE) '
  1112. r'(?:SET NULL|SET DEFAULT|CASCADE|RESTRICT|NO ACTION) *)*)'
  1113. )
  1114. for match in re.finditer(FK_PATTERN, table_data, re.I):
  1115. (
  1116. constraint_name, constrained_columns,
  1117. referred_quoted_name, referred_name,
  1118. referred_columns, onupdatedelete) = \
  1119. match.group(1, 2, 3, 4, 5, 6)
  1120. constrained_columns = list(
  1121. self._find_cols_in_sig(constrained_columns))
  1122. if not referred_columns:
  1123. referred_columns = constrained_columns
  1124. else:
  1125. referred_columns = list(
  1126. self._find_cols_in_sig(referred_columns))
  1127. referred_name = referred_quoted_name or referred_name
  1128. options = {}
  1129. for token in re.split(r" *\bON\b *", onupdatedelete.upper()):
  1130. if token.startswith("DELETE"):
  1131. options['ondelete'] = token[6:].strip()
  1132. elif token.startswith("UPDATE"):
  1133. options["onupdate"] = token[6:].strip()
  1134. yield (
  1135. constraint_name, constrained_columns,
  1136. referred_name, referred_columns, options)
  1137. fkeys = []
  1138. for (
  1139. constraint_name, constrained_columns,
  1140. referred_name, referred_columns, options) in parse_fks():
  1141. sig = fk_sig(
  1142. constrained_columns, referred_name, referred_columns)
  1143. if sig not in keys_by_signature:
  1144. util.warn(
  1145. "WARNING: SQL-parsed foreign key constraint "
  1146. "'%s' could not be located in PRAGMA "
  1147. "foreign_keys for table %s" % (
  1148. sig,
  1149. table_name
  1150. ))
  1151. continue
  1152. key = keys_by_signature.pop(sig)
  1153. key['name'] = constraint_name
  1154. key['options'] = options
  1155. fkeys.append(key)
  1156. # assume the remainders are the unnamed, inline constraints, just
  1157. # use them as is as it's extremely difficult to parse inline
  1158. # constraints
  1159. fkeys.extend(keys_by_signature.values())
  1160. return fkeys
  1161. def _find_cols_in_sig(self, sig):
  1162. for match in re.finditer(r'(?:"(.+?)")|([a-z0-9_]+)', sig, re.I):
  1163. yield match.group(1) or match.group(2)
  1164. @reflection.cache
  1165. def get_unique_constraints(self, connection, table_name,
  1166. schema=None, **kw):
  1167. auto_index_by_sig = {}
  1168. for idx in self.get_indexes(
  1169. connection, table_name, schema=schema,
  1170. include_auto_indexes=True, **kw):
  1171. if not idx['name'].startswith("sqlite_autoindex"):
  1172. continue
  1173. sig = tuple(idx['column_names'])
  1174. auto_index_by_sig[sig] = idx
  1175. table_data = self._get_table_sql(
  1176. connection, table_name, schema=schema, **kw)
  1177. if not table_data:
  1178. return []
  1179. unique_constraints = []
  1180. def parse_uqs():
  1181. UNIQUE_PATTERN = r'(?:CONSTRAINT "?(.+?)"? +)?UNIQUE *\((.+?)\)'
  1182. INLINE_UNIQUE_PATTERN = (
  1183. r'(?:(".+?")|([a-z0-9]+)) '
  1184. r'+[a-z0-9_ ]+? +UNIQUE')
  1185. for match in re.finditer(UNIQUE_PATTERN, table_data, re.I):
  1186. name, cols = match.group(1, 2)
  1187. yield name, list(self._find_cols_in_sig(cols))
  1188. # we need to match inlines as well, as we seek to differentiate
  1189. # a UNIQUE constraint from a UNIQUE INDEX, even though these
  1190. # are kind of the same thing :)
  1191. for match in re.finditer(INLINE_UNIQUE_PATTERN, table_data, re.I):
  1192. cols = list(
  1193. self._find_cols_in_sig(match.group(1) or match.group(2)))
  1194. yield None, cols
  1195. for name, cols in parse_uqs():
  1196. sig = tuple(cols)
  1197. if sig in auto_index_by_sig:
  1198. auto_index_by_sig.pop(sig)
  1199. parsed_constraint = {
  1200. 'name': name,
  1201. 'column_names': cols
  1202. }
  1203. unique_constraints.append(parsed_constraint)
  1204. # NOTE: auto_index_by_sig might not be empty here,
  1205. # the PRIMARY KEY may have an entry.
  1206. return unique_constraints
  1207. @reflection.cache
  1208. def get_check_constraints(self, connection, table_name,
  1209. schema=None, **kw):
  1210. table_data = self._get_table_sql(
  1211. connection, table_name, schema=schema, **kw)
  1212. if not table_data:
  1213. return []
  1214. CHECK_PATTERN = (
  1215. r'(?:CONSTRAINT (\w+) +)?'
  1216. r'CHECK *\( *(.+) *\),? *'
  1217. )
  1218. check_constraints = []
  1219. # NOTE: we aren't using re.S here because we actually are
  1220. # taking advantage of each CHECK constraint being all on one
  1221. # line in the table definition in order to delineate. This
  1222. # necessarily makes assumptions as to how the CREATE TABLE
  1223. # was emitted.
  1224. for match in re.finditer(CHECK_PATTERN, table_data, re.I):
  1225. check_constraints.append({
  1226. 'sqltext': match.group(2),
  1227. 'name': match.group(1)
  1228. })
  1229. return check_constraints
  1230. @reflection.cache
  1231. def get_indexes(self, connection, table_name, schema=None, **kw):
  1232. pragma_indexes = self._get_table_pragma(
  1233. connection, "index_list", table_name, schema=schema)
  1234. indexes = []
  1235. include_auto_indexes = kw.pop('include_auto_indexes', False)
  1236. for row in pragma_indexes:
  1237. # ignore implicit primary key index.
  1238. # http://www.mail-archive.com/sqlite-users@sqlite.org/msg30517.html
  1239. if (not include_auto_indexes and
  1240. row[1].startswith('sqlite_autoindex')):
  1241. continue
  1242. indexes.append(dict(name=row[1], column_names=[], unique=row[2]))
  1243. # loop thru unique indexes to get the column names.
  1244. for idx in indexes:
  1245. pragma_index = self._get_table_pragma(
  1246. connection, "index_info", idx['name'])
  1247. for row in pragma_index:
  1248. idx['column_names'].append(row[2])
  1249. return indexes
  1250. @reflection.cache
  1251. def _get_table_sql(self, connection, table_name, schema=None, **kw):
  1252. try:
  1253. s = ("SELECT sql FROM "
  1254. " (SELECT * FROM sqlite_master UNION ALL "
  1255. " SELECT * FROM sqlite_temp_master) "
  1256. "WHERE name = '%s' "
  1257. "AND type = 'table'") % table_name
  1258. rs = connection.execute(s)
  1259. except exc.DBAPIError:
  1260. s = ("SELECT sql FROM sqlite_master WHERE name = '%s' "
  1261. "AND type = 'table'") % table_name
  1262. rs = connection.execute(s)
  1263. return rs.scalar()
  1264. def _get_table_pragma(self, connection, pragma, table_name, schema=None):
  1265. quote = self.identifier_preparer.quote_identifier
  1266. if schema is not None:
  1267. statement = "PRAGMA %s." % quote(schema)
  1268. else:
  1269. statement = "PRAGMA "
  1270. qtable = quote(table_name)
  1271. statement = "%s%s(%s)" % (statement, pragma, qtable)
  1272. cursor = connection.execute(statement)
  1273. if not cursor._soft_closed:
  1274. # work around SQLite issue whereby cursor.description
  1275. # is blank when PRAGMA returns no rows:
  1276. # http://www.sqlite.org/cvstrac/tktview?tn=1884
  1277. result = cursor.fetchall()
  1278. else:
  1279. result = []
  1280. return result