Debian Codegraph @

src/backend/catalog/pg_subscription.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * pg_subscription.c
4 * replication subscriptions
5 *
6 * Portions Copyright (c) 1996-2025, 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"
22 #include "catalog/pg_subscription.h"
23 #include "catalog/pg_subscription_rel.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
35 static List *textarray_to_stringlist(ArrayType *textarray);
36
37 /*
38 * Add a comma-separated list of publication names to the 'dest' string.
39 */
40 void
41 GetPublicationsStr(List *publications, StringInfo dest, bool quote_literal)
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)
58 appendStringInfoString(dest, quote_literal_cstr(pubname));
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 */
71 Subscription *
72 GetSubscription(Oid subid, bool missing_ok)
73 {
74 HeapTuple tup;
75 Subscription *sub;
76 Form_pg_subscription subform;
77 Datum datum;
78 bool isnull;
79
80 tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
81
82 if (!HeapTupleIsValid(tup))
83 {
84 if (missing_ok)
85 return NULL;
86
87 elog(ERROR, "cache lookup failed for subscription %u", subid);
88 }
89
90 subform = (Form_pg_subscription) GETSTRUCT(tup);
91
92 sub = (Subscription *) palloc(sizeof(Subscription));
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
107 /* Get conninfo */
108 datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
109 tup,
110 Anum_pg_subscription_subconninfo);
111 sub->conninfo = TextDatumGetCString(datum);
112
113 /* Get slotname */
114 datum = SysCacheGetAttr(SUBSCRIPTIONOID,
115 tup,
116 Anum_pg_subscription_subslotname,
117 &isnull);
118 if (!isnull)
119 sub->slotname = pstrdup(NameStr(*DatumGetName(datum)));
120 else
121 sub->slotname = NULL;
122
123 /* Get synccommit */
124 datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
125 tup,
126 Anum_pg_subscription_subsynccommit);
127 sub->synccommit = TextDatumGetCString(datum);
128
129 /* Get publications */
130 datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
131 tup,
132 Anum_pg_subscription_subpublications);
133 sub->publications = textarray_to_stringlist(DatumGetArrayTypeP(datum));
134
135 /* Get origin */
136 datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
137 tup,
138 Anum_pg_subscription_suborigin);
139 sub->origin = TextDatumGetCString(datum);
140
141 /* Is the subscription owner a superuser? */
142 sub->ownersuperuser = superuser_arg(sub->owner);
143
144 ReleaseSysCache(tup);
145
146 return sub;
147 }
148
149 /*
150 * Return number of subscriptions defined in given database.
151 * Used by dropdb() to check if database can indeed be dropped.
152 */
153 int
154 CountDBSubscriptions(Oid dbid)
155 {
156 int nsubs = 0;
157 Relation rel;
158 ScanKeyData scankey;
159 SysScanDesc scan;
160 HeapTuple tup;
161
162 rel = table_open(SubscriptionRelationId, RowExclusiveLock);
163
164 ScanKeyInit(&scankey,
165 Anum_pg_subscription_subdbid,
166 BTEqualStrategyNumber, F_OIDEQ,
167 ObjectIdGetDatum(dbid));
168
169 scan = systable_beginscan(rel, InvalidOid, false,
170 NULL, 1, &scankey);
171
172 while (HeapTupleIsValid(tup = systable_getnext(scan)))
173 nsubs++;
174
175 systable_endscan(scan);
176
177 table_close(rel, NoLock);
178
179 return nsubs;
180 }
181
182 /*
183 * Free memory allocated by subscription struct.
184 */
185 void
186 FreeSubscription(Subscription *sub)
187 {
188 pfree(sub->name);
189 pfree(sub->conninfo);
190 if (sub->slotname)
191 pfree(sub->slotname);
192 list_free_deep(sub->publications);
193 pfree(sub);
194 }
195
196 /*
197 * Disable the given subscription.
198 */
199 void
200 DisableSubscription(Oid subid)
201 {
202 Relation rel;
203 bool nulls[Natts_pg_subscription];
204 bool replaces[Natts_pg_subscription];
205 Datum values[Natts_pg_subscription];
206 HeapTuple tup;
207
208 /* Look up the subscription in the catalog */
209 rel = table_open(SubscriptionRelationId, RowExclusiveLock);
210 tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
211
212 if (!HeapTupleIsValid(tup))
213 elog(ERROR, "cache lookup failed for subscription %u", subid);
214
215 LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
216
217 /* Form a new tuple. */
218 memset(values, 0, sizeof(values));
219 memset(nulls, false, sizeof(nulls));
220 memset(replaces, false, sizeof(replaces));
221
222 /* Set the subscription to disabled. */
223 values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(false);
224 replaces[Anum_pg_subscription_subenabled - 1] = true;
225
226 /* Update the catalog */
227 tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
228 replaces);
229 CatalogTupleUpdate(rel, &tup->t_self, tup);
230 heap_freetuple(tup);
231
232 table_close(rel, NoLock);
233 }
234
235 /*
236 * Convert text array to list of strings.
237 *
238 * Note: the resulting list of strings is pallocated here.
239 */
240 static List *
241 textarray_to_stringlist(ArrayType *textarray)
242 {
243 Datum *elems;
244 int nelems,
245 i;
246 List *res = NIL;
247
248 deconstruct_array_builtin(textarray, TEXTOID, &elems, NULL, &nelems);
249
250 if (nelems == 0)
251 return NIL;
252
253 for (i = 0; i < nelems; i++)
254 res = lappend(res, makeString(TextDatumGetCString(elems[i])));
255
256 return res;
257 }
258
259 /*
260 * Add new state record for a subscription table.
261 *
262 * If retain_lock is true, then don't release the locks taken in this function.
263 * We normally release the locks at the end of transaction but in binary-upgrade
264 * mode, we expect to release those immediately.
265 */
266 void
267 AddSubscriptionRelState(Oid subid, Oid relid, char state,
268 XLogRecPtr sublsn, bool retain_lock)
269 {
270 Relation rel;
271 HeapTuple tup;
272 bool nulls[Natts_pg_subscription_rel];
273 Datum values[Natts_pg_subscription_rel];
274
275 LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
276
277 rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
278
279 /* Try finding existing mapping. */
280 tup = SearchSysCacheCopy2(SUBSCRIPTIONRELMAP,
281 ObjectIdGetDatum(relid),
282 ObjectIdGetDatum(subid));
283 if (HeapTupleIsValid(tup))
284 elog(ERROR, "subscription table %u in subscription %u already exists",
285 relid, subid);
286
287 /* Form the tuple. */
288 memset(values, 0, sizeof(values));
289 memset(nulls, false, sizeof(nulls));
290 values[Anum_pg_subscription_rel_srsubid - 1] = ObjectIdGetDatum(subid);
291 values[Anum_pg_subscription_rel_srrelid - 1] = ObjectIdGetDatum(relid);
292 values[Anum_pg_subscription_rel_srsubstate - 1] = CharGetDatum(state);
293 if (sublsn != InvalidXLogRecPtr)
294 values[Anum_pg_subscription_rel_srsublsn - 1] = LSNGetDatum(sublsn);
295 else
296 nulls[Anum_pg_subscription_rel_srsublsn - 1] = true;
297
298 tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
299
300 /* Insert tuple into catalog. */
301 CatalogTupleInsert(rel, tup);
302
303 heap_freetuple(tup);
304
305 /* Cleanup. */
306 if (retain_lock)
307 {
308 table_close(rel, NoLock);
309 }
310 else
311 {
312 table_close(rel, RowExclusiveLock);
313 UnlockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
314 }
315 }
316
317 /*
318 * Update the state of a subscription table.
319 */
320 void
321 UpdateSubscriptionRelState(Oid subid, Oid relid, char state,
322 XLogRecPtr sublsn, bool already_locked)
323 {
324 Relation rel;
325 HeapTuple tup;
326 bool nulls[Natts_pg_subscription_rel];
327 Datum values[Natts_pg_subscription_rel];
328 bool replaces[Natts_pg_subscription_rel];
329
330 if (already_locked)
331 {
332 #ifdef USE_ASSERT_CHECKING
333 LOCKTAG tag;
334
335 Assert(CheckRelationOidLockedByMe(SubscriptionRelRelationId,
336 RowExclusiveLock, true));
337 SET_LOCKTAG_OBJECT(tag, InvalidOid, SubscriptionRelationId, subid, 0);
338 Assert(LockHeldByMe(&tag, AccessShareLock, true));
339 #endif
340
341 rel = table_open(SubscriptionRelRelationId, NoLock);
342 }
343 else
344 {
345 LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
346 rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
347 }
348
349 /* Try finding existing mapping. */
350 tup = SearchSysCacheCopy2(SUBSCRIPTIONRELMAP,
351 ObjectIdGetDatum(relid),
352 ObjectIdGetDatum(subid));
353 if (!HeapTupleIsValid(tup))
354 elog(ERROR, "subscription table %u in subscription %u does not exist",
355 relid, subid);
356
357 /* Update the tuple. */
358 memset(values, 0, sizeof(values));
359 memset(nulls, false, sizeof(nulls));
360 memset(replaces, false, sizeof(replaces));
361
362 replaces[Anum_pg_subscription_rel_srsubstate - 1] = true;
363 values[Anum_pg_subscription_rel_srsubstate - 1] = CharGetDatum(state);
364
365 replaces[Anum_pg_subscription_rel_srsublsn - 1] = true;
366 if (sublsn != InvalidXLogRecPtr)
367 values[Anum_pg_subscription_rel_srsublsn - 1] = LSNGetDatum(sublsn);
368 else
369 nulls[Anum_pg_subscription_rel_srsublsn - 1] = true;
370
371 tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
372 replaces);
373
374 /* Update the catalog. */
375 CatalogTupleUpdate(rel, &tup->t_self, tup);
376
377 /* Cleanup. */
378 table_close(rel, NoLock);
379 }
380
381 /*
382 * Get state of subscription table.
383 *
384 * Returns SUBREL_STATE_UNKNOWN when the table is not in the subscription.
385 */
386 char
387 GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
388 {
389 HeapTuple tup;
390 char substate;
391 bool isnull;
392 Datum d;
393 Relation rel;
394
395 /*
396 * This is to avoid the race condition with AlterSubscription which tries
397 * to remove this relstate.
398 */
399 rel = table_open(SubscriptionRelRelationId, AccessShareLock);
400
401 /* Try finding the mapping. */
402 tup = SearchSysCache2(SUBSCRIPTIONRELMAP,
403 ObjectIdGetDatum(relid),
404 ObjectIdGetDatum(subid));
405
406 if (!HeapTupleIsValid(tup))
407 {
408 table_close(rel, AccessShareLock);
409 *sublsn = InvalidXLogRecPtr;
410 return SUBREL_STATE_UNKNOWN;
411 }
412
413 /* Get the state. */
414 substate = ((Form_pg_subscription_rel) GETSTRUCT(tup))->srsubstate;
415
416 /* Get the LSN */
417 d = SysCacheGetAttr(SUBSCRIPTIONRELMAP, tup,
418 Anum_pg_subscription_rel_srsublsn, &isnull);
419 if (isnull)
420 *sublsn = InvalidXLogRecPtr;
421 else
422 *sublsn = DatumGetLSN(d);
423
424 /* Cleanup */
425 ReleaseSysCache(tup);
426
427 table_close(rel, AccessShareLock);
428
429 return substate;
430 }
431
432 /*
433 * Drop subscription relation mapping. These can be for a particular
434 * subscription, or for a particular relation, or both.
435 */
436 void
437 RemoveSubscriptionRel(Oid subid, Oid relid)
438 {
439 Relation rel;
440 TableScanDesc scan;
441 ScanKeyData skey[2];
442 HeapTuple tup;
443 int nkeys = 0;
444
445 rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
446
447 if (OidIsValid(subid))
448 {
449 ScanKeyInit(&skey[nkeys++],
450 Anum_pg_subscription_rel_srsubid,
451 BTEqualStrategyNumber,
452 F_OIDEQ,
453 ObjectIdGetDatum(subid));
454 }
455
456 if (OidIsValid(relid))
457 {
458 ScanKeyInit(&skey[nkeys++],
459 Anum_pg_subscription_rel_srrelid,
460 BTEqualStrategyNumber,
461 F_OIDEQ,
462 ObjectIdGetDatum(relid));
463 }
464
465 /* Do the search and delete what we found. */
466 scan = table_beginscan_catalog(rel, nkeys, skey);
467 while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
468 {
469 Form_pg_subscription_rel subrel;
470
471 subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
472
473 /*
474 * We don't allow to drop the relation mapping when the table
475 * synchronization is in progress unless the caller updates the
476 * corresponding subscription as well. This is to ensure that we don't
477 * leave tablesync slots or origins in the system when the
478 * corresponding table is dropped.
479 */
480 if (!OidIsValid(subid) && subrel->srsubstate != SUBREL_STATE_READY)
481 {
482 ereport(ERROR,
483 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
484 errmsg("could not drop relation mapping for subscription \"%s\"",
485 get_subscription_name(subrel->srsubid, false)),
486 errdetail("Table synchronization for relation \"%s\" is in progress and is in state \"%c\".",
487 get_rel_name(relid), subrel->srsubstate),
488
489 /*
490 * translator: first %s is a SQL ALTER command and second %s is a
491 * SQL DROP command
492 */
493 errhint("Use %s to enable subscription if not already enabled or use %s to drop the subscription.",
494 "ALTER SUBSCRIPTION ... ENABLE",
495 "DROP SUBSCRIPTION ...")));
496 }
497
498 CatalogTupleDelete(rel, &tup->t_self);
499 }
500 table_endscan(scan);
501
502 table_close(rel, RowExclusiveLock);
503 }
504
505 /*
506 * Does the subscription have any relations?
507 *
508 * Use this function only to know true/false, and when you have no need for the
509 * List returned by GetSubscriptionRelations.
510 */
511 bool
512 HasSubscriptionRelations(Oid subid)
513 {
514 Relation rel;
515 ScanKeyData skey[1];
516 SysScanDesc scan;
517 bool has_subrels;
518
519 rel = table_open(SubscriptionRelRelationId, AccessShareLock);
520
521 ScanKeyInit(&skey[0],
522 Anum_pg_subscription_rel_srsubid,
523 BTEqualStrategyNumber, F_OIDEQ,
524 ObjectIdGetDatum(subid));
525
526 scan = systable_beginscan(rel, InvalidOid, false,
527 NULL, 1, skey);
528
529 /* If even a single tuple exists then the subscription has tables. */
530 has_subrels = HeapTupleIsValid(systable_getnext(scan));
531
532 /* Cleanup */
533 systable_endscan(scan);
534 table_close(rel, AccessShareLock);
535
536 return has_subrels;
537 }
538
539 /*
540 * Get the relations for the subscription.
541 *
542 * If not_ready is true, return only the relations that are not in a ready
543 * state, otherwise return all the relations of the subscription. The
544 * returned list is palloc'ed in the current memory context.
545 */
546 List *
547 GetSubscriptionRelations(Oid subid, bool not_ready)
548 {
549 List *res = NIL;
550 Relation rel;
551 HeapTuple tup;
552 int nkeys = 0;
553 ScanKeyData skey[2];
554 SysScanDesc scan;
555
556 rel = table_open(SubscriptionRelRelationId, AccessShareLock);
557
558 ScanKeyInit(&skey[nkeys++],
559 Anum_pg_subscription_rel_srsubid,
560 BTEqualStrategyNumber, F_OIDEQ,
561 ObjectIdGetDatum(subid));
562
563 if (not_ready)
564 ScanKeyInit(&skey[nkeys++],
565 Anum_pg_subscription_rel_srsubstate,
566 BTEqualStrategyNumber, F_CHARNE,
567 CharGetDatum(SUBREL_STATE_READY));
568
569 scan = systable_beginscan(rel, InvalidOid, false,
570 NULL, nkeys, skey);
571
572 while (HeapTupleIsValid(tup = systable_getnext(scan)))
573 {
574 Form_pg_subscription_rel subrel;
575 SubscriptionRelState *relstate;
576 Datum d;
577 bool isnull;
578
579 subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
580
581 relstate = (SubscriptionRelState *) palloc(sizeof(SubscriptionRelState));
582 relstate->relid = subrel->srrelid;
583 relstate->state = subrel->srsubstate;
584 d = SysCacheGetAttr(SUBSCRIPTIONRELMAP, tup,
585 Anum_pg_subscription_rel_srsublsn, &isnull);
586 if (isnull)
587 relstate->lsn = InvalidXLogRecPtr;
588 else
589 relstate->lsn = DatumGetLSN(d);
590
591 res = lappend(res, relstate);
592 }
593
594 /* Cleanup */
595 systable_endscan(scan);
596 table_close(rel, AccessShareLock);
597
598 return res;
599 }