Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * arrayfuncs.c
4 : : * Support functions for arrays.
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/utils/adt/arrayfuncs.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include <ctype.h>
18 : : #include <math.h>
19 : :
20 : : #include "access/transam.h"
21 : : #include "catalog/pg_type.h"
22 : : #include "common/int.h"
23 : : #include "funcapi.h"
24 : : #include "libpq/pqformat.h"
25 : : #include "nodes/nodeFuncs.h"
26 : : #include "nodes/supportnodes.h"
27 : : #include "optimizer/optimizer.h"
28 : : #include "parser/scansup.h"
29 : : #include "port/pg_bitutils.h"
30 : : #include "utils/array.h"
31 : : #include "utils/arrayaccess.h"
32 : : #include "utils/builtins.h"
33 : : #include "utils/datum.h"
34 : : #include "utils/fmgroids.h"
35 : : #include "utils/lsyscache.h"
36 : : #include "utils/memutils.h"
37 : : #include "utils/selfuncs.h"
38 : : #include "utils/typcache.h"
39 : :
40 : :
41 : : /*
42 : : * Local definitions
43 : : */
44 : : #define ASSGN "="
45 : :
46 : : #define AARR_FREE_IF_COPY(array,n) \
47 : : do { \
48 : : if (!VARATT_IS_EXPANDED_HEADER(array)) \
49 : : PG_FREE_IF_COPY(array, n); \
50 : : } while (0)
51 : :
52 : : /* ReadArrayToken return type */
53 : : typedef enum
54 : : {
55 : : ATOK_LEVEL_START,
56 : : ATOK_LEVEL_END,
57 : : ATOK_DELIM,
58 : : ATOK_ELEM,
59 : : ATOK_ELEM_NULL,
60 : : ATOK_ERROR,
61 : : } ArrayToken;
62 : :
63 : : /* Working state for array_iterate() */
64 : : typedef struct ArrayIteratorData
65 : : {
66 : : /* basic info about the array, set up during array_create_iterator() */
67 : : ArrayType *arr; /* array we're iterating through */
68 : : uint8 *nullbitmap; /* its null bitmap, if any */
69 : : int nitems; /* total number of elements in array */
70 : : int16 typlen; /* element type's length */
71 : : bool typbyval; /* element type's byval property */
72 : : char typalign; /* element type's align property */
73 : : uint8 typalignby; /* typalign mapped to numeric alignment */
74 : :
75 : : /* information about the requested slice size */
76 : : int slice_ndim; /* slice dimension, or 0 if not slicing */
77 : : int slice_len; /* number of elements per slice */
78 : : int *slice_dims; /* slice dims array */
79 : : int *slice_lbound; /* slice lbound array */
80 : : Datum *slice_values; /* workspace of length slice_len */
81 : : bool *slice_nulls; /* workspace of length slice_len */
82 : :
83 : : /* current position information, updated on each iteration */
84 : : char *data_ptr; /* our current position in the array */
85 : : int current_item; /* the item # we're at in the array */
86 : : } ArrayIteratorData;
87 : :
88 : : static bool ReadArrayDimensions(char **srcptr, int *ndim_p,
89 : : int *dim, int *lBound,
90 : : const char *origStr, Node *escontext);
91 : : static bool ReadDimensionInt(char **srcptr, int *result,
92 : : const char *origStr, Node *escontext);
93 : : static bool ReadArrayStr(char **srcptr,
94 : : FmgrInfo *inputproc, Oid typioparam, int32 typmod,
95 : : char typdelim,
96 : : int typlen, bool typbyval, char typalign,
97 : : int *ndim_p, int *dim,
98 : : int *nitems_p,
99 : : Datum **values_p, bool **nulls_p,
100 : : const char *origStr, Node *escontext);
101 : : static ArrayToken ReadArrayToken(char **srcptr, StringInfo elembuf, char typdelim,
102 : : const char *origStr, Node *escontext);
103 : : static void ReadArrayBinary(StringInfo buf, int nitems,
104 : : FmgrInfo *receiveproc, Oid typioparam, int32 typmod,
105 : : int typlen, bool typbyval, char typalign,
106 : : Datum *values, bool *nulls,
107 : : bool *hasnulls, int32 *nbytes);
108 : : static Datum array_get_element_expanded(Datum arraydatum,
109 : : int nSubscripts, int *indx,
110 : : int arraytyplen,
111 : : int elmlen, bool elmbyval, char elmalign,
112 : : bool *isNull);
113 : : static Datum array_set_element_expanded(Datum arraydatum,
114 : : int nSubscripts, int *indx,
115 : : Datum dataValue, bool isNull,
116 : : int arraytyplen,
117 : : int elmlen, bool elmbyval, char elmalign);
118 : : static bool array_get_isnull(const uint8 *nullbitmap, int offset);
119 : : static void array_set_isnull(uint8 *nullbitmap, int offset, bool isNull);
120 : : static Datum ArrayCast(char *value, bool byval, int len);
121 : : static int ArrayCastAndSet(Datum src,
122 : : int typlen, bool typbyval, uint8 typalignby,
123 : : char *dest);
124 : : static char *array_seek(char *ptr, int offset, uint8 *nullbitmap, int nitems,
125 : : int typlen, bool typbyval, char typalign);
126 : : static int array_nelems_size(char *ptr, int offset, uint8 *nullbitmap,
127 : : int nitems, int typlen, bool typbyval, char typalign);
128 : : static int array_copy(char *destptr, int nitems,
129 : : char *srcptr, int offset, uint8 *nullbitmap,
130 : : int typlen, bool typbyval, char typalign);
131 : : static int array_slice_size(char *arraydataptr, uint8 *arraynullsptr,
132 : : int ndim, int *dim, int *lb,
133 : : int *st, int *endp,
134 : : int typlen, bool typbyval, char typalign);
135 : : static void array_extract_slice(ArrayType *newarray,
136 : : int ndim, int *dim, int *lb,
137 : : char *arraydataptr, uint8 *arraynullsptr,
138 : : int *st, int *endp,
139 : : int typlen, bool typbyval, char typalign);
140 : : static void array_insert_slice(ArrayType *destArray, ArrayType *origArray,
141 : : ArrayType *srcArray,
142 : : int ndim, int *dim, int *lb,
143 : : int *st, int *endp,
144 : : int typlen, bool typbyval, char typalign);
145 : : static int array_cmp(FunctionCallInfo fcinfo);
146 : : static ArrayType *create_array_envelope(int ndims, int *dimv, int *lbsv, int nbytes,
147 : : Oid elmtype, int dataoffset);
148 : : static ArrayType *array_fill_internal(ArrayType *dims, ArrayType *lbs,
149 : : Datum value, bool isnull, Oid elmtype,
150 : : FunctionCallInfo fcinfo);
151 : : static ArrayType *array_replace_internal(ArrayType *array,
152 : : Datum search, bool search_isnull,
153 : : Datum replace, bool replace_isnull,
154 : : bool remove, Oid collation,
155 : : FunctionCallInfo fcinfo);
156 : : static int width_bucket_array_float8(Datum operand, ArrayType *thresholds);
157 : : static int width_bucket_array_fixed(Datum operand,
158 : : ArrayType *thresholds,
159 : : Oid collation,
160 : : TypeCacheEntry *typentry);
161 : : static int width_bucket_array_variable(Datum operand,
162 : : ArrayType *thresholds,
163 : : Oid collation,
164 : : TypeCacheEntry *typentry);
165 : :
166 : :
167 : : /*
168 : : * array_in :
169 : : * converts an array from the external format in "string" to
170 : : * its internal format.
171 : : *
172 : : * return value :
173 : : * the internal representation of the input array
174 : : */
175 : : Datum
176 : 160916 : array_in(PG_FUNCTION_ARGS)
177 : : {
178 : 160916 : char *string = PG_GETARG_CSTRING(0); /* external form */
179 : 160916 : Oid element_type = PG_GETARG_OID(1); /* type of an array
180 : : * element */
181 : 160916 : int32 typmod = PG_GETARG_INT32(2); /* typmod for array elements */
182 : 160916 : Node *escontext = fcinfo->context;
183 : : int typlen;
184 : : bool typbyval;
185 : : char typalign;
186 : : uint8 typalignby;
187 : : char typdelim;
188 : : Oid typioparam;
189 : : char *p;
190 : : int nitems;
191 : : Datum *values;
192 : : bool *nulls;
193 : : bool hasnulls;
194 : : int32 nbytes;
195 : : int32 dataoffset;
196 : : ArrayType *retval;
197 : : int ndim,
198 : : dim[MAXDIM],
199 : : lBound[MAXDIM];
200 : : ArrayMetaState *my_extra;
201 : :
202 : : /*
203 : : * We arrange to look up info about element type, including its input
204 : : * conversion proc, only once per series of calls, assuming the element
205 : : * type doesn't change underneath us.
206 : : */
207 : 160916 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
208 [ + + ]: 160916 : if (my_extra == NULL)
209 : : {
210 : 57729 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
211 : : sizeof(ArrayMetaState));
212 : 57729 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
213 : 57729 : my_extra->element_type = ~element_type;
214 : : }
215 : :
216 [ + + ]: 160916 : if (my_extra->element_type != element_type)
217 : : {
218 : : /*
219 : : * Get info about element type, including its input conversion proc
220 : : */
221 : 57937 : get_type_io_data(element_type, IOFunc_input,
222 : : &my_extra->typlen, &my_extra->typbyval,
223 : : &my_extra->typalign, &my_extra->typdelim,
224 : : &my_extra->typioparam, &my_extra->typiofunc);
225 : 57937 : fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
226 : 57937 : fcinfo->flinfo->fn_mcxt);
227 : 57937 : my_extra->element_type = element_type;
228 : : }
229 : 160916 : typlen = my_extra->typlen;
230 : 160916 : typbyval = my_extra->typbyval;
231 : 160916 : typalign = my_extra->typalign;
232 : 160916 : typalignby = typalign_to_alignby(typalign);
233 : 160916 : typdelim = my_extra->typdelim;
234 : 160916 : typioparam = my_extra->typioparam;
235 : :
236 : : /*
237 : : * Initialize dim[] and lBound[] for ReadArrayStr, in case there is no
238 : : * explicit dimension info. (If there is, ReadArrayDimensions will
239 : : * overwrite this.)
240 : : */
241 [ + + ]: 1126412 : for (int i = 0; i < MAXDIM; i++)
242 : : {
243 : 965496 : dim[i] = -1; /* indicates "not yet known" */
244 : 965496 : lBound[i] = 1; /* default lower bound */
245 : : }
246 : :
247 : : /*
248 : : * Start processing the input string.
249 : : *
250 : : * If the input string starts with dimension info, read and use that.
251 : : * Otherwise, we'll determine the dimensions during ReadArrayStr.
252 : : */
253 : 160916 : p = string;
254 [ - + ]: 160916 : if (!ReadArrayDimensions(&p, &ndim, dim, lBound, string, escontext))
255 : 0 : return (Datum) 0;
256 : :
257 [ + + ]: 160888 : if (ndim == 0)
258 : : {
259 : : /* No array dimensions, so next character should be a left brace */
260 [ + + ]: 160791 : if (*p != '{')
261 [ + + ]: 10 : ereturn(escontext, (Datum) 0,
262 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
263 : : errmsg("malformed array literal: \"%s\"", string),
264 : : errdetail("Array value must start with \"{\" or dimension information.")));
265 : : }
266 : : else
267 : : {
268 : : /* If array dimensions are given, expect '=' operator */
269 [ - + ]: 97 : if (strncmp(p, ASSGN, strlen(ASSGN)) != 0)
270 [ # # ]: 0 : ereturn(escontext, (Datum) 0,
271 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
272 : : errmsg("malformed array literal: \"%s\"", string),
273 : : errdetail("Missing \"%s\" after array dimensions.",
274 : : ASSGN)));
275 : 97 : p += strlen(ASSGN);
276 : : /* Allow whitespace after it */
277 [ - + ]: 97 : while (scanner_isspace(*p))
278 : 0 : p++;
279 : :
280 [ - + ]: 97 : if (*p != '{')
281 [ # # ]: 0 : ereturn(escontext, (Datum) 0,
282 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
283 : : errmsg("malformed array literal: \"%s\"", string),
284 : : errdetail("Array contents must start with \"{\".")));
285 : : }
286 : :
287 : : /* Parse the value part, in the curly braces: { ... } */
288 [ + + ]: 160878 : if (!ReadArrayStr(&p,
289 : : &my_extra->proc, typioparam, typmod,
290 : : typdelim,
291 : : typlen, typbyval, typalign,
292 : : &ndim,
293 : : dim,
294 : : &nitems,
295 : : &values, &nulls,
296 : : string,
297 : : escontext))
298 : 64 : return (Datum) 0;
299 : :
300 : : /* only whitespace is allowed after the closing brace */
301 [ + + ]: 160707 : while (*p)
302 : : {
303 [ + - ]: 8 : if (!scanner_isspace(*p++))
304 [ + - ]: 8 : ereturn(escontext, (Datum) 0,
305 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
306 : : errmsg("malformed array literal: \"%s\"", string),
307 : : errdetail("Junk after closing right brace.")));
308 : : }
309 : :
310 : : /* Empty array? */
311 [ + + ]: 160699 : if (nitems == 0)
312 : 2858 : PG_RETURN_ARRAYTYPE_P(construct_empty_array(element_type));
313 : :
314 : : /*
315 : : * Check for nulls, compute total data space needed
316 : : */
317 : 157841 : hasnulls = false;
318 : 157841 : nbytes = 0;
319 [ + + ]: 915088 : for (int i = 0; i < nitems; i++)
320 : : {
321 [ + + ]: 757247 : if (nulls[i])
322 : 509 : hasnulls = true;
323 : : else
324 : : {
325 : : /* let's just make sure data is not toasted */
326 [ + + ]: 756738 : if (typlen == -1)
327 : 434121 : values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
328 [ + + + + ]: 756738 : nbytes = att_addlength_datum(nbytes, typlen, values[i]);
329 : 756738 : nbytes = att_nominal_alignby(nbytes, typalignby);
330 : : /* check for overflow of total request */
331 [ - + ]: 756738 : if (!AllocSizeIsValid(nbytes))
332 [ # # ]: 0 : ereturn(escontext, (Datum) 0,
333 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
334 : : errmsg("array size exceeds the maximum allowed (%zu)",
335 : : MaxAllocSize)));
336 : : }
337 : : }
338 [ + + ]: 157841 : if (hasnulls)
339 : : {
340 : 460 : dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
341 : 460 : nbytes += dataoffset;
342 : : }
343 : : else
344 : : {
345 : 157381 : dataoffset = 0; /* marker for no null bitmap */
346 : 157381 : nbytes += ARR_OVERHEAD_NONULLS(ndim);
347 : : }
348 : :
349 : : /*
350 : : * Construct the final array datum
351 : : */
352 : 157841 : retval = (ArrayType *) palloc0(nbytes);
353 : 157841 : SET_VARSIZE(retval, nbytes);
354 : 157841 : retval->ndim = ndim;
355 : 157841 : retval->dataoffset = dataoffset;
356 : :
357 : : /*
358 : : * This comes from the array's pg_type.typelem (which points to the base
359 : : * data type's pg_type.oid) and stores system oids in user tables. This
360 : : * oid must be preserved by binary upgrades.
361 : : */
362 : 157841 : retval->elemtype = element_type;
363 : 157841 : memcpy(ARR_DIMS(retval), dim, ndim * sizeof(int));
364 : 157841 : memcpy(ARR_LBOUND(retval), lBound, ndim * sizeof(int));
365 : :
366 : 157841 : CopyArrayEls(retval,
367 : : values, nulls, nitems,
368 : : typlen, typbyval, typalign,
369 : : true);
370 : :
371 : 157841 : pfree(values);
372 : 157841 : pfree(nulls);
373 : :
374 : 157841 : PG_RETURN_ARRAYTYPE_P(retval);
375 : : }
376 : :
377 : : /*
378 : : * ReadArrayDimensions
379 : : * parses the array dimensions part of the input and converts the values
380 : : * to internal format.
381 : : *
382 : : * On entry, *srcptr points to the string to parse. It is advanced to point
383 : : * after whitespace (if any) and dimension info (if any).
384 : : *
385 : : * *ndim_p, dim[], and lBound[] are output variables. They are filled with the
386 : : * number of dimensions (<= MAXDIM), the lengths of each dimension, and the
387 : : * lower subscript bounds, respectively. If no dimension info appears,
388 : : * *ndim_p will be set to zero, and dim[] and lBound[] are unchanged.
389 : : *
390 : : * 'origStr' is the original input string, used only in error messages.
391 : : * If *escontext points to an ErrorSaveContext, details of any error are
392 : : * reported there.
393 : : *
394 : : * Result:
395 : : * true for success, false for failure (if escontext is provided).
396 : : *
397 : : * Note that dim[] and lBound[] are allocated by the caller, and must have
398 : : * MAXDIM elements.
399 : : */
400 : : static bool
401 : 160916 : ReadArrayDimensions(char **srcptr, int *ndim_p, int *dim, int *lBound,
402 : : const char *origStr, Node *escontext)
403 : : {
404 : 160916 : char *p = *srcptr;
405 : : int ndim;
406 : :
407 : : /*
408 : : * Dimension info takes the form of one or more [n] or [m:n] items. This
409 : : * loop iterates once per dimension item.
410 : : */
411 : 160916 : ndim = 0;
412 : : for (;;)
413 : 134 : {
414 : : char *q;
415 : : int ub;
416 : : int i;
417 : :
418 : : /*
419 : : * Note: we currently allow whitespace between, but not within,
420 : : * dimension items.
421 : : */
422 [ + + ]: 161058 : while (scanner_isspace(*p))
423 : 8 : p++;
424 [ + + ]: 161050 : if (*p != '[')
425 : 160888 : break; /* no more dimension items */
426 : 162 : p++;
427 [ - + ]: 162 : if (ndim >= MAXDIM)
428 [ # # ]: 0 : ereturn(escontext, false,
429 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
430 : : errmsg("number of array dimensions exceeds the maximum allowed (%d)",
431 : : MAXDIM)));
432 : :
433 : 162 : q = p;
434 [ - + ]: 162 : if (!ReadDimensionInt(&p, &i, origStr, escontext))
435 : 0 : return false;
436 [ + + ]: 154 : if (p == q) /* no digits? */
437 [ + - ]: 4 : ereturn(escontext, false,
438 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
439 : : errmsg("malformed array literal: \"%s\"", origStr),
440 : : errdetail("\"[\" must introduce explicitly-specified array dimensions.")));
441 : :
442 [ + + ]: 150 : if (*p == ':')
443 : : {
444 : : /* [m:n] format */
445 : 142 : lBound[ndim] = i;
446 : 142 : p++;
447 : 142 : q = p;
448 [ - + ]: 142 : if (!ReadDimensionInt(&p, &ub, origStr, escontext))
449 : 0 : return false;
450 [ + + ]: 142 : if (p == q) /* no digits? */
451 [ + - ]: 4 : ereturn(escontext, false,
452 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
453 : : errmsg("malformed array literal: \"%s\"", origStr),
454 : : errdetail("Missing array dimension value.")));
455 : : }
456 : : else
457 : : {
458 : : /* [n] format */
459 : 8 : lBound[ndim] = 1;
460 : 8 : ub = i;
461 : : }
462 [ - + ]: 146 : if (*p != ']')
463 [ # # ]: 0 : ereturn(escontext, false,
464 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
465 : : errmsg("malformed array literal: \"%s\"", origStr),
466 : : errdetail("Missing \"%s\" after array dimensions.",
467 : : "]")));
468 : 146 : p++;
469 : :
470 : : /*
471 : : * Note: we could accept ub = lb-1 to represent a zero-length
472 : : * dimension. However, that would result in an empty array, for which
473 : : * we don't keep any dimension data, so that e.g. [1:0] and [101:100]
474 : : * would be equivalent. Given the lack of field demand, there seems
475 : : * little point in allowing such cases.
476 : : */
477 [ + + ]: 146 : if (ub < lBound[ndim])
478 [ + - ]: 8 : ereturn(escontext, false,
479 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
480 : : errmsg("upper bound cannot be less than lower bound")));
481 : :
482 : : /* Upper bound of INT_MAX must be disallowed, cf ArrayCheckBounds() */
483 [ + + ]: 138 : if (ub == INT_MAX)
484 [ + - ]: 4 : ereturn(escontext, false,
485 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
486 : : errmsg("array upper bound is too large: %d", ub)));
487 : :
488 : : /* Compute "ub - lBound[ndim] + 1", detecting overflow */
489 [ + - - + ]: 268 : if (pg_sub_s32_overflow(ub, lBound[ndim], &ub) ||
490 : 134 : pg_add_s32_overflow(ub, 1, &ub))
491 [ # # ]: 0 : ereturn(escontext, false,
492 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
493 : : errmsg("array size exceeds the maximum allowed (%zu)",
494 : : MaxArraySize)));
495 : :
496 : 134 : dim[ndim] = ub;
497 : 134 : ndim++;
498 : : }
499 : :
500 : 160888 : *srcptr = p;
501 : 160888 : *ndim_p = ndim;
502 : 160888 : return true;
503 : : }
504 : :
505 : : /*
506 : : * ReadDimensionInt
507 : : * parse an integer, for the array dimensions
508 : : *
509 : : * On entry, *srcptr points to the string to parse. It is advanced past the
510 : : * digits of the integer. If there are no digits, returns true and leaves
511 : : * *srcptr unchanged.
512 : : *
513 : : * Result:
514 : : * true for success, false for failure (if escontext is provided).
515 : : * On success, the parsed integer is returned in *result.
516 : : */
517 : : static bool
518 : 304 : ReadDimensionInt(char **srcptr, int *result,
519 : : const char *origStr, Node *escontext)
520 : : {
521 : 304 : char *p = *srcptr;
522 : : long l;
523 : :
524 : : /* don't accept leading whitespace */
525 [ + + + + : 304 : if (!isdigit((unsigned char) *p) && *p != '-' && *p != '+')
+ - ]
526 : : {
527 : 8 : *result = 0;
528 : 8 : return true;
529 : : }
530 : :
531 : 296 : errno = 0;
532 : 296 : l = strtol(p, srcptr, 10);
533 : :
534 [ + - + + : 296 : if (errno == ERANGE || l > PG_INT32_MAX || l < PG_INT32_MIN)
+ + ]
535 [ + - ]: 8 : ereturn(escontext, false,
536 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
537 : : errmsg("array bound is out of integer range")));
538 : :
539 : 288 : *result = (int) l;
540 : 288 : return true;
541 : : }
542 : :
543 : : /*
544 : : * ReadArrayStr :
545 : : * parses the array string pointed to by *srcptr and converts the values
546 : : * to internal format. Determines the array dimensions as it goes.
547 : : *
548 : : * On entry, *srcptr points to the string to parse (it must point to a '{').
549 : : * On successful return, it is advanced to point past the closing '}'.
550 : : *
551 : : * If dimensions were specified explicitly, they are passed in *ndim_p and
552 : : * dim[]. This function will check that the array values match the specified
553 : : * dimensions. If dimensions were not given, caller must pass *ndim_p == 0
554 : : * and initialize all elements of dim[] to -1. Then this function will
555 : : * deduce the dimensions from the structure of the input and store them in
556 : : * *ndim_p and the dim[] array.
557 : : *
558 : : * Element type information:
559 : : * inputproc: type-specific input procedure for element datatype.
560 : : * typioparam, typmod: auxiliary values to pass to inputproc.
561 : : * typdelim: the value delimiter (type-specific).
562 : : * typlen, typbyval, typalign: storage parameters of element datatype.
563 : : *
564 : : * Outputs:
565 : : * *ndim_p, dim: dimensions deduced from the input structure.
566 : : * *nitems_p: total number of elements.
567 : : * *values_p[]: palloc'd array, filled with converted data values.
568 : : * *nulls_p[]: palloc'd array, filled with is-null markers.
569 : : *
570 : : * 'origStr' is the original input string, used only in error messages.
571 : : * If *escontext points to an ErrorSaveContext, details of any error are
572 : : * reported there.
573 : : *
574 : : * Result:
575 : : * true for success, false for failure (if escontext is provided).
576 : : */
577 : : static bool
578 : 160878 : ReadArrayStr(char **srcptr,
579 : : FmgrInfo *inputproc,
580 : : Oid typioparam,
581 : : int32 typmod,
582 : : char typdelim,
583 : : int typlen,
584 : : bool typbyval,
585 : : char typalign,
586 : : int *ndim_p,
587 : : int *dim,
588 : : int *nitems_p,
589 : : Datum **values_p,
590 : : bool **nulls_p,
591 : : const char *origStr,
592 : : Node *escontext)
593 : : {
594 : 160878 : int ndim = *ndim_p;
595 : 160878 : bool dimensions_specified = (ndim != 0);
596 : : int maxitems;
597 : : Datum *values;
598 : : bool *nulls;
599 : : StringInfoData elembuf;
600 : : int nest_level;
601 : : int nitems;
602 : : bool ndim_frozen;
603 : : bool expect_delim;
604 : : int nelems[MAXDIM];
605 : :
606 : : /* Allocate some starting output workspace; we'll enlarge as needed */
607 : 160878 : maxitems = 16;
608 : 160878 : values = palloc_array(Datum, maxitems);
609 : 160878 : nulls = palloc_array(bool, maxitems);
610 : :
611 : : /* Allocate workspace to hold (string representation of) one element */
612 : 160878 : initStringInfo(&elembuf);
613 : :
614 : : /* Loop below assumes first token is ATOK_LEVEL_START */
615 : : Assert(**srcptr == '{');
616 : :
617 : : /* Parse tokens until we reach the matching right brace */
618 : 160878 : nest_level = 0;
619 : 160878 : nitems = 0;
620 : 160878 : ndim_frozen = dimensions_specified;
621 : 160878 : expect_delim = false;
622 : : do
623 : : {
624 : : ArrayToken tok;
625 : :
626 : 1680895 : tok = ReadArrayToken(srcptr, &elembuf, typdelim, origStr, escontext);
627 : :
628 [ + + + + : 1680875 : switch (tok)
+ - ]
629 : : {
630 : 162073 : case ATOK_LEVEL_START:
631 : : /* Can't write left brace where delim is expected */
632 [ + + ]: 162073 : if (expect_delim)
633 [ + - ]: 4 : ereturn(escontext, false,
634 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
635 : : errmsg("malformed array literal: \"%s\"", origStr),
636 : : errdetail("Unexpected \"%c\" character.", '{')));
637 : :
638 : : /* Initialize element counting in the new level */
639 [ + + ]: 162069 : if (nest_level >= MAXDIM)
640 [ + - ]: 1 : ereturn(escontext, false,
641 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
642 : : errmsg("number of array dimensions exceeds the maximum allowed (%d)",
643 : : MAXDIM)));
644 : :
645 : 162068 : nelems[nest_level] = 0;
646 : 162068 : nest_level++;
647 [ + + ]: 162068 : if (nest_level > ndim)
648 : : {
649 : : /* Can't increase ndim once it's frozen */
650 [ + + ]: 161180 : if (ndim_frozen)
651 : 8 : goto dimension_error;
652 : 161172 : ndim = nest_level;
653 : : }
654 : 162060 : break;
655 : :
656 : 161875 : case ATOK_LEVEL_END:
657 : : /* Can't get here with nest_level == 0 */
658 : : Assert(nest_level > 0);
659 : :
660 : : /*
661 : : * We allow a right brace to terminate an empty sub-array,
662 : : * otherwise it must occur where we expect a delimiter.
663 : : */
664 [ + + + + ]: 161875 : if (nelems[nest_level - 1] > 0 && !expect_delim)
665 [ + - ]: 16 : ereturn(escontext, false,
666 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
667 : : errmsg("malformed array literal: \"%s\"", origStr),
668 : : errdetail("Unexpected \"%c\" character.",
669 : : '}')));
670 : 161859 : nest_level--;
671 : : /* Nested sub-arrays count as elements of outer level */
672 [ + + ]: 161859 : if (nest_level > 0)
673 : 1148 : nelems[nest_level - 1]++;
674 : :
675 : : /*
676 : : * Note: if we had dimensionality info, then dim[nest_level]
677 : : * is initially non-negative, and we'll check each sub-array's
678 : : * length against that.
679 : : */
680 [ + + ]: 161859 : if (dim[nest_level] < 0)
681 : : {
682 : : /* Save length of first sub-array of this level */
683 : 160979 : dim[nest_level] = nelems[nest_level];
684 : : }
685 [ + + ]: 880 : else if (nelems[nest_level] != dim[nest_level])
686 : : {
687 : : /* Subsequent sub-arrays must have same length */
688 : 21 : goto dimension_error;
689 : : }
690 : :
691 : : /*
692 : : * Must have a delim or another right brace following, unless
693 : : * we have reached nest_level 0, where this won't matter.
694 : : */
695 : 161838 : expect_delim = true;
696 : 161838 : break;
697 : :
698 : 599496 : case ATOK_DELIM:
699 [ + + ]: 599496 : if (!expect_delim)
700 [ + - ]: 4 : ereturn(escontext, false,
701 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
702 : : errmsg("malformed array literal: \"%s\"", origStr),
703 : : errdetail("Unexpected \"%c\" character.",
704 : : typdelim)));
705 : 599492 : expect_delim = false;
706 : 599492 : break;
707 : :
708 : 757427 : case ATOK_ELEM:
709 : : case ATOK_ELEM_NULL:
710 : : /* Can't get here with nest_level == 0 */
711 : : Assert(nest_level > 0);
712 : :
713 : : /* Disallow consecutive ELEM tokens */
714 [ + + ]: 757427 : if (expect_delim)
715 [ + - ]: 4 : ereturn(escontext, false,
716 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
717 : : errmsg("malformed array literal: \"%s\"", origStr),
718 : : errdetail("Unexpected array element.")));
719 : :
720 : : /* Enlarge the values/nulls arrays if needed */
721 [ + + ]: 757423 : if (nitems >= maxitems)
722 : : {
723 [ - + ]: 3459 : if (maxitems >= MaxArraySize)
724 [ # # ]: 0 : ereturn(escontext, false,
725 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
726 : : errmsg("array size exceeds the maximum allowed (%zu)",
727 : : MaxArraySize)));
728 [ + - ]: 3459 : maxitems = Min(maxitems * 2, MaxArraySize);
729 : 3459 : values = repalloc_array(values, Datum, maxitems);
730 : 3459 : nulls = repalloc_array(nulls, bool, maxitems);
731 : : }
732 : :
733 : : /* Read the element's value, or check that NULL is allowed */
734 [ + + ]: 757423 : if (!InputFunctionCallSafe(inputproc,
735 : : (tok == ATOK_ELEM_NULL) ? NULL : elembuf.data,
736 : : typioparam, typmod,
737 : : escontext,
738 [ + + ]: 757423 : &values[nitems]))
739 : 60 : return false;
740 : 757342 : nulls[nitems] = (tok == ATOK_ELEM_NULL);
741 : 757342 : nitems++;
742 : :
743 : : /*
744 : : * Once we have found an element, the number of dimensions can
745 : : * no longer increase, and subsequent elements must all be at
746 : : * the same nesting depth.
747 : : */
748 : 757342 : ndim_frozen = true;
749 [ + + ]: 757342 : if (nest_level != ndim)
750 : 8 : goto dimension_error;
751 : : /* Count the new element */
752 : 757334 : nelems[nest_level - 1]++;
753 : :
754 : : /* Must have a delim or a right brace following */
755 : 757334 : expect_delim = true;
756 : 757334 : break;
757 : :
758 : 4 : case ATOK_ERROR:
759 : 4 : return false;
760 : : }
761 [ + + ]: 1680724 : } while (nest_level > 0);
762 : :
763 : : /* Clean up and return results */
764 : 160707 : pfree(elembuf.data);
765 : :
766 : 160707 : *ndim_p = ndim;
767 : 160707 : *nitems_p = nitems;
768 : 160707 : *values_p = values;
769 : 160707 : *nulls_p = nulls;
770 : 160707 : return true;
771 : :
772 : 37 : dimension_error:
773 [ + + ]: 37 : if (dimensions_specified)
774 [ + - ]: 4 : ereturn(escontext, false,
775 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
776 : : errmsg("malformed array literal: \"%s\"", origStr),
777 : : errdetail("Specified array dimensions do not match array contents.")));
778 : : else
779 [ + - ]: 33 : ereturn(escontext, false,
780 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
781 : : errmsg("malformed array literal: \"%s\"", origStr),
782 : : errdetail("Multidimensional arrays must have sub-arrays with matching dimensions.")));
783 : : }
784 : :
785 : : /*
786 : : * ReadArrayToken
787 : : * read one token from an array value string
788 : : *
789 : : * Starts scanning from *srcptr. On non-error return, *srcptr is
790 : : * advanced past the token.
791 : : *
792 : : * If the token is ATOK_ELEM, the de-escaped string is returned in elembuf.
793 : : */
794 : : static ArrayToken
795 : 1680895 : ReadArrayToken(char **srcptr, StringInfo elembuf, char typdelim,
796 : : const char *origStr, Node *escontext)
797 : : {
798 : 1680895 : char *p = *srcptr;
799 : : int dstlen;
800 : : bool has_escapes;
801 : :
802 : 1680895 : resetStringInfo(elembuf);
803 : :
804 : : /* Identify token type. Loop advances over leading whitespace. */
805 : : for (;;)
806 : : {
807 [ - + + + : 1697910 : switch (*p)
+ ]
808 : : {
809 : 0 : case '\0':
810 : 0 : goto ending_error;
811 : 162073 : case '{':
812 : 162073 : *srcptr = p + 1;
813 : 162073 : return ATOK_LEVEL_START;
814 : 161875 : case '}':
815 : 161875 : *srcptr = p + 1;
816 : 161875 : return ATOK_LEVEL_END;
817 : 341319 : case '"':
818 : 341319 : p++;
819 : 341319 : goto quoted_element;
820 : 1032643 : default:
821 [ + + ]: 1032643 : if (*p == typdelim)
822 : : {
823 : 599496 : *srcptr = p + 1;
824 : 599496 : return ATOK_DELIM;
825 : : }
826 [ + + ]: 433147 : if (scanner_isspace(*p))
827 : : {
828 : 17015 : p++;
829 : 17015 : continue;
830 : : }
831 : 416132 : goto unquoted_element;
832 : : }
833 : : }
834 : :
835 : 341319 : quoted_element:
836 : : for (;;)
837 : : {
838 [ - + + + ]: 2580778 : switch (*p)
839 : : {
840 : 0 : case '\0':
841 : 0 : goto ending_error;
842 : 714 : case '\\':
843 : : /* Skip backslash, copy next character as-is. */
844 : 714 : p++;
845 [ - + ]: 714 : if (*p == '\0')
846 : 0 : goto ending_error;
847 : 714 : appendStringInfoChar(elembuf, *p++);
848 : 714 : break;
849 : 341319 : case '"':
850 : :
851 : : /*
852 : : * If next non-whitespace isn't typdelim or a brace, complain
853 : : * about incorrect quoting. While we could leave such cases
854 : : * to be detected as incorrect token sequences, the resulting
855 : : * message wouldn't be as helpful. (We could also give the
856 : : * incorrect-quoting error when next is '{', but treating that
857 : : * as a token sequence error seems better.)
858 : : */
859 [ + - ]: 341343 : while (*(++p) != '\0')
860 : : {
861 [ + + + + : 341343 : if (*p == typdelim || *p == '}' || *p == '{')
+ + ]
862 : : {
863 : 341307 : *srcptr = p;
864 : 341307 : return ATOK_ELEM;
865 : : }
866 [ + + ]: 36 : if (!scanner_isspace(*p))
867 [ + - ]: 12 : ereturn(escontext, ATOK_ERROR,
868 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
869 : : errmsg("malformed array literal: \"%s\"", origStr),
870 : : errdetail("Incorrectly quoted array element.")));
871 : : }
872 : 0 : goto ending_error;
873 : 2238745 : default:
874 : 2238745 : appendStringInfoChar(elembuf, *p++);
875 : 2238745 : break;
876 : : }
877 : : }
878 : :
879 : 416132 : unquoted_element:
880 : :
881 : : /*
882 : : * We don't include trailing whitespace in the result. dstlen tracks how
883 : : * much of the output string is known to not be trailing whitespace.
884 : : */
885 : 416132 : dstlen = 0;
886 : 416132 : has_escapes = false;
887 : : for (;;)
888 : : {
889 [ + + + + : 2360319 : switch (*p)
+ ]
890 : : {
891 : 4 : case '\0':
892 : 4 : goto ending_error;
893 : 4 : case '{':
894 [ + - ]: 4 : ereturn(escontext, ATOK_ERROR,
895 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
896 : : errmsg("malformed array literal: \"%s\"", origStr),
897 : : errdetail("Unexpected \"%c\" character.",
898 : : '{')));
899 : 4 : case '"':
900 : : /* Must double-quote all or none of an element. */
901 [ + - ]: 4 : ereturn(escontext, ATOK_ERROR,
902 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
903 : : errmsg("malformed array literal: \"%s\"", origStr),
904 : : errdetail("Incorrectly quoted array element.")));
905 : 16 : case '\\':
906 : : /* Skip backslash, copy next character as-is. */
907 : 16 : p++;
908 [ - + ]: 16 : if (*p == '\0')
909 : 0 : goto ending_error;
910 : 16 : appendStringInfoChar(elembuf, *p++);
911 : 16 : dstlen = elembuf->len; /* treat it as non-whitespace */
912 : 16 : has_escapes = true;
913 : 16 : break;
914 : 2360291 : default:
915 : : /* End of elem? */
916 [ + + + + ]: 2360291 : if (*p == typdelim || *p == '}')
917 : : {
918 : : /* hack: truncate the output string to dstlen */
919 : 416120 : elembuf->data[dstlen] = '\0';
920 : 416120 : elembuf->len = dstlen;
921 : 416120 : *srcptr = p;
922 : : /* Check if it's unquoted "NULL" */
923 [ + + + + ]: 832224 : if (!has_escapes &&
924 : 416104 : pg_strcasecmp(elembuf->data, "NULL") == 0)
925 : 509 : return ATOK_ELEM_NULL;
926 : : else
927 : 415611 : return ATOK_ELEM;
928 : : }
929 : 1944171 : appendStringInfoChar(elembuf, *p);
930 [ + + ]: 1944171 : if (!scanner_isspace(*p))
931 : 1943587 : dstlen = elembuf->len;
932 : 1944171 : p++;
933 : 1944171 : break;
934 : : }
935 : : }
936 : :
937 : 4 : ending_error:
938 [ - + ]: 4 : ereturn(escontext, ATOK_ERROR,
939 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
940 : : errmsg("malformed array literal: \"%s\"", origStr),
941 : : errdetail("Unexpected end of input.")));
942 : : }
943 : :
944 : : /*
945 : : * Copy data into an array object from a temporary array of Datums.
946 : : *
947 : : * array: array object (with header fields already filled in)
948 : : * values: array of Datums to be copied
949 : : * nulls: array of is-null flags (can be NULL if no nulls)
950 : : * nitems: number of Datums to be copied
951 : : * typbyval, typlen, typalign: info about element datatype
952 : : * freedata: if true and element type is pass-by-ref, pfree data values
953 : : * referenced by Datums after copying them.
954 : : *
955 : : * If the input data is of varlena type, the caller must have ensured that
956 : : * the values are not toasted. (Doing it here doesn't work since the
957 : : * caller has already allocated space for the array...)
958 : : */
959 : : void
960 : 1166590 : CopyArrayEls(ArrayType *array,
961 : : const Datum *values,
962 : : const bool *nulls,
963 : : int nitems,
964 : : int typlen,
965 : : bool typbyval,
966 : : char typalign,
967 : : bool freedata)
968 : : {
969 [ + + ]: 1166590 : char *p = ARR_DATA_PTR(array);
970 [ + + ]: 1166590 : uint8 *bitmap = ARR_NULLBITMAP(array);
971 : 1166590 : int bitval = 0;
972 : 1166590 : int bitmask = 1;
973 : 1166590 : uint8 typalignby = typalign_to_alignby(typalign);
974 : : int i;
975 : :
976 [ + + ]: 1166590 : if (typbyval)
977 : 772478 : freedata = false;
978 : :
979 [ + + ]: 8326461 : for (i = 0; i < nitems; i++)
980 : : {
981 [ + + + + ]: 7159871 : if (nulls && nulls[i])
982 : : {
983 [ - + ]: 22721 : if (!bitmap) /* shouldn't happen */
984 [ # # ]: 0 : elog(ERROR, "null array element where not supported");
985 : : /* bitmap bit stays 0 */
986 : : }
987 : : else
988 : : {
989 : 7137150 : bitval |= bitmask;
990 : 7137150 : p += ArrayCastAndSet(values[i], typlen, typbyval, typalignby, p);
991 [ + + ]: 7137150 : if (freedata)
992 : 446004 : pfree(DatumGetPointer(values[i]));
993 : : }
994 [ + + ]: 7159871 : if (bitmap)
995 : : {
996 : 525304 : bitmask <<= 1;
997 [ + + ]: 525304 : if (bitmask == 0x100)
998 : : {
999 : 63479 : *bitmap++ = bitval;
1000 : 63479 : bitval = 0;
1001 : 63479 : bitmask = 1;
1002 : : }
1003 : : }
1004 : : }
1005 : :
1006 [ + + + + ]: 1166590 : if (bitmap && bitmask != 1)
1007 : 12336 : *bitmap = bitval;
1008 : 1166590 : }
1009 : :
1010 : : /*
1011 : : * array_out :
1012 : : * takes the internal representation of an array and returns a string
1013 : : * containing the array in its external format.
1014 : : */
1015 : : Datum
1016 : 453642 : array_out(PG_FUNCTION_ARGS)
1017 : : {
1018 : 453642 : AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
1019 [ + + ]: 453642 : Oid element_type = AARR_ELEMTYPE(v);
1020 : : int typlen;
1021 : : bool typbyval;
1022 : : char typalign;
1023 : : char typdelim;
1024 : : char *p,
1025 : : *tmp,
1026 : : *retval,
1027 : : **values,
1028 : : dims_str[(MAXDIM * 33) + 2];
1029 : :
1030 : : /*
1031 : : * 33 per dim since we assume 15 digits per number + ':' +'[]'
1032 : : *
1033 : : * +2 allows for assignment operator + trailing null
1034 : : */
1035 : : bool *needquotes,
1036 : 453642 : needdims = false;
1037 : : size_t overall_length;
1038 : : int nitems,
1039 : : i,
1040 : : j,
1041 : : k,
1042 : : indx[MAXDIM];
1043 : : int ndim,
1044 : : *dims,
1045 : : *lb;
1046 : : array_iter iter;
1047 : : ArrayMetaState *my_extra;
1048 : :
1049 : : /*
1050 : : * We arrange to look up info about element type, including its output
1051 : : * conversion proc, only once per series of calls, assuming the element
1052 : : * type doesn't change underneath us.
1053 : : */
1054 : 453642 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1055 [ + + ]: 453642 : if (my_extra == NULL)
1056 : : {
1057 : 16924 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1058 : : sizeof(ArrayMetaState));
1059 : 16924 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1060 : 16924 : my_extra->element_type = ~element_type;
1061 : : }
1062 : :
1063 [ + + ]: 453642 : if (my_extra->element_type != element_type)
1064 : : {
1065 : : /*
1066 : : * Get info about element type, including its output conversion proc
1067 : : */
1068 : 19261 : get_type_io_data(element_type, IOFunc_output,
1069 : : &my_extra->typlen, &my_extra->typbyval,
1070 : : &my_extra->typalign, &my_extra->typdelim,
1071 : : &my_extra->typioparam, &my_extra->typiofunc);
1072 : 19261 : fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
1073 : 19261 : fcinfo->flinfo->fn_mcxt);
1074 : 19261 : my_extra->element_type = element_type;
1075 : : }
1076 : 453642 : typlen = my_extra->typlen;
1077 : 453642 : typbyval = my_extra->typbyval;
1078 : 453642 : typalign = my_extra->typalign;
1079 : 453642 : typdelim = my_extra->typdelim;
1080 : :
1081 [ + + ]: 453642 : ndim = AARR_NDIM(v);
1082 [ + + ]: 453642 : dims = AARR_DIMS(v);
1083 [ + + ]: 453642 : lb = AARR_LBOUND(v);
1084 : 453642 : nitems = ArrayGetNItems(ndim, dims);
1085 : :
1086 [ + + ]: 453642 : if (nitems == 0)
1087 : : {
1088 : 2109 : retval = pstrdup("{}");
1089 : 2109 : PG_RETURN_CSTRING(retval);
1090 : : }
1091 : :
1092 : : /*
1093 : : * we will need to add explicit dimensions if any dimension has a lower
1094 : : * bound other than one
1095 : : */
1096 [ + + ]: 903538 : for (i = 0; i < ndim; i++)
1097 : : {
1098 [ + + ]: 452207 : if (lb[i] != 1)
1099 : : {
1100 : 202 : needdims = true;
1101 : 202 : break;
1102 : : }
1103 : : }
1104 : :
1105 : : /*
1106 : : * Convert all values to string form, count total space needed (including
1107 : : * any overhead such as escaping backslashes), and detect whether each
1108 : : * item needs double quotes.
1109 : : */
1110 : 451533 : values = palloc_array(char *, nitems);
1111 : 451533 : needquotes = palloc_array(bool, nitems);
1112 : 451533 : overall_length = 0;
1113 : :
1114 : 451533 : array_iter_setup(&iter, v, typlen, typbyval, typalign);
1115 : :
1116 [ + + ]: 1746966 : for (i = 0; i < nitems; i++)
1117 : : {
1118 : : Datum itemvalue;
1119 : : bool isnull;
1120 : : bool needquote;
1121 : :
1122 : : /* Get source element, checking for NULL */
1123 : 1295453 : itemvalue = array_iter_next(&iter, &isnull, i);
1124 : :
1125 [ + + ]: 1295453 : if (isnull)
1126 : : {
1127 : 1544 : values[i] = pstrdup("NULL");
1128 : 1544 : overall_length += 4;
1129 : 1544 : needquote = false;
1130 : : }
1131 : : else
1132 : : {
1133 : 1293909 : values[i] = OutputFunctionCall(&my_extra->proc, itemvalue);
1134 : :
1135 : : /* count data plus backslashes; detect chars needing quotes */
1136 [ + + ]: 1293889 : if (values[i][0] == '\0')
1137 : 318 : needquote = true; /* force quotes for empty string */
1138 [ + + ]: 1293571 : else if (pg_strcasecmp(values[i], "NULL") == 0)
1139 : 12 : needquote = true; /* force quotes for literal NULL */
1140 : : else
1141 : 1293559 : needquote = false;
1142 : :
1143 [ + + ]: 18256169 : for (tmp = values[i]; *tmp != '\0'; tmp++)
1144 : : {
1145 : 16962280 : char ch = *tmp;
1146 : :
1147 : 16962280 : overall_length += 1;
1148 [ + + + + ]: 16962280 : if (ch == '"' || ch == '\\')
1149 : : {
1150 : 2520 : needquote = true;
1151 : 2520 : overall_length += 1;
1152 : : }
1153 [ + + + + : 33888389 : else if (ch == '{' || ch == '}' || ch == typdelim ||
+ + + + ]
1154 : 16928629 : scanner_isspace(ch))
1155 : 126596 : needquote = true;
1156 : : }
1157 : : }
1158 : :
1159 : 1295433 : needquotes[i] = needquote;
1160 : :
1161 : : /* Count the pair of double quotes, if needed */
1162 [ + + ]: 1295433 : if (needquote)
1163 : 16391 : overall_length += 2;
1164 : : /* and the comma (or other typdelim delimiter) */
1165 : 1295433 : overall_length += 1;
1166 : : }
1167 : :
1168 : : /*
1169 : : * The very last array element doesn't have a typdelim delimiter after it,
1170 : : * but that's OK; that space is needed for the trailing '\0'.
1171 : : *
1172 : : * Now count total number of curly brace pairs in output string.
1173 : : */
1174 [ + + ]: 903744 : for (i = j = 0, k = 1; i < ndim; i++)
1175 : : {
1176 : 452231 : j += k, k *= dims[i];
1177 : : }
1178 : 451513 : overall_length += 2 * j;
1179 : :
1180 : : /* Format explicit dimensions if required */
1181 : 451513 : dims_str[0] = '\0';
1182 [ + + ]: 451513 : if (needdims)
1183 : : {
1184 : 202 : char *ptr = dims_str;
1185 : :
1186 [ + + ]: 449 : for (i = 0; i < ndim; i++)
1187 : : {
1188 : 247 : sprintf(ptr, "[%d:%d]", lb[i], lb[i] + dims[i] - 1);
1189 : 247 : ptr += strlen(ptr);
1190 : : }
1191 : 202 : *ptr++ = *ASSGN;
1192 : 202 : *ptr = '\0';
1193 : 202 : overall_length += ptr - dims_str;
1194 : : }
1195 : :
1196 : : /* Now construct the output string */
1197 : 451513 : retval = (char *) palloc(overall_length);
1198 : 451513 : p = retval;
1199 : :
1200 : : #define APPENDSTR(str) (strcpy(p, (str)), p += strlen(p))
1201 : : #define APPENDCHAR(ch) (*p++ = (ch), *p = '\0')
1202 : :
1203 [ + + ]: 451513 : if (needdims)
1204 : 202 : APPENDSTR(dims_str);
1205 : 451513 : APPENDCHAR('{');
1206 [ + + ]: 903744 : for (i = 0; i < ndim; i++)
1207 : 452231 : indx[i] = 0;
1208 : 451513 : j = 0;
1209 : 451513 : k = 0;
1210 : : do
1211 : : {
1212 [ + + ]: 1300664 : for (i = j; i < ndim - 1; i++)
1213 : 5231 : APPENDCHAR('{');
1214 : :
1215 [ + + ]: 1295433 : if (needquotes[k])
1216 : : {
1217 : 16391 : APPENDCHAR('"');
1218 [ + + ]: 680712 : for (tmp = values[k]; *tmp; tmp++)
1219 : : {
1220 : 664321 : char ch = *tmp;
1221 : :
1222 [ + + + + ]: 664321 : if (ch == '"' || ch == '\\')
1223 : 2520 : *p++ = '\\';
1224 : 664321 : *p++ = ch;
1225 : : }
1226 : 16391 : *p = '\0';
1227 : 16391 : APPENDCHAR('"');
1228 : : }
1229 : : else
1230 : 1279042 : APPENDSTR(values[k]);
1231 : 1295433 : pfree(values[k++]);
1232 : :
1233 [ + + ]: 1752177 : for (i = ndim - 1; i >= 0; i--)
1234 : : {
1235 [ + + ]: 1300664 : if (++(indx[i]) < dims[i])
1236 : : {
1237 : 843920 : APPENDCHAR(typdelim);
1238 : 843920 : break;
1239 : : }
1240 : : else
1241 : : {
1242 : 456744 : indx[i] = 0;
1243 : 456744 : APPENDCHAR('}');
1244 : : }
1245 : : }
1246 : 1295433 : j = i;
1247 [ + + ]: 1295433 : } while (j != -1);
1248 : :
1249 : : #undef APPENDSTR
1250 : : #undef APPENDCHAR
1251 : :
1252 : : /* Assert that we calculated the string length accurately */
1253 : : Assert(overall_length == (p - retval + 1));
1254 : :
1255 : 451513 : pfree(values);
1256 : 451513 : pfree(needquotes);
1257 : :
1258 : 451513 : PG_RETURN_CSTRING(retval);
1259 : : }
1260 : :
1261 : : /*
1262 : : * array_recv :
1263 : : * converts an array from the external binary format to
1264 : : * its internal format.
1265 : : *
1266 : : * return value :
1267 : : * the internal representation of the input array
1268 : : */
1269 : : Datum
1270 : 31 : array_recv(PG_FUNCTION_ARGS)
1271 : : {
1272 : 31 : StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
1273 : 31 : Oid spec_element_type = PG_GETARG_OID(1); /* type of an array
1274 : : * element */
1275 : 31 : int32 typmod = PG_GETARG_INT32(2); /* typmod for array elements */
1276 : : Oid element_type;
1277 : : int typlen;
1278 : : bool typbyval;
1279 : : char typalign;
1280 : : Oid typioparam;
1281 : : int i,
1282 : : nitems;
1283 : : Datum *dataPtr;
1284 : : bool *nullsPtr;
1285 : : bool hasnulls;
1286 : : int32 nbytes;
1287 : : int32 dataoffset;
1288 : : ArrayType *retval;
1289 : : int ndim,
1290 : : flags,
1291 : : dim[MAXDIM],
1292 : : lBound[MAXDIM];
1293 : : ArrayMetaState *my_extra;
1294 : :
1295 : : /* Get the array header information */
1296 : 31 : ndim = pq_getmsgint(buf, 4);
1297 [ - + ]: 31 : if (ndim < 0) /* we do allow zero-dimension arrays */
1298 [ # # ]: 0 : ereport(ERROR,
1299 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1300 : : errmsg("invalid number of dimensions: %d", ndim)));
1301 [ - + ]: 31 : if (ndim > MAXDIM)
1302 [ # # ]: 0 : ereport(ERROR,
1303 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1304 : : errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
1305 : : ndim, MAXDIM)));
1306 : :
1307 : 31 : flags = pq_getmsgint(buf, 4);
1308 [ - + - - ]: 31 : if (flags != 0 && flags != 1)
1309 [ # # ]: 0 : ereport(ERROR,
1310 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1311 : : errmsg("invalid array flags")));
1312 : :
1313 : : /* Check element type recorded in the data */
1314 : 31 : element_type = pq_getmsgint(buf, sizeof(Oid));
1315 : :
1316 : : /*
1317 : : * From a security standpoint, it doesn't matter whether the input's
1318 : : * element type matches what we expect: the element type's receive
1319 : : * function has to be robust enough to cope with invalid data. However,
1320 : : * from a user-friendliness standpoint, it's nicer to complain about type
1321 : : * mismatches than to throw "improper binary format" errors. But there's
1322 : : * a problem: only built-in types have OIDs that are stable enough to
1323 : : * believe that a mismatch is a real issue. So complain only if both OIDs
1324 : : * are in the built-in range. Otherwise, carry on with the element type
1325 : : * we "should" be getting.
1326 : : */
1327 [ - + ]: 31 : if (element_type != spec_element_type)
1328 : : {
1329 [ # # # # ]: 0 : if (element_type < FirstGenbkiObjectId &&
1330 : : spec_element_type < FirstGenbkiObjectId)
1331 [ # # ]: 0 : ereport(ERROR,
1332 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
1333 : : errmsg("binary data has array element type %u (%s) instead of expected %u (%s)",
1334 : : element_type,
1335 : : format_type_extended(element_type, -1,
1336 : : FORMAT_TYPE_ALLOW_INVALID),
1337 : : spec_element_type,
1338 : : format_type_extended(spec_element_type, -1,
1339 : : FORMAT_TYPE_ALLOW_INVALID))));
1340 : 0 : element_type = spec_element_type;
1341 : : }
1342 : :
1343 [ + + ]: 62 : for (i = 0; i < ndim; i++)
1344 : : {
1345 : 31 : dim[i] = pq_getmsgint(buf, 4);
1346 : 31 : lBound[i] = pq_getmsgint(buf, 4);
1347 : : }
1348 : :
1349 : : /* This checks for overflow of array dimensions */
1350 : 31 : nitems = ArrayGetNItems(ndim, dim);
1351 : 31 : ArrayCheckBounds(ndim, dim, lBound);
1352 : :
1353 : : /*
1354 : : * We arrange to look up info about element type, including its receive
1355 : : * conversion proc, only once per series of calls, assuming the element
1356 : : * type doesn't change underneath us.
1357 : : */
1358 : 31 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1359 [ + + ]: 31 : if (my_extra == NULL)
1360 : : {
1361 : 28 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1362 : : sizeof(ArrayMetaState));
1363 : 28 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1364 : 28 : my_extra->element_type = ~element_type;
1365 : : }
1366 : :
1367 [ + + ]: 31 : if (my_extra->element_type != element_type)
1368 : : {
1369 : : /* Get info about element type, including its receive proc */
1370 : 28 : get_type_io_data(element_type, IOFunc_receive,
1371 : : &my_extra->typlen, &my_extra->typbyval,
1372 : : &my_extra->typalign, &my_extra->typdelim,
1373 : : &my_extra->typioparam, &my_extra->typiofunc);
1374 [ - + ]: 28 : if (!OidIsValid(my_extra->typiofunc))
1375 [ # # ]: 0 : ereport(ERROR,
1376 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
1377 : : errmsg("no binary input function available for type %s",
1378 : : format_type_be(element_type))));
1379 : 28 : fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
1380 : 28 : fcinfo->flinfo->fn_mcxt);
1381 : 28 : my_extra->element_type = element_type;
1382 : : }
1383 : :
1384 [ - + ]: 31 : if (nitems == 0)
1385 : : {
1386 : : /* Return empty array ... but not till we've validated element_type */
1387 : 0 : PG_RETURN_ARRAYTYPE_P(construct_empty_array(element_type));
1388 : : }
1389 : :
1390 : 31 : typlen = my_extra->typlen;
1391 : 31 : typbyval = my_extra->typbyval;
1392 : 31 : typalign = my_extra->typalign;
1393 : 31 : typioparam = my_extra->typioparam;
1394 : :
1395 : 31 : dataPtr = palloc_array(Datum, nitems);
1396 : 31 : nullsPtr = palloc_array(bool, nitems);
1397 : 31 : ReadArrayBinary(buf, nitems,
1398 : : &my_extra->proc, typioparam, typmod,
1399 : : typlen, typbyval, typalign,
1400 : : dataPtr, nullsPtr,
1401 : : &hasnulls, &nbytes);
1402 [ - + ]: 31 : if (hasnulls)
1403 : : {
1404 : 0 : dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
1405 : 0 : nbytes += dataoffset;
1406 : : }
1407 : : else
1408 : : {
1409 : 31 : dataoffset = 0; /* marker for no null bitmap */
1410 : 31 : nbytes += ARR_OVERHEAD_NONULLS(ndim);
1411 : : }
1412 : 31 : retval = (ArrayType *) palloc0(nbytes);
1413 : 31 : SET_VARSIZE(retval, nbytes);
1414 : 31 : retval->ndim = ndim;
1415 : 31 : retval->dataoffset = dataoffset;
1416 : 31 : retval->elemtype = element_type;
1417 : 31 : memcpy(ARR_DIMS(retval), dim, ndim * sizeof(int));
1418 : 31 : memcpy(ARR_LBOUND(retval), lBound, ndim * sizeof(int));
1419 : :
1420 : 31 : CopyArrayEls(retval,
1421 : : dataPtr, nullsPtr, nitems,
1422 : : typlen, typbyval, typalign,
1423 : : true);
1424 : :
1425 : 31 : pfree(dataPtr);
1426 : 31 : pfree(nullsPtr);
1427 : :
1428 : 31 : PG_RETURN_ARRAYTYPE_P(retval);
1429 : : }
1430 : :
1431 : : /*
1432 : : * ReadArrayBinary:
1433 : : * collect the data elements of an array being read in binary style.
1434 : : *
1435 : : * Inputs:
1436 : : * buf: the data buffer to read from.
1437 : : * nitems: total number of array elements (already read).
1438 : : * receiveproc: type-specific receive procedure for element datatype.
1439 : : * typioparam, typmod: auxiliary values to pass to receiveproc.
1440 : : * typlen, typbyval, typalign: storage parameters of element datatype.
1441 : : *
1442 : : * Outputs:
1443 : : * values[]: filled with converted data values.
1444 : : * nulls[]: filled with is-null markers.
1445 : : * *hasnulls: set true iff there are any null elements.
1446 : : * *nbytes: set to total size of data area needed (including alignment
1447 : : * padding but not including array header overhead).
1448 : : *
1449 : : * Note that values[] and nulls[] are allocated by the caller, and must have
1450 : : * nitems elements.
1451 : : */
1452 : : static void
1453 : 31 : ReadArrayBinary(StringInfo buf,
1454 : : int nitems,
1455 : : FmgrInfo *receiveproc,
1456 : : Oid typioparam,
1457 : : int32 typmod,
1458 : : int typlen,
1459 : : bool typbyval,
1460 : : char typalign,
1461 : : Datum *values,
1462 : : bool *nulls,
1463 : : bool *hasnulls,
1464 : : int32 *nbytes)
1465 : : {
1466 : : int i;
1467 : : bool hasnull;
1468 : : int32 totbytes;
1469 : 31 : uint8 typalignby = typalign_to_alignby(typalign);
1470 : :
1471 [ + + ]: 124 : for (i = 0; i < nitems; i++)
1472 : : {
1473 : : int itemlen;
1474 : : StringInfoData elem_buf;
1475 : :
1476 : : /* Get and check the item length */
1477 : 93 : itemlen = pq_getmsgint(buf, 4);
1478 [ + - - + ]: 93 : if (itemlen < -1 || itemlen > (buf->len - buf->cursor))
1479 [ # # ]: 0 : ereport(ERROR,
1480 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1481 : : errmsg("insufficient data left in message")));
1482 : :
1483 [ - + ]: 93 : if (itemlen == -1)
1484 : : {
1485 : : /* -1 length means NULL */
1486 : 0 : values[i] = ReceiveFunctionCall(receiveproc, NULL,
1487 : : typioparam, typmod);
1488 : 0 : nulls[i] = true;
1489 : 0 : continue;
1490 : : }
1491 : :
1492 : : /*
1493 : : * Rather than copying data around, we just initialize a StringInfo
1494 : : * pointing to the correct portion of the message buffer.
1495 : : */
1496 : 93 : initReadOnlyStringInfo(&elem_buf, &buf->data[buf->cursor], itemlen);
1497 : :
1498 : 93 : buf->cursor += itemlen;
1499 : :
1500 : : /* Now call the element's receiveproc */
1501 : 93 : values[i] = ReceiveFunctionCall(receiveproc, &elem_buf,
1502 : : typioparam, typmod);
1503 : 93 : nulls[i] = false;
1504 : :
1505 : : /* Trouble if it didn't eat the whole buffer */
1506 [ - + ]: 93 : if (elem_buf.cursor != itemlen)
1507 [ # # ]: 0 : ereport(ERROR,
1508 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1509 : : errmsg("improper binary format in array element %d",
1510 : : i + 1)));
1511 : : }
1512 : :
1513 : : /*
1514 : : * Check for nulls, compute total data space needed
1515 : : */
1516 : 31 : hasnull = false;
1517 : 31 : totbytes = 0;
1518 [ + + ]: 124 : for (i = 0; i < nitems; i++)
1519 : : {
1520 [ - + ]: 93 : if (nulls[i])
1521 : 0 : hasnull = true;
1522 : : else
1523 : : {
1524 : : /* let's just make sure data is not toasted */
1525 [ + + ]: 93 : if (typlen == -1)
1526 : 54 : values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
1527 [ + + + - ]: 93 : totbytes = att_addlength_datum(totbytes, typlen, values[i]);
1528 : 93 : totbytes = att_nominal_alignby(totbytes, typalignby);
1529 : : /* check for overflow of total request */
1530 [ - + ]: 93 : if (!AllocSizeIsValid(totbytes))
1531 [ # # ]: 0 : ereport(ERROR,
1532 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1533 : : errmsg("array size exceeds the maximum allowed (%zu)",
1534 : : MaxAllocSize)));
1535 : : }
1536 : : }
1537 : 31 : *hasnulls = hasnull;
1538 : 31 : *nbytes = totbytes;
1539 : 31 : }
1540 : :
1541 : :
1542 : : /*
1543 : : * array_send :
1544 : : * takes the internal representation of an array and returns a bytea
1545 : : * containing the array in its external binary format.
1546 : : */
1547 : : Datum
1548 : 23 : array_send(PG_FUNCTION_ARGS)
1549 : : {
1550 : 23 : AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
1551 [ - + ]: 23 : Oid element_type = AARR_ELEMTYPE(v);
1552 : : int typlen;
1553 : : bool typbyval;
1554 : : char typalign;
1555 : : int nitems,
1556 : : i;
1557 : : int ndim,
1558 : : *dim,
1559 : : *lb;
1560 : : StringInfoData buf;
1561 : : array_iter iter;
1562 : : ArrayMetaState *my_extra;
1563 : :
1564 : : /*
1565 : : * We arrange to look up info about element type, including its send
1566 : : * conversion proc, only once per series of calls, assuming the element
1567 : : * type doesn't change underneath us.
1568 : : */
1569 : 23 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1570 [ + + ]: 23 : if (my_extra == NULL)
1571 : : {
1572 : 20 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1573 : : sizeof(ArrayMetaState));
1574 : 20 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1575 : 20 : my_extra->element_type = ~element_type;
1576 : : }
1577 : :
1578 [ + + ]: 23 : if (my_extra->element_type != element_type)
1579 : : {
1580 : : /* Get info about element type, including its send proc */
1581 : 20 : get_type_io_data(element_type, IOFunc_send,
1582 : : &my_extra->typlen, &my_extra->typbyval,
1583 : : &my_extra->typalign, &my_extra->typdelim,
1584 : : &my_extra->typioparam, &my_extra->typiofunc);
1585 [ - + ]: 20 : if (!OidIsValid(my_extra->typiofunc))
1586 [ # # ]: 0 : ereport(ERROR,
1587 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
1588 : : errmsg("no binary output function available for type %s",
1589 : : format_type_be(element_type))));
1590 : 20 : fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
1591 : 20 : fcinfo->flinfo->fn_mcxt);
1592 : 20 : my_extra->element_type = element_type;
1593 : : }
1594 : 23 : typlen = my_extra->typlen;
1595 : 23 : typbyval = my_extra->typbyval;
1596 : 23 : typalign = my_extra->typalign;
1597 : :
1598 [ - + ]: 23 : ndim = AARR_NDIM(v);
1599 [ - + ]: 23 : dim = AARR_DIMS(v);
1600 [ - + ]: 23 : lb = AARR_LBOUND(v);
1601 : 23 : nitems = ArrayGetNItems(ndim, dim);
1602 : :
1603 : 23 : pq_begintypsend(&buf);
1604 : :
1605 : : /* Send the array header information */
1606 : 23 : pq_sendint32(&buf, ndim);
1607 [ - + - - ]: 23 : pq_sendint32(&buf, AARR_HASNULL(v) ? 1 : 0);
1608 : 23 : pq_sendint32(&buf, element_type);
1609 [ + + ]: 46 : for (i = 0; i < ndim; i++)
1610 : : {
1611 : 23 : pq_sendint32(&buf, dim[i]);
1612 : 23 : pq_sendint32(&buf, lb[i]);
1613 : : }
1614 : :
1615 : : /* Send the array elements using the element's own sendproc */
1616 : 23 : array_iter_setup(&iter, v, typlen, typbyval, typalign);
1617 : :
1618 [ + + ]: 92 : for (i = 0; i < nitems; i++)
1619 : : {
1620 : : Datum itemvalue;
1621 : : bool isnull;
1622 : :
1623 : : /* Get source element, checking for NULL */
1624 : 69 : itemvalue = array_iter_next(&iter, &isnull, i);
1625 : :
1626 [ - + ]: 69 : if (isnull)
1627 : : {
1628 : : /* -1 length means a NULL */
1629 : 0 : pq_sendint32(&buf, -1);
1630 : : }
1631 : : else
1632 : : {
1633 : : bytea *outputbytes;
1634 : :
1635 : 69 : outputbytes = SendFunctionCall(&my_extra->proc, itemvalue);
1636 : 69 : pq_sendint32(&buf, VARSIZE(outputbytes) - VARHDRSZ);
1637 : 69 : pq_sendbytes(&buf, VARDATA(outputbytes),
1638 : 69 : VARSIZE(outputbytes) - VARHDRSZ);
1639 : 69 : pfree(outputbytes);
1640 : : }
1641 : : }
1642 : :
1643 : 23 : PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
1644 : : }
1645 : :
1646 : : /*
1647 : : * array_ndims :
1648 : : * returns the number of dimensions of the array pointed to by "v"
1649 : : */
1650 : : Datum
1651 : 1460 : array_ndims(PG_FUNCTION_ARGS)
1652 : : {
1653 : 1460 : AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
1654 : :
1655 : : /* Sanity check: does it look like an array at all? */
1656 [ - + - - : 1460 : if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
+ + - + -
- - + ]
1657 : 8 : PG_RETURN_NULL();
1658 : :
1659 [ - + ]: 1452 : PG_RETURN_INT32(AARR_NDIM(v));
1660 : : }
1661 : :
1662 : : /*
1663 : : * array_dims :
1664 : : * returns the dimensions of the array pointed to by "v", as a "text"
1665 : : */
1666 : : Datum
1667 : 6737 : array_dims(PG_FUNCTION_ARGS)
1668 : : {
1669 : 6737 : AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
1670 : : char *p;
1671 : : int i;
1672 : : int *dimv,
1673 : : *lb;
1674 : :
1675 : : /*
1676 : : * 33 since we assume 15 digits per number + ':' +'[]'
1677 : : *
1678 : : * +1 for trailing null
1679 : : */
1680 : : char buf[MAXDIM * 33 + 1];
1681 : :
1682 : : /* Sanity check: does it look like an array at all? */
1683 [ - + - - : 6737 : if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
+ + - + -
- - + ]
1684 : 48 : PG_RETURN_NULL();
1685 : :
1686 [ - + ]: 6689 : dimv = AARR_DIMS(v);
1687 [ - + ]: 6689 : lb = AARR_LBOUND(v);
1688 : :
1689 : 6689 : p = buf;
1690 [ - + + + ]: 13450 : for (i = 0; i < AARR_NDIM(v); i++)
1691 : : {
1692 : 6761 : sprintf(p, "[%d:%d]", lb[i], dimv[i] + lb[i] - 1);
1693 : 6761 : p += strlen(p);
1694 : : }
1695 : :
1696 : 6689 : PG_RETURN_TEXT_P(cstring_to_text(buf));
1697 : : }
1698 : :
1699 : : /*
1700 : : * array_lower :
1701 : : * returns the lower dimension, of the DIM requested, for
1702 : : * the array pointed to by "v", as an int4
1703 : : */
1704 : : Datum
1705 : 17549 : array_lower(PG_FUNCTION_ARGS)
1706 : : {
1707 : 17549 : AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
1708 : 17549 : int reqdim = PG_GETARG_INT32(1);
1709 : : int *lb;
1710 : : int result;
1711 : :
1712 : : /* Sanity check: does it look like an array at all? */
1713 [ + + + - : 17549 : if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
+ - + + -
+ - + ]
1714 : 0 : PG_RETURN_NULL();
1715 : :
1716 : : /* Sanity check: was the requested dim valid */
1717 [ + - + + : 17549 : if (reqdim <= 0 || reqdim > AARR_NDIM(v))
- + ]
1718 : 0 : PG_RETURN_NULL();
1719 : :
1720 [ + + ]: 17549 : lb = AARR_LBOUND(v);
1721 : 17549 : result = lb[reqdim - 1];
1722 : :
1723 : 17549 : PG_RETURN_INT32(result);
1724 : : }
1725 : :
1726 : : /*
1727 : : * array_upper :
1728 : : * returns the upper dimension, of the DIM requested, for
1729 : : * the array pointed to by "v", as an int4
1730 : : */
1731 : : Datum
1732 : 17979 : array_upper(PG_FUNCTION_ARGS)
1733 : : {
1734 : 17979 : AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
1735 : 17979 : int reqdim = PG_GETARG_INT32(1);
1736 : : int *dimv,
1737 : : *lb;
1738 : : int result;
1739 : :
1740 : : /* Sanity check: does it look like an array at all? */
1741 [ + + + - : 17979 : if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
+ + + + -
+ - + ]
1742 : 21 : PG_RETURN_NULL();
1743 : :
1744 : : /* Sanity check: was the requested dim valid */
1745 [ + - + + : 17958 : if (reqdim <= 0 || reqdim > AARR_NDIM(v))
- + ]
1746 : 0 : PG_RETURN_NULL();
1747 : :
1748 [ + + ]: 17958 : lb = AARR_LBOUND(v);
1749 [ + + ]: 17958 : dimv = AARR_DIMS(v);
1750 : :
1751 : 17958 : result = dimv[reqdim - 1] + lb[reqdim - 1] - 1;
1752 : :
1753 : 17958 : PG_RETURN_INT32(result);
1754 : : }
1755 : :
1756 : : /*
1757 : : * array_length :
1758 : : * returns the length, of the dimension requested, for
1759 : : * the array pointed to by "v", as an int4
1760 : : */
1761 : : Datum
1762 : 78679 : array_length(PG_FUNCTION_ARGS)
1763 : : {
1764 : 78679 : AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
1765 : 78679 : int reqdim = PG_GETARG_INT32(1);
1766 : : int *dimv;
1767 : : int result;
1768 : :
1769 : : /* Sanity check: does it look like an array at all? */
1770 [ + + + - : 78679 : if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
+ - + + -
+ - + ]
1771 : 0 : PG_RETURN_NULL();
1772 : :
1773 : : /* Sanity check: was the requested dim valid */
1774 [ + + + + : 78679 : if (reqdim <= 0 || reqdim > AARR_NDIM(v))
+ + ]
1775 : 10 : PG_RETURN_NULL();
1776 : :
1777 [ + + ]: 78669 : dimv = AARR_DIMS(v);
1778 : :
1779 : 78669 : result = dimv[reqdim - 1];
1780 : :
1781 : 78669 : PG_RETURN_INT32(result);
1782 : : }
1783 : :
1784 : : /*
1785 : : * array_cardinality:
1786 : : * returns the total number of elements in an array
1787 : : */
1788 : : Datum
1789 : 1694 : array_cardinality(PG_FUNCTION_ARGS)
1790 : : {
1791 : 1694 : AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
1792 : :
1793 [ - + - + ]: 1694 : PG_RETURN_INT32(ArrayGetNItems(AARR_NDIM(v), AARR_DIMS(v)));
1794 : : }
1795 : :
1796 : :
1797 : : /*
1798 : : * array_get_element :
1799 : : * This routine takes an array datum and a subscript array and returns
1800 : : * the referenced item as a Datum. Note that for a pass-by-reference
1801 : : * datatype, the returned Datum is a pointer into the array object.
1802 : : *
1803 : : * This handles both ordinary varlena arrays and fixed-length arrays.
1804 : : *
1805 : : * Inputs:
1806 : : * arraydatum: the array object (mustn't be NULL)
1807 : : * nSubscripts: number of subscripts supplied
1808 : : * indx[]: the subscript values
1809 : : * arraytyplen: pg_type.typlen for the array type
1810 : : * elmlen: pg_type.typlen for the array's element type
1811 : : * elmbyval: pg_type.typbyval for the array's element type
1812 : : * elmalign: pg_type.typalign for the array's element type
1813 : : *
1814 : : * Outputs:
1815 : : * The return value is the element Datum.
1816 : : * *isNull is set to indicate whether the element is NULL.
1817 : : */
1818 : : Datum
1819 : 507673 : array_get_element(Datum arraydatum,
1820 : : int nSubscripts,
1821 : : int *indx,
1822 : : int arraytyplen,
1823 : : int elmlen,
1824 : : bool elmbyval,
1825 : : char elmalign,
1826 : : bool *isNull)
1827 : : {
1828 : : int i,
1829 : : ndim,
1830 : : *dim,
1831 : : *lb,
1832 : : offset,
1833 : : fixedDim[1],
1834 : : fixedLb[1];
1835 : : char *arraydataptr,
1836 : : *retptr;
1837 : : uint8 *arraynullsptr;
1838 : :
1839 [ + + ]: 507673 : if (arraytyplen > 0)
1840 : : {
1841 : : /*
1842 : : * fixed-length arrays -- these are assumed to be 1-d, 0-based
1843 : : */
1844 : 195872 : ndim = 1;
1845 : 195872 : fixedDim[0] = arraytyplen / elmlen;
1846 : 195872 : fixedLb[0] = 0;
1847 : 195872 : dim = fixedDim;
1848 : 195872 : lb = fixedLb;
1849 : 195872 : arraydataptr = (char *) DatumGetPointer(arraydatum);
1850 : 195872 : arraynullsptr = NULL;
1851 : : }
1852 [ + + ]: 311801 : else if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(arraydatum)))
1853 : : {
1854 : : /* expanded array: let's do this in a separate function */
1855 : 3421 : return array_get_element_expanded(arraydatum,
1856 : : nSubscripts,
1857 : : indx,
1858 : : arraytyplen,
1859 : : elmlen,
1860 : : elmbyval,
1861 : : elmalign,
1862 : : isNull);
1863 : : }
1864 : : else
1865 : : {
1866 : : /* detoast array if necessary, producing normal varlena input */
1867 : 308380 : ArrayType *array = DatumGetArrayTypeP(arraydatum);
1868 : :
1869 : 308380 : ndim = ARR_NDIM(array);
1870 : 308380 : dim = ARR_DIMS(array);
1871 : 308380 : lb = ARR_LBOUND(array);
1872 [ + + ]: 308380 : arraydataptr = ARR_DATA_PTR(array);
1873 [ + + ]: 308380 : arraynullsptr = ARR_NULLBITMAP(array);
1874 : : }
1875 : :
1876 : : /*
1877 : : * Return NULL for invalid subscript
1878 : : */
1879 [ + + + - : 504252 : if (ndim != nSubscripts || ndim <= 0 || ndim > MAXDIM)
- + ]
1880 : : {
1881 : 64 : *isNull = true;
1882 : 64 : return (Datum) 0;
1883 : : }
1884 [ + + ]: 973084 : for (i = 0; i < ndim; i++)
1885 : : {
1886 [ + + + + ]: 504256 : if (indx[i] < lb[i] || indx[i] >= (dim[i] + lb[i]))
1887 : : {
1888 : 35360 : *isNull = true;
1889 : 35360 : return (Datum) 0;
1890 : : }
1891 : : }
1892 : :
1893 : : /*
1894 : : * Calculate the element number
1895 : : */
1896 : 468828 : offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
1897 : :
1898 : : /*
1899 : : * Check for NULL array element
1900 : : */
1901 [ + + ]: 468828 : if (array_get_isnull(arraynullsptr, offset))
1902 : : {
1903 : 48 : *isNull = true;
1904 : 48 : return (Datum) 0;
1905 : : }
1906 : :
1907 : : /*
1908 : : * OK, get the element
1909 : : */
1910 : 468780 : *isNull = false;
1911 : 468780 : retptr = array_seek(arraydataptr, 0, arraynullsptr, offset,
1912 : : elmlen, elmbyval, elmalign);
1913 : 468780 : return ArrayCast(retptr, elmbyval, elmlen);
1914 : : }
1915 : :
1916 : : /*
1917 : : * Implementation of array_get_element() for an expanded array
1918 : : */
1919 : : static Datum
1920 : 3421 : array_get_element_expanded(Datum arraydatum,
1921 : : int nSubscripts, int *indx,
1922 : : int arraytyplen,
1923 : : int elmlen, bool elmbyval, char elmalign,
1924 : : bool *isNull)
1925 : : {
1926 : : ExpandedArrayHeader *eah;
1927 : : int i,
1928 : : ndim,
1929 : : *dim,
1930 : : *lb,
1931 : : offset;
1932 : : Datum *dvalues;
1933 : : bool *dnulls;
1934 : :
1935 : 3421 : eah = (ExpandedArrayHeader *) DatumGetEOHP(arraydatum);
1936 : : Assert(eah->ea_magic == EA_MAGIC);
1937 : :
1938 : : /* sanity-check caller's info against object */
1939 : : Assert(arraytyplen == -1);
1940 : : Assert(elmlen == eah->typlen);
1941 : : Assert(elmbyval == eah->typbyval);
1942 : : Assert(elmalign == eah->typalign);
1943 : :
1944 : 3421 : ndim = eah->ndims;
1945 : 3421 : dim = eah->dims;
1946 : 3421 : lb = eah->lbound;
1947 : :
1948 : : /*
1949 : : * Return NULL for invalid subscript
1950 : : */
1951 [ + + + - : 3421 : if (ndim != nSubscripts || ndim <= 0 || ndim > MAXDIM)
- + ]
1952 : : {
1953 : 4 : *isNull = true;
1954 : 4 : return (Datum) 0;
1955 : : }
1956 [ + + ]: 6834 : for (i = 0; i < ndim; i++)
1957 : : {
1958 [ + - - + ]: 3417 : if (indx[i] < lb[i] || indx[i] >= (dim[i] + lb[i]))
1959 : : {
1960 : 0 : *isNull = true;
1961 : 0 : return (Datum) 0;
1962 : : }
1963 : : }
1964 : :
1965 : : /*
1966 : : * Calculate the element number
1967 : : */
1968 : 3417 : offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
1969 : :
1970 : : /*
1971 : : * Deconstruct array if we didn't already. Note that we apply this even
1972 : : * if the input is nominally read-only: it should be safe enough.
1973 : : */
1974 : 3417 : deconstruct_expanded_array(eah);
1975 : :
1976 : 3417 : dvalues = eah->dvalues;
1977 : 3417 : dnulls = eah->dnulls;
1978 : :
1979 : : /*
1980 : : * Check for NULL array element
1981 : : */
1982 [ - + - - ]: 3417 : if (dnulls && dnulls[offset])
1983 : : {
1984 : 0 : *isNull = true;
1985 : 0 : return (Datum) 0;
1986 : : }
1987 : :
1988 : : /*
1989 : : * OK, get the element. It's OK to return a pass-by-ref value as a
1990 : : * pointer into the expanded array, for the same reason that regular
1991 : : * array_get_element can return a pointer into flat arrays: the value is
1992 : : * assumed not to change for as long as the Datum reference can exist.
1993 : : */
1994 : 3417 : *isNull = false;
1995 : 3417 : return dvalues[offset];
1996 : : }
1997 : :
1998 : : /*
1999 : : * array_get_slice :
2000 : : * This routine takes an array and a range of indices (upperIndx and
2001 : : * lowerIndx), creates a new array structure for the referred elements
2002 : : * and returns a pointer to it.
2003 : : *
2004 : : * This handles both ordinary varlena arrays and fixed-length arrays.
2005 : : *
2006 : : * Inputs:
2007 : : * arraydatum: the array object (mustn't be NULL)
2008 : : * nSubscripts: number of subscripts supplied (must be same for upper/lower)
2009 : : * upperIndx[]: the upper subscript values
2010 : : * lowerIndx[]: the lower subscript values
2011 : : * upperProvided[]: true for provided upper subscript values
2012 : : * lowerProvided[]: true for provided lower subscript values
2013 : : * arraytyplen: pg_type.typlen for the array type
2014 : : * elmlen: pg_type.typlen for the array's element type
2015 : : * elmbyval: pg_type.typbyval for the array's element type
2016 : : * elmalign: pg_type.typalign for the array's element type
2017 : : *
2018 : : * Outputs:
2019 : : * The return value is the new array Datum (it's never NULL)
2020 : : *
2021 : : * Omitted upper and lower subscript values are replaced by the corresponding
2022 : : * array bound.
2023 : : *
2024 : : * NOTE: we assume it is OK to scribble on the provided subscript arrays
2025 : : * lowerIndx[] and upperIndx[]; also, these arrays must be of size MAXDIM
2026 : : * even when nSubscripts is less. These are generally just temporaries.
2027 : : */
2028 : : Datum
2029 : 276 : array_get_slice(Datum arraydatum,
2030 : : int nSubscripts,
2031 : : int *upperIndx,
2032 : : int *lowerIndx,
2033 : : bool *upperProvided,
2034 : : bool *lowerProvided,
2035 : : int arraytyplen,
2036 : : int elmlen,
2037 : : bool elmbyval,
2038 : : char elmalign)
2039 : : {
2040 : : ArrayType *array;
2041 : : ArrayType *newarray;
2042 : : int i,
2043 : : ndim,
2044 : : *dim,
2045 : : *lb,
2046 : : *newlb;
2047 : : int fixedDim[1],
2048 : : fixedLb[1];
2049 : : Oid elemtype;
2050 : : char *arraydataptr;
2051 : : uint8 *arraynullsptr;
2052 : : int32 dataoffset;
2053 : : int bytes,
2054 : : span[MAXDIM];
2055 : :
2056 [ + + ]: 276 : if (arraytyplen > 0)
2057 : : {
2058 : : /*
2059 : : * fixed-length arrays -- currently, cannot slice these because parser
2060 : : * labels output as being of the fixed-length array type! Code below
2061 : : * shows how we could support it if the parser were changed to label
2062 : : * output as a suitable varlena array type.
2063 : : */
2064 [ + - ]: 16 : ereport(ERROR,
2065 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2066 : : errmsg("slices of fixed-length arrays not implemented")));
2067 : :
2068 : : /*
2069 : : * fixed-length arrays -- these are assumed to be 1-d, 0-based
2070 : : *
2071 : : * XXX where would we get the correct ELEMTYPE from?
2072 : : */
2073 : : ndim = 1;
2074 : : fixedDim[0] = arraytyplen / elmlen;
2075 : : fixedLb[0] = 0;
2076 : : dim = fixedDim;
2077 : : lb = fixedLb;
2078 : : elemtype = InvalidOid; /* XXX */
2079 : : arraydataptr = (char *) DatumGetPointer(arraydatum);
2080 : : arraynullsptr = NULL;
2081 : : }
2082 : : else
2083 : : {
2084 : : /* detoast input array if necessary */
2085 : 260 : array = DatumGetArrayTypeP(arraydatum);
2086 : :
2087 : 260 : ndim = ARR_NDIM(array);
2088 : 260 : dim = ARR_DIMS(array);
2089 : 260 : lb = ARR_LBOUND(array);
2090 : 260 : elemtype = ARR_ELEMTYPE(array);
2091 [ + + ]: 260 : arraydataptr = ARR_DATA_PTR(array);
2092 [ + + ]: 260 : arraynullsptr = ARR_NULLBITMAP(array);
2093 : : }
2094 : :
2095 : : /*
2096 : : * Check provided subscripts. A slice exceeding the current array limits
2097 : : * is silently truncated to the array limits. If we end up with an empty
2098 : : * slice, return an empty array.
2099 : : */
2100 [ + + + - : 260 : if (ndim < nSubscripts || ndim <= 0 || ndim > MAXDIM)
- + ]
2101 : 64 : return PointerGetDatum(construct_empty_array(elemtype));
2102 : :
2103 [ + + ]: 451 : for (i = 0; i < nSubscripts; i++)
2104 : : {
2105 [ + + + + ]: 263 : if (!lowerProvided[i] || lowerIndx[i] < lb[i])
2106 : 84 : lowerIndx[i] = lb[i];
2107 [ + + + + ]: 263 : if (!upperProvided[i] || upperIndx[i] >= (dim[i] + lb[i]))
2108 : 48 : upperIndx[i] = dim[i] + lb[i] - 1;
2109 [ + + ]: 263 : if (lowerIndx[i] > upperIndx[i])
2110 : 8 : return PointerGetDatum(construct_empty_array(elemtype));
2111 : : }
2112 : : /* fill any missing subscript positions with full array range */
2113 [ + + ]: 221 : for (; i < ndim; i++)
2114 : : {
2115 : 33 : lowerIndx[i] = lb[i];
2116 : 33 : upperIndx[i] = dim[i] + lb[i] - 1;
2117 [ - + ]: 33 : if (lowerIndx[i] > upperIndx[i])
2118 : 0 : return PointerGetDatum(construct_empty_array(elemtype));
2119 : : }
2120 : :
2121 : 188 : mda_get_range(ndim, span, lowerIndx, upperIndx);
2122 : :
2123 : 188 : bytes = array_slice_size(arraydataptr, arraynullsptr,
2124 : : ndim, dim, lb,
2125 : : lowerIndx, upperIndx,
2126 : : elmlen, elmbyval, elmalign);
2127 : :
2128 : : /*
2129 : : * Currently, we put a null bitmap in the result if the source has one;
2130 : : * could be smarter ...
2131 : : */
2132 [ + + ]: 188 : if (arraynullsptr)
2133 : : {
2134 : 24 : dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, ArrayGetNItems(ndim, span));
2135 : 24 : bytes += dataoffset;
2136 : : }
2137 : : else
2138 : : {
2139 : 164 : dataoffset = 0; /* marker for no null bitmap */
2140 : 164 : bytes += ARR_OVERHEAD_NONULLS(ndim);
2141 : : }
2142 : :
2143 : 188 : newarray = (ArrayType *) palloc0(bytes);
2144 : 188 : SET_VARSIZE(newarray, bytes);
2145 : 188 : newarray->ndim = ndim;
2146 : 188 : newarray->dataoffset = dataoffset;
2147 : 188 : newarray->elemtype = elemtype;
2148 : 188 : memcpy(ARR_DIMS(newarray), span, ndim * sizeof(int));
2149 : :
2150 : : /*
2151 : : * Lower bounds of the new array are set to 1. Formerly (before 7.3) we
2152 : : * copied the given lowerIndx values ... but that seems confusing.
2153 : : */
2154 : 188 : newlb = ARR_LBOUND(newarray);
2155 [ + + ]: 476 : for (i = 0; i < ndim; i++)
2156 : 288 : newlb[i] = 1;
2157 : :
2158 : 188 : array_extract_slice(newarray,
2159 : : ndim, dim, lb,
2160 : : arraydataptr, arraynullsptr,
2161 : : lowerIndx, upperIndx,
2162 : : elmlen, elmbyval, elmalign);
2163 : :
2164 : 188 : return PointerGetDatum(newarray);
2165 : : }
2166 : :
2167 : : /*
2168 : : * array_set_element :
2169 : : * This routine sets the value of one array element (specified by
2170 : : * a subscript array) to a new value specified by "dataValue".
2171 : : *
2172 : : * This handles both ordinary varlena arrays and fixed-length arrays.
2173 : : *
2174 : : * Inputs:
2175 : : * arraydatum: the initial array object (mustn't be NULL)
2176 : : * nSubscripts: number of subscripts supplied
2177 : : * indx[]: the subscript values
2178 : : * dataValue: the datum to be inserted at the given position
2179 : : * isNull: whether dataValue is NULL
2180 : : * arraytyplen: pg_type.typlen for the array type
2181 : : * elmlen: pg_type.typlen for the array's element type
2182 : : * elmbyval: pg_type.typbyval for the array's element type
2183 : : * elmalign: pg_type.typalign for the array's element type
2184 : : *
2185 : : * Result:
2186 : : * A new array is returned, just like the old except for the one
2187 : : * modified entry. The original array object is not changed,
2188 : : * unless what is passed is a read-write reference to an expanded
2189 : : * array object; in that case the expanded array is updated in-place.
2190 : : *
2191 : : * For one-dimensional arrays only, we allow the array to be extended
2192 : : * by assigning to a position outside the existing subscript range; any
2193 : : * positions between the existing elements and the new one are set to NULLs.
2194 : : * (XXX TODO: allow a corresponding behavior for multidimensional arrays)
2195 : : *
2196 : : * NOTE: For assignments, we throw an error for invalid subscripts etc,
2197 : : * rather than returning a NULL as the fetch operations do.
2198 : : */
2199 : : Datum
2200 : 2708 : array_set_element(Datum arraydatum,
2201 : : int nSubscripts,
2202 : : int *indx,
2203 : : Datum dataValue,
2204 : : bool isNull,
2205 : : int arraytyplen,
2206 : : int elmlen,
2207 : : bool elmbyval,
2208 : : char elmalign)
2209 : : {
2210 : : ArrayType *array;
2211 : : ArrayType *newarray;
2212 : : int i,
2213 : : ndim,
2214 : : dim[MAXDIM],
2215 : : lb[MAXDIM],
2216 : : offset;
2217 : : char *elt_ptr;
2218 : : bool newhasnulls;
2219 : : uint8 *oldnullbitmap;
2220 : : int oldnitems,
2221 : : newnitems,
2222 : : olddatasize,
2223 : : newsize,
2224 : : olditemlen,
2225 : : newitemlen,
2226 : : overheadlen,
2227 : : oldoverheadlen,
2228 : : addedbefore,
2229 : : addedafter,
2230 : : lenbefore,
2231 : : lenafter;
2232 : 2708 : uint8 elmalignby = typalign_to_alignby(elmalign);
2233 : :
2234 [ + + ]: 2708 : if (arraytyplen > 0)
2235 : : {
2236 : : /*
2237 : : * fixed-length arrays -- these are assumed to be 1-d, 0-based. We
2238 : : * cannot extend them, either.
2239 : : */
2240 : : bool isname;
2241 : : int numelems;
2242 : : char *resultarray;
2243 : :
2244 [ - + ]: 12 : if (nSubscripts != 1)
2245 [ # # ]: 0 : ereport(ERROR,
2246 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2247 : : errmsg("wrong number of array subscripts")));
2248 : :
2249 : : /*
2250 : : * Normally, any element of the array can be assigned to. But for
2251 : : * type "name" we should not allow assignment to the last element,
2252 : : * since it's supposed to stay '\0'. Unfortunately we can't directly
2253 : : * test whether the array is of type "name" without changing this
2254 : : * function's API. But given the tiny usage of fixed-length-array
2255 : : * types, it should be good enough to check for elmlen = 1 and
2256 : : * arraytyplen = NAMEDATALEN.
2257 : : */
2258 [ - + - - ]: 12 : isname = (elmlen == 1 && arraytyplen == NAMEDATALEN);
2259 [ - + ]: 12 : if (isname)
2260 : 0 : numelems = NAMEDATALEN - 1;
2261 : : else
2262 : 12 : numelems = arraytyplen / elmlen;
2263 : :
2264 [ + - + + ]: 12 : if (indx[0] < 0 || indx[0] >= numelems)
2265 [ + - ]: 4 : ereport(ERROR,
2266 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2267 : : errmsg("array subscript out of range")));
2268 : :
2269 [ - + ]: 8 : if (isNull)
2270 [ # # ]: 0 : ereport(ERROR,
2271 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2272 : : errmsg("cannot assign null value to an element of a fixed-length array")));
2273 : :
2274 : 8 : resultarray = (char *) palloc(arraytyplen);
2275 : 8 : memcpy(resultarray, DatumGetPointer(arraydatum), arraytyplen);
2276 : 8 : elt_ptr = resultarray + indx[0] * elmlen;
2277 : 8 : ArrayCastAndSet(dataValue, elmlen, elmbyval, elmalignby, elt_ptr);
2278 : :
2279 : : /*
2280 : : * Another problem with allowing element assignment for type "name" is
2281 : : * that it can produce an invalidly-encoded string. Reject that.
2282 : : */
2283 [ - + ]: 8 : if (isname)
2284 : 0 : pg_verifymbstr(resultarray, strlen(resultarray), false);
2285 : :
2286 : 8 : return PointerGetDatum(resultarray);
2287 : : }
2288 : :
2289 [ + - - + ]: 2696 : if (nSubscripts <= 0 || nSubscripts > MAXDIM)
2290 [ # # ]: 0 : ereport(ERROR,
2291 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2292 : : errmsg("wrong number of array subscripts")));
2293 : :
2294 : : /* make sure item to be inserted is not toasted */
2295 [ + + + + ]: 2696 : if (elmlen == -1 && !isNull)
2296 : 1614 : dataValue = PointerGetDatum(PG_DETOAST_DATUM(dataValue));
2297 : :
2298 [ + + ]: 2696 : if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(arraydatum)))
2299 : : {
2300 : : /* expanded array: let's do this in a separate function */
2301 : 1361 : return array_set_element_expanded(arraydatum,
2302 : : nSubscripts,
2303 : : indx,
2304 : : dataValue,
2305 : : isNull,
2306 : : arraytyplen,
2307 : : elmlen,
2308 : : elmbyval,
2309 : : elmalign);
2310 : : }
2311 : :
2312 : : /* detoast input array if necessary */
2313 : 1335 : array = DatumGetArrayTypeP(arraydatum);
2314 : :
2315 : 1335 : ndim = ARR_NDIM(array);
2316 : :
2317 : : /*
2318 : : * if number of dims is zero, i.e. an empty array, create an array with
2319 : : * nSubscripts dimensions, and set the lower bounds to the supplied
2320 : : * subscripts
2321 : : */
2322 [ + + ]: 1335 : if (ndim == 0)
2323 : : {
2324 : 248 : Oid elmtype = ARR_ELEMTYPE(array);
2325 : :
2326 [ + + ]: 497 : for (i = 0; i < nSubscripts; i++)
2327 : : {
2328 : 249 : dim[i] = 1;
2329 : 249 : lb[i] = indx[i];
2330 : : }
2331 : :
2332 : 248 : return PointerGetDatum(construct_md_array(&dataValue, &isNull,
2333 : : nSubscripts, dim, lb,
2334 : : elmtype,
2335 : : elmlen, elmbyval, elmalign));
2336 : : }
2337 : :
2338 [ + + ]: 1087 : if (ndim != nSubscripts)
2339 [ + - ]: 4 : ereport(ERROR,
2340 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2341 : : errmsg("wrong number of array subscripts")));
2342 : :
2343 : : /* copy dim/lb since we may modify them */
2344 : 1083 : memcpy(dim, ARR_DIMS(array), ndim * sizeof(int));
2345 : 1083 : memcpy(lb, ARR_LBOUND(array), ndim * sizeof(int));
2346 : :
2347 [ + + + + ]: 1083 : newhasnulls = (ARR_HASNULL(array) || isNull);
2348 : 1083 : addedbefore = addedafter = 0;
2349 : :
2350 : : /*
2351 : : * Check subscripts. We assume the existing subscripts passed
2352 : : * ArrayCheckBounds, so that dim[i] + lb[i] can be computed without
2353 : : * overflow. But we must beware of other overflows in our calculations of
2354 : : * new dim[] values.
2355 : : */
2356 [ + + ]: 1083 : if (ndim == 1)
2357 : : {
2358 [ + + ]: 1079 : if (indx[0] < lb[0])
2359 : : {
2360 : : /* addedbefore = lb[0] - indx[0]; */
2361 : : /* dim[0] += addedbefore; */
2362 [ + - - + ]: 32 : if (pg_sub_s32_overflow(lb[0], indx[0], &addedbefore) ||
2363 : 16 : pg_add_s32_overflow(dim[0], addedbefore, &dim[0]))
2364 [ # # ]: 0 : ereport(ERROR,
2365 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2366 : : errmsg("array size exceeds the maximum allowed (%zu)",
2367 : : MaxArraySize)));
2368 : 16 : lb[0] = indx[0];
2369 [ + + ]: 16 : if (addedbefore > 1)
2370 : 8 : newhasnulls = true; /* will insert nulls */
2371 : : }
2372 [ + + ]: 1079 : if (indx[0] >= (dim[0] + lb[0]))
2373 : : {
2374 : : /* addedafter = indx[0] - (dim[0] + lb[0]) + 1; */
2375 : : /* dim[0] += addedafter; */
2376 [ + + + - ]: 1662 : if (pg_sub_s32_overflow(indx[0], dim[0] + lb[0], &addedafter) ||
2377 [ - + ]: 1658 : pg_add_s32_overflow(addedafter, 1, &addedafter) ||
2378 : 829 : pg_add_s32_overflow(dim[0], addedafter, &dim[0]))
2379 [ + - ]: 4 : ereport(ERROR,
2380 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2381 : : errmsg("array size exceeds the maximum allowed (%zu)",
2382 : : MaxArraySize)));
2383 [ + + ]: 829 : if (addedafter > 1)
2384 : 25 : newhasnulls = true; /* will insert nulls */
2385 : : }
2386 : : }
2387 : : else
2388 : : {
2389 : : /*
2390 : : * XXX currently we do not support extending multi-dimensional arrays
2391 : : * during assignment
2392 : : */
2393 [ + + ]: 12 : for (i = 0; i < ndim; i++)
2394 : : {
2395 [ + - ]: 8 : if (indx[i] < lb[i] ||
2396 [ - + ]: 8 : indx[i] >= (dim[i] + lb[i]))
2397 [ # # ]: 0 : ereport(ERROR,
2398 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2399 : : errmsg("array subscript out of range")));
2400 : : }
2401 : : }
2402 : :
2403 : : /* This checks for overflow of the array dimensions */
2404 : 1079 : newnitems = ArrayGetNItems(ndim, dim);
2405 : 1079 : ArrayCheckBounds(ndim, dim, lb);
2406 : :
2407 : : /*
2408 : : * Compute sizes of items and areas to copy
2409 : : */
2410 [ + + ]: 1079 : if (newhasnulls)
2411 : 90 : overheadlen = ARR_OVERHEAD_WITHNULLS(ndim, newnitems);
2412 : : else
2413 : 989 : overheadlen = ARR_OVERHEAD_NONULLS(ndim);
2414 : 1079 : oldnitems = ArrayGetNItems(ndim, ARR_DIMS(array));
2415 [ + + ]: 1079 : oldnullbitmap = ARR_NULLBITMAP(array);
2416 [ + + ]: 1079 : oldoverheadlen = ARR_DATA_OFFSET(array);
2417 : 1079 : olddatasize = ARR_SIZE(array) - oldoverheadlen;
2418 [ + + ]: 1079 : if (addedbefore)
2419 : : {
2420 : 16 : offset = 0;
2421 : 16 : lenbefore = 0;
2422 : 16 : olditemlen = 0;
2423 : 16 : lenafter = olddatasize;
2424 : : }
2425 [ + + ]: 1063 : else if (addedafter)
2426 : : {
2427 : 829 : offset = oldnitems;
2428 : 829 : lenbefore = olddatasize;
2429 : 829 : olditemlen = 0;
2430 : 829 : lenafter = 0;
2431 : : }
2432 : : else
2433 : : {
2434 : 234 : offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
2435 [ + + ]: 234 : elt_ptr = array_seek(ARR_DATA_PTR(array), 0, oldnullbitmap, offset,
2436 : : elmlen, elmbyval, elmalign);
2437 [ + + ]: 234 : lenbefore = (int) (elt_ptr - ARR_DATA_PTR(array));
2438 [ + + ]: 234 : if (array_get_isnull(oldnullbitmap, offset))
2439 : 16 : olditemlen = 0;
2440 : : else
2441 : : {
2442 [ + + + - ]: 218 : olditemlen = att_addlength_pointer(0, elmlen, elt_ptr);
2443 : 218 : olditemlen = att_nominal_alignby(olditemlen, elmalignby);
2444 : : }
2445 : 234 : lenafter = olddatasize - lenbefore - olditemlen;
2446 : : }
2447 : :
2448 [ + + ]: 1079 : if (isNull)
2449 : 13 : newitemlen = 0;
2450 : : else
2451 : : {
2452 [ + + + - ]: 1066 : newitemlen = att_addlength_datum(0, elmlen, dataValue);
2453 : 1066 : newitemlen = att_nominal_alignby(newitemlen, elmalignby);
2454 : : }
2455 : :
2456 : 1079 : newsize = overheadlen + lenbefore + newitemlen + lenafter;
2457 : :
2458 : : /*
2459 : : * OK, create the new array and fill in header/dimensions
2460 : : */
2461 : 1079 : newarray = (ArrayType *) palloc0(newsize);
2462 : 1079 : SET_VARSIZE(newarray, newsize);
2463 : 1079 : newarray->ndim = ndim;
2464 [ + + ]: 1079 : newarray->dataoffset = newhasnulls ? overheadlen : 0;
2465 : 1079 : newarray->elemtype = ARR_ELEMTYPE(array);
2466 : 1079 : memcpy(ARR_DIMS(newarray), dim, ndim * sizeof(int));
2467 : 1079 : memcpy(ARR_LBOUND(newarray), lb, ndim * sizeof(int));
2468 : :
2469 : : /*
2470 : : * Fill in data
2471 : : */
2472 : 1079 : memcpy((char *) newarray + overheadlen,
2473 : : (char *) array + oldoverheadlen,
2474 : : lenbefore);
2475 [ + + ]: 1079 : if (!isNull)
2476 : 1066 : ArrayCastAndSet(dataValue, elmlen, elmbyval, elmalignby,
2477 : 1066 : (char *) newarray + overheadlen + lenbefore);
2478 : 1079 : memcpy((char *) newarray + overheadlen + lenbefore + newitemlen,
2479 : 1079 : (char *) array + oldoverheadlen + lenbefore + olditemlen,
2480 : : lenafter);
2481 : :
2482 : : /*
2483 : : * Fill in nulls bitmap if needed
2484 : : *
2485 : : * Note: it's possible we just replaced the last NULL with a non-NULL, and
2486 : : * could get rid of the bitmap. Seems not worth testing for though.
2487 : : */
2488 [ + + ]: 1079 : if (newhasnulls)
2489 : : {
2490 [ + - ]: 90 : uint8 *newnullbitmap = ARR_NULLBITMAP(newarray);
2491 : :
2492 : : /* palloc0 above already marked any inserted positions as nulls */
2493 : : /* Fix the inserted value */
2494 [ + + ]: 90 : if (addedafter)
2495 : 38 : array_set_isnull(newnullbitmap, newnitems - 1, isNull);
2496 : : else
2497 : 52 : array_set_isnull(newnullbitmap, offset, isNull);
2498 : : /* Fix the copied range(s) */
2499 [ + + ]: 90 : if (addedbefore)
2500 : 16 : array_bitmap_copy(newnullbitmap, addedbefore,
2501 : : oldnullbitmap, 0,
2502 : : oldnitems);
2503 : : else
2504 : : {
2505 : 74 : array_bitmap_copy(newnullbitmap, 0,
2506 : : oldnullbitmap, 0,
2507 : : offset);
2508 [ + + ]: 74 : if (addedafter == 0)
2509 : 36 : array_bitmap_copy(newnullbitmap, offset + 1,
2510 : : oldnullbitmap, offset + 1,
2511 : 36 : oldnitems - offset - 1);
2512 : : }
2513 : : }
2514 : :
2515 : 1079 : return PointerGetDatum(newarray);
2516 : : }
2517 : :
2518 : : /*
2519 : : * Implementation of array_set_element() for an expanded array
2520 : : *
2521 : : * Note: as with any operation on a read/write expanded object, we must
2522 : : * take pains not to leave the object in a corrupt state if we fail partway
2523 : : * through.
2524 : : */
2525 : : static Datum
2526 : 1361 : array_set_element_expanded(Datum arraydatum,
2527 : : int nSubscripts, int *indx,
2528 : : Datum dataValue, bool isNull,
2529 : : int arraytyplen,
2530 : : int elmlen, bool elmbyval, char elmalign)
2531 : : {
2532 : : ExpandedArrayHeader *eah;
2533 : : Datum *dvalues;
2534 : : bool *dnulls;
2535 : : int i,
2536 : : ndim,
2537 : : dim[MAXDIM],
2538 : : lb[MAXDIM],
2539 : : offset;
2540 : : bool dimschanged,
2541 : : newhasnulls;
2542 : : int addedbefore,
2543 : : addedafter;
2544 : : char *oldValue;
2545 : :
2546 : : /* Convert to R/W object if not so already */
2547 : 1361 : eah = DatumGetExpandedArray(arraydatum);
2548 : :
2549 : : /* Sanity-check caller's info against object; we don't use it otherwise */
2550 : : Assert(arraytyplen == -1);
2551 : : Assert(elmlen == eah->typlen);
2552 : : Assert(elmbyval == eah->typbyval);
2553 : : Assert(elmalign == eah->typalign);
2554 : :
2555 : : /*
2556 : : * Copy dimension info into local storage. This allows us to modify the
2557 : : * dimensions if needed, while not messing up the expanded value if we
2558 : : * fail partway through.
2559 : : */
2560 : 1361 : ndim = eah->ndims;
2561 : : Assert(ndim >= 0 && ndim <= MAXDIM);
2562 : 1361 : memcpy(dim, eah->dims, ndim * sizeof(int));
2563 : 1361 : memcpy(lb, eah->lbound, ndim * sizeof(int));
2564 : 1361 : dimschanged = false;
2565 : :
2566 : : /*
2567 : : * if number of dims is zero, i.e. an empty array, create an array with
2568 : : * nSubscripts dimensions, and set the lower bounds to the supplied
2569 : : * subscripts.
2570 : : */
2571 [ + + ]: 1361 : if (ndim == 0)
2572 : : {
2573 : : /*
2574 : : * Allocate adequate space for new dimension info. This is harmless
2575 : : * if we fail later.
2576 : : */
2577 : : Assert(nSubscripts > 0 && nSubscripts <= MAXDIM);
2578 : 271 : eah->dims = (int *) MemoryContextAllocZero(eah->hdr.eoh_context,
2579 : : nSubscripts * sizeof(int));
2580 : 271 : eah->lbound = (int *) MemoryContextAllocZero(eah->hdr.eoh_context,
2581 : : nSubscripts * sizeof(int));
2582 : :
2583 : : /* Update local copies of dimension info */
2584 : 271 : ndim = nSubscripts;
2585 [ + + ]: 542 : for (i = 0; i < nSubscripts; i++)
2586 : : {
2587 : 271 : dim[i] = 0;
2588 : 271 : lb[i] = indx[i];
2589 : : }
2590 : 271 : dimschanged = true;
2591 : : }
2592 [ - + ]: 1090 : else if (ndim != nSubscripts)
2593 [ # # ]: 0 : ereport(ERROR,
2594 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2595 : : errmsg("wrong number of array subscripts")));
2596 : :
2597 : : /*
2598 : : * Deconstruct array if we didn't already. (Someday maybe add a special
2599 : : * case path for fixed-length, no-nulls cases, where we can overwrite an
2600 : : * element in place without ever deconstructing. But today is not that
2601 : : * day.)
2602 : : */
2603 : 1361 : deconstruct_expanded_array(eah);
2604 : :
2605 : : /*
2606 : : * Copy new element into array's context, if needed (we assume it's
2607 : : * already detoasted, so no junk should be created). Doing this before
2608 : : * we've made any significant changes ensures that our behavior is sane
2609 : : * even when the source is a reference to some element of this same array.
2610 : : * If we fail further down, this memory is leaked, but that's reasonably
2611 : : * harmless.
2612 : : */
2613 [ + + + - ]: 1361 : if (!eah->typbyval && !isNull)
2614 : : {
2615 : 587 : MemoryContext oldcxt = MemoryContextSwitchTo(eah->hdr.eoh_context);
2616 : :
2617 : 587 : dataValue = datumCopy(dataValue, false, eah->typlen);
2618 : 587 : MemoryContextSwitchTo(oldcxt);
2619 : : }
2620 : :
2621 : 1361 : dvalues = eah->dvalues;
2622 : 1361 : dnulls = eah->dnulls;
2623 : :
2624 [ + - - + ]: 1361 : newhasnulls = ((dnulls != NULL) || isNull);
2625 : 1361 : addedbefore = addedafter = 0;
2626 : :
2627 : : /*
2628 : : * Check subscripts (this logic must match array_set_element). We assume
2629 : : * the existing subscripts passed ArrayCheckBounds, so that dim[i] + lb[i]
2630 : : * can be computed without overflow. But we must beware of other
2631 : : * overflows in our calculations of new dim[] values.
2632 : : */
2633 [ + - ]: 1361 : if (ndim == 1)
2634 : : {
2635 [ + + ]: 1361 : if (indx[0] < lb[0])
2636 : : {
2637 : : /* addedbefore = lb[0] - indx[0]; */
2638 : : /* dim[0] += addedbefore; */
2639 [ + - - + ]: 126 : if (pg_sub_s32_overflow(lb[0], indx[0], &addedbefore) ||
2640 : 63 : pg_add_s32_overflow(dim[0], addedbefore, &dim[0]))
2641 [ # # ]: 0 : ereport(ERROR,
2642 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2643 : : errmsg("array size exceeds the maximum allowed (%zu)",
2644 : : MaxArraySize)));
2645 : 63 : lb[0] = indx[0];
2646 : 63 : dimschanged = true;
2647 [ - + ]: 63 : if (addedbefore > 1)
2648 : 0 : newhasnulls = true; /* will insert nulls */
2649 : : }
2650 [ + + ]: 1361 : if (indx[0] >= (dim[0] + lb[0]))
2651 : : {
2652 : : /* addedafter = indx[0] - (dim[0] + lb[0]) + 1; */
2653 : : /* dim[0] += addedafter; */
2654 [ + + + - ]: 2528 : if (pg_sub_s32_overflow(indx[0], dim[0] + lb[0], &addedafter) ||
2655 [ - + ]: 2524 : pg_add_s32_overflow(addedafter, 1, &addedafter) ||
2656 : 1262 : pg_add_s32_overflow(dim[0], addedafter, &dim[0]))
2657 [ + - ]: 4 : ereport(ERROR,
2658 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2659 : : errmsg("array size exceeds the maximum allowed (%zu)",
2660 : : MaxArraySize)));
2661 : 1262 : dimschanged = true;
2662 [ - + ]: 1262 : if (addedafter > 1)
2663 : 0 : newhasnulls = true; /* will insert nulls */
2664 : : }
2665 : : }
2666 : : else
2667 : : {
2668 : : /*
2669 : : * XXX currently we do not support extending multi-dimensional arrays
2670 : : * during assignment
2671 : : */
2672 [ # # ]: 0 : for (i = 0; i < ndim; i++)
2673 : : {
2674 [ # # ]: 0 : if (indx[i] < lb[i] ||
2675 [ # # ]: 0 : indx[i] >= (dim[i] + lb[i]))
2676 [ # # ]: 0 : ereport(ERROR,
2677 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2678 : : errmsg("array subscript out of range")));
2679 : : }
2680 : : }
2681 : :
2682 : : /* Check for overflow of the array dimensions */
2683 [ + + ]: 1357 : if (dimschanged)
2684 : : {
2685 : 1325 : (void) ArrayGetNItems(ndim, dim);
2686 : 1325 : ArrayCheckBounds(ndim, dim, lb);
2687 : : }
2688 : :
2689 : : /* Now we can calculate linear offset of target item in array */
2690 : 1357 : offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
2691 : :
2692 : : /* Physically enlarge existing dvalues/dnulls arrays if needed */
2693 [ + + ]: 1357 : if (dim[0] > eah->dvalueslen)
2694 : : {
2695 : : /* We want some extra space if we're enlarging */
2696 : 1317 : int newlen = dim[0] + dim[0] / 8;
2697 : :
2698 : 1317 : newlen = Max(newlen, dim[0]); /* integer overflow guard */
2699 : 1317 : eah->dvalues = dvalues = repalloc_array(dvalues, Datum, newlen);
2700 [ - + ]: 1317 : if (dnulls)
2701 : 0 : eah->dnulls = dnulls = repalloc_array(dnulls, bool, newlen);
2702 : 1317 : eah->dvalueslen = newlen;
2703 : : }
2704 : :
2705 : : /*
2706 : : * If we need a nulls bitmap and don't already have one, create it, being
2707 : : * sure to mark all existing entries as not null.
2708 : : */
2709 [ - + - - ]: 1357 : if (newhasnulls && dnulls == NULL)
2710 : 0 : eah->dnulls = dnulls = (bool *)
2711 : 0 : MemoryContextAllocZero(eah->hdr.eoh_context,
2712 : 0 : eah->dvalueslen * sizeof(bool));
2713 : :
2714 : : /*
2715 : : * We now have all the needed space allocated, so we're ready to make
2716 : : * irreversible changes. Be very wary of allowing failure below here.
2717 : : */
2718 : :
2719 : : /* Flattened value will no longer represent array accurately */
2720 : 1357 : eah->fvalue = NULL;
2721 : : /* And we don't know the flattened size either */
2722 : 1357 : eah->flat_size = 0;
2723 : :
2724 : : /* Update dimensionality info if needed */
2725 [ + + ]: 1357 : if (dimschanged)
2726 : : {
2727 : 1325 : eah->ndims = ndim;
2728 : 1325 : memcpy(eah->dims, dim, ndim * sizeof(int));
2729 : 1325 : memcpy(eah->lbound, lb, ndim * sizeof(int));
2730 : : }
2731 : :
2732 : : /* Reposition items if needed, and fill addedbefore items with nulls */
2733 [ + + ]: 1357 : if (addedbefore > 0)
2734 : : {
2735 : 63 : memmove(dvalues + addedbefore, dvalues, eah->nelems * sizeof(Datum));
2736 [ + + ]: 126 : for (i = 0; i < addedbefore; i++)
2737 : 63 : dvalues[i] = (Datum) 0;
2738 [ - + ]: 63 : if (dnulls)
2739 : : {
2740 : 0 : memmove(dnulls + addedbefore, dnulls, eah->nelems * sizeof(bool));
2741 [ # # ]: 0 : for (i = 0; i < addedbefore; i++)
2742 : 0 : dnulls[i] = true;
2743 : : }
2744 : 63 : eah->nelems += addedbefore;
2745 : : }
2746 : :
2747 : : /* fill addedafter items with nulls */
2748 [ + + ]: 1357 : if (addedafter > 0)
2749 : : {
2750 [ + + ]: 2524 : for (i = 0; i < addedafter; i++)
2751 : 1262 : dvalues[eah->nelems + i] = (Datum) 0;
2752 [ - + ]: 1262 : if (dnulls)
2753 : : {
2754 [ # # ]: 0 : for (i = 0; i < addedafter; i++)
2755 : 0 : dnulls[eah->nelems + i] = true;
2756 : : }
2757 : 1262 : eah->nelems += addedafter;
2758 : : }
2759 : :
2760 : : /* Grab old element value for pfree'ing, if needed. */
2761 [ + + - + : 1357 : if (!eah->typbyval && (dnulls == NULL || !dnulls[offset]))
- - ]
2762 : 587 : oldValue = (char *) DatumGetPointer(dvalues[offset]);
2763 : : else
2764 : 770 : oldValue = NULL;
2765 : :
2766 : : /* And finally we can insert the new element. */
2767 : 1357 : dvalues[offset] = dataValue;
2768 [ - + ]: 1357 : if (dnulls)
2769 : 0 : dnulls[offset] = isNull;
2770 : :
2771 : : /*
2772 : : * Free old element if needed; this keeps repeated element replacements
2773 : : * from bloating the array's storage. If the pfree somehow fails, it
2774 : : * won't corrupt the array.
2775 : : */
2776 [ + + ]: 1357 : if (oldValue)
2777 : : {
2778 : : /* Don't try to pfree a part of the original flat array */
2779 [ + - - + ]: 1 : if (oldValue < eah->fstartptr || oldValue >= eah->fendptr)
2780 : 0 : pfree(oldValue);
2781 : : }
2782 : :
2783 : : /* Done, return standard TOAST pointer for object */
2784 : 1357 : return EOHPGetRWDatum(&eah->hdr);
2785 : : }
2786 : :
2787 : : /*
2788 : : * array_set_slice :
2789 : : * This routine sets the value of a range of array locations (specified
2790 : : * by upper and lower subscript values) to new values passed as
2791 : : * another array.
2792 : : *
2793 : : * This handles both ordinary varlena arrays and fixed-length arrays.
2794 : : *
2795 : : * Inputs:
2796 : : * arraydatum: the initial array object (mustn't be NULL)
2797 : : * nSubscripts: number of subscripts supplied (must be same for upper/lower)
2798 : : * upperIndx[]: the upper subscript values
2799 : : * lowerIndx[]: the lower subscript values
2800 : : * upperProvided[]: true for provided upper subscript values
2801 : : * lowerProvided[]: true for provided lower subscript values
2802 : : * srcArrayDatum: the source for the inserted values
2803 : : * isNull: indicates whether srcArrayDatum is NULL
2804 : : * arraytyplen: pg_type.typlen for the array type
2805 : : * elmlen: pg_type.typlen for the array's element type
2806 : : * elmbyval: pg_type.typbyval for the array's element type
2807 : : * elmalign: pg_type.typalign for the array's element type
2808 : : *
2809 : : * Result:
2810 : : * A new array is returned, just like the old except for the
2811 : : * modified range. The original array object is not changed.
2812 : : *
2813 : : * Omitted upper and lower subscript values are replaced by the corresponding
2814 : : * array bound.
2815 : : *
2816 : : * For one-dimensional arrays only, we allow the array to be extended
2817 : : * by assigning to positions outside the existing subscript range; any
2818 : : * positions between the existing elements and the new ones are set to NULLs.
2819 : : * (XXX TODO: allow a corresponding behavior for multidimensional arrays)
2820 : : *
2821 : : * NOTE: we assume it is OK to scribble on the provided index arrays
2822 : : * lowerIndx[] and upperIndx[]; also, these arrays must be of size MAXDIM
2823 : : * even when nSubscripts is less. These are generally just temporaries.
2824 : : *
2825 : : * NOTE: For assignments, we throw an error for silly subscripts etc,
2826 : : * rather than returning a NULL or empty array as the fetch operations do.
2827 : : */
2828 : : Datum
2829 : 180 : array_set_slice(Datum arraydatum,
2830 : : int nSubscripts,
2831 : : int *upperIndx,
2832 : : int *lowerIndx,
2833 : : bool *upperProvided,
2834 : : bool *lowerProvided,
2835 : : Datum srcArrayDatum,
2836 : : bool isNull,
2837 : : int arraytyplen,
2838 : : int elmlen,
2839 : : bool elmbyval,
2840 : : char elmalign)
2841 : : {
2842 : : ArrayType *array;
2843 : : ArrayType *srcArray;
2844 : : ArrayType *newarray;
2845 : : int i,
2846 : : ndim,
2847 : : dim[MAXDIM],
2848 : : lb[MAXDIM],
2849 : : span[MAXDIM];
2850 : : bool newhasnulls;
2851 : : int nitems,
2852 : : nsrcitems,
2853 : : olddatasize,
2854 : : newsize,
2855 : : olditemsize,
2856 : : newitemsize,
2857 : : overheadlen,
2858 : : oldoverheadlen,
2859 : : addedbefore,
2860 : : addedafter,
2861 : : lenbefore,
2862 : : lenafter,
2863 : : itemsbefore,
2864 : : itemsafter,
2865 : : nolditems;
2866 : :
2867 : : /* Currently, assignment from a NULL source array is a no-op */
2868 [ - + ]: 180 : if (isNull)
2869 : 0 : return arraydatum;
2870 : :
2871 [ - + ]: 180 : if (arraytyplen > 0)
2872 : : {
2873 : : /*
2874 : : * fixed-length arrays -- not got round to doing this...
2875 : : *
2876 : : * If we ever do implement this, note the special handling of type
2877 : : * "name" in array_set_element().
2878 : : */
2879 [ # # ]: 0 : ereport(ERROR,
2880 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2881 : : errmsg("updates on slices of fixed-length arrays not implemented")));
2882 : : }
2883 : :
2884 : : /* detoast arrays if necessary */
2885 : 180 : array = DatumGetArrayTypeP(arraydatum);
2886 : 180 : srcArray = DatumGetArrayTypeP(srcArrayDatum);
2887 : :
2888 : : /* note: we assume srcArray contains no toasted elements */
2889 : :
2890 : 180 : ndim = ARR_NDIM(array);
2891 : :
2892 : : /*
2893 : : * if number of dims is zero, i.e. an empty array, create an array with
2894 : : * nSubscripts dimensions, and set the upper and lower bounds to the
2895 : : * supplied subscripts
2896 : : */
2897 [ + + ]: 180 : if (ndim == 0)
2898 : : {
2899 : : Datum *dvalues;
2900 : : bool *dnulls;
2901 : : int nelems;
2902 : 43 : Oid elmtype = ARR_ELEMTYPE(array);
2903 : :
2904 : 43 : deconstruct_array(srcArray, elmtype, elmlen, elmbyval, elmalign,
2905 : : &dvalues, &dnulls, &nelems);
2906 : :
2907 [ + + ]: 89 : for (i = 0; i < nSubscripts; i++)
2908 : : {
2909 [ + + - + ]: 58 : if (!upperProvided[i] || !lowerProvided[i])
2910 [ + - ]: 4 : ereport(ERROR,
2911 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2912 : : errmsg("array slice subscript must provide both boundaries"),
2913 : : errdetail("When assigning to a slice of an empty array value,"
2914 : : " slice boundaries must be fully specified.")));
2915 : :
2916 : : /* compute "upperIndx[i] - lowerIndx[i] + 1", detecting overflow */
2917 [ + + + + ]: 104 : if (pg_sub_s32_overflow(upperIndx[i], lowerIndx[i], &dim[i]) ||
2918 : 50 : pg_add_s32_overflow(dim[i], 1, &dim[i]))
2919 [ + - ]: 8 : ereport(ERROR,
2920 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2921 : : errmsg("array size exceeds the maximum allowed (%zu)",
2922 : : MaxArraySize)));
2923 : :
2924 : 46 : lb[i] = lowerIndx[i];
2925 : : }
2926 : :
2927 : : /* complain if too few source items; we ignore extras, however */
2928 [ - + ]: 31 : if (nelems < ArrayGetNItems(nSubscripts, dim))
2929 [ # # ]: 0 : ereport(ERROR,
2930 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2931 : : errmsg("source array too small")));
2932 : :
2933 : 31 : return PointerGetDatum(construct_md_array(dvalues, dnulls, nSubscripts,
2934 : : dim, lb, elmtype,
2935 : : elmlen, elmbyval, elmalign));
2936 : : }
2937 : :
2938 [ + - + - : 137 : if (ndim < nSubscripts || ndim <= 0 || ndim > MAXDIM)
- + ]
2939 [ # # ]: 0 : ereport(ERROR,
2940 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2941 : : errmsg("wrong number of array subscripts")));
2942 : :
2943 : : /* copy dim/lb since we may modify them */
2944 : 137 : memcpy(dim, ARR_DIMS(array), ndim * sizeof(int));
2945 : 137 : memcpy(lb, ARR_LBOUND(array), ndim * sizeof(int));
2946 : :
2947 [ + + - + ]: 137 : newhasnulls = (ARR_HASNULL(array) || ARR_HASNULL(srcArray));
2948 : 137 : addedbefore = addedafter = 0;
2949 : :
2950 : : /*
2951 : : * Check subscripts. We assume the existing subscripts passed
2952 : : * ArrayCheckBounds, so that dim[i] + lb[i] can be computed without
2953 : : * overflow. But we must beware of other overflows in our calculations of
2954 : : * new dim[] values.
2955 : : */
2956 [ + + ]: 137 : if (ndim == 1)
2957 : : {
2958 : : Assert(nSubscripts == 1);
2959 [ + + ]: 117 : if (!lowerProvided[0])
2960 : 24 : lowerIndx[0] = lb[0];
2961 [ + + ]: 117 : if (!upperProvided[0])
2962 : 28 : upperIndx[0] = dim[0] + lb[0] - 1;
2963 [ - + ]: 117 : if (lowerIndx[0] > upperIndx[0])
2964 [ # # ]: 0 : ereport(ERROR,
2965 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2966 : : errmsg("upper bound cannot be less than lower bound")));
2967 [ + + ]: 117 : if (lowerIndx[0] < lb[0])
2968 : : {
2969 : : /* addedbefore = lb[0] - lowerIndx[0]; */
2970 : : /* dim[0] += addedbefore; */
2971 [ + - - + ]: 64 : if (pg_sub_s32_overflow(lb[0], lowerIndx[0], &addedbefore) ||
2972 : 32 : pg_add_s32_overflow(dim[0], addedbefore, &dim[0]))
2973 [ # # ]: 0 : ereport(ERROR,
2974 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2975 : : errmsg("array size exceeds the maximum allowed (%zu)",
2976 : : MaxArraySize)));
2977 : 32 : lb[0] = lowerIndx[0];
2978 [ + + ]: 32 : if (addedbefore > 1)
2979 : 24 : newhasnulls = true; /* will insert nulls */
2980 : : }
2981 [ + + ]: 117 : if (upperIndx[0] >= (dim[0] + lb[0]))
2982 : : {
2983 : : /* addedafter = upperIndx[0] - (dim[0] + lb[0]) + 1; */
2984 : : /* dim[0] += addedafter; */
2985 [ + + + - ]: 78 : if (pg_sub_s32_overflow(upperIndx[0], dim[0] + lb[0], &addedafter) ||
2986 [ - + ]: 74 : pg_add_s32_overflow(addedafter, 1, &addedafter) ||
2987 : 37 : pg_add_s32_overflow(dim[0], addedafter, &dim[0]))
2988 [ + - ]: 4 : ereport(ERROR,
2989 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2990 : : errmsg("array size exceeds the maximum allowed (%zu)",
2991 : : MaxArraySize)));
2992 [ + + ]: 37 : if (addedafter > 1)
2993 : 24 : newhasnulls = true; /* will insert nulls */
2994 : : }
2995 : : }
2996 : : else
2997 : : {
2998 : : /*
2999 : : * XXX currently we do not support extending multi-dimensional arrays
3000 : : * during assignment
3001 : : */
3002 [ + + ]: 68 : for (i = 0; i < nSubscripts; i++)
3003 : : {
3004 [ + + ]: 48 : if (!lowerProvided[i])
3005 : 8 : lowerIndx[i] = lb[i];
3006 [ + + ]: 48 : if (!upperProvided[i])
3007 : 16 : upperIndx[i] = dim[i] + lb[i] - 1;
3008 [ - + ]: 48 : if (lowerIndx[i] > upperIndx[i])
3009 [ # # ]: 0 : ereport(ERROR,
3010 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
3011 : : errmsg("upper bound cannot be less than lower bound")));
3012 [ + - ]: 48 : if (lowerIndx[i] < lb[i] ||
3013 [ - + ]: 48 : upperIndx[i] >= (dim[i] + lb[i]))
3014 [ # # ]: 0 : ereport(ERROR,
3015 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
3016 : : errmsg("array subscript out of range")));
3017 : : }
3018 : : /* fill any missing subscript positions with full array range */
3019 [ - + ]: 20 : for (; i < ndim; i++)
3020 : : {
3021 : 0 : lowerIndx[i] = lb[i];
3022 : 0 : upperIndx[i] = dim[i] + lb[i] - 1;
3023 [ # # ]: 0 : if (lowerIndx[i] > upperIndx[i])
3024 [ # # ]: 0 : ereport(ERROR,
3025 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
3026 : : errmsg("upper bound cannot be less than lower bound")));
3027 : : }
3028 : : }
3029 : :
3030 : : /* Do this mainly to check for overflow */
3031 : 133 : nitems = ArrayGetNItems(ndim, dim);
3032 : 133 : ArrayCheckBounds(ndim, dim, lb);
3033 : :
3034 : : /*
3035 : : * Make sure source array has enough entries. Note we ignore the shape of
3036 : : * the source array and just read entries serially.
3037 : : */
3038 : 133 : mda_get_range(ndim, span, lowerIndx, upperIndx);
3039 : 133 : nsrcitems = ArrayGetNItems(ndim, span);
3040 [ + + ]: 133 : if (nsrcitems > ArrayGetNItems(ARR_NDIM(srcArray), ARR_DIMS(srcArray)))
3041 [ + - ]: 4 : ereport(ERROR,
3042 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
3043 : : errmsg("source array too small")));
3044 : :
3045 : : /*
3046 : : * Compute space occupied by new entries, space occupied by replaced
3047 : : * entries, and required space for new array.
3048 : : */
3049 [ + + ]: 129 : if (newhasnulls)
3050 : 64 : overheadlen = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
3051 : : else
3052 : 65 : overheadlen = ARR_OVERHEAD_NONULLS(ndim);
3053 [ + + ]: 129 : newitemsize = array_nelems_size(ARR_DATA_PTR(srcArray), 0,
3054 [ + + ]: 129 : ARR_NULLBITMAP(srcArray), nsrcitems,
3055 : : elmlen, elmbyval, elmalign);
3056 [ + + ]: 129 : oldoverheadlen = ARR_DATA_OFFSET(array);
3057 : 129 : olddatasize = ARR_SIZE(array) - oldoverheadlen;
3058 [ + + ]: 129 : if (ndim > 1)
3059 : : {
3060 : : /*
3061 : : * here we do not need to cope with extension of the array; it would
3062 : : * be a lot more complicated if we had to do so...
3063 : : */
3064 [ - + ]: 20 : olditemsize = array_slice_size(ARR_DATA_PTR(array),
3065 [ - + ]: 20 : ARR_NULLBITMAP(array),
3066 : : ndim, dim, lb,
3067 : : lowerIndx, upperIndx,
3068 : : elmlen, elmbyval, elmalign);
3069 : 20 : lenbefore = lenafter = 0; /* keep compiler quiet */
3070 : 20 : itemsbefore = itemsafter = nolditems = 0;
3071 : : }
3072 : : else
3073 : : {
3074 : : /*
3075 : : * here we must allow for possibility of slice larger than orig array
3076 : : * and/or not adjacent to orig array subscripts
3077 : : */
3078 : 109 : int oldlb = ARR_LBOUND(array)[0];
3079 : 109 : int oldub = oldlb + ARR_DIMS(array)[0] - 1;
3080 : 109 : int slicelb = Max(oldlb, lowerIndx[0]);
3081 : 109 : int sliceub = Min(oldub, upperIndx[0]);
3082 [ + + ]: 109 : char *oldarraydata = ARR_DATA_PTR(array);
3083 [ + + ]: 109 : uint8 *oldarraybitmap = ARR_NULLBITMAP(array);
3084 : :
3085 : : /* count/size of old array entries that will go before the slice */
3086 : 109 : itemsbefore = Min(slicelb, oldub + 1) - oldlb;
3087 : 109 : lenbefore = array_nelems_size(oldarraydata, 0, oldarraybitmap,
3088 : : itemsbefore,
3089 : : elmlen, elmbyval, elmalign);
3090 : : /* count/size of old array entries that will be replaced by slice */
3091 [ + + ]: 109 : if (slicelb > sliceub)
3092 : : {
3093 : 36 : nolditems = 0;
3094 : 36 : olditemsize = 0;
3095 : : }
3096 : : else
3097 : : {
3098 : 73 : nolditems = sliceub - slicelb + 1;
3099 : 73 : olditemsize = array_nelems_size(oldarraydata + lenbefore,
3100 : : itemsbefore, oldarraybitmap,
3101 : : nolditems,
3102 : : elmlen, elmbyval, elmalign);
3103 : : }
3104 : : /* count/size of old array entries that will go after the slice */
3105 : 109 : itemsafter = oldub + 1 - Max(sliceub + 1, oldlb);
3106 : 109 : lenafter = olddatasize - lenbefore - olditemsize;
3107 : : }
3108 : :
3109 : 129 : newsize = overheadlen + olddatasize - olditemsize + newitemsize;
3110 : :
3111 : 129 : newarray = (ArrayType *) palloc0(newsize);
3112 : 129 : SET_VARSIZE(newarray, newsize);
3113 : 129 : newarray->ndim = ndim;
3114 [ + + ]: 129 : newarray->dataoffset = newhasnulls ? overheadlen : 0;
3115 : 129 : newarray->elemtype = ARR_ELEMTYPE(array);
3116 : 129 : memcpy(ARR_DIMS(newarray), dim, ndim * sizeof(int));
3117 : 129 : memcpy(ARR_LBOUND(newarray), lb, ndim * sizeof(int));
3118 : :
3119 [ + + ]: 129 : if (ndim > 1)
3120 : : {
3121 : : /*
3122 : : * here we do not need to cope with extension of the array; it would
3123 : : * be a lot more complicated if we had to do so...
3124 : : */
3125 : 20 : array_insert_slice(newarray, array, srcArray,
3126 : : ndim, dim, lb,
3127 : : lowerIndx, upperIndx,
3128 : : elmlen, elmbyval, elmalign);
3129 : : }
3130 : : else
3131 : : {
3132 : : /* fill in data */
3133 : 109 : memcpy((char *) newarray + overheadlen,
3134 : : (char *) array + oldoverheadlen,
3135 : : lenbefore);
3136 : 218 : memcpy((char *) newarray + overheadlen + lenbefore,
3137 [ + + ]: 109 : ARR_DATA_PTR(srcArray),
3138 : : newitemsize);
3139 : 109 : memcpy((char *) newarray + overheadlen + lenbefore + newitemsize,
3140 : 109 : (char *) array + oldoverheadlen + lenbefore + olditemsize,
3141 : : lenafter);
3142 : : /* fill in nulls bitmap if needed */
3143 [ + + ]: 109 : if (newhasnulls)
3144 : : {
3145 [ + - ]: 64 : uint8 *newnullbitmap = ARR_NULLBITMAP(newarray);
3146 [ + - ]: 64 : uint8 *oldnullbitmap = ARR_NULLBITMAP(array);
3147 : :
3148 : : /* palloc0 above already marked any inserted positions as nulls */
3149 : 64 : array_bitmap_copy(newnullbitmap, addedbefore,
3150 : : oldnullbitmap, 0,
3151 : : itemsbefore);
3152 : 64 : array_bitmap_copy(newnullbitmap, lowerIndx[0] - lb[0],
3153 [ + + ]: 64 : ARR_NULLBITMAP(srcArray), 0,
3154 : : nsrcitems);
3155 : 64 : array_bitmap_copy(newnullbitmap, addedbefore + itemsbefore + nolditems,
3156 : : oldnullbitmap, itemsbefore + nolditems,
3157 : : itemsafter);
3158 : : }
3159 : : }
3160 : :
3161 : 129 : return PointerGetDatum(newarray);
3162 : : }
3163 : :
3164 : : /*
3165 : : * array_ref : backwards compatibility wrapper for array_get_element
3166 : : *
3167 : : * This only works for detoasted/flattened varlena arrays, since the array
3168 : : * argument is declared as "ArrayType *". However there's enough code like
3169 : : * that to justify preserving this API.
3170 : : */
3171 : : Datum
3172 : 30122 : array_ref(ArrayType *array, int nSubscripts, int *indx,
3173 : : int arraytyplen, int elmlen, bool elmbyval, char elmalign,
3174 : : bool *isNull)
3175 : : {
3176 : 30122 : return array_get_element(PointerGetDatum(array), nSubscripts, indx,
3177 : : arraytyplen, elmlen, elmbyval, elmalign,
3178 : : isNull);
3179 : : }
3180 : :
3181 : : /*
3182 : : * array_set : backwards compatibility wrapper for array_set_element
3183 : : *
3184 : : * This only works for detoasted/flattened varlena arrays, since the array
3185 : : * argument and result are declared as "ArrayType *". However there's enough
3186 : : * code like that to justify preserving this API.
3187 : : */
3188 : : ArrayType *
3189 : 636 : array_set(ArrayType *array, int nSubscripts, int *indx,
3190 : : Datum dataValue, bool isNull,
3191 : : int arraytyplen, int elmlen, bool elmbyval, char elmalign)
3192 : : {
3193 : 636 : return DatumGetArrayTypeP(array_set_element(PointerGetDatum(array),
3194 : : nSubscripts, indx,
3195 : : dataValue, isNull,
3196 : : arraytyplen,
3197 : : elmlen, elmbyval, elmalign));
3198 : : }
3199 : :
3200 : : /*
3201 : : * array_map()
3202 : : *
3203 : : * Map an array through an arbitrary expression. Return a new array with
3204 : : * the same dimensions and each source element transformed by the given,
3205 : : * already-compiled expression. Each source element is placed in the
3206 : : * innermost_caseval/innermost_casenull fields of the ExprState.
3207 : : *
3208 : : * Parameters are:
3209 : : * * arrayd: Datum representing array argument.
3210 : : * * exprstate: ExprState representing the per-element transformation.
3211 : : * * econtext: context for expression evaluation.
3212 : : * * retType: OID of element type of output array. This must be the same as,
3213 : : * or binary-compatible with, the result type of the expression. It might
3214 : : * be different from the input array's element type.
3215 : : * * amstate: workspace for array_map. Must be zeroed by caller before
3216 : : * first call, and not touched after that.
3217 : : *
3218 : : * It is legitimate to pass a freshly-zeroed ArrayMapState on each call,
3219 : : * but better performance can be had if the state can be preserved across
3220 : : * a series of calls.
3221 : : *
3222 : : * NB: caller must assure that input array is not NULL. NULL elements in
3223 : : * the array are OK however.
3224 : : * NB: caller should be running in econtext's per-tuple memory context.
3225 : : */
3226 : : Datum
3227 : 20654 : array_map(Datum arrayd,
3228 : : ExprState *exprstate, ExprContext *econtext,
3229 : : Oid retType, ArrayMapState *amstate)
3230 : : {
3231 : 20654 : AnyArrayType *v = DatumGetAnyArrayP(arrayd);
3232 : : ArrayType *result;
3233 : : Datum *values;
3234 : : bool *nulls;
3235 : : int *dim;
3236 : : int ndim;
3237 : : int nitems;
3238 : : int i;
3239 : 20654 : int32 nbytes = 0;
3240 : : int32 dataoffset;
3241 : : bool hasnulls;
3242 : : Oid inpType;
3243 : : int inp_typlen;
3244 : : bool inp_typbyval;
3245 : : char inp_typalign;
3246 : : int typlen;
3247 : : bool typbyval;
3248 : : char typalign;
3249 : : uint8 typalignby;
3250 : : array_iter iter;
3251 : : ArrayMetaState *inp_extra;
3252 : : ArrayMetaState *ret_extra;
3253 : 20654 : Datum *transform_source = exprstate->innermost_caseval;
3254 : 20654 : bool *transform_source_isnull = exprstate->innermost_casenull;
3255 : :
3256 [ - + ]: 20654 : inpType = AARR_ELEMTYPE(v);
3257 [ - + ]: 20654 : ndim = AARR_NDIM(v);
3258 [ - + ]: 20654 : dim = AARR_DIMS(v);
3259 : 20654 : nitems = ArrayGetNItems(ndim, dim);
3260 : :
3261 : : /* Check for empty array */
3262 [ + + ]: 20654 : if (nitems <= 0)
3263 : : {
3264 : : /* Return empty array */
3265 : 10 : return PointerGetDatum(construct_empty_array(retType));
3266 : : }
3267 : :
3268 : : /*
3269 : : * We arrange to look up info about input and return element types only
3270 : : * once per series of calls, assuming the element type doesn't change
3271 : : * underneath us.
3272 : : */
3273 : 20644 : inp_extra = &amstate->inp_extra;
3274 : 20644 : ret_extra = &amstate->ret_extra;
3275 : :
3276 [ + + ]: 20644 : if (inp_extra->element_type != inpType)
3277 : : {
3278 : 332 : get_typlenbyvalalign(inpType,
3279 : : &inp_extra->typlen,
3280 : : &inp_extra->typbyval,
3281 : : &inp_extra->typalign);
3282 : 332 : inp_extra->element_type = inpType;
3283 : : }
3284 : 20644 : inp_typlen = inp_extra->typlen;
3285 : 20644 : inp_typbyval = inp_extra->typbyval;
3286 : 20644 : inp_typalign = inp_extra->typalign;
3287 : :
3288 [ + + ]: 20644 : if (ret_extra->element_type != retType)
3289 : : {
3290 : 332 : get_typlenbyvalalign(retType,
3291 : : &ret_extra->typlen,
3292 : : &ret_extra->typbyval,
3293 : : &ret_extra->typalign);
3294 : 332 : ret_extra->element_type = retType;
3295 : : }
3296 : 20644 : typlen = ret_extra->typlen;
3297 : 20644 : typbyval = ret_extra->typbyval;
3298 : 20644 : typalign = ret_extra->typalign;
3299 : 20644 : typalignby = typalign_to_alignby(typalign);
3300 : :
3301 : : /* Allocate temporary arrays for new values */
3302 : 20644 : values = palloc_array(Datum, nitems);
3303 : 20644 : nulls = palloc_array(bool, nitems);
3304 : :
3305 : : /* Loop over source data */
3306 : 20644 : array_iter_setup(&iter, v, inp_typlen, inp_typbyval, inp_typalign);
3307 : 20644 : hasnulls = false;
3308 : :
3309 [ + + ]: 231715 : for (i = 0; i < nitems; i++)
3310 : : {
3311 : : /* Get source element, checking for NULL */
3312 : 211091 : *transform_source =
3313 : 211091 : array_iter_next(&iter, transform_source_isnull, i);
3314 : :
3315 : : /* Apply the given expression to source element */
3316 : 211091 : values[i] = ExecEvalExpr(exprstate, econtext, &nulls[i]);
3317 : :
3318 [ + + ]: 211071 : if (nulls[i])
3319 : 10 : hasnulls = true;
3320 : : else
3321 : : {
3322 : : /* Ensure data is not toasted */
3323 [ + + ]: 211061 : if (typlen == -1)
3324 : 366 : values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
3325 : : /* Update total result size */
3326 [ + + + - ]: 211061 : nbytes = att_addlength_datum(nbytes, typlen, values[i]);
3327 : 211061 : nbytes = att_nominal_alignby(nbytes, typalignby);
3328 : : /* check for overflow of total request */
3329 [ - + ]: 211061 : if (!AllocSizeIsValid(nbytes))
3330 [ # # ]: 0 : ereport(ERROR,
3331 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3332 : : errmsg("array size exceeds the maximum allowed (%zu)",
3333 : : MaxAllocSize)));
3334 : : }
3335 : : }
3336 : :
3337 : : /* Allocate and fill the result array */
3338 [ + + ]: 20624 : if (hasnulls)
3339 : : {
3340 : 5 : dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
3341 : 5 : nbytes += dataoffset;
3342 : : }
3343 : : else
3344 : : {
3345 : 20619 : dataoffset = 0; /* marker for no null bitmap */
3346 : 20619 : nbytes += ARR_OVERHEAD_NONULLS(ndim);
3347 : : }
3348 : 20624 : result = (ArrayType *) palloc0(nbytes);
3349 : 20624 : SET_VARSIZE(result, nbytes);
3350 : 20624 : result->ndim = ndim;
3351 : 20624 : result->dataoffset = dataoffset;
3352 : 20624 : result->elemtype = retType;
3353 [ - + ]: 20624 : memcpy(ARR_DIMS(result), AARR_DIMS(v), ndim * sizeof(int));
3354 [ - + ]: 20624 : memcpy(ARR_LBOUND(result), AARR_LBOUND(v), ndim * sizeof(int));
3355 : :
3356 : 20624 : CopyArrayEls(result,
3357 : : values, nulls, nitems,
3358 : : typlen, typbyval, typalign,
3359 : : false);
3360 : :
3361 : : /*
3362 : : * Note: do not risk trying to pfree the results of the called expression
3363 : : */
3364 : 20624 : pfree(values);
3365 : 20624 : pfree(nulls);
3366 : :
3367 : 20624 : return PointerGetDatum(result);
3368 : : }
3369 : :
3370 : : /*
3371 : : * construct_array --- simple method for constructing an array object
3372 : : *
3373 : : * elems: array of Datum items to become the array contents
3374 : : * (NULL element values are not supported).
3375 : : * nelems: number of items
3376 : : * elmtype, elmlen, elmbyval, elmalign: info for the datatype of the items
3377 : : *
3378 : : * A palloc'd 1-D array object is constructed and returned. Note that
3379 : : * elem values will be copied into the object even if pass-by-ref type.
3380 : : * Also note the result will be 0-D not 1-D if nelems = 0.
3381 : : *
3382 : : * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
3383 : : * from the system catalogs, given the elmtype. However, the caller is
3384 : : * in a better position to cache this info across multiple uses, or even
3385 : : * to hard-wire values if the element type is hard-wired.
3386 : : */
3387 : : ArrayType *
3388 : 216454 : construct_array(Datum *elems, int nelems,
3389 : : Oid elmtype,
3390 : : int elmlen, bool elmbyval, char elmalign)
3391 : : {
3392 : : int dims[1];
3393 : : int lbs[1];
3394 : :
3395 : 216454 : dims[0] = nelems;
3396 : 216454 : lbs[0] = 1;
3397 : :
3398 : 216454 : return construct_md_array(elems, NULL, 1, dims, lbs,
3399 : : elmtype, elmlen, elmbyval, elmalign);
3400 : : }
3401 : :
3402 : : /*
3403 : : * Like construct_array(), where elmtype must be a built-in type, and
3404 : : * elmlen/elmbyval/elmalign is looked up from hardcoded data. This is often
3405 : : * useful when manipulating arrays from/for system catalogs.
3406 : : */
3407 : : ArrayType *
3408 : 154901 : construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
3409 : : {
3410 : : int elmlen;
3411 : : bool elmbyval;
3412 : : char elmalign;
3413 : :
3414 [ + + + + : 154901 : switch (elmtype)
+ + + + +
+ + + - ]
3415 : : {
3416 : 2082 : case CHAROID:
3417 : 2082 : elmlen = 1;
3418 : 2082 : elmbyval = true;
3419 : 2082 : elmalign = TYPALIGN_CHAR;
3420 : 2082 : break;
3421 : :
3422 : 4991 : case CSTRINGOID:
3423 : 4991 : elmlen = -2;
3424 : 4991 : elmbyval = false;
3425 : 4991 : elmalign = TYPALIGN_CHAR;
3426 : 4991 : break;
3427 : :
3428 : 87350 : case FLOAT4OID:
3429 : 87350 : elmlen = sizeof(float4);
3430 : 87350 : elmbyval = true;
3431 : 87350 : elmalign = TYPALIGN_INT;
3432 : 87350 : break;
3433 : :
3434 : 40 : case FLOAT8OID:
3435 : 40 : elmlen = sizeof(float8);
3436 : 40 : elmbyval = true;
3437 : 40 : elmalign = TYPALIGN_DOUBLE;
3438 : 40 : break;
3439 : :
3440 : 36563 : case INT2OID:
3441 : 36563 : elmlen = sizeof(int16);
3442 : 36563 : elmbyval = true;
3443 : 36563 : elmalign = TYPALIGN_SHORT;
3444 : 36563 : break;
3445 : :
3446 : 4299 : case INT4OID:
3447 : 4299 : elmlen = sizeof(int32);
3448 : 4299 : elmbyval = true;
3449 : 4299 : elmalign = TYPALIGN_INT;
3450 : 4299 : break;
3451 : :
3452 : 2 : case INT8OID:
3453 : 2 : elmlen = sizeof(int64);
3454 : 2 : elmbyval = true;
3455 : 2 : elmalign = TYPALIGN_DOUBLE;
3456 : 2 : break;
3457 : :
3458 : 429 : case NAMEOID:
3459 : 429 : elmlen = NAMEDATALEN;
3460 : 429 : elmbyval = false;
3461 : 429 : elmalign = TYPALIGN_CHAR;
3462 : 429 : break;
3463 : :
3464 : 11432 : case OIDOID:
3465 : : case REGTYPEOID:
3466 : 11432 : elmlen = sizeof(Oid);
3467 : 11432 : elmbyval = true;
3468 : 11432 : elmalign = TYPALIGN_INT;
3469 : 11432 : break;
3470 : :
3471 : 7643 : case TEXTOID:
3472 : 7643 : elmlen = -1;
3473 : 7643 : elmbyval = false;
3474 : 7643 : elmalign = TYPALIGN_INT;
3475 : 7643 : break;
3476 : :
3477 : 68 : case TIDOID:
3478 : 68 : elmlen = sizeof(ItemPointerData);
3479 : 68 : elmbyval = false;
3480 : 68 : elmalign = TYPALIGN_SHORT;
3481 : 68 : break;
3482 : :
3483 : 2 : case XIDOID:
3484 : 2 : elmlen = sizeof(TransactionId);
3485 : 2 : elmbyval = true;
3486 : 2 : elmalign = TYPALIGN_INT;
3487 : 2 : break;
3488 : :
3489 : 0 : default:
3490 [ # # ]: 0 : elog(ERROR, "type %u not supported by construct_array_builtin()", elmtype);
3491 : : /* keep compiler quiet */
3492 : : elmlen = 0;
3493 : : elmbyval = false;
3494 : : elmalign = 0;
3495 : : }
3496 : :
3497 : 154901 : return construct_array(elems, nelems, elmtype, elmlen, elmbyval, elmalign);
3498 : : }
3499 : :
3500 : : /*
3501 : : * construct_md_array --- simple method for constructing an array object
3502 : : * with arbitrary dimensions and possible NULLs
3503 : : *
3504 : : * elems: array of Datum items to become the array contents
3505 : : * nulls: array of is-null flags (can be NULL if no nulls)
3506 : : * ndims: number of dimensions
3507 : : * dims: integer array with size of each dimension
3508 : : * lbs: integer array with lower bound of each dimension
3509 : : * elmtype, elmlen, elmbyval, elmalign: info for the datatype of the items
3510 : : *
3511 : : * A palloc'd ndims-D array object is constructed and returned. Note that
3512 : : * elem values will be copied into the object even if pass-by-ref type.
3513 : : * Also note the result will be 0-D not ndims-D if any dims[i] = 0.
3514 : : *
3515 : : * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
3516 : : * from the system catalogs, given the elmtype. However, the caller is
3517 : : * in a better position to cache this info across multiple uses, or even
3518 : : * to hard-wire values if the element type is hard-wired.
3519 : : */
3520 : : ArrayType *
3521 : 1017276 : construct_md_array(Datum *elems,
3522 : : bool *nulls,
3523 : : int ndims,
3524 : : int *dims,
3525 : : int *lbs,
3526 : : Oid elmtype, int elmlen, bool elmbyval, char elmalign)
3527 : : {
3528 : : ArrayType *result;
3529 : : bool hasnulls;
3530 : : int32 nbytes;
3531 : : int32 dataoffset;
3532 : : int i;
3533 : : int nelems;
3534 : 1017276 : uint8 elmalignby = typalign_to_alignby(elmalign);
3535 : :
3536 [ - + ]: 1017276 : if (ndims < 0) /* we do allow zero-dimension arrays */
3537 [ # # ]: 0 : ereport(ERROR,
3538 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3539 : : errmsg("invalid number of dimensions: %d", ndims)));
3540 [ - + ]: 1017276 : if (ndims > MAXDIM)
3541 [ # # ]: 0 : ereport(ERROR,
3542 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3543 : : errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
3544 : : ndims, MAXDIM)));
3545 : :
3546 : : /* This checks for overflow of the array dimensions */
3547 : 1017276 : nelems = ArrayGetNItems(ndims, dims);
3548 : 1017276 : ArrayCheckBounds(ndims, dims, lbs);
3549 : :
3550 : : /* if ndims <= 0 or any dims[i] == 0, return empty array */
3551 [ + + ]: 1017276 : if (nelems <= 0)
3552 : 31421 : return construct_empty_array(elmtype);
3553 : :
3554 : : /* compute required space */
3555 : 985855 : nbytes = 0;
3556 : 985855 : hasnulls = false;
3557 [ + + ]: 7171173 : for (i = 0; i < nelems; i++)
3558 : : {
3559 [ + + + + ]: 6185318 : if (nulls && nulls[i])
3560 : : {
3561 : 22197 : hasnulls = true;
3562 : 22197 : continue;
3563 : : }
3564 : : /* make sure data is not toasted */
3565 [ + + ]: 6163121 : if (elmlen == -1)
3566 : 1587317 : elems[i] = PointerGetDatum(PG_DETOAST_DATUM(elems[i]));
3567 [ + + + + ]: 6163121 : nbytes = att_addlength_datum(nbytes, elmlen, elems[i]);
3568 : 6163121 : nbytes = att_nominal_alignby(nbytes, elmalignby);
3569 : : /* check for overflow of total request */
3570 [ - + ]: 6163121 : if (!AllocSizeIsValid(nbytes))
3571 [ # # ]: 0 : ereport(ERROR,
3572 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3573 : : errmsg("array size exceeds the maximum allowed (%zu)",
3574 : : MaxAllocSize)));
3575 : : }
3576 : :
3577 : : /* Allocate and initialize result array */
3578 [ + + ]: 985855 : if (hasnulls)
3579 : : {
3580 : 11998 : dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nelems);
3581 : 11998 : nbytes += dataoffset;
3582 : : }
3583 : : else
3584 : : {
3585 : 973857 : dataoffset = 0; /* marker for no null bitmap */
3586 : 973857 : nbytes += ARR_OVERHEAD_NONULLS(ndims);
3587 : : }
3588 : 985855 : result = (ArrayType *) palloc0(nbytes);
3589 : 985855 : SET_VARSIZE(result, nbytes);
3590 : 985855 : result->ndim = ndims;
3591 : 985855 : result->dataoffset = dataoffset;
3592 : 985855 : result->elemtype = elmtype;
3593 : 985855 : memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
3594 : 985855 : memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
3595 : :
3596 : 985855 : CopyArrayEls(result,
3597 : : elems, nulls, nelems,
3598 : : elmlen, elmbyval, elmalign,
3599 : : false);
3600 : :
3601 : 985855 : return result;
3602 : : }
3603 : :
3604 : : /*
3605 : : * construct_empty_array --- make a zero-dimensional array of given type
3606 : : */
3607 : : ArrayType *
3608 : 1462033 : construct_empty_array(Oid elmtype)
3609 : : {
3610 : : ArrayType *result;
3611 : :
3612 : 1462033 : result = palloc0_object(ArrayType);
3613 : 1462033 : SET_VARSIZE(result, sizeof(ArrayType));
3614 : 1462033 : result->ndim = 0;
3615 : 1462033 : result->dataoffset = 0;
3616 : 1462033 : result->elemtype = elmtype;
3617 : 1462033 : return result;
3618 : : }
3619 : :
3620 : : /*
3621 : : * construct_empty_expanded_array: make an empty expanded array
3622 : : * given only type information. (metacache can be NULL if not needed.)
3623 : : */
3624 : : ExpandedArrayHeader *
3625 : 17 : construct_empty_expanded_array(Oid element_type,
3626 : : MemoryContext parentcontext,
3627 : : ArrayMetaState *metacache)
3628 : : {
3629 : 17 : ArrayType *array = construct_empty_array(element_type);
3630 : : Datum d;
3631 : :
3632 : 17 : d = expand_array(PointerGetDatum(array), parentcontext, metacache);
3633 : 17 : pfree(array);
3634 : 17 : return (ExpandedArrayHeader *) DatumGetEOHP(d);
3635 : : }
3636 : :
3637 : : /*
3638 : : * deconstruct_array --- simple method for extracting data from an array
3639 : : *
3640 : : * array: array object to examine (must not be NULL)
3641 : : * elmtype, elmlen, elmbyval, elmalign: info for the datatype of the items
3642 : : * elemsp: return value, set to point to palloc'd array of Datum values
3643 : : * nullsp: return value, set to point to palloc'd array of isnull markers
3644 : : * nelemsp: return value, set to number of extracted values
3645 : : *
3646 : : * The caller may pass nullsp == NULL if it does not support NULLs in the
3647 : : * array. Note that this produces a very uninformative error message,
3648 : : * so do it only in cases where a NULL is really not expected.
3649 : : *
3650 : : * If array elements are pass-by-ref data type, the returned Datums will
3651 : : * be pointers into the array object.
3652 : : *
3653 : : * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
3654 : : * from the system catalogs, given the elmtype. However, the caller is
3655 : : * in a better position to cache this info across multiple uses, or even
3656 : : * to hard-wire values if the element type is hard-wired.
3657 : : */
3658 : : void
3659 : 2193832 : deconstruct_array(const ArrayType *array,
3660 : : Oid elmtype,
3661 : : int elmlen, bool elmbyval, char elmalign,
3662 : : Datum **elemsp, bool **nullsp, int *nelemsp)
3663 : : {
3664 : : Datum *elems;
3665 : : bool *nulls;
3666 : : int nelems;
3667 : : char *p;
3668 : : uint8 *bitmap;
3669 : : int bitmask;
3670 : : int i;
3671 : 2193832 : uint8 elmalignby = typalign_to_alignby(elmalign);
3672 : :
3673 : : Assert(ARR_ELEMTYPE(array) == elmtype);
3674 : :
3675 : 2193832 : nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
3676 : 2193832 : *elemsp = elems = palloc_array(Datum, nelems);
3677 [ + + ]: 2193832 : if (nullsp)
3678 : 1239066 : *nullsp = nulls = palloc0_array(bool, nelems);
3679 : : else
3680 : 954766 : nulls = NULL;
3681 : 2193832 : *nelemsp = nelems;
3682 : :
3683 [ + + ]: 2193832 : p = ARR_DATA_PTR(array);
3684 [ + + ]: 2193832 : bitmap = ARR_NULLBITMAP(array);
3685 : 2193832 : bitmask = 1;
3686 : :
3687 [ + + ]: 38810427 : for (i = 0; i < nelems; i++)
3688 : : {
3689 : : /* Get source element, checking for NULL */
3690 [ + + + + ]: 36616595 : if (bitmap && (*bitmap & bitmask) == 0)
3691 : : {
3692 : 2400 : elems[i] = (Datum) 0;
3693 [ + - ]: 2400 : if (nulls)
3694 : 2400 : nulls[i] = true;
3695 : : else
3696 [ # # ]: 0 : ereport(ERROR,
3697 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3698 : : errmsg("null array element not allowed in this context")));
3699 : : }
3700 : : else
3701 : : {
3702 : 36614195 : elems[i] = fetch_att(p, elmbyval, elmlen);
3703 [ + + + + ]: 36614195 : p = att_addlength_pointer(p, elmlen, p);
3704 : 36614195 : p = (char *) att_nominal_alignby(p, elmalignby);
3705 : : }
3706 : :
3707 : : /* advance bitmap pointer if any */
3708 [ + + ]: 36616595 : if (bitmap)
3709 : : {
3710 : 3785 : bitmask <<= 1;
3711 [ + + ]: 3785 : if (bitmask == 0x100)
3712 : : {
3713 : 52 : bitmap++;
3714 : 52 : bitmask = 1;
3715 : : }
3716 : : }
3717 : : }
3718 : 2193832 : }
3719 : :
3720 : : /*
3721 : : * Like deconstruct_array(), where elmtype must be a built-in type, and
3722 : : * elmlen/elmbyval/elmalign is looked up from hardcoded data. This is often
3723 : : * useful when manipulating arrays from/for system catalogs.
3724 : : */
3725 : : void
3726 : 344419 : deconstruct_array_builtin(const ArrayType *array,
3727 : : Oid elmtype,
3728 : : Datum **elemsp, bool **nullsp, int *nelemsp)
3729 : : {
3730 : : int elmlen;
3731 : : bool elmbyval;
3732 : : char elmalign;
3733 : :
3734 [ + + + + : 344419 : switch (elmtype)
+ + + +
- ]
3735 : : {
3736 : 14 : case CHAROID:
3737 : 14 : elmlen = 1;
3738 : 14 : elmbyval = true;
3739 : 14 : elmalign = TYPALIGN_CHAR;
3740 : 14 : break;
3741 : :
3742 : 7511 : case CSTRINGOID:
3743 : 7511 : elmlen = -2;
3744 : 7511 : elmbyval = false;
3745 : 7511 : elmalign = TYPALIGN_CHAR;
3746 : 7511 : break;
3747 : :
3748 : 20 : case FLOAT8OID:
3749 : 20 : elmlen = sizeof(float8);
3750 : 20 : elmbyval = true;
3751 : 20 : elmalign = TYPALIGN_DOUBLE;
3752 : 20 : break;
3753 : :
3754 : 3182 : case INT2OID:
3755 : 3182 : elmlen = sizeof(int16);
3756 : 3182 : elmbyval = true;
3757 : 3182 : elmalign = TYPALIGN_SHORT;
3758 : 3182 : break;
3759 : :
3760 : 200 : case INT4OID:
3761 : 200 : elmlen = sizeof(int32);
3762 : 200 : elmbyval = true;
3763 : 200 : elmalign = TYPALIGN_INT;
3764 : 200 : break;
3765 : :
3766 : 246 : case OIDOID:
3767 : 246 : elmlen = sizeof(Oid);
3768 : 246 : elmbyval = true;
3769 : 246 : elmalign = TYPALIGN_INT;
3770 : 246 : break;
3771 : :
3772 : 333217 : case TEXTOID:
3773 : 333217 : elmlen = -1;
3774 : 333217 : elmbyval = false;
3775 : 333217 : elmalign = TYPALIGN_INT;
3776 : 333217 : break;
3777 : :
3778 : 29 : case TIDOID:
3779 : 29 : elmlen = sizeof(ItemPointerData);
3780 : 29 : elmbyval = false;
3781 : 29 : elmalign = TYPALIGN_SHORT;
3782 : 29 : break;
3783 : :
3784 : 0 : default:
3785 [ # # ]: 0 : elog(ERROR, "type %u not supported by deconstruct_array_builtin()", elmtype);
3786 : : /* keep compiler quiet */
3787 : : elmlen = 0;
3788 : : elmbyval = false;
3789 : : elmalign = 0;
3790 : : }
3791 : :
3792 : 344419 : deconstruct_array(array, elmtype, elmlen, elmbyval, elmalign, elemsp, nullsp, nelemsp);
3793 : 344419 : }
3794 : :
3795 : : /*
3796 : : * array_contains_nulls --- detect whether an array has any null elements
3797 : : *
3798 : : * This gives an accurate answer, whereas testing ARR_HASNULL only tells
3799 : : * if the array *might* contain a null.
3800 : : */
3801 : : bool
3802 : 41280 : array_contains_nulls(const ArrayType *array)
3803 : : {
3804 : : int nelems;
3805 : : uint8 *bitmap;
3806 : : int bitmask;
3807 : :
3808 : : /* Easy answer if there's no null bitmap */
3809 [ + + ]: 41280 : if (!ARR_HASNULL(array))
3810 : 41228 : return false;
3811 : :
3812 : 52 : nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
3813 : :
3814 [ + - ]: 52 : bitmap = ARR_NULLBITMAP(array);
3815 : :
3816 : : /* check whole bytes of the bitmap byte-at-a-time */
3817 [ + + ]: 52 : while (nelems >= 8)
3818 : : {
3819 [ + - ]: 14 : if (*bitmap != 0xFF)
3820 : 14 : return true;
3821 : 0 : bitmap++;
3822 : 0 : nelems -= 8;
3823 : : }
3824 : :
3825 : : /* check last partial byte */
3826 : 38 : bitmask = 1;
3827 [ + - ]: 93 : while (nelems > 0)
3828 : : {
3829 [ + + ]: 93 : if ((*bitmap & bitmask) == 0)
3830 : 38 : return true;
3831 : 55 : bitmask <<= 1;
3832 : 55 : nelems--;
3833 : : }
3834 : :
3835 : 0 : return false;
3836 : : }
3837 : :
3838 : :
3839 : : /*
3840 : : * array_eq :
3841 : : * compares two arrays for equality
3842 : : * result :
3843 : : * returns true if the arrays are equal, false otherwise.
3844 : : *
3845 : : * Note: we do not use array_cmp here, since equality may be meaningful in
3846 : : * datatypes that don't have a total ordering (and hence no btree support).
3847 : : */
3848 : : Datum
3849 : 157332 : array_eq(PG_FUNCTION_ARGS)
3850 : : {
3851 : 157332 : LOCAL_FCINFO(locfcinfo, 2);
3852 : 157332 : AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
3853 : 157332 : AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
3854 : 157332 : Oid collation = PG_GET_COLLATION();
3855 [ + + ]: 157332 : int ndims1 = AARR_NDIM(array1);
3856 [ + + ]: 157332 : int ndims2 = AARR_NDIM(array2);
3857 [ + + ]: 157332 : int *dims1 = AARR_DIMS(array1);
3858 [ + + ]: 157332 : int *dims2 = AARR_DIMS(array2);
3859 [ + + ]: 157332 : int *lbs1 = AARR_LBOUND(array1);
3860 [ + + ]: 157332 : int *lbs2 = AARR_LBOUND(array2);
3861 [ + + ]: 157332 : Oid element_type = AARR_ELEMTYPE(array1);
3862 : 157332 : bool result = true;
3863 : : int nitems;
3864 : : TypeCacheEntry *typentry;
3865 : : int typlen;
3866 : : bool typbyval;
3867 : : char typalign;
3868 : : array_iter it1;
3869 : : array_iter it2;
3870 : : int i;
3871 : :
3872 [ + + - + ]: 157332 : if (element_type != AARR_ELEMTYPE(array2))
3873 [ # # ]: 0 : ereport(ERROR,
3874 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3875 : : errmsg("cannot compare arrays of different element types")));
3876 : :
3877 : : /* fast path if the arrays do not have the same dimensionality */
3878 [ + + ]: 157332 : if (ndims1 != ndims2 ||
3879 [ + + ]: 149733 : memcmp(dims1, dims2, ndims1 * sizeof(int)) != 0 ||
3880 [ - + ]: 113174 : memcmp(lbs1, lbs2, ndims1 * sizeof(int)) != 0)
3881 : 44158 : result = false;
3882 : : else
3883 : : {
3884 : : /*
3885 : : * We arrange to look up the equality function only once per series of
3886 : : * calls, assuming the element type doesn't change underneath us. The
3887 : : * typcache is used so that we have no memory leakage when being used
3888 : : * as an index support function.
3889 : : */
3890 : 113174 : typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
3891 [ + + ]: 113174 : if (typentry == NULL ||
3892 [ - + ]: 111375 : typentry->type_id != element_type)
3893 : : {
3894 : 1799 : typentry = lookup_type_cache(element_type,
3895 : : TYPECACHE_EQ_OPR_FINFO);
3896 [ - + ]: 1799 : if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
3897 [ # # ]: 0 : ereport(ERROR,
3898 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
3899 : : errmsg("could not identify an equality operator for type %s",
3900 : : format_type_be(element_type))));
3901 : 1799 : fcinfo->flinfo->fn_extra = typentry;
3902 : : }
3903 : 113174 : typlen = typentry->typlen;
3904 : 113174 : typbyval = typentry->typbyval;
3905 : 113174 : typalign = typentry->typalign;
3906 : :
3907 : : /*
3908 : : * apply the operator to each pair of array elements.
3909 : : */
3910 : 113174 : InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
3911 : : collation, NULL, NULL);
3912 : :
3913 : : /* Loop over source data */
3914 : 113174 : nitems = ArrayGetNItems(ndims1, dims1);
3915 : 113174 : array_iter_setup(&it1, array1, typlen, typbyval, typalign);
3916 : 113174 : array_iter_setup(&it2, array2, typlen, typbyval, typalign);
3917 : :
3918 [ + + ]: 267671 : for (i = 0; i < nitems; i++)
3919 : : {
3920 : : Datum elt1;
3921 : : Datum elt2;
3922 : : bool isnull1;
3923 : : bool isnull2;
3924 : : bool oprresult;
3925 : :
3926 : : /* Get elements, checking for NULL */
3927 : 175419 : elt1 = array_iter_next(&it1, &isnull1, i);
3928 : 175419 : elt2 = array_iter_next(&it2, &isnull2, i);
3929 : :
3930 : : /*
3931 : : * We consider two NULLs equal; NULL and not-NULL are unequal.
3932 : : */
3933 [ + + + - ]: 175419 : if (isnull1 && isnull2)
3934 : 29 : continue;
3935 [ + - + + ]: 175390 : if (isnull1 || isnull2)
3936 : : {
3937 : 72 : result = false;
3938 : 20922 : break;
3939 : : }
3940 : :
3941 : : /*
3942 : : * Apply the operator to the element pair; treat NULL as false
3943 : : */
3944 : 175318 : locfcinfo->args[0].value = elt1;
3945 : 175318 : locfcinfo->args[0].isnull = false;
3946 : 175318 : locfcinfo->args[1].value = elt2;
3947 : 175318 : locfcinfo->args[1].isnull = false;
3948 : 175318 : locfcinfo->isnull = false;
3949 : 175318 : oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
3950 [ + - + + ]: 175318 : if (locfcinfo->isnull || !oprresult)
3951 : : {
3952 : 20850 : result = false;
3953 : 20850 : break;
3954 : : }
3955 : : }
3956 : : }
3957 : :
3958 : : /* Avoid leaking memory when handed toasted input. */
3959 [ + + + + ]: 157332 : AARR_FREE_IF_COPY(array1, 0);
3960 [ + + + + ]: 157332 : AARR_FREE_IF_COPY(array2, 1);
3961 : :
3962 : 157332 : PG_RETURN_BOOL(result);
3963 : : }
3964 : :
3965 : :
3966 : : /*-----------------------------------------------------------------------------
3967 : : * array-array bool operators:
3968 : : * Given two arrays, iterate comparison operators
3969 : : * over the array. Uses logic similar to text comparison
3970 : : * functions, except element-by-element instead of
3971 : : * character-by-character.
3972 : : *----------------------------------------------------------------------------
3973 : : */
3974 : :
3975 : : Datum
3976 : 700 : array_ne(PG_FUNCTION_ARGS)
3977 : : {
3978 : 700 : PG_RETURN_BOOL(!DatumGetBool(array_eq(fcinfo)));
3979 : : }
3980 : :
3981 : : Datum
3982 : 4404 : array_lt(PG_FUNCTION_ARGS)
3983 : : {
3984 : 4404 : PG_RETURN_BOOL(array_cmp(fcinfo) < 0);
3985 : : }
3986 : :
3987 : : Datum
3988 : 12 : array_gt(PG_FUNCTION_ARGS)
3989 : : {
3990 : 12 : PG_RETURN_BOOL(array_cmp(fcinfo) > 0);
3991 : : }
3992 : :
3993 : : Datum
3994 : 12 : array_le(PG_FUNCTION_ARGS)
3995 : : {
3996 : 12 : PG_RETURN_BOOL(array_cmp(fcinfo) <= 0);
3997 : : }
3998 : :
3999 : : Datum
4000 : 12 : array_ge(PG_FUNCTION_ARGS)
4001 : : {
4002 : 12 : PG_RETURN_BOOL(array_cmp(fcinfo) >= 0);
4003 : : }
4004 : :
4005 : : Datum
4006 : 5431777 : btarraycmp(PG_FUNCTION_ARGS)
4007 : : {
4008 : 5431777 : PG_RETURN_INT32(array_cmp(fcinfo));
4009 : : }
4010 : :
4011 : : /*
4012 : : * array_cmp()
4013 : : * Internal comparison function for arrays.
4014 : : *
4015 : : * Returns -1, 0 or 1
4016 : : */
4017 : : static int
4018 : 5436581 : array_cmp(FunctionCallInfo fcinfo)
4019 : : {
4020 : 5436581 : LOCAL_FCINFO(locfcinfo, 2);
4021 : 5436581 : AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
4022 : 5436581 : AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
4023 : 5436581 : Oid collation = PG_GET_COLLATION();
4024 [ - + ]: 5436581 : int ndims1 = AARR_NDIM(array1);
4025 [ - + ]: 5436581 : int ndims2 = AARR_NDIM(array2);
4026 [ - + ]: 5436581 : int *dims1 = AARR_DIMS(array1);
4027 [ - + ]: 5436581 : int *dims2 = AARR_DIMS(array2);
4028 : 5436581 : int nitems1 = ArrayGetNItems(ndims1, dims1);
4029 : 5436581 : int nitems2 = ArrayGetNItems(ndims2, dims2);
4030 [ - + ]: 5436581 : Oid element_type = AARR_ELEMTYPE(array1);
4031 : 5436581 : int result = 0;
4032 : : TypeCacheEntry *typentry;
4033 : : int typlen;
4034 : : bool typbyval;
4035 : : char typalign;
4036 : : int min_nitems;
4037 : : array_iter it1;
4038 : : array_iter it2;
4039 : : int i;
4040 : :
4041 [ - + + + ]: 5436581 : if (element_type != AARR_ELEMTYPE(array2))
4042 [ + - ]: 4 : ereport(ERROR,
4043 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
4044 : : errmsg("cannot compare arrays of different element types")));
4045 : :
4046 : : /*
4047 : : * We arrange to look up the comparison function only once per series of
4048 : : * calls, assuming the element type doesn't change underneath us. The
4049 : : * typcache is used so that we have no memory leakage when being used as
4050 : : * an index support function.
4051 : : */
4052 : 5436577 : typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
4053 [ + + ]: 5436577 : if (typentry == NULL ||
4054 [ - + ]: 5434958 : typentry->type_id != element_type)
4055 : : {
4056 : 1619 : typentry = lookup_type_cache(element_type,
4057 : : TYPECACHE_CMP_PROC_FINFO);
4058 [ + + ]: 1619 : if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
4059 [ + - ]: 4 : ereport(ERROR,
4060 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
4061 : : errmsg("could not identify a comparison function for type %s",
4062 : : format_type_be(element_type))));
4063 : 1615 : fcinfo->flinfo->fn_extra = typentry;
4064 : : }
4065 : 5436573 : typlen = typentry->typlen;
4066 : 5436573 : typbyval = typentry->typbyval;
4067 : 5436573 : typalign = typentry->typalign;
4068 : :
4069 : : /*
4070 : : * apply the operator to each pair of array elements.
4071 : : */
4072 : 5436573 : InitFunctionCallInfoData(*locfcinfo, &typentry->cmp_proc_finfo, 2,
4073 : : collation, NULL, NULL);
4074 : :
4075 : : /* Loop over source data */
4076 : 5436573 : min_nitems = Min(nitems1, nitems2);
4077 : 5436573 : array_iter_setup(&it1, array1, typlen, typbyval, typalign);
4078 : 5436573 : array_iter_setup(&it2, array2, typlen, typbyval, typalign);
4079 : :
4080 [ + + ]: 11323216 : for (i = 0; i < min_nitems; i++)
4081 : : {
4082 : : Datum elt1;
4083 : : Datum elt2;
4084 : : bool isnull1;
4085 : : bool isnull2;
4086 : : int32 cmpresult;
4087 : :
4088 : : /* Get elements, checking for NULL */
4089 : 9761307 : elt1 = array_iter_next(&it1, &isnull1, i);
4090 : 9761307 : elt2 = array_iter_next(&it2, &isnull2, i);
4091 : :
4092 : : /*
4093 : : * We consider two NULLs equal; NULL > not-NULL.
4094 : : */
4095 [ + + + + ]: 9761307 : if (isnull1 && isnull2)
4096 : 5886643 : continue;
4097 [ + + ]: 9761294 : if (isnull1)
4098 : : {
4099 : : /* arg1 is greater than arg2 */
4100 : 144 : result = 1;
4101 : 3874664 : break;
4102 : : }
4103 [ + + ]: 9761150 : if (isnull2)
4104 : : {
4105 : : /* arg1 is less than arg2 */
4106 : 230 : result = -1;
4107 : 230 : break;
4108 : : }
4109 : :
4110 : : /* Compare the pair of elements */
4111 : 9760920 : locfcinfo->args[0].value = elt1;
4112 : 9760920 : locfcinfo->args[0].isnull = false;
4113 : 9760920 : locfcinfo->args[1].value = elt2;
4114 : 9760920 : locfcinfo->args[1].isnull = false;
4115 : 9760920 : cmpresult = DatumGetInt32(FunctionCallInvoke(locfcinfo));
4116 : :
4117 : : /* We don't expect comparison support functions to return null */
4118 : : Assert(!locfcinfo->isnull);
4119 : :
4120 [ + + ]: 9760920 : if (cmpresult == 0)
4121 : 5886630 : continue; /* equal */
4122 : :
4123 [ + + ]: 3874290 : if (cmpresult < 0)
4124 : : {
4125 : : /* arg1 is less than arg2 */
4126 : 2215179 : result = -1;
4127 : 2215179 : break;
4128 : : }
4129 : : else
4130 : : {
4131 : : /* arg1 is greater than arg2 */
4132 : 1659111 : result = 1;
4133 : 1659111 : break;
4134 : : }
4135 : : }
4136 : :
4137 : : /*
4138 : : * If arrays contain same data (up to end of shorter one), apply
4139 : : * additional rules to sort by dimensionality. The relative significance
4140 : : * of the different bits of information is historical; mainly we just care
4141 : : * that we don't say "equal" for arrays of different dimensionality.
4142 : : */
4143 [ + + ]: 5436573 : if (result == 0)
4144 : : {
4145 [ + + ]: 1561909 : if (nitems1 != nitems2)
4146 [ + + ]: 133545 : result = (nitems1 < nitems2) ? -1 : 1;
4147 [ - + ]: 1428364 : else if (ndims1 != ndims2)
4148 [ # # ]: 0 : result = (ndims1 < ndims2) ? -1 : 1;
4149 : : else
4150 : : {
4151 [ + + ]: 2856701 : for (i = 0; i < ndims1; i++)
4152 : : {
4153 [ - + ]: 1428337 : if (dims1[i] != dims2[i])
4154 : : {
4155 [ # # ]: 0 : result = (dims1[i] < dims2[i]) ? -1 : 1;
4156 : 0 : break;
4157 : : }
4158 : : }
4159 [ + - ]: 1428364 : if (result == 0)
4160 : : {
4161 [ - + ]: 1428364 : int *lbound1 = AARR_LBOUND(array1);
4162 [ - + ]: 1428364 : int *lbound2 = AARR_LBOUND(array2);
4163 : :
4164 [ + + ]: 2856701 : for (i = 0; i < ndims1; i++)
4165 : : {
4166 [ - + ]: 1428337 : if (lbound1[i] != lbound2[i])
4167 : : {
4168 [ # # ]: 0 : result = (lbound1[i] < lbound2[i]) ? -1 : 1;
4169 : 0 : break;
4170 : : }
4171 : : }
4172 : : }
4173 : : }
4174 : : }
4175 : :
4176 : : /* Avoid leaking memory when handed toasted input. */
4177 [ + - + + ]: 5436573 : AARR_FREE_IF_COPY(array1, 0);
4178 [ + - + + ]: 5436573 : AARR_FREE_IF_COPY(array2, 1);
4179 : :
4180 : 5436573 : return result;
4181 : : }
4182 : :
4183 : :
4184 : : /*-----------------------------------------------------------------------------
4185 : : * array hashing
4186 : : * Hash the elements and combine the results.
4187 : : *----------------------------------------------------------------------------
4188 : : */
4189 : :
4190 : : Datum
4191 : 41546 : hash_array(PG_FUNCTION_ARGS)
4192 : : {
4193 : 41546 : LOCAL_FCINFO(locfcinfo, 1);
4194 : 41546 : AnyArrayType *array = PG_GETARG_ANY_ARRAY_P(0);
4195 [ + + ]: 41546 : int ndims = AARR_NDIM(array);
4196 [ + + ]: 41546 : int *dims = AARR_DIMS(array);
4197 [ + + ]: 41546 : Oid element_type = AARR_ELEMTYPE(array);
4198 : 41546 : uint32 result = 1;
4199 : : int nitems;
4200 : : TypeCacheEntry *typentry;
4201 : : int typlen;
4202 : : bool typbyval;
4203 : : char typalign;
4204 : : int i;
4205 : : array_iter iter;
4206 : :
4207 : : /*
4208 : : * We arrange to look up the hash function only once per series of calls,
4209 : : * assuming the element type doesn't change underneath us. The typcache
4210 : : * is used so that we have no memory leakage when being used as an index
4211 : : * support function.
4212 : : */
4213 : 41546 : typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
4214 [ + + ]: 41546 : if (typentry == NULL ||
4215 [ - + ]: 41064 : typentry->type_id != element_type)
4216 : : {
4217 : 482 : typentry = lookup_type_cache(element_type,
4218 : : TYPECACHE_HASH_PROC_FINFO);
4219 [ + + + + ]: 482 : if (!OidIsValid(typentry->hash_proc_finfo.fn_oid) && element_type != RECORDOID)
4220 [ + - ]: 4 : ereport(ERROR,
4221 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
4222 : : errmsg("could not identify a hash function for type %s",
4223 : : format_type_be(element_type))));
4224 : :
4225 : : /*
4226 : : * The type cache doesn't believe that record is hashable (see
4227 : : * cache_record_field_properties()), but since we're here, we're
4228 : : * committed to hashing, so we can assume it does. Worst case, if any
4229 : : * components of the record don't support hashing, we will fail at
4230 : : * execution.
4231 : : */
4232 [ + + ]: 478 : if (element_type == RECORDOID)
4233 : : {
4234 : : MemoryContext oldcontext;
4235 : : TypeCacheEntry *record_typentry;
4236 : :
4237 : 12 : oldcontext = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);
4238 : :
4239 : : /*
4240 : : * Make fake type cache entry structure. Note that we can't just
4241 : : * modify typentry, since that points directly into the type
4242 : : * cache.
4243 : : */
4244 : 12 : record_typentry = palloc0_object(TypeCacheEntry);
4245 : 12 : record_typentry->type_id = element_type;
4246 : :
4247 : : /* fill in what we need below */
4248 : 12 : record_typentry->typlen = typentry->typlen;
4249 : 12 : record_typentry->typbyval = typentry->typbyval;
4250 : 12 : record_typentry->typalign = typentry->typalign;
4251 : 12 : fmgr_info(F_HASH_RECORD, &record_typentry->hash_proc_finfo);
4252 : :
4253 : 12 : MemoryContextSwitchTo(oldcontext);
4254 : :
4255 : 12 : typentry = record_typentry;
4256 : : }
4257 : :
4258 : 478 : fcinfo->flinfo->fn_extra = typentry;
4259 : : }
4260 : :
4261 : 41542 : typlen = typentry->typlen;
4262 : 41542 : typbyval = typentry->typbyval;
4263 : 41542 : typalign = typentry->typalign;
4264 : :
4265 : : /*
4266 : : * apply the hash function to each array element.
4267 : : */
4268 : 41542 : InitFunctionCallInfoData(*locfcinfo, &typentry->hash_proc_finfo, 1,
4269 : : PG_GET_COLLATION(), NULL, NULL);
4270 : :
4271 : : /* Loop over source data */
4272 : 41542 : nitems = ArrayGetNItems(ndims, dims);
4273 : 41542 : array_iter_setup(&iter, array, typlen, typbyval, typalign);
4274 : :
4275 [ + + ]: 109661 : for (i = 0; i < nitems; i++)
4276 : : {
4277 : : Datum elt;
4278 : : bool isnull;
4279 : : uint32 elthash;
4280 : :
4281 : : /* Get element, checking for NULL */
4282 : 68119 : elt = array_iter_next(&iter, &isnull, i);
4283 : :
4284 [ + + ]: 68119 : if (isnull)
4285 : : {
4286 : : /* Treat nulls as having hashvalue 0 */
4287 : 32 : elthash = 0;
4288 : : }
4289 : : else
4290 : : {
4291 : : /* Apply the hash function */
4292 : 68087 : locfcinfo->args[0].value = elt;
4293 : 68087 : locfcinfo->args[0].isnull = false;
4294 : 68087 : elthash = DatumGetUInt32(FunctionCallInvoke(locfcinfo));
4295 : : /* We don't expect hash functions to return null */
4296 : : Assert(!locfcinfo->isnull);
4297 : : }
4298 : :
4299 : : /*
4300 : : * Combine hash values of successive elements by multiplying the
4301 : : * current value by 31 and adding on the new element's hash value.
4302 : : *
4303 : : * The result is a sum in which each element's hash value is
4304 : : * multiplied by a different power of 31. This is modulo 2^32
4305 : : * arithmetic, and the powers of 31 modulo 2^32 form a cyclic group of
4306 : : * order 2^27. So for arrays of up to 2^27 elements, each element's
4307 : : * hash value is multiplied by a different (odd) number, resulting in
4308 : : * a good mixing of all the elements' hash values.
4309 : : */
4310 : 68119 : result = (result << 5) - result + elthash;
4311 : : }
4312 : :
4313 : : /* Avoid leaking memory when handed toasted input. */
4314 [ + + + + ]: 41542 : AARR_FREE_IF_COPY(array, 0);
4315 : :
4316 : 41542 : PG_RETURN_UINT32(result);
4317 : : }
4318 : :
4319 : : /*
4320 : : * Returns 64-bit value by hashing a value to a 64-bit value, with a seed.
4321 : : * Otherwise, similar to hash_array.
4322 : : */
4323 : : Datum
4324 : 100 : hash_array_extended(PG_FUNCTION_ARGS)
4325 : : {
4326 : 100 : LOCAL_FCINFO(locfcinfo, 2);
4327 : 100 : AnyArrayType *array = PG_GETARG_ANY_ARRAY_P(0);
4328 : 100 : uint64 seed = PG_GETARG_INT64(1);
4329 [ - + ]: 100 : int ndims = AARR_NDIM(array);
4330 [ - + ]: 100 : int *dims = AARR_DIMS(array);
4331 [ - + ]: 100 : Oid element_type = AARR_ELEMTYPE(array);
4332 : 100 : uint64 result = 1;
4333 : : int nitems;
4334 : : TypeCacheEntry *typentry;
4335 : : int typlen;
4336 : : bool typbyval;
4337 : : char typalign;
4338 : : int i;
4339 : : array_iter iter;
4340 : :
4341 : 100 : typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
4342 [ + + ]: 100 : if (typentry == NULL ||
4343 [ - + ]: 56 : typentry->type_id != element_type)
4344 : : {
4345 : 44 : typentry = lookup_type_cache(element_type,
4346 : : TYPECACHE_HASH_EXTENDED_PROC_FINFO);
4347 [ + + ]: 44 : if (!OidIsValid(typentry->hash_extended_proc_finfo.fn_oid))
4348 [ + - ]: 4 : ereport(ERROR,
4349 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
4350 : : errmsg("could not identify an extended hash function for type %s",
4351 : : format_type_be(element_type))));
4352 : 40 : fcinfo->flinfo->fn_extra = typentry;
4353 : : }
4354 : 96 : typlen = typentry->typlen;
4355 : 96 : typbyval = typentry->typbyval;
4356 : 96 : typalign = typentry->typalign;
4357 : :
4358 : 96 : InitFunctionCallInfoData(*locfcinfo, &typentry->hash_extended_proc_finfo, 2,
4359 : : PG_GET_COLLATION(), NULL, NULL);
4360 : :
4361 : : /* Loop over source data */
4362 : 96 : nitems = ArrayGetNItems(ndims, dims);
4363 : 96 : array_iter_setup(&iter, array, typlen, typbyval, typalign);
4364 : :
4365 [ + + ]: 314 : for (i = 0; i < nitems; i++)
4366 : : {
4367 : : Datum elt;
4368 : : bool isnull;
4369 : : uint64 elthash;
4370 : :
4371 : : /* Get element, checking for NULL */
4372 : 218 : elt = array_iter_next(&iter, &isnull, i);
4373 : :
4374 [ - + ]: 218 : if (isnull)
4375 : : {
4376 : 0 : elthash = 0;
4377 : : }
4378 : : else
4379 : : {
4380 : : /* Apply the hash function */
4381 : 218 : locfcinfo->args[0].value = elt;
4382 : 218 : locfcinfo->args[0].isnull = false;
4383 : 218 : locfcinfo->args[1].value = Int64GetDatum(seed);
4384 : 218 : locfcinfo->args[1].isnull = false;
4385 : 218 : elthash = DatumGetUInt64(FunctionCallInvoke(locfcinfo));
4386 : : /* We don't expect hash functions to return null */
4387 : : Assert(!locfcinfo->isnull);
4388 : : }
4389 : :
4390 : 218 : result = (result << 5) - result + elthash;
4391 : : }
4392 : :
4393 [ + - - + ]: 96 : AARR_FREE_IF_COPY(array, 0);
4394 : :
4395 : 96 : PG_RETURN_UINT64(result);
4396 : : }
4397 : :
4398 : :
4399 : : /*-----------------------------------------------------------------------------
4400 : : * array overlap/containment comparisons
4401 : : * These use the same methods of comparing array elements as array_eq.
4402 : : * We consider only the elements of the arrays, ignoring dimensionality.
4403 : : *----------------------------------------------------------------------------
4404 : : */
4405 : :
4406 : : /*
4407 : : * array_contain_compare :
4408 : : * compares two arrays for overlap/containment
4409 : : *
4410 : : * When matchall is true, return true if all members of array1 are in array2.
4411 : : * When matchall is false, return true if any members of array1 are in array2.
4412 : : */
4413 : : static bool
4414 : 54772 : array_contain_compare(AnyArrayType *array1, AnyArrayType *array2, Oid collation,
4415 : : bool matchall, void **fn_extra)
4416 : : {
4417 : 54772 : LOCAL_FCINFO(locfcinfo, 2);
4418 : 54772 : bool result = matchall;
4419 [ + + ]: 54772 : Oid element_type = AARR_ELEMTYPE(array1);
4420 : : TypeCacheEntry *typentry;
4421 : : int nelems1;
4422 : : Datum *values2;
4423 : : bool *nulls2;
4424 : : int nelems2;
4425 : : int typlen;
4426 : : bool typbyval;
4427 : : char typalign;
4428 : : int i;
4429 : : int j;
4430 : : array_iter it1;
4431 : :
4432 [ + + - + ]: 54772 : if (element_type != AARR_ELEMTYPE(array2))
4433 [ # # ]: 0 : ereport(ERROR,
4434 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
4435 : : errmsg("cannot compare arrays of different element types")));
4436 : :
4437 : : /*
4438 : : * We arrange to look up the equality function only once per series of
4439 : : * calls, assuming the element type doesn't change underneath us. The
4440 : : * typcache is used so that we have no memory leakage when being used as
4441 : : * an index support function.
4442 : : */
4443 : 54772 : typentry = (TypeCacheEntry *) *fn_extra;
4444 [ + + ]: 54772 : if (typentry == NULL ||
4445 [ - + ]: 54412 : typentry->type_id != element_type)
4446 : : {
4447 : 360 : typentry = lookup_type_cache(element_type,
4448 : : TYPECACHE_EQ_OPR_FINFO);
4449 [ - + ]: 360 : if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
4450 [ # # ]: 0 : ereport(ERROR,
4451 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
4452 : : errmsg("could not identify an equality operator for type %s",
4453 : : format_type_be(element_type))));
4454 : 360 : *fn_extra = typentry;
4455 : : }
4456 : 54772 : typlen = typentry->typlen;
4457 : 54772 : typbyval = typentry->typbyval;
4458 : 54772 : typalign = typentry->typalign;
4459 : :
4460 : : /*
4461 : : * Since we probably will need to scan array2 multiple times, it's
4462 : : * worthwhile to use deconstruct_array on it. We scan array1 the hard way
4463 : : * however, since we very likely won't need to look at all of it.
4464 : : */
4465 [ + + ]: 54772 : if (VARATT_IS_EXPANDED_HEADER(array2))
4466 : : {
4467 : : /* This should be safe even if input is read-only */
4468 : 3408 : deconstruct_expanded_array(&(array2->xpn));
4469 : 3408 : values2 = array2->xpn.dvalues;
4470 : 3408 : nulls2 = array2->xpn.dnulls;
4471 : 3408 : nelems2 = array2->xpn.nelems;
4472 : : }
4473 : : else
4474 : 51364 : deconstruct_array((ArrayType *) array2,
4475 : : element_type, typlen, typbyval, typalign,
4476 : : &values2, &nulls2, &nelems2);
4477 : :
4478 : : /*
4479 : : * Apply the comparison operator to each pair of array elements.
4480 : : */
4481 : 54772 : InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
4482 : : collation, NULL, NULL);
4483 : :
4484 : : /* Loop over source data */
4485 [ + + + + ]: 54772 : nelems1 = ArrayGetNItems(AARR_NDIM(array1), AARR_DIMS(array1));
4486 : 54772 : array_iter_setup(&it1, array1, typlen, typbyval, typalign);
4487 : :
4488 [ + + ]: 359900 : for (i = 0; i < nelems1; i++)
4489 : : {
4490 : : Datum elt1;
4491 : : bool isnull1;
4492 : :
4493 : : /* Get element, checking for NULL */
4494 : 311348 : elt1 = array_iter_next(&it1, &isnull1, i);
4495 : :
4496 : : /*
4497 : : * We assume that the comparison operator is strict, so a NULL can't
4498 : : * match anything. XXX this diverges from the "NULL=NULL" behavior of
4499 : : * array_eq, should we act like that?
4500 : : */
4501 [ + + ]: 311348 : if (isnull1)
4502 : : {
4503 [ + + ]: 880 : if (matchall)
4504 : : {
4505 : 840 : result = false;
4506 : 6220 : break;
4507 : : }
4508 : 40 : continue;
4509 : : }
4510 : :
4511 [ + + ]: 12317185 : for (j = 0; j < nelems2; j++)
4512 : : {
4513 : 12290993 : Datum elt2 = values2[j];
4514 [ + + ]: 12290993 : bool isnull2 = nulls2 ? nulls2[j] : false;
4515 : : bool oprresult;
4516 : :
4517 [ + + ]: 12290993 : if (isnull2)
4518 : 4808 : continue; /* can't match */
4519 : :
4520 : : /*
4521 : : * Apply the operator to the element pair; treat NULL as false
4522 : : */
4523 : 12286185 : locfcinfo->args[0].value = elt1;
4524 : 12286185 : locfcinfo->args[0].isnull = false;
4525 : 12286185 : locfcinfo->args[1].value = elt2;
4526 : 12286185 : locfcinfo->args[1].isnull = false;
4527 : 12286185 : locfcinfo->isnull = false;
4528 : 12286185 : oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
4529 [ + - + + ]: 12286185 : if (!locfcinfo->isnull && oprresult)
4530 : 284276 : break;
4531 : : }
4532 : :
4533 [ + + ]: 310468 : if (j < nelems2)
4534 : : {
4535 : : /* found a match for elt1 */
4536 [ + + ]: 284276 : if (!matchall)
4537 : : {
4538 : 152 : result = true;
4539 : 152 : break;
4540 : : }
4541 : : }
4542 : : else
4543 : : {
4544 : : /* no match for elt1 */
4545 [ + + ]: 26192 : if (matchall)
4546 : : {
4547 : 5228 : result = false;
4548 : 5228 : break;
4549 : : }
4550 : : }
4551 : : }
4552 : :
4553 : 54772 : return result;
4554 : : }
4555 : :
4556 : : Datum
4557 : 4080 : arrayoverlap(PG_FUNCTION_ARGS)
4558 : : {
4559 : 4080 : AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
4560 : 4080 : AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
4561 : 4080 : Oid collation = PG_GET_COLLATION();
4562 : : bool result;
4563 : :
4564 : 4080 : result = array_contain_compare(array1, array2, collation, false,
4565 : 4080 : &fcinfo->flinfo->fn_extra);
4566 : :
4567 : : /* Avoid leaking memory when handed toasted input. */
4568 [ + - + + ]: 4080 : AARR_FREE_IF_COPY(array1, 0);
4569 [ + - - + ]: 4080 : AARR_FREE_IF_COPY(array2, 1);
4570 : :
4571 : 4080 : PG_RETURN_BOOL(result);
4572 : : }
4573 : :
4574 : : Datum
4575 : 46348 : arraycontains(PG_FUNCTION_ARGS)
4576 : : {
4577 : 46348 : AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
4578 : 46348 : AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
4579 : 46348 : Oid collation = PG_GET_COLLATION();
4580 : : bool result;
4581 : :
4582 : 46348 : result = array_contain_compare(array2, array1, collation, true,
4583 : 46348 : &fcinfo->flinfo->fn_extra);
4584 : :
4585 : : /* Avoid leaking memory when handed toasted input. */
4586 [ + + + + ]: 46348 : AARR_FREE_IF_COPY(array1, 0);
4587 [ + + - + ]: 46348 : AARR_FREE_IF_COPY(array2, 1);
4588 : :
4589 : 46348 : PG_RETURN_BOOL(result);
4590 : : }
4591 : :
4592 : : Datum
4593 : 4344 : arraycontained(PG_FUNCTION_ARGS)
4594 : : {
4595 : 4344 : AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
4596 : 4344 : AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
4597 : 4344 : Oid collation = PG_GET_COLLATION();
4598 : : bool result;
4599 : :
4600 : 4344 : result = array_contain_compare(array1, array2, collation, true,
4601 : 4344 : &fcinfo->flinfo->fn_extra);
4602 : :
4603 : : /* Avoid leaking memory when handed toasted input. */
4604 [ + + + + ]: 4344 : AARR_FREE_IF_COPY(array1, 0);
4605 [ + + - + ]: 4344 : AARR_FREE_IF_COPY(array2, 1);
4606 : :
4607 : 4344 : PG_RETURN_BOOL(result);
4608 : : }
4609 : :
4610 : :
4611 : : /*-----------------------------------------------------------------------------
4612 : : * Array iteration functions
4613 : : * These functions are used to iterate efficiently through arrays
4614 : : *-----------------------------------------------------------------------------
4615 : : */
4616 : :
4617 : : /*
4618 : : * array_create_iterator --- set up to iterate through an array
4619 : : *
4620 : : * If slice_ndim is zero, we will iterate element-by-element; the returned
4621 : : * datums are of the array's element type.
4622 : : *
4623 : : * If slice_ndim is 1..ARR_NDIM(arr), we will iterate by slices: the
4624 : : * returned datums are of the same array type as 'arr', but of size
4625 : : * equal to the rightmost N dimensions of 'arr'.
4626 : : *
4627 : : * The passed-in array must remain valid for the lifetime of the iterator.
4628 : : */
4629 : : ArrayIterator
4630 : 370 : array_create_iterator(ArrayType *arr, int slice_ndim, ArrayMetaState *mstate)
4631 : : {
4632 : 370 : ArrayIterator iterator = palloc0_object(ArrayIteratorData);
4633 : :
4634 : : /*
4635 : : * Sanity-check inputs --- caller should have got this right already
4636 : : */
4637 : : Assert(arr);
4638 [ + - - + ]: 370 : if (slice_ndim < 0 || slice_ndim > ARR_NDIM(arr))
4639 [ # # ]: 0 : elog(ERROR, "invalid arguments to array_create_iterator");
4640 : :
4641 : : /*
4642 : : * Remember basic info about the array and its element type
4643 : : */
4644 : 370 : iterator->arr = arr;
4645 [ + + ]: 370 : iterator->nullbitmap = ARR_NULLBITMAP(arr);
4646 : 370 : iterator->nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
4647 : :
4648 [ + + ]: 370 : if (mstate != NULL)
4649 : : {
4650 : : Assert(mstate->element_type == ARR_ELEMTYPE(arr));
4651 : :
4652 : 261 : iterator->typlen = mstate->typlen;
4653 : 261 : iterator->typbyval = mstate->typbyval;
4654 : 261 : iterator->typalign = mstate->typalign;
4655 : : }
4656 : : else
4657 : 109 : get_typlenbyvalalign(ARR_ELEMTYPE(arr),
4658 : : &iterator->typlen,
4659 : : &iterator->typbyval,
4660 : : &iterator->typalign);
4661 : 370 : iterator->typalignby = typalign_to_alignby(iterator->typalign);
4662 : :
4663 : : /*
4664 : : * Remember the slicing parameters.
4665 : : */
4666 : 370 : iterator->slice_ndim = slice_ndim;
4667 : :
4668 [ + + ]: 370 : if (slice_ndim > 0)
4669 : : {
4670 : : /*
4671 : : * Get pointers into the array's dims and lbound arrays to represent
4672 : : * the dims/lbound arrays of a slice. These are the same as the
4673 : : * rightmost N dimensions of the array.
4674 : : */
4675 : 58 : iterator->slice_dims = ARR_DIMS(arr) + ARR_NDIM(arr) - slice_ndim;
4676 : 58 : iterator->slice_lbound = ARR_LBOUND(arr) + ARR_NDIM(arr) - slice_ndim;
4677 : :
4678 : : /*
4679 : : * Compute number of elements in a slice.
4680 : : */
4681 : 116 : iterator->slice_len = ArrayGetNItems(slice_ndim,
4682 : 58 : iterator->slice_dims);
4683 : :
4684 : : /*
4685 : : * Create workspace for building sub-arrays.
4686 : : */
4687 : 58 : iterator->slice_values = palloc_array(Datum, iterator->slice_len);
4688 : 58 : iterator->slice_nulls = palloc_array(bool, iterator->slice_len);
4689 : : }
4690 : :
4691 : : /*
4692 : : * Initialize our data pointer and linear element number. These will
4693 : : * advance through the array during array_iterate().
4694 : : */
4695 [ + + ]: 370 : iterator->data_ptr = ARR_DATA_PTR(arr);
4696 : 370 : iterator->current_item = 0;
4697 : :
4698 : 370 : return iterator;
4699 : : }
4700 : :
4701 : : /*
4702 : : * Iterate through the array referenced by 'iterator'.
4703 : : *
4704 : : * As long as there is another element (or slice), return it into
4705 : : * *value / *isnull, and return true. Return false when no more data.
4706 : : */
4707 : : bool
4708 : 5223 : array_iterate(ArrayIterator iterator, Datum *value, bool *isnull)
4709 : : {
4710 : : /* Done if we have reached the end of the array */
4711 [ + + ]: 5223 : if (iterator->current_item >= iterator->nitems)
4712 : 261 : return false;
4713 : :
4714 [ + + ]: 4962 : if (iterator->slice_ndim == 0)
4715 : : {
4716 : : /*
4717 : : * Scalar case: return one element.
4718 : : */
4719 [ + + ]: 4843 : if (array_get_isnull(iterator->nullbitmap, iterator->current_item++))
4720 : : {
4721 : 55 : *isnull = true;
4722 : 55 : *value = (Datum) 0;
4723 : : }
4724 : : else
4725 : : {
4726 : : /* non-NULL, so fetch the individual Datum to return */
4727 : 4788 : char *p = iterator->data_ptr;
4728 : :
4729 : 4788 : *isnull = false;
4730 : 4788 : *value = fetch_att(p, iterator->typbyval, iterator->typlen);
4731 : :
4732 : : /* Move our data pointer forward to the next element */
4733 [ + + + - ]: 4788 : p = att_addlength_pointer(p, iterator->typlen, p);
4734 : 4788 : p = (char *) att_nominal_alignby(p, iterator->typalignby);
4735 : 4788 : iterator->data_ptr = p;
4736 : : }
4737 : : }
4738 : : else
4739 : : {
4740 : : /*
4741 : : * Slice case: build and return an array of the requested size.
4742 : : */
4743 : : ArrayType *result;
4744 : 119 : Datum *values = iterator->slice_values;
4745 : 119 : bool *nulls = iterator->slice_nulls;
4746 : 119 : char *p = iterator->data_ptr;
4747 : : int i;
4748 : :
4749 [ + + ]: 375 : for (i = 0; i < iterator->slice_len; i++)
4750 : : {
4751 [ - + ]: 256 : if (array_get_isnull(iterator->nullbitmap,
4752 : 256 : iterator->current_item++))
4753 : : {
4754 : 0 : nulls[i] = true;
4755 : 0 : values[i] = (Datum) 0;
4756 : : }
4757 : : else
4758 : : {
4759 : 256 : nulls[i] = false;
4760 : 256 : values[i] = fetch_att(p, iterator->typbyval, iterator->typlen);
4761 : :
4762 : : /* Move our data pointer forward to the next element */
4763 [ + + + - ]: 256 : p = att_addlength_pointer(p, iterator->typlen, p);
4764 : 256 : p = (char *) att_nominal_alignby(p, iterator->typalignby);
4765 : : }
4766 : : }
4767 : :
4768 : 119 : iterator->data_ptr = p;
4769 : :
4770 : 119 : result = construct_md_array(values,
4771 : : nulls,
4772 : : iterator->slice_ndim,
4773 : : iterator->slice_dims,
4774 : : iterator->slice_lbound,
4775 : 119 : ARR_ELEMTYPE(iterator->arr),
4776 : 119 : iterator->typlen,
4777 : 119 : iterator->typbyval,
4778 : 119 : iterator->typalign);
4779 : :
4780 : 119 : *isnull = false;
4781 : 119 : *value = PointerGetDatum(result);
4782 : : }
4783 : :
4784 : 4962 : return true;
4785 : : }
4786 : :
4787 : : /*
4788 : : * Release an ArrayIterator data structure
4789 : : */
4790 : : void
4791 : 261 : array_free_iterator(ArrayIterator iterator)
4792 : : {
4793 [ + + ]: 261 : if (iterator->slice_ndim > 0)
4794 : : {
4795 : 34 : pfree(iterator->slice_values);
4796 : 34 : pfree(iterator->slice_nulls);
4797 : : }
4798 : 261 : pfree(iterator);
4799 : 261 : }
4800 : :
4801 : :
4802 : : /***************************************************************************/
4803 : : /******************| Support Routines |*****************/
4804 : : /***************************************************************************/
4805 : :
4806 : : /*
4807 : : * Check whether a specific array element is NULL
4808 : : *
4809 : : * nullbitmap: pointer to array's null bitmap (NULL if none)
4810 : : * offset: 0-based linear element number of array element
4811 : : */
4812 : : static bool
4813 : 474333 : array_get_isnull(const uint8 *nullbitmap, int offset)
4814 : : {
4815 [ + + ]: 474333 : if (nullbitmap == NULL)
4816 : 473705 : return false; /* assume not null */
4817 [ + + ]: 628 : if (nullbitmap[offset / 8] & (1 << (offset % 8)))
4818 : 501 : return false; /* not null */
4819 : 127 : return true;
4820 : : }
4821 : :
4822 : : /*
4823 : : * Set a specific array element's null-bitmap entry
4824 : : *
4825 : : * nullbitmap: pointer to array's null bitmap (mustn't be NULL)
4826 : : * offset: 0-based linear element number of array element
4827 : : * isNull: null status to set
4828 : : */
4829 : : static void
4830 : 90 : array_set_isnull(uint8 *nullbitmap, int offset, bool isNull)
4831 : : {
4832 : : int bitmask;
4833 : :
4834 : 90 : nullbitmap += offset / 8;
4835 : 90 : bitmask = 1 << (offset % 8);
4836 [ + + ]: 90 : if (isNull)
4837 : 13 : *nullbitmap &= ~bitmask;
4838 : : else
4839 : 77 : *nullbitmap |= bitmask;
4840 : 90 : }
4841 : :
4842 : : /*
4843 : : * Fetch array element at pointer, converted correctly to a Datum
4844 : : *
4845 : : * Caller must have handled case of NULL element
4846 : : */
4847 : : static Datum
4848 : 468780 : ArrayCast(char *value, bool byval, int len)
4849 : : {
4850 : 468780 : return fetch_att(value, byval, len);
4851 : : }
4852 : :
4853 : : /*
4854 : : * Copy datum to *dest and return total space used (including align padding)
4855 : : *
4856 : : * Caller must have handled case of NULL element
4857 : : */
4858 : : static int
4859 : 9638436 : ArrayCastAndSet(Datum src,
4860 : : int typlen,
4861 : : bool typbyval,
4862 : : uint8 typalignby,
4863 : : char *dest)
4864 : : {
4865 : : int inc;
4866 : :
4867 [ + + ]: 9638436 : if (typlen > 0)
4868 : : {
4869 [ + + ]: 7602185 : if (typbyval)
4870 : 4435608 : store_att_byval(dest, src, typlen);
4871 : : else
4872 : 3166577 : memmove(dest, DatumGetPointer(src), typlen);
4873 : 7602185 : inc = att_nominal_alignby(typlen, typalignby);
4874 : : }
4875 : : else
4876 : : {
4877 : : Assert(!typbyval);
4878 [ + - + + ]: 2036251 : inc = att_addlength_datum(0, typlen, src);
4879 : 2036251 : memmove(dest, DatumGetPointer(src), inc);
4880 : 2036251 : inc = att_nominal_alignby(inc, typalignby);
4881 : : }
4882 : :
4883 : 9638436 : return inc;
4884 : : }
4885 : :
4886 : : /*
4887 : : * Advance ptr over nitems array elements
4888 : : *
4889 : : * ptr: starting location in array
4890 : : * offset: 0-based linear element number of first element (the one at *ptr)
4891 : : * nullbitmap: start of array's null bitmap, or NULL if none
4892 : : * nitems: number of array elements to advance over (>= 0)
4893 : : * typlen, typbyval, typalign: storage parameters of array element datatype
4894 : : *
4895 : : * It is caller's responsibility to ensure that nitems is within range
4896 : : */
4897 : : static char *
4898 : 470434 : array_seek(char *ptr, int offset, uint8 *nullbitmap, int nitems,
4899 : : int typlen, bool typbyval, char typalign)
4900 : : {
4901 : 470434 : uint8 typalignby = typalign_to_alignby(typalign);
4902 : : int bitmask;
4903 : : int i;
4904 : :
4905 : : /* easy if fixed-size elements and no NULLs */
4906 [ + + + + ]: 470434 : if (typlen > 0 && !nullbitmap)
4907 : 330516 : return ptr + nitems * ((Size) att_nominal_alignby(typlen, typalignby));
4908 : :
4909 : : /* seems worth having separate loops for NULL and no-NULLs cases */
4910 [ + + ]: 139918 : if (nullbitmap)
4911 : : {
4912 : 402 : nullbitmap += offset / 8;
4913 : 402 : bitmask = 1 << (offset % 8);
4914 : :
4915 [ + + ]: 1234 : for (i = 0; i < nitems; i++)
4916 : : {
4917 [ + + ]: 832 : if (*nullbitmap & bitmask)
4918 : : {
4919 [ + + + - ]: 592 : ptr = att_addlength_pointer(ptr, typlen, ptr);
4920 : 592 : ptr = (char *) att_nominal_alignby(ptr, typalignby);
4921 : : }
4922 : 832 : bitmask <<= 1;
4923 [ + + ]: 832 : if (bitmask == 0x100)
4924 : : {
4925 : 32 : nullbitmap++;
4926 : 32 : bitmask = 1;
4927 : : }
4928 : : }
4929 : : }
4930 : : else
4931 : : {
4932 [ + + ]: 616598 : for (i = 0; i < nitems; i++)
4933 : : {
4934 [ - + + - ]: 477082 : ptr = att_addlength_pointer(ptr, typlen, ptr);
4935 : 477082 : ptr = (char *) att_nominal_alignby(ptr, typalignby);
4936 : : }
4937 : : }
4938 : 139918 : return ptr;
4939 : : }
4940 : :
4941 : : /*
4942 : : * Compute total size of the nitems array elements starting at *ptr
4943 : : *
4944 : : * Parameters same as for array_seek
4945 : : */
4946 : : static int
4947 : 1105 : array_nelems_size(char *ptr, int offset, uint8 *nullbitmap, int nitems,
4948 : : int typlen, bool typbyval, char typalign)
4949 : : {
4950 : 1105 : return array_seek(ptr, offset, nullbitmap, nitems,
4951 : 1105 : typlen, typbyval, typalign) - ptr;
4952 : : }
4953 : :
4954 : : /*
4955 : : * Copy nitems array elements from srcptr to destptr
4956 : : *
4957 : : * destptr: starting destination location (must be enough room!)
4958 : : * nitems: number of array elements to copy (>= 0)
4959 : : * srcptr: starting location in source array
4960 : : * offset: 0-based linear element number of first element (the one at *srcptr)
4961 : : * nullbitmap: start of source array's null bitmap, or NULL if none
4962 : : * typlen, typbyval, typalign: storage parameters of array element datatype
4963 : : *
4964 : : * Returns number of bytes copied
4965 : : *
4966 : : * NB: this does not take care of setting up the destination's null bitmap!
4967 : : */
4968 : : static int
4969 : 794 : array_copy(char *destptr, int nitems,
4970 : : char *srcptr, int offset, uint8 *nullbitmap,
4971 : : int typlen, bool typbyval, char typalign)
4972 : : {
4973 : : int numbytes;
4974 : :
4975 : 794 : numbytes = array_nelems_size(srcptr, offset, nullbitmap, nitems,
4976 : : typlen, typbyval, typalign);
4977 : 794 : memcpy(destptr, srcptr, numbytes);
4978 : 794 : return numbytes;
4979 : : }
4980 : :
4981 : : /*
4982 : : * Copy nitems null-bitmap bits from source to destination
4983 : : *
4984 : : * destbitmap: start of destination array's null bitmap (mustn't be NULL)
4985 : : * destoffset: 0-based linear element number of first dest element
4986 : : * srcbitmap: start of source array's null bitmap, or NULL if none
4987 : : * srcoffset: 0-based linear element number of first source element
4988 : : * nitems: number of bits to copy (>= 0)
4989 : : *
4990 : : * If srcbitmap is NULL then we assume the source is all-non-NULL and
4991 : : * fill 1's into the destination bitmap. Note that only the specified
4992 : : * bits in the destination map are changed, not any before or after.
4993 : : *
4994 : : * Note: this could certainly be optimized using standard bitblt methods.
4995 : : * However, it's not clear that the typical Postgres array has enough elements
4996 : : * to make it worth worrying too much. For the moment, KISS.
4997 : : */
4998 : : void
4999 : 20703 : array_bitmap_copy(uint8 *destbitmap, int destoffset,
5000 : : const uint8 *srcbitmap, int srcoffset,
5001 : : int nitems)
5002 : : {
5003 : : int destbitmask,
5004 : : destbitval,
5005 : : srcbitmask,
5006 : : srcbitval;
5007 : :
5008 : : Assert(destbitmap);
5009 [ + + ]: 20703 : if (nitems <= 0)
5010 : 128 : return; /* don't risk fetch off end of memory */
5011 : 20575 : destbitmap += destoffset / 8;
5012 : 20575 : destbitmask = 1 << (destoffset % 8);
5013 : 20575 : destbitval = *destbitmap;
5014 [ + + ]: 20575 : if (srcbitmap)
5015 : : {
5016 : 10473 : srcbitmap += srcoffset / 8;
5017 : 10473 : srcbitmask = 1 << (srcoffset % 8);
5018 : 10473 : srcbitval = *srcbitmap;
5019 [ + + ]: 49731 : while (nitems-- > 0)
5020 : : {
5021 [ + + ]: 39258 : if (srcbitval & srcbitmask)
5022 : 14940 : destbitval |= destbitmask;
5023 : : else
5024 : 24318 : destbitval &= ~destbitmask;
5025 : 39258 : destbitmask <<= 1;
5026 [ + + ]: 39258 : if (destbitmask == 0x100)
5027 : : {
5028 : 4611 : *destbitmap++ = destbitval;
5029 : 4611 : destbitmask = 1;
5030 [ + + ]: 4611 : if (nitems > 0)
5031 : 3510 : destbitval = *destbitmap;
5032 : : }
5033 : 39258 : srcbitmask <<= 1;
5034 [ + + ]: 39258 : if (srcbitmask == 0x100)
5035 : : {
5036 : 3527 : srcbitmap++;
5037 : 3527 : srcbitmask = 1;
5038 [ + + ]: 3527 : if (nitems > 0)
5039 : 3479 : srcbitval = *srcbitmap;
5040 : : }
5041 : : }
5042 [ + + ]: 10473 : if (destbitmask != 1)
5043 : 9372 : *destbitmap = destbitval;
5044 : : }
5045 : : else
5046 : : {
5047 [ + + ]: 20412 : while (nitems-- > 0)
5048 : : {
5049 : 10310 : destbitval |= destbitmask;
5050 : 10310 : destbitmask <<= 1;
5051 [ + + ]: 10310 : if (destbitmask == 0x100)
5052 : : {
5053 : 1452 : *destbitmap++ = destbitval;
5054 : 1452 : destbitmask = 1;
5055 [ - + ]: 1452 : if (nitems > 0)
5056 : 0 : destbitval = *destbitmap;
5057 : : }
5058 : : }
5059 [ + + ]: 10102 : if (destbitmask != 1)
5060 : 8650 : *destbitmap = destbitval;
5061 : : }
5062 : : }
5063 : :
5064 : : /*
5065 : : * Compute space needed for a slice of an array
5066 : : *
5067 : : * We assume the caller has verified that the slice coordinates are valid.
5068 : : */
5069 : : static int
5070 : 208 : array_slice_size(char *arraydataptr, uint8 *arraynullsptr,
5071 : : int ndim, int *dim, int *lb,
5072 : : int *st, int *endp,
5073 : : int typlen, bool typbyval, char typalign)
5074 : : {
5075 : : int src_offset,
5076 : : span[MAXDIM],
5077 : : prod[MAXDIM],
5078 : : dist[MAXDIM],
5079 : : indx[MAXDIM];
5080 : : char *ptr;
5081 : : int i,
5082 : : j,
5083 : : inc;
5084 : 208 : int count = 0;
5085 : 208 : uint8 typalignby = typalign_to_alignby(typalign);
5086 : :
5087 : 208 : mda_get_range(ndim, span, st, endp);
5088 : :
5089 : : /* Pretty easy for fixed element length without nulls ... */
5090 [ + + + + ]: 208 : if (typlen > 0 && !arraynullsptr)
5091 : 156 : return ArrayGetNItems(ndim, span) * att_nominal_alignby(typlen, typalignby);
5092 : :
5093 : : /* Else gotta do it the hard way */
5094 : 52 : src_offset = ArrayGetOffset(ndim, dim, lb, st);
5095 : 52 : ptr = array_seek(arraydataptr, 0, arraynullsptr, src_offset,
5096 : : typlen, typbyval, typalign);
5097 : 52 : mda_get_prod(ndim, dim, prod);
5098 : 52 : mda_get_offset_values(ndim, dist, prod, span);
5099 [ + + ]: 132 : for (i = 0; i < ndim; i++)
5100 : 80 : indx[i] = 0;
5101 : 52 : j = ndim - 1;
5102 : : do
5103 : : {
5104 [ - + ]: 172 : if (dist[j])
5105 : : {
5106 : 0 : ptr = array_seek(ptr, src_offset, arraynullsptr, dist[j],
5107 : : typlen, typbyval, typalign);
5108 : 0 : src_offset += dist[j];
5109 : : }
5110 [ + + ]: 172 : if (!array_get_isnull(arraynullsptr, src_offset))
5111 : : {
5112 [ + + + - ]: 164 : inc = att_addlength_pointer(0, typlen, ptr);
5113 : 164 : inc = att_nominal_alignby(inc, typalignby);
5114 : 164 : ptr += inc;
5115 : 164 : count += inc;
5116 : : }
5117 : 172 : src_offset++;
5118 [ + + ]: 172 : } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
5119 : 52 : return count;
5120 : : }
5121 : :
5122 : : /*
5123 : : * Extract a slice of an array into consecutive elements in the destination
5124 : : * array.
5125 : : *
5126 : : * We assume the caller has verified that the slice coordinates are valid,
5127 : : * allocated enough storage for the result, and initialized the header
5128 : : * of the new array.
5129 : : */
5130 : : static void
5131 : 188 : array_extract_slice(ArrayType *newarray,
5132 : : int ndim,
5133 : : int *dim,
5134 : : int *lb,
5135 : : char *arraydataptr,
5136 : : uint8 *arraynullsptr,
5137 : : int *st,
5138 : : int *endp,
5139 : : int typlen,
5140 : : bool typbyval,
5141 : : char typalign)
5142 : : {
5143 [ + + ]: 188 : char *destdataptr = ARR_DATA_PTR(newarray);
5144 [ + + ]: 188 : uint8 *destnullsptr = ARR_NULLBITMAP(newarray);
5145 : : char *srcdataptr;
5146 : : int src_offset,
5147 : : dest_offset,
5148 : : prod[MAXDIM],
5149 : : span[MAXDIM],
5150 : : dist[MAXDIM],
5151 : : indx[MAXDIM];
5152 : : int i,
5153 : : j,
5154 : : inc;
5155 : :
5156 : 188 : src_offset = ArrayGetOffset(ndim, dim, lb, st);
5157 : 188 : srcdataptr = array_seek(arraydataptr, 0, arraynullsptr, src_offset,
5158 : : typlen, typbyval, typalign);
5159 : 188 : mda_get_prod(ndim, dim, prod);
5160 : 188 : mda_get_range(ndim, span, st, endp);
5161 : 188 : mda_get_offset_values(ndim, dist, prod, span);
5162 [ + + ]: 476 : for (i = 0; i < ndim; i++)
5163 : 288 : indx[i] = 0;
5164 : 188 : dest_offset = 0;
5165 : 188 : j = ndim - 1;
5166 : : do
5167 : : {
5168 [ + + ]: 690 : if (dist[j])
5169 : : {
5170 : : /* skip unwanted elements */
5171 : 23 : srcdataptr = array_seek(srcdataptr, src_offset, arraynullsptr,
5172 : : dist[j],
5173 : : typlen, typbyval, typalign);
5174 : 23 : src_offset += dist[j];
5175 : : }
5176 : 690 : inc = array_copy(destdataptr, 1,
5177 : : srcdataptr, src_offset, arraynullsptr,
5178 : : typlen, typbyval, typalign);
5179 [ + + ]: 690 : if (destnullsptr)
5180 : 120 : array_bitmap_copy(destnullsptr, dest_offset,
5181 : : arraynullsptr, src_offset,
5182 : : 1);
5183 : 690 : destdataptr += inc;
5184 : 690 : srcdataptr += inc;
5185 : 690 : src_offset++;
5186 : 690 : dest_offset++;
5187 [ + + ]: 690 : } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
5188 : 188 : }
5189 : :
5190 : : /*
5191 : : * Insert a slice into an array.
5192 : : *
5193 : : * ndim/dim[]/lb[] are dimensions of the original array. A new array with
5194 : : * those same dimensions is to be constructed. destArray must already
5195 : : * have been allocated and its header initialized.
5196 : : *
5197 : : * st[]/endp[] identify the slice to be replaced. Elements within the slice
5198 : : * volume are taken from consecutive elements of the srcArray; elements
5199 : : * outside it are copied from origArray.
5200 : : *
5201 : : * We assume the caller has verified that the slice coordinates are valid.
5202 : : */
5203 : : static void
5204 : 20 : array_insert_slice(ArrayType *destArray,
5205 : : ArrayType *origArray,
5206 : : ArrayType *srcArray,
5207 : : int ndim,
5208 : : int *dim,
5209 : : int *lb,
5210 : : int *st,
5211 : : int *endp,
5212 : : int typlen,
5213 : : bool typbyval,
5214 : : char typalign)
5215 : : {
5216 [ - + ]: 20 : char *destPtr = ARR_DATA_PTR(destArray);
5217 [ - + ]: 20 : char *origPtr = ARR_DATA_PTR(origArray);
5218 [ - + ]: 20 : char *srcPtr = ARR_DATA_PTR(srcArray);
5219 [ - + ]: 20 : uint8 *destBitmap = ARR_NULLBITMAP(destArray);
5220 [ - + ]: 20 : uint8 *origBitmap = ARR_NULLBITMAP(origArray);
5221 [ - + ]: 20 : uint8 *srcBitmap = ARR_NULLBITMAP(srcArray);
5222 : 20 : int orignitems = ArrayGetNItems(ARR_NDIM(origArray),
5223 : : ARR_DIMS(origArray));
5224 : : int dest_offset,
5225 : : orig_offset,
5226 : : src_offset,
5227 : : prod[MAXDIM],
5228 : : span[MAXDIM],
5229 : : dist[MAXDIM],
5230 : : indx[MAXDIM];
5231 : : int i,
5232 : : j,
5233 : : inc;
5234 : :
5235 : 20 : dest_offset = ArrayGetOffset(ndim, dim, lb, st);
5236 : : /* copy items before the slice start */
5237 : 20 : inc = array_copy(destPtr, dest_offset,
5238 : : origPtr, 0, origBitmap,
5239 : : typlen, typbyval, typalign);
5240 : 20 : destPtr += inc;
5241 : 20 : origPtr += inc;
5242 [ - + ]: 20 : if (destBitmap)
5243 : 0 : array_bitmap_copy(destBitmap, 0, origBitmap, 0, dest_offset);
5244 : 20 : orig_offset = dest_offset;
5245 : 20 : mda_get_prod(ndim, dim, prod);
5246 : 20 : mda_get_range(ndim, span, st, endp);
5247 : 20 : mda_get_offset_values(ndim, dist, prod, span);
5248 [ + + ]: 68 : for (i = 0; i < ndim; i++)
5249 : 48 : indx[i] = 0;
5250 : 20 : src_offset = 0;
5251 : 20 : j = ndim - 1;
5252 : : do
5253 : : {
5254 : : /* Copy/advance over elements between here and next part of slice */
5255 [ + + ]: 52 : if (dist[j])
5256 : : {
5257 : 12 : inc = array_copy(destPtr, dist[j],
5258 : : origPtr, orig_offset, origBitmap,
5259 : : typlen, typbyval, typalign);
5260 : 12 : destPtr += inc;
5261 : 12 : origPtr += inc;
5262 [ - + ]: 12 : if (destBitmap)
5263 : 0 : array_bitmap_copy(destBitmap, dest_offset,
5264 : : origBitmap, orig_offset,
5265 : : dist[j]);
5266 : 12 : dest_offset += dist[j];
5267 : 12 : orig_offset += dist[j];
5268 : : }
5269 : : /* Copy new element at this slice position */
5270 : 52 : inc = array_copy(destPtr, 1,
5271 : : srcPtr, src_offset, srcBitmap,
5272 : : typlen, typbyval, typalign);
5273 [ - + ]: 52 : if (destBitmap)
5274 : 0 : array_bitmap_copy(destBitmap, dest_offset,
5275 : : srcBitmap, src_offset,
5276 : : 1);
5277 : 52 : destPtr += inc;
5278 : 52 : srcPtr += inc;
5279 : 52 : dest_offset++;
5280 : 52 : src_offset++;
5281 : : /* Advance over old element at this slice position */
5282 : 52 : origPtr = array_seek(origPtr, orig_offset, origBitmap, 1,
5283 : : typlen, typbyval, typalign);
5284 : 52 : orig_offset++;
5285 [ + + ]: 52 : } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
5286 : :
5287 : : /* don't miss any data at the end */
5288 : 20 : array_copy(destPtr, orignitems - orig_offset,
5289 : : origPtr, orig_offset, origBitmap,
5290 : : typlen, typbyval, typalign);
5291 [ - + ]: 20 : if (destBitmap)
5292 : 0 : array_bitmap_copy(destBitmap, dest_offset,
5293 : : origBitmap, orig_offset,
5294 : : orignitems - orig_offset);
5295 : 20 : }
5296 : :
5297 : : /*
5298 : : * initArrayResult - initialize an empty ArrayBuildState
5299 : : *
5300 : : * element_type is the array element type (must be a valid array element type)
5301 : : * rcontext is where to keep working state
5302 : : * subcontext is a flag determining whether to use a separate memory context
5303 : : *
5304 : : * Note: there are two common schemes for using accumArrayResult().
5305 : : * In the older scheme, you start with a NULL ArrayBuildState pointer, and
5306 : : * call accumArrayResult once per element. In this scheme you end up with
5307 : : * a NULL pointer if there were no elements, which you need to special-case.
5308 : : * In the newer scheme, call initArrayResult and then call accumArrayResult
5309 : : * once per element. In this scheme you always end with a non-NULL pointer
5310 : : * that you can pass to makeArrayResult; you get an empty array if there
5311 : : * were no elements. This is preferred if an empty array is what you want.
5312 : : *
5313 : : * It's possible to choose whether to create a separate memory context for the
5314 : : * array build state, or whether to allocate it directly within rcontext.
5315 : : *
5316 : : * When there are many concurrent small states (e.g. array_agg() using hash
5317 : : * aggregation of many small groups), using a separate memory context for each
5318 : : * one may result in severe memory bloat. In such cases, use the same memory
5319 : : * context to initialize all such array build states, and pass
5320 : : * subcontext=false.
5321 : : *
5322 : : * In cases when the array build states have different lifetimes, using a
5323 : : * single memory context is impractical. Instead, pass subcontext=true so that
5324 : : * the array build states can be freed individually.
5325 : : */
5326 : : ArrayBuildState *
5327 : 220202 : initArrayResult(Oid element_type, MemoryContext rcontext, bool subcontext)
5328 : : {
5329 : : /*
5330 : : * When using a subcontext, we can afford to start with a somewhat larger
5331 : : * initial array size. Without subcontexts, we'd better hope that most of
5332 : : * the states stay small ...
5333 : : */
5334 [ + + ]: 220202 : return initArrayResultWithSize(element_type, rcontext, subcontext,
5335 : : subcontext ? 64 : 8);
5336 : : }
5337 : :
5338 : : /*
5339 : : * initArrayResultWithSize
5340 : : * As initArrayResult, but allow the initial size of the allocated arrays
5341 : : * to be specified.
5342 : : */
5343 : : ArrayBuildState *
5344 : 220322 : initArrayResultWithSize(Oid element_type, MemoryContext rcontext,
5345 : : bool subcontext, int initsize)
5346 : : {
5347 : : ArrayBuildState *astate;
5348 : 220322 : MemoryContext arr_context = rcontext;
5349 : :
5350 : : /* Make a temporary context to hold all the junk */
5351 [ + + ]: 220322 : if (subcontext)
5352 : 143321 : arr_context = AllocSetContextCreate(rcontext,
5353 : : "accumArrayResult",
5354 : : ALLOCSET_DEFAULT_SIZES);
5355 : :
5356 : : astate = (ArrayBuildState *)
5357 : 220322 : MemoryContextAlloc(arr_context, sizeof(ArrayBuildState));
5358 : 220322 : astate->mcontext = arr_context;
5359 : 220322 : astate->private_cxt = subcontext;
5360 : 220322 : astate->alen = initsize;
5361 : 220322 : astate->dvalues = (Datum *)
5362 : 220322 : MemoryContextAlloc(arr_context, astate->alen * sizeof(Datum));
5363 : 220322 : astate->dnulls = (bool *)
5364 : 220322 : MemoryContextAlloc(arr_context, astate->alen * sizeof(bool));
5365 : 220322 : astate->nelems = 0;
5366 : 220322 : astate->element_type = element_type;
5367 : 220322 : get_typlenbyvalalign(element_type,
5368 : : &astate->typlen,
5369 : : &astate->typbyval,
5370 : : &astate->typalign);
5371 : :
5372 : 220322 : return astate;
5373 : : }
5374 : :
5375 : : /*
5376 : : * accumArrayResult - accumulate one (more) Datum for an array result
5377 : : *
5378 : : * astate is working state (can be NULL on first call)
5379 : : * dvalue/disnull represent the new Datum to append to the array
5380 : : * element_type is the Datum's type (must be a valid array element type)
5381 : : * rcontext is where to keep working state
5382 : : */
5383 : : ArrayBuildState *
5384 : 2228355 : accumArrayResult(ArrayBuildState *astate,
5385 : : Datum dvalue, bool disnull,
5386 : : Oid element_type,
5387 : : MemoryContext rcontext)
5388 : : {
5389 : : MemoryContext oldcontext;
5390 : :
5391 [ + + ]: 2228355 : if (astate == NULL)
5392 : : {
5393 : : /* First time through --- initialize */
5394 : 111186 : astate = initArrayResult(element_type, rcontext, true);
5395 : : }
5396 : : else
5397 : : {
5398 : : Assert(astate->element_type == element_type);
5399 : : }
5400 : :
5401 : 2228355 : oldcontext = MemoryContextSwitchTo(astate->mcontext);
5402 : :
5403 : : /* enlarge dvalues[]/dnulls[] if needed */
5404 [ + + ]: 2228355 : if (astate->nelems >= astate->alen)
5405 : : {
5406 : 46740 : astate->alen *= 2;
5407 : : /* give an array-related error if we go past MaxAllocSize */
5408 [ - + ]: 46740 : if (!AllocSizeIsValid(astate->alen * sizeof(Datum)))
5409 [ # # ]: 0 : ereport(ERROR,
5410 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5411 : : errmsg("array size exceeds the maximum allowed (%zu)",
5412 : : MaxAllocSize)));
5413 : 46740 : astate->dvalues = repalloc_array(astate->dvalues, Datum, astate->alen);
5414 : 46740 : astate->dnulls = repalloc_array(astate->dnulls, bool, astate->alen);
5415 : : }
5416 : :
5417 : : /*
5418 : : * Ensure pass-by-ref stuff is copied into mcontext; and detoast it too if
5419 : : * it's varlena. (You might think that detoasting is not needed here
5420 : : * because construct_md_array can detoast the array elements later.
5421 : : * However, we must not let construct_md_array modify the ArrayBuildState
5422 : : * because that would mean array_agg_finalfn damages its input, which is
5423 : : * verboten. Also, this way frequently saves one copying step.)
5424 : : */
5425 [ + + + + ]: 2228355 : if (!disnull && !astate->typbyval)
5426 : : {
5427 [ + + ]: 1491399 : if (astate->typlen == -1)
5428 : 1005572 : dvalue = PointerGetDatum(PG_DETOAST_DATUM_COPY(dvalue));
5429 : : else
5430 : 485827 : dvalue = datumCopy(dvalue, astate->typbyval, astate->typlen);
5431 : : }
5432 : :
5433 : 2228355 : astate->dvalues[astate->nelems] = dvalue;
5434 : 2228355 : astate->dnulls[astate->nelems] = disnull;
5435 : 2228355 : astate->nelems++;
5436 : :
5437 : 2228355 : MemoryContextSwitchTo(oldcontext);
5438 : :
5439 : 2228355 : return astate;
5440 : : }
5441 : :
5442 : : /*
5443 : : * makeArrayResult - produce 1-D final result of accumArrayResult
5444 : : *
5445 : : * Note: only releases astate if it was initialized within a separate memory
5446 : : * context (i.e. using subcontext=true when calling initArrayResult).
5447 : : *
5448 : : * astate is working state (must not be NULL)
5449 : : * rcontext is where to construct result
5450 : : */
5451 : : Datum
5452 : 111324 : makeArrayResult(ArrayBuildState *astate,
5453 : : MemoryContext rcontext)
5454 : : {
5455 : : int ndims;
5456 : : int dims[1];
5457 : : int lbs[1];
5458 : :
5459 : : /* If no elements were presented, we want to create an empty array */
5460 : 111324 : ndims = (astate->nelems > 0) ? 1 : 0;
5461 : 111324 : dims[0] = astate->nelems;
5462 : 111324 : lbs[0] = 1;
5463 : :
5464 : 222648 : return makeMdArrayResult(astate, ndims, dims, lbs, rcontext,
5465 : 111324 : astate->private_cxt);
5466 : : }
5467 : :
5468 : : /*
5469 : : * makeMdArrayResult - produce multi-D final result of accumArrayResult
5470 : : *
5471 : : * beware: no check that specified dimensions match the number of values
5472 : : * accumulated.
5473 : : *
5474 : : * Note: if the astate was not initialized within a separate memory context
5475 : : * (that is, initArrayResult was called with subcontext=false), then using
5476 : : * release=true is illegal. Instead, release astate along with the rest of its
5477 : : * context when appropriate.
5478 : : *
5479 : : * astate is working state (must not be NULL)
5480 : : * rcontext is where to construct result
5481 : : * release is true if okay to release working state
5482 : : */
5483 : : Datum
5484 : 219442 : makeMdArrayResult(ArrayBuildState *astate,
5485 : : int ndims,
5486 : : int *dims,
5487 : : int *lbs,
5488 : : MemoryContext rcontext,
5489 : : bool release)
5490 : : {
5491 : : ArrayType *result;
5492 : : MemoryContext oldcontext;
5493 : :
5494 : : /* Build the final array result in rcontext */
5495 : 219442 : oldcontext = MemoryContextSwitchTo(rcontext);
5496 : :
5497 : 219442 : result = construct_md_array(astate->dvalues,
5498 : : astate->dnulls,
5499 : : ndims,
5500 : : dims,
5501 : : lbs,
5502 : : astate->element_type,
5503 : 219442 : astate->typlen,
5504 : 219442 : astate->typbyval,
5505 : 219442 : astate->typalign);
5506 : :
5507 : 219442 : MemoryContextSwitchTo(oldcontext);
5508 : :
5509 : : /* Clean up all the junk */
5510 [ + + ]: 219442 : if (release)
5511 : : {
5512 : : Assert(astate->private_cxt);
5513 : 142913 : MemoryContextDelete(astate->mcontext);
5514 : : }
5515 : :
5516 : 219442 : return PointerGetDatum(result);
5517 : : }
5518 : :
5519 : : /*
5520 : : * The following three functions provide essentially the same API as
5521 : : * initArrayResult/accumArrayResult/makeArrayResult, but instead of accepting
5522 : : * inputs that are array elements, they accept inputs that are arrays and
5523 : : * produce an output array having N+1 dimensions. The inputs must all have
5524 : : * identical dimensionality as well as element type.
5525 : : */
5526 : :
5527 : : /*
5528 : : * initArrayResultArr - initialize an empty ArrayBuildStateArr
5529 : : *
5530 : : * array_type is the array type (must be a valid varlena array type)
5531 : : * element_type is the type of the array's elements (lookup if InvalidOid)
5532 : : * rcontext is where to keep working state
5533 : : * subcontext is a flag determining whether to use a separate memory context
5534 : : */
5535 : : ArrayBuildStateArr *
5536 : 428 : initArrayResultArr(Oid array_type, Oid element_type, MemoryContext rcontext,
5537 : : bool subcontext)
5538 : : {
5539 : : ArrayBuildStateArr *astate;
5540 : 428 : MemoryContext arr_context = rcontext; /* by default use the parent ctx */
5541 : :
5542 : : /* Lookup element type, unless element_type already provided */
5543 [ + + ]: 428 : if (!OidIsValid(element_type))
5544 : : {
5545 : 348 : element_type = get_element_type(array_type);
5546 : :
5547 [ - + ]: 348 : if (!OidIsValid(element_type))
5548 [ # # ]: 0 : ereport(ERROR,
5549 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
5550 : : errmsg("data type %s is not an array type",
5551 : : format_type_be(array_type))));
5552 : : }
5553 : :
5554 : : /* Make a temporary context to hold all the junk */
5555 [ + + ]: 428 : if (subcontext)
5556 : 38 : arr_context = AllocSetContextCreate(rcontext,
5557 : : "accumArrayResultArr",
5558 : : ALLOCSET_DEFAULT_SIZES);
5559 : :
5560 : : /* Note we initialize all fields to zero */
5561 : : astate = (ArrayBuildStateArr *)
5562 : 428 : MemoryContextAllocZero(arr_context, sizeof(ArrayBuildStateArr));
5563 : 428 : astate->mcontext = arr_context;
5564 : 428 : astate->private_cxt = subcontext;
5565 : :
5566 : : /* Save relevant datatype information */
5567 : 428 : astate->array_type = array_type;
5568 : 428 : astate->element_type = element_type;
5569 : :
5570 : 428 : return astate;
5571 : : }
5572 : :
5573 : : /*
5574 : : * accumArrayResultArr - accumulate one (more) sub-array for an array result
5575 : : *
5576 : : * astate is working state (can be NULL on first call)
5577 : : * dvalue/disnull represent the new sub-array to append to the array
5578 : : * array_type is the array type (must be a valid varlena array type)
5579 : : * rcontext is where to keep working state
5580 : : */
5581 : : ArrayBuildStateArr *
5582 : 84000 : accumArrayResultArr(ArrayBuildStateArr *astate,
5583 : : Datum dvalue, bool disnull,
5584 : : Oid array_type,
5585 : : MemoryContext rcontext)
5586 : : {
5587 : : ArrayType *arg;
5588 : : MemoryContext oldcontext;
5589 : : int *dims,
5590 : : *lbs,
5591 : : ndims,
5592 : : nitems,
5593 : : ndatabytes;
5594 : : char *data;
5595 : : int i;
5596 : : int newnitems;
5597 : :
5598 : : /*
5599 : : * We disallow accumulating null subarrays. Another plausible definition
5600 : : * is to ignore them, but callers that want that can just skip calling
5601 : : * this function.
5602 : : */
5603 [ + + ]: 84000 : if (disnull)
5604 [ + - ]: 4 : ereport(ERROR,
5605 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5606 : : errmsg("cannot accumulate null arrays")));
5607 : :
5608 : : /* Detoast input array in caller's context */
5609 : 83996 : arg = DatumGetArrayTypeP(dvalue);
5610 : :
5611 [ - + ]: 83996 : if (astate == NULL)
5612 : 0 : astate = initArrayResultArr(array_type, InvalidOid, rcontext, true);
5613 : : else
5614 : : Assert(astate->array_type == array_type);
5615 : :
5616 : 83996 : oldcontext = MemoryContextSwitchTo(astate->mcontext);
5617 : :
5618 : : /* Collect this input's dimensions */
5619 : 83996 : ndims = ARR_NDIM(arg);
5620 : 83996 : dims = ARR_DIMS(arg);
5621 : 83996 : lbs = ARR_LBOUND(arg);
5622 [ + + ]: 83996 : data = ARR_DATA_PTR(arg);
5623 : 83996 : nitems = ArrayGetNItems(ndims, dims);
5624 [ + + ]: 83996 : ndatabytes = ARR_SIZE(arg) - ARR_DATA_OFFSET(arg);
5625 : :
5626 : : /* Check that the array doesn't grow too large */
5627 : 83996 : newnitems = astate->nitems + nitems;
5628 [ - + ]: 83996 : if (newnitems > MaxArraySize)
5629 [ # # ]: 0 : ereport(ERROR,
5630 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5631 : : errmsg("array size exceeds the maximum allowed (%zu)",
5632 : : MaxArraySize)));
5633 : :
5634 [ + + ]: 83996 : if (astate->ndims == 0)
5635 : : {
5636 : : /* First input; check/save the dimensionality info */
5637 : :
5638 : : /* Should we allow empty inputs and just produce an empty output? */
5639 [ + + ]: 304 : if (ndims == 0)
5640 [ + - ]: 4 : ereport(ERROR,
5641 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
5642 : : errmsg("cannot accumulate empty arrays")));
5643 [ - + ]: 300 : if (ndims + 1 > MAXDIM)
5644 [ # # ]: 0 : ereport(ERROR,
5645 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5646 : : errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5647 : : ndims + 1, MAXDIM)));
5648 : :
5649 : : /*
5650 : : * The output array will have n+1 dimensions, with the ones after the
5651 : : * first matching the input's dimensions.
5652 : : */
5653 : 300 : astate->ndims = ndims + 1;
5654 : 300 : astate->dims[0] = 0;
5655 : 300 : memcpy(&astate->dims[1], dims, ndims * sizeof(int));
5656 : 300 : astate->lbs[0] = 1;
5657 : 300 : memcpy(&astate->lbs[1], lbs, ndims * sizeof(int));
5658 : :
5659 : : /* Allocate at least enough data space for this item */
5660 : 300 : astate->abytes = pg_nextpower2_32(Max(1024, ndatabytes + 1));
5661 : 300 : astate->data = (char *) palloc(astate->abytes);
5662 : : }
5663 : : else
5664 : : {
5665 : : /* Second or later input: must match first input's dimensionality */
5666 [ - + ]: 83692 : if (astate->ndims != ndims + 1)
5667 [ # # ]: 0 : ereport(ERROR,
5668 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
5669 : : errmsg("cannot accumulate arrays of different dimensionality")));
5670 [ + + ]: 167380 : for (i = 0; i < ndims; i++)
5671 : : {
5672 [ + + - + ]: 83692 : if (astate->dims[i + 1] != dims[i] || astate->lbs[i + 1] != lbs[i])
5673 [ + - ]: 4 : ereport(ERROR,
5674 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
5675 : : errmsg("cannot accumulate arrays of different dimensionality")));
5676 : : }
5677 : :
5678 : : /* Enlarge data space if needed */
5679 [ + + ]: 83688 : if (astate->nbytes + ndatabytes > astate->abytes)
5680 : : {
5681 : 106 : astate->abytes = Max(astate->abytes * 2,
5682 : : astate->nbytes + ndatabytes);
5683 : 106 : astate->data = (char *) repalloc(astate->data, astate->abytes);
5684 : : }
5685 : : }
5686 : :
5687 : : /*
5688 : : * Copy the data portion of the sub-array. Note we assume that the
5689 : : * advertised data length of the sub-array is properly aligned. We do not
5690 : : * have to worry about detoasting elements since whatever's in the
5691 : : * sub-array should be OK already.
5692 : : */
5693 : 83988 : memcpy(astate->data + astate->nbytes, data, ndatabytes);
5694 : 83988 : astate->nbytes += ndatabytes;
5695 : :
5696 : : /* Deal with null bitmap if needed */
5697 [ + + + + ]: 83988 : if (astate->nullbitmap || ARR_HASNULL(arg))
5698 : : {
5699 [ + + ]: 20061 : if (astate->nullbitmap == NULL)
5700 : : {
5701 : : /*
5702 : : * First input with nulls; we must retrospectively handle any
5703 : : * previous inputs by marking all their items non-null.
5704 : : */
5705 : 85 : astate->aitems = pg_nextpower2_32(Max(256, newnitems + 1));
5706 : 85 : astate->nullbitmap = palloc_array(uint8, (astate->aitems + 7) / 8);
5707 : 85 : array_bitmap_copy(astate->nullbitmap, 0,
5708 : : NULL, 0,
5709 : : astate->nitems);
5710 : : }
5711 [ + + ]: 19976 : else if (newnitems > astate->aitems)
5712 : : {
5713 : 35 : astate->aitems = Max(astate->aitems * 2, newnitems);
5714 : 35 : astate->nullbitmap = repalloc_array(astate->nullbitmap,
5715 : : uint8, (astate->aitems + 7) / 8);
5716 : : }
5717 : 20061 : array_bitmap_copy(astate->nullbitmap, astate->nitems,
5718 [ + + ]: 20061 : ARR_NULLBITMAP(arg), 0,
5719 : : nitems);
5720 : : }
5721 : :
5722 : 83988 : astate->nitems = newnitems;
5723 : 83988 : astate->dims[0] += 1;
5724 : :
5725 : 83988 : MemoryContextSwitchTo(oldcontext);
5726 : :
5727 : : /* Release detoasted copy if any */
5728 [ + + ]: 83988 : if (arg != DatumGetPointer(dvalue))
5729 : 3774 : pfree(arg);
5730 : :
5731 : 83988 : return astate;
5732 : : }
5733 : :
5734 : : /*
5735 : : * makeArrayResultArr - produce N+1-D final result of accumArrayResultArr
5736 : : *
5737 : : * astate is working state (must not be NULL)
5738 : : * rcontext is where to construct result
5739 : : * release is true if okay to release working state
5740 : : */
5741 : : Datum
5742 : 256 : makeArrayResultArr(ArrayBuildStateArr *astate,
5743 : : MemoryContext rcontext,
5744 : : bool release)
5745 : : {
5746 : : ArrayType *result;
5747 : : MemoryContext oldcontext;
5748 : :
5749 : : /* Build the final array result in rcontext */
5750 : 256 : oldcontext = MemoryContextSwitchTo(rcontext);
5751 : :
5752 [ - + ]: 256 : if (astate->ndims == 0)
5753 : : {
5754 : : /* No inputs, return empty array */
5755 : 0 : result = construct_empty_array(astate->element_type);
5756 : : }
5757 : : else
5758 : : {
5759 : : int dataoffset,
5760 : : nbytes;
5761 : :
5762 : : /* Check for overflow of the array dimensions */
5763 : 256 : (void) ArrayGetNItems(astate->ndims, astate->dims);
5764 : 256 : ArrayCheckBounds(astate->ndims, astate->dims, astate->lbs);
5765 : :
5766 : : /* Compute required space */
5767 : 256 : nbytes = astate->nbytes;
5768 [ + + ]: 256 : if (astate->nullbitmap != NULL)
5769 : : {
5770 : 65 : dataoffset = ARR_OVERHEAD_WITHNULLS(astate->ndims, astate->nitems);
5771 : 65 : nbytes += dataoffset;
5772 : : }
5773 : : else
5774 : : {
5775 : 191 : dataoffset = 0;
5776 : 191 : nbytes += ARR_OVERHEAD_NONULLS(astate->ndims);
5777 : : }
5778 : :
5779 : 256 : result = (ArrayType *) palloc0(nbytes);
5780 : 256 : SET_VARSIZE(result, nbytes);
5781 : 256 : result->ndim = astate->ndims;
5782 : 256 : result->dataoffset = dataoffset;
5783 : 256 : result->elemtype = astate->element_type;
5784 : :
5785 : 256 : memcpy(ARR_DIMS(result), astate->dims, astate->ndims * sizeof(int));
5786 : 256 : memcpy(ARR_LBOUND(result), astate->lbs, astate->ndims * sizeof(int));
5787 [ + + ]: 256 : memcpy(ARR_DATA_PTR(result), astate->data, astate->nbytes);
5788 : :
5789 [ + + ]: 256 : if (astate->nullbitmap != NULL)
5790 : 65 : array_bitmap_copy(ARR_NULLBITMAP(result), 0,
5791 [ + - ]: 65 : astate->nullbitmap, 0,
5792 : : astate->nitems);
5793 : : }
5794 : :
5795 : 256 : MemoryContextSwitchTo(oldcontext);
5796 : :
5797 : : /* Clean up all the junk */
5798 [ + + ]: 256 : if (release)
5799 : : {
5800 : : Assert(astate->private_cxt);
5801 : 38 : MemoryContextDelete(astate->mcontext);
5802 : : }
5803 : :
5804 : 256 : return PointerGetDatum(result);
5805 : : }
5806 : :
5807 : : /*
5808 : : * The following three functions provide essentially the same API as
5809 : : * initArrayResult/accumArrayResult/makeArrayResult, but can accept either
5810 : : * scalar or array inputs, invoking the appropriate set of functions above.
5811 : : */
5812 : :
5813 : : /*
5814 : : * initArrayResultAny - initialize an empty ArrayBuildStateAny
5815 : : *
5816 : : * input_type is the input datatype (either element or array type)
5817 : : * rcontext is where to keep working state
5818 : : * subcontext is a flag determining whether to use a separate memory context
5819 : : */
5820 : : ArrayBuildStateAny *
5821 : 30540 : initArrayResultAny(Oid input_type, MemoryContext rcontext, bool subcontext)
5822 : : {
5823 : : ArrayBuildStateAny *astate;
5824 : :
5825 : : /*
5826 : : * int2vector and oidvector will satisfy both get_element_type and
5827 : : * get_array_type. We prefer to treat them as scalars, to be consistent
5828 : : * with get_promoted_array_type. Hence, check get_array_type not
5829 : : * get_element_type.
5830 : : */
5831 [ + + ]: 30540 : if (!OidIsValid(get_array_type(input_type)))
5832 : : {
5833 : : /* Array case */
5834 : : ArrayBuildStateArr *arraystate;
5835 : :
5836 : 38 : arraystate = initArrayResultArr(input_type, InvalidOid, rcontext, subcontext);
5837 : : astate = (ArrayBuildStateAny *)
5838 : 38 : MemoryContextAlloc(arraystate->mcontext,
5839 : : sizeof(ArrayBuildStateAny));
5840 : 38 : astate->scalarstate = NULL;
5841 : 38 : astate->arraystate = arraystate;
5842 : : }
5843 : : else
5844 : : {
5845 : : /* Scalar case */
5846 : : ArrayBuildState *scalarstate;
5847 : :
5848 : 30502 : scalarstate = initArrayResult(input_type, rcontext, subcontext);
5849 : : astate = (ArrayBuildStateAny *)
5850 : 30502 : MemoryContextAlloc(scalarstate->mcontext,
5851 : : sizeof(ArrayBuildStateAny));
5852 : 30502 : astate->scalarstate = scalarstate;
5853 : 30502 : astate->arraystate = NULL;
5854 : : }
5855 : :
5856 : 30540 : return astate;
5857 : : }
5858 : :
5859 : : /*
5860 : : * accumArrayResultAny - accumulate one (more) input for an array result
5861 : : *
5862 : : * astate is working state (can be NULL on first call)
5863 : : * dvalue/disnull represent the new input to append to the array
5864 : : * input_type is the input datatype (either element or array type)
5865 : : * rcontext is where to keep working state
5866 : : */
5867 : : ArrayBuildStateAny *
5868 : 76770 : accumArrayResultAny(ArrayBuildStateAny *astate,
5869 : : Datum dvalue, bool disnull,
5870 : : Oid input_type,
5871 : : MemoryContext rcontext)
5872 : : {
5873 [ + + ]: 76770 : if (astate == NULL)
5874 : 99 : astate = initArrayResultAny(input_type, rcontext, true);
5875 : :
5876 [ + + ]: 76770 : if (astate->scalarstate)
5877 : 76663 : (void) accumArrayResult(astate->scalarstate,
5878 : : dvalue, disnull,
5879 : : input_type, rcontext);
5880 : : else
5881 : 107 : (void) accumArrayResultArr(astate->arraystate,
5882 : : dvalue, disnull,
5883 : : input_type, rcontext);
5884 : :
5885 : 76770 : return astate;
5886 : : }
5887 : :
5888 : : /*
5889 : : * makeArrayResultAny - produce final result of accumArrayResultAny
5890 : : *
5891 : : * astate is working state (must not be NULL)
5892 : : * rcontext is where to construct result
5893 : : * release is true if okay to release working state
5894 : : */
5895 : : Datum
5896 : 30540 : makeArrayResultAny(ArrayBuildStateAny *astate,
5897 : : MemoryContext rcontext, bool release)
5898 : : {
5899 : : Datum result;
5900 : :
5901 [ + + ]: 30540 : if (astate->scalarstate)
5902 : : {
5903 : : /* Must use makeMdArrayResult to support "release" parameter */
5904 : : int ndims;
5905 : : int dims[1];
5906 : : int lbs[1];
5907 : :
5908 : : /* If no elements were presented, we want to create an empty array */
5909 : 30502 : ndims = (astate->scalarstate->nelems > 0) ? 1 : 0;
5910 : 30502 : dims[0] = astate->scalarstate->nelems;
5911 : 30502 : lbs[0] = 1;
5912 : :
5913 : 30502 : result = makeMdArrayResult(astate->scalarstate, ndims, dims, lbs,
5914 : : rcontext, release);
5915 : : }
5916 : : else
5917 : : {
5918 : 38 : result = makeArrayResultArr(astate->arraystate,
5919 : : rcontext, release);
5920 : : }
5921 : 30540 : return result;
5922 : : }
5923 : :
5924 : :
5925 : : Datum
5926 : 192 : array_larger(PG_FUNCTION_ARGS)
5927 : : {
5928 [ + + ]: 192 : if (array_cmp(fcinfo) > 0)
5929 : 96 : PG_RETURN_DATUM(PG_GETARG_DATUM(0));
5930 : : else
5931 : 92 : PG_RETURN_DATUM(PG_GETARG_DATUM(1));
5932 : : }
5933 : :
5934 : : Datum
5935 : 172 : array_smaller(PG_FUNCTION_ARGS)
5936 : : {
5937 [ + + ]: 172 : if (array_cmp(fcinfo) < 0)
5938 : 116 : PG_RETURN_DATUM(PG_GETARG_DATUM(0));
5939 : : else
5940 : 56 : PG_RETURN_DATUM(PG_GETARG_DATUM(1));
5941 : : }
5942 : :
5943 : :
5944 : : typedef struct generate_subscripts_fctx
5945 : : {
5946 : : int32 lower;
5947 : : int32 upper;
5948 : : bool reverse;
5949 : : } generate_subscripts_fctx;
5950 : :
5951 : : /*
5952 : : * generate_subscripts(array anyarray, dim int [, reverse bool])
5953 : : * Returns all subscripts of the array for any dimension
5954 : : */
5955 : : Datum
5956 : 2630 : generate_subscripts(PG_FUNCTION_ARGS)
5957 : : {
5958 : : FuncCallContext *funcctx;
5959 : : MemoryContext oldcontext;
5960 : : generate_subscripts_fctx *fctx;
5961 : :
5962 : : /* stuff done only on the first call of the function */
5963 [ + + ]: 2630 : if (SRF_IS_FIRSTCALL())
5964 : : {
5965 : 1199 : AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
5966 : 1199 : int reqdim = PG_GETARG_INT32(1);
5967 : : int *lb,
5968 : : *dimv;
5969 : :
5970 : : /* create a function context for cross-call persistence */
5971 : 1199 : funcctx = SRF_FIRSTCALL_INIT();
5972 : :
5973 : : /* Sanity check: does it look like an array at all? */
5974 [ - + - - : 1199 : if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
+ + - + -
- - + ]
5975 : 5 : SRF_RETURN_DONE(funcctx);
5976 : :
5977 : : /* Sanity check: was the requested dim valid */
5978 [ + - - + : 1194 : if (reqdim <= 0 || reqdim > AARR_NDIM(v))
- + ]
5979 : 0 : SRF_RETURN_DONE(funcctx);
5980 : :
5981 : : /*
5982 : : * switch to memory context appropriate for multiple function calls
5983 : : */
5984 : 1194 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5985 : 1194 : fctx = palloc_object(generate_subscripts_fctx);
5986 : :
5987 [ - + ]: 1194 : lb = AARR_LBOUND(v);
5988 [ - + ]: 1194 : dimv = AARR_DIMS(v);
5989 : :
5990 : 1194 : fctx->lower = lb[reqdim - 1];
5991 : 1194 : fctx->upper = dimv[reqdim - 1] + lb[reqdim - 1] - 1;
5992 [ - + - - ]: 1194 : fctx->reverse = (PG_NARGS() < 3) ? false : PG_GETARG_BOOL(2);
5993 : :
5994 : 1194 : funcctx->user_fctx = fctx;
5995 : :
5996 : 1194 : MemoryContextSwitchTo(oldcontext);
5997 : : }
5998 : :
5999 : 2625 : funcctx = SRF_PERCALL_SETUP();
6000 : :
6001 : 2625 : fctx = funcctx->user_fctx;
6002 : :
6003 [ + + ]: 2625 : if (fctx->lower <= fctx->upper)
6004 : : {
6005 [ + - ]: 1431 : if (!fctx->reverse)
6006 : 1431 : SRF_RETURN_NEXT(funcctx, Int32GetDatum(fctx->lower++));
6007 : : else
6008 : 0 : SRF_RETURN_NEXT(funcctx, Int32GetDatum(fctx->upper--));
6009 : : }
6010 : : else
6011 : : /* done when there are no more elements left */
6012 : 1194 : SRF_RETURN_DONE(funcctx);
6013 : : }
6014 : :
6015 : : /*
6016 : : * generate_subscripts_nodir
6017 : : * Implements the 2-argument version of generate_subscripts
6018 : : */
6019 : : Datum
6020 : 2630 : generate_subscripts_nodir(PG_FUNCTION_ARGS)
6021 : : {
6022 : : /* just call the other one -- it can handle both cases */
6023 : 2630 : return generate_subscripts(fcinfo);
6024 : : }
6025 : :
6026 : : /*
6027 : : * array_fill_with_lower_bounds
6028 : : * Create and fill array with defined lower bounds.
6029 : : */
6030 : : Datum
6031 : 51 : array_fill_with_lower_bounds(PG_FUNCTION_ARGS)
6032 : : {
6033 : : ArrayType *dims;
6034 : : ArrayType *lbs;
6035 : : ArrayType *result;
6036 : : Oid elmtype;
6037 : : Datum value;
6038 : : bool isnull;
6039 : :
6040 [ + + + + ]: 51 : if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
6041 [ + - ]: 8 : ereport(ERROR,
6042 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6043 : : errmsg("dimension array or low bound array cannot be null")));
6044 : :
6045 : 43 : dims = PG_GETARG_ARRAYTYPE_P(1);
6046 : 43 : lbs = PG_GETARG_ARRAYTYPE_P(2);
6047 : :
6048 [ + + ]: 43 : if (!PG_ARGISNULL(0))
6049 : : {
6050 : 33 : value = PG_GETARG_DATUM(0);
6051 : 33 : isnull = false;
6052 : : }
6053 : : else
6054 : : {
6055 : 10 : value = 0;
6056 : 10 : isnull = true;
6057 : : }
6058 : :
6059 : 43 : elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
6060 [ - + ]: 43 : if (!OidIsValid(elmtype))
6061 [ # # ]: 0 : elog(ERROR, "could not determine data type of input");
6062 : :
6063 : 43 : result = array_fill_internal(dims, lbs, value, isnull, elmtype, fcinfo);
6064 : 35 : PG_RETURN_ARRAYTYPE_P(result);
6065 : : }
6066 : :
6067 : : /*
6068 : : * array_fill
6069 : : * Create and fill array with default lower bounds.
6070 : : */
6071 : : Datum
6072 : 71 : array_fill(PG_FUNCTION_ARGS)
6073 : : {
6074 : : ArrayType *dims;
6075 : : ArrayType *result;
6076 : : Oid elmtype;
6077 : : Datum value;
6078 : : bool isnull;
6079 : :
6080 [ - + ]: 71 : if (PG_ARGISNULL(1))
6081 [ # # ]: 0 : ereport(ERROR,
6082 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6083 : : errmsg("dimension array or low bound array cannot be null")));
6084 : :
6085 : 71 : dims = PG_GETARG_ARRAYTYPE_P(1);
6086 : :
6087 [ + + ]: 71 : if (!PG_ARGISNULL(0))
6088 : : {
6089 : 61 : value = PG_GETARG_DATUM(0);
6090 : 61 : isnull = false;
6091 : : }
6092 : : else
6093 : : {
6094 : 10 : value = 0;
6095 : 10 : isnull = true;
6096 : : }
6097 : :
6098 : 71 : elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
6099 [ - + ]: 71 : if (!OidIsValid(elmtype))
6100 [ # # ]: 0 : elog(ERROR, "could not determine data type of input");
6101 : :
6102 : 71 : result = array_fill_internal(dims, NULL, value, isnull, elmtype, fcinfo);
6103 : 63 : PG_RETURN_ARRAYTYPE_P(result);
6104 : : }
6105 : :
6106 : : static ArrayType *
6107 : 53 : create_array_envelope(int ndims, int *dimv, int *lbsv, int nbytes,
6108 : : Oid elmtype, int dataoffset)
6109 : : {
6110 : : ArrayType *result;
6111 : :
6112 : 53 : result = (ArrayType *) palloc0(nbytes);
6113 : 53 : SET_VARSIZE(result, nbytes);
6114 : 53 : result->ndim = ndims;
6115 : 53 : result->dataoffset = dataoffset;
6116 : 53 : result->elemtype = elmtype;
6117 : 53 : memcpy(ARR_DIMS(result), dimv, ndims * sizeof(int));
6118 : 53 : memcpy(ARR_LBOUND(result), lbsv, ndims * sizeof(int));
6119 : :
6120 : 53 : return result;
6121 : : }
6122 : :
6123 : : static ArrayType *
6124 : 114 : array_fill_internal(ArrayType *dims, ArrayType *lbs,
6125 : : Datum value, bool isnull, Oid elmtype,
6126 : : FunctionCallInfo fcinfo)
6127 : : {
6128 : : ArrayType *result;
6129 : : int *dimv;
6130 : : int *lbsv;
6131 : : int ndims;
6132 : : int nitems;
6133 : : int deflbs[MAXDIM];
6134 : : int16 elmlen;
6135 : : bool elmbyval;
6136 : : char elmalign;
6137 : : uint8 elmalignby;
6138 : : ArrayMetaState *my_extra;
6139 : :
6140 : : /*
6141 : : * Params checks
6142 : : */
6143 [ + + ]: 114 : if (ARR_NDIM(dims) > 1)
6144 [ + - ]: 4 : ereport(ERROR,
6145 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
6146 : : errmsg("wrong number of array subscripts"),
6147 : : errdetail("Dimension array must be one dimensional.")));
6148 : :
6149 [ + + ]: 110 : if (array_contains_nulls(dims))
6150 [ + - ]: 4 : ereport(ERROR,
6151 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6152 : : errmsg("dimension values cannot be null")));
6153 : :
6154 [ - + ]: 106 : dimv = (int *) ARR_DATA_PTR(dims);
6155 [ + + ]: 106 : ndims = (ARR_NDIM(dims) > 0) ? ARR_DIMS(dims)[0] : 0;
6156 : :
6157 [ - + ]: 106 : if (ndims < 0) /* we do allow zero-dimension arrays */
6158 [ # # ]: 0 : ereport(ERROR,
6159 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6160 : : errmsg("invalid number of dimensions: %d", ndims)));
6161 [ - + ]: 106 : if (ndims > MAXDIM)
6162 [ # # ]: 0 : ereport(ERROR,
6163 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
6164 : : errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
6165 : : ndims, MAXDIM)));
6166 : :
6167 [ + + ]: 106 : if (lbs != NULL)
6168 : : {
6169 [ - + ]: 43 : if (ARR_NDIM(lbs) > 1)
6170 [ # # ]: 0 : ereport(ERROR,
6171 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
6172 : : errmsg("wrong number of array subscripts"),
6173 : : errdetail("Dimension array must be one dimensional.")));
6174 : :
6175 [ - + ]: 43 : if (array_contains_nulls(lbs))
6176 [ # # ]: 0 : ereport(ERROR,
6177 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6178 : : errmsg("dimension values cannot be null")));
6179 : :
6180 [ + + + + ]: 43 : if (ndims != ((ARR_NDIM(lbs) > 0) ? ARR_DIMS(lbs)[0] : 0))
6181 [ + - ]: 8 : ereport(ERROR,
6182 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
6183 : : errmsg("wrong number of array subscripts"),
6184 : : errdetail("Low bound array has different size than dimensions array.")));
6185 : :
6186 [ - + ]: 35 : lbsv = (int *) ARR_DATA_PTR(lbs);
6187 : : }
6188 : : else
6189 : : {
6190 : : int i;
6191 : :
6192 [ + + ]: 441 : for (i = 0; i < MAXDIM; i++)
6193 : 378 : deflbs[i] = 1;
6194 : :
6195 : 63 : lbsv = deflbs;
6196 : : }
6197 : :
6198 : : /* This checks for overflow of the array dimensions */
6199 : 98 : nitems = ArrayGetNItems(ndims, dimv);
6200 : 98 : ArrayCheckBounds(ndims, dimv, lbsv);
6201 : :
6202 : : /* fast track for empty array */
6203 [ + + ]: 98 : if (nitems <= 0)
6204 : 45 : return construct_empty_array(elmtype);
6205 : :
6206 : : /*
6207 : : * We arrange to look up info about element type only once per series of
6208 : : * calls, assuming the element type doesn't change underneath us.
6209 : : */
6210 : 53 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
6211 [ + - ]: 53 : if (my_extra == NULL)
6212 : : {
6213 : 53 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
6214 : : sizeof(ArrayMetaState));
6215 : 53 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
6216 : 53 : my_extra->element_type = InvalidOid;
6217 : : }
6218 : :
6219 [ + - ]: 53 : if (my_extra->element_type != elmtype)
6220 : : {
6221 : : /* Get info about element type */
6222 : 53 : get_typlenbyvalalign(elmtype,
6223 : : &my_extra->typlen,
6224 : : &my_extra->typbyval,
6225 : : &my_extra->typalign);
6226 : 53 : my_extra->element_type = elmtype;
6227 : : }
6228 : :
6229 : 53 : elmlen = my_extra->typlen;
6230 : 53 : elmbyval = my_extra->typbyval;
6231 : 53 : elmalign = my_extra->typalign;
6232 : 53 : elmalignby = typalign_to_alignby(elmalign);
6233 : :
6234 : : /* compute required space */
6235 [ + + ]: 53 : if (!isnull)
6236 : : {
6237 : : int i;
6238 : : char *p;
6239 : : int nbytes;
6240 : : int totbytes;
6241 : :
6242 : : /* make sure data is not toasted */
6243 [ + + ]: 33 : if (elmlen == -1)
6244 : 10 : value = PointerGetDatum(PG_DETOAST_DATUM(value));
6245 : :
6246 [ + + + - ]: 33 : nbytes = att_addlength_datum(0, elmlen, value);
6247 : 33 : nbytes = att_nominal_alignby(nbytes, elmalignby);
6248 : : Assert(nbytes > 0);
6249 : :
6250 : 33 : totbytes = nbytes * nitems;
6251 : :
6252 : : /* check for overflow of multiplication or total request */
6253 [ + - ]: 33 : if (totbytes / nbytes != nitems ||
6254 [ - + ]: 33 : !AllocSizeIsValid(totbytes))
6255 [ # # ]: 0 : ereport(ERROR,
6256 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
6257 : : errmsg("array size exceeds the maximum allowed (%zu)",
6258 : : MaxAllocSize)));
6259 : :
6260 : : /*
6261 : : * This addition can't overflow, but it might cause us to go past
6262 : : * MaxAllocSize. We leave it to palloc to complain in that case.
6263 : : */
6264 : 33 : totbytes += ARR_OVERHEAD_NONULLS(ndims);
6265 : :
6266 : 33 : result = create_array_envelope(ndims, dimv, lbsv, totbytes,
6267 : : elmtype, 0);
6268 : :
6269 [ - + ]: 33 : p = ARR_DATA_PTR(result);
6270 [ + + ]: 2500245 : for (i = 0; i < nitems; i++)
6271 : 2500212 : p += ArrayCastAndSet(value, elmlen, elmbyval, elmalignby, p);
6272 : : }
6273 : : else
6274 : : {
6275 : : int nbytes;
6276 : : int dataoffset;
6277 : :
6278 : 20 : dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
6279 : 20 : nbytes = dataoffset;
6280 : :
6281 : 20 : result = create_array_envelope(ndims, dimv, lbsv, nbytes,
6282 : : elmtype, dataoffset);
6283 : :
6284 : : /* create_array_envelope already zeroed the bitmap, so we're done */
6285 : : }
6286 : :
6287 : 53 : return result;
6288 : : }
6289 : :
6290 : :
6291 : : /*
6292 : : * UNNEST
6293 : : */
6294 : : Datum
6295 : 348945 : array_unnest(PG_FUNCTION_ARGS)
6296 : : {
6297 : : typedef struct
6298 : : {
6299 : : array_iter iter;
6300 : : int nextelem;
6301 : : int numelems;
6302 : : } array_unnest_fctx;
6303 : :
6304 : : FuncCallContext *funcctx;
6305 : : array_unnest_fctx *fctx;
6306 : : MemoryContext oldcontext;
6307 : :
6308 : : /* stuff done only on the first call of the function */
6309 [ + + ]: 348945 : if (SRF_IS_FIRSTCALL())
6310 : : {
6311 : : AnyArrayType *arr;
6312 : : int16 elmlen;
6313 : : bool elmbyval;
6314 : : char elmalign;
6315 : :
6316 : : /* create a function context for cross-call persistence */
6317 : 56399 : funcctx = SRF_FIRSTCALL_INIT();
6318 : :
6319 : : /*
6320 : : * switch to memory context appropriate for multiple function calls
6321 : : */
6322 : 56399 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
6323 : :
6324 : : /*
6325 : : * Get the array value and detoast if needed. We can't do this
6326 : : * earlier because if we have to detoast, we want the detoasted copy
6327 : : * to be in multi_call_memory_ctx, so it will go away when we're done
6328 : : * and not before. (If no detoast happens, we assume the originally
6329 : : * passed array will stick around till then.)
6330 : : */
6331 : 56399 : arr = PG_GETARG_ANY_ARRAY_P(0);
6332 : :
6333 : : /* allocate memory for user context */
6334 : 56399 : fctx = palloc_object(array_unnest_fctx);
6335 : :
6336 : : /* get element-type data */
6337 [ + + ]: 56399 : if (VARATT_IS_EXPANDED_HEADER(arr))
6338 : : {
6339 : : /* we can just grab the type data from expanded array */
6340 : 1 : elmlen = arr->xpn.typlen;
6341 : 1 : elmbyval = arr->xpn.typbyval;
6342 : 1 : elmalign = arr->xpn.typalign;
6343 : : }
6344 : : else
6345 [ - + ]: 56398 : get_typlenbyvalalign(AARR_ELEMTYPE(arr),
6346 : : &elmlen,
6347 : : &elmbyval,
6348 : : &elmalign);
6349 : :
6350 : : /* initialize state */
6351 : 56399 : array_iter_setup(&fctx->iter, arr, elmlen, elmbyval, elmalign);
6352 : 56399 : fctx->nextelem = 0;
6353 [ + + + + ]: 56399 : fctx->numelems = ArrayGetNItems(AARR_NDIM(arr), AARR_DIMS(arr));
6354 : :
6355 : 56399 : funcctx->user_fctx = fctx;
6356 : 56399 : MemoryContextSwitchTo(oldcontext);
6357 : : }
6358 : :
6359 : : /* stuff done on every call of the function */
6360 : 348945 : funcctx = SRF_PERCALL_SETUP();
6361 : 348945 : fctx = funcctx->user_fctx;
6362 : :
6363 [ + + ]: 348945 : if (fctx->nextelem < fctx->numelems)
6364 : : {
6365 : 292550 : int offset = fctx->nextelem++;
6366 : : Datum elem;
6367 : :
6368 : 292550 : elem = array_iter_next(&fctx->iter, &fcinfo->isnull, offset);
6369 : :
6370 : 292550 : SRF_RETURN_NEXT(funcctx, elem);
6371 : : }
6372 : : else
6373 : : {
6374 : : /* do when there is no more left */
6375 : 56395 : SRF_RETURN_DONE(funcctx);
6376 : : }
6377 : : }
6378 : :
6379 : : /*
6380 : : * Planner support function for array_unnest(anyarray)
6381 : : *
6382 : : * Note: this is now also used for information_schema._pg_expandarray(),
6383 : : * which is simply a wrapper around array_unnest().
6384 : : */
6385 : : Datum
6386 : 17903 : array_unnest_support(PG_FUNCTION_ARGS)
6387 : : {
6388 : 17903 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
6389 : 17903 : Node *ret = NULL;
6390 : :
6391 [ + + ]: 17903 : if (IsA(rawreq, SupportRequestRows))
6392 : : {
6393 : : /* Try to estimate the number of rows returned */
6394 : 4928 : SupportRequestRows *req = (SupportRequestRows *) rawreq;
6395 : :
6396 [ + + ]: 4928 : if (is_funcclause(req->node)) /* be paranoid */
6397 : : {
6398 : 4923 : List *args = ((FuncExpr *) req->node)->args;
6399 : : Node *arg1;
6400 : :
6401 : : /* We can use estimated argument values here */
6402 : 4923 : arg1 = estimate_expression_value(req->root, linitial(args));
6403 : :
6404 : 4923 : req->rows = estimate_array_length(req->root, arg1);
6405 : 4923 : ret = (Node *) req;
6406 : : }
6407 : : }
6408 : :
6409 : 17903 : PG_RETURN_POINTER(ret);
6410 : : }
6411 : :
6412 : :
6413 : : /*
6414 : : * array_replace/array_remove support
6415 : : *
6416 : : * Find all array entries matching (not distinct from) search/search_isnull,
6417 : : * and delete them if remove is true, else replace them with
6418 : : * replace/replace_isnull. Comparisons are done using the specified
6419 : : * collation. fcinfo is passed only for caching purposes.
6420 : : */
6421 : : static ArrayType *
6422 : 1950 : array_replace_internal(ArrayType *array,
6423 : : Datum search, bool search_isnull,
6424 : : Datum replace, bool replace_isnull,
6425 : : bool remove, Oid collation,
6426 : : FunctionCallInfo fcinfo)
6427 : : {
6428 : 1950 : LOCAL_FCINFO(locfcinfo, 2);
6429 : : ArrayType *result;
6430 : : Oid element_type;
6431 : : Datum *values;
6432 : : bool *nulls;
6433 : : int *dim;
6434 : : int ndim;
6435 : : int nitems,
6436 : : nresult;
6437 : : int i;
6438 : 1950 : int32 nbytes = 0;
6439 : : int32 dataoffset;
6440 : : bool hasnulls;
6441 : : int typlen;
6442 : : bool typbyval;
6443 : : char typalign;
6444 : : uint8 typalignby;
6445 : : char *arraydataptr;
6446 : : uint8 *bitmap;
6447 : : int bitmask;
6448 : 1950 : bool changed = false;
6449 : : TypeCacheEntry *typentry;
6450 : :
6451 : 1950 : element_type = ARR_ELEMTYPE(array);
6452 : 1950 : ndim = ARR_NDIM(array);
6453 : 1950 : dim = ARR_DIMS(array);
6454 : 1950 : nitems = ArrayGetNItems(ndim, dim);
6455 : :
6456 : : /* Return input array unmodified if it is empty */
6457 [ - + ]: 1950 : if (nitems <= 0)
6458 : 0 : return array;
6459 : :
6460 : : /*
6461 : : * We can't remove elements from multi-dimensional arrays, since the
6462 : : * result might not be rectangular.
6463 : : */
6464 [ + + + + ]: 1950 : if (remove && ndim > 1)
6465 [ + - ]: 4 : ereport(ERROR,
6466 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6467 : : errmsg("removing elements from multidimensional arrays is not supported")));
6468 : :
6469 : : /*
6470 : : * We arrange to look up the equality function only once per series of
6471 : : * calls, assuming the element type doesn't change underneath us.
6472 : : */
6473 : 1946 : typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
6474 [ + + ]: 1946 : if (typentry == NULL ||
6475 [ - + ]: 1454 : typentry->type_id != element_type)
6476 : : {
6477 : 492 : typentry = lookup_type_cache(element_type,
6478 : : TYPECACHE_EQ_OPR_FINFO);
6479 [ - + ]: 492 : if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
6480 [ # # ]: 0 : ereport(ERROR,
6481 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
6482 : : errmsg("could not identify an equality operator for type %s",
6483 : : format_type_be(element_type))));
6484 : 492 : fcinfo->flinfo->fn_extra = typentry;
6485 : : }
6486 : 1946 : typlen = typentry->typlen;
6487 : 1946 : typbyval = typentry->typbyval;
6488 : 1946 : typalign = typentry->typalign;
6489 : 1946 : typalignby = typalign_to_alignby(typalign);
6490 : :
6491 : : /*
6492 : : * Detoast values if they are toasted. The replacement value must be
6493 : : * detoasted for insertion into the result array, while detoasting the
6494 : : * search value only once saves cycles.
6495 : : */
6496 [ + + ]: 1946 : if (typlen == -1)
6497 : : {
6498 [ + + ]: 1911 : if (!search_isnull)
6499 : 1906 : search = PointerGetDatum(PG_DETOAST_DATUM(search));
6500 [ + + ]: 1911 : if (!replace_isnull)
6501 : 10 : replace = PointerGetDatum(PG_DETOAST_DATUM(replace));
6502 : : }
6503 : :
6504 : : /* Prepare to apply the comparison operator */
6505 : 1946 : InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
6506 : : collation, NULL, NULL);
6507 : :
6508 : : /* Allocate temporary arrays for new values */
6509 : 1946 : values = palloc_array(Datum, nitems);
6510 : 1946 : nulls = palloc_array(bool, nitems);
6511 : :
6512 : : /* Loop over source data */
6513 [ + + ]: 1946 : arraydataptr = ARR_DATA_PTR(array);
6514 [ + + ]: 1946 : bitmap = ARR_NULLBITMAP(array);
6515 : 1946 : bitmask = 1;
6516 : 1946 : hasnulls = false;
6517 : 1946 : nresult = 0;
6518 : :
6519 [ + + ]: 4279 : for (i = 0; i < nitems; i++)
6520 : : {
6521 : : Datum elt;
6522 : : bool isNull;
6523 : : bool oprresult;
6524 : 2333 : bool skip = false;
6525 : :
6526 : : /* Get source element, checking for NULL */
6527 [ + + + + ]: 2333 : if (bitmap && (*bitmap & bitmask) == 0)
6528 : : {
6529 : 30 : isNull = true;
6530 : : /* If searching for NULL, we have a match */
6531 [ + - ]: 30 : if (search_isnull)
6532 : : {
6533 [ + + ]: 30 : if (remove)
6534 : : {
6535 : 10 : skip = true;
6536 : 10 : changed = true;
6537 : : }
6538 [ + + ]: 20 : else if (!replace_isnull)
6539 : : {
6540 : 15 : values[nresult] = replace;
6541 : 15 : isNull = false;
6542 : 15 : changed = true;
6543 : : }
6544 : : }
6545 : : }
6546 : : else
6547 : : {
6548 : 2303 : isNull = false;
6549 : 2303 : elt = fetch_att(arraydataptr, typbyval, typlen);
6550 [ + + + - ]: 2303 : arraydataptr = att_addlength_datum(arraydataptr, typlen, elt);
6551 : 2303 : arraydataptr = (char *) att_nominal_alignby(arraydataptr, typalignby);
6552 : :
6553 [ + + ]: 2303 : if (search_isnull)
6554 : : {
6555 : : /* no match possible, keep element */
6556 : 45 : values[nresult] = elt;
6557 : : }
6558 : : else
6559 : : {
6560 : : /*
6561 : : * Apply the operator to the element pair; treat NULL as false
6562 : : */
6563 : 2258 : locfcinfo->args[0].value = elt;
6564 : 2258 : locfcinfo->args[0].isnull = false;
6565 : 2258 : locfcinfo->args[1].value = search;
6566 : 2258 : locfcinfo->args[1].isnull = false;
6567 : 2258 : locfcinfo->isnull = false;
6568 : 2258 : oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
6569 [ + - + + ]: 2258 : if (locfcinfo->isnull || !oprresult)
6570 : : {
6571 : : /* no match, keep element */
6572 : 2154 : values[nresult] = elt;
6573 : : }
6574 : : else
6575 : : {
6576 : : /* match, so replace or delete */
6577 : 104 : changed = true;
6578 [ + + ]: 104 : if (remove)
6579 : 84 : skip = true;
6580 : : else
6581 : : {
6582 : 20 : values[nresult] = replace;
6583 : 20 : isNull = replace_isnull;
6584 : : }
6585 : : }
6586 : : }
6587 : : }
6588 : :
6589 [ + + ]: 2333 : if (!skip)
6590 : : {
6591 : 2239 : nulls[nresult] = isNull;
6592 [ + + ]: 2239 : if (isNull)
6593 : 10 : hasnulls = true;
6594 : : else
6595 : : {
6596 : : /* Update total result size */
6597 [ + + + - ]: 2229 : nbytes = att_addlength_datum(nbytes, typlen, values[nresult]);
6598 : 2229 : nbytes = att_nominal_alignby(nbytes, typalignby);
6599 : : /* check for overflow of total request */
6600 [ - + ]: 2229 : if (!AllocSizeIsValid(nbytes))
6601 [ # # ]: 0 : ereport(ERROR,
6602 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
6603 : : errmsg("array size exceeds the maximum allowed (%zu)",
6604 : : MaxAllocSize)));
6605 : : }
6606 : 2239 : nresult++;
6607 : : }
6608 : :
6609 : : /* advance bitmap pointer if any */
6610 [ + + ]: 2333 : if (bitmap)
6611 : : {
6612 : 75 : bitmask <<= 1;
6613 [ - + ]: 75 : if (bitmask == 0x100)
6614 : : {
6615 : 0 : bitmap++;
6616 : 0 : bitmask = 1;
6617 : : }
6618 : : }
6619 : : }
6620 : :
6621 : : /*
6622 : : * If not changed just return the original array
6623 : : */
6624 [ + + ]: 1946 : if (!changed)
6625 : : {
6626 : 1847 : pfree(values);
6627 : 1847 : pfree(nulls);
6628 : 1847 : return array;
6629 : : }
6630 : :
6631 : : /* If all elements were removed return an empty array */
6632 [ + + ]: 99 : if (nresult == 0)
6633 : : {
6634 : 5 : pfree(values);
6635 : 5 : pfree(nulls);
6636 : 5 : return construct_empty_array(element_type);
6637 : : }
6638 : :
6639 : : /* Allocate and initialize the result array */
6640 [ + + ]: 94 : if (hasnulls)
6641 : : {
6642 : 5 : dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nresult);
6643 : 5 : nbytes += dataoffset;
6644 : : }
6645 : : else
6646 : : {
6647 : 89 : dataoffset = 0; /* marker for no null bitmap */
6648 : 89 : nbytes += ARR_OVERHEAD_NONULLS(ndim);
6649 : : }
6650 : 94 : result = (ArrayType *) palloc0(nbytes);
6651 : 94 : SET_VARSIZE(result, nbytes);
6652 : 94 : result->ndim = ndim;
6653 : 94 : result->dataoffset = dataoffset;
6654 : 94 : result->elemtype = element_type;
6655 : 94 : memcpy(ARR_DIMS(result), ARR_DIMS(array), ndim * sizeof(int));
6656 : 94 : memcpy(ARR_LBOUND(result), ARR_LBOUND(array), ndim * sizeof(int));
6657 : :
6658 [ + + ]: 94 : if (remove)
6659 : : {
6660 : : /* Adjust the result length */
6661 : 69 : ARR_DIMS(result)[0] = nresult;
6662 : : }
6663 : :
6664 : : /* Insert data into result array */
6665 : 94 : CopyArrayEls(result,
6666 : : values, nulls, nresult,
6667 : : typlen, typbyval, typalign,
6668 : : false);
6669 : :
6670 : 94 : pfree(values);
6671 : 94 : pfree(nulls);
6672 : :
6673 : 94 : return result;
6674 : : }
6675 : :
6676 : : /*
6677 : : * Remove any occurrences of an element from an array
6678 : : *
6679 : : * If used on a multi-dimensional array this will raise an error.
6680 : : */
6681 : : Datum
6682 : 115588 : array_remove(PG_FUNCTION_ARGS)
6683 : : {
6684 : : ArrayType *array;
6685 : 115588 : Datum search = PG_GETARG_DATUM(1);
6686 : 115588 : bool search_isnull = PG_ARGISNULL(1);
6687 : :
6688 [ + + ]: 115588 : if (PG_ARGISNULL(0))
6689 : 113668 : PG_RETURN_NULL();
6690 : 1920 : array = PG_GETARG_ARRAYTYPE_P(0);
6691 : :
6692 : 1920 : array = array_replace_internal(array,
6693 : : search, search_isnull,
6694 : : (Datum) 0, true,
6695 : : true, PG_GET_COLLATION(),
6696 : : fcinfo);
6697 : 1916 : PG_RETURN_ARRAYTYPE_P(array);
6698 : : }
6699 : :
6700 : : /*
6701 : : * Replace any occurrences of an element in an array
6702 : : */
6703 : : Datum
6704 : 30 : array_replace(PG_FUNCTION_ARGS)
6705 : : {
6706 : : ArrayType *array;
6707 : 30 : Datum search = PG_GETARG_DATUM(1);
6708 : 30 : bool search_isnull = PG_ARGISNULL(1);
6709 : 30 : Datum replace = PG_GETARG_DATUM(2);
6710 : 30 : bool replace_isnull = PG_ARGISNULL(2);
6711 : :
6712 [ - + ]: 30 : if (PG_ARGISNULL(0))
6713 : 0 : PG_RETURN_NULL();
6714 : 30 : array = PG_GETARG_ARRAYTYPE_P(0);
6715 : :
6716 : 30 : array = array_replace_internal(array,
6717 : : search, search_isnull,
6718 : : replace, replace_isnull,
6719 : : false, PG_GET_COLLATION(),
6720 : : fcinfo);
6721 : 30 : PG_RETURN_ARRAYTYPE_P(array);
6722 : : }
6723 : :
6724 : : /*
6725 : : * Implements width_bucket(anyelement, anyarray).
6726 : : *
6727 : : * 'thresholds' is an array containing lower bound values for each bucket;
6728 : : * these must be sorted from smallest to largest, or bogus results will be
6729 : : * produced. If N thresholds are supplied, the output is from 0 to N:
6730 : : * 0 is for inputs < first threshold, N is for inputs >= last threshold.
6731 : : */
6732 : : Datum
6733 : 542 : width_bucket_array(PG_FUNCTION_ARGS)
6734 : : {
6735 : 542 : Datum operand = PG_GETARG_DATUM(0);
6736 : 542 : ArrayType *thresholds = PG_GETARG_ARRAYTYPE_P(1);
6737 : 542 : Oid collation = PG_GET_COLLATION();
6738 : 542 : Oid element_type = ARR_ELEMTYPE(thresholds);
6739 : : int result;
6740 : :
6741 : : /* Check input */
6742 [ + + ]: 542 : if (ARR_NDIM(thresholds) > 1)
6743 [ + - ]: 4 : ereport(ERROR,
6744 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
6745 : : errmsg("thresholds must be one-dimensional array")));
6746 : :
6747 [ + + ]: 538 : if (array_contains_nulls(thresholds))
6748 [ + - ]: 4 : ereport(ERROR,
6749 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6750 : : errmsg("thresholds array must not contain NULLs")));
6751 : :
6752 : : /* We have a dedicated implementation for float8 data */
6753 [ + + ]: 534 : if (element_type == FLOAT8OID)
6754 : 244 : result = width_bucket_array_float8(operand, thresholds);
6755 : : else
6756 : : {
6757 : : TypeCacheEntry *typentry;
6758 : :
6759 : : /* Cache information about the input type */
6760 : 290 : typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
6761 [ + + ]: 290 : if (typentry == NULL ||
6762 [ - + ]: 260 : typentry->type_id != element_type)
6763 : : {
6764 : 30 : typentry = lookup_type_cache(element_type,
6765 : : TYPECACHE_CMP_PROC_FINFO);
6766 [ - + ]: 30 : if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
6767 [ # # ]: 0 : ereport(ERROR,
6768 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
6769 : : errmsg("could not identify a comparison function for type %s",
6770 : : format_type_be(element_type))));
6771 : 30 : fcinfo->flinfo->fn_extra = typentry;
6772 : : }
6773 : :
6774 : : /*
6775 : : * We have separate implementation paths for fixed- and variable-width
6776 : : * types, since indexing the array is a lot cheaper in the first case.
6777 : : */
6778 [ + + ]: 290 : if (typentry->typlen > 0)
6779 : 62 : result = width_bucket_array_fixed(operand, thresholds,
6780 : : collation, typentry);
6781 : : else
6782 : 228 : result = width_bucket_array_variable(operand, thresholds,
6783 : : collation, typentry);
6784 : : }
6785 : :
6786 : : /* Avoid leaking memory when handed toasted input. */
6787 [ - + ]: 534 : PG_FREE_IF_COPY(thresholds, 1);
6788 : :
6789 : 534 : PG_RETURN_INT32(result);
6790 : : }
6791 : :
6792 : : /*
6793 : : * width_bucket_array for float8 data.
6794 : : */
6795 : : static int
6796 : 244 : width_bucket_array_float8(Datum operand, ArrayType *thresholds)
6797 : : {
6798 : 244 : float8 op = DatumGetFloat8(operand);
6799 : : float8 *thresholds_data;
6800 : : int left;
6801 : : int right;
6802 : :
6803 : : /*
6804 : : * Since we know the array contains no NULLs, we can just index it
6805 : : * directly.
6806 : : */
6807 [ - + ]: 244 : thresholds_data = (float8 *) ARR_DATA_PTR(thresholds);
6808 : :
6809 : 244 : left = 0;
6810 : 244 : right = ArrayGetNItems(ARR_NDIM(thresholds), ARR_DIMS(thresholds));
6811 : :
6812 : : /*
6813 : : * If the probe value is a NaN, it's greater than or equal to all possible
6814 : : * threshold values (including other NaNs), so we need not search. Note
6815 : : * that this would give the same result as searching even if the array
6816 : : * contains multiple NaNs (as long as they're correctly sorted), since the
6817 : : * loop logic will find the rightmost of multiple equal threshold values.
6818 : : */
6819 [ + + ]: 244 : if (isnan(op))
6820 : 4 : return right;
6821 : :
6822 : : /* Find the bucket */
6823 [ + + ]: 756 : while (left < right)
6824 : : {
6825 : 516 : int mid = (left + right) / 2;
6826 : :
6827 [ + + + + ]: 516 : if (isnan(thresholds_data[mid]) || op < thresholds_data[mid])
6828 : 224 : right = mid;
6829 : : else
6830 : 292 : left = mid + 1;
6831 : : }
6832 : :
6833 : 240 : return left;
6834 : : }
6835 : :
6836 : : /*
6837 : : * width_bucket_array for generic fixed-width data types.
6838 : : */
6839 : : static int
6840 : 62 : width_bucket_array_fixed(Datum operand,
6841 : : ArrayType *thresholds,
6842 : : Oid collation,
6843 : : TypeCacheEntry *typentry)
6844 : : {
6845 : 62 : LOCAL_FCINFO(locfcinfo, 2);
6846 : : char *thresholds_data;
6847 : 62 : int typlen = typentry->typlen;
6848 : 62 : bool typbyval = typentry->typbyval;
6849 : : int left;
6850 : : int right;
6851 : :
6852 : : /*
6853 : : * Since we know the array contains no NULLs, we can just index it
6854 : : * directly.
6855 : : */
6856 [ - + ]: 62 : thresholds_data = (char *) ARR_DATA_PTR(thresholds);
6857 : :
6858 : 62 : InitFunctionCallInfoData(*locfcinfo, &typentry->cmp_proc_finfo, 2,
6859 : : collation, NULL, NULL);
6860 : :
6861 : : /* Find the bucket */
6862 : 62 : left = 0;
6863 : 62 : right = ArrayGetNItems(ARR_NDIM(thresholds), ARR_DIMS(thresholds));
6864 [ + + ]: 183 : while (left < right)
6865 : : {
6866 : 121 : int mid = (left + right) / 2;
6867 : : char *ptr;
6868 : : int32 cmpresult;
6869 : :
6870 : 121 : ptr = thresholds_data + mid * typlen;
6871 : :
6872 : 121 : locfcinfo->args[0].value = operand;
6873 : 121 : locfcinfo->args[0].isnull = false;
6874 : 121 : locfcinfo->args[1].value = fetch_att(ptr, typbyval, typlen);
6875 : 121 : locfcinfo->args[1].isnull = false;
6876 : :
6877 : 121 : cmpresult = DatumGetInt32(FunctionCallInvoke(locfcinfo));
6878 : :
6879 : : /* We don't expect comparison support functions to return null */
6880 : : Assert(!locfcinfo->isnull);
6881 : :
6882 [ + + ]: 121 : if (cmpresult < 0)
6883 : 60 : right = mid;
6884 : : else
6885 : 61 : left = mid + 1;
6886 : : }
6887 : :
6888 : 62 : return left;
6889 : : }
6890 : :
6891 : : /*
6892 : : * width_bucket_array for generic variable-width data types.
6893 : : */
6894 : : static int
6895 : 228 : width_bucket_array_variable(Datum operand,
6896 : : ArrayType *thresholds,
6897 : : Oid collation,
6898 : : TypeCacheEntry *typentry)
6899 : : {
6900 : 228 : LOCAL_FCINFO(locfcinfo, 2);
6901 : : char *thresholds_data;
6902 : 228 : int typlen = typentry->typlen;
6903 : 228 : bool typbyval = typentry->typbyval;
6904 : 228 : char typalign = typentry->typalign;
6905 : 228 : uint8 typalignby = typalign_to_alignby(typalign);
6906 : : int left;
6907 : : int right;
6908 : :
6909 [ - + ]: 228 : thresholds_data = (char *) ARR_DATA_PTR(thresholds);
6910 : :
6911 : 228 : InitFunctionCallInfoData(*locfcinfo, &typentry->cmp_proc_finfo, 2,
6912 : : collation, NULL, NULL);
6913 : :
6914 : : /* Find the bucket */
6915 : 228 : left = 0;
6916 : 228 : right = ArrayGetNItems(ARR_NDIM(thresholds), ARR_DIMS(thresholds));
6917 [ + + ]: 712 : while (left < right)
6918 : : {
6919 : 484 : int mid = (left + right) / 2;
6920 : : char *ptr;
6921 : : int i;
6922 : : int32 cmpresult;
6923 : :
6924 : : /* Locate mid'th array element by advancing from left element */
6925 : 484 : ptr = thresholds_data;
6926 [ + + ]: 828 : for (i = left; i < mid; i++)
6927 : : {
6928 [ - + + - ]: 344 : ptr = att_addlength_pointer(ptr, typlen, ptr);
6929 : 344 : ptr = (char *) att_nominal_alignby(ptr, typalignby);
6930 : : }
6931 : :
6932 : 484 : locfcinfo->args[0].value = operand;
6933 : 484 : locfcinfo->args[0].isnull = false;
6934 : 484 : locfcinfo->args[1].value = fetch_att(ptr, typbyval, typlen);
6935 : 484 : locfcinfo->args[1].isnull = false;
6936 : :
6937 : 484 : cmpresult = DatumGetInt32(FunctionCallInvoke(locfcinfo));
6938 : :
6939 : : /* We don't expect comparison support functions to return null */
6940 : : Assert(!locfcinfo->isnull);
6941 : :
6942 [ + + ]: 484 : if (cmpresult < 0)
6943 : 200 : right = mid;
6944 : : else
6945 : : {
6946 : 284 : left = mid + 1;
6947 : :
6948 : : /*
6949 : : * Move the thresholds pointer to match new "left" index, so we
6950 : : * don't have to seek over those elements again. This trick
6951 : : * ensures we do only O(N) array indexing work, not O(N^2).
6952 : : */
6953 [ - + + - ]: 284 : ptr = att_addlength_pointer(ptr, typlen, ptr);
6954 : 284 : thresholds_data = (char *) att_nominal_alignby(ptr, typalignby);
6955 : : }
6956 : : }
6957 : :
6958 : 228 : return left;
6959 : : }
6960 : :
6961 : : /*
6962 : : * Trim the last N elements from an array by building an appropriate slice.
6963 : : * Only the first dimension is trimmed.
6964 : : */
6965 : : Datum
6966 : 32 : trim_array(PG_FUNCTION_ARGS)
6967 : : {
6968 : 32 : ArrayType *v = PG_GETARG_ARRAYTYPE_P(0);
6969 : 32 : int n = PG_GETARG_INT32(1);
6970 [ + + ]: 32 : int array_length = (ARR_NDIM(v) > 0) ? ARR_DIMS(v)[0] : 0;
6971 : : int16 elmlen;
6972 : : bool elmbyval;
6973 : : char elmalign;
6974 : : int lower[MAXDIM];
6975 : : int upper[MAXDIM];
6976 : : bool lowerProvided[MAXDIM];
6977 : : bool upperProvided[MAXDIM];
6978 : : Datum result;
6979 : :
6980 : : /* Per spec, throw an error if out of bounds */
6981 [ + + + + ]: 32 : if (n < 0 || n > array_length)
6982 [ + - ]: 12 : ereport(ERROR,
6983 : : (errcode(ERRCODE_ARRAY_ELEMENT_ERROR),
6984 : : errmsg("number of elements to trim must be between 0 and %d",
6985 : : array_length)));
6986 : :
6987 : : /* Set all the bounds as unprovided except the first upper bound */
6988 : 20 : memset(lowerProvided, false, sizeof(lowerProvided));
6989 : 20 : memset(upperProvided, false, sizeof(upperProvided));
6990 [ + - ]: 20 : if (ARR_NDIM(v) > 0)
6991 : : {
6992 : 20 : upper[0] = ARR_LBOUND(v)[0] + array_length - n - 1;
6993 : 20 : upperProvided[0] = true;
6994 : : }
6995 : :
6996 : : /* Fetch the needed information about the element type */
6997 : 20 : get_typlenbyvalalign(ARR_ELEMTYPE(v), &elmlen, &elmbyval, &elmalign);
6998 : :
6999 : : /* Get the slice */
7000 : 20 : result = array_get_slice(PointerGetDatum(v), 1,
7001 : : upper, lower, upperProvided, lowerProvided,
7002 : : -1, elmlen, elmbyval, elmalign);
7003 : :
7004 : 20 : PG_RETURN_DATUM(result);
7005 : : }
|