示例#1
0
bool type_is_domain(char *type_name, Oid *base_type) {
    bool       rc;
    StringInfo query;

    SPI_connect();
    query = makeStringInfo();
    appendStringInfo(query, "SELECT typtype = 'd', typbasetype FROM pg_type WHERE typname = %s", TextDatumGetCString(DirectFunctionCall1(quote_literal, CStringGetTextDatum(type_name))));

    if (SPI_execute(query->data, true, 1) != SPI_OK_SELECT)
        elog(ERROR, "Problem determing if %s is a domain with query: %s", type_name, query->data);

    if (SPI_processed == 0) {
        rc = false;
    } else {
        bool  isnull;
        Datum d;

        d  = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
        rc = isnull || DatumGetBool(d);

        d = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull);
        *base_type = isnull ? InvalidOid : DatumGetObjectId(d);
    }

    SPI_finish();

    return rc;
}
示例#2
0
/*
 * load queue info from pgq.queue table.
 */
static void load_queue_info(Datum queue_name, struct QueueState *state)
{
	Datum values[1];
	int res;
	TupleDesc   desc;
	HeapTuple   row;
	bool isnull;

	values[0] = queue_name;
	res = SPI_execute_plan(queue_plan, values, NULL, false, 0);
	if (res != SPI_OK_SELECT)
		elog(ERROR, "Queue fetch failed");
	if (SPI_processed == 0)
		elog(ERROR, "No such queue");

	row = SPI_tuptable->vals[0];
	desc = SPI_tuptable->tupdesc;
	state->queue_id = DatumGetInt32(SPI_getbinval(row, desc, COL_QUEUE_ID, &isnull));
	if (isnull)
		elog(ERROR, "queue id NULL");
	state->cur_table = DatumGetInt32(SPI_getbinval(row, desc, COL_TBLNO, &isnull));
	if (isnull)
		elog(ERROR, "table nr NULL");
	state->table_prefix = SPI_getvalue(row, desc, COL_PREFIX);
	if (state->table_prefix == NULL)
		elog(ERROR, "table prefix NULL");
	state->next_event_id = SPI_getbinval(row, desc, COL_EVENT_ID, &isnull);
	if (isnull)
		elog(ERROR, "Seq name NULL");
}
示例#3
0
int64_t
pgr_SPI_getBigInt(HeapTuple *tuple, TupleDesc *tupdesc, Column_info_t info) {
    Datum binval;
    bool isnull;
    int64_t value = 0;
    binval = SPI_getbinval(*tuple, *tupdesc, info.colNumber, &isnull);
    if (isnull)
        elog(ERROR, "Unexpected Null value in column %s", info.name);
    switch (info.type) {
        case INT2OID:
            value = (int64_t) DatumGetInt16(binval);
            break;
        case INT4OID:
            value = (int64_t) DatumGetInt32(binval);
            break;
        case INT8OID:
            value = DatumGetInt64(binval);
            break;
        default:
            elog(ERROR,
                    "Unexpected Column type of %s. Expected ANY-INTEGER",
                    info.name);
    }
    PGR_DBG("Variable: %s Value: %lld", info.name, value);
    return value;
}
示例#4
0
double
pgr_SPI_getFloat8(HeapTuple *tuple, TupleDesc *tupdesc, Column_info_t info) {
    Datum binval;
    bool isnull;
    double value = 0.0;
    binval = SPI_getbinval(*tuple, *tupdesc, info.colNumber, &isnull);
    if (isnull)
        elog(ERROR, "Unexpected Null value in column %s", info.name);

    switch (info.type) {
        case INT2OID:
            value = (double) DatumGetInt16(binval);
            break;
        case INT4OID:
            value = (double) DatumGetInt32(binval);
            break;
        case INT8OID:
            value = (double) DatumGetInt64(binval);
            break;
        case FLOAT4OID:
            value = (double) DatumGetFloat4(binval);
            break;
        case FLOAT8OID:
            value = DatumGetFloat8(binval);
            break;
        default:
            elog(ERROR,
                    "Unexpected Column type of %s. Expected ANY-NUMERICAL",
                    info.name);
    }
    PGR_DBG("Variable: %s Value: %lf", info.name, value);
    return value;
}
示例#5
0
int2vector *
getPrimaryKey(Oid tblOid)
{
	char	   *queryBase;
	char	   *query;
	bool		isNull;
	int2vector *resultKey;
	int2vector *tpResultKey;
	HeapTuple	resTuple;
	Datum		resDatum;
	int			ret;

	queryBase = "SELECT indkey FROM pg_index WHERE indisprimary='t' AND indrelid=";
	query = SPI_palloc(strlen(queryBase) + MAX_OID_LEN + 1);
	sprintf(query, "%s%d", queryBase, tblOid);
	ret = SPI_exec(query, 1);
	SPI_pfree(query);
	if (ret != SPI_OK_SELECT || SPI_processed != 1)
		return NULL;

	resTuple = SPI_tuptable->vals[0];
	resDatum = SPI_getbinval(resTuple, SPI_tuptable->tupdesc, 1, &isNull);

	tpResultKey = (int2vector *) DatumGetPointer(resDatum);
	resultKey = SPI_palloc(VARSIZE(tpResultKey));
	memcpy(resultKey, tpResultKey, VARSIZE(tpResultKey));

	return resultKey;
}
示例#6
0
static Oid
getoid(HeapTuple tuple, TupleDesc desc, int column)
{
    bool	isnull;
    Datum	datum = SPI_getbinval(tuple, desc, column, &isnull);
    return isnull ? InvalidOid : DatumGetObjectId(datum);
}
示例#7
0
static int16
getint16(HeapTuple tuple, TupleDesc desc, int column)
{
    bool	isnull;
    Datum	datum = SPI_getbinval(tuple, desc, column, &isnull);
    return isnull ? 0 : DatumGetInt16(datum);
}
示例#8
0
long long * all_referenced_files(int * countOut)
{
	char query[128];
	snprintf(query, 128, "SELECT file_id FROM "WDB_SCHEMA".file_blob");
	SPI_connect();
	int result = SPI_execute(query, true, 0);
	if ( SPI_OK_SELECT != result )
		ereport(ERROR, (errcode( ERRCODE_RAISE_EXCEPTION ),	errmsg("Error when reading from file_blob")));

	* countOut = SPI_processed;

	long long * ret = (long long *) SPI_palloc(sizeof(long long) * (* countOut));

	int i;
	for ( i = 0; i < * countOut; ++ i )
	{
		bool isNull; // unused
		Datum d = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, & isNull);
		ret[i] = DatumGetInt64(d);
	}

	SPI_finish();

	return ret;
}
示例#9
0
static void getExtensionLoadPath()
{
	MemoryContext curr;
	Datum dtm;
	bool isnull;

	/*
	 * Check whether sqlj.loadpath exists before querying it. I would more
	 * happily just PG_CATCH() the error and compare to ERRCODE_UNDEFINED_TABLE
	 * but what's required to make that work right is "not terribly well
	 * documented, but the exception-block handling in plpgsql provides a
	 * working model" and that code is a lot more fiddly than you would guess.
	 */
	if ( InvalidOid == get_relname_relid("loadpath",
		GetSysCacheOid1(NAMESPACENAME, CStringGetDatum("sqlj"))) )
		return;

	SPI_connect();
	curr = CurrentMemoryContext;
	if ( SPI_OK_SELECT == SPI_execute(
		"SELECT path, exnihilo FROM sqlj.loadpath", true, 1)
		&& 1 == SPI_processed )
	{
		MemoryContextSwitchTo(TopMemoryContext);
		pljavaLoadPath = (char const *)SPI_getvalue(
			SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
		MemoryContextSwitchTo(curr);
		dtm = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2,
			&isnull);
		if ( isnull )
			elog(ERROR, "defect in CREATE EXTENSION script");
		extensionExNihilo = DatumGetBool(dtm);
	}
	SPI_finish();
}
示例#10
0
void
init_dict(Oid id, DictInfo * dict)
{
	Oid			arg[1];
	bool		isnull;
	Datum		pars[1];
	int			stat;
	void	   *plan;
	char		buf[1024];
	char	   *nsp = get_namespace(TSNSP_FunctionOid);

	arg[0] = OIDOID;
	pars[0] = ObjectIdGetDatum(id);

	memset(dict, 0, sizeof(DictInfo));
	SPI_connect();
	sprintf(buf, "select dict_init, dict_initoption, dict_lexize from %s.pg_ts_dict where oid = $1", nsp);
	pfree(nsp);
	plan = SPI_prepare(buf, 1, arg);
	if (!plan)
		ts_error(ERROR, "SPI_prepare() failed");

	stat = SPI_execp(plan, pars, " ", 1);
	if (stat < 0)
		ts_error(ERROR, "SPI_execp return %d", stat);
	if (SPI_processed > 0)
	{
		Datum		opt;
		Oid			oid = InvalidOid;

		oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
		if (!(isnull || oid == InvalidOid))
		{
			opt = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull);
			dict->dictionary = (void *) DatumGetPointer(OidFunctionCall1(oid, opt));
		}
		oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull));
		if (isnull || oid == InvalidOid)
			ts_error(ERROR, "Null dict_lexize for dictonary %d", id);
		fmgr_info_cxt(oid, &(dict->lexize_info), TopMemoryContext);
		dict->dict_id = id;
	}
	else
		ts_error(ERROR, "No dictionary with id %d", id);
	SPI_freeplan(plan);
	SPI_finish();
}
示例#11
0
void
init_prs(Oid id, WParserInfo * prs)
{
	Oid			arg[1];
	bool		isnull;
	Datum		pars[1];
	int			stat;
	void	   *plan;
	char		buf[1024],
			   *nsp;

	arg[0] = OIDOID;
	pars[0] = ObjectIdGetDatum(id);

	memset(prs, 0, sizeof(WParserInfo));
	SPI_connect();
	nsp = get_namespace(TSNSP_FunctionOid);
	sprintf(buf, "select prs_start, prs_nexttoken, prs_end, prs_lextype, prs_headline from %s.pg_ts_parser where oid = $1", nsp);
	pfree(nsp);
	plan = SPI_prepare(buf, 1, arg);
	if (!plan)
		ts_error(ERROR, "SPI_prepare() failed");

	stat = SPI_execp(plan, pars, " ", 1);
	if (stat < 0)
		ts_error(ERROR, "SPI_execp return %d", stat);
	if (SPI_processed > 0)
	{
		Oid			oid = InvalidOid;

		oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
		fmgr_info_cxt(oid, &(prs->start_info), TopMemoryContext);
		oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull));
		fmgr_info_cxt(oid, &(prs->getlexeme_info), TopMemoryContext);
		oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull));
		fmgr_info_cxt(oid, &(prs->end_info), TopMemoryContext);
		prs->lextype = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 4, &isnull));
		oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 5, &isnull));
		fmgr_info_cxt(oid, &(prs->headline_info), TopMemoryContext);
		prs->prs_id = id;
	}
	else
		ts_error(ERROR, "No parser with id %d", id);
	SPI_freeplan(plan);
	SPI_finish();
}
示例#12
0
static void
fetch_vertex(HeapTuple *tuple, TupleDesc *tupdesc,
             vertex_columns_t *vertex_columns, vertex_t *target_vertex)
{
    Datum binval;
    bool isnull;

    binval = SPI_getbinval(*tuple, *tupdesc, vertex_columns->x, &isnull);
    if (isnull)
        elog(ERROR, "x contains a null value");
    target_vertex->x = DatumGetFloat8(binval);

    binval = SPI_getbinval(*tuple, *tupdesc, vertex_columns->y, &isnull);
    if (isnull)
        elog(ERROR, "y contains a null value");
    target_vertex->y = DatumGetFloat8(binval);
}
示例#13
0
/*
 * Initialize workspace for a worker process: create the schema if it doesn't
 * already exist.
 */
static void
initialize_worker_spi(worktable *table)
{
	int			ret;
	int			ntup;
	bool		isnull;
	StringInfoData buf;

	SetCurrentStatementStartTimestamp();
	StartTransactionCommand();
	SPI_connect();
	PushActiveSnapshot(GetTransactionSnapshot());
	pgstat_report_activity(STATE_RUNNING, "initializing spi_worker schema");

	/* XXX could we use CREATE SCHEMA IF NOT EXISTS? */
	initStringInfo(&buf);
	appendStringInfo(&buf, "select count(*) from pg_namespace where nspname = '%s'",
					 table->schema);

	ret = SPI_execute(buf.data, true, 0);
	if (ret != SPI_OK_SELECT)
		elog(FATAL, "SPI_execute failed: error code %d", ret);

	if (SPI_processed != 1)
		elog(FATAL, "not a singleton result");

	ntup = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0],
									   SPI_tuptable->tupdesc,
									   1, &isnull));
	if (isnull)
		elog(FATAL, "null result");

	if (ntup == 0)
	{
		resetStringInfo(&buf);
		appendStringInfo(&buf,
						 "CREATE SCHEMA \"%s\" "
						 "CREATE TABLE \"%s\" ("
			   "		type text CHECK (type IN ('total', 'delta')), "
						 "		value	integer)"
				  "CREATE UNIQUE INDEX \"%s_unique_total\" ON \"%s\" (type) "
						 "WHERE type = 'total'",
					   table->schema, table->name, table->name, table->name);

		/* set statement start time */
		SetCurrentStatementStartTimestamp();

		ret = SPI_execute(buf.data, false, 0);

		if (ret != SPI_OK_UTILITY)
			elog(FATAL, "failed to create my schema");
	}

	SPI_finish();
	PopActiveSnapshot();
	CommitTransactionCommand();
	pgstat_report_activity(STATE_IDLE, NULL);
}
示例#14
0
struct PlaceSpecification * getPlaceSpecificationFromDatabase(long long placeid)
{
	const char * query = build_placeSpecQuery(placeid);
	if ( SPI_execute(query, true, 1) != SPI_OK_SELECT )
		ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg(
				"Error when performing placeid query")));

	if ( SPI_processed < 1 )
		ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg(
						"unable to find placespecification")));
	else if ( SPI_processed > 1 )
		ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg(
						"too many placespecifications returned!")));

	HeapTuple placeRow = * SPI_tuptable->vals;

	struct PlaceSpecification * ret = (struct PlaceSpecification *) malloc(sizeof(struct PlaceSpecification));
	ret->startX_ = DatumGetFloat4( SPI_getbinval(placeRow, SPI_tuptable->tupdesc, 1, NULL) );
	ret->startY_ = DatumGetFloat4( SPI_getbinval(placeRow, SPI_tuptable->tupdesc, 2, NULL) );
	ret->xNumber_ = DatumGetInt32( SPI_getbinval(placeRow, SPI_tuptable->tupdesc, 3, NULL) );
	ret->yNumber_ = DatumGetInt32( SPI_getbinval(placeRow, SPI_tuptable->tupdesc, 4, NULL) );
	ret->xIncrement_ = DatumGetFloat4( SPI_getbinval(placeRow, SPI_tuptable->tupdesc, 5, NULL) );
	ret->yIncrement_ = DatumGetFloat4( SPI_getbinval(placeRow, SPI_tuptable->tupdesc, 6, NULL) );
	ret->srid_ = DatumGetInt32( SPI_getbinval(placeRow, SPI_tuptable->tupdesc, 7, NULL) );
	char * projDef = SPI_getvalue(placeRow, SPI_tuptable->tupdesc, 8);
	ret->projDefinition_ = strdup(projDef);
	pfree(projDef);

	return ret;
}
示例#15
0
static void
fetch_edge(HeapTuple *tuple, TupleDesc *tupdesc, edge_columns_t *edge_columns, 
           edge_t *target_edge)
{
  Datum binval;
  bool isnull;
  
  binval = SPI_getbinval(*tuple, *tupdesc, edge_columns->id, &isnull);
 
  if (isnull)
    elog(ERROR, "id contains a null value");
  target_edge->id = DatumGetInt32(binval);
  
  binval = SPI_getbinval(*tuple, *tupdesc, edge_columns->source, &isnull);
  
  if (isnull)
    elog(ERROR, "source contains a null value");

  target_edge->source = DatumGetInt32(binval);
  
  binval = SPI_getbinval(*tuple, *tupdesc, edge_columns->target, &isnull);

  if (isnull)
    elog(ERROR, "target contains a null value");
  
  target_edge->target = DatumGetInt32(binval);
  
  binval = SPI_getbinval(*tuple, *tupdesc, edge_columns->cost, &isnull);
  
  if (isnull)
    elog(ERROR, "cost contains a null value");
  
  target_edge->cost = DatumGetFloat8(binval);
  
  if (edge_columns->reverse_cost != -1) {
    binval = SPI_getbinval(*tuple, *tupdesc, edge_columns->reverse_cost, 
                           &isnull);
    
    if (isnull)
      elog(ERROR, "reverse_cost contains a null value");
    target_edge->reverse_cost =  DatumGetFloat8(binval);
  }
}
示例#16
0
/**
 * Get the data from the tuple
 */
static void fetchEdgeTsp(HeapTuple *tuple, TupleDesc *tupdesc,
         tspEdgeType *edgeColumns,
         tspEdgeType *target_edge,bool reverseCost) {
	Datum binval;
  	bool isnull;

  	binval = SPI_getbinval(*tuple, *tupdesc, edgeColumns->id, &isnull);
  	if (isnull) {
		elog(ERROR, "id contains a null value");
	}
  	target_edge->id = DatumGetInt32(binval);

  	binval = SPI_getbinval(*tuple, *tupdesc, edgeColumns->source, &isnull);
  	if (isnull) {
		elog(ERROR, "source contains a null value");
	}
  	target_edge->source = DatumGetInt32(binval);

  	binval = SPI_getbinval(*tuple, *tupdesc, edgeColumns->target, &isnull);
  	if (isnull) {
		elog(ERROR, "target contains a null value");
	}
  	target_edge->target = DatumGetInt32(binval);

  	binval = SPI_getbinval(*tuple, *tupdesc, edgeColumns->cost, &isnull);
  	
	if (isnull) {
		elog(ERROR, "cost contains a null value");
	}
  	target_edge->cost = DatumGetFloat8(binval);

  	if(reverseCost ) {
		binval = SPI_getbinval(*tuple, *tupdesc, edgeColumns->reverseCost, &isnull);
  	
		if (isnull) {
			elog(ERROR, "reverse_cost contains a null value");
		}
  		target_edge->reverseCost = DatumGetFloat8(binval);
	}

}
示例#17
0
static void
fetch_restrict(HeapTuple *tuple, TupleDesc *tupdesc, 
           restrict_columns_t *restrict_columns, restrict_t *rest)
{
  Datum binval;
  bool isnull;
  int t;

  for(t=0; t<MAX_RULE_LENGTH;++t)
    rest->via[t] = -1;

  binval = SPI_getbinval(*tuple, *tupdesc, restrict_columns->target_id, &isnull);
  if (isnull)
    elog(ERROR, "target_id contains a null value");
  rest->target_id = DatumGetInt32(binval);

  binval = SPI_getbinval(*tuple, *tupdesc, restrict_columns->to_cost, &isnull);
  if (isnull)
    elog(ERROR, "to_cost contains a null value");
  rest->to_cost = DatumGetFloat8(binval);
  char *str = DatumGetCString(SPI_getvalue(*tuple, *tupdesc, restrict_columns->via_path));

  //PGR_DBG("restriction: %f, %i, %s", rest->to_cost, rest->target_id, str);

  if (str != NULL) {
    char* pch = NULL;
    int ci = 0;

    pch = (char *)strtok (str," ,");

    while (pch != NULL && ci < MAX_RULE_LENGTH)
    {
      rest->via[ci] = atoi(pch);
      //PGR_DBG("    rest->via[%i]=%i", ci, rest->via[ci]);
      ci++;
      pch = (char *)strtok (NULL, " ,");
    }
  }

}
示例#18
0
static void
execute_pg_settings_logger(config_log_objects *objects) {

	int		ret;
	bool	isnull;
	StringInfoData	buf;


	SetCurrentStatementStartTimestamp();
	StartTransactionCommand();
	SPI_connect();
	PushActiveSnapshot(GetTransactionSnapshot());
	pgstat_report_activity(STATE_RUNNING, "executing configuration logger function");

	initStringInfo(&buf);

	appendStringInfo(
		&buf,
		"SELECT %s.%s()",
		config_log_schema,
		objects->function_name
		);

	ret = SPI_execute(buf.data, false, 0);
	if (ret != SPI_OK_SELECT)
	{
		elog(FATAL, "SPI_execute failed: error code %d", ret);
	}

	if (SPI_processed != 1)
	{
		elog(FATAL, "not a singleton result");
	}

	log_info("pg_settings_logger() executed");

	if(DatumGetBool(SPI_getbinval(SPI_tuptable->vals[0],
				  SPI_tuptable->tupdesc,
				  1, &isnull)))
	{
		log_info("Configuration changes recorded");
	}
	else
	{
		log_info("No configuration changes detected");
	}

   	SPI_finish();
	PopActiveSnapshot();
	CommitTransactionCommand();
	pgstat_report_activity(STATE_IDLE, NULL);
}
示例#19
0
文件: common.c 项目: ssinger/skytools
static Datum tg_value_lookup(void *arg, int spi_nr, bool *isnull)
{
	TriggerData *tg = arg;
	TupleDesc desc = tg->tg_relation->rd_att;
	HeapTuple row;

	if (TRIGGER_FIRED_BY_UPDATE(tg->tg_event))
		row = tg->tg_newtuple;
	else
		row = tg->tg_trigtuple;

	return SPI_getbinval(row, desc, spi_nr, isnull);
}
long getTokenFrequency(char *token)
{
    bool isNull;
    text *tokenTextP;
    Datum tokenDatum, countDatum;
    Datum *args;
    Oid *argTypes;
    int spiResultCode;
    long count;

    SPI_connect();
    tokenTextP = cstring_to_text(token);
    tokenDatum = PointerGetDatum(tokenTextP);
    argTypes = palloc(sizeof(Oid));
    argTypes[0] = TEXTOID;
    args = (Datum *) palloc(sizeof(Datum));
    args[0] = tokenDatum;

    count = -1;

    spiResultCode = SPI_execute_with_args(
        "SELECT count::integer FROM TokenDictionaryMaterialized WHERE token = $1",
        1,
        argTypes,
        args,
        NULL,
        true,
        1
    );

    if(spiResultCode == SPI_OK_SELECT)
    {
        if(SPI_processed > 0)
        {
            countDatum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isNull);
            count = DatumGetInt32(countDatum);
        } else {
            ereport(ERROR, (errmsg("Token '%s' is not in TokenDictionaryMaterialized", token)));
        }
    } else {
        ereport(ERROR, (errmsg("Unable to query TokenDictionaryMaterialized table. Does it exist?")));
    }

    pfree(args);
    pfree(argTypes);
    pfree(tokenTextP);
    SPI_finish();

    return count;
}
示例#21
0
文件: ts_cfg.c 项目: merlintang/sgb
Oid
name2id_cfg(text *name)
{
    Oid			arg[1];
    bool		isnull;
    Datum		pars[1];
    int			stat;
    Oid			id = findSNMap_t(&(CList.name2id_map), name);
    void	   *plan;
    char	   *nsp;
    char		buf[1024];

    arg[0] = TEXTOID;
    pars[0] = PointerGetDatum(name);

    if (id)
        return id;

    nsp = get_namespace(TSNSP_FunctionOid);
    SPI_connect();
    sprintf(buf, "select oid from %s.pg_ts_cfg where ts_name = $1", nsp);
    plan = SPI_prepare(buf, 1, arg);
    if (!plan)
        /* internal error */
        elog(ERROR, "SPI_prepare() failed");

    stat = SPI_execp(plan, pars, " ", 1);
    if (stat < 0)
        /* internal error */
        elog(ERROR, "SPI_execp return %d", stat);
    if (SPI_processed > 0)
    {
        id = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
        if (isnull)
            ereport(ERROR,
                    (errcode(ERRCODE_CONFIG_FILE_ERROR),
                     errmsg("null id for tsearch config")));
    }
    else
        ereport(ERROR,
                (errcode(ERRCODE_CONFIG_FILE_ERROR),
                 errmsg("no tsearch config")));

    SPI_freeplan(plan);
    SPI_finish();
    addSNMap_t(&(CList.name2id_map), name, id);
    return id;
}
示例#22
0
文件: common.c 项目: ssinger/skytools
static void override_fields(struct PgqTriggerEvent *ev)
{
	TriggerData *tg = ev->tgdata;
	int res, i;
	char *val;

	/* no overrides */
	if (!ev->tgargs)
		return;

	for (i = 0; i < EV_NFIELDS; i++) {
		if (!ev->tgargs->query[i])
			continue;
		res = qb_execute(ev->tgargs->query[i], tg);
		if (res != SPI_OK_SELECT)
			elog(ERROR, "Override query failed");
		if (SPI_processed != 1)
			elog(ERROR, "Expect 1 row from override query, got %d", SPI_processed);

		/* special handling for EV_WHEN */
		if (i == EV_WHEN) {
			bool isnull;
			Oid oid = SPI_gettypeid(SPI_tuptable->tupdesc, 1);
			Datum res;
			if (oid != BOOLOID)
				elog(ERROR, "when= query result must be boolean, got=%u", oid);
			res = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
			if (isnull)
				elog(ERROR, "when= should not be NULL");
			if (DatumGetBool(res) == 0)
				ev->skip_event = true;
			continue;
		}

		/* normal field */
		val = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
		if (ev->field[i]) {
			pfree(ev->field[i]->data);
			pfree(ev->field[i]);
			ev->field[i] = NULL;
		}
		if (val) {
			ev->field[i] = pgq_init_varbuf();
			appendStringInfoString(ev->field[i], val);
		}
	}
}
示例#23
0
static void
get_tsq_Oid(void)
{
	int			ret;
	bool		isnull;

	if ((ret = SPI_exec("select oid from pg_type where typname='tsquery'", 1)) < 0)
		/* internal error */
		elog(ERROR, "SPI_exec to get tsquery oid returns %d", ret);

	if (SPI_processed < 1)
		/* internal error */
		elog(ERROR, "there is no tsvector type");
	tsqOid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
	if (tsqOid == InvalidOid)
		/* internal error */
		elog(ERROR, "tsquery type has InvalidOid");
}
示例#24
0
文件: ts_cfg.c 项目: merlintang/sgb
int
get_currcfg(void)
{
    Oid			arg[1] = {TEXTOID};
    const char *curlocale;
    Datum		pars[1];
    bool		isnull;
    int			stat;
    char		buf[1024];
    char	   *nsp;
    void	   *plan;

    if (current_cfg_id > 0)
        return current_cfg_id;

    nsp = get_namespace(TSNSP_FunctionOid);
    SPI_connect();
    sprintf(buf, "select oid from %s.pg_ts_cfg where locale = $1 ", nsp);
    pfree(nsp);
    plan = SPI_prepare(buf, 1, arg);
    if (!plan)
        /* internal error */
        elog(ERROR, "SPI_prepare() failed");

    curlocale = setlocale(LC_CTYPE, NULL);
    pars[0] = PointerGetDatum(char2text((char *) curlocale));
    stat = SPI_execp(plan, pars, " ", 1);

    if (stat < 0)
        /* internal error */
        elog(ERROR, "SPI_execp return %d", stat);
    if (SPI_processed > 0)
        current_cfg_id = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
    else
        ereport(ERROR,
                (errcode(ERRCODE_CONFIG_FILE_ERROR),
                 errmsg("could not find tsearch config by locale")));

    pfree(DatumGetPointer(pars[0]));
    SPI_freeplan(plan);
    SPI_finish();
    return current_cfg_id;
}
示例#25
0
文件: common.c 项目: ssinger/skytools
/*
 * Fill table information in hash table.
 */
static void fill_tbl_info(Relation rel, struct PgqTableInfo *info)
{
	StringInfo pkeys;
	Datum values[1];
	const char *name = find_table_name(rel);
	TupleDesc desc;
	HeapTuple row;
	bool isnull;
	int res, i, attno;

	/* allow reset ASAP, but ignore it in this call */
	info->invalid = false;

	/* load pkeys */
	values[0] = ObjectIdGetDatum(rel->rd_id);
	res = SPI_execute_plan(pkey_plan, values, NULL, false, 0);
	if (res != SPI_OK_SELECT)
		elog(ERROR, "pkey_plan exec failed");

	/*
	 * Fill info
	 */

	desc = SPI_tuptable->tupdesc;
	pkeys = makeStringInfo();
	info->n_pkeys = SPI_processed;
	info->table_name = MemoryContextStrdup(tbl_cache_ctx, name);
	info->pkey_attno = MemoryContextAlloc(tbl_cache_ctx, info->n_pkeys * sizeof(int));

	for (i = 0; i < SPI_processed; i++) {
		row = SPI_tuptable->vals[i];

		attno = DatumGetInt16(SPI_getbinval(row, desc, 1, &isnull));
		name = SPI_getvalue(row, desc, 2);
		info->pkey_attno[i] = attno;
		if (i > 0)
			appendStringInfoChar(pkeys, ',');
		appendStringInfoString(pkeys, name);
	}
	info->pkey_list = MemoryContextStrdup(tbl_cache_ctx, pkeys->data);
	info->tg_cache = NULL;
}
long getDocumentCount()
{
    int spiResultCode;
    Datum countDatum;
    bool isNull;
    long count;

    SPI_connect();
    spiResultCode = SPI_execute("SELECT COUNT(*)::integer FROM CardVectors", 1, 1);
    if(spiResultCode == SPI_OK_SELECT)
    {
        countDatum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isNull);
        count = DatumGetInt32(countDatum);
    } else {
        ereport(ERROR, (errmsg("Unable to query CardVectors table. Does it exist?")));
        count = -1;
    }

    SPI_finish();
    return count;
}
示例#27
0
static Oid
GetRelOid(Oid filenode)
{
	int			ret;
	Oid			relid;
	bool		isnull;
	Datum		value[1] = { ObjectIdGetDatum(filenode) };

	static SPIPlanPtr	plan = NULL;

	/* If this is our first time here, create a plan and save it for later calls. */
	if (plan == NULL)
	{
		StringInfoData	buf;
		Oid	paramType[1] = {OIDOID};

		initStringInfo(&buf);
		appendStringInfo(&buf, "select oid from pg_class where pg_relation_filenode(oid) = $1");

		plan = SPI_prepare(buf.data, 1, (Oid*)&paramType);

		if (plan == NULL)
			elog(ERROR, "SPI_prepare returned %d", SPI_result);
	}

	ret = SPI_execute_plan(plan, (Datum*)&value, NULL, true, 1);

	if (ret != SPI_OK_SELECT)
		ereport(FATAL, (errmsg("SPI_execute_plan failed: error code %d", ret)));

	if (SPI_processed < 1)
		return InvalidOid;

	relid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0],
											SPI_tuptable->tupdesc, 1, &isnull));
	if (isnull)
		return InvalidOid;

	return relid;
}
示例#28
0
/*
 * http://doxygen.postgresql.org/include_2catalog_2pg__type_8h.html;
 */
char
pgr_SPI_getChar(
        HeapTuple *tuple, TupleDesc *tupdesc, Column_info_t info,
        bool strict, char default_value) {
    Datum binval;
    bool isNull;
    char value = default_value;

    binval = SPI_getbinval(*tuple, *tupdesc, info.colNumber, &isNull);
    if (!(info.type == BPCHAROID)) {
        elog(ERROR, "Unexpected Column type of %s. Expected CHAR", info.name);
    }
    if (!isNull) {
        value =  ((char*)binval)[1];
    } else {
        if (strict) {
            elog(ERROR, "Unexpected Null value in column %s", info.name);
        }
        value = default_value;
    }
    return value;
}
示例#29
0
文件: Tuple.c 项目: tada/pljava
jobject
Tuple_getObject(TupleDesc tupleDesc, HeapTuple tuple, int index, jclass rqcls)
{
	jobject result = 0;
	PG_TRY();
	{
		Type type = TupleDesc_getColumnType(tupleDesc, index);
		if(type != 0)
		{
			bool wasNull = false;
			Datum binVal = SPI_getbinval(tuple, tupleDesc, (int)index, &wasNull);
			if(!wasNull)
				result = Type_coerceDatumAs(type, binVal, rqcls).l;
		}
	}
	PG_CATCH();
	{
		Exception_throw_ERROR("SPI_getbinval");
	}
	PG_END_TRY();
	return result;
}
示例#30
0
Oid
name2id_prs(text *name)
{
	Oid			arg[1];
	bool		isnull;
	Datum		pars[1];
	int			stat;
	Oid			id = findSNMap_t(&(PList.name2id_map), name);
	char		buf[1024],
			   *nsp;
	void	   *plan;

	arg[0] = TEXTOID;
	pars[0] = PointerGetDatum(name);

	if (id)
		return id;

	SPI_connect();
	nsp = get_namespace(TSNSP_FunctionOid);
	sprintf(buf, "select oid from %s.pg_ts_parser where prs_name = $1", nsp);
	pfree(nsp);
	plan = SPI_prepare(buf, 1, arg);
	if (!plan)
		ts_error(ERROR, "SPI_prepare() failed");

	stat = SPI_execp(plan, pars, " ", 1);
	if (stat < 0)
		ts_error(ERROR, "SPI_execp return %d", stat);
	if (SPI_processed > 0)
		id = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
	else
		ts_error(ERROR, "No parser '%s'", text2char(name));
	SPI_freeplan(plan);
	SPI_finish();
	addSNMap_t(&(PList.name2id_map), name, id);
	return id;
}