ctkDICOMDatabase.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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. if (dO->isaString())
  359. {
  360. QString tag = QString("%1,%2").arg(
  361. dO->getGTag(),4,16,QLatin1Char('0')).arg(
  362. dO->getETag(),4,16,QLatin1Char('0'));
  363. std::ostringstream s;
  364. dO->print(s);
  365. d->LoadedHeader[tag] = QString(s.str().c_str());
  366. }
  367. }
  368. }
  369. return;
  370. }
  371. //------------------------------------------------------------------------------
  372. QStringList ctkDICOMDatabase::headerKeys ()
  373. {
  374. Q_D(ctkDICOMDatabase);
  375. return (d->LoadedHeader.keys());
  376. }
  377. //------------------------------------------------------------------------------
  378. QString ctkDICOMDatabase::headerValue (QString key)
  379. {
  380. Q_D(ctkDICOMDatabase);
  381. return (d->LoadedHeader[key]);
  382. }
  383. //------------------------------------------------------------------------------
  384. /*
  385. void ctkDICOMDatabase::insert ( DcmDataset *dataset ) {
  386. this->insert ( dataset, QString() );
  387. }
  388. */
  389. //------------------------------------------------------------------------------
  390. void ctkDICOMDatabase::insert( DcmDataset *dataset, bool storeFile, bool generateThumbnail)
  391. {
  392. if (!dataset)
  393. {
  394. return;
  395. }
  396. ctkDICOMDataset ctkDataset;
  397. ctkDataset.InitializeFromDataset(dataset, false /* do not take ownership */);
  398. this->insert(ctkDataset,storeFile,generateThumbnail);
  399. }
  400. void ctkDICOMDatabase::insert( const ctkDICOMDataset& ctkDataset, bool storeFile, bool generateThumbnail)
  401. {
  402. Q_D(ctkDICOMDatabase);
  403. d->insert(ctkDataset, QString(), storeFile, generateThumbnail);
  404. }
  405. //------------------------------------------------------------------------------
  406. void ctkDICOMDatabase::insert ( const QString& filePath, bool storeFile, bool generateThumbnail, bool createHierarchy, const QString& destinationDirectoryName)
  407. {
  408. Q_D(ctkDICOMDatabase);
  409. Q_UNUSED(createHierarchy);
  410. Q_UNUSED(destinationDirectoryName);
  411. /// first we check if the file is already in the database
  412. if (fileExistsAndUpToDate(filePath))
  413. {
  414. logger.debug( "File " + filePath + " already added.");
  415. return;
  416. }
  417. logger.debug( "Processing " + filePath );
  418. std::string filename = filePath.toStdString();
  419. DcmFileFormat fileformat;
  420. ctkDICOMDataset ctkDataset;
  421. ctkDataset.InitializeFromFile(filePath);
  422. if ( ctkDataset.IsInitialized() )
  423. {
  424. d->insert( ctkDataset, filePath, storeFile, generateThumbnail );
  425. }
  426. else
  427. {
  428. logger.warn(QString("Could not read DICOM file:") + filePath);
  429. }
  430. }
  431. //------------------------------------------------------------------------------
  432. void ctkDICOMDatabasePrivate::insert( const ctkDICOMDataset& ctkDataset, const QString& filePath, bool storeFile, bool generateThumbnail)
  433. {
  434. Q_Q(ctkDICOMDatabase);
  435. // Check to see if the file has already been loaded
  436. // TODO:
  437. // It could make sense to actually remove the dataset and re-add it. This needs the remove
  438. // method we still have to write.
  439. //
  440. QString sopInstanceUID ( ctkDataset.GetElementAsString(DCM_SOPInstanceUID) );
  441. QSqlQuery fileExists ( Database );
  442. fileExists.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == ?");
  443. fileExists.bindValue(0,sopInstanceUID);
  444. fileExists.exec();
  445. if ( fileExists.next() && QFileInfo(fileExists.value(1).toString()).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) )
  446. {
  447. logger.debug ( "File " + fileExists.value(1).toString() + " already added" );
  448. return;
  449. }
  450. //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  451. QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) );
  452. QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) );
  453. QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  454. QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) );
  455. if ( patientsName.isEmpty() && !patientID.isEmpty() )
  456. { // Use patient id as name if name is empty - can happen on anonymized datasets
  457. // see: http://www.na-mic.org/Bug/view.php?id=1643
  458. patientsName = patientID;
  459. }
  460. if ( patientsName.isEmpty() || studyInstanceUID.isEmpty() || patientID.isEmpty() )
  461. {
  462. logger.error("Dataset is missing necessary information!");
  463. return;
  464. }
  465. QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) );
  466. QString patientsBirthTime(ctkDataset.GetElementAsString(DCM_PatientBirthTime) );
  467. QString patientsSex(ctkDataset.GetElementAsString(DCM_PatientSex) );
  468. QString patientsAge(ctkDataset.GetElementAsString(DCM_PatientAge) );
  469. QString patientComments(ctkDataset.GetElementAsString(DCM_PatientComments) );
  470. QString studyID(ctkDataset.GetElementAsString(DCM_StudyID) );
  471. QString studyDate(ctkDataset.GetElementAsString(DCM_StudyDate) );
  472. QString studyTime(ctkDataset.GetElementAsString(DCM_StudyTime) );
  473. QString accessionNumber(ctkDataset.GetElementAsString(DCM_AccessionNumber) );
  474. QString modalitiesInStudy(ctkDataset.GetElementAsString(DCM_ModalitiesInStudy) );
  475. QString institutionName(ctkDataset.GetElementAsString(DCM_InstitutionName) );
  476. QString performingPhysiciansName(ctkDataset.GetElementAsString(DCM_PerformingPhysicianName) );
  477. QString referringPhysician(ctkDataset.GetElementAsString(DCM_ReferringPhysicianName) );
  478. QString studyDescription(ctkDataset.GetElementAsString(DCM_StudyDescription) );
  479. QString seriesDate(ctkDataset.GetElementAsString(DCM_SeriesDate) );
  480. QString seriesTime(ctkDataset.GetElementAsString(DCM_SeriesTime) );
  481. QString seriesDescription(ctkDataset.GetElementAsString(DCM_SeriesDescription) );
  482. QString bodyPartExamined(ctkDataset.GetElementAsString(DCM_BodyPartExamined) );
  483. QString frameOfReferenceUID(ctkDataset.GetElementAsString(DCM_FrameOfReferenceUID) );
  484. QString contrastAgent(ctkDataset.GetElementAsString(DCM_ContrastBolusAgent) );
  485. QString scanningSequence(ctkDataset.GetElementAsString(DCM_ScanningSequence) );
  486. long seriesNumber(ctkDataset.GetElementAsInteger(DCM_SeriesNumber) );
  487. long acquisitionNumber(ctkDataset.GetElementAsInteger(DCM_AcquisitionNumber) );
  488. long echoNumber(ctkDataset.GetElementAsInteger(DCM_EchoNumbers) );
  489. long temporalPosition(ctkDataset.GetElementAsInteger(DCM_TemporalPositionIdentifier) );
  490. // store the file if the database is not in memomry
  491. // TODO: if we are called from insert(file) we
  492. // have to do something else
  493. //
  494. QString filename = filePath;
  495. if ( storeFile && !q->isInMemory() && !seriesInstanceUID.isEmpty() )
  496. {
  497. // QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
  498. QString destinationDirectoryName = q->databaseDirectory() + "/dicom/";
  499. QDir destinationDir(destinationDirectoryName);
  500. filename = destinationDirectoryName +
  501. studyInstanceUID + "/" +
  502. seriesInstanceUID + "/" +
  503. sopInstanceUID;
  504. destinationDir.mkpath(studyInstanceUID + "/" +
  505. seriesInstanceUID);
  506. if(filePath.isEmpty())
  507. {
  508. logger.debug ( "Saving file: " + filename );
  509. if ( !ctkDataset.SaveToFile( filename) )
  510. {
  511. logger.error ( "Error saving file: " + filename );
  512. return;
  513. }
  514. }
  515. else
  516. {
  517. // we're inserting an existing file
  518. QFile currentFile( filePath );
  519. currentFile.copy(filename);
  520. logger.debug( "Copy file from: " + filePath );
  521. logger.debug( "Copy file to : " + filename );
  522. }
  523. }
  524. QSqlQuery checkPatientExistsQuery(Database);
  525. //The dbPatientID is a unique number within the database,
  526. //generated by the sqlite autoincrement
  527. //The patientID is the (non-unique) DICOM patient id
  528. int dbPatientID = -1;
  529. if ( patientID != "" && patientsName != "" )
  530. {
  531. //Speed up: Check if patient is the same as in last file;
  532. // very probable, as all images belonging to a study have the same patient
  533. if ( lastPatientID != patientID
  534. || lastPatientsBirthDate != patientsBirthDate
  535. || lastPatientsName != patientsName )
  536. {
  537. // Ok, something is different from last insert, let's insert him if he's not
  538. // already in the db.
  539. //
  540. // Check if patient is already present in the db
  541. // TODO: maybe add birthdate check for extra safety
  542. checkPatientExistsQuery.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
  543. checkPatientExistsQuery.bindValue ( 0, patientID );
  544. checkPatientExistsQuery.bindValue ( 1, patientsName );
  545. loggedExec(checkPatientExistsQuery);
  546. if (checkPatientExistsQuery.next())
  547. {
  548. // we found him
  549. dbPatientID = checkPatientExistsQuery.value(checkPatientExistsQuery.record().indexOf("UID")).toInt();
  550. }
  551. else
  552. {
  553. // Insert it
  554. QSqlQuery insertPatientStatement ( Database );
  555. insertPatientStatement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
  556. insertPatientStatement.bindValue ( 0, patientsName );
  557. insertPatientStatement.bindValue ( 1, patientID );
  558. insertPatientStatement.bindValue ( 2, patientsBirthDate );
  559. insertPatientStatement.bindValue ( 3, patientsBirthTime );
  560. insertPatientStatement.bindValue ( 4, patientsSex );
  561. // TODO: shift patient's age to study,
  562. // since this is not a patient level attribute in images
  563. // insertPatientStatement.bindValue ( 5, patientsAge );
  564. insertPatientStatement.bindValue ( 6, patientComments );
  565. loggedExec(insertPatientStatement);
  566. dbPatientID = insertPatientStatement.lastInsertId().toInt();
  567. logger.debug ( "New patient inserted: " + QString().setNum ( dbPatientID ) );
  568. }
  569. /// keep this for the next image
  570. lastPatientUID = dbPatientID;
  571. lastPatientID = patientID;
  572. lastPatientsBirthDate = patientsBirthDate;
  573. lastPatientsName = patientsName;
  574. }
  575. // Patient is in now. Let's continue with the study
  576. if ( studyInstanceUID != "" && lastStudyInstanceUID != studyInstanceUID )
  577. {
  578. QSqlQuery checkStudyExistsQuery (Database);
  579. checkStudyExistsQuery.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
  580. checkStudyExistsQuery.bindValue ( 0, studyInstanceUID );
  581. checkStudyExistsQuery.exec();
  582. if(!checkStudyExistsQuery.next())
  583. {
  584. QSqlQuery insertStudyStatement ( Database );
  585. insertStudyStatement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  586. insertStudyStatement.bindValue ( 0, studyInstanceUID );
  587. insertStudyStatement.bindValue ( 1, dbPatientID );
  588. insertStudyStatement.bindValue ( 2, studyID );
  589. insertStudyStatement.bindValue ( 3, QDate::fromString ( studyDate, "yyyyMMdd" ) );
  590. insertStudyStatement.bindValue ( 4, studyTime );
  591. insertStudyStatement.bindValue ( 5, accessionNumber );
  592. insertStudyStatement.bindValue ( 6, modalitiesInStudy );
  593. insertStudyStatement.bindValue ( 7, institutionName );
  594. insertStudyStatement.bindValue ( 8, referringPhysician );
  595. insertStudyStatement.bindValue ( 9, performingPhysiciansName );
  596. insertStudyStatement.bindValue ( 10, studyDescription );
  597. if ( !insertStudyStatement.exec() )
  598. {
  599. logger.error ( "Error executing statament: " + insertStudyStatement.lastQuery() + " Error: " + insertStudyStatement.lastError().text() );
  600. }
  601. else
  602. {
  603. lastStudyInstanceUID = studyInstanceUID;
  604. }
  605. }
  606. }
  607. if ( seriesInstanceUID != "" && seriesInstanceUID != lastSeriesInstanceUID )
  608. {
  609. QSqlQuery checkSeriesExistsQuery (Database);
  610. checkSeriesExistsQuery.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
  611. checkSeriesExistsQuery.bindValue ( 0, seriesInstanceUID );
  612. logger.warn ( "Statement: " + checkSeriesExistsQuery.lastQuery() );
  613. loggedExec(checkSeriesExistsQuery);
  614. if(!checkSeriesExistsQuery.next())
  615. {
  616. QSqlQuery insertSeriesStatement ( Database );
  617. insertSeriesStatement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  618. insertSeriesStatement.bindValue ( 0, seriesInstanceUID );
  619. insertSeriesStatement.bindValue ( 1, studyInstanceUID );
  620. insertSeriesStatement.bindValue ( 2, static_cast<int>(seriesNumber) );
  621. insertSeriesStatement.bindValue ( 3, seriesDate );
  622. insertSeriesStatement.bindValue ( 4, QDate::fromString ( seriesTime, "yyyyMMdd" ) );
  623. insertSeriesStatement.bindValue ( 5, seriesDescription );
  624. insertSeriesStatement.bindValue ( 6, bodyPartExamined );
  625. insertSeriesStatement.bindValue ( 7, frameOfReferenceUID );
  626. insertSeriesStatement.bindValue ( 8, static_cast<int>(acquisitionNumber) );
  627. insertSeriesStatement.bindValue ( 9, contrastAgent );
  628. insertSeriesStatement.bindValue ( 10, scanningSequence );
  629. insertSeriesStatement.bindValue ( 11, static_cast<int>(echoNumber) );
  630. insertSeriesStatement.bindValue ( 12, static_cast<int>(temporalPosition) );
  631. if ( !insertSeriesStatement.exec() )
  632. {
  633. logger.error ( "Error executing statament: "
  634. + insertSeriesStatement.lastQuery()
  635. + " Error: " + insertSeriesStatement.lastError().text() );
  636. lastSeriesInstanceUID = "";
  637. }
  638. else
  639. {
  640. lastSeriesInstanceUID = seriesInstanceUID;
  641. }
  642. }
  643. }
  644. // TODO: what to do with imported files
  645. //
  646. if ( !filename.isEmpty() && !seriesInstanceUID.isEmpty() )
  647. {
  648. QSqlQuery checkImageExistsQuery (Database);
  649. checkImageExistsQuery.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
  650. checkImageExistsQuery.bindValue ( 0, filename );
  651. checkImageExistsQuery.exec();
  652. if(!checkImageExistsQuery.next())
  653. {
  654. QSqlQuery insertImageStatement ( Database );
  655. insertImageStatement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" );
  656. insertImageStatement.bindValue ( 0, sopInstanceUID );
  657. insertImageStatement.bindValue ( 1, filename );
  658. insertImageStatement.bindValue ( 2, seriesInstanceUID );
  659. insertImageStatement.bindValue ( 3, QDateTime::currentDateTime() );
  660. insertImageStatement.exec();
  661. }
  662. }
  663. if( generateThumbnail && thumbnailGenerator && !seriesInstanceUID.isEmpty() )
  664. {
  665. QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
  666. //Create thumbnail here
  667. QString thumbnailPath = q->databaseDirectory() +
  668. "/thumbs/" + studyInstanceUID + "/" + seriesInstanceUID
  669. + "/" + sopInstanceUID + ".png";
  670. QFileInfo thumbnailInfo(thumbnailPath);
  671. if( !(thumbnailInfo.exists()
  672. && (thumbnailInfo.lastModified() > QFileInfo(filename).lastModified())))
  673. {
  674. QDir(q->databaseDirectory() + "/thumbs/").mkpath(studySeriesDirectory);
  675. DicomImage dcmImage(QDir::toNativeSeparators(filename).toAscii());
  676. thumbnailGenerator->generateThumbnail(&dcmImage, thumbnailPath);
  677. }
  678. }
  679. if (q->isInMemory())
  680. {
  681. emit q->databaseChanged();
  682. }
  683. }
  684. }
  685. bool ctkDICOMDatabase::fileExistsAndUpToDate(const QString& filePath)
  686. {
  687. Q_D(ctkDICOMDatabase);
  688. bool result(false);
  689. QSqlQuery check_filename_query(database());
  690. check_filename_query.prepare("SELECT InsertTimestamp FROM Images WHERE Filename == ?");
  691. check_filename_query.bindValue(0,filePath);
  692. d->loggedExec(check_filename_query);
  693. if (
  694. check_filename_query.next() &&
  695. QFileInfo(filePath).lastModified() < QDateTime::fromString(check_filename_query.value(0).toString(),Qt::ISODate)
  696. )
  697. {
  698. result = true;
  699. }
  700. check_filename_query.finish();
  701. return result;
  702. }
  703. bool ctkDICOMDatabase::isOpen() const
  704. {
  705. Q_D(const ctkDICOMDatabase);
  706. return d->Database.isOpen();
  707. }
  708. bool ctkDICOMDatabase::isInMemory() const
  709. {
  710. Q_D(const ctkDICOMDatabase);
  711. return d->DatabaseFileName == ":memory:";
  712. }
  713. bool ctkDICOMDatabase::removeSeries(const QString& seriesInstanceUID)
  714. {
  715. Q_D(ctkDICOMDatabase);
  716. // get all images from series
  717. QSqlQuery fileExists ( d->Database );
  718. fileExists.prepare("SELECT Filename, SOPInstanceUID, StudyInstanceUID FROM Images,Series WHERE Series.SeriesInstanceUID = Images.SeriesInstanceUID AND Images.SeriesInstanceUID = :seriesID");
  719. fileExists.bindValue(":seriesID",seriesInstanceUID);
  720. bool success = fileExists.exec();
  721. if (!success)
  722. {
  723. logger.error("SQLITE ERROR: " + fileExists.lastError().driverText());
  724. return false;
  725. }
  726. QList< QPair<QString,QString> > removeList;
  727. while ( fileExists.next() )
  728. {
  729. QString dbFilePath = fileExists.value(fileExists.record().indexOf("Filename")).toString();
  730. QString sopInstanceUID = fileExists.value(fileExists.record().indexOf("SOPInstanceUID")).toString();
  731. QString studyInstanceUID = fileExists.value(fileExists.record().indexOf("StudyInstanceUID")).toString();
  732. QString internalFilePath = studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID;
  733. removeList << qMakePair(dbFilePath,internalFilePath);
  734. }
  735. QSqlQuery fileRemove ( d->Database );
  736. fileRemove.prepare("DELETE FROM Images WHERE SeriesInstanceUID == ?");
  737. fileRemove.bindValue(0,seriesInstanceUID);
  738. fileRemove.exec();
  739. QPair<QString,QString> fileToRemove;
  740. foreach (fileToRemove, removeList)
  741. {
  742. QString dbFilePath = fileToRemove.first;
  743. QString thumbnailToRemove = databaseDirectory() + "/thumbs/" + fileToRemove.second + ".png";
  744. // check that the file is below our internal storage
  745. if (dbFilePath.startsWith( databaseDirectory() + "/dicom/"))
  746. {
  747. if (!dbFilePath.endsWith(fileToRemove.second))
  748. {
  749. logger.error("Database inconsistency detected during delete!");
  750. continue;
  751. }
  752. if (QFile( dbFilePath ).remove())
  753. {
  754. logger.debug("Removed file " + dbFilePath );
  755. }
  756. else
  757. {
  758. logger.warn("Failed to remove file " + dbFilePath );
  759. }
  760. }
  761. if (QFile( thumbnailToRemove ).remove())
  762. {
  763. logger.debug("Removed thumbnail " + thumbnailToRemove);
  764. }
  765. else
  766. {
  767. logger.warn("Failed to remove thumbnail " + thumbnailToRemove);
  768. }
  769. }
  770. this->cleanup();
  771. return true;
  772. }
  773. bool ctkDICOMDatabase::cleanup()
  774. {
  775. Q_D(ctkDICOMDatabase);
  776. QSqlQuery seriesCleanup ( d->Database );
  777. seriesCleanup.exec("DELETE FROM Series WHERE ( SELECT COUNT(*) FROM Images WHERE Images.SeriesInstanceUID = Series.SeriesInstanceUID ) = 0;");
  778. seriesCleanup.exec("DELETE FROM Studies WHERE ( SELECT COUNT(*) FROM Series WHERE Series.StudyInstanceUID = Studies.StudyInstanceUID ) = 0;");
  779. seriesCleanup.exec("DELETE FROM Patients WHERE ( SELECT COUNT(*) FROM Studies WHERE Studies.PatientsUID = Patients.UID ) = 0;");
  780. return true;
  781. }
  782. bool ctkDICOMDatabase::removeStudy(const QString& studyInstanceUID)
  783. {
  784. Q_D(ctkDICOMDatabase);
  785. QSqlQuery seriesForStudy( d->Database );
  786. seriesForStudy.prepare("SELECT SeriesInstanceUID FROM Series WHERE StudyInstanceUID = :studyID");
  787. seriesForStudy.bindValue(":studyID", studyInstanceUID);
  788. bool success = seriesForStudy.exec();
  789. if (!success)
  790. {
  791. logger.error("SQLITE ERROR: " + seriesForStudy.lastError().driverText());
  792. return false;
  793. }
  794. bool result = true;
  795. while ( seriesForStudy.next() )
  796. {
  797. QString seriesInstanceUID = seriesForStudy.value(seriesForStudy.record().indexOf("SeriesInstanceUID")).toString();
  798. if ( ! this->removeSeries(seriesInstanceUID) )
  799. {
  800. result = false;
  801. }
  802. }
  803. return result;;
  804. }
  805. bool ctkDICOMDatabase::removePatient(const QString& patientID)
  806. {
  807. Q_D(ctkDICOMDatabase);
  808. QSqlQuery studiesForPatient( d->Database );
  809. studiesForPatient.prepare("SELECT StudyInstanceUID FROM Studies WHERE PatientsUID = :patientsID");
  810. studiesForPatient.bindValue(":patientsID", patientID);
  811. bool success = studiesForPatient.exec();
  812. if (!success)
  813. {
  814. logger.error("SQLITE ERROR: " + studiesForPatient.lastError().driverText());
  815. return false;
  816. }
  817. bool result = true;
  818. while ( studiesForPatient.next() )
  819. {
  820. QString studyInstanceUID = studiesForPatient.value(studiesForPatient.record().indexOf("StudyInstanceUID")).toString();
  821. if ( ! this->removeStudy(studyInstanceUID) )
  822. {
  823. result = false;
  824. }
  825. }
  826. return result;;
  827. }