ctkDICOMDatabase.cpp 49 KB

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