From 75410228dfd16e49eb3c0ea30b59b4c0d2ea6b03 Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Wed, 15 Apr 2020 02:20:46 -0700 Subject: Fixed #31473 -- Made sql_flush() use RESTART IDENTITY to reset sequences on PostgreSQL. The sql_flush() positional argument sequences is replaced by the boolean keyword-only argument reset_sequences. This ensures that the old function signature can't be used by mistake when upgrading Django. When the new argument is True, the sequences of the truncated tables will reset. Using a single boolean value, rather than a list, allows making a binary yes/no choice as to whether to reset all sequences rather than a working on a completely different set. --- django/db/backends/postgresql/operations.py | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) (limited to 'django/db/backends/postgresql/operations.py') diff --git a/django/db/backends/postgresql/operations.py b/django/db/backends/postgresql/operations.py index dd422af1af..70880d4179 100644 --- a/django/db/backends/postgresql/operations.py +++ b/django/db/backends/postgresql/operations.py @@ -117,28 +117,21 @@ class DatabaseOperations(BaseDatabaseOperations): def set_time_zone_sql(self): return "SET TIME ZONE %s" - def sql_flush(self, style, tables, sequences, allow_cascade=False): + def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if not tables: return [] # Perform a single SQL 'TRUNCATE x, y, z...;' statement. It allows us # to truncate tables referenced by a foreign key in any other table. - tables_sql = ', '.join( - style.SQL_FIELD(self.quote_name(table)) for table in tables - ) + sql_parts = [ + style.SQL_KEYWORD('TRUNCATE'), + ', '.join(style.SQL_FIELD(self.quote_name(table)) for table in tables), + ] + if reset_sequences: + sql_parts.append(style.SQL_KEYWORD('RESTART IDENTITY')) if allow_cascade: - sql = ['%s %s %s;' % ( - style.SQL_KEYWORD('TRUNCATE'), - tables_sql, - style.SQL_KEYWORD('CASCADE'), - )] - else: - sql = ['%s %s;' % ( - style.SQL_KEYWORD('TRUNCATE'), - tables_sql, - )] - sql.extend(self.sequence_reset_by_name_sql(style, sequences)) - return sql + sql_parts.append(style.SQL_KEYWORD('CASCADE')) + return ['%s;' % ' '.join(sql_parts)] def sequence_reset_by_name_sql(self, style, sequences): # 'ALTER SEQUENCE sequence_name RESTART WITH 1;'... style SQL statements -- cgit v1.3