Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
/*-------------------------------------------------------------------------
 *
 * pg_subscription.c
 *      replication subscriptions
 *
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 * IDENTIFICATION
 *      src/backend/catalog/pg_subscription.c
 *
 *-------------------------------------------------------------------------
 */
 
#include "postgres.h"
 
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/tableam.h"
#include "catalog/indexing.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_subscription.h"
#include "catalog/pg_subscription_rel.h"
#include "catalog/pg_type.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "storage/lmgr.h"
#include "storage/lock.h"
#include "utils/acl.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
#include "utils/rel.h"
#include "utils/syscache.h"
 
static List *textarray_to_stringlist(ArrayType *textarray);
 
/*
 * Add a comma-separated list of publication names to the 'dest' string.
 *
 * If quote_literal is true, the returned list can be used to construct an SQL
 * command, thus no translation is applied.  Otherwise, the string can be used
 * to create a user-facing message, so translatable quote marks are added.
 */
void
GetPublicationsStr(List *publications, StringInfo dest, bool quote_literal)
{
    ListCell   *lc;
    bool        first = true;
 
    Assert(publications != NIL);
 
    foreach(lc, publications)
    {
        char       *pubname = strVal(lfirst(lc));
 
        if (quote_literal)
        {
            if (!first)
                appendStringInfoString(dest, ", ");
            appendStringInfoString(dest, quote_literal_cstr(pubname));
        }
        else
        {
            if (first)
                appendStringInfo(dest, _("\"%s\""), pubname);
            else
                appendStringInfo(dest, _(", \"%s\""), pubname);
        }
 
        first = false;
    }
}
 
/*
 * Fetch the subscription from the syscache.
 *
 * Callers that need conninfo must call SubscriptionConninfo().
 */
Subscription *
GetSubscription(Oid subid, bool missing_ok)
{
    HeapTuple   tup;
    Subscription *sub;
    Form_pg_subscription subform;
    Datum       datum;
    bool        isnull;
    MemoryContext cxt;
    MemoryContext oldcxt;
 
    tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
 
    if (!HeapTupleIsValid(tup))
    {
        if (missing_ok)
            return NULL;
 
        elog(ERROR, "cache lookup failed for subscription %u", subid);
    }
 
    cxt = AllocSetContextCreate(CurrentMemoryContext, "subscription",
                                ALLOCSET_SMALL_SIZES);
    oldcxt = MemoryContextSwitchTo(cxt);
 
    subform = (Form_pg_subscription) GETSTRUCT(tup);
 
    /*
     * It's only safe to access subscriptions from another database from the
     * launcher process, which does not call GetSubscription().
     */
    Assert(subform->subdbid == MyDatabaseId);
 
    sub = palloc0_object(Subscription);
    sub->cxt = cxt;
    sub->oid = subid;
    sub->dbid = subform->subdbid;
    sub->skiplsn = subform->subskiplsn;
    sub->name = pstrdup(NameStr(subform->subname));
    sub->owner = subform->subowner;
    sub->enabled = subform->subenabled;
    sub->binary = subform->subbinary;
    sub->stream = subform->substream;
    sub->twophasestate = subform->subtwophasestate;
    sub->disableonerr = subform->subdisableonerr;
    sub->passwordrequired = subform->subpasswordrequired;
    sub->runasowner = subform->subrunasowner;
    sub->failover = subform->subfailover;
    sub->retaindeadtuples = subform->subretaindeadtuples;
    sub->maxretention = subform->submaxretention;
    sub->retentionactive = subform->subretentionactive;
 
    /* Get slotname */
    datum = SysCacheGetAttr(SUBSCRIPTIONOID,
                            tup,
                            Anum_pg_subscription_subslotname,
                            &isnull);
    if (!isnull)
        sub->slotname = pstrdup(NameStr(*DatumGetName(datum)));
    else
        sub->slotname = NULL;
 
    /* Get synccommit */
    datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
                                   tup,
                                   Anum_pg_subscription_subsynccommit);
    sub->synccommit = TextDatumGetCString(datum);
 
    /* Get walrcvtimeout */
    datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
                                   tup,
                                   Anum_pg_subscription_subwalrcvtimeout);
    sub->walrcvtimeout = TextDatumGetCString(datum);
 
    /* Get publications */
    datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
                                   tup,
                                   Anum_pg_subscription_subpublications);
    sub->publications = textarray_to_stringlist(DatumGetArrayTypeP(datum));
 
    /* Get origin */
    datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
                                   tup,
                                   Anum_pg_subscription_suborigin);
    sub->origin = TextDatumGetCString(datum);
 
    /* Is the subscription owner a superuser? */
    sub->ownersuperuser = superuser_arg(sub->owner);
 
    ReleaseSysCache(tup);
 
    MemoryContextSwitchTo(oldcxt);
 
    return sub;
}
 
/*
 * Generate the connection string for a subscription.
 *
 * This is deliberately separate from GetSubscription() because resolving
 * conninfo for a server-based subscription has its own error paths (foreign
 * server USAGE, user mapping, ForeignServerConnectionString()).  Keeping it
 * separate lets a caller load the subscription and decide whether a
 * connection is actually needed, and check things such as whether the
 * subscription is enabled, before risking those errors.  Callers that never
 * connect thus never hit them, which matters during restore.
 */
char *
SubscriptionConninfo(Subscription *sub)
{
    HeapTuple   tup;
    Form_pg_subscription subform;
    Datum       datum;
    char       *conninfo;
 
    tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(sub->oid));
    if (!HeapTupleIsValid(tup))
        elog(ERROR, "cache lookup failed for subscription %u", sub->oid);
 
    subform = (Form_pg_subscription) GETSTRUCT(tup);
 
    if (OidIsValid(subform->subserver))
    {
        ForeignServer *server;
        AclResult   aclresult;
 
        server = GetForeignServer(subform->subserver);
 
        aclresult = object_aclcheck(ForeignServerRelationId,
                                    subform->subserver,
                                    sub->owner, ACL_USAGE);
        if (aclresult != ACLCHECK_OK)
            ereport(ERROR,
                    (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                     errmsg("subscription owner \"%s\" does not have permission on foreign server \"%s\"",
                            GetUserNameFromId(sub->owner, false),
                            server->servername)));
 
        conninfo = ForeignServerConnectionString(sub->owner, server);
    }
    else
    {
        datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
                                       Anum_pg_subscription_subconninfo);
        conninfo = TextDatumGetCString(datum);
    }
 
    ReleaseSysCache(tup);
 
    return conninfo;
}
 
/*
 * Return number of subscriptions defined in given database.
 * Used by dropdb() to check if database can indeed be dropped.
 */
int
CountDBSubscriptions(Oid dbid)
{
    int         nsubs = 0;
    Relation    rel;
    ScanKeyData scankey;
    SysScanDesc scan;
    HeapTuple   tup;
 
    rel = table_open(SubscriptionRelationId, RowExclusiveLock);
 
    ScanKeyInit(&scankey,
                Anum_pg_subscription_subdbid,
                BTEqualStrategyNumber, F_OIDEQ,
                ObjectIdGetDatum(dbid));
 
    scan = systable_beginscan(rel, InvalidOid, false,
                              NULL, 1, &scankey);
 
    while (HeapTupleIsValid(tup = systable_getnext(scan)))
        nsubs++;
 
    systable_endscan(scan);
 
    table_close(rel, NoLock);
 
    return nsubs;
}
 
/*
 * Disable the given subscription.
 */
void
DisableSubscription(Oid subid)
{
    Relation    rel;
    bool        nulls[Natts_pg_subscription];
    bool        replaces[Natts_pg_subscription];
    Datum       values[Natts_pg_subscription];
    HeapTuple   tup;
 
    /* Look up the subscription in the catalog */
    rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
 
    if (!HeapTupleIsValid(tup))
        elog(ERROR, "cache lookup failed for subscription %u", subid);
 
    /* Must only modify subscriptions belonging to the current database. */
    Assert(((Form_pg_subscription) GETSTRUCT(tup))->subdbid == MyDatabaseId);
 
    LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
 
    /* Form a new tuple. */
    memset(values, 0, sizeof(values));
    memset(nulls, false, sizeof(nulls));
    memset(replaces, false, sizeof(replaces));
 
    /* Set the subscription to disabled. */
    values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(false);
    replaces[Anum_pg_subscription_subenabled - 1] = true;
 
    /* Update the catalog */
    tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
                            replaces);
    CatalogTupleUpdate(rel, &tup->t_self, tup);
    heap_freetuple(tup);
 
    table_close(rel, NoLock);
}
 
/*
 * Convert text array to list of strings.
 *
 * Note: the resulting list of strings is pallocated here.
 */
static List *
textarray_to_stringlist(ArrayType *textarray)
{
    Datum      *elems;
    int         nelems,
                i;
    List       *res = NIL;
 
    deconstruct_array_builtin(textarray, TEXTOID, &elems, NULL, &nelems);
 
    if (nelems == 0)
        return NIL;
 
    for (i = 0; i < nelems; i++)
        res = lappend(res, makeString(TextDatumGetCString(elems[i])));
 
    return res;
}
 
/*
 * Add new state record for a subscription table.
 *
 * If retain_lock is true, then don't release the locks taken in this function.
 * We normally release the locks at the end of transaction but in binary-upgrade
 * mode, we expect to release those immediately.
 */
void
AddSubscriptionRelState(Oid subid, Oid relid, char state,
                        XLogRecPtr sublsn, bool retain_lock)
{
    Relation    rel;
    HeapTuple   tup;
    bool        nulls[Natts_pg_subscription_rel];
    Datum       values[Natts_pg_subscription_rel];
 
    LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
 
    rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
 
    /* Try finding existing mapping. */
    tup = SearchSysCacheCopy2(SUBSCRIPTIONRELMAP,
                              ObjectIdGetDatum(relid),
                              ObjectIdGetDatum(subid));
    if (HeapTupleIsValid(tup))
        elog(ERROR, "subscription relation %u in subscription %u already exists",
             relid, subid);
 
    /* Form the tuple. */
    memset(values, 0, sizeof(values));
    memset(nulls, false, sizeof(nulls));
    values[Anum_pg_subscription_rel_srsubid - 1] = ObjectIdGetDatum(subid);
    values[Anum_pg_subscription_rel_srrelid - 1] = ObjectIdGetDatum(relid);
    values[Anum_pg_subscription_rel_srsubstate - 1] = CharGetDatum(state);
    if (XLogRecPtrIsValid(sublsn))
        values[Anum_pg_subscription_rel_srsublsn - 1] = LSNGetDatum(sublsn);
    else
        nulls[Anum_pg_subscription_rel_srsublsn - 1] = true;
 
    tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
 
    /* Insert tuple into catalog. */
    CatalogTupleInsert(rel, tup);
 
    heap_freetuple(tup);
 
    /* Cleanup. */
    if (retain_lock)
    {
        table_close(rel, NoLock);
    }
    else
    {
        table_close(rel, RowExclusiveLock);
        UnlockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
    }
}
 
/*
 * Update the state of a subscription table.
 */
void
UpdateSubscriptionRelState(Oid subid, Oid relid, char state,
                           XLogRecPtr sublsn, bool already_locked)
{
    Relation    rel;
    HeapTuple   tup;
    bool        nulls[Natts_pg_subscription_rel];
    Datum       values[Natts_pg_subscription_rel];
    bool        replaces[Natts_pg_subscription_rel];
 
    if (already_locked)
    {
#ifdef USE_ASSERT_CHECKING
        LOCKTAG     tag;
 
        Assert(CheckRelationOidLockedByMe(SubscriptionRelRelationId,
                                          RowExclusiveLock, true));
        SET_LOCKTAG_OBJECT(tag, InvalidOid, SubscriptionRelationId, subid, 0);
        Assert(LockHeldByMe(&tag, AccessShareLock, true));
#endif
 
        rel = table_open(SubscriptionRelRelationId, NoLock);
    }
    else
    {
        LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
        rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
    }
 
    /* Try finding existing mapping. */
    tup = SearchSysCacheCopy2(SUBSCRIPTIONRELMAP,
                              ObjectIdGetDatum(relid),
                              ObjectIdGetDatum(subid));
    if (!HeapTupleIsValid(tup))
        elog(ERROR, "subscription relation %u in subscription %u does not exist",
             relid, subid);
 
    /* Update the tuple. */
    memset(values, 0, sizeof(values));
    memset(nulls, false, sizeof(nulls));
    memset(replaces, false, sizeof(replaces));
 
    replaces[Anum_pg_subscription_rel_srsubstate - 1] = true;
    values[Anum_pg_subscription_rel_srsubstate - 1] = CharGetDatum(state);
 
    replaces[Anum_pg_subscription_rel_srsublsn - 1] = true;
    if (XLogRecPtrIsValid(sublsn))
        values[Anum_pg_subscription_rel_srsublsn - 1] = LSNGetDatum(sublsn);
    else
        nulls[Anum_pg_subscription_rel_srsublsn - 1] = true;
 
    tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
                            replaces);
 
    /* Update the catalog. */
    CatalogTupleUpdate(rel, &tup->t_self, tup);
 
    /* Cleanup. */
    table_close(rel, NoLock);
}
 
/*
 * Get state of subscription table.
 *
 * Returns SUBREL_STATE_UNKNOWN when the table is not in the subscription.
 */
char
GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
{
    HeapTuple   tup;
    char        substate;
    bool        isnull;
    Datum       d;
    Relation    rel;
 
    /*
     * This is to avoid the race condition with AlterSubscription which tries
     * to remove this relstate.
     */
    rel = table_open(SubscriptionRelRelationId, AccessShareLock);
 
    /* Try finding the mapping. */
    tup = SearchSysCache2(SUBSCRIPTIONRELMAP,
                          ObjectIdGetDatum(relid),
                          ObjectIdGetDatum(subid));
 
    if (!HeapTupleIsValid(tup))
    {
        table_close(rel, AccessShareLock);
        *sublsn = InvalidXLogRecPtr;
        return SUBREL_STATE_UNKNOWN;
    }
 
    /* Get the state. */
    substate = ((Form_pg_subscription_rel) GETSTRUCT(tup))->srsubstate;
 
    /* Get the LSN */
    d = SysCacheGetAttr(SUBSCRIPTIONRELMAP, tup,
                        Anum_pg_subscription_rel_srsublsn, &isnull);
    if (isnull)
        *sublsn = InvalidXLogRecPtr;
    else
        *sublsn = DatumGetLSN(d);
 
    /* Cleanup */
    ReleaseSysCache(tup);
 
    table_close(rel, AccessShareLock);
 
    return substate;
}
 
/*
 * Drop subscription relation mapping. These can be for a particular
 * subscription, or for a particular relation, or both.
 */
void
RemoveSubscriptionRel(Oid subid, Oid relid)
{
    Relation    rel;
    TableScanDesc scan;
    ScanKeyData skey[2];
    HeapTuple   tup;
    int         nkeys = 0;
 
    rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
 
    if (OidIsValid(subid))
    {
        ScanKeyInit(&skey[nkeys++],
                    Anum_pg_subscription_rel_srsubid,
                    BTEqualStrategyNumber,
                    F_OIDEQ,
                    ObjectIdGetDatum(subid));
    }
 
    if (OidIsValid(relid))
    {
        ScanKeyInit(&skey[nkeys++],
                    Anum_pg_subscription_rel_srrelid,
                    BTEqualStrategyNumber,
                    F_OIDEQ,
                    ObjectIdGetDatum(relid));
    }
 
    /* Do the search and delete what we found. */
    scan = table_beginscan_catalog(rel, nkeys, skey);
    while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
    {
        Form_pg_subscription_rel subrel;
 
        subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
 
        /*
         * We don't allow to drop the relation mapping when the table
         * synchronization is in progress unless the caller updates the
         * corresponding subscription as well. This is to ensure that we don't
         * leave tablesync slots or origins in the system when the
         * corresponding table is dropped. For sequences, however, it's ok to
         * drop them since no separate slots or origins are created during
         * synchronization.
         */
        if (!OidIsValid(subid) &&
            subrel->srsubstate != SUBREL_STATE_READY &&
            get_rel_relkind(subrel->srrelid) != RELKIND_SEQUENCE)
        {
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("could not drop relation mapping for subscription \"%s\"",
                            get_subscription_name(subrel->srsubid, false)),
                     errdetail("Table synchronization for relation \"%s\" is in progress and is in state \"%c\".",
                               get_rel_name(relid), subrel->srsubstate),
 
            /*
             * translator: first %s is a SQL ALTER command and second %s is a
             * SQL DROP command
             */
                     errhint("Use %s to enable subscription if not already enabled or use %s to drop the subscription.",
                             "ALTER SUBSCRIPTION ... ENABLE",
                             "DROP SUBSCRIPTION ...")));
        }
 
        CatalogTupleDelete(rel, &tup->t_self);
    }
    table_endscan(scan);
 
    table_close(rel, RowExclusiveLock);
}
 
/*
 * Does the subscription have any tables?
 *
 * Use this function only to know true/false, and when you have no need for the
 * List returned by GetSubscriptionRelations.
 */
bool
HasSubscriptionTables(Oid subid)
{
    Relation    rel;
    ScanKeyData skey[1];
    SysScanDesc scan;
    HeapTuple   tup;
    bool        has_subtables = false;
 
    rel = table_open(SubscriptionRelRelationId, AccessShareLock);
 
    ScanKeyInit(&skey[0],
                Anum_pg_subscription_rel_srsubid,
                BTEqualStrategyNumber, F_OIDEQ,
                ObjectIdGetDatum(subid));
 
    scan = systable_beginscan(rel, InvalidOid, false,
                              NULL, 1, skey);
 
    while (HeapTupleIsValid(tup = systable_getnext(scan)))
    {
        Form_pg_subscription_rel subrel;
        char        relkind;
 
        subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
        relkind = get_rel_relkind(subrel->srrelid);
 
        if (relkind == RELKIND_RELATION ||
            relkind == RELKIND_PARTITIONED_TABLE)
        {
            has_subtables = true;
            break;
        }
    }
 
    /* Cleanup */
    systable_endscan(scan);
    table_close(rel, AccessShareLock);
 
    return has_subtables;
}
 
/*
 * Get the relations for the subscription.
 *
 * If not_ready is true, return only the relations that are not in a ready
 * state, otherwise return all the relations of the subscription.  The
 * returned list is palloc'ed in the current memory context.
 */
List *
GetSubscriptionRelations(Oid subid, bool tables, bool sequences,
                         bool not_ready)
{
    List       *res = NIL;
    Relation    rel;
    HeapTuple   tup;
    int         nkeys = 0;
    ScanKeyData skey[2];
    SysScanDesc scan;
 
    /* One or both of 'tables' and 'sequences' must be true. */
    Assert(tables || sequences);
 
    rel = table_open(SubscriptionRelRelationId, AccessShareLock);
 
    ScanKeyInit(&skey[nkeys++],
                Anum_pg_subscription_rel_srsubid,
                BTEqualStrategyNumber, F_OIDEQ,
                ObjectIdGetDatum(subid));
 
    if (not_ready)
        ScanKeyInit(&skey[nkeys++],
                    Anum_pg_subscription_rel_srsubstate,
                    BTEqualStrategyNumber, F_CHARNE,
                    CharGetDatum(SUBREL_STATE_READY));
 
    scan = systable_beginscan(rel, InvalidOid, false,
                              NULL, nkeys, skey);
 
    while (HeapTupleIsValid(tup = systable_getnext(scan)))
    {
        Form_pg_subscription_rel subrel;
        SubscriptionRelState *relstate;
        Datum       d;
        bool        isnull;
        char        relkind;
 
        subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
 
        relkind = get_rel_relkind(subrel->srrelid);
 
        /* The relation may have been dropped concurrently. */
        if (relkind == '\0')
            continue;
 
        /*
         * The relation must be either a sequence or a table. Anything else
         * indicates an unexpected relation kind for a subscription relation.
         */
        if (relkind == RELKIND_SEQUENCE)
        {
            /* Skip sequences if they were not requested */
            if (!sequences)
                continue;
        }
        else if (relkind == RELKIND_RELATION ||
                 relkind == RELKIND_PARTITIONED_TABLE)
        {
            /* Skip tables if they were not requested */
            if (!tables)
                continue;
        }
        else
            elog(ERROR, "unexpected relkind \"%c\" for relation %u in subscription %u",
                 relkind, subrel->srrelid, subid);
 
        relstate = palloc_object(SubscriptionRelState);
        relstate->relid = subrel->srrelid;
        relstate->state = subrel->srsubstate;
        d = SysCacheGetAttr(SUBSCRIPTIONRELMAP, tup,
                            Anum_pg_subscription_rel_srsublsn, &isnull);
        if (isnull)
            relstate->lsn = InvalidXLogRecPtr;
        else
            relstate->lsn = DatumGetLSN(d);
 
        res = lappend(res, relstate);
    }
 
    /* Cleanup */
    systable_endscan(scan);
    table_close(rel, AccessShareLock);
 
    return res;
}
 
/*
 * Update the dead tuple retention status for the given subscription.
 */
void
UpdateDeadTupleRetentionStatus(Oid subid, bool active)
{
    Relation    rel;
    bool        nulls[Natts_pg_subscription];
    bool        replaces[Natts_pg_subscription];
    Datum       values[Natts_pg_subscription];
    HeapTuple   tup;
 
    /* Look up the subscription in the catalog */
    rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
 
    if (!HeapTupleIsValid(tup))
        elog(ERROR, "cache lookup failed for subscription %u", subid);
 
    /* Must only modify subscriptions belonging to the current database. */
    Assert(((Form_pg_subscription) GETSTRUCT(tup))->subdbid == MyDatabaseId);
 
    LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
 
    /* Form a new tuple. */
    memset(values, 0, sizeof(values));
    memset(nulls, false, sizeof(nulls));
    memset(replaces, false, sizeof(replaces));
 
    /* Set the subscription to disabled. */
    values[Anum_pg_subscription_subretentionactive - 1] = BoolGetDatum(active);
    replaces[Anum_pg_subscription_subretentionactive - 1] = true;
 
    /* Update the catalog */
    tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
                            replaces);
    CatalogTupleUpdate(rel, &tup->t_self, tup);
    heap_freetuple(tup);
 
    table_close(rel, NoLock);
}