/source/otp_src_R14B02/erts/example/pg_async.erl

https://github.com/akiernan/omnibus · Erlang · 57 lines · 32 code · 7 blank · 18 comment · 0 complexity · da6ec8e101b49011e16d88194ed97d64 MD5 · raw file

  1. %%
  2. %% %CopyrightBegin%
  3. %%
  4. %% Copyright Ericsson AB 2006-2009. All Rights Reserved.
  5. %%
  6. %% The contents of this file are subject to the Erlang Public License,
  7. %% Version 1.1, (the "License"); you may not use this file except in
  8. %% compliance with the License. You should have received a copy of the
  9. %% Erlang Public License along with this software. If not, it can be
  10. %% retrieved online at http://www.erlang.org/.
  11. %%
  12. %% Software distributed under the License is distributed on an "AS IS"
  13. %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
  14. %% the License for the specific language governing rights and limitations
  15. %% under the License.
  16. %%
  17. %% %CopyrightEnd%
  18. %%
  19. -module(pg_async).
  20. -define(DRV_CONNECT, $C).
  21. -define(DRV_DISCONNECT, $D).
  22. -define(DRV_SELECT, $S).
  23. -export([connect/1, disconnect/1, select/2]).
  24. connect(ConnectStr) ->
  25. case erl_ddll:load_driver(".", "pg_async") of
  26. ok -> ok;
  27. {error, already_loaded} -> ok;
  28. E -> exit(E)
  29. end,
  30. Port = open_port({spawn, ?MODULE}, [binary]),
  31. port_control(Port, ?DRV_CONNECT, ConnectStr),
  32. case return_port_data(Port) of
  33. ok ->
  34. {ok, Port};
  35. Error ->
  36. Error
  37. end.
  38. disconnect(Port) ->
  39. port_control(Port, ?DRV_DISCONNECT, ""),
  40. R = return_port_data(Port),
  41. port_close(Port),
  42. R.
  43. select(Port, Query) ->
  44. port_control(Port, ?DRV_SELECT, Query),
  45. return_port_data(Port).
  46. return_port_data(Port) ->
  47. receive
  48. {Port, {data, Data}} ->
  49. binary_to_term(Data)
  50. end.