Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 237 lines (202 sloc) 8.522 kb
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
1 """
2 MySQL database backend for Django.
3
4 Requires MySQLdb: http://sourceforge.net/projects/mysql-python
5 """
6
38b5d7f2 »
2007-08-19 Began implementing BaseDatabaseOperations class for every database ba…
7 from django.db.backends import BaseDatabaseWrapper, BaseDatabaseOperations, util
8e9833f2 »
2006-05-26 Fixed #1673 -- Every database backend now raises ImproperlyConfigured…
8 try:
9 import MySQLdb as Database
10 except ImportError, e:
11 from django.core.exceptions import ImproperlyConfigured
12 raise ImproperlyConfigured, "Error loading MySQLdb module: %s" % e
cb624b13 »
2007-03-18 Fixed #3747 -- Added a stricter MySQLdb version check so that (1, 2, 1,
13
14 # We want version (1, 2, 1, 'final', 2) or later. We can't just use
15 # lexicographic ordering in this check because then (1, 2, 1, 'gamma')
16 # inadvertently passes the version test.
17 version = Database.version_info
92c35a06 »
2007-05-21 Fixed #2365, #3324 -- Renamed FloatField to DecimalField and changed …
18 if (version < (1,2,1) or (version[:3] == (1, 2, 1) and
cb624b13 »
2007-03-18 Fixed #3747 -- Added a stricter MySQLdb version check so that (1, 2, 1,
19 (len(version) < 5 or version[3] != 'final' or version[4] < 2))):
20 raise ImportError, "MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__
f9c4ce51 »
2007-03-14 Fixed #2635 -- Added improved MySQL backend support from Andy Dustman…
21
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
22 from MySQLdb.converters import conversions
23 from MySQLdb.constants import FIELD_TYPE
24 import types
6068f3e4 »
2006-09-27 Reintroduced the changes from [3855] with more flexible handling of v…
25 import re
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
26
27 DatabaseError = Database.DatabaseError
b3e0b59d »
2007-04-25 Fixed #3450 -- Exposed IntegrityError in a backend-neutral fashion. T…
28 IntegrityError = Database.IntegrityError
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
29
f9c4ce51 »
2007-03-14 Fixed #2635 -- Added improved MySQL backend support from Andy Dustman…
30 # MySQLdb-1.2.1 supports the Python boolean type, and only uses datetime
31 # module for time-related columns; older versions could have used mx.DateTime
32 # or strings if there were no datetime module. However, MySQLdb still returns
33 # TIME columns as timedelta -- they are more like timedelta in terms of actual
34 # behavior as they are signed and include days -- and Django expects time, so
35 # we still need to override that.
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
36 django_conversions = conversions.copy()
37 django_conversions.update({
38 FIELD_TYPE.TIME: util.typecast_time,
92c35a06 »
2007-05-21 Fixed #2365, #3324 -- Renamed FloatField to DecimalField and changed …
39 FIELD_TYPE.DECIMAL: util.typecast_decimal,
40 FIELD_TYPE.NEWDECIMAL: util.typecast_decimal,
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
41 })
42
6068f3e4 »
2006-09-27 Reintroduced the changes from [3855] with more flexible handling of v…
43 # This should match the numerical portion of the version numbers (we can treat
44 # versions like 5.0.24 and 5.0.24a as the same). Based on the list of version
45 # at http://dev.mysql.com/doc/refman/4.1/en/news.html and
46 # http://dev.mysql.com/doc/refman/5.0/en/news.html .
47 server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
48
f9c4ce51 »
2007-03-14 Fixed #2635 -- Added improved MySQL backend support from Andy Dustman…
49 # MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on
50 # MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the
51 # point is to raise Warnings as exceptions, this can be done with the Python
52 # warning module, and this is setup when the connection is created, and the
53 # standard util.CursorDebugWrapper can be used. Also, using sql_mode
54 # TRADITIONAL will automatically cause most warnings to be treated as errors.
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
55
38b5d7f2 »
2007-08-19 Began implementing BaseDatabaseOperations class for every database ba…
56 class DatabaseOperations(BaseDatabaseOperations):
aab04a4c »
2007-08-19 Refactored get_date_extract_sql() to DatabaseOperations.date_extract_…
57 def date_extract_sql(self, lookup_type, field_name):
58 # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
59 return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
38b5d7f2 »
2007-08-19 Began implementing BaseDatabaseOperations class for every database ba…
60
7c41b19c »
2007-08-19 Refactored all database backends to inherit from a common base class …
61 class DatabaseWrapper(BaseDatabaseWrapper):
38b5d7f2 »
2007-08-19 Began implementing BaseDatabaseOperations class for every database ba…
62 ops = DatabaseOperations()
63
fef89a01 »
2006-11-07 Fixed #2866: Added DATABASE_OPTIONS setting which gets passed as extr…
64 def __init__(self, **kwargs):
7c41b19c »
2007-08-19 Refactored all database backends to inherit from a common base class …
65 super(DatabaseWrapper, self).__init__(**kwargs)
6068f3e4 »
2006-09-27 Reintroduced the changes from [3855] with more flexible handling of v…
66 self.server_version = None
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
67
68 def _valid_connection(self):
69 if self.connection is not None:
70 try:
71 self.connection.ping()
72 return True
73 except DatabaseError:
74 self.connection.close()
75 self.connection = None
76 return False
77
7c41b19c »
2007-08-19 Refactored all database backends to inherit from a common base class …
78 def _cursor(self, settings):
f9c4ce51 »
2007-03-14 Fixed #2635 -- Added improved MySQL backend support from Andy Dustman…
79 from warnings import filterwarnings
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
80 if not self._valid_connection():
81 kwargs = {
82 'conv': django_conversions,
1f9711ff »
2007-03-20 Fixed #3754 -- Re-introduced utf-8 as default encoding for interactio…
83 'charset': 'utf8',
953badbe »
2007-07-04 Merged Unicode branch into trunk (r4952:5608). This should be fully
84 'use_unicode': True,
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
85 }
f9c4ce51 »
2007-03-14 Fixed #2635 -- Added improved MySQL backend support from Andy Dustman…
86 if settings.DATABASE_USER:
87 kwargs['user'] = settings.DATABASE_USER
88 if settings.DATABASE_NAME:
89 kwargs['db'] = settings.DATABASE_NAME
90 if settings.DATABASE_PASSWORD:
91 kwargs['passwd'] = settings.DATABASE_PASSWORD
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
92 if settings.DATABASE_HOST.startswith('/'):
93 kwargs['unix_socket'] = settings.DATABASE_HOST
f9c4ce51 »
2007-03-14 Fixed #2635 -- Added improved MySQL backend support from Andy Dustman…
94 elif settings.DATABASE_HOST:
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
95 kwargs['host'] = settings.DATABASE_HOST
96 if settings.DATABASE_PORT:
97 kwargs['port'] = int(settings.DATABASE_PORT)
fef89a01 »
2006-11-07 Fixed #2866: Added DATABASE_OPTIONS setting which gets passed as extr…
98 kwargs.update(self.options)
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
99 self.connection = Database.connect(**kwargs)
7c41b19c »
2007-08-19 Refactored all database backends to inherit from a common base class …
100 cursor = self.connection.cursor()
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
101 if settings.DEBUG:
f9c4ce51 »
2007-03-14 Fixed #2635 -- Added improved MySQL backend support from Andy Dustman…
102 filterwarnings("error", category=Database.Warning)
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
103 return cursor
104
105 def _rollback(self):
7c41b19c »
2007-08-19 Refactored all database backends to inherit from a common base class …
106 try:
107 BaseDatabaseWrapper._rollback(self)
108 except Database.NotSupportedError:
109 pass
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
110
6068f3e4 »
2006-09-27 Reintroduced the changes from [3855] with more flexible handling of v…
111 def get_server_version(self):
112 if not self.server_version:
113 if not self._valid_connection():
114 self.cursor()
115 m = server_version_re.match(self.connection.get_server_info())
116 if not m:
117 raise Exception('Unable to determine MySQL version from version string %r' % self.connection.get_server_info())
a834f213 »
2006-09-27 Fixed omission in [3872].
118 self.server_version = tuple([int(x) for x in m.groups()])
6068f3e4 »
2006-09-27 Reintroduced the changes from [3855] with more flexible handling of v…
119 return self.server_version
120
ac64e91a »
2007-06-23 Merged boulder-oracle-sprint branch (r3965:5512) back into trunk. All
121 allows_group_by_ordinal = True
122 allows_unique_and_pk = True
123 autoindexes_primary_keys = False
124 needs_datetime_string_cast = True # MySQLdb requires a typecast for dates
125 needs_upper_for_iops = False
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
126 supports_constraints = True
ac64e91a »
2007-06-23 Merged boulder-oracle-sprint branch (r3965:5512) back into trunk. All
127 supports_tablespaces = False
128 uses_case_insensitive_names = False
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
129
130 def quote_name(name):
131 if name.startswith("`") and name.endswith("`"):
132 return name # Quoting once is enough.
133 return "`%s`" % name
134
135 dictfetchone = util.dictfetchone
136 dictfetchmany = util.dictfetchmany
137 dictfetchall = util.dictfetchall
138
139 def get_last_insert_id(cursor, table_name, pk_name):
140 return cursor.lastrowid
141
142 def get_date_trunc_sql(lookup_type, field_name):
143 # lookup_type is 'year', 'month', 'day'
144 fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
145 format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
146 format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
147 try:
148 i = fields.index(lookup_type) + 1
149 except ValueError:
150 sql = field_name
151 else:
152 format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
153 sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
154 return sql
155
ac64e91a »
2007-06-23 Merged boulder-oracle-sprint branch (r3965:5512) back into trunk. All
156 def get_datetime_cast_sql():
157 return None
158
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
159 def get_limit_offset_sql(limit, offset=None):
160 sql = "LIMIT "
161 if offset and offset != 0:
162 sql += "%s," % offset
163 return sql + str(limit)
164
165 def get_random_function_sql():
166 return "RAND()"
167
51f39d59 »
2007-02-26 Fixed #3390: the serializer can now contain forward references. Thank…
168 def get_deferrable_sql():
169 return ""
170
168429d5 »
2006-06-03 Fixed #593 -- Added 'search' DB-API lookup type, which does full-text…
171 def get_fulltext_search_sql(field_name):
172 return 'MATCH (%s) AGAINST (%%s IN BOOLEAN MODE)' % field_name
173
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
174 def get_drop_foreignkey_sql():
175 return "DROP FOREIGN KEY"
176
7e2b888a »
2006-06-08 Fixed #2108 -- allow saving of empty models, rather than just droppin…
177 def get_pk_default_value():
178 return "DEFAULT"
179
ac64e91a »
2007-06-23 Merged boulder-oracle-sprint branch (r3965:5512) back into trunk. All
180 def get_max_name_length():
181 return None;
182
183 def get_start_transaction_sql():
184 return "BEGIN;"
185
f2582eb9 »
2007-03-01 Fixes #2333 -- Added test fixtures framework.
186 def get_sql_flush(style, tables, sequences):
187 """Return a list of SQL statements required to remove all data from
188 all tables in the database (without actually removing the tables
189 themselves) and put the database in an empty 'initial' state
ac64e91a »
2007-06-23 Merged boulder-oracle-sprint branch (r3965:5512) back into trunk. All
190
f2582eb9 »
2007-03-01 Fixes #2333 -- Added test fixtures framework.
191 """
192 # NB: The generated SQL below is specific to MySQL
193 # 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements
194 # to clear all tables of all data
195 if tables:
196 sql = ['SET FOREIGN_KEY_CHECKS = 0;'] + \
197 ['%s %s;' % \
198 (style.SQL_KEYWORD('TRUNCATE'),
199 style.SQL_FIELD(quote_name(table))
200 ) for table in tables] + \
201 ['SET FOREIGN_KEY_CHECKS = 1;']
ac64e91a »
2007-06-23 Merged boulder-oracle-sprint branch (r3965:5512) back into trunk. All
202
f2582eb9 »
2007-03-01 Fixes #2333 -- Added test fixtures framework.
203 # 'ALTER TABLE table AUTO_INCREMENT = 1;'... style SQL statements
204 # to reset sequence indices
205 sql.extend(["%s %s %s %s %s;" % \
206 (style.SQL_KEYWORD('ALTER'),
207 style.SQL_KEYWORD('TABLE'),
208 style.SQL_TABLE(quote_name(sequence['table'])),
209 style.SQL_KEYWORD('AUTO_INCREMENT'),
210 style.SQL_FIELD('= 1'),
211 ) for sequence in sequences])
212 return sql
213 else:
214 return []
215
dabd9664 »
2007-04-06 Fixed #3790 -- Fixed a problem with sequence resetting during fixture…
216 def get_sql_sequence_reset(style, model_list):
217 "Returns a list of the SQL statements to reset sequences for the given models."
218 # No sequence reset required
219 return []
220
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
221 OPERATOR_MAPPING = {
222 'exact': '= %s',
223 'iexact': 'LIKE %s',
224 'contains': 'LIKE BINARY %s',
225 'icontains': 'LIKE %s',
24512a74 »
2007-06-27 Fixed #1465: added support for regex lookups. Thanks, Tom Tobin.
226 'regex': 'REGEXP BINARY %s',
227 'iregex': 'REGEXP %s',
f69cf70e »
2006-05-02 MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards…
228 'gt': '> %s',
229 'gte': '>= %s',
230 'lt': '< %s',
231 'lte': '<= %s',
232 'startswith': 'LIKE BINARY %s',
233 'endswith': 'LIKE BINARY %s',
234 'istartswith': 'LIKE %s',
235 'iendswith': 'LIKE %s',
236 }
Something went wrong with that request. Please try again.