ctkDICOMDatabase.cpp 53 KB

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