Extend database values with arrays
authorJosé Bollo <jose.bollo@iot.bzh>
Tue, 2 May 2017 14:08:35 +0000 (16:08 +0200)
committerJosé Bollo <jose.bollo@iot.bzh>
Tue, 19 Sep 2017 13:25:36 +0000 (15:25 +0200)
Change-Id: I9ab94413abce0d13102711091ec48a5894ccadd9
Signed-off-by: José Bollo <jose.bollo@iot.bzh>
src/afm-udb.c

index 9b1a354..e199ae1 100644 (file)
@@ -89,6 +89,41 @@ static void apps_put(struct afm_apps *apps)
        json_object_put(apps->prvobj);
 }
 
+/*
+ * Append the field 'data' to the field 'name' of the 'object'.
+ * When a second append is done to one field, it is automatically
+ * transformed to an array.
+ * Return 0 in case of success or -1 in case of error.
+ */
+static int append_field(
+               struct json_object *object,
+               const char *name,
+               struct json_object *data
+)
+{
+       struct json_object *item, *array;
+
+       if (!json_object_object_get_ex(object, name, &item))
+               json_object_object_add(object, name, data);
+       else {
+               if (json_object_is_type(item, json_type_array))
+                       array = item;
+               else {
+                       array = json_object_new_array();
+                       if (!array)
+                               goto error;
+                       json_object_array_add(array, item);
+                       json_object_object_add(object, name, array);
+               }
+               json_object_array_add(array, data);
+       }
+       return 0;
+ error:
+       json_object_put(data);
+       errno = ENOMEM;
+       return -1;
+}
+
 /*
  * Adds the field of 'name' and 'value' in 'priv' and also if possible in 'pub'
  * Returns 0 on success or -1 on error.
@@ -121,10 +156,10 @@ static int add_field(
 
        /* add the value */
        if (name[0] == '-') {
-               json_object_object_add(priv, &name[1], v);
+               append_field(priv, &name[1], v);
        } else {
-               json_object_object_add(priv, name, json_object_get(v));
-               json_object_object_add(pub, name, v);
+               append_field(priv, name, json_object_get(v));
+               append_field(pub, name, v);
        }
        return 0;
 }