@@ -67,10 +67,14 @@ static Datum aggGetAttr(TupleTableSlot *tuple, Aggref *aggref, bool *isNull);
6767 * value1[i] = initcond1
6868 * value2[i] = initcond2
6969 * forall tuples do
70- *value1[i] = sfunc1(aggregate_attribute, value1[i])
70+ *value1[i] = sfunc1(value1[i], aggregated_value )
7171 *value2[i] = sfunc2(value2[i])
7272 * value1[i] = finalfunc(value1[i], value2[i])
7373 *
74+ * If initcond1 is NULL then the first non-NULL aggregated_value is
75+ * assigned directly to value1[i]. sfunc1 isn't applied until value1[i]
76+ * is non-NULL.
77+ *
7478 * If the outer subplan is a Group node, ExecAgg returns as many tuples
7579 * as there are groups.
7680 *
@@ -272,7 +276,6 @@ ExecAgg(Agg *node)
272276{
273277Aggref * aggref = lfirst (alist );
274278AttrNumber attnum ;
275- int2 attlen = 0 ;
276279Datum newVal = (Datum )NULL ;
277280AggFuncInfo * aggfns = & aggFuncInfo [++ aggno ];
278281Datum args [2 ];
@@ -309,6 +312,7 @@ ExecAgg(Agg *node)
309312{
310313if (noInitValue [aggno ])
311314{
315+ int attlen = 0 ;
312316int byVal = 0 ;
313317
314318/*
@@ -352,16 +356,16 @@ ExecAgg(Agg *node)
352356default :
353357elog (ERROR ,"ExecAgg: Bad Agg->Target for Agg %d" ,aggno );
354358}
355- if (attlen == -1 )
356- {
357- /* variable length */
358- attlen = VARSIZE ((struct varlena * )newVal );
359- }
360- value1 [aggno ]= (Datum )palloc (attlen );
361359if (byVal )
362360value1 [aggno ]= newVal ;
363361else
364- memmove ((char * ) (value1 [aggno ]), (char * )newVal ,attlen );
362+ {
363+ if (attlen == -1 )/* variable length */
364+ attlen = VARSIZE ((struct varlena * )newVal );
365+ value1 [aggno ]= (Datum )palloc (attlen );
366+ memcpy ((char * ) (value1 [aggno ]), (char * )newVal ,
367+ attlen );
368+ }
365369noInitValue [aggno ]= 0 ;
366370nulls [aggno ]= 0 ;
367371}
@@ -380,10 +384,9 @@ ExecAgg(Agg *node)
380384
381385if (aggfns -> xfn2 .fn_addr != NULL )
382386{
383- Datum xfn2_val = value2 [aggno ];
384-
387+ args [0 ]= value2 [aggno ];
385388value2 [aggno ]= (Datum )fmgr_c (& aggfns -> xfn2 ,
386- (FmgrValues * )& xfn2_val ,& isNull2 );
389+ (FmgrValues * )args ,& isNull2 );
387390Assert (!isNull2 );
388391}
389392}