PostgreSQL Source Code  git master
misc.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * misc.c
4  *
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/utils/adt/misc.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include <sys/file.h>
18 #include <sys/stat.h>
19 #include <dirent.h>
20 #include <fcntl.h>
21 #include <math.h>
22 #include <unistd.h>
23 
24 #include "access/sysattr.h"
25 #include "access/table.h"
26 #include "catalog/catalog.h"
27 #include "catalog/pg_tablespace.h"
28 #include "catalog/pg_type.h"
29 #include "catalog/system_fk_info.h"
30 #include "commands/dbcommands.h"
31 #include "commands/tablespace.h"
32 #include "common/keywords.h"
33 #include "funcapi.h"
34 #include "miscadmin.h"
35 #include "parser/scansup.h"
36 #include "pgstat.h"
37 #include "postmaster/syslogger.h"
38 #include "rewrite/rewriteHandler.h"
39 #include "storage/fd.h"
40 #include "storage/latch.h"
41 #include "tcop/tcopprot.h"
42 #include "utils/builtins.h"
43 #include "utils/fmgroids.h"
44 #include "utils/lsyscache.h"
45 #include "utils/ruleutils.h"
46 #include "utils/timestamp.h"
47 
48 /*
49  * Common subroutine for num_nulls() and num_nonnulls().
50  * Returns true if successful, false if function should return NULL.
51  * If successful, total argument count and number of nulls are
52  * returned into *nargs and *nulls.
53  */
54 static bool
56  int32 *nargs, int32 *nulls)
57 {
58  int32 count = 0;
59  int i;
60 
61  /* Did we get a VARIADIC array argument, or separate arguments? */
62  if (get_fn_expr_variadic(fcinfo->flinfo))
63  {
64  ArrayType *arr;
65  int ndims,
66  nitems,
67  *dims;
68  bits8 *bitmap;
69 
70  Assert(PG_NARGS() == 1);
71 
72  /*
73  * If we get a null as VARIADIC array argument, we can't say anything
74  * useful about the number of elements, so return NULL. This behavior
75  * is consistent with other variadic functions - see concat_internal.
76  */
77  if (PG_ARGISNULL(0))
78  return false;
79 
80  /*
81  * Non-null argument had better be an array. We assume that any call
82  * context that could let get_fn_expr_variadic return true will have
83  * checked that a VARIADIC-labeled parameter actually is an array. So
84  * it should be okay to just Assert that it's an array rather than
85  * doing a full-fledged error check.
86  */
88 
89  /* OK, safe to fetch the array value */
90  arr = PG_GETARG_ARRAYTYPE_P(0);
91 
92  /* Count the array elements */
93  ndims = ARR_NDIM(arr);
94  dims = ARR_DIMS(arr);
95  nitems = ArrayGetNItems(ndims, dims);
96 
97  /* Count those that are NULL */
98  bitmap = ARR_NULLBITMAP(arr);
99  if (bitmap)
100  {
101  int bitmask = 1;
102 
103  for (i = 0; i < nitems; i++)
104  {
105  if ((*bitmap & bitmask) == 0)
106  count++;
107 
108  bitmask <<= 1;
109  if (bitmask == 0x100)
110  {
111  bitmap++;
112  bitmask = 1;
113  }
114  }
115  }
116 
117  *nargs = nitems;
118  *nulls = count;
119  }
120  else
121  {
122  /* Separate arguments, so just count 'em */
123  for (i = 0; i < PG_NARGS(); i++)
124  {
125  if (PG_ARGISNULL(i))
126  count++;
127  }
128 
129  *nargs = PG_NARGS();
130  *nulls = count;
131  }
132 
133  return true;
134 }
135 
136 /*
137  * num_nulls()
138  * Count the number of NULL arguments
139  */
140 Datum
142 {
143  int32 nargs,
144  nulls;
145 
146  if (!count_nulls(fcinfo, &nargs, &nulls))
147  PG_RETURN_NULL();
148 
149  PG_RETURN_INT32(nulls);
150 }
151 
152 /*
153  * num_nonnulls()
154  * Count the number of non-NULL arguments
155  */
156 Datum
158 {
159  int32 nargs,
160  nulls;
161 
162  if (!count_nulls(fcinfo, &nargs, &nulls))
163  PG_RETURN_NULL();
164 
165  PG_RETURN_INT32(nargs - nulls);
166 }
167 
168 
169 /*
170  * current_database()
171  * Expose the current database to the user
172  */
173 Datum
175 {
176  Name db;
177 
178  db = (Name) palloc(NAMEDATALEN);
179 
181  PG_RETURN_NAME(db);
182 }
183 
184 
185 /*
186  * current_query()
187  * Expose the current query to the user (useful in stored procedures)
188  * We might want to use ActivePortal->sourceText someday.
189  */
190 Datum
192 {
193  /* there is no easy way to access the more concise 'query_string' */
194  if (debug_query_string)
196  else
197  PG_RETURN_NULL();
198 }
199 
200 /* Function to find out which databases make use of a tablespace */
201 
202 Datum
204 {
205  Oid tablespaceOid = PG_GETARG_OID(0);
206  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
207  char *location;
208  DIR *dirdesc;
209  struct dirent *de;
210 
212 
213  if (tablespaceOid == GLOBALTABLESPACE_OID)
214  {
216  (errmsg("global tablespace never has databases")));
217  /* return empty tuplestore */
218  return (Datum) 0;
219  }
220 
221  if (tablespaceOid == DEFAULTTABLESPACE_OID)
222  location = "base";
223  else
224  location = psprintf("pg_tblspc/%u/%s", tablespaceOid,
226 
227  dirdesc = AllocateDir(location);
228 
229  if (!dirdesc)
230  {
231  /* the only expected error is ENOENT */
232  if (errno != ENOENT)
233  ereport(ERROR,
235  errmsg("could not open directory \"%s\": %m",
236  location)));
238  (errmsg("%u is not a tablespace OID", tablespaceOid)));
239  /* return empty tuplestore */
240  return (Datum) 0;
241  }
242 
243  while ((de = ReadDir(dirdesc, location)) != NULL)
244  {
245  Oid datOid = atooid(de->d_name);
246  char *subdir;
247  bool isempty;
248  Datum values[1];
249  bool nulls[1];
250 
251  /* this test skips . and .., but is awfully weak */
252  if (!datOid)
253  continue;
254 
255  /* if database subdir is empty, don't report tablespace as used */
256 
257  subdir = psprintf("%s/%s", location, de->d_name);
258  isempty = directory_is_empty(subdir);
259  pfree(subdir);
260 
261  if (isempty)
262  continue; /* indeed, nothing in it */
263 
264  values[0] = ObjectIdGetDatum(datOid);
265  nulls[0] = false;
266 
267  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
268  values, nulls);
269  }
270 
271  FreeDir(dirdesc);
272  return (Datum) 0;
273 }
274 
275 
276 /*
277  * pg_tablespace_location - get location for a tablespace
278  */
279 Datum
281 {
282  Oid tablespaceOid = PG_GETARG_OID(0);
283  char sourcepath[MAXPGPATH];
284  char targetpath[MAXPGPATH];
285  int rllen;
286  struct stat st;
287 
288  /*
289  * It's useful to apply this function to pg_class.reltablespace, wherein
290  * zero means "the database's default tablespace". So, rather than
291  * throwing an error for zero, we choose to assume that's what is meant.
292  */
293  if (tablespaceOid == InvalidOid)
294  tablespaceOid = MyDatabaseTableSpace;
295 
296  /*
297  * Return empty string for the cluster's default tablespaces
298  */
299  if (tablespaceOid == DEFAULTTABLESPACE_OID ||
300  tablespaceOid == GLOBALTABLESPACE_OID)
302 
303  /*
304  * Find the location of the tablespace by reading the symbolic link that
305  * is in pg_tblspc/<oid>.
306  */
307  snprintf(sourcepath, sizeof(sourcepath), "pg_tblspc/%u", tablespaceOid);
308 
309  /*
310  * Before reading the link, check if the source path is a link or a
311  * junction point. Note that a directory is possible for a tablespace
312  * created with allow_in_place_tablespaces enabled. If a directory is
313  * found, a relative path to the data directory is returned.
314  */
315  if (lstat(sourcepath, &st) < 0)
316  {
317  ereport(ERROR,
319  errmsg("could not stat file \"%s\": %m",
320  sourcepath)));
321  }
322 
323  if (!S_ISLNK(st.st_mode))
324  PG_RETURN_TEXT_P(cstring_to_text(sourcepath));
325 
326  /*
327  * In presence of a link or a junction point, return the path pointing to.
328  */
329  rllen = readlink(sourcepath, targetpath, sizeof(targetpath));
330  if (rllen < 0)
331  ereport(ERROR,
333  errmsg("could not read symbolic link \"%s\": %m",
334  sourcepath)));
335  if (rllen >= sizeof(targetpath))
336  ereport(ERROR,
337  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
338  errmsg("symbolic link \"%s\" target is too long",
339  sourcepath)));
340  targetpath[rllen] = '\0';
341 
342  PG_RETURN_TEXT_P(cstring_to_text(targetpath));
343 }
344 
345 /*
346  * pg_sleep - delay for N seconds
347  */
348 Datum
350 {
351  float8 secs = PG_GETARG_FLOAT8(0);
352  float8 endtime;
353 
354  /*
355  * We sleep using WaitLatch, to ensure that we'll wake up promptly if an
356  * important signal (such as SIGALRM or SIGINT) arrives. Because
357  * WaitLatch's upper limit of delay is INT_MAX milliseconds, and the user
358  * might ask for more than that, we sleep for at most 10 minutes and then
359  * loop.
360  *
361  * By computing the intended stop time initially, we avoid accumulation of
362  * extra delay across multiple sleeps. This also ensures we won't delay
363  * less than the specified time when WaitLatch is terminated early by a
364  * non-query-canceling signal such as SIGHUP.
365  */
366 #define GetNowFloat() ((float8) GetCurrentTimestamp() / 1000000.0)
367 
368  endtime = GetNowFloat() + secs;
369 
370  for (;;)
371  {
372  float8 delay;
373  long delay_ms;
374 
376 
377  delay = endtime - GetNowFloat();
378  if (delay >= 600.0)
379  delay_ms = 600000;
380  else if (delay > 0.0)
381  delay_ms = (long) ceil(delay * 1000.0);
382  else
383  break;
384 
385  (void) WaitLatch(MyLatch,
387  delay_ms,
390  }
391 
392  PG_RETURN_VOID();
393 }
394 
395 /* Function to return the list of grammar keywords */
396 Datum
398 {
399  FuncCallContext *funcctx;
400 
401  if (SRF_IS_FIRSTCALL())
402  {
403  MemoryContext oldcontext;
404  TupleDesc tupdesc;
405 
406  funcctx = SRF_FIRSTCALL_INIT();
407  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
408 
409  tupdesc = CreateTemplateTupleDesc(5);
410  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "word",
411  TEXTOID, -1, 0);
412  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "catcode",
413  CHAROID, -1, 0);
414  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "barelabel",
415  BOOLOID, -1, 0);
416  TupleDescInitEntry(tupdesc, (AttrNumber) 4, "catdesc",
417  TEXTOID, -1, 0);
418  TupleDescInitEntry(tupdesc, (AttrNumber) 5, "baredesc",
419  TEXTOID, -1, 0);
420 
421  funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
422 
423  MemoryContextSwitchTo(oldcontext);
424  }
425 
426  funcctx = SRF_PERCALL_SETUP();
427 
428  if (funcctx->call_cntr < ScanKeywords.num_keywords)
429  {
430  char *values[5];
431  HeapTuple tuple;
432 
433  /* cast-away-const is ugly but alternatives aren't much better */
434  values[0] = unconstify(char *,
435  GetScanKeyword(funcctx->call_cntr,
436  &ScanKeywords));
437 
438  switch (ScanKeywordCategories[funcctx->call_cntr])
439  {
440  case UNRESERVED_KEYWORD:
441  values[1] = "U";
442  values[3] = _("unreserved");
443  break;
444  case COL_NAME_KEYWORD:
445  values[1] = "C";
446  values[3] = _("unreserved (cannot be function or type name)");
447  break;
449  values[1] = "T";
450  values[3] = _("reserved (can be function or type name)");
451  break;
452  case RESERVED_KEYWORD:
453  values[1] = "R";
454  values[3] = _("reserved");
455  break;
456  default: /* shouldn't be possible */
457  values[1] = NULL;
458  values[3] = NULL;
459  break;
460  }
461 
462  if (ScanKeywordBareLabel[funcctx->call_cntr])
463  {
464  values[2] = "true";
465  values[4] = _("can be bare label");
466  }
467  else
468  {
469  values[2] = "false";
470  values[4] = _("requires AS");
471  }
472 
473  tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
474 
475  SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
476  }
477 
478  SRF_RETURN_DONE(funcctx);
479 }
480 
481 
482 /* Function to return the list of catalog foreign key relationships */
483 Datum
485 {
486  FuncCallContext *funcctx;
487  FmgrInfo *arrayinp;
488 
489  if (SRF_IS_FIRSTCALL())
490  {
491  MemoryContext oldcontext;
492  TupleDesc tupdesc;
493 
494  funcctx = SRF_FIRSTCALL_INIT();
495  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
496 
497  tupdesc = CreateTemplateTupleDesc(6);
498  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "fktable",
499  REGCLASSOID, -1, 0);
500  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "fkcols",
501  TEXTARRAYOID, -1, 0);
502  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "pktable",
503  REGCLASSOID, -1, 0);
504  TupleDescInitEntry(tupdesc, (AttrNumber) 4, "pkcols",
505  TEXTARRAYOID, -1, 0);
506  TupleDescInitEntry(tupdesc, (AttrNumber) 5, "is_array",
507  BOOLOID, -1, 0);
508  TupleDescInitEntry(tupdesc, (AttrNumber) 6, "is_opt",
509  BOOLOID, -1, 0);
510 
511  funcctx->tuple_desc = BlessTupleDesc(tupdesc);
512 
513  /*
514  * We use array_in to convert the C strings in sys_fk_relationships[]
515  * to text arrays. But we cannot use DirectFunctionCallN to call
516  * array_in, and it wouldn't be very efficient if we could. Fill an
517  * FmgrInfo to use for the call.
518  */
519  arrayinp = (FmgrInfo *) palloc(sizeof(FmgrInfo));
520  fmgr_info(F_ARRAY_IN, arrayinp);
521  funcctx->user_fctx = arrayinp;
522 
523  MemoryContextSwitchTo(oldcontext);
524  }
525 
526  funcctx = SRF_PERCALL_SETUP();
527  arrayinp = (FmgrInfo *) funcctx->user_fctx;
528 
529  if (funcctx->call_cntr < lengthof(sys_fk_relationships))
530  {
531  const SysFKRelationship *fkrel = &sys_fk_relationships[funcctx->call_cntr];
532  Datum values[6];
533  bool nulls[6];
534  HeapTuple tuple;
535 
536  memset(nulls, false, sizeof(nulls));
537 
538  values[0] = ObjectIdGetDatum(fkrel->fk_table);
539  values[1] = FunctionCall3(arrayinp,
540  CStringGetDatum(fkrel->fk_columns),
541  ObjectIdGetDatum(TEXTOID),
542  Int32GetDatum(-1));
543  values[2] = ObjectIdGetDatum(fkrel->pk_table);
544  values[3] = FunctionCall3(arrayinp,
545  CStringGetDatum(fkrel->pk_columns),
546  ObjectIdGetDatum(TEXTOID),
547  Int32GetDatum(-1));
548  values[4] = BoolGetDatum(fkrel->is_array);
549  values[5] = BoolGetDatum(fkrel->is_opt);
550 
551  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
552 
553  SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
554  }
555 
556  SRF_RETURN_DONE(funcctx);
557 }
558 
559 
560 /*
561  * Return the type of the argument.
562  */
563 Datum
565 {
566  PG_RETURN_OID(get_fn_expr_argtype(fcinfo->flinfo, 0));
567 }
568 
569 
570 /*
571  * Implementation of the COLLATE FOR expression; returns the collation
572  * of the argument.
573  */
574 Datum
576 {
577  Oid typeid;
578  Oid collid;
579 
580  typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
581  if (!typeid)
582  PG_RETURN_NULL();
583  if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
584  ereport(ERROR,
585  (errcode(ERRCODE_DATATYPE_MISMATCH),
586  errmsg("collations are not supported by type %s",
587  format_type_be(typeid))));
588 
589  collid = PG_GET_COLLATION();
590  if (!collid)
591  PG_RETURN_NULL();
593 }
594 
595 
596 /*
597  * pg_relation_is_updatable - determine which update events the specified
598  * relation supports.
599  *
600  * This relies on relation_is_updatable() in rewriteHandler.c, which see
601  * for additional information.
602  */
603 Datum
605 {
606  Oid reloid = PG_GETARG_OID(0);
607  bool include_triggers = PG_GETARG_BOOL(1);
608 
609  PG_RETURN_INT32(relation_is_updatable(reloid, NIL, include_triggers, NULL));
610 }
611 
612 /*
613  * pg_column_is_updatable - determine whether a column is updatable
614  *
615  * This function encapsulates the decision about just what
616  * information_schema.columns.is_updatable actually means. It's not clear
617  * whether deletability of the column's relation should be required, so
618  * we want that decision in C code where we could change it without initdb.
619  */
620 Datum
622 {
623  Oid reloid = PG_GETARG_OID(0);
626  bool include_triggers = PG_GETARG_BOOL(2);
627  int events;
628 
629  /* System columns are never updatable */
630  if (attnum <= 0)
631  PG_RETURN_BOOL(false);
632 
633  events = relation_is_updatable(reloid, NIL, include_triggers,
634  bms_make_singleton(col));
635 
636  /* We require both updatability and deletability of the relation */
637 #define REQ_EVENTS ((1 << CMD_UPDATE) | (1 << CMD_DELETE))
638 
639  PG_RETURN_BOOL((events & REQ_EVENTS) == REQ_EVENTS);
640 }
641 
642 
643 /*
644  * Is character a valid identifier start?
645  * Must match scan.l's {ident_start} character class.
646  */
647 static bool
648 is_ident_start(unsigned char c)
649 {
650  /* Underscores and ASCII letters are OK */
651  if (c == '_')
652  return true;
653  if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
654  return true;
655  /* Any high-bit-set character is OK (might be part of a multibyte char) */
656  if (IS_HIGHBIT_SET(c))
657  return true;
658  return false;
659 }
660 
661 /*
662  * Is character a valid identifier continuation?
663  * Must match scan.l's {ident_cont} character class.
664  */
665 static bool
666 is_ident_cont(unsigned char c)
667 {
668  /* Can be digit or dollar sign ... */
669  if ((c >= '0' && c <= '9') || c == '$')
670  return true;
671  /* ... or an identifier start character */
672  return is_ident_start(c);
673 }
674 
675 /*
676  * parse_ident - parse a SQL qualified identifier into separate identifiers.
677  * When strict mode is active (second parameter), then any chars after
678  * the last identifier are disallowed.
679  */
680 Datum
682 {
683  text *qualname = PG_GETARG_TEXT_PP(0);
684  bool strict = PG_GETARG_BOOL(1);
685  char *qualname_str = text_to_cstring(qualname);
686  ArrayBuildState *astate = NULL;
687  char *nextp;
688  bool after_dot = false;
689 
690  /*
691  * The code below scribbles on qualname_str in some cases, so we should
692  * reconvert qualname if we need to show the original string in error
693  * messages.
694  */
695  nextp = qualname_str;
696 
697  /* skip leading whitespace */
698  while (scanner_isspace(*nextp))
699  nextp++;
700 
701  for (;;)
702  {
703  char *curname;
704  bool missing_ident = true;
705 
706  if (*nextp == '"')
707  {
708  char *endp;
709 
710  curname = nextp + 1;
711  for (;;)
712  {
713  endp = strchr(nextp + 1, '"');
714  if (endp == NULL)
715  ereport(ERROR,
716  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
717  errmsg("string is not a valid identifier: \"%s\"",
718  text_to_cstring(qualname)),
719  errdetail("String has unclosed double quotes.")));
720  if (endp[1] != '"')
721  break;
722  memmove(endp, endp + 1, strlen(endp));
723  nextp = endp;
724  }
725  nextp = endp + 1;
726  *endp = '\0';
727 
728  if (endp - curname == 0)
729  ereport(ERROR,
730  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
731  errmsg("string is not a valid identifier: \"%s\"",
732  text_to_cstring(qualname)),
733  errdetail("Quoted identifier must not be empty.")));
734 
735  astate = accumArrayResult(astate, CStringGetTextDatum(curname),
736  false, TEXTOID, CurrentMemoryContext);
737  missing_ident = false;
738  }
739  else if (is_ident_start((unsigned char) *nextp))
740  {
741  char *downname;
742  int len;
743  text *part;
744 
745  curname = nextp++;
746  while (is_ident_cont((unsigned char) *nextp))
747  nextp++;
748 
749  len = nextp - curname;
750 
751  /*
752  * We don't implicitly truncate identifiers. This is useful for
753  * allowing the user to check for specific parts of the identifier
754  * being too long. It's easy enough for the user to get the
755  * truncated names by casting our output to name[].
756  */
757  downname = downcase_identifier(curname, len, false, false);
758  part = cstring_to_text_with_len(downname, len);
759  astate = accumArrayResult(astate, PointerGetDatum(part), false,
760  TEXTOID, CurrentMemoryContext);
761  missing_ident = false;
762  }
763 
764  if (missing_ident)
765  {
766  /* Different error messages based on where we failed. */
767  if (*nextp == '.')
768  ereport(ERROR,
769  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
770  errmsg("string is not a valid identifier: \"%s\"",
771  text_to_cstring(qualname)),
772  errdetail("No valid identifier before \".\".")));
773  else if (after_dot)
774  ereport(ERROR,
775  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
776  errmsg("string is not a valid identifier: \"%s\"",
777  text_to_cstring(qualname)),
778  errdetail("No valid identifier after \".\".")));
779  else
780  ereport(ERROR,
781  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
782  errmsg("string is not a valid identifier: \"%s\"",
783  text_to_cstring(qualname))));
784  }
785 
786  while (scanner_isspace(*nextp))
787  nextp++;
788 
789  if (*nextp == '.')
790  {
791  after_dot = true;
792  nextp++;
793  while (scanner_isspace(*nextp))
794  nextp++;
795  }
796  else if (*nextp == '\0')
797  {
798  break;
799  }
800  else
801  {
802  if (strict)
803  ereport(ERROR,
804  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
805  errmsg("string is not a valid identifier: \"%s\"",
806  text_to_cstring(qualname))));
807  break;
808  }
809  }
810 
812 }
813 
814 /*
815  * pg_current_logfile
816  *
817  * Report current log file used by log collector by scanning current_logfiles.
818  */
819 Datum
821 {
822  FILE *fd;
823  char lbuffer[MAXPGPATH];
824  char *logfmt;
825 
826  /* The log format parameter is optional */
827  if (PG_NARGS() == 0 || PG_ARGISNULL(0))
828  logfmt = NULL;
829  else
830  {
831  logfmt = text_to_cstring(PG_GETARG_TEXT_PP(0));
832 
833  if (strcmp(logfmt, "stderr") != 0 &&
834  strcmp(logfmt, "csvlog") != 0 &&
835  strcmp(logfmt, "jsonlog") != 0)
836  ereport(ERROR,
837  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
838  errmsg("log format \"%s\" is not supported", logfmt),
839  errhint("The supported log formats are \"stderr\", \"csvlog\", and \"jsonlog\".")));
840  }
841 
843  if (fd == NULL)
844  {
845  if (errno != ENOENT)
846  ereport(ERROR,
848  errmsg("could not read file \"%s\": %m",
850  PG_RETURN_NULL();
851  }
852 
853 #ifdef WIN32
854  /* syslogger.c writes CRLF line endings on Windows */
855  _setmode(_fileno(fd), _O_TEXT);
856 #endif
857 
858  /*
859  * Read the file to gather current log filename(s) registered by the
860  * syslogger.
861  */
862  while (fgets(lbuffer, sizeof(lbuffer), fd) != NULL)
863  {
864  char *log_format;
865  char *log_filepath;
866  char *nlpos;
867 
868  /* Extract log format and log file path from the line. */
869  log_format = lbuffer;
870  log_filepath = strchr(lbuffer, ' ');
871  if (log_filepath == NULL)
872  {
873  /* Uh oh. No space found, so file content is corrupted. */
874  elog(ERROR,
875  "missing space character in \"%s\"", LOG_METAINFO_DATAFILE);
876  break;
877  }
878 
879  *log_filepath = '\0';
880  log_filepath++;
881  nlpos = strchr(log_filepath, '\n');
882  if (nlpos == NULL)
883  {
884  /* Uh oh. No newline found, so file content is corrupted. */
885  elog(ERROR,
886  "missing newline character in \"%s\"", LOG_METAINFO_DATAFILE);
887  break;
888  }
889  *nlpos = '\0';
890 
891  if (logfmt == NULL || strcmp(logfmt, log_format) == 0)
892  {
893  FreeFile(fd);
894  PG_RETURN_TEXT_P(cstring_to_text(log_filepath));
895  }
896  }
897 
898  /* Close the current log filename file. */
899  FreeFile(fd);
900 
901  PG_RETURN_NULL();
902 }
903 
904 /*
905  * Report current log file used by log collector (1 argument version)
906  *
907  * note: this wrapper is necessary to pass the sanity check in opr_sanity,
908  * which checks that all built-in functions that share the implementing C
909  * function take the same number of arguments
910  */
911 Datum
913 {
914  return pg_current_logfile(fcinfo);
915 }
916 
917 /*
918  * SQL wrapper around RelationGetReplicaIndex().
919  */
920 Datum
922 {
923  Oid reloid = PG_GETARG_OID(0);
924  Oid idxoid;
925  Relation rel;
926 
927  rel = table_open(reloid, AccessShareLock);
928  idxoid = RelationGetReplicaIndex(rel);
930 
931  if (OidIsValid(idxoid))
932  PG_RETURN_OID(idxoid);
933  else
934  PG_RETURN_NULL();
935 }
#define ARR_NDIM(a)
Definition: array.h:283
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:256
#define ARR_NULLBITMAP(a)
Definition: array.h:293
#define ARR_DIMS(a)
Definition: array.h:287
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5277
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5341
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:76
int16 AttrNumber
Definition: attnum.h:21
bool directory_is_empty(const char *path)
Definition: tablespace.c:859
Datum pg_typeof(PG_FUNCTION_ARGS)
Definition: misc.c:564
Datum parse_ident(PG_FUNCTION_ARGS)
Definition: misc.c:681
static bool count_nulls(FunctionCallInfo fcinfo, int32 *nargs, int32 *nulls)
Definition: misc.c:55
Datum pg_tablespace_databases(PG_FUNCTION_ARGS)
Definition: misc.c:203
#define GetNowFloat()
static bool is_ident_cont(unsigned char c)
Definition: misc.c:666
#define REQ_EVENTS
Datum current_query(PG_FUNCTION_ARGS)
Definition: misc.c:191
Datum pg_get_catalog_foreign_keys(PG_FUNCTION_ARGS)
Definition: misc.c:484
Datum pg_sleep(PG_FUNCTION_ARGS)
Definition: misc.c:349
Datum pg_get_replica_identity_index(PG_FUNCTION_ARGS)
Definition: misc.c:921
Datum pg_current_logfile(PG_FUNCTION_ARGS)
Definition: misc.c:820
Datum pg_get_keywords(PG_FUNCTION_ARGS)
Definition: misc.c:397
static bool is_ident_start(unsigned char c)
Definition: misc.c:648
Datum current_database(PG_FUNCTION_ARGS)
Definition: misc.c:174
Datum pg_column_is_updatable(PG_FUNCTION_ARGS)
Definition: misc.c:621
Datum pg_num_nulls(PG_FUNCTION_ARGS)
Definition: misc.c:141
Datum pg_current_logfile_1arg(PG_FUNCTION_ARGS)
Definition: misc.c:912
Datum pg_tablespace_location(PG_FUNCTION_ARGS)
Definition: misc.c:280
Datum pg_relation_is_updatable(PG_FUNCTION_ARGS)
Definition: misc.c:604
Datum pg_collation_for(PG_FUNCTION_ARGS)
Definition: misc.c:575
Datum pg_num_nonnulls(PG_FUNCTION_ARGS)
Definition: misc.c:157
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:186
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:85
#define unconstify(underlying_type, expr)
Definition: c.h:1181
NameData * Name
Definition: c.h:680
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1094
signed int int32
Definition: c.h:430
double float8
Definition: c.h:566
uint8 bits8
Definition: c.h:449
#define lengthof(array)
Definition: c.h:724
#define OidIsValid(objectId)
Definition: c.h:711
const uint8 ScanKeywordCategories[SCANKEYWORDS_NUM_KEYWORDS]
Definition: keywords.c:29
const bool ScanKeywordBareLabel[SCANKEYWORDS_NUM_KEYWORDS]
Definition: keywords.c:42
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2981
int errcode_for_file_access(void)
Definition: elog.c:718
int errdetail(const char *fmt,...)
Definition: elog.c:1039
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define _(x)
Definition: elog.c:90
#define WARNING
Definition: elog.h:32
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2071
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2135
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2086
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2709
int FreeDir(DIR *dir)
Definition: fd.c:2761
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2383
int FreeFile(FILE *file)
Definition: fd.c:2581
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2643
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
bool get_fn_expr_variadic(FmgrInfo *flinfo)
Definition: fmgr.c:1920
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1786
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_GETARG_FLOAT8(n)
Definition: fmgr.h:282
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_NARGS()
Definition: fmgr.h:203
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define PG_RETURN_NAME(x)
Definition: fmgr.h:363
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
#define PG_GET_COLLATION()
Definition: fmgr.h:198
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition: fmgr.h:664
#define PG_RETURN_OID(x)
Definition: fmgr.h:360
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
#define PG_GETARG_INT16(n)
Definition: fmgr.h:271
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:303
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:307
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:309
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:305
static Datum HeapTupleGetDatum(const HeapTupleData *tuple)
Definition: funcapi.h:230
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:327
#define MAT_SRF_USE_EXPECTED_DESC
Definition: funcapi.h:295
Oid MyDatabaseTableSpace
Definition: globals.c:91
struct Latch * MyLatch
Definition: globals.c:58
Oid MyDatabaseId
Definition: globals.c:89
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
PGDLLIMPORT const ScanKeywordList ScanKeywords
#define COL_NAME_KEYWORD
Definition: keywords.h:21
#define UNRESERVED_KEYWORD
Definition: keywords.h:20
#define TYPE_FUNC_NAME_KEYWORD
Definition: keywords.h:22
#define RESERVED_KEYWORD
Definition: keywords.h:23
static const char * GetScanKeyword(int n, const ScanKeywordList *keywords)
Definition: kwlookup.h:39
void ResetLatch(Latch *latch)
Definition: latch.c:683
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:476
#define WL_TIMEOUT
Definition: latch.h:128
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
Assert(fmt[strlen(fmt) - 1] !='\n')
#define AccessShareLock
Definition: lockdefs.h:36
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:3039
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2790
void pfree(void *pointer)
Definition: mcxt.c:1306
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
void * palloc(Size size)
Definition: mcxt.c:1199
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
void namestrcpy(Name name, const char *str)
Definition: name.c:233
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
int16 attnum
Definition: pg_attribute.h:83
#define NAMEDATALEN
#define MAXPGPATH
const void size_t len
#define NIL
Definition: pg_list.h:66
#define snprintf
Definition: port.h:238
const char * debug_query_string
Definition: postgres.c:82
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
uintptr_t Datum
Definition: postgres.h:412
static Datum BoolGetDatum(bool X)
Definition: postgres.h:450
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:698
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:560
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define atooid(x)
Definition: postgres_ext.h:42
char * c
static int fd(const char *x, int i)
Definition: preproc-init.c:105
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4947
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:33
int relation_is_updatable(Oid reloid, List *outer_reloids, bool include_triggers, Bitmapset *include_cols)
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:12041
bool scanner_isspace(char ch)
Definition: scansup.c:117
char * downcase_identifier(const char *ident, int len, bool warn, bool truncate)
Definition: scansup.c:46
Definition: dirent.c:26
Definition: fmgr.h:57
void * user_fctx
Definition: funcapi.h:82
uint64 call_cntr
Definition: funcapi.h:65
AttInMetadata * attinmeta
Definition: funcapi.h:91
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
TupleDesc tuple_desc
Definition: funcapi.h:112
FmgrInfo * flinfo
Definition: fmgr.h:87
TupleDesc setDesc
Definition: execnodes.h:332
Tuplestorestate * setResult
Definition: execnodes.h:331
int num_keywords
Definition: kwlookup.h:30
Definition: dirent.h:10
Definition: c.h:677
unsigned short st_mode
Definition: win32_port.h:270
Definition: c.h:623
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:100
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:583
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
char * text_to_cstring(const text *t)
Definition: varlena.c:222
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:201
text * cstring_to_text(const char *s)
Definition: varlena.c:189
@ WAIT_EVENT_PG_SLEEP
Definition: wait_event.h:144
#define lstat(path, sb)
Definition: win32_port.h:287
#define S_ISLNK(m)
Definition: win32_port.h:346
#define readlink(path, buf, size)
Definition: win32_port.h:238