Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/***********************************************************************************************************************************
Postgres Client
***********************************************************************************************************************************/
#include <build.h>
 
#include <libpq-fe.h>
 
#include "common/debug.h"
#include "common/io/fd.h"
#include "common/log.h"
#include "common/wait.h"
#include "postgres/client.h"
 
/***********************************************************************************************************************************
Object type
***********************************************************************************************************************************/
struct PgClient
{
    PgClientPub pub;                                                // Publicly accessible variables
    PGconn *connection;                                             // Pg connection
};
 
/***********************************************************************************************************************************
Close protocol connection
***********************************************************************************************************************************/
static void
pgClientFreeResource(THIS_VOID)
{
    THIS(PgClient);
 
    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(PG_CLIENT, this);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
 
    PQfinish(this->connection);
 
    FUNCTION_LOG_RETURN_VOID();
}
 
/**********************************************************************************************************************************/
FN_EXTERN PgClient *
pgClientNew(
    const String *const host, const unsigned int port, const String *const database, const String *const user,
    const TimeMSec timeout)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(STRING, host);
        FUNCTION_LOG_PARAM(UINT, port);
        FUNCTION_LOG_PARAM(STRING, database);
        FUNCTION_LOG_PARAM(STRING, user);
        FUNCTION_LOG_PARAM(TIME_MSEC, timeout);
    FUNCTION_LOG_END();
 
    ASSERT(port >= 1 && port <= 65535);
    ASSERT(database != NULL);
 
    OBJ_NEW_BEGIN(PgClient, .childQty = MEM_CONTEXT_QTY_MAX, .callbackQty = 1)
    {
        *this = (PgClient)
        {
            .pub =
            {
                .host = strDup(host),
                .port = port,
                .database = strDup(database),
                .user = strDup(user),
                .timeout = timeout,
            },
        };
    }
    OBJ_NEW_END();
 
    FUNCTION_LOG_RETURN(PG_CLIENT, this);
}
 
/***********************************************************************************************************************************
Just ignore notices and warnings
***********************************************************************************************************************************/
static void
pgClientNoticeProcessor(void *const arg, const char *const message)
{
    (void)arg;
    (void)message;
}
 
/***********************************************************************************************************************************
Encode string to escape ' and \
***********************************************************************************************************************************/
static String *
pgClientEscape(const String *const string)
{
    FUNCTION_TEST_BEGIN();
        FUNCTION_TEST_PARAM(STRING, string);
    FUNCTION_TEST_END();
 
    ASSERT(string != NULL);
 
    String *const result = strCatZ(strNew(), "'");
 
    // Iterate all characters in the string
    for (unsigned stringIdx = 0; stringIdx < strSize(string); stringIdx++)
    {
        char stringChar = strZ(string)[stringIdx];
 
        // These characters are escaped
        if (stringChar == '\'' || stringChar == '\\')
            strCatChr(result, '\\');
 
        strCatChr(result, stringChar);
    }
 
    strCatChr(result, '\'');
 
    FUNCTION_TEST_RETURN(STRING, result);
}
 
/**********************************************************************************************************************************/
FN_EXTERN PgClient *
pgClientOpen(PgClient *const this)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(PG_CLIENT, this);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    CHECK(AssertError, this->connection == NULL, "invalid connection");
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        // Base connection string
        String *const connInfo = strCatFmt(
            strNew(), "dbname=%s port=%u", strZ(pgClientEscape(pgClientDatabase(this))), pgClientPort(this));
 
        // Add user if specified
        if (pgClientUser(this) != NULL)
            strCatFmt(connInfo, " user=%s", strZ(pgClientEscape(pgClientUser(this))));
 
        // Add host if specified
        if (pgClientHost(this) != NULL)
            strCatFmt(connInfo, " host=%s", strZ(pgClientEscape(pgClientHost(this))));
 
        // Make the connection
        this->connection = PQconnectdb(strZ(connInfo));
 
        // Set a callback to shutdown the connection
        memContextCallbackSet(objMemContext(this), pgClientFreeResource, this);
 
        // Handle errors
        if (PQstatus(this->connection) != CONNECTION_OK)
        {
            THROW_FMT(
                DbConnectError, "unable to connect to '%s': %s", strZ(connInfo),
                strZ(strTrim(strNewZ(PQerrorMessage(this->connection)))));
        }
 
        // Set notice and warning processor
        PQsetNoticeProcessor(this->connection, pgClientNoticeProcessor, NULL);
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN(PG_CLIENT, this);
}
 
/**********************************************************************************************************************************/
FN_EXTERN Pack *
pgClientQuery(PgClient *const this, const String *const query, const PgClientQueryResult resultType)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(PG_CLIENT, this);
        FUNCTION_LOG_PARAM(STRING, query);
        FUNCTION_LOG_PARAM(STRING_ID, resultType);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    CHECK(AssertError, this->connection != NULL, "invalid connection");
    ASSERT(query != NULL);
    ASSERT(resultType != 0);
 
    Pack *result = NULL;
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        // Send the query without waiting for results so we can timeout if needed
        if (!PQsendQuery(this->connection, strZ(query)))
        {
            THROW_FMT(
                DbQueryError, "unable to send query '%s': %s", strZ(query),
                strZ(strTrim(strNewZ(PQerrorMessage(this->connection)))));
        }
 
        // Wait for a result
        Wait *const wait = waitNew(pgClientTimeout(this));
        bool busy = false;
 
        do
        {
            PQconsumeInput(this->connection);
            busy = PQisBusy(this->connection);
        }
        while (busy && fdReadyRead(PQsocket(this->connection), waitRemains(wait)));
 
        // If the query is still busy after the timeout attempt to cancel
        if (busy)
        {
            PGcancel *const cancel = PQgetCancel(this->connection);
 
            // If cancel is NULL then more than likely the server process crashed or disconnected
            if (cancel == NULL)
                THROW_FMT(DbQueryError, "unable to cancel query '%s': connection was lost", strZ(query));
 
            TRY_BEGIN()
            {
                char error[256];
 
                if (!PQcancel(cancel, error, sizeof(error)))
                    THROW_FMT(DbQueryError, "unable to cancel query '%s': %s", strZ(query), strZ(strTrim(strNewZ(error))));
            }
            FINALLY()
            {
                PQfreeCancel(cancel);
            }
            TRY_END();
        }
 
        // Get the result (even if query was cancelled -- to prevent the connection being left in a bad state)
        PGresult *const pgResult = PQgetResult(this->connection);
 
        TRY_BEGIN()
        {
            // Throw timeout error if cancelled
            if (busy)
                THROW_FMT(DbQueryError, "query '%s' timed out after %" PRIu64 "ms", strZ(query), pgClientTimeout(this));
 
            // If this was a command that returned no results then we are done
            const ExecStatusType resultStatus = PQresultStatus(pgResult);
 
            if (resultStatus == PGRES_COMMAND_OK)
            {
                if (resultType != pgClientQueryResultNone && resultType != pgClientQueryResultAny)
                    THROW_FMT(DbQueryError, "result expected from '%s'", strZ(query));
            }
            else
            {
                // If no tuples then the result is an error
                if (resultStatus != PGRES_TUPLES_OK)
                {
                    THROW_FMT(
                        DbQueryError, "unable to execute query '%s': %s", strZ(query),
                        strZ(strTrim(strNewZ(PQresultErrorMessage(pgResult)))));
                }
 
                // Expect some rows to be returned
                if (resultType == pgClientQueryResultNone)
                    THROW_FMT(DbQueryError, "no result expected from '%s'", strZ(query));
 
                // Fetch row and column values
                PackWrite *const pack = pckWriteNewP();
 
                const int rowTotal = PQntuples(pgResult);
                const int columnTotal = PQnfields(pgResult);
 
                if (resultType != pgClientQueryResultAny)
                {
                    if (rowTotal != 1)
                        THROW_FMT(DbQueryError, "expected one row from '%s'", strZ(query));
 
                    if (resultType == pgClientQueryResultColumn && columnTotal != 1)
                        THROW_FMT(DbQueryError, "expected one column from '%s'", strZ(query));
                }
 
                // Get column types
                Oid *const columnType = memNew(sizeof(int) * (size_t)columnTotal);
 
                for (int columnIdx = 0; columnIdx < columnTotal; columnIdx++)
                    columnType[columnIdx] = PQftype(pgResult, columnIdx);
 
                // Get values
                for (int rowIdx = 0; rowIdx < rowTotal; rowIdx++)
                {
                    if (resultType == pgClientQueryResultAny)
                        pckWriteArrayBeginP(pack);
 
                    for (int columnIdx = 0; columnIdx < columnTotal; columnIdx++)
                    {
                        const char *const value = PQgetvalue(pgResult, rowIdx, columnIdx);
 
                        // If value is zero-length then check if it is null
                        if (value[0] == '\0' && PQgetisnull(pgResult, rowIdx, columnIdx))
                        {
                            pckWriteNullP(pack);
                        }
                        // Else convert the value to a variant
                        else
                        {
                            // Convert column type. Not all PostgreSQL types are supported but these should suffice.
                            switch (columnType[columnIdx])
                            {
                                // Boolean type
                                case 16:                            // bool
                                    pckWriteBoolP(pack, varBoolForce(varNewStrZ(value)), .defaultWrite = true);
                                    break;
 
                                // Text/char types
                                case 18:                            // char
                                case 19:                            // name
                                case 25:                            // text
                                    pckWriteStrP(pack, STR(value), .defaultWrite = true);
                                    break;
 
                                // 64-bit integer type
                                case 20:                            // int8
                                    pckWriteI64P(pack, cvtZToInt64(value), .defaultWrite = true);
                                    break;
 
                                // 32-bit integer type
                                case 23:                            // int4
                                    pckWriteI32P(pack, cvtZToInt(value), .defaultWrite = true);
                                    break;
 
                                // 32-bit unsigned integer type
                                case 26:                            // oid
                                    pckWriteU32P(pack, cvtZToUInt(value), .defaultWrite = true);
                                    break;
 
                                default:
                                    THROW_FMT(
                                        FormatError, "unable to parse type %u in column %d for query '%s'",
                                        columnType[columnIdx], columnIdx, strZ(query));
                            }
                        }
                    }
 
                    if (resultType == pgClientQueryResultAny)
                        pckWriteArrayEndP(pack);
                }
 
                // End pack and return result
                pckWriteEndP(pack);
 
                result = pckMove(pckWriteResult(pack), memContextPrior());
            }
        }
        FINALLY()
        {
            // Free the result
            PQclear(pgResult);
 
            // The command is only complete once a NULL result is returned. A non-NULL result here means an extra result was
            // received, which almost always means the connection was lost while the query was running.
            PGresult *const pgResultExtra = PQgetResult(this->connection);
 
            if (pgResultExtra != NULL)
            {
                // Attempt to retrieve the error so the actual cause is reported
                const String *const error = strTrim(strNewZ(PQresultErrorMessage(pgResultExtra)));
                PQclear(pgResultExtra);
 
                THROW_FMT(
                    DbQueryError,
                    "unable to complete query '%s'%s%s\n"
                    "HINT: this is usually caused by the connection to PostgreSQL being lost while the query was running.\n"
                    "HINT: check idle_session_timeout and idle_in_transaction_session_timeout for aggressive settings.\n"
                    "HINT: check the PostgreSQL log and network for a crash, restart, or timeout.",
                    strZ(query), strEmpty(error) ? "" : ": ", strZ(error));
            }
        }
        TRY_END();
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN(PACK, result);
}
 
/**********************************************************************************************************************************/
FN_EXTERN void
pgClientToLog(const PgClient *const this, StringStatic *const debugLog)
{
    strStcCat(debugLog, "{host: ");
    strStcResultSizeInc(
        debugLog,
        FUNCTION_LOG_OBJECT_FORMAT(pgClientHost(this), strToLog, strStcRemains(debugLog), strStcRemainsSize(debugLog)));
 
    strStcCat(debugLog, ", database: ");
    strToLog(pgClientDatabase(this), debugLog);
 
    strStcCat(debugLog, ", user: ");
    strStcResultSizeInc(
        debugLog,
        FUNCTION_LOG_OBJECT_FORMAT(pgClientUser(this), strToLog, strStcRemains(debugLog), strStcRemainsSize(debugLog)));
 
    strStcFmt(
        debugLog, ", port: %u, queryTimeout %" PRIu64 "}", pgClientPort(this), pgClientTimeout(this));
}