summaryrefslogtreecommitdiff
path: root/contrib/intagg/int_aggregate.c
blob: f4391b46996cc3784b900d69b9aa4d667cdbcb68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
 * Integer array aggregator / enumerator
 *
 * Mark L. Woodward
 * DMN Digital Music Network.
 * www.dmn.com
 *
 * Copyright (C) Digital Music Network
 * December 20, 2001
 *
 * This file is the property of the Digital Music Network (DMN).
 * It is being made available to users of the PostgreSQL system
 * under the BSD license.
 */
#include "postgres.h"

#include <ctype.h>
#include <sys/types.h>

#include "access/heapam.h"
#include "catalog/indexing.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "utils/syscache.h"
#include "access/tupmacs.h"
#include "access/xact.h"
#include "fmgr.h"
#include "miscadmin.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/lsyscache.h"


/*
 * This is actually a postgres version of a one dimensional array.
 * We cheat a little by using the lower-bound field as an indicator
 * of the physically allocated size, while the dimensionality is the
 * count of items accumulated so far.
 */
typedef struct
{
	ArrayType	a;
	int			items;
	int			lower;
	int4		array[1];
}	PGARRAY;

/* This is used to keep track of our position during enumeration */
typedef struct callContext
{
	PGARRAY    *p;
	int			num;
	int			flags;
}	CTX;

#define TOASTED		1
#define START_NUM	8			/* initial size of arrays */
#define PGARRAY_SIZE(n) (sizeof(PGARRAY) + (((n)-1)*sizeof(int4)))

static PGARRAY *GetPGArray(PGARRAY *p, AggState *aggstate, bool fAdd);
static PGARRAY *ShrinkPGArray(PGARRAY *p);

Datum		int_agg_state(PG_FUNCTION_ARGS);
Datum		int_agg_final_array(PG_FUNCTION_ARGS);
Datum		int_enum(PG_FUNCTION_ARGS);

PG_FUNCTION_INFO_V1(int_agg_state);
PG_FUNCTION_INFO_V1(int_agg_final_array);
PG_FUNCTION_INFO_V1(int_enum);

/*
 * Manage the allocation state of the array
 *
 * Note that the array needs to be in a reasonably long-lived context,
 * ie the Agg node's aggcontext.
 */
static PGARRAY *
GetPGArray(PGARRAY *p, AggState *aggstate, bool fAdd)
{
	if (!p)
	{
		/* New array */
		int			cb = PGARRAY_SIZE(START_NUM);

		p = (PGARRAY *) MemoryContextAlloc(aggstate->aggcontext, cb);
		p->a.size = cb;
		p->a.ndim = 1;
		p->a.flags = 0;
		p->a.elemtype = INT4OID;
		p->items = 0;
		p->lower = START_NUM;
	}
	else if (fAdd)
	{
		/* Ensure array has space for another item */
		if (p->items >= p->lower)
		{
			PGARRAY	   *pn;
			int			n = p->lower * 2;
			int			cbNew = PGARRAY_SIZE(n);

			pn = (PGARRAY *) MemoryContextAlloc(aggstate->aggcontext, cbNew);
			memcpy(pn, p, p->a.size);
			pn->a.size = cbNew;
			pn->lower = n;
			/* do not pfree(p), because nodeAgg.c will */
			p = pn;
		}
	}
	return p;
}

/*
 * Shrinks the array to its actual size and moves it into the standard
 * memory allocation context
 */
static PGARRAY *
ShrinkPGArray(PGARRAY *p)
{
	PGARRAY    *pnew;
	/* get target size */
	int			cb = PGARRAY_SIZE(p->items);

	/* use current transaction context */
	pnew = palloc(cb);
	memcpy(pnew, p, cb);

	/* fix up the fields in the new array to match normal conventions */
	pnew->a.size = cb;
	pnew->lower = 1;

	/* do not pfree(p), because nodeAgg.c will */

	return pnew;
}

/* Called for each iteration during an aggregate function */
Datum
int_agg_state(PG_FUNCTION_ARGS)
{
	PGARRAY    *state;
	PGARRAY    *p;

	/*
	 * As of PG 8.1 we can actually verify that we are being used as an
	 * aggregate function, and so it is safe to scribble on our left input.
	 */
	if (!(fcinfo->context && IsA(fcinfo->context, AggState)))
		elog(ERROR, "int_agg_state may only be used as an aggregate");

	if (PG_ARGISNULL(0))
		state = NULL;			/* first time through */
	else
		state = (PGARRAY *) PG_GETARG_POINTER(0);
	p = GetPGArray(state, (AggState *) fcinfo->context, true);

	if (!PG_ARGISNULL(1))
	{
		int4	value = PG_GETARG_INT32(1);

		if (!p)		/* internal error */
			elog(ERROR, "no aggregate storage");
		else if (p->items >= p->lower)		/* internal error */
			elog(ERROR, "aggregate storage too small");
		else
			p->array[p->items++] = value;
	}
	PG_RETURN_POINTER(p);
}

/*
 * This is the final function used for the integer aggregator. It returns all
 * the integers collected as a one dimensional integer array
 */
Datum
int_agg_final_array(PG_FUNCTION_ARGS)
{
	PGARRAY    *state;
	PGARRAY    *p;
	PGARRAY    *pnew;

	/*
	 * As of PG 8.1 we can actually verify that we are being used as an
	 * aggregate function, and so it is safe to scribble on our left input.
	 */
	if (!(fcinfo->context && IsA(fcinfo->context, AggState)))
		elog(ERROR, "int_agg_final_array may only be used as an aggregate");

	if (PG_ARGISNULL(0))
		state = NULL;			/* zero items in aggregation */
	else
		state = (PGARRAY *) PG_GETARG_POINTER(0);
	p = GetPGArray(state, (AggState *) fcinfo->context, false);

	pnew = ShrinkPGArray(p);
	PG_RETURN_POINTER(pnew);
}

/*
 * This function accepts an array, and returns one item for each entry in the
 * array
 */
Datum
int_enum(PG_FUNCTION_ARGS)
{
	PGARRAY    *p = (PGARRAY *) PG_GETARG_POINTER(0);
	CTX		   *pc;
	ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;

	if (!rsi || !IsA(rsi, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
		 errmsg("int_enum called in context that cannot accept a set")));

	if (!p)
	{
		elog(WARNING, "no data sent");
		PG_RETURN_NULL();
	}

	if (!fcinfo->flinfo->fn_extra)
	{
		/* Allocate working state */
		MemoryContext	oldcontext;

		oldcontext = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);

		pc = (CTX *) palloc(sizeof(CTX));

		/* Don't copy attribute if you don't need to */
		if (VARATT_IS_EXTENDED(p))
		{
			/* Toasted!!! */
			pc->p = (PGARRAY *) PG_DETOAST_DATUM_COPY(p);
			pc->flags = TOASTED;
		}
		else
		{
			/* Untoasted */
			pc->p = p;
			pc->flags = 0;
		}
		/* Now that we have a detoasted array, verify dimensions */
		/* We'll treat a zero-D array as empty, below */
		if (pc->p->a.ndim > 1)
			elog(ERROR, "int_enum only accepts 1-D arrays");
		pc->num = 0;
		fcinfo->flinfo->fn_extra = (void *) pc;
		MemoryContextSwitchTo(oldcontext);
	}
	else	/* use existing working state */
		pc = (CTX *) fcinfo->flinfo->fn_extra;

	/* Are we done yet? */
	if (pc->p->a.ndim < 1 || pc->num >= pc->p->items)
	{
		/* We are done */
		if (pc->flags & TOASTED)
			pfree(pc->p);
		pfree(pc);
		fcinfo->flinfo->fn_extra = NULL;
		rsi->isDone = ExprEndResult;
	}
	else
	{
		/* nope, return the next value */
		int			val = pc->p->array[pc->num++];

		rsi->isDone = ExprMultipleResult;
		PG_RETURN_INT32(val);
	}
	PG_RETURN_NULL();
}