ctkDICOMDatabase.cpp 60 KB

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