PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
pg_publication.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pg_publication.c
4  * publication C API manipulation
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * pg_publication.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 
15 #include "postgres.h"
16 
17 #include "funcapi.h"
18 #include "miscadmin.h"
19 
20 #include "access/genam.h"
21 #include "access/hash.h"
22 #include "access/heapam.h"
23 #include "access/htup_details.h"
24 #include "access/xact.h"
25 
26 #include "catalog/catalog.h"
27 #include "catalog/dependency.h"
28 #include "catalog/index.h"
29 #include "catalog/indexing.h"
30 #include "catalog/namespace.h"
31 #include "catalog/objectaccess.h"
32 #include "catalog/objectaddress.h"
33 #include "catalog/pg_type.h"
34 #include "catalog/pg_publication.h"
36 
37 #include "utils/array.h"
38 #include "utils/builtins.h"
39 #include "utils/catcache.h"
40 #include "utils/fmgroids.h"
41 #include "utils/inval.h"
42 #include "utils/lsyscache.h"
43 #include "utils/rel.h"
44 #include "utils/syscache.h"
45 
46 /*
47  * Check if relation can be in given publication and throws appropriate
48  * error if not.
49  */
50 static void
52 {
53  /* Give more specific error for partitioned tables */
54  if (RelationGetForm(targetrel)->relkind == RELKIND_PARTITIONED_TABLE)
55  ereport(ERROR,
56  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
57  errmsg("\"%s\" is a partitioned table",
58  RelationGetRelationName(targetrel)),
59  errdetail("Adding partitioned tables to publications is not supported."),
60  errhint("You can add the table partitions individually.")));
61 
62  /* Must be table */
63  if (RelationGetForm(targetrel)->relkind != RELKIND_RELATION)
64  ereport(ERROR,
65  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
66  errmsg("\"%s\" is not a table",
67  RelationGetRelationName(targetrel)),
68  errdetail("Only tables can be added to publications.")));
69 
70  /* Can't be system table */
71  if (IsCatalogRelation(targetrel))
72  ereport(ERROR,
73  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
74  errmsg("\"%s\" is a system table",
75  RelationGetRelationName(targetrel)),
76  errdetail("System tables cannot be added to publications.")));
77 
78  /* UNLOGGED and TEMP relations cannot be part of publication. */
79  if (!RelationNeedsWAL(targetrel))
80  ereport(ERROR,
81  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
82  errmsg("table \"%s\" cannot be replicated",
83  RelationGetRelationName(targetrel)),
84  errdetail("Temporary and unlogged relations cannot be replicated.")));
85 }
86 
87 /*
88  * Returns if relation represented by oid and Form_pg_class entry
89  * is publishable.
90  *
91  * Does same checks as the above, but does not need relation to be opened
92  * and also does not throw errors.
93  */
94 static bool
96 {
97  return reltuple->relkind == RELKIND_RELATION &&
98  !IsCatalogClass(relid, reltuple) &&
99  reltuple->relpersistence == RELPERSISTENCE_PERMANENT &&
100  /*
101  * Also exclude any tables created as part of initdb. This mainly
102  * affects the preinstalled information_schema.
103  * Note that IsCatalogClass() only checks for these inside pg_catalog
104  * and toast schemas.
105  */
106  relid >= FirstNormalObjectId;
107 }
108 
109 /*
110  * Insert new publication / relation mapping.
111  */
114  bool if_not_exists)
115 {
116  Relation rel;
117  HeapTuple tup;
119  bool nulls[Natts_pg_publication_rel];
120  Oid relid = RelationGetRelid(targetrel);
121  Oid prrelid;
122  Publication *pub = GetPublication(pubid);
123  ObjectAddress myself,
124  referenced;
125 
127 
128  /*
129  * Check for duplicates. Note that this does not really prevent
130  * duplicates, it's here just to provide nicer error message in common
131  * case. The real protection is the unique key on the catalog.
132  */
134  ObjectIdGetDatum(pubid)))
135  {
137 
138  if (if_not_exists)
139  return InvalidObjectAddress;
140 
141  ereport(ERROR,
143  errmsg("relation \"%s\" is already member of publication \"%s\"",
144  RelationGetRelationName(targetrel), pub->name)));
145  }
146 
148 
149  /* Form a tuple. */
150  memset(values, 0, sizeof(values));
151  memset(nulls, false, sizeof(nulls));
152 
153  values[Anum_pg_publication_rel_prpubid - 1] =
154  ObjectIdGetDatum(pubid);
155  values[Anum_pg_publication_rel_prrelid - 1] =
156  ObjectIdGetDatum(relid);
157 
158  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
159 
160  /* Insert tuple into catalog. */
161  prrelid = CatalogTupleInsert(rel, tup);
162  heap_freetuple(tup);
163 
164  ObjectAddressSet(myself, PublicationRelRelationId, prrelid);
165 
166  /* Add dependency on the publication */
167  ObjectAddressSet(referenced, PublicationRelationId, pubid);
168  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
169 
170  /* Add dependency on the relation */
171  ObjectAddressSet(referenced, RelationRelationId, relid);
172  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
173 
174  /* Close the table. */
176 
177  /* Invalidate relcache so that publication info is rebuilt. */
178  CacheInvalidateRelcache(targetrel);
179 
180  return myself;
181 }
182 
183 
184 /*
185  * Gets list of publication oids for a relation oid.
186  */
187 List *
189 {
190  List *result = NIL;
191  CatCList *pubrellist;
192  int i;
193 
194  /* Find all publications associated with the relation. */
196  ObjectIdGetDatum(relid));
197  for (i = 0; i < pubrellist->n_members; i++)
198  {
199  HeapTuple tup = &pubrellist->members[i]->tuple;
200  Oid pubid = ((Form_pg_publication_rel) GETSTRUCT(tup))->prpubid;
201 
202  result = lappend_oid(result, pubid);
203  }
204 
205  ReleaseSysCacheList(pubrellist);
206 
207  return result;
208 }
209 
210 /*
211  * Gets list of relation oids for a publication.
212  *
213  * This should only be used for normal publications, the FOR ALL TABLES
214  * should use GetAllTablesPublicationRelations().
215  */
216 List *
218 {
219  List *result;
220  Relation pubrelsrel;
221  ScanKeyData scankey;
222  SysScanDesc scan;
223  HeapTuple tup;
224 
225  /* Find all publications associated with the relation. */
227 
228  ScanKeyInit(&scankey,
230  BTEqualStrategyNumber, F_OIDEQ,
231  ObjectIdGetDatum(pubid));
232 
234  true, NULL, 1, &scankey);
235 
236  result = NIL;
237  while (HeapTupleIsValid(tup = systable_getnext(scan)))
238  {
240 
241  pubrel = (Form_pg_publication_rel) GETSTRUCT(tup);
242 
243  result = lappend_oid(result, pubrel->prrelid);
244  }
245 
246  systable_endscan(scan);
247  heap_close(pubrelsrel, AccessShareLock);
248 
249  return result;
250 }
251 
252 /*
253  * Gets list of publication oids for publications marked as FOR ALL TABLES.
254  */
255 List *
257 {
258  List *result;
259  Relation rel;
260  ScanKeyData scankey;
261  SysScanDesc scan;
262  HeapTuple tup;
263 
264  /* Find all publications that are marked as for all tables. */
266 
267  ScanKeyInit(&scankey,
269  BTEqualStrategyNumber, F_BOOLEQ,
270  BoolGetDatum(true));
271 
272  scan = systable_beginscan(rel, InvalidOid, false,
273  NULL, 1, &scankey);
274 
275  result = NIL;
276  while (HeapTupleIsValid(tup = systable_getnext(scan)))
277  result = lappend_oid(result, HeapTupleGetOid(tup));
278 
279  systable_endscan(scan);
281 
282  return result;
283 }
284 
285 /*
286  * Gets list of all relation published by FOR ALL TABLES publication(s).
287  */
288 List *
290 {
291  Relation classRel;
292  ScanKeyData key[1];
293  HeapScanDesc scan;
294  HeapTuple tuple;
295  List *result = NIL;
296 
298 
299  ScanKeyInit(&key[0],
301  BTEqualStrategyNumber, F_CHAREQ,
303 
304  scan = heap_beginscan_catalog(classRel, 1, key);
305 
306  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
307  {
308  Oid relid = HeapTupleGetOid(tuple);
309  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
310 
311  if (is_publishable_class(relid, relForm))
312  result = lappend_oid(result, relid);
313  }
314 
315  heap_endscan(scan);
316  heap_close(classRel, AccessShareLock);
317 
318  return result;
319 }
320 
321 /*
322  * Get publication using oid
323  *
324  * The Publication struct and it's data are palloced here.
325  */
326 Publication *
328 {
329  HeapTuple tup;
330  Publication *pub;
331  Form_pg_publication pubform;
332 
334 
335  if (!HeapTupleIsValid(tup))
336  elog(ERROR, "cache lookup failed for publication %u", pubid);
337 
338  pubform = (Form_pg_publication) GETSTRUCT(tup);
339 
340  pub = (Publication *) palloc(sizeof(Publication));
341  pub->oid = pubid;
342  pub->name = pstrdup(NameStr(pubform->pubname));
343  pub->alltables = pubform->puballtables;
344  pub->pubactions.pubinsert = pubform->pubinsert;
345  pub->pubactions.pubupdate = pubform->pubupdate;
346  pub->pubactions.pubdelete = pubform->pubdelete;
347 
348  ReleaseSysCache(tup);
349 
350  return pub;
351 }
352 
353 
354 /*
355  * Get Publication using name.
356  */
357 Publication *
358 GetPublicationByName(const char *pubname, bool missing_ok)
359 {
360  Oid oid;
361 
363  if (!OidIsValid(oid))
364  {
365  if (missing_ok)
366  return NULL;
367 
368  ereport(ERROR,
369  (errcode(ERRCODE_UNDEFINED_OBJECT),
370  errmsg("publication \"%s\" does not exist", pubname)));
371  }
372 
373  return GetPublication(oid);
374 }
375 
376 /*
377  * get_publication_oid - given a publication name, look up the OID
378  *
379  * If missing_ok is false, throw an error if name not found. If true, just
380  * return InvalidOid.
381  */
382 Oid
383 get_publication_oid(const char *pubname, bool missing_ok)
384 {
385  Oid oid;
386 
388  if (!OidIsValid(oid) && !missing_ok)
389  ereport(ERROR,
390  (errcode(ERRCODE_UNDEFINED_OBJECT),
391  errmsg("publication \"%s\" does not exist", pubname)));
392  return oid;
393 }
394 
395 /*
396  * get_publication_name - given a publication Oid, look up the name
397  */
398 char *
400 {
401  HeapTuple tup;
402  char *pubname;
403  Form_pg_publication pubform;
404 
406 
407  if (!HeapTupleIsValid(tup))
408  elog(ERROR, "cache lookup failed for publication %u", pubid);
409 
410  pubform = (Form_pg_publication) GETSTRUCT(tup);
411  pubname = pstrdup(NameStr(pubform->pubname));
412 
413  ReleaseSysCache(tup);
414 
415  return pubname;
416 }
417 
418 /*
419  * Returns Oids of tables in a publication.
420  */
421 Datum
423 {
424  FuncCallContext *funcctx;
425  char *pubname = text_to_cstring(PG_GETARG_TEXT_PP(0));
426  Publication *publication;
427  List *tables;
428  ListCell **lcp;
429 
430  /* stuff done only on the first call of the function */
431  if (SRF_IS_FIRSTCALL())
432  {
433  MemoryContext oldcontext;
434 
435  /* create a function context for cross-call persistence */
436  funcctx = SRF_FIRSTCALL_INIT();
437 
438  /* switch to memory context appropriate for multiple function calls */
439  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
440 
441  publication = GetPublicationByName(pubname, false);
442  if (publication->alltables)
444  else
445  tables = GetPublicationRelations(publication->oid);
446  lcp = (ListCell **) palloc(sizeof(ListCell *));
447  *lcp = list_head(tables);
448  funcctx->user_fctx = (void *) lcp;
449 
450  MemoryContextSwitchTo(oldcontext);
451  }
452 
453  /* stuff done on every call of the function */
454  funcctx = SRF_PERCALL_SETUP();
455  lcp = (ListCell **) funcctx->user_fctx;
456 
457  while (*lcp != NULL)
458  {
459  Oid relid = lfirst_oid(*lcp);
460 
461  *lcp = lnext(*lcp);
462  SRF_RETURN_NEXT(funcctx, ObjectIdGetDatum(relid));
463  }
464 
465  SRF_RETURN_DONE(funcctx);
466 }
#define NIL
Definition: pg_list.h:69
PublicationActions pubactions
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:91
int n_members
Definition: catcache.h:154
List * GetAllTablesPublicationRelations(void)
int errhint(const char *fmt,...)
Definition: elog.c:987
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
bool IsCatalogClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:103
#define RelationGetDescr(relation)
Definition: rel.h:429
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:285
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#define RelationGetForm(relation)
Definition: rel.h:411
#define RelationRelationId
Definition: pg_class.h:29
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PublicationRelationId
return result
Definition: formatting.c:1618
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:538
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:289
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
Publication * GetPublicationByName(const char *pubname, bool missing_ok)
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
#define FirstNormalObjectId
Definition: transam.h:94
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
#define PublicationRelRelationId
#define GetSysCacheOid1(cacheId, key1)
Definition: syscache.h:179
#define RELPERSISTENCE_PERMANENT
Definition: pg_class.h:170
CatCTup * members[FLEXIBLE_ARRAY_MEMBER]
Definition: catcache.h:155
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:291
#define Anum_pg_class_relkind
Definition: pg_class.h:118
List * GetRelationPublications(Oid relid)
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
Publication * GetPublication(Oid pubid)
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
static void check_publication_add_relation(Relation targetrel)
#define Anum_pg_publication_rel_prpubid
#define Anum_pg_publication_rel_prrelid
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define CStringGetDatum(X)
Definition: postgres.h:584
#define RelationGetRelationName(relation)
Definition: rel.h:437
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define SearchSysCacheList1(cacheId, key1)
Definition: syscache.h:197
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
#define PublicationRelPrrelidPrpubidIndexId
Definition: indexing.h:351
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define ReleaseSysCacheList(x)
Definition: syscache.h:206
char * get_publication_name(Oid pubid)
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define BoolGetDatum(X)
Definition: postgres.h:408
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
List * GetAllTablesPublications(void)
List * GetPublicationRelations(Oid pubid)
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:109
#define SearchSysCacheExists2(cacheId, key1, key2)
Definition: syscache.h:172
#define RelationNeedsWAL(relation)
Definition: rel.h:506
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define CharGetDatum(X)
Definition: postgres.h:422
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1226
static Datum values[MAXATTR]
Definition: bootstrap.c:163
char * text_to_cstring(const text *t)
Definition: varlena.c:182
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
void * user_fctx
Definition: funcapi.h:90
const ObjectAddress InvalidObjectAddress
Datum pg_get_publication_tables(PG_FUNCTION_ARGS)
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define Anum_pg_publication_puballtables
FormData_pg_publication_rel * Form_pg_publication_rel
int i
#define Natts_pg_publication_rel
#define NameStr(name)
Definition: c.h:499
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
static bool is_publishable_class(Oid relid, Form_pg_class reltuple)
Oid get_publication_oid(const char *pubname, bool missing_ok)
#define PG_FUNCTION_ARGS
Definition: fmgr.h:158
HeapTupleData tuple
Definition: catcache.h:116
ObjectAddress publication_add_relation(Oid pubid, Relation targetrel, bool if_not_exists)
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
FormData_pg_publication * Form_pg_publication
#define RELKIND_RELATION
Definition: pg_class.h:160
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:417
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:108
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:309
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:287