MemoryContext oldcxt;
oldcxt = MemoryContextSwitchTo(indexInfo->ii_Context);
- bistate = palloc0(sizeof(BrinInsertState));
+ bistate = palloc0_object(BrinInsertState);
bistate->bis_desc = brin_build_desc(idxRel);
bistate->bis_rmAccess = brinRevmapInitialize(idxRel,
&bistate->bis_pages_per_range);
{
SortCoordinate coordinate;
- coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
+ coordinate = palloc0_object(SortCoordinateData);
coordinate->isWorker = false;
coordinate->nParticipants =
state->bs_leader->nparticipanttuplesorts;
Size estsort;
BrinShared *brinshared;
Sharedsort *sharedsort;
- BrinLeader *brinleader = (BrinLeader *) palloc0(sizeof(BrinLeader));
+ BrinLeader *brinleader = palloc0_object(BrinLeader);
WalUsage *walusage;
BufferUsage *bufferusage;
bool leaderparticipates = true;
IndexInfo *indexInfo;
/* Initialize local tuplesort coordination state */
- coordinate = palloc0(sizeof(SortCoordinateData));
+ coordinate = palloc0_object(SortCoordinateData);
coordinate->isWorker = true;
coordinate->nParticipants = -1;
coordinate->sharedsort = sharedsort;
return NULL;
ndistances = (neranges - 1);
- distances = (DistanceValue *) palloc0(sizeof(DistanceValue) * ndistances);
+ distances = palloc0_array(DistanceValue, ndistances);
/*
* Walk through the ranges once and compute the distance between the
/* allocate space for the boundary values */
nvalues = 0;
- values = (Datum *) palloc(sizeof(Datum) * max_values);
+ values = palloc_array(Datum, max_values);
/* add the global min/max values, from the first/last range */
values[nvalues++] = eranges[0].minval;
page = BufferGetPage(meta);
metadata = (BrinMetaPageData *) PageGetContents(page);
- revmap = palloc(sizeof(BrinRevmap));
+ revmap = palloc_object(BrinRevmap);
revmap->rm_irel = idxrel;
revmap->rm_pagesPerRange = metadata->pagesPerRange;
revmap->rm_lastRevmapPage = metadata->lastRevmapPage;
Assert(brdesc->bd_totalstored > 0);
- values = (Datum *) palloc(sizeof(Datum) * brdesc->bd_totalstored);
- nulls = (bool *) palloc0(sizeof(bool) * brdesc->bd_totalstored);
- phony_nullbitmap = (bits8 *)
- palloc(sizeof(bits8) * BITMAPLEN(brdesc->bd_totalstored));
+ values = palloc_array(Datum, brdesc->bd_totalstored);
+ nulls = palloc0_array(bool, brdesc->bd_totalstored);
+ phony_nullbitmap = palloc_array(bits8, BITMAPLEN(brdesc->bd_totalstored));
#ifdef TOAST_INDEX_HACK
- untoasted_values = (Datum *) palloc(sizeof(Datum) * brdesc->bd_totalstored);
+ untoasted_values = palloc_array(Datum, brdesc->bd_totalstored);
#endif
/*
sizeof(BrinValues) * brdesc->bd_tupdesc->natts);
dtup = palloc0(basesize + sizeof(Datum) * brdesc->bd_totalstored);
- dtup->bt_values = palloc(sizeof(Datum) * brdesc->bd_totalstored);
- dtup->bt_allnulls = palloc(sizeof(bool) * brdesc->bd_tupdesc->natts);
- dtup->bt_hasnulls = palloc(sizeof(bool) * brdesc->bd_tupdesc->natts);
+ dtup->bt_values = palloc_array(Datum, brdesc->bd_totalstored);
+ dtup->bt_allnulls = palloc_array(bool, brdesc->bd_tupdesc->natts);
+ dtup->bt_hasnulls = palloc_array(bool, brdesc->bd_tupdesc->natts);
dtup->bt_empty_range = true;
{
AttrMap *res;
- res = (AttrMap *) palloc0(sizeof(AttrMap));
+ res = palloc0_object(AttrMap);
res->maplen = maplen;
- res->attnums = (AttrNumber *) palloc0(sizeof(AttrNumber) * maplen);
+ res->attnums = palloc0_array(AttrNumber, maplen);
return res;
}
* O(N^2) if there are many non-replaced columns, so it seems better to
* err on the side of linear cost.
*/
- values = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
- isnull = (bool *) palloc(numberOfAttributes * sizeof(bool));
+ values = palloc_array(Datum, numberOfAttributes);
+ isnull = palloc_array(bool, numberOfAttributes);
heap_deform_tuple(tuple, tupleDesc, values, isnull);
* allocate and fill values and isnull arrays from the tuple, then replace
* selected columns from the input arrays.
*/
- values = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
- isnull = (bool *) palloc(numberOfAttributes * sizeof(bool));
+ values = palloc_array(Datum, numberOfAttributes);
+ isnull = palloc_array(bool, numberOfAttributes);
heap_deform_tuple(tuple, tupleDesc, values, isnull);
DestReceiver *
printtup_create_DR(CommandDest dest)
{
- DR_printtup *self = (DR_printtup *) palloc0(sizeof(DR_printtup));
+ DR_printtup *self = palloc0_object(DR_printtup);
self->pub.receiveSlot = printtup; /* might get changed later */
self->pub.rStartup = printtup_startup;
static void
add_local_reloption(local_relopts *relopts, relopt_gen *newoption, int offset)
{
- local_relopt *opt = palloc(sizeof(*opt));
+ local_relopt *opt = palloc_object(local_relopt);
Assert(offset < relopts->relopt_struct_size);
parseLocalRelOptions(local_relopts *relopts, Datum options, bool validate)
{
int nopts = list_length(relopts->options);
- relopt_value *values = palloc(sizeof(*values) * nopts);
+ relopt_value *values = palloc_array(relopt_value, nopts);
ListCell *lc;
int i = 0;
build_local_reloptions(local_relopts *relopts, Datum options, bool validate)
{
int noptions = list_length(relopts->options);
- relopt_parse_elt *elems = palloc(sizeof(*elems) * noptions);
+ relopt_parse_elt *elems = palloc_array(relopt_parse_elt, noptions);
relopt_value *vals;
void *opts;
int i = 0;
size_t minContextSize = ALLOCSET_DEFAULT_MINSIZE;
size_t maxBlockSize = ALLOCSET_DEFAULT_MAXSIZE;
- ts = palloc0(sizeof(TidStore));
+ ts = palloc0_object(TidStore);
/* choose the maxBlockSize to be no larger than 1/16 of max_bytes */
while (16 * maxBlockSize > max_bytes)
size_t dsa_init_size = DSA_DEFAULT_INIT_SEGMENT_SIZE;
size_t dsa_max_size = DSA_MAX_SEGMENT_SIZE;
- ts = palloc0(sizeof(TidStore));
+ ts = palloc0_object(TidStore);
/*
* Choose the initial and maximum DSA segment sizes to be no longer than
Assert(DsaPointerIsValid(handle));
/* create per-backend state */
- ts = palloc0(sizeof(TidStore));
+ ts = palloc0_object(TidStore);
area = dsa_attach(area_handle);
{
TidStoreIter *iter;
- iter = palloc0(sizeof(TidStoreIter));
+ iter = palloc0_object(TidStoreIter);
iter->ts = ts;
if (TidStoreIsShared(ts))
*num_indexes = list_length(indexlist);
/* Open all the index relations */
- *toastidxs = (Relation *) palloc(*num_indexes * sizeof(Relation));
+ *toastidxs = palloc_array(Relation, *num_indexes);
foreach(lc, indexlist)
(*toastidxs)[i++] = index_open(lfirst_oid(lc), lock);
}
/* Prepare the map structure */
- map = (TupleConversionMap *) palloc(sizeof(TupleConversionMap));
+ map = palloc_object(TupleConversionMap);
map->indesc = indesc;
map->outdesc = outdesc;
map->attrMap = attrMap;
/* preallocate workspace for Datum arrays */
n = outdesc->natts + 1; /* +1 for NULL */
- map->outvalues = (Datum *) palloc(n * sizeof(Datum));
- map->outisnull = (bool *) palloc(n * sizeof(bool));
+ map->outvalues = palloc_array(Datum, n);
+ map->outisnull = palloc_array(bool, n);
n = indesc->natts + 1; /* +1 for NULL */
- map->invalues = (Datum *) palloc(n * sizeof(Datum));
- map->inisnull = (bool *) palloc(n * sizeof(bool));
+ map->invalues = palloc_array(Datum, n);
+ map->inisnull = palloc_array(bool, n);
map->invalues[0] = (Datum) 0; /* set up the NULL entry */
map->inisnull[0] = true;
Assert(attrMap != NULL);
/* Prepare the map structure */
- map = (TupleConversionMap *) palloc(sizeof(TupleConversionMap));
+ map = palloc_object(TupleConversionMap);
map->indesc = indesc;
map->outdesc = outdesc;
map->attrMap = attrMap;
/* preallocate workspace for Datum arrays */
- map->outvalues = (Datum *) palloc(n * sizeof(Datum));
- map->outisnull = (bool *) palloc(n * sizeof(bool));
+ map->outvalues = palloc_array(Datum, n);
+ map->outisnull = palloc_array(bool, n);
n = indesc->natts + 1; /* +1 for NULL */
- map->invalues = (Datum *) palloc(n * sizeof(Datum));
- map->inisnull = (bool *) palloc(n * sizeof(bool));
+ map->invalues = palloc_array(Datum, n);
+ map->inisnull = palloc_array(bool, n);
map->invalues[0] = (Datum) 0; /* set up the NULL entry */
map->inisnull[0] = true;
/* Copy the TupleConstr data structure, if any */
if (constr)
{
- TupleConstr *cpy = (TupleConstr *) palloc0(sizeof(TupleConstr));
+ TupleConstr *cpy = palloc0_object(TupleConstr);
cpy->has_not_null = constr->has_not_null;
cpy->has_generated_stored = constr->has_generated_stored;
{
GinBtreeStack *stack;
- stack = (GinBtreeStack *) palloc(sizeof(GinBtreeStack));
+ stack = palloc_object(GinBtreeStack);
stack->blkno = btree->rootBlkno;
stack->buffer = ReadBuffer(btree->index, btree->rootBlkno);
stack->parent = NULL;
}
else
{
- GinBtreeStack *ptr = (GinBtreeStack *) palloc(sizeof(GinBtreeStack));
+ GinBtreeStack *ptr = palloc_object(GinBtreeStack);
ptr->parent = stack;
stack = ptr;
blkno = root->blkno;
buffer = root->buffer;
- ptr = (GinBtreeStack *) palloc(sizeof(GinBtreeStack));
+ ptr = palloc_object(GinBtreeStack);
for (;;)
{
*/
if (accum->entryallocator == NULL || accum->eas_used >= DEF_NENTRY)
{
- accum->entryallocator = palloc(sizeof(GinEntryAccumulator) * DEF_NENTRY);
+ accum->entryallocator = palloc_array(GinEntryAccumulator, DEF_NENTRY);
accum->allocatedMemory += GetMemoryChunkSpace(accum->entryallocator);
accum->eas_used = 0;
}
ea->maxcount = DEF_NPTR;
ea->count = 1;
ea->shouldSort = false;
- ea->list =
- (ItemPointerData *) palloc(sizeof(ItemPointerData) * DEF_NPTR);
+ ea->list = palloc_array(ItemPointerData, DEF_NPTR);
ea->list[0] = *heapptr;
accum->allocatedMemory += GetMemoryChunkSpace(ea->list);
}
static void *
dataPrepareDownlink(GinBtree btree, Buffer lbuf)
{
- PostingItem *pitem = palloc(sizeof(PostingItem));
+ PostingItem *pitem = palloc_object(PostingItem);
Page lpage = BufferGetPage(lbuf);
PostingItemSetBlockNumber(pitem, BufferGetBlockNumber(lbuf));
char *segbegin;
char *segend;
- leaf = palloc0(sizeof(disassembledLeaf));
+ leaf = palloc0_object(disassembledLeaf);
dlist_init(&leaf->segments);
if (GinPageIsCompressed(page))
segend = segbegin + GinDataLeafPageGetPostingListSize(page);
while ((char *) seg < segend)
{
- leafSegmentInfo *seginfo = palloc(sizeof(leafSegmentInfo));
+ leafSegmentInfo *seginfo = palloc_object(leafSegmentInfo);
seginfo->action = GIN_SEGMENT_UNMODIFIED;
seginfo->seg = seg;
if (nuncompressed > 0)
{
- seginfo = palloc(sizeof(leafSegmentInfo));
+ seginfo = palloc_object(leafSegmentInfo);
seginfo->action = GIN_SEGMENT_REPLACE;
seginfo->seg = NULL;
*/
if (dlist_is_empty(&leaf->segments))
{
- newseg = palloc(sizeof(leafSegmentInfo));
+ newseg = palloc_object(leafSegmentInfo);
newseg->seg = NULL;
newseg->items = newItems;
newseg->nitems = nNewItems;
cur->seg != NULL &&
SizeOfGinPostingList(cur->seg) >= GinPostingListSegmentTargetSize)
{
- newseg = palloc(sizeof(leafSegmentInfo));
+ newseg = palloc_object(leafSegmentInfo);
newseg->seg = NULL;
newseg->items = nextnew;
newseg->nitems = nthis;
if (seginfo->action != GIN_SEGMENT_INSERT)
seginfo->action = GIN_SEGMENT_REPLACE;
- nextseg = palloc(sizeof(leafSegmentInfo));
+ nextseg = palloc_object(leafSegmentInfo);
nextseg->action = GIN_SEGMENT_INSERT;
nextseg->seg = NULL;
nextseg->items = &seginfo->items[npacked];
}
else
{
- ipd = (ItemPointer) palloc(sizeof(ItemPointerData) * nipd);
+ ipd = palloc_array(ItemPointerData, nipd);
memcpy(ipd, ptr, sizeof(ItemPointerData) * nipd);
}
*nitems = nipd;
itup = getRightMostTuple(lpage);
- insertData = palloc(sizeof(GinBtreeEntryInsertData));
+ insertData = palloc_object(GinBtreeEntryInsertData);
insertData->entry = GinFormInteriorTuple(itup, lpage, lblkno);
insertData->isDelete = false;
{
MemoryContextSwitchTo(so->tempCtx);
- entryIndexes = (int *) palloc(sizeof(int) * key->nentries);
+ entryIndexes = palloc_array(int, key->nentries);
for (i = 0; i < key->nentries; i++)
entryIndexes[i] = i;
qsort_arg(entryIndexes, key->nentries, sizeof(int),
LockBuffer(pos.pendingBuffer, GIN_SHARE);
pos.firstOffset = FirstOffsetNumber;
UnlockReleaseBuffer(metabuffer);
- pos.hasMatchKey = palloc(sizeof(bool) * so->nkeys);
+ pos.hasMatchKey = palloc_array(bool, so->nkeys);
/*
* loop for each heap row. scanGetCandidate returns full row or row's
{
SortCoordinate coordinate;
- coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
+ coordinate = palloc0_object(SortCoordinateData);
coordinate->isWorker = false;
coordinate->nParticipants =
state->bs_leader->nparticipanttuplesorts;
/*
* Return statistics
*/
- result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
+ result = palloc_object(IndexBuildResult);
result->heap_tuples = reltuples;
result->index_tuples = buildstate.indtuples;
if (ginstate == NULL)
{
oldCtx = MemoryContextSwitchTo(indexInfo->ii_Context);
- ginstate = (GinState *) palloc(sizeof(GinState));
+ ginstate = palloc_object(GinState);
initGinState(ginstate, index);
indexInfo->ii_AmCache = ginstate;
MemoryContextSwitchTo(oldCtx);
Size estsort;
GinBuildShared *ginshared;
Sharedsort *sharedsort;
- GinLeader *ginleader = (GinLeader *) palloc0(sizeof(GinLeader));
+ GinLeader *ginleader = palloc0_object(GinLeader);
WalUsage *walusage;
BufferUsage *bufferusage;
bool leaderparticipates = true;
static GinBuffer *
GinBufferInit(Relation index)
{
- GinBuffer *buffer = palloc0(sizeof(GinBuffer));
+ GinBuffer *buffer = palloc0_object(GinBuffer);
int i,
nKeys;
TupleDesc desc = RelationGetDescr(index);
nKeys = IndexRelationGetNumberOfKeyAttributes(index);
- buffer->ssup = palloc0(sizeof(SortSupportData) * nKeys);
+ buffer->ssup = palloc0_array(SortSupportData, nKeys);
/*
* Lookup ordering operator for the index key data type, and initialize
IndexInfo *indexInfo;
/* Initialize local tuplesort coordination state */
- coordinate = palloc0(sizeof(SortCoordinateData));
+ coordinate = palloc0_object(SortCoordinateData);
coordinate->isWorker = true;
coordinate->nParticipants = -1;
coordinate->sharedsort = sharedsort;
while (ncompressed < nitems)
{
int cnt;
- GinSegmentInfo *seginfo = palloc(sizeof(GinSegmentInfo));
+ GinSegmentInfo *seginfo = palloc_object(GinSegmentInfo);
seginfo->seg = ginCompressPostingList(&items[ncompressed],
(nitems - ncompressed),
scan = RelationGetIndexScan(rel, nkeys, norderbys);
/* allocate private workspace */
- so = (GinScanOpaque) palloc(sizeof(GinScanOpaqueData));
+ so = (GinScanOpaque) palloc_object(GinScanOpaqueData);
so->keys = NULL;
so->nkeys = 0;
so->tempCtx = AllocSetContextCreate(CurrentMemoryContext,
}
/* Nope, create a new entry */
- scanEntry = (GinScanEntry) palloc(sizeof(GinScanEntryData));
+ scanEntry = palloc_object(GinScanEntryData);
scanEntry->queryKey = queryKey;
scanEntry->queryCategory = queryCategory;
scanEntry->isPartialMatch = isPartialMatch;
if (so->totalentries >= so->allocentries)
{
so->allocentries *= 2;
- so->entries = (GinScanEntry *)
- repalloc(so->entries, so->allocentries * sizeof(GinScanEntry));
+ so->entries = repalloc_array(so->entries, GinScanEntry, so->allocentries);
}
so->entries[so->totalentries++] = scanEntry;
key->nuserentries = nQueryValues;
/* Allocate one extra array slot for possible "hidden" entry */
- key->scanEntry = (GinScanEntry *) palloc(sizeof(GinScanEntry) *
- (nQueryValues + 1));
- key->entryRes = (GinTernaryValue *) palloc0(sizeof(GinTernaryValue) *
- (nQueryValues + 1));
+ key->scanEntry = palloc_array(GinScanEntry, nQueryValues + 1);
+ key->entryRes = palloc0_array(GinTernaryValue, nQueryValues + 1);
key->query = query;
key->queryValues = queryValues;
if (isNull)
{
*nentries = 1;
- entries = (Datum *) palloc(sizeof(Datum));
+ entries = palloc_object(Datum);
entries[0] = (Datum) 0;
- *categories = (GinNullCategory *) palloc(sizeof(GinNullCategory));
+ *categories = palloc_object(GinNullCategory);
(*categories)[0] = GIN_CAT_NULL_ITEM;
return entries;
}
if (entries == NULL || *nentries <= 0)
{
*nentries = 1;
- entries = (Datum *) palloc(sizeof(Datum));
+ entries = palloc_object(Datum);
entries[0] = (Datum) 0;
- *categories = (GinNullCategory *) palloc(sizeof(GinNullCategory));
+ *categories = palloc_object(GinNullCategory);
(*categories)[0] = GIN_CAT_EMPTY_ITEM;
return entries;
}
keyEntryData *keydata;
cmpEntriesArg arg;
- keydata = (keyEntryData *) palloc(*nentries * sizeof(keyEntryData));
+ keydata = palloc_array(keyEntryData, *nentries);
for (i = 0; i < *nentries; i++)
{
keydata[i].datum = entries[i];
* First TID to be deleted: allocate memory to hold the
* remaining items.
*/
- tmpitems = palloc(sizeof(ItemPointerData) * nitem);
+ tmpitems = palloc_array(ItemPointerData, nitem);
memcpy(tmpitems, items, sizeof(ItemPointerData) * i);
}
}
{
if (!parent->child)
{
- me = (DataPageDeleteStack *) palloc0(sizeof(DataPageDeleteStack));
+ me = palloc0_object(DataPageDeleteStack);
me->parent = parent;
parent->child = me;
me->leftBuffer = InvalidBuffer;
if (stats == NULL)
{
/* Yes, so initialize stats to zeroes */
- stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ stats = palloc0_object(IndexBulkDeleteResult);
/*
* and cleanup any pending inserts
*/
if (stats == NULL)
{
- stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ stats = palloc0_object(IndexBulkDeleteResult);
initGinState(&ginstate, index);
ginInsertCleanup(&ginstate, !AmAutoVacuumWorkerProcess(),
false, true, stats);
#define ROTATEDIST(d) do { \
- SplitPageLayout *tmp = (SplitPageLayout *) palloc0(sizeof(SplitPageLayout)); \
+ SplitPageLayout *tmp = palloc0_object(SplitPageLayout); \
tmp->block.blkno = InvalidBlockNumber; \
tmp->buffer = InvalidBuffer; \
tmp->next = (d); \
/* Prepare a vector of all the downlinks */
for (ptr = dist; ptr; ptr = ptr->next)
ndownlinks++;
- downlinks = palloc(sizeof(IndexTuple) * ndownlinks);
+ downlinks = palloc_array(IndexTuple, ndownlinks);
for (i = 0, ptr = dist; ptr; ptr = ptr->next)
downlinks[i++] = ptr->itup;
/* Prepare split-info to be returned to caller */
for (ptr = dist; ptr; ptr = ptr->next)
{
- GISTPageSplitInfo *si = palloc(sizeof(GISTPageSplitInfo));
+ GISTPageSplitInfo *si = palloc_object(GISTPageSplitInfo);
si->buf = ptr->buffer;
si->downlink = ptr->itup;
xlocked = false;
/* descend to the chosen child */
- item = (GISTInsertStack *) palloc0(sizeof(GISTInsertStack));
+ item = palloc0_object(GISTInsertStack);
item->blkno = childblkno;
item->parent = stack;
item->downlinkoffnum = downlinkoffnum;
*ptr;
BlockNumber blkno;
- top = (GISTInsertStack *) palloc0(sizeof(GISTInsertStack));
+ top = palloc0_object(GISTInsertStack);
top->blkno = GIST_ROOT_BLKNO;
top->downlinkoffnum = InvalidOffsetNumber;
* leaf pages, and we assume that there can't be any non-leaf
* pages behind leaf pages.
*/
- ptr = (GISTInsertStack *) palloc0(sizeof(GISTInsertStack));
+ ptr = palloc0_object(GISTInsertStack);
ptr->blkno = GistPageGetOpaque(page)->rightlink;
ptr->downlinkoffnum = InvalidOffsetNumber;
ptr->parent = top->parent;
else
{
/* Append this child to the list of pages to visit later */
- ptr = (GISTInsertStack *) palloc0(sizeof(GISTInsertStack));
+ ptr = palloc0_object(GISTInsertStack);
ptr->blkno = blkno;
ptr->downlinkoffnum = i;
ptr->parent = top;
*/
for (;;)
{
- GISTPageSplitInfo *si = palloc(sizeof(GISTPageSplitInfo));
+ GISTPageSplitInfo *si = palloc_object(GISTPageSplitInfo);
IndexTuple downlink;
page = BufferGetPage(buf);
gistSplitByKey(r, page, itup, len, giststate, &v, 0);
/* form left and right vector */
- lvectup = (IndexTuple *) palloc(sizeof(IndexTuple) * (len + 1));
- rvectup = (IndexTuple *) palloc(sizeof(IndexTuple) * (len + 1));
+ lvectup = palloc_array(IndexTuple, len + 1);
+ rvectup = palloc_array(IndexTuple, len + 1);
for (i = 0; i < v.splitVector.spl_nleft; i++)
lvectup[i] = itup[v.splitVector.spl_left[i] - 1];
oldCxt = MemoryContextSwitchTo(scanCxt);
/* Create and fill in the GISTSTATE */
- giststate = (GISTSTATE *) palloc(sizeof(GISTSTATE));
+ giststate = palloc_object(GISTSTATE);
giststate->scanCxt = scanCxt;
giststate->tempCxt = scanCxt; /* caller must change this if needed */
/*
* Return statistics
*/
- result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
+ result = palloc_object(IndexBuildResult);
result->heap_tuples = reltuples;
result->index_tuples = (double) buildstate.indtuples;
state->bulkstate = smgr_bulk_start_rel(state->indexrel, MAIN_FORKNUM);
/* Allocate a temporary buffer for the first leaf page batch. */
- levelstate = palloc0(sizeof(GistSortedBuildLevelState));
+ levelstate = palloc0_object(GistSortedBuildLevelState);
levelstate->pages[0] = palloc(BLCKSZ);
levelstate->parent = NULL;
gistinitpage(levelstate->pages[0], F_LEAF);
else
{
/* Create split layout from single page */
- dist = (SplitPageLayout *) palloc0(sizeof(SplitPageLayout));
+ dist = palloc0_object(SplitPageLayout);
union_tuple = gistunion(state->indexrel, itvec, vect_len,
state->giststate);
dist->itup = union_tuple;
parent = levelstate->parent;
if (parent == NULL)
{
- parent = palloc0(sizeof(GistSortedBuildLevelState));
+ parent = palloc0_object(GistSortedBuildLevelState);
parent->pages[0] = palloc(BLCKSZ);
parent->parent = NULL;
gistinitpage(parent->pages[0], 0);
/* Create an array of all the downlink tuples */
ndownlinks = list_length(splitinfo);
- downlinks = (IndexTuple *) palloc(sizeof(IndexTuple) * ndownlinks);
+ downlinks = palloc_array(IndexTuple, ndownlinks);
i = 0;
foreach(lc, splitinfo)
{
GISTBuildBuffers *gfbb;
HASHCTL hashCtl;
- gfbb = palloc(sizeof(GISTBuildBuffers));
+ gfbb = palloc_object(GISTBuildBuffers);
gfbb->pagesPerBuffer = pagesPerBuffer;
gfbb->levelStep = levelStep;
/* Initialize free page management. */
gfbb->nFreeBlocks = 0;
gfbb->freeBlocksLen = 32;
- gfbb->freeBlocks = (long *) palloc(gfbb->freeBlocksLen * sizeof(long));
+ gfbb->freeBlocks = palloc_array(long, gfbb->freeBlocksLen);
/*
* Current memory context will be used for all in-memory data structures
* buffers are inserted here when they are created.
*/
gfbb->buffersOnLevelsLen = 1;
- gfbb->buffersOnLevels = (List **) palloc(sizeof(List *) *
- gfbb->buffersOnLevelsLen);
+ gfbb->buffersOnLevels = palloc_array(List *, gfbb->buffersOnLevelsLen);
gfbb->buffersOnLevels[0] = NIL;
/*
* into main memory.
*/
gfbb->loadedBuffersLen = 32;
- gfbb->loadedBuffers = (GISTNodeBuffer **) palloc(gfbb->loadedBuffersLen *
- sizeof(GISTNodeBuffer *));
+ gfbb->loadedBuffers = palloc_array(GISTNodeBuffer *, gfbb->loadedBuffersLen);
gfbb->loadedBuffersCount = 0;
gfbb->rootlevel = maxLevel;
* Allocate memory for information about relocation buffers.
*/
splitPagesCount = list_length(splitinfo);
- relocationBuffersInfos =
- (RelocationBufferInfo *) palloc(sizeof(RelocationBufferInfo) *
- splitPagesCount);
+ relocationBuffersInfos = palloc_array(RelocationBufferInfo, splitPagesCount);
/*
* Fill relocation buffers information for node buffers of pages produced
*pageunion;
numranges = entryvec->n;
- pageunion = (BOX *) palloc(sizeof(BOX));
+ pageunion = palloc_object(BOX);
cur = DatumGetBoxP(entryvec->vector[0].key);
memcpy(pageunion, cur, sizeof(BOX));
v->spl_left[v->spl_nleft] = i;
if (unionL == NULL)
{
- unionL = (BOX *) palloc(sizeof(BOX));
+ unionL = palloc_object(BOX);
*unionL = *cur;
}
else
v->spl_right[v->spl_nright] = i;
if (unionR == NULL)
{
- unionR = (BOX *) palloc(sizeof(BOX));
+ unionR = palloc_object(BOX);
*unionR = *cur;
}
else
v->spl_nright = 0;
/* Allocate bounding boxes of left and right groups */
- leftBox = palloc0(sizeof(BOX));
- rightBox = palloc0(sizeof(BOX));
+ leftBox = palloc0_object(BOX);
+ rightBox = palloc0_object(BOX);
/*
* Allocate an array for "common entries" - entries which can be placed to
POLYGON *in = DatumGetPolygonP(entry->key);
BOX *r;
- r = (BOX *) palloc(sizeof(BOX));
+ r = palloc_object(BOX);
memcpy(r, &(in->boundbox), sizeof(BOX));
- retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+ retval = palloc_object(GISTENTRY);
gistentryinit(*retval, PointerGetDatum(r),
entry->rel, entry->page,
entry->offset, false);
CIRCLE *in = DatumGetCircleP(entry->key);
BOX *r;
- r = (BOX *) palloc(sizeof(BOX));
+ r = palloc_object(BOX);
r->high.x = float8_pl(in->center.x, in->radius);
r->low.x = float8_mi(in->center.x, in->radius);
r->high.y = float8_pl(in->center.y, in->radius);
r->low.y = float8_mi(in->center.y, in->radius);
- retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+ retval = palloc_object(GISTENTRY);
gistentryinit(*retval, PointerGetDatum(r),
entry->rel, entry->page,
entry->offset, false);
if (entry->leafkey) /* Point, actually */
{
- BOX *box = palloc(sizeof(BOX));
+ BOX *box = palloc_object(BOX);
Point *point = DatumGetPointP(entry->key);
- GISTENTRY *retval = palloc(sizeof(GISTENTRY));
+ GISTENTRY *retval = palloc_object(GISTENTRY);
box->high = box->low = *point;
Point *r;
GISTENTRY *retval;
- retval = palloc(sizeof(GISTENTRY));
+ retval = palloc_object(GISTENTRY);
- r = (Point *) palloc(sizeof(Point));
+ r = palloc_object(Point);
r->x = in->high.x;
r->y = in->high.y;
gistentryinit(*retval, PointerGetDatum(r),
oldCxt = MemoryContextSwitchTo(giststate->scanCxt);
/* initialize opaque data */
- so = (GISTScanOpaque) palloc0(sizeof(GISTScanOpaqueData));
+ so = palloc0_object(GISTScanOpaqueData);
so->giststate = giststate;
giststate->tempCxt = createTempGistContext();
so->queue = NULL;
so->qual_ok = true; /* in case there are zero keys */
if (scan->numberOfOrderBys > 0)
{
- scan->xs_orderbyvals = palloc0(sizeof(Datum) * scan->numberOfOrderBys);
- scan->xs_orderbynulls = palloc(sizeof(bool) * scan->numberOfOrderBys);
+ scan->xs_orderbyvals = palloc0_array(Datum, scan->numberOfOrderBys);
+ scan->xs_orderbynulls = palloc_array(bool, scan->numberOfOrderBys);
memset(scan->xs_orderbynulls, true, sizeof(bool) * scan->numberOfOrderBys);
}
int i,
cleanedLen = 0;
- cleanedItVec = (IndexTuple *) palloc(sizeof(IndexTuple) * gsvp->len);
+ cleanedItVec = palloc_array(IndexTuple, gsvp->len);
for (i = 0; i < gsvp->len; i++)
{
* Locate don't-care tuples, if any. If there are none, the split is
* optimal, so just fall out and return false.
*/
- v->spl_dontcare = (bool *) palloc0(sizeof(bool) * (entryvec->n + 1));
+ v->spl_dontcare = palloc0_array(bool, entryvec->n + 1);
NumDontCare = findDontCares(r, giststate, entryvec->vector, v, attno);
* call will overwrite that with its own result.
*/
backupSplit = v->splitVector;
- backupSplit.spl_left = (OffsetNumber *) palloc(sizeof(OffsetNumber) * len);
+ backupSplit.spl_left = palloc_array(OffsetNumber, len);
memcpy(backupSplit.spl_left, v->splitVector.spl_left, sizeof(OffsetNumber) * v->splitVector.spl_nleft);
- backupSplit.spl_right = (OffsetNumber *) palloc(sizeof(OffsetNumber) * len);
+ backupSplit.spl_right = palloc_array(OffsetNumber, len);
memcpy(backupSplit.spl_right, v->splitVector.spl_right, sizeof(OffsetNumber) * v->splitVector.spl_nright);
/* Recursively decide how to split the don't-care tuples */
maxoff = PageGetMaxOffsetNumber(page);
*len = maxoff;
- itvec = palloc(sizeof(IndexTuple) * maxoff);
+ itvec = palloc_array(IndexTuple, maxoff);
for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
itvec[i - FirstOffsetNumber] = (IndexTuple) PageGetItem(page, PageGetItemId(page, i));
IndexTuple *
gistjoinvector(IndexTuple *itvec, int *len, IndexTuple *additvec, int addlen)
{
- itvec = (IndexTuple *) repalloc(itvec, sizeof(IndexTuple) * ((*len) + addlen));
+ itvec = repalloc_array(itvec, IndexTuple, (*len) + addlen);
memmove(&itvec[*len], additvec, sizeof(IndexTuple) * addlen);
*len += addlen;
return itvec;
{
/* allocate stats if first time through, else re-use existing struct */
if (stats == NULL)
- stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ stats = palloc0_object(IndexBulkDeleteResult);
gistvacuumscan(info, stats, callback, callback_state);
*/
if (stats == NULL)
{
- stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ stats = palloc0_object(IndexBulkDeleteResult);
gistvacuumscan(info, stats, NULL, NULL);
}
/*
* Return statistics
*/
- result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
+ result = palloc_object(IndexBuildResult);
result->heap_tuples = reltuples;
result->index_tuples = buildstate.indtuples;
* entries.
*/
if (so->killedItems == NULL)
- so->killedItems = (int *)
- palloc(MaxIndexTuplesPerPage * sizeof(int));
+ so->killedItems = palloc_array(int, MaxIndexTuplesPerPage);
if (so->numKilled < MaxIndexTuplesPerPage)
so->killedItems[so->numKilled++] = so->currPos.itemIndex;
scan = RelationGetIndexScan(rel, nkeys, norderbys);
- so = (HashScanOpaque) palloc(sizeof(HashScanOpaqueData));
+ so = (HashScanOpaque) palloc_object(HashScanOpaqueData);
HashScanPosInvalidate(so->currPos);
so->hashso_bucket_buf = InvalidBuffer;
so->hashso_split_bucket_buf = InvalidBuffer;
/* return statistics */
if (stats == NULL)
- stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ stats = palloc0_object(IndexBulkDeleteResult);
stats->estimated_count = false;
stats->num_index_tuples = num_index_tuples;
stats->tuples_removed += tuples_removed;
HSpool *
_h_spoolinit(Relation heap, Relation index, uint32 num_buckets)
{
- HSpool *hspool = (HSpool *) palloc0(sizeof(HSpool));
+ HSpool *hspool = palloc0_object(HSpool);
hspool->index = index;
*/
if (flags & SO_TYPE_BITMAPSCAN)
{
- BitmapHeapScanDesc bscan = palloc(sizeof(BitmapHeapScanDescData));
+ BitmapHeapScanDesc bscan = palloc_object(BitmapHeapScanDescData);
/*
* Bitmap Heap scans do not have any fields that a normal Heap Scan
scan = (HeapScanDesc) bscan;
}
else
- scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
+ scan = (HeapScanDesc) palloc_object(HeapScanDescData);
scan->rs_base.rs_rd = relation;
scan->rs_base.rs_snapshot = snapshot;
* when doing a parallel scan.
*/
if (parallel_scan != NULL)
- scan->rs_parallelworkerdata = palloc(sizeof(ParallelBlockTableScanWorkerData));
+ scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
else
scan->rs_parallelworkerdata = NULL;
* initscan() and we don't want to allocate memory again
*/
if (nkeys > 0)
- scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
+ scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
else
scan->rs_base.rs_key = NULL;
{
BulkInsertState bistate;
- bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
+ bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
bistate->current_buf = InvalidBuffer;
bistate->next_free = InvalidBlockNumber;
* even member XIDs >= OldestXmin often won't be kept by second pass.
*/
nnewmembers = 0;
- newmembers = palloc(sizeof(MultiXactMember) * nmembers);
+ newmembers = palloc_array(MultiXactMember, nmembers);
has_lockers = false;
update_xid = InvalidTransactionId;
update_committed = false;
Assert(delstate->ndeltids > 0);
/* Calculate per-heap-block count of TIDs */
- blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
+ blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
for (int i = 0; i < delstate->ndeltids; i++)
{
TM_IndexDelete *ideltid = &delstate->deltids[i];
static IndexFetchTableData *
heapam_index_fetch_begin(Relation rel)
{
- IndexFetchHeapData *hscan = palloc0(sizeof(IndexFetchHeapData));
+ IndexFetchHeapData *hscan = palloc0_object(IndexFetchHeapData);
hscan->xs_base.rel = rel;
hscan->xs_cbuf = InvalidBuffer;
/* Preallocate values/isnull arrays */
natts = newTupDesc->natts;
- values = (Datum *) palloc(natts * sizeof(Datum));
- isnull = (bool *) palloc(natts * sizeof(bool));
+ values = palloc_array(Datum, natts);
+ isnull = palloc_array(bool, natts);
/* Initialize the rewrite operation */
rwstate = begin_heap_rewrite(OldHeap, NewHeap, OldestXmin, *xid_cutoff,
old_cxt = MemoryContextSwitchTo(rw_cxt);
/* Create and fill in the state struct */
- state = palloc0(sizeof(RewriteStateData));
+ state = palloc0_object(RewriteStateData);
state->rs_old_rel = old_heap;
state->rs_new_rel = new_heap;
* of each rel. It's convenient for code in lazy_scan_heap to always use
* these temp copies.
*/
- vacrel = (LVRelState *) palloc0(sizeof(LVRelState));
+ vacrel = palloc0_object(LVRelState);
vacrel->dbname = get_database_name(MyDatabaseId);
vacrel->relnamespace = get_namespace_name(RelationGetNamespace(rel));
vacrel->relname = pstrdup(RelationGetRelationName(rel));
if (instrument && vacrel->nindexes > 0)
{
/* Copy index names used by instrumentation (not error reporting) */
- indnames = palloc(sizeof(char *) * vacrel->nindexes);
+ indnames = palloc_array(char *, vacrel->nindexes);
for (int i = 0; i < vacrel->nindexes; i++)
indnames[i] = pstrdup(RelationGetRelationName(vacrel->indrels[i]));
}
* locally.
*/
- dead_items_info = (VacDeadItemsInfo *) palloc(sizeof(VacDeadItemsInfo));
+ dead_items_info = palloc_object(VacDeadItemsInfo);
dead_items_info->max_bytes = vac_work_mem * (Size) 1024;
dead_items_info->num_items = 0;
vacrel->dead_items_info = dead_items_info;
}
/* Time for a new group */
- thisgroup = (OpFamilyOpFuncGroup *) palloc(sizeof(OpFamilyOpFuncGroup));
+ thisgroup = palloc_object(OpFamilyOpFuncGroup);
if (oprform &&
(!procform ||
(oprform->amoplefttype < procform->amproclefttype ||
{
IndexScanDesc scan;
- scan = (IndexScanDesc) palloc(sizeof(IndexScanDescData));
+ scan = palloc_object(IndexScanDescData);
scan->heapRelation = NULL; /* may be set later */
scan->xs_heapfetch = NULL;
* We allocate key workspace here, but it won't get filled until amrescan.
*/
if (nkeys > 0)
- scan->keyData = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
+ scan->keyData = palloc_array(ScanKeyData, nkeys);
else
scan->keyData = NULL;
if (norderbys > 0)
- scan->orderByData = (ScanKey) palloc(sizeof(ScanKeyData) * norderbys);
+ scan->orderByData = palloc_array(ScanKeyData, norderbys);
else
scan->orderByData = NULL;
delstate.bottomup = false;
delstate.bottomupfreespace = 0;
delstate.ndeltids = 0;
- delstate.deltids = palloc(nitems * sizeof(TM_IndexDelete));
- delstate.status = palloc(nitems * sizeof(TM_IndexStatus));
+ delstate.deltids = palloc_array(TM_IndexDelete, nitems);
+ delstate.status = palloc_array(TM_IndexStatus, nitems);
/* identify what the index tuples about to be deleted point to */
for (int i = 0; i < nitems; i++)
else
irel = NULL;
- sysscan = (SysScanDesc) palloc(sizeof(SysScanDescData));
+ sysscan = palloc_object(SysScanDescData);
sysscan->heap_rel = heapRelation;
sysscan->irel = irel;
elog(WARNING, "using index \"%s\" despite IgnoreSystemIndexes",
RelationGetRelationName(indexRelation));
- sysscan = (SysScanDesc) palloc(sizeof(SysScanDescData));
+ sysscan = palloc_object(SysScanDescData);
sysscan->heap_rel = heapRelation;
sysscan->irel = indexRelation;
* That ought to leave us with a good split point when pages full of
* duplicates can be split several times.
*/
- state = (BTDedupState) palloc(sizeof(BTDedupStateData));
+ state = palloc_object(BTDedupStateData);
state->deduplicate = true;
state->nmaxitems = 0;
state->maxpostingsize = Min(BTMaxItemSize / 2, INDEX_SIZE_MASK);
newitemsz += sizeof(ItemIdData);
/* Initialize deduplication state */
- state = (BTDedupState) palloc(sizeof(BTDedupStateData));
+ state = palloc_object(BTDedupStateData);
state->deduplicate = true;
state->nmaxitems = 0;
state->maxpostingsize = BLCKSZ; /* We're not really deduplicating */
delstate.bottomup = true;
delstate.bottomupfreespace = Max(BLCKSZ / 16, newitemsz);
delstate.ndeltids = 0;
- delstate.deltids = palloc(MaxTIDsPerBTreePage * sizeof(TM_IndexDelete));
- delstate.status = palloc(MaxTIDsPerBTreePage * sizeof(TM_IndexStatus));
+ delstate.deltids = palloc_array(TM_IndexDelete, MaxTIDsPerBTreePage);
+ delstate.status = palloc_array(TM_IndexStatus, MaxTIDsPerBTreePage);
minoff = P_FIRSTDATAKEY(opaque);
maxoff = PageGetMaxOffsetNumber(page);
*/
spacentids = ndeletable + 1;
ntids = 0;
- tidblocks = (BlockNumber *) palloc(sizeof(BlockNumber) * spacentids);
+ tidblocks = palloc_array(BlockNumber, spacentids);
/*
* First add the table block for the incoming newitem. This is the one
vstate->maxbufsize = (int) maxbufsize;
/* Allocate buffer, indicate that there are currently 0 pending pages */
- vstate->pendingpages = palloc(sizeof(BTPendingFSM) * vstate->bufsize);
+ vstate->pendingpages = palloc_array(BTPendingFSM, vstate->bufsize);
vstate->npendingpages = 0;
}
* just forget any excess entries.
*/
if (so->killedItems == NULL)
- so->killedItems = (int *)
- palloc(MaxTIDsPerBTreePage * sizeof(int));
+ so->killedItems = palloc_array(int, MaxTIDsPerBTreePage);
if (so->numKilled < MaxTIDsPerBTreePage)
so->killedItems[so->numKilled++] = so->currPos.itemIndex;
}
scan = RelationGetIndexScan(rel, nkeys, norderbys);
/* allocate private workspace */
- so = (BTScanOpaque) palloc(sizeof(BTScanOpaqueData));
+ so = palloc_object(BTScanOpaqueData);
BTScanPosInvalidate(so->currPos);
BTScanPosInvalidate(so->markPos);
if (scan->numberOfKeys > 0)
/* allocate stats if first time through, else re-use existing struct */
if (stats == NULL)
- stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ stats = palloc0_object(IndexBulkDeleteResult);
/* Establish the vacuum cycle ID to use for this scan */
/* The ENSURE stuff ensures we clean up shared memory on failure */
* We handle the problem by making num_index_tuples an estimate in
* cleanup-only case.
*/
- stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ stats = palloc0_object(IndexBulkDeleteResult);
btvacuumscan(info, stats, NULL, NULL, 0);
stats->estimated_count = true;
}
* page one level down, it usually ends up inserting a new pivot
* tuple/downlink immediately after the location recorded here.
*/
- new_stack = (BTStack) palloc(sizeof(BTStackData));
+ new_stack = (BTStack) palloc_object(BTStackData);
new_stack->bts_blkno = BufferGetBlockNumber(*bufP);
new_stack->bts_offset = offnum;
new_stack->bts_parent = stack_in;
if (buildstate.btleader)
_bt_end_parallel(buildstate.btleader);
- result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
+ result = palloc_object(IndexBuildResult);
result->heap_tuples = reltuples;
result->index_tuples = buildstate.indtuples;
_bt_spools_heapscan(Relation heap, Relation index, BTBuildState *buildstate,
IndexInfo *indexInfo)
{
- BTSpool *btspool = (BTSpool *) palloc0(sizeof(BTSpool));
+ BTSpool *btspool = palloc0_object(BTSpool);
SortCoordinate coordinate = NULL;
double reltuples = 0;
*/
if (buildstate->btleader)
{
- coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
+ coordinate = palloc0_object(SortCoordinateData);
coordinate->isWorker = false;
coordinate->nParticipants =
buildstate->btleader->nparticipanttuplesorts;
*/
if (indexInfo->ii_Unique)
{
- BTSpool *btspool2 = (BTSpool *) palloc0(sizeof(BTSpool));
+ BTSpool *btspool2 = palloc0_object(BTSpool);
SortCoordinate coordinate2 = NULL;
/* Initialize secondary spool */
* tuplesort_begin_index_btree() about the basic high level
* coordination of a parallel sort.
*/
- coordinate2 = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
+ coordinate2 = palloc0_object(SortCoordinateData);
coordinate2->isWorker = false;
coordinate2->nParticipants =
buildstate->btleader->nparticipanttuplesorts;
static BTPageState *
_bt_pagestate(BTWriteState *wstate, uint32 level)
{
- BTPageState *state = (BTPageState *) palloc0(sizeof(BTPageState));
+ BTPageState *state = palloc0_object(BTPageState);
/* create initial page for level */
state->btps_buf = _bt_blnewpage(wstate, level);
if (last_off == P_HIKEY)
{
Assert(state->btps_lowkey == NULL);
- state->btps_lowkey = palloc0(sizeof(IndexTupleData));
+ state->btps_lowkey = palloc0_object(IndexTupleData);
state->btps_lowkey->t_info = sizeof(IndexTupleData);
BTreeTupleSetNAtts(state->btps_lowkey, 0, false);
}
itup2 = tuplesort_getindextuple(btspool2->sortstate, true);
/* Prepare SortSupport data for each column */
- sortKeys = (SortSupport) palloc0(keysz * sizeof(SortSupportData));
+ sortKeys = palloc0_array(SortSupportData, keysz);
for (i = 0; i < keysz; i++)
{
/* merge is unnecessary, deduplicate into posting lists */
BTDedupState dstate;
- dstate = (BTDedupState) palloc(sizeof(BTDedupStateData));
+ dstate = palloc_object(BTDedupStateData);
dstate->deduplicate = true; /* unused */
dstate->nmaxitems = 0; /* unused */
dstate->maxpostingsize = 0; /* set later */
Sharedsort *sharedsort;
Sharedsort *sharedsort2;
BTSpool *btspool = buildstate->spool;
- BTLeader *btleader = (BTLeader *) palloc0(sizeof(BTLeader));
+ BTLeader *btleader = palloc0_object(BTLeader);
WalUsage *walusage;
BufferUsage *bufferusage;
bool leaderparticipates = true;
int sortmem;
/* Allocate memory and initialize private spool */
- leaderworker = (BTSpool *) palloc0(sizeof(BTSpool));
+ leaderworker = palloc0_object(BTSpool);
leaderworker->heap = buildstate->spool->heap;
leaderworker->index = buildstate->spool->index;
leaderworker->isunique = buildstate->spool->isunique;
else
{
/* Allocate memory for worker's own private secondary spool */
- leaderworker2 = (BTSpool *) palloc0(sizeof(BTSpool));
+ leaderworker2 = palloc0_object(BTSpool);
/* Initialize worker's own secondary spool */
leaderworker2->heap = leaderworker->heap;
indexRel = index_open(btshared->indexrelid, indexLockmode);
/* Initialize worker's own spool */
- btspool = (BTSpool *) palloc0(sizeof(BTSpool));
+ btspool = palloc0_object(BTSpool);
btspool->heap = heapRel;
btspool->index = indexRel;
btspool->isunique = btshared->isunique;
else
{
/* Allocate memory for worker's own private secondary spool */
- btspool2 = (BTSpool *) palloc0(sizeof(BTSpool));
+ btspool2 = palloc0_object(BTSpool);
/* Initialize worker's own secondary spool */
btspool2->heap = btspool->heap;
IndexInfo *indexInfo;
/* Initialize local tuplesort coordination state */
- coordinate = palloc0(sizeof(SortCoordinateData));
+ coordinate = palloc0_object(SortCoordinateData);
coordinate->isWorker = true;
coordinate->nParticipants = -1;
coordinate->sharedsort = sharedsort;
* worker). Worker processes are generally permitted to allocate
* work_mem independently.
*/
- coordinate2 = palloc0(sizeof(SortCoordinateData));
+ coordinate2 = palloc0_object(SortCoordinateData);
coordinate2->isWorker = true;
coordinate2->nParticipants = -1;
coordinate2->sharedsort = sharedsort2;
* between tuples will be legal).
*/
state.maxsplits = maxoff;
- state.splits = palloc(sizeof(SplitPoint) * state.maxsplits);
+ state.splits = palloc_array(SplitPoint, state.maxsplits);
state.nsplits = 0;
/*
BTDedupInterval *intervals;
Page newpage;
- state = (BTDedupState) palloc(sizeof(BTDedupStateData));
+ state = palloc_object(BTDedupStateData);
state->deduplicate = true; /* unused */
state->nmaxitems = 0; /* unused */
/* Conservatively use larger maxpostingsize than primary */
else if (offset > tuple->nNodes)
elog(ERROR, "invalid offset for adding node to SPGiST inner tuple");
- nodes = palloc(sizeof(SpGistNodeTuple) * (tuple->nNodes + 1));
+ nodes = palloc_array(SpGistNodeTuple, tuple->nNodes + 1);
SGITITERATE(tuple, i, node)
{
if (i < offset)
/* Locate the tuples to be moved, and count up the space needed */
i = PageGetMaxOffsetNumber(current->page);
- toDelete = (OffsetNumber *) palloc(sizeof(OffsetNumber) * i);
- toInsert = (OffsetNumber *) palloc(sizeof(OffsetNumber) * (i + 1));
+ toDelete = palloc_array(OffsetNumber, i);
+ toInsert = palloc_array(OffsetNumber, i + 1);
size = newLeafTuple->size + sizeof(ItemIdData);
{
Datum theLabel = out->nodeLabels[theNode];
- out->nodeLabels = (Datum *) palloc(sizeof(Datum) * out->nNodes);
+ out->nodeLabels = palloc_array(Datum, out->nNodes);
for (i = 0; i < out->nNodes; i++)
out->nodeLabels[i] = theLabel;
}
*/
max = PageGetMaxOffsetNumber(current->page);
n = max + 1;
- in.datums = (Datum *) palloc(sizeof(Datum) * n);
- toDelete = (OffsetNumber *) palloc(sizeof(OffsetNumber) * n);
- toInsert = (OffsetNumber *) palloc(sizeof(OffsetNumber) * n);
- oldLeafs = (SpGistLeafTuple *) palloc(sizeof(SpGistLeafTuple) * n);
- newLeafs = (SpGistLeafTuple *) palloc(sizeof(SpGistLeafTuple) * n);
- leafPageSelect = (uint8 *) palloc(sizeof(uint8) * n);
+ in.datums = palloc_array(Datum, n);
+ toDelete = palloc_array(OffsetNumber, n);
+ toInsert = palloc_array(OffsetNumber, n);
+ oldLeafs = palloc_array(SpGistLeafTuple, n);
+ newLeafs = palloc_array(SpGistLeafTuple, n);
+ leafPageSelect = palloc_array(uint8, n);
STORE_STATE(state, xlrec.stateSrc);
out.hasPrefix = false;
out.nNodes = 1;
out.nodeLabels = NULL;
- out.mapTuplesToNodes = palloc0(sizeof(int) * in.nTuples);
+ out.mapTuplesToNodes = palloc0_array(int, in.nTuples);
/*
* Form new leaf tuples and count up the total space needed.
* out.nNodes with a value larger than the number of tuples on the input
* page, we can't allocate these arrays before here.
*/
- nodes = (SpGistNodeTuple *) palloc(sizeof(SpGistNodeTuple) * out.nNodes);
- leafSizes = (int *) palloc0(sizeof(int) * out.nNodes);
+ nodes = palloc_array(SpGistNodeTuple, out.nNodes);
+ leafSizes = palloc0_array(int, out.nNodes);
/*
* Form nodes of inner tuple and inner tuple itself
* do so, even if totalLeafSizes is less than the available space,
* because we can't split a group across pages.
*/
- nodePageSelect = (uint8 *) palloc(sizeof(uint8) * out.nNodes);
+ nodePageSelect = palloc_array(uint8, out.nNodes);
curspace = currentFreeSpace;
newspace = PageGetExactFreeSpace(BufferGetPage(newLeafBuffer));
* Construct new prefix tuple with requested number of nodes. We'll fill
* in the childNodeN'th node's downlink below.
*/
- nodes = (SpGistNodeTuple *) palloc(sizeof(SpGistNodeTuple) *
- out->result.splitTuple.prefixNNodes);
+ nodes = palloc_array(SpGistNodeTuple, out->result.splitTuple.prefixNNodes);
for (i = 0; i < out->result.splitTuple.prefixNNodes; i++)
{
* same node datums, but with the prefix specified by the picksplit
* function.
*/
- nodes = palloc(sizeof(SpGistNodeTuple) * innerTuple->nNodes);
+ nodes = palloc_array(SpGistNodeTuple, innerTuple->nNodes);
SGITITERATE(innerTuple, i, node)
{
nodes[i] = node;
true);
}
- result = (IndexBuildResult *) palloc0(sizeof(IndexBuildResult));
+ result = palloc0_object(IndexBuildResult);
result->heap_tuples = reltuples;
result->index_tuples = buildstate.indtuples;
SortedPoint *sorted;
double coord;
- sorted = palloc(sizeof(*sorted) * in->nTuples);
+ sorted = palloc_array(SortedPoint, in->nTuples);
for (i = 0; i < in->nTuples; i++)
{
sorted[i].p = DatumGetPointP(in->datums[i]);
out->nNodes = 2;
out->nodeLabels = NULL; /* we don't need node labels */
- out->mapTuplesToNodes = palloc(sizeof(int) * in->nTuples);
- out->leafTupleDatums = palloc(sizeof(Datum) * in->nTuples);
+ out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+ out->leafTupleDatums = palloc_array(Datum, in->nTuples);
/*
* Note: points that have coordinates exactly equal to coord may get
if (!which)
PG_RETURN_VOID();
- out->nodeNumbers = (int *) palloc(sizeof(int) * 2);
+ out->nodeNumbers = palloc_array(int, 2);
/*
* When ordering scan keys are specified, we've to calculate distance for
BOX infArea;
BOX *area;
- out->distances = (double **) palloc(sizeof(double *) * in->nNodes);
- out->traversalValues = (void **) palloc(sizeof(void *) * in->nNodes);
+ out->distances = palloc_array(double *, in->nNodes);
+ out->traversalValues = palloc_array(void *, in->nNodes);
if (in->level == 0)
{
}
/* Set up level increments, too */
- out->levelAdds = (int *) palloc(sizeof(int) * 2);
+ out->levelAdds = palloc_array(int, 2);
out->levelAdds[0] = 1;
out->levelAdds[1] = 1;
ScanKey orderbys, int norderbys)
{
int sk_num;
- double *distances = (double *) palloc(norderbys * sizeof(double)),
+ double *distances = palloc_array(double, norderbys),
*distance = distances;
for (sk_num = 0; sk_num < norderbys; ++sk_num, ++orderbys, ++distance)
BOX *
box_copy(BOX *orig)
{
- BOX *result = palloc(sizeof(BOX));
+ BOX *result = palloc_object(BOX);
*result = *orig;
return result;
static BOX *
getQuadrantArea(BOX *bbox, Point *centroid, int quadrant)
{
- BOX *result = (BOX *) palloc(sizeof(BOX));
+ BOX *result = palloc_object(BOX);
switch (quadrant)
{
/* Use the median values of x and y as the centroid point */
Point **sorted;
- sorted = palloc(sizeof(*sorted) * in->nTuples);
+ sorted = palloc_array(Point *, in->nTuples);
for (i = 0; i < in->nTuples; i++)
sorted[i] = DatumGetPointP(in->datums[i]);
- centroid = palloc(sizeof(*centroid));
+ centroid = palloc_object(Point);
qsort(sorted, in->nTuples, sizeof(*sorted), x_cmp);
centroid->x = sorted[in->nTuples >> 1]->x;
centroid->y = sorted[in->nTuples >> 1]->y;
#else
/* Use the average values of x and y as the centroid point */
- centroid = palloc0(sizeof(*centroid));
+ centroid = palloc0_object(Point);
for (i = 0; i < in->nTuples; i++)
{
out->nNodes = 4;
out->nodeLabels = NULL; /* we don't need node labels */
- out->mapTuplesToNodes = palloc(sizeof(int) * in->nTuples);
- out->leafTupleDatums = palloc(sizeof(Datum) * in->nTuples);
+ out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+ out->leafTupleDatums = palloc_array(Datum, in->nTuples);
for (i = 0; i < in->nTuples; i++)
{
*/
if (in->norderbys > 0)
{
- out->distances = (double **) palloc(sizeof(double *) * in->nNodes);
- out->traversalValues = (void **) palloc(sizeof(void *) * in->nNodes);
+ out->distances = palloc_array(double *, in->nNodes);
+ out->traversalValues = palloc_array(void *, in->nNodes);
if (in->level == 0)
{
{
/* Report that all nodes should be visited */
out->nNodes = in->nNodes;
- out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
+ out->nodeNumbers = palloc_array(int, in->nNodes);
for (i = 0; i < in->nNodes; i++)
{
out->nodeNumbers[i] = i;
break; /* no need to consider remaining conditions */
}
- out->levelAdds = palloc(sizeof(int) * 4);
+ out->levelAdds = palloc_array(int, 4);
for (i = 0; i < 4; ++i)
out->levelAdds[i] = 1;
/* We must descend into the quadrant(s) identified by which */
- out->nodeNumbers = (int *) palloc(sizeof(int) * 4);
+ out->nodeNumbers = palloc_array(int, 4);
out->nNodes = 0;
for (i = 1; i <= 4; i++)
scan = RelationGetIndexScan(rel, keysz, orderbysz);
- so = (SpGistScanOpaque) palloc0(sizeof(SpGistScanOpaqueData));
+ so = palloc0_object(SpGistScanOpaqueData);
if (keysz > 0)
- so->keyData = (ScanKey) palloc(sizeof(ScanKeyData) * keysz);
+ so->keyData = palloc_array(ScanKeyData, keysz);
else
so->keyData = NULL;
initSpGistState(&so->state, scan->indexRelation);
if (scan->numberOfOrderBys > 0)
{
/* This will be filled in spgrescan, but allocate the space here */
- so->orderByTypes = (Oid *)
- palloc(sizeof(Oid) * scan->numberOfOrderBys);
- so->nonNullOrderByOffsets = (int *)
- palloc(sizeof(int) * scan->numberOfOrderBys);
+ so->orderByTypes = palloc_array(Oid, scan->numberOfOrderBys);
+ so->nonNullOrderByOffsets = palloc_array(int, scan->numberOfOrderBys);
/* These arrays have constant contents, so we can fill them now */
- so->zeroDistances = (double *)
- palloc(sizeof(double) * scan->numberOfOrderBys);
- so->infDistances = (double *)
- palloc(sizeof(double) * scan->numberOfOrderBys);
+ so->zeroDistances = palloc_array(double, scan->numberOfOrderBys);
+ so->infDistances = palloc_array(double, scan->numberOfOrderBys);
for (i = 0; i < scan->numberOfOrderBys; i++)
{
so->infDistances[i] = get_float8_infinity();
}
- scan->xs_orderbyvals = (Datum *)
- palloc0(sizeof(Datum) * scan->numberOfOrderBys);
- scan->xs_orderbynulls = (bool *)
- palloc(sizeof(bool) * scan->numberOfOrderBys);
+ scan->xs_orderbyvals = palloc0_array(Datum, scan->numberOfOrderBys);
+ scan->xs_orderbynulls = palloc_array(bool, scan->numberOfOrderBys);
memset(scan->xs_orderbynulls, true,
sizeof(bool) * scan->numberOfOrderBys);
}
{
/* force all children to be visited */
out.nNodes = nNodes;
- out.nodeNumbers = (int *) palloc(sizeof(int) * nNodes);
+ out.nodeNumbers = palloc_array(int, nNodes);
for (i = 0; i < nNodes; i++)
out.nodeNumbers[i] = i;
}
{
/* collect node pointers */
SpGistNodeTuple node;
- SpGistNodeTuple *nodes = (SpGistNodeTuple *) palloc(sizeof(SpGistNodeTuple) * nNodes);
+ SpGistNodeTuple *nodes = palloc_array(SpGistNodeTuple, nNodes);
SGITITERATE(innerTuple, i, node)
{
so->distances[so->nPtrs] = NULL;
else
{
- IndexOrderByDistance *distances =
- palloc(sizeof(distances[0]) * so->numberOfOrderBys);
+ IndexOrderByDistance *distances = palloc_array(IndexOrderByDistance,
+ so->numberOfOrderBys);
int i;
for (i = 0; i < so->numberOfOrderBys; i++)
formTextDatum(prefixStr, commonLen);
}
out->result.splitTuple.prefixNNodes = 1;
- out->result.splitTuple.prefixNodeLabels =
- (Datum *) palloc(sizeof(Datum));
+ out->result.splitTuple.prefixNodeLabels = palloc_object(Datum);
out->result.splitTuple.prefixNodeLabels[0] =
Int16GetDatum(*(unsigned char *) (prefixStr + commonLen));
out->result.splitTuple.prefixHasPrefix = in->hasPrefix;
out->result.splitTuple.prefixPrefixDatum = in->prefixDatum;
out->result.splitTuple.prefixNNodes = 1;
- out->result.splitTuple.prefixNodeLabels = (Datum *) palloc(sizeof(Datum));
+ out->result.splitTuple.prefixNodeLabels = palloc_object(Datum);
out->result.splitTuple.prefixNodeLabels[0] = Int16GetDatum(-2);
out->result.splitTuple.childNodeN = 0;
out->result.splitTuple.postfixHasPrefix = false;
}
/* Extract the node label (first non-common byte) from each value */
- nodes = (spgNodePtr *) palloc(sizeof(spgNodePtr) * in->nTuples);
+ nodes = palloc_array(spgNodePtr, in->nTuples);
for (i = 0; i < in->nTuples; i++)
{
/* And emit results */
out->nNodes = 0;
- out->nodeLabels = (Datum *) palloc(sizeof(Datum) * in->nTuples);
- out->mapTuplesToNodes = (int *) palloc(sizeof(int) * in->nTuples);
- out->leafTupleDatums = (Datum *) palloc(sizeof(Datum) * in->nTuples);
+ out->nodeLabels = palloc_array(Datum, in->nTuples);
+ out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+ out->leafTupleDatums = palloc_array(Datum, in->nTuples);
for (i = 0; i < in->nTuples; i++)
{
* and see if it's consistent with the query. If so, emit an entry into
* the output arrays.
*/
- out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
- out->levelAdds = (int *) palloc(sizeof(int) * in->nNodes);
- out->reconstructedValues = (Datum *) palloc(sizeof(Datum) * in->nNodes);
+ out->nodeNumbers = palloc_array(int, in->nNodes);
+ out->levelAdds = palloc_array(int, in->nNodes);
+ out->reconstructedValues = palloc_array(Datum, in->nNodes);
out->nNodes = 0;
for (i = 0; i < in->nNodes; i++)
}
else
{
- nodeLabels = (Datum *) palloc(sizeof(Datum) * innerTuple->nNodes);
+ nodeLabels = palloc_array(Datum, innerTuple->nNodes);
SGITITERATE(innerTuple, i, node)
{
if (IndexTupleHasNulls(node))
listLink = &pitem->next;
}
/* not there, so append new entry */
- pitem = (spgVacPendingItem *) palloc(sizeof(spgVacPendingItem));
+ pitem = palloc_object(spgVacPendingItem);
pitem->tid = *tid;
pitem->done = false;
pitem->next = NULL;
/* allocate stats if first time through, else re-use existing struct */
if (stats == NULL)
- stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ stats = palloc0_object(IndexBulkDeleteResult);
bds.info = info;
bds.stats = stats;
bds.callback = callback;
*/
if (stats == NULL)
{
- stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ stats = palloc0_object(IndexBulkDeleteResult);
bds.info = info;
bds.stats = stats;
bds.callback = dummy_callback;
int max = PageGetMaxOffsetNumber(page);
OffsetNumber *toDelete;
- toDelete = palloc(sizeof(OffsetNumber) * max);
+ toDelete = palloc_array(OffsetNumber, max);
for (i = xldata->firstPlaceholder; i <= max; i++)
toDelete[i - xldata->firstPlaceholder] = i;
static void
system_initsamplescan(SampleScanState *node, int eflags)
{
- node->tsm_state = palloc0(sizeof(SystemSamplerData));
+ node->tsm_state = palloc0_object(SystemSamplerData);
}
/*
* Note we have the same race condition here as above: j could be 0 at the
* end of the loop.
*/
- newMembers = (MultiXactMember *)
- palloc(sizeof(MultiXactMember) * (nmembers + 1));
+ newMembers = palloc_array(MultiXactMember, nmembers + 1);
for (i = 0, j = 0; i < nmembers; i++)
{
oldcontext = MemoryContextSwitchTo(TopTransactionContext);
/* Initialize a new ParallelContext. */
- pcxt = palloc0(sizeof(ParallelContext));
+ pcxt = palloc0_object(ParallelContext);
pcxt->subid = GetCurrentSubTransactionId();
pcxt->nworkers = nworkers;
pcxt->nworkers_to_launch = nworkers;
clientconninfospace);
/* Allocate space for worker information. */
- pcxt->worker = palloc0(sizeof(ParallelWorkerInfo) * pcxt->nworkers);
+ pcxt->worker = palloc0_array(ParallelWorkerInfo, pcxt->nworkers);
/*
* Establish error queues in dynamic shared memory.
*/
if (pcxt->nworkers_launched > 0)
{
- pcxt->known_attached_workers =
- palloc0(sizeof(bool) * pcxt->nworkers_launched);
+ pcxt->known_attached_workers = palloc0_array(bool, pcxt->nworkers_launched);
pcxt->nknown_attached_workers = 0;
}
/* Timeline 1 does not have a history file, so no need to check */
if (targetTLI == 1)
{
- entry = (TimeLineHistoryEntry *) palloc(sizeof(TimeLineHistoryEntry));
+ entry = palloc_object(TimeLineHistoryEntry);
entry->tli = targetTLI;
entry->begin = entry->end = InvalidXLogRecPtr;
return list_make1(entry);
(errcode_for_file_access(),
errmsg("could not open file \"%s\": %m", path)));
/* Not there, so assume no parents */
- entry = (TimeLineHistoryEntry *) palloc(sizeof(TimeLineHistoryEntry));
+ entry = palloc_object(TimeLineHistoryEntry);
entry->tli = targetTLI;
entry->begin = entry->end = InvalidXLogRecPtr;
return list_make1(entry);
lasttli = tli;
- entry = (TimeLineHistoryEntry *) palloc(sizeof(TimeLineHistoryEntry));
+ entry = palloc_object(TimeLineHistoryEntry);
entry->tli = tli;
entry->begin = prevend;
entry->end = ((uint64) (switchpoint_hi)) << 32 | (uint64) switchpoint_lo;
* Create one more entry for the "tip" of the timeline, which has no entry
* in the history file.
*/
- entry = (TimeLineHistoryEntry *) palloc(sizeof(TimeLineHistoryEntry));
+ entry = palloc_object(TimeLineHistoryEntry);
entry->tli = targetTLI;
entry->begin = prevend;
entry->end = InvalidXLogRecPtr;
}
num = TwoPhaseState->numPrepXacts;
- array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
+ array = palloc_array(GlobalTransactionData, num);
*gxacts = array;
for (i = 0; i < num; i++)
memcpy(array + i, TwoPhaseState->prepXacts[i],
* Collect all the 2PC status information that we will format and send
* out as a result set.
*/
- status = (Working_State *) palloc(sizeof(Working_State));
+ status = palloc_object(Working_State);
funcctx->user_fctx = status;
status->ngxacts = GetPreparedTransactionList(&status->array);
if (padlen > records.bytes_free)
{
- records.tail->next = palloc0(sizeof(StateFileChunk));
+ records.tail->next = palloc0_object(StateFileChunk);
records.tail = records.tail->next;
records.tail->len = 0;
records.tail->next = NULL;
SharedInvalidationMessage *invalmsgs;
/* Initialize linked list */
- records.head = palloc0(sizeof(StateFileChunk));
+ records.head = palloc0_object(StateFileChunk);
records.head->len = 0;
records.head->next = NULL;
if (len != NULL)
*len = XLogRecGetDataLen(xlogreader);
- *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
+ *buf = palloc_array(char, XLogRecGetDataLen(xlogreader));
memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
XLogReaderFree(xlogreader);
TransactionState *parents;
size_t parentOffset = 0;
- parents = palloc(sizeof(TransactionState) * s->nestingLevel);
+ parents = palloc_array(TransactionState, s->nestingLevel);
while (p != NULL && !FullTransactionIdIsValid(p->fullTransactionId))
{
parents[parentOffset++] = p;
LocalProcessControlFile(bool reset)
{
Assert(reset || ControlFile == NULL);
- ControlFile = palloc(sizeof(ControlFileData));
+ ControlFile = palloc_object(ControlFileData);
ReadControlFile();
}
continue;
}
- ti = palloc(sizeof(tablespaceinfo));
+ ti = palloc_object(tablespaceinfo);
ti->oid = tsoid;
ti->path = pstrdup(linkpath);
ti->rpath = relpath;
}
oldcontext = MemoryContextSwitchTo(backupcontext);
- backup_state = (BackupState *) palloc0(sizeof(BackupState));
+ backup_state = palloc0_object(BackupState);
tablespace_map = makeStringInfo();
MemoryContextSwitchTo(oldcontext);
XLogPrefetcher *prefetcher;
HASHCTL ctl;
- prefetcher = palloc0(sizeof(XLogPrefetcher));
+ prefetcher = palloc0_object(XLogPrefetcher);
prefetcher->reader = reader;
ctl.keysize = sizeof(RelFileLocator);
* Set the WAL reading processor now, as it will be needed when reading
* the checkpoint record required (backup_label or not).
*/
- private = palloc0(sizeof(XLogPageReadPrivate));
+ private = palloc0_object(XLogPageReadPrivate);
xlogreader =
XLogReaderAllocate(wal_segment_size, NULL,
XL_ROUTINE(.page_read = &XLogPageRead,
errmsg("invalid data in file \"%s\"", TABLESPACE_MAP)));
str[n++] = '\0';
- ti = palloc0(sizeof(tablespaceinfo));
+ ti = palloc0_object(tablespaceinfo);
errno = 0;
ti->oid = strtoul(str, &endp, 10);
if (*endp != '\0' || errno == EINVAL || errno == ERANGE)
EndOfWalRecoveryInfo *
FinishWalRecovery(void)
{
- EndOfWalRecoveryInfo *result = palloc(sizeof(EndOfWalRecoveryInfo));
+ EndOfWalRecoveryInfo *result = palloc_object(EndOfWalRecoveryInfo);
XLogRecPtr lastRec;
TimeLineID lastRecTLI;
XLogRecPtr endOfLog;
Relation rel;
/* Allocate the Relation struct and all related space in one block. */
- fakeentry = palloc0(sizeof(FakeRelCacheEntryData));
+ fakeentry = palloc0_object(FakeRelCacheEntryData);
rel = (Relation) fakeentry;
rel->rd_rel = &fakeentry->pgc;
total_checksum_failures = 0;
/* Allocate backup related variables. */
- backup_state = (BackupState *) palloc0(sizeof(BackupState));
+ backup_state = palloc0_object(BackupState);
initStringInfo(&tablespace_map);
basebackup_progress_wait_checkpoint();
PrepareForIncrementalBackup(ib, backup_state);
/* Add a node for the base directory at the end */
- newti = palloc0(sizeof(tablespaceinfo));
+ newti = palloc0_object(tablespaceinfo);
newti->size = -1;
state.tablespaces = lappend(state.tablespaces, newti);
* But we don't need it at all if this is not an incremental backup.
*/
if (ib != NULL)
- relative_block_numbers = palloc(sizeof(BlockNumber) * RELSEG_SIZE);
+ relative_block_numbers = palloc_array(BlockNumber, RELSEG_SIZE);
/*
* Determine if the current path is a database directory that can contain
bbsink *
bbsink_copystream_new(bool send_to_client)
{
- bbsink_copystream *sink = palloc0(sizeof(bbsink_copystream));
+ bbsink_copystream *sink = palloc0_object(bbsink_copystream);
*((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_copystream_ops;
sink->send_to_client = send_to_client;
Assert((compresslevel >= 1 && compresslevel <= 9) ||
compresslevel == Z_DEFAULT_COMPRESSION);
- sink = palloc0(sizeof(bbsink_gzip));
+ sink = palloc0_object(bbsink_gzip);
*((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_gzip_ops;
sink->base.bbs_next = next;
sink->compresslevel = compresslevel;
oldcontext = MemoryContextSwitchTo(mcxt);
- ib = palloc0(sizeof(IncrementalBackupInfo));
+ ib = palloc0_object(IncrementalBackupInfo);
ib->mcxt = mcxt;
initStringInfo(&ib->buf);
*/
ib->manifest_files = backup_file_create(mcxt, 10000, NULL);
- context = palloc0(sizeof(JsonManifestParseContext));
+ context = palloc0_object(JsonManifestParseContext);
/* Parse the manifest. */
context->private_data = ib;
context->version_cb = manifest_process_version;
XLogRecPtr end_lsn)
{
IncrementalBackupInfo *ib = context->private_data;
- backup_wal_range *range = palloc(sizeof(backup_wal_range));
+ backup_wal_range *range = palloc_object(backup_wal_range);
range->tli = tli;
range->start_lsn = start_lsn;
compresslevel = compress->level;
Assert(compresslevel >= 0 && compresslevel <= 12);
- sink = palloc0(sizeof(bbsink_lz4));
+ sink = palloc0_object(bbsink_lz4);
*((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_lz4_ops;
sink->base.bbs_next = next;
sink->compresslevel = compresslevel;
Assert(next != NULL);
- sink = palloc0(sizeof(bbsink));
+ sink = palloc0_object(bbsink);
*((const bbsink_ops **) &sink->bbs_ops) = &bbsink_progress_ops;
sink->bbs_next = next;
bbsink *
bbsink_server_new(bbsink *next, char *pathname)
{
- bbsink_server *sink = palloc0(sizeof(bbsink_server));
+ bbsink_server *sink = palloc0_object(bbsink_server);
*((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_server_ops;
sink->pathname = pathname;
* name into a newly-allocated chunk of memory.
*/
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
- newtype = palloc(sizeof(BaseBackupTargetType));
+ newtype = palloc_object(BaseBackupTargetType);
newtype->name = pstrdup(name);
newtype->check_detail = check_detail;
newtype->get_sink = get_sink;
BaseBackupTargetHandle *handle;
/* Found the target. */
- handle = palloc(sizeof(BaseBackupTargetHandle));
+ handle = palloc_object(BaseBackupTargetHandle);
handle->type = ttype;
handle->detail_arg = ttype->check_detail(target, target_detail);
Assert(next != NULL);
Assert(maxrate > 0);
- sink = palloc0(sizeof(bbsink_throttle));
+ sink = palloc0_object(bbsink_throttle);
*((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_throttle_ops;
sink->base.bbs_next = next;
Assert(next != NULL);
- sink = palloc0(sizeof(bbsink_zstd));
+ sink = palloc0_object(bbsink_zstd);
*((const bbsink_ops **) &sink->base.bbs_ops) = &bbsink_zstd_ops;
sink->base.bbs_next = next;
sink->compress = compress;
continue;
/* Add it to the list. */
- ws = palloc(sizeof(WalSummaryFile));
+ ws = palloc_object(WalSummaryFile);
ws->tli = file_tli;
ws->start_lsn = file_start_lsn;
ws->end_lsn = file_end_lsn;
Form_pg_type typForm = (Form_pg_type) GETSTRUCT(tup);
struct typmap *newtyp;
- newtyp = (struct typmap *) palloc(sizeof(struct typmap));
+ newtyp = palloc_object(struct typmap);
Typ = lappend(Typ, newtyp);
newtyp->am_oid = typForm->oid;
oldcxt = MemoryContextSwitchTo(nogc);
- newind = (IndexList *) palloc(sizeof(IndexList));
+ newind = palloc_object(IndexList);
newind->il_heap = heap;
newind->il_ind = ind;
- newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
+ newind->il_info = palloc_object(IndexInfo);
memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
/* expressions will likely be null, but may as well copy it */
* regression testing.)
*/
maxDependentObjects = 128; /* arbitrary initial allocation */
- dependentObjects = (ObjectAddressAndFlags *)
- palloc(maxDependentObjects * sizeof(ObjectAddressAndFlags));
+ dependentObjects = palloc_array(ObjectAddressAndFlags, maxDependentObjects);
numDependentObjects = 0;
ScanKeyInit(&key[0],
{
ObjectAddresses *addrs;
- addrs = palloc(sizeof(ObjectAddresses));
+ addrs = palloc_object(ObjectAddresses);
addrs->numrefs = 0;
addrs->maxrefs = 32;
- addrs->refs = (ObjectAddress *)
- palloc(addrs->maxrefs * sizeof(ObjectAddress));
+ addrs->refs = palloc_array(ObjectAddress, addrs->maxrefs);
addrs->extras = NULL; /* until/unless needed */
return addrs;
/* Initialize the number of slots to use */
nslots = Min(tupdesc->natts,
(MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_attribute)));
- slot = palloc(sizeof(TupleTableSlot *) * nslots);
+ slot = palloc_array(TupleTableSlot *, nslots);
for (int i = 0; i < nslots; i++)
slot[i] = MakeSingleTupleTableSlot(td, &TTSOpsHeapTuple);
defOid = StoreAttrDefault(rel, colDef->attnum, expr, is_internal);
- cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+ cooked = palloc_object(CookedConstraint);
cooked->contype = CONSTR_DEFAULT;
cooked->conoid = defOid;
cooked->name = NULL;
numchecks++;
- cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+ cooked = palloc_object(CookedConstraint);
cooked->contype = CONSTR_CHECK;
cooked->conoid = constrOid;
cooked->name = ccname;
inhcount,
cdef->is_no_inherit);
- nncooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+ nncooked = palloc_object(CookedConstraint);
nncooked->contype = CONSTR_NOTNULL;
nncooked->conoid = constrOid;
nncooked->name = nnname;
}
/* Extract opclass options for each attribute */
- opclassOptions = palloc0(sizeof(Datum) * newInfo->ii_NumIndexAttrs);
+ opclassOptions = palloc0_array(Datum, newInfo->ii_NumIndexAttrs);
for (int i = 0; i < newInfo->ii_NumIndexAttrs; i++)
opclassOptions[i] = get_attoptions(oldIndexId, i + 1);
*/
Assert(ii->ii_Unique);
- ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
- ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
- ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
+ ii->ii_UniqueOps = palloc_array(Oid, indnkeyatts);
+ ii->ii_UniqueProcs = palloc_array(Oid, indnkeyatts);
+ ii->ii_UniqueStrats = palloc_array(uint16, indnkeyatts);
/*
* We have to look up the operator's strategy number. This provides a
oldcxt = MemoryContextSwitchTo(context);
- result = (SearchPathMatcher *) palloc0(sizeof(SearchPathMatcher));
+ result = palloc0_object(SearchPathMatcher);
schemas = list_copy(activeSearchPath);
while (schemas && linitial_oid(schemas) != activeCreationNamespace)
{
{
SearchPathMatcher *result;
- result = (SearchPathMatcher *) palloc(sizeof(SearchPathMatcher));
+ result = palloc_object(SearchPathMatcher);
result->schemas = list_copy(path->schemas);
result->addCatalog = path->addCatalog;
result->addTemp = path->addTemp;
ALLOCSET_DEFAULT_SIZES);
oldcxt = MemoryContextSwitchTo(memcxt);
- datums = (Datum *) palloc(sizeof(Datum) * list_length(list));
- nulls = palloc(sizeof(bool) * list_length(list));
+ datums = palloc_array(Datum, list_length(list));
+ nulls = palloc_array(bool, list_length(list));
foreach(cell, list)
{
{
CookedConstraint *cooked;
- cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+ cooked = palloc_object(CookedConstraint);
cooked->contype = CONSTR_NOTNULL;
cooked->conoid = conForm->oid;
*/
max_slots = Min(nreferenced,
MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_depend));
- slot = palloc(sizeof(TupleTableSlot *) * max_slots);
+ slot = palloc_array(TupleTableSlot *, max_slots);
/* Don't open indexes unless we need to make an update */
indstate = NULL;
* allocating the next), trouble could only occur if the OID counter wraps
* all the way around before we finish. Which seems unlikely.
*/
- oids = (Oid *) palloc(num_elems * sizeof(Oid));
+ oids = palloc_array(Oid, num_elems);
for (elemno = 0; elemno < num_elems; elemno++)
{
/* allocate the slots to use and initialize them */
nslots = Min(num_elems,
MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_enum));
- slot = palloc(sizeof(TupleTableSlot *) * nslots);
+ slot = palloc_array(TupleTableSlot *, nslots);
for (int i = 0; i < nslots; i++)
slot[i] = MakeSingleTupleTableSlot(RelationGetDescr(pg_enum),
&TTSOpsHeapTuple);
nelems = list->n_members;
/* Sort the existing members by enumsortorder */
- existing = (HeapTuple *) palloc(nelems * sizeof(HeapTuple));
+ existing = palloc_array(HeapTuple, nelems);
for (i = 0; i < nelems; i++)
existing[i] = &(list->members[i]->tuple);
pubform = (Form_pg_publication) GETSTRUCT(tup);
- pub = (Publication *) palloc(sizeof(Publication));
+ pub = palloc_object(Publication);
pub->oid = pubid;
pub->name = pstrdup(NameStr(pubform->pubname));
pub->alltables = pubform->puballtables;
*/
foreach(lc, pub_elem_tables)
{
- published_rel *table_info = (published_rel *) palloc(sizeof(published_rel));
+ published_rel *table_info = palloc_object(published_rel);
table_info->relid = lfirst_oid(lc);
table_info->pubid = pub_elem->oid;
TupleDesc desc = RelationGetDescr(rel);
int i;
- attnums = (int16 *) palloc(desc->natts * sizeof(int16));
+ attnums = palloc_array(int16, desc->natts);
for (i = 0; i < desc->natts; i++)
{
}
if (!stored)
{
- dep = (remoteDep *) palloc(sizeof(remoteDep));
+ dep = palloc_object(remoteDep);
dep->dbOid = sdepForm->dbid;
dep->count = 1;
remDeps = lappend(remDeps, dep);
* know that they will be used.
*/
max_slots = MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_shdepend);
- slot = palloc(sizeof(TupleTableSlot *) * max_slots);
+ slot = palloc_array(TupleTableSlot *, max_slots);
indstate = CatalogOpenIndexes(sdepRel);
subform = (Form_pg_subscription) GETSTRUCT(tup);
- sub = (Subscription *) palloc(sizeof(Subscription));
+ sub = palloc_object(Subscription);
sub->oid = subid;
sub->dbid = subform->subdbid;
sub->skiplsn = subform->subskiplsn;
relkind == RELKIND_PARTITIONED_TABLE) && !tables)
continue;
- relstate = (SubscriptionRelState *) palloc(sizeof(SubscriptionRelState));
+ relstate = palloc_object(SubscriptionRelState);
relstate->relid = subrel->srrelid;
relstate->state = subrel->srsubstate;
d = SysCacheGetAttr(SUBSCRIPTIONRELMAP, tup,
if (maxrels == 0)
{
maxrels = 8;
- srels = palloc(sizeof(SMgrRelation) * maxrels);
+ srels = palloc_array(SMgrRelation, maxrels);
}
else if (maxrels <= nrels)
{
maxrels *= 2;
- srels = repalloc(srels, sizeof(SMgrRelation) * maxrels);
+ srels = repalloc_array(srels, SMgrRelation, maxrels);
}
srels[nrels++] = srel;
if (maxrels == 0)
{
maxrels = 8;
- srels = palloc(sizeof(SMgrRelation) * maxrels);
+ srels = palloc_array(SMgrRelation, maxrels);
}
else if (maxrels <= nrels)
{
maxrels *= 2;
- srels = repalloc(srels, sizeof(SMgrRelation) * maxrels);
+ srels = repalloc_array(srels, SMgrRelation, maxrels);
}
srels[nrels++] = srel;
*ptr = NULL;
return 0;
}
- rptr = (RelFileLocator *) palloc(nrels * sizeof(RelFileLocator));
+ rptr = palloc_array(RelFileLocator, nrels);
*ptr = rptr;
for (pending = pendingDeletes; pending != NULL; pending = pending->next)
{
/*
* Create the VacAttrStats struct.
*/
- stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
+ stats = palloc0_object(VacAttrStats);
stats->attstattarget = attstattarget;
/*
NULL);
/* Save the operator info for compute_stats routines */
- mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
+ mystats = palloc_object(StdAnalyzeData);
mystats->eqopr = eqopr;
mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
mystats->ltopr = ltopr;
/* Must copy the target values into anl_context */
old_context = MemoryContextSwitchTo(stats->anl_context);
- corrs = (float4 *) palloc(sizeof(float4));
+ corrs = palloc_object(float4);
MemoryContextSwitchTo(old_context);
/*----------
/* Use a permanent memory context for the result list */
old_context = MemoryContextSwitchTo(cluster_context);
- rtc = (RelToCluster *) palloc(sizeof(RelToCluster));
+ rtc = palloc_object(RelToCluster);
rtc->tableOid = index->indrelid;
rtc->indexOid = index->indexrelid;
rtcs = lappend(rtcs, rtc);
/* Use a permanent memory context for the result list */
old_context = MemoryContextSwitchTo(cluster_context);
- rtc = (RelToCluster *) palloc(sizeof(RelToCluster));
+ rtc = palloc_object(RelToCluster);
rtc->tableOid = relid;
rtc->indexOid = indexrelid;
rtcs = lappend(rtcs, rtc);
/* Support external use for option sanity checking */
if (opts_out == NULL)
- opts_out = (CopyFormatOptions *) palloc0(sizeof(CopyFormatOptions));
+ opts_out = palloc0_object(CopyFormatOptions);
opts_out->file_encoding = -1;
{
CopyMultiInsertBuffer *buffer;
- buffer = (CopyMultiInsertBuffer *) palloc(sizeof(CopyMultiInsertBuffer));
+ buffer = palloc_object(CopyMultiInsertBuffer);
memset(buffer->slots, 0, sizeof(TupleTableSlot *) * MAX_BUFFERED_TUPLES);
buffer->resultRelInfo = rri;
buffer->bistate = (rri->ri_FdwRoutine == NULL) ? GetBulkInsertState() : NULL;
};
/* Allocate workspace and zero all fields */
- cstate = (CopyFromStateData *) palloc0(sizeof(CopyFromStateData));
+ cstate = palloc0_object(CopyFromStateData);
/*
* We allocate everything used by a cstate in a new memory context. This
/* Allocate workspace and zero all fields */
- cstate = (CopyToStateData *) palloc0(sizeof(CopyToStateData));
+ cstate = palloc0_object(CopyToStateData);
/*
* We allocate everything used by a cstate in a new memory context. This
DestReceiver *
CreateCopyDestReceiver(void)
{
- DR_copy *self = (DR_copy *) palloc(sizeof(DR_copy));
+ DR_copy *self = palloc_object(DR_copy);
self->pub.receiveSlot = copy_dest_receive;
self->pub.rStartup = copy_dest_startup;
DestReceiver *
CreateIntoRelDestReceiver(IntoClause *intoClause)
{
- DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
+ DR_intorel *self = palloc0_object(DR_intorel);
self->pub.receiveSlot = intorel_receive;
self->pub.rStartup = intorel_startup;
classForm->oid);
/* Prepare a rel info element and add it to the list. */
- relinfo = (CreateDBRelInfo *) palloc(sizeof(CreateDBRelInfo));
+ relinfo = palloc_object(CreateDBRelInfo);
if (OidIsValid(classForm->reltablespace))
relinfo->rlocator.spcOid = classForm->reltablespace;
else
int i = 0,
l = list_length(filterlist);
- data = (Datum *) palloc(l * sizeof(Datum));
+ data = palloc_array(Datum, l);
foreach(lc, filterlist)
{
oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
- obj = palloc0(sizeof(SQLDropObject));
+ obj = palloc0_object(SQLDropObject);
obj->address = *object;
obj->original = original;
obj->normal = normal;
oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
- command = palloc(sizeof(CollectedCommand));
+ command = palloc_object(CollectedCommand);
command->type = SCT_Simple;
command->in_extension = creating_extension;
oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
- command = palloc(sizeof(CollectedCommand));
+ command = palloc_object(CollectedCommand);
command->type = SCT_AlterTable;
command->in_extension = creating_extension;
oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
- newsub = palloc(sizeof(CollectedATSubcmd));
+ newsub = palloc_object(CollectedATSubcmd);
newsub->address = address;
newsub->parsetree = copyObject(subcmd);
/*
* This is tedious, but necessary.
*/
- icopy = palloc(sizeof(InternalGrant));
+ icopy = palloc_object(InternalGrant);
memcpy(icopy, istmt, sizeof(InternalGrant));
icopy->objects = list_copy(istmt->objects);
icopy->grantees = list_copy(istmt->grantees);
icopy->col_privs = lappend(icopy->col_privs, copyObject(lfirst(cell)));
/* Now collect it, using the copied InternalGrant */
- command = palloc(sizeof(CollectedCommand));
+ command = palloc_object(CollectedCommand);
command->type = SCT_Grant;
command->in_extension = creating_extension;
command->d.grant.istmt = icopy;
oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
- command = palloc(sizeof(CollectedCommand));
+ command = palloc_object(CollectedCommand);
command->type = SCT_AlterOpFamily;
command->in_extension = creating_extension;
ObjectAddressSet(command->d.opfam.address,
oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
- command = palloc0(sizeof(CollectedCommand));
+ command = palloc0_object(CollectedCommand);
command->type = SCT_CreateOpClass;
command->in_extension = creating_extension;
ObjectAddressSet(command->d.createopc.address,
oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
- command = palloc0(sizeof(CollectedCommand));
+ command = palloc0_object(CollectedCommand);
command->type = SCT_AlterTSConfig;
command->in_extension = creating_extension;
ObjectAddressSet(command->d.atscfg.address,
TSConfigRelationId, cfgId);
- command->d.atscfg.dictIds = palloc(sizeof(Oid) * ndicts);
+ command->d.atscfg.dictIds = palloc_array(Oid, ndicts);
memcpy(command->d.atscfg.dictIds, dictIds, sizeof(Oid) * ndicts);
command->d.atscfg.ndicts = ndicts;
command->parsetree = (Node *) copyObject(stmt);
oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
- command = palloc0(sizeof(CollectedCommand));
+ command = palloc0_object(CollectedCommand);
command->type = SCT_AlterDefaultPrivileges;
command->d.defprivs.objtype = stmt->action->objtype;
command->in_extension = creating_extension;
{
ExplainWorkersState *wstate;
- wstate = (ExplainWorkersState *) palloc(sizeof(ExplainWorkersState));
+ wstate = palloc_object(ExplainWorkersState);
wstate->num_workers = num_workers;
wstate->worker_inited = (bool *) palloc0(num_workers * sizeof(bool));
wstate->worker_str = (StringInfoData *)
{
SerializeDestReceiver *self;
- self = (SerializeDestReceiver *) palloc0(sizeof(SerializeDestReceiver));
+ self = palloc0_object(SerializeDestReceiver);
self->pub.receiveSlot = serializeAnalyzeReceive;
self->pub.rStartup = serializeAnalyzeStartup;
ExplainState *
NewExplainState(void)
{
- ExplainState *es = (ExplainState *) palloc0(sizeof(ExplainState));
+ ExplainState *es = palloc0_object(ExplainState);
/* Set default options (most fields can be left as zeroes). */
es->costs = true;
int i;
i = pg_nextpower2_32(extension_id + 1);
- es->extension_state = (void **)
- repalloc0(es->extension_state,
- es->extension_state_allocated * sizeof(void *),
- i * sizeof(void *));
+ es->extension_state = repalloc0_array(es->extension_state, void *, es->extension_state_allocated, i);
es->extension_state_allocated = i;
}
/*
* Flat-copy the struct. Pointer fields share values with original.
*/
- acontrol = (ExtensionControlFile *) palloc(sizeof(ExtensionControlFile));
+ acontrol = palloc_object(ExtensionControlFile);
memcpy(acontrol, pcontrol, sizeof(ExtensionControlFile));
/*
return evi;
}
- evi = (ExtensionVersionInfo *) palloc(sizeof(ExtensionVersionInfo));
+ evi = palloc_object(ExtensionVersionInfo);
evi->name = pstrdup(versionname);
evi->reachable = NIL;
evi->installable = false;
{
SQLFunctionParseInfoPtr pinfo;
- pinfo = (SQLFunctionParseInfoPtr) palloc0(sizeof(SQLFunctionParseInfo));
+ pinfo = palloc0_object(SQLFunctionParseInfo);
pinfo->fname = funcname;
pinfo->nargs = list_length(parameterTypes);
DestReceiver *
CreateTransientRelDestReceiver(Oid transientoid)
{
- DR_transientrel *self = (DR_transientrel *) palloc0(sizeof(DR_transientrel));
+ DR_transientrel *self = palloc0_object(DR_transientrel);
self->pub.receiveSlot = transientrel_receive;
self->pub.rStartup = transientrel_startup;
* include all rows.
*/
tupdesc = matviewRel->rd_att;
- opUsedForQual = (Oid *) palloc0(sizeof(Oid) * relnatts);
+ opUsedForQual = palloc0_array(Oid, relnatts);
foundUniqueIndex = false;
indexoidlist = RelationGetIndexList(matviewRel);
#endif
/* Save the info */
- member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+ member = palloc0_object(OpFamilyMember);
member->is_func = false;
member->object = operOid;
member->number = item->number;
get_func_name(funcOid));
#endif
/* Save the info */
- member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+ member = palloc0_object(OpFamilyMember);
member->is_func = true;
member->object = funcOid;
member->number = item->number;
#endif
/* Save the info */
- member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+ member = palloc0_object(OpFamilyMember);
member->is_func = false;
member->object = operOid;
member->number = item->number;
#endif
/* Save the info */
- member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+ member = palloc0_object(OpFamilyMember);
member->is_func = true;
member->object = funcOid;
member->number = item->number;
item->number, maxOpNumber)));
processTypesSpec(item->class_args, &lefttype, &righttype);
/* Save the info */
- member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+ member = palloc0_object(OpFamilyMember);
member->is_func = false;
member->number = item->number;
member->lefttype = lefttype;
item->number, maxProcNumber)));
processTypesSpec(item->class_args, &lefttype, &righttype);
/* Save the info */
- member = (OpFamilyMember *) palloc0(sizeof(OpFamilyMember));
+ member = palloc0_object(OpFamilyMember);
member->is_func = true;
member->number = item->number;
member->lefttype = lefttype;
if (roles == NIL)
{
*num_roles = 1;
- role_oids = (Datum *) palloc(*num_roles * sizeof(Datum));
+ role_oids = palloc_array(Datum, *num_roles);
role_oids[0] = ObjectIdGetDatum(ACL_ID_PUBLIC);
return role_oids;
* Ordinarily there'd be exactly one, but we must cope with duplicate
* mentions, since CREATE/ALTER POLICY historically have allowed that.
*/
- role_oids = (Datum *) palloc(num_roles * sizeof(Datum));
+ role_oids = palloc_array(Datum, num_roles);
for (i = 0, j = 0; i < num_roles; i++)
{
if (roles[i] != roleid)
nitems = ARR_DIMS(policy_roles)[0];
- role_oids = (Datum *) palloc(nitems * sizeof(Datum));
+ role_oids = palloc_array(Datum, nitems);
for (i = 0; i < nitems; i++)
role_oids[i] = ObjectIdGetDatum(roles[i]);
*/
if (!found)
{
- oldrel = palloc(sizeof(PublicationRelInfo));
+ oldrel = palloc_object(PublicationRelInfo);
oldrel->whereClause = NULL;
oldrel->columns = NIL;
oldrel->relation = table_open(oldrelid,
continue;
}
- pub_rel = palloc(sizeof(PublicationRelInfo));
+ pub_rel = palloc_object(PublicationRelInfo);
pub_rel->relation = rel;
pub_rel->whereClause = t->whereClause;
pub_rel->columns = t->columns;
/* find_all_inheritors already got lock */
rel = table_open(childrelid, NoLock);
- pub_rel = palloc(sizeof(PublicationRelInfo));
+ pub_rel = palloc_object(PublicationRelInfo);
pub_rel->relation = rel;
/* child inherits WHERE clause from parent */
pub_rel->whereClause = t->whereClause;
MemoryContext oldcxt;
oldcxt = MemoryContextSwitchTo(TopMemoryContext);
- provider = palloc(sizeof(LabelProvider));
+ provider = palloc_object(LabelProvider);
provider->provider_name = pstrdup(provider_name);
provider->hook = hook;
label_provider_list = lappend(label_provider_list, provider);
ALLOCSET_DEFAULT_SIZES);
oldcxt = MemoryContextSwitchTo(memcxt);
- datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
+ datums = palloc_array(Datum, list_length(publist));
check_duplicates_in_publist(publist, datums);
{
char state;
XLogRecPtr statelsn;
- SubRemoveRels *remove_rel = palloc(sizeof(SubRemoveRels));
+ SubRemoveRels *remove_rel = palloc_object(SubRemoveRels);
/*
* Lock pg_subscription_rel with AccessExclusiveLock to
Assert(colDef->cooked_default == NULL);
- rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
+ rawEnt = palloc_object(RawColumnDefault);
rawEnt->attnum = attnum;
rawEnt->raw_default = colDef->raw_default;
rawEnt->generated = colDef->generated;
{
CookedConstraint *cooked;
- cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
+ cooked = palloc_object(CookedConstraint);
cooked->contype = CONSTR_DEFAULT;
cooked->conoid = InvalidOid; /* until created */
cooked->name = NULL;
* Not there, so add it. Note that we make a copy of the relation's
* existing descriptor before anything interesting can happen to it.
*/
- tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
+ tab = palloc0_object(AlteredTableInfo);
tab->relid = relid;
tab->rel = NULL; /* set later */
tab->relkind = rel->rd_rel->relkind;
{
RawColumnDefault *rawEnt;
- rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
+ rawEnt = palloc_object(RawColumnDefault);
rawEnt->attnum = attribute->attnum;
rawEnt->raw_default = copyObject(colDef->raw_default);
rawEnt->generated = colDef->generated;
defval = expression_planner(defval);
/* Add the new default to the newvals list */
- newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
+ newval = palloc0_object(NewColumnValue);
newval->attnum = attribute->attnum;
newval->expr = defval;
newval->is_generated = (colDef->generated != '\0');
/* SET DEFAULT */
RawColumnDefault *rawEnt;
- rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
+ rawEnt = palloc_object(RawColumnDefault);
rawEnt->attnum = attnum;
rawEnt->raw_default = newDefault;
rawEnt->generated = '\0';
false, false);
/* Prepare to store the new expression, in the catalogs */
- rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
+ rawEnt = palloc_object(RawColumnDefault);
rawEnt->attnum = attnum;
rawEnt->raw_default = newExpr;
rawEnt->generated = attgenerated;
/* Prepare for table rewrite */
defval = (Expr *) build_column_default(rel, attnum);
- newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
+ newval = palloc0_object(NewColumnValue);
newval->attnum = attnum;
newval->expr = expression_planner(defval);
newval->is_generated = true;
{
NewConstraint *newcon;
- newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+ newcon = palloc0_object(NewConstraint);
newcon->name = ccon->name;
newcon->contype = ccon->contype;
newcon->qual = ccon->expr;
false);
if (map)
{
- mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
+ mapped_pkattnum = palloc_array(AttrNumber, numfks);
for (int j = 0; j < numfks; j++)
mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
}
tab = ATGetQueueEntry(wqueue, rel);
- newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+ newcon = palloc0_object(NewConstraint);
newcon->name = get_constraint_name(parentConstr);
newcon->contype = CONSTR_FOREIGN;
newcon->refrelid = RelationGetRelid(pkrel);
AlteredTableInfo *tab;
NewConstraint *newcon;
- newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+ newcon = palloc0_object(NewConstraint);
newcon->name = fkconstraint->conname;
newcon->contype = CONSTR_FOREIGN;
newcon->refrelid = currcon->confrelid;
/* for now this is all we need */
fkconstraint->conname = pstrdup(NameStr(con->conname));
- newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+ newcon = palloc0_object(NewConstraint);
newcon->name = fkconstraint->conname;
newcon->contype = CONSTR_FOREIGN;
newcon->refrelid = con->confrelid;
}
/* Queue validation for phase 3 */
- newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
+ newcon = palloc0_object(NewConstraint);
newcon->name = constrName;
newcon->contype = CONSTR_CHECK;
newcon->refrelid = InvalidOid;
* Add a work queue item to make ATRewriteTable update the column
* contents.
*/
- newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
+ newval = palloc0_object(NewColumnValue);
newval->attnum = attnum;
newval->expr = (Expr *) transform;
newval->is_generated = false;
oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
- oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
+ oc = palloc_object(OnCommitItem);
oc->relid = relid;
oc->oncommit = action;
oc->creating_subid = GetCurrentSubTransactionId();
idxes = RelationGetIndexList(rel);
attachRelIdxs = RelationGetIndexList(attachrel);
- attachrelIdxRels = palloc(sizeof(Relation) * list_length(attachRelIdxs));
- attachInfos = palloc(sizeof(IndexInfo *) * list_length(attachRelIdxs));
+ attachrelIdxRels = palloc_array(Relation, list_length(attachRelIdxs));
+ attachInfos = palloc_array(IndexInfo *, list_length(attachRelIdxs));
/* Build arrays of all existing indexes and their IndexInfos */
foreach_oid(cldIdxId, attachRelIdxs)
}
/* Build trigdesc */
- trigdesc = (TriggerDesc *) palloc0(sizeof(TriggerDesc));
+ trigdesc = palloc0_object(TriggerDesc);
trigdesc->triggers = triggers;
trigdesc->numtriggers = numtrigs;
for (i = 0; i < numtrigs; i++)
if (trigdesc == NULL || trigdesc->numtriggers <= 0)
return NULL;
- newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
+ newdesc = palloc_object(TriggerDesc);
memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
oldcxt = MemoryContextSwitchTo(CurTransactionContext);
- table = (AfterTriggersTableData *) palloc0(sizeof(AfterTriggersTableData));
+ table = palloc0_object(AfterTriggersTableData);
table->relid = relid;
table->cmdType = cmdType;
qs->tables = lappend(qs->tables, table);
MemoryContextSwitchTo(oldcxt);
/* Now build the TransitionCaptureState struct, in caller's context */
- state = (TransitionCaptureState *) palloc0(sizeof(TransitionCaptureState));
+ state = palloc0_object(TransitionCaptureState);
state->tcs_delete_old_table = need_old_del;
state->tcs_update_old_table = need_old_upd;
state->tcs_update_new_table = need_new_upd;
* know that they will be used.
*/
max_slots = MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_ts_config_map);
- slot = palloc(sizeof(TupleTableSlot *) * max_slots);
+ slot = palloc_array(TupleTableSlot *, max_slots);
ScanKeyInit(&skey,
Anum_pg_ts_config_map_mapcfg,
{
if (strcmp(strVal(val), list[j].alias) == 0)
{
- TSTokenTypeItem *ts = (TSTokenTypeItem *) palloc0(sizeof(TSTokenTypeItem));
+ TSTokenTypeItem *ts = palloc0_object(TSTokenTypeItem);
ts->num = list[j].lexid;
ts->name = pstrdup(strVal(val));
* Convert list of dictionary names to array of dict OIDs
*/
ndict = list_length(stmt->dicts);
- dictIds = (Oid *) palloc(sizeof(Oid) * ndict);
+ dictIds = palloc_array(Oid, ndict);
i = 0;
foreach(c, stmt->dicts)
{
/* Allocate the slots to use and initialize them */
nslots = Min(ntoken * ndict,
MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_ts_config_map));
- slot = palloc(sizeof(TupleTableSlot *) * nslots);
+ slot = palloc_array(TupleTableSlot *, nslots);
for (i = 0; i < nslots; i++)
slot[i] = MakeSingleTupleTableSlot(RelationGetDescr(relMap),
&TTSOpsHeapTuple);
}
/* Build the RelToCheck entry with enough space for all atts */
- rtc = (RelToCheck *) palloc(sizeof(RelToCheck));
+ rtc = palloc_object(RelToCheck);
rtc->rel = rel;
rtc->natts = 0;
- rtc->atts = (int *) palloc(sizeof(int) * RelationGetNumberOfAttributes(rel));
+ rtc->atts = palloc_array(int, RelationGetNumberOfAttributes(rel));
result = lappend(result, rtc);
}
else
{
Oid objectId;
- Oid *newmembers = palloc(sizeof(Oid));
+ Oid *newmembers = palloc_object(Oid);
/*
* The values for these options can be taken directly from 'popt'.
if (memlist->n_members == 0)
return NULL;
- result = palloc(sizeof(RevokeRoleGrantAction) * memlist->n_members);
+ result = palloc_array(RevokeRoleGrantAction, memlist->n_members);
for (i = 0; i < memlist->n_members; i++)
result[i] = RRG_NOOP;
return result;
/*
* Compute the number of parallel vacuum workers to launch
*/
- will_parallel_vacuum = (bool *) palloc0(sizeof(bool) * nindexes);
+ will_parallel_vacuum = palloc0_array(bool, nindexes);
parallel_workers = parallel_vacuum_compute_workers(indrels, nindexes,
nrequested_workers,
will_parallel_vacuum);
return NULL;
}
- pvs = (ParallelVacuumState *) palloc0(sizeof(ParallelVacuumState));
+ pvs = palloc0_object(ParallelVacuumState);
pvs->indrels = indrels;
pvs->nindexes = nindexes;
pvs->will_parallel_vacuum = will_parallel_vacuum;
if (indstats->istat_updated)
{
- istats[i] = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
+ istats[i] = palloc0_object(IndexBulkDeleteResult);
memcpy(istats[i], &indstats->istat, sizeof(IndexBulkDeleteResult));
}
else
}
/* Set up the primary fmgr lookup information */
- finfo = palloc0(sizeof(FmgrInfo));
+ finfo = palloc0_object(FmgrInfo);
fcinfo = palloc0(SizeForFunctionCallInfo(2));
fmgr_info(cmpfuncid, finfo);
fmgr_info_set_expr((Node *) node, finfo);
/* allocate scratch memory used by all steps of AND/OR */
if (boolexpr->boolop != NOT_EXPR)
- scratch.d.boolexpr.anynull = (bool *) palloc(sizeof(bool));
+ scratch.d.boolexpr.anynull = palloc_object(bool);
/*
* For each argument evaluate the argument itself, then
ReleaseTupleDesc(tupDesc);
/* create workspace for column values */
- values = (Datum *) palloc(sizeof(Datum) * ncolumns);
- nulls = (bool *) palloc(sizeof(bool) * ncolumns);
+ values = palloc_array(Datum, ncolumns);
+ nulls = palloc_array(bool, ncolumns);
/* create shared composite-type-lookup cache struct */
- rowcachep = palloc(sizeof(ExprEvalRowtypeCache));
+ rowcachep = palloc_object(ExprEvalRowtypeCache);
rowcachep->cacheptr = NULL;
/* emit code to evaluate the composite input value */
scratch.opcode = EEOP_IOCOERCE_SAFE;
/* lookup the source type's output function */
- scratch.d.iocoerce.finfo_out = palloc0(sizeof(FmgrInfo));
+ scratch.d.iocoerce.finfo_out = palloc0_object(FmgrInfo);
scratch.d.iocoerce.fcinfo_data_out = palloc0(SizeForFunctionCallInfo(1));
getTypeOutputInfo(exprType((Node *) iocoerce->arg),
1, InvalidOid, NULL, NULL);
/* lookup the result type's input function */
- scratch.d.iocoerce.finfo_in = palloc0(sizeof(FmgrInfo));
+ scratch.d.iocoerce.finfo_in = palloc0_object(FmgrInfo);
scratch.d.iocoerce.fcinfo_data_in = palloc0(SizeForFunctionCallInfo(3));
getTypeInputInfo(iocoerce->resulttype,
elemstate->parent = state->parent;
elemstate->ext_params = state->ext_params;
- elemstate->innermost_caseval = (Datum *) palloc(sizeof(Datum));
- elemstate->innermost_casenull = (bool *) palloc(sizeof(bool));
+ elemstate->innermost_caseval = palloc_object(Datum);
+ elemstate->innermost_casenull = palloc_object(bool);
ExecInitExprRec(acoerce->elemexpr, elemstate,
&elemstate->resvalue, &elemstate->resnull);
if (elemstate)
{
/* Set up workspace for array_map */
- scratch.d.arraycoerce.amstate =
- (ArrayMapState *) palloc0(sizeof(ArrayMapState));
+ scratch.d.arraycoerce.amstate = palloc0_object(ArrayMapState);
}
else
{
if (caseExpr->arg != NULL)
{
/* Evaluate testexpr into caseval/casenull workspace */
- caseval = palloc(sizeof(Datum));
- casenull = palloc(sizeof(bool));
+ caseval = palloc_object(Datum);
+ casenull = palloc_object(bool);
ExecInitExprRec(caseExpr->arg, state,
caseval, casenull);
*/
scratch.opcode = EEOP_ARRAYEXPR;
scratch.d.arrayexpr.elemvalues =
- (Datum *) palloc(sizeof(Datum) * nelems);
+ palloc_array(Datum, nelems);
scratch.d.arrayexpr.elemnulls =
- (bool *) palloc(sizeof(bool) * nelems);
+ palloc_array(bool, nelems);
scratch.d.arrayexpr.nelems = nelems;
/* fill remaining fields of step */
/* space for the individual field datums */
scratch.d.row.elemvalues =
- (Datum *) palloc(sizeof(Datum) * nelems);
+ palloc_array(Datum, nelems);
scratch.d.row.elemnulls =
- (bool *) palloc(sizeof(bool) * nelems);
+ palloc_array(bool, nelems);
/* as explained above, make sure any extra columns are null */
memset(scratch.d.row.elemnulls, true, sizeof(bool) * nelems);
BTORDER_PROC, lefttype, righttype, opfamily);
/* Set up the primary fmgr lookup information */
- finfo = palloc0(sizeof(FmgrInfo));
+ finfo = palloc0_object(FmgrInfo);
fcinfo = palloc0(SizeForFunctionCallInfo(2));
fmgr_info(proc, finfo);
fmgr_info_set_expr((Node *) node, finfo);
*/
/* Perform function lookup */
- finfo = palloc0(sizeof(FmgrInfo));
+ finfo = palloc0_object(FmgrInfo);
fcinfo = palloc0(SizeForFunctionCallInfo(2));
fmgr_info(typentry->cmp_proc, finfo);
fmgr_info_set_expr((Node *) node, finfo);
scratch.opcode = EEOP_MINMAX;
/* allocate space to store arguments */
- scratch.d.minmax.values =
- (Datum *) palloc(sizeof(Datum) * nelems);
- scratch.d.minmax.nulls =
- (bool *) palloc(sizeof(bool) * nelems);
+ scratch.d.minmax.values = palloc_array(Datum, nelems);
+ scratch.d.minmax.nulls = palloc_array(bool, nelems);
scratch.d.minmax.nelems = nelems;
scratch.d.minmax.op = minmaxexpr->op;
/* allocate space for storing all the arguments */
if (nnamed)
{
- scratch.d.xmlexpr.named_argvalue =
- (Datum *) palloc(sizeof(Datum) * nnamed);
- scratch.d.xmlexpr.named_argnull =
- (bool *) palloc(sizeof(bool) * nnamed);
+ scratch.d.xmlexpr.named_argvalue = palloc_array(Datum, nnamed);
+ scratch.d.xmlexpr.named_argnull = palloc_array(bool, nnamed);
}
else
{
if (nargs)
{
- scratch.d.xmlexpr.argvalue =
- (Datum *) palloc(sizeof(Datum) * nargs);
- scratch.d.xmlexpr.argnull =
- (bool *) palloc(sizeof(bool) * nargs);
+ scratch.d.xmlexpr.argvalue = palloc_array(Datum, nargs);
+ scratch.d.xmlexpr.argnull = palloc_array(bool, nargs);
}
else
{
{
JsonConstructorExprState *jcstate;
- jcstate = palloc0(sizeof(JsonConstructorExprState));
+ jcstate = palloc0_object(JsonConstructorExprState);
scratch.opcode = EEOP_JSON_CONSTRUCTOR;
scratch.d.json_constructor.jcstate = jcstate;
jcstate->constructor = ctor;
- jcstate->arg_values = (Datum *) palloc(sizeof(Datum) * nargs);
- jcstate->arg_nulls = (bool *) palloc(sizeof(bool) * nargs);
- jcstate->arg_types = (Oid *) palloc(sizeof(Oid) * nargs);
+ jcstate->arg_values = palloc_array(Datum, nargs);
+ jcstate->arg_nulls = palloc_array(bool, nargs);
+ jcstate->arg_types = palloc_array(Oid, nargs);
jcstate->nargs = nargs;
foreach(lc, args)
if (es->steps_alloc == 0)
{
es->steps_alloc = 16;
- es->steps = palloc(sizeof(ExprEvalStep) * es->steps_alloc);
+ es->steps = palloc_array(ExprEvalStep, es->steps_alloc);
}
else if (es->steps_alloc == es->steps_len)
{
FUNC_MAX_ARGS)));
/* Allocate function lookup data and parameter workspace for this call */
- scratch->d.func.finfo = palloc0(sizeof(FmgrInfo));
+ scratch->d.func.finfo = palloc0_object(FmgrInfo);
scratch->d.func.fcinfo_data = palloc0(SizeForFunctionCallInfo(nargs));
flinfo = scratch->d.func.finfo;
fcinfo = scratch->d.func.fcinfo_data;
* during executor initialization. That means we don't need typcache.c to
* provide compiled exprs.
*/
- constraint_ref = (DomainConstraintRef *)
- palloc(sizeof(DomainConstraintRef));
+ constraint_ref = palloc_object(DomainConstraintRef);
InitDomainConstraintRef(ctest->resulttype,
constraint_ref,
CurrentMemoryContext,
if (scratch->d.domaincheck.checkvalue == NULL)
{
scratch->d.domaincheck.checkvalue =
- (Datum *) palloc(sizeof(Datum));
+ palloc_object(Datum);
scratch->d.domaincheck.checknull =
- (bool *) palloc(sizeof(bool));
+ palloc_object(bool);
}
/*
ExprEvalStep scratch2 = {0};
/* Yes, so make output workspace for MAKE_READONLY */
- domainval = (Datum *) palloc(sizeof(Datum));
- domainnull = (bool *) palloc(sizeof(bool));
+ domainval = palloc_object(Datum);
+ domainnull = palloc_object(bool);
/* Emit MAKE_READONLY */
scratch2.opcode = EEOP_MAKE_READONLY;
* one column to hash or an initial value plus one column.
*/
if ((int64) numCols + (init_value != 0) > 1)
- iresult = palloc(sizeof(NullableDatum));
+ iresult = palloc_object(NullableDatum);
/* find the highest attnum so we deform the tuple to that point */
for (int i = 0; i < numCols; i++)
* than one expression to hash or an initial value plus one expression.
*/
if ((int64) num_exprs + (init_value != 0) > 1)
- iresult = palloc(sizeof(NullableDatum));
+ iresult = palloc_object(NullableDatum);
if (init_value == 0)
{
funcid = hashfunc_oids[i];
/* Allocate hash function lookup data. */
- finfo = palloc0(sizeof(FmgrInfo));
+ finfo = palloc0_object(FmgrInfo);
fcinfo = palloc0(SizeForFunctionCallInfo(1));
fmgr_info(funcid, finfo);
InvokeFunctionExecuteHook(foid);
/* Set up the primary fmgr lookup information */
- finfo = palloc0(sizeof(FmgrInfo));
+ finfo = palloc0_object(FmgrInfo);
fcinfo = palloc0(SizeForFunctionCallInfo(2));
fmgr_info(foid, finfo);
fmgr_info_set_expr(NULL, finfo);
InvokeFunctionExecuteHook(foid);
/* Set up the primary fmgr lookup information */
- finfo = palloc0(sizeof(FmgrInfo));
+ finfo = palloc0_object(FmgrInfo);
fcinfo = palloc0(SizeForFunctionCallInfo(2));
fmgr_info(foid, finfo);
fmgr_info_set_expr(NULL, finfo);
Datum *resv, bool *resnull,
ExprEvalStep *scratch)
{
- JsonExprState *jsestate = palloc0(sizeof(JsonExprState));
+ JsonExprState *jsestate = palloc0_object(JsonExprState);
ListCell *argexprlc;
ListCell *argnamelc;
List *jumps_return_null = NIL;
{
Expr *argexpr = (Expr *) lfirst(argexprlc);
String *argname = lfirst_node(String, argnamelc);
- JsonPathVariable *var = palloc(sizeof(*var));
+ JsonPathVariable *var = palloc_object(JsonPathVariable);
var->name = argname->sval;
var->namelen = strlen(var->name);
FunctionCallInfo fcinfo;
getTypeInputInfo(jsexpr->returning->typid, &typinput, &typioparam);
- finfo = palloc0(sizeof(FmgrInfo));
+ finfo = palloc0_object(FmgrInfo);
fcinfo = palloc0(SizeForFunctionCallInfo(3));
fmgr_info(typinput, finfo);
fmgr_info_set_expr((Node *) jsexpr->returning, finfo);
oldcontext = MemoryContextSwitchTo(metacxt);
- hashtable = (TupleHashTable) palloc(sizeof(TupleHashTableData));
+ hashtable = palloc_object(TupleHashTableData);
hashtable->numCols = numCols;
hashtable->keyColIdx = keyColIdx;
/*
* allocate space for result arrays
*/
- relationDescs = (RelationPtr) palloc(len * sizeof(Relation));
- indexInfoArray = (IndexInfo **) palloc(len * sizeof(IndexInfo *));
+ relationDescs = palloc_array(Relation, len);
+ indexInfoArray = palloc_array(IndexInfo *, len);
resultRelInfo->ri_NumIndices = len;
resultRelInfo->ri_IndexRelationDescs = relationDescs;
nParamExec = list_length(queryDesc->plannedstmt->paramExecTypes);
estate->es_param_exec_vals = (ParamExecData *)
- palloc0(nParamExec * sizeof(ParamExecData));
+ palloc0_array(ParamExecData, nParamExec);
}
/* We now require all callers to provide sourceText */
if (plannedstmt->rowMarks)
{
estate->es_rowmarks = (ExecRowMark **)
- palloc0(estate->es_range_table_size * sizeof(ExecRowMark *));
+ palloc0_array(ExecRowMark *, estate->es_range_table_size);
foreach(l, plannedstmt->rowMarks)
{
PlanRowMark *rc = (PlanRowMark *) lfirst(l);
if (relation)
CheckValidRowMarkRel(relation, rc->markType);
- erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
+ erm = palloc_object(ExecRowMark);
erm->relation = relation;
erm->relid = relid;
erm->rti = rc->rti;
int n = resultRelInfo->ri_TrigDesc->numtriggers;
resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
- palloc0(n * sizeof(FmgrInfo));
+ palloc0_array(FmgrInfo, n);
resultRelInfo->ri_TrigWhenExprs = (ExprState **)
- palloc0(n * sizeof(ExprState *));
+ palloc0_array(ExprState *, n);
if (instrument_options)
resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
}
ExecAuxRowMark *
ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
{
- ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
+ ExecAuxRowMark *aerm = palloc0_object(ExecAuxRowMark);
char resname[32];
aerm->rowmark = erm;
* EvalPlanQualBegin().
*/
epqstate->tuple_table = NIL;
- epqstate->relsubs_slot = (TupleTableSlot **)
- palloc0(rtsize * sizeof(TupleTableSlot *));
+ epqstate->relsubs_slot = palloc0_array(TupleTableSlot *, rtsize);
/* ... and remember data that EvalPlanQualBegin will need */
epqstate->plan = subplan;
/* now make the internal param workspace ... */
i = list_length(parentestate->es_plannedstmt->paramExecTypes);
- rcestate->es_param_exec_vals = (ParamExecData *)
- palloc0(i * sizeof(ParamExecData));
+ rcestate->es_param_exec_vals = palloc0_array(ParamExecData, i);
/* ... and copy down all values, whether really needed or not */
while (--i >= 0)
{
* EvalPlanQualFetchRowMark() can efficiently access the to be fetched
* rowmark.
*/
- epqstate->relsubs_rowmark = (ExecAuxRowMark **)
- palloc0(rtsize * sizeof(ExecAuxRowMark *));
+ epqstate->relsubs_rowmark = palloc0_array(ExecAuxRowMark *, rtsize);
foreach(l, epqstate->arowMarks)
{
ExecAuxRowMark *earm = (ExecAuxRowMark *) lfirst(l);
ExecSetParamPlanMulti(sendParams, GetPerTupleExprContext(estate));
/* Allocate object for return value. */
- pei = palloc0(sizeof(ParallelExecutorInfo));
+ pei = palloc0_object(ParallelExecutorInfo);
pei->finished = false;
pei->planstate = planstate;
if (!isIdxSafeToSkipDuplicates)
{
if (eq == NULL)
- eq = palloc0(sizeof(*eq) * outslot->tts_tupleDescriptor->natts);
+ eq = palloc0_array(TypeCacheEntry *, outslot->tts_tupleDescriptor->natts);
if (!tuples_equal(outslot, searchslot, eq, NULL))
continue;
Assert(equalTupleDescs(desc, outslot->tts_tupleDescriptor));
- eq = palloc0(sizeof(*eq) * outslot->tts_tupleDescriptor->natts);
+ eq = palloc0_array(TypeCacheEntry *, outslot->tts_tupleDescriptor->natts);
/* Start a heap scan. */
InitDirtySnapshot(snap);
indexbitmap = RelationGetIndexAttrBitmap(rel,
INDEX_ATTR_BITMAP_PRIMARY_KEY);
- eq = palloc0(sizeof(*eq) * searchslot->tts_tupleDescriptor->natts);
+ eq = palloc0_array(TypeCacheEntry *, searchslot->tts_tupleDescriptor->natts);
/*
* Start a heap scan using SnapshotAny to identify dead tuples that are
if (!isIdxSafeToSkipDuplicates)
{
if (eq == NULL)
- eq = palloc0(sizeof(*eq) * scanslot->tts_tupleDescriptor->natts);
+ eq = palloc0_array(TypeCacheEntry *, scanslot->tts_tupleDescriptor->natts);
if (!tuples_equal(scanslot, searchslot, eq, NULL))
continue;
int32 *atttypmods;
AttInMetadata *attinmeta;
- attinmeta = (AttInMetadata *) palloc(sizeof(AttInMetadata));
+ attinmeta = palloc_object(AttInMetadata);
/* "Bless" the tupledesc so that we can make rowtype datums with it */
attinmeta->tupdesc = BlessTupleDesc(tupdesc);
{
TupOutputState *tstate;
- tstate = (TupOutputState *) palloc(sizeof(TupOutputState));
+ tstate = palloc_object(TupOutputState);
tstate->slot = MakeSingleTupleTableSlot(tupdesc, tts_ops);
tstate->dest = dest;
Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
int nargs;
- pinfo = (SQLFunctionParseInfoPtr) palloc0(sizeof(SQLFunctionParseInfo));
+ pinfo = (SQLFunctionParseInfoPtr) palloc0_object(SQLFunctionParseInfo);
/* Function's name (only) can be used to qualify argument names */
pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
DestReceiver *
CreateSQLFunctionDestReceiver(void)
{
- DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
+ DR_sqlfunction *self = palloc0_object(DR_sqlfunction);
self->pub.receiveSlot = sqlfunction_receive;
self->pub.rStartup = sqlfunction_startup;
aggstate->hash_tapeset = LogicalTapeSetCreate(true, NULL, -1);
- aggstate->hash_spills = palloc(sizeof(HashAggSpill) * aggstate->num_hashes);
+ aggstate->hash_spills = palloc_array(HashAggSpill, aggstate->num_hashes);
for (int setno = 0; setno < aggstate->num_hashes; setno++)
{
}
#endif
- spill->partitions = palloc0(sizeof(LogicalTape *) * npartitions);
- spill->ntuples = palloc0(sizeof(int64) * npartitions);
- spill->hll_card = palloc0(sizeof(hyperLogLogState) * npartitions);
+ spill->partitions = palloc0_array(LogicalTape *, npartitions);
+ spill->ntuples = palloc0_array(int64, npartitions);
+ spill->hll_card = palloc0_array(hyperLogLogState, npartitions);
for (int i = 0; i < npartitions; i++)
spill->partitions[i] = LogicalTapeCreate(tapeset);
hashagg_batch_new(LogicalTape *input_tape, int setno,
int64 input_tuples, double input_card, int used_bits)
{
- HashAggBatch *batch = palloc0(sizeof(HashAggBatch));
+ HashAggBatch *batch = palloc0_object(HashAggBatch);
batch->setno = setno;
batch->used_bits = used_bits;
aggstate->maxsets = numGroupingSets;
aggstate->numphases = numPhases;
- aggstate->aggcontexts = (ExprContext **)
- palloc0(sizeof(ExprContext *) * numGroupingSets);
+ aggstate->aggcontexts = palloc0_array(ExprContext *, numGroupingSets);
/*
* Create expression contexts. We need three or more, one for
* For each phase, prepare grouping set data and fmgr lookup data for
* compare functions. Accumulate all_grouped_cols in passing.
*/
- aggstate->phases = palloc0(numPhases * sizeof(AggStatePerPhaseData));
+ aggstate->phases = palloc0_array(AggStatePerPhaseData, numPhases);
aggstate->num_hashes = numHashes;
if (numHashes)
{
- aggstate->perhash = palloc0(sizeof(AggStatePerHashData) * numHashes);
+ aggstate->perhash = palloc0_array(AggStatePerHashData, numHashes);
aggstate->phases[0].numsets = 0;
- aggstate->phases[0].gset_lengths = palloc(numHashes * sizeof(int));
- aggstate->phases[0].grouped_cols = palloc(numHashes * sizeof(Bitmapset *));
+ aggstate->phases[0].gset_lengths = palloc_array(int, numHashes);
+ aggstate->phases[0].grouped_cols = palloc_array(Bitmapset *, numHashes);
}
phase = 0;
* Build a separate function for each subset of columns that
* need to be compared.
*/
- phasedata->eqfunctions =
- (ExprState **) palloc0(aggnode->numCols * sizeof(ExprState *));
+ phasedata->eqfunctions = palloc0_array(ExprState *, aggnode->numCols);
/* for each grouping set */
for (int k = 0; k < phasedata->numsets; k++)
* allocate my private per-agg working storage
*/
econtext = aggstate->ss.ps.ps_ExprContext;
- econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numaggs);
- econtext->ecxt_aggnulls = (bool *) palloc0(sizeof(bool) * numaggs);
+ econtext->ecxt_aggvalues = palloc0_array(Datum, numaggs);
+ econtext->ecxt_aggnulls = palloc0_array(bool, numaggs);
- peraggs = (AggStatePerAgg) palloc0(sizeof(AggStatePerAggData) * numaggs);
- pertransstates = (AggStatePerTrans) palloc0(sizeof(AggStatePerTransData) * numtrans);
+ peraggs = palloc0_array(AggStatePerAggData, numaggs);
+ pertransstates = palloc0_array(AggStatePerTransData, numtrans);
aggstate->peragg = peraggs;
aggstate->pertrans = pertransstates;
- aggstate->all_pergroups =
- (AggStatePerGroup *) palloc0(sizeof(AggStatePerGroup)
- * (numGroupingSets + numHashes));
+ aggstate->all_pergroups = palloc0_array(AggStatePerGroup, numGroupingSets + numHashes);
pergroups = aggstate->all_pergroups;
if (node->aggstrategy != AGG_HASHED)
{
for (i = 0; i < numGroupingSets; i++)
{
- pergroups[i] = (AggStatePerGroup) palloc0(sizeof(AggStatePerGroupData)
- * numaggs);
+ pergroups[i] = palloc0_array(AggStatePerGroupData, numaggs);
}
aggstate->pergroups = pergroups;
pfree(ops);
}
- pertrans->sortstates = (Tuplesortstate **)
- palloc0(sizeof(Tuplesortstate *) * numGroupingSets);
+ pertrans->sortstates = palloc0_array(Tuplesortstate *, numGroupingSets);
}
{
AsyncRequest *areq;
- areq = palloc(sizeof(AsyncRequest));
+ areq = palloc_object(AsyncRequest);
areq->requestor = (PlanState *) appendstate;
areq->requestee = appendplanstates[i];
areq->request_index = i;
*/
ExecAssignExprContext(estate, &scanstate->ss.ps);
- scanstate->funcstates = palloc(nfuncs * sizeof(FunctionScanPerFuncState));
+ scanstate->funcstates = palloc_array(FunctionScanPerFuncState, nfuncs);
natts = 0;
i = 0;
int i;
gm_state->gm_nkeys = node->numCols;
- gm_state->gm_sortkeys =
- palloc0(sizeof(SortSupportData) * node->numCols);
+ gm_state->gm_sortkeys = palloc0_array(SortSupportData, node->numCols);
for (i = 0; i < node->numCols; i++)
{
for (i = 0; i < nreaders; i++)
{
/* Allocate the tuple array with length MAX_TUPLE_STORE */
- gm_state->gm_tuple_buffers[i].tuple =
- (MinimalTuple *) palloc0(sizeof(MinimalTuple) * MAX_TUPLE_STORE);
+ gm_state->gm_tuple_buffers[i].tuple = palloc0_array(MinimalTuple, MAX_TUPLE_STORE);
/* Initialize tuple slot for worker */
gm_state->gm_slots[i + 1] =
*/
if (OidIsValid(hash->skewTable))
{
- hashstate->skew_hashfunction = palloc0(sizeof(FmgrInfo));
+ hashstate->skew_hashfunction = palloc0_object(FmgrInfo);
hashstate->skew_collation = linitial_oid(node->hashcollations);
fmgr_info(outer_hashfuncid[0], hashstate->skew_hashfunction);
}
/* accumulate stats from old hash table, if wanted */
/* (this should match ExecShutdownHash) */
if (hashNode->ps.instrument && !hashNode->hinstrument)
- hashNode->hinstrument = (HashInstrumentation *)
- palloc0(sizeof(HashInstrumentation));
+ hashNode->hinstrument = palloc0_object(HashInstrumentation);
if (hashNode->hinstrument)
ExecHashAccumInstrumentation(hashNode->hinstrument,
hashNode->hashtable);
* Now create an array to mark the attribute numbers of the keys that
* need to be converted from cstring to name.
*/
- indexstate->ioss_NameCStringAttNums = (AttrNumber *)
- palloc(sizeof(AttrNumber) * namecount);
+ indexstate->ioss_NameCStringAttNums = palloc_array(AttrNumber, namecount);
for (int attnum = 0; attnum < indnkeyatts; attnum++)
{
ReorderTuple *rt;
int i;
- rt = (ReorderTuple *) palloc(sizeof(ReorderTuple));
+ rt = palloc_object(ReorderTuple);
rt->htup = ExecCopySlotHeapTuple(slot);
- rt->orderbyvals =
- (Datum *) palloc(sizeof(Datum) * scandesc->numberOfOrderBys);
- rt->orderbynulls =
- (bool *) palloc(sizeof(bool) * scandesc->numberOfOrderBys);
+ rt->orderbyvals = palloc_array(Datum, scandesc->numberOfOrderBys);
+ rt->orderbynulls = palloc_array(bool, scandesc->numberOfOrderBys);
for (i = 0; i < node->iss_NumOrderByKeys; i++)
{
if (!orderbynulls[i])
oldcontext = MemoryContextSwitchTo(mstate->tableContext);
/* Allocate a new key */
- entry->key = key = (MemoizeKey *) palloc(sizeof(MemoizeKey));
+ entry->key = key = palloc_object(MemoizeKey);
key->params = ExecCopySlotMinimalTuple(mstate->probeslot);
/* Update the total cache memory utilization */
oldcontext = MemoryContextSwitchTo(mstate->tableContext);
- tuple = (MemoizeTuple *) palloc(sizeof(MemoizeTuple));
+ tuple = palloc_object(MemoizeTuple);
tuple->mintuple = ExecCopySlotMinimalTuple(slot);
tuple->next = NULL;
mergestate->ms_prune_state = NULL;
}
- mergeplanstates = (PlanState **) palloc(nplans * sizeof(PlanState *));
+ mergeplanstates = palloc_array(PlanState *, nplans);
mergestate->mergeplans = mergeplanstates;
mergestate->ms_nplans = nplans;
- mergestate->ms_slots = (TupleTableSlot **) palloc0(sizeof(TupleTableSlot *) * nplans);
+ mergestate->ms_slots = palloc0_array(TupleTableSlot *, nplans);
mergestate->ms_heap = binaryheap_allocate(nplans, heap_compare_slots,
mergestate);
* initialize sort-key information
*/
mergestate->ms_nkeys = node->numCols;
- mergestate->ms_sortkeys = palloc0(sizeof(SortSupportData) * node->numCols);
+ mergestate->ms_sortkeys = palloc0_array(SortSupportData, node->numCols);
for (i = 0; i < node->numCols; i++)
{
oldContext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
- values = palloc(sizeof(*values) * natts);
- nulls = palloc(sizeof(*nulls) * natts);
+ values = palloc_array(Datum, natts);
+ nulls = palloc_array(bool, natts);
slot_getallattrs(slot);
memcpy(nulls, slot->tts_isnull, sizeof(*nulls) * natts);
if (resultRelInfo->ri_Slots == NULL)
{
- resultRelInfo->ri_Slots = palloc(sizeof(TupleTableSlot *) *
- resultRelInfo->ri_BatchSize);
- resultRelInfo->ri_PlanSlots = palloc(sizeof(TupleTableSlot *) *
- resultRelInfo->ri_BatchSize);
+ resultRelInfo->ri_Slots = palloc_array(TupleTableSlot *, resultRelInfo->ri_BatchSize);
+ resultRelInfo->ri_PlanSlots = palloc_array(TupleTableSlot *, resultRelInfo->ri_BatchSize);
}
/*
mtstate->mt_done = false;
mtstate->mt_nrels = nrels;
- mtstate->resultRelInfo = (ResultRelInfo *)
- palloc(nrels * sizeof(ResultRelInfo));
+ mtstate->resultRelInfo = palloc_array(ResultRelInfo, nrels);
mtstate->mt_merge_pending_not_matched = NULL;
mtstate->mt_merge_inserted = 0;
/* Create workspace for per-tlist-entry expr state & SRF-is-done state */
state->nelems = list_length(node->plan.targetlist);
- state->elems = (Node **)
- palloc(sizeof(Node *) * state->nelems);
- state->elemdone = (ExprDoneCond *)
- palloc(sizeof(ExprDoneCond) * state->nelems);
+ state->elems = palloc_array(Node *, state->nelems);
+ state->elemdone = palloc_array(ExprDoneCond, state->nelems);
/*
* Build expressions to evaluate targetlist. We can't use
ListCell *arg;
scanstate->donetuples = 0;
- params = (Datum *) palloc(list_length(scanstate->args) * sizeof(Datum));
+ params = palloc_array(Datum, list_length(scanstate->args));
i = 0;
foreach(arg, scanstate->args)
scanstate->notnulls = tf->notnulls;
/* these are allocated now and initialized later */
- scanstate->in_functions = palloc(sizeof(FmgrInfo) * tupdesc->natts);
- scanstate->typioparams = palloc(sizeof(Oid) * tupdesc->natts);
+ scanstate->in_functions = palloc_array(FmgrInfo, tupdesc->natts);
+ scanstate->typioparams = palloc_array(Oid, tupdesc->natts);
/*
* Fill in the necessary fmgr infos.
else
elog(ERROR, "could not identify CTID variable");
- tidopexpr = (TidOpExpr *) palloc(sizeof(TidOpExpr));
+ tidopexpr = palloc_object(TidOpExpr);
tidopexpr->inclusive = false; /* for now */
switch (expr->opno)
foreach(l, node->tidquals)
{
Expr *expr = (Expr *) lfirst(l);
- TidExpr *tidexpr = (TidExpr *) palloc0(sizeof(TidExpr));
+ TidExpr *tidexpr = palloc0_object(TidExpr);
if (is_opclause(expr))
{
numfuncs = winstate->numfuncs;
numaggs = winstate->numaggs;
econtext = winstate->ss.ps.ps_ExprContext;
- econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numfuncs);
- econtext->ecxt_aggnulls = (bool *) palloc0(sizeof(bool) * numfuncs);
+ econtext->ecxt_aggvalues = palloc0_array(Datum, numfuncs);
+ econtext->ecxt_aggnulls = palloc0_array(bool, numfuncs);
/*
* allocate per-wfunc/per-agg state information.
*/
- perfunc = (WindowStatePerFunc) palloc0(sizeof(WindowStatePerFuncData) * numfuncs);
- peragg = (WindowStatePerAgg) palloc0(sizeof(WindowStatePerAggData) * numaggs);
+ perfunc = palloc0_array(WindowStatePerFuncData, numfuncs);
+ peragg = palloc0_array(WindowStatePerAggData, numaggs);
winstate->perfunc = perfunc;
winstate->peragg = peragg;
if (winobj->ignore_nulls == PARSER_IGNORE_NULLS)
{
- winobj->notnull_info = palloc0(sizeof(uint8 *) * numargs);
- winobj->num_notnull_info = palloc0(sizeof(int64) * numargs);
+ winobj->notnull_info = palloc0_array(uint8 *, numargs);
+ winobj->num_notnull_info = palloc0_array(int64, numargs);
}
}
SPI_result = 0;
numberOfAttributes = rel->rd_att->natts;
- v = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
- n = (bool *) palloc(numberOfAttributes * sizeof(bool));
+ v = palloc_array(Datum, numberOfAttributes);
+ n = palloc_array(bool, numberOfAttributes);
/* fetch old values and nulls */
heap_deform_tuple(tuple, rel->rd_att, v, n);
ALLOCSET_DEFAULT_SIZES);
MemoryContextSwitchTo(tuptabcxt);
- _SPI_current->tuptable = tuptable = (SPITupleTable *)
- palloc0(sizeof(SPITupleTable));
+ _SPI_current->tuptable = tuptable = palloc0_object(SPITupleTable);
tuptable->tuptabcxt = tuptabcxt;
tuptable->subid = GetCurrentSubTransactionId();
/* set up initial allocations */
tuptable->alloced = 128;
- tuptable->vals = (HeapTuple *) palloc(tuptable->alloced * sizeof(HeapTuple));
+ tuptable->vals = palloc_array(HeapTuple, tuptable->alloced);
tuptable->numvals = 0;
tuptable->tupdesc = CreateTupleDescCopy(typeinfo);
oldcxt = MemoryContextSwitchTo(plancxt);
/* Copy the _SPI_plan struct and subsidiary data into the new context */
- newplan = (SPIPlanPtr) palloc0(sizeof(_SPI_plan));
+ newplan = palloc0_object(_SPI_plan);
newplan->magic = _SPI_PLAN_MAGIC;
newplan->plancxt = plancxt;
newplan->parse_mode = plan->parse_mode;
newplan->nargs = plan->nargs;
if (plan->nargs > 0)
{
- newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
+ newplan->argtypes = palloc_array(Oid, plan->nargs);
memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
}
else
oldcxt = MemoryContextSwitchTo(plancxt);
/* Copy the SPI plan into its own context */
- newplan = (SPIPlanPtr) palloc0(sizeof(_SPI_plan));
+ newplan = palloc0_object(_SPI_plan);
newplan->magic = _SPI_PLAN_MAGIC;
newplan->plancxt = plancxt;
newplan->parse_mode = plan->parse_mode;
newplan->nargs = plan->nargs;
if (plan->nargs > 0)
{
- newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
+ newplan->argtypes = palloc_array(Oid, plan->nargs);
memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
}
else
if (tdata->tg_newtable)
{
EphemeralNamedRelation enr =
- palloc(sizeof(EphemeralNamedRelationData));
+ palloc_object(EphemeralNamedRelationData);
int rc;
enr->md.name = tdata->tg_trigger->tgnewtable;
if (tdata->tg_oldtable)
{
EphemeralNamedRelation enr =
- palloc(sizeof(EphemeralNamedRelationData));
+ palloc_object(EphemeralNamedRelationData);
int rc;
enr->md.name = tdata->tg_trigger->tgoldtable;
{
TQueueDestReceiver *self;
- self = (TQueueDestReceiver *) palloc0(sizeof(TQueueDestReceiver));
+ self = palloc0_object(TQueueDestReceiver);
self->pub.receiveSlot = tqueueReceiveSlot;
self->pub.rStartup = tqueueStartupReceiver;
TupleQueueReader *
CreateTupleQueueReader(shm_mq_handle *handle)
{
- TupleQueueReader *reader = palloc0(sizeof(TupleQueueReader));
+ TupleQueueReader *reader = palloc0_object(TupleQueueReader);
reader->queue = handle;
DestReceiver *
CreateTuplestoreDestReceiver(void)
{
- TStoreState *self = (TStoreState *) palloc0(sizeof(TStoreState));
+ TStoreState *self = palloc0_object(TStoreState);
self->pub.receiveSlot = tstoreReceiveSlot_notoast; /* might change */
self->pub.rStartup = tstoreStartupReceiver;
fdwform = (Form_pg_foreign_data_wrapper) GETSTRUCT(tp);
- fdw = (ForeignDataWrapper *) palloc(sizeof(ForeignDataWrapper));
+ fdw = palloc_object(ForeignDataWrapper);
fdw->fdwid = fdwid;
fdw->owner = fdwform->fdwowner;
fdw->fdwname = pstrdup(NameStr(fdwform->fdwname));
serverform = (Form_pg_foreign_server) GETSTRUCT(tp);
- server = (ForeignServer *) palloc(sizeof(ForeignServer));
+ server = palloc_object(ForeignServer);
server->serverid = serverid;
server->servername = pstrdup(NameStr(serverform->srvname));
server->owner = serverform->srvowner;
MappingUserName(userid), server->servername)));
}
- um = (UserMapping *) palloc(sizeof(UserMapping));
+ um = palloc_object(UserMapping);
um->umid = ((Form_pg_user_mapping) GETSTRUCT(tp))->oid;
um->userid = userid;
um->serverid = serverid;
elog(ERROR, "cache lookup failed for foreign table %u", relid);
tableform = (Form_pg_foreign_table) GETSTRUCT(tp);
- ft = (ForeignTable *) palloc(sizeof(ForeignTable));
+ ft = palloc_object(ForeignTable);
ft->relid = relid;
ft->serverid = tableform->ftserver;
/* We have valid cached data --- does the caller want a copy? */
if (makecopy)
{
- fdwroutine = (FdwRoutine *) palloc(sizeof(FdwRoutine));
+ fdwroutine = palloc_object(FdwRoutine);
memcpy(fdwroutine, relation->rd_fdwroutine, sizeof(FdwRoutine));
return fdwroutine;
}
if (num_attributes == 0)
return;
- attrs = palloc(sizeof(LLVMAttributeRef) * num_attributes);
+ attrs = palloc_array(LLVMAttributeRef, num_attributes);
LLVMGetAttributesAtIndex(v_from, index, attrs);
for (int attno = 0; attno < num_attributes; attno++)
LLVMOrcCLookupSet LookupSet, size_t LookupSetSize)
{
#if LLVM_VERSION_MAJOR > 14
- LLVMOrcCSymbolMapPairs symbols = palloc0(sizeof(LLVMOrcCSymbolMapPair) * LookupSetSize);
+ LLVMOrcCSymbolMapPairs symbols = palloc0_array(LLVMOrcCSymbolMapPair, LookupSetSize);
#else
- LLVMOrcCSymbolMapPairs symbols = palloc0(sizeof(LLVMJITCSymbolMapPair) * LookupSetSize);
+ LLVMOrcCSymbolMapPairs symbols = palloc0_array(LLVMJITCSymbolMapPair, LookupSetSize);
#endif
LLVMErrorRef error;
LLVMOrcMaterializationUnitRef mu;
b = LLVMCreateBuilderInContext(lc);
- attcheckattnoblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
- attstartblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
- attisnullblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
- attcheckalignblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
- attalignblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
- attstoreblocks = palloc(sizeof(LLVMBasicBlockRef) * natts);
+ attcheckattnoblocks = palloc_array(LLVMBasicBlockRef, natts);
+ attstartblocks = palloc_array(LLVMBasicBlockRef, natts);
+ attisnullblocks = palloc_array(LLVMBasicBlockRef, natts);
+ attcheckalignblocks = palloc_array(LLVMBasicBlockRef, natts);
+ attalignblocks = palloc_array(LLVMBasicBlockRef, natts);
+ attstoreblocks = palloc_array(LLVMBasicBlockRef, natts);
known_alignment = 0;
"v.econtext.aggnulls");
/* allocate blocks for each op upfront, so we can do jumps easily */
- opblocks = palloc(sizeof(LLVMBasicBlockRef) * state->steps_len);
+ opblocks = palloc_array(LLVMBasicBlockRef, state->steps_len);
for (int opno = 0; opno < state->steps_len; opno++)
opblocks[opno] = l_bb_append_v(eval_fn, "b.op.%d.start", opno);
v_nullsp = l_ptr_const(nulls, l_ptr(TypeStorageBool));
/* create blocks for checking args */
- b_checknulls = palloc(sizeof(LLVMBasicBlockRef) * nargs);
+ b_checknulls = palloc_array(LLVMBasicBlockRef, nargs);
for (int argno = 0; argno < nargs; argno++)
{
b_checknulls[argno] =
*/
{
- CompiledExprState *cstate = palloc0(sizeof(CompiledExprState));
+ CompiledExprState *cstate = palloc0_object(CompiledExprState);
cstate->context = context;
cstate->funcname = funcname;
elog(ERROR, "parameter mismatch: %s expects %d passed %d",
funcname, LLVMCountParams(v_fn), nargs + 2);
- params = palloc(sizeof(LLVMValueRef) * (2 + nargs));
+ params = palloc_array(LLVMValueRef, (2 + nargs));
params[argno++] = v_state;
params[argno++] = l_ptr_const(op, l_ptr(StructExprEvalStep));
BipartiteMatchState *
BipartiteMatch(int u_size, int v_size, short **adjacency)
{
- BipartiteMatchState *state = palloc(sizeof(BipartiteMatchState));
+ BipartiteMatchState *state = palloc_object(BipartiteMatchState);
if (u_size < 0 || u_size >= SHRT_MAX ||
v_size < 0 || v_size >= SHRT_MAX)
dsa_pointer control;
/* Allocate the backend-local object representing the hash table. */
- hash_table = palloc(sizeof(dshash_table));
+ hash_table = palloc_object(dshash_table);
/* Allocate the control object in shared memory. */
control = dsa_allocate(area, sizeof(dshash_table_control));
dsa_pointer control;
/* Allocate the backend-local object representing the hash table. */
- hash_table = palloc(sizeof(dshash_table));
+ hash_table = palloc_object(dshash_table);
/* Find the control object in shared memory. */
control = handle;
{
IntegerSet *intset;
- intset = (IntegerSet *) palloc(sizeof(IntegerSet));
+ intset = palloc_object(IntegerSet);
intset->context = CurrentMemoryContext;
intset->mem_used = GetMemoryChunkSpace(intset);
{
pairingheap *heap;
- heap = (pairingheap *) palloc(sizeof(pairingheap));
+ heap = palloc_object(pairingheap);
pairingheap_initialize(heap, compare, arg);
return heap;
rbt_freefunc freefunc,
void *arg)
{
- RBTree *tree = (RBTree *) palloc(sizeof(RBTree));
+ RBTree *tree = palloc_object(RBTree);
Assert(node_size > sizeof(RBTNode));
errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("client selected an invalid SASL authentication mechanism"));
- ctx = palloc0(sizeof(*ctx));
+ ctx = palloc0_object(struct oauth_ctx);
ctx->state = OAUTH_STATE_INIT;
ctx->port = port;
errmsg("validation of OAuth token requested without a validator loaded"));
/* Call the validation function from the validator module */
- ret = palloc0(sizeof(ValidatorModuleResult));
+ ret = palloc0_object(ValidatorModuleResult);
if (!ValidatorCallbacks->validate_cb(validator_module_state, token,
port->user_name, ret))
{
"OAuth validator", libname, "validate_cb"));
/* Allocate memory for validator library private state data */
- validator_module_state = (ValidatorModuleState *) palloc0(sizeof(ValidatorModuleState));
+ validator_module_state = palloc0_object(ValidatorModuleState);
validator_module_state->sversion = PG_VERSION_NUM;
if (ValidatorCallbacks->startup_cb != NULL)
ValidatorCallbacks->startup_cb(validator_module_state);
/* Shut down the library before cleaning up its state. */
- mcb = palloc0(sizeof(*mcb));
+ mcb = palloc0_object(MemoryContextCallback);
mcb->func = shutdown_validator_library;
MemoryContextRegisterResetCallback(CurrentMemoryContext, mcb);
scram_state *state;
bool got_secret;
- state = (scram_state *) palloc0(sizeof(scram_state));
+ state = palloc0_object(scram_state);
state->port = port;
state->state = SCRAM_AUTH_INIT;
if (token->string[0] != '/')
return 0; /* nothing to compile */
- token->regex = (regex_t *) palloc0(sizeof(regex_t));
+ token->regex = palloc0_object(regex_t);
wstr = palloc((strlen(token->string + 1) + 1) * sizeof(pg_wchar));
wlen = pg_mb2wchar_with_len(token->string + 1,
wstr, strlen(token->string + 1));
* to this list.
*/
oldcxt = MemoryContextSwitchTo(tokenize_context);
- tok_line = (TokenizedAuthLine *) palloc0(sizeof(TokenizedAuthLine));
+ tok_line = palloc0_object(TokenizedAuthLine);
tok_line->fields = current_line;
tok_line->file_name = pstrdup(filename);
tok_line->line_num = line_number;
AuthToken *token;
HbaLine *parsedline;
- parsedline = palloc0(sizeof(HbaLine));
+ parsedline = palloc0_object(HbaLine);
parsedline->sourcefile = pstrdup(file_name);
parsedline->linenumber = line_num;
parsedline->rawline = pstrdup(tok_line->raw_line);
}
/* If no matching entry was found, then implicitly reject. */
- hba = palloc0(sizeof(HbaLine));
+ hba = palloc0_object(HbaLine);
hba->auth_method = uaImplicitReject;
port->hba = hba;
}
Assert(tok_line->fields != NIL);
field = list_head(tok_line->fields);
- parsedline = palloc0(sizeof(IdentLine));
+ parsedline = palloc0_object(IdentLine);
parsedline->linenumber = line_num;
/* Get the map token (must exist) */
int latch_pos PG_USED_FOR_ASSERTS_ONLY;
/* allocate the Port struct and copy the ClientSocket contents to it */
- port = palloc0(sizeof(Port));
+ port = palloc0_object(Port);
port->sock = client_sock->sock;
memcpy(&port->raddr.addr, &client_sock->raddr.addr, client_sock->raddr.salen);
port->raddr.salen = client_sock->raddr.salen;
*/
#define FLATCOPY(newnode, node, nodetype) \
- ( (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
+ ( (newnode) = palloc_object(nodetype), \
memcpy((newnode), (node), sizeof(nodetype)) )
#define MUTATE(newfield, oldfield, fieldtype) \
{
JumbleState *jstate;
- jstate = (JumbleState *) palloc(sizeof(JumbleState));
+ jstate = palloc_object(JumbleState);
/* Set up workspace for query jumbling */
jstate->jumble = (unsigned char *) palloc(JUMBLE_SIZE);
* Create the TBMPrivateIterator struct, with enough trailing space to
* serve the needs of the TBMIterateResult sub-struct.
*/
- iterator = (TBMPrivateIterator *) palloc(sizeof(TBMPrivateIterator));
+ iterator = palloc_object(TBMPrivateIterator);
iterator->tbm = tbm;
/*
* Create the TBMSharedIterator struct, with enough trailing space to
* serve the needs of the TBMIterateResult sub-struct.
*/
- iterator = (TBMSharedIterator *) palloc0(sizeof(TBMSharedIterator));
+ iterator = palloc0_object(TBMSharedIterator);
istate = (TBMSharedIteratorState *) dsa_get_address(dsa, dp);
* directly; 0 will not be used
*/
- edge_table = (Edge *) palloc((num_gene + 1) * sizeof(Edge));
+ edge_table = palloc_array(Edge, num_gene + 1);
return edge_table;
}
cur_rel_index - 1);
/* Make it into a single-rel clump */
- cur_clump = (Clump *) palloc(sizeof(Clump));
+ cur_clump = palloc_object(Clump);
cur_clump->joinrel = cur_rel;
cur_clump->size = 1;
void
pmx(PlannerInfo *root, Gene *tour1, Gene *tour2, Gene *offspring, int num_gene)
{
- int *failed = (int *) palloc((num_gene + 1) * sizeof(int));
- int *from = (int *) palloc((num_gene + 1) * sizeof(int));
- int *indx = (int *) palloc((num_gene + 1) * sizeof(int));
- int *check_list = (int *) palloc((num_gene + 1) * sizeof(int));
+ int *failed = palloc_array(int, num_gene + 1);
+ int *from = palloc_array(int, num_gene + 1);
+ int *indx = palloc_array(int, num_gene + 1);
+ int *check_list = palloc_array(int, num_gene + 1);
int left,
right,
int i;
/* pool */
- new_pool = (Pool *) palloc(sizeof(Pool));
+ new_pool = palloc_object(Pool);
new_pool->size = pool_size;
new_pool->string_length = string_length;
/* all chromosome */
- new_pool->data = (Chromosome *) palloc(pool_size * sizeof(Chromosome));
+ new_pool->data = palloc_array(Chromosome, pool_size);
/* all gene */
chromo = (Chromosome *) new_pool->data; /* vector of all chromos */
for (i = 0; i < pool_size; i++)
- chromo[i].string = palloc((string_length + 1) * sizeof(Gene));
+ chromo[i].string = palloc_array(Gene, string_length + 1);
return new_pool;
}
{
Chromosome *chromo;
- chromo = (Chromosome *) palloc(sizeof(Chromosome));
- chromo->string = (Gene *) palloc((string_length + 1) * sizeof(Gene));
+ chromo = palloc_object(Chromosome);
+ chromo->string = palloc_array(Gene, string_length + 1);
return chromo;
}
* palloc one extra location so that nodes numbered 1..n can be indexed
* directly; 0 will not be used
*/
- city_table = (City *) palloc((num_gene + 1) * sizeof(City));
+ city_table = palloc_array(City, num_gene + 1);
return city_table;
}
}
/* No matching var found, so make a new clause-pair data structure */
- rqelem = (RangeQueryClause *) palloc(sizeof(RangeQueryClause));
+ rqelem = palloc_object(RangeQueryClause);
rqelem->var = var;
if (is_lobound)
{
* whichever is less.
*/
arrlen = Min(parallel_workers, numpaths);
- costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
+ costarr = palloc_array(Cost, arrlen);
/* The first few paths will each be claimed by a different worker. */
path_index = 0;
/* Cache the result in suitably long-lived workspace */
oldcontext = MemoryContextSwitchTo(root->planner_cxt);
- cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
+ cache = palloc_object(MergeScanSelCache);
cache->opfamily = pathkey->pk_opfamily;
cache->collation = pathkey->pk_eclass->ec_collation;
cache->cmptype = pathkey->pk_cmptype;
* which will be used to sort these arguments at the next step.
*/
i = -1;
- matches = (OrArgIndexMatch *) palloc(sizeof(OrArgIndexMatch) * n);
+ matches = palloc_array(OrArgIndexMatch, n);
foreach(lc, orargs)
{
Node *arg = lfirst(lc);
* same set of clauses; keep only the cheapest-to-scan of any such groups.
* The surviving paths are put into an array for qsort'ing.
*/
- pathinfoarray = (PathClauseUsage **)
- palloc(npaths * sizeof(PathClauseUsage *));
+ pathinfoarray = palloc_array(PathClauseUsage *, npaths);
clauselist = NIL;
npaths = 0;
foreach(l, paths)
Bitmapset *clauseids;
ListCell *lc;
- result = (PathClauseUsage *) palloc(sizeof(PathClauseUsage));
+ result = palloc_object(PathClauseUsage);
result->path = path;
/* Recursively find the quals and preds used by the path */
Assert(nparts > 0);
joinrel->boundinfo = boundinfo;
joinrel->nparts = nparts;
- joinrel->part_rels =
- (RelOptInfo **) palloc0(sizeof(RelOptInfo *) * nparts);
+ joinrel->part_rels = palloc0_array(RelOptInfo *, nparts);
}
else
{
* In order to find relations with the same oid we first build an array of
* candidates and then sort it by oid.
*/
- candidates = (SelfJoinCandidate *) palloc(sizeof(SelfJoinCandidate) *
- numRels);
+ candidates = palloc_array(SelfJoinCandidate, numRels);
i = -1;
j = 0;
while ((i = bms_next_member(relids, i)) >= 0)
Assert(grouping_map);
- new_grpColIdx = palloc0(sizeof(AttrNumber) * list_length(groupClause));
+ new_grpColIdx = palloc0_array(AttrNumber, list_length(groupClause));
i = 0;
foreach(lc, groupClause)
* Convert SortGroupClause lists into arrays of attr indexes and equality
* operators, as wanted by executor.
*/
- partColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numPart);
- partOperators = (Oid *) palloc(sizeof(Oid) * numPart);
- partCollations = (Oid *) palloc(sizeof(Oid) * numPart);
+ partColIdx = palloc_array(AttrNumber, numPart);
+ partOperators = palloc_array(Oid, numPart);
+ partCollations = palloc_array(Oid, numPart);
partNumCols = 0;
foreach(lc, wc->partitionClause)
partNumCols++;
}
- ordColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numOrder);
- ordOperators = (Oid *) palloc(sizeof(Oid) * numOrder);
- ordCollations = (Oid *) palloc(sizeof(Oid) * numOrder);
+ ordColIdx = palloc_array(AttrNumber, numOrder);
+ ordOperators = palloc_array(Oid, numOrder);
+ ordCollations = palloc_array(Oid, numOrder);
ordNumCols = 0;
foreach(lc, wc->orderClause)
Oid *dupCollations;
ListCell *slitem;
- dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
- dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
- dupCollations = (Oid *) palloc(sizeof(Oid) * numCols);
+ dupColIdx = palloc_array(AttrNumber, numCols);
+ dupOperators = palloc_array(Oid, numCols);
+ dupCollations = palloc_array(Oid, numCols);
foreach(slitem, distinctList)
{
* prepare_sort_from_pathkeys ... maybe unify sometime?
*/
Assert(numCols >= 0 && numCols <= list_length(pathkeys));
- uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
- uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
- uniqCollations = (Oid *) palloc(sizeof(Oid) * numCols);
+ uniqColIdx = palloc_array(AttrNumber, numCols);
+ uniqOperators = palloc_array(Oid, numCols);
+ uniqCollations = palloc_array(Oid, numCols);
foreach(lc, pathkeys)
{
* convert SortGroupClause list into arrays of attr indexes and comparison
* operators, as wanted by executor
*/
- cmpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
- cmpOperators = (Oid *) palloc(sizeof(Oid) * numCols);
- cmpCollations = (Oid *) palloc(sizeof(Oid) * numCols);
- cmpNullsFirst = (bool *) palloc(sizeof(bool) * numCols);
+ cmpColIdx = palloc_array(AttrNumber, numCols);
+ cmpOperators = palloc_array(Oid, numCols);
+ cmpCollations = palloc_array(Oid, numCols);
+ cmpNullsFirst = palloc_array(bool, numCols);
foreach(slitem, groupList)
{
* Fill groupbyattnos[k] with a bitmapset of the column attnos of RTE k
* that are GROUP BY items.
*/
- groupbyattnos = (Bitmapset **) palloc0(sizeof(Bitmapset *) *
- (list_length(parse->rtable) + 1));
+ groupbyattnos = palloc0_array(Bitmapset *, list_length(parse->rtable) + 1);
foreach(lc, root->processed_groupClause)
{
SortGroupClause *sgc = lfirst_node(SortGroupClause, lc);
* allocate the surplusvars[] array until we find something.
*/
if (surplusvars == NULL)
- surplusvars = (Bitmapset **) palloc0(sizeof(Bitmapset *) *
- (list_length(parse->rtable) + 1));
+ surplusvars = palloc0_array(Bitmapset *, list_length(parse->rtable) + 1);
/* Remember the attnos of the removable columns */
surplusvars[relid] = bms_difference(relattnos, best_keycolumns);
* than before. (This means that when we are done, there will be no Vars
* of level 1, which is why the subquery can become an initplan.)
*/
- subroot = (PlannerInfo *) palloc(sizeof(PlannerInfo));
+ subroot = palloc_object(PlannerInfo);
memcpy(subroot, root, sizeof(PlannerInfo));
subroot->query_level++;
subroot->parent_root = root;
List *sets;
int maxref = 0;
ListCell *lc_set;
- grouping_sets_data *gd = palloc0(sizeof(grouping_sets_data));
+ grouping_sets_data *gd = palloc0_object(grouping_sets_data);
/*
* We don't currently make any attempt to optimize the groupClause when
List *result = NIL;
ListCell *lc;
int nActive = 0;
- WindowClauseSortData *actives = palloc(sizeof(WindowClauseSortData)
- * list_length(windowClause));
+ WindowClauseSortData *actives = palloc_array(WindowClauseSortData,
+ list_length(windowClause));
/* First, construct an array of the active windows */
foreach(lc, windowClause)
root->simple_rte_array[rc->rti] != NULL);
/* flat copy is enough since all fields are scalars */
- newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
+ newrc = palloc_object(PlanRowMark);
memcpy(newrc, rc, sizeof(PlanRowMark));
/* adjust indexes ... but *not* the rowmarkId */
RangeTblEntry *newrte;
/* flat copy to duplicate all the scalar fields */
- newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
+ newrte = palloc_object(RangeTblEntry);
memcpy(newrte, rte, sizeof(RangeTblEntry));
/* zap unneeded sub-structure */
static inline Var *
copyVar(Var *var)
{
- Var *newvar = (Var *) palloc(sizeof(Var));
+ Var *newvar = palloc_object(Var);
*newvar = *var;
return newvar;
* Make a modifiable copy of join node, but don't bother copying its
* subnodes (yet).
*/
- j = (JoinExpr *) palloc(sizeof(JoinExpr));
+ j = palloc_object(JoinExpr);
memcpy(j, jtnode, sizeof(JoinExpr));
jtlink = (Node *) j;
{
reduce_outer_joins_pass1_state *result;
- result = (reduce_outer_joins_pass1_state *)
- palloc(sizeof(reduce_outer_joins_pass1_state));
+ result = palloc_object(reduce_outer_joins_pass1_state);
result->relids = NULL;
result->contains_outer = false;
result->sub_states = NIL;
{
reduce_outer_joins_partial_state *statep;
- statep = palloc(sizeof(reduce_outer_joins_partial_state));
+ statep = palloc_object(reduce_outer_joins_partial_state);
statep->full_join_rti = rtindex;
statep->unreduced_side = relids;
state2->partial_reduced = lappend(state2->partial_reduced, statep);
* If the inputs all agree on type and typmod of a particular column, use
* that typmod; else use -1.
*/
- colTypmods = (int32 *) palloc(list_length(colTypes) * sizeof(int32));
+ colTypmods = palloc_array(int32, list_length(colTypes));
foreach(tlistl, input_tlists)
{
int i;
/* Allocate an array that's certainly big enough */
- appinfos = (AppendRelInfo **)
- palloc(sizeof(AppendRelInfo *) * bms_num_members(relids));
+ appinfos = palloc_array(AppendRelInfo *, bms_num_members(relids));
i = -1;
while ((i = bms_next_member(relids, i)) >= 0)
WindowFuncLists *
find_window_functions(Node *clause, Index maxWinRef)
{
- WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
+ WindowFuncLists *lists = palloc_object(WindowFuncLists);
lists->numWindowFuncs = 0;
lists->maxWinRef = maxWinRef;
get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
- elems = (Datum *) palloc(sizeof(Datum) * list_length(exprs));
- nulls = (bool *) palloc(sizeof(bool) * list_length(exprs));
+ elems = palloc_array(Datum, list_length(exprs));
+ nulls = palloc_array(bool, list_length(exprs));
foreach_node(Const, value, exprs)
{
elems[i] = value->constvalue;
int i;
i = pg_nextpower2_32(extension_id + 1);
- glob->extension_state = (void **)
- repalloc0(glob->extension_state,
- glob->extension_state_allocated * sizeof(void *),
- i * sizeof(void *));
+ glob->extension_state = repalloc0_array(glob->extension_state, void *,
+ glob->extension_state_allocated, i);
glob->extension_state_allocated = i;
}
int i;
i = pg_nextpower2_32(extension_id + 1);
- root->extension_state = (void **)
- repalloc0(root->extension_state,
- root->extension_state_allocated * sizeof(void *),
- i * sizeof(void *));
+ root->extension_state = repalloc0_array(root->extension_state, void *,
+ root->extension_state_allocated, i);
root->extension_state_allocated = i;
}
int i;
i = pg_nextpower2_32(extension_id + 1);
- rel->extension_state = (void **)
- repalloc0(rel->extension_state,
- rel->extension_state_allocated * sizeof(void *),
- i * sizeof(void *));
+ rel->extension_state = repalloc0_array(rel->extension_state, void *,
+ rel->extension_state_allocated, i);
rel->extension_state_allocated = i;
}
info->ncolumns = ncolumns = index->indnatts;
info->nkeycolumns = nkeycolumns = index->indnkeyatts;
- info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
- info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
- info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
- info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
- info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
+ info->indexkeys = palloc_array(int, ncolumns);
+ info->indexcollations = palloc_array(Oid, nkeycolumns);
+ info->opfamily = palloc_array(Oid, nkeycolumns);
+ info->opcintype = palloc_array(Oid, nkeycolumns);
+ info->canreturn = palloc_array(bool, ncolumns);
for (i = 0; i < ncolumns; i++)
{
Assert(amroutine->amcanorder);
info->sortopfamily = info->opfamily;
- info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
- info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
+ info->reverse_sort = palloc_array(bool, nkeycolumns);
+ info->nulls_first = palloc_array(bool, nkeycolumns);
for (i = 0; i < nkeycolumns; i++)
{
* corresponding btree opfamily for each opfamily of the
* other index type.
*/
- info->sortopfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
- info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
- info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
+ info->sortopfamily = palloc_array(Oid, nkeycolumns);
+ info->reverse_sort = palloc_array(bool, nkeycolumns);
+ info->nulls_first = palloc_array(bool, nkeycolumns);
for (i = 0; i < nkeycolumns; i++)
{
* array since the relcache entry may not survive after we have closed the
* relation.
*/
- part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
+ part_scheme = palloc0_object(PartitionSchemeData);
part_scheme->strategy = partkey->strategy;
part_scheme->partnatts = partkey->partnatts;
- part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
+ part_scheme->partopfamily = palloc_array(Oid, partnatts);
memcpy(part_scheme->partopfamily, partkey->partopfamily,
sizeof(Oid) * partnatts);
- part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
+ part_scheme->partopcintype = palloc_array(Oid, partnatts);
memcpy(part_scheme->partopcintype, partkey->partopcintype,
sizeof(Oid) * partnatts);
- part_scheme->partcollation = (Oid *) palloc(sizeof(Oid) * partnatts);
+ part_scheme->partcollation = palloc_array(Oid, partnatts);
memcpy(part_scheme->partcollation, partkey->partcollation,
sizeof(Oid) * partnatts);
- part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
+ part_scheme->parttyplen = palloc_array(int16, partnatts);
memcpy(part_scheme->parttyplen, partkey->parttyplen,
sizeof(int16) * partnatts);
- part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
+ part_scheme->parttypbyval = palloc_array(bool, partnatts);
memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
sizeof(bool) * partnatts);
- part_scheme->partsupfunc = (FmgrInfo *)
- palloc(sizeof(FmgrInfo) * partnatts);
+ part_scheme->partsupfunc = palloc_array(FmgrInfo, partnatts);
for (i = 0; i < partnatts; i++)
fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
CurrentMemoryContext);
Assert(partkey != NULL);
partnatts = partkey->partnatts;
- partexprs = (List **) palloc(sizeof(List *) * partnatts);
+ partexprs = palloc_array(List *, partnatts);
lc = list_head(partkey->partexprs);
for (cnt = 0; cnt < partnatts; cnt++)
* expression lists to keep partition key expression handling code simple.
* See build_joinrel_partition_info() and match_expr_to_partition_keys().
*/
- rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
+ rel->nullable_partexprs = palloc0_array(List *, partnatts);
}
/*
char elmalign;
/* Create working state struct */
- state = (ArrayConstIterState *) palloc(sizeof(ArrayConstIterState));
+ state = palloc_object(ArrayConstIterState);
info->state = state;
/* Deconstruct the array literal */
ArrayExpr *arrayexpr;
/* Create working state struct */
- state = (ArrayExprIterState *) palloc(sizeof(ArrayExprIterState));
+ state = palloc_object(ArrayExprIterState);
info->state = state;
/* Set up a dummy OpExpr to return as the per-item node */
* exist yet. It'll be filled by later calls to build_simple_rel().
*/
root->simple_rel_array = (RelOptInfo **)
- palloc0(size * sizeof(RelOptInfo *));
+ palloc0_array(RelOptInfo *, size);
/* simple_rte_array is an array equivalent of the rtable list */
root->simple_rte_array = (RangeTblEntry **)
- palloc0(size * sizeof(RangeTblEntry *));
+ palloc0_array(RangeTblEntry *, size);
rti = 1;
foreach(lc, root->parse->rtable)
{
}
root->append_rel_array = (AppendRelInfo **)
- palloc0(size * sizeof(AppendRelInfo *));
+ palloc0_array(AppendRelInfo *, size);
/*
* append_rel_array is filled with any already-existing AppendRelInfos,
rel->min_attr = 0;
rel->max_attr = list_length(rte->eref->colnames);
rel->attr_needed = (Relids *)
- palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
+ palloc0_array(Relids, rel->max_attr - rel->min_attr + 1);
rel->attr_widths = (int32 *)
- palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
+ palloc0_array(int32, rel->max_attr - rel->min_attr + 1);
break;
case RTE_RESULT:
/* RTE_RESULT has no columns, nor could it have whole-row Var */
PartitionScheme part_scheme = joinrel->part_scheme;
int partnatts = part_scheme->partnatts;
- joinrel->partexprs = (List **) palloc0(sizeof(List *) * partnatts);
- joinrel->nullable_partexprs =
- (List **) palloc0(sizeof(List *) * partnatts);
+ joinrel->partexprs = palloc0_array(List *, partnatts);
+ joinrel->nullable_partexprs = palloc0_array(List *, partnatts);
/*
* The joinrel's partition expressions are the same as those of the input
Oid *groupOperators;
ListCell *glitem;
- groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
+ groupOperators = palloc_array(Oid, numCols);
foreach(glitem, groupClause)
{
Oid *grpCollations;
ListCell *glitem;
- grpCollations = (Oid *) palloc(sizeof(Oid) * numCols);
+ grpCollations = palloc_array(Oid, numCols);
foreach(glitem, groupClause)
{
int colno = 0;
ListCell *glitem;
- grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
+ grpColIdx = palloc_array(AttrNumber, numCols);
foreach(glitem, groupClause)
{
*/
if (list_member(context->input_target_exprs, node))
{
- split_pathtarget_item *item = palloc(sizeof(split_pathtarget_item));
+ split_pathtarget_item *item = palloc_object(split_pathtarget_item);
item->expr = node;
item->sortgroupref = context->current_sgref;
IsA(node, GroupingFunc) ||
IsA(node, WindowFunc))
{
- split_pathtarget_item *item = palloc(sizeof(split_pathtarget_item));
+ split_pathtarget_item *item = palloc_object(split_pathtarget_item);
item->expr = node;
item->sortgroupref = context->current_sgref;
*/
if (IS_SRF_CALL(node))
{
- split_pathtarget_item *item = palloc(sizeof(split_pathtarget_item));
+ split_pathtarget_item *item = palloc_object(split_pathtarget_item);
List *save_input_vars = context->current_input_vars;
List *save_input_srfs = context->current_input_srfs;
int save_current_depth = context->current_depth;
colnames = pstate->p_target_nsitem->p_rte->eref->colnames;
numattrs = list_length(colnames);
- nscolumns = (ParseNamespaceColumn *)
- palloc(numattrs * sizeof(ParseNamespaceColumn));
+ nscolumns = palloc_array(ParseNamespaceColumn, numattrs);
memcpy(nscolumns, pstate->p_target_nsitem->p_nscolumns,
numattrs * sizeof(ParseNamespaceColumn));
nscolumns[i].p_varreturningtype = returning_type;
/* build the nsitem, copying most fields from the target relation */
- nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
+ nsitem = palloc_object(ParseNamespaceItem);
nsitem->p_names = makeAlias(aliasname, colnames);
nsitem->p_rte = pstate->p_target_nsitem->p_rte;
nsitem->p_rtindex = pstate->p_target_nsitem->p_rtindex;
key_actions:
key_update
{
- KeyActions *n = palloc(sizeof(KeyActions));
+ KeyActions *n = palloc_object(KeyActions);
n->updateAction = $1;
- n->deleteAction = palloc(sizeof(KeyAction));
+ n->deleteAction = palloc_object(KeyAction);
n->deleteAction->action = FKCONSTR_ACTION_NOACTION;
n->deleteAction->cols = NIL;
$$ = n;
}
| key_delete
{
- KeyActions *n = palloc(sizeof(KeyActions));
+ KeyActions *n = palloc_object(KeyActions);
- n->updateAction = palloc(sizeof(KeyAction));
+ n->updateAction = palloc_object(KeyAction);
n->updateAction->action = FKCONSTR_ACTION_NOACTION;
n->updateAction->cols = NIL;
n->deleteAction = $1;
}
| key_update key_delete
{
- KeyActions *n = palloc(sizeof(KeyActions));
+ KeyActions *n = palloc_object(KeyActions);
n->updateAction = $1;
n->deleteAction = $2;
}
| key_delete key_update
{
- KeyActions *n = palloc(sizeof(KeyActions));
+ KeyActions *n = palloc_object(KeyActions);
n->updateAction = $2;
n->deleteAction = $1;
}
| /*EMPTY*/
{
- KeyActions *n = palloc(sizeof(KeyActions));
+ KeyActions *n = palloc_object(KeyActions);
- n->updateAction = palloc(sizeof(KeyAction));
+ n->updateAction = palloc_object(KeyAction);
n->updateAction->action = FKCONSTR_ACTION_NOACTION;
n->updateAction->cols = NIL;
- n->deleteAction = palloc(sizeof(KeyAction));
+ n->deleteAction = palloc_object(KeyAction);
n->deleteAction->action = FKCONSTR_ACTION_NOACTION;
n->deleteAction->cols = NIL;
$$ = n;
key_action:
NO ACTION
{
- KeyAction *n = palloc(sizeof(KeyAction));
+ KeyAction *n = palloc_object(KeyAction);
n->action = FKCONSTR_ACTION_NOACTION;
n->cols = NIL;
}
| RESTRICT
{
- KeyAction *n = palloc(sizeof(KeyAction));
+ KeyAction *n = palloc_object(KeyAction);
n->action = FKCONSTR_ACTION_RESTRICT;
n->cols = NIL;
}
| CASCADE
{
- KeyAction *n = palloc(sizeof(KeyAction));
+ KeyAction *n = palloc_object(KeyAction);
n->action = FKCONSTR_ACTION_CASCADE;
n->cols = NIL;
}
| SET NULL_P opt_column_list
{
- KeyAction *n = palloc(sizeof(KeyAction));
+ KeyAction *n = palloc_object(KeyAction);
n->action = FKCONSTR_ACTION_SETNULL;
n->cols = $3;
}
| SET DEFAULT opt_column_list
{
- KeyAction *n = palloc(sizeof(KeyAction));
+ KeyAction *n = palloc_object(KeyAction);
n->action = FKCONSTR_ACTION_SETDEFAULT;
n->cols = $3;
import_qualification:
import_qualification_type '(' relation_expr_list ')'
{
- ImportQual *n = (ImportQual *) palloc(sizeof(ImportQual));
+ ImportQual *n = palloc_object(ImportQual);
n->type = $1;
n->table_names = $3;
}
| /*EMPTY*/
{
- ImportQual *n = (ImportQual *) palloc(sizeof(ImportQual));
+ ImportQual *n = palloc_object(ImportQual);
n->type = FDW_IMPORT_SCHEMA_ALL;
n->table_names = NIL;
$$ = n;
privilege_target:
qualified_name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_TABLE;
}
| TABLE qualified_name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_TABLE;
}
| SEQUENCE qualified_name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_SEQUENCE;
}
| FOREIGN DATA_P WRAPPER name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_FDW;
}
| FOREIGN SERVER name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_FOREIGN_SERVER;
}
| FUNCTION function_with_argtypes_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_FUNCTION;
}
| PROCEDURE function_with_argtypes_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_PROCEDURE;
}
| ROUTINE function_with_argtypes_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_ROUTINE;
}
| DATABASE name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_DATABASE;
}
| DOMAIN_P any_name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_DOMAIN;
}
| LANGUAGE name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_LANGUAGE;
}
| LARGE_P OBJECT_P NumericOnly_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_LARGEOBJECT;
}
| PARAMETER parameter_name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_PARAMETER_ACL;
n->objs = $2;
}
| SCHEMA name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_SCHEMA;
}
| TABLESPACE name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_TABLESPACE;
}
| TYPE_P any_name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_OBJECT;
n->objtype = OBJECT_TYPE;
}
| ALL TABLES IN_P SCHEMA name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
n->objtype = OBJECT_TABLE;
}
| ALL SEQUENCES IN_P SCHEMA name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
n->objtype = OBJECT_SEQUENCE;
}
| ALL FUNCTIONS IN_P SCHEMA name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
n->objtype = OBJECT_FUNCTION;
}
| ALL PROCEDURES IN_P SCHEMA name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
n->objtype = OBJECT_PROCEDURE;
}
| ALL ROUTINES IN_P SCHEMA name_list
{
- PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
+ PrivTarget *n = palloc_object(PrivTarget);
n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
n->objtype = OBJECT_ROUTINE;
}
| offset_clause
{
- SelectLimit *n = (SelectLimit *) palloc(sizeof(SelectLimit));
+ SelectLimit *n = palloc_object(SelectLimit);
n->limitOffset = $1;
n->limitCount = NULL;
limit_clause:
LIMIT select_limit_value
{
- SelectLimit *n = (SelectLimit *) palloc(sizeof(SelectLimit));
+ SelectLimit *n = palloc_object(SelectLimit);
n->limitOffset = NULL;
n->limitCount = $2;
*/
| FETCH first_or_next select_fetch_first_value row_or_rows ONLY
{
- SelectLimit *n = (SelectLimit *) palloc(sizeof(SelectLimit));
+ SelectLimit *n = palloc_object(SelectLimit);
n->limitOffset = NULL;
n->limitCount = $3;
}
| FETCH first_or_next select_fetch_first_value row_or_rows WITH TIES
{
- SelectLimit *n = (SelectLimit *) palloc(sizeof(SelectLimit));
+ SelectLimit *n = palloc_object(SelectLimit);
n->limitOffset = NULL;
n->limitCount = $3;
}
| FETCH first_or_next row_or_rows ONLY
{
- SelectLimit *n = (SelectLimit *) palloc(sizeof(SelectLimit));
+ SelectLimit *n = palloc_object(SelectLimit);
n->limitOffset = NULL;
n->limitCount = makeIntConst(1, -1);
}
| FETCH first_or_next row_or_rows WITH TIES
{
- SelectLimit *n = (SelectLimit *) palloc(sizeof(SelectLimit));
+ SelectLimit *n = palloc_object(SelectLimit);
n->limitOffset = NULL;
n->limitCount = makeIntConst(1, -1);
group_clause:
GROUP_P BY set_quantifier group_by_list
{
- GroupClause *n = (GroupClause *) palloc(sizeof(GroupClause));
+ GroupClause *n = palloc_object(GroupClause);
n->distinct = $3 == SET_QUANTIFIER_DISTINCT;
n->all = false;
}
| GROUP_P BY ALL
{
- GroupClause *n = (GroupClause *) palloc(sizeof(GroupClause));
+ GroupClause *n = palloc_object(GroupClause);
n->distinct = false;
n->all = true;
n->list = NIL;
}
| /*EMPTY*/
{
- GroupClause *n = (GroupClause *) palloc(sizeof(GroupClause));
+ GroupClause *n = palloc_object(GroupClause);
n->distinct = false;
n->all = false;
tf->ordinalitycol = -1;
/* Process column specs */
- names = palloc(sizeof(char *) * list_length(rtf->columns));
+ names = palloc_array(char *, list_length(rtf->columns));
colno = 0;
foreach(col, rtf->columns)
{
ParseNamespaceItem *jnsitem;
- jnsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
+ jnsitem = palloc_object(ParseNamespaceItem);
jnsitem->p_names = j->join_using_alias;
jnsitem->p_rte = nsitem->p_rte;
jnsitem->p_rtindex = nsitem->p_rtindex;
* operators, and see which interpretations (cmptypes) exist for each
* operator.
*/
- opinfo_lists = (List **) palloc(nopers * sizeof(List *));
+ opinfo_lists = palloc_array(List *, nopers);
cmptypes = NULL;
i = 0;
foreach(l, opexprs)
{
JsonEncoding encoding;
const char *enc;
- Name encname = palloc(sizeof(NameData));
+ Name encname = palloc_object(NameData);
if (!format ||
format->format_type == JS_FORMAT_DEFAULT ||
{
ParseState *pstate;
- pstate = palloc0(sizeof(ParseState));
+ pstate = palloc0_object(ParseState);
pstate->parentParseState = parentParseState;
setup_parse_fixed_parameters(ParseState *pstate,
const Oid *paramTypes, int numParams)
{
- FixedParamState *parstate = palloc(sizeof(FixedParamState));
+ FixedParamState *parstate = palloc_object(FixedParamState);
parstate->paramTypes = paramTypes;
parstate->numParams = numParams;
setup_parse_variable_parameters(ParseState *pstate,
Oid **paramTypes, int *numParams)
{
- VarParamState *parstate = palloc(sizeof(VarParamState));
+ VarParamState *parstate = palloc_object(VarParamState);
parstate->paramTypes = paramTypes;
parstate->numParams = numParams;
int location)
{
ParseState *orig_pstate = pstate;
- FuzzyAttrMatchState *fuzzystate = palloc(sizeof(FuzzyAttrMatchState));
+ FuzzyAttrMatchState *fuzzystate = palloc_object(FuzzyAttrMatchState);
fuzzystate->distance = MAX_FUZZY_DISTANCE + 1;
fuzzystate->rfirst = NULL;
}
/* ... and build the nsitem */
- nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
+ nsitem = palloc_object(ParseNamespaceItem);
nsitem->p_names = rte->eref;
nsitem->p_rte = rte;
nsitem->p_rtindex = rtindex;
}
/* ... and build the nsitem */
- nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
+ nsitem = palloc_object(ParseNamespaceItem);
nsitem->p_names = rte->eref;
nsitem->p_rte = rte;
nsitem->p_rtindex = rtindex;
rte->eref = eref;
/* Process each function ... */
- functupdescs = (TupleDesc *) palloc(nfuncs * sizeof(TupleDesc));
+ functupdescs = palloc_array(TupleDesc, nfuncs);
totalatts = 0;
funcno = 0;
* Build a ParseNamespaceItem, but don't add it to the pstate's namespace
* list --- caller must do that if appropriate.
*/
- nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
+ nsitem = palloc_object(ParseNamespaceItem);
nsitem->p_names = rte->eref;
nsitem->p_rte = rte;
nsitem->p_perminfo = NULL;
* Currently, we allow simple numeric constants, string literals, and
* identifiers; possibly this list could be extended.
*/
- datums = (Datum *) palloc(list_length(typeName->typmods) * sizeof(Datum));
+ datums = palloc_array(Datum, list_length(typeName->typmods));
n = 0;
foreach(l, typeName->typmods)
{
* Initialize mapping array with invalid values, this is filled within
* each sub-routine below depending on the bound type.
*/
- *mapping = (int *) palloc(sizeof(int) * nparts);
+ *mapping = palloc_array(int, nparts);
for (i = 0; i < nparts; i++)
(*mapping)[i] = -1;
int greatest_modulus;
Datum *boundDatums;
- boundinfo = (PartitionBoundInfoData *)
- palloc0(sizeof(PartitionBoundInfoData));
+ boundinfo = palloc0_object(PartitionBoundInfoData);
boundinfo->strategy = key->strategy;
/* No special hash partitions. */
boundinfo->null_index = -1;
boundinfo->default_index = -1;
- hbounds = (PartitionHashBound *)
- palloc(nparts * sizeof(PartitionHashBound));
+ hbounds = palloc_array(PartitionHashBound, nparts);
/* Convert from node to the internal representation */
for (i = 0; i < nparts; i++)
greatest_modulus = hbounds[nparts - 1].modulus;
boundinfo->ndatums = nparts;
- boundinfo->datums = (Datum **) palloc0(nparts * sizeof(Datum *));
+ boundinfo->datums = palloc0_array(Datum *, nparts);
boundinfo->kind = NULL;
boundinfo->interleaved_parts = NULL;
boundinfo->nindexes = greatest_modulus;
int null_index = -1;
Datum *boundDatums;
- boundinfo = (PartitionBoundInfoData *)
- palloc0(sizeof(PartitionBoundInfoData));
+ boundinfo = palloc0_object(PartitionBoundInfoData);
boundinfo->strategy = key->strategy;
/* Will be set correctly below. */
boundinfo->null_index = -1;
qsort_partition_list_value_cmp, key);
boundinfo->ndatums = ndatums;
- boundinfo->datums = (Datum **) palloc0(ndatums * sizeof(Datum *));
+ boundinfo->datums = palloc0_array(Datum *, ndatums);
boundinfo->kind = NULL;
boundinfo->interleaved_parts = NULL;
boundinfo->nindexes = ndatums;
Datum *boundDatums;
PartitionRangeDatumKind *boundKinds;
- boundinfo = (PartitionBoundInfoData *)
- palloc0(sizeof(PartitionBoundInfoData));
+ boundinfo = palloc0_object(PartitionBoundInfoData);
boundinfo->strategy = key->strategy;
/* There is no special null-accepting range partition. */
boundinfo->null_index = -1;
/* Will be set correctly below. */
boundinfo->default_index = -1;
- all_bounds = (PartitionRangeBound **)
- palloc0(2 * nparts * sizeof(PartitionRangeBound *));
+ all_bounds = palloc0_array(PartitionRangeBound *, 2 * nparts);
/* Create a unified list of range bounds across all the partitions. */
ndatums = 0;
* bound.
*/
boundinfo->ndatums = ndatums;
- boundinfo->datums = (Datum **) palloc0(ndatums * sizeof(Datum *));
- boundinfo->kind = (PartitionRangeDatumKind **)
- palloc(ndatums *
- sizeof(PartitionRangeDatumKind *));
+ boundinfo->datums = palloc0_array(Datum *, ndatums);
+ boundinfo->kind = palloc0_array(PartitionRangeDatumKind *, ndatums);
boundinfo->interleaved_parts = NULL;
/*
* element of the indexes[] array.
*/
boundinfo->nindexes = ndatums + 1;
- boundinfo->indexes = (int *) palloc((ndatums + 1) * sizeof(int));
+ boundinfo->indexes = palloc_array(int, (ndatums + 1));
/*
* In the loop below, to save from allocating a series of small arrays,
*/
partnatts = key->partnatts;
boundDatums = (Datum *) palloc(ndatums * partnatts * sizeof(Datum));
- boundKinds = (PartitionRangeDatumKind *) palloc(ndatums * partnatts *
- sizeof(PartitionRangeDatumKind));
+ boundKinds = palloc_array(PartitionRangeDatumKind, ndatums * partnatts);
for (i = 0; i < ndatums; i++)
{
int nindexes;
int partnatts;
- dest = (PartitionBoundInfo) palloc(sizeof(PartitionBoundInfoData));
+ dest = (PartitionBoundInfo) palloc_object(PartitionBoundInfoData);
dest->strategy = src->strategy;
ndatums = dest->ndatums = src->ndatums;
/* List partitioned tables have only a single partition key. */
Assert(key->strategy != PARTITION_STRATEGY_LIST || partnatts == 1);
- dest->datums = (Datum **) palloc(sizeof(Datum *) * ndatums);
+ dest->datums = palloc_array(Datum *, ndatums);
if (src->kind != NULL && ndatums > 0)
{
}
}
- dest->indexes = (int *) palloc(sizeof(int) * nindexes);
+ dest->indexes = palloc_array(int, nindexes);
memcpy(dest->indexes, src->indexes, sizeof(int) * nindexes);
dest->null_index = src->null_index;
int i;
map->nparts = nparts;
- map->merged_indexes = (int *) palloc(sizeof(int) * nparts);
- map->merged = (bool *) palloc(sizeof(bool) * nparts);
+ map->merged_indexes = palloc_array(int, nparts);
+ map->merged = palloc_array(bool, nparts);
map->did_remapping = false;
- map->old_indexes = (int *) palloc(sizeof(int) * nparts);
+ map->old_indexes = palloc_array(int, nparts);
for (i = 0; i < nparts; i++)
{
map->merged_indexes[i] = map->old_indexes[i] = -1;
Assert(nmerged > 0);
- new_indexes = (int *) palloc(sizeof(int) * nmerged);
+ new_indexes = palloc_array(int, nmerged);
for (i = 0; i < nmerged; i++)
new_indexes[i] = -1;
Assert(*outer_parts == NIL);
Assert(*inner_parts == NIL);
- outer_indexes = (int *) palloc(sizeof(int) * nmerged);
- inner_indexes = (int *) palloc(sizeof(int) * nmerged);
+ outer_indexes = palloc_array(int, nmerged);
+ inner_indexes = palloc_array(int, nmerged);
for (i = 0; i < nmerged; i++)
outer_indexes[i] = inner_indexes[i] = -1;
int pos;
ListCell *lc;
- merged_bounds = (PartitionBoundInfo) palloc(sizeof(PartitionBoundInfoData));
+ merged_bounds = palloc_object(PartitionBoundInfoData);
merged_bounds->strategy = strategy;
merged_bounds->ndatums = ndatums;
- merged_bounds->datums = (Datum **) palloc(sizeof(Datum *) * ndatums);
+ merged_bounds->datums = palloc_array(Datum *, ndatums);
pos = 0;
foreach(lc, merged_datums)
merged_bounds->datums[pos++] = (Datum *) lfirst(lc);
if (strategy == PARTITION_STRATEGY_RANGE)
{
Assert(list_length(merged_kinds) == ndatums);
- merged_bounds->kind = (PartitionRangeDatumKind **)
- palloc(sizeof(PartitionRangeDatumKind *) * ndatums);
+ merged_bounds->kind = palloc_array(PartitionRangeDatumKind *, ndatums);
pos = 0;
foreach(lc, merged_kinds)
merged_bounds->kind[pos++] = (PartitionRangeDatumKind *) lfirst(lc);
Assert(list_length(merged_indexes) == ndatums);
merged_bounds->nindexes = ndatums;
- merged_bounds->indexes = (int *) palloc(sizeof(int) * ndatums);
+ merged_bounds->indexes = palloc_array(int, ndatums);
pos = 0;
foreach(lc, merged_indexes)
merged_bounds->indexes[pos++] = lfirst_int(lc);
Assert(datums != NIL);
- bound = (PartitionRangeBound *) palloc0(sizeof(PartitionRangeBound));
+ bound = palloc0_object(PartitionRangeBound);
bound->index = index;
- bound->datums = (Datum *) palloc0(key->partnatts * sizeof(Datum));
- bound->kind = (PartitionRangeDatumKind *) palloc0(key->partnatts *
- sizeof(PartitionRangeDatumKind));
+ bound->datums = palloc0_array(Datum, key->partnatts);
+ bound->kind = palloc0_array(PartitionRangeDatumKind, key->partnatts);
bound->lower = lower;
i = 0;
PartitionDirectory pdir;
HASHCTL ctl;
- pdir = palloc(sizeof(PartitionDirectoryData));
+ pdir = palloc_object(PartitionDirectoryData);
pdir->pdir_mcxt = mcxt;
ctl.keysize = sizeof(Oid);
*/
oldcxt = MemoryContextSwitchTo(resultcxt);
- avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
+ avdb = palloc_object(avw_dbase);
avdb->adw_datid = pgdatabase->oid;
avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
if (relopts == NULL)
return NULL;
- av = palloc(sizeof(AutoVacOpts));
+ av = palloc_object(AutoVacOpts);
memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
pfree(relopts);
? avopts->multixact_freeze_table_age
: default_multixact_freeze_table_age;
- tab = palloc(sizeof(autovac_table));
+ tab = palloc_object(autovac_table);
tab->at_relid = relid;
tab->at_sharedrel = classForm->relisshared;
*/
if (success && handle)
{
- *handle = palloc(sizeof(BackgroundWorkerHandle));
+ *handle = palloc_object(BackgroundWorkerHandle);
(*handle)->slot = slotno;
(*handle)->generation = generation;
}
num_requests = CheckpointerShmem->num_requests;
/* Initialize skip_slot array */
- skip_slot = palloc0(sizeof(bool) * max_requests);
+ skip_slot = palloc0_array(bool, max_requests);
head = CheckpointerShmem->head;
MyPMChildSlot = child_slot;
if (client_sock)
{
- MyClientSocket = palloc(sizeof(ClientSocket));
+ MyClientSocket = palloc_object(ClientSocket);
memcpy(MyClientSocket, client_sock, sizeof(ClientSocket));
}
PgArch->pgprocno = MyProcNumber;
/* Create workspace for pgarch_readyXlog() */
- arch_files = palloc(sizeof(struct arch_files_state));
+ arch_files = palloc_object(struct arch_files_state);
arch_files->arch_files_size = 0;
/* Initialize our max-heap for prioritizing files to archive. */
ereport(ERROR,
(errmsg("archive modules must register an archive callback")));
- archive_module_state = (ArchiveModuleState *) palloc0(sizeof(ArchiveModuleState));
+ archive_module_state = palloc0_object(ArchiveModuleState);
if (ArchiveCallbacks->startup_cb != NULL)
ArchiveCallbacks->startup_cb(archive_module_state);
{
win32_deadchild_waitinfo *childinfo;
- childinfo = palloc(sizeof(win32_deadchild_waitinfo));
+ childinfo = palloc_object(win32_deadchild_waitinfo);
childinfo->procHandle = procHandle;
childinfo->procId = procId;
* Need a free slot, but there isn't one in the list,
* so create a new one and extend the list with it.
*/
- free_slot = palloc(sizeof(save_buffer));
+ free_slot = palloc_object(save_buffer);
buffer_list = lappend(buffer_list, free_slot);
buffer_lists[p.pid % NBUFFER_LISTS] = buffer_list;
}
bool fast_forward = true;
/* Initialize private data for xlogreader. */
- private_data = (SummarizerReadLocalXLogPrivate *)
- palloc0(sizeof(SummarizerReadLocalXLogPrivate));
+ private_data = palloc0_object(SummarizerReadLocalXLogPrivate);
private_data->tli = tli;
private_data->historic = XLogRecPtrIsValid(switch_lsn);
private_data->read_upto = maximum_lsn;
Assert(i < lengthof(keys));
- conn = palloc0(sizeof(WalReceiverConn));
+ conn = palloc0_object(WalReceiverConn);
conn->streamConn =
libpqsrv_connect_params(keys, vals,
/* expand_dbname = */ true,
const int nRetTypes, const Oid *retTypes)
{
PGresult *pgres = NULL;
- WalRcvExecResult *walres = palloc0(sizeof(WalRcvExecResult));
+ WalRcvExecResult *walres = palloc0_object(WalRcvExecResult);
char *diag_sqlstate;
if (MyDatabaseId == InvalidOid)
*/
oldcontext = MemoryContextSwitchTo(ApplyContext);
- winfo = (ParallelApplyWorkerInfo *) palloc0(sizeof(ParallelApplyWorkerInfo));
+ winfo = palloc0_object(ParallelApplyWorkerInfo);
/* Setup shared memory. */
if (!pa_setup_dsm(winfo))
*/
oldcxt = MemoryContextSwitchTo(resultcxt);
- sub = (Subscription *) palloc0(sizeof(Subscription));
+ sub = palloc0_object(Subscription);
sub->oid = subform->oid;
sub->dbid = subform->subdbid;
sub->owner = subform->subowner;
"Logical decoding context",
ALLOCSET_DEFAULT_SIZES);
old_context = MemoryContextSwitchTo(context);
- ctx = palloc0(sizeof(LogicalDecodingContext));
+ ctx = palloc0_object(LogicalDecodingContext);
ctx->context = context;
arr = PG_GETARG_ARRAYTYPE_P(3);
/* state to write output to */
- p = palloc0(sizeof(DecodingOutputState));
+ p = palloc0_object(DecodingOutputState);
p->binary_output = binary;
LogicalRepRelation *
logicalrep_read_rel(StringInfo in)
{
- LogicalRepRelation *rel = palloc(sizeof(LogicalRepRelation));
+ LogicalRepRelation *rel = palloc_object(LogicalRepRelation);
rel->remoteid = pq_getmsgint(in, 4);
/* Allocate space for per-column values; zero out unused StringInfoDatas */
tuple->colvalues = (StringInfoData *) palloc0(natts * sizeof(StringInfoData));
- tuple->colstatus = (char *) palloc(natts * sizeof(char));
+ tuple->colstatus = palloc_array(char, natts);
tuple->ncols = natts;
/* Read the data */
Bitmapset *attkeys = NULL;
natts = pq_getmsgint(in, 2);
- attnames = palloc(natts * sizeof(char *));
- atttyps = palloc(natts * sizeof(Oid));
+ attnames = palloc_array(char *, natts);
+ atttyps = palloc_array(Oid, natts);
/* read the attributes */
for (i = 0; i < natts; i++)
entry->remoterel.nspname = pstrdup(remoterel->nspname);
entry->remoterel.relname = pstrdup(remoterel->relname);
entry->remoterel.natts = remoterel->natts;
- entry->remoterel.attnames = palloc(remoterel->natts * sizeof(char *));
- entry->remoterel.atttyps = palloc(remoterel->natts * sizeof(Oid));
+ entry->remoterel.attnames = palloc_array(char *, remoterel->natts);
+ entry->remoterel.atttyps = palloc_array(Oid, remoterel->natts);
for (i = 0; i < remoterel->natts; i++)
{
entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
entry->remoterel.nspname = pstrdup(remoterel->nspname);
entry->remoterel.relname = pstrdup(remoterel->relname);
entry->remoterel.natts = remoterel->natts;
- entry->remoterel.attnames = palloc(remoterel->natts * sizeof(char *));
- entry->remoterel.atttyps = palloc(remoterel->natts * sizeof(Oid));
+ entry->remoterel.attnames = palloc_array(char *, remoterel->natts);
+ entry->remoterel.atttyps = palloc_array(Oid, remoterel->natts);
for (i = 0; i < remoterel->natts; i++)
{
entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
change = ReorderBufferAllocChange(rb);
change->action = REORDER_BUFFER_CHANGE_INVALIDATION;
change->data.inval.ninvalidations = nmsgs;
- change->data.inval.invalidations = (SharedInvalidationMessage *)
- palloc(sizeof(SharedInvalidationMessage) * nmsgs);
+ change->data.inval.invalidations = palloc_array(SharedInvalidationMessage, nmsgs);
memcpy(change->data.inval.invalidations, msgs,
sizeof(SharedInvalidationMessage) * nmsgs);
if (*ninvals_out == 0)
{
*ninvals_out = nmsgs_new;
- *invals_out = (SharedInvalidationMessage *)
- palloc(sizeof(SharedInvalidationMessage) * nmsgs_new);
+ *invals_out = palloc_array(SharedInvalidationMessage, nmsgs_new);
memcpy(*invals_out, msgs_new, sizeof(SharedInvalidationMessage) * nmsgs_new);
}
else
return NULL;
/* Initialize XID array */
- xids = (TransactionId *) palloc(sizeof(TransactionId) *
- dclist_count(&rb->catchange_txns));
+ xids = palloc_array(TransactionId, dclist_count(&rb->catchange_txns));
dclist_foreach(iter, &rb->catchange_txns)
{
ReorderBufferTXN *txn = dclist_container(ReorderBufferTXN,
toast_desc = RelationGetDescr(toast_rel);
/* should we allocate from stack instead? */
- attrs = palloc0(sizeof(Datum) * desc->natts);
- isnull = palloc0(sizeof(bool) * desc->natts);
- free = palloc0(sizeof(bool) * desc->natts);
+ attrs = palloc0_array(Datum, desc->natts);
+ isnull = palloc0_array(bool, desc->natts);
+ free = palloc0_array(bool, desc->natts);
newtup = change->data.tp.newtuple;
continue;
/* ok, relevant, queue for apply */
- f = palloc(sizeof(RewriteMappingFile));
+ f = palloc_object(RewriteMappingFile);
f->lsn = f_lsn;
strcpy(f->fname, mapping_de->d_name);
files = lappend(files, f);
while (tuplestore_gettupleslot(res->tuplestore, true, false, tupslot))
{
bool isnull;
- RemoteSlot *remote_slot = palloc0(sizeof(RemoteSlot));
+ RemoteSlot *remote_slot = palloc0_object(RemoteSlot);
Datum d;
int col = 0;
ALLOCSET_DEFAULT_SIZES);
oldcontext = MemoryContextSwitchTo(context);
- builder = palloc0(sizeof(SnapBuild));
+ builder = palloc0_object(SnapBuild);
builder->state = SNAPBUILD_START;
builder->context = context;
MyProc->xmin = snap->xmin;
/* allocate in transaction context */
- newxip = (TransactionId *)
- palloc(sizeof(TransactionId) * GetMaxSnapshotXidCount());
+ newxip = palloc_array(TransactionId, GetMaxSnapshotXidCount());
/*
* snapbuild.c builds transactions in an "inverted" manner, which means it
has_subsequences_non_ready = true;
else
{
- rstate = palloc(sizeof(SubscriptionRelState));
+ rstate = palloc_object(SubscriptionRelState);
memcpy(rstate, subrel, sizeof(SubscriptionRelState));
table_states_not_ready = lappend(table_states_not_ready,
rstate);
List *perminfos = NIL;
ResultRelInfo *resultRelInfo;
- edata = (ApplyExecutionData *) palloc0(sizeof(ApplyExecutionData));
+ edata = palloc0_object(ApplyExecutionData);
edata->targetRel = rel;
edata->estate = estate = CreateExecutorState();
oldctx = MemoryContextSwitchTo(ApplyContext);
- MyLogicalRepWorker->stream_fileset = palloc(sizeof(FileSet));
+ MyLogicalRepWorker->stream_fileset = palloc_object(FileSet);
FileSetInit(MyLogicalRepWorker->stream_fileset);
MemoryContextSwitchTo(oldctx);
MemoryContextSwitchTo(ApplyContext);
/* Track commit lsn */
- flushpos = (FlushPosition *) palloc(sizeof(FlushPosition));
+ flushpos = palloc_object(FlushPosition);
flushpos->local_end = local_lsn;
flushpos->remote_end = remote_lsn;
pgoutput_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt,
bool is_init)
{
- PGOutputData *data = palloc0(sizeof(PGOutputData));
+ PGOutputData *data = palloc0_object(PGOutputData);
static bool publication_callback_registered = false;
MemoryContextCallback *mcallback;
* Ensure to cleanup RelationSyncCache even when logical decoding invoked
* via SQL interface ends up with an error.
*/
- mcallback = palloc0(sizeof(MemoryContextCallback));
+ mcallback = palloc0_object(MemoryContextCallback);
mcallback->func = pgoutput_memory_context_reset;
MemoryContextRegisterResetCallback(ctx->context, mcallback);
/* Should have enough candidates, or somebody messed up */
Assert(nth > 0 && nth <= num_standbys);
- write_array = (XLogRecPtr *) palloc(sizeof(XLogRecPtr) * num_standbys);
- flush_array = (XLogRecPtr *) palloc(sizeof(XLogRecPtr) * num_standbys);
- apply_array = (XLogRecPtr *) palloc(sizeof(XLogRecPtr) * num_standbys);
+ write_array = palloc_array(XLogRecPtr, num_standbys);
+ flush_array = palloc_array(XLogRecPtr, num_standbys);
+ apply_array = palloc_array(XLogRecPtr, num_standbys);
for (i = 0; i < num_standbys; i++)
{
int n;
/* Create result array */
- *standbys = (SyncRepStandbyData *)
- palloc(max_wal_senders * sizeof(SyncRepStandbyData));
+ *standbys = palloc_array(SyncRepStandbyData, max_wal_senders);
/* Quick exit if sync replication is not requested */
if (SyncRepConfig == NULL)
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
elog(ERROR, "return type must be a row type");
- values = palloc0(sizeof(Datum) * tupdesc->natts);
- nulls = palloc0(sizeof(bool) * tupdesc->natts);
+ values = palloc0_array(Datum, tupdesc->natts);
+ nulls = palloc0_array(bool, tupdesc->natts);
/* Fetch values */
values[0] = Int32GetDatum(pid);
static Interval *
offset_to_interval(TimeOffset offset)
{
- Interval *result = palloc(sizeof(Interval));
+ Interval *result = palloc_object(Interval);
result->month = 0;
result->day = 0;
RelationGetRelationName(rt_entry_relation))));
}
- rev = (rewrite_event *) palloc(sizeof(rewrite_event));
+ rev = palloc_object(rewrite_event);
rev->relation = RelationGetRelid(rt_entry_relation);
rev->event = event;
rewrite_events = lappend(rewrite_events, rev);
var->varlevelsup == context->sublevels_up)
{
/* Found a matching variable, make the substitution */
- Var *newvar = (Var *) palloc(sizeof(Var));
+ Var *newvar = palloc_object(Var);
int attno = var->varattno;
*newvar = *var; /* initially copy all fields of the Var */
context->to_rowtype != var->vartype)
{
ConvertRowtypeExpr *newnode;
- Var *newvar = (Var *) palloc(sizeof(Var));
+ Var *newvar = palloc_object(Var);
/* whole-row variable, warn caller */
*(context->found_whole_row) = true;
/* Var itself is changed to the requested type. */
newvar->vartype = context->to_rowtype;
- newnode = (ConvertRowtypeExpr *) palloc(sizeof(ConvertRowtypeExpr));
+ newnode = palloc_object(ConvertRowtypeExpr);
*newnode = *r; /* initially copy all fields of the CRE */
newnode->arg = (Expr *) newvar;
bool stoploaded = false;
ListCell *l;
- d = (DictSnowball *) palloc0(sizeof(DictSnowball));
+ d = palloc0_object(DictSnowball);
foreach(l, dictoptions)
{
char *in = (char *) PG_GETARG_POINTER(1);
int32 len = PG_GETARG_INT32(2);
char *txt = str_tolower(in, len, DEFAULT_COLLATION_OID);
- TSLexeme *res = palloc0(sizeof(TSLexeme) * 2);
+ TSLexeme *res = palloc0_array(TSLexeme, 2);
/*
* Do not pass strings exceeding 1000 bytes to the stemmer, as they're
static void
generate_dependencies(DependencyGenerator state)
{
- AttrNumber *current = (AttrNumber *) palloc0(sizeof(AttrNumber) * state->k);
+ AttrNumber *current = palloc0_array(AttrNumber, state->k);
generate_dependencies_recurse(state, 0, 0, current);
Assert((n >= k) && (k > 0));
/* allocate the DependencyGenerator state */
- state = (DependencyGenerator) palloc0(sizeof(DependencyGeneratorData));
- state->dependencies = (AttrNumber *) palloc(k * sizeof(AttrNumber));
+ state = palloc0_object(DependencyGeneratorData);
+ state->dependencies = palloc_array(AttrNumber, k);
state->ndependencies = 0;
state->current = 0;
* Translate the array of indexes to regular attnums for the dependency
* (we will need this to identify the columns in StatsBuildData).
*/
- attnums_dep = (AttrNumber *) palloc(k * sizeof(AttrNumber));
+ attnums_dep = palloc_array(AttrNumber, k);
for (i = 0; i < k; i++)
attnums_dep[i] = data->attnums[dependency[i]];
/* initialize the list of dependencies */
if (dependencies == NULL)
{
- dependencies
- = (MVDependencies *) palloc0(sizeof(MVDependencies));
+ dependencies = palloc0_object(MVDependencies);
dependencies->magic = STATS_DEPS_MAGIC;
dependencies->type = STATS_DEPS_TYPE_BASIC;
VARSIZE_ANY_EXHDR(data), SizeOfHeader);
/* read the MVDependencies header */
- dependencies = (MVDependencies *) palloc0(sizeof(MVDependencies));
+ dependencies = palloc0_object(MVDependencies);
/* initialize pointer to the data part (skip the varlena header) */
tmp = VARDATA_ANY(data);
* and mark all the corresponding clauses as estimated.
*/
nattrs = bms_num_members(attnums);
- attr_sel = (Selectivity *) palloc(sizeof(Selectivity) * nattrs);
+ attr_sel = palloc_array(Selectivity, nattrs);
attidx = 0;
i = -1;
if (!has_stats_of_kind(rel->statlist, STATS_EXT_DEPENDENCIES))
return 1.0;
- list_attnums = (AttrNumber *) palloc(sizeof(AttrNumber) *
- list_length(clauses));
+ list_attnums = palloc_array(AttrNumber, list_length(clauses));
/*
* We allocate space as if every clause was a unique expression, although
* we'll translate to attnums, and there might be duplicates. But it's
* easier and cheaper to just do one allocation than repalloc later.
*/
- unique_exprs = (Node **) palloc(sizeof(Node *) * list_length(clauses));
+ unique_exprs = palloc_array(Node *, list_length(clauses));
unique_exprs_cnt = 0;
/*
* make it just the right size, but it's likely wasteful anyway thanks to
* moving the freed chunks to freelists etc.
*/
- func_dependencies = (MVDependencies **) palloc(sizeof(MVDependencies *) *
- list_length(rel->statlist));
+ func_dependencies = palloc_array(MVDependencies *, list_length(rel->statlist));
nfunc_dependencies = 0;
total_ndeps = 0;
* Work out which dependencies we can apply, starting with the
* widest/strongest ones, and proceeding to smaller/weaker ones.
*/
- dependencies = (MVDependency **) palloc(sizeof(MVDependency *) *
- total_ndeps);
+ dependencies = palloc_array(MVDependency *, total_ndeps);
ndependencies = 0;
while (true)
Form_pg_statistic_ext staForm;
List *exprs = NIL;
- entry = palloc0(sizeof(StatExtEntry));
+ entry = palloc0_object(StatExtEntry);
staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
entry->statOid = staForm->oid;
entry->schema = get_namespace_name(staForm->stxnamespace);
/*
* Create the VacAttrStats struct.
*/
- stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
+ stats = palloc0_object(VacAttrStats);
stats->attstattarget = -1;
/*
/*
* Create the VacAttrStats struct.
*/
- stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
+ stats = palloc0_object(VacAttrStats);
/*
* We can't have statistics target specified for the expression, so we
*numattrs = num;
/* build attnums from the bitmapset */
- attnums = (AttrNumber *) palloc(sizeof(AttrNumber) * num);
+ attnums = palloc_array(AttrNumber, num);
i = 0;
j = -1;
while ((j = bms_next_member(attrs, j)) >= 0)
}
/* build a local cache of typlen for all attributes */
- typlen = (int *) palloc(sizeof(int) * data->nattnums);
+ typlen = palloc_array(int, data->nattnums);
for (i = 0; i < data->nattnums; i++)
typlen[i] = get_typlen(data->stats[i]->attrtypid);
if (!has_stats_of_kind(rel->statlist, STATS_EXT_MCV))
return sel;
- list_attnums = (Bitmapset **) palloc(sizeof(Bitmapset *) *
- list_length(clauses));
+ list_attnums = palloc_array(Bitmapset *, list_length(clauses));
/* expressions extracted from complex expressions */
- list_exprs = (List **) palloc(sizeof(Node *) * list_length(clauses));
+ list_exprs = palloc_array(List *, list_length(clauses));
/*
* Pre-process the clauses list to extract the attnums and expressions
+ sizeof(SortSupportData));
/* compute frequencies for values in each column */
- nfreqs = (int *) palloc0(sizeof(int) * numattrs);
+ nfreqs = palloc0_array(int, numattrs);
freqs = build_column_frequencies(groups, ngroups, mss, nfreqs);
/*
/* just point to the proper place in the list */
MCVItem *item = &mcvlist->items[i];
- item->values = (Datum *) palloc(sizeof(Datum) * numattrs);
- item->isnull = (bool *) palloc(sizeof(bool) * numattrs);
+ item->values = palloc_array(Datum, numattrs);
+ item->isnull = palloc_array(bool, numattrs);
/* copy values for the group */
memcpy(item->values, groups[i].values, sizeof(Datum) * numattrs);
char *endptr PG_USED_FOR_ASSERTS_ONLY;
/* values per dimension (and number of non-NULL values) */
- Datum **values = (Datum **) palloc0(sizeof(Datum *) * ndims);
- int *counts = (int *) palloc0(sizeof(int) * ndims);
+ Datum **values = palloc0_array(Datum *, ndims);
+ int *counts = palloc0_array(int, ndims);
/*
* We'll include some rudimentary information about the attribute types
* the statistics gets dropped automatically. We need to store the info
* about the arrays of deduplicated values anyway.
*/
- info = (DimensionInfo *) palloc0(sizeof(DimensionInfo) * ndims);
+ info = palloc0_array(DimensionInfo, ndims);
/* sort support data for all attributes included in the MCV list */
- ssup = (SortSupport) palloc0(sizeof(SortSupportData) * ndims);
+ ssup = palloc0_array(SortSupportData, ndims);
/* collect and deduplicate values for each dimension (attribute) */
for (dim = 0; dim < ndims; dim++)
info[dim].typbyval = stats[dim]->attrtype->typbyval;
/* allocate space for values in the attribute and collect them */
- values[dim] = (Datum *) palloc0(sizeof(Datum) * mcvlist->nitems);
+ values[dim] = palloc0_array(Datum, mcvlist->nitems);
for (i = 0; i < mcvlist->nitems; i++)
{
* original values (it might go away).
*/
datalen = 0; /* space for by-ref data */
- map = (Datum **) palloc(ndims * sizeof(Datum *));
+ map = palloc_array(Datum *, ndims);
for (dim = 0; dim < ndims; dim++)
{
- map[dim] = (Datum *) palloc(sizeof(Datum) * info[dim].nvalues);
+ map[dim] = palloc_array(Datum, info[dim].nvalues);
/* space needed for a copy of data for by-ref types */
datalen += info[dim].nbytes_aligned;
Assert(mcvlist->nitems > 0);
Assert(mcvlist->nitems <= STATS_MCVLIST_MAX_ITEMS);
- matches = palloc(sizeof(bool) * mcvlist->nitems);
+ matches = palloc_array(bool, mcvlist->nitems);
memset(matches, !is_or, sizeof(bool) * mcvlist->nitems);
/*
/* build the OR-matches bitmap, if not built already */
if (*or_matches == NULL)
- *or_matches = palloc0(sizeof(bool) * mcv->nitems);
+ *or_matches = palloc0_array(bool, mcv->nitems);
/* build the match bitmap for the new clause */
new_matches = mcv_get_match_bitmap(root, list_make1(clause), stat->keys,
static BufFile *
makeBufFileCommon(int nfiles)
{
- BufFile *file = (BufFile *) palloc(sizeof(BufFile));
+ BufFile *file = palloc_object(BufFile);
file->numFiles = nfiles;
file->isInterXact = false;
{
BufFile *file = makeBufFileCommon(1);
- file->files = (File *) palloc(sizeof(File));
+ file->files = palloc_object(File);
file->files[0] = firstfile;
file->readOnly = false;
file->fileset = NULL;
file = makeBufFileCommon(1);
file->fileset = fileset;
file->name = pstrdup(name);
- file->files = (File *) palloc(sizeof(File));
+ file->files = palloc_object(File);
file->files[0] = MakeNewFileSetSegment(file, 0);
file->readOnly = false;
File *files;
int nfiles = 0;
- files = palloc(sizeof(File) * capacity);
+ files = palloc_array(File, capacity);
/*
* We don't know how many segments there are, so we'll probe the
if (nfiles + 1 > capacity)
{
capacity *= 2;
- files = repalloc(files, sizeof(File) * capacity);
+ files = repalloc_array(files, File, capacity);
}
/* Try to load a segment. */
FileSetSegmentName(segment_name, name, nfiles);
* Allocate a temporary array to avoid modifying the array passed as
* argument.
*/
- xids = palloc(sizeof(TransactionId) * (running->xcnt + running->subxcnt));
+ xids = palloc_array(TransactionId, running->xcnt + running->subxcnt);
/*
* Add to the temp array any xids which have not already completed.
Assert(type != 0);
/* allocate what's certainly enough result space */
- vxids = (VirtualTransactionId *)
- palloc(sizeof(VirtualTransactionId) * arrayP->maxProcs);
+ vxids = palloc_array(VirtualTransactionId, arrayP->maxProcs);
LWLockAcquire(ProcArrayLock, LW_SHARED);
int index;
/* allocate what's certainly enough result space */
- vxids = (VirtualTransactionId *)
- palloc(sizeof(VirtualTransactionId) * arrayP->maxProcs);
+ vxids = palloc_array(VirtualTransactionId, arrayP->maxProcs);
LWLockAcquire(ProcArrayLock, LW_SHARED);
shm_mq_handle *
shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
{
- shm_mq_handle *mqh = palloc(sizeof(shm_mq_handle));
+ shm_mq_handle *mqh = palloc_object(shm_mq_handle);
Assert(mq->mq_receiver == MyProc || mq->mq_sender == MyProc);
mqh->mqh_queue = mq;
InitMaterializedSRF(fcinfo, 0);
max_nodes = pg_numa_get_max_node();
- nodes = palloc(sizeof(Size) * (max_nodes + 1));
+ nodes = palloc_array(Size, max_nodes + 1);
/*
* Shared memory allocations can vary in size and may not align with OS
* them using only fraction of the total pages.
*/
shm_total_page_count = (ShmemSegHdr->totalsize / os_page_size) + 1;
- page_ptrs = palloc0(sizeof(void *) * shm_total_page_count);
- pages_status = palloc(sizeof(int) * shm_total_page_count);
+ page_ptrs = palloc0_array(void *, shm_total_page_count);
+ pages_status = palloc_array(int, shm_total_page_count);
if (firstNumaTouch)
elog(DEBUG1, "NUMA: page-faulting shared memory segments for proper NUMA readouts");
(MaxBackends + max_prepared_xacts + 1));
}
else
- vxids = (VirtualTransactionId *)
- palloc0(sizeof(VirtualTransactionId) *
- (MaxBackends + max_prepared_xacts + 1));
+ vxids = palloc0_array(VirtualTransactionId, (MaxBackends + max_prepared_xacts + 1));
/* Compute hash code and partition lock, and look up conflicting modes. */
hashcode = LockTagHashCode(locktag);
int el;
int i;
- data = (LockData *) palloc(sizeof(LockData));
+ data = palloc_object(LockData);
/* Guess how much space we'll need. */
els = MaxBackends;
el = 0;
- data->locks = (LockInstanceData *) palloc(sizeof(LockInstanceData) * els);
+ data->locks = palloc_array(LockInstanceData, els);
/*
* First, we iterate through the per-backend fast-path arrays, locking
PGPROC *proc;
int i;
- data = (BlockedProcsData *) palloc(sizeof(BlockedProcsData));
+ data = palloc_object(BlockedProcsData);
/*
* Guess how much space we'll need, and preallocate. Most of the time
*/
data->nprocs = data->nlocks = data->npids = 0;
data->maxprocs = data->maxlocks = data->maxpids = MaxBackends;
- data->procs = (BlockedProcData *) palloc(sizeof(BlockedProcData) * data->maxprocs);
- data->locks = (LockInstanceData *) palloc(sizeof(LockInstanceData) * data->maxlocks);
- data->waiter_pids = (int *) palloc(sizeof(int) * data->maxpids);
+ data->procs = palloc_array(BlockedProcData, data->maxprocs);
+ data->locks = palloc_array(LockInstanceData, data->maxlocks);
+ data->waiter_pids = palloc_array(int, data->maxpids);
/*
* In order to search the ProcArray for blocked_pid and assume that that
HASH_SEQ_STATUS seqstat;
PREDICATELOCK *predlock;
- data = (PredicateLockData *) palloc(sizeof(PredicateLockData));
+ data = palloc_object(PredicateLockData);
/*
* To ensure consistency, take simultaneous locks on all partition locks
/* Get number of locks and allocate appropriately-sized arrays. */
els = hash_get_num_entries(PredicateLockHash);
data->nelements = els;
- data->locktags = (PREDICATELOCKTARGETTAG *)
- palloc(sizeof(PREDICATELOCKTARGETTAG) * els);
- data->xacts = (SERIALIZABLEXACT *)
- palloc(sizeof(SERIALIZABLEXACT) * els);
+ data->locktags = palloc_array(PREDICATELOCKTARGETTAG, els);
+ data->xacts = palloc_array(SERIALIZABLEXACT, els);
/* Scan through PredicateLockHash and copy contents */
{
BulkWriteState *state;
- state = palloc(sizeof(BulkWriteState));
+ state = palloc_object(BulkWriteState);
state->smgr = smgr;
state->forknum = forknum;
state->use_wal = use_wal;
SMgrRelation *srels;
int i;
- srels = palloc(sizeof(SMgrRelation) * ndelrels);
+ srels = palloc_array(SMgrRelation, ndelrels);
for (i = 0; i < ndelrels; i++)
{
SMgrRelation srel = smgropen(delrels[i], INVALID_PROC_NUMBER);
* create an array which contains all relations to be dropped, and close
* each relation's forks at the smgr level while at it
*/
- rlocators = palloc(sizeof(RelFileLocatorBackend) * nrels);
+ rlocators = palloc_array(RelFileLocatorBackend, nrels);
for (i = 0; i < nrels; i++)
{
RelFileLocatorBackend rlocator = rels[i]->smgr_rlocator;
MemoryContext oldcxt = MemoryContextSwitchTo(pendingOpsCxt);
PendingUnlinkEntry *entry;
- entry = palloc(sizeof(PendingUnlinkEntry));
+ entry = palloc_object(PendingUnlinkEntry);
entry->tag = *ftag;
entry->cycle_ctr = checkpoint_cycle_ctr;
entry->canceled = false;
QueryEnvironment *queryEnv,
int instrument_options)
{
- QueryDesc *qd = (QueryDesc *) palloc(sizeof(QueryDesc));
+ QueryDesc *qd = palloc_object(QueryDesc);
qd->operation = plannedstmt->commandType; /* operation */
qd->plannedstmt = plannedstmt; /* plan */
ptr = res;
while (ptr->lexeme)
ptr++;
- da = (Datum *) palloc(sizeof(Datum) * (ptr - res));
+ da = (Datum *) palloc_array(Datum, ptr - res);
ptr = res;
while (ptr->lexeme)
{
stoploaded = false;
ListCell *l;
- d = (DictISpell *) palloc0(sizeof(DictISpell));
+ d = palloc0_object(DictISpell);
NIStartBuild(&(d->obj));
dsimple_init(PG_FUNCTION_ARGS)
{
List *dictoptions = (List *) PG_GETARG_POINTER(0);
- DictSimple *d = (DictSimple *) palloc0(sizeof(DictSimple));
+ DictSimple *d = palloc0_object(DictSimple);
bool stoploaded = false,
acceptloaded = false;
ListCell *l;
{
/* reject as stopword */
pfree(txt);
- res = palloc0(sizeof(TSLexeme) * 2);
+ res = palloc0_array(TSLexeme, 2);
PG_RETURN_POINTER(res);
}
else if (d->accept)
{
/* accept */
- res = palloc0(sizeof(TSLexeme) * 2);
+ res = palloc0_array(TSLexeme, 2);
res[0].lexeme = txt;
PG_RETURN_POINTER(res);
}
errmsg("could not open synonym file \"%s\": %m",
filename)));
- d = (DictSyn *) palloc0(sizeof(DictSyn));
+ d = palloc0_object(DictSyn);
while ((line = tsearch_readline(&trst)) != NULL)
{
if (d->len == 0)
{
d->len = 64;
- d->syn = (Syn *) palloc(sizeof(Syn) * d->len);
+ d->syn = palloc_array(Syn, d->len);
}
else
{
d->len *= 2;
- d->syn = (Syn *) repalloc(d->syn, sizeof(Syn) * d->len);
+ d->syn = repalloc_array(d->syn, Syn, d->len);
}
}
if (!found)
PG_RETURN_POINTER(NULL);
- res = palloc0(sizeof(TSLexeme) * 2);
+ res = palloc0_array(TSLexeme, 2);
res[0].lexeme = pnstrdup(found->out, found->outlen);
res[0].flags = found->flags;
if (d->ntwrds == 0)
{
d->ntwrds = 16;
- d->wrds = (TheLexeme *) palloc(sizeof(TheLexeme) * d->ntwrds);
+ d->wrds = palloc_array(TheLexeme, d->ntwrds);
}
else
{
d->ntwrds *= 2;
- d->wrds = (TheLexeme *) repalloc(d->wrds, sizeof(TheLexeme) * d->ntwrds);
+ d->wrds = repalloc_array(d->wrds, TheLexeme, d->ntwrds);
}
}
memcpy(ptr->lexeme, b, e - b);
ptr->lexeme[e - b] = '\0';
- ptr->entries = (LexemeInfo *) palloc(sizeof(LexemeInfo));
+ ptr->entries = palloc_object(LexemeInfo);
ptr->entries->nextentry = NULL;
ptr->entries->idsubst = idsubst;
if (d->nsubst == 0)
{
d->nsubst = 16;
- d->subst = (TheSubstitute *) palloc(sizeof(TheSubstitute) * d->nsubst);
+ d->subst = palloc_array(TheSubstitute, d->nsubst);
}
else
{
d->nsubst *= 2;
- d->subst = (TheSubstitute *) repalloc(d->subst, sizeof(TheSubstitute) * d->nsubst);
+ d->subst = repalloc_array(d->subst, TheSubstitute, d->nsubst);
}
}
}
if (ntres == 0)
{
ntres = 2;
- ptr->res = (TSLexeme *) palloc(sizeof(TSLexeme) * ntres);
+ ptr->res = palloc_array(TSLexeme, ntres);
}
else
{
ntres *= 2;
- ptr->res = (TSLexeme *) repalloc(ptr->res, sizeof(TSLexeme) * ntres);
+ ptr->res = repalloc_array(ptr->res, TSLexeme, ntres);
}
}
newwrds = (TheLexeme *) repalloc(newwrds, sizeof(TheLexeme) * *tnm);
}
- newwrds[*nnw].entries = (LexemeInfo *) palloc(sizeof(LexemeInfo));
+ newwrds[*nnw].entries = palloc_object(LexemeInfo);
if (lexeme && lexeme->lexeme)
{
int i,
nnw = 0,
tnm = 16;
- TheLexeme *newwrds = (TheLexeme *) palloc(sizeof(TheLexeme) * tnm),
+ TheLexeme *newwrds = palloc_array(TheLexeme, tnm),
*ptrwrds;
for (i = 0; i < d->nwrds; i++)
*inptr;
int n = 2;
- outptr = d->subst[i].res = (TSLexeme *) palloc(sizeof(TSLexeme) * n);
+ outptr = d->subst[i].res = palloc_array(TSLexeme, n);
outptr->lexeme = NULL;
inptr = rem;
List *namelist;
ListCell *l;
- d = (DictThesaurus *) palloc0(sizeof(DictThesaurus));
+ d = palloc0_object(DictThesaurus);
foreach(l, dictoptions)
{
TSLexeme *res;
uint16 i;
- res = (TSLexeme *) palloc(sizeof(TSLexeme) * (ts->reslen + 1));
+ res = palloc_array(TSLexeme, ts->reslen + 1);
for (i = 0; i < ts->reslen; i++)
{
res[i] = ts->res[i];
ptr++;
}
- infos = (LexemeInfo **) palloc(sizeof(LexemeInfo *) * nlex);
+ infos = palloc_array(LexemeInfo *, nlex);
for (i = 0; i < nlex; i++)
if ((infos[i] = findTheLexeme(d, basevar[i].lexeme)) == NULL)
break;
else
{
Conf->maffixes = 16;
- Conf->Affix = (AFFIX *) palloc(Conf->maffixes * sizeof(AFFIX));
+ Conf->Affix = palloc_array(AFFIX, Conf->maffixes);
}
}
* allocated in the dictionary's memory context, and will be freed
* automatically when it is destroyed.
*/
- Affix->reg.pregex = palloc(sizeof(regex_t));
+ Affix->reg.pregex = palloc_object(regex_t);
err = pg_regcomp(Affix->reg.pregex, wmask, wmasklen,
REG_ADVANCED | REG_NOSUB,
DEFAULT_COLLATION_OID);
/* Also reserve place for empty flag set */
naffix++;
- Conf->AffixData = (const char **) palloc0(naffix * sizeof(char *));
+ Conf->AffixData = palloc0_array(const char *, naffix);
Conf->lenAffixData = Conf->nAffixData = naffix;
/* Add empty flag set into AffixData */
* dictionary. Replace textual flag-field of Conf->Spell entries with
* indexes into Conf->AffixData array.
*/
- Conf->AffixData = (const char **) palloc0(naffix * sizeof(const char *));
+ Conf->AffixData = palloc0_array(const char *, naffix);
curaffix = -1;
for (i = 0; i < Conf->nspell; i++)
/* Store compound affixes in the Conf->CompoundAffix array */
if (Conf->naffixes > 1)
qsort(Conf->Affix, Conf->naffixes, sizeof(AFFIX), cmpaffix);
- Conf->CompoundAffix = ptr = (CMPDAffix *) palloc(sizeof(CMPDAffix) * Conf->naffixes);
+ Conf->CompoundAffix = ptr = palloc_array(CMPDAffix, Conf->naffixes);
ptr->affix = NULL;
for (i = 0; i < Conf->naffixes; i++)
/* Convert data string to wide characters */
newword_len = strlen(newword);
- data = (pg_wchar *) palloc((newword_len + 1) * sizeof(pg_wchar));
+ data = palloc_array(pg_wchar, newword_len + 1);
data_len = pg_mb2wchar_with_len(newword, data, newword_len);
if (pg_regexec(Affix->reg.pregex, data, data_len,
if (wrdlen > MAXNORMLEN)
return NULL;
- cur = forms = (char **) palloc(MAX_NORM * sizeof(char *));
+ cur = forms = palloc_array(char *, MAX_NORM);
*cur = NULL;
static SplitVar *
CopyVar(SplitVar *s, int makedup)
{
- SplitVar *v = (SplitVar *) palloc(sizeof(SplitVar));
+ SplitVar *v = palloc_object(SplitVar);
v->next = NULL;
if (s)
int i;
v->lenstem = s->lenstem;
- v->stem = (char **) palloc(sizeof(char *) * v->lenstem);
+ v->stem = palloc_array(char *, v->lenstem);
v->nstem = s->nstem;
for (i = 0; i < s->nstem; i++)
v->stem[i] = (makedup) ? pstrdup(s->stem[i]) : s->stem[i];
else
{
v->lenstem = 16;
- v->stem = (char **) palloc(sizeof(char *) * v->lenstem);
+ v->stem = palloc_array(char *, v->lenstem);
v->nstem = 0;
}
return v;
addNorm(TSLexeme **lres, TSLexeme **lcur, char *word, int flags, uint16 NVariant)
{
if (*lres == NULL)
- *lcur = *lres = (TSLexeme *) palloc(MAX_NORM * sizeof(TSLexeme));
+ *lcur = *lres = palloc_array(TSLexeme, MAX_NORM);
if (*lcur - *lres < MAX_NORM - 1)
{
{
tmppos = LIMITPOS(a->pos.pos);
a->alen = 2;
- a->pos.apos = (uint16 *) palloc(sizeof(uint16) * a->alen);
+ a->pos.apos = palloc_array(uint16, a->alen);
a->pos.apos[0] = 1;
a->pos.apos[1] = tmppos;
return l;
*/
tmppos = LIMITPOS(a->pos.pos);
a->alen = 2;
- a->pos.apos = (uint16 *) palloc(sizeof(uint16) * a->alen);
+ a->pos.apos = palloc_array(uint16, a->alen);
a->pos.apos[0] = 1;
a->pos.apos[1] = tmppos;
res->word = ptr->word;
tmppos = LIMITPOS(ptr->pos.pos);
res->alen = 2;
- res->pos.apos = (uint16 *) palloc(sizeof(uint16) * res->alen);
+ res->pos.apos = palloc_array(uint16, res->alen);
res->pos.apos[0] = 1;
res->pos.apos[1] = tmppos;
}
if (res->pos.apos[0] + 1 >= res->alen)
{
res->alen *= 2;
- res->pos.apos = (uint16 *) repalloc(res->pos.apos, sizeof(uint16) * res->alen);
+ res->pos.apos = repalloc_array(res->pos.apos, uint16, res->alen);
}
if (res->pos.apos[0] == 0 || res->pos.apos[res->pos.apos[0]] != LIMITPOS(ptr->pos.pos))
{
prs.lenwords = MaxAllocSize / sizeof(ParsedWord);
prs.curwords = 0;
prs.pos = 0;
- prs.words = (ParsedWord *) palloc(sizeof(ParsedWord) * prs.lenwords);
+ prs.words = palloc_array(ParsedWord, prs.lenwords);
parsetext(cfgId, &prs, VARDATA_ANY(in), VARSIZE_ANY_EXHDR(in));
* (parsetext() will realloc it bigger as needed.)
*/
prs->lenwords = 16;
- prs->words = (ParsedWord *) palloc(sizeof(ParsedWord) * prs->lenwords);
+ prs->words = palloc_array(ParsedWord, prs->lenwords);
prs->curwords = 0;
prs->pos = 0;
}
prs.lenwords = 4;
prs.curwords = 0;
prs.pos = 0;
- prs.words = (ParsedWord *) palloc(sizeof(ParsedWord) * prs.lenwords);
+ prs.words = palloc_array(ParsedWord, prs.lenwords);
parsetext(data->cfg_id, &prs, strval, lenval);
static void
LexizeAddLemm(LexizeData *ld, int type, char *lemm, int lenlemm)
{
- ParsedLex *newpl = (ParsedLex *) palloc(sizeof(ParsedLex));
+ ParsedLex *newpl = palloc_object(ParsedLex);
newpl->type = type;
newpl->lemm = lemm;
/*
* Transpose the data into a single array so we can use bsearch().
*/
- lookup = (TextFreq *) palloc(sizeof(TextFreq) * nmcelem);
+ lookup = palloc_array(TextFreq, nmcelem);
for (i = 0; i < nmcelem; i++)
{
/*
cutoff_freq = 9 * lexeme_no / bucket_width;
i = hash_get_num_entries(lexemes_tab); /* surely enough space */
- sort_table = (TrackItem **) palloc(sizeof(TrackItem *) * i);
+ sort_table = palloc_array(TrackItem *, i);
hash_seq_init(&scan_status, lexemes_tab);
track_len = 0;
* create that for a tsvector column, since null elements aren't
* possible.)
*/
- mcelem_values = (Datum *) palloc(num_mcelem * sizeof(Datum));
- mcelem_freqs = (float4 *) palloc((num_mcelem + 2) * sizeof(float4));
+ mcelem_values = palloc_array(Datum, num_mcelem);
+ mcelem_freqs = palloc_array(float4, num_mcelem + 2);
/*
* See comments above about use of nonnull_cnt as the divisor for
if (reallen == 0)
{
reallen = 64;
- stop = (char **) palloc(sizeof(char *) * reallen);
+ stop = palloc_array(char *, reallen);
}
else
{
reallen *= 2;
- stop = (char **) repalloc(stop, sizeof(char *) * reallen);
+ stop = repalloc_array(stop, char *, reallen);
}
}
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
- st = (TSTokenTypeStorage *) palloc(sizeof(TSTokenTypeStorage));
+ st = palloc_object(TSTokenTypeStorage);
st->cur = 0;
/* lextype takes one dummy argument */
st->list = (LexDescr *) DatumGetPointer(OidFunctionCall1(prs->lextypeOid,
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
- st = (PrsStorage *) palloc(sizeof(PrsStorage));
+ st = palloc_object(PrsStorage);
st->cur = 0;
st->len = 16;
- st->list = (LexemeEntry *) palloc(sizeof(LexemeEntry) * st->len);
+ st->list = palloc_array(LexemeEntry, st->len);
prsdata = DatumGetPointer(FunctionCall2(&prs->prsstart,
PointerGetDatum(VARDATA_ANY(txt)),
memset(&prs, 0, sizeof(HeadlineParsedText));
prs.lenwords = 32;
- prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords);
+ prs.words = palloc_array(HeadlineWordEntry, prs.lenwords);
hlparsetext(cfg->cfgId, &prs, query,
VARDATA_ANY(in), VARSIZE_ANY_EXHDR(in));
Jsonb *out;
JsonTransformStringValuesAction action = (JsonTransformStringValuesAction) headline_json_value;
HeadlineParsedText prs;
- HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState));
+ HeadlineJsonState *state = palloc0_object(HeadlineJsonState);
memset(&prs, 0, sizeof(HeadlineParsedText));
prs.lenwords = 32;
- prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords);
+ prs.words = palloc_array(HeadlineWordEntry, prs.lenwords);
state->prs = &prs;
state->cfg = lookup_ts_config_cache(tsconfig);
JsonTransformStringValuesAction action = (JsonTransformStringValuesAction) headline_json_value;
HeadlineParsedText prs;
- HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState));
+ HeadlineJsonState *state = palloc0_object(HeadlineJsonState);
memset(&prs, 0, sizeof(HeadlineParsedText));
prs.lenwords = 32;
- prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords);
+ prs.words = palloc_array(HeadlineWordEntry, prs.lenwords);
state->prs = &prs;
state->cfg = lookup_ts_config_cache(tsconfig);
static TParserPosition *
newTParserPosition(TParserPosition *prev)
{
- TParserPosition *res = (TParserPosition *) palloc(sizeof(TParserPosition));
+ TParserPosition *res = palloc_object(TParserPosition);
if (prev)
memcpy(res, prev, sizeof(TParserPosition));
static TParser *
TParserInit(char *str, int len)
{
- TParser *prs = (TParser *) palloc0(sizeof(TParser));
+ TParser *prs = palloc0_object(TParser);
prs->charmaxlen = pg_database_encoding_max_length();
prs->str = str;
prs->lenstr = len;
- prs->pgwstr = (pg_wchar *) palloc(sizeof(pg_wchar) * (prs->lenstr + 1));
+ prs->pgwstr = palloc_array(pg_wchar, prs->lenstr + 1);
pg_mb2wchar_with_len(prs->str, prs->pgwstr, prs->lenstr);
prs->state = newTParserPosition(NULL);
static TParser *
TParserCopyInit(const TParser *orig)
{
- TParser *prs = (TParser *) palloc0(sizeof(TParser));
+ TParser *prs = palloc0_object(TParser);
prs->charmaxlen = orig->charmaxlen;
prs->str = orig->str + orig->state->posbyte;
Datum
prsd_lextype(PG_FUNCTION_ARGS)
{
- LexDescr *descr = (LexDescr *) palloc(sizeof(LexDescr) * (LASTNUM + 1));
+ LexDescr *descr = palloc_array(LexDescr, LASTNUM + 1);
int i;
for (i = 1; i <= LASTNUM; i++)
if (!data->pos)
{
- data->pos = palloc(sizeof(WordEntryPos) * checkval->len);
+ data->pos = palloc_array(WordEntryPos, checkval->len);
data->allocated = true;
data->npos = 1;
data->pos[0] = checkval->words[i].pos;
}
tabentry = (PgStat_TableStatus *) entry_ref->pending;
- tablestatus = palloc(sizeof(PgStat_TableStatus));
+ tablestatus = palloc_object(PgStat_TableStatus);
*tablestatus = *tabentry;
/*
els = hash_get_num_entries(WaitEventCustomHashByName);
/* Allocate enough space for all entries */
- waiteventnames = palloc(els * sizeof(char *));
+ waiteventnames = palloc_array(char *, els);
/* Now scan the hash table to copy the data */
hash_seq_init(&hash_seq, WaitEventCustomHashByName);
Node *escontext = fcinfo->context;
AclItem *aip;
- aip = (AclItem *) palloc(sizeof(AclItem));
+ aip = palloc_object(AclItem);
s = aclparse(s, aip, escontext);
if (s == NULL)
priv = convert_any_priv_string(privtext, any_priv_map);
- result = (AclItem *) palloc(sizeof(AclItem));
+ result = palloc_object(AclItem);
result->ai_grantee = grantee;
result->ai_grantor = grantor;
funcctx->tuple_desc = BlessTupleDesc(tupdesc);
/* allocate memory for user context */
- idx = (int *) palloc(sizeof(int[2]));
+ idx = palloc_array(int, 2);
idx[0] = 0; /* ACL array item index */
idx[1] = -1; /* privilege type counter */
funcctx->user_fctx = idx;
* elem_selec is array of estimated frequencies for elements in the
* constant.
*/
- elem_selec = (float *) palloc(sizeof(float) * nitems);
+ elem_selec = palloc_array(float, nitems);
/* Scan mcelem and array in parallel. */
mcelem_index = 0;
next_interval;
float frac;
- hist_part = (float *) palloc((n + 1) * sizeof(float));
+ hist_part = palloc_array(float, n + 1);
/*
* frac is a probability contribution for each interval between histogram
* Since we return only the last row of the matrix and need only the
* current and previous row for calculations, allocate two rows.
*/
- row = (float *) palloc((m + 1) * sizeof(float));
- prev_row = (float *) palloc((m + 1) * sizeof(float));
+ row = palloc_array(float, m + 1);
+ prev_row = palloc_array(float, m + 1);
/* M[0,0] = 1 */
row[0] = 1.0f;
PG_RETURN_BOOL(true);
/* Store our findings for use by compute_array_stats() */
- extra_data = (ArrayAnalyzeExtraData *) palloc(sizeof(ArrayAnalyzeExtraData));
+ extra_data = palloc_object(ArrayAnalyzeExtraData);
extra_data->type_id = typentry->type_id;
extra_data->eq_opr = typentry->eq_opr;
extra_data->coll_id = stats->attrcollid; /* collation we should use */
cutoff_freq = 9 * element_no / bucket_width;
i = hash_get_num_entries(elements_tab); /* surely enough space */
- sort_table = (TrackItem **) palloc(sizeof(TrackItem *) * i);
+ sort_table = palloc_array(TrackItem *, i);
hash_seq_init(&scan_status, elements_tab);
track_len = 0;
* Create an array of DECountItem pointers, and sort them into
* increasing count order.
*/
- sorted_count_items = (DECountItem **)
- palloc(sizeof(DECountItem *) * count_items_count);
+ sorted_count_items = palloc_array(DECountItem *, count_items_count);
hash_seq_init(&scan_status, count_tab);
j = 0;
while ((count_item = (DECountItem *) hash_seq_search(&scan_status)) != NULL)
* themselves) of the input argument arrays
*/
ndims = ndims1;
- dims = (int *) palloc(ndims * sizeof(int));
- lbs = (int *) palloc(ndims * sizeof(int));
+ dims = palloc_array(int, ndims);
+ lbs = palloc_array(int, ndims);
dims[0] = dims1[0] + dims2[0];
lbs[0] = lbs1[0];
* the first argument inserted at the front of the outer dimension
*/
ndims = ndims2;
- dims = (int *) palloc(ndims * sizeof(int));
- lbs = (int *) palloc(ndims * sizeof(int));
+ dims = palloc_array(int, ndims);
+ lbs = palloc_array(int, ndims);
memcpy(dims, dims2, ndims * sizeof(int));
memcpy(lbs, lbs2, ndims * sizeof(int));
* second argument appended to the end of the outer dimension
*/
ndims = ndims1;
- dims = (int *) palloc(ndims * sizeof(int));
- lbs = (int *) palloc(ndims * sizeof(int));
+ dims = palloc_array(int, ndims);
+ lbs = palloc_array(int, ndims);
memcpy(dims, dims1, ndims * sizeof(int));
memcpy(lbs, lbs1, ndims * sizeof(int));
{
ArrayType *result;
- result = (ArrayType *) palloc0(sizeof(ArrayType));
+ result = palloc0_object(ArrayType);
SET_VARSIZE(result, sizeof(ArrayType));
result->ndim = 0;
result->dataoffset = 0;
Assert(ARR_ELEMTYPE(array) == elmtype);
nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
- *elemsp = elems = (Datum *) palloc(nelems * sizeof(Datum));
+ *elemsp = elems = palloc_array(Datum, nelems);
if (nullsp)
- *nullsp = nulls = (bool *) palloc0(nelems * sizeof(bool));
+ *nullsp = nulls = palloc0_array(bool, nelems);
else
nulls = NULL;
*nelemsp = nelems;
* modify typentry, since that points directly into the type
* cache.
*/
- record_typentry = palloc0(sizeof(*record_typentry));
+ record_typentry = palloc0_object(TypeCacheEntry);
record_typentry->type_id = element_type;
/* fill in what we need below */
ArrayIterator
array_create_iterator(ArrayType *arr, int slice_ndim, ArrayMetaState *mstate)
{
- ArrayIterator iterator = palloc0(sizeof(ArrayIteratorData));
+ ArrayIterator iterator = palloc0_object(ArrayIteratorData);
/*
* Sanity-check inputs --- caller should have got this right already
* switch to memory context appropriate for multiple function calls
*/
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
- fctx = (generate_subscripts_fctx *) palloc(sizeof(generate_subscripts_fctx));
+ fctx = palloc_object(generate_subscripts_fctx);
lb = AARR_LBOUND(v);
dimv = AARR_DIMS(v);
arr = PG_GETARG_ANY_ARRAY_P(0);
/* allocate memory for user context */
- fctx = (array_unnest_fctx *) palloc(sizeof(array_unnest_fctx));
+ fctx = palloc_object(array_unnest_fctx);
/* initialize state */
array_iter_setup(&fctx->iter, arr);
/*
* Allocate type-specific workspace.
*/
- workspace = (ArraySubWorkspace *) palloc(sizeof(ArraySubWorkspace));
+ workspace = palloc_object(ArraySubWorkspace);
sbsrefstate->workspace = workspace;
/*
GetCurrentTimeUsec(tm, &fsec, &tz);
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
tm2timetz(tm, fsec, tz, result);
AdjustTimeForTypmod(&(result->time), typmod);
return result;
TimeADT time = PG_GETARG_TIMEADT(0);
Interval *result;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
result->time = time;
result->day = 0;
TimeADT time2 = PG_GETARG_TIMEADT(1);
Interval *result;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
result->month = 0;
result->day = 0;
PG_RETURN_NULL();
}
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
tm2timetz(tm, fsec, tz, result);
AdjustTimeForTypmod(&(result->time), typmod);
int32 typmod = PG_GETARG_INT32(2);
TimeTzADT *result;
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
result->time = pq_getmsgint64(buf);
int32 typmod = PG_GETARG_INT32(1);
TimeTzADT *result;
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
result->time = time->time;
result->zone = time->zone;
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("cannot add infinite interval to time")));
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
result->time = time->time + span->time;
result->time -= result->time / USECS_PER_DAY * USECS_PER_DAY;
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("cannot subtract infinite interval from time")));
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
result->time = time->time - span->time;
result->time -= result->time / USECS_PER_DAY * USECS_PER_DAY;
time2tm(time, tm, &fsec);
tz = DetermineTimeZoneOffset(tm, session_timezone);
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
result->time = time;
result->zone = tz;
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
tm2timetz(tm, fsec, tz, result);
errmsg("timestamp out of range")));
}
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
result->time = t->time + (t->zone - tz) * USECS_PER_SEC;
/* C99 modulo has the wrong sign convention for negative input */
tz = -(zone->time / USECS_PER_SEC);
- result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+ result = palloc_object(TimeTzADT);
result->time = time->time + (time->zone - tz) * USECS_PER_SEC;
/* C99 modulo has the wrong sign convention for negative input */
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate memory for user context */
- pindex = (int *) palloc(sizeof(int));
+ pindex = palloc_object(int);
*pindex = 0;
funcctx->user_fctx = pindex;
/* Convert offset (in seconds) to an interval; can't overflow */
MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
itm_in.tm_usec = (int64) gmtoff * USECS_PER_SEC;
- resInterval = (Interval *) palloc(sizeof(Interval));
+ resInterval = palloc_object(Interval);
(void) itmin2interval(&itm_in, resInterval);
values[1] = IntervalPGetDatum(resInterval);
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate memory for user context */
- pindex = (int *) palloc(sizeof(int));
+ pindex = palloc_object(int);
*pindex = 0;
funcctx->user_fctx = pindex;
/* Convert offset (in seconds) to an interval; can't overflow */
MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
itm_in.tm_usec = (int64) gmtoffset * USECS_PER_SEC;
- resInterval = (Interval *) palloc(sizeof(Interval));
+ resInterval = palloc_object(Interval);
(void) itmin2interval(&itm_in, resInterval);
values[1] = IntervalPGetDatum(resInterval);
/* Convert tzoff to an interval; can't overflow */
MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
itm_in.tm_usec = (int64) -tzoff * USECS_PER_SEC;
- resInterval = (Interval *) palloc(sizeof(Interval));
+ resInterval = palloc_object(Interval);
(void) itmin2interval(&itm_in, resInterval);
values[2] = IntervalPGetDatum(resInterval);
{
if (flags & DCH_ZONED)
{
- TimeTzADT *result = palloc(sizeof(TimeTzADT));
+ TimeTzADT *result = palloc_object(TimeTzADT);
if (ftz.has_tz)
{
{
char *str = PG_GETARG_CSTRING(0);
Node *escontext = fcinfo->context;
- BOX *box = (BOX *) palloc(sizeof(BOX));
+ BOX *box = palloc_object(BOX);
bool isopen;
float8 x,
y;
float8 x,
y;
- box = (BOX *) palloc(sizeof(BOX));
+ box = palloc_object(BOX);
box->high.x = pq_getmsgfloat8(buf);
box->high.y = pq_getmsgfloat8(buf);
box_center(PG_FUNCTION_ARGS)
{
BOX *box = PG_GETARG_BOX_P(0);
- Point *result = (Point *) palloc(sizeof(Point));
+ Point *result = palloc_object(Point);
box_cn(result, box);
if (!box_ov(box1, box2))
PG_RETURN_NULL();
- result = (BOX *) palloc(sizeof(BOX));
+ result = palloc_object(BOX);
result->high.x = float8_min(box1->high.x, box2->high.x);
result->low.x = float8_max(box1->low.x, box2->low.x);
box_diagonal(PG_FUNCTION_ARGS)
{
BOX *box = PG_GETARG_BOX_P(0);
- LSEG *result = (LSEG *) palloc(sizeof(LSEG));
+ LSEG *result = palloc_object(LSEG);
statlseg_construct(result, &box->high, &box->low);
{
char *str = PG_GETARG_CSTRING(0);
Node *escontext = fcinfo->context;
- LINE *line = (LINE *) palloc(sizeof(LINE));
+ LINE *line = palloc_object(LINE);
LSEG lseg;
bool isopen;
char *s;
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
LINE *line;
- line = (LINE *) palloc(sizeof(LINE));
+ line = palloc_object(LINE);
line->A = pq_getmsgfloat8(buf);
line->B = pq_getmsgfloat8(buf);
{
Point *pt1 = PG_GETARG_POINT_P(0);
Point *pt2 = PG_GETARG_POINT_P(1);
- LINE *result = (LINE *) palloc(sizeof(LINE));
+ LINE *result = palloc_object(LINE);
if (point_eq_point(pt1, pt2))
ereport(ERROR,
LINE *l2 = PG_GETARG_LINE_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
if (!line_interpt_line(result, l1, l2))
PG_RETURN_NULL();
point_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
- Point *point = (Point *) palloc(sizeof(Point));
+ Point *point = palloc_object(Point);
/* Ignore failure from pair_decode, since our return value won't matter */
pair_decode(str, &point->x, &point->y, NULL, "point", str, fcinfo->context);
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
Point *point;
- point = (Point *) palloc(sizeof(Point));
+ point = palloc_object(Point);
point->x = pq_getmsgfloat8(buf);
point->y = pq_getmsgfloat8(buf);
PG_RETURN_POINT_P(point);
{
char *str = PG_GETARG_CSTRING(0);
Node *escontext = fcinfo->context;
- LSEG *lseg = (LSEG *) palloc(sizeof(LSEG));
+ LSEG *lseg = palloc_object(LSEG);
bool isopen;
if (!path_decode(str, true, 2, &lseg->p[0], &isopen, NULL, "lseg", str,
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
LSEG *lseg;
- lseg = (LSEG *) palloc(sizeof(LSEG));
+ lseg = palloc_object(LSEG);
lseg->p[0].x = pq_getmsgfloat8(buf);
lseg->p[0].y = pq_getmsgfloat8(buf);
{
Point *pt1 = PG_GETARG_POINT_P(0);
Point *pt2 = PG_GETARG_POINT_P(1);
- LSEG *result = (LSEG *) palloc(sizeof(LSEG));
+ LSEG *result = palloc_object(LSEG);
statlseg_construct(result, pt1, pt2);
LSEG *lseg = PG_GETARG_LSEG_P(0);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
result->x = float8_div(float8_pl(lseg->p[0].x, lseg->p[1].x), 2.0);
result->y = float8_div(float8_pl(lseg->p[0].y, lseg->p[1].y), 2.0);
LSEG *l2 = PG_GETARG_LSEG_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
if (!lseg_interpt_lseg(result, l1, l2))
PG_RETURN_NULL();
LINE *line = PG_GETARG_LINE_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
if (isnan(line_closept_point(result, line, pt)))
PG_RETURN_NULL();
LSEG *lseg = PG_GETARG_LSEG_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
if (isnan(lseg_closept_point(result, lseg, pt)))
PG_RETURN_NULL();
if (lseg_sl(l1) == lseg_sl(l2))
PG_RETURN_NULL();
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
if (isnan(lseg_closept_lseg(result, l2, l1)))
PG_RETURN_NULL();
BOX *box = PG_GETARG_BOX_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
if (isnan(box_closept_point(result, box, pt)))
PG_RETURN_NULL();
if (lseg_sl(lseg) == line_sl(line))
PG_RETURN_NULL();
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
if (isnan(lseg_closept_line(result, lseg, line)))
PG_RETURN_NULL();
BOX *box = PG_GETARG_BOX_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
if (isnan(box_closept_lseg(result, box, lseg)))
PG_RETURN_NULL();
float8 y = PG_GETARG_FLOAT8(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
point_construct(result, x, y);
Point *p2 = PG_GETARG_POINT_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
point_add_point(result, p1, p2);
Point *p2 = PG_GETARG_POINT_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
point_sub_point(result, p1, p2);
Point *p2 = PG_GETARG_POINT_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
point_mul_point(result, p1, p2);
Point *p2 = PG_GETARG_POINT_P(1);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
point_div_point(result, p1, p2);
Point *p2 = PG_GETARG_POINT_P(1);
BOX *result;
- result = (BOX *) palloc(sizeof(BOX));
+ result = palloc_object(BOX);
box_construct(result, p1, p2);
Point *p = PG_GETARG_POINT_P(1);
BOX *result;
- result = (BOX *) palloc(sizeof(BOX));
+ result = palloc_object(BOX);
point_add_point(&result->high, &box->high, p);
point_add_point(&result->low, &box->low, p);
Point *p = PG_GETARG_POINT_P(1);
BOX *result;
- result = (BOX *) palloc(sizeof(BOX));
+ result = palloc_object(BOX);
point_sub_point(&result->high, &box->high, p);
point_sub_point(&result->low, &box->low, p);
Point high,
low;
- result = (BOX *) palloc(sizeof(BOX));
+ result = palloc_object(BOX);
point_mul_point(&high, &box->high, p);
point_mul_point(&low, &box->low, p);
Point high,
low;
- result = (BOX *) palloc(sizeof(BOX));
+ result = palloc_object(BOX);
point_div_point(&high, &box->high, p);
point_div_point(&low, &box->low, p);
Point *pt = PG_GETARG_POINT_P(0);
BOX *box;
- box = (BOX *) palloc(sizeof(BOX));
+ box = palloc_object(BOX);
box->high.x = pt->x;
box->low.x = pt->x;
*box2 = PG_GETARG_BOX_P(1),
*container;
- container = (BOX *) palloc(sizeof(BOX));
+ container = palloc_object(BOX);
container->high.x = float8_max(box1->high.x, box2->high.x);
container->low.x = float8_min(box1->low.x, box2->low.x);
Point *result;
CIRCLE circle;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
poly_to_circle(&circle, poly);
*result = circle.center;
POLYGON *poly = PG_GETARG_POLYGON_P(0);
BOX *box;
- box = (BOX *) palloc(sizeof(BOX));
+ box = palloc_object(BOX);
*box = poly->boundbox;
PG_RETURN_BOX_P(box);
{
char *str = PG_GETARG_CSTRING(0);
Node *escontext = fcinfo->context;
- CIRCLE *circle = (CIRCLE *) palloc(sizeof(CIRCLE));
+ CIRCLE *circle = palloc_object(CIRCLE);
char *s,
*cp;
int depth = 0;
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
CIRCLE *circle;
- circle = (CIRCLE *) palloc(sizeof(CIRCLE));
+ circle = palloc_object(CIRCLE);
circle->center.x = pq_getmsgfloat8(buf);
circle->center.y = pq_getmsgfloat8(buf);
Point *point = PG_GETARG_POINT_P(1);
CIRCLE *result;
- result = (CIRCLE *) palloc(sizeof(CIRCLE));
+ result = palloc_object(CIRCLE);
point_add_point(&result->center, &circle->center, point);
result->radius = circle->radius;
Point *point = PG_GETARG_POINT_P(1);
CIRCLE *result;
- result = (CIRCLE *) palloc(sizeof(CIRCLE));
+ result = palloc_object(CIRCLE);
point_sub_point(&result->center, &circle->center, point);
result->radius = circle->radius;
Point *point = PG_GETARG_POINT_P(1);
CIRCLE *result;
- result = (CIRCLE *) palloc(sizeof(CIRCLE));
+ result = palloc_object(CIRCLE);
point_mul_point(&result->center, &circle->center, point);
result->radius = float8_mul(circle->radius, hypot(point->x, point->y));
Point *point = PG_GETARG_POINT_P(1);
CIRCLE *result;
- result = (CIRCLE *) palloc(sizeof(CIRCLE));
+ result = palloc_object(CIRCLE);
point_div_point(&result->center, &circle->center, point);
result->radius = float8_div(circle->radius, hypot(point->x, point->y));
CIRCLE *circle = PG_GETARG_CIRCLE_P(0);
Point *result;
- result = (Point *) palloc(sizeof(Point));
+ result = palloc_object(Point);
result->x = circle->center.x;
result->y = circle->center.y;
float8 radius = PG_GETARG_FLOAT8(1);
CIRCLE *result;
- result = (CIRCLE *) palloc(sizeof(CIRCLE));
+ result = palloc_object(CIRCLE);
result->center.x = center->x;
result->center.y = center->y;
BOX *box;
float8 delta;
- box = (BOX *) palloc(sizeof(BOX));
+ box = palloc_object(BOX);
delta = float8_div(circle->radius, sqrt(2.0));
BOX *box = PG_GETARG_BOX_P(0);
CIRCLE *circle;
- circle = (CIRCLE *) palloc(sizeof(CIRCLE));
+ circle = palloc_object(CIRCLE);
circle->center.x = float8_div(float8_pl(box->high.x, box->low.x), 2.0);
circle->center.y = float8_div(float8_pl(box->high.y, box->low.y), 2.0);
POLYGON *poly = PG_GETARG_POLYGON_P(0);
CIRCLE *result;
- result = (CIRCLE *) palloc(sizeof(CIRCLE));
+ result = palloc_object(CIRCLE);
poly_to_circle(result, poly);
static RangeBox *
getRangeBox(BOX *box)
{
- RangeBox *range_box = (RangeBox *) palloc(sizeof(RangeBox));
+ RangeBox *range_box = palloc_object(RangeBox);
range_box->left.low = box->low.x;
range_box->left.high = box->high.x;
static RectBox *
initRectBox(void)
{
- RectBox *rect_box = (RectBox *) palloc(sizeof(RectBox));
+ RectBox *rect_box = palloc_object(RectBox);
float8 infinity = get_float8_infinity();
rect_box->range_box_x.left.low = -infinity;
static RectBox *
nextRectBox(RectBox *rect_box, RangeBox *centroid, uint8 quadrant)
{
- RectBox *next_rect_box = (RectBox *) palloc(sizeof(RectBox));
+ RectBox *next_rect_box = palloc_object(RectBox);
memcpy(next_rect_box, rect_box, sizeof(RectBox));
BOX *centroid;
int median,
i;
- float8 *lowXs = palloc(sizeof(float8) * in->nTuples);
- float8 *highXs = palloc(sizeof(float8) * in->nTuples);
- float8 *lowYs = palloc(sizeof(float8) * in->nTuples);
- float8 *highYs = palloc(sizeof(float8) * in->nTuples);
+ float8 *lowXs = palloc_array(float8, in->nTuples);
+ float8 *highXs = palloc_array(float8, in->nTuples);
+ float8 *lowYs = palloc_array(float8, in->nTuples);
+ float8 *highYs = palloc_array(float8, in->nTuples);
/* Calculate median of all 4D coordinates */
for (i = 0; i < in->nTuples; i++)
median = in->nTuples / 2;
- centroid = palloc(sizeof(BOX));
+ centroid = palloc_object(BOX);
centroid->low.x = lowXs[median];
centroid->high.x = highXs[median];
out->nNodes = 16;
out->nodeLabels = NULL; /* We don't need node labels. */
- out->mapTuplesToNodes = palloc(sizeof(int) * in->nTuples);
- out->leafTupleDatums = palloc(sizeof(Datum) * in->nTuples);
+ out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+ out->leafTupleDatums = palloc_array(Datum, in->nTuples);
/*
* Assign ranges to corresponding nodes according to quadrants relative to
{
/* Report that all nodes should be visited */
out->nNodes = in->nNodes;
- out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
+ out->nodeNumbers = palloc_array(int, in->nNodes);
for (i = 0; i < in->nNodes; i++)
out->nodeNumbers[i] = i;
if (in->norderbys > 0 && in->nNodes > 0)
{
- double *distances = palloc(sizeof(double) * in->norderbys);
+ double *distances = palloc_array(double, in->norderbys);
int j;
for (j = 0; j < in->norderbys; j++)
distances[j] = pointToRectBoxDistance(pt, rect_box);
}
- out->distances = (double **) palloc(sizeof(double *) * in->nNodes);
+ out->distances = palloc_array(double *, in->nNodes);
out->distances[0] = distances;
for (i = 1; i < in->nNodes; i++)
{
- out->distances[i] = palloc(sizeof(double) * in->norderbys);
+ out->distances[i] = palloc_array(double, in->norderbys);
memcpy(out->distances[i], distances,
sizeof(double) * in->norderbys);
}
* following operations.
*/
centroid = getRangeBox(DatumGetBoxP(in->prefixDatum));
- queries = (RangeBox **) palloc(in->nkeys * sizeof(RangeBox *));
+ queries = palloc_array(RangeBox *, in->nkeys);
for (i = 0; i < in->nkeys; i++)
{
BOX *box = spg_box_quad_get_scankey_bbox(&in->scankeys[i], NULL);
/* Allocate enough memory for nodes */
out->nNodes = 0;
- out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
- out->traversalValues = (void **) palloc(sizeof(void *) * in->nNodes);
+ out->nodeNumbers = palloc_array(int, in->nNodes);
+ out->traversalValues = palloc_array(void *, in->nNodes);
if (in->norderbys > 0)
- out->distances = (double **) palloc(sizeof(double *) * in->nNodes);
+ out->distances = palloc_array(double *, in->nNodes);
/*
* We switch memory context, because we want to allocate memory for new
if (in->norderbys > 0)
{
- double *distances = palloc(sizeof(double) * in->norderbys);
+ double *distances = palloc_array(double, in->norderbys);
int j;
out->distances[out->nNodes] = distances;
POLYGON *polygon = PG_GETARG_POLYGON_P(0);
BOX *box;
- box = (BOX *) palloc(sizeof(BOX));
+ box = palloc_object(BOX);
*box = polygon->boundbox;
PG_RETURN_BOX_P(box);
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate memory for user context */
- fctx = (generate_series_fctx *) palloc(sizeof(generate_series_fctx));
+ fctx = palloc_object(generate_series_fctx);
/*
* Use fctx to keep state from call to call. Seed current with the
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate memory for user context */
- fctx = (generate_series_fctx *) palloc(sizeof(generate_series_fctx));
+ fctx = palloc_object(generate_series_fctx);
/*
* Use fctx to keep state from call to call. Seed current with the
* use the right context to enlarge the object if necessary.
*/
oldcontext = MemoryContextSwitchTo(aggcontext);
- state = (JsonAggState *) palloc(sizeof(JsonAggState));
+ state = palloc_object(JsonAggState);
state->str = makeStringInfo();
MemoryContextSwitchTo(oldcontext);
* sure they use the right context to enlarge the object if necessary.
*/
oldcontext = MemoryContextSwitchTo(aggcontext);
- state = (JsonAggState *) palloc(sizeof(JsonAggState));
+ state = palloc_object(JsonAggState);
state->str = makeStringInfo();
if (unique_keys)
json_unique_builder_init(&state->unique_check);
return JSON_SUCCESS;
/* push object entry to stack */
- entry = palloc(sizeof(*entry));
+ entry = palloc_object(JsonUniqueStackEntry);
entry->object_id = state->id_counter++;
entry->parent = state->stack;
state->stack = entry;
init_gin_entries(GinEntries *entries, int preallocated)
{
entries->allocated = preallocated;
- entries->buf = preallocated ? palloc(sizeof(Datum) * preallocated) : NULL;
+ entries->buf = preallocated ? palloc_array(Datum, preallocated) : NULL;
entries->count = 0;
}
if (entries->allocated)
{
entries->allocated *= 2;
- entries->buf = repalloc(entries->buf,
- sizeof(Datum) * entries->allocated);
+ entries->buf = repalloc_array(entries->buf,
+ Datum,
+ entries->allocated);
}
else
{
entries->allocated = 8;
- entries->buf = palloc(sizeof(Datum) * entries->allocated);
+ entries->buf = palloc_array(Datum, entries->allocated);
}
}
return false;
}
- pentry = palloc(sizeof(*pentry));
+ pentry = palloc_object(JsonPathGinPathItem);
pentry->type = jsp->type;
pentry->keyName = keyName;
if (!*nentries)
return NULL;
- *extra_data = palloc0(sizeof(**extra_data) * entries.count);
+ *extra_data = palloc0_array(Pointer, entries.count);
**extra_data = (Pointer) node;
return entries.buf;
text *query = PG_GETARG_TEXT_PP(0);
*nentries = 1;
- entries = (Datum *) palloc(sizeof(Datum));
+ entries = palloc_object(Datum);
entries[0] = make_text_key(JGINFLAG_KEY,
VARDATA_ANY(query),
VARSIZE_ANY_EXHDR(query));
deconstruct_array_builtin(query, TEXTOID, &key_datums, &key_nulls, &key_count);
- entries = (Datum *) palloc(sizeof(Datum) * key_count);
+ entries = palloc_array(Datum, key_count);
for (i = 0, j = 0; i < key_count; i++)
{
case WJB_BEGIN_OBJECT:
/* Push a stack level for this object */
parent = stack;
- stack = (PathHashStack *) palloc(sizeof(PathHashStack));
+ stack = palloc_object(PathHashStack);
/*
* We pass forward hashes from outer nesting levels so that
if ((flags & JB_FARRAY) && JsonContainerIsArray(container))
{
- JsonbValue *result = palloc(sizeof(JsonbValue));
+ JsonbValue *result = palloc_object(JsonbValue);
char *base_addr = (char *) (children + count);
uint32 offset = 0;
int i;
int index = stopMiddle + count;
if (!res)
- res = palloc(sizeof(JsonbValue));
+ res = palloc_object(JsonbValue);
fillJsonbValue(container, index, baseAddr,
getJsonbOffset(container, index),
if (i >= nelements)
return NULL;
- result = palloc(sizeof(JsonbValue));
+ result = palloc_object(JsonbValue);
fillJsonbValue(container, i, base_addr,
getJsonbOffset(container, i),
{
JsonbIterator *it;
- it = palloc0(sizeof(JsonbIterator));
+ it = palloc0_object(JsonbIterator);
it->container = container;
it->parent = parent;
it->nElems = JsonContainerSize(container);
uint32 j = 0;
/* Make room for all possible values */
- lhsConts = palloc(sizeof(JsonbValue) * nLhsElems);
+ lhsConts = palloc_array(JsonbValue, nLhsElems);
for (i = 0; i < nLhsElems; i++)
{
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
- state = palloc(sizeof(OkeysState));
+ state = palloc_object(OkeysState);
state->result_size = JB_ROOT_COUNT(jb);
state->result_count = 0;
state->sent_count = 0;
- state->result = palloc(state->result_size * sizeof(char *));
+ state->result = palloc_array(char *, state->result_size);
it = JsonbIteratorInit(&jb->root);
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
- state = palloc(sizeof(OkeysState));
- sem = palloc0(sizeof(JsonSemAction));
+ state = palloc_object(OkeysState);
+ sem = palloc0_object(JsonSemAction);
state->lex = makeJsonLexContext(&lex, json, true);
state->result_size = 256;
state->result_count = 0;
state->sent_count = 0;
- state->result = palloc(256 * sizeof(char *));
+ state->result = palloc_array(char *, 256);
sem->semstate = state;
sem->array_start = okeys_array_start;
deconstruct_array_builtin(path, TEXTOID, &pathtext, &pathnulls, &npath);
- tpath = palloc(npath * sizeof(char *));
- ipath = palloc(npath * sizeof(int));
+ tpath = palloc_array(char *, npath);
+ ipath = palloc_array(int, npath);
for (i = 0; i < npath; i++)
{
int npath,
bool normalize_results)
{
- JsonSemAction *sem = palloc0(sizeof(JsonSemAction));
- GetState *state = palloc0(sizeof(GetState));
+ JsonSemAction *sem = palloc0_object(JsonSemAction);
+ GetState *state = palloc0_object(GetState);
Assert(npath >= 0);
state->npath = npath;
state->path_names = tpath;
state->path_indexes = ipath;
- state->pathok = palloc0(sizeof(bool) * npath);
- state->array_cur_index = palloc(sizeof(int) * npath);
+ state->pathok = palloc0_array(bool, npath);
+ state->array_cur_index = palloc_array(int, npath);
if (npath > 0)
state->pathok[0] = true;
{
JsonbInState state = {0};
JsonbIterator *it;
- bool *path_nulls = palloc0(path_len * sizeof(bool));
+ bool *path_nulls = palloc0_array(bool, path_len);
if (newval->type == jbvArray && newval->val.array.rawScalar)
*newval = newval->val.array.elems[0];
* it contains only information about path slice from level to the end,
* the access index must be normalized by level.
*/
- enum jbvType *tpath = palloc0((path_len - level) * sizeof(enum jbvType));
+ enum jbvType *tpath = palloc0_array(enum jbvType, path_len - level);
JsonbValue newkey;
/*
JsonLexContext lex;
JsonSemAction *sem;
- state = palloc0(sizeof(AlenState));
+ state = palloc0_object(AlenState);
state->lex = makeJsonLexContext(&lex, json, false);
/* palloc0 does this for us */
#if 0
state->count = 0;
#endif
- sem = palloc0(sizeof(JsonSemAction));
+ sem = palloc0_object(JsonSemAction);
sem->semstate = state;
sem->object_start = alen_object_start;
sem->scalar = alen_scalar;
ReturnSetInfo *rsi;
EachState *state;
- state = palloc0(sizeof(EachState));
- sem = palloc0(sizeof(JsonSemAction));
+ state = palloc0_object(EachState);
+ sem = palloc0_object(JsonSemAction);
rsi = (ReturnSetInfo *) fcinfo->resultinfo;
/* elements only needs escaped strings when as_text */
makeJsonLexContext(&lex, json, as_text);
- state = palloc0(sizeof(ElementsState));
- sem = palloc0(sizeof(JsonSemAction));
+ state = palloc0_object(ElementsState);
+ sem = palloc0_object(JsonSemAction);
InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC | MAT_SRF_BLESS);
rsi = (ReturnSetInfo *) fcinfo->resultinfo;
}
ctx->ndims = ndims;
- ctx->dims = palloc(sizeof(int) * ndims);
- ctx->sizes = palloc0(sizeof(int) * ndims);
+ ctx->dims = palloc_array(int, ndims);
+ ctx->sizes = palloc0_array(int, ndims);
for (i = 0; i < ndims; i++)
ctx->dims[i] = -1; /* dimensions are unknown yet */
Assert(ctx.ndims > 0);
- lbs = palloc(sizeof(int) * ctx.ndims);
+ lbs = palloc_array(int, ctx.ndims);
for (i = 0; i < ctx.ndims; i++)
lbs[i] = 1;
&ctl,
HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
- state = palloc0(sizeof(JHashState));
- sem = palloc0(sizeof(JsonSemAction));
+ state = palloc0_object(JHashState);
+ sem = palloc0_object(JsonSemAction);
state->function_name = funcname;
state->hash = tab;
*/
update_cached_tupdesc(&cache->c.io.composite, cache->fn_mcxt);
- state = palloc0(sizeof(PopulateRecordsetState));
+ state = palloc0_object(PopulateRecordsetState);
/* make tuplestore in a sufficiently long-lived memory context */
old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
JsonLexContext lex;
JsonSemAction *sem;
- sem = palloc0(sizeof(JsonSemAction));
+ sem = palloc0_object(JsonSemAction);
makeJsonLexContext(&lex, json, true);
JsonLexContext lex;
JsonSemAction *sem;
- state = palloc0(sizeof(StripnullState));
- sem = palloc0(sizeof(JsonSemAction));
+ state = palloc0_object(StripnullState);
+ sem = palloc0_object(JsonSemAction);
initStringInfo(&strbuf);
state->lex = makeJsonLexContext(&lex, json, true);
JsonIterateStringValuesAction action)
{
JsonLexContext lex;
- JsonSemAction *sem = palloc0(sizeof(JsonSemAction));
- IterateJsonStringValuesState *state = palloc0(sizeof(IterateJsonStringValuesState));
+ JsonSemAction *sem = palloc0_object(JsonSemAction);
+ IterateJsonStringValuesState *state = palloc0_object(IterateJsonStringValuesState);
state->lex = makeJsonLexContext(&lex, json, true);
state->action = action;
JsonTransformStringValuesAction transform_action)
{
JsonLexContext lex;
- JsonSemAction *sem = palloc0(sizeof(JsonSemAction));
- TransformJsonStringValuesState *state = palloc0(sizeof(TransformJsonStringValuesState));
+ JsonSemAction *sem = palloc0_object(JsonSemAction);
+ TransformJsonStringValuesState *state = palloc0_object(TransformJsonStringValuesState);
StringInfoData strbuf;
initStringInfo(&strbuf);
break;
}
- v = hasNext ? &vbuf : palloc(sizeof(*v));
+ v = hasNext ? &vbuf : palloc_object(JsonbValue);
baseObject = cxt->baseObject;
getJsonPathItem(cxt, jsp, v);
case jpiType:
{
- JsonbValue *jbv = palloc(sizeof(*jbv));
+ JsonbValue *jbv = palloc_object(JsonbValue);
jbv->type = jbvString;
jbv->val.string.val = pstrdup(JsonbTypeName(jb));
size = 1;
}
- jb = palloc(sizeof(*jb));
+ jb = palloc_object(JsonbValue);
jb->type = jbvNumeric;
jb->val.numeric = int64_to_numeric(size);
last = cxt->innermostArraySize - 1;
- lastjbv = hasNext ? &tmpjbv : palloc(sizeof(*lastjbv));
+ lastjbv = hasNext ? &tmpjbv : palloc_object(JsonbValue);
lastjbv->type = jbvNumeric;
lastjbv->val.numeric = int64_to_numeric(last);
if (!jspGetNext(jsp, &elem) && !found)
return jperOk;
- lval = palloc(sizeof(*lval));
+ lval = palloc_object(JsonbValue);
lval->type = jbvNumeric;
lval->val.numeric = res;
if (!jspGetNext(jsp, &next) && !found)
return jperOk;
- jb = palloc(sizeof(*jb));
+ jb = palloc_object(JsonbValue);
jb->type = jbvNumeric;
jb->val.numeric = DatumGetNumeric(datum);
if (!hasNext && !found)
return res;
- jb = hasNext ? &jbvbuf : palloc(sizeof(*jb));
+ jb = hasNext ? &jbvbuf : palloc_object(JsonbValue);
jb->type = jbvDatetime;
jb->val.datetime.value = value;
return NULL;
}
- result = palloc(sizeof(JsonbValue));
+ result = palloc_object(JsonbValue);
if (var->isnull)
{
*baseObjectId = 0;
static JsonbValue *
copyJsonbValue(JsonbValue *src)
{
- JsonbValue *dst = palloc(sizeof(*dst));
+ JsonbValue *dst = palloc_object(JsonbValue);
*dst = *src;
JsonExpr *je = castNode(JsonExpr, tf->docexpr);
List *args = NIL;
- cxt = palloc0(sizeof(JsonTableExecContext));
+ cxt = palloc0_object(JsonTableExecContext);
cxt->magic = JSON_TABLE_EXEC_CONTEXT_MAGIC;
/*
{
ExprState *state = lfirst_node(ExprState, exprlc);
String *name = lfirst_node(String, namelc);
- JsonPathVariable *var = palloc(sizeof(*var));
+ JsonPathVariable *var = palloc_object(JsonPathVariable);
var->name = pstrdup(name->sval);
var->namelen = strlen(var->name);
}
}
- cxt->colplanstates = palloc(sizeof(JsonTablePlanState *) *
- list_length(tf->colvalexprs));
+ cxt->colplanstates = palloc_array(JsonTablePlanState *, list_length(tf->colvalexprs));
/*
* Initialize plan for the root path and, recursively, also any child
JsonTablePlanState *parentstate,
List *args, MemoryContext mcxt)
{
- JsonTablePlanState *planstate = palloc0(sizeof(*planstate));
+ JsonTablePlanState *planstate = palloc0_object(JsonTablePlanState);
planstate->plan = plan;
planstate->parent = parentstate;
result:
mode expr_or_predicate {
- *result = palloc(sizeof(JsonPathParseResult));
+ *result = palloc_object(JsonPathParseResult);
(*result)->expr = $2;
(*result)->lax = $1;
(void) yynerrs;
static JsonPathParseItem *
makeItemType(JsonPathItemType type)
{
- JsonPathParseItem *v = palloc(sizeof(*v));
+ JsonPathParseItem *v = palloc_object(JsonPathParseItem);
CHECK_FOR_INTERRUPTS();
* Collect all the locking information that we will format and send
* out as a result set.
*/
- mystatus = (PG_Lock_Status *) palloc(sizeof(PG_Lock_Status));
+ mystatus = palloc_object(PG_Lock_Status);
funcctx->user_fctx = mystatus;
mystatus->lockData = GetLockStatusData();
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("invalid octet value in \"macaddr\" value: \"%s\"", str)));
- result = (macaddr *) palloc(sizeof(macaddr));
+ result = palloc_object(macaddr);
result->a = a;
result->b = b;
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
macaddr *addr;
- addr = (macaddr *) palloc(sizeof(macaddr));
+ addr = palloc_object(macaddr);
addr->a = pq_getmsgbyte(buf);
addr->b = pq_getmsgbyte(buf);
macaddr *addr = PG_GETARG_MACADDR_P(0);
macaddr *result;
- result = (macaddr *) palloc(sizeof(macaddr));
+ result = palloc_object(macaddr);
result->a = ~addr->a;
result->b = ~addr->b;
result->c = ~addr->c;
macaddr *addr2 = PG_GETARG_MACADDR_P(1);
macaddr *result;
- result = (macaddr *) palloc(sizeof(macaddr));
+ result = palloc_object(macaddr);
result->a = addr1->a & addr2->a;
result->b = addr1->b & addr2->b;
result->c = addr1->c & addr2->c;
macaddr *addr2 = PG_GETARG_MACADDR_P(1);
macaddr *result;
- result = (macaddr *) palloc(sizeof(macaddr));
+ result = palloc_object(macaddr);
result->a = addr1->a | addr2->a;
result->b = addr1->b | addr2->b;
result->c = addr1->c | addr2->c;
macaddr *addr = PG_GETARG_MACADDR_P(0);
macaddr *result;
- result = (macaddr *) palloc(sizeof(macaddr));
+ result = palloc_object(macaddr);
result->a = addr->a;
result->b = addr->b;
oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
- uss = palloc(sizeof(macaddr_sortsupport_state));
+ uss = palloc_object(macaddr_sortsupport_state);
uss->input_count = 0;
uss->estimating = true;
initHyperLogLog(&uss->abbr_card, 10);
else if (count != 8)
goto fail;
- result = (macaddr8 *) palloc0(sizeof(macaddr8));
+ result = palloc0_object(macaddr8);
result->a = a;
result->b = b;
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
macaddr8 *addr;
- addr = (macaddr8 *) palloc0(sizeof(macaddr8));
+ addr = palloc0_object(macaddr8);
addr->a = pq_getmsgbyte(buf);
addr->b = pq_getmsgbyte(buf);
macaddr8 *addr = PG_GETARG_MACADDR8_P(0);
macaddr8 *result;
- result = (macaddr8 *) palloc0(sizeof(macaddr8));
+ result = palloc0_object(macaddr8);
result->a = ~addr->a;
result->b = ~addr->b;
result->c = ~addr->c;
macaddr8 *addr2 = PG_GETARG_MACADDR8_P(1);
macaddr8 *result;
- result = (macaddr8 *) palloc0(sizeof(macaddr8));
+ result = palloc0_object(macaddr8);
result->a = addr1->a & addr2->a;
result->b = addr1->b & addr2->b;
result->c = addr1->c & addr2->c;
macaddr8 *addr2 = PG_GETARG_MACADDR8_P(1);
macaddr8 *result;
- result = (macaddr8 *) palloc0(sizeof(macaddr8));
+ result = palloc0_object(macaddr8);
result->a = addr1->a | addr2->a;
result->b = addr1->b | addr2->b;
result->c = addr1->c | addr2->c;
macaddr8 *addr = PG_GETARG_MACADDR8_P(0);
macaddr8 *result;
- result = (macaddr8 *) palloc0(sizeof(macaddr8));
+ result = palloc0_object(macaddr8);
result->a = addr->a;
result->b = addr->b;
macaddr8 *addr = PG_GETARG_MACADDR8_P(0);
macaddr8 *result;
- result = (macaddr8 *) palloc0(sizeof(macaddr8));
+ result = palloc0_object(macaddr8);
result->a = addr->a | 0x02;
result->b = addr->b;
macaddr *addr6 = PG_GETARG_MACADDR_P(0);
macaddr8 *result;
- result = (macaddr8 *) palloc0(sizeof(macaddr8));
+ result = palloc0_object(macaddr8);
result->a = addr6->a;
result->b = addr6->b;
macaddr8 *addr = PG_GETARG_MACADDR8_P(0);
macaddr *result;
- result = (macaddr *) palloc0(sizeof(macaddr));
+ result = palloc0_object(macaddr);
if ((addr->d != 0xFF) || (addr->e != 0xFE))
ereport(ERROR,
ArrayType *result_array;
length = list_length(list);
- datum_array = (Datum *) palloc(length * sizeof(Datum));
+ datum_array = palloc_array(Datum, length);
foreach_int(i, list)
datum_array[foreach_current_index(i)] = Int32GetDatum(i);
* array_in, and it wouldn't be very efficient if we could. Fill an
* FmgrInfo to use for the call.
*/
- arrayinp = (FmgrInfo *) palloc(sizeof(FmgrInfo));
+ arrayinp = palloc_object(FmgrInfo);
fmgr_info(F_ARRAY_IN, arrayinp);
funcctx->user_fctx = arrayinp;
int32 range_count = 0;
int32 range_capacity = 8;
RangeType *range;
- RangeType **ranges = palloc(range_capacity * sizeof(RangeType *));
+ RangeType **ranges = palloc_array(RangeType *, range_capacity);
MultirangeIOData *cache;
MultirangeType *ret;
MultirangeParseState parse_state;
cache = get_multirange_io_data(fcinfo, mltrngtypoid, IOFunc_receive);
range_count = pq_getmsgint(buf, 4);
- ranges = palloc(range_count * sizeof(RangeType *));
+ ranges = palloc_array(RangeType *, range_count);
initStringInfo(&tmpbuf);
for (int i = 0; i < range_count; i++)
{
int i;
- *ranges = palloc(*range_count * sizeof(RangeType *));
+ *ranges = palloc_array(RangeType *, *range_count);
for (i = 0; i < *range_count; i++)
(*ranges)[i] = multirange_get_range(rangetyp, multirange, i);
}
mr = PG_GETARG_MULTIRANGE_P(0);
/* allocate memory for user context */
- fctx = (multirange_unnest_fctx *) palloc(sizeof(multirange_unnest_fctx));
+ fctx = palloc_object(multirange_unnest_fctx);
/* initialize state */
fctx->mr = mr;
* bounds.
*/
nhist = hslot.nvalues;
- hist_lower = (RangeBound *) palloc(sizeof(RangeBound) * nhist);
- hist_upper = (RangeBound *) palloc(sizeof(RangeBound) * nhist);
+ hist_lower = palloc_array(RangeBound, nhist);
+ hist_upper = palloc_array(RangeBound, nhist);
for (i = 0; i < nhist; i++)
{
bool empty;
funccxt = SRF_FIRSTCALL_INIT();
oldcxt = MemoryContextSwitchTo(funccxt->multi_call_memory_ctx);
- multi = palloc(sizeof(mxact));
+ multi = palloc_object(mxact);
/* no need to allow for old values here */
multi->nmembers = GetMultiXactIdMembers(mxid, &multi->members, false,
false);
int bits;
inet *dst;
- dst = (inet *) palloc0(sizeof(inet));
+ dst = (inet *) palloc0_object(inet);
/*
* First, check to see if this is an IPv6 or IPv4 address. IPv6 addresses
i;
/* make sure any unused bits in a CIDR value are zeroed */
- addr = (inet *) palloc0(sizeof(inet));
+ addr = palloc0_object(inet);
ip_family(addr) = pq_getmsgbyte(buf);
if (ip_family(addr) != PGSQL_AF_INET &&
inet *
cidr_set_masklen_internal(const inet *src, int bits)
{
- inet *dst = (inet *) palloc0(sizeof(inet));
+ inet *dst = palloc0_object(inet);
ip_family(dst) = ip_family(src);
ip_bits(dst) = bits;
oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
- uss = palloc(sizeof(network_sortsupport_state));
+ uss = palloc_object(network_sortsupport_state);
uss->input_count = 0;
uss->estimating = true;
initHyperLogLog(&uss->abbr_card, 10);
*b;
/* make sure any unused bits are zeroed */
- dst = (inet *) palloc0(sizeof(inet));
+ dst = palloc0_object(inet);
maxbytes = ip_addrsize(ip);
bits = ip_bits(ip);
*b;
/* make sure any unused bits are zeroed */
- dst = (inet *) palloc0(sizeof(inet));
+ dst = palloc0_object(inet);
bits = ip_bits(ip);
a = ip_addr(ip);
unsigned char *b;
/* make sure any unused bits are zeroed */
- dst = (inet *) palloc0(sizeof(inet));
+ dst = palloc0_object(inet);
bits = ip_bits(ip);
b = ip_addr(dst);
unsigned char *b;
/* make sure any unused bits are zeroed */
- dst = (inet *) palloc0(sizeof(inet));
+ dst = palloc0_object(inet);
maxbytes = ip_addrsize(ip);
bits = ip_maxbits(ip) - ip_bits(ip);
inet *ip = PG_GETARG_INET_PP(0);
inet *dst;
- dst = (inet *) palloc0(sizeof(inet));
+ dst = palloc0_object(inet);
{
int nb = ip_addrsize(ip);
inet *ip2 = PG_GETARG_INET_PP(1);
inet *dst;
- dst = (inet *) palloc0(sizeof(inet));
+ dst = palloc0_object(inet);
if (ip_family(ip) != ip_family(ip2))
ereport(ERROR,
inet *ip2 = PG_GETARG_INET_PP(1);
inet *dst;
- dst = (inet *) palloc0(sizeof(inet));
+ dst = palloc0_object(inet);
if (ip_family(ip) != ip_family(ip2))
ereport(ERROR,
{
inet *dst;
- dst = (inet *) palloc0(sizeof(inet));
+ dst = palloc0_object(inet);
{
int nb = ip_addrsize(ip);
GistInetKey *result;
/* Make sure any unused bits are zeroed. */
- result = (GistInetKey *) palloc0(sizeof(GistInetKey));
+ result = palloc0_object(GistInetKey);
gk_ip_family(result) = family;
gk_ip_minbits(result) = minbits;
if (entry->leafkey)
{
- retval = palloc(sizeof(GISTENTRY));
+ retval = palloc_object(GISTENTRY);
if (DatumGetPointer(entry->key) != NULL)
{
inet *in = DatumGetInetPP(entry->key);
GistInetKey *r;
- r = (GistInetKey *) palloc0(sizeof(GistInetKey));
+ r = palloc0_object(GistInetKey);
gk_ip_family(r) = ip_family(in);
gk_ip_minbits(r) = ip_bits(in);
GISTENTRY *retval;
inet *dst;
- dst = (inet *) palloc0(sizeof(inet));
+ dst = palloc0_object(inet);
ip_family(dst) = gk_ip_family(key);
ip_bits(dst) = gk_ip_minbits(key);
memcpy(ip_addr(dst), gk_ip_addr(key), ip_addrsize(dst));
SET_INET_VARSIZE(dst);
- retval = palloc(sizeof(GISTENTRY));
+ retval = palloc_object(GISTENTRY);
gistentryinit(*retval, InetPGetDatum(dst), entry->rel, entry->page,
entry->offset, false);
/* Don't need labels; allocate output arrays */
out->nodeLabels = NULL;
- out->mapTuplesToNodes = (int *) palloc(sizeof(int) * in->nTuples);
- out->leafTupleDatums = (Datum *) palloc(sizeof(Datum) * in->nTuples);
+ out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+ out->leafTupleDatums = palloc_array(Datum, in->nTuples);
if (differentFamilies)
{
if (which)
{
- out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
+ out->nodeNumbers = palloc_array(int, in->nNodes);
for (i = 0; i < in->nNodes; i++)
{
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate memory for user context */
- fctx = (generate_series_numeric_fctx *)
- palloc(sizeof(generate_series_numeric_fctx));
+ fctx = palloc_object(generate_series_numeric_fctx);
/*
* Use fctx to keep state from call to call. Seed current with the
NumericSortSupport *nss;
MemoryContext oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
- nss = palloc(sizeof(NumericSortSupport));
+ nss = palloc_object(NumericSortSupport);
/*
* palloc a buffer for handling unaligned packed values in addition to
old_context = MemoryContextSwitchTo(agg_context);
- state = (NumericAggState *) palloc0(sizeof(NumericAggState));
+ state = palloc0_object(NumericAggState);
state->calcSumX2 = calcSumX2;
state->agg_context = agg_context;
{
NumericAggState *state;
- state = (NumericAggState *) palloc0(sizeof(NumericAggState));
+ state = palloc0_object(NumericAggState);
state->calcSumX2 = calcSumX2;
state->agg_context = CurrentMemoryContext;
old_context = MemoryContextSwitchTo(agg_context);
- state = (Int128AggState *) palloc0(sizeof(Int128AggState));
+ state = palloc0_object(Int128AggState);
state->calcSumX2 = calcSumX2;
MemoryContextSwitchTo(old_context);
{
Int128AggState *state;
- state = (Int128AggState *) palloc0(sizeof(Int128AggState));
+ state = palloc0_object(Int128AggState);
state->calcSumX2 = calcSumX2;
return state;
qcontext = fcinfo->flinfo->fn_mcxt;
oldcontext = MemoryContextSwitchTo(qcontext);
- qstate = (OSAPerQueryState *) palloc0(sizeof(OSAPerQueryState));
+ qstate = palloc0_object(OSAPerQueryState);
qstate->aggref = aggref;
qstate->qcontext = qcontext;
/* Now build the stuff we need in group-lifespan context */
oldcontext = MemoryContextSwitchTo(gcontext);
- osastate = (OSAPerGroupState *) palloc(sizeof(OSAPerGroupState));
+ osastate = palloc_object(OSAPerGroupState);
osastate->qstate = qstate;
osastate->gcontext = gcontext;
errmsg("out of memory")));
/* Output workspace cannot have more codes than input bytes */
- workspace = (wchar_t *) palloc((srclen + 1) * sizeof(wchar_t));
+ workspace = palloc_array(wchar_t, srclen + 1);
char2wchar(workspace, srclen + 1, src, srclen, loc);
errmsg("out of memory")));
/* Output workspace cannot have more codes than input bytes */
- workspace = (wchar_t *) palloc((srclen + 1) * sizeof(wchar_t));
+ workspace = palloc_array(wchar_t, srclen + 1);
char2wchar(workspace, srclen + 1, src, srclen, loc);
errmsg("out of memory")));
/* Output workspace cannot have more codes than input bytes */
- workspace = (wchar_t *) palloc((srclen + 1) * sizeof(wchar_t));
+ workspace = palloc_array(wchar_t, srclen + 1);
char2wchar(workspace, srclen + 1, src, srclen, loc);
}
/* Create the MVNDistinctItem */
- item = palloc(sizeof(MVNDistinctItem));
+ item = palloc_object(MVNDistinctItem);
item->nattributes = natts;
item->attributes = palloc0(natts * sizeof(AttrNumber));
item->ndistinct = (double) parse->ndistinct;
elog(ERROR, "range types do not match");
/* allocate memory for user context */
- fctx = (struct range_minus_multi_fctx *) palloc(sizeof(struct range_minus_multi_fctx));
+ fctx = palloc_object(struct range_minus_multi_fctx);
/*
* Initialize state. We can't store the range typcache in fn_extra
MultirangeType *mr = DatumGetMultirangeTypeP(entry->key);
RangeType *r;
TypeCacheEntry *typcache;
- GISTENTRY *retval = palloc(sizeof(GISTENTRY));
+ GISTENTRY *retval = palloc_object(GISTENTRY);
typcache = multirange_get_typcache(fcinfo, MultirangeTypeGetOid(mr));
r = multirange_get_union_range(typcache->rngtype, mr);
maxoff = entryvec->n - 1;
- sortItems = (SingleBoundSortItem *)
- palloc(maxoff * sizeof(SingleBoundSortItem));
+ sortItems = palloc_array(SingleBoundSortItem, maxoff);
/*
* Prepare auxiliary array and sort the values.
context.first = true;
/* Allocate arrays for sorted range bounds */
- by_lower = (NonEmptyRange *) palloc(nentries * sizeof(NonEmptyRange));
- by_upper = (NonEmptyRange *) palloc(nentries * sizeof(NonEmptyRange));
+ by_lower = palloc_array(NonEmptyRange, nentries);
+ by_upper = palloc_array(NonEmptyRange, nentries);
/* Fill arrays of bounds */
for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
*/
/* Allocate vectors for results */
- v->spl_left = (OffsetNumber *) palloc(nentries * sizeof(OffsetNumber));
- v->spl_right = (OffsetNumber *) palloc(nentries * sizeof(OffsetNumber));
+ v->spl_left = palloc_array(OffsetNumber, nentries);
+ v->spl_right = palloc_array(OffsetNumber, nentries);
v->spl_nleft = 0;
v->spl_nright = 0;
* either group without affecting overlap along selected axis.
*/
common_entries_count = 0;
- common_entries = (CommonEntry *) palloc(nentries * sizeof(CommonEntry));
+ common_entries = palloc_array(CommonEntry, nentries);
/*
* Distribute entries which can be distributed unambiguously, and collect
* bounds.
*/
nhist = hslot.nvalues;
- hist_lower = (RangeBound *) palloc(sizeof(RangeBound) * nhist);
- hist_upper = (RangeBound *) palloc(sizeof(RangeBound) * nhist);
+ hist_lower = palloc_array(RangeBound, nhist);
+ hist_upper = palloc_array(RangeBound, nhist);
for (i = 0; i < nhist; i++)
{
range_deserialize(typcache, DatumGetRangeTypeP(hslot.values[i]),
RangeTypeGetOid(DatumGetRangeTypeP(in->datums[0])));
/* Allocate memory for bounds */
- lowerBounds = palloc(sizeof(RangeBound) * in->nTuples);
- upperBounds = palloc(sizeof(RangeBound) * in->nTuples);
+ lowerBounds = palloc_array(RangeBound, in->nTuples);
+ upperBounds = palloc_array(RangeBound, in->nTuples);
j = 0;
/* Deserialize bounds of ranges, count non-empty ranges */
out->prefixDatum = PointerGetDatum(NULL);
out->nodeLabels = NULL;
- out->mapTuplesToNodes = palloc(sizeof(int) * in->nTuples);
- out->leafTupleDatums = palloc(sizeof(Datum) * in->nTuples);
+ out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+ out->leafTupleDatums = palloc_array(Datum, in->nTuples);
/* Place all ranges into node 0 */
for (i = 0; i < in->nTuples; i++)
out->nNodes = (in->level == 0) ? 5 : 4;
out->nodeLabels = NULL; /* we don't need node labels */
- out->mapTuplesToNodes = palloc(sizeof(int) * in->nTuples);
- out->leafTupleDatums = palloc(sizeof(Datum) * in->nTuples);
+ out->mapTuplesToNodes = palloc_array(int, in->nTuples);
+ out->leafTupleDatums = palloc_array(Datum, in->nTuples);
/*
* Assign ranges to corresponding nodes according to quadrants relative to
{
/* Report that all nodes should be visited */
out->nNodes = in->nNodes;
- out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
+ out->nodeNumbers = palloc_array(int, in->nNodes);
for (i = 0; i < in->nNodes; i++)
out->nodeNumbers[i] = i;
PG_RETURN_VOID();
}
/* We must descend into the quadrant(s) identified by 'which' */
- out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
+ out->nodeNumbers = palloc_array(int, in->nNodes);
if (needPrevious)
- out->traversalValues = (void **) palloc(sizeof(void *) * in->nNodes);
+ out->traversalValues = palloc_array(void *, in->nNodes);
out->nNodes = 0;
/*
has_subdiff = OidIsValid(typcache->rng_subdiff_finfo.fn_oid);
/* Allocate memory to hold range bounds and lengths of the sample ranges. */
- lowers = (RangeBound *) palloc(sizeof(RangeBound) * samplerows);
- uppers = (RangeBound *) palloc(sizeof(RangeBound) * samplerows);
- lengths = (float8 *) palloc(sizeof(float8) * samplerows);
+ lowers = palloc_array(RangeBound, samplerows);
+ uppers = palloc_array(RangeBound, samplerows);
+ lengths = palloc_array(float8, samplerows);
/* Loop over the sample ranges. */
for (range_no = 0; range_no < samplerows; range_no++)
stats->statypalign[slot_idx] = 'd';
/* Store the fraction of empty ranges */
- emptyfrac = (float4 *) palloc(sizeof(float4));
+ emptyfrac = palloc_object(float4);
*emptyfrac = ((double) empty_cnt) / ((double) non_null_cnt);
stats->stanumbers[slot_idx] = emptyfrac;
stats->numnumbers[slot_idx] = 1;
*/
/* Convert pattern string to wide characters */
- pattern = (pg_wchar *) palloc((text_re_len + 1) * sizeof(pg_wchar));
+ pattern = palloc_array(pg_wchar, text_re_len + 1);
pattern_len = pg_mb2wchar_with_len(text_re_val,
pattern,
text_re_len);
bool match;
/* Convert data string to wide characters */
- data = (pg_wchar *) palloc((dat_len + 1) * sizeof(pg_wchar));
+ data = palloc_array(pg_wchar, dat_len + 1);
data_len = pg_mb2wchar_with_len(dat, data, dat_len);
/* Perform RE match and return result */
Assert(matchctx->nmatches == 1);
/* Create workspace that build_regexp_match_result needs */
- matchctx->elems = (Datum *) palloc(sizeof(Datum) * matchctx->npatterns);
- matchctx->nulls = (bool *) palloc(sizeof(bool) * matchctx->npatterns);
+ matchctx->elems = palloc_array(Datum, matchctx->npatterns);
+ matchctx->nulls = palloc_array(bool, matchctx->npatterns);
PG_RETURN_DATUM(PointerGetDatum(build_regexp_match_result(matchctx)));
}
true, false, false);
/* Pre-create workspace that build_regexp_match_result needs */
- matchctx->elems = (Datum *) palloc(sizeof(Datum) * matchctx->npatterns);
- matchctx->nulls = (bool *) palloc(sizeof(bool) * matchctx->npatterns);
+ matchctx->elems = palloc_array(Datum, matchctx->npatterns);
+ matchctx->nulls = palloc_array(bool, matchctx->npatterns);
MemoryContextSwitchTo(oldcontext);
funcctx->user_fctx = matchctx;
bool ignore_degenerate,
bool fetching_unmatched)
{
- regexp_matches_ctx *matchctx = palloc0(sizeof(regexp_matches_ctx));
+ regexp_matches_ctx *matchctx = palloc0_object(regexp_matches_ctx);
int eml = pg_database_encoding_max_length();
int orig_len;
pg_wchar *wide_str;
/* convert string to pg_wchar form for matching */
orig_len = VARSIZE_ANY_EXHDR(orig_str);
- wide_str = (pg_wchar *) palloc(sizeof(pg_wchar) * (orig_len + 1));
+ wide_str = palloc_array(pg_wchar, orig_len + 1);
wide_len = pg_mb2wchar_with_len(VARDATA_ANY(orig_str), wide_str, orig_len);
/* set up the compiled pattern */
}
/* temporary output space for RE package */
- pmatch = palloc(sizeof(regmatch_t) * pmatch_len);
+ pmatch = palloc_array(regmatch_t, pmatch_len);
/*
* the real output space (grown dynamically if needed)
* than at 2^27
*/
array_len = re_flags->glob ? 255 : 31;
- matchctx->match_locs = (int *) palloc(sizeof(int) * array_len);
+ matchctx->match_locs = palloc_array(int, array_len);
array_idx = 0;
/* search for the pattern, perhaps repeatedly */
my_extra->ncolumns = ncolumns;
}
- values = (Datum *) palloc(ncolumns * sizeof(Datum));
- nulls = (bool *) palloc(ncolumns * sizeof(bool));
+ values = palloc_array(Datum, ncolumns);
+ nulls = palloc_array(bool, ncolumns);
/*
* Scan the string. We use "buf" to accumulate the de-quoted data for
my_extra->ncolumns = ncolumns;
}
- values = (Datum *) palloc(ncolumns * sizeof(Datum));
- nulls = (bool *) palloc(ncolumns * sizeof(bool));
+ values = palloc_array(Datum, ncolumns);
+ nulls = palloc_array(bool, ncolumns);
/* Break down the tuple into fields */
heap_deform_tuple(&tuple, tupdesc, values, nulls);
my_extra->ncolumns = ncolumns;
}
- values = (Datum *) palloc(ncolumns * sizeof(Datum));
- nulls = (bool *) palloc(ncolumns * sizeof(bool));
+ values = palloc_array(Datum, ncolumns);
+ nulls = palloc_array(bool, ncolumns);
/* Fetch number of columns user thinks it has */
usercols = pq_getmsgint(buf, 4);
my_extra->ncolumns = ncolumns;
}
- values = (Datum *) palloc(ncolumns * sizeof(Datum));
- nulls = (bool *) palloc(ncolumns * sizeof(bool));
+ values = palloc_array(Datum, ncolumns);
+ nulls = palloc_array(bool, ncolumns);
/* Break down the tuple into fields */
heap_deform_tuple(&tuple, tupdesc, values, nulls);
}
/* Break down the tuple into fields */
- values = (Datum *) palloc(ncolumns * sizeof(Datum));
- nulls = (bool *) palloc(ncolumns * sizeof(bool));
+ values = palloc_array(Datum, ncolumns);
+ nulls = palloc_array(bool, ncolumns);
heap_deform_tuple(&tuple, tupdesc, values, nulls);
for (int i = 0; i < ncolumns; i++)
}
/* Break down the tuple into fields */
- values = (Datum *) palloc(ncolumns * sizeof(Datum));
- nulls = (bool *) palloc(ncolumns * sizeof(bool));
+ values = palloc_array(Datum, ncolumns);
+ nulls = palloc_array(bool, ncolumns);
heap_deform_tuple(&tuple, tupdesc, values, nulls);
for (int i = 0; i < ncolumns; i++)
deparse_namespace *dpns;
RangeTblEntry *rte;
- dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
+ dpns = palloc0_object(deparse_namespace);
/* Build a minimal RTE for the rel */
rte = makeNode(RangeTblEntry);
{
deparse_namespace *dpns;
- dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
+ dpns = palloc0_object(deparse_namespace);
/* Initialize fields that stay the same across the whole plan tree */
dpns->rtable = pstmt->rtable;
}
}
- varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
+ varinfo = palloc_object(GroupVarInfo);
varinfo->var = var;
varinfo->rel = vardata->rel;
* estimate_multivariate_ndistinct(), which doesn't care about
* ndistinct and isdefault fields. Thus, skip these fields.
*/
- varinfo = (GroupVarInfo *) palloc0(sizeof(GroupVarInfo));
+ varinfo = palloc0_object(GroupVarInfo);
varinfo->var = expr;
varinfo->rel = root->simple_rel_array[relid];
varinfos = lappend(varinfos, varinfo);
if (!OidIsValid(skipSupportFunction))
return NULL;
- sksup = palloc(sizeof(SkipSupportData));
+ sksup = palloc_object(SkipSupportData);
OidFunctionCall1(skipSupportFunction, PointerGetDatum(sksup));
if (reverse)
"tid", str)));
offsetNumber = (OffsetNumber) cvt;
- result = (ItemPointer) palloc(sizeof(ItemPointerData));
+ result = (ItemPointer) palloc_object(ItemPointerData);
ItemPointerSet(result, blockNumber, offsetNumber);
blockNumber = pq_getmsgint(buf, sizeof(blockNumber));
offsetNumber = pq_getmsgint(buf, sizeof(offsetNumber));
- result = (ItemPointer) palloc(sizeof(ItemPointerData));
+ result = (ItemPointer) palloc_object(ItemPointerData);
ItemPointerSet(result, blockNumber, offsetNumber);
Snapshot snapshot;
TableScanDesc scan;
- result = (ItemPointer) palloc(sizeof(ItemPointerData));
+ result = (ItemPointer) palloc_object(ItemPointerData);
aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
ACL_SELECT);
PG_RETURN_NULL();
}
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
switch (dtype)
{
int32 typmod = PG_GETARG_INT32(2);
Interval *interval;
- interval = (Interval *) palloc(sizeof(Interval));
+ interval = palloc_object(Interval);
interval->time = pq_getmsgint64(buf);
interval->day = pq_getmsgint(buf, sizeof(interval->day));
int32 typmod = PG_GETARG_INT32(1);
Interval *result;
- result = palloc(sizeof(Interval));
+ result = palloc_object(Interval);
*result = *interval;
AdjustIntervalForTypmod(result, typmod, NULL);
if (isinf(secs) || isnan(secs))
goto out_of_range;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
/* years and months -> months */
if (pg_mul_s32_overflow(years, MONTHS_PER_YEAR, &result->month) ||
Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
Interval *result;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
/*
* Handle infinities.
TimeOffset wholeday;
int32 wholemonth;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
result->month = span->month;
result->day = span->day;
result->time = span->time;
Interval *result;
TimeOffset wholeday;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
result->month = span->month;
result->day = span->day;
result->time = span->time;
Interval *result;
int32 wholemonth;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
result->month = span->month;
result->day = span->day;
result->time = span->time;
Interval *interval = PG_GETARG_INTERVAL_P(0);
Interval *result;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
interval_um_internal(interval, result);
PG_RETURN_INTERVAL_P(result);
Interval *span2 = PG_GETARG_INTERVAL_P(1);
Interval *result;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
/*
* Handle infinities.
Interval *span2 = PG_GETARG_INTERVAL_P(1);
Interval *result;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
/*
* Handle infinities.
orig_day = span->day;
Interval *result;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
/*
* Handle NaN and infinities.
orig_day = span->day;
Interval *result;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
if (factor == 0.0)
ereport(ERROR,
old_context = MemoryContextSwitchTo(agg_context);
- state = (IntervalAggState *) palloc0(sizeof(IntervalAggState));
+ state = palloc0_object(IntervalAggState);
MemoryContextSwitchTo(old_context);
initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
VARSIZE_ANY_EXHDR(sstate));
- result = (IntervalAggState *) palloc0(sizeof(IntervalAggState));
+ result = palloc0_object(IntervalAggState);
/* N */
result->N = pq_getmsgint64(&buf);
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("interval out of range")));
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
if (state->pInfcount > 0)
INTERVAL_NOEND(result);
else
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("interval out of range")));
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
if (state->pInfcount > 0)
INTERVAL_NOEND(result);
struct pg_tm tt2,
*tm2 = &tt2;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
/*
* Handle infinities.
int tz1;
int tz2;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
/*
* Handle infinities.
struct pg_itm tt,
*tm = &tt;
- result = (Interval *) palloc(sizeof(Interval));
+ result = palloc_object(Interval);
lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
VARSIZE_ANY_EXHDR(units),
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate memory for user context */
- fctx = (generate_series_timestamp_fctx *)
- palloc(sizeof(generate_series_timestamp_fctx));
+ fctx = palloc_object(generate_series_timestamp_fctx);
/*
* Use fctx to keep state from call to call. Seed current with the
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate memory for user context */
- fctx = (generate_series_timestamptz_fctx *)
- palloc(sizeof(generate_series_timestamptz_fctx));
+ fctx = palloc_object(generate_series_timestamptz_fctx);
/*
* Use fctx to keep state from call to call. Seed current with the
int i;
WordEntry *we = ARRPTR(vector);
- entries = (Datum *) palloc(sizeof(Datum) * vector->size);
+ entries = palloc_array(Datum, vector->size);
for (i = 0; i < vector->size; i++)
{
}
*nentries = j;
- entries = (Datum *) palloc(sizeof(Datum) * j);
- partialmatch = *ptr_partialmatch = (bool *) palloc(sizeof(bool) * j);
+ entries = palloc_array(Datum, j);
+ partialmatch = *ptr_partialmatch = palloc_array(bool, j);
/*
* Make map to convert item's number to corresponding operand's (the
* same, entry's) number. Entry's number is used in check array in
* consistent method. We use the same map for each entry.
*/
- *extra_data = (Pointer *) palloc(sizeof(Pointer) * j);
- map_item_operand = (int *) palloc0(sizeof(int) * query->size);
+ *extra_data = palloc_array(Pointer, j);
+ map_item_operand = palloc0_array(int, query->size);
/* Now rescan the VAL items and fill in the arrays */
j = 0;
res = ressign;
}
- retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+ retval = palloc_object(GISTENTRY);
gistentryinit(*retval, PointerGetDatum(res),
entry->rel, entry->page,
entry->offset, false);
}
res = gtsvector_alloc(SIGNKEY | ALLISTRUE, siglen, sign);
- retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+ retval = palloc_object(GISTENTRY);
gistentryinit(*retval, PointerGetDatum(res),
entry->rel, entry->page,
entry->offset, false);
if (key != (SignTSVector *) DatumGetPointer(entry->key))
{
- GISTENTRY *retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+ GISTENTRY *retval = palloc_object(GISTENTRY);
gistentryinit(*retval, PointerGetDatum(key),
entry->rel, entry->page,
v->spl_left = (OffsetNumber *) palloc(nbytes);
v->spl_right = (OffsetNumber *) palloc(nbytes);
- cache = (CACHESIGN *) palloc(sizeof(CACHESIGN) * (maxoff + 2));
+ cache = palloc_array(CACHESIGN, maxoff + 2);
cache_sign = palloc(siglen * (maxoff + 2));
for (j = 0; j < maxoff + 2; j++)
maxoff = OffsetNumberNext(maxoff);
fillcache(&cache[maxoff], GETENTRY(entryvec, maxoff), siglen);
/* sort before ... */
- costvector = (SPLITCOST *) palloc(sizeof(SPLITCOST) * maxoff);
+ costvector = palloc_array(SPLITCOST, maxoff);
for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
{
costvector[j - 1].pos = j;
Assert(oper == OP_NOT || oper == OP_AND || oper == OP_OR || oper == OP_PHRASE);
- tmp = (QueryOperator *) palloc0(sizeof(QueryOperator));
+ tmp = palloc0_object(QueryOperator);
tmp->type = QI_OPR;
tmp->oper = oper;
tmp->distance = (oper == OP_PHRASE) ? distance : 0;
errmsg("operand is too long in tsquery: \"%s\"",
state->buffer)));
- tmp = (QueryOperand *) palloc0(sizeof(QueryOperand));
+ tmp = palloc0_object(QueryOperand);
tmp->type = QI_VAL;
tmp->weight = weight;
tmp->prefix = prefix;
{
QueryOperand *tmp;
- tmp = (QueryOperand *) palloc0(sizeof(QueryOperand));
+ tmp = palloc0_object(QueryOperand);
tmp->type = QI_VALSTOP;
state->polstr = lcons(tmp, state->polstr);
nrm.curpol = in->curpol;
nrm.op = in->op;
nrm.buflen = 16;
- nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
+ nrm.cur = nrm.buf = palloc_array(char, nrm.buflen);
/* get right operand */
infix(&nrm, priority, (op == OP_PHRASE));
}
nrm.curpol = GETQUERY(query);
nrm.buflen = 32;
- nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
+ nrm.cur = nrm.buf = palloc_array(char, nrm.buflen);
*(nrm.cur) = '\0';
nrm.op = GETOPERAND(query);
infix(&nrm, -1 /* lowest priority */ , false);
{
nrm.curpol = q;
nrm.buflen = 32;
- nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
+ nrm.cur = nrm.buf = palloc_array(char, nrm.buflen);
*(nrm.cur) = '\0';
nrm.op = GETOPERAND(query);
infix(&nrm, -1, false);
static NODE *
maketree(QueryItem *in)
{
- NODE *node = (NODE *) palloc(sizeof(NODE));
+ NODE *node = palloc_object(NODE);
/* since this function recurses, it could be driven to stack overflow. */
check_stack_depth();
{
TSQuerySign sign;
- retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+ retval = palloc_object(GISTENTRY);
sign = makeTSQuerySign(DatumGetTSQuery(entry->key));
gistentryinit(*retval, TSQuerySignGetDatum(sign),
datum_r = GETENTRY(entryvec, seed_2);
maxoff = OffsetNumberNext(maxoff);
- costvector = (SPLITCOST *) palloc(sizeof(SPLITCOST) * maxoff);
+ costvector = palloc_array(SPLITCOST, maxoff);
for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
{
costvector[j - 1].pos = j;
static QTNode *
join_tsqueries(TSQuery a, TSQuery b, int8 operator, uint16 distance)
{
- QTNode *res = (QTNode *) palloc0(sizeof(QTNode));
+ QTNode *res = palloc0_object(QTNode);
res->flags |= QTN_NEEDFREE;
- res->valnode = (QueryItem *) palloc0(sizeof(QueryItem));
+ res->valnode = palloc0_object(QueryItem);
res->valnode->type = QI_OPR;
res->valnode->qoperator.oper = operator;
if (operator == OP_PHRASE)
res->valnode->qoperator.distance = distance;
- res->child = (QTNode **) palloc0(sizeof(QTNode *) * 2);
+ res->child = palloc0_array(QTNode *, 2);
res->child[0] = QT2QTN(GETQUERY(b), GETOPERAND(b));
res->child[1] = QT2QTN(GETQUERY(a), GETOPERAND(a));
res->nchild = 2;
if (a->size == 0)
PG_RETURN_POINTER(a);
- res = (QTNode *) palloc0(sizeof(QTNode));
+ res = palloc0_object(QTNode);
res->flags |= QTN_NEEDFREE;
- res->valnode = (QueryItem *) palloc0(sizeof(QueryItem));
+ res->valnode = palloc0_object(QueryItem);
res->valnode->type = QI_OPR;
res->valnode->qoperator.oper = OP_NOT;
- res->child = (QTNode **) palloc0(sizeof(QTNode *));
+ res->child = palloc0_object(QTNode *);
res->child[0] = QT2QTN(GETQUERY(a), GETOPERAND(a));
res->nchild = 1;
int nvalues = 0;
int i;
- values = (char **) palloc(sizeof(char *) * a->size);
+ values = palloc_array(char *, a->size);
for (i = 0; i < a->size; i++)
{
QTNode *
QT2QTN(QueryItem *in, char *operand)
{
- QTNode *node = (QTNode *) palloc0(sizeof(QTNode));
+ QTNode *node = palloc0_object(QTNode);
/* since this function recurses, it could be driven to stack overflow. */
check_stack_depth();
if (in->type == QI_OPR)
{
- node->child = (QTNode **) palloc0(sizeof(QTNode *) * 2);
+ node->child = palloc0_array(QTNode *, 2);
node->child[0] = QT2QTN(in + 1, operand);
node->sign = node->child[0]->sign;
if (in->qoperator.oper == OP_NOT)
int oldnchild = in->nchild;
in->nchild += cc->nchild - 1;
- in->child = (QTNode **) repalloc(in->child, in->nchild * sizeof(QTNode *));
+ in->child = repalloc_array(in->child, QTNode *, in->nchild);
if (i + 1 != oldnchild)
memmove(in->child + i + cc->nchild, in->child + i + 1,
while (in->nchild > 2)
{
- QTNode *nn = (QTNode *) palloc0(sizeof(QTNode));
+ QTNode *nn = palloc0_object(QTNode);
- nn->valnode = (QueryItem *) palloc0(sizeof(QueryItem));
- nn->child = (QTNode **) palloc0(sizeof(QTNode *) * 2);
+ nn->valnode = palloc0_object(QueryItem);
+ nn->child = palloc0_array(QTNode *, 2);
nn->nchild = 2;
nn->flags = QTN_NEEDFREE;
/* since this function recurses, it could be driven to stack overflow. */
check_stack_depth();
- out = (QTNode *) palloc(sizeof(QTNode));
+ out = palloc_object(QTNode);
*out = *in;
- out->valnode = (QueryItem *) palloc(sizeof(QueryItem));
+ out->valnode = palloc_object(QueryItem);
*(out->valnode) = *(in->valnode);
out->flags |= QTN_NEEDFREE;
{
int i;
- out->child = (QTNode **) palloc(sizeof(QTNode *) * in->nchild);
+ out->child = palloc_array(QTNode *, in->nchild);
for (i = 0; i < in->nchild; i++)
out->child[i] = QTNCopy(in->child[i]);
**ptr,
**prevptr;
- ptr = res = (QueryOperand **) palloc(sizeof(QueryOperand *) * *size);
+ ptr = res = palloc_array(QueryOperand *, *size);
/* Collect all operands from the tree to res */
while ((*size)--)
pfree(item);
return calc_rank_or(w, t, q);
}
- pos = (WordEntryPosVector **) palloc0(sizeof(WordEntryPosVector *) * q->size);
+ pos = palloc0_array(WordEntryPosVector *, q->size);
/* A dummy WordEntryPos array to use when haspos is false */
posnull.npos = 1;
cur = 0;
DocRepresentation *doc;
- doc = (DocRepresentation *) palloc(sizeof(DocRepresentation) * len);
+ doc = palloc_array(DocRepresentation, len);
/*
* Iterate through query to make DocRepresentation for words and it's
* Join QueryItem per WordEntry and its position
*/
storage.pos = doc->pos;
- storage.data.query.items = palloc(sizeof(QueryItem *) * qr->query->size);
+ storage.data.query.items = palloc_array(QueryItem *, qr->query->size);
storage.data.query.items[0] = doc->data.map.item;
storage.data.query.nitem = 1;
*wptr = storage;
wptr++;
storage.pos = rptr->pos;
- storage.data.query.items = palloc(sizeof(QueryItem *) * qr->query->size);
+ storage.data.query.items = palloc_array(QueryItem *, qr->query->size);
storage.data.query.items[0] = rptr->data.map.item;
storage.data.query.nitem = 1;
}
}
qr.query = query;
- qr.operandData = (QueryRepresentationOperand *)
- palloc0(sizeof(QueryRepresentationOperand) * query->size);
+ qr.operandData = palloc0_array(QueryRepresentationOperand, query->size);
doc = get_docrep(txt, &qr, &doclen);
if (!doc)
state = init_tsvector_parser(buf, 0, escontext);
arrlen = 64;
- arr = (WordEntryIN *) palloc(sizeof(WordEntryIN) * arrlen);
- cur = tmpbuf = (char *) palloc(buflen);
+ arr = palloc_array(WordEntryIN, arrlen);
+ cur = tmpbuf = palloc_array(char, buflen);
while (gettoken_tsvector(state, &token, &toklen, &pos, &poslen, NULL))
{
/*
* Filter position information by weights
*/
- dptr = data->pos = palloc(sizeof(WordEntryPos) * posvec->npos);
+ dptr = data->pos = palloc_array(WordEntryPos, posvec->npos);
data->allocated = true;
/* Is there a position with a matching weight? */
if (totalpos == 0)
{
totalpos = 256;
- allpos = palloc(sizeof(WordEntryPos) * totalpos);
+ allpos = palloc_array(WordEntryPos, totalpos);
}
else
{
totalpos *= 2;
- allpos = repalloc(allpos, sizeof(WordEntryPos) * totalpos);
+ allpos = repalloc_array(allpos, WordEntryPos, totalpos);
}
}
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
- stat->stack = palloc0(sizeof(StatEntry *) * (stat->maxdepth + 1));
+ stat->stack = palloc0_array(StatEntry *, stat->maxdepth + 1);
stat->stackpos = 0;
node = stat->root;
prs.lenwords = 32;
prs.curwords = 0;
prs.pos = 0;
- prs.words = (ParsedWord *) palloc(sizeof(ParsedWord) * prs.lenwords);
+ prs.words = palloc_array(ParsedWord, prs.lenwords);
/* find all words in indexable column(s) */
for (i = 2; i < trigger->tgnargs; i++)
{
TSVectorParseState state;
- state = (TSVectorParseState) palloc(sizeof(struct TSVectorParseStateData));
+ state = palloc_object(struct TSVectorParseStateData);
state->prsbuf = input;
state->bufstart = input;
state->len = 32;
if (posalen == 0)
{
posalen = 4;
- pos = (WordEntryPos *) palloc(sizeof(WordEntryPos) * posalen);
+ pos = palloc_array(WordEntryPos, posalen);
npos = 0;
}
else if (npos + 1 >= posalen)
{
posalen *= 2;
- pos = (WordEntryPos *) repalloc(pos, sizeof(WordEntryPos) * posalen);
+ pos = repalloc_array(pos, WordEntryPos, posalen);
}
npos++;
WEP_SETPOS(pos[npos - 1], LIMITPOS(atoi(state->prsbuf)));
char *uuid_str = PG_GETARG_CSTRING(0);
pg_uuid_t *uuid;
- uuid = (pg_uuid_t *) palloc(sizeof(*uuid));
+ uuid = palloc_object(pg_uuid_t);
string_to_uuid(uuid_str, uuid, fcinfo->context);
PG_RETURN_UUID_P(uuid);
}
oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
- uss = palloc(sizeof(uuid_sortsupport_state));
+ uss = palloc_object(uuid_sortsupport_state);
uss->input_count = 0;
uss->estimating = true;
initHyperLogLog(&uss->abbr_card, 10);
*/
if (abbreviate || !collate_c)
{
- sss = palloc(sizeof(VarStringSortSupport));
+ sss = palloc_object(VarStringSortSupport);
sss->buf1 = palloc(TEXTBUFLEN);
sss->buflen1 = TEXTBUFLEN;
sss->buf2 = palloc(TEXTBUFLEN);
pg_xml_init_library();
/* Create error handling context structure */
- errcxt = (PgXmlErrorContext *) palloc(sizeof(PgXmlErrorContext));
+ errcxt = palloc_object(PgXmlErrorContext);
errcxt->magic = ERRCXT_MAGIC;
errcxt->strictness = strictness;
errcxt->err_occurred = false;
XmlTableBuilderData *xtCxt;
PgXmlErrorContext *xmlerrcxt;
- xtCxt = palloc0(sizeof(XmlTableBuilderData));
+ xtCxt = palloc0_object(XmlTableBuilderData);
xtCxt->magic = XMLTABLE_CONTEXT_MAGIC;
xtCxt->natts = natts;
- xtCxt->xpathscomp = palloc0(sizeof(xmlXPathCompExprPtr) * natts);
+ xtCxt->xpathscomp = palloc0_array(xmlXPathCompExprPtr, natts);
xmlerrcxt = pg_xml_init(PG_XML_STRICTNESS_ALL);
*/
if (CacheHdr == NULL)
{
- CacheHdr = (CatCacheHeader *) palloc(sizeof(CatCacheHeader));
+ CacheHdr = palloc_object(CatCacheHeader);
slist_init(&CacheHdr->ch_caches);
CacheHdr->ch_ntup = 0;
#ifdef CATCACHE_STATS
{
/* Set up keys for a negative cache entry */
oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
- ct = (CatCTup *) palloc(sizeof(CatCTup));
+ ct = palloc_object(CatCTup);
/*
* Store keys - they'll point into separately allocated memory if not
oldcontext = MemoryContextSwitchTo(EventTriggerCacheContext);
/* Allocate new cache item. */
- item = palloc0(sizeof(EventTriggerCacheItem));
+ item = palloc0_object(EventTriggerCacheItem);
item->fnoid = form->evtfoid;
item->enabled = form->evtenabled;
Assert(inplaceInvalInfo == NULL);
/* gone after WAL insertion CritSection ends, so use current context */
- myInfo = (InvalidationInfo *) palloc0(sizeof(InvalidationInfo));
+ myInfo = palloc0_object(InvalidationInfo);
/* Stash our messages past end of the transactional messages, if any. */
if (transInvalInfo != NULL)
if (cmptype == COMPARE_INVALID)
continue;
- thisresult = (OpIndexInterpretation *)
- palloc(sizeof(OpIndexInterpretation));
+ thisresult = palloc_object(OpIndexInterpretation);
thisresult->opfamily_id = op_form->amopfamily;
thisresult->cmptype = cmptype;
thisresult->oplefttype = op_form->amoplefttype;
continue;
/* OK, report it as COMPARE_NE */
- thisresult = (OpIndexInterpretation *)
- palloc(sizeof(OpIndexInterpretation));
+ thisresult = palloc_object(OpIndexInterpretation);
thisresult->opfamily_id = op_form->amopfamily;
thisresult->cmptype = COMPARE_NE;
thisresult->oplefttype = op_form->amoplefttype;
/* Allocate assorted arrays in the partkeycxt, which we'll fill below */
oldcxt = MemoryContextSwitchTo(partkeycxt);
- key->partattrs = (AttrNumber *) palloc0(key->partnatts * sizeof(AttrNumber));
- key->partopfamily = (Oid *) palloc0(key->partnatts * sizeof(Oid));
- key->partopcintype = (Oid *) palloc0(key->partnatts * sizeof(Oid));
- key->partsupfunc = (FmgrInfo *) palloc0(key->partnatts * sizeof(FmgrInfo));
-
- key->partcollation = (Oid *) palloc0(key->partnatts * sizeof(Oid));
- key->parttypid = (Oid *) palloc0(key->partnatts * sizeof(Oid));
- key->parttypmod = (int32 *) palloc0(key->partnatts * sizeof(int32));
- key->parttyplen = (int16 *) palloc0(key->partnatts * sizeof(int16));
- key->parttypbyval = (bool *) palloc0(key->partnatts * sizeof(bool));
- key->parttypalign = (char *) palloc0(key->partnatts * sizeof(char));
- key->parttypcoll = (Oid *) palloc0(key->partnatts * sizeof(Oid));
+ key->partattrs = palloc0_array(AttrNumber, key->partnatts);
+ key->partopfamily = palloc0_array(Oid, key->partnatts);
+ key->partopcintype = palloc0_array(Oid, key->partnatts);
+ key->partsupfunc = palloc0_array(FmgrInfo, key->partnatts);
+
+ key->partcollation = palloc0_array(Oid, key->partnatts);
+ key->parttypid = palloc0_array(Oid, key->partnatts);
+ key->parttypmod = palloc0_array(int32, key->partnatts);
+ key->parttyplen = palloc0_array(int16, key->partnatts);
+ key->parttypbyval = palloc0_array(bool, key->partnatts);
+ key->parttypalign = palloc0_array(char, key->partnatts);
+ key->parttypcoll = palloc0_array(Oid, key->partnatts);
MemoryContextSwitchTo(oldcxt);
/* determine support function number to search for */
*/
oldcxt = MemoryContextSwitchTo(source_context);
- plansource = (CachedPlanSource *) palloc0(sizeof(CachedPlanSource));
+ plansource = palloc0_object(CachedPlanSource);
plansource->magic = CACHEDPLANSOURCE_MAGIC;
plansource->raw_parse_tree = copyObject(raw_parse_tree);
plansource->analyzed_parse_tree = NULL;
* Create and fill the CachedPlanSource struct within the caller's memory
* context. Most fields are just left empty for the moment.
*/
- plansource = (CachedPlanSource *) palloc0(sizeof(CachedPlanSource));
+ plansource = palloc0_object(CachedPlanSource);
plansource->magic = CACHEDPLANSOURCE_MAGIC;
plansource->raw_parse_tree = raw_parse_tree;
plansource->analyzed_parse_tree = NULL;
if (num_params > 0)
{
- plansource->param_types = (Oid *) palloc(num_params * sizeof(Oid));
+ plansource->param_types = palloc_array(Oid, num_params);
memcpy(plansource->param_types, param_types, num_params * sizeof(Oid));
}
else
/*
* Create and fill the CachedPlan struct within the new context.
*/
- plan = (CachedPlan *) palloc(sizeof(CachedPlan));
+ plan = palloc_object(CachedPlan);
plan->magic = CACHEDPLAN_MAGIC;
plan->stmt_list = plist;
oldcxt = MemoryContextSwitchTo(source_context);
- newsource = (CachedPlanSource *) palloc0(sizeof(CachedPlanSource));
+ newsource = palloc0_object(CachedPlanSource);
newsource->magic = CACHEDPLANSOURCE_MAGIC;
newsource->raw_parse_tree = copyObject(plansource->raw_parse_tree);
newsource->analyzed_parse_tree = copyObject(plansource->analyzed_parse_tree);
newsource->commandTag = plansource->commandTag;
if (plansource->num_params > 0)
{
- newsource->param_types = (Oid *)
- palloc(plansource->num_params * sizeof(Oid));
+ newsource->param_types = palloc_array(Oid, plansource->num_params);
memcpy(newsource->param_types, plansource->param_types,
plansource->num_params * sizeof(Oid));
}
oldcxt = MemoryContextSwitchTo(cexpr_context);
- cexpr = (CachedExpression *) palloc(sizeof(CachedExpression));
+ cexpr = palloc_object(CachedExpression);
cexpr->magic = CACHEDEXPR_MAGIC;
cexpr->expr = copyObject(expr);
cexpr->is_valid = true;
/*
* allocate and zero space for new relation descriptor
*/
- relation = (Relation) palloc0(sizeof(RelationData));
+ relation = palloc0_object(RelationData);
/* make sure relation is marked as having no open file yet */
relation->rd_smgr = NULL;
/*
* allocate new relation desc, clear all fields of reldesc
*/
- relation = (Relation) palloc0(sizeof(RelationData));
+ relation = palloc0_object(RelationData);
/* make sure relation is marked as having no open file yet */
relation->rd_smgr = NULL;
/* mark not-null status */
if (has_not_null)
{
- TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
+ TupleConstr *constr = palloc0_object(TupleConstr);
constr->has_not_null = true;
relation->rd_att->constr = constr;
/*
* allocate a new relation descriptor and fill in basic state fields.
*/
- rel = (Relation) palloc0(sizeof(RelationData));
+ rel = palloc0_object(RelationData);
/* make sure relation is marked as having no open file yet */
rel->rd_smgr = NULL;
if (has_not_null)
{
- TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
+ TupleConstr *constr = palloc0_object(TupleConstr);
constr->has_not_null = true;
rel->rd_att->constr = constr;
indnkeyatts = IndexRelationGetNumberOfKeyAttributes(indexRelation);
/* Allocate result space in caller context */
- *operators = ops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
- *procs = funcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
- *strategies = strats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
+ *operators = ops = palloc_array(Oid, indnkeyatts);
+ *procs = funcs = palloc_array(Oid, indnkeyatts);
+ *strategies = strats = palloc_array(uint16, indnkeyatts);
/* Quick exit if we have the data cached already */
if (indexRelation->rd_exclstrats != NULL)
/* Save a copy of the results in the relcache entry. */
oldcxt = MemoryContextSwitchTo(indexRelation->rd_indexcxt);
- indexRelation->rd_exclops = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
- indexRelation->rd_exclprocs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
- indexRelation->rd_exclstrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
+ indexRelation->rd_exclops = palloc_array(Oid, indnkeyatts);
+ indexRelation->rd_exclprocs = palloc_array(Oid, indnkeyatts);
+ indexRelation->rd_exclstrats = palloc_array(uint16, indnkeyatts);
memcpy(indexRelation->rd_exclops, ops, sizeof(Oid) * indnkeyatts);
memcpy(indexRelation->rd_exclprocs, funcs, sizeof(Oid) * indnkeyatts);
memcpy(indexRelation->rd_exclstrats, strats, sizeof(uint16) * indnkeyatts);
/* Now save copy of the descriptor in the relcache entry. */
oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
- relation->rd_pubdesc = palloc(sizeof(PublicationDesc));
+ relation->rd_pubdesc = palloc_object(PublicationDesc);
memcpy(relation->rd_pubdesc, pubdesc, sizeof(PublicationDesc));
MemoryContextSwitchTo(oldcxt);
}
static bytea **
CopyIndexAttOptions(bytea **srcopts, int natts)
{
- bytea **opts = palloc(sizeof(*opts) * natts);
+ bytea **opts = palloc_array(bytea *, natts);
for (int i = 0; i < natts; i++)
{
return copy ? CopyIndexAttOptions(opts, natts) : opts;
/* Get and parse opclass options. */
- opts = palloc0(sizeof(*opts) * natts);
+ opts = palloc0_array(bytea *, natts);
for (i = 0; i < natts; i++)
{
/* mark not-null status */
if (has_not_null)
{
- TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
+ TupleConstr *constr = palloc0_object(TupleConstr);
constr->has_not_null = true;
rel->rd_att->constr = constr;
* through.
*/
maxitems = 64;
- items = (EnumItem *) palloc(sizeof(EnumItem) * maxitems);
+ items = palloc_array(EnumItem, maxitems);
numitems = 0;
/* Scan pg_enum for the members of the target enum type. */
Assert(CurrentMemoryContext != ErrorContext);
/* Copy the struct itself */
- newedata = (ErrorData *) palloc(sizeof(ErrorData));
+ newedata = palloc_object(ErrorData);
memcpy(newedata, edata, sizeof(ErrorData));
/*
&elems, NULL, &nelems);
if (nelems != numargs) /* should not happen */
elog(ERROR, "proargnames must have the same number of elements as the function has arguments");
- *p_argnames = (char **) palloc(sizeof(char *) * numargs);
+ *p_argnames = palloc_array(char *, numargs);
for (i = 0; i < numargs; i++)
(*p_argnames)[i] = TextDatumGetCString(elems[i]);
}
maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
- av = (char **) palloc(maxac * sizeof(char *));
+ av = palloc_array(char *, maxac);
ac = 0;
av[ac++] = "postgres";
*/
if (codepage != 0)
{
- utf16 = (WCHAR *) palloc(sizeof(WCHAR) * (len + 1));
+ utf16 = palloc_array(WCHAR, len + 1);
dstlen = MultiByteToWideChar(codepage, 0, str, len, utf16, len);
utf16[dstlen] = (WCHAR) 0;
}
else
utf8 = (char *) str;
- utf16 = (WCHAR *) palloc(sizeof(WCHAR) * (len + 1));
+ utf16 = palloc_array(WCHAR, len + 1);
dstlen = MultiByteToWideChar(CP_UTF8, 0, utf8, len, utf16, len);
utf16[dstlen] = (WCHAR) 0;
* them prior to caller processing the contents.
*/
size_filenames = 32;
- filenames = (char **) palloc(size_filenames * sizeof(char *));
+ filenames = palloc_array(char *, size_filenames);
*num_filenames = 0;
while ((de = ReadDir(d, directory)) != NULL)
{
ConfigVariable *item;
- item = palloc(sizeof *item);
+ item = palloc_object(ConfigVariable);
item->name = NULL;
item->value = NULL;
item->errmsg = pstrdup(errmsg);
else
{
/* ordinary variable, append to list */
- item = palloc(sizeof *item);
+ item = palloc_object(ConfigVariable);
item->name = opt_name;
item->value = opt_value;
item->errmsg = NULL;
int i;
*num_vars = hash_get_num_entries(guc_hashtab);
- result = palloc(sizeof(struct config_generic *) * *num_vars);
+ result = palloc_array(struct config_generic *, *num_vars);
/* Extract pointers from the hash table */
i = 0;
* While only a fraction of all the GUC variables are marked GUC_EXPLAIN,
* it doesn't seem worth dynamically resizing this array.
*/
- result = palloc(sizeof(struct config_generic *) * hash_get_num_entries(guc_hashtab));
+ result = palloc_array(struct config_generic *, hash_get_num_entries(guc_hashtab));
/* We need only consider GUCs with source not PGC_S_DEFAULT */
dlist_foreach(iter, &guc_nondef_list)
if (generation % 2 == 0)
continue;
- inj_point = (InjectionPointData *) palloc0(sizeof(InjectionPointData));
+ inj_point = palloc0_object(InjectionPointData);
inj_point->name = pstrdup(entry->name);
inj_point->library = pstrdup(entry->library);
inj_point->function = pstrdup(entry->function);
QueryEnvironment *
create_queryEnv(void)
{
- return (QueryEnvironment *) palloc0(sizeof(QueryEnvironment));
+ return palloc0_object(QueryEnvironment);
}
EphemeralNamedRelationMetadata
/* Initialize array at a reasonable size */
arraysize = 128;
- array = (tzEntry *) palloc(arraysize * sizeof(tzEntry));
+ array = palloc_array(tzEntry, arraysize);
/* Parse the file(s) */
n = ParseTzFile(filename, 0, &array, &arraysize, 0);
* area. Other backends will need to obtain their own dsa_area object by
* attaching.
*/
- area = palloc(sizeof(dsa_area));
+ area = palloc_object(dsa_area);
area->control = control;
area->resowner = CurrentResourceOwner;
memset(area->segment_maps, 0, sizeof(dsa_segment_map) * DSA_MAX_SEGMENTS);
(DSA_SEGMENT_HEADER_MAGIC ^ handle ^ 0));
/* Build the backend-local area object. */
- area = palloc(sizeof(dsa_area));
+ area = palloc_object(dsa_area);
area->control = control;
area->resowner = CurrentResourceOwner;
memset(&area->segment_maps[0], 0,
if (lt->prealloc == NULL)
{
lt->prealloc_size = TAPE_WRITE_PREALLOC_MIN;
- lt->prealloc = (int64 *) palloc(sizeof(int64) * lt->prealloc_size);
+ lt->prealloc = palloc_array(int64, lt->prealloc_size);
}
else if (lt->prealloc_size < TAPE_WRITE_PREALLOC_MAX)
{
/*
* Create top-level struct including per-tape LogicalTape structs.
*/
- lts = (LogicalTapeSet *) palloc(sizeof(LogicalTapeSet));
+ lts = palloc_object(LogicalTapeSet);
lts->nBlocksAllocated = 0L;
lts->nBlocksWritten = 0L;
lts->nHoleBl