ctkDICOMDatabase.cpp 61 KB

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