2005-07-13 09:25:57 +08:00
|
|
|
"""
|
|
|
|
MySQL database backend for Django.
|
|
|
|
|
|
|
|
Requires MySQLdb: http://sourceforge.net/projects/mysql-python
|
|
|
|
"""
|
|
|
|
|
|
|
|
from django.core.db import base, typecasts
|
2005-07-21 23:48:20 +08:00
|
|
|
from django.core.db.dicthelpers import *
|
2005-07-13 09:25:57 +08:00
|
|
|
import MySQLdb as Database
|
|
|
|
from MySQLdb.converters import conversions
|
|
|
|
from MySQLdb.constants import FIELD_TYPE
|
|
|
|
import types
|
|
|
|
|
|
|
|
DatabaseError = Database.DatabaseError
|
|
|
|
|
|
|
|
django_conversions = conversions.copy()
|
|
|
|
django_conversions.update({
|
|
|
|
types.BooleanType: typecasts.rev_typecast_boolean,
|
|
|
|
FIELD_TYPE.DATETIME: typecasts.typecast_timestamp,
|
|
|
|
FIELD_TYPE.DATE: typecasts.typecast_date,
|
|
|
|
FIELD_TYPE.TIME: typecasts.typecast_time,
|
|
|
|
})
|
|
|
|
|
2005-10-09 05:00:25 +08:00
|
|
|
# This is an extra debug layer over MySQL queries, to display warnings.
|
|
|
|
# It's only used when DEBUG=True.
|
|
|
|
class MysqlDebugWrapper:
|
|
|
|
def __init__(self, cursor):
|
|
|
|
self.cursor = cursor
|
|
|
|
|
|
|
|
def execute(self, sql, params=()):
|
|
|
|
try:
|
|
|
|
return self.cursor.execute(sql, params)
|
|
|
|
except Database.Warning, w:
|
|
|
|
self.cursor.execute("SHOW WARNINGS")
|
|
|
|
raise Database.Warning, "%s: %s" % (w, self.cursor.fetchall())
|
|
|
|
|
|
|
|
def executemany(self, sql, param_list):
|
|
|
|
try:
|
|
|
|
return self.cursor.executemany(sql, param_list)
|
|
|
|
except Database.Warning:
|
|
|
|
self.cursor.execute("SHOW WARNINGS")
|
|
|
|
raise Database.Warning, "%s: %s" % (w, self.cursor.fetchall())
|
|
|
|
|
|
|
|
def __getattr__(self, attr):
|
|
|
|
if self.__dict__.has_key(attr):
|
|
|
|
return self.__dict__[attr]
|
|
|
|
else:
|
|
|
|
return getattr(self.cursor, attr)
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class DatabaseWrapper:
|
|
|
|
def __init__(self):
|
|
|
|
self.connection = None
|
|
|
|
self.queries = []
|
|
|
|
|
|
|
|
def cursor(self):
|
2005-10-14 11:43:01 +08:00
|
|
|
from django.conf.settings import DATABASE_USER, DATABASE_NAME, DATABASE_HOST, DATABASE_PORT, DATABASE_PASSWORD, DEBUG
|
2005-07-13 09:25:57 +08:00
|
|
|
if self.connection is None:
|
2005-10-14 11:43:01 +08:00
|
|
|
kwargs = {
|
|
|
|
'user': DATABASE_USER,
|
|
|
|
'db': DATABASE_NAME,
|
|
|
|
'passwd': DATABASE_PASSWORD,
|
|
|
|
'host': DATABASE_HOST,
|
|
|
|
'conv': django_conversions,
|
|
|
|
}
|
|
|
|
if DATABASE_PORT:
|
|
|
|
kwargs['port'] = DATABASE_PORT
|
|
|
|
self.connection = Database.connect(**kwargs)
|
2005-07-13 09:25:57 +08:00
|
|
|
if DEBUG:
|
2005-10-09 05:00:25 +08:00
|
|
|
return base.CursorDebugWrapper(MysqlDebugWrapper(self.connection.cursor()), self)
|
2005-07-13 09:25:57 +08:00
|
|
|
return self.connection.cursor()
|
|
|
|
|
|
|
|
def commit(self):
|
2005-07-17 05:10:25 +08:00
|
|
|
self.connection.commit()
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def rollback(self):
|
2005-07-17 05:10:25 +08:00
|
|
|
if self.connection:
|
2005-08-10 12:45:10 +08:00
|
|
|
try:
|
|
|
|
self.connection.rollback()
|
2005-08-10 12:48:47 +08:00
|
|
|
except Database.NotSupportedError:
|
2005-08-10 12:45:10 +08:00
|
|
|
pass
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def close(self):
|
|
|
|
if self.connection is not None:
|
|
|
|
self.connection.close()
|
|
|
|
self.connection = None
|
|
|
|
|
2005-11-13 13:11:41 +08:00
|
|
|
def quote_name(self, name):
|
|
|
|
if name.startswith("`") and name.endswith("`"):
|
|
|
|
return name # Quoting once is enough.
|
|
|
|
return "`%s`" % name
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def get_last_insert_id(cursor, table_name, pk_name):
|
|
|
|
cursor.execute("SELECT LAST_INSERT_ID()")
|
|
|
|
return cursor.fetchone()[0]
|
|
|
|
|
2005-07-18 02:23:34 +08:00
|
|
|
def get_date_extract_sql(lookup_type, table_name):
|
|
|
|
# lookup_type is 'year', 'month', 'day'
|
2005-07-18 04:16:06 +08:00
|
|
|
# http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
|
2005-07-18 02:23:34 +08:00
|
|
|
return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), table_name)
|
|
|
|
|
2005-07-18 04:16:06 +08:00
|
|
|
def get_date_trunc_sql(lookup_type, field_name):
|
|
|
|
# lookup_type is 'year', 'month', 'day'
|
|
|
|
# http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
|
|
|
|
# MySQL doesn't support DATE_TRUNC, so we fake it by subtracting intervals.
|
|
|
|
# If you know of a better way to do this, please file a Django ticket.
|
|
|
|
subtractions = ["interval (DATE_FORMAT(%s, '%%%%s')) second - interval (DATE_FORMAT(%s, '%%%%i')) minute - interval (DATE_FORMAT(%s, '%%%%H')) hour" % (field_name, field_name, field_name)]
|
|
|
|
if lookup_type in ('year', 'month'):
|
|
|
|
subtractions.append(" - interval (DATE_FORMAT(%s, '%%%%e')-1) day" % field_name)
|
|
|
|
if lookup_type == 'year':
|
|
|
|
subtractions.append(" - interval (DATE_FORMAT(%s, '%%%%m')-1) month" % field_name)
|
|
|
|
return "(%s - %s)" % (field_name, ''.join(subtractions))
|
|
|
|
|
2005-08-20 05:51:14 +08:00
|
|
|
def get_limit_offset_sql(limit, offset=None):
|
|
|
|
sql = "LIMIT "
|
|
|
|
if offset and offset != 0:
|
|
|
|
sql += "%s," % offset
|
|
|
|
return sql + str(limit)
|
|
|
|
|
2005-09-03 04:46:00 +08:00
|
|
|
def get_random_function_sql():
|
|
|
|
return "RAND()"
|
|
|
|
|
2005-08-03 01:08:24 +08:00
|
|
|
def get_table_list(cursor):
|
|
|
|
"Returns a list of table names in the current database."
|
|
|
|
cursor.execute("SHOW TABLES")
|
|
|
|
return [row[0] for row in cursor.fetchall()]
|
|
|
|
|
2005-11-29 10:05:32 +08:00
|
|
|
def get_table_description(cursor, table_name):
|
|
|
|
"Returns a description of the table, with the DB-API cursor.description interface."
|
2005-12-16 13:13:25 +08:00
|
|
|
cursor.execute("SELECT * FROM %s LIMIT 1" % DatabaseWrapper.quote_name(table_name))
|
2005-11-29 10:05:32 +08:00
|
|
|
return cursor.description
|
|
|
|
|
2005-08-03 06:33:39 +08:00
|
|
|
def get_relations(cursor, table_name):
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
OPERATOR_MAPPING = {
|
2005-11-21 10:46:15 +08:00
|
|
|
'exact': '= %s',
|
|
|
|
'iexact': 'LIKE %s',
|
|
|
|
'contains': 'LIKE BINARY %s',
|
|
|
|
'icontains': 'LIKE %s',
|
|
|
|
'ne': '!= %s',
|
|
|
|
'gt': '> %s',
|
|
|
|
'gte': '>= %s',
|
|
|
|
'lt': '< %s',
|
|
|
|
'lte': '<= %s',
|
|
|
|
'startswith': 'LIKE BINARY %s',
|
|
|
|
'endswith': 'LIKE BINARY %s',
|
|
|
|
'istartswith': 'LIKE %s',
|
|
|
|
'iendswith': 'LIKE %s',
|
2005-07-13 09:25:57 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
# This dictionary maps Field objects to their associated MySQL column
|
|
|
|
# types, as strings. Column-type strings can contain format strings; they'll
|
|
|
|
# be interpolated against the values of Field.__dict__ before being output.
|
|
|
|
# If a column type is set to None, it won't be included in the output.
|
|
|
|
DATA_TYPES = {
|
2005-07-18 21:53:45 +08:00
|
|
|
'AutoField': 'mediumint(9) unsigned auto_increment',
|
2005-07-13 09:25:57 +08:00
|
|
|
'BooleanField': 'bool',
|
|
|
|
'CharField': 'varchar(%(maxlength)s)',
|
|
|
|
'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)',
|
|
|
|
'DateField': 'date',
|
|
|
|
'DateTimeField': 'datetime',
|
|
|
|
'FileField': 'varchar(100)',
|
2005-10-12 12:14:21 +08:00
|
|
|
'FilePathField': 'varchar(100)',
|
2005-07-13 09:25:57 +08:00
|
|
|
'FloatField': 'numeric(%(max_digits)s, %(decimal_places)s)',
|
|
|
|
'ImageField': 'varchar(100)',
|
|
|
|
'IntegerField': 'integer',
|
|
|
|
'IPAddressField': 'char(15)',
|
|
|
|
'ManyToManyField': None,
|
|
|
|
'NullBooleanField': 'bool',
|
2005-07-18 01:22:17 +08:00
|
|
|
'OneToOneField': 'integer',
|
2005-07-13 09:25:57 +08:00
|
|
|
'PhoneNumberField': 'varchar(20)',
|
|
|
|
'PositiveIntegerField': 'integer UNSIGNED',
|
|
|
|
'PositiveSmallIntegerField': 'smallint UNSIGNED',
|
|
|
|
'SlugField': 'varchar(50)',
|
|
|
|
'SmallIntegerField': 'smallint',
|
2005-09-25 01:37:30 +08:00
|
|
|
'TextField': 'longtext',
|
2005-07-13 09:25:57 +08:00
|
|
|
'TimeField': 'time',
|
|
|
|
'URLField': 'varchar(200)',
|
|
|
|
'USStateField': 'varchar(2)',
|
|
|
|
}
|
2005-08-03 01:08:24 +08:00
|
|
|
|
|
|
|
DATA_TYPES_REVERSE = {
|
|
|
|
FIELD_TYPE.BLOB: 'TextField',
|
|
|
|
FIELD_TYPE.CHAR: 'CharField',
|
|
|
|
FIELD_TYPE.DECIMAL: 'FloatField',
|
|
|
|
FIELD_TYPE.DATE: 'DateField',
|
|
|
|
FIELD_TYPE.DATETIME: 'DateTimeField',
|
|
|
|
FIELD_TYPE.DOUBLE: 'FloatField',
|
|
|
|
FIELD_TYPE.FLOAT: 'FloatField',
|
|
|
|
FIELD_TYPE.INT24: 'IntegerField',
|
|
|
|
FIELD_TYPE.LONG: 'IntegerField',
|
|
|
|
FIELD_TYPE.LONGLONG: 'IntegerField',
|
|
|
|
FIELD_TYPE.SHORT: 'IntegerField',
|
|
|
|
FIELD_TYPE.STRING: 'TextField',
|
|
|
|
FIELD_TYPE.TIMESTAMP: 'DateTimeField',
|
|
|
|
FIELD_TYPE.TINY_BLOB: 'TextField',
|
|
|
|
FIELD_TYPE.MEDIUM_BLOB: 'TextField',
|
|
|
|
FIELD_TYPE.LONG_BLOB: 'TextField',
|
|
|
|
FIELD_TYPE.VAR_STRING: 'CharField',
|
|
|
|
}
|