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