While running a stored procedure, the procedure can raise warning messages.
Is there any way to get these messages using Postgresql driver(https://github.com/lib/pq) in Golang ?
For lib/pq driver, the answer is "still no".
See open issue and sources for details.
Meanwhile, another driver, https://github.com/jackc/pgx has support for messages in current (v4) version, see https://godoc.org/github.com/jackc/pgconn#Notice and earlier (see https://github.com/jackc/pgx/blob/v3/conn.go#L54)
Update: According to PR #932 which has been merged at Jan-2020, lib/pq supports NoticeHandler now. See example.
The answer appears to be no.
In my tests the Postgres server did not appear to send the warning with the results. Even if it did, returning an error along with the sql.Result would be confusing at best and would require lib/pq modifications. Raising an error in the function did return an error, but (obviously) no result.
If this is a critical requirement (and your function can support it) you might consider using a notification channel. Bear in mind that this would tie your code to Postgres.
--
Here is the function I used:
CREATE OR REPLACE function fugo()
RETURNS bool as $$
BEGIN
RAISE WARNING 'My function notice.' USING errcode = '01000';
return TRUE;
END;$$
language 'plpgsql';
Related
Tell me, please, why does the empty value come?
To send a request, I use SoapUI 5.5.
But :body is not null.
Do I need to do something in the settings of ORDS?
DECLARE
--b_body BLOB := :body;
c_body CLOB := :body_text;
BEGIN
if :body_text is null then
htp.print('EMPTY');
end if;
END;
As it says in documentation https://docs.oracle.com/en/database/oracle/oracle-rest-data-services/18.3/aelig/implicit-parameters.html#GUID-76A23568-EA67-4375-A4AA-880E1D160D27, for each implicit parameter :body and :body_text "if it is dereferenced more than once, then the second and subsequent dereferences will appear to be empty."
So, change your code like this:
DECLARE
--b_body BLOB := :body;
c_body CLOB := :body_text;
BEGIN
if c_body is null then
htp.print('EMPTY');
end if;
END;
If I remember correct it's not a good idea to use both binds in 1 code block...
If ORDS checks that you're using :body, :body_text is not populated (I think because of the overall performance of converting a blob to clob).
So just use :body_text and you should be fine!
This symptom may result from creating RESTful Services via older versions of the APEX SQL Workshop interface. APEX 5.1 certainly exhibits this behaviour, possibly others. If you are unable to upgrade APEX, use SQL Developer to create your ORDS modules.
I'm looking at this example provided by MS as I'm trying to learn Try...Catch. I understand the syntax and Output (for the most part) but I have one question:
The Output will show the Error_Line as '4'. This is fine but if I remove the line break between GO and BEGIN TRY it'll show the Error_Line as '3'. I just want to understand the logic here.
What I imagine is happening is that SQL Server is counting the lines by beginning the batch immediately after GO, even if that line is blank but I do not know this for certain. Can anyone clarify? If that theory is correct, wouldn't that make finding errors difficult if scripts are written with line breaks like this?
-- Verify that the stored procedure does not already exist.
IF OBJECT_ID ( 'usp_GetErrorInfo', 'P' ) IS NOT NULL
DROP PROCEDURE usp_GetErrorInfo;
GO
-- Create procedure to retrieve error information.
CREATE PROCEDURE usp_GetErrorInfo
AS
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
GO
--Line 1
BEGIN TRY --Line 2
-- Generate divide-by-zero error. --Line 3
SELECT 1/0; --Line 4
END TRY
BEGIN CATCH
-- Execute error retrieval routine.
EXECUTE usp_GetErrorInfo;
END CATCH;
You can't really rely on ERROR_LINE(), especially when the error is thrown in internal stored procedure or there is dynamic T-SQL statement which is executed.
But do you really need the exact error line?
in real production code, the fix for the line causing the error may not be so obvious as in your example;
it will be better to debug the stored procedure or the function with the corresponding input parameter in order to reproduce the error
In this way it will be easier to fix an issue. In order to debug a SQL routine:
just script it
remove the drop and create stuff
add declare in front of the input parameters and initialized them with the values causing the error
Basically, instead of the exact error line (which can be easily fine having the correct input parameters and executing the routine) you may found useful two things:
which routing is causing the error (for example, you can add additional parameter to user usp_GetErrorInfo SP which is yielding the SP name as well
the input parameters which are causing the error (this can be done using separated table for logging the errors in the CATCH clause - you simple insert the input parameters in the table and information about the error)
Having this information, it will be easy to reproduce and then fix an issue (in many cases).
I program with libpq.so. I want to get the error code which is called sql state in SQL Standard.How should I get this in my c code?
The obvious Google search for libpq get sqlstate finds the libpq-exec documentation. Searching that for SQLSTATE finds PG_DIAG_SQLSTATE in the PQresultErrorField section.
Thus, you can see that you can call PQresultErrorField(thePgResult, PG_DIAG_SQLSTATE) to get the SQLSTATE.
This is just addition I can not leave in form of comment due to reputation reasons.
Note that you can not portably get SQLSTATE for errors that can occur during PQconnectdb. In theory, you can read pg_conn (internal struct) field last_sqlstate which contains correct value.
For example, if you try to connect with invalid login/password, it will give you 28P01. For wrong database it will contain 3D000.
I wish they defined publically available getter for this field.
You can check this one as well:
libpq: How to get the error code after a failed PGconn connection
I had been using MySQL as database and had planned to move to postgresql. I had used aes_encrypt and aes_decrypt functions in MySQL extensively throughout my application. So whenever the encryption/decrytion fails, MySQL automatically returns 'null'.
I am unsure how to handle the same in postgresql. Tried using the pgp_sym_encrypt/pgp_sym_decrypt functions. If the encryption key is wrong, it throws error "Wrong key/corrupt data". I tried searching for some functions that could capture this error and return 'null' as in MySQL so that I need not modify my code. I had been searching but could not find one.
Has anybody used any error handling mechanism for individual queries? I had found that error handling can be done for procedures. But, I had to completely rewrite the entire application for that.
If you could share some details, it would be of great help. Thanks.
If you wish to avoid modifying your code and have the functions return NULL on error, you can do this by wrapping them in a PL/PgSQL function that uses a BEGIN ... EXCEPTION block to trap the error.
To do this, first I get the SQLSTATE for the error:
regress=# \set VERBOSITY verbose
regress=# SELECT pgp_sym_decrypt('fred','key');
ERROR: 39000: Wrong key or corrupt data
LOCATION: decrypt_internal, pgp-pgsql.c:607
I could use this directly in the error handler, but I prefer to use a symbolic name, so I look up the error name associated with 39000 in Appendix A - Error codes, finding that it's the generic function call error external_routine_invocation_exception. Not as specific as we would've liked, but it'll do.
Now a wrapper function is required. Something like this must be defined, with one function for each overloaded signature of pgp_sym_decrypt that you wish to support. For the (bytea,text) form that returns text, for example:
CREATE OR REPLACE FUNCTION pgp_sym_decrypt_null_on_err(data bytea, psw text) RETURNS text AS $$
BEGIN
RETURN pgp_sym_decrypt(data, psw);
EXCEPTION
WHEN external_routine_invocation_exception THEN
RAISE DEBUG USING
MESSAGE = format('Decryption failed: SQLSTATE %s, Msg: %s',
SQLSTATE,SQLERRM),
HINT = 'pgp_sym_encrypt(...) failed; check your key',
ERRCODE = 'external_routine_invocation_exception';
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
I've chosen to preseve the original error in a DEBUG level message. Here's a comparison of the original and wrapper, with full message verbosity and debug level output.
Enable debug output to show the RAISE. Note that it also shows the *original query text of the pgp_decrypt_sym call, including parameters.
regress=# SET client_min_messages = DEBUG;
New wrapped function still reports the error if detailed logging is enabled, but returns NULL:
regress=# SELECT pgp_sym_decrypt_null_on_err('redsdfsfdsfd','bobsdf');
LOG: 00000: statement: SELECT pgp_sym_decrypt_null_on_err('redsdfsfdsfd','bobsdf');
LOCATION: exec_simple_query, postgres.c:860
DEBUG: 39000: Decryption failed: SQLSTATE 39000, Msg: Wrong key or corrupt data
HINT: pgp_sym_encrypt(...) failed; check your key
LOCATION: exec_stmt_raise, pl_exec.c:2806
pgp_sym_decrypt_null_on_err
-----------------------------
(1 row)
compared to the original, which fails:
regress=# SELECT pgp_sym_decrypt('redsdfsfdsfd','bobsdf');
LOG: 00000: statement: SELECT pgp_sym_decrypt('redsdfsfdsfd','bobsdf');
LOCATION: exec_simple_query, postgres.c:860
ERROR: 39000: Wrong key or corrupt data
LOCATION: decrypt_internal, pgp-pgsql.c:607
Note that both forms show the parameters the function was called with when it failed. The parameters won't be shown if you've used bind parameters ("prepared statements"), but you should still consider your logs to be security critical if you're using in-database encryption.
Personally, I think it's better to do crypto in the app, so the DB never has access to the keys.
I am using Sybase ASE 12.5 at the moment. I have a code below:
create procedure test_launcher_fail_wrapper
as
begin
select convert(numeric(2),1234345)
if ##error != 0
begin
select "SP failed to execute"
return 1
end
end
Here, I am trying to convert a very large value/amount (1234345) to Numeric size 2. Which is not possible and it generates error.
Questions:
Is having ##error useful here? I ran this SP and it never went into
error handling
How to error handle these kind of scenarios?
I treat error handling in procs similarly to error handling in applications -- if there's an opportunity for you to contribute some actual value by handling the error, then by all means, do so, but if you can't really do anything to help, then you're better off just letting it go.
As an example of adding value, I've got one or two procs that add contextual information in the error message, like a list of ID values that conflict with an update operation. In this particular case, I know that the upstream consumer of the proc will log this error, and the text will be available to an operator who will find this information valuable when debugging the problem. I also know that while this condition is a real error, it's been known to happen from time-to-time, and the effort to format the error is worthwhile.
Does this catch your error?
create procedure test_launcher_fail_wrapper
as
begin
declare #database_err int
set #database_err = 0
select convert(numeric(2),1234345)
set #database_err = ##error
if #database_err <> 0
begin
PRINT 'SP failed to execute'
return 1
end
end
##error is the way to go but beware since:
Every Transact-SQL statement, including print statements and if tests, resets ##error, so the status check must immediately follow the batch for which success is in question.
As for a suggestion on how to handle error management in similar scenarios, have you considered using raiserror ?
An example:
create procedure proc1 as
begin
select convert(numeric(2),1234345)
if ##error <> 0
begin
raiserror 20001 "Error during convert in proc1"
return 1
end
end