PostgreSQL Source Code git master
Loading...
Searching...
No Matches
pg_subscription.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * pg_subscription.c
4 * replication subscriptions
5 *
6 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 * IDENTIFICATION
10 * src/backend/catalog/pg_subscription.c
11 *
12 *-------------------------------------------------------------------------
13 */
14
15#include "postgres.h"
16
17#include "access/genam.h"
18#include "access/heapam.h"
19#include "access/htup_details.h"
20#include "access/tableam.h"
21#include "catalog/indexing.h"
24#include "catalog/pg_type.h"
25#include "miscadmin.h"
26#include "storage/lmgr.h"
27#include "utils/array.h"
28#include "utils/builtins.h"
29#include "utils/fmgroids.h"
30#include "utils/lsyscache.h"
31#include "utils/pg_lsn.h"
32#include "utils/rel.h"
33#include "utils/syscache.h"
34
36
37/*
38 * Add a comma-separated list of publication names to the 'dest' string.
39 */
40void
42{
43 ListCell *lc;
44 bool first = true;
45
46 Assert(publications != NIL);
47
48 foreach(lc, publications)
49 {
50 char *pubname = strVal(lfirst(lc));
51
52 if (first)
53 first = false;
54 else
55 appendStringInfoString(dest, ", ");
56
57 if (quote_literal)
59 else
60 {
61 appendStringInfoChar(dest, '"');
62 appendStringInfoString(dest, pubname);
63 appendStringInfoChar(dest, '"');
64 }
65 }
66}
67
68/*
69 * Fetch the subscription from the syscache.
70 */
72GetSubscription(Oid subid, bool missing_ok)
73{
75 Subscription *sub;
77 Datum datum;
78 bool isnull;
79
81
83 {
84 if (missing_ok)
85 return NULL;
86
87 elog(ERROR, "cache lookup failed for subscription %u", subid);
88 }
89
91
93 sub->oid = subid;
94 sub->dbid = subform->subdbid;
95 sub->skiplsn = subform->subskiplsn;
96 sub->name = pstrdup(NameStr(subform->subname));
97 sub->owner = subform->subowner;
98 sub->enabled = subform->subenabled;
99 sub->binary = subform->subbinary;
100 sub->stream = subform->substream;
101 sub->twophasestate = subform->subtwophasestate;
102 sub->disableonerr = subform->subdisableonerr;
103 sub->passwordrequired = subform->subpasswordrequired;
104 sub->runasowner = subform->subrunasowner;
105 sub->failover = subform->subfailover;
106 sub->retaindeadtuples = subform->subretaindeadtuples;
107 sub->maxretention = subform->submaxretention;
108 sub->retentionactive = subform->subretentionactive;
109
110 /* Get conninfo */
112 tup,
114 sub->conninfo = TextDatumGetCString(datum);
115
116 /* Get slotname */
118 tup,
120 &isnull);
121 if (!isnull)
122 sub->slotname = pstrdup(NameStr(*DatumGetName(datum)));
123 else
124 sub->slotname = NULL;
125
126 /* Get synccommit */
128 tup,
130 sub->synccommit = TextDatumGetCString(datum);
131
132 /* Get publications */
134 tup,
137
138 /* Get origin */
140 tup,
142 sub->origin = TextDatumGetCString(datum);
143
144 /* Is the subscription owner a superuser? */
146
148
149 return sub;
150}
151
152/*
153 * Return number of subscriptions defined in given database.
154 * Used by dropdb() to check if database can indeed be dropped.
155 */
156int
158{
159 int nsubs = 0;
160 Relation rel;
162 SysScanDesc scan;
164
166
170 ObjectIdGetDatum(dbid));
171
172 scan = systable_beginscan(rel, InvalidOid, false,
173 NULL, 1, &scankey);
174
175 while (HeapTupleIsValid(tup = systable_getnext(scan)))
176 nsubs++;
177
178 systable_endscan(scan);
179
180 table_close(rel, NoLock);
181
182 return nsubs;
183}
184
185/*
186 * Free memory allocated by subscription struct.
187 */
188void
190{
191 pfree(sub->name);
192 pfree(sub->conninfo);
193 if (sub->slotname)
194 pfree(sub->slotname);
196 pfree(sub);
197}
198
199/*
200 * Disable the given subscription.
201 */
202void
204{
205 Relation rel;
206 bool nulls[Natts_pg_subscription];
210
211 /* Look up the subscription in the catalog */
214
215 if (!HeapTupleIsValid(tup))
216 elog(ERROR, "cache lookup failed for subscription %u", subid);
217
219
220 /* Form a new tuple. */
221 memset(values, 0, sizeof(values));
222 memset(nulls, false, sizeof(nulls));
223 memset(replaces, false, sizeof(replaces));
224
225 /* Set the subscription to disabled. */
228
229 /* Update the catalog */
231 replaces);
232 CatalogTupleUpdate(rel, &tup->t_self, tup);
234
235 table_close(rel, NoLock);
236}
237
238/*
239 * Convert text array to list of strings.
240 *
241 * Note: the resulting list of strings is pallocated here.
242 */
243static List *
245{
246 Datum *elems;
247 int nelems,
248 i;
249 List *res = NIL;
250
252
253 if (nelems == 0)
254 return NIL;
255
256 for (i = 0; i < nelems; i++)
257 res = lappend(res, makeString(TextDatumGetCString(elems[i])));
258
259 return res;
260}
261
262/*
263 * Add new state record for a subscription table.
264 *
265 * If retain_lock is true, then don't release the locks taken in this function.
266 * We normally release the locks at the end of transaction but in binary-upgrade
267 * mode, we expect to release those immediately.
268 */
269void
272{
273 Relation rel;
275 bool nulls[Natts_pg_subscription_rel];
277
279
281
282 /* Try finding existing mapping. */
284 ObjectIdGetDatum(relid),
285 ObjectIdGetDatum(subid));
287 elog(ERROR, "subscription relation %u in subscription %u already exists",
288 relid, subid);
289
290 /* Form the tuple. */
291 memset(values, 0, sizeof(values));
292 memset(nulls, false, sizeof(nulls));
298 else
299 nulls[Anum_pg_subscription_rel_srsublsn - 1] = true;
300
302
303 /* Insert tuple into catalog. */
305
307
308 /* Cleanup. */
309 if (retain_lock)
310 {
311 table_close(rel, NoLock);
312 }
313 else
314 {
317 }
318}
319
320/*
321 * Update the state of a subscription table.
322 */
323void
326{
327 Relation rel;
329 bool nulls[Natts_pg_subscription_rel];
332
333 if (already_locked)
334 {
335#ifdef USE_ASSERT_CHECKING
336 LOCKTAG tag;
337
339 RowExclusiveLock, true));
341 Assert(LockHeldByMe(&tag, AccessShareLock, true));
342#endif
343
345 }
346 else
347 {
350 }
351
352 /* Try finding existing mapping. */
354 ObjectIdGetDatum(relid),
355 ObjectIdGetDatum(subid));
356 if (!HeapTupleIsValid(tup))
357 elog(ERROR, "subscription relation %u in subscription %u does not exist",
358 relid, subid);
359
360 /* Update the tuple. */
361 memset(values, 0, sizeof(values));
362 memset(nulls, false, sizeof(nulls));
363 memset(replaces, false, sizeof(replaces));
364
367
371 else
372 nulls[Anum_pg_subscription_rel_srsublsn - 1] = true;
373
375 replaces);
376
377 /* Update the catalog. */
378 CatalogTupleUpdate(rel, &tup->t_self, tup);
379
380 /* Cleanup. */
381 table_close(rel, NoLock);
382}
383
384/*
385 * Get state of subscription table.
386 *
387 * Returns SUBREL_STATE_UNKNOWN when the table is not in the subscription.
388 */
389char
391{
393 char substate;
394 bool isnull;
395 Datum d;
396 Relation rel;
397
398 /*
399 * This is to avoid the race condition with AlterSubscription which tries
400 * to remove this relstate.
401 */
403
404 /* Try finding the mapping. */
406 ObjectIdGetDatum(relid),
407 ObjectIdGetDatum(subid));
408
409 if (!HeapTupleIsValid(tup))
410 {
414 }
415
416 /* Get the state. */
418
419 /* Get the LSN */
422 if (isnull)
424 else
425 *sublsn = DatumGetLSN(d);
426
427 /* Cleanup */
429
431
432 return substate;
433}
434
435/*
436 * Drop subscription relation mapping. These can be for a particular
437 * subscription, or for a particular relation, or both.
438 */
439void
441{
442 Relation rel;
443 TableScanDesc scan;
444 ScanKeyData skey[2];
446 int nkeys = 0;
447
449
450 if (OidIsValid(subid))
451 {
452 ScanKeyInit(&skey[nkeys++],
455 F_OIDEQ,
456 ObjectIdGetDatum(subid));
457 }
458
459 if (OidIsValid(relid))
460 {
461 ScanKeyInit(&skey[nkeys++],
464 F_OIDEQ,
465 ObjectIdGetDatum(relid));
466 }
467
468 /* Do the search and delete what we found. */
469 scan = table_beginscan_catalog(rel, nkeys, skey);
471 {
473
475
476 /*
477 * We don't allow to drop the relation mapping when the table
478 * synchronization is in progress unless the caller updates the
479 * corresponding subscription as well. This is to ensure that we don't
480 * leave tablesync slots or origins in the system when the
481 * corresponding table is dropped. For sequences, however, it's ok to
482 * drop them since no separate slots or origins are created during
483 * synchronization.
484 */
485 if (!OidIsValid(subid) &&
486 subrel->srsubstate != SUBREL_STATE_READY &&
488 {
491 errmsg("could not drop relation mapping for subscription \"%s\"",
492 get_subscription_name(subrel->srsubid, false)),
493 errdetail("Table synchronization for relation \"%s\" is in progress and is in state \"%c\".",
494 get_rel_name(relid), subrel->srsubstate),
495
496 /*
497 * translator: first %s is a SQL ALTER command and second %s is a
498 * SQL DROP command
499 */
500 errhint("Use %s to enable subscription if not already enabled or use %s to drop the subscription.",
501 "ALTER SUBSCRIPTION ... ENABLE",
502 "DROP SUBSCRIPTION ...")));
503 }
504
505 CatalogTupleDelete(rel, &tup->t_self);
506 }
507 table_endscan(scan);
508
510}
511
512/*
513 * Does the subscription have any tables?
514 *
515 * Use this function only to know true/false, and when you have no need for the
516 * List returned by GetSubscriptionRelations.
517 */
518bool
520{
521 Relation rel;
522 ScanKeyData skey[1];
523 SysScanDesc scan;
525 bool has_subtables = false;
526
528
529 ScanKeyInit(&skey[0],
532 ObjectIdGetDatum(subid));
533
534 scan = systable_beginscan(rel, InvalidOid, false,
535 NULL, 1, skey);
536
537 while (HeapTupleIsValid(tup = systable_getnext(scan)))
538 {
540 char relkind;
541
543 relkind = get_rel_relkind(subrel->srrelid);
544
545 if (relkind == RELKIND_RELATION ||
546 relkind == RELKIND_PARTITIONED_TABLE)
547 {
548 has_subtables = true;
549 break;
550 }
551 }
552
553 /* Cleanup */
554 systable_endscan(scan);
556
557 return has_subtables;
558}
559
560/*
561 * Get the relations for the subscription.
562 *
563 * If not_ready is true, return only the relations that are not in a ready
564 * state, otherwise return all the relations of the subscription. The
565 * returned list is palloc'ed in the current memory context.
566 */
567List *
568GetSubscriptionRelations(Oid subid, bool tables, bool sequences,
569 bool not_ready)
570{
571 List *res = NIL;
572 Relation rel;
574 int nkeys = 0;
575 ScanKeyData skey[2];
576 SysScanDesc scan;
577
578 /* One or both of 'tables' and 'sequences' must be true. */
579 Assert(tables || sequences);
580
582
583 ScanKeyInit(&skey[nkeys++],
586 ObjectIdGetDatum(subid));
587
588 if (not_ready)
589 ScanKeyInit(&skey[nkeys++],
593
594 scan = systable_beginscan(rel, InvalidOid, false,
595 NULL, nkeys, skey);
596
597 while (HeapTupleIsValid(tup = systable_getnext(scan)))
598 {
600 SubscriptionRelState *relstate;
601 Datum d;
602 bool isnull;
603 char relkind;
604
606
607 /* Relation is either a sequence or a table */
608 relkind = get_rel_relkind(subrel->srrelid);
609 Assert(relkind == RELKIND_SEQUENCE || relkind == RELKIND_RELATION ||
610 relkind == RELKIND_PARTITIONED_TABLE);
611
612 /* Skip sequences if they were not requested */
613 if ((relkind == RELKIND_SEQUENCE) && !sequences)
614 continue;
615
616 /* Skip tables if they were not requested */
617 if ((relkind == RELKIND_RELATION ||
618 relkind == RELKIND_PARTITIONED_TABLE) && !tables)
619 continue;
620
622 relstate->relid = subrel->srrelid;
623 relstate->state = subrel->srsubstate;
626 if (isnull)
627 relstate->lsn = InvalidXLogRecPtr;
628 else
629 relstate->lsn = DatumGetLSN(d);
630
631 res = lappend(res, relstate);
632 }
633
634 /* Cleanup */
635 systable_endscan(scan);
637
638 return res;
639}
640
641/*
642 * Update the dead tuple retention status for the given subscription.
643 */
644void
646{
647 Relation rel;
648 bool nulls[Natts_pg_subscription];
652
653 /* Look up the subscription in the catalog */
656
657 if (!HeapTupleIsValid(tup))
658 elog(ERROR, "cache lookup failed for subscription %u", subid);
659
661
662 /* Form a new tuple. */
663 memset(values, 0, sizeof(values));
664 memset(nulls, false, sizeof(nulls));
665 memset(replaces, false, sizeof(replaces));
666
667 /* Set the subscription to disabled. */
670
671 /* Update the catalog */
673 replaces);
674 CatalogTupleUpdate(rel, &tup->t_self, tup);
676
677 table_close(rel, NoLock);
678}
#define DatumGetArrayTypeP(X)
Definition array.h:261
void deconstruct_array_builtin(const ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
static Datum values[MAXATTR]
Definition bootstrap.c:155
#define TextDatumGetCString(d)
Definition builtins.h:98
#define NameStr(name)
Definition c.h:765
#define Assert(condition)
Definition c.h:873
#define OidIsValid(objectId)
Definition c.h:788
int errdetail(const char *fmt,...)
Definition elog.c:1216
int errhint(const char *fmt,...)
Definition elog.c:1330
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
#define palloc_object(type)
Definition fe_memutils.h:74
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:514
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1408
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1210
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1117
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1435
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
void CatalogTupleDelete(Relation heapRel, const ItemPointerData *tid)
Definition indexing.c:365
int i
Definition isn.c:77
List * lappend(List *list, void *datum)
Definition list.c:339
void list_free_deep(List *list)
Definition list.c:1560
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1088
bool CheckRelationOidLockedByMe(Oid relid, LOCKMODE lockmode, bool orstronger)
Definition lmgr.c:351
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1148
bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger)
Definition lock.c:643
#define SET_LOCKTAG_OBJECT(locktag, dboid, classoid, objoid, objsubid)
Definition lock.h:264
#define NoLock
Definition lockdefs.h:34
#define AccessShareLock
Definition lockdefs.h:36
#define RowExclusiveLock
Definition lockdefs.h:38
char * get_rel_name(Oid relid)
Definition lsyscache.c:2078
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2153
char * get_subscription_name(Oid subid, bool missing_ok)
Definition lsyscache.c:3845
char * pstrdup(const char *in)
Definition mcxt.c:1781
void pfree(void *pointer)
Definition mcxt.c:1616
static SequenceItem * sequences
Definition pg_dump.c:214
#define lfirst(lc)
Definition pg_list.h:172
#define NIL
Definition pg_list.h:68
static Datum LSNGetDatum(XLogRecPtr X)
Definition pg_lsn.h:31
static XLogRecPtr DatumGetLSN(Datum X)
Definition pg_lsn.h:25
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn, bool already_locked)
int CountDBSubscriptions(Oid dbid)
void FreeSubscription(Subscription *sub)
void DisableSubscription(Oid subid)
void RemoveSubscriptionRel(Oid subid, Oid relid)
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
void GetPublicationsStr(List *publications, StringInfo dest, bool quote_literal)
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn, bool retain_lock)
bool HasSubscriptionTables(Oid subid)
static List * textarray_to_stringlist(ArrayType *textarray)
void UpdateDeadTupleRetentionStatus(Oid subid, bool active)
Subscription * GetSubscription(Oid subid, bool missing_ok)
List * GetSubscriptionRelations(Oid subid, bool tables, bool sequences, bool not_ready)
FormData_pg_subscription * Form_pg_subscription
FormData_pg_subscription_rel * Form_pg_subscription_rel
static Name DatumGetName(Datum X)
Definition postgres.h:390
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
uint64_t Datum
Definition postgres.h:70
static Datum CharGetDatum(char X)
Definition postgres.h:132
#define InvalidOid
unsigned int Oid
static int fb(int x)
char * quote_literal_cstr(const char *rawstr)
Definition quote.c:101
Datum quote_literal(PG_FUNCTION_ARGS)
Definition quote.c:76
#define RelationGetDescr(relation)
Definition rel.h:540
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
@ ForwardScanDirection
Definition sdir.h:28
#define BTEqualStrategyNumber
Definition stratnum.h:31
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
Definition pg_list.h:54
XLogRecPtr skiplsn
bool superuser_arg(Oid roleid)
Definition superuser.c:56
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition syscache.c:220
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition syscache.c:230
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:625
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition syscache.h:93
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, ScanKeyData *key)
Definition tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition tableam.h:985
String * makeString(char *str)
Definition value.c:63
#define strVal(v)
Definition value.h:82
#define XLogRecPtrIsValid(r)
Definition xlogdefs.h:29
uint64 XLogRecPtr
Definition xlogdefs.h:21
#define InvalidXLogRecPtr
Definition xlogdefs.h:28