ctkDICOMDatabase.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  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. logger.debug("Register compression libraries");
  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. QStringList ctkDICOMDatabase::seriesForStudy(QString studyUID)
  568. {
  569. Q_D(ctkDICOMDatabase);
  570. QSqlQuery query(d->Database);
  571. query.prepare ( "SELECT SeriesInstanceUID FROM Series WHERE StudyInstanceUID=?");
  572. query.bindValue ( 0, studyUID );
  573. query.exec();
  574. QStringList result;
  575. while (query.next())
  576. {
  577. result << query.value(0).toString();
  578. }
  579. return( result );
  580. }
  581. //------------------------------------------------------------------------------
  582. QStringList ctkDICOMDatabase::filesForSeries(QString seriesUID)
  583. {
  584. Q_D(ctkDICOMDatabase);
  585. QSqlQuery query(d->Database);
  586. query.prepare ( "SELECT Filename FROM Images WHERE SeriesInstanceUID=?");
  587. query.bindValue ( 0, seriesUID );
  588. query.exec();
  589. QStringList result;
  590. while (query.next())
  591. {
  592. result << query.value(0).toString();
  593. }
  594. return( result );
  595. }
  596. //------------------------------------------------------------------------------
  597. QString ctkDICOMDatabase::fileForInstance(QString sopInstanceUID)
  598. {
  599. Q_D(ctkDICOMDatabase);
  600. QSqlQuery query(d->Database);
  601. query.prepare ( "SELECT Filename FROM Images WHERE SOPInstanceUID=?");
  602. query.bindValue ( 0, sopInstanceUID );
  603. query.exec();
  604. QString result;
  605. if (query.next())
  606. {
  607. result = query.value(0).toString();
  608. }
  609. return( result );
  610. }
  611. //------------------------------------------------------------------------------
  612. QString ctkDICOMDatabase::seriesForFile(QString fileName)
  613. {
  614. Q_D(ctkDICOMDatabase);
  615. QSqlQuery query(d->Database);
  616. query.prepare ( "SELECT SeriesInstanceUID FROM Images WHERE Filename=?");
  617. query.bindValue ( 0, fileName );
  618. query.exec();
  619. QString result;
  620. if (query.next())
  621. {
  622. result = query.value(0).toString();
  623. }
  624. return( result );
  625. }
  626. //------------------------------------------------------------------------------
  627. QString ctkDICOMDatabase::instanceForFile(QString fileName)
  628. {
  629. Q_D(ctkDICOMDatabase);
  630. QSqlQuery query(d->Database);
  631. query.prepare ( "SELECT SOPInstanceUID FROM Images WHERE Filename=?");
  632. query.bindValue ( 0, fileName );
  633. query.exec();
  634. QString result;
  635. if (query.next())
  636. {
  637. result = query.value(0).toString();
  638. }
  639. return( result );
  640. }
  641. //------------------------------------------------------------------------------
  642. QDateTime ctkDICOMDatabase::insertDateTimeForInstance(QString sopInstanceUID)
  643. {
  644. Q_D(ctkDICOMDatabase);
  645. QSqlQuery query(d->Database);
  646. query.prepare ( "SELECT InsertTimestamp FROM Images WHERE SOPInstanceUID=?");
  647. query.bindValue ( 0, sopInstanceUID );
  648. query.exec();
  649. QDateTime result;
  650. if (query.next())
  651. {
  652. result = QDateTime::fromString(query.value(0).toString(), Qt::ISODate);
  653. }
  654. return( result );
  655. }
  656. //
  657. // instance header methods
  658. //
  659. //------------------------------------------------------------------------------
  660. QStringList ctkDICOMDatabase::allFiles()
  661. {
  662. Q_D(ctkDICOMDatabase);
  663. return d->filenames("Images");
  664. }
  665. //------------------------------------------------------------------------------
  666. void ctkDICOMDatabase::loadInstanceHeader (QString sopInstanceUID)
  667. {
  668. Q_D(ctkDICOMDatabase);
  669. QSqlQuery query(d->Database);
  670. query.prepare ( "SELECT Filename FROM Images WHERE SOPInstanceUID=?");
  671. query.bindValue ( 0, sopInstanceUID );
  672. query.exec();
  673. if (query.next())
  674. {
  675. QString fileName = query.value(0).toString();
  676. this->loadFileHeader(fileName);
  677. }
  678. return;
  679. }
  680. //------------------------------------------------------------------------------
  681. void ctkDICOMDatabase::loadFileHeader (QString fileName)
  682. {
  683. Q_D(ctkDICOMDatabase);
  684. d->LoadedHeader.clear();
  685. DcmFileFormat fileFormat;
  686. OFCondition status = fileFormat.loadFile(fileName.toLatin1().data());
  687. if (status.good())
  688. {
  689. DcmDataset *dataset = fileFormat.getDataset();
  690. DcmStack stack;
  691. while (dataset->nextObject(stack, true) == EC_Normal)
  692. {
  693. DcmObject *dO = stack.top();
  694. if (dO)
  695. {
  696. QString tag = QString("%1,%2").arg(
  697. dO->getGTag(),4,16,QLatin1Char('0')).arg(
  698. dO->getETag(),4,16,QLatin1Char('0'));
  699. std::ostringstream s;
  700. dO->print(s);
  701. d->LoadedHeader[tag] = QString(s.str().c_str());
  702. }
  703. }
  704. }
  705. return;
  706. }
  707. //------------------------------------------------------------------------------
  708. QStringList ctkDICOMDatabase::headerKeys ()
  709. {
  710. Q_D(ctkDICOMDatabase);
  711. return (d->LoadedHeader.keys());
  712. }
  713. //------------------------------------------------------------------------------
  714. QString ctkDICOMDatabase::headerValue (QString key)
  715. {
  716. Q_D(ctkDICOMDatabase);
  717. return (d->LoadedHeader[key]);
  718. }
  719. //
  720. // instanceValue and fileValue methods
  721. //
  722. //------------------------------------------------------------------------------
  723. QString ctkDICOMDatabase::instanceValue(QString sopInstanceUID, QString tag)
  724. {
  725. QString value = this->cachedTag(sopInstanceUID, tag);
  726. if (value == TagNotInInstance || value == ValueIsEmptyString)
  727. {
  728. return "";
  729. }
  730. if (value != "")
  731. {
  732. return value;
  733. }
  734. unsigned short group, element;
  735. this->tagToGroupElement(tag, group, element);
  736. return( this->instanceValue(sopInstanceUID, group, element) );
  737. }
  738. //------------------------------------------------------------------------------
  739. QString ctkDICOMDatabase::instanceValue(const QString sopInstanceUID, const unsigned short group, const unsigned short element)
  740. {
  741. QString tag = this->groupElementToTag(group,element);
  742. QString value = this->cachedTag(sopInstanceUID, tag);
  743. if (value == TagNotInInstance || value == ValueIsEmptyString)
  744. {
  745. return "";
  746. }
  747. if (value != "")
  748. {
  749. return value;
  750. }
  751. QString filePath = this->fileForInstance(sopInstanceUID);
  752. if (filePath != "" )
  753. {
  754. value = this->fileValue(filePath, group, element);
  755. return( value );
  756. }
  757. else
  758. {
  759. return ("");
  760. }
  761. }
  762. //------------------------------------------------------------------------------
  763. QString ctkDICOMDatabase::fileValue(const QString fileName, QString tag)
  764. {
  765. unsigned short group, element;
  766. this->tagToGroupElement(tag, group, element);
  767. QString sopInstanceUID = this->instanceForFile(fileName);
  768. QString value = this->cachedTag(sopInstanceUID, tag);
  769. if (value == TagNotInInstance || value == ValueIsEmptyString)
  770. {
  771. return "";
  772. }
  773. if (value != "")
  774. {
  775. return value;
  776. }
  777. return( this->fileValue(fileName, group, element) );
  778. }
  779. //------------------------------------------------------------------------------
  780. QString ctkDICOMDatabase::fileValue(const QString fileName, const unsigned short group, const unsigned short element)
  781. {
  782. // here is where the real lookup happens
  783. // - first we check the tagCache to see if the value exists for this instance tag
  784. // If not,
  785. // - for now we create a ctkDICOMItem and extract the value from there
  786. // - then we convert to the appropriate type of string
  787. //
  788. //As an optimization we could consider
  789. // - check if we are currently looking at the dataset for this fileName
  790. // - if so, are we looking for a group/element that is past the last one
  791. // accessed
  792. // -- if so, keep looking for the requested group/element
  793. // -- if not, start again from the begining
  794. QString tag = this->groupElementToTag(group, element);
  795. QString sopInstanceUID = this->instanceForFile(fileName);
  796. QString value = this->cachedTag(sopInstanceUID, tag);
  797. if (value == TagNotInInstance || value == ValueIsEmptyString)
  798. {
  799. return "";
  800. }
  801. if (value != "")
  802. {
  803. return value;
  804. }
  805. ctkDICOMItem dataset;
  806. dataset.InitializeFromFile(fileName);
  807. DcmTagKey tagKey(group, element);
  808. value = dataset.GetAllElementValuesAsString(tagKey);
  809. this->cacheTag(sopInstanceUID, tag, value);
  810. return( value );
  811. }
  812. //------------------------------------------------------------------------------
  813. bool ctkDICOMDatabase::tagToGroupElement(const QString tag, unsigned short& group, unsigned short& element)
  814. {
  815. QStringList groupElement = tag.split(",");
  816. bool groupOK, elementOK;
  817. if (groupElement.length() != 2)
  818. {
  819. return false;
  820. }
  821. group = groupElement[0].toUInt(&groupOK, 16);
  822. element = groupElement[1].toUInt(&elementOK, 16);
  823. return( groupOK && elementOK );
  824. }
  825. //------------------------------------------------------------------------------
  826. QString ctkDICOMDatabase::groupElementToTag(const unsigned short& group, const unsigned short& element)
  827. {
  828. return QString("%1,%2").arg(group,4,16,QLatin1Char('0')).arg(element,4,16,QLatin1Char('0'));
  829. }
  830. //
  831. // methods related to insert
  832. //
  833. //------------------------------------------------------------------------------
  834. void ctkDICOMDatabase::insert( DcmItem *item, bool storeFile, bool generateThumbnail)
  835. {
  836. if (!item)
  837. {
  838. return;
  839. }
  840. ctkDICOMItem ctkDataset;
  841. ctkDataset.InitializeFromItem(item, false /* do not take ownership */);
  842. this->insert(ctkDataset,storeFile,generateThumbnail);
  843. }
  844. void ctkDICOMDatabase::insert( const ctkDICOMItem& ctkDataset, bool storeFile, bool generateThumbnail)
  845. {
  846. Q_D(ctkDICOMDatabase);
  847. d->insert(ctkDataset, QString(), storeFile, generateThumbnail);
  848. }
  849. //------------------------------------------------------------------------------
  850. void ctkDICOMDatabase::insert ( const QString& filePath, bool storeFile, bool generateThumbnail, bool createHierarchy, const QString& destinationDirectoryName)
  851. {
  852. Q_D(ctkDICOMDatabase);
  853. Q_UNUSED(createHierarchy);
  854. Q_UNUSED(destinationDirectoryName);
  855. /// first we check if the file is already in the database
  856. if (fileExistsAndUpToDate(filePath))
  857. {
  858. logger.debug( "File " + filePath + " already added.");
  859. return;
  860. }
  861. logger.debug( "Processing " + filePath );
  862. std::string filename = filePath.toStdString();
  863. DcmFileFormat fileformat;
  864. ctkDICOMItem ctkDataset;
  865. ctkDataset.InitializeFromFile(filePath);
  866. if ( ctkDataset.IsInitialized() )
  867. {
  868. d->insert( ctkDataset, filePath, storeFile, generateThumbnail );
  869. }
  870. else
  871. {
  872. logger.warn(QString("Could not read DICOM file:") + filePath);
  873. }
  874. }
  875. //------------------------------------------------------------------------------
  876. int ctkDICOMDatabasePrivate::insertPatient(const ctkDICOMItem& ctkDataset)
  877. {
  878. int dbPatientID;
  879. // Check if patient is already present in the db
  880. // TODO: maybe add birthdate check for extra safety
  881. QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) );
  882. QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) );
  883. QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) );
  884. QSqlQuery checkPatientExistsQuery(Database);
  885. checkPatientExistsQuery.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
  886. checkPatientExistsQuery.bindValue ( 0, patientID );
  887. checkPatientExistsQuery.bindValue ( 1, patientsName );
  888. loggedExec(checkPatientExistsQuery);
  889. if (checkPatientExistsQuery.next())
  890. {
  891. // we found him
  892. dbPatientID = checkPatientExistsQuery.value(checkPatientExistsQuery.record().indexOf("UID")).toInt();
  893. qDebug() << "Found patient in the database as UId: " << dbPatientID;
  894. }
  895. else
  896. {
  897. // Insert it
  898. QString patientsBirthTime(ctkDataset.GetElementAsString(DCM_PatientBirthTime) );
  899. QString patientsSex(ctkDataset.GetElementAsString(DCM_PatientSex) );
  900. QString patientsAge(ctkDataset.GetElementAsString(DCM_PatientAge) );
  901. QString patientComments(ctkDataset.GetElementAsString(DCM_PatientComments) );
  902. QSqlQuery insertPatientStatement ( Database );
  903. insertPatientStatement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
  904. insertPatientStatement.bindValue ( 0, patientsName );
  905. insertPatientStatement.bindValue ( 1, patientID );
  906. insertPatientStatement.bindValue ( 2, QDate::fromString ( patientsBirthDate, "yyyyMMdd" ) );
  907. insertPatientStatement.bindValue ( 3, patientsBirthTime );
  908. insertPatientStatement.bindValue ( 4, patientsSex );
  909. // TODO: shift patient's age to study,
  910. // since this is not a patient level attribute in images
  911. // insertPatientStatement.bindValue ( 5, patientsAge );
  912. insertPatientStatement.bindValue ( 6, patientComments );
  913. loggedExec(insertPatientStatement);
  914. dbPatientID = insertPatientStatement.lastInsertId().toInt();
  915. logger.debug ( "New patient inserted: " + QString().setNum ( dbPatientID ) );
  916. qDebug() << "New patient inserted as : " << dbPatientID;
  917. }
  918. return dbPatientID;
  919. }
  920. //------------------------------------------------------------------------------
  921. void ctkDICOMDatabasePrivate::insertStudy(const ctkDICOMItem& ctkDataset, int dbPatientID)
  922. {
  923. QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) );
  924. QSqlQuery checkStudyExistsQuery (Database);
  925. checkStudyExistsQuery.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
  926. checkStudyExistsQuery.bindValue ( 0, studyInstanceUID );
  927. checkStudyExistsQuery.exec();
  928. if(!checkStudyExistsQuery.next())
  929. {
  930. qDebug() << "Need to insert new study: " << studyInstanceUID;
  931. QString studyID(ctkDataset.GetElementAsString(DCM_StudyID) );
  932. QString studyDate(ctkDataset.GetElementAsString(DCM_StudyDate) );
  933. QString studyTime(ctkDataset.GetElementAsString(DCM_StudyTime) );
  934. QString accessionNumber(ctkDataset.GetElementAsString(DCM_AccessionNumber) );
  935. QString modalitiesInStudy(ctkDataset.GetElementAsString(DCM_ModalitiesInStudy) );
  936. QString institutionName(ctkDataset.GetElementAsString(DCM_InstitutionName) );
  937. QString performingPhysiciansName(ctkDataset.GetElementAsString(DCM_PerformingPhysicianName) );
  938. QString referringPhysician(ctkDataset.GetElementAsString(DCM_ReferringPhysicianName) );
  939. QString studyDescription(ctkDataset.GetElementAsString(DCM_StudyDescription) );
  940. QSqlQuery insertStudyStatement ( Database );
  941. insertStudyStatement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  942. insertStudyStatement.bindValue ( 0, studyInstanceUID );
  943. insertStudyStatement.bindValue ( 1, dbPatientID );
  944. insertStudyStatement.bindValue ( 2, studyID );
  945. insertStudyStatement.bindValue ( 3, QDate::fromString ( studyDate, "yyyyMMdd" ) );
  946. insertStudyStatement.bindValue ( 4, studyTime );
  947. insertStudyStatement.bindValue ( 5, accessionNumber );
  948. insertStudyStatement.bindValue ( 6, modalitiesInStudy );
  949. insertStudyStatement.bindValue ( 7, institutionName );
  950. insertStudyStatement.bindValue ( 8, referringPhysician );
  951. insertStudyStatement.bindValue ( 9, performingPhysiciansName );
  952. insertStudyStatement.bindValue ( 10, studyDescription );
  953. if ( !insertStudyStatement.exec() )
  954. {
  955. logger.error ( "Error executing statament: " + insertStudyStatement.lastQuery() + " Error: " + insertStudyStatement.lastError().text() );
  956. }
  957. else
  958. {
  959. LastStudyInstanceUID = studyInstanceUID;
  960. }
  961. }
  962. else
  963. {
  964. qDebug() << "Used existing study: " << studyInstanceUID;
  965. }
  966. }
  967. //------------------------------------------------------------------------------
  968. void ctkDICOMDatabasePrivate::insertSeries(const ctkDICOMItem& ctkDataset, QString studyInstanceUID)
  969. {
  970. QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  971. QSqlQuery checkSeriesExistsQuery (Database);
  972. checkSeriesExistsQuery.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
  973. checkSeriesExistsQuery.bindValue ( 0, seriesInstanceUID );
  974. logger.warn ( "Statement: " + checkSeriesExistsQuery.lastQuery() );
  975. checkSeriesExistsQuery.exec();
  976. if(!checkSeriesExistsQuery.next())
  977. {
  978. qDebug() << "Need to insert new series: " << seriesInstanceUID;
  979. QString seriesDate(ctkDataset.GetElementAsString(DCM_SeriesDate) );
  980. QString seriesTime(ctkDataset.GetElementAsString(DCM_SeriesTime) );
  981. QString seriesDescription(ctkDataset.GetElementAsString(DCM_SeriesDescription) );
  982. QString modality(ctkDataset.GetElementAsString(DCM_Modality) );
  983. QString bodyPartExamined(ctkDataset.GetElementAsString(DCM_BodyPartExamined) );
  984. QString frameOfReferenceUID(ctkDataset.GetElementAsString(DCM_FrameOfReferenceUID) );
  985. QString contrastAgent(ctkDataset.GetElementAsString(DCM_ContrastBolusAgent) );
  986. QString scanningSequence(ctkDataset.GetElementAsString(DCM_ScanningSequence) );
  987. long seriesNumber(ctkDataset.GetElementAsInteger(DCM_SeriesNumber) );
  988. long acquisitionNumber(ctkDataset.GetElementAsInteger(DCM_AcquisitionNumber) );
  989. long echoNumber(ctkDataset.GetElementAsInteger(DCM_EchoNumbers) );
  990. long temporalPosition(ctkDataset.GetElementAsInteger(DCM_TemporalPositionIdentifier) );
  991. QSqlQuery insertSeriesStatement ( Database );
  992. insertSeriesStatement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'Modality', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
  993. insertSeriesStatement.bindValue ( 0, seriesInstanceUID );
  994. insertSeriesStatement.bindValue ( 1, studyInstanceUID );
  995. insertSeriesStatement.bindValue ( 2, static_cast<int>(seriesNumber) );
  996. insertSeriesStatement.bindValue ( 3, QDate::fromString ( seriesDate, "yyyyMMdd" ) );
  997. insertSeriesStatement.bindValue ( 4, seriesTime );
  998. insertSeriesStatement.bindValue ( 5, seriesDescription );
  999. insertSeriesStatement.bindValue ( 6, modality );
  1000. insertSeriesStatement.bindValue ( 7, bodyPartExamined );
  1001. insertSeriesStatement.bindValue ( 8, frameOfReferenceUID );
  1002. insertSeriesStatement.bindValue ( 9, static_cast<int>(acquisitionNumber) );
  1003. insertSeriesStatement.bindValue ( 10, contrastAgent );
  1004. insertSeriesStatement.bindValue ( 11, scanningSequence );
  1005. insertSeriesStatement.bindValue ( 12, static_cast<int>(echoNumber) );
  1006. insertSeriesStatement.bindValue ( 13, static_cast<int>(temporalPosition) );
  1007. if ( !insertSeriesStatement.exec() )
  1008. {
  1009. logger.error ( "Error executing statament: "
  1010. + insertSeriesStatement.lastQuery()
  1011. + " Error: " + insertSeriesStatement.lastError().text() );
  1012. LastSeriesInstanceUID = "";
  1013. }
  1014. else
  1015. {
  1016. LastSeriesInstanceUID = seriesInstanceUID;
  1017. }
  1018. }
  1019. else
  1020. {
  1021. qDebug() << "Used existing series: " << seriesInstanceUID;
  1022. }
  1023. }
  1024. //------------------------------------------------------------------------------
  1025. void ctkDICOMDatabase::setTagsToPrecache( const QStringList tags)
  1026. {
  1027. Q_D(ctkDICOMDatabase);
  1028. d->TagsToPrecache = tags;
  1029. }
  1030. //------------------------------------------------------------------------------
  1031. const QStringList ctkDICOMDatabase::tagsToPrecache()
  1032. {
  1033. Q_D(ctkDICOMDatabase);
  1034. return d->TagsToPrecache;
  1035. }
  1036. //------------------------------------------------------------------------------
  1037. void ctkDICOMDatabasePrivate::precacheTags( const QString sopInstanceUID )
  1038. {
  1039. Q_Q(ctkDICOMDatabase);
  1040. ctkDICOMItem dataset;
  1041. QString fileName = q->fileForInstance(sopInstanceUID);
  1042. dataset.InitializeFromFile(fileName);
  1043. QStringList sopInstanceUIDs, tags, values;
  1044. foreach (const QString &tag, this->TagsToPrecache)
  1045. {
  1046. unsigned short group, element;
  1047. q->tagToGroupElement(tag, group, element);
  1048. DcmTagKey tagKey(group, element);
  1049. QString value = dataset.GetAllElementValuesAsString(tagKey);
  1050. sopInstanceUIDs << sopInstanceUID;
  1051. tags << tag;
  1052. values << value;
  1053. }
  1054. this->beginTransaction();
  1055. q->cacheTags(sopInstanceUIDs, tags, values);
  1056. this->endTransaction();
  1057. }
  1058. //------------------------------------------------------------------------------
  1059. void ctkDICOMDatabasePrivate::insert( const ctkDICOMItem& ctkDataset, const QString& filePath, bool storeFile, bool generateThumbnail)
  1060. {
  1061. Q_Q(ctkDICOMDatabase);
  1062. // this is the method that all other insert signatures end up calling
  1063. // after they have pre-parsed their arguments
  1064. // Check to see if the file has already been loaded
  1065. // TODO:
  1066. // It could make sense to actually remove the dataset and re-add it. This needs the remove
  1067. // method we still have to write.
  1068. //
  1069. //
  1070. QString sopInstanceUID ( ctkDataset.GetElementAsString(DCM_SOPInstanceUID) );
  1071. QSqlQuery fileExistsQuery ( Database );
  1072. fileExistsQuery.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == :sopInstanceUID");
  1073. fileExistsQuery.bindValue(":sopInstanceUID",sopInstanceUID);
  1074. {
  1075. bool success = fileExistsQuery.exec();
  1076. if (!success)
  1077. {
  1078. logger.error("SQLITE ERROR: " + fileExistsQuery.lastError().driverText());
  1079. return;
  1080. }
  1081. fileExistsQuery.next();
  1082. QString databaseFilename(fileExistsQuery.value(1).toString());
  1083. QDateTime fileLastModified(QFileInfo(databaseFilename).lastModified());
  1084. QDateTime databaseInsertTimestamp(QDateTime::fromString(fileExistsQuery.value(0).toString(),Qt::ISODate));
  1085. qDebug() << "inserting filePath: " << filePath;
  1086. if (databaseFilename == "")
  1087. {
  1088. qDebug() << "database filename for " << sopInstanceUID << " is empty - we should insert on top of it";
  1089. }
  1090. else
  1091. {
  1092. if ( databaseFilename == filePath && fileLastModified < databaseInsertTimestamp )
  1093. {
  1094. logger.debug ( "File " + databaseFilename + " already added" );
  1095. return;
  1096. }
  1097. else
  1098. {
  1099. QSqlQuery deleteFile ( Database );
  1100. deleteFile.prepare("DELETE FROM Images WHERE SOPInstanceUID == :sopInstanceUID");
  1101. deleteFile.bindValue(":sopInstanceUID",sopInstanceUID);
  1102. bool success = deleteFile.exec();
  1103. if (!success)
  1104. {
  1105. logger.error("SQLITE ERROR deleting old image row: " + deleteFile.lastError().driverText());
  1106. return;
  1107. }
  1108. }
  1109. }
  1110. }
  1111. //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  1112. QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) );
  1113. QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) );
  1114. QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  1115. QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) );
  1116. if ( patientID.isEmpty() && !studyInstanceUID.isEmpty() )
  1117. { // Use study instance uid as patient id if patient id is empty - can happen on anonymized datasets
  1118. // see: http://www.na-mic.org/Bug/view.php?id=2040
  1119. logger.warn("Patient ID is empty, using studyInstanceUID as patient ID");
  1120. patientID = studyInstanceUID;
  1121. }
  1122. if ( patientsName.isEmpty() && !patientID.isEmpty() )
  1123. { // Use patient id as name if name is empty - can happen on anonymized datasets
  1124. // see: http://www.na-mic.org/Bug/view.php?id=1643
  1125. patientsName = patientID;
  1126. }
  1127. if ( patientsName.isEmpty() || studyInstanceUID.isEmpty() || patientID.isEmpty() )
  1128. {
  1129. logger.error("Dataset is missing necessary information (patient name, study instance UID, or patient ID)!");
  1130. return;
  1131. }
  1132. // store the file if the database is not in memomry
  1133. // TODO: if we are called from insert(file) we
  1134. // have to do something else
  1135. //
  1136. QString filename = filePath;
  1137. if ( storeFile && !q->isInMemory() && !seriesInstanceUID.isEmpty() )
  1138. {
  1139. // QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
  1140. QString destinationDirectoryName = q->databaseDirectory() + "/dicom/";
  1141. QDir destinationDir(destinationDirectoryName);
  1142. filename = destinationDirectoryName +
  1143. studyInstanceUID + "/" +
  1144. seriesInstanceUID + "/" +
  1145. sopInstanceUID;
  1146. destinationDir.mkpath(studyInstanceUID + "/" +
  1147. seriesInstanceUID);
  1148. if(filePath.isEmpty())
  1149. {
  1150. logger.debug ( "Saving file: " + filename );
  1151. if ( !ctkDataset.SaveToFile( filename) )
  1152. {
  1153. logger.error ( "Error saving file: " + filename );
  1154. return;
  1155. }
  1156. }
  1157. else
  1158. {
  1159. // we're inserting an existing file
  1160. QFile currentFile( filePath );
  1161. currentFile.copy(filename);
  1162. logger.debug( "Copy file from: " + filePath );
  1163. logger.debug( "Copy file to : " + filename );
  1164. }
  1165. }
  1166. //The dbPatientID is a unique number within the database,
  1167. //generated by the sqlite autoincrement
  1168. //The patientID is the (non-unique) DICOM patient id
  1169. int dbPatientID = LastPatientUID;
  1170. if ( patientID != "" && patientsName != "" )
  1171. {
  1172. //Speed up: Check if patient is the same as in last file;
  1173. // very probable, as all images belonging to a study have the same patient
  1174. QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) );
  1175. if ( LastPatientID != patientID
  1176. || LastPatientsBirthDate != patientsBirthDate
  1177. || LastPatientsName != patientsName )
  1178. { QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  1179. qDebug() << "This looks like a different patient from last insert: " << patientID;
  1180. // Ok, something is different from last insert, let's insert him if he's not
  1181. // already in the db.
  1182. dbPatientID = insertPatient( ctkDataset );
  1183. // let users of this class track when things happen
  1184. emit q->patientAdded(dbPatientID, patientID, patientsName, patientsBirthDate);
  1185. /// keep this for the next image
  1186. LastPatientUID = dbPatientID;
  1187. LastPatientID = patientID;
  1188. LastPatientsBirthDate = patientsBirthDate;
  1189. LastPatientsName = patientsName;
  1190. }
  1191. qDebug() << "Going to insert this instance with dbPatientID: " << dbPatientID;
  1192. // Patient is in now. Let's continue with the study
  1193. if ( studyInstanceUID != "" && LastStudyInstanceUID != studyInstanceUID )
  1194. {
  1195. insertStudy(ctkDataset,dbPatientID);
  1196. // let users of this class track when things happen
  1197. emit q->studyAdded(studyInstanceUID);
  1198. qDebug() << "Study Added";
  1199. }
  1200. if ( seriesInstanceUID != "" && seriesInstanceUID != LastSeriesInstanceUID )
  1201. {
  1202. insertSeries(ctkDataset, studyInstanceUID);
  1203. // let users of this class track when things happen
  1204. emit q->seriesAdded(seriesInstanceUID);
  1205. qDebug() << "Series Added";
  1206. }
  1207. // TODO: what to do with imported files
  1208. //
  1209. if ( !filename.isEmpty() && !seriesInstanceUID.isEmpty() )
  1210. {
  1211. QSqlQuery checkImageExistsQuery (Database);
  1212. checkImageExistsQuery.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
  1213. checkImageExistsQuery.bindValue ( 0, filename );
  1214. checkImageExistsQuery.exec();
  1215. qDebug() << "Maybe add Instance";
  1216. if(!checkImageExistsQuery.next())
  1217. {
  1218. QSqlQuery insertImageStatement ( Database );
  1219. insertImageStatement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" );
  1220. insertImageStatement.bindValue ( 0, sopInstanceUID );
  1221. insertImageStatement.bindValue ( 1, filename );
  1222. insertImageStatement.bindValue ( 2, seriesInstanceUID );
  1223. insertImageStatement.bindValue ( 3, QDateTime::currentDateTime() );
  1224. insertImageStatement.exec();
  1225. // insert was needed, so cache any application-requested tags
  1226. this->precacheTags(sopInstanceUID);
  1227. // let users of this class track when things happen
  1228. emit q->instanceAdded(sopInstanceUID);
  1229. qDebug() << "Instance Added";
  1230. }
  1231. }
  1232. if( generateThumbnail && thumbnailGenerator && !seriesInstanceUID.isEmpty() )
  1233. {
  1234. QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
  1235. //Create thumbnail here
  1236. QString thumbnailPath = q->databaseDirectory() +
  1237. "/thumbs/" + studyInstanceUID + "/" + seriesInstanceUID
  1238. + "/" + sopInstanceUID + ".png";
  1239. QFileInfo thumbnailInfo(thumbnailPath);
  1240. if( !(thumbnailInfo.exists()
  1241. && (thumbnailInfo.lastModified() > QFileInfo(filename).lastModified())))
  1242. {
  1243. QDir(q->databaseDirectory() + "/thumbs/").mkpath(studySeriesDirectory);
  1244. DicomImage dcmImage(QDir::toNativeSeparators(filename).toLatin1());
  1245. thumbnailGenerator->generateThumbnail(&dcmImage, thumbnailPath);
  1246. }
  1247. }
  1248. if (q->isInMemory())
  1249. {
  1250. emit q->databaseChanged();
  1251. }
  1252. }
  1253. else
  1254. {
  1255. qDebug() << "No patient name or no patient id - not inserting!";
  1256. }
  1257. }
  1258. //------------------------------------------------------------------------------
  1259. bool ctkDICOMDatabase::fileExistsAndUpToDate(const QString& filePath)
  1260. {
  1261. Q_D(ctkDICOMDatabase);
  1262. bool result(false);
  1263. QSqlQuery check_filename_query(database());
  1264. check_filename_query.prepare("SELECT InsertTimestamp FROM Images WHERE Filename == ?");
  1265. check_filename_query.bindValue(0,filePath);
  1266. d->loggedExec(check_filename_query);
  1267. if (
  1268. check_filename_query.next() &&
  1269. QFileInfo(filePath).lastModified() < QDateTime::fromString(check_filename_query.value(0).toString(),Qt::ISODate)
  1270. )
  1271. {
  1272. result = true;
  1273. }
  1274. check_filename_query.finish();
  1275. return result;
  1276. }
  1277. //------------------------------------------------------------------------------
  1278. bool ctkDICOMDatabase::isOpen() const
  1279. {
  1280. Q_D(const ctkDICOMDatabase);
  1281. return d->Database.isOpen();
  1282. }
  1283. //------------------------------------------------------------------------------
  1284. bool ctkDICOMDatabase::isInMemory() const
  1285. {
  1286. Q_D(const ctkDICOMDatabase);
  1287. return d->DatabaseFileName == ":memory:";
  1288. }
  1289. //------------------------------------------------------------------------------
  1290. bool ctkDICOMDatabase::removeSeries(const QString& seriesInstanceUID)
  1291. {
  1292. Q_D(ctkDICOMDatabase);
  1293. // get all images from series
  1294. QSqlQuery fileExistsQuery ( d->Database );
  1295. fileExistsQuery.prepare("SELECT Filename, SOPInstanceUID, StudyInstanceUID FROM Images,Series WHERE Series.SeriesInstanceUID = Images.SeriesInstanceUID AND Images.SeriesInstanceUID = :seriesID");
  1296. fileExistsQuery.bindValue(":seriesID",seriesInstanceUID);
  1297. bool success = fileExistsQuery.exec();
  1298. if (!success)
  1299. {
  1300. logger.error("SQLITE ERROR: " + fileExistsQuery.lastError().driverText());
  1301. return false;
  1302. }
  1303. QList< QPair<QString,QString> > removeList;
  1304. while ( fileExistsQuery.next() )
  1305. {
  1306. QString dbFilePath = fileExistsQuery.value(fileExistsQuery.record().indexOf("Filename")).toString();
  1307. QString sopInstanceUID = fileExistsQuery.value(fileExistsQuery.record().indexOf("SOPInstanceUID")).toString();
  1308. QString studyInstanceUID = fileExistsQuery.value(fileExistsQuery.record().indexOf("StudyInstanceUID")).toString();
  1309. QString internalFilePath = studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID;
  1310. removeList << qMakePair(dbFilePath,internalFilePath);
  1311. }
  1312. QSqlQuery fileRemove ( d->Database );
  1313. fileRemove.prepare("DELETE FROM Images WHERE SeriesInstanceUID == :seriesID");
  1314. fileRemove.bindValue(":seriesID",seriesInstanceUID);
  1315. logger.debug("SQLITE: removing seriesInstanceUID " + seriesInstanceUID);
  1316. success = fileRemove.exec();
  1317. if (!success)
  1318. {
  1319. logger.error("SQLITE ERROR: could not remove seriesInstanceUID " + seriesInstanceUID);
  1320. logger.error("SQLITE ERROR: " + fileRemove.lastError().driverText());
  1321. }
  1322. QPair<QString,QString> fileToRemove;
  1323. foreach (fileToRemove, removeList)
  1324. {
  1325. QString dbFilePath = fileToRemove.first;
  1326. QString thumbnailToRemove = databaseDirectory() + "/thumbs/" + fileToRemove.second + ".png";
  1327. // check that the file is below our internal storage
  1328. if (dbFilePath.startsWith( databaseDirectory() + "/dicom/"))
  1329. {
  1330. if (!dbFilePath.endsWith(fileToRemove.second))
  1331. {
  1332. logger.error("Database inconsistency detected during delete!");
  1333. continue;
  1334. }
  1335. if (QFile( dbFilePath ).remove())
  1336. {
  1337. logger.debug("Removed file " + dbFilePath );
  1338. }
  1339. else
  1340. {
  1341. logger.warn("Failed to remove file " + dbFilePath );
  1342. }
  1343. }
  1344. if (QFile( thumbnailToRemove ).remove())
  1345. {
  1346. logger.debug("Removed thumbnail " + thumbnailToRemove);
  1347. }
  1348. else
  1349. {
  1350. logger.warn("Failed to remove thumbnail " + thumbnailToRemove);
  1351. }
  1352. }
  1353. this->cleanup();
  1354. d->resetLastInsertedValues();
  1355. return true;
  1356. }
  1357. //------------------------------------------------------------------------------
  1358. bool ctkDICOMDatabase::cleanup()
  1359. {
  1360. Q_D(ctkDICOMDatabase);
  1361. QSqlQuery seriesCleanup ( d->Database );
  1362. seriesCleanup.exec("DELETE FROM Series WHERE ( SELECT COUNT(*) FROM Images WHERE Images.SeriesInstanceUID = Series.SeriesInstanceUID ) = 0;");
  1363. seriesCleanup.exec("DELETE FROM Studies WHERE ( SELECT COUNT(*) FROM Series WHERE Series.StudyInstanceUID = Studies.StudyInstanceUID ) = 0;");
  1364. seriesCleanup.exec("DELETE FROM Patients WHERE ( SELECT COUNT(*) FROM Studies WHERE Studies.PatientsUID = Patients.UID ) = 0;");
  1365. return true;
  1366. }
  1367. //------------------------------------------------------------------------------
  1368. bool ctkDICOMDatabase::removeStudy(const QString& studyInstanceUID)
  1369. {
  1370. Q_D(ctkDICOMDatabase);
  1371. QSqlQuery seriesForStudy( d->Database );
  1372. seriesForStudy.prepare("SELECT SeriesInstanceUID FROM Series WHERE StudyInstanceUID = :studyID");
  1373. seriesForStudy.bindValue(":studyID", studyInstanceUID);
  1374. bool success = seriesForStudy.exec();
  1375. if (!success)
  1376. {
  1377. logger.error("SQLITE ERROR: " + seriesForStudy.lastError().driverText());
  1378. return false;
  1379. }
  1380. bool result = true;
  1381. while ( seriesForStudy.next() )
  1382. {
  1383. QString seriesInstanceUID = seriesForStudy.value(seriesForStudy.record().indexOf("SeriesInstanceUID")).toString();
  1384. if ( ! this->removeSeries(seriesInstanceUID) )
  1385. {
  1386. result = false;
  1387. }
  1388. }
  1389. d->resetLastInsertedValues();
  1390. return result;
  1391. }
  1392. //------------------------------------------------------------------------------
  1393. bool ctkDICOMDatabase::removePatient(const QString& patientID)
  1394. {
  1395. Q_D(ctkDICOMDatabase);
  1396. QSqlQuery studiesForPatient( d->Database );
  1397. studiesForPatient.prepare("SELECT StudyInstanceUID FROM Studies WHERE PatientsUID = :patientsID");
  1398. studiesForPatient.bindValue(":patientsID", patientID);
  1399. bool success = studiesForPatient.exec();
  1400. if (!success)
  1401. {
  1402. logger.error("SQLITE ERROR: " + studiesForPatient.lastError().driverText());
  1403. return false;
  1404. }
  1405. bool result = true;
  1406. while ( studiesForPatient.next() )
  1407. {
  1408. QString studyInstanceUID = studiesForPatient.value(studiesForPatient.record().indexOf("StudyInstanceUID")).toString();
  1409. if ( ! this->removeStudy(studyInstanceUID) )
  1410. {
  1411. result = false;
  1412. }
  1413. }
  1414. d->resetLastInsertedValues();
  1415. return result;
  1416. }
  1417. ///
  1418. /// Code related to the tagCache
  1419. ///
  1420. //------------------------------------------------------------------------------
  1421. bool ctkDICOMDatabase::tagCacheExists()
  1422. {
  1423. Q_D(ctkDICOMDatabase);
  1424. if (d->TagCacheVerified)
  1425. {
  1426. return true;
  1427. }
  1428. // try to open the database if it's not already open
  1429. if ( !(d->TagCacheDatabase.isOpen()) )
  1430. {
  1431. qDebug() << "TagCacheDatabase not open\n";
  1432. d->TagCacheDatabase = QSqlDatabase::addDatabase("QSQLITE", d->Database.connectionName() + "TagCache");
  1433. d->TagCacheDatabase.setDatabaseName(d->TagCacheDatabaseFilename);
  1434. if ( !(d->TagCacheDatabase.open()) )
  1435. {
  1436. qDebug() << "TagCacheDatabase would not open!\n";
  1437. qDebug() << "TagCacheDatabaseFilename is: " << d->TagCacheDatabaseFilename << "\n";
  1438. return false;
  1439. }
  1440. //Disable synchronous writing to make modifications faster
  1441. QSqlQuery pragmaSyncQuery(d->TagCacheDatabase);
  1442. pragmaSyncQuery.exec("PRAGMA synchronous = OFF");
  1443. pragmaSyncQuery.finish();
  1444. }
  1445. // check that the table exists
  1446. QSqlQuery cacheExists( d->TagCacheDatabase );
  1447. cacheExists.prepare("SELECT * FROM TagCache LIMIT 1");
  1448. bool success = d->loggedExec(cacheExists);
  1449. if (success)
  1450. {
  1451. qDebug() << "TagCacheDatabase verified!\n";
  1452. d->TagCacheVerified = true;
  1453. return true;
  1454. }
  1455. qDebug() << "TagCacheDatabase NOT verified based on table check!\n";
  1456. return false;
  1457. }
  1458. //------------------------------------------------------------------------------
  1459. bool ctkDICOMDatabase::initializeTagCache()
  1460. {
  1461. Q_D(ctkDICOMDatabase);
  1462. // First, drop any existing table
  1463. if ( this->tagCacheExists() )
  1464. {
  1465. qDebug() << "TagCacheDatabase drop existing table\n";
  1466. QSqlQuery dropCacheTable( d->TagCacheDatabase );
  1467. dropCacheTable.prepare( "DROP TABLE TagCache" );
  1468. d->loggedExec(dropCacheTable);
  1469. }
  1470. // now create a table
  1471. qDebug() << "TagCacheDatabase adding table\n";
  1472. QSqlQuery createCacheTable( d->TagCacheDatabase );
  1473. createCacheTable.prepare(
  1474. "CREATE TABLE TagCache (SOPInstanceUID, Tag, Value, PRIMARY KEY (SOPInstanceUID, Tag))" );
  1475. bool success = d->loggedExec(createCacheTable);
  1476. if (success)
  1477. {
  1478. d->TagCacheVerified = true;
  1479. return true;
  1480. }
  1481. return false;
  1482. }
  1483. //------------------------------------------------------------------------------
  1484. QString ctkDICOMDatabase::cachedTag(const QString sopInstanceUID, const QString tag)
  1485. {
  1486. Q_D(ctkDICOMDatabase);
  1487. if ( !this->tagCacheExists() )
  1488. {
  1489. if ( !this->initializeTagCache() )
  1490. {
  1491. return( "" );
  1492. }
  1493. }
  1494. QSqlQuery selectValue( d->TagCacheDatabase );
  1495. selectValue.prepare( "SELECT Value FROM TagCache WHERE SOPInstanceUID = :sopInstanceUID AND Tag = :tag" );
  1496. selectValue.bindValue(":sopInstanceUID",sopInstanceUID);
  1497. selectValue.bindValue(":tag",tag);
  1498. d->loggedExec(selectValue);
  1499. QString result("");
  1500. if (selectValue.next())
  1501. {
  1502. result = selectValue.value(0).toString();
  1503. if (result == QString(""))
  1504. {
  1505. result = ValueIsEmptyString;
  1506. }
  1507. }
  1508. return( result );
  1509. }
  1510. //------------------------------------------------------------------------------
  1511. bool ctkDICOMDatabase::cacheTag(const QString sopInstanceUID, const QString tag, const QString value)
  1512. {
  1513. QStringList sopInstanceUIDs, tags, values;
  1514. sopInstanceUIDs << sopInstanceUID;
  1515. tags << tag;
  1516. values << value;
  1517. return this->cacheTags(sopInstanceUIDs, tags, values);
  1518. }
  1519. //------------------------------------------------------------------------------
  1520. bool ctkDICOMDatabase::cacheTags(const QStringList sopInstanceUIDs, const QStringList tags, QStringList values)
  1521. {
  1522. Q_D(ctkDICOMDatabase);
  1523. if ( !this->tagCacheExists() )
  1524. {
  1525. if ( !this->initializeTagCache() )
  1526. {
  1527. return false;
  1528. }
  1529. }
  1530. // replace empty strings with special flag string
  1531. QStringList::iterator i;
  1532. for (i = values.begin(); i != values.end(); ++i)
  1533. {
  1534. if (*i == "")
  1535. {
  1536. *i = TagNotInInstance;
  1537. }
  1538. }
  1539. QSqlQuery insertTags( d->TagCacheDatabase );
  1540. insertTags.prepare( "INSERT OR REPLACE INTO TagCache VALUES(?,?,?)" );
  1541. insertTags.addBindValue(sopInstanceUIDs);
  1542. insertTags.addBindValue(tags);
  1543. insertTags.addBindValue(values);
  1544. return d->loggedExecBatch(insertTags);
  1545. }