OpenTREP Logo  0.07.18
C++ Open Travel Request Parsing Library
Loading...
Searching...
No Matches
DBSessionManager.cpp
Go to the documentation of this file.
1// //////////////////////////////////////////////////////////////////////
2// Import section
3// //////////////////////////////////////////////////////////////////////
4// STL
5#include <cassert>
6#include <string>
7#include <sstream>
8// SOCI
9#include <soci/soci.h>
10#include <soci/sqlite3/soci-sqlite3.h>
11// OpenTrep
12#include <opentrep/DBParams.hpp>
15
16namespace OPENTREP {
17
18 // //////////////////////////////////////////////////////////////////////
19 DBSessionManager::DBSessionManager() : _dbSession (NULL) {
20 }
21
22 // //////////////////////////////////////////////////////////////////////
23 DBSessionManager::DBSessionManager (const DBParams& iDBParams)
24 : _dbSession (NULL) {
25 init (iDBParams);
26 }
27
28 // //////////////////////////////////////////////////////////////////////
29 DBSessionManager::~DBSessionManager() {
30 // Properly close the (SOCI) database session, only when one has been created
31 if (_dbSession != NULL) {
32 _dbSession->close();
33 }
34 // Reset the underlying (SOCI) database connection
35 delete _dbSession; _dbSession = NULL;
36 }
37
38 // //////////////////////////////////////////////////////////////////////
39 soci::session& DBSessionManager::getDBSessionRef() const {
40 assert (_dbSession != NULL);
41 return *_dbSession;
42 }
43
44 // //////////////////////////////////////////////////////////////////////
45 void DBSessionManager::init (const DBParams& iDBParams) {
46
47 // Check that the parameters for the SQL database are not empty
48 if (iDBParams.checkSQLite() == false) {
49 std::ostringstream errorStr;
50 errorStr << "At least one of the parameters for the SQL "
51 << "database is empty: " << iDBParams;
52 OPENTREP_LOG_ERROR (errorStr.str());
53 throw XapianTravelDatabaseEmptyException (errorStr.str());
54 }
55
56 // Instanciate a (SOCI) database session: nothing is performed at
57 // that stage, else than creating a SOCI session object
58 _dbSession = new soci::session();
59
60 try {
61
62 // Open the connection to the database
63 _dbSession->open (soci::sqlite3, iDBParams.toSQLiteConnectionString());
64
65 } catch (std::exception const& lException) {
66 std::ostringstream errorStr;
67 errorStr << "Error while opening a connection to database: "
68 << lException.what() << std::endl;
69 errorStr << "Database parameters used: " << iDBParams.toString();
70 OPENTREP_LOG_ERROR (errorStr.str());
71 throw SQLDatabaseImpossibleConnectionException (errorStr.str());
72 }
73 }
74
75}
#define OPENTREP_LOG_ERROR(iToBeLogged)
Definition Logger.hpp:24