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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use bytes::Bytes;

use edgedb_protocol::QueryResult;
use edgedb_protocol::query_arg::QueryArgs;
use edgedb_protocol::descriptors::OutputTypedesc;
use edgedb_protocol::client_message::{Cardinality, IoFormat};

use crate::errors::{Error, NoResultExpected, NoDataError, ErrorKind};
use crate::Client;
use crate::client::StatementParams;
use crate::model::Json;


/// Result returned from [`execute()`][Executor#method.execute] call
#[derive(Debug, Clone)]
pub struct ExecuteResult {
    pub(crate) marker: Bytes,
}

struct Statement<'a, A> {
    params: StatementParams,
    query: &'a str,
    arguments: &'a A,
}

pub struct GenericResult {
    pub(crate) descriptor: OutputTypedesc,
    pub(crate) data: Vec<Bytes>,
    pub(crate) completion: Bytes,
}

pub trait GenericQuery: Send + Sync {
    fn query(&self) -> &str;
    fn arguments(&self) -> &dyn QueryArgs;
    fn params(&self) -> &StatementParams;
}

pub trait Encoder: Send + Sync {
}
pub trait Decoder: Send + Sync {
}
pub trait Decodable {
}
#[async_trait::async_trait]
pub trait Sealed {
    async fn query_dynamic(&mut self, query: &dyn GenericQuery)
        -> Result<GenericResult, Error>;
}

/// Main trait that allows executing queries
///
/// Note comparing to [Client] this trait has `&mut self` for query methods.
/// This is because we need to support [Executor] for a transaction.
/// To overcome this issue for [Client] you can either use inherent methods on
/// pool rather than this trait or just clone it (cloning [Client] is cheap):
///
/// ```rust,ignore
/// do_query(&mut global_pool_reference.clone())?;
/// ```
/// Note: due to limitations of Rust type system, the query methods are
/// part of inherent implementation for `dyn Executor` itself, not in the trait
/// itself. This should not be a problem in most cases.
///
/// This trait is sealed (no imlementation can be done outside of this crate),
/// since we don't want to expose too much implementation details for now.
pub trait Executor: Sealed {
}

#[async_trait::async_trait]
impl Sealed for Client {
    async fn query_dynamic(&mut self, query: &dyn GenericQuery)
        -> Result<GenericResult, Error>
    {
        // TODO(tailhook) retry loop
        let mut conn = self.inner.acquire().await?;
        conn.query_dynamic(query).await
    }
}

impl Executor for Client {}

impl dyn Executor + '_ {
    /// Execute a query returning a list of arguments
    ///
    /// Most of the times you have to specify return type for the query:
    ///
    /// ```rust,ignore
    /// let greeting = pool.query::<String, _>("SELECT 'hello'", &());
    /// // or
    /// let greeting: Vec<String> = pool.query("SELECT 'hello'", &());
    /// ```
    ///
    /// This method can be used both with static arguments, like a tuple of
    /// scalars. And with dynamic arguments [`edgedb_protocol::value::Value`].
    /// Similarly dynamically typed results are also suported.
    pub async fn query<R, A>(&mut self, query: &str, arguments: &A)
        -> Result<Vec<R>, Error>
        where A: QueryArgs,
              R: QueryResult,
    {
        let result = self.query_dynamic(&Statement {
            params: StatementParams::new(),
            query,
            arguments,
        }).await?;
        match result.descriptor.root_pos() {
            Some(root_pos) => {
                let ctx = result.descriptor.as_queryable_context();
                let mut state = R::prepare(&ctx, root_pos)?;
                let mut res = Vec::with_capacity(result.data.len());
                for datum in result.data.into_iter() {
                    res.push(R::decode(&mut state, &datum)?);
                }
                Ok(res)
            }
            None => {
                Err(NoResultExpected::with_message(
                    String::from_utf8_lossy(&result.completion[..])
                    .to_string()))?
            }
        }
    }

    /// Execute a query returning a single result
    ///
    /// Most of the times you have to specify return type for the query:
    ///
    /// ```rust,ignore
    /// let greeting = pool.query::<String, _>("SELECT 'hello'", &());
    /// // or
    /// let greeting: String = pool.query("SELECT 'hello'", &());
    /// ```
    ///
    /// The query must return exactly one element. If the query returns more
    /// than one element, an
    /// [`ResultCardinalityMismatchError`][crate::errors::ResultCardinalityMismatchError]
    /// is raised, if it returns an empty set, an
    /// [`NoDataError`][crate::errors::NoDataError] is raised.
    ///
    /// This method can be used both with static arguments, like a tuple of
    /// scalars. And with dynamic arguments [`edgedb_protocol::value::Value`].
    /// Similarly dynamically typed results are also suported.
    pub async fn query_single<R, A>(&mut self, query: &str, arguments: &A)
        -> Result<R, Error>
        where A: QueryArgs,
              R: QueryResult,
    {
        let result = self.query_dynamic(&Statement {
            params: StatementParams::new()
                .cardinality(Cardinality::AtMostOne)
                .clone(),
            query,
            arguments,
        }).await?;
        match result.descriptor.root_pos() {
            Some(root_pos) => {
                let ctx = result.descriptor.as_queryable_context();
                let mut state = R::prepare(&ctx, root_pos)?;
                if result.data.len() == 0 {
                    return Err(NoDataError::with_message(
                        "query_single() returned zero results"))
                }
                return Ok(R::decode(&mut state, &result.data[0])?)
            }
            None => {
                Err(NoResultExpected::with_message(
                    String::from_utf8_lossy(&result.completion[..])
                    .to_string()))?
            }
        }
    }

    /// Execute a query returning result as a JSON
    pub async fn query_json<A>(&mut self, query: &str, arguments: &A)
        -> Result<Json, Error>
        where A: QueryArgs,
    {
        let result = self.query_dynamic(&Statement {
            params: StatementParams::new()
                .io_format(IoFormat::Json)
                .clone(),
            query,
            arguments,
        }).await?;
        match result.descriptor.root_pos() {
            Some(root_pos) => {
                let ctx = result.descriptor.as_queryable_context();
                let mut state = <String as QueryResult>
                    ::prepare(&ctx, root_pos)?;
                if result.data.len() == 0 {
                    return Err(NoDataError::with_message(
                        "query_json() returned zero results"))
                }
                let data = <String as QueryResult>::decode(
                    &mut state, &result.data[0])?;
                // trust database to produce valid JSON
                let json = unsafe { Json::new_unchecked(data) };
                return Ok(json)
            }
            None => {
                Err(NoResultExpected::with_message(
                    String::from_utf8_lossy(&result.completion[..])
                    .to_string()))?
            }
        }
    }

    /// Run a singleton-returning query and return its element in JSON
    ///
    /// The query must return exactly one element. If the query returns more
    /// than one element, an
    /// [`ResultCardinalityMismatchError`][crate::errors::ResultCardinalityMismatchError]
    /// is raised, if it returns an empty set, an
    /// [`NoDataError`][crate::errors::NoDataError] is raised.
    pub async fn query_single_json<A>(&mut self, query: &str, arguments: &A)
        -> Result<Json, Error>
        where A: QueryArgs,
    {
        let result = self.query_dynamic(&Statement {
            params: StatementParams::new()
                .io_format(IoFormat::Json)
                .cardinality(Cardinality::AtMostOne)
                .clone(),
            query,
            arguments,
        }).await?;
        match result.descriptor.root_pos() {
            Some(root_pos) => {
                let ctx = result.descriptor.as_queryable_context();
                let mut state = <String as QueryResult>
                    ::prepare(&ctx, root_pos)?;
                if result.data.len() == 0 {
                    return Err(NoDataError::with_message(
                        "query_single_json() returned zero results"))
                }
                let data = <String as QueryResult>::decode(
                    &mut state, &result.data[0])?;
                // trust database to produce valid JSON
                let json = unsafe { Json::new_unchecked(data) };
                return Ok(json)
            }
            None => {
                Err(NoResultExpected::with_message(
                    String::from_utf8_lossy(&result.completion[..])
                    .to_string()))?
            }
        }
    }
    /// Execute an EdgeQL command (or commands).
    ///
    /// Note: If the results of query are desired, [`query()`][Client::query] or
    /// [`query_single()`][Client::query_single] should be used instead.
    pub async fn execute<A>(&mut self, query: &str, arguments: &A)
        -> Result<ExecuteResult, Error>
        where A: QueryArgs,
    {
        let result = self.query_dynamic(&Statement {
            params: StatementParams::new(),
            query,
            arguments,
        }).await?;
        // Dropping the actual results
        return Ok(ExecuteResult { marker: result.completion });
    }
}

impl<A: QueryArgs + Send + Sync + Sized> GenericQuery for Statement<'_, A> {
    fn query(&self) -> &str {
        &self.query
    }
    fn arguments(&self) -> &dyn QueryArgs {
        self.arguments
    }
    fn params(&self) -> &StatementParams {
        &self.params
    }
}