/*
 * Test the sys.start_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 );

	-- ***** TESTS BEGIN HERE *****
	SELECT plan( 5 );
	
	UPDATE sys.status SET maintenance_start = now( ) , current_tick = NULL;
	SELECT diag_test_name( 'sys.start_tick() - Ticks do not start if maintenance mode is active' );
	SELECT ok( sys.start_tick( ) IS NULL );
	
	UPDATE sys.status SET maintenance_start = NULL , current_tick = next_tick;
	SELECT diag_test_name( 'sys.start_tick() - Ticks do not start if current_tick is set' );
	SELECT ok( sys.start_tick( ) IS NULL );
	
	UPDATE sys.status SET current_tick = NULL , next_tick = 2;
	UPDATE sys.updates SET update_state = 'PROCESSED' , update_last = -1;
	UPDATE sys.updates su SET update_last = 514
		FROM test.test_updates tu
		WHERE su.update_id = tu.update_id
			AND tu.test_id = 3;
	SELECT diag_test_name( 'sys.start_tick() - Returns next tick identifier when ticks can start' );
	SELECT is( sys.start_tick( ) , 2::BIGINT );
	SELECT diag_test_name( 'sys.start_tick() - System status is updated' );
	SELECT set_eq(
		$$ SELECT current_tick , next_tick FROM sys.status $$ ,
		$$ VALUES ( 2 , 3 ) $$
	);
	SELECT diag_test_name( 'sys.start_tick() - Update rows are marked for processing when necessary' );
	SELECT set_eq(
		$$ SELECT test_id
			FROM test.test_updates
				INNER JOIN sys.updates
					USING ( update_id , updtgt_id , updtype_id )
			WHERE update_state = 'FUTURE' AND update_last = 2 $$ ,
		$$ VALUES ( 1 ) , ( 2 ) $$
	);

	SELECT * FROM finish( );
ROLLBACK;