您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ tuplestore_begin_heap函数代码示例

51自学网 2021-06-03 09:00:52
  C++
这篇教程C++ tuplestore_begin_heap函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中tuplestore_begin_heap函数的典型用法代码示例。如果您正苦于以下问题:C++ tuplestore_begin_heap函数的具体用法?C++ tuplestore_begin_heap怎么用?C++ tuplestore_begin_heap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了tuplestore_begin_heap函数的27个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: PortalCreateHoldStore

/* * PortalCreateHoldStore *		Create the tuplestore for a portal. */voidPortalCreateHoldStore(Portal portal){	MemoryContext oldcxt;	Assert(portal->holdContext == NULL);	Assert(portal->holdStore == NULL);	/*	 * Create the memory context that is used for storage of the tuple set.	 * Note this is NOT a child of the portal's heap memory.	 */	portal->holdContext =		AllocSetContextCreate(PortalMemory,							  "PortalHoldContext",							  ALLOCSET_DEFAULT_MINSIZE,							  ALLOCSET_DEFAULT_INITSIZE,							  ALLOCSET_DEFAULT_MAXSIZE);	/* Create the tuple store, selecting cross-transaction temp files. */	oldcxt = MemoryContextSwitchTo(portal->holdContext);	/* XXX: Should maintenance_work_mem be used for the portal size? */	portal->holdStore = tuplestore_begin_heap(true, true, work_mem);	MemoryContextSwitchTo(oldcxt);}
开发者ID:CraigBryan,项目名称:PostgresqlFun,代码行数:31,


示例2: deflist_to_tuplestore

/* * deflist_to_tuplestore - Helper function to convert DefElem list to * tuplestore usable in SRF. */static voiddeflist_to_tuplestore(ReturnSetInfo *rsinfo, List *options){	ListCell   *cell;	TupleDesc	tupdesc;	Tuplestorestate *tupstore;	Datum		values[2];	bool		nulls[2];	MemoryContext per_query_ctx;	MemoryContext oldcontext;	/* check to see if caller supports us returning a tuplestore */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (!(rsinfo->allowedModes & SFRM_Materialize) ||		rsinfo->expectedDesc == NULL)		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not allowed in this context")));	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	/*	 * Now prepare the result set.	 */	tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);	tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = tupstore;	rsinfo->setDesc = tupdesc;	foreach(cell, options)	{		DefElem    *def = lfirst(cell);		values[0] = CStringGetTextDatum(def->defname);		nulls[0] = false;		if (def->arg)		{			values[1] = CStringGetTextDatum(((Value *) (def->arg))->val.str);			nulls[1] = false;		}		else		{			values[1] = (Datum) 0;			nulls[1] = true;		}		tuplestore_putvalues(tupstore, tupdesc, values, nulls);	}
开发者ID:bwright,项目名称:postgres,代码行数:56,


示例3: worker_copy_shard_placement

/* * worker_copy_shard_placement implements a internal UDF to copy a table's data from * a healthy placement into a receiving table on an unhealthy placement. This * function returns a boolean reflecting success or failure. */Datumworker_copy_shard_placement(PG_FUNCTION_ARGS){    text *shardRelationNameText = PG_GETARG_TEXT_P(0);    text *nodeNameText = PG_GETARG_TEXT_P(1);    int32 nodePort = PG_GETARG_INT32(2);    char *shardRelationName = text_to_cstring(shardRelationNameText);    char *nodeName = text_to_cstring(nodeNameText);    bool fetchSuccessful = false;    Oid shardRelationId = ResolveRelationId(shardRelationNameText);    Relation shardTable = heap_open(shardRelationId, RowExclusiveLock);    TupleDesc tupleDescriptor = RelationGetDescr(shardTable);    Tuplestorestate *tupleStore = tuplestore_begin_heap(false, false, work_mem);    StringInfo selectAllQuery = NULL;    ShardPlacement *placement = NULL;    Task *task = NULL;    selectAllQuery = makeStringInfo();    appendStringInfo(selectAllQuery, SELECT_ALL_QUERY,                     quote_identifier(shardRelationName));    placement = (ShardPlacement *) palloc0(sizeof(ShardPlacement));    placement->nodeName = nodeName;    placement->nodePort = nodePort;    task = (Task *) palloc0(sizeof(Task));    task->queryString = selectAllQuery;    task->taskPlacementList = list_make1(placement);    fetchSuccessful = ExecuteTaskAndStoreResults(task, tupleDescriptor, tupleStore);    if (!fetchSuccessful)    {        ereport(ERROR, (errmsg("could not store shard rows from healthy placement"),                        errhint("Consult recent messages in the server logs for "                                "details.")));    }    CopyDataFromTupleStoreToRelation(tupleStore, shardTable);    tuplestore_end(tupleStore);    heap_close(shardTable, RowExclusiveLock);    PG_RETURN_VOID();}
开发者ID:chinnitv,项目名称:pg_shard,代码行数:52,


示例4: pgmpc_init_setof

/* * pgmpc_init_setof * Intilialize properly a function returning multiple tuples with a * tuplestore and a TupDesc. */static voidpgmpc_init_setof(FunctionCallInfo fcinfo,				 int argnum,				 Oid *argtypes,				 char **argnames,				 TupleDesc *tupdesc,				 Tuplestorestate **tupstore){	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	MemoryContext per_query_ctx;	MemoryContext oldcontext;	int i;	/* check to see if caller supports us returning a tuplestore */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (!(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not " /						"allowed in this context")));	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	/* Build tuple descriptor */	*tupdesc = CreateTemplateTupleDesc(argnum, false);	for (i = 0; i < argnum; i++)		TupleDescInitEntry(*tupdesc, (AttrNumber) i + 1, argnames[i],						   argtypes[i], -1, 0);	*tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = *tupstore;	rsinfo->setDesc = *tupdesc;	MemoryContextSwitchTo(oldcontext);}
开发者ID:harry-2016,项目名称:pg_plugins,代码行数:45,


示例5: json_populate_recordset

/* * SQL function json_populate_recordset * * set fields in a set of records from the argument json, * which must be an array of objects. * * similar to json_populate_record, but the tuple-building code * is pushed down into the semantic action handlers so it's done * per object in the array. */Datumjson_populate_recordset(PG_FUNCTION_ARGS){	Oid			argtype = get_fn_expr_argtype(fcinfo->flinfo, 0);	text	   *json = PG_GETARG_TEXT_P(1);	bool		use_json_as_text = PG_GETARG_BOOL(2);	ReturnSetInfo *rsi;	MemoryContext old_cxt;	Oid			tupType;	int32		tupTypmod;	HeapTupleHeader rec;	TupleDesc	tupdesc;	RecordIOData *my_extra;	int			ncolumns;	JsonLexContext *lex;	JsonSemAction sem;	PopulateRecordsetState state;	if (!type_is_rowtype(argtype))		ereport(ERROR,				(errcode(ERRCODE_DATATYPE_MISMATCH),				 errmsg("first argument must be a rowtype")));	rsi = (ReturnSetInfo *) fcinfo->resultinfo;	if (!rsi || !IsA(rsi, ReturnSetInfo) ||		(rsi->allowedModes & SFRM_Materialize) == 0 ||		rsi->expectedDesc == NULL)		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that "						"cannot accept a set")));	rsi->returnMode = SFRM_Materialize;	/*	 * get the tupdesc from the result set info - it must be a record type	 * because we already checked that arg1 is a record type.	 */	(void) get_call_result_type(fcinfo, NULL, &tupdesc);	state = palloc0(sizeof(populateRecordsetState));	sem = palloc0(sizeof(jsonSemAction));	/* make these in a sufficiently long-lived memory context */	old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);	state->ret_tdesc = CreateTupleDescCopy(tupdesc);	BlessTupleDesc(state->ret_tdesc);	state->tuple_store =		tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize,							  false, work_mem);	MemoryContextSwitchTo(old_cxt);	/* if the json is null send back an empty set */	if (PG_ARGISNULL(1))		PG_RETURN_NULL();	if (PG_ARGISNULL(0))		rec = NULL;	else		rec = PG_GETARG_HEAPTUPLEHEADER(0);	tupType = tupdesc->tdtypeid;	tupTypmod = tupdesc->tdtypmod;	ncolumns = tupdesc->natts;	lex = makeJsonLexContext(json, true);	/*	 * We arrange to look up the needed I/O info just once per series of	 * calls, assuming the record type doesn't change underneath us.	 */	my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;	if (my_extra == NULL ||		my_extra->ncolumns != ncolumns)	{		fcinfo->flinfo->fn_extra =			MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,							   sizeof(RecordIOData) - sizeof(ColumnIOData)							   + ncolumns * sizeof(ColumnIOData));		my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;		my_extra->record_type = InvalidOid;		my_extra->record_typmod = 0;	}	if (my_extra->record_type != tupType ||//.........这里部分代码省略.........
开发者ID:50wu,项目名称:gpdb,代码行数:101,


示例6: json_array_elements

/* * SQL function json_array_elements * * get the elements from a json array * * a lot of this processing is similar to the json_each* functions */Datumjson_array_elements(PG_FUNCTION_ARGS){	text	   *json = PG_GETARG_TEXT_P(0);	/* elements doesn't need any escaped strings, so use false here */	JsonLexContext *lex = makeJsonLexContext(json, false);	JsonSemAction sem;	ReturnSetInfo *rsi;	MemoryContext old_cxt;	TupleDesc	tupdesc;	ElementsState state;	state = palloc0(sizeof(elementsState));	sem = palloc0(sizeof(jsonSemAction));	rsi = (ReturnSetInfo *) fcinfo->resultinfo;	if (!rsi || !IsA(rsi, ReturnSetInfo) ||		(rsi->allowedModes & SFRM_Materialize) == 0 ||		rsi->expectedDesc == NULL)		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that "						"cannot accept a set")));	rsi->returnMode = SFRM_Materialize;	/* it's a simple type, so don't use get_call_result_type() */	tupdesc = rsi->expectedDesc;	/* make these in a sufficiently long-lived memory context */	old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);	state->ret_tdesc = CreateTupleDescCopy(tupdesc);	BlessTupleDesc(state->ret_tdesc);	state->tuple_store =		tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize,							  false, work_mem);	MemoryContextSwitchTo(old_cxt);	sem->semstate = (void *) state;	sem->object_start = elements_object_start;	sem->scalar = elements_scalar;	sem->array_element_start = elements_array_element_start;	sem->array_element_end = elements_array_element_end;	state->lex = lex;	state->tmp_cxt = AllocSetContextCreate(CurrentMemoryContext,										 "json_array_elements temporary cxt",										   ALLOCSET_DEFAULT_MINSIZE,										   ALLOCSET_DEFAULT_INITSIZE,										   ALLOCSET_DEFAULT_MAXSIZE);	pg_parse_json(lex, sem);	rsi->setResult = state->tuple_store;	rsi->setDesc = state->ret_tdesc;	PG_RETURN_NULL();}
开发者ID:50wu,项目名称:gpdb,代码行数:70,


示例7: pgsynck

Datumpgsynck(PG_FUNCTION_ARGS){/*	List			   *raw_parsetree_list = NULL; */	char			   *query_string = NULL;	char			   *oneq = NULL;	char			   *q;	ErrorData		   *edata = NULL;	MemoryContext		oldcontext = CurrentMemoryContext;	MemoryContext		per_query_ctx;	ReturnSetInfo	   *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	TupleDesc			tupdesc;	Tuplestorestate	   *tupstore;	/* check to see if caller supports us returning a tuplestore */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (!(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not " /						"allowed in this context")));	/* Build a tuple descriptor for our result type */	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)		elog(ERROR, "return type must be a row type");	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = tupstore;	rsinfo->setDesc = tupdesc;	MemoryContextSwitchTo(oldcontext);	q = query_string = text_to_cstring(PG_GETARG_TEXT_PP(0));	oneq = get_one_query(&q);	while (oneq != NULL)	{		int			j = 0;		Datum		values[PGSYNCK_COLS];		bool		nulls[PGSYNCK_COLS];		memset(values, 0, sizeof(values));		memset(nulls, 0, sizeof(nulls));		/* sql */		values[j++] = CStringGetTextDatum(oneq);		PG_TRY();		{			raw_parser(oneq);			/* cursorpos */			values[j++] = Int32GetDatum(0);			/* sqlerrcode */			values[j++] = Int32GetDatum(0);			/* message - primary error message */			values[j++] = CStringGetTextDatum("");			/* hint - hint message */			values[j++] = CStringGetTextDatum("");			tuplestore_putvalues(tupstore, tupdesc, values, nulls);		}		PG_CATCH();		{			/* Save error info */			MemoryContextSwitchTo(oldcontext);			edata = CopyErrorData();			FlushErrorState();			/* cursorpos - cursor index into query string */			values[j++] = Int32GetDatum(edata->cursorpos);			/* sqlerrcode - encoded ERRSTATE */			values[j++] = Int32GetDatum(edata->sqlerrcode);			/* message - primary error message */			values[j++] = CStringGetTextDatum(edata->message ? edata->message:"");			/* hint - hint message */			values[j++] = CStringGetTextDatum(edata->hint ? edata->hint:"");			tuplestore_putvalues(tupstore, tupdesc, values, nulls);			FreeErrorData(edata);		}		PG_END_TRY();		oneq = get_one_query(&q);	}	/* clean up and return the tuplestore *///.........这里部分代码省略.........
开发者ID:jconway,项目名称:pgsynck,代码行数:101,


示例8: pg_logical_slot_get_changes_guts

//.........这里部分代码省略.........				 errmsg("array must be one-dimensional")));	}	else if (array_contains_nulls(arr))	{		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("array must not contain nulls")));	}	else if (ndim == 1)	{		int			nelems;		Datum	   *datum_opts;		int			i;		Assert(ARR_ELEMTYPE(arr) == TEXTOID);		deconstruct_array(arr, TEXTOID, -1, false, 'i',						  &datum_opts, NULL, &nelems);		if (nelems % 2 != 0)			ereport(ERROR,					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),					 errmsg("array must have even number of elements")));		for (i = 0; i < nelems; i += 2)		{			char	   *name = TextDatumGetCString(datum_opts[i]);			char	   *opt = TextDatumGetCString(datum_opts[i + 1]);			options = lappend(options, makeDefElem(name, (Node *) makeString(opt)));		}	}	p->tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = p->tupstore;	rsinfo->setDesc = p->tupdesc;	/* compute the current end-of-wal */	if (!RecoveryInProgress())		end_of_wal = GetFlushRecPtr();	else		end_of_wal = GetXLogReplayRecPtr(NULL);	CheckLogicalDecodingRequirements();	ReplicationSlotAcquire(NameStr(*name));	PG_TRY();	{		ctx = CreateDecodingContext(InvalidXLogRecPtr,									options,									logical_read_local_xlog_page,									LogicalOutputPrepareWrite,									LogicalOutputWrite);		MemoryContextSwitchTo(oldcontext);		/*		 * Check whether the output pluggin writes textual output if that's		 * what we need.		 */		if (!binary &&			ctx->options.output_type != OUTPUT_PLUGIN_TEXTUAL_OUTPUT)			ereport(ERROR,					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),					 errmsg("output plugin cannot produce binary output")));
开发者ID:dimitri,项目名称:postgres,代码行数:67,


示例9: plperl_return_next

/* * Note: plperl_return_next is called both in Postgres and Perl contexts. * We report any errors in Postgres fashion (via ereport).	If called in * Perl context, it is SPI.xs's responsibility to catch the error and * convert to a Perl error.  We assume (perhaps without adequate justification) * that we need not abort the current transaction if the Perl code traps the * error. */voidplperl_return_next(SV *sv){	plperl_proc_desc *prodesc = plperl_current_prodesc;	FunctionCallInfo fcinfo = plperl_current_caller_info;	ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;	MemoryContext cxt;	HeapTuple	tuple;	TupleDesc	tupdesc;	if (!sv)		return;	if (!prodesc->fn_retisset)		ereport(ERROR,				(errcode(ERRCODE_SYNTAX_ERROR),				 errmsg("cannot use return_next in a non-SETOF function")));	if (prodesc->fn_retistuple &&		!(SvOK(sv) && SvTYPE(sv) == SVt_RV && SvTYPE(SvRV(sv)) == SVt_PVHV))		ereport(ERROR,				(errcode(ERRCODE_DATATYPE_MISMATCH),				 errmsg("setof-composite-returning Perl function "						"must call return_next with reference to hash")));	cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);	if (!plperl_current_tuple_store)		plperl_current_tuple_store =			tuplestore_begin_heap(true, false, work_mem);	if (prodesc->fn_retistuple)	{		TypeFuncClass rettype;		AttInMetadata *attinmeta;		rettype = get_call_result_type(fcinfo, NULL, &tupdesc);		tupdesc = CreateTupleDescCopy(tupdesc);		attinmeta = TupleDescGetAttInMetadata(tupdesc);		tuple = plperl_build_tuple_result((HV *) SvRV(sv), attinmeta);	}	else	{		Datum		ret;		bool		isNull;		tupdesc = CreateTupleDescCopy(rsi->expectedDesc);		if (SvOK(sv) && SvTYPE(sv) != SVt_NULL)		{			char	   *val = SvPV(sv, PL_na);			ret = FunctionCall3(&prodesc->result_in_func,								PointerGetDatum(val),								ObjectIdGetDatum(prodesc->result_typioparam),								Int32GetDatum(-1));			isNull = false;		}		else		{			ret = (Datum) 0;			isNull = true;		}		tuple = heap_form_tuple(tupdesc, &ret, &isNull);	}	if (!plperl_current_tuple_desc)		plperl_current_tuple_desc = tupdesc;	tuplestore_puttuple(plperl_current_tuple_store, tuple);	heap_freetuple(tuple);	MemoryContextSwitchTo(cxt);}
开发者ID:shubham2094,项目名称:postgresql_8.1,代码行数:82,


示例10: pg_stat_statements

/* * Retrieve statement statistics. */Datumpg_stat_statements(PG_FUNCTION_ARGS){	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	TupleDesc	tupdesc;	Tuplestorestate *tupstore;	MemoryContext per_query_ctx;	MemoryContext oldcontext;	Oid			userid = GetUserId();	bool		is_superuser = superuser();	HASH_SEQ_STATUS hash_seq;	pgssEntry  *entry;	if (!pgss || !pgss_hash)		ereport(ERROR,				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),				 errmsg("pg_stat_statements must be loaded via shared_preload_libraries")));	/* check to see if caller supports us returning a tuplestore */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (!(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not " /						"allowed in this context")));	/* Build a tuple descriptor for our result type */	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)		elog(ERROR, "return type must be a row type");	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = tupstore;	rsinfo->setDesc = tupdesc;	MemoryContextSwitchTo(oldcontext);	LWLockAcquire(pgss->lock, LW_SHARED);	hash_seq_init(&hash_seq, pgss_hash);	while ((entry = hash_seq_search(&hash_seq)) != NULL)	{		Datum		values[PG_STAT_STATEMENTS_COLS];		bool		nulls[PG_STAT_STATEMENTS_COLS];		int			i = 0;		Counters	tmp;		memset(values, 0, sizeof(values));		memset(nulls, 0, sizeof(nulls));		values[i++] = ObjectIdGetDatum(entry->key.userid);		values[i++] = ObjectIdGetDatum(entry->key.dbid);		if (is_superuser || entry->key.userid == userid)		{			char	   *qstr;			qstr = (char *)				pg_do_encoding_conversion((unsigned char *) entry->query,										  entry->key.query_len,										  entry->key.encoding,										  GetDatabaseEncoding());			values[i++] = CStringGetTextDatum(qstr);			if (qstr != entry->query)				pfree(qstr);		}		else			values[i++] = CStringGetTextDatum("<insufficient privilege>");		/* copy counters to a local variable to keep locking time short */		{			volatile pgssEntry *e = (volatile pgssEntry *) entry;			SpinLockAcquire(&e->mutex);			tmp = e->counters;			SpinLockRelease(&e->mutex);		}		values[i++] = Int64GetDatumFast(tmp.calls);		values[i++] = Float8GetDatumFast(tmp.total_time);		values[i++] = Int64GetDatumFast(tmp.rows);		values[i++] = Int64GetDatumFast(tmp.shared_blks_hit);		values[i++] = Int64GetDatumFast(tmp.shared_blks_read);		values[i++] = Int64GetDatumFast(tmp.shared_blks_written);		values[i++] = Int64GetDatumFast(tmp.local_blks_hit);		values[i++] = Int64GetDatumFast(tmp.local_blks_read);		values[i++] = Int64GetDatumFast(tmp.local_blks_written);		values[i++] = Int64GetDatumFast(tmp.temp_blks_read);		values[i++] = Int64GetDatumFast(tmp.temp_blks_written);		Assert(i == PG_STAT_STATEMENTS_COLS);//.........这里部分代码省略.........
开发者ID:HBPSP8Repo,项目名称:NoDB,代码行数:101,


示例11: ExecInitCteScan

/* ---------------------------------------------------------------- *		ExecInitCteScan * ---------------------------------------------------------------- */CteScanState *ExecInitCteScan(CteScan *node, EState *estate, int eflags){	CteScanState *scanstate;	ParamExecData *prmdata;	/* check for unsupported flags */	Assert(!(eflags & EXEC_FLAG_MARK));	/*	 * For the moment we have to force the tuplestore to allow REWIND, because	 * we might be asked to rescan the CTE even though upper levels didn't	 * tell us to be prepared to do it efficiently.  Annoying, since this	 * prevents truncation of the tuplestore.  XXX FIXME	 *	 * Note: if we are in an EPQ recheck plan tree, it's likely that no access	 * to the tuplestore is needed at all, making this even more annoying.	 * It's not worth improving that as long as all the read pointers would	 * have REWIND anyway, but if we ever improve this logic then that aspect	 * should be considered too.	 */	eflags |= EXEC_FLAG_REWIND;	/*	 * CteScan should not have any children.	 */	Assert(outerPlan(node) == NULL);	Assert(innerPlan(node) == NULL);	/*	 * create new CteScanState for node	 */	scanstate = makeNode(CteScanState);	scanstate->ss.ps.plan = (Plan *) node;	scanstate->ss.ps.state = estate;	scanstate->eflags = eflags;	scanstate->cte_table = NULL;	scanstate->eof_cte = false;	/*	 * Find the already-initialized plan for the CTE query.	 */	scanstate->cteplanstate = (PlanState *) list_nth(estate->es_subplanstates,													 node->ctePlanId - 1);	/*	 * The Param slot associated with the CTE query is used to hold a pointer	 * to the CteState of the first CteScan node that initializes for this	 * CTE.  This node will be the one that holds the shared state for all the	 * CTEs, particularly the shared tuplestore.	 */	prmdata = &(estate->es_param_exec_vals[node->cteParam]);	Assert(prmdata->execPlan == NULL);	Assert(!prmdata->isnull);	scanstate->leader = (CteScanState *) DatumGetPointer(prmdata->value);	if (scanstate->leader == NULL)	{		/* I am the leader */		prmdata->value = PointerGetDatum(scanstate);		scanstate->leader = scanstate;		scanstate->cte_table = tuplestore_begin_heap(true, false, work_mem);		tuplestore_set_eflags(scanstate->cte_table, scanstate->eflags);		scanstate->readptr = 0;	}	else	{		/* Not the leader */		Assert(IsA(scanstate->leader, CteScanState));		/* Create my own read pointer, and ensure it is at start */		scanstate->readptr =			tuplestore_alloc_read_pointer(scanstate->leader->cte_table,										  scanstate->eflags);		tuplestore_select_read_pointer(scanstate->leader->cte_table,									   scanstate->readptr);		tuplestore_rescan(scanstate->leader->cte_table);	}	/*	 * Miscellaneous initialization	 *	 * create expression context for node	 */	ExecAssignExprContext(estate, &scanstate->ss.ps);	/*	 * initialize child expressions	 */	scanstate->ss.ps.targetlist = (List *)		ExecInitExpr((Expr *) node->scan.plan.targetlist,					 (PlanState *) scanstate);	scanstate->ss.ps.qual = (List *)		ExecInitExpr((Expr *) node->scan.plan.qual,					 (PlanState *) scanstate);	/*	 * tuple table initialization//.........这里部分代码省略.........
开发者ID:adam8157,项目名称:gpdb,代码行数:101,


示例12: ExecMakeTableFunctionResult

//.........这里部分代码省略.........		{			pgstat_init_function_usage(&fcinfo, &fcusage);			fcinfo.isnull = false;			rsinfo.isDone = ExprSingleResult;			result = FunctionCallInvoke(&fcinfo);			pgstat_end_function_usage(&fcusage,									  rsinfo.isDone != ExprMultipleResult);		}		else		{			result =				ExecEvalExpr(setexpr->elidedFuncState, econtext, &fcinfo.isnull);			rsinfo.isDone = ExprSingleResult;		}		/* Which protocol does function want to use? */		if (rsinfo.returnMode == SFRM_ValuePerCall)		{			/*			 * Check for end of result set.			 */			if (rsinfo.isDone == ExprEndResult)				break;			/*			 * If first time through, build tuplestore for result.  For a			 * scalar function result type, also make a suitable tupdesc.			 */			if (first_time)			{				oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);				tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);				rsinfo.setResult = tupstore;				if (!returnsTuple)				{					tupdesc = CreateTemplateTupleDesc(1, false);					TupleDescInitEntry(tupdesc,									   (AttrNumber) 1,									   "column",									   funcrettype,									   -1,									   0);					rsinfo.setDesc = tupdesc;				}				MemoryContextSwitchTo(oldcontext);			}			/*			 * Store current resultset item.			 */			if (returnsTuple)			{				if (!fcinfo.isnull)				{					HeapTupleHeader td = DatumGetHeapTupleHeader(result);					if (tupdesc == NULL)					{						/*						 * This is the first non-NULL result from the						 * function.  Use the type info embedded in the						 * rowtype Datum to look up the needed tupdesc.  Make						 * a copy for the query.						 */
开发者ID:Brar,项目名称:postgres,代码行数:67,


示例13: pg_get_replication_slots

/* * pg_get_replication_slots - SQL SRF showing active replication slots. */Datumpg_get_replication_slots(PG_FUNCTION_ARGS){#define PG_GET_REPLICATION_SLOTS_COLS 10	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	TupleDesc	tupdesc;	Tuplestorestate *tupstore;	MemoryContext per_query_ctx;	MemoryContext oldcontext;	int			slotno;	/* check to see if caller supports us returning a tuplestore */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (!(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not " /						"allowed in this context")));	/* Build a tuple descriptor for our result type */	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)		elog(ERROR, "return type must be a row type");	/*	 * We don't require any special permission to see this function's data	 * because nothing should be sensitive. The most critical being the slot	 * name, which shouldn't contain anything particularly sensitive.	 */	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = tupstore;	rsinfo->setDesc = tupdesc;	MemoryContextSwitchTo(oldcontext);	for (slotno = 0; slotno < max_replication_slots; slotno++)	{		ReplicationSlot *slot = &ReplicationSlotCtl->replication_slots[slotno];		Datum		values[PG_GET_REPLICATION_SLOTS_COLS];		bool		nulls[PG_GET_REPLICATION_SLOTS_COLS];		TransactionId xmin;		TransactionId catalog_xmin;		XLogRecPtr	restart_lsn;		XLogRecPtr	confirmed_flush_lsn;		pid_t		active_pid;		Oid			database;		NameData	slot_name;		NameData	plugin;		int			i;		SpinLockAcquire(&slot->mutex);		if (!slot->in_use)		{			SpinLockRelease(&slot->mutex);			continue;		}		else		{			xmin = slot->data.xmin;			catalog_xmin = slot->data.catalog_xmin;			database = slot->data.database;			restart_lsn = slot->data.restart_lsn;			confirmed_flush_lsn = slot->data.confirmed_flush;			namecpy(&slot_name, &slot->data.name);			namecpy(&plugin, &slot->data.plugin);			active_pid = slot->active_pid;		}		SpinLockRelease(&slot->mutex);		memset(nulls, 0, sizeof(nulls));		i = 0;		values[i++] = NameGetDatum(&slot_name);		if (database == InvalidOid)			nulls[i++] = true;		else			values[i++] = NameGetDatum(&plugin);		if (database == InvalidOid)			values[i++] = CStringGetTextDatum("physical");		else			values[i++] = CStringGetTextDatum("logical");		if (database == InvalidOid)			nulls[i++] = true;		else			values[i++] = database;//.........这里部分代码省略.........
开发者ID:eydunn,项目名称:postgres,代码行数:101,


示例14: pg_logical_slot_get_changes_guts

//.........这里部分代码省略.........				 errmsg("array must be one-dimensional")));	}	else if (array_contains_nulls(arr))	{		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("array must not contain nulls")));	}	else if (ndim == 1)	{		int			nelems;		Datum	   *datum_opts;		int			i;		Assert(ARR_ELEMTYPE(arr) == TEXTOID);		deconstruct_array(arr, TEXTOID, -1, false, 'i',						  &datum_opts, NULL, &nelems);		if (nelems % 2 != 0)			ereport(ERROR,					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),					 errmsg("array must have even number of elements")));		for (i = 0; i < nelems; i += 2)		{			char	   *name = TextDatumGetCString(datum_opts[i]);			char	   *opt = TextDatumGetCString(datum_opts[i + 1]);			options = lappend(options, makeDefElem(name, (Node *) makeString(opt), -1));		}	}	p->tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = p->tupstore;	rsinfo->setDesc = p->tupdesc;	/*	 * Compute the current end-of-wal and maintain ThisTimeLineID.	 * RecoveryInProgress() will update ThisTimeLineID on promotion.	 */	if (!RecoveryInProgress())		end_of_wal = GetFlushRecPtr();	else		end_of_wal = GetXLogReplayRecPtr(&ThisTimeLineID);	ReplicationSlotAcquire(NameStr(*name), true);	PG_TRY();	{		/* restart at slot's confirmed_flush */		ctx = CreateDecodingContext(InvalidXLogRecPtr,									options,									false,									logical_read_local_xlog_page,									LogicalOutputPrepareWrite,									LogicalOutputWrite, NULL);		MemoryContextSwitchTo(oldcontext);		/*		 * Check whether the output plugin writes textual output if that's		 * what we need.		 */		if (!binary &&
开发者ID:RingsC,项目名称:postgres,代码行数:67,


示例15: ExecRecursiveUnion

/* ---------------------------------------------------------------- *		ExecRecursiveUnion(node) * *		Scans the recursive query sequentially and returns the next *		qualifying tuple. * * 1. evaluate non recursive term and assign the result to RT * * 2. execute recursive terms * * 2.1 WT := RT * 2.2 while WT is not empty repeat 2.3 to 2.6. if WT is empty returns RT * 2.3 replace the name of recursive term with WT * 2.4 evaluate the recursive term and store into WT * 2.5 append WT to RT * 2.6 go back to 2.2 * ---------------------------------------------------------------- */TupleTableSlot *ExecRecursiveUnion(RecursiveUnionState *node){	PlanState  *outerPlan = outerPlanState(node);	PlanState  *innerPlan = innerPlanState(node);	RecursiveUnion *plan = (RecursiveUnion *) node->ps.plan;	TupleTableSlot *slot;	RUHashEntry entry;	bool		isnew;	/* 1. Evaluate non-recursive term */	if (!node->recursing)	{		for (;;)		{			slot = ExecProcNode(outerPlan);			if (TupIsNull(slot))				break;			if (plan->numCols > 0)			{				/* Find or build hashtable entry for this tuple's group */				entry = (RUHashEntry)					LookupTupleHashEntry(node->hashtable, slot, &isnew);				/* Must reset temp context after each hashtable lookup */				MemoryContextReset(node->tempContext);				/* Ignore tuple if already seen */				if (!isnew)					continue;			}			/* Each non-duplicate tuple goes to the working table ... */			tuplestore_puttupleslot(node->working_table, slot);			/* ... and to the caller */			return slot;		}		node->recursing = true;	}	/* 2. Execute recursive term */	for (;;)	{		slot = ExecProcNode(innerPlan);		if (TupIsNull(slot))		{			/* Done if there's nothing in the intermediate table */			if (node->intermediate_empty)				break;			/* done with old working table ... */			tuplestore_end(node->working_table);			/* intermediate table becomes working table */			node->working_table = node->intermediate_table;			/* create new empty intermediate table */			node->intermediate_table = tuplestore_begin_heap(false, false,															 work_mem);			node->intermediate_empty = true;			/* reset the recursive term */			innerPlan->chgParam = bms_add_member(innerPlan->chgParam,												 plan->wtParam);			/* and continue fetching from recursive term */			continue;		}		if (plan->numCols > 0)		{			/* Find or build hashtable entry for this tuple's group */			entry = (RUHashEntry)				LookupTupleHashEntry(node->hashtable, slot, &isnew);			/* Must reset temp context after each hashtable lookup */			MemoryContextReset(node->tempContext);			/* Ignore tuple if already seen */			if (!isnew)				continue;		}		/* Else, tuple is good; stash it in intermediate table ... */		node->intermediate_empty = false;		tuplestore_puttupleslot(node->intermediate_table, slot);		/* ... and return it *///.........这里部分代码省略.........
开发者ID:LittleForker,项目名称:postgres,代码行数:101,


示例16: ExecInitRecursiveUnion

/* ---------------------------------------------------------------- *		ExecInitRecursiveUnionScan * ---------------------------------------------------------------- */RecursiveUnionState *ExecInitRecursiveUnion(RecursiveUnion *node, EState *estate, int eflags){	RecursiveUnionState *rustate;	ParamExecData *prmdata;	/* check for unsupported flags */	Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));	/*	 * create state structure	 */	rustate = makeNode(RecursiveUnionState);	rustate->ps.plan = (Plan *) node;	rustate->ps.state = estate;	rustate->eqfunctions = NULL;	rustate->hashfunctions = NULL;	rustate->hashtable = NULL;	rustate->tempContext = NULL;	rustate->tableContext = NULL;	/* initialize processing state */	rustate->recursing = false;	rustate->intermediate_empty = true;	rustate->working_table = tuplestore_begin_heap(false, false, work_mem);	rustate->intermediate_table = tuplestore_begin_heap(false, false, work_mem);	/*	 * If hashing, we need a per-tuple memory context for comparisons, and a	 * longer-lived context to store the hash table.  The table can't just be	 * kept in the per-query context because we want to be able to throw it	 * away when rescanning.	 */	if (node->numCols > 0)	{		rustate->tempContext =			AllocSetContextCreate(CurrentMemoryContext,								  "RecursiveUnion",								  ALLOCSET_DEFAULT_MINSIZE,								  ALLOCSET_DEFAULT_INITSIZE,								  ALLOCSET_DEFAULT_MAXSIZE);		rustate->tableContext =			AllocSetContextCreate(CurrentMemoryContext,								  "RecursiveUnion hash table",								  ALLOCSET_DEFAULT_MINSIZE,								  ALLOCSET_DEFAULT_INITSIZE,								  ALLOCSET_DEFAULT_MAXSIZE);	}	/*	 * Make the state structure available to descendant WorkTableScan nodes	 * via the Param slot reserved for it.	 */	prmdata = &(estate->es_param_exec_vals[node->wtParam]);	Assert(prmdata->execPlan == NULL);	prmdata->value = PointerGetDatum(rustate);	prmdata->isnull = false;	/*	 * Miscellaneous initialization	 *	 * RecursiveUnion plans don't have expression contexts because they never	 * call ExecQual or ExecProject.	 */	Assert(node->plan.qual == NIL);	/*	 * RecursiveUnion nodes still have Result slots, which hold pointers to	 * tuples, so we have to initialize them.	 */	ExecInitResultTupleSlot(estate, &rustate->ps);	/*	 * Initialize result tuple type and projection info.  (Note: we have to	 * set up the result type before initializing child nodes, because	 * nodeWorktablescan.c expects it to be valid.)	 */	ExecAssignResultTypeFromTL(&rustate->ps);	rustate->ps.ps_ProjInfo = NULL;	/*	 * initialize child nodes	 */	outerPlanState(rustate) = ExecInitNode(outerPlan(node), estate, eflags);	innerPlanState(rustate) = ExecInitNode(innerPlan(node), estate, eflags);	/*	 * If hashing, precompute fmgr lookup data for inner loop, and create the	 * hash table.	 */	if (node->numCols > 0)	{		execTuplesHashPrepare(node->numCols,							  node->dupOperators,							  &rustate->eqfunctions,//.........这里部分代码省略.........
开发者ID:LittleForker,项目名称:postgres,代码行数:101,


示例17: each_worker

static inline Datumeach_worker(PG_FUNCTION_ARGS, bool as_text){	text	   *json = PG_GETARG_TEXT_P(0);	JsonLexContext *lex = makeJsonLexContext(json, true);	JsonSemAction sem;	ReturnSetInfo *rsi;	MemoryContext old_cxt;	TupleDesc	tupdesc;	EachState	state;	state = palloc0(sizeof(eachState));	sem = palloc0(sizeof(jsonSemAction));	rsi = (ReturnSetInfo *) fcinfo->resultinfo;	if (!rsi || !IsA(rsi, ReturnSetInfo) ||		(rsi->allowedModes & SFRM_Materialize) == 0 ||		rsi->expectedDesc == NULL)		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that "						"cannot accept a set")));	rsi->returnMode = SFRM_Materialize;	(void) get_call_result_type(fcinfo, NULL, &tupdesc);	/* make these in a sufficiently long-lived memory context */	old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);	state->ret_tdesc = CreateTupleDescCopy(tupdesc);	BlessTupleDesc(state->ret_tdesc);	state->tuple_store =		tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize,							  false, work_mem);	MemoryContextSwitchTo(old_cxt);	sem->semstate = (void *) state;	sem->array_start = each_array_start;	sem->scalar = each_scalar;	sem->object_field_start = each_object_field_start;	sem->object_field_end = each_object_field_end;	state->normalize_results = as_text;	state->next_scalar = false;	state->lex = lex;	state->tmp_cxt = AllocSetContextCreate(CurrentMemoryContext,										   "json_each temporary cxt",										   ALLOCSET_DEFAULT_MINSIZE,										   ALLOCSET_DEFAULT_INITSIZE,										   ALLOCSET_DEFAULT_MAXSIZE);	pg_parse_json(lex, sem);	rsi->setResult = state->tuple_store;	rsi->setDesc = state->ret_tdesc;	PG_RETURN_NULL();}
开发者ID:50wu,项目名称:gpdb,代码行数:63,


示例18: pg_stop_backup_v2

/* * pg_stop_backup_v2: finish taking exclusive or nonexclusive on-line backup. * * Works the same as pg_stop_backup, except for non-exclusive backups it returns * the backup label and tablespace map files as text fields in as part of the * resultset. * * Permission checking for this function is managed through the normal * GRANT system. */Datumpg_stop_backup_v2(PG_FUNCTION_ARGS){	ReturnSetInfo  *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	TupleDesc		tupdesc;	Tuplestorestate *tupstore;	MemoryContext	per_query_ctx;	MemoryContext	oldcontext;	Datum			values[3];	bool			nulls[3];	bool			exclusive = PG_GETARG_BOOL(0);	XLogRecPtr		stoppoint;	/* check to see if caller supports us returning a tuplestore */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (!(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not " /						"allowed in this context")));	/* Build a tuple descriptor for our result type */	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)		elog(ERROR, "return type must be a row type");	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = tupstore;	rsinfo->setDesc = tupdesc;	MemoryContextSwitchTo(oldcontext);	MemSet(values, 0, sizeof(values));	MemSet(nulls, 0, sizeof(nulls));	if (exclusive)	{		if (nonexclusive_backup_running)			ereport(ERROR,					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),					 errmsg("non-exclusive backup in progress"),					 errhint("did you mean to use pg_stop_backup('f')?")));		/*		 * Stop the exclusive backup, and since we're in an exclusive backup		 * return NULL for both backup_label and tablespace_map.		 */		stoppoint = do_pg_stop_backup(NULL, true, NULL);		exclusive_backup_running = false;		nulls[1] = true;		nulls[2] = true;	}	else	{		if (!nonexclusive_backup_running)			ereport(ERROR,					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),					 errmsg("non-exclusive backup is not in progress"),					 errhint("did you mean to use pg_stop_backup('t')?")));		/*		 * Stop the non-exclusive backup. Return a copy of the backup		 * label and tablespace map so they can be written to disk by		 * the caller.		 */		stoppoint = do_pg_stop_backup(label_file->data, true, NULL);		nonexclusive_backup_running = false;		cancel_before_shmem_exit(nonexclusive_base_backup_cleanup, (Datum) 0);		values[1] = CStringGetTextDatum(label_file->data);		values[2] = CStringGetTextDatum(tblspc_map_file->data);		/* Free structures allocated in TopMemoryContext */		pfree(label_file->data);		pfree(label_file);		label_file = NULL;		pfree(tblspc_map_file->data);		pfree(tblspc_map_file);		tblspc_map_file = NULL;	}	/* Stoppoint is included on both exclusive and nonexclusive backups *///.........这里部分代码省略.........
开发者ID:Gordiychuk,项目名称:postgres,代码行数:101,


示例19: pg_stat_get_activity

/* * Returns activity of PG backends. */Datumpg_stat_get_activity(PG_FUNCTION_ARGS){#define PG_STAT_GET_ACTIVITY_COLS	22	int					num_backends = pgstat_fetch_stat_numbackends();	int					curr_backend;	int					pid = PG_ARGISNULL(0) ? -1 : PG_GETARG_INT32(0);	ReturnSetInfo	   *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	TupleDesc			tupdesc;	Tuplestorestate	   *tupstore;	MemoryContext		per_query_ctx;	MemoryContext		oldcontext;	/* check to see if caller supports us returning a tuplestore */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (!(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not " /						"allowed in this context")));	/* Build a tuple descriptor for our result type */	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)		elog(ERROR, "return type must be a row type");	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = tupstore;	rsinfo->setDesc = tupdesc;	MemoryContextSwitchTo(oldcontext);	/* 1-based index */	for (curr_backend = 1; curr_backend <= num_backends; curr_backend++)	{		/* for each row */		Datum		values[PG_STAT_GET_ACTIVITY_COLS];		bool		nulls[PG_STAT_GET_ACTIVITY_COLS];		LocalPgBackendStatus *local_beentry;		PgBackendStatus *beentry;		MemSet(values, 0, sizeof(values));		MemSet(nulls, 0, sizeof(nulls));		if (pid != -1)		{			/* Skip any which are not the one we're looking for. */			PgBackendStatus *be = pgstat_fetch_stat_beentry(curr_backend);			if (!be || be->st_procpid != pid)				continue;		}		/* Get the next one in the list */		local_beentry = pgstat_fetch_stat_local_beentry(curr_backend);		if (!local_beentry)			continue;		beentry = &local_beentry->backendStatus;		if (!beentry)		{			int			i;			for (i = 0; i < sizeof(nulls) / sizeof(nulls[0]); i++)				nulls[i] = true;			nulls[5] = false;			values[5] = CStringGetTextDatum("<backend information not available>");			tuplestore_putvalues(tupstore, tupdesc, values, nulls);			continue;		}		/* Values available to all callers */		values[0] = ObjectIdGetDatum(beentry->st_databaseid);		values[1] = Int32GetDatum(beentry->st_procpid);		values[2] = ObjectIdGetDatum(beentry->st_userid);		if (beentry->st_appname)			values[3] = CStringGetTextDatum(beentry->st_appname);		else			nulls[3] = true;		if (TransactionIdIsValid(local_beentry->backend_xid))			values[14] = TransactionIdGetDatum(local_beentry->backend_xid);		else			nulls[14] = true;		if (TransactionIdIsValid(local_beentry->backend_xmin))			values[15] = TransactionIdGetDatum(local_beentry->backend_xmin);		else//.........这里部分代码省略.........
开发者ID:EccentricLoggers,项目名称:peloton,代码行数:101,


示例20: pg_stat_get_wal_senders

/* * Returns activity of walsenders, including pids and xlog locations sent to * standby servers. */Datumpg_stat_get_wal_senders(PG_FUNCTION_ARGS){#define PG_STAT_GET_WAL_SENDERS_COLS	8	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	TupleDesc	tupdesc;	Tuplestorestate *tupstore;	MemoryContext per_query_ctx;	MemoryContext oldcontext;	int		   *sync_priority;	int			priority = 0;	int			sync_standby = -1;	int			i;	/* check to see if caller supports us returning a tuplestore */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (!(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not " /						"allowed in this context")));	/* Build a tuple descriptor for our result type */	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)		elog(ERROR, "return type must be a row type");	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = tupstore;	rsinfo->setDesc = tupdesc;	MemoryContextSwitchTo(oldcontext);	/*	 * Get the priorities of sync standbys all in one go, to minimise lock	 * acquisitions and to allow us to evaluate who is the current sync	 * standby. This code must match the code in SyncRepReleaseWaiters().	 */	sync_priority = palloc(sizeof(int) * max_wal_senders);	LWLockAcquire(SyncRepLock, LW_SHARED);	for (i = 0; i < max_wal_senders; i++)	{		/* use volatile pointer to prevent code rearrangement */		volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];		if (walsnd->pid != 0)		{			sync_priority[i] = walsnd->sync_standby_priority;			if (walsnd->state == WALSNDSTATE_STREAMING &&				walsnd->sync_standby_priority > 0 &&				(priority == 0 ||				 priority > walsnd->sync_standby_priority))			{				priority = walsnd->sync_standby_priority;				sync_standby = i;			}		}	}	LWLockRelease(SyncRepLock);	for (i = 0; i < max_wal_senders; i++)	{		/* use volatile pointer to prevent code rearrangement */		volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];		char		location[MAXFNAMELEN];		XLogRecPtr	sentPtr;		XLogRecPtr	write;		XLogRecPtr	flush;		XLogRecPtr	apply;		WalSndState state;		Datum		values[PG_STAT_GET_WAL_SENDERS_COLS];		bool		nulls[PG_STAT_GET_WAL_SENDERS_COLS];		if (walsnd->pid == 0)			continue;		SpinLockAcquire(&walsnd->mutex);		sentPtr = walsnd->sentPtr;		state = walsnd->state;		write = walsnd->write;		flush = walsnd->flush;		apply = walsnd->apply;		SpinLockRelease(&walsnd->mutex);		memset(nulls, 0, sizeof(nulls));		values[0] = Int32GetDatum(walsnd->pid);		if (!superuser())		{//.........这里部分代码省略.........
开发者ID:ibejoeb,项目名称:postgres,代码行数:101,


示例21: xpath_table

Datumxpath_table(PG_FUNCTION_ARGS){	/* Function parameters */	char	   *pkeyfield = text_to_cstring(PG_GETARG_TEXT_PP(0));	char	   *xmlfield = text_to_cstring(PG_GETARG_TEXT_PP(1));	char	   *relname = text_to_cstring(PG_GETARG_TEXT_PP(2));	char	   *xpathset = text_to_cstring(PG_GETARG_TEXT_PP(3));	char	   *condition = text_to_cstring(PG_GETARG_TEXT_PP(4));	/* SPI (input tuple) support */	SPITupleTable *tuptable;	HeapTuple	spi_tuple;	TupleDesc	spi_tupdesc;	/* Output tuple (tuplestore) support */	Tuplestorestate *tupstore = NULL;	TupleDesc	ret_tupdesc;	HeapTuple	ret_tuple;	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	AttInMetadata *attinmeta;	MemoryContext per_query_ctx;	MemoryContext oldcontext;	char	  **values;	xmlChar   **xpaths;	char	   *pos;	const char *pathsep = "|";	int			numpaths;	int			ret;	int			proc;	int			i;	int			j;	int			rownr;			/* For issuing multiple rows from one original								 * document */	bool		had_values;		/* To determine end of nodeset results */	StringInfoData query_buf;	PgXmlErrorContext *xmlerrcxt;	volatile xmlDocPtr doctree = NULL;	/* We only have a valid tuple description in table function mode */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (rsinfo->expectedDesc == NULL)		ereport(ERROR,				(errcode(ERRCODE_SYNTAX_ERROR),				 errmsg("xpath_table must be called as a table function")));	/*	 * We want to materialise because it means that we don't have to carry	 * libxml2 parser state between invocations of this function	 */	if (!(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_SYNTAX_ERROR),			   errmsg("xpath_table requires Materialize mode, but it is not "					  "allowed in this context")));	/*	 * The tuplestore must exist in a higher context than this function call	 * (per_query_ctx is used)	 */	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	/*	 * Create the tuplestore - work_mem is the max in-memory size before a	 * file is created on disk to hold it.	 */	tupstore =		tuplestore_begin_heap(rsinfo->allowedModes & SFRM_Materialize_Random,							  false, work_mem);	MemoryContextSwitchTo(oldcontext);	/* get the requested return tuple description */	ret_tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);	/* must have at least one output column (for the pkey) */	if (ret_tupdesc->natts < 1)		ereport(ERROR,				(errcode(ERRCODE_SYNTAX_ERROR),				 errmsg("xpath_table must have at least one output column")));	/*	 * At the moment we assume that the returned attributes make sense for the	 * XPath specififed (i.e. we trust the caller). It's not fatal if they get	 * it wrong - the input function for the column type will raise an error	 * if the path result can't be converted into the correct binary	 * representation.	 */	attinmeta = TupleDescGetAttInMetadata(ret_tupdesc);	/* Set return mode and allocate value space. */	rsinfo->returnMode = SFRM_Materialize;//.........这里部分代码省略.........
开发者ID:42penguins,项目名称:postgres,代码行数:101,


示例22: ExecMaterial

/* ---------------------------------------------------------------- *		ExecMaterial * *		As long as we are at the end of the data collected in the tuplestore, *		we collect one new row from the subplan on each call, and stash it *		aside in the tuplestore before returning it.  The tuplestore is *		only read if we are asked to scan backwards, rescan, or mark/restore. * * ---------------------------------------------------------------- */TupleTableSlot *				/* result tuple from subplan */ExecMaterial(MaterialState *node){	EState	   *estate;	ScanDirection dir;	bool		forward;	Tuplestorestate *tuplestorestate;	HeapTuple	heapTuple = NULL;	bool		should_free = false;	bool		eof_tuplestore;	TupleTableSlot *slot;	/*	 * get state info from node	 */	estate = node->ss.ps.state;	dir = estate->es_direction;	forward = ScanDirectionIsForward(dir);	tuplestorestate = (Tuplestorestate *) node->tuplestorestate;	/*	 * If first time through, and we need a tuplestore, initialize it.	 */	if (tuplestorestate == NULL && node->randomAccess)	{		tuplestorestate = tuplestore_begin_heap(true, false, work_mem);		node->tuplestorestate = (void *) tuplestorestate;	}	/*	 * If we are not at the end of the tuplestore, or are going backwards, try	 * to fetch a tuple from tuplestore.	 */	eof_tuplestore = (tuplestorestate == NULL) ||		tuplestore_ateof(tuplestorestate);	if (!forward && eof_tuplestore)	{		if (!node->eof_underlying)		{			/*			 * When reversing direction at tuplestore EOF, the first			 * getheaptuple call will fetch the last-added tuple; but we want			 * to return the one before that, if possible. So do an extra			 * fetch.			 */			heapTuple = tuplestore_getheaptuple(tuplestorestate,												forward,												&should_free);			if (heapTuple == NULL)				return NULL;	/* the tuplestore must be empty */			if (should_free)				heap_freetuple(heapTuple);		}		eof_tuplestore = false;	}	if (!eof_tuplestore)	{		heapTuple = tuplestore_getheaptuple(tuplestorestate,											forward,											&should_free);		if (heapTuple == NULL && forward)			eof_tuplestore = true;	}	/*	 * If necessary, try to fetch another row from the subplan.	 *	 * Note: the eof_underlying state variable exists to short-circuit further	 * subplan calls.  It's not optional, unfortunately, because some plan	 * node types are not robust about being called again when they've already	 * returned NULL.	 */	if (eof_tuplestore && !node->eof_underlying)	{		PlanState  *outerNode;		TupleTableSlot *outerslot;		/*		 * We can only get here with forward==true, so no need to worry about		 * which direction the subplan will go.		 */		outerNode = outerPlanState(node);		outerslot = ExecProcNode(outerNode);		if (TupIsNull(outerslot))		{			node->eof_underlying = true;			return NULL;//.........这里部分代码省略.........
开发者ID:jaiminpan,项目名称:bizgres,代码行数:101,


示例23: ExecMaterial

/* ---------------------------------------------------------------- *		ExecMaterial * *		As long as we are at the end of the data collected in the tuplestore, *		we collect one new row from the subplan on each call, and stash it *		aside in the tuplestore before returning it.  The tuplestore is *		only read if we are asked to scan backwards, rescan, or mark/restore. * * ---------------------------------------------------------------- */TupleTableSlot *				/* result tuple from subplan */ExecMaterial(MaterialState *node){	EState	   *estate;	ScanDirection dir;	bool		forward;	Tuplestorestate *tuplestorestate;	bool		eof_tuplestore;	TupleTableSlot *slot;	/*	 * get state info from node	 */	estate = node->ss.ps.state;	dir = estate->es_direction;	forward = ScanDirectionIsForward(dir);	tuplestorestate = node->tuplestorestate;	/*	 * If first time through, and we need a tuplestore, initialize it.	 */	if (tuplestorestate == NULL && node->eflags != 0)	{		tuplestorestate = tuplestore_begin_heap(true, false, work_mem);		tuplestore_set_eflags(tuplestorestate, node->eflags);		if (node->eflags & EXEC_FLAG_MARK)		{			/*			 * Allocate a second read pointer to serve as the mark. We know it			 * must have index 1, so needn't store that.			 */			int ptrno	PG_USED_FOR_ASSERTS_ONLY;			ptrno = tuplestore_alloc_read_pointer(tuplestorestate,												  node->eflags);			Assert(ptrno == 1);		}		node->tuplestorestate = tuplestorestate;	}	/*	 * If we are not at the end of the tuplestore, or are going backwards, try	 * to fetch a tuple from tuplestore.	 */	eof_tuplestore = (tuplestorestate == NULL) ||		tuplestore_ateof(tuplestorestate);	if (!forward && eof_tuplestore)	{		if (!node->eof_underlying)		{			/*			 * When reversing direction at tuplestore EOF, the first			 * gettupleslot call will fetch the last-added tuple; but we want			 * to return the one before that, if possible. So do an extra			 * fetch.			 */			if (!tuplestore_advance(tuplestorestate, forward))				return NULL;	/* the tuplestore must be empty */		}		eof_tuplestore = false;	}	/*	 * If we can fetch another tuple from the tuplestore, return it.	 */	slot = node->ss.ps.ps_ResultTupleSlot;	if (!eof_tuplestore)	{		if (tuplestore_gettupleslot(tuplestorestate, forward, false, slot))			return slot;		if (forward)			eof_tuplestore = true;	}	/*	 * If necessary, try to fetch another row from the subplan.	 *	 * Note: the eof_underlying state variable exists to short-circuit further	 * subplan calls.  It's not optional, unfortunately, because some plan	 * node types are not robust about being called again when they've already	 * returned NULL.	 */	if (eof_tuplestore && !node->eof_underlying)	{		PlanState  *outerNode;		TupleTableSlot *outerslot;		/*		 * We can only get here with forward==true, so no need to worry about//.........这里部分代码省略.........
开发者ID:PJMODOS,项目名称:postgres,代码行数:101,


示例24: get_all_active_transactions

/* * get_all_active_transactions returns all the avaliable information about all * the active backends. */Datumget_all_active_transactions(PG_FUNCTION_ARGS){	ReturnSetInfo *returnSetInfo = (ReturnSetInfo *) fcinfo->resultinfo;	TupleDesc tupleDescriptor = NULL;	Tuplestorestate *tupleStore = NULL;	MemoryContext perQueryContext = NULL;	MemoryContext oldContext = NULL;	int backendIndex = 0;	Datum values[5];	bool isNulls[5];	CheckCitusVersion(ERROR);	/* check to see if caller supports us returning a tuplestore */	if (returnSetInfo == NULL || !IsA(returnSetInfo, ReturnSetInfo))	{		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context " /						"that cannot accept a set")));	}	if (!(returnSetInfo->allowedModes & SFRM_Materialize))	{		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not " /						"allowed in this context")));	}	/* build a tuple descriptor for our result type */	if (get_call_result_type(fcinfo, NULL, &tupleDescriptor) != TYPEFUNC_COMPOSITE)	{		elog(ERROR, "return type must be a row type");	}	perQueryContext = returnSetInfo->econtext->ecxt_per_query_memory;	oldContext = MemoryContextSwitchTo(perQueryContext);	tupleStore = tuplestore_begin_heap(true, false, work_mem);	returnSetInfo->returnMode = SFRM_Materialize;	returnSetInfo->setResult = tupleStore;	returnSetInfo->setDesc = tupleDescriptor;	MemoryContextSwitchTo(oldContext);	/*	 * We don't want to initialize memory while spinlock is held so we	 * prefer to do it here. This initialization is done only for the first	 * row.	 */	memset(values, 0, sizeof(values));	memset(isNulls, false, sizeof(isNulls));	/* we're reading all distributed transactions, prevent new backends */	LockBackendSharedMemory(LW_SHARED);	for (backendIndex = 0; backendIndex < MaxBackends; ++backendIndex)	{		BackendData *currentBackend =			&backendManagementShmemData->backends[backendIndex];		SpinLockAcquire(&currentBackend->mutex);		/* we're only interested in active backends */		if (currentBackend->transactionId.transactionNumber == 0)		{			SpinLockRelease(&currentBackend->mutex);			continue;		}		values[0] = ObjectIdGetDatum(currentBackend->databaseId);		values[1] = Int32GetDatum(ProcGlobal->allProcs[backendIndex].pid);		values[2] = Int32GetDatum(currentBackend->transactionId.initiatorNodeIdentifier);		values[3] = UInt64GetDatum(currentBackend->transactionId.transactionNumber);		values[4] = TimestampTzGetDatum(currentBackend->transactionId.timestamp);		SpinLockRelease(&currentBackend->mutex);		tuplestore_putvalues(tupleStore, tupleDescriptor, values, isNulls);		/*		 * We don't want to initialize memory while spinlock is held so we		 * prefer to do it here. This initialization is done for the rows		 * starting from the second one.		 */		memset(values, 0, sizeof(values));		memset(isNulls, false, sizeof(isNulls));	}	UnlockBackendSharedMemory();//.........这里部分代码省略.........
开发者ID:dreamsxin,项目名称:citus,代码行数:101,


示例25: pg_config

Datumpg_config(PG_FUNCTION_ARGS){	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	Tuplestorestate *tupstore;	HeapTuple	tuple;	TupleDesc	tupdesc;	AttInMetadata *attinmeta;	MemoryContext per_query_ctx;	MemoryContext oldcontext;	ConfigData *configdata;	size_t		configdata_len;	char	   *values[2];	int			i = 0;	/* check to see if caller supports us returning a tuplestore */	if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_SYNTAX_ERROR),				 errmsg("materialize mode required, but it is not "						"allowed in this context")));	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	/* get the requested return tuple description */	tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);	/*	 * Check to make sure we have a reasonable tuple descriptor	 */	if (tupdesc->natts != 2 ||		tupdesc->attrs[0]->atttypid != TEXTOID ||		tupdesc->attrs[1]->atttypid != TEXTOID)		ereport(ERROR,				(errcode(ERRCODE_SYNTAX_ERROR),				 errmsg("query-specified return tuple and "						"function return type are not compatible")));	/* OK to use it */	attinmeta = TupleDescGetAttInMetadata(tupdesc);	/* let the caller know we're sending back a tuplestore */	rsinfo->returnMode = SFRM_Materialize;	/* initialize our tuplestore */	tupstore = tuplestore_begin_heap(true, false, work_mem);	configdata = get_configdata(my_exec_path, &configdata_len);	for (i = 0; i < configdata_len; i++)	{		values[0] = configdata[i].name;		values[1] = configdata[i].setting;		tuple = BuildTupleFromCStrings(attinmeta, values);		tuplestore_puttuple(tupstore, tuple);	}	/*	 * no longer need the tuple descriptor reference created by	 * TupleDescGetAttInMetadata()	 */	ReleaseTupleDesc(tupdesc);	tuplestore_donestoring(tupstore);	rsinfo->setResult = tupstore;	/*	 * SFRM_Materialize mode expects us to return a NULL Datum. The actual	 * tuples are in our tuplestore and passed back through rsinfo->setResult.	 * rsinfo->setDesc is set to the tuple description that we actually used	 * to build our tuples with, so the caller can verify we did what it was	 * expecting.	 */	rsinfo->setDesc = tupdesc;	MemoryContextSwitchTo(oldcontext);	return (Datum) 0;}
开发者ID:0x0FFF,项目名称:postgres,代码行数:79,


示例26: brin_page_items

/* * Extract all item values from a BRIN index page * * Usage: SELECT * FROM brin_page_items(get_raw_page('idx', 1), 'idx'::regclass); */Datumbrin_page_items(PG_FUNCTION_ARGS){    bytea	   *raw_page = PG_GETARG_BYTEA_P(0);    Oid			indexRelid = PG_GETARG_OID(1);    ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;    TupleDesc	tupdesc;    MemoryContext oldcontext;    Tuplestorestate *tupstore;    Relation	indexRel;    brin_column_state **columns;    BrinDesc   *bdesc;    BrinMemTuple *dtup;    Page		page;    OffsetNumber offset;    AttrNumber	attno;    bool		unusedItem;    if (!superuser())        ereport(ERROR,                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),                 (errmsg("must be superuser to use raw page functions"))));    /* check to see if caller supports us returning a tuplestore */    if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))        ereport(ERROR,                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),                 errmsg("set-valued function called in context that cannot accept a set")));    if (!(rsinfo->allowedModes & SFRM_Materialize) ||            rsinfo->expectedDesc == NULL)        ereport(ERROR,                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),                 errmsg("materialize mode required, but it is not allowed in this context")));    /* Build a tuple descriptor for our result type */    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)        elog(ERROR, "return type must be a row type");    /* Build tuplestore to hold the result rows */    oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);    tupstore = tuplestore_begin_heap(true, false, work_mem);    rsinfo->returnMode = SFRM_Materialize;    rsinfo->setResult = tupstore;    rsinfo->setDesc = tupdesc;    MemoryContextSwitchTo(oldcontext);    indexRel = index_open(indexRelid, AccessShareLock);    bdesc = brin_build_desc(indexRel);    /* minimally verify the page we got */    page = verify_brin_page(raw_page, BRIN_PAGETYPE_REGULAR, "regular");    /*     * Initialize output functions for all indexed datatypes; simplifies     * calling them later.     */    columns = palloc(sizeof(brin_column_state *) * RelationGetDescr(indexRel)->natts);    for (attno = 1; attno <= bdesc->bd_tupdesc->natts; attno++)    {        Oid			output;        bool		isVarlena;        BrinOpcInfo *opcinfo;        int			i;        brin_column_state *column;        opcinfo = bdesc->bd_info[attno - 1];        column = palloc(offsetof(brin_column_state, outputFn) +                        sizeof(FmgrInfo) * opcinfo->oi_nstored);        column->nstored = opcinfo->oi_nstored;        for (i = 0; i < opcinfo->oi_nstored; i++)        {            getTypeOutputInfo(opcinfo->oi_typcache[i]->type_id, &output, &isVarlena);            fmgr_info(output, &column->outputFn[i]);        }        columns[attno - 1] = column;    }    offset = FirstOffsetNumber;    unusedItem = false;    dtup = NULL;    for (;;)    {        Datum		values[7];        bool		nulls[7];        /*         * This loop is called once for every attribute of every tuple in the         * page.  At the start of a tuple, we get a NULL dtup; that's our         * signal for obtaining and decoding the next one.  If that's not the         * case, we output the next attribute.         *///.........这里部分代码省略.........
开发者ID:linwanggm,项目名称:postgres,代码行数:101,


示例27: pg_stat_get_progress_info

/* * Returns command progress information for the named command. */Datumpg_stat_get_progress_info(PG_FUNCTION_ARGS){#define PG_STAT_GET_PROGRESS_COLS	PGSTAT_NUM_PROGRESS_PARAM + 3	int			num_backends = pgstat_fetch_stat_numbackends();	int			curr_backend;	char	   *cmd = text_to_cstring(PG_GETARG_TEXT_PP(0));	ProgressCommandType	cmdtype;	TupleDesc	tupdesc;	Tuplestorestate *tupstore;	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;	MemoryContext per_query_ctx;	MemoryContext oldcontext;	/* check to see if caller supports us returning a tuplestore */	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("set-valued function called in context that cannot accept a set")));	if (!(rsinfo->allowedModes & SFRM_Materialize))		ereport(ERROR,				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),				 errmsg("materialize mode required, but it is not " /						"allowed in this context")));	/* Build a tuple descriptor for our result type */	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)		elog(ERROR, "return type must be a row type");	/* Translate command name into command type code. */	if (pg_strcasecmp(cmd, "VACUUM") == 0)		cmdtype = PROGRESS_COMMAND_VACUUM;	else		ereport(ERROR,				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),				 errmsg("invalid command name: /"%s/"", cmd)));	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;	oldcontext = MemoryContextSwitchTo(per_query_ctx);	tupstore = tuplestore_begin_heap(true, false, work_mem);	rsinfo->returnMode = SFRM_Materialize;	rsinfo->setResult = tupstore;	rsinfo->setDesc = tupdesc;	MemoryContextSwitchTo(oldcontext);	/* 1-based index */	for (curr_backend = 1; curr_backend <= num_backends; curr_backend++)	{		LocalPgBackendStatus   *local_beentry;		PgBackendStatus		   *beentry;		Datum		values[PG_STAT_GET_PROGRESS_COLS];		bool		nulls[PG_STAT_GET_PROGRESS_COLS];		int			i;		MemSet(values, 0, sizeof(values));		MemSet(nulls, 0, sizeof(nulls));		local_beentry = pgstat_fetch_stat_local_beentry(curr_backend);		if (!local_beentry)			continue;		beentry = &local_beentry->backendStatus;		/*		 * Report values for only those backends which are running the given		 * command.		 */		if (!beentry || beentry->st_progress_command != cmdtype)			continue;		/* Value available to all callers */		values[0] = Int32GetDatum(beentry->st_procpid);		values[1] = ObjectIdGetDatum(beentry->st_databaseid);		/* show rest of the values including relid only to role members */		if (has_privs_of_role(GetUserId(), beentry->st_userid))		{			values[2] = ObjectIdGetDatum(beentry->st_progress_command_target);			for(i = 0; i < PGSTAT_NUM_PROGRESS_PARAM; i++)				values[i+3] = UInt32GetDatum(beentry->st_progress_param[i]);		}		else		{			nulls[2] = true;			for (i = 0; i < PGSTAT_NUM_PROGRESS_PARAM; i++)				nulls[i+3] = true;		}		tuplestore_putvalues(tupstore, tupdesc, values, nulls);	}	/* clean up and return the tuplestore */	tuplestore_donestoring(tupstore);	return (Datum) 0;//.........这里部分代码省略.........
开发者ID:BenjaminYu,项目名称:postgres,代码行数:101,



注:本文中的tuplestore_begin_heap函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ turnRight函数代码示例
C++ tuple函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。