We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Failed at database upgrade from version 31 to 32
## Problem Definition

Login fails with following message:
`Failed at database upgrade from version 31 to 32: UNIQUE constraint failed: history_events_copy.event_identifier, history_events_copy.sequence_index`

## Logs

Which logs do you need, if you need any?

### System Description

Operating system: Debian Buster (using the AppImage)
Rotki version: 1.24.0


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `rotkehlchen/db/upgrades/v31_v32.py`
Content:
```
1 from collections import defaultdict
2 from typing import TYPE_CHECKING, Dict, Set
3 
4 from rotkehlchen.db.constants import BINANCE_MARKETS_KEY
5 
6 if TYPE_CHECKING:
7     from sqlite3 import Cursor
8 
9     from rotkehlchen.db.dbhandler import DBHandler
10 
11 
12 def _upgrade_history_events(cursor: 'Cursor') -> None:
13     cursor.execute("""
14     CREATE TABLE IF NOT EXISTS history_events_copy (
15         identifier INTEGER NOT NULL PRIMARY KEY,
16         event_identifier TEXT NOT NULL,
17         sequence_index INTEGER NOT NULL,
18         timestamp INTEGER NOT NULL,
19         location TEXT NOT NULL,
20         location_label TEXT,
21         asset TEXT NOT NULL,
22         amount TEXT NOT NULL,
23         usd_value TEXT NOT NULL,
24         notes TEXT,
25         type TEXT NOT NULL,
26         subtype TEXT,
27         counterparty TEXT,
28         extra_data TEXT,
29         UNIQUE(event_identifier, sequence_index)
30     );""")
31     cursor.execute('UPDATE history_events SET timestamp = timestamp / 10;')
32     cursor.execute('UPDATE history_events SET subtype = "deposit asset" WHERE subtype = "staking deposit asset";')  # noqa: E501
33     cursor.execute('UPDATE history_events SET subtype = "receive wrapped" WHERE subtype = "staking receive asset";')  # noqa: E501
34     cursor.execute('UPDATE history_events SET subtype = "remove asset", type = "staking" WHERE subtype = "staking remove asset" AND type = "unstaking";')  # noqa: E501
35     cursor.execute('UPDATE history_events SET subtype = "return wrapped", type = "staking" WHERE subtype = "staking receive asset" AND type = "unstaking";')  # noqa: E501
36     cursor.execute('UPDATE history_events SET type = "informational" WHERE subtype = "unknown";')
37     cursor.execute("""
38     INSERT INTO history_events_copy (event_identifier, sequence_index, timestamp, location,
39     location_label, asset, amount, usd_value, notes, type, subtype)
40     SELECT event_identifier, sequence_index, timestamp, location, location_label, asset,
41     amount, usd_value, notes, type, subtype
42     FROM history_events;
43     """)
44     cursor.execute('DROP TABLE history_events;')
45     cursor.execute('ALTER TABLE history_events_copy RENAME TO history_events;')
46     cursor.execute(
47         'UPDATE history_events SET subtype="reward" WHERE type="staking" AND subtype IS NULL;',
48     )
49 
50 
51 def _remove_gitcoin(cursor: 'Cursor') -> None:
52     cursor.execute('DELETE from ledger_actions WHERE identifier IN (SELECT parent_id FROM ledger_actions_gitcoin_data)')  # noqa: E501
53     cursor.execute('DELETE from used_query_ranges WHERE name LIKE "gitcoingrants_%"')
54     cursor.execute('DROP TABLE IF exists gitcoin_grant_metadata')
55     cursor.execute('DROP TABLE IF exists ledger_actions_gitcoin_data')
56     cursor.execute('DROP TABLE IF exists gitcoin_tx_type')
57 
58 
59 def _add_new_tables(cursor: 'Cursor') -> None:
60     cursor.execute('INSERT OR IGNORE INTO location(location, seq) VALUES ("d", 36)')
61     cursor.execute("""
62     CREATE TABLE IF NOT EXISTS ethereum_internal_transactions (
63     parent_tx_hash BLOB NOT NULL,
64     trace_id INTEGER NOT NULL,
65     timestamp INTEGER NOT NULL,
66     block_number INTEGER NOT NULL,
67     from_address TEXT NOT NULL,
68     to_address TEXT,
69     value TEXT NOT NULL,
70     FOREIGN KEY(parent_tx_hash) REFERENCES ethereum_transactions(tx_hash) ON DELETE CASCADE ON UPDATE CASCADE,
71     PRIMARY KEY(parent_tx_hash, trace_id)
72 );""")  # noqa: E501
73     cursor.execute("""
74     CREATE TABLE IF NOT EXISTS ethtx_address_mappings (
75     address TEXT NOT NULL,
76     tx_hash BLOB NOT NULL,
77     blockchain TEXT NOT NULL,
78     FOREIGN KEY(blockchain, address) REFERENCES blockchain_accounts(blockchain, account) ON DELETE CASCADE,
79     FOREIGN KEY(tx_hash) references ethereum_transactions(tx_hash) ON UPDATE CASCADE ON DELETE CASCADE,
80     PRIMARY KEY (address, tx_hash, blockchain)
81 );""")  # noqa: E501
82     cursor.execute("""
83     CREATE TABLE IF NOT EXISTS evm_tx_mappings (
84     tx_hash BLOB NOT NULL,
85     blockchain TEXT NOT NULL,
86     value TEXT NOT NULL,
87     FOREIGN KEY(tx_hash) references ethereum_transactions(tx_hash) ON UPDATE CASCADE ON DELETE CASCADE,
88     PRIMARY KEY (tx_hash, value)
89 );""")  # noqa: E501
90     cursor.execute("""
91     CREATE TABLE IF NOT EXISTS history_events_mappings (
92     parent_identifier INTEGER NOT NULL,
93     value TEXT NOT NULL,
94     FOREIGN KEY(parent_identifier) references history_events(identifier) ON UPDATE CASCADE ON DELETE CASCADE,
95     PRIMARY KEY (parent_identifier, value)
96 );""")  # noqa: E501
97     cursor.execute("""
98     CREATE TABLE IF NOT EXISTS ens_mappings (
99     address TEXT NOT NULL PRIMARY KEY,
100     ens_name TEXT UNIQUE,
101     last_update INTEGER NOT NULL
102 );
103 """)
104 
105 
106 def _refactor_manual_balance_id(cursor: 'Cursor') -> None:
107     cursor.execute("""
108     CREATE TABLE manually_tracked_balances_copy (
109         id INTEGER PRIMARY KEY,
110         asset TEXT NOT NULL,
111         label TEXT NOT NULL,
112         amount TEXT,
113         location CHAR(1) NOT NULL DEFAULT('A') REFERENCES location(location),
114         category CHAR(1) NOT NULL DEFAULT('A') REFERENCES balance_category(category),
115         FOREIGN KEY(asset) REFERENCES assets(identifier) ON UPDATE CASCADE
116     );""")
117     cursor.execute("""
118     INSERT INTO manually_tracked_balances_copy(asset, label, amount, location, category)
119     SELECT asset, label, amount, location, category
120     FROM manually_tracked_balances;
121     """)
122     cursor.execute('DROP TABLE manually_tracked_balances;')
123     cursor.execute(
124         'ALTER TABLE manually_tracked_balances_copy RENAME TO '
125         'manually_tracked_balances;',
126     )
127 
128 
129 def _update_fee_for_existing_trades(cursor: 'Cursor') -> None:
130     cursor.execute('UPDATE trades SET fee = NULL WHERE fee_currency IS NULL')
131     cursor.execute('UPDATE trades SET fee_currency = NULL WHERE fee IS NULL')
132 
133 
134 def _update_history_entries_from_kraken(cursor: 'Cursor') -> None:
135     """The logic for kraken was adding additional entries for trades when fee + kfee was
136     being used. This function makes the state of the database consistent with the upgraded
137     logic by:
138     - Removing extra row additions
139     - Make sure that no other event has duplicated sequence indexes
140     """
141     cursor.execute("""
142     DELETE FROM history_events where location="B" AND asset="KFEE" AND
143      type="trade" AND subtype=NULL;
144     """)
145     cursor.execute("""
146     SELECT e.event_identifier, e.sequence_index, e.identifier from history_events e JOIN (SELECT event_identifier,
147     sequence_index, COUNT(*) as cnt FROM history_events GROUP BY event_identifier, sequence_index)
148     other ON e.event_identifier = other.event_identifier and e.sequence_index=other.sequence_index
149     WHERE other.cnt > 1;
150     """)  # noqa: E501
151 
152     update_tuples = []
153     eventid_to_indices: Dict[str, Set[int]] = defaultdict(set)
154     for event_identifier, sequence_index, identifier in cursor:
155         last_indices = eventid_to_indices.get(event_identifier)
156         if last_indices is None:
157             # Let the first one be the same as it was in the database
158             eventid_to_indices[event_identifier].add(sequence_index)
159             continue
160 
161         new_index = sequence_index + 1
162         while new_index in eventid_to_indices[event_identifier]:
163             new_index += 1
164         eventid_to_indices[event_identifier].add(new_index)
165         update_tuples.append((new_index, identifier))
166 
167     if len(update_tuples) != 0:
168         cursor.executemany(
169             'UPDATE history_events SET sequence_index=? WHERE identifier=?',
170             update_tuples,
171         )
172 
173 
174 def _update_settings_name_for_selected_binance_markets(cursor: 'Cursor') -> None:
175     cursor.execute("""
176     UPDATE user_credentials_mappings SET setting_name = ? WHERE setting_name = "PAIRS"
177     """, (BINANCE_MARKETS_KEY,))
178 
179 
180 def _update_manual_balances_tags(cursor_fetch: 'Cursor', cursor_update: 'Cursor') -> None:
181     manual_balances = cursor_fetch.execute('SELECT id, label FROM manually_tracked_balances')
182     for balance_id, label in manual_balances:
183         cursor_update.execute('UPDATE tag_mappings SET object_reference=? WHERE object_reference=?', (balance_id, label))  # noqa: E501
184 
185 
186 def upgrade_v31_to_v32(db: 'DBHandler') -> None:
187     """Upgrades the DB from v31 to v32
188     - use new identifiers for the history_events table. The id will be generated by sqlite
189     and will be the column rowid
190 
191     -Add the subtype REWARD to staking rewards (before they had type staking
192     and no subtype)
193 
194     -Remove all gitcoin grant related data that was pulled from their API and saved in
195     specific tables along with the tables themselves
196 
197     -Sets fee to null for existing trades if fee_currency is missing.
198     """
199     primary_cursor = db.conn.cursor()
200     secondary_cursor = db.conn.cursor()
201     _update_history_entries_from_kraken(primary_cursor)
202     _upgrade_history_events(primary_cursor)
203     _remove_gitcoin(primary_cursor)
204     _add_new_tables(primary_cursor)
205     _refactor_manual_balance_id(primary_cursor)
206     _update_fee_for_existing_trades(primary_cursor)
207     _update_settings_name_for_selected_binance_markets(primary_cursor)
208     _update_manual_balances_tags(cursor_fetch=primary_cursor, cursor_update=secondary_cursor)
209     db.conn.commit()
210
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/rotkehlchen/db/upgrades/v31_v32.py b/rotkehlchen/db/upgrades/v31_v32.py
--- a/rotkehlchen/db/upgrades/v31_v32.py
+++ b/rotkehlchen/db/upgrades/v31_v32.py
@@ -142,22 +142,20 @@
     DELETE FROM history_events where location="B" AND asset="KFEE" AND
      type="trade" AND subtype=NULL;
     """)
+
+    cursor.execute('SELECT event_identifier, sequence_index from history_events')
+    eventid_to_indices: Dict[str, Set[int]] = defaultdict(set)
+    for event_identifier, sequence_index in cursor:
+        eventid_to_indices[event_identifier].add(sequence_index)
+
     cursor.execute("""
     SELECT e.event_identifier, e.sequence_index, e.identifier from history_events e JOIN (SELECT event_identifier,
     sequence_index, COUNT(*) as cnt FROM history_events GROUP BY event_identifier, sequence_index)
     other ON e.event_identifier = other.event_identifier and e.sequence_index=other.sequence_index
     WHERE other.cnt > 1;
     """)  # noqa: E501
-
     update_tuples = []
-    eventid_to_indices: Dict[str, Set[int]] = defaultdict(set)
     for event_identifier, sequence_index, identifier in cursor:
-        last_indices = eventid_to_indices.get(event_identifier)
-        if last_indices is None:
-            # Let the first one be the same as it was in the database
-            eventid_to_indices[event_identifier].add(sequence_index)
-            continue
-
         new_index = sequence_index + 1
         while new_index in eventid_to_indices[event_identifier]:
             new_index += 1

{"golden_diff": "diff --git a/rotkehlchen/db/upgrades/v31_v32.py b/rotkehlchen/db/upgrades/v31_v32.py\n--- a/rotkehlchen/db/upgrades/v31_v32.py\n+++ b/rotkehlchen/db/upgrades/v31_v32.py\n@@ -142,22 +142,20 @@\n     DELETE FROM history_events where location=\"B\" AND asset=\"KFEE\" AND\n      type=\"trade\" AND subtype=NULL;\n     \"\"\")\n+\n+    cursor.execute('SELECT event_identifier, sequence_index from history_events')\n+    eventid_to_indices: Dict[str, Set[int]] = defaultdict(set)\n+    for event_identifier, sequence_index in cursor:\n+        eventid_to_indices[event_identifier].add(sequence_index)\n+\n     cursor.execute(\"\"\"\n     SELECT e.event_identifier, e.sequence_index, e.identifier from history_events e JOIN (SELECT event_identifier,\n     sequence_index, COUNT(*) as cnt FROM history_events GROUP BY event_identifier, sequence_index)\n     other ON e.event_identifier = other.event_identifier and e.sequence_index=other.sequence_index\n     WHERE other.cnt > 1;\n     \"\"\")  # noqa: E501\n-\n     update_tuples = []\n-    eventid_to_indices: Dict[str, Set[int]] = defaultdict(set)\n     for event_identifier, sequence_index, identifier in cursor:\n-        last_indices = eventid_to_indices.get(event_identifier)\n-        if last_indices is None:\n-            # Let the first one be the same as it was in the database\n-            eventid_to_indices[event_identifier].add(sequence_index)\n-            continue\n-\n         new_index = sequence_index + 1\n         while new_index in eventid_to_indices[event_identifier]:\n             new_index += 1\n", "issue": "Failed at database upgrade from version 31 to 32\n## Problem Definition\r\n\r\nLogin fails with following message:\r\n`Failed at database upgrade from version 31 to 32: UNIQUE constraint failed: history_events_copy.event_identifier, history_events_copy.sequence_index`\r\n\r\n## Logs\r\n\r\nWhich logs do you need, if you need any?\r\n\r\n### System Description\r\n\r\nOperating system: Debian Buster (using the AppImage)\r\nRotki version: 1.24.0\r\n\n", "before_files": [{"content": "from collections import defaultdict\nfrom typing import TYPE_CHECKING, Dict, Set\n\nfrom rotkehlchen.db.constants import BINANCE_MARKETS_KEY\n\nif TYPE_CHECKING:\n    from sqlite3 import Cursor\n\n    from rotkehlchen.db.dbhandler import DBHandler\n\n\ndef _upgrade_history_events(cursor: 'Cursor') -> None:\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS history_events_copy (\n        identifier INTEGER NOT NULL PRIMARY KEY,\n        event_identifier TEXT NOT NULL,\n        sequence_index INTEGER NOT NULL,\n        timestamp INTEGER NOT NULL,\n        location TEXT NOT NULL,\n        location_label TEXT,\n        asset TEXT NOT NULL,\n        amount TEXT NOT NULL,\n        usd_value TEXT NOT NULL,\n        notes TEXT,\n        type TEXT NOT NULL,\n        subtype TEXT,\n        counterparty TEXT,\n        extra_data TEXT,\n        UNIQUE(event_identifier, sequence_index)\n    );\"\"\")\n    cursor.execute('UPDATE history_events SET timestamp = timestamp / 10;')\n    cursor.execute('UPDATE history_events SET subtype = \"deposit asset\" WHERE subtype = \"staking deposit asset\";')  # noqa: E501\n    cursor.execute('UPDATE history_events SET subtype = \"receive wrapped\" WHERE subtype = \"staking receive asset\";')  # noqa: E501\n    cursor.execute('UPDATE history_events SET subtype = \"remove asset\", type = \"staking\" WHERE subtype = \"staking remove asset\" AND type = \"unstaking\";')  # noqa: E501\n    cursor.execute('UPDATE history_events SET subtype = \"return wrapped\", type = \"staking\" WHERE subtype = \"staking receive asset\" AND type = \"unstaking\";')  # noqa: E501\n    cursor.execute('UPDATE history_events SET type = \"informational\" WHERE subtype = \"unknown\";')\n    cursor.execute(\"\"\"\n    INSERT INTO history_events_copy (event_identifier, sequence_index, timestamp, location,\n    location_label, asset, amount, usd_value, notes, type, subtype)\n    SELECT event_identifier, sequence_index, timestamp, location, location_label, asset,\n    amount, usd_value, notes, type, subtype\n    FROM history_events;\n    \"\"\")\n    cursor.execute('DROP TABLE history_events;')\n    cursor.execute('ALTER TABLE history_events_copy RENAME TO history_events;')\n    cursor.execute(\n        'UPDATE history_events SET subtype=\"reward\" WHERE type=\"staking\" AND subtype IS NULL;',\n    )\n\n\ndef _remove_gitcoin(cursor: 'Cursor') -> None:\n    cursor.execute('DELETE from ledger_actions WHERE identifier IN (SELECT parent_id FROM ledger_actions_gitcoin_data)')  # noqa: E501\n    cursor.execute('DELETE from used_query_ranges WHERE name LIKE \"gitcoingrants_%\"')\n    cursor.execute('DROP TABLE IF exists gitcoin_grant_metadata')\n    cursor.execute('DROP TABLE IF exists ledger_actions_gitcoin_data')\n    cursor.execute('DROP TABLE IF exists gitcoin_tx_type')\n\n\ndef _add_new_tables(cursor: 'Cursor') -> None:\n    cursor.execute('INSERT OR IGNORE INTO location(location, seq) VALUES (\"d\", 36)')\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS ethereum_internal_transactions (\n    parent_tx_hash BLOB NOT NULL,\n    trace_id INTEGER NOT NULL,\n    timestamp INTEGER NOT NULL,\n    block_number INTEGER NOT NULL,\n    from_address TEXT NOT NULL,\n    to_address TEXT,\n    value TEXT NOT NULL,\n    FOREIGN KEY(parent_tx_hash) REFERENCES ethereum_transactions(tx_hash) ON DELETE CASCADE ON UPDATE CASCADE,\n    PRIMARY KEY(parent_tx_hash, trace_id)\n);\"\"\")  # noqa: E501\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS ethtx_address_mappings (\n    address TEXT NOT NULL,\n    tx_hash BLOB NOT NULL,\n    blockchain TEXT NOT NULL,\n    FOREIGN KEY(blockchain, address) REFERENCES blockchain_accounts(blockchain, account) ON DELETE CASCADE,\n    FOREIGN KEY(tx_hash) references ethereum_transactions(tx_hash) ON UPDATE CASCADE ON DELETE CASCADE,\n    PRIMARY KEY (address, tx_hash, blockchain)\n);\"\"\")  # noqa: E501\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS evm_tx_mappings (\n    tx_hash BLOB NOT NULL,\n    blockchain TEXT NOT NULL,\n    value TEXT NOT NULL,\n    FOREIGN KEY(tx_hash) references ethereum_transactions(tx_hash) ON UPDATE CASCADE ON DELETE CASCADE,\n    PRIMARY KEY (tx_hash, value)\n);\"\"\")  # noqa: E501\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS history_events_mappings (\n    parent_identifier INTEGER NOT NULL,\n    value TEXT NOT NULL,\n    FOREIGN KEY(parent_identifier) references history_events(identifier) ON UPDATE CASCADE ON DELETE CASCADE,\n    PRIMARY KEY (parent_identifier, value)\n);\"\"\")  # noqa: E501\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS ens_mappings (\n    address TEXT NOT NULL PRIMARY KEY,\n    ens_name TEXT UNIQUE,\n    last_update INTEGER NOT NULL\n);\n\"\"\")\n\n\ndef _refactor_manual_balance_id(cursor: 'Cursor') -> None:\n    cursor.execute(\"\"\"\n    CREATE TABLE manually_tracked_balances_copy (\n        id INTEGER PRIMARY KEY,\n        asset TEXT NOT NULL,\n        label TEXT NOT NULL,\n        amount TEXT,\n        location CHAR(1) NOT NULL DEFAULT('A') REFERENCES location(location),\n        category CHAR(1) NOT NULL DEFAULT('A') REFERENCES balance_category(category),\n        FOREIGN KEY(asset) REFERENCES assets(identifier) ON UPDATE CASCADE\n    );\"\"\")\n    cursor.execute(\"\"\"\n    INSERT INTO manually_tracked_balances_copy(asset, label, amount, location, category)\n    SELECT asset, label, amount, location, category\n    FROM manually_tracked_balances;\n    \"\"\")\n    cursor.execute('DROP TABLE manually_tracked_balances;')\n    cursor.execute(\n        'ALTER TABLE manually_tracked_balances_copy RENAME TO '\n        'manually_tracked_balances;',\n    )\n\n\ndef _update_fee_for_existing_trades(cursor: 'Cursor') -> None:\n    cursor.execute('UPDATE trades SET fee = NULL WHERE fee_currency IS NULL')\n    cursor.execute('UPDATE trades SET fee_currency = NULL WHERE fee IS NULL')\n\n\ndef _update_history_entries_from_kraken(cursor: 'Cursor') -> None:\n    \"\"\"The logic for kraken was adding additional entries for trades when fee + kfee was\n    being used. This function makes the state of the database consistent with the upgraded\n    logic by:\n    - Removing extra row additions\n    - Make sure that no other event has duplicated sequence indexes\n    \"\"\"\n    cursor.execute(\"\"\"\n    DELETE FROM history_events where location=\"B\" AND asset=\"KFEE\" AND\n     type=\"trade\" AND subtype=NULL;\n    \"\"\")\n    cursor.execute(\"\"\"\n    SELECT e.event_identifier, e.sequence_index, e.identifier from history_events e JOIN (SELECT event_identifier,\n    sequence_index, COUNT(*) as cnt FROM history_events GROUP BY event_identifier, sequence_index)\n    other ON e.event_identifier = other.event_identifier and e.sequence_index=other.sequence_index\n    WHERE other.cnt > 1;\n    \"\"\")  # noqa: E501\n\n    update_tuples = []\n    eventid_to_indices: Dict[str, Set[int]] = defaultdict(set)\n    for event_identifier, sequence_index, identifier in cursor:\n        last_indices = eventid_to_indices.get(event_identifier)\n        if last_indices is None:\n            # Let the first one be the same as it was in the database\n            eventid_to_indices[event_identifier].add(sequence_index)\n            continue\n\n        new_index = sequence_index + 1\n        while new_index in eventid_to_indices[event_identifier]:\n            new_index += 1\n        eventid_to_indices[event_identifier].add(new_index)\n        update_tuples.append((new_index, identifier))\n\n    if len(update_tuples) != 0:\n        cursor.executemany(\n            'UPDATE history_events SET sequence_index=? WHERE identifier=?',\n            update_tuples,\n        )\n\n\ndef _update_settings_name_for_selected_binance_markets(cursor: 'Cursor') -> None:\n    cursor.execute(\"\"\"\n    UPDATE user_credentials_mappings SET setting_name = ? WHERE setting_name = \"PAIRS\"\n    \"\"\", (BINANCE_MARKETS_KEY,))\n\n\ndef _update_manual_balances_tags(cursor_fetch: 'Cursor', cursor_update: 'Cursor') -> None:\n    manual_balances = cursor_fetch.execute('SELECT id, label FROM manually_tracked_balances')\n    for balance_id, label in manual_balances:\n        cursor_update.execute('UPDATE tag_mappings SET object_reference=? WHERE object_reference=?', (balance_id, label))  # noqa: E501\n\n\ndef upgrade_v31_to_v32(db: 'DBHandler') -> None:\n    \"\"\"Upgrades the DB from v31 to v32\n    - use new identifiers for the history_events table. The id will be generated by sqlite\n    and will be the column rowid\n\n    -Add the subtype REWARD to staking rewards (before they had type staking\n    and no subtype)\n\n    -Remove all gitcoin grant related data that was pulled from their API and saved in\n    specific tables along with the tables themselves\n\n    -Sets fee to null for existing trades if fee_currency is missing.\n    \"\"\"\n    primary_cursor = db.conn.cursor()\n    secondary_cursor = db.conn.cursor()\n    _update_history_entries_from_kraken(primary_cursor)\n    _upgrade_history_events(primary_cursor)\n    _remove_gitcoin(primary_cursor)\n    _add_new_tables(primary_cursor)\n    _refactor_manual_balance_id(primary_cursor)\n    _update_fee_for_existing_trades(primary_cursor)\n    _update_settings_name_for_selected_binance_markets(primary_cursor)\n    _update_manual_balances_tags(cursor_fetch=primary_cursor, cursor_update=secondary_cursor)\n    db.conn.commit()\n", "path": "rotkehlchen/db/upgrades/v31_v32.py"}], "after_files": [{"content": "from collections import defaultdict\nfrom typing import TYPE_CHECKING, Dict, Set\n\nfrom rotkehlchen.db.constants import BINANCE_MARKETS_KEY\n\nif TYPE_CHECKING:\n    from sqlite3 import Cursor\n\n    from rotkehlchen.db.dbhandler import DBHandler\n\n\ndef _upgrade_history_events(cursor: 'Cursor') -> None:\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS history_events_copy (\n        identifier INTEGER NOT NULL PRIMARY KEY,\n        event_identifier TEXT NOT NULL,\n        sequence_index INTEGER NOT NULL,\n        timestamp INTEGER NOT NULL,\n        location TEXT NOT NULL,\n        location_label TEXT,\n        asset TEXT NOT NULL,\n        amount TEXT NOT NULL,\n        usd_value TEXT NOT NULL,\n        notes TEXT,\n        type TEXT NOT NULL,\n        subtype TEXT,\n        counterparty TEXT,\n        extra_data TEXT,\n        UNIQUE(event_identifier, sequence_index)\n    );\"\"\")\n    cursor.execute('UPDATE history_events SET timestamp = timestamp / 10;')\n    cursor.execute('UPDATE history_events SET subtype = \"deposit asset\" WHERE subtype = \"staking deposit asset\";')  # noqa: E501\n    cursor.execute('UPDATE history_events SET subtype = \"receive wrapped\" WHERE subtype = \"staking receive asset\";')  # noqa: E501\n    cursor.execute('UPDATE history_events SET subtype = \"remove asset\", type = \"staking\" WHERE subtype = \"staking remove asset\" AND type = \"unstaking\";')  # noqa: E501\n    cursor.execute('UPDATE history_events SET subtype = \"return wrapped\", type = \"staking\" WHERE subtype = \"staking receive asset\" AND type = \"unstaking\";')  # noqa: E501\n    cursor.execute('UPDATE history_events SET type = \"informational\" WHERE subtype = \"unknown\";')\n    cursor.execute(\"\"\"\n    INSERT INTO history_events_copy (event_identifier, sequence_index, timestamp, location,\n    location_label, asset, amount, usd_value, notes, type, subtype)\n    SELECT event_identifier, sequence_index, timestamp, location, location_label, asset,\n    amount, usd_value, notes, type, subtype\n    FROM history_events;\n    \"\"\")\n    cursor.execute('DROP TABLE history_events;')\n    cursor.execute('ALTER TABLE history_events_copy RENAME TO history_events;')\n    cursor.execute(\n        'UPDATE history_events SET subtype=\"reward\" WHERE type=\"staking\" AND subtype IS NULL;',\n    )\n\n\ndef _remove_gitcoin(cursor: 'Cursor') -> None:\n    cursor.execute('DELETE from ledger_actions WHERE identifier IN (SELECT parent_id FROM ledger_actions_gitcoin_data)')  # noqa: E501\n    cursor.execute('DELETE from used_query_ranges WHERE name LIKE \"gitcoingrants_%\"')\n    cursor.execute('DROP TABLE IF exists gitcoin_grant_metadata')\n    cursor.execute('DROP TABLE IF exists ledger_actions_gitcoin_data')\n    cursor.execute('DROP TABLE IF exists gitcoin_tx_type')\n\n\ndef _add_new_tables(cursor: 'Cursor') -> None:\n    cursor.execute('INSERT OR IGNORE INTO location(location, seq) VALUES (\"d\", 36)')\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS ethereum_internal_transactions (\n    parent_tx_hash BLOB NOT NULL,\n    trace_id INTEGER NOT NULL,\n    timestamp INTEGER NOT NULL,\n    block_number INTEGER NOT NULL,\n    from_address TEXT NOT NULL,\n    to_address TEXT,\n    value TEXT NOT NULL,\n    FOREIGN KEY(parent_tx_hash) REFERENCES ethereum_transactions(tx_hash) ON DELETE CASCADE ON UPDATE CASCADE,\n    PRIMARY KEY(parent_tx_hash, trace_id)\n);\"\"\")  # noqa: E501\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS ethtx_address_mappings (\n    address TEXT NOT NULL,\n    tx_hash BLOB NOT NULL,\n    blockchain TEXT NOT NULL,\n    FOREIGN KEY(blockchain, address) REFERENCES blockchain_accounts(blockchain, account) ON DELETE CASCADE,\n    FOREIGN KEY(tx_hash) references ethereum_transactions(tx_hash) ON UPDATE CASCADE ON DELETE CASCADE,\n    PRIMARY KEY (address, tx_hash, blockchain)\n);\"\"\")  # noqa: E501\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS evm_tx_mappings (\n    tx_hash BLOB NOT NULL,\n    blockchain TEXT NOT NULL,\n    value TEXT NOT NULL,\n    FOREIGN KEY(tx_hash) references ethereum_transactions(tx_hash) ON UPDATE CASCADE ON DELETE CASCADE,\n    PRIMARY KEY (tx_hash, value)\n);\"\"\")  # noqa: E501\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS history_events_mappings (\n    parent_identifier INTEGER NOT NULL,\n    value TEXT NOT NULL,\n    FOREIGN KEY(parent_identifier) references history_events(identifier) ON UPDATE CASCADE ON DELETE CASCADE,\n    PRIMARY KEY (parent_identifier, value)\n);\"\"\")  # noqa: E501\n    cursor.execute(\"\"\"\n    CREATE TABLE IF NOT EXISTS ens_mappings (\n    address TEXT NOT NULL PRIMARY KEY,\n    ens_name TEXT UNIQUE,\n    last_update INTEGER NOT NULL\n);\n\"\"\")\n\n\ndef _refactor_manual_balance_id(cursor: 'Cursor') -> None:\n    cursor.execute(\"\"\"\n    CREATE TABLE manually_tracked_balances_copy (\n        id INTEGER PRIMARY KEY,\n        asset TEXT NOT NULL,\n        label TEXT NOT NULL,\n        amount TEXT,\n        location CHAR(1) NOT NULL DEFAULT('A') REFERENCES location(location),\n        category CHAR(1) NOT NULL DEFAULT('A') REFERENCES balance_category(category),\n        FOREIGN KEY(asset) REFERENCES assets(identifier) ON UPDATE CASCADE\n    );\"\"\")\n    cursor.execute(\"\"\"\n    INSERT INTO manually_tracked_balances_copy(asset, label, amount, location, category)\n    SELECT asset, label, amount, location, category\n    FROM manually_tracked_balances;\n    \"\"\")\n    cursor.execute('DROP TABLE manually_tracked_balances;')\n    cursor.execute(\n        'ALTER TABLE manually_tracked_balances_copy RENAME TO '\n        'manually_tracked_balances;',\n    )\n\n\ndef _update_fee_for_existing_trades(cursor: 'Cursor') -> None:\n    cursor.execute('UPDATE trades SET fee = NULL WHERE fee_currency IS NULL')\n    cursor.execute('UPDATE trades SET fee_currency = NULL WHERE fee IS NULL')\n\n\ndef _update_history_entries_from_kraken(cursor: 'Cursor') -> None:\n    \"\"\"The logic for kraken was adding additional entries for trades when fee + kfee was\n    being used. This function makes the state of the database consistent with the upgraded\n    logic by:\n    - Removing extra row additions\n    - Make sure that no other event has duplicated sequence indexes\n    \"\"\"\n    cursor.execute(\"\"\"\n    DELETE FROM history_events where location=\"B\" AND asset=\"KFEE\" AND\n     type=\"trade\" AND subtype=NULL;\n    \"\"\")\n\n    cursor.execute('SELECT event_identifier, sequence_index from history_events')\n    eventid_to_indices: Dict[str, Set[int]] = defaultdict(set)\n    for event_identifier, sequence_index in cursor:\n        eventid_to_indices[event_identifier].add(sequence_index)\n\n    cursor.execute(\"\"\"\n    SELECT e.event_identifier, e.sequence_index, e.identifier from history_events e JOIN (SELECT event_identifier,\n    sequence_index, COUNT(*) as cnt FROM history_events GROUP BY event_identifier, sequence_index)\n    other ON e.event_identifier = other.event_identifier and e.sequence_index=other.sequence_index\n    WHERE other.cnt > 1;\n    \"\"\")  # noqa: E501\n    update_tuples = []\n    for event_identifier, sequence_index, identifier in cursor:\n        new_index = sequence_index + 1\n        while new_index in eventid_to_indices[event_identifier]:\n            new_index += 1\n        eventid_to_indices[event_identifier].add(new_index)\n        update_tuples.append((new_index, identifier))\n\n    if len(update_tuples) != 0:\n        cursor.executemany(\n            'UPDATE history_events SET sequence_index=? WHERE identifier=?',\n            update_tuples,\n        )\n\n\ndef _update_settings_name_for_selected_binance_markets(cursor: 'Cursor') -> None:\n    cursor.execute(\"\"\"\n    UPDATE user_credentials_mappings SET setting_name = ? WHERE setting_name = \"PAIRS\"\n    \"\"\", (BINANCE_MARKETS_KEY,))\n\n\ndef _update_manual_balances_tags(cursor_fetch: 'Cursor', cursor_update: 'Cursor') -> None:\n    manual_balances = cursor_fetch.execute('SELECT id, label FROM manually_tracked_balances')\n    for balance_id, label in manual_balances:\n        cursor_update.execute('UPDATE tag_mappings SET object_reference=? WHERE object_reference=?', (balance_id, label))  # noqa: E501\n\n\ndef upgrade_v31_to_v32(db: 'DBHandler') -> None:\n    \"\"\"Upgrades the DB from v31 to v32\n    - use new identifiers for the history_events table. The id will be generated by sqlite\n    and will be the column rowid\n\n    -Add the subtype REWARD to staking rewards (before they had type staking\n    and no subtype)\n\n    -Remove all gitcoin grant related data that was pulled from their API and saved in\n    specific tables along with the tables themselves\n\n    -Sets fee to null for existing trades if fee_currency is missing.\n    \"\"\"\n    primary_cursor = db.conn.cursor()\n    secondary_cursor = db.conn.cursor()\n    _update_history_entries_from_kraken(primary_cursor)\n    _upgrade_history_events(primary_cursor)\n    _remove_gitcoin(primary_cursor)\n    _add_new_tables(primary_cursor)\n    _refactor_manual_balance_id(primary_cursor)\n    _update_fee_for_existing_trades(primary_cursor)\n    _update_settings_name_for_selected_binance_markets(primary_cursor)\n    _update_manual_balances_tags(cursor_fetch=primary_cursor, cursor_update=secondary_cursor)\n    db.conn.commit()\n", "path": "rotkehlchen/db/upgrades/v31_v32.py"}]}