PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/ref/databases.txt

https://code.google.com/p/mango-py/
Plain Text | 709 lines | 534 code | 175 blank | 0 comment | 0 complexity | 69238af3e110def7dd2f6f0336eacbfe MD5 | raw file
Possible License(s): BSD-3-Clause
  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 :setting:`OPTIONS`,
  204. this will take precedence over :setting:`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. .. _sqlite-notes:
  274. SQLite notes
  275. ============
  276. SQLite_ provides an excellent development alternative for applications that
  277. are predominantly read-only or require a smaller installation footprint. As
  278. with all database servers, though, there are some differences that are
  279. specific to SQLite that you should be aware of.
  280. .. _SQLite: http://www.sqlite.org/
  281. .. _sqlite-string-matching:
  282. String matching for non-ASCII strings
  283. --------------------------------------
  284. SQLite doesn't support case-insensitive matching for non-ASCII strings. Some
  285. possible workarounds for this are `documented at sqlite.org`_, but they are
  286. not utilised by the default SQLite backend in Django. Therefore, if you are
  287. using the ``iexact`` lookup type in your queryset filters, be aware that it
  288. will not work as expected for non-ASCII strings.
  289. .. _documented at sqlite.org: http://www.sqlite.org/faq.html#q18
  290. SQLite 3.3.6 or newer strongly recommended
  291. ------------------------------------------
  292. Versions of SQLite 3.3.5 and older contains the following bugs:
  293. * A bug when `handling`_ ``ORDER BY`` parameters. This can cause problems when
  294. you use the ``select`` parameter for the ``extra()`` QuerySet method. The bug
  295. can be identified by the error message ``OperationalError: ORDER BY terms
  296. must not be non-integer constants``.
  297. * A bug when handling `aggregation`_ together with DateFields and
  298. DecimalFields.
  299. .. _handling: http://www.sqlite.org/cvstrac/tktview?tn=1768
  300. .. _aggregation: http://code.djangoproject.com/ticket/10031
  301. SQLite 3.3.6 was released in April 2006, so most current binary distributions
  302. for different platforms include newer version of SQLite usable from Python
  303. through either the ``pysqlite2`` or the ``sqlite3`` modules.
  304. However, some platform/Python version combinations include older versions of
  305. SQLite (e.g. the official binary distribution of Python 2.5 for Windows, 2.5.4
  306. as of this writing, includes SQLite 3.3.4). There are (as of Django 1.1) even
  307. some tests in the Django test suite that will fail when run under this setup.
  308. As described :ref:`below<using-newer-versions-of-pysqlite>`, this can be solved
  309. by downloading and installing a newer version of ``pysqlite2``
  310. (``pysqlite-2.x.x.win32-py2.5.exe`` in the described case) that includes and
  311. uses a newer version of SQLite. Python 2.6 for Windows ships with a version of
  312. SQLite that is not affected by these issues.
  313. Version 3.5.9
  314. -------------
  315. The Ubuntu "Intrepid Ibex" (8.10) SQLite 3.5.9-3 package contains a bug that
  316. causes problems with the evaluation of query expressions. If you are using
  317. Ubuntu "Intrepid Ibex", you will need to update the package to version
  318. 3.5.9-3ubuntu1 or newer (recommended) or find an alternate source for SQLite
  319. packages, or install SQLite from source.
  320. At one time, Debian Lenny shipped with the same malfunctioning SQLite 3.5.9-3
  321. package. However the Debian project has subsequently issued updated versions
  322. of the SQLite package that correct these bugs. If you find you are getting
  323. unexpected results under Debian, ensure you have updated your SQLite package
  324. to 3.5.9-5 or later.
  325. The problem does not appear to exist with other versions of SQLite packaged
  326. with other operating systems.
  327. Version 3.6.2
  328. --------------
  329. SQLite version 3.6.2 (released August 30, 2008) introduced a bug into ``SELECT
  330. DISTINCT`` handling that is triggered by, amongst other things, Django's
  331. ``DateQuerySet`` (returned by the ``dates()`` method on a queryset).
  332. You should avoid using this version of SQLite with Django. Either upgrade to
  333. 3.6.3 (released September 22, 2008) or later, or downgrade to an earlier
  334. version of SQLite.
  335. .. _using-newer-versions-of-pysqlite:
  336. Using newer versions of the SQLite DB-API 2.0 driver
  337. ----------------------------------------------------
  338. For versions of Python 2.5 or newer that include ``sqlite3`` in the standard
  339. library Django will now use a ``pysqlite2`` interface in preference to
  340. ``sqlite3`` if it finds one is available.
  341. This provides the ability to upgrade both the DB-API 2.0 interface or SQLite 3
  342. itself to versions newer than the ones included with your particular Python
  343. binary distribution, if needed.
  344. "Database is locked" errors
  345. -----------------------------------------------
  346. SQLite is meant to be a lightweight database, and thus can't support a high
  347. level of concurrency. ``OperationalError: database is locked`` errors indicate
  348. that your application is experiencing more concurrency than ``sqlite`` can
  349. handle in default configuration. This error means that one thread or process has
  350. an exclusive lock on the database connection and another thread timed out
  351. waiting for the lock the be released.
  352. Python's SQLite wrapper has
  353. a default timeout value that determines how long the second thread is allowed to
  354. wait on the lock before it times out and raises the ``OperationalError: database
  355. is locked`` error.
  356. If you're getting this error, you can solve it by:
  357. * Switching to another database backend. At a certain point SQLite becomes
  358. too "lite" for real-world applications, and these sorts of concurrency
  359. errors indicate you've reached that point.
  360. * Rewriting your code to reduce concurrency and ensure that database
  361. transactions are short-lived.
  362. * Increase the default timeout value by setting the ``timeout`` database
  363. option option::
  364. 'OPTIONS': {
  365. # ...
  366. 'timeout': 20,
  367. # ...
  368. }
  369. This will simply make SQLite wait a bit longer before throwing "database
  370. is locked" errors; it won't really do anything to solve them.
  371. .. _oracle-notes:
  372. Oracle notes
  373. ============
  374. Django supports `Oracle Database Server`_ versions 9i and
  375. higher. Oracle version 10g or later is required to use Django's
  376. ``regex`` and ``iregex`` query operators. You will also need at least
  377. version 4.3.1 of the `cx_Oracle`_ Python driver.
  378. Note that due to a Unicode-corruption bug in ``cx_Oracle`` 5.0, that
  379. version of the driver should **not** be used with Django;
  380. ``cx_Oracle`` 5.0.1 resolved this issue, so if you'd like to use a
  381. more recent ``cx_Oracle``, use version 5.0.1.
  382. ``cx_Oracle`` 5.0.1 or greater can optionally be compiled with the
  383. ``WITH_UNICODE`` environment variable. This is recommended but not
  384. required.
  385. .. _`Oracle Database Server`: http://www.oracle.com/
  386. .. _`cx_Oracle`: http://cx-oracle.sourceforge.net/
  387. In order for the ``python manage.py syncdb`` command to work, your Oracle
  388. database user must have privileges to run the following commands:
  389. * CREATE TABLE
  390. * CREATE SEQUENCE
  391. * CREATE PROCEDURE
  392. * CREATE TRIGGER
  393. To run Django's test suite, the user needs these *additional* privileges:
  394. * CREATE USER
  395. * DROP USER
  396. * CREATE TABLESPACE
  397. * DROP TABLESPACE
  398. * CONNECT WITH ADMIN OPTION
  399. * RESOURCE WITH ADMIN OPTION
  400. Connecting to the database
  401. --------------------------
  402. Your Django settings.py file should look something like this for Oracle::
  403. DATABASES = {
  404. 'default': {
  405. 'ENGINE': 'django.db.backends.oracle',
  406. 'NAME': 'xe',
  407. 'USER': 'a_user',
  408. 'PASSWORD': 'a_password',
  409. 'HOST': '',
  410. 'PORT': '',
  411. }
  412. }
  413. If you don't use a ``tnsnames.ora`` file or a similar naming method that
  414. recognizes the SID ("xe" in this example), then fill in both
  415. :setting:`HOST` and :setting:`PORT` like so::
  416. DATABASES = {
  417. 'default': {
  418. 'ENGINE': 'django.db.backends.oracle',
  419. 'NAME': 'xe',
  420. 'USER': 'a_user',
  421. 'PASSWORD': 'a_password',
  422. 'HOST': 'dbprod01ned.mycompany.com',
  423. 'PORT': '1540',
  424. }
  425. }
  426. You should supply both :setting:`HOST` and :setting:`PORT`, or leave both
  427. as empty strings.
  428. Threaded option
  429. ----------------
  430. If you plan to run Django in a multithreaded environment (e.g. Apache in Windows
  431. using the default MPM module), then you **must** set the ``threaded`` option of
  432. your Oracle database configuration to True::
  433. 'OPTIONS': {
  434. 'threaded': True,
  435. },
  436. Failure to do this may result in crashes and other odd behavior.
  437. INSERT ... RETURNING INTO
  438. -------------------------
  439. By default, the Oracle backend uses a ``RETURNING INTO`` clause to efficiently
  440. retrieve the value of an ``AutoField`` when inserting new rows. This behavior
  441. may result in a ``DatabaseError`` in certain unusual setups, such as when
  442. inserting into a remote table, or into a view with an ``INSTEAD OF`` trigger.
  443. The ``RETURNING INTO`` clause can be disabled by setting the
  444. ``use_returning_into`` option of the database configuration to False::
  445. 'OPTIONS': {
  446. 'use_returning_into': False,
  447. },
  448. In this case, the Oracle backend will use a separate ``SELECT`` query to
  449. retrieve AutoField values.
  450. Tablespace options
  451. ------------------
  452. A common paradigm for optimizing performance in Oracle-based systems is the
  453. use of `tablespaces`_ to organize disk layout. The Oracle backend supports
  454. this use case by adding ``db_tablespace`` options to the ``Meta`` and
  455. ``Field`` classes. (When you use a backend that lacks support for tablespaces,
  456. Django ignores these options.)
  457. .. _`tablespaces`: http://en.wikipedia.org/wiki/Tablespace
  458. A tablespace can be specified for the table(s) generated by a model by
  459. supplying the ``db_tablespace`` option inside the model's ``class Meta``.
  460. Additionally, you can pass the ``db_tablespace`` option to a ``Field``
  461. constructor to specify an alternate tablespace for the ``Field``'s column
  462. index. If no index would be created for the column, the ``db_tablespace``
  463. option is ignored::
  464. class TablespaceExample(models.Model):
  465. name = models.CharField(max_length=30, db_index=True, db_tablespace="indexes")
  466. data = models.CharField(max_length=255, db_index=True)
  467. edges = models.ManyToManyField(to="self", db_tablespace="indexes")
  468. class Meta:
  469. db_tablespace = "tables"
  470. In this example, the tables generated by the ``TablespaceExample`` model
  471. (i.e., the model table and the many-to-many table) would be stored in the
  472. ``tables`` tablespace. The index for the name field and the indexes on the
  473. many-to-many table would be stored in the ``indexes`` tablespace. The ``data``
  474. field would also generate an index, but no tablespace for it is specified, so
  475. it would be stored in the model tablespace ``tables`` by default.
  476. Use the :setting:`DEFAULT_TABLESPACE` and :setting:`DEFAULT_INDEX_TABLESPACE`
  477. settings to specify default values for the db_tablespace options.
  478. These are useful for setting a tablespace for the built-in Django apps and
  479. other applications whose code you cannot control.
  480. Django does not create the tablespaces for you. Please refer to `Oracle's
  481. documentation`_ for details on creating and managing tablespaces.
  482. .. _`Oracle's documentation`: http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_7003.htm#SQLRF01403
  483. Naming issues
  484. -------------
  485. Oracle imposes a name length limit of 30 characters. To accommodate this, the
  486. backend truncates database identifiers to fit, replacing the final four
  487. characters of the truncated name with a repeatable MD5 hash value.
  488. When running syncdb, an ``ORA-06552`` error may be encountered if
  489. certain Oracle keywords are used as the name of a model field or the
  490. value of a ``db_column`` option. Django quotes all identifiers used
  491. in queries to prevent most such problems, but this error can still
  492. occur when an Oracle datatype is used as a column name. In
  493. particular, take care to avoid using the names ``date``,
  494. ``timestamp``, ``number`` or ``float`` as a field name.
  495. NULL and empty strings
  496. ----------------------
  497. Django generally prefers to use the empty string ('') rather than
  498. NULL, but Oracle treats both identically. To get around this, the
  499. Oracle backend coerces the ``null=True`` option on fields that have
  500. the empty string as a possible value. When fetching from the database,
  501. it is assumed that a NULL value in one of these fields really means
  502. the empty string, and the data is silently converted to reflect this
  503. assumption.
  504. ``TextField`` limitations
  505. -------------------------
  506. The Oracle backend stores ``TextFields`` as ``NCLOB`` columns. Oracle imposes
  507. some limitations on the usage of such LOB columns in general:
  508. * LOB columns may not be used as primary keys.
  509. * LOB columns may not be used in indexes.
  510. * LOB columns may not be used in a ``SELECT DISTINCT`` list. This means that
  511. attempting to use the ``QuerySet.distinct`` method on a model that
  512. includes ``TextField`` columns will result in an error when run against
  513. Oracle. As a workaround, use the ``QuerySet.defer`` method in conjunction
  514. with ``distinct()`` to prevent ``TextField`` columns from being included in
  515. the ``SELECT DISTINCT`` list.
  516. .. _third-party-notes:
  517. Using a 3rd-party database backend
  518. ==================================
  519. In addition to the officially supported databases, there are backends provided
  520. by 3rd parties that allow you to use other databases with Django:
  521. * `Sybase SQL Anywhere`_
  522. * `IBM DB2`_
  523. * `Microsoft SQL Server 2005`_
  524. * Firebird_
  525. * ODBC_
  526. The Django versions and ORM features supported by these unofficial backends
  527. vary considerably. Queries regarding the specific capabilities of these
  528. unofficial backends, along with any support queries, should be directed to
  529. the support channels provided by each 3rd party project.
  530. .. _Sybase SQL Anywhere: http://code.google.com/p/sqlany-django/
  531. .. _IBM DB2: http://code.google.com/p/ibm-db/
  532. .. _Microsoft SQL Server 2005: http://code.google.com/p/django-mssql/
  533. .. _Firebird: http://code.google.com/p/django-firebird/
  534. .. _ODBC: http://code.google.com/p/django-pyodbc/