From 55a77b0ef0a75292803640911c2bb71ddc4d010b Mon Sep 17 00:00:00 2001 From: Rafa de la Torre Date: Tue, 3 Jul 2018 13:00:24 +0200 Subject: [PATCH] Add a new helper function _CDB_Table_Exists --- Makefile | 3 ++- scripts-available/CDB_Helper.sql | 18 ++++++++++++++++++ test/CDB_HelperTest.sql | 10 ++++++++++ test/CDB_HelperTest_expect | 8 ++++++++ 4 files changed, 38 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index d72f7cc..f0925e7 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ # cartodb/Makefile EXTENSION = cartodb -EXTVERSION = 0.22.2 +EXTVERSION = 0.22.3 SED = sed AWK = awk @@ -88,6 +88,7 @@ UPGRADABLE = \ 0.22.0 \ 0.22.1 \ 0.22.2 \ + 0.22.3 \ $(EXTVERSION)dev \ $(EXTVERSION)next \ $(END) diff --git a/scripts-available/CDB_Helper.sql b/scripts-available/CDB_Helper.sql index 2732ac9..8d3c663 100644 --- a/scripts-available/CDB_Helper.sql +++ b/scripts-available/CDB_Helper.sql @@ -158,3 +158,21 @@ BEGIN RETURN left(string, (i - 1)); END; $$ LANGUAGE 'plpgsql' IMMUTABLE PARALLEL SAFE; + + +-- Checks if a given text representing a qualified or unqualified table name (relation) +-- actually exists in the database. It is meant to be used as a guard for other function/queries. +CREATE FUNCTION cartodb._CDB_Table_Exists(table_name_with_optional_schema TEXT) +RETURNS bool +AS $$ +BEGIN + IF EXISTS(SELECT * FROM pg_class WHERE table_name_with_optional_schema::regclass::oid = oid AND relkind = 'r') THEN + RETURN true; + ELSE + RETURN false; + END IF; +EXCEPTION + WHEN invalid_schema_name OR undefined_table THEN + RETURN false; +END; +$$ LANGUAGE PLPGSQL VOLATILE PARALLEL SAFE; diff --git a/test/CDB_HelperTest.sql b/test/CDB_HelperTest.sql index ac543f5..f33c2c7 100644 --- a/test/CDB_HelperTest.sql +++ b/test/CDB_HelperTest.sql @@ -126,3 +126,13 @@ SELECT * FROM cartodb._CDB_Octet_Truncate('piraña', 6); -- Test _CDB_Octet_Truncate UTF8 case SELECT * FROM cartodb._CDB_Octet_Truncate('piraña', 7); + +-- Test _CDB_Table_Exists +CREATE TABLE public.this_table_exists(); +SELECT cartodb._CDB_Table_Exists('this_table_does_not_exist'); +SELECT cartodb._CDB_Table_Exists('this_schema_does_not_exist.this_table_does_not_exist'); +SELECT cartodb._CDB_Table_Exists('this_table_exists'); +SELECT cartodb._CDB_Table_Exists('public.this_table_exists'); +SELECT cartodb._CDB_Table_Exists('raster_overviews'); -- view created by postgis +SELECT cartodb._CDB_Table_Exists('public.raster_overviews'); +DROP TABLE public.this_table_exists diff --git a/test/CDB_HelperTest_expect b/test/CDB_HelperTest_expect index 10a8d48..5ef82e5 100644 --- a/test/CDB_HelperTest_expect +++ b/test/CDB_HelperTest_expect @@ -57,3 +57,11 @@ DROP TABLE pira pirañ piraña +CREATE TABLE +f +f +t +t +f +f +DROP TABLE