will / crystal-pg

a postgres driver for crystal
BSD 3-Clause "New" or "Revised" License
462 stars 77 forks source link

Get SQL 'RAISE EXCEPTION' functionality from DB to Crystal #200

Open ArtLinkov opened 4 years ago

ArtLinkov commented 4 years ago

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?

straight-shoota commented 4 years ago

There's Connection#on_notice for receiving notices.

ArtLinkov commented 4 years ago

Ah, would you demonstrate how it can be used?

straight-shoota commented 4 years ago

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
ArtLinkov commented 4 years ago

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

will commented 4 years ago

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.

ArtLinkov commented 4 years ago

@will PR sent

jwoertink commented 3 years ago

I think this is closed by https://github.com/will/crystal-pg/pull/201