ctkDICOMDatabase.cpp 53 KB

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