1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
|
/**
* Orthanc - A Lightweight, RESTful DICOM Store
* Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
* Department, University Hospital of Liege, Belgium
* Copyright (C) 2017-2023 Osimis S.A., Belgium
* Copyright (C) 2021-2023 Sebastien Jodogne, ICTEAM UCLouvain, Belgium
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
#include "PostgreSQLIndex.h"
#include "../../Framework/Plugins/GlobalProperties.h"
#include "../../Framework/PostgreSQL/PostgreSQLDatabase.h"
#include "../../Framework/PostgreSQL/PostgreSQLTransaction.h"
#include "PostgreSQLDefinitions.h"
#include <EmbeddedResources.h> // Auto-generated file
#include <Compatibility.h> // For std::unique_ptr<>
#include <Logging.h>
#include <OrthancException.h>
namespace Orthanc
{
// Some aliases for internal properties
static const GlobalProperty GlobalProperty_HasTrigramIndex = GlobalProperty_DatabaseInternal0;
static const GlobalProperty GlobalProperty_HasCreateInstance = GlobalProperty_DatabaseInternal1;
static const GlobalProperty GlobalProperty_HasFastCountResources = GlobalProperty_DatabaseInternal2;
static const GlobalProperty GlobalProperty_GetLastChangeIndex = GlobalProperty_DatabaseInternal3;
}
namespace OrthancDatabases
{
PostgreSQLIndex::PostgreSQLIndex(OrthancPluginContext* context,
const PostgreSQLParameters& parameters) :
IndexBackend(context),
parameters_(parameters),
clearAll_(false)
{
}
IDatabaseFactory* PostgreSQLIndex::CreateDatabaseFactory()
{
return PostgreSQLDatabase::CreateDatabaseFactory(parameters_);
}
void PostgreSQLIndex::ConfigureDatabase(DatabaseManager& manager,
bool hasIdentifierTags,
const std::list<IdentifierTag>& identifierTags)
{
uint32_t expectedVersion = 6;
if (GetContext()) // "GetContext()" can possibly be NULL in the unit tests
{
expectedVersion = OrthancPluginGetExpectedDatabaseVersion(GetContext());
}
// Check the expected version of the database
if (expectedVersion != 6)
{
LOG(ERROR) << "This database plugin is incompatible with your version of Orthanc "
<< "expecting the DB schema version " << expectedVersion
<< ", but this plugin is only compatible with version 6";
throw Orthanc::OrthancException(Orthanc::ErrorCode_Plugin);
}
PostgreSQLDatabase& db = dynamic_cast<PostgreSQLDatabase&>(manager.GetDatabase());
if (parameters_.HasLock())
{
db.AdvisoryLock(POSTGRESQL_LOCK_INDEX);
}
{
PostgreSQLDatabase::TransientAdvisoryLock lock(db, POSTGRESQL_LOCK_DATABASE_SETUP);
if (clearAll_)
{
db.ClearAll();
}
{
DatabaseManager::Transaction t(manager, TransactionType_ReadWrite);
if (!t.GetDatabaseTransaction().DoesTableExist("Resources"))
{
std::string query;
Orthanc::EmbeddedResources::GetFileResource
(query, Orthanc::EmbeddedResources::POSTGRESQL_PREPARE_INDEX);
t.GetDatabaseTransaction().ExecuteMultiLines(query);
SetGlobalIntegerProperty(manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_DatabaseSchemaVersion, expectedVersion);
SetGlobalIntegerProperty(manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_DatabasePatchLevel, 1);
SetGlobalIntegerProperty(manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_HasTrigramIndex, 0);
}
if (!t.GetDatabaseTransaction().DoesTableExist("Resources"))
{
LOG(ERROR) << "Corrupted PostgreSQL database";
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
int version = 0;
if (!LookupGlobalIntegerProperty(version, manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_DatabaseSchemaVersion) ||
version != 6)
{
LOG(ERROR) << "PostgreSQL plugin is incompatible with database schema version: " << version;
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
int revision;
if (!LookupGlobalIntegerProperty(revision, manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_DatabasePatchLevel))
{
revision = 1;
SetGlobalIntegerProperty(manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_DatabasePatchLevel, revision);
}
if (revision != 1)
{
LOG(ERROR) << "PostgreSQL plugin is incompatible with database schema revision: " << revision;
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
t.Commit();
}
{
DatabaseManager::Transaction t(manager, TransactionType_ReadWrite);
int hasTrigram = 0;
if (!LookupGlobalIntegerProperty(hasTrigram, manager, MISSING_SERVER_IDENTIFIER,
Orthanc::GlobalProperty_HasTrigramIndex) ||
hasTrigram != 1)
{
/**
* Apply fix for performance issue (speed up wildcard search
* by using GIN trigrams). This implements the patch suggested
* in issue #47, BUT we also keep the original
* "DicomIdentifiersIndexValues", as it leads to better
* performance for "strict" searches (i.e. searches involving
* no wildcard).
* https://www.postgresql.org/docs/current/static/pgtrgm.html
* https://bugs.orthanc-server.com/show_bug.cgi?id=47
**/
try
{
// We've observed 9 minutes on DB with 100000 studies
LOG(WARNING) << "Trying to enable trigram matching on the PostgreSQL database "
<< "to speed up wildcard searches. This may take several minutes";
t.GetDatabaseTransaction().ExecuteMultiLines(
"CREATE EXTENSION IF NOT EXISTS pg_trgm; "
"CREATE INDEX DicomIdentifiersIndexValues2 ON DicomIdentifiers USING gin(value gin_trgm_ops);");
SetGlobalIntegerProperty(manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_HasTrigramIndex, 1);
LOG(WARNING) << "Trigram index has been created";
t.Commit();
}
catch (Orthanc::OrthancException&)
{
LOG(WARNING) << "Performance warning: Your PostgreSQL server does "
<< "not support trigram matching";
LOG(WARNING) << "-> Consider installing the \"pg_trgm\" extension on the "
<< "PostgreSQL server, e.g. on Debian: sudo apt install postgresql-contrib";
}
}
else
{
t.Commit();
}
}
{
DatabaseManager::Transaction t(manager, TransactionType_ReadWrite);
int property = 0;
if (!LookupGlobalIntegerProperty(property, manager, MISSING_SERVER_IDENTIFIER,
Orthanc::GlobalProperty_HasCreateInstance) ||
property != 2)
{
LOG(INFO) << "Installing the CreateInstance extension";
if (property == 1)
{
// Drop older, experimental versions of this extension
t.GetDatabaseTransaction().ExecuteMultiLines("DROP FUNCTION CreateInstance("
"IN patient TEXT, IN study TEXT, IN series TEXT, in instance TEXT)");
}
std::string query;
Orthanc::EmbeddedResources::GetFileResource
(query, Orthanc::EmbeddedResources::POSTGRESQL_CREATE_INSTANCE);
t.GetDatabaseTransaction().ExecuteMultiLines(query);
SetGlobalIntegerProperty(manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_HasCreateInstance, 2);
}
if (!LookupGlobalIntegerProperty(property, manager, MISSING_SERVER_IDENTIFIER,
Orthanc::GlobalProperty_GetTotalSizeIsFast) ||
property != 1)
{
LOG(INFO) << "Installing the FastTotalSize extension";
std::string query;
Orthanc::EmbeddedResources::GetFileResource
(query, Orthanc::EmbeddedResources::POSTGRESQL_FAST_TOTAL_SIZE);
t.GetDatabaseTransaction().ExecuteMultiLines(query);
SetGlobalIntegerProperty(manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_GetTotalSizeIsFast, 1);
}
// Installing this extension requires the "GlobalIntegers" table
// created by the "FastTotalSize" extension
property = 0;
if (!LookupGlobalIntegerProperty(property, manager, MISSING_SERVER_IDENTIFIER,
Orthanc::GlobalProperty_HasFastCountResources) ||
property != 1)
{
LOG(INFO) << "Installing the FastCountResources extension";
std::string query;
Orthanc::EmbeddedResources::GetFileResource
(query, Orthanc::EmbeddedResources::POSTGRESQL_FAST_COUNT_RESOURCES);
t.GetDatabaseTransaction().ExecuteMultiLines(query);
SetGlobalIntegerProperty(manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_HasFastCountResources, 1);
}
// Installing this extension requires the "GlobalIntegers" table
// created by the "GetLastChangeIndex" extension
property = 0;
if (!LookupGlobalIntegerProperty(property, manager, MISSING_SERVER_IDENTIFIER,
Orthanc::GlobalProperty_GetLastChangeIndex) ||
property != 1)
{
LOG(INFO) << "Installing the GetLastChangeIndex extension";
std::string query;
Orthanc::EmbeddedResources::GetFileResource
(query, Orthanc::EmbeddedResources::POSTGRESQL_GET_LAST_CHANGE_INDEX);
t.GetDatabaseTransaction().ExecuteMultiLines(query);
SetGlobalIntegerProperty(manager, MISSING_SERVER_IDENTIFIER, Orthanc::GlobalProperty_GetLastChangeIndex, 1);
}
t.Commit();
}
{
// New in release 4.0 to deal with multiple writers
DatabaseManager::Transaction t(manager, TransactionType_ReadWrite);
if (!t.GetDatabaseTransaction().DoesTableExist("ServerProperties"))
{
t.GetDatabaseTransaction().ExecuteMultiLines("CREATE TABLE ServerProperties(server VARCHAR(64) NOT NULL, "
"property INTEGER, value TEXT, PRIMARY KEY(server, property))");
}
/**
* PostgreSQL 9.5: "Adding a column with a default requires
* updating each row of the table (to store the new column
* value). However, if no default is specified, PostgreSQL is
* able to avoid the physical update." => We set no default
* for performance (older entries will be NULL)
* https://www.postgresql.org/docs/9.5/ddl-alter.html
**/
if (!db.DoesColumnExist("Metadata", "revision"))
{
t.GetDatabaseTransaction().ExecuteMultiLines("ALTER TABLE Metadata ADD COLUMN revision INTEGER");
}
if (!db.DoesColumnExist("AttachedFiles", "revision"))
{
t.GetDatabaseTransaction().ExecuteMultiLines("ALTER TABLE AttachedFiles ADD COLUMN revision INTEGER");
}
t.Commit();
}
{
// New in release 5.0 to deal with labels
DatabaseManager::Transaction t(manager, TransactionType_ReadWrite);
if (!t.GetDatabaseTransaction().DoesTableExist("Labels"))
{
t.GetDatabaseTransaction().ExecuteMultiLines(
"CREATE TABLE Labels("
"id BIGINT REFERENCES Resources(internalId) ON DELETE CASCADE,"
"label TEXT, PRIMARY KEY(id, label));"
"CREATE INDEX LabelsIndex1 ON LABELS(id);"
"CREATE INDEX LabelsIndex2 ON LABELS(label);");
}
t.Commit();
}
}
}
int64_t PostgreSQLIndex::CreateResource(DatabaseManager& manager,
const char* publicId,
OrthancPluginResourceType type)
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager,
"INSERT INTO Resources VALUES(DEFAULT, ${type}, ${id}, NULL) RETURNING internalId");
statement.SetParameterType("id", ValueType_Utf8String);
statement.SetParameterType("type", ValueType_Integer64);
Dictionary args;
args.SetUtf8Value("id", publicId);
args.SetIntegerValue("type", static_cast<int>(type));
statement.Execute(args);
return statement.ReadInteger64(0);
}
uint64_t PostgreSQLIndex::GetTotalCompressedSize(DatabaseManager& manager)
{
// Fast version if extension "./FastTotalSize.sql" is installed
uint64_t result;
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager,
"SELECT value FROM GlobalIntegers WHERE key = 0");
statement.SetReadOnly(true);
statement.Execute();
result = static_cast<uint64_t>(statement.ReadInteger64(0));
}
assert(result == IndexBackend::GetTotalCompressedSize(manager));
return result;
}
uint64_t PostgreSQLIndex::GetTotalUncompressedSize(DatabaseManager& manager)
{
// Fast version if extension "./FastTotalSize.sql" is installed
uint64_t result;
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager,
"SELECT value FROM GlobalIntegers WHERE key = 1");
statement.SetReadOnly(true);
statement.Execute();
result = static_cast<uint64_t>(statement.ReadInteger64(0));
}
assert(result == IndexBackend::GetTotalUncompressedSize(manager));
return result;
}
#if ORTHANC_PLUGINS_HAS_DATABASE_CONSTRAINT == 1
void PostgreSQLIndex::CreateInstance(OrthancPluginCreateInstanceResult& result,
DatabaseManager& manager,
const char* hashPatient,
const char* hashStudy,
const char* hashSeries,
const char* hashInstance)
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager,
"SELECT * FROM CreateInstance(${patient}, ${study}, ${series}, ${instance})");
statement.SetParameterType("patient", ValueType_Utf8String);
statement.SetParameterType("study", ValueType_Utf8String);
statement.SetParameterType("series", ValueType_Utf8String);
statement.SetParameterType("instance", ValueType_Utf8String);
Dictionary args;
args.SetUtf8Value("patient", hashPatient);
args.SetUtf8Value("study", hashStudy);
args.SetUtf8Value("series", hashSeries);
args.SetUtf8Value("instance", hashInstance);
statement.Execute(args);
if (statement.IsDone() ||
statement.GetResultFieldsCount() != 8)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
for (size_t i = 0; i < 8; i++)
{
statement.SetResultFieldType(i, ValueType_Integer64);
}
result.isNewInstance = (statement.ReadInteger64(3) == 1);
result.instanceId = statement.ReadInteger64(7);
if (result.isNewInstance)
{
result.isNewPatient = (statement.ReadInteger64(0) == 1);
result.isNewStudy = (statement.ReadInteger64(1) == 1);
result.isNewSeries = (statement.ReadInteger64(2) == 1);
result.patientId = statement.ReadInteger64(4);
result.studyId = statement.ReadInteger64(5);
result.seriesId = statement.ReadInteger64(6);
}
}
#endif
uint64_t PostgreSQLIndex::GetResourcesCount(DatabaseManager& manager,
OrthancPluginResourceType resourceType)
{
// Optimized version thanks to the "FastCountResources.sql" extension
assert(OrthancPluginResourceType_Patient == 0 &&
OrthancPluginResourceType_Study == 1 &&
OrthancPluginResourceType_Series == 2 &&
OrthancPluginResourceType_Instance == 3);
uint64_t result;
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager,
"SELECT value FROM GlobalIntegers WHERE key = ${key}");
statement.SetParameterType("key", ValueType_Integer64);
Dictionary args;
// For an explanation of the "+ 2" below, check out "FastCountResources.sql"
args.SetIntegerValue("key", static_cast<int>(resourceType + 2));
statement.SetReadOnly(true);
statement.Execute(args);
result = static_cast<uint64_t>(statement.ReadInteger64(0));
}
assert(result == IndexBackend::GetResourcesCount(manager, resourceType));
return result;
}
int64_t PostgreSQLIndex::GetLastChangeIndex(DatabaseManager& manager)
{
DatabaseManager::CachedStatement statement(
STATEMENT_FROM_HERE, manager,
"SELECT value FROM GlobalIntegers WHERE key = 6");
statement.SetReadOnly(true);
statement.Execute();
return statement.ReadInteger64(0);
}
void PostgreSQLIndex::TagMostRecentPatient(DatabaseManager& manager,
int64_t patient)
{
// This behavior is implemented in "CreateInstance()", and no
// backward compatibility is necessary
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
}
|