|
| 1 | +"""Smarter model pk sequence reset.""" |
| 2 | +from django.db import connection, models |
| 3 | + |
| 4 | + |
| 5 | +def pk_sequence_get(model): |
| 6 | + """Return a list of table, column tuples which should have sequences.""" |
| 7 | + for field in model._meta.get_fields(): |
| 8 | + if not getattr(field, 'primary_key', False): |
| 9 | + continue |
| 10 | + if not isinstance(field, models.AutoField): |
| 11 | + continue |
| 12 | + return field.db_column or field.column |
| 13 | + |
| 14 | + |
| 15 | +def sequence_reset(model): |
| 16 | + """ |
| 17 | + Better sequence reset than TransactionTestCase. |
| 18 | +
|
| 19 | + The difference with using TransactionTestCase with reset_sequences=True is |
| 20 | + that this will reset sequences for the given models to their higher value, |
| 21 | + supporting pre-existing models which could have been created by a |
| 22 | + migration. |
| 23 | + """ |
| 24 | + pk_field = pk_sequence_get(model) |
| 25 | + if not pk_field: |
| 26 | + return |
| 27 | + |
| 28 | + if connection.vendor == 'postgresql': |
| 29 | + reset = """ |
| 30 | + SELECT |
| 31 | + setval( |
| 32 | + pg_get_serial_sequence('{table}', '{column}'), |
| 33 | + coalesce(max({column}),0) + 1, |
| 34 | + false |
| 35 | + ) |
| 36 | + FROM {table} |
| 37 | + """ |
| 38 | + elif connection.vendor == 'sqlite': |
| 39 | + reset = """ |
| 40 | + UPDATE sqlite_sequence |
| 41 | + SET seq=(SELECT max({column}) from {table}) |
| 42 | + WHERE name='{table}' |
| 43 | + """ |
| 44 | + elif connection.vendor == 'mysql': |
| 45 | + cursor = connection.cursor() |
| 46 | + cursor.execute( |
| 47 | + 'SELECT MAX({column}) + 1 FROM {table}'.format( |
| 48 | + column=pk_field, table=model._meta.db_table |
| 49 | + ) |
| 50 | + ) |
| 51 | + result = cursor.fetchone()[0] or 0 |
| 52 | + reset = 'ALTER TABLE {table} AUTO_INCREMENT = %s' % result |
| 53 | + |
| 54 | + connection.cursor().execute( |
| 55 | + reset.format(column=pk_field, table=model._meta.db_table) |
| 56 | + ) |
0 commit comments