PostgreSQL Source Code  git master
array_userfuncs.c File Reference
#include "postgres.h"
#include "catalog/pg_type.h"
#include "libpq/pqformat.h"
#include "common/int.h"
#include "port/pg_bitutils.h"
#include "utils/array.h"
#include "utils/datum.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/typcache.h"
Include dependency graph for array_userfuncs.c:

Go to the source code of this file.

Data Structures

struct  SerialIOData
 
struct  DeserialIOData
 

Typedefs

typedef struct SerialIOData SerialIOData
 
typedef struct DeserialIOData DeserialIOData
 

Functions

static Datum array_position_common (FunctionCallInfo fcinfo)
 
static ExpandedArrayHeaderfetch_array_arg_replace_nulls (FunctionCallInfo fcinfo, int argno)
 
Datum array_append (PG_FUNCTION_ARGS)
 
Datum array_prepend (PG_FUNCTION_ARGS)
 
Datum array_cat (PG_FUNCTION_ARGS)
 
Datum array_agg_transfn (PG_FUNCTION_ARGS)
 
Datum array_agg_combine (PG_FUNCTION_ARGS)
 
Datum array_agg_serialize (PG_FUNCTION_ARGS)
 
Datum array_agg_deserialize (PG_FUNCTION_ARGS)
 
Datum array_agg_finalfn (PG_FUNCTION_ARGS)
 
Datum array_agg_array_transfn (PG_FUNCTION_ARGS)
 
Datum array_agg_array_combine (PG_FUNCTION_ARGS)
 
Datum array_agg_array_serialize (PG_FUNCTION_ARGS)
 
Datum array_agg_array_deserialize (PG_FUNCTION_ARGS)
 
Datum array_agg_array_finalfn (PG_FUNCTION_ARGS)
 
Datum array_position (PG_FUNCTION_ARGS)
 
Datum array_position_start (PG_FUNCTION_ARGS)
 
Datum array_positions (PG_FUNCTION_ARGS)
 

Typedef Documentation

◆ DeserialIOData

◆ SerialIOData

typedef struct SerialIOData SerialIOData

Function Documentation

◆ array_agg_array_combine()

Datum array_agg_array_combine ( PG_FUNCTION_ARGS  )

Definition at line 913 of file array_userfuncs.c.

914 {
915  ArrayBuildStateArr *state1;
916  ArrayBuildStateArr *state2;
917  MemoryContext agg_context;
918  MemoryContext old_context;
919 
920  if (!AggCheckCallContext(fcinfo, &agg_context))
921  elog(ERROR, "aggregate function called in non-aggregate context");
922 
923  state1 = PG_ARGISNULL(0) ? NULL : (ArrayBuildStateArr *) PG_GETARG_POINTER(0);
924  state2 = PG_ARGISNULL(1) ? NULL : (ArrayBuildStateArr *) PG_GETARG_POINTER(1);
925 
926  if (state2 == NULL)
927  {
928  /*
929  * NULL state2 is easy, just return state1, which we know is already
930  * in the agg_context
931  */
932  if (state1 == NULL)
933  PG_RETURN_NULL();
934  PG_RETURN_POINTER(state1);
935  }
936 
937  if (state1 == NULL)
938  {
939  /* We must copy state2's data into the agg_context */
940  old_context = MemoryContextSwitchTo(agg_context);
941 
942  state1 = initArrayResultArr(state2->array_type, InvalidOid,
943  agg_context, false);
944 
945  state1->abytes = state2->abytes;
946  state1->data = (char *) palloc(state1->abytes);
947 
948  if (state2->nullbitmap)
949  {
950  int size = (state2->aitems + 7) / 8;
951 
952  state1->nullbitmap = (bits8 *) palloc(size);
953  memcpy(state1->nullbitmap, state2->nullbitmap, size);
954  }
955 
956  memcpy(state1->data, state2->data, state2->nbytes);
957  state1->nbytes = state2->nbytes;
958  state1->aitems = state2->aitems;
959  state1->nitems = state2->nitems;
960  state1->ndims = state2->ndims;
961  memcpy(state1->dims, state2->dims, sizeof(state2->dims));
962  memcpy(state1->lbs, state2->lbs, sizeof(state2->lbs));
963  state1->array_type = state2->array_type;
964  state1->element_type = state2->element_type;
965 
966  MemoryContextSwitchTo(old_context);
967 
968  PG_RETURN_POINTER(state1);
969  }
970 
971  /* We only need to combine the two states if state2 has any items */
972  else if (state2->nitems > 0)
973  {
974  MemoryContext oldContext;
975  int reqsize = state1->nbytes + state2->nbytes;
976  int i;
977 
978  /*
979  * Check the states are compatible with each other. Ensure we use the
980  * same error messages that are listed in accumArrayResultArr so that
981  * the same error is shown as would have been if we'd not used the
982  * combine function for the aggregation.
983  */
984  if (state1->ndims != state2->ndims)
985  ereport(ERROR,
986  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
987  errmsg("cannot accumulate arrays of different dimensionality")));
988 
989  /* Check dimensions match ignoring the first dimension. */
990  for (i = 1; i < state1->ndims; i++)
991  {
992  if (state1->dims[i] != state2->dims[i] || state1->lbs[i] != state2->lbs[i])
993  ereport(ERROR,
994  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
995  errmsg("cannot accumulate arrays of different dimensionality")));
996  }
997 
998 
999  oldContext = MemoryContextSwitchTo(state1->mcontext);
1000 
1001  /*
1002  * If there's not enough space in state1 then we'll need to reallocate
1003  * more.
1004  */
1005  if (state1->abytes < reqsize)
1006  {
1007  /* use a power of 2 size rather than allocating just reqsize */
1008  state1->abytes = pg_nextpower2_32(reqsize);
1009  state1->data = (char *) repalloc(state1->data, state1->abytes);
1010  }
1011 
1012  if (state2->nullbitmap)
1013  {
1014  int newnitems = state1->nitems + state2->nitems;
1015 
1016  if (state1->nullbitmap == NULL)
1017  {
1018  /*
1019  * First input with nulls; we must retrospectively handle any
1020  * previous inputs by marking all their items non-null.
1021  */
1022  state1->aitems = pg_nextpower2_32(Max(256, newnitems + 1));
1023  state1->nullbitmap = (bits8 *) palloc((state1->aitems + 7) / 8);
1024  array_bitmap_copy(state1->nullbitmap, 0,
1025  NULL, 0,
1026  state1->nitems);
1027  }
1028  else if (newnitems > state1->aitems)
1029  {
1030  int newaitems = state1->aitems + state2->aitems;
1031 
1032  state1->aitems = pg_nextpower2_32(newaitems);
1033  state1->nullbitmap = (bits8 *)
1034  repalloc(state1->nullbitmap, (state1->aitems + 7) / 8);
1035  }
1036  array_bitmap_copy(state1->nullbitmap, state1->nitems,
1037  state2->nullbitmap, 0,
1038  state2->nitems);
1039  }
1040 
1041  memcpy(state1->data + state1->nbytes, state2->data, state2->nbytes);
1042  state1->nbytes += state2->nbytes;
1043  state1->nitems += state2->nitems;
1044 
1045  state1->dims[0] += state2->dims[0];
1046  /* remaing dims already match, per test above */
1047 
1048  Assert(state1->array_type == state2->array_type);
1049  Assert(state1->element_type == state2->element_type);
1050 
1051  MemoryContextSwitchTo(oldContext);
1052  }
1053 
1054  PG_RETURN_POINTER(state1);
1055 }
ArrayBuildStateArr * initArrayResultArr(Oid array_type, Oid element_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5469
void array_bitmap_copy(bits8 *destbitmap, int destoffset, const bits8 *srcbitmap, int srcoffset, int nitems)
Definition: arrayfuncs.c:4937
#define Max(x, y)
Definition: c.h:982
uint8 bits8
Definition: c.h:497
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1456
void * palloc(Size size)
Definition: mcxt.c:1210
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:4513
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:140
#define InvalidOid
Definition: postgres_ext.h:36
bits8 * nullbitmap
Definition: array.h:202
int lbs[MAXDIM]
Definition: array.h:209
MemoryContext mcontext
Definition: array.h:200
int dims[MAXDIM]
Definition: array.h:208

References ArrayBuildStateArr::abytes, AggCheckCallContext(), ArrayBuildStateArr::aitems, array_bitmap_copy(), ArrayBuildStateArr::array_type, Assert(), ArrayBuildStateArr::data, ArrayBuildStateArr::dims, ArrayBuildStateArr::element_type, elog(), ereport, errcode(), errmsg(), ERROR, i, initArrayResultArr(), InvalidOid, ArrayBuildStateArr::lbs, Max, ArrayBuildStateArr::mcontext, MemoryContextSwitchTo(), ArrayBuildStateArr::nbytes, ArrayBuildStateArr::ndims, ArrayBuildStateArr::nitems, ArrayBuildStateArr::nullbitmap, palloc(), PG_ARGISNULL, PG_GETARG_POINTER, pg_nextpower2_32(), PG_RETURN_NULL, PG_RETURN_POINTER, and repalloc().

◆ array_agg_array_deserialize()

Datum array_agg_array_deserialize ( PG_FUNCTION_ARGS  )

Definition at line 1121 of file array_userfuncs.c.

1122 {
1123  bytea *sstate;
1124  ArrayBuildStateArr *result;
1126  Oid element_type;
1127  Oid array_type;
1128  int nbytes;
1129  const char *temp;
1130 
1131  /* cannot be called directly because of internal-type argument */
1132  Assert(AggCheckCallContext(fcinfo, NULL));
1133 
1134  sstate = PG_GETARG_BYTEA_PP(0);
1135 
1136  /*
1137  * Copy the bytea into a StringInfo so that we can "receive" it using the
1138  * standard recv-function infrastructure.
1139  */
1140  initStringInfo(&buf);
1142  VARDATA_ANY(sstate), VARSIZE_ANY_EXHDR(sstate));
1143 
1144  /* element_type */
1145  element_type = pq_getmsgint(&buf, 4);
1146 
1147  /* array_type */
1148  array_type = pq_getmsgint(&buf, 4);
1149 
1150  /* nbytes */
1151  nbytes = pq_getmsgint(&buf, 4);
1152 
1153  result = initArrayResultArr(array_type, element_type,
1154  CurrentMemoryContext, false);
1155 
1156  result->abytes = 1024;
1157  while (result->abytes < nbytes)
1158  result->abytes *= 2;
1159 
1160  result->data = (char *) palloc(result->abytes);
1161 
1162  /* data */
1163  temp = pq_getmsgbytes(&buf, nbytes);
1164  memcpy(result->data, temp, nbytes);
1165  result->nbytes = nbytes;
1166 
1167  /* abytes */
1168  result->abytes = pq_getmsgint(&buf, 4);
1169 
1170  /* aitems: might be 0 */
1171  result->aitems = pq_getmsgint(&buf, 4);
1172 
1173  /* nullbitmap */
1174  if (result->aitems > 0)
1175  {
1176  int size = (result->aitems + 7) / 8;
1177 
1178  result->nullbitmap = (bits8 *) palloc(size);
1179  temp = pq_getmsgbytes(&buf, size);
1180  memcpy(result->nullbitmap, temp, size);
1181  }
1182  else
1183  result->nullbitmap = NULL;
1184 
1185  /* nitems */
1186  result->nitems = pq_getmsgint(&buf, 4);
1187 
1188  /* ndims */
1189  result->ndims = pq_getmsgint(&buf, 4);
1190 
1191  /* dims */
1192  temp = pq_getmsgbytes(&buf, sizeof(result->dims));
1193  memcpy(result->dims, temp, sizeof(result->dims));
1194 
1195  /* lbs */
1196  temp = pq_getmsgbytes(&buf, sizeof(result->lbs));
1197  memcpy(result->lbs, temp, sizeof(result->lbs));
1198 
1199  pq_getmsgend(&buf);
1200  pfree(buf.data);
1201 
1202  PG_RETURN_POINTER(result);
1203 }
#define PG_GETARG_BYTEA_PP(n)
Definition: fmgr.h:308
void pfree(void *pointer)
Definition: mcxt.c:1436
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
static char * buf
Definition: pg_test_fsync.c:67
unsigned int Oid
Definition: postgres_ext.h:31
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:418
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:638
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:511
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:227
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Definition: c.h:671
#define VARDATA_ANY(PTR)
Definition: varatt.h:324
#define VARSIZE_ANY_EXHDR(PTR)
Definition: varatt.h:317

References ArrayBuildStateArr::abytes, AggCheckCallContext(), ArrayBuildStateArr::aitems, appendBinaryStringInfo(), Assert(), buf, CurrentMemoryContext, ArrayBuildStateArr::data, ArrayBuildStateArr::dims, initArrayResultArr(), initStringInfo(), ArrayBuildStateArr::lbs, ArrayBuildStateArr::nbytes, ArrayBuildStateArr::ndims, ArrayBuildStateArr::nitems, ArrayBuildStateArr::nullbitmap, palloc(), pfree(), PG_GETARG_BYTEA_PP, PG_RETURN_POINTER, pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), VARDATA_ANY, and VARSIZE_ANY_EXHDR.

◆ array_agg_array_finalfn()

Datum array_agg_array_finalfn ( PG_FUNCTION_ARGS  )

Definition at line 1206 of file array_userfuncs.c.

1207 {
1208  Datum result;
1210 
1211  /* cannot be called directly because of internal-type argument */
1212  Assert(AggCheckCallContext(fcinfo, NULL));
1213 
1215 
1216  if (state == NULL)
1217  PG_RETURN_NULL(); /* returns null iff no input values */
1218 
1219  /*
1220  * Make the result. We cannot release the ArrayBuildStateArr because
1221  * sometimes aggregate final functions are re-executed. Rather, it is
1222  * nodeAgg.c's responsibility to reset the aggcontext when it's safe to do
1223  * so.
1224  */
1225  result = makeArrayResultArr(state, CurrentMemoryContext, false);
1226 
1227  PG_RETURN_DATUM(result);
1228 }
Datum makeArrayResultArr(ArrayBuildStateArr *astate, MemoryContext rcontext, bool release)
Definition: arrayfuncs.c:5668
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
uintptr_t Datum
Definition: postgres.h:64
Definition: regguts.h:318

References AggCheckCallContext(), Assert(), CurrentMemoryContext, makeArrayResultArr(), PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_DATUM, and PG_RETURN_NULL.

◆ array_agg_array_serialize()

Datum array_agg_array_serialize ( PG_FUNCTION_ARGS  )

Definition at line 1062 of file array_userfuncs.c.

1063 {
1066  bytea *result;
1067 
1068  /* cannot be called directly because of internal-type argument */
1069  Assert(AggCheckCallContext(fcinfo, NULL));
1070 
1072 
1073  pq_begintypsend(&buf);
1074 
1075  /*
1076  * element_type. Putting this first is more convenient in deserialization
1077  * so that we can init the new state sooner.
1078  */
1079  pq_sendint32(&buf, state->element_type);
1080 
1081  /* array_type */
1082  pq_sendint32(&buf, state->array_type);
1083 
1084  /* nbytes */
1085  pq_sendint32(&buf, state->nbytes);
1086 
1087  /* data */
1088  pq_sendbytes(&buf, state->data, state->nbytes);
1089 
1090  /* abytes */
1091  pq_sendint32(&buf, state->abytes);
1092 
1093  /* aitems */
1094  pq_sendint32(&buf, state->aitems);
1095 
1096  /* nullbitmap */
1097  if (state->nullbitmap)
1098  {
1099  Assert(state->aitems > 0);
1100  pq_sendbytes(&buf, (char *) state->nullbitmap, (state->aitems + 7) / 8);
1101  }
1102 
1103  /* nitems */
1104  pq_sendint32(&buf, state->nitems);
1105 
1106  /* ndims */
1107  pq_sendint32(&buf, state->ndims);
1108 
1109  /* dims: XXX should we just send ndims elements? */
1110  pq_sendbytes(&buf, (char *) state->dims, sizeof(state->dims));
1111 
1112  /* lbs */
1113  pq_sendbytes(&buf, (char *) state->lbs, sizeof(state->lbs));
1114 
1115  result = pq_endtypsend(&buf);
1116 
1117  PG_RETURN_BYTEA_P(result);
1118 }
#define PG_RETURN_BYTEA_P(x)
Definition: fmgr.h:371
void pq_begintypsend(StringInfo buf)
Definition: pqformat.c:329
void pq_sendbytes(StringInfo buf, const char *data, int datalen)
Definition: pqformat.c:126
bytea * pq_endtypsend(StringInfo buf)
Definition: pqformat.c:349
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145

References AggCheckCallContext(), Assert(), buf, PG_GETARG_POINTER, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendbytes(), and pq_sendint32().

◆ array_agg_array_transfn()

Datum array_agg_array_transfn ( PG_FUNCTION_ARGS  )

Definition at line 869 of file array_userfuncs.c.

870 {
871  Oid arg1_typeid = get_fn_expr_argtype(fcinfo->flinfo, 1);
872  MemoryContext aggcontext;
874 
875  if (arg1_typeid == InvalidOid)
876  ereport(ERROR,
877  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
878  errmsg("could not determine input data type")));
879 
880  /*
881  * Note: we do not need a run-time check about whether arg1_typeid is a
882  * valid array type, because the parser would have verified that while
883  * resolving the input/result types of this polymorphic aggregate.
884  */
885 
886  if (!AggCheckCallContext(fcinfo, &aggcontext))
887  {
888  /* cannot be called directly because of internal-type argument */
889  elog(ERROR, "array_agg_array_transfn called in non-aggregate context");
890  }
891 
892 
893  if (PG_ARGISNULL(0))
894  state = initArrayResultArr(arg1_typeid, InvalidOid, aggcontext, false);
895  else
897 
899  PG_GETARG_DATUM(1),
900  PG_ARGISNULL(1),
901  arg1_typeid,
902  aggcontext);
903 
904  /*
905  * The transition type for array_agg() is declared to be "internal", which
906  * is a pass-by-value type the same size as a pointer. So we can safely
907  * pass the ArrayBuildStateArr pointer through nodeAgg.c's machinations.
908  */
910 }
ArrayBuildStateArr * accumArrayResultArr(ArrayBuildStateArr *astate, Datum dvalue, bool disnull, Oid array_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5515
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1897
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268

References accumArrayResultArr(), AggCheckCallContext(), elog(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), initArrayResultArr(), InvalidOid, PG_ARGISNULL, PG_GETARG_DATUM, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ array_agg_combine()

Datum array_agg_combine ( PG_FUNCTION_ARGS  )

Definition at line 524 of file array_userfuncs.c.

525 {
526  ArrayBuildState *state1;
527  ArrayBuildState *state2;
528  MemoryContext agg_context;
529  MemoryContext old_context;
530 
531  if (!AggCheckCallContext(fcinfo, &agg_context))
532  elog(ERROR, "aggregate function called in non-aggregate context");
533 
534  state1 = PG_ARGISNULL(0) ? NULL : (ArrayBuildState *) PG_GETARG_POINTER(0);
535  state2 = PG_ARGISNULL(1) ? NULL : (ArrayBuildState *) PG_GETARG_POINTER(1);
536 
537  if (state2 == NULL)
538  {
539  /*
540  * NULL state2 is easy, just return state1, which we know is already
541  * in the agg_context
542  */
543  if (state1 == NULL)
544  PG_RETURN_NULL();
545  PG_RETURN_POINTER(state1);
546  }
547 
548  if (state1 == NULL)
549  {
550  /* We must copy state2's data into the agg_context */
551  state1 = initArrayResultWithSize(state2->element_type, agg_context,
552  false, state2->alen);
553 
554  old_context = MemoryContextSwitchTo(agg_context);
555 
556  for (int i = 0; i < state2->nelems; i++)
557  {
558  if (!state2->dnulls[i])
559  state1->dvalues[i] = datumCopy(state2->dvalues[i],
560  state1->typbyval,
561  state1->typlen);
562  else
563  state1->dvalues[i] = (Datum) 0;
564  }
565 
566  MemoryContextSwitchTo(old_context);
567 
568  memcpy(state1->dnulls, state2->dnulls, sizeof(bool) * state2->nelems);
569 
570  state1->nelems = state2->nelems;
571 
572  PG_RETURN_POINTER(state1);
573  }
574  else if (state2->nelems > 0)
575  {
576  /* We only need to combine the two states if state2 has any elements */
577  int reqsize = state1->nelems + state2->nelems;
578  MemoryContext oldContext = MemoryContextSwitchTo(state1->mcontext);
579 
580  Assert(state1->element_type == state2->element_type);
581 
582  /* Enlarge state1 arrays if needed */
583  if (state1->alen < reqsize)
584  {
585  /* Use a power of 2 size rather than allocating just reqsize */
586  state1->alen = pg_nextpower2_32(reqsize);
587  state1->dvalues = (Datum *) repalloc(state1->dvalues,
588  state1->alen * sizeof(Datum));
589  state1->dnulls = (bool *) repalloc(state1->dnulls,
590  state1->alen * sizeof(bool));
591  }
592 
593  /* Copy in the state2 elements to the end of the state1 arrays */
594  for (int i = 0; i < state2->nelems; i++)
595  {
596  if (!state2->dnulls[i])
597  state1->dvalues[i + state1->nelems] =
598  datumCopy(state2->dvalues[i],
599  state1->typbyval,
600  state1->typlen);
601  else
602  state1->dvalues[i + state1->nelems] = (Datum) 0;
603  }
604 
605  memcpy(&state1->dnulls[state1->nelems], state2->dnulls,
606  sizeof(bool) * state2->nelems);
607 
608  state1->nelems = reqsize;
609 
610  MemoryContextSwitchTo(oldContext);
611  }
612 
613  PG_RETURN_POINTER(state1);
614 }
ArrayBuildState * initArrayResultWithSize(Oid element_type, MemoryContext rcontext, bool subcontext, int initsize)
Definition: arrayfuncs.c:5281
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
bool * dnulls
Definition: array.h:184
bool typbyval
Definition: array.h:189
MemoryContext mcontext
Definition: array.h:182
int16 typlen
Definition: array.h:188
Oid element_type
Definition: array.h:187
Datum * dvalues
Definition: array.h:183

References AggCheckCallContext(), ArrayBuildState::alen, Assert(), datumCopy(), ArrayBuildState::dnulls, ArrayBuildState::dvalues, ArrayBuildState::element_type, elog(), ERROR, i, initArrayResultWithSize(), ArrayBuildState::mcontext, MemoryContextSwitchTo(), ArrayBuildState::nelems, PG_ARGISNULL, PG_GETARG_POINTER, pg_nextpower2_32(), PG_RETURN_NULL, PG_RETURN_POINTER, repalloc(), ArrayBuildState::typbyval, and ArrayBuildState::typlen.

◆ array_agg_deserialize()

Datum array_agg_deserialize ( PG_FUNCTION_ARGS  )

Definition at line 711 of file array_userfuncs.c.

712 {
713  bytea *sstate;
714  ArrayBuildState *result;
716  Oid element_type;
717  int64 nelems;
718  const char *temp;
719 
720  if (!AggCheckCallContext(fcinfo, NULL))
721  elog(ERROR, "aggregate function called in non-aggregate context");
722 
723  sstate = PG_GETARG_BYTEA_PP(0);
724 
725  /*
726  * Copy the bytea into a StringInfo so that we can "receive" it using the
727  * standard recv-function infrastructure.
728  */
731  VARDATA_ANY(sstate), VARSIZE_ANY_EXHDR(sstate));
732 
733  /* element_type */
734  element_type = pq_getmsgint(&buf, 4);
735 
736  /* nelems */
737  nelems = pq_getmsgint64(&buf);
738 
739  /* Create output ArrayBuildState with the needed number of elements */
740  result = initArrayResultWithSize(element_type, CurrentMemoryContext,
741  false, nelems);
742  result->nelems = nelems;
743 
744  /* typlen */
745  result->typlen = pq_getmsgint(&buf, 2);
746 
747  /* typbyval */
748  result->typbyval = pq_getmsgbyte(&buf);
749 
750  /* typalign */
751  result->typalign = pq_getmsgbyte(&buf);
752 
753  /* dnulls */
754  temp = pq_getmsgbytes(&buf, sizeof(bool) * nelems);
755  memcpy(result->dnulls, temp, sizeof(bool) * nelems);
756 
757  /* dvalues --- see comment in array_agg_serialize */
758  if (result->typbyval)
759  {
760  temp = pq_getmsgbytes(&buf, sizeof(Datum) * nelems);
761  memcpy(result->dvalues, temp, sizeof(Datum) * nelems);
762  }
763  else
764  {
765  DeserialIOData *iodata;
766 
767  /* Avoid repeat catalog lookups for typreceive function */
768  iodata = (DeserialIOData *) fcinfo->flinfo->fn_extra;
769  if (iodata == NULL)
770  {
771  Oid typreceive;
772 
773  iodata = (DeserialIOData *)
774  MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
775  sizeof(DeserialIOData));
776  getTypeBinaryInputInfo(element_type, &typreceive,
777  &iodata->typioparam);
778  fmgr_info_cxt(typreceive, &iodata->typreceive,
779  fcinfo->flinfo->fn_mcxt);
780  fcinfo->flinfo->fn_extra = (void *) iodata;
781  }
782 
783  for (int i = 0; i < nelems; i++)
784  {
785  int itemlen;
786  StringInfoData elem_buf;
787  char csave;
788 
789  if (result->dnulls[i])
790  {
791  result->dvalues[i] = (Datum) 0;
792  continue;
793  }
794 
795  itemlen = pq_getmsgint(&buf, 4);
796  if (itemlen < 0 || itemlen > (buf.len - buf.cursor))
797  ereport(ERROR,
798  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
799  errmsg("insufficient data left in message")));
800 
801  /*
802  * Rather than copying data around, we just set up a phony
803  * StringInfo pointing to the correct portion of the input buffer.
804  * We assume we can scribble on the input buffer so as to maintain
805  * the convention that StringInfos have a trailing null.
806  */
807  elem_buf.data = &buf.data[buf.cursor];
808  elem_buf.maxlen = itemlen + 1;
809  elem_buf.len = itemlen;
810  elem_buf.cursor = 0;
811 
812  buf.cursor += itemlen;
813 
814  csave = buf.data[buf.cursor];
815  buf.data[buf.cursor] = '\0';
816 
817  /* Now call the element's receiveproc */
818  result->dvalues[i] = ReceiveFunctionCall(&iodata->typreceive,
819  &elem_buf,
820  iodata->typioparam,
821  -1);
822 
823  buf.data[buf.cursor] = csave;
824  }
825  }
826 
827  pq_getmsgend(&buf);
828  pfree(buf.data);
829 
830  PG_RETURN_POINTER(result);
831 }
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:137
Datum ReceiveFunctionCall(FmgrInfo *flinfo, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:1684
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2898
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1005
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:402
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:456
char typalign
Definition: array.h:190
FmgrInfo typreceive
MemoryContext fn_mcxt
Definition: fmgr.h:65

References AggCheckCallContext(), appendBinaryStringInfo(), buf, CurrentMemoryContext, StringInfoData::cursor, StringInfoData::data, ArrayBuildState::dnulls, ArrayBuildState::dvalues, elog(), ereport, errcode(), errmsg(), ERROR, fmgr_info_cxt(), FmgrInfo::fn_mcxt, getTypeBinaryInputInfo(), i, if(), initArrayResultWithSize(), initStringInfo(), StringInfoData::len, StringInfoData::maxlen, MemoryContextAlloc(), ArrayBuildState::nelems, pfree(), PG_GETARG_BYTEA_PP, PG_RETURN_POINTER, pq_getmsgbyte(), pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), pq_getmsgint64(), ReceiveFunctionCall(), ArrayBuildState::typalign, ArrayBuildState::typbyval, DeserialIOData::typioparam, ArrayBuildState::typlen, DeserialIOData::typreceive, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

◆ array_agg_finalfn()

Datum array_agg_finalfn ( PG_FUNCTION_ARGS  )

Definition at line 834 of file array_userfuncs.c.

835 {
836  Datum result;
838  int dims[1];
839  int lbs[1];
840 
841  /* cannot be called directly because of internal-type argument */
842  Assert(AggCheckCallContext(fcinfo, NULL));
843 
845 
846  if (state == NULL)
847  PG_RETURN_NULL(); /* returns null iff no input values */
848 
849  dims[0] = state->nelems;
850  lbs[0] = 1;
851 
852  /*
853  * Make the result. We cannot release the ArrayBuildState because
854  * sometimes aggregate final functions are re-executed. Rather, it is
855  * nodeAgg.c's responsibility to reset the aggcontext when it's safe to do
856  * so.
857  */
858  result = makeMdArrayResult(state, 1, dims, lbs,
860  false);
861 
862  PG_RETURN_DATUM(result);
863 }
Datum makeMdArrayResult(ArrayBuildState *astate, int ndims, int *dims, int *lbs, MemoryContext rcontext, bool release)
Definition: arrayfuncs.c:5417

References AggCheckCallContext(), Assert(), CurrentMemoryContext, makeMdArrayResult(), PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_DATUM, and PG_RETURN_NULL.

◆ array_agg_serialize()

Datum array_agg_serialize ( PG_FUNCTION_ARGS  )

Definition at line 621 of file array_userfuncs.c.

622 {
625  bytea *result;
626 
627  /* cannot be called directly because of internal-type argument */
628  Assert(AggCheckCallContext(fcinfo, NULL));
629 
631 
633 
634  /*
635  * element_type. Putting this first is more convenient in deserialization
636  */
637  pq_sendint32(&buf, state->element_type);
638 
639  /*
640  * nelems -- send first so we know how large to make the dvalues and
641  * dnulls array during deserialization.
642  */
643  pq_sendint64(&buf, state->nelems);
644 
645  /* alen can be decided during deserialization */
646 
647  /* typlen */
648  pq_sendint16(&buf, state->typlen);
649 
650  /* typbyval */
651  pq_sendbyte(&buf, state->typbyval);
652 
653  /* typalign */
654  pq_sendbyte(&buf, state->typalign);
655 
656  /* dnulls */
657  pq_sendbytes(&buf, (char *) state->dnulls, sizeof(bool) * state->nelems);
658 
659  /*
660  * dvalues. By agreement with array_agg_deserialize, when the element
661  * type is byval, we just transmit the Datum array as-is, including any
662  * null elements. For by-ref types, we must invoke the element type's
663  * send function, and we skip null elements (which is why the nulls flags
664  * must be sent first).
665  */
666  if (state->typbyval)
667  pq_sendbytes(&buf, (char *) state->dvalues,
668  sizeof(Datum) * state->nelems);
669  else
670  {
671  SerialIOData *iodata;
672  int i;
673 
674  /* Avoid repeat catalog lookups for typsend function */
675  iodata = (SerialIOData *) fcinfo->flinfo->fn_extra;
676  if (iodata == NULL)
677  {
678  Oid typsend;
679  bool typisvarlena;
680 
681  iodata = (SerialIOData *)
682  MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
683  sizeof(SerialIOData));
684  getTypeBinaryOutputInfo(state->element_type, &typsend,
685  &typisvarlena);
686  fmgr_info_cxt(typsend, &iodata->typsend,
687  fcinfo->flinfo->fn_mcxt);
688  fcinfo->flinfo->fn_extra = (void *) iodata;
689  }
690 
691  for (i = 0; i < state->nelems; i++)
692  {
693  bytea *outputbytes;
694 
695  if (state->dnulls[i])
696  continue;
697  outputbytes = SendFunctionCall(&iodata->typsend,
698  state->dvalues[i]);
699  pq_sendint32(&buf, VARSIZE(outputbytes) - VARHDRSZ);
700  pq_sendbytes(&buf, VARDATA(outputbytes),
701  VARSIZE(outputbytes) - VARHDRSZ);
702  }
703  }
704 
705  result = pq_endtypsend(&buf);
706 
707  PG_RETURN_BYTEA_P(result);
708 }
#define VARHDRSZ
Definition: c.h:676
bytea * SendFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1731
void getTypeBinaryOutputInfo(Oid type, Oid *typSend, bool *typIsVarlena)
Definition: lsyscache.c:2931
static void pq_sendbyte(StringInfo buf, uint8 byt)
Definition: pqformat.h:161
static void pq_sendint64(StringInfo buf, uint64 i)
Definition: pqformat.h:153
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:137
FmgrInfo typsend
#define VARDATA(PTR)
Definition: varatt.h:278
#define VARSIZE(PTR)
Definition: varatt.h:279

References AggCheckCallContext(), Assert(), buf, fmgr_info_cxt(), FmgrInfo::fn_mcxt, getTypeBinaryOutputInfo(), i, if(), MemoryContextAlloc(), PG_GETARG_POINTER, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendbyte(), pq_sendbytes(), pq_sendint16(), pq_sendint32(), pq_sendint64(), SendFunctionCall(), SerialIOData::typsend, VARDATA, VARHDRSZ, and VARSIZE.

◆ array_agg_transfn()

Datum array_agg_transfn ( PG_FUNCTION_ARGS  )

Definition at line 478 of file array_userfuncs.c.

479 {
480  Oid arg1_typeid = get_fn_expr_argtype(fcinfo->flinfo, 1);
481  MemoryContext aggcontext;
483  Datum elem;
484 
485  if (arg1_typeid == InvalidOid)
486  ereport(ERROR,
487  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
488  errmsg("could not determine input data type")));
489 
490  /*
491  * Note: we do not need a run-time check about whether arg1_typeid is a
492  * valid array element type, because the parser would have verified that
493  * while resolving the input/result types of this polymorphic aggregate.
494  */
495 
496  if (!AggCheckCallContext(fcinfo, &aggcontext))
497  {
498  /* cannot be called directly because of internal-type argument */
499  elog(ERROR, "array_agg_transfn called in non-aggregate context");
500  }
501 
502  if (PG_ARGISNULL(0))
503  state = initArrayResult(arg1_typeid, aggcontext, false);
504  else
506 
507  elem = PG_ARGISNULL(1) ? (Datum) 0 : PG_GETARG_DATUM(1);
508 
510  elem,
511  PG_ARGISNULL(1),
512  arg1_typeid,
513  aggcontext);
514 
515  /*
516  * The transition type for array_agg() is declared to be "internal", which
517  * is a pass-by-value type the same size as a pointer. So we can safely
518  * pass the ArrayBuildState pointer through nodeAgg.c's machinations.
519  */
521 }
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5321
ArrayBuildState * initArrayResult(Oid element_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5264

References accumArrayResult(), AggCheckCallContext(), elog(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), initArrayResult(), InvalidOid, PG_ARGISNULL, PG_GETARG_DATUM, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ array_append()

Datum array_append ( PG_FUNCTION_ARGS  )

Definition at line 122 of file array_userfuncs.c.

123 {
124  ExpandedArrayHeader *eah;
125  Datum newelem;
126  bool isNull;
127  Datum result;
128  int *dimv,
129  *lb;
130  int indx;
131  ArrayMetaState *my_extra;
132 
133  eah = fetch_array_arg_replace_nulls(fcinfo, 0);
134  isNull = PG_ARGISNULL(1);
135  if (isNull)
136  newelem = (Datum) 0;
137  else
138  newelem = PG_GETARG_DATUM(1);
139 
140  if (eah->ndims == 1)
141  {
142  /* append newelem */
143  lb = eah->lbound;
144  dimv = eah->dims;
145 
146  /* index of added elem is at lb[0] + (dimv[0] - 1) + 1 */
147  if (pg_add_s32_overflow(lb[0], dimv[0], &indx))
148  ereport(ERROR,
149  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
150  errmsg("integer out of range")));
151  }
152  else if (eah->ndims == 0)
153  indx = 1;
154  else
155  ereport(ERROR,
156  (errcode(ERRCODE_DATA_EXCEPTION),
157  errmsg("argument must be empty or one-dimensional array")));
158 
159  /* Perform element insertion */
160  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
161 
162  result = array_set_element(EOHPGetRWDatum(&eah->hdr),
163  1, &indx, newelem, isNull,
164  -1, my_extra->typlen, my_extra->typbyval, my_extra->typalign);
165 
166  PG_RETURN_DATUM(result);
167 }
static ExpandedArrayHeader * fetch_array_arg_replace_nulls(FunctionCallInfo fcinfo, int argno)
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:2236
static Datum EOHPGetRWDatum(const struct ExpandedObjectHeader *eohptr)
static bool pg_add_s32_overflow(int32 a, int32 b, int32 *result)
Definition: int.h:104
char typalign
Definition: array.h:234
int16 typlen
Definition: array.h:232
bool typbyval
Definition: array.h:233
ExpandedObjectHeader hdr
Definition: array.h:111

References array_set_element(), ExpandedArrayHeader::dims, EOHPGetRWDatum(), ereport, errcode(), errmsg(), ERROR, fetch_array_arg_replace_nulls(), ExpandedArrayHeader::hdr, ExpandedArrayHeader::lbound, ExpandedArrayHeader::ndims, pg_add_s32_overflow(), PG_ARGISNULL, PG_GETARG_DATUM, PG_RETURN_DATUM, ArrayMetaState::typalign, ArrayMetaState::typbyval, and ArrayMetaState::typlen.

◆ array_cat()

Datum array_cat ( PG_FUNCTION_ARGS  )

Definition at line 239 of file array_userfuncs.c.

240 {
241  ArrayType *v1,
242  *v2;
243  ArrayType *result;
244  int *dims,
245  *lbs,
246  ndims,
247  nitems,
248  ndatabytes,
249  nbytes;
250  int *dims1,
251  *lbs1,
252  ndims1,
253  nitems1,
254  ndatabytes1;
255  int *dims2,
256  *lbs2,
257  ndims2,
258  nitems2,
259  ndatabytes2;
260  int i;
261  char *dat1,
262  *dat2;
263  bits8 *bitmap1,
264  *bitmap2;
265  Oid element_type;
266  Oid element_type1;
267  Oid element_type2;
268  int32 dataoffset;
269 
270  /* Concatenating a null array is a no-op, just return the other input */
271  if (PG_ARGISNULL(0))
272  {
273  if (PG_ARGISNULL(1))
274  PG_RETURN_NULL();
275  result = PG_GETARG_ARRAYTYPE_P(1);
276  PG_RETURN_ARRAYTYPE_P(result);
277  }
278  if (PG_ARGISNULL(1))
279  {
280  result = PG_GETARG_ARRAYTYPE_P(0);
281  PG_RETURN_ARRAYTYPE_P(result);
282  }
283 
284  v1 = PG_GETARG_ARRAYTYPE_P(0);
285  v2 = PG_GETARG_ARRAYTYPE_P(1);
286 
287  element_type1 = ARR_ELEMTYPE(v1);
288  element_type2 = ARR_ELEMTYPE(v2);
289 
290  /* Check we have matching element types */
291  if (element_type1 != element_type2)
292  ereport(ERROR,
293  (errcode(ERRCODE_DATATYPE_MISMATCH),
294  errmsg("cannot concatenate incompatible arrays"),
295  errdetail("Arrays with element types %s and %s are not "
296  "compatible for concatenation.",
297  format_type_be(element_type1),
298  format_type_be(element_type2))));
299 
300  /* OK, use it */
301  element_type = element_type1;
302 
303  /*----------
304  * We must have one of the following combinations of inputs:
305  * 1) one empty array, and one non-empty array
306  * 2) both arrays empty
307  * 3) two arrays with ndims1 == ndims2
308  * 4) ndims1 == ndims2 - 1
309  * 5) ndims1 == ndims2 + 1
310  *----------
311  */
312  ndims1 = ARR_NDIM(v1);
313  ndims2 = ARR_NDIM(v2);
314 
315  /*
316  * short circuit - if one input array is empty, and the other is not, we
317  * return the non-empty one as the result
318  *
319  * if both are empty, return the first one
320  */
321  if (ndims1 == 0 && ndims2 > 0)
323 
324  if (ndims2 == 0)
326 
327  /* the rest fall under rule 3, 4, or 5 */
328  if (ndims1 != ndims2 &&
329  ndims1 != ndims2 - 1 &&
330  ndims1 != ndims2 + 1)
331  ereport(ERROR,
332  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
333  errmsg("cannot concatenate incompatible arrays"),
334  errdetail("Arrays of %d and %d dimensions are not "
335  "compatible for concatenation.",
336  ndims1, ndims2)));
337 
338  /* get argument array details */
339  lbs1 = ARR_LBOUND(v1);
340  lbs2 = ARR_LBOUND(v2);
341  dims1 = ARR_DIMS(v1);
342  dims2 = ARR_DIMS(v2);
343  dat1 = ARR_DATA_PTR(v1);
344  dat2 = ARR_DATA_PTR(v2);
345  bitmap1 = ARR_NULLBITMAP(v1);
346  bitmap2 = ARR_NULLBITMAP(v2);
347  nitems1 = ArrayGetNItems(ndims1, dims1);
348  nitems2 = ArrayGetNItems(ndims2, dims2);
349  ndatabytes1 = ARR_SIZE(v1) - ARR_DATA_OFFSET(v1);
350  ndatabytes2 = ARR_SIZE(v2) - ARR_DATA_OFFSET(v2);
351 
352  if (ndims1 == ndims2)
353  {
354  /*
355  * resulting array is made up of the elements (possibly arrays
356  * themselves) of the input argument arrays
357  */
358  ndims = ndims1;
359  dims = (int *) palloc(ndims * sizeof(int));
360  lbs = (int *) palloc(ndims * sizeof(int));
361 
362  dims[0] = dims1[0] + dims2[0];
363  lbs[0] = lbs1[0];
364 
365  for (i = 1; i < ndims; i++)
366  {
367  if (dims1[i] != dims2[i] || lbs1[i] != lbs2[i])
368  ereport(ERROR,
369  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
370  errmsg("cannot concatenate incompatible arrays"),
371  errdetail("Arrays with differing element dimensions are "
372  "not compatible for concatenation.")));
373 
374  dims[i] = dims1[i];
375  lbs[i] = lbs1[i];
376  }
377  }
378  else if (ndims1 == ndims2 - 1)
379  {
380  /*
381  * resulting array has the second argument as the outer array, with
382  * the first argument inserted at the front of the outer dimension
383  */
384  ndims = ndims2;
385  dims = (int *) palloc(ndims * sizeof(int));
386  lbs = (int *) palloc(ndims * sizeof(int));
387  memcpy(dims, dims2, ndims * sizeof(int));
388  memcpy(lbs, lbs2, ndims * sizeof(int));
389 
390  /* increment number of elements in outer array */
391  dims[0] += 1;
392 
393  /* make sure the added element matches our existing elements */
394  for (i = 0; i < ndims1; i++)
395  {
396  if (dims1[i] != dims[i + 1] || lbs1[i] != lbs[i + 1])
397  ereport(ERROR,
398  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
399  errmsg("cannot concatenate incompatible arrays"),
400  errdetail("Arrays with differing dimensions are not "
401  "compatible for concatenation.")));
402  }
403  }
404  else
405  {
406  /*
407  * (ndims1 == ndims2 + 1)
408  *
409  * resulting array has the first argument as the outer array, with the
410  * second argument appended to the end of the outer dimension
411  */
412  ndims = ndims1;
413  dims = (int *) palloc(ndims * sizeof(int));
414  lbs = (int *) palloc(ndims * sizeof(int));
415  memcpy(dims, dims1, ndims * sizeof(int));
416  memcpy(lbs, lbs1, ndims * sizeof(int));
417 
418  /* increment number of elements in outer array */
419  dims[0] += 1;
420 
421  /* make sure the added element matches our existing elements */
422  for (i = 0; i < ndims2; i++)
423  {
424  if (dims2[i] != dims[i + 1] || lbs2[i] != lbs[i + 1])
425  ereport(ERROR,
426  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
427  errmsg("cannot concatenate incompatible arrays"),
428  errdetail("Arrays with differing dimensions are not "
429  "compatible for concatenation.")));
430  }
431  }
432 
433  /* Do this mainly for overflow checking */
434  nitems = ArrayGetNItems(ndims, dims);
435  ArrayCheckBounds(ndims, dims, lbs);
436 
437  /* build the result array */
438  ndatabytes = ndatabytes1 + ndatabytes2;
439  if (ARR_HASNULL(v1) || ARR_HASNULL(v2))
440  {
441  dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
442  nbytes = ndatabytes + dataoffset;
443  }
444  else
445  {
446  dataoffset = 0; /* marker for no null bitmap */
447  nbytes = ndatabytes + ARR_OVERHEAD_NONULLS(ndims);
448  }
449  result = (ArrayType *) palloc0(nbytes);
450  SET_VARSIZE(result, nbytes);
451  result->ndim = ndims;
452  result->dataoffset = dataoffset;
453  result->elemtype = element_type;
454  memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
455  memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
456  /* data area is arg1 then arg2 */
457  memcpy(ARR_DATA_PTR(result), dat1, ndatabytes1);
458  memcpy(ARR_DATA_PTR(result) + ndatabytes1, dat2, ndatabytes2);
459  /* handle the null bitmap if needed */
460  if (ARR_HASNULL(result))
461  {
463  bitmap1, 0,
464  nitems1);
465  array_bitmap_copy(ARR_NULLBITMAP(result), nitems1,
466  bitmap2, 0,
467  nitems2);
468  }
469 
470  PG_RETURN_ARRAYTYPE_P(result);
471 }
#define ARR_NDIM(a)
Definition: array.h:283
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:256
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define ARR_NULLBITMAP(a)
Definition: array.h:293
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:305
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:258
#define ARR_SIZE(a)
Definition: array.h:282
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:303
#define ARR_DATA_OFFSET(a)
Definition: array.h:309
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_HASNULL(a)
Definition: array.h:284
#define ARR_LBOUND(a)
Definition: array.h:289
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:76
void ArrayCheckBounds(int ndim, const int *dims, const int *lb)
Definition: arrayutils.c:138
signed int int32
Definition: c.h:478
int errdetail(const char *fmt,...)
Definition: elog.c:1202
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
void * palloc0(Size size)
Definition: mcxt.c:1241
Oid elemtype
Definition: array.h:90
int ndim
Definition: array.h:88
int32 dataoffset
Definition: array.h:89
#define SET_VARSIZE(PTR, len)
Definition: varatt.h:305

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(), ArrayCheckBounds(), ArrayGetNItems(), ArrayType::dataoffset, ArrayType::elemtype, ereport, errcode(), errdetail(), errmsg(), ERROR, format_type_be(), i, ArrayType::ndim, palloc(), palloc0(), PG_ARGISNULL, PG_GETARG_ARRAYTYPE_P, PG_RETURN_ARRAYTYPE_P, PG_RETURN_NULL, and SET_VARSIZE.

◆ array_position()

Datum array_position ( PG_FUNCTION_ARGS  )

Definition at line 1239 of file array_userfuncs.c.

1240 {
1241  return array_position_common(fcinfo);
1242 }
static Datum array_position_common(FunctionCallInfo fcinfo)

References array_position_common().

Referenced by MakeOldSnapshotTimeMappingTuple().

◆ array_position_common()

static Datum array_position_common ( FunctionCallInfo  fcinfo)
static

Definition at line 1258 of file array_userfuncs.c.

1259 {
1260  ArrayType *array;
1261  Oid collation = PG_GET_COLLATION();
1262  Oid element_type;
1263  Datum searched_element,
1264  value;
1265  bool isnull;
1266  int position,
1267  position_min;
1268  bool found = false;
1269  TypeCacheEntry *typentry;
1270  ArrayMetaState *my_extra;
1271  bool null_search;
1273 
1274  if (PG_ARGISNULL(0))
1275  PG_RETURN_NULL();
1276 
1277  array = PG_GETARG_ARRAYTYPE_P(0);
1278  element_type = ARR_ELEMTYPE(array);
1279 
1280  /*
1281  * We refuse to search for elements in multi-dimensional arrays, since we
1282  * have no good way to report the element's location in the array.
1283  */
1284  if (ARR_NDIM(array) > 1)
1285  ereport(ERROR,
1286  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1287  errmsg("searching for elements in multidimensional arrays is not supported")));
1288 
1289  if (PG_ARGISNULL(1))
1290  {
1291  /* fast return when the array doesn't have nulls */
1292  if (!array_contains_nulls(array))
1293  PG_RETURN_NULL();
1294  searched_element = (Datum) 0;
1295  null_search = true;
1296  }
1297  else
1298  {
1299  searched_element = PG_GETARG_DATUM(1);
1300  null_search = false;
1301  }
1302 
1303  position = (ARR_LBOUND(array))[0] - 1;
1304 
1305  /* figure out where to start */
1306  if (PG_NARGS() == 3)
1307  {
1308  if (PG_ARGISNULL(2))
1309  ereport(ERROR,
1310  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1311  errmsg("initial position must not be null")));
1312 
1313  position_min = PG_GETARG_INT32(2);
1314  }
1315  else
1316  position_min = (ARR_LBOUND(array))[0];
1317 
1318  /*
1319  * We arrange to look up type info for array_create_iterator only once per
1320  * series of calls, assuming the element type doesn't change underneath
1321  * us.
1322  */
1323  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1324  if (my_extra == NULL)
1325  {
1326  fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1327  sizeof(ArrayMetaState));
1328  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1329  my_extra->element_type = ~element_type;
1330  }
1331 
1332  if (my_extra->element_type != element_type)
1333  {
1334  get_typlenbyvalalign(element_type,
1335  &my_extra->typlen,
1336  &my_extra->typbyval,
1337  &my_extra->typalign);
1338 
1339  typentry = lookup_type_cache(element_type, TYPECACHE_EQ_OPR_FINFO);
1340 
1341  if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
1342  ereport(ERROR,
1343  (errcode(ERRCODE_UNDEFINED_FUNCTION),
1344  errmsg("could not identify an equality operator for type %s",
1345  format_type_be(element_type))));
1346 
1347  my_extra->element_type = element_type;
1348  fmgr_info_cxt(typentry->eq_opr_finfo.fn_oid, &my_extra->proc,
1349  fcinfo->flinfo->fn_mcxt);
1350  }
1351 
1352  /* Examine each array element until we find a match. */
1353  array_iterator = array_create_iterator(array, 0, my_extra);
1354  while (array_iterate(array_iterator, &value, &isnull))
1355  {
1356  position++;
1357 
1358  /* skip initial elements if caller requested so */
1359  if (position < position_min)
1360  continue;
1361 
1362  /*
1363  * Can't look at the array element's value if it's null; but if we
1364  * search for null, we have a hit and are done.
1365  */
1366  if (isnull || null_search)
1367  {
1368  if (isnull && null_search)
1369  {
1370  found = true;
1371  break;
1372  }
1373  else
1374  continue;
1375  }
1376 
1377  /* not nulls, so run the operator */
1378  if (DatumGetBool(FunctionCall2Coll(&my_extra->proc, collation,
1379  searched_element, value)))
1380  {
1381  found = true;
1382  break;
1383  }
1384  }
1385 
1387 
1388  /* Avoid leaking memory when handed toasted input */
1389  PG_FREE_IF_COPY(array, 0);
1390 
1391  if (!found)
1392  PG_RETURN_NULL();
1393 
1394  PG_RETURN_INT32(position);
1395 }
static bool array_iterator(ArrayType *la, PGCALL2 callback, void *param, ltree **found)
Definition: _ltree_op.c:38
bool array_contains_nulls(ArrayType *array)
Definition: arrayfuncs.c:3738
bool array_iterate(ArrayIterator iterator, Datum *value, bool *isnull)
Definition: arrayfuncs.c:4647
void array_free_iterator(ArrayIterator iterator)
Definition: arrayfuncs.c:4730
ArrayIterator array_create_iterator(ArrayType *arr, int slice_ndim, ArrayMetaState *mstate)
Definition: arrayfuncs.c:4568
#define OidIsValid(objectId)
Definition: c.h:759
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1136
#define PG_FREE_IF_COPY(ptr, n)
Definition: fmgr.h:260
#define PG_NARGS()
Definition: fmgr.h:203
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define PG_GET_COLLATION()
Definition: fmgr.h:198
static struct @143 value
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2229
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
Oid element_type
Definition: array.h:231
FmgrInfo proc
Definition: array.h:238
void * fn_extra
Definition: fmgr.h:64
Oid fn_oid
Definition: fmgr.h:59
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:339
#define TYPECACHE_EQ_OPR_FINFO
Definition: typcache.h:141

References ARR_ELEMTYPE, ARR_LBOUND, ARR_NDIM, array_contains_nulls(), array_create_iterator(), array_free_iterator(), array_iterate(), array_iterator(), DatumGetBool(), ArrayMetaState::element_type, TypeCacheEntry::eq_opr_finfo, ereport, errcode(), errmsg(), ERROR, FunctionCallInfoBaseData::flinfo, fmgr_info_cxt(), FmgrInfo::fn_extra, FmgrInfo::fn_mcxt, FmgrInfo::fn_oid, format_type_be(), FunctionCall2Coll(), get_typlenbyvalalign(), if(), lookup_type_cache(), MemoryContextAlloc(), OidIsValid, PG_ARGISNULL, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_GETARG_INT32, PG_NARGS, PG_RETURN_INT32, PG_RETURN_NULL, ArrayMetaState::proc, ArrayMetaState::typalign, ArrayMetaState::typbyval, TYPECACHE_EQ_OPR_FINFO, ArrayMetaState::typlen, and value.

Referenced by array_position(), and array_position_start().

◆ array_position_start()

Datum array_position_start ( PG_FUNCTION_ARGS  )

Definition at line 1245 of file array_userfuncs.c.

1246 {
1247  return array_position_common(fcinfo);
1248 }

References array_position_common().

◆ array_positions()

Datum array_positions ( PG_FUNCTION_ARGS  )

Definition at line 1409 of file array_userfuncs.c.

1410 {
1411  ArrayType *array;
1412  Oid collation = PG_GET_COLLATION();
1413  Oid element_type;
1414  Datum searched_element,
1415  value;
1416  bool isnull;
1417  int position;
1418  TypeCacheEntry *typentry;
1419  ArrayMetaState *my_extra;
1420  bool null_search;
1422  ArrayBuildState *astate = NULL;
1423 
1424  if (PG_ARGISNULL(0))
1425  PG_RETURN_NULL();
1426 
1427  array = PG_GETARG_ARRAYTYPE_P(0);
1428  element_type = ARR_ELEMTYPE(array);
1429 
1430  position = (ARR_LBOUND(array))[0] - 1;
1431 
1432  /*
1433  * We refuse to search for elements in multi-dimensional arrays, since we
1434  * have no good way to report the element's location in the array.
1435  */
1436  if (ARR_NDIM(array) > 1)
1437  ereport(ERROR,
1438  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1439  errmsg("searching for elements in multidimensional arrays is not supported")));
1440 
1441  astate = initArrayResult(INT4OID, CurrentMemoryContext, false);
1442 
1443  if (PG_ARGISNULL(1))
1444  {
1445  /* fast return when the array doesn't have nulls */
1446  if (!array_contains_nulls(array))
1448  searched_element = (Datum) 0;
1449  null_search = true;
1450  }
1451  else
1452  {
1453  searched_element = PG_GETARG_DATUM(1);
1454  null_search = false;
1455  }
1456 
1457  /*
1458  * We arrange to look up type info for array_create_iterator only once per
1459  * series of calls, assuming the element type doesn't change underneath
1460  * us.
1461  */
1462  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1463  if (my_extra == NULL)
1464  {
1465  fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
1466  sizeof(ArrayMetaState));
1467  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
1468  my_extra->element_type = ~element_type;
1469  }
1470 
1471  if (my_extra->element_type != element_type)
1472  {
1473  get_typlenbyvalalign(element_type,
1474  &my_extra->typlen,
1475  &my_extra->typbyval,
1476  &my_extra->typalign);
1477 
1478  typentry = lookup_type_cache(element_type, TYPECACHE_EQ_OPR_FINFO);
1479 
1480  if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
1481  ereport(ERROR,
1482  (errcode(ERRCODE_UNDEFINED_FUNCTION),
1483  errmsg("could not identify an equality operator for type %s",
1484  format_type_be(element_type))));
1485 
1486  my_extra->element_type = element_type;
1487  fmgr_info_cxt(typentry->eq_opr_finfo.fn_oid, &my_extra->proc,
1488  fcinfo->flinfo->fn_mcxt);
1489  }
1490 
1491  /*
1492  * Accumulate each array position iff the element matches the given
1493  * element.
1494  */
1495  array_iterator = array_create_iterator(array, 0, my_extra);
1496  while (array_iterate(array_iterator, &value, &isnull))
1497  {
1498  position += 1;
1499 
1500  /*
1501  * Can't look at the array element's value if it's null; but if we
1502  * search for null, we have a hit.
1503  */
1504  if (isnull || null_search)
1505  {
1506  if (isnull && null_search)
1507  astate =
1508  accumArrayResult(astate, Int32GetDatum(position), false,
1509  INT4OID, CurrentMemoryContext);
1510 
1511  continue;
1512  }
1513 
1514  /* not nulls, so run the operator */
1515  if (DatumGetBool(FunctionCall2Coll(&my_extra->proc, collation,
1516  searched_element, value)))
1517  astate =
1518  accumArrayResult(astate, Int32GetDatum(position), false,
1519  INT4OID, CurrentMemoryContext);
1520  }
1521 
1523 
1524  /* Avoid leaking memory when handed toasted input */
1525  PG_FREE_IF_COPY(array, 0);
1526 
1528 }
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5385
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212

References accumArrayResult(), ARR_ELEMTYPE, ARR_LBOUND, ARR_NDIM, array_contains_nulls(), array_create_iterator(), array_free_iterator(), array_iterate(), array_iterator(), CurrentMemoryContext, DatumGetBool(), ArrayMetaState::element_type, TypeCacheEntry::eq_opr_finfo, ereport, errcode(), errmsg(), ERROR, fmgr_info_cxt(), FmgrInfo::fn_mcxt, FmgrInfo::fn_oid, format_type_be(), FunctionCall2Coll(), get_typlenbyvalalign(), if(), initArrayResult(), Int32GetDatum(), lookup_type_cache(), makeArrayResult(), MemoryContextAlloc(), OidIsValid, PG_ARGISNULL, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_RETURN_DATUM, PG_RETURN_NULL, ArrayMetaState::proc, ArrayMetaState::typalign, ArrayMetaState::typbyval, TYPECACHE_EQ_OPR_FINFO, ArrayMetaState::typlen, and value.

◆ array_prepend()

Datum array_prepend ( PG_FUNCTION_ARGS  )

Definition at line 175 of file array_userfuncs.c.

176 {
177  ExpandedArrayHeader *eah;
178  Datum newelem;
179  bool isNull;
180  Datum result;
181  int *lb;
182  int indx;
183  int lb0;
184  ArrayMetaState *my_extra;
185 
186  isNull = PG_ARGISNULL(0);
187  if (isNull)
188  newelem = (Datum) 0;
189  else
190  newelem = PG_GETARG_DATUM(0);
191  eah = fetch_array_arg_replace_nulls(fcinfo, 1);
192 
193  if (eah->ndims == 1)
194  {
195  /* prepend newelem */
196  lb = eah->lbound;
197  lb0 = lb[0];
198 
199  if (pg_sub_s32_overflow(lb0, 1, &indx))
200  ereport(ERROR,
201  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
202  errmsg("integer out of range")));
203  }
204  else if (eah->ndims == 0)
205  {
206  indx = 1;
207  lb0 = 1;
208  }
209  else
210  ereport(ERROR,
211  (errcode(ERRCODE_DATA_EXCEPTION),
212  errmsg("argument must be empty or one-dimensional array")));
213 
214  /* Perform element insertion */
215  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
216 
217  result = array_set_element(EOHPGetRWDatum(&eah->hdr),
218  1, &indx, newelem, isNull,
219  -1, my_extra->typlen, my_extra->typbyval, my_extra->typalign);
220 
221  /* Readjust result's LB to match the input's, as expected for prepend */
222  Assert(result == EOHPGetRWDatum(&eah->hdr));
223  if (eah->ndims == 1)
224  {
225  /* This is ok whether we've deconstructed or not */
226  eah->lbound[0] = lb0;
227  }
228 
229  PG_RETURN_DATUM(result);
230 }
static bool pg_sub_s32_overflow(int32 a, int32 b, int32 *result)
Definition: int.h:122

References array_set_element(), Assert(), EOHPGetRWDatum(), ereport, errcode(), errmsg(), ERROR, fetch_array_arg_replace_nulls(), ExpandedArrayHeader::hdr, ExpandedArrayHeader::lbound, ExpandedArrayHeader::ndims, PG_ARGISNULL, PG_GETARG_DATUM, PG_RETURN_DATUM, pg_sub_s32_overflow(), ArrayMetaState::typalign, ArrayMetaState::typbyval, and ArrayMetaState::typlen.

◆ fetch_array_arg_replace_nulls()

static ExpandedArrayHeader* fetch_array_arg_replace_nulls ( FunctionCallInfo  fcinfo,
int  argno 
)
static

Definition at line 63 of file array_userfuncs.c.

64 {
66  Oid element_type;
67  ArrayMetaState *my_extra;
68  MemoryContext resultcxt;
69 
70  /* If first time through, create datatype cache struct */
71  my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
72  if (my_extra == NULL)
73  {
74  my_extra = (ArrayMetaState *)
76  sizeof(ArrayMetaState));
77  my_extra->element_type = InvalidOid;
78  fcinfo->flinfo->fn_extra = my_extra;
79  }
80 
81  /* Figure out which context we want the result in */
82  if (!AggCheckCallContext(fcinfo, &resultcxt))
83  resultcxt = CurrentMemoryContext;
84 
85  /* Now collect the array value */
86  if (!PG_ARGISNULL(argno))
87  {
88  MemoryContext oldcxt = MemoryContextSwitchTo(resultcxt);
89 
90  eah = PG_GETARG_EXPANDED_ARRAYX(argno, my_extra);
91  MemoryContextSwitchTo(oldcxt);
92  }
93  else
94  {
95  /* We have to look up the array type and element type */
96  Oid arr_typeid = get_fn_expr_argtype(fcinfo->flinfo, argno);
97 
98  if (!OidIsValid(arr_typeid))
99  ereport(ERROR,
100  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
101  errmsg("could not determine input data type")));
102  element_type = get_element_type(arr_typeid);
103  if (!OidIsValid(element_type))
104  ereport(ERROR,
105  (errcode(ERRCODE_DATATYPE_MISMATCH),
106  errmsg("input data type is not an array")));
107 
108  eah = construct_empty_expanded_array(element_type,
109  resultcxt,
110  my_extra);
111  }
112 
113  return eah;
114 }
#define PG_GETARG_EXPANDED_ARRAYX(n, metacache)
Definition: array.h:262
ExpandedArrayHeader * construct_empty_expanded_array(Oid element_type, MemoryContext parentcontext, ArrayMetaState *metacache)
Definition: arrayfuncs.c:3568
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2717

References AggCheckCallContext(), construct_empty_expanded_array(), CurrentMemoryContext, ArrayMetaState::element_type, ereport, errcode(), errmsg(), ERROR, FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_extra, FmgrInfo::fn_mcxt, get_element_type(), get_fn_expr_argtype(), if(), InvalidOid, MemoryContextAlloc(), MemoryContextSwitchTo(), OidIsValid, PG_ARGISNULL, and PG_GETARG_EXPANDED_ARRAYX.

Referenced by array_append(), and array_prepend().