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
use crate::{Fetch, FilterBuilder, Persistent, Ref, SRes, StructsyImpl, StructsyIter, StructsyQueryTx};
use persy::Transaction;
use std::{io::Cursor, marker::PhantomData, sync::Arc};

/// Owned transation to use with [`StructsyTx`] trait
///
/// [`StructsyTx`]: trait.StructsyTx.html
pub struct OwnedSytx {
    pub(crate) structsy_impl: Arc<StructsyImpl>,
    pub(crate) trans: Transaction,
}

impl OwnedSytx {
    /// 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 fn query<T: Persistent>(&mut self) -> StructsyQueryTx<T> {
        StructsyQueryTx {
            tx: self,
            builder: FilterBuilder::new(),
        }
    }

    pub fn into_iter<R: Fetch<T>, T>(&mut self, filter: R) -> StructsyIter<T> {
        filter.fetch_tx(self)
    }
    pub(crate) fn reference(&mut self) -> RefSytx {
        RefSytx {
            trans: &mut self.trans,
            structsy_impl: self.structsy_impl.clone(),
        }
    }
}

/// Reference transaction to use with [`StructsyTx`] trait
///
/// [`StructsyTx`]: trait.StructsyTx.html
pub struct RefSytx<'a> {
    pub(crate) structsy_impl: Arc<StructsyImpl>,
    pub(crate) trans: &'a mut Transaction,
}

/// Internal use transaction reference
pub struct TxRef<'a> {
    pub(crate) trans: &'a mut Transaction,
}

/// Internal use implementation reference
pub struct ImplRef {
    pub(crate) structsy_impl: Arc<StructsyImpl>,
}

pub trait Sytx {
    /// Internal Use Only
    ///
    #[doc(hidden)]
    fn tx(&mut self) -> TxRef;
    /// Internal Use Only
    ///
    #[doc(hidden)]
    fn structsy(&self) -> ImplRef;
}

impl Sytx for OwnedSytx {
    fn tx(&mut self) -> TxRef {
        TxRef { trans: &mut self.trans }
    }
    fn structsy(&self) -> ImplRef {
        ImplRef {
            structsy_impl: self.structsy_impl.clone(),
        }
    }
}
impl StructsyTx for OwnedSytx {
    fn commit(self) -> SRes<()> {
        let prepared = self.trans.prepare()?;
        prepared.commit()?;
        Ok(())
    }

    fn prepare_commit(self) -> SRes<Prepared> {
        Ok(Prepared {
            prepared: self.trans.prepare()?,
        })
    }
}

impl<'a> Sytx for RefSytx<'a> {
    fn tx(&mut self) -> TxRef {
        TxRef { trans: self.trans }
    }
    fn structsy(&self) -> ImplRef {
        ImplRef {
            structsy_impl: self.structsy_impl.clone(),
        }
    }
}
impl<'a> StructsyTx for RefSytx<'a> {
    fn commit(self) -> SRes<()> {
        unreachable!();
    }
    fn prepare_commit(self) -> SRes<Prepared> {
        unreachable!();
    }
}

///
/// Transaction prepared state ready to be committed if the second phase is considered successful
///
pub struct Prepared {
    prepared: persy::TransactionFinalize,
}
impl Prepared {
    /// Commit all the prepared changes
    pub fn commit(self) -> SRes<()> {
        self.prepared.commit()?;
        Ok(())
    }
    /// Rollback all the prepared changes
    pub fn rollback(self) -> SRes<()> {
        self.prepared.rollback()?;
        Ok(())
    }
}

/// Transaction behaviour trait.
pub trait StructsyTx: Sytx + Sized {
    /// Persist a new struct instance.
    ///
    /// # Example
    /// ```
    /// use structsy::{Structsy,StructsyTx};
    /// use structsy_derive::Persistent;
    /// #[derive(Persistent)]
    /// struct Example {
    ///     value:u8,
    /// }
    /// # use structsy::SRes;
    /// # fn example() -> SRes<()> {
    /// # let structsy = Structsy::open("path/to/file.stry")?;
    /// //.. open structsy etc.
    /// let mut tx = structsy.begin()?;
    /// tx.insert(&Example{value:10})?;
    /// tx.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn insert<T: Persistent>(&mut self, sct: &T) -> SRes<Ref<T>> {
        let def = self.structsy().structsy_impl.check_defined::<T>()?;
        let mut buff = Vec::new();
        sct.write(&mut buff)?;
        let id = self.tx().trans.insert(def.segment_name(), &buff)?;
        let id_ref = Ref::new(id);
        sct.put_indexes(self, &id_ref)?;
        Ok(id_ref)
    }

    /// Update a persistent instance with a new value.
    ///
    /// # Example
    /// ```
    /// use structsy::{Structsy,StructsyTx};
    /// use structsy_derive::Persistent;
    /// #[derive(Persistent)]
    /// struct Example {
    ///     value:u8,
    /// }
    /// # use structsy::SRes;
    /// # fn example() -> SRes<()> {
    /// # let structsy = Structsy::open("path/to/file.stry")?;
    /// //.. open structsy etc.
    /// let mut tx = structsy.begin()?;
    /// let id = tx.insert(&Example{value:10})?;
    /// tx.update(&id, &Example{value:20})?;
    /// tx.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn update<T: Persistent>(&mut self, sref: &Ref<T>, sct: &T) -> SRes<()> {
        let def = self.structsy().structsy_impl.check_defined::<T>()?;
        let mut buff = Vec::new();
        sct.write(&mut buff)?;
        let old = self.read::<T>(sref)?;
        if let Some(old_rec) = old {
            old_rec.remove_indexes(self, sref)?;
        }
        self.tx().trans.update(def.segment_name(), &sref.raw_id, &buff)?;
        sct.put_indexes(self, sref)?;
        Ok(())
    }

    /// Delete a persistent instance.
    ///
    /// # Example
    /// ```
    /// use structsy::{Structsy,StructsyTx};
    /// use structsy_derive::Persistent;
    /// #[derive(Persistent)]
    /// struct Example {
    ///     value:u8,
    /// }
    /// # use structsy::SRes;
    /// # fn example() -> SRes<()> {
    /// # let structsy = Structsy::open("path/to/file.stry")?;
    /// //.. open structsy etc.
    /// let mut tx = structsy.begin()?;
    /// let id = tx.insert(&Example{value:10})?;
    /// tx.delete(&id)?;
    /// tx.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn delete<T: Persistent>(&mut self, sref: &Ref<T>) -> SRes<()> {
        let def = self.structsy().structsy_impl.check_defined::<T>()?;
        let old = self.read::<T>(sref)?;
        if let Some(old_rec) = old {
            old_rec.remove_indexes(self, sref)?;
        }
        self.tx().trans.delete(def.segment_name(), &sref.raw_id)?;
        Ok(())
    }

    /// Read a persistent instance considering changes in transaction.
    ///
    /// # Example
    /// ```
    /// use structsy::{Structsy,StructsyTx};
    /// use structsy_derive::Persistent;
    /// #[derive(Persistent)]
    /// struct Example {
    ///     value:u8,
    /// }
    /// # use structsy::SRes;
    /// # fn example() -> SRes<()> {
    /// # let structsy = Structsy::open("path/to/file.stry")?;
    /// //.. open structsy etc.
    /// let mut tx = structsy.begin()?;
    /// let id = tx.insert(&Example{value:10})?;
    /// let read = tx.read(&id)?;
    /// assert_eq!(10,read.unwrap().value);
    /// tx.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn read<T: Persistent>(&mut self, sref: &Ref<T>) -> SRes<Option<T>> {
        let def = self.structsy().structsy_impl.check_defined::<T>()?;
        crate::structsy::tx_read(def.segment_name(), &mut self.tx().trans, &sref.raw_id)
    }

    /// Scan persistent instances of a struct considering changes in transaction.
    ///
    /// # Example
    /// ```
    /// use structsy::{Structsy,StructsyTx};
    /// use structsy_derive::Persistent;
    /// #[derive(Persistent)]
    /// struct Example {
    ///     value:u8,
    /// }
    /// # use structsy::SRes;
    /// # fn example() -> SRes<()> {
    /// # let structsy = Structsy::open("path/to/file.stry")?;
    /// //.. open structsy etc.
    /// let mut tx = structsy.begin()?;
    /// for (id, inst) in tx.scan::<Example>()? {
    ///     // logic
    /// }
    /// tx.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn scan<T: Persistent>(&mut self) -> SRes<TxRecordIter<T>> {
        raw_tx_scan(self.structsy().structsy_impl, self.tx().trans)
    }

    /// Commit a transaction
    ///
    ///
    /// # Example
    /// ```
    /// use structsy::{Structsy,StructsyTx};
    /// # use structsy::SRes;
    /// # fn example() -> SRes<()> {
    /// let stry = Structsy::open("path/to/file.stry")?;
    /// //....
    /// let mut tx = stry.begin()?;
    /// // ... operate on tx.
    /// tx.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn commit(self) -> SRes<()>;

    /// Prepare Commit a transaction
    ///
    ///
    /// # Example
    /// ```
    /// use structsy::{Structsy,StructsyTx};
    /// # use structsy::SRes;
    /// # fn example() -> SRes<()> {
    /// let stry = Structsy::open("path/to/file.stry")?;
    /// //....
    /// let mut tx = stry.begin()?;
    /// // ... operate on tx.
    /// let prepared = tx.prepare_commit()?;
    /// prepared.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn prepare_commit(self) -> SRes<Prepared>;
}

pub(crate) fn raw_tx_scan<'a, T: Persistent>(
    structsy: Arc<StructsyImpl>,
    trans: &'a mut Transaction,
) -> SRes<TxRecordIter<'a, T>> {
    let def = structsy.check_defined::<T>()?;
    let iter = trans.scan(def.segment_name())?;
    Ok(TxRecordIter::new(iter, structsy))
}

pub trait TxIterator<'a>: Iterator {
    fn tx(&mut self) -> RefSytx;
}

impl<'a, T: Persistent> TxIterator<'a> for TxRecordIter<'a, T> {
    fn tx(&mut self) -> RefSytx {
        self.tx()
    }
}

/// Iterator for record instances aware of transactions changes
pub struct TxRecordIter<'a, T> {
    iter: persy::TxSegmentIter<'a>,
    marker: PhantomData<T>,
    structsy_impl: Arc<StructsyImpl>,
}

impl<'a, T> TxRecordIter<'a, T> {
    fn new(iter: persy::TxSegmentIter<'a>, structsy_impl: Arc<StructsyImpl>) -> TxRecordIter<'a, T> {
        TxRecordIter {
            iter,
            marker: PhantomData,
            structsy_impl,
        }
    }

    pub fn tx(&mut self) -> RefSytx {
        RefSytx {
            trans: self.iter.tx(),
            structsy_impl: self.structsy_impl.clone(),
        }
    }
}

impl<'a, T: Persistent> TxRecordIter<'a, T> {
    pub fn next_tx(&mut self) -> Option<(Ref<T>, T, RefSytx)> {
        if let Some((id, buff, tx)) = self.iter.next_tx() {
            if let Ok(x) = T::read(&mut Cursor::new(buff)) {
                let stx = RefSytx {
                    trans: tx,
                    structsy_impl: self.structsy_impl.clone(),
                };
                Some((Ref::new(id), x, stx))
            } else {
                None
            }
        } else {
            None
        }
    }
}

impl<'a, T: Persistent> Iterator for TxRecordIter<'a, T> {
    type Item = (Ref<T>, T);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((id, buff)) = self.iter.next() {
            if let Ok(x) = T::read(&mut Cursor::new(buff)) {
                Some((Ref::new(id), x))
            } else {
                None
            }
        } else {
            None
        }
    }
}