ctkDICOMDatabase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.commontk.org/LICENSE
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. #include <stdexcept>
  15. // Qt includes
  16. #include <QSqlQuery>
  17. #include <QSqlRecord>
  18. #include <QSqlError>
  19. #include <QVariant>
  20. #include <QDate>
  21. #include <QStringList>
  22. #include <QSet>
  23. #include <QFile>
  24. #include <QDirIterator>
  25. #include <QFileInfo>
  26. #include <QDebug>
  27. // ctkDICOM includes
  28. #include "ctkDICOMDatabase.h"
  29. #include "ctkLogger.h"
  30. // DCMTK includes
  31. #ifndef WIN32
  32. #define HAVE_CONFIG_H
  33. #endif
  34. #include <dcmtk/dcmdata/dcfilefo.h>
  35. #include <dcmtk/dcmdata/dcfilefo.h>
  36. #include <dcmtk/dcmdata/dcdeftag.h>
  37. #include <dcmtk/dcmdata/dcdatset.h>
  38. #include <dcmtk/ofstd/ofcond.h>
  39. #include <dcmtk/ofstd/ofstring.h>
  40. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  41. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  42. //------------------------------------------------------------------------------
  43. static ctkLogger logger("org.commontk.dicom.DICOMDatabase" );
  44. //------------------------------------------------------------------------------
  45. //------------------------------------------------------------------------------
  46. class ctkDICOMDatabasePrivate
  47. {
  48. Q_DECLARE_PUBLIC(ctkDICOMDatabase);
  49. protected:
  50. ctkDICOMDatabase* const q_ptr;
  51. public:
  52. ctkDICOMDatabasePrivate(ctkDICOMDatabase&);
  53. ~ctkDICOMDatabasePrivate();
  54. void init(QString databaseFile);
  55. bool executeScript(const QString script);
  56. QString DatabaseFileName;
  57. QString LastError;
  58. QSqlDatabase Database;
  59. };
  60. //------------------------------------------------------------------------------
  61. // ctkDICOMDatabasePrivate methods
  62. //------------------------------------------------------------------------------
  63. ctkDICOMDatabasePrivate::ctkDICOMDatabasePrivate(ctkDICOMDatabase& o): q_ptr(&o)
  64. {
  65. }
  66. //------------------------------------------------------------------------------
  67. void ctkDICOMDatabasePrivate::init(QString databaseFilename)
  68. {
  69. Q_Q(ctkDICOMDatabase);
  70. q->openDatabase(databaseFilename);
  71. }
  72. //------------------------------------------------------------------------------
  73. ctkDICOMDatabasePrivate::~ctkDICOMDatabasePrivate()
  74. {
  75. }
  76. //------------------------------------------------------------------------------
  77. void ctkDICOMDatabase::openDatabase(const QString databaseFile)
  78. {
  79. Q_D(ctkDICOMDatabase);
  80. d->Database = QSqlDatabase::addDatabase("QSQLITE","DICOM-DB");
  81. d->Database.setDatabaseName(databaseFile);
  82. if ( ! (d->Database.open()) )
  83. {
  84. d->LastError = d->Database.lastError().text();
  85. throw std::runtime_error(qPrintable(d->LastError));
  86. }
  87. if ( d->Database.tables().empty() )
  88. {
  89. initializeDatabase();
  90. }
  91. }
  92. //------------------------------------------------------------------------------
  93. // ctkDICOMDatabase methods
  94. //------------------------------------------------------------------------------
  95. ctkDICOMDatabase::ctkDICOMDatabase(QString databaseFile)
  96. : d_ptr(new ctkDICOMDatabasePrivate(*this))
  97. {
  98. Q_D(ctkDICOMDatabase);
  99. d->init(databaseFile);
  100. }
  101. ctkDICOMDatabase::ctkDICOMDatabase()
  102. : d_ptr(new ctkDICOMDatabasePrivate(*this))
  103. {
  104. }
  105. //------------------------------------------------------------------------------
  106. ctkDICOMDatabase::~ctkDICOMDatabase()
  107. {
  108. }
  109. //----------------------------------------------------------------------------
  110. //------------------------------------------------------------------------------
  111. const QString ctkDICOMDatabase::GetLastError() const {
  112. Q_D(const ctkDICOMDatabase);
  113. return d->LastError;
  114. }
  115. //------------------------------------------------------------------------------
  116. const QSqlDatabase& ctkDICOMDatabase::database() const {
  117. Q_D(const ctkDICOMDatabase);
  118. return d->Database;
  119. }
  120. //------------------------------------------------------------------------------
  121. bool ctkDICOMDatabasePrivate::executeScript(const QString script) {
  122. QFile scriptFile(script);
  123. scriptFile.open(QIODevice::ReadOnly);
  124. if ( !scriptFile.isOpen() )
  125. {
  126. qDebug() << "Script file " << script << " could not be opened!\n";
  127. return false;
  128. }
  129. QString sqlCommands( QTextStream(&scriptFile).readAll() );
  130. sqlCommands.replace( '\n', ' ' );
  131. sqlCommands.replace("; ", ";\n");
  132. QStringList sqlCommandsLines = sqlCommands.split('\n');
  133. QSqlQuery query(Database);
  134. for (QStringList::iterator it = sqlCommandsLines.begin(); it != sqlCommandsLines.end()-1; ++it)
  135. {
  136. if (! (*it).startsWith("--") )
  137. {
  138. qDebug() << *it << "\n";
  139. query.exec(*it);
  140. if (query.lastError().type())
  141. {
  142. qDebug() << "There was an error during execution of the statement: " << (*it);
  143. qDebug() << "Error message: " << query.lastError().text();
  144. return false;
  145. }
  146. }
  147. }
  148. return true;
  149. }
  150. //------------------------------------------------------------------------------
  151. bool ctkDICOMDatabase::initializeDatabase(const char* sqlFileName)
  152. {
  153. Q_D(ctkDICOMDatabase);
  154. return d->executeScript(sqlFileName);
  155. }
  156. //------------------------------------------------------------------------------
  157. void ctkDICOMDatabase::closeDatabase()
  158. {
  159. Q_D(ctkDICOMDatabase);
  160. d->Database.close();
  161. }
  162. //------------------------------------------------------------------------------
  163. void ctkDICOMDatabase::insert ( DcmDataset *dataset ) {
  164. this->insert ( dataset, QString() );
  165. }
  166. //------------------------------------------------------------------------------
  167. void ctkDICOMDatabase::insert ( DcmDataset *dataset, QString filename ) {
  168. Q_D(ctkDICOMDatabase);
  169. // Check to see if the file has already been loaded
  170. QSqlQuery fileExists ( d->Database );
  171. fileExists.prepare("SELECT InsertTimestamp FROM Images WHERE Filename == ?");
  172. fileExists.bindValue(0,filename);
  173. fileExists.exec();
  174. if ( fileExists.next() && QFileInfo(filename).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) )
  175. {
  176. logger.debug ( "File " + filename + " already added" );
  177. return;
  178. }
  179. OFString patientsName, patientID, patientsBirthDate, patientsBirthTime, patientsSex,
  180. patientComments, patientsAge;
  181. OFString studyInstanceUID, studyID, studyDate, studyTime,
  182. accessionNumber, modalitiesInStudy, institutionName, performingPhysiciansName, referringPhysician, studyDescription;
  183. OFString seriesInstanceUID, seriesDate, seriesTime,
  184. seriesDescription, bodyPartExamined, frameOfReferenceUID,
  185. contrastAgent, scanningSequence;
  186. OFString instanceNumber;
  187. Sint32 seriesNumber = 0, acquisitionNumber = 0, echoNumber = 0, temporalPosition = 0;
  188. //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  189. dataset->findAndGetOFString(DCM_PatientsName, patientsName);
  190. dataset->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID);
  191. dataset->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID);
  192. dataset->findAndGetOFString(DCM_PatientID, patientID);
  193. dataset->findAndGetOFString(DCM_PatientsBirthDate, patientsBirthDate);
  194. dataset->findAndGetOFString(DCM_PatientsBirthTime, patientsBirthTime);
  195. dataset->findAndGetOFString(DCM_PatientsSex, patientsSex);
  196. dataset->findAndGetOFString(DCM_PatientsAge, patientsAge);
  197. dataset->findAndGetOFString(DCM_PatientComments, patientComments);
  198. dataset->findAndGetOFString(DCM_StudyID, studyID);
  199. dataset->findAndGetOFString(DCM_StudyDate, studyDate);
  200. dataset->findAndGetOFString(DCM_StudyTime, studyTime);
  201. dataset->findAndGetOFString(DCM_AccessionNumber, accessionNumber);
  202. dataset->findAndGetOFString(DCM_ModalitiesInStudy, modalitiesInStudy);
  203. dataset->findAndGetOFString(DCM_InstitutionName, institutionName);
  204. dataset->findAndGetOFString(DCM_PerformingPhysiciansName, performingPhysiciansName);
  205. dataset->findAndGetOFString(DCM_ReferringPhysiciansName, referringPhysician);
  206. dataset->findAndGetOFString(DCM_StudyDescription, studyDescription);
  207. dataset->findAndGetOFString(DCM_SeriesDate, seriesDate);
  208. dataset->findAndGetOFString(DCM_SeriesTime, seriesTime);
  209. dataset->findAndGetOFString(DCM_SeriesDescription, seriesDescription);
  210. dataset->findAndGetOFString(DCM_BodyPartExamined, bodyPartExamined);
  211. dataset->findAndGetOFString(DCM_FrameOfReferenceUID, frameOfReferenceUID);
  212. dataset->findAndGetOFString(DCM_ContrastBolusAgent, contrastAgent);
  213. dataset->findAndGetOFString(DCM_ScanningSequence, scanningSequence);
  214. dataset->findAndGetSint32(DCM_SeriesNumber, seriesNumber);
  215. dataset->findAndGetSint32(DCM_AcquisitionNumber, acquisitionNumber);
  216. dataset->findAndGetSint32(DCM_EchoNumbers, echoNumber);
  217. dataset->findAndGetSint32(DCM_TemporalPositionIdentifier, temporalPosition);
  218. QSqlQuery check_exists_query(d->Database);
  219. //The patient UID is a unique number within the database, generated by the sqlite autoincrement
  220. int patientUID = -1;
  221. if ( patientID != "" && patientsName != "" )
  222. {
  223. //Check if patient is already present in the db
  224. check_exists_query.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
  225. check_exists_query.bindValue ( 0, QString ( patientID.c_str() ) );
  226. check_exists_query.bindValue ( 1, QString ( patientsName.c_str() ) );
  227. check_exists_query.exec();
  228. if (check_exists_query.next())
  229. {
  230. patientUID = check_exists_query.value(check_exists_query.record().indexOf("UID")).toInt();
  231. }
  232. else
  233. {
  234. // Insert it
  235. QSqlQuery statement ( d->Database );
  236. statement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
  237. statement.bindValue ( 0, QString ( patientsName.c_str() ) );
  238. statement.bindValue ( 1, QString ( patientID.c_str() ) );
  239. statement.bindValue ( 2, QString ( patientsBirthDate.c_str() ) );
  240. statement.bindValue ( 3, QString ( patientsBirthTime.c_str() ) );
  241. statement.bindValue ( 4, QString ( patientsSex.c_str() ) );
  242. statement.bindValue ( 5, QString ( patientsAge.c_str() ) );
  243. statement.bindValue ( 6, QString ( patientComments.c_str() ) );
  244. statement.exec ();
  245. patientUID = statement.lastInsertId().toInt();
  246. logger.debug ( "New patient inserted: " + QString().setNum ( patientUID ) );
  247. }
  248. }
  249. if ( studyInstanceUID != "" )
  250. {
  251. check_exists_query.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
  252. check_exists_query.bindValue ( 0, QString ( studyInstanceUID.c_str() ) );
  253. check_exists_query.exec();
  254. if(!check_exists_query.next())
  255. {
  256. QSqlQuery statement ( d->Database );
  257. statement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  258. statement.bindValue ( 0, QString ( studyInstanceUID.c_str() ) );
  259. statement.bindValue ( 1, patientUID );
  260. statement.bindValue ( 2, QString ( studyID.c_str() ) );
  261. statement.bindValue ( 3, QDate::fromString ( studyDate.c_str(), "yyyyMMdd" ) );
  262. statement.bindValue ( 4, QString ( studyTime.c_str() ) );
  263. statement.bindValue ( 5, QString ( accessionNumber.c_str() ) );
  264. statement.bindValue ( 6, QString ( modalitiesInStudy.c_str() ) );
  265. statement.bindValue ( 7, QString ( institutionName.c_str() ) );
  266. statement.bindValue ( 8, QString ( referringPhysician.c_str() ) );
  267. statement.bindValue ( 9, QString ( performingPhysiciansName.c_str() ) );
  268. statement.bindValue ( 10, QString ( studyDescription.c_str() ) );
  269. if ( !statement.exec() )
  270. {
  271. logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() );
  272. }
  273. }
  274. }
  275. if ( seriesInstanceUID != "" )
  276. {
  277. check_exists_query.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
  278. check_exists_query.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) );
  279. logger.warn ( "Statement: " + check_exists_query.lastQuery() );
  280. check_exists_query.exec();
  281. if(!check_exists_query.next())
  282. {
  283. QSqlQuery statement ( d->Database );
  284. statement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  285. statement.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) );
  286. statement.bindValue ( 1, QString ( studyInstanceUID.c_str() ) );
  287. statement.bindValue ( 2, static_cast<int>(seriesNumber) );
  288. statement.bindValue ( 3, QString ( seriesDate.c_str() ) );
  289. statement.bindValue ( 4, QDate::fromString ( seriesTime.c_str(), "yyyyMMdd" ) );
  290. statement.bindValue ( 5, QString ( seriesDescription.c_str() ) );
  291. statement.bindValue ( 6, QString ( bodyPartExamined.c_str() ) );
  292. statement.bindValue ( 7, QString ( frameOfReferenceUID.c_str() ) );
  293. statement.bindValue ( 8, static_cast<int>(acquisitionNumber) );
  294. statement.bindValue ( 9, QString ( contrastAgent.c_str() ) );
  295. statement.bindValue ( 10, QString ( scanningSequence.c_str() ) );
  296. statement.bindValue ( 11, static_cast<int>(echoNumber) );
  297. statement.bindValue ( 12, static_cast<int>(temporalPosition) );
  298. if ( !statement.exec() )
  299. {
  300. logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() );
  301. }
  302. }
  303. }
  304. if ( !filename.isEmpty() )
  305. {
  306. check_exists_query.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
  307. check_exists_query.bindValue ( 0, filename );
  308. check_exists_query.exec();
  309. if(!check_exists_query.next())
  310. {
  311. QSqlQuery statement ( d->Database );
  312. statement.prepare ( "INSERT INTO Images ( 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ? )" );
  313. statement.bindValue ( 0, filename );
  314. statement.bindValue ( 1, QString ( seriesInstanceUID.c_str() ) );
  315. statement.bindValue ( 2, QDateTime::currentDateTime() );
  316. statement.exec();
  317. }
  318. }
  319. }