1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.data.mapping.model;
7 
8 /// Base-interface for a model.
9 interface IModel { }
10 
11 /// Wrapper for a base model.
12 abstract class Model : IModel
13 {
14   private:
15   /// The reader.
16   void delegate() _reader;
17   /// The inserter.
18   void delegate() _inserter;
19   /// The updater.
20   void delegate() _updater;
21   /// The deleter.
22   void delegate() _deleter;
23   /// The relationship reader.
24   void delegate() _readerRelationship;
25 
26   public:
27   final:
28   /// Creates a new model.
29   this()
30   {
31 
32   }
33 
34   protected
35   {
36     void setReader(void delegate() reader)
37     {
38       _reader = reader;
39     }
40 
41     void setInserter(void delegate() inserter)
42     {
43       _inserter = inserter;
44     }
45 
46     void setUpdater(void delegate() updater)
47     {
48       _updater = updater;
49     }
50 
51     void setDeleter(void delegate() deleter)
52     {
53       _deleter = deleter;
54     }
55 
56     void setReaderRelationship(void delegate() readerRelationship)
57     {
58       _readerRelationship = readerRelationship;
59     }
60   }
61 
62   /// Reads the model from the reader. Called internally from readSingle & readMany
63   void readModel() @system
64   {
65     if (_reader)
66     {
67       _reader();
68     }
69   }
70 
71   /// Inserts the model.
72   void insertModel() @system
73   {
74     if (_inserter)
75     {
76       _inserter();
77     }
78   }
79 
80   /// Updates the model.
81   void updateModel() @system
82   {
83     if (_updater)
84     {
85       _updater();
86     }
87   }
88 
89   /// Deletes the model.
90   void deleteModel() @system
91   {
92     if (_deleter)
93     {
94       _deleter();
95     }
96   }
97 
98   /// Reads the relationships the model has.
99   void readRelationships() @system
100   {
101     if (_readerRelationship)
102     {
103       _readerRelationship();
104     }
105   }
106 }
107 
108 // TODO: Optimize these to do CTFE:
109 
110 /**
111 * Inserts an array of models.
112 *  Params:
113 *    models = The models to insert.
114 */
115 void insertMany(T : IModel)(T[] models) @system
116 {
117   foreach (model; models)
118   {
119     model.insertModel();
120   }
121 }
122 
123 /**
124 * Updates an array of models.
125 *  Params:
126 *    models = The models to update.
127 */
128 void updateMany(T : IModel)(T[] models) @system
129 {
130   foreach (model; models)
131   {
132     model.updateModel();
133   }
134 }
135 
136 /**
137 * Deletes an array of models.
138 *  Params:
139 *    models = The models to delete.
140 */
141 void deleteMany(T : IModel)(T[] models) @system
142 {
143   foreach (model; models)
144   {
145     model.deleteModel();
146   }
147 }