From c13dd65d28cdae132574030ade581a96e49a6c50 Mon Sep 17 00:00:00 2001 From: David Sanders <> Date: Mon, 1 Apr 2024 22:13:51 +1100 Subject: [PATCH] Update reset sequence sql to allow restarting sequences --- django/db/backends/oracle/operations.py | 35 +++++++++++-------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py index 15edb292b8..e4838f3a2f 100644 --- a/django/db/backends/oracle/operations.py +++ b/django/db/backends/oracle/operations.py @@ -38,25 +38,24 @@ class DatabaseOperations(BaseDatabaseOperations): # TODO: colorize this SQL code with style.SQL_KEYWORD(), etc. _sequence_reset_sql = """ DECLARE - table_value integer; - seq_value integer; - seq_name user_tab_identity_cols.sequence_name%%TYPE; + identity_col_found integer; + new_start integer; BEGIN - BEGIN - SELECT sequence_name INTO seq_name FROM user_tab_identity_cols - WHERE table_name = '%(table_name)s' AND - column_name = '%(column_name)s'; - EXCEPTION WHEN NO_DATA_FOUND THEN - seq_name := '%(no_autofield_sequence_name)s'; - END; + SELECT COUNT(*) INTO identity_col_found FROM user_tab_identity_cols + WHERE table_name = '%(table_name)s' AND + column_name = '%(column_name)s'; - SELECT NVL(MAX(%(column)s), 0) INTO table_value FROM %(table)s; - SELECT NVL(last_number - cache_size, 0) INTO seq_value FROM user_sequences - WHERE sequence_name = seq_name; - WHILE table_value > seq_value LOOP - EXECUTE IMMEDIATE 'SELECT "'||seq_name||'".nextval%(suffix)s' - INTO seq_value; - END LOOP; + IF identity_col_found >= 1 THEN + EXECUTE IMMEDIATE 'ALTER TABLE %(table)s ' || + 'MODIFY %(column)s ' || + 'GENERATED BY DEFAULT ON NULL AS IDENTITY ' || + 'START WITH LIMIT VALUE'; + ELSE + SELECT NVL(MAX(%(column)s), 0) + 1 INTO new_start FROM %(table)s; + EXECUTE IMMEDIATE 'ALTER SEQUENCE "%(no_autofield_sequence_name)s" ' || + 'RESTART START WITH ' || new_start; + + END IF; END; /""" @@ -537,7 +536,6 @@ END; "column": column, "table_name": strip_quotes(table), "column_name": strip_quotes(column), - "suffix": self.connection.features.bare_select_suffix, } sql.append(query) return sql @@ -561,7 +559,6 @@ END; "column": column, "table_name": strip_quotes(table), "column_name": strip_quotes(column), - "suffix": self.connection.features.bare_select_suffix, } ) # Only one AutoField is allowed per model, so don't