SWITCH_DECLARE(switch_pgsql_status_t) switch_pgsql_finish_results_real(const char* file, const char* func, int line, switch_pgsql_handle_t *handle) { #ifdef SWITCH_HAVE_PGSQL switch_pgsql_result_t *res = NULL; switch_pgsql_status_t final_status = SWITCH_PGSQL_SUCCESS; int done = 0; do { switch_pgsql_next_result(handle, &res); if (res && res->err && !switch_stristr("already exists", res->err) && !switch_stristr("duplicate key name", res->err)) { switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, SWITCH_LOG_ERROR, "Error executing query:\n%s\n", res->err); final_status = SWITCH_PGSQL_FAIL; } if (!res) { done = 1; } else if (res->result) { char *affected_rows = PQcmdTuples(res->result); if (!zstr(affected_rows)) { handle->affected_rows = atoi(affected_rows); } } switch_pgsql_free_result(&res); } while (!done); return final_status; #else return SWITCH_PGSQL_FAIL; #endif }
/* * call-seq: * res.cmd_tuples() -> Fixnum * * Returns the number of tuples (rows) affected by the SQL command. * * If the SQL command that generated the PG::Result was not one of: * * +INSERT+ * * +UPDATE+ * * +DELETE+ * * +MOVE+ * * +FETCH+ * or if no tuples were affected, <tt>0</tt> is returned. */ static VALUE pgresult_cmd_tuples(VALUE self) { long n; n = strtol(PQcmdTuples(pgresult_get(self)),NULL, 10); return INT2NUM(n); }
static HB_ERRCODE pgsqlExecute( SQLDDCONNECTION * pConnection, PHB_ITEM pItem ) { PGconn * pConn = ( ( SDDCONN * ) pConnection->pSDDConn )->pConn; int iTuples; PGresult * pResult; ExecStatusType status; unsigned long ulAffectedRows; pResult = PQexec( pConn, hb_itemGetCPtr( pItem ) ); if( ! pResult ) { hb_rddsqlSetError( 1, PQerrorMessage( pConn ), hb_itemGetCPtr( pItem ), NULL, 0 ); return HB_FAILURE; } status = PQresultStatus( pResult ); if( status != PGRES_TUPLES_OK && status != PGRES_COMMAND_OK ) { hb_rddsqlSetError( status, PQresultErrorMessage( pResult ), hb_itemGetCPtr( pItem ), NULL, 0 ); return HB_FAILURE; } iTuples = PQntuples( pResult ); if( iTuples > 0 ) ulAffectedRows = ( unsigned long ) iTuples; else ulAffectedRows = ( unsigned long ) atol( PQcmdTuples( pResult ) ); hb_rddsqlSetError( 0, NULL, hb_itemGetCPtr( pItem ), NULL, ulAffectedRows ); PQclear( pResult ); return HB_SUCCESS; }
void encode_result(ei_x_buff* x, PGresult* res, PGconn* conn) { int row, n_rows, col, n_cols; switch (PQresultStatus(res)) { case PGRES_TUPLES_OK: n_rows = PQntuples(res); n_cols = PQnfields(res); ei_x_encode_tuple_header(x, 2); encode_ok(x); ei_x_encode_list_header(x, n_rows+1); ei_x_encode_list_header(x, n_cols); for (col = 0; col < n_cols; ++col) { ei_x_encode_string(x, PQfname(res, col)); } ei_x_encode_empty_list(x); for (row = 0; row < n_rows; ++row) { ei_x_encode_list_header(x, n_cols); for (col = 0; col < n_cols; ++col) { ei_x_encode_string(x, PQgetvalue(res, row, col)); } ei_x_encode_empty_list(x); } ei_x_encode_empty_list(x); break; case PGRES_COMMAND_OK: ei_x_encode_tuple_header(x, 2); encode_ok(x); ei_x_encode_string(x, PQcmdTuples(res)); break; default: encode_error(x, conn); break; } }
/* ML type : pgresult_ -> int */ EXTERNML value pq_cmdtuples(value pgresval) { const char* s = PQcmdTuples(PGresult_val(pgresval)); if (s == NULL) failwith("pq_cmdtuples"); return Val_long(atoi(s)); }
unsigned long psMysqlConnection::Command(const char *sql,...) { psStopWatch timer; csString querystr; va_list args; va_start(args, sql); querystr.FormatV(sql, args); va_end(args); lastquery = querystr; timer.Start(); PGresult *res = PQexec(conn, querystr.GetData()); if(res && PQresultStatus(res) != PGRES_FATAL_ERROR) { if(timer.Stop() > 1000) { csString status; status.Format("SQL query %s, has taken %u time to process.\n", querystr.GetData(), timer.Stop()); if(logcsv) logcsv->Write(CSV_STATUS, status); } profs.AddSQLTime(querystr, timer.Stop()); lastRow = PQoidValue(res); const char *const RowsStr = PQcmdTuples(res); return (unsigned long) (RowsStr[0] ? atoi(RowsStr) : 0); } else { PQclear(res); return QUERY_FAILED; } }
PgSQLResult::PgSQLResult(PgSQLConnection* pConnection, PGresult * sqlResult) : KCSQLResultBase(pConnection) { m_sqlResult = sqlResult; if (m_sqlResult) { m_numRows = PQntuples(m_sqlResult); m_numFields = PQnfields(m_sqlResult); m_sqlRow = -1; for (int i = 0; i<m_numFields; ++i) { m_vName.push_back( PQfname(m_sqlResult, i) ); } m_vValue.resize(m_numFields); const char* pszResult = PQcmdTuples(sqlResult); if (pszResult) { m_affectRowCount = atoi(pszResult); } Seek(0); } else { m_sqlRow = -1; m_numRows = 0; m_numFields = 0; } }
static zend_long pgsql_handle_doer(pdo_dbh_t *dbh, const char *sql, zend_long sql_len) { pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data; PGresult *res; zend_long ret = 1; ExecStatusType qs; if (!(res = PQexec(H->server, sql))) { /* fatal error */ pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL); return -1; } qs = PQresultStatus(res); if (qs != PGRES_COMMAND_OK && qs != PGRES_TUPLES_OK) { pdo_pgsql_error(dbh, qs, pdo_pgsql_sqlstate(res)); PQclear(res); return -1; } H->pgoid = PQoidValue(res); if (qs == PGRES_COMMAND_OK) { ZEND_ATOL(ret, PQcmdTuples(res)); } else { ret = Z_L(0); } PQclear(res); return ret; }
void doSQL(PGconn *conn, char *command) { PGresult *result; printf("%s\n", command); result = PQexec(conn, command); printf("status is %s\n", PQresStatus(PQresultStatus(result))); printf("#rows affected %s\n", PQcmdTuples(result)); printf("result message: %s\n", PQresultErrorMessage(result)); switch(PQresultStatus(result)) { case PGRES_TUPLES_OK: { int r, n; int nrows = PQntuples(result); int nfields = PQnfields(result); printf("number of rows returned = %d\n", nrows); printf("number of fields returned = %d\n", nfields); for(r = 0; r < nrows; r++) { for(n = 0; n < nfields; n++) printf(" %s = %s(%d),", PQfname(result, n), PQgetvalue(result, r, n), PQgetlength(result, r, n)); printf("\n"); } } } PQclear(result); }
static int pgsql_update(void *theconn, const Octstr *sql, List *binds) { int rows; PGresult *res = NULL; PGconn *conn = (PGconn*) theconn; res = PQexec(conn, octstr_get_cstr(sql)); if (res == NULL) return -1; switch (PQresultStatus(res)) { case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: error(0, "PGSQL: %s", octstr_get_cstr(sql)); error(0, "PGSQL: %s", PQresultErrorMessage(res)); PQclear(res); return -1; default: /* for compiler please */ break; } rows = atoi(PQcmdTuples(res)); PQclear(res); return rows; }
int PG::operacion(const char* query){ PGresult *res = PQexec(conn,query); int x = atoi(PQcmdTuples(res)); // Para obtener errores : // char* error = PQresultErrorField(res,PG_DIAG_SQLSTATE); PQclear(res); return x; }
static awk_value_t * process_result(PGconn *conn, PGresult *res, awk_value_t *resp) { ExecStatusType rc; switch (rc = PQresultStatus(res)) { case PGRES_TUPLES_OK: { static unsigned long hnum = 0; char handle[64]; size_t sl; snprintf(handle, sizeof(handle), "TUPLES %d pgres%lu", PQntuples(res), hnum++); sl = strlen(handle); strhash_get(results, handle, sl, 1)->data = res; make_string_malloc(handle, sl, resp); } break; case PGRES_COMMAND_OK: case PGRES_EMPTY_QUERY: { char result[32]; int cnt; if (sscanf(PQcmdTuples(res), "%d", &cnt) != 1) cnt = 0; snprintf(result, sizeof(result), "OK %d", cnt); PQclear(res); make_string_malloc(result, strlen(result), resp); } break; case PGRES_COPY_IN: { char buf[100]; snprintf(buf, sizeof(buf), "COPY_IN %d %s", PQnfields(res), (PQbinaryTuples(res) ? "BINARY" : "TEXT")); make_string_malloc(buf, strlen(buf), resp); PQclear(res); } break; case PGRES_COPY_OUT: { char buf[100]; snprintf(buf, sizeof(buf), "COPY_OUT %d %s", PQnfields(res), (PQbinaryTuples(res) ? "BINARY" : "TEXT")); make_string_malloc(buf, strlen(buf), resp); PQclear(res); } break; default: /* error */ set_error(conn, rc, resp); set_ERRNO(PQresultErrorMessage(res)); PQclear(res); } return resp; }
int changed_tuples() const { std::string t = PQcmdTuples(res); if (t.empty()) throw Error::no_tuples("", conn.getName()); std::stringstream s; s << t; int r; s >> r; return r; }
long PgQuery::affectedRows () { long res = 0; char *str_rows = PQcmdTuples (_res); if (!str_rows || !*str_rows) return res; if (sscanf (str_rows, "%ld", &res) != 1) return 0; return res; }
size_t evsql_result_affected (const struct evsql_result *res) { switch (res->evsql->type) { case EVSQL_EVPQ: // XXX: errors? return strtol(PQcmdTuples(res->result.pq), NULL, 10); default: FATAL("res->evsql->type"); } }
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> uint64_t PostgreSQLDatabase::numberOfAffectedRows() { char *number = PQcmdTuples(_result); if ( number == NULL || *number == '\0' ) return (uint64_t)~0; uint64_t count; if ( sscanf(number, "%lud", &count) == 1 ) return count; return (uint64_t)~0; }
int ResultSet::getTupleCount(void) { //In case the result has some tuples if(!empty_result) //Returns the tuple count gathered after the SQL command return(PQntuples(sql_result)); else /* Returns the line amount that were affected by the SQL command (only for INSERT, DELETE, UPDATE) */ return(atoi(PQcmdTuples(sql_result))); }
virtual int Rows() { if(!cols && !rows) { return atoi(PQcmdTuples(res)); } else { return rows; } }
VALUE do_postgres_cCommand_execute_non_query(int argc, VALUE *argv, VALUE self) { VALUE connection = rb_iv_get(self, "@connection"); VALUE postgres_connection = rb_iv_get(connection, "@connection"); if (postgres_connection == Qnil) { rb_raise(eDO_ConnectionError, "This connection has already been closed."); } VALUE query = data_objects_build_query_from_args(self, argc, argv); PGconn *db = DATA_PTR(postgres_connection); PGresult *response; int status; response = do_postgres_cCommand_execute(self, connection, db, query); status = PQresultStatus(response); VALUE affected_rows = Qnil; VALUE insert_id = Qnil; if (status == PGRES_TUPLES_OK) { if (PQgetlength(response, 0, 0) == 0) { insert_id = Qnil; } else { insert_id = INT2NUM(atoi(PQgetvalue(response, 0, 0))); } affected_rows = INT2NUM(atoi(PQcmdTuples(response))); } else if (status == PGRES_COMMAND_OK) { insert_id = Qnil; affected_rows = INT2NUM(atoi(PQcmdTuples(response))); } else { do_postgres_raise_error(self, response, query); } PQclear(response); return rb_funcall(cDO_PostgresResult, DO_ID_NEW, 3, self, affected_rows, insert_id); }
/************************************************************************* * * Function: sql_query * * Purpose: Issue a query to the database * *************************************************************************/ static int sql_query(SQLSOCK * sqlsocket, SQL_CONFIG *config, char *querystr) { rlm_sql_postgres_sock *pg_sock = sqlsocket->conn; if (config->sqltrace) radlog(L_DBG,"rlm_sql_postgresql: query:\n%s", querystr); if (pg_sock->conn == NULL) { radlog(L_ERR, "rlm_sql_postgresql: Socket not connected"); return SQL_DOWN; } pg_sock->result = PQexec(pg_sock->conn, querystr); /* Returns a result pointer or possibly a NULL pointer. * A non-NULL pointer will generally be returned except in * out-of-memory conditions or serious errors such as inability * to send the command to the backend. If a NULL is returned, * it should be treated like a PGRES_FATAL_ERROR result. * Use PQerrorMessage to get more information about the error. */ if (!pg_sock->result) { radlog(L_ERR, "rlm_sql_postgresql: PostgreSQL Query failed Error: %s", PQerrorMessage(pg_sock->conn)); return SQL_DOWN; } else { ExecStatusType status = PQresultStatus(pg_sock->result); radlog(L_DBG, "rlm_sql_postgresql: Status: %s", PQresStatus(status)); radlog(L_DBG, "rlm_sql_postgresql: affected rows = %s", PQcmdTuples(pg_sock->result)); if (!status_is_ok(status)) return sql_check_error(status); if (strncasecmp("select", querystr, 6) != 0) { /* store the number of affected rows because the sql module * calls finish_query before it retrieves the number of affected * rows from the driver */ pg_sock->affected_rows = affected_rows(pg_sock->result); return 0; } else { if ((sql_store_result(sqlsocket, config) == 0) && (sql_num_fields(sqlsocket, config) >= 0)) return 0; else return -1; } } }
static VALUE cCommand_execute_non_query(int argc, VALUE *argv[], VALUE self) { 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; int status; VALUE affected_rows = Qnil; VALUE insert_id = Qnil; VALUE query = build_query_from_args(self, argc, argv); response = cCommand_execute(self, db, query); status = PQresultStatus(response); if ( status == PGRES_TUPLES_OK ) { insert_id = INT2NUM(atoi(PQgetvalue(response, 0, 0))); affected_rows = INT2NUM(atoi(PQcmdTuples(response))); } else if ( status == PGRES_COMMAND_OK ) { insert_id = Qnil; affected_rows = INT2NUM(atoi(PQcmdTuples(response))); } else { raise_error(self, response, query); } PQclear(response); return rb_funcall(cResult, ID_NEW, 3, self, affected_rows, insert_id); }
virtual unsigned long long affected() { if(res_) { char const *s=PQcmdTuples(res_); if(!s || !*s) return 0; unsigned long long rows = 0; fmt_.str(s); fmt_.clear(); fmt_ >> rows; fmt_.str(std::string()); fmt_.clear(); return rows; } return 0; }
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; }
int PgSQLQuery::execute(const std::string& query) { if (!conn_) { LOG_FATAL("event=[pgsqlquery] type=[execute] status=[invalid]"); return Status::NOHANLDER; } if (result_) { PQclear(result_); result_ = nullptr; } bool isFirst = true; do { PGconn* pgsql = conn_->handler(); if (!pgsql) { LOG_FATAL("event=[pgsqlquery] type=[execute] status=[invalid]"); return Status::NOHANLDER; } // exec sql query result_ = PQexec(pgsql, query.c_str()); if (PQresultStatus(result_) == PGRES_FATAL_ERROR) { LOG_FATAL("PQexec error:%s", PQerrorMessage(pgsql)); if (isFirst) { isFirst = false; if (PgSQLConn::Status::OK != conn_->connect()) { LOG_FATAL("reconnect pgsql failed:%s.", PQerrorMessage(pgsql)); return Status::FAILED; } continue; } return Status::FAILED; } // for command:CREATE,UPDATE,DELETE SQL etc. if (PQresultStatus(result_) == PGRES_COMMAND_OK) { LOG_INFO("%s", PQcmdTuples(result_)); } // for command:SELECT SQL. if (PQresultStatus(result_) == PGRES_TUPLES_OK) { tuplesOffset_ = 0; tuples_ = PQntuples(result_); } break; } while (true); return Status::OK; }
int pg_command(ClipMachine* mp,SQLSTMT* stmt,ClipVar* ap){ int status; const char* tups; pg_bindpars((PG_STMT*)stmt,ap); ((PG_STMT*)stmt)->res = PQexec(((PG_STMT*)stmt)->conn->conn, ((PG_STMT*)stmt)->sql); status = PQresultStatus(((PG_STMT*)stmt)->res); if(status != PGRES_COMMAND_OK){ _clip_trap_err(mp,0,0,0,subsys,ER_BADSTATEMENT, PQresultErrorMessage(((PG_STMT*)stmt)->res)); return -1; } tups = PQcmdTuples(((PG_STMT*)stmt)->res); return atoi(tups); }
void cmdev_edit_game(const struct lh_kv_elem *params, const struct lh_kv_elem *cookies, struct lh_response* resp) { //parse param int err = 0; const char *gameid = lh_kv_string(params, "gameid", &err); const char *gamename = lh_kv_string(params, "gamename", &err); if (err) { return cm_send_error(resp, CMERR_PARAM); } //check auth cm::Session session; err = cm::find_session(cookies, session); if (err) { return cm_send_error(resp, CMERR_AUTH); } //update db PGconn *cmatchdb = cm::get_context()->cmatchdb; if (PQstatus(cmatchdb) != CONNECTION_OK) { return cm_send_error(resp, CMERR_DB); } const int VAR_NUMS = 3; const char *vars[VAR_NUMS] = { gamename, gameid, session.userid.c_str(), }; PGresult *res = PQexecParams(cmatchdb, "UPDATE game SET name=$1 WHERE id=$2 AND developer_id=$3;", VAR_NUMS, NULL, vars, NULL, NULL, 0); Autofree af_res_insert(res, (Freefunc)PQclear); if (PQresultStatus(res) != PGRES_COMMAND_OK){ return cm_send_error(resp, CMERR_DB); } const char *affected = PQcmdTuples(res); if (!affected || *affected == '0') { return cm_send_error(resp, CMERR_NOT_EXIST); } //send to client lh_append_body(resp, "{\"error\":0}"); }
/* ** Execute an SQL statement. ** Return a Cursor object if the statement is a query, otherwise ** return the number of tuples affected by the statement. */ static int conn_execute (lua_State *L) { conn_data *conn = getconnection (L); const char *statement = luaL_checkstring (L, 2); PGresult *res = PQexec(conn->pg_conn, statement); if (res && PQresultStatus(res)==PGRES_COMMAND_OK) { /* no tuples returned */ lua_pushnumber(L, atof(PQcmdTuples(res))); PQclear (res); return 1; } else if (res && PQresultStatus(res)==PGRES_TUPLES_OK) /* tuples returned */ return create_cursor (L, 1, res); else { /* error */ PQclear (res); return luasql_failmsg(L, "error executing statement. PostgreSQL: ", PQerrorMessage(conn->pg_conn)); } }
/* Buttons */ void button_create_clicked (GtkButton *button, gpointer user_data){ FZ_Create *field = user_data; if (!conn) if (connection() != 0){ g_print("Configure a Conexão do Sistema"); return; } gchar* SQL; SQL = g_strdup_printf(str_boot_create, gtk_entry_get_text(GTK_ENTRY(field->entry_db)) ); result = PQexec(conn, SQL ); g_free(SQL); if(!result) { g_print("Erro executando comando. "); } else { switch(PQresultStatus(result)) { case PGRES_EMPTY_QUERY: g_print("Nada aconteceu.\n"); break; case PGRES_TUPLES_OK: g_print("A query retornou %d linhas.\n", PQntuples(result)); break; case PGRES_FATAL_ERROR: g_print("Erro na Consulta: %s\n", PQresultErrorMessage(result)); break; case PGRES_COMMAND_OK: g_print("%s linhas afetadas.\n", PQcmdTuples(result)); break; default: g_print("Algum outro resultado ocorreu.\n"); break; } } }
/*Method to execute quick and fast sql statements like UPDATE and INSERT Inputs: query- string containing sql query qlength - length of query (for binary data). if 0 then assume null terminated. affectedrows - will recieve number of rows updated or inserted Output: False on error */ Bool DBConnection_POSTGRESQL::sqlExecute(char *p_query, DBString *p_arguments, int p_argument_count, unsigned int &r_affected_rows) { PGresult *t_postgres_result; t_postgres_result = ExecuteQuery(p_query, p_arguments, p_argument_count); if (t_postgres_result == NULL) return False; ExecStatusType t_status; t_status = PQresultStatus(t_postgres_result); Bool t_result; t_result = False; if (t_status == PGRES_COMMAND_OK) { t_result = True; char *t_affected_rows; t_affected_rows = PQcmdTuples(t_postgres_result); if (strcmp(t_affected_rows, "") == 0) r_affected_rows = 0; else r_affected_rows = atol(t_affected_rows); } if (t_status == PGRES_TUPLES_OK) { // This means the query was a select query. No rows would have been "affected" // so the result should be zero. t_result = True; r_affected_rows = 0; } // OK-2007-09-10 : Bug 5360, if the execution succeeded, we clear the error message, otherwise we set it. if (t_result) errorMessageSet(NULL); else errorMessageSet(PQerrorMessage(dbconn)); PQclear(t_postgres_result); return t_result; }
/* function to call for inserts or updates, returns # of rows affected */ int pgconn_update(PGConnection *conn, const char *query) { int rowsModified; PGresult *res; res = PQexec(conn->stream,query); if(res == NULL) THROW("SQLException", "%s", PQerrorMessage(conn->stream)); if(PQresultStatus(res) != PGRES_COMMAND_OK) THROW("SQLException", "%s", PQresultErrorMessage(res)); rowsModified = strtol(PQcmdTuples(res), NULL, 10); lastOid = PQoidValue(res); PQclear(res); return rowsModified; }