PostgreSQL Source Code  git master
pgrowlocks.c
Go to the documentation of this file.
1 /*
2  * contrib/pgrowlocks/pgrowlocks.c
3  *
4  * Copyright (c) 2005-2006 Tatsuo Ishii
5  *
6  * Permission to use, copy, modify, and distribute this software and
7  * its documentation for any purpose, without fee, and without a
8  * written agreement is hereby granted, provided that the above
9  * copyright notice and this paragraph and the following two
10  * paragraphs appear in all copies.
11  *
12  * IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
13  * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
14  * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
15  * DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED
16  * OF THE POSSIBILITY OF SUCH DAMAGE.
17  *
18  * THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20  * A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS
21  * IS" BASIS, AND THE AUTHOR HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,
22  * SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23  */
24 
25 #include "postgres.h"
26 
27 #include "access/heapam.h"
28 #include "access/multixact.h"
29 #include "access/relscan.h"
30 #include "access/tableam.h"
31 #include "access/xact.h"
32 #include "catalog/namespace.h"
33 #include "catalog/pg_am_d.h"
34 #include "catalog/pg_authid.h"
35 #include "funcapi.h"
36 #include "miscadmin.h"
37 #include "storage/bufmgr.h"
38 #include "storage/procarray.h"
39 #include "utils/acl.h"
40 #include "utils/builtins.h"
41 #include "utils/rel.h"
42 #include "utils/snapmgr.h"
43 #include "utils/varlena.h"
44 
46 
48 
49 /* ----------
50  * pgrowlocks:
51  * returns tids of rows being locked
52  * ----------
53  */
54 
55 #define NCHARS 32
56 
57 typedef struct
58 {
61  int ncolumns;
62 } MyData;
63 
64 #define Atnum_tid 0
65 #define Atnum_xmax 1
66 #define Atnum_ismulti 2
67 #define Atnum_xids 3
68 #define Atnum_modes 4
69 #define Atnum_pids 5
70 
71 Datum
73 {
74  FuncCallContext *funcctx;
75  TableScanDesc scan;
76  HeapScanDesc hscan;
77  HeapTuple tuple;
78  TupleDesc tupdesc;
79  AttInMetadata *attinmeta;
80  Datum result;
81  MyData *mydata;
82  Relation rel;
83 
84  if (SRF_IS_FIRSTCALL())
85  {
86  text *relname;
87  RangeVar *relrv;
88  MemoryContext oldcontext;
89  AclResult aclresult;
90 
91  funcctx = SRF_FIRSTCALL_INIT();
92  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
93 
94  /* Build a tuple descriptor for our result type */
95  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
96  elog(ERROR, "return type must be a row type");
97 
98  attinmeta = TupleDescGetAttInMetadata(tupdesc);
99  funcctx->attinmeta = attinmeta;
100 
101  relname = PG_GETARG_TEXT_PP(0);
103  rel = relation_openrv(relrv, AccessShareLock);
104 
105  if (rel->rd_rel->relam != HEAP_TABLE_AM_OID)
106  ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
107  errmsg("only heap AM is supported")));
108 
109  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
110  ereport(ERROR,
111  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
112  errmsg("\"%s\" is a partitioned table",
114  errdetail("Partitioned tables do not contain rows.")));
115  else if (rel->rd_rel->relkind != RELKIND_RELATION)
116  ereport(ERROR,
117  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
118  errmsg("\"%s\" is not a table",
119  RelationGetRelationName(rel))));
120 
121  /*
122  * check permissions: must have SELECT on table or be in
123  * pg_stat_scan_tables
124  */
125  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
126  ACL_SELECT);
127  if (aclresult != ACLCHECK_OK)
128  aclresult = is_member_of_role(GetUserId(), DEFAULT_ROLE_STAT_SCAN_TABLES) ? ACLCHECK_OK : ACLCHECK_NO_PRIV;
129 
130  if (aclresult != ACLCHECK_OK)
131  aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
133 
134  scan = table_beginscan(rel, GetActiveSnapshot(), 0, NULL);
135  hscan = (HeapScanDesc) scan;
136  mydata = palloc(sizeof(*mydata));
137  mydata->rel = rel;
138  mydata->scan = scan;
139  mydata->ncolumns = tupdesc->natts;
140  funcctx->user_fctx = mydata;
141 
142  MemoryContextSwitchTo(oldcontext);
143  }
144 
145  funcctx = SRF_PERCALL_SETUP();
146  attinmeta = funcctx->attinmeta;
147  mydata = (MyData *) funcctx->user_fctx;
148  scan = mydata->scan;
149  hscan = (HeapScanDesc) scan;
150 
151  /* scan the relation */
152  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
153  {
154  TM_Result htsu;
155  TransactionId xmax;
156  uint16 infomask;
157 
158  /* must hold a buffer lock to call HeapTupleSatisfiesUpdate */
160 
161  htsu = HeapTupleSatisfiesUpdate(tuple,
162  GetCurrentCommandId(false),
163  hscan->rs_cbuf);
164  xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
165  infomask = tuple->t_data->t_infomask;
166 
167  /*
168  * A tuple is locked if HTSU returns BeingModified.
169  */
170  if (htsu == TM_BeingModified)
171  {
172  char **values;
173 
174  values = (char **) palloc(mydata->ncolumns * sizeof(char *));
175 
176  values[Atnum_tid] = (char *) DirectFunctionCall1(tidout,
177  PointerGetDatum(&tuple->t_self));
178 
179  values[Atnum_xmax] = palloc(NCHARS * sizeof(char));
180  snprintf(values[Atnum_xmax], NCHARS, "%d", xmax);
181  if (infomask & HEAP_XMAX_IS_MULTI)
182  {
183  MultiXactMember *members;
184  int nmembers;
185  bool first = true;
186  bool allow_old;
187 
188  values[Atnum_ismulti] = pstrdup("true");
189 
190  allow_old = HEAP_LOCKED_UPGRADED(infomask);
191  nmembers = GetMultiXactIdMembers(xmax, &members, allow_old,
192  false);
193  if (nmembers == -1)
194  {
195  values[Atnum_xids] = "{0}";
196  values[Atnum_modes] = "{transient upgrade status}";
197  values[Atnum_pids] = "{0}";
198  }
199  else
200  {
201  int j;
202 
203  values[Atnum_xids] = palloc(NCHARS * nmembers);
204  values[Atnum_modes] = palloc(NCHARS * nmembers);
205  values[Atnum_pids] = palloc(NCHARS * nmembers);
206 
207  strcpy(values[Atnum_xids], "{");
208  strcpy(values[Atnum_modes], "{");
209  strcpy(values[Atnum_pids], "{");
210 
211  for (j = 0; j < nmembers; j++)
212  {
213  char buf[NCHARS];
214 
215  if (!first)
216  {
217  strcat(values[Atnum_xids], ",");
218  strcat(values[Atnum_modes], ",");
219  strcat(values[Atnum_pids], ",");
220  }
221  snprintf(buf, NCHARS, "%d", members[j].xid);
222  strcat(values[Atnum_xids], buf);
223  switch (members[j].status)
224  {
226  snprintf(buf, NCHARS, "Update");
227  break;
229  snprintf(buf, NCHARS, "No Key Update");
230  break;
232  snprintf(buf, NCHARS, "For Update");
233  break;
235  snprintf(buf, NCHARS, "For No Key Update");
236  break;
238  snprintf(buf, NCHARS, "Share");
239  break;
241  snprintf(buf, NCHARS, "Key Share");
242  break;
243  }
244  strcat(values[Atnum_modes], buf);
245  snprintf(buf, NCHARS, "%d",
246  BackendXidGetPid(members[j].xid));
247  strcat(values[Atnum_pids], buf);
248 
249  first = false;
250  }
251 
252  strcat(values[Atnum_xids], "}");
253  strcat(values[Atnum_modes], "}");
254  strcat(values[Atnum_pids], "}");
255  }
256  }
257  else
258  {
259  values[Atnum_ismulti] = pstrdup("false");
260 
261  values[Atnum_xids] = palloc(NCHARS * sizeof(char));
262  snprintf(values[Atnum_xids], NCHARS, "{%d}", xmax);
263 
264  values[Atnum_modes] = palloc(NCHARS);
265  if (infomask & HEAP_XMAX_LOCK_ONLY)
266  {
267  if (HEAP_XMAX_IS_SHR_LOCKED(infomask))
268  snprintf(values[Atnum_modes], NCHARS, "{For Share}");
269  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
270  snprintf(values[Atnum_modes], NCHARS, "{For Key Share}");
271  else if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
272  {
273  if (tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED)
274  snprintf(values[Atnum_modes], NCHARS, "{For Update}");
275  else
276  snprintf(values[Atnum_modes], NCHARS, "{For No Key Update}");
277  }
278  else
279  /* neither keyshare nor exclusive bit it set */
280  snprintf(values[Atnum_modes], NCHARS,
281  "{transient upgrade status}");
282  }
283  else
284  {
285  if (tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED)
286  snprintf(values[Atnum_modes], NCHARS, "{Update}");
287  else
288  snprintf(values[Atnum_modes], NCHARS, "{No Key Update}");
289  }
290 
291  values[Atnum_pids] = palloc(NCHARS * sizeof(char));
292  snprintf(values[Atnum_pids], NCHARS, "{%d}",
293  BackendXidGetPid(xmax));
294  }
295 
297 
298  /* build a tuple */
299  tuple = BuildTupleFromCStrings(attinmeta, values);
300 
301  /* make the tuple into a datum */
302  result = HeapTupleGetDatum(tuple);
303 
304  /*
305  * no need to pfree what we allocated; it's on a short-lived
306  * memory context anyway
307  */
308 
309  SRF_RETURN_NEXT(funcctx, result);
310  }
311  else
312  {
314  }
315  }
316 
317  table_endscan(scan);
318  table_close(mydata->rel, AccessShareLock);
319 
320  SRF_RETURN_DONE(funcctx);
321 }
#define NCHARS
Definition: pgrowlocks.c:55
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:86
PG_FUNCTION_INFO_V1(pgrowlocks)
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:196
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define HEAP_XMAX_LOCK_ONLY
Definition: htup_details.h:196
uint32 TransactionId
Definition: c.h:514
Oid GetUserId(void)
Definition: miscinit.c:380
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:282
#define PointerGetDatum(X)
Definition: postgres.h:556
char * pstrdup(const char *in)
Definition: mcxt.c:1186
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:841
#define HEAP_LOCKED_UPGRADED(infomask)
Definition: htup_details.h:252
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:608
Datum pgrowlocks(PG_FUNCTION_ARGS)
Definition: pgrowlocks.c:72
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3054
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:615
Form_pg_class rd_rel
Definition: rel.h:83
NameData relname
Definition: pg_class.h:35
TM_Result HeapTupleSatisfiesUpdate(HeapTuple htup, CommandId curcid, Buffer buffer)
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:286
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:72
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2116
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
#define HEAP_XMAX_IS_SHR_LOCKED(infomask)
Definition: htup_details.h:262
HeapTupleHeader t_data
Definition: htup.h:68
#define Atnum_tid
Definition: pgrowlocks.c:64
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:288
Relation rel
Definition: pgrowlocks.c:59
PG_MODULE_MAGIC
Definition: pgrowlocks.c:45
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3352
#define HeapTupleHeaderGetRawXmax(tup)
Definition: htup_details.h:375
unsigned short uint16
Definition: c.h:358
#define ERROR
Definition: elog.h:43
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key)
Definition: tableam.h:736
ItemPointerData t_self
Definition: htup.h:65
static char * buf
Definition: pg_test_fsync.c:67
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
AttInMetadata * attinmeta
Definition: funcapi.h:91
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define RelationGetRelationName(relation)
Definition: rel.h:456
#define ereport(elevel, rest)
Definition: elog.h:141
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3594
TM_Result
Definition: tableam.h:68
int BackendXidGetPid(TransactionId xid)
Definition: procarray.c:2425
#define Atnum_modes
Definition: pgrowlocks.c:68
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
#define ACL_SELECT
Definition: parsenodes.h:75
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2067
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3602
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:138
#define HEAP_KEYS_UPDATED
Definition: htup_details.h:278
#define HEAP_XMAX_IS_MULTI
Definition: htup_details.h:208
TableScanDesc scan
Definition: pgrowlocks.c:60
bool is_member_of_role(Oid member, Oid role)
Definition: acl.c:4924
Buffer rs_cbuf
Definition: heapam.h:59
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:220
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4629
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define Atnum_xids
Definition: pgrowlocks.c:67
void * user_fctx
Definition: funcapi.h:82
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
ObjectType get_relkind_objtype(char relkind)
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:87
Definition: c.h:556
#define PG_FUNCTION_ARGS
Definition: fmgr.h:188
#define Atnum_pids
Definition: pgrowlocks.c:69
int ncolumns
Definition: pgrowlocks.c:61
#define HEAP_XMAX_IS_EXCL_LOCKED(infomask)
Definition: htup_details.h:264
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:745
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool onlyLock)
Definition: multixact.c:1204
#define HEAP_XMAX_IS_KEYSHR_LOCKED(infomask)
Definition: htup_details.h:266
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:226
#define snprintf
Definition: port.h:192
Datum tidout(PG_FUNCTION_ARGS)
Definition: tid.c:106
#define RelationGetRelid(relation)
Definition: rel.h:422
#define Atnum_xmax
Definition: pgrowlocks.c:65
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:306
#define Atnum_ismulti
Definition: pgrowlocks.c:66
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:284