PostgreSQL Source Code  git master
arrayfuncs.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <math.h>
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "libpq/pqformat.h"
#include "nodes/nodeFuncs.h"
#include "nodes/supportnodes.h"
#include "optimizer/optimizer.h"
#include "port/pg_bitutils.h"
#include "utils/array.h"
#include "utils/arrayaccess.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/selfuncs.h"
#include "utils/typcache.h"
Include dependency graph for arrayfuncs.c:

Go to the source code of this file.

Data Structures

struct  ArrayIteratorData
 
struct  generate_subscripts_fctx
 

Macros

#define ASSGN   "="
 
#define AARR_FREE_IF_COPY(array, n)
 
#define APPENDSTR(str)   (strcpy(p, (str)), p += strlen(p))
 
#define APPENDCHAR(ch)   (*p++ = (ch), *p = '\0')
 

Typedefs

typedef struct ArrayIteratorData ArrayIteratorData
 
typedef struct generate_subscripts_fctx generate_subscripts_fctx
 

Enumerations

enum  ArrayParseState {
  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
}
 

Functions

static bool array_isspace (char ch)
 
static int ArrayCount (const char *str, int *dim, char typdelim)
 
static void ReadArrayStr (char *arrayStr, const char *origStr, int nitems, int ndim, int *dim, FmgrInfo *inputproc, Oid typioparam, int32 typmod, char typdelim, int typlen, bool typbyval, char typalign, Datum *values, bool *nulls, bool *hasnulls, int32 *nbytes)
 
static void ReadArrayBinary (StringInfo buf, int nitems, FmgrInfo *receiveproc, Oid typioparam, int32 typmod, int typlen, bool typbyval, char typalign, Datum *values, bool *nulls, bool *hasnulls, int32 *nbytes)
 
static Datum array_get_element_expanded (Datum arraydatum, int nSubscripts, int *indx, int arraytyplen, int elmlen, bool elmbyval, char elmalign, bool *isNull)
 
static Datum array_set_element_expanded (Datum arraydatum, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
 
static bool array_get_isnull (const bits8 *nullbitmap, int offset)
 
static void array_set_isnull (bits8 *nullbitmap, int offset, bool isNull)
 
static Datum ArrayCast (char *value, bool byval, int len)
 
static int ArrayCastAndSet (Datum src, int typlen, bool typbyval, char typalign, char *dest)
 
static char * array_seek (char *ptr, int offset, bits8 *nullbitmap, int nitems, 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)
 
static int array_slice_size (char *arraydataptr, bits8 *arraynullsptr, int ndim, int *dim, int *lb, int *st, int *endp, int typlen, bool typbyval, char typalign)
 
static void array_extract_slice (ArrayType *newarray, int ndim, int *dim, int *lb, char *arraydataptr, bits8 *arraynullsptr, int *st, int *endp, int typlen, bool typbyval, char typalign)
 
static void array_insert_slice (ArrayType *destArray, ArrayType *origArray, ArrayType *srcArray, int ndim, int *dim, int *lb, int *st, int *endp, int typlen, bool typbyval, char typalign)
 
static int array_cmp (FunctionCallInfo fcinfo)
 
static ArrayTypecreate_array_envelope (int ndims, int *dimv, int *lbsv, int nbytes, Oid elmtype, int dataoffset)
 
static ArrayTypearray_fill_internal (ArrayType *dims, ArrayType *lbs, Datum value, bool isnull, Oid elmtype, FunctionCallInfo fcinfo)
 
static ArrayTypearray_replace_internal (ArrayType *array, Datum search, bool search_isnull, Datum replace, bool replace_isnull, bool remove, Oid collation, FunctionCallInfo fcinfo)
 
static int width_bucket_array_float8 (Datum operand, ArrayType *thresholds)
 
static int width_bucket_array_fixed (Datum operand, ArrayType *thresholds, Oid collation, TypeCacheEntry *typentry)
 
static int width_bucket_array_variable (Datum operand, ArrayType *thresholds, Oid collation, TypeCacheEntry *typentry)
 
Datum array_in (PG_FUNCTION_ARGS)
 
void CopyArrayEls (ArrayType *array, Datum *values, bool *nulls, int nitems, int typlen, bool typbyval, char typalign, bool freedata)
 
Datum array_out (PG_FUNCTION_ARGS)
 
Datum array_recv (PG_FUNCTION_ARGS)
 
Datum array_send (PG_FUNCTION_ARGS)
 
Datum array_ndims (PG_FUNCTION_ARGS)
 
Datum array_dims (PG_FUNCTION_ARGS)
 
Datum array_lower (PG_FUNCTION_ARGS)
 
Datum array_upper (PG_FUNCTION_ARGS)
 
Datum array_length (PG_FUNCTION_ARGS)
 
Datum array_cardinality (PG_FUNCTION_ARGS)
 
Datum array_get_element (Datum arraydatum, int nSubscripts, int *indx, int arraytyplen, int elmlen, bool elmbyval, char elmalign, bool *isNull)
 
Datum array_get_slice (Datum arraydatum, int nSubscripts, int *upperIndx, int *lowerIndx, bool *upperProvided, bool *lowerProvided, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
 
Datum array_set_element (Datum arraydatum, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
 
Datum array_set_slice (Datum arraydatum, int nSubscripts, int *upperIndx, int *lowerIndx, bool *upperProvided, bool *lowerProvided, Datum srcArrayDatum, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
 
Datum array_ref (ArrayType *array, int nSubscripts, int *indx, int arraytyplen, int elmlen, bool elmbyval, char elmalign, bool *isNull)
 
ArrayTypearray_set (ArrayType *array, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
 
Datum array_map (Datum arrayd, ExprState *exprstate, ExprContext *econtext, Oid retType, ArrayMapState *amstate)
 
ArrayTypeconstruct_array (Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
 
ArrayTypeconstruct_md_array (Datum *elems, bool *nulls, int ndims, int *dims, int *lbs, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
 
ArrayTypeconstruct_empty_array (Oid elmtype)
 
ExpandedArrayHeaderconstruct_empty_expanded_array (Oid element_type, MemoryContext parentcontext, ArrayMetaState *metacache)
 
void deconstruct_array (ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
 
bool array_contains_nulls (ArrayType *array)
 
Datum array_eq (PG_FUNCTION_ARGS)
 
Datum array_ne (PG_FUNCTION_ARGS)
 
Datum array_lt (PG_FUNCTION_ARGS)
 
Datum array_gt (PG_FUNCTION_ARGS)
 
Datum array_le (PG_FUNCTION_ARGS)
 
Datum array_ge (PG_FUNCTION_ARGS)
 
Datum btarraycmp (PG_FUNCTION_ARGS)
 
Datum hash_array (PG_FUNCTION_ARGS)
 
Datum hash_array_extended (PG_FUNCTION_ARGS)
 
static bool array_contain_compare (AnyArrayType *array1, AnyArrayType *array2, Oid collation, bool matchall, void **fn_extra)
 
Datum arrayoverlap (PG_FUNCTION_ARGS)
 
Datum arraycontains (PG_FUNCTION_ARGS)
 
Datum arraycontained (PG_FUNCTION_ARGS)
 
ArrayIterator array_create_iterator (ArrayType *arr, int slice_ndim, ArrayMetaState *mstate)
 
bool array_iterate (ArrayIterator iterator, Datum *value, bool *isnull)
 
void array_free_iterator (ArrayIterator iterator)
 
void array_bitmap_copy (bits8 *destbitmap, int destoffset, const bits8 *srcbitmap, int srcoffset, int nitems)
 
ArrayBuildStateinitArrayResult (Oid element_type, MemoryContext rcontext, bool subcontext)
 
ArrayBuildStateaccumArrayResult (ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
 
Datum makeArrayResult (ArrayBuildState *astate, MemoryContext rcontext)
 
Datum makeMdArrayResult (ArrayBuildState *astate, int ndims, int *dims, int *lbs, MemoryContext rcontext, bool release)
 
ArrayBuildStateArrinitArrayResultArr (Oid array_type, Oid element_type, MemoryContext rcontext, bool subcontext)
 
ArrayBuildStateArraccumArrayResultArr (ArrayBuildStateArr *astate, Datum dvalue, bool disnull, Oid array_type, MemoryContext rcontext)
 
Datum makeArrayResultArr (ArrayBuildStateArr *astate, MemoryContext rcontext, bool release)
 
ArrayBuildStateAnyinitArrayResultAny (Oid input_type, MemoryContext rcontext, bool subcontext)
 
ArrayBuildStateAnyaccumArrayResultAny (ArrayBuildStateAny *astate, Datum dvalue, bool disnull, Oid input_type, MemoryContext rcontext)
 
Datum makeArrayResultAny (ArrayBuildStateAny *astate, MemoryContext rcontext, bool release)
 
Datum array_larger (PG_FUNCTION_ARGS)
 
Datum array_smaller (PG_FUNCTION_ARGS)
 
Datum generate_subscripts (PG_FUNCTION_ARGS)
 
Datum generate_subscripts_nodir (PG_FUNCTION_ARGS)
 
Datum array_fill_with_lower_bounds (PG_FUNCTION_ARGS)
 
Datum array_fill (PG_FUNCTION_ARGS)
 
Datum array_unnest (PG_FUNCTION_ARGS)
 
Datum array_unnest_support (PG_FUNCTION_ARGS)
 
Datum array_remove (PG_FUNCTION_ARGS)
 
Datum array_replace (PG_FUNCTION_ARGS)
 
Datum width_bucket_array (PG_FUNCTION_ARGS)
 

Variables

bool Array_nulls = true
 

Macro Definition Documentation

◆ AARR_FREE_IF_COPY

#define AARR_FREE_IF_COPY (   array,
 
)
Value:
do { \
PG_FREE_IF_COPY(array, n); \
} while (0)
#define VARATT_IS_EXPANDED_HEADER(PTR)

Definition at line 48 of file arrayfuncs.c.

Referenced by array_cmp(), array_eq(), arraycontained(), arraycontains(), arrayoverlap(), hash_array(), and hash_array_extended().

◆ APPENDCHAR

#define APPENDCHAR (   ch)    (*p++ = (ch), *p = '\0')

Referenced by array_out().

◆ APPENDSTR

#define APPENDSTR (   str)    (strcpy(p, (str)), p += strlen(p))

Referenced by array_out().

◆ ASSGN

#define ASSGN   "="

Definition at line 46 of file arrayfuncs.c.

Referenced by array_in(), and array_out().

Typedef Documentation

◆ ArrayIteratorData

◆ generate_subscripts_fctx

Enumeration Type Documentation

◆ ArrayParseState

Enumerator
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 

Definition at line 54 of file arrayfuncs.c.

Function Documentation

◆ accumArrayResult()

ArrayBuildState* accumArrayResult ( ArrayBuildState astate,
Datum  dvalue,
bool  disnull,
Oid  element_type,
MemoryContext  rcontext 
)

Definition at line 5080 of file arrayfuncs.c.

References ArrayBuildState::alen, Assert, datumCopy(), ArrayBuildState::dnulls, ArrayBuildState::dvalues, ArrayBuildState::element_type, initArrayResult(), ArrayBuildState::mcontext, MemoryContextSwitchTo(), ArrayBuildState::nelems, PG_DETOAST_DATUM_COPY, PointerGetDatum, repalloc(), ArrayBuildState::typbyval, and ArrayBuildState::typlen.

Referenced by accumArrayResultAny(), array_agg_transfn(), array_positions(), array_to_datum_internal(), dblink_get_connections(), get_altertable_subcmdtypes(), optionListToArray(), parse_ident(), pg_stats_ext_mcvlist_items(), populate_array_element(), regexp_split_to_array(), SPI_sql_row_to_xmlelement(), split_text_accum_result(), transformRelOptions(), and tuple_data_split_internal().

5084 {
5085  MemoryContext oldcontext;
5086 
5087  if (astate == NULL)
5088  {
5089  /* First time through --- initialize */
5090  astate = initArrayResult(element_type, rcontext, true);
5091  }
5092  else
5093  {
5094  Assert(astate->element_type == element_type);
5095  }
5096 
5097  oldcontext = MemoryContextSwitchTo(astate->mcontext);
5098 
5099  /* enlarge dvalues[]/dnulls[] if needed */
5100  if (astate->nelems >= astate->alen)
5101  {
5102  astate->alen *= 2;
5103  astate->dvalues = (Datum *)
5104  repalloc(astate->dvalues, astate->alen * sizeof(Datum));
5105  astate->dnulls = (bool *)
5106  repalloc(astate->dnulls, astate->alen * sizeof(bool));
5107  }
5108 
5109  /*
5110  * Ensure pass-by-ref stuff is copied into mcontext; and detoast it too if
5111  * it's varlena. (You might think that detoasting is not needed here
5112  * because construct_md_array can detoast the array elements later.
5113  * However, we must not let construct_md_array modify the ArrayBuildState
5114  * because that would mean array_agg_finalfn damages its input, which is
5115  * verboten. Also, this way frequently saves one copying step.)
5116  */
5117  if (!disnull && !astate->typbyval)
5118  {
5119  if (astate->typlen == -1)
5120  dvalue = PointerGetDatum(PG_DETOAST_DATUM_COPY(dvalue));
5121  else
5122  dvalue = datumCopy(dvalue, astate->typbyval, astate->typlen);
5123  }
5124 
5125  astate->dvalues[astate->nelems] = dvalue;
5126  astate->dnulls[astate->nelems] = disnull;
5127  astate->nelems++;
5128 
5129  MemoryContextSwitchTo(oldcontext);
5130 
5131  return astate;
5132 }
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
ArrayBuildState * initArrayResult(Oid element_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5041
#define PointerGetDatum(X)
Definition: postgres.h:556
Datum * dvalues
Definition: array.h:178
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
bool typbyval
Definition: array.h:184
Oid element_type
Definition: array.h:182
bool * dnulls
Definition: array.h:179
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
uintptr_t Datum
Definition: postgres.h:367
#define Assert(condition)
Definition: c.h:746
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1070
MemoryContext mcontext
Definition: array.h:177
int16 typlen
Definition: array.h:183

◆ accumArrayResultAny()

ArrayBuildStateAny* accumArrayResultAny ( ArrayBuildStateAny astate,
Datum  dvalue,
bool  disnull,
Oid  input_type,
MemoryContext  rcontext 
)

Definition at line 5547 of file arrayfuncs.c.

References accumArrayResult(), accumArrayResultArr(), ArrayBuildStateAny::arraystate, initArrayResultAny(), and ArrayBuildStateAny::scalarstate.

Referenced by ExecScanSubPlan(), and ExecSetParamPlan().

5551 {
5552  if (astate == NULL)
5553  astate = initArrayResultAny(input_type, rcontext, true);
5554 
5555  if (astate->scalarstate)
5556  (void) accumArrayResult(astate->scalarstate,
5557  dvalue, disnull,
5558  input_type, rcontext);
5559  else
5560  (void) accumArrayResultArr(astate->arraystate,
5561  dvalue, disnull,
5562  input_type, rcontext);
5563 
5564  return astate;
5565 }
ArrayBuildStateAny * initArrayResultAny(Oid input_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5502
ArrayBuildState * scalarstate
Definition: array.h:217
ArrayBuildStateArr * accumArrayResultArr(ArrayBuildStateArr *astate, Datum dvalue, bool disnull, Oid array_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5274
ArrayBuildStateArr * arraystate
Definition: array.h:218
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5080

◆ accumArrayResultArr()

ArrayBuildStateArr* accumArrayResultArr ( ArrayBuildStateArr astate,
Datum  dvalue,
bool  disnull,
Oid  array_type,
MemoryContext  rcontext 
)

Definition at line 5274 of file arrayfuncs.c.

References ArrayBuildStateArr::abytes, ArrayBuildStateArr::aitems, arg, ARR_DATA_OFFSET, ARR_DATA_PTR, ARR_DIMS, ARR_HASNULL, ARR_LBOUND, ARR_NDIM, ARR_NULLBITMAP, ARR_SIZE, array_bitmap_copy(), ArrayBuildStateArr::array_type, ArrayGetNItems(), Assert, ArrayBuildStateArr::data, DatumGetArrayTypeP, DatumGetPointer, ArrayBuildStateArr::dims, ereport, errcode(), errmsg(), ERROR, i, initArrayResultArr(), InvalidOid, ArrayBuildStateArr::lbs, Max, MAXDIM, ArrayBuildStateArr::mcontext, MemoryContextSwitchTo(), ArrayBuildStateArr::nbytes, ArrayBuildStateArr::ndims, ArrayIteratorData::nitems, ArrayBuildStateArr::nitems, ArrayBuildStateArr::nullbitmap, palloc(), pfree(), pg_nextpower2_32(), and repalloc().

Referenced by accumArrayResultAny(), and array_agg_array_transfn().

5278 {
5279  ArrayType *arg;
5280  MemoryContext oldcontext;
5281  int *dims,
5282  *lbs,
5283  ndims,
5284  nitems,
5285  ndatabytes;
5286  char *data;
5287  int i;
5288 
5289  /*
5290  * We disallow accumulating null subarrays. Another plausible definition
5291  * is to ignore them, but callers that want that can just skip calling
5292  * this function.
5293  */
5294  if (disnull)
5295  ereport(ERROR,
5296  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5297  errmsg("cannot accumulate null arrays")));
5298 
5299  /* Detoast input array in caller's context */
5300  arg = DatumGetArrayTypeP(dvalue);
5301 
5302  if (astate == NULL)
5303  astate = initArrayResultArr(array_type, InvalidOid, rcontext, true);
5304  else
5305  Assert(astate->array_type == array_type);
5306 
5307  oldcontext = MemoryContextSwitchTo(astate->mcontext);
5308 
5309  /* Collect this input's dimensions */
5310  ndims = ARR_NDIM(arg);
5311  dims = ARR_DIMS(arg);
5312  lbs = ARR_LBOUND(arg);
5313  data = ARR_DATA_PTR(arg);
5314  nitems = ArrayGetNItems(ndims, dims);
5315  ndatabytes = ARR_SIZE(arg) - ARR_DATA_OFFSET(arg);
5316 
5317  if (astate->ndims == 0)
5318  {
5319  /* First input; check/save the dimensionality info */
5320 
5321  /* Should we allow empty inputs and just produce an empty output? */
5322  if (ndims == 0)
5323  ereport(ERROR,
5324  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
5325  errmsg("cannot accumulate empty arrays")));
5326  if (ndims + 1 > MAXDIM)
5327  ereport(ERROR,
5328  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5329  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5330  ndims + 1, MAXDIM)));
5331 
5332  /*
5333  * The output array will have n+1 dimensions, with the ones after the
5334  * first matching the input's dimensions.
5335  */
5336  astate->ndims = ndims + 1;
5337  astate->dims[0] = 0;
5338  memcpy(&astate->dims[1], dims, ndims * sizeof(int));
5339  astate->lbs[0] = 1;
5340  memcpy(&astate->lbs[1], lbs, ndims * sizeof(int));
5341 
5342  /* Allocate at least enough data space for this item */
5343  astate->abytes = pg_nextpower2_32(Max(1024, ndatabytes + 1));
5344  astate->data = (char *) palloc(astate->abytes);
5345  }
5346  else
5347  {
5348  /* Second or later input: must match first input's dimensionality */
5349  if (astate->ndims != ndims + 1)
5350  ereport(ERROR,
5351  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
5352  errmsg("cannot accumulate arrays of different dimensionality")));
5353  for (i = 0; i < ndims; i++)
5354  {
5355  if (astate->dims[i + 1] != dims[i] || astate->lbs[i + 1] != lbs[i])
5356  ereport(ERROR,
5357  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
5358  errmsg("cannot accumulate arrays of different dimensionality")));
5359  }
5360 
5361  /* Enlarge data space if needed */
5362  if (astate->nbytes + ndatabytes > astate->abytes)
5363  {
5364  astate->abytes = Max(astate->abytes * 2,
5365  astate->nbytes + ndatabytes);
5366  astate->data = (char *) repalloc(astate->data, astate->abytes);
5367  }
5368  }
5369 
5370  /*
5371  * Copy the data portion of the sub-array. Note we assume that the
5372  * advertised data length of the sub-array is properly aligned. We do not
5373  * have to worry about detoasting elements since whatever's in the
5374  * sub-array should be OK already.
5375  */
5376  memcpy(astate->data + astate->nbytes, data, ndatabytes);
5377  astate->nbytes += ndatabytes;
5378 
5379  /* Deal with null bitmap if needed */
5380  if (astate->nullbitmap || ARR_HASNULL(arg))
5381  {
5382  int newnitems = astate->nitems + nitems;
5383 
5384  if (astate->nullbitmap == NULL)
5385  {
5386  /*
5387  * First input with nulls; we must retrospectively handle any
5388  * previous inputs by marking all their items non-null.
5389  */
5390  astate->aitems = pg_nextpower2_32(Max(256, newnitems + 1));
5391  astate->nullbitmap = (bits8 *) palloc((astate->aitems + 7) / 8);
5392  array_bitmap_copy(astate->nullbitmap, 0,
5393  NULL, 0,
5394  astate->nitems);
5395  }
5396  else if (newnitems > astate->aitems)
5397  {
5398  astate->aitems = Max(astate->aitems * 2, newnitems);
5399  astate->nullbitmap = (bits8 *)
5400  repalloc(astate->nullbitmap, (astate->aitems + 7) / 8);
5401  }
5402  array_bitmap_copy(astate->nullbitmap, astate->nitems,
5403  ARR_NULLBITMAP(arg), 0,
5404  nitems);
5405  }
5406 
5407  astate->nitems += nitems;
5408  astate->dims[0] += 1;
5409 
5410  MemoryContextSwitchTo(oldcontext);
5411 
5412  /* Release detoasted copy if any */
5413  if ((Pointer) arg != DatumGetPointer(dvalue))
5414  pfree(arg);
5415 
5416  return astate;
5417 }
#define ARR_SIZE(a)
Definition: array.h:277
#define MAXDIM
Definition: c.h:543
void array_bitmap_copy(bits8 *destbitmap, int destoffset, const bits8 *srcbitmap, int srcoffset, int nitems)
Definition: arrayfuncs.c:4714
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:610
ArrayBuildStateArr * initArrayResultArr(Oid array_type, Oid element_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5228
#define ARR_DATA_OFFSET(a)
Definition: array.h:304
#define ARR_LBOUND(a)
Definition: array.h:284
bits8 * nullbitmap
Definition: array.h:197
void pfree(void *pointer)
Definition: mcxt.c:1057
char * Pointer
Definition: c.h:352
#define ERROR
Definition: elog.h:43
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:146
#define ARR_HASNULL(a)
Definition: array.h:279
uint8 bits8
Definition: c.h:382
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
int lbs[MAXDIM]
Definition: array.h:204
#define Max(x, y)
Definition: c.h:922
#define Assert(condition)
Definition: c.h:746
#define ARR_NDIM(a)
Definition: array.h:278
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1070
#define DatumGetPointer(X)
Definition: postgres.h:549
int dims[MAXDIM]
Definition: array.h:203
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
int i
void * arg
#define ARR_NULLBITMAP(a)
Definition: array.h:288
MemoryContext mcontext
Definition: array.h:195
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ array_bitmap_copy()

void array_bitmap_copy ( bits8 destbitmap,
int  destoffset,
const bits8 srcbitmap,
int  srcoffset,
int  nitems 
)

Definition at line 4714 of file arrayfuncs.c.

References Assert.

Referenced by accumArrayResultArr(), array_cat(), array_extract_slice(), array_insert_slice(), array_set_element(), array_set_slice(), ExecEvalArrayExpr(), and makeArrayResultArr().

4717 {
4718  int destbitmask,
4719  destbitval,
4720  srcbitmask,
4721  srcbitval;
4722 
4723  Assert(destbitmap);
4724  if (nitems <= 0)
4725  return; /* don't risk fetch off end of memory */
4726  destbitmap += destoffset / 8;
4727  destbitmask = 1 << (destoffset % 8);
4728  destbitval = *destbitmap;
4729  if (srcbitmap)
4730  {
4731  srcbitmap += srcoffset / 8;
4732  srcbitmask = 1 << (srcoffset % 8);
4733  srcbitval = *srcbitmap;
4734  while (nitems-- > 0)
4735  {
4736  if (srcbitval & srcbitmask)
4737  destbitval |= destbitmask;
4738  else
4739  destbitval &= ~destbitmask;
4740  destbitmask <<= 1;
4741  if (destbitmask == 0x100)
4742  {
4743  *destbitmap++ = destbitval;
4744  destbitmask = 1;
4745  if (nitems > 0)
4746  destbitval = *destbitmap;
4747  }
4748  srcbitmask <<= 1;
4749  if (srcbitmask == 0x100)
4750  {
4751  srcbitmap++;
4752  srcbitmask = 1;
4753  if (nitems > 0)
4754  srcbitval = *srcbitmap;
4755  }
4756  }
4757  if (destbitmask != 1)
4758  *destbitmap = destbitval;
4759  }
4760  else
4761  {
4762  while (nitems-- > 0)
4763  {
4764  destbitval |= destbitmask;
4765  destbitmask <<= 1;
4766  if (destbitmask == 0x100)
4767  {
4768  *destbitmap++ = destbitval;
4769  destbitmask = 1;
4770  if (nitems > 0)
4771  destbitval = *destbitmap;
4772  }
4773  }
4774  if (destbitmask != 1)
4775  *destbitmap = destbitval;
4776  }
4777 }
#define Assert(condition)
Definition: c.h:746

◆ array_cardinality()

Datum array_cardinality ( PG_FUNCTION_ARGS  )

Definition at line 1811 of file arrayfuncs.c.

References AARR_DIMS, AARR_NDIM, ArrayGetNItems(), PG_GETARG_ANY_ARRAY_P, and PG_RETURN_INT32.

1812 {
1814 
1816 }
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:262
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define PG_RETURN_INT32(x)
Definition: fmgr.h:353
#define AARR_DIMS(a)
Definition: array.h:326
#define AARR_NDIM(a)
Definition: array.h:316

◆ array_cmp()

static int array_cmp ( FunctionCallInfo  fcinfo)
static

Definition at line 3768 of file arrayfuncs.c.

References AARR_DIMS, AARR_ELEMTYPE, AARR_FREE_IF_COPY, AARR_LBOUND, AARR_NDIM, array_iter_next(), array_iter_setup(), ArrayGetNItems(), Assert, TypeCacheEntry::cmp_proc_finfo, DatumGetInt32, ereport, errcode(), errmsg(), ERROR, FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_extra, FmgrInfo::fn_oid, format_type_be(), FunctionCallInvoke, i, InitFunctionCallInfoData, LOCAL_FCINFO, lookup_type_cache(), Min, OidIsValid, PG_GET_COLLATION, PG_GETARG_ANY_ARRAY_P, TypeCacheEntry::typalign, ArrayIteratorData::typalign, TypeCacheEntry::typbyval, ArrayIteratorData::typbyval, TypeCacheEntry::type_id, TYPECACHE_CMP_PROC_FINFO, TypeCacheEntry::typlen, and ArrayIteratorData::typlen.

Referenced by array_ge(), array_gt(), array_larger(), array_le(), array_lt(), array_smaller(), and btarraycmp().

3769 {
3770  LOCAL_FCINFO(locfcinfo, 2);
3771  AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
3772  AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
3773  Oid collation = PG_GET_COLLATION();
3774  int ndims1 = AARR_NDIM(array1);
3775  int ndims2 = AARR_NDIM(array2);
3776  int *dims1 = AARR_DIMS(array1);
3777  int *dims2 = AARR_DIMS(array2);
3778  int nitems1 = ArrayGetNItems(ndims1, dims1);
3779  int nitems2 = ArrayGetNItems(ndims2, dims2);
3780  Oid element_type = AARR_ELEMTYPE(array1);
3781  int result = 0;
3782  TypeCacheEntry *typentry;
3783  int typlen;
3784  bool typbyval;
3785  char typalign;
3786  int min_nitems;
3787  array_iter it1;
3788  array_iter it2;
3789  int i;
3790 
3791  if (element_type != AARR_ELEMTYPE(array2))
3792  ereport(ERROR,
3793  (errcode(ERRCODE_DATATYPE_MISMATCH),
3794  errmsg("cannot compare arrays of different element types")));
3795 
3796  /*
3797  * We arrange to look up the comparison function only once per series of
3798  * calls, assuming the element type doesn't change underneath us. The
3799  * typcache is used so that we have no memory leakage when being used as
3800  * an index support function.
3801  */
3802  typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
3803  if (typentry == NULL ||
3804  typentry->type_id != element_type)
3805  {
3806  typentry = lookup_type_cache(element_type,
3808  if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
3809  ereport(ERROR,
3810  (errcode(ERRCODE_UNDEFINED_FUNCTION),
3811  errmsg("could not identify a comparison function for type %s",
3812  format_type_be(element_type))));
3813  fcinfo->flinfo->fn_extra = (void *) typentry;
3814  }
3815  typlen = typentry->typlen;
3816  typbyval = typentry->typbyval;
3817  typalign = typentry->typalign;
3818 
3819  /*
3820  * apply the operator to each pair of array elements.
3821  */
3822  InitFunctionCallInfoData(*locfcinfo, &typentry->cmp_proc_finfo, 2,
3823  collation, NULL, NULL);
3824 
3825  /* Loop over source data */
3826  min_nitems = Min(nitems1, nitems2);
3827  array_iter_setup(&it1, array1);
3828  array_iter_setup(&it2, array2);
3829 
3830  for (i = 0; i < min_nitems; i++)
3831  {
3832  Datum elt1;
3833  Datum elt2;
3834  bool isnull1;
3835  bool isnull2;
3836  int32 cmpresult;
3837 
3838  /* Get elements, checking for NULL */
3839  elt1 = array_iter_next(&it1, &isnull1, i, typlen, typbyval, typalign);
3840  elt2 = array_iter_next(&it2, &isnull2, i, typlen, typbyval, typalign);
3841 
3842  /*
3843  * We consider two NULLs equal; NULL > not-NULL.
3844  */
3845  if (isnull1 && isnull2)
3846  continue;
3847  if (isnull1)
3848  {
3849  /* arg1 is greater than arg2 */
3850  result = 1;
3851  break;
3852  }
3853  if (isnull2)
3854  {
3855  /* arg1 is less than arg2 */
3856  result = -1;
3857  break;
3858  }
3859 
3860  /* Compare the pair of elements */
3861  locfcinfo->args[0].value = elt1;
3862  locfcinfo->args[0].isnull = false;
3863  locfcinfo->args[1].value = elt2;
3864  locfcinfo->args[1].isnull = false;
3865  cmpresult = DatumGetInt32(FunctionCallInvoke(locfcinfo));
3866 
3867  /* We don't expect comparison support functions to return null */
3868  Assert(!locfcinfo->isnull);
3869 
3870  if (cmpresult == 0)
3871  continue; /* equal */
3872 
3873  if (cmpresult < 0)
3874  {
3875  /* arg1 is less than arg2 */
3876  result = -1;
3877  break;
3878  }
3879  else
3880  {
3881  /* arg1 is greater than arg2 */
3882  result = 1;
3883  break;
3884  }
3885  }
3886 
3887  /*
3888  * If arrays contain same data (up to end of shorter one), apply
3889  * additional rules to sort by dimensionality. The relative significance
3890  * of the different bits of information is historical; mainly we just care
3891  * that we don't say "equal" for arrays of different dimensionality.
3892  */
3893  if (result == 0)
3894  {
3895  if (nitems1 != nitems2)
3896  result = (nitems1 < nitems2) ? -1 : 1;
3897  else if (ndims1 != ndims2)
3898  result = (ndims1 < ndims2) ? -1 : 1;
3899  else
3900  {
3901  for (i = 0; i < ndims1; i++)
3902  {
3903  if (dims1[i] != dims2[i])
3904  {
3905  result = (dims1[i] < dims2[i]) ? -1 : 1;
3906  break;
3907  }
3908  }
3909  if (result == 0)
3910  {
3911  int *lbound1 = AARR_LBOUND(array1);
3912  int *lbound2 = AARR_LBOUND(array2);
3913 
3914  for (i = 0; i < ndims1; i++)
3915  {
3916  if (lbound1[i] != lbound2[i])
3917  {
3918  result = (lbound1[i] < lbound2[i]) ? -1 : 1;
3919  break;
3920  }
3921  }
3922  }
3923  }
3924  }
3925 
3926  /* Avoid leaking memory when handed toasted input. */
3927  AARR_FREE_IF_COPY(array1, 0);
3928  AARR_FREE_IF_COPY(array2, 1);
3929 
3930  return result;
3931 }
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:262
#define DatumGetInt32(X)
Definition: postgres.h:472
static Datum array_iter_next(array_iter *it, bool *isnull, int i, int elmlen, bool elmbyval, char elmalign)
Definition: arrayaccess.h:81
#define Min(x, y)
Definition: c.h:928
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
int16 typlen
Definition: typcache.h:39
bool typbyval
Definition: typcache.h:40
#define OidIsValid(objectId)
Definition: c.h:652
#define PG_GET_COLLATION()
Definition: fmgr.h:198
signed int int32
Definition: c.h:363
FmgrInfo cmp_proc_finfo
Definition: typcache.h:75
char typalign
Definition: pg_type.h:170
#define ERROR
Definition: elog.h:43
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
static void array_iter_setup(array_iter *it, AnyArrayType *a)
Definition: arrayaccess.h:49
uintptr_t Datum
Definition: postgres.h:367
FmgrInfo * flinfo
Definition: fmgr.h:87
#define AARR_DIMS(a)
Definition: array.h:326
#define AARR_ELEMTYPE(a)
Definition: array.h:323
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:331
Oid fn_oid
Definition: fmgr.h:59
#define ereport(elevel,...)
Definition: elog.h:144
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define AARR_LBOUND(a)
Definition: array.h:329
#define Assert(condition)
Definition: c.h:746
#define AARR_NDIM(a)
Definition: array.h:316
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
#define AARR_FREE_IF_COPY(array, n)
Definition: arrayfuncs.c:48
void * fn_extra
Definition: fmgr.h:64
char typalign
Definition: typcache.h:41
int errmsg(const char *fmt,...)
Definition: elog.c:821
int i
#define TYPECACHE_CMP_PROC_FINFO
Definition: typcache.h:136

◆ array_contain_compare()

static bool array_contain_compare ( AnyArrayType array1,
AnyArrayType array2,
Oid  collation,
bool  matchall,
void **  fn_extra 
)
static

Definition at line 4129 of file arrayfuncs.c.

References AARR_DIMS, AARR_ELEMTYPE, AARR_NDIM, array_iter_next(), array_iter_setup(), ArrayGetNItems(), DatumGetBool, deconstruct_array(), deconstruct_expanded_array(), ExpandedArrayHeader::dnulls, ExpandedArrayHeader::dvalues, TypeCacheEntry::eq_opr_finfo, ereport, errcode(), errmsg(), ERROR, FmgrInfo::fn_oid, format_type_be(), FunctionCallInvoke, i, InitFunctionCallInfoData, LOCAL_FCINFO, lookup_type_cache(), ExpandedArrayHeader::nelems, OidIsValid, TypeCacheEntry::typalign, ArrayIteratorData::typalign, TypeCacheEntry::typbyval, ArrayIteratorData::typbyval, TypeCacheEntry::type_id, TYPECACHE_EQ_OPR_FINFO, TypeCacheEntry::typlen, ArrayIteratorData::typlen, VARATT_IS_EXPANDED_HEADER, and AnyArrayType::xpn.

Referenced by arraycontained(), arraycontains(), and arrayoverlap().

4131 {
4132  LOCAL_FCINFO(locfcinfo, 2);
4133  bool result = matchall;
4134  Oid element_type = AARR_ELEMTYPE(array1);
4135  TypeCacheEntry *typentry;
4136  int nelems1;
4137  Datum *values2;
4138  bool *nulls2;
4139  int nelems2;
4140  int typlen;
4141  bool typbyval;
4142  char typalign;
4143  int i;
4144  int j;
4145  array_iter it1;
4146 
4147  if (element_type != AARR_ELEMTYPE(array2))
4148  ereport(ERROR,
4149  (errcode(ERRCODE_DATATYPE_MISMATCH),
4150  errmsg("cannot compare arrays of different element types")));
4151 
4152  /*
4153  * We arrange to look up the equality function only once per series of
4154  * calls, assuming the element type doesn't change underneath us. The
4155  * typcache is used so that we have no memory leakage when being used as
4156  * an index support function.
4157  */
4158  typentry = (TypeCacheEntry *) *fn_extra;
4159  if (typentry == NULL ||
4160  typentry->type_id != element_type)
4161  {
4162  typentry = lookup_type_cache(element_type,
4164  if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
4165  ereport(ERROR,
4166  (errcode(ERRCODE_UNDEFINED_FUNCTION),
4167  errmsg("could not identify an equality operator for type %s",
4168  format_type_be(element_type))));
4169  *fn_extra = (void *) typentry;
4170  }
4171  typlen = typentry->typlen;
4172  typbyval = typentry->typbyval;
4173  typalign = typentry->typalign;
4174 
4175  /*
4176  * Since we probably will need to scan array2 multiple times, it's
4177  * worthwhile to use deconstruct_array on it. We scan array1 the hard way
4178  * however, since we very likely won't need to look at all of it.
4179  */
4180  if (VARATT_IS_EXPANDED_HEADER(array2))
4181  {
4182  /* This should be safe even if input is read-only */
4183  deconstruct_expanded_array(&(array2->xpn));
4184  values2 = array2->xpn.dvalues;
4185  nulls2 = array2->xpn.dnulls;
4186  nelems2 = array2->xpn.nelems;
4187  }
4188  else
4189  deconstruct_array((ArrayType *) array2,
4190  element_type, typlen, typbyval, typalign,
4191  &values2, &nulls2, &nelems2);
4192 
4193  /*
4194  * Apply the comparison operator to each pair of array elements.
4195  */
4196  InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
4197  collation, NULL, NULL);
4198 
4199  /* Loop over source data */
4200  nelems1 = ArrayGetNItems(AARR_NDIM(array1), AARR_DIMS(array1));
4201  array_iter_setup(&it1, array1);
4202 
4203  for (i = 0; i < nelems1; i++)
4204  {
4205  Datum elt1;
4206  bool isnull1;
4207 
4208  /* Get element, checking for NULL */
4209  elt1 = array_iter_next(&it1, &isnull1, i, typlen, typbyval, typalign);
4210 
4211  /*
4212  * We assume that the comparison operator is strict, so a NULL can't
4213  * match anything. XXX this diverges from the "NULL=NULL" behavior of
4214  * array_eq, should we act like that?
4215  */
4216  if (isnull1)
4217  {
4218  if (matchall)
4219  {
4220  result = false;
4221  break;
4222  }
4223  continue;
4224  }
4225 
4226  for (j = 0; j < nelems2; j++)
4227  {
4228  Datum elt2 = values2[j];
4229  bool isnull2 = nulls2 ? nulls2[j] : false;
4230  bool oprresult;
4231 
4232  if (isnull2)
4233  continue; /* can't match */
4234 
4235  /*
4236  * Apply the operator to the element pair; treat NULL as false
4237  */
4238  locfcinfo->args[0].value = elt1;
4239  locfcinfo->args[0].isnull = false;
4240  locfcinfo->args[1].value = elt2;
4241  locfcinfo->args[1].isnull = false;
4242  locfcinfo->isnull = false;
4243  oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
4244  if (!locfcinfo->isnull && oprresult)
4245  break;
4246  }
4247 
4248  if (j < nelems2)
4249  {
4250  /* found a match for elt1 */
4251  if (!matchall)
4252  {
4253  result = true;
4254  break;
4255  }
4256  }
4257  else
4258  {
4259  /* no match for elt1 */
4260  if (matchall)
4261  {
4262  result = false;
4263  break;
4264  }
4265  }
4266  }
4267 
4268  return result;
4269 }
void deconstruct_expanded_array(ExpandedArrayHeader *eah)
static Datum array_iter_next(array_iter *it, bool *isnull, int i, int elmlen, bool elmbyval, char elmalign)
Definition: arrayaccess.h:81
#define TYPECACHE_EQ_OPR_FINFO
Definition: typcache.h:135
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
ExpandedArrayHeader xpn
Definition: array.h:168
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
Datum * dvalues
Definition: array.h:134
unsigned int Oid
Definition: postgres_ext.h:31
int16 typlen
Definition: typcache.h:39
bool typbyval
Definition: typcache.h:40
#define OidIsValid(objectId)
Definition: c.h:652
char typalign
Definition: pg_type.h:170
#define ERROR
Definition: elog.h:43
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
static void array_iter_setup(array_iter *it, AnyArrayType *a)
Definition: arrayaccess.h:49
#define DatumGetBool(X)
Definition: postgres.h:393
uintptr_t Datum
Definition: postgres.h:367
#define AARR_DIMS(a)
Definition: array.h:326
#define AARR_ELEMTYPE(a)
Definition: array.h:323
FmgrInfo eq_opr_finfo
Definition: typcache.h:74
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:331
Oid fn_oid
Definition: fmgr.h:59
#define ereport(elevel,...)
Definition: elog.h:144
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define AARR_NDIM(a)
Definition: array.h:316
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
#define VARATT_IS_EXPANDED_HEADER(PTR)
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3483
char typalign
Definition: typcache.h:41
int errmsg(const char *fmt,...)
Definition: elog.c:821
int i

◆ array_contains_nulls()

bool array_contains_nulls ( ArrayType array)

Definition at line 3550 of file arrayfuncs.c.

References ARR_DIMS, ARR_HASNULL, ARR_NDIM, ARR_NULLBITMAP, and ArrayGetNItems().

Referenced by _arrq_cons(), _lca(), _lt_q_regex(), _ltree_compress(), array_fill_internal(), array_iterator(), array_position_common(), array_positions(), ArrayGetIntegerTypmods(), arrq_cons(), cube_a_f8(), cube_a_f8_f8(), cube_subset(), get_jsonb_path_all(), get_path_all(), getWeights(), lt_q_regex(), pg_isolation_test_session_is_blocked(), pg_logical_slot_get_changes_guts(), sanity_check_tid_array(), and width_bucket_array().

3551 {
3552  int nelems;
3553  bits8 *bitmap;
3554  int bitmask;
3555 
3556  /* Easy answer if there's no null bitmap */
3557  if (!ARR_HASNULL(array))
3558  return false;
3559 
3560  nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
3561 
3562  bitmap = ARR_NULLBITMAP(array);
3563 
3564  /* check whole bytes of the bitmap byte-at-a-time */
3565  while (nelems >= 8)
3566  {
3567  if (*bitmap != 0xFF)
3568  return true;
3569  bitmap++;
3570  nelems -= 8;
3571  }
3572 
3573  /* check last partial byte */
3574  bitmask = 1;
3575  while (nelems > 0)
3576  {
3577  if ((*bitmap & bitmask) == 0)
3578  return true;
3579  bitmask <<= 1;
3580  nelems--;
3581  }
3582 
3583  return false;
3584 }
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_HASNULL(a)
Definition: array.h:279
uint8 bits8
Definition: c.h:382
#define ARR_NDIM(a)
Definition: array.h:278
#define ARR_NULLBITMAP(a)
Definition: array.h:288

◆ array_copy()

static int array_copy ( char *  destptr,
int  nitems,
char *  srcptr,
int  offset,
bits8 nullbitmap,
int  typlen,
bool  typbyval,
char  typalign 
)
static

Definition at line 4684 of file arrayfuncs.c.

References array_nelems_size().

Referenced by array_extract_slice(), and array_insert_slice().

4687 {
4688  int numbytes;
4689 
4690  numbytes = array_nelems_size(srcptr, offset, nullbitmap, nitems,
4691  typlen, typbyval, typalign);
4692  memcpy(destptr, srcptr, numbytes);
4693  return numbytes;
4694 }
char typalign
Definition: pg_type.h:170
static int array_nelems_size(char *ptr, int offset, bits8 *nullbitmap, int nitems, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4662

◆ array_create_iterator()

ArrayIterator array_create_iterator ( ArrayType arr,
int  slice_ndim,
ArrayMetaState mstate 
)

Definition at line 4345 of file arrayfuncs.c.

References ArrayIteratorData::arr, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_LBOUND, ARR_NDIM, ARR_NULLBITMAP, ArrayGetNItems(), Assert, ArrayIteratorData::current_item, ArrayIteratorData::data_ptr, ArrayMetaState::element_type, elog, ERROR, get_typlenbyvalalign(), ArrayIteratorData::nitems, ArrayIteratorData::nullbitmap, palloc(), palloc0(), PointerIsValid, ArrayIteratorData::slice_dims, ArrayIteratorData::slice_lbound, ArrayIteratorData::slice_len, ArrayIteratorData::slice_ndim, ArrayIteratorData::slice_nulls, ArrayIteratorData::slice_values, ArrayIteratorData::typalign, ArrayMetaState::typalign, ArrayIteratorData::typbyval, ArrayMetaState::typbyval, ArrayIteratorData::typlen, and ArrayMetaState::typlen.

Referenced by array_position_common(), array_positions(), and exec_stmt_foreach_a().

4346 {
4347  ArrayIterator iterator = palloc0(sizeof(ArrayIteratorData));
4348 
4349  /*
4350  * Sanity-check inputs --- caller should have got this right already
4351  */
4352  Assert(PointerIsValid(arr));
4353  if (slice_ndim < 0 || slice_ndim > ARR_NDIM(arr))
4354  elog(ERROR, "invalid arguments to array_create_iterator");
4355 
4356  /*
4357  * Remember basic info about the array and its element type
4358  */
4359  iterator->arr = arr;
4360  iterator->nullbitmap = ARR_NULLBITMAP(arr);
4361  iterator->nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
4362 
4363  if (mstate != NULL)
4364  {
4365  Assert(mstate->element_type == ARR_ELEMTYPE(arr));
4366 
4367  iterator->typlen = mstate->typlen;
4368  iterator->typbyval = mstate->typbyval;
4369  iterator->typalign = mstate->typalign;
4370  }
4371  else
4373  &iterator->typlen,
4374  &iterator->typbyval,
4375  &iterator->typalign);
4376 
4377  /*
4378  * Remember the slicing parameters.
4379  */
4380  iterator->slice_ndim = slice_ndim;
4381 
4382  if (slice_ndim > 0)
4383  {
4384  /*
4385  * Get pointers into the array's dims and lbound arrays to represent
4386  * the dims/lbound arrays of a slice. These are the same as the
4387  * rightmost N dimensions of the array.
4388  */
4389  iterator->slice_dims = ARR_DIMS(arr) + ARR_NDIM(arr) - slice_ndim;
4390  iterator->slice_lbound = ARR_LBOUND(arr) + ARR_NDIM(arr) - slice_ndim;
4391 
4392  /*
4393  * Compute number of elements in a slice.
4394  */
4395  iterator->slice_len = ArrayGetNItems(slice_ndim,
4396  iterator->slice_dims);
4397 
4398  /*
4399  * Create workspace for building sub-arrays.
4400  */
4401  iterator->slice_values = (Datum *)
4402  palloc(iterator->slice_len * sizeof(Datum));
4403  iterator->slice_nulls = (bool *)
4404  palloc(iterator->slice_len * sizeof(bool));
4405  }
4406 
4407  /*
4408  * Initialize our data pointer and linear element number. These will
4409  * advance through the array during array_iterate().
4410  */
4411  iterator->data_ptr = ARR_DATA_PTR(arr);
4412  iterator->current_item = 0;
4413 
4414  return iterator;
4415 }
bits8 * nullbitmap
Definition: arrayfuncs.c:72
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2159
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_LBOUND(a)
Definition: array.h:284
bool typbyval
Definition: array.h:228
bool * slice_nulls
Definition: arrayfuncs.c:84
#define ERROR
Definition: elog.h:43
Datum * slice_values
Definition: arrayfuncs.c:83
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
int16 typlen
Definition: array.h:227
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
#define Assert(condition)
Definition: c.h:746
#define ARR_NDIM(a)
Definition: array.h:278
char typalign
Definition: array.h:229
void * palloc(Size size)
Definition: mcxt.c:950
#define elog(elevel,...)
Definition: elog.h:214
Oid element_type
Definition: array.h:226
#define PointerIsValid(pointer)
Definition: c.h:640
#define ARR_ELEMTYPE(a)
Definition: array.h:280
#define ARR_NULLBITMAP(a)
Definition: array.h:288
ArrayType * arr
Definition: arrayfuncs.c:71

◆ array_dims()

Datum array_dims ( PG_FUNCTION_ARGS  )

Definition at line 1689 of file arrayfuncs.c.

References AARR_DIMS, AARR_LBOUND, AARR_NDIM, buf, cstring_to_text(), i, MAXDIM, PG_GETARG_ANY_ARRAY_P, PG_RETURN_NULL, PG_RETURN_TEXT_P, and sprintf.

1690 {
1692  char *p;
1693  int i;
1694  int *dimv,
1695  *lb;
1696 
1697  /*
1698  * 33 since we assume 15 digits per number + ':' +'[]'
1699  *
1700  * +1 for trailing null
1701  */
1702  char buf[MAXDIM * 33 + 1];
1703 
1704  /* Sanity check: does it look like an array at all? */
1705  if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
1706  PG_RETURN_NULL();
1707 
1708  dimv = AARR_DIMS(v);
1709  lb = AARR_LBOUND(v);
1710 
1711  p = buf;
1712  for (i = 0; i < AARR_NDIM(v); i++)
1713  {
1714  sprintf(p, "[%d:%d]", lb[i], dimv[i] + lb[i] - 1);
1715  p += strlen(p);
1716  }
1717 
1719 }
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:262
#define MAXDIM
Definition: c.h:543
#define sprintf
Definition: port.h:217
static char * buf
Definition: pg_test_fsync.c:68
#define AARR_DIMS(a)
Definition: array.h:326
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:370
text * cstring_to_text(const char *s)
Definition: varlena.c:188
#define AARR_LBOUND(a)
Definition: array.h:329
#define AARR_NDIM(a)
Definition: array.h:316
int i
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ array_eq()

Datum array_eq ( PG_FUNCTION_ARGS  )

Definition at line 3597 of file arrayfuncs.c.

References AARR_DIMS, AARR_ELEMTYPE, AARR_FREE_IF_COPY, AARR_LBOUND, AARR_NDIM, array_iter_next(), array_iter_setup(), ArrayGetNItems(), DatumGetBool, TypeCacheEntry::eq_opr_finfo, ereport, errcode(), errmsg(), ERROR, FmgrInfo::fn_oid, format_type_be(), FunctionCallInvoke, i, InitFunctionCallInfoData, LOCAL_FCINFO, lookup_type_cache(), ArrayIteratorData::nitems, OidIsValid, PG_GET_COLLATION, PG_GETARG_ANY_ARRAY_P, PG_RETURN_BOOL, TypeCacheEntry::typalign, ArrayIteratorData::typalign, TypeCacheEntry::typbyval, ArrayIteratorData::typbyval, TypeCacheEntry::type_id, TYPECACHE_EQ_OPR_FINFO, TypeCacheEntry::typlen, and ArrayIteratorData::typlen.

Referenced by array_ne(), and CompareOpclassOptions().

3598 {
3599  LOCAL_FCINFO(locfcinfo, 2);
3600  AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
3601  AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
3602  Oid collation = PG_GET_COLLATION();
3603  int ndims1 = AARR_NDIM(array1);
3604  int ndims2 = AARR_NDIM(array2);
3605  int *dims1 = AARR_DIMS(array1);
3606  int *dims2 = AARR_DIMS(array2);
3607  int *lbs1 = AARR_LBOUND(array1);
3608  int *lbs2 = AARR_LBOUND(array2);
3609  Oid element_type = AARR_ELEMTYPE(array1);
3610  bool result = true;
3611  int nitems;
3612  TypeCacheEntry *typentry;
3613  int typlen;
3614  bool typbyval;
3615  char typalign;
3616  array_iter it1;
3617  array_iter it2;
3618  int i;
3619 
3620  if (element_type != AARR_ELEMTYPE(array2))
3621  ereport(ERROR,
3622  (errcode(ERRCODE_DATATYPE_MISMATCH),
3623  errmsg("cannot compare arrays of different element types")));
3624 
3625  /* fast path if the arrays do not have the same dimensionality */
3626  if (ndims1 != ndims2 ||
3627  memcmp(dims1, dims2, ndims1 * sizeof(int)) != 0 ||
3628  memcmp(lbs1, lbs2, ndims1 * sizeof(int)) != 0)
3629  result = false;
3630  else
3631  {
3632  /*
3633  * We arrange to look up the equality function only once per series of
3634  * calls, assuming the element type doesn't change underneath us. The
3635  * typcache is used so that we have no memory leakage when being used
3636  * as an index support function.
3637  */
3638  typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
3639  if (typentry == NULL ||
3640  typentry->type_id != element_type)
3641  {
3642  typentry = lookup_type_cache(element_type,
3644  if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
3645  ereport(ERROR,
3646  (errcode(ERRCODE_UNDEFINED_FUNCTION),
3647  errmsg("could not identify an equality operator for type %s",
3648  format_type_be(element_type))));
3649  fcinfo->flinfo->fn_extra = (void *) typentry;
3650  }
3651  typlen = typentry->typlen;
3652  typbyval = typentry->typbyval;
3653  typalign = typentry->typalign;
3654 
3655  /*
3656  * apply the operator to each pair of array elements.
3657  */
3658  InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
3659  collation, NULL, NULL);
3660 
3661  /* Loop over source data */
3662  nitems = ArrayGetNItems(ndims1, dims1);
3663  array_iter_setup(&it1, array1);
3664  array_iter_setup(&it2, array2);
3665 
3666  for (i = 0; i < nitems; i++)
3667  {
3668  Datum elt1;
3669  Datum elt2;
3670  bool isnull1;
3671  bool isnull2;
3672  bool oprresult;
3673 
3674  /* Get elements, checking for NULL */
3675  elt1 = array_iter_next(&it1, &isnull1, i,
3676  typlen, typbyval, typalign);
3677  elt2 = array_iter_next(&it2, &isnull2, i,
3678  typlen, typbyval, typalign);
3679 
3680  /*
3681  * We consider two NULLs equal; NULL and not-NULL are unequal.
3682  */
3683  if (isnull1 && isnull2)
3684  continue;
3685  if (isnull1 || isnull2)
3686  {
3687  result = false;
3688  break;
3689  }
3690 
3691  /*
3692  * Apply the operator to the element pair; treat NULL as false
3693  */
3694  locfcinfo->args[0].value = elt1;
3695  locfcinfo->args[0].isnull = false;
3696  locfcinfo->args[1].value = elt2;
3697  locfcinfo->args[1].isnull = false;
3698  locfcinfo->isnull = false;
3699  oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
3700  if (locfcinfo->isnull || !oprresult)
3701  {
3702  result = false;
3703  break;
3704  }
3705  }
3706  }
3707 
3708  /* Avoid leaking memory when handed toasted input. */
3709  AARR_FREE_IF_COPY(array1, 0);
3710  AARR_FREE_IF_COPY(array2, 1);
3711 
3712  PG_RETURN_BOOL(result);
3713 }
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:262
static Datum array_iter_next(array_iter *it, bool *isnull, int i, int elmlen, bool elmbyval, char elmalign)
Definition: arrayaccess.h:81
#define TYPECACHE_EQ_OPR_FINFO
Definition: typcache.h:135
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
int16 typlen
Definition: typcache.h:39
bool typbyval
Definition: typcache.h:40
#define OidIsValid(objectId)
Definition: c.h:652
#define PG_GET_COLLATION()
Definition: fmgr.h:198
char typalign
Definition: pg_type.h:170
#define ERROR
Definition: elog.h:43
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
static void array_iter_setup(array_iter *it, AnyArrayType *a)
Definition: arrayaccess.h:49
#define DatumGetBool(X)
Definition: postgres.h:393
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:358
uintptr_t Datum
Definition: postgres.h:367
#define AARR_DIMS(a)
Definition: array.h:326
#define AARR_ELEMTYPE(a)
Definition: array.h:323
FmgrInfo eq_opr_finfo
Definition: typcache.h:74
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:331
Oid fn_oid
Definition: fmgr.h:59
#define ereport(elevel,...)
Definition: elog.h:144
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define AARR_LBOUND(a)
Definition: array.h:329
#define AARR_NDIM(a)
Definition: array.h:316
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
#define AARR_FREE_IF_COPY(array, n)
Definition: arrayfuncs.c:48
char typalign
Definition: typcache.h:41
int errmsg(const char *fmt,...)
Definition: elog.c:821
int i

◆ array_extract_slice()

static void array_extract_slice ( ArrayType newarray,
int  ndim,
int *  dim,
int *  lb,
char *  arraydataptr,
bits8 arraynullsptr,
int *  st,
int *  endp,
int  typlen,
bool  typbyval,
char  typalign 
)
static

Definition at line 4845 of file arrayfuncs.c.

References ARR_DATA_PTR, ARR_NULLBITMAP, array_bitmap_copy(), array_copy(), array_seek(), ArrayGetOffset(), i, MAXDIM, mda_get_offset_values(), mda_get_prod(), mda_get_range(), and mda_next_tuple().

Referenced by array_get_slice().

4856 {
4857  char *destdataptr = ARR_DATA_PTR(newarray);
4858  bits8 *destnullsptr = ARR_NULLBITMAP(newarray);
4859  char *srcdataptr;
4860  int src_offset,
4861  dest_offset,
4862  prod[MAXDIM],
4863  span[MAXDIM],
4864  dist[MAXDIM],
4865  indx[MAXDIM];
4866  int i,
4867  j,
4868  inc;
4869 
4870  src_offset = ArrayGetOffset(ndim, dim, lb, st);
4871  srcdataptr = array_seek(arraydataptr, 0, arraynullsptr, src_offset,
4872  typlen, typbyval, typalign);
4873  mda_get_prod(ndim, dim, prod);
4874  mda_get_range(ndim, span, st, endp);
4875  mda_get_offset_values(ndim, dist, prod, span);
4876  for (i = 0; i < ndim; i++)
4877  indx[i] = 0;
4878  dest_offset = 0;
4879  j = ndim - 1;
4880  do
4881  {
4882  if (dist[j])
4883  {
4884  /* skip unwanted elements */
4885  srcdataptr = array_seek(srcdataptr, src_offset, arraynullsptr,
4886  dist[j],
4887  typlen, typbyval, typalign);
4888  src_offset += dist[j];
4889  }
4890  inc = array_copy(destdataptr, 1,
4891  srcdataptr, src_offset, arraynullsptr,
4892  typlen, typbyval, typalign);
4893  if (destnullsptr)
4894  array_bitmap_copy(destnullsptr, dest_offset,
4895  arraynullsptr, src_offset,
4896  1);
4897  destdataptr += inc;
4898  srcdataptr += inc;
4899  src_offset++;
4900  dest_offset++;
4901  } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
4902 }
#define MAXDIM
Definition: c.h:543
int ArrayGetOffset(int n, const int *dim, const int *lb, const int *indx)
Definition: arrayutils.c:31
void mda_get_prod(int n, const int *range, int *prod)
Definition: arrayutils.c:134
void array_bitmap_copy(bits8 *destbitmap, int destoffset, const bits8 *srcbitmap, int srcoffset, int nitems)
Definition: arrayfuncs.c:4714
static int array_copy(char *destptr, int nitems, char *srcptr, int offset, bits8 *nullbitmap, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4684
char typalign
Definition: pg_type.h:170
#define ARR_DATA_PTR(a)
Definition: array.h:310
void mda_get_offset_values(int n, int *dist, const int *prod, const int *span)
Definition: arrayutils.c:150
uint8 bits8
Definition: c.h:382
void mda_get_range(int n, int *span, const int *st, const int *endp)
Definition: arrayutils.c:120
static char * array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4614
int mda_next_tuple(int n, int *curr, const int *span)
Definition: arrayutils.c:175
int i
#define ARR_NULLBITMAP(a)
Definition: array.h:288

◆ array_fill()

Datum array_fill ( PG_FUNCTION_ARGS  )

Definition at line 5751 of file arrayfuncs.c.

References array_fill_internal(), elog, ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), OidIsValid, PG_ARGISNULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_RETURN_ARRAYTYPE_P, and value.

5752 {
5753  ArrayType *dims;
5754  ArrayType *result;
5755  Oid elmtype;
5756  Datum value;
5757  bool isnull;
5758 
5759  if (PG_ARGISNULL(1))
5760  ereport(ERROR,
5761  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5762  errmsg("dimension array or low bound array cannot be null")));
5763 
5764  dims = PG_GETARG_ARRAYTYPE_P(1);
5765 
5766  if (!PG_ARGISNULL(0))
5767  {
5768  value = PG_GETARG_DATUM(0);
5769  isnull = false;
5770  }
5771  else
5772  {
5773  value = 0;
5774  isnull = true;
5775  }
5776 
5777  elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
5778  if (!OidIsValid(elmtype))
5779  elog(ERROR, "could not determine data type of input");
5780 
5781  result = array_fill_internal(dims, NULL, value, isnull, elmtype, fcinfo);
5782  PG_RETURN_ARRAYTYPE_P(result);
5783 }
static ArrayType * array_fill_internal(ArrayType *dims, ArrayType *lbs, Datum value, bool isnull, Oid elmtype, FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:5803
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:251
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1804
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:253
uintptr_t Datum
Definition: postgres.h:367
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214

◆ array_fill_internal()

static ArrayType * array_fill_internal ( ArrayType dims,
ArrayType lbs,
Datum  value,
bool  isnull,
Oid  elmtype,
FunctionCallInfo  fcinfo 
)
static

Definition at line 5803 of file arrayfuncs.c.

References AllocSizeIsValid, ARR_DATA_PTR, ARR_DIMS, ARR_NDIM, ARR_OVERHEAD_NONULLS, ARR_OVERHEAD_WITHNULLS, array_contains_nulls(), ArrayCastAndSet(), ArrayGetNItems(), Assert, att_addlength_datum, att_align_nominal, construct_empty_array(), create_array_envelope(), ArrayMetaState::element_type, ereport, errcode(), errdetail(), errmsg(), ERROR, FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_extra, FmgrInfo::fn_mcxt, get_typlenbyvalalign(), i, InvalidOid, MaxAllocSize, MAXDIM, MemoryContextAlloc(), ArrayIteratorData::nitems, PG_DETOAST_DATUM, PointerGetDatum, ArrayMetaState::typalign, ArrayMetaState::typbyval, and ArrayMetaState::typlen.

Referenced by array_fill(), and array_fill_with_lower_bounds().

5806 {
5807  ArrayType *result;
5808  int *dimv;
5809  int *lbsv;
5810  int ndims;
5811  int nitems;
5812  int deflbs[MAXDIM];
5813  int16 elmlen;
5814  bool elmbyval;
5815  char elmalign;
5816  ArrayMetaState *my_extra;
5817 
5818  /*
5819  * Params checks
5820  */
5821  if (ARR_NDIM(dims) > 1)
5822  ereport(ERROR,
5823  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
5824  errmsg("wrong number of array subscripts"),
5825  errdetail("Dimension array must be one dimensional.")));
5826 
5827  if (array_contains_nulls(dims))
5828  ereport(ERROR,
5829  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5830  errmsg("dimension values cannot be null")));
5831 
5832  dimv = (int *) ARR_DATA_PTR(dims);
5833  ndims = (ARR_NDIM(dims) > 0) ? ARR_DIMS(dims)[0] : 0;
5834 
5835  if (ndims < 0) /* we do allow zero-dimension arrays */
5836  ereport(ERROR,
5837  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5838  errmsg("invalid number of dimensions: %d", ndims)));
5839  if (ndims > MAXDIM)
5840  ereport(ERROR,
5841  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5842  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5843  ndims, MAXDIM)));
5844 
5845  if (lbs != NULL)
5846  {
5847  if (ARR_NDIM(lbs) > 1)
5848  ereport(ERROR,
5849  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
5850  errmsg("wrong number of array subscripts"),
5851  errdetail("Dimension array must be one dimensional.")));
5852 
5853  if (array_contains_nulls(lbs))
5854  ereport(ERROR,
5855  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5856  errmsg("dimension values cannot be null")));
5857 
5858  if (ndims != ((ARR_NDIM(lbs) > 0) ? ARR_DIMS(lbs)[0] : 0))
5859  ereport(ERROR,
5860  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
5861  errmsg("wrong number of array subscripts"),
5862  errdetail("Low bound array has different size than dimensions array.")));
5863 
5864  lbsv = (int *) ARR_DATA_PTR(lbs);
5865  }
5866  else
5867  {
5868  int i;
5869 
5870  for (i = 0; i < MAXDIM; i++)
5871  deflbs[i] = 1;
5872 
5873  lbsv = deflbs;
5874  }
5875 
5876  nitems = ArrayGetNItems(ndims, dimv);
5877 
5878  /* fast track for empty array */
5879  if (nitems <= 0)
5880  return construct_empty_array(elmtype);
5881 
5882  /*
5883  * We arrange to look up info about element type only once per series of
5884  * calls, assuming the element type doesn't change underneath us.
5885  */
5886  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
5887  if (my_extra == NULL)
5888  {
5889  fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
5890  sizeof(ArrayMetaState));
5891  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
5892  my_extra->element_type = InvalidOid;
5893  }
5894 
5895  if (my_extra->element_type != elmtype)
5896  {
5897  /* Get info about element type */
5898  get_typlenbyvalalign(elmtype,
5899  &my_extra->typlen,
5900  &my_extra->typbyval,
5901  &my_extra->typalign);
5902  my_extra->element_type = elmtype;
5903  }
5904 
5905  elmlen = my_extra->typlen;
5906  elmbyval = my_extra->typbyval;
5907  elmalign = my_extra->typalign;
5908 
5909  /* compute required space */
5910  if (!isnull)
5911  {
5912  int i;
5913  char *p;
5914  int nbytes;
5915  int totbytes;
5916 
5917  /* make sure data is not toasted */
5918  if (elmlen == -1)
5920 
5921  nbytes = att_addlength_datum(0, elmlen, value);
5922  nbytes = att_align_nominal(nbytes, elmalign);
5923  Assert(nbytes > 0);
5924 
5925  totbytes = nbytes * nitems;
5926 
5927  /* check for overflow of multiplication or total request */
5928  if (totbytes / nbytes != nitems ||
5929  !AllocSizeIsValid(totbytes))
5930  ereport(ERROR,
5931  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5932  errmsg("array size exceeds the maximum allowed (%d)",
5933  (int) MaxAllocSize)));
5934 
5935  /*
5936  * This addition can't overflow, but it might cause us to go past
5937  * MaxAllocSize. We leave it to palloc to complain in that case.
5938  */
5939  totbytes += ARR_OVERHEAD_NONULLS(ndims);
5940 
5941  result = create_array_envelope(ndims, dimv, lbsv, totbytes,
5942  elmtype, 0);
5943 
5944  p = ARR_DATA_PTR(result);
5945  for (i = 0; i < nitems; i++)
5946  p += ArrayCastAndSet(value, elmlen, elmbyval, elmalign, p);
5947  }
5948  else
5949  {
5950  int nbytes;
5951  int dataoffset;
5952 
5953  dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
5954  nbytes = dataoffset;
5955 
5956  result = create_array_envelope(ndims, dimv, lbsv, nbytes,
5957  elmtype, dataoffset);
5958 
5959  /* create_array_envelope already zeroed the bitmap, so we're done */
5960  }
5961 
5962  return result;
5963 }
signed short int16
Definition: c.h:362
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:298
MemoryContext fn_mcxt
Definition: fmgr.h:65
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
#define MAXDIM
Definition: c.h:543
static int ArrayCastAndSet(Datum src, int typlen, bool typbyval, char typalign, char *dest)
Definition: arrayfuncs.c:4575
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2159
#define PointerGetDatum(X)
Definition: postgres.h:556
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:610
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3432
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:300
bool typbyval
Definition: array.h:228
#define ERROR
Definition: elog.h:43
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
int16 typlen
Definition: array.h:227
int errdetail(const char *fmt,...)
Definition: elog.c:954
#define AllocSizeIsValid(size)
Definition: memutils.h:42
#define MaxAllocSize
Definition: memutils.h:40
FmgrInfo * flinfo
Definition: fmgr.h:87
#define InvalidOid
Definition: postgres_ext.h:36
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
static ArrayType * create_array_envelope(int ndims, int *dimv, int *lbsv, int nbytes, Oid elmtype, int dataoffset)
Definition: arrayfuncs.c:5786
void * fn_extra
Definition: fmgr.h:64
#define ARR_NDIM(a)
Definition: array.h:278
char typalign
Definition: array.h:229
#define att_addlength_datum(cur_offset, attlen, attdatum)
Definition: tupmacs.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:821
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
int i
Oid element_type
Definition: array.h:226
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
bool array_contains_nulls(ArrayType *array)
Definition: arrayfuncs.c:3550

◆ array_fill_with_lower_bounds()

Datum array_fill_with_lower_bounds ( PG_FUNCTION_ARGS  )

Definition at line 5710 of file arrayfuncs.c.

References array_fill_internal(), elog, ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), OidIsValid, PG_ARGISNULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_RETURN_ARRAYTYPE_P, and value.

5711 {
5712  ArrayType *dims;
5713  ArrayType *lbs;
5714  ArrayType *result;
5715  Oid elmtype;
5716  Datum value;
5717  bool isnull;
5718 
5719  if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
5720  ereport(ERROR,
5721  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5722  errmsg("dimension array or low bound array cannot be null")));
5723 
5724  dims = PG_GETARG_ARRAYTYPE_P(1);
5725  lbs = PG_GETARG_ARRAYTYPE_P(2);
5726 
5727  if (!PG_ARGISNULL(0))
5728  {
5729  value = PG_GETARG_DATUM(0);
5730  isnull = false;
5731  }
5732  else
5733  {
5734  value = 0;
5735  isnull = true;
5736  }
5737 
5738  elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
5739  if (!OidIsValid(elmtype))
5740  elog(ERROR, "could not determine data type of input");
5741 
5742  result = array_fill_internal(dims, lbs, value, isnull, elmtype, fcinfo);
5743  PG_RETURN_ARRAYTYPE_P(result);
5744 }
static ArrayType * array_fill_internal(ArrayType *dims, ArrayType *lbs, Datum value, bool isnull, Oid elmtype, FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:5803
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:251
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1804
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:253
uintptr_t Datum
Definition: postgres.h:367
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214

◆ array_free_iterator()

void array_free_iterator ( ArrayIterator  iterator)

Definition at line 4507 of file arrayfuncs.c.

References pfree(), ArrayIteratorData::slice_ndim, ArrayIteratorData::slice_nulls, and ArrayIteratorData::slice_values.

Referenced by array_position_common(), and array_positions().

4508 {
4509  if (iterator->slice_ndim > 0)
4510  {
4511  pfree(iterator->slice_values);
4512  pfree(iterator->slice_nulls);
4513  }
4514  pfree(iterator);
4515 }
bool * slice_nulls
Definition: arrayfuncs.c:84
void pfree(void *pointer)
Definition: mcxt.c:1057
Datum * slice_values
Definition: arrayfuncs.c:83

◆ array_ge()

Datum array_ge ( PG_FUNCTION_ARGS  )

Definition at line 3750 of file arrayfuncs.c.

References array_cmp(), and PG_RETURN_BOOL.

3751 {
3752  PG_RETURN_BOOL(array_cmp(fcinfo) >= 0);
3753 }
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3768
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:358

◆ array_get_element()

Datum array_get_element ( Datum  arraydatum,
int  nSubscripts,
int *  indx,
int  arraytyplen,
int  elmlen,
bool  elmbyval,
char  elmalign,
bool isNull 
)

Definition at line 1841 of file arrayfuncs.c.

References ARR_DATA_PTR, ARR_DIMS, ARR_LBOUND, ARR_NDIM, ARR_NULLBITMAP, array_get_element_expanded(), array_get_isnull(), array_seek(), ArrayCast(), ArrayGetOffset(), DatumGetArrayTypeP, DatumGetPointer, i, MAXDIM, and VARATT_IS_EXTERNAL_EXPANDED.

Referenced by array_ref(), ATExecAlterColumnType(), ExecEvalSubscriptingRefFetch(), ExecEvalSubscriptingRefOld(), and RelationBuildTupleDesc().

1849 {
1850  int i,
1851  ndim,
1852  *dim,
1853  *lb,
1854  offset,
1855  fixedDim[1],
1856  fixedLb[1];
1857  char *arraydataptr,
1858  *retptr;
1859  bits8 *arraynullsptr;
1860 
1861  if (arraytyplen > 0)
1862  {
1863  /*
1864  * fixed-length arrays -- these are assumed to be 1-d, 0-based
1865  */
1866  ndim = 1;
1867  fixedDim[0] = arraytyplen / elmlen;
1868  fixedLb[0] = 0;
1869  dim = fixedDim;
1870  lb = fixedLb;
1871  arraydataptr = (char *) DatumGetPointer(arraydatum);
1872  arraynullsptr = NULL;
1873  }
1874  else if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(arraydatum)))
1875  {
1876  /* expanded array: let's do this in a separate function */
1877  return array_get_element_expanded(arraydatum,
1878  nSubscripts,
1879  indx,
1880  arraytyplen,
1881  elmlen,
1882  elmbyval,
1883  elmalign,
1884  isNull);
1885  }
1886  else
1887  {
1888  /* detoast array if necessary, producing normal varlena input */
1889  ArrayType *array = DatumGetArrayTypeP(arraydatum);
1890 
1891  ndim = ARR_NDIM(array);
1892  dim = ARR_DIMS(array);
1893  lb = ARR_LBOUND(array);
1894  arraydataptr = ARR_DATA_PTR(array);
1895  arraynullsptr = ARR_NULLBITMAP(array);
1896  }
1897 
1898  /*
1899  * Return NULL for invalid subscript
1900  */
1901  if (ndim != nSubscripts || ndim <= 0 || ndim > MAXDIM)
1902  {
1903  *isNull = true;
1904  return (Datum) 0;
1905  }
1906  for (i = 0; i < ndim; i++)
1907  {
1908  if (indx[i] < lb[i] || indx[i] >= (dim[i] + lb[i]))
1909  {
1910  *isNull = true;
1911  return (Datum) 0;
1912  }
1913  }
1914 
1915  /*
1916  * Calculate the element number
1917  */
1918  offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
1919 
1920  /*
1921  * Check for NULL array element
1922  */
1923  if (array_get_isnull(arraynullsptr, offset))
1924  {
1925  *isNull = true;
1926  return (Datum) 0;
1927  }
1928 
1929  /*
1930  * OK, get the element
1931  */
1932  *isNull = false;
1933  retptr = array_seek(arraydataptr, 0, arraynullsptr, offset,
1934  elmlen, elmbyval, elmalign);
1935  return ArrayCast(retptr, elmbyval, elmlen);
1936 }
#define VARATT_IS_EXTERNAL_EXPANDED(PTR)
Definition: postgres.h:322
#define MAXDIM
Definition: c.h:543
int ArrayGetOffset(int n, const int *dim, const int *lb, const int *indx)
Definition: arrayutils.c:31
#define ARR_LBOUND(a)
Definition: array.h:284
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
static Datum array_get_element_expanded(Datum arraydatum, int nSubscripts, int *indx, int arraytyplen, int elmlen, bool elmbyval, char elmalign, bool *isNull)
Definition: arrayfuncs.c:1942
uint8 bits8
Definition: c.h:382
uintptr_t Datum
Definition: postgres.h:367
static char * array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4614
static Datum ArrayCast(char *value, bool byval, int len)
Definition: arrayfuncs.c:4564
static bool array_get_isnull(const bits8 *nullbitmap, int offset)
Definition: arrayfuncs.c:4529
#define ARR_NDIM(a)
Definition: array.h:278
#define DatumGetPointer(X)
Definition: postgres.h:549
int i
#define ARR_NULLBITMAP(a)
Definition: array.h:288
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ array_get_element_expanded()

static Datum array_get_element_expanded ( Datum  arraydatum,
int  nSubscripts,
int *  indx,
int  arraytyplen,
int  elmlen,
bool  elmbyval,
char  elmalign,
bool isNull 
)
static

Definition at line 1942 of file arrayfuncs.c.

References ArrayGetOffset(), Assert, DatumGetEOHP(), deconstruct_expanded_array(), ExpandedArrayHeader::dims, ExpandedArrayHeader::dnulls, ExpandedArrayHeader::dvalues, EA_MAGIC, ExpandedArrayHeader::ea_magic, i, ExpandedArrayHeader::lbound, MAXDIM, ExpandedArrayHeader::ndims, ExpandedArrayHeader::typalign, ExpandedArrayHeader::typbyval, and ExpandedArrayHeader::typlen.

Referenced by array_get_element().

1947 {
1948  ExpandedArrayHeader *eah;
1949  int i,
1950  ndim,
1951  *dim,
1952  *lb,
1953  offset;
1954  Datum *dvalues;
1955  bool *dnulls;
1956 
1957  eah = (ExpandedArrayHeader *) DatumGetEOHP(arraydatum);
1958  Assert(eah->ea_magic == EA_MAGIC);
1959 
1960  /* sanity-check caller's info against object */
1961  Assert(arraytyplen == -1);
1962  Assert(elmlen == eah->typlen);
1963  Assert(elmbyval == eah->typbyval);
1964  Assert(elmalign == eah->typalign);
1965 
1966  ndim = eah->ndims;
1967  dim = eah->dims;
1968  lb = eah->lbound;
1969 
1970  /*
1971  * Return NULL for invalid subscript
1972  */
1973  if (ndim != nSubscripts || ndim <= 0 || ndim > MAXDIM)
1974  {
1975  *isNull = true;
1976  return (Datum) 0;
1977  }
1978  for (i = 0; i < ndim; i++)
1979  {
1980  if (indx[i] < lb[i] || indx[i] >= (dim[i] + lb[i]))
1981  {
1982  *isNull = true;
1983  return (Datum) 0;
1984  }
1985  }
1986 
1987  /*
1988  * Calculate the element number
1989  */
1990  offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
1991 
1992  /*
1993  * Deconstruct array if we didn't already. Note that we apply this even
1994  * if the input is nominally read-only: it should be safe enough.
1995  */
1997 
1998  dvalues = eah->dvalues;
1999  dnulls = eah->dnulls;
2000 
2001  /*
2002  * Check for NULL array element
2003  */
2004  if (dnulls && dnulls[offset])
2005  {
2006  *isNull = true;
2007  return (Datum) 0;
2008  }
2009 
2010  /*
2011  * OK, get the element. It's OK to return a pass-by-ref value as a
2012  * pointer into the expanded array, for the same reason that regular
2013  * array_get_element can return a pointer into flat arrays: the value is
2014  * assumed not to change for as long as the Datum reference can exist.
2015  */
2016  *isNull = false;
2017  return dvalues[offset];
2018 }
void deconstruct_expanded_array(ExpandedArrayHeader *eah)
#define MAXDIM
Definition: c.h:543
int ArrayGetOffset(int n, const int *dim, const int *lb, const int *indx)
Definition: arrayutils.c:31
Datum * dvalues
Definition: array.h:134
#define EA_MAGIC
Definition: array.h:101
ExpandedObjectHeader * DatumGetEOHP(Datum d)
Definition: expandeddatum.c:29
uintptr_t Datum
Definition: postgres.h:367
#define Assert(condition)
Definition: c.h:746
int i

◆ array_get_isnull()

static bool array_get_isnull ( const bits8 nullbitmap,
int  offset 
)
static

Definition at line 4529 of file arrayfuncs.c.

Referenced by array_get_element(), array_iterate(), array_set_element(), and array_slice_size().

4530 {
4531  if (nullbitmap == NULL)
4532  return false; /* assume not null */
4533  if (nullbitmap[offset / 8] & (1 << (offset % 8)))
4534  return false; /* not null */
4535  return true;
4536 }

◆ array_get_slice()

Datum array_get_slice ( Datum  arraydatum,
int  nSubscripts,
int *  upperIndx,
int *  lowerIndx,
bool upperProvided,
bool lowerProvided,
int  arraytyplen,
int  elmlen,
bool  elmbyval,
char  elmalign 
)

Definition at line 2050 of file arrayfuncs.c.

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_LBOUND, ARR_NDIM, ARR_NULLBITMAP, ARR_OVERHEAD_NONULLS, ARR_OVERHEAD_WITHNULLS, array_extract_slice(), array_slice_size(), ArrayGetNItems(), generate_unaccent_rules::bytes(), construct_empty_array(), ArrayType::dataoffset, DatumGetArrayTypeP, DatumGetPointer, ArrayType::elemtype, ereport, errcode(), errmsg(), ERROR, i, InvalidOid, MAXDIM, mda_get_range(), ArrayType::ndim, palloc0(), PointerGetDatum, and SET_VARSIZE.

Referenced by ExecEvalSubscriptingRefFetch(), and ExecEvalSubscriptingRefOld().

2060 {
2061  ArrayType *array;
2062  ArrayType *newarray;
2063  int i,
2064  ndim,
2065  *dim,
2066  *lb,
2067  *newlb;
2068  int fixedDim[1],
2069  fixedLb[1];
2070  Oid elemtype;
2071  char *arraydataptr;
2072  bits8 *arraynullsptr;
2073  int32 dataoffset;
2074  int bytes,
2075  span[MAXDIM];
2076 
2077  if (arraytyplen > 0)
2078  {
2079  /*
2080  * fixed-length arrays -- currently, cannot slice these because parser
2081  * labels output as being of the fixed-length array type! Code below
2082  * shows how we could support it if the parser were changed to label
2083  * output as a suitable varlena array type.
2084  */
2085  ereport(ERROR,
2086  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2087  errmsg("slices of fixed-length arrays not implemented")));
2088 
2089  /*
2090  * fixed-length arrays -- these are assumed to be 1-d, 0-based
2091  *
2092  * XXX where would we get the correct ELEMTYPE from?
2093  */
2094  ndim = 1;
2095  fixedDim[0] = arraytyplen / elmlen;
2096  fixedLb[0] = 0;
2097  dim = fixedDim;
2098  lb = fixedLb;
2099  elemtype = InvalidOid; /* XXX */
2100  arraydataptr = (char *) DatumGetPointer(arraydatum);
2101  arraynullsptr = NULL;
2102  }
2103  else
2104  {
2105  /* detoast input array if necessary */
2106  array = DatumGetArrayTypeP(arraydatum);
2107 
2108  ndim = ARR_NDIM(array);
2109  dim = ARR_DIMS(array);
2110  lb = ARR_LBOUND(array);
2111  elemtype = ARR_ELEMTYPE(array);
2112  arraydataptr = ARR_DATA_PTR(array);
2113  arraynullsptr = ARR_NULLBITMAP(array);
2114  }
2115 
2116  /*
2117  * Check provided subscripts. A slice exceeding the current array limits
2118  * is silently truncated to the array limits. If we end up with an empty
2119  * slice, return an empty array.
2120  */
2121  if (ndim < nSubscripts || ndim <= 0 || ndim > MAXDIM)
2122  return PointerGetDatum(construct_empty_array(elemtype));
2123 
2124  for (i = 0; i < nSubscripts; i++)
2125  {
2126  if (!lowerProvided[i] || lowerIndx[i] < lb[i])
2127  lowerIndx[i] = lb[i];
2128  if (!upperProvided[i] || upperIndx[i] >= (dim[i] + lb[i]))
2129  upperIndx[i] = dim[i] + lb[i] - 1;
2130  if (lowerIndx[i] > upperIndx[i])
2131  return PointerGetDatum(construct_empty_array(elemtype));
2132  }
2133  /* fill any missing subscript positions with full array range */
2134  for (; i < ndim; i++)
2135  {
2136  lowerIndx[i] = lb[i];
2137  upperIndx[i] = dim[i] + lb[i] - 1;
2138  if (lowerIndx[i] > upperIndx[i])
2139  return PointerGetDatum(construct_empty_array(elemtype));
2140  }
2141 
2142  mda_get_range(ndim, span, lowerIndx, upperIndx);
2143 
2144  bytes = array_slice_size(arraydataptr, arraynullsptr,
2145  ndim, dim, lb,
2146  lowerIndx, upperIndx,
2147  elmlen, elmbyval, elmalign);
2148 
2149  /*
2150  * Currently, we put a null bitmap in the result if the source has one;
2151  * could be smarter ...
2152  */
2153  if (arraynullsptr)
2154  {
2155  dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, ArrayGetNItems(ndim, span));
2156  bytes += dataoffset;
2157  }
2158  else
2159  {
2160  dataoffset = 0; /* marker for no null bitmap */
2161  bytes += ARR_OVERHEAD_NONULLS(ndim);
2162  }
2163 
2164  newarray = (ArrayType *) palloc0(bytes);
2165  SET_VARSIZE(newarray, bytes);
2166  newarray->ndim = ndim;
2167  newarray->dataoffset = dataoffset;
2168  newarray->elemtype = elemtype;
2169  memcpy(ARR_DIMS(newarray), span, ndim * sizeof(int));
2170 
2171  /*
2172  * Lower bounds of the new array are set to 1. Formerly (before 7.3) we
2173  * copied the given lowerIndx values ... but that seems confusing.
2174  */
2175  newlb = ARR_LBOUND(newarray);
2176  for (i = 0; i < ndim; i++)
2177  newlb[i] = 1;
2178 
2179  array_extract_slice(newarray,
2180  ndim, dim, lb,
2181  arraydataptr, arraynullsptr,
2182  lowerIndx, upperIndx,
2183  elmlen, elmbyval, elmalign);
2184 
2185  return PointerGetDatum(newarray);
2186 }
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:298
#define MAXDIM
Definition: c.h:543
#define PointerGetDatum(X)
Definition: postgres.h:556
def bytes(source, encoding='ascii', errors='strict')
int32 dataoffset
Definition: array.h:84
static int array_slice_size(char *arraydataptr, bits8 *arraynullsptr, int ndim, int *dim, int *lb, int *st, int *endp, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4785
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:610
static void array_extract_slice(ArrayType *newarray, int ndim, int *dim, int *lb, char *arraydataptr, bits8 *arraynullsptr, int *st, int *endp, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4845
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3432
unsigned int Oid
Definition: postgres_ext.h:31
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:300
signed int int32
Definition: c.h:363
#define ARR_LBOUND(a)
Definition: array.h:284
#define ERROR
Definition: elog.h:43
Oid elemtype
Definition: array.h:85
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
uint8 bits8
Definition: c.h:382
void * palloc0(Size size)
Definition: mcxt.c:981
void mda_get_range(int n, int *span, const int *st, const int *endp)
Definition: arrayutils.c:120
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define ARR_NDIM(a)
Definition: array.h:278
#define DatumGetPointer(X)
Definition: postgres.h:549
int errmsg(const char *fmt,...)
Definition: elog.c:821
int i
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329
#define ARR_ELEMTYPE(a)
Definition: array.h:280
#define ARR_NULLBITMAP(a)
Definition: array.h:288
int ndim
Definition: array.h:83
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ array_gt()

Datum array_gt ( PG_FUNCTION_ARGS  )

Definition at line 3738 of file arrayfuncs.c.

References array_cmp(), and PG_RETURN_BOOL.

3739 {
3740  PG_RETURN_BOOL(array_cmp(fcinfo) > 0);
3741 }
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3768
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:358

◆ array_in()

Datum array_in ( PG_FUNCTION_ARGS  )

Definition at line 173 of file arrayfuncs.c.

References ARR_DIMS, ARR_LBOUND, ARR_OVERHEAD_NONULLS, ARR_OVERHEAD_WITHNULLS, array_isspace(), ArrayCount(), ArrayGetNItems(), ASSGN, construct_empty_array(), CopyArrayEls(), ArrayType::dataoffset, ArrayMetaState::element_type, ArrayType::elemtype, ereport, errcode(), errdetail(), errmsg(), ERROR, fmgr_info_cxt(), FmgrInfo::fn_mcxt, get_type_io_data(), i, IOFunc_input, MAXDIM, MemoryContextAlloc(), ArrayType::ndim, ArrayIteratorData::nitems, palloc(), palloc0(), pfree(), PG_GETARG_CSTRING, PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_ARRAYTYPE_P, printf, ArrayMetaState::proc, pstrdup(), ReadArrayStr(), SET_VARSIZE, ArrayIteratorData::typalign, ArrayMetaState::typalign, ArrayIteratorData::typbyval, ArrayMetaState::typbyval, ArrayMetaState::typdelim, ArrayMetaState::typiofunc, ArrayMetaState::typioparam, ArrayIteratorData::typlen, and ArrayMetaState::typlen.

Referenced by extract_variadic_args().

174 {
175  char *string = PG_GETARG_CSTRING(0); /* external form */
176  Oid element_type = PG_GETARG_OID(1); /* type of an array
177  * element */
178  int32 typmod = PG_GETARG_INT32(2); /* typmod for array elements */
179  int typlen;
180  bool typbyval;
181  char typalign;
182  char typdelim;
183  Oid typioparam;
184  char *string_save,
185  *p;
186  int i,
187  nitems;
188  Datum *dataPtr;
189  bool *nullsPtr;
190  bool hasnulls;
191  int32 nbytes;
192  int32 dataoffset;
193  ArrayType *retval;
194  int ndim,
195  dim[MAXDIM],
196  lBound[MAXDIM];
197  ArrayMetaState *my_extra;
198 
199  /*
200  * We arrange to look up info about element type, including its input
201  * conversion proc, only once per series of calls, assuming the element
202  * type doesn't change underneath us.
203  */
204  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
205  if (my_extra == NULL)
206  {
207  fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
208  sizeof(ArrayMetaState));
209  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
210  my_extra->element_type = ~element_type;
211  }
212 
213  if (my_extra->element_type != element_type)
214  {
215  /*
216  * Get info about element type, including its input conversion proc
217  */
218  get_type_io_data(element_type, IOFunc_input,
219  &my_extra->typlen, &my_extra->typbyval,
220  &my_extra->typalign, &my_extra->typdelim,
221  &my_extra->typioparam, &my_extra->typiofunc);
222  fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
223  fcinfo->flinfo->fn_mcxt);
224  my_extra->element_type = element_type;
225  }
226  typlen = my_extra->typlen;
227  typbyval = my_extra->typbyval;
228  typalign = my_extra->typalign;
229  typdelim = my_extra->typdelim;
230  typioparam = my_extra->typioparam;
231 
232  /* Make a modifiable copy of the input */
233  string_save = pstrdup(string);
234 
235  /*
236  * If the input string starts with dimension info, read and use that.
237  * Otherwise, we require the input to be in curly-brace style, and we
238  * prescan the input to determine dimensions.
239  *
240  * Dimension info takes the form of one or more [n] or [m:n] items. The
241  * outer loop iterates once per dimension item.
242  */
243  p = string_save;
244  ndim = 0;
245  for (;;)
246  {
247  char *q;
248  int ub;
249 
250  /*
251  * Note: we currently allow whitespace between, but not within,
252  * dimension items.
253  */
254  while (array_isspace(*p))
255  p++;
256  if (*p != '[')
257  break; /* no more dimension items */
258  p++;
259  if (ndim >= MAXDIM)
260  ereport(ERROR,
261  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
262  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
263  ndim + 1, MAXDIM)));
264 
265  for (q = p; isdigit((unsigned char) *q) || (*q == '-') || (*q == '+'); q++)
266  /* skip */ ;
267  if (q == p) /* no digits? */
268  ereport(ERROR,
269  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
270  errmsg("malformed array literal: \"%s\"", string),
271  errdetail("\"[\" must introduce explicitly-specified array dimensions.")));
272 
273  if (*q == ':')
274  {
275  /* [m:n] format */
276  *q = '\0';
277  lBound[ndim] = atoi(p);
278  p = q + 1;
279  for (q = p; isdigit((unsigned char) *q) || (*q == '-') || (*q == '+'); q++)
280  /* skip */ ;
281  if (q == p) /* no digits? */
282  ereport(ERROR,
283  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
284  errmsg("malformed array literal: \"%s\"", string),
285  errdetail("Missing array dimension value.")));
286  }
287  else
288  {
289  /* [n] format */
290  lBound[ndim] = 1;
291  }
292  if (*q != ']')
293  ereport(ERROR,
294  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
295  errmsg("malformed array literal: \"%s\"", string),
296  errdetail("Missing \"%s\" after array dimensions.",
297  "]")));
298 
299  *q = '\0';
300  ub = atoi(p);
301  p = q + 1;
302  if (ub < lBound[ndim])
303  ereport(ERROR,
304  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
305  errmsg("upper bound cannot be less than lower bound")));
306 
307  dim[ndim] = ub - lBound[ndim] + 1;
308  ndim++;
309  }
310 
311  if (ndim == 0)
312  {
313  /* No array dimensions, so intuit dimensions from brace structure */
314  if (*p != '{')
315  ereport(ERROR,
316  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
317  errmsg("malformed array literal: \"%s\"", string),
318  errdetail("Array value must start with \"{\" or dimension information.")));
319  ndim = ArrayCount(p, dim, typdelim);
320  for (i = 0; i < ndim; i++)
321  lBound[i] = 1;
322  }
323  else
324  {
325  int ndim_braces,
326  dim_braces[MAXDIM];
327 
328  /* If array dimensions are given, expect '=' operator */
329  if (strncmp(p, ASSGN, strlen(ASSGN)) != 0)
330  ereport(ERROR,
331  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
332  errmsg("malformed array literal: \"%s\"", string),
333  errdetail("Missing \"%s\" after array dimensions.",
334  ASSGN)));
335  p += strlen(ASSGN);
336  while (array_isspace(*p))
337  p++;
338 
339  /*
340  * intuit dimensions from brace structure -- it better match what we
341  * were given
342  */
343  if (*p != '{')
344  ereport(ERROR,
345  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
346  errmsg("malformed array literal: \"%s\"", string),
347  errdetail("Array contents must start with \"{\".")));
348  ndim_braces = ArrayCount(p, dim_braces, typdelim);
349  if (ndim_braces != ndim)
350  ereport(ERROR,
351  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
352  errmsg("malformed array literal: \"%s\"", string),
353  errdetail("Specified array dimensions do not match array contents.")));
354  for (i = 0; i < ndim; ++i)
355  {
356  if (dim[i] != dim_braces[i])
357  ereport(ERROR,
358  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
359  errmsg("malformed array literal: \"%s\"", string),
360  errdetail("Specified array dimensions do not match array contents.")));
361  }
362  }
363 
364 #ifdef ARRAYDEBUG
365  printf("array_in- ndim %d (", ndim);
366  for (i = 0; i < ndim; i++)
367  {
368  printf(" %d", dim[i]);
369  };
370  printf(") for %s\n", string);
371 #endif
372 
373  /* This checks for overflow of the array dimensions */
374  nitems = ArrayGetNItems(ndim, dim);
375  /* Empty array? */
376  if (nitems == 0)
378 
379  dataPtr = (Datum *) palloc(nitems * sizeof(Datum));
380  nullsPtr = (bool *) palloc(nitems * sizeof(bool));
381  ReadArrayStr(p, string,
382  nitems, ndim, dim,
383  &my_extra->proc, typioparam, typmod,
384  typdelim,
385  typlen, typbyval, typalign,
386  dataPtr, nullsPtr,
387  &hasnulls, &nbytes);
388  if (hasnulls)
389  {
390  dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
391  nbytes += dataoffset;
392  }
393  else
394  {
395  dataoffset = 0; /* marker for no null bitmap */
396  nbytes += ARR_OVERHEAD_NONULLS(ndim);
397  }
398  retval = (ArrayType *) palloc0(nbytes);
399  SET_VARSIZE(retval, nbytes);
400  retval->ndim = ndim;
401  retval->dataoffset = dataoffset;
402 
403  /*
404  * This comes from the array's pg_type.typelem (which points to the base
405  * data type's pg_type.oid) and stores system oids in user tables. This
406  * oid must be preserved by binary upgrades.
407  */
408  retval->elemtype = element_type;
409  memcpy(ARR_DIMS(retval), dim, ndim * sizeof(int));
410  memcpy(ARR_LBOUND(retval), lBound, ndim * sizeof(int));
411 
412  CopyArrayEls(retval,
413  dataPtr, nullsPtr, nitems,
414  typlen, typbyval, typalign,
415  true);
416 
417  pfree(dataPtr);
418  pfree(nullsPtr);
419  pfree(string_save);
420 
421  PG_RETURN_ARRAYTYPE_P(retval);
422 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
static bool array_isspace(char ch)
Definition: arrayfuncs.c:433
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:298
MemoryContext fn_mcxt
Definition: fmgr.h:65
#define MAXDIM
Definition: c.h:543
char * pstrdup(const char *in)
Definition: mcxt.c:1187
int32 dataoffset
Definition: array.h:84
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:610
#define printf(...)
Definition: port.h:221
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3432
unsigned int Oid
Definition: postgres_ext.h:31
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:300
signed int int32
Definition: c.h:363
static void ReadArrayStr(char *arrayStr, const char *origStr, int nitems, int ndim, int *dim, FmgrInfo *inputproc, Oid typioparam, int32 typmod, char typdelim, int typlen, bool typbyval, char typalign, Datum *values, bool *nulls, bool *hasnulls, int32 *nbytes)
Definition: arrayfuncs.c:718
#define ARR_LBOUND(a)
Definition: array.h:284
bool typbyval
Definition: array.h:228
void pfree(void *pointer)
Definition: mcxt.c:1057
char typalign
Definition: pg_type.h:170
#define ERROR
Definition: elog.h:43
Oid elemtype
Definition: array.h:85
#define ARR_DIMS(a)
Definition: array.h:282
int16 typlen
Definition: array.h:227
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
char typdelim
Definition: array.h:230
int errdetail(const char *fmt,...)
Definition: elog.c:954
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:253
#define ASSGN
Definition: arrayfuncs.c:46
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:144
Oid typioparam
Definition: array.h:231
static int ArrayCount(const char *str, int *dim, char typdelim)
Definition: arrayfuncs.c:453
void CopyArrayEls(ArrayType *array, Datum *values, bool *nulls, int nitems, int typlen, bool typbyval, char typalign, bool freedata)
Definition: arrayfuncs.c:958
Oid typiofunc
Definition: array.h:232
char typalign
Definition: array.h:229
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
FmgrInfo proc
Definition: array.h:233
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
int i
Oid element_type
Definition: array.h:226
#define PG_GETARG_CSTRING(n)
Definition: fmgr.h:277
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329
int ndim
Definition: array.h:83
void get_type_io_data(Oid typid, IOFuncSelector which_func, int16 *typlen, bool *typbyval, char *typalign, char *typdelim, Oid *typioparam, Oid *func)
Definition: lsyscache.c:2213

◆ array_insert_slice()

static void array_insert_slice ( ArrayType destArray,
ArrayType origArray,
ArrayType srcArray,
int  ndim,
int *  dim,
int *  lb,
int *  st,
int *  endp,
int  typlen,
bool  typbyval,
char  typalign 
)
static

Definition at line 4918 of file arrayfuncs.c.

References ARR_DATA_PTR, ARR_DIMS, ARR_NDIM, ARR_NULLBITMAP, array_bitmap_copy(), array_copy(), array_seek(), ArrayGetNItems(), ArrayGetOffset(), i, MAXDIM, mda_get_offset_values(), mda_get_prod(), mda_get_range(), and mda_next_tuple().

Referenced by array_set_slice().

4929 {
4930  char *destPtr = ARR_DATA_PTR(destArray);
4931  char *origPtr = ARR_DATA_PTR(origArray);
4932  char *srcPtr = ARR_DATA_PTR(srcArray);
4933  bits8 *destBitmap = ARR_NULLBITMAP(destArray);
4934  bits8 *origBitmap = ARR_NULLBITMAP(origArray);
4935  bits8 *srcBitmap = ARR_NULLBITMAP(srcArray);
4936  int orignitems = ArrayGetNItems(ARR_NDIM(origArray),
4937  ARR_DIMS(origArray));
4938  int dest_offset,
4939  orig_offset,
4940  src_offset,
4941  prod[MAXDIM],
4942  span[MAXDIM],
4943  dist[MAXDIM],
4944  indx[MAXDIM];
4945  int i,
4946  j,
4947  inc;
4948 
4949  dest_offset = ArrayGetOffset(ndim, dim, lb, st);
4950  /* copy items before the slice start */
4951  inc = array_copy(destPtr, dest_offset,
4952  origPtr, 0, origBitmap,
4953  typlen, typbyval, typalign);
4954  destPtr += inc;
4955  origPtr += inc;
4956  if (destBitmap)
4957  array_bitmap_copy(destBitmap, 0, origBitmap, 0, dest_offset);
4958  orig_offset = dest_offset;
4959  mda_get_prod(ndim, dim, prod);
4960  mda_get_range(ndim, span, st, endp);
4961  mda_get_offset_values(ndim, dist, prod, span);
4962  for (i = 0; i < ndim; i++)
4963  indx[i] = 0;
4964  src_offset = 0;
4965  j = ndim - 1;
4966  do
4967  {
4968  /* Copy/advance over elements between here and next part of slice */
4969  if (dist[j])
4970  {
4971  inc = array_copy(destPtr, dist[j],
4972  origPtr, orig_offset, origBitmap,
4973  typlen, typbyval, typalign);
4974  destPtr += inc;
4975  origPtr += inc;
4976  if (destBitmap)
4977  array_bitmap_copy(destBitmap, dest_offset,
4978  origBitmap, orig_offset,
4979  dist[j]);
4980  dest_offset += dist[j];
4981  orig_offset += dist[j];
4982  }
4983  /* Copy new element at this slice position */
4984  inc = array_copy(destPtr, 1,
4985  srcPtr, src_offset, srcBitmap,
4986  typlen, typbyval, typalign);
4987  if (destBitmap)
4988  array_bitmap_copy(destBitmap, dest_offset,
4989  srcBitmap, src_offset,
4990  1);
4991  destPtr += inc;
4992  srcPtr += inc;
4993  dest_offset++;
4994  src_offset++;
4995  /* Advance over old element at this slice position */
4996  origPtr = array_seek(origPtr, orig_offset, origBitmap, 1,
4997  typlen, typbyval, typalign);
4998  orig_offset++;
4999  } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
5000 
5001  /* don't miss any data at the end */
5002  array_copy(destPtr, orignitems - orig_offset,
5003  origPtr, orig_offset, origBitmap,
5004  typlen, typbyval, typalign);
5005  if (destBitmap)
5006  array_bitmap_copy(destBitmap, dest_offset,
5007  origBitmap, orig_offset,
5008  orignitems - orig_offset);
5009 }
#define MAXDIM
Definition: c.h:543
int ArrayGetOffset(int n, const int *dim, const int *lb, const int *indx)
Definition: arrayutils.c:31
void mda_get_prod(int n, const int *range, int *prod)
Definition: arrayutils.c:134
void array_bitmap_copy(bits8 *destbitmap, int destoffset, const bits8 *srcbitmap, int srcoffset, int nitems)
Definition: arrayfuncs.c:4714
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
static int array_copy(char *destptr, int nitems, char *srcptr, int offset, bits8 *nullbitmap, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4684
char typalign
Definition: pg_type.h:170
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
void mda_get_offset_values(int n, int *dist, const int *prod, const int *span)
Definition: arrayutils.c:150
uint8 bits8
Definition: c.h:382
void mda_get_range(int n, int *span, const int *st, const int *endp)
Definition: arrayutils.c:120
static char * array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4614
#define ARR_NDIM(a)
Definition: array.h:278
int mda_next_tuple(int n, int *curr, const int *span)
Definition: arrayutils.c:175
int i
#define ARR_NULLBITMAP(a)
Definition: array.h:288

◆ array_isspace()

static bool array_isspace ( char  ch)
static

Definition at line 433 of file arrayfuncs.c.

Referenced by array_in(), array_out(), ArrayCount(), and ReadArrayStr().

434 {
435  if (ch == ' ' ||
436  ch == '\t' ||
437  ch == '\n' ||
438  ch == '\r' ||
439  ch == '\v' ||
440  ch == '\f')
441  return true;
442  return false;
443 }

◆ array_iterate()

bool array_iterate ( ArrayIterator  iterator,
Datum value,
bool isnull 
)

Definition at line 4424 of file arrayfuncs.c.

References ArrayIteratorData::arr, ARR_ELEMTYPE, array_get_isnull(), att_addlength_pointer, att_align_nominal, construct_md_array(), ArrayIteratorData::current_item, ArrayIteratorData::data_ptr, fetch_att, i, ArrayIteratorData::nitems, ArrayIteratorData::nullbitmap, PointerGetDatum, ArrayIteratorData::slice_dims, ArrayIteratorData::slice_lbound, ArrayIteratorData::slice_len, ArrayIteratorData::slice_ndim, ArrayIteratorData::slice_nulls, ArrayIteratorData::slice_values, ArrayIteratorData::typalign, ArrayIteratorData::typbyval, ArrayIteratorData::typlen, and values.

Referenced by array_position_common(), array_positions(), and exec_stmt_foreach_a().

4425 {
4426  /* Done if we have reached the end of the array */
4427  if (iterator->current_item >= iterator->nitems)
4428  return false;
4429 
4430  if (iterator->slice_ndim == 0)
4431  {
4432  /*
4433  * Scalar case: return one element.
4434  */
4435  if (array_get_isnull(iterator->nullbitmap, iterator->current_item++))
4436  {
4437  *isnull = true;
4438  *value = (Datum) 0;
4439  }
4440  else
4441  {
4442  /* non-NULL, so fetch the individual Datum to return */
4443  char *p = iterator->data_ptr;
4444 
4445  *isnull = false;
4446  *value = fetch_att(p, iterator->typbyval, iterator->typlen);
4447 
4448  /* Move our data pointer forward to the next element */
4449  p = att_addlength_pointer(p, iterator->typlen, p);
4450  p = (char *) att_align_nominal(p, iterator->typalign);
4451  iterator->data_ptr = p;
4452  }
4453  }
4454  else
4455  {
4456  /*
4457  * Slice case: build and return an array of the requested size.
4458  */
4459  ArrayType *result;
4460  Datum *values = iterator->slice_values;
4461  bool *nulls = iterator->slice_nulls;
4462  char *p = iterator->data_ptr;
4463  int i;
4464 
4465  for (i = 0; i < iterator->slice_len; i++)
4466  {
4467  if (array_get_isnull(iterator->nullbitmap,
4468  iterator->current_item++))
4469  {
4470  nulls[i] = true;
4471  values[i] = (Datum) 0;
4472  }
4473  else
4474  {
4475  nulls[i] = false;
4476  values[i] = fetch_att(p, iterator->typbyval, iterator->typlen);
4477 
4478  /* Move our data pointer forward to the next element */
4479  p = att_addlength_pointer(p, iterator->typlen, p);
4480  p = (char *) att_align_nominal(p, iterator->typalign);
4481  }
4482  }
4483 
4484  iterator->data_ptr = p;
4485 
4486  result = construct_md_array(values,
4487  nulls,
4488  iterator->slice_ndim,
4489  iterator->slice_dims,
4490  iterator->slice_lbound,
4491  ARR_ELEMTYPE(iterator->arr),
4492  iterator->typlen,
4493  iterator->typbyval,
4494  iterator->typalign);
4495 
4496  *isnull = false;
4497  *value = PointerGetDatum(result);
4498  }
4499 
4500  return true;
4501 }
bits8 * nullbitmap
Definition: arrayfuncs.c:72
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
#define PointerGetDatum(X)
Definition: postgres.h:556
bool * slice_nulls
Definition: arrayfuncs.c:84
Datum * slice_values
Definition: arrayfuncs.c:83
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:176
uintptr_t Datum
Definition: postgres.h:367
static struct @143 value
static bool array_get_isnull(const bits8 *nullbitmap, int offset)
Definition: arrayfuncs.c:4529
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define fetch_att(T, attbyval, attlen)
Definition: tupmacs.h:75
int i
ArrayType * construct_md_array(Datum *elems, bool *nulls, int ndims, int *dims, int *lbs, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3348
#define ARR_ELEMTYPE(a)
Definition: array.h:280
ArrayType * arr
Definition: arrayfuncs.c:71

◆ array_larger()

Datum array_larger ( PG_FUNCTION_ARGS  )

Definition at line 5605 of file arrayfuncs.c.

References array_cmp(), PG_GETARG_DATUM, and PG_RETURN_DATUM.

5606 {
5607  if (array_cmp(fcinfo) > 0)
5609  else
5611 }
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3768
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:352

◆ array_le()

Datum array_le ( PG_FUNCTION_ARGS  )

Definition at line 3744 of file arrayfuncs.c.

References array_cmp(), and PG_RETURN_BOOL.

3745 {
3746  PG_RETURN_BOOL(array_cmp(fcinfo) <= 0);
3747 }
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3768
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:358

◆ array_length()

Datum array_length ( PG_FUNCTION_ARGS  )

Definition at line 1784 of file arrayfuncs.c.

References AARR_DIMS, AARR_NDIM, MAXDIM, PG_GETARG_ANY_ARRAY_P, PG_GETARG_INT32, PG_RETURN_INT32, and PG_RETURN_NULL.

1785 {
1787  int reqdim = PG_GETARG_INT32(1);
1788  int *dimv;
1789  int result;
1790 
1791  /* Sanity check: does it look like an array at all? */
1792  if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
1793  PG_RETURN_NULL();
1794 
1795  /* Sanity check: was the requested dim valid */
1796  if (reqdim <= 0 || reqdim > AARR_NDIM(v))
1797  PG_RETURN_NULL();
1798 
1799  dimv = AARR_DIMS(v);
1800 
1801  result = dimv[reqdim - 1];
1802 
1803  PG_RETURN_INT32(result);
1804 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:262
#define MAXDIM
Definition: c.h:543
#define PG_RETURN_INT32(x)
Definition: fmgr.h:353
#define AARR_DIMS(a)
Definition: array.h:326
#define AARR_NDIM(a)
Definition: array.h:316
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ array_lower()

Datum array_lower ( PG_FUNCTION_ARGS  )

Definition at line 1727 of file arrayfuncs.c.

References AARR_LBOUND, AARR_NDIM, MAXDIM, PG_GETARG_ANY_ARRAY_P, PG_GETARG_INT32, PG_RETURN_INT32, and PG_RETURN_NULL.

1728 {
1730  int reqdim = PG_GETARG_INT32(1);
1731  int *lb;
1732  int result;
1733 
1734  /* Sanity check: does it look like an array at all? */
1735  if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
1736  PG_RETURN_NULL();
1737 
1738  /* Sanity check: was the requested dim valid */
1739  if (reqdim <= 0 || reqdim > AARR_NDIM(v))
1740  PG_RETURN_NULL();
1741 
1742  lb = AARR_LBOUND(v);
1743  result = lb[reqdim - 1];
1744 
1745  PG_RETURN_INT32(result);
1746 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:262
#define MAXDIM
Definition: c.h:543
#define PG_RETURN_INT32(x)
Definition: fmgr.h:353
#define AARR_LBOUND(a)
Definition: array.h:329
#define AARR_NDIM(a)
Definition: array.h:316
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ array_lt()

Datum array_lt ( PG_FUNCTION_ARGS  )

Definition at line 3732 of file arrayfuncs.c.

References array_cmp(), and PG_RETURN_BOOL.

3733 {
3734  PG_RETURN_BOOL(array_cmp(fcinfo) < 0);
3735 }
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3768
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:358

◆ array_map()

Datum array_map ( Datum  arrayd,
ExprState exprstate,
ExprContext econtext,
Oid  retType,
ArrayMapState amstate 
)

Definition at line 3153 of file arrayfuncs.c.

References AARR_DIMS, AARR_ELEMTYPE, AARR_LBOUND, AARR_NDIM, AllocSizeIsValid, ARR_DIMS, ARR_LBOUND, ARR_OVERHEAD_NONULLS, ARR_OVERHEAD_WITHNULLS, array_iter_next(), array_iter_setup(), ArrayGetNItems(), att_addlength_datum, att_align_nominal, construct_empty_array(), CopyArrayEls(), ArrayType::dataoffset, DatumGetAnyArrayP(), ArrayMetaState::element_type, ArrayType::elemtype, ereport, errcode(), errmsg(), ERROR, ExecEvalExpr(), get_typlenbyvalalign(), i, ExprState::innermost_casenull, ExprState::innermost_caseval, ArrayMapState::inp_extra, MaxAllocSize, ArrayType::ndim, ArrayIteratorData::nitems, palloc(), palloc0(), pfree(), PG_DETOAST_DATUM, PointerGetDatum, ArrayMapState::ret_extra, SET_VARSIZE, ArrayIteratorData::typalign, ArrayMetaState::typalign, ArrayIteratorData::typbyval, ArrayMetaState::typbyval, ArrayIteratorData::typlen, ArrayMetaState::typlen, and values.

Referenced by ExecEvalArrayCoerce().

3156 {
3157  AnyArrayType *v = DatumGetAnyArrayP(arrayd);
3158  ArrayType *result;
3159  Datum *values;
3160  bool *nulls;
3161  int *dim;
3162  int ndim;
3163  int nitems;
3164  int i;
3165  int32 nbytes = 0;
3166  int32 dataoffset;
3167  bool hasnulls;
3168  Oid inpType;
3169  int inp_typlen;
3170  bool inp_typbyval;
3171  char inp_typalign;
3172  int typlen;
3173  bool typbyval;
3174  char typalign;
3175  array_iter iter;
3176  ArrayMetaState *inp_extra;
3177  ArrayMetaState *ret_extra;
3178  Datum *transform_source = exprstate->innermost_caseval;
3179  bool *transform_source_isnull = exprstate->innermost_casenull;
3180 
3181  inpType = AARR_ELEMTYPE(v);
3182  ndim = AARR_NDIM(v);
3183  dim = AARR_DIMS(v);
3184  nitems = ArrayGetNItems(ndim, dim);
3185 
3186  /* Check for empty array */
3187  if (nitems <= 0)
3188  {
3189  /* Return empty array */
3190  return PointerGetDatum(construct_empty_array(retType));
3191  }
3192 
3193  /*
3194  * We arrange to look up info about input and return element types only
3195  * once per series of calls, assuming the element type doesn't change
3196  * underneath us.
3197  */
3198  inp_extra = &amstate->inp_extra;
3199  ret_extra = &amstate->ret_extra;
3200 
3201  if (inp_extra->element_type != inpType)
3202  {
3203  get_typlenbyvalalign(inpType,
3204  &inp_extra->typlen,
3205  &inp_extra->typbyval,
3206  &inp_extra->typalign);
3207  inp_extra->element_type = inpType;
3208  }
3209  inp_typlen = inp_extra->typlen;
3210  inp_typbyval = inp_extra->typbyval;
3211  inp_typalign = inp_extra->typalign;
3212 
3213  if (ret_extra->element_type != retType)
3214  {
3215  get_typlenbyvalalign(retType,
3216  &ret_extra->typlen,
3217  &ret_extra->typbyval,
3218  &ret_extra->typalign);
3219  ret_extra->element_type = retType;
3220  }
3221  typlen = ret_extra->typlen;
3222  typbyval = ret_extra->typbyval;
3223  typalign = ret_extra->typalign;
3224 
3225  /* Allocate temporary arrays for new values */
3226  values = (Datum *) palloc(nitems * sizeof(Datum));
3227  nulls = (bool *) palloc(nitems * sizeof(bool));
3228 
3229  /* Loop over source data */
3230  array_iter_setup(&iter, v);
3231  hasnulls = false;
3232 
3233  for (i = 0; i < nitems; i++)
3234  {
3235  /* Get source element, checking for NULL */
3236  *transform_source =
3237  array_iter_next(&iter, transform_source_isnull, i,
3238  inp_typlen, inp_typbyval, inp_typalign);
3239 
3240  /* Apply the given expression to source element */
3241  values[i] = ExecEvalExpr(exprstate, econtext, &nulls[i]);
3242 
3243  if (nulls[i])
3244  hasnulls = true;
3245  else
3246  {
3247  /* Ensure data is not toasted */
3248  if (typlen == -1)
3249  values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
3250  /* Update total result size */
3251  nbytes = att_addlength_datum(nbytes, typlen, values[i]);
3252  nbytes = att_align_nominal(nbytes, typalign);
3253  /* check for overflow of total request */
3254  if (!AllocSizeIsValid(nbytes))
3255  ereport(ERROR,
3256  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3257  errmsg("array size exceeds the maximum allowed (%d)",
3258  (int) MaxAllocSize)));
3259  }
3260  }
3261 
3262  /* Allocate and fill the result array */
3263  if (hasnulls)
3264  {
3265  dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
3266  nbytes += dataoffset;
3267  }
3268  else
3269  {
3270  dataoffset = 0; /* marker for no null bitmap */
3271  nbytes += ARR_OVERHEAD_NONULLS(ndim);
3272  }
3273  result = (ArrayType *) palloc0(nbytes);
3274  SET_VARSIZE(result, nbytes);
3275  result->ndim = ndim;
3276  result->dataoffset = dataoffset;
3277  result->elemtype = retType;
3278  memcpy(ARR_DIMS(result), AARR_DIMS(v), ndim * sizeof(int));
3279  memcpy(ARR_LBOUND(result), AARR_LBOUND(v), ndim * sizeof(int));
3280 
3281  CopyArrayEls(result,
3282  values, nulls, nitems,
3283  typlen, typbyval, typalign,
3284  false);
3285 
3286  /*
3287  * Note: do not risk trying to pfree the results of the called expression
3288  */
3289  pfree(values);
3290  pfree(nulls);
3291 
3292  return PointerGetDatum(result);
3293 }
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:298
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
static Datum array_iter_next(array_iter *it, bool *isnull, int i, int elmlen, bool elmbyval, char elmalign)
Definition: arrayaccess.h:81
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2159
#define PointerGetDatum(X)
Definition: postgres.h:556
bool * innermost_casenull
Definition: execnodes.h:111
int32 dataoffset
Definition: array.h:84
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:610
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3432
unsigned int Oid
Definition: postgres_ext.h:31
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:300
signed int int32
Definition: c.h:363
AnyArrayType * DatumGetAnyArrayP(Datum d)
#define ARR_LBOUND(a)
Definition: array.h:284
bool typbyval
Definition: array.h:228
void pfree(void *pointer)
Definition: mcxt.c:1057
char typalign
Definition: pg_type.h:170
#define ERROR
Definition: elog.h:43
Oid elemtype
Definition: array.h:85
#define ARR_DIMS(a)
Definition: array.h:282
ArrayMetaState inp_extra
Definition: array.h:241
int16 typlen
Definition: array.h:227
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:289
static void array_iter_setup(array_iter *it, AnyArrayType *a)
Definition: arrayaccess.h:49
Datum * innermost_caseval
Definition: execnodes.h:110
#define AllocSizeIsValid(size)
Definition: memutils.h:42
#define MaxAllocSize
Definition: memutils.h:40
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
#define AARR_DIMS(a)
Definition: array.h:326
#define AARR_ELEMTYPE(a)
Definition: array.h:323
#define ereport(elevel,...)
Definition: elog.h:144
#define AARR_LBOUND(a)
Definition: array.h:329
#define AARR_NDIM(a)
Definition: array.h:316
ArrayMetaState ret_extra
Definition: array.h:242
void CopyArrayEls(ArrayType *array, Datum *values, bool *nulls, int nitems, int typlen, bool typbyval, char typalign, bool freedata)
Definition: arrayfuncs.c:958
char typalign
Definition: array.h:229
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define att_addlength_datum(cur_offset, attlen, attdatum)
Definition: tupmacs.h:164
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
int i
Oid element_type
Definition: array.h:226
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329
int ndim
Definition: array.h:83

◆ array_ndims()

Datum array_ndims ( PG_FUNCTION_ARGS  )

Definition at line 1673 of file arrayfuncs.c.

References AARR_NDIM, MAXDIM, PG_GETARG_ANY_ARRAY_P, PG_RETURN_INT32, and PG_RETURN_NULL.

1674 {
1676 
1677  /* Sanity check: does it look like an array at all? */
1678  if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
1679  PG_RETURN_NULL();
1680 
1682 }
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:262
#define MAXDIM
Definition: c.h:543
#define PG_RETURN_INT32(x)
Definition: fmgr.h:353
#define AARR_NDIM(a)
Definition: array.h:316
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ array_ne()

Datum array_ne ( PG_FUNCTION_ARGS  )

Definition at line 3726 of file arrayfuncs.c.

References array_eq(), DatumGetBool, and PG_RETURN_BOOL.

3727 {
3729 }
#define DatumGetBool(X)
Definition: postgres.h:393
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:358
Datum array_eq(PG_FUNCTION_ARGS)
Definition: arrayfuncs.c:3597

◆ array_nelems_size()

static int array_nelems_size ( char *  ptr,
int  offset,
bits8 nullbitmap,
int  nitems,
int  typlen,
bool  typbyval,
char  typalign 
)
static

Definition at line 4662 of file arrayfuncs.c.

References array_seek().

Referenced by array_copy(), and array_set_slice().

4664 {
4665  return array_seek(ptr, offset, nullbitmap, nitems,
4666  typlen, typbyval, typalign) - ptr;
4667 }
char typalign
Definition: pg_type.h:170
static char * array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4614

◆ array_out()

Datum array_out ( PG_FUNCTION_ARGS  )

Definition at line 1013 of file arrayfuncs.c.

References AARR_DIMS, AARR_ELEMTYPE, AARR_LBOUND, AARR_NDIM, APPENDCHAR, APPENDSTR, array_isspace(), array_iter_next(), array_iter_setup(), ArrayGetNItems(), Assert, ASSGN, ArrayMetaState::element_type, fmgr_info_cxt(), FmgrInfo::fn_mcxt, get_type_io_data(), i, IOFunc_output, MAXDIM, MemoryContextAlloc(), ArrayIteratorData::nitems, OutputFunctionCall(), palloc(), pfree(), PG_GETARG_ANY_ARRAY_P, PG_RETURN_CSTRING, pg_strcasecmp(), ArrayMetaState::proc, pstrdup(), sprintf, ArrayIteratorData::typalign, ArrayMetaState::typalign, ArrayIteratorData::typbyval, ArrayMetaState::typbyval, ArrayMetaState::typdelim, ArrayMetaState::typiofunc, ArrayMetaState::typioparam, ArrayIteratorData::typlen, ArrayMetaState::typlen, and values.

Referenced by anyarray_out(), and anycompatiblearray_out().

1014 {
1016  Oid element_type = AARR_ELEMTYPE(v);
1017  int typlen;
1018  bool typbyval;
1019  char typalign;
1020  char typdelim;
1021  char *p,
1022  *tmp,
1023  *retval,
1024  **values,
1025  dims_str[(MAXDIM * 33) + 2];
1026 
1027  /*
1028  * 33 per dim since we assume 15 digits per number + ':' +'[]'
1029  *
1030  * +2 allows for assignment operator + trailing null
1031  */
1032  bool *needquotes,
1033  needdims = false;
1034  size_t overall_length;
1035  int nitems,
1036  i,
1037  j,
1038  k,
1039  indx[MAXDIM];
1040  int ndim,
1041  *dims,
1042  *lb;
1043  array_iter iter;
1044  ArrayMetaState *my_extra;
1045 
1046  /*
1047  * We arrange to look up info about element type, including its output
1048  * conversion proc, only once per series of calls, assuming the element
1049  * type doesn't change underneath us.
1050  */
1051  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1052  if (my_extra == NULL)
1053  {
1054  fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1055  sizeof(ArrayMetaState));
1056  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1057  my_extra->element_type = ~element_type;
1058  }
1059 
1060  if (my_extra->element_type != element_type)
1061  {
1062  /*
1063  * Get info about element type, including its output conversion proc
1064  */
1065  get_type_io_data(element_type, IOFunc_output,
1066  &my_extra->typlen, &my_extra->typbyval,
1067  &my_extra->typalign, &my_extra->typdelim,
1068  &my_extra->typioparam, &my_extra->typiofunc);
1069  fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
1070  fcinfo->flinfo->fn_mcxt);
1071  my_extra->element_type = element_type;
1072  }
1073  typlen = my_extra->typlen;
1074  typbyval = my_extra->typbyval;
1075  typalign = my_extra->typalign;
1076  typdelim = my_extra->typdelim;
1077 
1078  ndim = AARR_NDIM(v);
1079  dims = AARR_DIMS(v);
1080  lb = AARR_LBOUND(v);
1081  nitems = ArrayGetNItems(ndim, dims);
1082 
1083  if (nitems == 0)
1084  {
1085  retval = pstrdup("{}");
1086  PG_RETURN_CSTRING(retval);
1087  }
1088 
1089  /*
1090  * we will need to add explicit dimensions if any dimension has a lower
1091  * bound other than one
1092  */
1093  for (i = 0; i < ndim; i++)
1094  {
1095  if (lb[i] != 1)
1096  {
1097  needdims = true;
1098  break;
1099  }
1100  }
1101 
1102  /*
1103  * Convert all values to string form, count total space needed (including
1104  * any overhead such as escaping backslashes), and detect whether each
1105  * item needs double quotes.
1106  */
1107  values = (char **) palloc(nitems * sizeof(char *));
1108  needquotes = (bool *) palloc(nitems * sizeof(bool));
1109  overall_length = 0;
1110 
1111  array_iter_setup(&iter, v);
1112 
1113  for (i = 0; i < nitems; i++)
1114  {
1115  Datum itemvalue;
1116  bool isnull;
1117  bool needquote;
1118 
1119  /* Get source element, checking for NULL */
1120  itemvalue = array_iter_next(&iter, &isnull, i,
1121  typlen, typbyval, typalign);
1122 
1123  if (isnull)
1124  {
1125  values[i] = pstrdup("NULL");
1126  overall_length += 4;
1127  needquote = false;
1128  }
1129  else
1130  {
1131  values[i] = OutputFunctionCall(&my_extra->proc, itemvalue);
1132 
1133  /* count data plus backslashes; detect chars needing quotes */
1134  if (values[i][0] == '\0')
1135  needquote = true; /* force quotes for empty string */
1136  else if (pg_strcasecmp(values[i], "NULL") == 0)
1137  needquote = true; /* force quotes for literal NULL */
1138  else
1139  needquote = false;
1140 
1141  for (tmp = values[i]; *tmp != '\0'; tmp++)
1142  {
1143  char ch = *tmp;
1144 
1145  overall_length += 1;
1146  if (ch == '"' || ch == '\\')
1147  {
1148  needquote = true;
1149  overall_length += 1;
1150  }
1151  else if (ch == '{' || ch == '}' || ch == typdelim ||
1152  array_isspace(ch))
1153  needquote = true;
1154  }
1155  }
1156 
1157  needquotes[i] = needquote;
1158 
1159  /* Count the pair of double quotes, if needed */
1160  if (needquote)
1161  overall_length += 2;
1162  /* and the comma (or other typdelim delimiter) */
1163  overall_length += 1;
1164  }
1165 
1166  /*
1167  * The very last array element doesn't have a typdelim delimiter after it,
1168  * but that's OK; that space is needed for the trailing '\0'.
1169  *
1170  * Now count total number of curly brace pairs in output string.
1171  */
1172  for (i = j = 0, k = 1; i < ndim; i++)
1173  {
1174  j += k, k *= dims[i];
1175  }
1176  overall_length += 2 * j;
1177 
1178  /* Format explicit dimensions if required */
1179  dims_str[0] = '\0';
1180  if (needdims)
1181  {
1182  char *ptr = dims_str;
1183 
1184  for (i = 0; i < ndim; i++)
1185  {
1186  sprintf(ptr, "[%d:%d]", lb[i], lb[i] + dims[i] - 1);
1187  ptr += strlen(ptr);
1188  }
1189  *ptr++ = *ASSGN;
1190  *ptr = '\0';
1191  overall_length += ptr - dims_str;
1192  }
1193 
1194  /* Now construct the output string */
1195  retval = (char *) palloc(overall_length);
1196  p = retval;
1197 
1198 #define APPENDSTR(str) (strcpy(p, (str)), p += strlen(p))
1199 #define APPENDCHAR(ch) (*p++ = (ch), *p = '\0')
1200 
1201  if (needdims)
1202  APPENDSTR(dims_str);
1203  APPENDCHAR('{');
1204  for (i = 0; i < ndim; i++)
1205  indx[i] = 0;
1206  j = 0;
1207  k = 0;
1208  do
1209  {
1210  for (i = j; i < ndim - 1; i++)
1211  APPENDCHAR('{');
1212 
1213  if (needquotes[k])
1214  {
1215  APPENDCHAR('"');
1216  for (tmp = values[k]; *tmp; tmp++)
1217  {
1218  char ch = *tmp;
1219 
1220  if (ch == '"' || ch == '\\')
1221  *p++ = '\\';
1222  *p++ = ch;
1223  }
1224  *p = '\0';
1225  APPENDCHAR('"');
1226  }
1227  else
1228  APPENDSTR(values[k]);
1229  pfree(values[k++]);
1230 
1231  for (i = ndim - 1; i >= 0; i--)
1232  {
1233  if (++(indx[i]) < dims[i])
1234  {
1235  APPENDCHAR(typdelim);
1236  break;
1237  }
1238  else
1239  {
1240  indx[i] = 0;
1241  APPENDCHAR('}');
1242  }
1243  }
1244  j = i;
1245  } while (j != -1);
1246 
1247 #undef APPENDSTR
1248 #undef APPENDCHAR
1249 
1250  /* Assert that we calculated the string length accurately */
1251  Assert(overall_length == (p - retval + 1));
1252 
1253  pfree(values);
1254  pfree(needquotes);
1255 
1256  PG_RETURN_CSTRING(retval);
1257 }
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:262
static bool array_isspace(char ch)
Definition: arrayfuncs.c:433
MemoryContext fn_mcxt
Definition: fmgr.h:65
#define MAXDIM
Definition: c.h:543
static Datum array_iter_next(array_iter *it, bool *isnull, int i, int elmlen, bool elmbyval, char elmalign)
Definition: arrayaccess.h:81
char * pstrdup(const char *in)
Definition: mcxt.c:1187
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
unsigned int Oid
Definition: postgres_ext.h:31
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1577
bool typbyval
Definition: array.h:228
#define sprintf
Definition: port.h:217
void pfree(void *pointer)
Definition: mcxt.c:1057
char typalign
Definition: pg_type.h:170
#define APPENDCHAR(ch)
#define APPENDSTR(str)
int16 typlen
Definition: array.h:227
char typdelim
Definition: array.h:230
static void array_iter_setup(array_iter *it, AnyArrayType *a)
Definition: arrayaccess.h:49
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
#define ASSGN
Definition: arrayfuncs.c:46
uintptr_t Datum
Definition: postgres.h:367
#define AARR_DIMS(a)
Definition: array.h:326
#define AARR_ELEMTYPE(a)
Definition: array.h:323
#define AARR_LBOUND(a)
Definition: array.h:329
#define Assert(condition)
Definition: c.h:746
Oid typioparam
Definition: array.h:231
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:361
#define AARR_NDIM(a)
Definition: array.h:316
Oid typiofunc
Definition: array.h:232
char typalign
Definition: array.h:229
static Datum values[MAXATTR]
Definition: bootstrap.c:165
void * palloc(Size size)
Definition: mcxt.c:950
FmgrInfo proc
Definition: array.h:233
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
int i
Oid element_type
Definition: array.h:226
void get_type_io_data(Oid typid, IOFuncSelector which_func, int16 *typlen, bool *typbyval, char *typalign, char *typdelim, Oid *typioparam, Oid *func)
Definition: lsyscache.c:2213

◆ array_recv()

Datum array_recv ( PG_FUNCTION_ARGS  )

Definition at line 1268 of file arrayfuncs.c.

References ARR_DIMS, ARR_LBOUND, ARR_OVERHEAD_NONULLS, ARR_OVERHEAD_WITHNULLS, ArrayGetNItems(), buf, construct_empty_array(), CopyArrayEls(), ArrayType::dataoffset, ArrayMetaState::element_type, ArrayType::elemtype, ereport, errcode(), errmsg(), ERROR, FirstGenbkiObjectId, fmgr_info_cxt(), FmgrInfo::fn_mcxt, FORMAT_TYPE_ALLOW_INVALID, format_type_be(), format_type_extended(), get_type_io_data(), i, IOFunc_receive, MAXDIM, MemoryContextAlloc(), ArrayType::ndim, ArrayIteratorData::nitems, OidIsValid, palloc(), palloc0(), pfree(), PG_GETARG_INT32, PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_ARRAYTYPE_P, pq_getmsgint(), ArrayMetaState::proc, ReadArrayBinary(), SET_VARSIZE, ArrayIteratorData::typalign, ArrayMetaState::typalign, ArrayIteratorData::typbyval, ArrayMetaState::typbyval, ArrayMetaState::typdelim, ArrayMetaState::typiofunc, ArrayMetaState::typioparam, ArrayIteratorData::typlen, and ArrayMetaState::typlen.

Referenced by int2vectorrecv(), and oidvectorrecv().

1269 {
1271  Oid spec_element_type = PG_GETARG_OID(1); /* type of an array
1272  * element */
1273  int32 typmod = PG_GETARG_INT32(2); /* typmod for array elements */
1274  Oid element_type;
1275  int typlen;
1276  bool typbyval;
1277  char typalign;
1278  Oid typioparam;
1279  int i,
1280  nitems;
1281  Datum *dataPtr;
1282  bool *nullsPtr;
1283  bool hasnulls;
1284  int32 nbytes;
1285  int32 dataoffset;
1286  ArrayType *retval;
1287  int ndim,
1288  flags,
1289  dim[MAXDIM],
1290  lBound[MAXDIM];
1291  ArrayMetaState *my_extra;
1292 
1293  /* Get the array header information */
1294  ndim = pq_getmsgint(buf, 4);
1295  if (ndim < 0) /* we do allow zero-dimension arrays */
1296  ereport(ERROR,
1297  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1298  errmsg("invalid number of dimensions: %d", ndim)));
1299  if (ndim > MAXDIM)
1300  ereport(ERROR,
1301  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1302  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
1303  ndim, MAXDIM)));
1304 
1305  flags = pq_getmsgint(buf, 4);
1306  if (flags != 0 && flags != 1)
1307  ereport(ERROR,
1308  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1309  errmsg("invalid array flags")));
1310 
1311  /* Check element type recorded in the data */
1312  element_type = pq_getmsgint(buf, sizeof(Oid));
1313 
1314  /*
1315  * From a security standpoint, it doesn't matter whether the input's
1316  * element type matches what we expect: the element type's receive
1317  * function has to be robust enough to cope with invalid data. However,
1318  * from a user-friendliness standpoint, it's nicer to complain about type
1319  * mismatches than to throw "improper binary format" errors. But there's
1320  * a problem: only built-in types have OIDs that are stable enough to
1321  * believe that a mismatch is a real issue. So complain only if both OIDs
1322  * are in the built-in range. Otherwise, carry on with the element type
1323  * we "should" be getting.
1324  */
1325  if (element_type != spec_element_type)
1326  {
1327  if (element_type < FirstGenbkiObjectId &&
1328  spec_element_type < FirstGenbkiObjectId)
1329  ereport(ERROR,
1330  (errcode(ERRCODE_DATATYPE_MISMATCH),
1331  errmsg("binary data has array element type %u (%s) instead of expected %u (%s)",
1332  element_type,
1333  format_type_extended(element_type, -1,
1335  spec_element_type,
1336  format_type_extended(spec_element_type, -1,
1338  element_type = spec_element_type;
1339  }
1340 
1341  for (i = 0; i < ndim; i++)
1342  {
1343  dim[i] = pq_getmsgint(buf, 4);
1344  lBound[i] = pq_getmsgint(buf, 4);
1345 
1346  /*
1347  * Check overflow of upper bound. (ArrayGetNItems() below checks that
1348  * dim[i] >= 0)
1349  */
1350  if (dim[i] != 0)
1351  {
1352  int ub = lBound[i] + dim[i] - 1;
1353 
1354  if (lBound[i] > ub)
1355  ereport(ERROR,
1356  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1357  errmsg("integer out of range")));
1358  }
1359  }
1360 
1361  /* This checks for overflow of array dimensions */
1362  nitems = ArrayGetNItems(ndim, dim);
1363 
1364  /*
1365  * We arrange to look up info about element type, including its receive
1366  * conversion proc, only once per series of calls, assuming the element
1367  * type doesn't change underneath us.
1368  */
1369  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1370  if (my_extra == NULL)
1371  {
1372  fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1373  sizeof(ArrayMetaState));
1374  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1375  my_extra->element_type = ~element_type;
1376  }
1377 
1378  if (my_extra->element_type != element_type)
1379  {
1380  /* Get info about element type, including its receive proc */
1381  get_type_io_data(element_type, IOFunc_receive,
1382  &my_extra->typlen, &my_extra->typbyval,
1383  &my_extra->typalign, &my_extra->typdelim,
1384  &my_extra->typioparam, &my_extra->typiofunc);
1385  if (!OidIsValid(my_extra->typiofunc))
1386  ereport(ERROR,
1387  (errcode(ERRCODE_UNDEFINED_FUNCTION),
1388  errmsg("no binary input function available for type %s",
1389  format_type_be(element_type))));
1390  fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
1391  fcinfo->flinfo->fn_mcxt);
1392  my_extra->element_type = element_type;
1393  }
1394 
1395  if (nitems == 0)
1396  {
1397  /* Return empty array ... but not till we've validated element_type */
1399  }
1400 
1401  typlen = my_extra->typlen;
1402  typbyval = my_extra->typbyval;
1403  typalign = my_extra->typalign;
1404  typioparam = my_extra->typioparam;
1405 
1406  dataPtr = (Datum *) palloc(nitems * sizeof(Datum));
1407  nullsPtr = (bool *) palloc(nitems * sizeof(bool));
1408  ReadArrayBinary(buf, nitems,
1409  &my_extra->proc, typioparam, typmod,
1410  typlen, typbyval, typalign,
1411  dataPtr, nullsPtr,
1412  &hasnulls, &nbytes);
1413  if (hasnulls)
1414  {
1415  dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
1416  nbytes += dataoffset;
1417  }
1418  else
1419  {
1420  dataoffset = 0; /* marker for no null bitmap */
1421  nbytes += ARR_OVERHEAD_NONULLS(ndim);
1422  }
1423  retval = (ArrayType *) palloc0(nbytes);
1424  SET_VARSIZE(retval, nbytes);
1425  retval->ndim = ndim;
1426  retval->dataoffset = dataoffset;
1427  retval->elemtype = element_type;
1428  memcpy(ARR_DIMS(retval), dim, ndim * sizeof(int));
1429  memcpy(ARR_LBOUND(retval), lBound, ndim * sizeof(int));
1430 
1431  CopyArrayEls(retval,
1432  dataPtr, nullsPtr, nitems,
1433  typlen, typbyval, typalign,
1434  true);
1435 
1436  pfree(dataPtr);
1437  pfree(nullsPtr);
1438 
1439  PG_RETURN_ARRAYTYPE_P(retval);
1440 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:298
MemoryContext fn_mcxt
Definition: fmgr.h:65
#define MAXDIM
Definition: c.h:543
int32 dataoffset
Definition: array.h:84
StringInfoData * StringInfo
Definition: stringinfo.h:44
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3432
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:300
signed int int32
Definition: c.h:363
#define ARR_LBOUND(a)
Definition: array.h:284
bool typbyval
Definition: array.h:228
void pfree(void *pointer)
Definition: mcxt.c:1057
char typalign
Definition: pg_type.h:170
#define ERROR
Definition: elog.h:43
Oid elemtype
Definition: array.h:85
#define ARR_DIMS(a)
Definition: array.h:282
int16 typlen
Definition: array.h:227
static char * buf
Definition: pg_test_fsync.c:68
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
char typdelim
Definition: array.h:230
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:253
static void ReadArrayBinary(StringInfo buf, int nitems, FmgrInfo *receiveproc, Oid typioparam, int32 typmod, int typlen, bool typbyval, char typalign, Datum *values, bool *nulls, bool *hasnulls, int32 *nbytes)
Definition: arrayfuncs.c:1464
#define FORMAT_TYPE_ALLOW_INVALID
Definition: builtins.h:113
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:144
Oid typioparam
Definition: array.h:231
char * format_type_extended(Oid type_oid, int32 typemod, bits16 flags)
Definition: format_type.c:111
void CopyArrayEls(ArrayType *array, Datum *values, bool *nulls, int nitems, int typlen, bool typbyval, char typalign, bool freedata)
Definition: arrayfuncs.c:958
Oid typiofunc
Definition: array.h:232
char typalign
Definition: array.h:229
#define FirstGenbkiObjectId
Definition: transam.h:188
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
FmgrInfo proc
Definition: array.h:233
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
int i
Oid element_type
Definition: array.h:226
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329
int ndim
Definition: array.h:83
void get_type_io_data(Oid typid, IOFuncSelector which_func, int16 *typlen, bool *typbyval, char *typalign, char *typdelim, Oid *typioparam, Oid *func)
Definition: lsyscache.c:2213

◆ array_ref()

Datum array_ref ( ArrayType array,
int  nSubscripts,
int *  indx,
int  arraytyplen,
int  elmlen,
bool  elmbyval,
char  elmalign,
bool isNull 
)

Definition at line 3098 of file arrayfuncs.c.

References array_get_element(), and PointerGetDatum.

Referenced by GUCArrayAdd(), GUCArrayDelete(), GUCArrayReset(), pg_get_functiondef(), and ProcessGUCArray().

3101 {
3102  return array_get_element(PointerGetDatum(array), nSubscripts, indx,
3103  arraytyplen, elmlen, elmbyval, elmalign,
3104  isNull);
3105 }
#define PointerGetDatum(X)
Definition: postgres.h:556
Datum array_get_element(Datum arraydatum, int nSubscripts, int *indx, int arraytyplen, int elmlen, bool elmbyval, char elmalign, bool *isNull)
Definition: arrayfuncs.c:1841

◆ array_remove()

Datum array_remove ( PG_FUNCTION_ARGS  )

Definition at line 6352 of file arrayfuncs.c.

References array_replace_internal(), PG_ARGISNULL, PG_GET_COLLATION, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_RETURN_ARRAYTYPE_P, and PG_RETURN_NULL.

6353 {
6354  ArrayType *array;
6355  Datum search = PG_GETARG_DATUM(1);
6356  bool search_isnull = PG_ARGISNULL(1);
6357 
6358  if (PG_ARGISNULL(0))
6359  PG_RETURN_NULL();
6360  array = PG_GETARG_ARRAYTYPE_P(0);
6361 
6362  array = array_replace_internal(array,
6363  search, search_isnull,
6364  (Datum) 0, true,
6365  true, PG_GET_COLLATION(),
6366  fcinfo);
6367  PG_RETURN_ARRAYTYPE_P(array);
6368 }
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define PG_GET_COLLATION()
Definition: fmgr.h:198
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:251
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:253
uintptr_t Datum
Definition: postgres.h:367
static ArrayType * array_replace_internal(ArrayType *array, Datum search, bool search_isnull, Datum replace, bool replace_isnull, bool remove, Oid collation, FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:6094
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ array_replace()

Datum array_replace ( PG_FUNCTION_ARGS  )

Definition at line 6374 of file arrayfuncs.c.

References array_replace_internal(), PG_ARGISNULL, PG_GET_COLLATION, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_RETURN_ARRAYTYPE_P, and PG_RETURN_NULL.

6375 {
6376  ArrayType *array;
6377  Datum search = PG_GETARG_DATUM(1);
6378  bool search_isnull = PG_ARGISNULL(1);
6379  Datum replace = PG_GETARG_DATUM(2);
6380  bool replace_isnull = PG_ARGISNULL(2);
6381 
6382  if (PG_ARGISNULL(0))
6383  PG_RETURN_NULL();
6384  array = PG_GETARG_ARRAYTYPE_P(0);
6385 
6386  array = array_replace_internal(array,
6387  search, search_isnull,
6388  replace, replace_isnull,
6389  false, PG_GET_COLLATION(),
6390  fcinfo);
6391  PG_RETURN_ARRAYTYPE_P(array);
6392 }
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define PG_GET_COLLATION()
Definition: fmgr.h:198
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:251
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:253
uintptr_t Datum
Definition: postgres.h:367
static ArrayType * array_replace_internal(ArrayType *array, Datum search, bool search_isnull, Datum replace, bool replace_isnull, bool remove, Oid collation, FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:6094
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ array_replace_internal()

static ArrayType * array_replace_internal ( ArrayType array,
Datum  search,
bool  search_isnull,
Datum  replace,
bool  replace_isnull,
bool  remove,
Oid  collation,
FunctionCallInfo  fcinfo 
)
static

Definition at line 6094 of file arrayfuncs.c.

References AllocSizeIsValid, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_LBOUND, ARR_NDIM, ARR_NULLBITMAP, ARR_OVERHEAD_NONULLS, ARR_OVERHEAD_WITHNULLS, ArrayGetNItems(), att_addlength_datum, att_align_nominal, construct_empty_array(), CopyArrayEls(), ArrayType::dataoffset, DatumGetBool, ArrayType::elemtype, TypeCacheEntry::eq_opr_finfo, ereport, errcode(), errmsg(), ERROR, fetch_att, FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_extra, FmgrInfo::fn_oid, format_type_be(), FunctionCallInvoke, i, InitFunctionCallInfoData, LOCAL_FCINFO, lookup_type_cache(), MaxAllocSize, ArrayType::ndim, ArrayIteratorData::nitems, OidIsValid, palloc(), palloc0(), pfree(), PG_DETOAST_DATUM, PointerGetDatum, SET_VARSIZE, skip, TypeCacheEntry::typalign, ArrayIteratorData::typalign, TypeCacheEntry::typbyval, ArrayIteratorData::typbyval, TypeCacheEntry::type_id, TYPECACHE_EQ_OPR_FINFO, TypeCacheEntry::typlen, ArrayIteratorData::typlen, and values.

Referenced by array_remove(), and array_replace().

6099 {
6100  LOCAL_FCINFO(locfcinfo, 2);
6101  ArrayType *result;
6102  Oid element_type;
6103  Datum *values;
6104  bool *nulls;
6105  int *dim;
6106  int ndim;
6107  int nitems,
6108  nresult;
6109  int i;
6110  int32 nbytes = 0;
6111  int32 dataoffset;
6112  bool hasnulls;
6113  int typlen;
6114  bool typbyval;
6115  char typalign;
6116  char *arraydataptr;
6117  bits8 *bitmap;
6118  int bitmask;
6119  bool changed = false;
6120  TypeCacheEntry *typentry;
6121 
6122  element_type = ARR_ELEMTYPE(array);
6123  ndim = ARR_NDIM(array);
6124  dim = ARR_DIMS(array);
6125  nitems = ArrayGetNItems(ndim, dim);
6126 
6127  /* Return input array unmodified if it is empty */
6128  if (nitems <= 0)
6129  return array;
6130 
6131  /*
6132  * We can't remove elements from multi-dimensional arrays, since the
6133  * result might not be rectangular.
6134  */
6135  if (remove && ndim > 1)
6136  ereport(ERROR,
6137  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6138  errmsg("removing elements from multidimensional arrays is not supported")));
6139 
6140  /*
6141  * We arrange to look up the equality function only once per series of
6142  * calls, assuming the element type doesn't change underneath us.
6143  */
6144  typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
6145  if (typentry == NULL ||
6146  typentry->type_id != element_type)
6147  {
6148  typentry = lookup_type_cache(element_type,
6150  if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
6151  ereport(ERROR,
6152  (errcode(ERRCODE_UNDEFINED_FUNCTION),
6153  errmsg("could not identify an equality operator for type %s",
6154  format_type_be(element_type))));
6155  fcinfo->flinfo->fn_extra = (void *) typentry;
6156  }
6157  typlen = typentry->typlen;
6158  typbyval = typentry->typbyval;
6159  typalign = typentry->typalign;
6160 
6161  /*
6162  * Detoast values if they are toasted. The replacement value must be
6163  * detoasted for insertion into the result array, while detoasting the
6164  * search value only once saves cycles.
6165  */
6166  if (typlen == -1)
6167  {
6168  if (!search_isnull)
6169  search = PointerGetDatum(PG_DETOAST_DATUM(search));
6170  if (!replace_isnull)
6171  replace = PointerGetDatum(PG_DETOAST_DATUM(replace));
6172  }
6173 
6174  /* Prepare to apply the comparison operator */
6175  InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
6176  collation, NULL, NULL);
6177 
6178  /* Allocate temporary arrays for new values */
6179  values = (Datum *) palloc(nitems * sizeof(Datum));
6180  nulls = (bool *) palloc(nitems * sizeof(bool));
6181 
6182  /* Loop over source data */
6183  arraydataptr = ARR_DATA_PTR(array);
6184  bitmap = ARR_NULLBITMAP(array);
6185  bitmask = 1;
6186  hasnulls = false;
6187  nresult = 0;
6188 
6189  for (i = 0; i < nitems; i++)
6190  {
6191  Datum elt;
6192  bool isNull;
6193  bool oprresult;
6194  bool skip = false;
6195 
6196  /* Get source element, checking for NULL */
6197  if (bitmap && (*bitmap & bitmask) == 0)
6198  {
6199  isNull = true;
6200  /* If searching for NULL, we have a match */
6201  if (search_isnull)
6202  {
6203  if (remove)
6204  {
6205  skip = true;
6206  changed = true;
6207  }
6208  else if (!replace_isnull)
6209  {
6210  values[nresult] = replace;
6211  isNull = false;
6212  changed = true;
6213  }
6214  }
6215  }
6216  else
6217  {
6218  isNull = false;
6219  elt = fetch_att(arraydataptr, typbyval, typlen);
6220  arraydataptr = att_addlength_datum(arraydataptr, typlen, elt);
6221  arraydataptr = (char *) att_align_nominal(arraydataptr, typalign);
6222 
6223  if (search_isnull)
6224  {
6225  /* no match possible, keep element */
6226  values[nresult] = elt;
6227  }
6228  else
6229  {
6230  /*
6231  * Apply the operator to the element pair; treat NULL as false
6232  */
6233  locfcinfo->args[0].value = elt;
6234  locfcinfo->args[0].isnull = false;
6235  locfcinfo->args[1].value = search;
6236  locfcinfo->args[1].isnull = false;
6237  locfcinfo->isnull = false;
6238  oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
6239  if (locfcinfo->isnull || !oprresult)
6240  {
6241  /* no match, keep element */
6242  values[nresult] = elt;
6243  }
6244  else
6245  {
6246  /* match, so replace or delete */
6247  changed = true;
6248  if (remove)
6249  skip = true;
6250  else
6251  {
6252  values[nresult] = replace;
6253  isNull = replace_isnull;
6254  }
6255  }
6256  }
6257  }
6258 
6259  if (!skip)
6260  {
6261  nulls[nresult] = isNull;
6262  if (isNull)
6263  hasnulls = true;
6264  else
6265  {
6266  /* Update total result size */
6267  nbytes = att_addlength_datum(nbytes, typlen, values[nresult]);
6268  nbytes = att_align_nominal(nbytes, typalign);
6269  /* check for overflow of total request */
6270  if (!AllocSizeIsValid(nbytes))
6271  ereport(ERROR,
6272  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
6273  errmsg("array size exceeds the maximum allowed (%d)",
6274  (int) MaxAllocSize)));
6275  }
6276  nresult++;
6277  }
6278 
6279  /* advance bitmap pointer if any */
6280  if (bitmap)
6281  {
6282  bitmask <<= 1;
6283  if (bitmask == 0x100)
6284  {
6285  bitmap++;
6286  bitmask = 1;
6287  }
6288  }
6289  }
6290 
6291  /*
6292  * If not changed just return the original array
6293  */
6294  if (!changed)
6295  {
6296  pfree(values);
6297  pfree(nulls);
6298  return array;
6299  }
6300 
6301  /* If all elements were removed return an empty array */
6302  if (nresult == 0)
6303  {
6304  pfree(values);
6305  pfree(nulls);
6306  return construct_empty_array(element_type);
6307  }
6308 
6309  /* Allocate and initialize the result array */
6310  if (hasnulls)
6311  {
6312  dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nresult);
6313  nbytes += dataoffset;
6314  }
6315  else
6316  {
6317  dataoffset = 0; /* marker for no null bitmap */
6318  nbytes += ARR_OVERHEAD_NONULLS(ndim);
6319  }
6320  result = (ArrayType *) palloc0(nbytes);
6321  SET_VARSIZE(result, nbytes);
6322  result->ndim = ndim;
6323  result->dataoffset = dataoffset;
6324  result->elemtype = element_type;
6325  memcpy(ARR_DIMS(result), ARR_DIMS(array), ndim * sizeof(int));
6326  memcpy(ARR_LBOUND(result), ARR_LBOUND(array), ndim * sizeof(int));
6327 
6328  if (remove)
6329  {
6330  /* Adjust the result length */
6331  ARR_DIMS(result)[0] = nresult;
6332  }
6333 
6334  /* Insert data into result array */
6335  CopyArrayEls(result,
6336  values, nulls, nresult,
6337  typlen, typbyval, typalign,
6338  false);
6339 
6340  pfree(values);
6341  pfree(nulls);
6342 
6343  return result;
6344 }
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:298
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
#define PointerGetDatum(X)
Definition: postgres.h:556
#define TYPECACHE_EQ_OPR_FINFO
Definition: typcache.h:135
int32 dataoffset
Definition: array.h:84
static const struct exclude_list_item skip[]
Definition: pg_checksums.c:112
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3432
unsigned int Oid
Definition: postgres_ext.h:31
int16 typlen
Definition: typcache.h:39
bool typbyval
Definition: typcache.h:40
#define OidIsValid(objectId)
Definition: c.h:652
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:300
signed int int32
Definition: c.h:363
#define ARR_LBOUND(a)
Definition: array.h:284
void pfree(void *pointer)
Definition: mcxt.c:1057
char typalign
Definition: pg_type.h:170
#define ERROR
Definition: elog.h:43
Oid elemtype
Definition: array.h:85
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
#define DatumGetBool(X)
Definition: postgres.h:393
#define AllocSizeIsValid(size)
Definition: memutils.h:42
#define MaxAllocSize
Definition: memutils.h:40
uint8 bits8
Definition: c.h:382
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
FmgrInfo * flinfo
Definition: fmgr.h:87
FmgrInfo eq_opr_finfo
Definition: typcache.h:74
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:331
Oid fn_oid
Definition: fmgr.h:59
#define ereport(elevel,...)
Definition: elog.h:144
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
void * fn_extra
Definition: fmgr.h:64
#define ARR_NDIM(a)
Definition: array.h:278
void CopyArrayEls(ArrayType *array, Datum *values, bool *nulls, int nitems, int typlen, bool typbyval, char typalign, bool freedata)
Definition: arrayfuncs.c:958
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define att_addlength_datum(cur_offset, attlen, attdatum)
Definition: tupmacs.h:164
char typalign
Definition: typcache.h:41
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define fetch_att(T, attbyval, attlen)
Definition: tupmacs.h:75
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329
#define ARR_ELEMTYPE(a)
Definition: array.h:280
#define ARR_NULLBITMAP(a)
Definition: array.h:288
int ndim
Definition: array.h:83

◆ array_seek()

static char * array_seek ( char *  ptr,
int  offset,
bits8 nullbitmap,
int  nitems,
int  typlen,
bool  typbyval,
char  typalign 
)
static

Definition at line 4614 of file arrayfuncs.c.

References att_addlength_pointer, att_align_nominal, i, and ArrayIteratorData::nitems.

Referenced by array_extract_slice(), array_get_element(), array_insert_slice(), array_nelems_size(), array_set_element(), and array_slice_size().

4616 {
4617  int bitmask;
4618  int i;
4619 
4620  /* easy if fixed-size elements and no NULLs */
4621  if (typlen > 0 && !nullbitmap)
4622  return ptr + nitems * ((Size) att_align_nominal(typlen, typalign));
4623 
4624  /* seems worth having separate loops for NULL and no-NULLs cases */
4625  if (nullbitmap)
4626  {
4627  nullbitmap += offset / 8;
4628  bitmask = 1 << (offset % 8);
4629 
4630  for (i = 0; i < nitems; i++)
4631  {
4632  if (*nullbitmap & bitmask)
4633  {
4634  ptr = att_addlength_pointer(ptr, typlen, ptr);
4635  ptr = (char *) att_align_nominal(ptr, typalign);
4636  }
4637  bitmask <<= 1;
4638  if (bitmask == 0x100)
4639  {
4640  nullbitmap++;
4641  bitmask = 1;
4642  }
4643  }
4644  }
4645  else
4646  {
4647  for (i = 0; i < nitems; i++)
4648  {
4649  ptr = att_addlength_pointer(ptr, typlen, ptr);
4650  ptr = (char *) att_align_nominal(ptr, typalign);
4651  }
4652  }
4653  return ptr;
4654 }
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
char typalign
Definition: pg_type.h:170
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:176
size_t Size
Definition: c.h:474
int i

◆ array_send()

Datum array_send ( PG_FUNCTION_ARGS  )

Definition at line 1569 of file arrayfuncs.c.

References AARR_DIMS, AARR_ELEMTYPE, AARR_HASNULL, AARR_LBOUND, AARR_NDIM, array_iter_next(), array_iter_setup(), ArrayGetNItems(), buf, ArrayMetaState::element_type, ereport, errcode(), errmsg(), ERROR, fmgr_info_cxt(), FmgrInfo::fn_mcxt, format_type_be(), get_type_io_data(), i, IOFunc_send, MemoryContextAlloc(), ArrayIteratorData::nitems, OidIsValid, pfree(), PG_GETARG_ANY_ARRAY_P, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendbytes(), pq_sendint32(), ArrayMetaState::proc, SendFunctionCall(), ArrayIteratorData::typalign, ArrayMetaState::typalign, ArrayIteratorData::typbyval, ArrayMetaState::typbyval, ArrayMetaState::typdelim, ArrayMetaState::typiofunc, ArrayMetaState::typioparam, ArrayIteratorData::typlen, ArrayMetaState::typlen, VARDATA, VARHDRSZ, and VARSIZE.

Referenced by anyarray_send(), anycompatiblearray_send(), int2vectorsend(), and oidvectorsend().

1570 {
1572  Oid element_type = AARR_ELEMTYPE(v);
1573  int typlen;
1574  bool typbyval;
1575  char typalign;
1576  int nitems,
1577  i;
1578  int ndim,
1579  *dim,
1580  *lb;
1582  array_iter iter;
1583  ArrayMetaState *my_extra;
1584 
1585  /*
1586  * We arrange to look up info about element type, including its send
1587  * conversion proc, only once per series of calls, assuming the element
1588  * type doesn't change underneath us.
1589  */
1590  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1591  if (my_extra == NULL)
1592  {
1593  fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1594  sizeof(ArrayMetaState));
1595  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1596  my_extra->element_type = ~element_type;
1597  }
1598 
1599  if (my_extra->element_type != element_type)
1600  {
1601  /* Get info about element type, including its send proc */
1602  get_type_io_data(element_type, IOFunc_send,
1603  &my_extra->typlen, &my_extra->typbyval,
1604  &my_extra->typalign, &my_extra->typdelim,
1605  &my_extra->typioparam, &my_extra->typiofunc);
1606  if (!OidIsValid(my_extra->typiofunc))
1607  ereport(ERROR,
1608  (errcode(ERRCODE_UNDEFINED_FUNCTION),
1609  errmsg("no binary output function available for type %s",
1610  format_type_be(element_type))));
1611  fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
1612  fcinfo->flinfo->fn_mcxt);
1613  my_extra->element_type = element_type;
1614  }
1615  typlen = my_extra->typlen;
1616  typbyval = my_extra->typbyval;
1617  typalign = my_extra->typalign;
1618 
1619  ndim = AARR_NDIM(v);
1620  dim = AARR_DIMS(v);
1621  lb = AARR_LBOUND(v);
1622  nitems = ArrayGetNItems(ndim, dim);
1623 
1624  pq_begintypsend(&buf);
1625 
1626  /* Send the array header information */
1627  pq_sendint32(&buf, ndim);
1628  pq_sendint32(&buf, AARR_HASNULL(v) ? 1 : 0);
1629  pq_sendint32(&buf, element_type);
1630  for (i = 0; i < ndim; i++)
1631  {
1632  pq_sendint32(&buf, dim[i]);
1633  pq_sendint32(&buf, lb[i]);
1634  }
1635 
1636  /* Send the array elements using the element's own sendproc */
1637  array_iter_setup(&iter, v);
1638 
1639  for (i = 0; i < nitems; i++)
1640  {
1641  Datum itemvalue;
1642  bool isnull;
1643 
1644  /* Get source element, checking for NULL */
1645  itemvalue = array_iter_next(&iter, &isnull, i,
1646  typlen, typbyval, typalign);
1647 
1648  if (isnull)
1649  {
1650  /* -1 length means a NULL */
1651  pq_sendint32(&buf, -1);
1652  }
1653  else
1654  {
1655  bytea *outputbytes;
1656 
1657  outputbytes = SendFunctionCall(&my_extra->proc, itemvalue);
1658  pq_sendint32(&buf, VARSIZE(outputbytes) - VARHDRSZ);
1659  pq_sendbytes(&buf, VARDATA(outputbytes),
1660  VARSIZE(outputbytes) - VARHDRSZ);
1661  pfree(outputbytes);
1662  }
1663  }
1664 
1666 }
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:262
#define VARDATA(PTR)
Definition: postgres.h:302
MemoryContext fn_mcxt
Definition: fmgr.h:65
#define VARSIZE(PTR)
Definition: postgres.h:303
static Datum array_iter_next(array_iter *it, bool *isnull, int i, int elmlen, bool elmbyval, char elmalign)
Definition: arrayaccess.h:81
void pq_begintypsend(StringInfo buf)
Definition: pqformat.c:328
#define VARHDRSZ
Definition: c.h:569
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define AARR_HASNULL(a)
Definition: array.h:319
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define PG_RETURN_BYTEA_P(x)
Definition: fmgr.h:369
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
bytea * pq_endtypsend(StringInfo buf)
Definition: pqformat.c:348
bool typbyval
Definition: array.h:228
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
void pfree(void *pointer)
Definition: mcxt.c:1057
char typalign
Definition: pg_type.h:170
#define ERROR
Definition: elog.h:43
int16 typlen
Definition: array.h:227
static char * buf
Definition: pg_test_fsync.c:68
char typdelim
Definition: array.h:230
static void array_iter_setup(array_iter *it, AnyArrayType *a)
Definition: arrayaccess.h:49
bytea * SendFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1638
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
uintptr_t Datum
Definition: postgres.h:367
#define AARR_DIMS(a)
Definition: array.h:326
#define AARR_ELEMTYPE(a)
Definition: array.h:323
#define ereport(elevel,...)
Definition: elog.h:144
#define AARR_LBOUND(a)
Definition: array.h:329
Oid typioparam
Definition: array.h:231
#define AARR_NDIM(a)
Definition: array.h:316
Oid typiofunc
Definition: array.h:232
char typalign
Definition: array.h:229
void pq_sendbytes(StringInfo buf, const char *data, int datalen)
Definition: pqformat.c:125
int errmsg(const char *fmt,...)
Definition: elog.c:821
FmgrInfo proc
Definition: array.h:233
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
int i
Oid element_type
Definition: array.h:226
Definition: c.h:563
void get_type_io_data(Oid typid, IOFuncSelector which_func, int16 *typlen, bool *typbyval, char *typalign, char *typdelim, Oid *typioparam, Oid *func)
Definition: lsyscache.c:2213

◆ array_set()

ArrayType* array_set ( ArrayType array,
int  nSubscripts,
int *  indx,
Datum  dataValue,
bool  isNull,
int  arraytyplen,
int  elmlen,
bool  elmbyval,
char  elmalign 
)

Definition at line 3115 of file arrayfuncs.c.

References array_set_element(), DatumGetArrayTypeP, and PointerGetDatum.

Referenced by GUCArrayAdd(), GUCArrayDelete(), GUCArrayReset(), and pg_extension_config_dump().

3118 {
3120  nSubscripts, indx,
3121  dataValue, isNull,
3122  arraytyplen,
3123  elmlen, elmbyval, elmalign));
3124 }
#define PointerGetDatum(X)
Definition: postgres.h:556
Datum array_set_element(Datum arraydatum, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:2221
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ array_set_element()

Datum array_set_element ( Datum  arraydatum,
int  nSubscripts,
int *  indx,
Datum  dataValue,
bool  isNull,
int  arraytyplen,
int  elmlen,
bool  elmbyval,
char  elmalign 
)

Definition at line 2221 of file arrayfuncs.c.

References ARR_DATA_OFFSET, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_LBOUND, ARR_NDIM, ARR_NULLBITMAP, ARR_OVERHEAD_NONULLS, ARR_OVERHEAD_WITHNULLS, ARR_SIZE, array_bitmap_copy(), array_get_isnull(), array_seek(), array_set_element_expanded(), array_set_isnull(), ArrayCastAndSet(), ArrayGetNItems(), ArrayGetOffset(), att_addlength_datum, att_addlength_pointer, att_align_nominal, construct_md_array(), ArrayType::dataoffset, DatumGetArrayTypeP, DatumGetPointer, ArrayType::elemtype, ereport, errcode(), errmsg(), ERROR, i, MAXDIM, MemSet, ArrayType::ndim, palloc(), palloc0(), PG_DETOAST_DATUM, PointerGetDatum, SET_VARSIZE, and VARATT_IS_EXTERNAL_EXPANDED.

Referenced by array_append(), array_prepend(), array_set(), exec_assign_value(), and ExecEvalSubscriptingRefAssign().

2230 {
2231  ArrayType *array;
2232  ArrayType *newarray;
2233  int i,
2234  ndim,
2235  dim[MAXDIM],
2236  lb[MAXDIM],
2237  offset;
2238  char *elt_ptr;
2239  bool newhasnulls;
2240  bits8 *oldnullbitmap;
2241  int oldnitems,
2242  newnitems,
2243  olddatasize,
2244  newsize,
2245  olditemlen,
2246  newitemlen,
2247  overheadlen,
2248  oldoverheadlen,
2249  addedbefore,
2250  addedafter,
2251  lenbefore,
2252  lenafter;
2253 
2254  if (arraytyplen > 0)
2255  {
2256  /*
2257  * fixed-length arrays -- these are assumed to be 1-d, 0-based. We
2258  * cannot extend them, either.
2259  */
2260  char *resultarray;
2261 
2262  if (nSubscripts != 1)
2263  ereport(ERROR,
2264  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2265  errmsg("wrong number of array subscripts")));
2266 
2267  if (indx[0] < 0 || indx[0] * elmlen >= arraytyplen)
2268  ereport(ERROR,
2269  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2270  errmsg("array subscript out of range")));
2271 
2272  if (isNull)
2273  ereport(ERROR,
2274  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2275  errmsg("cannot assign null value to an element of a fixed-length array")));
2276 
2277  resultarray = (char *) palloc(arraytyplen);
2278  memcpy(resultarray, DatumGetPointer(arraydatum), arraytyplen);
2279  elt_ptr = (char *) resultarray + indx[0] * elmlen;
2280  ArrayCastAndSet(dataValue, elmlen, elmbyval, elmalign, elt_ptr);
2281  return PointerGetDatum(resultarray);
2282  }
2283 
2284  if (nSubscripts <= 0 || nSubscripts > MAXDIM)
2285  ereport(ERROR,
2286  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2287  errmsg("wrong number of array subscripts")));
2288 
2289  /* make sure item to be inserted is not toasted */
2290  if (elmlen == -1 && !isNull)
2291  dataValue = PointerGetDatum(PG_DETOAST_DATUM(dataValue));
2292 
2294  {
2295  /* expanded array: let's do this in a separate function */
2296  return array_set_element_expanded(arraydatum,
2297  nSubscripts,
2298  indx,
2299  dataValue,
2300  isNull,
2301  arraytyplen,
2302  elmlen,
2303  elmbyval,
2304  elmalign);
2305  }
2306 
2307  /* detoast input array if necessary */
2308  array = DatumGetArrayTypeP(arraydatum);
2309 
2310  ndim = ARR_NDIM(array);
2311 
2312  /*
2313  * if number of dims is zero, i.e. an empty array, create an array with
2314  * nSubscripts dimensions, and set the lower bounds to the supplied
2315  * subscripts
2316  */
2317  if (ndim == 0)
2318  {
2319  Oid elmtype = ARR_ELEMTYPE(array);
2320 
2321  for (i = 0; i < nSubscripts; i++)
2322  {
2323  dim[i] = 1;
2324  lb[i] = indx[i];
2325  }
2326 
2327  return PointerGetDatum(construct_md_array(&dataValue, &isNull,
2328  nSubscripts, dim, lb,
2329  elmtype,
2330  elmlen, elmbyval, elmalign));
2331  }
2332 
2333  if (ndim != nSubscripts)
2334  ereport(ERROR,
2335  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2336  errmsg("wrong number of array subscripts")));
2337 
2338  /* copy dim/lb since we may modify them */
2339  memcpy(dim, ARR_DIMS(array), ndim * sizeof(int));
2340  memcpy(lb, ARR_LBOUND(array), ndim * sizeof(int));
2341 
2342  newhasnulls = (ARR_HASNULL(array) || isNull);
2343  addedbefore = addedafter = 0;
2344 
2345  /*
2346  * Check subscripts
2347  */
2348  if (ndim == 1)
2349  {
2350  if (indx[0] < lb[0])
2351  {
2352  addedbefore = lb[0] - indx[0];
2353  dim[0] += addedbefore;
2354  lb[0] = indx[0];
2355  if (addedbefore > 1)
2356  newhasnulls = true; /* will insert nulls */
2357  }
2358  if (indx[0] >= (dim[0] + lb[0]))
2359  {
2360  addedafter = indx[0] - (dim[0] + lb[0]) + 1;
2361  dim[0] += addedafter;
2362  if (addedafter > 1)
2363  newhasnulls = true; /* will insert nulls */
2364  }
2365  }
2366  else
2367  {
2368  /*
2369  * XXX currently we do not support extending multi-dimensional arrays
2370  * during assignment
2371  */
2372  for (i = 0; i < ndim; i++)
2373  {
2374  if (indx[i] < lb[i] ||
2375  indx[i] >= (dim[i] + lb[i]))
2376  ereport(ERROR,
2377  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2378  errmsg("array subscript out of range")));
2379  }
2380  }
2381 
2382  /*
2383  * Compute sizes of items and areas to copy
2384  */
2385  newnitems = ArrayGetNItems(ndim, dim);
2386  if (newhasnulls)
2387  overheadlen = ARR_OVERHEAD_WITHNULLS(ndim, newnitems);
2388  else
2389  overheadlen = ARR_OVERHEAD_NONULLS(ndim);
2390  oldnitems = ArrayGetNItems(ndim, ARR_DIMS(array));
2391  oldnullbitmap = ARR_NULLBITMAP(array);
2392  oldoverheadlen = ARR_DATA_OFFSET(array);
2393  olddatasize = ARR_SIZE(array) - oldoverheadlen;
2394  if (addedbefore)
2395  {
2396  offset = 0;
2397  lenbefore = 0;
2398  olditemlen = 0;
2399  lenafter = olddatasize;
2400  }
2401  else if (addedafter)
2402  {
2403  offset = oldnitems;
2404  lenbefore = olddatasize;
2405  olditemlen = 0;
2406  lenafter = 0;
2407  }
2408  else
2409  {
2410  offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
2411  elt_ptr = array_seek(ARR_DATA_PTR(array), 0, oldnullbitmap, offset,
2412  elmlen, elmbyval, elmalign);
2413  lenbefore = (int) (elt_ptr - ARR_DATA_PTR(array));
2414  if (array_get_isnull(oldnullbitmap, offset))
2415  olditemlen = 0;
2416  else
2417  {
2418  olditemlen = att_addlength_pointer(0, elmlen, elt_ptr);
2419  olditemlen = att_align_nominal(olditemlen, elmalign);
2420  }
2421  lenafter = (int) (olddatasize - lenbefore - olditemlen);
2422  }
2423 
2424  if (isNull)
2425  newitemlen = 0;
2426  else
2427  {
2428  newitemlen = att_addlength_datum(0, elmlen, dataValue);
2429  newitemlen = att_align_nominal(newitemlen, elmalign);
2430  }
2431 
2432  newsize = overheadlen + lenbefore + newitemlen + lenafter;
2433 
2434  /*
2435  * OK, create the new array and fill in header/dimensions
2436  */
2437  newarray = (ArrayType *) palloc0(newsize);
2438  SET_VARSIZE(newarray, newsize);
2439  newarray->ndim = ndim;
2440  newarray->dataoffset = newhasnulls ? overheadlen : 0;
2441  newarray->elemtype = ARR_ELEMTYPE(array);
2442  memcpy(ARR_DIMS(newarray), dim, ndim * sizeof(int));
2443  memcpy(ARR_LBOUND(newarray), lb, ndim * sizeof(int));
2444 
2445  /*
2446  * Fill in data
2447  */
2448  memcpy((char *) newarray + overheadlen,
2449  (char *) array + oldoverheadlen,
2450  lenbefore);
2451  if (!isNull)
2452  ArrayCastAndSet(dataValue, elmlen, elmbyval, elmalign,
2453  (char *) newarray + overheadlen + lenbefore);
2454  memcpy((char *) newarray + overheadlen + lenbefore + newitemlen,
2455  (char *) array + oldoverheadlen + lenbefore + olditemlen,
2456  lenafter);
2457 
2458  /*
2459  * Fill in nulls bitmap if needed
2460  *
2461  * Note: it's possible we just replaced the last NULL with a non-NULL, and
2462  * could get rid of the bitmap. Seems not worth testing for though.
2463  */
2464  if (newhasnulls)
2465  {
2466  bits8 *newnullbitmap = ARR_NULLBITMAP(newarray);
2467 
2468  /* Zero the bitmap to take care of marking inserted positions null */
2469  MemSet(newnullbitmap, 0, (newnitems + 7) / 8);
2470  /* Fix the inserted value */
2471  if (addedafter)
2472  array_set_isnull(newnullbitmap, newnitems - 1, isNull);
2473  else
2474  array_set_isnull(newnullbitmap, offset, isNull);
2475  /* Fix the copied range(s) */
2476  if (addedbefore)
2477  array_bitmap_copy(newnullbitmap, addedbefore,
2478  oldnullbitmap, 0,
2479  oldnitems);
2480  else
2481  {
2482  array_bitmap_copy(newnullbitmap, 0,
2483  oldnullbitmap, 0,
2484  offset);
2485  if (addedafter == 0)
2486  array_bitmap_copy(newnullbitmap, offset + 1,
2487  oldnullbitmap, offset + 1,
2488  oldnitems - offset - 1);
2489  }
2490  }
2491 
2492  return PointerGetDatum(newarray);
2493 }
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:298
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
#define ARR_SIZE(a)
Definition: array.h:277
#define VARATT_IS_EXTERNAL_EXPANDED(PTR)
Definition: postgres.h:322
#define MAXDIM
Definition: c.h:543
int ArrayGetOffset(int n, const int *dim, const int *lb, const int *indx)
Definition: arrayutils.c:31
static int ArrayCastAndSet(Datum src, int typlen, bool typbyval, char typalign, char *dest)
Definition: arrayfuncs.c:4575
#define PointerGetDatum(X)
Definition: postgres.h:556
void array_bitmap_copy(bits8 *destbitmap, int destoffset, const bits8 *srcbitmap, int srcoffset, int nitems)
Definition: arrayfuncs.c:4714
int32 dataoffset
Definition: array.h:84
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:610
#define MemSet(start, val, len)
Definition: c.h:950
unsigned int Oid
Definition: postgres_ext.h:31
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:300
#define ARR_DATA_OFFSET(a)
Definition: array.h:304
#define ARR_LBOUND(a)
Definition: array.h:284
#define ERROR
Definition: elog.h:43
Oid elemtype
Definition: array.h:85
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
static Datum array_set_element_expanded(Datum arraydatum, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:2503
#define ARR_HASNULL(a)
Definition: array.h:279
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:176
uint8 bits8
Definition: c.h:382
void * palloc0(Size size)
Definition: mcxt.c:981
static void array_set_isnull(bits8 *nullbitmap, int offset, bool isNull)
Definition: arrayfuncs.c:4546
#define ereport(elevel,...)
Definition: elog.h:144
static char * array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4614
static bool array_get_isnull(const bits8 *nullbitmap, int offset)
Definition: arrayfuncs.c:4529
#define ARR_NDIM(a)
Definition: array.h:278
#define DatumGetPointer(X)
Definition: postgres.h:549
#define att_addlength_datum(cur_offset, attlen, attdatum)
Definition: tupmacs.h:164
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329
ArrayType * construct_md_array(Datum *elems, bool *nulls, int ndims, int *dims, int *lbs, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3348
#define ARR_ELEMTYPE(a)
Definition: array.h:280
#define ARR_NULLBITMAP(a)
Definition: array.h:288
int ndim
Definition: array.h:83
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ array_set_element_expanded()

static Datum array_set_element_expanded ( Datum  arraydatum,
int  nSubscripts,
int *  indx,
Datum  dataValue,
bool  isNull,
int  arraytyplen,
int  elmlen,
bool  elmbyval,
char  elmalign 
)
static

Definition at line 2503 of file arrayfuncs.c.

References ArrayGetOffset(), Assert, datumCopy(), DatumGetExpandedArray(), DatumGetPointer, deconstruct_expanded_array(), ExpandedArrayHeader::dims, ExpandedArrayHeader::dnulls, ExpandedArrayHeader::dvalues, ExpandedArrayHeader::dvalueslen, ExpandedObjectHeader::eoh_context, EOHPGetRWDatum, ereport, errcode(), errmsg(), ERROR, ExpandedArrayHeader::fendptr, ExpandedArrayHeader::flat_size, ExpandedArrayHeader::fvalue, ExpandedArrayHeader::hdr, i, ExpandedArrayHeader::lbound, Max, MAXDIM, MemoryContextAllocZero(), MemoryContextSwitchTo(), ExpandedArrayHeader::ndims, ExpandedArrayHeader::nelems, pfree(), repalloc(), ExpandedArrayHeader::typalign, ExpandedArrayHeader::typbyval, and ExpandedArrayHeader::typlen.

Referenced by array_set_element().

2508 {
2509  ExpandedArrayHeader *eah;
2510  Datum *dvalues;
2511  bool *dnulls;
2512  int i,
2513  ndim,
2514  dim[MAXDIM],
2515  lb[MAXDIM],
2516  offset;
2517  bool dimschanged,
2518  newhasnulls;
2519  int addedbefore,
2520  addedafter;
2521  char *oldValue;
2522 
2523  /* Convert to R/W object if not so already */
2524  eah = DatumGetExpandedArray(arraydatum);
2525 
2526  /* Sanity-check caller's info against object; we don't use it otherwise */
2527  Assert(arraytyplen == -1);
2528  Assert(elmlen == eah->typlen);
2529  Assert(elmbyval == eah->typbyval);
2530  Assert(elmalign == eah->typalign);
2531 
2532  /*
2533  * Copy dimension info into local storage. This allows us to modify the
2534  * dimensions if needed, while not messing up the expanded value if we
2535  * fail partway through.
2536  */
2537  ndim = eah->ndims;
2538  Assert(ndim >= 0 && ndim <= MAXD