Ticket #12923: last_executed_query.patch

File last_executed_query.patch, 2.9 KB (added by Pablo Brasero, 15 years ago)

Patch for DatabaseOperations, with tests for MySQL and SQLite

  • django/db/backends/mysql/base.py

     
    224224        second = '%s-12-31 23:59:59.99'
    225225        return [first % value, second % value]
    226226
     227    def construct_query(self, cursor, sql, params):
     228        return sql % tuple(cursor.connection.literal(param) for param in params)
     229
    227230class DatabaseWrapper(BaseDatabaseWrapper):
    228231
    229232    operators = {
  • django/db/backends/__init__.py

     
    212212        else:
    213213            u_params = dict([(to_unicode(k), to_unicode(v)) for k, v in params.items()])
    214214
    215         return smart_unicode(sql) % u_params
     215        return self.construct_query(cursor, smart_unicode(sql), u_params)
    216216
     217    def construct_query(self, cursor, sql, params):
     218        """
     219        Returns a string of the query that results of composing the
     220        parameters into the given sql template.
     221
     222        `sql` is the raw query containing placeholders, and `params` is the
     223        sequence of parameters. The result is the combination of both.
     224        Additionally, `cursor` is provided for use by backends that may
     225        need it.
     226        """
     227        return sql % tuple(['"' + param.replace('"', '""') + '"' for param in params])
     228
    217229    def last_insert_id(self, cursor, table_name, pk_name):
    218230        """
    219231        Given a cursor object that has just performed an INSERT statement into
  • tests/regressiontests/backends/tests.py

     
    3434            c.execute('DROP TABLE ltext')
    3535            self.assertEquals(long_str, row[0].read())
    3636
     37class LastExecutedQuery(unittest.TestCase):
     38
     39    def test_last_executed_query(self):
     40        c = connection.cursor()
     41        c.execute('CREATE TABLE last_executed_query (example1 VARCHAR(255), example2 VARCHAR(255))')
     42        query = 'INSERT INTO last_executed_query (example1, example2) VALUES (%s, %s)'
     43        args = ('dangerous"string', "more'danger")
     44        c.execute(query, args)
     45       
     46        expectation = {
     47            'django.db.backends.sqlite3': u'INSERT INTO last_executed_query (example1, example2) VALUES ("dangerous""string", "more\'danger")',
     48            'django.db.backends.mysql': u"INSERT INTO last_executed_query (example1, example2) VALUES ('dangerous\\\"string', 'more\\'danger')",
     49        }[settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE']]
     50
     51        self.assertEquals(expectation, connection.ops.last_executed_query(c, query, args))
     52
     53
    3754def connection_created_test(sender, **kwargs):
    3855    print 'connection_created signal'
    3956
Back to Top