Permalink
Browse files

Refactored quote_name() to DatabaseOperations.quote_name(). Refs #5106

git-svn-id: http://code.djangoproject.com/svn/django/trunk@5967 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
1 parent d4f218b commit 221f99ed5831b71b7ddb810ec8808a884773ef04 @adrianholovaty adrianholovaty committed Aug 20, 2007
@@ -1,6 +1,6 @@
from django.core import validators
from django.core.exceptions import ImproperlyConfigured
-from django.db import backend, connection, models
+from django.db import connection, models
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _
@@ -203,20 +203,21 @@ def get_group_permissions(self):
# AND gp."group_id" = ug."group_id"
# AND ct."id" = p."content_type_id"
# AND ug."user_id" = %s, [self.id])
+ qn = connection.ops.quote_name
sql = """
SELECT ct.%s, p.%s
FROM %s p, %s gp, %s ug, %s ct
WHERE p.%s = gp.%s
AND gp.%s = ug.%s
AND ct.%s = p.%s
AND ug.%s = %%s""" % (
- backend.quote_name('app_label'), backend.quote_name('codename'),
- backend.quote_name('auth_permission'), backend.quote_name('auth_group_permissions'),
- backend.quote_name('auth_user_groups'), backend.quote_name('django_content_type'),
- backend.quote_name('id'), backend.quote_name('permission_id'),
- backend.quote_name('group_id'), backend.quote_name('group_id'),
- backend.quote_name('id'), backend.quote_name('content_type_id'),
- backend.quote_name('user_id'),)
+ qn('app_label'), qn('codename'),
+ qn('auth_permission'), qn('auth_group_permissions'),
+ qn('auth_user_groups'), qn('django_content_type'),
+ qn('id'), qn('permission_id'),
+ qn('group_id'), qn('group_id'),
+ qn('id'), qn('content_type_id'),
+ qn('user_id'),)
cursor.execute(sql, [self.id])
self._group_perm_cache = set(["%s.%s" % (row[0], row[1]) for row in cursor.fetchall()])
return self._group_perm_cache
@@ -4,7 +4,7 @@
from django import oldforms
from django.core.exceptions import ObjectDoesNotExist
-from django.db import backend
+from django.db import connection
from django.db.models import signals
from django.db.models.fields.related import RelatedField, Field, ManyToManyRel
from django.db.models.loading import get_model
@@ -163,13 +163,15 @@ def __get__(self, instance, instance_type=None):
superclass = rel_model._default_manager.__class__
RelatedManager = create_generic_related_manager(superclass)
+ qn = connection.ops.quote_name
+
manager = RelatedManager(
model = rel_model,
instance = instance,
symmetrical = (self.field.rel.symmetrical and instance.__class__ == rel_model),
- join_table = backend.quote_name(self.field.m2m_db_table()),
- source_col_name = backend.quote_name(self.field.m2m_column_name()),
- target_col_name = backend.quote_name(self.field.m2m_reverse_name()),
+ join_table = qn(self.field.m2m_db_table()),
+ source_col_name = qn(self.field.m2m_column_name()),
+ target_col_name = qn(self.field.m2m_reverse_name()),
content_type = ContentType.objects.get_for_model(self.field.model),
content_type_field_name = self.field.content_type_field_name,
object_id_field_name = self.field.object_id_field_name
@@ -8,7 +8,7 @@ class Command(LabelCommand):
requires_model_validation = False
def handle_label(self, tablename, **options):
- from django.db import backend, connection, transaction, models
+ from django.db import connection, transaction, models
fields = (
# "key" is a reserved word in MySQL, so use "cache_key" instead.
models.CharField(name='cache_key', max_length=255, unique=True, primary_key=True),
@@ -17,8 +17,9 @@ def handle_label(self, tablename, **options):
)
table_output = []
index_output = []
+ qn = connection.ops.quote_name
for f in fields:
- field_output = [backend.quote_name(f.name), f.db_type()]
+ field_output = [qn(f.name), f.db_type()]
field_output.append("%sNULL" % (not f.null and "NOT " or ""))
if f.unique:
field_output.append("UNIQUE")
@@ -27,10 +28,10 @@ def handle_label(self, tablename, **options):
if f.db_index:
unique = f.unique and "UNIQUE " or ""
index_output.append("CREATE %sINDEX %s_%s ON %s (%s);" % \
- (unique, tablename, f.name, backend.quote_name(tablename),
- backend.quote_name(f.name)))
+ (unique, tablename, f.name, qn(tablename),
+ qn(f.name)))
table_output.append(" ".join(field_output))
- full_statement = ["CREATE TABLE %s (" % backend.quote_name(tablename)]
+ full_statement = ["CREATE TABLE %s (" % qn(tablename)]
for i, line in enumerate(table_output):
full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or ''))
full_statement.append(');')
@@ -116,6 +116,7 @@ def sql_delete(app, style):
table_name_converter = lambda x: x
output = []
+ qn = connection.ops.quote_name
# Output DROP TABLE statements for standard application tables.
to_delete = set()
@@ -136,7 +137,7 @@ def sql_delete(app, style):
if cursor and table_name_converter(model._meta.db_table) in table_names:
# Drop the table now
output.append('%s %s;' % (style.SQL_KEYWORD('DROP TABLE'),
- style.SQL_TABLE(backend.quote_name(model._meta.db_table))))
+ style.SQL_TABLE(qn(model._meta.db_table))))
if backend.supports_constraints and model in references_to_delete:
for rel_class, f in references_to_delete[model]:
table = rel_class._meta.db_table
@@ -146,7 +147,7 @@ def sql_delete(app, style):
r_name = '%s_refs_%s_%x' % (col, r_col, abs(hash((table, r_table))))
output.append('%s %s %s %s;' % \
(style.SQL_KEYWORD('ALTER TABLE'),
- style.SQL_TABLE(backend.quote_name(table)),
+ style.SQL_TABLE(qn(table)),
style.SQL_KEYWORD(connection.ops.drop_foreignkey_sql()),
style.SQL_FIELD(truncate_name(r_name, connection.ops.max_name_length()))))
del references_to_delete[model]
@@ -159,7 +160,7 @@ def sql_delete(app, style):
for f in opts.many_to_many:
if cursor and table_name_converter(f.m2m_db_table()) in table_names:
output.append("%s %s;" % (style.SQL_KEYWORD('DROP TABLE'),
- style.SQL_TABLE(backend.quote_name(f.m2m_db_table()))))
+ style.SQL_TABLE(qn(f.m2m_db_table()))))
if hasattr(backend, 'get_drop_sequence'):
output.append(backend.get_drop_sequence("%s_%s" % (model._meta.db_table, f.column)))
@@ -219,6 +220,7 @@ def sql_model_create(model, style, known_models=set()):
final_output = []
table_output = []
pending_references = {}
+ qn = connection.ops.quote_name
for f in opts.fields:
col_type = f.db_type()
tablespace = f.db_tablespace or opts.db_tablespace
@@ -227,7 +229,7 @@ def sql_model_create(model, style, known_models=set()):
# database columns in this table.
continue
# Make the definition (e.g. 'foo VARCHAR(30)') for this field.
- field_output = [style.SQL_FIELD(backend.quote_name(f.column)),
+ field_output = [style.SQL_FIELD(qn(f.column)),
style.SQL_COLTYPE(col_type)]
field_output.append(style.SQL_KEYWORD('%sNULL' % (not f.null and 'NOT ' or '')))
if f.unique and (not f.primary_key or backend.allows_unique_and_pk):
@@ -241,8 +243,8 @@ def sql_model_create(model, style, known_models=set()):
if f.rel:
if f.rel.to in known_models:
field_output.append(style.SQL_KEYWORD('REFERENCES') + ' ' + \
- style.SQL_TABLE(backend.quote_name(f.rel.to._meta.db_table)) + ' (' + \
- style.SQL_FIELD(backend.quote_name(f.rel.to._meta.get_field(f.rel.field_name).column)) + ')' +
+ style.SQL_TABLE(qn(f.rel.to._meta.db_table)) + ' (' + \
+ style.SQL_FIELD(qn(f.rel.to._meta.get_field(f.rel.field_name).column)) + ')' +
connection.ops.deferrable_sql()
)
else:
@@ -251,14 +253,14 @@ def sql_model_create(model, style, known_models=set()):
pr = pending_references.setdefault(f.rel.to, []).append((model, f))
table_output.append(' '.join(field_output))
if opts.order_with_respect_to:
- table_output.append(style.SQL_FIELD(backend.quote_name('_order')) + ' ' + \
+ table_output.append(style.SQL_FIELD(qn('_order')) + ' ' + \
style.SQL_COLTYPE(models.IntegerField().db_type()) + ' ' + \
style.SQL_KEYWORD('NULL'))
for field_constraints in opts.unique_together:
table_output.append(style.SQL_KEYWORD('UNIQUE') + ' (%s)' % \
- ", ".join([backend.quote_name(style.SQL_FIELD(opts.get_field(f).column)) for f in field_constraints]))
+ ", ".join([qn(style.SQL_FIELD(opts.get_field(f).column)) for f in field_constraints]))
- full_statement = [style.SQL_KEYWORD('CREATE TABLE') + ' ' + style.SQL_TABLE(backend.quote_name(opts.db_table)) + ' (']
+ full_statement = [style.SQL_KEYWORD('CREATE TABLE') + ' ' + style.SQL_TABLE(qn(opts.db_table)) + ' (']
for i, line in enumerate(table_output): # Combine and add commas.
full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or ''))
full_statement.append(')')
@@ -283,6 +285,7 @@ def sql_for_pending_references(model, style, pending_references):
from django.db import backend, connection
from django.db.backends.util import truncate_name
+ qn = connection.ops.quote_name
final_output = []
if backend.supports_constraints:
opts = model._meta
@@ -297,8 +300,8 @@ def sql_for_pending_references(model, style, pending_references):
# So we are careful with character usage here.
r_name = '%s_refs_%s_%x' % (r_col, col, abs(hash((r_table, table))))
final_output.append(style.SQL_KEYWORD('ALTER TABLE') + ' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s;' % \
- (backend.quote_name(r_table), truncate_name(r_name, connection.ops.max_name_length()),
- backend.quote_name(r_col), backend.quote_name(table), backend.quote_name(col),
+ (qn(r_table), truncate_name(r_name, connection.ops.max_name_length()),
+ qn(r_col), qn(table), qn(col),
connection.ops.deferrable_sql()))
del pending_references[model]
return final_output
@@ -309,6 +312,7 @@ def many_to_many_sql_for_model(model, style):
opts = model._meta
final_output = []
+ qn = connection.ops.quote_name
for f in opts.many_to_many:
if not isinstance(f.rel, generic.GenericRel):
tablespace = f.db_tablespace or opts.db_tablespace
@@ -317,30 +321,30 @@ def many_to_many_sql_for_model(model, style):
else:
tablespace_sql = ''
table_output = [style.SQL_KEYWORD('CREATE TABLE') + ' ' + \
- style.SQL_TABLE(backend.quote_name(f.m2m_db_table())) + ' (']
+ style.SQL_TABLE(qn(f.m2m_db_table())) + ' (']
table_output.append(' %s %s %s%s,' % \
- (style.SQL_FIELD(backend.quote_name('id')),
+ (style.SQL_FIELD(qn('id')),
style.SQL_COLTYPE(models.AutoField(primary_key=True).db_type()),
style.SQL_KEYWORD('NOT NULL PRIMARY KEY'),
tablespace_sql))
table_output.append(' %s %s %s %s (%s)%s,' % \
- (style.SQL_FIELD(backend.quote_name(f.m2m_column_name())),
+ (style.SQL_FIELD(qn(f.m2m_column_name())),
style.SQL_COLTYPE(models.ForeignKey(model).db_type()),
style.SQL_KEYWORD('NOT NULL REFERENCES'),
- style.SQL_TABLE(backend.quote_name(opts.db_table)),
- style.SQL_FIELD(backend.quote_name(opts.pk.column)),
+ style.SQL_TABLE(qn(opts.db_table)),
+ style.SQL_FIELD(qn(opts.pk.column)),
connection.ops.deferrable_sql()))
table_output.append(' %s %s %s %s (%s)%s,' % \
- (style.SQL_FIELD(backend.quote_name(f.m2m_reverse_name())),
+ (style.SQL_FIELD(qn(f.m2m_reverse_name())),
style.SQL_COLTYPE(models.ForeignKey(f.rel.to).db_type()),
style.SQL_KEYWORD('NOT NULL REFERENCES'),
- style.SQL_TABLE(backend.quote_name(f.rel.to._meta.db_table)),
- style.SQL_FIELD(backend.quote_name(f.rel.to._meta.pk.column)),
+ style.SQL_TABLE(qn(f.rel.to._meta.db_table)),
+ style.SQL_FIELD(qn(f.rel.to._meta.pk.column)),
connection.ops.deferrable_sql()))
table_output.append(' %s (%s, %s)%s' % \
(style.SQL_KEYWORD('UNIQUE'),
- style.SQL_FIELD(backend.quote_name(f.m2m_column_name())),
- style.SQL_FIELD(backend.quote_name(f.m2m_reverse_name())),
+ style.SQL_FIELD(qn(f.m2m_column_name())),
+ style.SQL_FIELD(qn(f.m2m_reverse_name())),
tablespace_sql))
table_output.append(')')
if opts.db_tablespace and backend.supports_tablespaces:
@@ -350,7 +354,7 @@ def many_to_many_sql_for_model(model, style):
final_output.append('\n'.join(table_output))
# Add any extra SQL needed to support auto-incrementing PKs
- autoinc_sql = backend.get_autoinc_sql(f.m2m_db_table())
+ autoinc_sql = connection.ops.autoinc_sql(f.m2m_db_table())
if autoinc_sql:
for stmt in autoinc_sql:
final_output.append(stmt)
@@ -389,6 +393,7 @@ def sql_indexes_for_model(model, style):
from django.db import backend, connection
output = []
+ qn = connection.ops.quote_name
for f in model._meta.fields:
if f.db_index and not ((f.primary_key or f.unique) and backend.autoindexes_primary_keys):
unique = f.unique and 'UNIQUE ' or ''
@@ -399,10 +404,10 @@ def sql_indexes_for_model(model, style):
tablespace_sql = ''
output.append(
style.SQL_KEYWORD('CREATE %sINDEX' % unique) + ' ' + \
- style.SQL_TABLE(backend.quote_name('%s_%s' % (model._meta.db_table, f.column))) + ' ' + \
+ style.SQL_TABLE(qn('%s_%s' % (model._meta.db_table, f.column))) + ' ' + \
style.SQL_KEYWORD('ON') + ' ' + \
- style.SQL_TABLE(backend.quote_name(model._meta.db_table)) + ' ' + \
- "(%s)" % style.SQL_FIELD(backend.quote_name(f.column)) + \
+ style.SQL_TABLE(qn(model._meta.db_table)) + ' ' + \
+ "(%s)" % style.SQL_FIELD(qn(f.column)) + \
"%s;" % tablespace_sql
)
return output
@@ -134,6 +134,13 @@ def pk_default_value(self):
"""
return 'DEFAULT'
+ def quote_name(self, name):
+ """
+ Returns a quoted version of the given table, index or column name. Does
+ not quote the given name if it's already been quoted.
+ """
+ raise NotImplementedError()
+
def random_function_sql(self):
"""
Returns a SQL expression that returns a random value.
@@ -67,11 +67,16 @@ def last_insert_id(self, cursor, table_name, pk_name):
cursor.execute("SELECT %s FROM %s WHERE %s = @@IDENTITY" % (pk_name, table_name, pk_name))
return cursor.fetchone()[0]
+ def quote_name(self, name):
+ if name.startswith('[') and name.endswith(']'):
+ return name # Quoting once is enough.
+ return '[%s]' % name
+
def random_function_sql(self):
return 'RAND()'
def tablespace_sql(self, tablespace, inline=False):
- return "ON %s" % quote_name(tablespace)
+ return "ON %s" % self.quote_name(tablespace)
class DatabaseWrapper(BaseDatabaseWrapper):
ops = DatabaseOperations()
@@ -97,11 +102,6 @@ def _cursor(self, settings):
supports_tablespaces = True
uses_case_insensitive_names = False
-def quote_name(name):
- if name.startswith('[') and name.endswith(']'):
- return name # Quoting once is enough.
- return '[%s]' % name
-
dictfetchone = util.dictfetchone
dictfetchmany = util.dictfetchmany
dictfetchall = util.dictfetchall
@@ -39,7 +39,6 @@ def close(self):
supports_constraints = False
supports_tablespaces = False
-quote_name = complain
dictfetchone = complain
dictfetchmany = complain
dictfetchall = complain
@@ -84,6 +84,11 @@ def limit_offset_sql(self, limit, offset=None):
sql += "%s," % offset
return sql + str(limit)
+ def quote_name(self, name):
+ if name.startswith("`") and name.endswith("`"):
+ return name # Quoting once is enough.
+ return "`%s`" % name
+
def random_function_sql(self):
return 'RAND()'
@@ -94,15 +99,15 @@ def sql_flush(self, style, tables, sequences):
if tables:
sql = ['SET FOREIGN_KEY_CHECKS = 0;']
for table in tables:
- sql.append('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table))))
+ sql.append('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(self.quote_name(table))))
sql.append('SET FOREIGN_KEY_CHECKS = 1;')
# 'ALTER TABLE table AUTO_INCREMENT = 1;'... style SQL statements
# to reset sequence indices
sql.extend(["%s %s %s %s %s;" % \
(style.SQL_KEYWORD('ALTER'),
style.SQL_KEYWORD('TABLE'),
- style.SQL_TABLE(quote_name(sequence['table'])),
+ style.SQL_TABLE(self.quote_name(sequence['table'])),
style.SQL_KEYWORD('AUTO_INCREMENT'),
style.SQL_FIELD('= 1'),
) for sequence in sequences])
@@ -179,11 +184,6 @@ def get_server_version(self):
supports_tablespaces = False
uses_case_insensitive_names = False
-def quote_name(name):
- if name.startswith("`") and name.endswith("`"):
- return name # Quoting once is enough.
- return "`%s`" % name
-
dictfetchone = util.dictfetchone
dictfetchmany = util.dictfetchmany
dictfetchall = util.dictfetchall
@@ -1,8 +1,9 @@
-from django.db.backends.mysql.base import quote_name
+from django.db.backends.mysql.base import DatabaseOperations
from MySQLdb import ProgrammingError, OperationalError
from MySQLdb.constants import FIELD_TYPE
import re
+quote_name = DatabaseOperations().quote_name
foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
def get_table_list(cursor):
Oops, something went wrong. Retry.

0 comments on commit 221f99e

Please sign in to comment.