From 16f88339ed7fffa8e4573466da9e0b3573f9cf1f Mon Sep 17 00:00:00 2001 From: totoro Date: Sat, 29 Sep 2018 23:55:27 +0200 Subject: [PATCH] add more helper in sql_utils: - update_with_clause (make conditional update) - get_all_to_json (extract only fields by given extractors from the table cursor result to a list of JSON value) --- controller/hk_sql_utils.anubis | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+), 0 deletions(-) diff --git a/controller/hk_sql_utils.anubis b/controller/hk_sql_utils.anubis index 878903b..923956b 100644 --- a/controller/hk_sql_utils.anubis +++ b/controller/hk_sql_utils.anubis @@ -235,6 +235,46 @@ public define (String, String, String, String) -> Maybe(One -> SQLite3Row) ok(_, cursor, _) then success(cursor) } . + + /***** JSON *****/ + +public define Maybe(JsonValue) + extract_cursor_to_json + ( + SQLite3DataBase db, + List(((Int -> SQLite3Datum) -> JsonMember)) extractors, + One -> SQLite3Row table_cursor + ) = + //get next cursor + if table_cursor(unique) is + { + error(sql_error) then println(db_error(sql_error, "extract_cursor_to_json")); failure, + no_more_row then failure, + row(cursor) then + success( + json_object( + map(((Int -> SQLite3Datum) -> JsonMember extractor) |-> extractor(cursor) , extractors) + )) + } +. + +public define List(JsonValue) + get_all_to_json + ( + SQLite3DataBase db, + List(((Int -> SQLite3Datum) -> JsonMember)) extractors, + One -> SQLite3Row table_cursor, + List(JsonValue) so_far + ) = + if extract_cursor_to_json(db, extractors, table_cursor) is + { + failure then reverse(so_far), + success(data) then get_all_to_json(db, extractors, table_cursor, [data . so_far]) + } +. + + + /***** Type $T ******/ define (One -> SQLite3Row, List($T)) ->List($T) _get_all @@ -459,6 +499,7 @@ public define Maybe($T) success(id) then get_by_clause_to_mb_type(db, "id = "+id) } . + public define Maybe(Int) insert_or_update ( @@ -501,3 +542,22 @@ public define Maybe(Int) } } . + +public define Maybe(One) + update_with_clause + ( + SQLite3DataBase db, + String table_name, + String clause, + List(SQLite3_update_field) fields + )= + + since make_update_clause_and_binds(fields) is (binds, set_string), + if sql_query_timeout(db, "UPDATE "+table_name+" SET "+set_string +" "+clause+";", binds, table_name+" (UPDATE)") is + { + error(sql_error) then + //logError(debug_log, db_error(sql_error, table_name)); + failure, + ok(_, _, _) then success(unique) + } +. -- libgit2 0.21.4