/**
 * Test for view statistics_query_activity
 *
 * Every test does raise division by zero if it failes
 *
 * @author: "Stefanie Janine Stölting"<stefanie@proopensource.eu>
 * @license: PostgreSQL https://opensource.org/licenses/postgresql
 */

 DO $$
 DECLARE
 	pg_extension_installed BOOLEAN;
  	version_greater_13 BOOLEAN;
	test_result BOOLEAN;
 BEGIN
	 SELECT count(*) > 0 AS pg_stat_statements_exists
	 FROM pg_extension
	 WHERE extname = 'pg_stat_statements'
	 INTO pg_extension_installed
	 ;

 	SELECT to_number((string_to_array(version(), ' '))[2], '999.99') >= 14
	INTO version_greater_13;
 	
 	IF pg_extension_installed AND version_greater_13 THEN
		-- Test if the function exists
		WITH test AS
			(
				SELECT COUNT(*) AS exist
					, 0 AS zero
				FROM pg_catalog.pg_views
				WHERE viewname = 'statistics_query_activity'
			)
		SELECT
			CASE
				WHEN 1 / test.exist = 1 THEN
					TRUE
				ELSE
					(1 / zero)::BOOLEAN
			END AS res
			INTO test_result
		FROM test
		;
		
		-- Test if the view runs without errors
		SELECT true
		INTO test_result
		FROM statistics_query_activity
		;
	END IF;
END
$$;