ctkDICOMDatabase.cpp 58 KB

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