File: connection.hpp

package info (click to toggle)
mapnik 4.2.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 18,656 kB
  • sloc: cpp: 163,870; python: 1,332; sh: 690; xml: 161; makefile: 123; perl: 28; lisp: 13
file content (280 lines) | stat: -rw-r--r-- 8,359 bytes parent folder | download
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
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2025 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef POSTGIS_CONNECTION_HPP
#define POSTGIS_CONNECTION_HPP

// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/timer.hpp>

// std
#include <memory>
#include <sstream>
#include <iostream>

extern "C" {
#include "libpq-fe.h"
}

#include "resultset.hpp"

class Connection
{
  public:
    Connection(std::string const& connection_str, std::optional<std::string> const& password)
        : cursorId(0),
          closed_(false),
          pending_(false)
    {
        std::string connect_with_pass = connection_str;
        if (password && !password->empty())
        {
            connect_with_pass += " password=" + *password;
        }
        conn_ = PQconnectdb(connect_with_pass.c_str());
        MAPNIK_LOG_DEBUG(postgis) << "postgis_connection: postgresql connection create - " << this;
        if (PQstatus(conn_) != CONNECTION_OK)
        {
            std::string err_msg = "Postgis Plugin: ";
            err_msg += status();
            err_msg += "Connection string: '";
            err_msg += connection_str;
            err_msg += "'\n";
            MAPNIK_LOG_DEBUG(postgis) << "postgis_connection: creation failed, closing connection - " << this;
            close();
            throw mapnik::datasource_exception(err_msg);
        }
        PGresult* result =
          PQexec(conn_, "SET DEFAULT_TRANSACTION_READ_ONLY = TRUE; SET CLIENT_MIN_MESSAGES = WARNING;");
        bool ok = (result && (PQresultStatus(result) == PGRES_COMMAND_OK));
        if (result)
            PQclear(result);
        if (!ok)
        {
            std::string err_msg = "Postgis Plugin: ";
            err_msg += status();
            err_msg += "Connection string: '";
            err_msg += connection_str;
            err_msg += "'\n";
            close();
            throw mapnik::datasource_exception(err_msg);
        }
    }

    ~Connection()
    {
        if (!closed_)
        {
            PQfinish(conn_);
            MAPNIK_LOG_DEBUG(postgis) << "postgis_connection: postgresql connection closed - " << this;
            closed_ = true;
        }
    }

    bool execute(std::string const& sql)
    {
#ifdef MAPNIK_STATS
        mapnik::progress_timer __stats__(std::clog, std::string("postgis_connection::execute ") + sql);
#endif

        if (!executeAsyncQuery(sql))
            return false;
        PGresult* result = 0;
        // fetch multiple times until NULL is returned,
        // to handle multi-statement queries
        while (PGresult* tmp = getResult())
        {
            if (result)
                PQclear(result);
            result = tmp;
        }
        bool ok = (result && (PQresultStatus(result) == PGRES_COMMAND_OK));
        if (result)
            PQclear(result);
        return ok;
    }

    std::shared_ptr<ResultSet> executeQuery(std::string const& sql, int type = 0)
    {
#ifdef MAPNIK_STATS
        mapnik::progress_timer __stats__(std::clog, std::string("postgis_connection::execute_query ") + sql);
#endif
        PGresult* result = 0;
        if (executeAsyncQuery(sql, type))
        {
            // fetch multiple times until NULL is returned,
            // to handle multi-statement queries
            while (PGresult* tmp = getResult())
            {
                if (result)
                    PQclear(result);
                result = tmp;
            }
        }

        if (!result || (PQresultStatus(result) != PGRES_TUPLES_OK))
        {
            std::string err_msg = "Postgis Plugin: ";
            err_msg += status();
            err_msg += "in executeQuery Full sql was: '";
            err_msg += sql;
            err_msg += "'\n";
            if (result)
                PQclear(result);
            throw mapnik::datasource_exception(err_msg);
        }

        return std::make_shared<ResultSet>(result);
    }

    std::string status() const
    {
        std::string status;
        if (conn_)
        {
            char* err_msg = PQerrorMessage(conn_);
            if (err_msg == nullptr)
            {
                status = "Bad connection\n";
            }
            else
            {
                status = std::string(err_msg);
            }
        }
        else
        {
            status = "Uninitialized connection\n";
        }
        return status;
    }

    bool executeAsyncQuery(std::string const& sql, int type = 0)
    {
        int result = 0;
        if (type == 1)
        {
            result = PQsendQueryParams(conn_, sql.c_str(), 0, 0, 0, 0, 0, 1);
        }
        else
        {
            result = PQsendQuery(conn_, sql.c_str());
        }
        if (result != 1)
        {
            std::string err_msg = "Postgis Plugin: ";
            err_msg += status();
            err_msg += "in executeAsyncQuery Full sql was: '";
            err_msg += sql;
            err_msg += "'\n";
            clearAsyncResult(PQgetResult(conn_));
            close();
            throw mapnik::datasource_exception(err_msg);
        }
        pending_ = true;
        return result;
    }

    PGresult* getResult()
    {
        PGresult* result = PQgetResult(conn_);
        return result;
    }

    std::shared_ptr<ResultSet> getNextAsyncResult()
    {
        PGresult* result = getResult();
        if (result && (PQresultStatus(result) != PGRES_TUPLES_OK))
        {
            std::string err_msg = "Postgis Plugin: ";
            err_msg += status();
            err_msg += "in getNextAsyncResult";
            clearAsyncResult(result);
            // We need to guarde against losing the connection
            // (i.e db restart) so here we invalidate the full connection
            close();
            throw mapnik::datasource_exception(err_msg);
        }
        return std::make_shared<ResultSet>(result);
    }

    std::shared_ptr<ResultSet> getAsyncResult()
    {
        PGresult* result = getResult();
        if (!result || (PQresultStatus(result) != PGRES_TUPLES_OK))
        {
            std::string err_msg = "Postgis Plugin: ";
            err_msg += status();
            err_msg += "in getAsyncResult";
            clearAsyncResult(result);
            // We need to be guarded against losing the connection
            // (i.e db restart), we invalidate the full connection
            close();
            throw mapnik::datasource_exception(err_msg);
        }
        return std::make_shared<ResultSet>(result);
    }

    std::string client_encoding() const { return PQparameterStatus(conn_, "client_encoding"); }

    bool isOK() const { return (!closed_) && (PQstatus(conn_) != CONNECTION_BAD); }

    bool isPending() const { return pending_; }

    void close()
    {
        if (!closed_)
        {
            PQfinish(conn_);
            MAPNIK_LOG_DEBUG(postgis) << "postgis_connection: closing connection (close)- " << this;
            closed_ = true;
        }
    }

    std::string new_cursor_name()
    {
        std::ostringstream s;
        s << "mapnik_" << (cursorId++);
        return s.str();
    }

  private:
    PGconn* conn_;
    int cursorId;
    bool closed_;
    bool pending_;

    void clearAsyncResult(PGresult* result)
    {
        // Clear all pending results
        while (result)
        {
            PQclear(result);
            result = PQgetResult(conn_);
        }
        pending_ = false;
    }
};

#endif // CONNECTION_HPP