How to get the definition / source code of an aggregate in PostgreSQL?

I found this answer helpful:

But how do I get a statement CREATE AGGREGATEwithout a GUI client (for example, with the psql command line)?

+4
source share
3 answers

Something like this, but I'm not sure if this covers all possible ways of creating an aggregate (it definitely does not require accounting for quoted identifiers)

SELECT 'create aggregate '||n.nspname||'.'||p.proname||'('||format_type(a.aggtranstype, null)||') (sfunc = '||a.aggtransfn
       ||', stype = '||format_type(a.aggtranstype, null)
       ||case when op.oprname is null then '' else ', sortop = '||op.oprname end 
       ||case when a.agginitval is null then '' else ', initcond = '||a.agginitval end
       ||')' as source
FROM pg_proc p 
  JOIN pg_namespace n ON p.pronamespace = n.oid 
  JOIN pg_aggregate a ON a.aggfnoid = p.oid 
  LEFT JOIN pg_operator op ON op.oid = a.aggsortop 
where p.proname = 'your_aggregate'
  and n.nspname = 'public' --- replace with your schema name  
+3
source

CREATE AGGREGATE - format() , , :

SELECT format('CREATE AGGREGATE %s (SFUNC = %s, STYPE = %s%s%s%s%s)'
            , aggfnoid::regprocedure
            , aggtransfn
            , aggtranstype::regtype
            , ', SORTOP = '    || NULLIF(aggsortop, 0)::regoper
            , ', INITCOND = '  || agginitval
            , ', FINALFUNC = ' || NULLIF(aggfinalfn, 0)
            , CASE WHEN aggfinalextra THEN ', FINALFUNC_EXTRA' END
            --  add more to cover special cases like moving-aggregate etc.
              ) AS ddl_agg
FROM   pg_aggregate
WHERE  aggfnoid = 'my_agg_func'::regproc;  -- name of agg func here

, : 'public.my_agg_func'::regproc.
/ : 'array_agg(anyarray)'::regprocedure.

, .. , Postgres. .

pg_get_aggregatedef(), pg_get_functiondef(), , Postgres...

+1

My version using some system functions

SELECT 
format(
   E'CREATE AGGREGATE %s (\n%s\n);'
   , (pg_identify_object('pg_proc'::regclass, aggfnoid, 0)).identity
   , array_to_string(
      ARRAY[
     format(E'\tSFUNC = %s', aggtransfn::regproc)
     , format(E'\tSTYPE = %s', format_type(aggtranstype, NULL))
     , CASE aggfinalfn WHEN '-'::regproc THEN NULL ELSE format(E'\tFINALFUNC = %s',aggfinalfn::text) END
     , CASE aggsortop WHEN 0 THEN NULL ELSE format(E'\tSORTOP = %s', oprname) END
     , CASE WHEN agginitval IS NULL THEN NULL ELSE format(E'\tINITCOND = %s', agginitval) END
      ]
      , E',\n'
   )
)

FROM pg_aggregate
LEFT JOIN pg_operator ON pg_operator.oid = aggsortop
WHERE aggfnoid = 'regr_r2'::regproc;
0
source

Source: https://habr.com/ru/post/1570844/


All Articles