shared/gatt-client: Don't clear db in case of errors

If the db was not empty when initializing the instance set the
discovery last handle to avoid clearing the database in case of
cache validation error.

(cherry picked from commit e43847bc6bf27d731657baed9a816d3bd42861db)

Change-Id: I93c59cfed2afe5d9f97fb3005f24531cf850afc4
diff --git a/src/shared/gatt-client.c b/src/shared/gatt-client.c
index dc98aaa..0134721 100644
--- a/src/shared/gatt-client.c
+++ b/src/shared/gatt-client.c
@@ -340,12 +340,8 @@
 								uint8_t err)
 {
 	/* Reset remaining range */
-	if (success) {
-		if (op->last != UINT16_MAX)
-			gatt_db_clear_range(op->client->db, op->last + 1,
-								UINT16_MAX);
-	} else
-		gatt_db_clear(op->client->db);
+	if (op->last != UINT16_MAX)
+		gatt_db_clear_range(op->client->db, op->last + 1, UINT16_MAX);
 
 	op->success = success;
 	op->complete_func(op, success, err);
@@ -368,6 +364,7 @@
 	op->failure_func = failure_func;
 	op->start = start;
 	op->end = end;
+	op->last = gatt_db_isempty(client->db) ? 0 : UINT16_MAX;
 
 	return op;
 }
@@ -386,7 +383,7 @@
 	if (__sync_sub_and_fetch(&op->ref_count, 1))
 		return;
 
-	if (!op->success)
+	if (!op->success && op->failure_func)
 		op->failure_func(op);
 
 	discovery_op_free(op);
@@ -983,6 +980,8 @@
 				success = false;
 				goto done;
 			}
+			/* Database has changed adjust last handle */
+			op->last = end;
 		}
 
 		/* Skip if service already active */
@@ -1094,6 +1093,8 @@
 				success = false;
 				goto done;
 			}
+			/* Database has changed adjust last handle */
+			op->last = end;
 		}
 
 		/* Skip if service already active */
@@ -1609,13 +1610,6 @@
 	notify_client_ready(client, success, att_ecode);
 }
 
-static void init_fail(struct discovery_op *op)
-{
-	struct bt_gatt_client *client = op->client;
-
-	gatt_db_clear(client->db);
-}
-
 static bool gatt_client_init(struct bt_gatt_client *client, uint16_t mtu)
 {
 	struct discovery_op *op;
@@ -1623,8 +1617,7 @@
 	if (client->in_init || client->ready)
 		return false;
 
-	op = discovery_op_create(client, 0x0001, 0xffff, init_complete,
-								init_fail);
+	op = discovery_op_create(client, 0x0001, 0xffff, init_complete, NULL);
 	if (!op)
 		return false;