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)
 
Datum trim_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 5085 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(), brin_minmax_multi_summary_out(), dblink_get_connections(), get_altertable_subcmdtypes(), optionListToArray(), parse_ident(), pg_get_statisticsobjdef_expressions(), pg_stats_ext_mcvlist_items(), populate_array_element(), range_agg_transfn(), regexp_split_to_array(), serialize_expr_stats(), SPI_sql_row_to_xmlelement(), split_text_accum_result(), transformRelOptions(), and tuple_data_split_internal().

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

◆ accumArrayResultAny()

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

Definition at line 5552 of file arrayfuncs.c.

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

Referenced by ExecScanSubPlan(), and ExecSetParamPlan().

5556 {
5557  if (astate == NULL)
5558  astate = initArrayResultAny(input_type, rcontext, true);
5559 
5560  if (astate->scalarstate)
5561  (void) accumArrayResult(astate->scalarstate,
5562  dvalue, disnull,
5563  input_type, rcontext);
5564  else
5565  (void) accumArrayResultArr(astate->arraystate,
5566  dvalue, disnull,
5567  input_type, rcontext);
5568 
5569  return astate;
5570 }
ArrayBuildStateAny * initArrayResultAny(Oid input_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5507
ArrayBuildState * scalarstate
Definition: array.h:222
ArrayBuildStateArr * accumArrayResultArr(ArrayBuildStateArr *astate, Datum dvalue, bool disnull, Oid array_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5279
ArrayBuildStateArr * arraystate
Definition: array.h:223
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5085

◆ accumArrayResultArr()

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

Definition at line 5279 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().

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

◆ array_bitmap_copy()

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

Definition at line 4719 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().

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

◆ 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:267
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define AARR_DIMS(a)
Definition: array.h:331
#define AARR_NDIM(a)
Definition: array.h:321

◆ array_cmp()

static int array_cmp ( FunctionCallInfo  fcinfo)
static

Definition at line 3773 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().

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

◆ array_contain_compare()

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

Definition at line 4134 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().

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

◆ array_contains_nulls()

bool array_contains_nulls ( ArrayType array)

Definition at line 3555 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().

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

◆ 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 4689 of file arrayfuncs.c.

References array_nelems_size().

Referenced by array_extract_slice(), and array_insert_slice().

4692 {
4693  int numbytes;
4694 
4695  numbytes = array_nelems_size(srcptr, offset, nullbitmap, nitems,
4696  typlen, typbyval, typalign);
4697  memcpy(destptr, srcptr, numbytes);
4698  return numbytes;
4699 }
char typalign
Definition: pg_type.h:176
static int array_nelems_size(char *ptr, int offset, bits8 *nullbitmap, int nitems, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4667

◆ array_create_iterator()

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

Definition at line 4350 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().

4351 {
4352  ArrayIterator iterator = palloc0(sizeof(ArrayIteratorData));
4353 
4354  /*
4355  * Sanity-check inputs --- caller should have got this right already
4356  */
4357  Assert(PointerIsValid(arr));
4358  if (slice_ndim < 0 || slice_ndim > ARR_NDIM(arr))
4359  elog(ERROR, "invalid arguments to array_create_iterator");
4360 
4361  /*
4362  * Remember basic info about the array and its element type
4363  */
4364  iterator->arr = arr;
4365  iterator->nullbitmap = ARR_NULLBITMAP(arr);
4366  iterator->nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
4367 
4368  if (mstate != NULL)
4369  {
4370  Assert(mstate->element_type == ARR_ELEMTYPE(arr));
4371 
4372  iterator->typlen = mstate->typlen;
4373  iterator->typbyval = mstate->typbyval;
4374  iterator->typalign = mstate->typalign;
4375  }
4376  else
4378  &iterator->typlen,
4379  &iterator->typbyval,
4380  &iterator->typalign);
4381 
4382  /*
4383  * Remember the slicing parameters.
4384  */
4385  iterator->slice_ndim = slice_ndim;
4386 
4387  if (slice_ndim > 0)
4388  {
4389  /*
4390  * Get pointers into the array's dims and lbound arrays to represent
4391  * the dims/lbound arrays of a slice. These are the same as the
4392  * rightmost N dimensions of the array.
4393  */
4394  iterator->slice_dims = ARR_DIMS(arr) + ARR_NDIM(arr) - slice_ndim;
4395  iterator->slice_lbound = ARR_LBOUND(arr) + ARR_NDIM(arr) - slice_ndim;
4396 
4397  /*
4398  * Compute number of elements in a slice.
4399  */
4400  iterator->slice_len = ArrayGetNItems(slice_ndim,
4401  iterator->slice_dims);
4402 
4403  /*
4404  * Create workspace for building sub-arrays.
4405  */
4406  iterator->slice_values = (Datum *)
4407  palloc(iterator->slice_len * sizeof(Datum));
4408  iterator->slice_nulls = (bool *)
4409  palloc(iterator->slice_len * sizeof(bool));
4410  }
4411 
4412  /*
4413  * Initialize our data pointer and linear element number. These will
4414  * advance through the array during array_iterate().
4415  */
4416  iterator->data_ptr = ARR_DATA_PTR(arr);
4417  iterator->current_item = 0;
4418 
4419  return iterator;
4420 }
bits8 * nullbitmap
Definition: arrayfuncs.c:72
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2218
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_LBOUND(a)
Definition: array.h:289
bool typbyval
Definition: array.h:233
bool * slice_nulls
Definition: arrayfuncs.c:84
#define ERROR
Definition: elog.h:46
Datum * slice_values
Definition: arrayfuncs.c:83
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_DATA_PTR(a)
Definition: array.h:315
int16 typlen
Definition: array.h:232
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
#define Assert(condition)
Definition: c.h:804
#define ARR_NDIM(a)
Definition: array.h:283
char typalign
Definition: array.h:234
void * palloc(Size size)
Definition: mcxt.c:1062
#define elog(elevel,...)
Definition: elog.h:232
Oid element_type
Definition: array.h:231
#define PointerIsValid(pointer)
Definition: c.h:698
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define ARR_NULLBITMAP(a)
Definition: array.h:293
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:267
#define sprintf
Definition: port.h:218
static char * buf
Definition: pg_test_fsync.c:68
#define MAXDIM
Definition: array.h:75
#define AARR_DIMS(a)
Definition: array.h:331
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
#define AARR_LBOUND(a)
Definition: array.h:334
#define AARR_NDIM(a)
Definition: array.h:321
int i
#define PG_RETURN_NULL()
Definition: fmgr.h:345

◆ array_eq()

Datum array_eq ( PG_FUNCTION_ARGS  )

Definition at line 3602 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().

3603 {
3604  LOCAL_FCINFO(locfcinfo, 2);
3605  AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
3606  AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
3607  Oid collation = PG_GET_COLLATION();
3608  int ndims1 = AARR_NDIM(array1);
3609  int ndims2 = AARR_NDIM(array2);
3610  int *dims1 = AARR_DIMS(array1);
3611  int *dims2 = AARR_DIMS(array2);
3612  int *lbs1 = AARR_LBOUND(array1);
3613  int *lbs2 = AARR_LBOUND(array2);
3614  Oid element_type = AARR_ELEMTYPE(array1);
3615  bool result = true;
3616  int nitems;
3617  TypeCacheEntry *typentry;
3618  int typlen;
3619  bool typbyval;
3620  char typalign;
3621  array_iter it1;
3622  array_iter it2;
3623  int i;
3624 
3625  if (element_type != AARR_ELEMTYPE(array2))
3626  ereport(ERROR,
3627  (errcode(ERRCODE_DATATYPE_MISMATCH),
3628  errmsg("cannot compare arrays of different element types")));
3629 
3630  /* fast path if the arrays do not have the same dimensionality */
3631  if (ndims1 != ndims2 ||
3632  memcmp(dims1, dims2, ndims1 * sizeof(int)) != 0 ||
3633  memcmp(lbs1, lbs2, ndims1 * sizeof(int)) != 0)
3634  result = false;
3635  else
3636  {
3637  /*
3638  * We arrange to look up the equality function only once per series of
3639  * calls, assuming the element type doesn't change underneath us. The
3640  * typcache is used so that we have no memory leakage when being used
3641  * as an index support function.
3642  */
3643  typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
3644  if (typentry == NULL ||
3645  typentry->type_id != element_type)
3646  {
3647  typentry = lookup_type_cache(element_type,
3649  if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
3650  ereport(ERROR,
3651  (errcode(ERRCODE_UNDEFINED_FUNCTION),
3652  errmsg("could not identify an equality operator for type %s",
3653  format_type_be(element_type))));
3654  fcinfo->flinfo->fn_extra = (void *) typentry;
3655  }
3656  typlen = typentry->typlen;
3657  typbyval = typentry->typbyval;
3658  typalign = typentry->typalign;
3659 
3660  /*
3661  * apply the operator to each pair of array elements.
3662  */
3663  InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
3664  collation, NULL, NULL);
3665 
3666  /* Loop over source data */
3667  nitems = ArrayGetNItems(ndims1, dims1);
3668  array_iter_setup(&it1, array1);
3669  array_iter_setup(&it2, array2);
3670 
3671  for (i = 0; i < nitems; i++)
3672  {
3673  Datum elt1;
3674  Datum elt2;
3675  bool isnull1;
3676  bool isnull2;
3677  bool oprresult;
3678 
3679  /* Get elements, checking for NULL */
3680  elt1 = array_iter_next(&it1, &isnull1, i,
3681  typlen, typbyval, typalign);
3682  elt2 = array_iter_next(&it2, &isnull2, i,
3683  typlen, typbyval, typalign);
3684 
3685  /*
3686  * We consider two NULLs equal; NULL and not-NULL are unequal.
3687  */
3688  if (isnull1 && isnull2)
3689  continue;
3690  if (isnull1 || isnull2)
3691  {
3692  result = false;
3693  break;
3694  }
3695 
3696  /*
3697  * Apply the operator to the element pair; treat NULL as false
3698  */
3699  locfcinfo->args[0].value = elt1;
3700  locfcinfo->args[0].isnull = false;
3701  locfcinfo->args[1].value = elt2;
3702  locfcinfo->args[1].isnull = false;
3703  locfcinfo->isnull = false;
3704  oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
3705  if (locfcinfo->isnull || !oprresult)
3706  {
3707  result = false;
3708  break;
3709  }
3710  }
3711  }
3712 
3713  /* Avoid leaking memory when handed toasted input. */
3714  AARR_FREE_IF_COPY(array1, 0);
3715  AARR_FREE_IF_COPY(array2, 1);
3716 
3717  PG_RETURN_BOOL(result);
3718 }
#define PG_GETARG_ANY_ARRAY_P(n)
Definition: array.h:267
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:141
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:698
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:710
#define PG_GET_COLLATION()
Definition: fmgr.h:198
char typalign
Definition: pg_type.h:176
#define ERROR
Definition: elog.h:46
#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:437
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
uintptr_t Datum
Definition: postgres.h:411
#define AARR_DIMS(a)
Definition: array.h:331
#define AARR_ELEMTYPE(a)
Definition: array.h:328
FmgrInfo eq_opr_finfo
Definition: typcache.h:75
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:338
Oid fn_oid
Definition: fmgr.h:59
#define ereport(elevel,...)
Definition: elog.h:157
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define AARR_LBOUND(a)
Definition: array.h:334
#define AARR_NDIM(a)
Definition: array.h:321
#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:909
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 4850 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().

4861 {
4862  char *destdataptr = ARR_DATA_PTR(newarray);
4863  bits8 *destnullsptr = ARR_NULLBITMAP(newarray);
4864  char *srcdataptr;
4865  int src_offset,
4866  dest_offset,
4867  prod[MAXDIM],
4868  span[MAXDIM],
4869  dist[MAXDIM],
4870  indx[MAXDIM];
4871  int i,
4872  j,
4873  inc;
4874 
4875  src_offset = ArrayGetOffset(ndim, dim, lb, st);
4876  srcdataptr = array_seek(arraydataptr, 0, arraynullsptr, src_offset,
4877  typlen, typbyval, typalign);
4878  mda_get_prod(ndim, dim, prod);
4879  mda_get_range(ndim, span, st, endp);
4880  mda_get_offset_values(ndim, dist, prod, span);
4881  for (i = 0; i < ndim; i++)
4882  indx[i] = 0;
4883  dest_offset = 0;
4884  j = ndim - 1;
4885  do
4886  {
4887  if (dist[j])
4888  {
4889  /* skip unwanted elements */
4890  srcdataptr = array_seek(srcdataptr, src_offset, arraynullsptr,
4891  dist[j],
4892  typlen, typbyval, typalign);
4893  src_offset += dist[j];
4894  }
4895  inc = array_copy(destdataptr, 1,
4896  srcdataptr, src_offset, arraynullsptr,
4897  typlen, typbyval, typalign);
4898  if (destnullsptr)
4899  array_bitmap_copy(destnullsptr, dest_offset,
4900  arraynullsptr, src_offset,
4901  1);
4902  destdataptr += inc;
4903  srcdataptr += inc;
4904  src_offset++;
4905  dest_offset++;
4906  } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
4907 }
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:4719
static int array_copy(char *destptr, int nitems, char *srcptr, int offset, bits8 *nullbitmap, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4689
char typalign
Definition: pg_type.h:176
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define MAXDIM
Definition: array.h:75
void mda_get_offset_values(int n, int *dist, const int *prod, const int *span)
Definition: arrayutils.c:150
uint8 bits8
Definition: c.h:448
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:4619
int mda_next_tuple(int n, int *curr, const int *span)
Definition: arrayutils.c:175
int i
#define ARR_NULLBITMAP(a)
Definition: array.h:293

◆ array_fill()

Datum array_fill ( PG_FUNCTION_ARGS  )

Definition at line 5756 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.

5757 {
5758  ArrayType *dims;
5759  ArrayType *result;
5760  Oid elmtype;
5761  Datum value;
5762  bool isnull;
5763 
5764  if (PG_ARGISNULL(1))
5765  ereport(ERROR,
5766  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5767  errmsg("dimension array or low bound array cannot be null")));
5768 
5769  dims = PG_GETARG_ARRAYTYPE_P(1);
5770 
5771  if (!PG_ARGISNULL(0))
5772  {
5773  value = PG_GETARG_DATUM(0);
5774  isnull = false;
5775  }
5776  else
5777  {
5778  value = 0;
5779  isnull = true;
5780  }
5781 
5782  elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
5783  if (!OidIsValid(elmtype))
5784  elog(ERROR, "could not determine data type of input");
5785 
5786  result = array_fill_internal(dims, NULL, value, isnull, elmtype, fcinfo);
5787  PG_RETURN_ARRAYTYPE_P(result);
5788 }
static struct @142 value
static ArrayType * array_fill_internal(ArrayType *dims, ArrayType *lbs, Datum value, bool isnull, Oid elmtype, FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:5808
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:256
#define ERROR
Definition: elog.h:46
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1803
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:258
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232

◆ array_fill_internal()

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

Definition at line 5808 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().

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

◆ array_fill_with_lower_bounds()

Datum array_fill_with_lower_bounds ( PG_FUNCTION_ARGS  )

Definition at line 5715 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.

5716 {
5717  ArrayType *dims;
5718  ArrayType *lbs;
5719  ArrayType *result;
5720  Oid elmtype;
5721  Datum value;
5722  bool isnull;
5723 
5724  if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
5725  ereport(ERROR,
5726  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5727  errmsg("dimension array or low bound array cannot be null")));
5728 
5729  dims = PG_GETARG_ARRAYTYPE_P(1);
5730  lbs = PG_GETARG_ARRAYTYPE_P(2);
5731 
5732  if (!PG_ARGISNULL(0))
5733  {
5734  value = PG_GETARG_DATUM(0);
5735  isnull = false;
5736  }
5737  else
5738  {
5739  value = 0;
5740  isnull = true;
5741  }
5742 
5743  elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
5744  if (!OidIsValid(elmtype))
5745  elog(ERROR, "could not determine data type of input");
5746 
5747  result = array_fill_internal(dims, lbs, value, isnull, elmtype, fcinfo);
5748  PG_RETURN_ARRAYTYPE_P(result);
5749 }
static struct @142 value
static ArrayType * array_fill_internal(ArrayType *dims, ArrayType *lbs, Datum value, bool isnull, Oid elmtype, FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:5808
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:256
#define ERROR
Definition: elog.h:46
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1803
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:258
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232

◆ array_free_iterator()

void array_free_iterator ( ArrayIterator  iterator)

Definition at line 4512 of file arrayfuncs.c.

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

Referenced by array_position_common(), and array_positions().

4513 {
4514  if (iterator->slice_ndim > 0)
4515  {
4516  pfree(iterator->slice_values);
4517  pfree(iterator->slice_nulls);
4518  }
4519  pfree(iterator);
4520 }
bool * slice_nulls
Definition: arrayfuncs.c:84
void pfree(void *pointer)
Definition: mcxt.c:1169
Datum * slice_values
Definition: arrayfuncs.c:83

◆ array_ge()

Datum array_ge ( PG_FUNCTION_ARGS  )

Definition at line 3755 of file arrayfuncs.c.

References array_cmp(), and PG_RETURN_BOOL.

3756 {
3757  PG_RETURN_BOOL(array_cmp(fcinfo) >= 0);
3758 }
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3773
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359

◆ 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(), array_subscript_fetch(), array_subscript_fetch_old(), ATExecAlterColumnType(), 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:335
int ArrayGetOffset(int n, const int *dim, const int *lb, const int *indx)
Definition: arrayutils.c:31
#define ARR_LBOUND(a)
Definition: array.h:289
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_DATA_PTR(a)
Definition: array.h:315
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
#define MAXDIM
Definition: array.h:75
uint8 bits8
Definition: c.h:448
uintptr_t Datum
Definition: postgres.h:411
static char * array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4619
static Datum ArrayCast(char *value, bool byval, int len)
Definition: arrayfuncs.c:4569
static bool array_get_isnull(const bits8 *nullbitmap, int offset)
Definition: arrayfuncs.c:4534
#define ARR_NDIM(a)
Definition: array.h:283
#define DatumGetPointer(X)
Definition: postgres.h:593
int i
#define ARR_NULLBITMAP(a)
Definition: array.h:293
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ 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)
int ArrayGetOffset(int n, const int *dim, const int *lb, const int *indx)
Definition: arrayutils.c:31
Datum * dvalues
Definition: array.h:139
#define EA_MAGIC
Definition: array.h:106
#define MAXDIM
Definition: array.h:75
ExpandedObjectHeader * DatumGetEOHP(Datum d)
Definition: expandeddatum.c:29
uintptr_t Datum
Definition: postgres.h:411
#define Assert(condition)
Definition: c.h:804
int i

◆ array_get_isnull()

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

Definition at line 4534 of file arrayfuncs.c.

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

4535 {
4536  if (nullbitmap == NULL)
4537  return false; /* assume not null */
4538  if (nullbitmap[offset / 8] & (1 << (offset % 8)))
4539  return false; /* not null */
4540  return true;
4541 }

◆ 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 2051 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 array_subscript_fetch_old_slice(), array_subscript_fetch_slice(), and trim_array().

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

◆ array_gt()

Datum array_gt ( PG_FUNCTION_ARGS  )

Definition at line 3743 of file arrayfuncs.c.

References array_cmp(), and PG_RETURN_BOOL.

3744 {
3745  PG_RETURN_BOOL(array_cmp(fcinfo) > 0);
3746 }
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3773
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359

◆ 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:303
MemoryContext fn_mcxt
Definition: fmgr.h:65
char * pstrdup(const char *in)
Definition: mcxt.c:1299
int32 dataoffset
Definition: array.h:89
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:698
#define printf(...)
Definition: port.h:222
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3437
unsigned int Oid
Definition: postgres_ext.h:31
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:305
signed int int32
Definition: c.h:429
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:289
bool typbyval
Definition: array.h:233
void pfree(void *pointer)
Definition: mcxt.c:1169
char typalign
Definition: pg_type.h:176
#define ERROR
Definition: elog.h:46
Oid elemtype
Definition: array.h:90
#define ARR_DIMS(a)
Definition: array.h:287
int16 typlen
Definition: array.h:232
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
char typdelim
Definition: array.h:235
#define MAXDIM
Definition: array.h:75
int errdetail(const char *fmt,...)
Definition: elog.c:1042
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:258
#define ASSGN
Definition: arrayfuncs.c:46
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
Oid typioparam
Definition: array.h:236
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:237
char typalign
Definition: array.h:234
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
FmgrInfo proc
Definition: array.h:238
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
int i
Oid element_type
Definition: array.h:231
#define PG_GETARG_CSTRING(n)
Definition: fmgr.h:277
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:342
int ndim
Definition: array.h:88
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:2272

◆ 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 4923 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().

4934 {
4935  char *destPtr = ARR_DATA_PTR(destArray);
4936  char *origPtr = ARR_DATA_PTR(origArray);
4937  char *srcPtr = ARR_DATA_PTR(srcArray);
4938  bits8 *destBitmap = ARR_NULLBITMAP(destArray);
4939  bits8 *origBitmap = ARR_NULLBITMAP(origArray);
4940  bits8 *srcBitmap = ARR_NULLBITMAP(srcArray);
4941  int orignitems = ArrayGetNItems(ARR_NDIM(origArray),
4942  ARR_DIMS(origArray));
4943  int dest_offset,
4944  orig_offset,
4945  src_offset,
4946  prod[MAXDIM],
4947  span[MAXDIM],
4948  dist[MAXDIM],
4949  indx[MAXDIM];
4950  int i,
4951  j,
4952  inc;
4953 
4954  dest_offset = ArrayGetOffset(ndim, dim, lb, st);
4955  /* copy items before the slice start */
4956  inc = array_copy(destPtr, dest_offset,
4957  origPtr, 0, origBitmap,
4958  typlen, typbyval, typalign);
4959  destPtr += inc;
4960  origPtr += inc;
4961  if (destBitmap)
4962  array_bitmap_copy(destBitmap, 0, origBitmap, 0, dest_offset);
4963  orig_offset = dest_offset;
4964  mda_get_prod(ndim, dim, prod);
4965  mda_get_range(ndim, span, st, endp);
4966  mda_get_offset_values(ndim, dist, prod, span);
4967  for (i = 0; i < ndim; i++)
4968  indx[i] = 0;
4969  src_offset = 0;
4970  j = ndim - 1;
4971  do
4972  {
4973  /* Copy/advance over elements between here and next part of slice */
4974  if (dist[j])
4975  {
4976  inc = array_copy(destPtr, dist[j],
4977  origPtr, orig_offset, origBitmap,
4978  typlen, typbyval, typalign);
4979  destPtr += inc;
4980  origPtr += inc;
4981  if (destBitmap)
4982  array_bitmap_copy(destBitmap, dest_offset,
4983  origBitmap, orig_offset,
4984  dist[j]);
4985  dest_offset += dist[j];
4986  orig_offset += dist[j];
4987  }
4988  /* Copy new element at this slice position */
4989  inc = array_copy(destPtr, 1,
4990  srcPtr, src_offset, srcBitmap,
4991  typlen, typbyval, typalign);
4992  if (destBitmap)
4993  array_bitmap_copy(destBitmap, dest_offset,
4994  srcBitmap, src_offset,
4995  1);
4996  destPtr += inc;
4997  srcPtr += inc;
4998  dest_offset++;
4999  src_offset++;
5000  /* Advance over old element at this slice position */
5001  origPtr = array_seek(origPtr, orig_offset, origBitmap, 1,
5002  typlen, typbyval, typalign);
5003  orig_offset++;
5004  } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
5005 
5006  /* don't miss any data at the end */
5007  array_copy(destPtr, orignitems - orig_offset,
5008  origPtr, orig_offset, origBitmap,
5009  typlen, typbyval, typalign);
5010  if (destBitmap)
5011  array_bitmap_copy(destBitmap, dest_offset,
5012  origBitmap, orig_offset,
5013  orignitems - orig_offset);
5014 }
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:4719
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:4689
char typalign
Definition: pg_type.h:176
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define MAXDIM
Definition: array.h:75
void mda_get_offset_values(int n, int *dist, const int *prod, const int *span)
Definition: arrayutils.c:150
uint8 bits8
Definition: c.h:448
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:4619
#define ARR_NDIM(a)
Definition: array.h:283
int mda_next_tuple(int n, int *curr, const int *span)
Definition: arrayutils.c:175
int i
#define ARR_NULLBITMAP(a)
Definition: array.h:293

◆ 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 4429 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().

4430 {
4431  /* Done if we have reached the end of the array */
4432  if (iterator->current_item >= iterator->nitems)
4433  return false;
4434 
4435  if (iterator->slice_ndim == 0)
4436  {
4437  /*
4438  * Scalar case: return one element.
4439  */
4440  if (array_get_isnull(iterator->nullbitmap, iterator->current_item++))
4441  {
4442  *isnull = true;
4443  *value = (Datum) 0;
4444  }
4445  else
4446  {
4447  /* non-NULL, so fetch the individual Datum to return */
4448  char *p = iterator->data_ptr;
4449 
4450  *isnull = false;
4451  *value = fetch_att(p, iterator->typbyval, iterator->typlen);
4452 
4453  /* Move our data pointer forward to the next element */
4454  p = att_addlength_pointer(p, iterator->typlen, p);
4455  p = (char *) att_align_nominal(p, iterator->typalign);
4456  iterator->data_ptr = p;
4457  }
4458  }
4459  else
4460  {
4461  /*
4462  * Slice case: build and return an array of the requested size.
4463  */
4464  ArrayType *result;
4465  Datum *values = iterator->slice_values;
4466  bool *nulls = iterator->slice_nulls;
4467  char *p = iterator->data_ptr;
4468  int i;
4469 
4470  for (i = 0; i < iterator->slice_len; i++)
4471  {
4472  if (array_get_isnull(iterator->nullbitmap,
4473  iterator->current_item++))
4474  {
4475  nulls[i] = true;
4476  values[i] = (Datum) 0;
4477  }
4478  else
4479  {
4480  nulls[i] = false;
4481  values[i] = fetch_att(p, iterator->typbyval, iterator->typlen);
4482 
4483  /* Move our data pointer forward to the next element */
4484  p = att_addlength_pointer(p, iterator->typlen, p);
4485  p = (char *) att_align_nominal(p, iterator->typalign);
4486  }
4487  }
4488 
4489  iterator->data_ptr = p;
4490 
4491  result = construct_md_array(values,
4492  nulls,
4493  iterator->slice_ndim,
4494  iterator->slice_dims,
4495  iterator->slice_lbound,
4496  ARR_ELEMTYPE(iterator->arr),
4497  iterator->typlen,
4498  iterator->typbyval,
4499  iterator->typalign);
4500 
4501  *isnull = false;
4502  *value = PointerGetDatum(result);
4503  }
4504 
4505  return true;
4506 }
bits8 * nullbitmap
Definition: arrayfuncs.c:72
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
static struct @142 value
#define PointerGetDatum(X)
Definition: postgres.h:600
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:411
static bool array_get_isnull(const bits8 *nullbitmap, int offset)
Definition: arrayfuncs.c:4534
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#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:3353
#define ARR_ELEMTYPE(a)
Definition: array.h:285
ArrayType * arr
Definition: arrayfuncs.c:71

◆ array_larger()

Datum array_larger ( PG_FUNCTION_ARGS  )

Definition at line 5610 of file arrayfuncs.c.

References array_cmp(), PG_GETARG_DATUM, and PG_RETURN_DATUM.

5611 {
5612  if (array_cmp(fcinfo) > 0)
5614  else
5616 }
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3773
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353

◆ array_le()

Datum array_le ( PG_FUNCTION_ARGS  )

Definition at line 3749 of file arrayfuncs.c.

References array_cmp(), and PG_RETURN_BOOL.

3750 {
3751  PG_RETURN_BOOL(array_cmp(fcinfo) <= 0);
3752 }
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3773
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359

◆ 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.

Referenced by trim_array().

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:267
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define MAXDIM
Definition: array.h:75
#define AARR_DIMS(a)
Definition: array.h:331
#define AARR_NDIM(a)
Definition: array.h:321
#define PG_RETURN_NULL()
Definition: fmgr.h:345

◆ 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:267
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define MAXDIM
Definition: array.h:75
#define AARR_LBOUND(a)
Definition: array.h:334
#define AARR_NDIM(a)
Definition: array.h:321
#define PG_RETURN_NULL()
Definition: fmgr.h:345

◆ array_lt()

Datum array_lt ( PG_FUNCTION_ARGS  )

Definition at line 3737 of file arrayfuncs.c.

References array_cmp(), and PG_RETURN_BOOL.

3738 {
3739  PG_RETURN_BOOL(array_cmp(fcinfo) < 0);
3740 }
static int array_cmp(FunctionCallInfo fcinfo)
Definition: arrayfuncs.c:3773
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359

◆ array_map()

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

Definition at line 3158 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().

3161 {
3162  AnyArrayType *v = DatumGetAnyArrayP(arrayd);
3163  ArrayType *result;
3164  Datum *values;
3165  bool *nulls;
3166  int *dim;
3167  int ndim;
3168  int nitems;
3169  int i;
3170  int32 nbytes = 0;
3171  int32 dataoffset;
3172  bool hasnulls;
3173  Oid inpType;
3174  int inp_typlen;
3175  bool inp_typbyval;
3176  char inp_typalign;
3177  int typlen;
3178  bool typbyval;
3179  char typalign;
3180  array_iter iter;
3181  ArrayMetaState *inp_extra;
3182  ArrayMetaState *ret_extra;
3183  Datum *transform_source = exprstate->innermost_caseval;
3184  bool *transform_source_isnull = exprstate->innermost_casenull;
3185 
3186  inpType = AARR_ELEMTYPE(v);
3187  ndim = AARR_NDIM(v);
3188  dim = AARR_DIMS(v);
3189  nitems = ArrayGetNItems(ndim, dim);
3190 
3191  /* Check for empty array */
3192  if (nitems <= 0)
3193  {
3194  /* Return empty array */
3195  return PointerGetDatum(construct_empty_array(retType));
3196  }
3197 
3198  /*
3199  * We arrange to look up info about input and return element types only
3200  * once per series of calls, assuming the element type doesn't change
3201  * underneath us.
3202  */
3203  inp_extra = &amstate->inp_extra;
3204  ret_extra = &amstate->ret_extra;
3205 
3206  if (inp_extra->element_type != inpType)
3207  {
3208  get_typlenbyvalalign(inpType,
3209  &inp_extra->typlen,
3210  &inp_extra->typbyval,
3211  &inp_extra->typalign);
3212  inp_extra->element_type = inpType;
3213  }
3214  inp_typlen = inp_extra->typlen;
3215  inp_typbyval = inp_extra->typbyval;
3216  inp_typalign = inp_extra->typalign;
3217 
3218  if (ret_extra->element_type != retType)
3219  {
3220  get_typlenbyvalalign(retType,
3221  &ret_extra->typlen,
3222  &ret_extra->typbyval,
3223  &ret_extra->typalign);
3224  ret_extra->element_type = retType;
3225  }
3226  typlen = ret_extra->typlen;
3227  typbyval = ret_extra->typbyval;
3228  typalign = ret_extra->typalign;
3229 
3230  /* Allocate temporary arrays for new values */
3231  values = (Datum *) palloc(nitems * sizeof(Datum));
3232  nulls = (bool *) palloc(nitems * sizeof(bool));
3233 
3234  /* Loop over source data */
3235  array_iter_setup(&iter, v);
3236  hasnulls = false;
3237 
3238  for (i = 0; i < nitems; i++)
3239  {
3240  /* Get source element, checking for NULL */
3241  *transform_source =
3242  array_iter_next(&iter, transform_source_isnull, i,
3243  inp_typlen, inp_typbyval, inp_typalign);
3244 
3245  /* Apply the given expression to source element */
3246  values[i] = ExecEvalExpr(exprstate, econtext, &nulls[i]);
3247 
3248  if (nulls[i])
3249  hasnulls = true;
3250  else
3251  {
3252  /* Ensure data is not toasted */
3253  if (typlen == -1)
3254  values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
3255  /* Update total result size */
3256  nbytes = att_addlength_datum(nbytes, typlen, values[i]);
3257  nbytes = att_align_nominal(nbytes, typalign);
3258  /* check for overflow of total request */
3259  if (!AllocSizeIsValid(nbytes))
3260  ereport(ERROR,
3261  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3262  errmsg("array size exceeds the maximum allowed (%d)",
3263  (int) MaxAllocSize)));
3264  }
3265  }
3266 
3267  /* Allocate and fill the result array */
3268  if (hasnulls)
3269  {
3270  dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
3271  nbytes += dataoffset;
3272  }
3273  else
3274  {
3275  dataoffset = 0; /* marker for no null bitmap */
3276  nbytes += ARR_OVERHEAD_NONULLS(ndim);
3277  }
3278  result = (ArrayType *) palloc0(nbytes);
3279  SET_VARSIZE(result, nbytes);
3280  result->ndim = ndim;
3281  result->dataoffset = dataoffset;
3282  result->elemtype = retType;
3283  memcpy(ARR_DIMS(result), AARR_DIMS(v), ndim * sizeof(int));
3284  memcpy(ARR_LBOUND(result), AARR_LBOUND(v), ndim * sizeof(int));
3285 
3286  CopyArrayEls(result,
3287  values, nulls, nitems,
3288  typlen, typbyval, typalign,
3289  false);
3290 
3291  /*
3292  * Note: do not risk trying to pfree the results of the called expression
3293  */
3294  pfree(values);
3295  pfree(nulls);
3296 
3297  return PointerGetDatum(result);
3298 }
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:303
#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:2218
#define PointerGetDatum(X)
Definition: postgres.h:600
bool * innermost_casenull
Definition: execnodes.h:112
int32 dataoffset
Definition: array.h:89
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:698
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3437
unsigned int Oid
Definition: postgres_ext.h:31
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:305
signed int int32
Definition: c.h:429
AnyArrayType * DatumGetAnyArrayP(Datum d)
#define ARR_LBOUND(a)
Definition: array.h:289
bool typbyval
Definition: array.h:233
void pfree(void *pointer)
Definition: mcxt.c:1169
char typalign
Definition: pg_type.h:176
#define ERROR
Definition: elog.h:46
Oid elemtype
Definition: array.h:90
#define ARR_DIMS(a)
Definition: array.h:287
ArrayMetaState inp_extra
Definition: array.h:246
int16 typlen
Definition: array.h:232
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:315
static void array_iter_setup(array_iter *it, AnyArrayType *a)
Definition: arrayaccess.h:49
Datum * innermost_caseval
Definition: execnodes.h:111
#define AllocSizeIsValid(size)
Definition: memutils.h:42
#define MaxAllocSize
Definition: memutils.h:40
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
#define AARR_DIMS(a)
Definition: array.h:331
#define AARR_ELEMTYPE(a)
Definition: array.h:328
#define ereport(elevel,...)
Definition: elog.h:157
#define AARR_LBOUND(a)
Definition: array.h:334
#define AARR_NDIM(a)
Definition: array.h:321
ArrayMetaState ret_extra
Definition: array.h:247
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:234
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define att_addlength_datum(cur_offset, attlen, attdatum)
Definition: tupmacs.h:164
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
Oid element_type
Definition: array.h:231
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:342
int ndim
Definition: array.h:88

◆ 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:267
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define MAXDIM
Definition: array.h:75
#define AARR_NDIM(a)
Definition: array.h:321
#define PG_RETURN_NULL()
Definition: fmgr.h:345

◆ array_ne()

Datum array_ne ( PG_FUNCTION_ARGS  )

Definition at line 3731 of file arrayfuncs.c.

References array_eq(), DatumGetBool, and PG_RETURN_BOOL.

3732 {
3734 }
#define DatumGetBool(X)
Definition: postgres.h:437
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
Datum array_eq(PG_FUNCTION_ARGS)
Definition: arrayfuncs.c:3602

◆ 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 4667 of file arrayfuncs.c.

References array_seek().

Referenced by array_copy(), and array_set_slice().

4669 {
4670  return array_seek(ptr, offset, nullbitmap, nitems,
4671  typlen, typbyval, typalign) - ptr;
4672 }
char typalign
Definition: pg_type.h:176
static char * array_seek(char *ptr, int offset, bits8 *nullbitmap, int nitems, int typlen, bool typbyval, char typalign)
Definition: arrayfuncs.c:4619

◆ 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:267
static bool array_isspace(char ch)
Definition: arrayfuncs.c:433
MemoryContext fn_mcxt
Definition: fmgr.h:65
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:1299
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:1576
bool typbyval
Definition: array.h:233
#define sprintf
Definition: port.h:218
void pfree(void *pointer)
Definition: mcxt.c:1169
char typalign
Definition: pg_type.h:176
#define APPENDCHAR(ch)
#define APPENDSTR(str)
int16 typlen
Definition: array.h:232
char typdelim
Definition: array.h:235
static void array_iter_setup(array_iter *it, AnyArrayType *a)
Definition: arrayaccess.h:49
#define MAXDIM
Definition: array.h:75
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:411
#define AARR_DIMS(a)
Definition: array.h:331
#define AARR_ELEMTYPE(a)
Definition: array.h:328
#define AARR_LBOUND(a)
Definition: array.h:334
#define Assert(condition)
Definition: c.h:804
Oid typioparam
Definition: array.h:236
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:362
#define AARR_NDIM(a)
Definition: array.h:321
Oid typiofunc
Definition: array.h:237
char typalign
Definition: array.h:234
static Datum values[MAXATTR]
Definition: bootstrap.c:166
void * palloc(Size size)
Definition: mcxt.c:1062
FmgrInfo proc
Definition: array.h:238
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
int i
Oid element_type
Definition: array.h:231
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:2272

◆ 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:303
MemoryContext fn_mcxt
Definition: fmgr.h:65
int32 dataoffset
Definition: array.h:89
StringInfoData * StringInfo
Definition: stringinfo.h:44
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int errcode(int sqlerrcode)
Definition: elog.c:698
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:3437
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:305
signed int int32
Definition: c.h:429
#define ARR_LBOUND(a)
Definition: array.h:289
bool typbyval
Definition: array.h:233
void pfree(void *pointer)
Definition: mcxt.c:1169
char typalign
Definition: pg_type.h:176
#define ERROR
Definition: elog.h:46
Oid elemtype
Definition: array.h:90
#define ARR_DIMS(a)
Definition: array.h:287
int16 typlen
Definition: array.h:232
static char * buf
Definition: pg_test_fsync.c:68
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
char typdelim
Definition: array.h:235
#define MAXDIM
Definition: array.h:75
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:258
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:109
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
Oid typioparam
Definition: array.h:236
char * format_type_extended(Oid type_oid, int32 typemod, bits16 flags)
Definition: format_type.c:112
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:237
char typalign
Definition: array.h:234
#define FirstGenbkiObjectId
Definition: transam.h:188
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
FmgrInfo proc
Definition: array.h:238
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
int i
Oid element_type
Definition: array.h:231
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:342
int ndim
Definition: array.h:88
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:2272

◆ array_ref()

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

Definition at line 3103 of file arrayfuncs.c.

References array_get_element(), and PointerGetDatum.

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

3106 {
3107  return array_get_element(PointerGetDatum(array), nSubscripts, indx,
3108  arraytyplen, elmlen, elmbyval, elmalign,
3109  isNull);
3110 }
#define PointerGetDatum(X)
Definition: postgres.h:600
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 6357 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.

6358 {
6359  ArrayType *array;
6360  Datum search = PG_GETARG_DATUM(1);
6361  bool search_isnull = PG_ARGISNULL(1);
6362 
6363  if (PG_ARGISNULL(0))
6364  PG_RETURN_NULL();
6365  array = PG_GETARG_ARRAYTYPE_P(0);
6366 
6367  array = array_replace_internal(array,
6368  search, search_isnull,
6369  (Datum) 0, true,
6370  true, PG_GET_COLLATION(),
6371  fcinfo);
6372  PG_RETURN_ARRAYTYPE_P(array);
6373 }
#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:256
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:258
uintptr_t Datum
Definition: postgres.h:411
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:6099
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_RETURN_NULL()
Definition: fmgr.h:345

◆ array_replace()

Datum array_replace ( PG_FUNCTION_ARGS  )

Definition at line 6379 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.

6380 {
6381  ArrayType *array;
6382  Datum search = PG_GETARG_DATUM(1);
6383  bool search_isnull = PG_ARGISNULL(1);
6384  Datum replace = PG_GETARG_DATUM(2);
6385  bool replace_isnull = PG_ARGISNULL(2);
6386 
6387  if (PG_ARGISNULL(0))
6388  PG_RETURN_NULL();
6389  array = PG_GETARG_ARRAYTYPE_P(0);
6390 
6391  array = array_replace_internal(array,
6392  search, search_isnull,
6393  replace, replace_isnull,
6394  false, PG_GET_COLLATION(),
6395  fcinfo);
6396  PG_RETURN_ARRAYTYPE_P(array);
6397 }
#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:256
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:258
uintptr_t Datum
Definition: postgres.h:411
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:6099
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_RETURN_NULL()
Definition: fmgr.h:345

◆ 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 6099 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().

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

◆ array_seek()

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

Definition at line 4619 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().

4621 {
4622  int bitmask;
4623  int i;
4624 
4625  /* easy if fixed-size elements and no NULLs */
4626  if (typlen > 0 && !nullbitmap)
4627  return ptr + nitems * ((Size) att_align_nominal(typlen, typalign));
4628 
4629  /* seems worth having separate loops for NULL and no-NULLs cases */
4630  if (nullbitmap)
4631  {
4632  nullbitmap += offset / 8;
4633  bitmask = 1 << (offset % 8);
4634 
4635  for (i = 0; i < nitems; i++)
4636  {
4637  if (*nullbitmap & bitmask)
4638  {
4639  ptr = att_addlength_pointer(ptr, typlen, ptr);
4640  ptr = (char *) att_align_nominal(ptr, typalign);
4641  }
4642  bitmask <<= 1;
4643  if (bitmask == 0x100)
4644  {
4645  nullbitmap++;
4646  bitmask = 1;
4647  }
4648  }
4649  }
4650  else
4651  {
4652  for (i = 0; i < nitems; i++)
4653  {
4654  ptr = att_addlength_pointer(ptr, typlen, ptr);
4655  ptr = (char *) att_align_nominal(ptr, typalign);
4656  }
4657  }
4658  return ptr;
4659 }
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
char typalign
Definition: pg_type.h:176
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:176
size_t Size
Definition: c.h:540
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:267
#define VARDATA(PTR)
Definition: postgres.h:315
MemoryContext fn_mcxt
Definition: fmgr.h:65
#define VARSIZE(PTR)
Definition: postgres.h:316
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:627
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define AARR_HASNULL(a)
Definition: array.h:324
int errcode(int sqlerrcode)
Definition: elog.c:698
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define PG_RETURN_BYTEA_P(x)
Definition: fmgr.h:371
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
bytea * pq_endtypsend(StringInfo buf)
Definition: pqformat.c:348
bool typbyval
Definition: array.h:233
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
void pfree(void *pointer)
Definition: mcxt.c:1169
char typalign
Definition: pg_type.h:176
#define ERROR
Definition: elog.h:46
int16 typlen
Definition: array.h:232
static char * buf
Definition: pg_test_fsync.c:68
char typdelim
Definition: array.h:235
static void array_iter_setup(array_iter *it, AnyArrayType *a)
Definition: arrayaccess.h:49
bytea * SendFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1637
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
uintptr_t Datum
Definition: postgres.h:411
#define AARR_DIMS(a)
Definition: array.h:331
#define AARR_ELEMTYPE(a)
Definition: array.h:328
#define ereport(elevel,...)
Definition: elog.h:157
#define AARR_LBOUND(a)
Definition: array.h:334
Oid typioparam
Definition: array.h:236
#define AARR_NDIM(a)
Definition: array.h:321
Oid typiofunc
Definition: array.h:237
char typalign
Definition: array.h:234
void pq_sendbytes(StringInfo buf, const char *data, int datalen)
Definition: pqformat.c:125
int errmsg(const char *fmt,...)
Definition: elog.c:909
FmgrInfo proc
Definition: array.h:238
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
int i
Oid element_type
Definition: array.h:231
Definition: c.h:621
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:2272

◆ 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 3120 of file arrayfuncs.c.

References array_set_element(), DatumGetArrayTypeP, and PointerGetDatum.

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

3123 {
3125  nSubscripts, indx,
3126  dataValue, isNull,
3127  arraytyplen,
3128  elmlen, elmbyval, elmalign));
3129 }
#define PointerGetDatum(X)
Definition: postgres.h:600
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:2222
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ 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 2222 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(), and array_subscript_assign().

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

◆ 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 2504 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().

2509 {
2510  ExpandedArrayHeader *eah;
2511  Datum *dvalues;
2512  bool *dnulls;
2513  int i,
2514  ndim,
2515  dim[MAXDIM],
2516  lb[MAXDIM],
2517  offset;
2518  bool dimschanged,
2519  newhasnulls;
2520  int addedbefore,
2521  addedafter;
2522  char *oldValue;
2523 
2524  /* Convert to R/W object if not so already */
2525  eah = DatumGetExpandedArray(arraydatum);
2526 
2527  /* Sanity-check caller's info against object; we don't use it otherwise */
2528  Assert(arraytyplen == -1);
2529  Assert(elmlen == eah->typlen);
2530  Assert(elmbyval == eah->typbyval);
2531  Assert<