Code

Ticket #967: safe_quoted_tables.diff

File safe_quoted_tables.diff, 1.6 KB (added by freakboy@…, 8 years ago)

Patch for safe quoting of table names in db queries

Line 
1Index: django/core/meta/__init__.py
2===================================================================
3--- django/core/meta/__init__.py        (revision 1508)
4+++ django/core/meta/__init__.py        (working copy)
5@@ -1580,9 +1580,20 @@
6     return tables, join_where, where, params, table_count
7 
8 def function_get_sql_clause(opts, **kwargs):
9+    def quote_only_if_word(word):
10+        """
11+        Helper function used to protect user-provided names that might be
12+        subselects in their own right
13+        """
14+        if word.find(' ')>=0:
15+            return word
16+        else:
17+            return db.db.quote_name(word)
18+
19+    # Construct the fundamental parts of the query: SELECT X FROM Y WHERE Z
20     select = ["%s.%s" % (db.db.quote_name(opts.db_table), db.db.quote_name(f.column)) for f in opts.fields]
21     tables = [opts.db_table] + (kwargs.get('tables') and kwargs['tables'][:] or [])
22-    tables = [db.db.quote_name(t) for t in tables]
23+    tables = [quote_only_if_word(t) for t in tables]
24     where = kwargs.get('where') and kwargs['where'][:] or []
25     params = kwargs.get('params') and kwargs['params'][:] or []
26 
27@@ -1600,11 +1611,6 @@
28         _fill_table_cache(opts, select, tables, where, opts.db_table, [opts.db_table])
29 
30     # Add any additional SELECTs passed in via kwargs.
31-    def quote_only_if_word(word):
32-        if word.find(' ')>=0:
33-            return word
34-        else:
35-            return db.db.quote_name(word)
36     if kwargs.get('select'):
37         select.extend(['(%s) AS %s' % (quote_only_if_word(s[1]), db.db.quote_name(s[0])) for s in kwargs['select']])
38