static void pg_result_error(PGresult *pg_result) { const char *diag_sqlstate = PQresultErrorField(pg_result, PG_DIAG_SQLSTATE); const char *diag_primary = PQresultErrorField(pg_result, PG_DIAG_MESSAGE_PRIMARY); const char *diag_detail = PQresultErrorField(pg_result, PG_DIAG_MESSAGE_DETAIL); const char *diag_context = PQresultErrorField(pg_result, PG_DIAG_CONTEXT); const char *diag_hint = PQresultErrorField(pg_result, PG_DIAG_MESSAGE_HINT); int sqlstate; if (diag_sqlstate) sqlstate = MAKE_SQLSTATE(diag_sqlstate[0], diag_sqlstate[1], diag_sqlstate[2], diag_sqlstate[3], diag_sqlstate[4]); else sqlstate = ERRCODE_CONNECTION_FAILURE; PQclear(pg_result); ereport(ERROR, (errcode(sqlstate), errmsg("Remote error: %s", diag_primary), diag_detail ? errdetail("Remote detail: %s", diag_detail) : 0, diag_hint ? errhint("Remote hint: %s", diag_hint) : 0, diag_context ? errcontext("Remote context: %s", diag_context) : 0)); }
/* * insert a row into the db * this expects an escaped table name */ enum DB_RESULT __db_insert(const char *table_esc, unsigned long iid, struct timeval current_time, unsigned long long insert_val, double insert_rate) { PGconn *pgsql = getpgsql(); char *query; char *diag; char now[20]; enum DB_RESULT status; PGresult *result; if (pgsql == NULL) { debug(LOW, "No Postgres connection in db_insert\n"); return FALSE; } tv2iso8601(now, current_time); /* INSERT INTO %s (iid,dtime,counter,rate) VALUES (%d, NOW(), %llu, %.6f) */ /* don't include the rate column if it's not needed */ if (insert_rate > 0) { /* double columns have precision of at least 15 digits */ asprintf(&query, "INSERT INTO \"%s\" (iid,dtime,counter,rate) VALUES (%lu,\'%s\',%llu,%.15f)", table_esc, iid, now, insert_val, insert_rate); } else { asprintf(&query, "INSERT INTO \"%s\" (iid,dtime,counter) VALUES (%lu,\'%s\',%llu)", table_esc, iid, now, insert_val); } db_debug(HIGH, "Query = %s\n", query); result = PQexec(pgsql, query); if (PQresultStatus(result) == PGRES_COMMAND_OK) { status = DB_OK; } else { /* Note that by libpq convention, a non-empty PQerrorMessage will include a trailing newline. */ /* also errors start with 'ERROR:' so we don't need to */ db_debug(LOW, "(error code %s) %s", PQresultErrorField(result, PG_DIAG_SQLSTATE), PQerrorMessage(pgsql)); db_debug(LOW, "%s\n", query); diag = PQresultErrorField(result, PG_DIAG_SQLSTATE); if (diag && strncmp(diag, "22003", 5) == 0) { /* NUMERIC VALUE OUT OF RANGE */ /* this can happen because postgres doesn't have unsigned integers */ status = DB_OOR; } else { status = DB_RETRY; } } /* free the result */ (void)PQclear(result); free(query); return(status); }
/* * Pass remote error/notice/warning through. */ void plproxy_remote_error(ProxyFunction *func, ProxyConnection *conn, const PGresult *res, bool iserr) { const char *ss = PQresultErrorField(res, PG_DIAG_SQLSTATE); const char *sev = PQresultErrorField(res, PG_DIAG_SEVERITY); const char *msg = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY); const char *det = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL); const char *hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT); const char *spos = PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION); const char *ipos = PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION); const char *iquery = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY); const char *ctx = PQresultErrorField(res, PG_DIAG_CONTEXT); int elevel; /* libpq errors may not have sqlstate */ if (!ss) ss = "XX000"; if (iserr) /* must ignore remote level, as it may be FATAL/PANIC */ elevel = ERROR; else /* cannot look at sev here, as it may be localized */ elevel = !strncmp(ss, "00", 2) ? NOTICE : WARNING; ereport(elevel, ( errcode(MAKE_SQLSTATE(ss[0], ss[1], ss[2], ss[3], ss[4])), errmsg("%s(%d): [%s] REMOTE %s: %s", func->name, func->arg_count, PQdb(conn->cur->db), sev, msg), det ? errdetail("Remote detail: %s", det) : 0, hint ? errhint("Remote hint: %s", hint) : 0, spos ? errposition(atoi(spos)) : 0, ipos ? internalerrposition(atoi(ipos)) : 0, iquery ? internalerrquery(iquery) : 0, ctx ? errcontext("Remote context: %s", ctx) : 0)); }
void ecpg_raise_backend(int line, PGresult *result, PGconn *conn, int compat) { struct sqlca_t *sqlca = ECPGget_sqlca(); char *sqlstate; char *message; if (result) { sqlstate = PQresultErrorField(result, PG_DIAG_SQLSTATE); if (sqlstate == NULL) sqlstate = ECPG_SQLSTATE_ECPG_INTERNAL_ERROR; message = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY); } else { sqlstate = ECPG_SQLSTATE_ECPG_INTERNAL_ERROR; message = PQerrorMessage(conn); } if (strcmp(sqlstate, ECPG_SQLSTATE_ECPG_INTERNAL_ERROR) == 0) { /* we might get here if the connection breaks down, so let's * check for this instead of giving just the generic internal error */ if (PQstatus(conn) == CONNECTION_BAD) { sqlstate = "57P02"; message = ecpg_gettext("the connection to the server was lost"); } } /* copy error message */ snprintf(sqlca->sqlerrm.sqlerrmc, sizeof(sqlca->sqlerrm.sqlerrmc), "%s on line %d", message, line); sqlca->sqlerrm.sqlerrml = strlen(sqlca->sqlerrm.sqlerrmc); /* copy SQLSTATE */ strncpy(sqlca->sqlstate, sqlstate, sizeof(sqlca->sqlstate)); /* assign SQLCODE for backward compatibility */ if (strncmp(sqlca->sqlstate, "23505", sizeof(sqlca->sqlstate)) == 0) sqlca->sqlcode = INFORMIX_MODE(compat) ? ECPG_INFORMIX_DUPLICATE_KEY : ECPG_DUPLICATE_KEY; else if (strncmp(sqlca->sqlstate, "21000", sizeof(sqlca->sqlstate)) == 0) sqlca->sqlcode = INFORMIX_MODE(compat) ? ECPG_INFORMIX_SUBSELECT_NOT_ONE : ECPG_SUBSELECT_NOT_ONE; else sqlca->sqlcode = ECPG_PGSQL; /* %.*s is safe here as long as sqlstate is all-ASCII */ ecpg_log("raising sqlstate %.*s (sqlcode %d): %s\n", sizeof(sqlca->sqlstate), sqlca->sqlstate, sqlca->sqlcode, sqlca->sqlerrm.sqlerrmc); /* free all memory we have allocated for the user */ ECPGfree_auto_mem(); }
static void ECPGnoticeReceiver(void *arg, const PGresult *result) { char *sqlstate = PQresultErrorField(result, PG_DIAG_SQLSTATE); char *message = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY); struct sqlca_t *sqlca = ECPGget_sqlca(); int sqlcode; if (sqlca == NULL) { ecpg_log("out of memory"); return; } (void) arg; /* keep the compiler quiet */ if (sqlstate == NULL) sqlstate = ECPG_SQLSTATE_ECPG_INTERNAL_ERROR; if (message == NULL) /* Shouldn't happen, but need to be sure */ message = ecpg_gettext("empty message text"); /* these are not warnings */ if (strncmp(sqlstate, "00", 2) == 0) return; ecpg_log("ECPGnoticeReceiver: %s\n", message); /* map to SQLCODE for backward compatibility */ if (strcmp(sqlstate, ECPG_SQLSTATE_INVALID_CURSOR_NAME) == 0) sqlcode = ECPG_WARNING_UNKNOWN_PORTAL; else if (strcmp(sqlstate, ECPG_SQLSTATE_ACTIVE_SQL_TRANSACTION) == 0) sqlcode = ECPG_WARNING_IN_TRANSACTION; else if (strcmp(sqlstate, ECPG_SQLSTATE_NO_ACTIVE_SQL_TRANSACTION) == 0) sqlcode = ECPG_WARNING_NO_TRANSACTION; else if (strcmp(sqlstate, ECPG_SQLSTATE_DUPLICATE_CURSOR) == 0) sqlcode = ECPG_WARNING_PORTAL_EXISTS; else sqlcode = 0; strncpy(sqlca->sqlstate, sqlstate, sizeof(sqlca->sqlstate)); sqlca->sqlcode = sqlcode; sqlca->sqlwarn[2] = 'W'; sqlca->sqlwarn[0] = 'W'; strncpy(sqlca->sqlerrm.sqlerrmc, message, sizeof(sqlca->sqlerrm.sqlerrmc)); sqlca->sqlerrm.sqlerrmc[sizeof(sqlca->sqlerrm.sqlerrmc) - 1] = 0; sqlca->sqlerrm.sqlerrml = strlen(sqlca->sqlerrm.sqlerrmc); ecpg_log("raising sqlcode %d\n", sqlcode); }
PyObject* SetResultError(PGresult* r) { // Creates an exception from `result`. // // This function takes ownership of `result` and will clear it, even if an exception cannot be created. // // Always returns zero so it can be called using "return SetResultError(result);" // TODO: Make a new exception class that always has SQLSTATE ResultHolder result(r); // make sure `r` gets cleared no matter what const char* szMessage = PQresultErrorMessage(result); const char* szSQLSTATE = PQresultErrorField(result, PG_DIAG_SQLSTATE); if (!szMessage || !szSQLSTATE) return PyErr_NoMemory(); Object msg(PyUnicode_FromFormat("[%s] %s", szSQLSTATE, szMessage)); if (!msg) return 0; PyObject* error = PyObject_CallFunction(Error, (char*)"O", msg.Get()); if (!error) return 0; for (size_t i = 0; i < _countof(errorFields); i++) { const char* szValue = PQresultErrorField(result, errorFields[i].fieldcode); Object value; if (szValue == 0) { value.AttachAndIncrement(Py_None); } else { value.Attach(PyUnicode_FromString(szValue)); if (!value) return 0; } if (PyObject_SetAttrString(error, errorFields[i].szAttr, value) == -1) return 0; } PyErr_SetObject(Error, error); return 0; }
static void transfer_message(void *arg, const PGresult *res) { int elevel; int code; const char *severity = PQresultErrorField(res, PG_DIAG_SEVERITY); const char *state = PQresultErrorField(res, PG_DIAG_SQLSTATE); const char *message = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY); const char *detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL); if (detail && !detail[0]) detail = NULL; switch (severity[0]) { case 'D': elevel = DEBUG2; break; case 'L': elevel = LOG; break; case 'I': elevel = INFO; break; case 'N': elevel = NOTICE; break; case 'E': case 'F': elevel = ERROR; break; default: elevel = WARNING; break; } code = MAKE_SQLSTATE(state[0], state[1], state[2], state[3], state[4]); if (elevel >= ERROR) { if (message) message = pstrdup(message); if (detail) detail = pstrdup(detail); PQclear((PGresult *) res); } ereport(elevel, (errcode(code), errmsg("%s", message), (detail ? errdetail("%s", detail) : 0))); }
/* * Report an error we got from the remote server. * * elevel: error level to use (typically ERROR, but might be less) * res: PGresult containing the error * conn: connection we did the query on * clear: if true, PQclear the result (otherwise caller will handle it) * sql: NULL, or text of remote command we tried to execute * * Note: callers that choose not to throw ERROR for a remote error are * responsible for making sure that the associated ConnCacheEntry gets * marked with have_error = true. */ void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql) { /* If requested, PGresult must be released before leaving this function. */ PG_TRY(); { char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE); char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY); char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL); char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT); char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT); int sqlstate; if (diag_sqlstate) sqlstate = MAKE_SQLSTATE(diag_sqlstate[0], diag_sqlstate[1], diag_sqlstate[2], diag_sqlstate[3], diag_sqlstate[4]); else sqlstate = ERRCODE_CONNECTION_FAILURE; /* * If we don't get a message from the PGresult, try the PGconn. This * is needed because for connection-level failures, PQexec may just * return NULL, not a PGresult at all. */ if (message_primary == NULL) message_primary = PQerrorMessage(conn); ereport(elevel, (errcode(sqlstate), message_primary ? errmsg_internal("%s", message_primary) : errmsg("unknown error"), message_detail ? errdetail_internal("%s", message_detail) : 0, message_hint ? errhint("%s", message_hint) : 0, message_context ? errcontext("%s", message_context) : 0, sql ? errcontext("Remote SQL command: %s", sql) : 0)); } PG_CATCH(); { if (clear) PQclear(res); PG_RE_THROW(); } PG_END_TRY(); if (clear) PQclear(res); }
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 ); }
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); }
//----------------------------------------------------------- void ConexaoBD::executarComandoDML(const QString &sql, Resultado &resultado) { Resultado *novo_res=NULL; PGresult *res_sql=NULL; //Dispara um erro caso o usuário tente reiniciar uma conexão não iniciada if(!conexao) throw Excecao(ERR_CONEXBD_OPRCONEXNAOALOC, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Aloca um novo resultado para receber o result-set vindo da execução do comando sql res_sql=PQexec(conexao, sql.toStdString().c_str()); if(strlen(PQerrorMessage(conexao))>0) { throw Excecao(QString(Excecao::obterMensagemErro(ERR_CONEXBD_CMDSQLNAOEXECUTADO)) .arg(PQerrorMessage(conexao)), ERR_CONEXBD_CMDSQLNAOEXECUTADO, __PRETTY_FUNCTION__, __FILE__, __LINE__, NULL, QString(PQresultErrorField(res_sql, PG_DIAG_SQLSTATE))); } novo_res=new Resultado(res_sql); //Copia o novo resultado para o resultado do parâmetro resultado=*(novo_res); //Desaloca o resultado criado delete(novo_res); }
/* * GetQueryResult * * Process the query result. Returns true if there's no error, false * otherwise -- but errors about trying to vacuum a missing relation are * reported and subsequently ignored. */ static bool GetQueryResult(PGconn *conn, const char *dbname, const char *progname) { PGresult *result; SetCancelConn(conn); while ((result = PQgetResult(conn)) != NULL) { /* * If errors are found, report them. Errors about a missing table are * harmless so we continue processing; but die for other errors. */ if (PQresultStatus(result) != PGRES_COMMAND_OK) { char *sqlState = PQresultErrorField(result, PG_DIAG_SQLSTATE); fprintf(stderr, _("%s: vacuuming of database \"%s\" failed: %s"), progname, dbname, PQerrorMessage(conn)); if (sqlState && strcmp(sqlState, ERRCODE_UNDEFINED_TABLE) != 0) { PQclear(result); return false; } } PQclear(result); } ResetCancelConn(); return true; }
void DBConnection::executeDMLCommand(const QString &sql, ResultSet &result) { ResultSet *new_res=nullptr; PGresult *sql_res=nullptr; //Raise an error in case the user try to close a not opened connection if(!connection) throw Exception(ERR_OPR_NOT_ALOC_CONN, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Alocates a new result to receive the resultset returned by the sql command sql_res=PQexec(connection, sql.toStdString().c_str()); //Raise an error in case the command sql execution is not sucessful if(strlen(PQerrorMessage(connection))>0) { throw Exception(QString(Exception::getErrorMessage(ERR_CMD_SQL_NOT_EXECUTED)) .arg(PQerrorMessage(connection)), ERR_CMD_SQL_NOT_EXECUTED, __PRETTY_FUNCTION__, __FILE__, __LINE__, nullptr, QString(PQresultErrorField(sql_res, PG_DIAG_SQLSTATE))); } //Generates the resultset based on the sql result descriptor new_res=new ResultSet(sql_res); //Copy the new resultset to the parameter resultset result=*(new_res); //Deallocate the new resultset delete(new_res); }
/* * 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; }
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)); }
/* * ReportRemoteError retrieves various error fields from the a remote result and * produces an error report at the WARNING level. */ void ReportRemoteError(PGconn *connection, PGresult *result) { char *sqlStateString = PQresultErrorField(result, PG_DIAG_SQLSTATE); char *remoteMessage = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY); char *nodeName = ConnectionGetOptionValue(connection, "host"); char *nodePort = ConnectionGetOptionValue(connection, "port"); char *errorPrefix = "Connection failed to"; int sqlState = ERRCODE_CONNECTION_FAILURE; if (sqlStateString != NULL) { sqlState = MAKE_SQLSTATE(sqlStateString[0], sqlStateString[1], sqlStateString[2], sqlStateString[3], sqlStateString[4]); /* use more specific error prefix for result failures */ if (sqlState != ERRCODE_CONNECTION_FAILURE) { errorPrefix = "Bad result from"; } } /* * If the PGresult did not contain a message, the connection may provide a * suitable top level one. At worst, this is an empty string. */ if (remoteMessage == NULL) { char *lastNewlineIndex = NULL; remoteMessage = PQerrorMessage(connection); lastNewlineIndex = strrchr(remoteMessage, '\n'); /* trim trailing newline, if any */ if (lastNewlineIndex != NULL) { *lastNewlineIndex = '\0'; } } ereport(WARNING, (errcode(sqlState), errmsg("%s %s:%s", errorPrefix, nodeName, nodePort), errdetail("Remote message: %s", remoteMessage))); }
void ECPGraise_backend(int line, PGresult *result, PGconn *conn, int compat) { struct sqlca_t *sqlca = ECPGget_sqlca(); char *sqlstate; char *message; if (result) { sqlstate = PQresultErrorField(result, PG_DIAG_SQLSTATE); if (sqlstate == NULL) sqlstate = ECPG_SQLSTATE_ECPG_INTERNAL_ERROR; message = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY); } else { sqlstate = ECPG_SQLSTATE_ECPG_INTERNAL_ERROR; message = PQerrorMessage(conn); } /* copy error message */ snprintf(sqlca->sqlerrm.sqlerrmc, sizeof(sqlca->sqlerrm.sqlerrmc), "'%s' in line %d.", message, line); sqlca->sqlerrm.sqlerrml = strlen(sqlca->sqlerrm.sqlerrmc); /* copy SQLSTATE */ strncpy(sqlca->sqlstate, sqlstate, sizeof(sqlca->sqlstate)); /* assign SQLCODE for backward compatibility */ if (strncmp(sqlca->sqlstate, "23505", sizeof(sqlca->sqlstate)) == 0) sqlca->sqlcode = INFORMIX_MODE(compat) ? ECPG_INFORMIX_DUPLICATE_KEY : ECPG_DUPLICATE_KEY; else if (strncmp(sqlca->sqlstate, "21000", sizeof(sqlca->sqlstate)) == 0) sqlca->sqlcode = INFORMIX_MODE(compat) ? ECPG_INFORMIX_SUBSELECT_NOT_ONE : ECPG_SUBSELECT_NOT_ONE; else sqlca->sqlcode = ECPG_PGSQL; ECPGlog("raising sqlstate %.*s in line %d, '%s'.\n", sizeof(sqlca->sqlstate), sqlca->sqlstate, line, sqlca->sqlerrm.sqlerrmc); /* free all memory we have allocated for the user */ ECPGfree_auto_mem(); }
/* * Report an error we got from the remote server. * * elevel: error level to use (typically ERROR, but might be less) * res: PGresult containing the error * clear: if true, PQclear the result (otherwise caller will handle it) * sql: NULL, or text of remote command we tried to execute * * Note: callers that choose not to throw ERROR for a remote error are * responsible for making sure that the associated ConnCacheEntry gets * marked with have_error = true. */ void pgfdw_report_error(int elevel, PGresult *res, bool clear, const char *sql) { /* If requested, PGresult must be released before leaving this function. */ PG_TRY(); { char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE); char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY); char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL); char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT); char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT); int sqlstate; if (diag_sqlstate) sqlstate = MAKE_SQLSTATE(diag_sqlstate[0], diag_sqlstate[1], diag_sqlstate[2], diag_sqlstate[3], diag_sqlstate[4]); else sqlstate = ERRCODE_CONNECTION_FAILURE; ereport(elevel, (errcode(sqlstate), message_primary ? errmsg_internal("%s", message_primary) : errmsg("unknown error"), message_detail ? errdetail_internal("%s", message_detail) : 0, message_hint ? errhint("%s", message_hint) : 0, message_context ? errcontext("%s", message_context) : 0, sql ? errcontext("Remote SQL command: %s", sql) : 0)); } PG_CATCH(); { if (clear) PQclear(res); PG_RE_THROW(); } PG_END_TRY(); if (clear) PQclear(res); }
/* * call-seq: * res.check -> nil * * Raises appropriate exception if PG::Result is in a bad state. */ VALUE pg_result_check( VALUE self ) { t_pg_result *this = pgresult_get_this(self); VALUE error, exception, klass; char * sqlstate; if(this->pgresult == NULL) { PGconn *conn = pg_get_pgconn(this->connection); error = rb_str_new2( PQerrorMessage(conn) ); } else { switch (PQresultStatus(this->pgresult)) { 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 self; case PGRES_BAD_RESPONSE: case PGRES_FATAL_ERROR: case PGRES_NONFATAL_ERROR: error = rb_str_new2( PQresultErrorMessage(this->pgresult) ); break; default: error = rb_str_new2( "internal error : unknown result status." ); } } PG_ENCODING_SET_NOCHECK( error, ENCODING_GET(self) ); sqlstate = PQresultErrorField( this->pgresult, PG_DIAG_SQLSTATE ); klass = lookup_error_class( sqlstate ); exception = rb_exc_new3( klass, error ); rb_iv_set( exception, "@connection", this->connection ); rb_iv_set( exception, "@result", this->pgresult ? self : Qnil ); rb_exc_raise( exception ); /* Not reached */ return self; }
/* * Report just the primary error; this is to avoid cluttering the output * with, for instance, a redisplay of the internally generated query */ static void minimal_error_message(PGresult *res) { PQExpBuffer msg; const char *fld; msg = createPQExpBuffer(); fld = PQresultErrorField(res, PG_DIAG_SEVERITY); if (fld) printfPQExpBuffer(msg, "%s: ", fld); else printfPQExpBuffer(msg, "ERROR: "); fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY); if (fld) appendPQExpBufferStr(msg, fld); else appendPQExpBufferStr(msg, "(not available)"); appendPQExpBufferStr(msg, "\n"); psql_error("%s", msg->data); destroyPQExpBuffer(msg); }
/* * call-seq: * res.error_field(fieldcode) -> String * * Returns the individual field of an error. * * +fieldcode+ is one of: * * +PG_DIAG_SEVERITY+ * * +PG_DIAG_SQLSTATE+ * * +PG_DIAG_MESSAGE_PRIMARY+ * * +PG_DIAG_MESSAGE_DETAIL+ * * +PG_DIAG_MESSAGE_HINT+ * * +PG_DIAG_STATEMENT_POSITION+ * * +PG_DIAG_INTERNAL_POSITION+ * * +PG_DIAG_INTERNAL_QUERY+ * * +PG_DIAG_CONTEXT+ * * +PG_DIAG_SOURCE_FILE+ * * +PG_DIAG_SOURCE_LINE+ * * +PG_DIAG_SOURCE_FUNCTION+ * * An example: * * begin * conn.exec( "SELECT * FROM nonexistant_table" ) * rescue PG::Error => err * p [ * err.result.error_field( PG::Result::PG_DIAG_SEVERITY ), * err.result.error_field( PG::Result::PG_DIAG_SQLSTATE ), * err.result.error_field( PG::Result::PG_DIAG_MESSAGE_PRIMARY ), * err.result.error_field( PG::Result::PG_DIAG_MESSAGE_DETAIL ), * err.result.error_field( PG::Result::PG_DIAG_MESSAGE_HINT ), * err.result.error_field( PG::Result::PG_DIAG_STATEMENT_POSITION ), * err.result.error_field( PG::Result::PG_DIAG_INTERNAL_POSITION ), * err.result.error_field( PG::Result::PG_DIAG_INTERNAL_QUERY ), * err.result.error_field( PG::Result::PG_DIAG_CONTEXT ), * err.result.error_field( PG::Result::PG_DIAG_SOURCE_FILE ), * err.result.error_field( PG::Result::PG_DIAG_SOURCE_LINE ), * err.result.error_field( PG::Result::PG_DIAG_SOURCE_FUNCTION ), * ] * end * * Outputs: * * ["ERROR", "42P01", "relation \"nonexistant_table\" does not exist", nil, nil, * "15", nil, nil, nil, "path/to/parse_relation.c", "857", "parserOpenTable"] */ static VALUE pgresult_error_field(VALUE self, VALUE field) { PGresult *result = pgresult_get( self ); int fieldcode = NUM2INT( field ); char * fieldstr = PQresultErrorField( result, fieldcode ); VALUE ret = Qnil; if ( fieldstr ) { ret = rb_tainted_str_new2( fieldstr ); ASSOCIATE_INDEX( ret, self ); } return ret; }
//----------------------------------------------------------- void ConexaoBD::executarComandoDDL(const QString &sql) { PGresult *res_sql=NULL; //Dispara um erro caso o usuário tente reiniciar uma conexão não iniciada if(!conexao) throw Excecao(ERR_CONEXBD_OPRCONEXNAOALOC, __PRETTY_FUNCTION__, __FILE__, __LINE__); res_sql=PQexec(conexao, sql.toStdString().c_str()); if(strlen(PQerrorMessage(conexao)) > 0) { throw Excecao(QString(Excecao::obterMensagemErro(ERR_CONEXBD_CMDSQLNAOEXECUTADO)) .arg(PQerrorMessage(conexao)), ERR_CONEXBD_CMDSQLNAOEXECUTADO, __PRETTY_FUNCTION__, __FILE__, __LINE__, NULL, QString(PQresultErrorField(res_sql, PG_DIAG_SQLSTATE))); } }
void DBConnection::executeDDLCommand(const QString &sql) { PGresult *sql_res=nullptr; //Raise an error in case the user try to close a not opened connection if(!connection) throw Exception(ERR_OPR_NOT_ALOC_CONN, __PRETTY_FUNCTION__, __FILE__, __LINE__); sql_res=PQexec(connection, sql.toStdString().c_str()); //Raise an error in case the command sql execution is not sucessful if(strlen(PQerrorMessage(connection)) > 0) { throw Exception(QString(Exception::getErrorMessage(ERR_CMD_SQL_NOT_EXECUTED)) .arg(PQerrorMessage(connection)), ERR_CMD_SQL_NOT_EXECUTED, __PRETTY_FUNCTION__, __FILE__, __LINE__, nullptr, QString(PQresultErrorField(sql_res, PG_DIAG_SQLSTATE))); } }
static PGresult * table_postgres_query(const char *key, int service) { PGresult *res; const char *errfld; char *stmt; int i; retry: stmt = NULL; for(i = 0; i < SQL_MAX; i++) if (service == 1 << i) { stmt = config->statements[i]; break; } if (stmt == NULL) return NULL; res = PQexecPrepared(config->db, stmt, 1, &key, NULL, NULL, 0); if (PQresultStatus(res) != PGRES_TUPLES_OK) { errfld = PQresultErrorField(res, PG_DIAG_SQLSTATE); /* PQresultErrorField can return NULL if the connection to the server suddenly closed (e.g. server restart) */ if (errfld == NULL || (errfld[0] == '0' && errfld[1] == '8')) { log_warnx("warn: table-postgres: trying to reconnect after error: %s", PQerrorMessage(config->db)); PQclear(res); if (config_connect(config)) goto retry; return NULL; } log_warnx("warn: table-postgres: PQexecPrepared: %s", PQerrorMessage(config->db)); PQclear(res); return NULL; } return res; }
/** * @brief Receives notices from Postgre and post them as an OML log message * @param arg application-specific state (in our case, the table name) * @param res a PGRES_NONFATAL_ERROR PGresult which can be used with PQresultErrorField and PQresultErrorMessage * @return something not documented in the Postgre manual */ static void psql_receive_notice(void *arg, const PGresult *res) { switch(*PQresultErrorField(res, PG_DIAG_SEVERITY)) { case 'E': /*RROR*/ case 'F': /*ATAL*/ case 'P': /*ANIC*/ logerror("psql:%s': %s", (char*)arg, PQresultErrorMessage(res)); break; case 'W': /*ARNING*/ logwarn("psql:%s': %s", (char*)arg, PQresultErrorMessage(res)); break; case 'N': /*OTICE*/ case 'I': /*NFO*/ /* Infos and notice from Postgre are not the primary purpose of OML. * We only display them as debug messages. */ case 'L': /*OG*/ case 'D': /*EBUG*/ logdebug("psql:%s': %s", (char*)arg, PQresultErrorMessage(res)); break; default: logwarn("'psql:%s': Unknown notice: %s", (char*)arg, PQresultErrorMessage(res)); } }
void sql_stream::execute() { /* in the general case execute() will be called implicitly as soon as all the variables are bound. However the user code might want to call it explicitly to have a better control over the execution workflow. That's why in the case of a second call to execute() we choose not to throw any error and instead just return, except if m_auto_exec is false in which case execute() is always explicit */ if (m_bExecuted && m_auto_exec) return; if (m_nArgPos<(int)m_vars.size()) throw db_excpt(m_queryBuf, QString("Not all variables are bound (%1 out of %2)").arg(m_nArgPos).arg(m_vars.size())); DBG_PRINTF(5,"execute: %s", m_queryBuf); m_pgRes=PQexec(m_db.connection(), m_queryBuf); if (!m_pgRes) throw db_excpt(m_queryBuf, PQerrorMessage(m_db.connection())); if (PQresultStatus(m_pgRes)!=PGRES_TUPLES_OK && PQresultStatus(m_pgRes)!=PGRES_COMMAND_OK) { throw db_excpt(m_queryBuf, PQresultErrorMessage(m_pgRes), QString(PQresultErrorField(m_pgRes, PG_DIAG_SQLSTATE))); } const char* t=PQcmdTuples(m_pgRes); if (t && *t) { m_affected_rows=atoi(t); } else m_affected_rows=0; m_rowNumber=0; m_colNumber=0; m_bExecuted=1; }
/* * ProcessQueryResult * * Process (and delete) a query result. Returns true if there's no error, * false otherwise -- but errors about trying to vacuum a missing relation * are reported and subsequently ignored. */ static bool ProcessQueryResult(PGconn *conn, PGresult *result, const char *progname) { /* * If it's an error, report it. Errors about a missing table are harmless * so we continue processing; but die for other errors. */ if (PQresultStatus(result) != PGRES_COMMAND_OK) { char *sqlState = PQresultErrorField(result, PG_DIAG_SQLSTATE); fprintf(stderr, _("%s: vacuuming of database \"%s\" failed: %s"), progname, PQdb(conn), PQerrorMessage(conn)); if (sqlState && strcmp(sqlState, ERRCODE_UNDEFINED_TABLE) != 0) { PQclear(result); return false; } } PQclear(result); return true; }
/* * Our caller already sent the query associated with this step. Wait for it * to either complete or (if given the STEP_NONBLOCK flag) to block while * waiting for a lock. We assume that any lock wait will persist until we * have executed additional steps in the permutation. * * When calling this function on behalf of a given step for a second or later * time, pass the STEP_RETRY flag. This only affects the messages printed. * * If the connection returns an error, the message is saved in step->errormsg. * Caller should call report_error_message shortly after this, to have it * printed and cleared. * * If the STEP_NONBLOCK flag was specified and the query is waiting to acquire * a lock, returns true. Otherwise, returns false. */ static bool try_complete_step(Step * step, int flags) { PGconn *conn = conns[1 + step->session]; fd_set read_set; struct timeval timeout; int sock = PQsocket(conn); int ret; PGresult *res; FD_ZERO(&read_set); while ((flags & STEP_NONBLOCK) && PQisBusy(conn)) { FD_SET(sock, &read_set); timeout.tv_sec = 0; timeout.tv_usec = 10000; /* Check for lock waits every 10ms. */ ret = select(sock + 1, &read_set, NULL, NULL, &timeout); if (ret < 0) /* error in select() */ { if (errno == EINTR) continue; fprintf(stderr, "select failed: %s\n", strerror(errno)); exit_nicely(); } else if (ret == 0) /* select() timeout: check for lock wait */ { int ntuples; res = PQexecPrepared(conns[0], PREP_WAITING, 1, &backend_pids[step->session + 1], NULL, NULL, 0); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "lock wait query failed: %s", PQerrorMessage(conn)); exit_nicely(); } ntuples = PQntuples(res); PQclear(res); if (ntuples >= 1) /* waiting to acquire a lock */ { if (!(flags & STEP_RETRY)) printf("step %s: %s <waiting ...>\n", step->name, step->sql); return true; } /* else, not waiting: give it more time */ } else if (!PQconsumeInput(conn)) /* select(): data available */ { fprintf(stderr, "PQconsumeInput failed: %s\n", PQerrorMessage(conn)); exit_nicely(); } } if (flags & STEP_RETRY) printf("step %s: <... completed>\n", step->name); else printf("step %s: %s\n", step->name, step->sql); while ((res = PQgetResult(conn))) { switch (PQresultStatus(res)) { case PGRES_COMMAND_OK: break; case PGRES_TUPLES_OK: printResultSet(res); break; case PGRES_FATAL_ERROR: if (step->errormsg != NULL) { printf("WARNING: this step had a leftover error message\n"); printf("%s\n", step->errormsg); } /* * Detail may contain XID values, so we want to just show * primary. Beware however that libpq-generated error results * may not contain subfields, only an old-style message. */ { const char *sev = PQresultErrorField(res, PG_DIAG_SEVERITY); const char *msg = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY); if (sev && msg) { step->errormsg = malloc(5 + strlen(sev) + strlen(msg)); sprintf(step->errormsg, "%s: %s", sev, msg); } else step->errormsg = strdup(PQresultErrorMessage(res)); } break; default: printf("unexpected result status: %s\n", PQresStatus(PQresultStatus(res))); } PQclear(res); } return false; }
void pgError::SetError(PGresult *_res, wxMBConv *_conv) { if (!_conv) { _conv = &wxConvLibc; } if (_res) { msg_primary = wxString(PQresultErrorField(_res, PG_DIAG_MESSAGE_PRIMARY), *_conv); severity = wxString(PQresultErrorField(_res, PG_DIAG_SEVERITY), *_conv); sql_state = wxString(PQresultErrorField(_res, PG_DIAG_SQLSTATE), *_conv); msg_detail = wxString(PQresultErrorField(_res, PG_DIAG_MESSAGE_DETAIL), *_conv); msg_hint = wxString(PQresultErrorField(_res, PG_DIAG_MESSAGE_HINT), *_conv); statement_pos = wxString(PQresultErrorField(_res, PG_DIAG_STATEMENT_POSITION), *_conv); internal_pos = wxString(PQresultErrorField(_res, PG_DIAG_INTERNAL_POSITION), *_conv); internal_query = wxString(PQresultErrorField(_res, PG_DIAG_INTERNAL_QUERY), *_conv); context = wxString(PQresultErrorField(_res, PG_DIAG_CONTEXT), *_conv); source_file = wxString(PQresultErrorField(_res, PG_DIAG_SOURCE_FILE), *_conv); source_line = wxString(PQresultErrorField(_res, PG_DIAG_SOURCE_LINE), *_conv); source_function = wxString(PQresultErrorField(_res, PG_DIAG_SOURCE_FUNCTION), *_conv); } else { msg_primary = wxEmptyString; severity = wxEmptyString; sql_state = wxEmptyString; msg_detail = wxEmptyString; msg_hint = wxEmptyString; statement_pos = wxEmptyString; internal_pos = wxEmptyString; internal_query = wxEmptyString; context = wxEmptyString; source_file = wxEmptyString; source_line = wxEmptyString; source_function = wxEmptyString; } wxString errMsg; if (severity != wxEmptyString && msg_primary != wxEmptyString) errMsg = severity + wxT(": ") + msg_primary; else if (msg_primary != wxEmptyString) errMsg = msg_primary; if (!sql_state.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("SQL state: "); errMsg += sql_state; } if (!msg_detail.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("Detail: "); errMsg += msg_detail; } if (!msg_hint.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("Hint: "); errMsg += msg_hint; } if (!statement_pos.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("Character: "); errMsg += statement_pos; } if (!context.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("Context: "); errMsg += context; } formatted_msg = errMsg; }
void pgConn::SetLastResultError(PGresult *res, const wxString &msg) { if (res) { lastResultError.severity = wxString(PQresultErrorField(res, PG_DIAG_SEVERITY), *conv); lastResultError.sql_state = wxString(PQresultErrorField(res, PG_DIAG_SQLSTATE), *conv); lastResultError.msg_primary = wxString(PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY), *conv); lastResultError.msg_detail = wxString(PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL), *conv); lastResultError.msg_hint = wxString(PQresultErrorField(res, PG_DIAG_MESSAGE_HINT), *conv); lastResultError.statement_pos = wxString(PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION), *conv); lastResultError.internal_pos = wxString(PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION), *conv); lastResultError.internal_query = wxString(PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY), *conv); lastResultError.context = wxString(PQresultErrorField(res, PG_DIAG_CONTEXT), *conv); lastResultError.source_file = wxString(PQresultErrorField(res, PG_DIAG_SOURCE_FILE), *conv); lastResultError.source_line = wxString(PQresultErrorField(res, PG_DIAG_SOURCE_LINE), *conv); lastResultError.source_function = wxString(PQresultErrorField(res, PG_DIAG_SOURCE_FUNCTION), *conv); } else { lastResultError.severity = wxEmptyString; lastResultError.sql_state = wxEmptyString; if (msg.IsEmpty()) lastResultError.msg_primary = GetLastError(); else lastResultError.msg_primary = msg; lastResultError.msg_detail = wxEmptyString; lastResultError.msg_hint = wxEmptyString; lastResultError.statement_pos = wxEmptyString; lastResultError.internal_pos = wxEmptyString; lastResultError.internal_query = wxEmptyString; lastResultError.context = wxEmptyString; lastResultError.source_file = wxEmptyString; lastResultError.source_line = wxEmptyString; lastResultError.source_function = wxEmptyString; } wxString errMsg; if (lastResultError.severity != wxEmptyString && lastResultError.msg_primary != wxEmptyString) errMsg = lastResultError.severity + wxT(": ") + lastResultError.msg_primary; else if (lastResultError.msg_primary != wxEmptyString) errMsg = lastResultError.msg_primary; if (!lastResultError.sql_state.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("SQL state: "); errMsg += lastResultError.sql_state; } if (!lastResultError.msg_detail.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("Detail: "); errMsg += lastResultError.msg_detail; } if (!lastResultError.msg_hint.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("Hint: "); errMsg += lastResultError.msg_hint; } if (!lastResultError.statement_pos.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("Character: "); errMsg += lastResultError.statement_pos; } if (!lastResultError.context.IsEmpty()) { if (!errMsg.EndsWith(wxT("\n"))) errMsg += wxT("\n"); errMsg += _("Context: "); errMsg += lastResultError.context; } lastResultError.formatted_msg = errMsg; }