gopgext/agg

import "gopgext/agg"

Package agg writes aggregates whose state is a Go value (transition type internal): a slice of values for a median, a map for a mode, a sketch… The state is an *agg.State, and the aggregate’s functions are ordinary //gopgext:function functions taking and returning one (SQL type internal):

// MedianAdd is the transition function of median(float8).
//
//gopgext:function parallel=safe
func MedianAdd(s *agg.State, x *float64) *agg.State {
	if s == nil {
		s = agg.New(&values{}) // first row of a group
	}
	if x != nil {
		v := s.Value.(*values)
		*v = append(*v, *x)
	}
	return s
}

//gopgext:function parallel=safe
func MedianFinal(s *agg.State) *float64 { ... } // nil s: no rows

declared in sql/:

CREATE AGGREGATE median(float8) (
	SFUNC = median_add, STYPE = internal, FINALFUNC = median_final,
	-- parallel aggregation (optional): states are merged and travel
	-- between processes as bytea
	COMBINEFUNC = median_combine, SERIALFUNC = median_serialize,
	DESERIALFUNC = median_deserialize, PARALLEL = SAFE);

Functions with an *agg.State parameter aren’t STRICT (the state starts as NULL, a nil *agg.State): use pointer parameters for the aggregated values to see NULLs as nil (non-pointer ones raise an error on NULL). The serialization function takes an *agg.State and returns []byte; the deserialization function takes ([]byte, pg.Internal) and returns a new state.

A state lives as long as the aggregate’s memory context (a group, or the query): PostgreSQL frees it, and agg drops the Go value, when that context is reset, also after errors. Don’t keep states elsewhere.

Index#

Functions#

func Live#

func Live() int

Live returns the number of states alive in this backend (to check that none leak).

func Return#

func Return(c *fmgr.Call, s *State)

Return sets a state result, NULL for nil (generated code). A new state gets a handle in the calling aggregate’s memory context.

Types#

type State#

type State struct {
	Value any

	// in states; 0 until returned to PostgreSQL
	// the handle (struct agg_handle in agg.c)

}

State is the state of an aggregate: Value is any Go value.

func Arg#

func Arg(c *fmgr.Call, i int) *State

Arg returns state argument i, nil for NULL (generated code).

func New#

func New(v any) *State

New returns a new state holding v.