~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to docs/ref/databases.txt

  • Committer: Package Import Robot
  • Author(s): Luke Faraone
  • Date: 2013-11-07 15:33:49 UTC
  • mfrom: (1.3.12)
  • Revision ID: package-import@ubuntu.com-20131107153349-e31sc149l2szs3jb
Tags: 1.6-1
* New upstream version. Closes: #557474, #724637.
* python-django now also suggests the installation of ipython,
  bpython, python-django-doc, and libgdal1.
  Closes: #636511, #686333, #704203
* Set package maintainer to Debian Python Modules Team.
* Bump standards version to 3.9.5, no changes needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
usage. Of course, it is not intended as a replacement for server-specific
12
12
documentation or reference manuals.
13
13
 
 
14
General notes
 
15
=============
 
16
 
 
17
.. _persistent-database-connections:
 
18
 
 
19
Persistent connections
 
20
----------------------
 
21
 
 
22
.. versionadded:: 1.6
 
23
 
 
24
Persistent connections avoid the overhead of re-establishing a connection to
 
25
the database in each request. They're controlled by the
 
26
:setting:`CONN_MAX_AGE` parameter which defines the maximum lifetime of a
 
27
connection. It can be set independently for each database.
 
28
 
 
29
The default value is ``0``, preserving the historical behavior of closing the
 
30
database connection at the end of each request. To enable persistent
 
31
connections, set :setting:`CONN_MAX_AGE` to a positive number of seconds. For
 
32
unlimited persistent connections, set it to ``None``.
 
33
 
 
34
Connection management
 
35
~~~~~~~~~~~~~~~~~~~~~
 
36
 
 
37
Django opens a connection to the database when it first makes a database
 
38
query. It keeps this connection open and reuses it in subsequent requests.
 
39
Django closes the connection once it exceeds the maximum age defined by
 
40
:setting:`CONN_MAX_AGE` or when it isn't usable any longer.
 
41
 
 
42
In detail, Django automatically opens a connection to the database whenever it
 
43
needs one and doesn't have one already — either because this is the first
 
44
connection, or because the previous connection was closed.
 
45
 
 
46
At the beginning of each request, Django closes the connection if it has
 
47
reached its maximum age. If your database terminates idle connections after
 
48
some time, you should set :setting:`CONN_MAX_AGE` to a lower value, so that
 
49
Django doesn't attempt to use a connection that has been terminated by the
 
50
database server. (This problem may only affect very low traffic sites.)
 
51
 
 
52
At the end of each request, Django closes the connection if it has reached its
 
53
maximum age or if it is in an unrecoverable error state. If any database
 
54
errors have occurred while processing the requests, Django checks whether the
 
55
connection still works, and closes it if it doesn't. Thus, database errors
 
56
affect at most one request; if the connection becomes unusable, the next
 
57
request gets a fresh connection.
 
58
 
 
59
Caveats
 
60
~~~~~~~
 
61
 
 
62
Since each thread maintains its own connection, your database must support at
 
63
least as many simultaneous connections as you have worker threads.
 
64
 
 
65
Sometimes a database won't be accessed by the majority of your views, for
 
66
example because it's the database of an external system, or thanks to caching.
 
67
In such cases, you should set :setting:`CONN_MAX_AGE` to a low value or even
 
68
``0``, because it doesn't make sense to maintain a connection that's unlikely
 
69
to be reused. This will help keep the number of simultaneous connections to
 
70
this database small.
 
71
 
 
72
The development server creates a new thread for each request it handles,
 
73
negating the effect of persistent connections. Don't enable them during
 
74
development.
 
75
 
 
76
When Django establishes a connection to the database, it sets up appropriate
 
77
parameters, depending on the backend being used. If you enable persistent
 
78
connections, this setup is no longer repeated every request. If you modify
 
79
parameters such as the connection's isolation level or time zone, you should
 
80
either restore Django's defaults at the end of each request, force an
 
81
appropriate value at the beginning of each request, or disable persistent
 
82
connections.
 
83
 
14
84
.. _postgresql-notes:
15
85
 
16
86
PostgreSQL notes
17
87
================
18
88
 
19
 
.. versionchanged:: 1.4
20
 
 
21
 
Django supports PostgreSQL 8.2 and higher.
22
 
 
23
 
PostgreSQL 8.2 to 8.2.4
24
 
-----------------------
25
 
 
26
 
The implementation of the population statistics aggregates ``STDDEV_POP`` and
27
 
``VAR_POP`` that shipped with PostgreSQL 8.2 to 8.2.4 are `known to be
28
 
faulty`_. Users of these releases of PostgreSQL are advised to upgrade to
29
 
`Release 8.2.5`_ or later. Django will raise a ``NotImplementedError`` if you
30
 
attempt to use the ``StdDev(sample=False)`` or ``Variance(sample=False)``
31
 
aggregate with a database backend that falls within the affected release range.
32
 
 
33
 
.. _known to be faulty: http://archives.postgresql.org/pgsql-bugs/2007-07/msg00046.php
34
 
.. _Release 8.2.5: http://www.postgresql.org/docs/devel/static/release-8-2-5.html
 
89
Django supports PostgreSQL 8.4 and higher.
35
90
 
36
91
PostgreSQL connection settings
37
92
-------------------------------
44
99
Django needs the following parameters for its database connections:
45
100
 
46
101
- ``client_encoding``: ``'UTF8'``,
47
 
- ``default_transaction_isolation``: ``'read committed'``,
 
102
- ``default_transaction_isolation``: ``'read committed'`` by default,
 
103
  or the value set in the connection options (see below),
48
104
- ``timezone``: ``'UTC'`` when :setting:`USE_TZ` is ``True``, value of
49
105
  :setting:`TIME_ZONE` otherwise.
50
106
 
58
114
 
59
115
.. _ALTER ROLE: http://www.postgresql.org/docs/current/interactive/sql-alterrole.html
60
116
 
61
 
Transaction handling
62
 
---------------------
63
 
 
64
 
:doc:`By default </topics/db/transactions>`, Django runs with an open
65
 
transaction which it commits automatically when any built-in, data-altering
66
 
model function is called. The PostgreSQL backends normally operate the same as
67
 
any other Django backend in this respect.
68
 
 
69
117
.. _postgresql-autocommit-mode:
70
118
 
71
119
Autocommit mode
72
 
~~~~~~~~~~~~~~~
73
 
 
74
 
If your application is particularly read-heavy and doesn't make many
75
 
database writes, the overhead of a constantly open transaction can
76
 
sometimes be noticeable. For those situations, you can configure Django
77
 
to use *"autocommit"* behavior for the connection, meaning that each database
78
 
operation will normally be in its own transaction, rather than having
79
 
the transaction extend over multiple operations. In this case, you can
80
 
still manually start a transaction if you're doing something that
81
 
requires consistency across multiple database operations. The
82
 
autocommit behavior is enabled by setting the ``autocommit`` key in
83
 
the :setting:`OPTIONS` part of your database configuration in
84
 
:setting:`DATABASES`::
85
 
 
86
 
    'OPTIONS': {
87
 
        'autocommit': True,
88
 
    }
89
 
 
90
 
In this configuration, Django still ensures that :ref:`delete()
91
 
<topics-db-queries-delete>` and :ref:`update() <topics-db-queries-update>`
92
 
queries run inside a single transaction, so that either all the affected
93
 
objects are changed or none of them are.
94
 
 
95
 
.. admonition:: This is database-level autocommit
96
 
 
97
 
    This functionality is not the same as the :ref:`autocommit
98
 
    <topics-db-transactions-autocommit>` decorator. That decorator is
99
 
    a Django-level implementation that commits automatically after
100
 
    data changing operations. The feature enabled using the
101
 
    :setting:`OPTIONS` option provides autocommit behavior at the
102
 
    database adapter level. It commits after *every* operation.
103
 
 
104
 
If you are using this feature and performing an operation akin to delete or
105
 
updating that requires multiple operations, you are strongly recommended to
106
 
wrap you operations in manual transaction handling to ensure data consistency.
107
 
You should also audit your existing code for any instances of this behavior
108
 
before enabling this feature. It's faster, but it provides less automatic
109
 
protection for multi-call operations.
 
120
---------------
 
121
 
 
122
.. versionchanged:: 1.6
 
123
 
 
124
In previous versions of Django, database-level autocommit could be enabled by
 
125
setting the ``autocommit`` key in the :setting:`OPTIONS` part of your database
 
126
configuration in :setting:`DATABASES`::
 
127
 
 
128
    DATABASES = {
 
129
        # ...
 
130
        'OPTIONS': {
 
131
            'autocommit': True,
 
132
        },
 
133
    }
 
134
 
 
135
Since Django 1.6, autocommit is turned on by default. This configuration is
 
136
ignored and can be safely removed.
 
137
 
 
138
.. _database-isolation-level:
 
139
 
 
140
Isolation level
 
141
---------------
 
142
 
 
143
.. versionadded:: 1.6
 
144
 
 
145
Like PostgreSQL itself, Django defaults to the ``READ COMMITTED`` `isolation
 
146
level`_. If you need a higher isolation level such as ``REPEATABLE READ`` or
 
147
``SERIALIZABLE``, set it in the :setting:`OPTIONS` part of your database
 
148
configuration in :setting:`DATABASES`::
 
149
 
 
150
    import psycopg2.extensions
 
151
 
 
152
    DATABASES = {
 
153
        # ...
 
154
        'OPTIONS': {
 
155
            'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE,
 
156
        },
 
157
    }
 
158
 
 
159
.. note::
 
160
 
 
161
    Under higher isolation levels, your application should be prepared to
 
162
    handle exceptions raised on serialization failures. This option is
 
163
    designed for advanced uses.
 
164
 
 
165
.. _isolation level: http://www.postgresql.org/docs/current/static/transaction-iso.html
110
166
 
111
167
Indexes for ``varchar`` and ``text`` columns
112
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
168
--------------------------------------------
113
169
 
114
170
When specifying ``db_index=True`` on your model fields, Django typically
115
171
outputs a single ``CREATE INDEX`` statement.  However, if the database type
120
176
lookups that use the ``LIKE`` operator in their SQL, as is done with the
121
177
``contains`` and ``startswith`` lookup types.
122
178
 
123
 
.. _PostgreSQL operator class: http://www.postgresql.org/docs/8.4/static/indexes-opclass.html
 
179
.. _PostgreSQL operator class: http://www.postgresql.org/docs/current/static/indexes-opclass.html
124
180
 
125
181
.. _mysql-notes:
126
182
 
136
192
data on all database schema. Django's ``inspectdb`` feature uses it.
137
193
 
138
194
.. versionchanged:: 1.5
 
195
 
139
196
    The minimum version requirement of MySQL 5.0.3 was set in Django 1.5.
140
197
 
141
198
Django expects the database to support Unicode (UTF-8 encoding) and delegates to
156
213
 
157
214
Until MySQL 5.5.4, the default engine was MyISAM_ [#]_. The main drawbacks of
158
215
MyISAM are that it doesn't support transactions or enforce foreign-key
159
 
constraints. On the plus side, it's currently the only engine that supports
160
 
full-text indexing and searching.
 
216
constraints. On the plus side, it was the only engine that supported full-text
 
217
indexing and searching until MySQL 5.6.4.
161
218
 
162
219
Since MySQL 5.5.5, the default storage engine is InnoDB_. This engine is fully
163
220
transactional and supports foreign key references. It's probably the best
176
233
        1005, "Can't create table '\\db_name\\.#sql-4a8_ab' (errno: 150)"
177
234
    )
178
235
 
179
 
.. versionchanged:: 1.4
180
 
 
181
 
In previous versions of Django, fixtures with forward references (i.e.
182
 
relations to rows that have not yet been inserted into the database) would fail
183
 
to load when using the InnoDB storage engine. This was due to the fact that InnoDB
184
 
deviates from the SQL standard by checking foreign key constraints immediately
185
 
instead of deferring the check until the transaction is committed. This
186
 
problem has been resolved in Django 1.4. Fixture data is now loaded with foreign key
187
 
checks turned off; foreign key checks are then re-enabled when the data has
188
 
finished loading, at which point the entire table is checked for invalid foreign
189
 
key references and an `IntegrityError` is raised if any are found.
190
 
 
191
236
.. _storage engines: http://dev.mysql.com/doc/refman/5.5/en/storage-engines.html
192
237
.. _MyISAM: http://dev.mysql.com/doc/refman/5.5/en/myisam-storage-engine.html
193
238
.. _InnoDB: http://dev.mysql.com/doc/refman/5.5/en/innodb-storage-engine.html
210
255
    1.2.1p2 or newer, then delete the ``sets.py`` file in the MySQLdb
211
256
    directory that was left by an earlier version.
212
257
 
 
258
.. note::
 
259
    There are known issues with the way MySQLdb converts date strings into
 
260
    datetime objects. Specifically, date strings with value 0000-00-00 are valid for
 
261
    MySQL but will be converted into None by MySQLdb.
 
262
 
 
263
    This means you should be careful while using loaddata/dumpdata with rows
 
264
    that may have 0000-00-00 values, as they will be converted to None.
 
265
 
213
266
.. _MySQLdb: http://sourceforge.net/projects/mysql-python
214
267
 
215
268
Python 3
219
272
Python 3. In order to use MySQL under Python 3, you'll have to install an
220
273
unofficial fork, such as `MySQL-for-Python-3`_.
221
274
 
 
275
This port is still in alpha. In particular, it doesn't support binary data,
 
276
making it impossible to use :class:`django.db.models.BinaryField`.
 
277
 
222
278
.. _MySQL-for-Python-3: https://github.com/clelland/MySQL-for-Python-3
223
279
 
224
280
Creating your database
247
303
.. _documented thoroughly: http://dev.mysql.com/doc/refman/5.0/en/charset.html
248
304
 
249
305
By default, with a UTF-8 database, MySQL will use the
250
 
``utf8_general_ci_swedish`` collation. This results in all string equality
 
306
``utf8_general_ci`` collation. This results in all string equality
251
307
comparisons being done in a *case-insensitive* manner. That is, ``"Fred"`` and
252
308
``"freD"`` are considered equal at the database level. If you have a unique
253
309
constraint on a field, it would be illegal to try to insert both ``"aa"`` and
284
340
recommended solution.
285
341
 
286
342
Should you decide to use ``utf8_bin`` collation for some of your tables with
287
 
MySQLdb 1.2.1p2 or 1.2.2, you should still use ``utf8_collation_ci_swedish``
 
343
MySQLdb 1.2.1p2 or 1.2.2, you should still use ``utf8_general_ci``
288
344
(the default) collation for the ``django.contrib.sessions.models.Session``
289
345
table (usually called ``django_session``) and the
290
346
``django.contrib.admin.models.LogEntry`` table (usually called
389
445
 
390
446
Both the Django ORM and MySQL (when using the InnoDB :ref:`storage engine
391
447
<mysql-storage-engines>`) support database :ref:`savepoints
392
 
<topics-db-transactions-savepoints>`, but this feature wasn't available in
393
 
Django until version 1.4 when such supports was added.
 
448
<topics-db-transactions-savepoints>`.
394
449
 
395
450
If you use the MyISAM storage engine please be aware of the fact that you will
396
451
receive database-generated errors if you try to use the :ref:`savepoint-related
571
626
SQLite does not support the ``SELECT ... FOR UPDATE`` syntax. Calling it will
572
627
have no effect.
573
628
 
 
629
"pyformat" parameter style in raw queries not supported
 
630
-------------------------------------------------------
 
631
 
 
632
For most backends, raw queries (``Manager.raw()`` or ``cursor.execute()``)
 
633
can use the "pyformat" parameter style, where placeholders in the query
 
634
are given as ``'%(name)s'`` and the parameters are passed as a dictionary
 
635
rather than a list. SQLite does not support this.
 
636
 
574
637
.. _sqlite-connection-queries:
575
638
 
576
639
Parameters not quoted in ``connection.queries``
579
642
``sqlite3`` does not provide a way to retrieve the SQL after quoting and
580
643
substituting the parameters. Instead, the SQL in ``connection.queries`` is
581
644
rebuilt with a simple string interpolation. It may be incorrect. Make sure
582
 
you add quotes where necessary before copying a query into a SQLite shell.
 
645
you add quotes where necessary before copying a query into an SQLite shell.
583
646
 
584
647
.. _oracle-notes:
585
648
 
699
762
Oracle imposes a name length limit of 30 characters. To accommodate this, the
700
763
backend truncates database identifiers to fit, replacing the final four
701
764
characters of the truncated name with a repeatable MD5 hash value.
 
765
Additionally, the backend turns database identifiers to all-uppercase.
 
766
 
 
767
To prevent these transformations (this is usually required only when dealing
 
768
with legacy databases or accessing tables which belong to other users), use
 
769
a quoted name as the value for ``db_table``::
 
770
 
 
771
    class LegacyModel(models.Model):
 
772
        class Meta:
 
773
            db_table = '"name_left_in_lowercase"'
 
774
 
 
775
    class ForeignModel(models.Model):
 
776
        class Meta:
 
777
            db_table = '"OTHER_USER"."NAME_ONLY_SEEMS_OVER_30"'
 
778
 
 
779
Quoted names can also be used with Django's other supported database 
 
780
backends; except for Oracle, however, the quotes have no effect.
702
781
 
703
782
When running syncdb, an ``ORA-06552`` error may be encountered if
704
783
certain Oracle keywords are used as the name of a model field or the
760
839
.. _IBM DB2: http://code.google.com/p/ibm-db/
761
840
.. _Microsoft SQL Server 2005: http://code.google.com/p/django-mssql/
762
841
.. _Firebird: http://code.google.com/p/django-firebird/
763
 
.. _ODBC: http://code.google.com/p/django-pyodbc/
 
842
.. _ODBC: https://github.com/aurorasoftware/django-pyodbc/
764
843
.. _ADSDB: http://code.google.com/p/adsdb-django/