PostgreSQL Source Code  git master
relation.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  * relation.c
3  * PostgreSQL logical replication
4  *
5  * Copyright (c) 2016-2018, PostgreSQL Global Development Group
6  *
7  * IDENTIFICATION
8  * src/backend/replication/logical/relation.c
9  *
10  * NOTES
11  * This file contains helper functions for logical replication relation
12  * mapping cache.
13  *
14  *-------------------------------------------------------------------------
15  */
16 
17 #include "postgres.h"
18 
19 #include "access/heapam.h"
20 #include "access/sysattr.h"
21 #include "catalog/namespace.h"
23 #include "executor/executor.h"
24 #include "nodes/makefuncs.h"
27 #include "utils/builtins.h"
28 #include "utils/inval.h"
29 #include "utils/lsyscache.h"
30 #include "utils/memutils.h"
31 #include "utils/syscache.h"
32 
34 
35 static HTAB *LogicalRepRelMap = NULL;
36 static HTAB *LogicalRepTypMap = NULL;
37 
38 
39 /*
40  * Relcache invalidation callback for our relation map cache.
41  */
42 static void
44 {
45  LogicalRepRelMapEntry *entry;
46 
47  /* Just to be sure. */
48  if (LogicalRepRelMap == NULL)
49  return;
50 
51  if (reloid != InvalidOid)
52  {
54 
55  hash_seq_init(&status, LogicalRepRelMap);
56 
57  /* TODO, use inverse lookup hashtable? */
58  while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
59  {
60  if (entry->localreloid == reloid)
61  {
62  entry->localreloid = InvalidOid;
63  hash_seq_term(&status);
64  break;
65  }
66  }
67  }
68  else
69  {
70  /* invalidate all cache entries */
72 
73  hash_seq_init(&status, LogicalRepRelMap);
74 
75  while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
76  entry->localreloid = InvalidOid;
77  }
78 }
79 
80 /*
81  * Initialize the relation map cache.
82  */
83 static void
85 {
86  HASHCTL ctl;
87 
88  if (!LogicalRepRelMapContext)
89  LogicalRepRelMapContext =
91  "LogicalRepRelMapContext",
93 
94  /* Initialize the relation hash table. */
95  MemSet(&ctl, 0, sizeof(ctl));
96  ctl.keysize = sizeof(LogicalRepRelId);
97  ctl.entrysize = sizeof(LogicalRepRelMapEntry);
99 
100  LogicalRepRelMap = hash_create("logicalrep relation map cache", 128, &ctl,
102 
103  /* Initialize the type hash table. */
104  MemSet(&ctl, 0, sizeof(ctl));
105  ctl.keysize = sizeof(Oid);
106  ctl.entrysize = sizeof(LogicalRepTyp);
108 
109  /* This will usually be small. */
110  LogicalRepTypMap = hash_create("logicalrep type map cache", 2, &ctl,
112 
113  /* Watch for invalidation events. */
115  (Datum) 0);
116 }
117 
118 /*
119  * Free the entry of a relation map cache.
120  */
121 static void
123 {
124  LogicalRepRelation *remoterel;
125 
126  remoterel = &entry->remoterel;
127 
128  pfree(remoterel->nspname);
129  pfree(remoterel->relname);
130 
131  if (remoterel->natts > 0)
132  {
133  int i;
134 
135  for (i = 0; i < remoterel->natts; i++)
136  pfree(remoterel->attnames[i]);
137 
138  pfree(remoterel->attnames);
139  pfree(remoterel->atttyps);
140  }
141  bms_free(remoterel->attkeys);
142 
143  if (entry->attrmap)
144  pfree(entry->attrmap);
145 }
146 
147 /*
148  * Add new entry or update existing entry in the relation map cache.
149  *
150  * Called when new relation mapping is sent by the publisher to update
151  * our expected view of incoming data from said publisher.
152  */
153 void
155 {
156  MemoryContext oldctx;
157  LogicalRepRelMapEntry *entry;
158  bool found;
159  int i;
160 
161  if (LogicalRepRelMap == NULL)
163 
164  /*
165  * HASH_ENTER returns the existing entry if present or creates a new one.
166  */
167  entry = hash_search(LogicalRepRelMap, (void *) &remoterel->remoteid,
168  HASH_ENTER, &found);
169 
170  if (found)
172 
173  memset(entry, 0, sizeof(LogicalRepRelMapEntry));
174 
175  /* Make cached copy of the data */
176  oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
177  entry->remoterel.remoteid = remoterel->remoteid;
178  entry->remoterel.nspname = pstrdup(remoterel->nspname);
179  entry->remoterel.relname = pstrdup(remoterel->relname);
180  entry->remoterel.natts = remoterel->natts;
181  entry->remoterel.attnames = palloc(remoterel->natts * sizeof(char *));
182  entry->remoterel.atttyps = palloc(remoterel->natts * sizeof(Oid));
183  for (i = 0; i < remoterel->natts; i++)
184  {
185  entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
186  entry->remoterel.atttyps[i] = remoterel->atttyps[i];
187  }
188  entry->remoterel.replident = remoterel->replident;
189  entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
190  MemoryContextSwitchTo(oldctx);
191 }
192 
193 /*
194  * Find attribute index in TupleDesc struct by attribute name.
195  *
196  * Returns -1 if not found.
197  */
198 static int
200 {
201  int i;
202 
203  for (i = 0; i < remoterel->natts; i++)
204  {
205  if (strcmp(remoterel->attnames[i], attname) == 0)
206  return i;
207  }
208 
209  return -1;
210 }
211 
212 /*
213  * Open the local relation associated with the remote one.
214  *
215  * Optionally rebuilds the Relcache mapping if it was invalidated
216  * by local DDL.
217  */
220 {
221  LogicalRepRelMapEntry *entry;
222  bool found;
223 
224  if (LogicalRepRelMap == NULL)
226 
227  /* Search for existing entry. */
228  entry = hash_search(LogicalRepRelMap, (void *) &remoteid,
229  HASH_FIND, &found);
230 
231  if (!found)
232  elog(ERROR, "no relation map entry for remote relation ID %u",
233  remoteid);
234 
235  /* Need to update the local cache? */
236  if (!OidIsValid(entry->localreloid))
237  {
238  Oid relid;
239  int i;
240  int found;
241  Bitmapset *idkey;
242  TupleDesc desc;
243  LogicalRepRelation *remoterel;
244  MemoryContext oldctx;
245 
246  remoterel = &entry->remoterel;
247 
248  /* Try to find and lock the relation by name. */
249  relid = RangeVarGetRelid(makeRangeVar(remoterel->nspname,
250  remoterel->relname, -1),
251  lockmode, true);
252  if (!OidIsValid(relid))
253  ereport(ERROR,
254  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
255  errmsg("logical replication target relation \"%s.%s\" does not exist",
256  remoterel->nspname, remoterel->relname)));
257  entry->localrel = heap_open(relid, NoLock);
258 
259  /* Check for supported relkind. */
260  CheckSubscriptionRelkind(entry->localrel->rd_rel->relkind,
261  remoterel->nspname, remoterel->relname);
262 
263  /*
264  * Build the mapping of local attribute numbers to remote attribute
265  * numbers and validate that we don't miss any replicated columns as
266  * that would result in potentially unwanted data loss.
267  */
268  desc = RelationGetDescr(entry->localrel);
269  oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
270  entry->attrmap = palloc(desc->natts * sizeof(int));
271  MemoryContextSwitchTo(oldctx);
272 
273  found = 0;
274  for (i = 0; i < desc->natts; i++)
275  {
276  int attnum;
277  Form_pg_attribute attr = TupleDescAttr(desc, i);
278 
279  if (attr->attisdropped)
280  {
281  entry->attrmap[i] = -1;
282  continue;
283  }
284 
285  attnum = logicalrep_rel_att_by_name(remoterel,
286  NameStr(attr->attname));
287 
288  entry->attrmap[i] = attnum;
289  if (attnum >= 0)
290  found++;
291  }
292 
293  /* TODO, detail message with names of missing columns */
294  if (found < remoterel->natts)
295  ereport(ERROR,
296  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
297  errmsg("logical replication target relation \"%s.%s\" is missing "
298  "some replicated columns",
299  remoterel->nspname, remoterel->relname)));
300 
301  /*
302  * Check that replica identity matches. We allow for stricter replica
303  * identity (fewer columns) on subscriber as that will not stop us
304  * from finding unique tuple. IE, if publisher has identity
305  * (id,timestamp) and subscriber just (id) this will not be a problem,
306  * but in the opposite scenario it will.
307  *
308  * Don't throw any error here just mark the relation entry as not
309  * updatable, as replica identity is only for updates and deletes but
310  * inserts can be replicated even without it.
311  */
312  entry->updatable = true;
313  idkey = RelationGetIndexAttrBitmap(entry->localrel,
315  /* fallback to PK if no replica identity */
316  if (idkey == NULL)
317  {
318  idkey = RelationGetIndexAttrBitmap(entry->localrel,
320 
321  /*
322  * If no replica identity index and no PK, the published table
323  * must have replica identity FULL.
324  */
325  if (idkey == NULL && remoterel->replident != REPLICA_IDENTITY_FULL)
326  entry->updatable = false;
327  }
328 
329  i = -1;
330  while ((i = bms_next_member(idkey, i)) >= 0)
331  {
333 
334  if (!AttrNumberIsForUserDefinedAttr(attnum))
335  ereport(ERROR,
336  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
337  errmsg("logical replication target relation \"%s.%s\" uses "
338  "system columns in REPLICA IDENTITY index",
339  remoterel->nspname, remoterel->relname)));
340 
341  attnum = AttrNumberGetAttrOffset(attnum);
342 
343  if (!bms_is_member(entry->attrmap[attnum], remoterel->attkeys))
344  {
345  entry->updatable = false;
346  break;
347  }
348  }
349 
350  entry->localreloid = relid;
351  }
352  else
353  entry->localrel = heap_open(entry->localreloid, lockmode);
354 
355  if (entry->state != SUBREL_STATE_READY)
357  entry->localreloid,
358  &entry->statelsn,
359  true);
360 
361  return entry;
362 }
363 
364 /*
365  * Close the previously opened logical relation.
366  */
367 void
369 {
370  heap_close(rel->localrel, lockmode);
371  rel->localrel = NULL;
372 }
373 
374 /*
375  * Free the type map cache entry data.
376  */
377 static void
379 {
380  pfree(entry->nspname);
381  pfree(entry->typname);
382 }
383 
384 /*
385  * Add new entry or update existing entry in the type map cache.
386  */
387 void
389 {
390  MemoryContext oldctx;
391  LogicalRepTyp *entry;
392  bool found;
393 
394  if (LogicalRepTypMap == NULL)
396 
397  /*
398  * HASH_ENTER returns the existing entry if present or creates a new one.
399  */
400  entry = hash_search(LogicalRepTypMap, (void *) &remotetyp->remoteid,
401  HASH_ENTER, &found);
402 
403  if (found)
405 
406  /* Make cached copy of the data */
407  entry->remoteid = remotetyp->remoteid;
408  oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
409  entry->nspname = pstrdup(remotetyp->nspname);
410  entry->typname = pstrdup(remotetyp->typname);
411  MemoryContextSwitchTo(oldctx);
412 }
413 
414 /*
415  * Fetch type name from the cache by remote type OID.
416  *
417  * Return a substitute value if we cannot find the data type; no message is
418  * sent to the log in that case, because this is used by error callback
419  * already.
420  */
421 char *
423 {
424  LogicalRepTyp *entry;
425  bool found;
426 
427  /* Internal types are mapped directly. */
428  if (remoteid < FirstNormalObjectId)
429  {
430  if (!get_typisdefined(remoteid))
431  {
432  /*
433  * This can be caused by having a publisher with a higher
434  * PostgreSQL major version than the subscriber.
435  */
436  return psprintf("unrecognized %u", remoteid);
437  }
438 
439  return format_type_be(remoteid);
440  }
441 
442  if (LogicalRepTypMap == NULL)
443  {
444  /*
445  * If the typemap is not initialized yet, we cannot possibly attempt
446  * to search the hash table; but there's no way we know the type
447  * locally yet, since we haven't received a message about this type,
448  * so this is the best we can do.
449  */
450  return psprintf("unrecognized %u", remoteid);
451  }
452 
453  /* search the mapping */
454  entry = hash_search(LogicalRepTypMap, (void *) &remoteid,
455  HASH_FIND, &found);
456  if (!found)
457  return psprintf("unrecognized %u", remoteid);
458 
459  Assert(OidIsValid(entry->remoteid));
460  return psprintf("%s.%s", entry->nspname, entry->typname);
461 }
Subscription * MySubscription
Definition: worker.c:116
static void logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
Definition: relation.c:122
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:133
#define HASH_CONTEXT
Definition: hsearch.h:93
char * typname
Definition: logicalproto.h:60
#define HASH_ELEM
Definition: hsearch.h:87
MemoryContext hcxt
Definition: hsearch.h:78
#define RelationGetDescr(relation)
Definition: rel.h:433
int LOCKMODE
Definition: lockdefs.h:26
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:63
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
char * pstrdup(const char *in)
Definition: mcxt.c:1161
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1075
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Size entrysize
Definition: hsearch.h:73
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition: attnum.h:41
bool get_typisdefined(Oid typid)
Definition: lsyscache.c:1927
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:908
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:368
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
#define heap_close(r, l)
Definition: heapam.h:97
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
static HTAB * LogicalRepTypMap
Definition: relation.c:36
#define OidIsValid(objectId)
Definition: c.h:605
Bitmapset * attkeys
Definition: logicalproto.h:52
int natts
Definition: tupdesc.h:82
#define FirstNormalObjectId
Definition: transam.h:94
LogicalRepRelId remoteid
Definition: logicalproto.h:45
void CacheRegisterRelcacheCallback(RelcacheCallbackFunction func, Datum arg)
Definition: inval.c:1431
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:154
Definition: dynahash.c:208
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
static int logicalrep_rel_att_by_name(LogicalRepRelation *remoterel, const char *attname)
Definition: relation.c:199
LogicalRepRelation remoterel
static void logicalrep_relmap_invalidate_cb(Datum arg, Oid reloid)
Definition: relation.c:43
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define AttrNumberGetAttrOffset(attNum)
Definition: attnum.h:51
#define NoLock
Definition: lockdefs.h:34
static MemoryContext LogicalRepRelMapContext
Definition: relation.c:33
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:219
#define ereport(elevel, rest)
Definition: elog.h:122
struct LogicalRepTyp LogicalRepTyp
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:170
#define HASH_BLOBS
Definition: hsearch.h:88
struct LogicalRepRelMapEntry LogicalRepRelMapEntry
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
uintptr_t Datum
Definition: postgres.h:365
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
Size keysize
Definition: hsearch.h:72
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
void bms_free(Bitmapset *a)
Definition: bitmapset.c:267
#define Assert(condition)
Definition: c.h:699
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1389
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn, bool missing_ok)
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1379
char * logicalrep_typmap_gettypname(Oid remoteid)
Definition: relation.c:422
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:4758
#define NameStr(name)
Definition: c.h:576
void * arg
#define elog
Definition: elog.h:219
static void logicalrep_relmap_init(void)
Definition: relation.c:84
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:486
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:421
static void logicalrep_typmap_free_entry(LogicalRepTyp *entry)
Definition: relation.c:378
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1465
char * nspname
Definition: logicalproto.h:59
void logicalrep_typmap_update(LogicalRepTyp *remotetyp)
Definition: relation.c:388
static HTAB * LogicalRepRelMap
Definition: relation.c:35
uint32 LogicalRepRelId
Definition: logicalproto.h:39
MemoryContext CacheMemoryContext
Definition: mcxt.c:47