def _merge_tracks_gids(conn, name_with_id, target_id, source_ids):
    name = name_with_id.replace('_id', '')
    tab = schema.metadata.tables['track_%s' % name]
    col = tab.columns[name_with_id]
    tab_src = schema.metadata.tables['track_%s_source' % name]
    col_src = tab_src.columns['track_%s_id' % name]
    if name == 'mbid':
        tab_chg = schema.metadata.tables['track_%s_change' % name]
        col_chg = tab_chg.columns['track_%s_id' % name]
        tab_flag = schema.metadata.tables['track_%s_flag' % name]
        col_flag = tab_flag.columns['track_%s_id' % name]
    columns = [
        sql.func.min(tab.c.id).label('id'),
        sql.func.array_agg(tab.c.id).label('all_ids'),
        sql.func.sum(tab.c.submission_count).label('count'),
    ]
    if name == 'mbid':
        columns.append(sql.func.every(schema.track_mbid.c.disabled).label('all_disabled'))
    query = sql.select(columns, tab.c.track_id.in_(source_ids + [target_id]), group_by=col)
    rows = conn.execute(query).fetchall()
    to_delete = set()
    to_update = []
    for row in rows:
        old_ids = set(row['all_ids'])
        old_ids.remove(row['id'])
        to_delete.update(old_ids)
        to_update.append((old_ids, row))
        if old_ids:
            update_stmt = tab_src.update().where(col_src.in_(old_ids))
            conn.execute(update_stmt.values({col_src: row['id']}))
            if name == 'mbid':
                update_stmt = tab_chg.update().where(col_chg.in_(old_ids))
                conn.execute(update_stmt.values({col_chg: row['id']}))
                update_stmt = tab_flag.update().where(col_flag.in_(old_ids))
                conn.execute(update_stmt.values({col_flag: row['id']}))
    if to_delete:
        delete_stmt = tab.delete().where(tab.c.id.in_(to_delete))
        conn.execute(delete_stmt)
    for old_ids, row in to_update:
        update_stmt = tab.update().where(tab.c.id == row['id'])
        if name == 'mbid':
            conn.execute(update_stmt.values(submission_count=row['count'], track_id=target_id, disabled=row['all_disabled']))
        else:
            conn.execute(update_stmt.values(submission_count=row['count'], track_id=target_id))
dataset/ETHPy150Open lalinsky/acoustid-server/acoustid/data/track.py/_merge_tracks_gids/original