Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : * relation.c
3 : : * PostgreSQL logical replication relation mapping cache
4 : : *
5 : : * Copyright (c) 2016-2026, 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/amapi.h"
21 : : #include "access/genam.h"
22 : : #include "access/table.h"
23 : : #include "catalog/namespace.h"
24 : : #include "catalog/pg_subscription_rel.h"
25 : : #include "executor/executor.h"
26 : : #include "nodes/makefuncs.h"
27 : : #include "replication/logicalrelation.h"
28 : : #include "replication/worker_internal.h"
29 : : #include "utils/inval.h"
30 : : #include "utils/lsyscache.h"
31 : : #include "utils/syscache.h"
32 : : #include "utils/typcache.h"
33 : :
34 : :
35 : : static MemoryContext LogicalRepRelMapContext = NULL;
36 : :
37 : : static HTAB *LogicalRepRelMap = NULL;
38 : :
39 : : /*
40 : : * Partition map (LogicalRepPartMap)
41 : : *
42 : : * When a partitioned table is used as replication target, replicated
43 : : * operations are actually performed on its leaf partitions, which requires
44 : : * the partitions to also be mapped to the remote relation. Parent's entry
45 : : * (LogicalRepRelMapEntry) cannot be used as-is for all partitions, because
46 : : * individual partitions may have different attribute numbers, which means
47 : : * attribute mappings to remote relation's attributes must be maintained
48 : : * separately for each partition.
49 : : */
50 : : static MemoryContext LogicalRepPartMapContext = NULL;
51 : : static HTAB *LogicalRepPartMap = NULL;
52 : : typedef struct LogicalRepPartMapEntry
53 : : {
54 : : Oid partoid; /* LogicalRepPartMap's key */
55 : : LogicalRepRelMapEntry relmapentry;
56 : : } LogicalRepPartMapEntry;
57 : :
58 : : static Oid FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel,
59 : : AttrMap *attrMap);
60 : :
61 : : /*
62 : : * Relcache invalidation callback for our relation map cache.
63 : : */
64 : : static void
3507 peter_e@gmx.net 65 :CBC 730 : logicalrep_relmap_invalidate_cb(Datum arg, Oid reloid)
66 : : {
67 : : LogicalRepRelMapEntry *entry;
68 : :
69 : : /* Just to be sure. */
70 [ - + ]: 730 : if (LogicalRepRelMap == NULL)
3507 peter_e@gmx.net 71 :UBC 0 : return;
72 : :
3507 peter_e@gmx.net 73 [ + - ]:CBC 730 : if (reloid != InvalidOid)
74 : : {
75 : : HASH_SEQ_STATUS status;
76 : :
77 : 730 : hash_seq_init(&status, LogicalRepRelMap);
78 : :
79 : : /* TODO, use inverse lookup hashtable? */
80 [ + + ]: 3157 : while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
81 : : {
82 [ + + ]: 2559 : if (entry->localreloid == reloid)
83 : : {
2171 tgl@sss.pgh.pa.us 84 : 132 : entry->localrelvalid = false;
3507 peter_e@gmx.net 85 : 132 : hash_seq_term(&status);
86 : 132 : break;
87 : : }
88 : : }
89 : : }
90 : : else
91 : : {
92 : : /* invalidate all cache entries */
93 : : HASH_SEQ_STATUS status;
94 : :
3507 peter_e@gmx.net 95 :UBC 0 : hash_seq_init(&status, LogicalRepRelMap);
96 : :
97 [ # # ]: 0 : while ((entry = (LogicalRepRelMapEntry *) hash_seq_search(&status)) != NULL)
2171 tgl@sss.pgh.pa.us 98 : 0 : entry->localrelvalid = false;
99 : : }
100 : : }
101 : :
102 : : /*
103 : : * Initialize the relation map cache.
104 : : */
105 : : static void
3413 andres@anarazel.de 106 :CBC 419 : logicalrep_relmap_init(void)
107 : : {
108 : : HASHCTL ctl;
109 : :
3507 peter_e@gmx.net 110 [ + - ]: 419 : if (!LogicalRepRelMapContext)
111 : 419 : LogicalRepRelMapContext =
112 : 419 : AllocSetContextCreate(CacheMemoryContext,
113 : : "LogicalRepRelMapContext",
114 : : ALLOCSET_DEFAULT_SIZES);
115 : :
116 : : /* Initialize the relation hash table. */
117 : 419 : ctl.keysize = sizeof(LogicalRepRelId);
118 : 419 : ctl.entrysize = sizeof(LogicalRepRelMapEntry);
119 : 419 : ctl.hcxt = LogicalRepRelMapContext;
120 : :
121 : 419 : LogicalRepRelMap = hash_create("logicalrep relation map cache", 128, &ctl,
122 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
123 : :
124 : : /* Watch for invalidation events. */
125 : 419 : CacheRegisterRelcacheCallback(logicalrep_relmap_invalidate_cb,
126 : : (Datum) 0);
127 : 419 : }
128 : :
129 : : /*
130 : : * Free the entry of a relation map cache.
131 : : */
132 : : static void
133 : 143 : logicalrep_relmap_free_entry(LogicalRepRelMapEntry *entry)
134 : : {
135 : : LogicalRepRelation *remoterel;
136 : :
137 : 143 : remoterel = &entry->remoterel;
138 : :
139 : 143 : pfree(remoterel->nspname);
140 : 143 : pfree(remoterel->relname);
141 : :
142 [ + - ]: 143 : if (remoterel->natts > 0)
143 : : {
144 : : int i;
145 : :
146 [ + + ]: 434 : for (i = 0; i < remoterel->natts; i++)
147 : 291 : pfree(remoterel->attnames[i]);
148 : :
149 : 143 : pfree(remoterel->attnames);
150 : 143 : pfree(remoterel->atttyps);
151 : : }
152 : 143 : bms_free(remoterel->attkeys);
153 : :
154 [ + + ]: 143 : if (entry->attrmap)
1526 akapila@postgresql.o 155 : 121 : free_attrmap(entry->attrmap);
3507 peter_e@gmx.net 156 : 143 : }
157 : :
158 : : /*
159 : : * Add new entry or update existing entry in the relation map cache.
160 : : *
161 : : * Called when new relation mapping is sent by the publisher to update
162 : : * our expected view of incoming data from said publisher.
163 : : */
164 : : void
165 : 673 : logicalrep_relmap_update(LogicalRepRelation *remoterel)
166 : : {
167 : : MemoryContext oldctx;
168 : : LogicalRepRelMapEntry *entry;
169 : : bool found;
170 : : int i;
171 : :
172 [ + + ]: 673 : if (LogicalRepRelMap == NULL)
173 : 419 : logicalrep_relmap_init();
174 : :
175 : : /*
176 : : * HASH_ENTER returns the existing entry if present or creates a new one.
177 : : */
1298 peter@eisentraut.org 178 : 673 : entry = hash_search(LogicalRepRelMap, &remoterel->remoteid,
179 : : HASH_ENTER, &found);
180 : :
3507 peter_e@gmx.net 181 [ + + ]: 673 : if (found)
182 : 135 : logicalrep_relmap_free_entry(entry);
183 : :
3413 andres@anarazel.de 184 : 673 : memset(entry, 0, sizeof(LogicalRepRelMapEntry));
185 : :
186 : : /* Make cached copy of the data */
3507 peter_e@gmx.net 187 : 673 : oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
188 : 673 : entry->remoterel.remoteid = remoterel->remoteid;
189 : 673 : entry->remoterel.nspname = pstrdup(remoterel->nspname);
190 : 673 : entry->remoterel.relname = pstrdup(remoterel->relname);
191 : 673 : entry->remoterel.natts = remoterel->natts;
260 michael@paquier.xyz 192 : 673 : entry->remoterel.attnames = palloc_array(char *, remoterel->natts);
193 : 673 : entry->remoterel.atttyps = palloc_array(Oid, remoterel->natts);
3507 peter_e@gmx.net 194 [ + + ]: 1895 : for (i = 0; i < remoterel->natts; i++)
195 : : {
196 : 1222 : entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
197 : 1222 : entry->remoterel.atttyps[i] = remoterel->atttyps[i];
198 : : }
199 : 673 : entry->remoterel.replident = remoterel->replident;
200 : :
201 : : /*
202 : : * XXX The walsender currently does not transmit the relkind of the remote
203 : : * relation when replicating changes. Since we support replicating only
204 : : * table changes at present, we default to initializing relkind as
205 : : * RELKIND_RELATION. This is needed in CheckSubscriptionRelkind() to check
206 : : * if the publisher and subscriber relation kinds are compatible.
207 : : */
308 akapila@postgresql.o 208 : 673 : entry->remoterel.relkind =
209 [ + + ]: 673 : (remoterel->relkind == 0) ? RELKIND_RELATION : remoterel->relkind;
210 : :
3507 peter_e@gmx.net 211 : 673 : entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
212 : 673 : MemoryContextSwitchTo(oldctx);
213 : 673 : }
214 : :
215 : : /*
216 : : * Find attribute index in TupleDesc struct by attribute name.
217 : : *
218 : : * Returns -1 if not found.
219 : : */
220 : : static int
221 : 1382 : logicalrep_rel_att_by_name(LogicalRepRelation *remoterel, const char *attname)
222 : : {
223 : : int i;
224 : :
225 [ + + ]: 2608 : for (i = 0; i < remoterel->natts; i++)
226 : : {
227 [ + + ]: 2325 : if (strcmp(remoterel->attnames[i], attname) == 0)
228 : 1099 : return i;
229 : : }
230 : :
231 : 283 : return -1;
232 : : }
233 : :
234 : : /*
235 : : * Returns a comma-separated string of attribute names based on the provided
236 : : * relation and bitmap indicating which attributes to include.
237 : : */
238 : : static char *
638 akapila@postgresql.o 239 : 2 : logicalrep_get_attrs_str(LogicalRepRelation *remoterel, Bitmapset *atts)
240 : : {
241 : : StringInfoData attsbuf;
77 alvherre@kurilemu.de 242 : 2 : bool first = true;
638 akapila@postgresql.o 243 : 2 : int i = -1;
244 : :
245 [ - + ]: 2 : Assert(!bms_is_empty(atts));
246 : :
247 : 2 : initStringInfo(&attsbuf);
248 : :
249 [ + + ]: 6 : while ((i = bms_next_member(atts, i)) >= 0)
250 : : {
77 alvherre@kurilemu.de 251 [ + + ]: 4 : if (first)
252 : 2 : appendStringInfo(&attsbuf, _("\"%s\""), remoterel->attnames[i]);
253 : : else
254 : 2 : appendStringInfo(&attsbuf, _(", \"%s\""), remoterel->attnames[i]);
255 : 4 : first = false;
256 : : }
257 : :
638 akapila@postgresql.o 258 : 2 : return attsbuf.data;
259 : : }
260 : :
261 : : /*
262 : : * If attempting to replicate missing or generated columns, report an error.
263 : : * Prioritize 'missing' errors if both occur though the prioritization is
264 : : * arbitrary.
265 : : */
266 : : static void
267 : 605 : logicalrep_report_missing_or_gen_attrs(LogicalRepRelation *remoterel,
268 : : Bitmapset *missingatts,
269 : : Bitmapset *generatedatts)
270 : : {
271 [ + + ]: 605 : if (!bms_is_empty(missingatts))
2150 272 [ + - ]: 1 : ereport(ERROR,
273 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
274 : : errmsg_plural("logical replication target relation \"%s.%s\" is missing replicated column: %s",
275 : : "logical replication target relation \"%s.%s\" is missing replicated columns: %s",
276 : : bms_num_members(missingatts),
277 : : remoterel->nspname,
278 : : remoterel->relname,
279 : : logicalrep_get_attrs_str(remoterel,
280 : : missingatts)));
281 : :
638 282 [ + + ]: 604 : if (!bms_is_empty(generatedatts))
283 [ + - ]: 1 : ereport(ERROR,
284 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
285 : : errmsg_plural("logical replication target relation \"%s.%s\" has incompatible generated column: %s",
286 : : "logical replication target relation \"%s.%s\" has incompatible generated columns: %s",
287 : : bms_num_members(generatedatts),
288 : : remoterel->nspname,
289 : : remoterel->relname,
290 : : logicalrep_get_attrs_str(remoterel,
291 : : generatedatts)));
2150 292 : 603 : }
293 : :
294 : : /*
295 : : * Check if replica identity matches and mark the updatable flag.
296 : : *
297 : : * We allow for stricter replica identity (fewer columns) on subscriber as
298 : : * that will not stop us from finding unique tuple. IE, if publisher has
299 : : * identity (id,timestamp) and subscriber just (id) this will not be a
300 : : * problem, but in the opposite scenario it will.
301 : : *
302 : : * We just mark the relation entry as not updatable here if the local
303 : : * replica identity is found to be insufficient for applying
304 : : * updates/deletes (inserts don't care!) and leave it to
305 : : * check_relation_updatable() to throw the actual error if needed.
306 : : */
307 : : static void
1528 308 : 618 : logicalrep_rel_mark_updatable(LogicalRepRelMapEntry *entry)
309 : : {
310 : : Bitmapset *idkey;
311 : 618 : LogicalRepRelation *remoterel = &entry->remoterel;
312 : : int i;
313 : :
314 : 618 : entry->updatable = true;
315 : :
316 : 618 : idkey = RelationGetIndexAttrBitmap(entry->localrel,
317 : : INDEX_ATTR_BITMAP_IDENTITY_KEY);
318 : : /* fallback to PK if no replica identity */
319 [ + + ]: 618 : if (idkey == NULL)
320 : : {
321 : 229 : idkey = RelationGetIndexAttrBitmap(entry->localrel,
322 : : INDEX_ATTR_BITMAP_PRIMARY_KEY);
323 : :
324 : : /*
325 : : * If no replica identity index and no PK, the published table must
326 : : * have replica identity FULL.
327 : : */
328 [ + + + + ]: 229 : if (idkey == NULL && remoterel->replident != REPLICA_IDENTITY_FULL)
329 : 150 : entry->updatable = false;
330 : : }
331 : :
332 : 618 : i = -1;
333 [ + + ]: 1008 : while ((i = bms_next_member(idkey, i)) >= 0)
334 : : {
335 : 406 : int attnum = i + FirstLowInvalidHeapAttributeNumber;
336 : :
337 [ - + ]: 406 : if (!AttrNumberIsForUserDefinedAttr(attnum))
1528 akapila@postgresql.o 338 [ # # ]:UBC 0 : ereport(ERROR,
339 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
340 : : errmsg("logical replication target relation \"%s.%s\" uses "
341 : : "system columns in REPLICA IDENTITY index",
342 : : remoterel->nspname, remoterel->relname)));
343 : :
1528 akapila@postgresql.o 344 [ - + ]:CBC 406 : attnum = AttrNumberGetAttrOffset(attnum);
345 : :
346 [ + + ]: 406 : if (entry->attrmap->attnums[attnum] < 0 ||
347 [ + + ]: 405 : !bms_is_member(entry->attrmap->attnums[attnum], remoterel->attkeys))
348 : : {
349 : 16 : entry->updatable = false;
350 : 16 : break;
351 : : }
352 : : }
353 : 618 : }
354 : :
355 : : /*
356 : : * Open the local relation associated with the remote one.
357 : : *
358 : : * Rebuilds the Relcache mapping if it was invalidated by local DDL.
359 : : */
360 : : LogicalRepRelMapEntry *
3507 peter_e@gmx.net 361 : 168865 : logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
362 : : {
363 : : LogicalRepRelMapEntry *entry;
364 : : bool found;
365 : : LogicalRepRelation *remoterel;
366 : :
367 [ - + ]: 168865 : if (LogicalRepRelMap == NULL)
3507 peter_e@gmx.net 368 :UBC 0 : logicalrep_relmap_init();
369 : :
370 : : /* Search for existing entry. */
1298 peter@eisentraut.org 371 :CBC 168865 : entry = hash_search(LogicalRepRelMap, &remoteid,
372 : : HASH_FIND, &found);
373 : :
3507 peter_e@gmx.net 374 [ - + ]: 168865 : if (!found)
3507 peter_e@gmx.net 375 [ # # ]:UBC 0 : elog(ERROR, "no relation map entry for remote relation ID %u",
376 : : remoteid);
377 : :
2446 akapila@postgresql.o 378 :CBC 168865 : remoterel = &entry->remoterel;
379 : :
380 : : /* Ensure we don't leak a relcache refcount. */
2171 tgl@sss.pgh.pa.us 381 [ - + ]: 168865 : if (entry->localrel)
2171 tgl@sss.pgh.pa.us 382 [ # # ]:UBC 0 : elog(ERROR, "remote relation ID %u is already open", remoteid);
383 : :
384 : : /*
385 : : * When opening and locking a relation, pending invalidation messages are
386 : : * processed which can invalidate the relation. Hence, if the entry is
387 : : * currently considered valid, try to open the local relation by OID and
388 : : * see if invalidation ensues.
389 : : */
2171 tgl@sss.pgh.pa.us 390 [ + + ]:CBC 168865 : if (entry->localrelvalid)
391 : : {
392 : 168250 : entry->localrel = try_table_open(entry->localreloid, lockmode);
393 [ - + ]: 168250 : if (!entry->localrel)
394 : : {
395 : : /* Table was renamed or dropped. */
2171 tgl@sss.pgh.pa.us 396 :UBC 0 : entry->localrelvalid = false;
397 : : }
2171 tgl@sss.pgh.pa.us 398 [ - + ]:CBC 168250 : else if (!entry->localrelvalid)
399 : : {
400 : : /* Note we release the no-longer-useful lock here. */
2171 tgl@sss.pgh.pa.us 401 :UBC 0 : table_close(entry->localrel, lockmode);
402 : 0 : entry->localrel = NULL;
403 : : }
404 : : }
405 : :
406 : : /*
407 : : * If the entry has been marked invalid since we last had lock on it,
408 : : * re-open the local relation by name and rebuild all derived data.
409 : : */
2171 tgl@sss.pgh.pa.us 410 [ + + ]:CBC 168865 : if (!entry->localrelvalid)
411 : : {
412 : : Oid relid;
413 : : TupleDesc desc;
414 : : MemoryContext oldctx;
415 : : int i;
416 : : Bitmapset *missingatts;
638 akapila@postgresql.o 417 : 615 : Bitmapset *generatedattrs = NULL;
418 : :
419 : : /* Release the no-longer-useful attrmap, if any. */
1526 420 [ + + ]: 615 : if (entry->attrmap)
421 : : {
422 : 13 : free_attrmap(entry->attrmap);
423 : 13 : entry->attrmap = NULL;
424 : : }
425 : :
426 : : /* Try to find and lock the relation by name. */
3507 peter_e@gmx.net 427 : 615 : relid = RangeVarGetRelid(makeRangeVar(remoterel->nspname,
428 : : remoterel->relname, -1),
429 : : lockmode, true);
430 [ + + ]: 615 : if (!OidIsValid(relid))
431 [ + - ]: 10 : ereport(ERROR,
432 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
433 : : errmsg("logical replication target relation \"%s.%s\" does not exist",
434 : : remoterel->nspname, remoterel->relname)));
2775 andres@anarazel.de 435 : 605 : entry->localrel = table_open(relid, NoLock);
2171 tgl@sss.pgh.pa.us 436 : 605 : entry->localreloid = relid;
437 : :
438 : : /* Check for supported relkind. */
3390 peter_e@gmx.net 439 : 605 : CheckSubscriptionRelkind(entry->localrel->rd_rel->relkind,
308 akapila@postgresql.o 440 : 605 : remoterel->relkind,
3390 peter_e@gmx.net 441 : 605 : remoterel->nspname, remoterel->relname);
442 : :
443 : : /*
444 : : * Build the mapping of local attribute numbers to remote attribute
445 : : * numbers and validate that we don't miss any replicated columns as
446 : : * that would result in potentially unwanted data loss.
447 : : */
3507 448 : 605 : desc = RelationGetDescr(entry->localrel);
449 : 605 : oldctx = MemoryContextSwitchTo(LogicalRepRelMapContext);
2444 michael@paquier.xyz 450 : 605 : entry->attrmap = make_attrmap(desc->natts);
3507 peter_e@gmx.net 451 : 605 : MemoryContextSwitchTo(oldctx);
452 : :
453 : : /* check and report missing attrs, if any */
2150 akapila@postgresql.o 454 : 605 : missingatts = bms_add_range(NULL, 0, remoterel->natts - 1);
3507 peter_e@gmx.net 455 [ + + ]: 1989 : for (i = 0; i < desc->natts; i++)
456 : : {
457 : : int attnum;
3294 andres@anarazel.de 458 : 1384 : Form_pg_attribute attr = TupleDescAttr(desc, i);
459 : :
638 akapila@postgresql.o 460 [ + + ]: 1384 : if (attr->attisdropped)
461 : : {
2444 michael@paquier.xyz 462 : 2 : entry->attrmap->attnums[i] = -1;
3388 peter_e@gmx.net 463 : 2 : continue;
464 : : }
465 : :
466 : 1382 : attnum = logicalrep_rel_att_by_name(remoterel,
3294 andres@anarazel.de 467 : 1382 : NameStr(attr->attname));
468 : :
2444 michael@paquier.xyz 469 : 1382 : entry->attrmap->attnums[i] = attnum;
3507 peter_e@gmx.net 470 [ + + ]: 1382 : if (attnum >= 0)
471 : : {
472 : : /* Remember which subscriber columns are generated. */
638 akapila@postgresql.o 473 [ + + ]: 1099 : if (attr->attgenerated)
474 : 2 : generatedattrs = bms_add_member(generatedattrs, attnum);
475 : :
2150 476 : 1099 : missingatts = bms_del_member(missingatts, attnum);
477 : : }
478 : : }
479 : :
638 480 : 605 : logicalrep_report_missing_or_gen_attrs(remoterel, missingatts,
481 : : generatedattrs);
482 : :
483 : : /* be tidy */
484 : 603 : bms_free(generatedattrs);
2150 485 : 603 : bms_free(missingatts);
486 : :
487 : : /*
488 : : * Set if the table's replica identity is enough to apply
489 : : * update/delete.
490 : : */
1528 491 : 603 : logicalrep_rel_mark_updatable(entry);
492 : :
493 : : /*
494 : : * Finding a usable index is an infrequent task. It occurs when an
495 : : * operation is first performed on the relation, or after invalidation
496 : : * of the relation cache entry (such as ANALYZE or CREATE/DROP index
497 : : * on the relation).
498 : : */
1261 499 : 603 : entry->localindexoid = FindLogicalRepLocalIndex(entry->localrel, remoterel,
500 : : entry->attrmap);
501 : :
2171 tgl@sss.pgh.pa.us 502 : 603 : entry->localrelvalid = true;
503 : : }
504 : :
3444 peter_e@gmx.net 505 [ + + ]: 168853 : if (entry->state != SUBREL_STATE_READY)
506 : 663 : entry->state = GetSubscriptionRelState(MySubscription->oid,
507 : : entry->localreloid,
508 : : &entry->statelsn);
509 : :
3507 510 : 168853 : return entry;
511 : : }
512 : :
513 : : /*
514 : : * Close the previously opened logical relation.
515 : : */
516 : : void
517 : 168792 : logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
518 : : {
2775 andres@anarazel.de 519 : 168792 : table_close(rel->localrel, lockmode);
3507 peter_e@gmx.net 520 : 168792 : rel->localrel = NULL;
521 : 168792 : }
522 : :
523 : : /*
524 : : * Partition cache: look up partition LogicalRepRelMapEntry's
525 : : *
526 : : * Unlike relation map cache, this is keyed by partition OID, not remote
527 : : * relation OID, because we only have to use this cache in the case where
528 : : * partitions are not directly mapped to any remote relation, such as when
529 : : * replication is occurring with one of their ancestors as target.
530 : : */
531 : :
532 : : /*
533 : : * Relcache invalidation callback
534 : : */
535 : : static void
2334 peter@eisentraut.org 536 : 288 : logicalrep_partmap_invalidate_cb(Datum arg, Oid reloid)
537 : : {
538 : : LogicalRepPartMapEntry *entry;
539 : :
540 : : /* Just to be sure. */
541 [ - + ]: 288 : if (LogicalRepPartMap == NULL)
2334 peter@eisentraut.org 542 :UBC 0 : return;
543 : :
2334 peter@eisentraut.org 544 [ + - ]:CBC 288 : if (reloid != InvalidOid)
545 : : {
546 : : /*
547 : : * LogicalRepPartMap is keyed by partition OID, matching with
548 : : * entry->relmapentry.localreloid (see logicalrep_partition_open), so
549 : : * we can invalidate via a direct hash lookup.
550 : : */
31 michael@paquier.xyz 551 :GNC 288 : entry = hash_search(LogicalRepPartMap, &reloid, HASH_FIND, NULL);
552 [ + + ]: 288 : if (entry != NULL)
553 : 42 : entry->relmapentry.localrelvalid = false;
554 : : }
555 : : else
556 : : {
557 : : /* invalidate all cache entries */
558 : : HASH_SEQ_STATUS status;
559 : :
2334 peter@eisentraut.org 560 :UBC 0 : hash_seq_init(&status, LogicalRepPartMap);
561 : :
1534 akapila@postgresql.o 562 [ # # ]: 0 : while ((entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
563 : 0 : entry->relmapentry.localrelvalid = false;
564 : : }
565 : : }
566 : :
567 : : /*
568 : : * Reset the entries in the partition map that refer to remoterel.
569 : : *
570 : : * Called when new relation mapping is sent by the publisher to update our
571 : : * expected view of incoming data from said publisher.
572 : : *
573 : : * Note that we don't update the remoterel information in the entry here,
574 : : * we will update the information in logicalrep_partition_open to avoid
575 : : * unnecessary work.
576 : : */
577 : : void
1533 akapila@postgresql.o 578 :CBC 462 : logicalrep_partmap_reset_relmap(LogicalRepRelation *remoterel)
579 : : {
580 : : HASH_SEQ_STATUS status;
581 : : LogicalRepPartMapEntry *part_entry;
582 : : LogicalRepRelMapEntry *entry;
583 : :
584 [ + + ]: 462 : if (LogicalRepPartMap == NULL)
585 : 428 : return;
586 : :
587 : 34 : hash_seq_init(&status, LogicalRepPartMap);
588 [ + + ]: 87 : while ((part_entry = (LogicalRepPartMapEntry *) hash_seq_search(&status)) != NULL)
589 : : {
590 : 53 : entry = &part_entry->relmapentry;
591 : :
592 [ + + ]: 53 : if (entry->remoterel.remoteid != remoterel->remoteid)
593 : 45 : continue;
594 : :
595 : 8 : logicalrep_relmap_free_entry(entry);
596 : :
597 : 8 : memset(entry, 0, sizeof(LogicalRepRelMapEntry));
598 : : }
599 : : }
600 : :
601 : : /*
602 : : * Initialize the partition map cache.
603 : : */
604 : : static void
2334 peter@eisentraut.org 605 : 6 : logicalrep_partmap_init(void)
606 : : {
607 : : HASHCTL ctl;
608 : :
609 [ + - ]: 6 : if (!LogicalRepPartMapContext)
610 : 6 : LogicalRepPartMapContext =
611 : 6 : AllocSetContextCreate(CacheMemoryContext,
612 : : "LogicalRepPartMapContext",
613 : : ALLOCSET_DEFAULT_SIZES);
614 : :
615 : : /* Initialize the relation hash table. */
616 : 6 : ctl.keysize = sizeof(Oid); /* partition OID */
617 : 6 : ctl.entrysize = sizeof(LogicalRepPartMapEntry);
618 : 6 : ctl.hcxt = LogicalRepPartMapContext;
619 : :
620 : 6 : LogicalRepPartMap = hash_create("logicalrep partition map cache", 64, &ctl,
621 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
622 : :
623 : : /* Watch for invalidation events. */
624 : 6 : CacheRegisterRelcacheCallback(logicalrep_partmap_invalidate_cb,
625 : : (Datum) 0);
626 : 6 : }
627 : :
628 : : /*
629 : : * logicalrep_partition_open
630 : : *
631 : : * Returned entry reuses most of the values of the root table's entry, save
632 : : * the attribute map, which can be different for the partition. However,
633 : : * we must physically copy all the data, in case the root table's entry
634 : : * gets freed/rebuilt.
635 : : *
636 : : * Note there's no logicalrep_partition_close, because the caller closes the
637 : : * component relation.
638 : : */
639 : : LogicalRepRelMapEntry *
640 : 30 : logicalrep_partition_open(LogicalRepRelMapEntry *root,
641 : : Relation partrel, AttrMap *map)
642 : : {
643 : : LogicalRepRelMapEntry *entry;
644 : : LogicalRepPartMapEntry *part_entry;
645 : 30 : LogicalRepRelation *remoterel = &root->remoterel;
646 : 30 : Oid partOid = RelationGetRelid(partrel);
647 : 30 : AttrMap *attrmap = root->attrmap;
648 : : bool found;
649 : : MemoryContext oldctx;
650 : :
651 [ + + ]: 30 : if (LogicalRepPartMap == NULL)
652 : 6 : logicalrep_partmap_init();
653 : :
654 : : /* Search for existing entry. */
655 : 30 : part_entry = (LogicalRepPartMapEntry *) hash_search(LogicalRepPartMap,
656 : : &partOid,
657 : : HASH_ENTER, &found);
658 : :
1534 akapila@postgresql.o 659 : 30 : entry = &part_entry->relmapentry;
660 : :
661 : : /*
662 : : * We must always overwrite entry->localrel with the latest partition
663 : : * Relation pointer, because the Relation pointed to by the old value may
664 : : * have been cleared after the caller would have closed the partition
665 : : * relation after the last use of this entry. Note that localrelvalid is
666 : : * only updated by the relcache invalidation callback, so it may still be
667 : : * true irrespective of whether the Relation pointed to by localrel has
668 : : * been cleared or not.
669 : : */
670 [ + + + + ]: 30 : if (found && entry->localrelvalid)
671 : : {
31 michael@paquier.xyz 672 [ - + ]:GNC 15 : Assert(entry->localreloid == partOid);
1528 akapila@postgresql.o 673 :CBC 15 : entry->localrel = partrel;
1534 674 : 15 : return entry;
675 : : }
676 : :
677 : : /* Switch to longer-lived context. */
2334 peter@eisentraut.org 678 : 15 : oldctx = MemoryContextSwitchTo(LogicalRepPartMapContext);
679 : :
1534 akapila@postgresql.o 680 [ + + ]: 15 : if (!found)
681 : : {
682 : 9 : memset(part_entry, 0, sizeof(LogicalRepPartMapEntry));
683 : 9 : part_entry->partoid = partOid;
684 : : }
685 : :
686 : : /* Release the no-longer-useful attrmap, if any. */
1526 687 [ + + ]: 15 : if (entry->attrmap)
688 : : {
689 : 1 : free_attrmap(entry->attrmap);
690 : 1 : entry->attrmap = NULL;
691 : : }
692 : :
1534 693 [ + + ]: 15 : if (!entry->remoterel.remoteid)
694 : : {
695 : : int i;
696 : :
697 : : /* Remote relation is copied as-is from the root entry. */
698 : 14 : entry->remoterel.remoteid = remoterel->remoteid;
699 : 14 : entry->remoterel.nspname = pstrdup(remoterel->nspname);
700 : 14 : entry->remoterel.relname = pstrdup(remoterel->relname);
701 : 14 : entry->remoterel.natts = remoterel->natts;
260 michael@paquier.xyz 702 : 14 : entry->remoterel.attnames = palloc_array(char *, remoterel->natts);
703 : 14 : entry->remoterel.atttyps = palloc_array(Oid, remoterel->natts);
1534 akapila@postgresql.o 704 [ + + ]: 44 : for (i = 0; i < remoterel->natts; i++)
705 : : {
706 : 30 : entry->remoterel.attnames[i] = pstrdup(remoterel->attnames[i]);
707 : 30 : entry->remoterel.atttyps[i] = remoterel->atttyps[i];
708 : : }
709 : 14 : entry->remoterel.replident = remoterel->replident;
710 : 14 : entry->remoterel.attkeys = bms_copy(remoterel->attkeys);
711 : : }
712 : :
2334 peter@eisentraut.org 713 : 15 : entry->localrel = partrel;
714 : 15 : entry->localreloid = partOid;
715 : :
716 : : /*
717 : : * If the partition's attributes don't match the root relation's, we'll
718 : : * need to make a new attrmap which maps partition attribute numbers to
719 : : * remoterel's, instead of the original which maps root relation's
720 : : * attribute numbers to remoterel's.
721 : : *
722 : : * Note that 'map' which comes from the tuple routing data structure
723 : : * contains 1-based attribute numbers (of the parent relation). However,
724 : : * the map in 'entry', a logical replication data structure, contains
725 : : * 0-based attribute numbers (of the remote relation).
726 : : */
727 [ + + ]: 15 : if (map)
728 : : {
729 : : AttrNumber attno;
730 : :
731 : 8 : entry->attrmap = make_attrmap(map->maplen);
732 [ + + ]: 34 : for (attno = 0; attno < entry->attrmap->maplen; attno++)
733 : : {
734 : 26 : AttrNumber root_attno = map->attnums[attno];
735 : :
736 : : /* 0 means it's a dropped attribute. See comments atop AttrMap. */
1534 akapila@postgresql.o 737 [ + + ]: 26 : if (root_attno == 0)
738 : 2 : entry->attrmap->attnums[attno] = -1;
739 : : else
740 : 24 : entry->attrmap->attnums[attno] = attrmap->attnums[root_attno - 1];
741 : : }
742 : : }
743 : : else
744 : : {
745 : : /* Lacking copy_attmap, do this the hard way. */
1903 tgl@sss.pgh.pa.us 746 : 7 : entry->attrmap = make_attrmap(attrmap->maplen);
747 : 7 : memcpy(entry->attrmap->attnums, attrmap->attnums,
748 : 7 : attrmap->maplen * sizeof(AttrNumber));
749 : : }
750 : :
751 : : /* Set if the table's replica identity is enough to apply update/delete. */
1528 akapila@postgresql.o 752 : 15 : logicalrep_rel_mark_updatable(entry);
753 : :
754 : : /* state and statelsn are left set to 0. */
2334 peter@eisentraut.org 755 : 15 : MemoryContextSwitchTo(oldctx);
756 : :
757 : : /*
758 : : * Finding a usable index is an infrequent task. It occurs when an
759 : : * operation is first performed on the relation, or after invalidation of
760 : : * the relation cache entry (such as ANALYZE or CREATE/DROP index on the
761 : : * relation).
762 : : *
763 : : * We also prefer to run this code on the oldctx so that we do not leak
764 : : * anything in the LogicalRepPartMapContext (hence CacheMemoryContext).
765 : : */
1261 akapila@postgresql.o 766 : 15 : entry->localindexoid = FindLogicalRepLocalIndex(partrel, remoterel,
767 : : entry->attrmap);
768 : :
769 : 15 : entry->localrelvalid = true;
770 : :
2334 peter@eisentraut.org 771 : 15 : return entry;
772 : : }
773 : :
774 : : /*
775 : : * Returns the oid of an index that can be used by the apply worker to scan
776 : : * the relation.
777 : : *
778 : : * We expect to call this function when REPLICA IDENTITY FULL is defined for
779 : : * the remote relation.
780 : : *
781 : : * If no suitable index is found, returns InvalidOid.
782 : : */
783 : : static Oid
1261 akapila@postgresql.o 784 : 67 : FindUsableIndexForReplicaIdentityFull(Relation localrel, AttrMap *attrmap)
785 : : {
786 : 67 : List *idxlist = RelationGetIndexList(localrel);
787 : :
966 nathan@postgresql.or 788 [ + + + + : 123 : foreach_oid(idxoid, idxlist)
+ + ]
789 : : {
790 : : bool isUsableIdx;
791 : : Relation idxRel;
792 : :
1261 akapila@postgresql.o 793 : 21 : idxRel = index_open(idxoid, AccessShareLock);
794 : :
795 : : /*
796 : : * indisvalid is checked here, not in
797 : : * IsIndexUsableForReplicaIdentityFull(), since that function's other
798 : : * caller (an assertion) must tolerate an index made transiently
799 : : * invalid by a concurrent DROP INDEX CONCURRENTLY, whereas a
800 : : * permanently invalid leftover of a failed CREATE INDEX CONCURRENTLY
801 : : * must never be chosen here.
802 : : */
0 803 [ + + + + ]: 41 : isUsableIdx = idxRel->rd_index->indisvalid &&
804 : 20 : IsIndexUsableForReplicaIdentityFull(idxRel, attrmap);
1261 805 : 21 : index_close(idxRel, AccessShareLock);
806 : :
807 : : /* Return the first eligible index found */
1129 msawada@postgresql.o 808 [ + + ]: 21 : if (isUsableIdx)
1261 akapila@postgresql.o 809 : 16 : return idxoid;
810 : : }
811 : :
812 : 51 : return InvalidOid;
813 : : }
814 : :
815 : : /*
816 : : * Returns true if the index is usable for replica identity full.
817 : : *
818 : : * The index must have an equal strategy for each key column, be non-partial,
819 : : * and the leftmost field must be a column (not an expression) that references
820 : : * the remote relation column. These limitations help to keep the index scan
821 : : * similar to PK/RI index scans.
822 : : *
823 : : * attrmap is a map of local attributes to remote ones. We can consult this
824 : : * map to check whether the local index attribute has a corresponding remote
825 : : * attribute.
826 : : *
827 : : * Note that this function does not check indisvalid. Callers that are
828 : : * selecting an index to use for future lookups must check indisvalid
829 : : * themselves and reject invalid indexes.
830 : : *
831 : : * Note that the limitations of index scans for replica identity full only
832 : : * adheres to a subset of the limitations of PK/RI. For example, we support
833 : : * columns that are marked as [NULL] or we are not interested in the [NOT
834 : : * DEFERRABLE] aspect of constraints here. It works for us because we always
835 : : * compare the tuples for non-PK/RI index scans. See
836 : : * RelationFindReplTupleByIndex().
837 : : *
838 : : * XXX: To support partial indexes, the required changes are likely to be larger.
839 : : * If none of the tuples satisfy the expression for the index scan, we fall-back
840 : : * to sequential execution, which might not be a good idea in some cases.
841 : : */
842 : : bool
631 peter@eisentraut.org 843 : 39 : IsIndexUsableForReplicaIdentityFull(Relation idxrel, AttrMap *attrmap)
844 : : {
845 : : AttrNumber keycol;
846 : : oidvector *indclass;
847 : :
848 : : /* The index must not be a partial index */
849 [ + + ]: 39 : if (!heap_attisnull(idxrel->rd_indextuple, Anum_pg_index_indpred, NULL))
1140 akapila@postgresql.o 850 : 2 : return false;
851 : :
631 peter@eisentraut.org 852 [ - + ]: 37 : Assert(idxrel->rd_index->indnatts >= 1);
853 : :
625 854 : 37 : indclass = (oidvector *) DatumGetPointer(SysCacheGetAttrNotNull(INDEXRELID,
855 : 37 : idxrel->rd_indextuple,
856 : : Anum_pg_index_indclass));
857 : :
858 : : /* Ensure that the index has a valid equal strategy for each key column */
859 [ + + ]: 107 : for (int i = 0; i < idxrel->rd_index->indnkeyatts; i++)
860 : : {
861 : : Oid opfamily;
862 : :
552 863 : 70 : opfamily = get_opclass_family(indclass->values[i]);
864 [ - + ]: 70 : if (IndexAmTranslateCompareType(COMPARE_EQ, idxrel->rd_rel->relam, opfamily, true) == InvalidStrategy)
625 peter@eisentraut.org 865 :UBC 0 : return false;
866 : : }
867 : :
868 : : /*
869 : : * For indexes other than PK and REPLICA IDENTITY, we need to match the
870 : : * local and remote tuples. The equality routine tuples_equal() cannot
871 : : * accept a data type where the type cache cannot provide an equality
872 : : * operator.
873 : : */
625 peter@eisentraut.org 874 [ + + ]:CBC 107 : for (int i = 0; i < idxrel->rd_att->natts; i++)
875 : : {
876 : : TypeCacheEntry *typentry;
877 : :
878 : 70 : typentry = lookup_type_cache(TupleDescAttr(idxrel->rd_att, i)->atttypid, TYPECACHE_EQ_OPR_FINFO);
879 [ - + ]: 70 : if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
625 peter@eisentraut.org 880 :UBC 0 : return false;
881 : : }
882 : :
883 : : /* The leftmost index field must not be an expression */
631 peter@eisentraut.org 884 :CBC 37 : keycol = idxrel->rd_index->indkey.values[0];
1129 msawada@postgresql.o 885 [ + + ]: 37 : if (!AttributeNumberIsValid(keycol))
886 : 2 : return false;
887 : :
888 : : /*
889 : : * And the leftmost index field must reference the remote relation column.
890 : : * This is because if it doesn't, the sequential scan is favorable over
891 : : * index scan in most cases.
892 : : */
893 [ - + + - ]: 35 : if (attrmap->maplen <= AttrNumberGetAttrOffset(keycol) ||
894 [ - + - + ]: 35 : attrmap->attnums[AttrNumberGetAttrOffset(keycol)] < 0)
1140 akapila@postgresql.o 895 :UBC 0 : return false;
896 : :
897 : : /*
898 : : * The given index access method must implement "amgettuple", which will
899 : : * be used later to fetch the tuples. See RelationFindReplTupleByIndex().
900 : : */
625 peter@eisentraut.org 901 [ - + ]:CBC 35 : if (GetIndexAmRoutineByAmId(idxrel->rd_rel->relam, false)->amgettuple == NULL)
625 peter@eisentraut.org 902 :UBC 0 : return false;
903 : :
1140 akapila@postgresql.o 904 :CBC 35 : return true;
905 : : }
906 : :
907 : : /*
908 : : * Return the OID of the replica identity index if one is defined;
909 : : * the OID of the PK if one exists and is not deferrable;
910 : : * otherwise, InvalidOid.
911 : : */
912 : : Oid
1261 913 : 144811 : GetRelationIdentityOrPK(Relation rel)
914 : : {
915 : : Oid idxoid;
916 : :
917 : 144811 : idxoid = RelationGetReplicaIndex(rel);
918 : :
919 [ + + ]: 144811 : if (!OidIsValid(idxoid))
657 alvherre@alvh.no-ip. 920 : 277 : idxoid = RelationGetPrimaryKeyIndex(rel, false);
921 : :
1261 akapila@postgresql.o 922 : 144811 : return idxoid;
923 : : }
924 : :
925 : : /*
926 : : * Returns the index oid if we can use an index for subscriber. Otherwise,
927 : : * returns InvalidOid.
928 : : */
929 : : static Oid
930 : 618 : FindLogicalRepLocalIndex(Relation localrel, LogicalRepRelation *remoterel,
931 : : AttrMap *attrMap)
932 : : {
933 : : Oid idxoid;
934 : :
935 : : /*
936 : : * We never need index oid for partitioned tables, always rely on leaf
937 : : * partition's index.
938 : : */
939 [ + + ]: 618 : if (localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
940 : 79 : return InvalidOid;
941 : :
942 : : /*
943 : : * Simple case, we already have a primary key or a replica identity index.
944 : : */
945 : 539 : idxoid = GetRelationIdentityOrPK(localrel);
946 [ + + ]: 539 : if (OidIsValid(idxoid))
947 : 336 : return idxoid;
948 : :
949 [ + + ]: 203 : if (remoterel->replident == REPLICA_IDENTITY_FULL)
950 : : {
951 : : /*
952 : : * We are looking for one more opportunity for using an index. If
953 : : * there are any indexes defined on the local relation, try to pick a
954 : : * suitable index.
955 : : *
956 : : * The index selection safely assumes that all the columns are going
957 : : * to be available for the index scan given that remote relation has
958 : : * replica identity full.
959 : : *
960 : : * Note that we are not using the planner to find the cheapest method
961 : : * to scan the relation as that would require us to either use lower
962 : : * level planner functions which would be a maintenance burden in the
963 : : * long run or use the full-fledged planner which could cause
964 : : * overhead.
965 : : */
966 : 67 : return FindUsableIndexForReplicaIdentityFull(localrel, attrMap);
967 : : }
968 : :
969 : 136 : return InvalidOid;
970 : : }
|