ctkDICOMDatabase.cpp 36 KB

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