142

是否可以在每个表的每一列中搜索PostgreSQL 中的特定值?

Oracle有一个类似的问题

4

9 回答 9

155

如何转储数据库的内容,然后使用grep

$ pg_dump --data-only --inserts -U postgres your-db-name > a.tmp
$ grep United a.tmp
INSERT INTO countries VALUES ('US', 'United States');
INSERT INTO countries VALUES ('GB', 'United Kingdom');

相同的实用程序 pg_dump 可以在输出中包含列名。只需更改--inserts--column-inserts. 这样您也可以搜索特定的列名。但如果我正在寻找列名,我可能会转储模式而不是数据。

$ pg_dump --data-only --column-inserts -U postgres your-db-name > a.tmp
$ grep country_code a.tmp
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('US', 'United  States');
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('GB', 'United Kingdom');
于 2011-03-18T11:55:59.880 回答
93

这是一个pl/pgsql 函数,它定位任何列包含特定值的记录。它将以文本格式搜索的值、要搜索的表名数组(默认为所有表)和模式名数组(默认为所有模式名)作为参数。

它返回一个表结构,其中包含模式、表名、列名和伪列ctid(表中行的非持久物理位置,请参阅System Columns

CREATE OR REPLACE FUNCTION search_columns(
    needle text,
    haystack_tables name[] default '{}',
    haystack_schema name[] default '{}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
  FOR schemaname,tablename,columnname IN
      SELECT c.table_schema,c.table_name,c.column_name
      FROM information_schema.columns c
        JOIN information_schema.tables t ON
          (t.table_name=c.table_name AND t.table_schema=c.table_schema)
        JOIN information_schema.table_privileges p ON
          (t.table_name=p.table_name AND t.table_schema=p.table_schema
              AND p.privilege_type='SELECT')
        JOIN information_schema.schemata s ON
          (s.schema_name=t.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND (c.table_schema=ANY(haystack_schema) OR haystack_schema='{}')
        AND t.table_type='BASE TABLE'
  LOOP
    FOR rowctid IN
      EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
       schemaname,
       tablename,
       columnname,
       needle
      )
    LOOP
      -- uncomment next line to get some progress report
      -- RAISE NOTICE 'hit in %.%', schemaname, tablename;
      RETURN NEXT;
    END LOOP;
 END LOOP;
END;
$$ language plpgsql;

另请参阅github 上基于相同原理但增加了一些速度和报告改进的版本。

在测试数据库中的使用示例:

  • 在公共架构中的所有表中搜索:
select * from search_columns('foobar');
 模式名 | 表名 | 列名 | 行号
------------+-----------+------------+---------
 公共 | s3 | 用户名 | (0,11)
 公共 | s2 | 相对名称 | (7,29)
 公共 | w | 身体 | (0,2)
(3 行)
  • 在特定表中搜索:
select * from search_columns('foobar','{w}');
 模式名 | 表名 | 列名 | 行号
------------+-----------+------------+---------
 公共 | w | 身体 | (0,2)
(1 行)
  • 在从 select 获得的表子集中搜索:
select * from search_columns('foobar', array(select table_name::name from information_schema.tables where table_name like 's%'), array['public']);
 模式名 | 表名 | 列名 | 行号
------------+-----------+------------+---------
 公共 | s2 | 相对名称 | (7,29)
 公共 | s3 | 用户名 | (0,11)
(2 行)
  • 获取具有相应基表和 ctid 的结果行:
select * from public.w where ctid='(0,2)';
 标题 | 身体 | tsv         
--------+--------+----------
 多多| 吧台 | 'foobar':2 'toto':1

变体

  • 要针对正则表达式而不是严格相等进行测试,例如 grep,查询的这一部分:

    SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L

    可以改为:

    SELECT ctid FROM %I.%I WHERE cast(%I as text) ~ %L

  • 对于不区分大小写的比较,您可以编写:

    SELECT ctid FROM %I.%I WHERE lower(cast(%I as text)) = lower(%L)

于 2014-04-12T21:37:58.793 回答
12

在每个表的每一列中搜索特定值

这并没有定义如何精确匹配。
它也没有定义确切返回的内容。

假设:

  • 在其文本表示中查找具有包含给定值的任何列的任何行 - 而不是等于给定值。
  • 返回表名 ( regclass) 和元组 ID ( ctid),因为这是最简单的。

这是一个非常简单、快速且略显肮脏的方法:

CREATE OR REPLACE FUNCTION search_whole_db(_like_pattern text)
  RETURNS TABLE(_tbl regclass, _ctid tid) AS
$func$
BEGIN
   FOR _tbl IN
      SELECT c.oid::regclass
      FROM   pg_class c
      JOIN   pg_namespace n ON n.oid = relnamespace
      WHERE  c.relkind = 'r'                           -- only tables
      AND    n.nspname !~ '^(pg_|information_schema)'  -- exclude system schemas
      ORDER BY n.nspname, c.relname
   LOOP
      RETURN QUERY EXECUTE format(
         'SELECT $1, ctid FROM %s t WHERE t::text ~~ %L'
       , _tbl, '%' || _like_pattern || '%')
      USING _tbl;
   END LOOP;
END
$func$  LANGUAGE plpgsql;

称呼:

SELECT * FROM search_whole_db('mypattern');

提供不包含的搜索模式%

为什么有点脏?

如果表示中行的分隔符和装饰器text可以成为搜索模式的一部分,则可能会出现误报:

  • 列分隔符:,默认
  • 整行括在括号中:()
  • 一些值用双引号括起来"
  • \可以添加为转义字符

并且某些列的文本表示可能取决于本地设置 - 但这种歧义是问题所固有的,而不是我的解决方案。

每个符合条件的行仅返回一次,即使它匹配多次(与此处的其他答案相反)。

这将搜索除系统目录之外的整个数据库。通常需要很长时间才能完成。您可能希望限制为某些模式/表(甚至列),如其他答案中所示。或者添加通知和进度指示器,也在另一个答案中演示。

regclass对象标识符类型表示为表名,在需要根据当前消除歧义的情况下进行模式限定search_path

是什么ctid

您可能希望在搜索模式中转义具有特殊含义的字符。看:

于 2018-04-25T14:21:52.930 回答
9

有一种方法可以在不创建函数或使用外部工具的情况下实现这一点。通过使用query_to_xml()可以在另一个查询中动态运行查询的 Postgres 功能,可以跨多个表搜索文本。这是基于我对检索所有表的行数的回答:

要在架构中的所有表中搜索字符串foo,可以使用以下命令:

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
  left join xmltable('//table/row' 
                     passing table_rows
                       columns
                         table_row text path 'table_row') as x on true

请注意,使用xmltable需要 Postgres 10 或更高版本。对于旧的 Postgres 版本,这也可以使用 xpath() 来完成。

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
   cross join unnest(xpath('/table/row/table_row/text()', table_rows)) as r(data)

公用表表达式 ( WITH ...) 仅用于方便。它遍历public模式中的所有表。对于每个表,通过该query_to_xml()函数运行以下查询:

select to_jsonb(t)
from some_table t
where t::text like '%foo%';

where 子句用于确保仅对包含搜索字符串的行进行昂贵的 XML 内容生成。这可能会返回如下内容:

<table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
  <table_row>{"id": 42, "some_column": "foobar"}</table_row>
</row>
</table>

完成了整个行到的转换jsonb,以便在结果中可以看到哪个值属于哪个列。

以上可能会返回如下内容:

table_name   |   table_row
-------------+----------------------------------------
public.foo   |  {"id": 1, "some_column": "foobar"}
public.bar   |  {"id": 42, "another_column": "barfoo"}

Postgres 10+ 的在线示例

旧 Postgres 版本的在线示例

于 2019-07-01T15:04:29.050 回答
5

如果有人认为它可以提供帮助。这是@Daniel Vérité 的函数,带有另一个接受可用于搜索的列名称的参数。这样可以减少处理时间。至少在我的测试中它减少了很多。

CREATE OR REPLACE FUNCTION search_columns(
    needle text,
    haystack_columns name[] default '{}',
    haystack_tables name[] default '{}',
    haystack_schema name[] default '{public}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
  FOR schemaname,tablename,columnname IN
      SELECT c.table_schema,c.table_name,c.column_name
      FROM information_schema.columns c
      JOIN information_schema.tables t ON
        (t.table_name=c.table_name AND t.table_schema=c.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND c.table_schema=ANY(haystack_schema)
        AND (c.column_name=ANY(haystack_columns) OR haystack_columns='{}')
        AND t.table_type='BASE TABLE'
  LOOP
    EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
       schemaname,
       tablename,
       columnname,
       needle
    ) INTO rowctid;
    IF rowctid is not null THEN
      RETURN NEXT;
    END IF;
 END LOOP;
END;
$$ language plpgsql;

Bellow 是使用上面创建的 search_function 的示例。

SELECT * FROM search_columns('86192700'
    , array(SELECT DISTINCT a.column_name::name FROM information_schema.columns AS a
            INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)
        WHERE 
            a.column_name iLIKE '%cep%' 
            AND b.table_type = 'BASE TABLE'
            AND b.table_schema = 'public'
    )

    , array(SELECT b.table_name::name FROM information_schema.columns AS a
            INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)
        WHERE 
            a.column_name iLIKE '%cep%' 
            AND b.table_type = 'BASE TABLE'
            AND b.table_schema = 'public')
);
于 2014-09-18T14:25:17.907 回答
5

在不存储新过程的情况下,您可以使用代码块并执行来获取出现表。您可以按架构、表或列名过滤结果。

DO $$
DECLARE
  value int := 0;
  sql text := 'The constructed select statement';
  rec1 record;
  rec2 record;
BEGIN
  DROP TABLE IF EXISTS _x;
  CREATE TEMPORARY TABLE _x (
    schema_name text, 
    table_name text, 
    column_name text,
    found text
  );
  FOR rec1 IN 
        SELECT table_schema, table_name, column_name
        FROM information_schema.columns 
        WHERE table_name <> '_x'
                AND UPPER(column_name) LIKE UPPER('%%')                  
                AND table_schema <> 'pg_catalog'
                AND table_schema <> 'information_schema'
                AND data_type IN ('character varying', 'text', 'character', 'char', 'varchar')
        LOOP
    sql := concat('SELECT ', rec1."column_name", ' AS "found" FROM ',rec1."table_schema" , '.',rec1."table_name" , ' WHERE UPPER(',rec1."column_name" , ') LIKE UPPER(''','%my_substring_to_find_goes_here%' , ''')');
    RAISE NOTICE '%', sql;
    BEGIN
        FOR rec2 IN EXECUTE sql LOOP
            RAISE NOTICE '%', sql;
            INSERT INTO _x VALUES (rec1."table_schema", rec1."table_name", rec1."column_name", rec2."found");
        END LOOP;
    EXCEPTION WHEN OTHERS THEN
    END;
  END LOOP;
  END; $$;

SELECT * FROM _x;
于 2016-09-13T15:22:18.000 回答
4

如果您使用 IntelliJ 将数据库添加到数据库视图,然后右键单击数据库并选择全文搜索,它将列出您的特定文本的所有表和所有字段。

于 2020-12-10T13:16:01.653 回答
3

这是@Daniel Vérité 的带有进度报告功能的函数。它以三种方式报告进度:

  1. 发出通知;
  2. 通过将提供的 {progress_seq} 序列的值从 {total number of column to search in} 减少到 0;
  3. 通过将进度与找到的表一起写入位于 c:\windows\temp\{progress_seq}.txt 中的文本文件。

_

CREATE OR REPLACE FUNCTION search_columns(
    needle text,
    haystack_tables name[] default '{}',
    haystack_schema name[] default '{public}',
    progress_seq text default NULL
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
DECLARE
currenttable text;
columnscount integer;
foundintables text[];
foundincolumns text[];
begin
currenttable='';
columnscount = (SELECT count(1)
      FROM information_schema.columns c
      JOIN information_schema.tables t ON
        (t.table_name=c.table_name AND t.table_schema=c.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND c.table_schema=ANY(haystack_schema)
        AND t.table_type='BASE TABLE')::integer;
PERFORM setval(progress_seq::regclass, columnscount);

  FOR schemaname,tablename,columnname IN
      SELECT c.table_schema,c.table_name,c.column_name
      FROM information_schema.columns c
      JOIN information_schema.tables t ON
        (t.table_name=c.table_name AND t.table_schema=c.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND c.table_schema=ANY(haystack_schema)
        AND t.table_type='BASE TABLE'
  LOOP
    EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
       schemaname,
       tablename,
       columnname,
       needle
    ) INTO rowctid;
    IF rowctid is not null THEN
      RETURN NEXT;
      foundintables = foundintables || tablename;
      foundincolumns = foundincolumns || columnname;
      RAISE NOTICE 'FOUND! %, %, %, %', schemaname,tablename,columnname, rowctid;
    END IF;
         IF (progress_seq IS NOT NULL) THEN 
        PERFORM nextval(progress_seq::regclass);
    END IF;
    IF(currenttable<>tablename) THEN  
    currenttable=tablename;
     IF (progress_seq IS NOT NULL) THEN 
        RAISE NOTICE 'Columns left to look in: %; looking in table: %', currval(progress_seq::regclass), tablename;
        EXECUTE 'COPY (SELECT unnest(string_to_array(''Current table (column ' || columnscount-currval(progress_seq::regclass) || ' of ' || columnscount || '): ' || tablename || '\n\nFound in tables/columns:\n' || COALESCE(
        (SELECT string_agg(c1 || '/' || c2, '\n') FROM (SELECT unnest(foundintables) AS c1,unnest(foundincolumns) AS c2) AS t1)
        , '') || ''',''\n''))) TO ''c:\WINDOWS\temp\' || progress_seq || '.txt''';
    END IF;
    END IF;
 END LOOP;
END;
$$ language plpgsql;
于 2014-08-22T12:12:42.307 回答
3

-- 下面的函数将列出数据库中包含特定字符串的所有表

 select TablesCount(‘StringToSearch’);

--遍历数据库中的所有表

CREATE OR REPLACE FUNCTION **TablesCount**(_searchText TEXT)
RETURNS text AS 
$$ -- here start procedural part
   DECLARE _tname text;
   DECLARE cnt int;
   BEGIN
    FOR _tname IN SELECT table_name FROM information_schema.tables where table_schema='public' and table_type='BASE TABLE'  LOOP
         cnt= getMatchingCount(_tname,Columnames(_tname,_searchText));
                                RAISE NOTICE 'Count% ', CONCAT('  ',cnt,' Table name: ', _tname);
                END LOOP;
    RETURN _tname;
   END;
$$ -- here finish procedural part
LANGUAGE plpgsql; -- language specification

-- 返回满足条件的表的计数。-- 例如,如果预期的文本存在于表的任何字段中, -- 那么计数将大于 0。我们可以在 postgres 数据库的结果查看器的 Messages 部分找到通知。

CREATE OR REPLACE FUNCTION **getMatchingCount**(_tname TEXT, _clause TEXT)
RETURNS int AS 
$$
Declare outpt text;
    BEGIN
    EXECUTE 'Select Count(*) from '||_tname||' where '|| _clause
       INTO outpt;
       RETURN outpt;
    END;
$$ LANGUAGE plpgsql;

--获取每个表的字段。使用表的所有列构建 where 子句。

CREATE OR REPLACE FUNCTION **Columnames**(_tname text,st text)
RETURNS text AS 
$$ -- here start procedural part
DECLARE
                _name text;
                _helper text;
   BEGIN
                FOR _name IN SELECT column_name FROM information_schema.Columns WHERE table_name =_tname LOOP
                                _name=CONCAT('CAST(',_name,' as VarChar)',' like ','''%',st,'%''', ' OR ');
                                _helper= CONCAT(_helper,_name,' ');
                END LOOP;
                RETURN CONCAT(_helper, ' 1=2');

   END;
$$ -- here finish procedural part
LANGUAGE plpgsql; -- language specification
于 2019-02-05T08:14:22.110 回答