/*
 * Tests of the sys.check_stuck_tick() function
 */
BEGIN;
	-- Delete all registered update types and targets
	DELETE FROM sys.update_types;
	DELETE FROM sys.update_targets;
	
	-- Create a new update target / type which will be used in tests
	CREATE SCHEMA test
		CREATE TABLE test( test_id INT NOT NULL PRIMARY KEY );
	INSERT INTO sys.update_targets VALUES ( 1 , 'Test' , 'test' , 'test' );
	INSERT INTO sys.update_types VALUES ( 1 , 1 , 'Test' , 2 , '' , NULL , NULL );
	
	-- Insert a few update rows
	INSERT INTO test.test VALUES ( 1 ) , ( 2 ) , ( 3 );

	-- Replace sys.end_tick() with a function that inserts into some table
	CREATE TABLE end_tick_calls( tick_id BIGINT NOT NULL );
	CREATE OR REPLACE FUNCTION sys.end_tick( tick_id BIGINT )
		RETURNS VOID LANGUAGE SQL
		AS 'INSERT INTO end_tick_calls VALUES( $1 );';

	-- ***** TESTS BEGIN HERE *****
	SELECT plan( 8 );
	
	UPDATE sys.status SET maintenance_start = NULL , current_tick = NULL;
	SELECT diag_test_name( 'sys.check_stuck_tick() - Returns NULL if no tick is in progress' );
	SELECT ok( sys.check_stuck_tick() IS NULL );
	SELECT diag_test_name( 'sys.check_stuck_tick() - Does not call sys.end_tick() if no tick is in progress' );
	SELECT is_empty( $$ SELECT * FROM end_tick_calls $$ );
	DELETE FROM end_tick_calls;

	UPDATE sys.status SET maintenance_start = now( ) , current_tick = 2;
	SELECT diag_test_name( 'sys.check_stuck_tick() - Returns NULL if maintenance mode is enabled' );
	SELECT ok( sys.check_stuck_tick() IS NULL );
	SELECT diag_test_name( 'sys.check_stuck_tick() - Does not call sys.end_tick() if maintenance mode is enabled' );
	SELECT is_empty( $$ SELECT * FROM end_tick_calls $$ );
	DELETE FROM end_tick_calls;

	UPDATE sys.status SET maintenance_start = NULL , current_tick = 2;
	UPDATE sys.updates SET update_state = 'PROCESSED' , update_last = 2;
	SELECT diag_test_name( 'sys.check_stuck_tick() - Returns NULL if a tick is in progress but there are no updates left' );
	SELECT ok( sys.check_stuck_tick() IS NULL );
	SELECT diag_test_name( 'sys.check_stuck_tick() - Calls sys.end_tick() if a tick is in progress but there are no updates left' );
	SELECT set_eq(
		$$ SELECT * FROM end_tick_calls $$ ,
		$$ VALUES ( 2 ) $$
	);
	DELETE FROM end_tick_calls;

	UPDATE sys.status SET maintenance_start = NULL , current_tick = 2;
	UPDATE sys.updates SET update_state = 'FUTURE' , update_last = 2;
	SELECT diag_test_name( 'sys.check_stuck_tick() - Returns tick identifier if a tick is in progress and there are updates left' );
	SELECT is( sys.check_stuck_tick() , 2::BIGINT );
	SELECT diag_test_name( 'sys.check_stuck_tick() - Does not call sys.end_tick() if a tick is in progress and there are updates left' );
	SELECT is_empty( $$ SELECT * FROM end_tick_calls $$ );

	SELECT * FROM finish( );
ROLLBACK;