LCOV - code coverage report
Current view: top level - src/backend/replication/logical - conflict.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 90.2 % 346 312
Test Date: 2026-12-02 15:17:04 Functions: 100.0 % 17 17
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 75.5 % 192 145

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  * conflict.c
       3                 :             :  *     Support routines for logging conflicts.
       4                 :             :  *
       5                 :             :  * Copyright (c) 2024-2026, PostgreSQL Global Development Group
       6                 :             :  *
       7                 :             :  * IDENTIFICATION
       8                 :             :  *    src/backend/replication/logical/conflict.c
       9                 :             :  *
      10                 :             :  * This file contains the code for logging conflicts on the subscriber during
      11                 :             :  * logical replication.
      12                 :             :  *-------------------------------------------------------------------------
      13                 :             :  */
      14                 :             : 
      15                 :             : #include "postgres.h"
      16                 :             : 
      17                 :             : #include "access/commit_ts.h"
      18                 :             : #include "access/genam.h"
      19                 :             : #include "access/heapam.h"
      20                 :             : #include "access/tableam.h"
      21                 :             : #include "catalog/heap.h"
      22                 :             : #include "catalog/pg_am.h"
      23                 :             : #include "catalog/pg_namespace.h"
      24                 :             : #include "catalog/toasting.h"
      25                 :             : #include "executor/executor.h"
      26                 :             : #include "funcapi.h"
      27                 :             : #include "pgstat.h"
      28                 :             : #include "replication/conflict.h"
      29                 :             : #include "replication/worker_internal.h"
      30                 :             : #include "storage/lmgr.h"
      31                 :             : #include "utils/array.h"
      32                 :             : #include "utils/builtins.h"
      33                 :             : #include "utils/json.h"
      34                 :             : #include "utils/lsyscache.h"
      35                 :             : #include "utils/pg_lsn.h"
      36                 :             : #include "utils/xid8.h"
      37                 :             : 
      38                 :             : /*
      39                 :             :  * String representations for the supported conflict logging destinations.
      40                 :             :  */
      41                 :             : const char *const ConflictLogDestNames[] = {
      42                 :             :     [CONFLICT_LOG_DEST_LOG] = "log",
      43                 :             :     [CONFLICT_LOG_DEST_TABLE] = "table",
      44                 :             :     [CONFLICT_LOG_DEST_ALL] = "all"
      45                 :             : };
      46                 :             : 
      47                 :             : StaticAssertDecl(lengthof(ConflictLogDestNames) == CONFLICT_LOG_DEST_ALL + 1,
      48                 :             :                  "ConflictLogDestNames length mismatch");
      49                 :             : 
      50                 :             : 
      51                 :             : /* Structure to hold metadata for one column of the conflict log table */
      52                 :             : typedef struct ConflictLogColumnDef
      53                 :             : {
      54                 :             :     const char *attname;        /* Column name */
      55                 :             :     Oid         atttypid;       /* Data type OID */
      56                 :             : } ConflictLogColumnDef;
      57                 :             : 
      58                 :             : /*
      59                 :             :  * Schema definition for conflict log tables.
      60                 :             :  *
      61                 :             :  * Defines the fixed schema of the per-subscription conflict log table created
      62                 :             :  * in the pg_conflict namespace. Each entry specifies the column name and its
      63                 :             :  * type OID; the table is created in this column order by
      64                 :             :  * create_conflict_log_table().
      65                 :             :  *
      66                 :             :  * The replica_identity and local_conflicts columns are typed json rather than
      67                 :             :  * jsonb on purpose: they hold an exact audit snapshot of the replica identity
      68                 :             :  * key values and local conflict metadata, and json preserves the verbatim
      69                 :             :  * representation whereas jsonb would normalize it. Indexing them (jsonb's main
      70                 :             :  * advantage) wouldn't help anyway, as the conflict log is looked up by its
      71                 :             :  * scalar columns (relid, conflict_type, commit timestamp) while these json
      72                 :             :  * columns are per-conflict payload to inspect, not search keys.
      73                 :             :  *
      74                 :             :  * 'local_conflicts' is typed as an array of JSON objects (json[]), not a
      75                 :             :  * single json object, so that a future conflict type needing to record
      76                 :             :  * multiple local rows for one remote operation doesn't require a
      77                 :             :  * backward-incompatible schema change.
      78                 :             :  */
      79                 :             : static const ConflictLogColumnDef ConflictLogSchema[] = {
      80                 :             :     {.attname = "relid", .atttypid = OIDOID},
      81                 :             :     {.attname = "schemaname", .atttypid = TEXTOID},
      82                 :             :     {.attname = "relname", .atttypid = TEXTOID},
      83                 :             :     {.attname = "conflict_type", .atttypid = TEXTOID},
      84                 :             :     {.attname = "remote_xid", .atttypid = XIDOID},
      85                 :             :     {.attname = "remote_commit_lsn", .atttypid = LSNOID},
      86                 :             :     {.attname = "remote_commit_ts", .atttypid = TIMESTAMPTZOID},
      87                 :             :     {.attname = "apply_origin", .atttypid = TEXTOID},
      88                 :             :     {.attname = "replica_identity_full", .atttypid = BOOLOID},
      89                 :             :     {.attname = "replica_identity", .atttypid = JSONOID},
      90                 :             :     {.attname = "local_conflicts", .atttypid = JSONARRAYOID},
      91                 :             :     {.attname = "has_omitted_values", .atttypid = BOOLOID}
      92                 :             : };
      93                 :             : 
      94                 :             : #define NUM_CONFLICT_ATTRS ((AttrNumber) lengthof(ConflictLogSchema))
      95                 :             : 
      96                 :             : /*
      97                 :             :  * Maximum size in bytes of a replica identity key value recorded in the
      98                 :             :  * conflict log table. A larger value is replaced by a marker holding its
      99                 :             :  * length. See build_index_key_json().
     100                 :             :  *
     101                 :             :  * The cap applies to the length of the type's text output before JSON escaping.
     102                 :             :  * Since escape_json() expands each byte at most sixfold (to \uXXXX), and an
     103                 :             :  * index has at most INDEX_MAX_KEYS (32) key columns, the worst-case JSON output
     104                 :             :  * is 64kB * 6 * 32 = 12MB, comfortably inside the 1GB limit on a json value.
     105                 :             :  * Ordinary keys are orders of magnitude below the cap, so in practice nothing
     106                 :             :  * is ever omitted.
     107                 :             :  */
     108                 :             : #define CONFLICT_MAX_VALUE_SIZE (64 * 1024)
     109                 :             : 
     110                 :             : /*
     111                 :             :  * Schema for the elements within the 'local_conflicts' JSON array.
     112                 :             :  */
     113                 :             : static const ConflictLogColumnDef LocalConflictSchema[] =
     114                 :             : {
     115                 :             :     {.attname = "xid", .atttypid = XID8OID},
     116                 :             :     {.attname = "commit_ts", .atttypid = TIMESTAMPTZOID},
     117                 :             :     {.attname = "origin", .atttypid = TEXTOID}
     118                 :             : };
     119                 :             : 
     120                 :             : #define NUM_LOCAL_CONFLICT_ATTRS lengthof(LocalConflictSchema)
     121                 :             : 
     122                 :             : static const char *const ConflictTypeNames[] = {
     123                 :             :     [CT_INSERT_EXISTS] = "insert_exists",
     124                 :             :     [CT_UPDATE_ORIGIN_DIFFERS] = "update_origin_differs",
     125                 :             :     [CT_UPDATE_EXISTS] = "update_exists",
     126                 :             :     [CT_UPDATE_MISSING] = "update_missing",
     127                 :             :     [CT_DELETE_ORIGIN_DIFFERS] = "delete_origin_differs",
     128                 :             :     [CT_UPDATE_DELETED] = "update_deleted",
     129                 :             :     [CT_DELETE_MISSING] = "delete_missing",
     130                 :             :     [CT_MULTIPLE_UNIQUE_CONFLICTS] = "multiple_unique_conflicts"
     131                 :             : };
     132                 :             : 
     133                 :             : static Relation get_conflictlog_dest_and_table(int elevel,
     134                 :             :                                                ConflictLogDest *log_dest);
     135                 :             : static int  errcode_apply_conflict(ConflictType type);
     136                 :             : static void errdetail_apply_conflict(EState *estate,
     137                 :             :                                      ResultRelInfo *relinfo,
     138                 :             :                                      ConflictType type,
     139                 :             :                                      TupleTableSlot *searchslot,
     140                 :             :                                      TupleTableSlot *localslot,
     141                 :             :                                      TupleTableSlot *remoteslot,
     142                 :             :                                      Oid indexoid, TransactionId localxmin,
     143                 :             :                                      ReplOriginId localorigin,
     144                 :             :                                      TimestampTz localts, StringInfo err_msg);
     145                 :             : static void get_tuple_desc(EState *estate, ResultRelInfo *relinfo,
     146                 :             :                            ConflictType type, char **key_desc,
     147                 :             :                            TupleTableSlot *localslot, char **local_desc,
     148                 :             :                            TupleTableSlot *remoteslot, char **remote_desc,
     149                 :             :                            TupleTableSlot *searchslot, char **search_desc,
     150                 :             :                            Oid indexoid);
     151                 :             : static void build_index_datums_from_slot(EState *estate, Relation localrel,
     152                 :             :                                          TupleTableSlot *slot,
     153                 :             :                                          Relation indexDesc, Datum *values,
     154                 :             :                                          bool *isnull);
     155                 :             : static char *build_index_value_desc(EState *estate, Relation localrel,
     156                 :             :                                     TupleTableSlot *slot, Oid indexoid);
     157                 :             : static Datum build_index_key_json(EState *estate,
     158                 :             :                                   Relation localrel,
     159                 :             :                                   Oid replica_index,
     160                 :             :                                   TupleTableSlot *slot,
     161                 :             :                                   bool *omitted);
     162                 :             : static TupleDesc build_local_conflicts_tupledesc(void);
     163                 :             : static Datum build_local_conflicts_json_array(List *conflicttuples);
     164                 :             : static void insert_conflict_log_tuple(EState *estate, Relation rel,
     165                 :             :                                       Relation conflictlogrel,
     166                 :             :                                       ConflictType conflict_type,
     167                 :             :                                       Oid searchindexoid,
     168                 :             :                                       TupleTableSlot *searchslot,
     169                 :             :                                       List *conflicttuples);
     170                 :             : 
     171                 :             : /*
     172                 :             :  * Builds the TupleDesc for the conflict log table.
     173                 :             :  */
     174                 :             : static TupleDesc
     175                 :          22 : create_conflict_log_table_tupdesc(void)
     176                 :             : {
     177                 :             :     TupleDesc   tupdesc;
     178                 :             : 
     179                 :          22 :     tupdesc = CreateTemplateTupleDesc(NUM_CONFLICT_ATTRS);
     180                 :             : 
     181         [ +  + ]:         286 :     for (int i = 0; i < NUM_CONFLICT_ATTRS; i++)
     182                 :         264 :         TupleDescInitEntry(tupdesc, i + 1,
     183                 :         264 :                            ConflictLogSchema[i].attname,
     184                 :         264 :                            ConflictLogSchema[i].atttypid,
     185                 :             :                            -1, 0);
     186                 :             : 
     187                 :          22 :     TupleDescFinalize(tupdesc);
     188                 :             : 
     189                 :          22 :     return tupdesc;
     190                 :             : }
     191                 :             : 
     192                 :             : /*
     193                 :             :  * Create a structured conflict log table for a subscription.
     194                 :             :  *
     195                 :             :  * The table is created within the system-managed 'pg_conflict' namespace to
     196                 :             :  * prevent users from manually dropping or altering it.  This also prevents
     197                 :             :  * accidental name collisions with user-created tables with the same name.
     198                 :             :  *
     199                 :             :  * The table name is generated automatically using the subscription's OID
     200                 :             :  * (e.g., "pg_conflict_log_<subid>") to ensure uniqueness within the
     201                 :             :  * cluster and to avoid collisions during subscription renames.
     202                 :             :  */
     203                 :             : Oid
     204                 :          22 : create_conflict_log_table(Oid subid, char *subname, Oid subowner)
     205                 :             : {
     206                 :             :     TupleDesc   tupdesc;
     207                 :             :     Oid         relid;
     208                 :             :     char        relname[NAMEDATALEN];
     209                 :             : 
     210                 :          22 :     snprintf(relname, NAMEDATALEN, CONFLICT_LOG_RELATION_NAME_FMT, subid);
     211                 :             : 
     212                 :             :     /* Build the tuple descriptor for the new table. */
     213                 :          22 :     tupdesc = create_conflict_log_table_tupdesc();
     214                 :             : 
     215                 :             :     /*
     216                 :             :      * Create conflict log table. Place it in the database's default
     217                 :             :      * tablespace, ignoring default_tablespace, so its placement does not
     218                 :             :      * depend on the session that creates it.
     219                 :             :      */
     220                 :          22 :     relid = heap_create_with_catalog(relname,
     221                 :             :                                      PG_CONFLICT_NAMESPACE,
     222                 :             :                                      InvalidOid,    /* tablespace */
     223                 :             :                                      InvalidOid,    /* relid */
     224                 :             :                                      InvalidOid,    /* reltypeid */
     225                 :             :                                      InvalidOid,    /* reloftypeid */
     226                 :             :                                      subowner,
     227                 :             :                                      HEAP_TABLE_AM_OID,
     228                 :             :                                      tupdesc,
     229                 :             :                                      NIL,
     230                 :             :                                      RELKIND_RELATION,
     231                 :             :                                      RELPERSISTENCE_PERMANENT,
     232                 :             :                                      false, /* shared_relation */
     233                 :             :                                      false, /* mapped_relation */
     234                 :             :                                      ONCOMMIT_NOOP,
     235                 :             :                                      (Datum) 0, /* reloptions */
     236                 :             :                                      false, /* use_user_acl */
     237                 :             :                                      false, /* allow_system_table_mods */
     238                 :             :                                      true,  /* is_internal */
     239                 :             :                                      InvalidOid,    /* relrewrite */
     240                 :             :                                      NULL); /* typaddress */
     241                 :             :     Assert(OidIsValid(relid));
     242                 :             : 
     243                 :             :     /* Release tuple descriptor memory. */
     244                 :          22 :     FreeTupleDesc(tupdesc);
     245                 :             : 
     246                 :             :     /*
     247                 :             :      * We must bump the command counter to make the newly-created relation
     248                 :             :      * tuple visible for opening.
     249                 :             :      */
     250                 :          22 :     CommandCounterIncrement();
     251                 :             : 
     252                 :             :     /*
     253                 :             :      * Create a TOAST table for the conflict log to support out-of-line
     254                 :             :      * storage of large json data.
     255                 :             :      */
     256                 :          22 :     NewRelationCreateToastTable(relid, (Datum) 0);
     257                 :             : 
     258         [ +  + ]:          22 :     ereport(NOTICE,
     259                 :             :             (errmsg("created conflict log table \"%s\" for subscription \"%s\"",
     260                 :             :                     get_qualified_objname(PG_CONFLICT_NAMESPACE, relname),
     261                 :             :                     subname)));
     262                 :             : 
     263                 :          22 :     return relid;
     264                 :             : }
     265                 :             : 
     266                 :             : /*
     267                 :             :  * Convert the string representation of a conflict logging destination to its
     268                 :             :  * corresponding enum value.
     269                 :             :  */
     270                 :             : ConflictLogDest
     271                 :         120 : GetConflictLogDest(const char *dest)
     272                 :             : {
     273                 :             :     /* NULL defaults to LOG. */
     274   [ +  -  +  + ]:         120 :     if (dest == NULL || pg_strcasecmp(dest, "log") == 0)
     275                 :          43 :         return CONFLICT_LOG_DEST_LOG;
     276                 :             : 
     277         [ +  + ]:          77 :     if (pg_strcasecmp(dest, "table") == 0)
     278                 :          45 :         return CONFLICT_LOG_DEST_TABLE;
     279                 :             : 
     280         [ +  + ]:          32 :     if (pg_strcasecmp(dest, "all") == 0)
     281                 :          24 :         return CONFLICT_LOG_DEST_ALL;
     282                 :             : 
     283                 :             :     /* Unrecognized string. */
     284         [ +  - ]:           8 :     ereport(ERROR,
     285                 :             :             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     286                 :             :              errmsg("unrecognized conflict_log_destination value: \"%s\"", dest),
     287                 :             :              errhint("Valid values are \"log\", \"table\", and \"all\".")));
     288                 :             : }
     289                 :             : 
     290                 :             : /*
     291                 :             :  * Get the xmin and commit timestamp data (origin and timestamp) associated
     292                 :             :  * with the provided local row.
     293                 :             :  *
     294                 :             :  * Return true if the commit timestamp data was found, false otherwise.
     295                 :             :  */
     296                 :             : bool
     297                 :       72421 : GetTupleTransactionInfo(TupleTableSlot *localslot, TransactionId *xmin,
     298                 :             :                         ReplOriginId *localorigin, TimestampTz *localts)
     299                 :             : {
     300                 :             :     Datum       xminDatum;
     301                 :             :     bool        isnull;
     302                 :             : 
     303                 :       72421 :     xminDatum = slot_getsysattr(localslot, MinTransactionIdAttributeNumber,
     304                 :             :                                 &isnull);
     305                 :       72421 :     *xmin = DatumGetTransactionId(xminDatum);
     306                 :             :     Assert(!isnull);
     307                 :             : 
     308                 :             :     /*
     309                 :             :      * The commit timestamp data is not available if track_commit_timestamp is
     310                 :             :      * disabled.
     311                 :             :      */
     312         [ +  + ]:       72421 :     if (!track_commit_timestamp)
     313                 :             :     {
     314                 :       72251 :         *localorigin = InvalidReplOriginId;
     315                 :       72251 :         *localts = 0;
     316                 :       72251 :         return false;
     317                 :             :     }
     318                 :             : 
     319                 :         170 :     return TransactionIdGetCommitTsData(*xmin, localts, localorigin);
     320                 :             : }
     321                 :             : 
     322                 :             : /*
     323                 :             :  * This function is used to report a conflict while applying replication
     324                 :             :  * changes.
     325                 :             :  *
     326                 :             :  * 'relmapentry' is the relation map entry that was used to search the local
     327                 :             :  * row, or NULL for ERROR-level insert/update conflicts. If the search used
     328                 :             :  * the replica identity or primary key index, the caller must have locked
     329                 :             :  * it, which the search itself does, see FindReplTupleInLocalRel().
     330                 :             :  *
     331                 :             :  * 'searchslot' should contain the tuple used to search the local row to be
     332                 :             :  * updated or deleted.
     333                 :             :  *
     334                 :             :  * 'remoteslot' should contain the remote new tuple, if any.
     335                 :             :  *
     336                 :             :  * conflicttuples is a list of local rows that caused the conflict and the
     337                 :             :  * conflict related information. See ConflictTupleInfo.
     338                 :             :  *
     339                 :             :  * The caller must ensure that all the indexes passed in ConflictTupleInfo are
     340                 :             :  * locked so that we can fetch and display the conflicting key values.
     341                 :             :  */
     342                 :             : void
     343                 :         124 : ReportApplyConflict(EState *estate, ResultRelInfo *relinfo, int elevel,
     344                 :             :                     ConflictType type, LogicalRepRelMapEntry *relmapentry,
     345                 :             :                     TupleTableSlot *searchslot,
     346                 :             :                     TupleTableSlot *remoteslot, List *conflicttuples)
     347                 :             : {
     348                 :         124 :     Relation    localrel = relinfo->ri_RelationDesc;
     349                 :             :     ConflictLogDest dest;
     350                 :         124 :     Oid         searchindexoid = InvalidOid;
     351                 :             :     Relation    conflictlogrel;
     352                 :             :     StringInfoData err_detail;
     353                 :             : 
     354                 :         124 :     pgstat_report_subscription_conflict(MySubscription->oid, type);
     355                 :             : 
     356                 :             :     /*
     357                 :             :      * Use the replica identity or primary key index that the search actually
     358                 :             :      * used, which the caller has locked, rather than looking it up again.
     359                 :             :      * Concurrent DDL could have changed which index that is since the search,
     360                 :             :      * see comments in FindReplTupleInLocalRel().
     361                 :             :      */
     362   [ +  +  +  + ]:         124 :     if (relmapentry && relmapentry->idxisreplident)
     363                 :          27 :         searchindexoid = relmapentry->localindexoid;
     364                 :             : 
     365                 :         124 :     conflictlogrel = get_conflictlog_dest_and_table(elevel, &dest);
     366                 :             : 
     367                 :         124 :     initStringInfo(&err_detail);
     368                 :             : 
     369                 :             :     /*
     370                 :             :      * Log the full details to the server log, unless the conflict goes only
     371                 :             :      * to the conflict log table, in which case just point to the table.
     372                 :             :      */
     373   [ +  +  +  + ]:         124 :     if (CONFLICTS_LOGGED_TO_LOG(dest))
     374                 :             :     {
     375                 :             :         /* Form errdetail message by combining conflicting tuples information. */
     376         [ +  + ]:         122 :         if (conflicttuples != NIL)
     377                 :             :         {
     378   [ +  -  +  +  :         394 :             foreach_ptr(ConflictTupleInfo, conflicttuple, conflicttuples)
                   +  + ]
     379                 :         190 :                 errdetail_apply_conflict(estate, relinfo, type, searchslot,
     380                 :             :                                          conflicttuple->slot, remoteslot,
     381                 :             :                                          conflicttuple->indexoid,
     382                 :         190 :                                          XidFromFullTransactionId(conflicttuple->xmin),
     383                 :         190 :                                          conflicttuple->origin,
     384                 :             :                                          conflicttuple->ts,
     385                 :             :                                          &err_detail);
     386                 :             :         }
     387                 :             :         else
     388                 :             :         {
     389                 :          20 :             errdetail_apply_conflict(estate, relinfo, type, searchslot,
     390                 :             :                                      NULL, remoteslot,
     391                 :             :                                      InvalidOid,
     392                 :             :                                      InvalidTransactionId,
     393                 :             :                                      InvalidReplOriginId,
     394                 :             :                                      0,
     395                 :             :                                      &err_detail);
     396                 :             :         }
     397                 :             :     }
     398                 :             :     else
     399                 :             :     {
     400                 :             :         Assert(conflictlogrel);
     401                 :             : 
     402                 :           4 :         appendStringInfo(&err_detail,
     403                 :           2 :                          _("Conflict details are logged to the conflict log table \"%s.%s\"."),
     404                 :           2 :                          get_namespace_name(RelationGetNamespace(conflictlogrel)),
     405                 :           2 :                          RelationGetRelationName(conflictlogrel));
     406                 :             :     }
     407                 :             : 
     408         [ +  - ]:         124 :     ereport(elevel,
     409                 :             :             errcode_apply_conflict(type),
     410                 :             :             errmsg("conflict detected on relation \"%s.%s\": conflict=%s",
     411                 :             :                    get_namespace_name(RelationGetNamespace(localrel)),
     412                 :             :                    RelationGetRelationName(localrel),
     413                 :             :                    ConflictTypeNames[type]),
     414                 :             :             errdetail_internal("%s", err_detail.data));
     415                 :             : 
     416                 :             :     /*
     417                 :             :      * Insert into the conflict log table for LOG-level conflicts if
     418                 :             :      * requested.
     419                 :             :      */
     420         [ +  + ]:          33 :     if (conflictlogrel)
     421                 :             :     {
     422                 :          14 :         insert_conflict_log_tuple(estate,
     423                 :             :                                   relinfo->ri_RelationDesc,
     424                 :             :                                   conflictlogrel,
     425                 :             :                                   type,
     426                 :             :                                   searchindexoid,
     427                 :             :                                   searchslot,
     428                 :             :                                   conflicttuples);
     429                 :          14 :         table_close(conflictlogrel, NoLock);
     430                 :             :     }
     431                 :          33 : }
     432                 :             : 
     433                 :             : /*
     434                 :             :  * Find all unique indexes to check for a conflict and store them into
     435                 :             :  * ResultRelInfo.
     436                 :             :  */
     437                 :             : void
     438                 :      136134 : InitConflictIndexes(ResultRelInfo *relInfo)
     439                 :             : {
     440                 :      136134 :     List       *uniqueIndexes = NIL;
     441                 :             : 
     442         [ +  + ]:      248894 :     for (int i = 0; i < relInfo->ri_NumIndices; i++)
     443                 :             :     {
     444                 :      112760 :         Relation    indexRelation = relInfo->ri_IndexRelationDescs[i];
     445                 :             : 
     446         [ -  + ]:      112760 :         if (indexRelation == NULL)
     447                 :           0 :             continue;
     448                 :             : 
     449                 :             :         /* Detect conflict only for unique indexes */
     450         [ +  + ]:      112760 :         if (!relInfo->ri_IndexRelationInfo[i]->ii_Unique)
     451                 :          30 :             continue;
     452                 :             : 
     453                 :             :         /* Don't support conflict detection for deferrable index */
     454         [ -  + ]:      112730 :         if (!indexRelation->rd_index->indimmediate)
     455                 :           0 :             continue;
     456                 :             : 
     457                 :      112730 :         uniqueIndexes = lappend_oid(uniqueIndexes,
     458                 :             :                                     RelationGetRelid(indexRelation));
     459                 :             :     }
     460                 :             : 
     461                 :      136134 :     relInfo->ri_onConflictArbiterIndexes = uniqueIndexes;
     462                 :      136134 : }
     463                 :             : 
     464                 :             : /*
     465                 :             :  * get_conflictlog_dest_and_table
     466                 :             :  *
     467                 :             :  * Decides where a conflict of the given elevel is to be reported, based on
     468                 :             :  * the subscription's conflict_log_destination. Sets *log_dest to the
     469                 :             :  * effective destination and, if that includes the conflict log table, returns
     470                 :             :  * the table opened for insertion. Otherwise returns NULL.
     471                 :             :  *
     472                 :             :  * Only LOG-level conflicts (i.e. resolved conflicts where the transaction
     473                 :             :  * continues) are recorded in the conflict log table. ERROR-level conflicts
     474                 :             :  * halt replication and abort the transaction, so they are always reported
     475                 :             :  * exclusively to the server log.
     476                 :             :  */
     477                 :             : static Relation
     478                 :         124 : get_conflictlog_dest_and_table(int elevel, ConflictLogDest *log_dest)
     479                 :             : {
     480                 :             :     Relation    conflictlogrel;
     481                 :             :     Oid         conflictlogrelid;
     482                 :             : 
     483         [ +  + ]:         124 :     if (elevel >= ERROR)
     484                 :             :     {
     485                 :          91 :         *log_dest = CONFLICT_LOG_DEST_LOG;
     486                 :          91 :         return NULL;
     487                 :             :     }
     488                 :             : 
     489                 :             :     /* Convert the text log destination to the internal enum. */
     490                 :          33 :     *log_dest = GetConflictLogDest(MySubscription->conflictlogdest);
     491                 :             : 
     492                 :             :     /* Quick exit if a conflict log table was not requested. */
     493   [ +  +  +  + ]:          33 :     if (!CONFLICTS_LOGGED_TO_TABLE(*log_dest))
     494                 :          19 :         return NULL;
     495                 :             : 
     496                 :          14 :     conflictlogrelid = MySubscription->conflictlogrelid;
     497                 :             : 
     498                 :             :     Assert(OidIsValid(conflictlogrelid));
     499                 :             : 
     500                 :             :     /*
     501                 :             :      * Use try_table_open() because the table may have been dropped
     502                 :             :      * concurrently by an ALTER SUBSCRIPTION that changed
     503                 :             :      * conflict_log_destination. In that case, fall back to the server log
     504                 :             :      * instead of failing.
     505                 :             :      */
     506                 :          14 :     conflictlogrel = try_table_open(conflictlogrelid, RowExclusiveLock);
     507                 :             : 
     508         [ -  + ]:          14 :     if (!conflictlogrel)
     509                 :           0 :         *log_dest = CONFLICT_LOG_DEST_LOG;
     510                 :             : 
     511                 :          14 :     return conflictlogrel;
     512                 :             : }
     513                 :             : 
     514                 :             : /*
     515                 :             :  * Add SQLSTATE error code to the current conflict report.
     516                 :             :  */
     517                 :             : static int
     518                 :         124 : errcode_apply_conflict(ConflictType type)
     519                 :             : {
     520      [ +  +  - ]:         124 :     switch (type)
     521                 :             :     {
     522                 :          91 :         case CT_INSERT_EXISTS:
     523                 :             :         case CT_UPDATE_EXISTS:
     524                 :             :         case CT_MULTIPLE_UNIQUE_CONFLICTS:
     525                 :          91 :             return errcode(ERRCODE_UNIQUE_VIOLATION);
     526                 :          33 :         case CT_UPDATE_ORIGIN_DIFFERS:
     527                 :             :         case CT_UPDATE_MISSING:
     528                 :             :         case CT_DELETE_ORIGIN_DIFFERS:
     529                 :             :         case CT_UPDATE_DELETED:
     530                 :             :         case CT_DELETE_MISSING:
     531                 :          33 :             return errcode(ERRCODE_T_R_SERIALIZATION_FAILURE);
     532                 :             :     }
     533                 :             : 
     534                 :             :     Assert(false);
     535                 :           0 :     return 0;                   /* silence compiler warning */
     536                 :             : }
     537                 :             : 
     538                 :             : /*
     539                 :             :  * Helper function to build the additional details for conflicting key,
     540                 :             :  * local row, remote row, and replica identity columns.
     541                 :             :  */
     542                 :             : static void
     543                 :         301 : append_tuple_value_detail(StringInfo buf, List *tuple_values)
     544                 :             : {
     545                 :         301 :     bool        first = true;
     546                 :             : 
     547                 :             :     Assert(buf != NULL && tuple_values != NIL);
     548                 :             : 
     549   [ +  -  +  +  :        1200 :     foreach_ptr(char, tuple_value, tuple_values)
                   +  + ]
     550                 :             :     {
     551                 :             :         /*
     552                 :             :          * Skip if the value is NULL. This means the current user does not
     553                 :             :          * have enough permissions to see all columns in the table. See
     554                 :             :          * get_tuple_desc().
     555                 :             :          */
     556         [ +  + ]:         598 :         if (!tuple_value)
     557                 :          94 :             continue;
     558                 :             : 
     559                 :             :         /* standard SQL punctuation, not translated */
     560         [ +  + ]:         504 :         if (!first)
     561                 :         203 :             appendStringInfoString(buf, ", ");
     562                 :             : 
     563                 :         504 :         appendStringInfoString(buf, tuple_value);
     564                 :         504 :         first = false;
     565                 :             :     }
     566                 :         301 : }
     567                 :             : 
     568                 :             : /*
     569                 :             :  * Add an errdetail() line showing conflict detail.
     570                 :             :  *
     571                 :             :  * The DETAIL line comprises of two parts:
     572                 :             :  * 1. Explanation of the conflict type, including the origin and commit
     573                 :             :  *    timestamp of the local row.
     574                 :             :  * 2. Display of conflicting key, local row, remote new row, and replica
     575                 :             :  *    identity columns, if any. The remote old row is excluded as its
     576                 :             :  *    information is covered in the replica identity columns.
     577                 :             :  */
     578                 :             : static void
     579                 :         210 : errdetail_apply_conflict(EState *estate, ResultRelInfo *relinfo,
     580                 :             :                          ConflictType type, TupleTableSlot *searchslot,
     581                 :             :                          TupleTableSlot *localslot, TupleTableSlot *remoteslot,
     582                 :             :                          Oid indexoid, TransactionId localxmin,
     583                 :             :                          ReplOriginId localorigin, TimestampTz localts,
     584                 :             :                          StringInfo err_msg)
     585                 :             : {
     586                 :             :     StringInfoData err_detail;
     587                 :             :     StringInfoData tuple_buf;
     588                 :             :     char       *origin_name;
     589                 :         210 :     char       *key_desc = NULL;
     590                 :         210 :     char       *local_desc = NULL;
     591                 :         210 :     char       *remote_desc = NULL;
     592                 :         210 :     char       *search_desc = NULL;
     593                 :             : 
     594                 :             :     /* Get key, replica identity, remote, and local value data */
     595                 :         210 :     get_tuple_desc(estate, relinfo, type, &key_desc,
     596                 :             :                    localslot, &local_desc,
     597                 :             :                    remoteslot, &remote_desc,
     598                 :             :                    searchslot, &search_desc,
     599                 :             :                    indexoid);
     600                 :             : 
     601                 :         210 :     initStringInfo(&err_detail);
     602                 :         210 :     initStringInfo(&tuple_buf);
     603                 :             : 
     604                 :             :     /* Construct a detailed message describing the type of conflict */
     605   [ +  +  +  +  :         210 :     switch (type)
                +  +  - ]
     606                 :             :     {
     607                 :         179 :         case CT_INSERT_EXISTS:
     608                 :             :         case CT_UPDATE_EXISTS:
     609                 :             :         case CT_MULTIPLE_UNIQUE_CONFLICTS:
     610                 :             :             Assert(OidIsValid(indexoid) &&
     611                 :             :                    CheckRelationOidLockedByMe(indexoid, RowExclusiveLock, true));
     612                 :             : 
     613         [ +  + ]:         179 :             if (err_msg->len == 0)
     614                 :             :             {
     615                 :          91 :                 append_tuple_value_detail(&tuple_buf,
     616                 :             :                                           list_make2(remote_desc, search_desc));
     617                 :             : 
     618         [ +  - ]:          91 :                 if (tuple_buf.len)
     619                 :          91 :                     appendStringInfo(&err_detail, _("Could not apply remote change: %s.\n"),
     620                 :             :                                      tuple_buf.data);
     621                 :             :                 else
     622                 :           0 :                     appendStringInfo(&err_detail, _("Could not apply remote change.\n"));
     623                 :             : 
     624                 :             : 
     625                 :          91 :                 resetStringInfo(&tuple_buf);
     626                 :             :             }
     627                 :             : 
     628                 :         179 :             append_tuple_value_detail(&tuple_buf,
     629                 :             :                                       list_make2(key_desc, local_desc));
     630                 :             : 
     631         [ +  + ]:         179 :             if (localts)
     632                 :             :             {
     633         [ -  + ]:           3 :                 if (localorigin == InvalidReplOriginId)
     634                 :             :                 {
     635         [ #  # ]:           0 :                     if (tuple_buf.len)
     636                 :           0 :                         appendStringInfo(&err_detail, _("Key already exists in unique index \"%s\", modified locally in transaction %u at %s: %s."),
     637                 :             :                                          get_rel_name(indexoid),
     638                 :             :                                          localxmin, timestamptz_to_str(localts),
     639                 :             :                                          tuple_buf.data);
     640                 :             :                     else
     641                 :           0 :                         appendStringInfo(&err_detail, _("Key already exists in unique index \"%s\", modified locally in transaction %u at %s."),
     642                 :             :                                          get_rel_name(indexoid),
     643                 :             :                                          localxmin, timestamptz_to_str(localts));
     644                 :             :                 }
     645         [ +  + ]:           3 :                 else if (replorigin_by_oid(localorigin, true, &origin_name))
     646                 :             :                 {
     647         [ +  - ]:           1 :                     if (tuple_buf.len)
     648                 :           1 :                         appendStringInfo(&err_detail, _("Key already exists in unique index \"%s\", modified by origin \"%s\" in transaction %u at %s: %s."),
     649                 :             :                                          get_rel_name(indexoid), origin_name,
     650                 :             :                                          localxmin, timestamptz_to_str(localts),
     651                 :             :                                          tuple_buf.data);
     652                 :             :                     else
     653                 :           0 :                         appendStringInfo(&err_detail, _("Key already exists in unique index \"%s\", modified by origin \"%s\" in transaction %u at %s."),
     654                 :             :                                          get_rel_name(indexoid), origin_name,
     655                 :             :                                          localxmin, timestamptz_to_str(localts));
     656                 :             :                 }
     657                 :             : 
     658                 :             :                 /*
     659                 :             :                  * The origin that modified this row has been removed. This
     660                 :             :                  * can happen if the origin was created by a different apply
     661                 :             :                  * worker and its associated subscription and origin were
     662                 :             :                  * dropped after updating the row, or if the origin was
     663                 :             :                  * manually dropped by the user.
     664                 :             :                  */
     665                 :             :                 else
     666                 :             :                 {
     667         [ +  - ]:           2 :                     if (tuple_buf.len)
     668                 :           2 :                         appendStringInfo(&err_detail, _("Key already exists in unique index \"%s\", modified by a non-existent origin in transaction %u at %s: %s."),
     669                 :             :                                          get_rel_name(indexoid),
     670                 :             :                                          localxmin, timestamptz_to_str(localts),
     671                 :             :                                          tuple_buf.data);
     672                 :             :                     else
     673                 :           0 :                         appendStringInfo(&err_detail, _("Key already exists in unique index \"%s\", modified by a non-existent origin in transaction %u at %s."),
     674                 :             :                                          get_rel_name(indexoid),
     675                 :             :                                          localxmin, timestamptz_to_str(localts));
     676                 :             :                 }
     677                 :             :             }
     678                 :             :             else
     679                 :             :             {
     680         [ +  - ]:         176 :                 if (tuple_buf.len)
     681                 :         176 :                     appendStringInfo(&err_detail, _("Key already exists in unique index \"%s\", modified in transaction %u: %s."),
     682                 :             :                                      get_rel_name(indexoid), localxmin,
     683                 :             :                                      tuple_buf.data);
     684                 :             :                 else
     685                 :           0 :                     appendStringInfo(&err_detail, _("Key already exists in unique index \"%s\", modified in transaction %u."),
     686                 :             :                                      get_rel_name(indexoid), localxmin);
     687                 :             :             }
     688                 :             : 
     689                 :         179 :             break;
     690                 :             : 
     691                 :           3 :         case CT_UPDATE_ORIGIN_DIFFERS:
     692                 :           3 :             append_tuple_value_detail(&tuple_buf,
     693                 :             :                                       list_make3(local_desc, remote_desc,
     694                 :             :                                                  search_desc));
     695                 :             : 
     696         [ +  + ]:           3 :             if (localorigin == InvalidReplOriginId)
     697                 :             :             {
     698         [ +  - ]:           1 :                 if (tuple_buf.len)
     699                 :           1 :                     appendStringInfo(&err_detail, _("Updating the row that was modified locally in transaction %u at %s: %s."),
     700                 :             :                                      localxmin, timestamptz_to_str(localts),
     701                 :             :                                      tuple_buf.data);
     702                 :             :                 else
     703                 :           0 :                     appendStringInfo(&err_detail, _("Updating the row that was modified locally in transaction %u at %s."),
     704                 :             :                                      localxmin, timestamptz_to_str(localts));
     705                 :             :             }
     706         [ +  + ]:           2 :             else if (replorigin_by_oid(localorigin, true, &origin_name))
     707                 :             :             {
     708         [ +  - ]:           1 :                 if (tuple_buf.len)
     709                 :           1 :                     appendStringInfo(&err_detail, _("Updating the row that was modified by a different origin \"%s\" in transaction %u at %s: %s."),
     710                 :             :                                      origin_name, localxmin,
     711                 :             :                                      timestamptz_to_str(localts),
     712                 :             :                                      tuple_buf.data);
     713                 :             :                 else
     714                 :           0 :                     appendStringInfo(&err_detail, _("Updating the row that was modified by a different origin \"%s\" in transaction %u at %s."),
     715                 :             :                                      origin_name, localxmin,
     716                 :             :                                      timestamptz_to_str(localts));
     717                 :             :             }
     718                 :             : 
     719                 :             :             /* The origin that modified this row has been removed. */
     720                 :             :             else
     721                 :             :             {
     722         [ +  - ]:           1 :                 if (tuple_buf.len)
     723                 :           1 :                     appendStringInfo(&err_detail, _("Updating the row that was modified by a non-existent origin in transaction %u at %s: %s."),
     724                 :             :                                      localxmin, timestamptz_to_str(localts),
     725                 :             :                                      tuple_buf.data);
     726                 :             :                 else
     727                 :           0 :                     appendStringInfo(&err_detail, _("Updating the row that was modified by a non-existent origin in transaction %u at %s."),
     728                 :             :                                      localxmin, timestamptz_to_str(localts));
     729                 :             :             }
     730                 :             : 
     731                 :           3 :             break;
     732                 :             : 
     733                 :           3 :         case CT_UPDATE_DELETED:
     734                 :           3 :             append_tuple_value_detail(&tuple_buf,
     735                 :             :                                       list_make2(remote_desc, search_desc));
     736                 :             : 
     737         [ +  - ]:           3 :             if (tuple_buf.len)
     738                 :           3 :                 appendStringInfo(&err_detail, _("Could not find the row to be updated: %s.\n"),
     739                 :             :                                  tuple_buf.data);
     740                 :             :             else
     741                 :           0 :                 appendStringInfo(&err_detail, _("Could not find the row to be updated.\n"));
     742                 :             : 
     743         [ +  - ]:           3 :             if (localts)
     744                 :             :             {
     745         [ +  - ]:           3 :                 if (localorigin == InvalidReplOriginId)
     746                 :           3 :                     appendStringInfo(&err_detail, _("The row to be updated was deleted locally in transaction %u at %s."),
     747                 :             :                                      localxmin, timestamptz_to_str(localts));
     748         [ #  # ]:           0 :                 else if (replorigin_by_oid(localorigin, true, &origin_name))
     749                 :           0 :                     appendStringInfo(&err_detail, _("The row to be updated was deleted by a different origin \"%s\" in transaction %u at %s."),
     750                 :             :                                      origin_name, localxmin, timestamptz_to_str(localts));
     751                 :             : 
     752                 :             :                 /* The origin that modified this row has been removed. */
     753                 :             :                 else
     754                 :           0 :                     appendStringInfo(&err_detail, _("The row to be updated was deleted by a non-existent origin in transaction %u at %s."),
     755                 :             :                                      localxmin, timestamptz_to_str(localts));
     756                 :             :             }
     757                 :             :             else
     758                 :           0 :                 appendStringInfoString(&err_detail, _("The row to be updated was deleted."));
     759                 :             : 
     760                 :           3 :             break;
     761                 :             : 
     762                 :           8 :         case CT_UPDATE_MISSING:
     763                 :           8 :             append_tuple_value_detail(&tuple_buf,
     764                 :             :                                       list_make2(remote_desc, search_desc));
     765                 :             : 
     766         [ +  - ]:           8 :             if (tuple_buf.len)
     767                 :           8 :                 appendStringInfo(&err_detail, _("Could not find the row to be updated: %s."),
     768                 :             :                                  tuple_buf.data);
     769                 :             :             else
     770                 :           0 :                 appendStringInfo(&err_detail, _("Could not find the row to be updated."));
     771                 :             : 
     772                 :           8 :             break;
     773                 :             : 
     774                 :           5 :         case CT_DELETE_ORIGIN_DIFFERS:
     775                 :           5 :             append_tuple_value_detail(&tuple_buf,
     776                 :             :                                       list_make3(local_desc, remote_desc,
     777                 :             :                                                  search_desc));
     778                 :             : 
     779         [ +  + ]:           5 :             if (localorigin == InvalidReplOriginId)
     780                 :             :             {
     781         [ +  - ]:           4 :                 if (tuple_buf.len)
     782                 :           4 :                     appendStringInfo(&err_detail, _("Deleting the row that was modified locally in transaction %u at %s: %s."),
     783                 :             :                                      localxmin, timestamptz_to_str(localts),
     784                 :             :                                      tuple_buf.data);
     785                 :             :                 else
     786                 :           0 :                     appendStringInfo(&err_detail, _("Deleting the row that was modified locally in transaction %u at %s."),
     787                 :             :                                      localxmin, timestamptz_to_str(localts));
     788                 :             :             }
     789         [ +  - ]:           1 :             else if (replorigin_by_oid(localorigin, true, &origin_name))
     790                 :             :             {
     791         [ +  - ]:           1 :                 if (tuple_buf.len)
     792                 :           1 :                     appendStringInfo(&err_detail, _("Deleting the row that was modified by a different origin \"%s\" in transaction %u at %s: %s."),
     793                 :             :                                      origin_name, localxmin,
     794                 :             :                                      timestamptz_to_str(localts),
     795                 :             :                                      tuple_buf.data);
     796                 :             :                 else
     797                 :           0 :                     appendStringInfo(&err_detail, _("Deleting the row that was modified by a different origin \"%s\" in transaction %u at %s."),
     798                 :             :                                      origin_name, localxmin,
     799                 :             :                                      timestamptz_to_str(localts));
     800                 :             :             }
     801                 :             : 
     802                 :             :             /* The origin that modified this row has been removed. */
     803                 :             :             else
     804                 :             :             {
     805         [ #  # ]:           0 :                 if (tuple_buf.len)
     806                 :           0 :                     appendStringInfo(&err_detail, _("Deleting the row that was modified by a non-existent origin in transaction %u at %s: %s."),
     807                 :             :                                      localxmin, timestamptz_to_str(localts),
     808                 :             :                                      tuple_buf.data);
     809                 :             :                 else
     810                 :           0 :                     appendStringInfo(&err_detail, _("Deleting the row that was modified by a non-existent origin in transaction %u at %s."),
     811                 :             :                                      localxmin, timestamptz_to_str(localts));
     812                 :             :             }
     813                 :             : 
     814                 :           5 :             break;
     815                 :             : 
     816                 :          12 :         case CT_DELETE_MISSING:
     817                 :          12 :             append_tuple_value_detail(&tuple_buf,
     818                 :             :                                       list_make1(search_desc));
     819                 :             : 
     820         [ +  - ]:          12 :             if (tuple_buf.len)
     821                 :          12 :                 appendStringInfo(&err_detail, _("Could not find the row to be deleted: %s."),
     822                 :             :                                  tuple_buf.data);
     823                 :             :             else
     824                 :           0 :                 appendStringInfo(&err_detail, _("Could not find the row to be deleted."));
     825                 :             : 
     826                 :          12 :             break;
     827                 :             :     }
     828                 :             : 
     829                 :             :     Assert(err_detail.len > 0);
     830                 :             : 
     831                 :             :     /*
     832                 :             :      * Insert a blank line to visually separate the new detail line from the
     833                 :             :      * existing ones.
     834                 :             :      */
     835         [ +  + ]:         210 :     if (err_msg->len > 0)
     836                 :          88 :         appendStringInfoChar(err_msg, '\n');
     837                 :             : 
     838                 :         210 :     appendStringInfoString(err_msg, err_detail.data);
     839                 :         210 : }
     840                 :             : 
     841                 :             : /*
     842                 :             :  * Extract conflicting key, local row, remote row, and replica identity
     843                 :             :  * columns. Results are set at xxx_desc.
     844                 :             :  *
     845                 :             :  * If the output is NULL, it indicates that the current user lacks permissions
     846                 :             :  * to view the columns involved.
     847                 :             :  */
     848                 :             : static void
     849                 :         210 : get_tuple_desc(EState *estate, ResultRelInfo *relinfo, ConflictType type,
     850                 :             :                char **key_desc,
     851                 :             :                TupleTableSlot *localslot, char **local_desc,
     852                 :             :                TupleTableSlot *remoteslot, char **remote_desc,
     853                 :             :                TupleTableSlot *searchslot, char **search_desc,
     854                 :             :                Oid indexoid)
     855                 :             : {
     856                 :         210 :     Relation    localrel = relinfo->ri_RelationDesc;
     857                 :         210 :     Oid         relid = RelationGetRelid(localrel);
     858                 :         210 :     TupleDesc   tupdesc = RelationGetDescr(localrel);
     859                 :         210 :     char       *desc = NULL;
     860                 :             : 
     861                 :             :     Assert((localslot && local_desc) || (remoteslot && remote_desc) ||
     862                 :             :            (searchslot && search_desc));
     863                 :             : 
     864                 :             :     /*
     865                 :             :      * Report the conflicting key values in the case of a unique constraint
     866                 :             :      * violation.
     867                 :             :      */
     868   [ +  +  +  +  :         210 :     if (type == CT_INSERT_EXISTS || type == CT_UPDATE_EXISTS ||
                   +  + ]
     869                 :             :         type == CT_MULTIPLE_UNIQUE_CONFLICTS)
     870                 :             :     {
     871                 :             :         Assert(OidIsValid(indexoid) && localslot);
     872                 :             : 
     873                 :         179 :         desc = build_index_value_desc(estate, localrel, localslot,
     874                 :             :                                       indexoid);
     875                 :             : 
     876         [ +  - ]:         179 :         if (desc)
     877                 :         179 :             *key_desc = psprintf(_("key %s"), desc);
     878                 :             :     }
     879                 :             : 
     880         [ +  + ]:         210 :     if (localslot)
     881                 :             :     {
     882                 :             :         /*
     883                 :             :          * The 'modifiedCols' only applies to the new tuple, hence we pass
     884                 :             :          * NULL for the local row.
     885                 :             :          */
     886                 :         187 :         desc = ExecBuildSlotValueDescription(relid, localslot, tupdesc,
     887                 :             :                                              NULL, 64);
     888                 :             : 
     889         [ +  - ]:         187 :         if (desc)
     890                 :         187 :             *local_desc = psprintf(_("local row %s"), desc);
     891                 :             :     }
     892                 :             : 
     893         [ +  + ]:         210 :     if (remoteslot)
     894                 :             :     {
     895                 :             :         Bitmapset  *modifiedCols;
     896                 :             : 
     897                 :             :         /*
     898                 :             :          * Although logical replication doesn't maintain the bitmap for the
     899                 :             :          * columns being inserted, we still use it to create 'modifiedCols'
     900                 :             :          * for consistency with other calls to ExecBuildSlotValueDescription.
     901                 :             :          *
     902                 :             :          * Note that generated columns are formed locally on the subscriber.
     903                 :             :          */
     904                 :         193 :         modifiedCols = bms_union(ExecGetInsertedCols(relinfo, estate),
     905                 :         193 :                                  ExecGetUpdatedCols(relinfo, estate));
     906                 :         193 :         desc = ExecBuildSlotValueDescription(relid, remoteslot,
     907                 :             :                                              tupdesc, modifiedCols,
     908                 :             :                                              64);
     909                 :             : 
     910         [ +  - ]:         193 :         if (desc)
     911                 :         193 :             *remote_desc = psprintf(_("remote row %s"), desc);
     912                 :             :     }
     913                 :             : 
     914         [ +  + ]:         210 :     if (searchslot)
     915                 :             :     {
     916                 :             :         /*
     917                 :             :          * Note that while index other than replica identity may be used (see
     918                 :             :          * IsIndexUsableForReplicaIdentityFull for details) to find the tuple
     919                 :             :          * when applying update or delete, such an index scan may not result
     920                 :             :          * in a unique tuple and we still compare the complete tuple in such
     921                 :             :          * cases, thus such indexes are not used here.
     922                 :             :          *
     923                 :             :          * XXX This can disagree with the index the apply worker searched by,
     924                 :             :          * see FindReplTupleInLocalRel(). It may not even be one that
     925                 :             :          * ExecOpenIndices() locked.
     926                 :             :          */
     927                 :          35 :         Oid         replica_index = GetRelationIdentityOrPK(localrel);
     928                 :             : 
     929                 :             :         Assert(type != CT_INSERT_EXISTS);
     930                 :             : 
     931                 :             :         /*
     932                 :             :          * If the table has a valid replica identity index, build the index
     933                 :             :          * key value string. Otherwise, construct the full tuple value for
     934                 :             :          * REPLICA IDENTITY FULL cases.
     935                 :             :          */
     936         [ +  + ]:          35 :         if (OidIsValid(replica_index))
     937                 :          30 :             desc = build_index_value_desc(estate, localrel, searchslot, replica_index);
     938                 :             :         else
     939                 :           5 :             desc = ExecBuildSlotValueDescription(relid, searchslot, tupdesc, NULL, 64);
     940                 :             : 
     941         [ +  - ]:          35 :         if (desc)
     942                 :             :         {
     943         [ +  + ]:          35 :             if (OidIsValid(replica_index))
     944                 :          30 :                 *search_desc = psprintf(_("replica identity %s"), desc);
     945                 :             :             else
     946                 :           5 :                 *search_desc = psprintf(_("replica identity full %s"), desc);
     947                 :             :         }
     948                 :             :     }
     949                 :         210 : }
     950                 :             : 
     951                 :             : /*
     952                 :             :  * Helper function to extract the "raw" index key Datums and their null flags
     953                 :             :  * from a TupleTableSlot, given an already open index descriptor.
     954                 :             :  */
     955                 :             : static void
     956                 :         219 : build_index_datums_from_slot(EState *estate, Relation localrel,
     957                 :             :                              TupleTableSlot *slot,
     958                 :             :                              Relation indexDesc, Datum *values,
     959                 :             :                              bool *isnull)
     960                 :             : {
     961                 :         219 :     TupleTableSlot *tableslot = slot;
     962                 :             : 
     963                 :             :     /*
     964                 :             :      * FormIndexDatum needs an EState whose per-tuple econtext's scantuple
     965                 :             :      * points to the slot holding the tuple, to evaluate any index
     966                 :             :      * expressions. It also requires a heap tuple slot, so copy a virtual slot
     967                 :             :      * into one, created in the EState's tuple table so that it is freed along
     968                 :             :      * with it.
     969                 :             :      */
     970         [ +  + ]:         219 :     if (TTS_IS_VIRTUAL(slot))
     971                 :             :     {
     972                 :          31 :         tableslot = table_slot_create(localrel, &estate->es_tupleTable);
     973                 :          31 :         tableslot = ExecCopySlot(tableslot, slot);
     974                 :             :     }
     975                 :             : 
     976         [ +  - ]:         219 :     GetPerTupleExprContext(estate)->ecxt_scantuple = tableslot;
     977                 :             : 
     978                 :             :     /* Form the index datums */
     979                 :         219 :     FormIndexDatum(BuildIndexInfo(indexDesc), tableslot, estate, values,
     980                 :             :                    isnull);
     981                 :         219 : }
     982                 :             : 
     983                 :             : /*
     984                 :             :  * Helper functions to construct a string describing the contents of an index
     985                 :             :  * entry. See BuildIndexValueDescription for details.
     986                 :             :  *
     987                 :             :  * The caller must ensure that the index with the OID 'indexoid' is locked so
     988                 :             :  * that we can fetch and display the conflicting key value.
     989                 :             :  */
     990                 :             : static char *
     991                 :         209 : build_index_value_desc(EState *estate, Relation localrel, TupleTableSlot *slot,
     992                 :             :                        Oid indexoid)
     993                 :             : {
     994                 :             :     char       *index_value;
     995                 :             :     Relation    indexDesc;
     996                 :             :     Datum       values[INDEX_MAX_KEYS];
     997                 :             :     bool        isnull[INDEX_MAX_KEYS];
     998                 :             : 
     999         [ -  + ]:         209 :     if (!slot)
    1000                 :           0 :         return NULL;
    1001                 :             : 
    1002                 :             :     Assert(CheckRelationOidLockedByMe(indexoid, RowExclusiveLock, true));
    1003                 :             : 
    1004                 :         209 :     indexDesc = index_open(indexoid, NoLock);
    1005                 :             : 
    1006                 :         209 :     build_index_datums_from_slot(estate, localrel, slot, indexDesc, values,
    1007                 :             :                                  isnull);
    1008                 :             : 
    1009                 :         209 :     index_value = BuildIndexValueDescription(indexDesc, values, isnull);
    1010                 :             : 
    1011                 :         209 :     index_close(indexDesc, NoLock);
    1012                 :             : 
    1013                 :         209 :     return index_value;
    1014                 :             : }
    1015                 :             : 
    1016                 :             : /*
    1017                 :             :  * build_index_key_json
    1018                 :             :  *
    1019                 :             :  * Fetch replica identity key from the tuple table slot and convert into a
    1020                 :             :  * JSON datum.
    1021                 :             :  *
    1022                 :             :  * The caller must ensure that the index with the OID 'indexid' is locked so
    1023                 :             :  * that we can safely fetch and construct the replica identity key values.
    1024                 :             :  * See comments atop ReportApplyConflict() for how this holds.
    1025                 :             :  */
    1026                 :             : static Datum
    1027                 :          10 : build_index_key_json(EState *estate, Relation localrel,
    1028                 :             :                      Oid indexid, TupleTableSlot *slot,
    1029                 :             :                      bool *omitted)
    1030                 :             : {
    1031                 :             :     Relation    indexDesc;
    1032                 :          10 :     TupleDesc   reltupdesc = RelationGetDescr(localrel);
    1033                 :             :     Datum       values[INDEX_MAX_KEYS];
    1034                 :             :     bool        isnull[INDEX_MAX_KEYS];
    1035                 :             :     StringInfoData result;
    1036                 :             :     int         indnkeyatts;
    1037                 :             :     Datum       datum;
    1038                 :             : 
    1039                 :             :     Assert(slot != NULL);
    1040                 :             : 
    1041                 :             :     Assert(CheckRelationOidLockedByMe(indexid, RowExclusiveLock, true));
    1042                 :             : 
    1043                 :          10 :     indexDesc = index_open(indexid, NoLock);
    1044                 :             : 
    1045                 :          10 :     build_index_datums_from_slot(estate, localrel, slot, indexDesc, values,
    1046                 :             :                                  isnull);
    1047                 :             : 
    1048                 :             :     /*
    1049                 :             :      * Build the JSON object here rather than passing the values to
    1050                 :             :      * row_to_json(). For a type at or above FirstNormalObjectId,
    1051                 :             :      * json_categorize_type() would use a user-defined cast to json if one
    1052                 :             :      * exists. Nothing else in apply calls that cast, so its output is
    1053                 :             :      * unrelated to the size of the value we received, and a small key could
    1054                 :             :      * produce a json value over the 1GB limit and fail the apply worker.
    1055                 :             :      * Rendering each value with its type's output function keeps us to the
    1056                 :             :      * representation the publisher sent (when the column types and output
    1057                 :             :      * settings match, see below), and matches what the server log does in
    1058                 :             :      * BuildIndexValueDescription().
    1059                 :             :      *
    1060                 :             :      * Only the key attributes are recorded. FormIndexDatum() above also fills
    1061                 :             :      * in any non-key (INCLUDE) columns, but those are not part of the replica
    1062                 :             :      * identity.
    1063                 :             :      */
    1064                 :          10 :     indnkeyatts = IndexRelationGetNumberOfKeyAttributes(indexDesc);
    1065                 :             : 
    1066                 :          10 :     initStringInfo(&result);
    1067                 :          10 :     appendStringInfoChar(&result, '{');
    1068                 :             : 
    1069         [ +  + ]:          21 :     for (int i = 0; i < indnkeyatts; i++)
    1070                 :             :     {
    1071                 :             :         Form_pg_attribute att;
    1072                 :             :         AttrNumber  attnum;
    1073                 :             : 
    1074                 :             :         /*
    1075                 :             :          * Take the column name from the table, not the index descriptor. The
    1076                 :             :          * index keeps the name it had at creation, which goes stale after a
    1077                 :             :          * column rename and can be wrong for repeated columns such as UNIQUE
    1078                 :             :          * (a, a). Using the table's names keeps these consistent with the
    1079                 :             :          * server log.
    1080                 :             :          *
    1081                 :             :          * Replica identity and primary key indexes have no expression
    1082                 :             :          * columns, so every key maps to a table column.
    1083                 :             :          */
    1084                 :          11 :         attnum = indexDesc->rd_index->indkey.values[i];
    1085                 :             :         Assert(attnum > 0);
    1086                 :             : 
    1087                 :          11 :         att = TupleDescAttr(reltupdesc, attnum - 1);
    1088                 :             : 
    1089         [ +  + ]:          11 :         if (i > 0)
    1090                 :           1 :             appendStringInfoChar(&result, ',');
    1091                 :             : 
    1092                 :          11 :         escape_json(&result, NameStr(att->attname));
    1093                 :          11 :         appendStringInfoChar(&result, ':');
    1094                 :             : 
    1095         [ -  + ]:          11 :         if (isnull[i])
    1096                 :           0 :             appendStringInfoString(&result, "null");
    1097                 :             :         else
    1098                 :             :         {
    1099                 :             :             Oid         outfuncoid;
    1100                 :             :             bool        typisvarlena;
    1101                 :             :             char       *outputstr;
    1102                 :             :             Size        outputlen;
    1103                 :             : 
    1104                 :             :             /*
    1105                 :             :              * See BuildIndexValueDescription() for why we used rd_opcintype
    1106                 :             :              * instead of index's tupleDesc.
    1107                 :             :              */
    1108                 :          11 :             getTypeOutputInfo(indexDesc->rd_opcintype[i], &outfuncoid, &typisvarlena);
    1109                 :             : 
    1110                 :             :             /*
    1111                 :             :              * XXX The cap below is checked only after the value is rendered.
    1112                 :             :              * The publisher rendered the same value to send it, which bounds
    1113                 :             :              * its length, unless the column types differ, subscription option
    1114                 :             :              * binary = true, or the apply worker's bytea_output or
    1115                 :             :              * quote_all_identifiers differs. Then the render can exceed 1GB
    1116                 :             :              * and error out the apply worker.
    1117                 :             :              */
    1118                 :          11 :             outputstr = OidOutputFunctionCall(outfuncoid, values[i]);
    1119                 :          11 :             outputlen = strlen(outputstr);
    1120                 :             : 
    1121                 :             :             /*
    1122                 :             :              * Don't record a value larger than CONFLICT_MAX_VALUE_SIZE.
    1123                 :             :              * Instead, put a marker recording its length in its place.
    1124                 :             :              *
    1125                 :             :              * XXX The marker deliberately keeps no prefix of the value. For
    1126                 :             :              * arrays, composites and similar types the leading bytes are
    1127                 :             :              * mostly punctuation and say little about the value.
    1128                 :             :              */
    1129         [ +  + ]:          11 :             if (outputlen > CONFLICT_MAX_VALUE_SIZE)
    1130                 :             :             {
    1131                 :             :                 /* A marker is an object, so it is appended unescaped. */
    1132                 :           1 :                 appendStringInfo(&result,
    1133                 :             :                                  "{\"omitted\":true,\"length\":" UINT64_FORMAT "}",
    1134                 :             :                                  (uint64) outputlen);
    1135                 :           1 :                 *omitted = true;
    1136                 :           1 :                 pfree(outputstr);
    1137                 :           1 :                 continue;
    1138                 :             :             }
    1139                 :             : 
    1140                 :          10 :             escape_json(&result, outputstr);
    1141                 :          10 :             pfree(outputstr);
    1142                 :             :         }
    1143                 :             :     }
    1144                 :             : 
    1145                 :          10 :     appendStringInfoChar(&result, '}');
    1146                 :             : 
    1147                 :          10 :     index_close(indexDesc, NoLock);
    1148                 :             : 
    1149                 :          10 :     datum = PointerGetDatum(cstring_to_text_with_len(result.data, result.len));
    1150                 :          10 :     pfree(result.data);
    1151                 :             : 
    1152                 :          10 :     return datum;
    1153                 :             : }
    1154                 :             : 
    1155                 :             : /*
    1156                 :             :  * build_local_conflicts_tupledesc
    1157                 :             :  *
    1158                 :             :  * Build and bless a tuple descriptor for the elements of the local_conflicts
    1159                 :             :  * array based on the predefined LocalConflictSchema.
    1160                 :             :  */
    1161                 :             : static TupleDesc
    1162                 :           6 : build_local_conflicts_tupledesc(void)
    1163                 :             : {
    1164                 :             :     static TupleDesc cached_tupdesc = NULL;
    1165                 :             : 
    1166         [ +  + ]:           6 :     if (cached_tupdesc == NULL)
    1167                 :             :     {
    1168                 :             :         MemoryContext oldcxt;
    1169                 :             : 
    1170                 :           5 :         oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
    1171                 :             : 
    1172                 :           5 :         cached_tupdesc = CreateTemplateTupleDesc(NUM_LOCAL_CONFLICT_ATTRS);
    1173                 :             : 
    1174         [ +  + ]:          20 :         for (int i = 0; i < NUM_LOCAL_CONFLICT_ATTRS; i++)
    1175                 :          15 :             TupleDescInitEntry(cached_tupdesc,
    1176                 :          15 :                                (AttrNumber) (i + 1),
    1177                 :          15 :                                LocalConflictSchema[i].attname,
    1178                 :          15 :                                LocalConflictSchema[i].atttypid,
    1179                 :             :                                -1, 0);
    1180                 :             : 
    1181                 :           5 :         TupleDescFinalize(cached_tupdesc);
    1182                 :             : 
    1183                 :             :         /*
    1184                 :             :          * Bless once so it can be used as a RECORD type (e.g. for row_to_json
    1185                 :             :          * or other record-based operations).
    1186                 :             :          */
    1187                 :           5 :         BlessTupleDesc(cached_tupdesc);
    1188                 :             : 
    1189                 :           5 :         MemoryContextSwitchTo(oldcxt);
    1190                 :             :     }
    1191                 :             : 
    1192                 :           6 :     return cached_tupdesc;
    1193                 :             : }
    1194                 :             : 
    1195                 :             : /*
    1196                 :             :  * Builds the local conflicts JSON array column from the list of
    1197                 :             :  * ConflictTupleInfo objects.
    1198                 :             :  *
    1199                 :             :  * Example output structure:
    1200                 :             :  * [ { "xid": "1001", "commit_ts": "...", "origin": "..." }, ... ]
    1201                 :             :  */
    1202                 :             : static Datum
    1203                 :           6 : build_local_conflicts_json_array(List *conflicttuples)
    1204                 :             : {
    1205                 :             :     Datum      *json_datum_array;
    1206                 :             :     Datum       json_array_datum;
    1207                 :             :     int         num_conflicts;
    1208                 :           6 :     int         i = 0;
    1209                 :             :     int16       typlen;
    1210                 :             :     bool        typbyval;
    1211                 :             :     char        typalign;
    1212                 :             :     TupleDesc   tupdesc;
    1213                 :             : 
    1214                 :             :     Assert(conflicttuples != NIL);
    1215                 :             : 
    1216                 :             :     /* Build local conflicts tuple descriptor. */
    1217                 :           6 :     tupdesc = build_local_conflicts_tupledesc();
    1218                 :             : 
    1219                 :           6 :     num_conflicts = list_length(conflicttuples);
    1220                 :           6 :     json_datum_array = palloc_array(Datum, num_conflicts);
    1221                 :             : 
    1222                 :             :     /* Process local conflict tuple list and prepare an array of JSON. */
    1223   [ +  -  +  +  :          18 :     foreach_ptr(ConflictTupleInfo, conflicttuple, conflicttuples)
                   +  + ]
    1224                 :             :     {
    1225                 :           6 :         Datum       values[NUM_LOCAL_CONFLICT_ATTRS] = {0};
    1226                 :           6 :         bool        nulls[NUM_LOCAL_CONFLICT_ATTRS] = {0};
    1227                 :           6 :         char       *origin_name = NULL;
    1228                 :             :         HeapTuple   tuple;
    1229                 :             :         Datum       datum;
    1230                 :             :         Datum       json_datum;
    1231                 :             :         int         attno;
    1232                 :             : 
    1233                 :           6 :         attno = 0;
    1234         [ +  - ]:           6 :         if (FullTransactionIdIsValid(conflicttuple->xmin))
    1235                 :           6 :             values[attno++] = FullTransactionIdGetDatum(conflicttuple->xmin);
    1236                 :             :         else
    1237                 :           0 :             nulls[attno++] = true;
    1238                 :             : 
    1239         [ +  - ]:           6 :         if (conflicttuple->ts)
    1240                 :           6 :             values[attno++] = TimestampTzGetDatum(conflicttuple->ts);
    1241                 :             :         else
    1242                 :           0 :             nulls[attno++] = true;
    1243                 :             : 
    1244         [ -  + ]:           6 :         if (conflicttuple->origin != InvalidReplOriginId)
    1245                 :           0 :             replorigin_by_oid(conflicttuple->origin, true, &origin_name);
    1246                 :             : 
    1247                 :             :         /*
    1248                 :             :          * Set NULL if origin name for the tuple is InvalidReplOriginId or not
    1249                 :             :          * found.
    1250                 :             :          */
    1251         [ -  + ]:           6 :         if (origin_name != NULL)
    1252                 :           0 :             values[attno++] = CStringGetTextDatum(origin_name);
    1253                 :             :         else
    1254                 :           6 :             nulls[attno++] = true;
    1255                 :             : 
    1256                 :             :         Assert(attno == NUM_LOCAL_CONFLICT_ATTRS);
    1257                 :             : 
    1258                 :           6 :         tuple = heap_form_tuple(tupdesc, values, nulls);
    1259                 :             : 
    1260                 :           6 :         datum = heap_copy_tuple_as_datum(tuple, tupdesc);
    1261                 :             : 
    1262                 :             :         /*
    1263                 :             :          * Build the higher level JSON datum in format described in function
    1264                 :             :          * header.
    1265                 :             :          *
    1266                 :             :          * Unlike build_index_key_json(), using row_to_json() is safe here
    1267                 :             :          * because the object's fields are all built-in types (xid8,
    1268                 :             :          * timestamptz, text) below FirstNormalObjectId, so
    1269                 :             :          * json_categorize_type() never invokes a user CREATE CAST (t AS
    1270                 :             :          * json), and the values are small and bounded.
    1271                 :             :          */
    1272                 :           6 :         json_datum = DirectFunctionCall1(row_to_json, datum);
    1273                 :             : 
    1274                 :             :         /* Done with the temporary tuple. */
    1275                 :           6 :         heap_freetuple(tuple);
    1276                 :             : 
    1277                 :             :         /* Add to the array element. */
    1278                 :           6 :         json_datum_array[i++] = json_datum;
    1279                 :             :     }
    1280                 :             : 
    1281                 :             :     Assert(i == num_conflicts);
    1282                 :             : 
    1283                 :             :     /* Construct the JSON array Datum. */
    1284                 :           6 :     get_typlenbyvalalign(JSONOID, &typlen, &typbyval, &typalign);
    1285                 :           6 :     json_array_datum = PointerGetDatum(construct_array(json_datum_array,
    1286                 :             :                                                        num_conflicts,
    1287                 :             :                                                        JSONOID,
    1288                 :             :                                                        typlen,
    1289                 :             :                                                        typbyval,
    1290                 :             :                                                        typalign));
    1291                 :           6 :     pfree(json_datum_array);
    1292                 :             : 
    1293                 :           6 :     return json_array_datum;
    1294                 :             : }
    1295                 :             : 
    1296                 :             : /*
    1297                 :             :  * insert_conflict_log_tuple
    1298                 :             :  *
    1299                 :             :  * Prepares and inserts a tuple detailing a conflict encountered during
    1300                 :             :  * logical replication into the conflict log table.
    1301                 :             :  */
    1302                 :             : static void
    1303                 :          14 : insert_conflict_log_tuple(EState *estate, Relation rel,
    1304                 :             :                           Relation conflictlogrel,
    1305                 :             :                           ConflictType conflict_type,
    1306                 :             :                           Oid searchindexoid,
    1307                 :             :                           TupleTableSlot *searchslot,
    1308                 :             :                           List *conflicttuples)
    1309                 :             : {
    1310                 :          14 :     Datum       values[NUM_CONFLICT_ATTRS] = {0};
    1311                 :          14 :     bool        nulls[NUM_CONFLICT_ATTRS] = {0};
    1312                 :             :     int         attno;
    1313                 :          14 :     char       *apply_origin = NULL;
    1314                 :             :     TransactionId remote_xid;
    1315                 :             :     XLogRecPtr  remote_final_lsn;
    1316                 :             :     TimestampTz remote_commit_ts;
    1317                 :          14 :     bool        omitted = false;
    1318                 :             :     Oid         replica_index;
    1319                 :             :     HeapTuple   tuple;
    1320                 :             : 
    1321                 :             :     Assert(conflictlogrel != NULL);
    1322                 :             : 
    1323                 :             :     /* Fetch the information of the remote transaction being applied. */
    1324                 :          14 :     GetRemoteTransactionInfoForConflict(&remote_xid, &remote_final_lsn,
    1325                 :             :                                         &remote_commit_ts);
    1326                 :             : 
    1327                 :             :     /* Populate the values and nulls arrays. */
    1328                 :          14 :     attno = 0;
    1329                 :          14 :     values[attno++] = ObjectIdGetDatum(RelationGetRelid(rel));
    1330                 :             : 
    1331                 :          14 :     values[attno++] =
    1332                 :          14 :         CStringGetTextDatum(get_namespace_name(RelationGetNamespace(rel)));
    1333                 :             : 
    1334                 :          14 :     values[attno++] = CStringGetTextDatum(RelationGetRelationName(rel));
    1335                 :             : 
    1336                 :          14 :     values[attno++] = CStringGetTextDatum(ConflictTypeNames[conflict_type]);
    1337                 :             : 
    1338                 :             :     /*
    1339                 :             :      * The remote xid is always valid here: a conflict is only detected while
    1340                 :             :      * applying a row change, which is preceded by a BEGIN, BEGIN PREPARE or
    1341                 :             :      * STREAM START that recorded a valid top-level xid.
    1342                 :             :      */
    1343                 :             :     Assert(TransactionIdIsValid(remote_xid));
    1344                 :          14 :     values[attno++] = TransactionIdGetDatum(remote_xid);
    1345                 :             : 
    1346         [ +  - ]:          14 :     if (XLogRecPtrIsValid(remote_final_lsn))
    1347                 :          14 :         values[attno++] = LSNGetDatum(remote_final_lsn);
    1348                 :             :     else
    1349                 :           0 :         nulls[attno++] = true;
    1350                 :             : 
    1351         [ +  + ]:          14 :     if (remote_commit_ts != 0)
    1352                 :          13 :         values[attno++] = TimestampTzGetDatum(remote_commit_ts);
    1353                 :             :     else
    1354                 :           1 :         nulls[attno++] = true;
    1355                 :             : 
    1356         [ +  - ]:          14 :     if (replorigin_xact_state.origin != InvalidReplOriginId)
    1357                 :          14 :         replorigin_by_oid(replorigin_xact_state.origin, true, &apply_origin);
    1358                 :             : 
    1359         [ +  - ]:          14 :     if (apply_origin != NULL)
    1360                 :          14 :         values[attno++] = CStringGetTextDatum(apply_origin);
    1361                 :             :     else
    1362                 :           0 :         nulls[attno++] = true;
    1363                 :             : 
    1364                 :             :     /*
    1365                 :             :      * All conflicts logged to the table are LOG-level update or delete
    1366                 :             :      * conflicts, which always have a searchslot. Insert conflicts, which
    1367                 :             :      * don't, are ERROR-level and never reach here.
    1368                 :             :      */
    1369                 :             :     Assert(!TupIsNull(searchslot));
    1370                 :             : 
    1371                 :          14 :     replica_index = searchindexoid;
    1372                 :             : 
    1373                 :             :     /*
    1374                 :             :      * If the search used a replica identity index, build the index JSON datum
    1375                 :             :      * from key value. Otherwise, in REPLICA IDENTITY FULL cases, set
    1376                 :             :      * replica_identity_full to true and leave replica_identity NULL to avoid
    1377                 :             :      * serializing full tuples that could exceed memory allocation limits.
    1378                 :             :      */
    1379         [ +  + ]:          14 :     if (OidIsValid(replica_index))
    1380                 :             :     {
    1381                 :          10 :         values[attno++] = BoolGetDatum(false);
    1382                 :          10 :         values[attno++] = build_index_key_json(estate, rel,
    1383                 :             :                                                replica_index,
    1384                 :             :                                                searchslot,
    1385                 :             :                                                &omitted);
    1386                 :             :     }
    1387                 :             :     else
    1388                 :             :     {
    1389                 :           4 :         values[attno++] = BoolGetDatum(true);
    1390                 :           4 :         nulls[attno++] = true;
    1391                 :             :     }
    1392                 :             : 
    1393                 :             :     /*
    1394                 :             :      * In update_missing and delete_missing conflicts, there are no local
    1395                 :             :      * conflicting rows, so set local_conflicts to NULL.
    1396                 :             :      */
    1397         [ +  + ]:          14 :     if (conflicttuples != NIL)
    1398                 :           6 :         values[attno++] = build_local_conflicts_json_array(conflicttuples);
    1399                 :             :     else
    1400                 :           8 :         nulls[attno++] = true;
    1401                 :             : 
    1402                 :          14 :     values[attno] = BoolGetDatum(omitted);
    1403                 :             : 
    1404                 :             :     Assert(attno + 1 == NUM_CONFLICT_ATTRS);
    1405                 :             : 
    1406                 :             :     /*
    1407                 :             :      * Conflict log tables are always created with the heap access method (see
    1408                 :             :      * create_conflict_log_table()) and cannot be altered, so we can call
    1409                 :             :      * heap_insert() directly instead of creating a TupleTableSlot for
    1410                 :             :      * table_tuple_insert().
    1411                 :             :      *
    1412                 :             :      * The conflict log table itself is never logically decoded, but its TOAST
    1413                 :             :      * table would be. heap_insert() passes HEAP_INSERT_NO_LOGICAL on to the
    1414                 :             :      * TOAST inserts, so toasted values are not decoded either.
    1415                 :             :      */
    1416                 :          14 :     tuple = heap_form_tuple(RelationGetDescr(conflictlogrel), values, nulls);
    1417                 :             : 
    1418                 :          14 :     heap_insert(conflictlogrel, tuple,
    1419                 :             :                 GetCurrentCommandId(true), HEAP_INSERT_NO_LOGICAL, NULL);
    1420                 :             : 
    1421                 :          14 :     heap_freetuple(tuple);
    1422                 :          14 : }
        

Generated by: LCOV version 2.0-1