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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// Copyright 2018 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

#![macro_use]
use std::collections::{
    BTreeMap,
};

use mentat_core::{
    DateTime,
    Entid,
    Keyword,
    Binding,
    TypedValue,
    Utc,
    ValueType,
};

use ::{
    HasSchema,
    Queryable,
    QueryInputs,
    QueryOutput,
    RelResult,
    Store,
    Variable,
};

use errors::{
    MentatError,
    Result,
};

pub struct QueryBuilder<'a> {
    query: String,
    values: BTreeMap<Variable, TypedValue>,
    types: BTreeMap<Variable, ValueType>,
    store: &'a mut Store,
}

impl<'a> QueryBuilder<'a> {
    pub fn new<T>(store: &'a mut Store, query: T) -> QueryBuilder where T: Into<String> {
        QueryBuilder { query: query.into(), values: BTreeMap::new(), types: BTreeMap::new(), store }
    }

    pub fn bind_value<T>(&mut self, var: &str, value: T) -> &mut Self where T: Into<TypedValue> {
        self.values.insert(Variable::from_valid_name(var), value.into());
        self
    }

    pub fn bind_ref_from_kw(&mut self, var: &str, value: Keyword) -> Result<&mut Self> {
        let entid = self.store.conn().current_schema().get_entid(&value).ok_or(MentatError::UnknownAttribute(value.to_string()))?;
        self.values.insert(Variable::from_valid_name(var), TypedValue::Ref(entid.into()));
        Ok(self)
    }

    pub fn bind_ref<T>(&mut self, var: &str, value: T) -> &mut Self where T: Into<Entid> {
       self.values.insert(Variable::from_valid_name(var), TypedValue::Ref(value.into()));
       self
    }

    pub fn bind_long(&mut self, var: &str, value: i64) -> &mut Self {
       self.values.insert(Variable::from_valid_name(var), TypedValue::Long(value));
       self
    }

    pub fn bind_instant(&mut self, var: &str, value: i64) -> &mut Self {
       self.values.insert(Variable::from_valid_name(var), TypedValue::instant(value));

       self
    }

    pub fn bind_date_time(&mut self, var: &str, value: DateTime<Utc>) -> &mut Self {
       self.values.insert(Variable::from_valid_name(var), TypedValue::Instant(value));
       self
    }

    pub fn bind_type(&mut self, var: &str, value_type: ValueType) -> &mut Self {
        self.types.insert(Variable::from_valid_name(var), value_type);
        self
    }

    pub fn execute(&mut self) -> Result<QueryOutput> {
        let values = ::std::mem::replace(&mut self.values, Default::default());
        let types = ::std::mem::replace(&mut self.types, Default::default());
        let query_inputs = QueryInputs::new(types, values)?;
        let read = self.store.begin_read()?;
        read.q_once(&self.query, query_inputs)
    }

    pub fn execute_scalar(&mut self) -> Result<Option<Binding>> {
        let results = self.execute()?;
        results.into_scalar().map_err(|e| e.into())
    }

    pub fn execute_coll(&mut self) -> Result<Vec<Binding>> {
        let results = self.execute()?;
        results.into_coll().map_err(|e| e.into())
    }

    pub fn execute_tuple(&mut self) -> Result<Option<Vec<Binding>>> {
        let results = self.execute()?;
        results.into_tuple().map_err(|e| e.into())
    }

    pub fn execute_rel(&mut self) -> Result<RelResult<Binding>> {
        let results = self.execute()?;
        results.into_rel().map_err(|e| e.into())
    }
}

#[cfg(test)]
mod test {
    use super::{
        QueryBuilder,
        TypedValue,
        Store,
    };

    #[test]
    fn test_scalar_query() {
        let mut store = Store::open("").expect("store connection");
        store.transact(r#"[
            [:db/add "s" :db/ident :foo/boolean]
            [:db/add "s" :db/valueType :db.type/boolean]
            [:db/add "s" :db/cardinality :db.cardinality/one]
        ]"#).expect("successful transaction");

        let report = store.transact(r#"[
            [:db/add "u" :foo/boolean true]
            [:db/add "p" :foo/boolean false]
        ]"#).expect("successful transaction");

        let yes = report.tempids.get("u").expect("found it").clone();

        let entid = QueryBuilder::new(&mut store, r#"[:find ?x .
                                                      :in ?v
                                                      :where [?x :foo/boolean ?v]]"#)
                              .bind_value("?v", true)
                              .execute_scalar().expect("ScalarResult")
                              .map_or(None, |t| t.into_entid());
        assert_eq!(entid, Some(yes));
    }

    #[test]
    fn test_coll_query() {
        let mut store = Store::open("").expect("store connection");
        store.transact(r#"[
            [:db/add "s" :db/ident :foo/boolean]
            [:db/add "s" :db/valueType :db.type/boolean]
            [:db/add "s" :db/cardinality :db.cardinality/one]
            [:db/add "t" :db/ident :foo/long]
            [:db/add "t" :db/valueType :db.type/long]
            [:db/add "t" :db/cardinality :db.cardinality/one]
        ]"#).expect("successful transaction");

        let report = store.transact(r#"[
            [:db/add "l" :foo/boolean true]
            [:db/add "l" :foo/long 25]
            [:db/add "m" :foo/boolean false]
            [:db/add "m" :foo/long 26]
            [:db/add "n" :foo/boolean true]
            [:db/add "n" :foo/long 27]
            [:db/add "p" :foo/boolean false]
            [:db/add "p" :foo/long 24]
            [:db/add "u" :foo/boolean true]
            [:db/add "u" :foo/long 23]
        ]"#).expect("successful transaction");

        let u_yes = report.tempids.get("u").expect("found it").clone();
        let l_yes = report.tempids.get("l").expect("found it").clone();
        let n_yes = report.tempids.get("n").expect("found it").clone();

        let entids: Vec<i64> = QueryBuilder::new(&mut store, r#"[:find [?x ...]
                                                                 :in ?v
                                                                 :where [?x :foo/boolean ?v]]"#)
                              .bind_value("?v", true)
                              .execute_coll().expect("CollResult")
                              .into_iter()
                              .map(|v| v.into_entid().expect("val"))
                              .collect();

        assert_eq!(entids, vec![l_yes, n_yes, u_yes]);
    }

    #[test]
    fn test_coll_query_by_row() {
        let mut store = Store::open("").expect("store connection");
        store.transact(r#"[
            [:db/add "s" :db/ident :foo/boolean]
            [:db/add "s" :db/valueType :db.type/boolean]
            [:db/add "s" :db/cardinality :db.cardinality/one]
            [:db/add "t" :db/ident :foo/long]
            [:db/add "t" :db/valueType :db.type/long]
            [:db/add "t" :db/cardinality :db.cardinality/one]
        ]"#).expect("successful transaction");

        let report = store.transact(r#"[
            [:db/add "l" :foo/boolean true]
            [:db/add "l" :foo/long 25]
            [:db/add "m" :foo/boolean false]
            [:db/add "m" :foo/long 26]
            [:db/add "n" :foo/boolean true]
            [:db/add "n" :foo/long 27]
            [:db/add "p" :foo/boolean false]
            [:db/add "p" :foo/long 24]
            [:db/add "u" :foo/boolean true]
            [:db/add "u" :foo/long 23]
        ]"#).expect("successful transaction");

        let n_yes = report.tempids.get("n").expect("found it").clone();

        let results = QueryBuilder::new(&mut store, r#"[:find [?x ...]
                                                        :in ?v
                                                        :where [?x :foo/boolean ?v]]"#)
                              .bind_value("?v", true)
                              .execute_coll().expect("CollResult");
        let entid = results.get(1).map_or(None, |t| t.to_owned().into_entid()).expect("entid");

        assert_eq!(entid, n_yes);
    }

    #[test]
    fn test_tuple_query_result_by_column() {
        let mut store = Store::open("").expect("store connection");
        store.transact(r#"[
            [:db/add "s" :db/ident :foo/boolean]
            [:db/add "s" :db/valueType :db.type/boolean]
            [:db/add "s" :db/cardinality :db.cardinality/one]
            [:db/add "t" :db/ident :foo/long]
            [:db/add "t" :db/valueType :db.type/long]
            [:db/add "t" :db/cardinality :db.cardinality/one]
        ]"#).expect("successful transaction");

        let report = store.transact(r#"[
            [:db/add "l" :foo/boolean true]
            [:db/add "l" :foo/long 25]
            [:db/add "m" :foo/boolean false]
            [:db/add "m" :foo/long 26]
            [:db/add "n" :foo/boolean true]
            [:db/add "n" :foo/long 27]
            [:db/add "p" :foo/boolean false]
            [:db/add "p" :foo/long 24]
            [:db/add "u" :foo/boolean true]
            [:db/add "u" :foo/long 23]
        ]"#).expect("successful transaction");

        let n_yes = report.tempids.get("n").expect("found it").clone();

        let results = QueryBuilder::new(&mut store, r#"[:find [?x, ?i]
                                                        :in ?v ?i
                                                        :where [?x :foo/boolean ?v]
                                                               [?x :foo/long ?i]]"#)
                              .bind_value("?v", true)
                              .bind_long("?i", 27)
                              .execute_tuple().expect("TupleResult").expect("Vec<TypedValue>");
        let entid = results.get(0).map_or(None, |t| t.to_owned().into_entid()).expect("entid");
        let long_val = results.get(1).map_or(None, |t| t.to_owned().into_long()).expect("long");

        assert_eq!(entid, n_yes);
        assert_eq!(long_val, 27);
    }

    #[test]
    fn test_tuple_query_result_by_iter() {
        let mut store = Store::open("").expect("store connection");
        store.transact(r#"[
            [:db/add "s" :db/ident :foo/boolean]
            [:db/add "s" :db/valueType :db.type/boolean]
            [:db/add "s" :db/cardinality :db.cardinality/one]
            [:db/add "t" :db/ident :foo/long]
            [:db/add "t" :db/valueType :db.type/long]
            [:db/add "t" :db/cardinality :db.cardinality/one]
        ]"#).expect("successful transaction");

        let report = store.transact(r#"[
            [:db/add "l" :foo/boolean true]
            [:db/add "l" :foo/long 25]
            [:db/add "m" :foo/boolean false]
            [:db/add "m" :foo/long 26]
            [:db/add "n" :foo/boolean true]
            [:db/add "n" :foo/long 27]
            [:db/add "p" :foo/boolean false]
            [:db/add "p" :foo/long 24]
            [:db/add "u" :foo/boolean true]
            [:db/add "u" :foo/long 23]
        ]"#).expect("successful transaction");

        let n_yes = report.tempids.get("n").expect("found it").clone();

        let results: Vec<_> = QueryBuilder::new(&mut store, r#"[:find [?x, ?i]
                                                                :in ?v ?i
                                                                :where [?x :foo/boolean ?v]
                                                                       [?x :foo/long ?i]]"#)
                              .bind_value("?v", true)
                              .bind_long("?i", 27)
                              .execute_tuple().expect("TupleResult").unwrap_or(vec![]);
        let entid = TypedValue::Ref(n_yes.clone()).into();
        let long_val = TypedValue::Long(27).into();

        assert_eq!(results, vec![entid, long_val]);
    }

    #[test]
    fn test_rel_query_result() {
        let mut store = Store::open("").expect("store connection");
        store.transact(r#"[
            [:db/add "s" :db/ident :foo/boolean]
            [:db/add "s" :db/valueType :db.type/boolean]
            [:db/add "s" :db/cardinality :db.cardinality/one]
            [:db/add "t" :db/ident :foo/long]
            [:db/add "t" :db/valueType :db.type/long]
            [:db/add "t" :db/cardinality :db.cardinality/one]
        ]"#).expect("successful transaction");

        let report = store.transact(r#"[
            [:db/add "l" :foo/boolean true]
            [:db/add "l" :foo/long 25]
            [:db/add "m" :foo/boolean false]
            [:db/add "m" :foo/long 26]
            [:db/add "n" :foo/boolean true]
            [:db/add "n" :foo/long 27]
        ]"#).expect("successful transaction");

        let l_yes = report.tempids.get("l").expect("found it").clone();
        let m_yes = report.tempids.get("m").expect("found it").clone();
        let n_yes = report.tempids.get("n").expect("found it").clone();

        #[derive(Debug, PartialEq)]
        struct Res {
            entid: i64,
            boolean: bool,
            long_val: i64,
        };

        let mut results: Vec<Res> = QueryBuilder::new(&mut store, r#"[:find ?x ?v ?i
                                                                      :where [?x :foo/boolean ?v]
                                                                             [?x :foo/long ?i]]"#)
                              .execute_rel().expect("RelResult")
                              .into_iter()
                              .map(|row| {
                                  Res {
                                      entid: row.get(0).map_or(None, |t| t.to_owned().into_entid()).expect("entid"),
                                      boolean: row.get(1).map_or(None, |t| t.to_owned().into_boolean()).expect("boolean"),
                                      long_val: row.get(2).map_or(None, |t| t.to_owned().into_long()).expect("long"),
                                  }
                              })
                              .collect();

        let res1 = results.pop().expect("res");
        assert_eq!(res1, Res { entid: n_yes, boolean: true, long_val: 27 });
        let res2 = results.pop().expect("res");
        assert_eq!(res2, Res { entid: m_yes, boolean: false, long_val: 26 });
        let res3 = results.pop().expect("res");
        assert_eq!(res3, Res { entid: l_yes, boolean: true, long_val: 25 });
        assert_eq!(results.pop(), None);
    }

    #[test]
    fn test_bind_ref() {
        let mut store = Store::open("").expect("store connection");
        store.transact(r#"[
            [:db/add "s" :db/ident :foo/boolean]
            [:db/add "s" :db/valueType :db.type/boolean]
            [:db/add "s" :db/cardinality :db.cardinality/one]
            [:db/add "t" :db/ident :foo/long]
            [:db/add "t" :db/valueType :db.type/long]
            [:db/add "t" :db/cardinality :db.cardinality/one]
        ]"#).expect("successful transaction");

        let report = store.transact(r#"[
            [:db/add "l" :foo/boolean true]
            [:db/add "l" :foo/long 25]
            [:db/add "m" :foo/boolean false]
            [:db/add "m" :foo/long 26]
            [:db/add "n" :foo/boolean true]
            [:db/add "n" :foo/long 27]
        ]"#).expect("successful transaction");

        let l_yes = report.tempids.get("l").expect("found it").clone();

        let results = QueryBuilder::new(&mut store, r#"[:find [?v ?i]
                                                        :in ?x
                                                        :where [?x :foo/boolean ?v]
                                                               [?x :foo/long ?i]]"#)
                              .bind_ref("?x", l_yes)
                              .execute_tuple().expect("TupleResult")
                              .unwrap_or(vec![]);
        assert_eq!(results.get(0).map_or(None, |t| t.to_owned().into_boolean()).expect("boolean"), true);
        assert_eq!(results.get(1).map_or(None, |t| t.to_owned().into_long()).expect("long"), 25);
    }
}