Skip to content

Merging Databases

Liam DeVoe edited this page Feb 28, 2022 · 4 revisions

If you're an advanced user, you may want the ability to merge two database files. To do so, rename the database you want to keep to "master.db", the database you want to merge into the other database to "slave.db", and put them both in the same directory as this script. Then run this script by saving it to a file called merge_cg_db.py and run python3 merge_cg_db.py, or maybe python merge_cg_db.py, depending on your python installation.

import sqlite3
from pathlib import Path

master_conn = sqlite3.connect(Path(__file__).parent / "master.db")
slave_conn = sqlite3.connect(Path(__file__).parent / "slave.db")
cursor_master = master_conn.cursor()
cursor_slave = slave_conn.cursor()

for row in cursor_slave.execute("SELECT * FROM replays").fetchall():
    (map_id, user_id, replay_data, replay_id, mods) = row
    if (cursor_master.execute("SELECT * FROM replays WHERE replay_id = ?",
        [replay_id]).fetchone()):
        print(f"replay {replay_id} already exists in master db, skipping")
        continue
    print(f"inserting replay {replay_id} into master db")
    cursor_master.execute("INSERT INTO replays VALUES (?, ?, ?, ?, ?)",
        [map_id, user_id, replay_data, replay_id, mods])

master_conn.commit()

You might want to make a backup of your databases before running this script, just in case. Afterwards you can delete slave.db since it's been fully merged into master.db, and you can move master.db back to circleguard's database location, or use it however else you want.

Clone this wiki locally