Ticket #3460: insertwithreturning.patch

File insertwithreturning.patch, 2.0 KB (added by Seb Potter, 16 years ago)

Replace SELECT CURRVAL with INSERT ... RETURNING for psycopg2 backend.

  • django/db/backends/__init__.py

    diff -r 3758c6563608 django/db/backends/__init__.py
    a b  
    5252    uses_custom_query_class = False
    5353    empty_fetchmany_value = []
    5454    update_can_self_select = True
     55    supports_return_id_from_insert = False
    5556
    5657class BaseDatabaseOperations(object):
    5758    """
  • django/db/backends/postgresql_psycopg2/base.py

    diff -r 3758c6563608 django/db/backends/postgresql_psycopg2/base.py
    a b  
    2323class DatabaseFeatures(BaseDatabaseFeatures):
    2424    needs_datetime_string_cast = False
    2525    needs_upper_for_iops = True
     26    supports_return_id_from_insert = True
    2627
    2728class DatabaseOperations(PostgresqlDatabaseOperations):
    2829    def last_executed_query(self, cursor, sql, params):
  • django/db/models/sql/subqueries.py

    diff -r 3758c6563608 django/db/models/sql/subqueries.py
    a b  
    294294        result = ['INSERT INTO %s' % qn(self.model._meta.db_table)]
    295295        result.append('(%s)' % ', '.join([qn(c) for c in self.columns]))
    296296        result.append('VALUES (%s)' % ', '.join(self.values))
     297        if self.connection.features.supports_return_id_from_insert:
     298            result.append('RETURNING %s.%s' % (qn(self.model._meta.db_table),
     299                                 qn(self.model._meta.pk.column)))
     300
    297301        return ' '.join(result), self.params
    298302
    299303    def execute_sql(self, return_id=False):
    300304        cursor = super(InsertQuery, self).execute_sql(None)
    301         if return_id:
     305        if return_id and self.connection.features.supports_return_id_from_insert:
     306            row_id = cursor.fetchone()[0]
     307            return row_id
     308        elif return_id:
    302309            return self.connection.ops.last_insert_id(cursor,
    303310                    self.model._meta.db_table, self.model._meta.pk.column)
Back to Top