/*
 * Tests of the update target definitions
 */
BEGIN;
	-- Make sure we get rid of all existing definitions first
	DELETE FROM sys.update_types;
	DELETE FROM sys.update_targets;

	-- Create a test schema & table which will be used as the target
	CREATE SCHEMA test
		CREATE TABLE test(
			test_id		SERIAL NOT NULL PRIMARY KEY
		)
		CREATE TABLE test2(
			test_id		SERIAL NOT NULL PRIMARY KEY
		);

	-- ***** TESTS BEGIN HERE *****
	SELECT plan( 8 );

	SELECT diag_test_name( 'Update target definitions - Failure if schema/table do not exist' );
	SELECT throws_ok(
			$$ INSERT INTO sys.update_targets(
					updtgt_name , updtgt_schema , updtgt_table
				) VALUES (
					'Test' , 'test' , 'does_not_exist'
				); $$ ,
			23503
		);

	SELECT diag_test_name( 'Update target definitions - Successful insertion' );
	SELECT lives_ok( $$
		INSERT INTO sys.update_targets(
				updtgt_name , updtgt_schema , updtgt_table
			) VALUES (
				'Test' , 'test' , 'test'
			);
	$$ );
	SELECT diag_test_name( 'Update target definitions - Specific update table - Exists after insertion' );
	SELECT has_table( 'test' , 'test_updates' , 'No specific update table' );
	SELECT diag_test_name( 'Update target definitions - Specific update table - Primary key' );
	SELECT index_is_primary( 'test' , 'test_updates' , 'test_updates_pkey' );
	SELECT diag_test_name( 'Update target definitions - Specific update table - Primary key definition' );
	SELECT has_index( 'test' , 'test_updates' , 'test_updates_pkey' ,
		ARRAY[ 'updtgt_id' , 'updtype_id' , 'update_id' , 'test_id' ] );

	SELECT diag_test_name( 'Update target definitions - Duplicate name' );
	SELECT throws_ok( $$
		INSERT INTO sys.update_targets(
				updtgt_name , updtgt_schema , updtgt_table
			) VALUES (
				'Test' , 'test' , 'test2'
			);
	$$ , 23505 );

	SELECT diag_test_name( 'Update target definitions - Duplicate table reference' );
	SELECT throws_ok( $$
		INSERT INTO sys.update_targets(
				updtgt_name , updtgt_schema , updtgt_table
			) VALUES (
				'Test 2' , 'test' , 'test'
			);
	$$ , 23505 );

	SELECT diag_test_name( 'Update target definitions - Deletion drops the specific update table' );
	DELETE FROM sys.update_targets;
	SELECT hasnt_table( 'test' , 'test_updates' , 'Specific update table still exists' );

	SELECT * FROM finish( );
ROLLBACK;