Ticket #121: change_all_sql.patch
File change_all_sql.patch, 36.3 KB (added by , 19 years ago) |
---|
-
django/models/auth.py
86 86 if not hasattr(self, '_group_perm_cache'): 87 87 import sets 88 88 cursor = db.cursor() 89 cursor.execute(""" 90 SELECT p.package, p.codename 91 FROM auth_permissions p, auth_groups_permissions gp, auth_users_groups ug 92 WHERE p.id = gp.permission_id 93 AND gp.group_id = ug.group_id 94 AND ug.user_id = %s""", [self.id]) 89 # The SQL below works out to the following after db quoting: 90 #cursor.execute(""" 91 # SELECT p.package, p.codename 92 # FROM auth_permissions p, auth_groups_permissions gp, auth_users_groups ug 93 # WHERE p.id = gp.permission_id 94 # AND gp.group_id = ug.group_id 95 # AND ug.user_id = %s""", [self.id]) 96 sql = """ 97 SELECT p.%s, p.%s 98 FROM %s p, %s gp, %s ug 99 WHERE p.%s = gp.%s 100 AND gp.%s = ug.%s 101 AND ug.%s = %%s""" % ( 102 db.quote_name("package"), db.quote_name("codename"), 103 db.quote_name("auth_permissions"), db.quote_name("auth_groups_permissions"), db.quote_name("auth_users_groups"), 104 db.quote_name("id"), db.quote_name("permission_id"), 105 db.quote_name("group_id"), db.quote_name("group_id"), 106 db.quote_name("user_id")) 107 cursor.execute(sql, [self.id]) 95 108 self._group_perm_cache = sets.Set(["%s.%s" % (row[0], row[1]) for row in cursor.fetchall()]) 96 109 return self._group_perm_cache 97 110 -
django/bin/daily_cleanup.py
7 7 def clean_up(): 8 8 # Clean up old database records 9 9 cursor = db.cursor() 10 cursor.execute("DELETE FROM auth_sessions WHERE start_time < NOW() - INTERVAL '2 weeks'")11 cursor.execute("DELETE FROM registration_challenges WHERE request_date < NOW() - INTERVAL '1 week'")10 cursor.execute("DELETE FROM %s WHERE %s < NOW() - INTERVAL '2 weeks'" % (db.quote_name("auth_sessions"), db.quote_name("start_time"))) 11 cursor.execute("DELETE FROM %s WHERE %s < NOW() - INTERVAL '1 week'" % (db.quote_name("registration_challenges"), db.quote_name("request_date"))) 12 12 db.commit() 13 13 14 14 if __name__ == "__main__": -
django/core/management.py
20 20 ADMIN_TEMPLATE_DIR = os.path.join(django.__path__[0], 'conf/admin_templates') 21 21 22 22 def _get_packages_insert(app_label): 23 return "INSERT INTO packages (label, name) VALUES ('%s', '%s');" % (app_label, app_label) 23 from django.core import db 24 return "INSERT INTO %s (%s, %s) VALUES ('%s', '%s');" % ( 25 db.quote_name("packages"), db.quote_name("label"), db.quote_name("name"), 26 app_label, app_label) 24 27 25 28 def _get_permission_codename(action, opts): 26 29 return '%s_%s' % (action, opts.object_name.lower()) … … 34 37 return perms + list(opts.permissions) 35 38 36 39 def _get_permission_insert(name, codename, opts): 37 return "INSERT INTO auth_permissions (name, package, codename) VALUES ('%s', '%s', '%s');" % \ 38 (name.replace("'", "''"), opts.app_label, codename) 40 from django.core import db 41 return "INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s');" % ( 42 db.quote_name("auth_permissions"), db.quote_name("name"), db.quote_name("package"), db.quote_name("codename"), 43 name.replace("'", "''"), opts.app_label, codename) 39 44 40 45 def _get_contenttype_insert(opts): 41 return "INSERT INTO content_types (name, package, python_module_name) VALUES ('%s', '%s', '%s');" % \ 42 (opts.verbose_name, opts.app_label, opts.module_name) 46 from django.core import db 47 return "INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s');" % ( 48 db.quote_name("content_types"), db.quote_name("name"), db.quote_name("package"), db.quote_name("python_module_name"), 49 opts.verbose_name, opts.app_label, opts.module_name) 43 50 44 51 def _is_valid_dir_name(s): 45 52 return bool(re.search(r'^\w+$', s)) … … 67 74 data_type = f.__class__.__name__ 68 75 col_type = db.DATA_TYPES[data_type] 69 76 if col_type is not None: 70 field_output = [ f.name, col_type % rel_field.__dict__]77 field_output = [db.quote_name(f.name), col_type % rel_field.__dict__] 71 78 field_output.append('%sNULL' % (not f.null and 'NOT ' or '')) 72 79 if f.unique: 73 80 field_output.append('UNIQUE') … … 75 82 field_output.append('PRIMARY KEY') 76 83 if f.rel: 77 84 field_output.append('REFERENCES %s (%s)' % \ 78 ( f.rel.to.db_table, f.rel.to.get_field(f.rel.field_name).name))85 (db.quote_name(f.rel.to.db_table), db.quote_name(f.rel.to.get_field(f.rel.field_name).name))) 79 86 table_output.append(' '.join(field_output)) 80 87 if opts.order_with_respect_to: 81 table_output.append(' _order %s NULL' % db.DATA_TYPES['IntegerField'])88 table_output.append('%s %s NULL' % (db.quote_name("_order"), db.DATA_TYPES['IntegerField'])) 82 89 for field_constraints in opts.unique_together: 83 table_output.append('UNIQUE (%s)' % ", ".join( field_constraints))90 table_output.append('UNIQUE (%s)' % ", ".join([db.quote_name(s) for s in field_constraints])) 84 91 85 full_statement = ['CREATE TABLE %s (' % opts.db_table]92 full_statement = ['CREATE TABLE %s (' % db.quote_name(opts.db_table)] 86 93 for i, line in enumerate(table_output): # Combine and add commas. 87 94 full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or '')) 88 95 full_statement.append(');') … … 91 98 for klass in mod._MODELS: 92 99 opts = klass._meta 93 100 for f in opts.many_to_many: 94 table_output = ['CREATE TABLE %s (' % f.get_m2m_db_table(opts)] 95 table_output.append(' id %s NOT NULL PRIMARY KEY,' % db.DATA_TYPES['AutoField']) 96 table_output.append(' %s_id %s NOT NULL REFERENCES %s (%s),' % \ 97 (opts.object_name.lower(), db.DATA_TYPES['IntegerField'], opts.db_table, opts.pk.name)) 98 table_output.append(' %s_id %s NOT NULL REFERENCES %s (%s),' % \ 99 (f.rel.to.object_name.lower(), db.DATA_TYPES['IntegerField'], f.rel.to.db_table, f.rel.to.pk.name)) 100 table_output.append(' UNIQUE (%s_id, %s_id)' % (opts.object_name.lower(), f.rel.to.object_name.lower())) 101 table_output = ['CREATE TABLE %s (' % db.quote_name(f.get_m2m_db_table(opts))] 102 table_output.append(' %s %s NOT NULL PRIMARY KEY,' % ( 103 db.quote_name("id"), db.DATA_TYPES['AutoField'])) 104 table_output.append(' %s %s NOT NULL REFERENCES %s (%s),' % ( 105 db.quote_name(opts.object_name.lower() + '_id'), db.DATA_TYPES['IntegerField'], 106 db.quote_name(opts.db_table), db.quote_name(opts.pk.name))) 107 table_output.append(' %s %s NOT NULL REFERENCES %s (%s),' % ( 108 db.quote_name(f.rel.to.object_name.lower() + '_id'), db.DATA_TYPES['IntegerField'], 109 db.quote_name(f.rel.to.db_table), db.quote_name(f.rel.to.pk.name))) 110 table_output.append(' UNIQUE (%s, %s)' % ( 111 db.quote_name(opts.object_name.lower() + '_id'), db.quote_name(f.rel.to.object_name.lower() + '_id'))) 101 112 table_output.append(');') 102 113 final_output.append('\n'.join(table_output)) 103 114 return final_output … … 116 127 try: 117 128 if cursor is not None: 118 129 # Check whether the table exists. 119 cursor.execute("SELECT 1 FROM %s LIMIT 1" % klass._meta.db_table)130 cursor.execute("SELECT 1 FROM %s LIMIT 1" % db.quote_name(klass._meta.db_table)) 120 131 except: 121 132 # The table doesn't exist, so it doesn't need to be dropped. 122 133 db.db.rollback() 123 134 else: 124 output.append("DROP TABLE %s;" % klass._meta.db_table)135 output.append("DROP TABLE %s;" % db.quote_name(klass._meta.db_table)) 125 136 for klass in mod._MODELS: 126 137 opts = klass._meta 127 138 for f in opts.many_to_many: 128 139 try: 129 140 if cursor is not None: 130 cursor.execute("SELECT 1 FROM %s LIMIT 1" % f.get_m2m_db_table(opts))141 cursor.execute("SELECT 1 FROM %s LIMIT 1" % db.quote_name(f.get_m2m_db_table(opts))) 131 142 except: 132 143 db.db.rollback() 133 144 else: 134 output.append("DROP TABLE %s;" % f.get_m2m_db_table(opts))145 output.append("DROP TABLE %s;" % db.quote_name(f.get_m2m_db_table(opts))) 135 146 136 147 app_label = mod._MODELS[0]._meta.app_label 137 148 138 149 # Delete from packages, auth_permissions, content_types. 139 output.append("DELETE FROM packages WHERE label = '%s';" % app_label)140 output.append("DELETE FROM auth_permissions WHERE package = '%s';" % app_label)141 output.append("DELETE FROM content_types WHERE package = '%s';" % app_label)150 output.append("DELETE FROM %s WHERE %s = '%s';" % (db.quote_name("packages"), db.quote_name("label"), app_label)) 151 output.append("DELETE FROM %s WHERE %s = '%s';" % (db.quote_name("auth_permissions"), db.quote_name("package"), app_label)) 152 output.append("DELETE FROM %s WHERE %s = '%s';" % (db.quote_name("content_types"), db.quote_name("package"), app_label)) 142 153 143 154 # Delete from the admin log. 144 155 if cursor is not None: 145 cursor.execute("SELECT id FROM content_types WHERE package = %s", [app_label]) 156 cursor.execute("SELECT %s FROM %s WHERE %s = %%s" % ( 157 db.quote_name("id"), db.quote_name("content_types"), db.quote_name("package")), 158 [app_label]) 146 159 for row in cursor.fetchall(): 147 output.append("DELETE FROM auth_admin_log WHERE content_type_id = %s;" % row[0])160 output.append("DELETE FROM %s WHERE %s = %s;" % (db.quote_name("auth_admin_log"), db.quote_name("content_type_id"), row[0])) 148 161 149 162 return output[::-1] # Reverse it, to deal with table dependencies. 150 163 get_sql_delete.help_doc = "Prints the DROP TABLE SQL statements for the given app(s)." … … 181 194 182 195 def get_sql_sequence_reset(mod): 183 196 "Returns a list of the SQL statements to reset PostgreSQL sequences for the given module." 184 from django.core import meta197 from django.core import db, meta 185 198 output = [] 186 199 for klass in mod._MODELS: 187 200 for f in klass._meta.fields: 188 201 if isinstance(f, meta.AutoField): 189 output.append("SELECT setval('%s_%s_seq', (SELECT max(%s) FROM %s));" % (klass._meta.db_table, f.name, f.name, klass._meta.db_table)) 202 output.append("SELECT setval('%s_%s_seq', (SELECT max(%s) FROM %s));" % (klass._meta.db_table, f.name, 203 db.quote_name(f.name), db.quote_name(klass._meta.db_table))) 190 204 return output 191 205 get_sql_sequence_reset.help_doc = "Prints the SQL statements for resetting PostgreSQL sequences for the given app(s)." 192 206 get_sql_sequence_reset.args = APP_ARGS 193 207 194 208 def get_sql_indexes(mod): 195 209 "Returns a list of the CREATE INDEX SQL statements for the given module." 210 from django.core import db 196 211 output = [] 197 212 for klass in mod._MODELS: 198 213 for f in klass._meta.fields: 199 214 if f.db_index: 200 215 unique = f.unique and "UNIQUE " or "" 201 output.append("CREATE %sINDEX %s_%s ON %s (%s);" % \ 202 (unique, klass._meta.db_table, f.name, klass._meta.db_table, f.name)) 216 output.append("CREATE %sINDEX %s ON %s (%s);" % \ 217 (unique, db.quote_name(klass._meta.db_table + '_' + f.name), 218 db.quote_name(klass._meta.db_table), db.quote_name(f.name))) 203 219 return output 204 220 get_sql_indexes.help_doc = "Prints the CREATE INDEX SQL statements for the given app(s)." 205 221 get_sql_indexes.args = APP_ARGS … … 217 233 app_label = mod._MODELS[0]._meta.app_label 218 234 219 235 # Check that the package exists in the database. 220 cursor.execute("SELECT 1 FROM packages WHERE label = %s", [app_label]) 236 cursor.execute("SELECT 1 FROM %s WHERE %s = %%s" % ( 237 db.quote_name("package"), db.quote_name("label")), 238 [app_label]) 221 239 if cursor.rowcount < 1: 222 240 # sys.stderr.write("The '%s' package isn't installed.\n" % app_label) 223 241 print _get_packages_insert(app_label) … … 231 249 perms_seen.update(dict(perms)) 232 250 contenttypes_seen[opts.module_name] = 1 233 251 for codename, name in perms: 234 cursor.execute("SELECT 1 FROM auth_permissions WHERE package = %s AND codename = %s", (app_label, codename)) 252 cursor.execute("SELECT 1 FROM %s WHERE %s = %%s AND %s = %%s" % ( 253 db.quote_name("auth_permissions"), db.quote_name("package"), db.quote_name("codename")), 254 (app_label, codename)) 235 255 if cursor.rowcount < 1: 236 256 # sys.stderr.write("The '%s.%s' permission doesn't exist.\n" % (app_label, codename)) 237 257 print _get_permission_insert(name, codename, opts) 238 cursor.execute("SELECT 1 FROM content_types WHERE package = %s AND python_module_name = %s", (app_label, opts.module_name)) 258 cursor.execute("SELECT 1 FROM %s WHERE %s = %%s AND %s = %%s" % ( 259 db.quote_name("content_types"), db.quote_name("package"), db.quote_name("python_module_name")), 260 (app_label, opts.module_name)) 239 261 if cursor.rowcount < 1: 240 262 # sys.stderr.write("The '%s.%s' content type doesn't exist.\n" % (app_label, opts.module_name)) 241 263 print _get_contenttype_insert(opts) 242 264 243 265 # Check that there aren't any *extra* permissions in the DB that the model 244 266 # doesn't know about. 245 cursor.execute("SELECT codename FROM auth_permissions WHERE package = %s", (app_label,)) 267 cursor.execute("SELECT %s FROM %s WHERE %s = %%s" % ( 268 db.quote_name("codename"), db.quote_name("auth_permissions"), db.quote_name("package")), 269 (app_label,)) 246 270 for row in cursor.fetchall(): 247 271 try: 248 272 perms_seen[row[0]] 249 273 except KeyError: 250 274 # sys.stderr.write("A permission called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0])) 251 print "DELETE FROM auth_permissions WHERE package='%s' AND codename = '%s';" % (app_label, row[0]) 275 print "DELETE FROM %s WHERE %s='%s' AND %s = '%s';" % (db.quote_name("auth_permissions"), 276 db.quote_name("package"), app_label, db.quote_name("codename"), row[0]) 252 277 253 278 # Check that there aren't any *extra* content types in the DB that the 254 279 # model doesn't know about. 255 cursor.execute("SELECT python_module_name FROM content_types WHERE package = %s", (app_label,)) 280 cursor.execute("SELECT %s FROM %s WHERE %s = %%s" % (db.quote_name("python_module_name"), 281 db.quote_name("content_types"), db.quote_name("package")), (app_label,)) 256 282 for row in cursor.fetchall(): 257 283 try: 258 284 contenttypes_seen[row[0]] 259 285 except KeyError: 260 286 # sys.stderr.write("A content type called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0])) 261 print "DELETE FROM content_types WHERE package='%s' AND python_module_name = '%s';" % (app_label, row[0]) 287 print "DELETE FROM %s WHERE %s='%s' AND %s = '%s';" % (db.quote_name("content_types"), 288 db.quote_name("package"), app_label, db.quote_name("python_module_name"), row[0]) 262 289 database_check.help_doc = "Checks that everything is installed in the database for the given app(s) and prints SQL statements if needed." 263 290 database_check.args = APP_ARGS 264 291 … … 293 320 cursor = db.db.cursor() 294 321 for sql in get_sql_create(core) + get_sql_create(auth) + get_sql_initial_data(core) + get_sql_initial_data(auth): 295 322 cursor.execute(sql) 296 cursor.execute("INSERT INTO %s (domain, name) VALUES ('mysite.com', 'My Django site')" % core.Site._meta.db_table) 323 cursor.execute("INSERT INTO %s (%s, %s) VALUES ('mysite.com', 'My Django site')" % (db.quote_name(core.Site._meta.db_table), 324 db.quote_name("domain"), db.quote_name("name"))) 297 325 except Exception, e: 298 326 sys.stderr.write("Error: The database couldn't be initialized. Here's the full exception:\n%s\n" % e) 299 327 db.db.rollback() -
django/core/meta.py
47 47 capfirst = lambda x: x and x[0].upper() + x[1:] 48 48 49 49 # prepares a value for use in a LIKE query 50 prep_for_like_query = lambda x: str(x).replace("%", "\%").replace("_","\_")50 prep_for_like_query = lambda x: str(x).replace("%", r"\%").replace("_", r"\_") 51 51 52 52 # returns the <ul> class for a given radio_admin value 53 53 get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '') … … 72 72 return new_order_list 73 73 74 74 def orderlist2sql(order_list, prefix=''): 75 if prefix.endswith('.'): 76 prefix = db.quote_name(prefix[:-1])+'.' 75 77 output = [] 76 78 for f in handle_legacy_orderlist(order_list): 77 79 if f.startswith('-'): 78 output.append('%s%s DESC' % (prefix, f[1:]))80 output.append('%s%s DESC' % (prefix, db.quote_name(f[1:]))) 79 81 elif f == '?': 80 82 output.append('RANDOM()') 81 83 else: 82 output.append('%s%s ASC' % (prefix, f))84 output.append('%s%s ASC' % (prefix, db.quote_name(f))) 83 85 return ', '.join(output) 84 86 85 87 def curry(*args, **kwargs): … … 740 742 # primary key field is set manually. 741 743 if isinstance(opts.pk.rel, OneToOne): 742 744 cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \ 743 (opts.db_table, ','.join(['%s=%%s' % f.name for f in non_pks]), 744 opts.pk.name), db_values + [getattr(self, opts.pk.name)]) 745 (db.quote_name(opts.db_table), 746 ','.join(['%s=%%s' % db.quote_name(f.name) for f in non_pks]), 747 db.quote_name(opts.pk.name)), db_values + [getattr(self, opts.pk.name)]) 745 748 if cursor.rowcount == 0: # If nothing was updated, add the record. 746 field_names = [ f.namefor f in opts.fields]749 field_names = [db.quote_name(f.name) for f in opts.fields] 747 750 placeholders = ['%s'] * len(field_names) 748 751 cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \ 749 ( opts.db_table, ','.join(field_names), ','.join(placeholders)),752 (db.quote_name(opts.db_table), ','.join(field_names), ','.join(placeholders)), 750 753 [f.get_db_prep_save(getattr(self, f.name), add=True) for f in opts.fields]) 751 754 else: 752 755 if not add: 753 756 cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \ 754 ( opts.db_table, ','.join(['%s=%%s' % f.namefor f in non_pks]),755 opts.pk.name), db_values + [getattr(self, opts.pk.name)])757 (db.quote_name(opts.db_table), ','.join(['%s=%%s' % db.quote_name(f.name) for f in non_pks]), 758 db.quote_name(opts.pk.name)), db_values + [getattr(self, opts.pk.name)]) 756 759 else: 757 field_names = [ f.namefor f in non_pks]760 field_names = [db.quote_name(f.name) for f in non_pks] 758 761 placeholders = ['%s'] * len(field_names) 759 762 if opts.order_with_respect_to: 760 field_names.append( '_order')763 field_names.append(db.quote_name('_order')) 761 764 placeholders.append('(SELECT COUNT(*) FROM %s WHERE %s = %%s)' % \ 762 ( opts.db_table, opts.order_with_respect_to.name))765 (db.quote_name(opts.db_table), db.quote_name(opts.order_with_respect_to.name))) 763 766 db_values.append(getattr(self, opts.order_with_respect_to.name)) 764 767 cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \ 765 ( opts.db_table, ','.join(field_names), ','.join(placeholders)), db_values)768 (db.quote_name(opts.db_table), ','.join(field_names), ','.join(placeholders)), db_values) 766 769 setattr(self, opts.pk.name, db.get_last_insert_id(cursor, opts.db_table, opts.pk.name)) 767 770 db.db.commit() 768 771 # Run any post-save hooks. … … 785 788 for sub_obj in getattr(self, 'get_%s_list' % rel_opts_name)(): 786 789 sub_obj.delete() 787 790 for rel_opts, rel_field in opts.get_all_related_many_to_many_objects(): 788 cursor.execute("DELETE FROM %s WHERE %s _id=%%s" % (rel_field.get_m2m_db_table(rel_opts),789 self._meta.object_name.lower()), [getattr(self, opts.pk.name)])790 cursor.execute("DELETE FROM %s WHERE %s=%%s" % ( opts.db_table, opts.pk.name), [getattr(self, opts.pk.name)])791 cursor.execute("DELETE FROM %s WHERE %s=%%s" % (db.quote_name(rel_field.get_m2m_db_table(rel_opts)), 792 db.quote_name(self._meta.object_name.lower()) + '_id'), [getattr(self, opts.pk.name)]) 793 cursor.execute("DELETE FROM %s WHERE %s=%%s" % (db.quote_name(opts.db_table), db.quote_name(opts.pk.name)), [getattr(self, opts.pk.name)]) 791 794 db.db.commit() 792 795 setattr(self, opts.pk.name, None) 793 796 for f in opts.fields: … … 801 804 def method_get_next_in_order(opts, order_field, self): 802 805 if not hasattr(self, '_next_in_order_cache'): 803 806 self._next_in_order_cache = opts.get_model_module().get_object(order_by=('_order',), 804 where=['_order > (SELECT _order FROM %s WHERE %s=%%s)' % ( opts.db_table, opts.pk.name),805 '%s=%%s' % order_field.name], limit=1,807 where=['_order > (SELECT _order FROM %s WHERE %s=%%s)' % (db.quote_name(opts.db_table), db.quote_name(opts.pk.name)), 808 '%s=%%s' % db.quote_name(order_field.name)], limit=1, 806 809 params=[getattr(self, opts.pk.name), getattr(self, order_field.name)]) 807 810 return self._next_in_order_cache 808 811 809 812 def method_get_previous_in_order(opts, order_field, self): 810 813 if not hasattr(self, '_previous_in_order_cache'): 811 814 self._previous_in_order_cache = opts.get_model_module().get_object(order_by=('-_order',), 812 where=['_order < (SELECT _order FROM %s WHERE %s=%%s)' % ( opts.db_table, opts.pk.name),813 '%s=%%s' % order_field.name], limit=1,815 where=['_order < (SELECT _order FROM %s WHERE %s=%%s)' % (db.quote_name(opts.db_table), db.quote_name(opts.pk.name)), 816 '%s=%%s' % db.quote_name(order_field.name)], limit=1, 814 817 params=[getattr(self, opts.pk.name), getattr(self, order_field.name)]) 815 818 return self._previous_in_order_cache 816 819 … … 835 838 cache_var = '_%s_cache' % field_with_rel.name 836 839 if not hasattr(self, cache_var): 837 840 mod = rel.get_model_module() 838 sql = "SELECT %s FROM %s a, %s b WHERE a.%s = b.%s_id AND b.%s_id = %%s %s" % \ 839 (','.join(['a.%s' % f.name for f in rel.fields]), rel.db_table, 840 field_with_rel.get_m2m_db_table(self._meta), rel.pk.name, 841 rel.object_name.lower(), self._meta.object_name.lower(), rel.get_order_sql('a')) 841 sql = "SELECT %s FROM %s a, %s b WHERE a.%s = b.%s AND b.%s = %%s %s" % \ 842 (','.join(['a.%s' % db.quote_name(f.name) for f in rel.fields]), db.quote_name(rel.db_table), 843 db.quote_name(field_with_rel.get_m2m_db_table(self._meta)), db.quote_name(rel.pk.name), 844 db.quote_name(rel.object_name.lower() + '_id'), db.quote_name(self._meta.object_name.lower() + '_id'), 845 rel.get_order_sql('a')) 842 846 cursor = db.db.cursor() 843 847 cursor.execute(sql, [getattr(self, self._meta.pk.name)]) 844 848 setattr(self, cache_var, [getattr(mod, rel.object_name)(*row) for row in cursor.fetchall()]) … … 864 868 cursor = db.db.cursor() 865 869 this_id = getattr(self, self._meta.pk.name) 866 870 if ids_to_delete: 867 sql = "DELETE FROM %s WHERE %s_id = %%s AND %s_id IN (%s)" % (m2m_table, self._meta.object_name.lower(), rel.object_name.lower(), ','.join(map(str, ids_to_delete))) 871 sql = "DELETE FROM %s WHERE %s = %%s AND %s IN (%s)" % (db.quote_name(m2m_table), 872 db.quote_name(self._meta.object_name.lower() + '_id'), db.quote_name(rel.object_name.lower() + '_id'), 873 ','.join(map(str, ids_to_delete))) 868 874 cursor.execute(sql, [this_id]) 869 875 if ids_to_add: 870 sql = "INSERT INTO %s (%s_id, %s_id) VALUES (%%s, %%s)" % (m2m_table, self._meta.object_name.lower(), rel.object_name.lower()) 876 sql = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (db.quote_name(m2m_table), 877 db.quote_name(self._meta.object_name.lower() + '_id'), db.quote_name(rel.object_name.lower() + '_id')) 871 878 cursor.executemany(sql, [(this_id, i) for i in ids_to_add]) 872 879 db.db.commit() 873 880 try: … … 910 917 m2m_table = rel_field.get_m2m_db_table(rel_opts) 911 918 this_id = getattr(self, self._meta.pk.name) 912 919 cursor = db.db.cursor() 913 cursor.execute("DELETE FROM %s WHERE %s_id = %%s" % (m2m_table, rel.object_name.lower()), [this_id]) 914 sql = "INSERT INTO %s (%s_id, %s_id) VALUES (%%s, %%s)" % (m2m_table, rel.object_name.lower(), rel_opts.object_name.lower()) 920 cursor.execute("DELETE FROM %s WHERE %s = %%s" % (db.quote_name(m2m_table), db.quote_name(rel.object_name.lower() + '_id')), [this_id]) 921 sql = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (db.quote_name(m2m_table), 922 db.quote_name(rel.object_name.lower() + '_id'), 923 db.quote_name(rel_opts.object_name.lower() + '_id')) 915 924 cursor.executemany(sql, [(this_id, i) for i in id_list]) 916 925 db.db.commit() 917 926 … … 920 929 def method_set_order(ordered_obj, self, id_list): 921 930 cursor = db.db.cursor() 922 931 # Example: "UPDATE poll_choices SET _order = %s WHERE poll_id = %s AND id = %s" 923 sql = "UPDATE %s SET _order = %%s WHERE %s = %%s AND %s = %%s" % (ordered_obj.db_table, ordered_obj.order_with_respect_to.name, ordered_obj.pk.name) 932 sql = "UPDATE %s SET _order = %%s WHERE %s = %%s AND %s = %%s" % (db.quote_name(ordered_obj.db_table), 933 db.quote_name(ordered_obj.order_with_respect_to.name), db.quote_name(ordered_obj.pk.name)) 924 934 rel_val = getattr(self, ordered_obj.order_with_respect_to.rel.field_name) 925 935 cursor.executemany(sql, [(i, rel_val, j) for i, j in enumerate(id_list)]) 926 936 db.db.commit() … … 928 938 def method_get_order(ordered_obj, self): 929 939 cursor = db.db.cursor() 930 940 # Example: "SELECT id FROM poll_choices WHERE poll_id = %s ORDER BY _order" 931 sql = "SELECT %s FROM %s WHERE %s = %%s ORDER BY _order" % (ordered_obj.pk.name, ordered_obj.db_table, ordered_obj.order_with_respect_to.name) 941 sql = "SELECT %s FROM %s WHERE %s = %%s ORDER BY _order" % (db.quote_name(ordered_obj.pk.name), 942 db.quote_name(ordered_obj.db_table), db.quote_name(ordered_obj.order_with_respect_to.name)) 932 943 rel_val = getattr(self, ordered_obj.order_with_respect_to.rel.field_name) 933 944 cursor.execute(sql, [rel_val]) 934 945 return [r[0] for r in cursor.fetchall()] … … 936 947 # DATE-RELATED METHODS ##################### 937 948 938 949 def method_get_next_or_previous(get_object_func, field, is_next, self, **kwargs): 939 kwargs.setdefault('where', []).append('%s %s %%s' % ( field.name, (is_next and '>' or '<')))950 kwargs.setdefault('where', []).append('%s %s %%s' % (db.quote_name(field.name), (is_next and '>' or '<'))) 940 951 kwargs.setdefault('params', []).append(str(getattr(self, field.name))) 941 952 kwargs['order_by'] = [(not is_next and '-' or '') + field.name] 942 953 kwargs['limit'] = 1 … … 1016 1027 return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self) 1017 1028 1018 1029 def _get_where_clause(lookup_type, table_prefix, field_name, value): 1030 if table_prefix.endswith('.'): 1031 table_prefix = db.quote_name(table_prefix[:-1])+'.' 1019 1032 try: 1020 return '%s%s %s %%s' % (table_prefix, field_name, db.OPERATOR_MAPPING[lookup_type])1033 return '%s%s %s %%s' % (table_prefix, db.quote_name(field_name), db.OPERATOR_MAPPING[lookup_type]) 1021 1034 except KeyError: 1022 1035 pass 1023 1036 if lookup_type == 'in': 1024 return '%s%s IN (%s)' % (table_prefix, field_name, ','.join(['%s' for v in value]))1037 return '%s%s IN (%s)' % (table_prefix, db.quote_name(field_name), ','.join(['%s' for v in value])) 1025 1038 elif lookup_type in ('range', 'year'): 1026 return '%s%s BETWEEN %%s AND %%s' % (table_prefix, field_name)1039 return '%s%s BETWEEN %%s AND %%s' % (table_prefix, db.quote_name(field_name)) 1027 1040 elif lookup_type in ('month', 'day'): 1028 return "%s = %%s" % db.get_date_extract_sql(lookup_type, table_prefix + field_name)1041 return "%s = %%s" % db.get_date_extract_sql(lookup_type, table_prefix + db.quote_name(field_name)) 1029 1042 elif lookup_type == 'isnull': 1030 return "%s%s IS %sNULL" % (table_prefix, field_name, (not value and 'NOT ' or ''))1043 return "%s%s IS %sNULL" % (table_prefix, db.quote_name(field_name), (not value and 'NOT ' or '')) 1031 1044 raise TypeError, "Got invalid lookup_type: %s" % repr(lookup_type) 1032 1045 1033 1046 def function_get_object(opts, klass, does_not_exist_exception, **kwargs): … … 1092 1105 if f.rel and not f.null: 1093 1106 db_table = f.rel.to.db_table 1094 1107 if db_table not in cache_tables_seen: 1095 tables.append(db _table)1108 tables.append(db.quote_name(db_table)) 1096 1109 else: # The table was already seen, so give it a table alias. 1097 1110 new_prefix = '%s%s' % (db_table, len(cache_tables_seen)) 1098 tables.append('%s %s' % (db _table, new_prefix))1111 tables.append('%s %s' % (db.quote_name(db_table), db.quote_name(new_prefix))) 1099 1112 db_table = new_prefix 1100 1113 cache_tables_seen.append(db_table) 1101 where.append('%s.%s = %s.%s' % ( old_prefix, f.name, db_table, f.rel.field_name))1102 select.extend(['%s.%s' % (db _table, f2.name) for f2 in f.rel.to.fields])1114 where.append('%s.%s = %s.%s' % (db.quote_name(old_prefix), db.quote_name(f.name), db.quote_name(db_table), db.quote_name(f.rel.field_name))) 1115 select.extend(['%s.%s' % (db.quote_name(db_table), db.quote_name(f2.name)) for f2 in f.rel.to.fields]) 1103 1116 _fill_table_cache(f.rel.to, select, tables, where, db_table, cache_tables_seen) 1104 1117 1105 1118 def _throw_bad_kwarg_error(kwarg): … … 1157 1170 if f.name == current: 1158 1171 rel_table_alias = 't%s' % table_count 1159 1172 table_count += 1 1160 tables.append('%s %s' % ( f.get_m2m_db_table(current_opts), rel_table_alias))1161 join_where.append('%s.%s = %s.%s _id' % (current_table_alias, current_opts.pk.name,1162 rel_table_alias, current_opts.object_name.lower()))1173 tables.append('%s %s' % (db.quote_name(f.get_m2m_db_table(current_opts)), db.quote_name(rel_table_alias))) 1174 join_where.append('%s.%s = %s.%s' % (db.quote_name(current_table_alias), db.quote_name(current_opts.pk.name), 1175 db.quote_name(rel_table_alias), db.quote_name(current_opts.object_name.lower() + "_id"))) 1163 1176 # Optimization: In the case of primary-key lookups, we 1164 1177 # don't have to do an extra join. 1165 1178 if lookup_list and lookup_list[0] == f.rel.to.pk.name and lookup_type == 'exact': … … 1170 1183 param_required = False 1171 1184 else: 1172 1185 new_table_alias = 't%s' % table_count 1173 tables.append('%s %s' % ( f.rel.to.db_table, new_table_alias))1174 join_where.append('%s.%s _id = %s.%s' % (rel_table_alias, f.rel.to.object_name.lower(),1175 new_table_alias, f.rel.to.pk.name))1186 tables.append('%s %s' % (db.quote_name(f.rel.to.db_table), db.quote_name(new_table_alias))) 1187 join_where.append('%s.%s = %s.%s' % (db.quote_name(rel_table_alias), db.quote_name(f.rel.to.object_name.lower() + "_id"), 1188 db.quote_name(new_table_alias), db.quote_name(f.rel.to.pk.name))) 1176 1189 current_table_alias = new_table_alias 1177 1190 param_required = True 1178 1191 current_opts = f.rel.to … … 1189 1202 param_required = False 1190 1203 else: 1191 1204 new_table_alias = 't%s' % table_count 1192 tables.append('%s %s' % (f.rel.to.db_table, new_table_alias)) 1193 join_where.append('%s.%s = %s.%s' % (current_table_alias, f.name, new_table_alias, f.rel.to.pk.name)) 1205 tables.append('%s %s' % (db.quote_name(f.rel.to.db_table), db.quote_name(new_table_alias))) 1206 join_where.append('%s.%s = %s.%s' % (db.quote_name(current_table_alias), db.quote_name(f.name), 1207 db.quote_name(new_table_alias), db.quote_name(f.rel.to.pk.name))) 1194 1208 current_table_alias = new_table_alias 1195 1209 param_required = True 1196 1210 current_opts = f.rel.to … … 1209 1223 return tables, join_where, where, params, table_count 1210 1224 1211 1225 def function_get_sql_clause(opts, **kwargs): 1212 select = ["%s.%s" % ( opts.db_table, f.name) for f in opts.fields]1226 select = ["%s.%s" % (db.quote_name(opts.db_table), db.quote_name(f.name)) for f in opts.fields] 1213 1227 tables = [opts.db_table] + (kwargs.get('tables') and kwargs['tables'][:] or []) 1214 1228 where = kwargs.get('where') and kwargs['where'][:] or [] 1215 1229 params = kwargs.get('params') and kwargs['params'][:] or [] … … 1229 1243 1230 1244 # Add any additional SELECTs passed in via kwargs. 1231 1245 if kwargs.get('select', False): 1232 select.extend(['(%s) AS %s' % ( s[1], s[0]) for s in kwargs['select']])1246 select.extend(['(%s) AS %s' % (db.quote_name(s[1]), db.quote_name(s[0])) for s in kwargs['select']]) 1233 1247 1234 1248 # ORDER BY clause 1235 1249 order_by = [] … … 1240 1254 # Use the database table as a column prefix if it wasn't given, 1241 1255 # and if the requested column isn't a custom SELECT. 1242 1256 if "." not in f and f not in [k[0] for k in kwargs.get('select', [])]: 1243 table_prefix = opts.db_table+ '.'1257 table_prefix = db.quote_name(opts.db_table) + '.' 1244 1258 else: 1245 1259 table_prefix = '' 1246 1260 if f.startswith('-'): 1247 order_by.append('%s%s DESC' % (table_prefix, f[1:]))1261 order_by.append('%s%s DESC' % (table_prefix, db.quote_name(f[1:]))) 1248 1262 else: 1249 order_by.append('%s%s ASC' % (table_prefix, f))1263 order_by.append('%s%s ASC' % (table_prefix, db.quote_name(f))) 1250 1264 order_by = ", ".join(order_by) 1251 1265 1252 1266 # LIMIT and OFFSET clauses … … 1262 1276 def function_get_in_bulk(opts, klass, *args, **kwargs): 1263 1277 id_list = args and args[0] or kwargs['id_list'] 1264 1278 assert id_list != [], "get_in_bulk() cannot be passed an empty list." 1265 kwargs['where'] = ["%s. id IN (%s)" % (opts.db_table, ",".join(map(str, id_list)))]1279 kwargs['where'] = ["%s.%s IN (%s)" % (db.quote_name(opts.db_table), db.quote_name("id"), ",".join(map(str, id_list)))] 1266 1280 obj_list = function_get_list(opts, klass, **kwargs) 1267 1281 return dict([(o.id, o) for o in obj_list]) 1268 1282 … … 1282 1296 assert order in ('ASC', 'DESC'), "'order' must be either 'ASC' or 'DESC'" 1283 1297 kwargs['order_by'] = [] # Clear this because it'll mess things up otherwise. 1284 1298 if field.null: 1285 kwargs.setdefault('where', []).append('%s.%s IS NOT NULL' % ( opts.db_table, field.name))1299 kwargs.setdefault('where', []).append('%s.%s IS NOT NULL' % (db.quote_name(opts.db_table), db.quote_name(field.name))) 1286 1300 select, sql, params = function_get_sql_clause(opts, **kwargs) 1287 sql = 'SELECT %s %s GROUP BY 1 ORDER BY 1' % (db.get_date_trunc_sql(kind, '%s.%s' % ( opts.db_table, field.name)), sql)1301 sql = 'SELECT %s %s GROUP BY 1 ORDER BY 1' % (db.get_date_trunc_sql(kind, '%s.%s' % (db.quote_name(opts.db_table), db.quote_name(field.name))), sql) 1288 1302 cursor = db.db.cursor() 1289 1303 cursor.execute(sql, params) 1290 1304 # We have to manually run typecast_timestamp(str()) on the results, because