databases.txt 27 KB

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