from patch.include import *
from tqdm import tqdm


@app_context(commit=True)
def fix():
    sql = "UPDATE cmf_full_search SET obj_parent_model = COALESCE(SUBSTRING(obj_parent_id FROM '[^:]*'), '') where id in (select id from cmf_full_search where obj_parent_model is null limit 100) returning id;"
    res = True
    i = 0
    while res:
        i += 100
        res = models.CmfGlobalSettings.dp.data_driver.Session().execute(sql, {}).fetchall()
        print(f'Update {i} CmfFullSearch', flush=True)
        models.CmfGlobalSettings.dp.commit()
    
    # Шаг2. Удаляем CmtAttachment где obj_parent_model == CmfPerson
    res = models.CmfGlobalSettings.dp.data_driver.Session().execute('DELETE from cmf_full_search where obj_model=\'CmfAttachment\' and obj_parent_model=\'CmfPerson\'', {})
    models.CmfGlobalSettings.dp.commit()

if __name__ == "__main__":
    fix()
