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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
#[allow(deprecated)]
use crate::{
    filter::Filter,
    filter_builder::Reader,
    internal::{EmbeddedDescription, Projection},
    Fetch, FilterBuilder, IntoResult, OwnedSytx, Persistent, PersistentEmbedded, Ref, Snapshot, Structsy,
};
/// Iterator for query results
pub struct StructsyIter<'a, T> {
    iterator: Box<dyn Iterator<Item = T> + 'a>,
}

impl<'a, T> StructsyIter<'a, T> {
    pub fn new<I>(iterator: I) -> StructsyIter<'a, T>
    where
        I: Iterator<Item = T>,
        I: 'a,
    {
        StructsyIter {
            iterator: Box::new(iterator),
        }
    }
}

impl<'a, T> Iterator for StructsyIter<'a, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.iterator.next()
    }
}

/// And/Or/Not Operators
/// # Example
/// ```
/// use structsy::{ Structsy, StructsyTx, StructsyError, Operators};
/// use structsy_derive::{queries, Persistent};
/// #[derive(Persistent)]
/// struct Basic {
///     name: String,
/// }
/// impl Basic {
///     fn new(name: &str) -> Basic {
///         Basic { name: name.to_string() }
///     }
/// }
///
/// #[queries(Basic)]
/// trait BasicQuery {
///      fn by_name(self, name: String) -> Self;
/// }
///
///
/// fn basic_query() -> Result<(), StructsyError> {
///     let structsy = Structsy::open("file.structsy")?;
///     structsy.define::<Basic>()?;
///     let mut tx = structsy.begin()?;
///     tx.insert(&Basic::new("aaa"))?;
///     tx.insert(&Basic::new("bbb"))?;
///     tx.commit()?;
///     let count = structsy.query::<Basic>().or(|or| {
///             or.by_name("aaa".to_string()).by_name("bbb".to_string())
///         }).fetch().count();
///     assert_eq!(count, 2);
///     let count = structsy.query::<Basic>().not(|not| {
///             not.by_name("aaa".to_string())
///         }).fetch().count();
///     assert_eq!(count, 1);
///     let count = structsy.query::<Basic>().and(|and| {
///             and.by_name("aaa".to_string()).by_name("bbb".to_string())
///         }).fetch().count();
///     assert_eq!(count, 0);
///     Ok(())
/// }
/// ```
pub trait Operators<F> {
    fn or<FN: Fn(F) -> F>(self, builder: FN) -> Self;
    fn and<FN: Fn(F) -> F>(self, builder: FN) -> Self;
    fn not<FN: Fn(F) -> F>(self, builder: FN) -> Self;
}

pub trait EmbeddedQuery<T: PersistentEmbedded + 'static>: Sized {
    fn filter_builder(&mut self) -> &mut FilterBuilder<T>;
    fn add_group(&mut self, filter: Filter<T>);
}

impl<T: EmbeddedDescription + 'static, Q: EmbeddedQuery<T>> Operators<Filter<T>> for Q {
    fn or<FN: Fn(Filter<T>) -> Filter<T>>(mut self, builder: FN) -> Self {
        self.filter_builder().or(builder(Filter::<T>::new()).extract_filter());
        self
    }
    fn and<FN: Fn(Filter<T>) -> Filter<T>>(mut self, builder: FN) -> Self {
        self.filter_builder().and(builder(Filter::<T>::new()).extract_filter());
        self
    }
    fn not<FN: Fn(Filter<T>) -> Filter<T>>(mut self, builder: FN) -> Self {
        self.filter_builder().not(builder(Filter::<T>::new()).extract_filter());
        self
    }
}

pub struct ProjectionResult<P, T> {
    filter: FilterBuilder<T>,
    phantom: std::marker::PhantomData<P>,
}
impl<P, T> ProjectionResult<P, T> {
    pub(crate) fn new(filter: FilterBuilder<T>) -> Self {
        Self {
            filter,
            phantom: std::marker::PhantomData,
        }
    }
}

impl<P: Projection<T>, T: Persistent + 'static> Fetch<P> for ProjectionResult<P, T> {
    fn into(self, structsy: &Structsy) -> StructsyIter<P> {
        self.fetch(structsy)
    }

    fn into_tx(self, tx: &mut OwnedSytx) -> StructsyIter<P> {
        self.fetch_tx(tx)
    }

    fn fetch(self, structsy: &Structsy) -> StructsyIter<P> {
        let data = self.filter.finish(Reader::Structsy(structsy.clone()));
        StructsyIter::new(Box::new(data.map(|(_, r)| Projection::projection(&r))))
    }

    fn fetch_tx(self, tx: &mut OwnedSytx) -> StructsyIter<P> {
        let data = self.filter.finish(Reader::Tx(tx.reference()));
        StructsyIter::new(Box::new(data.map(|(_, r)| Projection::projection(&r))))
    }

    fn fetch_snapshot(self, snapshot: &Snapshot) -> StructsyIter<P> {
        let data = self.filter.finish(Reader::Snapshot(snapshot.clone()));
        StructsyIter::new(Box::new(data.map(|(_, r)| Projection::projection(&r))))
    }
}

#[allow(deprecated)]
impl<P: Projection<T>, T: Persistent + 'static> IntoResult<P> for ProjectionResult<P, T> {}

#[allow(deprecated)]
impl<T: Persistent + 'static> IntoResult<(Ref<T>, T)> for Filter<T> {}

/// Base trait for all the query types
pub trait Query<T: Persistent + 'static>: Sized {
    fn filter_builder(&mut self) -> &mut FilterBuilder<T>;
    fn add_group(&mut self, filter: Filter<T>);
}

/// A query to be executed on a specific snapshot
pub struct SnapshotQuery<T> {
    pub(crate) snapshot: Snapshot,
    pub(crate) builder: FilterBuilder<T>,
}

impl<T: Persistent + 'static> IntoIterator for SnapshotQuery<T> {
    type Item = (Ref<T>, T);
    type IntoIter = StructsyIter<'static, (Ref<T>, T)>;
    fn into_iter(self) -> Self::IntoIter {
        StructsyIter::new(self.builder.finish(Reader::Snapshot(self.snapshot)))
    }
}

impl<T: Persistent + 'static> Query<T> for SnapshotQuery<T> {
    fn filter_builder(&mut self) -> &mut FilterBuilder<T> {
        &mut self.builder
    }
    fn add_group(&mut self, filter: Filter<T>) {
        let base = self.filter_builder();
        base.and_filter(filter.extract_filter());
    }
}
impl<T: Persistent + 'static> SnapshotQuery<T> {
    pub(crate) fn builder(self) -> FilterBuilder<T> {
        self.builder
    }
    pub fn projection<P: Projection<T>>(self) -> ProjectionSnapshotQuery<P, T> {
        ProjectionSnapshotQuery {
            builder: self.builder,
            snapshot: self.snapshot,
            phantom: std::marker::PhantomData,
        }
    }

    pub fn fetch(self) -> StructsyIter<'static, (Ref<T>, T)> {
        StructsyIter::new(self.builder.finish(Reader::Snapshot(self.snapshot)))
    }
}

pub struct ProjectionSnapshotQuery<P, T> {
    builder: FilterBuilder<T>,
    snapshot: Snapshot,
    phantom: std::marker::PhantomData<P>,
}

impl<P: Projection<T>, T: Persistent + 'static> ProjectionSnapshotQuery<P, T> {
    pub fn fetch(self) -> StructsyIter<'static, P> {
        let data = self.builder.finish(Reader::Snapshot(self.snapshot));
        StructsyIter::new(Box::new(data.map(|(_, r)| Projection::projection(&r))))
    }
}

impl<P: Projection<T>, T: Persistent + 'static> IntoIterator for ProjectionSnapshotQuery<P, T> {
    type Item = P;
    type IntoIter = StructsyIter<'static, P>;
    fn into_iter(self) -> Self::IntoIter {
        let data = self.builder.finish(Reader::Snapshot(self.snapshot));
        StructsyIter::new(Box::new(data.map(|(_, r)| Projection::projection(&r))))
    }
}

/// Query for a persistent struct
///
/// # Example
/// ```
/// use structsy::{ Structsy, StructsyTx, StructsyError};
/// use structsy_derive::{queries, Persistent};
/// #[derive(Persistent)]
/// struct Basic {
///     name: String,
/// }
/// impl Basic {
///     fn new(name: &str) -> Basic {
///         Basic { name: name.to_string() }
///     }
/// }
///
/// #[queries(Basic)]
/// trait BasicQuery {
///      fn by_name(self, name: String) -> Self;
/// }
///
///
/// fn basic_query() -> Result<(), StructsyError> {
///     let structsy = Structsy::open("file.structsy")?;
///     structsy.define::<Basic>()?;
///     let mut tx = structsy.begin()?;
///     tx.insert(&Basic::new("aaa"))?;
///     tx.commit()?;
///     let count = structsy.query::<Basic>().by_name("aaa".to_string()).fetch().count();
///     assert_eq!(count, 1);
///     Ok(())
/// }
/// ```
pub struct StructsyQuery<T: Persistent + 'static> {
    pub(crate) structsy: Structsy,
    pub(crate) builder: FilterBuilder<T>,
}

impl<T: Persistent + 'static> Query<T> for StructsyQuery<T> {
    fn filter_builder(&mut self) -> &mut FilterBuilder<T> {
        &mut self.builder
    }
    fn add_group(&mut self, filter: Filter<T>) {
        let base = self.filter_builder();
        base.and_filter(filter.extract_filter());
    }
}
impl<T: Persistent + 'static> StructsyQuery<T> {
    pub(crate) fn builder(self) -> FilterBuilder<T> {
        self.builder
    }
    pub fn projection<P: Projection<T>>(self) -> ProjectionQuery<P, T> {
        ProjectionQuery {
            builder: self.builder,
            structsy: self.structsy,
            phantom: std::marker::PhantomData,
        }
    }

    pub fn fetch(self) -> StructsyIter<'static, (Ref<T>, T)> {
        StructsyIter::new(self.builder.finish(Reader::Structsy(self.structsy.clone())))
    }
}

impl<T: Persistent> IntoIterator for StructsyQuery<T> {
    type Item = (Ref<T>, T);
    type IntoIter = StructsyIter<'static, (Ref<T>, T)>;
    fn into_iter(self) -> Self::IntoIter {
        StructsyIter::new(self.builder.finish(Reader::Structsy(self.structsy.clone())))
    }
}

pub struct ProjectionQuery<P: Projection<T>, T> {
    builder: FilterBuilder<T>,
    structsy: Structsy,
    phantom: std::marker::PhantomData<P>,
}

impl<P: Projection<T>, T: Persistent + 'static> ProjectionQuery<P, T> {
    pub fn fetch(self) -> StructsyIter<'static, P> {
        let data = self.builder.finish(Reader::Structsy(self.structsy.clone()));
        StructsyIter::new(Box::new(data.map(|(_, r)| Projection::projection(&r))))
    }
}

impl<P: Projection<T>, T: Persistent + 'static> IntoIterator for ProjectionQuery<P, T> {
    type Item = P;
    type IntoIter = StructsyIter<'static, P>;
    fn into_iter(self) -> Self::IntoIter {
        let data = self.builder.finish(Reader::Structsy(self.structsy.clone()));
        StructsyIter::new(Box::new(data.map(|(_, r)| Projection::projection(&r))))
    }
}

/// Query for a persistent struct considering in transaction changes.
///
/// # Example
/// ```
/// use structsy::{ Structsy, StructsyTx, StructsyError};
/// use structsy_derive::{queries, Persistent};
/// #[derive(Persistent)]
/// struct Basic {
///     name: String,
/// }
/// impl Basic {
///     fn new(name: &str) -> Basic {
///         Basic { name: name.to_string() }
///     }
/// }
///
/// #[queries(Basic)]
/// trait BasicQuery {
///     fn by_name(self, name: String) -> Self;
/// }
///
///
/// fn basic_query() -> Result<(), StructsyError> {
///     let structsy = Structsy::open("file.structsy")?;
///     structsy.define::<Basic>()?;
///     let mut tx = structsy.begin()?;
///     tx.insert(&Basic::new("aaa"))?;
///     let count = tx.query::<Basic>().by_name("aaa".to_string()).fetch().count();
///     assert_eq!(count, 1);
///     tx.commit()?;
///     Ok(())
/// }
/// ```
///
pub struct StructsyQueryTx<'a, T: Persistent + 'static> {
    pub(crate) tx: &'a mut OwnedSytx,
    pub(crate) builder: FilterBuilder<T>,
}

impl<'a, T: Persistent + 'static> Query<T> for StructsyQueryTx<'a, T> {
    fn filter_builder(&mut self) -> &mut FilterBuilder<T> {
        &mut self.builder
    }
    fn add_group(&mut self, filter: Filter<T>) {
        let base = self.filter_builder();
        base.and_filter(filter.extract_filter());
    }
}
impl<'a, T: Persistent> StructsyQueryTx<'a, T> {
    /// Make a projection from filtered structs.
    ///
    ///
    /// # Example
    /// ```rust
    /// use structsy::{ Structsy, StructsyTx, StructsyError, Filter};
    /// use structsy_derive::{queries, Projection, Persistent};
    ///
    /// #[derive(Persistent)]
    /// struct Person {
    ///     name:String,
    ///     surname:String,
    /// }
    ///
    /// impl Person {
    ///     fn new(name:&str, surname:&str) -> Self {
    ///         Person {
    ///             name: name.to_string(),
    ///             surname: surname.to_string(),
    ///         }
    ///     }
    /// }
    ///
    /// #[queries(Person)]
    /// trait PersonQuery {
    ///     fn by_name(self, name:&str) -> Self;
    /// }
    ///
    /// #[derive(Projection)]
    /// #[projection = "Person" ]
    /// struct NameProjection {
    ///     name:String,
    /// }
    ///
    ///
    /// fn main() -> Result<(), StructsyError> {
    ///     let structsy = Structsy::memory()?;
    ///     structsy.define::<Person>()?;
    ///     let mut tx = structsy.begin()?;
    ///     tx.insert(&Person::new("a_name", "a_surname"))?;
    ///     tx.commit()?;
    ///     let query = structsy.query::<Person>().by_name("a_name").projection::<NameProjection>();
    ///     assert_eq!(query.fetch().next().unwrap().name, "a_name");
    ///     Ok(())
    /// }
    /// ```
    pub fn projection<P: Projection<T>>(self) -> ProjectionQueryTx<'a, P, T> {
        ProjectionQueryTx {
            tx: self.tx,
            builder: self.builder,
            phantom: std::marker::PhantomData,
        }
    }

    pub fn fetch(self) -> StructsyIter<'a, (Ref<T>, T)> {
        StructsyIter::new(self.builder.finish(Reader::Tx(self.tx.reference())))
    }
}
pub struct ProjectionQueryTx<'a, P, T> {
    tx: &'a mut OwnedSytx,
    builder: FilterBuilder<T>,
    phantom: std::marker::PhantomData<P>,
}

impl<'a, P: Projection<T>, T: Persistent + 'static> ProjectionQueryTx<'a, P, T> {
    pub fn fetch(self) -> StructsyIter<'a, P> {
        let data = self.builder.finish(Reader::Tx(self.tx.reference()));
        StructsyIter::new(Box::new(data.map(|(_, r)| Projection::projection(&r))))
    }
}

impl<'a, P: Projection<T>, T: Persistent + 'static> IntoIterator for ProjectionQueryTx<'a, P, T> {
    type Item = P;
    type IntoIter = StructsyIter<'a, P>;
    fn into_iter(self) -> Self::IntoIter {
        let data = self.builder.finish(Reader::Tx(self.tx.reference()));
        StructsyIter::new(Box::new(data.map(|(_, r)| Projection::projection(&r))))
    }
}

impl<'a, T: Persistent> IntoIterator for StructsyQueryTx<'a, T> {
    type Item = (Ref<T>, T);
    type IntoIter = StructsyIter<'a, (Ref<T>, T)>;
    fn into_iter(self) -> Self::IntoIter {
        StructsyIter::new(self.builder.finish(Reader::Tx(self.tx.reference())))
    }
}

pub struct StructsyFilter<T: Persistent> {
    filter: Filter<T>,
}

impl<T: Persistent + 'static> StructsyFilter<T> {
    pub fn new() -> StructsyFilter<T> {
        StructsyFilter {
            filter: Filter::<T>::new(),
        }
    }
}
impl<T: Persistent + 'static> Query<T> for StructsyFilter<T> {
    fn filter_builder(&mut self) -> &mut FilterBuilder<T> {
        self.filter.filter_builder()
    }
    fn add_group(&mut self, filter: Filter<T>) {
        self.filter.add_group(filter)
    }
}

impl<T: Persistent + 'static, Q: Query<T>> Operators<StructsyFilter<T>> for Q {
    fn or<FN: Fn(StructsyFilter<T>) -> StructsyFilter<T>>(mut self, builder: FN) -> Self {
        self.filter_builder()
            .or(builder(StructsyFilter::<T>::new()).filter.extract_filter());
        self
    }
    fn and<FN: Fn(StructsyFilter<T>) -> StructsyFilter<T>>(mut self, builder: FN) -> Self {
        self.filter_builder()
            .and(builder(StructsyFilter::<T>::new()).filter.extract_filter());
        self
    }
    fn not<FN: Fn(StructsyFilter<T>) -> StructsyFilter<T>>(mut self, builder: FN) -> Self {
        self.filter_builder()
            .not(builder(StructsyFilter::<T>::new()).filter.extract_filter());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::Query;
    use crate::{
        actions::EqualAction,
        internal::{Description, Field},
        Filter, Persistent, Ref, SRes, Sytx,
    };

    use std::io::{Read, Write};
    struct ToQuery {
        first: String,
        second: Vec<String>,
    }
    impl Persistent for ToQuery {
        fn get_name() -> &'static str {
            "ToQuery"
        }
        fn get_description() -> Description {
            let fields = [
                crate::internal::FieldDescription::new::<String>(0u32, "first", None),
                crate::internal::FieldDescription::new::<Vec<String>>(2u32, "second", None),
            ];
            Description::Struct(crate::internal::StructDescription::new("ToQuery", &fields))
        }
        fn read(_read: &mut dyn Read) -> SRes<Self>
        where
            Self: std::marker::Sized,
        {
            unimplemented!()
        }
        fn remove_indexes(&self, _tx: &mut dyn Sytx, _id: &Ref<Self>) -> SRes<()>
        where
            Self: std::marker::Sized,
        {
            unimplemented!()
        }
        fn write(&self, _write: &mut dyn Write) -> SRes<()> {
            unimplemented!()
        }
        fn put_indexes(&self, _tx: &mut dyn Sytx, _id: &Ref<Self>) -> SRes<()>
        where
            Self: std::marker::Sized,
        {
            unimplemented!()
        }
        fn declare(_db: &mut dyn Sytx) -> SRes<()> {
            unimplemented!()
        }
    }
    impl ToQuery {
        pub fn field_first() -> Field<Self, String> {
            Field::<ToQuery, String>::new("first", |x| &x.first)
        }
        pub fn field_second() -> Field<Self, Vec<String>> {
            Field::<ToQuery, Vec<String>>::new("second", |x| &x.second)
        }
    }

    trait MyQuery {
        fn by_name(self, first: String) -> Self;
        fn by_second(self, second: String) -> Self;
        fn by_first_and_second(self, first: String, second: String) -> Self;
    }

    impl MyQuery for Filter<ToQuery> {
        fn by_name(mut self, first: String) -> Self {
            let builder = self.filter_builder();
            EqualAction::equal((ToQuery::field_first(), builder), first);
            self
        }
        fn by_second(mut self, second: String) -> Self {
            let builder = self.filter_builder();
            EqualAction::equal((ToQuery::field_second(), builder), second);
            self
        }
        fn by_first_and_second(mut self, first: String, second: String) -> Self {
            EqualAction::equal((ToQuery::field_first(), self.filter_builder()), first);
            EqualAction::equal((ToQuery::field_second(), self.filter_builder()), second);
            self
        }
    }
    #[test]
    fn test_query_build() {
        let filter = Filter::<ToQuery>::new();
        filter.by_name("one".to_string()).by_second("second".to_string());
    }
}