
CREATE OR REPLACE PROCEDURE Main() AS
$$
DECLARE
 _QueryCount INT DEFAULT 1000000;
 _CancelChance FLOAT8 DEFAULT .0001;
 _RandomSeconds FLOAT8 DEFAULT .1;
 _ConnectionCount INT DEFAULT 50;
 _CancelCount INT DEFAULT 0;
 _FinishedCount INT DEFAULT 0;
 
 _LogInterval INTERVAL DEFAULT '5 seconds'::INTERVAL;
 _LastLogTime TIMESTAMPTZ DEFAULT now();
 
 
 dtc RECORD;
BEGIN
  DROP TABLE IF EXISTS dblink_test_connection;
  
  CREATE TABLE dblink_test_connection
  (
    connection_name text PRIMARY KEY,
    active bool default false,
    cancelling bool default false
  );
  
  INSERT INTO dblink_test_connection 
  SELECT 
    'test_connection_' || s
  FROM generate_series(1, _ConnectionCount) s;
  
  PERFORM dblink_connect(connection_name, '') FROM dblink_test_connection;
  
  LOOP
    FOR dtc IN 
      SELECT * FROM dblink_test_connection
    LOOP
      IF dtc.Active
      THEN
        IF dblink_is_busy(dtc.connection_name) = 1
        THEN
          IF random() < _CancelChance AND NOT dtc.Cancelling
          THEN
            PERFORM dblink_cancel_query(dtc.connection_name);
            UPDATE dblink_test_connection SET Cancelling = true
            WHERE connection_name = dtc.connection_name;
            
            _CancelCount := _CancelCount + 1;
          END IF;
          
          CONTINUE;
        END IF;
        
        _FinishedCount := _FinishedCount + 1;
        
        SET client_min_messages = 'warning';
        PERFORM * FROM dblink_get_result(dtc.connection_name, false) AS R(V INT);
        PERFORM * FROM dblink_get_result(dtc.connection_name, false) AS R(V INT);
        SET client_min_messages = 'notice';
        
        UPDATE dblink_test_connection SET Active = false, cancelling = false
        WHERE connection_name = dtc.connection_name;
        
        CONTINUE;
      END IF;
      
      IF _QueryCount > 0
      THEN
        _QueryCount := _QueryCount - 1;     
        PERFORM dblink_send_query(dtc.connection_name, 
          format('select 0 FROM pg_sleep(%s)', _RandomSeconds * random())); 
        
        UPDATE dblink_test_connection SET Active = true
        WHERE connection_name = dtc.connection_name;
      END IF;
    END LOOP;
    
    IF _QueryCount = 0 AND NOT EXISTS (
        SELECT 1 FROM dblink_test_connection
        WHERE Active)
    THEN
      EXIT;
    END IF;
    
    IF _LastLogTime + _LogInterval < clock_timestamp()
    THEN
      _LastLogTime = clock_timestamp();
      
      RAISE NOTICE '% Active % Cancelling % queries remaning % finished % cancelled ',
        (SELECT count(*) FILTER (WHERE Active) FROM dblink_test_connection),
        (SELECT count(*) FILTER (WHERE Cancelling) FROM dblink_test_connection),
        _QueryCount,
        _FinishedCount,
        _CancelCount;
    END IF;
    
    COMMIT;
  END LOOP;
  
  PERFORM dblink_disconnect(connection_name) FROM dblink_test_connection;
  
  RAISE NOTICE 'Finished';
  
END;
$$ LANGUAGE PLPGSQL;









