comparison OrthancServer/Sources/Database/SQLiteDatabaseWrapper.cpp @ 4044:d25f4c0fa160 framework

splitting code into OrthancFramework and OrthancServer
author Sebastien Jodogne <s.jodogne@gmail.com>
date Wed, 10 Jun 2020 20:30:34 +0200
parents OrthancServer/Database/SQLiteDatabaseWrapper.cpp@058b5ade8acd
children 05b8fd21089c
comparison
equal deleted inserted replaced
4043:6c6239aec462 4044:d25f4c0fa160
1 /**
2 * Orthanc - A Lightweight, RESTful DICOM Store
3 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
4 * Department, University Hospital of Liege, Belgium
5 * Copyright (C) 2017-2020 Osimis S.A., Belgium
6 *
7 * This program is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
11 *
12 * In addition, as a special exception, the copyright holders of this
13 * program give permission to link the code of its release with the
14 * OpenSSL project's "OpenSSL" library (or with modified versions of it
15 * that use the same license as the "OpenSSL" library), and distribute
16 * the linked executables. You must obey the GNU General Public License
17 * in all respects for all of the code used other than "OpenSSL". If you
18 * modify file(s) with this exception, you may extend this exception to
19 * your version of the file(s), but you are not obligated to do so. If
20 * you do not wish to do so, delete this exception statement from your
21 * version. If you delete this exception statement from all source files
22 * in the program, then also delete it here.
23 *
24 * This program is distributed in the hope that it will be useful, but
25 * WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27 * General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 **/
32
33
34 #include "../PrecompiledHeadersServer.h"
35 #include "SQLiteDatabaseWrapper.h"
36
37 #include "../../Core/DicomFormat/DicomArray.h"
38 #include "../../Core/Logging.h"
39 #include "../../Core/SQLite/Transaction.h"
40 #include "../Search/ISqlLookupFormatter.h"
41 #include "../ServerToolbox.h"
42
43 #include <OrthancServerResources.h>
44
45 #include <stdio.h>
46 #include <boost/lexical_cast.hpp>
47
48 namespace Orthanc
49 {
50 namespace Internals
51 {
52 class SignalFileDeleted : public SQLite::IScalarFunction
53 {
54 private:
55 IDatabaseListener& listener_;
56
57 public:
58 SignalFileDeleted(IDatabaseListener& listener) :
59 listener_(listener)
60 {
61 }
62
63 virtual const char* GetName() const
64 {
65 return "SignalFileDeleted";
66 }
67
68 virtual unsigned int GetCardinality() const
69 {
70 return 7;
71 }
72
73 virtual void Compute(SQLite::FunctionContext& context)
74 {
75 std::string uncompressedMD5, compressedMD5;
76
77 if (!context.IsNullValue(5))
78 {
79 uncompressedMD5 = context.GetStringValue(5);
80 }
81
82 if (!context.IsNullValue(6))
83 {
84 compressedMD5 = context.GetStringValue(6);
85 }
86
87 FileInfo info(context.GetStringValue(0),
88 static_cast<FileContentType>(context.GetIntValue(1)),
89 static_cast<uint64_t>(context.GetInt64Value(2)),
90 uncompressedMD5,
91 static_cast<CompressionType>(context.GetIntValue(3)),
92 static_cast<uint64_t>(context.GetInt64Value(4)),
93 compressedMD5);
94
95 listener_.SignalFileDeleted(info);
96 }
97 };
98
99 class SignalResourceDeleted : public SQLite::IScalarFunction
100 {
101 private:
102 IDatabaseListener& listener_;
103
104 public:
105 SignalResourceDeleted(IDatabaseListener& listener) :
106 listener_(listener)
107 {
108 }
109
110 virtual const char* GetName() const
111 {
112 return "SignalResourceDeleted";
113 }
114
115 virtual unsigned int GetCardinality() const
116 {
117 return 2;
118 }
119
120 virtual void Compute(SQLite::FunctionContext& context)
121 {
122 ResourceType type = static_cast<ResourceType>(context.GetIntValue(1));
123 ServerIndexChange change(ChangeType_Deleted, type, context.GetStringValue(0));
124 listener_.SignalChange(change);
125 }
126 };
127
128 class SignalRemainingAncestor : public SQLite::IScalarFunction
129 {
130 private:
131 bool hasRemainingAncestor_;
132 std::string remainingPublicId_;
133 ResourceType remainingType_;
134
135 public:
136 SignalRemainingAncestor() :
137 hasRemainingAncestor_(false)
138 {
139 }
140
141 void Reset()
142 {
143 hasRemainingAncestor_ = false;
144 }
145
146 virtual const char* GetName() const
147 {
148 return "SignalRemainingAncestor";
149 }
150
151 virtual unsigned int GetCardinality() const
152 {
153 return 2;
154 }
155
156 virtual void Compute(SQLite::FunctionContext& context)
157 {
158 VLOG(1) << "There exists a remaining ancestor with public ID \""
159 << context.GetStringValue(0)
160 << "\" of type "
161 << context.GetIntValue(1);
162
163 if (!hasRemainingAncestor_ ||
164 remainingType_ >= context.GetIntValue(1))
165 {
166 hasRemainingAncestor_ = true;
167 remainingPublicId_ = context.GetStringValue(0);
168 remainingType_ = static_cast<ResourceType>(context.GetIntValue(1));
169 }
170 }
171
172 bool HasRemainingAncestor() const
173 {
174 return hasRemainingAncestor_;
175 }
176
177 const std::string& GetRemainingAncestorId() const
178 {
179 assert(hasRemainingAncestor_);
180 return remainingPublicId_;
181 }
182
183 ResourceType GetRemainingAncestorType() const
184 {
185 assert(hasRemainingAncestor_);
186 return remainingType_;
187 }
188 };
189 }
190
191
192 void SQLiteDatabaseWrapper::GetChangesInternal(std::list<ServerIndexChange>& target,
193 bool& done,
194 SQLite::Statement& s,
195 uint32_t maxResults)
196 {
197 target.clear();
198
199 while (target.size() < maxResults && s.Step())
200 {
201 int64_t seq = s.ColumnInt64(0);
202 ChangeType changeType = static_cast<ChangeType>(s.ColumnInt(1));
203 ResourceType resourceType = static_cast<ResourceType>(s.ColumnInt(3));
204 const std::string& date = s.ColumnString(4);
205
206 int64_t internalId = s.ColumnInt64(2);
207 std::string publicId = GetPublicId(internalId);
208
209 target.push_back(ServerIndexChange(seq, changeType, resourceType, publicId, date));
210 }
211
212 done = !(target.size() == maxResults && s.Step());
213 }
214
215
216 void SQLiteDatabaseWrapper::GetExportedResourcesInternal(std::list<ExportedResource>& target,
217 bool& done,
218 SQLite::Statement& s,
219 uint32_t maxResults)
220 {
221 target.clear();
222
223 while (target.size() < maxResults && s.Step())
224 {
225 int64_t seq = s.ColumnInt64(0);
226 ResourceType resourceType = static_cast<ResourceType>(s.ColumnInt(1));
227 std::string publicId = s.ColumnString(2);
228
229 ExportedResource resource(seq,
230 resourceType,
231 publicId,
232 s.ColumnString(3), // modality
233 s.ColumnString(8), // date
234 s.ColumnString(4), // patient ID
235 s.ColumnString(5), // study instance UID
236 s.ColumnString(6), // series instance UID
237 s.ColumnString(7)); // sop instance UID
238
239 target.push_back(resource);
240 }
241
242 done = !(target.size() == maxResults && s.Step());
243 }
244
245
246 void SQLiteDatabaseWrapper::GetChildren(std::list<std::string>& childrenPublicIds,
247 int64_t id)
248 {
249 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT publicId FROM Resources WHERE parentId=?");
250 s.BindInt64(0, id);
251
252 childrenPublicIds.clear();
253 while (s.Step())
254 {
255 childrenPublicIds.push_back(s.ColumnString(0));
256 }
257 }
258
259
260 void SQLiteDatabaseWrapper::DeleteResource(int64_t id)
261 {
262 signalRemainingAncestor_->Reset();
263
264 SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM Resources WHERE internalId=?");
265 s.BindInt64(0, id);
266 s.Run();
267
268 if (signalRemainingAncestor_->HasRemainingAncestor() &&
269 listener_ != NULL)
270 {
271 listener_->SignalRemainingAncestor(signalRemainingAncestor_->GetRemainingAncestorType(),
272 signalRemainingAncestor_->GetRemainingAncestorId());
273 }
274 }
275
276
277 bool SQLiteDatabaseWrapper::GetParentPublicId(std::string& target,
278 int64_t id)
279 {
280 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT a.publicId FROM Resources AS a, Resources AS b "
281 "WHERE a.internalId = b.parentId AND b.internalId = ?");
282 s.BindInt64(0, id);
283
284 if (s.Step())
285 {
286 target = s.ColumnString(0);
287 return true;
288 }
289 else
290 {
291 return false;
292 }
293 }
294
295
296 int64_t SQLiteDatabaseWrapper::GetTableRecordCount(const std::string& table)
297 {
298 /**
299 * "Generally one cannot use SQL parameters/placeholders for
300 * database identifiers (tables, columns, views, schemas, etc.) or
301 * database functions (e.g., CURRENT_DATE), but instead only for
302 * binding literal values." => To avoid any SQL injection, we
303 * check that the "table" parameter has only alphabetic
304 * characters.
305 * https://stackoverflow.com/a/1274764/881731
306 **/
307 for (size_t i = 0; i < table.size(); i++)
308 {
309 if (!isalpha(table[i]))
310 {
311 throw OrthancException(ErrorCode_ParameterOutOfRange);
312 }
313 }
314
315 // Don't use "SQLITE_FROM_HERE", otherwise "table" would be cached
316 SQLite::Statement s(db_, "SELECT COUNT(*) FROM " + table);
317
318 if (s.Step())
319 {
320 int64_t c = s.ColumnInt(0);
321 assert(!s.Step());
322 return c;
323 }
324 else
325 {
326 throw OrthancException(ErrorCode_InternalError);
327 }
328 }
329
330
331 SQLiteDatabaseWrapper::SQLiteDatabaseWrapper(const std::string& path) :
332 listener_(NULL),
333 signalRemainingAncestor_(NULL),
334 version_(0)
335 {
336 db_.Open(path);
337 }
338
339
340 SQLiteDatabaseWrapper::SQLiteDatabaseWrapper() :
341 listener_(NULL),
342 signalRemainingAncestor_(NULL),
343 version_(0)
344 {
345 db_.OpenInMemory();
346 }
347
348
349 int SQLiteDatabaseWrapper::GetGlobalIntegerProperty(GlobalProperty property,
350 int defaultValue)
351 {
352 std::string tmp;
353
354 if (!LookupGlobalProperty(tmp, GlobalProperty_DatabasePatchLevel))
355 {
356 return defaultValue;
357 }
358 else
359 {
360 try
361 {
362 return boost::lexical_cast<int>(tmp);
363 }
364 catch (boost::bad_lexical_cast&)
365 {
366 throw OrthancException(ErrorCode_ParameterOutOfRange,
367 "Global property " + boost::lexical_cast<std::string>(property) +
368 " should be an integer, but found: " + tmp);
369 }
370 }
371 }
372
373
374 void SQLiteDatabaseWrapper::Open()
375 {
376 db_.Execute("PRAGMA ENCODING=\"UTF-8\";");
377
378 // Performance tuning of SQLite with PRAGMAs
379 // http://www.sqlite.org/pragma.html
380 db_.Execute("PRAGMA SYNCHRONOUS=NORMAL;");
381 db_.Execute("PRAGMA JOURNAL_MODE=WAL;");
382 db_.Execute("PRAGMA LOCKING_MODE=EXCLUSIVE;");
383 db_.Execute("PRAGMA WAL_AUTOCHECKPOINT=1000;");
384 //db_.Execute("PRAGMA TEMP_STORE=memory");
385
386 // Make "LIKE" case-sensitive in SQLite
387 db_.Execute("PRAGMA case_sensitive_like = true;");
388
389 {
390 SQLite::Transaction t(db_);
391 t.Begin();
392
393 if (!db_.DoesTableExist("GlobalProperties"))
394 {
395 LOG(INFO) << "Creating the database";
396 std::string query;
397 ServerResources::GetFileResource(query, ServerResources::PREPARE_DATABASE);
398 db_.Execute(query);
399 }
400
401 // Check the version of the database
402 std::string tmp;
403 if (!LookupGlobalProperty(tmp, GlobalProperty_DatabaseSchemaVersion))
404 {
405 tmp = "Unknown";
406 }
407
408 bool ok = false;
409 try
410 {
411 LOG(INFO) << "Version of the Orthanc database: " << tmp;
412 version_ = boost::lexical_cast<unsigned int>(tmp);
413 ok = true;
414 }
415 catch (boost::bad_lexical_cast&)
416 {
417 }
418
419 if (!ok)
420 {
421 throw OrthancException(ErrorCode_IncompatibleDatabaseVersion,
422 "Incompatible version of the Orthanc database: " + tmp);
423 }
424
425 // New in Orthanc 1.5.1
426 if (version_ == 6)
427 {
428 if (!LookupGlobalProperty(tmp, GlobalProperty_GetTotalSizeIsFast) ||
429 tmp != "1")
430 {
431 LOG(INFO) << "Installing the SQLite triggers to track the size of the attachments";
432 std::string query;
433 ServerResources::GetFileResource(query, ServerResources::INSTALL_TRACK_ATTACHMENTS_SIZE);
434 db_.Execute(query);
435 }
436 }
437
438 t.Commit();
439 }
440
441 signalRemainingAncestor_ = new Internals::SignalRemainingAncestor;
442 db_.Register(signalRemainingAncestor_);
443 }
444
445
446 static void ExecuteUpgradeScript(SQLite::Connection& db,
447 ServerResources::FileResourceId script)
448 {
449 std::string upgrade;
450 ServerResources::GetFileResource(upgrade, script);
451 db.BeginTransaction();
452 db.Execute(upgrade);
453 db.CommitTransaction();
454 }
455
456
457 void SQLiteDatabaseWrapper::Upgrade(unsigned int targetVersion,
458 IStorageArea& storageArea)
459 {
460 if (targetVersion != 6)
461 {
462 throw OrthancException(ErrorCode_IncompatibleDatabaseVersion);
463 }
464
465 // This version of Orthanc is only compatible with versions 3, 4,
466 // 5 and 6 of the DB schema
467 if (version_ != 3 &&
468 version_ != 4 &&
469 version_ != 5 &&
470 version_ != 6)
471 {
472 throw OrthancException(ErrorCode_IncompatibleDatabaseVersion);
473 }
474
475 if (version_ == 3)
476 {
477 LOG(WARNING) << "Upgrading database version from 3 to 4";
478 ExecuteUpgradeScript(db_, ServerResources::UPGRADE_DATABASE_3_TO_4);
479 version_ = 4;
480 }
481
482 if (version_ == 4)
483 {
484 LOG(WARNING) << "Upgrading database version from 4 to 5";
485 ExecuteUpgradeScript(db_, ServerResources::UPGRADE_DATABASE_4_TO_5);
486 version_ = 5;
487 }
488
489 if (version_ == 5)
490 {
491 LOG(WARNING) << "Upgrading database version from 5 to 6";
492 // No change in the DB schema, the step from version 5 to 6 only
493 // consists in reconstructing the main DICOM tags information
494 // (as more tags got included).
495 db_.BeginTransaction();
496 ServerToolbox::ReconstructMainDicomTags(*this, storageArea, ResourceType_Patient);
497 ServerToolbox::ReconstructMainDicomTags(*this, storageArea, ResourceType_Study);
498 ServerToolbox::ReconstructMainDicomTags(*this, storageArea, ResourceType_Series);
499 ServerToolbox::ReconstructMainDicomTags(*this, storageArea, ResourceType_Instance);
500 db_.Execute("UPDATE GlobalProperties SET value=\"6\" WHERE property=" +
501 boost::lexical_cast<std::string>(GlobalProperty_DatabaseSchemaVersion) + ";");
502 db_.CommitTransaction();
503 version_ = 6;
504 }
505 }
506
507
508 void SQLiteDatabaseWrapper::SetListener(IDatabaseListener& listener)
509 {
510 listener_ = &listener;
511 db_.Register(new Internals::SignalFileDeleted(listener));
512 db_.Register(new Internals::SignalResourceDeleted(listener));
513 }
514
515
516 void SQLiteDatabaseWrapper::ClearTable(const std::string& tableName)
517 {
518 db_.Execute("DELETE FROM " + tableName);
519 }
520
521
522 bool SQLiteDatabaseWrapper::LookupParent(int64_t& parentId,
523 int64_t resourceId)
524 {
525 SQLite::Statement s(db_, SQLITE_FROM_HERE,
526 "SELECT parentId FROM Resources WHERE internalId=?");
527 s.BindInt64(0, resourceId);
528
529 if (!s.Step())
530 {
531 throw OrthancException(ErrorCode_UnknownResource);
532 }
533
534 if (s.ColumnIsNull(0))
535 {
536 return false;
537 }
538 else
539 {
540 parentId = s.ColumnInt(0);
541 return true;
542 }
543 }
544
545
546 ResourceType SQLiteDatabaseWrapper::GetResourceType(int64_t resourceId)
547 {
548 SQLite::Statement s(db_, SQLITE_FROM_HERE,
549 "SELECT resourceType FROM Resources WHERE internalId=?");
550 s.BindInt64(0, resourceId);
551
552 if (s.Step())
553 {
554 return static_cast<ResourceType>(s.ColumnInt(0));
555 }
556 else
557 {
558 throw OrthancException(ErrorCode_UnknownResource);
559 }
560 }
561
562
563 std::string SQLiteDatabaseWrapper::GetPublicId(int64_t resourceId)
564 {
565 SQLite::Statement s(db_, SQLITE_FROM_HERE,
566 "SELECT publicId FROM Resources WHERE internalId=?");
567 s.BindInt64(0, resourceId);
568
569 if (s.Step())
570 {
571 return s.ColumnString(0);
572 }
573 else
574 {
575 throw OrthancException(ErrorCode_UnknownResource);
576 }
577 }
578
579
580 void SQLiteDatabaseWrapper::GetChanges(std::list<ServerIndexChange>& target /*out*/,
581 bool& done /*out*/,
582 int64_t since,
583 uint32_t maxResults)
584 {
585 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT * FROM Changes WHERE seq>? ORDER BY seq LIMIT ?");
586 s.BindInt64(0, since);
587 s.BindInt(1, maxResults + 1);
588 GetChangesInternal(target, done, s, maxResults);
589 }
590
591
592 void SQLiteDatabaseWrapper::GetLastChange(std::list<ServerIndexChange>& target /*out*/)
593 {
594 bool done; // Ignored
595 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT * FROM Changes ORDER BY seq DESC LIMIT 1");
596 GetChangesInternal(target, done, s, 1);
597 }
598
599
600 class SQLiteDatabaseWrapper::Transaction : public IDatabaseWrapper::ITransaction
601 {
602 private:
603 SQLiteDatabaseWrapper& that_;
604 std::unique_ptr<SQLite::Transaction> transaction_;
605 int64_t initialDiskSize_;
606
607 public:
608 Transaction(SQLiteDatabaseWrapper& that) :
609 that_(that),
610 transaction_(new SQLite::Transaction(that_.db_))
611 {
612 #if defined(NDEBUG)
613 // Release mode
614 initialDiskSize_ = 0;
615 #else
616 // Debug mode
617 initialDiskSize_ = static_cast<int64_t>(that_.GetTotalCompressedSize());
618 #endif
619 }
620
621 virtual void Begin()
622 {
623 transaction_->Begin();
624 }
625
626 virtual void Rollback()
627 {
628 transaction_->Rollback();
629 }
630
631 virtual void Commit(int64_t fileSizeDelta /* only used in debug */)
632 {
633 transaction_->Commit();
634
635 assert(initialDiskSize_ + fileSizeDelta >= 0 &&
636 initialDiskSize_ + fileSizeDelta == static_cast<int64_t>(that_.GetTotalCompressedSize()));
637 }
638 };
639
640
641 IDatabaseWrapper::ITransaction* SQLiteDatabaseWrapper::StartTransaction()
642 {
643 return new Transaction(*this);
644 }
645
646
647 void SQLiteDatabaseWrapper::GetAllMetadata(std::map<MetadataType, std::string>& target,
648 int64_t id)
649 {
650 target.clear();
651
652 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT type, value FROM Metadata WHERE id=?");
653 s.BindInt64(0, id);
654
655 while (s.Step())
656 {
657 MetadataType key = static_cast<MetadataType>(s.ColumnInt(0));
658 target[key] = s.ColumnString(1);
659 }
660 }
661
662
663 void SQLiteDatabaseWrapper::SetGlobalProperty(GlobalProperty property,
664 const std::string& value)
665 {
666 SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT OR REPLACE INTO GlobalProperties VALUES(?, ?)");
667 s.BindInt(0, property);
668 s.BindString(1, value);
669 s.Run();
670 }
671
672
673 bool SQLiteDatabaseWrapper::LookupGlobalProperty(std::string& target,
674 GlobalProperty property)
675 {
676 SQLite::Statement s(db_, SQLITE_FROM_HERE,
677 "SELECT value FROM GlobalProperties WHERE property=?");
678 s.BindInt(0, property);
679
680 if (!s.Step())
681 {
682 return false;
683 }
684 else
685 {
686 target = s.ColumnString(0);
687 return true;
688 }
689 }
690
691
692 int64_t SQLiteDatabaseWrapper::CreateResource(const std::string& publicId,
693 ResourceType type)
694 {
695 SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO Resources VALUES(NULL, ?, ?, NULL)");
696 s.BindInt(0, type);
697 s.BindString(1, publicId);
698 s.Run();
699 return db_.GetLastInsertRowId();
700 }
701
702
703 bool SQLiteDatabaseWrapper::LookupResource(int64_t& id,
704 ResourceType& type,
705 const std::string& publicId)
706 {
707 SQLite::Statement s(db_, SQLITE_FROM_HERE,
708 "SELECT internalId, resourceType FROM Resources WHERE publicId=?");
709 s.BindString(0, publicId);
710
711 if (!s.Step())
712 {
713 return false;
714 }
715 else
716 {
717 id = s.ColumnInt(0);
718 type = static_cast<ResourceType>(s.ColumnInt(1));
719
720 // Check whether there is a single resource with this public id
721 assert(!s.Step());
722
723 return true;
724 }
725 }
726
727
728 void SQLiteDatabaseWrapper::AttachChild(int64_t parent,
729 int64_t child)
730 {
731 SQLite::Statement s(db_, SQLITE_FROM_HERE, "UPDATE Resources SET parentId = ? WHERE internalId = ?");
732 s.BindInt64(0, parent);
733 s.BindInt64(1, child);
734 s.Run();
735 }
736
737
738 void SQLiteDatabaseWrapper::SetMetadata(int64_t id,
739 MetadataType type,
740 const std::string& value)
741 {
742 SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT OR REPLACE INTO Metadata VALUES(?, ?, ?)");
743 s.BindInt64(0, id);
744 s.BindInt(1, type);
745 s.BindString(2, value);
746 s.Run();
747 }
748
749
750 void SQLiteDatabaseWrapper::DeleteMetadata(int64_t id,
751 MetadataType type)
752 {
753 SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM Metadata WHERE id=? and type=?");
754 s.BindInt64(0, id);
755 s.BindInt(1, type);
756 s.Run();
757 }
758
759
760 bool SQLiteDatabaseWrapper::LookupMetadata(std::string& target,
761 int64_t id,
762 MetadataType type)
763 {
764 SQLite::Statement s(db_, SQLITE_FROM_HERE,
765 "SELECT value FROM Metadata WHERE id=? AND type=?");
766 s.BindInt64(0, id);
767 s.BindInt(1, type);
768
769 if (!s.Step())
770 {
771 return false;
772 }
773 else
774 {
775 target = s.ColumnString(0);
776 return true;
777 }
778 }
779
780
781 void SQLiteDatabaseWrapper::AddAttachment(int64_t id,
782 const FileInfo& attachment)
783 {
784 SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO AttachedFiles VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
785 s.BindInt64(0, id);
786 s.BindInt(1, attachment.GetContentType());
787 s.BindString(2, attachment.GetUuid());
788 s.BindInt64(3, attachment.GetCompressedSize());
789 s.BindInt64(4, attachment.GetUncompressedSize());
790 s.BindInt(5, attachment.GetCompressionType());
791 s.BindString(6, attachment.GetUncompressedMD5());
792 s.BindString(7, attachment.GetCompressedMD5());
793 s.Run();
794 }
795
796
797 void SQLiteDatabaseWrapper::DeleteAttachment(int64_t id,
798 FileContentType attachment)
799 {
800 SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM AttachedFiles WHERE id=? AND fileType=?");
801 s.BindInt64(0, id);
802 s.BindInt(1, attachment);
803 s.Run();
804 }
805
806
807 void SQLiteDatabaseWrapper::ListAvailableAttachments(std::list<FileContentType>& target,
808 int64_t id)
809 {
810 target.clear();
811
812 SQLite::Statement s(db_, SQLITE_FROM_HERE,
813 "SELECT fileType FROM AttachedFiles WHERE id=?");
814 s.BindInt64(0, id);
815
816 while (s.Step())
817 {
818 target.push_back(static_cast<FileContentType>(s.ColumnInt(0)));
819 }
820 }
821
822 bool SQLiteDatabaseWrapper::LookupAttachment(FileInfo& attachment,
823 int64_t id,
824 FileContentType contentType)
825 {
826 SQLite::Statement s(db_, SQLITE_FROM_HERE,
827 "SELECT uuid, uncompressedSize, compressionType, compressedSize, "
828 "uncompressedMD5, compressedMD5 FROM AttachedFiles WHERE id=? AND fileType=?");
829 s.BindInt64(0, id);
830 s.BindInt(1, contentType);
831
832 if (!s.Step())
833 {
834 return false;
835 }
836 else
837 {
838 attachment = FileInfo(s.ColumnString(0),
839 contentType,
840 s.ColumnInt64(1),
841 s.ColumnString(4),
842 static_cast<CompressionType>(s.ColumnInt(2)),
843 s.ColumnInt64(3),
844 s.ColumnString(5));
845 return true;
846 }
847 }
848
849
850 void SQLiteDatabaseWrapper::ClearMainDicomTags(int64_t id)
851 {
852 {
853 SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM DicomIdentifiers WHERE id=?");
854 s.BindInt64(0, id);
855 s.Run();
856 }
857
858 {
859 SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM MainDicomTags WHERE id=?");
860 s.BindInt64(0, id);
861 s.Run();
862 }
863 }
864
865
866 void SQLiteDatabaseWrapper::SetMainDicomTag(int64_t id,
867 const DicomTag& tag,
868 const std::string& value)
869 {
870 SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO MainDicomTags VALUES(?, ?, ?, ?)");
871 s.BindInt64(0, id);
872 s.BindInt(1, tag.GetGroup());
873 s.BindInt(2, tag.GetElement());
874 s.BindString(3, value);
875 s.Run();
876 }
877
878
879 void SQLiteDatabaseWrapper::SetIdentifierTag(int64_t id,
880 const DicomTag& tag,
881 const std::string& value)
882 {
883 SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO DicomIdentifiers VALUES(?, ?, ?, ?)");
884 s.BindInt64(0, id);
885 s.BindInt(1, tag.GetGroup());
886 s.BindInt(2, tag.GetElement());
887 s.BindString(3, value);
888 s.Run();
889 }
890
891
892 void SQLiteDatabaseWrapper::GetMainDicomTags(DicomMap& map,
893 int64_t id)
894 {
895 map.Clear();
896
897 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT * FROM MainDicomTags WHERE id=?");
898 s.BindInt64(0, id);
899 while (s.Step())
900 {
901 map.SetValue(s.ColumnInt(1),
902 s.ColumnInt(2),
903 s.ColumnString(3), false);
904 }
905 }
906
907
908 void SQLiteDatabaseWrapper::GetChildrenPublicId(std::list<std::string>& target,
909 int64_t id)
910 {
911 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT a.publicId FROM Resources AS a, Resources AS b "
912 "WHERE a.parentId = b.internalId AND b.internalId = ?");
913 s.BindInt64(0, id);
914
915 target.clear();
916
917 while (s.Step())
918 {
919 target.push_back(s.ColumnString(0));
920 }
921 }
922
923
924 void SQLiteDatabaseWrapper::GetChildrenInternalId(std::list<int64_t>& target,
925 int64_t id)
926 {
927 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT a.internalId FROM Resources AS a, Resources AS b "
928 "WHERE a.parentId = b.internalId AND b.internalId = ?");
929 s.BindInt64(0, id);
930
931 target.clear();
932
933 while (s.Step())
934 {
935 target.push_back(s.ColumnInt64(0));
936 }
937 }
938
939
940 void SQLiteDatabaseWrapper::LogChange(int64_t internalId,
941 const ServerIndexChange& change)
942 {
943 SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO Changes VALUES(NULL, ?, ?, ?, ?)");
944 s.BindInt(0, change.GetChangeType());
945 s.BindInt64(1, internalId);
946 s.BindInt(2, change.GetResourceType());
947 s.BindString(3, change.GetDate());
948 s.Run();
949 }
950
951
952 void SQLiteDatabaseWrapper::LogExportedResource(const ExportedResource& resource)
953 {
954 SQLite::Statement s(db_, SQLITE_FROM_HERE,
955 "INSERT INTO ExportedResources VALUES(NULL, ?, ?, ?, ?, ?, ?, ?, ?)");
956
957 s.BindInt(0, resource.GetResourceType());
958 s.BindString(1, resource.GetPublicId());
959 s.BindString(2, resource.GetModality());
960 s.BindString(3, resource.GetPatientId());
961 s.BindString(4, resource.GetStudyInstanceUid());
962 s.BindString(5, resource.GetSeriesInstanceUid());
963 s.BindString(6, resource.GetSopInstanceUid());
964 s.BindString(7, resource.GetDate());
965 s.Run();
966 }
967
968
969 void SQLiteDatabaseWrapper::GetExportedResources(std::list<ExportedResource>& target,
970 bool& done,
971 int64_t since,
972 uint32_t maxResults)
973 {
974 SQLite::Statement s(db_, SQLITE_FROM_HERE,
975 "SELECT * FROM ExportedResources WHERE seq>? ORDER BY seq LIMIT ?");
976 s.BindInt64(0, since);
977 s.BindInt(1, maxResults + 1);
978 GetExportedResourcesInternal(target, done, s, maxResults);
979 }
980
981
982 void SQLiteDatabaseWrapper::GetLastExportedResource(std::list<ExportedResource>& target)
983 {
984 bool done; // Ignored
985 SQLite::Statement s(db_, SQLITE_FROM_HERE,
986 "SELECT * FROM ExportedResources ORDER BY seq DESC LIMIT 1");
987 GetExportedResourcesInternal(target, done, s, 1);
988 }
989
990
991 uint64_t SQLiteDatabaseWrapper::GetTotalCompressedSize()
992 {
993 // Old SQL query that was used in Orthanc <= 1.5.0:
994 // SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT SUM(compressedSize) FROM AttachedFiles");
995
996 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT value FROM GlobalIntegers WHERE key=0");
997 s.Run();
998 return static_cast<uint64_t>(s.ColumnInt64(0));
999 }
1000
1001
1002 uint64_t SQLiteDatabaseWrapper::GetTotalUncompressedSize()
1003 {
1004 // Old SQL query that was used in Orthanc <= 1.5.0:
1005 // SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT SUM(uncompressedSize) FROM AttachedFiles");
1006
1007 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT value FROM GlobalIntegers WHERE key=1");
1008 s.Run();
1009 return static_cast<uint64_t>(s.ColumnInt64(0));
1010 }
1011
1012
1013 uint64_t SQLiteDatabaseWrapper::GetResourceCount(ResourceType resourceType)
1014 {
1015 SQLite::Statement s(db_, SQLITE_FROM_HERE,
1016 "SELECT COUNT(*) FROM Resources WHERE resourceType=?");
1017 s.BindInt(0, resourceType);
1018
1019 if (!s.Step())
1020 {
1021 return 0;
1022 }
1023 else
1024 {
1025 int64_t c = s.ColumnInt(0);
1026 assert(!s.Step());
1027 return c;
1028 }
1029 }
1030
1031
1032 void SQLiteDatabaseWrapper::GetAllPublicIds(std::list<std::string>& target,
1033 ResourceType resourceType)
1034 {
1035 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT publicId FROM Resources WHERE resourceType=?");
1036 s.BindInt(0, resourceType);
1037
1038 target.clear();
1039 while (s.Step())
1040 {
1041 target.push_back(s.ColumnString(0));
1042 }
1043 }
1044
1045
1046 void SQLiteDatabaseWrapper::GetAllPublicIds(std::list<std::string>& target,
1047 ResourceType resourceType,
1048 size_t since,
1049 size_t limit)
1050 {
1051 if (limit == 0)
1052 {
1053 target.clear();
1054 return;
1055 }
1056
1057 SQLite::Statement s(db_, SQLITE_FROM_HERE,
1058 "SELECT publicId FROM Resources WHERE "
1059 "resourceType=? LIMIT ? OFFSET ?");
1060 s.BindInt(0, resourceType);
1061 s.BindInt64(1, limit);
1062 s.BindInt64(2, since);
1063
1064 target.clear();
1065 while (s.Step())
1066 {
1067 target.push_back(s.ColumnString(0));
1068 }
1069 }
1070
1071
1072 bool SQLiteDatabaseWrapper::SelectPatientToRecycle(int64_t& internalId)
1073 {
1074 SQLite::Statement s(db_, SQLITE_FROM_HERE,
1075 "SELECT patientId FROM PatientRecyclingOrder ORDER BY seq ASC LIMIT 1");
1076
1077 if (!s.Step())
1078 {
1079 // No patient remaining or all the patients are protected
1080 return false;
1081 }
1082 else
1083 {
1084 internalId = s.ColumnInt(0);
1085 return true;
1086 }
1087 }
1088
1089
1090 bool SQLiteDatabaseWrapper::SelectPatientToRecycle(int64_t& internalId,
1091 int64_t patientIdToAvoid)
1092 {
1093 SQLite::Statement s(db_, SQLITE_FROM_HERE,
1094 "SELECT patientId FROM PatientRecyclingOrder "
1095 "WHERE patientId != ? ORDER BY seq ASC LIMIT 1");
1096 s.BindInt64(0, patientIdToAvoid);
1097
1098 if (!s.Step())
1099 {
1100 // No patient remaining or all the patients are protected
1101 return false;
1102 }
1103 else
1104 {
1105 internalId = s.ColumnInt(0);
1106 return true;
1107 }
1108 }
1109
1110
1111 bool SQLiteDatabaseWrapper::IsProtectedPatient(int64_t internalId)
1112 {
1113 SQLite::Statement s(db_, SQLITE_FROM_HERE,
1114 "SELECT * FROM PatientRecyclingOrder WHERE patientId = ?");
1115 s.BindInt64(0, internalId);
1116 return !s.Step();
1117 }
1118
1119
1120 void SQLiteDatabaseWrapper::SetProtectedPatient(int64_t internalId,
1121 bool isProtected)
1122 {
1123 if (isProtected)
1124 {
1125 SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM PatientRecyclingOrder WHERE patientId=?");
1126 s.BindInt64(0, internalId);
1127 s.Run();
1128 }
1129 else if (IsProtectedPatient(internalId))
1130 {
1131 SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO PatientRecyclingOrder VALUES(NULL, ?)");
1132 s.BindInt64(0, internalId);
1133 s.Run();
1134 }
1135 else
1136 {
1137 // Nothing to do: The patient is already unprotected
1138 }
1139 }
1140
1141
1142 bool SQLiteDatabaseWrapper::IsExistingResource(int64_t internalId)
1143 {
1144 SQLite::Statement s(db_, SQLITE_FROM_HERE,
1145 "SELECT * FROM Resources WHERE internalId=?");
1146 s.BindInt64(0, internalId);
1147 return s.Step();
1148 }
1149
1150
1151 bool SQLiteDatabaseWrapper::IsDiskSizeAbove(uint64_t threshold)
1152 {
1153 return GetTotalCompressedSize() > threshold;
1154 }
1155
1156
1157
1158 class SQLiteDatabaseWrapper::LookupFormatter : public ISqlLookupFormatter
1159 {
1160 private:
1161 std::list<std::string> values_;
1162
1163 public:
1164 virtual std::string GenerateParameter(const std::string& value)
1165 {
1166 values_.push_back(value);
1167 return "?";
1168 }
1169
1170 virtual std::string FormatResourceType(ResourceType level)
1171 {
1172 return boost::lexical_cast<std::string>(level);
1173 }
1174
1175 virtual std::string FormatWildcardEscape()
1176 {
1177 return "ESCAPE '\\'";
1178 }
1179
1180 void Bind(SQLite::Statement& statement) const
1181 {
1182 size_t pos = 0;
1183
1184 for (std::list<std::string>::const_iterator
1185 it = values_.begin(); it != values_.end(); ++it, pos++)
1186 {
1187 statement.BindString(pos, *it);
1188 }
1189 }
1190 };
1191
1192
1193 static void AnswerLookup(std::list<std::string>& resourcesId,
1194 std::list<std::string>& instancesId,
1195 SQLite::Connection& db,
1196 ResourceType level)
1197 {
1198 resourcesId.clear();
1199 instancesId.clear();
1200
1201 std::unique_ptr<SQLite::Statement> statement;
1202
1203 switch (level)
1204 {
1205 case ResourceType_Patient:
1206 {
1207 statement.reset(
1208 new SQLite::Statement(
1209 db, SQLITE_FROM_HERE,
1210 "SELECT patients.publicId, instances.publicID FROM Lookup AS patients "
1211 "INNER JOIN Resources studies ON patients.internalId=studies.parentId "
1212 "INNER JOIN Resources series ON studies.internalId=series.parentId "
1213 "INNER JOIN Resources instances ON series.internalId=instances.parentId "
1214 "GROUP BY patients.publicId"));
1215
1216 break;
1217 }
1218
1219 case ResourceType_Study:
1220 {
1221 statement.reset(
1222 new SQLite::Statement(
1223 db, SQLITE_FROM_HERE,
1224 "SELECT studies.publicId, instances.publicID FROM Lookup AS studies "
1225 "INNER JOIN Resources series ON studies.internalId=series.parentId "
1226 "INNER JOIN Resources instances ON series.internalId=instances.parentId "
1227 "GROUP BY studies.publicId"));
1228
1229 break;
1230 }
1231
1232 case ResourceType_Series:
1233 {
1234 statement.reset(
1235 new SQLite::Statement(
1236 db, SQLITE_FROM_HERE,
1237 "SELECT series.publicId, instances.publicID FROM Lookup AS series "
1238 "INNER JOIN Resources instances ON series.internalId=instances.parentId "
1239 "GROUP BY series.publicId"));
1240
1241 break;
1242 }
1243
1244 case ResourceType_Instance:
1245 {
1246 statement.reset(
1247 new SQLite::Statement(
1248 db, SQLITE_FROM_HERE, "SELECT publicId, publicId FROM Lookup"));
1249
1250 break;
1251 }
1252
1253 default:
1254 throw OrthancException(ErrorCode_InternalError);
1255 }
1256
1257 assert(statement.get() != NULL);
1258
1259 while (statement->Step())
1260 {
1261 resourcesId.push_back(statement->ColumnString(0));
1262 instancesId.push_back(statement->ColumnString(1));
1263 }
1264 }
1265
1266
1267 void SQLiteDatabaseWrapper::ApplyLookupResources(std::list<std::string>& resourcesId,
1268 std::list<std::string>* instancesId,
1269 const std::vector<DatabaseConstraint>& lookup,
1270 ResourceType queryLevel,
1271 size_t limit)
1272 {
1273 LookupFormatter formatter;
1274
1275 std::string sql;
1276 LookupFormatter::Apply(sql, formatter, lookup, queryLevel, limit);
1277
1278 sql = "CREATE TEMPORARY TABLE Lookup AS " + sql;
1279
1280 {
1281 SQLite::Statement s(db_, SQLITE_FROM_HERE, "DROP TABLE IF EXISTS Lookup");
1282 s.Run();
1283 }
1284
1285 {
1286 SQLite::Statement statement(db_, sql);
1287 formatter.Bind(statement);
1288 statement.Run();
1289 }
1290
1291 if (instancesId != NULL)
1292 {
1293 AnswerLookup(resourcesId, *instancesId, db_, queryLevel);
1294 }
1295 else
1296 {
1297 resourcesId.clear();
1298
1299 SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT publicId FROM Lookup");
1300
1301 while (s.Step())
1302 {
1303 resourcesId.push_back(s.ColumnString(0));
1304 }
1305 }
1306 }
1307
1308
1309 int64_t SQLiteDatabaseWrapper::GetLastChangeIndex()
1310 {
1311 SQLite::Statement s(db_, SQLITE_FROM_HERE,
1312 "SELECT seq FROM sqlite_sequence WHERE name='Changes'");
1313
1314 if (s.Step())
1315 {
1316 int64_t c = s.ColumnInt(0);
1317 assert(!s.Step());
1318 return c;
1319 }
1320 else
1321 {
1322 // No change has been recorded so far in the database
1323 return 0;
1324 }
1325 }
1326
1327
1328 void SQLiteDatabaseWrapper::TagMostRecentPatient(int64_t patient)
1329 {
1330 {
1331 SQLite::Statement s(db_, SQLITE_FROM_HERE,
1332 "DELETE FROM PatientRecyclingOrder WHERE patientId=?");
1333 s.BindInt64(0, patient);
1334 s.Run();
1335
1336 assert(db_.GetLastChangeCount() == 0 ||
1337 db_.GetLastChangeCount() == 1);
1338
1339 if (db_.GetLastChangeCount() == 0)
1340 {
1341 // The patient was protected, there was nothing to delete from the recycling order
1342 return;
1343 }
1344 }
1345
1346 {
1347 SQLite::Statement s(db_, SQLITE_FROM_HERE,
1348 "INSERT INTO PatientRecyclingOrder VALUES(NULL, ?)");
1349 s.BindInt64(0, patient);
1350 s.Run();
1351 }
1352 }
1353 }