/**
 * Test for view statistics_top_ten_time_consuming_queries
 *
 * 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;
	view_source TEXT;
BEGIN

	SELECT count(*) AS pg_stat_statements_exists
	FROM pg_extension
	WHERE extname = 'pg_stat_statements'
	INTO pg_extension_installed
	;

	IF pg_extension_installed THEN
		-- Check view existence
		view_source :=
$string$
WITH test AS
	(
		SELECT COUNT(*) AS exist
			, 0 AS zero
		FROM pg_catalog.pg_views
		WHERE viewname = 'statistics_top_ten_time_consuming_queries'
	)
SELECT
	CASE
		WHEN 1 / test.exist = 1 THEN
			TRUE
		ELSE
			(1 / zero)::BOOLEAN
	END AS res
FROM test
;
$string$
;

		EXECUTE view_source;

		-- Test if the view runs without errors
		view_source :=
$string$
SELECT *
FROM statistics_top_ten_time_consuming_queries
;
$string$
;

		EXECUTE view_source;
	END IF;

END $$;
