From 4f2c4124d150bb4de50d21fa468c2d1417984d67 Mon Sep 17 00:00:00 2001 From: Chris Rienzo Date: Mon, 27 Jun 2016 17:23:40 -0400 Subject: [PATCH] FS-9302 [mod_mongo] mongo_find_one and mongo_find_n corrected to return -ERR when connection to database fails. --- src/mod/applications/mod_mongo/mod_mongo.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/mod/applications/mod_mongo/mod_mongo.c b/src/mod/applications/mod_mongo/mod_mongo.c index a614d1f79a..aac3221fe7 100644 --- a/src/mod/applications/mod_mongo/mod_mongo.c +++ b/src/mod/applications/mod_mongo/mod_mongo.c @@ -251,23 +251,30 @@ SWITCH_STANDARD_API(mod_mongo_find_n_function) mongoc_cursor_t *cursor = mongoc_collection_find(col, query_options, 0, n, 0, query, fields, NULL); if (cursor && !mongoc_cursor_error(cursor, &error)) { /* get results from cursor */ + switch_stream_handle_t result_stream = { 0 }; const bson_t *result; - stream->write_function(stream, "-OK\n["); + SWITCH_STANDARD_STREAM(result_stream); + if (mongoc_cursor_more(cursor) && mongoc_cursor_next(cursor, &result)) { char *json_result; json_result = bson_as_json(result, NULL); - stream->write_function(stream, "%s", json_result); + result_stream.write_function(&result_stream, "%s", json_result); bson_free(json_result); } while (mongoc_cursor_more(cursor) && mongoc_cursor_next(cursor, &result)) { char *json_result; json_result = bson_as_json(result, NULL); - stream->write_function(stream, ",%s", json_result); + result_stream.write_function(&result_stream, ",%s", json_result); bson_free(json_result); } - stream->write_function(stream, "]\n"); + if (!mongoc_cursor_error(cursor, &error)) { + stream->write_function(stream, "-OK\n[%s]", zstr((char *)result_stream.data) ? "" :(char *)result_stream.data); + } else { + stream->write_function(stream, "-ERR\nquery failed: %s", error.message); + } + switch_safe_free(result_stream.data); } else { - stream->write_function(stream, "-ERR\nquery failed!\n"); + stream->write_function(stream, "-ERR\nquery failed: %s", error.message); } if (cursor) { mongoc_cursor_destroy(cursor); @@ -342,6 +349,8 @@ SWITCH_STANDARD_API(mod_mongo_find_one_function) json_result = bson_as_json(result, NULL); stream->write_function(stream, "-OK\n%s\n", json_result); bson_free(json_result); + } else if (mongoc_cursor_error(cursor, &error)) { + stream->write_function(stream, "-ERR\nquery failed: %s\n", error.message); } else { /* empty set */ stream->write_function(stream, "-OK\n{}\n");