Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * pgoutput.c
4 : : * Logical Replication output plugin
5 : : *
6 : : * Copyright (c) 2012-2026, PostgreSQL Global Development Group
7 : : *
8 : : * IDENTIFICATION
9 : : * src/backend/replication/pgoutput/pgoutput.c
10 : : *
11 : : *-------------------------------------------------------------------------
12 : : */
13 : : #include "postgres.h"
14 : :
15 : : #include "access/tupconvert.h"
16 : : #include "catalog/partition.h"
17 : : #include "catalog/pg_publication.h"
18 : : #include "catalog/pg_publication_rel.h"
19 : : #include "catalog/pg_subscription.h"
20 : : #include "commands/defrem.h"
21 : : #include "commands/subscriptioncmds.h"
22 : : #include "executor/executor.h"
23 : : #include "fmgr.h"
24 : : #include "nodes/makefuncs.h"
25 : : #include "parser/parse_relation.h"
26 : : #include "replication/logical.h"
27 : : #include "replication/logicalproto.h"
28 : : #include "replication/origin.h"
29 : : #include "replication/pgoutput.h"
30 : : #include "rewrite/rewriteHandler.h"
31 : : #include "utils/builtins.h"
32 : : #include "utils/inval.h"
33 : : #include "utils/lsyscache.h"
34 : : #include "utils/memutils.h"
35 : : #include "utils/rel.h"
36 : : #include "utils/syscache.h"
37 : : #include "utils/varlena.h"
38 : :
612 tgl@sss.pgh.pa.us 39 :CBC 673 : PG_MODULE_MAGIC_EXT(
40 : : .name = "pgoutput",
41 : : .version = PG_VERSION
42 : : );
43 : :
44 : : static void pgoutput_startup(LogicalDecodingContext *ctx,
45 : : OutputPluginOptions *opt, bool is_init);
46 : : static void pgoutput_shutdown(LogicalDecodingContext *ctx);
47 : : static void pgoutput_begin_txn(LogicalDecodingContext *ctx,
48 : : ReorderBufferTXN *txn);
49 : : static void pgoutput_commit_txn(LogicalDecodingContext *ctx,
50 : : ReorderBufferTXN *txn, XLogRecPtr commit_lsn);
51 : : static void pgoutput_change(LogicalDecodingContext *ctx,
52 : : ReorderBufferTXN *txn, Relation relation,
53 : : ReorderBufferChange *change);
54 : : static void pgoutput_truncate(LogicalDecodingContext *ctx,
55 : : ReorderBufferTXN *txn, int nrelations, Relation relations[],
56 : : ReorderBufferChange *change);
57 : : static void pgoutput_message(LogicalDecodingContext *ctx,
58 : : ReorderBufferTXN *txn, TransactionId xid,
59 : : XLogRecPtr message_lsn, bool transactional,
60 : : const char *prefix, Size sz,
61 : : const char *message);
62 : : static bool pgoutput_origin_filter(LogicalDecodingContext *ctx,
63 : : ReplOriginId origin_id);
64 : : static void pgoutput_begin_prepare_txn(LogicalDecodingContext *ctx,
65 : : ReorderBufferTXN *txn);
66 : : static void pgoutput_prepare_txn(LogicalDecodingContext *ctx,
67 : : ReorderBufferTXN *txn, XLogRecPtr prepare_lsn);
68 : : static void pgoutput_commit_prepared_txn(LogicalDecodingContext *ctx,
69 : : ReorderBufferTXN *txn, XLogRecPtr commit_lsn);
70 : : static void pgoutput_rollback_prepared_txn(LogicalDecodingContext *ctx,
71 : : ReorderBufferTXN *txn,
72 : : XLogRecPtr prepare_end_lsn,
73 : : TimestampTz prepare_time);
74 : : static void pgoutput_stream_start(struct LogicalDecodingContext *ctx,
75 : : ReorderBufferTXN *txn);
76 : : static void pgoutput_stream_stop(struct LogicalDecodingContext *ctx,
77 : : ReorderBufferTXN *txn);
78 : : static void pgoutput_stream_abort(struct LogicalDecodingContext *ctx,
79 : : ReorderBufferTXN *txn,
80 : : XLogRecPtr abort_lsn);
81 : : static void pgoutput_stream_commit(struct LogicalDecodingContext *ctx,
82 : : ReorderBufferTXN *txn,
83 : : XLogRecPtr commit_lsn);
84 : : static void pgoutput_stream_prepare_txn(LogicalDecodingContext *ctx,
85 : : ReorderBufferTXN *txn, XLogRecPtr prepare_lsn);
86 : :
87 : : static bool publications_valid;
88 : :
89 : : static List *LoadPublications(List *pubnames);
90 : : static void publication_invalidation_cb(Datum arg, SysCacheIdentifier cacheid,
91 : : uint32 hashvalue);
92 : : static void send_repl_origin(LogicalDecodingContext *ctx,
93 : : ReplOriginId origin_id, XLogRecPtr origin_lsn,
94 : : bool send_origin);
95 : :
96 : : /*
97 : : * Only 3 publication actions are used for row filtering ("insert", "update",
98 : : * "delete"). See RelationSyncEntry.exprstate[].
99 : : */
100 : : enum RowFilterPubAction
101 : : {
102 : : PUBACTION_INSERT,
103 : : PUBACTION_UPDATE,
104 : : PUBACTION_DELETE,
105 : : };
106 : :
107 : : #define NUM_ROWFILTER_PUBACTIONS (PUBACTION_DELETE+1)
108 : :
109 : : /*
110 : : * Entry in the map used to remember which relation schemas we sent.
111 : : *
112 : : * The schema_sent flag determines if the current schema record for the
113 : : * relation (and for its ancestor if publish_as_relid is set) was already
114 : : * sent to the subscriber (in which case we don't need to send it again).
115 : : *
116 : : * The schema cache on downstream is however updated only at commit time,
117 : : * and with streamed transactions the commit order may be different from
118 : : * the order the transactions are sent in. Also, the (sub) transactions
119 : : * might get aborted so we need to send the schema for each (sub) transaction
120 : : * so that we don't lose the schema information on abort. For handling this,
121 : : * we maintain the list of xids (streamed_txns) for those we have already sent
122 : : * the schema.
123 : : *
124 : : * For partitions, 'pubactions' considers not only the table's own
125 : : * publications, but also those of all of its ancestors.
126 : : */
127 : : typedef struct RelationSyncEntry
128 : : {
129 : : Oid relid; /* relation oid */
130 : :
131 : : bool replicate_valid; /* overall validity flag for entry */
132 : :
133 : : bool schema_sent;
134 : :
135 : : /*
136 : : * This will be PUBLISH_GENCOLS_STORED if the relation contains generated
137 : : * columns and the 'publish_generated_columns' parameter is set to
138 : : * PUBLISH_GENCOLS_STORED. Otherwise, it will be PUBLISH_GENCOLS_NONE,
139 : : * indicating that no generated columns should be published, unless
140 : : * explicitly specified in the column list.
141 : : */
142 : : PublishGencolsType include_gencols_type;
143 : : List *streamed_txns; /* streamed toplevel transactions with this
144 : : * schema */
145 : :
146 : : /* are we publishing this rel? */
147 : : PublicationActions pubactions;
148 : :
149 : : /*
150 : : * ExprState array for row filter. Different publication actions don't
151 : : * allow multiple expressions to always be combined into one, because
152 : : * updates or deletes restrict the column in expression to be part of the
153 : : * replica identity index whereas inserts do not have this restriction, so
154 : : * there is one ExprState per publication action.
155 : : */
156 : : ExprState *exprstate[NUM_ROWFILTER_PUBACTIONS];
157 : : EState *estate; /* executor state used for row filter */
158 : : TupleTableSlot *new_slot; /* slot for storing new tuple */
159 : : TupleTableSlot *old_slot; /* slot for storing old tuple */
160 : :
161 : : /*
162 : : * OID of the relation to publish changes as. For a partition, this may
163 : : * be set to one of its ancestors whose schema will be used when
164 : : * replicating changes, if publish_via_partition_root is set for the
165 : : * publication.
166 : : */
167 : : Oid publish_as_relid;
168 : :
169 : : /*
170 : : * Map used when replicating using an ancestor's schema to convert tuples
171 : : * from partition's type to the ancestor's; NULL if publish_as_relid is
172 : : * same as 'relid' or if unnecessary due to partition and the ancestor
173 : : * having identical TupleDesc.
174 : : */
175 : : AttrMap *attrmap;
176 : :
177 : : /*
178 : : * Columns included in the publication, or NULL if all columns are
179 : : * included implicitly. Note that the attnums in this bitmap are not
180 : : * shifted by FirstLowInvalidHeapAttributeNumber.
181 : : */
182 : : Bitmapset *columns;
183 : :
184 : : /*
185 : : * Private context to store additional data for this entry - state for the
186 : : * row filter expressions, column list, etc.
187 : : */
188 : : MemoryContext entry_cxt;
189 : : } RelationSyncEntry;
190 : :
191 : : /*
192 : : * Maintain a per-transaction level variable to track whether the transaction
193 : : * has sent BEGIN. BEGIN is only sent when the first change in a transaction
194 : : * is processed. This makes it possible to skip sending a pair of BEGIN/COMMIT
195 : : * messages for empty transactions which saves network bandwidth.
196 : : *
197 : : * This optimization is not used for prepared transactions because if the
198 : : * WALSender restarts after prepare of a transaction and before commit prepared
199 : : * of the same transaction then we won't be able to figure out if we have
200 : : * skipped sending BEGIN/PREPARE of a transaction as it was empty. This is
201 : : * because we would have lost the in-memory txndata information that was
202 : : * present prior to the restart. This will result in sending a spurious
203 : : * COMMIT PREPARED without a corresponding prepared transaction at the
204 : : * downstream which would lead to an error when it tries to process it.
205 : : *
206 : : * XXX We could achieve this optimization by changing protocol to send
207 : : * additional information so that downstream can detect that the corresponding
208 : : * prepare has not been sent. However, adding such a check for every
209 : : * transaction in the downstream could be costly so we might want to do it
210 : : * optionally.
211 : : *
212 : : * We also don't have this optimization for streamed transactions because
213 : : * they can contain prepared transactions.
214 : : */
215 : : typedef struct PGOutputTxnData
216 : : {
217 : : bool sent_begin_txn; /* flag indicating whether BEGIN has been sent */
218 : : } PGOutputTxnData;
219 : :
220 : : /* Map used to remember which relation schemas we sent. */
221 : : static HTAB *RelationSyncCache = NULL;
222 : :
223 : : static void init_rel_sync_cache(MemoryContext cachectx);
224 : : static void cleanup_rel_sync_cache(TransactionId xid, bool mark_schema_sent);
225 : : static RelationSyncEntry *get_rel_sync_entry(PGOutputData *data,
226 : : Relation relation);
227 : : static void send_relation_and_attrs(Relation relation, TransactionId xid,
228 : : LogicalDecodingContext *ctx,
229 : : RelationSyncEntry *relentry);
230 : : static void rel_sync_cache_relation_cb(Datum arg, Oid relid);
231 : : static void rel_sync_cache_publication_cb(Datum arg, SysCacheIdentifier cacheid,
232 : : uint32 hashvalue);
233 : : static void set_schema_sent_in_streamed_txn(RelationSyncEntry *entry,
234 : : TransactionId xid);
235 : : static bool get_schema_sent_in_streamed_txn(RelationSyncEntry *entry,
236 : : TransactionId xid);
237 : : static void init_tuple_slot(PGOutputData *data, Relation relation,
238 : : RelationSyncEntry *entry);
239 : : static void pgoutput_memory_context_reset(void *arg);
240 : :
241 : : /* row filter routines */
242 : : static EState *create_estate_for_relation(Relation rel);
243 : : static void pgoutput_row_filter_init(PGOutputData *data,
244 : : List *publications,
245 : : RelationSyncEntry *entry);
246 : : static bool pgoutput_row_filter_exec_expr(ExprState *state,
247 : : ExprContext *econtext);
248 : : static bool pgoutput_row_filter(Relation relation, TupleTableSlot *old_slot,
249 : : TupleTableSlot **new_slot_ptr,
250 : : RelationSyncEntry *entry,
251 : : ReorderBufferChangeType *action);
252 : :
253 : : /* column list routines */
254 : : static void pgoutput_column_list_init(PGOutputData *data,
255 : : List *publications,
256 : : RelationSyncEntry *entry);
257 : :
258 : : /*
259 : : * Specify output plugin callbacks
260 : : */
261 : : void
3600 peter_e@gmx.net 262 : 887 : _PG_output_plugin_init(OutputPluginCallbacks *cb)
263 : : {
264 : 887 : cb->startup_cb = pgoutput_startup;
265 : 887 : cb->begin_cb = pgoutput_begin_txn;
266 : 887 : cb->change_cb = pgoutput_change;
3157 267 : 887 : cb->truncate_cb = pgoutput_truncate;
2062 akapila@postgresql.o 268 : 887 : cb->message_cb = pgoutput_message;
3600 peter_e@gmx.net 269 : 887 : cb->commit_cb = pgoutput_commit_txn;
270 : :
1963 akapila@postgresql.o 271 : 887 : cb->begin_prepare_cb = pgoutput_begin_prepare_txn;
272 : 887 : cb->prepare_cb = pgoutput_prepare_txn;
273 : 887 : cb->commit_prepared_cb = pgoutput_commit_prepared_txn;
274 : 887 : cb->rollback_prepared_cb = pgoutput_rollback_prepared_txn;
3600 peter_e@gmx.net 275 : 887 : cb->filter_by_origin_cb = pgoutput_origin_filter;
276 : 887 : cb->shutdown_cb = pgoutput_shutdown;
277 : :
278 : : /* transaction streaming */
2277 akapila@postgresql.o 279 : 887 : cb->stream_start_cb = pgoutput_stream_start;
280 : 887 : cb->stream_stop_cb = pgoutput_stream_stop;
281 : 887 : cb->stream_abort_cb = pgoutput_stream_abort;
282 : 887 : cb->stream_commit_cb = pgoutput_stream_commit;
283 : 887 : cb->stream_change_cb = pgoutput_change;
2062 284 : 887 : cb->stream_message_cb = pgoutput_message;
2277 285 : 887 : cb->stream_truncate_cb = pgoutput_truncate;
286 : : /* transaction streaming - two-phase commit */
1942 287 : 887 : cb->stream_prepare_cb = pgoutput_stream_prepare_txn;
3600 peter_e@gmx.net 288 : 887 : }
289 : :
290 : : static void
2062 akapila@postgresql.o 291 : 508 : parse_output_parameters(List *options, PGOutputData *data)
292 : : {
293 : : ListCell *lc;
3600 peter_e@gmx.net 294 : 508 : bool protocol_version_given = false;
295 : 508 : bool publication_names_given = false;
2324 tgl@sss.pgh.pa.us 296 : 508 : bool binary_option_given = false;
2062 akapila@postgresql.o 297 : 508 : bool messages_option_given = false;
2277 298 : 508 : bool streaming_given = false;
1963 299 : 508 : bool two_phase_option_given = false;
1591 300 : 508 : bool origin_option_given = false;
301 : :
302 : : /* Initialize optional parameters to defaults */
2062 303 : 508 : data->binary = false;
1419 304 : 508 : data->streaming = LOGICALREP_STREAM_OFF;
2062 305 : 508 : data->messages = false;
1963 306 : 508 : data->two_phase = false;
500 fujii@postgresql.org 307 : 508 : data->publish_no_origin = false;
308 : :
3600 peter_e@gmx.net 309 [ + - + + : 2514 : foreach(lc, options)
+ + ]
310 : : {
311 : 2009 : DefElem *defel = (DefElem *) lfirst(lc);
312 : :
313 [ + + - + ]: 2009 : Assert(defel->arg == NULL || IsA(defel->arg, String));
314 : :
315 : : /* Check each param, whether or not we recognize it */
316 [ + + ]: 2009 : if (strcmp(defel->defname, "proto_version") == 0)
317 : : {
318 : : unsigned long parsed;
319 : : char *endptr;
26 michael@paquier.xyz 320 : 508 : const char *val = defGetString(defel);
321 : :
3600 peter_e@gmx.net 322 [ - + ]: 507 : if (protocol_version_given)
3600 peter_e@gmx.net 323 [ # # ]:UBC 0 : ereport(ERROR,
324 : : (errcode(ERRCODE_SYNTAX_ERROR),
325 : : errmsg("conflicting or redundant options")));
3600 peter_e@gmx.net 326 :CBC 507 : protocol_version_given = true;
327 : :
1748 peter@eisentraut.org 328 : 507 : errno = 0;
114 michael@paquier.xyz 329 : 507 : parsed = strtoul(val, &endptr, 10);
330 [ + + + - : 507 : if (endptr == val || errno != 0 || *endptr != '\0')
- + ]
3600 peter_e@gmx.net 331 [ + - ]:GBC 1 : ereport(ERROR,
332 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
333 : : errmsg("invalid proto_version")));
334 : :
1748 peter@eisentraut.org 335 [ - + ]:CBC 506 : if (parsed > PG_UINT32_MAX)
3600 peter_e@gmx.net 336 [ # # ]:UBC 0 : ereport(ERROR,
337 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
338 : : errmsg("proto_version \"%s\" out of range", val)));
339 : :
2062 akapila@postgresql.o 340 :CBC 506 : data->protocol_version = (uint32) parsed;
341 : : }
3600 peter_e@gmx.net 342 [ + + ]: 1501 : else if (strcmp(defel->defname, "publication_names") == 0)
343 : : {
344 [ - + ]: 506 : if (publication_names_given)
3600 peter_e@gmx.net 345 [ # # ]:UBC 0 : ereport(ERROR,
346 : : (errcode(ERRCODE_SYNTAX_ERROR),
347 : : errmsg("conflicting or redundant options")));
3600 peter_e@gmx.net 348 :CBC 506 : publication_names_given = true;
349 : :
350 : : /*
351 : : * Pass a copy of the DefElem->arg since SplitIdentifierString
352 : : * modifies its input.
353 : : */
26 michael@paquier.xyz 354 [ - + ]: 506 : if (!SplitIdentifierString(pstrdup(defGetString(defel)), ',',
355 : : &data->publication_names))
3482 bruce@momjian.us 356 [ # # ]:UBC 0 : ereport(ERROR,
357 : : (errcode(ERRCODE_INVALID_NAME),
358 : : errmsg("invalid publication_names syntax")));
359 : : }
2324 tgl@sss.pgh.pa.us 360 [ + + ]:CBC 995 : else if (strcmp(defel->defname, "binary") == 0)
361 : : {
362 [ - + ]: 10 : if (binary_option_given)
2324 tgl@sss.pgh.pa.us 363 [ # # ]:UBC 0 : ereport(ERROR,
364 : : (errcode(ERRCODE_SYNTAX_ERROR),
365 : : errmsg("conflicting or redundant options")));
2324 tgl@sss.pgh.pa.us 366 :CBC 10 : binary_option_given = true;
367 : :
2062 akapila@postgresql.o 368 : 10 : data->binary = defGetBoolean(defel);
369 : : }
370 [ + + ]: 985 : else if (strcmp(defel->defname, "messages") == 0)
371 : : {
372 [ - + ]: 5 : if (messages_option_given)
2062 akapila@postgresql.o 373 [ # # ]:UBC 0 : ereport(ERROR,
374 : : (errcode(ERRCODE_SYNTAX_ERROR),
375 : : errmsg("conflicting or redundant options")));
2062 akapila@postgresql.o 376 :CBC 5 : messages_option_given = true;
377 : :
378 : 5 : data->messages = defGetBoolean(defel);
379 : : }
2277 380 [ + + ]: 980 : else if (strcmp(defel->defname, "streaming") == 0)
381 : : {
382 [ - + ]: 482 : if (streaming_given)
2277 akapila@postgresql.o 383 [ # # ]:UBC 0 : ereport(ERROR,
384 : : (errcode(ERRCODE_SYNTAX_ERROR),
385 : : errmsg("conflicting or redundant options")));
2277 akapila@postgresql.o 386 :CBC 482 : streaming_given = true;
387 : :
1419 388 : 482 : data->streaming = defGetStreamingMode(defel);
389 : : }
1963 390 [ + + ]: 498 : else if (strcmp(defel->defname, "two_phase") == 0)
391 : : {
392 [ - + ]: 8 : if (two_phase_option_given)
1963 akapila@postgresql.o 393 [ # # ]:UBC 0 : ereport(ERROR,
394 : : (errcode(ERRCODE_SYNTAX_ERROR),
395 : : errmsg("conflicting or redundant options")));
1963 akapila@postgresql.o 396 :CBC 8 : two_phase_option_given = true;
397 : :
398 : 8 : data->two_phase = defGetBoolean(defel);
399 : : }
1591 400 [ + - ]: 490 : else if (strcmp(defel->defname, "origin") == 0)
401 : : {
402 : : char *origin;
403 : :
404 [ - + ]: 490 : if (origin_option_given)
1591 akapila@postgresql.o 405 [ # # ]:UBC 0 : ereport(ERROR,
406 : : errcode(ERRCODE_SYNTAX_ERROR),
407 : : errmsg("conflicting or redundant options"));
1591 akapila@postgresql.o 408 :CBC 490 : origin_option_given = true;
409 : :
1158 410 : 490 : origin = defGetString(defel);
411 [ + + ]: 490 : if (pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) == 0)
412 : 33 : data->publish_no_origin = true;
413 [ + - ]: 457 : else if (pg_strcasecmp(origin, LOGICALREP_ORIGIN_ANY) == 0)
414 : 457 : data->publish_no_origin = false;
415 : : else
1591 akapila@postgresql.o 416 [ # # ]:UBC 0 : ereport(ERROR,
417 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
418 : : errmsg("unrecognized origin value: \"%s\"", origin));
419 : : }
420 : : else
3600 peter_e@gmx.net 421 [ # # ]: 0 : elog(ERROR, "unrecognized pgoutput option: %s", defel->defname);
422 : : }
423 : :
424 : : /* Check required options */
1075 akapila@postgresql.o 425 [ - + ]:CBC 505 : if (!protocol_version_given)
1075 akapila@postgresql.o 426 [ # # ]:UBC 0 : ereport(ERROR,
427 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
428 : : errmsg("option \"%s\" missing", "proto_version"));
1075 akapila@postgresql.o 429 [ - + ]:CBC 505 : if (!publication_names_given)
1075 akapila@postgresql.o 430 [ # # ]:UBC 0 : ereport(ERROR,
431 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
432 : : errmsg("option \"%s\" missing", "publication_names"));
3600 peter_e@gmx.net 433 :CBC 505 : }
434 : :
435 : : /*
436 : : * Memory context reset callback of PGOutputData->context.
437 : : */
438 : : static void
415 msawada@postgresql.o 439 : 1206 : pgoutput_memory_context_reset(void *arg)
440 : : {
441 [ + + ]: 1206 : if (RelationSyncCache)
442 : : {
443 : 224 : hash_destroy(RelationSyncCache);
444 : 224 : RelationSyncCache = NULL;
445 : : }
446 : 1206 : }
447 : :
448 : : /*
449 : : * Initialize this plugin
450 : : */
451 : : static void
3482 bruce@momjian.us 452 : 887 : pgoutput_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt,
453 : : bool is_init)
454 : : {
353 michael@paquier.xyz 455 : 887 : PGOutputData *data = palloc0_object(PGOutputData);
456 : : static bool publication_callback_registered = false;
457 : : MemoryContextCallback *mcallback;
458 : :
459 : : /* Create our memory context for private allocations. */
3600 peter_e@gmx.net 460 : 887 : data->context = AllocSetContextCreate(ctx->context,
461 : : "logical replication output context",
462 : : ALLOCSET_DEFAULT_SIZES);
463 : :
1740 akapila@postgresql.o 464 : 887 : data->cachectx = AllocSetContextCreate(ctx->context,
465 : : "logical replication cache context",
466 : : ALLOCSET_DEFAULT_SIZES);
467 : :
719 michael@paquier.xyz 468 : 887 : data->pubctx = AllocSetContextCreate(ctx->context,
469 : : "logical replication publication list context",
470 : : ALLOCSET_SMALL_SIZES);
471 : :
472 : : /*
473 : : * Ensure to cleanup RelationSyncCache even when logical decoding invoked
474 : : * via SQL interface ends up with an error.
475 : : */
353 476 : 887 : mcallback = palloc0_object(MemoryContextCallback);
415 msawada@postgresql.o 477 : 887 : mcallback->func = pgoutput_memory_context_reset;
478 : 887 : MemoryContextRegisterResetCallback(ctx->context, mcallback);
479 : :
3600 peter_e@gmx.net 480 : 887 : ctx->output_plugin_private = data;
481 : :
482 : : /* This plugin uses binary protocol. */
483 : 887 : opt->output_type = OUTPUT_PLUGIN_BINARY_OUTPUT;
484 : :
485 : : /*
486 : : * This is replication start and not slot initialization.
487 : : *
488 : : * Parse and validate options passed by the client.
489 : : */
490 [ + + ]: 887 : if (!is_init)
491 : : {
492 : : /* Parse the params and ERROR if we see any we don't recognize */
2062 akapila@postgresql.o 493 : 508 : parse_output_parameters(ctx->output_plugin_options, data);
494 : :
495 : : /* Check if we support requested protocol */
2254 496 [ - + ]: 505 : if (data->protocol_version > LOGICALREP_PROTO_MAX_VERSION_NUM)
3600 peter_e@gmx.net 497 [ # # ]:UBC 0 : ereport(ERROR,
498 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
499 : : errmsg("client sent proto_version=%d but server only supports protocol %d or lower",
500 : : data->protocol_version, LOGICALREP_PROTO_MAX_VERSION_NUM)));
501 : :
3600 peter_e@gmx.net 502 [ - + ]:CBC 505 : if (data->protocol_version < LOGICALREP_PROTO_MIN_VERSION_NUM)
3600 peter_e@gmx.net 503 [ # # ]:UBC 0 : ereport(ERROR,
504 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
505 : : errmsg("client sent proto_version=%d but server only supports protocol %d or higher",
506 : : data->protocol_version, LOGICALREP_PROTO_MIN_VERSION_NUM)));
507 : :
508 : : /*
509 : : * Decide whether to enable streaming. It is disabled by default, in
510 : : * which case we just update the flag in decoding context. Otherwise
511 : : * we only allow it with sufficient version of the protocol, and when
512 : : * the output plugin supports it.
513 : : */
1419 akapila@postgresql.o 514 [ + + ]:CBC 505 : if (data->streaming == LOGICALREP_STREAM_OFF)
2277 515 : 23 : ctx->streaming = false;
1419 516 [ + + ]: 482 : else if (data->streaming == LOGICALREP_STREAM_ON &&
517 [ - + ]: 27 : data->protocol_version < LOGICALREP_PROTO_STREAM_VERSION_NUM)
2277 akapila@postgresql.o 518 [ # # ]:UBC 0 : ereport(ERROR,
519 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
520 : : errmsg("requested proto_version=%d does not support streaming, need %d or higher",
521 : : data->protocol_version, LOGICALREP_PROTO_STREAM_VERSION_NUM)));
1419 akapila@postgresql.o 522 [ + + ]:CBC 482 : else if (data->streaming == LOGICALREP_STREAM_PARALLEL &&
523 [ - + ]: 455 : data->protocol_version < LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM)
1419 akapila@postgresql.o 524 [ # # ]:UBC 0 : ereport(ERROR,
525 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
526 : : errmsg("requested proto_version=%d does not support parallel streaming, need %d or higher",
527 : : data->protocol_version, LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM)));
2277 akapila@postgresql.o 528 [ - + ]:CBC 482 : else if (!ctx->streaming)
2277 akapila@postgresql.o 529 [ # # ]:UBC 0 : ereport(ERROR,
530 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
531 : : errmsg("streaming requested, but not supported by output plugin")));
532 : :
533 : : /*
534 : : * Here, we just check whether the two-phase option is passed by
535 : : * plugin and decide whether to enable it at later point of time. It
536 : : * remains enabled if the previous start-up has done so. But we only
537 : : * allow the option to be passed in with sufficient version of the
538 : : * protocol, and when the output plugin supports it.
539 : : */
1963 akapila@postgresql.o 540 [ + + ]:CBC 505 : if (!data->two_phase)
541 : 497 : ctx->twophase_opt_given = false;
542 [ - + ]: 8 : else if (data->protocol_version < LOGICALREP_PROTO_TWOPHASE_VERSION_NUM)
1963 akapila@postgresql.o 543 [ # # ]:UBC 0 : ereport(ERROR,
544 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
545 : : errmsg("requested proto_version=%d does not support two-phase commit, need %d or higher",
546 : : data->protocol_version, LOGICALREP_PROTO_TWOPHASE_VERSION_NUM)));
1963 akapila@postgresql.o 547 [ - + ]:CBC 8 : else if (!ctx->twophase)
1963 akapila@postgresql.o 548 [ # # ]:UBC 0 : ereport(ERROR,
549 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
550 : : errmsg("two-phase commit requested, but not supported by output plugin")));
551 : : else
1963 akapila@postgresql.o 552 :CBC 8 : ctx->twophase_opt_given = true;
553 : :
554 : : /* Init publication state. */
3600 peter_e@gmx.net 555 : 505 : data->publications = NIL;
556 : 505 : publications_valid = false;
557 : :
558 : : /*
559 : : * Register callback for pg_publication if we didn't already do that
560 : : * during some previous call in this process.
561 : : */
1374 tgl@sss.pgh.pa.us 562 [ + + ]: 505 : if (!publication_callback_registered)
563 : : {
564 : 503 : CacheRegisterSyscacheCallback(PUBLICATIONOID,
565 : : publication_invalidation_cb,
566 : : (Datum) 0);
625 akapila@postgresql.o 567 : 503 : CacheRegisterRelSyncCallback(rel_sync_cache_relation_cb,
568 : : (Datum) 0);
1374 tgl@sss.pgh.pa.us 569 : 503 : publication_callback_registered = true;
570 : : }
571 : :
572 : : /* Initialize relation schema cache. */
3600 peter_e@gmx.net 573 : 505 : init_rel_sync_cache(CacheMemoryContext);
574 : : }
575 : : else
576 : : {
577 : : /*
578 : : * Disable the streaming and prepared transactions during the slot
579 : : * initialization mode.
580 : : */
2277 akapila@postgresql.o 581 : 379 : ctx->streaming = false;
1963 582 : 379 : ctx->twophase = false;
583 : : }
3600 peter_e@gmx.net 584 : 884 : }
585 : :
586 : : /*
587 : : * BEGIN callback.
588 : : *
589 : : * Don't send the BEGIN message here instead postpone it until the first
590 : : * change. In logical replication, a common scenario is to replicate a set of
591 : : * tables (instead of all tables) and transactions whose changes were on
592 : : * the table(s) that are not published will produce empty transactions. These
593 : : * empty transactions will send BEGIN and COMMIT messages to subscribers,
594 : : * using bandwidth on something with little/no use for logical replication.
595 : : */
596 : : static void
1661 tgl@sss.pgh.pa.us 597 : 2019 : pgoutput_begin_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
598 : : {
599 : 2019 : PGOutputTxnData *txndata = MemoryContextAllocZero(ctx->context,
600 : : sizeof(PGOutputTxnData));
601 : :
1704 akapila@postgresql.o 602 : 2019 : txn->output_plugin_private = txndata;
603 : 2019 : }
604 : :
605 : : /*
606 : : * Send BEGIN.
607 : : *
608 : : * This is called while processing the first change of the transaction.
609 : : */
610 : : static void
611 : 526 : pgoutput_send_begin(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
612 : : {
304 msawada@postgresql.o 613 : 526 : bool send_replication_origin = txn->origin_id != InvalidReplOriginId;
1704 akapila@postgresql.o 614 : 526 : PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private;
615 : :
616 [ - + ]: 526 : Assert(txndata);
617 [ - + ]: 526 : Assert(!txndata->sent_begin_txn);
618 : :
3600 peter_e@gmx.net 619 : 526 : OutputPluginPrepareWrite(ctx, !send_replication_origin);
620 : 526 : logicalrep_write_begin(ctx->out, txn);
1704 akapila@postgresql.o 621 : 526 : txndata->sent_begin_txn = true;
622 : :
1963 623 : 526 : send_repl_origin(ctx, txn->origin_id, txn->origin_lsn,
624 : : send_replication_origin);
625 : :
3600 peter_e@gmx.net 626 : 526 : OutputPluginWrite(ctx, true);
627 : 526 : }
628 : :
629 : : /*
630 : : * COMMIT callback
631 : : */
632 : : static void
633 : 2014 : pgoutput_commit_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
634 : : XLogRecPtr commit_lsn)
635 : : {
1704 akapila@postgresql.o 636 : 2014 : PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private;
637 : : bool sent_begin_txn;
638 : :
639 [ - + ]: 2014 : Assert(txndata);
640 : :
641 : : /*
642 : : * We don't need to send the commit message unless some relevant change
643 : : * from this transaction has been sent to the downstream.
644 : : */
645 : 2014 : sent_begin_txn = txndata->sent_begin_txn;
1389 646 : 2014 : OutputPluginUpdateProgress(ctx, !sent_begin_txn);
1704 647 : 2014 : pfree(txndata);
648 : 2014 : txn->output_plugin_private = NULL;
649 : :
650 [ + + ]: 2014 : if (!sent_begin_txn)
651 : : {
652 [ + + ]: 1491 : elog(DEBUG1, "skipped replication of an empty transaction with XID: %u", txn->xid);
653 : 1491 : return;
654 : : }
655 : :
3600 peter_e@gmx.net 656 : 523 : OutputPluginPrepareWrite(ctx, true);
657 : 523 : logicalrep_write_commit(ctx->out, txn, commit_lsn);
658 : 523 : OutputPluginWrite(ctx, true);
659 : : }
660 : :
661 : : /*
662 : : * BEGIN PREPARE callback
663 : : */
664 : : static void
1963 akapila@postgresql.o 665 : 21 : pgoutput_begin_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
666 : : {
304 msawada@postgresql.o 667 : 21 : bool send_replication_origin = txn->origin_id != InvalidReplOriginId;
668 : :
1963 akapila@postgresql.o 669 : 21 : OutputPluginPrepareWrite(ctx, !send_replication_origin);
670 : 21 : logicalrep_write_begin_prepare(ctx->out, txn);
671 : :
672 : 21 : send_repl_origin(ctx, txn->origin_id, txn->origin_lsn,
673 : : send_replication_origin);
674 : :
675 : 21 : OutputPluginWrite(ctx, true);
676 : 21 : }
677 : :
678 : : /*
679 : : * PREPARE callback
680 : : */
681 : : static void
682 : 21 : pgoutput_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
683 : : XLogRecPtr prepare_lsn)
684 : : {
1389 685 : 21 : OutputPluginUpdateProgress(ctx, false);
686 : :
1963 687 : 21 : OutputPluginPrepareWrite(ctx, true);
688 : 21 : logicalrep_write_prepare(ctx->out, txn, prepare_lsn);
689 : 21 : OutputPluginWrite(ctx, true);
690 : 21 : }
691 : :
692 : : /*
693 : : * COMMIT PREPARED callback
694 : : */
695 : : static void
696 : 26 : pgoutput_commit_prepared_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
697 : : XLogRecPtr commit_lsn)
698 : : {
1389 699 : 26 : OutputPluginUpdateProgress(ctx, false);
700 : :
1963 701 : 26 : OutputPluginPrepareWrite(ctx, true);
702 : 26 : logicalrep_write_commit_prepared(ctx->out, txn, commit_lsn);
703 : 26 : OutputPluginWrite(ctx, true);
704 : 26 : }
705 : :
706 : : /*
707 : : * ROLLBACK PREPARED callback
708 : : */
709 : : static void
710 : 6 : pgoutput_rollback_prepared_txn(LogicalDecodingContext *ctx,
711 : : ReorderBufferTXN *txn,
712 : : XLogRecPtr prepare_end_lsn,
713 : : TimestampTz prepare_time)
714 : : {
1389 715 : 6 : OutputPluginUpdateProgress(ctx, false);
716 : :
1963 717 : 6 : OutputPluginPrepareWrite(ctx, true);
718 : 6 : logicalrep_write_rollback_prepared(ctx->out, txn, prepare_end_lsn,
719 : : prepare_time);
720 : 6 : OutputPluginWrite(ctx, true);
721 : 6 : }
722 : :
723 : : /*
724 : : * Write the current schema of the relation and its ancestor (if any) if not
725 : : * done yet.
726 : : */
727 : : static void
3157 peter_e@gmx.net 728 : 202725 : maybe_send_schema(LogicalDecodingContext *ctx,
729 : : ReorderBufferChange *change,
730 : : Relation relation, RelationSyncEntry *relentry)
731 : : {
1157 michael@paquier.xyz 732 : 202725 : PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
733 : : bool schema_sent;
2277 akapila@postgresql.o 734 : 202725 : TransactionId xid = InvalidTransactionId;
735 : 202725 : TransactionId topxid = InvalidTransactionId;
736 : :
737 : : /*
738 : : * Remember XID of the (sub)transaction for the change. We don't care if
739 : : * it's top-level transaction or not (we have already sent that XID in
740 : : * start of the current streaming block).
741 : : *
742 : : * If we're not in a streaming block, just use InvalidTransactionId and
743 : : * the write methods will not include it.
744 : : */
1157 michael@paquier.xyz 745 [ + + ]: 202725 : if (data->in_streaming)
2277 akapila@postgresql.o 746 : 175809 : xid = change->txn->xid;
747 : :
1352 748 [ + + ]: 202725 : if (rbtxn_is_subtxn(change->txn))
749 [ + - ]: 10107 : topxid = rbtxn_get_toptxn(change->txn)->xid;
750 : : else
2277 751 : 192618 : topxid = xid;
752 : :
753 : : /*
754 : : * Do we need to send the schema? We do track streamed transactions
755 : : * separately, because those may be applied later (and the regular
756 : : * transactions won't see their effects until then) and in an order that
757 : : * we don't know at this point.
758 : : *
759 : : * XXX There is a scope of optimization here. Currently, we always send
760 : : * the schema first time in a streaming transaction but we can probably
761 : : * avoid that by checking 'relentry->schema_sent' flag. However, before
762 : : * doing that we need to study its impact on the case where we have a mix
763 : : * of streaming and non-streaming transactions.
764 : : */
1157 michael@paquier.xyz 765 [ + + ]: 202725 : if (data->in_streaming)
2277 akapila@postgresql.o 766 : 175809 : schema_sent = get_schema_sent_in_streamed_txn(relentry, topxid);
767 : : else
768 : 26916 : schema_sent = relentry->schema_sent;
769 : :
770 : : /* Nothing to do if we already sent the schema. */
771 [ + + ]: 202725 : if (schema_sent)
2425 peter@eisentraut.org 772 : 202320 : return;
773 : :
774 : : /*
775 : : * Send the schema. If the changes will be published using an ancestor's
776 : : * schema, not the relation's own, send that ancestor's schema before
777 : : * sending relation's own (XXX - maybe sending only the former suffices?).
778 : : */
779 [ + + ]: 405 : if (relentry->publish_as_relid != RelationGetRelid(relation))
780 : : {
781 : 34 : Relation ancestor = RelationIdGetRelation(relentry->publish_as_relid);
782 : :
751 akapila@postgresql.o 783 : 34 : send_relation_and_attrs(ancestor, xid, ctx, relentry);
2425 peter@eisentraut.org 784 : 34 : RelationClose(ancestor);
785 : : }
786 : :
751 akapila@postgresql.o 787 : 405 : send_relation_and_attrs(relation, xid, ctx, relentry);
788 : :
1157 michael@paquier.xyz 789 [ + + ]: 405 : if (data->in_streaming)
2277 akapila@postgresql.o 790 : 67 : set_schema_sent_in_streamed_txn(relentry, topxid);
791 : : else
792 : 338 : relentry->schema_sent = true;
793 : : }
794 : :
795 : : /*
796 : : * Sends a relation
797 : : */
798 : : static void
799 : 439 : send_relation_and_attrs(Relation relation, TransactionId xid,
800 : : LogicalDecodingContext *ctx,
801 : : RelationSyncEntry *relentry)
802 : : {
2425 peter@eisentraut.org 803 : 439 : TupleDesc desc = RelationGetDescr(relation);
751 akapila@postgresql.o 804 : 439 : Bitmapset *columns = relentry->columns;
674 805 : 439 : PublishGencolsType include_gencols_type = relentry->include_gencols_type;
806 : : int i;
807 : :
808 : : /*
809 : : * Write out type info if needed. We do that only for user-created types.
810 : : * We use FirstGenbkiObjectId as the cutoff, so that we only consider
811 : : * objects with hand-assigned OIDs to be "built in", not for instance any
812 : : * function or type defined in the information_schema. This is important
813 : : * because only hand-assigned OIDs can be expected to remain stable across
814 : : * major versions.
815 : : */
2425 peter@eisentraut.org 816 [ + + ]: 1363 : for (i = 0; i < desc->natts; i++)
817 : : {
818 : 924 : Form_pg_attribute att = TupleDescAttr(desc, i);
819 : :
674 akapila@postgresql.o 820 [ + + ]: 924 : if (!logicalrep_should_publish_column(att, columns,
821 : : include_gencols_type))
2425 peter@eisentraut.org 822 : 71 : continue;
823 : :
824 [ + + ]: 853 : if (att->atttypid < FirstGenbkiObjectId)
825 : 834 : continue;
826 : :
3157 peter_e@gmx.net 827 : 19 : OutputPluginPrepareWrite(ctx, false);
2277 akapila@postgresql.o 828 : 19 : logicalrep_write_typ(ctx->out, xid, att->atttypid);
3157 peter_e@gmx.net 829 : 19 : OutputPluginWrite(ctx, false);
830 : : }
831 : :
2425 peter@eisentraut.org 832 : 439 : OutputPluginPrepareWrite(ctx, false);
674 akapila@postgresql.o 833 : 439 : logicalrep_write_rel(ctx->out, xid, relation, columns,
834 : : include_gencols_type);
2425 peter@eisentraut.org 835 : 439 : OutputPluginWrite(ctx, false);
3157 peter_e@gmx.net 836 : 439 : }
837 : :
838 : : /*
839 : : * Executor state preparation for evaluation of row filter expressions for the
840 : : * specified relation.
841 : : */
842 : : static EState *
1740 akapila@postgresql.o 843 : 18 : create_estate_for_relation(Relation rel)
844 : : {
845 : : EState *estate;
846 : : RangeTblEntry *rte;
1363 tgl@sss.pgh.pa.us 847 : 18 : List *perminfos = NIL;
848 : :
1740 akapila@postgresql.o 849 : 18 : estate = CreateExecutorState();
850 : :
851 : 18 : rte = makeNode(RangeTblEntry);
852 : 18 : rte->rtekind = RTE_RELATION;
853 : 18 : rte->relid = RelationGetRelid(rel);
854 : 18 : rte->relkind = rel->rd_rel->relkind;
855 : 18 : rte->rellockmode = AccessShareLock;
856 : :
1363 tgl@sss.pgh.pa.us 857 : 18 : addRTEPermissionInfo(&perminfos, rte);
858 : :
659 amitlan@postgresql.o 859 : 18 : ExecInitRangeTable(estate, list_make1(rte), perminfos,
860 : : bms_make_singleton(1));
861 : :
1740 akapila@postgresql.o 862 : 18 : estate->es_output_cid = GetCurrentCommandId(false);
863 : :
864 : 18 : return estate;
865 : : }
866 : :
867 : : /*
868 : : * Evaluates row filter.
869 : : *
870 : : * If the row filter evaluates to NULL, it is taken as false i.e. the change
871 : : * isn't replicated.
872 : : */
873 : : static bool
874 : 39 : pgoutput_row_filter_exec_expr(ExprState *state, ExprContext *econtext)
875 : : {
876 : : Datum ret;
877 : : bool isnull;
878 : :
879 [ - + ]: 39 : Assert(state != NULL);
880 : :
881 : 39 : ret = ExecEvalExprSwitchContext(state, econtext, &isnull);
882 : :
883 [ - + - - : 38 : elog(DEBUG3, "row filter evaluates to %s (isnull: %s)",
- - - - ]
884 : : isnull ? "false" : DatumGetBool(ret) ? "true" : "false",
885 : : isnull ? "true" : "false");
886 : :
887 [ + + ]: 38 : if (isnull)
888 : 1 : return false;
889 : :
890 : 37 : return DatumGetBool(ret);
891 : : }
892 : :
893 : : /*
894 : : * Make sure the per-entry memory context exists.
895 : : */
896 : : static void
1708 tomas.vondra@postgre 897 : 392 : pgoutput_ensure_entry_cxt(PGOutputData *data, RelationSyncEntry *entry)
898 : : {
899 : : Relation relation;
900 : :
901 : : /* The context may already exist, in which case bail out. */
902 [ + + ]: 392 : if (entry->entry_cxt)
903 : 18 : return;
904 : :
905 : 374 : relation = RelationIdGetRelation(entry->publish_as_relid);
906 : :
907 : 374 : entry->entry_cxt = AllocSetContextCreate(data->cachectx,
908 : : "entry private context",
909 : : ALLOCSET_SMALL_SIZES);
910 : :
911 : 374 : MemoryContextCopyAndSetIdentifier(entry->entry_cxt,
912 : : RelationGetRelationName(relation));
913 : : }
914 : :
915 : : /*
916 : : * Initialize the row filter.
917 : : */
918 : : static void
1740 akapila@postgresql.o 919 : 374 : pgoutput_row_filter_init(PGOutputData *data, List *publications,
920 : : RelationSyncEntry *entry)
921 : : {
922 : : ListCell *lc;
923 : 374 : List *rfnodes[] = {NIL, NIL, NIL}; /* One per pubaction */
924 : 374 : bool no_filter[] = {false, false, false}; /* One per pubaction */
925 : : MemoryContext oldctx;
926 : : int idx;
927 : 374 : bool has_filter = true;
1527 928 : 374 : Oid schemaid = get_rel_namespace(entry->publish_as_relid);
929 : :
930 : : /*
931 : : * Find if there are any row filters for this relation. If there are, then
932 : : * prepare the necessary ExprState and cache it in entry->exprstate. To
933 : : * build an expression state, we need to ensure the following:
934 : : *
935 : : * All the given publication-table mappings must be checked.
936 : : *
937 : : * Multiple publications might have multiple row filters for this
938 : : * relation. Since row filter usage depends on the DML operation, there
939 : : * are multiple lists (one for each operation) to which row filters will
940 : : * be appended.
941 : : *
942 : : * FOR ALL TABLES and FOR TABLES IN SCHEMA implies "don't use row filter
943 : : * expression" so it takes precedence.
944 : : */
1740 945 [ + - + + : 396 : foreach(lc, publications)
+ + ]
946 : : {
947 : 378 : Publication *pub = lfirst(lc);
948 : 378 : HeapTuple rftuple = NULL;
949 : 378 : Datum rfdatum = 0;
1527 950 : 378 : bool pub_no_filter = true;
951 : :
952 : : /*
953 : : * If the publication is FOR ALL TABLES, or the publication includes a
954 : : * FOR TABLES IN SCHEMA where the table belongs to the referred
955 : : * schema, then it is treated the same as if there are no row filters
956 : : * (even if other publications have a row filter).
957 : : */
958 [ + + ]: 378 : if (!pub->alltables &&
959 [ + + ]: 288 : !SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP,
960 : : ObjectIdGetDatum(schemaid),
961 : : ObjectIdGetDatum(pub->oid)))
962 : : {
963 : : /*
964 : : * Check for the presence of a row filter in this publication.
965 : : */
1740 966 : 281 : rftuple = SearchSysCache2(PUBLICATIONRELMAP,
967 : : ObjectIdGetDatum(entry->publish_as_relid),
968 : : ObjectIdGetDatum(pub->oid));
969 : :
970 [ + + ]: 281 : if (HeapTupleIsValid(rftuple))
971 : : {
972 : : /* Null indicates no filter. */
973 : 269 : rfdatum = SysCacheGetAttr(PUBLICATIONRELMAP, rftuple,
974 : : Anum_pg_publication_rel_prqual,
975 : : &pub_no_filter);
976 : : }
977 : : }
978 : :
979 [ + + ]: 378 : if (pub_no_filter)
980 : : {
981 [ + + ]: 363 : if (rftuple)
982 : 254 : ReleaseSysCache(rftuple);
983 : :
984 : 363 : no_filter[PUBACTION_INSERT] |= pub->pubactions.pubinsert;
985 : 363 : no_filter[PUBACTION_UPDATE] |= pub->pubactions.pubupdate;
986 : 363 : no_filter[PUBACTION_DELETE] |= pub->pubactions.pubdelete;
987 : :
988 : : /*
989 : : * Quick exit if all the DML actions are publicized via this
990 : : * publication.
991 : : */
992 [ + - ]: 363 : if (no_filter[PUBACTION_INSERT] &&
993 [ + + ]: 363 : no_filter[PUBACTION_UPDATE] &&
994 [ + - ]: 356 : no_filter[PUBACTION_DELETE])
995 : : {
996 : 356 : has_filter = false;
997 : 356 : break;
998 : : }
999 : :
1000 : : /* No additional work for this publication. Next one. */
1001 : 7 : continue;
1002 : : }
1003 : :
1004 : : /* Form the per pubaction row filter lists. */
1005 [ + - + - ]: 15 : if (pub->pubactions.pubinsert && !no_filter[PUBACTION_INSERT])
1006 : 15 : rfnodes[PUBACTION_INSERT] = lappend(rfnodes[PUBACTION_INSERT],
1007 : 15 : TextDatumGetCString(rfdatum));
1008 [ + - + - ]: 15 : if (pub->pubactions.pubupdate && !no_filter[PUBACTION_UPDATE])
1009 : 15 : rfnodes[PUBACTION_UPDATE] = lappend(rfnodes[PUBACTION_UPDATE],
1010 : 15 : TextDatumGetCString(rfdatum));
1011 [ + - + - ]: 15 : if (pub->pubactions.pubdelete && !no_filter[PUBACTION_DELETE])
1012 : 15 : rfnodes[PUBACTION_DELETE] = lappend(rfnodes[PUBACTION_DELETE],
1013 : 15 : TextDatumGetCString(rfdatum));
1014 : :
1015 : 15 : ReleaseSysCache(rftuple);
1016 : : } /* loop all subscribed publications */
1017 : :
1018 : : /* Clean the row filter */
1019 [ + + ]: 1496 : for (idx = 0; idx < NUM_ROWFILTER_PUBACTIONS; idx++)
1020 : : {
1021 [ + + ]: 1122 : if (no_filter[idx])
1022 : : {
1023 : 1077 : list_free_deep(rfnodes[idx]);
1024 : 1077 : rfnodes[idx] = NIL;
1025 : : }
1026 : : }
1027 : :
1028 [ + + ]: 374 : if (has_filter)
1029 : : {
1030 : 18 : Relation relation = RelationIdGetRelation(entry->publish_as_relid);
1031 : :
1708 tomas.vondra@postgre 1032 : 18 : pgoutput_ensure_entry_cxt(data, entry);
1033 : :
1034 : : /*
1035 : : * Now all the filters for all pubactions are known. Combine them when
1036 : : * their pubactions are the same.
1037 : : */
1038 : 18 : oldctx = MemoryContextSwitchTo(entry->entry_cxt);
1740 akapila@postgresql.o 1039 : 18 : entry->estate = create_estate_for_relation(relation);
1040 [ + + ]: 72 : for (idx = 0; idx < NUM_ROWFILTER_PUBACTIONS; idx++)
1041 : : {
1042 : 54 : List *filters = NIL;
1043 : : Expr *rfnode;
1044 : :
1045 [ + + ]: 54 : if (rfnodes[idx] == NIL)
1046 : 21 : continue;
1047 : :
1048 [ + - + + : 69 : foreach(lc, rfnodes[idx])
+ + ]
659 peter@eisentraut.org 1049 : 36 : filters = lappend(filters, expand_generated_columns_in_expr(stringToNode((char *) lfirst(lc)), relation, 1));
1050 : :
1051 : : /* combine the row filter and cache the ExprState */
1740 akapila@postgresql.o 1052 : 33 : rfnode = make_orclause(filters);
1053 : 33 : entry->exprstate[idx] = ExecPrepareExpr(rfnode, entry->estate);
1054 : : } /* for each pubaction */
1055 : 18 : MemoryContextSwitchTo(oldctx);
1056 : :
1057 : 18 : RelationClose(relation);
1058 : : }
1059 : 374 : }
1060 : :
1061 : : /*
1062 : : * If the table contains a generated column, check for any conflicting
1063 : : * values of 'publish_generated_columns' parameter in the publications.
1064 : : */
1065 : : static void
751 1066 : 374 : check_and_init_gencol(PGOutputData *data, List *publications,
1067 : : RelationSyncEntry *entry)
1068 : : {
1069 : 374 : Relation relation = RelationIdGetRelation(entry->publish_as_relid);
1070 : 374 : TupleDesc desc = RelationGetDescr(relation);
1071 : 374 : bool gencolpresent = false;
1072 : 374 : bool first = true;
1073 : :
1074 : : /* Check if there is any generated column present. */
1075 [ + + ]: 1152 : for (int i = 0; i < desc->natts; i++)
1076 : : {
402 drowley@postgresql.o 1077 : 785 : CompactAttribute *att = TupleDescCompactAttr(desc, i);
1078 : :
751 akapila@postgresql.o 1079 [ + + ]: 785 : if (att->attgenerated)
1080 : : {
1081 : 7 : gencolpresent = true;
1082 : 7 : break;
1083 : : }
1084 : : }
1085 : :
1086 : : /* There are no generated columns to be published. */
1087 [ + + ]: 374 : if (!gencolpresent)
1088 : : {
674 1089 : 367 : entry->include_gencols_type = PUBLISH_GENCOLS_NONE;
751 1090 : 367 : return;
1091 : : }
1092 : :
1093 : : /*
1094 : : * There may be a conflicting value for 'publish_generated_columns'
1095 : : * parameter in the publications.
1096 : : */
1097 [ + - + + : 22 : foreach_ptr(Publication, pub, publications)
+ + ]
1098 : : {
1099 : : /*
1100 : : * The column list takes precedence over the
1101 : : * 'publish_generated_columns' parameter. Those will be checked later,
1102 : : * see pgoutput_column_list_init.
1103 : : */
1104 [ + + ]: 8 : if (check_and_fetch_column_list(pub, entry->publish_as_relid, NULL, NULL))
1105 : 3 : continue;
1106 : :
1107 [ + - ]: 5 : if (first)
1108 : : {
674 1109 : 5 : entry->include_gencols_type = pub->pubgencols_type;
751 1110 : 5 : first = false;
1111 : : }
674 akapila@postgresql.o 1112 [ # # ]:UBC 0 : else if (entry->include_gencols_type != pub->pubgencols_type)
751 1113 [ # # ]: 0 : ereport(ERROR,
1114 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1115 : : errmsg("cannot use different values of publish_generated_columns for table \"%s.%s\" in different publications",
1116 : : get_namespace_name(RelationGetNamespace(relation)),
1117 : : RelationGetRelationName(relation)));
1118 : : }
1119 : : }
1120 : :
1121 : : /*
1122 : : * Initialize the column list.
1123 : : */
1124 : : static void
1708 tomas.vondra@postgre 1125 :CBC 374 : pgoutput_column_list_init(PGOutputData *data, List *publications,
1126 : : RelationSyncEntry *entry)
1127 : : {
1128 : : ListCell *lc;
1640 akapila@postgresql.o 1129 : 374 : bool first = true;
1130 : 374 : Relation relation = RelationIdGetRelation(entry->publish_as_relid);
751 1131 : 374 : bool found_pub_collist = false;
1132 : 374 : Bitmapset *relcols = NULL;
1133 : :
1134 : 374 : pgoutput_ensure_entry_cxt(data, entry);
1135 : :
1136 : : /*
1137 : : * Find if there are any column lists for this relation. If there are,
1138 : : * build a bitmap using the column lists.
1139 : : *
1140 : : * Multiple publications might have multiple column lists for this
1141 : : * relation.
1142 : : *
1143 : : * Note that we don't support the case where the column list is different
1144 : : * for the same table when combining publications. See comments atop
1145 : : * fetch_relation_list. But one can later change the publication so we
1146 : : * still need to check all the given publication-table mappings and report
1147 : : * an error if any publications have a different column list.
1148 : : */
1708 tomas.vondra@postgre 1149 [ + - + + : 758 : foreach(lc, publications)
+ + ]
1150 : : {
1151 : 385 : Publication *pub = lfirst(lc);
1640 akapila@postgresql.o 1152 : 385 : Bitmapset *cols = NULL;
1153 : :
1154 : : /* Retrieve the bitmap of columns for a column list publication. */
751 1155 : 385 : found_pub_collist |= check_and_fetch_column_list(pub,
1156 : : entry->publish_as_relid,
1157 : : entry->entry_cxt, &cols);
1158 : :
1159 : : /*
1160 : : * For non-column list publications — e.g. TABLE (without a column
1161 : : * list), ALL TABLES, or ALL TABLES IN SCHEMA, we consider all columns
1162 : : * of the table (including generated columns when
1163 : : * 'publish_generated_columns' parameter is true).
1164 : : */
1165 [ + + ]: 385 : if (!cols)
1166 : : {
1167 : : /*
1168 : : * Cache the table columns for the first publication with no
1169 : : * specified column list to detect publication with a different
1170 : : * column list.
1171 : : */
1172 [ + + + + ]: 346 : if (!relcols && (list_length(publications) > 1))
1173 : : {
1174 : 9 : MemoryContext oldcxt = MemoryContextSwitchTo(entry->entry_cxt);
1175 : :
674 1176 : 9 : relcols = pub_form_cols_map(relation,
1177 : : entry->include_gencols_type);
751 1178 : 9 : MemoryContextSwitchTo(oldcxt);
1179 : : }
1180 : :
1181 : 346 : cols = relcols;
1182 : : }
1183 : :
1640 1184 [ + + ]: 385 : if (first)
1185 : : {
1186 : 374 : entry->columns = cols;
1187 : 374 : first = false;
1188 : : }
1189 [ + + ]: 11 : else if (!bms_equal(entry->columns, cols))
1190 [ + - ]: 1 : ereport(ERROR,
1191 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1192 : : errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
1193 : : get_namespace_name(RelationGetNamespace(relation)),
1194 : : RelationGetRelationName(relation)));
1195 : : } /* loop all subscribed publications */
1196 : :
1197 : : /*
1198 : : * If no column list publications exist, columns to be published will be
1199 : : * computed later according to the 'publish_generated_columns' parameter.
1200 : : */
751 1201 [ + + ]: 373 : if (!found_pub_collist)
1202 : 337 : entry->columns = NULL;
1203 : :
1640 1204 : 373 : RelationClose(relation);
1708 tomas.vondra@postgre 1205 : 373 : }
1206 : :
1207 : : /*
1208 : : * Initialize the slot for storing new and old tuples, and build the map that
1209 : : * will be used to convert the relation's tuples into the ancestor's format.
1210 : : */
1211 : : static void
1740 akapila@postgresql.o 1212 : 374 : init_tuple_slot(PGOutputData *data, Relation relation,
1213 : : RelationSyncEntry *entry)
1214 : : {
1215 : : MemoryContext oldctx;
1216 : : TupleDesc oldtupdesc;
1217 : : TupleDesc newtupdesc;
1218 : :
1219 : 374 : oldctx = MemoryContextSwitchTo(data->cachectx);
1220 : :
1221 : : /*
1222 : : * Create tuple table slots. Create a copy of the TupleDesc as it needs to
1223 : : * live as long as the cache remains.
1224 : : */
1097 1225 : 374 : oldtupdesc = CreateTupleDescCopyConstr(RelationGetDescr(relation));
1226 : 374 : newtupdesc = CreateTupleDescCopyConstr(RelationGetDescr(relation));
1227 : :
1740 1228 : 374 : entry->old_slot = MakeSingleTupleTableSlot(oldtupdesc, &TTSOpsHeapTuple);
1229 : 374 : entry->new_slot = MakeSingleTupleTableSlot(newtupdesc, &TTSOpsHeapTuple);
1230 : :
1231 : 374 : MemoryContextSwitchTo(oldctx);
1232 : :
1233 : : /*
1234 : : * Cache the map that will be used to convert the relation's tuples into
1235 : : * the ancestor's format, if needed.
1236 : : */
1237 [ + + ]: 374 : if (entry->publish_as_relid != RelationGetRelid(relation))
1238 : : {
1239 : 38 : Relation ancestor = RelationIdGetRelation(entry->publish_as_relid);
1240 : 38 : TupleDesc indesc = RelationGetDescr(relation);
1241 : 38 : TupleDesc outdesc = RelationGetDescr(ancestor);
1242 : :
1243 : : /* Map must live as long as the logical decoding context. */
698 michael@paquier.xyz 1244 : 38 : oldctx = MemoryContextSwitchTo(data->cachectx);
1245 : :
1460 alvherre@alvh.no-ip. 1246 : 38 : entry->attrmap = build_attrmap_by_name_if_req(indesc, outdesc, false);
1247 : :
1740 akapila@postgresql.o 1248 : 38 : MemoryContextSwitchTo(oldctx);
1249 : 38 : RelationClose(ancestor);
1250 : : }
1251 : 374 : }
1252 : :
1253 : : /*
1254 : : * Change is checked against the row filter if any.
1255 : : *
1256 : : * Returns true if the change is to be replicated, else false.
1257 : : *
1258 : : * For inserts, evaluate the row filter for new tuple.
1259 : : * For deletes, evaluate the row filter for old tuple.
1260 : : * For updates, evaluate the row filter for old and new tuple.
1261 : : *
1262 : : * For updates, if both evaluations are true, we allow sending the UPDATE and
1263 : : * if both the evaluations are false, it doesn't replicate the UPDATE. Now, if
1264 : : * only one of the tuples matches the row filter expression, we transform
1265 : : * UPDATE to DELETE or INSERT to avoid any data inconsistency based on the
1266 : : * following rules:
1267 : : *
1268 : : * Case 1: old-row (no match) new-row (no match) -> (drop change)
1269 : : * Case 2: old-row (no match) new row (match) -> INSERT
1270 : : * Case 3: old-row (match) new-row (no match) -> DELETE
1271 : : * Case 4: old-row (match) new row (match) -> UPDATE
1272 : : *
1273 : : * The new action is updated in the action parameter.
1274 : : *
1275 : : * The new slot could be updated when transforming the UPDATE into INSERT,
1276 : : * because the original new tuple might not have column values from the replica
1277 : : * identity.
1278 : : *
1279 : : * Examples:
1280 : : * Let's say the old tuple satisfies the row filter but the new tuple doesn't.
1281 : : * Since the old tuple satisfies, the initial table synchronization copied this
1282 : : * row (or another method was used to guarantee that there is data
1283 : : * consistency). However, after the UPDATE the new tuple doesn't satisfy the
1284 : : * row filter, so from a data consistency perspective, that row should be
1285 : : * removed on the subscriber. The UPDATE should be transformed into a DELETE
1286 : : * statement and be sent to the subscriber. Keeping this row on the subscriber
1287 : : * is undesirable because it doesn't reflect what was defined in the row filter
1288 : : * expression on the publisher. This row on the subscriber would likely not be
1289 : : * modified by replication again. If someone inserted a new row with the same
1290 : : * old identifier, replication could stop due to a constraint violation.
1291 : : *
1292 : : * Let's say the old tuple doesn't match the row filter but the new tuple does.
1293 : : * Since the old tuple doesn't satisfy, the initial table synchronization
1294 : : * probably didn't copy this row. However, after the UPDATE the new tuple does
1295 : : * satisfy the row filter, so from a data consistency perspective, that row
1296 : : * should be inserted on the subscriber. Otherwise, subsequent UPDATE or DELETE
1297 : : * statements have no effect (it matches no row -- see
1298 : : * apply_handle_update_internal()). So, the UPDATE should be transformed into a
1299 : : * INSERT statement and be sent to the subscriber. However, this might surprise
1300 : : * someone who expects the data set to satisfy the row filter expression on the
1301 : : * provider.
1302 : : */
1303 : : static bool
1304 : 202720 : pgoutput_row_filter(Relation relation, TupleTableSlot *old_slot,
1305 : : TupleTableSlot **new_slot_ptr, RelationSyncEntry *entry,
1306 : : ReorderBufferChangeType *action)
1307 : : {
1308 : : TupleDesc desc;
1309 : : int i;
1310 : : bool old_matched,
1311 : : new_matched,
1312 : : result;
1313 : : TupleTableSlot *tmp_new_slot;
1314 : 202720 : TupleTableSlot *new_slot = *new_slot_ptr;
1315 : : ExprContext *ecxt;
1316 : : ExprState *filter_exprstate;
1317 : :
1318 : : /*
1319 : : * We need this map to avoid relying on ReorderBufferChangeType enums
1320 : : * having specific values.
1321 : : */
1322 : : static const int map_changetype_pubaction[] = {
1323 : : [REORDER_BUFFER_CHANGE_INSERT] = PUBACTION_INSERT,
1324 : : [REORDER_BUFFER_CHANGE_UPDATE] = PUBACTION_UPDATE,
1325 : : [REORDER_BUFFER_CHANGE_DELETE] = PUBACTION_DELETE
1326 : : };
1327 : :
1328 [ + + + + : 202720 : Assert(*action == REORDER_BUFFER_CHANGE_INSERT ||
- + ]
1329 : : *action == REORDER_BUFFER_CHANGE_UPDATE ||
1330 : : *action == REORDER_BUFFER_CHANGE_DELETE);
1331 : :
1332 [ + + - + ]: 202720 : Assert(new_slot || old_slot);
1333 : :
1334 : : /* Get the corresponding row filter */
1335 : 202720 : filter_exprstate = entry->exprstate[map_changetype_pubaction[*action]];
1336 : :
1337 : : /* Bail out if there is no row filter */
1338 [ + + ]: 202720 : if (!filter_exprstate)
1339 : 202685 : return true;
1340 : :
1341 [ - + ]: 35 : elog(DEBUG3, "table \"%s.%s\" has row filter",
1342 : : get_namespace_name(RelationGetNamespace(relation)),
1343 : : RelationGetRelationName(relation));
1344 : :
1345 [ + + ]: 35 : ResetPerTupleExprContext(entry->estate);
1346 : :
1347 [ + + ]: 35 : ecxt = GetPerTupleExprContext(entry->estate);
1348 : :
1349 : : /*
1350 : : * For the following occasions where there is only one tuple, we can
1351 : : * evaluate the row filter for that tuple and return.
1352 : : *
1353 : : * For inserts, we only have the new tuple.
1354 : : *
1355 : : * For updates, we can have only a new tuple when none of the replica
1356 : : * identity columns changed and none of those columns have external data
1357 : : * but we still need to evaluate the row filter for the new tuple as the
1358 : : * existing values of those columns might not match the filter. Also,
1359 : : * users can use constant expressions in the row filter, so we anyway need
1360 : : * to evaluate it for the new tuple.
1361 : : *
1362 : : * For deletes, we only have the old tuple.
1363 : : */
1364 [ + + + + ]: 35 : if (!new_slot || !old_slot)
1365 : : {
1366 [ + + ]: 31 : ecxt->ecxt_scantuple = new_slot ? new_slot : old_slot;
1367 : 31 : result = pgoutput_row_filter_exec_expr(filter_exprstate, ecxt);
1368 : :
1369 : 30 : return result;
1370 : : }
1371 : :
1372 : : /*
1373 : : * Both the old and new tuples must be valid only for updates and need to
1374 : : * be checked against the row filter.
1375 : : */
1376 [ - + ]: 4 : Assert(map_changetype_pubaction[*action] == PUBACTION_UPDATE);
1377 : :
1378 : 4 : slot_getallattrs(new_slot);
1379 : 4 : slot_getallattrs(old_slot);
1380 : :
1381 : 4 : tmp_new_slot = NULL;
1382 : 4 : desc = RelationGetDescr(relation);
1383 : :
1384 : : /*
1385 : : * The new tuple might not have all the replica identity columns, in which
1386 : : * case it needs to be copied over from the old tuple.
1387 : : */
1388 [ + + ]: 12 : for (i = 0; i < desc->natts; i++)
1389 : : {
708 drowley@postgresql.o 1390 : 8 : CompactAttribute *att = TupleDescCompactAttr(desc, i);
1391 : :
1392 : : /*
1393 : : * if the column in the new tuple or old tuple is null, nothing to do
1394 : : */
1740 akapila@postgresql.o 1395 [ + + - + ]: 8 : if (new_slot->tts_isnull[i] || old_slot->tts_isnull[i])
1396 : 1 : continue;
1397 : :
1398 : : /*
1399 : : * Unchanged toasted replica identity columns are only logged in the
1400 : : * old tuple. Copy this over to the new tuple. The changed (or WAL
1401 : : * Logged) toast values are always assembled in memory and set as
1402 : : * VARTAG_INDIRECT. See ReorderBufferToastReplace.
1403 : : */
1404 [ + + + + ]: 11 : if (att->attlen == -1 &&
480 peter@eisentraut.org 1405 : 4 : VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(new_slot->tts_values[i])) &&
1406 [ + - ]: 1 : !VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(old_slot->tts_values[i])))
1407 : : {
1740 akapila@postgresql.o 1408 [ + - ]: 1 : if (!tmp_new_slot)
1409 : : {
1410 : 1 : tmp_new_slot = MakeSingleTupleTableSlot(desc, &TTSOpsVirtual);
1411 : 1 : ExecClearTuple(tmp_new_slot);
1412 : :
1413 : 1 : memcpy(tmp_new_slot->tts_values, new_slot->tts_values,
1414 : 1 : desc->natts * sizeof(Datum));
1415 : 1 : memcpy(tmp_new_slot->tts_isnull, new_slot->tts_isnull,
1416 : 1 : desc->natts * sizeof(bool));
1417 : : }
1418 : :
1419 : 1 : tmp_new_slot->tts_values[i] = old_slot->tts_values[i];
1420 : 1 : tmp_new_slot->tts_isnull[i] = old_slot->tts_isnull[i];
1421 : : }
1422 : : }
1423 : :
1424 : 4 : ecxt->ecxt_scantuple = old_slot;
1425 : 4 : old_matched = pgoutput_row_filter_exec_expr(filter_exprstate, ecxt);
1426 : :
1427 [ + + ]: 4 : if (tmp_new_slot)
1428 : : {
1429 : 1 : ExecStoreVirtualTuple(tmp_new_slot);
1430 : 1 : ecxt->ecxt_scantuple = tmp_new_slot;
1431 : : }
1432 : : else
1433 : 3 : ecxt->ecxt_scantuple = new_slot;
1434 : :
1435 : 4 : new_matched = pgoutput_row_filter_exec_expr(filter_exprstate, ecxt);
1436 : :
1437 : : /*
1438 : : * Case 1: if both tuples don't match the row filter, bailout. Send
1439 : : * nothing.
1440 : : */
1441 [ + + - + ]: 4 : if (!old_matched && !new_matched)
1740 akapila@postgresql.o 1442 :UBC 0 : return false;
1443 : :
1444 : : /*
1445 : : * Case 2: if the old tuple doesn't satisfy the row filter but the new
1446 : : * tuple does, transform the UPDATE into INSERT.
1447 : : *
1448 : : * Use the newly transformed tuple that must contain the column values for
1449 : : * all the replica identity columns. This is required to ensure that the
1450 : : * while inserting the tuple in the downstream node, we have all the
1451 : : * required column values.
1452 : : */
1740 akapila@postgresql.o 1453 [ + + + - ]:CBC 4 : if (!old_matched && new_matched)
1454 : : {
1455 : 2 : *action = REORDER_BUFFER_CHANGE_INSERT;
1456 : :
1457 [ + + ]: 2 : if (tmp_new_slot)
1458 : 1 : *new_slot_ptr = tmp_new_slot;
1459 : : }
1460 : :
1461 : : /*
1462 : : * Case 3: if the old tuple satisfies the row filter but the new tuple
1463 : : * doesn't, transform the UPDATE into DELETE.
1464 : : *
1465 : : * This transformation does not require another tuple. The Old tuple will
1466 : : * be used for DELETE.
1467 : : */
1468 [ + - + + ]: 2 : else if (old_matched && !new_matched)
1469 : 1 : *action = REORDER_BUFFER_CHANGE_DELETE;
1470 : :
1471 : : /*
1472 : : * Case 4: if both tuples match the row filter, transformation isn't
1473 : : * required. (*action is default UPDATE).
1474 : : */
1475 : :
1476 : 4 : return true;
1477 : : }
1478 : :
1479 : : /*
1480 : : * Sends the decoded DML over wire.
1481 : : *
1482 : : * This is called both in streaming and non-streaming modes.
1483 : : */
1484 : : static void
3600 peter_e@gmx.net 1485 : 204651 : pgoutput_change(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
1486 : : Relation relation, ReorderBufferChange *change)
1487 : : {
3482 bruce@momjian.us 1488 : 204651 : PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
1704 akapila@postgresql.o 1489 : 204651 : PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private;
1490 : : MemoryContext old;
1491 : : RelationSyncEntry *relentry;
2277 1492 : 204651 : TransactionId xid = InvalidTransactionId;
2146 1493 : 204651 : Relation ancestor = NULL;
1740 1494 : 204651 : Relation targetrel = relation;
1495 : 204651 : ReorderBufferChangeType action = change->action;
1496 : 204651 : TupleTableSlot *old_slot = NULL;
1497 : 204651 : TupleTableSlot *new_slot = NULL;
1498 : :
3200 peter_e@gmx.net 1499 [ - + ]: 204651 : if (!is_publishable_relation(relation))
1500 : 1930 : return;
1501 : :
1502 : : /*
1503 : : * Remember the xid for the change in streaming mode. We need to send xid
1504 : : * with each change in the streaming mode so that subscriber can make
1505 : : * their association and on aborts, it can discard the corresponding
1506 : : * changes.
1507 : : */
1157 michael@paquier.xyz 1508 [ + + ]: 204651 : if (data->in_streaming)
2277 akapila@postgresql.o 1509 : 175809 : xid = change->txn->xid;
1510 : :
1740 1511 : 204651 : relentry = get_rel_sync_entry(data, relation);
1512 : :
1513 : : /* First check the table filter */
1514 [ + + + - ]: 204650 : switch (action)
1515 : : {
3600 peter_e@gmx.net 1516 : 127199 : case REORDER_BUFFER_CHANGE_INSERT:
1517 [ + + ]: 127199 : if (!relentry->pubactions.pubinsert)
1518 : 744 : return;
1519 : 126455 : break;
1520 : 34490 : case REORDER_BUFFER_CHANGE_UPDATE:
1521 [ + + ]: 34490 : if (!relentry->pubactions.pubupdate)
1522 : 44 : return;
1523 : 34446 : break;
1524 : 42961 : case REORDER_BUFFER_CHANGE_DELETE:
1525 [ + + ]: 42961 : if (!relentry->pubactions.pubdelete)
1526 : 1142 : return;
1527 : :
1528 : : /*
1529 : : * This is only possible if deletes are allowed even when replica
1530 : : * identity is not defined for a table. Since the DELETE action
1531 : : * can't be published, we simply return.
1532 : : */
1339 akapila@postgresql.o 1533 [ - + ]: 41819 : if (!change->data.tp.oldtuple)
1534 : : {
1339 akapila@postgresql.o 1535 [ # # ]:UBC 0 : elog(DEBUG1, "didn't send DELETE change because of missing oldtuple");
1536 : 0 : return;
1537 : : }
3600 peter_e@gmx.net 1538 :CBC 41819 : break;
3600 peter_e@gmx.net 1539 :UBC 0 : default:
1540 : 0 : Assert(false);
1541 : : }
1542 : :
1543 : : /* Avoid leaking memory by using and resetting our own context */
3600 peter_e@gmx.net 1544 :CBC 202720 : old = MemoryContextSwitchTo(data->context);
1545 : :
1546 : : /* Switch relation if publishing via root. */
1339 akapila@postgresql.o 1547 [ + + ]: 202720 : if (relentry->publish_as_relid != RelationGetRelid(relation))
1548 : : {
1549 [ - + ]: 69 : Assert(relation->rd_rel->relispartition);
1550 : 69 : ancestor = RelationIdGetRelation(relentry->publish_as_relid);
1551 : 69 : targetrel = ancestor;
1552 : : }
1553 : :
1554 [ + + ]: 202720 : if (change->data.tp.oldtuple)
1555 : : {
1556 : 41958 : old_slot = relentry->old_slot;
1034 msawada@postgresql.o 1557 : 41958 : ExecStoreHeapTuple(change->data.tp.oldtuple, old_slot, false);
1558 : :
1559 : : /* Convert tuple if needed. */
1339 akapila@postgresql.o 1560 [ + + ]: 41958 : if (relentry->attrmap)
1561 : : {
1562 : 5 : TupleTableSlot *slot = MakeTupleTableSlot(RelationGetDescr(targetrel),
1563 : : &TTSOpsVirtual, 0);
1564 : :
1565 : 5 : old_slot = execute_attr_map_slot(relentry->attrmap, old_slot, slot);
1566 : : }
1567 : : }
1568 : :
1569 [ + + ]: 202720 : if (change->data.tp.newtuple)
1570 : : {
1571 : 160901 : new_slot = relentry->new_slot;
1034 msawada@postgresql.o 1572 : 160901 : ExecStoreHeapTuple(change->data.tp.newtuple, new_slot, false);
1573 : :
1574 : : /* Convert tuple if needed. */
1339 akapila@postgresql.o 1575 [ + + ]: 160901 : if (relentry->attrmap)
1576 : : {
1577 : 20 : TupleTableSlot *slot = MakeTupleTableSlot(RelationGetDescr(targetrel),
1578 : : &TTSOpsVirtual, 0);
1579 : :
1580 : 20 : new_slot = execute_attr_map_slot(relentry->attrmap, new_slot, slot);
1581 : : }
1582 : : }
1583 : :
1584 : : /*
1585 : : * Check row filter.
1586 : : *
1587 : : * Updates could be transformed to inserts or deletes based on the results
1588 : : * of the row filter for old and new tuple.
1589 : : */
1590 [ + + ]: 202720 : if (!pgoutput_row_filter(targetrel, old_slot, &new_slot, relentry, &action))
1591 : 12 : goto cleanup;
1592 : :
1593 : : /*
1594 : : * Send BEGIN if we haven't yet.
1595 : : *
1596 : : * We send the BEGIN message after ensuring that we will actually send the
1597 : : * change. This avoids sending a pair of BEGIN/COMMIT messages for empty
1598 : : * transactions.
1599 : : */
1600 [ + + + + ]: 202707 : if (txndata && !txndata->sent_begin_txn)
1601 : 512 : pgoutput_send_begin(ctx, txn);
1602 : :
1603 : : /*
1604 : : * Schema should be sent using the original relation because it also sends
1605 : : * the ancestor's relation.
1606 : : */
1607 : 202707 : maybe_send_schema(ctx, change, relation, relentry);
1608 : :
1609 : 202707 : OutputPluginPrepareWrite(ctx, true);
1610 : :
1611 : : /* Send the data */
1612 [ + + + - ]: 202707 : switch (action)
1613 : : {
1614 : 126444 : case REORDER_BUFFER_CHANGE_INSERT:
1615 : 126444 : logicalrep_write_insert(ctx->out, xid, targetrel, new_slot,
751 1616 : 126444 : data->binary, relentry->columns,
1617 : : relentry->include_gencols_type);
1339 1618 : 126444 : break;
1619 : 34443 : case REORDER_BUFFER_CHANGE_UPDATE:
1620 : 34443 : logicalrep_write_update(ctx->out, xid, targetrel, old_slot,
751 1621 : 34443 : new_slot, data->binary, relentry->columns,
1622 : : relentry->include_gencols_type);
1740 1623 : 34443 : break;
3600 peter_e@gmx.net 1624 : 41820 : case REORDER_BUFFER_CHANGE_DELETE:
1339 akapila@postgresql.o 1625 : 41820 : logicalrep_write_delete(ctx->out, xid, targetrel, old_slot,
751 1626 : 41820 : data->binary, relentry->columns,
1627 : : relentry->include_gencols_type);
3600 peter_e@gmx.net 1628 : 41820 : break;
3600 peter_e@gmx.net 1629 :UBC 0 : default:
1630 : 0 : Assert(false);
1631 : : }
1632 : :
1339 akapila@postgresql.o 1633 :CBC 202707 : OutputPluginWrite(ctx, true);
1634 : :
1635 : 202715 : cleanup:
2146 1636 [ + + ]: 202715 : if (RelationIsValid(ancestor))
1637 : : {
1638 : 69 : RelationClose(ancestor);
1639 : 69 : ancestor = NULL;
1640 : : }
1641 : :
1642 : : /* Drop the new slots that were used to store the converted tuples. */
884 1643 [ + + ]: 202715 : if (relentry->attrmap)
1644 : : {
1645 [ + + ]: 25 : if (old_slot)
1646 : 5 : ExecDropSingleTupleTableSlot(old_slot);
1647 : :
1648 [ + + ]: 25 : if (new_slot)
1649 : 20 : ExecDropSingleTupleTableSlot(new_slot);
1650 : : }
1651 : :
3600 peter_e@gmx.net 1652 : 202715 : MemoryContextSwitchTo(old);
1653 : 202715 : MemoryContextReset(data->context);
1654 : : }
1655 : :
1656 : : static void
3157 1657 : 18 : pgoutput_truncate(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
1658 : : int nrelations, Relation relations[], ReorderBufferChange *change)
1659 : : {
1660 : 18 : PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
1704 akapila@postgresql.o 1661 : 18 : PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private;
1662 : : MemoryContext old;
1663 : : RelationSyncEntry *relentry;
1664 : : int i;
1665 : : int nrelids;
1666 : : Oid *relids;
2277 1667 : 18 : TransactionId xid = InvalidTransactionId;
1668 : :
1669 : : /* Remember the xid for the change in streaming mode. See pgoutput_change. */
1157 michael@paquier.xyz 1670 [ - + ]: 18 : if (data->in_streaming)
2277 akapila@postgresql.o 1671 :UBC 0 : xid = change->txn->xid;
1672 : :
3157 peter_e@gmx.net 1673 :CBC 18 : old = MemoryContextSwitchTo(data->context);
1674 : :
103 michael@paquier.xyz 1675 :GNC 18 : relids = palloc0_array(Oid, nrelations);
3157 peter_e@gmx.net 1676 :CBC 18 : nrelids = 0;
1677 : :
1678 [ + + ]: 55 : for (i = 0; i < nrelations; i++)
1679 : : {
1680 : 37 : Relation relation = relations[i];
1681 : 37 : Oid relid = RelationGetRelid(relation);
1682 : :
1683 [ - + ]: 37 : if (!is_publishable_relation(relation))
3157 peter_e@gmx.net 1684 :UBC 0 : continue;
1685 : :
1740 akapila@postgresql.o 1686 :CBC 37 : relentry = get_rel_sync_entry(data, relation);
1687 : :
3157 peter_e@gmx.net 1688 [ + + ]: 37 : if (!relentry->pubactions.pubtruncate)
1689 : 16 : continue;
1690 : :
1691 : : /*
1692 : : * Don't send partitions if the publication wants to send only the
1693 : : * root tables through it.
1694 : : */
2425 peter@eisentraut.org 1695 [ + + ]: 21 : if (relation->rd_rel->relispartition &&
1696 [ + + ]: 15 : relentry->publish_as_relid != relid)
2454 1697 : 3 : continue;
1698 : :
3157 peter_e@gmx.net 1699 : 18 : relids[nrelids++] = relid;
1700 : :
1701 : : /* Send BEGIN if we haven't yet */
1704 akapila@postgresql.o 1702 [ + - + + ]: 18 : if (txndata && !txndata->sent_begin_txn)
1703 : 12 : pgoutput_send_begin(ctx, txn);
1704 : :
1941 fujii@postgresql.org 1705 : 18 : maybe_send_schema(ctx, change, relation, relentry);
1706 : : }
1707 : :
3134 peter_e@gmx.net 1708 [ + + ]: 18 : if (nrelids > 0)
1709 : : {
1710 : 12 : OutputPluginPrepareWrite(ctx, true);
1711 : 12 : logicalrep_write_truncate(ctx->out,
1712 : : xid,
1713 : : nrelids,
1714 : : relids,
1715 : 12 : change->data.truncate.cascade,
1716 : 12 : change->data.truncate.restart_seqs);
1717 : 12 : OutputPluginWrite(ctx, true);
1718 : : }
1719 : :
3157 1720 : 18 : MemoryContextSwitchTo(old);
1721 : 18 : MemoryContextReset(data->context);
1722 : 18 : }
1723 : :
1724 : : static void
2062 akapila@postgresql.o 1725 : 8 : pgoutput_message(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
1726 : : TransactionId xid, XLogRecPtr message_lsn, bool transactional,
1727 : : const char *prefix, Size sz, const char *message)
1728 : : {
1729 : 8 : PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
5 msawada@postgresql.o 1730 :GNC 8 : TransactionId stream_xid = InvalidTransactionId;
1731 : :
2062 akapila@postgresql.o 1732 [ + + ]:CBC 8 : if (!data->messages)
1733 : 2 : return;
1734 : :
1735 : : /*
1736 : : * Remember the xid for the message in streaming mode. See
1737 : : * pgoutput_change.
1738 : : */
1157 michael@paquier.xyz 1739 [ + + ]: 6 : if (data->in_streaming)
5 msawada@postgresql.o 1740 :GNC 1 : stream_xid = xid;
1741 : :
1742 : : /*
1743 : : * Output BEGIN if we haven't yet. Avoid for non-transactional messages.
1744 : : */
1704 akapila@postgresql.o 1745 [ + + ]:CBC 6 : if (transactional)
1746 : : {
1747 : 3 : PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private;
1748 : :
1749 : : /* Send BEGIN if we haven't yet */
1750 [ + + + - ]: 3 : if (txndata && !txndata->sent_begin_txn)
1751 : 2 : pgoutput_send_begin(ctx, txn);
1752 : : }
1753 : :
2062 1754 : 6 : OutputPluginPrepareWrite(ctx, true);
1755 : 6 : logicalrep_write_message(ctx->out,
1756 : : stream_xid,
1757 : : message_lsn,
1758 : : transactional,
1759 : : prefix,
1760 : : sz,
1761 : : message);
1762 : 6 : OutputPluginWrite(ctx, true);
1763 : : }
1764 : :
1765 : : /*
1766 : : * Return true if the data is associated with an origin and the user has
1767 : : * requested the changes that don't have an origin, false otherwise.
1768 : : */
1769 : : static bool
3600 peter_e@gmx.net 1770 : 344509 : pgoutput_origin_filter(LogicalDecodingContext *ctx,
1771 : : ReplOriginId origin_id)
1772 : : {
1158 akapila@postgresql.o 1773 : 344509 : PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
1774 : :
304 msawada@postgresql.o 1775 [ + + + + ]: 344509 : if (data->publish_no_origin && origin_id != InvalidReplOriginId)
1591 akapila@postgresql.o 1776 : 188 : return true;
1777 : :
3600 peter_e@gmx.net 1778 : 344321 : return false;
1779 : : }
1780 : :
1781 : : /*
1782 : : * Shutdown the output plugin.
1783 : : *
1784 : : * Note, we don't need to clean the data->context, data->cachectx, and
1785 : : * data->pubctx as they are child contexts of the ctx->context so they
1786 : : * will be cleaned up by logical decoding machinery.
1787 : : */
1788 : : static void
3482 bruce@momjian.us 1789 : 602 : pgoutput_shutdown(LogicalDecodingContext *ctx)
1790 : : {
415 msawada@postgresql.o 1791 : 602 : pgoutput_memory_context_reset(NULL);
3600 peter_e@gmx.net 1792 : 602 : }
1793 : :
1794 : : /*
1795 : : * Load publications from the list of publication names.
1796 : : *
1797 : : * Here, we skip the publications that don't exist yet. This will allow us
1798 : : * to silently continue the replication in the absence of a missing publication.
1799 : : * This is required because we allow the users to create publications after they
1800 : : * have specified the required publications at the time of replication start.
1801 : : */
1802 : : static List *
1803 : 301 : LoadPublications(List *pubnames)
1804 : : {
1805 : 301 : List *result = NIL;
1806 : : ListCell *lc;
1807 : :
3482 bruce@momjian.us 1808 [ + - + + : 655 : foreach(lc, pubnames)
+ + ]
1809 : : {
1810 : 354 : char *pubname = (char *) lfirst(lc);
624 akapila@postgresql.o 1811 : 354 : Publication *pub = GetPublicationByName(pubname, true);
1812 : :
1813 [ + + ]: 354 : if (pub)
1814 : 352 : result = lappend(result, pub);
1815 : : else
1816 [ + - ]: 2 : ereport(WARNING,
1817 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1818 : : errmsg("skipped loading publication \"%s\"", pubname),
1819 : : errdetail("The publication does not exist at this point in the WAL."),
1820 : : errhint("Create the publication if it does not exist."));
1821 : : }
1822 : :
3600 peter_e@gmx.net 1823 : 301 : return result;
1824 : : }
1825 : :
1826 : : /*
1827 : : * Publication syscache invalidation callback.
1828 : : *
1829 : : * Called for invalidations on pg_publication.
1830 : : */
1831 : : static void
283 michael@paquier.xyz 1832 : 480 : publication_invalidation_cb(Datum arg, SysCacheIdentifier cacheid,
1833 : : uint32 hashvalue)
1834 : : {
3600 peter_e@gmx.net 1835 : 480 : publications_valid = false;
1836 : 480 : }
1837 : :
1838 : : /*
1839 : : * START STREAM callback
1840 : : */
1841 : : static void
2277 akapila@postgresql.o 1842 : 638 : pgoutput_stream_start(struct LogicalDecodingContext *ctx,
1843 : : ReorderBufferTXN *txn)
1844 : : {
1157 michael@paquier.xyz 1845 : 638 : PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
304 msawada@postgresql.o 1846 : 638 : bool send_replication_origin = txn->origin_id != InvalidReplOriginId;
1847 : :
1848 : : /* we can't nest streaming of transactions */
1157 michael@paquier.xyz 1849 [ - + ]: 638 : Assert(!data->in_streaming);
1850 : :
1851 : : /*
1852 : : * If we already sent the first stream for this transaction then don't
1853 : : * send the origin id in the subsequent streams.
1854 : : */
2277 akapila@postgresql.o 1855 [ + + ]: 638 : if (rbtxn_is_streamed(txn))
1856 : 580 : send_replication_origin = false;
1857 : :
1858 : 638 : OutputPluginPrepareWrite(ctx, !send_replication_origin);
1859 : 638 : logicalrep_write_stream_start(ctx->out, txn->xid, !rbtxn_is_streamed(txn));
1860 : :
1963 1861 : 638 : send_repl_origin(ctx, txn->origin_id, InvalidXLogRecPtr,
1862 : : send_replication_origin);
1863 : :
2277 1864 : 638 : OutputPluginWrite(ctx, true);
1865 : :
1866 : : /* we're streaming a chunk of transaction now */
1157 michael@paquier.xyz 1867 : 638 : data->in_streaming = true;
2277 akapila@postgresql.o 1868 : 638 : }
1869 : :
1870 : : /*
1871 : : * STOP STREAM callback
1872 : : */
1873 : : static void
1874 : 637 : pgoutput_stream_stop(struct LogicalDecodingContext *ctx,
1875 : : ReorderBufferTXN *txn)
1876 : : {
1157 michael@paquier.xyz 1877 : 637 : PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
1878 : :
1879 : : /* we should be streaming a transaction */
1880 [ - + ]: 637 : Assert(data->in_streaming);
1881 : :
2277 akapila@postgresql.o 1882 : 637 : OutputPluginPrepareWrite(ctx, true);
1883 : 637 : logicalrep_write_stream_stop(ctx->out);
1884 : 637 : OutputPluginWrite(ctx, true);
1885 : :
1886 : : /* we've stopped streaming a transaction */
1157 michael@paquier.xyz 1887 : 637 : data->in_streaming = false;
2277 akapila@postgresql.o 1888 : 637 : }
1889 : :
1890 : : /*
1891 : : * Notify downstream to discard the streamed transaction (along with all
1892 : : * its subtransactions, if it's a toplevel transaction).
1893 : : */
1894 : : static void
1895 : 27 : pgoutput_stream_abort(struct LogicalDecodingContext *ctx,
1896 : : ReorderBufferTXN *txn,
1897 : : XLogRecPtr abort_lsn)
1898 : : {
1899 : : ReorderBufferTXN *toptxn;
1419 1900 : 27 : PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
1901 : 27 : bool write_abort_info = (data->streaming == LOGICALREP_STREAM_PARALLEL);
1902 : :
1903 : : /*
1904 : : * The abort should happen outside streaming block, even for streamed
1905 : : * transactions. The transaction has to be marked as streamed, though.
1906 : : */
1157 michael@paquier.xyz 1907 [ - + ]: 27 : Assert(!data->in_streaming);
1908 : :
1909 : : /* determine the toplevel transaction */
1352 akapila@postgresql.o 1910 [ + + ]: 27 : toptxn = rbtxn_get_toptxn(txn);
1911 : :
2277 1912 [ - + ]: 27 : Assert(rbtxn_is_streamed(toptxn));
1913 : :
1914 : 27 : OutputPluginPrepareWrite(ctx, true);
1419 1915 : 27 : logicalrep_write_stream_abort(ctx->out, toptxn->xid, txn->xid, abort_lsn,
1916 : : txn->abort_time, write_abort_info);
1917 : :
2277 1918 : 27 : OutputPluginWrite(ctx, true);
1919 : :
1920 : 27 : cleanup_rel_sync_cache(toptxn->xid, false);
1921 : 27 : }
1922 : :
1923 : : /*
1924 : : * Notify downstream to apply the streamed transaction (along with all
1925 : : * its subtransactions).
1926 : : */
1927 : : static void
1928 : 44 : pgoutput_stream_commit(struct LogicalDecodingContext *ctx,
1929 : : ReorderBufferTXN *txn,
1930 : : XLogRecPtr commit_lsn)
1931 : : {
1157 michael@paquier.xyz 1932 : 44 : PGOutputData *data PG_USED_FOR_ASSERTS_ONLY = (PGOutputData *) ctx->output_plugin_private;
1933 : :
1934 : : /*
1935 : : * The commit should happen outside streaming block, even for streamed
1936 : : * transactions. The transaction has to be marked as streamed, though.
1937 : : */
1938 [ - + ]: 44 : Assert(!data->in_streaming);
2277 akapila@postgresql.o 1939 [ - + ]: 44 : Assert(rbtxn_is_streamed(txn));
1940 : :
1389 1941 : 44 : OutputPluginUpdateProgress(ctx, false);
1942 : :
2277 1943 : 44 : OutputPluginPrepareWrite(ctx, true);
1944 : 44 : logicalrep_write_stream_commit(ctx->out, txn, commit_lsn);
1945 : 44 : OutputPluginWrite(ctx, true);
1946 : :
1947 : 44 : cleanup_rel_sync_cache(txn->xid, true);
1948 : 44 : }
1949 : :
1950 : : /*
1951 : : * PREPARE callback (for streaming two-phase commit).
1952 : : *
1953 : : * Notify the downstream to prepare the transaction.
1954 : : */
1955 : : static void
1942 1956 : 10 : pgoutput_stream_prepare_txn(LogicalDecodingContext *ctx,
1957 : : ReorderBufferTXN *txn,
1958 : : XLogRecPtr prepare_lsn)
1959 : : {
1960 [ - + ]: 10 : Assert(rbtxn_is_streamed(txn));
1961 : :
1389 1962 : 10 : OutputPluginUpdateProgress(ctx, false);
1942 1963 : 10 : OutputPluginPrepareWrite(ctx, true);
1964 : 10 : logicalrep_write_stream_prepare(ctx->out, txn, prepare_lsn);
1965 : 10 : OutputPluginWrite(ctx, true);
1966 : :
1967 : : /* Schema cache updates at PREPARE survive ROLLBACK PREPARED. */
71 msawada@postgresql.o 1968 : 10 : cleanup_rel_sync_cache(txn->xid, true);
1942 akapila@postgresql.o 1969 : 10 : }
1970 : :
1971 : : /*
1972 : : * Initialize the relation schema sync cache for a decoding session.
1973 : : *
1974 : : * The hash table is destroyed at the end of a decoding session. While
1975 : : * relcache invalidations still exist and will still be invoked, they
1976 : : * will just see the null hash table global and take no action.
1977 : : */
1978 : : static void
3600 peter_e@gmx.net 1979 : 505 : init_rel_sync_cache(MemoryContext cachectx)
1980 : : {
1981 : : HASHCTL ctl;
1982 : : static bool relation_callbacks_registered = false;
1983 : :
1984 : : /* Nothing to do if hash table already exists */
1985 [ - + ]: 505 : if (RelationSyncCache != NULL)
1986 : 2 : return;
1987 : :
1988 : : /* Make a new hash table for the cache */
1989 : 505 : ctl.keysize = sizeof(Oid);
1990 : 505 : ctl.entrysize = sizeof(RelationSyncEntry);
1991 : 505 : ctl.hcxt = cachectx;
1992 : :
1993 : 505 : RelationSyncCache = hash_create("logical replication output relation cache",
1994 : : 128, &ctl,
1995 : : HASH_ELEM | HASH_CONTEXT | HASH_BLOBS);
1996 : :
1997 [ - + ]: 505 : Assert(RelationSyncCache != NULL);
1998 : :
1999 : : /* No more to do if we already registered callbacks */
1374 tgl@sss.pgh.pa.us 2000 [ + + ]: 505 : if (relation_callbacks_registered)
2001 : 2 : return;
2002 : :
2003 : : /* We must update the cache entry for a relation after a relcache flush */
3600 peter_e@gmx.net 2004 : 503 : CacheRegisterRelcacheCallback(rel_sync_cache_relation_cb, (Datum) 0);
2005 : :
2006 : : /*
2007 : : * Flush all cache entries after a pg_namespace change, in case it was a
2008 : : * schema rename affecting a relation being replicated.
2009 : : *
2010 : : * XXX: It is not a good idea to invalidate all the relation entries in
2011 : : * RelationSyncCache on schema rename. We can optimize it to invalidate
2012 : : * only the required relations by either having a specific invalidation
2013 : : * message containing impacted relations or by having schema information
2014 : : * in each RelationSyncCache entry and using hashvalue of pg_namespace.oid
2015 : : * passed to the callback.
2016 : : */
1422 tgl@sss.pgh.pa.us 2017 : 503 : CacheRegisterSyscacheCallback(NAMESPACEOID,
2018 : : rel_sync_cache_publication_cb,
2019 : : (Datum) 0);
2020 : :
1374 2021 : 503 : relation_callbacks_registered = true;
2022 : : }
2023 : :
2024 : : /*
2025 : : * We expect relatively small number of streamed transactions.
2026 : : */
2027 : : static bool
2277 akapila@postgresql.o 2028 : 175809 : get_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid)
2029 : : {
1608 alvherre@alvh.no-ip. 2030 : 175809 : return list_member_xid(entry->streamed_txns, xid);
2031 : : }
2032 : :
2033 : : /*
2034 : : * Add the xid in the rel sync entry for which we have already sent the schema
2035 : : * of the relation.
2036 : : */
2037 : : static void
2277 akapila@postgresql.o 2038 : 67 : set_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid)
2039 : : {
2040 : : MemoryContext oldctx;
2041 : :
2042 : 67 : oldctx = MemoryContextSwitchTo(CacheMemoryContext);
2043 : :
1608 alvherre@alvh.no-ip. 2044 : 67 : entry->streamed_txns = lappend_xid(entry->streamed_txns, xid);
2045 : :
2277 akapila@postgresql.o 2046 : 67 : MemoryContextSwitchTo(oldctx);
2047 : 67 : }
2048 : :
2049 : : /*
2050 : : * Find or create entry in the relation schema cache.
2051 : : *
2052 : : * This looks up publications that the given relation is directly or
2053 : : * indirectly part of (the latter if it's really the relation's ancestor that
2054 : : * is part of a publication) and fills up the found entry with the information
2055 : : * about which operations to publish and whether to use an ancestor's schema
2056 : : * when publishing.
2057 : : */
2058 : : static RelationSyncEntry *
1740 2059 : 204688 : get_rel_sync_entry(PGOutputData *data, Relation relation)
2060 : : {
2061 : : RelationSyncEntry *entry;
2062 : : bool found;
2063 : : MemoryContext oldctx;
2064 : 204688 : Oid relid = RelationGetRelid(relation);
2065 : :
3600 peter_e@gmx.net 2066 [ - + ]: 204688 : Assert(RelationSyncCache != NULL);
2067 : :
2068 : : /* Find cached relation info, creating if not found */
2069 : 204688 : entry = (RelationSyncEntry *) hash_search(RelationSyncCache,
2070 : : &relid,
2071 : : HASH_ENTER, &found);
2072 [ - + ]: 204688 : Assert(entry != NULL);
2073 : :
2074 : : /* initialize entry, if it's new */
2264 akapila@postgresql.o 2075 [ + + ]: 204688 : if (!found)
2076 : : {
1758 2077 : 457 : entry->replicate_valid = false;
2264 2078 : 457 : entry->schema_sent = false;
674 2079 : 457 : entry->include_gencols_type = PUBLISH_GENCOLS_NONE;
2264 2080 : 457 : entry->streamed_txns = NIL;
2081 : 457 : entry->pubactions.pubinsert = entry->pubactions.pubupdate =
1696 tomas.vondra@postgre 2082 : 457 : entry->pubactions.pubdelete = entry->pubactions.pubtruncate = false;
1740 akapila@postgresql.o 2083 : 457 : entry->new_slot = NULL;
2084 : 457 : entry->old_slot = NULL;
2085 : 457 : memset(entry->exprstate, 0, sizeof(entry->exprstate));
1708 tomas.vondra@postgre 2086 : 457 : entry->entry_cxt = NULL;
2264 akapila@postgresql.o 2087 : 457 : entry->publish_as_relid = InvalidOid;
1708 tomas.vondra@postgre 2088 : 457 : entry->columns = NULL;
1740 akapila@postgresql.o 2089 : 457 : entry->attrmap = NULL;
2090 : : }
2091 : :
2092 : : /* Validate the entry */
2264 2093 [ + + ]: 204688 : if (!entry->replicate_valid)
2094 : : {
1858 2095 : 562 : Oid schemaId = get_rel_namespace(relid);
269 2096 : 562 : List *pubids = GetRelationIncludedPublications(relid);
2097 : :
2098 : : /*
2099 : : * We don't acquire a lock on the namespace system table as we build
2100 : : * the cache entry using a historic snapshot and all the later changes
2101 : : * are absorbed while decoding WAL.
2102 : : */
1696 tomas.vondra@postgre 2103 : 562 : List *schemaPubids = GetSchemaPublications(schemaId);
2104 : : ListCell *lc;
2425 peter@eisentraut.org 2105 : 562 : Oid publish_as_relid = relid;
1718 tomas.vondra@postgre 2106 : 562 : int publish_ancestor_level = 0;
1696 2107 : 562 : char relkind = get_rel_relkind(relid);
1740 akapila@postgresql.o 2108 : 562 : List *rel_publications = NIL;
16 2109 : 562 : List *ancestors = NIL;
2110 : :
2111 : : /*
2112 : : * A partition whose concurrent detach has been committed but not
2113 : : * finalized reports no ancestors, even though relispartition is still
2114 : : * set. Treat it as a standalone table. Its changes are no longer
2115 : : * published via its former ancestors, but can still be published via
2116 : : * its own publications.
2117 : : */
2118 [ + + ]: 562 : if (get_rel_relispartition(relid))
2119 : 103 : ancestors = get_partition_ancestors(relid);
2120 : :
2121 : : /* Reload publications if needed before use. */
3600 peter_e@gmx.net 2122 [ + + ]: 562 : if (!publications_valid)
2123 : : {
719 michael@paquier.xyz 2124 : 301 : MemoryContextReset(data->pubctx);
2125 : :
2126 : 301 : oldctx = MemoryContextSwitchTo(data->pubctx);
3600 peter_e@gmx.net 2127 : 301 : data->publications = LoadPublications(data->publication_names);
2128 : 301 : MemoryContextSwitchTo(oldctx);
2129 : 301 : publications_valid = true;
2130 : : }
2131 : :
2132 : : /*
2133 : : * Reset schema_sent status as the relation definition may have
2134 : : * changed. Also reset pubactions to empty in case rel was dropped
2135 : : * from a publication. Also free any objects that depended on the
2136 : : * earlier definition.
2137 : : */
1758 akapila@postgresql.o 2138 : 562 : entry->schema_sent = false;
674 2139 : 562 : entry->include_gencols_type = PUBLISH_GENCOLS_NONE;
1758 2140 : 562 : list_free(entry->streamed_txns);
2141 : 562 : entry->streamed_txns = NIL;
1708 tomas.vondra@postgre 2142 : 562 : bms_free(entry->columns);
2143 : 562 : entry->columns = NULL;
1758 akapila@postgresql.o 2144 : 562 : entry->pubactions.pubinsert = false;
2145 : 562 : entry->pubactions.pubupdate = false;
2146 : 562 : entry->pubactions.pubdelete = false;
2147 : 562 : entry->pubactions.pubtruncate = false;
2148 : :
2149 : : /*
2150 : : * Tuple slots cleanups. (Will be rebuilt later if needed).
2151 : : */
1740 2152 [ + + ]: 562 : if (entry->old_slot)
2153 : : {
737 michael@paquier.xyz 2154 : 63 : TupleDesc desc = entry->old_slot->tts_tupleDescriptor;
2155 : :
2156 [ - + ]: 63 : Assert(desc->tdrefcount == -1);
2157 : :
1740 akapila@postgresql.o 2158 : 63 : ExecDropSingleTupleTableSlot(entry->old_slot);
2159 : :
2160 : : /*
2161 : : * ExecDropSingleTupleTableSlot() would not free the TupleDesc, so
2162 : : * do it now to avoid any leaks.
2163 : : */
737 michael@paquier.xyz 2164 : 63 : FreeTupleDesc(desc);
2165 : : }
1740 akapila@postgresql.o 2166 [ + + ]: 562 : if (entry->new_slot)
2167 : : {
737 michael@paquier.xyz 2168 : 63 : TupleDesc desc = entry->new_slot->tts_tupleDescriptor;
2169 : :
2170 [ - + ]: 63 : Assert(desc->tdrefcount == -1);
2171 : :
1740 akapila@postgresql.o 2172 : 63 : ExecDropSingleTupleTableSlot(entry->new_slot);
2173 : :
2174 : : /*
2175 : : * ExecDropSingleTupleTableSlot() would not free the TupleDesc, so
2176 : : * do it now to avoid any leaks.
2177 : : */
737 michael@paquier.xyz 2178 : 63 : FreeTupleDesc(desc);
2179 : : }
2180 : :
1740 akapila@postgresql.o 2181 : 562 : entry->old_slot = NULL;
2182 : 562 : entry->new_slot = NULL;
2183 : :
2184 [ + + ]: 562 : if (entry->attrmap)
2185 : 3 : free_attrmap(entry->attrmap);
2186 : 562 : entry->attrmap = NULL;
2187 : :
2188 : : /*
2189 : : * Row filter cache cleanups.
2190 : : */
1708 tomas.vondra@postgre 2191 [ + + ]: 562 : if (entry->entry_cxt)
2192 : 63 : MemoryContextDelete(entry->entry_cxt);
2193 : :
2194 : 562 : entry->entry_cxt = NULL;
1740 akapila@postgresql.o 2195 : 562 : entry->estate = NULL;
2196 : 562 : memset(entry->exprstate, 0, sizeof(entry->exprstate));
2197 : :
2198 : : /*
2199 : : * Build publication cache. We can't use one provided by relcache as
2200 : : * relcache considers all publications that the given relation is in,
2201 : : * but here we only need to consider ones that the subscriber
2202 : : * requested.
2203 : : */
3600 peter_e@gmx.net 2204 [ + + + + : 1298 : foreach(lc, data->publications)
+ + ]
2205 : : {
2206 : 736 : Publication *pub = lfirst(lc);
2425 peter@eisentraut.org 2207 : 736 : bool publish = false;
2208 : :
2209 : : /*
2210 : : * Under what relid should we publish changes in this publication?
2211 : : * We'll use the top-most relid across all publications. Also
2212 : : * track the ancestor level for this publication.
2213 : : */
1661 tgl@sss.pgh.pa.us 2214 : 736 : Oid pub_relid = relid;
2215 : 736 : int ancestor_level = 0;
2216 : :
2217 : : /*
2218 : : * If this is a FOR ALL TABLES publication, pick the partition
2219 : : * root and set the ancestor level accordingly.
2220 : : */
1696 tomas.vondra@postgre 2221 [ + + ]: 736 : if (pub->alltables)
2222 : : {
269 akapila@postgresql.o 2223 : 105 : List *exceptpubids = NIL;
2224 : :
16 2225 [ + + ]: 105 : if (ancestors)
2226 : : {
269 2227 : 32 : Oid last_ancestor_relid = llast_oid(ancestors);
2228 : :
2229 : : /*
2230 : : * For a partition, changes are published via top-most
2231 : : * ancestor when pubviaroot is true, so populate pub_relid
2232 : : * accordingly.
2233 : : */
2234 [ + + ]: 32 : if (pub->pubviaroot)
2235 : : {
2236 : 18 : pub_relid = last_ancestor_relid;
2237 : 18 : ancestor_level = list_length(ancestors);
2238 : : }
2239 : :
2240 : : /*
2241 : : * Only the top-most ancestor can appear in the EXCEPT
2242 : : * clause. Therefore, for a partition, exclusion must be
2243 : : * evaluated at the top-most ancestor.
2244 : : */
2245 : 32 : exceptpubids = GetRelationExcludedPublications(last_ancestor_relid);
2246 : : }
2247 : : else
2248 : : {
2249 : : /*
2250 : : * For a regular table or a root partitioned table, check
2251 : : * exclusion on table itself.
2252 : : */
2253 : 73 : exceptpubids = GetRelationExcludedPublications(pub_relid);
2254 : : }
2255 : :
2256 [ + + ]: 105 : if (!list_member_oid(exceptpubids, pub->oid))
2257 : 92 : publish = true;
2258 : :
2259 : 105 : list_free(exceptpubids);
2260 : :
2261 [ + + ]: 105 : if (!publish)
2262 : 13 : continue;
2263 : : }
2264 : :
2425 peter@eisentraut.org 2265 [ + + ]: 723 : if (!publish)
2266 : : {
2389 tgl@sss.pgh.pa.us 2267 : 631 : bool ancestor_published = false;
2268 : :
2269 : : /*
2270 : : * For a partition, check if any of the ancestors are
2271 : : * published. If so, note down the topmost ancestor that is
2272 : : * published via this publication, which will be used as the
2273 : : * relation via which to publish the partition's changes.
2274 : : */
16 akapila@postgresql.o 2275 [ + + ]: 631 : if (ancestors)
2276 : : {
2277 : : Oid ancestor;
2278 : : int level;
2279 : :
1740 2280 : 121 : ancestor = GetTopMostAncestorInPublication(pub->oid,
2281 : : ancestors,
2282 : : &level);
2283 : :
2284 [ + + ]: 121 : if (ancestor != InvalidOid)
2285 : : {
2286 : 48 : ancestor_published = true;
2287 [ + + ]: 48 : if (pub->pubviaroot)
2288 : : {
1718 tomas.vondra@postgre 2289 : 25 : pub_relid = ancestor;
2290 : 25 : ancestor_level = level;
2291 : : }
2292 : : }
2293 : : }
2294 : :
1858 akapila@postgresql.o 2295 [ + + + + ]: 998 : if (list_member_oid(pubids, pub->oid) ||
2296 [ + + ]: 727 : list_member_oid(schemaPubids, pub->oid) ||
2297 : : ancestor_published)
2425 peter@eisentraut.org 2298 : 299 : publish = true;
2299 : : }
2300 : :
2301 : : /*
2302 : : * If the relation is to be published, determine actions to
2303 : : * publish, and list of columns, if appropriate.
2304 : : *
2305 : : * Don't publish changes for partitioned tables, because
2306 : : * publishing those of its partitions suffices, unless partition
2307 : : * changes won't be published due to pubviaroot being set.
2308 : : */
2309 [ + + + + ]: 723 : if (publish &&
2310 [ + + ]: 4 : (relkind != RELKIND_PARTITIONED_TABLE || pub->pubviaroot))
2311 : : {
3600 peter_e@gmx.net 2312 : 388 : entry->pubactions.pubinsert |= pub->pubactions.pubinsert;
2313 : 388 : entry->pubactions.pubupdate |= pub->pubactions.pubupdate;
2314 : 388 : entry->pubactions.pubdelete |= pub->pubactions.pubdelete;
3157 2315 : 388 : entry->pubactions.pubtruncate |= pub->pubactions.pubtruncate;
2316 : :
2317 : : /*
2318 : : * We want to publish the changes as the top-most ancestor
2319 : : * across all publications. So we need to check if the already
2320 : : * calculated level is higher than the new one. If yes, we can
2321 : : * ignore the new value (as it's a child). Otherwise the new
2322 : : * value is an ancestor, so we keep it.
2323 : : */
1718 tomas.vondra@postgre 2324 [ + + ]: 388 : if (publish_ancestor_level > ancestor_level)
2325 : 1 : continue;
2326 : :
2327 : : /*
2328 : : * If we found an ancestor higher up in the tree, discard the
2329 : : * list of publications through which we replicate it, and use
2330 : : * the new ancestor.
2331 : : */
1717 2332 [ + + ]: 387 : if (publish_ancestor_level < ancestor_level)
2333 : : {
2334 : 39 : publish_as_relid = pub_relid;
2335 : 39 : publish_ancestor_level = ancestor_level;
2336 : :
2337 : : /* reset the publication list for this relation */
2338 : 39 : rel_publications = NIL;
2339 : : }
2340 : : else
2341 : : {
2342 : : /* Same ancestor level, has to be the same OID. */
2343 [ - + ]: 348 : Assert(publish_as_relid == pub_relid);
2344 : : }
2345 : :
2346 : : /* Track publications for this ancestor. */
2347 : 387 : rel_publications = lappend(rel_publications, pub);
2348 : : }
2349 : : }
2350 : :
1740 akapila@postgresql.o 2351 : 562 : entry->publish_as_relid = publish_as_relid;
2352 : :
2353 : : /*
2354 : : * Initialize the tuple slot, map, and row filter. These are only used
2355 : : * when publishing inserts, updates, or deletes.
2356 : : */
2357 [ + + + - ]: 562 : if (entry->pubactions.pubinsert || entry->pubactions.pubupdate ||
2358 [ - + ]: 188 : entry->pubactions.pubdelete)
2359 : : {
2360 : : /* Initialize the tuple slot and map */
2361 : 374 : init_tuple_slot(data, relation, entry);
2362 : :
2363 : : /* Initialize the row filter */
2364 : 374 : pgoutput_row_filter_init(data, rel_publications, entry);
2365 : :
2366 : : /* Check whether to publish generated columns. */
751 2367 : 374 : check_and_init_gencol(data, rel_publications, entry);
2368 : :
2369 : : /* Initialize the column list */
1708 tomas.vondra@postgre 2370 : 374 : pgoutput_column_list_init(data, rel_publications, entry);
2371 : : }
2372 : :
3600 peter_e@gmx.net 2373 : 561 : list_free(pubids);
1758 akapila@postgresql.o 2374 : 561 : list_free(schemaPubids);
1740 2375 : 561 : list_free(rel_publications);
16 2376 : 561 : list_free(ancestors);
2377 : :
3600 peter_e@gmx.net 2378 : 561 : entry->replicate_valid = true;
2379 : : }
2380 : :
2381 : 204687 : return entry;
2382 : : }
2383 : :
2384 : : /*
2385 : : * Cleanup list of streamed transactions and update the schema_sent flag.
2386 : : *
2387 : : * When a streamed transaction commits, aborts or prepares, we need to remove
2388 : : * the toplevel XID from the schema cache. If the transaction aborted, the
2389 : : * subscriber will simply throw away the schema records we streamed, so we
2390 : : * don't need to do anything else.
2391 : : *
2392 : : * If the transaction is committed or prepared, the subscriber will update
2393 : : * the relation cache - so tweak the schema_sent flag accordingly.
2394 : : */
2395 : : static void
71 msawada@postgresql.o 2396 : 81 : cleanup_rel_sync_cache(TransactionId xid, bool mark_schema_sent)
2397 : : {
2398 : : HASH_SEQ_STATUS hash_seq;
2399 : : RelationSyncEntry *entry;
2400 : :
2277 akapila@postgresql.o 2401 [ - + ]: 81 : Assert(RelationSyncCache != NULL);
2402 : :
2403 : 81 : hash_seq_init(&hash_seq, RelationSyncCache);
2404 [ + + ]: 163 : while ((entry = hash_seq_search(&hash_seq)) != NULL)
2405 : : {
2406 : : /*
2407 : : * We can set the schema_sent flag for an entry that has a committed
2408 : : * or prepared xid in the list as that ensures that the subscriber
2409 : : * would have the corresponding schema and we don't need to send it
2410 : : * unless there is any invalidation for that relation.
2411 : : */
1059 nathan@postgresql.or 2412 [ + + + - : 167 : foreach_xid(streamed_txn, entry->streamed_txns)
+ + ]
2413 : : {
2414 [ + + ]: 63 : if (xid == streamed_txn)
2415 : : {
71 msawada@postgresql.o 2416 [ + + ]: 60 : if (mark_schema_sent)
2277 akapila@postgresql.o 2417 : 49 : entry->schema_sent = true;
2418 : :
2419 : 60 : entry->streamed_txns =
1059 nathan@postgresql.or 2420 : 60 : foreach_delete_current(entry->streamed_txns, streamed_txn);
2277 akapila@postgresql.o 2421 : 60 : break;
2422 : : }
2423 : : }
2424 : : }
2425 : 81 : }
2426 : :
2427 : : /*
2428 : : * Relcache invalidation callback
2429 : : */
2430 : : static void
3600 peter_e@gmx.net 2431 : 7061 : rel_sync_cache_relation_cb(Datum arg, Oid relid)
2432 : : {
2433 : : RelationSyncEntry *entry;
2434 : :
2435 : : /*
2436 : : * We can get here if the plugin was used in SQL interface as the
2437 : : * RelationSyncCache is destroyed when the decoding finishes, but there is
2438 : : * no way to unregister the relcache invalidation callback.
2439 : : */
2440 [ + + ]: 7061 : if (RelationSyncCache == NULL)
2441 : 44 : return;
2442 : :
2443 : : /*
2444 : : * Nobody keeps pointers to entries in this hash table around outside
2445 : : * logical decoding callback calls - but invalidation events can come in
2446 : : * *during* a callback if we do any syscache access in the callback.
2447 : : * Because of that we must mark the cache entry as invalid but not damage
2448 : : * any of its substructure here. The next get_rel_sync_entry() call will
2449 : : * rebuild it all.
2450 : : */
1758 akapila@postgresql.o 2451 [ + + ]: 7017 : if (OidIsValid(relid))
2452 : : {
2453 : : /*
2454 : : * Getting invalidations for relations that aren't in the table is
2455 : : * entirely normal. So we don't care if it's found or not.
2456 : : */
2457 : 6935 : entry = (RelationSyncEntry *) hash_search(RelationSyncCache, &relid,
2458 : : HASH_FIND, NULL);
2459 [ + + ]: 6935 : if (entry != NULL)
2460 : 1139 : entry->replicate_valid = false;
2461 : : }
2462 : : else
2463 : : {
2464 : : /* Whole cache must be flushed. */
2465 : : HASH_SEQ_STATUS status;
2466 : :
2467 : 82 : hash_seq_init(&status, RelationSyncCache);
2468 [ + + ]: 156 : while ((entry = (RelationSyncEntry *) hash_seq_search(&status)) != NULL)
2469 : : {
2470 : 74 : entry->replicate_valid = false;
2471 : : }
2472 : : }
2473 : : }
2474 : :
2475 : : /*
2476 : : * Publication relation/schema map syscache invalidation callback
2477 : : *
2478 : : * Called for invalidations on pg_namespace.
2479 : : */
2480 : : static void
283 michael@paquier.xyz 2481 : 50 : rel_sync_cache_publication_cb(Datum arg, SysCacheIdentifier cacheid,
2482 : : uint32 hashvalue)
2483 : : {
2484 : : HASH_SEQ_STATUS status;
2485 : : RelationSyncEntry *entry;
2486 : :
2487 : : /*
2488 : : * We can get here if the plugin was used in SQL interface as the
2489 : : * RelationSyncCache is destroyed when the decoding finishes, but there is
2490 : : * no way to unregister the invalidation callbacks.
2491 : : */
3600 peter_e@gmx.net 2492 [ + + ]: 50 : if (RelationSyncCache == NULL)
2493 : 15 : return;
2494 : :
2495 : : /*
2496 : : * We have no easy way to identify which cache entries this invalidation
2497 : : * event might have affected, so just mark them all invalid.
2498 : : */
2499 : 35 : hash_seq_init(&status, RelationSyncCache);
2500 [ + + ]: 58 : while ((entry = (RelationSyncEntry *) hash_seq_search(&status)) != NULL)
2501 : : {
2502 : 23 : entry->replicate_valid = false;
2503 : : }
2504 : : }
2505 : :
2506 : : /* Send Replication origin */
2507 : : static void
304 msawada@postgresql.o 2508 : 1185 : send_repl_origin(LogicalDecodingContext *ctx, ReplOriginId origin_id,
2509 : : XLogRecPtr origin_lsn, bool send_origin)
2510 : : {
1963 akapila@postgresql.o 2511 [ + + ]: 1185 : if (send_origin)
2512 : : {
2513 : : char *origin;
2514 : :
2515 : : /*----------
2516 : : * XXX: which behaviour do we want here?
2517 : : *
2518 : : * Alternatives:
2519 : : * - don't send origin message if origin name not found
2520 : : * (that's what we do now)
2521 : : * - throw error - that will break replication, not good
2522 : : * - send some special "unknown" origin
2523 : : *----------
2524 : : */
2525 [ + - ]: 9 : if (replorigin_by_oid(origin_id, true, &origin))
2526 : : {
2527 : : /* Message boundary */
2528 : 9 : OutputPluginWrite(ctx, false);
2529 : 9 : OutputPluginPrepareWrite(ctx, true);
2530 : :
2531 : 9 : logicalrep_write_origin(ctx->out, origin, origin_lsn);
2532 : : }
2533 : : }
2534 : 1185 : }
|