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 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
|
/**
* 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 "DatabaseManager.h"
#include "Integer64Value.h"
#include "BinaryStringValue.h"
#include "Utf8StringValue.h"
#include <Compatibility.h> // For std::unique_ptr<>
#include <Logging.h>
#include <OrthancException.h>
#include <boost/thread.hpp>
namespace OrthancDatabases
{
void DatabaseManager::Close()
{
LOG(TRACE) << "Closing the connection to the database";
// Rollback active transaction, if any
transaction_.reset(NULL);
// Delete all the cached statements (must occur before closing
// the database)
for (CachedStatements::iterator it = cachedStatements_.begin();
it != cachedStatements_.end(); ++it)
{
assert(it->second != NULL);
delete it->second;
}
cachedStatements_.clear();
// Close the database
database_.reset(NULL);
LOG(TRACE) << "Connection to the database is closed";
}
void DatabaseManager::CloseIfUnavailable(Orthanc::ErrorCode e)
{
if (e != Orthanc::ErrorCode_Success
#if ORTHANC_FRAMEWORK_VERSION_IS_ABOVE(1, 9, 2)
&& e != Orthanc::ErrorCode_DatabaseCannotSerialize
#endif
)
{
transaction_.reset(NULL);
}
if (e == Orthanc::ErrorCode_DatabaseUnavailable)
{
LOG(ERROR) << "The database is not available, closing the connection";
Close();
}
}
IPrecompiledStatement* DatabaseManager::LookupCachedStatement(const StatementLocation& location) const
{
CachedStatements::const_iterator found = cachedStatements_.find(location);
if (found == cachedStatements_.end())
{
return NULL;
}
else
{
assert(found->second != NULL);
return found->second;
}
}
IPrecompiledStatement& DatabaseManager::CacheStatement(const StatementLocation& location,
const Query& query)
{
LOG(TRACE) << "Caching statement from " << location.GetFile() << ":" << location.GetLine();
std::unique_ptr<IPrecompiledStatement> statement(GetDatabase().Compile(query));
IPrecompiledStatement* tmp = statement.get();
if (tmp == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
assert(cachedStatements_.find(location) == cachedStatements_.end());
cachedStatements_[location] = statement.release();
return *tmp;
}
ITransaction& DatabaseManager::GetTransaction()
{
if (transaction_.get() == NULL)
{
LOG(TRACE) << "Automatically creating an implicit database transaction";
try
{
transaction_.reset(GetDatabase().CreateTransaction(TransactionType_Implicit));
}
catch (Orthanc::OrthancException& e)
{
CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
assert(transaction_.get() != NULL);
return *transaction_;
}
void DatabaseManager::ReleaseImplicitTransaction()
{
if (transaction_.get() != NULL &&
transaction_->IsImplicit())
{
LOG(TRACE) << "Committing an implicit database transaction";
try
{
transaction_->Commit();
transaction_.reset(NULL);
}
catch (Orthanc::OrthancException& e)
{
// Don't throw the exception, as we are in CachedStatement destructor
LOG(ERROR) << "Error while committing an implicit database transaction: " << e.What();
}
}
}
DatabaseManager::DatabaseManager(IDatabaseFactory* factory) :
factory_(factory),
dialect_(Dialect_Unknown)
{
if (factory == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
}
}
IDatabase& DatabaseManager::GetDatabase()
{
assert(factory_.get() != NULL);
if (database_.get() == NULL)
{
database_.reset(factory_->Open());
if (database_.get() == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
dialect_ = database_->GetDialect();
if (dialect_ == Dialect_Unknown)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
}
return *database_;
}
Dialect DatabaseManager::GetDialect() const
{
if (database_.get() == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
else
{
assert(dialect_ != Dialect_Unknown);
return dialect_;
}
}
void DatabaseManager::StartTransaction(TransactionType type)
{
try
{
if (transaction_.get() != NULL)
{
LOG(ERROR) << "Cannot start another transaction while there is an uncommitted transaction";
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
transaction_.reset(GetDatabase().CreateTransaction(type));
}
catch (Orthanc::OrthancException& e)
{
CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
void DatabaseManager::CommitTransaction()
{
if (transaction_.get() == NULL)
{
LOG(ERROR) << "Cannot commit a non-existing transaction";
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
else
{
try
{
transaction_->Commit();
transaction_.reset(NULL);
}
catch (Orthanc::OrthancException& e)
{
CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
}
void DatabaseManager::RollbackTransaction()
{
if (transaction_.get() == NULL)
{
LOG(INFO) << "Cannot rollback a non-existing transaction";
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
else
{
try
{
transaction_->Rollback();
transaction_.reset(NULL);
}
catch (Orthanc::OrthancException& e)
{
CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
}
DatabaseManager::Transaction::Transaction(DatabaseManager& manager,
TransactionType type) :
manager_(manager),
database_(manager.GetDatabase()),
active_(true)
{
manager_.StartTransaction(type);
}
DatabaseManager::Transaction::~Transaction()
{
if (active_)
{
try
{
manager_.RollbackTransaction();
}
catch (Orthanc::OrthancException& e)
{
// Don't rethrow the exception as we are in a destructor
LOG(ERROR) << "Uncatched error during some transaction rollback: " << e.What();
}
}
}
void DatabaseManager::Transaction::Commit()
{
if (active_)
{
manager_.CommitTransaction();
active_ = false;
}
else
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
}
void DatabaseManager::Transaction::Rollback()
{
if (active_)
{
manager_.RollbackTransaction();
active_ = false;
}
else
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
}
IResult& DatabaseManager::StatementBase::GetResult() const
{
if (result_.get() == NULL)
{
LOG(ERROR) << "Accessing the results of a statement without having executed it";
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
return *result_;
}
void DatabaseManager::StatementBase::SetQuery(Query* query)
{
std::unique_ptr<Query> protection(query);
if (query_.get() != NULL)
{
LOG(ERROR) << "Cannot set twice a query";
throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
}
if (query == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
}
query_.reset(protection.release());
}
void DatabaseManager::StatementBase::SetResult(IResult* result)
{
if (result == NULL)
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
}
else
{
result_.reset(result);
}
}
DatabaseManager::StatementBase::StatementBase(DatabaseManager& manager) :
manager_(manager),
transaction_(manager_.GetTransaction())
{
}
DatabaseManager::StatementBase::~StatementBase()
{
manager_.ReleaseImplicitTransaction();
}
void DatabaseManager::StatementBase::SetReadOnly(bool readOnly)
{
if (query_.get() != NULL)
{
query_->SetReadOnly(readOnly);
}
}
void DatabaseManager::StatementBase::SetParameterType(const std::string& parameter,
ValueType type)
{
if (query_.get() != NULL)
{
query_->SetType(parameter, type);
}
}
bool DatabaseManager::StatementBase::IsDone() const
{
try
{
return GetResult().IsDone();
}
catch (Orthanc::OrthancException& e)
{
manager_.CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
void DatabaseManager::StatementBase::Next()
{
try
{
GetResult().Next();
}
catch (Orthanc::OrthancException& e)
{
manager_.CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
size_t DatabaseManager::StatementBase::GetResultFieldsCount() const
{
try
{
return GetResult().GetFieldsCount();
}
catch (Orthanc::OrthancException& e)
{
manager_.CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
void DatabaseManager::StatementBase::SetResultFieldType(size_t field,
ValueType type)
{
try
{
if (!GetResult().IsDone())
{
GetResult().SetExpectedType(field, type);
}
}
catch (Orthanc::OrthancException& e)
{
manager_.CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
const IValue& DatabaseManager::StatementBase::GetResultField(size_t index) const
{
try
{
return GetResult().GetField(index);
}
catch (Orthanc::OrthancException& e)
{
manager_.CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
int64_t DatabaseManager::StatementBase::ReadInteger64(size_t field) const
{
if (IsDone())
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
else
{
const IValue& value = GetResultField(field);
switch (value.GetType())
{
case ValueType_Integer64:
return dynamic_cast<const Integer64Value&>(value).GetValue();
default:
//LOG(ERROR) << value.Format();
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
}
}
int32_t DatabaseManager::StatementBase::ReadInteger32(size_t field) const
{
if (IsDone())
{
throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
}
else
{
int64_t value = ReadInteger64(field);
if (value != static_cast<int64_t>(static_cast<int32_t>(value)))
{
LOG(ERROR) << "Integer overflow";
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
else
{
return static_cast<int32_t>(value);
}
}
}
std::string DatabaseManager::StatementBase::ReadString(size_t field) const
{
const IValue& value = GetResultField(field);
switch (value.GetType())
{
case ValueType_BinaryString:
return dynamic_cast<const BinaryStringValue&>(value).GetContent();
case ValueType_Utf8String:
return dynamic_cast<const Utf8StringValue&>(value).GetContent();
default:
//LOG(ERROR) << value.Format();
throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
}
}
DatabaseManager::CachedStatement::CachedStatement(const StatementLocation& location,
DatabaseManager& manager,
const std::string& sql) :
StatementBase(manager),
location_(location)
{
statement_ = GetManager().LookupCachedStatement(location_);
if (statement_ == NULL)
{
SetQuery(new Query(sql));
}
else
{
LOG(TRACE) << "Reusing cached statement from "
<< location_.GetFile() << ":" << location_.GetLine();
}
}
void DatabaseManager::CachedStatement::Execute(const Dictionary& parameters)
{
try
{
std::unique_ptr<Query> query(ReleaseQuery());
if (query.get() != NULL)
{
// Register the newly-created statement
assert(statement_ == NULL);
statement_ = &GetManager().CacheStatement(location_, *query);
}
assert(statement_ != NULL);
/*
TODO - Sample code to monitor the execution time of each
cached statement, and publish it as an Orthanc metrics
#if HAS_ORTHANC_PLUGIN_METRICS == 1
std::string name = (std::string(location_.GetFile()) + "_" +
boost::lexical_cast<std::string>(location_.GetLine()));
OrthancPlugins::MetricsTimer timer(name.c_str());
#endif
*/
SetResult(GetTransaction().Execute(*statement_, parameters));
}
catch (Orthanc::OrthancException& e)
{
GetManager().CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
DatabaseManager::StandaloneStatement::StandaloneStatement(DatabaseManager& manager,
const std::string& sql) :
StatementBase(manager)
{
SetQuery(new Query(sql));
}
DatabaseManager::StandaloneStatement::~StandaloneStatement()
{
// The result must be removed before the statement, cf. (*)
ClearResult();
statement_.reset();
}
void DatabaseManager::StandaloneStatement::Execute(const Dictionary& parameters)
{
try
{
std::unique_ptr<Query> query(ReleaseQuery());
assert(query.get() != NULL);
// The "statement_" object must be kept as long as the "IResult"
// is not destroyed, as the "IResult" can make calls to the
// statement (this is the case for SQLite and MySQL) - (*)
statement_.reset(GetManager().GetDatabase().Compile(*query));
assert(statement_.get() != NULL);
SetResult(GetTransaction().Execute(*statement_, parameters));
}
catch (Orthanc::OrthancException& e)
{
GetManager().CloseIfUnavailable(e.GetErrorCode());
throw;
}
}
}
|