Исходный код СУБД 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
/***********************************************************************************************************************************
Database Client
***********************************************************************************************************************************/
#include <build.h>
 
#include "common/debug.h"
#include "common/log.h"
#include "common/type/json.h"
#include "common/wait.h"
#include "config/config.h"
#include "config/protocol.h"
#include "db/db.h"
#include "db/protocol.h"
#include "postgres/interface.h"
#include "postgres/version.h"
#include "protocol/helper.h"
#include "version.h"
 
/***********************************************************************************************************************************
Constants
***********************************************************************************************************************************/
#define PG_BACKUP_ADVISORY_LOCK                                     "12340078987004321"
#define DB_PING_SEC                                                 30
 
/***********************************************************************************************************************************
Object type
***********************************************************************************************************************************/
struct Db
{
    DbPub pub;                                                      // Publicly accessible variables
    PgClient *client;                                               // Local PostgreSQL client
    ProtocolClient *remoteClient;                                   // Protocol client for remote db queries
    ProtocolClientSession *session;                                 // Protocol session for requests
    const Storage *storage;                                         // PostgreSQL storage
    const String *applicationName;                                  // Used to identify this connection in PostgreSQL
    time_t pingTimeLast;                                            // Last time cluster was pinged
};
 
/***********************************************************************************************************************************
Close protocol connection. No need to close a locally created PgClient since it has its own destructor.
***********************************************************************************************************************************/
static void
dbFreeResource(THIS_VOID)
{
    THIS(Db);
 
    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(DB, this);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
 
    protocolClientSessionFree(this->session);
 
    FUNCTION_LOG_RETURN_VOID();
}
 
/**********************************************************************************************************************************/
FN_EXTERN Db *
dbNew(PgClient *const client, ProtocolClient *const remoteClient, const Storage *const storage, const String *const applicationName)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(PG_CLIENT, client);
        FUNCTION_LOG_PARAM(PROTOCOL_CLIENT, remoteClient);
        FUNCTION_LOG_PARAM(STORAGE, storage);
        FUNCTION_LOG_PARAM(STRING, applicationName);
    FUNCTION_LOG_END();
 
    ASSERT((client != NULL && remoteClient == NULL) || (client == NULL && remoteClient != NULL));
    ASSERT(storage != NULL);
    ASSERT(applicationName != NULL);
 
    OBJ_NEW_BEGIN(Db, .childQty = MEM_CONTEXT_QTY_MAX, .callbackQty = 1)
    {
        *this = (Db)
        {
            .pub =
            {
                .memContext = memContextCurrent(),
            },
            .remoteClient = remoteClient,
            .session = remoteClient != NULL ? protocolClientSessionNewP(remoteClient, PROTOCOL_COMMAND_DB) : NULL,
            .storage = storage,
            .applicationName = strDup(applicationName),
        };
 
        this->client = pgClientMove(client, this->pub.memContext);
    }
    OBJ_NEW_END();
 
    FUNCTION_LOG_RETURN(DB, this);
}
 
/***********************************************************************************************************************************
Execute a query
***********************************************************************************************************************************/
static Pack *
dbQuery(Db *const this, const PgClientQueryResult resultType, const String *const query)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
        FUNCTION_LOG_PARAM(STRING_ID, resultType);
        FUNCTION_LOG_PARAM(STRING, query);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    ASSERT(resultType != 0);
    ASSERT(query != NULL);
 
    Pack *result;
 
    // Query remotely
    if (this->remoteClient != NULL)
    {
        MEM_CONTEXT_TEMP_BEGIN()
        {
            PackWrite *const param = protocolPackNew();
 
            pckWriteStrIdP(param, resultType);
            pckWriteStrP(param, query);
 
            PackRead *const read = protocolClientSessionRequestP(this->session, .param = param);
 
            MEM_CONTEXT_PRIOR_BEGIN()
            {
                result = pckReadPackP(read);
            }
            MEM_CONTEXT_PRIOR_END();
        }
        MEM_CONTEXT_TEMP_END();
    }
    // Else locally
    else
        result = pgClientQuery(this->client, query, resultType);
 
    FUNCTION_LOG_RETURN(PACK, result);
}
 
/***********************************************************************************************************************************
Execute a command that expects no output
***********************************************************************************************************************************/
static void
dbExec(Db *const this, const String *const command)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
        FUNCTION_LOG_PARAM(STRING, command);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    ASSERT(command != NULL);
 
    CHECK(AssertError, dbQuery(this, pgClientQueryResultNone, command) == NULL, "exec returned data");
 
    FUNCTION_LOG_RETURN_VOID();
}
 
/***********************************************************************************************************************************
Execute a query that returns a single row and column
***********************************************************************************************************************************/
static PackRead *
dbQueryColumn(Db *const this, const String *const query)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
        FUNCTION_LOG_PARAM(STRING, query);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    ASSERT(query != NULL);
 
    Pack *const pack = dbQuery(this, pgClientQueryResultColumn, query);
    PackRead *const result = pckReadNew(pack);
    pckMove(pack, objMemContext(result));
 
    FUNCTION_LOG_RETURN(PACK_READ, result);
}
 
/***********************************************************************************************************************************
Execute a query that returns a single row
***********************************************************************************************************************************/
static PackRead *
dbQueryRow(Db *const this, const String *const query)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
        FUNCTION_LOG_PARAM(STRING, query);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    ASSERT(query != NULL);
 
    Pack *const pack = dbQuery(this, pgClientQueryResultRow, query);
    PackRead *const result = pckReadNew(pack);
    pckMove(pack, objMemContext(result));
 
    FUNCTION_LOG_RETURN(PACK_READ, result);
}
 
/***********************************************************************************************************************************
Is the cluster in recovery?
***********************************************************************************************************************************/
static bool
dbIsInRecovery(Db *const this)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
 
    bool result;
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        result = pckReadBoolP(dbQueryColumn(this, STRDEF("select pg_catalog.pg_is_in_recovery()")));
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN(BOOL, result);
}
 
/**********************************************************************************************************************************/
FN_EXTERN void
dbOpen(Db *const this)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        // Open the connection
        if (this->remoteClient != NULL)
        {
            protocolClientSessionOpenP(this->session);
 
            // Set a callback to notify the remote when a connection is closed
            memContextCallbackSet(this->pub.memContext, dbFreeResource, this);
 
            // Get db-timeout from the remote since it might be different than the local value
            this->pub.dbTimeout = varUInt64Force(
                varLstGet(configOptionRemote(this->remoteClient, varLstAdd(varLstNew(), varNewStrZ(CFGOPT_DB_TIMEOUT))), 0));
        }
        else
        {
            pgClientOpen(this->client);
            this->pub.dbTimeout = cfgOptionUInt64(cfgOptDbTimeout);
        }
 
        // Set search_path to prevent overrides of the functions we expect to call. All queries should also be schema-qualified,
        // but this is an extra level protection.
        dbExec(this, STRDEF("set search_path = 'pg_catalog'"));
 
        // Set client encoding to UTF8. This is the only encoding (other than ASCII) that we can safely work with.
        dbExec(this, STRDEF("set client_encoding = 'UTF8'"));
 
        // Query the version and data_directory. Be sure the update the total in the null check below when adding/removing columns.
        const Pack *const row = dbQuery(
            this, pgClientQueryResultRow,
            STRDEF(
                "select (select setting from pg_catalog.pg_settings where name = 'server_version_num')::int4,"
                " (select setting from pg_catalog.pg_settings where name = 'data_directory')::text,"
                " (select setting from pg_catalog.pg_settings where name = 'archive_mode')::text,"
                " (select setting from pg_catalog.pg_settings where name = 'archive_command')::text,"
                " (select setting from pg_catalog.pg_settings where name = 'checkpoint_timeout')::int4"));
 
        // Check that none of the return values are null, which indicates the user cannot select some rows in pg_settings
        PackRead *read = pckReadNew(row);
 
        for (unsigned int columnIdx = 0; columnIdx < 5; columnIdx++)
        {
            if (pckReadNullP(read, .id = columnIdx + 1))
            {
                THROW(
                    DbQueryError,
                    "unable to select some rows from pg_settings\n"
                    "HINT: is the backup running as the postgres user?\n"
                    "HINT: is the pg_read_all_settings role assigned?");
            }
        }
 
        // Restart the read to get the data
        read = pckReadNew(row);
 
        // Strip the minor version off since we don't need it. In the future it might be a good idea to warn users when they are
        // running an old minor version.
        this->pub.pgVersion = (unsigned int)pckReadI32P(read) / 100 * 100;
 
        // Store the data directory that PostgreSQL is running in, the archive mode, and archive command. These can be compared to
        // the configured pgBackRest directory, and archive settings checked for validity, when validating the configuration.
        // Also store the checkpoint timeout to warn in case a backup is requested without using the start-fast option.
        MEM_CONTEXT_BEGIN(this->pub.memContext)
        {
            this->pub.pgDataPath = pckReadStrP(read);
            this->pub.archiveMode = pckReadStrP(read);
            this->pub.archiveCommand = pckReadStrP(read);
            this->pub.checkpointTimeout = (TimeMSec)pckReadI32P(read) * MSEC_PER_SEC;
        }
        MEM_CONTEXT_END();
 
        // Set application name to help identify the backup session
        dbExec(this, strNewFmt("set application_name = '%s'", strZ(this->applicationName)));
 
        // There is no need to have parallelism enabled in a backup session
        dbExec(this, STRDEF("set max_parallel_workers_per_gather = 0"));
 
        // Is the cluster a standby?
        this->pub.standby = dbIsInRecovery(this);
 
        // Get control file
        this->pub.pgControl = pgControlFromFile(this->storage, cfgOptionStrNull(cfgOptPgVersionForce));
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN_VOID();
}
 
/**********************************************************************************************************************************/
// Helper to build start backup query
static String *
dbBackupStartQuery(const unsigned int pgVersion, const bool startFast)
{
    FUNCTION_TEST_BEGIN();
        FUNCTION_TEST_PARAM(UINT, pgVersion);
        FUNCTION_TEST_PARAM(BOOL, startFast);
    FUNCTION_TEST_END();
 
    // Build query to return start lsn and WAL segment name
    String *result = strCatFmt(
        strNew(),
        "select lsn::text as lsn,\n"
        "       pg_catalog.pg_walfile_name(lsn)::text as wal_segment_name\n"
        "  from pg_catalog.pg_%s('" PROJECT_NAME " backup started at ' || current_timestamp::text",
        pgVersion >= PG_VERSION_15 ? "backup_start" : "start_backup");
 
    // Start backup after immediate checkpoint
    if (startFast)
    {
        strCatZ(result, ", " TRUE_Z);
    }
    // Else start backup at the next scheduled checkpoint
    else
        strCatZ(result, ", " FALSE_Z);
 
    // Use non-exclusive backup mode when available
    if (pgVersion <= PG_VERSION_14)
        strCatZ(result, ", " FALSE_Z);
 
    // Complete query
    strCatZ(result, ") as lsn");
 
    FUNCTION_TEST_RETURN(STRING, result);
}
 
FN_EXTERN DbBackupStartResult
dbBackupStart(Db *const this, const bool startFast, const bool archiveCheck)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
        FUNCTION_LOG_PARAM(BOOL, startFast);
        FUNCTION_LOG_PARAM(BOOL, archiveCheck);
    FUNCTION_LOG_END();
 
    FUNCTION_AUDIT_STRUCT();
 
    ASSERT(this != NULL);
 
    DbBackupStartResult result = {.lsn = NULL};
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        // When the start-fast option is disabled and db-timeout is smaller than checkpoint_timeout, the command may timeout
        // before the backup actually starts
        if (!startFast && dbDbTimeout(this) <= dbCheckpointTimeout(this))
        {
            LOG_WARN_FMT(
                CFGOPT_START_FAST " is disabled and " CFGOPT_DB_TIMEOUT " (%" PRIu64 "s) is smaller than the " PG_NAME
                " checkpoint_timeout (%" PRIu64 "s) - timeout may occur before the backup starts",
                dbDbTimeout(this) / MSEC_PER_SEC, dbCheckpointTimeout(this) / MSEC_PER_SEC);
        }
 
        // If archive check then get the current WAL segment
        const String *walSegmentCheck = NULL;
 
        if (archiveCheck)
        {
            walSegmentCheck = pckReadStrP(
                dbQueryColumn(this, STRDEF("select pg_catalog.pg_walfile_name(pg_catalog.pg_current_wal_insert_lsn())::text")));
        }
 
        // Start backup
        PackRead *const read = dbQueryRow(this, dbBackupStartQuery(dbPgVersion(this), startFast));
 
        // Make sure the backup start checkpoint was written to pg_control. This helps ensure that we have a consistent view of the
        // storage with PostgreSQL.
        const PgControl pgControl = pgControlFromFile(this->storage, cfgOptionStrNull(cfgOptPgVersionForce));
        const String *const lsnStart = pckReadStrP(read);
 
        if (pgControl.checkpoint < pgLsnFromStr(lsnStart))
        {
            THROW_FMT(
                DbMismatchError, "current checkpoint '%s' is less than backup start '%s'", strZ(pgLsnToStr(pgControl.checkpoint)),
                strZ(lsnStart));
        }
 
        // If archive check then make sure WAL segment was switched on start backup. The WAL segment might not have been switched if
        // a switch occurred before the backup and nothing was written since then. In this case, force a switch so we can verify
        // that archiving is functional before starting the backup.
        const String *const walSegmentName = pckReadStrP(read);
 
        if (archiveCheck && strEq(walSegmentCheck, walSegmentName))
            dbWalSwitch(this);
 
        // Check that the WAL timeline matches what is in pg_control
        if (pgTimelineFromWalSegment(walSegmentName) != dbPgControl(this).timeline)
        {
            THROW_FMT(
                DbMismatchError, "WAL timeline %u does not match " PG_FILE_PGCONTROL " timeline %u",
                pgTimelineFromWalSegment(walSegmentName), dbPgControl(this).timeline);
        }
 
        // Return results
        MEM_CONTEXT_PRIOR_BEGIN()
        {
            result.lsn = strDup(lsnStart);
            result.walSegmentName = strDup(walSegmentName);
            result.walSegmentCheck = strDup(walSegmentCheck);
        }
        MEM_CONTEXT_PRIOR_END();
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN_STRUCT(result);
}
 
/**********************************************************************************************************************************/
// Helper to build stop backup query
static String *
dbBackupStopQuery(const unsigned int pgVersion)
{
    FUNCTION_TEST_BEGIN();
        FUNCTION_TEST_PARAM(UINT, pgVersion);
    FUNCTION_TEST_END();
 
    // Build query to return start lsn and WAL segment name
    String *const result = strCatFmt(
        strNew(),
        "select lsn::text as lsn,\n"
        "       pg_catalog.pg_walfile_name(lsn)::text as wal_segment_name,\n"
        "       labelfile::text as backuplabel_file,\n"
        "       spcmapfile::text as tablespacemap_file\n"
        "  from pg_catalog.pg_%s(",
        pgVersion >= PG_VERSION_15 ? "backup_stop" : "stop_backup");
 
    // Use non-exclusive backup mode when available
    if (pgVersion <= PG_VERSION_14)
        strCatZ(result, FALSE_Z);
 
    // Disable archive checking since we do this elsewhere
    if (pgVersion <= PG_VERSION_14)
        strCatZ(result, ", ");
 
    strCatZ(result, FALSE_Z);
 
    // Complete query
    strCatZ(result, ")");
 
    FUNCTION_TEST_RETURN(STRING, result);
}
 
FN_EXTERN DbBackupStopResult
dbBackupStop(Db *const this)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
    FUNCTION_LOG_END();
 
    FUNCTION_AUDIT_STRUCT();
 
    ASSERT(this != NULL);
 
    DbBackupStopResult result = {.lsn = NULL};
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        // Stop backup
        PackRead *const read = dbQueryRow(this, dbBackupStopQuery(dbPgVersion(this)));
 
        // Return results
        MEM_CONTEXT_PRIOR_BEGIN()
        {
            result.lsn = pckReadStrP(read);
            result.walSegmentName = pckReadStrP(read);
            result.backupLabel = pckReadStrP(read);
 
            // Return the tablespace map if it is not empty
            String *const tablespaceMap = pckReadStrP(read);
            String *const tablespaceMapTrim = strTrim(strDup(tablespaceMap));
 
            if (!strEmpty(tablespaceMapTrim))
                result.tablespaceMap = tablespaceMap;
            else
                strFree(tablespaceMap);
 
            strFree(tablespaceMapTrim);
        }
        MEM_CONTEXT_PRIOR_END();
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN_STRUCT(result);
}
 
/**********************************************************************************************************************************/
FN_EXTERN Pack *
dbList(Db *const this)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
    FUNCTION_LOG_END();
 
    FUNCTION_LOG_RETURN(
        PACK,
        dbQuery(
            this, pgClientQueryResultAny,
            STRDEF(
                "select oid::oid, datname::text, (select oid::oid from pg_catalog.pg_database where datname = 'template0')"
                " as datlastsysoid from pg_catalog.pg_database")));
}
 
/**********************************************************************************************************************************/
FN_EXTERN void
dbReplayWait(Db *const this, const String *const targetLsn, const uint32_t targetTimeline, const TimeMSec timeout)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
        FUNCTION_LOG_PARAM(STRING, targetLsn);
        FUNCTION_LOG_PARAM(UINT, targetTimeline);
        FUNCTION_LOG_PARAM(TIME_MSEC, timeout);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    ASSERT(targetLsn != NULL);
    ASSERT(targetTimeline != 0);
    ASSERT(timeout > 0);
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        // Standby checkpoint before the backup started must be <= the target LSN. If not, it indicates that the standby was ahead
        // of the primary and cannot be following it.
        if (dbPgControl(this).checkpoint > pgLsnFromStr(targetLsn))
        {
            THROW_FMT(
                DbMismatchError, "standby checkpoint '%s' is ahead of target '%s'", strZ(pgLsnToStr(dbPgControl(this).checkpoint)),
                strZ(targetLsn));
        }
 
        // Loop until lsn has been reached or timeout
        Wait *wait = waitNew(timeout);
        bool targetReached = false;
        const String *const replayLsnFunction = STRDEF("pg_catalog.pg_last_wal_replay_lsn()");
        const String *replayLsn = NULL;
 
        do
        {
            // Build the query
            String *const query = strCatFmt(
                strNew(),
                "select replayLsn::text,\n"
                "       (replayLsn > '%s')::bool as targetReached",
                strZ(targetLsn));
 
            if (replayLsn != NULL)
            {
                strCatFmt(
                    query,
                    ",\n"
                    "       (replayLsn > '%s')::bool as replayProgress",
                    strZ(replayLsn));
            }
 
            strCatFmt(
                query,
                "\n"
                "  from %s as replayLsn",
                strZ(replayLsnFunction));
 
            // Execute the query and get replayLsn
            PackRead *const read = dbQueryRow(this, query);
            replayLsn = pckReadStrP(read);
 
            // Error when replayLsn is null which indicates that this is not a standby. This should have been sorted out before we
            // connected but it's possible that the standby was promoted in the meantime.
            if (replayLsn == NULL)
            {
                THROW_FMT(
                    ArchiveTimeoutError,
                    "unable to query replay lsn on the standby using '%s'\n"
                    "HINT: Is this a standby?",
                    strZ(replayLsnFunction));
            }
 
            targetReached = pckReadBoolP(read);
 
            // If the target has not been reached but progress is being made then reset the timer
            if (!targetReached && pckReadBoolP(read, .defaultValue = true))
                wait = waitNew(timeout);
 
            protocolKeepAlive();
        }
        while (!targetReached && waitMore(wait));
 
        // Error if a timeout occurred before the target lsn was reached
        if (!targetReached)
        {
            THROW_FMT(
                ArchiveTimeoutError,
                "timeout before standby replayed to %s - only reached %s\n"
                "HINT: is replication running and current on the standby?\n"
                "HINT: disable the 'backup-standby' option to backup directly from the primary.",
                strZ(targetLsn), strZ(replayLsn));
        }
 
        // Perform a checkpoint
        dbExec(this, STRDEF("checkpoint"));
 
        // Loop until the checkpoint has reached the target lsn (or timeout)
        wait = waitNew(timeout);
        targetReached = false;
        const String *checkpointLsn = NULL;
 
        do
        {
            // Build the query
            const String *const query = strNewFmt(
                "select (checkpoint_lsn >= '%s')::bool as targetReached,\n"
                "       checkpoint_lsn::text as checkpointLsn\n"
                "  from pg_catalog.pg_control_checkpoint()",
                strZ(targetLsn));
 
            // Execute the query and get checkpointLsn
            PackRead *const read = dbQueryRow(this, query);
            targetReached = pckReadBoolP(read);
            checkpointLsn = pckReadStrP(read);
 
            protocolKeepAlive();
        }
        while (!targetReached && waitMore(wait));
 
        // Error if a timeout occurred before the target lsn was reached
        if (!targetReached)
        {
            THROW_FMT(
                ArchiveTimeoutError, "timeout before standby checkpoint lsn reached %s - only reached %s", strZ(targetLsn),
                strZ(checkpointLsn));
        }
 
        // Reload pg_control in case timeline was updated by the checkpoint
        this->pub.pgControl = pgControlFromFile(this->storage, cfgOptionStrNull(cfgOptPgVersionForce));
 
        // Check that the timeline matches the primary
        if (dbPgControl(this).timeline != targetTimeline)
            THROW_FMT(DbMismatchError, "standby is on timeline %u but expected %u", dbPgControl(this).timeline, targetTimeline);
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN_VOID();
}
 
/**********************************************************************************************************************************/
FN_EXTERN void
dbPing(Db *const this, const bool force)
{
    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(DB, this);
        FUNCTION_LOG_PARAM(BOOL, force);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        // Ping if forced or interval has elapsed
        const time_t timeNow = time(NULL);
 
        if (force || timeNow - this->pingTimeLast > DB_PING_SEC)
        {
            // Make sure recovery state has not changed
            if (dbIsInRecovery(this) != dbIsStandby(this))
            {
                // If this is the standby then it must have been promoted
                if (dbIsStandby(this))
                {
                    THROW(
                        DbMismatchError,
                        "standby is no longer in recovery\n"
                        "HINT: was the standby promoted during the backup?");
                }
                // Else if a primary then something has gone seriously wrong
                else
                    THROW(AssertError, "primary has switched to recovery");
            }
 
            this->pingTimeLast = timeNow;
        }
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN_VOID();
}
 
/**********************************************************************************************************************************/
FN_EXTERN Pack *
dbTablespaceList(Db *const this)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
    FUNCTION_LOG_END();
 
    FUNCTION_LOG_RETURN(
        PACK,
        dbQuery(this, pgClientQueryResultAny, STRDEF("select oid::oid, spcname::text from pg_catalog.pg_tablespace")));
}
 
/**********************************************************************************************************************************/
FN_EXTERN TimeMSec
dbTimeMSec(Db *const this)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
    FUNCTION_LOG_END();
 
    TimeMSec result;
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        result = (TimeMSec)pckReadI64P(
            dbQueryColumn(this, STRDEF("select (extract(epoch from clock_timestamp()) * 1000)::bigint")));
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN(TIME_MSEC, result);
}
 
/**********************************************************************************************************************************/
FN_EXTERN String *
dbWalSwitch(Db *const this)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(DB, this);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
 
    String *result;
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        // Create a restore point to ensure current WAL will be archived
        dbQueryColumn(this, STRDEF("select pg_catalog.pg_create_restore_point('" PROJECT_NAME " Archive Check')::text"));
 
        // Request a WAL segment switch
        const String *const walFileName = pckReadStrP(
            dbQueryColumn(this, STRDEF("select pg_catalog.pg_walfile_name(pg_catalog.pg_switch_wal())::text")));
 
        // Copy WAL segment name to the prior context
        MEM_CONTEXT_PRIOR_BEGIN()
        {
            result = strDup(walFileName);
        }
        MEM_CONTEXT_PRIOR_END();
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN(STRING, result);
}
 
/**********************************************************************************************************************************/
FN_EXTERN void
dbToLog(const Db *const this, StringStatic *const debugLog)
{
    strStcCat(debugLog, "{client: ");
    strStcResultSizeInc(
        debugLog, FUNCTION_LOG_OBJECT_FORMAT(this->client, pgClientToLog, strStcRemains(debugLog), strStcRemainsSize(debugLog)));
 
    strStcCat(debugLog, ", remoteClient: ");
    strStcResultSizeInc(
        debugLog,
        FUNCTION_LOG_OBJECT_FORMAT(
            this->remoteClient, protocolClientToLog, strStcRemains(debugLog), strStcRemainsSize(debugLog)));
    strStcCatChr(debugLog, '}');
}