Postgresql

Postgres - 僅嘗試備份功能

  • December 10, 2020

我正在嘗試遵循 Craig Ringer 對這個問題的回答:

https ://stackoverflow.com/questions/13758003/how-to-take-backup-of-functions-only-in-postgres

我的命令是:

psql -U username -AT db_name -c "
   SELECT pg_get_functiondef(f.oid) 
   FROM pg_catalog.pg_proc f 
   INNER JOIN pg_catalog.pg_namespace n ON (f.pronamespace = n.oid) 
   WHERE n.nspname = 'public'
" > /dump/file/functions.sql

但我收到以下錯誤:

Error: "st_extent" is an aggregate function

為什麼它不喜歡聚合函式?我能做些什麼來解決這個問題?

這至少有兩個問題:

  1. 不要包含擴展安裝的功能。只需安裝擴展程序即可將該功能“恢復”到任何其他數據庫。
  2. 聚合函式完全不同,必須分開處理。語法CREATE AGGREGATE不同於.CREATE FUNCTION
  3. 您不想包含COMMENT每個功能嗎?(如果存在的話。)

我建議這兩個查詢:

職能

-- SET LOCAL search_path = '';  -- force schema-qualification everywhere
SELECT pg_get_functiondef(p.oid) AS function
    , 'COMMENT ON FUNCTION ' || p.oid::regprocedure
      || ' IS ' || quote_literal(obj_description(p.oid, 'pg_proc')) AS comment
FROM   pg_proc p
JOIN   pg_namespace n ON n.oid = p.pronamespace
WHERE  n.nspname !~ '^(pg_|information_schema)'    -- exclude system schemas
-- AND    n.nspname =  ...                         -- or from selected schema only?
AND    NOT EXISTS (                                -- exclude functions from extensions
  SELECT FROM pg_depend 
  WHERE  objid = p.oid 
  AND    deptype = 'e'
  )
--    AND    NOT p.proisagg                        -- exclude aggregate functions! for pg 10 or older
AND    NOT p.prokind = 'f'                         -- only normal functions! pg 11+
ORDER  BY n.nspname, p.proname;

各種類型的依賴項都儲存在系統目錄中pg_dependdeptype = 'e'表示它是擴展的一部分。

關於proisaggvs prokind

聚合(=聚合函式)

-- SET LOCAL search_path = '';  -- force schema-qualification everywhere
SELECT format('CREATE AGGREGATE %s (SFUNC = %s, STYPE = %s%s%s%s%s)'
           , a.aggfnoid::regprocedure
           , a.aggtransfn
           , a.aggtranstype::regtype
           , ', SORTOP = '    || NULLIF(a.aggsortop, 0)::regoper
           , ', INITCOND = '  || a.agginitval
           , ', FINALFUNC = ' || NULLIF(a.aggfinalfn, 0)
           , CASE WHEN a.aggfinalextra THEN ', FINALFUNC_EXTRA' END
           --  add more to cover special cases like moving-aggregate etc.
             ) AS aggregate
    , 'COMMENT ON AGGREGATE ' || aggfnoid::regprocedure
      || ' IS ' || quote_literal(obj_description(aggfnoid, 'pg_proc')) AS comment
FROM   pg_aggregate a
JOIN   pg_proc      p ON p.oid = a.aggfnoid
JOIN   pg_namespace n ON n.oid = p.pronamespace
WHERE  n.nspname !~ '^(pg_|information_schema)'    -- exclude system schemas
-- AND    n.nspname = 'public'                     -- or from selected schema only?
AND    NOT EXISTS (
  SELECT FROM pg_depend 
  WHERE  objid = a.aggfnoid
  AND    deptype = 'e'
  )
ORDER  BY n.nspname, p.proname;

這僅涵蓋普通的聚合函式。進一步閱讀:

為了使其完整,您可能需要添加所有權 ( ALTER FUNCTION ... OWNER TO ...;) 和特權 ( GRANT/ REVOKE)。

我今天遇到了同樣的問題,經過一些解決方法後,我從查詢中排除了這個“postgis”函式並得到了結果(where proname <> 'st_extent')。希望有所幫助

引用自:https://dba.stackexchange.com/questions/141174