comparison Framework/Common/DatabaseManager.cpp @ 0:7cea966b6829

initial commit
author Sebastien Jodogne <s.jodogne@gmail.com>
date Wed, 04 Jul 2018 08:16:29 +0200
parents
children 41543239072d
comparison
equal deleted inserted replaced
-1:000000000000 0:7cea966b6829
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-2018 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 Affero General Public License
9 * as published by the Free Software Foundation, either version 3 of
10 * the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Affero General Public License for more details.
16 *
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 **/
20
21
22 #include "DatabaseManager.h"
23
24 #include <Core/Logging.h>
25 #include <Core/OrthancException.h>
26
27 #include <boost/thread.hpp>
28
29 namespace OrthancDatabases
30 {
31 IDatabase& DatabaseManager::GetDatabase()
32 {
33 static const unsigned int MAX_CONNECTION_ATTEMPTS = 10; // TODO: Parameter
34
35 unsigned int count = 0;
36
37 while (database_.get() == NULL)
38 {
39 transaction_.reset(NULL);
40
41 try
42 {
43 database_.reset(factory_->Open());
44 }
45 catch (Orthanc::OrthancException& e)
46 {
47 if (e.GetErrorCode() == Orthanc::ErrorCode_DatabaseUnavailable)
48 {
49 count ++;
50
51 if (count <= MAX_CONNECTION_ATTEMPTS)
52 {
53 LOG(WARNING) << "Database is currently unavailable, retrying...";
54 boost::this_thread::sleep(boost::posix_time::seconds(1));
55 continue;
56 }
57 else
58 {
59 LOG(ERROR) << "Timeout when connecting to the database, giving up";
60 }
61 }
62
63 throw;
64 }
65 }
66
67 if (database_.get() == NULL ||
68 database_->GetDialect() != dialect_)
69 {
70 throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
71 }
72 else
73 {
74 return *database_;
75 }
76 }
77
78
79 void DatabaseManager::Close()
80 {
81 LOG(TRACE) << "Closing the connection to the database";
82
83 // Rollback active transaction, if any
84 transaction_.reset(NULL);
85
86 // Delete all the cached statements (must occur before closing
87 // the database)
88 for (CachedStatements::iterator it = cachedStatements_.begin();
89 it != cachedStatements_.end(); ++it)
90 {
91 assert(it->second != NULL);
92 delete it->second;
93 }
94
95 cachedStatements_.clear();
96
97 // Close the database
98 database_.reset(NULL);
99
100 LOG(TRACE) << "Connection to the database is closed";
101 }
102
103
104 void DatabaseManager::CloseIfUnavailable(Orthanc::ErrorCode e)
105 {
106 if (e != Orthanc::ErrorCode_Success)
107 {
108 transaction_.reset(NULL);
109 }
110
111 if (e == Orthanc::ErrorCode_DatabaseUnavailable)
112 {
113 LOG(ERROR) << "The database is not available, closing the connection";
114 Close();
115 }
116 }
117
118
119 IPrecompiledStatement* DatabaseManager::LookupCachedStatement(const StatementLocation& location) const
120 {
121 CachedStatements::const_iterator found = cachedStatements_.find(location);
122
123 if (found == cachedStatements_.end())
124 {
125 return NULL;
126 }
127 else
128 {
129 assert(found->second != NULL);
130 return found->second;
131 }
132 }
133
134
135 IPrecompiledStatement& DatabaseManager::CacheStatement(const StatementLocation& location,
136 const Query& query)
137 {
138 LOG(TRACE) << "Caching statement from " << location.GetFile() << ":" << location.GetLine();
139
140 std::auto_ptr<IPrecompiledStatement> statement(GetDatabase().Compile(query));
141
142 IPrecompiledStatement* tmp = statement.get();
143 if (tmp == NULL)
144 {
145 throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
146 }
147
148 assert(cachedStatements_.find(location) == cachedStatements_.end());
149 cachedStatements_[location] = statement.release();
150
151 return *tmp;
152 }
153
154
155 ITransaction& DatabaseManager::GetTransaction()
156 {
157 if (transaction_.get() == NULL)
158 {
159 LOG(TRACE) << "Automatically creating a database transaction";
160
161 try
162 {
163 transaction_.reset(GetDatabase().CreateTransaction());
164 }
165 catch (Orthanc::OrthancException& e)
166 {
167 CloseIfUnavailable(e.GetErrorCode());
168 throw;
169 }
170 }
171
172 assert(transaction_.get() != NULL);
173 return *transaction_;
174 }
175
176
177 DatabaseManager::DatabaseManager(IDatabaseFactory* factory) : // Takes ownership
178 factory_(factory)
179 {
180 if (factory == NULL)
181 {
182 throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer);
183 }
184
185 dialect_ = factory->GetDialect();
186 }
187
188
189 void DatabaseManager::StartTransaction()
190 {
191 boost::recursive_mutex::scoped_lock lock(mutex_);
192
193 try
194 {
195 if (transaction_.get() != NULL)
196 {
197 #if 0
198 // TODO: This should be the right implementation
199 if (transaction_->IsReadOnly())
200 {
201 LOG(TRACE) << "Rollback of an uncommitted read-only transaction to start another transaction";
202 transaction_->Rollback();
203 transaction_.reset(NULL);
204 }
205 else
206 {
207 LOG(ERROR) << "Cannot rollback an uncommitted write transaction to start another transaction";
208 throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
209 }
210 #else
211 LOG(INFO) << "Committing an uncommitted transaction to start another transaction";
212 transaction_->Commit();
213 transaction_.reset(NULL);
214 #endif
215 }
216
217 transaction_.reset(GetDatabase().CreateTransaction());
218 }
219 catch (Orthanc::OrthancException& e)
220 {
221 CloseIfUnavailable(e.GetErrorCode());
222 throw;
223 }
224 }
225
226
227 void DatabaseManager::CommitTransaction()
228 {
229 boost::recursive_mutex::scoped_lock lock(mutex_);
230
231 if (transaction_.get() == NULL)
232 {
233 LOG(ERROR) << "Cannot commit a non-existing transaction";
234 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
235 }
236 else
237 {
238 try
239 {
240 transaction_->Commit();
241 transaction_.reset(NULL);
242 }
243 catch (Orthanc::OrthancException& e)
244 {
245 CloseIfUnavailable(e.GetErrorCode());
246 throw;
247 }
248 }
249 }
250
251
252 void DatabaseManager::RollbackTransaction()
253 {
254 boost::recursive_mutex::scoped_lock lock(mutex_);
255
256 if (transaction_.get() == NULL)
257 {
258 LOG(ERROR) << "Cannot rollback a non-existing transaction";
259 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
260 }
261 else
262 {
263 try
264 {
265 transaction_->Rollback();
266 transaction_.reset(NULL);
267 }
268 catch (Orthanc::OrthancException& e)
269 {
270 CloseIfUnavailable(e.GetErrorCode());
271 throw;
272 }
273 }
274 }
275
276
277 IResult& DatabaseManager::CachedStatement::GetResult() const
278 {
279 if (result_.get() == NULL)
280 {
281 LOG(ERROR) << "Accessing the results of a statement without having executed it";
282 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
283 }
284
285 return *result_;
286 }
287
288
289 DatabaseManager::CachedStatement::CachedStatement(const StatementLocation& location,
290 DatabaseManager& manager,
291 const char* sql) :
292 lock_(manager.mutex_),
293 manager_(manager),
294 location_(location),
295 database_(manager.GetDatabase()),
296 transaction_(manager.GetTransaction())
297 {
298 statement_ = manager_.LookupCachedStatement(location);
299
300 if (statement_ == NULL)
301 {
302 query_.reset(new Query(sql));
303 }
304 else
305 {
306 LOG(TRACE) << "Reusing cached statement from "
307 << location.GetFile() << ":" << location.GetLine();
308 }
309 }
310
311
312 void DatabaseManager::CachedStatement::SetReadOnly(bool readOnly)
313 {
314 if (query_.get() != NULL)
315 {
316 query_->SetReadOnly(readOnly);
317 }
318 }
319
320
321 void DatabaseManager::CachedStatement::SetParameterType(const std::string& parameter,
322 ValueType type)
323 {
324 if (query_.get() != NULL)
325 {
326 query_->SetType(parameter, type);
327 }
328 }
329
330
331 void DatabaseManager::CachedStatement::Execute()
332 {
333 Dictionary parameters;
334 Execute(parameters);
335 }
336
337
338 void DatabaseManager::CachedStatement::Execute(const Dictionary& parameters)
339 {
340 if (result_.get() != NULL)
341 {
342 LOG(ERROR) << "Cannot execute twice a statement";
343 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
344 }
345
346 try
347 {
348 if (query_.get() != NULL)
349 {
350 // Register the newly-created statement
351 assert(statement_ == NULL);
352 statement_ = &manager_.CacheStatement(location_, *query_);
353 query_.reset(NULL);
354 }
355
356 assert(statement_ != NULL);
357 result_.reset(transaction_.Execute(*statement_, parameters));
358 }
359 catch (Orthanc::OrthancException& e)
360 {
361 manager_.CloseIfUnavailable(e.GetErrorCode());
362 throw;
363 }
364 }
365
366
367 bool DatabaseManager::CachedStatement::IsDone() const
368 {
369 try
370 {
371 return GetResult().IsDone();
372 }
373 catch (Orthanc::OrthancException& e)
374 {
375 manager_.CloseIfUnavailable(e.GetErrorCode());
376 throw;
377 }
378 }
379
380
381 void DatabaseManager::CachedStatement::Next()
382 {
383 try
384 {
385 GetResult().Next();
386 }
387 catch (Orthanc::OrthancException& e)
388 {
389 manager_.CloseIfUnavailable(e.GetErrorCode());
390 throw;
391 }
392 }
393
394
395 size_t DatabaseManager::CachedStatement::GetResultFieldsCount() const
396 {
397 try
398 {
399 return GetResult().GetFieldsCount();
400 }
401 catch (Orthanc::OrthancException& e)
402 {
403 manager_.CloseIfUnavailable(e.GetErrorCode());
404 throw;
405 }
406 }
407
408
409 void DatabaseManager::CachedStatement::SetResultFieldType(size_t field,
410 ValueType type)
411 {
412 try
413 {
414 if (!GetResult().IsDone())
415 {
416 GetResult().SetExpectedType(field, type);
417 }
418 }
419 catch (Orthanc::OrthancException& e)
420 {
421 manager_.CloseIfUnavailable(e.GetErrorCode());
422 throw;
423 }
424 }
425
426
427 const IValue& DatabaseManager::CachedStatement::GetResultField(size_t index) const
428 {
429 try
430 {
431 return GetResult().GetField(index);
432 }
433 catch (Orthanc::OrthancException& e)
434 {
435 manager_.CloseIfUnavailable(e.GetErrorCode());
436 throw;
437 }
438 }
439 }