LCOV - code coverage report
Current view: top level - src/backend/catalog - pg_subscription.c (source / functions) Hit Total Coverage
Test: PostgreSQL 16beta1 Lines: 164 174 94.3 %
Date: 2023-05-30 18:12:27 Functions: 11 11 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * pg_subscription.c
       4             :  *      replication subscriptions
       5             :  *
       6             :  * Portions Copyright (c) 1996-2023, 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 "access/xact.h"
      22             : #include "catalog/indexing.h"
      23             : #include "catalog/pg_subscription.h"
      24             : #include "catalog/pg_subscription_rel.h"
      25             : #include "catalog/pg_type.h"
      26             : #include "miscadmin.h"
      27             : #include "nodes/makefuncs.h"
      28             : #include "storage/lmgr.h"
      29             : #include "utils/array.h"
      30             : #include "utils/builtins.h"
      31             : #include "utils/fmgroids.h"
      32             : #include "utils/lsyscache.h"
      33             : #include "utils/pg_lsn.h"
      34             : #include "utils/rel.h"
      35             : #include "utils/syscache.h"
      36             : 
      37             : static List *textarray_to_stringlist(ArrayType *textarray);
      38             : 
      39             : /*
      40             :  * Fetch the subscription from the syscache.
      41             :  */
      42             : Subscription *
      43        1130 : GetSubscription(Oid subid, bool missing_ok)
      44             : {
      45             :     HeapTuple   tup;
      46             :     Subscription *sub;
      47             :     Form_pg_subscription subform;
      48             :     Datum       datum;
      49             :     bool        isnull;
      50             : 
      51        1130 :     tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
      52             : 
      53        1130 :     if (!HeapTupleIsValid(tup))
      54             :     {
      55           0 :         if (missing_ok)
      56           0 :             return NULL;
      57             : 
      58           0 :         elog(ERROR, "cache lookup failed for subscription %u", subid);
      59             :     }
      60             : 
      61        1130 :     subform = (Form_pg_subscription) GETSTRUCT(tup);
      62             : 
      63        1130 :     sub = (Subscription *) palloc(sizeof(Subscription));
      64        1130 :     sub->oid = subid;
      65        1130 :     sub->dbid = subform->subdbid;
      66        1130 :     sub->skiplsn = subform->subskiplsn;
      67        1130 :     sub->name = pstrdup(NameStr(subform->subname));
      68        1130 :     sub->owner = subform->subowner;
      69        1130 :     sub->enabled = subform->subenabled;
      70        1130 :     sub->binary = subform->subbinary;
      71        1130 :     sub->stream = subform->substream;
      72        1130 :     sub->twophasestate = subform->subtwophasestate;
      73        1130 :     sub->disableonerr = subform->subdisableonerr;
      74        1130 :     sub->passwordrequired = subform->subpasswordrequired;
      75        1130 :     sub->runasowner = subform->subrunasowner;
      76             : 
      77             :     /* Get conninfo */
      78        1130 :     datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
      79             :                                    tup,
      80             :                                    Anum_pg_subscription_subconninfo);
      81        1130 :     sub->conninfo = TextDatumGetCString(datum);
      82             : 
      83             :     /* Get slotname */
      84        1130 :     datum = SysCacheGetAttr(SUBSCRIPTIONOID,
      85             :                             tup,
      86             :                             Anum_pg_subscription_subslotname,
      87             :                             &isnull);
      88        1130 :     if (!isnull)
      89        1064 :         sub->slotname = pstrdup(NameStr(*DatumGetName(datum)));
      90             :     else
      91          66 :         sub->slotname = NULL;
      92             : 
      93             :     /* Get synccommit */
      94        1130 :     datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
      95             :                                    tup,
      96             :                                    Anum_pg_subscription_subsynccommit);
      97        1130 :     sub->synccommit = TextDatumGetCString(datum);
      98             : 
      99             :     /* Get publications */
     100        1130 :     datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
     101             :                                    tup,
     102             :                                    Anum_pg_subscription_subpublications);
     103        1130 :     sub->publications = textarray_to_stringlist(DatumGetArrayTypeP(datum));
     104             : 
     105             :     /* Get origin */
     106        1130 :     datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID,
     107             :                                    tup,
     108             :                                    Anum_pg_subscription_suborigin);
     109        1130 :     sub->origin = TextDatumGetCString(datum);
     110             : 
     111        1130 :     ReleaseSysCache(tup);
     112             : 
     113        1130 :     return sub;
     114             : }
     115             : 
     116             : /*
     117             :  * Return number of subscriptions defined in given database.
     118             :  * Used by dropdb() to check if database can indeed be dropped.
     119             :  */
     120             : int
     121          40 : CountDBSubscriptions(Oid dbid)
     122             : {
     123          40 :     int         nsubs = 0;
     124             :     Relation    rel;
     125             :     ScanKeyData scankey;
     126             :     SysScanDesc scan;
     127             :     HeapTuple   tup;
     128             : 
     129          40 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
     130             : 
     131          40 :     ScanKeyInit(&scankey,
     132             :                 Anum_pg_subscription_subdbid,
     133             :                 BTEqualStrategyNumber, F_OIDEQ,
     134             :                 ObjectIdGetDatum(dbid));
     135             : 
     136          40 :     scan = systable_beginscan(rel, InvalidOid, false,
     137             :                               NULL, 1, &scankey);
     138             : 
     139          40 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
     140           0 :         nsubs++;
     141             : 
     142          40 :     systable_endscan(scan);
     143             : 
     144          40 :     table_close(rel, NoLock);
     145             : 
     146          40 :     return nsubs;
     147             : }
     148             : 
     149             : /*
     150             :  * Free memory allocated by subscription struct.
     151             :  */
     152             : void
     153          48 : FreeSubscription(Subscription *sub)
     154             : {
     155          48 :     pfree(sub->name);
     156          48 :     pfree(sub->conninfo);
     157          48 :     if (sub->slotname)
     158          48 :         pfree(sub->slotname);
     159          48 :     list_free_deep(sub->publications);
     160          48 :     pfree(sub);
     161          48 : }
     162             : 
     163             : /*
     164             :  * Disable the given subscription.
     165             :  */
     166             : void
     167           8 : DisableSubscription(Oid subid)
     168             : {
     169             :     Relation    rel;
     170             :     bool        nulls[Natts_pg_subscription];
     171             :     bool        replaces[Natts_pg_subscription];
     172             :     Datum       values[Natts_pg_subscription];
     173             :     HeapTuple   tup;
     174             : 
     175             :     /* Look up the subscription in the catalog */
     176           8 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
     177           8 :     tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
     178             : 
     179           8 :     if (!HeapTupleIsValid(tup))
     180           0 :         elog(ERROR, "cache lookup failed for subscription %u", subid);
     181             : 
     182           8 :     LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
     183             : 
     184             :     /* Form a new tuple. */
     185           8 :     memset(values, 0, sizeof(values));
     186           8 :     memset(nulls, false, sizeof(nulls));
     187           8 :     memset(replaces, false, sizeof(replaces));
     188             : 
     189             :     /* Set the subscription to disabled. */
     190           8 :     values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(false);
     191           8 :     replaces[Anum_pg_subscription_subenabled - 1] = true;
     192             : 
     193             :     /* Update the catalog */
     194           8 :     tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
     195             :                             replaces);
     196           8 :     CatalogTupleUpdate(rel, &tup->t_self, tup);
     197           8 :     heap_freetuple(tup);
     198             : 
     199           8 :     table_close(rel, NoLock);
     200           8 : }
     201             : 
     202             : /*
     203             :  * Convert text array to list of strings.
     204             :  *
     205             :  * Note: the resulting list of strings is pallocated here.
     206             :  */
     207             : static List *
     208        1130 : textarray_to_stringlist(ArrayType *textarray)
     209             : {
     210             :     Datum      *elems;
     211             :     int         nelems,
     212             :                 i;
     213        1130 :     List       *res = NIL;
     214             : 
     215        1130 :     deconstruct_array_builtin(textarray, TEXTOID, &elems, NULL, &nelems);
     216             : 
     217        1130 :     if (nelems == 0)
     218           0 :         return NIL;
     219             : 
     220        2920 :     for (i = 0; i < nelems; i++)
     221        1790 :         res = lappend(res, makeString(TextDatumGetCString(elems[i])));
     222             : 
     223        1130 :     return res;
     224             : }
     225             : 
     226             : /*
     227             :  * Add new state record for a subscription table.
     228             :  */
     229             : void
     230         316 : AddSubscriptionRelState(Oid subid, Oid relid, char state,
     231             :                         XLogRecPtr sublsn)
     232             : {
     233             :     Relation    rel;
     234             :     HeapTuple   tup;
     235             :     bool        nulls[Natts_pg_subscription_rel];
     236             :     Datum       values[Natts_pg_subscription_rel];
     237             : 
     238         316 :     LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
     239             : 
     240         316 :     rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
     241             : 
     242             :     /* Try finding existing mapping. */
     243         316 :     tup = SearchSysCacheCopy2(SUBSCRIPTIONRELMAP,
     244             :                               ObjectIdGetDatum(relid),
     245             :                               ObjectIdGetDatum(subid));
     246         316 :     if (HeapTupleIsValid(tup))
     247           0 :         elog(ERROR, "subscription table %u in subscription %u already exists",
     248             :              relid, subid);
     249             : 
     250             :     /* Form the tuple. */
     251         316 :     memset(values, 0, sizeof(values));
     252         316 :     memset(nulls, false, sizeof(nulls));
     253         316 :     values[Anum_pg_subscription_rel_srsubid - 1] = ObjectIdGetDatum(subid);
     254         316 :     values[Anum_pg_subscription_rel_srrelid - 1] = ObjectIdGetDatum(relid);
     255         316 :     values[Anum_pg_subscription_rel_srsubstate - 1] = CharGetDatum(state);
     256         316 :     if (sublsn != InvalidXLogRecPtr)
     257           0 :         values[Anum_pg_subscription_rel_srsublsn - 1] = LSNGetDatum(sublsn);
     258             :     else
     259         316 :         nulls[Anum_pg_subscription_rel_srsublsn - 1] = true;
     260             : 
     261         316 :     tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
     262             : 
     263             :     /* Insert tuple into catalog. */
     264         316 :     CatalogTupleInsert(rel, tup);
     265             : 
     266         316 :     heap_freetuple(tup);
     267             : 
     268             :     /* Cleanup. */
     269         316 :     table_close(rel, NoLock);
     270         316 : }
     271             : 
     272             : /*
     273             :  * Update the state of a subscription table.
     274             :  */
     275             : void
     276        1196 : UpdateSubscriptionRelState(Oid subid, Oid relid, char state,
     277             :                            XLogRecPtr sublsn)
     278             : {
     279             :     Relation    rel;
     280             :     HeapTuple   tup;
     281             :     bool        nulls[Natts_pg_subscription_rel];
     282             :     Datum       values[Natts_pg_subscription_rel];
     283             :     bool        replaces[Natts_pg_subscription_rel];
     284             : 
     285        1196 :     LockSharedObject(SubscriptionRelationId, subid, 0, AccessShareLock);
     286             : 
     287        1196 :     rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
     288             : 
     289             :     /* Try finding existing mapping. */
     290        1196 :     tup = SearchSysCacheCopy2(SUBSCRIPTIONRELMAP,
     291             :                               ObjectIdGetDatum(relid),
     292             :                               ObjectIdGetDatum(subid));
     293        1196 :     if (!HeapTupleIsValid(tup))
     294           0 :         elog(ERROR, "subscription table %u in subscription %u does not exist",
     295             :              relid, subid);
     296             : 
     297             :     /* Update the tuple. */
     298        1196 :     memset(values, 0, sizeof(values));
     299        1196 :     memset(nulls, false, sizeof(nulls));
     300        1196 :     memset(replaces, false, sizeof(replaces));
     301             : 
     302        1196 :     replaces[Anum_pg_subscription_rel_srsubstate - 1] = true;
     303        1196 :     values[Anum_pg_subscription_rel_srsubstate - 1] = CharGetDatum(state);
     304             : 
     305        1196 :     replaces[Anum_pg_subscription_rel_srsublsn - 1] = true;
     306        1196 :     if (sublsn != InvalidXLogRecPtr)
     307         588 :         values[Anum_pg_subscription_rel_srsublsn - 1] = LSNGetDatum(sublsn);
     308             :     else
     309         608 :         nulls[Anum_pg_subscription_rel_srsublsn - 1] = true;
     310             : 
     311        1196 :     tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
     312             :                             replaces);
     313             : 
     314             :     /* Update the catalog. */
     315        1196 :     CatalogTupleUpdate(rel, &tup->t_self, tup);
     316             : 
     317             :     /* Cleanup. */
     318        1196 :     table_close(rel, NoLock);
     319        1196 : }
     320             : 
     321             : /*
     322             :  * Get state of subscription table.
     323             :  *
     324             :  * Returns SUBREL_STATE_UNKNOWN when the table is not in the subscription.
     325             :  */
     326             : char
     327        1904 : GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
     328             : {
     329             :     HeapTuple   tup;
     330             :     char        substate;
     331             :     bool        isnull;
     332             :     Datum       d;
     333             :     Relation    rel;
     334             : 
     335             :     /*
     336             :      * This is to avoid the race condition with AlterSubscription which tries
     337             :      * to remove this relstate.
     338             :      */
     339        1904 :     rel = table_open(SubscriptionRelRelationId, AccessShareLock);
     340             : 
     341             :     /* Try finding the mapping. */
     342        1904 :     tup = SearchSysCache2(SUBSCRIPTIONRELMAP,
     343             :                           ObjectIdGetDatum(relid),
     344             :                           ObjectIdGetDatum(subid));
     345             : 
     346        1904 :     if (!HeapTupleIsValid(tup))
     347             :     {
     348          52 :         table_close(rel, AccessShareLock);
     349          52 :         *sublsn = InvalidXLogRecPtr;
     350          52 :         return SUBREL_STATE_UNKNOWN;
     351             :     }
     352             : 
     353             :     /* Get the state. */
     354        1852 :     substate = ((Form_pg_subscription_rel) GETSTRUCT(tup))->srsubstate;
     355             : 
     356             :     /* Get the LSN */
     357        1852 :     d = SysCacheGetAttr(SUBSCRIPTIONRELMAP, tup,
     358             :                         Anum_pg_subscription_rel_srsublsn, &isnull);
     359        1852 :     if (isnull)
     360         966 :         *sublsn = InvalidXLogRecPtr;
     361             :     else
     362         886 :         *sublsn = DatumGetLSN(d);
     363             : 
     364             :     /* Cleanup */
     365        1852 :     ReleaseSysCache(tup);
     366             : 
     367        1852 :     table_close(rel, AccessShareLock);
     368             : 
     369        1852 :     return substate;
     370             : }
     371             : 
     372             : /*
     373             :  * Drop subscription relation mapping. These can be for a particular
     374             :  * subscription, or for a particular relation, or both.
     375             :  */
     376             : void
     377       38496 : RemoveSubscriptionRel(Oid subid, Oid relid)
     378             : {
     379             :     Relation    rel;
     380             :     TableScanDesc scan;
     381             :     ScanKeyData skey[2];
     382             :     HeapTuple   tup;
     383       38496 :     int         nkeys = 0;
     384             : 
     385       38496 :     rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
     386             : 
     387       38496 :     if (OidIsValid(subid))
     388             :     {
     389         200 :         ScanKeyInit(&skey[nkeys++],
     390             :                     Anum_pg_subscription_rel_srsubid,
     391             :                     BTEqualStrategyNumber,
     392             :                     F_OIDEQ,
     393             :                     ObjectIdGetDatum(subid));
     394             :     }
     395             : 
     396       38496 :     if (OidIsValid(relid))
     397             :     {
     398       38356 :         ScanKeyInit(&skey[nkeys++],
     399             :                     Anum_pg_subscription_rel_srrelid,
     400             :                     BTEqualStrategyNumber,
     401             :                     F_OIDEQ,
     402             :                     ObjectIdGetDatum(relid));
     403             :     }
     404             : 
     405             :     /* Do the search and delete what we found. */
     406       38496 :     scan = table_beginscan_catalog(rel, nkeys, skey);
     407       38658 :     while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
     408             :     {
     409             :         Form_pg_subscription_rel subrel;
     410             : 
     411         162 :         subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
     412             : 
     413             :         /*
     414             :          * We don't allow to drop the relation mapping when the table
     415             :          * synchronization is in progress unless the caller updates the
     416             :          * corresponding subscription as well. This is to ensure that we don't
     417             :          * leave tablesync slots or origins in the system when the
     418             :          * corresponding table is dropped.
     419             :          */
     420         162 :         if (!OidIsValid(subid) && subrel->srsubstate != SUBREL_STATE_READY)
     421             :         {
     422           0 :             ereport(ERROR,
     423             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     424             :                      errmsg("could not drop relation mapping for subscription \"%s\"",
     425             :                             get_subscription_name(subrel->srsubid, false)),
     426             :                      errdetail("Table synchronization for relation \"%s\" is in progress and is in state \"%c\".",
     427             :                                get_rel_name(relid), subrel->srsubstate),
     428             : 
     429             :             /*
     430             :              * translator: first %s is a SQL ALTER command and second %s is a
     431             :              * SQL DROP command
     432             :              */
     433             :                      errhint("Use %s to enable subscription if not already enabled or use %s to drop the subscription.",
     434             :                              "ALTER SUBSCRIPTION ... ENABLE",
     435             :                              "DROP SUBSCRIPTION ...")));
     436             :         }
     437             : 
     438         162 :         CatalogTupleDelete(rel, &tup->t_self);
     439             :     }
     440       38496 :     table_endscan(scan);
     441             : 
     442       38496 :     table_close(rel, RowExclusiveLock);
     443       38496 : }
     444             : 
     445             : /*
     446             :  * Does the subscription have any relations?
     447             :  *
     448             :  * Use this function only to know true/false, and when you have no need for the
     449             :  * List returned by GetSubscriptionRelations.
     450             :  */
     451             : bool
     452         342 : HasSubscriptionRelations(Oid subid)
     453             : {
     454             :     Relation    rel;
     455             :     ScanKeyData skey[1];
     456             :     SysScanDesc scan;
     457             :     bool        has_subrels;
     458             : 
     459         342 :     rel = table_open(SubscriptionRelRelationId, AccessShareLock);
     460             : 
     461         342 :     ScanKeyInit(&skey[0],
     462             :                 Anum_pg_subscription_rel_srsubid,
     463             :                 BTEqualStrategyNumber, F_OIDEQ,
     464             :                 ObjectIdGetDatum(subid));
     465             : 
     466         342 :     scan = systable_beginscan(rel, InvalidOid, false,
     467             :                               NULL, 1, skey);
     468             : 
     469             :     /* If even a single tuple exists then the subscription has tables. */
     470         342 :     has_subrels = HeapTupleIsValid(systable_getnext(scan));
     471             : 
     472             :     /* Cleanup */
     473         342 :     systable_endscan(scan);
     474         342 :     table_close(rel, AccessShareLock);
     475             : 
     476         342 :     return has_subrels;
     477             : }
     478             : 
     479             : /*
     480             :  * Get the relations for the subscription.
     481             :  *
     482             :  * If not_ready is true, return only the relations that are not in a ready
     483             :  * state, otherwise return all the relations of the subscription.  The
     484             :  * returned list is palloc'ed in the current memory context.
     485             :  */
     486             : List *
     487        1586 : GetSubscriptionRelations(Oid subid, bool not_ready)
     488             : {
     489        1586 :     List       *res = NIL;
     490             :     Relation    rel;
     491             :     HeapTuple   tup;
     492        1586 :     int         nkeys = 0;
     493             :     ScanKeyData skey[2];
     494             :     SysScanDesc scan;
     495             : 
     496        1586 :     rel = table_open(SubscriptionRelRelationId, AccessShareLock);
     497             : 
     498        1586 :     ScanKeyInit(&skey[nkeys++],
     499             :                 Anum_pg_subscription_rel_srsubid,
     500             :                 BTEqualStrategyNumber, F_OIDEQ,
     501             :                 ObjectIdGetDatum(subid));
     502             : 
     503        1586 :     if (not_ready)
     504        1510 :         ScanKeyInit(&skey[nkeys++],
     505             :                     Anum_pg_subscription_rel_srsubstate,
     506             :                     BTEqualStrategyNumber, F_CHARNE,
     507             :                     CharGetDatum(SUBREL_STATE_READY));
     508             : 
     509        1586 :     scan = systable_beginscan(rel, InvalidOid, false,
     510             :                               NULL, nkeys, skey);
     511             : 
     512        4168 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
     513             :     {
     514             :         Form_pg_subscription_rel subrel;
     515             :         SubscriptionRelState *relstate;
     516             :         Datum       d;
     517             :         bool        isnull;
     518             : 
     519        2582 :         subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
     520             : 
     521        2582 :         relstate = (SubscriptionRelState *) palloc(sizeof(SubscriptionRelState));
     522        2582 :         relstate->relid = subrel->srrelid;
     523        2582 :         relstate->state = subrel->srsubstate;
     524        2582 :         d = SysCacheGetAttr(SUBSCRIPTIONRELMAP, tup,
     525             :                             Anum_pg_subscription_rel_srsublsn, &isnull);
     526        2582 :         if (isnull)
     527        2106 :             relstate->lsn = InvalidXLogRecPtr;
     528             :         else
     529         476 :             relstate->lsn = DatumGetLSN(d);
     530             : 
     531        2582 :         res = lappend(res, relstate);
     532             :     }
     533             : 
     534             :     /* Cleanup */
     535        1586 :     systable_endscan(scan);
     536        1586 :     table_close(rel, AccessShareLock);
     537             : 
     538        1586 :     return res;
     539             : }

Generated by: LCOV version 1.14