ctkDICOMDatabase.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  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 <QDate>
  17. #include <QDebug>
  18. #include <QDirIterator>
  19. #include <QFile>
  20. #include <QFileInfo>
  21. #include <QFileSystemWatcher>
  22. #include <QMutexLocker>
  23. #include <QSet>
  24. #include <QSqlError>
  25. #include <QSqlQuery>
  26. #include <QSqlRecord>
  27. #include <QStringList>
  28. #include <QVariant>
  29. // ctkDICOM includes
  30. #include "ctkDICOMDatabase.h"
  31. #include "ctkDICOMAbstractThumbnailGenerator.h"
  32. #include "ctkDICOMDataset.h"
  33. #include "ctkLogger.h"
  34. // DCMTK includes
  35. #include <dcmtk/dcmdata/dcfilefo.h>
  36. #include <dcmtk/dcmdata/dcfilefo.h>
  37. #include <dcmtk/dcmdata/dcdeftag.h>
  38. #include <dcmtk/dcmdata/dcdatset.h>
  39. #include <dcmtk/ofstd/ofcond.h>
  40. #include <dcmtk/ofstd/ofstring.h>
  41. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  42. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  43. #include <dcmimage.h>
  44. #include <dcmtk/dcmjpeg/djdecode.h> /* for dcmjpeg decoders */
  45. #include <dcmtk/dcmjpeg/djencode.h> /* for dcmjpeg encoders */
  46. #include <dcmtk/dcmdata/dcrledrg.h> /* for DcmRLEDecoderRegistration */
  47. #include <dcmtk/dcmdata/dcrleerg.h> /* for DcmRLEEncoderRegistration */
  48. //------------------------------------------------------------------------------
  49. static ctkLogger logger("org.commontk.dicom.DICOMDatabase" );
  50. //------------------------------------------------------------------------------
  51. //------------------------------------------------------------------------------
  52. class ctkDICOMDatabasePrivate
  53. {
  54. Q_DECLARE_PUBLIC(ctkDICOMDatabase);
  55. protected:
  56. ctkDICOMDatabase* const q_ptr;
  57. public:
  58. ctkDICOMDatabasePrivate(ctkDICOMDatabase&);
  59. ~ctkDICOMDatabasePrivate();
  60. void init(QString databaseFile);
  61. void registerCompressionLibraries();
  62. bool executeScript(const QString script);
  63. ///
  64. /// \brief runs a query and prints debug output of status
  65. ///
  66. bool loggedExec(QSqlQuery& query);
  67. bool loggedExec(QSqlQuery& query, const QString& queryString);
  68. bool LoggedExecVerbose;
  69. // dataset must be set always
  70. // filePath has to be set if this is an import of an actual file
  71. void insert ( const ctkDICOMDataset& ctkDataset, const QString& filePath, bool storeFile = true, bool generateThumbnail = true);
  72. ///
  73. /// copy the complete list of files to an extra table
  74. ///
  75. void createBackupFileList();
  76. ///
  77. /// remove the extra table containing the backup
  78. ///
  79. void removeBackupFileList();
  80. ///
  81. /// get all Filename values from table
  82. QStringList filenames(QString table);
  83. /// Name of the database file (i.e. for SQLITE the sqlite file)
  84. QString DatabaseFileName;
  85. QString LastError;
  86. QSqlDatabase Database;
  87. QMap<QString, QString> LoadedHeader;
  88. ctkDICOMAbstractThumbnailGenerator* thumbnailGenerator;
  89. /// these are for optimizing the import of image sequences
  90. /// since most information are identical for all slices
  91. QString LastPatientID;
  92. QString LastPatientsName;
  93. QString LastPatientsBirthDate;
  94. QString LastStudyInstanceUID;
  95. QString LastSeriesInstanceUID;
  96. int LastPatientUID;
  97. /// parallel inserts are not allowed (yet)
  98. QMutex insertMutex;
  99. /// tagCache table has been checked to exist
  100. bool TagCacheVerified;
  101. /// tag cache has independent database to avoid locking issue
  102. /// with other access to the database which need to be
  103. /// reading while the tag cache is writing
  104. QSqlDatabase TagCacheDatabase;
  105. QString TagCacheDatabaseFilename;
  106. int insertPatient(const ctkDICOMDataset& ctkDataset);
  107. void insertStudy(const ctkDICOMDataset& ctkDataset, int dbPatientID);
  108. void insertSeries( const ctkDICOMDataset& ctkDataset, QString studyInstanceUID);
  109. };
  110. //------------------------------------------------------------------------------
  111. // ctkDICOMDatabasePrivate methods
  112. //------------------------------------------------------------------------------
  113. ctkDICOMDatabasePrivate::ctkDICOMDatabasePrivate(ctkDICOMDatabase& o): q_ptr(&o)
  114. {
  115. this->thumbnailGenerator = NULL;
  116. this->LoggedExecVerbose = false;
  117. this->LastPatientUID = -1;
  118. this->TagCacheVerified = false;
  119. }
  120. //------------------------------------------------------------------------------
  121. void ctkDICOMDatabasePrivate::init(QString databaseFilename)
  122. {
  123. Q_Q(ctkDICOMDatabase);
  124. q->openDatabase(databaseFilename);
  125. }
  126. //------------------------------------------------------------------------------
  127. void ctkDICOMDatabasePrivate::registerCompressionLibraries(){
  128. logger.debug("Register compression libraries");
  129. // Register the JPEG libraries in case we need them
  130. // (registration only happens once, so it's okay to call repeatedly)
  131. // register global JPEG decompression codecs
  132. DJDecoderRegistration::registerCodecs();
  133. // register global JPEG compression codecs
  134. DJEncoderRegistration::registerCodecs();
  135. // register RLE compression codec
  136. DcmRLEEncoderRegistration::registerCodecs();
  137. // register RLE decompression codec
  138. DcmRLEDecoderRegistration::registerCodecs();
  139. }
  140. //------------------------------------------------------------------------------
  141. ctkDICOMDatabasePrivate::~ctkDICOMDatabasePrivate()
  142. {
  143. }
  144. //------------------------------------------------------------------------------
  145. bool ctkDICOMDatabasePrivate::loggedExec(QSqlQuery& query)
  146. {
  147. return (loggedExec(query, QString("")));
  148. }
  149. //------------------------------------------------------------------------------
  150. bool ctkDICOMDatabasePrivate::loggedExec(QSqlQuery& query, const QString& queryString)
  151. {
  152. bool success;
  153. if (queryString.compare(""))
  154. {
  155. success = query.exec(queryString);
  156. }
  157. else
  158. {
  159. success = query.exec();
  160. }
  161. if (!success)
  162. {
  163. QSqlError sqlError = query.lastError();
  164. logger.debug( "SQL failed\n Bad SQL: " + query.lastQuery());
  165. logger.debug( "Error text: " + sqlError.text());
  166. }
  167. else
  168. {
  169. if (LoggedExecVerbose)
  170. {
  171. logger.debug( "SQL worked!\n SQL: " + query.lastQuery());
  172. }
  173. }
  174. return (success);
  175. }
  176. //------------------------------------------------------------------------------
  177. void ctkDICOMDatabasePrivate::createBackupFileList()
  178. {
  179. QSqlQuery query(this->Database);
  180. loggedExec(query, "CREATE TABLE IF NOT EXISTS main.Filenames_backup (Filename TEXT PRIMARY KEY NOT NULL )" );
  181. loggedExec(query, "INSERT INTO Filenames_backup SELECT Filename FROM Images;" );
  182. }
  183. //------------------------------------------------------------------------------
  184. void ctkDICOMDatabasePrivate::removeBackupFileList()
  185. {
  186. QSqlQuery query(this->Database);
  187. loggedExec(query, "DROP TABLE main.Filenames_backup; " );
  188. }
  189. //------------------------------------------------------------------------------
  190. void ctkDICOMDatabase::openDatabase(const QString databaseFile, const QString& connectionName )
  191. {
  192. Q_D(ctkDICOMDatabase);
  193. d->DatabaseFileName = databaseFile;
  194. d->Database = QSqlDatabase::addDatabase("QSQLITE", connectionName);
  195. d->Database.setDatabaseName(databaseFile);
  196. if ( ! (d->Database.open()) )
  197. {
  198. d->LastError = d->Database.lastError().text();
  199. return;
  200. }
  201. if ( d->Database.tables().empty() )
  202. {
  203. if (!initializeDatabase())
  204. {
  205. d->LastError = QString("Unable to initialize DICOM database!");
  206. return;
  207. }
  208. }
  209. if (!isInMemory())
  210. {
  211. QFileSystemWatcher* watcher = new QFileSystemWatcher(QStringList(databaseFile),this);
  212. connect(watcher, SIGNAL(fileChanged(QString)),this, SIGNAL (databaseChanged()) );
  213. }
  214. // set up the tag cache for use later
  215. QFileInfo fileInfo(d->DatabaseFileName);
  216. d->TagCacheDatabaseFilename = QString( fileInfo.dir().path() + "/ctkDICOMTagCache.sql" );
  217. d->TagCacheVerified = false;
  218. }
  219. //------------------------------------------------------------------------------
  220. // ctkDICOMDatabase methods
  221. //------------------------------------------------------------------------------
  222. ctkDICOMDatabase::ctkDICOMDatabase(QString databaseFile)
  223. : d_ptr(new ctkDICOMDatabasePrivate(*this))
  224. {
  225. Q_D(ctkDICOMDatabase);
  226. d->registerCompressionLibraries();
  227. d->init(databaseFile);
  228. }
  229. ctkDICOMDatabase::ctkDICOMDatabase(QObject* parent)
  230. : d_ptr(new ctkDICOMDatabasePrivate(*this))
  231. {
  232. Q_UNUSED(parent);
  233. Q_D(ctkDICOMDatabase);
  234. d->registerCompressionLibraries();
  235. }
  236. //------------------------------------------------------------------------------
  237. ctkDICOMDatabase::~ctkDICOMDatabase()
  238. {
  239. }
  240. //----------------------------------------------------------------------------
  241. //------------------------------------------------------------------------------
  242. const QString ctkDICOMDatabase::lastError() const {
  243. Q_D(const ctkDICOMDatabase);
  244. return d->LastError;
  245. }
  246. //------------------------------------------------------------------------------
  247. const QString ctkDICOMDatabase::databaseFilename() const {
  248. Q_D(const ctkDICOMDatabase);
  249. return d->DatabaseFileName;
  250. }
  251. //------------------------------------------------------------------------------
  252. const QString ctkDICOMDatabase::databaseDirectory() const {
  253. QString databaseFile = databaseFilename();
  254. if (!QFileInfo(databaseFile).isAbsolute())
  255. {
  256. databaseFile.prepend(QDir::currentPath() + "/");
  257. }
  258. return QFileInfo ( databaseFile ).absoluteDir().path();
  259. }
  260. //------------------------------------------------------------------------------
  261. const QSqlDatabase& ctkDICOMDatabase::database() const {
  262. Q_D(const ctkDICOMDatabase);
  263. return d->Database;
  264. }
  265. //------------------------------------------------------------------------------
  266. void ctkDICOMDatabase::setThumbnailGenerator(ctkDICOMAbstractThumbnailGenerator *generator){
  267. Q_D(ctkDICOMDatabase);
  268. d->thumbnailGenerator = generator;
  269. }
  270. //------------------------------------------------------------------------------
  271. ctkDICOMAbstractThumbnailGenerator* ctkDICOMDatabase::thumbnailGenerator(){
  272. Q_D(const ctkDICOMDatabase);
  273. return d->thumbnailGenerator;
  274. }
  275. //------------------------------------------------------------------------------
  276. bool ctkDICOMDatabasePrivate::executeScript(const QString script) {
  277. QFile scriptFile(script);
  278. scriptFile.open(QIODevice::ReadOnly);
  279. if ( !scriptFile.isOpen() )
  280. {
  281. qDebug() << "Script file " << script << " could not be opened!\n";
  282. return false;
  283. }
  284. QString sqlCommands( QTextStream(&scriptFile).readAll() );
  285. sqlCommands.replace( '\n', ' ' );
  286. sqlCommands.remove( '\r' );
  287. sqlCommands.replace("; ", ";\n");
  288. QStringList sqlCommandsLines = sqlCommands.split('\n');
  289. QSqlQuery query(Database);
  290. for (QStringList::iterator it = sqlCommandsLines.begin(); it != sqlCommandsLines.end()-1; ++it)
  291. {
  292. if (! (*it).startsWith("--") )
  293. {
  294. qDebug() << *it << "\n";
  295. query.exec(*it);
  296. if (query.lastError().type())
  297. {
  298. qDebug() << "There was an error during execution of the statement: " << (*it);
  299. qDebug() << "Error message: " << query.lastError().text();
  300. return false;
  301. }
  302. }
  303. }
  304. return true;
  305. }
  306. //------------------------------------------------------------------------------
  307. QStringList ctkDICOMDatabasePrivate::filenames(QString table)
  308. {
  309. /// get all filenames from the database
  310. QSqlQuery allFilesQuery(this->Database);
  311. QStringList allFileNames;
  312. loggedExec(allFilesQuery,QString("SELECT Filename from %1 ;").arg(table) );
  313. while (allFilesQuery.next())
  314. {
  315. allFileNames << allFilesQuery.value(0).toString();
  316. }
  317. return allFileNames;
  318. }
  319. //------------------------------------------------------------------------------
  320. bool ctkDICOMDatabase::initializeDatabase(const char* sqlFileName)
  321. {
  322. Q_D(ctkDICOMDatabase);
  323. return d->executeScript(sqlFileName);
  324. }
  325. //------------------------------------------------------------------------------
  326. bool ctkDICOMDatabase::updateSchema(const char* schemaFile)
  327. {
  328. // backup filelist
  329. // reinit with the new schema
  330. // reinsert everything
  331. Q_D(ctkDICOMDatabase);
  332. d->createBackupFileList();
  333. this->initializeDatabase(schemaFile);
  334. QStringList allFiles = d->filenames("Filenames_backup");
  335. foreach(QString file, allFiles)
  336. {
  337. // TODO: use QFuture
  338. this->insert(file,false,false,true);
  339. }
  340. // TODO: check better that everything is ok
  341. d->removeBackupFileList();
  342. return true;
  343. }
  344. //------------------------------------------------------------------------------
  345. void ctkDICOMDatabase::closeDatabase()
  346. {
  347. Q_D(ctkDICOMDatabase);
  348. d->Database.close();
  349. d->TagCacheDatabase.close();
  350. }
  351. //
  352. // Patient/study/series convenience methods
  353. //
  354. //------------------------------------------------------------------------------
  355. QStringList ctkDICOMDatabase::patients()
  356. {
  357. Q_D(ctkDICOMDatabase);
  358. QSqlQuery query(d->Database);
  359. query.prepare ( "SELECT UID FROM Patients" );
  360. query.exec();
  361. QStringList result;
  362. while (query.next())
  363. {
  364. result << query.value(0).toString();
  365. }
  366. return( result );
  367. }
  368. //------------------------------------------------------------------------------
  369. QStringList ctkDICOMDatabase::studiesForPatient(QString dbPatientID)
  370. {
  371. Q_D(ctkDICOMDatabase);
  372. QSqlQuery query(d->Database);
  373. query.prepare ( "SELECT StudyInstanceUID FROM Studies WHERE PatientsUID = ?" );
  374. query.bindValue ( 0, dbPatientID );
  375. query.exec();
  376. QStringList result;
  377. while (query.next())
  378. {
  379. result << query.value(0).toString();
  380. }
  381. return( result );
  382. }
  383. //------------------------------------------------------------------------------
  384. QStringList ctkDICOMDatabase::seriesForStudy(QString studyUID)
  385. {
  386. Q_D(ctkDICOMDatabase);
  387. QSqlQuery query(d->Database);
  388. query.prepare ( "SELECT SeriesInstanceUID FROM Series WHERE StudyInstanceUID=?");
  389. query.bindValue ( 0, studyUID );
  390. query.exec();
  391. QStringList result;
  392. while (query.next())
  393. {
  394. result << query.value(0).toString();
  395. }
  396. return( result );
  397. }
  398. //------------------------------------------------------------------------------
  399. QStringList ctkDICOMDatabase::filesForSeries(QString seriesUID)
  400. {
  401. Q_D(ctkDICOMDatabase);
  402. QSqlQuery query(d->Database);
  403. query.prepare ( "SELECT Filename FROM Images WHERE SeriesInstanceUID=?");
  404. query.bindValue ( 0, seriesUID );
  405. query.exec();
  406. QStringList result;
  407. while (query.next())
  408. {
  409. result << query.value(0).toString();
  410. }
  411. return( result );
  412. }
  413. //------------------------------------------------------------------------------
  414. QString ctkDICOMDatabase::fileForInstance(QString sopInstanceUID)
  415. {
  416. Q_D(ctkDICOMDatabase);
  417. QSqlQuery query(d->Database);
  418. query.prepare ( "SELECT Filename FROM Images WHERE SOPInstanceUID=?");
  419. query.bindValue ( 0, sopInstanceUID );
  420. query.exec();
  421. QString result;
  422. if (query.next())
  423. {
  424. result = query.value(0).toString();
  425. }
  426. return( result );
  427. }
  428. //------------------------------------------------------------------------------
  429. QString ctkDICOMDatabase::instanceForFile(QString fileName)
  430. {
  431. Q_D(ctkDICOMDatabase);
  432. QSqlQuery query(d->Database);
  433. query.prepare ( "SELECT SOPInstanceUID FROM Images WHERE Filename=?");
  434. query.bindValue ( 0, fileName );
  435. query.exec();
  436. QString result;
  437. if (query.next())
  438. {
  439. result = query.value(0).toString();
  440. }
  441. return( result );
  442. }
  443. //
  444. // instance header methods
  445. //
  446. //------------------------------------------------------------------------------
  447. QStringList ctkDICOMDatabase::allFiles()
  448. {
  449. Q_D(ctkDICOMDatabase);
  450. return d->filenames("Images");
  451. }
  452. //------------------------------------------------------------------------------
  453. void ctkDICOMDatabase::loadInstanceHeader (QString sopInstanceUID)
  454. {
  455. Q_D(ctkDICOMDatabase);
  456. QSqlQuery query(d->Database);
  457. query.prepare ( "SELECT Filename FROM Images WHERE SOPInstanceUID=?");
  458. query.bindValue ( 0, sopInstanceUID );
  459. query.exec();
  460. if (query.next())
  461. {
  462. QString fileName = query.value(0).toString();
  463. this->loadFileHeader(fileName);
  464. }
  465. return;
  466. }
  467. //------------------------------------------------------------------------------
  468. void ctkDICOMDatabase::loadFileHeader (QString fileName)
  469. {
  470. Q_D(ctkDICOMDatabase);
  471. d->LoadedHeader.clear();
  472. DcmFileFormat fileFormat;
  473. OFCondition status = fileFormat.loadFile(fileName.toLatin1().data());
  474. if (status.good())
  475. {
  476. DcmDataset *dataset = fileFormat.getDataset();
  477. DcmStack stack;
  478. while (dataset->nextObject(stack, true) == EC_Normal)
  479. {
  480. DcmObject *dO = stack.top();
  481. if (dO)
  482. {
  483. QString tag = QString("%1,%2").arg(
  484. dO->getGTag(),4,16,QLatin1Char('0')).arg(
  485. dO->getETag(),4,16,QLatin1Char('0'));
  486. std::ostringstream s;
  487. dO->print(s);
  488. d->LoadedHeader[tag] = QString(s.str().c_str());
  489. }
  490. }
  491. }
  492. return;
  493. }
  494. //------------------------------------------------------------------------------
  495. QStringList ctkDICOMDatabase::headerKeys ()
  496. {
  497. Q_D(ctkDICOMDatabase);
  498. return (d->LoadedHeader.keys());
  499. }
  500. //------------------------------------------------------------------------------
  501. QString ctkDICOMDatabase::headerValue (QString key)
  502. {
  503. Q_D(ctkDICOMDatabase);
  504. return (d->LoadedHeader[key]);
  505. }
  506. //
  507. // instanceValue and fileValue methods
  508. //
  509. //------------------------------------------------------------------------------
  510. QString ctkDICOMDatabase::instanceValue(QString sopInstanceUID, QString tag)
  511. {
  512. QString value = this->cachedTag(sopInstanceUID, tag);
  513. if (value != "")
  514. {
  515. return value;
  516. }
  517. unsigned short group, element;
  518. this->tagToGroupElement(tag, group, element);
  519. return( this->instanceValue(sopInstanceUID, group, element) );
  520. }
  521. //------------------------------------------------------------------------------
  522. QString ctkDICOMDatabase::instanceValue(const QString sopInstanceUID, const unsigned short group, const unsigned short element)
  523. {
  524. QString tag = this->groupElementToTag(group,element);
  525. QString value = this->cachedTag(sopInstanceUID, tag);
  526. if (value != "")
  527. {
  528. return value;
  529. }
  530. QString filePath = this->fileForInstance(sopInstanceUID);
  531. if (filePath != "" )
  532. {
  533. value = this->fileValue(filePath, group, element);
  534. return( value );
  535. }
  536. else
  537. {
  538. return ("");
  539. }
  540. }
  541. //------------------------------------------------------------------------------
  542. QString ctkDICOMDatabase::fileValue(const QString fileName, QString tag)
  543. {
  544. unsigned short group, element;
  545. this->tagToGroupElement(tag, group, element);
  546. QString sopInstanceUID = this->instanceForFile(fileName);
  547. QString value = this->cachedTag(sopInstanceUID, tag);
  548. if (value != "")
  549. {
  550. return value;
  551. }
  552. return( this->fileValue(fileName, group, element) );
  553. }
  554. //------------------------------------------------------------------------------
  555. QString ctkDICOMDatabase::fileValue(const QString fileName, const unsigned short group, const unsigned short element)
  556. {
  557. // here is where the real lookup happens
  558. // - first we check the tagCache to see if the value exists for this instance tag
  559. // If not,
  560. // - for now we create a ctkDICOMDataset and extract the value from there
  561. // - then we convert to the appropriate type of string
  562. //
  563. //As an optimization we could consider
  564. // - check if we are currently looking at the dataset for this fileName
  565. // - if so, are we looking for a group/element that is past the last one
  566. // accessed
  567. // -- if so, keep looking for the requested group/element
  568. // -- if not, start again from the begining
  569. QString tag = this->groupElementToTag(group, element);
  570. QString sopInstanceUID = this->instanceForFile(fileName);
  571. QString value = this->cachedTag(sopInstanceUID, tag);
  572. if (value != "")
  573. {
  574. return value;
  575. }
  576. ctkDICOMDataset dataset;
  577. dataset.InitializeFromFile(fileName);
  578. DcmTagKey tagKey(group, element);
  579. value = dataset.GetAllElementValuesAsString(tagKey);
  580. this->cacheTag(sopInstanceUID, tag, value);
  581. return( value );
  582. }
  583. //------------------------------------------------------------------------------
  584. bool ctkDICOMDatabase::tagToGroupElement(const QString tag, unsigned short& group, unsigned short& element)
  585. {
  586. QStringList groupElement = tag.split(",");
  587. bool groupOK, elementOK;
  588. group = groupElement[0].toUInt(&groupOK, 16);
  589. element = groupElement[1].toUInt(&elementOK, 16);
  590. return( groupOK && elementOK );
  591. }
  592. //------------------------------------------------------------------------------
  593. QString ctkDICOMDatabase::groupElementToTag(const unsigned short& group, const unsigned short& element)
  594. {
  595. return QString("%1,%2").arg(group,4,16,QLatin1Char('0')).arg(element,4,16,QLatin1Char('0'));
  596. }
  597. //
  598. // methods related to insert
  599. //
  600. //------------------------------------------------------------------------------
  601. void ctkDICOMDatabase::insert( DcmDataset *dataset, bool storeFile, bool generateThumbnail)
  602. {
  603. if (!dataset)
  604. {
  605. return;
  606. }
  607. ctkDICOMDataset ctkDataset;
  608. ctkDataset.InitializeFromDataset(dataset, false /* do not take ownership */);
  609. this->insert(ctkDataset,storeFile,generateThumbnail);
  610. }
  611. void ctkDICOMDatabase::insert( const ctkDICOMDataset& ctkDataset, bool storeFile, bool generateThumbnail)
  612. {
  613. Q_D(ctkDICOMDatabase);
  614. d->insert(ctkDataset, QString(), storeFile, generateThumbnail);
  615. }
  616. //------------------------------------------------------------------------------
  617. void ctkDICOMDatabase::insert ( const QString& filePath, bool storeFile, bool generateThumbnail, bool createHierarchy, const QString& destinationDirectoryName)
  618. {
  619. Q_D(ctkDICOMDatabase);
  620. Q_UNUSED(createHierarchy);
  621. Q_UNUSED(destinationDirectoryName);
  622. /// first we check if the file is already in the database
  623. if (fileExistsAndUpToDate(filePath))
  624. {
  625. logger.debug( "File " + filePath + " already added.");
  626. return;
  627. }
  628. logger.debug( "Processing " + filePath );
  629. std::string filename = filePath.toStdString();
  630. DcmFileFormat fileformat;
  631. ctkDICOMDataset ctkDataset;
  632. ctkDataset.InitializeFromFile(filePath);
  633. if ( ctkDataset.IsInitialized() )
  634. {
  635. d->insert( ctkDataset, filePath, storeFile, generateThumbnail );
  636. }
  637. else
  638. {
  639. logger.warn(QString("Could not read DICOM file:") + filePath);
  640. }
  641. }
  642. //------------------------------------------------------------------------------
  643. int ctkDICOMDatabasePrivate::insertPatient(const ctkDICOMDataset& ctkDataset)
  644. {
  645. int dbPatientID;
  646. // Check if patient is already present in the db
  647. // TODO: maybe add birthdate check for extra safety
  648. QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) );
  649. QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) );
  650. QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) );
  651. QSqlQuery checkPatientExistsQuery(Database);
  652. checkPatientExistsQuery.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
  653. checkPatientExistsQuery.bindValue ( 0, patientID );
  654. checkPatientExistsQuery.bindValue ( 1, patientsName );
  655. loggedExec(checkPatientExistsQuery);
  656. if (checkPatientExistsQuery.next())
  657. {
  658. // we found him
  659. dbPatientID = checkPatientExistsQuery.value(checkPatientExistsQuery.record().indexOf("UID")).toInt();
  660. qDebug() << "Found patient in the database as UId: " << dbPatientID;
  661. }
  662. else
  663. {
  664. // Insert it
  665. QString patientsBirthTime(ctkDataset.GetElementAsString(DCM_PatientBirthTime) );
  666. QString patientsSex(ctkDataset.GetElementAsString(DCM_PatientSex) );
  667. QString patientsAge(ctkDataset.GetElementAsString(DCM_PatientAge) );
  668. QString patientComments(ctkDataset.GetElementAsString(DCM_PatientComments) );
  669. QSqlQuery insertPatientStatement ( Database );
  670. insertPatientStatement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
  671. insertPatientStatement.bindValue ( 0, patientsName );
  672. insertPatientStatement.bindValue ( 1, patientID );
  673. insertPatientStatement.bindValue ( 2, patientsBirthDate );
  674. insertPatientStatement.bindValue ( 3, patientsBirthTime );
  675. insertPatientStatement.bindValue ( 4, patientsSex );
  676. // TODO: shift patient's age to study,
  677. // since this is not a patient level attribute in images
  678. // insertPatientStatement.bindValue ( 5, patientsAge );
  679. insertPatientStatement.bindValue ( 6, patientComments );
  680. loggedExec(insertPatientStatement);
  681. dbPatientID = insertPatientStatement.lastInsertId().toInt();
  682. logger.debug ( "New patient inserted: " + QString().setNum ( dbPatientID ) );
  683. qDebug() << "New patient inserted as : " << dbPatientID;
  684. }
  685. return dbPatientID;
  686. }
  687. //------------------------------------------------------------------------------
  688. void ctkDICOMDatabasePrivate::insertStudy(const ctkDICOMDataset& ctkDataset, int dbPatientID)
  689. {
  690. QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) );
  691. QSqlQuery checkStudyExistsQuery (Database);
  692. checkStudyExistsQuery.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
  693. checkStudyExistsQuery.bindValue ( 0, studyInstanceUID );
  694. checkStudyExistsQuery.exec();
  695. if(!checkStudyExistsQuery.next())
  696. {
  697. qDebug() << "Need to insert new study: " << studyInstanceUID;
  698. QString studyID(ctkDataset.GetElementAsString(DCM_StudyID) );
  699. QString studyDate(ctkDataset.GetElementAsString(DCM_StudyDate) );
  700. QString studyTime(ctkDataset.GetElementAsString(DCM_StudyTime) );
  701. QString accessionNumber(ctkDataset.GetElementAsString(DCM_AccessionNumber) );
  702. QString modalitiesInStudy(ctkDataset.GetElementAsString(DCM_ModalitiesInStudy) );
  703. QString institutionName(ctkDataset.GetElementAsString(DCM_InstitutionName) );
  704. QString performingPhysiciansName(ctkDataset.GetElementAsString(DCM_PerformingPhysicianName) );
  705. QString referringPhysician(ctkDataset.GetElementAsString(DCM_ReferringPhysicianName) );
  706. QString studyDescription(ctkDataset.GetElementAsString(DCM_StudyDescription) );
  707. QSqlQuery insertStudyStatement ( Database );
  708. insertStudyStatement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  709. insertStudyStatement.bindValue ( 0, studyInstanceUID );
  710. insertStudyStatement.bindValue ( 1, dbPatientID );
  711. insertStudyStatement.bindValue ( 2, studyID );
  712. insertStudyStatement.bindValue ( 3, QDate::fromString ( studyDate, "yyyyMMdd" ) );
  713. insertStudyStatement.bindValue ( 4, studyTime );
  714. insertStudyStatement.bindValue ( 5, accessionNumber );
  715. insertStudyStatement.bindValue ( 6, modalitiesInStudy );
  716. insertStudyStatement.bindValue ( 7, institutionName );
  717. insertStudyStatement.bindValue ( 8, referringPhysician );
  718. insertStudyStatement.bindValue ( 9, performingPhysiciansName );
  719. insertStudyStatement.bindValue ( 10, studyDescription );
  720. if ( !insertStudyStatement.exec() )
  721. {
  722. logger.error ( "Error executing statament: " + insertStudyStatement.lastQuery() + " Error: " + insertStudyStatement.lastError().text() );
  723. }
  724. else
  725. {
  726. LastStudyInstanceUID = studyInstanceUID;
  727. }
  728. }
  729. else
  730. {
  731. qDebug() << "Used existing study: " << studyInstanceUID;
  732. }
  733. }
  734. //------------------------------------------------------------------------------
  735. void ctkDICOMDatabasePrivate::insertSeries(const ctkDICOMDataset& ctkDataset, QString studyInstanceUID)
  736. {
  737. QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  738. QSqlQuery checkSeriesExistsQuery (Database);
  739. checkSeriesExistsQuery.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
  740. checkSeriesExistsQuery.bindValue ( 0, seriesInstanceUID );
  741. logger.warn ( "Statement: " + checkSeriesExistsQuery.lastQuery() );
  742. loggedExec(checkSeriesExistsQuery);
  743. if(!checkSeriesExistsQuery.next())
  744. {
  745. qDebug() << "Need to insert new series: " << seriesInstanceUID;
  746. QString seriesDate(ctkDataset.GetElementAsString(DCM_SeriesDate) );
  747. QString seriesTime(ctkDataset.GetElementAsString(DCM_SeriesTime) );
  748. QString seriesDescription(ctkDataset.GetElementAsString(DCM_SeriesDescription) );
  749. QString modality(ctkDataset.GetElementAsString(DCM_Modality) );
  750. QString bodyPartExamined(ctkDataset.GetElementAsString(DCM_BodyPartExamined) );
  751. QString frameOfReferenceUID(ctkDataset.GetElementAsString(DCM_FrameOfReferenceUID) );
  752. QString contrastAgent(ctkDataset.GetElementAsString(DCM_ContrastBolusAgent) );
  753. QString scanningSequence(ctkDataset.GetElementAsString(DCM_ScanningSequence) );
  754. long seriesNumber(ctkDataset.GetElementAsInteger(DCM_SeriesNumber) );
  755. long acquisitionNumber(ctkDataset.GetElementAsInteger(DCM_AcquisitionNumber) );
  756. long echoNumber(ctkDataset.GetElementAsInteger(DCM_EchoNumbers) );
  757. long temporalPosition(ctkDataset.GetElementAsInteger(DCM_TemporalPositionIdentifier) );
  758. QSqlQuery insertSeriesStatement ( Database );
  759. insertSeriesStatement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'Modality', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  760. insertSeriesStatement.bindValue ( 0, seriesInstanceUID );
  761. insertSeriesStatement.bindValue ( 1, studyInstanceUID );
  762. insertSeriesStatement.bindValue ( 2, static_cast<int>(seriesNumber) );
  763. insertSeriesStatement.bindValue ( 3, seriesDate );
  764. insertSeriesStatement.bindValue ( 4, QDate::fromString ( seriesTime, "yyyyMMdd" ) );
  765. insertSeriesStatement.bindValue ( 5, seriesDescription );
  766. insertSeriesStatement.bindValue ( 6, modality );
  767. insertSeriesStatement.bindValue ( 7, bodyPartExamined );
  768. insertSeriesStatement.bindValue ( 8, frameOfReferenceUID );
  769. insertSeriesStatement.bindValue ( 9, static_cast<int>(acquisitionNumber) );
  770. insertSeriesStatement.bindValue ( 10, contrastAgent );
  771. insertSeriesStatement.bindValue ( 11, scanningSequence );
  772. insertSeriesStatement.bindValue ( 12, static_cast<int>(echoNumber) );
  773. insertSeriesStatement.bindValue ( 13, static_cast<int>(temporalPosition) );
  774. if ( !insertSeriesStatement.exec() )
  775. {
  776. logger.error ( "Error executing statament: "
  777. + insertSeriesStatement.lastQuery()
  778. + " Error: " + insertSeriesStatement.lastError().text() );
  779. LastSeriesInstanceUID = "";
  780. }
  781. else
  782. {
  783. LastSeriesInstanceUID = seriesInstanceUID;
  784. }
  785. }
  786. else
  787. {
  788. qDebug() << "Used existing series: " << seriesInstanceUID;
  789. }
  790. }
  791. //------------------------------------------------------------------------------
  792. void ctkDICOMDatabasePrivate::insert( const ctkDICOMDataset& ctkDataset, const QString& filePath, bool storeFile, bool generateThumbnail)
  793. {
  794. Q_Q(ctkDICOMDatabase);
  795. QMutexLocker lock(&insertMutex);
  796. // Check to see if the file has already been loaded
  797. // TODO:
  798. // It could make sense to actually remove the dataset and re-add it. This needs the remove
  799. // method we still have to write.
  800. //
  801. QString sopInstanceUID ( ctkDataset.GetElementAsString(DCM_SOPInstanceUID) );
  802. QSqlQuery fileExists ( Database );
  803. fileExists.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == :sopInstanceUID");
  804. fileExists.bindValue(":sopInstanceUID",sopInstanceUID);
  805. bool success = fileExists.exec();
  806. if (!success)
  807. {
  808. logger.error("SQLITE ERROR: " + fileExists.lastError().driverText());
  809. return;
  810. }
  811. QString databaseFilename(fileExists.value(1).toString());
  812. QDateTime fileLastModified(QFileInfo(databaseFilename).lastModified());
  813. QDateTime databaseInsertTimestamp(QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate));
  814. qDebug() << "inserting filePath: " << filePath;
  815. if (databaseFilename == "")
  816. {
  817. qDebug() << "database filename for " << sopInstanceUID << " is empty - we should insert on top of it";
  818. }
  819. else
  820. {
  821. qDebug() << "database filename for " << sopInstanceUID << " is: " << databaseFilename;
  822. qDebug() << "modified date is: " << fileLastModified;
  823. qDebug() << "db insert date is: " << databaseInsertTimestamp;
  824. if ( fileExists.next() && fileLastModified < databaseInsertTimestamp )
  825. {
  826. logger.debug ( "File " + databaseFilename + " already added" );
  827. return;
  828. }
  829. }
  830. //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  831. QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) );
  832. QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) );
  833. QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  834. QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) );
  835. if ( patientsName.isEmpty() && !patientID.isEmpty() )
  836. { // Use patient id as name if name is empty - can happen on anonymized datasets
  837. // see: http://www.na-mic.org/Bug/view.php?id=1643
  838. patientsName = patientID;
  839. }
  840. if ( patientsName.isEmpty() || studyInstanceUID.isEmpty() || patientID.isEmpty() )
  841. {
  842. logger.error("Dataset is missing necessary information!");
  843. return;
  844. }
  845. // store the file if the database is not in memomry
  846. // TODO: if we are called from insert(file) we
  847. // have to do something else
  848. //
  849. QString filename = filePath;
  850. if ( storeFile && !q->isInMemory() && !seriesInstanceUID.isEmpty() )
  851. {
  852. // QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
  853. QString destinationDirectoryName = q->databaseDirectory() + "/dicom/";
  854. QDir destinationDir(destinationDirectoryName);
  855. filename = destinationDirectoryName +
  856. studyInstanceUID + "/" +
  857. seriesInstanceUID + "/" +
  858. sopInstanceUID;
  859. destinationDir.mkpath(studyInstanceUID + "/" +
  860. seriesInstanceUID);
  861. if(filePath.isEmpty())
  862. {
  863. logger.debug ( "Saving file: " + filename );
  864. if ( !ctkDataset.SaveToFile( filename) )
  865. {
  866. logger.error ( "Error saving file: " + filename );
  867. return;
  868. }
  869. }
  870. else
  871. {
  872. // we're inserting an existing file
  873. QFile currentFile( filePath );
  874. currentFile.copy(filename);
  875. logger.debug( "Copy file from: " + filePath );
  876. logger.debug( "Copy file to : " + filename );
  877. }
  878. }
  879. //The dbPatientID is a unique number within the database,
  880. //generated by the sqlite autoincrement
  881. //The patientID is the (non-unique) DICOM patient id
  882. int dbPatientID = LastPatientUID;
  883. if ( patientID != "" && patientsName != "" )
  884. {
  885. //Speed up: Check if patient is the same as in last file;
  886. // very probable, as all images belonging to a study have the same patient
  887. QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) );
  888. if ( LastPatientID != patientID
  889. || LastPatientsBirthDate != patientsBirthDate
  890. || LastPatientsName != patientsName )
  891. { QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  892. qDebug() << "This looks like a different patient from last insert: " << patientID;
  893. // Ok, something is different from last insert, let's insert him if he's not
  894. // already in the db.
  895. dbPatientID = insertPatient( ctkDataset );
  896. /// keep this for the next image
  897. LastPatientUID = dbPatientID;
  898. LastPatientID = patientID;
  899. LastPatientsBirthDate = patientsBirthDate;
  900. LastPatientsName = patientsName;
  901. }
  902. qDebug() << "Going to insert this instance with dbPatientID: " << dbPatientID;
  903. // Patient is in now. Let's continue with the study
  904. if ( studyInstanceUID != "" && LastStudyInstanceUID != studyInstanceUID )
  905. {
  906. insertStudy(ctkDataset,dbPatientID);
  907. }
  908. if ( seriesInstanceUID != "" && seriesInstanceUID != LastSeriesInstanceUID )
  909. {
  910. insertSeries(ctkDataset, studyInstanceUID);
  911. }
  912. // TODO: what to do with imported files
  913. //
  914. if ( !filename.isEmpty() && !seriesInstanceUID.isEmpty() )
  915. {
  916. QSqlQuery checkImageExistsQuery (Database);
  917. checkImageExistsQuery.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
  918. checkImageExistsQuery.bindValue ( 0, filename );
  919. checkImageExistsQuery.exec();
  920. if(!checkImageExistsQuery.next())
  921. {
  922. QSqlQuery insertImageStatement ( Database );
  923. insertImageStatement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" );
  924. insertImageStatement.bindValue ( 0, sopInstanceUID );
  925. insertImageStatement.bindValue ( 1, filename );
  926. insertImageStatement.bindValue ( 2, seriesInstanceUID );
  927. insertImageStatement.bindValue ( 3, QDateTime::currentDateTime() );
  928. insertImageStatement.exec();
  929. }
  930. }
  931. if( generateThumbnail && thumbnailGenerator && !seriesInstanceUID.isEmpty() )
  932. {
  933. QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
  934. //Create thumbnail here
  935. QString thumbnailPath = q->databaseDirectory() +
  936. "/thumbs/" + studyInstanceUID + "/" + seriesInstanceUID
  937. + "/" + sopInstanceUID + ".png";
  938. QFileInfo thumbnailInfo(thumbnailPath);
  939. if( !(thumbnailInfo.exists()
  940. && (thumbnailInfo.lastModified() > QFileInfo(filename).lastModified())))
  941. {
  942. QDir(q->databaseDirectory() + "/thumbs/").mkpath(studySeriesDirectory);
  943. DicomImage dcmImage(QDir::toNativeSeparators(filename).toAscii());
  944. thumbnailGenerator->generateThumbnail(&dcmImage, thumbnailPath);
  945. }
  946. }
  947. if (q->isInMemory())
  948. {
  949. emit q->databaseChanged();
  950. }
  951. }
  952. else
  953. {
  954. qDebug() << "No patient name or no patient id - not inserting!";
  955. }
  956. }
  957. //------------------------------------------------------------------------------
  958. bool ctkDICOMDatabase::fileExistsAndUpToDate(const QString& filePath)
  959. {
  960. Q_D(ctkDICOMDatabase);
  961. bool result(false);
  962. QSqlQuery check_filename_query(database());
  963. check_filename_query.prepare("SELECT InsertTimestamp FROM Images WHERE Filename == ?");
  964. check_filename_query.bindValue(0,filePath);
  965. d->loggedExec(check_filename_query);
  966. if (
  967. check_filename_query.next() &&
  968. QFileInfo(filePath).lastModified() < QDateTime::fromString(check_filename_query.value(0).toString(),Qt::ISODate)
  969. )
  970. {
  971. result = true;
  972. }
  973. check_filename_query.finish();
  974. return result;
  975. }
  976. //------------------------------------------------------------------------------
  977. bool ctkDICOMDatabase::isOpen() const
  978. {
  979. Q_D(const ctkDICOMDatabase);
  980. return d->Database.isOpen();
  981. }
  982. //------------------------------------------------------------------------------
  983. bool ctkDICOMDatabase::isInMemory() const
  984. {
  985. Q_D(const ctkDICOMDatabase);
  986. return d->DatabaseFileName == ":memory:";
  987. }
  988. //------------------------------------------------------------------------------
  989. bool ctkDICOMDatabase::removeSeries(const QString& seriesInstanceUID)
  990. {
  991. Q_D(ctkDICOMDatabase);
  992. // get all images from series
  993. QSqlQuery fileExists ( d->Database );
  994. fileExists.prepare("SELECT Filename, SOPInstanceUID, StudyInstanceUID FROM Images,Series WHERE Series.SeriesInstanceUID = Images.SeriesInstanceUID AND Images.SeriesInstanceUID = :seriesID");
  995. fileExists.bindValue(":seriesID",seriesInstanceUID);
  996. bool success = fileExists.exec();
  997. if (!success)
  998. {
  999. logger.error("SQLITE ERROR: " + fileExists.lastError().driverText());
  1000. return false;
  1001. }
  1002. QList< QPair<QString,QString> > removeList;
  1003. while ( fileExists.next() )
  1004. {
  1005. QString dbFilePath = fileExists.value(fileExists.record().indexOf("Filename")).toString();
  1006. QString sopInstanceUID = fileExists.value(fileExists.record().indexOf("SOPInstanceUID")).toString();
  1007. QString studyInstanceUID = fileExists.value(fileExists.record().indexOf("StudyInstanceUID")).toString();
  1008. QString internalFilePath = studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID;
  1009. removeList << qMakePair(dbFilePath,internalFilePath);
  1010. }
  1011. QSqlQuery fileRemove ( d->Database );
  1012. fileRemove.prepare("DELETE FROM Images WHERE SeriesInstanceUID == :seriesID");
  1013. fileRemove.bindValue(":seriesID",seriesInstanceUID);
  1014. logger.debug("SQLITE: removing seriesInstanceUID " + seriesInstanceUID);
  1015. success = fileRemove.exec();
  1016. if (!success)
  1017. {
  1018. logger.error("SQLITE ERROR: could not remove seriesInstanceUID " + seriesInstanceUID);
  1019. logger.error("SQLITE ERROR: " + fileRemove.lastError().driverText());
  1020. }
  1021. QPair<QString,QString> fileToRemove;
  1022. foreach (fileToRemove, removeList)
  1023. {
  1024. QString dbFilePath = fileToRemove.first;
  1025. QString thumbnailToRemove = databaseDirectory() + "/thumbs/" + fileToRemove.second + ".png";
  1026. // check that the file is below our internal storage
  1027. if (dbFilePath.startsWith( databaseDirectory() + "/dicom/"))
  1028. {
  1029. if (!dbFilePath.endsWith(fileToRemove.second))
  1030. {
  1031. logger.error("Database inconsistency detected during delete!");
  1032. continue;
  1033. }
  1034. if (QFile( dbFilePath ).remove())
  1035. {
  1036. logger.debug("Removed file " + dbFilePath );
  1037. }
  1038. else
  1039. {
  1040. logger.warn("Failed to remove file " + dbFilePath );
  1041. }
  1042. }
  1043. if (QFile( thumbnailToRemove ).remove())
  1044. {
  1045. logger.debug("Removed thumbnail " + thumbnailToRemove);
  1046. }
  1047. else
  1048. {
  1049. logger.warn("Failed to remove thumbnail " + thumbnailToRemove);
  1050. }
  1051. }
  1052. this->cleanup();
  1053. d->LastSeriesInstanceUID = "";
  1054. return true;
  1055. }
  1056. //------------------------------------------------------------------------------
  1057. bool ctkDICOMDatabase::cleanup()
  1058. {
  1059. Q_D(ctkDICOMDatabase);
  1060. QSqlQuery seriesCleanup ( d->Database );
  1061. seriesCleanup.exec("DELETE FROM Series WHERE ( SELECT COUNT(*) FROM Images WHERE Images.SeriesInstanceUID = Series.SeriesInstanceUID ) = 0;");
  1062. seriesCleanup.exec("DELETE FROM Studies WHERE ( SELECT COUNT(*) FROM Series WHERE Series.StudyInstanceUID = Studies.StudyInstanceUID ) = 0;");
  1063. seriesCleanup.exec("DELETE FROM Patients WHERE ( SELECT COUNT(*) FROM Studies WHERE Studies.PatientsUID = Patients.UID ) = 0;");
  1064. return true;
  1065. }
  1066. //------------------------------------------------------------------------------
  1067. bool ctkDICOMDatabase::removeStudy(const QString& studyInstanceUID)
  1068. {
  1069. Q_D(ctkDICOMDatabase);
  1070. QSqlQuery seriesForStudy( d->Database );
  1071. seriesForStudy.prepare("SELECT SeriesInstanceUID FROM Series WHERE StudyInstanceUID = :studyID");
  1072. seriesForStudy.bindValue(":studyID", studyInstanceUID);
  1073. bool success = seriesForStudy.exec();
  1074. if (!success)
  1075. {
  1076. logger.error("SQLITE ERROR: " + seriesForStudy.lastError().driverText());
  1077. return false;
  1078. }
  1079. bool result = true;
  1080. while ( seriesForStudy.next() )
  1081. {
  1082. QString seriesInstanceUID = seriesForStudy.value(seriesForStudy.record().indexOf("SeriesInstanceUID")).toString();
  1083. if ( ! this->removeSeries(seriesInstanceUID) )
  1084. {
  1085. result = false;
  1086. }
  1087. }
  1088. d->LastStudyInstanceUID = "";
  1089. return result;
  1090. }
  1091. //------------------------------------------------------------------------------
  1092. bool ctkDICOMDatabase::removePatient(const QString& patientID)
  1093. {
  1094. Q_D(ctkDICOMDatabase);
  1095. QSqlQuery studiesForPatient( d->Database );
  1096. studiesForPatient.prepare("SELECT StudyInstanceUID FROM Studies WHERE PatientsUID = :patientsID");
  1097. studiesForPatient.bindValue(":patientsID", patientID);
  1098. bool success = studiesForPatient.exec();
  1099. if (!success)
  1100. {
  1101. logger.error("SQLITE ERROR: " + studiesForPatient.lastError().driverText());
  1102. return false;
  1103. }
  1104. bool result = true;
  1105. while ( studiesForPatient.next() )
  1106. {
  1107. QString studyInstanceUID = studiesForPatient.value(studiesForPatient.record().indexOf("StudyInstanceUID")).toString();
  1108. if ( ! this->removeStudy(studyInstanceUID) )
  1109. {
  1110. result = false;
  1111. }
  1112. }
  1113. d->LastPatientID = "";
  1114. d->LastPatientsName = "";
  1115. d->LastPatientsBirthDate = "";
  1116. d->LastPatientUID = -1;
  1117. return result;
  1118. }
  1119. ///
  1120. /// Code related to the tagCache
  1121. ///
  1122. //------------------------------------------------------------------------------
  1123. bool ctkDICOMDatabase::tagCacheExists()
  1124. {
  1125. Q_D(ctkDICOMDatabase);
  1126. if (d->TagCacheVerified)
  1127. {
  1128. return true;
  1129. }
  1130. // try to open the database if it's not already open
  1131. if ( !(d->TagCacheDatabase.isOpen()) )
  1132. {
  1133. qDebug() << "TagCacheDatabase not open\n";
  1134. d->TagCacheDatabase = QSqlDatabase::addDatabase("QSQLITE", "TagCache");
  1135. d->TagCacheDatabase.setDatabaseName(d->TagCacheDatabaseFilename);
  1136. if ( !(d->TagCacheDatabase.open()) )
  1137. {
  1138. qDebug() << "TagCacheDatabase would not open!\n";
  1139. qDebug() << "TagCacheDatabaseFilename is: " << d->TagCacheDatabaseFilename << "\n";
  1140. return false;
  1141. }
  1142. }
  1143. // check that the table exists
  1144. QSqlQuery cacheExists( d->TagCacheDatabase );
  1145. cacheExists.prepare("SELECT * FROM TagCache LIMIT 1");
  1146. bool success = d->loggedExec(cacheExists);
  1147. if (success)
  1148. {
  1149. qDebug() << "TagCacheDatabase verified!\n";
  1150. d->TagCacheVerified = true;
  1151. return true;
  1152. }
  1153. qDebug() << "TagCacheDatabase NOT verified based on table check!\n";
  1154. return false;
  1155. }
  1156. //------------------------------------------------------------------------------
  1157. bool ctkDICOMDatabase::initializeTagCache()
  1158. {
  1159. Q_D(ctkDICOMDatabase);
  1160. // First, drop any existing table
  1161. if ( this->tagCacheExists() )
  1162. {
  1163. qDebug() << "TagCacheDatabase drop existing table\n";
  1164. QSqlQuery dropCacheTable( d->TagCacheDatabase );
  1165. dropCacheTable.prepare( "DROP TABLE TagCache" );
  1166. d->loggedExec(dropCacheTable);
  1167. }
  1168. // now create a table
  1169. qDebug() << "TagCacheDatabase adding table\n";
  1170. QSqlQuery createCacheTable( d->TagCacheDatabase );
  1171. createCacheTable.prepare(
  1172. "CREATE TABLE TagCache (SOPInstanceUID, Tag, Value, PRIMARY KEY (SOPInstanceUID, Tag))" );
  1173. bool success = d->loggedExec(createCacheTable);
  1174. if (success)
  1175. {
  1176. d->TagCacheVerified = true;
  1177. return true;
  1178. }
  1179. return false;
  1180. }
  1181. //------------------------------------------------------------------------------
  1182. QString ctkDICOMDatabase::cachedTag(const QString sopInstanceUID, const QString tag)
  1183. {
  1184. Q_D(ctkDICOMDatabase);
  1185. if ( !this->tagCacheExists() )
  1186. {
  1187. if ( !this->initializeTagCache() )
  1188. {
  1189. return( "" );
  1190. }
  1191. }
  1192. QSqlQuery selectValue( d->TagCacheDatabase );
  1193. selectValue.prepare( "SELECT Value FROM TagCache WHERE SOPInstanceUID = :sopInstanceUID AND Tag = :tag" );
  1194. selectValue.bindValue(":sopInstanceUID",sopInstanceUID);
  1195. selectValue.bindValue(":tag",tag);
  1196. d->loggedExec(selectValue);
  1197. QString result("");
  1198. if (selectValue.next())
  1199. {
  1200. result = selectValue.value(0).toString();
  1201. }
  1202. return( result );
  1203. }
  1204. //------------------------------------------------------------------------------
  1205. bool ctkDICOMDatabase::cacheTag(const QString sopInstanceUID, const QString tag, const QString value)
  1206. {
  1207. Q_D(ctkDICOMDatabase);
  1208. if ( !this->tagCacheExists() )
  1209. {
  1210. if ( !this->initializeTagCache() )
  1211. {
  1212. return false;
  1213. }
  1214. }
  1215. QSqlQuery insertTag( d->TagCacheDatabase );
  1216. insertTag.prepare( "INSERT OR REPLACE INTO TagCache VALUES(:sopInstanceUID, :tag, :value)" );
  1217. insertTag.bindValue(":sopInstanceUID",sopInstanceUID);
  1218. insertTag.bindValue(":tag",tag);
  1219. insertTag.bindValue(":value",value);
  1220. return d->loggedExec(insertTag);
  1221. }