Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

PostgreSQL Source Code git master
pgoutput.c File Reference
Include dependency graph for pgoutput.c:

Go to the source code of this file.

Data Structures

struct  RelationSyncEntry
 
struct  PGOutputTxnData
 

Macros

#define NUM_ROWFILTER_PUBACTIONS   (PUBACTION_DELETE+1)
 

Typedefs

typedef struct RelationSyncEntry RelationSyncEntry
 
typedef struct PGOutputTxnData PGOutputTxnData
 

Enumerations

enum  RowFilterPubAction { PUBACTION_INSERT , PUBACTION_UPDATE , PUBACTION_DELETE }
 

Functions

 PG_MODULE_MAGIC_EXT (.name="pgoutput",.version=PG_VERSION)
 
static void pgoutput_startup (LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
 
static void pgoutput_shutdown (LogicalDecodingContext *ctx)
 
static void pgoutput_begin_txn (LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
 
static void pgoutput_commit_txn (LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
 
static void pgoutput_change (LogicalDecodingContext *ctx, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change)
 
static void pgoutput_truncate (LogicalDecodingContext *ctx, ReorderBufferTXN *txn, int nrelations, Relation relations[], ReorderBufferChange *change)
 
static void pgoutput_message (LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr message_lsn, bool transactional, const char *prefix, Size sz, const char *message)
 
static bool pgoutput_origin_filter (LogicalDecodingContext *ctx, RepOriginId origin_id)
 
static void pgoutput_begin_prepare_txn (LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
 
static void pgoutput_prepare_txn (LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn)
 
static void pgoutput_commit_prepared_txn (LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
 
static void pgoutput_rollback_prepared_txn (LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_end_lsn, TimestampTz prepare_time)
 
static void pgoutput_stream_start (struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
 
static void pgoutput_stream_stop (struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
 
static void pgoutput_stream_abort (struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr abort_lsn)
 
static void pgoutput_stream_commit (struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
 
static void pgoutput_stream_prepare_txn (LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn)
 
static ListLoadPublications (List *pubnames)
 
static void publication_invalidation_cb (Datum arg, int cacheid, uint32 hashvalue)
 
static void send_repl_origin (LogicalDecodingContext *ctx, RepOriginId origin_id, XLogRecPtr origin_lsn, bool send_origin)
 
static void init_rel_sync_cache (MemoryContext cachectx)
 
static void cleanup_rel_sync_cache (TransactionId xid, bool is_commit)
 
static RelationSyncEntryget_rel_sync_entry (PGOutputData *data, Relation relation)
 
static void send_relation_and_attrs (Relation relation, TransactionId xid, LogicalDecodingContext *ctx, RelationSyncEntry *relentry)
 
static void rel_sync_cache_relation_cb (Datum arg, Oid relid)
 
static void rel_sync_cache_publication_cb (Datum arg, int cacheid, uint32 hashvalue)
 
static void set_schema_sent_in_streamed_txn (RelationSyncEntry *entry, TransactionId xid)
 
static bool get_schema_sent_in_streamed_txn (RelationSyncEntry *entry, TransactionId xid)
 
static void init_tuple_slot (PGOutputData *data, Relation relation, RelationSyncEntry *entry)
 
static EStatecreate_estate_for_relation (Relation rel)
 
static void pgoutput_row_filter_init (PGOutputData *data, List *publications, RelationSyncEntry *entry)
 
static bool pgoutput_row_filter_exec_expr (ExprState *state, ExprContext *econtext)
 
static bool pgoutput_row_filter (Relation relation, TupleTableSlot *old_slot, TupleTableSlot **new_slot_ptr, RelationSyncEntry *entry, ReorderBufferChangeType *action)
 
static void pgoutput_column_list_init (PGOutputData *data, List *publications, RelationSyncEntry *entry)
 
void _PG_output_plugin_init (OutputPluginCallbacks *cb)
 
static void parse_output_parameters (List *options, PGOutputData *data)
 
static void pgoutput_send_begin (LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
 
static void maybe_send_schema (LogicalDecodingContext *ctx, ReorderBufferChange *change, Relation relation, RelationSyncEntry *relentry)
 
static void pgoutput_ensure_entry_cxt (PGOutputData *data, RelationSyncEntry *entry)
 
static void check_and_init_gencol (PGOutputData *data, List *publications, RelationSyncEntry *entry)
 

Variables

static bool publications_valid
 
static HTABRelationSyncCache = NULL
 

Macro Definition Documentation

◆ NUM_ROWFILTER_PUBACTIONS

#define NUM_ROWFILTER_PUBACTIONS   (PUBACTION_DELETE+1)

Definition at line 106 of file pgoutput.c.

Typedef Documentation

◆ PGOutputTxnData

◆ RelationSyncEntry

Enumeration Type Documentation

◆ RowFilterPubAction

Enumerator
PUBACTION_INSERT 
PUBACTION_UPDATE 
PUBACTION_DELETE 

Definition at line 99 of file pgoutput.c.

100{
104};
@ PUBACTION_INSERT
Definition: pgoutput.c:101
@ PUBACTION_UPDATE
Definition: pgoutput.c:102
@ PUBACTION_DELETE
Definition: pgoutput.c:103

Function Documentation

◆ _PG_output_plugin_init()

void _PG_output_plugin_init ( OutputPluginCallbacks cb)

Definition at line 260 of file pgoutput.c.

261{
268
275
276 /* transaction streaming */
284 /* transaction streaming - two-phase commit */
286}
static void pgoutput_change(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change)
Definition: pgoutput.c:1457
static void pgoutput_begin_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
Definition: pgoutput.c:637
static void pgoutput_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
Definition: pgoutput.c:433
static void pgoutput_truncate(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, int nrelations, Relation relations[], ReorderBufferChange *change)
Definition: pgoutput.c:1629
static void pgoutput_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn)
Definition: pgoutput.c:654
static bool pgoutput_origin_filter(LogicalDecodingContext *ctx, RepOriginId origin_id)
Definition: pgoutput.c:1742
static void pgoutput_rollback_prepared_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_end_lsn, TimestampTz prepare_time)
Definition: pgoutput.c:682
static void pgoutput_shutdown(LogicalDecodingContext *ctx)
Definition: pgoutput.c:1761
static void pgoutput_stream_abort(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr abort_lsn)
Definition: pgoutput.c:1870
static void pgoutput_stream_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn)
Definition: pgoutput.c:1931
static void pgoutput_begin_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
Definition: pgoutput.c:569
static void pgoutput_stream_commit(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: pgoutput.c:1903
static void pgoutput_commit_prepared_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: pgoutput.c:668
static void pgoutput_stream_stop(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
Definition: pgoutput.c:1849
static void pgoutput_stream_start(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
Definition: pgoutput.c:1817
static void pgoutput_message(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr message_lsn, bool transactional, const char *prefix, Size sz, const char *message)
Definition: pgoutput.c:1697
static void pgoutput_commit_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: pgoutput.c:605
LogicalDecodeStreamChangeCB stream_change_cb
LogicalDecodeMessageCB message_cb
LogicalDecodeStreamTruncateCB stream_truncate_cb
LogicalDecodeStreamMessageCB stream_message_cb
LogicalDecodeFilterByOriginCB filter_by_origin_cb
LogicalDecodeTruncateCB truncate_cb
LogicalDecodeStreamStopCB stream_stop_cb
LogicalDecodeStreamCommitCB stream_commit_cb
LogicalDecodeRollbackPreparedCB rollback_prepared_cb
LogicalDecodeStreamPrepareCB stream_prepare_cb
LogicalDecodeCommitPreparedCB commit_prepared_cb
LogicalDecodeStreamStartCB stream_start_cb
LogicalDecodePrepareCB prepare_cb
LogicalDecodeStartupCB startup_cb
LogicalDecodeCommitCB commit_cb
LogicalDecodeBeginCB begin_cb
LogicalDecodeStreamAbortCB stream_abort_cb
LogicalDecodeBeginPrepareCB begin_prepare_cb
LogicalDecodeChangeCB change_cb
LogicalDecodeShutdownCB shutdown_cb

References OutputPluginCallbacks::begin_cb, OutputPluginCallbacks::begin_prepare_cb, OutputPluginCallbacks::change_cb, OutputPluginCallbacks::commit_cb, OutputPluginCallbacks::commit_prepared_cb, OutputPluginCallbacks::filter_by_origin_cb, OutputPluginCallbacks::message_cb, pgoutput_begin_prepare_txn(), pgoutput_begin_txn(), pgoutput_change(), pgoutput_commit_prepared_txn(), pgoutput_commit_txn(), pgoutput_message(), pgoutput_origin_filter(), pgoutput_prepare_txn(), pgoutput_rollback_prepared_txn(), pgoutput_shutdown(), pgoutput_startup(), pgoutput_stream_abort(), pgoutput_stream_commit(), pgoutput_stream_prepare_txn(), pgoutput_stream_start(), pgoutput_stream_stop(), pgoutput_truncate(), OutputPluginCallbacks::prepare_cb, OutputPluginCallbacks::rollback_prepared_cb, OutputPluginCallbacks::shutdown_cb, OutputPluginCallbacks::startup_cb, OutputPluginCallbacks::stream_abort_cb, OutputPluginCallbacks::stream_change_cb, OutputPluginCallbacks::stream_commit_cb, OutputPluginCallbacks::stream_message_cb, OutputPluginCallbacks::stream_prepare_cb, OutputPluginCallbacks::stream_start_cb, OutputPluginCallbacks::stream_stop_cb, OutputPluginCallbacks::stream_truncate_cb, and OutputPluginCallbacks::truncate_cb.

◆ check_and_init_gencol()

static void check_and_init_gencol ( PGOutputData data,
List publications,
RelationSyncEntry entry 
)
static

Definition at line 1038 of file pgoutput.c.

1040{
1042 TupleDesc desc = RelationGetDescr(relation);
1043 bool gencolpresent = false;
1044 bool first = true;
1045
1046 /* Check if there is any generated column present. */
1047 for (int i = 0; i < desc->natts; i++)
1048 {
1049 Form_pg_attribute att = TupleDescAttr(desc, i);
1050
1051 if (att->attgenerated)
1052 {
1053 gencolpresent = true;
1054 break;
1055 }
1056 }
1057
1058 /* There are no generated columns to be published. */
1059 if (!gencolpresent)
1060 {
1061 entry->include_gencols_type = PUBLISH_GENCOLS_NONE;
1062 return;
1063 }
1064
1065 /*
1066 * There may be a conflicting value for 'publish_generated_columns'
1067 * parameter in the publications.
1068 */
1069 foreach_ptr(Publication, pub, publications)
1070 {
1071 /*
1072 * The column list takes precedence over the
1073 * 'publish_generated_columns' parameter. Those will be checked later,
1074 * see pgoutput_column_list_init.
1075 */
1076 if (check_and_fetch_column_list(pub, entry->publish_as_relid, NULL, NULL))
1077 continue;
1078
1079 if (first)
1080 {
1081 entry->include_gencols_type = pub->pubgencols_type;
1082 first = false;
1083 }
1084 else if (entry->include_gencols_type != pub->pubgencols_type)
1085 ereport(ERROR,
1086 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1087 errmsg("cannot use different values of publish_generated_columns for table \"%s.%s\" in different publications",
1089 RelationGetRelationName(relation)));
1090 }
1091}
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:150
int i
Definition: isn.c:77
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3533
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
#define foreach_ptr(type, var, lst)
Definition: pg_list.h:469
bool check_and_fetch_column_list(Publication *pub, Oid relid, MemoryContext mcxt, Bitmapset **cols)
#define RelationGetDescr(relation)
Definition: rel.h:540
#define RelationGetRelationName(relation)
Definition: rel.h:548
#define RelationGetNamespace(relation)
Definition: rel.h:555
Relation RelationIdGetRelation(Oid relationId)
Definition: relcache.c:2099
PublishGencolsType include_gencols_type
Definition: pgoutput.c:141
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160

References check_and_fetch_column_list(), ereport, errcode(), errmsg(), ERROR, foreach_ptr, get_namespace_name(), i, RelationSyncEntry::include_gencols_type, TupleDescData::natts, RelationSyncEntry::publish_as_relid, RelationGetDescr, RelationGetNamespace, RelationGetRelationName, RelationIdGetRelation(), and TupleDescAttr().

Referenced by get_rel_sync_entry().

◆ cleanup_rel_sync_cache()

static void cleanup_rel_sync_cache ( TransactionId  xid,
bool  is_commit 
)
static

Definition at line 2326 of file pgoutput.c.

2327{
2328 HASH_SEQ_STATUS hash_seq;
2329 RelationSyncEntry *entry;
2330
2331 Assert(RelationSyncCache != NULL);
2332
2333 hash_seq_init(&hash_seq, RelationSyncCache);
2334 while ((entry = hash_seq_search(&hash_seq)) != NULL)
2335 {
2336 /*
2337 * We can set the schema_sent flag for an entry that has committed xid
2338 * in the list as that ensures that the subscriber would have the
2339 * corresponding schema and we don't need to send it unless there is
2340 * any invalidation for that relation.
2341 */
2342 foreach_xid(streamed_txn, entry->streamed_txns)
2343 {
2344 if (xid == streamed_txn)
2345 {
2346 if (is_commit)
2347 entry->schema_sent = true;
2348
2349 entry->streamed_txns =
2350 foreach_delete_current(entry->streamed_txns, streamed_txn);
2351 break;
2352 }
2353 }
2354 }
2355}
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1380
Assert(PointerIsAligned(start, uint64))
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
#define foreach_xid(var, lst)
Definition: pg_list.h:472
static HTAB * RelationSyncCache
Definition: pgoutput.c:220
List * streamed_txns
Definition: pgoutput.c:142

References Assert(), foreach_delete_current, foreach_xid, hash_seq_init(), hash_seq_search(), RelationSyncCache, RelationSyncEntry::schema_sent, and RelationSyncEntry::streamed_txns.

Referenced by pgoutput_stream_abort(), and pgoutput_stream_commit().

◆ create_estate_for_relation()

static EState * create_estate_for_relation ( Relation  rel)
static

Definition at line 815 of file pgoutput.c.

816{
817 EState *estate;
818 RangeTblEntry *rte;
819 List *perminfos = NIL;
820
821 estate = CreateExecutorState();
822
823 rte = makeNode(RangeTblEntry);
824 rte->rtekind = RTE_RELATION;
825 rte->relid = RelationGetRelid(rel);
826 rte->relkind = rel->rd_rel->relkind;
827 rte->rellockmode = AccessShareLock;
828
829 addRTEPermissionInfo(&perminfos, rte);
830
831 ExecInitRangeTable(estate, list_make1(rte), perminfos,
833
834 estate->es_output_cid = GetCurrentCommandId(false);
835
836 return estate;
837}
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
void ExecInitRangeTable(EState *estate, List *rangeTable, List *permInfos, Bitmapset *unpruned_relids)
Definition: execUtils.c:773
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define AccessShareLock
Definition: lockdefs.h:36
#define makeNode(_type_)
Definition: nodes.h:161
RTEPermissionInfo * addRTEPermissionInfo(List **rteperminfos, RangeTblEntry *rte)
@ RTE_RELATION
Definition: parsenodes.h:1042
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
#define RelationGetRelid(relation)
Definition: rel.h:514
CommandId es_output_cid
Definition: execnodes.h:682
Definition: pg_list.h:54
RTEKind rtekind
Definition: parsenodes.h:1077
Form_pg_class rd_rel
Definition: rel.h:111
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:829

References AccessShareLock, addRTEPermissionInfo(), bms_make_singleton(), CreateExecutorState(), EState::es_output_cid, ExecInitRangeTable(), GetCurrentCommandId(), list_make1, makeNode, NIL, RelationData::rd_rel, RelationGetRelid, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by pgoutput_row_filter_init().

◆ get_rel_sync_entry()

static RelationSyncEntry * get_rel_sync_entry ( PGOutputData data,
Relation  relation 
)
static

Definition at line 2031 of file pgoutput.c.

2032{
2033 RelationSyncEntry *entry;
2034 bool found;
2035 MemoryContext oldctx;
2036 Oid relid = RelationGetRelid(relation);
2037
2038 Assert(RelationSyncCache != NULL);
2039
2040 /* Find cached relation info, creating if not found */
2042 &relid,
2043 HASH_ENTER, &found);
2044 Assert(entry != NULL);
2045
2046 /* initialize entry, if it's new */
2047 if (!found)
2048 {
2049 entry->replicate_valid = false;
2050 entry->schema_sent = false;
2051 entry->include_gencols_type = PUBLISH_GENCOLS_NONE;
2052 entry->streamed_txns = NIL;
2053 entry->pubactions.pubinsert = entry->pubactions.pubupdate =
2054 entry->pubactions.pubdelete = entry->pubactions.pubtruncate = false;
2055 entry->new_slot = NULL;
2056 entry->old_slot = NULL;
2057 memset(entry->exprstate, 0, sizeof(entry->exprstate));
2058 entry->entry_cxt = NULL;
2060 entry->columns = NULL;
2061 entry->attrmap = NULL;
2062 }
2063
2064 /* Validate the entry */
2065 if (!entry->replicate_valid)
2066 {
2067 Oid schemaId = get_rel_namespace(relid);
2068 List *pubids = GetRelationPublications(relid);
2069
2070 /*
2071 * We don't acquire a lock on the namespace system table as we build
2072 * the cache entry using a historic snapshot and all the later changes
2073 * are absorbed while decoding WAL.
2074 */
2075 List *schemaPubids = GetSchemaPublications(schemaId);
2076 ListCell *lc;
2077 Oid publish_as_relid = relid;
2078 int publish_ancestor_level = 0;
2079 bool am_partition = get_rel_relispartition(relid);
2080 char relkind = get_rel_relkind(relid);
2081 List *rel_publications = NIL;
2082
2083 /* Reload publications if needed before use. */
2084 if (!publications_valid)
2085 {
2086 MemoryContextReset(data->pubctx);
2087
2088 oldctx = MemoryContextSwitchTo(data->pubctx);
2089 data->publications = LoadPublications(data->publication_names);
2090 MemoryContextSwitchTo(oldctx);
2091 publications_valid = true;
2092 }
2093
2094 /*
2095 * Reset schema_sent status as the relation definition may have
2096 * changed. Also reset pubactions to empty in case rel was dropped
2097 * from a publication. Also free any objects that depended on the
2098 * earlier definition.
2099 */
2100 entry->schema_sent = false;
2101 entry->include_gencols_type = PUBLISH_GENCOLS_NONE;
2102 list_free(entry->streamed_txns);
2103 entry->streamed_txns = NIL;
2104 bms_free(entry->columns);
2105 entry->columns = NULL;
2106 entry->pubactions.pubinsert = false;
2107 entry->pubactions.pubupdate = false;
2108 entry->pubactions.pubdelete = false;
2109 entry->pubactions.pubtruncate = false;
2110
2111 /*
2112 * Tuple slots cleanups. (Will be rebuilt later if needed).
2113 */
2114 if (entry->old_slot)
2115 {
2116 TupleDesc desc = entry->old_slot->tts_tupleDescriptor;
2117
2118 Assert(desc->tdrefcount == -1);
2119
2121
2122 /*
2123 * ExecDropSingleTupleTableSlot() would not free the TupleDesc, so
2124 * do it now to avoid any leaks.
2125 */
2126 FreeTupleDesc(desc);
2127 }
2128 if (entry->new_slot)
2129 {
2130 TupleDesc desc = entry->new_slot->tts_tupleDescriptor;
2131
2132 Assert(desc->tdrefcount == -1);
2133
2135
2136 /*
2137 * ExecDropSingleTupleTableSlot() would not free the TupleDesc, so
2138 * do it now to avoid any leaks.
2139 */
2140 FreeTupleDesc(desc);
2141 }
2142
2143 entry->old_slot = NULL;
2144 entry->new_slot = NULL;
2145
2146 if (entry->attrmap)
2147 free_attrmap(entry->attrmap);
2148 entry->attrmap = NULL;
2149
2150 /*
2151 * Row filter cache cleanups.
2152 */
2153 if (entry->entry_cxt)
2155
2156 entry->entry_cxt = NULL;
2157 entry->estate = NULL;
2158 memset(entry->exprstate, 0, sizeof(entry->exprstate));
2159
2160 /*
2161 * Build publication cache. We can't use one provided by relcache as
2162 * relcache considers all publications that the given relation is in,
2163 * but here we only need to consider ones that the subscriber
2164 * requested.
2165 */
2166 foreach(lc, data->publications)
2167 {
2168 Publication *pub = lfirst(lc);
2169 bool publish = false;
2170
2171 /*
2172 * Under what relid should we publish changes in this publication?
2173 * We'll use the top-most relid across all publications. Also
2174 * track the ancestor level for this publication.
2175 */
2176 Oid pub_relid = relid;
2177 int ancestor_level = 0;
2178
2179 /*
2180 * If this is a FOR ALL TABLES publication, pick the partition
2181 * root and set the ancestor level accordingly.
2182 */
2183 if (pub->alltables)
2184 {
2185 publish = true;
2186 if (pub->pubviaroot && am_partition)
2187 {
2188 List *ancestors = get_partition_ancestors(relid);
2189
2190 pub_relid = llast_oid(ancestors);
2191 ancestor_level = list_length(ancestors);
2192 }
2193 }
2194
2195 if (!publish)
2196 {
2197 bool ancestor_published = false;
2198
2199 /*
2200 * For a partition, check if any of the ancestors are
2201 * published. If so, note down the topmost ancestor that is
2202 * published via this publication, which will be used as the
2203 * relation via which to publish the partition's changes.
2204 */
2205 if (am_partition)
2206 {
2207 Oid ancestor;
2208 int level;
2209 List *ancestors = get_partition_ancestors(relid);
2210
2211 ancestor = GetTopMostAncestorInPublication(pub->oid,
2212 ancestors,
2213 &level);
2214
2215 if (ancestor != InvalidOid)
2216 {
2217 ancestor_published = true;
2218 if (pub->pubviaroot)
2219 {
2220 pub_relid = ancestor;
2221 ancestor_level = level;
2222 }
2223 }
2224 }
2225
2226 if (list_member_oid(pubids, pub->oid) ||
2227 list_member_oid(schemaPubids, pub->oid) ||
2228 ancestor_published)
2229 publish = true;
2230 }
2231
2232 /*
2233 * If the relation is to be published, determine actions to
2234 * publish, and list of columns, if appropriate.
2235 *
2236 * Don't publish changes for partitioned tables, because
2237 * publishing those of its partitions suffices, unless partition
2238 * changes won't be published due to pubviaroot being set.
2239 */
2240 if (publish &&
2241 (relkind != RELKIND_PARTITIONED_TABLE || pub->pubviaroot))
2242 {
2247
2248 /*
2249 * We want to publish the changes as the top-most ancestor
2250 * across all publications. So we need to check if the already
2251 * calculated level is higher than the new one. If yes, we can
2252 * ignore the new value (as it's a child). Otherwise the new
2253 * value is an ancestor, so we keep it.
2254 */
2255 if (publish_ancestor_level > ancestor_level)
2256 continue;
2257
2258 /*
2259 * If we found an ancestor higher up in the tree, discard the
2260 * list of publications through which we replicate it, and use
2261 * the new ancestor.
2262 */
2263 if (publish_ancestor_level < ancestor_level)
2264 {
2265 publish_as_relid = pub_relid;
2266 publish_ancestor_level = ancestor_level;
2267
2268 /* reset the publication list for this relation */
2269 rel_publications = NIL;
2270 }
2271 else
2272 {
2273 /* Same ancestor level, has to be the same OID. */
2274 Assert(publish_as_relid == pub_relid);
2275 }
2276
2277 /* Track publications for this ancestor. */
2278 rel_publications = lappend(rel_publications, pub);
2279 }
2280 }
2281
2282 entry->publish_as_relid = publish_as_relid;
2283
2284 /*
2285 * Initialize the tuple slot, map, and row filter. These are only used
2286 * when publishing inserts, updates, or deletes.
2287 */
2288 if (entry->pubactions.pubinsert || entry->pubactions.pubupdate ||
2289 entry->pubactions.pubdelete)
2290 {
2291 /* Initialize the tuple slot and map */
2292 init_tuple_slot(data, relation, entry);
2293
2294 /* Initialize the row filter */
2295 pgoutput_row_filter_init(data, rel_publications, entry);
2296
2297 /* Check whether to publish generated columns. */
2298 check_and_init_gencol(data, rel_publications, entry);
2299
2300 /* Initialize the column list */
2301 pgoutput_column_list_init(data, rel_publications, entry);
2302 }
2303
2304 list_free(pubids);
2305 list_free(schemaPubids);
2306 list_free(rel_publications);
2307
2308 entry->replicate_valid = true;
2309 }
2310
2311 return entry;
2312}
void free_attrmap(AttrMap *map)
Definition: attmap.c:56
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:952
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1443
@ HASH_ENTER
Definition: hsearch.h:114
List * lappend(List *list, void *datum)
Definition: list.c:339
void list_free(List *list)
Definition: list.c:1546
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:722
bool get_rel_relispartition(Oid relid)
Definition: lsyscache.c:2194
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2170
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:2119
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:400
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:469
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
List * get_partition_ancestors(Oid relid)
Definition: partition.c:134
const void * data
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define llast_oid(l)
Definition: pg_list.h:200
List * GetRelationPublications(Oid relid)
List * GetSchemaPublications(Oid schemaid)
Oid GetTopMostAncestorInPublication(Oid puboid, List *ancestors, int *ancestor_level)
static List * LoadPublications(List *pubnames)
Definition: pgoutput.c:1779
static void init_tuple_slot(PGOutputData *data, Relation relation, RelationSyncEntry *entry)
Definition: pgoutput.c:1184
static void pgoutput_row_filter_init(PGOutputData *data, List *publications, RelationSyncEntry *entry)
Definition: pgoutput.c:891
static void check_and_init_gencol(PGOutputData *data, List *publications, RelationSyncEntry *entry)
Definition: pgoutput.c:1038
static void pgoutput_column_list_init(PGOutputData *data, List *publications, RelationSyncEntry *entry)
Definition: pgoutput.c:1097
static bool publications_valid
Definition: pgoutput.c:86
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
PublicationActions pubactions
ExprState * exprstate[NUM_ROWFILTER_PUBACTIONS]
Definition: pgoutput.c:155
Bitmapset * columns
Definition: pgoutput.c:181
PublicationActions pubactions
Definition: pgoutput.c:146
TupleTableSlot * old_slot
Definition: pgoutput.c:158
bool replicate_valid
Definition: pgoutput.c:130
MemoryContext entry_cxt
Definition: pgoutput.c:187
EState * estate
Definition: pgoutput.c:156
TupleTableSlot * new_slot
Definition: pgoutput.c:157
AttrMap * attrmap
Definition: pgoutput.c:174
int tdrefcount
Definition: tupdesc.h:140
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
void FreeTupleDesc(TupleDesc tupdesc)
Definition: tupdesc.c:502

References Publication::alltables, Assert(), RelationSyncEntry::attrmap, bms_free(), check_and_init_gencol(), RelationSyncEntry::columns, data, RelationSyncEntry::entry_cxt, RelationSyncEntry::estate, ExecDropSingleTupleTableSlot(), RelationSyncEntry::exprstate, free_attrmap(), FreeTupleDesc(), get_partition_ancestors(), get_rel_namespace(), get_rel_relispartition(), get_rel_relkind(), GetRelationPublications(), GetSchemaPublications(), GetTopMostAncestorInPublication(), HASH_ENTER, hash_search(), RelationSyncEntry::include_gencols_type, init_tuple_slot(), InvalidOid, lappend(), lfirst, list_free(), list_length(), list_member_oid(), llast_oid, LoadPublications(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), RelationSyncEntry::new_slot, NIL, Publication::oid, RelationSyncEntry::old_slot, pgoutput_column_list_init(), pgoutput_row_filter_init(), RelationSyncEntry::pubactions, Publication::pubactions, PublicationActions::pubdelete, PublicationActions::pubinsert, publications_valid, RelationSyncEntry::publish_as_relid, PublicationActions::pubtruncate, PublicationActions::pubupdate, Publication::pubviaroot, RelationGetRelid, RelationSyncCache, RelationSyncEntry::replicate_valid, RelationSyncEntry::schema_sent, RelationSyncEntry::streamed_txns, TupleDescData::tdrefcount, and TupleTableSlot::tts_tupleDescriptor.

Referenced by pgoutput_change(), and pgoutput_truncate().

◆ get_schema_sent_in_streamed_txn()

static bool get_schema_sent_in_streamed_txn ( RelationSyncEntry entry,
TransactionId  xid 
)
static

Definition at line 2000 of file pgoutput.c.

2001{
2002 return list_member_xid(entry->streamed_txns, xid);
2003}
bool list_member_xid(const List *list, TransactionId datum)
Definition: list.c:742

References list_member_xid(), and RelationSyncEntry::streamed_txns.

Referenced by maybe_send_schema().

◆ init_rel_sync_cache()

static void init_rel_sync_cache ( MemoryContext  cachectx)
static

Definition at line 1951 of file pgoutput.c.

1952{
1953 HASHCTL ctl;
1954 static bool relation_callbacks_registered = false;
1955
1956 /* Nothing to do if hash table already exists */
1957 if (RelationSyncCache != NULL)
1958 return;
1959
1960 /* Make a new hash table for the cache */
1961 ctl.keysize = sizeof(Oid);
1962 ctl.entrysize = sizeof(RelationSyncEntry);
1963 ctl.hcxt = cachectx;
1964
1965 RelationSyncCache = hash_create("logical replication output relation cache",
1966 128, &ctl,
1968
1969 Assert(RelationSyncCache != NULL);
1970
1971 /* No more to do if we already registered callbacks */
1972 if (relation_callbacks_registered)
1973 return;
1974
1975 /* We must update the cache entry for a relation after a relcache flush */
1977
1978 /*
1979 * Flush all cache entries after a pg_namespace change, in case it was a
1980 * schema rename affecting a relation being replicated.
1981 *
1982 * XXX: It is not a good idea to invalidate all the relation entries in
1983 * RelationSyncCache on schema rename. We can optimize it to invalidate
1984 * only the required relations by either having a specific invalidation
1985 * message containing impacted relations or by having schema information
1986 * in each RelationSyncCache entry and using hashvalue of pg_namespace.oid
1987 * passed to the callback.
1988 */
1989 CacheRegisterSyscacheCallback(NAMESPACEOID,
1991 (Datum) 0);
1992
1993 relation_callbacks_registered = true;
1994}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:358
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void CacheRegisterRelcacheCallback(RelcacheCallbackFunction func, Datum arg)
Definition: inval.c:1854
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1812
static void rel_sync_cache_publication_cb(Datum arg, int cacheid, uint32 hashvalue)
Definition: pgoutput.c:2411
struct RelationSyncEntry RelationSyncEntry
static void rel_sync_cache_relation_cb(Datum arg, Oid relid)
Definition: pgoutput.c:2361
uint64_t Datum
Definition: postgres.h:70
tree ctl
Definition: radixtree.h:1838

References Assert(), CacheRegisterRelcacheCallback(), CacheRegisterSyscacheCallback(), ctl, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, rel_sync_cache_publication_cb(), rel_sync_cache_relation_cb(), and RelationSyncCache.

Referenced by pgoutput_startup().

◆ init_tuple_slot()

static void init_tuple_slot ( PGOutputData data,
Relation  relation,
RelationSyncEntry entry 
)
static

Definition at line 1184 of file pgoutput.c.

1186{
1187 MemoryContext oldctx;
1188 TupleDesc oldtupdesc;
1189 TupleDesc newtupdesc;
1190
1191 oldctx = MemoryContextSwitchTo(data->cachectx);
1192
1193 /*
1194 * Create tuple table slots. Create a copy of the TupleDesc as it needs to
1195 * live as long as the cache remains.
1196 */
1197 oldtupdesc = CreateTupleDescCopyConstr(RelationGetDescr(relation));
1198 newtupdesc = CreateTupleDescCopyConstr(RelationGetDescr(relation));
1199
1200 entry->old_slot = MakeSingleTupleTableSlot(oldtupdesc, &TTSOpsHeapTuple);
1201 entry->new_slot = MakeSingleTupleTableSlot(newtupdesc, &TTSOpsHeapTuple);
1202
1203 MemoryContextSwitchTo(oldctx);
1204
1205 /*
1206 * Cache the map that will be used to convert the relation's tuples into
1207 * the ancestor's format, if needed.
1208 */
1209 if (entry->publish_as_relid != RelationGetRelid(relation))
1210 {
1212 TupleDesc indesc = RelationGetDescr(relation);
1213 TupleDesc outdesc = RelationGetDescr(ancestor);
1214
1215 /* Map must live as long as the logical decoding context. */
1216 oldctx = MemoryContextSwitchTo(data->cachectx);
1217
1218 entry->attrmap = build_attrmap_by_name_if_req(indesc, outdesc, false);
1219
1220 MemoryContextSwitchTo(oldctx);
1221 RelationClose(ancestor);
1222 }
1223}
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:261
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1427
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:85
void RelationClose(Relation relation)
Definition: relcache.c:2220
TupleDesc CreateTupleDescCopyConstr(TupleDesc tupdesc)
Definition: tupdesc.c:340

References RelationSyncEntry::attrmap, build_attrmap_by_name_if_req(), CreateTupleDescCopyConstr(), data, MakeSingleTupleTableSlot(), MemoryContextSwitchTo(), RelationSyncEntry::new_slot, RelationSyncEntry::old_slot, RelationSyncEntry::publish_as_relid, RelationClose(), RelationGetDescr, RelationGetRelid, RelationIdGetRelation(), and TTSOpsHeapTuple.

Referenced by get_rel_sync_entry().

◆ LoadPublications()

static List * LoadPublications ( List pubnames)
static

Definition at line 1779 of file pgoutput.c.

1780{
1781 List *result = NIL;
1782 ListCell *lc;
1783
1784 foreach(lc, pubnames)
1785 {
1786 char *pubname = (char *) lfirst(lc);
1787 Publication *pub = GetPublicationByName(pubname, true);
1788
1789 if (pub)
1790 result = lappend(result, pub);
1791 else
1793 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1794 errmsg("skipped loading publication \"%s\"", pubname),
1795 errdetail("The publication does not exist at this point in the WAL."),
1796 errhint("Create the publication if it does not exist."));
1797 }
1798
1799 return result;
1800}
int errdetail(const char *fmt,...)
Definition: elog.c:1207
int errhint(const char *fmt,...)
Definition: elog.c:1321
#define WARNING
Definition: elog.h:36
Publication * GetPublicationByName(const char *pubname, bool missing_ok)

References ereport, errcode(), errdetail(), errhint(), errmsg(), GetPublicationByName(), lappend(), lfirst, NIL, and WARNING.

Referenced by get_rel_sync_entry().

◆ maybe_send_schema()

static void maybe_send_schema ( LogicalDecodingContext ctx,
ReorderBufferChange change,
Relation  relation,
RelationSyncEntry relentry 
)
static

Definition at line 700 of file pgoutput.c.

703{
705 bool schema_sent;
708
709 /*
710 * Remember XID of the (sub)transaction for the change. We don't care if
711 * it's top-level transaction or not (we have already sent that XID in
712 * start of the current streaming block).
713 *
714 * If we're not in a streaming block, just use InvalidTransactionId and
715 * the write methods will not include it.
716 */
717 if (data->in_streaming)
718 xid = change->txn->xid;
719
720 if (rbtxn_is_subtxn(change->txn))
721 topxid = rbtxn_get_toptxn(change->txn)->xid;
722 else
723 topxid = xid;
724
725 /*
726 * Do we need to send the schema? We do track streamed transactions
727 * separately, because those may be applied later (and the regular
728 * transactions won't see their effects until then) and in an order that
729 * we don't know at this point.
730 *
731 * XXX There is a scope of optimization here. Currently, we always send
732 * the schema first time in a streaming transaction but we can probably
733 * avoid that by checking 'relentry->schema_sent' flag. However, before
734 * doing that we need to study its impact on the case where we have a mix
735 * of streaming and non-streaming transactions.
736 */
737 if (data->in_streaming)
738 schema_sent = get_schema_sent_in_streamed_txn(relentry, topxid);
739 else
740 schema_sent = relentry->schema_sent;
741
742 /* Nothing to do if we already sent the schema. */
743 if (schema_sent)
744 return;
745
746 /*
747 * Send the schema. If the changes will be published using an ancestor's
748 * schema, not the relation's own, send that ancestor's schema before
749 * sending relation's own (XXX - maybe sending only the former suffices?).
750 */
751 if (relentry->publish_as_relid != RelationGetRelid(relation))
752 {
753 Relation ancestor = RelationIdGetRelation(relentry->publish_as_relid);
754
755 send_relation_and_attrs(ancestor, xid, ctx, relentry);
756 RelationClose(ancestor);
757 }
758
759 send_relation_and_attrs(relation, xid, ctx, relentry);
760
761 if (data->in_streaming)
762 set_schema_sent_in_streamed_txn(relentry, topxid);
763 else
764 relentry->schema_sent = true;
765}
uint32 TransactionId
Definition: c.h:658
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
static void send_relation_and_attrs(Relation relation, TransactionId xid, LogicalDecodingContext *ctx, RelationSyncEntry *relentry)
Definition: pgoutput.c:771
static void set_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid)
Definition: pgoutput.c:2010
static bool get_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid)
Definition: pgoutput.c:2000
#define rbtxn_get_toptxn(txn)
#define rbtxn_is_subtxn(txn)
void * output_plugin_private
Definition: logical.h:76
struct ReorderBufferTXN * txn
Definition: reorderbuffer.h:84
TransactionId xid
#define InvalidTransactionId
Definition: transam.h:31

References data, get_schema_sent_in_streamed_txn(), if(), InvalidTransactionId, LogicalDecodingContext::output_plugin_private, RelationSyncEntry::publish_as_relid, rbtxn_get_toptxn, rbtxn_is_subtxn, RelationClose(), RelationGetRelid, RelationIdGetRelation(), RelationSyncEntry::schema_sent, send_relation_and_attrs(), set_schema_sent_in_streamed_txn(), ReorderBufferChange::txn, and ReorderBufferTXN::xid.

Referenced by pgoutput_change(), and pgoutput_truncate().

◆ parse_output_parameters()

static void parse_output_parameters ( List options,
PGOutputData data 
)
static

Definition at line 289 of file pgoutput.c.

290{
291 ListCell *lc;
292 bool protocol_version_given = false;
293 bool publication_names_given = false;
294 bool binary_option_given = false;
295 bool messages_option_given = false;
296 bool streaming_given = false;
297 bool two_phase_option_given = false;
298 bool origin_option_given = false;
299
300 /* Initialize optional parameters to defaults */
301 data->binary = false;
302 data->streaming = LOGICALREP_STREAM_OFF;
303 data->messages = false;
304 data->two_phase = false;
305 data->publish_no_origin = false;
306
307 foreach(lc, options)
308 {
309 DefElem *defel = (DefElem *) lfirst(lc);
310
311 Assert(defel->arg == NULL || IsA(defel->arg, String));
312
313 /* Check each param, whether or not we recognize it */
314 if (strcmp(defel->defname, "proto_version") == 0)
315 {
316 unsigned long parsed;
317 char *endptr;
318
319 if (protocol_version_given)
321 (errcode(ERRCODE_SYNTAX_ERROR),
322 errmsg("conflicting or redundant options")));
323 protocol_version_given = true;
324
325 errno = 0;
326 parsed = strtoul(strVal(defel->arg), &endptr, 10);
327 if (errno != 0 || *endptr != '\0')
329 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
330 errmsg("invalid proto_version")));
331
332 if (parsed > PG_UINT32_MAX)
334 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
335 errmsg("proto_version \"%s\" out of range",
336 strVal(defel->arg))));
337
338 data->protocol_version = (uint32) parsed;
339 }
340 else if (strcmp(defel->defname, "publication_names") == 0)
341 {
342 if (publication_names_given)
344 (errcode(ERRCODE_SYNTAX_ERROR),
345 errmsg("conflicting or redundant options")));
346 publication_names_given = true;
347
348 if (!SplitIdentifierString(strVal(defel->arg), ',',
349 &data->publication_names))
351 (errcode(ERRCODE_INVALID_NAME),
352 errmsg("invalid publication_names syntax")));
353 }
354 else if (strcmp(defel->defname, "binary") == 0)
355 {
356 if (binary_option_given)
358 (errcode(ERRCODE_SYNTAX_ERROR),
359 errmsg("conflicting or redundant options")));
360 binary_option_given = true;
361
362 data->binary = defGetBoolean(defel);
363 }
364 else if (strcmp(defel->defname, "messages") == 0)
365 {
366 if (messages_option_given)
368 (errcode(ERRCODE_SYNTAX_ERROR),
369 errmsg("conflicting or redundant options")));
370 messages_option_given = true;
371
372 data->messages = defGetBoolean(defel);
373 }
374 else if (strcmp(defel->defname, "streaming") == 0)
375 {
376 if (streaming_given)
378 (errcode(ERRCODE_SYNTAX_ERROR),
379 errmsg("conflicting or redundant options")));
380 streaming_given = true;
381
382 data->streaming = defGetStreamingMode(defel);
383 }
384 else if (strcmp(defel->defname, "two_phase") == 0)
385 {
386 if (two_phase_option_given)
388 (errcode(ERRCODE_SYNTAX_ERROR),
389 errmsg("conflicting or redundant options")));
390 two_phase_option_given = true;
391
392 data->two_phase = defGetBoolean(defel);
393 }
394 else if (strcmp(defel->defname, "origin") == 0)
395 {
396 char *origin;
397
398 if (origin_option_given)
400 errcode(ERRCODE_SYNTAX_ERROR),
401 errmsg("conflicting or redundant options"));
402 origin_option_given = true;
403
404 origin = defGetString(defel);
405 if (pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) == 0)
406 data->publish_no_origin = true;
407 else if (pg_strcasecmp(origin, LOGICALREP_ORIGIN_ANY) == 0)
408 data->publish_no_origin = false;
409 else
411 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
412 errmsg("unrecognized origin value: \"%s\"", origin));
413 }
414 else
415 elog(ERROR, "unrecognized pgoutput option: %s", defel->defname);
416 }
417
418 /* Check required options */
419 if (!protocol_version_given)
421 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
422 errmsg("option \"%s\" missing", "proto_version"));
423 if (!publication_names_given)
425 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
426 errmsg("option \"%s\" missing", "publication_names"));
427}
#define PG_UINT32_MAX
Definition: c.h:596
uint32_t uint32
Definition: c.h:539
char * defGetString(DefElem *def)
Definition: define.c:35
bool defGetBoolean(DefElem *def)
Definition: define.c:94
#define elog(elevel,...)
Definition: elog.h:226
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
char * defname
Definition: parsenodes.h:842
Node * arg
Definition: parsenodes.h:843
Definition: value.h:64
char defGetStreamingMode(DefElem *def)
#define strVal(v)
Definition: value.h:82
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:2744

References DefElem::arg, Assert(), data, defGetBoolean(), defGetStreamingMode(), defGetString(), DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, IsA, lfirst, pg_strcasecmp(), PG_UINT32_MAX, SplitIdentifierString(), and strVal.

Referenced by pgoutput_startup().

◆ PG_MODULE_MAGIC_EXT()

PG_MODULE_MAGIC_EXT ( name = "pgoutput",
version = PG_VERSION 
)

◆ pgoutput_begin_prepare_txn()

static void pgoutput_begin_prepare_txn ( LogicalDecodingContext ctx,
ReorderBufferTXN txn 
)
static

Definition at line 637 of file pgoutput.c.

638{
639 bool send_replication_origin = txn->origin_id != InvalidRepOriginId;
640
641 OutputPluginPrepareWrite(ctx, !send_replication_origin);
643
644 send_repl_origin(ctx, txn->origin_id, txn->origin_lsn,
645 send_replication_origin);
646
647 OutputPluginWrite(ctx, true);
648}
void OutputPluginWrite(struct LogicalDecodingContext *ctx, bool last_write)
Definition: logical.c:705
void OutputPluginPrepareWrite(struct LogicalDecodingContext *ctx, bool last_write)
Definition: logical.c:692
#define InvalidRepOriginId
Definition: origin.h:33
static void send_repl_origin(LogicalDecodingContext *ctx, RepOriginId origin_id, XLogRecPtr origin_lsn, bool send_origin)
Definition: pgoutput.c:2437
void logicalrep_write_begin_prepare(StringInfo out, ReorderBufferTXN *txn)
Definition: proto.c:116
StringInfo out
Definition: logical.h:71
RepOriginId origin_id
XLogRecPtr origin_lsn

References InvalidRepOriginId, logicalrep_write_begin_prepare(), ReorderBufferTXN::origin_id, ReorderBufferTXN::origin_lsn, LogicalDecodingContext::out, OutputPluginPrepareWrite(), OutputPluginWrite(), and send_repl_origin().

Referenced by _PG_output_plugin_init().

◆ pgoutput_begin_txn()

static void pgoutput_begin_txn ( LogicalDecodingContext ctx,
ReorderBufferTXN txn 
)
static

Definition at line 569 of file pgoutput.c.

570{
572 sizeof(PGOutputTxnData));
573
574 txn->output_plugin_private = txndata;
575}
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1263
MemoryContext context
Definition: logical.h:36
void * output_plugin_private

References LogicalDecodingContext::context, MemoryContextAllocZero(), and ReorderBufferTXN::output_plugin_private.

Referenced by _PG_output_plugin_init().

◆ pgoutput_change()

static void pgoutput_change ( LogicalDecodingContext ctx,
ReorderBufferTXN txn,
Relation  relation,
ReorderBufferChange change 
)
static

Definition at line 1457 of file pgoutput.c.

1459{
1462 MemoryContext old;
1463 RelationSyncEntry *relentry;
1465 Relation ancestor = NULL;
1466 Relation targetrel = relation;
1468 TupleTableSlot *old_slot = NULL;
1469 TupleTableSlot *new_slot = NULL;
1470
1471 if (!is_publishable_relation(relation))
1472 return;
1473
1474 /*
1475 * Remember the xid for the change in streaming mode. We need to send xid
1476 * with each change in the streaming mode so that subscriber can make
1477 * their association and on aborts, it can discard the corresponding
1478 * changes.
1479 */
1480 if (data->in_streaming)
1481 xid = change->txn->xid;
1482
1483 relentry = get_rel_sync_entry(data, relation);
1484
1485 /* First check the table filter */
1486 switch (action)
1487 {
1489 if (!relentry->pubactions.pubinsert)
1490 return;
1491 break;
1493 if (!relentry->pubactions.pubupdate)
1494 return;
1495 break;
1497 if (!relentry->pubactions.pubdelete)
1498 return;
1499
1500 /*
1501 * This is only possible if deletes are allowed even when replica
1502 * identity is not defined for a table. Since the DELETE action
1503 * can't be published, we simply return.
1504 */
1505 if (!change->data.tp.oldtuple)
1506 {
1507 elog(DEBUG1, "didn't send DELETE change because of missing oldtuple");
1508 return;
1509 }
1510 break;
1511 default:
1512 Assert(false);
1513 }
1514
1515 /* Avoid leaking memory by using and resetting our own context */
1516 old = MemoryContextSwitchTo(data->context);
1517
1518 /* Switch relation if publishing via root. */
1519 if (relentry->publish_as_relid != RelationGetRelid(relation))
1520 {
1521 Assert(relation->rd_rel->relispartition);
1522 ancestor = RelationIdGetRelation(relentry->publish_as_relid);
1523 targetrel = ancestor;
1524 }
1525
1526 if (change->data.tp.oldtuple)
1527 {
1528 old_slot = relentry->old_slot;
1529 ExecStoreHeapTuple(change->data.tp.oldtuple, old_slot, false);
1530
1531 /* Convert tuple if needed. */
1532 if (relentry->attrmap)
1533 {
1535 &TTSOpsVirtual);
1536
1537 old_slot = execute_attr_map_slot(relentry->attrmap, old_slot, slot);
1538 }
1539 }
1540
1541 if (change->data.tp.newtuple)
1542 {
1543 new_slot = relentry->new_slot;
1544 ExecStoreHeapTuple(change->data.tp.newtuple, new_slot, false);
1545
1546 /* Convert tuple if needed. */
1547 if (relentry->attrmap)
1548 {
1550 &TTSOpsVirtual);
1551
1552 new_slot = execute_attr_map_slot(relentry->attrmap, new_slot, slot);
1553 }
1554 }
1555
1556 /*
1557 * Check row filter.
1558 *
1559 * Updates could be transformed to inserts or deletes based on the results
1560 * of the row filter for old and new tuple.
1561 */
1562 if (!pgoutput_row_filter(targetrel, old_slot, &new_slot, relentry, &action))
1563 goto cleanup;
1564
1565 /*
1566 * Send BEGIN if we haven't yet.
1567 *
1568 * We send the BEGIN message after ensuring that we will actually send the
1569 * change. This avoids sending a pair of BEGIN/COMMIT messages for empty
1570 * transactions.
1571 */
1572 if (txndata && !txndata->sent_begin_txn)
1573 pgoutput_send_begin(ctx, txn);
1574
1575 /*
1576 * Schema should be sent using the original relation because it also sends
1577 * the ancestor's relation.
1578 */
1579 maybe_send_schema(ctx, change, relation, relentry);
1580
1581 OutputPluginPrepareWrite(ctx, true);
1582
1583 /* Send the data */
1584 switch (action)
1585 {
1587 logicalrep_write_insert(ctx->out, xid, targetrel, new_slot,
1588 data->binary, relentry->columns,
1589 relentry->include_gencols_type);
1590 break;
1592 logicalrep_write_update(ctx->out, xid, targetrel, old_slot,
1593 new_slot, data->binary, relentry->columns,
1594 relentry->include_gencols_type);
1595 break;
1597 logicalrep_write_delete(ctx->out, xid, targetrel, old_slot,
1598 data->binary, relentry->columns,
1599 relentry->include_gencols_type);
1600 break;
1601 default:
1602 Assert(false);
1603 }
1604
1605 OutputPluginWrite(ctx, true);
1606
1607cleanup:
1608 if (RelationIsValid(ancestor))
1609 {
1610 RelationClose(ancestor);
1611 ancestor = NULL;
1612 }
1613
1614 /* Drop the new slots that were used to store the converted tuples. */
1615 if (relentry->attrmap)
1616 {
1617 if (old_slot)
1619
1620 if (new_slot)
1622 }
1623
1625 MemoryContextReset(data->context);
1626}
static void cleanup(void)
Definition: bootstrap.c:715
#define DEBUG1
Definition: elog.h:30
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1301
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1541
bool is_publishable_relation(Relation rel)
static void pgoutput_send_begin(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
Definition: pgoutput.c:583
static RelationSyncEntry * get_rel_sync_entry(PGOutputData *data, Relation relation)
Definition: pgoutput.c:2031
static void maybe_send_schema(LogicalDecodingContext *ctx, ReorderBufferChange *change, Relation relation, RelationSyncEntry *relentry)
Definition: pgoutput.c:700
static bool pgoutput_row_filter(Relation relation, TupleTableSlot *old_slot, TupleTableSlot **new_slot_ptr, RelationSyncEntry *entry, ReorderBufferChangeType *action)
Definition: pgoutput.c:1276
void logicalrep_write_insert(StringInfo out, TransactionId xid, Relation rel, TupleTableSlot *newslot, bool binary, Bitmapset *columns, PublishGencolsType include_gencols_type)
Definition: proto.c:403
void logicalrep_write_delete(StringInfo out, TransactionId xid, Relation rel, TupleTableSlot *oldslot, bool binary, Bitmapset *columns, PublishGencolsType include_gencols_type)
Definition: proto.c:528
void logicalrep_write_update(StringInfo out, TransactionId xid, Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool binary, Bitmapset *columns, PublishGencolsType include_gencols_type)
Definition: proto.c:450
#define RelationIsValid(relation)
Definition: rel.h:489
ReorderBufferChangeType
Definition: reorderbuffer.h:51
@ REORDER_BUFFER_CHANGE_INSERT
Definition: reorderbuffer.h:52
@ REORDER_BUFFER_CHANGE_DELETE
Definition: reorderbuffer.h:54
@ REORDER_BUFFER_CHANGE_UPDATE
Definition: reorderbuffer.h:53
ReorderBufferChangeType action
Definition: reorderbuffer.h:81
union ReorderBufferChange::@113 data
struct ReorderBufferChange::@113::@114 tp
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:192

References generate_unaccent_rules::action, ReorderBufferChange::action, Assert(), RelationSyncEntry::attrmap, cleanup(), RelationSyncEntry::columns, ReorderBufferChange::data, data, DEBUG1, elog, ExecDropSingleTupleTableSlot(), ExecStoreHeapTuple(), execute_attr_map_slot(), get_rel_sync_entry(), RelationSyncEntry::include_gencols_type, InvalidTransactionId, is_publishable_relation(), logicalrep_write_delete(), logicalrep_write_insert(), logicalrep_write_update(), MakeTupleTableSlot(), maybe_send_schema(), MemoryContextReset(), MemoryContextSwitchTo(), RelationSyncEntry::new_slot, ReorderBufferChange::newtuple, RelationSyncEntry::old_slot, ReorderBufferChange::oldtuple, LogicalDecodingContext::out, LogicalDecodingContext::output_plugin_private, ReorderBufferTXN::output_plugin_private, OutputPluginPrepareWrite(), OutputPluginWrite(), pgoutput_row_filter(), pgoutput_send_begin(), RelationSyncEntry::pubactions, PublicationActions::pubdelete, PublicationActions::pubinsert, RelationSyncEntry::publish_as_relid, PublicationActions::pubupdate, RelationData::rd_rel, RelationClose(), RelationGetDescr, RelationGetRelid, RelationIdGetRelation(), RelationIsValid, REORDER_BUFFER_CHANGE_DELETE, REORDER_BUFFER_CHANGE_INSERT, REORDER_BUFFER_CHANGE_UPDATE, ReorderBufferChange::tp, TTSOpsVirtual, ReorderBufferChange::txn, and ReorderBufferTXN::xid.

Referenced by _PG_output_plugin_init().

◆ pgoutput_column_list_init()

static void pgoutput_column_list_init ( PGOutputData data,
List publications,
RelationSyncEntry entry 
)
static

Definition at line 1097 of file pgoutput.c.

1099{
1100 ListCell *lc;
1101 bool first = true;
1103 bool found_pub_collist = false;
1104 Bitmapset *relcols = NULL;
1105
1107
1108 /*
1109 * Find if there are any column lists for this relation. If there are,
1110 * build a bitmap using the column lists.
1111 *
1112 * Multiple publications might have multiple column lists for this
1113 * relation.
1114 *
1115 * Note that we don't support the case where the column list is different
1116 * for the same table when combining publications. See comments atop
1117 * fetch_table_list. But one can later change the publication so we still
1118 * need to check all the given publication-table mappings and report an
1119 * error if any publications have a different column list.
1120 */
1121 foreach(lc, publications)
1122 {
1123 Publication *pub = lfirst(lc);
1124 Bitmapset *cols = NULL;
1125
1126 /* Retrieve the bitmap of columns for a column list publication. */
1127 found_pub_collist |= check_and_fetch_column_list(pub,
1128 entry->publish_as_relid,
1129 entry->entry_cxt, &cols);
1130
1131 /*
1132 * For non-column list publications — e.g. TABLE (without a column
1133 * list), ALL TABLES, or ALL TABLES IN SCHEMA, we consider all columns
1134 * of the table (including generated columns when
1135 * 'publish_generated_columns' parameter is true).
1136 */
1137 if (!cols)
1138 {
1139 /*
1140 * Cache the table columns for the first publication with no
1141 * specified column list to detect publication with a different
1142 * column list.
1143 */
1144 if (!relcols && (list_length(publications) > 1))
1145 {
1147
1148 relcols = pub_form_cols_map(relation,
1149 entry->include_gencols_type);
1150 MemoryContextSwitchTo(oldcxt);
1151 }
1152
1153 cols = relcols;
1154 }
1155
1156 if (first)
1157 {
1158 entry->columns = cols;
1159 first = false;
1160 }
1161 else if (!bms_equal(entry->columns, cols))
1162 ereport(ERROR,
1163 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1164 errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
1166 RelationGetRelationName(relation)));
1167 } /* loop all subscribed publications */
1168
1169 /*
1170 * If no column list publications exist, columns to be published will be
1171 * computed later according to the 'publish_generated_columns' parameter.
1172 */
1173 if (!found_pub_collist)
1174 entry->columns = NULL;
1175
1176 RelationClose(relation);
1177}
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:142
Bitmapset * pub_form_cols_map(Relation relation, PublishGencolsType include_gencols_type)
static void pgoutput_ensure_entry_cxt(PGOutputData *data, RelationSyncEntry *entry)
Definition: pgoutput.c:869

References bms_equal(), check_and_fetch_column_list(), RelationSyncEntry::columns, data, RelationSyncEntry::entry_cxt, ereport, errcode(), errmsg(), ERROR, get_namespace_name(), RelationSyncEntry::include_gencols_type, lfirst, list_length(), MemoryContextSwitchTo(), pgoutput_ensure_entry_cxt(), pub_form_cols_map(), RelationSyncEntry::publish_as_relid, RelationClose(), RelationGetNamespace, RelationGetRelationName, and RelationIdGetRelation().

Referenced by get_rel_sync_entry().

◆ pgoutput_commit_prepared_txn()

static void pgoutput_commit_prepared_txn ( LogicalDecodingContext ctx,
ReorderBufferTXN txn,
XLogRecPtr  commit_lsn 
)
static

Definition at line 668 of file pgoutput.c.

670{
671 OutputPluginUpdateProgress(ctx, false);
672
673 OutputPluginPrepareWrite(ctx, true);
674 logicalrep_write_commit_prepared(ctx->out, txn, commit_lsn);
675 OutputPluginWrite(ctx, true);
676}
void OutputPluginUpdateProgress(struct LogicalDecodingContext *ctx, bool skipped_xact)
Definition: logical.c:718
void logicalrep_write_commit_prepared(StringInfo out, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: proto.c:237

References logicalrep_write_commit_prepared(), LogicalDecodingContext::out, OutputPluginPrepareWrite(), OutputPluginUpdateProgress(), and OutputPluginWrite().

Referenced by _PG_output_plugin_init().

◆ pgoutput_commit_txn()

static void pgoutput_commit_txn ( LogicalDecodingContext ctx,
ReorderBufferTXN txn,
XLogRecPtr  commit_lsn 
)
static

Definition at line 605 of file pgoutput.c.

607{
609 bool sent_begin_txn;
610
611 Assert(txndata);
612
613 /*
614 * We don't need to send the commit message unless some relevant change
615 * from this transaction has been sent to the downstream.
616 */
617 sent_begin_txn = txndata->sent_begin_txn;
618 OutputPluginUpdateProgress(ctx, !sent_begin_txn);
619 pfree(txndata);
620 txn->output_plugin_private = NULL;
621
622 if (!sent_begin_txn)
623 {
624 elog(DEBUG1, "skipped replication of an empty transaction with XID: %u", txn->xid);
625 return;
626 }
627
628 OutputPluginPrepareWrite(ctx, true);
629 logicalrep_write_commit(ctx->out, txn, commit_lsn);
630 OutputPluginWrite(ctx, true);
631}
void pfree(void *pointer)
Definition: mcxt.c:1594
void logicalrep_write_commit(StringInfo out, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: proto.c:78
bool sent_begin_txn
Definition: pgoutput.c:216

References Assert(), DEBUG1, elog, logicalrep_write_commit(), LogicalDecodingContext::out, ReorderBufferTXN::output_plugin_private, OutputPluginPrepareWrite(), OutputPluginUpdateProgress(), OutputPluginWrite(), pfree(), PGOutputTxnData::sent_begin_txn, and ReorderBufferTXN::xid.

Referenced by _PG_output_plugin_init().

◆ pgoutput_ensure_entry_cxt()

static void pgoutput_ensure_entry_cxt ( PGOutputData data,
RelationSyncEntry entry 
)
static

Definition at line 869 of file pgoutput.c.

870{
871 Relation relation;
872
873 /* The context may already exist, in which case bail out. */
874 if (entry->entry_cxt)
875 return;
876
877 relation = RelationIdGetRelation(entry->publish_as_relid);
878
879 entry->entry_cxt = AllocSetContextCreate(data->cachectx,
880 "entry private context",
882
884 RelationGetRelationName(relation));
885}
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:170
#define MemoryContextCopyAndSetIdentifier(cxt, id)
Definition: memutils.h:101

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, data, RelationSyncEntry::entry_cxt, MemoryContextCopyAndSetIdentifier, RelationSyncEntry::publish_as_relid, RelationGetRelationName, and RelationIdGetRelation().

Referenced by pgoutput_column_list_init(), and pgoutput_row_filter_init().

◆ pgoutput_message()

static void pgoutput_message ( LogicalDecodingContext ctx,
ReorderBufferTXN txn,
XLogRecPtr  message_lsn,
bool  transactional,
const char *  prefix,
Size  sz,
const char *  message 
)
static

Definition at line 1697 of file pgoutput.c.

1700{
1703
1704 if (!data->messages)
1705 return;
1706
1707 /*
1708 * Remember the xid for the message in streaming mode. See
1709 * pgoutput_change.
1710 */
1711 if (data->in_streaming)
1712 xid = txn->xid;
1713
1714 /*
1715 * Output BEGIN if we haven't yet. Avoid for non-transactional messages.
1716 */
1717 if (transactional)
1718 {
1720
1721 /* Send BEGIN if we haven't yet */
1722 if (txndata && !txndata->sent_begin_txn)
1723 pgoutput_send_begin(ctx, txn);
1724 }
1725
1726 OutputPluginPrepareWrite(ctx, true);
1728 xid,
1729 message_lsn,
1730 transactional,
1731 prefix,
1732 sz,
1733 message);
1734 OutputPluginWrite(ctx, true);
1735}
void logicalrep_write_message(StringInfo out, TransactionId xid, XLogRecPtr lsn, bool transactional, const char *prefix, Size sz, const char *message)
Definition: proto.c:640

References data, if(), InvalidTransactionId, logicalrep_write_message(), LogicalDecodingContext::out, LogicalDecodingContext::output_plugin_private, ReorderBufferTXN::output_plugin_private, OutputPluginPrepareWrite(), OutputPluginWrite(), pgoutput_send_begin(), PGOutputTxnData::sent_begin_txn, and ReorderBufferTXN::xid.

Referenced by _PG_output_plugin_init().

◆ pgoutput_origin_filter()

static bool pgoutput_origin_filter ( LogicalDecodingContext ctx,
RepOriginId  origin_id 
)
static

Definition at line 1742 of file pgoutput.c.

1744{
1746
1747 if (data->publish_no_origin && origin_id != InvalidRepOriginId)
1748 return true;
1749
1750 return false;
1751}

References data, if(), InvalidRepOriginId, and LogicalDecodingContext::output_plugin_private.

Referenced by _PG_output_plugin_init().

◆ pgoutput_prepare_txn()

static void pgoutput_prepare_txn ( LogicalDecodingContext ctx,
ReorderBufferTXN txn,
XLogRecPtr  prepare_lsn 
)
static

Definition at line 654 of file pgoutput.c.

656{
657 OutputPluginUpdateProgress(ctx, false);
658
659 OutputPluginPrepareWrite(ctx, true);
660 logicalrep_write_prepare(ctx->out, txn, prepare_lsn);
661 OutputPluginWrite(ctx, true);
662}
void logicalrep_write_prepare(StringInfo out, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn)
Definition: proto.c:187

References logicalrep_write_prepare(), LogicalDecodingContext::out, OutputPluginPrepareWrite(), OutputPluginUpdateProgress(), and OutputPluginWrite().

Referenced by _PG_output_plugin_init().

◆ pgoutput_rollback_prepared_txn()

static void pgoutput_rollback_prepared_txn ( LogicalDecodingContext ctx,
ReorderBufferTXN txn,
XLogRecPtr  prepare_end_lsn,
TimestampTz  prepare_time 
)
static

Definition at line 682 of file pgoutput.c.

686{
687 OutputPluginUpdateProgress(ctx, false);
688
689 OutputPluginPrepareWrite(ctx, true);
690 logicalrep_write_rollback_prepared(ctx->out, txn, prepare_end_lsn,
691 prepare_time);
692 OutputPluginWrite(ctx, true);
693}
void logicalrep_write_rollback_prepared(StringInfo out, ReorderBufferTXN *txn, XLogRecPtr prepare_end_lsn, TimestampTz prepare_time)
Definition: proto.c:293

References logicalrep_write_rollback_prepared(), LogicalDecodingContext::out, OutputPluginPrepareWrite(), OutputPluginUpdateProgress(), and OutputPluginWrite().

Referenced by _PG_output_plugin_init().

◆ pgoutput_row_filter()

static bool pgoutput_row_filter ( Relation  relation,
TupleTableSlot old_slot,
TupleTableSlot **  new_slot_ptr,
RelationSyncEntry entry,
ReorderBufferChangeType action 
)
static

Definition at line 1276 of file pgoutput.c.

1279{
1280 TupleDesc desc;
1281 int i;
1282 bool old_matched,
1283 new_matched,
1284 result;
1285 TupleTableSlot *tmp_new_slot;
1286 TupleTableSlot *new_slot = *new_slot_ptr;
1287 ExprContext *ecxt;
1288 ExprState *filter_exprstate;
1289
1290 /*
1291 * We need this map to avoid relying on ReorderBufferChangeType enums
1292 * having specific values.
1293 */
1294 static const int map_changetype_pubaction[] = {
1298 };
1299
1303
1304 Assert(new_slot || old_slot);
1305
1306 /* Get the corresponding row filter */
1307 filter_exprstate = entry->exprstate[map_changetype_pubaction[*action]];
1308
1309 /* Bail out if there is no row filter */
1310 if (!filter_exprstate)
1311 return true;
1312
1313 elog(DEBUG3, "table \"%s.%s\" has row filter",
1315 RelationGetRelationName(relation));
1316
1318
1319 ecxt = GetPerTupleExprContext(entry->estate);
1320
1321 /*
1322 * For the following occasions where there is only one tuple, we can
1323 * evaluate the row filter for that tuple and return.
1324 *
1325 * For inserts, we only have the new tuple.
1326 *
1327 * For updates, we can have only a new tuple when none of the replica
1328 * identity columns changed and none of those columns have external data
1329 * but we still need to evaluate the row filter for the new tuple as the
1330 * existing values of those columns might not match the filter. Also,
1331 * users can use constant expressions in the row filter, so we anyway need
1332 * to evaluate it for the new tuple.
1333 *
1334 * For deletes, we only have the old tuple.
1335 */
1336 if (!new_slot || !old_slot)
1337 {
1338 ecxt->ecxt_scantuple = new_slot ? new_slot : old_slot;
1339 result = pgoutput_row_filter_exec_expr(filter_exprstate, ecxt);
1340
1341 return result;
1342 }
1343
1344 /*
1345 * Both the old and new tuples must be valid only for updates and need to
1346 * be checked against the row filter.
1347 */
1348 Assert(map_changetype_pubaction[*action] == PUBACTION_UPDATE);
1349
1350 slot_getallattrs(new_slot);
1351 slot_getallattrs(old_slot);
1352
1353 tmp_new_slot = NULL;
1354 desc = RelationGetDescr(relation);
1355
1356 /*
1357 * The new tuple might not have all the replica identity columns, in which
1358 * case it needs to be copied over from the old tuple.
1359 */
1360 for (i = 0; i < desc->natts; i++)
1361 {
1363
1364 /*
1365 * if the column in the new tuple or old tuple is null, nothing to do
1366 */
1367 if (new_slot->tts_isnull[i] || old_slot->tts_isnull[i])
1368 continue;
1369
1370 /*
1371 * Unchanged toasted replica identity columns are only logged in the
1372 * old tuple. Copy this over to the new tuple. The changed (or WAL
1373 * Logged) toast values are always assembled in memory and set as
1374 * VARTAG_INDIRECT. See ReorderBufferToastReplace.
1375 */
1376 if (att->attlen == -1 &&
1379 {
1380 if (!tmp_new_slot)
1381 {
1382 tmp_new_slot = MakeSingleTupleTableSlot(desc, &TTSOpsVirtual);
1383 ExecClearTuple(tmp_new_slot);
1384
1385 memcpy(tmp_new_slot->tts_values, new_slot->tts_values,
1386 desc->natts * sizeof(Datum));
1387 memcpy(tmp_new_slot->tts_isnull, new_slot->tts_isnull,
1388 desc->natts * sizeof(bool));
1389 }
1390
1391 tmp_new_slot->tts_values[i] = old_slot->tts_values[i];
1392 tmp_new_slot->tts_isnull[i] = old_slot->tts_isnull[i];
1393 }
1394 }
1395
1396 ecxt->ecxt_scantuple = old_slot;
1397 old_matched = pgoutput_row_filter_exec_expr(filter_exprstate, ecxt);
1398
1399 if (tmp_new_slot)
1400 {
1401 ExecStoreVirtualTuple(tmp_new_slot);
1402 ecxt->ecxt_scantuple = tmp_new_slot;
1403 }
1404 else
1405 ecxt->ecxt_scantuple = new_slot;
1406
1407 new_matched = pgoutput_row_filter_exec_expr(filter_exprstate, ecxt);
1408
1409 /*
1410 * Case 1: if both tuples don't match the row filter, bailout. Send
1411 * nothing.
1412 */
1413 if (!old_matched && !new_matched)
1414 return false;
1415
1416 /*
1417 * Case 2: if the old tuple doesn't satisfy the row filter but the new
1418 * tuple does, transform the UPDATE into INSERT.
1419 *
1420 * Use the newly transformed tuple that must contain the column values for
1421 * all the replica identity columns. This is required to ensure that the
1422 * while inserting the tuple in the downstream node, we have all the
1423 * required column values.
1424 */
1425 if (!old_matched && new_matched)
1426 {
1428
1429 if (tmp_new_slot)
1430 *new_slot_ptr = tmp_new_slot;
1431 }
1432
1433 /*
1434 * Case 3: if the old tuple satisfies the row filter but the new tuple
1435 * doesn't, transform the UPDATE into DELETE.
1436 *
1437 * This transformation does not require another tuple. The Old tuple will
1438 * be used for DELETE.
1439 */
1440 else if (old_matched && !new_matched)
1442
1443 /*
1444 * Case 4: if both tuples match the row filter, transformation isn't
1445 * required. (*action is default UPDATE).
1446 */
1447
1448 return true;
1449}
#define DEBUG3
Definition: elog.h:28
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1741
#define ResetPerTupleExprContext(estate)
Definition: executor.h:662
#define GetPerTupleExprContext(estate)
Definition: executor.h:653
static bool pgoutput_row_filter_exec_expr(ExprState *state, ExprContext *econtext)
Definition: pgoutput.c:846
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322
int16 attlen
Definition: tupdesc.h:71
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:273
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:175
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:458
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:372
static bool VARATT_IS_EXTERNAL_ONDISK(const void *PTR)
Definition: varatt.h:361

References generate_unaccent_rules::action, Assert(), CompactAttribute::attlen, DatumGetPointer(), DEBUG3, ExprContext::ecxt_scantuple, elog, RelationSyncEntry::estate, ExecClearTuple(), ExecStoreVirtualTuple(), RelationSyncEntry::exprstate, get_namespace_name(), GetPerTupleExprContext, i, MakeSingleTupleTableSlot(), TupleDescData::natts, pgoutput_row_filter_exec_expr(), PUBACTION_DELETE, PUBACTION_INSERT, PUBACTION_UPDATE, RelationGetDescr, RelationGetNamespace, RelationGetRelationName, REORDER_BUFFER_CHANGE_DELETE, REORDER_BUFFER_CHANGE_INSERT, REORDER_BUFFER_CHANGE_UPDATE, ResetPerTupleExprContext, slot_getallattrs(), TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, TTSOpsVirtual, TupleDescCompactAttr(), and VARATT_IS_EXTERNAL_ONDISK().

Referenced by pgoutput_change().

◆ pgoutput_row_filter_exec_expr()

static bool pgoutput_row_filter_exec_expr ( ExprState state,
ExprContext econtext 
)
static

Definition at line 846 of file pgoutput.c.

847{
848 Datum ret;
849 bool isnull;
850
851 Assert(state != NULL);
852
853 ret = ExecEvalExprSwitchContext(state, econtext, &isnull);
854
855 elog(DEBUG3, "row filter evaluates to %s (isnull: %s)",
856 isnull ? "false" : DatumGetBool(ret) ? "true" : "false",
857 isnull ? "true" : "false");
858
859 if (isnull)
860 return false;
861
862 return DatumGetBool(ret);
863}
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:433
static bool DatumGetBool(Datum X)
Definition: postgres.h:100
Definition: regguts.h:323

References Assert(), DatumGetBool(), DEBUG3, elog, and ExecEvalExprSwitchContext().

Referenced by pgoutput_row_filter().

◆ pgoutput_row_filter_init()

static void pgoutput_row_filter_init ( PGOutputData data,
List publications,
RelationSyncEntry entry 
)
static

Definition at line 891 of file pgoutput.c.

893{
894 ListCell *lc;
895 List *rfnodes[] = {NIL, NIL, NIL}; /* One per pubaction */
896 bool no_filter[] = {false, false, false}; /* One per pubaction */
897 MemoryContext oldctx;
898 int idx;
899 bool has_filter = true;
900 Oid schemaid = get_rel_namespace(entry->publish_as_relid);
901
902 /*
903 * Find if there are any row filters for this relation. If there are, then
904 * prepare the necessary ExprState and cache it in entry->exprstate. To
905 * build an expression state, we need to ensure the following:
906 *
907 * All the given publication-table mappings must be checked.
908 *
909 * Multiple publications might have multiple row filters for this
910 * relation. Since row filter usage depends on the DML operation, there
911 * are multiple lists (one for each operation) to which row filters will
912 * be appended.
913 *
914 * FOR ALL TABLES and FOR TABLES IN SCHEMA implies "don't use row filter
915 * expression" so it takes precedence.
916 */
917 foreach(lc, publications)
918 {
919 Publication *pub = lfirst(lc);
920 HeapTuple rftuple = NULL;
921 Datum rfdatum = 0;
922 bool pub_no_filter = true;
923
924 /*
925 * If the publication is FOR ALL TABLES, or the publication includes a
926 * FOR TABLES IN SCHEMA where the table belongs to the referred
927 * schema, then it is treated the same as if there are no row filters
928 * (even if other publications have a row filter).
929 */
930 if (!pub->alltables &&
931 !SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP,
932 ObjectIdGetDatum(schemaid),
933 ObjectIdGetDatum(pub->oid)))
934 {
935 /*
936 * Check for the presence of a row filter in this publication.
937 */
938 rftuple = SearchSysCache2(PUBLICATIONRELMAP,
940 ObjectIdGetDatum(pub->oid));
941
942 if (HeapTupleIsValid(rftuple))
943 {
944 /* Null indicates no filter. */
945 rfdatum = SysCacheGetAttr(PUBLICATIONRELMAP, rftuple,
946 Anum_pg_publication_rel_prqual,
947 &pub_no_filter);
948 }
949 }
950
951 if (pub_no_filter)
952 {
953 if (rftuple)
954 ReleaseSysCache(rftuple);
955
956 no_filter[PUBACTION_INSERT] |= pub->pubactions.pubinsert;
957 no_filter[PUBACTION_UPDATE] |= pub->pubactions.pubupdate;
958 no_filter[PUBACTION_DELETE] |= pub->pubactions.pubdelete;
959
960 /*
961 * Quick exit if all the DML actions are publicized via this
962 * publication.
963 */
964 if (no_filter[PUBACTION_INSERT] &&
965 no_filter[PUBACTION_UPDATE] &&
966 no_filter[PUBACTION_DELETE])
967 {
968 has_filter = false;
969 break;
970 }
971
972 /* No additional work for this publication. Next one. */
973 continue;
974 }
975
976 /* Form the per pubaction row filter lists. */
977 if (pub->pubactions.pubinsert && !no_filter[PUBACTION_INSERT])
978 rfnodes[PUBACTION_INSERT] = lappend(rfnodes[PUBACTION_INSERT],
979 TextDatumGetCString(rfdatum));
980 if (pub->pubactions.pubupdate && !no_filter[PUBACTION_UPDATE])
981 rfnodes[PUBACTION_UPDATE] = lappend(rfnodes[PUBACTION_UPDATE],
982 TextDatumGetCString(rfdatum));
983 if (pub->pubactions.pubdelete && !no_filter[PUBACTION_DELETE])
984 rfnodes[PUBACTION_DELETE] = lappend(rfnodes[PUBACTION_DELETE],
985 TextDatumGetCString(rfdatum));
986
987 ReleaseSysCache(rftuple);
988 } /* loop all subscribed publications */
989
990 /* Clean the row filter */
991 for (idx = 0; idx < NUM_ROWFILTER_PUBACTIONS; idx++)
992 {
993 if (no_filter[idx])
994 {
995 list_free_deep(rfnodes[idx]);
996 rfnodes[idx] = NIL;
997 }
998 }
999
1000 if (has_filter)
1001 {
1003
1005
1006 /*
1007 * Now all the filters for all pubactions are known. Combine them when
1008 * their pubactions are the same.
1009 */
1010 oldctx = MemoryContextSwitchTo(entry->entry_cxt);
1011 entry->estate = create_estate_for_relation(relation);
1012 for (idx = 0; idx < NUM_ROWFILTER_PUBACTIONS; idx++)
1013 {
1014 List *filters = NIL;
1015 Expr *rfnode;
1016
1017 if (rfnodes[idx] == NIL)
1018 continue;
1019
1020 foreach(lc, rfnodes[idx])
1021 filters = lappend(filters, expand_generated_columns_in_expr(stringToNode((char *) lfirst(lc)), relation, 1));
1022
1023 /* combine the row filter and cache the ExprState */
1024 rfnode = make_orclause(filters);
1025 entry->exprstate[idx] = ExecPrepareExpr(rfnode, entry->estate);
1026 } /* for each pubaction */
1027 MemoryContextSwitchTo(oldctx);
1028
1029 RelationClose(relation);
1030 }
1031}
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:262
#define TextDatumGetCString(d)
Definition: builtins.h:98
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:765
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void list_free_deep(List *list)
Definition: list.c:1560
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:743
#define NUM_ROWFILTER_PUBACTIONS
Definition: pgoutput.c:106
static EState * create_estate_for_relation(Relation rel)
Definition: pgoutput.c:815
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
void * stringToNode(const char *str)
Definition: read.c:90
Node * expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:595
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:230
#define SearchSysCacheExists2(cacheId, key1, key2)
Definition: syscache.h:102

References Publication::alltables, create_estate_for_relation(), data, RelationSyncEntry::entry_cxt, RelationSyncEntry::estate, ExecPrepareExpr(), expand_generated_columns_in_expr(), RelationSyncEntry::exprstate, get_rel_namespace(), HeapTupleIsValid, idx(), lappend(), lfirst, list_free_deep(), make_orclause(), MemoryContextSwitchTo(), NIL, NUM_ROWFILTER_PUBACTIONS, ObjectIdGetDatum(), Publication::oid, pgoutput_ensure_entry_cxt(), PUBACTION_DELETE, PUBACTION_INSERT, PUBACTION_UPDATE, Publication::pubactions, PublicationActions::pubdelete, PublicationActions::pubinsert, RelationSyncEntry::publish_as_relid, PublicationActions::pubupdate, RelationClose(), RelationIdGetRelation(), ReleaseSysCache(), SearchSysCache2(), SearchSysCacheExists2, stringToNode(), SysCacheGetAttr(), and TextDatumGetCString.

Referenced by get_rel_sync_entry().

◆ pgoutput_send_begin()

static void pgoutput_send_begin ( LogicalDecodingContext ctx,
ReorderBufferTXN txn 
)
static

Definition at line 583 of file pgoutput.c.

584{
585 bool send_replication_origin = txn->origin_id != InvalidRepOriginId;
587
588 Assert(txndata);
589 Assert(!txndata->sent_begin_txn);
590
591 OutputPluginPrepareWrite(ctx, !send_replication_origin);
592 logicalrep_write_begin(ctx->out, txn);
593 txndata->sent_begin_txn = true;
594
595 send_repl_origin(ctx, txn->origin_id, txn->origin_lsn,
596 send_replication_origin);
597
598 OutputPluginWrite(ctx, true);
599}
void logicalrep_write_begin(StringInfo out, ReorderBufferTXN *txn)
Definition: proto.c:49

References Assert(), InvalidRepOriginId, logicalrep_write_begin(), ReorderBufferTXN::origin_id, ReorderBufferTXN::origin_lsn, LogicalDecodingContext::out, ReorderBufferTXN::output_plugin_private, OutputPluginPrepareWrite(), OutputPluginWrite(), send_repl_origin(), and PGOutputTxnData::sent_begin_txn.

Referenced by pgoutput_change(), pgoutput_message(), and pgoutput_truncate().

◆ pgoutput_shutdown()

static void pgoutput_shutdown ( LogicalDecodingContext ctx)
static

Definition at line 1761 of file pgoutput.c.

1762{
1764 {
1766 RelationSyncCache = NULL;
1767 }
1768}
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:865

References hash_destroy(), and RelationSyncCache.

Referenced by _PG_output_plugin_init().

◆ pgoutput_startup()

static void pgoutput_startup ( LogicalDecodingContext ctx,
OutputPluginOptions opt,
bool  is_init 
)
static

Definition at line 433 of file pgoutput.c.

435{
437 static bool publication_callback_registered = false;
438
439 /* Create our memory context for private allocations. */
440 data->context = AllocSetContextCreate(ctx->context,
441 "logical replication output context",
443
444 data->cachectx = AllocSetContextCreate(ctx->context,
445 "logical replication cache context",
447
448 data->pubctx = AllocSetContextCreate(ctx->context,
449 "logical replication publication list context",
451
453
454 /* This plugin uses binary protocol. */
456
457 /*
458 * This is replication start and not slot initialization.
459 *
460 * Parse and validate options passed by the client.
461 */
462 if (!is_init)
463 {
464 /* Parse the params and ERROR if we see any we don't recognize */
466
467 /* Check if we support requested protocol */
468 if (data->protocol_version > LOGICALREP_PROTO_MAX_VERSION_NUM)
470 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
471 errmsg("client sent proto_version=%d but server only supports protocol %d or lower",
472 data->protocol_version, LOGICALREP_PROTO_MAX_VERSION_NUM)));
473
474 if (data->protocol_version < LOGICALREP_PROTO_MIN_VERSION_NUM)
476 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
477 errmsg("client sent proto_version=%d but server only supports protocol %d or higher",
478 data->protocol_version, LOGICALREP_PROTO_MIN_VERSION_NUM)));
479
480 /*
481 * Decide whether to enable streaming. It is disabled by default, in
482 * which case we just update the flag in decoding context. Otherwise
483 * we only allow it with sufficient version of the protocol, and when
484 * the output plugin supports it.
485 */
486 if (data->streaming == LOGICALREP_STREAM_OFF)
487 ctx->streaming = false;
488 else if (data->streaming == LOGICALREP_STREAM_ON &&
489 data->protocol_version < LOGICALREP_PROTO_STREAM_VERSION_NUM)
491 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
492 errmsg("requested proto_version=%d does not support streaming, need %d or higher",
493 data->protocol_version, LOGICALREP_PROTO_STREAM_VERSION_NUM)));
494 else if (data->streaming == LOGICALREP_STREAM_PARALLEL &&
497 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
498 errmsg("requested proto_version=%d does not support parallel streaming, need %d or higher",
500 else if (!ctx->streaming)
502 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
503 errmsg("streaming requested, but not supported by output plugin")));
504
505 /*
506 * Here, we just check whether the two-phase option is passed by
507 * plugin and decide whether to enable it at later point of time. It
508 * remains enabled if the previous start-up has done so. But we only
509 * allow the option to be passed in with sufficient version of the
510 * protocol, and when the output plugin supports it.
511 */
512 if (!data->two_phase)
513 ctx->twophase_opt_given = false;
514 else if (data->protocol_version < LOGICALREP_PROTO_TWOPHASE_VERSION_NUM)
516 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
517 errmsg("requested proto_version=%d does not support two-phase commit, need %d or higher",
518 data->protocol_version, LOGICALREP_PROTO_TWOPHASE_VERSION_NUM)));
519 else if (!ctx->twophase)
521 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
522 errmsg("two-phase commit requested, but not supported by output plugin")));
523 else
524 ctx->twophase_opt_given = true;
525
526 /* Init publication state. */
527 data->publications = NIL;
528 publications_valid = false;
529
530 /*
531 * Register callback for pg_publication if we didn't already do that
532 * during some previous call in this process.
533 */
534 if (!publication_callback_registered)
535 {
536 CacheRegisterSyscacheCallback(PUBLICATIONOID,
538 (Datum) 0);
540 (Datum) 0);
541 publication_callback_registered = true;
542 }
543
544 /* Initialize relation schema cache. */
546 }
547 else
548 {
549 /*
550 * Disable the streaming and prepared transactions during the slot
551 * initialization mode.
552 */
553 ctx->streaming = false;
554 ctx->twophase = false;
555 }
556}
void CacheRegisterRelSyncCallback(RelSyncCallbackFunction func, Datum arg)
Definition: inval.c:1875
#define LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM
Definition: logicalproto.h:44
#define LOGICALREP_PROTO_MIN_VERSION_NUM
Definition: logicalproto.h:40
#define LOGICALREP_PROTO_STREAM_VERSION_NUM
Definition: logicalproto.h:42
#define LOGICALREP_PROTO_TWOPHASE_VERSION_NUM
Definition: logicalproto.h:43
#define LOGICALREP_PROTO_MAX_VERSION_NUM
Definition: logicalproto.h:45
void * palloc0(Size size)
Definition: mcxt.c:1395
MemoryContext CacheMemoryContext
Definition: mcxt.c:169
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
@ OUTPUT_PLUGIN_BINARY_OUTPUT
Definition: output_plugin.h:19
static void parse_output_parameters(List *options, PGOutputData *data)
Definition: pgoutput.c:289
static void init_rel_sync_cache(MemoryContext cachectx)
Definition: pgoutput.c:1951
static void publication_invalidation_cb(Datum arg, int cacheid, uint32 hashvalue)
Definition: pgoutput.c:1808
List * output_plugin_options
Definition: logical.h:59
OutputPluginOutputType output_type
Definition: output_plugin.h:28

References ALLOCSET_DEFAULT_SIZES, ALLOCSET_SMALL_SIZES, AllocSetContextCreate, CacheMemoryContext, CacheRegisterRelSyncCallback(), CacheRegisterSyscacheCallback(), LogicalDecodingContext::context, data, ereport, errcode(), errmsg(), ERROR, init_rel_sync_cache(), LOGICALREP_PROTO_MAX_VERSION_NUM, LOGICALREP_PROTO_MIN_VERSION_NUM, LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM, LOGICALREP_PROTO_STREAM_VERSION_NUM, LOGICALREP_PROTO_TWOPHASE_VERSION_NUM, NIL, OUTPUT_PLUGIN_BINARY_OUTPUT, LogicalDecodingContext::output_plugin_options, LogicalDecodingContext::output_plugin_private, OutputPluginOptions::output_type, palloc0(), parse_output_parameters(), publication_invalidation_cb(), publications_valid, rel_sync_cache_relation_cb(), LogicalDecodingContext::streaming, LogicalDecodingContext::twophase, and LogicalDecodingContext::twophase_opt_given.

Referenced by _PG_output_plugin_init().

◆ pgoutput_stream_abort()

static void pgoutput_stream_abort ( struct LogicalDecodingContext ctx,
ReorderBufferTXN txn,
XLogRecPtr  abort_lsn 
)
static

Definition at line 1870 of file pgoutput.c.

1873{
1874 ReorderBufferTXN *toptxn;
1876 bool write_abort_info = (data->streaming == LOGICALREP_STREAM_PARALLEL);
1877
1878 /*
1879 * The abort should happen outside streaming block, even for streamed
1880 * transactions. The transaction has to be marked as streamed, though.
1881 */
1882 Assert(!data->in_streaming);
1883
1884 /* determine the toplevel transaction */
1885 toptxn = rbtxn_get_toptxn(txn);
1886
1887 Assert(rbtxn_is_streamed(toptxn));
1888
1889 OutputPluginPrepareWrite(ctx, true);
1890 logicalrep_write_stream_abort(ctx->out, toptxn->xid, txn->xid, abort_lsn,
1891 txn->xact_time.abort_time, write_abort_info);
1892
1893 OutputPluginWrite(ctx, true);
1894
1895 cleanup_rel_sync_cache(toptxn->xid, false);
1896}
static void cleanup_rel_sync_cache(TransactionId xid, bool is_commit)
Definition: pgoutput.c:2326
void logicalrep_write_stream_abort(StringInfo out, TransactionId xid, TransactionId subxid, XLogRecPtr abort_lsn, TimestampTz abort_time, bool write_abort_info)
Definition: proto.c:1158
#define rbtxn_is_streamed(txn)
union ReorderBufferTXN::@119 xact_time
TimestampTz abort_time

References ReorderBufferTXN::abort_time, Assert(), cleanup_rel_sync_cache(), data, logicalrep_write_stream_abort(), LogicalDecodingContext::out, LogicalDecodingContext::output_plugin_private, OutputPluginPrepareWrite(), OutputPluginWrite(), rbtxn_get_toptxn, rbtxn_is_streamed, ReorderBufferTXN::xact_time, and ReorderBufferTXN::xid.

Referenced by _PG_output_plugin_init().

◆ pgoutput_stream_commit()

static void pgoutput_stream_commit ( struct LogicalDecodingContext ctx,
ReorderBufferTXN txn,
XLogRecPtr  commit_lsn 
)
static

Definition at line 1903 of file pgoutput.c.

1906{
1908
1909 /*
1910 * The commit should happen outside streaming block, even for streamed
1911 * transactions. The transaction has to be marked as streamed, though.
1912 */
1913 Assert(!data->in_streaming);
1915
1916 OutputPluginUpdateProgress(ctx, false);
1917
1918 OutputPluginPrepareWrite(ctx, true);
1919 logicalrep_write_stream_commit(ctx->out, txn, commit_lsn);
1920 OutputPluginWrite(ctx, true);
1921
1922 cleanup_rel_sync_cache(txn->xid, true);
1923}
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:223
void logicalrep_write_stream_commit(StringInfo out, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: proto.c:1104

References Assert(), cleanup_rel_sync_cache(), data, logicalrep_write_stream_commit(), LogicalDecodingContext::out, LogicalDecodingContext::output_plugin_private, OutputPluginPrepareWrite(), OutputPluginUpdateProgress(), OutputPluginWrite(), PG_USED_FOR_ASSERTS_ONLY, rbtxn_is_streamed, and ReorderBufferTXN::xid.

Referenced by _PG_output_plugin_init().

◆ pgoutput_stream_prepare_txn()

static void pgoutput_stream_prepare_txn ( LogicalDecodingContext ctx,
ReorderBufferTXN txn,
XLogRecPtr  prepare_lsn 
)
static

Definition at line 1931 of file pgoutput.c.

1934{
1936
1937 OutputPluginUpdateProgress(ctx, false);
1938 OutputPluginPrepareWrite(ctx, true);
1939 logicalrep_write_stream_prepare(ctx->out, txn, prepare_lsn);
1940 OutputPluginWrite(ctx, true);
1941}
void logicalrep_write_stream_prepare(StringInfo out, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn)
Definition: proto.c:353

References Assert(), logicalrep_write_stream_prepare(), LogicalDecodingContext::out, OutputPluginPrepareWrite(), OutputPluginUpdateProgress(), OutputPluginWrite(), and rbtxn_is_streamed.

Referenced by _PG_output_plugin_init().

◆ pgoutput_stream_start()

static void pgoutput_stream_start ( struct LogicalDecodingContext ctx,
ReorderBufferTXN txn 
)
static

Definition at line 1817 of file pgoutput.c.

1819{
1821 bool send_replication_origin = txn->origin_id != InvalidRepOriginId;
1822
1823 /* we can't nest streaming of transactions */
1824 Assert(!data->in_streaming);
1825
1826 /*
1827 * If we already sent the first stream for this transaction then don't
1828 * send the origin id in the subsequent streams.
1829 */
1830 if (rbtxn_is_streamed(txn))
1831 send_replication_origin = false;
1832
1833 OutputPluginPrepareWrite(ctx, !send_replication_origin);
1835
1837 send_replication_origin);
1838
1839 OutputPluginWrite(ctx, true);
1840
1841 /* we're streaming a chunk of transaction now */
1842 data->in_streaming = true;
1843}
void logicalrep_write_stream_start(StringInfo out, TransactionId xid, bool first_segment)
Definition: proto.c:1061
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References Assert(), data, InvalidRepOriginId, InvalidXLogRecPtr, logicalrep_write_stream_start(), ReorderBufferTXN::origin_id, LogicalDecodingContext::out, LogicalDecodingContext::output_plugin_private, OutputPluginPrepareWrite(), OutputPluginWrite(), rbtxn_is_streamed, send_repl_origin(), and ReorderBufferTXN::xid.

Referenced by _PG_output_plugin_init().

◆ pgoutput_stream_stop()

static void pgoutput_stream_stop ( struct LogicalDecodingContext ctx,
ReorderBufferTXN txn 
)
static

Definition at line 1849 of file pgoutput.c.

1851{
1853
1854 /* we should be streaming a transaction */
1855 Assert(data->in_streaming);
1856
1857 OutputPluginPrepareWrite(ctx, true);
1859 OutputPluginWrite(ctx, true);
1860
1861 /* we've stopped streaming a transaction */
1862 data->in_streaming = false;
1863}
void logicalrep_write_stream_stop(StringInfo out)
Definition: proto.c:1095

References Assert(), data, logicalrep_write_stream_stop(), LogicalDecodingContext::out, LogicalDecodingContext::output_plugin_private, OutputPluginPrepareWrite(), and OutputPluginWrite().

Referenced by _PG_output_plugin_init().

◆ pgoutput_truncate()

static void pgoutput_truncate ( LogicalDecodingContext ctx,
ReorderBufferTXN txn,
int  nrelations,
Relation  relations[],
ReorderBufferChange change 
)
static

Definition at line 1629 of file pgoutput.c.

1631{
1634 MemoryContext old;
1635 RelationSyncEntry *relentry;
1636 int i;
1637 int nrelids;
1638 Oid *relids;
1640
1641 /* Remember the xid for the change in streaming mode. See pgoutput_change. */
1642 if (data->in_streaming)
1643 xid = change->txn->xid;
1644
1645 old = MemoryContextSwitchTo(data->context);
1646
1647 relids = palloc0(nrelations * sizeof(Oid));
1648 nrelids = 0;
1649
1650 for (i = 0; i < nrelations; i++)
1651 {
1652 Relation relation = relations[i];
1653 Oid relid = RelationGetRelid(relation);
1654
1655 if (!is_publishable_relation(relation))
1656 continue;
1657
1658 relentry = get_rel_sync_entry(data, relation);
1659
1660 if (!relentry->pubactions.pubtruncate)
1661 continue;
1662
1663 /*
1664 * Don't send partitions if the publication wants to send only the
1665 * root tables through it.
1666 */
1667 if (relation->rd_rel->relispartition &&
1668 relentry->publish_as_relid != relid)
1669 continue;
1670
1671 relids[nrelids++] = relid;
1672
1673 /* Send BEGIN if we haven't yet */
1674 if (txndata && !txndata->sent_begin_txn)
1675 pgoutput_send_begin(ctx, txn);
1676
1677 maybe_send_schema(ctx, change, relation, relentry);
1678 }
1679
1680 if (nrelids > 0)
1681 {
1682 OutputPluginPrepareWrite(ctx, true);
1684 xid,
1685 nrelids,
1686 relids,
1687 change->data.truncate.cascade,
1688 change->data.truncate.restart_seqs);
1689 OutputPluginWrite(ctx, true);
1690 }
1691
1693 MemoryContextReset(data->context);
1694}
void logicalrep_write_truncate(StringInfo out, TransactionId xid, int nrelids, Oid relids[], bool cascade, bool restart_seqs)
Definition: proto.c:583
struct ReorderBufferChange::@113::@115 truncate

References ReorderBufferChange::cascade, ReorderBufferChange::data, data, get_rel_sync_entry(), i, InvalidTransactionId, is_publishable_relation(), logicalrep_write_truncate(), maybe_send_schema(), MemoryContextReset(), MemoryContextSwitchTo(), LogicalDecodingContext::out, LogicalDecodingContext::output_plugin_private, ReorderBufferTXN::output_plugin_private, OutputPluginPrepareWrite(), OutputPluginWrite(), palloc0(), pgoutput_send_begin(), RelationSyncEntry::pubactions, RelationSyncEntry::publish_as_relid, PublicationActions::pubtruncate, RelationData::rd_rel, RelationGetRelid, ReorderBufferChange::restart_seqs, ReorderBufferChange::truncate, ReorderBufferChange::txn, and ReorderBufferTXN::xid.

Referenced by _PG_output_plugin_init().

◆ publication_invalidation_cb()

static void publication_invalidation_cb ( Datum  arg,
int  cacheid,
uint32  hashvalue 
)
static

Definition at line 1808 of file pgoutput.c.

1809{
1810 publications_valid = false;
1811}

References publications_valid.

Referenced by pgoutput_startup().

◆ rel_sync_cache_publication_cb()

static void rel_sync_cache_publication_cb ( Datum  arg,
int  cacheid,
uint32  hashvalue 
)
static

Definition at line 2411 of file pgoutput.c.

2412{
2413 HASH_SEQ_STATUS status;
2414 RelationSyncEntry *entry;
2415
2416 /*
2417 * We can get here if the plugin was used in SQL interface as the
2418 * RelationSyncCache is destroyed when the decoding finishes, but there is
2419 * no way to unregister the invalidation callbacks.
2420 */
2421 if (RelationSyncCache == NULL)
2422 return;
2423
2424 /*
2425 * We have no easy way to identify which cache entries this invalidation
2426 * event might have affected, so just mark them all invalid.
2427 */
2429 while ((entry = (RelationSyncEntry *) hash_seq_search(&status)) != NULL)
2430 {
2431 entry->replicate_valid = false;
2432 }
2433}

References hash_seq_init(), hash_seq_search(), RelationSyncCache, and RelationSyncEntry::replicate_valid.

Referenced by init_rel_sync_cache().

◆ rel_sync_cache_relation_cb()

static void rel_sync_cache_relation_cb ( Datum  arg,
Oid  relid 
)
static

Definition at line 2361 of file pgoutput.c.

2362{
2363 RelationSyncEntry *entry;
2364
2365 /*
2366 * We can get here if the plugin was used in SQL interface as the
2367 * RelationSyncCache is destroyed when the decoding finishes, but there is
2368 * no way to unregister the relcache invalidation callback.
2369 */
2370 if (RelationSyncCache == NULL)
2371 return;
2372
2373 /*
2374 * Nobody keeps pointers to entries in this hash table around outside
2375 * logical decoding callback calls - but invalidation events can come in
2376 * *during* a callback if we do any syscache access in the callback.
2377 * Because of that we must mark the cache entry as invalid but not damage
2378 * any of its substructure here. The next get_rel_sync_entry() call will
2379 * rebuild it all.
2380 */
2381 if (OidIsValid(relid))
2382 {
2383 /*
2384 * Getting invalidations for relations that aren't in the table is
2385 * entirely normal. So we don't care if it's found or not.
2386 */
2388 HASH_FIND, NULL);
2389 if (entry != NULL)
2390 entry->replicate_valid = false;
2391 }
2392 else
2393 {
2394 /* Whole cache must be flushed. */
2395 HASH_SEQ_STATUS status;
2396
2398 while ((entry = (RelationSyncEntry *) hash_seq_search(&status)) != NULL)
2399 {
2400 entry->replicate_valid = false;
2401 }
2402 }
2403}
#define OidIsValid(objectId)
Definition: c.h:775
@ HASH_FIND
Definition: hsearch.h:113

References HASH_FIND, hash_search(), hash_seq_init(), hash_seq_search(), OidIsValid, RelationSyncCache, and RelationSyncEntry::replicate_valid.

Referenced by init_rel_sync_cache(), and pgoutput_startup().

◆ send_relation_and_attrs()

static void send_relation_and_attrs ( Relation  relation,
TransactionId  xid,
LogicalDecodingContext ctx,
RelationSyncEntry relentry 
)
static

Definition at line 771 of file pgoutput.c.

774{
775 TupleDesc desc = RelationGetDescr(relation);
776 Bitmapset *columns = relentry->columns;
777 PublishGencolsType include_gencols_type = relentry->include_gencols_type;
778 int i;
779
780 /*
781 * Write out type info if needed. We do that only for user-created types.
782 * We use FirstGenbkiObjectId as the cutoff, so that we only consider
783 * objects with hand-assigned OIDs to be "built in", not for instance any
784 * function or type defined in the information_schema. This is important
785 * because only hand-assigned OIDs can be expected to remain stable across
786 * major versions.
787 */
788 for (i = 0; i < desc->natts; i++)
789 {
790 Form_pg_attribute att = TupleDescAttr(desc, i);
791
792 if (!logicalrep_should_publish_column(att, columns,
793 include_gencols_type))
794 continue;
795
796 if (att->atttypid < FirstGenbkiObjectId)
797 continue;
798
799 OutputPluginPrepareWrite(ctx, false);
800 logicalrep_write_typ(ctx->out, xid, att->atttypid);
801 OutputPluginWrite(ctx, false);
802 }
803
804 OutputPluginPrepareWrite(ctx, false);
805 logicalrep_write_rel(ctx->out, xid, relation, columns,
806 include_gencols_type);
807 OutputPluginWrite(ctx, false);
808}
void logicalrep_write_rel(StringInfo out, TransactionId xid, Relation rel, Bitmapset *columns, PublishGencolsType include_gencols_type)
Definition: proto.c:667
void logicalrep_write_typ(StringInfo out, TransactionId xid, Oid typoid)
Definition: proto.c:723
bool logicalrep_should_publish_column(Form_pg_attribute att, Bitmapset *columns, PublishGencolsType include_gencols_type)
Definition: proto.c:1279
#define FirstGenbkiObjectId
Definition: transam.h:195

References RelationSyncEntry::columns, FirstGenbkiObjectId, i, RelationSyncEntry::include_gencols_type, logicalrep_should_publish_column(), logicalrep_write_rel(), logicalrep_write_typ(), TupleDescData::natts, LogicalDecodingContext::out, OutputPluginPrepareWrite(), OutputPluginWrite(), RelationGetDescr, and TupleDescAttr().

Referenced by maybe_send_schema().

◆ send_repl_origin()

static void send_repl_origin ( LogicalDecodingContext ctx,
RepOriginId  origin_id,
XLogRecPtr  origin_lsn,
bool  send_origin 
)
static

Definition at line 2437 of file pgoutput.c.

2439{
2440 if (send_origin)
2441 {
2442 char *origin;
2443
2444 /*----------
2445 * XXX: which behaviour do we want here?
2446 *
2447 * Alternatives:
2448 * - don't send origin message if origin name not found
2449 * (that's what we do now)
2450 * - throw error - that will break replication, not good
2451 * - send some special "unknown" origin
2452 *----------
2453 */
2454 if (replorigin_by_oid(origin_id, true, &origin))
2455 {
2456 /* Message boundary */
2457 OutputPluginWrite(ctx, false);
2458 OutputPluginPrepareWrite(ctx, true);
2459
2460 logicalrep_write_origin(ctx->out, origin, origin_lsn);
2461 }
2462 }
2463}
bool replorigin_by_oid(RepOriginId roident, bool missing_ok, char **roname)
Definition: origin.c:493
void logicalrep_write_origin(StringInfo out, const char *origin, XLogRecPtr origin_lsn)
Definition: proto.c:374

References logicalrep_write_origin(), LogicalDecodingContext::out, OutputPluginPrepareWrite(), OutputPluginWrite(), and replorigin_by_oid().

Referenced by pgoutput_begin_prepare_txn(), pgoutput_send_begin(), and pgoutput_stream_start().

◆ set_schema_sent_in_streamed_txn()

static void set_schema_sent_in_streamed_txn ( RelationSyncEntry entry,
TransactionId  xid 
)
static

Definition at line 2010 of file pgoutput.c.

2011{
2012 MemoryContext oldctx;
2013
2015
2016 entry->streamed_txns = lappend_xid(entry->streamed_txns, xid);
2017
2018 MemoryContextSwitchTo(oldctx);
2019}
List * lappend_xid(List *list, TransactionId datum)
Definition: list.c:393

References CacheMemoryContext, lappend_xid(), MemoryContextSwitchTo(), and RelationSyncEntry::streamed_txns.

Referenced by maybe_send_schema().

Variable Documentation

◆ publications_valid

bool publications_valid
static

Definition at line 86 of file pgoutput.c.

Referenced by get_rel_sync_entry(), pgoutput_startup(), and publication_invalidation_cb().

◆ RelationSyncCache