databases.txt 35 KB

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