在特定会话中创建的临时表的大小

时间:2017-08-28 10:43:34

标签: postgresql greenplum

我使用以下查询

创建了一个临时表
Drop table if exists tmp_a;
Create temp table tmp_a
(
    id int
);

Insert into tmp_a select generate_series(1,10000);

当我查询pg_stat_activity时,它显示为" IDLE"在上述会话的current_query列中。

我将使用此query从pg_class表中获取所有临时表的大小。 但是我想要为特定会话创建的临时表列表以及那些临时表的大小,即如果我从两个不同的会话创建了两个临时表,那么结果应该如下所示

procpid | temp table name | size | username    
12345   | tmp_a           | 20   | gpadmin    
12346   | tmp_b           | 30   | gpadmin 

如果有人查询,请分享查询

1 个答案:

答案 0 :(得分:1)

它实际上比你想象的更简单 -
临时模式namesapce与会话标识相同 -

因此...

SELECT
  a.procpid as ProcessID,
  a.sess_id as SessionID,
    n.nspname as SchemaName,
    c.relname as RelationName,
    CASE c.relkind
    WHEN 'r' THEN 'table'
    WHEN 'v' THEN 'view'
    WHEN 'i' THEN 'index'
    WHEN 'S' THEN 'sequence'
    WHEN 's' THEN 'special'
    END as RelationType,
    pg_catalog.pg_get_userbyid(c.relowner) as RelationOwner,
    pg_size_pretty(pg_relation_size(n.nspname ||'.'|| c.relname)) as RelationSize
FROM 
  pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_catalog.pg_stat_activity a ON 'pg_temp_' || a.sess_id::varchar = n.nspname
WHERE  c.relkind IN ('r','s') 
AND  (n.nspname !~ '^pg_toast' and nspname like 'pg_temp%')
ORDER BY pg_relation_size(n.nspname ||'.'|| c.relname) DESC;

你得到 -

 processid | sessionid | schemaname | relationname | relationtype | relationowner | relationsize
-----------+-----------+------------+--------------+--------------+---------------+--------------
      5006 |         9 | pg_temp_9  | tmp_a        | table        | gpadmin       | 384 kB
      5006 |         9 | pg_temp_9  | tmp_b        | table        | gpadmin       | 384 kB
(2 rows)

让我们让这个过程入睡 - 并启动另一个......

gpadmin=#
[1]+  Stopped                 psql

[gpadmin@gpdb-sandbox ~]$ psql
psql (8.2.15)
Type "help" for help.

gpadmin=# SELECT nspname
FROM   pg_namespace
WHERE  oid = pg_my_temp_schema();

 nspname
---------
(0 rows)

gpadmin=# Create temp table tmp_a( id int );
NOTICE:  Table doesn't have 'DISTRIBUTED BY' clause -- Using column named 'id' as the Greenplum Database data distribution key for this table.
HINT:  The 'DISTRIBUTED BY' clause determines the distribution of data. Make sure column(s) chosen are the optimal data distribution key to minimize skew.
CREATE TABLE

gpadmin=# SELECT nspname
FROM   pg_namespace
WHERE  oid = pg_my_temp_schema();

 nspname
---------
 pg_temp_10
(1 row)

... run the same query ...

 processid | sessionid | schemaname | relationname | relationtype | relationowner | relationsize
-----------+-----------+------------+--------------+--------------+---------------+--------------
      5006 |         9 | pg_temp_9  | tmp_a        | table        | gpadmin       | 384 kB
      5006 |         9 | pg_temp_9  | tmp_b        | table        | gpadmin       | 384 kB
     27365 |        10 | pg_temp_10 | tmp_a        | table        | gpadmin       | 384 kB
(3 rows)