Ticket #121: change_all_sql.patch

File change_all_sql.patch, 36.3 KB (added by rmunn@…, 19 years ago)

Patch to quote all SQL identifiers with db.quote_name()

  • django/models/auth.py

     
    8686        if not hasattr(self, '_group_perm_cache'):
    8787            import sets
    8888            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])
    95108            self._group_perm_cache = sets.Set(["%s.%s" % (row[0], row[1]) for row in cursor.fetchall()])
    96109        return self._group_perm_cache
    97110
  • django/bin/daily_cleanup.py

     
    77def clean_up():
    88    # Clean up old database records
    99    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")))
    1212    db.commit()
    1313
    1414if __name__ == "__main__":
  • django/core/management.py

     
    2020ADMIN_TEMPLATE_DIR = os.path.join(django.__path__[0], 'conf/admin_templates')
    2121
    2222def _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)
    2427
    2528def _get_permission_codename(action, opts):
    2629    return '%s_%s' % (action, opts.object_name.lower())
     
    3437    return perms + list(opts.permissions)
    3538
    3639def _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)
    3944
    4045def _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)
    4350
    4451def _is_valid_dir_name(s):
    4552    return bool(re.search(r'^\w+$', s))
     
    6774                data_type = f.__class__.__name__
    6875            col_type = db.DATA_TYPES[data_type]
    6976            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__]
    7178                field_output.append('%sNULL' % (not f.null and 'NOT ' or ''))
    7279                if f.unique:
    7380                    field_output.append('UNIQUE')
     
    7582                    field_output.append('PRIMARY KEY')
    7683                if f.rel:
    7784                    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)))
    7986                table_output.append(' '.join(field_output))
    8087        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']))
    8289        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]))
    8491
    85         full_statement = ['CREATE TABLE %s (' % opts.db_table]
     92        full_statement = ['CREATE TABLE %s (' % db.quote_name(opts.db_table)]
    8693        for i, line in enumerate(table_output): # Combine and add commas.
    8794            full_statement.append('    %s%s' % (line, i < len(table_output)-1 and ',' or ''))
    8895        full_statement.append(');')
     
    9198    for klass in mod._MODELS:
    9299        opts = klass._meta
    93100        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')))
    101112            table_output.append(');')
    102113            final_output.append('\n'.join(table_output))
    103114    return final_output
     
    116127        try:
    117128            if cursor is not None:
    118129                # 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))
    120131        except:
    121132            # The table doesn't exist, so it doesn't need to be dropped.
    122133            db.db.rollback()
    123134        else:
    124             output.append("DROP TABLE %s;" % klass._meta.db_table)
     135            output.append("DROP TABLE %s;" % db.quote_name(klass._meta.db_table))
    125136    for klass in mod._MODELS:
    126137        opts = klass._meta
    127138        for f in opts.many_to_many:
    128139            try:
    129140                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)))
    131142            except:
    132143                db.db.rollback()
    133144            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)))
    135146
    136147    app_label = mod._MODELS[0]._meta.app_label
    137148
    138149    # 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))
    142153
    143154    # Delete from the admin log.
    144155    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])
    146159        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]))
    148161
    149162    return output[::-1] # Reverse it, to deal with table dependencies.
    150163get_sql_delete.help_doc = "Prints the DROP TABLE SQL statements for the given app(s)."
     
    181194
    182195def get_sql_sequence_reset(mod):
    183196    "Returns a list of the SQL statements to reset PostgreSQL sequences for the given module."
    184     from django.core import meta
     197    from django.core import db, meta
    185198    output = []
    186199    for klass in mod._MODELS:
    187200        for f in klass._meta.fields:
    188201            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)))
    190204    return output
    191205get_sql_sequence_reset.help_doc = "Prints the SQL statements for resetting PostgreSQL sequences for the given app(s)."
    192206get_sql_sequence_reset.args = APP_ARGS
    193207
    194208def get_sql_indexes(mod):
    195209    "Returns a list of the CREATE INDEX SQL statements for the given module."
     210    from django.core import db
    196211    output = []
    197212    for klass in mod._MODELS:
    198213        for f in klass._meta.fields:
    199214            if f.db_index:
    200215                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)))
    203219    return output
    204220get_sql_indexes.help_doc = "Prints the CREATE INDEX SQL statements for the given app(s)."
    205221get_sql_indexes.args = APP_ARGS
     
    217233    app_label = mod._MODELS[0]._meta.app_label
    218234
    219235    # 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])
    221239    if cursor.rowcount < 1:
    222240#         sys.stderr.write("The '%s' package isn't installed.\n" % app_label)
    223241        print _get_packages_insert(app_label)
     
    231249        perms_seen.update(dict(perms))
    232250        contenttypes_seen[opts.module_name] = 1
    233251        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))
    235255            if cursor.rowcount < 1:
    236256#                 sys.stderr.write("The '%s.%s' permission doesn't exist.\n" % (app_label, codename))
    237257                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))
    239261        if cursor.rowcount < 1:
    240262#             sys.stderr.write("The '%s.%s' content type doesn't exist.\n" % (app_label, opts.module_name))
    241263            print _get_contenttype_insert(opts)
    242264
    243265    # Check that there aren't any *extra* permissions in the DB that the model
    244266    # 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,))
    246270    for row in cursor.fetchall():
    247271        try:
    248272            perms_seen[row[0]]
    249273        except KeyError:
    250274#             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])
    252277
    253278    # Check that there aren't any *extra* content types in the DB that the
    254279    # 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,))
    256282    for row in cursor.fetchall():
    257283        try:
    258284            contenttypes_seen[row[0]]
    259285        except KeyError:
    260286#             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])
    262289database_check.help_doc = "Checks that everything is installed in the database for the given app(s) and prints SQL statements if needed."
    263290database_check.args = APP_ARGS
    264291
     
    293320        cursor = db.db.cursor()
    294321        for sql in get_sql_create(core) + get_sql_create(auth) + get_sql_initial_data(core) + get_sql_initial_data(auth):
    295322            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")))
    297325    except Exception, e:
    298326        sys.stderr.write("Error: The database couldn't be initialized. Here's the full exception:\n%s\n" % e)
    299327        db.db.rollback()
  • django/core/meta.py

     
    4747capfirst = lambda x: x and x[0].upper() + x[1:]
    4848
    4949# prepares a value for use in a LIKE query
    50 prep_for_like_query = lambda x: str(x).replace("%", "\%").replace("_", "\_")
     50prep_for_like_query = lambda x: str(x).replace("%", r"\%").replace("_", r"\_")
    5151
    5252# returns the <ul> class for a given radio_admin value
    5353get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '')
     
    7272        return new_order_list
    7373
    7474def orderlist2sql(order_list, prefix=''):
     75    if prefix.endswith('.'):
     76        prefix = db.quote_name(prefix[:-1])+'.'
    7577    output = []
    7678    for f in handle_legacy_orderlist(order_list):
    7779        if f.startswith('-'):
    78             output.append('%s%s DESC' % (prefix, f[1:]))
     80            output.append('%s%s DESC' % (prefix, db.quote_name(f[1:])))
    7981        elif f == '?':
    8082            output.append('RANDOM()')
    8183        else:
    82             output.append('%s%s ASC' % (prefix, f))
     84            output.append('%s%s ASC' % (prefix, db.quote_name(f)))
    8385    return ', '.join(output)
    8486
    8587def curry(*args, **kwargs):
     
    740742    # primary key field is set manually.
    741743    if isinstance(opts.pk.rel, OneToOne):
    742744        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)])
    745748        if cursor.rowcount == 0: # If nothing was updated, add the record.
    746             field_names = [f.name for f in opts.fields]
     749            field_names = [db.quote_name(f.name) for f in opts.fields]
    747750            placeholders = ['%s'] * len(field_names)
    748751            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)),
    750753                [f.get_db_prep_save(getattr(self, f.name), add=True) for f in opts.fields])
    751754    else:
    752755        if not add:
    753756            cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \
    754                 (opts.db_table, ','.join(['%s=%%s' % f.name for 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)])
    756759        else:
    757             field_names = [f.name for f in non_pks]
     760            field_names = [db.quote_name(f.name) for f in non_pks]
    758761            placeholders = ['%s'] * len(field_names)
    759762            if opts.order_with_respect_to:
    760                 field_names.append('_order')
     763                field_names.append(db.quote_name('_order'))
    761764                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)))
    763766                db_values.append(getattr(self, opts.order_with_respect_to.name))
    764767            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)
    766769            setattr(self, opts.pk.name, db.get_last_insert_id(cursor, opts.db_table, opts.pk.name))
    767770    db.db.commit()
    768771    # Run any post-save hooks.
     
    785788            for sub_obj in getattr(self, 'get_%s_list' % rel_opts_name)():
    786789                sub_obj.delete()
    787790    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)])
    791794    db.db.commit()
    792795    setattr(self, opts.pk.name, None)
    793796    for f in opts.fields:
     
    801804def method_get_next_in_order(opts, order_field, self):
    802805    if not hasattr(self, '_next_in_order_cache'):
    803806        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,
    806809            params=[getattr(self, opts.pk.name), getattr(self, order_field.name)])
    807810    return self._next_in_order_cache
    808811
    809812def method_get_previous_in_order(opts, order_field, self):
    810813    if not hasattr(self, '_previous_in_order_cache'):
    811814        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,
    814817            params=[getattr(self, opts.pk.name), getattr(self, order_field.name)])
    815818    return self._previous_in_order_cache
    816819
     
    835838    cache_var = '_%s_cache' % field_with_rel.name
    836839    if not hasattr(self, cache_var):
    837840        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'))
    842846        cursor = db.db.cursor()
    843847        cursor.execute(sql, [getattr(self, self._meta.pk.name)])
    844848        setattr(self, cache_var, [getattr(mod, rel.object_name)(*row) for row in cursor.fetchall()])
     
    864868    cursor = db.db.cursor()
    865869    this_id = getattr(self, self._meta.pk.name)
    866870    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)))
    868874        cursor.execute(sql, [this_id])
    869875    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'))
    871878        cursor.executemany(sql, [(this_id, i) for i in ids_to_add])
    872879    db.db.commit()
    873880    try:
     
    910917    m2m_table = rel_field.get_m2m_db_table(rel_opts)
    911918    this_id = getattr(self, self._meta.pk.name)
    912919    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'))
    915924    cursor.executemany(sql, [(this_id, i) for i in id_list])
    916925    db.db.commit()
    917926
     
    920929def method_set_order(ordered_obj, self, id_list):
    921930    cursor = db.db.cursor()
    922931    # 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))
    924934    rel_val = getattr(self, ordered_obj.order_with_respect_to.rel.field_name)
    925935    cursor.executemany(sql, [(i, rel_val, j) for i, j in enumerate(id_list)])
    926936    db.db.commit()
     
    928938def method_get_order(ordered_obj, self):
    929939    cursor = db.db.cursor()
    930940    # 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))
    932943    rel_val = getattr(self, ordered_obj.order_with_respect_to.rel.field_name)
    933944    cursor.execute(sql, [rel_val])
    934945    return [r[0] for r in cursor.fetchall()]
     
    936947# DATE-RELATED METHODS #####################
    937948
    938949def 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 '<')))
    940951    kwargs.setdefault('params', []).append(str(getattr(self, field.name)))
    941952    kwargs['order_by'] = [(not is_next and '-' or '') + field.name]
    942953    kwargs['limit'] = 1
     
    10161027    return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self)
    10171028
    10181029def _get_where_clause(lookup_type, table_prefix, field_name, value):
     1030    if table_prefix.endswith('.'):
     1031        table_prefix = db.quote_name(table_prefix[:-1])+'.'
    10191032    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])
    10211034    except KeyError:
    10221035        pass
    10231036    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]))
    10251038    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))
    10271040    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))
    10291042    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 ''))
    10311044    raise TypeError, "Got invalid lookup_type: %s" % repr(lookup_type)
    10321045
    10331046def function_get_object(opts, klass, does_not_exist_exception, **kwargs):
     
    10921105        if f.rel and not f.null:
    10931106            db_table = f.rel.to.db_table
    10941107            if db_table not in cache_tables_seen:
    1095                 tables.append(db_table)
     1108                tables.append(db.quote_name(db_table))
    10961109            else: # The table was already seen, so give it a table alias.
    10971110                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)))
    10991112                db_table = new_prefix
    11001113            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])
    11031116            _fill_table_cache(f.rel.to, select, tables, where, db_table, cache_tables_seen)
    11041117
    11051118def _throw_bad_kwarg_error(kwarg):
     
    11571170                    if f.name == current:
    11581171                        rel_table_alias = 't%s' % table_count
    11591172                        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")))
    11631176                        # Optimization: In the case of primary-key lookups, we
    11641177                        # don't have to do an extra join.
    11651178                        if lookup_list and lookup_list[0] == f.rel.to.pk.name and lookup_type == 'exact':
     
    11701183                            param_required = False
    11711184                        else:
    11721185                            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)))
    11761189                            current_table_alias = new_table_alias
    11771190                            param_required = True
    11781191                        current_opts = f.rel.to
     
    11891202                            param_required = False
    11901203                        else:
    11911204                            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)))
    11941208                            current_table_alias = new_table_alias
    11951209                            param_required = True
    11961210                        current_opts = f.rel.to
     
    12091223    return tables, join_where, where, params, table_count
    12101224
    12111225def 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]
    12131227    tables = [opts.db_table] + (kwargs.get('tables') and kwargs['tables'][:] or [])
    12141228    where = kwargs.get('where') and kwargs['where'][:] or []
    12151229    params = kwargs.get('params') and kwargs['params'][:] or []
     
    12291243
    12301244    # Add any additional SELECTs passed in via kwargs.
    12311245    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']])
    12331247
    12341248    # ORDER BY clause
    12351249    order_by = []
     
    12401254            # Use the database table as a column prefix if it wasn't given,
    12411255            # and if the requested column isn't a custom SELECT.
    12421256            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) + '.'
    12441258            else:
    12451259                table_prefix = ''
    12461260            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:])))
    12481262            else:
    1249                 order_by.append('%s%s ASC' % (table_prefix, f))
     1263                order_by.append('%s%s ASC' % (table_prefix, db.quote_name(f)))
    12501264    order_by = ", ".join(order_by)
    12511265
    12521266    # LIMIT and OFFSET clauses
     
    12621276def function_get_in_bulk(opts, klass, *args, **kwargs):
    12631277    id_list = args and args[0] or kwargs['id_list']
    12641278    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)))]
    12661280    obj_list = function_get_list(opts, klass, **kwargs)
    12671281    return dict([(o.id, o) for o in obj_list])
    12681282
     
    12821296    assert order in ('ASC', 'DESC'), "'order' must be either 'ASC' or 'DESC'"
    12831297    kwargs['order_by'] = [] # Clear this because it'll mess things up otherwise.
    12841298    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)))
    12861300    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)
    12881302    cursor = db.db.cursor()
    12891303    cursor.execute(sql, params)
    12901304    # We have to manually run typecast_timestamp(str()) on the results, because
Back to Top