062_drone_sets_unique.py revision 543d9fb64c2978a8094ca52b9045f43a3b54ff4b
1UP_SQL = """
2CREATE INDEX afe_drone_sets_drones_droneset_ibfk
3ON afe_drone_sets_drones (droneset_id);
4
5ALTER TABLE afe_drone_sets_drones
6DROP KEY afe_drone_sets_drones_unique;
7
8ALTER TABLE afe_drone_sets_drones
9ADD CONSTRAINT afe_drone_sets_drones_unique
10UNIQUE KEY (drone_id);
11
12ALTER TABLE afe_drone_sets_drones
13DROP KEY afe_drone_sets_drones_drone_ibfk;
14"""
15
16DOWN_SQL = """
17CREATE INDEX afe_drone_sets_drones_drone_ibfk
18ON afe_drone_sets_drones (drone_id);
19
20ALTER TABLE afe_drone_sets_drones
21DROP KEY afe_drone_sets_drones_unique;
22
23ALTER TABLE afe_drone_sets_drones
24ADD CONSTRAINT afe_drone_sets_drones_unique
25UNIQUE KEY (droneset_id, drone_id);
26
27ALTER TABLE afe_drone_sets_drones
28DROP KEY afe_drone_sets_drones_droneset_ibfk;
29"""
30
31
32def migrate_up(manager):
33    query = ('SELECT * FROM afe_drone_sets_drones '
34             'GROUP BY drone_id HAVING COUNT(*) > 1')
35    rows = manager.execute(query)
36    if rows:
37      raise Exception('Some drones are associated with more than one drone '
38                      'set. Please remove all duplicates before running this '
39                      'migration.')
40    manager.execute_script(UP_SQL)
41