databases.txt 37 KB

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