|
1 """ |
|
2 MySQL database backend for Django. |
|
3 |
|
4 Requires MySQLdb: http://sourceforge.net/projects/mysql-python |
|
5 """ |
|
6 |
|
7 from django.db.backends import BaseDatabaseWrapper, BaseDatabaseFeatures, BaseDatabaseOperations, util |
|
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) |
|
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 |
|
18 if (version < (1,2,1) or (version[:3] == (1, 2, 1) and |
|
19 (len(version) < 5 or version[3] != 'final' or version[4] < 2))): |
|
20 from django.core.exceptions import ImproperlyConfigured |
|
21 raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__) |
|
22 |
|
23 from MySQLdb.converters import conversions |
|
24 from MySQLdb.constants import FIELD_TYPE |
|
25 import re |
|
26 |
|
27 # Raise exceptions for database warnings if DEBUG is on |
|
28 from django.conf import settings |
|
29 if settings.DEBUG: |
|
30 from warnings import filterwarnings |
|
31 filterwarnings("error", category=Database.Warning) |
|
32 |
|
33 DatabaseError = Database.DatabaseError |
|
34 IntegrityError = Database.IntegrityError |
|
35 |
|
36 # MySQLdb-1.2.1 supports the Python boolean type, and only uses datetime |
|
37 # module for time-related columns; older versions could have used mx.DateTime |
|
38 # or strings if there were no datetime module. However, MySQLdb still returns |
|
39 # TIME columns as timedelta -- they are more like timedelta in terms of actual |
|
40 # behavior as they are signed and include days -- and Django expects time, so |
|
41 # we still need to override that. |
|
42 django_conversions = conversions.copy() |
|
43 django_conversions.update({ |
|
44 FIELD_TYPE.TIME: util.typecast_time, |
|
45 FIELD_TYPE.DECIMAL: util.typecast_decimal, |
|
46 FIELD_TYPE.NEWDECIMAL: util.typecast_decimal, |
|
47 }) |
|
48 |
|
49 # This should match the numerical portion of the version numbers (we can treat |
|
50 # versions like 5.0.24 and 5.0.24a as the same). Based on the list of version |
|
51 # at http://dev.mysql.com/doc/refman/4.1/en/news.html and |
|
52 # http://dev.mysql.com/doc/refman/5.0/en/news.html . |
|
53 server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})') |
|
54 |
|
55 # MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on |
|
56 # MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the |
|
57 # point is to raise Warnings as exceptions, this can be done with the Python |
|
58 # warning module, and this is setup when the connection is created, and the |
|
59 # standard util.CursorDebugWrapper can be used. Also, using sql_mode |
|
60 # TRADITIONAL will automatically cause most warnings to be treated as errors. |
|
61 |
|
62 class DatabaseFeatures(BaseDatabaseFeatures): |
|
63 autoindexes_primary_keys = False |
|
64 inline_fk_references = False |
|
65 empty_fetchmany_value = () |
|
66 update_can_self_select = False |
|
67 |
|
68 class DatabaseOperations(BaseDatabaseOperations): |
|
69 def date_extract_sql(self, lookup_type, field_name): |
|
70 # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html |
|
71 return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) |
|
72 |
|
73 def date_trunc_sql(self, lookup_type, field_name): |
|
74 fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] |
|
75 format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. |
|
76 format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') |
|
77 try: |
|
78 i = fields.index(lookup_type) + 1 |
|
79 except ValueError: |
|
80 sql = field_name |
|
81 else: |
|
82 format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]]) |
|
83 sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str) |
|
84 return sql |
|
85 |
|
86 def drop_foreignkey_sql(self): |
|
87 return "DROP FOREIGN KEY" |
|
88 |
|
89 def fulltext_search_sql(self, field_name): |
|
90 return 'MATCH (%s) AGAINST (%%s IN BOOLEAN MODE)' % field_name |
|
91 |
|
92 def limit_offset_sql(self, limit, offset=None): |
|
93 # 'LIMIT 20,40' |
|
94 sql = "LIMIT " |
|
95 if offset and offset != 0: |
|
96 sql += "%s," % offset |
|
97 return sql + str(limit) |
|
98 |
|
99 def no_limit_value(self): |
|
100 # 2**64 - 1, as recommended by the MySQL documentation |
|
101 return 18446744073709551615L |
|
102 |
|
103 def quote_name(self, name): |
|
104 if name.startswith("`") and name.endswith("`"): |
|
105 return name # Quoting once is enough. |
|
106 return "`%s`" % name |
|
107 |
|
108 def random_function_sql(self): |
|
109 return 'RAND()' |
|
110 |
|
111 def sql_flush(self, style, tables, sequences): |
|
112 # NB: The generated SQL below is specific to MySQL |
|
113 # 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements |
|
114 # to clear all tables of all data |
|
115 if tables: |
|
116 sql = ['SET FOREIGN_KEY_CHECKS = 0;'] |
|
117 for table in tables: |
|
118 sql.append('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(self.quote_name(table)))) |
|
119 sql.append('SET FOREIGN_KEY_CHECKS = 1;') |
|
120 |
|
121 # 'ALTER TABLE table AUTO_INCREMENT = 1;'... style SQL statements |
|
122 # to reset sequence indices |
|
123 sql.extend(["%s %s %s %s %s;" % \ |
|
124 (style.SQL_KEYWORD('ALTER'), |
|
125 style.SQL_KEYWORD('TABLE'), |
|
126 style.SQL_TABLE(self.quote_name(sequence['table'])), |
|
127 style.SQL_KEYWORD('AUTO_INCREMENT'), |
|
128 style.SQL_FIELD('= 1'), |
|
129 ) for sequence in sequences]) |
|
130 return sql |
|
131 else: |
|
132 return [] |
|
133 |
|
134 class DatabaseWrapper(BaseDatabaseWrapper): |
|
135 features = DatabaseFeatures() |
|
136 ops = DatabaseOperations() |
|
137 operators = { |
|
138 'exact': '= %s', |
|
139 'iexact': 'LIKE %s', |
|
140 'contains': 'LIKE BINARY %s', |
|
141 'icontains': 'LIKE %s', |
|
142 'regex': 'REGEXP BINARY %s', |
|
143 'iregex': 'REGEXP %s', |
|
144 'gt': '> %s', |
|
145 'gte': '>= %s', |
|
146 'lt': '< %s', |
|
147 'lte': '<= %s', |
|
148 'startswith': 'LIKE BINARY %s', |
|
149 'endswith': 'LIKE BINARY %s', |
|
150 'istartswith': 'LIKE %s', |
|
151 'iendswith': 'LIKE %s', |
|
152 } |
|
153 |
|
154 def __init__(self, **kwargs): |
|
155 super(DatabaseWrapper, self).__init__(**kwargs) |
|
156 self.server_version = None |
|
157 |
|
158 def _valid_connection(self): |
|
159 if self.connection is not None: |
|
160 try: |
|
161 self.connection.ping() |
|
162 return True |
|
163 except DatabaseError: |
|
164 self.connection.close() |
|
165 self.connection = None |
|
166 return False |
|
167 |
|
168 def _cursor(self, settings): |
|
169 if not self._valid_connection(): |
|
170 kwargs = { |
|
171 'conv': django_conversions, |
|
172 'charset': 'utf8', |
|
173 'use_unicode': True, |
|
174 } |
|
175 if settings.DATABASE_USER: |
|
176 kwargs['user'] = settings.DATABASE_USER |
|
177 if settings.DATABASE_NAME: |
|
178 kwargs['db'] = settings.DATABASE_NAME |
|
179 if settings.DATABASE_PASSWORD: |
|
180 kwargs['passwd'] = settings.DATABASE_PASSWORD |
|
181 if settings.DATABASE_HOST.startswith('/'): |
|
182 kwargs['unix_socket'] = settings.DATABASE_HOST |
|
183 elif settings.DATABASE_HOST: |
|
184 kwargs['host'] = settings.DATABASE_HOST |
|
185 if settings.DATABASE_PORT: |
|
186 kwargs['port'] = int(settings.DATABASE_PORT) |
|
187 kwargs.update(self.options) |
|
188 self.connection = Database.connect(**kwargs) |
|
189 cursor = self.connection.cursor() |
|
190 return cursor |
|
191 |
|
192 def _rollback(self): |
|
193 try: |
|
194 BaseDatabaseWrapper._rollback(self) |
|
195 except Database.NotSupportedError: |
|
196 pass |
|
197 |
|
198 def get_server_version(self): |
|
199 if not self.server_version: |
|
200 if not self._valid_connection(): |
|
201 self.cursor() |
|
202 m = server_version_re.match(self.connection.get_server_info()) |
|
203 if not m: |
|
204 raise Exception('Unable to determine MySQL version from version string %r' % self.connection.get_server_info()) |
|
205 self.server_version = tuple([int(x) for x in m.groups()]) |
|
206 return self.server_version |