1 // -*- C++ -*-
2 //=============================================================================
3 /**
4  *      Copyright (c) 2013,2014,2015 Guan Lisheng (guanlisheng@gmail.com)
5  *
6  *      @file
7  *
8  *      @author [sqlite2cpp.py]
9  *
10  *      @brief
11  *
12  *      Revision History:
13  *          AUTO GENERATED at 2015-01-25 15:29:25.126684.
14  *          DO NOT EDIT!
15  */
16 //=============================================================================
17 
18 #ifndef DB_TABLE_ATTACHMENT_V1_H
19 #define DB_TABLE_ATTACHMENT_V1_H
20 
21 #include "DB_Table.h"
22 
23 struct DB_Table_ATTACHMENT_V1 : public DB_Table
24 {
25     struct Data;
26     typedef DB_Table_ATTACHMENT_V1 Self;
27     /** A container to hold list of Data records for the table*/
28     struct Data_Set : public std::vector<Self::Data>
29     {
to_jsonDB_Table_ATTACHMENT_V1::Data_Set30         std::wstring to_json() const
31         {
32             json::Array a;
33             for (const auto & item: *this)
34             {
35                 json::Object o;
36                 item.to_json(o);
37                 a.Insert(o);
38             }
39             std::wstringstream ss;
40             json::Writer::Write(a, ss);
41             return ss.str();
42         }
43     };
44     /** A container to hold a list of Data record pointers for the table in memory*/
45     typedef std::vector<Self::Data*> Cache;
46     typedef std::map<int, Self::Data*> Index_By_Id;
47     Cache cache_;
48     Index_By_Id index_by_id_;
49 
50     /** Destructor: clears any data records stored in memory */
~DB_Table_ATTACHMENT_V1DB_Table_ATTACHMENT_V151     ~DB_Table_ATTACHMENT_V1()
52     {
53         destroy_cache();
54     }
55 
56     /** Removes all records stored in memory (cache) for the table*/
destroy_cacheDB_Table_ATTACHMENT_V157     void destroy_cache()
58     {
59         std::for_each(cache_.begin(), cache_.end(), std::mem_fun(&Data::destroy));
60         cache_.clear();
61         index_by_id_.clear(); // no memory release since it just stores pointer and the according objects are in cache
62     }
63 
64     /** Creates the database table if the table does not exist*/
ensureDB_Table_ATTACHMENT_V165     bool ensure(wxSQLite3Database* db)
66     {
67         if (!exists(db))
68 		{
69 			try
70 			{
71 				db->ExecuteUpdate("CREATE TABLE ATTACHMENT_V1 (ATTACHMENTID INTEGER NOT NULL PRIMARY KEY, REFTYPE TEXT NOT NULL /* Transaction, Stock, Asset, BankAccount, RepeatingTransaction, Payee */, REFID INTEGER NOT NULL, DESCRIPTION TEXT COLLATE NOCASE, FILENAME TEXT NOT NULL COLLATE NOCASE)");
72 			}
73 			catch(const wxSQLite3Exception &e)
74 			{
75 				wxLogError("ATTACHMENT_V1: Exception %s", e.GetMessage().c_str());
76 				return false;
77 			}
78 		}
79 
80         this->ensure_index(db);
81 
82         return true;
83     }
84 
ensure_indexDB_Table_ATTACHMENT_V185     bool ensure_index(wxSQLite3Database* db)
86     {
87         try
88         {
89             db->ExecuteUpdate("CREATE INDEX IF NOT EXISTS IDX_ATTACHMENT_REF ON ATTACHMENT_V1 (REFTYPE, REFID)");
90         }
91         catch(const wxSQLite3Exception &e)
92         {
93             wxLogError("ATTACHMENT_V1: Exception %s", e.GetMessage().c_str());
94             return false;
95         }
96 
97         return true;
98     }
99 
100     struct ATTACHMENTID : public DB_Column<int>
101     {
nameDB_Table_ATTACHMENT_V1::ATTACHMENTID102         static wxString name() { return "ATTACHMENTID"; }
103         explicit ATTACHMENTID(const int &v, OP op = EQUAL): DB_Column<int>(v, op) {}
104     };
105     struct REFTYPE : public DB_Column<wxString>
106     {
nameDB_Table_ATTACHMENT_V1::REFTYPE107         static wxString name() { return "REFTYPE"; }
108         explicit REFTYPE(const wxString &v, OP op = EQUAL): DB_Column<wxString>(v, op) {}
109     };
110     struct REFID : public DB_Column<int>
111     {
nameDB_Table_ATTACHMENT_V1::REFID112         static wxString name() { return "REFID"; }
113         explicit REFID(const int &v, OP op = EQUAL): DB_Column<int>(v, op) {}
114     };
115     struct DESCRIPTION : public DB_Column<wxString>
116     {
nameDB_Table_ATTACHMENT_V1::DESCRIPTION117         static wxString name() { return "DESCRIPTION"; }
118         explicit DESCRIPTION(const wxString &v, OP op = EQUAL): DB_Column<wxString>(v, op) {}
119     };
120     struct FILENAME : public DB_Column<wxString>
121     {
nameDB_Table_ATTACHMENT_V1::FILENAME122         static wxString name() { return "FILENAME"; }
123         explicit FILENAME(const wxString &v, OP op = EQUAL): DB_Column<wxString>(v, op) {}
124     };
125     typedef ATTACHMENTID PRIMARY;
126     enum COLUMN
127     {
128         COL_ATTACHMENTID = 0
129         , COL_REFTYPE = 1
130         , COL_REFID = 2
131         , COL_DESCRIPTION = 3
132         , COL_FILENAME = 4
133     };
134 
135     /** Returns the column name as a string*/
column_to_nameDB_Table_ATTACHMENT_V1136     static wxString column_to_name(COLUMN col)
137     {
138         switch(col)
139         {
140             case COL_ATTACHMENTID: return "ATTACHMENTID";
141             case COL_REFTYPE: return "REFTYPE";
142             case COL_REFID: return "REFID";
143             case COL_DESCRIPTION: return "DESCRIPTION";
144             case COL_FILENAME: return "FILENAME";
145             default: break;
146         }
147 
148         return "UNKNOWN";
149     }
150 
151     /** Returns the column number from the given column name*/
name_to_columnDB_Table_ATTACHMENT_V1152     static COLUMN name_to_column(const wxString& name)
153     {
154         if ("ATTACHMENTID" == name) return COL_ATTACHMENTID;
155         else if ("REFTYPE" == name) return COL_REFTYPE;
156         else if ("REFID" == name) return COL_REFID;
157         else if ("DESCRIPTION" == name) return COL_DESCRIPTION;
158         else if ("FILENAME" == name) return COL_FILENAME;
159 
160         return COLUMN(-1);
161     }
162 
163     /** Data is a single record in the database table*/
164     struct Data
165     {
166         friend struct DB_Table_ATTACHMENT_V1;
167         /** This is a instance pointer to itself in memory. */
168         Self* view_;
169 
170         int ATTACHMENTID;//  primary key
171         wxString REFTYPE;
172         int REFID;
173         wxString DESCRIPTION;
174         wxString FILENAME;
idDB_Table_ATTACHMENT_V1::Data175         int id() const { return ATTACHMENTID; }
idDB_Table_ATTACHMENT_V1::Data176         void id(int id) { ATTACHMENTID = id; }
177         bool operator < (const Data& r) const
178         {
179             return this->id() < r.id();
180         }
181         bool operator < (const Data* r) const
182         {
183             return this->id() < r->id();
184         }
185 
186         explicit Data(Self* view = 0)
187         {
188             view_ = view;
189 
190             ATTACHMENTID = -1;
191             REFID = -1;
192         }
193 
194         explicit Data(wxSQLite3ResultSet& q, Self* view = 0)
195         {
196             view_ = view;
197 
198             ATTACHMENTID = q.GetInt(0); // ATTACHMENTID
199             REFTYPE = q.GetString(1); // REFTYPE
200             REFID = q.GetInt(2); // REFID
201             DESCRIPTION = q.GetString(3); // DESCRIPTION
202             FILENAME = q.GetString(4); // FILENAME
203         }
204 
205         Data& operator=(const Data& other)
206         {
207             if (this == &other) return *this;
208 
209             ATTACHMENTID = other.ATTACHMENTID;
210             REFTYPE = other.REFTYPE;
211             REFID = other.REFID;
212             DESCRIPTION = other.DESCRIPTION;
213             FILENAME = other.FILENAME;
214             return *this;
215         }
216 
217         template<typename C>
matchDB_Table_ATTACHMENT_V1::Data218         bool match(const C &c) const
219         {
220             return false;
221         }
matchDB_Table_ATTACHMENT_V1::Data222         bool match(const Self::ATTACHMENTID &in) const
223         {
224             return this->ATTACHMENTID == in.v_;
225         }
matchDB_Table_ATTACHMENT_V1::Data226         bool match(const Self::REFTYPE &in) const
227         {
228             return this->REFTYPE.CmpNoCase(in.v_) == 0;
229         }
matchDB_Table_ATTACHMENT_V1::Data230         bool match(const Self::REFID &in) const
231         {
232             return this->REFID == in.v_;
233         }
matchDB_Table_ATTACHMENT_V1::Data234         bool match(const Self::DESCRIPTION &in) const
235         {
236             return this->DESCRIPTION.CmpNoCase(in.v_) == 0;
237         }
matchDB_Table_ATTACHMENT_V1::Data238         bool match(const Self::FILENAME &in) const
239         {
240             return this->FILENAME.CmpNoCase(in.v_) == 0;
241         }
to_jsonDB_Table_ATTACHMENT_V1::Data242         wxString to_json() const
243         {
244             json::Object o;
245             this->to_json(o);
246             std::wstringstream ss;
247             json::Writer::Write(o, ss);
248             return ss.str();
249         }
250 
to_jsonDB_Table_ATTACHMENT_V1::Data251         int to_json(json::Object& o) const
252         {
253             o[L"ATTACHMENTID"] = json::Number(this->ATTACHMENTID);
254             o[L"REFTYPE"] = json::String(this->REFTYPE.ToStdWstring());
255             o[L"REFID"] = json::Number(this->REFID);
256             o[L"DESCRIPTION"] = json::String(this->DESCRIPTION.ToStdWstring());
257             o[L"FILENAME"] = json::String(this->FILENAME.ToStdWstring());
258             return 0;
259         }
to_row_tDB_Table_ATTACHMENT_V1::Data260         row_t to_row_t() const
261         {
262             row_t row;
263             row(L"ATTACHMENTID") = ATTACHMENTID;
264             row(L"REFTYPE") = REFTYPE;
265             row(L"REFID") = REFID;
266             row(L"DESCRIPTION") = DESCRIPTION;
267             row(L"FILENAME") = FILENAME;
268             return row;
269         }
to_templateDB_Table_ATTACHMENT_V1::Data270         void to_template(html_template& t) const
271         {
272             t(L"ATTACHMENTID") = ATTACHMENTID;
273             t(L"REFTYPE") = REFTYPE;
274             t(L"REFID") = REFID;
275             t(L"DESCRIPTION") = DESCRIPTION;
276             t(L"FILENAME") = FILENAME;
277         }
278 
279         /** Save the record instance in memory to the database. */
saveDB_Table_ATTACHMENT_V1::Data280         bool save(wxSQLite3Database* db)
281         {
282             if (db && db->IsReadOnly()) return false;
283             if (!view_ || !db)
284             {
285                 wxLogError("can not save ATTACHMENT_V1");
286                 return false;
287             }
288 
289             return view_->save(this, db);
290         }
291 
292         /** Remove the record instance from memory and the database. */
removeDB_Table_ATTACHMENT_V1::Data293         bool remove(wxSQLite3Database* db)
294         {
295             if (!view_ || !db)
296             {
297                 wxLogError("can not remove ATTACHMENT_V1");
298                 return false;
299             }
300 
301             return view_->remove(this, db);
302         }
303 
destroyDB_Table_ATTACHMENT_V1::Data304         void destroy()
305         {
306             //if (this->id() < 0)
307             //    wxSafeShowMessage("unsaved object", this->to_json());
308             delete this;
309         }
310     };
311 
312     enum
313     {
314         NUM_COLUMNS = 5
315     };
316 
num_columnsDB_Table_ATTACHMENT_V1317     size_t num_columns() const { return NUM_COLUMNS; }
318 
319     /** Name of the table*/
nameDB_Table_ATTACHMENT_V1320     wxString name() const { return "ATTACHMENT_V1"; }
321 
DB_Table_ATTACHMENT_V1DB_Table_ATTACHMENT_V1322     DB_Table_ATTACHMENT_V1()
323     {
324         query_ = "SELECT * FROM ATTACHMENT_V1 ";
325     }
326 
327     /** Create a new Data record and add to memory table (cache)*/
createDB_Table_ATTACHMENT_V1328     Self::Data* create()
329     {
330         Self::Data* entity = new Self::Data(this);
331         cache_.push_back(entity);
332         return entity;
333     }
334 
335     /** Create a copy of the Data record and add to memory table (cache)*/
cloneDB_Table_ATTACHMENT_V1336     Self::Data* clone(const Data* e)
337     {
338         Self::Data* entity = create();
339         *entity = *e;
340         entity->id(-1);
341         return entity;
342     }
343 
344     /**
345     * Saves the Data record to the database table.
346     * Either create a new record or update the existing record.
347     * Remove old record from the memory table (cache)
348     */
saveDB_Table_ATTACHMENT_V1349     bool save(Self::Data* entity, wxSQLite3Database* db)
350     {
351         wxString sql = wxEmptyString;
352         if (entity->id() <= 0) //  new & insert
353         {
354             sql = "INSERT INTO ATTACHMENT_V1(REFTYPE, REFID, DESCRIPTION, FILENAME) VALUES(?, ?, ?, ?)";
355         }
356         else
357         {
358             sql = "UPDATE ATTACHMENT_V1 SET REFTYPE = ?, REFID = ?, DESCRIPTION = ?, FILENAME = ? WHERE ATTACHMENTID = ?";
359         }
360 
361         try
362         {
363             wxSQLite3Statement stmt = db->PrepareStatement(sql);
364 
365             stmt.Bind(1, entity->REFTYPE);
366             stmt.Bind(2, entity->REFID);
367             stmt.Bind(3, entity->DESCRIPTION);
368             stmt.Bind(4, entity->FILENAME);
369             if (entity->id() > 0)
370                 stmt.Bind(5, entity->ATTACHMENTID);
371 
372             stmt.ExecuteUpdate();
373             stmt.Finalize();
374 
375             if (entity->id() > 0) // existent
376             {
377                 for(Cache::iterator it = cache_.begin(); it != cache_.end(); ++ it)
378                 {
379                     Self::Data* e = *it;
380                     if (e->id() == entity->id())
381                         *e = *entity;  // in-place update
382                 }
383             }
384         }
385         catch(const wxSQLite3Exception &e)
386         {
387             wxLogError("ATTACHMENT_V1: Exception %s, %s", e.GetMessage().c_str(), entity->to_json());
388             return false;
389         }
390 
391         if (entity->id() <= 0)
392         {
393             entity->id((db->GetLastRowId()).ToLong());
394             index_by_id_.insert(std::make_pair(entity->id(), entity));
395         }
396         return true;
397     }
398 
399     /** Remove the Data record from the database and the memory table (cache) */
removeDB_Table_ATTACHMENT_V1400     bool remove(int id, wxSQLite3Database* db)
401     {
402         if (id <= 0) return false;
403         try
404         {
405             wxString sql = "DELETE FROM ATTACHMENT_V1 WHERE ATTACHMENTID = ?";
406             wxSQLite3Statement stmt = db->PrepareStatement(sql);
407             stmt.Bind(1, id);
408             stmt.ExecuteUpdate();
409             stmt.Finalize();
410 
411             Cache c;
412             for(Cache::iterator it = cache_.begin(); it != cache_.end(); ++ it)
413             {
414                 Self::Data* entity = *it;
415                 if (entity->id() == id)
416                 {
417                     index_by_id_.erase(entity->id());
418                     delete entity;
419                 }
420                 else
421                 {
422                     c.push_back(entity);
423                 }
424             }
425             cache_.clear();
426             cache_.swap(c);
427         }
428         catch(const wxSQLite3Exception &e)
429         {
430             wxLogError("ATTACHMENT_V1: Exception %s", e.GetMessage().c_str());
431             return false;
432         }
433 
434         return true;
435     }
436 
437     /** Remove the Data record from the database and the memory table (cache) */
removeDB_Table_ATTACHMENT_V1438     bool remove(Self::Data* entity, wxSQLite3Database* db)
439     {
440         if (remove(entity->id(), db))
441         {
442             entity->id(-1);
443             return true;
444         }
445 
446         return false;
447     }
448 
449     template<typename... Args>
get_oneDB_Table_ATTACHMENT_V1450     Self::Data* get_one(const Args& ... args)
451     {
452         for (Index_By_Id::iterator it = index_by_id_.begin(); it != index_by_id_.end(); ++ it)
453         {
454             Self::Data* item = it->second;
455             if (item->id() > 0 && match(item, args...))
456             {
457                 ++ hit_;
458                 return item;
459             }
460         }
461 
462         ++ miss_;
463 
464         return 0;
465     }
466 
467     /**
468     * Search the memory table (Cache) for the data record.
469     * If not found in memory, search the database and update the cache.
470     */
getDB_Table_ATTACHMENT_V1471     Self::Data* get(int id, wxSQLite3Database* db)
472     {
473         if (id <= 0)
474         {
475             ++ skip_;
476             return 0;
477         }
478 
479         Index_By_Id::iterator it = index_by_id_.find(id);
480         if (it != index_by_id_.end())
481         {
482             ++ hit_;
483             return it->second;
484         }
485 
486         ++ miss_;
487         Self::Data* entity = 0;
488         wxString where = wxString::Format(" WHERE %s = ?", PRIMARY::name().c_str());
489         try
490         {
491             wxSQLite3Statement stmt = db->PrepareStatement(this->query() + where);
492             stmt.Bind(1, id);
493 
494             wxSQLite3ResultSet q = stmt.ExecuteQuery();
495             if(q.NextRow())
496             {
497                 entity = new Self::Data(q, this);
498                 cache_.push_back(entity);
499                 index_by_id_.insert(std::make_pair(id, entity));
500             }
501             stmt.Finalize();
502         }
503         catch(const wxSQLite3Exception &e)
504         {
505             wxLogError("%s: Exception %s", this->name().c_str(), e.GetMessage().c_str());
506         }
507 
508         if (!entity)
509         {
510             wxLogError("%s: %d not found", this->name().c_str(), id);
511         }
512 
513         return entity;
514     }
515 
516     /**
517     * Return a list of Data records (Data_Set) derived directly from the database.
518     * The Data_Set is sorted based on the column number.
519     */
520     const Data_Set all(wxSQLite3Database* db, COLUMN col = COLUMN(0), bool asc = true)
521     {
522         Data_Set result;
523         try
524         {
525             wxSQLite3ResultSet q = db->ExecuteQuery(col == COLUMN(0) ? this->query() : this->query() + " ORDER BY " + column_to_name(col) + " COLLATE NOCASE " + (asc ? " ASC " : " DESC "));
526 
527             while(q.NextRow())
528             {
529                 Self::Data entity(q, this);
530                 result.push_back(entity);
531             }
532 
533             q.Finalize();
534         }
catchDB_Table_ATTACHMENT_V1535         catch(const wxSQLite3Exception &e)
536         {
537             wxLogError("%s: Exception %s", this->name().c_str(), e.GetMessage().c_str());
538         }
539 
540         return result;
541     }
542 };
543 #endif //
544