1 #include <creaImageIOSQLiteTreeHandler.h>
2 #include <creaImageIOSystem.h>
4 #include "CppSQLite3.h"
8 //#include <creaImageIOSQLiteTreeHandlerStructure.h>
10 //#include <creaImageIOUtilities.h>
12 //#include <icons/database.xpm>
18 #include <wx/filename.h>
21 //#include <icons/close.xpm>
26 #include <boost/filesystem.hpp>
27 #include <boost/algorithm/string/replace.hpp>
34 //=============================================================
35 SQLiteTreeHandler::SQLiteTreeHandler(const std::string& filename)
38 mDB = new CppSQLite3DB;
40 GimmickMessage(1,"SQLite version : "
41 <<std::string(mDB->SQLiteVersion())<< std::endl);
43 //=============================================================
45 //=============================================================
46 SQLiteTreeHandler::~SQLiteTreeHandler()
50 //=============================================================
53 //=============================================================
54 // void SQLiteTreeHandler::Print() const
57 std::cout << "-> '"<<GetName()<< "' - '"
58 << GetFileName()<<"'"<<std::endl;
59 ChildrenListType::const_iterator i;
60 for (i=GetChildrenList().begin(); i!=GetChildrenList().end(); i++)
66 //=============================================================
68 //=====================================================================
70 bool SQLiteTreeHandler::LocationIsValid()
76 //=====================================================================
79 //=====================================================================
80 bool SQLiteTreeHandler::Open(bool writable)
82 // std::cout << "***> SQLiteTreeHandler::Open('"<<GetFileName()<<"')"<<std::endl;
83 SetWritable(writable);
87 //=====================================================================
88 bool SQLiteTreeHandler::Create(bool writable)
90 // std::cout << "***> SQLiteTreeHandler::New('"<<GetFileName()<<"')"<<std::endl;
91 SetWritable(writable);
94 //=====================================================================
97 //=====================================================================
98 bool SQLiteTreeHandler::Close()
102 //=====================================================================
105 //=====================================================================
106 bool SQLiteTreeHandler::Destroy()
111 //=====================================================================
113 //=====================================================================
114 int SQLiteTreeHandler::LoadChildren(tree::Node* parent, int maxlevel)
116 if (parent==0) parent = GetTree().GetTree();
117 return DBLoadChildren(parent,maxlevel);
119 //=====================================================================
124 //=====================================================================
125 void SQLiteTreeHandler::UnLoad(tree::Node* n)
128 //=====================================================================
130 //=====================================================================
131 int SQLiteTreeHandler::AddBranch( const AttributeMapType& attr )
133 tree::Node* parent = DBGetParent(attr);
134 DBGraftToParent(parent,attr);
135 return (parent->GetLevel()+1);
138 //=====================================================================
141 //=====================================================================
142 bool SQLiteTreeHandler::Remove(tree::Node* node)
144 DBRecursiveRemoveNode(node);
146 // std::cout << "DELETE"<<std::endl;
148 tree::Node* parent=node->GetParent();
151 int nC = parent->RemoveChildrenFromList(node);
154 std::stringstream out;
156 SetAttribute(parent,"NumberOfChildren",out.str());
165 if(remove&&parent->GetLevel()>0)
169 // std::cout << "DELETE OK"<<std::endl;
173 //=====================================================================
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)
181 if (n==0) n=GetTree().GetTree();
182 return DBSetAttribute(n,key,value);
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)
193 DBSetAttribute(levelDescriptor,key,value,searchParam, searchVal);
195 //=====================================================================
197 void SQLiteTreeHandler::DeleteTuple(std::string levelDescriptor,
198 std::string key, std::string value)
200 DBDelete(levelDescriptor,key,value);
202 //=====================================================================
216 //=====================================================================
217 // SQLite DB specific methods
218 //=====================================================================
223 //=====================================================================
224 char* format_sql(const std::string& s)
226 return sqlite3_mprintf("%q",s.c_str());
228 //=====================================================================
230 // sqlite3_exec(db, zSQL, 0, 0, 0);
231 // sqlite3_free(zSQL);
232 // char* CHAIN = format_sql(QUER); \
233 // sqlite3_free(CHAIN); \
235 //=====================================================================
236 #define QUERYDB(QUER,RES) \
239 GimmickMessage(2,"SQL query: '"<<QUER<<"'"<<std::endl); \
240 RES = mDB->execQuery(QUER.c_str()); \
242 catch (CppSQLite3Exception& e) \
244 GimmickError("SQLite query '"<<QUER<<"' : " \
245 << e.errorCode() << ":" \
246 << e.errorMessage() ); \
249 //=====================================================================
251 //=====================================================================
252 #define UPDATEDB(UP) \
255 GimmickMessage(2,"SQL update: '"<<UP<<"'"<<std::endl); \
256 mDB->execDML(UP.c_str()); \
258 catch (CppSQLite3Exception& e) \
260 GimmickError("SQLite update '"<<UP<<"' Error : " \
261 << e.errorCode() << ":" \
262 << e.errorMessage() ); \
264 //=====================================================================
267 //=====================================================================
268 bool SQLiteTreeHandler::DBOpen()
270 GimmickMessage(1,"Opening SQLite database '"<<GetFileName()
271 <<"' ... "<<std::endl);
273 if (!boost::filesystem::exists(GetFileName()))
280 mDB->open(GetFileName().c_str());
282 catch (CppSQLite3Exception& e)
284 GimmickError("Opening '"<<GetFileName()<<"' : "
285 << e.errorCode() << ":"
286 << e.errorMessage());
289 // IMPORT TREE DESCRIPTION (AND TEST DB VALIDITY)
290 if (!DBImportTreeDescription())
295 GimmickDebugMessage(1,"Opening SQLite database '"<<GetFileName()
296 <<"' ... OK"<<std::endl);
299 //=====================================================================
301 //=====================================================================
302 bool SQLiteTreeHandler::DBCreate()
304 GimmickMessage(1,"Creating SQLite database '"<<GetFileName()
305 <<"' ... "<<std::endl);
307 if (boost::filesystem::exists(GetFileName()))
309 GimmickError(GetFileName()<<"' : "
310 << "file already exists");
317 mDB->open(GetFileName().c_str());
319 catch (CppSQLite3Exception& e)
321 GimmickError(e.errorCode() << ":"
322 << e.errorMessage() <<std::endl);
330 // Create LEVELS table
331 command = "create table LEVELS\n";
332 command += "( Name text )\n";
335 // Iterate the Levels
336 for (int l=0; l<GetTree().GetNumberOfLevels(); ++l)
338 command = "INSERT INTO LEVELS (Name) VALUES ('";
339 command += GetTree().GetLevelDescriptor(l).GetName();
343 // Create table of level (for level>0, i.e. not Root)
346 command = "CREATE TABLE ";
347 command += GetTree().GetLevelDescriptor(l).GetName();
348 command += "\n(\nID INTEGER PRIMARY KEY";
351 command += ",\nPARENT_ID int not null";
353 SQLAppendAttributesDefinition(l,command);
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";
364 // Add Attribute 'ID' to Description
365 GetTree().GetDescriptor().Add
366 (AttributeDescriptor( "ID",
367 "Database Identifier",
369 AttributeDescriptor::PRIVATE
374 // Add Attribute 'PARENT_ID' to Description
375 GetTree().GetDescriptor().Add
376 (AttributeDescriptor( "PARENT_ID",
377 "Database Parent Identifier",
379 AttributeDescriptor::PRIVATE
385 // Create table *_ATTRIBUTES
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";
399 // Fill the table *_ATTRIBUTES
400 LevelDescriptor::AttributeDescriptorListType::const_iterator i;
401 for (i = GetTree().GetAttributeDescriptorList(l).begin();
402 i != GetTree().GetAttributeDescriptorList(l).end();
406 std::stringstream insert;
407 insert << "INSERT INTO "
408 << GetTree().GetLevelDescriptor(l).GetName()
409 << "_Attributes (Key,Name,DicomGroup,DicomElement,Flags) "
411 << i->GetKey() << "','"
412 << i->GetName() << "',"
413 << i->GetGroup() << ","
414 << i->GetElement() << ","
415 << i->GetFlags() << ");";
416 UPDATEDB(insert.str());
421 // Initialize the root attributes
422 GetTree().InitializeAttributeMap();
423 // Insert the root in the level 0 table
424 DBInsert(GetTree().GetTree());
427 GetTree().SetChildrenLoaded(true);
428 GimmickMessage(1,"Creating SQLite database '"<<GetFileName()
429 <<"' ... OK"<<std::endl);
432 //=====================================================================
434 //=====================================================================
435 void SQLiteTreeHandler::SQLAppendAttributesDefinition(int level,
438 LevelDescriptor::AttributeDescriptorListType::const_iterator i;
439 for (i = GetTree().GetAttributeDescriptorList(level).begin();
440 i != GetTree().GetAttributeDescriptorList(level).end();
443 // if (i->second.flags==1) continue;
449 //=====================================================================
452 //=====================================================================
453 bool SQLiteTreeHandler::DBImportTreeDescription()
455 GimmickMessage(1,"Importing tree description from database ..."
458 // Test table 'LEVELS' existence
459 if ( ! mDB->tableExists("LEVELS") )
461 GimmickMessage(1,"!! ERROR : Table 'LEVELS' does not exist"
466 tree::Descriptor& desc = GetTree().GetDescriptor();
467 // clears the existing one
471 std::string query = "SELECT * FROM LEVELS";
477 std::string name = q.getStringField(0);
478 GimmickMessage(2," * Importing level '"<<name<<"'"<<std::endl);
479 desc.Add(LevelDescriptor(name));
484 for (int level = 0; level < nblevel; ++level )
486 std::string table = GetTree().GetLevelDescriptor(level).GetName();
487 table += "_Attributes";
488 // Test table 'LEVELS' existence
489 if ( ! mDB->tableExists(table.c_str()) )
491 GimmickMessage(1,"!! ERROR : Table '"<<table<<"' does not exist"
496 std::string query = "SELECT * FROM ";
501 GimmickMessage(2," * Level '"
502 <<GetTree().GetLevelDescriptor(level).GetName()
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;
513 std::string key(q.getStringField(0));
514 std::string name(q.getStringField(1));
515 GimmickMessage(2," - Importing attribute '"<<key<<"' '"<<name
518 (AttributeDescriptor( key, // Key
520 q.getIntField(2), // Group
521 q.getIntField(3), // Element
522 q.getIntField(4) // Flags
528 if ( key == "PARENT_ID" )
530 PARENT_ID_found = true;
535 if ( ! (ID_found || PARENT_ID_found ) )
537 GimmickMessage(1,"!! ERROR : Table '"<<table
538 <<"' does not contain mandatory attribute ID or PARENT_ID"
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();
554 AttributeMapType::const_iterator i = attr.find(a->GetKey());
555 if ( i != attr.end() )
560 GetTree().UnsafeSetAttribute( a->GetKey(), "" );
563 // Reading Root attributes
565 query = "SELECT * FROM ";
566 query += GetTree().GetLevelDescriptor(0).GetName();
569 for (int fld = 0; fld < q.numFields(); fld++)
571 GetTree().UnsafeSetAttribute(q.fieldName(fld),
572 q.getStringField(fld));
575 GimmickMessage(1,"Importing tree description from database ... OK"
579 //=====================================================================
597 //========================================================================
599 std::string& SQLformat(std::string& str)
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();
609 str = str.substr(0,i);
616 //========================================================================
618 //=====================================================================
619 void SQLiteTreeHandler::SQLAppendAttributesValues(tree::Node* n,
622 GimmickMessage(4,"SQLAppendAttributesValues"<<std::endl);
624 std::string values="";
625 tree::Node::AttributeMapType::iterator i;
626 for (i = n->GetAttributeMap().begin();
627 i != n->GetAttributeMap().end();
634 // std::cout << "("<<i->first<<","<<i->second<<")"<<std::endl;
635 atts += "'" + i->first + "'";
636 values += "'" + SQLformat(i->second) + "'";
639 GimmickMessage(4,"'"<<i->first<<"' = '"<<i->second<<"'"<<std::endl);
641 atts[atts.size()-1]=' ';
642 values[values.size()-1]=' ';
644 str = "("+atts+") VALUES ("+values+")";
645 GimmickMessage(4,"Result = '"<<str<<"'"<<std::endl);
647 //=====================================================================
649 //=====================================================================
650 tree::Node* SQLiteTreeHandler::DBGetParent( const AttributeMapType& attr)
652 Node* parent = GetTree().GetTree();
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();
665 if ( (*i)->Matches( attr ) )
676 //=====================================================================
679 //=====================================================================
680 int SQLiteTreeHandler::DBLoadChildren(tree::Node* node,
683 if (node->GetLevel()+1 >= node->GetTree()->GetNumberOfLevels() )
686 GimmickMessage(2,"Loading children of '"<<node->GetLabel()
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())
694 // Iterate the children
696 tree::Node::ChildrenListType::iterator i;
697 for (i = node->GetChildrenList().begin();
698 i!= node->GetChildrenList().end();
701 nbloaded += DBLoadChildren(*i,numberoflevels-1);
703 node->SetChildrenLoaded(true);
709 /// If children not loaded : do it and recurse
712 int level = node->GetLevel();
713 std::string query = "SELECT * FROM ";
715 query += GetTree().GetLevelDescriptor(level+1).GetName();
718 query += " WHERE PARENT_ID='" + node->UnsafeGetAttribute("ID")
728 // std::cout << "DBLoadCh : creating node level "<<level+1<<std::endl;
731 Node* n = new Node(node);
732 for (int fld = 0; fld < q.numFields(); fld++)
734 n->UnsafeSetAttribute(q.fieldName(fld),q.getStringField(fld));
740 ti.id = n->GetFieldValue("ID");
741 mTypeIdToNodeMap[ti] = n;
744 if ( numberoflevels != 1 )
747 nbloaded += DBLoadChildren(n, numberoflevels-1);
754 node->SetChildrenLoaded(true);
761 //=====================================================================
763 //======================================================================
764 void SQLiteTreeHandler::DBInsert(tree::Node* n)
766 GimmickMessage(2,"Inserting in DB '"<<n->GetLabel()
769 SQLAppendAttributesValues(n,val);
770 std::string insert("INSERT INTO ");
771 insert += GetTree().GetLevelDescriptor(n->GetLevel()).GetName();
772 insert += " " + val + ";";
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());
782 //======================================================================
784 //======================================================================
785 /// Graft the branch defined by the attributes to the parent
786 void SQLiteTreeHandler::DBGraftToParent( tree::Node* parent,
787 const AttributeMapType& attr)
789 // std::cout <<"Grafting to parent '"<<parent->GetLabel()
792 for (int level = parent->GetLevel()+1;
793 level < GetTree().GetNumberOfLevels();
797 tree::Node* child = new tree::Node(parent,attr);
798 child->SetChildrenLoaded(true);
801 int nc = GetNumberOfChildren(parent)+1;
803 // std::cout<<"Number of children "<<parent->GetNumberOfChildren()<<std::endl;
804 std::stringstream out;
806 SetAttribute(parent,"NumberOfChildren",out.str());
809 // Set PARENT_ID if necessary
810 if ( parent->GetLevel()>0 )
811 child->SetAttribute("PARENT_ID",parent->GetAttribute("ID"));
817 SQLAppendAttributesValues(child,val);
818 std::string insert("INSERT INTO ");
819 insert += GetTree().GetLevelDescriptor(child->GetLevel()).GetName();
820 insert += " " + val + ";";
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());
833 // Insert in TypeId map
835 ti.type = node->GetType();
837 mTypeIdToNodeMap[ti] = node;
838 // std::cout << "== Insert TypeId ("<<ti.type<<","<<ti.id<<")"<<std::endl;
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++;
849 //======================================================================
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)
858 GimmickMessage(3,"Setting Attribute of '"<<n->GetLabel()<<
859 "' "<<key<<"='"<<value<<"'"<<std::endl);
861 n->SetAttribute(key,value);
862 std::string sql = "UPDATE ";
863 sql += GetTree().GetLevelDescriptor(n->GetLevel()).GetName();
868 sql += "' WHERE ID = '";
869 sql += n->GetAttribute("ID");
871 // sql += " LIMIT 1";
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)
884 std::string sql = "UPDATE ";
885 sql += levelDescriptor;
897 //=====================================================================
898 void SQLiteTreeHandler::DBRecursiveRemoveNode(Node* node)
901 std::string query = "DELETE FROM ";
903 query += GetTree().GetLevelDescriptor(node->GetLevel()).GetName();
904 query += " WHERE ID='"+ node->GetAttribute("ID") + "';";
907 GimmickDebugMessage(2,
909 <<node->GetLabel()<<"' with ID '"
910 <<node->GetAttribute("ID")
911 <<"' in level "<< GetTree().GetLevelDescriptor(node->GetLevel()).GetName()
915 if(node->GetNumberOfChildren()!=0)
917 Node::ChildrenListType::iterator i;
918 for (i = node->GetChildrenList().begin();
919 i != node->GetChildrenList().end();
922 DBRecursiveRemoveNode((*i));
925 else if(node->GetLevel()<GetTree().GetNumberOfLevels()-1)
927 DBRecursiveRemoveNode(node->GetLevel()+1,node->GetAttribute("ID"));
931 //=====================================================================
932 void SQLiteTreeHandler::DBRecursiveRemoveNode(int level, std::string parentId)
934 std::stringstream out;
935 std::stringstream result;
936 out<<"SELECT ID FROM "<<GetTree().GetLevelDescriptor(level).GetName()<<" WHERE PARENT_ID='"<<parentId<<"'";
939 QUERYDB(out.str(),q);
943 for (int fld = 0; fld < q.numFields(); fld++)
945 result<<q.getStringField(fld)<<"#";
949 std::string res=result.str();
952 while(fin<res.size()-1)
954 fin=res.find('#',ini);
955 DBDelete(GetTree().GetLevelDescriptor(level).GetName(),"ID",res.substr(ini,fin-ini));
956 if(level<GetTree().GetNumberOfLevels()-1)
958 DBRecursiveRemoveNode(level+1,res.substr(ini,fin-ini));
966 //=====================================================================
967 void SQLiteTreeHandler::DBDelete(std::string levelDescriptor, std::string key, std::string value)
970 std::stringstream query;
971 query<<"DELETE FROM "<<levelDescriptor<<" WHERE "<<key<<"='"<<value<<"';";
973 UPDATEDB(query.str());
974 GimmickDebugMessage(2," Deleting: Query: "<<query.str()<<std::endl);
978 //=====================================================================
979 void SQLiteTreeHandler::GetAttribute(std::string levelDescriptor,
980 std::string searchParam,
981 std::string searchVal,
985 std::stringstream out;
986 std::stringstream results;
987 out<<"SELECT "<<key<<" FROM "<<levelDescriptor;
990 out<<" WHERE "<<searchParam<<"='"<<searchVal<<"'";
994 QUERYDB(out.str(),q);
999 for (int fld = 0; fld < q.numFields(); fld++)
1001 results<<q.getStringField(fld);
1009 result=results.str();
1012 //=====================================================================
1013 unsigned int SQLiteTreeHandler::GetNumberOfChildren(tree::Node* n)
1017 int level = n->GetLevel();
1019 if(level<GetTree().GetNumberOfLevels()&& level>0)
1021 std::string query = "SELECT NumberOfChildren FROM ";
1022 query += GetTree().GetLevelDescriptor(level).GetName();
1025 query += " WHERE ID='" + n->UnsafeGetAttribute("ID")
1034 for (int fld = 0; fld < q.numFields(); fld++)
1036 nb=q.getIntField(fld);
1050 //=====================================================================
1051 void SQLiteTreeHandler::GetTopLevelNodeId(const std::string& searchParam, const std::string& searchValue, std::string& parent_id)
1053 int level=GetTree().GetNumberOfLevels()-1;
1054 std::string sp=searchParam.c_str();
1055 std::string sv=searchValue.c_str();
1059 std::stringstream out;
1060 std::stringstream results;
1061 out<<"SELECT PARENT_ID FROM "<<GetTree().GetLevelDescriptor(level).GetName();
1062 out<<" WHERE "<<sp<<"='"<<sv<<"'";
1064 QUERYDB(out.str(),q);
1069 for (int fld = 0; fld < q.numFields(); fld++)
1071 results<<q.getStringField(fld);
1084 //=====================================================================
1085 bool SQLiteTreeHandler::DBInsert(Node* alien_node,
1086 UpdateSummary& summary)
1088 // std::cout << "SQLiteTreeHandler::Insert('"<<alien_node->GetLabel()
1089 // <<"')"<<std::endl;
1091 // if (!ChildrenLoaded()) DBLoadChildren(this,Node::Database);
1095 std::string parent_id;
1096 parent = DBGetOrCreateParent(alien_node,parent_id,summary);
1099 DBRecursiveGetOrCreateNode(alien_node,parent,parent_id,summary);
1102 //=====================================================================
1105 //=====================================================================
1106 Node* SQLiteTreeHandler::DBGetOrCreateParent(Node* alien_node,
1107 std::string& parent_id,
1108 UpdateSummary& summary)
1110 // std::cout << "DBGetOrCreateParent '" << alien_node->GetLabel()<<"'"
1112 // Load the patients if not already done
1113 DBLoadChildren(this,Node::Patient);
1116 Node* parent = this;
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)
1124 chain.push_front(cur);
1125 cur = cur->GetParent();
1128 // create the nodes if do not exist
1129 std::deque<Node*>::iterator i;
1130 for (i=chain.begin();i!=chain.end();++i)
1132 // std::cout << " cur = '"<<(*i)->GetLabel()<<"'"<<std::endl;
1133 // std::string cur_id = DBGetNodeId(*i,parent_id);
1134 // if (cur_id.size()==0)
1136 // Node does not exist : create it
1138 parent = DBGetOrCreateNode(*i,
1144 DBLoadChildren(parent,parent->GetType()+1);
1150 //=====================================================================
1154 //=====================================================================
1155 void SQLiteTreeHandler::DBRecursiveGetOrCreateNode(Node* alien_node,
1157 const std::string& parent_id,
1158 UpdateSummary& summary)
1160 // std::cout << "SQLiteTreeHandler::RecursiveGetOrCreateNode('"
1161 // <<alien_node->GetLabel()
1162 // <<"','"<<parent<<"','"<<parent_id<<"')"<<std::endl;
1165 // std::cout << " -- Parent = '"<<parent->GetLabel()<<"'"<<std::endl;
1168 Node* new_node = DBGetOrCreateNode(alien_node,
1173 Node::ChildrenListType::iterator i;
1174 for (i = alien_node->GetChildrenList().begin();
1175 i != alien_node->GetChildrenList().end();
1178 DBRecursiveGetOrCreateNode((*i),new_node,new_id,summary);
1181 //=====================================================================
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)
1191 // std::cout << "DBGetOrCreateNode('"<<alien_node->GetLabel()<<"','"
1192 // << internal_parent << "','"<< parent_id<<"')"<<std::endl;
1193 if (internal_parent != 0)
1195 // std::cout << " -- Parent = '"<<internal_parent->GetLabel()<<"'"<<std::endl;
1197 // Node Exists ? return it
1198 // First try among children of internal parent
1199 Node* node = GetChildrenLike(internal_parent,alien_node);
1202 node_id = node->UnsafeGetFieldValue("ID");
1205 // Second : try in DB
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();
1216 j = alien_node->GetFieldValueMap().find(i->first);
1217 if (j != alien_node->GetFieldValueMap().end() )
1219 i->second = j->second;
1224 if (node->GetType()!=Node::Patient)
1225 node->SetFieldValue("PARENT_ID",parent_id);
1229 BuildSQLFieldsValues(node,val);
1230 std::string insert("INSERT INTO ");
1231 insert += std::string(SQLiteTreeHandlerStructure::Table(node->GetType()))
1233 // std::cout << "** SQL = '"<<insert<<"'"<<std::endl;
1235 // std::cout << "** SQL OK"<<std::endl;
1237 // Store DB id of newly created node;
1238 long lastrow = mDB->lastRowId();
1239 std::stringstream ri;
1240 ri << mDB->lastRowId();
1242 // std::cout << "LastRowId='"<<mDB->lastRowId()<<"' vs '"<<created_id<<"'"<<std::endl;
1244 node->SetFieldValue("ID",node_id);
1245 // Insert in TypeId map
1247 ti.type = node->GetType();
1249 mTypeIdToNodeMap[ti] = node;
1250 // std::cout << "== Insert TypeId ("<<ti.type<<","<<ti.id<<")"<<std::endl;
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++;
1261 //=====================================================================
1263 //=====================================================================
1264 Node* SQLiteTreeHandler::GetChildrenLike(Node* parent,
1267 Node::ChildrenListType::iterator i;
1268 for (i = parent->GetChildrenList().begin();
1269 i != parent->GetChildrenList().end();
1272 Node::Type type = alien_node->GetType();
1275 j<SQLiteTreeHandlerStructure::NbQueryFields(type);
1279 alien_node->GetFieldValue(SQLiteTreeHandlerStructure::
1280 QueryField(type,j).key ) !=
1281 (*i)->GetFieldValue(SQLiteTreeHandlerStructure::
1282 QueryField(type,j).key ) )
1295 //=====================================================================
1297 //=====================================================================
1298 std::string SQLiteTreeHandler::DBGetNodeId(Node* node,
1299 const std::string& parent_id)
1301 // std::cout << "SQLiteTreeHandler::DBGetNodeId('"<<node->GetLabel()
1302 // <<"','"<<parent_id<<"')"
1305 int type = node->GetType();
1307 std::string table = SQLiteTreeHandlerStructure::Table(type);
1308 std::string where = "WHERE ";
1310 if (type!=Node::Patient)
1312 where += "PARENT_ID='" + parent_id
1313 //node->GetFieldValue("PARENT_ID")
1317 for (int i=0;i<SQLiteTreeHandlerStructure::NbQueryFields(type);i++)
1319 where += SQLiteTreeHandlerStructure::QueryField(type,i).key + "='"
1320 + node->GetFieldValue(SQLiteTreeHandlerStructure::QueryField(type,i).key) + "' ";
1321 if (i<SQLiteTreeHandlerStructure::NbQueryFields(type)-1)
1325 std::string query = "SELECT ID FROM " + table + " " + where + ";";
1326 // std::cout << "** SQL = '"<<query<<"'"<<std::endl;
1333 // std::cout << " - Node exists " << std::endl;
1334 std::string id = q.getStringField(0);
1335 // std::cout << " id = '"<<id<<"'"<<std::endl;
1342 //=====================================================================
1346 //=====================================================================
1347 Node* SQLiteTreeHandler::GetNodeFromTypeId(Node::Type type,
1348 const std::string& id)
1350 // std::cout << "GetNodeFromTypeId("<<type<<","<<id<<")"<<std::endl;
1356 TypeIdToNodeMapType::iterator i = mTypeIdToNodeMap.find(ti);
1357 if (i == mTypeIdToNodeMap.end())
1360 std::cout << "Internal error : mTypeIdToNodeMap does not contain key"
1362 creaError("Internal error : mTypeIdToNodeMap does not contain key");
1366 // std::cout << " ** Node = "<<i->second<<std::endl;
1370 //=====================================================================
1372 //=====================================================================
1373 bool SQLiteTreeHandler::Remove(Node* node)
1376 //DBRecursiveRemoveNode(node);
1378 // std::cout << "DELETE"<<std::endl;
1379 if (node->GetParent())
1381 node->GetParent()->RemoveChildrenFromList(node);
1384 // std::cout << "DELETE OK"<<std::endl;
1389 //========================================================================
1391 //=====================================================================
1392 void SQLiteTreeHandler::DBRecursiveRemoveNode(Node* node)
1394 // std::cout << "SQLiteTreeHandler::DBRecursiveRemoveNode('"
1395 // <<node->GetLabel()<<"')"<<std::endl;
1397 std::string query = "DELETE FROM ";
1398 query += SQLiteTreeHandlerStructure::Table(node->GetType());
1399 query += " WHERE ID='"+ node->GetFieldValue("ID") + "';";
1403 Node::ChildrenListType::iterator i;
1404 for (i = node->GetChildrenList().begin();
1405 i != node->GetChildrenList().end();
1408 DBRecursiveRemoveNode((*i));
1412 //=====================================================================
1414 //=====================================================================
1415 int SQLiteTreeHandler::DBQueryNumberOfChildren(Node* node)
1417 std::string query = "SELECT COUNT (ID) FROM ";
1418 query += SQLiteTreeHandlerStructure::Table(node->GetType()+1);
1419 if (node->GetType() != Node::Database)
1421 query += " WHERE PARENT_ID='"+ node->GetFieldValue("ID")+"'";
1425 // std::cout << "**SQL = "<< query << std::endl;
1430 // std::cout << "**RES = "<< q.getIntField(0) <<std::endl;
1432 return q.getIntField(0);
1434 //=====================================================================
1442 } // namespace creaImageIO