Home Explore Blog CI



postgresql

9th chunk of `doc/src/sgml/xaggr.sgml`
d0ec3854da5bc61af9f495d14f53df46e327577ae8bb1445000000010000096c
 underlying input
   type, as its second argument.  In particular, the rules for dealing
   with null values and strict functions are similar.  Also, if the aggregate
   definition specifies a non-null <literal>initcond</literal>, keep in mind that
   that will be used not only as the initial state for each partial
   aggregation run, but also as the initial state for the combine function,
   which will be called to combine each partial result into that state.
  </para>

  <para>
   If the aggregate's state type is declared as <type>internal</type>, it is
   the combine function's responsibility that its result is allocated in
   the correct memory context for aggregate state values.  This means in
   particular that when the first input is <literal>NULL</literal> it's invalid
   to simply return the second input, as that value will be in the wrong
   context and will not have sufficient lifespan.
  </para>

  <para>
   When the aggregate's state type is declared as <type>internal</type>, it is
   usually also appropriate for the aggregate definition to provide a
   <firstterm>serialization function</firstterm> and a <firstterm>deserialization
   function</firstterm>, which allow such a state value to be copied from one process
   to another.  Without these functions, parallel aggregation cannot be
   performed, and future applications such as local/remote aggregation will
   probably not work either.
  </para>

  <para>
   A serialization function must take a single argument of
   type <type>internal</type> and return a result of type <type>bytea</type>, which
   represents the state value packaged up into a flat blob of bytes.
   Conversely, a deserialization function reverses that conversion.  It must
   take two arguments of types <type>bytea</type> and <type>internal</type>, and
   return a result of type <type>internal</type>.  (The second argument is unused
   and is always zero, but it is required for type-safety reasons.)  The
   result of the deserialization function should simply be allocated in the
   current memory context, as unlike the combine function's result, it is not
   long-lived.
  </para>

  <para>
   Worth noting also is that for an aggregate to be executed in parallel,
   the aggregate itself must be marked <literal>PARALLEL SAFE</literal>.  The
   parallel-safety markings on its support functions are not consulted.
  </para>

 </sect2>

 <sect2

Title: Implementing Partial Aggregation with Internal State
Summary
When an aggregate's state type is declared as internal, the combine function must allocate its result in the correct memory context, and serialization and deserialization functions are typically required to enable parallel aggregation and other future applications, with the aggregate itself also needing to be marked as parallel safe