databases.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. .. _ref-databases:
  2. ===============================
  3. Notes about supported databases
  4. ===============================
  5. Django attempts to support as many features as possible on all database
  6. backends. However, not all database backends are alike, and we've had to make
  7. design decisions on which features to support and which assumptions we can make
  8. safely.
  9. This file describes some of the features that might be relevant to Django
  10. usage. Of course, it is not intended as a replacement for server-specific
  11. documentation or reference manuals.
  12. .. _mysql-notes:
  13. MySQL notes
  14. ===========
  15. Django expects the database to support transactions, referential integrity,
  16. and Unicode support (UTF-8 encoding). Fortunately, MySQL_ has all these
  17. features as available as far back as 3.23. While it may be possible to use
  18. 3.23 or 4.0, you'll probably have less trouble if you use 4.1 or 5.0.
  19. MySQL 4.1
  20. ---------
  21. `MySQL 4.1`_ has greatly improved support for character sets. It is possible to
  22. set different default character sets on the database, table, and column.
  23. Previous versions have only a server-wide character set setting. It's also the
  24. first version where the character set can be changed on the fly. 4.1 also has
  25. support for views, but Django currently doesn't use views.
  26. MySQL 5.0
  27. ---------
  28. `MySQL 5.0`_ adds the ``information_schema`` database, which contains detailed
  29. data on all database schema. Django's ``inspectdb`` feature uses this
  30. ``information_schema`` if it's available. 5.0 also has support for stored
  31. procedures, but Django currently doesn't use stored procedures.
  32. .. _MySQL: http://www.mysql.com/
  33. .. _MySQL 4.1: http://dev.mysql.com/doc/refman/4.1/en/index.html
  34. .. _MySQL 5.0: http://dev.mysql.com/doc/refman/5.0/en/index.html
  35. Storage engines
  36. ---------------
  37. MySQL has several `storage engines`_ (previously called table types). You can
  38. change the default storage engine in the server configuration.
  39. The default engine is MyISAM_ [#]_. The main drawback of MyISAM is that it
  40. doesn't currently support transactions or foreign keys. On the plus side, it's
  41. currently the only engine that supports full-text indexing and searching.
  42. The InnoDB_ engine is fully transactional and supports foreign key references.
  43. The BDB_ engine, like InnoDB, is also fully transactional and supports foreign
  44. key references. However, its use seems to be deprecated.
  45. `Other storage engines`_, including SolidDB_ and Falcon_, are on the horizon.
  46. For now, InnoDB is probably your best choice.
  47. .. _storage engines: http://dev.mysql.com/doc/refman/5.0/en/storage-engines.html
  48. .. _MyISAM: http://dev.mysql.com/doc/refman/5.0/en/myisam-storage-engine.html
  49. .. _BDB: http://dev.mysql.com/doc/refman/5.0/en/bdb-storage-engine.html
  50. .. _InnoDB: http://dev.mysql.com/doc/refman/5.0/en/innodb.html
  51. .. _Other storage engines: http://dev.mysql.com/doc/refman/5.1/en/storage-engines-other.html
  52. .. _SolidDB: http://forge.mysql.com/projects/project.php?id=139
  53. .. _Falcon: http://dev.mysql.com/doc/falcon/en/index.html
  54. .. [#] Unless this was changed by the packager of your MySQL package. We've
  55. had reports that the Windows Community Server installer sets up InnoDB as
  56. the default storage engine, for example.
  57. MySQLdb
  58. -------
  59. `MySQLdb`_ is the Python interface to MySQL. Version 1.2.1p2 or later is
  60. required for full MySQL support in Django.
  61. .. note::
  62. If you see ``ImportError: cannot import name ImmutableSet`` when trying to
  63. use Django, your MySQLdb installation may contain an outdated ``sets.py``
  64. file that conflicts with the built-in module of the same name from Python
  65. 2.4 and later. To fix this, verify that you have installed MySQLdb version
  66. 1.2.1p2 or newer, then delete the ``sets.py`` file in the MySQLdb
  67. directory that was left by an earlier version.
  68. .. _MySQLdb: http://sourceforge.net/projects/mysql-python
  69. Creating your database
  70. ----------------------
  71. You can `create your database`_ using the command-line tools and this SQL::
  72. CREATE DATABASE <dbname> CHARACTER SET utf8;
  73. This ensures all tables and columns will use UTF-8 by default.
  74. .. _create your database: http://dev.mysql.com/doc/refman/5.0/en/create-database.html
  75. .. _mysql-collation:
  76. Collation settings
  77. ~~~~~~~~~~~~~~~~~~
  78. The collation setting for a column controls the order in which data is sorted
  79. as well as what strings compare as equal. It can be set on a database-wide
  80. level and also per-table and per-column. This is `documented thoroughly`_ in
  81. the MySQL documentation. In all cases, you set the collation by directly
  82. manipulating the database tables; Django doesn't provide a way to set this on
  83. the model definition.
  84. .. _documented thoroughly: http://dev.mysql.com/doc/refman/5.0/en/charset.html
  85. By default, with a UTF-8 database, MySQL will use the
  86. ``utf8_general_ci_swedish`` collation. This results in all string equality
  87. comparisons being done in a *case-insensitive* manner. That is, ``"Fred"`` and
  88. ``"freD"`` are considered equal at the database level. If you have a unique
  89. constraint on a field, it would be illegal to try to insert both ``"aa"`` and
  90. ``"AA"`` into the same column, since they compare as equal (and, hence,
  91. non-unique) with the default collation.
  92. In many cases, this default will not be a problem. However, if you really want
  93. case-sensitive comparisons on a particular column or table, you would change
  94. the column or table to use the ``utf8_bin`` collation. The main thing to be
  95. aware of in this case is that if you are using MySQLdb 1.2.2, the database backend in Django will then return
  96. bytestrings (instead of unicode strings) for any character fields it returns
  97. receive from the database. This is a strong variation from Django's normal
  98. practice of *always* returning unicode strings. It is up to you, the
  99. developer, to handle the fact that you will receive bytestrings if you
  100. configure your table(s) to use ``utf8_bin`` collation. Django itself should work
  101. smoothly with such columns, but if your code must be prepared to call
  102. ``django.utils.encoding.smart_unicode()`` at times if it really wants to work
  103. with consistent data -- Django will not do this for you (the database backend
  104. layer and the model population layer are separated internally so the database
  105. layer doesn't know it needs to make this conversion in this one particular
  106. case).
  107. If you're using MySQLdb 1.2.1p2, Django's standard
  108. :class:`~django.db.models.CharField` class will return unicode strings even
  109. with ``utf8_bin`` collation. However, :class:`~django.db.models.TextField`
  110. fields will be returned as an ``array.array`` instance (from Python's standard
  111. ``array`` module). There isn't a lot Django can do about that, since, again,
  112. the information needed to make the necessary conversions isn't available when
  113. the data is read in from the database. This problem was `fixed in MySQLdb
  114. 1.2.2`_, so if you want to use :class:`~django.db.models.TextField` with
  115. ``utf8_bin`` collation, upgrading to version 1.2.2 and then dealing with the
  116. bytestrings (which shouldn't be too difficult) is the recommended solution.
  117. Should you decide to use ``utf8_bin`` collation for some of your tables with
  118. MySQLdb 1.2.1p2, you should still use ``utf8_collation_ci_swedish`` (the
  119. default) collation for the :class:`django.contrib.sessions.models.Session`
  120. table (usually called ``django_session`` and the table
  121. :class:`django.contrib.admin.models.LogEntry` table (usually called
  122. ``django_admin_log``). Those are the two standard tables that use
  123. :class:`~django.db.model.TextField` internally.
  124. .. _fixed in MySQLdb 1.2.2: http://sourceforge.net/tracker/index.php?func=detail&aid=1495765&group_id=22307&atid=374932
  125. Connecting to the database
  126. --------------------------
  127. Refer to the :ref:`settings documentation <ref-settings>`.
  128. Connection settings are used in this order:
  129. 1. :setting:`DATABASE_OPTIONS`.
  130. 2. :setting:`DATABASE_NAME`, :setting:`DATABASE_USER`,
  131. :setting:`DATABASE_PASSWORD`, :setting:`DATABASE_HOST`,
  132. :setting:`DATABASE_PORT`
  133. 3. MySQL option files.
  134. In other words, if you set the name of the database in ``DATABASE_OPTIONS``,
  135. this will take precedence over ``DATABASE_NAME``, which would override
  136. anything in a `MySQL option file`_.
  137. Here's a sample configuration which uses a MySQL option file::
  138. # settings.py
  139. DATABASE_ENGINE = "mysql"
  140. DATABASE_OPTIONS = {
  141. 'read_default_file': '/path/to/my.cnf',
  142. }
  143. # my.cnf
  144. [client]
  145. database = DATABASE_NAME
  146. user = DATABASE_USER
  147. password = DATABASE_PASSWORD
  148. default-character-set = utf8
  149. Several other MySQLdb connection options may be useful, such as ``ssl``,
  150. ``use_unicode``, ``init_command``, and ``sql_mode``. Consult the
  151. `MySQLdb documentation`_ for more details.
  152. .. _MySQL option file: http://dev.mysql.com/doc/refman/5.0/en/option-files.html
  153. .. _MySQLdb documentation: http://mysql-python.sourceforge.net/
  154. Creating your tables
  155. --------------------
  156. When Django generates the schema, it doesn't specify a storage engine, so
  157. tables will be created with whatever default storage engine your database
  158. server is configured for. The easiest solution is to set your database server's
  159. default storage engine to the desired engine.
  160. If you're using a hosting service and can't change your server's default
  161. storage engine, you have a couple of options.
  162. * After the tables are created, execute an ``ALTER TABLE`` statement to
  163. convert a table to a new storage engine (such as InnoDB)::
  164. ALTER TABLE <tablename> ENGINE=INNODB;
  165. This can be tedious if you have a lot of tables.
  166. * Another option is to use the ``init_command`` option for MySQLdb prior to
  167. creating your tables::
  168. DATABASE_OPTIONS = {
  169. # ...
  170. "init_command": "SET storage_engine=INNODB",
  171. # ...
  172. }
  173. This sets the default storage engine upon connecting to the database.
  174. After your tables have been created, you should remove this option.
  175. * Another method for changing the storage engine is described in
  176. AlterModelOnSyncDB_.
  177. .. _AlterModelOnSyncDB: http://code.djangoproject.com/wiki/AlterModelOnSyncDB
  178. Boolean fields in Django
  179. -------------------------
  180. Since MySQL doesn't have a direct ``BOOLEAN`` column type, Django uses a
  181. ``TINYINT`` column with values of ``1`` and ``0`` to store values for the
  182. :class:`~django.db.models.BooleanField` model field. Refer to the documentation
  183. of that field for more details, but usually this won't be something that will
  184. matter unless you're printing out the field values and are expecting to see
  185. ``True`` and ``False.``.
  186. .. _sqlite-notes:
  187. SQLite notes
  188. ============
  189. Versions of SQLite 3.3.5 and older `contain a bug`_ when handling ``ORDER BY``
  190. parameters. This can cause problems when you use the ``select`` parameter for
  191. the ``extra()`` QuerySet method. The bug can be identified by the error message
  192. ``OperationalError: ORDER BY terms must not be non-integer constants``. The
  193. problem can be solved updating SQLite to version 3.3.6 or newer, possibly also
  194. updating the ``pysqlite2`` Python module in the process.
  195. .. _contain a bug: http://www.sqlite.org/cvstrac/tktview?tn=1768
  196. This has a very low impact because 3.3.6 was released in April 2006, so most
  197. current binary distributions for different platforms include newer version of
  198. SQLite usable from Python through either the ``pysqlite2`` or the ``sqlite3``
  199. modules.
  200. However, in the case of Windows, the official binary distribution of the stable
  201. release of Python 2.5 (2.5.2, as of this writing) includes SQLite 3.3.4, so the bug can
  202. make itself evident in that platform. There are (as of Django 1.0) even three
  203. tests in the Django test suite that will fail when run under this setup. As
  204. described above, this can be solved by downloading and installing a newer
  205. version of ``pysqlite2`` (``pysqlite-2.x.x.win32-py2.5.exe``) that includes and
  206. uses a newer version of SQLite. Python 2.6 ships with a newer version of
  207. SQLite and is not affected by this issue.
  208. If you are in such platform and find yourself in the need to update
  209. ``pysqlite``/SQLite, you will also need to manually modify the
  210. ``django/db/backends/sqlite3/base.py`` file in the Django source tree so it
  211. attempts to import ``pysqlite2`` before than ``sqlite3`` and so it can take
  212. advantage of the new ``pysqlite2``/SQLite versions.
  213. .. _oracle-notes:
  214. Oracle notes
  215. ============
  216. Django supports `Oracle Database Server`_ versions 9i and higher. Oracle
  217. version 10g or later is required to use Django's ``regex`` and ``iregex`` query
  218. operators. You will also need the `cx_Oracle`_ driver, version 4.3.1 or newer.
  219. .. _`Oracle Database Server`: http://www.oracle.com/
  220. .. _`cx_Oracle`: http://cx-oracle.sourceforge.net/
  221. In order for the ``python manage.py syncdb`` command to work, your Oracle
  222. database user must have privileges to run the following commands:
  223. * CREATE TABLE
  224. * CREATE SEQUENCE
  225. * CREATE PROCEDURE
  226. * CREATE TRIGGER
  227. To run Django's test suite, the user needs these *additional* privileges:
  228. * CREATE USER
  229. * DROP USER
  230. * CREATE TABLESPACE
  231. * DROP TABLESPACE
  232. Connecting to the database
  233. --------------------------
  234. Your Django settings.py file should look something like this for Oracle::
  235. DATABASE_ENGINE = 'oracle'
  236. DATABASE_NAME = 'xe'
  237. DATABASE_USER = 'a_user'
  238. DATABASE_PASSWORD = 'a_password'
  239. DATABASE_HOST = ''
  240. DATABASE_PORT = ''
  241. If you don't use a ``tnsnames.ora`` file or a similar naming method that
  242. recognizes the SID ("xe" in this example), then fill in both
  243. :setting:`DATABASE_HOST` and :setting:`DATABASE_PORT` like so::
  244. DATABASE_ENGINE = 'oracle'
  245. DATABASE_NAME = 'xe'
  246. DATABASE_USER = 'a_user'
  247. DATABASE_PASSWORD = 'a_password'
  248. DATABASE_HOST = 'dbprod01ned.mycompany.com'
  249. DATABASE_PORT = '1540'
  250. You should supply both :setting:`DATABASE_HOST` and :setting:`DATABASE_PORT`, or leave both
  251. as empty strings.
  252. Tablespace options
  253. ------------------
  254. A common paradigm for optimizing performance in Oracle-based systems is the
  255. use of `tablespaces`_ to organize disk layout. The Oracle backend supports
  256. this use case by adding ``db_tablespace`` options to the ``Meta`` and
  257. ``Field`` classes. (When you use a backend that lacks support for tablespaces,
  258. Django ignores these options.)
  259. .. _`tablespaces`: http://en.wikipedia.org/wiki/Tablespace
  260. A tablespace can be specified for the table(s) generated by a model by
  261. supplying the ``db_tablespace`` option inside the model's ``class Meta``.
  262. Additionally, you can pass the ``db_tablespace`` option to a ``Field``
  263. constructor to specify an alternate tablespace for the ``Field``'s column
  264. index. If no index would be created for the column, the ``db_tablespace``
  265. option is ignored::
  266. class TablespaceExample(models.Model):
  267. name = models.CharField(max_length=30, db_index=True, db_tablespace="indexes")
  268. data = models.CharField(max_length=255, db_index=True)
  269. edges = models.ManyToManyField(to="self", db_tablespace="indexes")
  270. class Meta:
  271. db_tablespace = "tables"
  272. In this example, the tables generated by the ``TablespaceExample`` model
  273. (i.e., the model table and the many-to-many table) would be stored in the
  274. ``tables`` tablespace. The index for the name field and the indexes on the
  275. many-to-many table would be stored in the ``indexes`` tablespace. The ``data``
  276. field would also generate an index, but no tablespace for it is specified, so
  277. it would be stored in the model tablespace ``tables`` by default.
  278. .. versionadded:: 1.0
  279. Use the :setting:`DEFAULT_TABLESPACE` and :setting:`DEFAULT_INDEX_TABLESPACE`
  280. settings to specify default values for the db_tablespace options.
  281. These are useful for setting a tablespace for the built-in Django apps and
  282. other applications whose code you cannot control.
  283. Django does not create the tablespaces for you. Please refer to `Oracle's
  284. documentation`_ for details on creating and managing tablespaces.
  285. .. _`Oracle's documentation`: http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_7003.htm#SQLRF01403
  286. Naming issues
  287. -------------
  288. Oracle imposes a name length limit of 30 characters. To accommodate this, the
  289. backend truncates database identifiers to fit, replacing the final four
  290. characters of the truncated name with a repeatable MD5 hash value.
  291. NULL and empty strings
  292. ----------------------
  293. Django generally prefers to use the empty string ('') rather than NULL, but
  294. Oracle treats both identically. To get around this, the Oracle backend
  295. coerces the ``null=True`` option on fields that permit the empty string as a
  296. value. When fetching from the database, it is assumed that a NULL value in
  297. one of these fields really means the empty string, and the data is silently
  298. converted to reflect this assumption.
  299. ``TextField`` limitations
  300. -------------------------
  301. The Oracle backend stores ``TextFields`` as ``NCLOB`` columns. Oracle imposes
  302. some limitations on the usage of such LOB columns in general:
  303. * LOB columns may not be used as primary keys.
  304. * LOB columns may not be used in indexes.
  305. * LOB columns may not be used in a ``SELECT DISTINCT`` list. This means that
  306. attempting to use the ``QuerySet.distinct`` method on a model that
  307. includes ``TextField`` columns will result in an error when run against
  308. Oracle. A workaround to this is to keep ``TextField`` columns out of any
  309. models that you foresee performing ``distinct()`` queries on, and to
  310. include the ``TextField`` in a related model instead.