base.py 15 KB

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