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