PostgreSQL Source Code  git master
relation.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  * relation.c
3  * PostgreSQL logical replication relation mapping cache
4  *
5  * Copyright (c) 2016-2023, PostgreSQL Global Development Group
6  *
7  * IDENTIFICATION
8  * src/backend/replication/logical/relation.c
9  *
10  * NOTES
11  * Routines in this file mainly have to do with mapping the properties
12  * of local replication target relations to the properties of their
13  * remote counterpart.
14  *
15  *-------------------------------------------------------------------------
16  */
17 
18 #include "postgres.h"
19 
20 #include "access/genam.h"
21 #include "access/table.h"
22 #include "catalog/namespace.h"
23 #include "catalog/pg_am_d.h"
25 #include "executor/executor.h"
26 #include "nodes/makefuncs.h"
29 #include "utils/inval.h"
30 
31 
33 
34 static HTAB *LogicalRepRelMap = NULL;
35 
36 /*
37  * Partition map (LogicalRepPartMap)
38  *
39  * When a partitioned table is used as replication target, replicated
40  * operations are actually performed on its leaf partitions, which requires
41  * the partitions to also be mapped to the remote relation. Parent's entry
42  * (LogicalRepRelMapEntry) cannot be used as-is for all partitions, because
43  * individual partitions may have different attribute numbers, which means
44  * attribute mappings to remote relation's attributes must be maintained
45  * separately for each partition.
46  */
48 static HTAB *LogicalRepPartMap = NULL;
49 typedef struct LogicalRepPartMapEntry
50 {
51  Oid partoid; /* LogicalRepPartMap's key */
54 
55 static Oid FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel,
56  AttrMap *attrMap);
57 
58 /*
59  * Relcache invalidation callback for our relation map cache.
60  */
61 static void
63 {
64  LogicalRepRelMapEntry *entry;
65 
66  /* Just to be sure. */
67  if (LogicalRepRelMap == NULL)
68  return;
69 
70  if (reloid != InvalidOid)
71  {
73 
75 
76  /* TODO, use inverse lookup hashtable? */
77  while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
78  {
79  if (entry->localreloid == reloid)
80  {
81  entry->localrelvalid = false;
83  break;
84  }
85  }
86  }
87  else
88  {
89  /* invalidate all cache entries */
91 
93 
94  while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
95  entry->localrelvalid = false;
96  }
97 }
98 
99 /*
100  * Initialize the relation map cache.
101  */
102 static void
104 {
105  HASHCTL ctl;
106 
110  "LogicalRepRelMapContext",
112 
113  /* Initialize the relation hash table. */
114  ctl.keysize = sizeof(LogicalRepRelId);
115  ctl.entrysize = sizeof(LogicalRepRelMapEntry);
117 
118  LogicalRepRelMap = hash_create("logicalrep relation map cache", 128, &ctl,
120 
121  /* Watch for invalidation events. */
123  (Datum) 0);
124 }
125 
126 /*
127  * Free the entry of a relation map cache.
128  */
129 static void
131 {
132  LogicalRepRelation *remoterel;
133 
134  remoterel = &entry->remoterel;
135 
136  pfree(remoterel->nspname);
137  pfree(remoterel->relname);
138 
139  if (remoterel->natts > 0)
140  {
141  int i;
142 
143  for (i = 0; i < remoterel->natts; i++)
144  pfree(remoterel->attnames[i]);
145 
146  pfree(remoterel->attnames);
147  pfree(remoterel->atttyps);
148  }
149  bms_free(remoterel->attkeys);
150 
151  if (entry->attrmap)
152  free_attrmap(entry->attrmap);
153 }
154 
155 /*
156  * Add new entry or update existing entry in the relation map cache.
157  *
158  * Called when new relation mapping is sent by the publisher to update
159  * our expected view of incoming data from said publisher.
160  */
161 void
163 {
164  MemoryContext oldctx;
165  LogicalRepRelMapEntry *entry;
166  bool found;
167  int i;
168 
169  if (LogicalRepRelMap == NULL)
171 
172  /*
173  * HASH_ENTER returns the existing entry if present or creates a new one.
174  */
175  entry = hash_search(LogicalRepRelMap, &remoterel->remoteid,
176  HASH_ENTER, &found);
177 
178  if (found)
180 
181  memset(entry, 0, sizeof(LogicalRepRelMapEntry));
182 
183  /* Make cached copy of the data */
185  entry->remoterel.remoteid = remoterel->remoteid;
186  entry->remoterel.nspname = pstrdup(remoterel->nspname);
187  entry->remoterel.relname = pstrdup(remoterel->relname);
188  entry->remoterel.natts = remoterel->natts;
189  entry->remoterel.attnames = palloc(remoterel->natts * sizeof(char *));
190  entry->remoterel.atttyps = palloc(remoterel->natts * sizeof(Oid));
191  for (i = 0; i < remoterel->natts; i++)
192  {
193  entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
194  entry->remoterel.atttyps[i] = remoterel->atttyps[i];
195  }
196  entry->remoterel.replident = remoterel->replident;
197  entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
198  MemoryContextSwitchTo(oldctx);
199 }
200 
201 /*
202  * Find attribute index in TupleDesc struct by attribute name.
203  *
204  * Returns -1 if not found.
205  */
206 static int
208 {
209  int i;
210 
211  for (i = 0; i < remoterel->natts; i++)
212  {
213  if (strcmp(remoterel->attnames[i], attname) == 0)
214  return i;
215  }
216 
217  return -1;
218 }
219 
220 /*
221  * Report error with names of the missing local relation column(s), if any.
222  */
223 static void
225  Bitmapset *missingatts)
226 {
227  if (!bms_is_empty(missingatts))
228  {
229  StringInfoData missingattsbuf;
230  int missingattcnt = 0;
231  int i;
232 
233  initStringInfo(&missingattsbuf);
234 
235  i = -1;
236  while ((i = bms_next_member(missingatts, i)) >= 0)
237  {
238  missingattcnt++;
239  if (missingattcnt == 1)
240  appendStringInfo(&missingattsbuf, _("\"%s\""),
241  remoterel->attnames[i]);
242  else
243  appendStringInfo(&missingattsbuf, _(", \"%s\""),
244  remoterel->attnames[i]);
245  }
246 
247  ereport(ERROR,
248  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
249  errmsg_plural("logical replication target relation \"%s.%s\" is missing replicated column: %s",
250  "logical replication target relation \"%s.%s\" is missing replicated columns: %s",
251  missingattcnt,
252  remoterel->nspname,
253  remoterel->relname,
254  missingattsbuf.data)));
255  }
256 }
257 
258 /*
259  * Check if replica identity matches and mark the updatable flag.
260  *
261  * We allow for stricter replica identity (fewer columns) on subscriber as
262  * that will not stop us from finding unique tuple. IE, if publisher has
263  * identity (id,timestamp) and subscriber just (id) this will not be a
264  * problem, but in the opposite scenario it will.
265  *
266  * We just mark the relation entry as not updatable here if the local
267  * replica identity is found to be insufficient for applying
268  * updates/deletes (inserts don't care!) and leave it to
269  * check_relation_updatable() to throw the actual error if needed.
270  */
271 static void
273 {
274  Bitmapset *idkey;
275  LogicalRepRelation *remoterel = &entry->remoterel;
276  int i;
277 
278  entry->updatable = true;
279 
280  idkey = RelationGetIndexAttrBitmap(entry->localrel,
282  /* fallback to PK if no replica identity */
283  if (idkey == NULL)
284  {
285  idkey = RelationGetIndexAttrBitmap(entry->localrel,
287 
288  /*
289  * If no replica identity index and no PK, the published table must
290  * have replica identity FULL.
291  */
292  if (idkey == NULL && remoterel->replident != REPLICA_IDENTITY_FULL)
293  entry->updatable = false;
294  }
295 
296  i = -1;
297  while ((i = bms_next_member(idkey, i)) >= 0)
298  {
300 
302  ereport(ERROR,
303  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
304  errmsg("logical replication target relation \"%s.%s\" uses "
305  "system columns in REPLICA IDENTITY index",
306  remoterel->nspname, remoterel->relname)));
307 
309 
310  if (entry->attrmap->attnums[attnum] < 0 ||
311  !bms_is_member(entry->attrmap->attnums[attnum], remoterel->attkeys))
312  {
313  entry->updatable = false;
314  break;
315  }
316  }
317 }
318 
319 /*
320  * Open the local relation associated with the remote one.
321  *
322  * Rebuilds the Relcache mapping if it was invalidated by local DDL.
323  */
326 {
327  LogicalRepRelMapEntry *entry;
328  bool found;
329  LogicalRepRelation *remoterel;
330 
331  if (LogicalRepRelMap == NULL)
333 
334  /* Search for existing entry. */
335  entry = hash_search(LogicalRepRelMap, &remoteid,
336  HASH_FIND, &found);
337 
338  if (!found)
339  elog(ERROR, "no relation map entry for remote relation ID %u",
340  remoteid);
341 
342  remoterel = &entry->remoterel;
343 
344  /* Ensure we don't leak a relcache refcount. */
345  if (entry->localrel)
346  elog(ERROR, "remote relation ID %u is already open", remoteid);
347 
348  /*
349  * When opening and locking a relation, pending invalidation messages are
350  * processed which can invalidate the relation. Hence, if the entry is
351  * currently considered valid, try to open the local relation by OID and
352  * see if invalidation ensues.
353  */
354  if (entry->localrelvalid)
355  {
356  entry->localrel = try_table_open(entry->localreloid, lockmode);
357  if (!entry->localrel)
358  {
359  /* Table was renamed or dropped. */
360  entry->localrelvalid = false;
361  }
362  else if (!entry->localrelvalid)
363  {
364  /* Note we release the no-longer-useful lock here. */
365  table_close(entry->localrel, lockmode);
366  entry->localrel = NULL;
367  }
368  }
369 
370  /*
371  * If the entry has been marked invalid since we last had lock on it,
372  * re-open the local relation by name and rebuild all derived data.
373  */
374  if (!entry->localrelvalid)
375  {
376  Oid relid;
377  TupleDesc desc;
378  MemoryContext oldctx;
379  int i;
380  Bitmapset *missingatts;
381 
382  /* Release the no-longer-useful attrmap, if any. */
383  if (entry->attrmap)
384  {
385  free_attrmap(entry->attrmap);
386  entry->attrmap = NULL;
387  }
388 
389  /* Try to find and lock the relation by name. */
390  relid = RangeVarGetRelid(makeRangeVar(remoterel->nspname,
391  remoterel->relname, -1),
392  lockmode, true);
393  if (!OidIsValid(relid))
394  ereport(ERROR,
395  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
396  errmsg("logical replication target relation \"%s.%s\" does not exist",
397  remoterel->nspname, remoterel->relname)));
398  entry->localrel = table_open(relid, NoLock);
399  entry->localreloid = relid;
400 
401  /* Check for supported relkind. */
402  CheckSubscriptionRelkind(entry->localrel->rd_rel->relkind,
403  remoterel->nspname, remoterel->relname);
404 
405  /*
406  * Build the mapping of local attribute numbers to remote attribute
407  * numbers and validate that we don't miss any replicated columns as
408  * that would result in potentially unwanted data loss.
409  */
410  desc = RelationGetDescr(entry->localrel);
412  entry->attrmap = make_attrmap(desc->natts);
413  MemoryContextSwitchTo(oldctx);
414 
415  /* check and report missing attrs, if any */
416  missingatts = bms_add_range(NULL, 0, remoterel->natts - 1);
417  for (i = 0; i < desc->natts; i++)
418  {
419  int attnum;
420  Form_pg_attribute attr = TupleDescAttr(desc, i);
421 
422  if (attr->attisdropped || attr->attgenerated)
423  {
424  entry->attrmap->attnums[i] = -1;
425  continue;
426  }
427 
429  NameStr(attr->attname));
430 
431  entry->attrmap->attnums[i] = attnum;
432  if (attnum >= 0)
433  missingatts = bms_del_member(missingatts, attnum);
434  }
435 
436  logicalrep_report_missing_attrs(remoterel, missingatts);
437 
438  /* be tidy */
439  bms_free(missingatts);
440 
441  /*
442  * Set if the table's replica identity is enough to apply
443  * update/delete.
444  */
446 
447  /*
448  * Finding a usable index is an infrequent task. It occurs when an
449  * operation is first performed on the relation, or after invalidation
450  * of the relation cache entry (such as ANALYZE or CREATE/DROP index
451  * on the relation).
452  */
453  entry->localindexoid = FindLogicalRepLocalIndex(entry->localrel, remoterel,
454  entry->attrmap);
455 
456  entry->localrelvalid = true;
457  }
458 
459  if (entry->state != SUBREL_STATE_READY)
461  entry->localreloid,
462  &entry->statelsn);
463 
464  return entry;
465 }
466 
467 /*
468  * Close the previously opened logical relation.
469  */
470 void
472 {
473  table_close(rel->localrel, lockmode);
474  rel->localrel = NULL;
475 }
476 
477 /*
478  * Partition cache: look up partition LogicalRepRelMapEntry's
479  *
480  * Unlike relation map cache, this is keyed by partition OID, not remote
481  * relation OID, because we only have to use this cache in the case where
482  * partitions are not directly mapped to any remote relation, such as when
483  * replication is occurring with one of their ancestors as target.
484  */
485 
486 /*
487  * Relcache invalidation callback
488  */
489 static void
491 {
492  LogicalRepPartMapEntry *entry;
493 
494  /* Just to be sure. */
495  if (LogicalRepPartMap == NULL)
496  return;
497 
498  if (reloid != InvalidOid)
499  {
501 
503 
504  /* TODO, use inverse lookup hashtable? */
505  while ((entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
506  {
507  if (entry->relmapentry.localreloid == reloid)
508  {
509  entry->relmapentry.localrelvalid = false;
511  break;
512  }
513  }
514  }
515  else
516  {
517  /* invalidate all cache entries */
519 
521 
522  while ((entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
523  entry->relmapentry.localrelvalid = false;
524  }
525 }
526 
527 /*
528  * Reset the entries in the partition map that refer to remoterel.
529  *
530  * Called when new relation mapping is sent by the publisher to update our
531  * expected view of incoming data from said publisher.
532  *
533  * Note that we don't update the remoterel information in the entry here,
534  * we will update the information in logicalrep_partition_open to avoid
535  * unnecessary work.
536  */
537 void
539 {
541  LogicalRepPartMapEntry *part_entry;
542  LogicalRepRelMapEntry *entry;
543 
544  if (LogicalRepPartMap == NULL)
545  return;
546 
548  while ((part_entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
549  {
550  entry = &part_entry->relmapentry;
551 
552  if (entry->remoterel.remoteid != remoterel->remoteid)
553  continue;
554 
556 
557  memset(entry, 0, sizeof(LogicalRepRelMapEntry));
558  }
559 }
560 
561 /*
562  * Initialize the partition map cache.
563  */
564 static void
566 {
567  HASHCTL ctl;
568 
572  "LogicalRepPartMapContext",
574 
575  /* Initialize the relation hash table. */
576  ctl.keysize = sizeof(Oid); /* partition OID */
577  ctl.entrysize = sizeof(LogicalRepPartMapEntry);
579 
580  LogicalRepPartMap = hash_create("logicalrep partition map cache", 64, &ctl,
582 
583  /* Watch for invalidation events. */
585  (Datum) 0);
586 }
587 
588 /*
589  * logicalrep_partition_open
590  *
591  * Returned entry reuses most of the values of the root table's entry, save
592  * the attribute map, which can be different for the partition. However,
593  * we must physically copy all the data, in case the root table's entry
594  * gets freed/rebuilt.
595  *
596  * Note there's no logicalrep_partition_close, because the caller closes the
597  * component relation.
598  */
601  Relation partrel, AttrMap *map)
602 {
603  LogicalRepRelMapEntry *entry;
604  LogicalRepPartMapEntry *part_entry;
605  LogicalRepRelation *remoterel = &root->remoterel;
606  Oid partOid = RelationGetRelid(partrel);
607  AttrMap *attrmap = root->attrmap;
608  bool found;
609  MemoryContext oldctx;
610 
611  if (LogicalRepPartMap == NULL)
613 
614  /* Search for existing entry. */
616  &partOid,
617  HASH_ENTER, &found);
618 
619  entry = &part_entry->relmapentry;
620 
621  /*
622  * We must always overwrite entry->localrel with the latest partition
623  * Relation pointer, because the Relation pointed to by the old value may
624  * have been cleared after the caller would have closed the partition
625  * relation after the last use of this entry. Note that localrelvalid is
626  * only updated by the relcache invalidation callback, so it may still be
627  * true irrespective of whether the Relation pointed to by localrel has
628  * been cleared or not.
629  */
630  if (found && entry->localrelvalid)
631  {
632  entry->localrel = partrel;
633  return entry;
634  }
635 
636  /* Switch to longer-lived context. */
638 
639  if (!found)
640  {
641  memset(part_entry, 0, sizeof(LogicalRepPartMapEntry));
642  part_entry->partoid = partOid;
643  }
644 
645  /* Release the no-longer-useful attrmap, if any. */
646  if (entry->attrmap)
647  {
648  free_attrmap(entry->attrmap);
649  entry->attrmap = NULL;
650  }
651 
652  if (!entry->remoterel.remoteid)
653  {
654  int i;
655 
656  /* Remote relation is copied as-is from the root entry. */
657  entry = &part_entry->relmapentry;
658  entry->remoterel.remoteid = remoterel->remoteid;
659  entry->remoterel.nspname = pstrdup(remoterel->nspname);
660  entry->remoterel.relname = pstrdup(remoterel->relname);
661  entry->remoterel.natts = remoterel->natts;
662  entry->remoterel.attnames = palloc(remoterel->natts * sizeof(char *));
663  entry->remoterel.atttyps = palloc(remoterel->natts * sizeof(Oid));
664  for (i = 0; i < remoterel->natts; i++)
665  {
666  entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
667  entry->remoterel.atttyps[i] = remoterel->atttyps[i];
668  }
669  entry->remoterel.replident = remoterel->replident;
670  entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
671  }
672 
673  entry->localrel = partrel;
674  entry->localreloid = partOid;
675 
676  /*
677  * If the partition's attributes don't match the root relation's, we'll
678  * need to make a new attrmap which maps partition attribute numbers to
679  * remoterel's, instead of the original which maps root relation's
680  * attribute numbers to remoterel's.
681  *
682  * Note that 'map' which comes from the tuple routing data structure
683  * contains 1-based attribute numbers (of the parent relation). However,
684  * the map in 'entry', a logical replication data structure, contains
685  * 0-based attribute numbers (of the remote relation).
686  */
687  if (map)
688  {
689  AttrNumber attno;
690 
691  entry->attrmap = make_attrmap(map->maplen);
692  for (attno = 0; attno < entry->attrmap->maplen; attno++)
693  {
694  AttrNumber root_attno = map->attnums[attno];
695 
696  /* 0 means it's a dropped attribute. See comments atop AttrMap. */
697  if (root_attno == 0)
698  entry->attrmap->attnums[attno] = -1;
699  else
700  entry->attrmap->attnums[attno] = attrmap->attnums[root_attno - 1];
701  }
702  }
703  else
704  {
705  /* Lacking copy_attmap, do this the hard way. */
706  entry->attrmap = make_attrmap(attrmap->maplen);
707  memcpy(entry->attrmap->attnums, attrmap->attnums,
708  attrmap->maplen * sizeof(AttrNumber));
709  }
710 
711  /* Set if the table's replica identity is enough to apply update/delete. */
713 
714  /* state and statelsn are left set to 0. */
715  MemoryContextSwitchTo(oldctx);
716 
717  /*
718  * Finding a usable index is an infrequent task. It occurs when an
719  * operation is first performed on the relation, or after invalidation of
720  * the relation cache entry (such as ANALYZE or CREATE/DROP index on the
721  * relation).
722  *
723  * We also prefer to run this code on the oldctx so that we do not leak
724  * anything in the LogicalRepPartMapContext (hence CacheMemoryContext).
725  */
726  entry->localindexoid = FindLogicalRepLocalIndex(partrel, remoterel,
727  entry->attrmap);
728 
729  entry->localrelvalid = true;
730 
731  return entry;
732 }
733 
734 /*
735  * Returns true if the given index consists only of expressions such as:
736  * CREATE INDEX idx ON table(foo(col));
737  *
738  * Returns false even if there is one column reference:
739  * CREATE INDEX idx ON table(foo(col), col_2);
740  */
741 static bool
743 {
744  for (int i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
745  {
746  AttrNumber attnum = indexInfo->ii_IndexAttrNumbers[i];
747 
749  return false;
750  }
751 
752  return true;
753 }
754 
755 /*
756  * Returns true if the attrmap contains the leftmost column of the index.
757  * Otherwise returns false.
758  *
759  * attrmap is a map of local attributes to remote ones. We can consult this
760  * map to check whether the local index attribute has a corresponding remote
761  * attribute.
762  */
763 static bool
765 {
766  AttrNumber keycol;
767 
768  Assert(indexInfo->ii_NumIndexAttrs >= 1);
769 
770  keycol = indexInfo->ii_IndexAttrNumbers[0];
771  if (!AttributeNumberIsValid(keycol))
772  return false;
773 
774  if (attrmap->maplen <= AttrNumberGetAttrOffset(keycol))
775  return false;
776 
777  return attrmap->attnums[AttrNumberGetAttrOffset(keycol)] >= 0;
778 }
779 
780 /*
781  * Returns the oid of an index that can be used by the apply worker to scan
782  * the relation. The index must be btree, non-partial, and have at least
783  * one column reference (i.e. cannot consist of only expressions). These
784  * limitations help to keep the index scan similar to PK/RI index scans.
785  *
786  * Note that the limitations of index scans for replica identity full only
787  * adheres to a subset of the limitations of PK/RI. For example, we support
788  * columns that are marked as [NULL] or we are not interested in the [NOT
789  * DEFERRABLE] aspect of constraints here. It works for us because we always
790  * compare the tuples for non-PK/RI index scans. See
791  * RelationFindReplTupleByIndex().
792  *
793  * XXX: There are no fundamental problems for supporting non-btree indexes.
794  * We mostly need to relax the limitations in RelationFindReplTupleByIndex().
795  * For partial indexes, the required changes are likely to be larger. If
796  * none of the tuples satisfy the expression for the index scan, we fall-back
797  * to sequential execution, which might not be a good idea in some cases.
798  *
799  * We also skip indexes if the remote relation does not contain the leftmost
800  * column of the index. This is because in most such cases sequential scan is
801  * favorable over index scan.
802  *
803  * We expect to call this function when REPLICA IDENTITY FULL is defined for
804  * the remote relation.
805  *
806  * If no suitable index is found, returns InvalidOid.
807  */
808 static Oid
810 {
811  List *idxlist = RelationGetIndexList(localrel);
812  ListCell *lc;
813 
814  foreach(lc, idxlist)
815  {
816  Oid idxoid = lfirst_oid(lc);
817  bool isUsableIdx;
818  bool containsLeftMostCol;
819  Relation idxRel;
820  IndexInfo *idxInfo;
821 
822  idxRel = index_open(idxoid, AccessShareLock);
823  idxInfo = BuildIndexInfo(idxRel);
824  isUsableIdx = IsIndexUsableForReplicaIdentityFull(idxInfo);
825  containsLeftMostCol =
826  RemoteRelContainsLeftMostColumnOnIdx(idxInfo, attrmap);
827  index_close(idxRel, AccessShareLock);
828 
829  /* Return the first eligible index found */
830  if (isUsableIdx && containsLeftMostCol)
831  return idxoid;
832  }
833 
834  return InvalidOid;
835 }
836 
837 /*
838  * Returns true if the index is usable for replica identity full. For details,
839  * see FindUsableIndexForReplicaIdentityFull.
840  */
841 bool
843 {
844  bool is_btree = (indexInfo->ii_Am == BTREE_AM_OID);
845  bool is_partial = (indexInfo->ii_Predicate != NIL);
846  bool is_only_on_expression = IsIndexOnlyOnExpression(indexInfo);
847 
848  return is_btree && !is_partial && !is_only_on_expression;
849 }
850 
851 /*
852  * Get replica identity index or if it is not defined a primary key.
853  *
854  * If neither is defined, returns InvalidOid
855  */
856 Oid
858 {
859  Oid idxoid;
860 
861  idxoid = RelationGetReplicaIndex(rel);
862 
863  if (!OidIsValid(idxoid))
864  idxoid = RelationGetPrimaryKeyIndex(rel);
865 
866  return idxoid;
867 }
868 
869 /*
870  * Returns the index oid if we can use an index for subscriber. Otherwise,
871  * returns InvalidOid.
872  */
873 static Oid
875  AttrMap *attrMap)
876 {
877  Oid idxoid;
878 
879  /*
880  * We never need index oid for partitioned tables, always rely on leaf
881  * partition's index.
882  */
883  if (localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
884  return InvalidOid;
885 
886  /*
887  * Simple case, we already have a primary key or a replica identity index.
888  */
889  idxoid = GetRelationIdentityOrPK(localrel);
890  if (OidIsValid(idxoid))
891  return idxoid;
892 
893  if (remoterel->replident == REPLICA_IDENTITY_FULL)
894  {
895  /*
896  * We are looking for one more opportunity for using an index. If
897  * there are any indexes defined on the local relation, try to pick a
898  * suitable index.
899  *
900  * The index selection safely assumes that all the columns are going
901  * to be available for the index scan given that remote relation has
902  * replica identity full.
903  *
904  * Note that we are not using the planner to find the cheapest method
905  * to scan the relation as that would require us to either use lower
906  * level planner functions which would be a maintenance burden in the
907  * long run or use the full-fledged planner which could cause
908  * overhead.
909  */
910  return FindUsableIndexForReplicaIdentityFull(localrel, attrMap);
911  }
912 
913  return InvalidOid;
914 }
void free_attrmap(AttrMap *map)
Definition: attmap.c:57
AttrMap * make_attrmap(int maplen)
Definition: attmap.c:41
int16 AttrNumber
Definition: attnum.h:21
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define AttrNumberGetAttrOffset(attNum)
Definition: attnum.h:51
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition: attnum.h:41
Subscription * MySubscription
Definition: worker.c:314
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1039
void bms_free(Bitmapset *a)
Definition: bitmapset.c:209
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:444
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:792
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:74
Bitmapset * bms_add_range(Bitmapset *a, int lower, int upper)
Definition: bitmapset.c:859
#define bms_is_empty(a)
Definition: bitmapset.h:105
#define NameStr(name)
Definition: c.h:730
#define OidIsValid(objectId)
Definition: c.h:759
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
void hash_seq_term(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1507
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1431
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1421
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1179
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define _(x)
Definition: elog.c:91
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2434
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
void CacheRegisterRelcacheCallback(RelcacheCallbackFunction func, Datum arg)
Definition: inval.c:1561
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
int LOCKMODE
Definition: lockdefs.h:26
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
uint32 LogicalRepRelId
Definition: logicalproto.h:101
struct LogicalRepRelMapEntry LogicalRepRelMapEntry
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
char * pstrdup(const char *in)
Definition: mcxt.c:1624
void pfree(void *pointer)
Definition: mcxt.c:1436
MemoryContext CacheMemoryContext
Definition: mcxt.c:144
void * palloc(Size size)
Definition: mcxt.c:1210
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:83
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
void * arg
#define NIL
Definition: pg_list.h:68
#define lfirst_oid(lc)
Definition: pg_list.h:174
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
uintptr_t Datum
Definition: postgres.h:64
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetRelid(relation)
Definition: rel.h:503
#define RelationGetDescr(relation)
Definition: rel.h:529
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4739
Oid RelationGetPrimaryKeyIndex(Relation relation)
Definition: relcache.c:4927
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5169
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4948
@ INDEX_ATTR_BITMAP_PRIMARY_KEY
Definition: relcache.h:60
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition: relcache.h:61
static MemoryContext LogicalRepPartMapContext
Definition: relation.c:47
void logicalrep_partmap_reset_relmap(LogicalRepRelation *remoterel)
Definition: relation.c:538
static void logicalrep_partmap_init(void)
Definition: relation.c:565
static void logicalrep_report_missing_attrs(LogicalRepRelation *remoterel, Bitmapset *missingatts)
Definition: relation.c:224
static void logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
Definition: relation.c:130
LogicalRepRelMapEntry * logicalrep_partition_open(LogicalRepRelMapEntry *root, Relation partrel, AttrMap *map)
Definition: relation.c:600
struct LogicalRepPartMapEntry LogicalRepPartMapEntry
static void logicalrep_partmap_invalidate_cb(Datum arg, Oid reloid)
Definition: relation.c:490
static bool IsIndexOnlyOnExpression(IndexInfo *indexInfo)
Definition: relation.c:742
static HTAB * LogicalRepPartMap
Definition: relation.c:48
static HTAB * LogicalRepRelMap
Definition: relation.c:34
static void logicalrep_rel_mark_updatable(LogicalRepRelMapEntry *entry)
Definition: relation.c:272
static MemoryContext LogicalRepRelMapContext
Definition: relation.c:32
Oid GetRelationIdentityOrPK(Relation rel)
Definition: relation.c:857
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:162
static void logicalrep_relmap_init(void)
Definition: relation.c:103
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:325
bool IsIndexUsableForReplicaIdentityFull(IndexInfo *indexInfo)
Definition: relation.c:842
static int logicalrep_rel_att_by_name(LogicalRepRelation *remoterel, const char *attname)
Definition: relation.c:207
static bool RemoteRelContainsLeftMostColumnOnIdx(IndexInfo *indexInfo, AttrMap *attrmap)
Definition: relation.c:764
static Oid FindUsableIndexForReplicaIdentityFull(Relation localrel, AttrMap *attrmap)
Definition: relation.c:809
static void logicalrep_relmap_invalidate_cb(Datum arg, Oid reloid)
Definition: relation.c:62
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:471
static Oid FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel, AttrMap *attrMap)
Definition: relation.c:874
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Definition: attmap.h:35
int maplen
Definition: attmap.h:37
AttrNumber * attnums
Definition: attmap.h:36
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:220
int ii_NumIndexAttrs
Definition: execnodes.h:177
int ii_NumIndexKeyAttrs
Definition: execnodes.h:178
Oid ii_Am
Definition: execnodes.h:200
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:179
List * ii_Predicate
Definition: execnodes.h:182
Definition: pg_list.h:54
LogicalRepRelMapEntry relmapentry
Definition: relation.c:52
LogicalRepRelation remoterel
LogicalRepRelId remoteid
Definition: logicalproto.h:107
Bitmapset * attkeys
Definition: logicalproto.h:115
Form_pg_class rd_rel
Definition: rel.h:110
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:60
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92