In PostgreSQL, it allows to create temporary table with same name as existing regular table, in such case, temporary table has higher "visibility" than regular table.
Once you drop the temporary table, you can see the data in regular table again. But, if you issue drop table twice, then you drop both temporary table and regular table.
How to prevent regular table being dropped?
Here is a wrapper to safeguard this:
-- Function to drop a temporary table if it existsCREATE OR REPLACE FUNCTION drop_temp_table_if_exists(table_name text)RETURNS void AS $$DECLAREtemp_schema text;BEGIN-- Find the temporary schema name for the current sessionSELECT nspname INTO temp_schemaFROM pg_namespaceWHERE oid = pg_my_temp_schema();-- Check if the table exists in the temporary schemaIF EXISTS (SELECT 1FROM pg_class cJOIN pg_namespace n ON c.relnamespace = n.oidWHERE n.nspname = temp_schemaAND c.relname = table_nameAND c.relkind = 'r' -- 'r' indicates a regular table (in this context, a temp table)) THEN-- Construct the dynamic SQL to drop the tableEXECUTE format('DROP TABLE %I', table_name);END IF;END;$$ LANGUAGE plpgsql;
Demonstration:
mytest=# create table t1 (n text);CREATE TABLETime: 4.322 msmytest=# insert into t1 values ('regular');INSERT 0 1Time: 3.518 msmytest=# create temporary table t1 (n text);CREATE TABLETime: 3.192 msmytest=# insert into t1 values ('temporary');INSERT 0 1Time: 2.869 msmytest=# select * from t1;n-----------temporary(1 row)mytest=# SELECT drop_temp_table_if_exists('t1');drop_temp_table_if_exists---------------------------(1 row)Time: 5.620 msmytest=# select * from t1;n---------regular(1 row)Time: 0.251 msmytest=# SELECT drop_temp_table_if_exists('t1');drop_temp_table_if_exists---------------------------(1 row)Time: 0.740 msmytest=# select * from t1;n---------regular(1 row)Time: 0.410 ms
No comments:
Post a Comment