--
--Resolve the SQL statements that conflict with the statements for updating system tables in the online upgrade.
--
DECLARE
    wait_time text;
    table_text text;
    table_str text;
    table_name record;
    query_str text;
    row_name record;
    kill_str text;
BEGIN
    -- Maximum timeout for executing SQL statements for in-place upgrades. The default value is 3 minutes.
    wait_time := '00:03:00';

    query_str := 'SELECT s.query, t.node_name, t.db_name, t.tid, (current_timestamp - s.query_start) as runtime FROM pg_catalog.pgxc_stat_activity s, pg_catalog.pgxc_thread_wait_status t WHERE s.application_name=''gs_upgradectl'' AND runtime > '''|| wait_time || ''' AND s.query_id = t.query_id;';
    RAISE INFO 'query_str: %', query_str;
    FOR row_name IN EXECUTE(query_str) LOOP
        RAISE INFO 'query: %, node_name: %, db_name: %, tid: %, runtime: %', row_name.query, row_name.node_name, row_name.db_name, row_name.tid, row_name.runtime;
        -- Kill the background process invoked by non-OM applications.
        kill_str := 'EXECUTE DIRECT ON('|| row_name.node_name ||') ''SELECT pg_catalog.pg_terminate_backend(pid) FROM pg_catalog.pg_locks WHERE relation = (SELECT relation FROM pg_catalog.pg_locks WHERE pid = '|| row_name.tid || ' AND granted IS false) AND pid != '|| row_name.tid || ''';';
        RAISE INFO 'kill_str: %', kill_str;
        EXECUTE kill_str;
    END LOOP;
END;
/