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
use ::safer_ffi::prelude::*;
use ::serde::ser::Serialize;

use crate::{error::DittoError, utils::zstr::ZString};

/// DQL query statement
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Query {
    pub(crate) inner_string: ZString,
}

impl TryFrom<&str> for Query {
    type Error = DittoError;
    fn try_from(query: &str) -> Result<Query, DittoError> {
        Self::try_from(query.to_string())
    }
}

impl TryFrom<String> for Query {
    type Error = DittoError;
    fn try_from(query: String) -> Result<Query, Self::Error> {
        // TODO(Ronan) Add check of the query when the ffi will offer such method.
        Ok(Self::new(query))
    }
}

impl Query {
    /// Inner constructor to  prepare the string for the FFI.
    fn new(query_str: String) -> Self {
        Self {
            inner_string: char_p::new(query_str).into(),
        }
    }

    /// Prepare Query for FFI layer
    pub(crate) fn prepare_ffi(&self) -> char_p::Ref<'_> {
        (&*self.inner_string).into()
    }
}

/// Arguments that can be used with an associated [`Query`].
/// Currently QueryArguments can only be created from types that implement
/// [`serde::Serialize`].
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct QueryArguments {
    cbor: Vec<u8>,
}

impl<T: Serialize> From<T> for QueryArguments {
    // (Ronan) It would be nice to only accept key-value data but it doesn't seem doable easily
    // with Serde.
    fn from(query_args: T) -> QueryArguments {
        // Unwrap should be safe because the provided input is Serialize.
        let cbor = serde_cbor::to_vec(&query_args).unwrap();
        Self { cbor }
    }
}

impl QueryArguments {
    pub(crate) fn cbor(&self) -> &[u8] {
        &self.cbor
    }
}