ctkDICOMDatabase.cpp 61 KB

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