-- Ends any "add column" change that an interrupted earlier run left waiting for a table lock. While it waits it holds up every
-- other read of that table (the Contacts screen stopped answering). Only threads running exactly those ALTER statements are
-- ended; nothing else is touched. Safe to run any time: with nothing waiting it does nothing.
DROP PROCEDURE IF EXISTS tmp_end_stuck_alters;
DELIMITER //
CREATE PROCEDURE tmp_end_stuck_alters()
BEGIN
    DECLARE done INT DEFAULT 0;
    DECLARE pid BIGINT;
    DECLARE cur CURSOR FOR
        SELECT id FROM information_schema.PROCESSLIST
        WHERE id <> CONNECTION_ID()
          AND (info LIKE 'ALTER TABLE dim_contacts ADD COLUMN last_contacted_at%'
            OR info LIKE 'ALTER TABLE dim_web_sites ADD COLUMN portal_password_hash%');
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    OPEN cur;
    read_loop: LOOP
        FETCH cur INTO pid;
        IF done THEN LEAVE read_loop; END IF;
        SET @kill_sql = CONCAT('KILL ', pid);
        PREPARE kill_stmt FROM @kill_sql;
        EXECUTE kill_stmt;
        DEALLOCATE PREPARE kill_stmt;
    END LOOP;
    CLOSE cur;
END//
DELIMITER ;
CALL tmp_end_stuck_alters();
DROP PROCEDURE IF EXISTS tmp_end_stuck_alters;
