erlangerlang-ports

Messages received from port in erlang-sqlite3


Erlang-sqlite3 uses a port driver to connect with the SQLite database, and receives messages from the port:

wait_result(Port) ->
  receive
    {Port, Reply} ->
      % io:format("Reply: ~p~n", [Reply]),
      Reply;
    {error, Reason} ->
      io:format("Error: ~p~n", [Reason]),
      {error, Reason};
    _Else ->
      io:format("Else: ~p~n", [_Else]),
      _Else
  end.

I thought that messages from ports should look like this:

{Port,{data,Data}}    Data is received from the external program.
{Port,closed}         Reply to Port ! {Pid,close}.
{Port,connected}      Reply to Port ! {Pid,{connect,NewPid}}
{'EXIT',Port,Reason}  If the port has terminated for some reason.

So, when uncommenting the io:format line in {Port, Reply} clause, I should expect to see {data, ...} for actual replies. I don't; instead I see (for test.erl)

Reply: {ok,101}
Reply: [{columns,["name"]},{rows,[{<<"user">>}]}]
Reply: [{columns,["sql"]},
        {rows,[{<<"CREATE TABLE user (id INTEGER PRIMARY KEY, name TEXT, age INTEGER, wage INTEGER)">>}]}]
Reply: {id,1}
Reply: {id,2}
Reply: [{columns,["id","name","age","wage"]},
        {rows,[{1,<<"abby">>,20,2000},{2,<<"marge">>,30,2000}]}]
Reply: [{columns,["id","name","age","wage"]},{rows,[{1,<<"abby">>,20,2000}]}]
Reply: [{columns,["id","name","age","wage"]},
        {rows,[{1,<<"abby">>,20,2000},{2,<<"marge">>,30,2000}]}]
Reply: {ok,101}
Reply: [{columns,["id","name","age","wage"]},{rows,[{1,<<"abby">>,20,2000}]}]
Reply: {ok,101}
  1. Where am I going wrong?
  2. Will messages I get on a port error look like {'EXIT',Port,Reason} or not?

Solution

  • The relevant example in http://www.erlang.org/doc/apps/erts/driver.html is the last one. It turns out that when using driver_output_term, the term is sent by itself:

    receive
        Result ->
            Result
    end.
    

    instead of

    receive
        {Port, {data, Result}} ->
            Result
    end.