Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * array_userfuncs.c
4 : : * Misc user-visible array support functions
5 : : *
6 : : * Copyright (c) 2003-2026, PostgreSQL Global Development Group
7 : : *
8 : : * IDENTIFICATION
9 : : * src/backend/utils/adt/array_userfuncs.c
10 : : *
11 : : *-------------------------------------------------------------------------
12 : : */
13 : : #include "postgres.h"
14 : :
15 : : #include "catalog/pg_operator_d.h"
16 : : #include "catalog/pg_type.h"
17 : : #include "common/int.h"
18 : : #include "common/pg_prng.h"
19 : : #include "libpq/pqformat.h"
20 : : #include "miscadmin.h"
21 : : #include "nodes/supportnodes.h"
22 : : #include "port/pg_bitutils.h"
23 : : #include "utils/array.h"
24 : : #include "utils/builtins.h"
25 : : #include "utils/datum.h"
26 : : #include "utils/lsyscache.h"
27 : : #include "utils/memutils.h"
28 : : #include "utils/tuplesort.h"
29 : : #include "utils/typcache.h"
30 : :
31 : : /*
32 : : * SerialIOData
33 : : * Used for caching element-type data in array_agg_serialize
34 : : */
35 : : typedef struct SerialIOData
36 : : {
37 : : FmgrInfo typsend;
38 : : } SerialIOData;
39 : :
40 : : /*
41 : : * DeserialIOData
42 : : * Used for caching element-type data in array_agg_deserialize
43 : : */
44 : : typedef struct DeserialIOData
45 : : {
46 : : FmgrInfo typreceive;
47 : : Oid typioparam;
48 : : } DeserialIOData;
49 : :
50 : : /*
51 : : * ArraySortCachedInfo
52 : : * Used for caching catalog data in array_sort
53 : : */
54 : : typedef struct ArraySortCachedInfo
55 : : {
56 : : ArrayMetaState array_meta; /* metadata for array_create_iterator */
57 : : Oid elem_lt_opr; /* "<" operator for element type */
58 : : Oid elem_gt_opr; /* ">" operator for element type */
59 : : Oid array_type; /* pg_type OID of array type */
60 : : } ArraySortCachedInfo;
61 : :
62 : : static Datum array_position_common(FunctionCallInfo fcinfo);
63 : :
64 : :
65 : : /*
66 : : * fetch_array_arg_replace_nulls
67 : : *
68 : : * Fetch an array-valued argument in expanded form; if it's null, construct an
69 : : * empty array value of the proper data type. Also cache basic element type
70 : : * information in fn_extra.
71 : : *
72 : : * Caution: if the input is a read/write pointer, this returns the input
73 : : * argument; so callers must be sure that their changes are "safe", that is
74 : : * they cannot leave the array in a corrupt state.
75 : : *
76 : : * If we're being called as an aggregate function, make sure any newly-made
77 : : * expanded array is allocated in the aggregate state context, so as to save
78 : : * copying operations.
79 : : */
80 : : static ExpandedArrayHeader *
81 : 1316 : fetch_array_arg_replace_nulls(FunctionCallInfo fcinfo, int argno)
82 : : {
83 : : ExpandedArrayHeader *eah;
84 : : Oid element_type;
85 : : ArrayMetaState *my_extra;
86 : : MemoryContext resultcxt;
87 : :
88 : : /* If first time through, create datatype cache struct */
89 : 1316 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
90 [ + + ]: 1316 : if (my_extra == NULL)
91 : : {
92 : : my_extra = (ArrayMetaState *)
93 : 833 : MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
94 : : sizeof(ArrayMetaState));
95 : 833 : my_extra->element_type = InvalidOid;
96 : 833 : fcinfo->flinfo->fn_extra = my_extra;
97 : : }
98 : :
99 : : /* Figure out which context we want the result in */
100 [ + + ]: 1316 : if (!AggCheckCallContext(fcinfo, &resultcxt))
101 : 1236 : resultcxt = CurrentMemoryContext;
102 : :
103 : : /* Now collect the array value */
104 [ + + ]: 1316 : if (!PG_ARGISNULL(argno))
105 : : {
106 : 1299 : MemoryContext oldcxt = MemoryContextSwitchTo(resultcxt);
107 : :
108 : 1299 : eah = PG_GETARG_EXPANDED_ARRAYX(argno, my_extra);
109 : 1299 : MemoryContextSwitchTo(oldcxt);
110 : : }
111 : : else
112 : : {
113 : : /* We have to look up the array type and element type */
114 : 17 : Oid arr_typeid = get_fn_expr_argtype(fcinfo->flinfo, argno);
115 : :
116 [ - + ]: 17 : if (!OidIsValid(arr_typeid))
117 [ # # ]: 0 : ereport(ERROR,
118 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
119 : : errmsg("could not determine input data type")));
120 : 17 : element_type = get_element_type(arr_typeid);
121 [ - + ]: 17 : if (!OidIsValid(element_type))
122 [ # # ]: 0 : ereport(ERROR,
123 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
124 : : errmsg("input data type is not an array")));
125 : :
126 : 17 : eah = construct_empty_expanded_array(element_type,
127 : : resultcxt,
128 : : my_extra);
129 : : }
130 : :
131 : 1316 : return eah;
132 : : }
133 : :
134 : : /*-----------------------------------------------------------------------------
135 : : * array_append :
136 : : * push an element onto the end of a one-dimensional array
137 : : *----------------------------------------------------------------------------
138 : : */
139 : : Datum
140 : 1253 : array_append(PG_FUNCTION_ARGS)
141 : : {
142 : : ExpandedArrayHeader *eah;
143 : : Datum newelem;
144 : : bool isNull;
145 : : Datum result;
146 : : int *dimv,
147 : : *lb;
148 : : int indx;
149 : : ArrayMetaState *my_extra;
150 : :
151 : 1253 : eah = fetch_array_arg_replace_nulls(fcinfo, 0);
152 : 1253 : isNull = PG_ARGISNULL(1);
153 [ - + ]: 1253 : if (isNull)
154 : 0 : newelem = (Datum) 0;
155 : : else
156 : 1253 : newelem = PG_GETARG_DATUM(1);
157 : :
158 [ + + ]: 1253 : if (eah->ndims == 1)
159 : : {
160 : : /* append newelem */
161 : 982 : lb = eah->lbound;
162 : 982 : dimv = eah->dims;
163 : :
164 : : /* index of added elem is at lb[0] + (dimv[0] - 1) + 1 */
165 [ - + ]: 982 : if (pg_add_s32_overflow(lb[0], dimv[0], &indx))
166 [ # # ]: 0 : ereport(ERROR,
167 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
168 : : errmsg("integer out of range")));
169 : : }
170 [ + - ]: 271 : else if (eah->ndims == 0)
171 : 271 : indx = 1;
172 : : else
173 [ # # ]: 0 : ereport(ERROR,
174 : : (errcode(ERRCODE_DATA_EXCEPTION),
175 : : errmsg("argument must be empty or one-dimensional array")));
176 : :
177 : : /* Perform element insertion */
178 : 1253 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
179 : :
180 : 1253 : result = array_set_element(EOHPGetRWDatum(&eah->hdr),
181 : : 1, &indx, newelem, isNull,
182 : 1253 : -1, my_extra->typlen, my_extra->typbyval, my_extra->typalign);
183 : :
184 : 1253 : PG_RETURN_DATUM(result);
185 : : }
186 : :
187 : : /*
188 : : * array_append_support()
189 : : *
190 : : * Planner support function for array_append()
191 : : */
192 : : Datum
193 : 226 : array_append_support(PG_FUNCTION_ARGS)
194 : : {
195 : 226 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
196 : 226 : Node *ret = NULL;
197 : :
198 [ + + ]: 226 : if (IsA(rawreq, SupportRequestModifyInPlace))
199 : : {
200 : : /*
201 : : * We can optimize in-place appends if the function's array argument
202 : : * is the array being assigned to. We don't need to worry about array
203 : : * references within the other argument.
204 : : */
205 : 1 : SupportRequestModifyInPlace *req = (SupportRequestModifyInPlace *) rawreq;
206 : 1 : Param *arg = (Param *) linitial(req->args);
207 : :
208 [ + - + - ]: 1 : if (arg && IsA(arg, Param) &&
209 [ + - ]: 1 : arg->paramkind == PARAM_EXTERN &&
210 [ + - ]: 1 : arg->paramid == req->paramid)
211 : 1 : ret = (Node *) arg;
212 : : }
213 : :
214 : 226 : PG_RETURN_POINTER(ret);
215 : : }
216 : :
217 : : /*-----------------------------------------------------------------------------
218 : : * array_prepend :
219 : : * push an element onto the front of a one-dimensional array
220 : : *----------------------------------------------------------------------------
221 : : */
222 : : Datum
223 : 63 : array_prepend(PG_FUNCTION_ARGS)
224 : : {
225 : : ExpandedArrayHeader *eah;
226 : : Datum newelem;
227 : : bool isNull;
228 : : Datum result;
229 : : int *lb;
230 : : int indx;
231 : : int lb0;
232 : : ArrayMetaState *my_extra;
233 : :
234 : 63 : isNull = PG_ARGISNULL(0);
235 [ - + ]: 63 : if (isNull)
236 : 0 : newelem = (Datum) 0;
237 : : else
238 : 63 : newelem = PG_GETARG_DATUM(0);
239 : 63 : eah = fetch_array_arg_replace_nulls(fcinfo, 1);
240 : :
241 [ + - ]: 63 : if (eah->ndims == 1)
242 : : {
243 : : /* prepend newelem */
244 : 63 : lb = eah->lbound;
245 : 63 : lb0 = lb[0];
246 : :
247 [ - + ]: 63 : if (pg_sub_s32_overflow(lb0, 1, &indx))
248 [ # # ]: 0 : ereport(ERROR,
249 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
250 : : errmsg("integer out of range")));
251 : : }
252 [ # # ]: 0 : else if (eah->ndims == 0)
253 : : {
254 : 0 : indx = 1;
255 : 0 : lb0 = 1;
256 : : }
257 : : else
258 [ # # ]: 0 : ereport(ERROR,
259 : : (errcode(ERRCODE_DATA_EXCEPTION),
260 : : errmsg("argument must be empty or one-dimensional array")));
261 : :
262 : : /* Perform element insertion */
263 : 63 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
264 : :
265 : 63 : result = array_set_element(EOHPGetRWDatum(&eah->hdr),
266 : : 1, &indx, newelem, isNull,
267 : 63 : -1, my_extra->typlen, my_extra->typbyval, my_extra->typalign);
268 : :
269 : : /* Readjust result's LB to match the input's, as expected for prepend */
270 : : Assert(result == EOHPGetRWDatum(&eah->hdr));
271 [ + - ]: 63 : if (eah->ndims == 1)
272 : : {
273 : : /* This is ok whether we've deconstructed or not */
274 : 63 : eah->lbound[0] = lb0;
275 : : }
276 : :
277 : 63 : PG_RETURN_DATUM(result);
278 : : }
279 : :
280 : : /*
281 : : * array_prepend_support()
282 : : *
283 : : * Planner support function for array_prepend()
284 : : */
285 : : Datum
286 : 43 : array_prepend_support(PG_FUNCTION_ARGS)
287 : : {
288 : 43 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
289 : 43 : Node *ret = NULL;
290 : :
291 [ + + ]: 43 : if (IsA(rawreq, SupportRequestModifyInPlace))
292 : : {
293 : : /*
294 : : * We can optimize in-place prepends if the function's array argument
295 : : * is the array being assigned to. We don't need to worry about array
296 : : * references within the other argument.
297 : : */
298 : 1 : SupportRequestModifyInPlace *req = (SupportRequestModifyInPlace *) rawreq;
299 : 1 : Param *arg = (Param *) lsecond(req->args);
300 : :
301 [ + - + - ]: 1 : if (arg && IsA(arg, Param) &&
302 [ + - ]: 1 : arg->paramkind == PARAM_EXTERN &&
303 [ + - ]: 1 : arg->paramid == req->paramid)
304 : 1 : ret = (Node *) arg;
305 : : }
306 : :
307 : 43 : PG_RETURN_POINTER(ret);
308 : : }
309 : :
310 : : /*-----------------------------------------------------------------------------
311 : : * array_cat :
312 : : * concatenate two nD arrays to form an nD array, or
313 : : * push an (n-1)D array onto the end of an nD array
314 : : *----------------------------------------------------------------------------
315 : : */
316 : : Datum
317 : 15548 : array_cat(PG_FUNCTION_ARGS)
318 : : {
319 : : ArrayType *v1,
320 : : *v2;
321 : : ArrayType *result;
322 : : int *dims,
323 : : *lbs,
324 : : ndims,
325 : : nitems,
326 : : ndatabytes,
327 : : nbytes;
328 : : int *dims1,
329 : : *lbs1,
330 : : ndims1,
331 : : nitems1,
332 : : ndatabytes1;
333 : : int *dims2,
334 : : *lbs2,
335 : : ndims2,
336 : : nitems2,
337 : : ndatabytes2;
338 : : bool ovfl;
339 : : int i;
340 : : char *dat1,
341 : : *dat2;
342 : : uint8 *bitmap1,
343 : : *bitmap2;
344 : : Oid element_type;
345 : : Oid element_type1;
346 : : Oid element_type2;
347 : : int32 dataoffset;
348 : :
349 : : /* Concatenating a null array is a no-op, just return the other input */
350 [ + + ]: 15548 : if (PG_ARGISNULL(0))
351 : : {
352 [ - + ]: 1151 : if (PG_ARGISNULL(1))
353 : 0 : PG_RETURN_NULL();
354 : 1151 : result = PG_GETARG_ARRAYTYPE_P(1);
355 : 1151 : PG_RETURN_ARRAYTYPE_P(result);
356 : : }
357 [ - + ]: 14397 : if (PG_ARGISNULL(1))
358 : : {
359 : 0 : result = PG_GETARG_ARRAYTYPE_P(0);
360 : 0 : PG_RETURN_ARRAYTYPE_P(result);
361 : : }
362 : :
363 : 14397 : v1 = PG_GETARG_ARRAYTYPE_P(0);
364 : 14397 : v2 = PG_GETARG_ARRAYTYPE_P(1);
365 : :
366 : 14397 : element_type1 = ARR_ELEMTYPE(v1);
367 : 14397 : element_type2 = ARR_ELEMTYPE(v2);
368 : :
369 : : /* Check we have matching element types */
370 [ - + ]: 14397 : if (element_type1 != element_type2)
371 [ # # ]: 0 : ereport(ERROR,
372 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
373 : : errmsg("cannot concatenate incompatible arrays"),
374 : : errdetail("Arrays with element types %s and %s are not "
375 : : "compatible for concatenation.",
376 : : format_type_be(element_type1),
377 : : format_type_be(element_type2))));
378 : :
379 : : /* OK, use it */
380 : 14397 : element_type = element_type1;
381 : :
382 : : /*----------
383 : : * We must have one of the following combinations of inputs:
384 : : * 1) one empty array, and one non-empty array
385 : : * 2) both arrays empty
386 : : * 3) two arrays with ndims1 == ndims2
387 : : * 4) ndims1 == ndims2 - 1
388 : : * 5) ndims1 == ndims2 + 1
389 : : *----------
390 : : */
391 : 14397 : ndims1 = ARR_NDIM(v1);
392 : 14397 : ndims2 = ARR_NDIM(v2);
393 : :
394 : : /*
395 : : * short circuit - if one input array is empty, and the other is not, we
396 : : * return the non-empty one as the result
397 : : *
398 : : * if both are empty, return the first one
399 : : */
400 [ + + - + ]: 14397 : if (ndims1 == 0 && ndims2 > 0)
401 : 0 : PG_RETURN_ARRAYTYPE_P(v2);
402 : :
403 [ + + ]: 14397 : if (ndims2 == 0)
404 : 33 : PG_RETURN_ARRAYTYPE_P(v1);
405 : :
406 : : /* the rest fall under rule 3, 4, or 5 */
407 [ + + ]: 14364 : if (ndims1 != ndims2 &&
408 [ + + ]: 15 : ndims1 != ndims2 - 1 &&
409 [ - + ]: 10 : ndims1 != ndims2 + 1)
410 [ # # ]: 0 : ereport(ERROR,
411 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
412 : : errmsg("cannot concatenate incompatible arrays"),
413 : : errdetail("Arrays of %d and %d dimensions are not "
414 : : "compatible for concatenation.",
415 : : ndims1, ndims2)));
416 : :
417 : : /* get argument array details */
418 : 14364 : lbs1 = ARR_LBOUND(v1);
419 : 14364 : lbs2 = ARR_LBOUND(v2);
420 : 14364 : dims1 = ARR_DIMS(v1);
421 : 14364 : dims2 = ARR_DIMS(v2);
422 [ - + ]: 14364 : dat1 = ARR_DATA_PTR(v1);
423 [ - + ]: 14364 : dat2 = ARR_DATA_PTR(v2);
424 [ - + ]: 14364 : bitmap1 = ARR_NULLBITMAP(v1);
425 [ - + ]: 14364 : bitmap2 = ARR_NULLBITMAP(v2);
426 : 14364 : nitems1 = ArrayGetNItems(ndims1, dims1);
427 : 14364 : nitems2 = ArrayGetNItems(ndims2, dims2);
428 [ - + ]: 14364 : ndatabytes1 = ARR_SIZE(v1) - ARR_DATA_OFFSET(v1);
429 [ - + ]: 14364 : ndatabytes2 = ARR_SIZE(v2) - ARR_DATA_OFFSET(v2);
430 : :
431 [ + + ]: 14364 : if (ndims1 == ndims2)
432 : : {
433 : : /*
434 : : * resulting array is made up of the elements (possibly arrays
435 : : * themselves) of the input argument arrays
436 : : */
437 : 14349 : ndims = ndims1;
438 : 14349 : dims = palloc_array(int, ndims);
439 : 14349 : lbs = palloc_array(int, ndims);
440 : :
441 : 14349 : dims[0] = dims1[0] + dims2[0];
442 : 14349 : lbs[0] = lbs1[0];
443 : :
444 [ + + ]: 14359 : for (i = 1; i < ndims; i++)
445 : : {
446 [ + - - + ]: 10 : if (dims1[i] != dims2[i] || lbs1[i] != lbs2[i])
447 [ # # ]: 0 : ereport(ERROR,
448 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
449 : : errmsg("cannot concatenate incompatible arrays"),
450 : : errdetail("Arrays with differing element dimensions are "
451 : : "not compatible for concatenation.")));
452 : :
453 : 10 : dims[i] = dims1[i];
454 : 10 : lbs[i] = lbs1[i];
455 : : }
456 : : }
457 [ + + ]: 15 : else if (ndims1 == ndims2 - 1)
458 : : {
459 : : /*
460 : : * resulting array has the second argument as the outer array, with
461 : : * the first argument inserted at the front of the outer dimension
462 : : */
463 : 5 : ndims = ndims2;
464 : 5 : dims = palloc_array(int, ndims);
465 : 5 : lbs = palloc_array(int, ndims);
466 : 5 : memcpy(dims, dims2, ndims * sizeof(int));
467 : 5 : memcpy(lbs, lbs2, ndims * sizeof(int));
468 : :
469 : : /* increment number of elements in outer array */
470 : 5 : dims[0] += 1;
471 : :
472 : : /* make sure the added element matches our existing elements */
473 [ + + ]: 10 : for (i = 0; i < ndims1; i++)
474 : : {
475 [ + - - + ]: 5 : if (dims1[i] != dims[i + 1] || lbs1[i] != lbs[i + 1])
476 [ # # ]: 0 : ereport(ERROR,
477 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
478 : : errmsg("cannot concatenate incompatible arrays"),
479 : : errdetail("Arrays with differing dimensions are not "
480 : : "compatible for concatenation.")));
481 : : }
482 : : }
483 : : else
484 : : {
485 : : /*
486 : : * (ndims1 == ndims2 + 1)
487 : : *
488 : : * resulting array has the first argument as the outer array, with the
489 : : * second argument appended to the end of the outer dimension
490 : : */
491 : 10 : ndims = ndims1;
492 : 10 : dims = palloc_array(int, ndims);
493 : 10 : lbs = palloc_array(int, ndims);
494 : 10 : memcpy(dims, dims1, ndims * sizeof(int));
495 : 10 : memcpy(lbs, lbs1, ndims * sizeof(int));
496 : :
497 : : /* increment number of elements in outer array */
498 : 10 : dims[0] += 1;
499 : :
500 : : /* make sure the added element matches our existing elements */
501 [ + + ]: 20 : for (i = 0; i < ndims2; i++)
502 : : {
503 [ + - - + ]: 10 : if (dims2[i] != dims[i + 1] || lbs2[i] != lbs[i + 1])
504 [ # # ]: 0 : ereport(ERROR,
505 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
506 : : errmsg("cannot concatenate incompatible arrays"),
507 : : errdetail("Arrays with differing dimensions are not "
508 : : "compatible for concatenation.")));
509 : : }
510 : : }
511 : :
512 : : /* Do this mainly for overflow checking */
513 : 14364 : nitems = ArrayGetNItems(ndims, dims);
514 : 14364 : ArrayCheckBounds(ndims, dims, lbs);
515 : :
516 : : /* build the result array */
517 : 14364 : ovfl = pg_add_s32_overflow(ndatabytes1, ndatabytes2, &ndatabytes);
518 [ + - - + ]: 14364 : if (ovfl || !AllocSizeIsValid(ndatabytes))
519 [ # # ]: 0 : ereport(ERROR,
520 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
521 : : errmsg("result array is too big"));
522 : 14364 : ndatabytes = ndatabytes1 + ndatabytes2;
523 [ + - - + ]: 14364 : if (ARR_HASNULL(v1) || ARR_HASNULL(v2))
524 : : {
525 : 0 : dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
526 : 0 : nbytes = ndatabytes + dataoffset;
527 : : }
528 : : else
529 : : {
530 : 14364 : dataoffset = 0; /* marker for no null bitmap */
531 : 14364 : nbytes = ndatabytes + ARR_OVERHEAD_NONULLS(ndims);
532 : : }
533 : 14364 : result = (ArrayType *) palloc0(nbytes);
534 : 14364 : SET_VARSIZE(result, nbytes);
535 : 14364 : result->ndim = ndims;
536 : 14364 : result->dataoffset = dataoffset;
537 : 14364 : result->elemtype = element_type;
538 : 14364 : memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
539 : 14364 : memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
540 : : /* data area is arg1 then arg2 */
541 [ - + ]: 14364 : memcpy(ARR_DATA_PTR(result), dat1, ndatabytes1);
542 [ - + ]: 14364 : memcpy(ARR_DATA_PTR(result) + ndatabytes1, dat2, ndatabytes2);
543 : : /* handle the null bitmap if needed */
544 [ - + ]: 14364 : if (ARR_HASNULL(result))
545 : : {
546 [ # # ]: 0 : array_bitmap_copy(ARR_NULLBITMAP(result), 0,
547 : : bitmap1, 0,
548 : : nitems1);
549 [ # # ]: 0 : array_bitmap_copy(ARR_NULLBITMAP(result), nitems1,
550 : : bitmap2, 0,
551 : : nitems2);
552 : : }
553 : :
554 : 14364 : PG_RETURN_ARRAYTYPE_P(result);
555 : : }
556 : :
557 : :
558 : : /*
559 : : * ARRAY_AGG(anynonarray) aggregate function
560 : : */
561 : : Datum
562 : 1563617 : array_agg_transfn(PG_FUNCTION_ARGS)
563 : : {
564 : 1563617 : Oid arg1_typeid = get_fn_expr_argtype(fcinfo->flinfo, 1);
565 : : MemoryContext aggcontext;
566 : : ArrayBuildState *state;
567 : : Datum elem;
568 : :
569 [ - + ]: 1563617 : if (arg1_typeid == InvalidOid)
570 [ # # ]: 0 : ereport(ERROR,
571 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
572 : : errmsg("could not determine input data type")));
573 : :
574 : : /*
575 : : * Note: we do not need a run-time check about whether arg1_typeid is a
576 : : * valid array element type, because the parser would have verified that
577 : : * while resolving the input/result types of this polymorphic aggregate.
578 : : */
579 : :
580 [ - + ]: 1563617 : if (!AggCheckCallContext(fcinfo, &aggcontext))
581 : : {
582 : : /* cannot be called directly because of internal-type argument */
583 [ # # ]: 0 : elog(ERROR, "array_agg_transfn called in non-aggregate context");
584 : : }
585 : :
586 [ + + ]: 1563617 : if (PG_ARGISNULL(0))
587 : 76610 : state = initArrayResult(arg1_typeid, aggcontext, false);
588 : : else
589 : 1487007 : state = (ArrayBuildState *) PG_GETARG_POINTER(0);
590 : :
591 [ + + ]: 1563617 : elem = PG_ARGISNULL(1) ? (Datum) 0 : PG_GETARG_DATUM(1);
592 : :
593 : 1563617 : state = accumArrayResult(state,
594 : : elem,
595 : 1563617 : PG_ARGISNULL(1),
596 : : arg1_typeid,
597 : : aggcontext);
598 : :
599 : : /*
600 : : * The transition type for array_agg() is declared to be "internal", which
601 : : * is a pass-by-value type the same size as a pointer. So we can safely
602 : : * pass the ArrayBuildState pointer through nodeAgg.c's machinations.
603 : : */
604 : 1563617 : PG_RETURN_POINTER(state);
605 : : }
606 : :
607 : : Datum
608 : 70 : array_agg_combine(PG_FUNCTION_ARGS)
609 : : {
610 : : ArrayBuildState *state1;
611 : : ArrayBuildState *state2;
612 : : MemoryContext agg_context;
613 : : MemoryContext old_context;
614 : :
615 [ - + ]: 70 : if (!AggCheckCallContext(fcinfo, &agg_context))
616 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
617 : :
618 [ + + ]: 70 : state1 = PG_ARGISNULL(0) ? NULL : (ArrayBuildState *) PG_GETARG_POINTER(0);
619 [ + - ]: 70 : state2 = PG_ARGISNULL(1) ? NULL : (ArrayBuildState *) PG_GETARG_POINTER(1);
620 : :
621 [ - + ]: 70 : if (state2 == NULL)
622 : : {
623 : : /*
624 : : * NULL state2 is easy, just return state1, which we know is already
625 : : * in the agg_context
626 : : */
627 [ # # ]: 0 : if (state1 == NULL)
628 : 0 : PG_RETURN_NULL();
629 : 0 : PG_RETURN_POINTER(state1);
630 : : }
631 : :
632 [ + + ]: 70 : if (state1 == NULL)
633 : : {
634 : : /* We must copy state2's data into the agg_context */
635 : 40 : state1 = initArrayResultWithSize(state2->element_type, agg_context,
636 : : false, state2->alen);
637 : :
638 : 40 : old_context = MemoryContextSwitchTo(agg_context);
639 : :
640 [ + + ]: 9842 : for (int i = 0; i < state2->nelems; i++)
641 : : {
642 [ + + ]: 9802 : if (!state2->dnulls[i])
643 : 7350 : state1->dvalues[i] = datumCopy(state2->dvalues[i],
644 : 7350 : state1->typbyval,
645 : 7350 : state1->typlen);
646 : : else
647 : 2452 : state1->dvalues[i] = (Datum) 0;
648 : : }
649 : :
650 : 40 : MemoryContextSwitchTo(old_context);
651 : :
652 : 40 : memcpy(state1->dnulls, state2->dnulls, sizeof(bool) * state2->nelems);
653 : :
654 : 40 : state1->nelems = state2->nelems;
655 : :
656 : 40 : PG_RETURN_POINTER(state1);
657 : : }
658 [ + - ]: 30 : else if (state2->nelems > 0)
659 : : {
660 : : /* We only need to combine the two states if state2 has any elements */
661 : 30 : int reqsize = state1->nelems + state2->nelems;
662 : 30 : MemoryContext oldContext = MemoryContextSwitchTo(state1->mcontext);
663 : :
664 : : Assert(state1->element_type == state2->element_type);
665 : :
666 : : /* Enlarge state1 arrays if needed */
667 [ + - ]: 30 : if (state1->alen < reqsize)
668 : : {
669 : : /* Use a power of 2 size rather than allocating just reqsize */
670 : 30 : state1->alen = pg_nextpower2_32(reqsize);
671 : 30 : state1->dvalues = repalloc_array(state1->dvalues, Datum, state1->alen);
672 : 30 : state1->dnulls = repalloc_array(state1->dnulls, bool, state1->alen);
673 : : }
674 : :
675 : : /* Copy in the state2 elements to the end of the state1 arrays */
676 [ + + ]: 10228 : for (int i = 0; i < state2->nelems; i++)
677 : : {
678 [ + + ]: 10198 : if (!state2->dnulls[i])
679 : 7650 : state1->dvalues[i + state1->nelems] =
680 : 7650 : datumCopy(state2->dvalues[i],
681 : 7650 : state1->typbyval,
682 : 7650 : state1->typlen);
683 : : else
684 : 2548 : state1->dvalues[i + state1->nelems] = (Datum) 0;
685 : : }
686 : :
687 : 30 : memcpy(&state1->dnulls[state1->nelems], state2->dnulls,
688 : 30 : sizeof(bool) * state2->nelems);
689 : :
690 : 30 : state1->nelems = reqsize;
691 : :
692 : 30 : MemoryContextSwitchTo(oldContext);
693 : : }
694 : :
695 : 30 : PG_RETURN_POINTER(state1);
696 : : }
697 : :
698 : : /*
699 : : * array_agg_serialize
700 : : * Serialize ArrayBuildState into bytea.
701 : : */
702 : : Datum
703 : 70 : array_agg_serialize(PG_FUNCTION_ARGS)
704 : : {
705 : : ArrayBuildState *state;
706 : : StringInfoData buf;
707 : : bytea *result;
708 : :
709 : : /* cannot be called directly because of internal-type argument */
710 : : Assert(AggCheckCallContext(fcinfo, NULL));
711 : :
712 : 70 : state = (ArrayBuildState *) PG_GETARG_POINTER(0);
713 : :
714 : 70 : pq_begintypsend(&buf);
715 : :
716 : : /*
717 : : * element_type. Putting this first is more convenient in deserialization
718 : : */
719 : 70 : pq_sendint32(&buf, state->element_type);
720 : :
721 : : /*
722 : : * nelems -- send first so we know how large to make the dvalues and
723 : : * dnulls array during deserialization.
724 : : */
725 : 70 : pq_sendint64(&buf, state->nelems);
726 : :
727 : : /* alen can be decided during deserialization */
728 : :
729 : : /* typlen */
730 : 70 : pq_sendint16(&buf, state->typlen);
731 : :
732 : : /* typbyval */
733 : 70 : pq_sendbyte(&buf, state->typbyval);
734 : :
735 : : /* typalign */
736 : 70 : pq_sendbyte(&buf, state->typalign);
737 : :
738 : : /* dnulls */
739 : 70 : pq_sendbytes(&buf, state->dnulls, sizeof(bool) * state->nelems);
740 : :
741 : : /*
742 : : * dvalues. By agreement with array_agg_deserialize, when the element
743 : : * type is byval, we just transmit the Datum array as-is, including any
744 : : * null elements. For by-ref types, we must invoke the element type's
745 : : * send function, and we skip null elements (which is why the nulls flags
746 : : * must be sent first).
747 : : */
748 [ + - ]: 70 : if (state->typbyval)
749 : 70 : pq_sendbytes(&buf, state->dvalues, sizeof(Datum) * state->nelems);
750 : : else
751 : : {
752 : : SerialIOData *iodata;
753 : : int i;
754 : :
755 : : /* Avoid repeat catalog lookups for typsend function */
756 : 0 : iodata = (SerialIOData *) fcinfo->flinfo->fn_extra;
757 [ # # ]: 0 : if (iodata == NULL)
758 : : {
759 : : Oid typsend;
760 : : bool typisvarlena;
761 : :
762 : : iodata = (SerialIOData *)
763 : 0 : MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
764 : : sizeof(SerialIOData));
765 : 0 : getTypeBinaryOutputInfo(state->element_type, &typsend,
766 : : &typisvarlena);
767 : 0 : fmgr_info_cxt(typsend, &iodata->typsend,
768 : 0 : fcinfo->flinfo->fn_mcxt);
769 : 0 : fcinfo->flinfo->fn_extra = iodata;
770 : : }
771 : :
772 [ # # ]: 0 : for (i = 0; i < state->nelems; i++)
773 : : {
774 : : bytea *outputbytes;
775 : :
776 [ # # ]: 0 : if (state->dnulls[i])
777 : 0 : continue;
778 : 0 : outputbytes = SendFunctionCall(&iodata->typsend,
779 : 0 : state->dvalues[i]);
780 : 0 : pq_sendint32(&buf, VARSIZE(outputbytes) - VARHDRSZ);
781 : 0 : pq_sendbytes(&buf, VARDATA(outputbytes),
782 : 0 : VARSIZE(outputbytes) - VARHDRSZ);
783 : : }
784 : : }
785 : :
786 : 70 : result = pq_endtypsend(&buf);
787 : :
788 : 70 : PG_RETURN_BYTEA_P(result);
789 : : }
790 : :
791 : : Datum
792 : 70 : array_agg_deserialize(PG_FUNCTION_ARGS)
793 : : {
794 : : bytea *sstate;
795 : : ArrayBuildState *result;
796 : : StringInfoData buf;
797 : : Oid element_type;
798 : : int64 nelems;
799 : : const char *temp;
800 : :
801 [ - + ]: 70 : if (!AggCheckCallContext(fcinfo, NULL))
802 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
803 : :
804 : 70 : sstate = PG_GETARG_BYTEA_PP(0);
805 : :
806 : : /*
807 : : * Initialize a StringInfo so that we can "receive" it using the standard
808 : : * recv-function infrastructure.
809 : : */
810 : 70 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
811 : 70 : VARSIZE_ANY_EXHDR(sstate));
812 : :
813 : : /* element_type */
814 : 70 : element_type = pq_getmsgint(&buf, 4);
815 : :
816 : : /* nelems */
817 : 70 : nelems = pq_getmsgint64(&buf);
818 : :
819 : : /* Create output ArrayBuildState with the needed number of elements */
820 : 70 : result = initArrayResultWithSize(element_type, CurrentMemoryContext,
821 : : false, nelems);
822 : 70 : result->nelems = nelems;
823 : :
824 : : /* typlen */
825 : 70 : result->typlen = pq_getmsgint(&buf, 2);
826 : :
827 : : /* typbyval */
828 : 70 : result->typbyval = pq_getmsgbyte(&buf);
829 : :
830 : : /* typalign */
831 : 70 : result->typalign = pq_getmsgbyte(&buf);
832 : :
833 : : /* dnulls */
834 : 70 : temp = pq_getmsgbytes(&buf, sizeof(bool) * nelems);
835 : 70 : memcpy(result->dnulls, temp, sizeof(bool) * nelems);
836 : :
837 : : /* dvalues --- see comment in array_agg_serialize */
838 [ + - ]: 70 : if (result->typbyval)
839 : : {
840 : 70 : temp = pq_getmsgbytes(&buf, sizeof(Datum) * nelems);
841 : 70 : memcpy(result->dvalues, temp, sizeof(Datum) * nelems);
842 : : }
843 : : else
844 : : {
845 : : DeserialIOData *iodata;
846 : :
847 : : /* Avoid repeat catalog lookups for typreceive function */
848 : 0 : iodata = (DeserialIOData *) fcinfo->flinfo->fn_extra;
849 [ # # ]: 0 : if (iodata == NULL)
850 : : {
851 : : Oid typreceive;
852 : :
853 : : iodata = (DeserialIOData *)
854 : 0 : MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
855 : : sizeof(DeserialIOData));
856 : 0 : getTypeBinaryInputInfo(element_type, &typreceive,
857 : : &iodata->typioparam);
858 : 0 : fmgr_info_cxt(typreceive, &iodata->typreceive,
859 : 0 : fcinfo->flinfo->fn_mcxt);
860 : 0 : fcinfo->flinfo->fn_extra = iodata;
861 : : }
862 : :
863 [ # # ]: 0 : for (int i = 0; i < nelems; i++)
864 : : {
865 : : int itemlen;
866 : : StringInfoData elem_buf;
867 : :
868 [ # # ]: 0 : if (result->dnulls[i])
869 : : {
870 : 0 : result->dvalues[i] = (Datum) 0;
871 : 0 : continue;
872 : : }
873 : :
874 : 0 : itemlen = pq_getmsgint(&buf, 4);
875 [ # # # # ]: 0 : if (itemlen < 0 || itemlen > (buf.len - buf.cursor))
876 [ # # ]: 0 : ereport(ERROR,
877 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
878 : : errmsg("insufficient data left in message")));
879 : :
880 : : /*
881 : : * Rather than copying data around, we just initialize a
882 : : * StringInfo pointing to the correct portion of the message
883 : : * buffer.
884 : : */
885 : 0 : initReadOnlyStringInfo(&elem_buf, &buf.data[buf.cursor], itemlen);
886 : :
887 : 0 : buf.cursor += itemlen;
888 : :
889 : : /* Now call the element's receiveproc */
890 : 0 : result->dvalues[i] = ReceiveFunctionCall(&iodata->typreceive,
891 : : &elem_buf,
892 : : iodata->typioparam,
893 : : -1);
894 : : }
895 : : }
896 : :
897 : 70 : pq_getmsgend(&buf);
898 : :
899 : 70 : PG_RETURN_POINTER(result);
900 : : }
901 : :
902 : : Datum
903 : 82052 : array_agg_finalfn(PG_FUNCTION_ARGS)
904 : : {
905 : : Datum result;
906 : : ArrayBuildState *state;
907 : : int dims[1];
908 : : int lbs[1];
909 : :
910 : : /* cannot be called directly because of internal-type argument */
911 : : Assert(AggCheckCallContext(fcinfo, NULL));
912 : :
913 [ + + ]: 82052 : state = PG_ARGISNULL(0) ? NULL : (ArrayBuildState *) PG_GETARG_POINTER(0);
914 : :
915 [ + + ]: 82052 : if (state == NULL)
916 : 5460 : PG_RETURN_NULL(); /* returns null iff no input values */
917 : :
918 : 76592 : dims[0] = state->nelems;
919 : 76592 : lbs[0] = 1;
920 : :
921 : : /*
922 : : * Make the result. We cannot release the ArrayBuildState because
923 : : * sometimes aggregate final functions are re-executed. Rather, it is
924 : : * nodeAgg.c's responsibility to reset the aggcontext when it's safe to do
925 : : * so.
926 : : */
927 : 76592 : result = makeMdArrayResult(state, 1, dims, lbs,
928 : : CurrentMemoryContext,
929 : : false);
930 : :
931 : 76592 : PG_RETURN_DATUM(result);
932 : : }
933 : :
934 : : /*
935 : : * ARRAY_AGG(anyarray) aggregate function
936 : : */
937 : : Datum
938 : 83893 : array_agg_array_transfn(PG_FUNCTION_ARGS)
939 : : {
940 : 83893 : Oid arg1_typeid = get_fn_expr_argtype(fcinfo->flinfo, 1);
941 : : MemoryContext aggcontext;
942 : : ArrayBuildStateArr *state;
943 : :
944 [ - + ]: 83893 : if (arg1_typeid == InvalidOid)
945 [ # # ]: 0 : ereport(ERROR,
946 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
947 : : errmsg("could not determine input data type")));
948 : :
949 : : /*
950 : : * Note: we do not need a run-time check about whether arg1_typeid is a
951 : : * valid array type, because the parser would have verified that while
952 : : * resolving the input/result types of this polymorphic aggregate.
953 : : */
954 : :
955 [ - + ]: 83893 : if (!AggCheckCallContext(fcinfo, &aggcontext))
956 : : {
957 : : /* cannot be called directly because of internal-type argument */
958 [ # # ]: 0 : elog(ERROR, "array_agg_array_transfn called in non-aggregate context");
959 : : }
960 : :
961 : :
962 [ + + ]: 83893 : if (PG_ARGISNULL(0))
963 : 260 : state = initArrayResultArr(arg1_typeid, InvalidOid, aggcontext, false);
964 : : else
965 : 83633 : state = (ArrayBuildStateArr *) PG_GETARG_POINTER(0);
966 : :
967 : 83893 : state = accumArrayResultArr(state,
968 : : PG_GETARG_DATUM(1),
969 : 83893 : PG_ARGISNULL(1),
970 : : arg1_typeid,
971 : : aggcontext);
972 : :
973 : : /*
974 : : * The transition type for array_agg() is declared to be "internal", which
975 : : * is a pass-by-value type the same size as a pointer. So we can safely
976 : : * pass the ArrayBuildStateArr pointer through nodeAgg.c's machinations.
977 : : */
978 : 83881 : PG_RETURN_POINTER(state);
979 : : }
980 : :
981 : : Datum
982 : 70 : array_agg_array_combine(PG_FUNCTION_ARGS)
983 : : {
984 : : ArrayBuildStateArr *state1;
985 : : ArrayBuildStateArr *state2;
986 : : MemoryContext agg_context;
987 : : MemoryContext old_context;
988 : :
989 [ - + ]: 70 : if (!AggCheckCallContext(fcinfo, &agg_context))
990 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
991 : :
992 [ + + ]: 70 : state1 = PG_ARGISNULL(0) ? NULL : (ArrayBuildStateArr *) PG_GETARG_POINTER(0);
993 [ + - ]: 70 : state2 = PG_ARGISNULL(1) ? NULL : (ArrayBuildStateArr *) PG_GETARG_POINTER(1);
994 : :
995 [ - + ]: 70 : if (state2 == NULL)
996 : : {
997 : : /*
998 : : * NULL state2 is easy, just return state1, which we know is already
999 : : * in the agg_context
1000 : : */
1001 [ # # ]: 0 : if (state1 == NULL)
1002 : 0 : PG_RETURN_NULL();
1003 : 0 : PG_RETURN_POINTER(state1);
1004 : : }
1005 : :
1006 [ + + ]: 70 : if (state1 == NULL)
1007 : : {
1008 : : /* We must copy state2's data into the agg_context */
1009 : 40 : old_context = MemoryContextSwitchTo(agg_context);
1010 : :
1011 : 40 : state1 = initArrayResultArr(state2->array_type, InvalidOid,
1012 : : agg_context, false);
1013 : :
1014 : 40 : state1->abytes = state2->abytes;
1015 : 40 : state1->data = (char *) palloc(state1->abytes);
1016 : :
1017 [ + + ]: 40 : if (state2->nullbitmap)
1018 : : {
1019 : 20 : int size = (state2->aitems + 7) / 8;
1020 : :
1021 : 20 : state1->nullbitmap = (uint8 *) palloc(size);
1022 : 20 : memcpy(state1->nullbitmap, state2->nullbitmap, size);
1023 : : }
1024 : :
1025 : 40 : memcpy(state1->data, state2->data, state2->nbytes);
1026 : 40 : state1->nbytes = state2->nbytes;
1027 : 40 : state1->aitems = state2->aitems;
1028 : 40 : state1->nitems = state2->nitems;
1029 : 40 : state1->ndims = state2->ndims;
1030 : 40 : memcpy(state1->dims, state2->dims, sizeof(state2->dims));
1031 : 40 : memcpy(state1->lbs, state2->lbs, sizeof(state2->lbs));
1032 : 40 : state1->array_type = state2->array_type;
1033 : 40 : state1->element_type = state2->element_type;
1034 : :
1035 : 40 : MemoryContextSwitchTo(old_context);
1036 : :
1037 : 40 : PG_RETURN_POINTER(state1);
1038 : : }
1039 : :
1040 : : /* We only need to combine the two states if state2 has any items */
1041 [ + - ]: 30 : if (state2->nitems > 0)
1042 : : {
1043 : : MemoryContext oldContext;
1044 : : int reqsize;
1045 : : int newnitems;
1046 : : int i;
1047 : :
1048 : : /*
1049 : : * Check the states are compatible with each other. Ensure we use the
1050 : : * same error messages that are listed in accumArrayResultArr so that
1051 : : * the same error is shown as would have been if we'd not used the
1052 : : * combine function for the aggregation.
1053 : : */
1054 [ - + ]: 30 : if (state1->ndims != state2->ndims)
1055 [ # # ]: 0 : ereport(ERROR,
1056 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1057 : : errmsg("cannot accumulate arrays of different dimensionality")));
1058 : :
1059 : : /* Check dimensions match ignoring the first dimension. */
1060 [ + + ]: 60 : for (i = 1; i < state1->ndims; i++)
1061 : : {
1062 [ + - - + ]: 30 : if (state1->dims[i] != state2->dims[i] || state1->lbs[i] != state2->lbs[i])
1063 [ # # ]: 0 : ereport(ERROR,
1064 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1065 : : errmsg("cannot accumulate arrays of different dimensionality")));
1066 : : }
1067 : :
1068 : : /* Types should match already. */
1069 : : Assert(state1->array_type == state2->array_type);
1070 : : Assert(state1->element_type == state2->element_type);
1071 : :
1072 : : /* Calculate new sizes, guarding against overflow. */
1073 [ + - + - ]: 60 : if (pg_add_s32_overflow(state1->nbytes, state2->nbytes, &reqsize) ||
1074 : 30 : pg_add_s32_overflow(state1->nitems, state2->nitems, &newnitems) ||
1075 [ - + ]: 30 : !AllocSizeIsValid(reqsize))
1076 [ # # ]: 0 : ereport(ERROR,
1077 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1078 : : errmsg("array size exceeds the maximum allowed (%zu)",
1079 : : MaxArraySize)));
1080 : :
1081 : 30 : oldContext = MemoryContextSwitchTo(state1->mcontext);
1082 : :
1083 : : /*
1084 : : * If there's not enough space in state1 then we'll need to reallocate
1085 : : * more.
1086 : : */
1087 [ + + ]: 30 : if (state1->abytes < reqsize)
1088 : : {
1089 : : /* use a power of 2 size rather than allocating just reqsize */
1090 : 10 : state1->abytes = pg_nextpower2_32(reqsize);
1091 : 10 : state1->data = (char *) repalloc(state1->data, state1->abytes);
1092 : : }
1093 : :
1094 : : /* Combine the null bitmaps, if present. */
1095 [ + + - + ]: 30 : if (state1->nullbitmap || state2->nullbitmap)
1096 : : {
1097 [ - + ]: 15 : if (state1->nullbitmap == NULL)
1098 : : {
1099 : : /*
1100 : : * First input with nulls; we must retrospectively handle any
1101 : : * previous inputs by marking all their items non-null.
1102 : : */
1103 : 0 : state1->aitems = pg_nextpower2_32(Max(256, newnitems));
1104 : 0 : state1->nullbitmap = palloc_array(uint8, (state1->aitems + 7) / 8);
1105 : 0 : array_bitmap_copy(state1->nullbitmap, 0,
1106 : : NULL, 0,
1107 : : state1->nitems);
1108 : : }
1109 [ + + ]: 15 : else if (newnitems > state1->aitems)
1110 : : {
1111 : 10 : state1->aitems = pg_nextpower2_32(newnitems);
1112 : 10 : state1->nullbitmap = repalloc_array(state1->nullbitmap,
1113 : : uint8, (state1->aitems + 7) / 8);
1114 : : }
1115 : : /* This will do the right thing if state2->nullbitmap is NULL: */
1116 : 15 : array_bitmap_copy(state1->nullbitmap, state1->nitems,
1117 : 15 : state2->nullbitmap, 0,
1118 : : state2->nitems);
1119 : : }
1120 : :
1121 : : /* Finally, combine the data and adjust sizes. */
1122 : 30 : memcpy(state1->data + state1->nbytes, state2->data, state2->nbytes);
1123 : 30 : state1->nbytes += state2->nbytes;
1124 : 30 : state1->nitems += state2->nitems;
1125 : :
1126 : 30 : state1->dims[0] += state2->dims[0];
1127 : : /* remaining dims already match, per test above */
1128 : :
1129 : 30 : MemoryContextSwitchTo(oldContext);
1130 : : }
1131 : :
1132 : 30 : PG_RETURN_POINTER(state1);
1133 : : }
1134 : :
1135 : : /*
1136 : : * array_agg_array_serialize
1137 : : * Serialize ArrayBuildStateArr into bytea.
1138 : : */
1139 : : Datum
1140 : 70 : array_agg_array_serialize(PG_FUNCTION_ARGS)
1141 : : {
1142 : : ArrayBuildStateArr *state;
1143 : : StringInfoData buf;
1144 : : bytea *result;
1145 : :
1146 : : /* cannot be called directly because of internal-type argument */
1147 : : Assert(AggCheckCallContext(fcinfo, NULL));
1148 : :
1149 : 70 : state = (ArrayBuildStateArr *) PG_GETARG_POINTER(0);
1150 : :
1151 : 70 : pq_begintypsend(&buf);
1152 : :
1153 : : /*
1154 : : * element_type. Putting this first is more convenient in deserialization
1155 : : * so that we can init the new state sooner.
1156 : : */
1157 : 70 : pq_sendint32(&buf, state->element_type);
1158 : :
1159 : : /* array_type */
1160 : 70 : pq_sendint32(&buf, state->array_type);
1161 : :
1162 : : /* nbytes */
1163 : 70 : pq_sendint32(&buf, state->nbytes);
1164 : :
1165 : : /* data */
1166 : 70 : pq_sendbytes(&buf, state->data, state->nbytes);
1167 : :
1168 : : /* abytes */
1169 : 70 : pq_sendint32(&buf, state->abytes);
1170 : :
1171 : : /* aitems */
1172 : 70 : pq_sendint32(&buf, state->aitems);
1173 : :
1174 : : /* nullbitmap */
1175 [ + + ]: 70 : if (state->nullbitmap)
1176 : : {
1177 : : Assert(state->aitems > 0);
1178 : 35 : pq_sendbytes(&buf, state->nullbitmap, (state->aitems + 7) / 8);
1179 : : }
1180 : :
1181 : : /* nitems */
1182 : 70 : pq_sendint32(&buf, state->nitems);
1183 : :
1184 : : /* ndims */
1185 : 70 : pq_sendint32(&buf, state->ndims);
1186 : :
1187 : : /* dims: XXX should we just send ndims elements? */
1188 : 70 : pq_sendbytes(&buf, state->dims, sizeof(state->dims));
1189 : :
1190 : : /* lbs */
1191 : 70 : pq_sendbytes(&buf, state->lbs, sizeof(state->lbs));
1192 : :
1193 : 70 : result = pq_endtypsend(&buf);
1194 : :
1195 : 70 : PG_RETURN_BYTEA_P(result);
1196 : : }
1197 : :
1198 : : Datum
1199 : 70 : array_agg_array_deserialize(PG_FUNCTION_ARGS)
1200 : : {
1201 : : bytea *sstate;
1202 : : ArrayBuildStateArr *result;
1203 : : StringInfoData buf;
1204 : : Oid element_type;
1205 : : Oid array_type;
1206 : : int nbytes;
1207 : : const char *temp;
1208 : :
1209 : : /* cannot be called directly because of internal-type argument */
1210 : : Assert(AggCheckCallContext(fcinfo, NULL));
1211 : :
1212 : 70 : sstate = PG_GETARG_BYTEA_PP(0);
1213 : :
1214 : : /*
1215 : : * Initialize a StringInfo so that we can "receive" it using the standard
1216 : : * recv-function infrastructure.
1217 : : */
1218 : 70 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
1219 : 70 : VARSIZE_ANY_EXHDR(sstate));
1220 : :
1221 : : /* element_type */
1222 : 70 : element_type = pq_getmsgint(&buf, 4);
1223 : :
1224 : : /* array_type */
1225 : 70 : array_type = pq_getmsgint(&buf, 4);
1226 : :
1227 : : /* nbytes */
1228 : 70 : nbytes = pq_getmsgint(&buf, 4);
1229 : :
1230 : 70 : result = initArrayResultArr(array_type, element_type,
1231 : : CurrentMemoryContext, false);
1232 : :
1233 : 70 : result->abytes = 1024;
1234 [ + + ]: 90 : while (result->abytes < nbytes)
1235 : 20 : result->abytes *= 2;
1236 : :
1237 : 70 : result->data = (char *) palloc(result->abytes);
1238 : :
1239 : : /* data */
1240 : 70 : temp = pq_getmsgbytes(&buf, nbytes);
1241 : 70 : memcpy(result->data, temp, nbytes);
1242 : 70 : result->nbytes = nbytes;
1243 : :
1244 : : /* abytes */
1245 : 70 : result->abytes = pq_getmsgint(&buf, 4);
1246 : :
1247 : : /* aitems: might be 0 */
1248 : 70 : result->aitems = pq_getmsgint(&buf, 4);
1249 : :
1250 : : /* nullbitmap */
1251 [ + + ]: 70 : if (result->aitems > 0)
1252 : : {
1253 : 35 : int size = (result->aitems + 7) / 8;
1254 : :
1255 : 35 : result->nullbitmap = (uint8 *) palloc(size);
1256 : 35 : temp = pq_getmsgbytes(&buf, size);
1257 : 35 : memcpy(result->nullbitmap, temp, size);
1258 : : }
1259 : : else
1260 : 35 : result->nullbitmap = NULL;
1261 : :
1262 : : /* nitems */
1263 : 70 : result->nitems = pq_getmsgint(&buf, 4);
1264 : :
1265 : : /* ndims */
1266 : 70 : result->ndims = pq_getmsgint(&buf, 4);
1267 : :
1268 : : /* dims */
1269 : 70 : temp = pq_getmsgbytes(&buf, sizeof(result->dims));
1270 : 70 : memcpy(result->dims, temp, sizeof(result->dims));
1271 : :
1272 : : /* lbs */
1273 : 70 : temp = pq_getmsgbytes(&buf, sizeof(result->lbs));
1274 : 70 : memcpy(result->lbs, temp, sizeof(result->lbs));
1275 : :
1276 : 70 : pq_getmsgend(&buf);
1277 : :
1278 : 70 : PG_RETURN_POINTER(result);
1279 : : }
1280 : :
1281 : : Datum
1282 : 219 : array_agg_array_finalfn(PG_FUNCTION_ARGS)
1283 : : {
1284 : : Datum result;
1285 : : ArrayBuildStateArr *state;
1286 : :
1287 : : /* cannot be called directly because of internal-type argument */
1288 : : Assert(AggCheckCallContext(fcinfo, NULL));
1289 : :
1290 [ + + ]: 219 : state = PG_ARGISNULL(0) ? NULL : (ArrayBuildStateArr *) PG_GETARG_POINTER(0);
1291 : :
1292 [ + + ]: 219 : if (state == NULL)
1293 : 1 : PG_RETURN_NULL(); /* returns null iff no input values */
1294 : :
1295 : : /*
1296 : : * Make the result. We cannot release the ArrayBuildStateArr because
1297 : : * sometimes aggregate final functions are re-executed. Rather, it is
1298 : : * nodeAgg.c's responsibility to reset the aggcontext when it's safe to do
1299 : : * so.
1300 : : */
1301 : 218 : result = makeArrayResultArr(state, CurrentMemoryContext, false);
1302 : :
1303 : 218 : PG_RETURN_DATUM(result);
1304 : : }
1305 : :
1306 : : /*-----------------------------------------------------------------------------
1307 : : * array_position, array_position_start :
1308 : : * return the offset of a value in an array.
1309 : : *
1310 : : * IS NOT DISTINCT FROM semantics are used for comparisons. Return NULL when
1311 : : * the value is not found.
1312 : : *-----------------------------------------------------------------------------
1313 : : */
1314 : : Datum
1315 : 128 : array_position(PG_FUNCTION_ARGS)
1316 : : {
1317 : 128 : return array_position_common(fcinfo);
1318 : : }
1319 : :
1320 : : Datum
1321 : 12 : array_position_start(PG_FUNCTION_ARGS)
1322 : : {
1323 : 12 : return array_position_common(fcinfo);
1324 : : }
1325 : :
1326 : : /*
1327 : : * array_position_common
1328 : : * Common code for array_position and array_position_start
1329 : : *
1330 : : * These are separate wrappers for the sake of opr_sanity regression test.
1331 : : * They are not strict so we have to test for null inputs explicitly.
1332 : : */
1333 : : static Datum
1334 : 140 : array_position_common(FunctionCallInfo fcinfo)
1335 : : {
1336 : : ArrayType *array;
1337 : 140 : Oid collation = PG_GET_COLLATION();
1338 : : Oid element_type;
1339 : : Datum searched_element,
1340 : : value;
1341 : : bool isnull;
1342 : : int position,
1343 : : position_min;
1344 : 140 : bool found = false;
1345 : : TypeCacheEntry *typentry;
1346 : : ArrayMetaState *my_extra;
1347 : : bool null_search;
1348 : : ArrayIterator array_iterator;
1349 : :
1350 [ - + ]: 140 : if (PG_ARGISNULL(0))
1351 : 0 : PG_RETURN_NULL();
1352 : :
1353 : 140 : array = PG_GETARG_ARRAYTYPE_P(0);
1354 : :
1355 : : /*
1356 : : * We refuse to search for elements in multi-dimensional arrays, since we
1357 : : * have no good way to report the element's location in the array.
1358 : : */
1359 [ + + ]: 140 : if (ARR_NDIM(array) > 1)
1360 [ + - ]: 4 : ereport(ERROR,
1361 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1362 : : errmsg("searching for elements in multidimensional arrays is not supported")));
1363 : :
1364 : : /* Searching in an empty array is well-defined, though: it always fails */
1365 [ - + ]: 136 : if (ARR_NDIM(array) < 1)
1366 : 0 : PG_RETURN_NULL();
1367 : :
1368 [ + + ]: 136 : if (PG_ARGISNULL(1))
1369 : : {
1370 : : /* fast return when the array doesn't have nulls */
1371 [ + + ]: 10 : if (!array_contains_nulls(array))
1372 : 5 : PG_RETURN_NULL();
1373 : 5 : searched_element = (Datum) 0;
1374 : 5 : null_search = true;
1375 : : }
1376 : : else
1377 : : {
1378 : 126 : searched_element = PG_GETARG_DATUM(1);
1379 : 126 : null_search = false;
1380 : : }
1381 : :
1382 : 131 : element_type = ARR_ELEMTYPE(array);
1383 : 131 : position = (ARR_LBOUND(array))[0] - 1;
1384 : :
1385 : : /* figure out where to start */
1386 [ + + ]: 131 : if (PG_NARGS() == 3)
1387 : : {
1388 [ - + ]: 12 : if (PG_ARGISNULL(2))
1389 [ # # ]: 0 : ereport(ERROR,
1390 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1391 : : errmsg("initial position must not be null")));
1392 : :
1393 : 12 : position_min = PG_GETARG_INT32(2);
1394 : : }
1395 : : else
1396 : 119 : position_min = (ARR_LBOUND(array))[0];
1397 : :
1398 : : /*
1399 : : * We arrange to look up type info for array_create_iterator only once per
1400 : : * series of calls, assuming the element type doesn't change underneath
1401 : : * us.
1402 : : */
1403 : 131 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1404 [ + + ]: 131 : if (my_extra == NULL)
1405 : : {
1406 : 59 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1407 : : sizeof(ArrayMetaState));
1408 : 59 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1409 : 59 : my_extra->element_type = ~element_type;
1410 : : }
1411 : :
1412 [ + + ]: 131 : if (my_extra->element_type != element_type)
1413 : : {
1414 : 59 : get_typlenbyvalalign(element_type,
1415 : : &my_extra->typlen,
1416 : : &my_extra->typbyval,
1417 : : &my_extra->typalign);
1418 : :
1419 : 59 : typentry = lookup_type_cache(element_type, TYPECACHE_EQ_OPR_FINFO);
1420 : :
1421 [ - + ]: 59 : if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
1422 [ # # ]: 0 : ereport(ERROR,
1423 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
1424 : : errmsg("could not identify an equality operator for type %s",
1425 : : format_type_be(element_type))));
1426 : :
1427 : 59 : my_extra->element_type = element_type;
1428 : 59 : fmgr_info_cxt(typentry->eq_opr_finfo.fn_oid, &my_extra->proc,
1429 : 59 : fcinfo->flinfo->fn_mcxt);
1430 : : }
1431 : :
1432 : : /* Examine each array element until we find a match. */
1433 : 131 : array_iterator = array_create_iterator(array, 0, my_extra);
1434 [ + + ]: 395 : while (array_iterate(array_iterator, &value, &isnull))
1435 : : {
1436 : 373 : position++;
1437 : :
1438 : : /* skip initial elements if caller requested so */
1439 [ + + ]: 373 : if (position < position_min)
1440 : 52 : continue;
1441 : :
1442 : : /*
1443 : : * Can't look at the array element's value if it's null; but if we
1444 : : * search for null, we have a hit and are done.
1445 : : */
1446 [ + + + + ]: 321 : if (isnull || null_search)
1447 : : {
1448 [ + + + + ]: 35 : if (isnull && null_search)
1449 : : {
1450 : 5 : found = true;
1451 : 5 : break;
1452 : : }
1453 : : else
1454 : 30 : continue;
1455 : : }
1456 : :
1457 : : /* not nulls, so run the operator */
1458 [ + + ]: 286 : if (DatumGetBool(FunctionCall2Coll(&my_extra->proc, collation,
1459 : : searched_element, value)))
1460 : : {
1461 : 104 : found = true;
1462 : 104 : break;
1463 : : }
1464 : : }
1465 : :
1466 : 131 : array_free_iterator(array_iterator);
1467 : :
1468 : : /* Avoid leaking memory when handed toasted input */
1469 [ + + ]: 131 : PG_FREE_IF_COPY(array, 0);
1470 : :
1471 [ + + ]: 131 : if (!found)
1472 : 22 : PG_RETURN_NULL();
1473 : :
1474 : 109 : PG_RETURN_INT32(position);
1475 : : }
1476 : :
1477 : : /*-----------------------------------------------------------------------------
1478 : : * array_positions :
1479 : : * return an array of positions of a value in an array.
1480 : : *
1481 : : * IS NOT DISTINCT FROM semantics are used for comparisons. Returns NULL when
1482 : : * the input array is NULL. When the value is not found in the array, returns
1483 : : * an empty array.
1484 : : *
1485 : : * This is not strict so we have to test for null inputs explicitly.
1486 : : *-----------------------------------------------------------------------------
1487 : : */
1488 : : Datum
1489 : 46 : array_positions(PG_FUNCTION_ARGS)
1490 : : {
1491 : : ArrayType *array;
1492 : 46 : Oid collation = PG_GET_COLLATION();
1493 : : Oid element_type;
1494 : : Datum searched_element,
1495 : : value;
1496 : : bool isnull;
1497 : : int position;
1498 : : TypeCacheEntry *typentry;
1499 : : ArrayMetaState *my_extra;
1500 : : bool null_search;
1501 : : ArrayIterator array_iterator;
1502 : 46 : ArrayBuildState *astate = NULL;
1503 : :
1504 [ + + ]: 46 : if (PG_ARGISNULL(0))
1505 : 10 : PG_RETURN_NULL();
1506 : :
1507 : 36 : array = PG_GETARG_ARRAYTYPE_P(0);
1508 : :
1509 : : /*
1510 : : * We refuse to search for elements in multi-dimensional arrays, since we
1511 : : * have no good way to report the element's location in the array.
1512 : : */
1513 [ + + ]: 36 : if (ARR_NDIM(array) > 1)
1514 [ + - ]: 4 : ereport(ERROR,
1515 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1516 : : errmsg("searching for elements in multidimensional arrays is not supported")));
1517 : :
1518 : 32 : astate = initArrayResult(INT4OID, CurrentMemoryContext, false);
1519 : :
1520 : : /* Searching in an empty array is well-defined, though: it always fails */
1521 [ - + ]: 32 : if (ARR_NDIM(array) < 1)
1522 : 0 : PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
1523 : :
1524 [ + + ]: 32 : if (PG_ARGISNULL(1))
1525 : : {
1526 : : /* fast return when the array doesn't have nulls */
1527 [ + + ]: 10 : if (!array_contains_nulls(array))
1528 : 5 : PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
1529 : 5 : searched_element = (Datum) 0;
1530 : 5 : null_search = true;
1531 : : }
1532 : : else
1533 : : {
1534 : 22 : searched_element = PG_GETARG_DATUM(1);
1535 : 22 : null_search = false;
1536 : : }
1537 : :
1538 : 27 : element_type = ARR_ELEMTYPE(array);
1539 : 27 : position = (ARR_LBOUND(array))[0] - 1;
1540 : :
1541 : : /*
1542 : : * We arrange to look up type info for array_create_iterator only once per
1543 : : * series of calls, assuming the element type doesn't change underneath
1544 : : * us.
1545 : : */
1546 : 27 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1547 [ + + ]: 27 : if (my_extra == NULL)
1548 : : {
1549 : 23 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1550 : : sizeof(ArrayMetaState));
1551 : 23 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1552 : 23 : my_extra->element_type = ~element_type;
1553 : : }
1554 : :
1555 [ + + ]: 27 : if (my_extra->element_type != element_type)
1556 : : {
1557 : 23 : get_typlenbyvalalign(element_type,
1558 : : &my_extra->typlen,
1559 : : &my_extra->typbyval,
1560 : : &my_extra->typalign);
1561 : :
1562 : 23 : typentry = lookup_type_cache(element_type, TYPECACHE_EQ_OPR_FINFO);
1563 : :
1564 [ - + ]: 23 : if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
1565 [ # # ]: 0 : ereport(ERROR,
1566 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
1567 : : errmsg("could not identify an equality operator for type %s",
1568 : : format_type_be(element_type))));
1569 : :
1570 : 23 : my_extra->element_type = element_type;
1571 : 23 : fmgr_info_cxt(typentry->eq_opr_finfo.fn_oid, &my_extra->proc,
1572 : 23 : fcinfo->flinfo->fn_mcxt);
1573 : : }
1574 : :
1575 : : /*
1576 : : * Accumulate each array position iff the element matches the given
1577 : : * element.
1578 : : */
1579 : 27 : array_iterator = array_create_iterator(array, 0, my_extra);
1580 [ + + ]: 574 : while (array_iterate(array_iterator, &value, &isnull))
1581 : : {
1582 : 547 : position += 1;
1583 : :
1584 : : /*
1585 : : * Can't look at the array element's value if it's null; but if we
1586 : : * search for null, we have a hit.
1587 : : */
1588 [ + + + + ]: 547 : if (isnull || null_search)
1589 : : {
1590 [ + + + - ]: 60 : if (isnull && null_search)
1591 : : astate =
1592 : 10 : accumArrayResult(astate, Int32GetDatum(position), false,
1593 : : INT4OID, CurrentMemoryContext);
1594 : :
1595 : 60 : continue;
1596 : : }
1597 : :
1598 : : /* not nulls, so run the operator */
1599 [ + + ]: 487 : if (DatumGetBool(FunctionCall2Coll(&my_extra->proc, collation,
1600 : : searched_element, value)))
1601 : : astate =
1602 : 63 : accumArrayResult(astate, Int32GetDatum(position), false,
1603 : : INT4OID, CurrentMemoryContext);
1604 : : }
1605 : :
1606 : 27 : array_free_iterator(array_iterator);
1607 : :
1608 : : /* Avoid leaking memory when handed toasted input */
1609 [ - + ]: 27 : PG_FREE_IF_COPY(array, 0);
1610 : :
1611 : 27 : PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
1612 : : }
1613 : :
1614 : : /*
1615 : : * array_shuffle_n
1616 : : * Return a copy of array with n randomly chosen items.
1617 : : *
1618 : : * The number of items must not exceed the size of the first dimension of the
1619 : : * array. We preserve the first dimension's lower bound if keep_lb,
1620 : : * else it's set to 1. Lower-order dimensions are preserved in any case.
1621 : : *
1622 : : * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
1623 : : * from the system catalogs, given only the elmtyp. However, the caller is
1624 : : * in a better position to cache this info across multiple calls.
1625 : : */
1626 : : static ArrayType *
1627 : 32 : array_shuffle_n(ArrayType *array, int n, bool keep_lb,
1628 : : Oid elmtyp, TypeCacheEntry *typentry)
1629 : : {
1630 : : ArrayType *result;
1631 : : int ndim,
1632 : : *dims,
1633 : : *lbs,
1634 : : nelm,
1635 : : nitem,
1636 : : rdims[MAXDIM],
1637 : : rlbs[MAXDIM];
1638 : : int16 elmlen;
1639 : : bool elmbyval;
1640 : : char elmalign;
1641 : : Datum *elms,
1642 : : *ielms;
1643 : : bool *nuls,
1644 : : *inuls;
1645 : :
1646 : 32 : ndim = ARR_NDIM(array);
1647 : 32 : dims = ARR_DIMS(array);
1648 : 32 : lbs = ARR_LBOUND(array);
1649 : :
1650 : 32 : elmlen = typentry->typlen;
1651 : 32 : elmbyval = typentry->typbyval;
1652 : 32 : elmalign = typentry->typalign;
1653 : :
1654 : : /* If the target array is empty, exit fast */
1655 [ + - + - : 32 : if (ndim < 1 || dims[0] < 1 || n < 1)
- + ]
1656 : 0 : return construct_empty_array(elmtyp);
1657 : :
1658 : 32 : deconstruct_array(array, elmtyp, elmlen, elmbyval, elmalign,
1659 : : &elms, &nuls, &nelm);
1660 : :
1661 : 32 : nitem = dims[0]; /* total number of items */
1662 : 32 : nelm /= nitem; /* number of elements per item */
1663 : :
1664 : : Assert(n <= nitem); /* else it's caller error */
1665 : :
1666 : : /*
1667 : : * Shuffle array using Fisher-Yates algorithm. Scan the array and swap
1668 : : * current item (nelm datums starting at ielms) with a randomly chosen
1669 : : * later item (nelm datums starting at jelms) in each iteration. We can
1670 : : * stop once we've done n iterations; then first n items are the result.
1671 : : */
1672 : 32 : ielms = elms;
1673 : 32 : inuls = nuls;
1674 [ + + ]: 152 : for (int i = 0; i < n; i++)
1675 : : {
1676 : 120 : int j = (int) pg_prng_uint64_range(&pg_global_prng_state, i, nitem - 1) * nelm;
1677 : 120 : Datum *jelms = elms + j;
1678 : 120 : bool *jnuls = nuls + j;
1679 : :
1680 : : /* Swap i'th and j'th items; advance ielms/inuls to next item */
1681 [ + + ]: 328 : for (int k = 0; k < nelm; k++)
1682 : : {
1683 : 208 : Datum elm = *ielms;
1684 : 208 : bool nul = *inuls;
1685 : :
1686 : 208 : *ielms++ = *jelms;
1687 : 208 : *inuls++ = *jnuls;
1688 : 208 : *jelms++ = elm;
1689 : 208 : *jnuls++ = nul;
1690 : : }
1691 : : }
1692 : :
1693 : : /* Set up dimensions of the result */
1694 : 32 : memcpy(rdims, dims, ndim * sizeof(int));
1695 : 32 : memcpy(rlbs, lbs, ndim * sizeof(int));
1696 : 32 : rdims[0] = n;
1697 [ + + ]: 32 : if (!keep_lb)
1698 : 16 : rlbs[0] = 1;
1699 : :
1700 : 32 : result = construct_md_array(elms, nuls, ndim, rdims, rlbs,
1701 : : elmtyp, elmlen, elmbyval, elmalign);
1702 : :
1703 : 32 : pfree(elms);
1704 : 32 : pfree(nuls);
1705 : :
1706 : 32 : return result;
1707 : : }
1708 : :
1709 : : /*
1710 : : * array_shuffle
1711 : : *
1712 : : * Returns an array with the same dimensions as the input array, with its
1713 : : * first-dimension elements in random order.
1714 : : */
1715 : : Datum
1716 : 16 : array_shuffle(PG_FUNCTION_ARGS)
1717 : : {
1718 : 16 : ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);
1719 : : ArrayType *result;
1720 : : Oid elmtyp;
1721 : : TypeCacheEntry *typentry;
1722 : :
1723 : : /*
1724 : : * There is no point in shuffling empty arrays or arrays with less than
1725 : : * two items.
1726 : : */
1727 [ + - - + ]: 16 : if (ARR_NDIM(array) < 1 || ARR_DIMS(array)[0] < 2)
1728 : 0 : PG_RETURN_ARRAYTYPE_P(array);
1729 : :
1730 : 16 : elmtyp = ARR_ELEMTYPE(array);
1731 : 16 : typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
1732 [ - + - - ]: 16 : if (typentry == NULL || typentry->type_id != elmtyp)
1733 : : {
1734 : 16 : typentry = lookup_type_cache(elmtyp, 0);
1735 : 16 : fcinfo->flinfo->fn_extra = typentry;
1736 : : }
1737 : :
1738 : 16 : result = array_shuffle_n(array, ARR_DIMS(array)[0], true, elmtyp, typentry);
1739 : :
1740 : 16 : PG_RETURN_ARRAYTYPE_P(result);
1741 : : }
1742 : :
1743 : : /*
1744 : : * array_sample
1745 : : *
1746 : : * Returns an array of n randomly chosen first-dimension elements
1747 : : * from the input array.
1748 : : */
1749 : : Datum
1750 : 24 : array_sample(PG_FUNCTION_ARGS)
1751 : : {
1752 : 24 : ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);
1753 : 24 : int n = PG_GETARG_INT32(1);
1754 : : ArrayType *result;
1755 : : Oid elmtyp;
1756 : : TypeCacheEntry *typentry;
1757 : : int nitem;
1758 : :
1759 [ + - ]: 24 : nitem = (ARR_NDIM(array) < 1) ? 0 : ARR_DIMS(array)[0];
1760 : :
1761 [ + + + + ]: 24 : if (n < 0 || n > nitem)
1762 [ + - ]: 8 : ereport(ERROR,
1763 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1764 : : errmsg("sample size must be between 0 and %d", nitem)));
1765 : :
1766 : 16 : elmtyp = ARR_ELEMTYPE(array);
1767 : 16 : typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
1768 [ - + - - ]: 16 : if (typentry == NULL || typentry->type_id != elmtyp)
1769 : : {
1770 : 16 : typentry = lookup_type_cache(elmtyp, 0);
1771 : 16 : fcinfo->flinfo->fn_extra = typentry;
1772 : : }
1773 : :
1774 : 16 : result = array_shuffle_n(array, n, false, elmtyp, typentry);
1775 : :
1776 : 16 : PG_RETURN_ARRAYTYPE_P(result);
1777 : : }
1778 : :
1779 : :
1780 : : /*
1781 : : * array_reverse_n
1782 : : * Return a copy of array with reversed items.
1783 : : *
1784 : : * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
1785 : : * from the system catalogs, given only the elmtyp. However, the caller is
1786 : : * in a better position to cache this info across multiple calls.
1787 : : */
1788 : : static ArrayType *
1789 : 15 : array_reverse_n(ArrayType *array, Oid elmtyp, TypeCacheEntry *typentry)
1790 : : {
1791 : : ArrayType *result;
1792 : : int ndim,
1793 : : *dims,
1794 : : *lbs,
1795 : : nelm,
1796 : : nitem,
1797 : : rdims[MAXDIM],
1798 : : rlbs[MAXDIM];
1799 : : int16 elmlen;
1800 : : bool elmbyval;
1801 : : char elmalign;
1802 : : Datum *elms,
1803 : : *ielms;
1804 : : bool *nuls,
1805 : : *inuls;
1806 : :
1807 : 15 : ndim = ARR_NDIM(array);
1808 : 15 : dims = ARR_DIMS(array);
1809 : 15 : lbs = ARR_LBOUND(array);
1810 : :
1811 : 15 : elmlen = typentry->typlen;
1812 : 15 : elmbyval = typentry->typbyval;
1813 : 15 : elmalign = typentry->typalign;
1814 : :
1815 : 15 : deconstruct_array(array, elmtyp, elmlen, elmbyval, elmalign,
1816 : : &elms, &nuls, &nelm);
1817 : :
1818 : 15 : nitem = dims[0]; /* total number of items */
1819 : 15 : nelm /= nitem; /* number of elements per item */
1820 : :
1821 : : /* Reverse the array */
1822 : 15 : ielms = elms;
1823 : 15 : inuls = nuls;
1824 [ + + ]: 45 : for (int i = 0; i < nitem / 2; i++)
1825 : : {
1826 : 30 : int j = (nitem - i - 1) * nelm;
1827 : 30 : Datum *jelms = elms + j;
1828 : 30 : bool *jnuls = nuls + j;
1829 : :
1830 : : /* Swap i'th and j'th items; advance ielms/inuls to next item */
1831 [ + + ]: 70 : for (int k = 0; k < nelm; k++)
1832 : : {
1833 : 40 : Datum elm = *ielms;
1834 : 40 : bool nul = *inuls;
1835 : :
1836 : 40 : *ielms++ = *jelms;
1837 : 40 : *inuls++ = *jnuls;
1838 : 40 : *jelms++ = elm;
1839 : 40 : *jnuls++ = nul;
1840 : : }
1841 : : }
1842 : :
1843 : : /* Set up dimensions of the result */
1844 : 15 : memcpy(rdims, dims, ndim * sizeof(int));
1845 : 15 : memcpy(rlbs, lbs, ndim * sizeof(int));
1846 : 15 : rdims[0] = nitem;
1847 : :
1848 : 15 : result = construct_md_array(elms, nuls, ndim, rdims, rlbs,
1849 : : elmtyp, elmlen, elmbyval, elmalign);
1850 : :
1851 : 15 : pfree(elms);
1852 : 15 : pfree(nuls);
1853 : :
1854 : 15 : return result;
1855 : : }
1856 : :
1857 : : /*
1858 : : * array_reverse
1859 : : *
1860 : : * Returns an array with the same dimensions as the input array, with its
1861 : : * first-dimension elements in reverse order.
1862 : : */
1863 : : Datum
1864 : 25 : array_reverse(PG_FUNCTION_ARGS)
1865 : : {
1866 : 25 : ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);
1867 : : ArrayType *result;
1868 : : Oid elmtyp;
1869 : : TypeCacheEntry *typentry;
1870 : :
1871 : : /*
1872 : : * There is no point in reversing empty arrays or arrays with less than
1873 : : * two items.
1874 : : */
1875 [ + + + + ]: 25 : if (ARR_NDIM(array) < 1 || ARR_DIMS(array)[0] < 2)
1876 : 10 : PG_RETURN_ARRAYTYPE_P(array);
1877 : :
1878 : 15 : elmtyp = ARR_ELEMTYPE(array);
1879 : 15 : typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
1880 [ - + - - ]: 15 : if (typentry == NULL || typentry->type_id != elmtyp)
1881 : : {
1882 : 15 : typentry = lookup_type_cache(elmtyp, 0);
1883 : 15 : fcinfo->flinfo->fn_extra = (void *) typentry;
1884 : : }
1885 : :
1886 : 15 : result = array_reverse_n(array, elmtyp, typentry);
1887 : :
1888 : 15 : PG_RETURN_ARRAYTYPE_P(result);
1889 : : }
1890 : :
1891 : : /*
1892 : : * array_sort
1893 : : *
1894 : : * Sorts the first dimension of the array.
1895 : : */
1896 : : static ArrayType *
1897 : 127 : array_sort_internal(ArrayType *array, bool descending, bool nulls_first,
1898 : : FunctionCallInfo fcinfo)
1899 : : {
1900 : : ArrayType *newarray;
1901 : 127 : Oid collation = PG_GET_COLLATION();
1902 : : int ndim,
1903 : : *dims,
1904 : : *lbs;
1905 : : ArraySortCachedInfo *cache_info;
1906 : : Oid elmtyp;
1907 : : Oid sort_typ;
1908 : : Oid sort_opr;
1909 : : Tuplesortstate *tuplesortstate;
1910 : : ArrayIterator array_iterator;
1911 : : Datum value;
1912 : : bool isnull;
1913 : 127 : ArrayBuildStateAny *astate = NULL;
1914 : :
1915 : 127 : ndim = ARR_NDIM(array);
1916 : 127 : dims = ARR_DIMS(array);
1917 : 127 : lbs = ARR_LBOUND(array);
1918 : :
1919 : : /* Quick exit if we don't need to sort */
1920 [ + + + + ]: 127 : if (ndim < 1 || dims[0] < 2)
1921 : 20 : return array;
1922 : :
1923 : : /* Set up cache area if we didn't already */
1924 : 107 : cache_info = (ArraySortCachedInfo *) fcinfo->flinfo->fn_extra;
1925 [ + - ]: 107 : if (cache_info == NULL)
1926 : : {
1927 : : cache_info = (ArraySortCachedInfo *)
1928 : 107 : MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
1929 : : sizeof(ArraySortCachedInfo));
1930 : 107 : fcinfo->flinfo->fn_extra = cache_info;
1931 : : }
1932 : :
1933 : : /* Fetch and cache required data if we don't have it */
1934 : 107 : elmtyp = ARR_ELEMTYPE(array);
1935 [ + - ]: 107 : if (elmtyp != cache_info->array_meta.element_type)
1936 : : {
1937 : : TypeCacheEntry *typentry;
1938 : :
1939 : 107 : typentry = lookup_type_cache(elmtyp,
1940 : : TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
1941 : 107 : cache_info->array_meta.element_type = elmtyp;
1942 : 107 : cache_info->array_meta.typlen = typentry->typlen;
1943 : 107 : cache_info->array_meta.typbyval = typentry->typbyval;
1944 : 107 : cache_info->array_meta.typalign = typentry->typalign;
1945 : 107 : cache_info->elem_lt_opr = typentry->lt_opr;
1946 : 107 : cache_info->elem_gt_opr = typentry->gt_opr;
1947 : 107 : cache_info->array_type = typentry->typarray;
1948 : : }
1949 : :
1950 : : /* Identify the sort operator to use */
1951 [ + + ]: 107 : if (ndim == 1)
1952 : : {
1953 : : /* Need to sort the element type */
1954 : 73 : sort_typ = elmtyp;
1955 [ + + ]: 73 : sort_opr = (descending ? cache_info->elem_gt_opr : cache_info->elem_lt_opr);
1956 : : }
1957 : : else
1958 : : {
1959 : : /* Otherwise we're sorting arrays */
1960 : 34 : sort_typ = cache_info->array_type;
1961 [ - + ]: 34 : if (!OidIsValid(sort_typ))
1962 [ # # ]: 0 : ereport(ERROR,
1963 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
1964 : : errmsg("could not find array type for data type %s",
1965 : : format_type_be(elmtyp))));
1966 : : /* We know what operators to use for arrays */
1967 [ - + ]: 34 : sort_opr = (descending ? ARRAY_GT_OP : ARRAY_LT_OP);
1968 : : }
1969 : :
1970 : : /*
1971 : : * Fail if we don't know how to sort. The error message is chosen to
1972 : : * match what array_lt()/array_gt() will say in the multidimensional case.
1973 : : */
1974 [ + + ]: 107 : if (!OidIsValid(sort_opr))
1975 [ + - ]: 4 : ereport(ERROR,
1976 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1977 : : errmsg("could not identify a comparison function for type %s",
1978 : : format_type_be(elmtyp)));
1979 : :
1980 : : /* Put the things to be sorted (elements or sub-arrays) into a tuplesort */
1981 : 103 : tuplesortstate = tuplesort_begin_datum(sort_typ,
1982 : : sort_opr,
1983 : : collation,
1984 : : nulls_first,
1985 : : work_mem,
1986 : : NULL,
1987 : : TUPLESORT_NONE);
1988 : :
1989 : 103 : array_iterator = array_create_iterator(array, ndim - 1,
1990 : : &cache_info->array_meta);
1991 [ + + ]: 549 : while (array_iterate(array_iterator, &value, &isnull))
1992 : : {
1993 : 446 : tuplesort_putdatum(tuplesortstate, value, isnull);
1994 : : }
1995 : 103 : array_free_iterator(array_iterator);
1996 : :
1997 : : /* Do the sort */
1998 : 103 : tuplesort_performsort(tuplesortstate);
1999 : :
2000 : : /* Extract results into a new array */
2001 [ + + ]: 537 : while (tuplesort_getdatum(tuplesortstate, true, false, &value, &isnull, NULL))
2002 : : {
2003 : 438 : astate = accumArrayResultAny(astate, value, isnull,
2004 : : sort_typ, CurrentMemoryContext);
2005 : : }
2006 : 99 : tuplesort_end(tuplesortstate);
2007 : :
2008 : 99 : newarray = DatumGetArrayTypeP(makeArrayResultAny(astate,
2009 : : CurrentMemoryContext,
2010 : : true));
2011 : :
2012 : : /* Adjust lower bound to match the input */
2013 : 99 : ARR_LBOUND(newarray)[0] = lbs[0];
2014 : :
2015 : 99 : return newarray;
2016 : : }
2017 : :
2018 : : Datum
2019 : 97 : array_sort(PG_FUNCTION_ARGS)
2020 : : {
2021 : 97 : ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);
2022 : :
2023 : 97 : PG_RETURN_ARRAYTYPE_P(array_sort_internal(array,
2024 : : false,
2025 : : false,
2026 : : fcinfo));
2027 : : }
2028 : :
2029 : : Datum
2030 : 10 : array_sort_order(PG_FUNCTION_ARGS)
2031 : : {
2032 : 10 : ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);
2033 : 10 : bool descending = PG_GETARG_BOOL(1);
2034 : :
2035 : 10 : PG_RETURN_ARRAYTYPE_P(array_sort_internal(array,
2036 : : descending,
2037 : : descending,
2038 : : fcinfo));
2039 : : }
2040 : :
2041 : : Datum
2042 : 20 : array_sort_order_nulls_first(PG_FUNCTION_ARGS)
2043 : : {
2044 : 20 : ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);
2045 : 20 : bool descending = PG_GETARG_BOOL(1);
2046 : 20 : bool nulls_first = PG_GETARG_BOOL(2);
2047 : :
2048 : 20 : PG_RETURN_ARRAYTYPE_P(array_sort_internal(array,
2049 : : descending,
2050 : : nulls_first,
2051 : : fcinfo));
2052 : : }
|