/* * call-seq: * res.ftablecol( column_number ) -> Fixnum * * Returns the column number (within its table) of the table from * which the column _column_number_ is made up. * * Raises ArgumentError if _column_number_ is out of range or if * the column number from its table is undefined for that column. */ static VALUE pgresult_ftablecol(VALUE self, VALUE column_number) { int col_number = NUM2INT(column_number); PGresult *pgresult = pgresult_get(self); int n; if( col_number < 0 || col_number >= PQnfields(pgresult)) rb_raise(rb_eArgError,"Invalid column index: %d", col_number); n = PQftablecol(pgresult, col_number); return INT2FIX(n); }
/* * call-seq: * conn.select_value( query, *bind_values) * * Return the first value of the first row of the query results. * Equivalent to conn.query( query, *bind_values).first.first */ VALUE pgconn_select_value( int argc, VALUE *argv, VALUE self) { VALUE cmd, par; VALUE res; struct pgresult_data *r; pg_parse_parameters( argc, argv, &cmd, &par); res = pg_statement_exec( self, cmd, par); Data_Get_Struct( res, struct pgresult_data, r); return PQntuples( r->res) > 0 && PQnfields( r->res) > 0 ? pg_fetchresult( r, 0, 0) : Qnil; }
/* * StoreQueryTuple: assuming query result is OK, save data into variables * * Returns true if successful, false otherwise. */ static bool StoreQueryTuple(const PGresult *result) { bool success = true; if (PQntuples(result) < 1) { psql_error("no rows returned for \\gset\n"); success = false; } else if (PQntuples(result) > 1) { psql_error("more than one row returned for \\gset\n"); success = false; } else { int i; for (i = 0; i < PQnfields(result); i++) { char *colname = PQfname(result, i); char *varname; char *value; /* concate prefix and column name */ varname = psprintf("%s%s", pset.gset_prefix, colname); if (!PQgetisnull(result, 0, i)) value = PQgetvalue(result, 0, i); else { /* for NULL value, unset rather than set the variable */ value = NULL; } if (!SetVariable(pset.vars, varname, value)) { psql_error("could not set variable \"%s\"\n", varname); free(varname); success = false; break; } free(varname); } } return success; }
CRow CResult::operator[](int i){ if( i >= PQntuples(m_cResult) ){ PQclear(m_cResult); throw CExceptionConnection("Nao existe essa linha!"); } else{ CRow row(i); for( int n = 0; n < PQnfields(m_cResult); n++ ){ row.add( PQfname(m_cResult, n), PQgetvalue(m_cResult, i, n) ); } return row; } return CRow(0); }
bool GetRow(SQLEntries& result) { if (currentrow >= PQntuples(res)) return false; int ncols = PQnfields(res); for(int i = 0; i < ncols; i++) { result.push_back(GetValue(currentrow, i)); } currentrow++; return true; }
static awk_value_t * do_pg_nfields(int nargs, awk_value_t *result) { PGresult *res; if (do_lint && (nargs > 1)) lintwarn(ext_id, _("pg_nfields: called with too many arguments")); if (!(res = find_handle(results, 0))) { set_ERRNO(_("pg_nfields called with unknown result handle")); RET_NUM(-1); } RET_NUM(PQnfields(res)); }
/* * call-seq: * res.fmod( column_number ) * * Returns the type modifier associated with column _column_number_. See * the #ftype method for an example of how to use this. * * Raises an ArgumentError if _column_number_ is out of range. */ static VALUE pgresult_fmod(VALUE self, VALUE column_number) { PGresult *result = pgresult_get(self); int fnumber = NUM2INT(column_number); int modifier; if (fnumber < 0 || fnumber >= PQnfields(result)) { rb_raise(rb_eArgError, "Column number is out of range: %d", fnumber); } modifier = PQfmod(result,fnumber); return INT2NUM(modifier); }
/* * Get a file list. */ void libpqProcessFileList(void) { PGresult *res; const char *sql; int i; sql = "-- Create a recursive directory listing of the whole data directory\n" "with recursive files (path, size, isdir) as (\n" " select filename as path, size, isdir\n" " from (select pg_ls_dir('.') as filename) as filenames,\n" " pg_stat_file(filename) as this\n" " union all\n" " select parent.path || '/' || filename, this.size, this.isdir\n" " from files as parent,\n" " pg_ls_dir(parent.path) as filename,\n" " pg_stat_file(parent.path || '/' || filename) as this\n" " where parent.isdir = 't'\n" ")\n" "-- Using the cte, fetch all files in chunks.\n" "select path, size, isdir from files\n"; res = PQexec(conn, sql); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "unexpected result while fetching file list: %s\n", PQresultErrorMessage(res)); exit(1); } /* sanity check the result set */ if (!(PQnfields(res) == 3)) { fprintf(stderr, "unexpected result set while fetching file list\n"); exit(1); } /* Read result to local variables */ for (i = 0; i < PQntuples(res); i++) { char *path = PQgetvalue(res, i, 0); int filesize = atoi(PQgetvalue(res, i, 1)); bool isdir = (strcmp(PQgetvalue(res, i, 2), "t") == 0); process_remote_file(path, filesize, isdir); } }
char *pw_pgsql_getquery(PGconn * const id_sql_server, const char * const orig_query, const char * const account, const char * const ip, const char * const port, const char * const peer_ip, const char * const decimal_ip) { PGresult *qresult = NULL; size_t length; char *answer = NULL; char query[PGSQL_MAX_REQUEST_LENGTH]; if (orig_query == NULL || *orig_query == 0) { rprintf(FLOG,"ERR1\n"); goto bye; } if (sqlsubst(orig_query, query, sizeof query, account, ip, port, peer_ip, decimal_ip) == NULL) { rprintf(FLOG,"ERR2\n"); goto bye; } if ((qresult = PQexec(id_sql_server, query)) == NULL) { //logfile(LOG_WARNING, MSG_SQL_WRONG_PARMS " : [%s]", query); rprintf(FLOG,"MSG_SQL_WRONG_PARMS : [%s]\n", query); goto bye; } if (PQresultStatus(qresult) != PGRES_TUPLES_OK || PQnfields(qresult) != 1 || PQntuples(qresult) != 1 || PQgetisnull(qresult, 0, 0)) { rprintf(FLOG,"ERR Multiples\n"); goto bye; } if ((length = (size_t) PQgetlength(qresult, 0, 0) + (size_t) 1U) <= (size_t) 1U || (answer = malloc(length)) == NULL) { rprintf(FLOG,"ERR4\n"); goto bye; } strncpy(answer, PQgetvalue(qresult, 0, 0), length - (size_t) 1U); answer[length - (size_t) 1U] = 0; bye: if (qresult != NULL) { PQclear(qresult); } return answer; }
QueryResult* DatabasePostgre::Query(const char *sql) { if (!mPGconn) return 0; uint64 rowCount = 0; uint32 fieldCount = 0; // guarded block for thread-safe request ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex); #ifdef MANGOS_DEBUG uint32 _s = getMSTime(); #endif // Send the query PGresult * result = PQexec(mPGconn, sql); if (!result ) { return NULL; } if (PQresultStatus(result) != PGRES_TUPLES_OK) { sLog.outErrorDb( "SQL : %s", sql ); sLog.outErrorDb( "SQL %s", PQerrorMessage(mPGconn)); PQclear(result); return NULL; } else { #ifdef MANGOS_DEBUG sLog.outDebug("[%u ms] SQL: %s", getMSTime() - _s, sql ); #endif } rowCount = PQntuples(result); fieldCount = PQnfields(result); // end guarded block if (!rowCount) { PQclear(result); return NULL; } QueryResultPostgre * queryResult = new QueryResultPostgre(result, rowCount, fieldCount); queryResult->NextRow(); return queryResult; }
int be_pg_getuser(void *handle, const char *username, const char *password, char **phash, const char *clientid) { struct pg_backend *conf = (struct pg_backend *)handle; char *value = NULL, *v = NULL; long nrows; PGresult *res = NULL; _log(LOG_DEBUG, "GETTING USERS: %s", username); if (!conf || !conf->userquery || !username || !*username) return BACKEND_DEFER; const char *values[1] = {username}; int lengths[1] = {strlen(username)}; int binary[1] = {0}; res = PQexecParams(conf->conn, conf->userquery, 1, NULL, values, lengths, binary, 0); if (PQresultStatus(res) != PGRES_TUPLES_OK) { _log(LOG_DEBUG, "%s\n", PQresultErrorMessage(res)); if(PQstatus(conf->conn) == CONNECTION_BAD){ _log(LOG_NOTICE, "Noticed a postgres connection loss. Trying to reconnect ...\n"); //try to reinitiate the database connection PQreset(conf->conn); } goto out; } if ((nrows = PQntuples(res)) != 1) { //DEBUG fprintf(stderr, "rowcount = %ld; not ok\n", nrows); goto out; } if (PQnfields(res) != 1) { //DEBUG fprintf(stderr, "numfields not ok\n"); goto out; } if ((v = PQgetvalue(res, 0, 0)) == NULL) { goto out; } value = (v) ? strdup(v) : NULL; out: PQclear(res); *phash = value; return BACKEND_DEFER; }
void show_column_info(PGresult* result) { int num_columns=0; int i; if(!result) return; num_columns=PQnfields(result); printf("%d columns in the result set\n",num_columns); for(i=0;i<num_columns;i++) printf("Field: %d,Name: %s,Internal size: %d\n", i, PQfname(result,i), PQfsize(result,i)); }
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; }
const HashMap<String, String> *DatabaseQueryResult::FetchRow() { const uint32 nRow = PQntuples(m_pPostgreSQLResult); if (m_nCurrentRow >= nRow) return nullptr; // Error! const uint32 nColumn = PQnfields(m_pPostgreSQLResult); m_mapRow.Clear(); for (uint32 i=0; i<nColumn; i++) m_mapRow.Add(PQfname(m_pPostgreSQLResult, i), PQgetvalue(m_pPostgreSQLResult, m_nCurrentRow, i)); m_nCurrentRow++; // Return a pointer to the row map return &m_mapRow; }
ResultadoConsulta* PG::select(const char* query) { ResultadoConsulta *resultado = new ResultadoConsulta(); PGresult *res = PQexec(conn,query); for (int i=0;i<PQntuples(res);i++) { std::vector<const char*> unVector; for(int j=0;j<PQnfields(res);j++) { unVector.push_back(PQgetvalue(res, i, j)); } resultado->push_back(unVector); } return resultado; }
/* * call-seq: * res.fname( index ) -> String * * Returns the name of the column corresponding to _index_. */ static VALUE pgresult_fname(VALUE self, VALUE index) { VALUE fname; PGresult *result; int i = NUM2INT(index); result = pgresult_get(self); if (i < 0 || i >= PQnfields(result)) { rb_raise(rb_eArgError,"invalid field number %d", i); } fname = rb_tainted_str_new2(PQfname(result, i)); ASSOCIATE_INDEX(fname, self); return fname; }
virtual uint query( const char * statement ) { _clearResult(); if (this->conn == 0) return _error(0,0); res = PQexec(this->conn, statement); if (this->res == 0) return _error(0,0); this->ncols = PQnfields(this->res); this->nrows = PQntuples(this->res); return 1; }
char *be_pg_getuser(void *handle, const char *username, const char *password, int *authenticated) { struct pg_backend *conf = (struct pg_backend *)handle; char *value = NULL, *v = NULL; long nrows; PGresult *res = NULL; _log(LOG_DEBUG, "GETTING USERS: %s", username ); if (!conf || !conf->userquery || !username || !*username) return (NULL); const char *values[1] = {username}; int lengths[1] = {strlen(username)}; int binary[1] = {0}; res = PQexecParams(conf->conn, conf->userquery, 1, NULL, values, lengths, binary, 0); if ( PQresultStatus(res) != PGRES_TUPLES_OK ) { _log(LOG_DEBUG, "%s\n", PQresultErrorMessage(res)); goto out; } if ((nrows = PQntuples(res)) != 1) { // DEBUG fprintf(stderr, "rowcount = %ld; not ok\n", nrows); goto out; } if (PQnfields(res) != 1) { // DEBUG fprintf(stderr, "numfields not ok\n"); goto out; } if ((v = PQgetvalue(res,0,0)) == NULL) { goto out; } value = (v) ? strdup(v) : NULL; out: PQclear(res); return (value); }
/* * call-seq: * res.fields() -> Array * * Returns an array of Strings representing the names of the fields in the result. */ static VALUE pgresult_fields(VALUE self) { PGresult *result = pgresult_get( self ); int n = PQnfields( result ); VALUE fields = rb_ary_new2( n ); int i; for ( i = 0; i < n; i++ ) { VALUE val = rb_tainted_str_new2(PQfname(result, i)); ASSOCIATE_INDEX(val, self); rb_ary_store( fields, i, val ); } return fields; }
void printResults(PGresult *res) { /* first, print out the attribute names */ int nFields = PQnfields(res); for (int i = 0; i < nFields; i++) printf("%-15s", PQfname(res, i)); printf("\n\n"); /* next, print out the rows */ for (int i = 0; i < PQntuples(res); i++) { for (int j = 0; j < nFields; j++) printf("%-15s", PQgetvalue(res, i, j)); printf("\n"); } }
/* * call-seq: * res.getlength( tup_num, field_num ) -> Fixnum * * Returns the (String) length of the field in bytes. * * Equivalent to <tt>res.value(<i>tup_num</i>,<i>field_num</i>).length</tt>. */ static VALUE pgresult_getlength(VALUE self, VALUE tup_num, VALUE field_num) { PGresult *result; int i = NUM2INT(tup_num); int j = NUM2INT(field_num); result = pgresult_get(self); if (i < 0 || i >= PQntuples(result)) { rb_raise(rb_eArgError,"invalid tuple number %d", i); } if (j < 0 || j >= PQnfields(result)) { rb_raise(rb_eArgError,"invalid field number %d", j); } return INT2FIX(PQgetlength(result, i, j)); }
// 'schema' as in DB's structure, not as in Postgres namespace static bool verifyTheSchema(PGconn * const conn, PGresult * const result) { BOOST_ASSERT( NULL != conn ); BOOST_ASSERT( NULL != result ); const int numCols = PQnfields(result); bool allOk = false; if ( EXPECTED_NUM_COLS == numCols ) { std::cout << "As expected, we have " EXPECTED_NUM_COLS_STR " columns\n"; allOk = checkColumnsTypes(result,numCols) && checkColumnsNames(result); } else { std::cerr << "Incorrect number of columns in table. Expected " EXPECTED_NUM_COLS_STR " but found " << numCols << '\n'; } return allOk; }
/** * @brief Do a key-value style select on a database table. * * This function does a key lookup on a database table that is set up * in key-value style. The table can have more than two columns, but * this function SELECT's two of them and returns the value of the * value column. It checks to make sure that the key returned is the * one requested, then returns its corresponding value. * * This function makes a lot of assumptions about the database and * the table: * * #- the database exists and is open * #- the table exists in the database * #- there is a column named key_column in the table * #- there is a column named value_column in the table * * The function does not check for any of these conditions, but just * assumes they are true. Be advised. * * @param database the database to look up in. * @param table the name of the table to look up in. * @param key_column the name of the column holding the key strings. * @param value_column the name of the column holding the value strings. * @param key the key string to look up (i.e. WHERE key_column='key'). * * @return the string value corresponding to the given key, or NULL * if an error occurred of if the key was not present in the table. */ char* psql_get_key_value (Database *database, const char *table, const char *key_column, const char *value_column, const char *key) { if (database == NULL || table == NULL || key_column == NULL || value_column == NULL || key == NULL) return NULL; PGresult *res; PsqlDB *psqldb = (PsqlDB*) database->handle; MString *stmt = mstring_create(); mstring_sprintf (stmt, "SELECT %s FROM %s WHERE %s='%s';", value_column, table, key_column, key); res = PQexec (psqldb->conn, mstring_buf (stmt)); if (PQresultStatus(res) != PGRES_TUPLES_OK) { logerror("psql:%s: Error trying to get %s[%s]; (%s).\n", database->name, table, key, PQerrorMessage(psqldb->conn)); goto fail_exit; } if (PQntuples (res) == 0) goto fail_exit; if (PQnfields (res) < 1) goto fail_exit; if (PQntuples (res) > 1) logwarn("psql:%s: Key-value lookup for key '%s' in %s(%s, %s) returned more than one possible key.\n", database->name, key, table, key_column, value_column); char *value = NULL; value = PQgetvalue (res, 0, 0); if (value != NULL) value = xstrndup (value, strlen (value)); PQclear (res); mstring_delete (stmt); return value; fail_exit: PQclear (res); mstring_delete (stmt); return NULL; }
int execute_order_status(struct db_context_t *dbc, struct order_status_t *data) { PGresult *res; char stmt[512]; int nFields; int i, j; /* Start a transaction block. */ res = PQexec(dbc->conn, "BEGIN"); if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) { LOG_ERROR_MESSAGE("%s", PQerrorMessage(dbc->conn)); PQclear(res); return ERROR; } PQclear(res); /* Create the query and execute it. */ sprintf(stmt, "SELECT * FROM order_status(%d, %d, %d, '%s')", data->c_id, data->c_w_id, data->c_d_id, data->c_last); res = PQexec(dbc->conn, stmt); if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK)) { LOG_ERROR_MESSAGE("%s", PQerrorMessage(dbc->conn)); PQclear(res); return ERROR; } /* first, print out the attribute names */ nFields = PQnfields(res); for (i = 0; i < nFields; i++) { char* tmp = PQfname(res, i); if(g_debug) printf("%-15s", tmp); } if(g_debug) printf("\n\n"); /* next, print out the rows */ for (i = 0; i < PQntuples(res); i++) { for (j = 0; j < nFields; j++) { char* tmp = PQgetvalue(res, i, j); if(g_debug) printf("%-15s", tmp); } if(g_debug) printf("\n"); } PQclear(res); return OK; }
bool PostgreSQLConnection::_PostgreStoreResult( const char* sql, ResultInfo* outResInfo ) { PGresult* outResult = PQgetResult(_pgConn); if (!outResult) return false; ExecStatusType resStatus = PQresultStatus(outResult); int outRowCount = 0; int outFieldCount = 0; if (resStatus == PGRES_TUPLES_OK) //has resultset { outRowCount = PQntuples(outResult); outFieldCount = PQnfields(outResult); } else if (resStatus == PGRES_COMMAND_OK) //rows affected { const char* numTuples = PQcmdTuples(outResult); if (strlen(numTuples) > 0) outRowCount = atoi(numTuples); //don't need it anymore PQclear(outResult); outResult = nullptr; } else //errored { PQclear(outResult); outResult = nullptr; bool connLost = _ConnectionLost(); throw SqlException(resStatus,lastErrorDescr(outResult),"PostgreStoreResult",connLost,connLost,sql); } if (outResInfo != nullptr) { outResInfo->pgRes = outResult; outResInfo->numFields = outFieldCount; outResInfo->numRows = outRowCount; } else if (outResult != nullptr) { PQclear(outResult); outResult = nullptr; } return true; }
static void CfNewQueryPostgresqlDb(CfdbConn *c, const char *query) { DbPostgresqlConn *pc = c->data; pc->res = PQexec(pc->conn, query); if (PQresultStatus(pc->res) != PGRES_COMMAND_OK && PQresultStatus(pc->res) != PGRES_TUPLES_OK) { CfOut(cf_inform, "", "PostgreSQL query failed: %s, %s\n", query, PQerrorMessage(pc->conn)); } else { c->result = true; c->maxcolumns = PQnfields(pc->res); c->maxrows = PQntuples(pc->res); } }
PGSQLResult(PGresult *res, string query, void *obj) : SQLResult(query,obj) { int i,j; for ( j = 0; j < PQntuples(res); j++ ) { map<string,string> foo; for ( i=0;i<PQnfields(res);i++ ) { foo[PQfname(res,i)] = PQgetvalue(res, j, i); // printf(" adding %s %s\n",PQfname(res,i), PQgetvalue(res, j, i)); } m_Result.push_back(foo); } }
/* ** Create a new Cursor object and push it on top of the stack. */ static int create_cursor (lua_State *L, int conn, PGresult *result) { cur_data *cur = (cur_data *)lua_newuserdata(L, sizeof(cur_data)); luasql_setmeta (L, LUASQL_CURSOR_PG); /* fill in structure */ cur->closed = 0; cur->conn = LUA_NOREF; cur->numcols = PQnfields(result); cur->colnames = LUA_NOREF; cur->coltypes = LUA_NOREF; cur->curr_tuple = 0; cur->pg_res = result; lua_pushvalue (L, conn); cur->conn = luaL_ref (L, LUA_REGISTRYINDEX); return 1; }
static void CfNewQueryPostgresqlDb(CfdbConn *c, const char *query) { DbPostgresqlConn *pc = c->data; pc->res = PQexec(pc->conn, query); if (PQresultStatus(pc->res) != PGRES_COMMAND_OK && PQresultStatus(pc->res) != PGRES_TUPLES_OK) { Log(LOG_LEVEL_INFO, "PostgreSQL query '%s' failed. (PQExec: %s)", query, PQerrorMessage(pc->conn)); } else { c->result = true; c->maxcolumns = PQnfields(pc->res); c->maxrows = PQntuples(pc->res); } }
void preload_accounts(const char *conditions) { long acct_count, field_count, field_idx; const char **fields; PGresult *res; res = sql_query ("select idnum, name, password, email, date_part('epoch', creation_time) as creation_time, creation_addr, date_part('epoch', login_time) as login_time, login_addr, date_part('epoch', entry_time) as entry_time, ansi_level, compact_level, term_height, term_width, banned, reputation, quest_points, quest_banned, bank_past, bank_future, metric_units, trust from accounts where %s", conditions); acct_count = PQntuples(res); if (acct_count < 1) return; // Get field names and put them in an array field_count = PQnfields(res); fields = (const char **)malloc(sizeof(const char *) * field_count); for (field_idx = 0; field_idx < field_count; field_idx++) fields[field_idx] = PQfname(res, field_idx); int acct_idx; for (acct_idx = 0; acct_idx < acct_count; acct_idx++) { // Make sure we don't reload one that's already in the cache long idnum = atol(PQgetvalue(res, acct_idx, 0)); if (g_hash_table_lookup(account_cache, GINT_TO_POINTER(idnum))) continue; // Create a new account and load it up struct account *new_acct; CREATE(new_acct, struct account, 1); for (field_idx = 0; field_idx < field_count; field_idx++) account_set(new_acct, fields[field_idx], PQgetvalue(res, acct_idx, field_idx)); load_players(new_acct); load_trusted(new_acct); g_hash_table_insert(account_cache, GINT_TO_POINTER(idnum), new_acct); slog("Account %ld preloaded from database", idnum); } free(fields); }