databases.txt 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. =========
  2. Databases
  3. =========
  4. Django officially supports the following databases:
  5. * :ref:`PostgreSQL <postgresql-notes>`
  6. * :ref:`MariaDB <mariadb-notes>`
  7. * :ref:`MySQL <mysql-notes>`
  8. * :ref:`Oracle <oracle-notes>`
  9. * :ref:`SQLite <sqlite-notes>`
  10. There are also a number of :ref:`database backends provided by third parties
  11. <third-party-notes>`.
  12. Django attempts to support as many features as possible on all database
  13. backends. However, not all database backends are alike, and we've had to make
  14. design decisions on which features to support and which assumptions we can make
  15. safely.
  16. This file describes some of the features that might be relevant to Django
  17. usage. It is not intended as a replacement for server-specific documentation or
  18. reference manuals.
  19. General notes
  20. =============
  21. .. _persistent-database-connections:
  22. Persistent connections
  23. ----------------------
  24. Persistent connections avoid the overhead of reestablishing a connection to
  25. the database in each request. They're controlled by the
  26. :setting:`CONN_MAX_AGE` parameter which defines the maximum lifetime of a
  27. connection. It can be set independently for each database.
  28. The default value is ``0``, preserving the historical behavior of closing the
  29. database connection at the end of each request. To enable persistent
  30. connections, set :setting:`CONN_MAX_AGE` to a positive integer of seconds. For
  31. unlimited persistent connections, set it to ``None``.
  32. Connection management
  33. ~~~~~~~~~~~~~~~~~~~~~
  34. Django opens a connection to the database when it first makes a database
  35. query. It keeps this connection open and reuses it in subsequent requests.
  36. Django closes the connection once it exceeds the maximum age defined by
  37. :setting:`CONN_MAX_AGE` or when it isn't usable any longer.
  38. In detail, Django automatically opens a connection to the database whenever it
  39. needs one and doesn't have one already — either because this is the first
  40. connection, or because the previous connection was closed.
  41. At the beginning of each request, Django closes the connection if it has
  42. reached its maximum age. If your database terminates idle connections after
  43. some time, you should set :setting:`CONN_MAX_AGE` to a lower value, so that
  44. Django doesn't attempt to use a connection that has been terminated by the
  45. database server. (This problem may only affect very low traffic sites.)
  46. At the end of each request, Django closes the connection if it has reached its
  47. maximum age or if it is in an unrecoverable error state. If any database
  48. errors have occurred while processing the requests, Django checks whether the
  49. connection still works, and closes it if it doesn't. Thus, database errors
  50. affect at most one request per each application's worker thread; if the
  51. connection becomes unusable, the next request gets a fresh connection.
  52. Setting :setting:`CONN_HEALTH_CHECKS` to ``True`` can be used to improve the
  53. robustness of connection reuse and prevent errors when a connection has been
  54. closed by the database server which is now ready to accept and serve new
  55. connections, e.g. after database server restart. The health check is performed
  56. only once per request and only if the database is being accessed during the
  57. handling of the request.
  58. Caveats
  59. ~~~~~~~
  60. Since each thread maintains its own connection, your database must support at
  61. least as many simultaneous connections as you have worker threads.
  62. Sometimes a database won't be accessed by the majority of your views, for
  63. example because it's the database of an external system, or thanks to caching.
  64. In such cases, you should set :setting:`CONN_MAX_AGE` to a low value or even
  65. ``0``, because it doesn't make sense to maintain a connection that's unlikely
  66. to be reused. This will help keep the number of simultaneous connections to
  67. this database small.
  68. The development server creates a new thread for each request it handles,
  69. negating the effect of persistent connections. Don't enable them during
  70. development.
  71. When Django establishes a connection to the database, it sets up appropriate
  72. parameters, depending on the backend being used. If you enable persistent
  73. connections, this setup is no longer repeated every request. If you modify
  74. parameters such as the connection's isolation level or time zone, you should
  75. either restore Django's defaults at the end of each request, force an
  76. appropriate value at the beginning of each request, or disable persistent
  77. connections.
  78. Encoding
  79. --------
  80. Django assumes that all databases use UTF-8 encoding. Using other encodings may
  81. result in unexpected behavior such as "value too long" errors from your
  82. database for data that is valid in Django. See the database specific notes
  83. below for information on how to set up your database correctly.
  84. .. _postgresql-notes:
  85. PostgreSQL notes
  86. ================
  87. Django supports PostgreSQL 12 and higher. `psycopg`_ 3.1.8+ or `psycopg2`_
  88. 2.8.4+ is required, though the latest `psycopg`_ 3.1.8+ is recommended.
  89. .. note::
  90. Support for ``psycopg2`` is likely to be deprecated and removed at some
  91. point in the future.
  92. .. versionchanged:: 4.2
  93. Support for ``psycopg`` 3.1.8+ was added.
  94. .. _postgresql-connection-settings:
  95. PostgreSQL connection settings
  96. -------------------------------
  97. See :setting:`HOST` for details.
  98. To connect using a service name from the `connection service file`_ and a
  99. password from the `password file`_, you must specify them in the
  100. :setting:`OPTIONS` part of your database configuration in :setting:`DATABASES`:
  101. .. code-block:: python
  102. :caption: ``settings.py``
  103. DATABASES = {
  104. 'default': {
  105. 'ENGINE': 'django.db.backends.postgresql',
  106. 'OPTIONS': {
  107. 'service': 'my_service',
  108. 'passfile': '.my_pgpass',
  109. },
  110. }
  111. }
  112. .. code-block:: text
  113. :caption: ``.pg_service.conf``
  114. [my_service]
  115. host=localhost
  116. user=USER
  117. dbname=NAME
  118. port=5432
  119. .. code-block:: text
  120. :caption: ``.my_pgpass``
  121. localhost:5432:NAME:USER:PASSWORD
  122. .. _connection service file: https://www.postgresql.org/docs/current/libpq-pgservice.html
  123. .. _password file: https://www.postgresql.org/docs/current/libpq-pgpass.html
  124. .. warning::
  125. Using a service name for testing purposes is not supported. This
  126. :ticket:`may be implemented later <33685>`.
  127. Optimizing PostgreSQL's configuration
  128. -------------------------------------
  129. Django needs the following parameters for its database connections:
  130. - ``client_encoding``: ``'UTF8'``,
  131. - ``default_transaction_isolation``: ``'read committed'`` by default,
  132. or the value set in the connection options (see below),
  133. - ``timezone``:
  134. - when :setting:`USE_TZ` is ``True``, ``'UTC'`` by default, or the
  135. :setting:`TIME_ZONE <DATABASE-TIME_ZONE>` value set for the connection,
  136. - when :setting:`USE_TZ` is ``False``, the value of the global
  137. :setting:`TIME_ZONE` setting.
  138. If these parameters already have the correct values, Django won't set them for
  139. every new connection, which improves performance slightly. You can configure
  140. them directly in :file:`postgresql.conf` or more conveniently per database
  141. user with `ALTER ROLE`_.
  142. Django will work just fine without this optimization, but each new connection
  143. will do some additional queries to set these parameters.
  144. .. _ALTER ROLE: https://www.postgresql.org/docs/current/sql-alterrole.html
  145. .. _database-isolation-level:
  146. Isolation level
  147. ---------------
  148. Like PostgreSQL itself, Django defaults to the ``READ COMMITTED`` `isolation
  149. level`_. If you need a higher isolation level such as ``REPEATABLE READ`` or
  150. ``SERIALIZABLE``, set it in the :setting:`OPTIONS` part of your database
  151. configuration in :setting:`DATABASES`::
  152. from django.db.backends.postgresql.psycopg_any import IsolationLevel
  153. DATABASES = {
  154. # ...
  155. 'OPTIONS': {
  156. 'isolation_level': IsolationLevel.SERIALIZABLE,
  157. },
  158. }
  159. .. note::
  160. Under higher isolation levels, your application should be prepared to
  161. handle exceptions raised on serialization failures. This option is
  162. designed for advanced uses.
  163. .. _isolation level: https://www.postgresql.org/docs/current/transaction-iso.html
  164. .. versionchanged:: 4.2
  165. ``IsolationLevel`` was added.
  166. .. _database-role:
  167. Role
  168. ----
  169. .. versionadded:: 4.2
  170. If you need to use a different role for database connections than the role use
  171. to establish the connection, set it in the :setting:`OPTIONS` part of your
  172. database configuration in :setting:`DATABASES`::
  173. DATABASES = {
  174. "default": {
  175. "ENGINE": "django.db.backends.postgresql",
  176. # ...
  177. "OPTIONS": {
  178. "assume_role": "my_application_role",
  179. },
  180. },
  181. }
  182. .. _database-server-side-parameters-binding:
  183. Server-side parameters binding
  184. ------------------------------
  185. .. versionadded:: 4.2
  186. With `psycopg`_ 3.1.8+, Django defaults to the :ref:`client-side binding
  187. cursors <psycopg:client-side-binding-cursors>`. If you want to use the
  188. :ref:`server-side binding <psycopg:server-side-binding>` set it in the
  189. :setting:`OPTIONS` part of your database configuration in
  190. :setting:`DATABASES`::
  191. DATABASES = {
  192. "default": {
  193. "ENGINE": "django.db.backends.postgresql",
  194. # ...
  195. "OPTIONS": {
  196. "server_side_binding": True,
  197. },
  198. },
  199. }
  200. This option is ignored with ``psycopg2``.
  201. Indexes for ``varchar`` and ``text`` columns
  202. --------------------------------------------
  203. When specifying ``db_index=True`` on your model fields, Django typically
  204. outputs a single ``CREATE INDEX`` statement. However, if the database type
  205. for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``,
  206. ``FileField``, and ``TextField``), then Django will create
  207. an additional index that uses an appropriate `PostgreSQL operator class`_
  208. for the column. The extra index is necessary to correctly perform
  209. lookups that use the ``LIKE`` operator in their SQL, as is done with the
  210. ``contains`` and ``startswith`` lookup types.
  211. .. _PostgreSQL operator class: https://www.postgresql.org/docs/current/indexes-opclass.html
  212. Migration operation for adding extensions
  213. -----------------------------------------
  214. If you need to add a PostgreSQL extension (like ``hstore``, ``postgis``, etc.)
  215. using a migration, use the
  216. :class:`~django.contrib.postgres.operations.CreateExtension` operation.
  217. .. _postgresql-server-side-cursors:
  218. Server-side cursors
  219. -------------------
  220. When using :meth:`QuerySet.iterator()
  221. <django.db.models.query.QuerySet.iterator>`, Django opens a :ref:`server-side
  222. cursor <psycopg:server-side-cursors>`. By default, PostgreSQL assumes that
  223. only the first 10% of the results of cursor queries will be fetched. The query
  224. planner spends less time planning the query and starts returning results
  225. faster, but this could diminish performance if more than 10% of the results are
  226. retrieved. PostgreSQL's assumptions on the number of rows retrieved for a
  227. cursor query is controlled with the `cursor_tuple_fraction`_ option.
  228. .. _cursor_tuple_fraction: https://www.postgresql.org/docs/current/runtime-config-query.html#GUC-CURSOR-TUPLE-FRACTION
  229. .. _transaction-pooling-server-side-cursors:
  230. Transaction pooling and server-side cursors
  231. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  232. Using a connection pooler in transaction pooling mode (e.g. `PgBouncer`_)
  233. requires disabling server-side cursors for that connection.
  234. Server-side cursors are local to a connection and remain open at the end of a
  235. transaction when :setting:`AUTOCOMMIT <DATABASE-AUTOCOMMIT>` is ``True``. A
  236. subsequent transaction may attempt to fetch more results from a server-side
  237. cursor. In transaction pooling mode, there's no guarantee that subsequent
  238. transactions will use the same connection. If a different connection is used,
  239. an error is raised when the transaction references the server-side cursor,
  240. because server-side cursors are only accessible in the connection in which they
  241. were created.
  242. One solution is to disable server-side cursors for a connection in
  243. :setting:`DATABASES` by setting :setting:`DISABLE_SERVER_SIDE_CURSORS
  244. <DATABASE-DISABLE_SERVER_SIDE_CURSORS>` to ``True``.
  245. To benefit from server-side cursors in transaction pooling mode, you could set
  246. up :doc:`another connection to the database </topics/db/multi-db>` in order to
  247. perform queries that use server-side cursors. This connection needs to either
  248. be directly to the database or to a connection pooler in session pooling mode.
  249. Another option is to wrap each ``QuerySet`` using server-side cursors in an
  250. :func:`~django.db.transaction.atomic` block, because it disables ``autocommit``
  251. for the duration of the transaction. This way, the server-side cursor will only
  252. live for the duration of the transaction.
  253. .. _PgBouncer: https://www.pgbouncer.org/
  254. .. _manually-specified-autoincrement-pk:
  255. Manually-specifying values of auto-incrementing primary keys
  256. ------------------------------------------------------------
  257. Django uses PostgreSQL's identity columns to store auto-incrementing primary
  258. keys. An identity column is populated with values from a `sequence`_ that keeps
  259. track of the next available value. Manually assigning a value to an
  260. auto-incrementing field doesn't update the field's sequence, which might later
  261. cause a conflict. For example:
  262. .. code-block:: pycon
  263. >>> from django.contrib.auth.models import User
  264. >>> User.objects.create(username='alice', pk=1)
  265. <User: alice>
  266. >>> # The sequence hasn't been updated; its next value is 1.
  267. >>> User.objects.create(username='bob')
  268. ...
  269. IntegrityError: duplicate key value violates unique constraint
  270. "auth_user_pkey" DETAIL: Key (id)=(1) already exists.
  271. If you need to specify such values, reset the sequence afterward to avoid
  272. reusing a value that's already in the table. The :djadmin:`sqlsequencereset`
  273. management command generates the SQL statements to do that.
  274. .. _sequence: https://www.postgresql.org/docs/current/sql-createsequence.html
  275. Test database templates
  276. -----------------------
  277. You can use the :setting:`TEST['TEMPLATE'] <TEST_TEMPLATE>` setting to specify
  278. a `template`_ (e.g. ``'template0'``) from which to create a test database.
  279. .. _template: https://www.postgresql.org/docs/current/sql-createdatabase.html
  280. Speeding up test execution with non-durable settings
  281. ----------------------------------------------------
  282. You can speed up test execution times by `configuring PostgreSQL to be
  283. non-durable <https://www.postgresql.org/docs/current/non-durability.html>`_.
  284. .. warning::
  285. This is dangerous: it will make your database more susceptible to data loss
  286. or corruption in the case of a server crash or power loss. Only use this on
  287. a development machine where you can easily restore the entire contents of
  288. all databases in the cluster.
  289. .. _psycopg: https://www.psycopg.org/psycopg3/
  290. .. _psycopg2: https://www.psycopg.org/
  291. .. _mariadb-notes:
  292. MariaDB notes
  293. =============
  294. Django supports MariaDB 10.4 and higher.
  295. To use MariaDB, use the MySQL backend, which is shared between the two. See the
  296. :ref:`MySQL notes <mysql-notes>` for more details.
  297. .. _mysql-notes:
  298. MySQL notes
  299. ===========
  300. Version support
  301. ---------------
  302. Django supports MySQL 8 and higher.
  303. Django's ``inspectdb`` feature uses the ``information_schema`` database, which
  304. contains detailed data on all database schemas.
  305. Django expects the database to support Unicode (UTF-8 encoding) and delegates to
  306. it the task of enforcing transactions and referential integrity. It is important
  307. to be aware of the fact that the two latter ones aren't actually enforced by
  308. MySQL when using the MyISAM storage engine, see the next section.
  309. .. _mysql-storage-engines:
  310. Storage engines
  311. ---------------
  312. MySQL has several `storage engines`_. You can change the default storage engine
  313. in the server configuration.
  314. MySQL's default storage engine is InnoDB_. This engine is fully transactional
  315. and supports foreign key references. It's the recommended choice. However, the
  316. InnoDB autoincrement counter is lost on a MySQL restart because it does not
  317. remember the ``AUTO_INCREMENT`` value, instead recreating it as "max(id)+1".
  318. This may result in an inadvertent reuse of :class:`~django.db.models.AutoField`
  319. values.
  320. The main drawbacks of MyISAM_ are that it doesn't support transactions or
  321. enforce foreign-key constraints.
  322. .. _storage engines: https://dev.mysql.com/doc/refman/en/storage-engines.html
  323. .. _MyISAM: https://dev.mysql.com/doc/refman/en/myisam-storage-engine.html
  324. .. _InnoDB: https://dev.mysql.com/doc/refman/en/innodb-storage-engine.html
  325. .. _mysql-db-api-drivers:
  326. MySQL DB API Drivers
  327. --------------------
  328. MySQL has a couple drivers that implement the Python Database API described in
  329. :pep:`249`:
  330. - `mysqlclient`_ is a native driver. It's **the recommended choice**.
  331. - `MySQL Connector/Python`_ is a pure Python driver from Oracle that does not
  332. require the MySQL client library or any Python modules outside the standard
  333. library.
  334. .. _mysqlclient: https://pypi.org/project/mysqlclient/
  335. .. _MySQL Connector/Python: https://dev.mysql.com/downloads/connector/python/
  336. These drivers are thread-safe and provide connection pooling.
  337. In addition to a DB API driver, Django needs an adapter to access the database
  338. drivers from its ORM. Django provides an adapter for mysqlclient while MySQL
  339. Connector/Python includes `its own`_.
  340. .. _its own: https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html
  341. mysqlclient
  342. ~~~~~~~~~~~
  343. Django requires `mysqlclient`_ 1.4.3 or later.
  344. MySQL Connector/Python
  345. ~~~~~~~~~~~~~~~~~~~~~~
  346. MySQL Connector/Python is available from the `download page`_.
  347. The Django adapter is available in versions 1.1.X and later. It may not
  348. support the most recent releases of Django.
  349. .. _download page: https://dev.mysql.com/downloads/connector/python/
  350. .. _mysql-time-zone-definitions:
  351. Time zone definitions
  352. ---------------------
  353. If you plan on using Django's :doc:`timezone support </topics/i18n/timezones>`,
  354. use `mysql_tzinfo_to_sql`_ to load time zone tables into the MySQL database.
  355. This needs to be done just once for your MySQL server, not per database.
  356. .. _mysql_tzinfo_to_sql: https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html
  357. Creating your database
  358. ----------------------
  359. You can `create your database`_ using the command-line tools and this SQL:
  360. .. code-block:: sql
  361. CREATE DATABASE <dbname> CHARACTER SET utf8;
  362. This ensures all tables and columns will use UTF-8 by default.
  363. .. _create your database: https://dev.mysql.com/doc/refman/en/create-database.html
  364. .. _mysql-collation:
  365. Collation settings
  366. ~~~~~~~~~~~~~~~~~~
  367. The collation setting for a column controls the order in which data is sorted
  368. as well as what strings compare as equal. You can specify the ``db_collation``
  369. parameter to set the collation name of the column for
  370. :attr:`CharField <django.db.models.CharField.db_collation>` and
  371. :attr:`TextField <django.db.models.TextField.db_collation>`.
  372. The collation can also be set on a database-wide level and per-table. This is
  373. `documented thoroughly`_ in the MySQL documentation. In such cases, you must
  374. set the collation by directly manipulating the database settings or tables.
  375. Django doesn't provide an API to change them.
  376. .. _documented thoroughly: https://dev.mysql.com/doc/refman/en/charset.html
  377. By default, with a UTF-8 database, MySQL will use the
  378. ``utf8_general_ci`` collation. This results in all string equality
  379. comparisons being done in a *case-insensitive* manner. That is, ``"Fred"`` and
  380. ``"freD"`` are considered equal at the database level. If you have a unique
  381. constraint on a field, it would be illegal to try to insert both ``"aa"`` and
  382. ``"AA"`` into the same column, since they compare as equal (and, hence,
  383. non-unique) with the default collation. If you want case-sensitive comparisons
  384. on a particular column or table, change the column or table to use the
  385. ``utf8_bin`` collation.
  386. Please note that according to `MySQL Unicode Character Sets`_, comparisons for
  387. the ``utf8_general_ci`` collation are faster, but slightly less correct, than
  388. comparisons for ``utf8_unicode_ci``. If this is acceptable for your application,
  389. you should use ``utf8_general_ci`` because it is faster. If this is not acceptable
  390. (for example, if you require German dictionary order), use ``utf8_unicode_ci``
  391. because it is more accurate.
  392. .. _MySQL Unicode Character Sets: https://dev.mysql.com/doc/refman/en/charset-unicode-sets.html
  393. .. warning::
  394. Model formsets validate unique fields in a case-sensitive manner. Thus when
  395. using a case-insensitive collation, a formset with unique field values that
  396. differ only by case will pass validation, but upon calling ``save()``, an
  397. ``IntegrityError`` will be raised.
  398. Connecting to the database
  399. --------------------------
  400. Refer to the :doc:`settings documentation </ref/settings>`.
  401. Connection settings are used in this order:
  402. #. :setting:`OPTIONS`.
  403. #. :setting:`NAME`, :setting:`USER`, :setting:`PASSWORD`, :setting:`HOST`,
  404. :setting:`PORT`
  405. #. MySQL option files.
  406. In other words, if you set the name of the database in :setting:`OPTIONS`,
  407. this will take precedence over :setting:`NAME`, which would override
  408. anything in a `MySQL option file`_.
  409. Here's a sample configuration which uses a MySQL option file::
  410. # settings.py
  411. DATABASES = {
  412. 'default': {
  413. 'ENGINE': 'django.db.backends.mysql',
  414. 'OPTIONS': {
  415. 'read_default_file': '/path/to/my.cnf',
  416. },
  417. }
  418. }
  419. .. code-block:: ini
  420. # my.cnf
  421. [client]
  422. database = NAME
  423. user = USER
  424. password = PASSWORD
  425. default-character-set = utf8
  426. Several other `MySQLdb connection options`_ may be useful, such as ``ssl``,
  427. ``init_command``, and ``sql_mode``.
  428. .. _MySQL option file: https://dev.mysql.com/doc/refman/en/option-files.html
  429. .. _MySQLdb connection options: https://mysqlclient.readthedocs.io/user_guide.html#functions-and-attributes
  430. .. _mysql-sql-mode:
  431. Setting ``sql_mode``
  432. ~~~~~~~~~~~~~~~~~~~~
  433. The default value of the ``sql_mode`` option contains ``STRICT_TRANS_TABLES``.
  434. That option escalates warnings into errors when data are truncated upon
  435. insertion, so Django highly recommends activating a `strict mode`_ for MySQL to
  436. prevent data loss (either ``STRICT_TRANS_TABLES`` or ``STRICT_ALL_TABLES``).
  437. .. _strict mode: https://dev.mysql.com/doc/refman/en/sql-mode.html#sql-mode-strict
  438. If you need to customize the SQL mode, you can set the ``sql_mode`` variable
  439. like other MySQL options: either in a config file or with the entry
  440. ``'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"`` in the
  441. :setting:`OPTIONS` part of your database configuration in :setting:`DATABASES`.
  442. .. _mysql-isolation-level:
  443. Isolation level
  444. ~~~~~~~~~~~~~~~
  445. When running concurrent loads, database transactions from different sessions
  446. (say, separate threads handling different requests) may interact with each
  447. other. These interactions are affected by each session's `transaction isolation
  448. level`_. You can set a connection's isolation level with an
  449. ``'isolation_level'`` entry in the :setting:`OPTIONS` part of your database
  450. configuration in :setting:`DATABASES`. Valid values for
  451. this entry are the four standard isolation levels:
  452. * ``'read uncommitted'``
  453. * ``'read committed'``
  454. * ``'repeatable read'``
  455. * ``'serializable'``
  456. or ``None`` to use the server's configured isolation level. However, Django
  457. works best with and defaults to read committed rather than MySQL's default,
  458. repeatable read. Data loss is possible with repeatable read. In particular,
  459. you may see cases where :meth:`~django.db.models.query.QuerySet.get_or_create`
  460. will raise an :exc:`~django.db.IntegrityError` but the object won't appear in
  461. a subsequent :meth:`~django.db.models.query.QuerySet.get` call.
  462. .. _transaction isolation level: https://dev.mysql.com/doc/refman/en/innodb-transaction-isolation-levels.html
  463. Creating your tables
  464. --------------------
  465. When Django generates the schema, it doesn't specify a storage engine, so
  466. tables will be created with whatever default storage engine your database
  467. server is configured for. The easiest solution is to set your database server's
  468. default storage engine to the desired engine.
  469. If you're using a hosting service and can't change your server's default
  470. storage engine, you have a couple of options.
  471. * After the tables are created, execute an ``ALTER TABLE`` statement to
  472. convert a table to a new storage engine (such as InnoDB):
  473. .. code-block:: sql
  474. ALTER TABLE <tablename> ENGINE=INNODB;
  475. This can be tedious if you have a lot of tables.
  476. * Another option is to use the ``init_command`` option for MySQLdb prior to
  477. creating your tables::
  478. 'OPTIONS': {
  479. 'init_command': 'SET default_storage_engine=INNODB',
  480. }
  481. This sets the default storage engine upon connecting to the database.
  482. After your tables have been created, you should remove this option as it
  483. adds a query that is only needed during table creation to each database
  484. connection.
  485. Table names
  486. -----------
  487. There are `known issues`_ in even the latest versions of MySQL that can cause the
  488. case of a table name to be altered when certain SQL statements are executed
  489. under certain conditions. It is recommended that you use lowercase table
  490. names, if possible, to avoid any problems that might arise from this behavior.
  491. Django uses lowercase table names when it auto-generates table names from
  492. models, so this is mainly a consideration if you are overriding the table name
  493. via the :class:`~django.db.models.Options.db_table` parameter.
  494. .. _known issues: https://bugs.mysql.com/bug.php?id=48875
  495. Savepoints
  496. ----------
  497. Both the Django ORM and MySQL (when using the InnoDB :ref:`storage engine
  498. <mysql-storage-engines>`) support database :ref:`savepoints
  499. <topics-db-transactions-savepoints>`.
  500. If you use the MyISAM storage engine please be aware of the fact that you will
  501. receive database-generated errors if you try to use the :ref:`savepoint-related
  502. methods of the transactions API <topics-db-transactions-savepoints>`. The reason
  503. for this is that detecting the storage engine of a MySQL database/table is an
  504. expensive operation so it was decided it isn't worth to dynamically convert
  505. these methods in no-op's based in the results of such detection.
  506. Notes on specific fields
  507. ------------------------
  508. .. _mysql-character-fields:
  509. Character fields
  510. ~~~~~~~~~~~~~~~~
  511. Any fields that are stored with ``VARCHAR`` column types may have their
  512. ``max_length`` restricted to 255 characters if you are using ``unique=True``
  513. for the field. This affects :class:`~django.db.models.CharField`,
  514. :class:`~django.db.models.SlugField`. See `the MySQL documentation`_ for more
  515. details.
  516. .. _the MySQL documentation: https://dev.mysql.com/doc/refman/en/create-index.html#create-index-column-prefixes
  517. ``TextField`` limitations
  518. ~~~~~~~~~~~~~~~~~~~~~~~~~
  519. MySQL can index only the first N chars of a ``BLOB`` or ``TEXT`` column. Since
  520. ``TextField`` doesn't have a defined length, you can't mark it as
  521. ``unique=True``. MySQL will report: "BLOB/TEXT column '<db_column>' used in key
  522. specification without a key length".
  523. .. _mysql-fractional-seconds:
  524. Fractional seconds support for Time and DateTime fields
  525. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  526. MySQL can store fractional seconds, provided that the column definition
  527. includes a fractional indication (e.g. ``DATETIME(6)``).
  528. Django will not upgrade existing columns to include fractional seconds if the
  529. database server supports it. If you want to enable them on an existing database,
  530. it's up to you to either manually update the column on the target database, by
  531. executing a command like:
  532. .. code-block:: sql
  533. ALTER TABLE `your_table` MODIFY `your_datetime_column` DATETIME(6)
  534. or using a :class:`~django.db.migrations.operations.RunSQL` operation in a
  535. :ref:`data migration <data-migrations>`.
  536. ``TIMESTAMP`` columns
  537. ~~~~~~~~~~~~~~~~~~~~~
  538. If you are using a legacy database that contains ``TIMESTAMP`` columns, you must
  539. set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption.
  540. :djadmin:`inspectdb` maps these columns to
  541. :class:`~django.db.models.DateTimeField` and if you enable timezone support,
  542. both MySQL and Django will attempt to convert the values from UTC to local time.
  543. Row locking with ``QuerySet.select_for_update()``
  544. -------------------------------------------------
  545. MySQL and MariaDB do not support some options to the ``SELECT ... FOR UPDATE``
  546. statement. If ``select_for_update()`` is used with an unsupported option, then
  547. a :exc:`~django.db.NotSupportedError` is raised.
  548. =============== ========= ==========
  549. Option MariaDB MySQL
  550. =============== ========= ==========
  551. ``SKIP LOCKED`` X (≥10.6) X (≥8.0.1)
  552. ``NOWAIT`` X X (≥8.0.1)
  553. ``OF`` X (≥8.0.1)
  554. ``NO KEY``
  555. =============== ========= ==========
  556. When using ``select_for_update()`` on MySQL, make sure you filter a queryset
  557. against at least a set of fields contained in unique constraints or only
  558. against fields covered by indexes. Otherwise, an exclusive write lock will be
  559. acquired over the full table for the duration of the transaction.
  560. Automatic typecasting can cause unexpected results
  561. --------------------------------------------------
  562. When performing a query on a string type, but with an integer value, MySQL will
  563. coerce the types of all values in the table to an integer before performing the
  564. comparison. If your table contains the values ``'abc'``, ``'def'`` and you
  565. query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE mycolumn=1``
  566. will match the value ``'abc1'``. Therefore, string type fields included in Django
  567. will always cast the value to a string before using it in a query.
  568. If you implement custom model fields that inherit from
  569. :class:`~django.db.models.Field` directly, are overriding
  570. :meth:`~django.db.models.Field.get_prep_value`, or use
  571. :class:`~django.db.models.expressions.RawSQL`,
  572. :meth:`~django.db.models.query.QuerySet.extra`, or
  573. :meth:`~django.db.models.Manager.raw`, you should ensure that you perform
  574. appropriate typecasting.
  575. .. _sqlite-notes:
  576. SQLite notes
  577. ============
  578. Django supports SQLite 3.21.0 and later.
  579. SQLite_ provides an excellent development alternative for applications that
  580. are predominantly read-only or require a smaller installation footprint. As
  581. with all database servers, though, there are some differences that are
  582. specific to SQLite that you should be aware of.
  583. .. _SQLite: https://www.sqlite.org/
  584. .. _sqlite-string-matching:
  585. Substring matching and case sensitivity
  586. ---------------------------------------
  587. For all SQLite versions, there is some slightly counter-intuitive behavior when
  588. attempting to match some types of strings. These are triggered when using the
  589. :lookup:`iexact` or :lookup:`contains` filters in Querysets. The behavior
  590. splits into two cases:
  591. 1. For substring matching, all matches are done case-insensitively. That is a
  592. filter such as ``filter(name__contains="aa")`` will match a name of ``"Aabb"``.
  593. 2. For strings containing characters outside the ASCII range, all exact string
  594. matches are performed case-sensitively, even when the case-insensitive options
  595. are passed into the query. So the :lookup:`iexact` filter will behave exactly
  596. the same as the :lookup:`exact` filter in these cases.
  597. Some possible workarounds for this are `documented at sqlite.org`_, but they
  598. aren't utilized by the default SQLite backend in Django, as incorporating them
  599. would be fairly difficult to do robustly. Thus, Django exposes the default
  600. SQLite behavior and you should be aware of this when doing case-insensitive or
  601. substring filtering.
  602. .. _documented at sqlite.org: https://www.sqlite.org/faq.html#q18
  603. .. _sqlite-decimal-handling:
  604. Decimal handling
  605. ----------------
  606. SQLite has no real decimal internal type. Decimal values are internally
  607. converted to the ``REAL`` data type (8-byte IEEE floating point number), as
  608. explained in the `SQLite datatypes documentation`__, so they don't support
  609. correctly-rounded decimal floating point arithmetic.
  610. __ https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes
  611. "Database is locked" errors
  612. ---------------------------
  613. SQLite is meant to be a lightweight database, and thus can't support a high
  614. level of concurrency. ``OperationalError: database is locked`` errors indicate
  615. that your application is experiencing more concurrency than ``sqlite`` can
  616. handle in default configuration. This error means that one thread or process has
  617. an exclusive lock on the database connection and another thread timed out
  618. waiting for the lock the be released.
  619. Python's SQLite wrapper has
  620. a default timeout value that determines how long the second thread is allowed to
  621. wait on the lock before it times out and raises the ``OperationalError: database
  622. is locked`` error.
  623. If you're getting this error, you can solve it by:
  624. * Switching to another database backend. At a certain point SQLite becomes
  625. too "lite" for real-world applications, and these sorts of concurrency
  626. errors indicate you've reached that point.
  627. * Rewriting your code to reduce concurrency and ensure that database
  628. transactions are short-lived.
  629. * Increase the default timeout value by setting the ``timeout`` database
  630. option::
  631. 'OPTIONS': {
  632. # ...
  633. 'timeout': 20,
  634. # ...
  635. }
  636. This will make SQLite wait a bit longer before throwing "database is locked"
  637. errors; it won't really do anything to solve them.
  638. ``QuerySet.select_for_update()`` not supported
  639. ----------------------------------------------
  640. SQLite does not support the ``SELECT ... FOR UPDATE`` syntax. Calling it will
  641. have no effect.
  642. .. _sqlite-isolation:
  643. Isolation when using ``QuerySet.iterator()``
  644. --------------------------------------------
  645. There are special considerations described in `Isolation In SQLite`_ when
  646. modifying a table while iterating over it using :meth:`.QuerySet.iterator`. If
  647. a row is added, changed, or deleted within the loop, then that row may or may
  648. not appear, or may appear twice, in subsequent results fetched from the
  649. iterator. Your code must handle this.
  650. .. _`Isolation in SQLite`: https://www.sqlite.org/isolation.html
  651. .. _sqlite-json1:
  652. Enabling JSON1 extension on SQLite
  653. ----------------------------------
  654. To use :class:`~django.db.models.JSONField` on SQLite, you need to enable the
  655. `JSON1 extension`_ on Python's :py:mod:`sqlite3` library. If the extension is
  656. not enabled on your installation, a system error (``fields.E180``) will be
  657. raised.
  658. To enable the JSON1 extension you can follow the instruction on
  659. `the wiki page`_.
  660. .. note::
  661. The JSON1 extension is enabled by default on SQLite 3.38+.
  662. .. _JSON1 extension: https://www.sqlite.org/json1.html
  663. .. _the wiki page: https://code.djangoproject.com/wiki/JSON1Extension
  664. .. _oracle-notes:
  665. Oracle notes
  666. ============
  667. Django supports `Oracle Database Server`_ versions 19c and higher. Version 7.0
  668. or higher of the `cx_Oracle`_ Python driver is required.
  669. .. _`Oracle Database Server`: https://www.oracle.com/
  670. .. _`cx_Oracle`: https://oracle.github.io/python-cx_Oracle/
  671. In order for the ``python manage.py migrate`` command to work, your Oracle
  672. database user must have privileges to run the following commands:
  673. * CREATE TABLE
  674. * CREATE SEQUENCE
  675. * CREATE PROCEDURE
  676. * CREATE TRIGGER
  677. To run a project's test suite, the user usually needs these *additional*
  678. privileges:
  679. * CREATE USER
  680. * ALTER USER
  681. * DROP USER
  682. * CREATE TABLESPACE
  683. * DROP TABLESPACE
  684. * CREATE SESSION WITH ADMIN OPTION
  685. * CREATE TABLE WITH ADMIN OPTION
  686. * CREATE SEQUENCE WITH ADMIN OPTION
  687. * CREATE PROCEDURE WITH ADMIN OPTION
  688. * CREATE TRIGGER WITH ADMIN OPTION
  689. While the ``RESOURCE`` role has the required ``CREATE TABLE``,
  690. ``CREATE SEQUENCE``, ``CREATE PROCEDURE``, and ``CREATE TRIGGER`` privileges,
  691. and a user granted ``RESOURCE WITH ADMIN OPTION`` can grant ``RESOURCE``, such
  692. a user cannot grant the individual privileges (e.g. ``CREATE TABLE``), and thus
  693. ``RESOURCE WITH ADMIN OPTION`` is not usually sufficient for running tests.
  694. Some test suites also create views or materialized views; to run these, the
  695. user also needs ``CREATE VIEW WITH ADMIN OPTION`` and
  696. ``CREATE MATERIALIZED VIEW WITH ADMIN OPTION`` privileges. In particular, this
  697. is needed for Django's own test suite.
  698. All of these privileges are included in the DBA role, which is appropriate
  699. for use on a private developer's database.
  700. The Oracle database backend uses the ``SYS.DBMS_LOB`` and ``SYS.DBMS_RANDOM``
  701. packages, so your user will require execute permissions on it. It's normally
  702. accessible to all users by default, but in case it is not, you'll need to grant
  703. permissions like so:
  704. .. code-block:: sql
  705. GRANT EXECUTE ON SYS.DBMS_LOB TO user;
  706. GRANT EXECUTE ON SYS.DBMS_RANDOM TO user;
  707. Connecting to the database
  708. --------------------------
  709. To connect using the service name of your Oracle database, your ``settings.py``
  710. file should look something like this::
  711. DATABASES = {
  712. 'default': {
  713. 'ENGINE': 'django.db.backends.oracle',
  714. 'NAME': 'xe',
  715. 'USER': 'a_user',
  716. 'PASSWORD': 'a_password',
  717. 'HOST': '',
  718. 'PORT': '',
  719. }
  720. }
  721. In this case, you should leave both :setting:`HOST` and :setting:`PORT` empty.
  722. However, if you don't use a ``tnsnames.ora`` file or a similar naming method
  723. and want to connect using the SID ("xe" in this example), then fill in both
  724. :setting:`HOST` and :setting:`PORT` like so::
  725. DATABASES = {
  726. 'default': {
  727. 'ENGINE': 'django.db.backends.oracle',
  728. 'NAME': 'xe',
  729. 'USER': 'a_user',
  730. 'PASSWORD': 'a_password',
  731. 'HOST': 'dbprod01ned.mycompany.com',
  732. 'PORT': '1540',
  733. }
  734. }
  735. You should either supply both :setting:`HOST` and :setting:`PORT`, or leave
  736. both as empty strings. Django will use a different connect descriptor depending
  737. on that choice.
  738. Full DSN and Easy Connect
  739. ~~~~~~~~~~~~~~~~~~~~~~~~~
  740. A Full DSN or Easy Connect string can be used in :setting:`NAME` if both
  741. :setting:`HOST` and :setting:`PORT` are empty. This format is required when
  742. using RAC or pluggable databases without ``tnsnames.ora``, for example.
  743. Example of an Easy Connect string::
  744. 'NAME': 'localhost:1521/orclpdb1'
  745. Example of a full DSN string::
  746. 'NAME': (
  747. '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))'
  748. '(CONNECT_DATA=(SERVICE_NAME=orclpdb1)))'
  749. )
  750. Threaded option
  751. ---------------
  752. If you plan to run Django in a multithreaded environment (e.g. Apache using the
  753. default MPM module on any modern operating system), then you **must** set
  754. the ``threaded`` option of your Oracle database configuration to ``True``::
  755. 'OPTIONS': {
  756. 'threaded': True,
  757. }
  758. Failure to do this may result in crashes and other odd behavior.
  759. INSERT ... RETURNING INTO
  760. -------------------------
  761. By default, the Oracle backend uses a ``RETURNING INTO`` clause to efficiently
  762. retrieve the value of an ``AutoField`` when inserting new rows. This behavior
  763. may result in a ``DatabaseError`` in certain unusual setups, such as when
  764. inserting into a remote table, or into a view with an ``INSTEAD OF`` trigger.
  765. The ``RETURNING INTO`` clause can be disabled by setting the
  766. ``use_returning_into`` option of the database configuration to ``False``::
  767. 'OPTIONS': {
  768. 'use_returning_into': False,
  769. }
  770. In this case, the Oracle backend will use a separate ``SELECT`` query to
  771. retrieve ``AutoField`` values.
  772. Naming issues
  773. -------------
  774. Oracle imposes a name length limit of 30 characters. To accommodate this, the
  775. backend truncates database identifiers to fit, replacing the final four
  776. characters of the truncated name with a repeatable MD5 hash value.
  777. Additionally, the backend turns database identifiers to all-uppercase.
  778. To prevent these transformations (this is usually required only when dealing
  779. with legacy databases or accessing tables which belong to other users), use
  780. a quoted name as the value for ``db_table``::
  781. class LegacyModel(models.Model):
  782. class Meta:
  783. db_table = '"name_left_in_lowercase"'
  784. class ForeignModel(models.Model):
  785. class Meta:
  786. db_table = '"OTHER_USER"."NAME_ONLY_SEEMS_OVER_30"'
  787. Quoted names can also be used with Django's other supported database
  788. backends; except for Oracle, however, the quotes have no effect.
  789. When running ``migrate``, an ``ORA-06552`` error may be encountered if
  790. certain Oracle keywords are used as the name of a model field or the
  791. value of a ``db_column`` option. Django quotes all identifiers used
  792. in queries to prevent most such problems, but this error can still
  793. occur when an Oracle datatype is used as a column name. In
  794. particular, take care to avoid using the names ``date``,
  795. ``timestamp``, ``number`` or ``float`` as a field name.
  796. .. _oracle-null-empty-strings:
  797. NULL and empty strings
  798. ----------------------
  799. Django generally prefers to use the empty string (``''``) rather than
  800. ``NULL``, but Oracle treats both identically. To get around this, the
  801. Oracle backend ignores an explicit ``null`` option on fields that
  802. have the empty string as a possible value and generates DDL as if
  803. ``null=True``. When fetching from the database, it is assumed that
  804. a ``NULL`` value in one of these fields really means the empty
  805. string, and the data is silently converted to reflect this assumption.
  806. ``TextField`` limitations
  807. -------------------------
  808. The Oracle backend stores ``TextFields`` as ``NCLOB`` columns. Oracle imposes
  809. some limitations on the usage of such LOB columns in general:
  810. * LOB columns may not be used as primary keys.
  811. * LOB columns may not be used in indexes.
  812. * LOB columns may not be used in a ``SELECT DISTINCT`` list. This means that
  813. attempting to use the ``QuerySet.distinct`` method on a model that
  814. includes ``TextField`` columns will result in an ``ORA-00932`` error when
  815. run against Oracle. As a workaround, use the ``QuerySet.defer`` method in
  816. conjunction with ``distinct()`` to prevent ``TextField`` columns from being
  817. included in the ``SELECT DISTINCT`` list.
  818. .. _subclassing-database-backends:
  819. Subclassing the built-in database backends
  820. ==========================================
  821. Django comes with built-in database backends. You may subclass an existing
  822. database backends to modify its behavior, features, or configuration.
  823. Consider, for example, that you need to change a single database feature.
  824. First, you have to create a new directory with a ``base`` module in it. For
  825. example:
  826. .. code-block:: text
  827. mysite/
  828. ...
  829. mydbengine/
  830. __init__.py
  831. base.py
  832. The ``base.py`` module must contain a class named ``DatabaseWrapper`` that
  833. subclasses an existing engine from the ``django.db.backends`` module. Here's an
  834. example of subclassing the PostgreSQL engine to change a feature class
  835. ``allows_group_by_selected_pks_on_model``:
  836. .. code-block:: python
  837. :caption: ``mysite/mydbengine/base.py``
  838. from django.db.backends.postgresql import base, features
  839. class DatabaseFeatures(features.DatabaseFeatures):
  840. def allows_group_by_selected_pks_on_model(self, model):
  841. return True
  842. class DatabaseWrapper(base.DatabaseWrapper):
  843. features_class = DatabaseFeatures
  844. Finally, you must specify a :setting:`DATABASE-ENGINE` in your ``settings.py``
  845. file::
  846. DATABASES = {
  847. 'default': {
  848. 'ENGINE': 'mydbengine',
  849. # ...
  850. },
  851. }
  852. You can see the current list of database engines by looking in
  853. :source:`django/db/backends`.
  854. .. _third-party-notes:
  855. Using a 3rd-party database backend
  856. ==================================
  857. In addition to the officially supported databases, there are backends provided
  858. by 3rd parties that allow you to use other databases with Django:
  859. * `CockroachDB`_
  860. * `Firebird`_
  861. * `Google Cloud Spanner`_
  862. * `Microsoft SQL Server`_
  863. * `TiDB`_
  864. * `YugabyteDB`_
  865. The Django versions and ORM features supported by these unofficial backends
  866. vary considerably. Queries regarding the specific capabilities of these
  867. unofficial backends, along with any support queries, should be directed to
  868. the support channels provided by each 3rd party project.
  869. .. _CockroachDB: https://pypi.org/project/django-cockroachdb/
  870. .. _Firebird: https://pypi.org/project/django-firebird/
  871. .. _Google Cloud Spanner: https://pypi.org/project/django-google-spanner/
  872. .. _Microsoft SQL Server: https://pypi.org/project/mssql-django/
  873. .. _TiDB: https://pypi.org/project/django-tidb/
  874. .. _YugabyteDB: https://pypi.org/project/django-yugabytedb/