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
use edgedb_protocol::value::Value;
use crate::{ToEdgeQl, ToEdgeQuery, ToEdgeValue};


const UNLESS_CONFLICT: &'static str = " unless conflict ";
const ON: &'static str = "on ";
const OPEN_PARENTHESIS: &'static str = "( ";
const CLOSE_PARENTHESIS: &'static str = " )";
const COMMA: &'static str = ", ";
const ELSE: &'static str = " else ( ";

/// Conflict trait represents an 'unless conflict' statement in an edgeDB query
pub trait Conflict<T: ToEdgeQuery + Clone> {
    fn fields(&self) -> Option<Vec<&str>>;
    fn else_query(&self) -> Option<T>;
}

/// InsertConflict struct
pub struct UnlessConflictElse<T: ToEdgeQuery> {
    pub fields: Option<Vec<&'static str>>,
    pub else_query: Option<T>
}

impl<T: ToEdgeQuery + Clone> Conflict<T> for UnlessConflictElse<T> {

    fn fields(&self) -> Option<Vec<&str>> {
        self.fields.clone()
    }

    fn else_query(&self) -> Option<T> {
        self.else_query.clone()
    }
}


/// DefaultInsertConflict struct
pub struct UnlessConflict {
    pub fields: Option<Vec<&'static str>>,
}

#[derive(Clone)]
pub struct EmptyQuery;

impl ToEdgeQl for EmptyQuery {
    fn to_edgeql(&self) -> String {
        String::default()
    }
}

impl ToEdgeValue for EmptyQuery {
    fn to_edge_value(&self) -> Value {
        Value::Nothing
    }
}

impl ToEdgeQuery for EmptyQuery{}

impl Conflict<EmptyQuery> for UnlessConflict {

    fn fields(&self) -> Option<Vec<&str>> {
        self.fields.clone()
    }

    fn else_query(&self) -> Option<EmptyQuery> {
        None
    }
}


/// parse a conflict into a string statement
///
/// ## Examples
///
/// ```
///use edgedb_protocol::value::Value;
///use edgedb_query::queries::conflict::{UnlessConflictElse, Conflict, parse_conflict};
///use edgedb_query::{ToEdgeQl, ToEdgeQuery, ToEdgeValue};
///
///#[derive(Clone)]
///pub struct FindUser {}
///
///impl ToEdgeQl for FindUser {
///   fn to_edgeql(&self) -> String {
///       format!("select users")
///   }
///}
///
///impl ToEdgeValue for FindUser {
///   fn to_edge_value(&self) -> Value {
///       Value::Nothing
///   }
///}
///
///impl ToEdgeQuery for FindUser  {}
///
///fn main() {
///   let insert_conflict = UnlessConflictElse {
///       fields: Some(vec!["name", "age"]),
///       else_query: Some(FindUser{}),
///   };
///
///   let stmt = parse_conflict(&insert_conflict, vec![]);
///
///    assert_eq!(stmt, " unless conflict on ( .name, .age ) else ( select users )");
/// }
/// ```
pub fn parse_conflict<T: ToEdgeQuery + Clone, R: Conflict<T>>(conflict: &R, query_fields: Vec<&str>) -> String {
    let mut stmt = UNLESS_CONFLICT.to_owned();

    if let Some(fields) = conflict.fields() {

        if fields.iter().any(|f| !query_fields.contains(f)) {
            panic!("Unless conflict fields must be one of : {:#?}", query_fields)
        }

        stmt.push_str(ON);

        if fields.len() > 1 {
            stmt.push_str(OPEN_PARENTHESIS);
        }
        stmt.push_str(fields
            .iter()
            .map(|s| format!(".{}", s))
            .collect::<Vec<String>>()
            .join(COMMA).as_str()
        );
        if fields.len() > 1 {
            stmt.push_str(CLOSE_PARENTHESIS);
        }

        if let Some(else_query)= conflict.else_query() {
            stmt.push_str(ELSE);
            stmt.push_str(else_query.to_edgeql().as_str());
            stmt.push_str(CLOSE_PARENTHESIS);
        }
    }

    stmt
}