예제 #1
0
QSqlRecord QPSQLResult::record() const
{
    QSqlRecord info;
    if (!isActive() || !isSelect())
        return info;

    int count = PQnfields(d->result);
    for (int i = 0; i < count; ++i) {
        QSqlField f;
        if (d->driver->isUtf8)
            f.setName(QString::fromUtf8(PQfname(d->result, i)));
        else
            f.setName(QString::fromLocal8Bit(PQfname(d->result, i)));
        f.setType(qDecodePSQLType(PQftype(d->result, i)));
        int len = PQfsize(d->result, i);
        int precision = PQfmod(d->result, i);
        // swap length and precision if length == -1
        if (len == -1 && precision > -1) {
            len = precision - 4;
            precision = -1;
        }
        f.setLength(len);
        f.setPrecision(precision);
        f.setSqlType(PQftype(d->result, i));
        info.append(f);
    }
    return info;
}
예제 #2
0
void fill_query_column_types(pgsnmpd_query *query)
{
    int i;
    Oid type;  /* NB! PostgreSQL's Oid, not Net-SNMP's oid */
    PGresult *res;
    const char *values[1];
    char param[10];
    
    /* This translates SQL types to SNMP types, as follows:
     * Conversions for these four types are obvious
     * ASN_INTEGER
     * ASN_FLOAT
     * ASN_BOOLEAN
     * ASN_OBJECT_ID
     * 
     * Everything else becomes a string:
     * ASN_OCTET_STR
     * 
     * Perhaps one day we'll also use ASN_DOUBLE
     */

    if (query->result == NULL)
        return;

    values[0] = param;

    for (i = 0; i < query->colcount; i++) {
        if (query->types[i] != 255) {
            continue;
        }
        type = PQftype(query->result, i);
        /* 
         * TODO: query pg_type table (including pg_type.h to use builtin
         * constants got all kinds of errors I'd rather not deal with
         */
        sprintf(param, "%d", type);
        res = PQexecPrepared(dbconn, "TYPEQUERY", 1, values, NULL, NULL, 0);
        if (PQresultStatus(res) != PGRES_TUPLES_OK)
            snmp_log(LOG_ERR, "Couldn't determine column type\n");
        else {
            switch (atoi(PQgetvalue(res, 0, 0))) {
                case 0:
                    query->types[i] = ASN_INTEGER;
                    break;
                case 1:
                    query->types[i] = ASN_FLOAT;
                    break;
                case 2: 
                    query->types[i] = ASN_BOOLEAN;
                    break;
                case 3: 
                    query->types[i] = ASN_OCTET_STR;
                    break;
                default: /* If we get here, it's because the TYPEQUERY is b0rken */
                    snmp_log(LOG_ERR, "Unknown column type translation. This is a bug.\n");
            }
        }
        PQclear(res);
    }
}
예제 #3
0
static void postgres_ingest_stats(postgres_check_info_t *ci) {
  if(ci->rv == PGRES_TUPLES_OK) {
    /* metrics */
    int nrows, ncols, i, j;
    nrows = PQntuples(ci->result);
    ncols = PQnfields(ci->result);
    noit_stats_set_metric(&ci->current, "row_count", METRIC_INT32, &nrows);
    for (i=0; i<nrows; i++) {
      noitL(nldeb, "postgres: row %d [%d cols]:\n", i, ncols);
      if(ncols<2) continue;
      if(PQgetisnull(ci->result, i, 0)) continue;
      for (j=1; j<ncols; j++) {
        Oid coltype;
        int iv, *piv;
        int64_t lv, *plv;
        double dv, *pdv;
        char *sv;
        char mname[128];
  
        snprintf(mname, sizeof(mname), "%s`%s",
                 PQgetvalue(ci->result, i, 0), PQfname(ci->result, j));
        coltype = PQftype(ci->result, j);
        noitL(nldeb, "postgres:   col %d (%s) type %d:\n", j, mname, coltype);
        switch(coltype) {
          case BOOLOID:
            if(PQgetisnull(ci->result, i, j)) piv = NULL;
            else {
              iv = strcmp(PQgetvalue(ci->result, i, j), "f") ? 1 : 0;
              piv = &iv;
            }
            noit_stats_set_metric(&ci->current, mname, METRIC_INT32, piv);
            break;
          case INT2OID:
          case INT4OID:
          case INT8OID:
            if(PQgetisnull(ci->result, i, j)) plv = NULL;
            else {
              lv = strtoll(PQgetvalue(ci->result, i, j), NULL, 10);
              plv = &lv;
            }
            noit_stats_set_metric(&ci->current, mname, METRIC_INT64, plv);
          case FLOAT4OID:
          case FLOAT8OID:
          case NUMERICOID:
            if(PQgetisnull(ci->result, i, j)) pdv = NULL;
            else {
              dv = atof(PQgetvalue(ci->result, i, j));
              pdv = &dv;
            }
            noit_stats_set_metric(&ci->current, mname, METRIC_DOUBLE, pdv);
          default:
            if(PQgetisnull(ci->result, i, j)) sv = NULL;
            else sv = PQgetvalue(ci->result, i, j);
            noit_stats_set_metric(&ci->current, mname, METRIC_GUESS, sv);
            break;
        }
      }
    }
  }
}
예제 #4
0
 int column::sql_type() const
 {
     if (!is_valid()) {
         throw no_such_column_exception();
     }
     return PQftype(stmt_.get(), column_);
 }
예제 #5
0
//==================================================================================
//Create a cursor result set
bool PostgresqlCursor::drv_open(const KDbEscapedString& sql)
{
    d->res = d->executeSQL(sql);
    d->resultStatus = PQresultStatus(d->res);
    if (d->resultStatus != PGRES_TUPLES_OK && d->resultStatus != PGRES_COMMAND_OK) {
        storeResultAndClear(&d->res, d->resultStatus);
        return false;
    }
    m_fieldsToStoreInRecord = PQnfields(d->res);
    m_fieldCount = m_fieldsToStoreInRecord - (containsRecordIdInfo() ? 1 : 0);
    m_numRows = PQntuples(d->res);
    m_records_in_buf = m_numRows;
    m_buffering_completed = true;

    // get real types for all fields
    PostgresqlDriver* drv = static_cast<PostgresqlDriver*>(connection()->driver());

    m_realTypes.resize(m_fieldsToStoreInRecord);
    m_realLengths.resize(m_fieldsToStoreInRecord);
    for (int i = 0; i < int(m_fieldsToStoreInRecord); i++) {
        const int pqtype = PQftype(d->res, i);
        const int pqfmod = PQfmod(d->res, i);
        m_realTypes[i] = drv->pgsqlToKDbType(pqtype, pqfmod, &m_realLengths[i]);
    }
    return true;
}
예제 #6
0
static int pgsql_stmt_describe(pdo_stmt_t *stmt, int colno)
{
	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
	struct pdo_column_data *cols = stmt->columns;
	struct pdo_bound_param_data *param;
	char *str;

	if (!S->result) {
		return 0;
	}

	str = PQfname(S->result, colno);
	cols[colno].name = zend_string_init(str, strlen(str), 0);
	cols[colno].maxlen = PQfsize(S->result, colno);
	cols[colno].precision = PQfmod(S->result, colno);
	S->cols[colno].pgsql_type = PQftype(S->result, colno);

	switch (S->cols[colno].pgsql_type) {

		case BOOLOID:
			cols[colno].param_type = PDO_PARAM_BOOL;
			break;

		case OIDOID:
			/* did the user bind the column as a LOB ? */
			if (stmt->bound_columns && (
					(param = zend_hash_index_find_ptr(stmt->bound_columns, colno)) != NULL ||
					(param = zend_hash_find_ptr(stmt->bound_columns, cols[colno].name)) != NULL)) {

				if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB) {
					cols[colno].param_type = PDO_PARAM_LOB;
					break;
				}
			}
			cols[colno].param_type = PDO_PARAM_INT;
			break;

		case INT2OID:
		case INT4OID:
			cols[colno].param_type = PDO_PARAM_INT;
			break;

		case INT8OID:
			if (sizeof(zend_long)>=8) {
				cols[colno].param_type = PDO_PARAM_INT;
			} else {
				cols[colno].param_type = PDO_PARAM_STR;
			}
			break;

		case BYTEAOID:
			cols[colno].param_type = PDO_PARAM_LOB;
			break;

		default:
			cols[colno].param_type = PDO_PARAM_STR;
	}

	return 1;
}
예제 #7
0
파일: sqlda.c 프로젝트: alvherre/postgres
struct sqlda_struct *
ecpg_build_native_sqlda(int line, PGresult *res, int row, enum COMPAT_MODE compat)
{
	struct sqlda_struct *sqlda;
	long		size;
	int			i;

	size = sqlda_native_total_size(res, row, compat);
	sqlda = (struct sqlda_struct *) ecpg_alloc(size, line);
	if (!sqlda)
		return NULL;

	memset(sqlda, 0, size);

	sprintf(sqlda->sqldaid, "SQLDA  ");
	sqlda->sqld = sqlda->sqln = PQnfields(res);
	ecpg_log("ecpg_build_native_sqlda on line %d sqld = %d\n", line, sqlda->sqld);
	sqlda->sqldabc = sizeof(struct sqlda_struct) + (sqlda->sqld - 1) * sizeof(struct sqlvar_struct);

	for (i = 0; i < sqlda->sqld; i++)
	{
		char	   *fname;

		sqlda->sqlvar[i].sqltype = sqlda_dynamic_type(PQftype(res, i), compat);
		fname = PQfname(res, i);
		sqlda->sqlvar[i].sqlname.length = strlen(fname);
		strcpy(sqlda->sqlvar[i].sqlname.data, fname);
	}

	return sqlda;
}
예제 #8
0
static VALUE result_each(VALUE self) {
    int r, c, rows, cols, *types, failed;
    PGresult *res;
    Data_Get_Struct(self, PGresult, res);

    VALUE fields = rb_ary_new();
    rows  = PQntuples(res);
    cols  = PQnfields(res);
    types = (int*)malloc(sizeof(int)*cols);
    for (c = 0; c < cols; c++) {
        rb_ary_push(fields, ID2SYM(rb_intern(PQfname(res, c))));
        types[c] = PQftype(res, c);
    }

    for (r = 0; r < rows; r++) {
        VALUE tuple = rb_hash_new();
        for (c = 0; c < cols; c++) {
            rb_hash_aset(tuple, rb_ary_entry(fields, c),
                PQgetisnull(res, r, c) ? Qnil : typecast(PQgetvalue(res, r, c), PQgetlength(res, r, c), types[c]));
        }
        rb_protect(rb_yield, tuple, &failed);
        if (failed) {
            free(types);
            rb_jump_tag(failed);
        }
    }

    free(types);
    return Qnil;
}
예제 #9
0
static VALUE cCommand_execute_reader(int argc, VALUE *argv[], VALUE self) {
  VALUE reader, query;
  VALUE field_names, field_types;

  int i;
  int field_count;
  int infer_types = 0;

  VALUE connection = rb_iv_get(self, "@connection");
  VALUE postgres_connection = rb_iv_get(connection, "@connection");
  if (Qnil == postgres_connection) {
    rb_raise(eConnectionError, "This connection has already been closed.");
  }

  PGconn *db = DATA_PTR(postgres_connection);
  PGresult *response;

  query = build_query_from_args(self, argc, argv);

  response = cCommand_execute(self, db, query);

  if ( PQresultStatus(response) != PGRES_TUPLES_OK ) {
    raise_error(self, response, query);
  }

  field_count = PQnfields(response);

  reader = rb_funcall(cReader, ID_NEW, 0);
  rb_iv_set(reader, "@connection", connection);
  rb_iv_set(reader, "@reader", Data_Wrap_Struct(rb_cObject, 0, 0, response));
  rb_iv_set(reader, "@field_count", INT2NUM(field_count));
  rb_iv_set(reader, "@row_count", INT2NUM(PQntuples(response)));

  field_names = rb_ary_new();
  field_types = rb_iv_get(self, "@field_types");

  if ( field_types == Qnil || 0 == RARRAY_LEN(field_types) ) {
    field_types = rb_ary_new();
    infer_types = 1;
  } else if (RARRAY_LEN(field_types) != field_count) {
    // Whoops...  wrong number of types passed to set_types.  Close the reader and raise
    // and error
    rb_funcall(reader, rb_intern("close"), 0);
    rb_raise(eArgumentError, "Field-count mismatch. Expected %ld fields, but the query yielded %d", RARRAY_LEN(field_types), field_count);
  }

  for ( i = 0; i < field_count; i++ ) {
    rb_ary_push(field_names, rb_str_new2(PQfname(response, i)));
    if ( infer_types == 1 ) {
      rb_ary_push(field_types, infer_ruby_type(PQftype(response, i)));
    }
  }

  rb_iv_set(reader, "@position", INT2NUM(0));
  rb_iv_set(reader, "@fields", field_names);
  rb_iv_set(reader, "@field_types", field_types);

  return reader;
}
예제 #10
0
/*
 *	Read in field descriptions from a libpq result set.
 *	If self is not null, then also store the information.
 *	If self is null, then just read, don't store.
 */
BOOL
CI_read_fields_from_pgres(ColumnInfoClass *self, PGresult *pgres)
{
	CSTR		func = "CI_read_fields";
	Int2		lf;
	int			new_num_fields;
	OID		new_adtid, new_relid = 0, new_attid = 0;
	Int2		new_adtsize;
	Int4		new_atttypmod = -1;
	char	   *new_field_name;

	/* at first read in the number of fields that are in the query */
	new_num_fields = PQnfields(pgres);

	mylog("num_fields = %d\n", new_num_fields);

	if (self)
	{
		/* according to that allocate memory */
		CI_set_num_fields(self, new_num_fields);
		if (NULL == self->coli_array)
			return FALSE;
	}

	/* now read in the descriptions */
	for (lf = 0; lf < new_num_fields; lf++)
	{
		new_field_name = PQfname(pgres, lf);
		new_relid = PQftable(pgres, lf);
		new_attid = PQftablecol(pgres, lf);
		new_adtid = PQftype(pgres, lf);
		new_adtsize = PQfsize(pgres, lf);

		mylog("READING ATTTYPMOD\n");
		new_atttypmod = PQfmod(pgres, lf);

		/* Subtract the header length */
		switch (new_adtid)
		{
			case PG_TYPE_DATETIME:
			case PG_TYPE_TIMESTAMP_NO_TMZONE:
			case PG_TYPE_TIME:
			case PG_TYPE_TIME_WITH_TMZONE:
				break;
			default:
				new_atttypmod -= 4;
		}
		if (new_atttypmod < 0)
			new_atttypmod = -1;

		mylog("%s: fieldname='%s', adtid=%d, adtsize=%d, atttypmod=%d (rel,att)=(%d,%d)\n", func, new_field_name, new_adtid, new_adtsize, new_atttypmod, new_relid, new_attid);

		if (self)
			CI_set_field_info(self, lf, new_field_name, new_adtid, new_adtsize, new_atttypmod, new_relid, new_attid);
	}

	return TRUE;
}
예제 #11
0
void PgStatement::GetFieldValue
  (
  int         nIndex,
  wxVariant&  v
  )
  {
  int nIsNull = PQgetisnull(pgr, nCurrentRecord, nIndex);
  if(nIsNull != 0)
    {
    v.MakeNull();
    return;
    }

	char * sz = PQgetvalue(pgr, nCurrentRecord, nIndex);

  Oid typ = PQftype(pgr, nIndex);
  switch(typ)
    {
    case PG_OID_BOOLEAN:
      {
      bool b = (sz[0] == 't')? true : false;
      v = b;
      break;
      }
    case PG_OID_OID:
    case PG_OID_INT4:
    case PG_OID_TRANSACTIONID:
      {
      long n = atol(sz);
      v = n;
      break;
      }
    case PG_OID_DOUBLE:
      {
      double d = atof(sz);
      v = d;
      break;
      }
    case PG_OID_NAME:
    case PG_OID_TEXT:
    case PG_OID_VARCHAR_LENGTH:
      {
      //int nFormat = PQfformat(pgr, nIndex); // 0 => text, 1 => binary
      wxString s(sz, wxConvLocal);
      //wxString s = wxConvUTF8.cMB2WX(sz);
      v = s;
      break;
      }
    // Items we don't know how to handle
    case PG_OID_TEXTARRAY:
    case PG_OID_ACLITEMARRAY:
      v = wxT("");
      break;

    default:
      throw wx::Exception(wxT("PgStatement::GetFieldValue() Unhandled data type %d"), typ);
    }
  }
예제 #12
0
unsigned ResultSet::getColumnTypeId(int column_idx)
{
	//Throws an error in case the column index is invalid
	if(column_idx < 0 || column_idx >= getColumnCount())
		throw Exception(ERR_REF_TUPLE_COL_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__);

	//Returns the column type id on the specified index
	return(static_cast<unsigned>(PQftype(sql_result, column_idx)));
}
예제 #13
0
            sql_value column::to_value() const
            {
                if (!is_valid()) {
                    throw no_such_column_exception();
                }

                return data_mapper::to_value(PQftype(stmt_.get(), column_), PQgetvalue(stmt_.get(), row_, column_),
                                             PQgetlength(stmt_.get(), row_, column_));
            }
예제 #14
0
 virtual int getTypeOID(const char* name) const
 {
     int col = PQfnumber(res_, name);
     if (col >= 0)
     {
         return PQftype(res_, col);
     }
     return 0;
 }
예제 #15
0
파일: sqlda.c 프로젝트: alvherre/postgres
/*
 * Build "struct sqlda_compat" (metadata only) from PGresult
 * leaving enough space for the field values in
 * the given row number
 */
struct sqlda_compat *
ecpg_build_compat_sqlda(int line, PGresult *res, int row, enum COMPAT_MODE compat)
{
	struct sqlda_compat *sqlda;
	struct sqlvar_compat *sqlvar;
	char	   *fname;
	long		size;
	int			sqld;
	int			i;

	size = sqlda_compat_total_size(res, row, compat);
	sqlda = (struct sqlda_compat *) ecpg_alloc(size, line);
	if (!sqlda)
		return NULL;

	memset(sqlda, 0, size);
	sqlvar = (struct sqlvar_compat *) (sqlda + 1);
	sqld = PQnfields(res);
	fname = (char *) (sqlvar + sqld);

	sqlda->sqld = sqld;
	ecpg_log("ecpg_build_compat_sqlda on line %d sqld = %d\n", line, sqld);
	sqlda->desc_occ = size;		/* cheat here, keep the full allocated size */
	sqlda->sqlvar = sqlvar;

	for (i = 0; i < sqlda->sqld; i++)
	{
		sqlda->sqlvar[i].sqltype = sqlda_dynamic_type(PQftype(res, i), compat);
		strcpy(fname, PQfname(res, i));
		sqlda->sqlvar[i].sqlname = fname;
		fname += strlen(sqlda->sqlvar[i].sqlname) + 1;

		/*
		 * this is reserved for future use, so we leave it empty for the time
		 * being
		 */
		/* sqlda->sqlvar[i].sqlformat = (char *) (long) PQfformat(res, i); */
		sqlda->sqlvar[i].sqlxid = PQftype(res, i);
		sqlda->sqlvar[i].sqltypelen = PQfsize(res, i);
	}

	return sqlda;
}
예제 #16
0
/*
 * call-seq:
 *    res.ftype( column_number )
 *
 * Returns the data type associated with _column_number_.
 *
 * The integer returned is the internal +OID+ number (in PostgreSQL)
 * of the type. To get a human-readable value for the type, use the
 * returned OID and the field's #fmod value with the format_type() SQL
 * function:
 *
 *   # Get the type of the second column of the result 'res'
 *   typename = conn.
 *     exec( "SELECT format_type($1,$2)", [res.ftype(1), res.fmod(1)] ).
 *     getvalue( 0, 0 )
 *
 * Raises an ArgumentError if _column_number_ is out of range.
 */
static VALUE
pgresult_ftype(VALUE self, VALUE index)
{
	PGresult* result = pgresult_get(self);
	int i = NUM2INT(index);
	if (i < 0 || i >= PQnfields(result)) {
		rb_raise(rb_eArgError, "invalid field number %d", i);
	}
	return INT2NUM(PQftype(result, i));
}
예제 #17
0
QueryResultPostgre::QueryResultPostgre(PGresult *result, uint64 rowCount, uint32 fieldCount) :
    QueryResult(rowCount, fieldCount), mResult(result),  mTableIndex(0)
{

    mCurrentRow = new Field[mFieldCount];
    ASSERT(mCurrentRow);

    for (uint32 i = 0; i < mFieldCount; i++)
        mCurrentRow[i].SetType(ConvertNativeType(PQftype( result, i )));
}
예제 #18
0
bool ResultSet::isColumnBinaryFormat(int column_idx)
{
	//Raise an error in case the column index is invalid
	if(column_idx < 0 || column_idx >= getColumnCount())
		throw Exception(ERR_REF_TUPLE_COL_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__);

	/* Returns the column format in the current tuple.
		According to libpq documentation, value = 0, indicates column text format,
	value = 1 the column has binary format, the other values are reserved.

	One additional check is made, if the type of the column is bytea. */
	return(PQfformat(sql_result, column_idx)==1 || PQftype(sql_result, column_idx)==BYTEAOID);
}
예제 #19
0
static void
esql_module_setup_cb(PGresult *pres, int col, Eina_Value_Struct_Member *m)
{
   m->name = eina_stringshare_add(PQfname(pres, col));

   switch (PQftype(pres, col))
     {
      case TIMESTAMPOID:
      case ABSTIMEOID:
        m->type = EINA_VALUE_TYPE_TIMESTAMP;
        break;

      case BYTEAOID:
      case NAMEOID:
      case TEXTOID:
      case VARCHAROID:
      case BPCHAROID:
        m->type = EINA_VALUE_TYPE_STRING;
        break;

      case BOOLOID:
      case CHAROID:
        m->type = EINA_VALUE_TYPE_CHAR;
        break;

      case INT2OID:
        m->type = EINA_VALUE_TYPE_SHORT;
        break;

      case INT4OID:
        m->type = EINA_VALUE_TYPE_LONG;
        break;

      case INT8OID:
        m->type = EINA_VALUE_TYPE_INT64;
        break;

      case FLOAT4OID:
        m->type = EINA_VALUE_TYPE_FLOAT;
        break;

      case FLOAT8OID:
      case TINTERVALOID:
      case RELTIMEOID:
        m->type = EINA_VALUE_TYPE_DOUBLE;
        break;

      default:
        m->type = EINA_VALUE_TYPE_BLOB;
     }
}
예제 #20
0
boost::shared_ptr<avro::RecordSchema> schema_for_table_row(std::string schema_name, boost::shared_ptr<PGresult> res)
{
    boost::shared_ptr<avro::RecordSchema> record_schema = boost::make_shared<avro::RecordSchema>(schema_name);

    int nFields = PQnfields(res.get());
    for (int i = 0; i < nFields; i++)
    {
        Oid col_type = PQftype(res.get(), i);
        std::string col_name = PQfname(res.get(), i);
        boost::shared_ptr<avro::Schema> col_schema = schema_for_oid(col_type);
        /* TODO ensure that names abide by Avro's requirements */
        record_schema->addField(col_name, *col_schema);
    }
    return record_schema;
}
예제 #21
0
boost::shared_ptr<avro::RecordSchema> schema_for_table_key(std::string schema_name, const std::vector<std::string>& keys, boost::shared_ptr<PGresult> res)
{
    boost::shared_ptr<avro::RecordSchema> record_schema = boost::make_shared<avro::RecordSchema>(schema_name);
    for (std::vector<std::string>::const_iterator i = keys.begin(); i != keys.end(); i++)
    {
        int column_index = PQfnumber(res.get(), i->c_str());
        assert(column_index >= 0);
        if (column_index >= 0)
        {
            Oid col_type = PQftype(res.get(), column_index);
            boost::shared_ptr<avro::Schema> col_schema = schema_for_oid(col_type);
            /* TODO ensure that names abide by Avro's requirements */
            record_schema->addField(*i, *col_schema);
        }
    }
    return record_schema;
}
예제 #22
0
// returns true if checks passed, false if they failed
// We check the types of columns 0 and 1.
static bool checkColumnsTypes(PGresult * const result, const int numCols) {
  BOOST_ASSERT_MSG( (EXPECTED_NUM_COLS == numCols), "Unexpected bad number of columns: this should have been handled earlier" );

  bool typesAreCorrect = true; // leave as true until we find a bad type

  for (int i = 0; i != EXPECTED_NUM_COLS; ++i) {

    const Oid typeForCol = PQftype(result, i);
    if (expectedTypes[i] == typeForCol) {
      std::cout << "Correct type found for column " << i << '\n';
    } else {
      typesAreCorrect = false;
      std::cerr << "Incorrect type for column " << i << ": OID number of " << typeForCol << '\n';
    }

  }

  return typesAreCorrect;
}
예제 #23
0
bool CPostgresRecordset::Init(PGconn *pDb, PGresult *pStmt)
{
	m_pStmt = pStmt;

	m_num_fields = PQnfields(m_pStmt);
	m_sqlfields.resize(m_num_fields);
	for(int n=0; n<m_num_fields; n++)
	{
		m_sqlfields[n].field = n;
		m_sqlfields[n].rs = this;
		m_sqlfields[n].name = PQfname(m_pStmt,n);
		m_sqlfields[n].type = PQftype(m_pStmt,n);
	}

	m_num_rows = PQntuples(m_pStmt);
	CServerIo::trace(3,"PG_rs: m_num_fields=%d; m_num_rows=%d",m_num_fields, m_num_rows);
	m_current_row = 0;

	return true;
}
예제 #24
0
/*--------------------------------------------------------------------------------*/
bool PostgresDatabase::PostgresQuery::Fetch(AString& results)
{
	bool success = false;

	if (res && nfields && (row < nrows)) {
		uint_t i;

		results.Delete();

		for (i = 0; i < nfields; i++) {
			if (i) results.printf(",");

			const char *p = PQgetvalue(res, row, i);
			switch (PQftype(res, i)) {
				case TIMESTAMPOID: {
					ADateTime dt;
					dt.FromTimeStamp(p, true);
					results += AString((uint64_t)dt);
					//debug("%s->%llu->%s (%s)\n", p, (uint64)dt, dt.DateFormat("%Y-%M-%D %h:%m:%s.%S").str(), dt.UTCToLocal().DateFormat("%Y-%M-%D %h:%m:%s.%S").str());
					break;
				}

				case TEXTOID:
				case CHAROID:
				case VARCHAROID:
					results.printf("'%s'", AString(p).Escapify().str());
					break;

				default:
					results.printf("%s", p);
					break;
			}
		}

		//debug("Row %u/%u: %s\n", row, nrows, results.str());
		row++;
		success = true;
	}

	return success;
}
예제 #25
0
파일: pgmquery.c 프로젝트: Torvus/pgmanager
GType
pgm_query_get_column_gtype( PgmQuery *query, gint column )
{
	g_return_val_if_fail( query != NULL, G_TYPE_INVALID );
	g_return_val_if_fail( column >= 0, G_TYPE_INVALID );
	g_return_val_if_fail( column < pgm_query_get_columns( query ), G_TYPE_INVALID );

	if( query->result == NULL )
		return G_TYPE_NONE;

	switch( PQftype( query->result, column ) )
	{
		case BOOLOID:   return G_TYPE_BOOLEAN;
		case INT8OID:   return G_TYPE_INT;
		case NUMERICOID:
		case INT2OID:   return G_TYPE_LONG;
		case INT4OID:   return G_TYPE_ULONG;
		case FLOAT4OID: return G_TYPE_DOUBLE;
		case FLOAT8OID: return G_TYPE_FLOAT;
	}
	return G_TYPE_STRING;
}
예제 #26
0
/*
** Get the internal database type of the given column.
*/
static char *getcolumntype (PGconn *conn, PGresult *result, int i, char *buff) {
	Oid codigo = PQftype (result, i);
	char stmt[100];
	PGresult *res;

	sprintf (stmt, "select typname from pg_type where oid = %d", codigo);
	res = PQexec(conn, stmt);
	strcpy (buff, "undefined");

	if (PQresultStatus (res) == PGRES_TUPLES_OK) {
		if (PQntuples(res) > 0) {
			char *name = PQgetvalue(res, 0, 0);
			if (strcmp (name, "bpchar")==0 || strcmp (name, "varchar")==0) {
				int modifier = PQfmod (result, i) - 4;
				sprintf (buff, "%.20s (%d)", name, modifier);
			}
			else
				strncpy (buff, name, 20);
		}
	}
	PQclear(res);
	return buff;
}
예제 #27
0
static SCM pg_exec(SCM conn, SCM query) {
	struct pg_conn *pgc;
	struct pg_res *pgr;
	char *query_s;
	int i;
	SCM res_smob;
	scm_assert_smob_type(pg_conn_tag, conn);
	pgc = (struct pg_conn *)SCM_SMOB_DATA(conn);
	pgr = (struct pg_res *)scm_gc_malloc(sizeof(struct pg_res),
					"pg_res");
	query_s = scm_to_utf8_string(query);
	scm_lock_mutex(pgc->mutex);
	pgr->res = PQexec(pgc->conn, query_s);
	scm_unlock_mutex(pgc->mutex);
	pgr->cursor = 0;
	pgr->fields = SCM_EOL;
	pgr->types = SCM_EOL;
	pgr->nfields = PQnfields(pgr->res);
	pgr->tuples = PQntuples(pgr->res);
	pgr->cmd_tuples = atoi(PQcmdTuples(pgr->res));
	pgr->status = PQresultStatus(pgr->res);
	if ((pgr->status == PGRES_FATAL_ERROR) ||
			(pgr->status == PGRES_NONFATAL_ERROR)) {
		log_msg("PQquery: %s\n", query_s);
		log_msg("PQerr: %s", PQresultErrorMessage(pgr->res));
		}
	free(query_s);
	for (i = pgr->nfields - 1; i >= 0; i--) {
		pgr->fields = scm_cons(scm_from_utf8_symbol(
			PQfname(pgr->res, i)), pgr->fields);
		pgr->types = scm_cons(scm_from_unsigned_integer(PQftype(pgr->res, i)),
				pgr->types);
		}
	SCM_NEWSMOB(res_smob, pg_res_tag, pgr);
	return res_smob;
	}
예제 #28
0
파일: psql.c 프로젝트: aosm/X11
LispObj *
Lisp_PQftype(LispBuiltin *builtin)
{
    Oid oid;
    int field;
    PGresult *res;

    LispObj *result, *field_number;

    field_number = ARGUMENT(1);
    result = ARGUMENT(0);

    if (!CHECKO(result, PGresult_t))
	LispDestroy("%s: cannot convert %s to PGresult*",
		    STRFUN(builtin), STROBJ(result));
    res = (PGresult*)(result->data.opaque.data);

    CHECK_INDEX(field_number);
    field = FIXNUM_VALUE(field_number);

    oid = PQftype(res, field);

    return (INTEGER(oid));
}
예제 #29
0
파일: pgconn.c 프로젝트: berkus/moto
PGResultSet *
pgconn_query(PGConnection *conn, const char *query)
{
   int i;
   PGresult *result;
   PGResultSet *rset;

   result = PQexec(conn->stream, query);

   if (result == NULL)
      THROW("SQLException", "%s", PQerrorMessage(conn->stream));

   if(PQresultStatus(result) != PGRES_TUPLES_OK)
      THROW("SQLException", "%s", PQresultErrorMessage(result));

   rset = pgrset_createDefault(conn, result);

   for(i = 0; i < rset->columns; i++){
      rset->column_names[i] = estrdup(PQfname(result, i));
      rset->column_types[i] = PQftype(result, i);
   }

   return rset;
}
예제 #30
0
파일: pgsql_cursor.c 프로젝트: antono/gsql
GSQLCursorState
pgsql_cursor_open_bind (GSQLCursor *cursor, GList *args) {
	GSQL_TRACE_FUNC;
	GSQLEPGSQLSession *e_session = NULL;
	GSQLEPGSQLCursor  *e_cursor = NULL;
	GSQLVariable *var;
	GSQLWorkspace *workspace = NULL;
	PGSQL_FIELD *field;

	gulong binds_arg, n, n_fields, is_null = 1;
	// store parameters information
	Oid *paramTypes = NULL;
	const char **paramValues = NULL;
	int *paramLengths = NULL;
	int *paramFormats = NULL;

	GList *vlist = args;
	GType vtype;
	gchar error_str[2048];
	
	g_return_if_fail (GSQL_IS_CURSOR(cursor));
	
	g_return_if_fail(GSQL_IS_SESSION(cursor->session));
	e_session = cursor->session->spec;

	workspace = gsql_session_get_workspace (cursor->session);
	g_return_if_fail(GSQL_IS_WORKSPACE(workspace));
  
	if (!pgsql_cursor_prepare (cursor)) {
		return GSQL_CURSOR_STATE_ERROR;
	}

	e_cursor = cursor->spec;
	
	binds_arg = g_list_length (args) / 2;

	paramTypes = g_malloc0 ( sizeof(Oid) * binds_arg );
	paramValues = g_malloc0 ( sizeof (char *) * binds_arg );
	paramLengths = g_malloc0 ( sizeof(int) * binds_arg );
	paramFormats = g_malloc0 ( sizeof(int) * binds_arg );
	n = 0;

	GSQL_DEBUG ( "Executing [%s]...", cursor->sql );
	while (vlist) {
		vtype = (GType) vlist->data;
		vlist = g_list_next (vlist);
		if (vlist->data == NULL)
			is_null = 1;
		else 
			is_null = 0;
		switch (vtype) {
			case G_TYPE_STRING:
			case G_TYPE_POINTER:
				paramTypes[n] = VARCHAROID;
				paramValues[n] = (char *) vlist->data;
				paramLengths[n] = g_utf8_strlen((gchar *) 
								vlist->data,
								1048576);
				paramFormats[n] = 0;
				break;
	
			case G_TYPE_INT:
			case G_TYPE_UINT:
				paramTypes[n] = INT4OID;
				paramValues[n] = (char *) &vlist->data;
				paramLengths[n] = 0;
				paramFormats[n] = 0;
				break;
				
			case G_TYPE_UINT64:
			case G_TYPE_INT64:
				paramTypes[n] = INT8OID;
				paramValues[n] = (char *) &vlist->data;
				paramLengths[n] = 0;
				paramFormats[n] = 0;
				break;
	
			case G_TYPE_DOUBLE:
				paramTypes[n] = FLOAT4OID;
				paramValues[n] = (char *) &vlist->data;
				paramLengths[n] = 0;
				paramFormats[n] = 0;
				break;
		}

		//GSQL_DEBUG ("Parms [%d] = [%s]", n, paramValues[n]);
		vlist = g_list_next (vlist);
		n++;
	}

	if (! e_session->pgconn ) {
		GSQL_DEBUG ("BIND: pgconn empty!");
	}

	if ( PQstatus(e_session->pgconn) != CONNECTION_OK ) {
		GSQL_DEBUG("BIND: lost connection!");
	}

	e_cursor->result = PQexecParams(e_session->pgconn, cursor->sql,
					binds_arg, paramTypes, paramValues,
					paramLengths, paramFormats, 0);

	if ( ! e_cursor->result ) {
		g_sprintf ( error_str, "Error occured: %s", 
			    pgsql_session_get_error(cursor->session) );
		gsql_message_add (workspace, GSQL_MESSAGE_ERROR, error_str);
		g_free (paramTypes);
		g_free (paramValues);
		g_free (paramLengths);
		g_free (paramFormats);
    
		return GSQL_CURSOR_STATE_ERROR;
	}


	pgsql_cursor_statement_detect (cursor);
  
	g_free (paramTypes);
	g_free (paramValues);
	g_free (paramLengths);
	g_free (paramFormats);
  
	n_fields =  PQnfields (e_cursor->result);

	if (n_fields == 0)
		return GSQL_CURSOR_STATE_OPEN;
  
	for (n = 0; n < n_fields; n++) {
		// TODO: free this in on_variable_delete
		field = g_malloc0 ( sizeof(PGSQL_FIELD) );
		field->name = PQfname(e_cursor->result, n);
		field->type = PQftype(e_cursor->result, n);
		field->size = PQfsize(e_cursor->result, n);

		var = gsql_variable_new ();
		pgsql_variable_init (var, field);
		cursor->var_list = g_list_append (cursor->var_list, var);
	}

	return GSQL_CURSOR_STATE_OPEN;
}