databases.txt 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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. .. _postgresql-notes:
  12. PostgreSQL notes
  13. ================
  14. .. versionchanged:: 1.4
  15. Django supports PostgreSQL 8.2 and higher.
  16. PostgreSQL 8.2 to 8.2.4
  17. -----------------------
  18. The implementation of the population statistics aggregates ``STDDEV_POP`` and
  19. ``VAR_POP`` that shipped with PostgreSQL 8.2 to 8.2.4 are `known to be
  20. faulty`_. Users of these releases of PostgreSQL are advised to upgrade to
  21. `Release 8.2.5`_ or later. Django will raise a ``NotImplementedError`` if you
  22. attempt to use the ``StdDev(sample=False)`` or ``Variance(sample=False)``
  23. aggregate with a database backend that falls within the affected release range.
  24. .. _known to be faulty: http://archives.postgresql.org/pgsql-bugs/2007-07/msg00046.php
  25. .. _Release 8.2.5: http://developer.postgresql.org/pgdocs/postgres/release-8-2-5.html
  26. Optimizing PostgreSQL's configuration
  27. -------------------------------------
  28. Django needs the following parameters for its database connections:
  29. - ``client_encoding``: ``'UTF8'``,
  30. - ``default_transaction_isolation``: ``'read committed'``,
  31. - ``timezone``: ``'UTC'`` when :setting:`USE_TZ` is ``True``, value of
  32. :setting:`TIME_ZONE` otherwise.
  33. If these parameters already have the correct values, Django won't set them for
  34. every new connection, which improves performance slightly. You can configure
  35. them directly in :file:`postgresql.conf` or more conveniently per database
  36. user with `ALTER ROLE`_.
  37. Django will work just fine without this optimization, but each new connection
  38. will do some additional queries to set these parameters.
  39. .. _ALTER ROLE: http://www.postgresql.org/docs/current/interactive/sql-alterrole.html
  40. Transaction handling
  41. ---------------------
  42. :doc:`By default </topics/db/transactions>`, Django starts a transaction when a
  43. database connection is first used and commits the result at the end of the
  44. request/response handling. The PostgreSQL backends normally operate the same
  45. as any other Django backend in this respect.
  46. .. _postgresql-autocommit-mode:
  47. Autocommit mode
  48. ~~~~~~~~~~~~~~~
  49. If your application is particularly read-heavy and doesn't make many
  50. database writes, the overhead of a constantly open transaction can
  51. sometimes be noticeable. For those situations, you can configure Django
  52. to use *"autocommit"* behavior for the connection, meaning that each database
  53. operation will normally be in its own transaction, rather than having
  54. the transaction extend over multiple operations. In this case, you can
  55. still manually start a transaction if you're doing something that
  56. requires consistency across multiple database operations. The
  57. autocommit behavior is enabled by setting the ``autocommit`` key in
  58. the :setting:`OPTIONS` part of your database configuration in
  59. :setting:`DATABASES`::
  60. 'OPTIONS': {
  61. 'autocommit': True,
  62. }
  63. In this configuration, Django still ensures that :ref:`delete()
  64. <topics-db-queries-delete>` and :ref:`update() <topics-db-queries-update>`
  65. queries run inside a single transaction, so that either all the affected
  66. objects are changed or none of them are.
  67. .. admonition:: This is database-level autocommit
  68. This functionality is not the same as the :ref:`autocommit
  69. <topics-db-transactions-autocommit>` decorator. That decorator is
  70. a Django-level implementation that commits automatically after
  71. data changing operations. The feature enabled using the
  72. :setting:`OPTIONS` option provides autocommit behavior at the
  73. database adapter level. It commits after *every* operation.
  74. If you are using this feature and performing an operation akin to delete or
  75. updating that requires multiple operations, you are strongly recommended to
  76. wrap you operations in manual transaction handling to ensure data consistency.
  77. You should also audit your existing code for any instances of this behavior
  78. before enabling this feature. It's faster, but it provides less automatic
  79. protection for multi-call operations.
  80. Indexes for ``varchar`` and ``text`` columns
  81. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  82. When specifying ``db_index=True`` on your model fields, Django typically
  83. outputs a single ``CREATE INDEX`` statement. However, if the database type
  84. for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``,
  85. ``FileField``, and ``TextField``), then Django will create
  86. an additional index that uses an appropriate `PostgreSQL operator class`_
  87. for the column. The extra index is necessary to correctly perfrom
  88. lookups that use the ``LIKE`` operator in their SQL, as is done with the
  89. ``contains`` and ``startswith`` lookup types.
  90. .. _PostgreSQL operator class: http://www.postgresql.org/docs/8.4/static/indexes-opclass.html
  91. .. _mysql-notes:
  92. MySQL notes
  93. ===========
  94. Django expects the database to support transactions, referential integrity, and
  95. Unicode (UTF-8 encoding). Fortunately, MySQL_ has all these features as
  96. available as far back as 3.23. While it may be possible to use 3.23 or 4.0,
  97. you'll probably have less trouble if you use 4.1 or 5.0.
  98. MySQL 4.1
  99. ---------
  100. `MySQL 4.1`_ has greatly improved support for character sets. It is possible to
  101. set different default character sets on the database, table, and column.
  102. Previous versions have only a server-wide character set setting. It's also the
  103. first version where the character set can be changed on the fly. 4.1 also has
  104. support for views, but Django currently doesn't use views.
  105. MySQL 5.0
  106. ---------
  107. `MySQL 5.0`_ adds the ``information_schema`` database, which contains detailed
  108. data on all database schema. Django's ``inspectdb`` feature uses this
  109. ``information_schema`` if it's available. 5.0 also has support for stored
  110. procedures, but Django currently doesn't use stored procedures.
  111. .. _MySQL: http://www.mysql.com/
  112. .. _MySQL 4.1: http://dev.mysql.com/doc/refman/4.1/en/index.html
  113. .. _MySQL 5.0: http://dev.mysql.com/doc/refman/5.0/en/index.html
  114. Storage engines
  115. ---------------
  116. MySQL has several `storage engines`_ (previously called table types). You can
  117. change the default storage engine in the server configuration.
  118. Until MySQL 5.5.4, the default engine was MyISAM_ [#]_. The main drawbacks of
  119. MyISAM are that it doesn't support transactions or enforce foreign-key
  120. constraints. On the plus side, it's currently the only engine that supports
  121. full-text indexing and searching.
  122. Since MySQL 5.5.5, the default storage engine is InnoDB_. This engine is fully
  123. transactional and supports foreign key references. It's probably the best
  124. choice at this point.
  125. .. versionchanged:: 1.4
  126. In previous versions of Django, fixtures with forward references (i.e.
  127. relations to rows that have not yet been inserted into the database) would fail
  128. to load when using the InnoDB storage engine. This was due to the fact that InnoDB
  129. deviates from the SQL standard by checking foreign key constraints immediately
  130. instead of deferring the check until the transaction is committed. This
  131. problem has been resolved in Django 1.4. Fixture data is now loaded with foreign key
  132. checks turned off; foreign key checks are then re-enabled when the data has
  133. finished loading, at which point the entire table is checked for invalid foreign
  134. key references and an `IntegrityError` is raised if any are found.
  135. .. _storage engines: http://dev.mysql.com/doc/refman/5.5/en/storage-engines.html
  136. .. _MyISAM: http://dev.mysql.com/doc/refman/5.5/en/myisam-storage-engine.html
  137. .. _InnoDB: http://dev.mysql.com/doc/refman/5.5/en/innodb.html
  138. .. [#] Unless this was changed by the packager of your MySQL package. We've
  139. had reports that the Windows Community Server installer sets up InnoDB as
  140. the default storage engine, for example.
  141. MySQLdb
  142. -------
  143. `MySQLdb`_ is the Python interface to MySQL. Version 1.2.1p2 or later is
  144. required for full MySQL support in Django.
  145. .. note::
  146. If you see ``ImportError: cannot import name ImmutableSet`` when trying to
  147. use Django, your MySQLdb installation may contain an outdated ``sets.py``
  148. file that conflicts with the built-in module of the same name from Python
  149. 2.4 and later. To fix this, verify that you have installed MySQLdb version
  150. 1.2.1p2 or newer, then delete the ``sets.py`` file in the MySQLdb
  151. directory that was left by an earlier version.
  152. .. _MySQLdb: http://sourceforge.net/projects/mysql-python
  153. Creating your database
  154. ----------------------
  155. You can `create your database`_ using the command-line tools and this SQL::
  156. CREATE DATABASE <dbname> CHARACTER SET utf8;
  157. This ensures all tables and columns will use UTF-8 by default.
  158. .. _create your database: http://dev.mysql.com/doc/refman/5.0/en/create-database.html
  159. .. _mysql-collation:
  160. Collation settings
  161. ~~~~~~~~~~~~~~~~~~
  162. The collation setting for a column controls the order in which data is sorted
  163. as well as what strings compare as equal. It can be set on a database-wide
  164. level and also per-table and per-column. This is `documented thoroughly`_ in
  165. the MySQL documentation. In all cases, you set the collation by directly
  166. manipulating the database tables; Django doesn't provide a way to set this on
  167. the model definition.
  168. .. _documented thoroughly: http://dev.mysql.com/doc/refman/5.0/en/charset.html
  169. By default, with a UTF-8 database, MySQL will use the
  170. ``utf8_general_ci_swedish`` collation. This results in all string equality
  171. comparisons being done in a *case-insensitive* manner. That is, ``"Fred"`` and
  172. ``"freD"`` are considered equal at the database level. If you have a unique
  173. constraint on a field, it would be illegal to try to insert both ``"aa"`` and
  174. ``"AA"`` into the same column, since they compare as equal (and, hence,
  175. non-unique) with the default collation.
  176. In many cases, this default will not be a problem. However, if you really want
  177. case-sensitive comparisons on a particular column or table, you would change
  178. the column or table to use the ``utf8_bin`` collation. The main thing to be
  179. aware of in this case is that if you are using MySQLdb 1.2.2, the database
  180. backend in Django will then return bytestrings (instead of unicode strings) for
  181. any character fields it receive from the database. This is a strong variation
  182. from Django's normal practice of *always* returning unicode strings. It is up
  183. to you, the developer, to handle the fact that you will receive bytestrings if
  184. you configure your table(s) to use ``utf8_bin`` collation. Django itself should
  185. mostly work smoothly with such columns (except for the ``contrib.sessions``
  186. ``Session`` and ``contrib.admin`` ``LogEntry`` tables described below), but
  187. your code must be prepared to call ``django.utils.encoding.smart_unicode()`` at
  188. times if it really wants to work with consistent data -- Django will not do
  189. this for you (the database backend layer and the model population layer are
  190. separated internally so the database layer doesn't know it needs to make this
  191. conversion in this one particular case).
  192. If you're using MySQLdb 1.2.1p2, Django's standard
  193. :class:`~django.db.models.CharField` class will return unicode strings even
  194. with ``utf8_bin`` collation. However, :class:`~django.db.models.TextField`
  195. fields will be returned as an ``array.array`` instance (from Python's standard
  196. ``array`` module). There isn't a lot Django can do about that, since, again,
  197. the information needed to make the necessary conversions isn't available when
  198. the data is read in from the database. This problem was `fixed in MySQLdb
  199. 1.2.2`_, so if you want to use :class:`~django.db.models.TextField` with
  200. ``utf8_bin`` collation, upgrading to version 1.2.2 and then dealing with the
  201. bytestrings (which shouldn't be too difficult) as described above is the
  202. recommended solution.
  203. Should you decide to use ``utf8_bin`` collation for some of your tables with
  204. MySQLdb 1.2.1p2 or 1.2.2, you should still use ``utf8_collation_ci_swedish``
  205. (the default) collation for the :class:`django.contrib.sessions.models.Session`
  206. table (usually called ``django_session``) and the
  207. :class:`django.contrib.admin.models.LogEntry` table (usually called
  208. ``django_admin_log``). Those are the two standard tables that use
  209. :class:`~django.db.models.TextField` internally.
  210. .. _fixed in MySQLdb 1.2.2: http://sourceforge.net/tracker/index.php?func=detail&aid=1495765&group_id=22307&atid=374932
  211. Connecting to the database
  212. --------------------------
  213. Refer to the :doc:`settings documentation </ref/settings>`.
  214. Connection settings are used in this order:
  215. 1. :setting:`OPTIONS`.
  216. 2. :setting:`NAME`, :setting:`USER`, :setting:`PASSWORD`,
  217. :setting:`HOST`, :setting:`PORT`
  218. 3. MySQL option files.
  219. In other words, if you set the name of the database in :setting:`OPTIONS`,
  220. this will take precedence over :setting:`NAME`, which would override
  221. anything in a `MySQL option file`_.
  222. Here's a sample configuration which uses a MySQL option file::
  223. # settings.py
  224. DATABASES = {
  225. 'default': {
  226. 'ENGINE': 'django.db.backends.mysql',
  227. 'OPTIONS': {
  228. 'read_default_file': '/path/to/my.cnf',
  229. },
  230. }
  231. }
  232. # my.cnf
  233. [client]
  234. database = NAME
  235. user = USER
  236. password = PASSWORD
  237. default-character-set = utf8
  238. Several other MySQLdb connection options may be useful, such as ``ssl``,
  239. ``use_unicode``, ``init_command``, and ``sql_mode``. Consult the
  240. `MySQLdb documentation`_ for more details.
  241. .. _MySQL option file: http://dev.mysql.com/doc/refman/5.0/en/option-files.html
  242. .. _MySQLdb documentation: http://mysql-python.sourceforge.net/
  243. Creating your tables
  244. --------------------
  245. When Django generates the schema, it doesn't specify a storage engine, so
  246. tables will be created with whatever default storage engine your database
  247. server is configured for. The easiest solution is to set your database server's
  248. default storage engine to the desired engine.
  249. If you're using a hosting service and can't change your server's default
  250. storage engine, you have a couple of options.
  251. * After the tables are created, execute an ``ALTER TABLE`` statement to
  252. convert a table to a new storage engine (such as InnoDB)::
  253. ALTER TABLE <tablename> ENGINE=INNODB;
  254. This can be tedious if you have a lot of tables.
  255. * Another option is to use the ``init_command`` option for MySQLdb prior to
  256. creating your tables::
  257. 'OPTIONS': {
  258. 'init_command': 'SET storage_engine=INNODB',
  259. }
  260. This sets the default storage engine upon connecting to the database.
  261. After your tables have been created, you should remove this option.
  262. * Another method for changing the storage engine is described in
  263. AlterModelOnSyncDB_.
  264. .. _AlterModelOnSyncDB: https://code.djangoproject.com/wiki/AlterModelOnSyncDB
  265. Table names
  266. -----------
  267. There are `known issues`_ in even the latest versions of MySQL that can cause the
  268. case of a table name to be altered when certain SQL statements are executed
  269. under certain conditions. It is recommended that you use lowercase table
  270. names, if possible, to avoid any problems that might arise from this behavior.
  271. Django uses lowercase table names when it auto-generates table names from
  272. models, so this is mainly a consideration if you are overriding the table name
  273. via the :class:`~django.db.models.Options.db_table` parameter.
  274. .. _known issues: http://bugs.mysql.com/bug.php?id=48875
  275. Notes on specific fields
  276. ------------------------
  277. Boolean fields
  278. ~~~~~~~~~~~~~~
  279. .. versionchanged:: 1.2
  280. In previous versions of Django when running under MySQL ``BooleanFields`` would
  281. return their data as ``ints``, instead of true ``bools``. See the release
  282. notes for a complete description of the change.
  283. Character fields
  284. ~~~~~~~~~~~~~~~~
  285. Any fields that are stored with ``VARCHAR`` column types have their
  286. ``max_length`` restricted to 255 characters if you are using ``unique=True``
  287. for the field. This affects :class:`~django.db.models.CharField`,
  288. :class:`~django.db.models.SlugField` and
  289. :class:`~django.db.models.CommaSeparatedIntegerField`.
  290. Furthermore, if you are using a version of MySQL prior to 5.0.3, all of those
  291. column types have a maximum length restriction of 255 characters, regardless
  292. of whether ``unique=True`` is specified or not.
  293. DateTime fields
  294. ~~~~~~~~~~~~~~~
  295. MySQL does not have a timezone-aware column type. If an attempt is made to
  296. store a timezone-aware ``time`` or ``datetime`` to a
  297. :class:`~django.db.models.TimeField` or :class:`~django.db.models.DateTimeField`
  298. respectively, a ``ValueError`` is raised rather than truncating data.
  299. MySQL does not store fractions of seconds. Fractions of seconds are truncated
  300. to zero when the time is stored.
  301. Row locking with ``QuerySet.select_for_update()``
  302. -------------------------------------------------
  303. MySQL does not support the ``NOWAIT`` option to the ``SELECT ... FOR UPDATE``
  304. statement. If ``select_for_update()`` is used with ``nowait=True`` then a
  305. ``DatabaseError`` will be raised.
  306. .. _sqlite-notes:
  307. SQLite notes
  308. ============
  309. SQLite_ provides an excellent development alternative for applications that
  310. are predominantly read-only or require a smaller installation footprint. As
  311. with all database servers, though, there are some differences that are
  312. specific to SQLite that you should be aware of.
  313. .. _SQLite: http://www.sqlite.org/
  314. .. _sqlite-string-matching:
  315. Substring matching and case sensitivity
  316. -----------------------------------------
  317. For all SQLite versions, there is some slightly counter-intuitive behavior when
  318. attempting to match some types of strings. These are triggered when using the
  319. :lookup:`iexact` or :lookup:`contains` filters in Querysets. The behavior
  320. splits into two cases:
  321. 1. For substring matching, all matches are done case-insensitively. That is a
  322. filter such as ``filter(name__contains="aa")`` will match a name of ``"Aabb"``.
  323. 2. For strings containing characters outside the ASCII range, all exact string
  324. matches are performed case-sensitively, even when the case-insensitive options
  325. are passed into the query. So the :lookup:`iexact` filter will behave exactly
  326. the same as the :lookup:`exact` filter in these cases.
  327. Some possible workarounds for this are `documented at sqlite.org`_, but they
  328. aren't utilised by the default SQLite backend in Django, as incorporating them
  329. would be fairly difficult to do robustly. Thus, Django exposes the default
  330. SQLite behavior and you should be aware of this when doing case-insensitive or
  331. substring filtering.
  332. .. _documented at sqlite.org: http://www.sqlite.org/faq.html#q18
  333. SQLite 3.3.6 or newer strongly recommended
  334. ------------------------------------------
  335. Versions of SQLite 3.3.5 and older contains the following bugs:
  336. * A bug when `handling`_ ``ORDER BY`` parameters. This can cause problems when
  337. you use the ``select`` parameter for the ``extra()`` QuerySet method. The bug
  338. can be identified by the error message ``OperationalError: ORDER BY terms
  339. must not be non-integer constants``.
  340. * A bug when handling `aggregation`_ together with DateFields and
  341. DecimalFields.
  342. .. _handling: http://www.sqlite.org/cvstrac/tktview?tn=1768
  343. .. _aggregation: https://code.djangoproject.com/ticket/10031
  344. SQLite 3.3.6 was released in April 2006, so most current binary distributions
  345. for different platforms include newer version of SQLite usable from Python
  346. through either the ``pysqlite2`` or the ``sqlite3`` modules.
  347. Version 3.5.9
  348. -------------
  349. The Ubuntu "Intrepid Ibex" (8.10) SQLite 3.5.9-3 package contains a bug that
  350. causes problems with the evaluation of query expressions. If you are using
  351. Ubuntu "Intrepid Ibex", you will need to update the package to version
  352. 3.5.9-3ubuntu1 or newer (recommended) or find an alternate source for SQLite
  353. packages, or install SQLite from source.
  354. At one time, Debian Lenny shipped with the same malfunctioning SQLite 3.5.9-3
  355. package. However the Debian project has subsequently issued updated versions
  356. of the SQLite package that correct these bugs. If you find you are getting
  357. unexpected results under Debian, ensure you have updated your SQLite package
  358. to 3.5.9-5 or later.
  359. The problem does not appear to exist with other versions of SQLite packaged
  360. with other operating systems.
  361. Version 3.6.2
  362. --------------
  363. SQLite version 3.6.2 (released August 30, 2008) introduced a bug into ``SELECT
  364. DISTINCT`` handling that is triggered by, amongst other things, Django's
  365. ``DateQuerySet`` (returned by the ``dates()`` method on a queryset).
  366. You should avoid using this version of SQLite with Django. Either upgrade to
  367. 3.6.3 (released September 22, 2008) or later, or downgrade to an earlier
  368. version of SQLite.
  369. .. _using-newer-versions-of-pysqlite:
  370. Using newer versions of the SQLite DB-API 2.0 driver
  371. ----------------------------------------------------
  372. For versions of Python 2.5 or newer that include ``sqlite3`` in the standard
  373. library Django will now use a ``pysqlite2`` interface in preference to
  374. ``sqlite3`` if it finds one is available.
  375. This provides the ability to upgrade both the DB-API 2.0 interface or SQLite 3
  376. itself to versions newer than the ones included with your particular Python
  377. binary distribution, if needed.
  378. "Database is locked" errors
  379. ---------------------------
  380. SQLite is meant to be a lightweight database, and thus can't support a high
  381. level of concurrency. ``OperationalError: database is locked`` errors indicate
  382. that your application is experiencing more concurrency than ``sqlite`` can
  383. handle in default configuration. This error means that one thread or process has
  384. an exclusive lock on the database connection and another thread timed out
  385. waiting for the lock the be released.
  386. Python's SQLite wrapper has
  387. a default timeout value that determines how long the second thread is allowed to
  388. wait on the lock before it times out and raises the ``OperationalError: database
  389. is locked`` error.
  390. If you're getting this error, you can solve it by:
  391. * Switching to another database backend. At a certain point SQLite becomes
  392. too "lite" for real-world applications, and these sorts of concurrency
  393. errors indicate you've reached that point.
  394. * Rewriting your code to reduce concurrency and ensure that database
  395. transactions are short-lived.
  396. * Increase the default timeout value by setting the ``timeout`` database
  397. option option::
  398. 'OPTIONS': {
  399. # ...
  400. 'timeout': 20,
  401. # ...
  402. }
  403. This will simply make SQLite wait a bit longer before throwing "database
  404. is locked" errors; it won't really do anything to solve them.
  405. ``QuerySet.select_for_update()`` not supported
  406. ----------------------------------------------
  407. SQLite does not support the ``SELECT ... FOR UPDATE`` syntax. Calling it will
  408. have no effect.
  409. .. _sqlite-connection-queries:
  410. Parameters not quoted in ``connection.queries``
  411. -----------------------------------------------
  412. ``sqlite3`` does not provide a way to retrieve the SQL after quoting and
  413. substituting the parameters. Instead, the SQL in ``connection.queries`` is
  414. rebuilt with a simple string interpolation. It may be incorrect. Make sure
  415. you add quotes where necessary before copying a query into a SQLite shell.
  416. .. _oracle-notes:
  417. Oracle notes
  418. ============
  419. Django supports `Oracle Database Server`_ versions 9i and
  420. higher. Oracle version 10g or later is required to use Django's
  421. ``regex`` and ``iregex`` query operators. You will also need at least
  422. version 4.3.1 of the `cx_Oracle`_ Python driver.
  423. Note that due to a Unicode-corruption bug in ``cx_Oracle`` 5.0, that
  424. version of the driver should **not** be used with Django;
  425. ``cx_Oracle`` 5.0.1 resolved this issue, so if you'd like to use a
  426. more recent ``cx_Oracle``, use version 5.0.1.
  427. ``cx_Oracle`` 5.0.1 or greater can optionally be compiled with the
  428. ``WITH_UNICODE`` environment variable. This is recommended but not
  429. required.
  430. .. _`Oracle Database Server`: http://www.oracle.com/
  431. .. _`cx_Oracle`: http://cx-oracle.sourceforge.net/
  432. In order for the ``python manage.py syncdb`` command to work, your Oracle
  433. database user must have privileges to run the following commands:
  434. * CREATE TABLE
  435. * CREATE SEQUENCE
  436. * CREATE PROCEDURE
  437. * CREATE TRIGGER
  438. To run Django's test suite, the user needs these *additional* privileges:
  439. * CREATE USER
  440. * DROP USER
  441. * CREATE TABLESPACE
  442. * DROP TABLESPACE
  443. * CONNECT WITH ADMIN OPTION
  444. * RESOURCE WITH ADMIN OPTION
  445. Connecting to the database
  446. --------------------------
  447. Your Django settings.py file should look something like this for Oracle::
  448. DATABASES = {
  449. 'default': {
  450. 'ENGINE': 'django.db.backends.oracle',
  451. 'NAME': 'xe',
  452. 'USER': 'a_user',
  453. 'PASSWORD': 'a_password',
  454. 'HOST': '',
  455. 'PORT': '',
  456. }
  457. }
  458. If you don't use a ``tnsnames.ora`` file or a similar naming method that
  459. recognizes the SID ("xe" in this example), then fill in both
  460. :setting:`HOST` and :setting:`PORT` like so::
  461. DATABASES = {
  462. 'default': {
  463. 'ENGINE': 'django.db.backends.oracle',
  464. 'NAME': 'xe',
  465. 'USER': 'a_user',
  466. 'PASSWORD': 'a_password',
  467. 'HOST': 'dbprod01ned.mycompany.com',
  468. 'PORT': '1540',
  469. }
  470. }
  471. You should supply both :setting:`HOST` and :setting:`PORT`, or leave both
  472. as empty strings.
  473. Threaded option
  474. ----------------
  475. If you plan to run Django in a multithreaded environment (e.g. Apache in Windows
  476. using the default MPM module), then you **must** set the ``threaded`` option of
  477. your Oracle database configuration to True::
  478. 'OPTIONS': {
  479. 'threaded': True,
  480. },
  481. Failure to do this may result in crashes and other odd behavior.
  482. INSERT ... RETURNING INTO
  483. -------------------------
  484. By default, the Oracle backend uses a ``RETURNING INTO`` clause to efficiently
  485. retrieve the value of an ``AutoField`` when inserting new rows. This behavior
  486. may result in a ``DatabaseError`` in certain unusual setups, such as when
  487. inserting into a remote table, or into a view with an ``INSTEAD OF`` trigger.
  488. The ``RETURNING INTO`` clause can be disabled by setting the
  489. ``use_returning_into`` option of the database configuration to False::
  490. 'OPTIONS': {
  491. 'use_returning_into': False,
  492. },
  493. In this case, the Oracle backend will use a separate ``SELECT`` query to
  494. retrieve AutoField values.
  495. Naming issues
  496. -------------
  497. Oracle imposes a name length limit of 30 characters. To accommodate this, the
  498. backend truncates database identifiers to fit, replacing the final four
  499. characters of the truncated name with a repeatable MD5 hash value.
  500. When running syncdb, an ``ORA-06552`` error may be encountered if
  501. certain Oracle keywords are used as the name of a model field or the
  502. value of a ``db_column`` option. Django quotes all identifiers used
  503. in queries to prevent most such problems, but this error can still
  504. occur when an Oracle datatype is used as a column name. In
  505. particular, take care to avoid using the names ``date``,
  506. ``timestamp``, ``number`` or ``float`` as a field name.
  507. NULL and empty strings
  508. ----------------------
  509. Django generally prefers to use the empty string ('') rather than
  510. NULL, but Oracle treats both identically. To get around this, the
  511. Oracle backend coerces the ``null=True`` option on fields that have
  512. the empty string as a possible value. When fetching from the database,
  513. it is assumed that a NULL value in one of these fields really means
  514. the empty string, and the data is silently converted to reflect this
  515. assumption.
  516. ``TextField`` limitations
  517. -------------------------
  518. The Oracle backend stores ``TextFields`` as ``NCLOB`` columns. Oracle imposes
  519. some limitations on the usage of such LOB columns in general:
  520. * LOB columns may not be used as primary keys.
  521. * LOB columns may not be used in indexes.
  522. * LOB columns may not be used in a ``SELECT DISTINCT`` list. This means that
  523. attempting to use the ``QuerySet.distinct`` method on a model that
  524. includes ``TextField`` columns will result in an error when run against
  525. Oracle. As a workaround, use the ``QuerySet.defer`` method in conjunction
  526. with ``distinct()`` to prevent ``TextField`` columns from being included in
  527. the ``SELECT DISTINCT`` list.
  528. .. _third-party-notes:
  529. Using a 3rd-party database backend
  530. ==================================
  531. In addition to the officially supported databases, there are backends provided
  532. by 3rd parties that allow you to use other databases with Django:
  533. * `Sybase SQL Anywhere`_
  534. * `IBM DB2`_
  535. * `Microsoft SQL Server 2005`_
  536. * Firebird_
  537. * ODBC_
  538. * ADSDB_
  539. The Django versions and ORM features supported by these unofficial backends
  540. vary considerably. Queries regarding the specific capabilities of these
  541. unofficial backends, along with any support queries, should be directed to
  542. the support channels provided by each 3rd party project.
  543. .. _Sybase SQL Anywhere: http://code.google.com/p/sqlany-django/
  544. .. _IBM DB2: http://code.google.com/p/ibm-db/
  545. .. _Microsoft SQL Server 2005: http://code.google.com/p/django-mssql/
  546. .. _Firebird: http://code.google.com/p/django-firebird/
  547. .. _ODBC: http://code.google.com/p/django-pyodbc/
  548. .. _ADSDB: http://code.google.com/p/adsdb-django/