Estoy tratando de eliminar un índice usando migraciones. Ejecutar SQL pero tengo un problema que no existe, ¿hay alguna forma de eliminar un índice solo en el caso de que exista? Algo así como migraciones. Ejecutar SQL ("DROP INDEX IF EXISTS index_id ON table").
Muchas gracias
Dado que IF EXISTS no es compatible con la indexación de MySQL, es posible que desee escribir su propia migración:
def drop_index_if_exists(apps, schema_editor): # access to the connection since schema_editor.execute does not return the cursor with schema_editor.connection.cursor() as cursor: cursor.execute("SHOW INDEX FROM table_name WHERE KEY_NAME = 'index_name'"); exists = int(cursor.fetchone()) > 0 # outside with to close the cursor if exists: schema_editor.execute("CREATE INDEX index_name ON ...") operations = [ migrations.RunPython(drop_index_if_exists) ] Para mantener la coherencia, puede escribir un método create_index_if_not_exists para cancelar la aplicación de la migración y llamarlo:
migrations.RunPython(drop_index_if_exists, create_index_if_not_exists)Aquí hay una solución, gracias por la idea @alfonso.kim
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def drop_index_if_exists_and_create(apps, schema_editor): # access to the connection since schema_editor.execute does not return the cursor with schema_editor.connection.cursor() as cursor: cursor.execute("SHOW INDEX FROM table_name WHERE KEY_NAME = 'index_name'") exists = True if cursor.fetchone() else False # outside with to close the cursor if exists: schema_editor.execute("DROP INDEX index_name ON table_name") schema_editor.execute("CREATE INDEX index_name ON table_name(index_name(191))") class Migration(migrations.Migration): dependencies = [ ('table_name', ''), ] operations = [ migrations.RunPython(drop_index_if_exists_and_create) ]Recibo un error de transacción después de ejecutar su código:
django.db.transaction.TransactionManagementError: Executing DDL statements while in a transaction on databases that can't perform a rollback is prohibited.Django 2.5 MySQL 5.7