databases.txt 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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.0 and higher. It requires the use of Psycopg2
  74. 2.0.9 or higher.
  75. PostgreSQL connection settings
  76. -------------------------------
  77. See :setting:`HOST` for details.
  78. Optimizing PostgreSQL's configuration
  79. -------------------------------------
  80. Django needs the following parameters for its database connections:
  81. - ``client_encoding``: ``'UTF8'``,
  82. - ``default_transaction_isolation``: ``'read committed'`` by default,
  83. or the value set in the connection options (see below),
  84. - ``timezone``: ``'UTC'`` when :setting:`USE_TZ` is ``True``, value of
  85. :setting:`TIME_ZONE` otherwise.
  86. If these parameters already have the correct values, Django won't set them for
  87. every new connection, which improves performance slightly. You can configure
  88. them directly in :file:`postgresql.conf` or more conveniently per database
  89. user with `ALTER ROLE`_.
  90. Django will work just fine without this optimization, but each new connection
  91. will do some additional queries to set these parameters.
  92. .. _ALTER ROLE: http://www.postgresql.org/docs/current/interactive/sql-alterrole.html
  93. .. _database-isolation-level:
  94. Isolation level
  95. ---------------
  96. Like PostgreSQL itself, Django defaults to the ``READ COMMITTED`` `isolation
  97. level`_. If you need a higher isolation level such as ``REPEATABLE READ`` or
  98. ``SERIALIZABLE``, set it in the :setting:`OPTIONS` part of your database
  99. configuration in :setting:`DATABASES`::
  100. import psycopg2.extensions
  101. DATABASES = {
  102. # ...
  103. 'OPTIONS': {
  104. 'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE,
  105. },
  106. }
  107. .. note::
  108. Under higher isolation levels, your application should be prepared to
  109. handle exceptions raised on serialization failures. This option is
  110. designed for advanced uses.
  111. .. _isolation level: http://www.postgresql.org/docs/current/static/transaction-iso.html
  112. Indexes for ``varchar`` and ``text`` columns
  113. --------------------------------------------
  114. When specifying ``db_index=True`` on your model fields, Django typically
  115. outputs a single ``CREATE INDEX`` statement. However, if the database type
  116. for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``,
  117. ``FileField``, and ``TextField``), then Django will create
  118. an additional index that uses an appropriate `PostgreSQL operator class`_
  119. for the column. The extra index is necessary to correctly perform
  120. lookups that use the ``LIKE`` operator in their SQL, as is done with the
  121. ``contains`` and ``startswith`` lookup types.
  122. .. _PostgreSQL operator class: http://www.postgresql.org/docs/current/static/indexes-opclass.html
  123. .. _mysql-notes:
  124. MySQL notes
  125. ===========
  126. Version support
  127. ---------------
  128. Django supports MySQL 5.5 and higher.
  129. Django's ``inspectdb`` feature uses the ``information_schema`` database, which
  130. contains detailed data on all database schemas.
  131. Django expects the database to support Unicode (UTF-8 encoding) and delegates to
  132. it the task of enforcing transactions and referential integrity. It is important
  133. to be aware of the fact that the two latter ones aren't actually enforced by
  134. MySQL when using the MyISAM storage engine, see the next section.
  135. .. _mysql-storage-engines:
  136. Storage engines
  137. ---------------
  138. MySQL has several `storage engines`_. You can change the default storage engine
  139. in the server configuration.
  140. Until MySQL 5.5.4, the default engine was MyISAM_ [#]_. The main drawbacks of
  141. MyISAM are that it doesn't support transactions or enforce foreign-key
  142. constraints. On the plus side, it was the only engine that supported full-text
  143. indexing and searching until MySQL 5.6.4.
  144. Since MySQL 5.5.5, the default storage engine is InnoDB_. This engine is fully
  145. transactional and supports foreign key references. It's probably the best
  146. choice at this point. However, note that the InnoDB autoincrement counter
  147. is lost on a MySQL restart because it does not remember the
  148. ``AUTO_INCREMENT`` value, instead recreating it as "max(id)+1". This may
  149. result in an inadvertent reuse of :class:`~django.db.models.AutoField` values.
  150. If you upgrade an existing project to MySQL 5.5.5 and subsequently add some
  151. tables, ensure that your tables are using the same storage engine (i.e. MyISAM
  152. vs. InnoDB). Specifically, if tables that have a ``ForeignKey`` between them
  153. use different storage engines, you may see an error like the following when
  154. running ``migrate``::
  155. _mysql_exceptions.OperationalError: (
  156. 1005, "Can't create table '\\db_name\\.#sql-4a8_ab' (errno: 150)"
  157. )
  158. .. _storage engines: http://dev.mysql.com/doc/refman/5.6/en/storage-engines.html
  159. .. _MyISAM: http://dev.mysql.com/doc/refman/5.6/en/myisam-storage-engine.html
  160. .. _InnoDB: http://dev.mysql.com/doc/refman/5.6/en/innodb-storage-engine.html
  161. .. [#] Unless this was changed by the packager of your MySQL package. We've
  162. had reports that the Windows Community Server installer sets up InnoDB as
  163. the default storage engine, for example.
  164. .. _mysql-db-api-drivers:
  165. MySQL DB API Drivers
  166. --------------------
  167. The Python Database API is described in :pep:`249`. MySQL has three prominent
  168. drivers that implement this API:
  169. - `MySQLdb`_ is a native driver that has been developed and supported for over
  170. a decade by Andy Dustman.
  171. - `mysqlclient`_ is a fork of ``MySQLdb`` which notably supports Python 3 and
  172. can be used as a drop-in replacement for MySQLdb. At the time of this writing,
  173. this is **the recommended choice** for using MySQL with Django.
  174. - `MySQL Connector/Python`_ is a pure Python driver from Oracle that does not
  175. require the MySQL client library or any Python modules outside the standard
  176. library.
  177. .. _MySQLdb: https://pypi.python.org/pypi/MySQL-python/1.2.4
  178. .. _mysqlclient: https://pypi.python.org/pypi/mysqlclient
  179. .. _MySQL Connector/Python: http://dev.mysql.com/downloads/connector/python
  180. All these drivers are thread-safe and provide connection pooling. ``MySQLdb``
  181. is the only one not supporting Python 3 currently.
  182. In addition to a DB API driver, Django needs an adapter to access the database
  183. drivers from its ORM. Django provides an adapter for MySQLdb/mysqlclient while
  184. MySQL Connector/Python includes `its own`_.
  185. .. _its own: http://dev.mysql.com/doc/refman/5.6/en/connector-python-info.html
  186. MySQLdb
  187. ~~~~~~~
  188. Django requires MySQLdb version 1.2.1p2 or later.
  189. .. note::
  190. If you see ``ImportError: cannot import name ImmutableSet`` when trying to
  191. use Django, your MySQLdb installation may contain an outdated ``sets.py``
  192. file that conflicts with the built-in module of the same name from Python
  193. 2.4 and later. To fix this, verify that you have installed MySQLdb version
  194. 1.2.1p2 or newer, then delete the ``sets.py`` file in the MySQLdb
  195. directory that was left by an earlier version.
  196. .. note::
  197. There are known issues with the way MySQLdb converts date strings into
  198. datetime objects. Specifically, date strings with value 0000-00-00 are
  199. valid for MySQL but will be converted into None by MySQLdb.
  200. This means you should be careful while using loaddata/dumpdata with rows
  201. that may have 0000-00-00 values, as they will be converted to None.
  202. .. note::
  203. At the time of writing, the latest release of MySQLdb (1.2.4) doesn't
  204. support Python 3. In order to use MySQLdb under Python 3, you'll have to
  205. install ``mysqlclient``.
  206. mysqlclient
  207. ~~~~~~~~~~~
  208. Django requires `mysqlclient`_ 1.3.3 or later. Note that Python 3.2 is not
  209. supported. Except for the Python 3.3+ support, mysqlclient should mostly behave
  210. the same as MySQLDB.
  211. MySQL Connector/Python
  212. ~~~~~~~~~~~~~~~~~~~~~~
  213. MySQL Connector/Python is available from the `download page`_.
  214. The Django adapter is available in versions 1.1.X and later. It may not
  215. support the most recent releases of Django.
  216. .. _download page: http://dev.mysql.com/downloads/connector/python/
  217. .. _mysql-time-zone-definitions:
  218. Time zone definitions
  219. ---------------------
  220. If you plan on using Django's :doc:`timezone support </topics/i18n/timezones>`,
  221. use `mysql_tzinfo_to_sql`_ to load time zone tables into the MySQL database.
  222. This needs to be done just once for your MySQL server, not per database.
  223. .. _mysql_tzinfo_to_sql: http://dev.mysql.com/doc/refman/5.6/en/mysql-tzinfo-to-sql.html
  224. Creating your database
  225. ----------------------
  226. You can `create your database`_ using the command-line tools and this SQL::
  227. CREATE DATABASE <dbname> CHARACTER SET utf8;
  228. This ensures all tables and columns will use UTF-8 by default.
  229. .. _create your database: http://dev.mysql.com/doc/refman/5.6/en/create-database.html
  230. .. _mysql-collation:
  231. Collation settings
  232. ~~~~~~~~~~~~~~~~~~
  233. The collation setting for a column controls the order in which data is sorted
  234. as well as what strings compare as equal. It can be set on a database-wide
  235. level and also per-table and per-column. This is `documented thoroughly`_ in
  236. the MySQL documentation. In all cases, you set the collation by directly
  237. manipulating the database tables; Django doesn't provide a way to set this on
  238. the model definition.
  239. .. _documented thoroughly: http://dev.mysql.com/doc/refman/5.6/en/charset.html
  240. By default, with a UTF-8 database, MySQL will use the
  241. ``utf8_general_ci`` collation. This results in all string equality
  242. comparisons being done in a *case-insensitive* manner. That is, ``"Fred"`` and
  243. ``"freD"`` are considered equal at the database level. If you have a unique
  244. constraint on a field, it would be illegal to try to insert both ``"aa"`` and
  245. ``"AA"`` into the same column, since they compare as equal (and, hence,
  246. non-unique) with the default collation.
  247. In many cases, this default will not be a problem. However, if you really want
  248. case-sensitive comparisons on a particular column or table, you would change
  249. the column or table to use the ``utf8_bin`` collation. The main thing to be
  250. aware of in this case is that if you are using MySQLdb 1.2.2, the database
  251. backend in Django will then return bytestrings (instead of unicode strings) for
  252. any character fields it receive from the database. This is a strong variation
  253. from Django's normal practice of *always* returning unicode strings. It is up
  254. to you, the developer, to handle the fact that you will receive bytestrings if
  255. you configure your table(s) to use ``utf8_bin`` collation. Django itself should
  256. mostly work smoothly with such columns (except for the ``contrib.sessions``
  257. ``Session`` and ``contrib.admin`` ``LogEntry`` tables described below), but
  258. your code must be prepared to call ``django.utils.encoding.smart_text()`` at
  259. times if it really wants to work with consistent data -- Django will not do
  260. this for you (the database backend layer and the model population layer are
  261. separated internally so the database layer doesn't know it needs to make this
  262. conversion in this one particular case).
  263. If you're using MySQLdb 1.2.1p2, Django's standard
  264. :class:`~django.db.models.CharField` class will return unicode strings even
  265. with ``utf8_bin`` collation. However, :class:`~django.db.models.TextField`
  266. fields will be returned as an ``array.array`` instance (from Python's standard
  267. ``array`` module). There isn't a lot Django can do about that, since, again,
  268. the information needed to make the necessary conversions isn't available when
  269. the data is read in from the database. This problem was `fixed in MySQLdb
  270. 1.2.2`_, so if you want to use :class:`~django.db.models.TextField` with
  271. ``utf8_bin`` collation, upgrading to version 1.2.2 and then dealing with the
  272. bytestrings (which shouldn't be too difficult) as described above is the
  273. recommended solution.
  274. Should you decide to use ``utf8_bin`` collation for some of your tables with
  275. MySQLdb 1.2.1p2 or 1.2.2, you should still use ``utf8_general_ci``
  276. (the default) collation for the ``django.contrib.sessions.models.Session``
  277. table (usually called ``django_session``) and the
  278. ``django.contrib.admin.models.LogEntry`` table (usually called
  279. ``django_admin_log``). Those are the two standard tables that use
  280. :class:`~django.db.models.TextField` internally.
  281. .. _fixed in MySQLdb 1.2.2: http://sourceforge.net/tracker/index.php?func=detail&aid=1495765&group_id=22307&atid=374932
  282. Please note that according to `MySQL Unicode Character Sets`_, comparisons for
  283. the ``utf8_general_ci`` collation are faster, but slightly less correct, than
  284. comparisons for ``utf8_unicode_ci``. If this is acceptable for your application,
  285. you should use ``utf8_general_ci`` because it is faster. If this is not acceptable
  286. (for example, if you require German dictionary order), use ``utf8_unicode_ci``
  287. because it is more accurate.
  288. .. _MySQL Unicode Character Sets: http://dev.mysql.com/doc/refman/5.7/en/charset-unicode-sets.html
  289. .. warning::
  290. Model formsets validate unique fields in a case-sensitive manner. Thus when
  291. using a case-insensitive collation, a formset with unique field values that
  292. differ only by case will pass validation, but upon calling ``save()``, an
  293. ``IntegrityError`` will be raised.
  294. Connecting to the database
  295. --------------------------
  296. Refer to the :doc:`settings documentation </ref/settings>`.
  297. Connection settings are used in this order:
  298. 1. :setting:`OPTIONS`.
  299. 2. :setting:`NAME`, :setting:`USER`, :setting:`PASSWORD`,
  300. :setting:`HOST`, :setting:`PORT`
  301. 3. MySQL option files.
  302. In other words, if you set the name of the database in :setting:`OPTIONS`,
  303. this will take precedence over :setting:`NAME`, which would override
  304. anything in a `MySQL option file`_.
  305. Here's a sample configuration which uses a MySQL option file::
  306. # settings.py
  307. DATABASES = {
  308. 'default': {
  309. 'ENGINE': 'django.db.backends.mysql',
  310. 'OPTIONS': {
  311. 'read_default_file': '/path/to/my.cnf',
  312. },
  313. }
  314. }
  315. # my.cnf
  316. [client]
  317. database = NAME
  318. user = USER
  319. password = PASSWORD
  320. default-character-set = utf8
  321. Several other MySQLdb connection options may be useful, such as ``ssl``,
  322. ``init_command``, and ``sql_mode``. Consult the `MySQLdb documentation`_ for
  323. more details.
  324. .. _MySQL option file: http://dev.mysql.com/doc/refman/5.6/en/option-files.html
  325. .. _MySQLdb documentation: http://mysql-python.sourceforge.net/
  326. Creating your tables
  327. --------------------
  328. When Django generates the schema, it doesn't specify a storage engine, so
  329. tables will be created with whatever default storage engine your database
  330. server is configured for. The easiest solution is to set your database server's
  331. default storage engine to the desired engine.
  332. If you're using a hosting service and can't change your server's default
  333. storage engine, you have a couple of options.
  334. * After the tables are created, execute an ``ALTER TABLE`` statement to
  335. convert a table to a new storage engine (such as InnoDB)::
  336. ALTER TABLE <tablename> ENGINE=INNODB;
  337. This can be tedious if you have a lot of tables.
  338. * Another option is to use the ``init_command`` option for MySQLdb prior to
  339. creating your tables::
  340. 'OPTIONS': {
  341. 'init_command': 'SET storage_engine=INNODB',
  342. }
  343. This sets the default storage engine upon connecting to the database.
  344. After your tables have been created, you should remove this option as it
  345. adds a query that is only needed during table creation to each database
  346. connection.
  347. Table names
  348. -----------
  349. There are `known issues`_ in even the latest versions of MySQL that can cause the
  350. case of a table name to be altered when certain SQL statements are executed
  351. under certain conditions. It is recommended that you use lowercase table
  352. names, if possible, to avoid any problems that might arise from this behavior.
  353. Django uses lowercase table names when it auto-generates table names from
  354. models, so this is mainly a consideration if you are overriding the table name
  355. via the :class:`~django.db.models.Options.db_table` parameter.
  356. .. _known issues: http://bugs.mysql.com/bug.php?id=48875
  357. Savepoints
  358. ----------
  359. Both the Django ORM and MySQL (when using the InnoDB :ref:`storage engine
  360. <mysql-storage-engines>`) support database :ref:`savepoints
  361. <topics-db-transactions-savepoints>`.
  362. If you use the MyISAM storage engine please be aware of the fact that you will
  363. receive database-generated errors if you try to use the :ref:`savepoint-related
  364. methods of the transactions API <topics-db-transactions-savepoints>`. The reason
  365. for this is that detecting the storage engine of a MySQL database/table is an
  366. expensive operation so it was decided it isn't worth to dynamically convert
  367. these methods in no-op's based in the results of such detection.
  368. Notes on specific fields
  369. ------------------------
  370. Character fields
  371. ~~~~~~~~~~~~~~~~
  372. Any fields that are stored with ``VARCHAR`` column types have their
  373. ``max_length`` restricted to 255 characters if you are using ``unique=True``
  374. for the field. This affects :class:`~django.db.models.CharField`,
  375. :class:`~django.db.models.SlugField` and
  376. :class:`~django.db.models.CommaSeparatedIntegerField`.
  377. .. _mysql-fractional-seconds:
  378. Fractional seconds support for Time and DateTime fields
  379. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  380. MySQL 5.6.4 and later can store fractional seconds, provided that the
  381. column definition includes a fractional indication (e.g. ``DATETIME(6)``).
  382. Earlier versions do not support them at all. In addition, versions of MySQLdb
  383. older than 1.2.5 have `a bug`_ that also prevents the use of fractional seconds
  384. with MySQL.
  385. .. _a bug: https://github.com/farcepest/MySQLdb1/issues/24
  386. Django will not upgrade existing columns to include fractional seconds if the
  387. database server supports it. If you want to enable them on an existing database,
  388. it's up to you to either manually update the column on the target database, by
  389. executing a command like::
  390. ALTER TABLE `your_table` MODIFY `your_datetime_column` DATETIME(6)
  391. or using a :class:`~django.db.migrations.operations.RunSQL` operation in a
  392. :ref:`data migration <data-migrations>`.
  393. .. versionchanged:: 1.8
  394. Previously, Django truncated fractional seconds from ``datetime`` and
  395. ``time`` values when using the MySQL backend. Now it lets the database
  396. decide whether it should drop that part of the value or not. By default, new
  397. ``DateTimeField`` or ``TimeField`` columns are now created with fractional
  398. seconds support on MySQL 5.6.4 or later with either mysqlclient or
  399. MySQLdb 1.2.5 or later.
  400. ``TIMESTAMP`` columns
  401. ~~~~~~~~~~~~~~~~~~~~~
  402. If you are using a legacy database that contains ``TIMESTAMP`` columns, you must
  403. set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption.
  404. :djadmin:`inspectdb` maps these columns to
  405. :class:`~django.db.models.DateTimeField` and if you enable timezone support,
  406. both MySQL and Django will attempt to convert the values from UTC to local time.
  407. Row locking with ``QuerySet.select_for_update()``
  408. -------------------------------------------------
  409. MySQL does not support the ``NOWAIT`` option to the ``SELECT ... FOR UPDATE``
  410. statement. If ``select_for_update()`` is used with ``nowait=True`` then a
  411. ``DatabaseError`` will be raised.
  412. Automatic typecasting can cause unexpected results
  413. --------------------------------------------------
  414. When performing a query on a string type, but with an integer value, MySQL will
  415. coerce the types of all values in the table to an integer before performing the
  416. comparison. If your table contains the values ``'abc'``, ``'def'`` and you
  417. query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE mycolumn=1``
  418. will match the value ``'abc1'``. Therefore, string type fields included in Django
  419. will always cast the value to a string before using it in a query.
  420. If you implement custom model fields that inherit from :class:`~django.db.models.Field`
  421. directly, are overriding :meth:`~django.db.models.Field.get_prep_value`, or use
  422. :meth:`extra() <django.db.models.query.QuerySet.extra>` or
  423. :meth:`raw() <django.db.models.Manager.raw>`, you should ensure that you
  424. perform the appropriate typecasting.
  425. .. _sqlite-notes:
  426. SQLite notes
  427. ============
  428. SQLite_ provides an excellent development alternative for applications that
  429. are predominantly read-only or require a smaller installation footprint. As
  430. with all database servers, though, there are some differences that are
  431. specific to SQLite that you should be aware of.
  432. .. _SQLite: http://www.sqlite.org/
  433. .. _sqlite-string-matching:
  434. Substring matching and case sensitivity
  435. -----------------------------------------
  436. For all SQLite versions, there is some slightly counter-intuitive behavior when
  437. attempting to match some types of strings. These are triggered when using the
  438. :lookup:`iexact` or :lookup:`contains` filters in Querysets. The behavior
  439. splits into two cases:
  440. 1. For substring matching, all matches are done case-insensitively. That is a
  441. filter such as ``filter(name__contains="aa")`` will match a name of ``"Aabb"``.
  442. 2. For strings containing characters outside the ASCII range, all exact string
  443. matches are performed case-sensitively, even when the case-insensitive options
  444. are passed into the query. So the :lookup:`iexact` filter will behave exactly
  445. the same as the :lookup:`exact` filter in these cases.
  446. Some possible workarounds for this are `documented at sqlite.org`_, but they
  447. aren't utilized by the default SQLite backend in Django, as incorporating them
  448. would be fairly difficult to do robustly. Thus, Django exposes the default
  449. SQLite behavior and you should be aware of this when doing case-insensitive or
  450. substring filtering.
  451. .. _documented at sqlite.org: http://www.sqlite.org/faq.html#q18
  452. .. _using-newer-versions-of-pysqlite:
  453. Using newer versions of the SQLite DB-API 2.0 driver
  454. ----------------------------------------------------
  455. Django will use a ``pysqlite2`` module in preference to ``sqlite3`` as shipped
  456. with the Python standard library if it finds one is available.
  457. This provides the ability to upgrade both the DB-API 2.0 interface or SQLite 3
  458. itself to versions newer than the ones included with your particular Python
  459. binary distribution, if needed.
  460. "Database is locked" errors
  461. ---------------------------
  462. SQLite is meant to be a lightweight database, and thus can't support a high
  463. level of concurrency. ``OperationalError: database is locked`` errors indicate
  464. that your application is experiencing more concurrency than ``sqlite`` can
  465. handle in default configuration. This error means that one thread or process has
  466. an exclusive lock on the database connection and another thread timed out
  467. waiting for the lock the be released.
  468. Python's SQLite wrapper has
  469. a default timeout value that determines how long the second thread is allowed to
  470. wait on the lock before it times out and raises the ``OperationalError: database
  471. is locked`` error.
  472. If you're getting this error, you can solve it by:
  473. * Switching to another database backend. At a certain point SQLite becomes
  474. too "lite" for real-world applications, and these sorts of concurrency
  475. errors indicate you've reached that point.
  476. * Rewriting your code to reduce concurrency and ensure that database
  477. transactions are short-lived.
  478. * Increase the default timeout value by setting the ``timeout`` database
  479. option option::
  480. 'OPTIONS': {
  481. # ...
  482. 'timeout': 20,
  483. # ...
  484. }
  485. This will simply make SQLite wait a bit longer before throwing "database
  486. is locked" errors; it won't really do anything to solve them.
  487. ``QuerySet.select_for_update()`` not supported
  488. ----------------------------------------------
  489. SQLite does not support the ``SELECT ... FOR UPDATE`` syntax. Calling it will
  490. have no effect.
  491. "pyformat" parameter style in raw queries not supported
  492. -------------------------------------------------------
  493. For most backends, raw queries (``Manager.raw()`` or ``cursor.execute()``)
  494. can use the "pyformat" parameter style, where placeholders in the query
  495. are given as ``'%(name)s'`` and the parameters are passed as a dictionary
  496. rather than a list. SQLite does not support this.
  497. .. _sqlite-connection-queries:
  498. Parameters not quoted in ``connection.queries``
  499. -----------------------------------------------
  500. ``sqlite3`` does not provide a way to retrieve the SQL after quoting and
  501. substituting the parameters. Instead, the SQL in ``connection.queries`` is
  502. rebuilt with a simple string interpolation. It may be incorrect. Make sure
  503. you add quotes where necessary before copying a query into an SQLite shell.
  504. .. _oracle-notes:
  505. Oracle notes
  506. ============
  507. Django supports `Oracle Database Server`_ versions 11.1 and higher. Version
  508. 4.3.1 or higher of the `cx_Oracle`_ Python driver is required, although we
  509. recommend version 5.1.3 or later as these versions support Python 3.
  510. Note that due to a Unicode-corruption bug in ``cx_Oracle`` 5.0, that
  511. version of the driver should **not** be used with Django;
  512. ``cx_Oracle`` 5.0.1 resolved this issue, so if you'd like to use a
  513. more recent ``cx_Oracle``, use version 5.0.1.
  514. ``cx_Oracle`` 5.0.1 or greater can optionally be compiled with the
  515. ``WITH_UNICODE`` environment variable. This is recommended but not
  516. required.
  517. .. _`Oracle Database Server`: http://www.oracle.com/
  518. .. _`cx_Oracle`: http://cx-oracle.sourceforge.net/
  519. In order for the ``python manage.py migrate`` command to work, your Oracle
  520. database user must have privileges to run the following commands:
  521. * CREATE TABLE
  522. * CREATE SEQUENCE
  523. * CREATE PROCEDURE
  524. * CREATE TRIGGER
  525. To run a project's test suite, the user usually needs these *additional*
  526. privileges:
  527. * CREATE USER
  528. * DROP USER
  529. * CREATE TABLESPACE
  530. * DROP TABLESPACE
  531. * CREATE SESSION WITH ADMIN OPTION
  532. * CREATE TABLE WITH ADMIN OPTION
  533. * CREATE SEQUENCE WITH ADMIN OPTION
  534. * CREATE PROCEDURE WITH ADMIN OPTION
  535. * CREATE TRIGGER WITH ADMIN OPTION
  536. Note that, while the RESOURCE role has the required CREATE TABLE, CREATE
  537. SEQUENCE, CREATE PROCEDURE and CREATE TRIGGER privileges, and a user
  538. granted RESOURCE WITH ADMIN OPTION can grant RESOURCE, such a user cannot
  539. grant the individual privileges (e.g. CREATE TABLE), and thus RESOURCE
  540. WITH ADMIN OPTION is not usually sufficient for running tests.
  541. Some test suites also create views; to run these, the user also needs
  542. the CREATE VIEW WITH ADMIN OPTION privilege. In particular, this is needed
  543. for Django's own test suite.
  544. .. versionchanged:: 1.8
  545. Prior to Django 1.8, the test user was granted the CONNECT and RESOURCE
  546. roles, so the extra privileges required for running the test suite were
  547. different.
  548. All of these privileges are included in the DBA role, which is appropriate
  549. for use on a private developer's database.
  550. The Oracle database backend uses the ``SYS.DBMS_LOB`` package, so your user
  551. will require execute permissions on it. It's normally accessible to all users
  552. by default, but in case it is not, you'll need to grant permissions like so:
  553. .. code-block:: sql
  554. GRANT EXECUTE ON SYS.DBMS_LOB TO user;
  555. Connecting to the database
  556. --------------------------
  557. To connect using the service name of your Oracle database, your ``settings.py``
  558. file should look something like this::
  559. DATABASES = {
  560. 'default': {
  561. 'ENGINE': 'django.db.backends.oracle',
  562. 'NAME': 'xe',
  563. 'USER': 'a_user',
  564. 'PASSWORD': 'a_password',
  565. 'HOST': '',
  566. 'PORT': '',
  567. }
  568. }
  569. In this case, you should leave both :setting:`HOST` and :setting:`PORT` empty.
  570. However, if you don't use a ``tnsnames.ora`` file or a similar naming method
  571. and want to connect using the SID ("xe" in this example), then fill in both
  572. :setting:`HOST` and :setting:`PORT` like so::
  573. DATABASES = {
  574. 'default': {
  575. 'ENGINE': 'django.db.backends.oracle',
  576. 'NAME': 'xe',
  577. 'USER': 'a_user',
  578. 'PASSWORD': 'a_password',
  579. 'HOST': 'dbprod01ned.mycompany.com',
  580. 'PORT': '1540',
  581. }
  582. }
  583. You should either supply both :setting:`HOST` and :setting:`PORT`, or leave
  584. both as empty strings. Django will use a different connect descriptor depending
  585. on that choice.
  586. Threaded option
  587. ----------------
  588. If you plan to run Django in a multithreaded environment (e.g. Apache using the
  589. default MPM module on any modern operating system), then you **must** set
  590. the ``threaded`` option of your Oracle database configuration to True::
  591. 'OPTIONS': {
  592. 'threaded': True,
  593. },
  594. Failure to do this may result in crashes and other odd behavior.
  595. INSERT ... RETURNING INTO
  596. -------------------------
  597. By default, the Oracle backend uses a ``RETURNING INTO`` clause to efficiently
  598. retrieve the value of an ``AutoField`` when inserting new rows. This behavior
  599. may result in a ``DatabaseError`` in certain unusual setups, such as when
  600. inserting into a remote table, or into a view with an ``INSTEAD OF`` trigger.
  601. The ``RETURNING INTO`` clause can be disabled by setting the
  602. ``use_returning_into`` option of the database configuration to False::
  603. 'OPTIONS': {
  604. 'use_returning_into': False,
  605. },
  606. In this case, the Oracle backend will use a separate ``SELECT`` query to
  607. retrieve AutoField values.
  608. Naming issues
  609. -------------
  610. Oracle imposes a name length limit of 30 characters. To accommodate this, the
  611. backend truncates database identifiers to fit, replacing the final four
  612. characters of the truncated name with a repeatable MD5 hash value.
  613. Additionally, the backend turns database identifiers to all-uppercase.
  614. To prevent these transformations (this is usually required only when dealing
  615. with legacy databases or accessing tables which belong to other users), use
  616. a quoted name as the value for ``db_table``::
  617. class LegacyModel(models.Model):
  618. class Meta:
  619. db_table = '"name_left_in_lowercase"'
  620. class ForeignModel(models.Model):
  621. class Meta:
  622. db_table = '"OTHER_USER"."NAME_ONLY_SEEMS_OVER_30"'
  623. Quoted names can also be used with Django's other supported database
  624. backends; except for Oracle, however, the quotes have no effect.
  625. When running ``migrate``, an ``ORA-06552`` error may be encountered if
  626. certain Oracle keywords are used as the name of a model field or the
  627. value of a ``db_column`` option. Django quotes all identifiers used
  628. in queries to prevent most such problems, but this error can still
  629. occur when an Oracle datatype is used as a column name. In
  630. particular, take care to avoid using the names ``date``,
  631. ``timestamp``, ``number`` or ``float`` as a field name.
  632. NULL and empty strings
  633. ----------------------
  634. Django generally prefers to use the empty string ('') rather than
  635. NULL, but Oracle treats both identically. To get around this, the
  636. Oracle backend ignores an explicit ``null`` option on fields that
  637. have the empty string as a possible value and generates DDL as if
  638. ``null=True``. When fetching from the database, it is assumed that
  639. a ``NULL`` value in one of these fields really means the empty
  640. string, and the data is silently converted to reflect this assumption.
  641. ``TextField`` limitations
  642. -------------------------
  643. The Oracle backend stores ``TextFields`` as ``NCLOB`` columns. Oracle imposes
  644. some limitations on the usage of such LOB columns in general:
  645. * LOB columns may not be used as primary keys.
  646. * LOB columns may not be used in indexes.
  647. * LOB columns may not be used in a ``SELECT DISTINCT`` list. This means that
  648. attempting to use the ``QuerySet.distinct`` method on a model that
  649. includes ``TextField`` columns will result in an error when run against
  650. Oracle. As a workaround, use the ``QuerySet.defer`` method in conjunction
  651. with ``distinct()`` to prevent ``TextField`` columns from being included in
  652. the ``SELECT DISTINCT`` list.
  653. .. _third-party-notes:
  654. Using a 3rd-party database backend
  655. ==================================
  656. In addition to the officially supported databases, there are backends provided
  657. by 3rd parties that allow you to use other databases with Django:
  658. * `SAP SQL Anywhere`_
  659. * `IBM DB2`_
  660. * `Microsoft SQL Server`_
  661. * Firebird_
  662. * ODBC_
  663. * ADSDB_
  664. The Django versions and ORM features supported by these unofficial backends
  665. vary considerably. Queries regarding the specific capabilities of these
  666. unofficial backends, along with any support queries, should be directed to
  667. the support channels provided by each 3rd party project.
  668. .. _SAP SQL Anywhere: https://github.com/sqlanywhere/sqlany-django
  669. .. _IBM DB2: http://code.google.com/p/ibm-db/
  670. .. _Microsoft SQL Server: http://django-mssql.readthedocs.org/en/latest/
  671. .. _Firebird: https://github.com/maxirobaina/django-firebird
  672. .. _ODBC: https://github.com/lionheart/django-pyodbc/
  673. .. _ADSDB: http://code.google.com/p/adsdb-django/