File: PostgreSQLResult.cpp

package info (click to toggle)
orthanc-postgresql 5.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 1,372 kB
  • sloc: cpp: 18,362; python: 388; sql: 275; makefile: 30; sh: 13
file content (262 lines) | stat: -rw-r--r-- 7,242 bytes parent folder | download | duplicates (2)
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
/**
 * 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 "PostgreSQLIncludes.h"  // Must be the first
#include "PostgreSQLResult.h"

#include "../Common/BinaryStringValue.h"
#include "../Common/ResultFileValue.h"
#include "../Common/Integer64Value.h"
#include "../Common/NullValue.h"
#include "../Common/Utf8StringValue.h"

#include <Compatibility.h>  // For std::unique_ptr<>
#include <OrthancException.h>
#include <Logging.h>
#include <Endianness.h>

#include <cassert>
#include <boost/lexical_cast.hpp>


namespace OrthancDatabases
{
  void PostgreSQLResult::Clear()
  {
    if (result_ != NULL)
    {
      PQclear(reinterpret_cast<PGresult*>(result_));
      result_ = NULL;
    }
  }


  void PostgreSQLResult::CheckDone()
  {
    if (position_ >= PQntuples(reinterpret_cast<PGresult*>(result_)))
    {
      // We are at the end of the result set
      Clear();
    }
  }


  void PostgreSQLResult::CheckColumn(unsigned int column, unsigned int /*Oid*/ expectedType) const
  {
    if (IsDone())
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls);
    }

    if (column >= static_cast<unsigned int>(PQnfields(reinterpret_cast<PGresult*>(result_))))
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange);
    }

    if (expectedType != 0 &&
        expectedType != PQftype(reinterpret_cast<PGresult*>(result_), column))
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadParameterType);
    }
  }


  PostgreSQLResult::PostgreSQLResult(PostgreSQLStatement& statement) : 
    position_(0), 
    database_(statement.GetDatabase())
  {
    result_ = statement.Execute();
    assert(result_ != NULL);   // An exception would have been thrown otherwise

    // This is the first call to "Next()"
    if (PQresultStatus(reinterpret_cast<PGresult*>(result_)) == PGRES_TUPLES_OK)
    {
      CheckDone();
      columnsCount_ = static_cast<unsigned int>(PQnfields(reinterpret_cast<PGresult*>(result_)));
    }
    else
    {
      // This is not a SELECT request, we're done
      Clear();
      columnsCount_ = 0;
    }
  }


  PostgreSQLResult::~PostgreSQLResult()
  {
    try
    {
      Clear();
    }
    catch (Orthanc::OrthancException&)
    {
      // Ignore possible exceptions due to connection loss
    }
  }


  void PostgreSQLResult::Next()
  {
    position_++;
    CheckDone();
  }


  bool PostgreSQLResult::IsNull(unsigned int column) const
  {
    CheckColumn(column, 0);
    return PQgetisnull(reinterpret_cast<PGresult*>(result_), position_, column) != 0;
  }


  bool PostgreSQLResult::GetBoolean(unsigned int column) const
  {
    CheckColumn(column, BOOLOID);
    assert(PQfsize(reinterpret_cast<PGresult*>(result_), column) == 1);
    const uint8_t *v = reinterpret_cast<const uint8_t*>
      (PQgetvalue(reinterpret_cast<PGresult*>(result_), position_, column));
    return (v[0] != 0);
  }


  int PostgreSQLResult::GetInteger(unsigned int column) const
  {
    CheckColumn(column, INT4OID);
    assert(PQfsize(reinterpret_cast<PGresult*>(result_), column) == 4);
    char *v = PQgetvalue(reinterpret_cast<PGresult*>(result_), position_, column);
    return htobe32(*reinterpret_cast<int32_t*>(v));
  }


  int64_t PostgreSQLResult::GetInteger64(unsigned int column) const
  {
    CheckColumn(column, INT8OID);
    assert(PQfsize(reinterpret_cast<PGresult*>(result_), column) == 8);
    char *v = PQgetvalue(reinterpret_cast<PGresult*>(result_), position_, column);
    return htobe64(*reinterpret_cast<int64_t*>(v));
  }


  std::string PostgreSQLResult::GetString(unsigned int column) const
  {
    CheckColumn(column, 0);

    Oid oid = PQftype(reinterpret_cast<PGresult*>(result_), column);
    if (oid != TEXTOID && oid != VARCHAROID && oid != BYTEAOID)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadParameterType);
    }

    return std::string(PQgetvalue(reinterpret_cast<PGresult*>(result_), position_, column));
  }


  std::string PostgreSQLResult::GetLargeObjectOid(unsigned int column) const
  {
    CheckColumn(column, OIDOID);

    /**
     * In PostgreSQL, the type "Oid" corresponds to "unsigned int", cf.
     * /usr/include/postgresql/10/server/postgres_ext.h
     **/
    Oid oid;
    assert(PQfsize(reinterpret_cast<PGresult*>(result_), column) == sizeof(oid));

    oid = *(const Oid*) PQgetvalue(reinterpret_cast<PGresult*>(result_), position_, column);
    oid = ntohl(oid);

    return boost::lexical_cast<std::string>(oid);
  }


  void PostgreSQLResult::GetLargeObjectContent(std::string& content,
                                               unsigned int column) const
  {
    PostgreSQLLargeObject::ReadWhole(content, database_, GetLargeObjectOid(column));
  }


  class PostgreSQLResult::LargeObjectResult : public ResultFileValue
  {
  private:
    PostgreSQLDatabase&  database_;
    std::string          oid_;

  public:
    LargeObjectResult(PostgreSQLDatabase& database,
                      const std::string& oid) :
      database_(database),
      oid_(oid)
    {
    }

    virtual void ReadWhole(std::string& target) const ORTHANC_OVERRIDE
    {
      PostgreSQLLargeObject::ReadWhole(target, database_, oid_);
    }
    
    virtual void ReadRange(std::string& target,
                           uint64_t start,
                           size_t length) const ORTHANC_OVERRIDE
    {
      PostgreSQLLargeObject::ReadRange(target, database_, oid_, start, length);
    }
  };


  IValue* PostgreSQLResult::GetValue(unsigned int column) const
  {
    if (IsNull(column))
    {
      return new NullValue;
    }

    Oid type = PQftype(reinterpret_cast<PGresult*>(result_), column);

    switch (type)
    {
      case BOOLOID:
        // Convert Boolean values as integers
        return new Integer64Value(GetBoolean(column) ? 1 : 0);

      case INT4OID:
        return new Integer64Value(GetInteger(column));

      case INT8OID:
        return new Integer64Value(GetInteger64(column));

      case TEXTOID:
      case VARCHAROID:
        return new Utf8StringValue(GetString(column));

      case BYTEAOID:
        return new BinaryStringValue(GetString(column));

      case OIDOID:
        return new LargeObjectResult(database_, GetLargeObjectOid(column));

      default:
        throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented);
    }
  }
}