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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
//  ------------------------------------------------------------------
//  Airone
//  is a Rust library which provides a simple in-memory,
//  write-on-update database that is persisted
//  to an append-only transaction file.
//
//  Copyright © 2022 Massimo Gismondi
//
//  This file is part of Airone.
//  Airone is free software: you can redistribute it and/or
//  modify it under the terms of the GNU Affero General Public License
//  as published by the Free Software Foundation, either version 3
//  of the License, or (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU Affero General Public License
//  along with this program. If not, see <https://www.gnu.org/licenses/>.
//  ------------------------------------------------------------------

#![doc = include_str!("../DOCS.md")]

pub use paste;
pub use std;
mod error;
pub use error::AironeError;
mod traits;
pub use traits::{LoadableValue, PersistableValue};

mod query_build;
pub use query_build::Query;

#[cfg(test)]
mod tests;

/// A single change in the database,
/// that can be applied or reverted
#[derive(Clone)]
pub struct SingleChange
{
    pub apply_change: Operation,
    pub revert_change: Operation
}

/// Represents an internal operations as an enumerative type.
/// Each operation includes all needed fields.
/// 
#[derive(Clone, PartialEq)]
pub enum Operation
{
    /// Add operation. Includes the index where
    /// the new item will be inserted
    /// and a String representation of the new object to add
    Add
    {
        index: usize,
        serialized_object: String
    },
    /// A Delete operations. Only needs the index of the element to remove
    Delete
    {
        index: usize
    },
    /// An Edit operation.
    /// Expects the index of the element to change,
    /// plus the field name, field type and the new value to insert, converted to a String.
    /// 
    /// You can obtain the String representation of a value using the [PersistableValue::to_persistable_string()] method.
    Edit
    {
        variable_type: String,
        index: usize,
        field_name: String,
        new_value_str: String
    }
}
impl Operation
{
    /// Tries to create an [Operation] enum from a line string in Airone format.
    pub fn parse_line(line: &str) -> Result<Operation, AironeError>
    {
        let mut parts_iter = line.split("\t");
        let tipo_op = parts_iter.next().unwrap();
        if tipo_op == "A"
        {
            // Aggiungi un elemento
            let index: usize = parts_iter.next().unwrap().parse().unwrap();
            let obj_string = parts_iter.collect::<Vec<&str>>().join("\t");
            return Ok(Operation::Add {
                index,
                serialized_object: obj_string
            });
        }
        else if tipo_op == "D"
        {
            let index: usize = parts_iter.next().unwrap().parse().unwrap();
            return Ok(Operation::Delete { index });
        }
        else if tipo_op == "E"
        {
            // formato:
            // E indice campo valore
            let my_type: String = parts_iter.next().unwrap().to_string();
            let index: usize = parts_iter.next().unwrap().parse().unwrap();
            let field: String = parts_iter.next().unwrap().to_string();
            let value_str: String = parts_iter.next().unwrap().to_string();

            return Ok(Operation::Edit {
                variable_type: my_type,
                index,
                field_name: field,
                new_value_str: value_str
            });
        }
        else
        {
            return Err(AironeError::ParseFailed);
        }
    }

    /// Converts an [Operation] to a properly formatted String, so it can be persisted to disk. 
    pub fn to_line(&self) -> String
    {
        match &self
        {
            Operation::Add {
                index,
                serialized_object
            } =>
            {
                format!("A\t{}\t{}",
                    index,
                    serialized_object
                )
            }
            Operation::Delete { index } =>
            {
                format!("D\t{}", index)
            }
            Operation::Edit {
                variable_type,
                index,
                field_name,
                new_value_str
            } =>
            {
                format!("E\t{}\t{}\t{}\t{}",
                    variable_type,
                    index,
                    field_name,
                    new_value_str
                )
            }
        }
    }
}

// Spiegazione della lifetime del Deserialize
// https://users.rust-lang.org/t/serde-generics-implement-deserialize-with-lifetime/45683/2

/// This trait exposes public methods to access the data
pub trait Database<T>
{
    /// Constructor method, initializing the save file
    /// named as the struct you passed to the [airone_db!] macro
    fn new() -> Self;

    /// Constructor method, initializing the save file
    /// using the given name.
    ///
    /// Do _NOT_ include the file extension.
    fn new_with_filename(custom_filename: &str) -> Self;

    /// Returns a reference to the element at the provided index
    fn get(&self, index: usize) -> Result<&T, AironeError>;

    /// Returns a non-mutable reference to the inner list.
    ///
    /// You are forced to change data through the provided methods
    /// of Airone, so that changes are correctly persisted.
    fn get_all(&self) -> &Vec<T>;

    /// Adds a new element to the list at the given index position
    fn insert(&mut self, index: usize, element: T) -> Result<(), AironeError>;

    /// Adds a new element to the end of the list
    fn push(&mut self, element: T) -> Result<(), AironeError>;

    /// Adds multiple elements to the end of the list, automatically reducing the number of syscalls to write them to disk
    fn bulk_push(&mut self, elements: Vec<T>) -> Result<(), AironeError>;

    /// Removes the first element of the list
    fn pop(&mut self) -> Result<(), AironeError>;

    /// Removes the element at the specified index from the list
    fn remove(&mut self, index: usize) -> Result<(), AironeError>;

    /// Removes the elements at the specified indices from the list,
    /// automatically reducing the number of syscalls to write them to disk
    fn bulk_remove(&mut self, indices: Vec<usize>) -> Result<(), AironeError>;

    /// Returns the current number of elements in the list
    fn len(&self) -> usize;

    /// Filters the elements with the given predicate.
    /// Returns a list of indices that match the filter.
    ///
    /// You can later use those indices with [bulk_remove](Database::bulk_remove) methods or `bulk_set_$field_name` setters generated by the macro.
    fn filter<F>(&self, f: F) -> Vec<usize>
    where
        F: Fn(&T) -> bool;

    // Transazioni
    /// Commits a transaction by saving change to disk
    fn commit(&mut self) -> Result<(), AironeError>;

    /// Rolls back data in memory to the last successfull commit.
    fn rollback(&mut self) -> Result<(), AironeError>;
    /// Enables or disables autocommit
    fn set_auto_commit(&mut self, new_state: bool);
}

/// This macro creates a new struct which will be used to interact with the underlying data.
///
/// The resulting struct implements the [Database] trait and also generates appropriate getter and setter methods for each struct field.
#[macro_export]
macro_rules! airone_db
{
    (
        $(#[$meta:meta])*
        $vis:vis struct $struct_name:ident
        {
            $(
                $field_vis:vis $field_name:ident : $field_type:ty
            ),*
        }
    ) => {
        // La struct ricevuta in input
        $(#[$meta])*
        $vis struct $struct_name
        {
            $(
                $field_vis $field_name: $field_type,
            )*
        }
        $crate::paste::paste!{
            impl $struct_name
            {
                $(
                    fn [<get_ $field_name>](&self) -> &$field_type
                    {
                        &self.$field_name
                    }
                    fn [<set_ $field_name>](&mut self, value: $field_type)
                    {
                        self.$field_name = value;
                    }
                )*
            }
        }

        // La struct Database esterna
        $crate::paste::paste!{
            $vis struct [<$struct_name AironeListProxy>]
            {
                buf_writer: $crate::std::io::BufWriter<$crate::std::fs::File>,
                elements: Vec<$struct_name>,
                current_transaction_changes: Vec<$crate::SingleChange>,
                autocommit: bool
            }

            impl [<$struct_name AironeListProxy>]
            {
                fn serialize_object(obj: &$struct_name) -> String
                {
                    let mut output = String::new();
                    $(
                        let value: Box<dyn $crate::PersistableValue> = Box::new(obj.$field_name.clone());
                        output.push_str(&format!(
                            "{}\t",
                            value.to_persistable_string()
                        ));
                    )*
                    output.pop();
                    return output;
                }
                fn deserialize_object(line: &str) -> $struct_name
                {
                    let mut parts = line.split("\t");
                    $(
                        let next_part = parts.next().unwrap().to_string();
                        let [<found_ $field_name>]: $field_type = $crate::LoadableValue::from_persistable_string(&next_part);
                    )*

                    let obj = $struct_name {
                        $(
                            $field_name: [<found_ $field_name>],
                        )*
                    };
                    return obj;
                }

                fn get_elements(&self) -> &Vec<$struct_name>
                {
                    return &self.elements;
                }
                fn get_elements_mut(&mut self) -> &mut Vec<$struct_name>
                {
                    return &mut self.elements;
                }
                fn get_buf_writer(&mut self) -> &mut $crate::std::io::BufWriter<$crate::std::fs::File>
                {
                    return &mut self.buf_writer;
                }
                fn apply_single_edit(elements: &mut Vec<$struct_name>, operation: &$crate::Operation)
                -> Result<(), $crate::AironeError>
                {
                    match operation
                    {
                        $crate::Operation::Add {
                            index,
                            serialized_object
                        } =>
                        {
                            let el: $struct_name = Self::deserialize_object(&serialized_object);
                            elements.insert(*index, el);
                        }
                        $crate::Operation::Delete { index } =>
                        {
                            elements.remove(*index);
                        }
                        $crate::Operation::Edit {
                            variable_type,
                            index,
                            field_name,
                            new_value_str
                        } =>
                        {
                            println!("matching {} {}", variable_type, field_name);
                            match (field_name.as_str(), variable_type.as_str()) {
                                $(
                                    (stringify!($field_name), stringify!($field_type)) =>
                                    {
                                        println!("matched {} {}", variable_type, field_name);
                                        let lo: $field_type = $crate::LoadableValue::from_persistable_string(new_value_str);
                                        if let Some(e) = elements.get_mut(*index)
                                        {
                                            e.[<set_ $field_name>](lo);
                                        }
                                        else
                                        {
                                            return Err($crate::AironeError::OutOfBound);
                                        }
                                    }
                                )*
                                _ => {return Err($crate::AironeError::ParseFailed);}
                            };
                        }
                    }

                    Ok(())
                }

                fn transact_insert_change(&mut self, change: $crate::SingleChange) -> Result<(), $crate::AironeError>
                {
                    self.current_transaction_changes.push(change);
                    if self.autocommit
                    {
                        self.commit()?;
                    }
                    Ok(())
                }
            }

            impl $crate::Database<$struct_name> for [<$struct_name AironeListProxy>]
            {
                /// Enables or disables autocommits.
                ///
                /// Autocommit means that each change is instantly flushed to disk without having to call `commit()`. The rollback() function is useless in this state.
                ///
                /// Disabled autocommit means the you have to manually commit or rollback changes.
                fn set_auto_commit(&mut self, new_state: bool)
                {
                    self.autocommit = new_state;
                }
                fn commit(&mut self)
                -> Result<(), $crate::AironeError>
                {
                    use $crate::std::io::Write;
                    for el in self.current_transaction_changes.clone()
                    {
                        if writeln!(self.get_buf_writer(), "{}", el.apply_change.to_line()).is_err()
                        {
                            return Err($crate::AironeError::IOError);
                        }
                    }

                    if self.get_buf_writer().flush().is_err()
                    {
                        return Err($crate::AironeError::IOError);
                    }

                    self.current_transaction_changes = Vec::new();
                    Ok(())
                }
                fn rollback(&mut self)
                -> Result<(), $crate::AironeError>
                {
                    self.current_transaction_changes.reverse();
                    for el in self.current_transaction_changes.clone()
                    {
                        Self::apply_single_edit(self.get_elements_mut(), &el.revert_change)?;
                    }
                    self.current_transaction_changes = Vec::new();
                    Ok(())
                }

                fn filter<F>(&self, f: F) -> Vec<usize>
                where F: Fn(&$struct_name) -> bool
                {
                    return self.get_elements().iter().enumerate()
                    .filter( |(_k, v)| { f(v) })
                    .map(|(k, _v)| { k }).collect();
                }

                fn new() -> Self
                {
                    const FILENAME: &str = stringify!($struct_name);
                    return Self::new_with_filename(FILENAME);
                }

                fn new_with_filename(custom_filename: &str) -> Self
                {
                    if cfg!(target_os="windows")
                    {
                        eprintln!("You're running a Windows operating system, but Airone is not supported on, has never been tested on and does not endorse proprietary operating systems.\n\
                        I encourage you to switch to an actually privacy-and-freedom respecting operating system such as Gnu/Linux.\n\
                        Head to https://www.fsf.org/windows for more information.");
                    }
                    else if cfg!(target_os="macos") || cfg!(target_os="ios")
                    {
                        eprintln!("You're running an Apple operating system, but Airone is not supported on, has never been tested on and does not endorse proprietary operating systems.\n\
                        I encourage you to switch to an actually privacy-and-freedom respecting operating system such as Gnu/Linux.\n\
                        Learn more at https://www.fsf.org/campaigns/apple");
                    }
                    {
                        // WSL
                        let output = std::process::Command::new("uname")
                        .arg("-a")
                        .output()
                        .expect("Failed to execute command");
                        let st =  String::from_utf8(output.stdout).unwrap();
                        if st.to_ascii_lowercase().contains("microsoft")
                        {
                            eprintln!("You're running airone inside of WSL, which is a compatibility layer and may unexpectedly break or introduce bugs. Airone has never been tested on WSL. Moreover, WSL limits your freedom as it makes you stick to a proprietary OS, but that's a personal decision. \n\
                            Anyway, to get the best from this library I highly encourage you to switch to a traditionally installed operating system such as Gnu/Linux instead.
                            ");
                        }
                    }


                    let mut starting_elements: Vec<$struct_name> = Vec::new();

                    Self::load_base_data(&mut starting_elements, custom_filename);
                    Self::apply_edits(&mut starting_elements, custom_filename).unwrap();
                    Self::compact(&mut starting_elements, custom_filename).unwrap();
                    let mut file = $crate::std::fs::OpenOptions::new()
                        .write(true)
                        .append(true)
                        .create(true)
                        .open(format!("{}{}", custom_filename, ".changes.csv"))
                        .unwrap();
                    return Self {
                        autocommit: true,
                        current_transaction_changes: Vec::new(),
                        elements: starting_elements,
                        buf_writer: $crate::std::io::BufWriter::new(
                            file
                        )
                    };
                }

                /// Read only access to the element at the specified index
                fn get(&self, index: usize) -> Result<&$struct_name, AironeError>
                {
                    match self.get_elements().get(index)
                    {
                        Some(e) => Ok(e),
                        None => Err(AironeError::OutOfBound)
                    }
                }
                fn get_all(&self) -> &Vec<$struct_name>
                {
                    return self.get_elements();
                }

                fn insert(&mut self, index: usize, element: $struct_name) -> Result<(), AironeError>
                {
                    self.transact_insert_change(
                        self.internal_op_add(&element, index)
                    )?;
                    self.get_elements_mut().insert(index, element);
                    // println!("{:?}", self.get_elements());
                    Ok(())
                }

                fn push(&mut self, element: $struct_name) -> Result<(), $crate::AironeError>
                {
                    return self.insert(self.get_elements().len(), element);
                }
                fn bulk_push(&mut self, elements: Vec<$struct_name>) -> Result<(), $crate::AironeError>
                {
                    let current_autocommit_state = self.autocommit;

                    self.autocommit = false;
                    for el in elements
                    {
                        self.push(el)?;
                    }
                    self.autocommit = current_autocommit_state;
                    if self.autocommit
                    {
                        self.commit()?;
                    }
                    return Ok(())
                }
                fn pop(&mut self) -> Result<(), $crate::AironeError>
                {
                    if let Some(el) = self.get_elements_mut().pop()
                    {
                        self.transact_insert_change(
                            self.internal_op_delete(self.get_elements().len(), &el)
                        )?;
                        Ok(())
                    }
                    else
                    {
                        return Err($crate::AironeError::ListAlreadyEmpty)
                    }
                }
                fn remove(&mut self, index: usize) -> Result<(), $crate::AironeError>
                {
                    if self.get_elements().len() == 0
                    {
                        self.rollback()?;
                        return Err($crate::AironeError::ListAlreadyEmpty);
                    }
                    if index < self.get_elements().len()
                    {
                        let el = self.get_elements_mut().remove(index);
                        self.transact_insert_change(
                            self.internal_op_delete(index, &el)
                        )?;
                        return Ok(())
                    }
                    else
                    {
                        self.rollback()?;
                        return Err($crate::AironeError::OutOfBound);
                    }
                }
                fn bulk_remove(&mut self, indices: Vec<usize>) -> Result<(), $crate::AironeError>
                {
                    for index in indices.iter()
                    {
                        if index >= &self.get_elements().len()
                        {
                            self.rollback()?;
                            return Err($crate::AironeError::OutOfBound);
                        }
                    }
                    if indices.len() > self.get_elements().len()
                    {
                        self.rollback()?;
                        return Err($crate::AironeError::OutOfBound);
                    }


                    let current_autocommit_state = self.autocommit;
                    self.autocommit = false;


                    let mut my_indices = indices.clone();
                    my_indices.sort();
                    my_indices.reverse();
                    for index in my_indices.iter()
                    {
                        self.remove(index.clone())?;
                    }

                    self.autocommit = current_autocommit_state;
                    if self.autocommit
                    {
                        self.commit()?;
                    }
                    Ok(())
                }


                fn len(&self) -> usize
                {
                    self.get_elements().len()
                }
            }

            impl [<$struct_name AironeListProxy>]
            {
                // Getter e setter,
                // che chiamano internamente il salvataggio
                // su file
                $(
                    $field_vis fn [<get_ $field_name>](&self, index: usize) -> Result<&$field_type,AironeError>
                    {
                        if let Some(e) = &self.elements.get(index)
                        {
                            return Ok(&e.$field_name)
                        }
                        else
                        {
                            return Err(AironeError::OutOfBound)
                        }
                    }
                    $field_vis fn [<set_ $field_name>](&mut self, index: usize, value: $field_type) -> Result<(),AironeError>
                    {
                        if let Some(el) = self.get_elements_mut().get_mut(index)
                        {
                            let old_value = el.$field_name.clone();
                            el.$field_name = value.clone();

                            self.transact_insert_change(
                                self.internal_op_edit(
                                    stringify!($field_type),
                                    index,
                                    stringify!($field_name),
                                    &old_value,
                                    &value
                                )
                            )?;
                            return Ok(())
                        }
                        else
                        {
                            return Err(AironeError::OutOfBound);
                        }
                    }

                    $field_vis fn [<set_bulk_ $field_name>](&mut self, indices: Vec<usize>, value: $field_type) -> Result<(),AironeError>
                    {
                        for index in indices
                        {
                            let el: &mut $struct_name = match self.get_elements_mut().get_mut(index)
                            {
                                Some(e) => e,
                                None => return Err(AironeError::OutOfBound)
                            };
                            let old_value = el.$field_name.clone();
                            el.$field_name = value.clone();

                            self.transact_insert_change(
                                self.internal_op_edit(
                                    stringify!($field_type),
                                    index,
                                    stringify!($field_name),
                                    &old_value,
                                    &value
                                )
                            )?;
                        }
                        return Ok(())
                    }
                )*


                fn full_dump(objects: &Vec<$struct_name>) -> Vec<String>
                {
                    let mut output:Vec<String> = Vec::new();
                    for object in objects
                    {
                        output.push(
                            Self::serialize_object(object)
                        );
                    }
                    return output;
                }
                fn full_load(reader: std::io::BufReader<std::fs::File>) -> Vec<$struct_name>
                {
                    use $crate::std::io::BufRead;
                    let mut found_elements: Vec<$struct_name> = Vec::new();
                    for line in reader.lines()
                    {
                        found_elements.push(
                            Self::deserialize_object(&line.unwrap())
                        );
                    }
                    return found_elements;
                }

                //------------------------------------------
                // Operazioni interne per il salvataggio,
                // tutte salvano su file la modifica
                //------------------------------------------
                //
                fn internal_op_add(&self, new_object: &$struct_name, index_for_revert: usize) -> $crate::SingleChange
                {
                    return $crate::SingleChange{
                        apply_change: $crate::Operation::Add{
                            index: index_for_revert,
                            serialized_object: Self::serialize_object(new_object)
                        },
                        revert_change: $crate::Operation::Delete{
                            index: index_for_revert
                        }
                    };
                }
                fn internal_op_delete(&self, index: usize, removed_object: &$struct_name) -> $crate::SingleChange
                {
                    return $crate::SingleChange{
                        apply_change: $crate::Operation::Delete{
                            index: index
                        },
                        revert_change: $crate::Operation::Add{
                            index: index,
                            serialized_object: Self::serialize_object(removed_object)
                        }
                    };
                }
                fn internal_op_edit<C: $crate::PersistableValue>(
                    &self, el_type: &str, index: usize, key: &str, old_value: &C, new_value: &C)
                    -> $crate::SingleChange
                {
                    return $crate::SingleChange{
                        apply_change: $crate::Operation::Edit{
                            variable_type: el_type.to_string(),
                            index,
                            field_name: key.to_string(),
                            new_value_str: new_value.to_persistable_string()
                        },
                        revert_change: $crate::Operation::Edit{
                            variable_type: el_type.to_string(),
                            index,
                            field_name: key.to_string(),
                            new_value_str: old_value.to_persistable_string()
                        }
                    };
                }

                // ------------------------------------------
                // Quando il database viene istanziato,
                // devo caricare il JSON base e poi
                // applicare le modifiche
                // ------------------------------------------
                /// Carica il JSON di base senza applicare le modifiche
                fn load_base_data(elements: &mut Vec<$struct_name>, filename: &str)
                {
                    use std::io::BufRead;
                    // Carico JSON di base
                    if let Ok(file) = std::fs::OpenOptions::new()
                        .read(true)
                        .open(format!("{}{}", filename, ".csv"))
                    {
                        let buf = std::io::BufReader::new(file);
                        let mut els: Vec<$struct_name> = Vec::new();
                        for (i, line) in buf.lines().enumerate()
                        {
                            els.push(
                                Self::deserialize_object(&line.unwrap())
                            );
                        }

                        for el in els
                        {
                            elements.push(el);
                        }
                    }
                    else
                    {
                        std::fs::File::create(format!("{}{}", filename, ".csv")).unwrap();
                    }
                }

                /// Applica le modifiche sui dati
                /// già caricati in memoria
                fn apply_edits(elements: &mut Vec<$struct_name>, filename: &str)
                -> Result<(), $crate::AironeError>
                {
                    use std::io::BufRead;
                    {
                        let file = match std::fs::OpenOptions::new()
                            .read(true)
                            .open(format!("{}{}", filename, ".changes.csv"))
                            {
                                Ok(e) => {e},
                                Err(_) => {
                                    return Ok(());
                                }
                            };
                        let reader = std::io::BufReader::new(file);

                        for line in reader.lines()
                        {
                            let my_line = line.unwrap();
                            Self::apply_single_edit(elements, &$crate::Operation::parse_line(&my_line)?)?;
                        }
                    }

                    // Svuoto file modifiche
                    std::fs::File::create(format!("{}{}", filename, ".changes.csv")).unwrap();

                    Ok(())
                }

                /// Salva su file il JSON intero compattato
                /// ed elimina il file delle modifiche
                fn compact(elements: &Vec<$struct_name>, filename: &str)
                -> Result<(), $crate::AironeError>
                {
                    use std::io::Write;
                    let mut file = std::fs::OpenOptions::new()
                        .create(true)
                        .write(true)
                        .truncate(true)
                        .open(format!("{}{}", filename, ".csv"))
                        .unwrap();
                    let mut writer = std::io::BufWriter::new(file);
                    for element in elements
                    {
                        let string = Self::serialize_object(element);
                        writeln!(writer, "{}", string).unwrap();
                    }

                    Ok(())
                }
            }
        }
    }
}