ctkDICOMDatabase.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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.apache.org/licenses/LICENSE-2.0.txt
  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. #include <QFileSystemWatcher>
  28. // ctkDICOM includes
  29. #include "ctkDICOMDatabase.h"
  30. #include "ctkDICOMAbstractThumbnailGenerator.h"
  31. #include "ctkDICOMDataset.h"
  32. #include "ctkLogger.h"
  33. // DCMTK includes
  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. #include <dcmimage.h>
  43. #include <dcmtk/dcmjpeg/djdecode.h> /* for dcmjpeg decoders */
  44. #include <dcmtk/dcmjpeg/djencode.h> /* for dcmjpeg encoders */
  45. #include <dcmtk/dcmdata/dcrledrg.h> /* for DcmRLEDecoderRegistration */
  46. #include <dcmtk/dcmdata/dcrleerg.h> /* for DcmRLEEncoderRegistration */
  47. //------------------------------------------------------------------------------
  48. static ctkLogger logger("org.commontk.dicom.DICOMDatabase" );
  49. //------------------------------------------------------------------------------
  50. //------------------------------------------------------------------------------
  51. class ctkDICOMDatabasePrivate
  52. {
  53. Q_DECLARE_PUBLIC(ctkDICOMDatabase);
  54. protected:
  55. ctkDICOMDatabase* const q_ptr;
  56. public:
  57. ctkDICOMDatabasePrivate(ctkDICOMDatabase&);
  58. ~ctkDICOMDatabasePrivate();
  59. void init(QString databaseFile);
  60. void registerCompressionLibraries();
  61. bool executeScript(const QString script);
  62. ///
  63. /// \brief runs a query and prints debug output of status
  64. ///
  65. bool loggedExec(QSqlQuery& query);
  66. bool loggedExec(QSqlQuery& query, const QString& queryString);
  67. // dataset must be set always
  68. // filePath has to be set if this is an import of an actual file
  69. void insert ( const ctkDICOMDataset& ctkDataset, const QString& filePath, bool storeFile = true, bool generateThumbnail = true);
  70. /// Name of the database file (i.e. for SQLITE the sqlite file)
  71. QString DatabaseFileName;
  72. QString LastError;
  73. QSqlDatabase Database;
  74. QMap<QString, QString> LoadedHeader;
  75. ctkDICOMAbstractThumbnailGenerator* thumbnailGenerator;
  76. /// these are for optimizing the import of image sequences
  77. /// since most information are identical for all slices
  78. QString lastPatientID;
  79. QString lastPatientsName;
  80. QString lastPatientsBirthDate;
  81. QString lastStudyInstanceUID;
  82. QString lastSeriesInstanceUID;
  83. int lastPatientUID;
  84. };
  85. //------------------------------------------------------------------------------
  86. // ctkDICOMDatabasePrivate methods
  87. //------------------------------------------------------------------------------
  88. ctkDICOMDatabasePrivate::ctkDICOMDatabasePrivate(ctkDICOMDatabase& o): q_ptr(&o)
  89. {
  90. this->thumbnailGenerator = NULL;
  91. }
  92. //------------------------------------------------------------------------------
  93. void ctkDICOMDatabasePrivate::init(QString databaseFilename)
  94. {
  95. Q_Q(ctkDICOMDatabase);
  96. q->openDatabase(databaseFilename);
  97. }
  98. //------------------------------------------------------------------------------
  99. void ctkDICOMDatabasePrivate::registerCompressionLibraries(){
  100. logger.debug("Register compression libraries");
  101. // Register the JPEG libraries in case we need them
  102. // (registration only happens once, so it's okay to call repeatedly)
  103. // register global JPEG decompression codecs
  104. DJDecoderRegistration::registerCodecs();
  105. // register global JPEG compression codecs
  106. DJEncoderRegistration::registerCodecs();
  107. // register RLE compression codec
  108. DcmRLEEncoderRegistration::registerCodecs();
  109. // register RLE decompression codec
  110. DcmRLEDecoderRegistration::registerCodecs();
  111. }
  112. //------------------------------------------------------------------------------
  113. ctkDICOMDatabasePrivate::~ctkDICOMDatabasePrivate()
  114. {
  115. }
  116. //------------------------------------------------------------------------------
  117. bool ctkDICOMDatabasePrivate::loggedExec(QSqlQuery& query)
  118. {
  119. return (loggedExec(query, QString("")));
  120. }
  121. //------------------------------------------------------------------------------
  122. bool ctkDICOMDatabasePrivate::loggedExec(QSqlQuery& query, const QString& queryString)
  123. {
  124. bool success;
  125. if (queryString.compare(""))
  126. {
  127. success = query.exec(queryString);
  128. }
  129. else
  130. {
  131. success = query.exec();
  132. }
  133. if (!success)
  134. {
  135. QSqlError sqlError = query.lastError();
  136. logger.debug( "SQL failed\n Bad SQL: " + query.lastQuery());
  137. logger.debug( "Error text: " + sqlError.text());
  138. }
  139. else
  140. {
  141. logger.debug( "SQL worked!\n SQL: " + query.lastQuery());
  142. }
  143. return (success);
  144. }
  145. //------------------------------------------------------------------------------
  146. void ctkDICOMDatabase::openDatabase(const QString databaseFile, const QString& connectionName )
  147. {
  148. Q_D(ctkDICOMDatabase);
  149. d->DatabaseFileName = databaseFile;
  150. d->Database = QSqlDatabase::addDatabase("QSQLITE", connectionName);
  151. d->Database.setDatabaseName(databaseFile);
  152. if ( ! (d->Database.open()) )
  153. {
  154. d->LastError = d->Database.lastError().text();
  155. return;
  156. }
  157. if ( d->Database.tables().empty() )
  158. {
  159. if (!initializeDatabase())
  160. {
  161. d->LastError = QString("Unable to initialize DICOM database!");
  162. return;
  163. }
  164. }
  165. if (!isInMemory())
  166. {
  167. QFileSystemWatcher* watcher = new QFileSystemWatcher(QStringList(databaseFile),this);
  168. connect(watcher, SIGNAL(fileChanged(QString)),this, SIGNAL (databaseChanged()) );
  169. }
  170. }
  171. //------------------------------------------------------------------------------
  172. // ctkDICOMDatabase methods
  173. //------------------------------------------------------------------------------
  174. ctkDICOMDatabase::ctkDICOMDatabase(QString databaseFile)
  175. : d_ptr(new ctkDICOMDatabasePrivate(*this))
  176. {
  177. Q_D(ctkDICOMDatabase);
  178. d->registerCompressionLibraries();
  179. d->init(databaseFile);
  180. }
  181. ctkDICOMDatabase::ctkDICOMDatabase(QObject* parent)
  182. : d_ptr(new ctkDICOMDatabasePrivate(*this))
  183. {
  184. Q_UNUSED(parent);
  185. Q_D(ctkDICOMDatabase);
  186. d->registerCompressionLibraries();
  187. }
  188. //------------------------------------------------------------------------------
  189. ctkDICOMDatabase::~ctkDICOMDatabase()
  190. {
  191. }
  192. //----------------------------------------------------------------------------
  193. //------------------------------------------------------------------------------
  194. const QString ctkDICOMDatabase::lastError() const {
  195. Q_D(const ctkDICOMDatabase);
  196. return d->LastError;
  197. }
  198. //------------------------------------------------------------------------------
  199. const QString ctkDICOMDatabase::databaseFilename() const {
  200. Q_D(const ctkDICOMDatabase);
  201. return d->DatabaseFileName;
  202. }
  203. //------------------------------------------------------------------------------
  204. const QString ctkDICOMDatabase::databaseDirectory() const {
  205. QString databaseFile = databaseFilename();
  206. if (!QFileInfo(databaseFile).isAbsolute())
  207. {
  208. databaseFile.prepend(QDir::currentPath() + "/");
  209. }
  210. return QFileInfo ( databaseFile ).absoluteDir().path();
  211. }
  212. //------------------------------------------------------------------------------
  213. const QSqlDatabase& ctkDICOMDatabase::database() const {
  214. Q_D(const ctkDICOMDatabase);
  215. return d->Database;
  216. }
  217. //------------------------------------------------------------------------------
  218. void ctkDICOMDatabase::setThumbnailGenerator(ctkDICOMAbstractThumbnailGenerator *generator){
  219. Q_D(ctkDICOMDatabase);
  220. d->thumbnailGenerator = generator;
  221. }
  222. //------------------------------------------------------------------------------
  223. ctkDICOMAbstractThumbnailGenerator* ctkDICOMDatabase::thumbnailGenerator(){
  224. Q_D(const ctkDICOMDatabase);
  225. return d->thumbnailGenerator;
  226. }
  227. //------------------------------------------------------------------------------
  228. bool ctkDICOMDatabasePrivate::executeScript(const QString script) {
  229. QFile scriptFile(script);
  230. scriptFile.open(QIODevice::ReadOnly);
  231. if ( !scriptFile.isOpen() )
  232. {
  233. qDebug() << "Script file " << script << " could not be opened!\n";
  234. return false;
  235. }
  236. QString sqlCommands( QTextStream(&scriptFile).readAll() );
  237. sqlCommands.replace( '\n', ' ' );
  238. sqlCommands.remove( '\r' );
  239. sqlCommands.replace("; ", ";\n");
  240. QStringList sqlCommandsLines = sqlCommands.split('\n');
  241. QSqlQuery query(Database);
  242. for (QStringList::iterator it = sqlCommandsLines.begin(); it != sqlCommandsLines.end()-1; ++it)
  243. {
  244. if (! (*it).startsWith("--") )
  245. {
  246. qDebug() << *it << "\n";
  247. query.exec(*it);
  248. if (query.lastError().type())
  249. {
  250. qDebug() << "There was an error during execution of the statement: " << (*it);
  251. qDebug() << "Error message: " << query.lastError().text();
  252. return false;
  253. }
  254. }
  255. }
  256. return true;
  257. }
  258. //------------------------------------------------------------------------------
  259. bool ctkDICOMDatabase::initializeDatabase(const char* sqlFileName)
  260. {
  261. Q_D(ctkDICOMDatabase);
  262. return d->executeScript(sqlFileName);
  263. }
  264. //------------------------------------------------------------------------------
  265. void ctkDICOMDatabase::closeDatabase()
  266. {
  267. Q_D(ctkDICOMDatabase);
  268. d->Database.close();
  269. }
  270. //------------------------------------------------------------------------------
  271. QStringList ctkDICOMDatabase::patients()
  272. {
  273. Q_D(ctkDICOMDatabase);
  274. QSqlQuery query(d->Database);
  275. query.prepare ( "SELECT UID FROM Patients" );
  276. query.exec();
  277. QStringList result;
  278. while (query.next())
  279. {
  280. result << query.value(0).toString();
  281. }
  282. return( result );
  283. }
  284. //------------------------------------------------------------------------------
  285. QStringList ctkDICOMDatabase::studiesForPatient(QString dbPatientID)
  286. {
  287. Q_D(ctkDICOMDatabase);
  288. QSqlQuery query(d->Database);
  289. query.prepare ( "SELECT StudyInstanceUID FROM Studies WHERE PatientsUID = ?" );
  290. query.bindValue ( 0, dbPatientID );
  291. query.exec();
  292. QStringList result;
  293. while (query.next())
  294. {
  295. result << query.value(0).toString();
  296. }
  297. return( result );
  298. }
  299. //------------------------------------------------------------------------------
  300. QStringList ctkDICOMDatabase::seriesForStudy(QString studyUID)
  301. {
  302. Q_D(ctkDICOMDatabase);
  303. QSqlQuery query(d->Database);
  304. query.prepare ( "SELECT SeriesInstanceUID FROM Series WHERE StudyInstanceUID=?");
  305. query.bindValue ( 0, studyUID );
  306. query.exec();
  307. QStringList result;
  308. while (query.next())
  309. {
  310. result << query.value(0).toString();
  311. }
  312. return( result );
  313. }
  314. //------------------------------------------------------------------------------
  315. QStringList ctkDICOMDatabase::filesForSeries(QString seriesUID)
  316. {
  317. Q_D(ctkDICOMDatabase);
  318. QSqlQuery query(d->Database);
  319. query.prepare ( "SELECT Filename FROM Images WHERE SeriesInstanceUID=?");
  320. query.bindValue ( 0, seriesUID );
  321. query.exec();
  322. QStringList result;
  323. while (query.next())
  324. {
  325. result << query.value(0).toString();
  326. }
  327. return( result );
  328. }
  329. //------------------------------------------------------------------------------
  330. void ctkDICOMDatabase::loadInstanceHeader (QString sopInstanceUID)
  331. {
  332. Q_D(ctkDICOMDatabase);
  333. QSqlQuery query(d->Database);
  334. query.prepare ( "SELECT Filename FROM Images WHERE SOPInstanceUID=?");
  335. query.bindValue ( 0, sopInstanceUID );
  336. query.exec();
  337. if (query.next())
  338. {
  339. QString fileName = query.value(0).toString();
  340. this->loadFileHeader(fileName);
  341. }
  342. return;
  343. }
  344. //------------------------------------------------------------------------------
  345. void ctkDICOMDatabase::loadFileHeader (QString fileName)
  346. {
  347. Q_D(ctkDICOMDatabase);
  348. d->LoadedHeader.clear();
  349. DcmFileFormat fileFormat;
  350. OFCondition status = fileFormat.loadFile(fileName.toLatin1().data());
  351. if (status.good())
  352. {
  353. DcmDataset *dataset = fileFormat.getDataset();
  354. DcmStack stack;
  355. while (dataset->nextObject(stack, true) == EC_Normal)
  356. {
  357. DcmObject *dO = stack.top();
  358. QString tag = QString("%1,%2").arg(
  359. dO->getGTag(),4,16,QLatin1Char('0')).arg(
  360. dO->getETag(),4,16,QLatin1Char('0'));
  361. std::ostringstream s;
  362. dO->print(s);
  363. d->LoadedHeader[tag] = QString(s.str().c_str());
  364. }
  365. }
  366. return;
  367. }
  368. //------------------------------------------------------------------------------
  369. QStringList ctkDICOMDatabase::headerKeys ()
  370. {
  371. Q_D(ctkDICOMDatabase);
  372. return (d->LoadedHeader.keys());
  373. }
  374. //------------------------------------------------------------------------------
  375. QString ctkDICOMDatabase::headerValue (QString key)
  376. {
  377. Q_D(ctkDICOMDatabase);
  378. return (d->LoadedHeader[key]);
  379. }
  380. //------------------------------------------------------------------------------
  381. /*
  382. void ctkDICOMDatabase::insert ( DcmDataset *dataset ) {
  383. this->insert ( dataset, QString() );
  384. }
  385. */
  386. //------------------------------------------------------------------------------
  387. void ctkDICOMDatabase::insert( DcmDataset *dataset, bool storeFile, bool generateThumbnail)
  388. {
  389. if (!dataset)
  390. {
  391. return;
  392. }
  393. ctkDICOMDataset ctkDataset;
  394. ctkDataset.InitializeFromDataset(dataset, false /* do not take ownership */);
  395. this->insert(ctkDataset,storeFile,generateThumbnail);
  396. }
  397. void ctkDICOMDatabase::insert( const ctkDICOMDataset& ctkDataset, bool storeFile, bool generateThumbnail)
  398. {
  399. Q_D(ctkDICOMDatabase);
  400. d->insert(ctkDataset, QString(), storeFile, generateThumbnail);
  401. }
  402. //------------------------------------------------------------------------------
  403. void ctkDICOMDatabase::insert ( const QString& filePath, bool storeFile, bool generateThumbnail, bool createHierarchy, const QString& destinationDirectoryName)
  404. {
  405. Q_D(ctkDICOMDatabase);
  406. Q_UNUSED(createHierarchy);
  407. Q_UNUSED(destinationDirectoryName);
  408. /// first we check if the file is already in the database
  409. if (fileExistsAndUpToDate(filePath))
  410. {
  411. logger.debug( "File " + filePath + " already added.");
  412. return;
  413. }
  414. logger.debug( "Processing " + filePath );
  415. std::string filename = filePath.toStdString();
  416. DcmFileFormat fileformat;
  417. ctkDICOMDataset ctkDataset;
  418. ctkDataset.InitializeFromFile(filePath);
  419. if ( ctkDataset.IsInitialized() )
  420. {
  421. d->insert( ctkDataset, filePath, storeFile, generateThumbnail );
  422. }
  423. else
  424. {
  425. logger.warn(QString("Could not read DICOM file:") + filePath);
  426. }
  427. }
  428. //------------------------------------------------------------------------------
  429. void ctkDICOMDatabasePrivate::insert( const ctkDICOMDataset& ctkDataset, const QString& filePath, bool storeFile, bool generateThumbnail)
  430. {
  431. Q_Q(ctkDICOMDatabase);
  432. // Check to see if the file has already been loaded
  433. // TODO:
  434. // It could make sense to actually remove the dataset and re-add it. This needs the remove
  435. // method we still have to write.
  436. //
  437. QString sopInstanceUID ( ctkDataset.GetElementAsString(DCM_SOPInstanceUID) );
  438. QSqlQuery fileExists ( Database );
  439. fileExists.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == ?");
  440. fileExists.bindValue(0,sopInstanceUID);
  441. fileExists.exec();
  442. if ( fileExists.next() && QFileInfo(fileExists.value(1).toString()).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) )
  443. {
  444. logger.debug ( "File " + fileExists.value(1).toString() + " already added" );
  445. return;
  446. }
  447. //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  448. QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) );
  449. QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) );
  450. QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  451. QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) );
  452. if ( patientsName.isEmpty() && !patientID.isEmpty() )
  453. { // Use patient id as name if name is empty - can happen on anonymized datasets
  454. // see: http://www.na-mic.org/Bug/view.php?id=1643
  455. patientsName = patientID;
  456. }
  457. if ( patientsName.isEmpty() || studyInstanceUID.isEmpty() || patientID.isEmpty() )
  458. {
  459. logger.error("Dataset is missing necessary information!");
  460. return;
  461. }
  462. QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) );
  463. QString patientsBirthTime(ctkDataset.GetElementAsString(DCM_PatientBirthTime) );
  464. QString patientsSex(ctkDataset.GetElementAsString(DCM_PatientSex) );
  465. QString patientsAge(ctkDataset.GetElementAsString(DCM_PatientAge) );
  466. QString patientComments(ctkDataset.GetElementAsString(DCM_PatientComments) );
  467. QString studyID(ctkDataset.GetElementAsString(DCM_StudyID) );
  468. QString studyDate(ctkDataset.GetElementAsString(DCM_StudyDate) );
  469. QString studyTime(ctkDataset.GetElementAsString(DCM_StudyTime) );
  470. QString accessionNumber(ctkDataset.GetElementAsString(DCM_AccessionNumber) );
  471. QString modalitiesInStudy(ctkDataset.GetElementAsString(DCM_ModalitiesInStudy) );
  472. QString institutionName(ctkDataset.GetElementAsString(DCM_InstitutionName) );
  473. QString performingPhysiciansName(ctkDataset.GetElementAsString(DCM_PerformingPhysicianName) );
  474. QString referringPhysician(ctkDataset.GetElementAsString(DCM_ReferringPhysicianName) );
  475. QString studyDescription(ctkDataset.GetElementAsString(DCM_StudyDescription) );
  476. QString seriesDate(ctkDataset.GetElementAsString(DCM_SeriesDate) );
  477. QString seriesTime(ctkDataset.GetElementAsString(DCM_SeriesTime) );
  478. QString seriesDescription(ctkDataset.GetElementAsString(DCM_SeriesDescription) );
  479. QString bodyPartExamined(ctkDataset.GetElementAsString(DCM_BodyPartExamined) );
  480. QString frameOfReferenceUID(ctkDataset.GetElementAsString(DCM_FrameOfReferenceUID) );
  481. QString contrastAgent(ctkDataset.GetElementAsString(DCM_ContrastBolusAgent) );
  482. QString scanningSequence(ctkDataset.GetElementAsString(DCM_ScanningSequence) );
  483. long seriesNumber(ctkDataset.GetElementAsInteger(DCM_SeriesNumber) );
  484. long acquisitionNumber(ctkDataset.GetElementAsInteger(DCM_AcquisitionNumber) );
  485. long echoNumber(ctkDataset.GetElementAsInteger(DCM_EchoNumbers) );
  486. long temporalPosition(ctkDataset.GetElementAsInteger(DCM_TemporalPositionIdentifier) );
  487. // store the file if the database is not in memomry
  488. // TODO: if we are called from insert(file) we
  489. // have to do something else
  490. //
  491. QString filename = filePath;
  492. if ( storeFile && !q->isInMemory() && !seriesInstanceUID.isEmpty() )
  493. {
  494. // QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
  495. QString destinationDirectoryName = q->databaseDirectory() + "/dicom/";
  496. QDir destinationDir(destinationDirectoryName);
  497. filename = destinationDirectoryName +
  498. studyInstanceUID + "/" +
  499. seriesInstanceUID + "/" +
  500. sopInstanceUID;
  501. destinationDir.mkpath(studyInstanceUID + "/" +
  502. seriesInstanceUID);
  503. if(filePath.isEmpty())
  504. {
  505. logger.debug ( "Saving file: " + filename );
  506. if ( !ctkDataset.SaveToFile( filename) )
  507. {
  508. logger.error ( "Error saving file: " + filename );
  509. return;
  510. }
  511. }
  512. else
  513. {
  514. // we're inserting an existing file
  515. QFile currentFile( filePath );
  516. currentFile.copy(filename);
  517. logger.debug( "Copy file from: " + filePath );
  518. logger.debug( "Copy file to : " + filename );
  519. }
  520. }
  521. QSqlQuery checkPatientExistsQuery(Database);
  522. //The dbPatientID is a unique number within the database,
  523. //generated by the sqlite autoincrement
  524. //The patientID is the (non-unique) DICOM patient id
  525. int dbPatientID = -1;
  526. if ( patientID != "" && patientsName != "" )
  527. {
  528. //Speed up: Check if patient is the same as in last file;
  529. // very probable, as all images belonging to a study have the same patient
  530. if ( lastPatientID != patientID
  531. || lastPatientsBirthDate != patientsBirthDate
  532. || lastPatientsName != patientsName )
  533. {
  534. // Ok, something is different from last insert, let's insert him if he's not
  535. // already in the db.
  536. //
  537. // Check if patient is already present in the db
  538. // TODO: maybe add birthdate check for extra safety
  539. checkPatientExistsQuery.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
  540. checkPatientExistsQuery.bindValue ( 0, patientID );
  541. checkPatientExistsQuery.bindValue ( 1, patientsName );
  542. loggedExec(checkPatientExistsQuery);
  543. if (checkPatientExistsQuery.next())
  544. {
  545. // we found him
  546. dbPatientID = checkPatientExistsQuery.value(checkPatientExistsQuery.record().indexOf("UID")).toInt();
  547. }
  548. else
  549. {
  550. // Insert it
  551. QSqlQuery insertPatientStatement ( Database );
  552. insertPatientStatement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
  553. insertPatientStatement.bindValue ( 0, patientsName );
  554. insertPatientStatement.bindValue ( 1, patientID );
  555. insertPatientStatement.bindValue ( 2, patientsBirthDate );
  556. insertPatientStatement.bindValue ( 3, patientsBirthTime );
  557. insertPatientStatement.bindValue ( 4, patientsSex );
  558. // TODO: shift patient's age to study,
  559. // since this is not a patient level attribute in images
  560. // insertPatientStatement.bindValue ( 5, patientsAge );
  561. insertPatientStatement.bindValue ( 6, patientComments );
  562. loggedExec(insertPatientStatement);
  563. dbPatientID = insertPatientStatement.lastInsertId().toInt();
  564. logger.debug ( "New patient inserted: " + QString().setNum ( dbPatientID ) );
  565. }
  566. /// keep this for the next image
  567. lastPatientUID = dbPatientID;
  568. lastPatientID = patientID;
  569. lastPatientsBirthDate = patientsBirthDate;
  570. lastPatientsName = patientsName;
  571. }
  572. // Patient is in now. Let's continue with the study
  573. if ( studyInstanceUID != "" && lastStudyInstanceUID != studyInstanceUID )
  574. {
  575. QSqlQuery checkStudyExistsQuery (Database);
  576. checkStudyExistsQuery.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
  577. checkStudyExistsQuery.bindValue ( 0, studyInstanceUID );
  578. checkStudyExistsQuery.exec();
  579. if(!checkStudyExistsQuery.next())
  580. {
  581. QSqlQuery insertStudyStatement ( Database );
  582. insertStudyStatement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  583. insertStudyStatement.bindValue ( 0, studyInstanceUID );
  584. insertStudyStatement.bindValue ( 1, dbPatientID );
  585. insertStudyStatement.bindValue ( 2, studyID );
  586. insertStudyStatement.bindValue ( 3, QDate::fromString ( studyDate, "yyyyMMdd" ) );
  587. insertStudyStatement.bindValue ( 4, studyTime );
  588. insertStudyStatement.bindValue ( 5, accessionNumber );
  589. insertStudyStatement.bindValue ( 6, modalitiesInStudy );
  590. insertStudyStatement.bindValue ( 7, institutionName );
  591. insertStudyStatement.bindValue ( 8, referringPhysician );
  592. insertStudyStatement.bindValue ( 9, performingPhysiciansName );
  593. insertStudyStatement.bindValue ( 10, studyDescription );
  594. if ( !insertStudyStatement.exec() )
  595. {
  596. logger.error ( "Error executing statament: " + insertStudyStatement.lastQuery() + " Error: " + insertStudyStatement.lastError().text() );
  597. }
  598. else
  599. {
  600. lastStudyInstanceUID = studyInstanceUID;
  601. }
  602. }
  603. }
  604. if ( seriesInstanceUID != "" && seriesInstanceUID != lastSeriesInstanceUID )
  605. {
  606. QSqlQuery checkSeriesExistsQuery (Database);
  607. checkSeriesExistsQuery.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
  608. checkSeriesExistsQuery.bindValue ( 0, seriesInstanceUID );
  609. logger.warn ( "Statement: " + checkSeriesExistsQuery.lastQuery() );
  610. loggedExec(checkSeriesExistsQuery);
  611. if(!checkSeriesExistsQuery.next())
  612. {
  613. QSqlQuery insertSeriesStatement ( Database );
  614. insertSeriesStatement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  615. insertSeriesStatement.bindValue ( 0, seriesInstanceUID );
  616. insertSeriesStatement.bindValue ( 1, studyInstanceUID );
  617. insertSeriesStatement.bindValue ( 2, static_cast<int>(seriesNumber) );
  618. insertSeriesStatement.bindValue ( 3, seriesDate );
  619. insertSeriesStatement.bindValue ( 4, QDate::fromString ( seriesTime, "yyyyMMdd" ) );
  620. insertSeriesStatement.bindValue ( 5, seriesDescription );
  621. insertSeriesStatement.bindValue ( 6, bodyPartExamined );
  622. insertSeriesStatement.bindValue ( 7, frameOfReferenceUID );
  623. insertSeriesStatement.bindValue ( 8, static_cast<int>(acquisitionNumber) );
  624. insertSeriesStatement.bindValue ( 9, contrastAgent );
  625. insertSeriesStatement.bindValue ( 10, scanningSequence );
  626. insertSeriesStatement.bindValue ( 11, static_cast<int>(echoNumber) );
  627. insertSeriesStatement.bindValue ( 12, static_cast<int>(temporalPosition) );
  628. if ( !insertSeriesStatement.exec() )
  629. {
  630. logger.error ( "Error executing statament: "
  631. + insertSeriesStatement.lastQuery()
  632. + " Error: " + insertSeriesStatement.lastError().text() );
  633. lastSeriesInstanceUID = "";
  634. }
  635. else
  636. {
  637. lastSeriesInstanceUID = seriesInstanceUID;
  638. }
  639. }
  640. }
  641. // TODO: what to do with imported files
  642. //
  643. if ( !filename.isEmpty() && !seriesInstanceUID.isEmpty() )
  644. {
  645. QSqlQuery checkImageExistsQuery (Database);
  646. checkImageExistsQuery.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
  647. checkImageExistsQuery.bindValue ( 0, filename );
  648. checkImageExistsQuery.exec();
  649. if(!checkImageExistsQuery.next())
  650. {
  651. QSqlQuery insertImageStatement ( Database );
  652. insertImageStatement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" );
  653. insertImageStatement.bindValue ( 0, sopInstanceUID );
  654. insertImageStatement.bindValue ( 1, filename );
  655. insertImageStatement.bindValue ( 2, seriesInstanceUID );
  656. insertImageStatement.bindValue ( 3, QDateTime::currentDateTime() );
  657. insertImageStatement.exec();
  658. }
  659. }
  660. if( generateThumbnail && thumbnailGenerator && !seriesInstanceUID.isEmpty() )
  661. {
  662. QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
  663. //Create thumbnail here
  664. QString thumbnailPath = q->databaseDirectory() +
  665. "/thumbs/" + studyInstanceUID + "/" + seriesInstanceUID
  666. + "/" + sopInstanceUID + ".png";
  667. QFileInfo thumbnailInfo(thumbnailPath);
  668. if( !(thumbnailInfo.exists()
  669. && (thumbnailInfo.lastModified() > QFileInfo(filename).lastModified())))
  670. {
  671. QDir(q->databaseDirectory() + "/thumbs/").mkpath(studySeriesDirectory);
  672. DicomImage dcmImage(QDir::toNativeSeparators(filename).toAscii());
  673. thumbnailGenerator->generateThumbnail(&dcmImage, thumbnailPath);
  674. }
  675. }
  676. if (q->isInMemory())
  677. {
  678. emit q->databaseChanged();
  679. }
  680. }
  681. }
  682. bool ctkDICOMDatabase::fileExistsAndUpToDate(const QString& filePath)
  683. {
  684. Q_D(ctkDICOMDatabase);
  685. bool result(false);
  686. QSqlQuery check_filename_query(database());
  687. check_filename_query.prepare("SELECT InsertTimestamp FROM Images WHERE Filename == ?");
  688. check_filename_query.bindValue(0,filePath);
  689. d->loggedExec(check_filename_query);
  690. if (
  691. check_filename_query.next() &&
  692. QFileInfo(filePath).lastModified() < QDateTime::fromString(check_filename_query.value(0).toString(),Qt::ISODate)
  693. )
  694. {
  695. result = true;
  696. }
  697. check_filename_query.finish();
  698. return result;
  699. }
  700. bool ctkDICOMDatabase::isOpen() const
  701. {
  702. Q_D(const ctkDICOMDatabase);
  703. return d->Database.isOpen();
  704. }
  705. bool ctkDICOMDatabase::isInMemory() const
  706. {
  707. Q_D(const ctkDICOMDatabase);
  708. return d->DatabaseFileName == ":memory:";
  709. }
  710. bool ctkDICOMDatabase::removeSeries(const QString& seriesInstanceUID)
  711. {
  712. Q_D(ctkDICOMDatabase);
  713. // get all images from series
  714. QSqlQuery fileExists ( d->Database );
  715. fileExists.prepare("SELECT Filename, SOPInstanceUID, StudyInstanceUID FROM Images,Series WHERE Series.SeriesInstanceUID = Images.SeriesInstanceUID AND Images.SeriesInstanceUID = :seriesID");
  716. fileExists.bindValue(":seriesID",seriesInstanceUID);
  717. bool success = fileExists.exec();
  718. if (!success)
  719. {
  720. logger.error("SQLITE ERROR: " + fileExists.lastError().driverText());
  721. return false;
  722. }
  723. QList< QPair<QString,QString> > removeList;
  724. while ( fileExists.next() )
  725. {
  726. QString dbFilePath = fileExists.value(fileExists.record().indexOf("Filename")).toString();
  727. QString sopInstanceUID = fileExists.value(fileExists.record().indexOf("SOPInstanceUID")).toString();
  728. QString studyInstanceUID = fileExists.value(fileExists.record().indexOf("StudyInstanceUID")).toString();
  729. QString internalFilePath = studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID;
  730. removeList << qMakePair(dbFilePath,internalFilePath);
  731. }
  732. QSqlQuery fileRemove ( d->Database );
  733. fileRemove.prepare("DELETE FROM Images WHERE SeriesInstanceUID == ?");
  734. fileRemove.bindValue(0,seriesInstanceUID);
  735. fileRemove.exec();
  736. QPair<QString,QString> fileToRemove;
  737. foreach (fileToRemove, removeList)
  738. {
  739. QString dbFilePath = fileToRemove.first;
  740. QString thumbnailToRemove = databaseDirectory() + "/thumbs/" + fileToRemove.second + ".png";
  741. // check that the file is below our internal storage
  742. if (dbFilePath.startsWith( databaseDirectory() + "/dicom/"))
  743. {
  744. if (!dbFilePath.endsWith(fileToRemove.second))
  745. {
  746. logger.error("Database inconsistency detected during delete!");
  747. continue;
  748. }
  749. if (QFile( dbFilePath ).remove())
  750. {
  751. logger.debug("Removed file " + dbFilePath );
  752. }
  753. else
  754. {
  755. logger.warn("Failed to remove file " + dbFilePath );
  756. }
  757. }
  758. if (QFile( thumbnailToRemove ).remove())
  759. {
  760. logger.debug("Removed thumbnail " + thumbnailToRemove);
  761. }
  762. else
  763. {
  764. logger.warn("Failed to remove thumbnail " + thumbnailToRemove);
  765. }
  766. }
  767. this->cleanup();
  768. return true;
  769. }
  770. bool ctkDICOMDatabase::cleanup()
  771. {
  772. Q_D(ctkDICOMDatabase);
  773. QSqlQuery seriesCleanup ( d->Database );
  774. seriesCleanup.exec("DELETE FROM Series WHERE ( SELECT COUNT(*) FROM Images WHERE Images.SeriesInstanceUID = Series.SeriesInstanceUID ) = 0;");
  775. seriesCleanup.exec("DELETE FROM Studies WHERE ( SELECT COUNT(*) FROM Series WHERE Series.StudyInstanceUID = Studies.StudyInstanceUID ) = 0;");
  776. seriesCleanup.exec("DELETE FROM Patients WHERE ( SELECT COUNT(*) FROM Studies WHERE Studies.PatientsUID = Patients.UID ) = 0;");
  777. return true;
  778. }
  779. bool ctkDICOMDatabase::removeStudy(const QString& studyInstanceUID)
  780. {
  781. Q_D(ctkDICOMDatabase);
  782. QSqlQuery seriesForStudy( d->Database );
  783. seriesForStudy.prepare("SELECT SeriesInstanceUID FROM Series WHERE StudyInstanceUID = :studyID");
  784. seriesForStudy.bindValue(":studyID", studyInstanceUID);
  785. bool success = seriesForStudy.exec();
  786. if (!success)
  787. {
  788. logger.error("SQLITE ERROR: " + seriesForStudy.lastError().driverText());
  789. return false;
  790. }
  791. bool result = true;
  792. while ( seriesForStudy.next() )
  793. {
  794. QString seriesInstanceUID = seriesForStudy.value(seriesForStudy.record().indexOf("SeriesInstanceUID")).toString();
  795. if ( ! this->removeSeries(seriesInstanceUID) )
  796. {
  797. result = false;
  798. }
  799. }
  800. return result;;
  801. }
  802. bool ctkDICOMDatabase::removePatient(const QString& patientID)
  803. {
  804. Q_D(ctkDICOMDatabase);
  805. QSqlQuery studiesForPatient( d->Database );
  806. studiesForPatient.prepare("SELECT StudyInstanceUID FROM Studies WHERE PatientsUID = :patientsID");
  807. studiesForPatient.bindValue(":patientsID", patientID);
  808. bool success = studiesForPatient.exec();
  809. if (!success)
  810. {
  811. logger.error("SQLITE ERROR: " + studiesForPatient.lastError().driverText());
  812. return false;
  813. }
  814. bool result = true;
  815. while ( studiesForPatient.next() )
  816. {
  817. QString studyInstanceUID = studiesForPatient.value(studiesForPatient.record().indexOf("StudyInstanceUID")).toString();
  818. if ( ! this->removeStudy(studyInstanceUID) )
  819. {
  820. result = false;
  821. }
  822. }
  823. return result;;
  824. }