]> Creatis software - creaImageIO.git/blob - src2/creaImageIOSQLiteTreeHandler.cpp
Added synchronization
[creaImageIO.git] / src2 / creaImageIOSQLiteTreeHandler.cpp
1 #include <creaImageIOSQLiteTreeHandler.h>
2 #include <creaImageIOSystem.h>
3
4 #include "CppSQLite3.h"
5
6 #include <sys/stat.h>
7
8 //#include <creaImageIOSQLiteTreeHandlerStructure.h>
9
10 //#include <creaImageIOUtilities.h>
11
12 //#include <icons/database.xpm>
13
14 #include <deque>
15
16 #include "wx/wx.h"
17 #include <wx/dir.h>
18 #include <wx/filename.h>
19
20
21 //#include <icons/close.xpm>
22
23 #include <creaWx.h>
24 using namespace crea;
25
26 #include <boost/filesystem.hpp>
27 #include <boost/algorithm/string/replace.hpp>
28
29 namespace creaImageIO
30 {
31   using namespace tree;
32
33
34   //=============================================================
35   SQLiteTreeHandler::SQLiteTreeHandler(const std::string& filename)
36     : mFileName(filename)
37   {
38     mDB = new CppSQLite3DB;
39         mIsAdding=false;
40     GimmickMessage(1,"SQLite version : "
41                    <<std::string(mDB->SQLiteVersion())<< std::endl);
42   }
43   //=============================================================
44
45   //=============================================================
46   SQLiteTreeHandler::~SQLiteTreeHandler()
47   {
48     delete mDB;
49   }
50   //=============================================================
51   
52
53   //=============================================================
54   //  void SQLiteTreeHandler::Print() const 
55   //  {
56     /*
57     std::cout << "-> '"<<GetName()<< "' - '"
58               << GetFileName()<<"'"<<std::endl;
59     ChildrenListType::const_iterator i;
60     for (i=GetChildrenList().begin(); i!=GetChildrenList().end(); i++)
61       {
62         (*i)->Print();
63       }
64     */
65   //  }
66   //=============================================================
67   
68   //=====================================================================
69   /*
70   bool SQLiteTreeHandler::LocationIsValid()
71   {
72     // TO DO 
73     return true;
74   }
75   */
76   //=====================================================================
77
78
79   //=====================================================================
80   bool SQLiteTreeHandler::Open(bool writable)
81   {
82     //    std::cout << "***> SQLiteTreeHandler::Open('"<<GetFileName()<<"')"<<std::endl;
83     SetWritable(writable);
84     return DBOpen();
85   }
86
87   //=====================================================================
88   bool SQLiteTreeHandler::Create(bool writable)
89   {
90     //    std::cout << "***> SQLiteTreeHandler::New('"<<GetFileName()<<"')"<<std::endl;
91     SetWritable(writable);
92     return DBCreate();
93   }
94   //=====================================================================
95
96
97   //=====================================================================
98   bool SQLiteTreeHandler::Close()
99   {
100     return true;
101   }
102   //=====================================================================
103
104
105   //=====================================================================
106   bool SQLiteTreeHandler::Destroy()
107   {
108     return false;
109   }
110   
111   //===================================================================== 
112
113   //===================================================================== 
114   int SQLiteTreeHandler::LoadChildren(tree::Node* parent, int maxlevel)
115   {
116     if (parent==0) parent = GetTree().GetTree();
117     return DBLoadChildren(parent,maxlevel);
118   }
119   //===================================================================== 
120
121
122
123
124   //===================================================================== 
125   void SQLiteTreeHandler::UnLoad(tree::Node* n)
126   {
127   }
128   //===================================================================== 
129
130   //===================================================================== 
131   int SQLiteTreeHandler::AddBranch( const AttributeMapType& attr )
132   {
133     tree::Node* parent = DBGetParent(attr);
134     DBGraftToParent(parent,attr);
135     return (parent->GetLevel()+1);
136           
137   }
138   //===================================================================== 
139  
140
141   //===================================================================== 
142    bool SQLiteTreeHandler::Remove(tree::Node* node)
143    {
144    DBRecursiveRemoveNode(node);
145  
146     //    std::cout << "DELETE"<<std::endl;
147    bool remove=false;
148    tree::Node* parent=node->GetParent();
149     if (parent)
150       {
151         int nC = parent->RemoveChildrenFromList(node);
152         if(nC>0)
153         {       
154                 std::stringstream out;
155                 out <<nC;
156                 SetAttribute(parent,"NumberOfChildren",out.str());
157         }
158         else
159         {
160                 remove=true;
161         }
162
163       }
164     delete node;
165         if(remove&&parent->GetLevel()>0)
166         {
167                 Remove(parent);
168         }
169     //    std::cout << "DELETE OK"<<std::endl;
170     return true;
171    }
172   
173   //===================================================================== 
174
175   //===================================================================== 
176   /// Sets an attribute of a Node
177   bool SQLiteTreeHandler::SetAttribute(tree::Node* n, 
178                                        const std::string& key,
179                                        const std::string& value)
180   {
181     if (n==0) n=GetTree().GetTree();
182     return DBSetAttribute(n,key,value);
183   }
184   //===================================================================== 
185    //===================================================================== 
186   /// Sets an attribute
187   void SQLiteTreeHandler::SetAttribute(const std::string& levelDescriptor, 
188                               const std::string& key,
189                               const std::string& value,
190                                   const std::string& searchParam, 
191                                   const std::string& searchVal)
192   {
193         DBSetAttribute(levelDescriptor,key,value,searchParam, searchVal);
194   }
195   //===================================================================== 
196   /// Deletes a tuple
197   void SQLiteTreeHandler::DeleteTuple(std::string levelDescriptor, 
198                                                                 std::string key, std::string value)
199   {
200     DBDelete(levelDescriptor,key,value);
201   }
202   //===================================================================== 
203
204
205
206
207
208
209
210
211
212
213
214
215
216   //=====================================================================
217   // SQLite DB specific methods
218   //=====================================================================
219
220
221
222
223   //=====================================================================
224   char* format_sql(const std::string& s)
225   { 
226     return sqlite3_mprintf("%q",s.c_str());
227   }
228   //=====================================================================
229
230   //  sqlite3_exec(db, zSQL, 0, 0, 0);
231   //  sqlite3_free(zSQL);
232   //    char* CHAIN = format_sql(QUER);         \
233 //  sqlite3_free(CHAIN);                                \
234
235   //=====================================================================
236 #define QUERYDB(QUER,RES)                                               \
237     try                                                                 \
238       {                                                                 \
239         GimmickMessage(2,"SQL query: '"<<QUER<<"'"<<std::endl);         \
240         RES = mDB->execQuery(QUER.c_str());                             \
241       }                                                                 \
242     catch (CppSQLite3Exception& e)                                      \
243       {                                                                 \
244         GimmickError("SQLite query '"<<QUER<<"' : "                     \
245                      << e.errorCode() << ":"                            \
246                      << e.errorMessage() );                             \
247       }                                                                 \
248     
249   //=====================================================================
250   
251   //=====================================================================
252 #define UPDATEDB(UP)                                                    \
253   try                                                                   \
254     {                                                                   \
255       GimmickMessage(2,"SQL update: '"<<UP<<"'"<<std::endl);            \
256       mDB->execDML(UP.c_str());                                         \
257     }                                                                   \
258   catch (CppSQLite3Exception& e)                                        \
259     {                                                                   \
260       GimmickError("SQLite update '"<<UP<<"' Error : "                  \
261                    << e.errorCode() << ":"                              \
262                    << e.errorMessage() );                               \
263     }                                                                   
264   //=====================================================================
265
266
267   //=====================================================================
268   bool SQLiteTreeHandler::DBOpen()
269   {
270     GimmickMessage(1,"Opening SQLite database '"<<GetFileName()
271                    <<"' ... "<<std::endl);
272     // OPENING FILE
273     if (!boost::filesystem::exists(GetFileName())) 
274       {
275         return false;
276       }
277
278     try
279       {
280         mDB->open(GetFileName().c_str());
281       }
282     catch (CppSQLite3Exception& e)
283       {
284         GimmickError("Opening '"<<GetFileName()<<"' : "
285                      << e.errorCode() << ":" 
286                      << e.errorMessage());
287         return false;
288       }
289     // IMPORT TREE DESCRIPTION (AND TEST DB VALIDITY)
290     if (!DBImportTreeDescription())
291       {
292         return false;
293       }
294
295     GimmickDebugMessage(1,"Opening SQLite database '"<<GetFileName()
296                    <<"' ... OK"<<std::endl);
297     return true;
298   }
299   //=====================================================================
300
301   //=====================================================================
302   bool SQLiteTreeHandler::DBCreate()
303   {
304     GimmickMessage(1,"Creating SQLite database '"<<GetFileName()
305                    <<"' ... "<<std::endl);
306
307     if (boost::filesystem::exists(GetFileName())) 
308       {
309         GimmickError(GetFileName()<<"' : "
310                      << "file already exists");
311         return false;
312       }
313     
314     // OPENING
315     try
316       {
317         mDB->open(GetFileName().c_str());
318       }
319     catch (CppSQLite3Exception& e)
320       {
321         GimmickError(e.errorCode() << ":" 
322                      << e.errorMessage() <<std::endl);
323         return false;
324       }
325     
326      
327     // CREATING TABLES
328     
329     std::string command;
330     // Create LEVELS table
331     command = "create table LEVELS\n";
332     command += "( Name text )\n";
333     UPDATEDB(command);
334     
335     // Iterate the Levels
336     for (int l=0; l<GetTree().GetNumberOfLevels(); ++l)
337       {
338         command = "INSERT INTO LEVELS (Name) VALUES ('";
339         command += GetTree().GetLevelDescriptor(l).GetName();
340         command += "')";
341         UPDATEDB(command);
342         
343         // Create table of level (for level>0, i.e. not Root)
344         if (l>=0)
345           {
346             command = "CREATE TABLE ";
347             command += GetTree().GetLevelDescriptor(l).GetName();
348             command += "\n(\nID INTEGER PRIMARY KEY";
349             if (l>1) 
350               {
351                 command += ",\nPARENT_ID int not null"; 
352               }
353             SQLAppendAttributesDefinition(l,command);
354             if (l>1) 
355               {
356                 command += ",\nconstraint FK_PARENT foreign key (PARENT_ID) references ";
357                 command += GetTree().GetLevelDescriptor(l-1).GetName();
358                 command += "(ID) on delete restrict on update restrict";
359               }
360             command += "\n)";
361             UPDATEDB(command);
362             
363             
364             // Add Attribute 'ID' to Description
365             GetTree().GetDescriptor().Add
366               (AttributeDescriptor( "ID",
367                                     "Database Identifier",
368                                     0,0,
369                                     AttributeDescriptor::PRIVATE
370                                     ),l);
371             
372             if (l>1) 
373               {
374                 // Add Attribute 'PARENT_ID' to Description
375                 GetTree().GetDescriptor().Add
376                   (AttributeDescriptor( "PARENT_ID",
377                                         "Database Parent Identifier",
378                                         0,0,
379                                         AttributeDescriptor::PRIVATE
380                                         ),l);
381               }
382             
383           }
384         
385         // Create table *_ATTRIBUTES
386         
387         command = "CREATE TABLE ";
388         command += GetTree().GetLevelDescriptor(l).GetName();
389         command += "_Attributes\n(\n";
390         command += "Key text,\n";
391         command += "Name text,\n";          
392         command += "DicomGroup int,\n";
393         command += "DicomElement int,\n";           
394         command += "Flags int\n";           
395         command += "\n)";
396         UPDATEDB(command);
397         
398         
399         // Fill the table *_ATTRIBUTES
400         LevelDescriptor::AttributeDescriptorListType::const_iterator i;
401         for (i  = GetTree().GetAttributeDescriptorList(l).begin();
402              i != GetTree().GetAttributeDescriptorList(l).end();
403              ++i)
404           {
405             
406             std::stringstream insert;
407             insert << "INSERT INTO "
408                    << GetTree().GetLevelDescriptor(l).GetName()
409                    << "_Attributes (Key,Name,DicomGroup,DicomElement,Flags) "
410                    << "VALUES ('"
411                    << i->GetKey() << "','"
412                    << i->GetName() << "',"
413                    << i->GetGroup() << ","
414                    << i->GetElement() << ","
415                    << i->GetFlags() << ");";
416             UPDATEDB(insert.str());
417           }
418
419       } // For l=0...
420
421     // Initialize the root attributes
422     GetTree().InitializeAttributeMap();
423     // Insert the root in the level 0 table 
424     DBInsert(GetTree().GetTree());
425     
426     
427     GetTree().SetChildrenLoaded(true);
428     GimmickMessage(1,"Creating SQLite database '"<<GetFileName()
429                    <<"' ... OK"<<std::endl);
430     return true;
431   }
432   //=====================================================================
433   
434   //=====================================================================
435   void SQLiteTreeHandler::SQLAppendAttributesDefinition(int level,
436                                                         std::string& s)
437   {
438     LevelDescriptor::AttributeDescriptorListType::const_iterator i;
439     for (i  = GetTree().GetAttributeDescriptorList(level).begin();
440          i != GetTree().GetAttributeDescriptorList(level).end();
441          ++i)
442       {
443         //      if (i->second.flags==1) continue;
444         s += ",\n";
445         s += i->GetKey();
446         s += " text";
447       }
448   }
449   //=====================================================================
450   
451   
452   //=====================================================================
453   bool SQLiteTreeHandler::DBImportTreeDescription()
454   {
455     GimmickMessage(1,"Importing tree description from database ..."
456                    <<std::endl);
457
458     // Test table 'LEVELS' existence
459     if ( ! mDB->tableExists("LEVELS") )
460       {
461         GimmickMessage(1,"!! ERROR : Table 'LEVELS' does not exist"
462                        <<std::endl);
463         return false;
464       }
465
466     tree::Descriptor& desc = GetTree().GetDescriptor();
467     // clears the existing one
468     desc.Clear();
469      
470     int nblevel = 0;
471     std::string query = "SELECT * FROM LEVELS";
472     CppSQLite3Query q;
473     QUERYDB(query,q);
474
475     while (!q.eof())
476       {
477         std::string name = q.getStringField(0);
478         GimmickMessage(2," * Importing level '"<<name<<"'"<<std::endl);
479         desc.Add(LevelDescriptor(name));
480         nblevel++;
481         q.nextRow();
482       }   
483     
484     for (int level = 0; level < nblevel; ++level )
485       {
486         std::string table = GetTree().GetLevelDescriptor(level).GetName();
487         table += "_Attributes";
488         // Test table 'LEVELS' existence
489         if ( ! mDB->tableExists(table.c_str()) )
490           {
491             GimmickMessage(1,"!! ERROR : Table '"<<table<<"' does not exist"
492                            <<std::endl);
493             return false;
494           }
495         
496         std::string query = "SELECT * FROM ";
497         query += table;
498         CppSQLite3Query q;
499         QUERYDB(query,q);
500         
501         GimmickMessage(2," * Level '"
502                        <<GetTree().GetLevelDescriptor(level).GetName()
503                        <<"'"<<std::endl);
504
505         // Test that ID and PARENT_ID mandatory attributes exist
506         bool ID_found = false;
507         bool PARENT_ID_found = false;
508         if (level==0) ID_found = true;
509         if (level<=1) PARENT_ID_found = true;
510
511         while (!q.eof())
512           {
513             std::string key(q.getStringField(0));
514             std::string name(q.getStringField(1));
515             GimmickMessage(2,"  - Importing attribute '"<<key<<"' '"<<name
516                            <<"'"<<std::endl);
517             desc.Add
518               (AttributeDescriptor( key, // Key
519                                     name, // Name
520                                     q.getIntField(2), // Group
521                                     q.getIntField(3), // Element 
522                                     q.getIntField(4) // Flags
523                                     ),level);
524             if ( key == "ID" ) 
525               {
526                 ID_found = true;
527               }
528             if ( key == "PARENT_ID" ) 
529               {
530                 PARENT_ID_found = true;
531               }
532             q.nextRow();
533           }
534         
535         if ( ! (ID_found || PARENT_ID_found ) )
536           {
537             GimmickMessage(1,"!! ERROR : Table '"<<table
538                            <<"' does not contain mandatory attribute ID or PARENT_ID"
539                            <<std::endl);
540             return false;
541  
542           }
543       }
544
545
546     // Create the attributes table for Root (i.e. Tree)
547     LevelDescriptor::AttributeDescriptorListType::const_iterator a;
548     for (a = GetTree().GetAttributeDescriptorList(0).begin();
549          a!= GetTree().GetAttributeDescriptorList(0).end();
550          ++a)
551       {
552         /*
553         std::string v;
554         AttributeMapType::const_iterator i = attr.find(a->GetKey());
555         if ( i != attr.end() )  
556           {
557             v = i->second;
558           }
559         */
560         GetTree().UnsafeSetAttribute( a->GetKey(), "" );
561       }
562
563     // Reading Root attributes
564     // Query DB
565     query = "SELECT * FROM ";
566     query += GetTree().GetLevelDescriptor(0).GetName();
567     QUERYDB(query,q);
568
569     for (int fld = 0; fld < q.numFields(); fld++)
570       {
571         GetTree().UnsafeSetAttribute(q.fieldName(fld),
572                                      q.getStringField(fld));        
573       }
574
575     GimmickMessage(1,"Importing tree description from database ... OK"
576                    <<std::endl);
577     return true;
578   }
579   //=====================================================================
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597   //========================================================================
598   /// 
599   std::string& SQLformat(std::string& str)
600   {
601     // quote must be doubled
602     boost::algorithm::replace_all(str,"'","''");
603     // Found strange strings which contained NULL char INSIDE string 
604     int i,size=str.size();
605     for (i=0;i<size;++i) 
606       {
607         if (str[i]==0) 
608           {
609             str = str.substr(0,i);
610             break;
611           }
612       }
613     //    if (i<str.size())
614     return str;
615   }
616   //========================================================================
617   
618   //=====================================================================
619   void SQLiteTreeHandler::SQLAppendAttributesValues(tree::Node* n, 
620                                                     std::string& str)
621   {
622     GimmickMessage(4,"SQLAppendAttributesValues"<<std::endl);
623     std::string atts="";
624     std::string values="";
625     tree::Node::AttributeMapType::iterator i;
626     for (i =  n->GetAttributeMap().begin();
627          i != n->GetAttributeMap().end();
628          i++)
629       {
630         if (i->first=="ID") 
631           {
632             continue;
633           }
634         //      std::cout << "("<<i->first<<","<<i->second<<")"<<std::endl;
635         atts += "'" + i->first + "'";
636         values += "'" + SQLformat(i->second) + "'"; 
637         atts += ",";
638         values += ",";
639         GimmickMessage(4,"'"<<i->first<<"' = '"<<i->second<<"'"<<std::endl);
640       }
641     atts[atts.size()-1]=' ';
642     values[values.size()-1]=' ';
643
644     str = "("+atts+") VALUES ("+values+")";
645     GimmickMessage(4,"Result = '"<<str<<"'"<<std::endl);
646   }
647   //=====================================================================
648
649   //=====================================================================
650   tree::Node* SQLiteTreeHandler::DBGetParent( const AttributeMapType& attr) 
651   {
652     Node* parent = GetTree().GetTree();
653     bool go_down;
654     do 
655       {
656         go_down = false;
657         // Load the children of the current parent
658         DBLoadChildren(parent);
659         // Iterate the children 
660         tree::Node::ChildrenListType::const_iterator i;
661         for (i = parent->GetChildrenList().begin();
662              i!= parent->GetChildrenList().end();
663              ++i)
664           {
665             if ( (*i)->Matches( attr ) ) 
666               {
667                 go_down = true;
668                 parent = *i;
669                 break;
670               }
671           }     
672       }
673     while (go_down);
674     return parent;
675   }
676   //=====================================================================
677
678
679   //=====================================================================
680   int SQLiteTreeHandler::DBLoadChildren(tree::Node* node, 
681                                         int numberoflevels)
682   {
683     if (node->GetLevel()+1 >= node->GetTree()->GetNumberOfLevels() ) 
684       return 0;
685
686     GimmickMessage(2,"Loading children of '"<<node->GetLabel()
687                    <<"'"<<std::endl);
688
689     int nbloaded = 0;
690     // If children loaded we do not have to do it but we need to recurse
691     // in order to load the children's children if necessary, and so on...
692     if (node->GetChildrenLoaded()) 
693       {
694         // Iterate the children 
695
696         tree::Node::ChildrenListType::iterator i;
697         for (i = node->GetChildrenList().begin();
698              i!= node->GetChildrenList().end();
699              ++i)
700           {
701             nbloaded += DBLoadChildren(*i,numberoflevels-1);
702           }
703         node->SetChildrenLoaded(true);
704         return nbloaded;
705
706       }
707         else
708         {
709     /// If children not loaded : do it and recurse
710
711     // Query DB
712     int level = node->GetLevel();
713     std::string query = "SELECT * FROM ";
714         
715     query += GetTree().GetLevelDescriptor(level+1).GetName();
716     if (level>0)
717       {
718         query += " WHERE PARENT_ID='" + node->UnsafeGetAttribute("ID") 
719           + "'";
720       }
721     CppSQLite3Query q;
722     QUERYDB(query,q);
723
724         int p=0;
725     while (!q.eof())
726       {
727
728         //      std::cout << "DBLoadCh : creating node level "<<level+1<<std::endl;
729
730         nbloaded++;
731         Node* n = new Node(node);
732         for (int fld = 0; fld < q.numFields(); fld++)
733           {
734             n->UnsafeSetAttribute(q.fieldName(fld),q.getStringField(fld));          
735           }
736         /*
737         // Index 
738         TypeId ti;
739         ti.type = type;
740         ti.id = n->GetFieldValue("ID");    
741         mTypeIdToNodeMap[ti] = n;
742         */
743         // recurse 
744         if ( numberoflevels != 1 ) 
745           {
746             //  msw[2].Pause();
747             nbloaded += DBLoadChildren(n, numberoflevels-1);
748             //      msw[2].Resume();
749           }
750         // next entry in db
751         q.nextRow();
752       }
753
754     node->SetChildrenLoaded(true);
755         
756     
757     //    msw[2].Pause();
758     return nbloaded;
759         }
760   }
761   //=====================================================================
762
763   //======================================================================
764   void SQLiteTreeHandler::DBInsert(tree::Node* n)
765   {
766     GimmickMessage(2,"Inserting in DB '"<<n->GetLabel()
767                    <<"'"<<std::endl);
768     std::string val;
769     SQLAppendAttributesValues(n,val);
770     std::string insert("INSERT INTO ");
771     insert += GetTree().GetLevelDescriptor(n->GetLevel()).GetName();
772     insert += " " + val + ";";
773
774     UPDATEDB(insert);
775         
776     // Store DB id of newly created node;
777     long lastrow = mDB->lastRowId();
778     std::stringstream ri;
779     ri << mDB->lastRowId();
780     n->SetAttribute("ID",ri.str());
781   }
782   //======================================================================
783
784   //======================================================================
785   /// Graft the branch defined by the attributes to the parent
786   void SQLiteTreeHandler::DBGraftToParent( tree::Node* parent, 
787                                             const AttributeMapType& attr)
788   {
789     //    std::cout <<"Grafting to parent '"<<parent->GetLabel()
790     //             <<"'"<<std::endl;
791
792     for (int level = parent->GetLevel()+1;
793          level < GetTree().GetNumberOfLevels();
794          level++)
795       {
796         // Create Node
797         tree::Node* child = new tree::Node(parent,attr);
798         child->SetChildrenLoaded(true);
799         if (level>1)
800           {
801             int nc = GetNumberOfChildren(parent)+1;
802             
803             //  std::cout<<"Number of children "<<parent->GetNumberOfChildren()<<std::endl;
804             std::stringstream out;
805             out << nc;
806             SetAttribute(parent,"NumberOfChildren",out.str());
807           }
808
809         // Set PARENT_ID if necessary 
810         if ( parent->GetLevel()>0 )
811           child->SetAttribute("PARENT_ID",parent->GetAttribute("ID"));
812         
813         // Insert in DB
814         DBInsert(child);
815         /*
816         std::string val;
817         SQLAppendAttributesValues(child,val);
818         std::string insert("INSERT INTO ");
819         insert += GetTree().GetLevelDescriptor(child->GetLevel()).GetName();
820         insert += " " + val + ";";
821         UPDATEDB(insert);
822         
823         // Store DB id of newly created node;
824         long lastrow = mDB->lastRowId();
825         std::stringstream ri;
826         ri << mDB->lastRowId();
827         child->SetAttribute("ID",ri.str());
828         */
829         // Down one level
830         parent = child;
831         
832         /*
833         // Insert in TypeId map
834         TypeId ti;
835         ti.type = node->GetType();
836         ti.id = node_id;
837         mTypeIdToNodeMap[ti] = node;
838         //    std::cout << "== Insert TypeId ("<<ti.type<<","<<ti.id<<")"<<std::endl; 
839         // 
840         msw[2].Pause();
841         
842         if (node->GetType()==Node::Patient) summary.added_patients++;
843         if (node->GetType()==Node::Study) summary.added_studies++;
844         if (node->GetType()==Node::Series) summary.added_series++;
845         if (node->GetType()==Node::Image) summary.added_images++;
846         */
847       }
848   }
849   //======================================================================
850
851
852   //===================================================================== 
853   /// Sets an attribute of a Node
854   bool SQLiteTreeHandler::DBSetAttribute(tree::Node* n, 
855                                          const std::string& key,
856                                          const std::string& value)
857   {
858     GimmickMessage(3,"Setting Attribute of '"<<n->GetLabel()<<
859                    "' "<<key<<"='"<<value<<"'"<<std::endl);
860
861     n->SetAttribute(key,value);
862     std::string sql = "UPDATE ";
863     sql += GetTree().GetLevelDescriptor(n->GetLevel()).GetName();
864     sql += " SET ";
865     sql += key;
866     sql += " = '";
867     sql += value;
868     sql += "' WHERE ID = '";
869     sql += n->GetAttribute("ID");
870         sql +="'";
871     //    sql += " LIMIT 1";
872     UPDATEDB(sql);
873   }
874
875   //===================================================================== 
876   /// Sets an attribute of a Node
877   void SQLiteTreeHandler::DBSetAttribute(const std::string& levelDescriptor, 
878                               const std::string& key,
879                               const std::string& value,
880                                   const std::string& searchParam, 
881                                   const std::string& searchVal)
882   {
883
884     std::string sql = "UPDATE ";
885     sql += levelDescriptor;
886     sql += " SET ";
887     sql += key;
888     sql += " = '";
889     sql += value;
890     sql += "' WHERE ";
891         sql += searchParam;
892         sql += " = '";
893     sql += searchVal;
894         sql += "'";
895     UPDATEDB(sql);
896   }
897    //=====================================================================
898   void SQLiteTreeHandler::DBRecursiveRemoveNode(Node* node)
899   {
900        
901     std::string query = "DELETE FROM ";
902    
903     query += GetTree().GetLevelDescriptor(node->GetLevel()).GetName();
904     query += " WHERE ID='"+ node->GetAttribute("ID") + "';";
905  
906     UPDATEDB(query);
907         GimmickDebugMessage(2,
908                             " Deleting '"
909                                 <<node->GetLabel()<<"' with ID '"
910                             <<node->GetAttribute("ID")
911                             <<"' in level "<< GetTree().GetLevelDescriptor(node->GetLevel()).GetName()
912                             <<std::endl);
913
914
915         if(node->GetNumberOfChildren()!=0)
916         {
917                 Node::ChildrenListType::iterator i;
918                 for (i  = node->GetChildrenList().begin();
919                 i != node->GetChildrenList().end();
920                 i++)
921                 {
922                 DBRecursiveRemoveNode((*i));
923                 }
924         }
925         else if(node->GetLevel()<GetTree().GetNumberOfLevels()-1)
926         {
927                 DBRecursiveRemoveNode(node->GetLevel()+1,node->GetAttribute("ID"));
928     }
929   }
930
931   //=====================================================================
932   void SQLiteTreeHandler::DBRecursiveRemoveNode(int level, std::string parentId)
933   {
934     std::stringstream out;
935         std::stringstream result;
936         out<<"SELECT ID FROM "<<GetTree().GetLevelDescriptor(level).GetName()<<" WHERE PARENT_ID='"<<parentId<<"'";
937                 
938         CppSQLite3Query q;
939         QUERYDB(out.str(),q);
940         
941         while (!q.eof())
942           {
943             for (int fld = 0; fld < q.numFields(); fld++)
944               {
945                           result<<q.getStringField(fld)<<"#";
946               }
947             q.nextRow();
948           }
949           std::string res=result.str();
950           size_t ini=0;
951           size_t fin=0;
952           while(fin<res.size()-1)
953           {
954            fin=res.find('#',ini);
955            DBDelete(GetTree().GetLevelDescriptor(level).GetName(),"ID",res.substr(ini,fin-ini));
956           if(level<GetTree().GetNumberOfLevels()-1)
957           {
958                 DBRecursiveRemoveNode(level+1,res.substr(ini,fin-ini));
959           } 
960            ini=fin+1;
961           }
962           
963     
964   }
965
966   //=====================================================================
967   void SQLiteTreeHandler::DBDelete(std::string levelDescriptor, std::string key, std::string value)
968   {
969        
970     std::stringstream query;
971         query<<"DELETE FROM "<<levelDescriptor<<" WHERE "<<key<<"='"<<value<<"';";
972  
973     UPDATEDB(query.str());
974         GimmickDebugMessage(2," Deleting: Query: "<<query.str()<<std::endl);
975   }
976
977
978   //===================================================================== 
979   void SQLiteTreeHandler::GetAttribute(std::string levelDescriptor,
980                                                                            std::string searchParam, 
981                                                                            std::string searchVal, 
982                                                                            std::string key, 
983                                                                            std::string& result) 
984   { 
985         std::stringstream out;
986         std::stringstream results;
987         out<<"SELECT "<<key<<" FROM "<<levelDescriptor;
988         if(searchParam!="")
989         {
990                 out<<" WHERE "<<searchParam<<"='"<<searchVal<<"'";
991         }
992         
993         CppSQLite3Query q;
994         QUERYDB(out.str(),q);
995         
996         
997         while (!q.eof())
998           {
999             for (int fld = 0; fld < q.numFields(); fld++)
1000               {
1001                           results<<q.getStringField(fld);
1002                           if(searchParam=="")
1003                           {
1004                                   results<<"#";
1005                           }
1006               }
1007             q.nextRow();
1008           }
1009         result=results.str();
1010       
1011   }
1012   //===================================================================== 
1013   unsigned int SQLiteTreeHandler::GetNumberOfChildren(tree::Node* n) 
1014   { 
1015     // Query DB
1016     int nb=0;
1017     int level = n->GetLevel();
1018
1019     if(level<GetTree().GetNumberOfLevels()&& level>0)
1020       {
1021         std::string query = "SELECT NumberOfChildren FROM ";
1022         query += GetTree().GetLevelDescriptor(level).GetName();
1023         if (level>0)
1024           {
1025             query += " WHERE ID='" + n->UnsafeGetAttribute("ID") 
1026               + "'";
1027           }
1028         CppSQLite3Query q;
1029         QUERYDB(query,q);
1030         
1031         
1032         while (!q.eof())
1033           {
1034             for (int fld = 0; fld < q.numFields(); fld++)
1035               {
1036                 nb=q.getIntField(fld);  
1037               }
1038             q.nextRow();
1039           }
1040       }
1041     /*
1042     if(nb==0)
1043       { 
1044         nb=1;
1045       }
1046     */
1047     return nb; 
1048   }
1049
1050   //===================================================================== 
1051   void SQLiteTreeHandler::GetTopLevelNodeId(const std::string& searchParam, const std::string& searchValue, std::string& parent_id) 
1052   {
1053           int level=GetTree().GetNumberOfLevels()-1;
1054           std::string sp=searchParam.c_str();
1055           std::string sv=searchValue.c_str();
1056
1057           while(level>1)
1058           {
1059                 std::stringstream out;
1060                 std::stringstream results;
1061                 out<<"SELECT PARENT_ID FROM "<<GetTree().GetLevelDescriptor(level).GetName();
1062                 out<<" WHERE "<<sp<<"='"<<sv<<"'";      
1063                 CppSQLite3Query q;
1064                 QUERYDB(out.str(),q);
1065                 
1066                 
1067                 while (!q.eof())
1068                 {
1069                         for (int fld = 0; fld < q.numFields(); fld++)
1070                         {
1071                                 results<<q.getStringField(fld);
1072                         }
1073                         q.nextRow();
1074                 }
1075                 level=level-1;
1076                 sp="ID";
1077                 sv=results.str();
1078           }
1079           parent_id=sv;
1080
1081   }
1082
1083   /*
1084   //=====================================================================
1085   bool SQLiteTreeHandler::DBInsert(Node* alien_node,
1086                                    UpdateSummary& summary)
1087   {
1088     //    std::cout << "SQLiteTreeHandler::Insert('"<<alien_node->GetLabel()
1089     //        <<"')"<<std::endl;
1090     
1091     //    if (!ChildrenLoaded()) DBLoadChildren(this,Node::Database);
1092     
1093     // Find parent
1094     Node* parent;
1095     std::string parent_id; 
1096     parent = DBGetOrCreateParent(alien_node,parent_id,summary);
1097     
1098     // Insert 
1099     DBRecursiveGetOrCreateNode(alien_node,parent,parent_id,summary);
1100    return true;
1101   }
1102   //=====================================================================
1103
1104
1105   //=====================================================================
1106   Node* SQLiteTreeHandler::DBGetOrCreateParent(Node* alien_node,
1107                                                 std::string& parent_id,
1108                                                 UpdateSummary& summary)
1109   {
1110     //    std::cout << "DBGetOrCreateParent '" << alien_node->GetLabel()<<"'"
1111     //        << std::endl;
1112     // Load the patients if not already done
1113     DBLoadChildren(this,Node::Patient);
1114
1115     parent_id = "";
1116     Node* parent = this;
1117
1118     // The chain of ancestors
1119     std::deque<Node*> chain;
1120     Node* cur = alien_node->GetParent();
1121     for (int type=Node::Patient; 
1122          type<alien_node->GetType();++type)
1123       {
1124         chain.push_front(cur);
1125         cur = cur->GetParent();
1126       }
1127
1128     // create the nodes if do not exist
1129     std::deque<Node*>::iterator i;
1130     for (i=chain.begin();i!=chain.end();++i)
1131       {
1132         //      std::cout << " cur = '"<<(*i)->GetLabel()<<"'"<<std::endl;
1133         //      std::string cur_id = DBGetNodeId(*i,parent_id);
1134         //      if (cur_id.size()==0)
1135         //        {
1136         // Node does not exist : create it
1137         std::string cur_id;
1138         parent = DBGetOrCreateNode(*i, 
1139                                         parent,
1140                                         parent_id,
1141                                         cur_id,
1142                                         summary
1143                                         );
1144         DBLoadChildren(parent,parent->GetType()+1);
1145
1146         parent_id = cur_id;
1147       }
1148     return parent;
1149   }
1150   //=====================================================================
1151
1152
1153
1154   //=====================================================================
1155   void SQLiteTreeHandler::DBRecursiveGetOrCreateNode(Node* alien_node, 
1156                                                       Node* parent, 
1157                                                       const std::string& parent_id,
1158                                                       UpdateSummary& summary)
1159   {
1160     //    std::cout << "SQLiteTreeHandler::RecursiveGetOrCreateNode('"
1161     //        <<alien_node->GetLabel()
1162     //        <<"','"<<parent<<"','"<<parent_id<<"')"<<std::endl;
1163     if (parent != 0) 
1164       {
1165         //      std::cout << " -- Parent = '"<<parent->GetLabel()<<"'"<<std::endl;
1166       }   
1167     std::string new_id;
1168     Node* new_node = DBGetOrCreateNode(alien_node, 
1169                                                  parent,
1170                                                  parent_id,
1171                                                  new_id,
1172                                                  summary);
1173     Node::ChildrenListType::iterator i;
1174     for (i  = alien_node->GetChildrenList().begin();
1175          i != alien_node->GetChildrenList().end();
1176          i++)
1177       {
1178         DBRecursiveGetOrCreateNode((*i),new_node,new_id,summary);
1179       }
1180   }
1181   //=====================================================================
1182
1183
1184   //=====================================================================
1185   Node* SQLiteTreeHandler::DBGetOrCreateNode(Node* alien_node, 
1186                                                    Node* internal_parent,
1187                                                    std::string parent_id,
1188                                                    std::string& node_id,
1189                                                    UpdateSummary& summary)
1190   {
1191     //   std::cout << "DBGetOrCreateNode('"<<alien_node->GetLabel()<<"','"
1192     //        << internal_parent << "','"<< parent_id<<"')"<<std::endl;
1193     if (internal_parent != 0) 
1194       {
1195         //      std::cout << " -- Parent = '"<<internal_parent->GetLabel()<<"'"<<std::endl;
1196       }
1197     // Node Exists ? return it 
1198     // First try among children of internal parent 
1199     Node* node = GetChildrenLike(internal_parent,alien_node);
1200     if (node>0)
1201       {
1202         node_id = node->UnsafeGetFieldValue("ID");
1203         return node;
1204       }
1205     // Second : try in DB 
1206    
1207     // Does not exist : Create new one
1208     node = new Node(alien_node->GetType(),this,internal_parent);
1209     node->SetChildrenLoaded(true);
1210     // Copy fields values from alien
1211     Node::FieldValueMapType::iterator i,j;
1212     for (i =  node->GetFieldValueMap().begin();
1213          i != node->GetFieldValueMap().end();
1214          i++)
1215       {
1216         j = alien_node->GetFieldValueMap().find(i->first);
1217         if (j != alien_node->GetFieldValueMap().end() )
1218           {
1219             i->second = j->second;
1220           }
1221       }
1222
1223     msw[2].Resume();
1224     if (node->GetType()!=Node::Patient) 
1225       node->SetFieldValue("PARENT_ID",parent_id);
1226
1227     // Insert in DB
1228     std::string val;
1229     BuildSQLFieldsValues(node,val);
1230     std::string insert("INSERT INTO ");
1231     insert += std::string(SQLiteTreeHandlerStructure::Table(node->GetType())) 
1232       + " " + val + ";";
1233     //    std::cout << "** SQL = '"<<insert<<"'"<<std::endl;
1234     UPDATEDB(insert);
1235     //    std::cout << "** SQL OK"<<std::endl;
1236
1237     // Store DB id of newly created node;
1238     long lastrow = mDB->lastRowId();
1239     std::stringstream ri;
1240     ri << mDB->lastRowId();
1241     node_id = ri.str();
1242     //    std::cout << "LastRowId='"<<mDB->lastRowId()<<"' vs '"<<created_id<<"'"<<std::endl;
1243
1244     node->SetFieldValue("ID",node_id);
1245     // Insert in TypeId map
1246     TypeId ti;
1247     ti.type = node->GetType();
1248     ti.id = node_id;
1249     mTypeIdToNodeMap[ti] = node;
1250     //    std::cout << "== Insert TypeId ("<<ti.type<<","<<ti.id<<")"<<std::endl; 
1251     // 
1252     msw[2].Pause();
1253
1254     if (node->GetType()==Node::Patient) summary.added_patients++;
1255     if (node->GetType()==Node::Study) summary.added_studies++;
1256     if (node->GetType()==Node::Series) summary.added_series++;
1257     if (node->GetType()==Node::Image) summary.added_images++;
1258
1259     return node;
1260   }
1261   //=====================================================================
1262
1263   //=====================================================================
1264   Node* SQLiteTreeHandler::GetChildrenLike(Node* parent,
1265                                             Node* alien_node)
1266   {
1267     Node::ChildrenListType::iterator i;
1268     for (i  = parent->GetChildrenList().begin();
1269          i != parent->GetChildrenList().end();
1270          i++)
1271       {
1272         Node::Type type = alien_node->GetType();
1273         bool ok = true;
1274         for (int j=0;
1275              j<SQLiteTreeHandlerStructure::NbQueryFields(type);
1276              j++) 
1277           {
1278             if ( 
1279                 alien_node->GetFieldValue(SQLiteTreeHandlerStructure::
1280                                     QueryField(type,j).key )   !=
1281                 (*i)->GetFieldValue(SQLiteTreeHandlerStructure::
1282                                     QueryField(type,j).key ) )
1283               {
1284                 ok = false;
1285                 break;
1286               }
1287           }
1288         if (ok) 
1289           {
1290             return (*i);
1291           }
1292       }
1293     return 0;    
1294   }
1295   //=====================================================================
1296
1297   //=====================================================================
1298   std::string SQLiteTreeHandler::DBGetNodeId(Node* node, 
1299                                               const std::string& parent_id)
1300   {
1301     //    std::cout << "SQLiteTreeHandler::DBGetNodeId('"<<node->GetLabel()
1302     //        <<"','"<<parent_id<<"')"
1303     //        <<std::endl;
1304     msw[2].Resume();
1305     int type = node->GetType();
1306
1307     std::string table = SQLiteTreeHandlerStructure::Table(type);
1308     std::string where = "WHERE ";
1309     
1310     if (type!=Node::Patient)
1311       {
1312         where += "PARENT_ID='" + parent_id 
1313           //node->GetFieldValue("PARENT_ID") 
1314           + "' AND ";
1315       }
1316
1317     for (int i=0;i<SQLiteTreeHandlerStructure::NbQueryFields(type);i++) 
1318       {
1319         where += SQLiteTreeHandlerStructure::QueryField(type,i).key + "='"
1320           + node->GetFieldValue(SQLiteTreeHandlerStructure::QueryField(type,i).key) + "' ";
1321         if (i<SQLiteTreeHandlerStructure::NbQueryFields(type)-1)
1322           where += "AND ";
1323     }
1324
1325     std::string query = "SELECT ID FROM " + table + " " + where + ";";                                                    
1326     //    std::cout << "** SQL = '"<<query<<"'"<<std::endl;
1327     CppSQLite3Query q;
1328     QUERYDB(query,q);
1329
1330     if (!q.eof())
1331       {
1332         
1333         //      std::cout << " - Node exists " << std::endl;
1334         std::string id = q.getStringField(0);
1335         //      std::cout << " id = '"<<id<<"'"<<std::endl;
1336         msw[2].Pause();
1337         return id;
1338       }
1339     msw[2].Pause();
1340     return "";
1341   }
1342   //=====================================================================
1343
1344
1345
1346   //=====================================================================
1347   Node* SQLiteTreeHandler::GetNodeFromTypeId(Node::Type type,
1348                                        const std::string& id)
1349   {
1350     //    std::cout << "GetNodeFromTypeId("<<type<<","<<id<<")"<<std::endl;
1351
1352     TypeId ti;
1353     ti.type = type;
1354     ti.id = id;
1355     
1356     TypeIdToNodeMapType::iterator i = mTypeIdToNodeMap.find(ti);
1357     if (i == mTypeIdToNodeMap.end())
1358       {
1359
1360             std::cout << "Internal error : mTypeIdToNodeMap does not contain key"
1361                       << std::endl;
1362             creaError("Internal error : mTypeIdToNodeMap does not contain key");
1363             // }
1364       }
1365
1366     //    std::cout << " ** Node = "<<i->second<<std::endl;
1367     return i->second;
1368   }
1369  
1370   //=====================================================================
1371
1372   //=====================================================================
1373   bool SQLiteTreeHandler::Remove(Node* node)
1374   {
1375
1376     //DBRecursiveRemoveNode(node);
1377  
1378     //    std::cout << "DELETE"<<std::endl;
1379     if (node->GetParent())
1380       {
1381         node->GetParent()->RemoveChildrenFromList(node);
1382       }
1383     delete node;
1384     //    std::cout << "DELETE OK"<<std::endl;
1385     return true;
1386   }
1387   
1388   
1389   //========================================================================
1390
1391   //=====================================================================
1392   void SQLiteTreeHandler::DBRecursiveRemoveNode(Node* node)
1393   {
1394     //    std::cout << "SQLiteTreeHandler::DBRecursiveRemoveNode('"
1395     //        <<node->GetLabel()<<"')"<<std::endl;
1396
1397     std::string query = "DELETE FROM ";
1398     query += SQLiteTreeHandlerStructure::Table(node->GetType());
1399     query += " WHERE ID='"+ node->GetFieldValue("ID") + "';";
1400  
1401     UPDATEDB(query);
1402
1403     Node::ChildrenListType::iterator i;
1404     for (i  = node->GetChildrenList().begin();
1405          i != node->GetChildrenList().end();
1406          i++)
1407       {
1408         DBRecursiveRemoveNode((*i));
1409       }
1410   }
1411   
1412   //=====================================================================
1413   
1414   //=====================================================================
1415   int SQLiteTreeHandler::DBQueryNumberOfChildren(Node* node)
1416   {
1417     std::string query = "SELECT COUNT (ID) FROM ";
1418     query += SQLiteTreeHandlerStructure::Table(node->GetType()+1);
1419     if (node->GetType() != Node::Database) 
1420       {
1421         query += " WHERE PARENT_ID='"+ node->GetFieldValue("ID")+"'";
1422       }
1423     query  += ";";
1424     
1425     //   std::cout << "**SQL = "<< query << std::endl;
1426     
1427     CppSQLite3Query q;
1428     QUERYDB(query,q);
1429    
1430      //    std::cout << "**RES = "<< q.getIntField(0) <<std::endl;
1431
1432     return q.getIntField(0);
1433   }
1434   //=====================================================================
1435  
1436  
1437
1438 */
1439
1440
1441
1442 } // namespace creaImageIO