arrayfuncs.c 107 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * arrayfuncs.c
4
 *	  Support functions for arrays.
5
 *
6
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $PostgreSQL: pgsql/src/backend/utils/adt/arrayfuncs.c,v 1.141 2008/02/29 20:58:33 alvherre Exp $
12 13 14
 *
 *-------------------------------------------------------------------------
 */
15
#include "postgres.h"
16

17 18
#include <ctype.h>

19
#include "access/tupmacs.h"
20
#include "libpq/pqformat.h"
21
#include "parser/parse_coerce.h"
Bruce Momjian's avatar
Bruce Momjian committed
22
#include "utils/array.h"
23
#include "utils/builtins.h"
24
#include "utils/datum.h"
25
#include "utils/lsyscache.h"
26
#include "utils/memutils.h"
27
#include "utils/typcache.h"
28

29

30 31
/*
 * GUC parameter
32
 */
33
bool		Array_nulls = true;
34

35
/*
36 37 38 39
 * Local definitions
 */
#define ASSGN	 "="

40 41 42 43 44 45 46 47 48 49 50 51
typedef enum
{
	ARRAY_NO_LEVEL,
	ARRAY_LEVEL_STARTED,
	ARRAY_ELEM_STARTED,
	ARRAY_ELEM_COMPLETED,
	ARRAY_QUOTED_ELEM_STARTED,
	ARRAY_QUOTED_ELEM_COMPLETED,
	ARRAY_ELEM_DELIMITED,
	ARRAY_LEVEL_COMPLETED,
	ARRAY_LEVEL_DELIMITED
} ArrayParseState;
52

53 54
static int	ArrayCount(const char *str, int *dim, char typdelim);
static void ReadArrayStr(char *arrayStr, const char *origStr,
55
			 int nitems, int ndim, int *dim,
56
			 FmgrInfo *inputproc, Oid typioparam, int32 typmod,
57 58
			 char typdelim,
			 int typlen, bool typbyval, char typalign,
59 60 61
			 Datum *values, bool *nulls,
			 bool *hasnulls, int32 *nbytes);
static void ReadArrayBinary(StringInfo buf, int nitems,
62
				FmgrInfo *receiveproc, Oid typioparam, int32 typmod,
Bruce Momjian's avatar
Bruce Momjian committed
63
				int typlen, bool typbyval, char typalign,
64 65 66
				Datum *values, bool *nulls,
				bool *hasnulls, int32 *nbytes);
static void CopyArrayEls(ArrayType *array,
67 68 69
			 Datum *values, bool *nulls, int nitems,
			 int typlen, bool typbyval, char typalign,
			 bool freedata);
70 71
static bool array_get_isnull(const bits8 *nullbitmap, int offset);
static void array_set_isnull(bits8 *nullbitmap, int offset, bool isNull);
72
static Datum ArrayCast(char *value, bool byval, int len);
Bruce Momjian's avatar
Bruce Momjian committed
73 74 75
static int ArrayCastAndSet(Datum src,
				int typlen, bool typbyval, char typalign,
				char *dest);
76
static char *array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems,
77 78 79 80 81 82
		   int typlen, bool typbyval, char typalign);
static int array_nelems_size(char *ptr, int offset, bits8 *nullbitmap,
				  int nitems, int typlen, bool typbyval, char typalign);
static int array_copy(char *destptr, int nitems,
		   char *srcptr, int offset, bits8 *nullbitmap,
		   int typlen, bool typbyval, char typalign);
83
static int array_slice_size(char *arraydataptr, bits8 *arraynullsptr,
84 85 86
				 int ndim, int *dim, int *lb,
				 int *st, int *endp,
				 int typlen, bool typbyval, char typalign);
87
static void array_extract_slice(ArrayType *newarray,
88 89 90 91
					int ndim, int *dim, int *lb,
					char *arraydataptr, bits8 *arraynullsptr,
					int *st, int *endp,
					int typlen, bool typbyval, char typalign);
92
static void array_insert_slice(ArrayType *destArray, ArrayType *origArray,
93 94 95 96
				   ArrayType *srcArray,
				   int ndim, int *dim, int *lb,
				   int *st, int *endp,
				   int typlen, bool typbyval, char typalign);
Bruce Momjian's avatar
Bruce Momjian committed
97
static int	array_cmp(FunctionCallInfo fcinfo);
98

99

100
/*
101 102
 * array_in :
 *		  converts an array from the external format in "string" to
103
 *		  its internal format.
104
 *
105
 * return value :
106
 *		  the internal representation of the input array
107
 */
108 109
Datum
array_in(PG_FUNCTION_ARGS)
110
{
111 112 113
	char	   *string = PG_GETARG_CSTRING(0);	/* external form */
	Oid			element_type = PG_GETARG_OID(1);		/* type of an array
														 * element */
114
	int32		typmod = PG_GETARG_INT32(2);	/* typmod for array elements */
115
	int			typlen;
116
	bool		typbyval;
117
	char		typalign;
118
	char		typdelim;
119
	Oid			typioparam;
120
	char	   *string_save,
121
			   *p;
122
	int			i,
123
				nitems;
124
	Datum	   *dataPtr;
125 126 127 128
	bool	   *nullsPtr;
	bool		hasnulls;
	int32		nbytes;
	int32		dataoffset;
129
	ArrayType  *retval;
130 131 132
	int			ndim,
				dim[MAXDIM],
				lBound[MAXDIM];
133
	ArrayMetaState *my_extra;
134

135 136
	/*
	 * We arrange to look up info about element type, including its input
137 138
	 * conversion proc, only once per series of calls, assuming the element
	 * type doesn't change underneath us.
139 140 141 142 143
	 */
	my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
	if (my_extra == NULL)
	{
		fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
144
													  sizeof(ArrayMetaState));
145
		my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
146
		my_extra->element_type = ~element_type;
147 148 149 150
	}

	if (my_extra->element_type != element_type)
	{
Bruce Momjian's avatar
Bruce Momjian committed
151
		/*
152
		 * Get info about element type, including its input conversion proc
Bruce Momjian's avatar
Bruce Momjian committed
153
		 */
154 155 156
		get_type_io_data(element_type, IOFunc_input,
						 &my_extra->typlen, &my_extra->typbyval,
						 &my_extra->typalign, &my_extra->typdelim,
157
						 &my_extra->typioparam, &my_extra->typiofunc);
158 159 160 161 162 163 164 165
		fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
					  fcinfo->flinfo->fn_mcxt);
		my_extra->element_type = element_type;
	}
	typlen = my_extra->typlen;
	typbyval = my_extra->typbyval;
	typalign = my_extra->typalign;
	typdelim = my_extra->typdelim;
166
	typioparam = my_extra->typioparam;
167

168
	/* Make a modifiable copy of the input */
169
	string_save = pstrdup(string);
170

171 172 173 174 175
	/*
	 * If the input string starts with dimension info, read and use that.
	 * Otherwise, we require the input to be in curly-brace style, and we
	 * prescan the input to determine dimensions.
	 *
176 177
	 * Dimension info takes the form of one or more [n] or [m:n] items. The
	 * outer loop iterates once per dimension item.
178 179 180 181
	 */
	p = string_save;
	ndim = 0;
	for (;;)
182
	{
183 184 185 186 187 188 189
		char	   *q;
		int			ub;

		/*
		 * Note: we currently allow whitespace between, but not within,
		 * dimension items.
		 */
190
		while (isspace((unsigned char) *p))
191
			p++;
192 193 194 195
		if (*p != '[')
			break;				/* no more dimension items */
		p++;
		if (ndim >= MAXDIM)
196 197
			ereport(ERROR,
					(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
198 199
					 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
							ndim, MAXDIM)));
200

201
		for (q = p; isdigit((unsigned char) *q) || (*q == '-') || (*q == '+'); q++);
202
		if (q == p)				/* no digits? */
203 204 205 206
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
					 errmsg("missing dimension value")));

207
		if (*q == ':')
208
		{
209
			/* [m:n] format */
210
			*q = '\0';
211
			lBound[ndim] = atoi(p);
212
			p = q + 1;
213
			for (q = p; isdigit((unsigned char) *q) || (*q == '-') || (*q == '+'); q++);
214
			if (q == p)			/* no digits? */
215 216 217
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
						 errmsg("missing dimension value")));
218 219
		}
		else
220 221 222 223 224
		{
			/* [n] format */
			lBound[ndim] = 1;
		}
		if (*q != ']')
225 226 227 228
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
					 errmsg("missing \"]\" in array dimensions")));

229 230 231 232
		*q = '\0';
		ub = atoi(p);
		p = q + 1;
		if (ub < lBound[ndim])
233 234
			ereport(ERROR,
					(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
235
					 errmsg("upper bound cannot be less than lower bound")));
236

237 238
		dim[ndim] = ub - lBound[ndim] + 1;
		ndim++;
239 240 241 242
	}

	if (ndim == 0)
	{
243 244
		/* No array dimensions, so intuit dimensions from brace structure */
		if (*p != '{')
245 246 247
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
					 errmsg("array value must start with \"{\" or dimension information")));
248 249 250
		ndim = ArrayCount(p, dim, typdelim);
		for (i = 0; i < ndim; i++)
			lBound[i] = 1;
251 252 253
	}
	else
	{
254 255 256
		int			ndim_braces,
					dim_braces[MAXDIM];

257
		/* If array dimensions are given, expect '=' operator */
258
		if (strncmp(p, ASSGN, strlen(ASSGN)) != 0)
259 260 261
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
					 errmsg("missing assignment operator")));
262
		p += strlen(ASSGN);
263
		while (isspace((unsigned char) *p))
264
			p++;
265 266

		/*
267 268
		 * intuit dimensions from brace structure -- it better match what we
		 * were given
269 270 271 272 273 274 275 276 277
		 */
		if (*p != '{')
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
					 errmsg("array value must start with \"{\" or dimension information")));
		ndim_braces = ArrayCount(p, dim_braces, typdelim);
		if (ndim_braces != ndim)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
278
				errmsg("array dimensions incompatible with array literal")));
279 280 281 282 283
		for (i = 0; i < ndim; ++i)
		{
			if (dim[i] != dim_braces[i])
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
284
				errmsg("array dimensions incompatible with array literal")));
285
		}
286 287
	}

288
#ifdef ARRAYDEBUG
289 290 291 292 293 294
	printf("array_in- ndim %d (", ndim);
	for (i = 0; i < ndim; i++)
	{
		printf(" %d", dim[i]);
	};
	printf(") for %s\n", string);
295 296
#endif

297
	/* This checks for overflow of the array dimensions */
298
	nitems = ArrayGetNItems(ndim, dim);
299
	/* Empty array? */
300
	if (nitems == 0)
301 302 303 304 305 306 307 308 309 310 311 312
		PG_RETURN_ARRAYTYPE_P(construct_empty_array(element_type));

	dataPtr = (Datum *) palloc(nitems * sizeof(Datum));
	nullsPtr = (bool *) palloc(nitems * sizeof(bool));
	ReadArrayStr(p, string,
				 nitems, ndim, dim,
				 &my_extra->proc, typioparam, typmod,
				 typdelim,
				 typlen, typbyval, typalign,
				 dataPtr, nullsPtr,
				 &hasnulls, &nbytes);
	if (hasnulls)
313
	{
314 315
		dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
		nbytes += dataoffset;
316
	}
317 318 319 320 321 322
	else
	{
		dataoffset = 0;			/* marker for no null bitmap */
		nbytes += ARR_OVERHEAD_NONULLS(ndim);
	}
	retval = (ArrayType *) palloc(nbytes);
323
	SET_VARSIZE(retval, nbytes);
324
	retval->ndim = ndim;
325
	retval->dataoffset = dataoffset;
326
	retval->elemtype = element_type;
327 328
	memcpy(ARR_DIMS(retval), dim, ndim * sizeof(int));
	memcpy(ARR_LBOUND(retval), lBound, ndim * sizeof(int));
329

330 331 332 333 334
	CopyArrayEls(retval,
				 dataPtr, nullsPtr, nitems,
				 typlen, typbyval, typalign,
				 true);

335
	pfree(dataPtr);
336
	pfree(nullsPtr);
337
	pfree(string_save);
338

339
	PG_RETURN_ARRAYTYPE_P(retval);
340 341
}

342
/*
343
 * ArrayCount
344 345 346 347
 *	 Determines the dimensions for an array string.
 *
 * Returns number of dimensions as function result.  The axis lengths are
 * returned in dim[], which must be of size MAXDIM.
348 349
 */
static int
350
ArrayCount(const char *str, int *dim, char typdelim)
351
{
Bruce Momjian's avatar
Bruce Momjian committed
352 353 354 355 356 357
	int			nest_level = 0,
				i;
	int			ndim = 1,
				temp[MAXDIM],
				nelems[MAXDIM],
				nelems_last[MAXDIM];
358
	bool		in_quotes = false;
Bruce Momjian's avatar
Bruce Momjian committed
359 360
	bool		eoArray = false;
	bool		empty_array = true;
361
	const char *ptr;
Bruce Momjian's avatar
Bruce Momjian committed
362
	ArrayParseState parse_state = ARRAY_NO_LEVEL;
363 364

	for (i = 0; i < MAXDIM; ++i)
365
	{
366
		temp[i] = dim[i] = 0;
367 368
		nelems_last[i] = nelems[i] = 1;
	}
369

370 371
	ptr = str;
	while (!eoArray)
372
	{
373
		bool		itemdone = false;
374

375
		while (!itemdone)
376
		{
377 378 379
			if (parse_state == ARRAY_ELEM_STARTED ||
				parse_state == ARRAY_QUOTED_ELEM_STARTED)
				empty_array = false;
Bruce Momjian's avatar
Bruce Momjian committed
380

381
			switch (*ptr)
382
			{
383
				case '\0':
384
					/* Signal a premature end of the string */
385 386
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
387
							 errmsg("malformed array literal: \"%s\"", str)));
388
					break;
389
				case '\\':
Bruce Momjian's avatar
Bruce Momjian committed
390

391
					/*
392 393 394
					 * An escape must be after a level start, after an element
					 * start, or after an element delimiter. In any case we
					 * now must be past an element start.
395 396 397 398 399 400
					 */
					if (parse_state != ARRAY_LEVEL_STARTED &&
						parse_state != ARRAY_ELEM_STARTED &&
						parse_state != ARRAY_QUOTED_ELEM_STARTED &&
						parse_state != ARRAY_ELEM_DELIMITED)
						ereport(ERROR,
401 402
								(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
							errmsg("malformed array literal: \"%s\"", str)));
403 404
					if (parse_state != ARRAY_QUOTED_ELEM_STARTED)
						parse_state = ARRAY_ELEM_STARTED;
405 406 407 408
					/* skip the escaped character */
					if (*(ptr + 1))
						ptr++;
					else
409
						ereport(ERROR,
410 411
								(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
							errmsg("malformed array literal: \"%s\"", str)));
412
					break;
413
				case '\"':
Bruce Momjian's avatar
Bruce Momjian committed
414

415 416
					/*
					 * A quote must be after a level start, after a quoted
417 418
					 * element start, or after an element delimiter. In any
					 * case we now must be past an element start.
419 420 421 422 423
					 */
					if (parse_state != ARRAY_LEVEL_STARTED &&
						parse_state != ARRAY_QUOTED_ELEM_STARTED &&
						parse_state != ARRAY_ELEM_DELIMITED)
						ereport(ERROR,
424 425
								(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
							errmsg("malformed array literal: \"%s\"", str)));
426 427
					in_quotes = !in_quotes;
					if (in_quotes)
428 429 430
						parse_state = ARRAY_QUOTED_ELEM_STARTED;
					else
						parse_state = ARRAY_QUOTED_ELEM_COMPLETED;
431 432
					break;
				case '{':
433
					if (!in_quotes)
434
					{
435
						/*
436 437 438
						 * A left brace can occur if no nesting has occurred
						 * yet, after a level start, or after a level
						 * delimiter.
439 440 441 442 443
						 */
						if (parse_state != ARRAY_NO_LEVEL &&
							parse_state != ARRAY_LEVEL_STARTED &&
							parse_state != ARRAY_LEVEL_DELIMITED)
							ereport(ERROR,
444 445
							   (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
							errmsg("malformed array literal: \"%s\"", str)));
446
						parse_state = ARRAY_LEVEL_STARTED;
447
						if (nest_level >= MAXDIM)
448
							ereport(ERROR,
449 450 451
									(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
									 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
											nest_level, MAXDIM)));
452 453
						temp[nest_level] = 0;
						nest_level++;
454 455
						if (ndim < nest_level)
							ndim = nest_level;
456 457 458
					}
					break;
				case '}':
459
					if (!in_quotes)
460
					{
461
						/*
462 463 464
						 * A right brace can occur after an element start, an
						 * element completion, a quoted element completion, or
						 * a level completion.
465 466 467 468
						 */
						if (parse_state != ARRAY_ELEM_STARTED &&
							parse_state != ARRAY_ELEM_COMPLETED &&
							parse_state != ARRAY_QUOTED_ELEM_COMPLETED &&
469
							parse_state != ARRAY_LEVEL_COMPLETED &&
Bruce Momjian's avatar
Bruce Momjian committed
470
							!(nest_level == 1 && parse_state == ARRAY_LEVEL_STARTED))
471
							ereport(ERROR,
472 473
							   (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
							errmsg("malformed array literal: \"%s\"", str)));
474
						parse_state = ARRAY_LEVEL_COMPLETED;
475
						if (nest_level == 0)
476
							ereport(ERROR,
477 478
							   (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
							errmsg("malformed array literal: \"%s\"", str)));
479
						nest_level--;
480 481

						if ((nelems_last[nest_level] != 1) &&
482
							(nelems[nest_level] != nelems_last[nest_level]))
483
							ereport(ERROR,
484 485 486 487
							   (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
								errmsg("multidimensional arrays must have "
									   "array expressions with matching "
									   "dimensions")));
488 489
						nelems_last[nest_level] = nelems[nest_level];
						nelems[nest_level] = 1;
490
						if (nest_level == 0)
491 492 493 494 495 496 497 498 499
							eoArray = itemdone = true;
						else
						{
							/*
							 * We don't set itemdone here; see comments in
							 * ReadArrayStr
							 */
							temp[nest_level - 1]++;
						}
500 501 502
					}
					break;
				default:
503
					if (!in_quotes)
504
					{
505 506 507
						if (*ptr == typdelim)
						{
							/*
508 509 510
							 * Delimiters can occur after an element start, an
							 * element completion, a quoted element
							 * completion, or a level completion.
Bruce Momjian's avatar
Bruce Momjian committed
511
							 */
512 513
							if (parse_state != ARRAY_ELEM_STARTED &&
								parse_state != ARRAY_ELEM_COMPLETED &&
514
								parse_state != ARRAY_QUOTED_ELEM_COMPLETED &&
515 516
								parse_state != ARRAY_LEVEL_COMPLETED)
								ereport(ERROR,
517 518
								(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
								 errmsg("malformed array literal: \"%s\"", str)));
519 520 521 522 523 524 525
							if (parse_state == ARRAY_LEVEL_COMPLETED)
								parse_state = ARRAY_LEVEL_DELIMITED;
							else
								parse_state = ARRAY_ELEM_DELIMITED;
							itemdone = true;
							nelems[nest_level - 1]++;
						}
526
						else if (!isspace((unsigned char) *ptr))
527 528
						{
							/*
Bruce Momjian's avatar
Bruce Momjian committed
529
							 * Other non-space characters must be after a
530 531 532
							 * level start, after an element start, or after
							 * an element delimiter. In any case we now must
							 * be past an element start.
Bruce Momjian's avatar
Bruce Momjian committed
533
							 */
534 535 536 537
							if (parse_state != ARRAY_LEVEL_STARTED &&
								parse_state != ARRAY_ELEM_STARTED &&
								parse_state != ARRAY_ELEM_DELIMITED)
								ereport(ERROR,
538 539
								(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
								 errmsg("malformed array literal: \"%s\"", str)));
540 541
							parse_state = ARRAY_ELEM_STARTED;
						}
542
					}
543
					break;
544
			}
545 546
			if (!itemdone)
				ptr++;
547
		}
548
		temp[ndim - 1]++;
549
		ptr++;
550
	}
Bruce Momjian's avatar
Bruce Momjian committed
551

552 553 554
	/* only whitespace is allowed after the closing brace */
	while (*ptr)
	{
555
		if (!isspace((unsigned char) *ptr++))
556
			ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
557 558
					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
					 errmsg("malformed array literal: \"%s\"", str)));
559
	}
Bruce Momjian's avatar
Bruce Momjian committed
560

561 562 563
	/* special case for an empty array */
	if (empty_array)
		return 0;
Bruce Momjian's avatar
Bruce Momjian committed
564

565 566 567
	for (i = 0; i < ndim; ++i)
		dim[i] = temp[i];

568
	return ndim;
569 570
}

571
/*
572
 * ReadArrayStr :
573 574 575
 *	 parses the array string pointed to by "arrayStr" and converts the values
 *	 to internal format.  Unspecified elements are initialized to nulls.
 *	 The array dimensions must already have been determined.
576
 *
577 578 579 580 581 582 583 584 585 586 587
 * Inputs:
 *	arrayStr: the string to parse.
 *			  CAUTION: the contents of "arrayStr" will be modified!
 *	origStr: the unmodified input string, used only in error messages.
 *	nitems: total number of array elements, as already determined.
 *	ndim: number of array dimensions
 *	dim[]: array axis lengths
 *	inputproc: type-specific input procedure for element datatype.
 *	typioparam, typmod: auxiliary values to pass to inputproc.
 *	typdelim: the value delimiter (type-specific).
 *	typlen, typbyval, typalign: storage parameters of element datatype.
588
 *
589 590 591 592 593 594 595 596 597
 * Outputs:
 *	values[]: filled with converted data values.
 *	nulls[]: filled with is-null markers.
 *	*hasnulls: set TRUE iff there are any null elements.
 *	*nbytes: set to total size of data area needed (including alignment
 *		padding but not including array header overhead).
 *
 * Note that values[] and nulls[] are allocated by the caller, and must have
 * nitems elements.
598
 */
599
static void
600
ReadArrayStr(char *arrayStr,
601
			 const char *origStr,
602 603 604 605
			 int nitems,
			 int ndim,
			 int *dim,
			 FmgrInfo *inputproc,
606
			 Oid typioparam,
607 608 609 610 611
			 int32 typmod,
			 char typdelim,
			 int typlen,
			 bool typbyval,
			 char typalign,
612 613 614 615
			 Datum *values,
			 bool *nulls,
			 bool *hasnulls,
			 int32 *nbytes)
616
{
617 618
	int			i,
				nest_level = 0;
619 620
	char	   *srcptr;
	bool		in_quotes = false;
621
	bool		eoArray = false;
622 623
	bool		hasnull;
	int32		totbytes;
624 625
	int			indx[MAXDIM],
				prod[MAXDIM];
626 627

	mda_get_prod(ndim, dim, prod);
628
	MemSet(indx, 0, sizeof(indx));
629

630 631 632
	/* Initialize is-null markers to true */
	memset(nulls, true, nitems * sizeof(bool));

633
	/*
634 635 636 637
	 * We have to remove " and \ characters to create a clean item value to
	 * pass to the datatype input routine.	We overwrite each item value
	 * in-place within arrayStr to do this.  srcptr is the current scan point,
	 * and dstptr is where we are copying to.
638
	 *
639 640 641
	 * We also want to suppress leading and trailing unquoted whitespace. We
	 * use the leadingspace flag to suppress leading space.  Trailing space is
	 * tracked by using dstendptr to point to the last significant output
642
	 * character.
643
	 *
644 645
	 * The error checking in this routine is mostly pro-forma, since we expect
	 * that ArrayCount() already validated the string.
646 647
	 */
	srcptr = arrayStr;
648 649
	while (!eoArray)
	{
650
		bool		itemdone = false;
651
		bool		leadingspace = true;
652
		bool		hasquoting = false;
653
		char	   *itemstart;
654 655
		char	   *dstptr;
		char	   *dstendptr;
656

657 658
		i = -1;
		itemstart = dstptr = dstendptr = srcptr;
659

660
		while (!itemdone)
661
		{
662
			switch (*srcptr)
663
			{
664 665
				case '\0':
					/* Signal a premature end of the string */
666 667
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
668 669
							 errmsg("malformed array literal: \"%s\"",
									origStr)));
670
					break;
671
				case '\\':
672 673 674 675 676 677 678 679 680 681 682
					/* Skip backslash, copy next character as-is. */
					srcptr++;
					if (*srcptr == '\0')
						ereport(ERROR,
								(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
								 errmsg("malformed array literal: \"%s\"",
										origStr)));
					*dstptr++ = *srcptr++;
					/* Treat the escaped character as non-whitespace */
					leadingspace = false;
					dstendptr = dstptr;
683
					hasquoting = true;	/* can't be a NULL marker */
684
					break;
685
				case '\"':
686 687 688 689
					in_quotes = !in_quotes;
					if (in_quotes)
						leadingspace = false;
					else
Bruce Momjian's avatar
Bruce Momjian committed
690
					{
691 692 693 694 695 696
						/*
						 * Advance dstendptr when we exit in_quotes; this
						 * saves having to do it in all the other in_quotes
						 * cases.
						 */
						dstendptr = dstptr;
Bruce Momjian's avatar
Bruce Momjian committed
697
					}
698
					hasquoting = true;	/* can't be a NULL marker */
699 700
					srcptr++;
					break;
701
				case '{':
702
					if (!in_quotes)
703
					{
704
						if (nest_level >= ndim)
705
							ereport(ERROR,
706 707 708
							   (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
								errmsg("malformed array literal: \"%s\"",
									   origStr)));
709
						nest_level++;
710
						indx[nest_level - 1] = 0;
711
						srcptr++;
712
					}
713 714
					else
						*dstptr++ = *srcptr++;
715 716
					break;
				case '}':
717
					if (!in_quotes)
718
					{
719
						if (nest_level == 0)
720
							ereport(ERROR,
721 722 723
							   (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
								errmsg("malformed array literal: \"%s\"",
									   origStr)));
724
						if (i == -1)
725
							i = ArrayGetOffset0(ndim, indx, prod);
726
						indx[nest_level - 1] = 0;
727 728
						nest_level--;
						if (nest_level == 0)
729
							eoArray = itemdone = true;
730 731
						else
							indx[nest_level - 1]++;
732
						srcptr++;
733
					}
734 735
					else
						*dstptr++ = *srcptr++;
736 737
					break;
				default:
738 739 740
					if (in_quotes)
						*dstptr++ = *srcptr++;
					else if (*srcptr == typdelim)
741 742
					{
						if (i == -1)
743
							i = ArrayGetOffset0(ndim, indx, prod);
744
						itemdone = true;
745
						indx[ndim - 1]++;
746 747 748 749 750
						srcptr++;
					}
					else if (isspace((unsigned char) *srcptr))
					{
						/*
751 752
						 * If leading space, drop it immediately.  Else, copy
						 * but don't advance dstendptr.
753 754 755 756 757 758 759 760 761 762 763
						 */
						if (leadingspace)
							srcptr++;
						else
							*dstptr++ = *srcptr++;
					}
					else
					{
						*dstptr++ = *srcptr++;
						leadingspace = false;
						dstendptr = dstptr;
764 765
					}
					break;
766
			}
767
		}
768 769 770 771

		Assert(dstptr < srcptr);
		*dstendptr = '\0';

772
		if (i < 0 || i >= nitems)
773 774
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
775 776
					 errmsg("malformed array literal: \"%s\"",
							origStr)));
777

778
		if (Array_nulls && !hasquoting &&
779 780 781
			pg_strcasecmp(itemstart, "NULL") == 0)
		{
			/* it's a NULL item */
782 783
			values[i] = InputFunctionCall(inputproc, NULL,
										  typioparam, typmod);
784 785 786 787
			nulls[i] = true;
		}
		else
		{
788 789
			values[i] = InputFunctionCall(inputproc, itemstart,
										  typioparam, typmod);
790 791
			nulls[i] = false;
		}
792
	}
793

794
	/*
795
	 * Check for nulls, compute total data space needed
796
	 */
797 798 799
	hasnull = false;
	totbytes = 0;
	for (i = 0; i < nitems; i++)
800
	{
801 802 803
		if (nulls[i])
			hasnull = true;
		else
804
		{
805 806 807
			/* let's just make sure data is not toasted */
			if (typlen == -1)
				values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
808 809
			totbytes = att_addlength_datum(totbytes, typlen, values[i]);
			totbytes = att_align_nominal(totbytes, typalign);
810 811 812 813 814 815
			/* check for overflow of total request */
			if (!AllocSizeIsValid(totbytes))
				ereport(ERROR,
						(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
						 errmsg("array size exceeds the maximum allowed (%d)",
								(int) MaxAllocSize)));
816
		}
817
	}
818
	*hasnulls = hasnull;
819
	*nbytes = totbytes;
820 821 822
}


823
/*
824 825
 * Copy data into an array object from a temporary array of Datums.
 *
826
 * array: array object (with header fields already filled in)
827
 * values: array of Datums to be copied
828
 * nulls: array of is-null flags (can be NULL if no nulls)
829 830 831 832
 * nitems: number of Datums to be copied
 * typbyval, typlen, typalign: info about element datatype
 * freedata: if TRUE and element type is pass-by-ref, pfree data values
 * referenced by Datums after copying them.
833 834
 *
 * If the input data is of varlena type, the caller must have ensured that
835
 * the values are not toasted.	(Doing it here doesn't work since the
836
 * caller has already allocated space for the array...)
837
 */
838
static void
839
CopyArrayEls(ArrayType *array,
840
			 Datum *values,
841
			 bool *nulls,
842 843
			 int nitems,
			 int typlen,
844
			 bool typbyval,
845 846
			 char typalign,
			 bool freedata)
847
{
848 849 850 851
	char	   *p = ARR_DATA_PTR(array);
	bits8	   *bitmap = ARR_NULLBITMAP(array);
	int			bitval = 0;
	int			bitmask = 1;
852
	int			i;
853 854 855

	if (typbyval)
		freedata = false;
856 857 858

	for (i = 0; i < nitems; i++)
	{
859 860
		if (nulls && nulls[i])
		{
861
			if (!bitmap)		/* shouldn't happen */
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
				elog(ERROR, "null array element where not supported");
			/* bitmap bit stays 0 */
		}
		else
		{
			bitval |= bitmask;
			p += ArrayCastAndSet(values[i], typlen, typbyval, typalign, p);
			if (freedata)
				pfree(DatumGetPointer(values[i]));
		}
		if (bitmap)
		{
			bitmask <<= 1;
			if (bitmask == 0x100)
			{
				*bitmap++ = bitval;
				bitval = 0;
				bitmask = 1;
			}
		}
882
	}
883 884 885

	if (bitmap && bitmask != 1)
		*bitmap = bitval;
886 887
}

888
/*
889 890 891
 * array_out :
 *		   takes the internal representation of an array and returns a string
 *		  containing the array in its external format.
892
 */
893 894
Datum
array_out(PG_FUNCTION_ARGS)
895
{
896
	ArrayType  *v = PG_GETARG_ARRAYTYPE_P(0);
897
	Oid			element_type = ARR_ELEMTYPE(v);
898 899 900
	int			typlen;
	bool		typbyval;
	char		typalign;
901
	char		typdelim;
902 903
	char	   *p,
			   *tmp,
904
			   *retval,
905
			  **values,
906
				dims_str[(MAXDIM * 33) + 2];
907

Bruce Momjian's avatar
Bruce Momjian committed
908 909 910 911 912
	/*
	 * 33 per dim since we assume 15 digits per number + ':' +'[]'
	 *
	 * +2 allows for assignment operator + trailing null
	 */
913 914
	bits8	   *bitmap;
	int			bitmask;
915 916
	bool	   *needquotes,
				needdims = false;
917 918 919 920 921 922 923
	int			nitems,
				overall_length,
				i,
				j,
				k,
				indx[MAXDIM];
	int			ndim,
924
			   *dims,
925
			   *lb;
926
	ArrayMetaState *my_extra;
927

928 929
	/*
	 * We arrange to look up info about element type, including its output
930 931
	 * conversion proc, only once per series of calls, assuming the element
	 * type doesn't change underneath us.
932 933 934 935 936
	 */
	my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
	if (my_extra == NULL)
	{
		fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
937
													  sizeof(ArrayMetaState));
938
		my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
939
		my_extra->element_type = ~element_type;
940 941 942 943
	}

	if (my_extra->element_type != element_type)
	{
Bruce Momjian's avatar
Bruce Momjian committed
944
		/*
945
		 * Get info about element type, including its output conversion proc
Bruce Momjian's avatar
Bruce Momjian committed
946
		 */
947 948 949
		get_type_io_data(element_type, IOFunc_output,
						 &my_extra->typlen, &my_extra->typbyval,
						 &my_extra->typalign, &my_extra->typdelim,
950
						 &my_extra->typioparam, &my_extra->typiofunc);
951 952 953 954 955 956 957 958
		fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
					  fcinfo->flinfo->fn_mcxt);
		my_extra->element_type = element_type;
	}
	typlen = my_extra->typlen;
	typbyval = my_extra->typbyval;
	typalign = my_extra->typalign;
	typdelim = my_extra->typdelim;
959

960
	ndim = ARR_NDIM(v);
961
	dims = ARR_DIMS(v);
962
	lb = ARR_LBOUND(v);
963
	nitems = ArrayGetNItems(ndim, dims);
964 965 966

	if (nitems == 0)
	{
967
		retval = pstrdup("{}");
968
		PG_RETURN_CSTRING(retval);
969 970
	}

971
	/*
972 973
	 * we will need to add explicit dimensions if any dimension has a lower
	 * bound other than one
974 975 976 977 978 979 980 981 982 983
	 */
	for (i = 0; i < ndim; i++)
	{
		if (lb[i] != 1)
		{
			needdims = true;
			break;
		}
	}

984
	/*
985 986 987
	 * Convert all values to string form, count total space needed (including
	 * any overhead such as escaping backslashes), and detect whether each
	 * item needs double quotes.
988 989 990
	 */
	values = (char **) palloc(nitems * sizeof(char *));
	needquotes = (bool *) palloc(nitems * sizeof(bool));
991 992
	overall_length = 1;			/* don't forget to count \0 at end. */

993 994 995 996
	p = ARR_DATA_PTR(v);
	bitmap = ARR_NULLBITMAP(v);
	bitmask = 1;

997 998
	for (i = 0; i < nitems; i++)
	{
999
		bool		needquote;
1000

1001 1002 1003 1004 1005
		/* Get source element, checking for NULL */
		if (bitmap && (*bitmap & bitmask) == 0)
		{
			values[i] = pstrdup("NULL");
			overall_length += 4;
1006
			needquote = false;
1007 1008
		}
		else
1009
		{
1010 1011 1012
			Datum		itemvalue;

			itemvalue = fetch_att(p, typbyval, typlen);
1013
			values[i] = OutputFunctionCall(&my_extra->proc, itemvalue);
1014 1015
			p = att_addlength_pointer(p, typlen, p);
			p = (char *) att_align_nominal(p, typalign);
1016 1017 1018

			/* count data plus backslashes; detect chars needing quotes */
			if (values[i][0] == '\0')
1019
				needquote = true;		/* force quotes for empty string */
1020
			else if (pg_strcasecmp(values[i], "NULL") == 0)
1021
				needquote = true;		/* force quotes for literal NULL */
1022 1023
			else
				needquote = false;
1024

1025
			for (tmp = values[i]; *tmp != '\0'; tmp++)
1026
			{
1027 1028
				char		ch = *tmp;

1029
				overall_length += 1;
1030 1031 1032 1033 1034 1035 1036 1037
				if (ch == '"' || ch == '\\')
				{
					needquote = true;
					overall_length += 1;
				}
				else if (ch == '{' || ch == '}' || ch == typdelim ||
						 isspace((unsigned char) ch))
					needquote = true;
1038
			}
1039
		}
1040

1041
		needquotes[i] = needquote;
1042 1043

		/* Count the pair of double quotes, if needed */
1044
		if (needquote)
1045 1046
			overall_length += 2;
		/* and the comma */
1047
		overall_length += 1;
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058

		/* advance bitmap pointer if any */
		if (bitmap)
		{
			bitmask <<= 1;
			if (bitmask == 0x100)
			{
				bitmap++;
				bitmask = 1;
			}
		}
1059 1060 1061 1062
	}

	/*
	 * count total number of curly braces in output string
1063
	 */
1064 1065 1066 1067
	for (i = j = 0, k = 1; i < ndim; i++)
		k *= dims[i], j += k;

	dims_str[0] = '\0';
1068

1069 1070 1071
	/* add explicit dimensions if required */
	if (needdims)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1072
		char	   *ptr = dims_str;
1073 1074 1075

		for (i = 0; i < ndim; i++)
		{
1076
			sprintf(ptr, "[%d:%d]", lb[i], lb[i] + dims[i] - 1);
1077 1078 1079 1080 1081 1082 1083
			ptr += strlen(ptr);
		}
		*ptr++ = *ASSGN;
		*ptr = '\0';
	}

	retval = (char *) palloc(strlen(dims_str) + overall_length + 2 * j);
1084 1085 1086 1087
	p = retval;

#define APPENDSTR(str)	(strcpy(p, (str)), p += strlen(p))
#define APPENDCHAR(ch)	(*p++ = (ch), *p = '\0')
1088

1089 1090
	if (needdims)
		APPENDSTR(dims_str);
1091
	APPENDCHAR('{');
1092 1093
	for (i = 0; i < ndim; i++)
		indx[i] = 0;
1094 1095 1096 1097 1098
	j = 0;
	k = 0;
	do
	{
		for (i = j; i < ndim - 1; i++)
1099
			APPENDCHAR('{');
1100

1101
		if (needquotes[k])
1102
		{
1103
			APPENDCHAR('"');
1104 1105
			for (tmp = values[k]; *tmp; tmp++)
			{
Bruce Momjian's avatar
Bruce Momjian committed
1106
				char		ch = *tmp;
1107 1108 1109 1110

				if (ch == '"' || ch == '\\')
					*p++ = '\\';
				*p++ = ch;
1111
			}
1112 1113
			*p = '\0';
			APPENDCHAR('"');
1114 1115
		}
		else
1116
			APPENDSTR(values[k]);
1117 1118 1119 1120
		pfree(values[k++]);

		for (i = ndim - 1; i >= 0; i--)
		{
1121
			indx[i] = (indx[i] + 1) % dims[i];
1122 1123
			if (indx[i])
			{
1124
				APPENDCHAR(typdelim);
1125 1126 1127
				break;
			}
			else
1128
				APPENDCHAR('}');
1129 1130 1131 1132
		}
		j = i;
	} while (j != -1);

1133 1134 1135
#undef APPENDSTR
#undef APPENDCHAR

1136
	pfree(values);
1137 1138
	pfree(needquotes);

1139
	PG_RETURN_CSTRING(retval);
1140 1141
}

1142
/*
1143 1144 1145
 * array_recv :
 *		  converts an array from the external binary format to
 *		  its internal format.
1146
 *
1147 1148 1149 1150 1151 1152
 * return value :
 *		  the internal representation of the input array
 */
Datum
array_recv(PG_FUNCTION_ARGS)
{
1153 1154 1155
	StringInfo	buf = (StringInfo) PG_GETARG_POINTER(0);
	Oid			spec_element_type = PG_GETARG_OID(1);	/* type of an array
														 * element */
1156
	int32		typmod = PG_GETARG_INT32(2);	/* typmod for array elements */
1157 1158 1159
	Oid			element_type;
	int			typlen;
	bool		typbyval;
1160
	char		typalign;
1161
	Oid			typioparam;
1162 1163 1164
	int			i,
				nitems;
	Datum	   *dataPtr;
1165 1166 1167 1168
	bool	   *nullsPtr;
	bool		hasnulls;
	int32		nbytes;
	int32		dataoffset;
1169 1170 1171 1172 1173
	ArrayType  *retval;
	int			ndim,
				flags,
				dim[MAXDIM],
				lBound[MAXDIM];
1174
	ArrayMetaState *my_extra;
1175 1176 1177

	/* Get the array header information */
	ndim = pq_getmsgint(buf, 4);
1178 1179 1180 1181 1182 1183 1184
	if (ndim < 0)				/* we do allow zero-dimension arrays */
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
				 errmsg("invalid number of dimensions: %d", ndim)));
	if (ndim > MAXDIM)
		ereport(ERROR,
				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1185 1186
				 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
						ndim, MAXDIM)));
1187

1188
	flags = pq_getmsgint(buf, 4);
1189
	if (flags != 0 && flags != 1)
1190 1191 1192 1193
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
				 errmsg("invalid array flags")));

1194 1195 1196 1197
	element_type = pq_getmsgint(buf, sizeof(Oid));
	if (element_type != spec_element_type)
	{
		/* XXX Can we allow taking the input element type in any cases? */
1198 1199 1200
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
				 errmsg("wrong element type")));
1201 1202 1203 1204 1205 1206 1207
	}

	for (i = 0; i < ndim; i++)
	{
		dim[i] = pq_getmsgint(buf, 4);
		lBound[i] = pq_getmsgint(buf, 4);
	}
1208 1209

	/* This checks for overflow of array dimensions */
1210 1211
	nitems = ArrayGetNItems(ndim, dim);

1212
	/*
1213 1214 1215
	 * We arrange to look up info about element type, including its receive
	 * conversion proc, only once per series of calls, assuming the element
	 * type doesn't change underneath us.
1216 1217 1218 1219 1220
	 */
	my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
	if (my_extra == NULL)
	{
		fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1221
													  sizeof(ArrayMetaState));
1222
		my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1223
		my_extra->element_type = ~element_type;
1224 1225 1226 1227 1228 1229 1230 1231
	}

	if (my_extra->element_type != element_type)
	{
		/* Get info about element type, including its receive proc */
		get_type_io_data(element_type, IOFunc_receive,
						 &my_extra->typlen, &my_extra->typbyval,
						 &my_extra->typalign, &my_extra->typdelim,
1232
						 &my_extra->typioparam, &my_extra->typiofunc);
1233
		if (!OidIsValid(my_extra->typiofunc))
1234 1235
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_FUNCTION),
1236 1237
					 errmsg("no binary input function available for type %s",
							format_type_be(element_type))));
1238 1239 1240 1241
		fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
					  fcinfo->flinfo->fn_mcxt);
		my_extra->element_type = element_type;
	}
1242 1243 1244 1245

	if (nitems == 0)
	{
		/* Return empty array ... but not till we've validated element_type */
1246
		PG_RETURN_ARRAYTYPE_P(construct_empty_array(element_type));
1247 1248
	}

1249 1250 1251
	typlen = my_extra->typlen;
	typbyval = my_extra->typbyval;
	typalign = my_extra->typalign;
1252
	typioparam = my_extra->typioparam;
1253

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
	dataPtr = (Datum *) palloc(nitems * sizeof(Datum));
	nullsPtr = (bool *) palloc(nitems * sizeof(bool));
	ReadArrayBinary(buf, nitems,
					&my_extra->proc, typioparam, typmod,
					typlen, typbyval, typalign,
					dataPtr, nullsPtr,
					&hasnulls, &nbytes);
	if (hasnulls)
	{
		dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
		nbytes += dataoffset;
	}
	else
	{
		dataoffset = 0;			/* marker for no null bitmap */
		nbytes += ARR_OVERHEAD_NONULLS(ndim);
	}
	retval = (ArrayType *) palloc(nbytes);
1272
	SET_VARSIZE(retval, nbytes);
1273
	retval->ndim = ndim;
1274
	retval->dataoffset = dataoffset;
1275
	retval->elemtype = element_type;
1276 1277
	memcpy(ARR_DIMS(retval), dim, ndim * sizeof(int));
	memcpy(ARR_LBOUND(retval), lBound, ndim * sizeof(int));
1278

1279 1280 1281 1282 1283
	CopyArrayEls(retval,
				 dataPtr, nullsPtr, nitems,
				 typlen, typbyval, typalign,
				 true);

1284
	pfree(dataPtr);
1285
	pfree(nullsPtr);
1286 1287

	PG_RETURN_ARRAYTYPE_P(retval);
1288 1289
}

1290
/*
1291 1292
 * ReadArrayBinary:
 *	 collect the data elements of an array being read in binary style.
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
 *
 * Inputs:
 *	buf: the data buffer to read from.
 *	nitems: total number of array elements (already read).
 *	receiveproc: type-specific receive procedure for element datatype.
 *	typioparam, typmod: auxiliary values to pass to receiveproc.
 *	typlen, typbyval, typalign: storage parameters of element datatype.
 *
 * Outputs:
 *	values[]: filled with converted data values.
 *	nulls[]: filled with is-null markers.
 *	*hasnulls: set TRUE iff there are any null elements.
 *	*nbytes: set to total size of data area needed (including alignment
 *		padding but not including array header overhead).
 *
 * Note that values[] and nulls[] are allocated by the caller, and must have
 * nitems elements.
1310
 */
1311
static void
1312 1313 1314
ReadArrayBinary(StringInfo buf,
				int nitems,
				FmgrInfo *receiveproc,
1315
				Oid typioparam,
1316
				int32 typmod,
1317 1318 1319
				int typlen,
				bool typbyval,
				char typalign,
1320 1321 1322 1323
				Datum *values,
				bool *nulls,
				bool *hasnulls,
				int32 *nbytes)
1324 1325
{
	int			i;
1326 1327
	bool		hasnull;
	int32		totbytes;
1328 1329 1330

	for (i = 0; i < nitems; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1331
		int			itemlen;
1332
		StringInfoData elem_buf;
Bruce Momjian's avatar
Bruce Momjian committed
1333
		char		csave;
1334 1335 1336

		/* Get and check the item length */
		itemlen = pq_getmsgint(buf, 4);
1337
		if (itemlen < -1 || itemlen > (buf->len - buf->cursor))
1338 1339 1340
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
					 errmsg("insufficient data left in message")));
1341

1342 1343 1344
		if (itemlen == -1)
		{
			/* -1 length means NULL */
1345 1346
			values[i] = ReceiveFunctionCall(receiveproc, NULL,
											typioparam, typmod);
1347 1348 1349 1350
			nulls[i] = true;
			continue;
		}

1351
		/*
1352 1353 1354 1355
		 * Rather than copying data around, we just set up a phony StringInfo
		 * pointing to the correct portion of the input buffer. We assume we
		 * can scribble on the input buffer so as to maintain the convention
		 * that StringInfos have a trailing null.
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
		 */
		elem_buf.data = &buf->data[buf->cursor];
		elem_buf.maxlen = itemlen + 1;
		elem_buf.len = itemlen;
		elem_buf.cursor = 0;

		buf->cursor += itemlen;

		csave = buf->data[buf->cursor];
		buf->data[buf->cursor] = '\0';

		/* Now call the element's receiveproc */
1368 1369
		values[i] = ReceiveFunctionCall(receiveproc, &elem_buf,
										typioparam, typmod);
1370
		nulls[i] = false;
1371 1372 1373

		/* Trouble if it didn't eat the whole buffer */
		if (elem_buf.cursor != itemlen)
1374 1375 1376
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
					 errmsg("improper binary format in array element %d",
Bruce Momjian's avatar
Bruce Momjian committed
1377
							i + 1)));
1378 1379 1380 1381 1382

		buf->data[buf->cursor] = csave;
	}

	/*
1383
	 * Check for nulls, compute total data space needed
1384
	 */
1385 1386 1387
	hasnull = false;
	totbytes = 0;
	for (i = 0; i < nitems; i++)
1388
	{
1389 1390 1391
		if (nulls[i])
			hasnull = true;
		else
1392 1393 1394 1395
		{
			/* let's just make sure data is not toasted */
			if (typlen == -1)
				values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
1396 1397
			totbytes = att_addlength_datum(totbytes, typlen, values[i]);
			totbytes = att_align_nominal(totbytes, typalign);
1398 1399 1400 1401 1402 1403
			/* check for overflow of total request */
			if (!AllocSizeIsValid(totbytes))
				ereport(ERROR,
						(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
						 errmsg("array size exceeds the maximum allowed (%d)",
								(int) MaxAllocSize)));
1404 1405
		}
	}
1406 1407
	*hasnulls = hasnull;
	*nbytes = totbytes;
1408 1409 1410
}


1411
/*
1412
 * array_send :
1413
 *		  takes the internal representation of an array and returns a bytea
1414 1415 1416 1417 1418
 *		  containing the array in its external binary format.
 */
Datum
array_send(PG_FUNCTION_ARGS)
{
1419
	ArrayType  *v = PG_GETARG_ARRAYTYPE_P(0);
1420
	Oid			element_type = ARR_ELEMTYPE(v);
1421 1422 1423 1424
	int			typlen;
	bool		typbyval;
	char		typalign;
	char	   *p;
1425 1426
	bits8	   *bitmap;
	int			bitmask;
1427 1428 1429 1430 1431
	int			nitems,
				i;
	int			ndim,
			   *dim;
	StringInfoData buf;
1432
	ArrayMetaState *my_extra;
1433

1434 1435
	/*
	 * We arrange to look up info about element type, including its send
1436 1437
	 * conversion proc, only once per series of calls, assuming the element
	 * type doesn't change underneath us.
1438 1439 1440 1441 1442
	 */
	my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
	if (my_extra == NULL)
	{
		fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1443
													  sizeof(ArrayMetaState));
1444
		my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1445
		my_extra->element_type = ~element_type;
1446 1447 1448 1449 1450 1451 1452 1453
	}

	if (my_extra->element_type != element_type)
	{
		/* Get info about element type, including its send proc */
		get_type_io_data(element_type, IOFunc_send,
						 &my_extra->typlen, &my_extra->typbyval,
						 &my_extra->typalign, &my_extra->typdelim,
1454
						 &my_extra->typioparam, &my_extra->typiofunc);
1455
		if (!OidIsValid(my_extra->typiofunc))
1456 1457
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_FUNCTION),
1458 1459
					 errmsg("no binary output function available for type %s",
							format_type_be(element_type))));
1460 1461 1462 1463 1464 1465 1466
		fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
					  fcinfo->flinfo->fn_mcxt);
		my_extra->element_type = element_type;
	}
	typlen = my_extra->typlen;
	typbyval = my_extra->typbyval;
	typalign = my_extra->typalign;
1467 1468 1469 1470 1471 1472 1473 1474 1475

	ndim = ARR_NDIM(v);
	dim = ARR_DIMS(v);
	nitems = ArrayGetNItems(ndim, dim);

	pq_begintypsend(&buf);

	/* Send the array header information */
	pq_sendint(&buf, ndim, 4);
1476
	pq_sendint(&buf, ARR_HASNULL(v) ? 1 : 0, 4);
1477 1478 1479 1480 1481 1482 1483 1484 1485
	pq_sendint(&buf, element_type, sizeof(Oid));
	for (i = 0; i < ndim; i++)
	{
		pq_sendint(&buf, ARR_DIMS(v)[i], 4);
		pq_sendint(&buf, ARR_LBOUND(v)[i], 4);
	}

	/* Send the array elements using the element's own sendproc */
	p = ARR_DATA_PTR(v);
1486 1487 1488
	bitmap = ARR_NULLBITMAP(v);
	bitmask = 1;

1489 1490
	for (i = 0; i < nitems; i++)
	{
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
		/* Get source element, checking for NULL */
		if (bitmap && (*bitmap & bitmask) == 0)
		{
			/* -1 length means a NULL */
			pq_sendint(&buf, -1, 4);
		}
		else
		{
			Datum		itemvalue;
			bytea	   *outputbytes;
1501

1502
			itemvalue = fetch_att(p, typbyval, typlen);
1503
			outputbytes = SendFunctionCall(&my_extra->proc, itemvalue);
1504 1505 1506 1507
			pq_sendint(&buf, VARSIZE(outputbytes) - VARHDRSZ, 4);
			pq_sendbytes(&buf, VARDATA(outputbytes),
						 VARSIZE(outputbytes) - VARHDRSZ);
			pfree(outputbytes);
1508

1509 1510
			p = att_addlength_pointer(p, typlen, p);
			p = (char *) att_align_nominal(p, typalign);
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
		}

		/* advance bitmap pointer if any */
		if (bitmap)
		{
			bitmask <<= 1;
			if (bitmask == 0x100)
			{
				bitmap++;
				bitmask = 1;
			}
		}
1523 1524 1525
	}

	PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
1526 1527
}

1528
/*
1529
 * array_dims :
1530
 *		  returns the dimensions of the array pointed to by "v", as a "text"
1531
 */
1532 1533
Datum
array_dims(PG_FUNCTION_ARGS)
1534
{
1535
	ArrayType  *v = PG_GETARG_ARRAYTYPE_P(0);
1536 1537
	text	   *result;
	char	   *p;
1538 1539 1540 1541
	int			nbytes,
				i;
	int		   *dimv,
			   *lb;
1542

1543 1544 1545 1546
	/* Sanity check: does it look like an array at all? */
	if (ARR_NDIM(v) <= 0 || ARR_NDIM(v) > MAXDIM)
		PG_RETURN_NULL();

1547
	nbytes = ARR_NDIM(v) * 33 + 1;
1548

1549 1550
	/*
	 * 33 since we assume 15 digits per number + ':' +'[]'
1551 1552
	 *
	 * +1 allows for temp trailing null
1553
	 */
1554 1555 1556 1557

	result = (text *) palloc(nbytes + VARHDRSZ);
	p = VARDATA(result);

1558 1559
	dimv = ARR_DIMS(v);
	lb = ARR_LBOUND(v);
1560

1561 1562 1563 1564 1565
	for (i = 0; i < ARR_NDIM(v); i++)
	{
		sprintf(p, "[%d:%d]", lb[i], dimv[i] + lb[i] - 1);
		p += strlen(p);
	}
1566
	SET_VARSIZE(result, strlen(VARDATA(result)) + VARHDRSZ);
1567 1568

	PG_RETURN_TEXT_P(result);
1569
}
1570

1571
/*
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
 * array_lower :
 *		returns the lower dimension, of the DIM requested, for
 *		the array pointed to by "v", as an int4
 */
Datum
array_lower(PG_FUNCTION_ARGS)
{
	ArrayType  *v = PG_GETARG_ARRAYTYPE_P(0);
	int			reqdim = PG_GETARG_INT32(1);
	int		   *lb;
	int			result;

	/* Sanity check: does it look like an array at all? */
	if (ARR_NDIM(v) <= 0 || ARR_NDIM(v) > MAXDIM)
		PG_RETURN_NULL();

	/* Sanity check: was the requested dim valid */
	if (reqdim <= 0 || reqdim > ARR_NDIM(v))
		PG_RETURN_NULL();

	lb = ARR_LBOUND(v);
	result = lb[reqdim - 1];

	PG_RETURN_INT32(result);
}

1598
/*
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
 * array_upper :
 *		returns the upper dimension, of the DIM requested, for
 *		the array pointed to by "v", as an int4
 */
Datum
array_upper(PG_FUNCTION_ARGS)
{
	ArrayType  *v = PG_GETARG_ARRAYTYPE_P(0);
	int			reqdim = PG_GETARG_INT32(1);
	int		   *dimv,
			   *lb;
	int			result;

	/* Sanity check: does it look like an array at all? */
	if (ARR_NDIM(v) <= 0 || ARR_NDIM(v) > MAXDIM)
		PG_RETURN_NULL();

	/* Sanity check: was the requested dim valid */
	if (reqdim <= 0 || reqdim > ARR_NDIM(v))
		PG_RETURN_NULL();

	lb = ARR_LBOUND(v);
	dimv = ARR_DIMS(v);

	result = dimv[reqdim - 1] + lb[reqdim - 1] - 1;

	PG_RETURN_INT32(result);
}

1628
/*
1629
 * array_ref :
1630
 *	  This routine takes an array pointer and a subscript array and returns
1631 1632
 *	  the referenced item as a Datum.  Note that for a pass-by-reference
 *	  datatype, the returned Datum is a pointer into the array object.
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
 *
 * This handles both ordinary varlena arrays and fixed-length arrays.
 *
 * Inputs:
 *	array: the array object (mustn't be NULL)
 *	nSubscripts: number of subscripts supplied
 *	indx[]: the subscript values
 *	arraytyplen: pg_type.typlen for the array type
 *	elmlen: pg_type.typlen for the array's element type
 *	elmbyval: pg_type.typbyval for the array's element type
 *	elmalign: pg_type.typalign for the array's element type
 *
 * Outputs:
 *	The return value is the element Datum.
 *	*isNull is set to indicate whether the element is NULL.
1648 1649
 */
Datum
Bruce Momjian's avatar
Bruce Momjian committed
1650
array_ref(ArrayType *array,
1651
		  int nSubscripts,
1652
		  int *indx,
1653
		  int arraytyplen,
1654 1655 1656
		  int elmlen,
		  bool elmbyval,
		  char elmalign,
1657
		  bool *isNull)
1658
{
1659 1660
	int			i,
				ndim,
1661 1662
			   *dim,
			   *lb,
1663 1664 1665 1666 1667
				offset,
				fixedDim[1],
				fixedLb[1];
	char	   *arraydataptr,
			   *retptr;
1668
	bits8	   *arraynullsptr;
1669

1670
	if (arraytyplen > 0)
1671 1672
	{
		/*
1673
		 * fixed-length arrays -- these are assumed to be 1-d, 0-based
1674
		 */
1675
		ndim = 1;
1676
		fixedDim[0] = arraytyplen / elmlen;
1677 1678 1679 1680
		fixedLb[0] = 0;
		dim = fixedDim;
		lb = fixedLb;
		arraydataptr = (char *) array;
1681
		arraynullsptr = NULL;
1682
	}
1683 1684
	else
	{
1685
		/* detoast input array if necessary */
1686
		array = DatumGetArrayTypeP(PointerGetDatum(array));
1687

1688 1689 1690 1691
		ndim = ARR_NDIM(array);
		dim = ARR_DIMS(array);
		lb = ARR_LBOUND(array);
		arraydataptr = ARR_DATA_PTR(array);
1692
		arraynullsptr = ARR_NULLBITMAP(array);
1693
	}
1694

1695 1696 1697 1698
	/*
	 * Return NULL for invalid subscript
	 */
	if (ndim != nSubscripts || ndim <= 0 || ndim > MAXDIM)
1699 1700 1701 1702
	{
		*isNull = true;
		return (Datum) 0;
	}
1703
	for (i = 0; i < ndim; i++)
1704
	{
1705
		if (indx[i] < lb[i] || indx[i] >= (dim[i] + lb[i]))
1706 1707 1708 1709 1710
		{
			*isNull = true;
			return (Datum) 0;
		}
	}
1711

1712
	/*
1713
	 * Calculate the element number
1714
	 */
1715
	offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
1716

1717 1718 1719 1720 1721 1722 1723 1724
	/*
	 * Check for NULL array element
	 */
	if (array_get_isnull(arraynullsptr, offset))
	{
		*isNull = true;
		return (Datum) 0;
	}
1725

1726 1727 1728
	/*
	 * OK, get the element
	 */
1729
	*isNull = false;
1730 1731
	retptr = array_seek(arraydataptr, 0, arraynullsptr, offset,
						elmlen, elmbyval, elmalign);
1732
	return ArrayCast(retptr, elmbyval, elmlen);
1733 1734
}

1735
/*
1736 1737
 * array_get_slice :
 *		   This routine takes an array and a range of indices (upperIndex and
1738 1739
 *		   lowerIndx), creates a new array structure for the referred elements
 *		   and returns a pointer to it.
1740
 *
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
 * This handles both ordinary varlena arrays and fixed-length arrays.
 *
 * Inputs:
 *	array: the array object (mustn't be NULL)
 *	nSubscripts: number of subscripts supplied (must be same for upper/lower)
 *	upperIndx[]: the upper subscript values
 *	lowerIndx[]: the lower subscript values
 *	arraytyplen: pg_type.typlen for the array type
 *	elmlen: pg_type.typlen for the array's element type
 *	elmbyval: pg_type.typbyval for the array's element type
 *	elmalign: pg_type.typalign for the array's element type
 *
 * Outputs:
 *	The return value is the new array Datum (it's never NULL)
 *
 * NOTE: we assume it is OK to scribble on the provided subscript arrays
1757
 * lowerIndx[] and upperIndx[].  These are generally just temporaries.
1758
 */
1759
ArrayType *
1760 1761 1762 1763
array_get_slice(ArrayType *array,
				int nSubscripts,
				int *upperIndx,
				int *lowerIndx,
1764
				int arraytyplen,
1765 1766
				int elmlen,
				bool elmbyval,
1767
				char elmalign)
1768
{
1769
	ArrayType  *newarray;
1770 1771 1772
	int			i,
				ndim,
			   *dim,
1773 1774
			   *lb,
			   *newlb;
1775 1776
	int			fixedDim[1],
				fixedLb[1];
1777
	Oid			elemtype;
1778
	char	   *arraydataptr;
1779 1780
	bits8	   *arraynullsptr;
	int32		dataoffset;
1781 1782
	int			bytes,
				span[MAXDIM];
1783

1784
	if (arraytyplen > 0)
1785 1786
	{
		/*
1787 1788 1789 1790
		 * fixed-length arrays -- currently, cannot slice these because parser
		 * labels output as being of the fixed-length array type! Code below
		 * shows how we could support it if the parser were changed to label
		 * output as a suitable varlena array type.
1791
		 */
1792 1793
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1794
				 errmsg("slices of fixed-length arrays not implemented")));
1795

1796
		/*
1797 1798 1799
		 * fixed-length arrays -- these are assumed to be 1-d, 0-based
		 *
		 * XXX where would we get the correct ELEMTYPE from?
1800 1801
		 */
		ndim = 1;
1802
		fixedDim[0] = arraytyplen / elmlen;
1803 1804 1805
		fixedLb[0] = 0;
		dim = fixedDim;
		lb = fixedLb;
1806
		elemtype = InvalidOid;	/* XXX */
1807
		arraydataptr = (char *) array;
1808
		arraynullsptr = NULL;
1809 1810 1811
	}
	else
	{
1812
		/* detoast input array if necessary */
1813
		array = DatumGetArrayTypeP(PointerGetDatum(array));
1814

1815 1816 1817
		ndim = ARR_NDIM(array);
		dim = ARR_DIMS(array);
		lb = ARR_LBOUND(array);
1818
		elemtype = ARR_ELEMTYPE(array);
1819
		arraydataptr = ARR_DATA_PTR(array);
1820
		arraynullsptr = ARR_NULLBITMAP(array);
1821
	}
1822

1823
	/*
1824 1825
	 * Check provided subscripts.  A slice exceeding the current array limits
	 * is silently truncated to the array limits.  If we end up with an empty
1826
	 * slice, return an empty array.
1827
	 */
1828
	if (ndim < nSubscripts || ndim <= 0 || ndim > MAXDIM)
1829
		return construct_empty_array(elemtype);
1830

1831
	for (i = 0; i < nSubscripts; i++)
1832 1833 1834 1835 1836
	{
		if (lowerIndx[i] < lb[i])
			lowerIndx[i] = lb[i];
		if (upperIndx[i] >= (dim[i] + lb[i]))
			upperIndx[i] = dim[i] + lb[i] - 1;
1837
		if (lowerIndx[i] > upperIndx[i])
1838
			return construct_empty_array(elemtype);
1839
	}
1840 1841 1842 1843 1844 1845
	/* fill any missing subscript positions with full array range */
	for (; i < ndim; i++)
	{
		lowerIndx[i] = lb[i];
		upperIndx[i] = dim[i] + lb[i] - 1;
		if (lowerIndx[i] > upperIndx[i])
1846
			return construct_empty_array(elemtype);
1847
	}
1848

1849
	mda_get_range(ndim, span, lowerIndx, upperIndx);
1850

1851 1852
	bytes = array_slice_size(arraydataptr, arraynullsptr,
							 ndim, dim, lb,
1853 1854
							 lowerIndx, upperIndx,
							 elmlen, elmbyval, elmalign);
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869

	/*
	 * Currently, we put a null bitmap in the result if the source has one;
	 * could be smarter ...
	 */
	if (arraynullsptr)
	{
		dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, ArrayGetNItems(ndim, span));
		bytes += dataoffset;
	}
	else
	{
		dataoffset = 0;			/* marker for no null bitmap */
		bytes += ARR_OVERHEAD_NONULLS(ndim);
	}
1870 1871

	newarray = (ArrayType *) palloc(bytes);
1872
	SET_VARSIZE(newarray, bytes);
1873
	newarray->ndim = ndim;
1874 1875
	newarray->dataoffset = dataoffset;
	newarray->elemtype = elemtype;
1876
	memcpy(ARR_DIMS(newarray), span, ndim * sizeof(int));
Bruce Momjian's avatar
Bruce Momjian committed
1877

1878
	/*
1879 1880
	 * Lower bounds of the new array are set to 1.	Formerly (before 7.3) we
	 * copied the given lowerIndx values ... but that seems confusing.
1881 1882 1883 1884 1885
	 */
	newlb = ARR_LBOUND(newarray);
	for (i = 0; i < ndim; i++)
		newlb[i] = 1;

1886 1887 1888 1889
	array_extract_slice(newarray,
						ndim, dim, lb,
						arraydataptr, arraynullsptr,
						lowerIndx, upperIndx,
1890
						elmlen, elmbyval, elmalign);
1891 1892

	return newarray;
1893 1894
}

1895
/*
1896
 * array_set :
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
 *		  This routine sets the value of an array element (specified by
 *		  a subscript array) to a new value specified by "dataValue".
 *
 * This handles both ordinary varlena arrays and fixed-length arrays.
 *
 * Inputs:
 *	array: the initial array object (mustn't be NULL)
 *	nSubscripts: number of subscripts supplied
 *	indx[]: the subscript values
 *	dataValue: the datum to be inserted at the given position
 *	isNull: whether dataValue is NULL
 *	arraytyplen: pg_type.typlen for the array type
 *	elmlen: pg_type.typlen for the array's element type
 *	elmbyval: pg_type.typbyval for the array's element type
 *	elmalign: pg_type.typalign for the array's element type
 *
 * Result:
1914
 *		  A new array is returned, just like the old except for the one
1915
 *		  modified entry.  The original array object is not changed.
1916
 *
1917
 * For one-dimensional arrays only, we allow the array to be extended
1918 1919 1920
 * by assigning to a position outside the existing subscript range; any
 * positions between the existing elements and the new one are set to NULLs.
 * (XXX TODO: allow a corresponding behavior for multidimensional arrays)
1921 1922
 *
 * NOTE: For assignments, we throw an error for invalid subscripts etc,
1923
 * rather than returning a NULL as the fetch operations do.
1924
 */
1925
ArrayType *
Bruce Momjian's avatar
Bruce Momjian committed
1926
array_set(ArrayType *array,
1927
		  int nSubscripts,
1928
		  int *indx,
1929
		  Datum dataValue,
1930 1931
		  bool isNull,
		  int arraytyplen,
1932 1933
		  int elmlen,
		  bool elmbyval,
1934
		  char elmalign)
1935
{
1936
	ArrayType  *newarray;
1937 1938 1939 1940
	int			i,
				ndim,
				dim[MAXDIM],
				lb[MAXDIM],
1941 1942
				offset;
	char	   *elt_ptr;
1943 1944 1945
	bool		newhasnulls;
	bits8	   *oldnullbitmap;
	int			oldnitems,
1946
				newnitems,
1947
				olddatasize,
1948
				newsize,
1949 1950 1951
				olditemlen,
				newitemlen,
				overheadlen,
1952
				oldoverheadlen,
1953 1954
				addedbefore,
				addedafter,
1955 1956
				lenbefore,
				lenafter;
1957

1958
	if (arraytyplen > 0)
1959 1960
	{
		/*
1961 1962
		 * fixed-length arrays -- these are assumed to be 1-d, 0-based. We
		 * cannot extend them, either.
1963
		 */
1964
		if (nSubscripts != 1)
1965 1966
			ereport(ERROR,
					(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1967
					 errmsg("wrong number of array subscripts")));
1968

1969
		if (indx[0] < 0 || indx[0] * elmlen >= arraytyplen)
1970 1971
			ereport(ERROR,
					(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1972
					 errmsg("array subscript out of range")));
1973

1974 1975 1976
		if (isNull)
			ereport(ERROR,
					(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1977
					 errmsg("cannot assign null value to an element of a fixed-length array")));
1978 1979 1980

		newarray = (ArrayType *) palloc(arraytyplen);
		memcpy(newarray, array, arraytyplen);
1981
		elt_ptr = (char *) newarray + indx[0] * elmlen;
1982
		ArrayCastAndSet(dataValue, elmlen, elmbyval, elmalign, elt_ptr);
1983
		return newarray;
1984
	}
1985

1986 1987 1988
	if (nSubscripts <= 0 || nSubscripts > MAXDIM)
		ereport(ERROR,
				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1989
				 errmsg("wrong number of array subscripts")));
1990

1991
	/* make sure item to be inserted is not toasted */
1992
	if (elmlen == -1 && !isNull)
1993 1994
		dataValue = PointerGetDatum(PG_DETOAST_DATUM(dataValue));

1995
	/* detoast input array if necessary */
1996 1997 1998
	array = DatumGetArrayTypeP(PointerGetDatum(array));

	ndim = ARR_NDIM(array);
1999 2000

	/*
2001 2002 2003
	 * if number of dims is zero, i.e. an empty array, create an array with
	 * nSubscripts dimensions, and set the lower bounds to the supplied
	 * subscripts
2004 2005 2006
	 */
	if (ndim == 0)
	{
Bruce Momjian's avatar
Bruce Momjian committed
2007
		Oid			elmtype = ARR_ELEMTYPE(array);
2008 2009 2010 2011 2012 2013 2014

		for (i = 0; i < nSubscripts; i++)
		{
			dim[i] = 1;
			lb[i] = indx[i];
		}

2015 2016
		return construct_md_array(&dataValue, &isNull, nSubscripts,
								  dim, lb, elmtype,
Bruce Momjian's avatar
Bruce Momjian committed
2017
								  elmlen, elmbyval, elmalign);
2018 2019
	}

2020
	if (ndim != nSubscripts)
2021 2022
		ereport(ERROR,
				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2023
				 errmsg("wrong number of array subscripts")));
2024

2025 2026 2027
	/* copy dim/lb since we may modify them */
	memcpy(dim, ARR_DIMS(array), ndim * sizeof(int));
	memcpy(lb, ARR_LBOUND(array), ndim * sizeof(int));
2028

2029 2030 2031
	newhasnulls = (ARR_HASNULL(array) || isNull);
	addedbefore = addedafter = 0;

2032 2033 2034
	/*
	 * Check subscripts
	 */
2035
	if (ndim == 1)
2036
	{
2037
		if (indx[0] < lb[0])
2038
		{
2039 2040 2041 2042
			addedbefore = lb[0] - indx[0];
			dim[0] += addedbefore;
			lb[0] = indx[0];
			if (addedbefore > 1)
Bruce Momjian's avatar
Bruce Momjian committed
2043
				newhasnulls = true;		/* will insert nulls */
2044
		}
2045
		if (indx[0] >= (dim[0] + lb[0]))
2046
		{
2047 2048 2049
			addedafter = indx[0] - (dim[0] + lb[0]) + 1;
			dim[0] += addedafter;
			if (addedafter > 1)
Bruce Momjian's avatar
Bruce Momjian committed
2050
				newhasnulls = true;		/* will insert nulls */
2051 2052 2053 2054 2055
		}
	}
	else
	{
		/*
Bruce Momjian's avatar
Bruce Momjian committed
2056 2057
		 * XXX currently we do not support extending multi-dimensional arrays
		 * during assignment
2058 2059 2060 2061 2062
		 */
		for (i = 0; i < ndim; i++)
		{
			if (indx[i] < lb[i] ||
				indx[i] >= (dim[i] + lb[i]))
2063 2064
				ereport(ERROR,
						(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2065
						 errmsg("array subscript out of range")));
2066 2067
		}
	}
2068

2069 2070 2071
	/*
	 * Compute sizes of items and areas to copy
	 */
2072 2073 2074
	newnitems = ArrayGetNItems(ndim, dim);
	if (newhasnulls)
		overheadlen = ARR_OVERHEAD_WITHNULLS(ndim, newnitems);
2075 2076 2077 2078 2079 2080
	else
		overheadlen = ARR_OVERHEAD_NONULLS(ndim);
	oldnitems = ArrayGetNItems(ndim, ARR_DIMS(array));
	oldnullbitmap = ARR_NULLBITMAP(array);
	oldoverheadlen = ARR_DATA_OFFSET(array);
	olddatasize = ARR_SIZE(array) - oldoverheadlen;
2081
	if (addedbefore)
2082
	{
2083
		offset = 0;
2084 2085 2086 2087
		lenbefore = 0;
		olditemlen = 0;
		lenafter = olddatasize;
	}
2088
	else if (addedafter)
2089
	{
2090
		offset = oldnitems;
2091 2092 2093
		lenbefore = olddatasize;
		olditemlen = 0;
		lenafter = 0;
2094 2095 2096
	}
	else
	{
2097
		offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
2098
		elt_ptr = array_seek(ARR_DATA_PTR(array), 0, oldnullbitmap, offset,
2099
							 elmlen, elmbyval, elmalign);
2100
		lenbefore = (int) (elt_ptr - ARR_DATA_PTR(array));
2101 2102 2103 2104
		if (array_get_isnull(oldnullbitmap, offset))
			olditemlen = 0;
		else
		{
2105 2106
			olditemlen = att_addlength_pointer(0, elmlen, elt_ptr);
			olditemlen = att_align_nominal(olditemlen, elmalign);
2107
		}
2108
		lenafter = (int) (olddatasize - lenbefore - olditemlen);
2109
	}
2110

2111 2112 2113 2114
	if (isNull)
		newitemlen = 0;
	else
	{
2115 2116
		newitemlen = att_addlength_datum(0, elmlen, dataValue);
		newitemlen = att_align_nominal(newitemlen, elmalign);
2117
	}
2118 2119

	newsize = overheadlen + lenbefore + newitemlen + lenafter;
2120

2121
	/*
2122
	 * OK, create the new array and fill in header/dimensions
2123
	 */
2124
	newarray = (ArrayType *) palloc(newsize);
2125
	SET_VARSIZE(newarray, newsize);
2126
	newarray->ndim = ndim;
2127
	newarray->dataoffset = newhasnulls ? overheadlen : 0;
2128
	newarray->elemtype = ARR_ELEMTYPE(array);
2129 2130
	memcpy(ARR_DIMS(newarray), dim, ndim * sizeof(int));
	memcpy(ARR_LBOUND(newarray), lb, ndim * sizeof(int));
2131 2132 2133 2134

	/*
	 * Fill in data
	 */
2135
	memcpy((char *) newarray + overheadlen,
2136
		   (char *) array + oldoverheadlen,
2137
		   lenbefore);
2138 2139 2140
	if (!isNull)
		ArrayCastAndSet(dataValue, elmlen, elmbyval, elmalign,
						(char *) newarray + overheadlen + lenbefore);
2141
	memcpy((char *) newarray + overheadlen + lenbefore + newitemlen,
2142
		   (char *) array + oldoverheadlen + lenbefore + olditemlen,
2143 2144
		   lenafter);

2145 2146 2147
	/*
	 * Fill in nulls bitmap if needed
	 *
2148 2149
	 * Note: it's possible we just replaced the last NULL with a non-NULL, and
	 * could get rid of the bitmap.  Seems not worth testing for though.
2150 2151 2152
	 */
	if (newhasnulls)
	{
2153
		bits8	   *newnullbitmap = ARR_NULLBITMAP(newarray);
2154

2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
		/* Zero the bitmap to take care of marking inserted positions null */
		MemSet(newnullbitmap, 0, (newnitems + 7) / 8);
		/* Fix the inserted value */
		if (addedafter)
			array_set_isnull(newnullbitmap, newnitems - 1, isNull);
		else
			array_set_isnull(newnullbitmap, offset, isNull);
		/* Fix the copied range(s) */
		if (addedbefore)
			array_bitmap_copy(newnullbitmap, addedbefore,
2165 2166 2167 2168 2169 2170 2171
							  oldnullbitmap, 0,
							  oldnitems);
		else
		{
			array_bitmap_copy(newnullbitmap, 0,
							  oldnullbitmap, 0,
							  offset);
2172
			if (addedafter == 0)
2173 2174
				array_bitmap_copy(newnullbitmap, offset + 1,
								  oldnullbitmap, offset + 1,
2175 2176 2177
								  oldnitems - offset - 1);
		}
	}
2178 2179

	return newarray;
2180 2181
}

2182
/*
2183
 * array_set_slice :
2184
 *		  This routine sets the value of a range of array locations (specified
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
 *		  by upper and lower subscript values) to new values passed as
 *		  another array.
 *
 * This handles both ordinary varlena arrays and fixed-length arrays.
 *
 * Inputs:
 *	array: the initial array object (mustn't be NULL)
 *	nSubscripts: number of subscripts supplied (must be same for upper/lower)
 *	upperIndx[]: the upper subscript values
 *	lowerIndx[]: the lower subscript values
 *	srcArray: the source for the inserted values
 *	isNull: indicates whether srcArray is NULL
 *	arraytyplen: pg_type.typlen for the array type
 *	elmlen: pg_type.typlen for the array's element type
 *	elmbyval: pg_type.typbyval for the array's element type
 *	elmalign: pg_type.typalign for the array's element type
 *
 * Result:
2203
 *		  A new array is returned, just like the old except for the
2204
 *		  modified range.  The original array object is not changed.
2205
 *
2206 2207 2208 2209 2210
 * For one-dimensional arrays only, we allow the array to be extended
 * by assigning to positions outside the existing subscript range; any
 * positions between the existing elements and the new ones are set to NULLs.
 * (XXX TODO: allow a corresponding behavior for multidimensional arrays)
 *
2211 2212 2213
 * NOTE: we assume it is OK to scribble on the provided index arrays
 * lowerIndx[] and upperIndx[].  These are generally just temporaries.
 *
2214
 * NOTE: For assignments, we throw an error for silly subscripts etc,
2215
 * rather than returning a NULL or empty array as the fetch operations do.
2216
 */
2217
ArrayType *
2218 2219 2220 2221 2222
array_set_slice(ArrayType *array,
				int nSubscripts,
				int *upperIndx,
				int *lowerIndx,
				ArrayType *srcArray,
2223 2224
				bool isNull,
				int arraytyplen,
2225 2226
				int elmlen,
				bool elmbyval,
2227
				char elmalign)
2228
{
2229
	ArrayType  *newarray;
2230 2231
	int			i,
				ndim,
2232 2233 2234
				dim[MAXDIM],
				lb[MAXDIM],
				span[MAXDIM];
2235 2236 2237
	bool		newhasnulls;
	int			nitems,
				nsrcitems,
2238 2239 2240 2241 2242
				olddatasize,
				newsize,
				olditemsize,
				newitemsize,
				overheadlen,
2243
				oldoverheadlen,
2244 2245
				addedbefore,
				addedafter,
2246
				lenbefore,
2247 2248 2249 2250
				lenafter,
				itemsbefore,
				itemsafter,
				nolditems;
2251

2252 2253
	/* Currently, assignment from a NULL source array is a no-op */
	if (isNull)
2254
		return array;
2255

2256
	if (arraytyplen > 0)
2257 2258
	{
		/*
2259
		 * fixed-length arrays -- not got round to doing this...
2260
		 */
2261 2262
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2263
		errmsg("updates on slices of fixed-length arrays not implemented")));
2264 2265
	}

2266 2267
	/* detoast arrays if necessary */
	array = DatumGetArrayTypeP(PointerGetDatum(array));
2268 2269
	srcArray = DatumGetArrayTypeP(PointerGetDatum(srcArray));

2270 2271
	/* note: we assume srcArray contains no toasted elements */

2272
	ndim = ARR_NDIM(array);
2273 2274

	/*
2275 2276 2277
	 * if number of dims is zero, i.e. an empty array, create an array with
	 * nSubscripts dimensions, and set the upper and lower bounds to the
	 * supplied subscripts
2278 2279 2280
	 */
	if (ndim == 0)
	{
Bruce Momjian's avatar
Bruce Momjian committed
2281
		Datum	   *dvalues;
2282
		bool	   *dnulls;
Bruce Momjian's avatar
Bruce Momjian committed
2283 2284
		int			nelems;
		Oid			elmtype = ARR_ELEMTYPE(array);
2285 2286

		deconstruct_array(srcArray, elmtype, elmlen, elmbyval, elmalign,
2287
						  &dvalues, &dnulls, &nelems);
2288 2289 2290 2291 2292 2293 2294

		for (i = 0; i < nSubscripts; i++)
		{
			dim[i] = 1 + upperIndx[i] - lowerIndx[i];
			lb[i] = lowerIndx[i];
		}

2295 2296 2297 2298 2299 2300
		/* complain if too few source items; we ignore extras, however */
		if (nelems < ArrayGetNItems(nSubscripts, dim))
			ereport(ERROR,
					(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
					 errmsg("source array too small")));

2301 2302
		return construct_md_array(dvalues, dnulls, nSubscripts,
								  dim, lb, elmtype,
Bruce Momjian's avatar
Bruce Momjian committed
2303
								  elmlen, elmbyval, elmalign);
2304 2305
	}

2306
	if (ndim < nSubscripts || ndim <= 0 || ndim > MAXDIM)
2307 2308
		ereport(ERROR,
				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2309
				 errmsg("wrong number of array subscripts")));
2310

2311 2312 2313 2314
	/* copy dim/lb since we may modify them */
	memcpy(dim, ARR_DIMS(array), ndim * sizeof(int));
	memcpy(lb, ARR_LBOUND(array), ndim * sizeof(int));

2315 2316 2317
	newhasnulls = (ARR_HASNULL(array) || ARR_HASNULL(srcArray));
	addedbefore = addedafter = 0;

2318
	/*
2319
	 * Check subscripts
2320
	 */
2321
	if (ndim == 1)
2322
	{
2323 2324
		Assert(nSubscripts == 1);
		if (lowerIndx[0] > upperIndx[0])
2325 2326
			ereport(ERROR,
					(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2327 2328
					 errmsg("upper bound cannot be less than lower bound")));
		if (lowerIndx[0] < lb[0])
2329
		{
2330
			if (upperIndx[0] < lb[0] - 1)
Bruce Momjian's avatar
Bruce Momjian committed
2331
				newhasnulls = true;		/* will insert nulls */
2332 2333 2334 2335 2336 2337 2338
			addedbefore = lb[0] - lowerIndx[0];
			dim[0] += addedbefore;
			lb[0] = lowerIndx[0];
		}
		if (upperIndx[0] >= (dim[0] + lb[0]))
		{
			if (lowerIndx[0] > (dim[0] + lb[0]))
Bruce Momjian's avatar
Bruce Momjian committed
2339
				newhasnulls = true;		/* will insert nulls */
2340 2341 2342 2343 2344 2345 2346
			addedafter = upperIndx[0] - (dim[0] + lb[0]) + 1;
			dim[0] += addedafter;
		}
	}
	else
	{
		/*
Bruce Momjian's avatar
Bruce Momjian committed
2347 2348
		 * XXX currently we do not support extending multi-dimensional arrays
		 * during assignment
2349 2350 2351 2352 2353 2354
		 */
		for (i = 0; i < nSubscripts; i++)
		{
			if (lowerIndx[i] > upperIndx[i])
				ereport(ERROR,
						(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
2355
					 errmsg("upper bound cannot be less than lower bound")));
2356 2357
			if (lowerIndx[i] < lb[i] ||
				upperIndx[i] >= (dim[i] + lb[i]))
2358 2359
				ereport(ERROR,
						(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2360
						 errmsg("array subscript out of range")));
2361
		}
2362 2363
		/* fill any missing subscript positions with full array range */
		for (; i < ndim; i++)
2364
		{
2365 2366 2367
			lowerIndx[i] = lb[i];
			upperIndx[i] = dim[i] + lb[i] - 1;
			if (lowerIndx[i] > upperIndx[i])
2368 2369
				ereport(ERROR,
						(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
2370
					 errmsg("upper bound cannot be less than lower bound")));
2371 2372
		}
	}
2373

2374 2375 2376
	/* Do this mainly to check for overflow */
	nitems = ArrayGetNItems(ndim, dim);

2377
	/*
2378 2379
	 * Make sure source array has enough entries.  Note we ignore the shape of
	 * the source array and just read entries serially.
2380
	 */
2381
	mda_get_range(ndim, span, lowerIndx, upperIndx);
2382 2383
	nsrcitems = ArrayGetNItems(ndim, span);
	if (nsrcitems > ArrayGetNItems(ARR_NDIM(srcArray), ARR_DIMS(srcArray)))
2384 2385 2386
		ereport(ERROR,
				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
				 errmsg("source array too small")));
2387

2388 2389 2390 2391
	/*
	 * Compute space occupied by new entries, space occupied by replaced
	 * entries, and required space for new array.
	 */
2392
	if (newhasnulls)
2393 2394 2395 2396 2397
		overheadlen = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
	else
		overheadlen = ARR_OVERHEAD_NONULLS(ndim);
	newitemsize = array_nelems_size(ARR_DATA_PTR(srcArray), 0,
									ARR_NULLBITMAP(srcArray), nsrcitems,
2398
									elmlen, elmbyval, elmalign);
2399 2400
	oldoverheadlen = ARR_DATA_OFFSET(array);
	olddatasize = ARR_SIZE(array) - oldoverheadlen;
2401 2402 2403
	if (ndim > 1)
	{
		/*
2404 2405
		 * here we do not need to cope with extension of the array; it would
		 * be a lot more complicated if we had to do so...
2406
		 */
2407 2408 2409
		olditemsize = array_slice_size(ARR_DATA_PTR(array),
									   ARR_NULLBITMAP(array),
									   ndim, dim, lb,
2410 2411
									   lowerIndx, upperIndx,
									   elmlen, elmbyval, elmalign);
2412
		lenbefore = lenafter = 0;		/* keep compiler quiet */
2413
		itemsbefore = itemsafter = nolditems = 0;
2414 2415 2416 2417
	}
	else
	{
		/*
2418
		 * here we must allow for possibility of slice larger than orig array
2419
		 */
2420 2421
		int			oldlb = ARR_LBOUND(array)[0];
		int			oldub = oldlb + ARR_DIMS(array)[0] - 1;
2422 2423
		int			slicelb = Max(oldlb, lowerIndx[0]);
		int			sliceub = Min(oldub, upperIndx[0]);
2424
		char	   *oldarraydata = ARR_DATA_PTR(array);
2425
		bits8	   *oldarraybitmap = ARR_NULLBITMAP(array);
2426

2427
		itemsbefore = Min(slicelb, oldub + 1) - oldlb;
2428 2429
		lenbefore = array_nelems_size(oldarraydata, 0, oldarraybitmap,
									  itemsbefore,
2430
									  elmlen, elmbyval, elmalign);
2431
		if (slicelb > sliceub)
2432 2433
		{
			nolditems = 0;
2434
			olditemsize = 0;
2435
		}
2436
		else
2437 2438
		{
			nolditems = sliceub - slicelb + 1;
2439
			olditemsize = array_nelems_size(oldarraydata + lenbefore,
2440 2441
											itemsbefore, oldarraybitmap,
											nolditems,
2442
											elmlen, elmbyval, elmalign);
2443 2444
		}
		itemsafter = oldub - sliceub;
2445 2446 2447 2448 2449 2450
		lenafter = olddatasize - lenbefore - olditemsize;
	}

	newsize = overheadlen + olddatasize - olditemsize + newitemsize;

	newarray = (ArrayType *) palloc(newsize);
2451
	SET_VARSIZE(newarray, newsize);
2452
	newarray->ndim = ndim;
2453
	newarray->dataoffset = newhasnulls ? overheadlen : 0;
2454
	newarray->elemtype = ARR_ELEMTYPE(array);
2455 2456 2457 2458 2459 2460
	memcpy(ARR_DIMS(newarray), dim, ndim * sizeof(int));
	memcpy(ARR_LBOUND(newarray), lb, ndim * sizeof(int));

	if (ndim > 1)
	{
		/*
2461 2462
		 * here we do not need to cope with extension of the array; it would
		 * be a lot more complicated if we had to do so...
2463
		 */
2464 2465 2466
		array_insert_slice(newarray, array, srcArray,
						   ndim, dim, lb,
						   lowerIndx, upperIndx,
2467
						   elmlen, elmbyval, elmalign);
2468 2469 2470
	}
	else
	{
2471
		/* fill in data */
2472
		memcpy((char *) newarray + overheadlen,
2473
			   (char *) array + oldoverheadlen,
2474 2475 2476 2477 2478
			   lenbefore);
		memcpy((char *) newarray + overheadlen + lenbefore,
			   ARR_DATA_PTR(srcArray),
			   newitemsize);
		memcpy((char *) newarray + overheadlen + lenbefore + newitemsize,
2479
			   (char *) array + oldoverheadlen + lenbefore + olditemsize,
2480
			   lenafter);
2481 2482 2483
		/* fill in nulls bitmap if needed */
		if (newhasnulls)
		{
2484 2485
			bits8	   *newnullbitmap = ARR_NULLBITMAP(newarray);
			bits8	   *oldnullbitmap = ARR_NULLBITMAP(array);
2486

2487 2488 2489
			/* Zero the bitmap to handle marking inserted positions null */
			MemSet(newnullbitmap, 0, (nitems + 7) / 8);
			array_bitmap_copy(newnullbitmap, addedbefore,
2490 2491
							  oldnullbitmap, 0,
							  itemsbefore);
2492
			array_bitmap_copy(newnullbitmap, lowerIndx[0] - lb[0],
2493 2494
							  ARR_NULLBITMAP(srcArray), 0,
							  nsrcitems);
2495
			array_bitmap_copy(newnullbitmap, addedbefore + itemsbefore + nolditems,
2496
							  oldnullbitmap, itemsbefore + nolditems,
2497 2498
							  itemsafter);
		}
2499
	}
2500

2501
	return newarray;
2502 2503
}

2504 2505 2506
/*
 * array_map()
 *
2507
 * Map an array through an arbitrary function.	Return a new array with
2508 2509 2510 2511 2512 2513 2514
 * same dimensions and each source element transformed by fn().  Each
 * source element is passed as the first argument to fn(); additional
 * arguments to be passed to fn() can be specified by the caller.
 * The output array can have a different element type than the input.
 *
 * Parameters are:
 * * fcinfo: a function-call data structure pre-constructed by the caller
2515 2516 2517 2518 2519
 *	 to be ready to call the desired function, with everything except the
 *	 first argument position filled in.  In particular, flinfo identifies
 *	 the function fn(), and if nargs > 1 then argument positions after the
 *	 first must be preset to the additional values to be passed.  The
 *	 first argument position initially holds the input array value.
2520
 * * inpType: OID of element type of input array.  This must be the same as,
2521 2522 2523
 *	 or binary-compatible with, the first argument type of fn().
 * * retType: OID of element type of output array.	This must be the same as,
 *	 or binary-compatible with, the result type of fn().
2524
 * * amstate: workspace for array_map.	Must be zeroed by caller before
2525 2526 2527 2528 2529
 *	 first call, and not touched after that.
 *
 * It is legitimate to pass a freshly-zeroed ArrayMapState on each call,
 * but better performance can be had if the state can be preserved across
 * a series of calls.
2530
 *
2531 2532
 * NB: caller must assure that input array is not NULL.  NULL elements in
 * the array are OK however.
2533
 */
2534
Datum
2535 2536
array_map(FunctionCallInfo fcinfo, Oid inpType, Oid retType,
		  ArrayMapState *amstate)
2537
{
2538
	ArrayType  *v;
Bruce Momjian's avatar
Bruce Momjian committed
2539
	ArrayType  *result;
2540
	Datum	   *values;
2541
	bool	   *nulls;
2542
	Datum		elt;
Bruce Momjian's avatar
Bruce Momjian committed
2543
	int		   *dim;
2544 2545 2546
	int			ndim;
	int			nitems;
	int			i;
2547 2548 2549
	int32		nbytes = 0;
	int32		dataoffset;
	bool		hasnulls;
2550 2551
	int			inp_typlen;
	bool		inp_typbyval;
2552
	char		inp_typalign;
2553 2554
	int			typlen;
	bool		typbyval;
2555
	char		typalign;
Bruce Momjian's avatar
Bruce Momjian committed
2556
	char	   *s;
2557 2558
	bits8	   *bitmap;
	int			bitmask;
2559 2560
	ArrayMetaState *inp_extra;
	ArrayMetaState *ret_extra;
2561 2562 2563

	/* Get input array */
	if (fcinfo->nargs < 1)
2564
		elog(ERROR, "invalid nargs: %d", fcinfo->nargs);
2565
	if (PG_ARGISNULL(0))
2566
		elog(ERROR, "null input array");
2567
	v = PG_GETARG_ARRAYTYPE_P(0);
2568

2569 2570
	Assert(ARR_ELEMTYPE(v) == inpType);

Bruce Momjian's avatar
Bruce Momjian committed
2571 2572
	ndim = ARR_NDIM(v);
	dim = ARR_DIMS(v);
2573
	nitems = ArrayGetNItems(ndim, dim);
2574 2575

	/* Check for empty array */
Bruce Momjian's avatar
Bruce Momjian committed
2576
	if (nitems <= 0)
2577 2578
	{
		/* Return empty array */
2579
		PG_RETURN_ARRAYTYPE_P(construct_empty_array(retType));
2580
	}
2581

2582
	/*
2583 2584 2585
	 * We arrange to look up info about input and return element types only
	 * once per series of calls, assuming the element type doesn't change
	 * underneath us.
2586
	 */
2587 2588
	inp_extra = &amstate->inp_extra;
	ret_extra = &amstate->ret_extra;
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612

	if (inp_extra->element_type != inpType)
	{
		get_typlenbyvalalign(inpType,
							 &inp_extra->typlen,
							 &inp_extra->typbyval,
							 &inp_extra->typalign);
		inp_extra->element_type = inpType;
	}
	inp_typlen = inp_extra->typlen;
	inp_typbyval = inp_extra->typbyval;
	inp_typalign = inp_extra->typalign;

	if (ret_extra->element_type != retType)
	{
		get_typlenbyvalalign(retType,
							 &ret_extra->typlen,
							 &ret_extra->typbyval,
							 &ret_extra->typalign);
		ret_extra->element_type = retType;
	}
	typlen = ret_extra->typlen;
	typbyval = ret_extra->typbyval;
	typalign = ret_extra->typalign;
2613

2614
	/* Allocate temporary arrays for new values */
2615
	values = (Datum *) palloc(nitems * sizeof(Datum));
2616
	nulls = (bool *) palloc(nitems * sizeof(bool));
2617 2618

	/* Loop over source data */
2619 2620 2621 2622 2623
	s = ARR_DATA_PTR(v);
	bitmap = ARR_NULLBITMAP(v);
	bitmask = 1;
	hasnulls = false;

Bruce Momjian's avatar
Bruce Momjian committed
2624 2625
	for (i = 0; i < nitems; i++)
	{
2626
		bool		callit = true;
2627

2628 2629 2630 2631 2632 2633 2634 2635
		/* Get source element, checking for NULL */
		if (bitmap && (*bitmap & bitmask) == 0)
		{
			fcinfo->argnull[0] = true;
		}
		else
		{
			elt = fetch_att(s, inp_typbyval, inp_typlen);
2636 2637
			s = att_addlength_datum(s, inp_typlen, elt);
			s = (char *) att_align_nominal(s, inp_typalign);
2638 2639 2640
			fcinfo->arg[0] = elt;
			fcinfo->argnull[0] = false;
		}
2641 2642

		/*
2643
		 * Apply the given function to source elt and extra args.
2644
		 */
2645 2646
		if (fcinfo->flinfo->fn_strict)
		{
2647
			int			j;
2648

2649 2650 2651 2652 2653 2654 2655 2656 2657
			for (j = 0; j < fcinfo->nargs; j++)
			{
				if (fcinfo->argnull[j])
				{
					callit = false;
					break;
				}
			}
		}
2658

2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
		if (callit)
		{
			fcinfo->isnull = false;
			values[i] = FunctionCallInvoke(fcinfo);
		}
		else
			fcinfo->isnull = true;

		nulls[i] = fcinfo->isnull;
		if (fcinfo->isnull)
			hasnulls = true;
		else
		{
			/* Ensure data is not toasted */
			if (typlen == -1)
				values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
			/* Update total result size */
2676 2677
			nbytes = att_addlength_datum(nbytes, typlen, values[i]);
			nbytes = att_align_nominal(nbytes, typalign);
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
			/* check for overflow of total request */
			if (!AllocSizeIsValid(nbytes))
				ereport(ERROR,
						(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
						 errmsg("array size exceeds the maximum allowed (%d)",
								(int) MaxAllocSize)));
		}

		/* advance bitmap pointer if any */
		if (bitmap)
		{
			bitmask <<= 1;
			if (bitmask == 0x100)
			{
				bitmap++;
				bitmask = 1;
			}
		}
2696 2697 2698
	}

	/* Allocate and initialize the result array */
2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
	if (hasnulls)
	{
		dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
		nbytes += dataoffset;
	}
	else
	{
		dataoffset = 0;			/* marker for no null bitmap */
		nbytes += ARR_OVERHEAD_NONULLS(ndim);
	}
	result = (ArrayType *) palloc(nbytes);
2710
	SET_VARSIZE(result, nbytes);
2711
	result->ndim = ndim;
2712
	result->dataoffset = dataoffset;
2713
	result->elemtype = retType;
2714
	memcpy(ARR_DIMS(result), ARR_DIMS(v), 2 * ndim * sizeof(int));
2715

2716
	/*
2717
	 * Note: do not risk trying to pfree the results of the called function
2718
	 */
2719 2720 2721 2722 2723
	CopyArrayEls(result,
				 values, nulls, nitems,
				 typlen, typbyval, typalign,
				 false);

2724
	pfree(values);
2725
	pfree(nulls);
2726

2727
	PG_RETURN_ARRAYTYPE_P(result);
2728 2729
}

2730
/*
2731
 * construct_array	--- simple method for constructing an array object
2732 2733
 *
 * elems: array of Datum items to become the array contents
2734
 *		  (NULL element values are not supported).
2735
 * nelems: number of items
2736
 * elmtype, elmlen, elmbyval, elmalign: info for the datatype of the items
2737 2738 2739
 *
 * A palloc'd 1-D array object is constructed and returned.  Note that
 * elem values will be copied into the object even if pass-by-ref type.
2740 2741
 *
 * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
2742 2743 2744
 * from the system catalogs, given the elmtype.  However, the caller is
 * in a better position to cache this info across multiple uses, or even
 * to hard-wire values if the element type is hard-wired.
2745
 */
2746
ArrayType *
2747
construct_array(Datum *elems, int nelems,
2748 2749
				Oid elmtype,
				int elmlen, bool elmbyval, char elmalign)
2750
{
Bruce Momjian's avatar
Bruce Momjian committed
2751 2752
	int			dims[1];
	int			lbs[1];
2753 2754 2755 2756

	dims[0] = nelems;
	lbs[0] = 1;

2757
	return construct_md_array(elems, NULL, 1, dims, lbs,
2758 2759 2760
							  elmtype, elmlen, elmbyval, elmalign);
}

2761
/*
2762
 * construct_md_array	--- simple method for constructing an array object
2763
 *							with arbitrary dimensions and possible NULLs
2764 2765
 *
 * elems: array of Datum items to become the array contents
2766
 * nulls: array of is-null flags (can be NULL if no nulls)
2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
 * ndims: number of dimensions
 * dims: integer array with size of each dimension
 * lbs: integer array with lower bound of each dimension
 * elmtype, elmlen, elmbyval, elmalign: info for the datatype of the items
 *
 * A palloc'd ndims-D array object is constructed and returned.  Note that
 * elem values will be copied into the object even if pass-by-ref type.
 *
 * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
 * from the system catalogs, given the elmtype.  However, the caller is
 * in a better position to cache this info across multiple uses, or even
 * to hard-wire values if the element type is hard-wired.
 */
ArrayType *
construct_md_array(Datum *elems,
2782
				   bool *nulls,
2783 2784 2785 2786
				   int ndims,
				   int *dims,
				   int *lbs,
				   Oid elmtype, int elmlen, bool elmbyval, char elmalign)
2787 2788
{
	ArrayType  *result;
2789 2790 2791
	bool		hasnulls;
	int32		nbytes;
	int32		dataoffset;
2792
	int			i;
2793 2794
	int			nelems;

2795 2796 2797 2798 2799 2800 2801
	if (ndims < 0)				/* we do allow zero-dimension arrays */
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("invalid number of dimensions: %d", ndims)));
	if (ndims > MAXDIM)
		ereport(ERROR,
				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2802 2803
				 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
						ndims, MAXDIM)));
2804 2805 2806

	/* fast track for empty array */
	if (ndims == 0)
2807
		return construct_empty_array(elmtype);
2808 2809

	nelems = ArrayGetNItems(ndims, dims);
2810

2811
	/* compute required space */
2812 2813 2814
	nbytes = 0;
	hasnulls = false;
	for (i = 0; i < nelems; i++)
2815
	{
2816
		if (nulls && nulls[i])
2817
		{
2818 2819
			hasnulls = true;
			continue;
2820
		}
2821 2822 2823
		/* make sure data is not toasted */
		if (elmlen == -1)
			elems[i] = PointerGetDatum(PG_DETOAST_DATUM(elems[i]));
2824 2825
		nbytes = att_addlength_datum(nbytes, elmlen, elems[i]);
		nbytes = att_align_nominal(nbytes, elmalign);
2826 2827 2828 2829 2830 2831
		/* check for overflow of total request */
		if (!AllocSizeIsValid(nbytes))
			ereport(ERROR,
					(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
					 errmsg("array size exceeds the maximum allowed (%d)",
							(int) MaxAllocSize)));
2832 2833
	}

2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
	/* Allocate and initialize result array */
	if (hasnulls)
	{
		dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nelems);
		nbytes += dataoffset;
	}
	else
	{
		dataoffset = 0;			/* marker for no null bitmap */
		nbytes += ARR_OVERHEAD_NONULLS(ndims);
	}
2845
	result = (ArrayType *) palloc(nbytes);
2846
	SET_VARSIZE(result, nbytes);
2847
	result->ndim = ndims;
2848
	result->dataoffset = dataoffset;
2849
	result->elemtype = elmtype;
2850 2851
	memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
	memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
2852

2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
	CopyArrayEls(result,
				 elems, nulls, nelems,
				 elmlen, elmbyval, elmalign,
				 false);

	return result;
}

/*
 * construct_empty_array	--- make a zero-dimensional array of given type
 */
ArrayType *
construct_empty_array(Oid elmtype)
{
	ArrayType  *result;

	result = (ArrayType *) palloc(sizeof(ArrayType));
2870
	SET_VARSIZE(result, sizeof(ArrayType));
2871 2872 2873
	result->ndim = 0;
	result->dataoffset = 0;
	result->elemtype = elmtype;
2874 2875 2876
	return result;
}

2877
/*
2878 2879 2880
 * deconstruct_array  --- simple method for extracting data from an array
 *
 * array: array object to examine (must not be NULL)
2881
 * elmtype, elmlen, elmbyval, elmalign: info for the datatype of the items
2882
 * elemsp: return value, set to point to palloc'd array of Datum values
2883
 * nullsp: return value, set to point to palloc'd array of isnull markers
2884 2885
 * nelemsp: return value, set to number of extracted values
 *
2886 2887 2888 2889
 * The caller may pass nullsp == NULL if it does not support NULLs in the
 * array.  Note that this produces a very uninformative error message,
 * so do it only in cases where a NULL is really not expected.
 *
2890 2891
 * If array elements are pass-by-ref data type, the returned Datums will
 * be pointers into the array object.
2892 2893 2894 2895 2896
 *
 * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
 * from the system catalogs, given the elmtype.  However, in most current
 * uses the type is hard-wired into the caller and so we can save a lookup
 * cycle by hard-wiring the type info as well.
2897 2898 2899
 */
void
deconstruct_array(ArrayType *array,
2900 2901
				  Oid elmtype,
				  int elmlen, bool elmbyval, char elmalign,
2902
				  Datum **elemsp, bool **nullsp, int *nelemsp)
2903 2904
{
	Datum	   *elems;
2905
	bool	   *nulls;
2906 2907
	int			nelems;
	char	   *p;
2908 2909
	bits8	   *bitmap;
	int			bitmask;
2910 2911
	int			i;

2912 2913
	Assert(ARR_ELEMTYPE(array) == elmtype);

2914
	nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
2915
	*elemsp = elems = (Datum *) palloc(nelems * sizeof(Datum));
2916 2917 2918 2919
	if (nullsp)
		*nullsp = nulls = (bool *) palloc(nelems * sizeof(bool));
	else
		nulls = NULL;
2920 2921 2922
	*nelemsp = nelems;

	p = ARR_DATA_PTR(array);
2923 2924 2925
	bitmap = ARR_NULLBITMAP(array);
	bitmask = 1;

2926 2927
	for (i = 0; i < nelems; i++)
	{
2928 2929 2930 2931 2932 2933 2934 2935 2936
		/* Get source element, checking for NULL */
		if (bitmap && (*bitmap & bitmask) == 0)
		{
			elems[i] = (Datum) 0;
			if (nulls)
				nulls[i] = true;
			else
				ereport(ERROR,
						(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2937
				  errmsg("null array element not allowed in this context")));
2938 2939 2940 2941 2942 2943
		}
		else
		{
			elems[i] = fetch_att(p, elmbyval, elmlen);
			if (nulls)
				nulls[i] = false;
2944 2945
			p = att_addlength_pointer(p, elmlen, p);
			p = (char *) att_align_nominal(p, elmalign);
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
		}

		/* advance bitmap pointer if any */
		if (bitmap)
		{
			bitmask <<= 1;
			if (bitmask == 0x100)
			{
				bitmap++;
				bitmask = 1;
			}
		}
2958 2959 2960 2961
	}
}


2962
/*
2963
 * array_eq :
2964
 *		  compares two arrays for equality
2965
 * result :
2966
 *		  returns true if the arrays are equal, false otherwise.
2967 2968 2969
 *
 * Note: we do not use array_cmp here, since equality may be meaningful in
 * datatypes that don't have a total ordering (and hence no btree support).
2970
 */
2971 2972
Datum
array_eq(PG_FUNCTION_ARGS)
2973
{
2974 2975
	ArrayType  *array1 = PG_GETARG_ARRAYTYPE_P(0);
	ArrayType  *array2 = PG_GETARG_ARRAYTYPE_P(1);
2976 2977 2978 2979 2980
	int			ndims1 = ARR_NDIM(array1);
	int			ndims2 = ARR_NDIM(array2);
	int		   *dims1 = ARR_DIMS(array1);
	int		   *dims2 = ARR_DIMS(array2);
	Oid			element_type = ARR_ELEMTYPE(array1);
2981
	bool		result = true;
2982
	int			nitems;
2983
	TypeCacheEntry *typentry;
2984 2985 2986
	int			typlen;
	bool		typbyval;
	char		typalign;
2987 2988 2989 2990 2991
	char	   *ptr1;
	char	   *ptr2;
	bits8	   *bitmap1;
	bits8	   *bitmap2;
	int			bitmask;
2992 2993
	int			i;
	FunctionCallInfoData locfcinfo;
2994

2995
	if (element_type != ARR_ELEMTYPE(array2))
2996 2997
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
2998
				 errmsg("cannot compare arrays of different element types")));
2999

3000 3001 3002
	/* fast path if the arrays do not have the same dimensionality */
	if (ndims1 != ndims2 ||
		memcmp(dims1, dims2, 2 * ndims1 * sizeof(int)) != 0)
3003
		result = false;
3004 3005 3006
	else
	{
		/*
3007 3008 3009 3010
		 * We arrange to look up the equality function only once per series of
		 * calls, assuming the element type doesn't change underneath us.  The
		 * typcache is used so that we have no memory leakage when being used
		 * as an index support function.
3011
		 */
3012 3013 3014
		typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
		if (typentry == NULL ||
			typentry->type_id != element_type)
3015
		{
3016 3017 3018 3019 3020
			typentry = lookup_type_cache(element_type,
										 TYPECACHE_EQ_OPR_FINFO);
			if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_FUNCTION),
3021 3022
				errmsg("could not identify an equality operator for type %s",
					   format_type_be(element_type))));
3023
			fcinfo->flinfo->fn_extra = (void *) typentry;
3024
		}
3025 3026 3027
		typlen = typentry->typlen;
		typbyval = typentry->typbyval;
		typalign = typentry->typalign;
3028 3029 3030 3031

		/*
		 * apply the operator to each pair of array elements.
		 */
3032 3033
		InitFunctionCallInfoData(locfcinfo, &typentry->eq_opr_finfo, 2,
								 NULL, NULL);
3034 3035

		/* Loop over source data */
3036
		nitems = ArrayGetNItems(ndims1, dims1);
3037 3038 3039 3040 3041 3042
		ptr1 = ARR_DATA_PTR(array1);
		ptr2 = ARR_DATA_PTR(array2);
		bitmap1 = ARR_NULLBITMAP(array1);
		bitmap2 = ARR_NULLBITMAP(array2);
		bitmask = 1;			/* use same bitmask for both arrays */

3043
		for (i = 0; i < nitems; i++)
3044
		{
Bruce Momjian's avatar
Bruce Momjian committed
3045 3046
			Datum		elt1;
			Datum		elt2;
3047 3048
			bool		isnull1;
			bool		isnull2;
Bruce Momjian's avatar
Bruce Momjian committed
3049
			bool		oprresult;
3050

3051 3052 3053 3054 3055 3056 3057 3058 3059 3060
			/* Get elements, checking for NULL */
			if (bitmap1 && (*bitmap1 & bitmask) == 0)
			{
				isnull1 = true;
				elt1 = (Datum) 0;
			}
			else
			{
				isnull1 = false;
				elt1 = fetch_att(ptr1, typbyval, typlen);
3061 3062
				ptr1 = att_addlength_pointer(ptr1, typlen, ptr1);
				ptr1 = (char *) att_align_nominal(ptr1, typalign);
3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073
			}

			if (bitmap2 && (*bitmap2 & bitmask) == 0)
			{
				isnull2 = true;
				elt2 = (Datum) 0;
			}
			else
			{
				isnull2 = false;
				elt2 = fetch_att(ptr2, typbyval, typlen);
3074 3075
				ptr2 = att_addlength_pointer(ptr2, typlen, ptr2);
				ptr2 = (char *) att_align_nominal(ptr2, typalign);
3076
			}
3077

3078 3079 3080 3081 3082 3083 3084 3085 3086 3087
			/* advance bitmap pointers if any */
			bitmask <<= 1;
			if (bitmask == 0x100)
			{
				if (bitmap1)
					bitmap1++;
				if (bitmap2)
					bitmap2++;
				bitmask = 1;
			}
3088

3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
			/*
			 * We consider two NULLs equal; NULL and not-NULL are unequal.
			 */
			if (isnull1 && isnull2)
				continue;
			if (isnull1 || isnull2)
			{
				result = false;
				break;
			}
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115

			/*
			 * Apply the operator to the element pair
			 */
			locfcinfo.arg[0] = elt1;
			locfcinfo.arg[1] = elt2;
			locfcinfo.argnull[0] = false;
			locfcinfo.argnull[1] = false;
			locfcinfo.isnull = false;
			oprresult = DatumGetBool(FunctionCallInvoke(&locfcinfo));
			if (!oprresult)
			{
				result = false;
				break;
			}
		}
	}
3116

3117 3118 3119 3120 3121
	/* Avoid leaking memory when handed toasted input. */
	PG_FREE_IF_COPY(array1, 0);
	PG_FREE_IF_COPY(array2, 1);

	PG_RETURN_BOOL(result);
3122 3123
}

3124

3125 3126 3127 3128 3129 3130 3131 3132
/*-----------------------------------------------------------------------------
 * array-array bool operators:
 *		Given two arrays, iterate comparison operators
 *		over the array. Uses logic similar to text comparison
 *		functions, except element-by-element instead of
 *		character-by-character.
 *----------------------------------------------------------------------------
 */
3133

3134 3135 3136 3137 3138
Datum
array_ne(PG_FUNCTION_ARGS)
{
	PG_RETURN_BOOL(!DatumGetBool(array_eq(fcinfo)));
}
Bruce Momjian's avatar
Bruce Momjian committed
3139

3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159
Datum
array_lt(PG_FUNCTION_ARGS)
{
	PG_RETURN_BOOL(array_cmp(fcinfo) < 0);
}

Datum
array_gt(PG_FUNCTION_ARGS)
{
	PG_RETURN_BOOL(array_cmp(fcinfo) > 0);
}

Datum
array_le(PG_FUNCTION_ARGS)
{
	PG_RETURN_BOOL(array_cmp(fcinfo) <= 0);
}

Datum
array_ge(PG_FUNCTION_ARGS)
Bruce Momjian's avatar
Bruce Momjian committed
3160
{
3161 3162 3163 3164 3165 3166 3167
	PG_RETURN_BOOL(array_cmp(fcinfo) >= 0);
}

Datum
btarraycmp(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT32(array_cmp(fcinfo));
Bruce Momjian's avatar
Bruce Momjian committed
3168 3169
}

3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180
/*
 * array_cmp()
 * Internal comparison function for arrays.
 *
 * Returns -1, 0 or 1
 */
static int
array_cmp(FunctionCallInfo fcinfo)
{
	ArrayType  *array1 = PG_GETARG_ARRAYTYPE_P(0);
	ArrayType  *array2 = PG_GETARG_ARRAYTYPE_P(1);
3181 3182 3183 3184 3185 3186 3187
	int			ndims1 = ARR_NDIM(array1);
	int			ndims2 = ARR_NDIM(array2);
	int		   *dims1 = ARR_DIMS(array1);
	int		   *dims2 = ARR_DIMS(array2);
	int			nitems1 = ArrayGetNItems(ndims1, dims1);
	int			nitems2 = ArrayGetNItems(ndims2, dims2);
	Oid			element_type = ARR_ELEMTYPE(array1);
3188
	int			result = 0;
3189
	TypeCacheEntry *typentry;
3190 3191 3192
	int			typlen;
	bool		typbyval;
	char		typalign;
3193
	int			min_nitems;
3194 3195 3196 3197 3198
	char	   *ptr1;
	char	   *ptr2;
	bits8	   *bitmap1;
	bits8	   *bitmap2;
	int			bitmask;
3199
	int			i;
3200
	FunctionCallInfoData locfcinfo;
3201 3202

	if (element_type != ARR_ELEMTYPE(array2))
3203 3204
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
3205
				 errmsg("cannot compare arrays of different element types")));
3206 3207

	/*
3208 3209 3210 3211
	 * We arrange to look up the comparison function only once per series of
	 * calls, assuming the element type doesn't change underneath us. The
	 * typcache is used so that we have no memory leakage when being used as
	 * an index support function.
3212
	 */
3213 3214 3215
	typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
	if (typentry == NULL ||
		typentry->type_id != element_type)
3216
	{
3217 3218 3219 3220 3221
		typentry = lookup_type_cache(element_type,
									 TYPECACHE_CMP_PROC_FINFO);
		if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_FUNCTION),
3222 3223
			   errmsg("could not identify a comparison function for type %s",
					  format_type_be(element_type))));
3224
		fcinfo->flinfo->fn_extra = (void *) typentry;
3225
	}
3226 3227 3228
	typlen = typentry->typlen;
	typbyval = typentry->typbyval;
	typalign = typentry->typalign;
3229

3230 3231 3232
	/*
	 * apply the operator to each pair of array elements.
	 */
3233 3234
	InitFunctionCallInfoData(locfcinfo, &typentry->cmp_proc_finfo, 2,
							 NULL, NULL);
3235

3236
	/* Loop over source data */
3237
	min_nitems = Min(nitems1, nitems2);
3238 3239 3240 3241 3242 3243
	ptr1 = ARR_DATA_PTR(array1);
	ptr2 = ARR_DATA_PTR(array2);
	bitmap1 = ARR_NULLBITMAP(array1);
	bitmap2 = ARR_NULLBITMAP(array2);
	bitmask = 1;				/* use same bitmask for both arrays */

3244 3245 3246 3247
	for (i = 0; i < min_nitems; i++)
	{
		Datum		elt1;
		Datum		elt2;
3248 3249
		bool		isnull1;
		bool		isnull2;
3250
		int32		cmpresult;
3251

3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
		/* Get elements, checking for NULL */
		if (bitmap1 && (*bitmap1 & bitmask) == 0)
		{
			isnull1 = true;
			elt1 = (Datum) 0;
		}
		else
		{
			isnull1 = false;
			elt1 = fetch_att(ptr1, typbyval, typlen);
3262 3263
			ptr1 = att_addlength_pointer(ptr1, typlen, ptr1);
			ptr1 = (char *) att_align_nominal(ptr1, typalign);
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
		}

		if (bitmap2 && (*bitmap2 & bitmask) == 0)
		{
			isnull2 = true;
			elt2 = (Datum) 0;
		}
		else
		{
			isnull2 = false;
			elt2 = fetch_att(ptr2, typbyval, typlen);
3275 3276
			ptr2 = att_addlength_pointer(ptr2, typlen, ptr2);
			ptr2 = (char *) att_align_nominal(ptr2, typalign);
3277
		}
3278

3279 3280 3281 3282 3283 3284 3285 3286 3287 3288
		/* advance bitmap pointers if any */
		bitmask <<= 1;
		if (bitmask == 0x100)
		{
			if (bitmap1)
				bitmap1++;
			if (bitmap2)
				bitmap2++;
			bitmask = 1;
		}
3289

3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306
		/*
		 * We consider two NULLs equal; NULL > not-NULL.
		 */
		if (isnull1 && isnull2)
			continue;
		if (isnull1)
		{
			/* arg1 is greater than arg2 */
			result = 1;
			break;
		}
		if (isnull2)
		{
			/* arg1 is less than arg2 */
			result = -1;
			break;
		}
3307 3308

		/* Compare the pair of elements */
3309 3310 3311 3312 3313 3314
		locfcinfo.arg[0] = elt1;
		locfcinfo.arg[1] = elt2;
		locfcinfo.argnull[0] = false;
		locfcinfo.argnull[1] = false;
		locfcinfo.isnull = false;
		cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
3315

3316 3317
		if (cmpresult == 0)
			continue;			/* equal */
3318

3319
		if (cmpresult < 0)
3320
		{
3321 3322 3323 3324 3325 3326 3327 3328 3329
			/* arg1 is less than arg2 */
			result = -1;
			break;
		}
		else
		{
			/* arg1 is greater than arg2 */
			result = 1;
			break;
3330 3331 3332
		}
	}

3333
	/*
3334 3335 3336 3337
	 * If arrays contain same data (up to end of shorter one), apply
	 * additional rules to sort by dimensionality.	The relative significance
	 * of the different bits of information is historical; mainly we just care
	 * that we don't say "equal" for arrays of different dimensionality.
3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
	 */
	if (result == 0)
	{
		if (nitems1 != nitems2)
			result = (nitems1 < nitems2) ? -1 : 1;
		else if (ndims1 != ndims2)
			result = (ndims1 < ndims2) ? -1 : 1;
		else
		{
			/* this relies on LB array immediately following DIMS array */
			for (i = 0; i < ndims1 * 2; i++)
			{
				if (dims1[i] != dims2[i])
				{
					result = (dims1[i] < dims2[i]) ? -1 : 1;
					break;
				}
			}
		}
	}
3358 3359 3360 3361 3362 3363 3364 3365 3366

	/* Avoid leaking memory when handed toasted input. */
	PG_FREE_IF_COPY(array1, 0);
	PG_FREE_IF_COPY(array2, 1);

	return result;
}


3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409
/*-----------------------------------------------------------------------------
 * array overlap/containment comparisons
 *		These use the same methods of comparing array elements as array_eq.
 *		We consider only the elements of the arrays, ignoring dimensionality.
 *----------------------------------------------------------------------------
 */

/*
 * array_contain_compare :
 *		  compares two arrays for overlap/containment
 *
 * When matchall is true, return true if all members of array1 are in array2.
 * When matchall is false, return true if any members of array1 are in array2.
 */
static bool
array_contain_compare(ArrayType *array1, ArrayType *array2, bool matchall,
					  void **fn_extra)
{
	bool		result = matchall;
	Oid			element_type = ARR_ELEMTYPE(array1);
	TypeCacheEntry *typentry;
	int			nelems1;
	Datum	   *values2;
	bool	   *nulls2;
	int			nelems2;
	int			typlen;
	bool		typbyval;
	char		typalign;
	char	   *ptr1;
	bits8	   *bitmap1;
	int			bitmask;
	int			i;
	int			j;
	FunctionCallInfoData locfcinfo;

	if (element_type != ARR_ELEMTYPE(array2))
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
				 errmsg("cannot compare arrays of different element types")));

	/*
	 * We arrange to look up the equality function only once per series of
	 * calls, assuming the element type doesn't change underneath us.  The
Bruce Momjian's avatar
Bruce Momjian committed
3410 3411
	 * typcache is used so that we have no memory leakage when being used as
	 * an index support function.
3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
	 */
	typentry = (TypeCacheEntry *) *fn_extra;
	if (typentry == NULL ||
		typentry->type_id != element_type)
	{
		typentry = lookup_type_cache(element_type,
									 TYPECACHE_EQ_OPR_FINFO);
		if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_FUNCTION),
Bruce Momjian's avatar
Bruce Momjian committed
3422 3423
				errmsg("could not identify an equality operator for type %s",
					   format_type_be(element_type))));
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
		*fn_extra = (void *) typentry;
	}
	typlen = typentry->typlen;
	typbyval = typentry->typbyval;
	typalign = typentry->typalign;

	/*
	 * Since we probably will need to scan array2 multiple times, it's
	 * worthwhile to use deconstruct_array on it.  We scan array1 the hard way
	 * however, since we very likely won't need to look at all of it.
	 */
	deconstruct_array(array2, element_type, typlen, typbyval, typalign,
					  &values2, &nulls2, &nelems2);

	/*
	 * Apply the comparison operator to each pair of array elements.
	 */
	InitFunctionCallInfoData(locfcinfo, &typentry->eq_opr_finfo, 2,
							 NULL, NULL);

	/* Loop over source data */
	nelems1 = ArrayGetNItems(ARR_NDIM(array1), ARR_DIMS(array1));
	ptr1 = ARR_DATA_PTR(array1);
	bitmap1 = ARR_NULLBITMAP(array1);
	bitmask = 1;

	for (i = 0; i < nelems1; i++)
	{
		Datum		elt1;
		bool		isnull1;

		/* Get element, checking for NULL */
		if (bitmap1 && (*bitmap1 & bitmask) == 0)
		{
			isnull1 = true;
			elt1 = (Datum) 0;
		}
		else
		{
			isnull1 = false;
			elt1 = fetch_att(ptr1, typbyval, typlen);
3465 3466
			ptr1 = att_addlength_pointer(ptr1, typlen, ptr1);
			ptr1 = (char *) att_align_nominal(ptr1, typalign);
3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478
		}

		/* advance bitmap pointer if any */
		bitmask <<= 1;
		if (bitmask == 0x100)
		{
			if (bitmap1)
				bitmap1++;
			bitmask = 1;
		}

		/*
Bruce Momjian's avatar
Bruce Momjian committed
3479 3480 3481
		 * We assume that the comparison operator is strict, so a NULL can't
		 * match anything.	XXX this diverges from the "NULL=NULL" behavior of
		 * array_eq, should we act like that?
3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592
		 */
		if (isnull1)
		{
			if (matchall)
			{
				result = false;
				break;
			}
			continue;
		}

		for (j = 0; j < nelems2; j++)
		{
			Datum		elt2 = values2[j];
			bool		isnull2 = nulls2[j];
			bool		oprresult;

			if (isnull2)
				continue;		/* can't match */

			/*
			 * Apply the operator to the element pair
			 */
			locfcinfo.arg[0] = elt1;
			locfcinfo.arg[1] = elt2;
			locfcinfo.argnull[0] = false;
			locfcinfo.argnull[1] = false;
			locfcinfo.isnull = false;
			oprresult = DatumGetBool(FunctionCallInvoke(&locfcinfo));
			if (oprresult)
				break;
		}

		if (j < nelems2)
		{
			/* found a match for elt1 */
			if (!matchall)
			{
				result = true;
				break;
			}
		}
		else
		{
			/* no match for elt1 */
			if (matchall)
			{
				result = false;
				break;
			}
		}
	}

	pfree(values2);
	pfree(nulls2);

	return result;
}

Datum
arrayoverlap(PG_FUNCTION_ARGS)
{
	ArrayType  *array1 = PG_GETARG_ARRAYTYPE_P(0);
	ArrayType  *array2 = PG_GETARG_ARRAYTYPE_P(1);
	bool		result;

	result = array_contain_compare(array1, array2, false,
								   &fcinfo->flinfo->fn_extra);

	/* Avoid leaking memory when handed toasted input. */
	PG_FREE_IF_COPY(array1, 0);
	PG_FREE_IF_COPY(array2, 1);

	PG_RETURN_BOOL(result);
}

Datum
arraycontains(PG_FUNCTION_ARGS)
{
	ArrayType  *array1 = PG_GETARG_ARRAYTYPE_P(0);
	ArrayType  *array2 = PG_GETARG_ARRAYTYPE_P(1);
	bool		result;

	result = array_contain_compare(array2, array1, true,
								   &fcinfo->flinfo->fn_extra);

	/* Avoid leaking memory when handed toasted input. */
	PG_FREE_IF_COPY(array1, 0);
	PG_FREE_IF_COPY(array2, 1);

	PG_RETURN_BOOL(result);
}

Datum
arraycontained(PG_FUNCTION_ARGS)
{
	ArrayType  *array1 = PG_GETARG_ARRAYTYPE_P(0);
	ArrayType  *array2 = PG_GETARG_ARRAYTYPE_P(1);
	bool		result;

	result = array_contain_compare(array1, array2, true,
								   &fcinfo->flinfo->fn_extra);

	/* Avoid leaking memory when handed toasted input. */
	PG_FREE_IF_COPY(array1, 0);
	PG_FREE_IF_COPY(array2, 1);

	PG_RETURN_BOOL(result);
}


3593 3594 3595 3596
/***************************************************************************/
/******************|		  Support  Routines			  |*****************/
/***************************************************************************/

3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632
/*
 * Check whether a specific array element is NULL
 *
 * nullbitmap: pointer to array's null bitmap (NULL if none)
 * offset: 0-based linear element number of array element
 */
static bool
array_get_isnull(const bits8 *nullbitmap, int offset)
{
	if (nullbitmap == NULL)
		return false;			/* assume not null */
	if (nullbitmap[offset / 8] & (1 << (offset % 8)))
		return false;			/* not null */
	return true;
}

/*
 * Set a specific array element's null-bitmap entry
 *
 * nullbitmap: pointer to array's null bitmap (mustn't be NULL)
 * offset: 0-based linear element number of array element
 * isNull: null status to set
 */
static void
array_set_isnull(bits8 *nullbitmap, int offset, bool isNull)
{
	int			bitmask;

	nullbitmap += offset / 8;
	bitmask = 1 << (offset % 8);
	if (isNull)
		*nullbitmap &= ~bitmask;
	else
		*nullbitmap |= bitmask;
}

3633 3634
/*
 * Fetch array element at pointer, converted correctly to a Datum
3635 3636
 *
 * Caller must have handled case of NULL element
3637
 */
3638
static Datum
3639
ArrayCast(char *value, bool byval, int len)
3640
{
3641
	return fetch_att(value, byval, len);
3642 3643
}

3644 3645
/*
 * Copy datum to *dest and return total space used (including align padding)
3646 3647
 *
 * Caller must have handled case of NULL element
3648
 */
3649
static int
3650
ArrayCastAndSet(Datum src,
3651
				int typlen,
3652 3653
				bool typbyval,
				char typalign,
3654
				char *dest)
3655
{
3656
	int			inc;
3657 3658 3659 3660

	if (typlen > 0)
	{
		if (typbyval)
3661
			store_att_byval(dest, src, typlen);
3662
		else
3663
			memmove(dest, DatumGetPointer(src), typlen);
3664
		inc = att_align_nominal(typlen, typalign);
3665 3666 3667
	}
	else
	{
3668
		Assert(!typbyval);
3669
		inc = att_addlength_datum(0, typlen, src);
3670
		memmove(dest, DatumGetPointer(src), inc);
3671
		inc = att_align_nominal(inc, typalign);
3672
	}
3673

3674
	return inc;
3675
}
3676

3677
/*
3678 3679 3680 3681 3682 3683 3684 3685 3686
 * Advance ptr over nitems array elements
 *
 * ptr: starting location in array
 * offset: 0-based linear element number of first element (the one at *ptr)
 * nullbitmap: start of array's null bitmap, or NULL if none
 * nitems: number of array elements to advance over (>= 0)
 * typlen, typbyval, typalign: storage parameters of array element datatype
 *
 * It is caller's responsibility to ensure that nitems is within range
3687
 */
3688 3689 3690
static char *
array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems,
		   int typlen, bool typbyval, char typalign)
3691
{
3692
	int			bitmask;
3693
	int			i;
3694

3695 3696
	/* easy if fixed-size elements and no NULLs */
	if (typlen > 0 && !nullbitmap)
3697
		return ptr + nitems * ((Size) att_align_nominal(typlen, typalign));
3698

3699 3700
	/* seems worth having separate loops for NULL and no-NULLs cases */
	if (nullbitmap)
3701
	{
3702 3703 3704 3705 3706 3707 3708
		nullbitmap += offset / 8;
		bitmask = 1 << (offset % 8);

		for (i = 0; i < nitems; i++)
		{
			if (*nullbitmap & bitmask)
			{
3709 3710
				ptr = att_addlength_pointer(ptr, typlen, ptr);
				ptr = (char *) att_align_nominal(ptr, typalign);
3711 3712 3713 3714 3715 3716 3717 3718
			}
			bitmask <<= 1;
			if (bitmask == 0x100)
			{
				nullbitmap++;
				bitmask = 1;
			}
		}
3719
	}
3720 3721 3722 3723
	else
	{
		for (i = 0; i < nitems; i++)
		{
3724 3725
			ptr = att_addlength_pointer(ptr, typlen, ptr);
			ptr = (char *) att_align_nominal(ptr, typalign);
3726 3727 3728
		}
	}
	return ptr;
3729 3730
}

3731
/*
3732 3733 3734
 * Compute total size of the nitems array elements starting at *ptr
 *
 * Parameters same as for array_seek
3735
 */
3736 3737 3738
static int
array_nelems_size(char *ptr, int offset, bits8 *nullbitmap, int nitems,
				  int typlen, bool typbyval, char typalign)
3739
{
3740 3741
	return array_seek(ptr, offset, nullbitmap, nitems,
					  typlen, typbyval, typalign) - ptr;
3742
}
3743

3744 3745 3746
/*
 * Copy nitems array elements from srcptr to destptr
 *
3747 3748 3749 3750 3751 3752 3753
 * destptr: starting destination location (must be enough room!)
 * nitems: number of array elements to copy (>= 0)
 * srcptr: starting location in source array
 * offset: 0-based linear element number of first element (the one at *srcptr)
 * nullbitmap: start of source array's null bitmap, or NULL if none
 * typlen, typbyval, typalign: storage parameters of array element datatype
 *
3754
 * Returns number of bytes copied
3755 3756
 *
 * NB: this does not take care of setting up the destination's null bitmap!
3757 3758
 */
static int
3759 3760
array_copy(char *destptr, int nitems,
		   char *srcptr, int offset, bits8 *nullbitmap,
3761
		   int typlen, bool typbyval, char typalign)
3762
{
3763
	int			numbytes;
3764

3765 3766 3767
	numbytes = array_nelems_size(srcptr, offset, nullbitmap, nitems,
								 typlen, typbyval, typalign);
	memcpy(destptr, srcptr, numbytes);
3768
	return numbytes;
3769 3770
}

3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785
/*
 * Copy nitems null-bitmap bits from source to destination
 *
 * destbitmap: start of destination array's null bitmap (mustn't be NULL)
 * destoffset: 0-based linear element number of first dest element
 * srcbitmap: start of source array's null bitmap, or NULL if none
 * srcoffset: 0-based linear element number of first source element
 * nitems: number of bits to copy (>= 0)
 *
 * If srcbitmap is NULL then we assume the source is all-non-NULL and
 * fill 1's into the destination bitmap.  Note that only the specified
 * bits in the destination map are changed, not any before or after.
 *
 * Note: this could certainly be optimized using standard bitblt methods.
 * However, it's not clear that the typical Postgres array has enough elements
3786
 * to make it worth worrying too much.	For the moment, KISS.
3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853
 */
void
array_bitmap_copy(bits8 *destbitmap, int destoffset,
				  const bits8 *srcbitmap, int srcoffset,
				  int nitems)
{
	int			destbitmask,
				destbitval,
				srcbitmask,
				srcbitval;

	Assert(destbitmap);
	if (nitems <= 0)
		return;					/* don't risk fetch off end of memory */
	destbitmap += destoffset / 8;
	destbitmask = 1 << (destoffset % 8);
	destbitval = *destbitmap;
	if (srcbitmap)
	{
		srcbitmap += srcoffset / 8;
		srcbitmask = 1 << (srcoffset % 8);
		srcbitval = *srcbitmap;
		while (nitems-- > 0)
		{
			if (srcbitval & srcbitmask)
				destbitval |= destbitmask;
			else
				destbitval &= ~destbitmask;
			destbitmask <<= 1;
			if (destbitmask == 0x100)
			{
				*destbitmap++ = destbitval;
				destbitmask = 1;
				if (nitems > 0)
					destbitval = *destbitmap;
			}
			srcbitmask <<= 1;
			if (srcbitmask == 0x100)
			{
				srcbitmap++;
				srcbitmask = 1;
				if (nitems > 0)
					srcbitval = *srcbitmap;
			}
		}
		if (destbitmask != 1)
			*destbitmap = destbitval;
	}
	else
	{
		while (nitems-- > 0)
		{
			destbitval |= destbitmask;
			destbitmask <<= 1;
			if (destbitmask == 0x100)
			{
				*destbitmap++ = destbitval;
				destbitmask = 1;
				if (nitems > 0)
					destbitval = *destbitmap;
			}
		}
		if (destbitmask != 1)
			*destbitmap = destbitval;
	}
}

3854 3855 3856 3857 3858
/*
 * Compute space needed for a slice of an array
 *
 * We assume the caller has verified that the slice coordinates are valid.
 */
3859
static int
3860 3861
array_slice_size(char *arraydataptr, bits8 *arraynullsptr,
				 int ndim, int *dim, int *lb,
3862 3863
				 int *st, int *endp,
				 int typlen, bool typbyval, char typalign)
3864
{
3865
	int			src_offset,
3866 3867
				span[MAXDIM],
				prod[MAXDIM],
3868 3869
				dist[MAXDIM],
				indx[MAXDIM];
3870
	char	   *ptr;
3871 3872
	int			i,
				j,
3873
				inc;
3874
	int			count = 0;
3875

3876 3877
	mda_get_range(ndim, span, st, endp);

3878 3879
	/* Pretty easy for fixed element length without nulls ... */
	if (typlen > 0 && !arraynullsptr)
3880
		return ArrayGetNItems(ndim, span) * att_align_nominal(typlen, typalign);
3881 3882

	/* Else gotta do it the hard way */
3883 3884
	src_offset = ArrayGetOffset(ndim, dim, lb, st);
	ptr = array_seek(arraydataptr, 0, arraynullsptr, src_offset,
3885
					 typlen, typbyval, typalign);
3886 3887 3888
	mda_get_prod(ndim, dim, prod);
	mda_get_offset_values(ndim, dist, prod, span);
	for (i = 0; i < ndim; i++)
3889
		indx[i] = 0;
3890
	j = ndim - 1;
3891 3892
	do
	{
3893 3894 3895 3896 3897 3898 3899 3900
		if (dist[j])
		{
			ptr = array_seek(ptr, src_offset, arraynullsptr, dist[j],
							 typlen, typbyval, typalign);
			src_offset += dist[j];
		}
		if (!array_get_isnull(arraynullsptr, src_offset))
		{
3901 3902
			inc = att_addlength_pointer(0, typlen, ptr);
			inc = att_align_nominal(inc, typalign);
3903 3904 3905 3906
			ptr += inc;
			count += inc;
		}
		src_offset++;
3907
	} while ((j = mda_next_tuple(ndim, indx, span)) != -1);
3908
	return count;
3909 3910
}

3911
/*
3912 3913
 * Extract a slice of an array into consecutive elements in the destination
 * array.
3914
 *
3915 3916 3917
 * We assume the caller has verified that the slice coordinates are valid,
 * allocated enough storage for the result, and initialized the header
 * of the new array.
3918 3919
 */
static void
3920 3921
array_extract_slice(ArrayType *newarray,
					int ndim,
3922 3923 3924
					int *dim,
					int *lb,
					char *arraydataptr,
3925
					bits8 *arraynullsptr,
3926 3927
					int *st,
					int *endp,
3928 3929 3930
					int typlen,
					bool typbyval,
					char typalign)
3931
{
3932 3933 3934 3935 3936
	char	   *destdataptr = ARR_DATA_PTR(newarray);
	bits8	   *destnullsptr = ARR_NULLBITMAP(newarray);
	char	   *srcdataptr;
	int			src_offset,
				dest_offset,
3937 3938 3939 3940 3941 3942 3943
				prod[MAXDIM],
				span[MAXDIM],
				dist[MAXDIM],
				indx[MAXDIM];
	int			i,
				j,
				inc;
3944

3945 3946
	src_offset = ArrayGetOffset(ndim, dim, lb, st);
	srcdataptr = array_seek(arraydataptr, 0, arraynullsptr, src_offset,
3947
							typlen, typbyval, typalign);
3948 3949 3950 3951 3952
	mda_get_prod(ndim, dim, prod);
	mda_get_range(ndim, span, st, endp);
	mda_get_offset_values(ndim, dist, prod, span);
	for (i = 0; i < ndim; i++)
		indx[i] = 0;
3953
	dest_offset = 0;
3954 3955 3956
	j = ndim - 1;
	do
	{
3957 3958 3959 3960 3961 3962 3963 3964 3965 3966
		if (dist[j])
		{
			/* skip unwanted elements */
			srcdataptr = array_seek(srcdataptr, src_offset, arraynullsptr,
									dist[j],
									typlen, typbyval, typalign);
			src_offset += dist[j];
		}
		inc = array_copy(destdataptr, 1,
						 srcdataptr, src_offset, arraynullsptr,
3967
						 typlen, typbyval, typalign);
3968 3969 3970 3971 3972 3973 3974 3975
		if (destnullsptr)
			array_bitmap_copy(destnullsptr, dest_offset,
							  arraynullsptr, src_offset,
							  1);
		destdataptr += inc;
		srcdataptr += inc;
		src_offset++;
		dest_offset++;
3976
	} while ((j = mda_next_tuple(ndim, indx, span)) != -1);
3977 3978
}

3979 3980 3981
/*
 * Insert a slice into an array.
 *
3982
 * ndim/dim[]/lb[] are dimensions of the original array.  A new array with
3983
 * those same dimensions is to be constructed.	destArray must already
3984
 * have been allocated and its header initialized.
3985
 *
3986 3987 3988
 * st[]/endp[] identify the slice to be replaced.  Elements within the slice
 * volume are taken from consecutive elements of the srcArray; elements
 * outside it are copied from origArray.
3989
 *
3990
 * We assume the caller has verified that the slice coordinates are valid.
3991 3992
 */
static void
3993 3994 3995 3996
array_insert_slice(ArrayType *destArray,
				   ArrayType *origArray,
				   ArrayType *srcArray,
				   int ndim,
3997 3998 3999 4000
				   int *dim,
				   int *lb,
				   int *st,
				   int *endp,
4001 4002 4003
				   int typlen,
				   bool typbyval,
				   char typalign)
4004
{
4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015
	char	   *destPtr = ARR_DATA_PTR(destArray);
	char	   *origPtr = ARR_DATA_PTR(origArray);
	char	   *srcPtr = ARR_DATA_PTR(srcArray);
	bits8	   *destBitmap = ARR_NULLBITMAP(destArray);
	bits8	   *origBitmap = ARR_NULLBITMAP(origArray);
	bits8	   *srcBitmap = ARR_NULLBITMAP(srcArray);
	int			orignitems = ArrayGetNItems(ARR_NDIM(origArray),
											ARR_DIMS(origArray));
	int			dest_offset,
				orig_offset,
				src_offset,
4016 4017 4018 4019
				prod[MAXDIM],
				span[MAXDIM],
				dist[MAXDIM],
				indx[MAXDIM];
4020
	int			i,
4021 4022
				j,
				inc;
4023

4024 4025 4026 4027
	dest_offset = ArrayGetOffset(ndim, dim, lb, st);
	/* copy items before the slice start */
	inc = array_copy(destPtr, dest_offset,
					 origPtr, 0, origBitmap,
4028
					 typlen, typbyval, typalign);
4029 4030
	destPtr += inc;
	origPtr += inc;
4031 4032 4033
	if (destBitmap)
		array_bitmap_copy(destBitmap, 0, origBitmap, 0, dest_offset);
	orig_offset = dest_offset;
4034 4035 4036 4037 4038
	mda_get_prod(ndim, dim, prod);
	mda_get_range(ndim, span, st, endp);
	mda_get_offset_values(ndim, dist, prod, span);
	for (i = 0; i < ndim; i++)
		indx[i] = 0;
4039
	src_offset = 0;
4040 4041
	j = ndim - 1;
	do
4042
	{
4043
		/* Copy/advance over elements between here and next part of slice */
4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057
		if (dist[j])
		{
			inc = array_copy(destPtr, dist[j],
							 origPtr, orig_offset, origBitmap,
							 typlen, typbyval, typalign);
			destPtr += inc;
			origPtr += inc;
			if (destBitmap)
				array_bitmap_copy(destBitmap, dest_offset,
								  origBitmap, orig_offset,
								  dist[j]);
			dest_offset += dist[j];
			orig_offset += dist[j];
		}
4058
		/* Copy new element at this slice position */
4059 4060
		inc = array_copy(destPtr, 1,
						 srcPtr, src_offset, srcBitmap,
4061
						 typlen, typbyval, typalign);
4062 4063 4064 4065
		if (destBitmap)
			array_bitmap_copy(destBitmap, dest_offset,
							  srcBitmap, src_offset,
							  1);
4066 4067
		destPtr += inc;
		srcPtr += inc;
4068 4069
		dest_offset++;
		src_offset++;
4070
		/* Advance over old element at this slice position */
4071
		origPtr = array_seek(origPtr, orig_offset, origBitmap, 1,
4072
							 typlen, typbyval, typalign);
4073
		orig_offset++;
4074 4075 4076
	} while ((j = mda_next_tuple(ndim, indx, span)) != -1);

	/* don't miss any data at the end */
4077 4078 4079 4080 4081 4082 4083
	array_copy(destPtr, orignitems - orig_offset,
			   origPtr, orig_offset, origBitmap,
			   typlen, typbyval, typalign);
	if (destBitmap)
		array_bitmap_copy(destBitmap, dest_offset,
						  origBitmap, orig_offset,
						  orignitems - orig_offset);
4084
}
4085

4086 4087 4088 4089 4090 4091 4092
/*
 * accumArrayResult - accumulate one (more) Datum for an array result
 *
 *	astate is working state (NULL on first call)
 *	rcontext is where to keep working state
 */
ArrayBuildState *
4093
accumArrayResult(ArrayBuildState *astate,
4094 4095 4096 4097 4098
				 Datum dvalue, bool disnull,
				 Oid element_type,
				 MemoryContext rcontext)
{
	MemoryContext arr_context,
Bruce Momjian's avatar
Bruce Momjian committed
4099
				oldcontext;
4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113

	if (astate == NULL)
	{
		/* First time through --- initialize */

		/* Make a temporary context to hold all the junk */
		arr_context = AllocSetContextCreate(rcontext,
											"accumArrayResult",
											ALLOCSET_DEFAULT_MINSIZE,
											ALLOCSET_DEFAULT_INITSIZE,
											ALLOCSET_DEFAULT_MAXSIZE);
		oldcontext = MemoryContextSwitchTo(arr_context);
		astate = (ArrayBuildState *) palloc(sizeof(ArrayBuildState));
		astate->mcontext = arr_context;
4114 4115 4116
		astate->alen = 64;		/* arbitrary starting array size */
		astate->dvalues = (Datum *) palloc(astate->alen * sizeof(Datum));
		astate->dnulls = (bool *) palloc(astate->alen * sizeof(bool));
4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
		astate->nelems = 0;
		astate->element_type = element_type;
		get_typlenbyvalalign(element_type,
							 &astate->typlen,
							 &astate->typbyval,
							 &astate->typalign);
	}
	else
	{
		oldcontext = MemoryContextSwitchTo(astate->mcontext);
		Assert(astate->element_type == element_type);
4128
		/* enlarge dvalues[]/dnulls[] if needed */
4129
		if (astate->nelems >= astate->alen)
4130
		{
4131
			astate->alen *= 2;
4132
			astate->dvalues = (Datum *)
4133
				repalloc(astate->dvalues, astate->alen * sizeof(Datum));
4134
			astate->dnulls = (bool *)
4135
				repalloc(astate->dnulls, astate->alen * sizeof(bool));
4136
		}
4137 4138 4139
	}

	/* Use datumCopy to ensure pass-by-ref stuff is copied into mcontext */
4140 4141 4142 4143 4144 4145
	if (!disnull && !astate->typbyval)
		dvalue = datumCopy(dvalue, astate->typbyval, astate->typlen);

	astate->dvalues[astate->nelems] = dvalue;
	astate->dnulls[astate->nelems] = disnull;
	astate->nelems++;
4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158

	MemoryContextSwitchTo(oldcontext);

	return astate;
}

/*
 * makeArrayResult - produce 1-D final result of accumArrayResult
 *
 *	astate is working state (not NULL)
 *	rcontext is where to construct result
 */
Datum
4159
makeArrayResult(ArrayBuildState *astate,
4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180
				MemoryContext rcontext)
{
	int			dims[1];
	int			lbs[1];

	dims[0] = astate->nelems;
	lbs[0] = 1;

	return makeMdArrayResult(astate, 1, dims, lbs, rcontext);
}

/*
 * makeMdArrayResult - produce multi-D final result of accumArrayResult
 *
 * beware: no check that specified dimensions match the number of values
 * accumulated.
 *
 *	astate is working state (not NULL)
 *	rcontext is where to construct result
 */
Datum
4181
makeMdArrayResult(ArrayBuildState *astate,
4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
				  int ndims,
				  int *dims,
				  int *lbs,
				  MemoryContext rcontext)
{
	ArrayType  *result;
	MemoryContext oldcontext;

	/* Build the final array result in rcontext */
	oldcontext = MemoryContextSwitchTo(rcontext);

	result = construct_md_array(astate->dvalues,
4194
								astate->dnulls,
4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209
								ndims,
								dims,
								lbs,
								astate->element_type,
								astate->typlen,
								astate->typbyval,
								astate->typalign);

	MemoryContextSwitchTo(oldcontext);

	/* Clean up all the junk */
	MemoryContextDelete(astate->mcontext);

	return PointerGetDatum(result);
}
4210 4211 4212 4213

Datum
array_larger(PG_FUNCTION_ARGS)
{
4214 4215 4216
	ArrayType  *v1,
			   *v2,
			   *result;
4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228

	v1 = PG_GETARG_ARRAYTYPE_P(0);
	v2 = PG_GETARG_ARRAYTYPE_P(1);

	result = ((array_cmp(fcinfo) > 0) ? v1 : v2);

	PG_RETURN_ARRAYTYPE_P(result);
}

Datum
array_smaller(PG_FUNCTION_ARGS)
{
4229 4230 4231
	ArrayType  *v1,
			   *v2,
			   *result;
4232 4233 4234 4235 4236 4237 4238 4239

	v1 = PG_GETARG_ARRAYTYPE_P(0);
	v2 = PG_GETARG_ARRAYTYPE_P(1);

	result = ((array_cmp(fcinfo) < 0) ? v1 : v2);

	PG_RETURN_ARRAYTYPE_P(result);
}