From 30c25d061149c90c9ff3d674ea9e169925e09893 Mon Sep 17 00:00:00 2001 From: Maas-Maarten Zeeman Date: Mon, 21 Nov 2011 20:56:19 +0100 Subject: [PATCH] Adding column names as option to map and foreach functions --- src/esqlite3.erl | 27 ++++++++++++++++++++------- test/esqlite_test.erl | 12 ++++++++++-- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/esqlite3.erl b/src/esqlite3.erl index edea656..59ae2ed 100644 --- a/src/esqlite3.erl +++ b/src/esqlite3.erl @@ -70,22 +70,35 @@ foreach(F, Sql, Connection) -> foreach_s(F, Statement). %% -foreach_s(F, Statement) -> +foreach_s(F, Statement) when is_function(F, 1) -> case try_step(Statement, 0) of - '$done' -> - ok; + '$done' -> ok; Row when is_tuple(Row) -> F(Row), foreach_s(F, Statement) - end. + end; +foreach_s(F, Statement) when is_function(F, 2) -> + ColumnNames = column_names(Statement), + case try_step(Statement, 0) of + '$done' -> ok; + Row when is_tuple(Row) -> + F(ColumnNames, Row), + foreach_s(F, Statement) + end. %% -map_s(F, Statement) -> +map_s(F, Statement) when is_function(F, 1) -> case try_step(Statement, 0) of - '$done' -> - []; + '$done' -> []; Row when is_tuple(Row) -> [F(Row) | map_s(F, Statement)] + end; +map_s(F, Statement) when is_function(F, 2) -> + ColumnNames = column_names(Statement), + case try_step(Statement, 0) of + '$done' -> []; + Row when is_tuple(Row) -> + [F(ColumnNames, Row) | map_s(F, Statement)] end. %% diff --git a/test/esqlite_test.erl b/test/esqlite_test.erl index 925210b..6d5c54e 100644 --- a/test/esqlite_test.erl +++ b/test/esqlite_test.erl @@ -87,8 +87,6 @@ column_names_test() -> ok. - - foreach_test() -> {ok, Db} = esqlite3:open(":memory:"), ok = esqlite3:exec("begin;", Db), @@ -130,6 +128,16 @@ map_test() -> F = fun(Row) -> Row end, [{"hello1",10},{"hello2",11},{"hello3",12},{"hello4",13}] = esqlite3:map(F, "select * from test_table", Db), + + %% Test that when the row-names are added.. + Assoc = fun(Names, Row) -> + lists:zip(tuple_to_list(Names), tuple_to_list(Row)) + end, + + [[{one,"hello1"},{two,10}], + [{one,"hello2"},{two,11}], + [{one,"hello3"},{two,12}], + [{one,"hello4"},{two,13}]] = esqlite3:map(Assoc, "select * from test_table", Db), ok.