【问题标题】:Phantom Postgres table exists but can't be dropped?Phantom Postgres 表存在但不能删除?
【发布时间】:2018-03-26 22:48:01
【问题描述】:

我似乎在 Postgres 中有某种幻像表。

假设我执行以下操作:

select * from information_schema.tables where table_schema = 'public';

我明白了:

table_name     | table_type | ...
phantom_table    BASE TABLE
...

所以,我跑了:

drop table phantom_table cascade;

我得到:

ERROR: table "phantom_table" does not exist

我尝试过的事情:

  1. 检查拼写错误并确保架构正确(我什至从信息架构查询结果中复制/粘贴了表名)。
  2. vacuum
  3. 正在重新连接。
  4. 从我的用户那里杀死其他正在运行的进程(没有其他人在使用数据库)。
  5. 检查表上的活动锁(没有任何锁)。

有人对我应该尝试的事情有任何其他想法吗?

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    您可能在名称末尾有一些空格。

    最简单的方法是让format() 函数为您生成正确的表名和语句:

    select format('drop table %I.%I;', table_schema, table_name) as drop_statement
    from information_schema.tables 
    where table_schema = 'public'
      and table_name like '%phantom%';
    

    编辑:Windows 上的psql 似乎无法在drop 语句中处理带有新行的标识符(但在创建表时会这样做)。

    要解决此问题,您可以使用 DO 块:

    do
    $$
    declare
     l_stmt text;
    begin
      select format('drop table %I.%I;', table_schema, table_name) as drop_statement
        into l_stmt
      from information_schema.tables 
      where table_schema = 'public'
        and table_name like '%phantom%';
      execute l_stmt;    
    end;
    $$
    ;
    

    请注意,此代码假定仅存在一个具有该名称的表。

    【讨论】:

    • 有趣...我得到的 drop 语句确实在表名中有换行符,但该语句仍然没有运行。
    • @JohnChrysostom:那么您的名称中确实有一些空格。但是生成的语句应该可以应付。
    • 无法使生成的语句正常工作 - 我怀疑我正在与 Windows/Unix 换行符差异作斗争。能够使用此功能的修改版本完成它,但是...stackoverflow.com/questions/4202135/… 感谢您的帮助。
    猜你喜欢
    • 2022-08-15
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 2021-09-27
    相关资源
    最近更新 更多