databases.txt 29 KB

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