base.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. """
  2. SQLite backend for the sqlite3 module in the standard library.
  3. """
  4. import datetime
  5. import decimal
  6. import warnings
  7. from collections.abc import Mapping
  8. from itertools import chain, tee
  9. from sqlite3 import dbapi2 as Database
  10. from django.core.exceptions import ImproperlyConfigured
  11. from django.db import IntegrityError
  12. from django.db.backends.base.base import BaseDatabaseWrapper
  13. from django.utils.asyncio import async_unsafe
  14. from django.utils.dateparse import parse_date, parse_datetime, parse_time
  15. from django.utils.regex_helper import _lazy_re_compile
  16. from ._functions import register as register_functions
  17. from .client import DatabaseClient
  18. from .creation import DatabaseCreation
  19. from .features import DatabaseFeatures
  20. from .introspection import DatabaseIntrospection
  21. from .operations import DatabaseOperations
  22. from .schema import DatabaseSchemaEditor
  23. def decoder(conv_func):
  24. """
  25. Convert bytestrings from Python's sqlite3 interface to a regular string.
  26. """
  27. return lambda s: conv_func(s.decode())
  28. def adapt_date(val):
  29. return val.isoformat()
  30. def adapt_datetime(val):
  31. return val.isoformat(" ")
  32. Database.register_converter("bool", b"1".__eq__)
  33. Database.register_converter("date", decoder(parse_date))
  34. Database.register_converter("time", decoder(parse_time))
  35. Database.register_converter("datetime", decoder(parse_datetime))
  36. Database.register_converter("timestamp", decoder(parse_datetime))
  37. Database.register_adapter(decimal.Decimal, str)
  38. Database.register_adapter(datetime.date, adapt_date)
  39. Database.register_adapter(datetime.datetime, adapt_datetime)
  40. class DatabaseWrapper(BaseDatabaseWrapper):
  41. vendor = "sqlite"
  42. display_name = "SQLite"
  43. # SQLite doesn't actually support most of these types, but it "does the right
  44. # thing" given more verbose field definitions, so leave them as is so that
  45. # schema inspection is more useful.
  46. data_types = {
  47. "AutoField": "integer",
  48. "BigAutoField": "integer",
  49. "BinaryField": "BLOB",
  50. "BooleanField": "bool",
  51. "CharField": "varchar(%(max_length)s)",
  52. "DateField": "date",
  53. "DateTimeField": "datetime",
  54. "DecimalField": "decimal",
  55. "DurationField": "bigint",
  56. "FileField": "varchar(%(max_length)s)",
  57. "FilePathField": "varchar(%(max_length)s)",
  58. "FloatField": "real",
  59. "IntegerField": "integer",
  60. "BigIntegerField": "bigint",
  61. "IPAddressField": "char(15)",
  62. "GenericIPAddressField": "char(39)",
  63. "JSONField": "text",
  64. "OneToOneField": "integer",
  65. "PositiveBigIntegerField": "bigint unsigned",
  66. "PositiveIntegerField": "integer unsigned",
  67. "PositiveSmallIntegerField": "smallint unsigned",
  68. "SlugField": "varchar(%(max_length)s)",
  69. "SmallAutoField": "integer",
  70. "SmallIntegerField": "smallint",
  71. "TextField": "text",
  72. "TimeField": "time",
  73. "UUIDField": "char(32)",
  74. }
  75. data_type_check_constraints = {
  76. "PositiveBigIntegerField": '"%(column)s" >= 0',
  77. "JSONField": '(JSON_VALID("%(column)s") OR "%(column)s" IS NULL)',
  78. "PositiveIntegerField": '"%(column)s" >= 0',
  79. "PositiveSmallIntegerField": '"%(column)s" >= 0',
  80. }
  81. data_types_suffix = {
  82. "AutoField": "AUTOINCREMENT",
  83. "BigAutoField": "AUTOINCREMENT",
  84. "SmallAutoField": "AUTOINCREMENT",
  85. }
  86. # SQLite requires LIKE statements to include an ESCAPE clause if the value
  87. # being escaped has a percent or underscore in it.
  88. # See https://www.sqlite.org/lang_expr.html for an explanation.
  89. operators = {
  90. "exact": "= %s",
  91. "iexact": "LIKE %s ESCAPE '\\'",
  92. "contains": "LIKE %s ESCAPE '\\'",
  93. "icontains": "LIKE %s ESCAPE '\\'",
  94. "regex": "REGEXP %s",
  95. "iregex": "REGEXP '(?i)' || %s",
  96. "gt": "> %s",
  97. "gte": ">= %s",
  98. "lt": "< %s",
  99. "lte": "<= %s",
  100. "startswith": "LIKE %s ESCAPE '\\'",
  101. "endswith": "LIKE %s ESCAPE '\\'",
  102. "istartswith": "LIKE %s ESCAPE '\\'",
  103. "iendswith": "LIKE %s ESCAPE '\\'",
  104. }
  105. # The patterns below are used to generate SQL pattern lookup clauses when
  106. # the right-hand side of the lookup isn't a raw string (it might be an expression
  107. # or the result of a bilateral transformation).
  108. # In those cases, special characters for LIKE operators (e.g. \, *, _) should be
  109. # escaped on database side.
  110. #
  111. # Note: we use str.format() here for readability as '%' is used as a wildcard for
  112. # the LIKE operator.
  113. pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\', '\\'), '%%', '\%%'), '_', '\_')"
  114. pattern_ops = {
  115. "contains": r"LIKE '%%' || {} || '%%' ESCAPE '\'",
  116. "icontains": r"LIKE '%%' || UPPER({}) || '%%' ESCAPE '\'",
  117. "startswith": r"LIKE {} || '%%' ESCAPE '\'",
  118. "istartswith": r"LIKE UPPER({}) || '%%' ESCAPE '\'",
  119. "endswith": r"LIKE '%%' || {} ESCAPE '\'",
  120. "iendswith": r"LIKE '%%' || UPPER({}) ESCAPE '\'",
  121. }
  122. transaction_modes = frozenset(["DEFERRED", "EXCLUSIVE", "IMMEDIATE"])
  123. Database = Database
  124. SchemaEditorClass = DatabaseSchemaEditor
  125. # Classes instantiated in __init__().
  126. client_class = DatabaseClient
  127. creation_class = DatabaseCreation
  128. features_class = DatabaseFeatures
  129. introspection_class = DatabaseIntrospection
  130. ops_class = DatabaseOperations
  131. def get_connection_params(self):
  132. settings_dict = self.settings_dict
  133. if not settings_dict["NAME"]:
  134. raise ImproperlyConfigured(
  135. "settings.DATABASES is improperly configured. "
  136. "Please supply the NAME value."
  137. )
  138. kwargs = {
  139. "database": settings_dict["NAME"],
  140. "detect_types": Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,
  141. **settings_dict["OPTIONS"],
  142. }
  143. # Always allow the underlying SQLite connection to be shareable
  144. # between multiple threads. The safe-guarding will be handled at a
  145. # higher level by the `BaseDatabaseWrapper.allow_thread_sharing`
  146. # property. This is necessary as the shareability is disabled by
  147. # default in sqlite3 and it cannot be changed once a connection is
  148. # opened.
  149. if "check_same_thread" in kwargs and kwargs["check_same_thread"]:
  150. warnings.warn(
  151. "The `check_same_thread` option was provided and set to "
  152. "True. It will be overridden with False. Use the "
  153. "`DatabaseWrapper.allow_thread_sharing` property instead "
  154. "for controlling thread shareability.",
  155. RuntimeWarning,
  156. )
  157. kwargs.update({"check_same_thread": False, "uri": True})
  158. transaction_mode = kwargs.pop("transaction_mode", None)
  159. if (
  160. transaction_mode is not None
  161. and transaction_mode.upper() not in self.transaction_modes
  162. ):
  163. allowed_transaction_modes = ", ".join(
  164. [f"{mode!r}" for mode in sorted(self.transaction_modes)]
  165. )
  166. raise ImproperlyConfigured(
  167. f"settings.DATABASES[{self.alias!r}]['OPTIONS']['transaction_mode'] "
  168. f"is improperly configured to '{transaction_mode}'. Use one of "
  169. f"{allowed_transaction_modes}, or None."
  170. )
  171. self.transaction_mode = transaction_mode.upper() if transaction_mode else None
  172. init_command = kwargs.pop("init_command", "")
  173. self.init_commands = init_command.split(";")
  174. return kwargs
  175. def get_database_version(self):
  176. return self.Database.sqlite_version_info
  177. @async_unsafe
  178. def get_new_connection(self, conn_params):
  179. conn = Database.connect(**conn_params)
  180. register_functions(conn)
  181. conn.execute("PRAGMA foreign_keys = ON")
  182. # The macOS bundled SQLite defaults legacy_alter_table ON, which
  183. # prevents atomic table renames.
  184. conn.execute("PRAGMA legacy_alter_table = OFF")
  185. for init_command in self.init_commands:
  186. if init_command := init_command.strip():
  187. conn.execute(init_command)
  188. return conn
  189. def create_cursor(self, name=None):
  190. return self.connection.cursor(factory=SQLiteCursorWrapper)
  191. @async_unsafe
  192. def close(self):
  193. self.validate_thread_sharing()
  194. # If database is in memory, closing the connection destroys the
  195. # database. To prevent accidental data loss, ignore close requests on
  196. # an in-memory db.
  197. if not self.is_in_memory_db():
  198. BaseDatabaseWrapper.close(self)
  199. def _savepoint_allowed(self):
  200. # When 'isolation_level' is not None, sqlite3 commits before each
  201. # savepoint; it's a bug. When it is None, savepoints don't make sense
  202. # because autocommit is enabled. The only exception is inside 'atomic'
  203. # blocks. To work around that bug, on SQLite, 'atomic' starts a
  204. # transaction explicitly rather than simply disable autocommit.
  205. return self.in_atomic_block
  206. def _set_autocommit(self, autocommit):
  207. if autocommit:
  208. level = None
  209. else:
  210. # sqlite3's internal default is ''. It's different from None.
  211. # See Modules/_sqlite/connection.c.
  212. level = ""
  213. # 'isolation_level' is a misleading API.
  214. # SQLite always runs at the SERIALIZABLE isolation level.
  215. with self.wrap_database_errors:
  216. self.connection.isolation_level = level
  217. def disable_constraint_checking(self):
  218. with self.cursor() as cursor:
  219. cursor.execute("PRAGMA foreign_keys = OFF")
  220. # Foreign key constraints cannot be turned off while in a multi-
  221. # statement transaction. Fetch the current state of the pragma
  222. # to determine if constraints are effectively disabled.
  223. enabled = cursor.execute("PRAGMA foreign_keys").fetchone()[0]
  224. return not bool(enabled)
  225. def enable_constraint_checking(self):
  226. with self.cursor() as cursor:
  227. cursor.execute("PRAGMA foreign_keys = ON")
  228. def check_constraints(self, table_names=None):
  229. """
  230. Check each table name in `table_names` for rows with invalid foreign
  231. key references. This method is intended to be used in conjunction with
  232. `disable_constraint_checking()` and `enable_constraint_checking()`, to
  233. determine if rows with invalid references were entered while constraint
  234. checks were off.
  235. """
  236. with self.cursor() as cursor:
  237. if table_names is None:
  238. violations = cursor.execute("PRAGMA foreign_key_check").fetchall()
  239. else:
  240. violations = chain.from_iterable(
  241. cursor.execute(
  242. "PRAGMA foreign_key_check(%s)" % self.ops.quote_name(table_name)
  243. ).fetchall()
  244. for table_name in table_names
  245. )
  246. # See https://www.sqlite.org/pragma.html#pragma_foreign_key_check
  247. for (
  248. table_name,
  249. rowid,
  250. referenced_table_name,
  251. foreign_key_index,
  252. ) in violations:
  253. foreign_key = cursor.execute(
  254. "PRAGMA foreign_key_list(%s)" % self.ops.quote_name(table_name)
  255. ).fetchall()[foreign_key_index]
  256. column_name, referenced_column_name = foreign_key[3:5]
  257. primary_key_column_name = self.introspection.get_primary_key_column(
  258. cursor, table_name
  259. )
  260. primary_key_value, bad_value = cursor.execute(
  261. "SELECT %s, %s FROM %s WHERE rowid = %%s"
  262. % (
  263. self.ops.quote_name(primary_key_column_name),
  264. self.ops.quote_name(column_name),
  265. self.ops.quote_name(table_name),
  266. ),
  267. (rowid,),
  268. ).fetchone()
  269. raise IntegrityError(
  270. "The row in table '%s' with primary key '%s' has an "
  271. "invalid foreign key: %s.%s contains a value '%s' that "
  272. "does not have a corresponding value in %s.%s."
  273. % (
  274. table_name,
  275. primary_key_value,
  276. table_name,
  277. column_name,
  278. bad_value,
  279. referenced_table_name,
  280. referenced_column_name,
  281. )
  282. )
  283. def is_usable(self):
  284. return True
  285. def _start_transaction_under_autocommit(self):
  286. """
  287. Start a transaction explicitly in autocommit mode.
  288. Staying in autocommit mode works around a bug of sqlite3 that breaks
  289. savepoints when autocommit is disabled.
  290. """
  291. if self.transaction_mode is None:
  292. self.cursor().execute("BEGIN")
  293. else:
  294. self.cursor().execute(f"BEGIN {self.transaction_mode}")
  295. def is_in_memory_db(self):
  296. return self.creation.is_in_memory_db(self.settings_dict["NAME"])
  297. FORMAT_QMARK_REGEX = _lazy_re_compile(r"(?<!%)%s")
  298. class SQLiteCursorWrapper(Database.Cursor):
  299. """
  300. Django uses the "format" and "pyformat" styles, but Python's sqlite3 module
  301. supports neither of these styles.
  302. This wrapper performs the following conversions:
  303. - "format" style to "qmark" style
  304. - "pyformat" style to "named" style
  305. In both cases, if you want to use a literal "%s", you'll need to use "%%s".
  306. """
  307. def execute(self, query, params=None):
  308. if params is None:
  309. return super().execute(query)
  310. # Extract names if params is a mapping, i.e. "pyformat" style is used.
  311. param_names = list(params) if isinstance(params, Mapping) else None
  312. query = self.convert_query(query, param_names=param_names)
  313. return super().execute(query, params)
  314. def executemany(self, query, param_list):
  315. # Extract names if params is a mapping, i.e. "pyformat" style is used.
  316. # Peek carefully as a generator can be passed instead of a list/tuple.
  317. peekable, param_list = tee(iter(param_list))
  318. if (params := next(peekable, None)) and isinstance(params, Mapping):
  319. param_names = list(params)
  320. else:
  321. param_names = None
  322. query = self.convert_query(query, param_names=param_names)
  323. return super().executemany(query, param_list)
  324. def convert_query(self, query, *, param_names=None):
  325. if param_names is None:
  326. # Convert from "format" style to "qmark" style.
  327. return FORMAT_QMARK_REGEX.sub("?", query).replace("%%", "%")
  328. else:
  329. # Convert from "pyformat" style to "named" style.
  330. return query % {name: f":{name}" for name in param_names}