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 exists
CREATE OR REPLACE FUNCTION drop_temp_table_if_exists(table_name text)
RETURNS void AS $$
DECLARE
temp_schema text;
BEGIN
-- Find the temporary schema name for the current session
SELECT nspname INTO temp_schema
FROM pg_namespace
WHERE oid = pg_my_temp_schema();
-- Check if the table exists in the temporary schema
IF EXISTS (
SELECT 1
FROM pg_class c
JOIN pg_namespace n ON c.relnamespace = n.oid
WHERE n.nspname = temp_schema
AND c.relname = table_name
AND c.relkind = 'r' -- 'r' indicates a regular table (in this context, a temp table)
) THEN
-- Construct the dynamic SQL to drop the table
EXECUTE format('DROP TABLE %I', table_name);
END IF;
END;
$$ LANGUAGE plpgsql;
Demonstration:
mytest=# create table t1 (n text);
CREATE TABLE
Time: 4.322 ms
mytest=# insert into t1 values ('regular');
INSERT 0 1
Time: 3.518 ms
mytest=# create temporary table t1 (n text);
CREATE TABLE
Time: 3.192 ms
mytest=# insert into t1 values ('temporary');
INSERT 0 1
Time: 2.869 ms
mytest=# 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 ms
mytest=# select * from t1;
n
---------
regular
(1 row)
Time: 0.251 ms
mytest=# SELECT drop_temp_table_if_exists('t1');
drop_temp_table_if_exists
---------------------------
(1 row)
Time: 0.740 ms
mytest=# select * from t1;
n
---------
regular
(1 row)
Time: 0.410 ms
No comments:
Post a Comment