will/crystal-pg

Get SQL 'RAISE EXCEPTION' functionality from DB to Crystal

ArtLinkov opened this issue · 7 comments

It is possible to write exceptions and notices in SQL functions (like in any programming language), for example:

CREATE OR REPLACE FUNCTION foo(IN str TEXT)
  RETURNS VOID
  LANGUAGE 'plpgsql'
  AS $$
     BEGIN
	IF str = 'yes' THEN
          RAISE NOTICE 'Glad we agree!';
	ELSE
	  RAISE EXCEPTION 'You know nothing John Snow!';
        END IF;
     END;
  $$;

I did not find any method of querying that also captures such exceptions and returns them to crystal.
Does this functionality exist or is it a missing feature?

There's Connection#on_notice for receiving notices.

Ah, would you demonstrate how it can be used?

That's how I use it in specs to just print the notice to STDOUT:

db.connection.on_notice do |notice|
  puts
  print "NOTICE from PG: "
  puts notice
end

I see!
Thanks @straight-shoota! 😄
It may be a good idea to add this to the docs somewhere.

will commented

It may be a good idea to add this to the docs somewhere.

@ArtLinkov Would you be able to open a PR for the readme? There is a related part here https://github.com/will/crystal-pg#listennotify where it could go. Since you most recently knew what you were looking for, you'd be in the best spot to write it in such a way that would be easy for the next person having the same issue.

@will PR sent

I think this is closed by #201