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  * Note this also excludes all tables with relid < FirstNormalObjectId,
95  * ie all tables created during initdb. This mainly affects the preinstalled
96  * information_schema. (IsCatalogClass() only checks for these inside
97  * pg_catalog and toast schemas.)
98  */
99 static bool
101 {
102  return reltuple->relkind == RELKIND_RELATION &&
103  !IsCatalogClass(relid, reltuple) &&
104  reltuple->relpersistence == RELPERSISTENCE_PERMANENT &&
105  relid >= FirstNormalObjectId;
106 }
107 
108 
109 /*
110  * SQL-callable variant of the above
111  *
112  * This returns null when the relation does not exist. This is intended to be
113  * used for example in psql to avoid gratuitous errors when there are
114  * concurrent catalog changes.
115  */
116 Datum
118 {
119  Oid relid = PG_GETARG_OID(0);
120  HeapTuple tuple;
121  bool result;
122 
123  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
124  if (!tuple)
125  PG_RETURN_NULL();
126  result = is_publishable_class(relid, (Form_pg_class) GETSTRUCT(tuple));
127  ReleaseSysCache(tuple);
128  PG_RETURN_BOOL(result);
129 }
130 
131 
132 /*
133  * Insert new publication / relation mapping.
134  */
137  bool if_not_exists)
138 {
139  Relation rel;
140  HeapTuple tup;
142  bool nulls[Natts_pg_publication_rel];
143  Oid relid = RelationGetRelid(targetrel);
144  Oid prrelid;
145  Publication *pub = GetPublication(pubid);
146  ObjectAddress myself,
147  referenced;
148 
150 
151  /*
152  * Check for duplicates. Note that this does not really prevent
153  * duplicates, it's here just to provide nicer error message in common
154  * case. The real protection is the unique key on the catalog.
155  */
157  ObjectIdGetDatum(pubid)))
158  {
160 
161  if (if_not_exists)
162  return InvalidObjectAddress;
163 
164  ereport(ERROR,
166  errmsg("relation \"%s\" is already member of publication \"%s\"",
167  RelationGetRelationName(targetrel), pub->name)));
168  }
169 
171 
172  /* Form a tuple. */
173  memset(values, 0, sizeof(values));
174  memset(nulls, false, sizeof(nulls));
175 
176  values[Anum_pg_publication_rel_prpubid - 1] =
177  ObjectIdGetDatum(pubid);
178  values[Anum_pg_publication_rel_prrelid - 1] =
179  ObjectIdGetDatum(relid);
180 
181  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
182 
183  /* Insert tuple into catalog. */
184  prrelid = CatalogTupleInsert(rel, tup);
185  heap_freetuple(tup);
186 
187  ObjectAddressSet(myself, PublicationRelRelationId, prrelid);
188 
189  /* Add dependency on the publication */
190  ObjectAddressSet(referenced, PublicationRelationId, pubid);
191  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
192 
193  /* Add dependency on the relation */
194  ObjectAddressSet(referenced, RelationRelationId, relid);
195  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
196 
197  /* Close the table. */
199 
200  /* Invalidate relcache so that publication info is rebuilt. */
201  CacheInvalidateRelcache(targetrel);
202 
203  return myself;
204 }
205 
206 
207 /*
208  * Gets list of publication oids for a relation oid.
209  */
210 List *
212 {
213  List *result = NIL;
214  CatCList *pubrellist;
215  int i;
216 
217  /* Find all publications associated with the relation. */
219  ObjectIdGetDatum(relid));
220  for (i = 0; i < pubrellist->n_members; i++)
221  {
222  HeapTuple tup = &pubrellist->members[i]->tuple;
223  Oid pubid = ((Form_pg_publication_rel) GETSTRUCT(tup))->prpubid;
224 
225  result = lappend_oid(result, pubid);
226  }
227 
228  ReleaseSysCacheList(pubrellist);
229 
230  return result;
231 }
232 
233 /*
234  * Gets list of relation oids for a publication.
235  *
236  * This should only be used for normal publications, the FOR ALL TABLES
237  * should use GetAllTablesPublicationRelations().
238  */
239 List *
241 {
242  List *result;
243  Relation pubrelsrel;
244  ScanKeyData scankey;
245  SysScanDesc scan;
246  HeapTuple tup;
247 
248  /* Find all publications associated with the relation. */
250 
251  ScanKeyInit(&scankey,
253  BTEqualStrategyNumber, F_OIDEQ,
254  ObjectIdGetDatum(pubid));
255 
257  true, NULL, 1, &scankey);
258 
259  result = NIL;
260  while (HeapTupleIsValid(tup = systable_getnext(scan)))
261  {
263 
264  pubrel = (Form_pg_publication_rel) GETSTRUCT(tup);
265 
266  result = lappend_oid(result, pubrel->prrelid);
267  }
268 
269  systable_endscan(scan);
270  heap_close(pubrelsrel, AccessShareLock);
271 
272  return result;
273 }
274 
275 /*
276  * Gets list of publication oids for publications marked as FOR ALL TABLES.
277  */
278 List *
280 {
281  List *result;
282  Relation rel;
283  ScanKeyData scankey;
284  SysScanDesc scan;
285  HeapTuple tup;
286 
287  /* Find all publications that are marked as for all tables. */
289 
290  ScanKeyInit(&scankey,
292  BTEqualStrategyNumber, F_BOOLEQ,
293  BoolGetDatum(true));
294 
295  scan = systable_beginscan(rel, InvalidOid, false,
296  NULL, 1, &scankey);
297 
298  result = NIL;
299  while (HeapTupleIsValid(tup = systable_getnext(scan)))
300  result = lappend_oid(result, HeapTupleGetOid(tup));
301 
302  systable_endscan(scan);
304 
305  return result;
306 }
307 
308 /*
309  * Gets list of all relation published by FOR ALL TABLES publication(s).
310  */
311 List *
313 {
314  Relation classRel;
315  ScanKeyData key[1];
316  HeapScanDesc scan;
317  HeapTuple tuple;
318  List *result = NIL;
319 
321 
322  ScanKeyInit(&key[0],
324  BTEqualStrategyNumber, F_CHAREQ,
326 
327  scan = heap_beginscan_catalog(classRel, 1, key);
328 
329  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
330  {
331  Oid relid = HeapTupleGetOid(tuple);
332  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
333 
334  if (is_publishable_class(relid, relForm))
335  result = lappend_oid(result, relid);
336  }
337 
338  heap_endscan(scan);
339  heap_close(classRel, AccessShareLock);
340 
341  return result;
342 }
343 
344 /*
345  * Get publication using oid
346  *
347  * The Publication struct and its data are palloc'ed here.
348  */
349 Publication *
351 {
352  HeapTuple tup;
353  Publication *pub;
354  Form_pg_publication pubform;
355 
357 
358  if (!HeapTupleIsValid(tup))
359  elog(ERROR, "cache lookup failed for publication %u", pubid);
360 
361  pubform = (Form_pg_publication) GETSTRUCT(tup);
362 
363  pub = (Publication *) palloc(sizeof(Publication));
364  pub->oid = pubid;
365  pub->name = pstrdup(NameStr(pubform->pubname));
366  pub->alltables = pubform->puballtables;
367  pub->pubactions.pubinsert = pubform->pubinsert;
368  pub->pubactions.pubupdate = pubform->pubupdate;
369  pub->pubactions.pubdelete = pubform->pubdelete;
370 
371  ReleaseSysCache(tup);
372 
373  return pub;
374 }
375 
376 
377 /*
378  * Get Publication using name.
379  */
380 Publication *
381 GetPublicationByName(const char *pubname, bool missing_ok)
382 {
383  Oid oid;
384 
386  if (!OidIsValid(oid))
387  {
388  if (missing_ok)
389  return NULL;
390 
391  ereport(ERROR,
392  (errcode(ERRCODE_UNDEFINED_OBJECT),
393  errmsg("publication \"%s\" does not exist", pubname)));
394  }
395 
396  return GetPublication(oid);
397 }
398 
399 /*
400  * get_publication_oid - given a publication name, look up the OID
401  *
402  * If missing_ok is false, throw an error if name not found. If true, just
403  * return InvalidOid.
404  */
405 Oid
406 get_publication_oid(const char *pubname, bool missing_ok)
407 {
408  Oid oid;
409 
411  if (!OidIsValid(oid) && !missing_ok)
412  ereport(ERROR,
413  (errcode(ERRCODE_UNDEFINED_OBJECT),
414  errmsg("publication \"%s\" does not exist", pubname)));
415  return oid;
416 }
417 
418 /*
419  * get_publication_name - given a publication Oid, look up the name
420  */
421 char *
423 {
424  HeapTuple tup;
425  char *pubname;
426  Form_pg_publication pubform;
427 
429 
430  if (!HeapTupleIsValid(tup))
431  elog(ERROR, "cache lookup failed for publication %u", pubid);
432 
433  pubform = (Form_pg_publication) GETSTRUCT(tup);
434  pubname = pstrdup(NameStr(pubform->pubname));
435 
436  ReleaseSysCache(tup);
437 
438  return pubname;
439 }
440 
441 /*
442  * Returns Oids of tables in a publication.
443  */
444 Datum
446 {
447  FuncCallContext *funcctx;
448  char *pubname = text_to_cstring(PG_GETARG_TEXT_PP(0));
449  Publication *publication;
450  List *tables;
451  ListCell **lcp;
452 
453  /* stuff done only on the first call of the function */
454  if (SRF_IS_FIRSTCALL())
455  {
456  MemoryContext oldcontext;
457 
458  /* create a function context for cross-call persistence */
459  funcctx = SRF_FIRSTCALL_INIT();
460 
461  /* switch to memory context appropriate for multiple function calls */
462  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
463 
464  publication = GetPublicationByName(pubname, false);
465  if (publication->alltables)
467  else
468  tables = GetPublicationRelations(publication->oid);
469  lcp = (ListCell **) palloc(sizeof(ListCell *));
470  *lcp = list_head(tables);
471  funcctx->user_fctx = (void *) lcp;
472 
473  MemoryContextSwitchTo(oldcontext);
474  }
475 
476  /* stuff done on every call of the function */
477  funcctx = SRF_PERCALL_SETUP();
478  lcp = (ListCell **) funcctx->user_fctx;
479 
480  while (*lcp != NULL)
481  {
482  Oid relid = lfirst_oid(*lcp);
483 
484  *lcp = lnext(*lcp);
485  SRF_RETURN_NEXT(funcctx, ObjectIdGetDatum(relid));
486  }
487 
488  SRF_RETURN_DONE(funcctx);
489 }
#define NIL
Definition: pg_list.h:69
PublicationActions pubactions
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:92
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:104
#define RelationGetDescr(relation)
Definition: rel.h:428
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:285
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#define RelationGetForm(relation)
Definition: rel.h:410
#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:1633
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:1372
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:156
#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:183
#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 PG_GETARG_OID(n)
Definition: fmgr.h:240
#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
Datum pg_relation_is_publishable(PG_FUNCTION_ARGS)
#define CStringGetDatum(X)
Definition: postgres.h:584
#define RelationGetRelationName(relation)
Definition: rel.h:436
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define SearchSysCacheList1(cacheId, key1)
Definition: syscache.h:201
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:210
char * get_publication_name(Oid pubid)
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:319
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
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:176
#define RelationNeedsWAL(relation)
Definition: rel.h:505
#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:1233
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:32
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
#define PG_RETURN_NULL()
Definition: fmgr.h:305
#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