1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use crate::query::query_values::QueryValues;
use crate::DbElement;
use crate::DbId;
use crate::DbImpl;
use crate::DbKeyValue;
use crate::QueryError;
use crate::QueryId;
use crate::QueryIds;
use crate::QueryMut;
use crate::QueryResult;
use crate::StorageData;

/// Query to insert or update key-value pairs (properties)
/// to existing elements in the database. All `ids` must exist
/// in the database. If `values` is set to `Single` the properties
/// will be inserted uniformly to all `ids` otherwise there must be
/// enough `values` for all `ids`.
///
/// The result will be number of inserted/updated values and inserted new
/// elements (nodes).
///
/// NOTE: The result is NOT number of affected elements but individual properties.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[derive(Debug, PartialEq)]
pub struct InsertValuesQuery {
    /// Ids whose properties should be updated
    pub ids: QueryIds,

    /// Key value pairs to be inserted to the existing elements.
    pub values: QueryValues,
}

impl QueryMut for InsertValuesQuery {
    fn process<Store: StorageData>(
        &self,
        db: &mut DbImpl<Store>,
    ) -> Result<QueryResult, QueryError> {
        let mut result = QueryResult::default();

        match &self.ids {
            QueryIds::Ids(ids) => match &self.values {
                QueryValues::Single(values) => {
                    for id in ids {
                        insert_values(db, id, values, &mut result)?;
                    }
                }
                QueryValues::Multi(values) => {
                    if ids.len() != values.len() {
                        return Err(QueryError::from("Ids and values length do not match"));
                    }

                    for (id, values) in ids.iter().zip(values) {
                        insert_values(db, id, values, &mut result)?;
                    }
                }
            },
            QueryIds::Search(search_query) => {
                let db_ids = search_query.search(db)?;

                match &self.values {
                    QueryValues::Single(values) => {
                        for db_id in db_ids {
                            insert_values_id(db, db_id, values, &mut result)?;
                        }
                    }
                    QueryValues::Multi(values) => {
                        if db_ids.len() != values.len() {
                            return Err(QueryError::from("Ids and values length do not match"));
                        }

                        for (db_id, values) in db_ids.iter().zip(values) {
                            insert_values_id(db, *db_id, values, &mut result)?;
                        }
                    }
                }
            }
        }

        Ok(result)
    }
}

fn insert_values<Store: StorageData>(
    db: &mut DbImpl<Store>,
    id: &QueryId,
    values: &[DbKeyValue],
    result: &mut QueryResult,
) -> Result<(), QueryError> {
    match db.db_id(id) {
        Ok(db_id) => insert_values_id(db, db_id, values, result),
        Err(e) => match id {
            QueryId::Id(id) => {
                if id.0 == 0 {
                    insert_values_new(db, None, values, result)
                } else {
                    Err(e)
                }
            }
            QueryId::Alias(alias) => insert_values_new(db, Some(alias), values, result),
        },
    }
}

fn insert_values_new<Store: StorageData>(
    db: &mut DbImpl<Store>,
    alias: Option<&String>,
    values: &[DbKeyValue],
    result: &mut QueryResult,
) -> Result<(), QueryError> {
    let db_id = db.insert_node()?;

    if let Some(alias) = alias {
        db.insert_new_alias(db_id, alias)?;
    }

    for key_value in values {
        db.insert_key_value(db_id, key_value)?;
    }

    result.result += values.len() as i64;
    result.elements.push(DbElement {
        id: db_id,
        from: None,
        to: None,
        values: vec![],
    });

    Ok(())
}

fn insert_values_id<Store: StorageData>(
    db: &mut DbImpl<Store>,
    db_id: DbId,
    values: &[DbKeyValue],
    result: &mut QueryResult,
) -> Result<(), QueryError> {
    for key_value in values {
        db.insert_or_replace_key_value(db_id, key_value)?;
        result.result += 1;
    }
    Ok(())
}