ctkDICOMDatabase.cpp 54 KB

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