Add ability to subscribe to table updates.

This was implemented based on
[this](https://www.sqlite.org/c3ref/update_hook.html) document.
This commit is contained in:
Connor Rigby
2018-11-29 13:29:15 -08:00
parent ab25c2d2b6
commit 8fa063a3f1
4 changed files with 307 additions and 187 deletions

View File

@@ -22,6 +22,7 @@
%% higher-level export
-export([open/1, open/2,
set_update_hook/2, set_update_hook/3,
exec/2, exec/3,
changes/1, changes/2,
insert/2,
@@ -69,6 +70,22 @@ open(Filename, Timeout) ->
Error
end.
%% @doc Subscribe to database notifications
%% Messages will come in the shape {action, table, id}
%% Where action will be insert | update | delete
%% and table will be a string
%% and id will be an integer
%%
-spec set_update_hook(pid(), connection()) -> ok | {error, term()}.
set_update_hook(Pid, Connection) ->
set_update_hook(Pid, Connection, ?DEFAULT_TIMEOUT).
-spec set_update_hook(pid(), connection(), timeout()) -> ok | {error, term()}.
set_update_hook(Pid, {connection, _Ref, Connection}, Timeout) ->
Ref = make_ref(),
ok = esqlite3_nif:set_update_hook(Connection, Ref, self(), Pid),
receive_answer(Ref, Timeout).
%% @doc Execute a sql statement, returns a list with tuples.
-spec q(sql(), connection()) -> list(tuple()) | {error, term()}.
q(Sql, Connection) ->
@@ -208,7 +225,7 @@ fetchall_internal(Statement, ChunkSize, Rest) ->
%% Try a number of steps, when the database is busy,
%% return rows in revers order
-spec try_multi_step(statement(), pos_integer(), list(tuple()), non_neg_integer()) ->
-spec try_multi_step(statement(), pos_integer(), list(tuple()), non_neg_integer()) ->
{rows, list(tuple())} |
{'$done', list(tuple())} |
{error, term()}.

View File

@@ -23,6 +23,7 @@
%% low-level exports
-export([start/0,
open/4,
set_update_hook/4,
exec/4,
changes/3,
insert/4,
@@ -62,6 +63,9 @@ start() ->
open(_Db, _Ref, _Dest, _Filename) ->
erlang:nif_error(nif_library_not_loaded).
set_update_hook(_Db, _Ref, _Dest, _Pid) ->
erlang:nif_error(nif_library_not_loaded).
%% @doc Exec the query.
%%
%% Sends an asynchronous exec command over the connection and returns