developer tip

와일드 카드를 사용하여 PostgreSQL에서 여러 테이블을 삭제하는 방법

optionbox 2020. 11. 7. 09:13
반응형

와일드 카드를 사용하여 PostgreSQL에서 여러 테이블을 삭제하는 방법


파티션으로 작업 할 때 모든 파티션을 한 번에 삭제해야하는 경우가 종종 있습니다.

하나

DROP TABLE tablename*

작동하지 않습니다. (와일드 카드는 존중되지 않습니다).

와일드 카드를 사용하여 하나의 명령으로 여러 테이블을 삭제하는 우아한 (읽기 : 기억하기 쉬운) 방법이 있습니까?


쉼표로 구분 된 목록을 사용하십시오.

DROP TABLE foo, bar, baz;

정말 풋 건이 필요하다면 이건 그 일을 할 것입니다 :

CREATE OR REPLACE FUNCTION footgun(IN _schema TEXT, IN _parttionbase TEXT) 
RETURNS void 
LANGUAGE plpgsql
AS
$$
DECLARE
    row     record;
BEGIN
    FOR row IN 
        SELECT
            table_schema,
            table_name
        FROM
            information_schema.tables
        WHERE
            table_type = 'BASE TABLE'
        AND
            table_schema = _schema
        AND
            table_name ILIKE (_parttionbase || '%')
    LOOP
        EXECUTE 'DROP TABLE ' || quote_ident(row.table_schema) || '.' || quote_ident(row.table_name);
        RAISE INFO 'Dropped table: %', quote_ident(row.table_schema) || '.' || quote_ident(row.table_name);
    END LOOP;
END;
$$;

SELECT footgun('public', 'tablename');

이 문제에 대한 또 다른 hackish 답변이 있습니다. 그것은 ubuntu다른 OS에서도 작동합니다 . \dtpostgres 명령 프롬프트에서 수행하십시오 ( genome-terminal내 경우 에는 명령 프롬프트가 실행 중이었습니다 ). 그러면 터미널에 많은 테이블이 표시됩니다. 이제의 ctrl+click-drag기능을 사용 genome-terminal하여 모든 테이블의 이름을 복사합니다. 여기에 이미지 설명 입력파이썬을 열고 일부 문자열 처리를 수행하면 ( ''를 '로 바꾼 다음'\ n '을', '로) 쉼표로 구분 된 모든 테이블 목록이 표시됩니다. 이제 psql 셸에서 a drop table CTRL+SHIFT+V를 수행하면 완료됩니다. 공유하고 싶었던 것이 너무 구체적이라는 것을 알고 있습니다. :)


나는 이것을 사용했다.

echo "select 'drop table '||tablename||';' from pg_tables where tablename like 'name%'" | \
    psql -U postgres -d dbname -t | \
    psql -U postgres -d dbname

dbname을 적절한 값으로 대체하십시오 name%.


I've always felt way more comfortable creating a sql script I can review and test before I run it than relying on getting the plpgsql just right so it doesn't blow away my database. Something simple in bash that selects the tablenames from the catalog, then creates the drop statements for me. So for 8.4.x you'd get this basic query:

SELECT 'drop table '||n.nspname ||'.'|| c.relname||';' as "Name" 
FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','v','S','')
     AND n.nspname <> 'pg_catalog'
     AND n.nspname <> 'information_schema'
     AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid);

Which you can add a where clause to. (where c.relname ilike 'bubba%')

Output looks like this:

         Name          
-----------------------
 drop table public.a1;
 drop table public.a2;

So, save that to a .sql file and run it with psql -f filename.sql


Disclosure: this answer is meant for Linux users.

I would add some more specific instructions to what @prongs said:

  • \dt can support wildcards: so you can run \dt myPrefix* for example, to select only the tables you want to drop;
  • after CTRL-SHIFT-DRAG to select then CTRL-SHIFT-C to copy the text;
  • in vim, go to INSERT MODE and paste the tables with CTRL-SHIFT-V;
  • press ESC, then run :%s/[ ]*\n/, /g to translate it to comma-separated list, then you can paste it (excluding the last comma) in DROP TABLE % CASCADE.

Using linux command line tools, it can be done this way:

psql -d mydb -P tuples_only=1 -c '\dt' | cut -d '|' -f 2 | paste -sd "," | sed 's/ //g' | xargs -I{} echo psql -d mydb -c "drop table {};"

NOTE: The last echo is there because I couldn't find a way to put quotes around the drop command, so you need to copy and paste the output and add the quotes yourself.

If anyone can fix that minor issue, that'd be awesome sauce.


So I faced this problem today. I loaded my server db through pgadmin3 and did it that way. Tables are sorted alphabetically so shift and click followed by delete works well.

참고URL : https://stackoverflow.com/questions/4202135/how-to-drop-multiple-tables-in-postgresql-using-a-wildcard

반응형