/* * call-seq: * res.error_message() -> String * * Returns the error message of the command as a string. */ static VALUE pgresult_error_message(VALUE self) { VALUE ret = rb_tainted_str_new2(PQresultErrorMessage(pgresult_get(self))); ASSOCIATE_INDEX(ret, self); 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 n = 0, r = 0; 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", PQfname(result, n),PQgetvalue(result,r,n)); printf("\n"); } } } PQclear(result); }
inline int sql_request(const char *format, ...) { va_list args; PGresult *res; if (format == NULL || *format == '\0') return 0; va_start(args, format); vsprintf(inbuf, format, args); va_end(args); priv_pgsql_adapt((char *)&inbuf); strcpy(last_request, inbuf); #ifdef MYSQL_DEBUG printf("Query: %s\n", inbuf); #endif res = PQexec(pgsql_handle, inbuf); if (PQresultStatus(res) == PGRES_COMMAND_OK) return 1; /* no data returned */ if (PQresultStatus(res) != PGRES_TUPLES_OK) { /* some error occured */ printf("SQLERR: Req: %s, Error: %s \n", last_request, PQresultErrorMessage(res)); PQclear(res); return 0; } if (pgsql_db_res) { PQclear(pgsql_db_res); pgsql_db_res = NULL; pgsql_db_row = 0; } pgsql_db_res = res; return 1; }
/* Reads the next result row from the snapshot query, parses and processes it. * Blocks until a new row is available, if necessary. */ int snapshot_poll(client_context_t context) { int err = 0; PGresult *res = PQgetResult(context->sql_conn); /* null result indicates that there are no more rows */ if (!res) { check(err, exec_sql(context, "COMMIT")); PQfinish(context->sql_conn); context->sql_conn = NULL; // Invoke the commit callback with xid==0 to indicate end of snapshot commit_txn_cb on_commit = context->repl.frame_reader->on_commit_txn; void *cb_context = context->repl.frame_reader->cb_context; if (on_commit) { check(err, on_commit(cb_context, context->repl.start_lsn, 0)); } return 0; } ExecStatusType status = PQresultStatus(res); if (status != PGRES_SINGLE_TUPLE && status != PGRES_TUPLES_OK) { client_error(context, "While reading snapshot: %s: %s", PQresStatus(PQresultStatus(res)), PQresultErrorMessage(res)); PQclear(res); return EIO; } int tuples = PQntuples(res); for (int tuple = 0; tuple < tuples; tuple++) { check(err, snapshot_tuple(context, res, tuple)); } PQclear(res); return err; }
void dlgDirectDbg::OnTargetComplete( wxCommandEvent &event ) { // Extract the result set handle from the event and log the status info PGresult *result = (PGresult *)event.GetClientData(); wxLogInfo( wxT( "OnTargetComplete() called\n" )); wxLogInfo( wxT( "%s\n" ), wxString(PQresStatus( PQresultStatus( result )), wxConvUTF8).c_str()); // If the query failed, write the error message to the status line, otherwise, copy the result set into the grid if(( PQresultStatus( result ) == PGRES_NONFATAL_ERROR ) || ( PQresultStatus( result ) == PGRES_FATAL_ERROR )) { wxString message( PQresultErrorMessage( result ), wxConvUTF8 ); message.Replace( wxT( "\n" ), wxT( " " )); m_parent->getStatusBar()->SetStatusText( message, 1 ); char *state = PQresultErrorField(result, PG_DIAG_SQLSTATE); // Don't bother telling the user that he aborted - he already knows! // Depending on the stage, m_conn might not be set all! so check for // that first if (m_conn) { if (state != NULL && strcmp(state, "57014")) wxLogError( wxT( "%s\n" ), wxString(PQerrorMessage(m_conn->getConnection()), wxConvUTF8).c_str()); else wxLogInfo( wxT( "%s\n" ), wxString(PQerrorMessage(m_conn->getConnection()), wxConvUTF8).c_str()); } } else { wxString message( PQcmdStatus( result ), wxConvUTF8 ); message.Replace( wxT( "\r" ), wxT( "" )); message.Replace( wxT( "\n" ), wxT( " " )); m_parent->getStatusBar()->SetStatusText( message, 1 ); // If this result set has any columns, add a result grid to the code window so // we can show the results to the user if( m_codeWindow && PQnfields( result )) { m_codeWindow->OnResultSet( result ); } } if (m_codeWindow) { m_codeWindow->m_targetComplete = true; m_codeWindow->disableTools( ); } // Do not show if aborted if ( m_codeWindow && m_codeWindow->m_targetAborted ) return; this->Show( true ); }
int execute_nonquery_statement(char* stmt) { int result = 0; char connect_string[MAX_STATEMENT]; snprintf(connect_string, MAX_STATEMENT, "hostaddr = '%s' port = '%s' dbname = '%s' user = '******' password = '******' connect_timeout = '10'", lg_psql.hostaddr, lg_psql.port, lg_psql.dbname, lg_psql.user, lg_psql.pw); PGconn* psql = PQconnectdb(connect_string); if (!psql) { msg(MSG_FATAL,"libpq error : PQconnectdb returned NULL.\n\n"); return result; } if (PQstatus(psql) != CONNECTION_OK) { msg(MSG_FATAL,"libpq error: PQstatus(psql) != CONNECTION_OK\n\n"); return result; } PGresult *res = PQexec(psql, stmt); if (PQresultStatus(res) != PGRES_COMMAND_OK) { msg(MSG_FATAL,"ERROR: %s",PQresultErrorMessage(res)); msg(MSG_FATAL,"while executing '%s'",stmt); result = 0; } else { result = 1; // success } PQfinish(psql); return result; }
bool PostgreDatabase::WaitExecute(const char* QueryString, ...) { if(QueryString == NULL) return false; va_list vlist; va_start(vlist, QueryString); mSearchMutex.acquire(); uint32 Connection = GetConnection(); InUseMarkers[Connection] = true; mSearchMutex.release(); vsprintf(QueryBuffer[Connection], QueryString, vlist); PGresult * res = SendQuery(Connection, QueryBuffer[Connection], false); if(res == 0) return false; InUseMarkers[Connection] = false; ExecStatusType result = PQresultStatus(res); bool passed = false; if(result == PGRES_TUPLES_OK || result == PGRES_COMMAND_OK) passed = true; else sLog.outError("Execute failed because of [%s]", PQresultErrorMessage(res)); // free up the memory PQclear(res); return passed; }
PgsqlReaderProvider::PgsqlReaderProvider(PgsqlConnectionProvider *connection, PgsqlCommandProvider *command) : connection(connection), command(command), closed(false), current_row(-1) { auto deleter = [](PGresult *ptr) {if (ptr) {PQclear(ptr);} }; std::unique_ptr<PGresult, decltype(deleter)> result_uniqueptr(command->exec_command(), deleter); result = result_uniqueptr.get(); switch (PQresultStatus(result)) { case PGRES_EMPTY_QUERY: throw Exception("Empty query"); case PGRES_COMMAND_OK: type = ResultType::EMPTY_RESULT; break; case PGRES_TUPLES_OK: type = ResultType::TUPLES_RESULT; break; case PGRES_NONFATAL_ERROR: throw Exception("Server gave an unknow answer"); case PGRES_FATAL_ERROR: throw Exception(PQerrorMessage(connection->db)); default: throw Exception(StringHelp::text_to_local8(PQresultErrorMessage(result))); } nb_rows = PQntuples(result); result_uniqueptr.release(); }
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; }
void EXE_SQL_CMD(const char* cmd){ PGresult* res = PQexec(conn,cmd); if(!res || PQresultStatus(res) != PGRES_COMMAND_OK){ fprintf(stderr, "SQL Error in cmd: %s\n", PQresultErrorMessage(res)); } PQclear(res); }
/* * Call pgpool_remote_start() function. */ static int exec_remote_start(PGconn *conn, BackendInfo *backend) { PGresult *result; char *hostname; int r; if (strlen(backend->backend_hostname) == 0 || *(backend->backend_hostname) == '/') hostname = "localhost"; else hostname = backend->backend_hostname; snprintf(recovery_command, sizeof(recovery_command), "SELECT pgpool_remote_start('%s', '%s')", hostname, backend->backend_data_directory); pool_debug("exec_remote_start: start pgpool_remote_start"); result = PQexec(conn, recovery_command); r = (PQresultStatus(result) != PGRES_TUPLES_OK); if (r != 0) pool_error("exec_remote_start: pgpool_remote_start failed: %s", PQresultErrorMessage(result)); PQclear(result); pool_debug("exec_remote_start: finish pgpool_remote_start"); return r; }
void DatabasePostgreSQL::UpdateLSAccountData(unsigned int id, string ip_address) { if(!db) { return; } /** * PostgreSQL doesn't have automatic reconnection option like mysql * but it's easy to check and reconnect */ if(PQstatus(db) != CONNECTION_OK) { PQreset(db); if(PQstatus(db) != CONNECTION_OK) { return; } } stringstream query(stringstream::in | stringstream::out); query << "UPDATE " << server.options.GetAccountTable() << " SET LastIPAddress = '"; query << ip_address; query << "', LastLoginDate = current_date where LoginServerID = "; query << id; PGresult *res = PQexec(db, query.str().c_str()); char *error = PQresultErrorMessage(res); if(strlen(error) > 0) { Log.Out(Logs::General, Logs::Error, "Database error in DatabasePostgreSQL::GetLoginDataFromAccountName(): %s", error); } PQclear(res); }
void doSQL(PGconn *conn, char *command){ PGresult *result; printf("%s\n", command); result = PQexec(conn, command); printf("Result message: %s\n", PQresultErrorMessage(result)); switch(PQresultStatus(result)) { case PGRES_TUPLES_OK:{ int n = 0, m = 0; int nrows = PQntuples(result); int nfields = PQnfields(result); for(m = 0; m < nrows; m++) { for(n = 0; n < nfields; n++) printf(" %s = %s", PQfname(result, n),PQgetvalue(result,m,n)); printf("\n"); } if(nrows == 0 || nfields == 0){ printf("Car does not exist in database!"); searchT = 0; } } } PQclear(result); }
bool PostgreSQLInterface::IsResultSuccessful(PGresult *result, bool rollbackOnFailure) { if (result==0) return false; bool success=false; ExecStatusType execStatus = PQresultStatus(result); strcpy(lastError,PQresultErrorMessage(result)); switch (execStatus) { case PGRES_COMMAND_OK: success=true; break; case PGRES_EMPTY_QUERY: break; case PGRES_TUPLES_OK: success=true; break; case PGRES_COPY_OUT: break; case PGRES_COPY_IN: break; case PGRES_BAD_RESPONSE: break; case PGRES_NONFATAL_ERROR: break; case PGRES_FATAL_ERROR: if (rollbackOnFailure) Rollback(); break; } return success; }
static void raise_error(VALUE self, PGresult *result, VALUE query) { VALUE exception; char *message; char *sqlstate; int postgres_errno; message = PQresultErrorMessage(result); sqlstate = PQresultErrorField(result, PG_DIAG_SQLSTATE); postgres_errno = MAKE_SQLSTATE(sqlstate[0], sqlstate[1], sqlstate[2], sqlstate[3], sqlstate[4]); PQclear(result); const char *exception_type = "SQLError"; struct errcodes *errs; for (errs = errors; errs->error_name; errs++) { if(errs->error_no == postgres_errno) { exception_type = errs->exception; break; } } VALUE uri = rb_funcall(rb_iv_get(self, "@connection"), rb_intern("to_s"), 0); exception = rb_funcall(CONST_GET(mDO, exception_type), ID_NEW, 5, rb_str_new2(message), INT2NUM(postgres_errno), rb_str_new2(sqlstate), query, uri); rb_exc_raise(exception); }
CONDITION TBL_DeleteTable(TBL_HANDLE ** handle, const TBL_CRITERIA * criteriaList, const char* tableName) { TBL_CONTEXT* tc; char* dbName; /*char *tableName;*/ int foundit; char deleteCommand[2048]; PGresult* res; PGconn* conn; #ifdef CTN_USE_THREADS THR_ObtainMutex(FAC_TBL); #endif tc = G_ContextHead; foundit = 0; while (tc != (TBL_CONTEXT *) NULL) { if (tc == (TBL_CONTEXT *) (*handle)) { dbName = tc->databaseName; /*tableName = tc->tableName;*/ conn = (PGconn*)tc->dbSpecific; foundit = 1; break; } tc = tc->next; } if (!foundit) { #ifdef CTN_USE_THREADS THR_ReleaseMutex(FAC_TBL); #endif return COND_PushCondition(TBL_ERROR(TBL_BADHANDLE), "TBL_Delete"); } strcpy(deleteCommand, "DELETE FROM "); strcat(deleteCommand, tableName); if ((criteriaList != (TBL_CRITERIA *) NULL) && (criteriaList->FieldName != 0)) { strcat(deleteCommand, " WHERE "); addCriteria(criteriaList, deleteCommand); } strcat(deleteCommand, ";" ); res = PQexec(conn, deleteCommand); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, PQresultErrorMessage(res)); fprintf(stderr, "<%s>\n", deleteCommand); exit(1); } PQclear(res); #ifdef CTN_USE_THREADS THR_ReleaseMutex(FAC_TBL); #endif return TBL_NORMAL; }
static SCM pg_error_msg(SCM res) { struct pg_res *pgr; scm_assert_smob_type(pg_res_tag, res); pgr = (struct pg_res *)SCM_SMOB_DATA(res); if ((pgr->status != PGRES_FATAL_ERROR) && (pgr->status != PGRES_NONFATAL_ERROR)) return SCM_BOOL_F; return c2s(PQresultErrorMessage(pgr->res)); }
static void SMSDPgSQL_LogError(GSM_SMSDConfig * Config, PGresult * Res) { if (Res == NULL) { SMSD_Log(DEBUG_INFO, Config, "Error: %s", PQerrorMessage(Config->conn.pg)); } else { SMSD_Log(DEBUG_INFO, Config, "Error: %s", PQresultErrorMessage(Res)); } }
s_object * RS_PostgreSQL_getResult(Con_Handle * conHandle) { S_EVALUATOR RS_DBI_connection * con; S_EVALUATOR RS_DBI_resultSet * result; PGconn *my_connection; Res_Handle *rsHandle; Sint res_id; PGresult *my_result; con = RS_DBI_getConnection(conHandle); my_connection = (PGconn *) con->drvConnection; if (con->num_res > 0) { res_id = (Sint) con->resultSetIds[0]; rsHandle = RS_DBI_asResHandle(MGR_ID(conHandle), CON_ID(conHandle), res_id); result = RS_DBI_getResultSet(rsHandle); if (result->completed == 0) { RS_DBI_errorMessage("connection with pending rows, close resultSet before continuing", RS_DBI_ERROR); } else { RS_PostgreSQL_closeResultSet(rsHandle); } } my_result = PQgetResult(my_connection); if(my_result == NULL) return S_NULL_ENTRY; if (strcmp(PQresultErrorMessage(my_result), "") != 0) { char *errResultMsg; const char *omsg; size_t len; omsg = PQerrorMessage(my_connection); len = strlen(omsg); errResultMsg = malloc(len + 80); /* 80 should be larger than the length of "could not ..."*/ snprintf(errResultMsg, len + 80, "could not Retrieve the result : %s", omsg); RS_DBI_errorMessage(errResultMsg, RS_DBI_ERROR); free(errResultMsg); /* Frees the storage associated with a PGresult. * void PQclear(PGresult *res); */ PQclear(my_result); } /* we now create the wrapper and copy values */ PROTECT(rsHandle = RS_DBI_allocResultSet(conHandle)); result = RS_DBI_getResultSet(rsHandle); result->drvResultSet = (void *) my_result; result->rowCount = (Sint) 0; result->isSelect = 0; result->rowsAffected = 0; result->completed = 1; UNPROTECT(1); return rsHandle; }
/* * call-seq: * res.check -> nil * * Raises appropriate exception if PG::Result is in a bad state. */ VALUE pg_result_check( VALUE self ) { VALUE error, exception, klass; VALUE rb_pgconn = rb_iv_get( self, "@connection" ); PGconn *conn = pg_get_pgconn(rb_pgconn); PGresult *result; #ifdef M17N_SUPPORTED rb_encoding *enc = pg_conn_enc_get( conn ); #endif char * sqlstate; Data_Get_Struct(self, PGresult, result); if(result == NULL) { error = rb_str_new2( PQerrorMessage(conn) ); } else { switch (PQresultStatus(result)) { case PGRES_TUPLES_OK: case PGRES_COPY_OUT: case PGRES_COPY_IN: #ifdef HAVE_CONST_PGRES_COPY_BOTH case PGRES_COPY_BOTH: #endif #ifdef HAVE_CONST_PGRES_SINGLE_TUPLE case PGRES_SINGLE_TUPLE: #endif case PGRES_EMPTY_QUERY: case PGRES_COMMAND_OK: return Qnil; case PGRES_BAD_RESPONSE: case PGRES_FATAL_ERROR: case PGRES_NONFATAL_ERROR: error = rb_str_new2( PQresultErrorMessage(result) ); break; default: error = rb_str_new2( "internal error : unknown result status." ); } } #ifdef M17N_SUPPORTED rb_enc_set_index( error, rb_enc_to_index(enc) ); #endif sqlstate = PQresultErrorField( result, PG_DIAG_SQLSTATE ); klass = lookup_error_class( sqlstate ); exception = rb_exc_new3( klass, error ); rb_iv_set( exception, "@connection", rb_pgconn ); rb_iv_set( exception, "@result", self ); rb_exc_raise( exception ); /* Not reached */ return Qnil; }
/** * @brief cleanup the copyright table and add foreign key * * Will delete any copyright records that refer to pfiles that don't exist. * And create the foreign key * * @param pgConn the connection to the database * @return 1 if the success at the end of the function, 0 otherwise */ int cleanup_copyright(PGconn* pgConn) { /* locals */ PGresult* pgResult; // the result from a database access /* initialize memory */ pgResult = NULL; /* clean up copyright records */ pgResult = PQexec(pgConn, cleanup_copyright_records); if(PQresultStatus(pgResult) != PGRES_COMMAND_OK) { fprintf(cerr, "ERROR %s.%d: Could not cleanup copyright records.\n", __FILE__, __LINE__); fprintf(cerr, "ERROR PQ error message: %s.\n", PQresultErrorMessage(pgResult)); fprintf(cerr, "ERROR sql was: %s\n", cleanup_copyright_records); PQclear(pgResult); return -1; } PQclear(pgResult); /* create the pfile foreign key index */ pgResult = PQexec(pgConn, create_pfile_foreign_index); if(PQresultStatus(pgResult) != PGRES_COMMAND_OK) { fprintf(cerr, "ERROR %s.%d: Could not create copyright pfile_fk.\n", __FILE__, __LINE__); fprintf(cerr, "ERROR PQ error message: %s.\n", PQresultErrorMessage(pgResult)); fprintf(cerr, "ERROR sql was: %s\n", create_pfile_foreign_index); PQclear(pgResult); return -1; } PQclear(pgResult); /* alter pfile_fk */ pgResult = PQexec(pgConn, alter_table_pfile); if(PQresultStatus(pgResult) != PGRES_COMMAND_OK) { fprintf(cerr, "ERROR %s.%d: Could not alter pfile_fk in copyright table.\n", __FILE__, __LINE__); fprintf(cerr, "ERROR PQ error message: %s.\n", PQresultErrorMessage(pgResult)); fprintf(cerr, "ERROR sql was: %s\n", alter_table_pfile); PQclear(pgResult); return -1; } PQclear(pgResult); return 1; }
libpq_fact_result(PGresult* r, ExecStatusType ok_status) : res(r) , row(0) { if(PQresultStatus(res) != ok_status) throw std::runtime_error( PQresultErrorMessage(res) ); }
bool DatabasePostgreSQL::GetWorldRegistration(string long_name, string short_name, unsigned int &id, string &desc, unsigned int &list_id, unsigned int &trusted, string &list_desc, string &account, string &password) { if(!db) { return false; } /** * PostgreSQL doesn't have automatic reconnection option like mysql * but it's easy to check and reconnect */ if(PQstatus(db) != CONNECTION_OK) { PQreset(db); if(PQstatus(db) != CONNECTION_OK) { return false; } } stringstream query(stringstream::in | stringstream::out); query << "SELECT WSR.ServerID, WSR.ServerTagDescription, WSR.ServerTrusted, SLT.ServerListTypeID, "; query << "SLT.ServerListTypeDescription, SAR.AccountName, SAR.AccountPassword FROM " << server.options.GetWorldRegistrationTable(); query << " AS WSR JOIN " << server.options.GetWorldServerTypeTable() << " AS SLT ON WSR.ServerListTypeID = SLT.ServerListTypeID JOIN "; query << server.options.GetWorldAdminRegistrationTable() << " AS SAR ON WSR.ServerAdminID = SAR.ServerAdminID WHERE WSR.ServerShortName"; query << " = '"; query << short_name; query << "'"; PGresult *res = PQexec(db, query.str().c_str()); char *error = PQresultErrorMessage(res); if(strlen(error) > 0) { server_log->Log(log_database, "Database error in DatabasePostgreSQL::GetWorldRegistration(): %s", error); PQclear(res); return false; } if(PQntuples(res) > 0) { id = atoi(PQgetvalue(res, 0, 0)); desc = PQgetvalue(res, 0, 1); trusted = atoi(PQgetvalue(res, 0, 2)); list_id = atoi(PQgetvalue(res, 0, 3)); list_desc = PQgetvalue(res, 0, 4); account = PQgetvalue(res, 0, 5); password = PQgetvalue(res, 0, 6); PQclear(res); return true; } PQclear(res); return false; }
postgresql_statement::postgresql_statement(shared_ptr<postgresql_connection_impl> conn, const string &query) : conn(conn) { postgresql_result res(PQprepare(conn->get(), "", convert_query(query).c_str(), 0, NULL)); if (!res.command_ok()) throw database_error(PQresultErrorMessage(res.get())); }
PQLExtension * getExtensions(PGconn *c, int *n) { PQLExtension *e; PGresult *res; int i; logNoise("extension: server version: %d", PQserverVersion(c)); /* bail out if we do not support it */ if (PQserverVersion(c) < 90100) { logWarning("ignoring extensions because server does not support it"); return NULL; } res = PQexec(c, "SELECT e.oid, extname AS extensionname, nspname, extversion AS version, extrelocatable, obj_description(e.oid, 'pg_extension') AS description FROM pg_extension e LEFT JOIN pg_namespace n ON (e.extnamespace = n.oid) ORDER BY extname"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { logError("query failed: %s", PQresultErrorMessage(res)); PQclear(res); PQfinish(c); /* XXX leak another connection? */ exit(EXIT_FAILURE); } *n = PQntuples(res); if (*n > 0) e = (PQLExtension *) malloc(*n * sizeof(PQLExtension)); else e = NULL; logDebug("number of extensions in server: %d", *n); for (i = 0; i < *n; i++) { e[i].oid = strtoul(PQgetvalue(res, i, PQfnumber(res, "oid")), NULL, 10); e[i].extensionname = strdup(PQgetvalue(res, i, PQfnumber(res, "extensionname"))); e[i].schemaname = strdup(PQgetvalue(res, i, PQfnumber(res, "nspname"))); e[i].version = strdup(PQgetvalue(res, i, PQfnumber(res, "version"))); e[i].relocatable = (PQgetvalue(res, i, PQfnumber(res, "extrelocatable"))[0] == 't'); if (PQgetisnull(res, i, PQfnumber(res, "description"))) e[i].comment = NULL; else e[i].comment = strdup(PQgetvalue(res, i, PQfnumber(res, "description"))); logDebug("extension \"%s\"", e[i].extensionname); } PQclear(res); return e; }
void do_postgres_raise_error(VALUE self, PGresult *result, VALUE query) { const char *message = PQresultErrorMessage(result); char *sql_state = PQresultErrorField(result, PG_DIAG_SQLSTATE); int postgres_errno = MAKE_SQLSTATE(sql_state[0], sql_state[1], sql_state[2], sql_state[3], sql_state[4]); PQclear(result); data_objects_raise_error(self, do_postgres_errors, postgres_errno, message, query, rb_str_new2(sql_state)); }
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; }
PQLSequence * getSequences(PGconn *c, int *n) { PQLSequence *s; PGresult *res; int i; logNoise("sequence: server version: %d", PQserverVersion(c)); res = PQexec(c, "SELECT c.oid, n.nspname, c.relname, obj_description(c.oid, 'pg_class') AS description, pg_get_userbyid(c.relowner) AS relowner, relacl FROM pg_class c INNER JOIN pg_namespace n ON (c.relnamespace = n.oid) WHERE relkind = 'S' AND nspname !~ '^pg_' AND nspname <> 'information_schema' ORDER BY nspname, relname"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { logError("query failed: %s", PQresultErrorMessage(res)); PQclear(res); PQfinish(c); /* XXX leak another connection? */ exit(EXIT_FAILURE); } *n = PQntuples(res); if (*n > 0) s = (PQLSequence *) malloc(*n * sizeof(PQLSequence)); else s = NULL; logDebug("number of sequences in server: %d", *n); for (i = 0; i < *n; i++) { s[i].obj.oid = strtoul(PQgetvalue(res, i, PQfnumber(res, "oid")), NULL, 10); s[i].obj.schemaname = strdup(PQgetvalue(res, i, PQfnumber(res, "nspname"))); s[i].obj.objectname = strdup(PQgetvalue(res, i, PQfnumber(res, "relname"))); if (PQgetisnull(res, i, PQfnumber(res, "description"))) s[i].comment = NULL; else s[i].comment = strdup(PQgetvalue(res, i, PQfnumber(res, "description"))); if (PQgetisnull(res, i, PQfnumber(res, "description"))) s[i].comment = NULL; else s[i].comment = strdup(PQgetvalue(res, i, PQfnumber(res, "description"))); s[i].owner = strdup(PQgetvalue(res, i, PQfnumber(res, "relowner"))); if (PQgetisnull(res, i, PQfnumber(res, "relacl"))) s[i].acl = NULL; else s[i].acl = strdup(PQgetvalue(res, i, PQfnumber(res, "relacl"))); logDebug("sequence %s.%s", formatObjectIdentifier(s[i].obj.schemaname), formatObjectIdentifier(s[i].obj.objectname)); } PQclear(res); return s; }
PGresult* EXE_SQL_QRY(const char* query){ PGresult* res = PQexec(conn,query); if(!res || PQresultStatus(res) != PGRES_TUPLES_OK){ fprintf(stderr, "SQL Error in query: %s\n", PQresultErrorMessage(res)); PQclear(res); return NULL; } return res; }
DBMSqlDatatable* PostgreSql::exec(const core::string &sql, const params_type ¶ms) { usize const sz_params = params.size(); if (0 == sz_params) return this->exec(sql); params_type str_params = params; //Oid* pm_types = (Oid*)malloc(sz_params * sizeof(Oid)); char const* *pm_vals = (char const* *)malloc(sz_params * sizeof(char const*)); int* pm_lens = (int*)malloc(sz_params * sizeof(int)); int* pm_fmts = (int*)malloc(sz_params * sizeof(int)); for (core::counter<params_type::iterator> each = str_params.begin(); each != str_params.end(); ++each) { variant_t& var = each->second; var.stringize(); pm_vals[each.count] = (char const*)var; pm_lens[each.count] = var.size(); pm_fmts[each.count] = 0; } PGresult* res = PQexecParams(d_ptr->pg, sql.c_str(), sz_params, NULL, pm_vals, pm_lens, pm_fmts, 0); //free(pm_types); free(pm_vals); free(pm_lens); free(pm_fmts); PgSqlDatatable* dt = NULL; switch (PQresultStatus(res)) { default: trace_msg(PQresultErrorMessage(res)); break; case PGRES_COMMAND_OK: break; case PGRES_TUPLES_OK: { dt = new PgSqlDatatable(res); dt->update(); } break; }; if (dt == NULL) PQclear(res); else if (dt->rows().size() == 0) zero_drop(dt); return dt; }