Post-PG 10 beta1 pgindent run

perltidy run not included.
pull/18/merge
Bruce Momjian 8 years ago
parent 8a94332478
commit a6fd7b7a5f
  1. 10
      contrib/bloom/blinsert.c
  2. 2
      contrib/bloom/blutils.c
  3. 32
      contrib/btree_gin/btree_gin.c
  4. 2
      contrib/btree_gist/btree_cash.c
  5. 2
      contrib/btree_gist/btree_date.c
  6. 10
      contrib/btree_gist/btree_enum.c
  7. 2
      contrib/btree_gist/btree_float4.c
  8. 2
      contrib/btree_gist/btree_float8.c
  9. 2
      contrib/btree_gist/btree_inet.c
  10. 2
      contrib/btree_gist/btree_int2.c
  11. 2
      contrib/btree_gist/btree_int4.c
  12. 2
      contrib/btree_gist/btree_int8.c
  13. 2
      contrib/btree_gist/btree_interval.c
  14. 2
      contrib/btree_gist/btree_oid.c
  15. 2
      contrib/btree_gist/btree_time.c
  16. 4
      contrib/btree_gist/btree_ts.c
  17. 14
      contrib/btree_gist/btree_utils_num.h
  18. 6
      contrib/btree_gist/btree_utils_var.c
  19. 12
      contrib/btree_gist/btree_utils_var.h
  20. 2
      contrib/btree_gist/btree_uuid.c
  21. 31
      contrib/dblink/dblink.c
  22. 2
      contrib/oid2name/oid2name.c
  23. 4
      contrib/pageinspect/brinfuncs.c
  24. 20
      contrib/pageinspect/hashfuncs.c
  25. 4
      contrib/pageinspect/rawpage.c
  26. 2
      contrib/pg_standby/pg_standby.c
  27. 4
      contrib/pg_visibility/pg_visibility.c
  28. 8
      contrib/pgcrypto/openssl.c
  29. 4
      contrib/pgcrypto/pgcrypto.c
  30. 5
      contrib/pgrowlocks/pgrowlocks.c
  31. 2
      contrib/pgstattuple/pgstatapprox.c
  32. 38
      contrib/pgstattuple/pgstatindex.c
  33. 16
      contrib/postgres_fdw/deparse.c
  34. 22
      contrib/postgres_fdw/postgres_fdw.c
  35. 4
      contrib/postgres_fdw/postgres_fdw.h
  36. 17
      src/backend/access/brin/brin.c
  37. 8
      src/backend/access/brin/brin_revmap.c
  38. 4
      src/backend/access/brin/brin_xlog.c
  39. 8
      src/backend/access/common/printsimple.c
  40. 42
      src/backend/access/gin/ginvacuum.c
  41. 28
      src/backend/access/hash/hash.c
  42. 40
      src/backend/access/hash/hash_xlog.c
  43. 51
      src/backend/access/hash/hashinsert.c
  44. 50
      src/backend/access/hash/hashpage.c
  45. 27
      src/backend/access/hash/hashutil.c
  46. 31
      src/backend/access/heap/heapam.c
  47. 12
      src/backend/access/nbtree/nbtree.c
  48. 2
      src/backend/access/rmgrdesc/brindesc.c
  49. 2
      src/backend/access/rmgrdesc/clogdesc.c
  50. 12
      src/backend/access/rmgrdesc/gindesc.c
  51. 8
      src/backend/access/spgist/spginsert.c
  52. 12
      src/backend/access/transam/clog.c
  53. 8
      src/backend/access/transam/commit_ts.c
  54. 14
      src/backend/access/transam/subtrans.c
  55. 109
      src/backend/access/transam/twophase.c
  56. 2
      src/backend/access/transam/varsup.c
  57. 9
      src/backend/access/transam/xact.c
  58. 112
      src/backend/access/transam/xlog.c
  59. 5
      src/backend/access/transam/xlogfuncs.c
  60. 23
      src/backend/access/transam/xloginsert.c
  61. 4
      src/backend/access/transam/xlogreader.c
  62. 57
      src/backend/access/transam/xlogutils.c
  63. 8
      src/backend/catalog/dependency.c
  64. 8
      src/backend/catalog/heap.c
  65. 34
      src/backend/catalog/objectaddress.c
  66. 28
      src/backend/catalog/pg_collation.c
  67. 6
      src/backend/catalog/pg_depend.c
  68. 12
      src/backend/catalog/pg_inherits.c
  69. 2
      src/backend/catalog/pg_namespace.c
  70. 66
      src/backend/catalog/pg_publication.c
  71. 57
      src/backend/catalog/pg_subscription.c
  72. 2
      src/backend/commands/alter.c
  73. 2
      src/backend/commands/analyze.c
  74. 38
      src/backend/commands/collationcmds.c
  75. 4
      src/backend/commands/copy.c
  76. 7
      src/backend/commands/dbcommands.c
  77. 2
      src/backend/commands/define.c
  78. 13
      src/backend/commands/dropcmds.c
  79. 4
      src/backend/commands/event_trigger.c
  80. 32
      src/backend/commands/foreigncmds.c
  81. 63
      src/backend/commands/publicationcmds.c
  82. 46
      src/backend/commands/sequence.c
  83. 4
      src/backend/commands/statscmds.c
  84. 133
      src/backend/commands/subscriptioncmds.c
  85. 50
      src/backend/commands/tablecmds.c
  86. 35
      src/backend/commands/trigger.c
  87. 8
      src/backend/commands/tsearchcmds.c
  88. 6
      src/backend/commands/user.c
  89. 6
      src/backend/commands/vacuumlazy.c
  90. 4
      src/backend/commands/view.c
  91. 13
      src/backend/executor/execAmi.c
  92. 2
      src/backend/executor/execGrouping.c
  93. 24
      src/backend/executor/execMain.c
  94. 6
      src/backend/executor/execParallel.c
  95. 2
      src/backend/executor/execProcnode.c
  96. 78
      src/backend/executor/execReplication.c
  97. 8
      src/backend/executor/execUtils.c
  98. 4
      src/backend/executor/nodeAgg.c
  99. 4
      src/backend/executor/nodeAppend.c
  100. 5
      src/backend/executor/nodeBitmapHeapscan.c
  101. Some files were not shown because too many files have changed in this diff Show More

@ -165,11 +165,11 @@ blbuildempty(Relation index)
BloomFillMetapage(index, metapage); BloomFillMetapage(index, metapage);
/* /*
* Write the page and log it. It might seem that an immediate sync * Write the page and log it. It might seem that an immediate sync would
* would be sufficient to guarantee that the file exists on disk, but * be sufficient to guarantee that the file exists on disk, but recovery
* recovery itself might remove it while replaying, for example, an * itself might remove it while replaying, for example, an
* XLOG_DBASE_CREATE or XLOG_TBLSPC_CREATE record. Therefore, we * XLOG_DBASE_CREATE or XLOG_TBLSPC_CREATE record. Therefore, we need
* need this even when wal_level=minimal. * this even when wal_level=minimal.
*/ */
PageSetChecksumInplace(metapage, BLOOM_METAPAGE_BLKNO); PageSetChecksumInplace(metapage, BLOOM_METAPAGE_BLKNO);
smgrwrite(index->rd_smgr, INIT_FORKNUM, BLOOM_METAPAGE_BLKNO, smgrwrite(index->rd_smgr, INIT_FORKNUM, BLOOM_METAPAGE_BLKNO,

@ -75,7 +75,7 @@ _PG_init(void)
bl_relopt_tab[i + 1].optname = MemoryContextStrdup(TopMemoryContext, bl_relopt_tab[i + 1].optname = MemoryContextStrdup(TopMemoryContext,
buf); buf);
bl_relopt_tab[i + 1].opttype = RELOPT_TYPE_INT; bl_relopt_tab[i + 1].opttype = RELOPT_TYPE_INT;
bl_relopt_tab[i + 1].offset = offsetof(BloomOptions, bitSize[0]) + sizeof(int) * i; bl_relopt_tab[i + 1].offset = offsetof(BloomOptions, bitSize[0]) +sizeof(int) * i;
} }
} }

@ -112,13 +112,13 @@ gin_btree_compare_prefix(FunctionCallInfo fcinfo)
cmp; cmp;
cmp = DatumGetInt32(CallerFInfoFunctionCall2( cmp = DatumGetInt32(CallerFInfoFunctionCall2(
data->typecmp, data->typecmp,
fcinfo->flinfo, fcinfo->flinfo,
PG_GET_COLLATION(), PG_GET_COLLATION(),
(data->strategy == BTLessStrategyNumber || (data->strategy == BTLessStrategyNumber ||
data->strategy == BTLessEqualStrategyNumber) data->strategy == BTLessEqualStrategyNumber)
? data->datum : a, ? data->datum : a,
b)); b));
switch (data->strategy) switch (data->strategy)
{ {
@ -438,16 +438,16 @@ GIN_SUPPORT(numeric, true, leftmostvalue_numeric, gin_numeric_cmp)
*/ */
#define ENUM_IS_LEFTMOST(x) ((x) == InvalidOid) #define ENUM_IS_LEFTMOST(x) ((x) == InvalidOid)
PG_FUNCTION_INFO_V1(gin_enum_cmp); PG_FUNCTION_INFO_V1(gin_enum_cmp);
Datum Datum
gin_enum_cmp(PG_FUNCTION_ARGS) gin_enum_cmp(PG_FUNCTION_ARGS)
{ {
Oid a = PG_GETARG_OID(0); Oid a = PG_GETARG_OID(0);
Oid b = PG_GETARG_OID(1); Oid b = PG_GETARG_OID(1);
int res = 0; int res = 0;
if (ENUM_IS_LEFTMOST(a)) if (ENUM_IS_LEFTMOST(a))
{ {
@ -460,11 +460,11 @@ gin_enum_cmp(PG_FUNCTION_ARGS)
else else
{ {
res = DatumGetInt32(CallerFInfoFunctionCall2( res = DatumGetInt32(CallerFInfoFunctionCall2(
enum_cmp, enum_cmp,
fcinfo->flinfo, fcinfo->flinfo,
PG_GET_COLLATION(), PG_GET_COLLATION(),
ObjectIdGetDatum(a), ObjectIdGetDatum(a),
ObjectIdGetDatum(b))); ObjectIdGetDatum(b)));
} }
PG_RETURN_INT32(res); PG_RETURN_INT32(res);

@ -170,7 +170,7 @@ gbt_cash_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -182,7 +182,7 @@ gbt_date_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -32,14 +32,14 @@ static bool
gbt_enumgt(const void *a, const void *b, FmgrInfo *flinfo) gbt_enumgt(const void *a, const void *b, FmgrInfo *flinfo)
{ {
return DatumGetBool( return DatumGetBool(
CallerFInfoFunctionCall2(enum_gt, flinfo, InvalidOid, ObjectIdGetDatum(*((const Oid *) a)), ObjectIdGetDatum(*((const Oid *) b))) CallerFInfoFunctionCall2(enum_gt, flinfo, InvalidOid, ObjectIdGetDatum(*((const Oid *) a)), ObjectIdGetDatum(*((const Oid *) b)))
); );
} }
static bool static bool
gbt_enumge(const void *a, const void *b, FmgrInfo *flinfo) gbt_enumge(const void *a, const void *b, FmgrInfo *flinfo)
{ {
return DatumGetBool( return DatumGetBool(
CallerFInfoFunctionCall2(enum_ge, flinfo, InvalidOid, ObjectIdGetDatum(*((const Oid *) a)), ObjectIdGetDatum(*((const Oid *) b))) CallerFInfoFunctionCall2(enum_ge, flinfo, InvalidOid, ObjectIdGetDatum(*((const Oid *) a)), ObjectIdGetDatum(*((const Oid *) b)))
); );
} }
static bool static bool
@ -74,12 +74,12 @@ gbt_enumkey_cmp(const void *a, const void *b, FmgrInfo *flinfo)
return 0; return 0;
return DatumGetInt32( return DatumGetInt32(
CallerFInfoFunctionCall2(enum_cmp, flinfo, InvalidOid, ObjectIdGetDatum(ia->upper), ObjectIdGetDatum(ib->upper)) CallerFInfoFunctionCall2(enum_cmp, flinfo, InvalidOid, ObjectIdGetDatum(ia->upper), ObjectIdGetDatum(ib->upper))
); );
} }
return DatumGetInt32( return DatumGetInt32(
CallerFInfoFunctionCall2(enum_cmp, flinfo, InvalidOid, ObjectIdGetDatum(ia->lower), ObjectIdGetDatum(ib->lower)) CallerFInfoFunctionCall2(enum_cmp, flinfo, InvalidOid, ObjectIdGetDatum(ia->lower), ObjectIdGetDatum(ib->lower))
); );
} }
@ -94,7 +94,7 @@ static const gbtree_ninfo tinfo =
gbt_enumle, gbt_enumle,
gbt_enumlt, gbt_enumlt,
gbt_enumkey_cmp, gbt_enumkey_cmp,
NULL /* no KNN support at least for now */ NULL /* no KNN support at least for now */
}; };

@ -163,7 +163,7 @@ gbt_float4_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -170,7 +170,7 @@ gbt_float8_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -133,7 +133,7 @@ gbt_inet_consistent(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_BOOL(gbt_num_consistent(&key, (void *) &query, PG_RETURN_BOOL(gbt_num_consistent(&key, (void *) &query,
&strategy, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)); &strategy, GIST_LEAF(entry), &tinfo, fcinfo->flinfo));
} }

@ -170,7 +170,7 @@ gbt_int2_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -171,7 +171,7 @@ gbt_int4_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -171,7 +171,7 @@ gbt_int8_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -245,7 +245,7 @@ gbt_intv_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -171,7 +171,7 @@ gbt_oid_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -235,7 +235,7 @@ gbt_time_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -283,7 +283,7 @@ gbt_ts_distance(PG_FUNCTION_ARGS)
key.upper = (GBT_NUMKEY *) &kkk->upper; key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }
@ -328,7 +328,7 @@ gbt_tstz_distance(PG_FUNCTION_ARGS)
qqq = tstz_to_ts_gmt(query); qqq = tstz_to_ts_gmt(query);
PG_RETURN_FLOAT8( PG_RETURN_FLOAT8(
gbt_num_distance(&key, (void *) &qqq, GIST_LEAF(entry), &tinfo, fcinfo->flinfo) gbt_num_distance(&key, (void *) &qqq, GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -42,13 +42,13 @@ typedef struct
/* Methods */ /* Methods */
bool (*f_gt) (const void *, const void *, FmgrInfo *); /* greater than */ bool (*f_gt) (const void *, const void *, FmgrInfo *); /* greater than */
bool (*f_ge) (const void *, const void *, FmgrInfo *); /* greater or equal */ bool (*f_ge) (const void *, const void *, FmgrInfo *); /* greater or equal */
bool (*f_eq) (const void *, const void *, FmgrInfo *); /* equal */ bool (*f_eq) (const void *, const void *, FmgrInfo *); /* equal */
bool (*f_le) (const void *, const void *, FmgrInfo *); /* less or equal */ bool (*f_le) (const void *, const void *, FmgrInfo *); /* less or equal */
bool (*f_lt) (const void *, const void *, FmgrInfo *); /* less than */ bool (*f_lt) (const void *, const void *, FmgrInfo *); /* less than */
int (*f_cmp) (const void *, const void *, FmgrInfo *); /* key compare function */ int (*f_cmp) (const void *, const void *, FmgrInfo *); /* key compare function */
float8 (*f_dist) (const void *, const void *, FmgrInfo *); /* key distance function */ float8 (*f_dist) (const void *, const void *, FmgrInfo *); /* key distance function */
} gbtree_ninfo; } gbtree_ninfo;

@ -25,7 +25,7 @@ typedef struct
{ {
const gbtree_vinfo *tinfo; const gbtree_vinfo *tinfo;
Oid collation; Oid collation;
FmgrInfo *flinfo; FmgrInfo *flinfo;
} gbt_vsrt_arg; } gbt_vsrt_arg;
@ -402,8 +402,8 @@ gbt_var_penalty(float *res, const GISTENTRY *o, const GISTENTRY *n,
*res = 0.0; *res = 0.0;
else if (!(((*tinfo->f_cmp) (nk.lower, ok.lower, collation, flinfo) >= 0 || else if (!(((*tinfo->f_cmp) (nk.lower, ok.lower, collation, flinfo) >= 0 ||
gbt_bytea_pf_match(ok.lower, nk.lower, tinfo)) && gbt_bytea_pf_match(ok.lower, nk.lower, tinfo)) &&
((*tinfo->f_cmp) (nk.upper, ok.upper, collation, flinfo) <= 0 || ((*tinfo->f_cmp) (nk.upper, ok.upper, collation, flinfo) <= 0 ||
gbt_bytea_pf_match(ok.upper, nk.upper, tinfo)))) gbt_bytea_pf_match(ok.upper, nk.upper, tinfo))))
{ {
Datum d = PointerGetDatum(0); Datum d = PointerGetDatum(0);
double dres; double dres;

@ -34,12 +34,12 @@ typedef struct
/* Methods */ /* Methods */
bool (*f_gt) (const void *, const void *, Oid, FmgrInfo *); /* greater than */ bool (*f_gt) (const void *, const void *, Oid, FmgrInfo *); /* greater than */
bool (*f_ge) (const void *, const void *, Oid, FmgrInfo *); /* greater equal */ bool (*f_ge) (const void *, const void *, Oid, FmgrInfo *); /* greater equal */
bool (*f_eq) (const void *, const void *, Oid, FmgrInfo *); /* equal */ bool (*f_eq) (const void *, const void *, Oid, FmgrInfo *); /* equal */
bool (*f_le) (const void *, const void *, Oid, FmgrInfo *); /* less equal */ bool (*f_le) (const void *, const void *, Oid, FmgrInfo *); /* less equal */
bool (*f_lt) (const void *, const void *, Oid, FmgrInfo *); /* less than */ bool (*f_lt) (const void *, const void *, Oid, FmgrInfo *); /* less than */
int32 (*f_cmp) (const void *, const void *, Oid, FmgrInfo *); /* compare */ int32 (*f_cmp) (const void *, const void *, Oid, FmgrInfo *); /* compare */
GBT_VARKEY *(*f_l2n) (GBT_VARKEY *, FmgrInfo *flinfo); /* convert leaf to node */ GBT_VARKEY *(*f_l2n) (GBT_VARKEY *, FmgrInfo *flinfo); /* convert leaf to node */
} gbtree_vinfo; } gbtree_vinfo;

@ -150,7 +150,7 @@ gbt_uuid_consistent(PG_FUNCTION_ARGS)
PG_RETURN_BOOL( PG_RETURN_BOOL(
gbt_num_consistent(&key, (void *) query, &strategy, gbt_num_consistent(&key, (void *) query, &strategy,
GIST_LEAF(entry), &tinfo, fcinfo->flinfo) GIST_LEAF(entry), &tinfo, fcinfo->flinfo)
); );
} }

@ -113,7 +113,7 @@ static char *generate_relation_name(Relation rel);
static void dblink_connstr_check(const char *connstr); static void dblink_connstr_check(const char *connstr);
static void dblink_security_check(PGconn *conn, remoteConn *rconn); static void dblink_security_check(PGconn *conn, remoteConn *rconn);
static void dblink_res_error(PGconn *conn, const char *conname, PGresult *res, static void dblink_res_error(PGconn *conn, const char *conname, PGresult *res,
const char *dblink_context_msg, bool fail); const char *dblink_context_msg, bool fail);
static char *get_connect_string(const char *servername); static char *get_connect_string(const char *servername);
static char *escape_param_str(const char *from); static char *escape_param_str(const char *from);
static void validate_pkattnums(Relation rel, static void validate_pkattnums(Relation rel,
@ -152,16 +152,19 @@ xpstrdup(const char *in)
return pstrdup(in); return pstrdup(in);
} }
static void pg_attribute_noreturn() static void
pg_attribute_noreturn()
dblink_res_internalerror(PGconn *conn, PGresult *res, const char *p2) dblink_res_internalerror(PGconn *conn, PGresult *res, const char *p2)
{ {
char *msg = pchomp(PQerrorMessage(conn)); char *msg = pchomp(PQerrorMessage(conn));
if (res) if (res)
PQclear(res); PQclear(res);
elog(ERROR, "%s: %s", p2, msg); elog(ERROR, "%s: %s", p2, msg);
} }
static void pg_attribute_noreturn() static void
pg_attribute_noreturn()
dblink_conn_not_avail(const char *conname) dblink_conn_not_avail(const char *conname)
{ {
if (conname) if (conname)
@ -176,7 +179,7 @@ dblink_conn_not_avail(const char *conname)
static void static void
dblink_get_conn(char *conname_or_str, dblink_get_conn(char *conname_or_str,
PGconn * volatile *conn_p, char **conname_p, volatile bool *freeconn_p) PGconn *volatile * conn_p, char **conname_p, volatile bool *freeconn_p)
{ {
remoteConn *rconn = getConnectionByName(conname_or_str); remoteConn *rconn = getConnectionByName(conname_or_str);
PGconn *conn; PGconn *conn;
@ -201,11 +204,12 @@ dblink_get_conn(char *conname_or_str,
if (PQstatus(conn) == CONNECTION_BAD) if (PQstatus(conn) == CONNECTION_BAD)
{ {
char *msg = pchomp(PQerrorMessage(conn)); char *msg = pchomp(PQerrorMessage(conn));
PQfinish(conn); PQfinish(conn);
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION), (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
errmsg("could not establish connection"), errmsg("could not establish connection"),
errdetail_internal("%s", msg))); errdetail_internal("%s", msg)));
} }
dblink_security_check(conn, rconn); dblink_security_check(conn, rconn);
if (PQclientEncoding(conn) != GetDatabaseEncoding()) if (PQclientEncoding(conn) != GetDatabaseEncoding())
@ -223,11 +227,12 @@ static PGconn *
dblink_get_named_conn(const char *conname) dblink_get_named_conn(const char *conname)
{ {
remoteConn *rconn = getConnectionByName(conname); remoteConn *rconn = getConnectionByName(conname);
if (rconn) if (rconn)
return rconn->conn; return rconn->conn;
dblink_conn_not_avail(conname); dblink_conn_not_avail(conname);
return NULL; /* keep compiler quiet */ return NULL; /* keep compiler quiet */
} }
static void static void
@ -2699,9 +2704,9 @@ dblink_res_error(PGconn *conn, const char *conname, PGresult *res,
message_context = xpstrdup(pg_diag_context); message_context = xpstrdup(pg_diag_context);
/* /*
* If we don't get a message from the PGresult, try the PGconn. This * If we don't get a message from the PGresult, try the PGconn. This is
* is needed because for connection-level failures, PQexec may just * needed because for connection-level failures, PQexec may just return
* return NULL, not a PGresult at all. * NULL, not a PGresult at all.
*/ */
if (message_primary == NULL) if (message_primary == NULL)
message_primary = pchomp(PQerrorMessage(conn)); message_primary = pchomp(PQerrorMessage(conn));
@ -2732,7 +2737,7 @@ get_connect_string(const char *servername)
ForeignServer *foreign_server = NULL; ForeignServer *foreign_server = NULL;
UserMapping *user_mapping; UserMapping *user_mapping;
ListCell *cell; ListCell *cell;
StringInfoData buf; StringInfoData buf;
ForeignDataWrapper *fdw; ForeignDataWrapper *fdw;
AclResult aclresult; AclResult aclresult;
char *srvname; char *srvname;
@ -2820,7 +2825,7 @@ static char *
escape_param_str(const char *str) escape_param_str(const char *str)
{ {
const char *cp; const char *cp;
StringInfoData buf; StringInfoData buf;
initStringInfo(&buf); initStringInfo(&buf);

@ -507,7 +507,7 @@ sql_exec_searchtables(PGconn *conn, struct options * opts)
todo = psprintf( todo = psprintf(
"SELECT pg_catalog.pg_relation_filenode(c.oid) as \"Filenode\", relname as \"Table Name\" %s\n" "SELECT pg_catalog.pg_relation_filenode(c.oid) as \"Filenode\", relname as \"Table Name\" %s\n"
"FROM pg_catalog.pg_class c\n" "FROM pg_catalog.pg_class c\n"
" LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n" " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"
" LEFT JOIN pg_catalog.pg_database d ON d.datname = pg_catalog.current_database(),\n" " LEFT JOIN pg_catalog.pg_database d ON d.datname = pg_catalog.current_database(),\n"
" pg_catalog.pg_tablespace t\n" " pg_catalog.pg_tablespace t\n"
"WHERE relkind IN (" CppAsString2(RELKIND_RELATION) "," "WHERE relkind IN (" CppAsString2(RELKIND_RELATION) ","

@ -226,8 +226,8 @@ brin_page_items(PG_FUNCTION_ARGS)
if (ItemIdIsUsed(itemId)) if (ItemIdIsUsed(itemId))
{ {
dtup = brin_deform_tuple(bdesc, dtup = brin_deform_tuple(bdesc,
(BrinTuple *) PageGetItem(page, itemId), (BrinTuple *) PageGetItem(page, itemId),
NULL); NULL);
attno = 1; attno = 1;
unusedItem = false; unusedItem = false;
} }

@ -34,10 +34,10 @@ PG_FUNCTION_INFO_V1(hash_metapage_info);
*/ */
typedef struct HashPageStat typedef struct HashPageStat
{ {
int live_items; int live_items;
int dead_items; int dead_items;
int page_size; int page_size;
int free_size; int free_size;
/* opaque data */ /* opaque data */
BlockNumber hasho_prevblkno; BlockNumber hasho_prevblkno;
@ -45,7 +45,7 @@ typedef struct HashPageStat
Bucket hasho_bucket; Bucket hasho_bucket;
uint16 hasho_flag; uint16 hasho_flag;
uint16 hasho_page_id; uint16 hasho_page_id;
} HashPageStat; } HashPageStat;
/* /*
@ -99,7 +99,7 @@ verify_hash_page(bytea *raw_page, int flags)
case LH_BUCKET_PAGE | LH_OVERFLOW_PAGE: case LH_BUCKET_PAGE | LH_OVERFLOW_PAGE:
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("page is not a hash bucket or overflow page"))); errmsg("page is not a hash bucket or overflow page")));
case LH_OVERFLOW_PAGE: case LH_OVERFLOW_PAGE:
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@ -107,7 +107,7 @@ verify_hash_page(bytea *raw_page, int flags)
default: default:
elog(ERROR, elog(ERROR,
"hash page of type %08x not in mask %08x", "hash page of type %08x not in mask %08x",
pagetype, flags); pagetype, flags);
} }
} }
@ -143,7 +143,7 @@ verify_hash_page(bytea *raw_page, int flags)
* ------------------------------------------------- * -------------------------------------------------
*/ */
static void static void
GetHashPageStatistics(Page page, HashPageStat * stat) GetHashPageStatistics(Page page, HashPageStat *stat)
{ {
OffsetNumber maxoff = PageGetMaxOffsetNumber(page); OffsetNumber maxoff = PageGetMaxOffsetNumber(page);
HashPageOpaque opaque = (HashPageOpaque) PageGetSpecialPointer(page); HashPageOpaque opaque = (HashPageOpaque) PageGetSpecialPointer(page);
@ -515,8 +515,8 @@ hash_metapage_info(PG_FUNCTION_ARGS)
j; j;
Datum values[16]; Datum values[16];
bool nulls[16]; bool nulls[16];
Datum spares[HASH_MAX_SPLITPOINTS]; Datum spares[HASH_MAX_SPLITPOINTS];
Datum mapp[HASH_MAX_BITMAPS]; Datum mapp[HASH_MAX_BITMAPS];
if (!superuser()) if (!superuser())
ereport(ERROR, ereport(ERROR,

@ -311,9 +311,9 @@ page_checksum(PG_FUNCTION_ARGS)
if (raw_page_size != BLCKSZ) if (raw_page_size != BLCKSZ)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("incorrect size of input page (%d bytes)", raw_page_size))); errmsg("incorrect size of input page (%d bytes)", raw_page_size)));
page = (PageHeader) VARDATA(raw_page); page = (PageHeader) VARDATA(raw_page);
PG_RETURN_INT16(pg_checksum_page((char *)page, blkno)); PG_RETURN_INT16(pg_checksum_page((char *) page, blkno));
} }

@ -57,7 +57,7 @@ char *xlogFilePath; /* where we are going to restore to */
char *nextWALFileName; /* the file we need to get from archive */ char *nextWALFileName; /* the file we need to get from archive */
char *restartWALFileName; /* the file from which we can restart restore */ char *restartWALFileName; /* the file from which we can restart restore */
char *priorWALFileName; /* the file we need to get from archive */ char *priorWALFileName; /* the file we need to get from archive */
char WALFilePath[MAXPGPATH * 2]; /* the file path including archive */ char WALFilePath[MAXPGPATH * 2]; /* the file path including archive */
char restoreCommand[MAXPGPATH]; /* run this to restore */ char restoreCommand[MAXPGPATH]; /* run this to restore */
char exclusiveCleanupFileName[MAXFNAMELEN]; /* the file we need to char exclusiveCleanupFileName[MAXFNAMELEN]; /* the file we need to
* get from archive */ * get from archive */

@ -774,6 +774,6 @@ check_relation_relkind(Relation rel)
rel->rd_rel->relkind != RELKIND_TOASTVALUE) rel->rd_rel->relkind != RELKIND_TOASTVALUE)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE), (errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table, materialized view, or TOAST table", errmsg("\"%s\" is not a table, materialized view, or TOAST table",
RelationGetRelationName(rel)))); RelationGetRelationName(rel))));
} }

@ -238,7 +238,7 @@ px_find_digest(const char *name, PX_MD **res)
* prototype for the EVP functions that return an algorithm, e.g. * prototype for the EVP functions that return an algorithm, e.g.
* EVP_aes_128_cbc(). * EVP_aes_128_cbc().
*/ */
typedef const EVP_CIPHER *(*ossl_EVP_cipher_func)(void); typedef const EVP_CIPHER *(*ossl_EVP_cipher_func) (void);
/* /*
* ossl_cipher contains the static information about each cipher. * ossl_cipher contains the static information about each cipher.
@ -706,13 +706,15 @@ static const struct ossl_cipher ossl_cast_cbc = {
static const struct ossl_cipher ossl_aes_ecb = { static const struct ossl_cipher ossl_aes_ecb = {
ossl_aes_ecb_init, ossl_aes_ecb_init,
NULL, /* EVP_aes_XXX_ecb(), determined in init function */ NULL, /* EVP_aes_XXX_ecb(), determined in init
* function */
128 / 8, 256 / 8 128 / 8, 256 / 8
}; };
static const struct ossl_cipher ossl_aes_cbc = { static const struct ossl_cipher ossl_aes_cbc = {
ossl_aes_cbc_init, ossl_aes_cbc_init,
NULL, /* EVP_aes_XXX_cbc(), determined in init function */ NULL, /* EVP_aes_XXX_cbc(), determined in init
* function */
128 / 8, 256 / 8 128 / 8, 256 / 8
}; };

@ -454,8 +454,8 @@ pg_random_uuid(PG_FUNCTION_ARGS)
uint8 *buf = (uint8 *) palloc(UUID_LEN); uint8 *buf = (uint8 *) palloc(UUID_LEN);
/* /*
* Generate random bits. pg_backend_random() will do here, we don't * Generate random bits. pg_backend_random() will do here, we don't promis
* promis UUIDs to be cryptographically random, when built with * UUIDs to be cryptographically random, when built with
* --disable-strong-random. * --disable-strong-random.
*/ */
if (!pg_backend_random((char *) buf, UUID_LEN)) if (!pg_backend_random((char *) buf, UUID_LEN))

@ -99,7 +99,10 @@ pgrowlocks(PG_FUNCTION_ARGS)
relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname)); relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
rel = heap_openrv(relrv, AccessShareLock); rel = heap_openrv(relrv, AccessShareLock);
/* check permissions: must have SELECT on table or be in pg_stat_scan_tables */ /*
* check permissions: must have SELECT on table or be in
* pg_stat_scan_tables
*/
aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(), aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
ACL_SELECT); ACL_SELECT);
if (aclresult != ACLCHECK_OK) if (aclresult != ACLCHECK_OK)

@ -31,7 +31,7 @@
PG_FUNCTION_INFO_V1(pgstattuple_approx); PG_FUNCTION_INFO_V1(pgstattuple_approx);
PG_FUNCTION_INFO_V1(pgstattuple_approx_v1_5); PG_FUNCTION_INFO_V1(pgstattuple_approx_v1_5);
Datum pgstattuple_approx_internal(Oid relid, FunctionCallInfo fcinfo); Datum pgstattuple_approx_internal(Oid relid, FunctionCallInfo fcinfo);
typedef struct output_type typedef struct output_type
{ {

@ -64,7 +64,7 @@ PG_FUNCTION_INFO_V1(pg_relpages_v1_5);
PG_FUNCTION_INFO_V1(pg_relpagesbyid_v1_5); PG_FUNCTION_INFO_V1(pg_relpagesbyid_v1_5);
PG_FUNCTION_INFO_V1(pgstatginindex_v1_5); PG_FUNCTION_INFO_V1(pgstatginindex_v1_5);
Datum pgstatginindex_internal(Oid relid, FunctionCallInfo fcinfo); Datum pgstatginindex_internal(Oid relid, FunctionCallInfo fcinfo);
#define IS_INDEX(r) ((r)->rd_rel->relkind == RELKIND_INDEX) #define IS_INDEX(r) ((r)->rd_rel->relkind == RELKIND_INDEX)
#define IS_BTREE(r) ((r)->rd_rel->relam == BTREE_AM_OID) #define IS_BTREE(r) ((r)->rd_rel->relam == BTREE_AM_OID)
@ -113,17 +113,17 @@ typedef struct GinIndexStat
*/ */
typedef struct HashIndexStat typedef struct HashIndexStat
{ {
int32 version; int32 version;
int32 space_per_page; int32 space_per_page;
BlockNumber bucket_pages; BlockNumber bucket_pages;
BlockNumber overflow_pages; BlockNumber overflow_pages;
BlockNumber bitmap_pages; BlockNumber bitmap_pages;
BlockNumber unused_pages; BlockNumber unused_pages;
int64 live_items; int64 live_items;
int64 dead_items; int64 dead_items;
uint64 free_space; uint64 free_space;
} HashIndexStat; } HashIndexStat;
static Datum pgstatindex_impl(Relation rel, FunctionCallInfo fcinfo); static Datum pgstatindex_impl(Relation rel, FunctionCallInfo fcinfo);
@ -581,8 +581,8 @@ Datum
pgstathashindex(PG_FUNCTION_ARGS) pgstathashindex(PG_FUNCTION_ARGS)
{ {
Oid relid = PG_GETARG_OID(0); Oid relid = PG_GETARG_OID(0);
BlockNumber nblocks; BlockNumber nblocks;
BlockNumber blkno; BlockNumber blkno;
Relation rel; Relation rel;
HashIndexStat stats; HashIndexStat stats;
BufferAccessStrategy bstrategy; BufferAccessStrategy bstrategy;
@ -591,7 +591,7 @@ pgstathashindex(PG_FUNCTION_ARGS)
Datum values[8]; Datum values[8];
bool nulls[8]; bool nulls[8];
Buffer metabuf; Buffer metabuf;
HashMetaPage metap; HashMetaPage metap;
float8 free_percent; float8 free_percent;
uint64 total_space; uint64 total_space;
@ -648,13 +648,13 @@ pgstathashindex(PG_FUNCTION_ARGS)
MAXALIGN(sizeof(HashPageOpaqueData))) MAXALIGN(sizeof(HashPageOpaqueData)))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INDEX_CORRUPTED), (errcode(ERRCODE_INDEX_CORRUPTED),
errmsg("index \"%s\" contains corrupted page at block %u", errmsg("index \"%s\" contains corrupted page at block %u",
RelationGetRelationName(rel), RelationGetRelationName(rel),
BufferGetBlockNumber(buf)))); BufferGetBlockNumber(buf))));
else else
{ {
HashPageOpaque opaque; HashPageOpaque opaque;
int pagetype; int pagetype;
opaque = (HashPageOpaque) PageGetSpecialPointer(page); opaque = (HashPageOpaque) PageGetSpecialPointer(page);
pagetype = opaque->hasho_flag & LH_PAGE_TYPE; pagetype = opaque->hasho_flag & LH_PAGE_TYPE;
@ -676,9 +676,9 @@ pgstathashindex(PG_FUNCTION_ARGS)
else else
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INDEX_CORRUPTED), (errcode(ERRCODE_INDEX_CORRUPTED),
errmsg("unexpected page type 0x%04X in HASH index \"%s\" block %u", errmsg("unexpected page type 0x%04X in HASH index \"%s\" block %u",
opaque->hasho_flag, RelationGetRelationName(rel), opaque->hasho_flag, RelationGetRelationName(rel),
BufferGetBlockNumber(buf)))); BufferGetBlockNumber(buf))));
} }
UnlockReleaseBuffer(buf); UnlockReleaseBuffer(buf);
} }
@ -735,12 +735,12 @@ static void
GetHashPageStats(Page page, HashIndexStat *stats) GetHashPageStats(Page page, HashIndexStat *stats)
{ {
OffsetNumber maxoff = PageGetMaxOffsetNumber(page); OffsetNumber maxoff = PageGetMaxOffsetNumber(page);
int off; int off;
/* count live and dead tuples, and free space */ /* count live and dead tuples, and free space */
for (off = FirstOffsetNumber; off <= maxoff; off++) for (off = FirstOffsetNumber; off <= maxoff; off++)
{ {
ItemId id = PageGetItemId(page, off); ItemId id = PageGetItemId(page, off);
if (!ItemIdIsDead(id)) if (!ItemIdIsDead(id))
stats->live_items++; stats->live_items++;

@ -171,8 +171,8 @@ static void deparseFromExprForRel(StringInfo buf, PlannerInfo *root,
RelOptInfo *joinrel, bool use_alias, List **params_list); RelOptInfo *joinrel, bool use_alias, List **params_list);
static void deparseFromExpr(List *quals, deparse_expr_cxt *context); static void deparseFromExpr(List *quals, deparse_expr_cxt *context);
static void deparseRangeTblRef(StringInfo buf, PlannerInfo *root, static void deparseRangeTblRef(StringInfo buf, PlannerInfo *root,
RelOptInfo *foreignrel, bool make_subquery, RelOptInfo *foreignrel, bool make_subquery,
List **params_list); List **params_list);
static void deparseAggref(Aggref *node, deparse_expr_cxt *context); static void deparseAggref(Aggref *node, deparse_expr_cxt *context);
static void appendGroupByClause(List *tlist, deparse_expr_cxt *context); static void appendGroupByClause(List *tlist, deparse_expr_cxt *context);
static void appendAggOrderBy(List *orderList, List *targetList, static void appendAggOrderBy(List *orderList, List *targetList,
@ -185,9 +185,9 @@ static Node *deparseSortGroupClause(Index ref, List *tlist,
* Helper functions * Helper functions
*/ */
static bool is_subquery_var(Var *node, RelOptInfo *foreignrel, static bool is_subquery_var(Var *node, RelOptInfo *foreignrel,
int *relno, int *colno); int *relno, int *colno);
static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel, static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel,
int *relno, int *colno); int *relno, int *colno);
/* /*
@ -1017,8 +1017,8 @@ deparseSelectSql(List *tlist, bool is_subquery, List **retrieved_attrs,
{ {
/* /*
* For a relation that is deparsed as a subquery, emit expressions * For a relation that is deparsed as a subquery, emit expressions
* specified in the relation's reltarget. Note that since this is * specified in the relation's reltarget. Note that since this is for
* for the subquery, no need to care about *retrieved_attrs. * the subquery, no need to care about *retrieved_attrs.
*/ */
deparseSubqueryTargetList(context); deparseSubqueryTargetList(context);
} }
@ -2189,8 +2189,8 @@ deparseVar(Var *node, deparse_expr_cxt *context)
/* /*
* If the Var belongs to the foreign relation that is deparsed as a * If the Var belongs to the foreign relation that is deparsed as a
* subquery, use the relation and column alias to the Var provided * subquery, use the relation and column alias to the Var provided by the
* by the subquery, instead of the remote name. * subquery, instead of the remote name.
*/ */
if (is_subquery_var(node, context->scanrel, &relno, &colno)) if (is_subquery_var(node, context->scanrel, &relno, &colno))
{ {

@ -417,8 +417,8 @@ static void add_foreign_grouping_paths(PlannerInfo *root,
static void apply_server_options(PgFdwRelationInfo *fpinfo); static void apply_server_options(PgFdwRelationInfo *fpinfo);
static void apply_table_options(PgFdwRelationInfo *fpinfo); static void apply_table_options(PgFdwRelationInfo *fpinfo);
static void merge_fdw_options(PgFdwRelationInfo *fpinfo, static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
const PgFdwRelationInfo *fpinfo_o, const PgFdwRelationInfo *fpinfo_o,
const PgFdwRelationInfo *fpinfo_i); const PgFdwRelationInfo *fpinfo_i);
/* /*
@ -4170,8 +4170,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype,
fpinfo->jointype = jointype; fpinfo->jointype = jointype;
/* /*
* By default, both the input relations are not required to be deparsed * By default, both the input relations are not required to be deparsed as
* as subqueries, but there might be some relations covered by the input * subqueries, but there might be some relations covered by the input
* relations that are required to be deparsed as subqueries, so save the * relations that are required to be deparsed as subqueries, so save the
* relids of those relations for later use by the deparser. * relids of those relations for later use by the deparser.
*/ */
@ -4227,8 +4227,8 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype,
case JOIN_FULL: case JOIN_FULL:
/* /*
* In this case, if any of the input relations has conditions, * In this case, if any of the input relations has conditions, we
* we need to deparse that relation as a subquery so that the * need to deparse that relation as a subquery so that the
* conditions can be evaluated before the join. Remember it in * conditions can be evaluated before the join. Remember it in
* the fpinfo of this relation so that the deparser can take * the fpinfo of this relation so that the deparser can take
* appropriate action. Also, save the relids of base relations * appropriate action. Also, save the relids of base relations
@ -4305,7 +4305,7 @@ foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype,
* Note that since this joinrel is at the end of the join_rel_list list * Note that since this joinrel is at the end of the join_rel_list list
* when we are called, we can get the position by list_length. * when we are called, we can get the position by list_length.
*/ */
Assert(fpinfo->relation_index == 0); /* shouldn't be set yet */ Assert(fpinfo->relation_index == 0); /* shouldn't be set yet */
fpinfo->relation_index = fpinfo->relation_index =
list_length(root->parse->rtable) + list_length(root->join_rel_list); list_length(root->parse->rtable) + list_length(root->join_rel_list);
@ -4354,7 +4354,7 @@ add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel,
static void static void
apply_server_options(PgFdwRelationInfo *fpinfo) apply_server_options(PgFdwRelationInfo *fpinfo)
{ {
ListCell *lc; ListCell *lc;
foreach(lc, fpinfo->server->options) foreach(lc, fpinfo->server->options)
{ {
@ -4382,7 +4382,7 @@ apply_server_options(PgFdwRelationInfo *fpinfo)
static void static void
apply_table_options(PgFdwRelationInfo *fpinfo) apply_table_options(PgFdwRelationInfo *fpinfo)
{ {
ListCell *lc; ListCell *lc;
foreach(lc, fpinfo->table->options) foreach(lc, fpinfo->table->options)
{ {
@ -4439,7 +4439,7 @@ merge_fdw_options(PgFdwRelationInfo *fpinfo,
* best. * best.
*/ */
fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate || fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate ||
fpinfo_i->use_remote_estimate; fpinfo_i->use_remote_estimate;
/* /*
* Set fetch size to maximum of the joining sides, since we are * Set fetch size to maximum of the joining sides, since we are
@ -4869,7 +4869,7 @@ add_foreign_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
fpinfo->table = ifpinfo->table; fpinfo->table = ifpinfo->table;
fpinfo->server = ifpinfo->server; fpinfo->server = ifpinfo->server;
fpinfo->user = ifpinfo->user; fpinfo->user = ifpinfo->user;
merge_fdw_options(fpinfo, ifpinfo , NULL); merge_fdw_options(fpinfo, ifpinfo, NULL);
/* Assess if it is safe to push down aggregation and grouping. */ /* Assess if it is safe to push down aggregation and grouping. */
if (!foreign_grouping_ok(root, grouped_rel)) if (!foreign_grouping_ok(root, grouped_rel))

@ -96,9 +96,9 @@ typedef struct PgFdwRelationInfo
List *grouped_tlist; List *grouped_tlist;
/* Subquery information */ /* Subquery information */
bool make_outerrel_subquery; /* do we deparse outerrel as a bool make_outerrel_subquery; /* do we deparse outerrel as a
* subquery? */ * subquery? */
bool make_innerrel_subquery; /* do we deparse innerrel as a bool make_innerrel_subquery; /* do we deparse innerrel as a
* subquery? */ * subquery? */
Relids lower_subquery_rels; /* all relids appearing in lower Relids lower_subquery_rels; /* all relids appearing in lower
* subqueries */ * subqueries */

@ -364,7 +364,7 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
MemoryContext oldcxt; MemoryContext oldcxt;
MemoryContext perRangeCxt; MemoryContext perRangeCxt;
BrinMemTuple *dtup; BrinMemTuple *dtup;
BrinTuple *btup = NULL; BrinTuple *btup = NULL;
Size btupsz = 0; Size btupsz = 0;
opaque = (BrinOpaque *) scan->opaque; opaque = (BrinOpaque *) scan->opaque;
@ -920,13 +920,13 @@ brin_summarize_range(PG_FUNCTION_ARGS)
Datum Datum
brin_desummarize_range(PG_FUNCTION_ARGS) brin_desummarize_range(PG_FUNCTION_ARGS)
{ {
Oid indexoid = PG_GETARG_OID(0); Oid indexoid = PG_GETARG_OID(0);
int64 heapBlk64 = PG_GETARG_INT64(1); int64 heapBlk64 = PG_GETARG_INT64(1);
BlockNumber heapBlk; BlockNumber heapBlk;
Oid heapoid; Oid heapoid;
Relation heapRel; Relation heapRel;
Relation indexRel; Relation indexRel;
bool done; bool done;
if (heapBlk64 > MaxBlockNumber || heapBlk64 < 0) if (heapBlk64 > MaxBlockNumber || heapBlk64 < 0)
{ {
@ -977,7 +977,8 @@ brin_desummarize_range(PG_FUNCTION_ARGS)
RelationGetRelationName(indexRel)))); RelationGetRelationName(indexRel))));
/* the revmap does the hard work */ /* the revmap does the hard work */
do { do
{
done = brinRevmapDesummarizeRange(indexRel, heapBlk); done = brinRevmapDesummarizeRange(indexRel, heapBlk);
} }
while (!done); while (!done);

@ -318,11 +318,11 @@ bool
brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk) brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk)
{ {
BrinRevmap *revmap; BrinRevmap *revmap;
BlockNumber pagesPerRange; BlockNumber pagesPerRange;
RevmapContents *contents; RevmapContents *contents;
ItemPointerData *iptr; ItemPointerData *iptr;
ItemPointerData invalidIptr; ItemPointerData invalidIptr;
BlockNumber revmapBlk; BlockNumber revmapBlk;
Buffer revmapBuf; Buffer revmapBuf;
Buffer regBuf; Buffer regBuf;
Page revmapPg; Page revmapPg;
@ -415,7 +415,7 @@ brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk)
if (RelationNeedsWAL(idxrel)) if (RelationNeedsWAL(idxrel))
{ {
xl_brin_desummarize xlrec; xl_brin_desummarize xlrec;
XLogRecPtr recptr; XLogRecPtr recptr;
xlrec.pagesPerRange = revmap->rm_pagesPerRange; xlrec.pagesPerRange = revmap->rm_pagesPerRange;
xlrec.heapBlk = heapBlk; xlrec.heapBlk = heapBlk;

@ -268,7 +268,7 @@ brin_xlog_desummarize_page(XLogReaderState *record)
action = XLogReadBufferForRedo(record, 0, &buffer); action = XLogReadBufferForRedo(record, 0, &buffer);
if (action == BLK_NEEDS_REDO) if (action == BLK_NEEDS_REDO)
{ {
ItemPointerData iptr; ItemPointerData iptr;
ItemPointerSetInvalid(&iptr); ItemPointerSetInvalid(&iptr);
brinSetHeapBlockItemptr(buffer, xlrec->pagesPerRange, xlrec->heapBlk, iptr); brinSetHeapBlockItemptr(buffer, xlrec->pagesPerRange, xlrec->heapBlk, iptr);
@ -283,7 +283,7 @@ brin_xlog_desummarize_page(XLogReaderState *record)
action = XLogReadBufferForRedo(record, 1, &buffer); action = XLogReadBufferForRedo(record, 1, &buffer);
if (action == BLK_NEEDS_REDO) if (action == BLK_NEEDS_REDO)
{ {
Page regPg = BufferGetPage(buffer); Page regPg = BufferGetPage(buffer);
PageIndexTupleDeleteNoCompact(regPg, xlrec->regOffset); PageIndexTupleDeleteNoCompact(regPg, xlrec->regOffset);

@ -102,8 +102,8 @@ printsimple(TupleTableSlot *slot, DestReceiver *self)
case INT4OID: case INT4OID:
{ {
int32 num = DatumGetInt32(value); int32 num = DatumGetInt32(value);
char str[12]; /* sign, 10 digits and '\0' */ char str[12]; /* sign, 10 digits and '\0' */
pg_ltoa(num, str); pg_ltoa(num, str);
pq_sendcountedtext(&buf, str, strlen(str), false); pq_sendcountedtext(&buf, str, strlen(str), false);
@ -112,8 +112,8 @@ printsimple(TupleTableSlot *slot, DestReceiver *self)
case INT8OID: case INT8OID:
{ {
int64 num = DatumGetInt64(value); int64 num = DatumGetInt64(value);
char str[23]; /* sign, 21 digits and '\0' */ char str[23]; /* sign, 21 digits and '\0' */
pg_lltoa(num, str); pg_lltoa(num, str);
pq_sendcountedtext(&buf, str, strlen(str), false); pq_sendcountedtext(&buf, str, strlen(str), false);

@ -140,9 +140,9 @@ ginDeletePage(GinVacuumState *gvs, BlockNumber deleteBlkno, BlockNumber leftBlkn
* exclusive cleanup lock. This guarantees that no insertions currently * exclusive cleanup lock. This guarantees that no insertions currently
* happen in this subtree. Caller also acquire Exclusive lock on deletable * happen in this subtree. Caller also acquire Exclusive lock on deletable
* page and is acquiring and releasing exclusive lock on left page before. * page and is acquiring and releasing exclusive lock on left page before.
* Left page was locked and released. Then parent and this page are locked. * Left page was locked and released. Then parent and this page are
* We acquire left page lock here only to mark page dirty after changing * locked. We acquire left page lock here only to mark page dirty after
* right pointer. * changing right pointer.
*/ */
lBuffer = ReadBufferExtended(gvs->index, MAIN_FORKNUM, leftBlkno, lBuffer = ReadBufferExtended(gvs->index, MAIN_FORKNUM, leftBlkno,
RBM_NORMAL, gvs->strategy); RBM_NORMAL, gvs->strategy);
@ -258,7 +258,7 @@ ginScanToDelete(GinVacuumState *gvs, BlockNumber blkno, bool isRoot,
buffer = ReadBufferExtended(gvs->index, MAIN_FORKNUM, blkno, buffer = ReadBufferExtended(gvs->index, MAIN_FORKNUM, blkno,
RBM_NORMAL, gvs->strategy); RBM_NORMAL, gvs->strategy);
if(!isRoot) if (!isRoot)
LockBuffer(buffer, GIN_EXCLUSIVE); LockBuffer(buffer, GIN_EXCLUSIVE);
page = BufferGetPage(buffer); page = BufferGetPage(buffer);
@ -295,8 +295,8 @@ ginScanToDelete(GinVacuumState *gvs, BlockNumber blkno, bool isRoot,
} }
} }
if(!isRoot) if (!isRoot)
LockBuffer(buffer, GIN_UNLOCK); LockBuffer(buffer, GIN_UNLOCK);
ReleaseBuffer(buffer); ReleaseBuffer(buffer);
@ -326,7 +326,7 @@ ginVacuumPostingTreeLeaves(GinVacuumState *gvs, BlockNumber blkno, bool isRoot)
RBM_NORMAL, gvs->strategy); RBM_NORMAL, gvs->strategy);
page = BufferGetPage(buffer); page = BufferGetPage(buffer);
ginTraverseLock(buffer,false); ginTraverseLock(buffer, false);
Assert(GinPageIsData(page)); Assert(GinPageIsData(page));
@ -347,15 +347,15 @@ ginVacuumPostingTreeLeaves(GinVacuumState *gvs, BlockNumber blkno, bool isRoot)
} }
else else
{ {
OffsetNumber i; OffsetNumber i;
bool hasEmptyChild = FALSE; bool hasEmptyChild = FALSE;
bool hasNonEmptyChild = FALSE; bool hasNonEmptyChild = FALSE;
OffsetNumber maxoff = GinPageGetOpaque(page)->maxoff; OffsetNumber maxoff = GinPageGetOpaque(page)->maxoff;
BlockNumber* children = palloc(sizeof(BlockNumber) * (maxoff + 1)); BlockNumber *children = palloc(sizeof(BlockNumber) * (maxoff + 1));
/* /*
* Read all children BlockNumbers. * Read all children BlockNumbers. Not sure it is safe if there are
* Not sure it is safe if there are many concurrent vacuums. * many concurrent vacuums.
*/ */
for (i = FirstOffsetNumber; i <= maxoff; i++) for (i = FirstOffsetNumber; i <= maxoff; i++)
@ -380,26 +380,26 @@ ginVacuumPostingTreeLeaves(GinVacuumState *gvs, BlockNumber blkno, bool isRoot)
vacuum_delay_point(); vacuum_delay_point();
/* /*
* All subtree is empty - just return TRUE to indicate that parent must * All subtree is empty - just return TRUE to indicate that parent
* do a cleanup. Unless we are ROOT an there is way to go upper. * must do a cleanup. Unless we are ROOT an there is way to go upper.
*/ */
if(hasEmptyChild && !hasNonEmptyChild && !isRoot) if (hasEmptyChild && !hasNonEmptyChild && !isRoot)
return TRUE; return TRUE;
if(hasEmptyChild) if (hasEmptyChild)
{ {
DataPageDeleteStack root, DataPageDeleteStack root,
*ptr, *ptr,
*tmp; *tmp;
buffer = ReadBufferExtended(gvs->index, MAIN_FORKNUM, blkno, buffer = ReadBufferExtended(gvs->index, MAIN_FORKNUM, blkno,
RBM_NORMAL, gvs->strategy); RBM_NORMAL, gvs->strategy);
LockBufferForCleanup(buffer); LockBufferForCleanup(buffer);
memset(&root, 0, sizeof(DataPageDeleteStack)); memset(&root, 0, sizeof(DataPageDeleteStack));
root.leftBlkno = InvalidBlockNumber; root.leftBlkno = InvalidBlockNumber;
root.isRoot = TRUE; root.isRoot = TRUE;
ginScanToDelete(gvs, blkno, TRUE, &root, InvalidOffsetNumber); ginScanToDelete(gvs, blkno, TRUE, &root, InvalidOffsetNumber);

@ -333,12 +333,12 @@ hashgettuple(IndexScanDesc scan, ScanDirection dir)
if (scan->kill_prior_tuple) if (scan->kill_prior_tuple)
{ {
/* /*
* Yes, so remember it for later. (We'll deal with all such * Yes, so remember it for later. (We'll deal with all such tuples
* tuples at once right after leaving the index page or at * at once right after leaving the index page or at end of scan.)
* end of scan.) In case if caller reverses the indexscan * In case if caller reverses the indexscan direction it is quite
* direction it is quite possible that the same item might * possible that the same item might get entered multiple times.
* get entered multiple times. But, we don't detect that; * But, we don't detect that; instead, we just forget any excess
* instead, we just forget any excess entries. * entries.
*/ */
if (so->killedItems == NULL) if (so->killedItems == NULL)
so->killedItems = palloc(MaxIndexTuplesPerPage * so->killedItems = palloc(MaxIndexTuplesPerPage *
@ -348,7 +348,7 @@ hashgettuple(IndexScanDesc scan, ScanDirection dir)
{ {
so->killedItems[so->numKilled].heapTid = so->hashso_heappos; so->killedItems[so->numKilled].heapTid = so->hashso_heappos;
so->killedItems[so->numKilled].indexOffset = so->killedItems[so->numKilled].indexOffset =
ItemPointerGetOffsetNumber(&(so->hashso_curpos)); ItemPointerGetOffsetNumber(&(so->hashso_curpos));
so->numKilled++; so->numKilled++;
} }
} }
@ -477,9 +477,8 @@ hashrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys,
Relation rel = scan->indexRelation; Relation rel = scan->indexRelation;
/* /*
* Before leaving current page, deal with any killed items. * Before leaving current page, deal with any killed items. Also, ensure
* Also, ensure that we acquire lock on current page before * that we acquire lock on current page before calling _hash_kill_items.
* calling _hash_kill_items.
*/ */
if (so->numKilled > 0) if (so->numKilled > 0)
{ {
@ -516,9 +515,8 @@ hashendscan(IndexScanDesc scan)
Relation rel = scan->indexRelation; Relation rel = scan->indexRelation;
/* /*
* Before leaving current page, deal with any killed items. * Before leaving current page, deal with any killed items. Also, ensure
* Also, ensure that we acquire lock on current page before * that we acquire lock on current page before calling _hash_kill_items.
* calling _hash_kill_items.
*/ */
if (so->numKilled > 0) if (so->numKilled > 0)
{ {
@ -889,8 +887,8 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
/* /*
* Let us mark the page as clean if vacuum removes the DEAD tuples * Let us mark the page as clean if vacuum removes the DEAD tuples
* from an index page. We do this by clearing LH_PAGE_HAS_DEAD_TUPLES * from an index page. We do this by clearing
* flag. * LH_PAGE_HAS_DEAD_TUPLES flag.
*/ */
if (tuples_removed && *tuples_removed > 0 && if (tuples_removed && *tuples_removed > 0 &&
H_HAS_DEAD_TUPLES(opaque)) H_HAS_DEAD_TUPLES(opaque))

@ -950,22 +950,22 @@ hash_xlog_update_meta_page(XLogReaderState *record)
static TransactionId static TransactionId
hash_xlog_vacuum_get_latestRemovedXid(XLogReaderState *record) hash_xlog_vacuum_get_latestRemovedXid(XLogReaderState *record)
{ {
xl_hash_vacuum_one_page *xlrec; xl_hash_vacuum_one_page *xlrec;
OffsetNumber *unused; OffsetNumber *unused;
Buffer ibuffer, Buffer ibuffer,
hbuffer; hbuffer;
Page ipage, Page ipage,
hpage; hpage;
RelFileNode rnode; RelFileNode rnode;
BlockNumber blkno; BlockNumber blkno;
ItemId iitemid, ItemId iitemid,
hitemid; hitemid;
IndexTuple itup; IndexTuple itup;
HeapTupleHeader htuphdr; HeapTupleHeader htuphdr;
BlockNumber hblkno; BlockNumber hblkno;
OffsetNumber hoffnum; OffsetNumber hoffnum;
TransactionId latestRemovedXid = InvalidTransactionId; TransactionId latestRemovedXid = InvalidTransactionId;
int i; int i;
xlrec = (xl_hash_vacuum_one_page *) XLogRecGetData(record); xlrec = (xl_hash_vacuum_one_page *) XLogRecGetData(record);
@ -984,9 +984,9 @@ hash_xlog_vacuum_get_latestRemovedXid(XLogReaderState *record)
return latestRemovedXid; return latestRemovedXid;
/* /*
* Check if WAL replay has reached a consistent database state. If not, * Check if WAL replay has reached a consistent database state. If not, we
* we must PANIC. See the definition of btree_xlog_delete_get_latestRemovedXid * must PANIC. See the definition of
* for more details. * btree_xlog_delete_get_latestRemovedXid for more details.
*/ */
if (!reachedConsistency) if (!reachedConsistency)
elog(PANIC, "hash_xlog_vacuum_get_latestRemovedXid: cannot operate with inconsistent data"); elog(PANIC, "hash_xlog_vacuum_get_latestRemovedXid: cannot operate with inconsistent data");
@ -1098,11 +1098,11 @@ hash_xlog_vacuum_get_latestRemovedXid(XLogReaderState *record)
static void static void
hash_xlog_vacuum_one_page(XLogReaderState *record) hash_xlog_vacuum_one_page(XLogReaderState *record)
{ {
XLogRecPtr lsn = record->EndRecPtr; XLogRecPtr lsn = record->EndRecPtr;
xl_hash_vacuum_one_page *xldata; xl_hash_vacuum_one_page *xldata;
Buffer buffer; Buffer buffer;
Buffer metabuf; Buffer metabuf;
Page page; Page page;
XLogRedoAction action; XLogRedoAction action;
HashPageOpaque pageopaque; HashPageOpaque pageopaque;
@ -1123,7 +1123,7 @@ hash_xlog_vacuum_one_page(XLogReaderState *record)
if (InHotStandby) if (InHotStandby)
{ {
TransactionId latestRemovedXid = TransactionId latestRemovedXid =
hash_xlog_vacuum_get_latestRemovedXid(record); hash_xlog_vacuum_get_latestRemovedXid(record);
RelFileNode rnode; RelFileNode rnode;
XLogRecGetBlockTag(record, 0, &rnode, NULL, NULL); XLogRecGetBlockTag(record, 0, &rnode, NULL, NULL);
@ -1146,8 +1146,8 @@ hash_xlog_vacuum_one_page(XLogReaderState *record)
} }
/* /*
* Mark the page as not containing any LP_DEAD items. See comments * Mark the page as not containing any LP_DEAD items. See comments in
* in _hash_vacuum_one_page() for details. * _hash_vacuum_one_page() for details.
*/ */
pageopaque = (HashPageOpaque) PageGetSpecialPointer(page); pageopaque = (HashPageOpaque) PageGetSpecialPointer(page);
pageopaque->hasho_flag &= ~LH_PAGE_HAS_DEAD_TUPLES; pageopaque->hasho_flag &= ~LH_PAGE_HAS_DEAD_TUPLES;
@ -1160,7 +1160,7 @@ hash_xlog_vacuum_one_page(XLogReaderState *record)
if (XLogReadBufferForRedo(record, 1, &metabuf) == BLK_NEEDS_REDO) if (XLogReadBufferForRedo(record, 1, &metabuf) == BLK_NEEDS_REDO)
{ {
Page metapage; Page metapage;
HashMetaPage metap; HashMetaPage metap;
metapage = BufferGetPage(metabuf); metapage = BufferGetPage(metabuf);

@ -24,7 +24,7 @@
#include "storage/buf_internals.h" #include "storage/buf_internals.h"
static void _hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf, static void _hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf,
RelFileNode hnode); RelFileNode hnode);
/* /*
* _hash_doinsert() -- Handle insertion of a single index tuple. * _hash_doinsert() -- Handle insertion of a single index tuple.
@ -63,8 +63,8 @@ restart_insert:
/* /*
* Read the metapage. We don't lock it yet; HashMaxItemSize() will * Read the metapage. We don't lock it yet; HashMaxItemSize() will
* examine pd_pagesize_version, but that can't change so we can examine * examine pd_pagesize_version, but that can't change so we can examine it
* it without a lock. * without a lock.
*/ */
metabuf = _hash_getbuf(rel, HASH_METAPAGE, HASH_NOLOCK, LH_META_PAGE); metabuf = _hash_getbuf(rel, HASH_METAPAGE, HASH_NOLOCK, LH_META_PAGE);
metapage = BufferGetPage(metabuf); metapage = BufferGetPage(metabuf);
@ -126,10 +126,9 @@ restart_insert:
BlockNumber nextblkno; BlockNumber nextblkno;
/* /*
* Check if current page has any DEAD tuples. If yes, * Check if current page has any DEAD tuples. If yes, delete these
* delete these tuples and see if we can get a space for * tuples and see if we can get a space for the new item to be
* the new item to be inserted before moving to the next * inserted before moving to the next page in the bucket chain.
* page in the bucket chain.
*/ */
if (H_HAS_DEAD_TUPLES(pageopaque)) if (H_HAS_DEAD_TUPLES(pageopaque))
{ {
@ -139,7 +138,7 @@ restart_insert:
_hash_vacuum_one_page(rel, metabuf, buf, heapRel->rd_node); _hash_vacuum_one_page(rel, metabuf, buf, heapRel->rd_node);
if (PageGetFreeSpace(page) >= itemsz) if (PageGetFreeSpace(page) >= itemsz)
break; /* OK, now we have enough space */ break; /* OK, now we have enough space */
} }
} }
@ -337,13 +336,13 @@ static void
_hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf, _hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf,
RelFileNode hnode) RelFileNode hnode)
{ {
OffsetNumber deletable[MaxOffsetNumber]; OffsetNumber deletable[MaxOffsetNumber];
int ndeletable = 0; int ndeletable = 0;
OffsetNumber offnum, OffsetNumber offnum,
maxoff; maxoff;
Page page = BufferGetPage(buf); Page page = BufferGetPage(buf);
HashPageOpaque pageopaque; HashPageOpaque pageopaque;
HashMetaPage metap; HashMetaPage metap;
/* Scan each tuple in page to see if it is marked as LP_DEAD */ /* Scan each tuple in page to see if it is marked as LP_DEAD */
maxoff = PageGetMaxOffsetNumber(page); maxoff = PageGetMaxOffsetNumber(page);
@ -351,7 +350,7 @@ _hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf,
offnum <= maxoff; offnum <= maxoff;
offnum = OffsetNumberNext(offnum)) offnum = OffsetNumberNext(offnum))
{ {
ItemId itemId = PageGetItemId(page, offnum); ItemId itemId = PageGetItemId(page, offnum);
if (ItemIdIsDead(itemId)) if (ItemIdIsDead(itemId))
deletable[ndeletable++] = offnum; deletable[ndeletable++] = offnum;
@ -360,8 +359,7 @@ _hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf,
if (ndeletable > 0) if (ndeletable > 0)
{ {
/* /*
* Write-lock the meta page so that we can decrement * Write-lock the meta page so that we can decrement tuple count.
* tuple count.
*/ */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE); LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
@ -374,8 +372,8 @@ _hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf,
* Mark the page as not containing any LP_DEAD items. This is not * Mark the page as not containing any LP_DEAD items. This is not
* certainly true (there might be some that have recently been marked, * certainly true (there might be some that have recently been marked,
* but weren't included in our target-item list), but it will almost * but weren't included in our target-item list), but it will almost
* always be true and it doesn't seem worth an additional page scan * always be true and it doesn't seem worth an additional page scan to
* to check it. Remember that LH_PAGE_HAS_DEAD_TUPLES is only a hint * check it. Remember that LH_PAGE_HAS_DEAD_TUPLES is only a hint
* anyway. * anyway.
*/ */
pageopaque = (HashPageOpaque) PageGetSpecialPointer(page); pageopaque = (HashPageOpaque) PageGetSpecialPointer(page);
@ -390,7 +388,7 @@ _hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf,
/* XLOG stuff */ /* XLOG stuff */
if (RelationNeedsWAL(rel)) if (RelationNeedsWAL(rel))
{ {
xl_hash_vacuum_one_page xlrec; xl_hash_vacuum_one_page xlrec;
XLogRecPtr recptr; XLogRecPtr recptr;
xlrec.hnode = hnode; xlrec.hnode = hnode;
@ -401,12 +399,12 @@ _hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf,
XLogRegisterData((char *) &xlrec, SizeOfHashVacuumOnePage); XLogRegisterData((char *) &xlrec, SizeOfHashVacuumOnePage);
/* /*
* We need the target-offsets array whether or not we store the whole * We need the target-offsets array whether or not we store the
* buffer, to allow us to find the latestRemovedXid on a standby * whole buffer, to allow us to find the latestRemovedXid on a
* server. * standby server.
*/ */
XLogRegisterData((char *) deletable, XLogRegisterData((char *) deletable,
ndeletable * sizeof(OffsetNumber)); ndeletable * sizeof(OffsetNumber));
XLogRegisterBuffer(1, metabuf, REGBUF_STANDARD); XLogRegisterBuffer(1, metabuf, REGBUF_STANDARD);
@ -417,9 +415,10 @@ _hash_vacuum_one_page(Relation rel, Buffer metabuf, Buffer buf,
} }
END_CRIT_SECTION(); END_CRIT_SECTION();
/* /*
* Releasing write lock on meta page as we have updated * Releasing write lock on meta page as we have updated the tuple
* the tuple count. * count.
*/ */
LockBuffer(metabuf, BUFFER_LOCK_UNLOCK); LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
} }

@ -177,8 +177,8 @@ _hash_initbuf(Buffer buf, uint32 max_bucket, uint32 num_bucket, uint32 flag,
pageopaque = (HashPageOpaque) PageGetSpecialPointer(page); pageopaque = (HashPageOpaque) PageGetSpecialPointer(page);
/* /*
* Set hasho_prevblkno with current hashm_maxbucket. This value will * Set hasho_prevblkno with current hashm_maxbucket. This value will be
* be used to validate cached HashMetaPageData. See * used to validate cached HashMetaPageData. See
* _hash_getbucketbuf_from_hashkey(). * _hash_getbucketbuf_from_hashkey().
*/ */
pageopaque->hasho_prevblkno = max_bucket; pageopaque->hasho_prevblkno = max_bucket;
@ -509,8 +509,8 @@ _hash_init_metabuffer(Buffer buf, double num_tuples, RegProcedure procid,
* Choose the number of initial bucket pages to match the fill factor * Choose the number of initial bucket pages to match the fill factor
* given the estimated number of tuples. We round up the result to the * given the estimated number of tuples. We round up the result to the
* total number of buckets which has to be allocated before using its * total number of buckets which has to be allocated before using its
* _hashm_spare element. However always force at least 2 bucket pages. * _hashm_spare element. However always force at least 2 bucket pages. The
* The upper limit is determined by considerations explained in * upper limit is determined by considerations explained in
* _hash_expandtable(). * _hash_expandtable().
*/ */
dnumbuckets = num_tuples / ffactor; dnumbuckets = num_tuples / ffactor;
@ -568,8 +568,8 @@ _hash_init_metabuffer(Buffer buf, double num_tuples, RegProcedure procid,
metap->hashm_maxbucket = num_buckets - 1; metap->hashm_maxbucket = num_buckets - 1;
/* /*
* Set highmask as next immediate ((2 ^ x) - 1), which should be sufficient * Set highmask as next immediate ((2 ^ x) - 1), which should be
* to cover num_buckets. * sufficient to cover num_buckets.
*/ */
metap->hashm_highmask = (1 << (_hash_log2(num_buckets + 1))) - 1; metap->hashm_highmask = (1 << (_hash_log2(num_buckets + 1))) - 1;
metap->hashm_lowmask = (metap->hashm_highmask >> 1); metap->hashm_lowmask = (metap->hashm_highmask >> 1);
@ -748,8 +748,8 @@ restart_expand:
{ {
/* /*
* Copy bucket mapping info now; refer to the comment in code below * Copy bucket mapping info now; refer to the comment in code below
* where we copy this information before calling _hash_splitbucket * where we copy this information before calling _hash_splitbucket to
* to see why this is okay. * see why this is okay.
*/ */
maxbucket = metap->hashm_maxbucket; maxbucket = metap->hashm_maxbucket;
highmask = metap->hashm_highmask; highmask = metap->hashm_highmask;
@ -792,8 +792,7 @@ restart_expand:
* We treat allocation of buckets as a separate WAL-logged action. * We treat allocation of buckets as a separate WAL-logged action.
* Even if we fail after this operation, won't leak bucket pages; * Even if we fail after this operation, won't leak bucket pages;
* rather, the next split will consume this space. In any case, even * rather, the next split will consume this space. In any case, even
* without failure we don't use all the space in one split * without failure we don't use all the space in one split operation.
* operation.
*/ */
buckets_to_add = _hash_get_totalbuckets(spare_ndx) - new_bucket; buckets_to_add = _hash_get_totalbuckets(spare_ndx) - new_bucket;
if (!_hash_alloc_buckets(rel, start_nblkno, buckets_to_add)) if (!_hash_alloc_buckets(rel, start_nblkno, buckets_to_add))
@ -870,10 +869,9 @@ restart_expand:
/* /*
* Mark the old bucket to indicate that split is in progress. (At * Mark the old bucket to indicate that split is in progress. (At
* operation end, we will clear the split-in-progress flag.) Also, * operation end, we will clear the split-in-progress flag.) Also, for a
* for a primary bucket page, hasho_prevblkno stores the number of * primary bucket page, hasho_prevblkno stores the number of buckets that
* buckets that existed as of the last split, so we must update that * existed as of the last split, so we must update that value here.
* value here.
*/ */
oopaque->hasho_flag |= LH_BUCKET_BEING_SPLIT; oopaque->hasho_flag |= LH_BUCKET_BEING_SPLIT;
oopaque->hasho_prevblkno = maxbucket; oopaque->hasho_prevblkno = maxbucket;
@ -1008,8 +1006,8 @@ _hash_alloc_buckets(Relation rel, BlockNumber firstblock, uint32 nblocks)
/* /*
* Initialize the page. Just zeroing the page won't work; see * Initialize the page. Just zeroing the page won't work; see
* _hash_freeovflpage for similar usage. We take care to make the * _hash_freeovflpage for similar usage. We take care to make the special
* special space valid for the benefit of tools such as pageinspect. * space valid for the benefit of tools such as pageinspect.
*/ */
_hash_pageinit(page, BLCKSZ); _hash_pageinit(page, BLCKSZ);
@ -1462,11 +1460,11 @@ log_split_page(Relation rel, Buffer buf)
* _hash_getcachedmetap() -- Returns cached metapage data. * _hash_getcachedmetap() -- Returns cached metapage data.
* *
* If metabuf is not InvalidBuffer, caller must hold a pin, but no lock, on * If metabuf is not InvalidBuffer, caller must hold a pin, but no lock, on
* the metapage. If not set, we'll set it before returning if we have to * the metapage. If not set, we'll set it before returning if we have to
* refresh the cache, and return with a pin but no lock on it; caller is * refresh the cache, and return with a pin but no lock on it; caller is
* responsible for releasing the pin. * responsible for releasing the pin.
* *
* We refresh the cache if it's not initialized yet or force_refresh is true. * We refresh the cache if it's not initialized yet or force_refresh is true.
*/ */
HashMetaPage HashMetaPage
_hash_getcachedmetap(Relation rel, Buffer *metabuf, bool force_refresh) _hash_getcachedmetap(Relation rel, Buffer *metabuf, bool force_refresh)
@ -1476,13 +1474,13 @@ _hash_getcachedmetap(Relation rel, Buffer *metabuf, bool force_refresh)
Assert(metabuf); Assert(metabuf);
if (force_refresh || rel->rd_amcache == NULL) if (force_refresh || rel->rd_amcache == NULL)
{ {
char *cache = NULL; char *cache = NULL;
/* /*
* It's important that we don't set rd_amcache to an invalid * It's important that we don't set rd_amcache to an invalid value.
* value. Either MemoryContextAlloc or _hash_getbuf could fail, * Either MemoryContextAlloc or _hash_getbuf could fail, so don't
* so don't install a pointer to the newly-allocated storage in the * install a pointer to the newly-allocated storage in the actual
* actual relcache entry until both have succeeeded. * relcache entry until both have succeeeded.
*/ */
if (rel->rd_amcache == NULL) if (rel->rd_amcache == NULL)
cache = MemoryContextAlloc(rel->rd_indexcxt, cache = MemoryContextAlloc(rel->rd_indexcxt,
@ -1517,7 +1515,7 @@ _hash_getcachedmetap(Relation rel, Buffer *metabuf, bool force_refresh)
* us an opportunity to use the previously saved metapage contents to reach * us an opportunity to use the previously saved metapage contents to reach
* the target bucket buffer, instead of reading from the metapage every time. * the target bucket buffer, instead of reading from the metapage every time.
* This saves one buffer access every time we want to reach the target bucket * This saves one buffer access every time we want to reach the target bucket
* buffer, which is very helpful savings in bufmgr traffic and contention. * buffer, which is very helpful savings in bufmgr traffic and contention.
* *
* The access type parameter (HASH_READ or HASH_WRITE) indicates whether the * The access type parameter (HASH_READ or HASH_WRITE) indicates whether the
* bucket buffer has to be locked for reading or writing. * bucket buffer has to be locked for reading or writing.

@ -528,20 +528,21 @@ _hash_get_newbucket_from_oldbucket(Relation rel, Bucket old_bucket,
void void
_hash_kill_items(IndexScanDesc scan) _hash_kill_items(IndexScanDesc scan)
{ {
HashScanOpaque so = (HashScanOpaque) scan->opaque; HashScanOpaque so = (HashScanOpaque) scan->opaque;
Page page; Page page;
HashPageOpaque opaque; HashPageOpaque opaque;
OffsetNumber offnum, maxoff; OffsetNumber offnum,
int numKilled = so->numKilled; maxoff;
int i; int numKilled = so->numKilled;
bool killedsomething = false; int i;
bool killedsomething = false;
Assert(so->numKilled > 0); Assert(so->numKilled > 0);
Assert(so->killedItems != NULL); Assert(so->killedItems != NULL);
/* /*
* Always reset the scan state, so we don't look for same * Always reset the scan state, so we don't look for same items on other
* items on other pages. * pages.
*/ */
so->numKilled = 0; so->numKilled = 0;
@ -555,7 +556,7 @@ _hash_kill_items(IndexScanDesc scan)
while (offnum <= maxoff) while (offnum <= maxoff)
{ {
ItemId iid = PageGetItemId(page, offnum); ItemId iid = PageGetItemId(page, offnum);
IndexTuple ituple = (IndexTuple) PageGetItem(page, iid); IndexTuple ituple = (IndexTuple) PageGetItem(page, iid);
if (ItemPointerEquals(&ituple->t_tid, &so->killedItems[i].heapTid)) if (ItemPointerEquals(&ituple->t_tid, &so->killedItems[i].heapTid))
@ -563,15 +564,15 @@ _hash_kill_items(IndexScanDesc scan)
/* found the item */ /* found the item */
ItemIdMarkDead(iid); ItemIdMarkDead(iid);
killedsomething = true; killedsomething = true;
break; /* out of inner search loop */ break; /* out of inner search loop */
} }
offnum = OffsetNumberNext(offnum); offnum = OffsetNumberNext(offnum);
} }
} }
/* /*
* Since this can be redone later if needed, mark as dirty hint. * Since this can be redone later if needed, mark as dirty hint. Whenever
* Whenever we mark anything LP_DEAD, we also set the page's * we mark anything LP_DEAD, we also set the page's
* LH_PAGE_HAS_DEAD_TUPLES flag, which is likewise just a hint. * LH_PAGE_HAS_DEAD_TUPLES flag, which is likewise just a hint.
*/ */
if (killedsomething) if (killedsomething)

@ -3518,10 +3518,10 @@ heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
* *
* For HOT considerations, this is wasted effort if we fail to update or * For HOT considerations, this is wasted effort if we fail to update or
* have to put the new tuple on a different page. But we must compute the * have to put the new tuple on a different page. But we must compute the
* list before obtaining buffer lock --- in the worst case, if we are doing * list before obtaining buffer lock --- in the worst case, if we are
* an update on one of the relevant system catalogs, we could deadlock if * doing an update on one of the relevant system catalogs, we could
* we try to fetch the list later. In any case, the relcache caches the * deadlock if we try to fetch the list later. In any case, the relcache
* data so this is usually pretty cheap. * caches the data so this is usually pretty cheap.
* *
* We also need columns used by the replica identity and columns that are * We also need columns used by the replica identity and columns that are
* considered the "key" of rows in the table. * considered the "key" of rows in the table.
@ -3540,15 +3540,16 @@ heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
page = BufferGetPage(buffer); page = BufferGetPage(buffer);
interesting_attrs = NULL; interesting_attrs = NULL;
/* /*
* If the page is already full, there is hardly any chance of doing a HOT * If the page is already full, there is hardly any chance of doing a HOT
* update on this page. It might be wasteful effort to look for index * update on this page. It might be wasteful effort to look for index
* column updates only to later reject HOT updates for lack of space in the * column updates only to later reject HOT updates for lack of space in
* same page. So we be conservative and only fetch hot_attrs if the page is * the same page. So we be conservative and only fetch hot_attrs if the
* not already full. Since we are already holding a pin on the buffer, * page is not already full. Since we are already holding a pin on the
* there is no chance that the buffer can get cleaned up concurrently and * buffer, there is no chance that the buffer can get cleaned up
* even if that was possible, in the worst case we lose a chance to do a * concurrently and even if that was possible, in the worst case we lose a
* HOT update. * chance to do a HOT update.
*/ */
if (!PageIsFull(page)) if (!PageIsFull(page))
{ {
@ -4176,7 +4177,7 @@ l2:
* logged. * logged.
*/ */
old_key_tuple = ExtractReplicaIdentity(relation, &oldtup, old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
bms_overlap(modified_attrs, id_attrs), bms_overlap(modified_attrs, id_attrs),
&old_key_copied); &old_key_copied);
/* NO EREPORT(ERROR) from here till changes are logged */ /* NO EREPORT(ERROR) from here till changes are logged */
@ -4422,17 +4423,17 @@ static Bitmapset *
HeapDetermineModifiedColumns(Relation relation, Bitmapset *interesting_cols, HeapDetermineModifiedColumns(Relation relation, Bitmapset *interesting_cols,
HeapTuple oldtup, HeapTuple newtup) HeapTuple oldtup, HeapTuple newtup)
{ {
int attnum; int attnum;
Bitmapset *modified = NULL; Bitmapset *modified = NULL;
while ((attnum = bms_first_member(interesting_cols)) >= 0) while ((attnum = bms_first_member(interesting_cols)) >= 0)
{ {
attnum += FirstLowInvalidHeapAttributeNumber; attnum += FirstLowInvalidHeapAttributeNumber;
if (!heap_tuple_attr_equals(RelationGetDescr(relation), if (!heap_tuple_attr_equals(RelationGetDescr(relation),
attnum, oldtup, newtup)) attnum, oldtup, newtup))
modified = bms_add_member(modified, modified = bms_add_member(modified,
attnum - FirstLowInvalidHeapAttributeNumber); attnum - FirstLowInvalidHeapAttributeNumber);
} }
return modified; return modified;

@ -100,7 +100,7 @@ typedef struct BTParallelScanDescData
* scan */ * scan */
slock_t btps_mutex; /* protects above variables */ slock_t btps_mutex; /* protects above variables */
ConditionVariable btps_cv; /* used to synchronize parallel scan */ ConditionVariable btps_cv; /* used to synchronize parallel scan */
} BTParallelScanDescData; } BTParallelScanDescData;
typedef struct BTParallelScanDescData *BTParallelScanDesc; typedef struct BTParallelScanDescData *BTParallelScanDesc;
@ -289,11 +289,11 @@ btbuildempty(Relation index)
_bt_initmetapage(metapage, P_NONE, 0); _bt_initmetapage(metapage, P_NONE, 0);
/* /*
* Write the page and log it. It might seem that an immediate sync * Write the page and log it. It might seem that an immediate sync would
* would be sufficient to guarantee that the file exists on disk, but * be sufficient to guarantee that the file exists on disk, but recovery
* recovery itself might remove it while replaying, for example, an * itself might remove it while replaying, for example, an
* XLOG_DBASE_CREATE or XLOG_TBLSPC_CREATE record. Therefore, we * XLOG_DBASE_CREATE or XLOG_TBLSPC_CREATE record. Therefore, we need
* need this even when wal_level=minimal. * this even when wal_level=minimal.
*/ */
PageSetChecksumInplace(metapage, BTREE_METAPAGE); PageSetChecksumInplace(metapage, BTREE_METAPAGE);
smgrwrite(index->rd_smgr, INIT_FORKNUM, BTREE_METAPAGE, smgrwrite(index->rd_smgr, INIT_FORKNUM, BTREE_METAPAGE,

@ -66,7 +66,7 @@ brin_desc(StringInfo buf, XLogReaderState *record)
xl_brin_desummarize *xlrec = (xl_brin_desummarize *) rec; xl_brin_desummarize *xlrec = (xl_brin_desummarize *) rec;
appendStringInfo(buf, "pagesPerRange %u, heapBlk %u, page offset %u", appendStringInfo(buf, "pagesPerRange %u, heapBlk %u, page offset %u",
xlrec->pagesPerRange, xlrec->heapBlk, xlrec->regOffset); xlrec->pagesPerRange, xlrec->heapBlk, xlrec->regOffset);
} }
} }

@ -36,7 +36,7 @@ clog_desc(StringInfo buf, XLogReaderState *record)
memcpy(&xlrec, rec, sizeof(xl_clog_truncate)); memcpy(&xlrec, rec, sizeof(xl_clog_truncate));
appendStringInfo(buf, "page %d; oldestXact %u", appendStringInfo(buf, "page %d; oldestXact %u",
xlrec.pageno, xlrec.oldestXact); xlrec.pageno, xlrec.oldestXact);
} }
} }

@ -117,18 +117,18 @@ gin_desc(StringInfo buf, XLogReaderState *record)
if (!(xlrec->flags & GIN_INSERT_ISDATA)) if (!(xlrec->flags & GIN_INSERT_ISDATA))
appendStringInfo(buf, " isdelete: %c", appendStringInfo(buf, " isdelete: %c",
(((ginxlogInsertEntry *) payload)->isDelete) ? 'T' : 'F'); (((ginxlogInsertEntry *) payload)->isDelete) ? 'T' : 'F');
else if (xlrec->flags & GIN_INSERT_ISLEAF) else if (xlrec->flags & GIN_INSERT_ISLEAF)
desc_recompress_leaf(buf, (ginxlogRecompressDataLeaf *) payload); desc_recompress_leaf(buf, (ginxlogRecompressDataLeaf *) payload);
else else
{ {
ginxlogInsertDataInternal *insertData = ginxlogInsertDataInternal *insertData =
(ginxlogInsertDataInternal *) payload; (ginxlogInsertDataInternal *) payload;
appendStringInfo(buf, " pitem: %u-%u/%u", appendStringInfo(buf, " pitem: %u-%u/%u",
PostingItemGetBlockNumber(&insertData->newitem), PostingItemGetBlockNumber(&insertData->newitem),
ItemPointerGetBlockNumber(&insertData->newitem.key), ItemPointerGetBlockNumber(&insertData->newitem.key),
ItemPointerGetOffsetNumber(&insertData->newitem.key)); ItemPointerGetOffsetNumber(&insertData->newitem.key));
} }
} }
} }
@ -159,7 +159,7 @@ gin_desc(StringInfo buf, XLogReaderState *record)
else else
{ {
ginxlogVacuumDataLeafPage *xlrec = ginxlogVacuumDataLeafPage *xlrec =
(ginxlogVacuumDataLeafPage *) XLogRecGetBlockData(record, 0, NULL); (ginxlogVacuumDataLeafPage *) XLogRecGetBlockData(record, 0, NULL);
desc_recompress_leaf(buf, &xlrec->data); desc_recompress_leaf(buf, &xlrec->data);
} }

@ -164,10 +164,10 @@ spgbuildempty(Relation index)
/* /*
* Write the page and log it unconditionally. This is important * Write the page and log it unconditionally. This is important
* particularly for indexes created on tablespaces and databases * particularly for indexes created on tablespaces and databases whose
* whose creation happened after the last redo pointer as recovery * creation happened after the last redo pointer as recovery removes any
* removes any of their existing content when the corresponding * of their existing content when the corresponding create records are
* create records are replayed. * replayed.
*/ */
PageSetChecksumInplace(page, SPGIST_METAPAGE_BLKNO); PageSetChecksumInplace(page, SPGIST_METAPAGE_BLKNO);
smgrwrite(index->rd_smgr, INIT_FORKNUM, SPGIST_METAPAGE_BLKNO, smgrwrite(index->rd_smgr, INIT_FORKNUM, SPGIST_METAPAGE_BLKNO,

@ -84,7 +84,7 @@ static int ZeroCLOGPage(int pageno, bool writeXlog);
static bool CLOGPagePrecedes(int page1, int page2); static bool CLOGPagePrecedes(int page1, int page2);
static void WriteZeroPageXlogRec(int pageno); static void WriteZeroPageXlogRec(int pageno);
static void WriteTruncateXlogRec(int pageno, TransactionId oldestXact, static void WriteTruncateXlogRec(int pageno, TransactionId oldestXact,
Oid oldestXidDb); Oid oldestXidDb);
static void TransactionIdSetPageStatus(TransactionId xid, int nsubxids, static void TransactionIdSetPageStatus(TransactionId xid, int nsubxids,
TransactionId *subxids, XidStatus status, TransactionId *subxids, XidStatus status,
XLogRecPtr lsn, int pageno); XLogRecPtr lsn, int pageno);
@ -680,13 +680,13 @@ TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid)
/* vac_truncate_clog already advanced oldestXid */ /* vac_truncate_clog already advanced oldestXid */
Assert(TransactionIdPrecedesOrEquals(oldestXact, Assert(TransactionIdPrecedesOrEquals(oldestXact,
ShmemVariableCache->oldestXid)); ShmemVariableCache->oldestXid));
/* /*
* Write XLOG record and flush XLOG to disk. We record the oldest xid we're * Write XLOG record and flush XLOG to disk. We record the oldest xid
* keeping information about here so we can ensure that it's always ahead * we're keeping information about here so we can ensure that it's always
* of clog truncation in case we crash, and so a standby finds out the new * ahead of clog truncation in case we crash, and so a standby finds out
* valid xid before the next checkpoint. * the new valid xid before the next checkpoint.
*/ */
WriteTruncateXlogRec(cutoffPage, oldestXact, oldestxid_datoid); WriteTruncateXlogRec(cutoffPage, oldestXact, oldestxid_datoid);

@ -748,8 +748,8 @@ ShutdownCommitTs(void)
SimpleLruFlush(CommitTsCtl, false); SimpleLruFlush(CommitTsCtl, false);
/* /*
* fsync pg_commit_ts to ensure that any files flushed previously are durably * fsync pg_commit_ts to ensure that any files flushed previously are
* on disk. * durably on disk.
*/ */
fsync_fname("pg_commit_ts", true); fsync_fname("pg_commit_ts", true);
} }
@ -764,8 +764,8 @@ CheckPointCommitTs(void)
SimpleLruFlush(CommitTsCtl, true); SimpleLruFlush(CommitTsCtl, true);
/* /*
* fsync pg_commit_ts to ensure that any files flushed previously are durably * fsync pg_commit_ts to ensure that any files flushed previously are
* on disk. * durably on disk.
*/ */
fsync_fname("pg_commit_ts", true); fsync_fname("pg_commit_ts", true);
} }

@ -87,9 +87,9 @@ SubTransSetParent(TransactionId xid, TransactionId parent)
ptr += entryno; ptr += entryno;
/* /*
* It's possible we'll try to set the parent xid multiple times * It's possible we'll try to set the parent xid multiple times but we
* but we shouldn't ever be changing the xid from one valid xid * shouldn't ever be changing the xid from one valid xid to another valid
* to another valid xid, which would corrupt the data structure. * xid, which would corrupt the data structure.
*/ */
if (*ptr != parent) if (*ptr != parent)
{ {
@ -162,13 +162,13 @@ SubTransGetTopmostTransaction(TransactionId xid)
parentXid = SubTransGetParent(parentXid); parentXid = SubTransGetParent(parentXid);
/* /*
* By convention the parent xid gets allocated first, so should * By convention the parent xid gets allocated first, so should always
* always precede the child xid. Anything else points to a corrupted * precede the child xid. Anything else points to a corrupted data
* data structure that could lead to an infinite loop, so exit. * structure that could lead to an infinite loop, so exit.
*/ */
if (!TransactionIdPrecedes(parentXid, previousXid)) if (!TransactionIdPrecedes(parentXid, previousXid))
elog(ERROR, "pg_subtrans contains invalid entry: xid %u points to parent xid %u", elog(ERROR, "pg_subtrans contains invalid entry: xid %u points to parent xid %u",
previousXid, parentXid); previousXid, parentXid);
} }
Assert(TransactionIdIsValid(previousXid)); Assert(TransactionIdIsValid(previousXid));

@ -166,7 +166,7 @@ typedef struct GlobalTransactionData
*/ */
XLogRecPtr prepare_start_lsn; /* XLOG offset of prepare record start */ XLogRecPtr prepare_start_lsn; /* XLOG offset of prepare record start */
XLogRecPtr prepare_end_lsn; /* XLOG offset of prepare record end */ XLogRecPtr prepare_end_lsn; /* XLOG offset of prepare record end */
TransactionId xid; /* The GXACT id */ TransactionId xid; /* The GXACT id */
Oid owner; /* ID of user that executed the xact */ Oid owner; /* ID of user that executed the xact */
BackendId locking_backend; /* backend currently working on the xact */ BackendId locking_backend; /* backend currently working on the xact */
@ -220,11 +220,11 @@ static void RemoveGXact(GlobalTransaction gxact);
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len); static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len);
static char *ProcessTwoPhaseBuffer(TransactionId xid, static char *ProcessTwoPhaseBuffer(TransactionId xid,
XLogRecPtr prepare_start_lsn, XLogRecPtr prepare_start_lsn,
bool fromdisk, bool setParent, bool setNextXid); bool fromdisk, bool setParent, bool setNextXid);
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid,
const char *gid, TimestampTz prepared_at, Oid owner, const char *gid, TimestampTz prepared_at, Oid owner,
Oid databaseid); Oid databaseid);
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning); static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning);
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len); static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len);
@ -1304,7 +1304,7 @@ XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY), (errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory"), errmsg("out of memory"),
errdetail("Failed while allocating a WAL reading processor."))); errdetail("Failed while allocating a WAL reading processor.")));
record = XLogReadRecord(xlogreader, lsn, &errormsg); record = XLogReadRecord(xlogreader, lsn, &errormsg);
if (record == NULL) if (record == NULL)
@ -1318,9 +1318,9 @@ XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
(XLogRecGetInfo(xlogreader) & XLOG_XACT_OPMASK) != XLOG_XACT_PREPARE) (XLogRecGetInfo(xlogreader) & XLOG_XACT_OPMASK) != XLOG_XACT_PREPARE)
ereport(ERROR, ereport(ERROR,
(errcode_for_file_access(), (errcode_for_file_access(),
errmsg("expected two-phase state data is not present in WAL at %X/%X", errmsg("expected two-phase state data is not present in WAL at %X/%X",
(uint32) (lsn >> 32), (uint32) (lsn >> 32),
(uint32) lsn))); (uint32) lsn)));
if (len != NULL) if (len != NULL)
*len = XLogRecGetDataLen(xlogreader); *len = XLogRecGetDataLen(xlogreader);
@ -1675,7 +1675,10 @@ CheckPointTwoPhase(XLogRecPtr redo_horizon)
LWLockAcquire(TwoPhaseStateLock, LW_SHARED); LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
for (i = 0; i < TwoPhaseState->numPrepXacts; i++) for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
{ {
/* Note that we are using gxact not pgxact so this works in recovery also */ /*
* Note that we are using gxact not pgxact so this works in recovery
* also
*/
GlobalTransaction gxact = TwoPhaseState->prepXacts[i]; GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
if ((gxact->valid || gxact->inredo) && if ((gxact->valid || gxact->inredo) &&
@ -1727,8 +1730,8 @@ CheckPointTwoPhase(XLogRecPtr redo_horizon)
void void
restoreTwoPhaseData(void) restoreTwoPhaseData(void)
{ {
DIR *cldir; DIR *cldir;
struct dirent *clde; struct dirent *clde;
cldir = AllocateDir(TWOPHASE_DIR); cldir = AllocateDir(TWOPHASE_DIR);
while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL) while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
@ -1801,8 +1804,8 @@ PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
xid = gxact->xid; xid = gxact->xid;
buf = ProcessTwoPhaseBuffer(xid, buf = ProcessTwoPhaseBuffer(xid,
gxact->prepare_start_lsn, gxact->prepare_start_lsn,
gxact->ondisk, false, true); gxact->ondisk, false, true);
if (buf == NULL) if (buf == NULL)
continue; continue;
@ -1876,8 +1879,8 @@ StandbyRecoverPreparedTransactions(void)
xid = gxact->xid; xid = gxact->xid;
buf = ProcessTwoPhaseBuffer(xid, buf = ProcessTwoPhaseBuffer(xid,
gxact->prepare_start_lsn, gxact->prepare_start_lsn,
gxact->ondisk, false, false); gxact->ondisk, false, false);
if (buf != NULL) if (buf != NULL)
pfree(buf); pfree(buf);
} }
@ -1920,17 +1923,17 @@ RecoverPreparedTransactions(void)
xid = gxact->xid; xid = gxact->xid;
/* /*
* Reconstruct subtrans state for the transaction --- needed * Reconstruct subtrans state for the transaction --- needed because
* because pg_subtrans is not preserved over a restart. Note that * pg_subtrans is not preserved over a restart. Note that we are
* we are linking all the subtransactions directly to the * linking all the subtransactions directly to the top-level XID;
* top-level XID; there may originally have been a more complex * there may originally have been a more complex hierarchy, but
* hierarchy, but there's no need to restore that exactly. * there's no need to restore that exactly. It's possible that
* It's possible that SubTransSetParent has been set before, if * SubTransSetParent has been set before, if the prepared transaction
* the prepared transaction generated xid assignment records. * generated xid assignment records.
*/ */
buf = ProcessTwoPhaseBuffer(xid, buf = ProcessTwoPhaseBuffer(xid,
gxact->prepare_start_lsn, gxact->prepare_start_lsn,
gxact->ondisk, true, false); gxact->ondisk, true, false);
if (buf == NULL) if (buf == NULL)
continue; continue;
@ -1949,9 +1952,8 @@ RecoverPreparedTransactions(void)
bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage)); bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
/* /*
* Recreate its GXACT and dummy PGPROC. But, check whether * Recreate its GXACT and dummy PGPROC. But, check whether it was
* it was added in redo and already has a shmem entry for * added in redo and already has a shmem entry for it.
* it.
*/ */
LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE); LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
MarkAsPreparingGuts(gxact, xid, gid, MarkAsPreparingGuts(gxact, xid, gid,
@ -1980,9 +1982,8 @@ RecoverPreparedTransactions(void)
StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids); StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
/* /*
* We're done with recovering this transaction. Clear * We're done with recovering this transaction. Clear MyLockedGxact,
* MyLockedGxact, like we do in PrepareTransaction() during normal * like we do in PrepareTransaction() during normal operation.
* operation.
*/ */
PostPrepare_Twophase(); PostPrepare_Twophase();
@ -2049,8 +2050,8 @@ ProcessTwoPhaseBuffer(TransactionId xid,
else else
{ {
ereport(WARNING, ereport(WARNING,
(errmsg("removing future two-phase state from memory for \"%u\"", (errmsg("removing future two-phase state from memory for \"%u\"",
xid))); xid)));
PrepareRedoRemove(xid, true); PrepareRedoRemove(xid, true);
} }
return NULL; return NULL;
@ -2063,8 +2064,8 @@ ProcessTwoPhaseBuffer(TransactionId xid,
if (buf == NULL) if (buf == NULL)
{ {
ereport(WARNING, ereport(WARNING,
(errmsg("removing corrupt two-phase state file for \"%u\"", (errmsg("removing corrupt two-phase state file for \"%u\"",
xid))); xid)));
RemoveTwoPhaseFile(xid, true); RemoveTwoPhaseFile(xid, true);
return NULL; return NULL;
} }
@ -2082,15 +2083,15 @@ ProcessTwoPhaseBuffer(TransactionId xid,
if (fromdisk) if (fromdisk)
{ {
ereport(WARNING, ereport(WARNING,
(errmsg("removing corrupt two-phase state file for \"%u\"", (errmsg("removing corrupt two-phase state file for \"%u\"",
xid))); xid)));
RemoveTwoPhaseFile(xid, true); RemoveTwoPhaseFile(xid, true);
} }
else else
{ {
ereport(WARNING, ereport(WARNING,
(errmsg("removing corrupt two-phase state from memory for \"%u\"", (errmsg("removing corrupt two-phase state from memory for \"%u\"",
xid))); xid)));
PrepareRedoRemove(xid, true); PrepareRedoRemove(xid, true);
} }
pfree(buf); pfree(buf);
@ -2098,8 +2099,8 @@ ProcessTwoPhaseBuffer(TransactionId xid,
} }
/* /*
* Examine subtransaction XIDs ... they should all follow main * Examine subtransaction XIDs ... they should all follow main XID, and
* XID, and they may force us to advance nextXid. * they may force us to advance nextXid.
*/ */
subxids = (TransactionId *) (buf + subxids = (TransactionId *) (buf +
MAXALIGN(sizeof(TwoPhaseFileHeader)) + MAXALIGN(sizeof(TwoPhaseFileHeader)) +
@ -2122,7 +2123,7 @@ ProcessTwoPhaseBuffer(TransactionId xid,
*/ */
LWLockAcquire(XidGenLock, LW_EXCLUSIVE); LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
if (TransactionIdFollowsOrEquals(subxid, if (TransactionIdFollowsOrEquals(subxid,
ShmemVariableCache->nextXid)) ShmemVariableCache->nextXid))
{ {
ShmemVariableCache->nextXid = subxid; ShmemVariableCache->nextXid = subxid;
TransactionIdAdvance(ShmemVariableCache->nextXid); TransactionIdAdvance(ShmemVariableCache->nextXid);
@ -2175,14 +2176,15 @@ RecordTransactionCommitPrepared(TransactionId xid,
MyPgXact->delayChkpt = true; MyPgXact->delayChkpt = true;
/* /*
* Emit the XLOG commit record. Note that we mark 2PC commits as potentially * Emit the XLOG commit record. Note that we mark 2PC commits as
* having AccessExclusiveLocks since we don't know whether or not they do. * potentially having AccessExclusiveLocks since we don't know whether or
* not they do.
*/ */
recptr = XactLogCommitRecord(committs, recptr = XactLogCommitRecord(committs,
nchildren, children, nrels, rels, nchildren, children, nrels, rels,
ninvalmsgs, invalmsgs, ninvalmsgs, invalmsgs,
initfileinval, false, initfileinval, false,
MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK, MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK,
xid); xid);
@ -2260,13 +2262,14 @@ RecordTransactionAbortPrepared(TransactionId xid,
START_CRIT_SECTION(); START_CRIT_SECTION();
/* /*
* Emit the XLOG commit record. Note that we mark 2PC aborts as potentially * Emit the XLOG commit record. Note that we mark 2PC aborts as
* having AccessExclusiveLocks since we don't know whether or not they do. * potentially having AccessExclusiveLocks since we don't know whether or
* not they do.
*/ */
recptr = XactLogAbortRecord(GetCurrentTimestamp(), recptr = XactLogAbortRecord(GetCurrentTimestamp(),
nchildren, children, nchildren, children,
nrels, rels, nrels, rels,
MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK, MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK,
xid); xid);
/* Always flush, since we're about to remove the 2PC state file */ /* Always flush, since we're about to remove the 2PC state file */
@ -2301,8 +2304,8 @@ void
PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn) PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
{ {
TwoPhaseFileHeader *hdr = (TwoPhaseFileHeader *) buf; TwoPhaseFileHeader *hdr = (TwoPhaseFileHeader *) buf;
char *bufptr; char *bufptr;
const char *gid; const char *gid;
GlobalTransaction gxact; GlobalTransaction gxact;
Assert(RecoveryInProgress()); Assert(RecoveryInProgress());
@ -2315,8 +2318,8 @@ PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
* *
* This creates a gxact struct and puts it into the active array. * This creates a gxact struct and puts it into the active array.
* *
* In redo, this struct is mainly used to track PREPARE/COMMIT entries * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
* in shared memory. Hence, we only fill up the bare minimum contents here. * shared memory. Hence, we only fill up the bare minimum contents here.
* The gxact also gets marked with gxact->inredo set to true to indicate * The gxact also gets marked with gxact->inredo set to true to indicate
* that it got added in the redo phase * that it got added in the redo phase
*/ */
@ -2340,7 +2343,7 @@ PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
gxact->locking_backend = InvalidBackendId; gxact->locking_backend = InvalidBackendId;
gxact->valid = false; gxact->valid = false;
gxact->ondisk = XLogRecPtrIsInvalid(start_lsn); gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
gxact->inredo = true; /* yes, added in redo */ gxact->inredo = true; /* yes, added in redo */
strcpy(gxact->gid, gid); strcpy(gxact->gid, gid);
/* And insert it into the active array */ /* And insert it into the active array */

@ -272,7 +272,7 @@ AdvanceOldestClogXid(TransactionId oldest_datfrozenxid)
{ {
LWLockAcquire(CLogTruncationLock, LW_EXCLUSIVE); LWLockAcquire(CLogTruncationLock, LW_EXCLUSIVE);
if (TransactionIdPrecedes(ShmemVariableCache->oldestClogXid, if (TransactionIdPrecedes(ShmemVariableCache->oldestClogXid,
oldest_datfrozenxid)) oldest_datfrozenxid))
{ {
ShmemVariableCache->oldestClogXid = oldest_datfrozenxid; ShmemVariableCache->oldestClogXid = oldest_datfrozenxid;
} }

@ -115,7 +115,7 @@ TransactionId *ParallelCurrentXids;
* globally accessible, so can be set from anywhere in the code that requires * globally accessible, so can be set from anywhere in the code that requires
* recording flags. * recording flags.
*/ */
int MyXactFlags; int MyXactFlags;
/* /*
* transaction states - transaction state from server perspective * transaction states - transaction state from server perspective
@ -2641,7 +2641,8 @@ CleanupTransaction(void)
* do abort cleanup processing * do abort cleanup processing
*/ */
AtCleanup_Portals(); /* now safe to release portal memory */ AtCleanup_Portals(); /* now safe to release portal memory */
AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */ AtEOXact_Snapshot(false, true); /* and release the transaction's
* snapshots */
CurrentResourceOwner = NULL; /* and resource owner */ CurrentResourceOwner = NULL; /* and resource owner */
if (TopTransactionResourceOwner) if (TopTransactionResourceOwner)
@ -5646,8 +5647,8 @@ xact_redo(XLogReaderState *record)
else if (info == XLOG_XACT_PREPARE) else if (info == XLOG_XACT_PREPARE)
{ {
/* /*
* Store xid and start/end pointers of the WAL record in * Store xid and start/end pointers of the WAL record in TwoPhaseState
* TwoPhaseState gxact entry. * gxact entry.
*/ */
PrepareRedoAdd(XLogRecGetData(record), PrepareRedoAdd(XLogRecGetData(record),
record->ReadRecPtr, record->ReadRecPtr,

@ -550,13 +550,12 @@ typedef struct XLogCtlInsert
bool fullPageWrites; bool fullPageWrites;
/* /*
* exclusiveBackupState indicates the state of an exclusive backup * exclusiveBackupState indicates the state of an exclusive backup (see
* (see comments of ExclusiveBackupState for more details). * comments of ExclusiveBackupState for more details). nonExclusiveBackups
* nonExclusiveBackups is a counter indicating the number of streaming * is a counter indicating the number of streaming base backups currently
* base backups currently in progress. forcePageWrites is set to true * in progress. forcePageWrites is set to true when either of these is
* when either of these is non-zero. lastBackupStart is the latest * non-zero. lastBackupStart is the latest checkpoint redo location used
* checkpoint redo location used as a starting point for an online * as a starting point for an online backup.
* backup.
*/ */
ExclusiveBackupState exclusiveBackupState; ExclusiveBackupState exclusiveBackupState;
int nonExclusiveBackups; int nonExclusiveBackups;
@ -1082,7 +1081,7 @@ XLogInsertRecord(XLogRecData *rdata,
*/ */
if ((flags & XLOG_MARK_UNIMPORTANT) == 0) if ((flags & XLOG_MARK_UNIMPORTANT) == 0)
{ {
int lockno = holdingAllLocks ? 0 : MyLockNo; int lockno = holdingAllLocks ? 0 : MyLockNo;
WALInsertLocks[lockno].l.lastImportantAt = StartPos; WALInsertLocks[lockno].l.lastImportantAt = StartPos;
} }
@ -1405,7 +1404,8 @@ checkXLogConsistency(XLogReaderState *record)
/* /*
* If the block LSN is already ahead of this WAL record, we can't * If the block LSN is already ahead of this WAL record, we can't
* expect contents to match. This can happen if recovery is restarted. * expect contents to match. This can happen if recovery is
* restarted.
*/ */
if (PageGetLSN(replay_image_masked) > record->EndRecPtr) if (PageGetLSN(replay_image_masked) > record->EndRecPtr)
continue; continue;
@ -4975,15 +4975,15 @@ BootStrapXLOG(void)
sysidentifier |= getpid() & 0xFFF; sysidentifier |= getpid() & 0xFFF;
/* /*
* Generate a random nonce. This is used for authentication requests * Generate a random nonce. This is used for authentication requests that
* that will fail because the user does not exist. The nonce is used to * will fail because the user does not exist. The nonce is used to create
* create a genuine-looking password challenge for the non-existent user, * a genuine-looking password challenge for the non-existent user, in lieu
* in lieu of an actual stored password. * of an actual stored password.
*/ */
if (!pg_backend_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN)) if (!pg_backend_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
ereport(PANIC, ereport(PANIC,
(errcode(ERRCODE_INTERNAL_ERROR), (errcode(ERRCODE_INTERNAL_ERROR),
errmsg("could not generate secret authorization token"))); errmsg("could not generate secret authorization token")));
/* First timeline ID is always 1 */ /* First timeline ID is always 1 */
ThisTimeLineID = 1; ThisTimeLineID = 1;
@ -5298,7 +5298,7 @@ readRecoveryCommandFile(void)
DatumGetLSN(DirectFunctionCall3(pg_lsn_in, DatumGetLSN(DirectFunctionCall3(pg_lsn_in,
CStringGetDatum(item->value), CStringGetDatum(item->value),
ObjectIdGetDatum(InvalidOid), ObjectIdGetDatum(InvalidOid),
Int32GetDatum(-1))); Int32GetDatum(-1)));
ereport(DEBUG2, ereport(DEBUG2,
(errmsg_internal("recovery_target_lsn = '%X/%X'", (errmsg_internal("recovery_target_lsn = '%X/%X'",
(uint32) (recoveryTargetLSN >> 32), (uint32) (recoveryTargetLSN >> 32),
@ -5643,9 +5643,9 @@ recoveryStopsBefore(XLogReaderState *record)
recoveryStopTime = 0; recoveryStopTime = 0;
recoveryStopName[0] = '\0'; recoveryStopName[0] = '\0';
ereport(LOG, ereport(LOG,
(errmsg("recovery stopping before WAL location (LSN) \"%X/%X\"", (errmsg("recovery stopping before WAL location (LSN) \"%X/%X\"",
(uint32) (recoveryStopLSN >> 32), (uint32) (recoveryStopLSN >> 32),
(uint32) recoveryStopLSN))); (uint32) recoveryStopLSN)));
return true; return true;
} }
@ -5800,9 +5800,9 @@ recoveryStopsAfter(XLogReaderState *record)
recoveryStopTime = 0; recoveryStopTime = 0;
recoveryStopName[0] = '\0'; recoveryStopName[0] = '\0';
ereport(LOG, ereport(LOG,
(errmsg("recovery stopping after WAL location (LSN) \"%X/%X\"", (errmsg("recovery stopping after WAL location (LSN) \"%X/%X\"",
(uint32) (recoveryStopLSN >> 32), (uint32) (recoveryStopLSN >> 32),
(uint32) recoveryStopLSN))); (uint32) recoveryStopLSN)));
return true; return true;
} }
@ -6348,12 +6348,12 @@ StartupXLOG(void)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY), (errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory"), errmsg("out of memory"),
errdetail("Failed while allocating a WAL reading processor."))); errdetail("Failed while allocating a WAL reading processor.")));
xlogreader->system_identifier = ControlFile->system_identifier; xlogreader->system_identifier = ControlFile->system_identifier;
/* /*
* Allocate pages dedicated to WAL consistency checks, those had better * Allocate pages dedicated to WAL consistency checks, those had better be
* be aligned. * aligned.
*/ */
replay_image_masked = (char *) palloc(BLCKSZ); replay_image_masked = (char *) palloc(BLCKSZ);
master_image_masked = (char *) palloc(BLCKSZ); master_image_masked = (char *) palloc(BLCKSZ);
@ -6687,21 +6687,21 @@ StartupXLOG(void)
/* /*
* Copy any missing timeline history files between 'now' and the recovery * Copy any missing timeline history files between 'now' and the recovery
* target timeline from archive to pg_wal. While we don't need those * target timeline from archive to pg_wal. While we don't need those files
* files ourselves - the history file of the recovery target timeline * ourselves - the history file of the recovery target timeline covers all
* covers all the previous timelines in the history too - a cascading * the previous timelines in the history too - a cascading standby server
* standby server might be interested in them. Or, if you archive the WAL * might be interested in them. Or, if you archive the WAL from this
* from this server to a different archive than the master, it'd be good * server to a different archive than the master, it'd be good for all the
* for all the history files to get archived there after failover, so that * history files to get archived there after failover, so that you can use
* you can use one of the old timelines as a PITR target. Timeline history * one of the old timelines as a PITR target. Timeline history files are
* files are small, so it's better to copy them unnecessarily than not * small, so it's better to copy them unnecessarily than not copy them and
* copy them and regret later. * regret later.
*/ */
restoreTimeLineHistoryFiles(ThisTimeLineID, recoveryTargetTLI); restoreTimeLineHistoryFiles(ThisTimeLineID, recoveryTargetTLI);
/* /*
* Before running in recovery, scan pg_twophase and fill in its status * Before running in recovery, scan pg_twophase and fill in its status to
* to be able to work on entries generated by redo. Doing a scan before * be able to work on entries generated by redo. Doing a scan before
* taking any recovery action has the merit to discard any 2PC files that * taking any recovery action has the merit to discard any 2PC files that
* are newer than the first record to replay, saving from any conflicts at * are newer than the first record to replay, saving from any conflicts at
* replay. This avoids as well any subsequent scans when doing recovery * replay. This avoids as well any subsequent scans when doing recovery
@ -7426,7 +7426,7 @@ StartupXLOG(void)
snprintf(reason, sizeof(reason), snprintf(reason, sizeof(reason),
"%s LSN %X/%X\n", "%s LSN %X/%X\n",
recoveryStopAfter ? "after" : "before", recoveryStopAfter ? "after" : "before",
(uint32 ) (recoveryStopLSN >> 32), (uint32) (recoveryStopLSN >> 32),
(uint32) recoveryStopLSN); (uint32) recoveryStopLSN);
else if (recoveryTarget == RECOVERY_TARGET_NAME) else if (recoveryTarget == RECOVERY_TARGET_NAME)
snprintf(reason, sizeof(reason), snprintf(reason, sizeof(reason),
@ -9645,6 +9645,7 @@ xlog_redo(XLogReaderState *record)
MultiXactAdvanceOldest(checkPoint.oldestMulti, MultiXactAdvanceOldest(checkPoint.oldestMulti,
checkPoint.oldestMultiDB); checkPoint.oldestMultiDB);
/* /*
* No need to set oldestClogXid here as well; it'll be set when we * No need to set oldestClogXid here as well; it'll be set when we
* redo an xl_clog_truncate if it changed since initialization. * redo an xl_clog_truncate if it changed since initialization.
@ -10238,8 +10239,8 @@ do_pg_start_backup(const char *backupidstr, bool fast, TimeLineID *starttli_p,
if (exclusive) if (exclusive)
{ {
/* /*
* At first, mark that we're now starting an exclusive backup, * At first, mark that we're now starting an exclusive backup, to
* to ensure that there are no other sessions currently running * ensure that there are no other sessions currently running
* pg_start_backup() or pg_stop_backup(). * pg_start_backup() or pg_stop_backup().
*/ */
if (XLogCtl->Insert.exclusiveBackupState != EXCLUSIVE_BACKUP_NONE) if (XLogCtl->Insert.exclusiveBackupState != EXCLUSIVE_BACKUP_NONE)
@ -10505,8 +10506,9 @@ do_pg_start_backup(const char *backupidstr, bool fast, TimeLineID *starttli_p,
{ {
/* /*
* Check for existing backup label --- implies a backup is already * Check for existing backup label --- implies a backup is already
* running. (XXX given that we checked exclusiveBackupState above, * running. (XXX given that we checked exclusiveBackupState
* maybe it would be OK to just unlink any such label file?) * above, maybe it would be OK to just unlink any such label
* file?)
*/ */
if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0) if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
{ {
@ -10727,8 +10729,8 @@ do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
if (exclusive) if (exclusive)
{ {
/* /*
* At first, mark that we're now stopping an exclusive backup, * At first, mark that we're now stopping an exclusive backup, to
* to ensure that there are no other sessions currently running * ensure that there are no other sessions currently running
* pg_start_backup() or pg_stop_backup(). * pg_start_backup() or pg_stop_backup().
*/ */
WALInsertLockAcquireExclusive(); WALInsertLockAcquireExclusive();
@ -10790,8 +10792,8 @@ do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
durable_unlink(BACKUP_LABEL_FILE, ERROR); durable_unlink(BACKUP_LABEL_FILE, ERROR);
/* /*
* Remove tablespace_map file if present, it is created only if there * Remove tablespace_map file if present, it is created only if
* are tablespaces. * there are tablespaces.
*/ */
durable_unlink(TABLESPACE_MAP, DEBUG1); durable_unlink(TABLESPACE_MAP, DEBUG1);
} }
@ -10978,9 +10980,9 @@ do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
* archived before returning. If archiving isn't enabled, the required WAL * archived before returning. If archiving isn't enabled, the required WAL
* needs to be transported via streaming replication (hopefully with * needs to be transported via streaming replication (hopefully with
* wal_keep_segments set high enough), or some more exotic mechanism like * wal_keep_segments set high enough), or some more exotic mechanism like
* polling and copying files from pg_wal with script. We have no * polling and copying files from pg_wal with script. We have no knowledge
* knowledge of those mechanisms, so it's up to the user to ensure that he * of those mechanisms, so it's up to the user to ensure that he gets all
* gets all the required WAL. * the required WAL.
* *
* We wait until both the last WAL file filled during backup and the * We wait until both the last WAL file filled during backup and the
* history file have been archived, and assume that the alphabetic sorting * history file have been archived, and assume that the alphabetic sorting
@ -10990,8 +10992,8 @@ do_pg_stop_backup(char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
* We wait forever, since archive_command is supposed to work and we * We wait forever, since archive_command is supposed to work and we
* assume the admin wanted his backup to work completely. If you don't * assume the admin wanted his backup to work completely. If you don't
* wish to wait, then either waitforarchive should be passed in as false, * wish to wait, then either waitforarchive should be passed in as false,
* or you can set statement_timeout. Also, some notices are * or you can set statement_timeout. Also, some notices are issued to
* issued to clue in anyone who might be doing this interactively. * clue in anyone who might be doing this interactively.
*/ */
if (waitforarchive && XLogArchivingActive()) if (waitforarchive && XLogArchivingActive())
{ {
@ -11717,8 +11719,8 @@ WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
* little chance that the problem will just go away, but * little chance that the problem will just go away, but
* PANIC is not good for availability either, especially * PANIC is not good for availability either, especially
* in hot standby mode. So, we treat that the same as * in hot standby mode. So, we treat that the same as
* disconnection, and retry from archive/pg_wal again. * disconnection, and retry from archive/pg_wal again. The
* The WAL in the archive should be identical to what was * WAL in the archive should be identical to what was
* streamed, so it's unlikely that it helps, but one can * streamed, so it's unlikely that it helps, but one can
* hope... * hope...
*/ */
@ -11881,9 +11883,9 @@ WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
* not open already. Also read the timeline history * not open already. Also read the timeline history
* file if we haven't initialized timeline history * file if we haven't initialized timeline history
* yet; it should be streamed over and present in * yet; it should be streamed over and present in
* pg_wal by now. Use XLOG_FROM_STREAM so that * pg_wal by now. Use XLOG_FROM_STREAM so that source
* source info is set correctly and XLogReceiptTime * info is set correctly and XLogReceiptTime isn't
* isn't changed. * changed.
*/ */
if (readFile < 0) if (readFile < 0)
{ {

@ -156,7 +156,8 @@ pg_stop_backup(PG_FUNCTION_ARGS)
* Exclusive backups were typically started in a different connection, so * Exclusive backups were typically started in a different connection, so
* don't try to verify that status of backup is set to * don't try to verify that status of backup is set to
* SESSION_BACKUP_EXCLUSIVE in this function. Actual verification that an * SESSION_BACKUP_EXCLUSIVE in this function. Actual verification that an
* exclusive backup is in fact running is handled inside do_pg_stop_backup. * exclusive backup is in fact running is handled inside
* do_pg_stop_backup.
*/ */
stoppoint = do_pg_stop_backup(NULL, true, NULL); stoppoint = do_pg_stop_backup(NULL, true, NULL);
@ -527,7 +528,7 @@ pg_walfile_name(PG_FUNCTION_ARGS)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("recovery is in progress"), errmsg("recovery is in progress"),
errhint("pg_walfile_name() cannot be executed during recovery."))); errhint("pg_walfile_name() cannot be executed during recovery.")));
XLByteToPrevSeg(locationpoint, xlogsegno); XLByteToPrevSeg(locationpoint, xlogsegno);
XLogFileName(xlogfilename, ThisTimeLineID, xlogsegno); XLogFileName(xlogfilename, ThisTimeLineID, xlogsegno);

@ -388,10 +388,10 @@ XLogRegisterBufData(uint8 block_id, char *data, int len)
* *
* The flags that can be used here are: * The flags that can be used here are:
* - XLOG_INCLUDE_ORIGIN, to determine if the replication origin should be * - XLOG_INCLUDE_ORIGIN, to determine if the replication origin should be
* included in the record. * included in the record.
* - XLOG_MARK_UNIMPORTANT, to signal that the record is not important for * - XLOG_MARK_UNIMPORTANT, to signal that the record is not important for
* durability, which allows to avoid triggering WAL archiving and other * durability, which allows to avoid triggering WAL archiving and other
* background activity. * background activity.
*/ */
void void
XLogSetRecordFlags(uint8 flags) XLogSetRecordFlags(uint8 flags)
@ -507,10 +507,10 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
hdr_rdt.data = hdr_scratch; hdr_rdt.data = hdr_scratch;
/* /*
* Enforce consistency checks for this record if user is looking for * Enforce consistency checks for this record if user is looking for it.
* it. Do this before at the beginning of this routine to give the * Do this before at the beginning of this routine to give the possibility
* possibility for callers of XLogInsert() to pass XLR_CHECK_CONSISTENCY * for callers of XLogInsert() to pass XLR_CHECK_CONSISTENCY directly for
* directly for a record. * a record.
*/ */
if (wal_consistency_checking[rmid]) if (wal_consistency_checking[rmid])
info |= XLR_CHECK_CONSISTENCY; info |= XLR_CHECK_CONSISTENCY;
@ -576,9 +576,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
bkpb.fork_flags |= BKPBLOCK_WILL_INIT; bkpb.fork_flags |= BKPBLOCK_WILL_INIT;
/* /*
* If needs_backup is true or WAL checking is enabled for * If needs_backup is true or WAL checking is enabled for current
* current resource manager, log a full-page write for the current * resource manager, log a full-page write for the current block.
* block.
*/ */
include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0; include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
@ -645,8 +644,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
bimg.bimg_info = (cbimg.hole_length == 0) ? 0 : BKPIMAGE_HAS_HOLE; bimg.bimg_info = (cbimg.hole_length == 0) ? 0 : BKPIMAGE_HAS_HOLE;
/* /*
* If WAL consistency checking is enabled for the resource manager of * If WAL consistency checking is enabled for the resource manager
* this WAL record, a full-page image is included in the record * of this WAL record, a full-page image is included in the record
* for the block modified. During redo, the full-page is replayed * for the block modified. During redo, the full-page is replayed
* only if BKPIMAGE_APPLY is set. * only if BKPIMAGE_APPLY is set.
*/ */

@ -892,8 +892,8 @@ XLogFindNextRecord(XLogReaderState *state, XLogRecPtr RecPtr)
* that, except when caller has explicitly specified the offset that * that, except when caller has explicitly specified the offset that
* falls somewhere there or when we are skipping multi-page * falls somewhere there or when we are skipping multi-page
* continuation record. It doesn't matter though because * continuation record. It doesn't matter though because
* ReadPageInternal() is prepared to handle that and will read at least * ReadPageInternal() is prepared to handle that and will read at
* short page-header worth of data * least short page-header worth of data
*/ */
targetRecOff = tmpRecPtr % XLOG_BLCKSZ; targetRecOff = tmpRecPtr % XLOG_BLCKSZ;

@ -805,22 +805,23 @@ XLogReadDetermineTimeline(XLogReaderState *state, XLogRecPtr wantPage, uint32 wa
Assert(state->readLen == 0 || state->readLen <= XLOG_BLCKSZ); Assert(state->readLen == 0 || state->readLen <= XLOG_BLCKSZ);
/* /*
* If the desired page is currently read in and valid, we have nothing to do. * If the desired page is currently read in and valid, we have nothing to
* do.
* *
* The caller should've ensured that it didn't previously advance readOff * The caller should've ensured that it didn't previously advance readOff
* past the valid limit of this timeline, so it doesn't matter if the current * past the valid limit of this timeline, so it doesn't matter if the
* TLI has since become historical. * current TLI has since become historical.
*/ */
if (lastReadPage == wantPage && if (lastReadPage == wantPage &&
state->readLen != 0 && state->readLen != 0 &&
lastReadPage + state->readLen >= wantPage + Min(wantLength,XLOG_BLCKSZ-1)) lastReadPage + state->readLen >= wantPage + Min(wantLength, XLOG_BLCKSZ - 1))
return; return;
/* /*
* If we're reading from the current timeline, it hasn't become historical * If we're reading from the current timeline, it hasn't become historical
* and the page we're reading is after the last page read, we can again * and the page we're reading is after the last page read, we can again
* just carry on. (Seeking backwards requires a check to make sure the older * just carry on. (Seeking backwards requires a check to make sure the
* page isn't on a prior timeline). * older page isn't on a prior timeline).
* *
* ThisTimeLineID might've become historical since we last looked, but the * ThisTimeLineID might've become historical since we last looked, but the
* caller is required not to read past the flush limit it saw at the time * caller is required not to read past the flush limit it saw at the time
@ -835,8 +836,8 @@ XLogReadDetermineTimeline(XLogReaderState *state, XLogRecPtr wantPage, uint32 wa
/* /*
* If we're just reading pages from a previously validated historical * If we're just reading pages from a previously validated historical
* timeline and the timeline we're reading from is valid until the * timeline and the timeline we're reading from is valid until the end of
* end of the current segment we can just keep reading. * the current segment we can just keep reading.
*/ */
if (state->currTLIValidUntil != InvalidXLogRecPtr && if (state->currTLIValidUntil != InvalidXLogRecPtr &&
state->currTLI != ThisTimeLineID && state->currTLI != ThisTimeLineID &&
@ -845,10 +846,10 @@ XLogReadDetermineTimeline(XLogReaderState *state, XLogRecPtr wantPage, uint32 wa
return; return;
/* /*
* If we reach this point we're either looking up a page for random access, * If we reach this point we're either looking up a page for random
* the current timeline just became historical, or we're reading from a new * access, the current timeline just became historical, or we're reading
* segment containing a timeline switch. In all cases we need to determine * from a new segment containing a timeline switch. In all cases we need
* the newest timeline on the segment. * to determine the newest timeline on the segment.
* *
* If it's the current timeline we can just keep reading from here unless * If it's the current timeline we can just keep reading from here unless
* we detect a timeline switch that makes the current timeline historical. * we detect a timeline switch that makes the current timeline historical.
@ -861,26 +862,29 @@ XLogReadDetermineTimeline(XLogReaderState *state, XLogRecPtr wantPage, uint32 wa
* We need to re-read the timeline history in case it's been changed * We need to re-read the timeline history in case it's been changed
* by a promotion or replay from a cascaded replica. * by a promotion or replay from a cascaded replica.
*/ */
List *timelineHistory = readTimeLineHistory(ThisTimeLineID); List *timelineHistory = readTimeLineHistory(ThisTimeLineID);
XLogRecPtr endOfSegment = (((wantPage / XLogSegSize) + 1) * XLogSegSize) - 1; XLogRecPtr endOfSegment = (((wantPage / XLogSegSize) + 1) * XLogSegSize) - 1;
Assert(wantPage / XLogSegSize == endOfSegment / XLogSegSize); Assert(wantPage / XLogSegSize == endOfSegment / XLogSegSize);
/* Find the timeline of the last LSN on the segment containing wantPage. */ /*
* Find the timeline of the last LSN on the segment containing
* wantPage.
*/
state->currTLI = tliOfPointInHistory(endOfSegment, timelineHistory); state->currTLI = tliOfPointInHistory(endOfSegment, timelineHistory);
state->currTLIValidUntil = tliSwitchPoint(state->currTLI, timelineHistory, state->currTLIValidUntil = tliSwitchPoint(state->currTLI, timelineHistory,
&state->nextTLI); &state->nextTLI);
Assert(state->currTLIValidUntil == InvalidXLogRecPtr || Assert(state->currTLIValidUntil == InvalidXLogRecPtr ||
wantPage + wantLength < state->currTLIValidUntil); wantPage + wantLength < state->currTLIValidUntil);
list_free_deep(timelineHistory); list_free_deep(timelineHistory);
elog(DEBUG3, "switched to timeline %u valid until %X/%X", elog(DEBUG3, "switched to timeline %u valid until %X/%X",
state->currTLI, state->currTLI,
(uint32)(state->currTLIValidUntil >> 32), (uint32) (state->currTLIValidUntil >> 32),
(uint32)(state->currTLIValidUntil)); (uint32) (state->currTLIValidUntil));
} }
} }
@ -929,21 +933,22 @@ read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr,
* *
* We have to do it each time through the loop because if we're in * We have to do it each time through the loop because if we're in
* recovery as a cascading standby, the current timeline might've * recovery as a cascading standby, the current timeline might've
* become historical. We can't rely on RecoveryInProgress() because * become historical. We can't rely on RecoveryInProgress() because in
* in a standby configuration like * a standby configuration like
* *
* A => B => C * A => B => C
* *
* if we're a logical decoding session on C, and B gets promoted, our * if we're a logical decoding session on C, and B gets promoted, our
* timeline will change while we remain in recovery. * timeline will change while we remain in recovery.
* *
* We can't just keep reading from the old timeline as the last WAL * We can't just keep reading from the old timeline as the last WAL
* archive in the timeline will get renamed to .partial by StartupXLOG(). * archive in the timeline will get renamed to .partial by
* StartupXLOG().
* *
* If that happens after our caller updated ThisTimeLineID but before * If that happens after our caller updated ThisTimeLineID but before
* we actually read the xlog page, we might still try to read from the * we actually read the xlog page, we might still try to read from the
* old (now renamed) segment and fail. There's not much we can do about * old (now renamed) segment and fail. There's not much we can do
* this, but it can only happen when we're a leaf of a cascading * about this, but it can only happen when we're a leaf of a cascading
* standby whose master gets promoted while we're decoding, so a * standby whose master gets promoted while we're decoding, so a
* one-off ERROR isn't too bad. * one-off ERROR isn't too bad.
*/ */

@ -1125,8 +1125,10 @@ doDeletion(const ObjectAddress *object, int flags)
heap_drop_with_catalog(object->objectId); heap_drop_with_catalog(object->objectId);
} }
/* for a sequence, in addition to dropping the heap, also /*
* delete pg_sequence tuple */ * for a sequence, in addition to dropping the heap, also
* delete pg_sequence tuple
*/
if (relKind == RELKIND_SEQUENCE) if (relKind == RELKIND_SEQUENCE)
DeleteSequenceTuple(object->objectId); DeleteSequenceTuple(object->objectId);
break; break;
@ -1942,7 +1944,7 @@ find_expr_references_walker(Node *node,
} }
else if (IsA(node, NextValueExpr)) else if (IsA(node, NextValueExpr))
{ {
NextValueExpr *nve = (NextValueExpr *) node; NextValueExpr *nve = (NextValueExpr *) node;
add_object_address(OCLASS_CLASS, nve->seqid, 0, add_object_address(OCLASS_CLASS, nve->seqid, 0,
context->addrs); context->addrs);

@ -1762,10 +1762,10 @@ heap_drop_with_catalog(Oid relid)
/* /*
* To drop a partition safely, we must grab exclusive lock on its parent, * To drop a partition safely, we must grab exclusive lock on its parent,
* because another backend might be about to execute a query on the parent * because another backend might be about to execute a query on the parent
* table. If it relies on previously cached partition descriptor, then * table. If it relies on previously cached partition descriptor, then it
* it could attempt to access the just-dropped relation as its partition. * could attempt to access the just-dropped relation as its partition. We
* We must therefore take a table lock strong enough to prevent all * must therefore take a table lock strong enough to prevent all queries
* queries on the table from proceeding until we commit and send out a * on the table from proceeding until we commit and send out a
* shared-cache-inval notice that will make them update their index lists. * shared-cache-inval notice that will make them update their index lists.
*/ */
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));

@ -854,7 +854,7 @@ get_object_address(ObjectType objtype, Node *object,
objlist = castNode(List, object); objlist = castNode(List, object);
domaddr = get_object_address_type(OBJECT_DOMAIN, domaddr = get_object_address_type(OBJECT_DOMAIN,
linitial_node(TypeName, objlist), linitial_node(TypeName, objlist),
missing_ok); missing_ok);
constrname = strVal(lsecond(objlist)); constrname = strVal(lsecond(objlist));
@ -878,7 +878,7 @@ get_object_address(ObjectType objtype, Node *object,
case OBJECT_PUBLICATION: case OBJECT_PUBLICATION:
case OBJECT_SUBSCRIPTION: case OBJECT_SUBSCRIPTION:
address = get_object_address_unqualified(objtype, address = get_object_address_unqualified(objtype,
(Value *) object, missing_ok); (Value *) object, missing_ok);
break; break;
case OBJECT_TYPE: case OBJECT_TYPE:
case OBJECT_DOMAIN: case OBJECT_DOMAIN:
@ -1345,7 +1345,7 @@ get_object_address_relobject(ObjectType objtype, List *object,
if (relation != NULL) if (relation != NULL)
heap_close(relation, AccessShareLock); heap_close(relation, AccessShareLock);
relation = NULL; /* department of accident prevention */ relation = NULL; /* department of accident prevention */
return address; return address;
} }
@ -1762,7 +1762,7 @@ get_object_address_publication_rel(List *object,
relname = linitial(object); relname = linitial(object);
relation = relation_openrv_extended(makeRangeVarFromNameList(relname), relation = relation_openrv_extended(makeRangeVarFromNameList(relname),
AccessShareLock, missing_ok); AccessShareLock, missing_ok);
if (!relation) if (!relation)
return address; return address;
@ -2138,7 +2138,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
if (list_length(name) != 1) if (list_length(name) != 1)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("name list length must be exactly %d", 1))); errmsg("name list length must be exactly %d", 1)));
objnode = linitial(name); objnode = linitial(name);
break; break;
case OBJECT_TYPE: case OBJECT_TYPE:
@ -2166,18 +2166,18 @@ pg_get_object_address(PG_FUNCTION_ARGS)
case OBJECT_FUNCTION: case OBJECT_FUNCTION:
case OBJECT_AGGREGATE: case OBJECT_AGGREGATE:
case OBJECT_OPERATOR: case OBJECT_OPERATOR:
{ {
ObjectWithArgs *owa = makeNode(ObjectWithArgs); ObjectWithArgs *owa = makeNode(ObjectWithArgs);
owa->objname = name; owa->objname = name;
owa->objargs = args; owa->objargs = args;
objnode = (Node *) owa; objnode = (Node *) owa;
break; break;
} }
case OBJECT_LARGEOBJECT: case OBJECT_LARGEOBJECT:
/* already handled above */ /* already handled above */
break; break;
/* no default, to let compiler warn about missing case */ /* no default, to let compiler warn about missing case */
} }
if (objnode == NULL) if (objnode == NULL)
@ -3370,7 +3370,7 @@ getObjectDescription(const ObjectAddress *object)
{ {
HeapTuple tup; HeapTuple tup;
char *pubname; char *pubname;
Form_pg_publication_rel prform; Form_pg_publication_rel prform;
tup = SearchSysCache1(PUBLICATIONREL, tup = SearchSysCache1(PUBLICATIONREL,
ObjectIdGetDatum(object->objectId)); ObjectIdGetDatum(object->objectId));
@ -4896,7 +4896,7 @@ getObjectIdentityParts(const ObjectAddress *object,
{ {
HeapTuple tup; HeapTuple tup;
char *pubname; char *pubname;
Form_pg_publication_rel prform; Form_pg_publication_rel prform;
tup = SearchSysCache1(PUBLICATIONREL, tup = SearchSysCache1(PUBLICATIONREL,
ObjectIdGetDatum(object->objectId)); ObjectIdGetDatum(object->objectId));
@ -5012,8 +5012,8 @@ getOpFamilyIdentity(StringInfo buffer, Oid opfid, List **object)
if (object) if (object)
*object = list_make3(pstrdup(NameStr(amForm->amname)), *object = list_make3(pstrdup(NameStr(amForm->amname)),
pstrdup(schema), pstrdup(schema),
pstrdup(NameStr(opfForm->opfname))); pstrdup(NameStr(opfForm->opfname)));
ReleaseSysCache(amTup); ReleaseSysCache(amTup);
ReleaseSysCache(opfTup); ReleaseSysCache(opfTup);

@ -80,12 +80,12 @@ CollationCreate(const char *collname, Oid collnamespace,
if (if_not_exists) if (if_not_exists)
{ {
ereport(NOTICE, ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_OBJECT), (errcode(ERRCODE_DUPLICATE_OBJECT),
collencoding == -1 collencoding == -1
? errmsg("collation \"%s\" already exists, skipping", ? errmsg("collation \"%s\" already exists, skipping",
collname) collname)
: errmsg("collation \"%s\" for encoding \"%s\" already exists, skipping", : errmsg("collation \"%s\" for encoding \"%s\" already exists, skipping",
collname, pg_encoding_to_char(collencoding)))); collname, pg_encoding_to_char(collencoding))));
return InvalidOid; return InvalidOid;
} }
else else
@ -94,8 +94,8 @@ CollationCreate(const char *collname, Oid collnamespace,
collencoding == -1 collencoding == -1
? errmsg("collation \"%s\" already exists", ? errmsg("collation \"%s\" already exists",
collname) collname)
: errmsg("collation \"%s\" for encoding \"%s\" already exists", : errmsg("collation \"%s\" for encoding \"%s\" already exists",
collname, pg_encoding_to_char(collencoding)))); collname, pg_encoding_to_char(collencoding))));
} }
/* open pg_collation; see below about the lock level */ /* open pg_collation; see below about the lock level */
@ -123,16 +123,16 @@ CollationCreate(const char *collname, Oid collnamespace,
{ {
heap_close(rel, NoLock); heap_close(rel, NoLock);
ereport(NOTICE, ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_OBJECT), (errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("collation \"%s\" already exists, skipping", errmsg("collation \"%s\" already exists, skipping",
collname))); collname)));
return InvalidOid; return InvalidOid;
} }
else else
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT), (errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("collation \"%s\" already exists", errmsg("collation \"%s\" already exists",
collname))); collname)));
} }
tupDesc = RelationGetDescr(rel); tupDesc = RelationGetDescr(rel);

@ -577,9 +577,9 @@ getOwnedSequences(Oid relid, AttrNumber attnum)
Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup); Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
/* /*
* We assume any auto or internal dependency of a sequence on a column must be * We assume any auto or internal dependency of a sequence on a column
* what we are looking for. (We need the relkind test because indexes * must be what we are looking for. (We need the relkind test because
* can also have auto dependencies on columns.) * indexes can also have auto dependencies on columns.)
*/ */
if (deprec->classid == RelationRelationId && if (deprec->classid == RelationRelationId &&
deprec->objsubid == 0 && deprec->objsubid == 0 &&

@ -38,8 +38,8 @@
*/ */
typedef struct SeenRelsEntry typedef struct SeenRelsEntry
{ {
Oid rel_id; /* relation oid */ Oid rel_id; /* relation oid */
ListCell *numparents_cell; /* corresponding list cell */ ListCell *numparents_cell; /* corresponding list cell */
} SeenRelsEntry; } SeenRelsEntry;
/* /*
@ -167,8 +167,8 @@ List *
find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents) find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
{ {
/* hash table for O(1) rel_oid -> rel_numparents cell lookup */ /* hash table for O(1) rel_oid -> rel_numparents cell lookup */
HTAB *seen_rels; HTAB *seen_rels;
HASHCTL ctl; HASHCTL ctl;
List *rels_list, List *rels_list,
*rel_numparents; *rel_numparents;
ListCell *l; ListCell *l;
@ -212,8 +212,8 @@ find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
foreach(lc, currentchildren) foreach(lc, currentchildren)
{ {
Oid child_oid = lfirst_oid(lc); Oid child_oid = lfirst_oid(lc);
bool found; bool found;
SeenRelsEntry *hash_entry; SeenRelsEntry *hash_entry;
hash_entry = hash_search(seen_rels, &child_oid, HASH_ENTER, &found); hash_entry = hash_search(seen_rels, &child_oid, HASH_ENTER, &found);
if (found) if (found)

@ -50,7 +50,7 @@ NamespaceCreate(const char *nspName, Oid ownerId, bool isTemp)
TupleDesc tupDesc; TupleDesc tupDesc;
ObjectAddress myself; ObjectAddress myself;
int i; int i;
Acl *nspacl; Acl *nspacl;
/* sanity checks */ /* sanity checks */
if (!nspName) if (!nspName)

@ -73,7 +73,7 @@ check_publication_add_relation(Relation targetrel)
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("\"%s\" is a system table", errmsg("\"%s\" is a system table",
RelationGetRelationName(targetrel)), RelationGetRelationName(targetrel)),
errdetail("System tables cannot be added to publications."))); errdetail("System tables cannot be added to publications.")));
/* UNLOGGED and TEMP relations cannot be part of publication. */ /* UNLOGGED and TEMP relations cannot be part of publication. */
if (!RelationNeedsWAL(targetrel)) if (!RelationNeedsWAL(targetrel))
@ -81,7 +81,7 @@ check_publication_add_relation(Relation targetrel)
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("table \"%s\" cannot be replicated", errmsg("table \"%s\" cannot be replicated",
RelationGetRelationName(targetrel)), RelationGetRelationName(targetrel)),
errdetail("Temporary and unlogged relations cannot be replicated."))); errdetail("Temporary and unlogged relations cannot be replicated.")));
} }
/* /*
@ -119,8 +119,8 @@ publication_add_relation(Oid pubid, Relation targetrel,
Oid relid = RelationGetRelid(targetrel); Oid relid = RelationGetRelid(targetrel);
Oid prrelid; Oid prrelid;
Publication *pub = GetPublication(pubid); Publication *pub = GetPublication(pubid);
ObjectAddress myself, ObjectAddress myself,
referenced; referenced;
rel = heap_open(PublicationRelRelationId, RowExclusiveLock); rel = heap_open(PublicationRelRelationId, RowExclusiveLock);
@ -139,8 +139,8 @@ publication_add_relation(Oid pubid, Relation targetrel,
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT), (errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("relation \"%s\" is already member of publication \"%s\"", errmsg("relation \"%s\" is already member of publication \"%s\"",
RelationGetRelationName(targetrel), pub->name))); RelationGetRelationName(targetrel), pub->name)));
} }
check_publication_add_relation(targetrel); check_publication_add_relation(targetrel);
@ -186,9 +186,9 @@ publication_add_relation(Oid pubid, Relation targetrel,
List * List *
GetRelationPublications(Oid relid) GetRelationPublications(Oid relid)
{ {
List *result = NIL; List *result = NIL;
CatCList *pubrellist; CatCList *pubrellist;
int i; int i;
/* Find all publications associated with the relation. */ /* Find all publications associated with the relation. */
pubrellist = SearchSysCacheList1(PUBLICATIONRELMAP, pubrellist = SearchSysCacheList1(PUBLICATIONRELMAP,
@ -215,11 +215,11 @@ GetRelationPublications(Oid relid)
List * List *
GetPublicationRelations(Oid pubid) GetPublicationRelations(Oid pubid)
{ {
List *result; List *result;
Relation pubrelsrel; Relation pubrelsrel;
ScanKeyData scankey; ScanKeyData scankey;
SysScanDesc scan; SysScanDesc scan;
HeapTuple tup; HeapTuple tup;
/* Find all publications associated with the relation. */ /* Find all publications associated with the relation. */
pubrelsrel = heap_open(PublicationRelRelationId, AccessShareLock); pubrelsrel = heap_open(PublicationRelRelationId, AccessShareLock);
@ -235,7 +235,7 @@ GetPublicationRelations(Oid pubid)
result = NIL; result = NIL;
while (HeapTupleIsValid(tup = systable_getnext(scan))) while (HeapTupleIsValid(tup = systable_getnext(scan)))
{ {
Form_pg_publication_rel pubrel; Form_pg_publication_rel pubrel;
pubrel = (Form_pg_publication_rel) GETSTRUCT(tup); pubrel = (Form_pg_publication_rel) GETSTRUCT(tup);
@ -254,11 +254,11 @@ GetPublicationRelations(Oid pubid)
List * List *
GetAllTablesPublications(void) GetAllTablesPublications(void)
{ {
List *result; List *result;
Relation rel; Relation rel;
ScanKeyData scankey; ScanKeyData scankey;
SysScanDesc scan; SysScanDesc scan;
HeapTuple tup; HeapTuple tup;
/* Find all publications that are marked as for all tables. */ /* Find all publications that are marked as for all tables. */
rel = heap_open(PublicationRelationId, AccessShareLock); rel = heap_open(PublicationRelationId, AccessShareLock);
@ -304,8 +304,8 @@ GetAllTablesPublicationRelations(void)
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{ {
Oid relid = HeapTupleGetOid(tuple); Oid relid = HeapTupleGetOid(tuple);
Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple); Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
if (is_publishable_class(relid, relForm)) if (is_publishable_class(relid, relForm))
result = lappend_oid(result, relid); result = lappend_oid(result, relid);
@ -325,9 +325,9 @@ GetAllTablesPublicationRelations(void)
Publication * Publication *
GetPublication(Oid pubid) GetPublication(Oid pubid)
{ {
HeapTuple tup; HeapTuple tup;
Publication *pub; Publication *pub;
Form_pg_publication pubform; Form_pg_publication pubform;
tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid)); tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid));
@ -397,9 +397,9 @@ get_publication_oid(const char *pubname, bool missing_ok)
char * char *
get_publication_name(Oid pubid) get_publication_name(Oid pubid)
{ {
HeapTuple tup; HeapTuple tup;
char *pubname; char *pubname;
Form_pg_publication pubform; Form_pg_publication pubform;
tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid)); tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid));
@ -421,10 +421,10 @@ Datum
pg_get_publication_tables(PG_FUNCTION_ARGS) pg_get_publication_tables(PG_FUNCTION_ARGS)
{ {
FuncCallContext *funcctx; FuncCallContext *funcctx;
char *pubname = text_to_cstring(PG_GETARG_TEXT_PP(0)); char *pubname = text_to_cstring(PG_GETARG_TEXT_PP(0));
Publication *publication; Publication *publication;
List *tables; List *tables;
ListCell **lcp; ListCell **lcp;
/* stuff done only on the first call of the function */ /* stuff done only on the first call of the function */
if (SRF_IS_FIRSTCALL()) if (SRF_IS_FIRSTCALL())
@ -455,7 +455,7 @@ pg_get_publication_tables(PG_FUNCTION_ARGS)
while (*lcp != NULL) while (*lcp != NULL)
{ {
Oid relid = lfirst_oid(*lcp); Oid relid = lfirst_oid(*lcp);
*lcp = lnext(*lcp); *lcp = lnext(*lcp);
SRF_RETURN_NEXT(funcctx, ObjectIdGetDatum(relid)); SRF_RETURN_NEXT(funcctx, ObjectIdGetDatum(relid));

@ -44,11 +44,11 @@ static List *textarray_to_stringlist(ArrayType *textarray);
Subscription * Subscription *
GetSubscription(Oid subid, bool missing_ok) GetSubscription(Oid subid, bool missing_ok)
{ {
HeapTuple tup; HeapTuple tup;
Subscription *sub; Subscription *sub;
Form_pg_subscription subform; Form_pg_subscription subform;
Datum datum; Datum datum;
bool isnull; bool isnull;
tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid)); tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
@ -115,11 +115,11 @@ GetSubscription(Oid subid, bool missing_ok)
int int
CountDBSubscriptions(Oid dbid) CountDBSubscriptions(Oid dbid)
{ {
int nsubs = 0; int nsubs = 0;
Relation rel; Relation rel;
ScanKeyData scankey; ScanKeyData scankey;
SysScanDesc scan; SysScanDesc scan;
HeapTuple tup; HeapTuple tup;
rel = heap_open(SubscriptionRelationId, RowExclusiveLock); rel = heap_open(SubscriptionRelationId, RowExclusiveLock);
@ -181,8 +181,8 @@ get_subscription_oid(const char *subname, bool missing_ok)
char * char *
get_subscription_name(Oid subid) get_subscription_name(Oid subid)
{ {
HeapTuple tup; HeapTuple tup;
char *subname; char *subname;
Form_pg_subscription subform; Form_pg_subscription subform;
tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid)); tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
@ -206,9 +206,10 @@ get_subscription_name(Oid subid)
static List * static List *
textarray_to_stringlist(ArrayType *textarray) textarray_to_stringlist(ArrayType *textarray)
{ {
Datum *elems; Datum *elems;
int nelems, i; int nelems,
List *res = NIL; i;
List *res = NIL;
deconstruct_array(textarray, deconstruct_array(textarray,
TEXTOID, -1, false, 'i', TEXTOID, -1, false, 'i',
@ -232,7 +233,7 @@ textarray_to_stringlist(ArrayType *textarray)
*/ */
Oid Oid
SetSubscriptionRelState(Oid subid, Oid relid, char state, SetSubscriptionRelState(Oid subid, Oid relid, char state,
XLogRecPtr sublsn) XLogRecPtr sublsn)
{ {
Relation rel; Relation rel;
HeapTuple tup; HeapTuple tup;
@ -248,8 +249,8 @@ SetSubscriptionRelState(Oid subid, Oid relid, char state,
ObjectIdGetDatum(subid)); ObjectIdGetDatum(subid));
/* /*
* If the record for given table does not exist yet create new * If the record for given table does not exist yet create new record,
* record, otherwise update the existing one. * otherwise update the existing one.
*/ */
if (!HeapTupleIsValid(tup)) if (!HeapTupleIsValid(tup))
{ {
@ -415,8 +416,8 @@ GetSubscriptionRelations(Oid subid)
Relation rel; Relation rel;
HeapTuple tup; HeapTuple tup;
int nkeys = 0; int nkeys = 0;
ScanKeyData skey[2]; ScanKeyData skey[2];
SysScanDesc scan; SysScanDesc scan;
rel = heap_open(SubscriptionRelRelationId, AccessShareLock); rel = heap_open(SubscriptionRelRelationId, AccessShareLock);
@ -430,12 +431,12 @@ GetSubscriptionRelations(Oid subid)
while (HeapTupleIsValid(tup = systable_getnext(scan))) while (HeapTupleIsValid(tup = systable_getnext(scan)))
{ {
Form_pg_subscription_rel subrel; Form_pg_subscription_rel subrel;
SubscriptionRelState *relstate; SubscriptionRelState *relstate;
subrel = (Form_pg_subscription_rel) GETSTRUCT(tup); subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
relstate = (SubscriptionRelState *)palloc(sizeof(SubscriptionRelState)); relstate = (SubscriptionRelState *) palloc(sizeof(SubscriptionRelState));
relstate->relid = subrel->srrelid; relstate->relid = subrel->srrelid;
relstate->state = subrel->srsubstate; relstate->state = subrel->srsubstate;
relstate->lsn = subrel->srsublsn; relstate->lsn = subrel->srsublsn;
@ -462,8 +463,8 @@ GetSubscriptionNotReadyRelations(Oid subid)
Relation rel; Relation rel;
HeapTuple tup; HeapTuple tup;
int nkeys = 0; int nkeys = 0;
ScanKeyData skey[2]; ScanKeyData skey[2];
SysScanDesc scan; SysScanDesc scan;
rel = heap_open(SubscriptionRelRelationId, AccessShareLock); rel = heap_open(SubscriptionRelRelationId, AccessShareLock);
@ -482,12 +483,12 @@ GetSubscriptionNotReadyRelations(Oid subid)
while (HeapTupleIsValid(tup = systable_getnext(scan))) while (HeapTupleIsValid(tup = systable_getnext(scan)))
{ {
Form_pg_subscription_rel subrel; Form_pg_subscription_rel subrel;
SubscriptionRelState *relstate; SubscriptionRelState *relstate;
subrel = (Form_pg_subscription_rel) GETSTRUCT(tup); subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
relstate = (SubscriptionRelState *)palloc(sizeof(SubscriptionRelState)); relstate = (SubscriptionRelState *) palloc(sizeof(SubscriptionRelState));
relstate->relid = subrel->srrelid; relstate->relid = subrel->srrelid;
relstate->state = subrel->srsubstate; relstate->state = subrel->srsubstate;
relstate->lsn = subrel->srsublsn; relstate->lsn = subrel->srsublsn;

@ -428,7 +428,7 @@ ExecAlterObjectDependsStmt(AlterObjectDependsStmt *stmt, ObjectAddress *refAddre
address = address =
get_object_address_rv(stmt->objectType, stmt->relation, (List *) stmt->object, get_object_address_rv(stmt->objectType, stmt->relation, (List *) stmt->object,
&rel, AccessExclusiveLock, false); &rel, AccessExclusiveLock, false);
/* /*
* If a relation was involved, it would have been opened and locked. We * If a relation was involved, it would have been opened and locked. We

@ -1275,7 +1275,7 @@ acquire_inherited_sample_rows(Relation onerel, int elevel,
nrels, nrels,
i; i;
ListCell *lc; ListCell *lc;
bool has_child; bool has_child;
/* /*
* Find all members of inheritance set. We only need AccessShareLock on * Find all members of inheritance set. We only need AccessShareLock on

@ -268,9 +268,9 @@ AlterCollation(AlterCollationStmt *stmt)
elog(ERROR, "invalid collation version change"); elog(ERROR, "invalid collation version change");
else if (oldversion && newversion && strcmp(newversion, oldversion) != 0) else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
{ {
bool nulls[Natts_pg_collation]; bool nulls[Natts_pg_collation];
bool replaces[Natts_pg_collation]; bool replaces[Natts_pg_collation];
Datum values[Natts_pg_collation]; Datum values[Natts_pg_collation];
ereport(NOTICE, ereport(NOTICE,
(errmsg("changing version from %s to %s", (errmsg("changing version from %s to %s",
@ -379,8 +379,8 @@ get_icu_language_tag(const char *localename)
uloc_toLanguageTag(localename, buf, sizeof(buf), TRUE, &status); uloc_toLanguageTag(localename, buf, sizeof(buf), TRUE, &status);
if (U_FAILURE(status)) if (U_FAILURE(status))
ereport(ERROR, ereport(ERROR,
(errmsg("could not convert locale name \"%s\" to language tag: %s", (errmsg("could not convert locale name \"%s\" to language tag: %s",
localename, u_errorName(status)))); localename, u_errorName(status))));
return pstrdup(buf); return pstrdup(buf);
} }
@ -405,7 +405,7 @@ get_icu_locale_comment(const char *localename)
return result; return result;
} }
#endif /* USE_ICU */ #endif /* USE_ICU */
Datum Datum
@ -493,7 +493,7 @@ pg_import_system_collations(PG_FUNCTION_ARGS)
CollationCreate(localebuf, nspid, GetUserId(), COLLPROVIDER_LIBC, enc, CollationCreate(localebuf, nspid, GetUserId(), COLLPROVIDER_LIBC, enc,
localebuf, localebuf, localebuf, localebuf,
get_collation_actual_version(COLLPROVIDER_LIBC, localebuf), get_collation_actual_version(COLLPROVIDER_LIBC, localebuf),
if_not_exists); if_not_exists);
CommandCounterIncrement(); CommandCounterIncrement();
@ -526,7 +526,7 @@ pg_import_system_collations(PG_FUNCTION_ARGS)
CollationCreate(alias, nspid, GetUserId(), COLLPROVIDER_LIBC, enc, CollationCreate(alias, nspid, GetUserId(), COLLPROVIDER_LIBC, enc,
locale, locale, locale, locale,
get_collation_actual_version(COLLPROVIDER_LIBC, locale), get_collation_actual_version(COLLPROVIDER_LIBC, locale),
true); true);
CommandCounterIncrement(); CommandCounterIncrement();
} }
@ -546,7 +546,7 @@ pg_import_system_collations(PG_FUNCTION_ARGS)
} }
else else
{ {
int i; int i;
/* /*
* Start the loop at -1 to sneak in the root locale without too much * Start the loop at -1 to sneak in the root locale without too much
@ -563,7 +563,7 @@ pg_import_system_collations(PG_FUNCTION_ARGS)
Oid collid; Oid collid;
if (i == -1) if (i == -1)
name = ""; /* ICU root locale */ name = ""; /* ICU root locale */
else else
name = ucol_getAvailable(i); name = ucol_getAvailable(i);
@ -572,7 +572,7 @@ pg_import_system_collations(PG_FUNCTION_ARGS)
collid = CollationCreate(psprintf("%s-x-icu", langtag), collid = CollationCreate(psprintf("%s-x-icu", langtag),
nspid, GetUserId(), COLLPROVIDER_ICU, -1, nspid, GetUserId(), COLLPROVIDER_ICU, -1,
collcollate, collcollate, collcollate, collcollate,
get_collation_actual_version(COLLPROVIDER_ICU, collcollate), get_collation_actual_version(COLLPROVIDER_ICU, collcollate),
if_not_exists); if_not_exists);
CreateComments(collid, CollationRelationId, 0, CreateComments(collid, CollationRelationId, 0,
@ -585,29 +585,29 @@ pg_import_system_collations(PG_FUNCTION_ARGS)
en = ucol_getKeywordValuesForLocale("collation", name, TRUE, &status); en = ucol_getKeywordValuesForLocale("collation", name, TRUE, &status);
if (U_FAILURE(status)) if (U_FAILURE(status))
ereport(ERROR, ereport(ERROR,
(errmsg("could not get keyword values for locale \"%s\": %s", (errmsg("could not get keyword values for locale \"%s\": %s",
name, u_errorName(status)))); name, u_errorName(status))));
status = U_ZERO_ERROR; status = U_ZERO_ERROR;
uenum_reset(en, &status); uenum_reset(en, &status);
while ((val = uenum_next(en, NULL, &status))) while ((val = uenum_next(en, NULL, &status)))
{ {
char *localeid = psprintf("%s@collation=%s", name, val); char *localeid = psprintf("%s@collation=%s", name, val);
langtag = get_icu_language_tag(localeid); langtag = get_icu_language_tag(localeid);
collcollate = U_ICU_VERSION_MAJOR_NUM >= 54 ? langtag : localeid; collcollate = U_ICU_VERSION_MAJOR_NUM >= 54 ? langtag : localeid;
collid = CollationCreate(psprintf("%s-x-icu", langtag), collid = CollationCreate(psprintf("%s-x-icu", langtag),
nspid, GetUserId(), COLLPROVIDER_ICU, -1, nspid, GetUserId(), COLLPROVIDER_ICU, -1,
collcollate, collcollate, collcollate, collcollate,
get_collation_actual_version(COLLPROVIDER_ICU, collcollate), get_collation_actual_version(COLLPROVIDER_ICU, collcollate),
if_not_exists); if_not_exists);
CreateComments(collid, CollationRelationId, 0, CreateComments(collid, CollationRelationId, 0,
get_icu_locale_comment(localeid)); get_icu_locale_comment(localeid));
} }
if (U_FAILURE(status)) if (U_FAILURE(status))
ereport(ERROR, ereport(ERROR,
(errmsg("could not get keyword values for locale \"%s\": %s", (errmsg("could not get keyword values for locale \"%s\": %s",
name, u_errorName(status)))); name, u_errorName(status))));
uenum_close(en); uenum_close(en);
} }
} }

@ -111,7 +111,7 @@ typedef struct CopyStateData
List *attnumlist; /* integer list of attnums to copy */ List *attnumlist; /* integer list of attnums to copy */
char *filename; /* filename, or NULL for STDIN/STDOUT */ char *filename; /* filename, or NULL for STDIN/STDOUT */
bool is_program; /* is 'filename' a program to popen? */ bool is_program; /* is 'filename' a program to popen? */
copy_data_source_cb data_source_cb; /* function for reading data*/ copy_data_source_cb data_source_cb; /* function for reading data */
bool binary; /* binary format? */ bool binary; /* binary format? */
bool oids; /* include OIDs? */ bool oids; /* include OIDs? */
bool freeze; /* freeze rows on loading? */ bool freeze; /* freeze rows on loading? */
@ -532,7 +532,7 @@ CopySendEndOfRow(CopyState cstate)
(void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len); (void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
break; break;
case COPY_CALLBACK: case COPY_CALLBACK:
Assert(false); /* Not yet supported. */ Assert(false); /* Not yet supported. */
break; break;
} }

@ -855,8 +855,8 @@ dropdb(const char *dbname, bool missing_ok)
{ {
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_OBJECT_IN_USE), (errcode(ERRCODE_OBJECT_IN_USE),
errmsg("database \"%s\" is used by an active logical replication slot", errmsg("database \"%s\" is used by an active logical replication slot",
dbname), dbname),
errdetail_plural("There is %d active slot", errdetail_plural("There is %d active slot",
"There are %d active slots", "There are %d active slots",
nslots_active, nslots_active))); nslots_active, nslots_active)));
@ -2134,7 +2134,8 @@ dbase_redo(XLogReaderState *record)
* which can happen in some cases. * which can happen in some cases.
* *
* This will lock out walsenders trying to connect to db-specific * This will lock out walsenders trying to connect to db-specific
* slots for logical decoding too, so it's safe for us to drop slots. * slots for logical decoding too, so it's safe for us to drop
* slots.
*/ */
LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock); LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
ResolveRecoveryConflictWithDatabase(xlrec->db_id); ResolveRecoveryConflictWithDatabase(xlrec->db_id);

@ -336,7 +336,7 @@ defGetStringList(DefElem *def)
if (nodeTag(def->arg) != T_List) if (nodeTag(def->arg) != T_List)
elog(ERROR, "unrecognized node type: %d", (int) nodeTag(def->arg)); elog(ERROR, "unrecognized node type: %d", (int) nodeTag(def->arg));
foreach(cell, (List *)def->arg) foreach(cell, (List *) def->arg)
{ {
Node *str = (Node *) lfirst(cell); Node *str = (Node *) lfirst(cell);

@ -102,7 +102,7 @@ RemoveObjects(DropStmt *stmt)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE), (errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is an aggregate function", errmsg("\"%s\" is an aggregate function",
NameListToString(castNode(ObjectWithArgs, object)->objname)), NameListToString(castNode(ObjectWithArgs, object)->objname)),
errhint("Use DROP AGGREGATE to drop aggregate functions."))); errhint("Use DROP AGGREGATE to drop aggregate functions.")));
ReleaseSysCache(tup); ReleaseSysCache(tup);
@ -145,7 +145,7 @@ owningrel_does_not_exist_skipping(List *object, const char **msg, char **name)
RangeVar *parent_rel; RangeVar *parent_rel;
parent_object = list_truncate(list_copy(object), parent_object = list_truncate(list_copy(object),
list_length(object) - 1); list_length(object) - 1);
if (schema_does_not_exist_skipping(parent_object, msg, name)) if (schema_does_not_exist_skipping(parent_object, msg, name))
return true; return true;
@ -328,6 +328,7 @@ does_not_exist_skipping(ObjectType objtype, Node *object)
case OBJECT_FUNCTION: case OBJECT_FUNCTION:
{ {
ObjectWithArgs *owa = castNode(ObjectWithArgs, object); ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) && if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) &&
!type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name)) !type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name))
{ {
@ -340,6 +341,7 @@ does_not_exist_skipping(ObjectType objtype, Node *object)
case OBJECT_AGGREGATE: case OBJECT_AGGREGATE:
{ {
ObjectWithArgs *owa = castNode(ObjectWithArgs, object); ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) && if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) &&
!type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name)) !type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name))
{ {
@ -352,6 +354,7 @@ does_not_exist_skipping(ObjectType objtype, Node *object)
case OBJECT_OPERATOR: case OBJECT_OPERATOR:
{ {
ObjectWithArgs *owa = castNode(ObjectWithArgs, object); ObjectWithArgs *owa = castNode(ObjectWithArgs, object);
if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) && if (!schema_does_not_exist_skipping(owa->objname, &msg, &name) &&
!type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name)) !type_in_list_does_not_exist_skipping(owa->objargs, &msg, &name))
{ {
@ -390,7 +393,7 @@ does_not_exist_skipping(ObjectType objtype, Node *object)
msg = gettext_noop("trigger \"%s\" for relation \"%s\" does not exist, skipping"); msg = gettext_noop("trigger \"%s\" for relation \"%s\" does not exist, skipping");
name = strVal(llast(castNode(List, object))); name = strVal(llast(castNode(List, object)));
args = NameListToString(list_truncate(list_copy(castNode(List, object)), args = NameListToString(list_truncate(list_copy(castNode(List, object)),
list_length(castNode(List, object)) - 1)); list_length(castNode(List, object)) - 1));
} }
break; break;
case OBJECT_POLICY: case OBJECT_POLICY:
@ -399,7 +402,7 @@ does_not_exist_skipping(ObjectType objtype, Node *object)
msg = gettext_noop("policy \"%s\" for relation \"%s\" does not exist, skipping"); msg = gettext_noop("policy \"%s\" for relation \"%s\" does not exist, skipping");
name = strVal(llast(castNode(List, object))); name = strVal(llast(castNode(List, object)));
args = NameListToString(list_truncate(list_copy(castNode(List, object)), args = NameListToString(list_truncate(list_copy(castNode(List, object)),
list_length(castNode(List, object)) - 1)); list_length(castNode(List, object)) - 1));
} }
break; break;
case OBJECT_EVENT_TRIGGER: case OBJECT_EVENT_TRIGGER:
@ -412,7 +415,7 @@ does_not_exist_skipping(ObjectType objtype, Node *object)
msg = gettext_noop("rule \"%s\" for relation \"%s\" does not exist, skipping"); msg = gettext_noop("rule \"%s\" for relation \"%s\" does not exist, skipping");
name = strVal(llast(castNode(List, object))); name = strVal(llast(castNode(List, object)));
args = NameListToString(list_truncate(list_copy(castNode(List, object)), args = NameListToString(list_truncate(list_copy(castNode(List, object)),
list_length(castNode(List, object)) - 1)); list_length(castNode(List, object)) - 1));
} }
break; break;
case OBJECT_FDW: case OBJECT_FDW:

@ -2250,7 +2250,7 @@ stringify_grantobjtype(GrantObjectType objtype)
} }
elog(ERROR, "unrecognized grant object type: %d", (int) objtype); elog(ERROR, "unrecognized grant object type: %d", (int) objtype);
return "???"; /* keep compiler quiet */ return "???"; /* keep compiler quiet */
} }
/* /*
@ -2292,5 +2292,5 @@ stringify_adefprivs_objtype(GrantObjectType objtype)
} }
elog(ERROR, "unrecognized grant object type: %d", (int) objtype); elog(ERROR, "unrecognized grant object type: %d", (int) objtype);
return "???"; /* keep compiler quiet */ return "???"; /* keep compiler quiet */
} }

@ -878,8 +878,8 @@ CreateForeignServer(CreateForeignServerStmt *stmt)
ownerId = GetUserId(); ownerId = GetUserId();
/* /*
* Check that there is no other foreign server by this name. * Check that there is no other foreign server by this name. Do nothing if
* Do nothing if IF NOT EXISTS was enforced. * IF NOT EXISTS was enforced.
*/ */
if (GetForeignServerByName(stmt->servername, true) != NULL) if (GetForeignServerByName(stmt->servername, true) != NULL)
{ {
@ -1171,20 +1171,20 @@ CreateUserMapping(CreateUserMappingStmt *stmt)
if (stmt->if_not_exists) if (stmt->if_not_exists)
{ {
ereport(NOTICE, ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_OBJECT), (errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("user mapping for \"%s\" already exists for server %s, skipping", errmsg("user mapping for \"%s\" already exists for server %s, skipping",
MappingUserName(useId), MappingUserName(useId),
stmt->servername))); stmt->servername)));
heap_close(rel, RowExclusiveLock); heap_close(rel, RowExclusiveLock);
return InvalidObjectAddress; return InvalidObjectAddress;
} }
else else
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT), (errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("user mapping for \"%s\" already exists for server %s", errmsg("user mapping for \"%s\" already exists for server %s",
MappingUserName(useId), MappingUserName(useId),
stmt->servername))); stmt->servername)));
} }
fdw = GetForeignDataWrapper(srv->fdwid); fdw = GetForeignDataWrapper(srv->fdwid);
@ -1275,8 +1275,8 @@ AlterUserMapping(AlterUserMappingStmt *stmt)
if (!OidIsValid(umId)) if (!OidIsValid(umId))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT), (errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("user mapping for \"%s\" does not exist for the server", errmsg("user mapping for \"%s\" does not exist for the server",
MappingUserName(useId)))); MappingUserName(useId))));
user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername); user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername);
@ -1390,13 +1390,13 @@ RemoveUserMapping(DropUserMappingStmt *stmt)
if (!stmt->missing_ok) if (!stmt->missing_ok)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT), (errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("user mapping for \"%s\" does not exist for the server", errmsg("user mapping for \"%s\" does not exist for the server",
MappingUserName(useId)))); MappingUserName(useId))));
/* IF EXISTS specified, just note it */ /* IF EXISTS specified, just note it */
ereport(NOTICE, ereport(NOTICE,
(errmsg("user mapping for \"%s\" does not exist for the server, skipping", (errmsg("user mapping for \"%s\" does not exist for the server, skipping",
MappingUserName(useId)))); MappingUserName(useId))));
return InvalidOid; return InvalidOid;
} }

@ -74,7 +74,7 @@ parse_publication_options(List *options,
*publish_delete = true; *publish_delete = true;
/* Parse options */ /* Parse options */
foreach (lc, options) foreach(lc, options)
{ {
DefElem *defel = (DefElem *) lfirst(lc); DefElem *defel = (DefElem *) lfirst(lc);
@ -106,9 +106,9 @@ parse_publication_options(List *options,
errmsg("invalid publish list"))); errmsg("invalid publish list")));
/* Process the option list. */ /* Process the option list. */
foreach (lc, publish_list) foreach(lc, publish_list)
{ {
char *publish_opt = (char *)lfirst(lc); char *publish_opt = (char *) lfirst(lc);
if (strcmp(publish_opt, "insert") == 0) if (strcmp(publish_opt, "insert") == 0)
*publish_insert = true; *publish_insert = true;
@ -157,7 +157,7 @@ CreatePublication(CreatePublicationStmt *stmt)
if (stmt->for_all_tables && !superuser()) if (stmt->for_all_tables && !superuser())
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
(errmsg("must be superuser to create FOR ALL TABLES publication")))); (errmsg("must be superuser to create FOR ALL TABLES publication"))));
rel = heap_open(PublicationRelationId, RowExclusiveLock); rel = heap_open(PublicationRelationId, RowExclusiveLock);
@ -228,7 +228,7 @@ CreatePublication(CreatePublicationStmt *stmt)
*/ */
static void static void
AlterPublicationOptions(AlterPublicationStmt *stmt, Relation rel, AlterPublicationOptions(AlterPublicationStmt *stmt, Relation rel,
HeapTuple tup) HeapTuple tup)
{ {
bool nulls[Natts_pg_publication]; bool nulls[Natts_pg_publication];
bool replaces[Natts_pg_publication]; bool replaces[Natts_pg_publication];
@ -237,7 +237,7 @@ AlterPublicationOptions(AlterPublicationStmt *stmt, Relation rel,
bool publish_insert; bool publish_insert;
bool publish_update; bool publish_update;
bool publish_delete; bool publish_delete;
ObjectAddress obj; ObjectAddress obj;
parse_publication_options(stmt->options, parse_publication_options(stmt->options,
&publish_given, &publish_insert, &publish_given, &publish_insert,
@ -275,7 +275,7 @@ AlterPublicationOptions(AlterPublicationStmt *stmt, Relation rel,
} }
else else
{ {
List *relids = GetPublicationRelations(HeapTupleGetOid(tup)); List *relids = GetPublicationRelations(HeapTupleGetOid(tup));
/* /*
* We don't want to send too many individual messages, at some point * We don't want to send too many individual messages, at some point
@ -283,11 +283,11 @@ AlterPublicationOptions(AlterPublicationStmt *stmt, Relation rel,
*/ */
if (list_length(relids) < MAX_RELCACHE_INVAL_MSGS) if (list_length(relids) < MAX_RELCACHE_INVAL_MSGS)
{ {
ListCell *lc; ListCell *lc;
foreach (lc, relids) foreach(lc, relids)
{ {
Oid relid = lfirst_oid(lc); Oid relid = lfirst_oid(lc);
CacheInvalidateRelcacheByRelid(relid); CacheInvalidateRelcacheByRelid(relid);
} }
@ -330,7 +330,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, Relation rel,
PublicationAddTables(pubid, rels, false, stmt); PublicationAddTables(pubid, rels, false, stmt);
else if (stmt->tableAction == DEFELEM_DROP) else if (stmt->tableAction == DEFELEM_DROP)
PublicationDropTables(pubid, rels, false); PublicationDropTables(pubid, rels, false);
else /* DEFELEM_SET */ else /* DEFELEM_SET */
{ {
List *oldrelids = GetPublicationRelations(pubid); List *oldrelids = GetPublicationRelations(pubid);
List *delrels = NIL; List *delrels = NIL;
@ -358,6 +358,7 @@ AlterPublicationTables(AlterPublicationStmt *stmt, Relation rel,
{ {
Relation oldrel = heap_open(oldrelid, Relation oldrel = heap_open(oldrelid,
ShareUpdateExclusiveLock); ShareUpdateExclusiveLock);
delrels = lappend(delrels, oldrel); delrels = lappend(delrels, oldrel);
} }
} }
@ -366,8 +367,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, Relation rel,
PublicationDropTables(pubid, delrels, true); PublicationDropTables(pubid, delrels, true);
/* /*
* Don't bother calculating the difference for adding, we'll catch * Don't bother calculating the difference for adding, we'll catch and
* and skip existing ones when doing catalog update. * skip existing ones when doing catalog update.
*/ */
PublicationAddTables(pubid, rels, true, stmt); PublicationAddTables(pubid, rels, true, stmt);
@ -386,8 +387,8 @@ AlterPublicationTables(AlterPublicationStmt *stmt, Relation rel,
void void
AlterPublication(AlterPublicationStmt *stmt) AlterPublication(AlterPublicationStmt *stmt)
{ {
Relation rel; Relation rel;
HeapTuple tup; HeapTuple tup;
rel = heap_open(PublicationRelationId, RowExclusiveLock); rel = heap_open(PublicationRelationId, RowExclusiveLock);
@ -444,9 +445,9 @@ RemovePublicationById(Oid pubid)
void void
RemovePublicationRelById(Oid proid) RemovePublicationRelById(Oid proid)
{ {
Relation rel; Relation rel;
HeapTuple tup; HeapTuple tup;
Form_pg_publication_rel pubrel; Form_pg_publication_rel pubrel;
rel = heap_open(PublicationRelRelationId, RowExclusiveLock); rel = heap_open(PublicationRelRelationId, RowExclusiveLock);
@ -570,14 +571,14 @@ static void
PublicationAddTables(Oid pubid, List *rels, bool if_not_exists, PublicationAddTables(Oid pubid, List *rels, bool if_not_exists,
AlterPublicationStmt *stmt) AlterPublicationStmt *stmt)
{ {
ListCell *lc; ListCell *lc;
Assert(!stmt || !stmt->for_all_tables); Assert(!stmt || !stmt->for_all_tables);
foreach(lc, rels) foreach(lc, rels)
{ {
Relation rel = (Relation) lfirst(lc); Relation rel = (Relation) lfirst(lc);
ObjectAddress obj; ObjectAddress obj;
/* Must be owner of the table or superuser. */ /* Must be owner of the table or superuser. */
if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId())) if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
@ -602,9 +603,9 @@ PublicationAddTables(Oid pubid, List *rels, bool if_not_exists,
static void static void
PublicationDropTables(Oid pubid, List *rels, bool missing_ok) PublicationDropTables(Oid pubid, List *rels, bool missing_ok)
{ {
ObjectAddress obj; ObjectAddress obj;
ListCell *lc; ListCell *lc;
Oid prid; Oid prid;
foreach(lc, rels) foreach(lc, rels)
{ {
@ -632,7 +633,7 @@ PublicationDropTables(Oid pubid, List *rels, bool missing_ok)
/* /*
* Internal workhorse for changing a publication owner * Internal workhorse for changing a publication owner
*/ */
static void static void
AlterPublicationOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId) AlterPublicationOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
{ {
Form_pg_publication form; Form_pg_publication form;
@ -663,8 +664,8 @@ AlterPublicationOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
if (form->puballtables && !superuser_arg(newOwnerId)) if (form->puballtables && !superuser_arg(newOwnerId))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied to change owner of publication \"%s\"", errmsg("permission denied to change owner of publication \"%s\"",
NameStr(form->pubname)), NameStr(form->pubname)),
errhint("The owner of a FOR ALL TABLES publication must be a superuser."))); errhint("The owner of a FOR ALL TABLES publication must be a superuser.")));
} }
@ -686,9 +687,9 @@ AlterPublicationOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
ObjectAddress ObjectAddress
AlterPublicationOwner(const char *name, Oid newOwnerId) AlterPublicationOwner(const char *name, Oid newOwnerId)
{ {
Oid subid; Oid subid;
HeapTuple tup; HeapTuple tup;
Relation rel; Relation rel;
ObjectAddress address; ObjectAddress address;
rel = heap_open(PublicationRelationId, RowExclusiveLock); rel = heap_open(PublicationRelationId, RowExclusiveLock);
@ -719,8 +720,8 @@ AlterPublicationOwner(const char *name, Oid newOwnerId)
void void
AlterPublicationOwner_oid(Oid subid, Oid newOwnerId) AlterPublicationOwner_oid(Oid subid, Oid newOwnerId)
{ {
HeapTuple tup; HeapTuple tup;
Relation rel; Relation rel;
rel = heap_open(PublicationRelationId, RowExclusiveLock); rel = heap_open(PublicationRelationId, RowExclusiveLock);

@ -100,10 +100,10 @@ static Form_pg_sequence_data read_seq_tuple(Relation rel,
Buffer *buf, HeapTuple seqdatatuple); Buffer *buf, HeapTuple seqdatatuple);
static LOCKMODE alter_sequence_get_lock_level(List *options); static LOCKMODE alter_sequence_get_lock_level(List *options);
static void init_params(ParseState *pstate, List *options, bool for_identity, static void init_params(ParseState *pstate, List *options, bool for_identity,
bool isInit, bool isInit,
Form_pg_sequence seqform, Form_pg_sequence seqform,
bool *changed_seqform, bool *changed_seqform,
Form_pg_sequence_data seqdataform, List **owned_by); Form_pg_sequence_data seqdataform, List **owned_by);
static void do_setval(Oid relid, int64 next, bool iscalled); static void do_setval(Oid relid, int64 next, bool iscalled);
static void process_owned_by(Relation seqrel, List *owned_by, bool for_identity); static void process_owned_by(Relation seqrel, List *owned_by, bool for_identity);
@ -117,7 +117,7 @@ DefineSequence(ParseState *pstate, CreateSeqStmt *seq)
{ {
FormData_pg_sequence seqform; FormData_pg_sequence seqform;
FormData_pg_sequence_data seqdataform; FormData_pg_sequence_data seqdataform;
bool changed_seqform = false; /* not used here */ bool changed_seqform = false; /* not used here */
List *owned_by; List *owned_by;
CreateStmt *stmt = makeNode(CreateStmt); CreateStmt *stmt = makeNode(CreateStmt);
Oid seqoid; Oid seqoid;
@ -703,9 +703,9 @@ nextval_internal(Oid relid, bool check_permissions)
snprintf(buf, sizeof(buf), INT64_FORMAT, maxv); snprintf(buf, sizeof(buf), INT64_FORMAT, maxv);
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SEQUENCE_GENERATOR_LIMIT_EXCEEDED), (errcode(ERRCODE_SEQUENCE_GENERATOR_LIMIT_EXCEEDED),
errmsg("nextval: reached maximum value of sequence \"%s\" (%s)", errmsg("nextval: reached maximum value of sequence \"%s\" (%s)",
RelationGetRelationName(seqrel), buf))); RelationGetRelationName(seqrel), buf)));
} }
next = minv; next = minv;
} }
@ -726,9 +726,9 @@ nextval_internal(Oid relid, bool check_permissions)
snprintf(buf, sizeof(buf), INT64_FORMAT, minv); snprintf(buf, sizeof(buf), INT64_FORMAT, minv);
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SEQUENCE_GENERATOR_LIMIT_EXCEEDED), (errcode(ERRCODE_SEQUENCE_GENERATOR_LIMIT_EXCEEDED),
errmsg("nextval: reached minimum value of sequence \"%s\" (%s)", errmsg("nextval: reached minimum value of sequence \"%s\" (%s)",
RelationGetRelationName(seqrel), buf))); RelationGetRelationName(seqrel), buf)));
} }
next = maxv; next = maxv;
} }
@ -1390,7 +1390,7 @@ init_params(ParseState *pstate, List *options, bool for_identity,
/* AS type */ /* AS type */
if (as_type != NULL) if (as_type != NULL)
{ {
Oid newtypid = typenameTypeId(pstate, defGetTypeName(as_type)); Oid newtypid = typenameTypeId(pstate, defGetTypeName(as_type));
if (newtypid != INT2OID && if (newtypid != INT2OID &&
newtypid != INT4OID && newtypid != INT4OID &&
@ -1399,7 +1399,7 @@ init_params(ParseState *pstate, List *options, bool for_identity,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
for_identity for_identity
? errmsg("identity column type must be smallint, integer, or bigint") ? errmsg("identity column type must be smallint, integer, or bigint")
: errmsg("sequence type must be smallint, integer, or bigint"))); : errmsg("sequence type must be smallint, integer, or bigint")));
if (!isInit) if (!isInit)
{ {
@ -1411,11 +1411,11 @@ init_params(ParseState *pstate, List *options, bool for_identity,
*/ */
if ((seqform->seqtypid == INT2OID && seqform->seqmax == PG_INT16_MAX) || if ((seqform->seqtypid == INT2OID && seqform->seqmax == PG_INT16_MAX) ||
(seqform->seqtypid == INT4OID && seqform->seqmax == PG_INT32_MAX) || (seqform->seqtypid == INT4OID && seqform->seqmax == PG_INT32_MAX) ||
(seqform->seqtypid == INT8OID && seqform->seqmax == PG_INT64_MAX)) (seqform->seqtypid == INT8OID && seqform->seqmax == PG_INT64_MAX))
reset_max_value = true; reset_max_value = true;
if ((seqform->seqtypid == INT2OID && seqform->seqmin == PG_INT16_MIN) || if ((seqform->seqtypid == INT2OID && seqform->seqmin == PG_INT16_MIN) ||
(seqform->seqtypid == INT4OID && seqform->seqmin == PG_INT32_MIN) || (seqform->seqtypid == INT4OID && seqform->seqmin == PG_INT32_MIN) ||
(seqform->seqtypid == INT8OID && seqform->seqmin == PG_INT64_MIN)) (seqform->seqtypid == INT8OID && seqform->seqmin == PG_INT64_MIN))
reset_min_value = true; reset_min_value = true;
} }
@ -1479,7 +1479,7 @@ init_params(ParseState *pstate, List *options, bool for_identity,
seqform->seqmax = PG_INT64_MAX; seqform->seqmax = PG_INT64_MAX;
} }
else else
seqform->seqmax = -1; /* descending seq */ seqform->seqmax = -1; /* descending seq */
*changed_seqform = true; *changed_seqform = true;
seqdataform->log_cnt = 0; seqdataform->log_cnt = 0;
} }
@ -1494,8 +1494,8 @@ init_params(ParseState *pstate, List *options, bool for_identity,
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("MAXVALUE (%s) is out of range for sequence data type %s", errmsg("MAXVALUE (%s) is out of range for sequence data type %s",
bufx, format_type_be(seqform->seqtypid)))); bufx, format_type_be(seqform->seqtypid))));
} }
/* MINVALUE (null arg means NO MINVALUE) */ /* MINVALUE (null arg means NO MINVALUE) */
@ -1518,7 +1518,7 @@ init_params(ParseState *pstate, List *options, bool for_identity,
seqform->seqmin = PG_INT64_MIN; seqform->seqmin = PG_INT64_MIN;
} }
else else
seqform->seqmin = 1; /* ascending seq */ seqform->seqmin = 1; /* ascending seq */
*changed_seqform = true; *changed_seqform = true;
seqdataform->log_cnt = 0; seqdataform->log_cnt = 0;
} }
@ -1533,8 +1533,8 @@ init_params(ParseState *pstate, List *options, bool for_identity,
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("MINVALUE (%s) is out of range for sequence data type %s", errmsg("MINVALUE (%s) is out of range for sequence data type %s",
bufm, format_type_be(seqform->seqtypid)))); bufm, format_type_be(seqform->seqtypid))));
} }
/* crosscheck min/max */ /* crosscheck min/max */
@ -1560,9 +1560,9 @@ init_params(ParseState *pstate, List *options, bool for_identity,
else if (isInit) else if (isInit)
{ {
if (seqform->seqincrement > 0) if (seqform->seqincrement > 0)
seqform->seqstart = seqform->seqmin; /* ascending seq */ seqform->seqstart = seqform->seqmin; /* ascending seq */
else else
seqform->seqstart = seqform->seqmax; /* descending seq */ seqform->seqstart = seqform->seqmax; /* descending seq */
*changed_seqform = true; *changed_seqform = true;
} }

@ -90,8 +90,8 @@ CreateStatistics(CreateStatsStmt *stmt)
{ {
ereport(NOTICE, ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_OBJECT), (errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("statistics object \"%s\" already exists, skipping", errmsg("statistics object \"%s\" already exists, skipping",
namestr))); namestr)));
return InvalidObjectAddress; return InvalidObjectAddress;
} }

@ -94,7 +94,7 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
*synchronous_commit = NULL; *synchronous_commit = NULL;
/* Parse options */ /* Parse options */
foreach (lc, options) foreach(lc, options)
{ {
DefElem *defel = (DefElem *) lfirst(lc); DefElem *defel = (DefElem *) lfirst(lc);
@ -200,8 +200,8 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
} }
/* /*
* Do additional checking for disallowed combination when * Do additional checking for disallowed combination when slot_name = NONE
* slot_name = NONE was used. * was used.
*/ */
if (slot_name && *slot_name_given && !*slot_name) if (slot_name && *slot_name_given && !*slot_name)
{ {
@ -367,7 +367,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
values[Anum_pg_subscription_subsynccommit - 1] = values[Anum_pg_subscription_subsynccommit - 1] =
CStringGetTextDatum(synchronous_commit); CStringGetTextDatum(synchronous_commit);
values[Anum_pg_subscription_subpublications - 1] = values[Anum_pg_subscription_subpublications - 1] =
publicationListToArray(publications); publicationListToArray(publications);
tup = heap_form_tuple(RelationGetDescr(rel), values, nulls); tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
@ -386,12 +386,12 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
*/ */
if (connect) if (connect)
{ {
XLogRecPtr lsn; XLogRecPtr lsn;
char *err; char *err;
WalReceiverConn *wrconn; WalReceiverConn *wrconn;
List *tables; List *tables;
ListCell *lc; ListCell *lc;
char table_state; char table_state;
/* Try to connect to the publisher. */ /* Try to connect to the publisher. */
wrconn = walrcv_connect(conninfo, true, stmt->subname, &err); wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
@ -412,7 +412,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
* info. * info.
*/ */
tables = fetch_table_list(wrconn, publications); tables = fetch_table_list(wrconn, publications);
foreach (lc, tables) foreach(lc, tables)
{ {
RangeVar *rv = (RangeVar *) lfirst(lc); RangeVar *rv = (RangeVar *) lfirst(lc);
Oid relid; Oid relid;
@ -431,9 +431,9 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
(errmsg("synchronized table states"))); (errmsg("synchronized table states")));
/* /*
* If requested, create permanent slot for the subscription. * If requested, create permanent slot for the subscription. We
* We won't use the initial snapshot for anything, so no need * won't use the initial snapshot for anything, so no need to
* to export it. * export it.
*/ */
if (create_slot) if (create_slot)
{ {
@ -442,8 +442,8 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
walrcv_create_slot(wrconn, slotname, false, walrcv_create_slot(wrconn, slotname, false,
CRS_NOEXPORT_SNAPSHOT, &lsn); CRS_NOEXPORT_SNAPSHOT, &lsn);
ereport(NOTICE, ereport(NOTICE,
(errmsg("created replication slot \"%s\" on publisher", (errmsg("created replication slot \"%s\" on publisher",
slotname))); slotname)));
} }
} }
PG_CATCH(); PG_CATCH();
@ -478,7 +478,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
static void static void
AlterSubscription_refresh(Subscription *sub, bool copy_data) AlterSubscription_refresh(Subscription *sub, bool copy_data)
{ {
char *err; char *err;
List *pubrel_names; List *pubrel_names;
List *subrel_states; List *subrel_states;
Oid *subrel_local_oids; Oid *subrel_local_oids;
@ -505,31 +505,31 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data)
subrel_states = GetSubscriptionRelations(sub->oid); subrel_states = GetSubscriptionRelations(sub->oid);
/* /*
* Build qsorted array of local table oids for faster lookup. * Build qsorted array of local table oids for faster lookup. This can
* This can potentially contain all tables in the database so * potentially contain all tables in the database so speed of lookup is
* speed of lookup is important. * important.
*/ */
subrel_local_oids = palloc(list_length(subrel_states) * sizeof(Oid)); subrel_local_oids = palloc(list_length(subrel_states) * sizeof(Oid));
off = 0; off = 0;
foreach(lc, subrel_states) foreach(lc, subrel_states)
{ {
SubscriptionRelState *relstate = (SubscriptionRelState *) lfirst(lc); SubscriptionRelState *relstate = (SubscriptionRelState *) lfirst(lc);
subrel_local_oids[off++] = relstate->relid; subrel_local_oids[off++] = relstate->relid;
} }
qsort(subrel_local_oids, list_length(subrel_states), qsort(subrel_local_oids, list_length(subrel_states),
sizeof(Oid), oid_cmp); sizeof(Oid), oid_cmp);
/* /*
* Walk over the remote tables and try to match them to locally * Walk over the remote tables and try to match them to locally known
* known tables. If the table is not known locally create a new state * tables. If the table is not known locally create a new state for it.
* for it.
* *
* Also builds array of local oids of remote tables for the next step. * Also builds array of local oids of remote tables for the next step.
*/ */
off = 0; off = 0;
pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid)); pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
foreach (lc, pubrel_names) foreach(lc, pubrel_names)
{ {
RangeVar *rv = (RangeVar *) lfirst(lc); RangeVar *rv = (RangeVar *) lfirst(lc);
Oid relid; Oid relid;
@ -546,7 +546,7 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data)
list_length(subrel_states), sizeof(Oid), oid_cmp)) list_length(subrel_states), sizeof(Oid), oid_cmp))
{ {
SetSubscriptionRelState(sub->oid, relid, SetSubscriptionRelState(sub->oid, relid,
copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY, copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
InvalidXLogRecPtr); InvalidXLogRecPtr);
ereport(NOTICE, ereport(NOTICE,
(errmsg("added subscription for table %s.%s", (errmsg("added subscription for table %s.%s",
@ -556,20 +556,20 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data)
} }
/* /*
* Next remove state for tables we should not care about anymore using * Next remove state for tables we should not care about anymore using the
* the data we collected above * data we collected above
*/ */
qsort(pubrel_local_oids, list_length(pubrel_names), qsort(pubrel_local_oids, list_length(pubrel_names),
sizeof(Oid), oid_cmp); sizeof(Oid), oid_cmp);
for (off = 0; off < list_length(subrel_states); off++) for (off = 0; off < list_length(subrel_states); off++)
{ {
Oid relid = subrel_local_oids[off]; Oid relid = subrel_local_oids[off];
if (!bsearch(&relid, pubrel_local_oids, if (!bsearch(&relid, pubrel_local_oids,
list_length(pubrel_names), sizeof(Oid), oid_cmp)) list_length(pubrel_names), sizeof(Oid), oid_cmp))
{ {
char *namespace; char *namespace;
RemoveSubscriptionRel(sub->oid, relid); RemoveSubscriptionRel(sub->oid, relid);
@ -596,7 +596,7 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
HeapTuple tup; HeapTuple tup;
Oid subid; Oid subid;
bool update_tuple = false; bool update_tuple = false;
Subscription *sub; Subscription *sub;
rel = heap_open(SubscriptionRelationId, RowExclusiveLock); rel = heap_open(SubscriptionRelationId, RowExclusiveLock);
@ -644,7 +644,7 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
if (slotname) if (slotname)
values[Anum_pg_subscription_subslotname - 1] = values[Anum_pg_subscription_subslotname - 1] =
DirectFunctionCall1(namein, CStringGetDatum(slotname)); DirectFunctionCall1(namein, CStringGetDatum(slotname));
else else
nulls[Anum_pg_subscription_subslotname - 1] = true; nulls[Anum_pg_subscription_subslotname - 1] = true;
replaces[Anum_pg_subscription_subslotname - 1] = true; replaces[Anum_pg_subscription_subslotname - 1] = true;
@ -663,8 +663,8 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
case ALTER_SUBSCRIPTION_ENABLED: case ALTER_SUBSCRIPTION_ENABLED:
{ {
bool enabled, bool enabled,
enabled_given; enabled_given;
parse_subscription_options(stmt->options, NULL, parse_subscription_options(stmt->options, NULL,
&enabled_given, &enabled, NULL, &enabled_given, &enabled, NULL,
@ -702,14 +702,14 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
case ALTER_SUBSCRIPTION_PUBLICATION: case ALTER_SUBSCRIPTION_PUBLICATION:
case ALTER_SUBSCRIPTION_PUBLICATION_REFRESH: case ALTER_SUBSCRIPTION_PUBLICATION_REFRESH:
{ {
bool copy_data; bool copy_data;
parse_subscription_options(stmt->options, NULL, NULL, NULL, parse_subscription_options(stmt->options, NULL, NULL, NULL,
NULL, NULL, NULL, &copy_data, NULL, NULL, NULL, &copy_data,
NULL); NULL);
values[Anum_pg_subscription_subpublications - 1] = values[Anum_pg_subscription_subpublications - 1] =
publicationListToArray(stmt->publication); publicationListToArray(stmt->publication);
replaces[Anum_pg_subscription_subpublications - 1] = true; replaces[Anum_pg_subscription_subpublications - 1] = true;
update_tuple = true; update_tuple = true;
@ -733,7 +733,7 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
case ALTER_SUBSCRIPTION_REFRESH: case ALTER_SUBSCRIPTION_REFRESH:
{ {
bool copy_data; bool copy_data;
if (!sub->enabled) if (!sub->enabled)
ereport(ERROR, ereport(ERROR,
@ -791,14 +791,13 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
char *slotname; char *slotname;
char originname[NAMEDATALEN]; char originname[NAMEDATALEN];
char *err = NULL; char *err = NULL;
RepOriginId originid; RepOriginId originid;
WalReceiverConn *wrconn = NULL; WalReceiverConn *wrconn = NULL;
StringInfoData cmd; StringInfoData cmd;
/* /*
* Lock pg_subscription with AccessExclusiveLock to ensure * Lock pg_subscription with AccessExclusiveLock to ensure that the
* that the launcher doesn't restart new worker during dropping * launcher doesn't restart new worker during dropping the subscription
* the subscription
*/ */
rel = heap_open(SubscriptionRelationId, AccessExclusiveLock); rel = heap_open(SubscriptionRelationId, AccessExclusiveLock);
@ -833,8 +832,8 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
InvokeObjectDropHook(SubscriptionRelationId, subid, 0); InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
/* /*
* Lock the subscription so nobody else can do anything with it * Lock the subscription so nobody else can do anything with it (including
* (including the replication workers). * the replication workers).
*/ */
LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock); LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
@ -895,7 +894,10 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
if (originid != InvalidRepOriginId) if (originid != InvalidRepOriginId)
replorigin_drop(originid); replorigin_drop(originid);
/* If there is no slot associated with the subscription, we can finish here. */ /*
* If there is no slot associated with the subscription, we can finish
* here.
*/
if (!slotname) if (!slotname)
{ {
heap_close(rel, NoLock); heap_close(rel, NoLock);
@ -903,8 +905,8 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
} }
/* /*
* Otherwise drop the replication slot at the publisher node using * Otherwise drop the replication slot at the publisher node using the
* the replication connection. * replication connection.
*/ */
load_file("libpqwalreceiver", false); load_file("libpqwalreceiver", false);
@ -922,14 +924,15 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
PG_TRY(); PG_TRY();
{ {
WalRcvExecResult *res; WalRcvExecResult *res;
res = walrcv_exec(wrconn, cmd.data, 0, NULL); res = walrcv_exec(wrconn, cmd.data, 0, NULL);
if (res->status != WALRCV_OK_COMMAND) if (res->status != WALRCV_OK_COMMAND)
ereport(ERROR, ereport(ERROR,
(errmsg("could not drop the replication slot \"%s\" on publisher", (errmsg("could not drop the replication slot \"%s\" on publisher",
slotname), slotname),
errdetail("The error was: %s", res->err))); errdetail("The error was: %s", res->err)));
else else
ereport(NOTICE, ereport(NOTICE,
(errmsg("dropped replication slot \"%s\" on publisher", (errmsg("dropped replication slot \"%s\" on publisher",
@ -973,9 +976,9 @@ AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
if (!superuser_arg(newOwnerId)) if (!superuser_arg(newOwnerId))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied to change owner of subscription \"%s\"", errmsg("permission denied to change owner of subscription \"%s\"",
NameStr(form->subname)), NameStr(form->subname)),
errhint("The owner of a subscription must be a superuser."))); errhint("The owner of a subscription must be a superuser.")));
form->subowner = newOwnerId; form->subowner = newOwnerId;
CatalogTupleUpdate(rel, &tup->t_self, tup); CatalogTupleUpdate(rel, &tup->t_self, tup);
@ -1055,24 +1058,24 @@ AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
static List * static List *
fetch_table_list(WalReceiverConn *wrconn, List *publications) fetch_table_list(WalReceiverConn *wrconn, List *publications)
{ {
WalRcvExecResult *res; WalRcvExecResult *res;
StringInfoData cmd; StringInfoData cmd;
TupleTableSlot *slot; TupleTableSlot *slot;
Oid tableRow[2] = {TEXTOID, TEXTOID}; Oid tableRow[2] = {TEXTOID, TEXTOID};
ListCell *lc; ListCell *lc;
bool first; bool first;
List *tablelist = NIL; List *tablelist = NIL;
Assert(list_length(publications) > 0); Assert(list_length(publications) > 0);
initStringInfo(&cmd); initStringInfo(&cmd);
appendStringInfo(&cmd, "SELECT DISTINCT t.schemaname, t.tablename\n" appendStringInfo(&cmd, "SELECT DISTINCT t.schemaname, t.tablename\n"
" FROM pg_catalog.pg_publication_tables t\n" " FROM pg_catalog.pg_publication_tables t\n"
" WHERE t.pubname IN ("); " WHERE t.pubname IN (");
first = true; first = true;
foreach (lc, publications) foreach(lc, publications)
{ {
char *pubname = strVal(lfirst(lc)); char *pubname = strVal(lfirst(lc));
if (first) if (first)
first = false; first = false;

@ -363,9 +363,9 @@ static ObjectAddress ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName, static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
Node *newDefault, LOCKMODE lockmode); Node *newDefault, LOCKMODE lockmode);
static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName, static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName,
Node *def, LOCKMODE lockmode); Node *def, LOCKMODE lockmode);
static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName, static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName,
Node *def, LOCKMODE lockmode); Node *def, LOCKMODE lockmode);
static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode); static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
static void ATPrepSetStatistics(Relation rel, const char *colName, static void ATPrepSetStatistics(Relation rel, const char *colName,
Node *newValue, LOCKMODE lockmode); Node *newValue, LOCKMODE lockmode);
@ -643,8 +643,8 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
descriptor->tdhasoid = (localHasOids || parentOidCount > 0); descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
/* /*
* If a partitioned table doesn't have the system OID column, then none * If a partitioned table doesn't have the system OID column, then none of
* of its partitions should have it. * its partitions should have it.
*/ */
if (stmt->partbound && parentOidCount == 0 && localHasOids) if (stmt->partbound && parentOidCount == 0 && localHasOids)
ereport(ERROR, ereport(ERROR,
@ -1112,9 +1112,9 @@ RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
} }
/* /*
* Similarly, if we previously locked some other partition's heap, and * Similarly, if we previously locked some other partition's heap, and the
* the name we're looking up no longer refers to that relation, release * name we're looking up no longer refers to that relation, release the
* the now-useless lock. * now-useless lock.
*/ */
if (relOid != oldRelOid && OidIsValid(state->partParentOid)) if (relOid != oldRelOid && OidIsValid(state->partParentOid))
{ {
@ -2219,8 +2219,8 @@ MergeAttributes(List *schema, List *supers, char relpersistence,
else else
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_COLUMN), (errcode(ERRCODE_DUPLICATE_COLUMN),
errmsg("column \"%s\" specified more than once", errmsg("column \"%s\" specified more than once",
coldef->colname))); coldef->colname)));
} }
prev = rest; prev = rest;
rest = next; rest = next;
@ -4541,7 +4541,7 @@ ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate, values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
econtext, econtext,
&isnull[ex->attnum - 1]); &isnull[ex->attnum - 1]);
} }
/* /*
@ -5589,12 +5589,12 @@ static void
ATPrepDropNotNull(Relation rel, bool recurse, bool recursing) ATPrepDropNotNull(Relation rel, bool recurse, bool recursing)
{ {
/* /*
* If the parent is a partitioned table, like check constraints, we do * If the parent is a partitioned table, like check constraints, we do not
* not support removing the NOT NULL while partitions exist. * support removing the NOT NULL while partitions exist.
*/ */
if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{ {
PartitionDesc partdesc = RelationGetPartitionDesc(rel); PartitionDesc partdesc = RelationGetPartitionDesc(rel);
Assert(partdesc != NULL); Assert(partdesc != NULL);
if (partdesc->nparts > 0 && !recurse && !recursing) if (partdesc->nparts > 0 && !recurse && !recursing)
@ -5639,8 +5639,8 @@ ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode)
if (get_attidentity(RelationGetRelid(rel), attnum)) if (get_attidentity(RelationGetRelid(rel), attnum))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("column \"%s\" of relation \"%s\" is an identity column", errmsg("column \"%s\" of relation \"%s\" is an identity column",
colName, RelationGetRelationName(rel)))); colName, RelationGetRelationName(rel))));
/* /*
* Check that the attribute is not in a primary key * Check that the attribute is not in a primary key
@ -5768,7 +5768,7 @@ ATPrepSetNotNull(Relation rel, bool recurse, bool recursing)
*/ */
if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{ {
PartitionDesc partdesc = RelationGetPartitionDesc(rel); PartitionDesc partdesc = RelationGetPartitionDesc(rel);
if (partdesc && partdesc->nparts > 0 && !recurse && !recursing) if (partdesc && partdesc->nparts > 0 && !recurse && !recursing)
ereport(ERROR, ereport(ERROR,
@ -5867,8 +5867,8 @@ ATExecColumnDefault(Relation rel, const char *colName,
if (get_attidentity(RelationGetRelid(rel), attnum)) if (get_attidentity(RelationGetRelid(rel), attnum))
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR), (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("column \"%s\" of relation \"%s\" is an identity column", errmsg("column \"%s\" of relation \"%s\" is an identity column",
colName, RelationGetRelationName(rel)), colName, RelationGetRelationName(rel)),
newDefault ? 0 : errhint("Use ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY instead."))); newDefault ? 0 : errhint("Use ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY instead.")));
/* /*
@ -5959,8 +5959,8 @@ ATExecAddIdentity(Relation rel, const char *colName,
if (attTup->atthasdef) if (attTup->atthasdef)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("column \"%s\" of relation \"%s\" already has a default value", errmsg("column \"%s\" of relation \"%s\" already has a default value",
colName, RelationGetRelationName(rel)))); colName, RelationGetRelationName(rel))));
attTup->attidentity = cdef->identity; attTup->attidentity = cdef->identity;
CatalogTupleUpdate(attrelation, &tuple->t_self, tuple); CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
@ -5986,7 +5986,7 @@ static ObjectAddress
ATExecSetIdentity(Relation rel, const char *colName, Node *def, LOCKMODE lockmode) ATExecSetIdentity(Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
{ {
ListCell *option; ListCell *option;
DefElem *generatedEl = NULL; DefElem *generatedEl = NULL;
HeapTuple tuple; HeapTuple tuple;
Form_pg_attribute attTup; Form_pg_attribute attTup;
AttrNumber attnum; AttrNumber attnum;
@ -5995,7 +5995,7 @@ ATExecSetIdentity(Relation rel, const char *colName, Node *def, LOCKMODE lockmod
foreach(option, castNode(List, def)) foreach(option, castNode(List, def))
{ {
DefElem *defel = lfirst_node(DefElem, option); DefElem *defel = lfirst_node(DefElem, option);
if (strcmp(defel->defname, "generated") == 0) if (strcmp(defel->defname, "generated") == 0)
{ {
@ -6036,8 +6036,8 @@ ATExecSetIdentity(Relation rel, const char *colName, Node *def, LOCKMODE lockmod
if (!attTup->attidentity) if (!attTup->attidentity)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("column \"%s\" of relation \"%s\" is not an identity column", errmsg("column \"%s\" of relation \"%s\" is not an identity column",
colName, RelationGetRelationName(rel)))); colName, RelationGetRelationName(rel))));
if (generatedEl) if (generatedEl)
{ {
@ -11137,7 +11137,7 @@ CreateInheritance(Relation child_rel, Relation parent_rel)
inhseqno + 1, inhseqno + 1,
catalogRelation, catalogRelation,
parent_rel->rd_rel->relkind == parent_rel->rd_rel->relkind ==
RELKIND_PARTITIONED_TABLE); RELKIND_PARTITIONED_TABLE);
/* Now we're done with pg_inherits */ /* Now we're done with pg_inherits */
heap_close(catalogRelation, RowExclusiveLock); heap_close(catalogRelation, RowExclusiveLock);

@ -340,7 +340,7 @@ CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
foreach(lc, varList) foreach(lc, varList)
{ {
TriggerTransition *tt = lfirst_node(TriggerTransition, lc); TriggerTransition *tt = lfirst_node(TriggerTransition, lc);
if (!(tt->isTable)) if (!(tt->isTable))
ereport(ERROR, ereport(ERROR,
@ -359,21 +359,21 @@ CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
(errcode(ERRCODE_WRONG_OBJECT_TYPE), (errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is a partitioned table", errmsg("\"%s\" is a partitioned table",
RelationGetRelationName(rel)), RelationGetRelationName(rel)),
errdetail("Triggers on partitioned tables cannot have transition tables."))); errdetail("Triggers on partitioned tables cannot have transition tables.")));
if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE) if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE), (errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is a foreign table", errmsg("\"%s\" is a foreign table",
RelationGetRelationName(rel)), RelationGetRelationName(rel)),
errdetail("Triggers on foreign tables cannot have transition tables."))); errdetail("Triggers on foreign tables cannot have transition tables.")));
if (rel->rd_rel->relkind == RELKIND_VIEW) if (rel->rd_rel->relkind == RELKIND_VIEW)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE), (errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is a view", errmsg("\"%s\" is a view",
RelationGetRelationName(rel)), RelationGetRelationName(rel)),
errdetail("Triggers on views cannot have transition tables."))); errdetail("Triggers on views cannot have transition tables.")));
if (stmt->timing != TRIGGER_TYPE_AFTER) if (stmt->timing != TRIGGER_TYPE_AFTER)
ereport(ERROR, ereport(ERROR,
@ -396,7 +396,7 @@ CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
if (newtablename != NULL) if (newtablename != NULL)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("NEW TABLE cannot be specified multiple times"))); errmsg("NEW TABLE cannot be specified multiple times")));
newtablename = tt->name; newtablename = tt->name;
} }
@ -411,7 +411,7 @@ CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
if (oldtablename != NULL) if (oldtablename != NULL)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("OLD TABLE cannot be specified multiple times"))); errmsg("OLD TABLE cannot be specified multiple times")));
oldtablename = tt->name; oldtablename = tt->name;
} }
@ -421,7 +421,7 @@ CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
strcmp(newtablename, oldtablename) == 0) strcmp(newtablename, oldtablename) == 0)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("OLD TABLE name and NEW TABLE name cannot be the same"))); errmsg("OLD TABLE name and NEW TABLE name cannot be the same")));
} }
/* /*
@ -782,12 +782,12 @@ CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
if (oldtablename) if (oldtablename)
values[Anum_pg_trigger_tgoldtable - 1] = DirectFunctionCall1(namein, values[Anum_pg_trigger_tgoldtable - 1] = DirectFunctionCall1(namein,
CStringGetDatum(oldtablename)); CStringGetDatum(oldtablename));
else else
nulls[Anum_pg_trigger_tgoldtable - 1] = true; nulls[Anum_pg_trigger_tgoldtable - 1] = true;
if (newtablename) if (newtablename)
values[Anum_pg_trigger_tgnewtable - 1] = DirectFunctionCall1(namein, values[Anum_pg_trigger_tgnewtable - 1] = DirectFunctionCall1(namein,
CStringGetDatum(newtablename)); CStringGetDatum(newtablename));
else else
nulls[Anum_pg_trigger_tgnewtable - 1] = true; nulls[Anum_pg_trigger_tgnewtable - 1] = true;
@ -3412,7 +3412,8 @@ typedef struct AfterTriggersData
AfterTriggerEventList events; /* deferred-event list */ AfterTriggerEventList events; /* deferred-event list */
int query_depth; /* current query list index */ int query_depth; /* current query list index */
AfterTriggerEventList *query_stack; /* events pending from each query */ AfterTriggerEventList *query_stack; /* events pending from each query */
Tuplestorestate **fdw_tuplestores; /* foreign tuples for one row from each query */ Tuplestorestate **fdw_tuplestores; /* foreign tuples for one row from
* each query */
Tuplestorestate **old_tuplestores; /* all old tuples from each query */ Tuplestorestate **old_tuplestores; /* all old tuples from each query */
Tuplestorestate **new_tuplestores; /* all new tuples from each query */ Tuplestorestate **new_tuplestores; /* all new tuples from each query */
int maxquerydepth; /* allocated len of above array */ int maxquerydepth; /* allocated len of above array */
@ -3778,8 +3779,8 @@ AfterTriggerExecute(AfterTriggerEvent event,
case AFTER_TRIGGER_FDW_FETCH: case AFTER_TRIGGER_FDW_FETCH:
{ {
Tuplestorestate *fdw_tuplestore = Tuplestorestate *fdw_tuplestore =
GetTriggerTransitionTuplestore GetTriggerTransitionTuplestore
(afterTriggers.fdw_tuplestores); (afterTriggers.fdw_tuplestores);
if (!tuplestore_gettupleslot(fdw_tuplestore, true, false, if (!tuplestore_gettupleslot(fdw_tuplestore, true, false,
trig_tuple_slot1)) trig_tuple_slot1))
@ -5130,7 +5131,7 @@ AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
Assert(oldtup != NULL); Assert(oldtup != NULL);
old_tuplestore = old_tuplestore =
GetTriggerTransitionTuplestore GetTriggerTransitionTuplestore
(afterTriggers.old_tuplestores); (afterTriggers.old_tuplestores);
tuplestore_puttuple(old_tuplestore, oldtup); tuplestore_puttuple(old_tuplestore, oldtup);
} }
if ((event == TRIGGER_EVENT_INSERT && if ((event == TRIGGER_EVENT_INSERT &&
@ -5143,14 +5144,14 @@ AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
Assert(newtup != NULL); Assert(newtup != NULL);
new_tuplestore = new_tuplestore =
GetTriggerTransitionTuplestore GetTriggerTransitionTuplestore
(afterTriggers.new_tuplestores); (afterTriggers.new_tuplestores);
tuplestore_puttuple(new_tuplestore, newtup); tuplestore_puttuple(new_tuplestore, newtup);
} }
/* If transition tables are the only reason we're here, return. */ /* If transition tables are the only reason we're here, return. */
if ((event == TRIGGER_EVENT_DELETE && !trigdesc->trig_delete_after_row) || if ((event == TRIGGER_EVENT_DELETE && !trigdesc->trig_delete_after_row) ||
(event == TRIGGER_EVENT_INSERT && !trigdesc->trig_insert_after_row) || (event == TRIGGER_EVENT_INSERT && !trigdesc->trig_insert_after_row) ||
(event == TRIGGER_EVENT_UPDATE && !trigdesc->trig_update_after_row)) (event == TRIGGER_EVENT_UPDATE && !trigdesc->trig_update_after_row))
return; return;
} }
@ -5253,7 +5254,7 @@ AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
{ {
fdw_tuplestore = fdw_tuplestore =
GetTriggerTransitionTuplestore GetTriggerTransitionTuplestore
(afterTriggers.fdw_tuplestores); (afterTriggers.fdw_tuplestores);
new_event.ate_flags = AFTER_TRIGGER_FDW_FETCH; new_event.ate_flags = AFTER_TRIGGER_FDW_FETCH;
} }
else else

@ -1685,7 +1685,7 @@ deserialize_deflist(Datum txt)
*wsptr++ = '\0'; *wsptr++ = '\0';
result = lappend(result, result = lappend(result,
makeDefElem(pstrdup(workspace), makeDefElem(pstrdup(workspace),
(Node *) makeString(pstrdup(startvalue)), -1)); (Node *) makeString(pstrdup(startvalue)), -1));
state = CS_WAITKEY; state = CS_WAITKEY;
} }
} }
@ -1717,7 +1717,7 @@ deserialize_deflist(Datum txt)
*wsptr++ = '\0'; *wsptr++ = '\0';
result = lappend(result, result = lappend(result,
makeDefElem(pstrdup(workspace), makeDefElem(pstrdup(workspace),
(Node *) makeString(pstrdup(startvalue)), -1)); (Node *) makeString(pstrdup(startvalue)), -1));
state = CS_WAITKEY; state = CS_WAITKEY;
} }
} }
@ -1732,7 +1732,7 @@ deserialize_deflist(Datum txt)
*wsptr++ = '\0'; *wsptr++ = '\0';
result = lappend(result, result = lappend(result,
makeDefElem(pstrdup(workspace), makeDefElem(pstrdup(workspace),
(Node *) makeString(pstrdup(startvalue)), -1)); (Node *) makeString(pstrdup(startvalue)), -1));
state = CS_WAITKEY; state = CS_WAITKEY;
} }
else else
@ -1751,7 +1751,7 @@ deserialize_deflist(Datum txt)
*wsptr++ = '\0'; *wsptr++ = '\0';
result = lappend(result, result = lappend(result,
makeDefElem(pstrdup(workspace), makeDefElem(pstrdup(workspace),
(Node *) makeString(pstrdup(startvalue)), -1)); (Node *) makeString(pstrdup(startvalue)), -1));
} }
else if (state != CS_WAITKEY) else if (state != CS_WAITKEY)
ereport(ERROR, ereport(ERROR,

@ -1463,7 +1463,7 @@ AddRoleMems(const char *rolename, Oid roleid,
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_INVALID_GRANT_OPERATION), (errcode(ERRCODE_INVALID_GRANT_OPERATION),
(errmsg("role \"%s\" is a member of role \"%s\"", (errmsg("role \"%s\" is a member of role \"%s\"",
rolename, get_rolespec_name(memberRole))))); rolename, get_rolespec_name(memberRole)))));
/* /*
* Check if entry for this role/member already exists; if so, give * Check if entry for this role/member already exists; if so, give
@ -1478,7 +1478,7 @@ AddRoleMems(const char *rolename, Oid roleid,
{ {
ereport(NOTICE, ereport(NOTICE,
(errmsg("role \"%s\" is already a member of role \"%s\"", (errmsg("role \"%s\" is already a member of role \"%s\"",
get_rolespec_name(memberRole), rolename))); get_rolespec_name(memberRole), rolename)));
ReleaseSysCache(authmem_tuple); ReleaseSysCache(authmem_tuple);
continue; continue;
} }
@ -1587,7 +1587,7 @@ DelRoleMems(const char *rolename, Oid roleid,
{ {
ereport(WARNING, ereport(WARNING,
(errmsg("role \"%s\" is not a member of role \"%s\"", (errmsg("role \"%s\" is not a member of role \"%s\"",
get_rolespec_name(memberRole), rolename))); get_rolespec_name(memberRole), rolename)));
continue; continue;
} }

@ -1337,7 +1337,7 @@ lazy_scan_heap(Relation onerel, int options, LVRelStats *vacrelstats,
*/ */
initStringInfo(&buf); initStringInfo(&buf);
appendStringInfo(&buf, appendStringInfo(&buf,
_("%.0f dead row versions cannot be removed yet, oldest xmin: %u\n"), _("%.0f dead row versions cannot be removed yet, oldest xmin: %u\n"),
nkeep, OldestXmin); nkeep, OldestXmin);
appendStringInfo(&buf, _("There were %.0f unused item pointers.\n"), appendStringInfo(&buf, _("There were %.0f unused item pointers.\n"),
nunused); nunused);
@ -1912,8 +1912,8 @@ count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats)
/* If we haven't prefetched this lot yet, do so now. */ /* If we haven't prefetched this lot yet, do so now. */
if (prefetchedUntil > blkno) if (prefetchedUntil > blkno)
{ {
BlockNumber prefetchStart; BlockNumber prefetchStart;
BlockNumber pblkno; BlockNumber pblkno;
prefetchStart = blkno & ~(PREFETCH_SIZE - 1); prefetchStart = blkno & ~(PREFETCH_SIZE - 1);
for (pblkno = prefetchStart; pblkno <= blkno; pblkno++) for (pblkno = prefetchStart; pblkno <= blkno; pblkno++)

@ -469,11 +469,11 @@ DefineView(ViewStmt *stmt, const char *queryString,
if (stmt->withCheckOption == LOCAL_CHECK_OPTION) if (stmt->withCheckOption == LOCAL_CHECK_OPTION)
stmt->options = lappend(stmt->options, stmt->options = lappend(stmt->options,
makeDefElem("check_option", makeDefElem("check_option",
(Node *) makeString("local"), -1)); (Node *) makeString("local"), -1));
else if (stmt->withCheckOption == CASCADED_CHECK_OPTION) else if (stmt->withCheckOption == CASCADED_CHECK_OPTION)
stmt->options = lappend(stmt->options, stmt->options = lappend(stmt->options,
makeDefElem("check_option", makeDefElem("check_option",
(Node *) makeString("cascaded"), -1)); (Node *) makeString("cascaded"), -1));
/* /*
* Check that the view is auto-updatable if WITH CHECK OPTION was * Check that the view is auto-updatable if WITH CHECK OPTION was

@ -413,12 +413,13 @@ ExecSupportsMarkRestore(Path *pathnode)
return true; return true;
case T_CustomScan: case T_CustomScan:
{ {
CustomPath *customPath = castNode(CustomPath, pathnode); CustomPath *customPath = castNode(CustomPath, pathnode);
if (customPath->flags & CUSTOMPATH_SUPPORT_MARK_RESTORE)
return true; if (customPath->flags & CUSTOMPATH_SUPPORT_MARK_RESTORE)
return false; return true;
} return false;
}
case T_Result: case T_Result:
/* /*

@ -380,7 +380,7 @@ LookupTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot,
hashtable->in_hash_funcs = hashtable->tab_hash_funcs; hashtable->in_hash_funcs = hashtable->tab_hash_funcs;
hashtable->cur_eq_funcs = hashtable->tab_eq_funcs; hashtable->cur_eq_funcs = hashtable->tab_eq_funcs;
key = NULL; /* flag to reference inputslot */ key = NULL; /* flag to reference inputslot */
if (isnew) if (isnew)
{ {

@ -868,7 +868,7 @@ InitPlan(QueryDesc *queryDesc, int eflags)
estate->es_num_root_result_relations = 0; estate->es_num_root_result_relations = 0;
if (plannedstmt->nonleafResultRelations) if (plannedstmt->nonleafResultRelations)
{ {
int num_roots = list_length(plannedstmt->rootResultRelations); int num_roots = list_length(plannedstmt->rootResultRelations);
/* /*
* Firstly, build ResultRelInfos for all the partitioned table * Firstly, build ResultRelInfos for all the partitioned table
@ -876,7 +876,7 @@ InitPlan(QueryDesc *queryDesc, int eflags)
* triggers, if any. * triggers, if any.
*/ */
resultRelInfos = (ResultRelInfo *) resultRelInfos = (ResultRelInfo *)
palloc(num_roots * sizeof(ResultRelInfo)); palloc(num_roots * sizeof(ResultRelInfo));
resultRelInfo = resultRelInfos; resultRelInfo = resultRelInfos;
foreach(l, plannedstmt->rootResultRelations) foreach(l, plannedstmt->rootResultRelations)
{ {
@ -900,7 +900,7 @@ InitPlan(QueryDesc *queryDesc, int eflags)
/* Simply lock the rest of them. */ /* Simply lock the rest of them. */
foreach(l, plannedstmt->nonleafResultRelations) foreach(l, plannedstmt->nonleafResultRelations)
{ {
Index resultRelIndex = lfirst_int(l); Index resultRelIndex = lfirst_int(l);
/* We locked the roots above. */ /* We locked the roots above. */
if (!list_member_int(plannedstmt->rootResultRelations, if (!list_member_int(plannedstmt->rootResultRelations,
@ -1919,13 +1919,13 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
if (resultRelInfo->ri_PartitionRoot) if (resultRelInfo->ri_PartitionRoot)
{ {
HeapTuple tuple = ExecFetchSlotTuple(slot); HeapTuple tuple = ExecFetchSlotTuple(slot);
TupleConversionMap *map; TupleConversionMap *map;
rel = resultRelInfo->ri_PartitionRoot; rel = resultRelInfo->ri_PartitionRoot;
tupdesc = RelationGetDescr(rel); tupdesc = RelationGetDescr(rel);
/* a reverse map */ /* a reverse map */
map = convert_tuples_by_name(orig_tupdesc, tupdesc, map = convert_tuples_by_name(orig_tupdesc, tupdesc,
gettext_noop("could not convert row type")); gettext_noop("could not convert row type"));
if (map != NULL) if (map != NULL)
{ {
tuple = do_convert_tuple(tuple, map); tuple = do_convert_tuple(tuple, map);
@ -1966,13 +1966,13 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{ {
HeapTuple tuple = ExecFetchSlotTuple(slot); HeapTuple tuple = ExecFetchSlotTuple(slot);
TupleDesc old_tupdesc = RelationGetDescr(rel); TupleDesc old_tupdesc = RelationGetDescr(rel);
TupleConversionMap *map; TupleConversionMap *map;
rel = resultRelInfo->ri_PartitionRoot; rel = resultRelInfo->ri_PartitionRoot;
tupdesc = RelationGetDescr(rel); tupdesc = RelationGetDescr(rel);
/* a reverse map */ /* a reverse map */
map = convert_tuples_by_name(old_tupdesc, tupdesc, map = convert_tuples_by_name(old_tupdesc, tupdesc,
gettext_noop("could not convert row type")); gettext_noop("could not convert row type"));
if (map != NULL) if (map != NULL)
{ {
tuple = do_convert_tuple(tuple, map); tuple = do_convert_tuple(tuple, map);
@ -2008,13 +2008,13 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{ {
HeapTuple tuple = ExecFetchSlotTuple(slot); HeapTuple tuple = ExecFetchSlotTuple(slot);
TupleDesc old_tupdesc = RelationGetDescr(rel); TupleDesc old_tupdesc = RelationGetDescr(rel);
TupleConversionMap *map; TupleConversionMap *map;
rel = resultRelInfo->ri_PartitionRoot; rel = resultRelInfo->ri_PartitionRoot;
tupdesc = RelationGetDescr(rel); tupdesc = RelationGetDescr(rel);
/* a reverse map */ /* a reverse map */
map = convert_tuples_by_name(old_tupdesc, tupdesc, map = convert_tuples_by_name(old_tupdesc, tupdesc,
gettext_noop("could not convert row type")); gettext_noop("could not convert row type"));
if (map != NULL) if (map != NULL)
{ {
tuple = do_convert_tuple(tuple, map); tuple = do_convert_tuple(tuple, map);
@ -3340,7 +3340,7 @@ ExecFindPartition(ResultRelInfo *resultRelInfo, PartitionDispatch *pd,
(errcode(ERRCODE_CHECK_VIOLATION), (errcode(ERRCODE_CHECK_VIOLATION),
errmsg("no partition of relation \"%s\" found for row", errmsg("no partition of relation \"%s\" found for row",
RelationGetRelationName(failed_rel)), RelationGetRelationName(failed_rel)),
val_desc ? errdetail("Partition key of the failing row contains %s.", val_desc) : 0)); val_desc ? errdetail("Partition key of the failing row contains %s.", val_desc) : 0));
} }
return result; return result;
@ -3359,8 +3359,8 @@ ExecBuildSlotPartitionKeyDescription(Relation rel,
bool *isnull, bool *isnull,
int maxfieldlen) int maxfieldlen)
{ {
StringInfoData buf; StringInfoData buf;
PartitionKey key = RelationGetPartitionKey(rel); PartitionKey key = RelationGetPartitionKey(rel);
int partnatts = get_partition_natts(key); int partnatts = get_partition_natts(key);
int i; int i;
Oid relid = RelationGetRelid(rel); Oid relid = RelationGetRelid(rel);

@ -608,9 +608,9 @@ ExecParallelRetrieveInstrumentation(PlanState *planstate,
/* /*
* Also store the per-worker detail. * Also store the per-worker detail.
* *
* Worker instrumentation should be allocated in the same context as * Worker instrumentation should be allocated in the same context as the
* the regular instrumentation information, which is the per-query * regular instrumentation information, which is the per-query context.
* context. Switch into per-query memory context. * Switch into per-query memory context.
*/ */
oldcontext = MemoryContextSwitchTo(planstate->state->es_query_cxt); oldcontext = MemoryContextSwitchTo(planstate->state->es_query_cxt);
ibytes = mul_size(instrumentation->num_workers, sizeof(Instrumentation)); ibytes = mul_size(instrumentation->num_workers, sizeof(Instrumentation));

@ -259,7 +259,7 @@ ExecInitNode(Plan *node, EState *estate, int eflags)
case T_NamedTuplestoreScan: case T_NamedTuplestoreScan:
result = (PlanState *) ExecInitNamedTuplestoreScan((NamedTuplestoreScan *) node, result = (PlanState *) ExecInitNamedTuplestoreScan((NamedTuplestoreScan *) node,
estate, eflags); estate, eflags);
break; break;
case T_WorkTableScan: case T_WorkTableScan:

@ -116,15 +116,15 @@ RelationFindReplTupleByIndex(Relation rel, Oid idxoid,
TupleTableSlot *searchslot, TupleTableSlot *searchslot,
TupleTableSlot *outslot) TupleTableSlot *outslot)
{ {
HeapTuple scantuple; HeapTuple scantuple;
ScanKeyData skey[INDEX_MAX_KEYS]; ScanKeyData skey[INDEX_MAX_KEYS];
IndexScanDesc scan; IndexScanDesc scan;
SnapshotData snap; SnapshotData snap;
TransactionId xwait; TransactionId xwait;
Relation idxrel; Relation idxrel;
bool found; bool found;
/* Open the index.*/ /* Open the index. */
idxrel = index_open(idxoid, RowExclusiveLock); idxrel = index_open(idxoid, RowExclusiveLock);
/* Start an index scan. */ /* Start an index scan. */
@ -152,8 +152,8 @@ retry:
snap.xmin : snap.xmax; snap.xmin : snap.xmax;
/* /*
* If the tuple is locked, wait for locking transaction to finish * If the tuple is locked, wait for locking transaction to finish and
* and retry. * retry.
*/ */
if (TransactionIdIsValid(xwait)) if (TransactionIdIsValid(xwait))
{ {
@ -165,7 +165,7 @@ retry:
/* Found tuple, try to lock it in the lockmode. */ /* Found tuple, try to lock it in the lockmode. */
if (found) if (found)
{ {
Buffer buf; Buffer buf;
HeapUpdateFailureData hufd; HeapUpdateFailureData hufd;
HTSU_Result res; HTSU_Result res;
HeapTupleData locktup; HeapTupleData locktup;
@ -177,7 +177,7 @@ retry:
res = heap_lock_tuple(rel, &locktup, GetCurrentCommandId(false), res = heap_lock_tuple(rel, &locktup, GetCurrentCommandId(false),
lockmode, lockmode,
LockWaitBlock, LockWaitBlock,
false /* don't follow updates */, false /* don't follow updates */ ,
&buf, &hufd); &buf, &hufd);
/* the tuple slot already has the buffer pinned */ /* the tuple slot already has the buffer pinned */
ReleaseBuffer(buf); ReleaseBuffer(buf);
@ -219,7 +219,7 @@ retry:
* to use. * to use.
*/ */
static bool static bool
tuple_equals_slot(TupleDesc desc, HeapTuple tup, TupleTableSlot *slot) tuple_equals_slot(TupleDesc desc, HeapTuple tup, TupleTableSlot *slot)
{ {
Datum values[MaxTupleAttributeNumber]; Datum values[MaxTupleAttributeNumber];
bool isnull[MaxTupleAttributeNumber]; bool isnull[MaxTupleAttributeNumber];
@ -267,12 +267,12 @@ bool
RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode, RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode,
TupleTableSlot *searchslot, TupleTableSlot *outslot) TupleTableSlot *searchslot, TupleTableSlot *outslot)
{ {
HeapTuple scantuple; HeapTuple scantuple;
HeapScanDesc scan; HeapScanDesc scan;
SnapshotData snap; SnapshotData snap;
TransactionId xwait; TransactionId xwait;
bool found; bool found;
TupleDesc desc = RelationGetDescr(rel); TupleDesc desc = RelationGetDescr(rel);
Assert(equalTupleDescs(desc, outslot->tts_tupleDescriptor)); Assert(equalTupleDescs(desc, outslot->tts_tupleDescriptor));
@ -299,8 +299,8 @@ retry:
snap.xmin : snap.xmax; snap.xmin : snap.xmax;
/* /*
* If the tuple is locked, wait for locking transaction to finish * If the tuple is locked, wait for locking transaction to finish and
* and retry. * retry.
*/ */
if (TransactionIdIsValid(xwait)) if (TransactionIdIsValid(xwait))
{ {
@ -312,7 +312,7 @@ retry:
/* Found tuple, try to lock it in the lockmode. */ /* Found tuple, try to lock it in the lockmode. */
if (found) if (found)
{ {
Buffer buf; Buffer buf;
HeapUpdateFailureData hufd; HeapUpdateFailureData hufd;
HTSU_Result res; HTSU_Result res;
HeapTupleData locktup; HeapTupleData locktup;
@ -324,7 +324,7 @@ retry:
res = heap_lock_tuple(rel, &locktup, GetCurrentCommandId(false), res = heap_lock_tuple(rel, &locktup, GetCurrentCommandId(false),
lockmode, lockmode,
LockWaitBlock, LockWaitBlock,
false /* don't follow updates */, false /* don't follow updates */ ,
&buf, &hufd); &buf, &hufd);
/* the tuple slot already has the buffer pinned */ /* the tuple slot already has the buffer pinned */
ReleaseBuffer(buf); ReleaseBuffer(buf);
@ -363,10 +363,10 @@ retry:
void void
ExecSimpleRelationInsert(EState *estate, TupleTableSlot *slot) ExecSimpleRelationInsert(EState *estate, TupleTableSlot *slot)
{ {
bool skip_tuple = false; bool skip_tuple = false;
HeapTuple tuple; HeapTuple tuple;
ResultRelInfo *resultRelInfo = estate->es_result_relation_info; ResultRelInfo *resultRelInfo = estate->es_result_relation_info;
Relation rel = resultRelInfo->ri_RelationDesc; Relation rel = resultRelInfo->ri_RelationDesc;
/* For now we support only tables. */ /* For now we support only tables. */
Assert(rel->rd_rel->relkind == RELKIND_RELATION); Assert(rel->rd_rel->relkind == RELKIND_RELATION);
@ -379,7 +379,7 @@ ExecSimpleRelationInsert(EState *estate, TupleTableSlot *slot)
{ {
slot = ExecBRInsertTriggers(estate, resultRelInfo, slot); slot = ExecBRInsertTriggers(estate, resultRelInfo, slot);
if (slot == NULL) /* "do nothing" */ if (slot == NULL) /* "do nothing" */
skip_tuple = true; skip_tuple = true;
} }
@ -420,10 +420,10 @@ void
ExecSimpleRelationUpdate(EState *estate, EPQState *epqstate, ExecSimpleRelationUpdate(EState *estate, EPQState *epqstate,
TupleTableSlot *searchslot, TupleTableSlot *slot) TupleTableSlot *searchslot, TupleTableSlot *slot)
{ {
bool skip_tuple = false; bool skip_tuple = false;
HeapTuple tuple; HeapTuple tuple;
ResultRelInfo *resultRelInfo = estate->es_result_relation_info; ResultRelInfo *resultRelInfo = estate->es_result_relation_info;
Relation rel = resultRelInfo->ri_RelationDesc; Relation rel = resultRelInfo->ri_RelationDesc;
/* For now we support only tables. */ /* For now we support only tables. */
Assert(rel->rd_rel->relkind == RELKIND_RELATION); Assert(rel->rd_rel->relkind == RELKIND_RELATION);
@ -438,7 +438,7 @@ ExecSimpleRelationUpdate(EState *estate, EPQState *epqstate,
&searchslot->tts_tuple->t_self, &searchslot->tts_tuple->t_self,
NULL, slot); NULL, slot);
if (slot == NULL) /* "do nothing" */ if (slot == NULL) /* "do nothing" */
skip_tuple = true; skip_tuple = true;
} }
@ -482,9 +482,9 @@ void
ExecSimpleRelationDelete(EState *estate, EPQState *epqstate, ExecSimpleRelationDelete(EState *estate, EPQState *epqstate,
TupleTableSlot *searchslot) TupleTableSlot *searchslot)
{ {
bool skip_tuple = false; bool skip_tuple = false;
ResultRelInfo *resultRelInfo = estate->es_result_relation_info; ResultRelInfo *resultRelInfo = estate->es_result_relation_info;
Relation rel = resultRelInfo->ri_RelationDesc; Relation rel = resultRelInfo->ri_RelationDesc;
/* For now we support only tables. */ /* For now we support only tables. */
Assert(rel->rd_rel->relkind == RELKIND_RELATION); Assert(rel->rd_rel->relkind == RELKIND_RELATION);
@ -568,6 +568,6 @@ CheckSubscriptionRelkind(char relkind, const char *nspname,
if (relkind != RELKIND_RELATION) if (relkind != RELKIND_RELATION)
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE), (errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("logical replication target relation \"%s.%s\" is not a table", errmsg("logical replication target relation \"%s.%s\" is not a table",
nspname, relname))); nspname, relname)));
} }

@ -826,14 +826,14 @@ void
ExecLockNonLeafAppendTables(List *partitioned_rels, EState *estate) ExecLockNonLeafAppendTables(List *partitioned_rels, EState *estate)
{ {
PlannedStmt *stmt = estate->es_plannedstmt; PlannedStmt *stmt = estate->es_plannedstmt;
ListCell *lc; ListCell *lc;
foreach(lc, partitioned_rels) foreach(lc, partitioned_rels)
{ {
ListCell *l; ListCell *l;
Index rti = lfirst_int(lc); Index rti = lfirst_int(lc);
bool is_result_rel = false; bool is_result_rel = false;
Oid relid = getrelid(rti, estate->es_range_table); Oid relid = getrelid(rti, estate->es_range_table);
/* If this is a result relation, already locked in InitPlan */ /* If this is a result relation, already locked in InitPlan */
foreach(l, stmt->nonleafResultRelations) foreach(l, stmt->nonleafResultRelations)

@ -471,7 +471,7 @@ typedef struct AggStatePerGroupData
* NULL and not auto-replace it with a later input value. Only the first * NULL and not auto-replace it with a later input value. Only the first
* non-NULL input will be auto-substituted. * non-NULL input will be auto-substituted.
*/ */
} AggStatePerGroupData; } AggStatePerGroupData;
/* /*
* AggStatePerPhaseData - per-grouping-set-phase state * AggStatePerPhaseData - per-grouping-set-phase state
@ -515,7 +515,7 @@ typedef struct AggStatePerHashData
AttrNumber *hashGrpColIdxInput; /* hash col indices in input slot */ AttrNumber *hashGrpColIdxInput; /* hash col indices in input slot */
AttrNumber *hashGrpColIdxHash; /* indices in hashtbl tuples */ AttrNumber *hashGrpColIdxHash; /* indices in hashtbl tuples */
Agg *aggnode; /* original Agg node, for numGroups etc. */ Agg *aggnode; /* original Agg node, for numGroups etc. */
} AggStatePerHashData; } AggStatePerHashData;
static void select_current_set(AggState *aggstate, int setno, bool is_hash); static void select_current_set(AggState *aggstate, int setno, bool is_hash);

@ -129,8 +129,8 @@ ExecInitAppend(Append *node, EState *estate, int eflags)
Assert(!(eflags & EXEC_FLAG_MARK)); Assert(!(eflags & EXEC_FLAG_MARK));
/* /*
* Lock the non-leaf tables in the partition tree controlled by this * Lock the non-leaf tables in the partition tree controlled by this node.
* node. It's a no-op for non-partitioned parent tables. * It's a no-op for non-partitioned parent tables.
*/ */
ExecLockNonLeafAppendTables(node->partitioned_rels, estate); ExecLockNonLeafAppendTables(node->partitioned_rels, estate);

@ -506,8 +506,9 @@ BitmapAdjustPrefetchIterator(BitmapHeapScanState *node,
* In case of shared mode, we can not ensure that the current * In case of shared mode, we can not ensure that the current
* blockno of the main iterator and that of the prefetch iterator * blockno of the main iterator and that of the prefetch iterator
* are same. It's possible that whatever blockno we are * are same. It's possible that whatever blockno we are
* prefetching will be processed by another process. Therefore, we * prefetching will be processed by another process. Therefore,
* don't validate the blockno here as we do in non-parallel case. * we don't validate the blockno here as we do in non-parallel
* case.
*/ */
if (prefetch_iterator) if (prefetch_iterator)
tbm_shared_iterate(prefetch_iterator); tbm_shared_iterate(prefetch_iterator);

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save