LCOV - differential code coverage report
Current view: top level - src/backend/replication/logical - conflict.c (source / functions) Coverage Total Hit UNC UBC GIC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 90.7 % 367 333 8 26 1 185 147 14
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 17 17 11 6
Baseline: lcov-20261128-baseline Branches: 70.2 % 252 177 29 46 83 94
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 95.2 % 167 159 8 159
(30,360] days: 81.4 % 113 92 21 26 66
(360..) days: 94.3 % 87 82 5 1 81
Function coverage date bins:
(1,7] days: 100.0 % 6 6 6
(30,360] days: 100.0 % 5 5 3 2
(360..) days: 100.0 % 6 6 2 4
Branch coverage date bins:
(1,7] days: 72.9 % 96 70 26 70
(30,360] days: 65.9 % 82 54 3 25 13 41
(360..) days: 71.6 % 74 53 21 53

 Age         Owner                    Branch data    TLA  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
  149 akapila@postgresql.o      175                 :GNC          18 : create_conflict_log_table_tupdesc(void)
                                176                 :                : {
                                177                 :                :     TupleDesc   tupdesc;
                                178                 :                : 
                                179                 :             18 :     tupdesc = CreateTemplateTupleDesc(NUM_CONFLICT_ATTRS);
                                180                 :                : 
                                181         [ +  + ]:            234 :     for (int i = 0; i < NUM_CONFLICT_ATTRS; i++)
                                182                 :            216 :         TupleDescInitEntry(tupdesc, i + 1,
                                183                 :            216 :                            ConflictLogSchema[i].attname,
                                184                 :            216 :                            ConflictLogSchema[i].atttypid,
                                185                 :                :                            -1, 0);
                                186                 :                : 
                                187                 :             18 :     TupleDescFinalize(tupdesc);
                                188                 :                : 
                                189                 :             18 :     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                 :             18 : create_conflict_log_table(Oid subid, char *subname, Oid subowner)
                                205                 :                : {
                                206                 :                :     TupleDesc   tupdesc;
                                207                 :                :     Oid         relid;
                                208                 :                :     char        relname[NAMEDATALEN];
                                209                 :                : 
                                210                 :             18 :     snprintf(relname, NAMEDATALEN, "pg_conflict_log_%u", subid);
                                211                 :                : 
                                212                 :                :     /* Build the tuple descriptor for the new table. */
                                213                 :             18 :     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                 :             18 :     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         [ -  + ]:             18 :     Assert(OidIsValid(relid));
                                242                 :                : 
                                243                 :                :     /* Release tuple descriptor memory. */
                                244                 :             18 :     FreeTupleDesc(tupdesc);
                                245                 :                : 
                                246                 :                :     /*
                                247                 :                :      * We must bump the command counter to make the newly-created relation
                                248                 :                :      * tuple visible for opening.
                                249                 :                :      */
                                250                 :             18 :     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                 :             18 :     NewRelationCreateToastTable(relid, (Datum) 0);
                                257                 :                : 
                                258         [ +  + ]:             18 :     ereport(NOTICE,
                                259                 :                :             (errmsg("created conflict log table \"%s\" for subscription \"%s\"",
                                260                 :                :                     get_qualified_objname(PG_CONFLICT_NAMESPACE, relname),
                                261                 :                :                     subname)));
                                262                 :                : 
                                263                 :             18 :     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                 :            112 : GetConflictLogDest(const char *dest)
                                272                 :                : {
                                273                 :                :     /* NULL defaults to LOG. */
                                274   [ +  -  +  + ]:            112 :     if (dest == NULL || pg_strcasecmp(dest, "log") == 0)
                                275                 :             42 :         return CONFLICT_LOG_DEST_LOG;
                                276                 :                : 
                                277         [ +  + ]:             70 :     if (pg_strcasecmp(dest, "table") == 0)
                                278                 :             39 :         return CONFLICT_LOG_DEST_TABLE;
                                279                 :                : 
                                280         [ +  + ]:             31 :     if (pg_strcasecmp(dest, "all") == 0)
                                281                 :             23 :         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
  830 akapila@postgresql.o      297                 :CBC       72358 : GetTupleTransactionInfo(TupleTableSlot *localslot, TransactionId *xmin,
                                298                 :                :                         ReplOriginId *localorigin, TimestampTz *localts)
                                299                 :                : {
                                300                 :                :     Datum       xminDatum;
                                301                 :                :     bool        isnull;
                                302                 :                : 
                                303                 :          72358 :     xminDatum = slot_getsysattr(localslot, MinTransactionIdAttributeNumber,
                                304                 :                :                                 &isnull);
                                305                 :          72358 :     *xmin = DatumGetTransactionId(xminDatum);
                                306         [ -  + ]:          72358 :     Assert(!isnull);
                                307                 :                : 
                                308                 :                :     /*
                                309                 :                :      * The commit timestamp data is not available if track_commit_timestamp is
                                310                 :                :      * disabled.
                                311                 :                :      */
                                312         [ +  + ]:          72358 :     if (!track_commit_timestamp)
                                313                 :                :     {
  304 msawada@postgresql.o      314                 :          72248 :         *localorigin = InvalidReplOriginId;
  830 akapila@postgresql.o      315                 :          72248 :         *localts = 0;
                                316                 :          72248 :         return false;
                                317                 :                :     }
                                318                 :                : 
                                319                 :            110 :     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                 :             92 : ReportApplyConflict(EState *estate, ResultRelInfo *relinfo, int elevel,
                                344                 :                :                     ConflictType type, LogicalRepRelMapEntry *relmapentry,
                                345                 :                :                     TupleTableSlot *searchslot,
                                346                 :                :                     TupleTableSlot *remoteslot, List *conflicttuples)
                                347                 :                : {
                                348                 :             92 :     Relation    localrel = relinfo->ri_RelationDesc;
                                349                 :                :     ConflictLogDest dest;
    4 akapila@postgresql.o      350                 :GNC          92 :     Oid         searchindexoid = InvalidOid;
                                351                 :                :     Relation    conflictlogrel;
                                352                 :                :     StringInfoData err_detail;
                                353                 :                : 
                                354                 :             92 :     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   [ +  +  +  + ]:             92 :     if (relmapentry && relmapentry->idxisreplident)
                                363                 :             27 :         searchindexoid = relmapentry->localindexoid;
                                364                 :                : 
                                365                 :             92 :     conflictlogrel = get_conflictlog_dest_and_table(elevel, &dest);
                                366                 :                : 
  614 akapila@postgresql.o      367                 :CBC          92 :     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                 :                :      */
    4 akapila@postgresql.o      373   [ +  +  +  + ]:GNC          92 :     if (CONFLICTS_LOGGED_TO_LOG(dest))
                                374                 :                :     {
                                375                 :                :         /* Form errdetail message by combining conflicting tuples information. */
                                376         [ +  + ]:             91 :         if (conflicttuples != NIL)
                                377                 :                :         {
                                378   [ +  -  +  +  :            269 :             foreach_ptr(ConflictTupleInfo, conflicttuple, conflicttuples)
                                              +  + ]
                                379                 :            127 :                 errdetail_apply_conflict(estate, relinfo, type, searchslot,
                                380                 :                :                                          conflicttuple->slot, remoteslot,
                                381                 :                :                                          conflicttuple->indexoid,
                                382                 :            127 :                                          XidFromFullTransactionId(conflicttuple->xmin),
                                383                 :            127 :                                          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         [ -  + ]:              1 :         Assert(conflictlogrel);
                                401                 :                : 
                                402                 :              2 :         appendStringInfo(&err_detail,
                                403                 :              1 :                          _("Conflict details are logged to the conflict log table \"%s.%s\"."),
                                404                 :              1 :                          get_namespace_name(RelationGetNamespace(conflictlogrel)),
                                405                 :              1 :                          RelationGetRelationName(conflictlogrel));
                                406                 :                :     }
                                407                 :                : 
  830 akapila@postgresql.o      408         [ +  - ]:CBC          92 :     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                 :                :      */
    4 akapila@postgresql.o      420         [ +  + ]:GNC          32 :     if (conflictlogrel)
                                421                 :                :     {
                                422                 :             13 :         insert_conflict_log_tuple(estate,
                                423                 :                :                                   relinfo->ri_RelationDesc,
                                424                 :                :                                   conflictlogrel,
                                425                 :                :                                   type,
                                426                 :                :                                   searchindexoid,
                                427                 :                :                                   searchslot,
                                428                 :                :                                   conflicttuples);
                                429                 :             13 :         table_close(conflictlogrel, NoLock);
                                430                 :                :     }
  830 akapila@postgresql.o      431                 :CBC          32 : }
                                432                 :                : 
                                433                 :                : /*
                                434                 :                :  * Find all unique indexes to check for a conflict and store them into
                                435                 :                :  * ResultRelInfo.
                                436                 :                :  */
                                437                 :                : void
                                438                 :         128107 : InitConflictIndexes(ResultRelInfo *relInfo)
                                439                 :                : {
                                440                 :         128107 :     List       *uniqueIndexes = NIL;
                                441                 :                : 
                                442         [ +  + ]:         235821 :     for (int i = 0; i < relInfo->ri_NumIndices; i++)
                                443                 :                :     {
                                444                 :         107714 :         Relation    indexRelation = relInfo->ri_IndexRelationDescs[i];
                                445                 :                : 
                                446         [ -  + ]:         107714 :         if (indexRelation == NULL)
  830 akapila@postgresql.o      447                 :UBC           0 :             continue;
                                448                 :                : 
                                449                 :                :         /* Detect conflict only for unique indexes */
  830 akapila@postgresql.o      450         [ +  + ]:CBC      107714 :         if (!relInfo->ri_IndexRelationInfo[i]->ii_Unique)
                                451                 :             30 :             continue;
                                452                 :                : 
                                453                 :                :         /* Don't support conflict detection for deferrable index */
                                454         [ -  + ]:         107684 :         if (!indexRelation->rd_index->indimmediate)
  830 akapila@postgresql.o      455                 :UBC           0 :             continue;
                                456                 :                : 
  830 akapila@postgresql.o      457                 :CBC      107684 :         uniqueIndexes = lappend_oid(uniqueIndexes,
                                458                 :                :                                     RelationGetRelid(indexRelation));
                                459                 :                :     }
                                460                 :                : 
                                461                 :         128107 :     relInfo->ri_onConflictArbiterIndexes = uniqueIndexes;
                                462                 :         128107 : }
                                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
    4 akapila@postgresql.o      478                 :GNC          92 : get_conflictlog_dest_and_table(int elevel, ConflictLogDest *log_dest)
                                479                 :                : {
                                480                 :                :     Relation    conflictlogrel;
                                481                 :                :     Oid         conflictlogrelid;
                                482                 :                : 
                                483         [ +  + ]:             92 :     if (elevel >= ERROR)
                                484                 :                :     {
                                485                 :             60 :         *log_dest = CONFLICT_LOG_DEST_LOG;
                                486                 :             60 :         return NULL;
                                487                 :                :     }
                                488                 :                : 
                                489                 :                :     /* Convert the text log destination to the internal enum. */
                                490                 :             32 :     *log_dest = GetConflictLogDest(MySubscription->conflictlogdest);
                                491                 :                : 
                                492                 :                :     /* Quick exit if a conflict log table was not requested. */
                                493   [ +  +  +  + ]:             32 :     if (!CONFLICTS_LOGGED_TO_TABLE(*log_dest))
                                494                 :             19 :         return NULL;
                                495                 :                : 
                                496                 :             13 :     conflictlogrelid = MySubscription->conflictlogrelid;
                                497                 :                : 
                                498         [ -  + ]:             13 :     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                 :             13 :     conflictlogrel = try_table_open(conflictlogrelid, RowExclusiveLock);
                                507                 :                : 
                                508         [ -  + ]:             13 :     if (!conflictlogrel)
    4 akapila@postgresql.o      509                 :UNC           0 :         *log_dest = CONFLICT_LOG_DEST_LOG;
                                510                 :                : 
    4 akapila@postgresql.o      511                 :GNC          13 :     return conflictlogrel;
                                512                 :                : }
                                513                 :                : 
                                514                 :                : /*
                                515                 :                :  * Add SQLSTATE error code to the current conflict report.
                                516                 :                :  */
                                517                 :                : static int
  830 akapila@postgresql.o      518                 :CBC          92 : errcode_apply_conflict(ConflictType type)
                                519                 :                : {
                                520      [ +  +  - ]:             92 :     switch (type)
                                521                 :                :     {
                                522                 :             60 :         case CT_INSERT_EXISTS:
                                523                 :                :         case CT_UPDATE_EXISTS:
                                524                 :                :         case CT_MULTIPLE_UNIQUE_CONFLICTS:
                                525                 :             60 :             return errcode(ERRCODE_UNIQUE_VIOLATION);
  821                           526                 :             32 :         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:
  830                           531                 :             32 :             return errcode(ERRCODE_T_R_SERIALIZATION_FAILURE);
                                532                 :                :     }
                                533                 :                : 
  830 akapila@postgresql.o      534                 :UBC           0 :     Assert(false);
                                535                 :                :     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
  208 akapila@postgresql.o      543                 :CBC         207 : append_tuple_value_detail(StringInfo buf, List *tuple_values)
                                544                 :                : {
  311                           545                 :            207 :     bool        first = true;
                                546                 :                : 
                                547   [ +  -  -  + ]:            207 :     Assert(buf != NULL && tuple_values != NIL);
                                548                 :                : 
                                549   [ +  -  +  +  :            824 :     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         [ +  + ]:            410 :         if (!tuple_value)
                                557                 :             63 :             continue;
                                558                 :                : 
                                559                 :                :         /* standard SQL punctuation, not translated */
  208                           560         [ +  + ]:            347 :         if (!first)
                                561                 :            140 :             appendStringInfoString(buf, ", ");
                                562                 :                : 
  311                           563                 :            347 :         appendStringInfoString(buf, tuple_value);
                                564                 :            347 :         first = false;
                                565                 :                :     }
                                566                 :            207 : }
                                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
  830                           579                 :            147 : 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;
  311                           589                 :            147 :     char       *key_desc = NULL;
                                590                 :            147 :     char       *local_desc = NULL;
                                591                 :            147 :     char       *remote_desc = NULL;
                                592                 :            147 :     char       *search_desc = NULL;
                                593                 :                : 
                                594                 :                :     /* Get key, replica identity, remote, and local value data */
                                595                 :            147 :     get_tuple_desc(estate, relinfo, type, &key_desc,
                                596                 :                :                    localslot, &local_desc,
                                597                 :                :                    remoteslot, &remote_desc,
                                598                 :                :                    searchslot, &search_desc,
                                599                 :                :                    indexoid);
                                600                 :                : 
  830                           601                 :            147 :     initStringInfo(&err_detail);
  208                           602                 :            147 :     initStringInfo(&tuple_buf);
                                603                 :                : 
                                604                 :                :     /* Construct a detailed message describing the type of conflict */
  830                           605   [ +  +  +  +  :            147 :     switch (type)
                                           +  +  - ]
                                606                 :                :     {
                                607                 :            116 :         case CT_INSERT_EXISTS:
                                608                 :                :         case CT_UPDATE_EXISTS:
                                609                 :                :         case CT_MULTIPLE_UNIQUE_CONFLICTS:
  614                           610   [ +  -  -  + ]:            116 :             Assert(OidIsValid(indexoid) &&
                                611                 :                :                    CheckRelationOidLockedByMe(indexoid, RowExclusiveLock, true));
                                612                 :                : 
  311                           613         [ +  + ]:            116 :             if (err_msg->len == 0)
                                614                 :                :             {
  208                           615                 :             60 :                 append_tuple_value_detail(&tuple_buf,
                                616                 :                :                                           list_make2(remote_desc, search_desc));
                                617                 :                : 
                                618         [ +  - ]:             60 :                 if (tuple_buf.len)
                                619                 :             60 :                     appendStringInfo(&err_detail, _("Could not apply remote change: %s.\n"),
                                620                 :                :                                      tuple_buf.data);
                                621                 :                :                 else
  208 akapila@postgresql.o      622                 :UBC           0 :                     appendStringInfo(&err_detail, _("Could not apply remote change.\n"));
                                623                 :                : 
                                624                 :                : 
  208 akapila@postgresql.o      625                 :CBC          60 :                 resetStringInfo(&tuple_buf);
                                626                 :                :             }
                                627                 :                : 
                                628                 :            116 :             append_tuple_value_detail(&tuple_buf,
                                629                 :                :                                       list_make2(key_desc, local_desc));
                                630                 :                : 
  830                           631         [ +  + ]:            116 :             if (localts)
                                632                 :                :             {
  304 msawada@postgresql.o      633         [ -  + ]:              3 :                 if (localorigin == InvalidReplOriginId)
                                634                 :                :                 {
  208 akapila@postgresql.o      635         [ #  # ]:UBC           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                 :                :                 }
  830 akapila@postgresql.o      645         [ +  + ]:CBC           3 :                 else if (replorigin_by_oid(localorigin, true, &origin_name))
                                646                 :                :                 {
  208                           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
  208 akapila@postgresql.o      653                 :UBC           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                 :                :                 {
  208 akapila@postgresql.o      667         [ +  - ]:CBC           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
  208 akapila@postgresql.o      673                 :UBC           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                 :                :             {
  208 akapila@postgresql.o      680         [ +  - ]:CBC         113 :                 if (tuple_buf.len)
                                681                 :            113 :                     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
  208 akapila@postgresql.o      685                 :UBC           0 :                     appendStringInfo(&err_detail, _("Key already exists in unique index \"%s\", modified in transaction %u."),
                                686                 :                :                                      get_rel_name(indexoid), localxmin);
                                687                 :                :             }
                                688                 :                : 
  830 akapila@postgresql.o      689                 :CBC         116 :             break;
                                690                 :                : 
  821                           691                 :              3 :         case CT_UPDATE_ORIGIN_DIFFERS:
  208                           692                 :              3 :             append_tuple_value_detail(&tuple_buf,
                                693                 :                :                                       list_make3(local_desc, remote_desc,
                                694                 :                :                                                  search_desc));
                                695                 :                : 
  304 msawada@postgresql.o      696         [ +  + ]:              3 :             if (localorigin == InvalidReplOriginId)
                                697                 :                :             {
  208 akapila@postgresql.o      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
  208 akapila@postgresql.o      703                 :UBC           0 :                     appendStringInfo(&err_detail, _("Updating the row that was modified locally in transaction %u at %s."),
                                704                 :                :                                      localxmin, timestamptz_to_str(localts));
                                705                 :                :             }
  830 akapila@postgresql.o      706         [ +  + ]:CBC           2 :             else if (replorigin_by_oid(localorigin, true, &origin_name))
                                707                 :                :             {
  208                           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
  208 akapila@postgresql.o      714                 :UBC           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                 :                :             {
  208 akapila@postgresql.o      722         [ +  - ]:CBC           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
  208 akapila@postgresql.o      727                 :UBC           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                 :                : 
  830 akapila@postgresql.o      731                 :CBC           3 :             break;
                                732                 :                : 
  481                           733                 :              3 :         case CT_UPDATE_DELETED:
  208                           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
  208 akapila@postgresql.o      741                 :UBC           0 :                 appendStringInfo(&err_detail, _("Could not find the row to be updated.\n"));
                                742                 :                : 
  481 akapila@postgresql.o      743         [ +  - ]:CBC           3 :             if (localts)
                                744                 :                :             {
  304 msawada@postgresql.o      745         [ +  - ]:              3 :                 if (localorigin == InvalidReplOriginId)
   86 akapila@postgresql.o      746                 :              3 :                     appendStringInfo(&err_detail, _("The row to be updated was deleted locally in transaction %u at %s."),
                                747                 :                :                                      localxmin, timestamptz_to_str(localts));
  481 akapila@postgresql.o      748         [ #  # ]:UBC           0 :                 else if (replorigin_by_oid(localorigin, true, &origin_name))
   86                           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                 :                : 
  481 akapila@postgresql.o      760                 :CBC           3 :             break;
                                761                 :                : 
  830                           762                 :              8 :         case CT_UPDATE_MISSING:
  208                           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
  208 akapila@postgresql.o      770                 :UBC           0 :                 appendStringInfo(&err_detail, _("Could not find the row to be updated."));
                                771                 :                : 
  830 akapila@postgresql.o      772                 :CBC           8 :             break;
                                773                 :                : 
  821                           774                 :              5 :         case CT_DELETE_ORIGIN_DIFFERS:
  208                           775                 :              5 :             append_tuple_value_detail(&tuple_buf,
                                776                 :                :                                       list_make3(local_desc, remote_desc,
                                777                 :                :                                                  search_desc));
                                778                 :                : 
  304 msawada@postgresql.o      779         [ +  + ]:              5 :             if (localorigin == InvalidReplOriginId)
                                780                 :                :             {
  208 akapila@postgresql.o      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
  208 akapila@postgresql.o      786                 :UBC           0 :                     appendStringInfo(&err_detail, _("Deleting the row that was modified locally in transaction %u at %s."),
                                787                 :                :                                      localxmin, timestamptz_to_str(localts));
                                788                 :                :             }
  830 akapila@postgresql.o      789         [ +  - ]:CBC           1 :             else if (replorigin_by_oid(localorigin, true, &origin_name))
                                790                 :                :             {
  208                           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
  208 akapila@postgresql.o      797                 :UBC           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                 :                : 
  830 akapila@postgresql.o      814                 :CBC           5 :             break;
                                815                 :                : 
                                816                 :             12 :         case CT_DELETE_MISSING:
  208                           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
  208 akapila@postgresql.o      824                 :UBC           0 :                 appendStringInfo(&err_detail, _("Could not find the row to be deleted."));
                                825                 :                : 
  830 akapila@postgresql.o      826                 :CBC          12 :             break;
                                827                 :                :     }
                                828                 :                : 
                                829         [ -  + ]:            147 :     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                 :                :      */
  614                           835         [ +  + ]:            147 :     if (err_msg->len > 0)
                                836                 :             56 :         appendStringInfoChar(err_msg, '\n');
                                837                 :                : 
  596 drowley@postgresql.o      838                 :            147 :     appendStringInfoString(err_msg, err_detail.data);
  830 akapila@postgresql.o      839                 :            147 : }
                                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
  311                           849                 :            147 : 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                 :                : {
  830                           856                 :            147 :     Relation    localrel = relinfo->ri_RelationDesc;
                                857                 :            147 :     Oid         relid = RelationGetRelid(localrel);
                                858                 :            147 :     TupleDesc   tupdesc = RelationGetDescr(localrel);
                                859                 :            147 :     char       *desc = NULL;
                                860                 :                : 
  311                           861   [ +  +  -  +  :            147 :     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                 :                :      */
  614                           868   [ +  +  +  +  :            147 :     if (type == CT_INSERT_EXISTS || type == CT_UPDATE_EXISTS ||
                                              +  + ]
                                869                 :                :         type == CT_MULTIPLE_UNIQUE_CONFLICTS)
                                870                 :                :     {
  830                           871   [ +  -  -  + ]:            116 :         Assert(OidIsValid(indexoid) && localslot);
                                872                 :                : 
  311                           873                 :            116 :         desc = build_index_value_desc(estate, localrel, localslot,
                                874                 :                :                                       indexoid);
                                875                 :                : 
  830                           876         [ +  - ]:            116 :         if (desc)
  311                           877                 :            116 :             *key_desc = psprintf(_("key %s"), desc);
                                878                 :                :     }
                                879                 :                : 
  830                           880         [ +  + ]:            147 :     if (localslot)
                                881                 :                :     {
                                882                 :                :         /*
                                883                 :                :          * The 'modifiedCols' only applies to the new tuple, hence we pass
                                884                 :                :          * NULL for the local row.
                                885                 :                :          */
                                886                 :            124 :         desc = ExecBuildSlotValueDescription(relid, localslot, tupdesc,
                                887                 :                :                                              NULL, 64);
                                888                 :                : 
                                889         [ +  - ]:            124 :         if (desc)
  311                           890                 :            124 :             *local_desc = psprintf(_("local row %s"), desc);
                                891                 :                :     }
                                892                 :                : 
  830                           893         [ +  + ]:            147 :     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                 :            130 :         modifiedCols = bms_union(ExecGetInsertedCols(relinfo, estate),
                                905                 :            130 :                                  ExecGetUpdatedCols(relinfo, estate));
  311                           906                 :            130 :         desc = ExecBuildSlotValueDescription(relid, remoteslot,
                                907                 :                :                                              tupdesc, modifiedCols,
                                908                 :                :                                              64);
                                909                 :                : 
  830                           910         [ +  - ]:            130 :         if (desc)
  311                           911                 :            130 :             *remote_desc = psprintf(_("remote row %s"), desc);
                                912                 :                :     }
                                913                 :                : 
  830                           914         [ +  + ]:            147 :     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         [ -  + ]:             35 :         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                 :                :         {
  311                           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                 :                :     }
  830                           949                 :            147 : }
                                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
    4 akapila@postgresql.o      956                 :GNC         156 : build_index_datums_from_slot(EState *estate, Relation localrel,
                                957                 :                :                              TupleTableSlot *slot,
                                958                 :                :                              Relation indexDesc, Datum *values,
                                959                 :                :                              bool *isnull)
                                960                 :                : {
                                961                 :            156 :     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         [ +  + ]:            156 :     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         [ +  - ]:            156 :     GetPerTupleExprContext(estate)->ecxt_scantuple = tableslot;
                                977                 :                : 
                                978                 :                :     /* Form the index datums */
                                979                 :            156 :     FormIndexDatum(BuildIndexInfo(indexDesc), tableslot, estate, values,
                                980                 :                :                    isnull);
                                981                 :            156 : }
                                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 *
  830 akapila@postgresql.o      991                 :CBC         146 : 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                 :                : 
    4 akapila@postgresql.o      999         [ -  + ]:GNC         146 :     if (!slot)
  830 akapila@postgresql.o     1000                 :UBC           0 :         return NULL;
                               1001                 :                : 
  830 akapila@postgresql.o     1002         [ -  + ]:CBC         146 :     Assert(CheckRelationOidLockedByMe(indexoid, RowExclusiveLock, true));
                               1003                 :                : 
                               1004                 :            146 :     indexDesc = index_open(indexoid, NoLock);
                               1005                 :                : 
    4 akapila@postgresql.o     1006                 :GNC         146 :     build_index_datums_from_slot(estate, localrel, slot, indexDesc, values,
                               1007                 :                :                                  isnull);
                               1008                 :                : 
                               1009                 :            146 :     index_value = BuildIndexValueDescription(indexDesc, values, isnull);
                               1010                 :                : 
                               1011                 :            146 :     index_close(indexDesc, NoLock);
                               1012                 :                : 
                               1013                 :            146 :     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         [ -  + ]:             10 :     Assert(slot != NULL);
                               1040                 :                : 
                               1041         [ -  + ]:             10 :     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         [ -  + ]:             11 :         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])
    4 akapila@postgresql.o     1096                 :UNC           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                 :                :              */
    4 akapila@postgresql.o     1108                 :GNC          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         [ -  + ]:              6 :     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
    4 akapila@postgresql.o     1237                 :UNC           0 :             nulls[attno++] = true;
                               1238                 :                : 
    4 akapila@postgresql.o     1239         [ +  - ]:GNC           6 :         if (conflicttuple->ts)
                               1240                 :              6 :             values[attno++] = TimestampTzGetDatum(conflicttuple->ts);
                               1241                 :                :         else
    4 akapila@postgresql.o     1242                 :UNC           0 :             nulls[attno++] = true;
                               1243                 :                : 
    4 akapila@postgresql.o     1244         [ -  + ]:GNC           6 :         if (conflicttuple->origin != InvalidReplOriginId)
    4 akapila@postgresql.o     1245                 :UNC           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                 :                :          */
    4 akapila@postgresql.o     1251         [ -  + ]:GNC           6 :         if (origin_name != NULL)
    4 akapila@postgresql.o     1252                 :UNC           0 :             values[attno++] = CStringGetTextDatum(origin_name);
                               1253                 :                :         else
    4 akapila@postgresql.o     1254                 :GNC           6 :             nulls[attno++] = true;
                               1255                 :                : 
                               1256         [ -  + ]:              6 :         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         [ -  + ]:              6 :     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                 :             13 : 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                 :             13 :     Datum       values[NUM_CONFLICT_ATTRS] = {0};
                               1311                 :             13 :     bool        nulls[NUM_CONFLICT_ATTRS] = {0};
                               1312                 :                :     int         attno;
                               1313                 :             13 :     char       *apply_origin = NULL;
                               1314                 :                :     TransactionId remote_xid;
                               1315                 :                :     XLogRecPtr  remote_final_lsn;
                               1316                 :                :     TimestampTz remote_commit_ts;
                               1317                 :             13 :     bool        omitted = false;
                               1318                 :                :     Oid         replica_index;
                               1319                 :                :     HeapTuple   tuple;
                               1320                 :                : 
                               1321         [ -  + ]:             13 :     Assert(conflictlogrel != NULL);
                               1322                 :                : 
                               1323                 :                :     /* Fetch the information of the remote transaction being applied. */
                               1324                 :             13 :     GetRemoteTransactionInfoForConflict(&remote_xid, &remote_final_lsn,
                               1325                 :                :                                         &remote_commit_ts);
                               1326                 :                : 
                               1327                 :                :     /* Populate the values and nulls arrays. */
                               1328                 :             13 :     attno = 0;
                               1329                 :             13 :     values[attno++] = ObjectIdGetDatum(RelationGetRelid(rel));
                               1330                 :                : 
                               1331                 :             13 :     values[attno++] =
                               1332                 :             13 :         CStringGetTextDatum(get_namespace_name(RelationGetNamespace(rel)));
                               1333                 :                : 
                               1334                 :             13 :     values[attno++] = CStringGetTextDatum(RelationGetRelationName(rel));
                               1335                 :                : 
                               1336                 :             13 :     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         [ -  + ]:             13 :     Assert(TransactionIdIsValid(remote_xid));
                               1344                 :             13 :     values[attno++] = TransactionIdGetDatum(remote_xid);
                               1345                 :                : 
                               1346         [ +  - ]:             13 :     if (XLogRecPtrIsValid(remote_final_lsn))
                               1347                 :             13 :         values[attno++] = LSNGetDatum(remote_final_lsn);
                               1348                 :                :     else
    4 akapila@postgresql.o     1349                 :UNC           0 :         nulls[attno++] = true;
                               1350                 :                : 
    4 akapila@postgresql.o     1351         [ +  + ]:GNC          13 :     if (remote_commit_ts != 0)
                               1352                 :             12 :         values[attno++] = TimestampTzGetDatum(remote_commit_ts);
                               1353                 :                :     else
                               1354                 :              1 :         nulls[attno++] = true;
                               1355                 :                : 
                               1356         [ +  - ]:             13 :     if (replorigin_xact_state.origin != InvalidReplOriginId)
                               1357                 :             13 :         replorigin_by_oid(replorigin_xact_state.origin, true, &apply_origin);
                               1358                 :                : 
                               1359         [ +  - ]:             13 :     if (apply_origin != NULL)
                               1360                 :             13 :         values[attno++] = CStringGetTextDatum(apply_origin);
                               1361                 :                :     else
    4 akapila@postgresql.o     1362                 :UNC           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                 :                :      */
    4 akapila@postgresql.o     1369   [ +  -  -  + ]:GNC          13 :     Assert(!TupIsNull(searchslot));
                               1370                 :                : 
                               1371                 :             13 :     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         [ +  + ]:             13 :     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                 :              3 :         values[attno++] = BoolGetDatum(true);
                               1390                 :              3 :         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         [ +  + ]:             13 :     if (conflicttuples != NIL)
                               1398                 :              6 :         values[attno++] = build_local_conflicts_json_array(conflicttuples);
                               1399                 :                :     else
                               1400                 :              7 :         nulls[attno++] = true;
                               1401                 :                : 
                               1402                 :             13 :     values[attno] = BoolGetDatum(omitted);
                               1403                 :                : 
                               1404         [ -  + ]:             13 :     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                 :             13 :     tuple = heap_form_tuple(RelationGetDescr(conflictlogrel), values, nulls);
                               1417                 :                : 
                               1418                 :             13 :     heap_insert(conflictlogrel, tuple,
                               1419                 :                :                 GetCurrentCommandId(true), HEAP_INSERT_NO_LOGICAL, NULL);
                               1420                 :                : 
                               1421                 :             13 :     heap_freetuple(tuple);
  830 akapila@postgresql.o     1422                 :GIC          13 : }
        

Generated by: LCOV version 2.0-1