文档首页> 数据仓库服务 GaussDB(DWS)> 故障排除> 数据库使用> 查询表大小时报错:could not open relation with OID xxxx
更新时间:2024-01-25 GMT+08:00

查询表大小时报错:could not open relation with OID xxxx

问题现象

在执行pg_table_size查询表大小时,出现报错:could not open relation with OID xxxx

原因分析

通过执行pg_table_size这个查询接口,对于不存在的表会返回NULL或者报错。

处理方法

  1. 通过Function的exception方式屏蔽该报错,将大小统一到一个值,对于不存在的表,可以用大小为-1来表示,函数如下
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    CREATE OR REPLACE FUNCTION public.pg_t_size(tab_oid OID,OUT retrun_code text) 
    RETURNS text 
    LANGUAGE plpgsql 
    AS $$ DECLARE   
    v_sql text;  
    ts text;   
    BEGIN   
    V_SQL:='select pg_size_pretty(pg_table_size('||tab_oid||'))';   
    EXECUTE IMMEDIATE V_SQL into ts;   
    IF ts IS NULL    
    THEN RETRUN_CODE:=-1;   
    ELSE     
    return ts;   
    END IF;  
    EXCEPTION   
    WHEN OTHERS THEN   
    RETRUN_CODE:=-1;  
    END$$;
    
  2. 执行如下命令查询结果:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    call public.pg_t_size('1','');
     retrun_code
    -------------
     -1
    (1 row)
    
    select oid from pg_class limit 2;
     oid
    ------
     2662
     2659
    (2 rows)
    
    call public.pg_t_size('2662','');
     retrun_code
    -------------
     120 KB
    (1 row)