comparison Framework/PostgreSQL/PostgreSQLDatabase.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 "PostgreSQLDatabase.h"
23
24 #include "PostgreSQLResult.h"
25 #include "PostgreSQLStatement.h"
26 #include "PostgreSQLTransaction.h"
27
28 #include <Core/Logging.h>
29 #include <Core/OrthancException.h>
30
31 #include <boost/lexical_cast.hpp>
32
33 // PostgreSQL includes
34 #include <libpq-fe.h>
35 #include <c.h>
36 #include <catalog/pg_type.h>
37
38
39 namespace OrthancDatabases
40 {
41 void PostgreSQLDatabase::ThrowException(bool log)
42 {
43 if (log)
44 {
45 LOG(ERROR) << "PostgreSQL error: "
46 << PQerrorMessage(reinterpret_cast<PGconn*>(pg_));
47 }
48
49 if (PQstatus(reinterpret_cast<PGconn*>(pg_)) == CONNECTION_OK)
50 {
51 throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
52 }
53 else
54 {
55 throw Orthanc::OrthancException(Orthanc::ErrorCode_DatabaseUnavailable);
56 }
57 }
58
59
60 void PostgreSQLDatabase::Close()
61 {
62 if (pg_ != NULL)
63 {
64 LOG(INFO) << "Closing connection to PostgreSQL";
65 PQfinish(reinterpret_cast<PGconn*>(pg_));
66 pg_ = NULL;
67 }
68 }
69
70
71 void PostgreSQLDatabase::Open()
72 {
73 if (pg_ != NULL)
74 {
75 // Already connected
76 return;
77 }
78
79 std::string s;
80 parameters_.Format(s);
81
82 pg_ = PQconnectdb(s.c_str());
83
84 if (pg_ == NULL ||
85 PQstatus(reinterpret_cast<PGconn*>(pg_)) != CONNECTION_OK)
86 {
87 std::string message;
88
89 if (pg_)
90 {
91 message = PQerrorMessage(reinterpret_cast<PGconn*>(pg_));
92 PQfinish(reinterpret_cast<PGconn*>(pg_));
93 pg_ = NULL;
94 }
95
96 LOG(ERROR) << "PostgreSQL error: " << message;
97 throw Orthanc::OrthancException(Orthanc::ErrorCode_DatabaseUnavailable);
98 }
99
100 if (parameters_.HasLock())
101 {
102 PostgreSQLTransaction transaction(*this);
103
104 int32_t lock = 42; // Some arbitrary constant
105
106 PostgreSQLStatement s(*this, "select pg_try_advisory_lock(" +
107 boost::lexical_cast<std::string>(lock) + ");");
108
109 PostgreSQLResult result(s);
110 if (result.IsDone() ||
111 !result.GetBoolean(0))
112 {
113 LOG(ERROR) << "The PostgreSQL database is locked by another instance of Orthanc";
114 throw Orthanc::OrthancException(Orthanc::ErrorCode_Database);
115 }
116
117 transaction.Commit();
118 }
119 }
120
121
122 void PostgreSQLDatabase::Execute(const std::string& sql)
123 {
124 LOG(TRACE) << "PostgreSQL: " << sql;
125 Open();
126
127 PGresult* result = PQexec(reinterpret_cast<PGconn*>(pg_), sql.c_str());
128 if (result == NULL)
129 {
130 ThrowException(true);
131 }
132
133 bool ok = (PQresultStatus(result) == PGRES_COMMAND_OK ||
134 PQresultStatus(result) == PGRES_TUPLES_OK);
135
136 if (ok)
137 {
138 PQclear(result);
139 }
140 else
141 {
142 std::string message = PQresultErrorMessage(result);
143 PQclear(result);
144
145 LOG(ERROR) << "PostgreSQL error: " << message;
146 ThrowException(false);
147 }
148 }
149
150
151 bool PostgreSQLDatabase::DoesTableExist(const char* name)
152 {
153 std::string lower(name);
154 std::transform(lower.begin(), lower.end(), lower.begin(), tolower);
155
156 // http://stackoverflow.com/a/24089729/881731
157
158 PostgreSQLStatement statement(*this,
159 "SELECT 1 FROM pg_catalog.pg_class c "
160 "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
161 "WHERE n.nspname = 'public' AND c.relkind='r' "
162 "AND c.relname=$1", true);
163
164 statement.DeclareInputString(0);
165 statement.BindString(0, lower);
166
167 PostgreSQLResult result(statement);
168 return !result.IsDone();
169 }
170
171
172 void PostgreSQLDatabase::ClearAll()
173 {
174 PostgreSQLTransaction transaction(*this);
175
176 // Remove all the large objects
177 Execute("SELECT lo_unlink(loid) FROM (SELECT DISTINCT loid FROM pg_catalog.pg_largeobject) as loids;");
178
179 // http://stackoverflow.com/a/21247009/881731
180 Execute("DROP SCHEMA public CASCADE;");
181 Execute("CREATE SCHEMA public;");
182 Execute("GRANT ALL ON SCHEMA public TO postgres;");
183 Execute("GRANT ALL ON SCHEMA public TO public;");
184 Execute("COMMENT ON SCHEMA public IS 'standard public schema';");
185
186 transaction.Commit();
187 }
188
189
190 IPrecompiledStatement* PostgreSQLDatabase::Compile(const Query& query)
191 {
192 return new PostgreSQLStatement(*this, query);
193 }
194
195
196 ITransaction* PostgreSQLDatabase::CreateTransaction()
197 {
198 return new PostgreSQLTransaction(*this);
199 }
200 }