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-2018, 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 <signal.h>
19 #include <dirent.h>
20 #include <math.h>
21 #include <unistd.h>
22 
23 #include "access/sysattr.h"
24 #include "catalog/pg_authid.h"
25 #include "catalog/catalog.h"
26 #include "catalog/pg_tablespace.h"
27 #include "catalog/pg_type.h"
28 #include "commands/dbcommands.h"
29 #include "commands/tablespace.h"
30 #include "common/keywords.h"
31 #include "funcapi.h"
32 #include "miscadmin.h"
33 #include "pgstat.h"
34 #include "parser/scansup.h"
35 #include "postmaster/syslogger.h"
36 #include "rewrite/rewriteHandler.h"
37 #include "storage/fd.h"
38 #include "storage/pmsignal.h"
39 #include "storage/proc.h"
40 #include "storage/procarray.h"
41 #include "utils/lsyscache.h"
42 #include "utils/ruleutils.h"
43 #include "tcop/tcopprot.h"
44 #include "utils/acl.h"
45 #include "utils/builtins.h"
46 #include "utils/timestamp.h"
47 
48 
49 /*
50  * Common subroutine for num_nulls() and num_nonnulls().
51  * Returns true if successful, false if function should return NULL.
52  * If successful, total argument count and number of nulls are
53  * returned into *nargs and *nulls.
54  */
55 static bool
57  int32 *nargs, int32 *nulls)
58 {
59  int32 count = 0;
60  int i;
61 
62  /* Did we get a VARIADIC array argument, or separate arguments? */
63  if (get_fn_expr_variadic(fcinfo->flinfo))
64  {
65  ArrayType *arr;
66  int ndims,
67  nitems,
68  *dims;
69  bits8 *bitmap;
70 
71  Assert(PG_NARGS() == 1);
72 
73  /*
74  * If we get a null as VARIADIC array argument, we can't say anything
75  * useful about the number of elements, so return NULL. This behavior
76  * is consistent with other variadic functions - see concat_internal.
77  */
78  if (PG_ARGISNULL(0))
79  return false;
80 
81  /*
82  * Non-null argument had better be an array. We assume that any call
83  * context that could let get_fn_expr_variadic return true will have
84  * checked that a VARIADIC-labeled parameter actually is an array. So
85  * it should be okay to just Assert that it's an array rather than
86  * doing a full-fledged error check.
87  */
89 
90  /* OK, safe to fetch the array value */
91  arr = PG_GETARG_ARRAYTYPE_P(0);
92 
93  /* Count the array elements */
94  ndims = ARR_NDIM(arr);
95  dims = ARR_DIMS(arr);
96  nitems = ArrayGetNItems(ndims, dims);
97 
98  /* Count those that are NULL */
99  bitmap = ARR_NULLBITMAP(arr);
100  if (bitmap)
101  {
102  int bitmask = 1;
103 
104  for (i = 0; i < nitems; i++)
105  {
106  if ((*bitmap & bitmask) == 0)
107  count++;
108 
109  bitmask <<= 1;
110  if (bitmask == 0x100)
111  {
112  bitmap++;
113  bitmask = 1;
114  }
115  }
116  }
117 
118  *nargs = nitems;
119  *nulls = count;
120  }
121  else
122  {
123  /* Separate arguments, so just count 'em */
124  for (i = 0; i < PG_NARGS(); i++)
125  {
126  if (PG_ARGISNULL(i))
127  count++;
128  }
129 
130  *nargs = PG_NARGS();
131  *nulls = count;
132  }
133 
134  return true;
135 }
136 
137 /*
138  * num_nulls()
139  * Count the number of NULL arguments
140  */
141 Datum
143 {
144  int32 nargs,
145  nulls;
146 
147  if (!count_nulls(fcinfo, &nargs, &nulls))
148  PG_RETURN_NULL();
149 
150  PG_RETURN_INT32(nulls);
151 }
152 
153 /*
154  * num_nonnulls()
155  * Count the number of non-NULL arguments
156  */
157 Datum
159 {
160  int32 nargs,
161  nulls;
162 
163  if (!count_nulls(fcinfo, &nargs, &nulls))
164  PG_RETURN_NULL();
165 
166  PG_RETURN_INT32(nargs - nulls);
167 }
168 
169 
170 /*
171  * current_database()
172  * Expose the current database to the user
173  */
174 Datum
176 {
177  Name db;
178 
179  db = (Name) palloc(NAMEDATALEN);
180 
182  PG_RETURN_NAME(db);
183 }
184 
185 
186 /*
187  * current_query()
188  * Expose the current query to the user (useful in stored procedures)
189  * We might want to use ActivePortal->sourceText someday.
190  */
191 Datum
193 {
194  /* there is no easy way to access the more concise 'query_string' */
195  if (debug_query_string)
197  else
198  PG_RETURN_NULL();
199 }
200 
201 /*
202  * Send a signal to another backend.
203  *
204  * The signal is delivered if the user is either a superuser or the same
205  * role as the backend being signaled. For "dangerous" signals, an explicit
206  * check for superuser needs to be done prior to calling this function.
207  *
208  * Returns 0 on success, 1 on general failure, 2 on normal permission error
209  * and 3 if the caller needs to be a superuser.
210  *
211  * In the event of a general failure (return code 1), a warning message will
212  * be emitted. For permission errors, doing that is the responsibility of
213  * the caller.
214  */
215 #define SIGNAL_BACKEND_SUCCESS 0
216 #define SIGNAL_BACKEND_ERROR 1
217 #define SIGNAL_BACKEND_NOPERMISSION 2
218 #define SIGNAL_BACKEND_NOSUPERUSER 3
219 static int
220 pg_signal_backend(int pid, int sig)
221 {
222  PGPROC *proc = BackendPidGetProc(pid);
223 
224  /*
225  * BackendPidGetProc returns NULL if the pid isn't valid; but by the time
226  * we reach kill(), a process for which we get a valid proc here might
227  * have terminated on its own. There's no way to acquire a lock on an
228  * arbitrary process to prevent that. But since so far all the callers of
229  * this mechanism involve some request for ending the process anyway, that
230  * it might end on its own first is not a problem.
231  */
232  if (proc == NULL)
233  {
234  /*
235  * This is just a warning so a loop-through-resultset will not abort
236  * if one backend terminated on its own during the run.
237  */
239  (errmsg("PID %d is not a PostgreSQL server process", pid)));
240  return SIGNAL_BACKEND_ERROR;
241  }
242 
243  /* Only allow superusers to signal superuser-owned backends. */
244  if (superuser_arg(proc->roleId) && !superuser())
246 
247  /* Users can signal backends they have role membership in. */
248  if (!has_privs_of_role(GetUserId(), proc->roleId) &&
249  !has_privs_of_role(GetUserId(), DEFAULT_ROLE_SIGNAL_BACKENDID))
251 
252  /*
253  * Can the process we just validated above end, followed by the pid being
254  * recycled for a new process, before reaching here? Then we'd be trying
255  * to kill the wrong thing. Seems near impossible when sequential pid
256  * assignment and wraparound is used. Perhaps it could happen on a system
257  * where pid re-use is randomized. That race condition possibility seems
258  * too unlikely to worry about.
259  */
260 
261  /* If we have setsid(), signal the backend's whole process group */
262 #ifdef HAVE_SETSID
263  if (kill(-pid, sig))
264 #else
265  if (kill(pid, sig))
266 #endif
267  {
268  /* Again, just a warning to allow loops */
270  (errmsg("could not send signal to process %d: %m", pid)));
271  return SIGNAL_BACKEND_ERROR;
272  }
273  return SIGNAL_BACKEND_SUCCESS;
274 }
275 
276 /*
277  * Signal to cancel a backend process. This is allowed if you are a member of
278  * the role whose process is being canceled.
279  *
280  * Note that only superusers can signal superuser-owned processes.
281  */
282 Datum
284 {
285  int r = pg_signal_backend(PG_GETARG_INT32(0), SIGINT);
286 
288  ereport(ERROR,
289  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
290  (errmsg("must be a superuser to cancel superuser query"))));
291 
293  ereport(ERROR,
294  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
295  (errmsg("must be a member of the role whose query is being canceled or member of pg_signal_backend"))));
296 
298 }
299 
300 /*
301  * Signal to terminate a backend process. This is allowed if you are a member
302  * of the role whose process is being terminated.
303  *
304  * Note that only superusers can signal superuser-owned processes.
305  */
306 Datum
308 {
309  int r = pg_signal_backend(PG_GETARG_INT32(0), SIGTERM);
310 
312  ereport(ERROR,
313  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
314  (errmsg("must be a superuser to terminate superuser process"))));
315 
317  ereport(ERROR,
318  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
319  (errmsg("must be a member of the role whose process is being terminated or member of pg_signal_backend"))));
320 
322 }
323 
324 /*
325  * Signal to reload the database configuration
326  *
327  * Permission checking for this function is managed through the normal
328  * GRANT system.
329  */
330 Datum
332 {
333  if (kill(PostmasterPid, SIGHUP))
334  {
336  (errmsg("failed to send signal to postmaster: %m")));
337  PG_RETURN_BOOL(false);
338  }
339 
340  PG_RETURN_BOOL(true);
341 }
342 
343 
344 /*
345  * Rotate log file
346  *
347  * This function is kept to support adminpack 1.0.
348  */
349 Datum
351 {
352  if (!superuser())
353  ereport(ERROR,
354  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
355  (errmsg("must be superuser to rotate log files with adminpack 1.0"),
356  errhint("Consider using pg_logfile_rotate(), which is part of core, instead."))));
357 
358  if (!Logging_collector)
359  {
361  (errmsg("rotation not possible because log collection not active")));
362  PG_RETURN_BOOL(false);
363  }
364 
366  PG_RETURN_BOOL(true);
367 }
368 
369 /*
370  * Rotate log file
371  *
372  * Permission checking for this function is managed through the normal
373  * GRANT system.
374  */
375 Datum
377 {
378  if (!Logging_collector)
379  {
381  (errmsg("rotation not possible because log collection not active")));
382  PG_RETURN_BOOL(false);
383  }
384 
386  PG_RETURN_BOOL(true);
387 }
388 
389 /* Function to find out which databases make use of a tablespace */
390 
391 typedef struct
392 {
393  char *location;
395 } ts_db_fctx;
396 
397 Datum
399 {
400  FuncCallContext *funcctx;
401  struct dirent *de;
402  ts_db_fctx *fctx;
403 
404  if (SRF_IS_FIRSTCALL())
405  {
406  MemoryContext oldcontext;
407  Oid tablespaceOid = PG_GETARG_OID(0);
408 
409  funcctx = SRF_FIRSTCALL_INIT();
410  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
411 
412  fctx = palloc(sizeof(ts_db_fctx));
413 
414  if (tablespaceOid == GLOBALTABLESPACE_OID)
415  {
416  fctx->dirdesc = NULL;
418  (errmsg("global tablespace never has databases")));
419  }
420  else
421  {
422  if (tablespaceOid == DEFAULTTABLESPACE_OID)
423  fctx->location = psprintf("base");
424  else
425  fctx->location = psprintf("pg_tblspc/%u/%s", tablespaceOid,
427 
428  fctx->dirdesc = AllocateDir(fctx->location);
429 
430  if (!fctx->dirdesc)
431  {
432  /* the only expected error is ENOENT */
433  if (errno != ENOENT)
434  ereport(ERROR,
436  errmsg("could not open directory \"%s\": %m",
437  fctx->location)));
439  (errmsg("%u is not a tablespace OID", tablespaceOid)));
440  }
441  }
442  funcctx->user_fctx = fctx;
443  MemoryContextSwitchTo(oldcontext);
444  }
445 
446  funcctx = SRF_PERCALL_SETUP();
447  fctx = (ts_db_fctx *) funcctx->user_fctx;
448 
449  if (!fctx->dirdesc) /* not a tablespace */
450  SRF_RETURN_DONE(funcctx);
451 
452  while ((de = ReadDir(fctx->dirdesc, fctx->location)) != NULL)
453  {
454  Oid datOid = atooid(de->d_name);
455  char *subdir;
456  bool isempty;
457 
458  /* this test skips . and .., but is awfully weak */
459  if (!datOid)
460  continue;
461 
462  /* if database subdir is empty, don't report tablespace as used */
463 
464  subdir = psprintf("%s/%s", fctx->location, de->d_name);
465  isempty = directory_is_empty(subdir);
466  pfree(subdir);
467 
468  if (isempty)
469  continue; /* indeed, nothing in it */
470 
471  SRF_RETURN_NEXT(funcctx, ObjectIdGetDatum(datOid));
472  }
473 
474  FreeDir(fctx->dirdesc);
475  SRF_RETURN_DONE(funcctx);
476 }
477 
478 
479 /*
480  * pg_tablespace_location - get location for a tablespace
481  */
482 Datum
484 {
485  Oid tablespaceOid = PG_GETARG_OID(0);
486  char sourcepath[MAXPGPATH];
487  char targetpath[MAXPGPATH];
488  int rllen;
489 
490  /*
491  * It's useful to apply this function to pg_class.reltablespace, wherein
492  * zero means "the database's default tablespace". So, rather than
493  * throwing an error for zero, we choose to assume that's what is meant.
494  */
495  if (tablespaceOid == InvalidOid)
496  tablespaceOid = MyDatabaseTableSpace;
497 
498  /*
499  * Return empty string for the cluster's default tablespaces
500  */
501  if (tablespaceOid == DEFAULTTABLESPACE_OID ||
502  tablespaceOid == GLOBALTABLESPACE_OID)
504 
505 #if defined(HAVE_READLINK) || defined(WIN32)
506 
507  /*
508  * Find the location of the tablespace by reading the symbolic link that
509  * is in pg_tblspc/<oid>.
510  */
511  snprintf(sourcepath, sizeof(sourcepath), "pg_tblspc/%u", tablespaceOid);
512 
513  rllen = readlink(sourcepath, targetpath, sizeof(targetpath));
514  if (rllen < 0)
515  ereport(ERROR,
517  errmsg("could not read symbolic link \"%s\": %m",
518  sourcepath)));
519  if (rllen >= sizeof(targetpath))
520  ereport(ERROR,
521  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
522  errmsg("symbolic link \"%s\" target is too long",
523  sourcepath)));
524  targetpath[rllen] = '\0';
525 
526  PG_RETURN_TEXT_P(cstring_to_text(targetpath));
527 #else
528  ereport(ERROR,
529  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
530  errmsg("tablespaces are not supported on this platform")));
531  PG_RETURN_NULL();
532 #endif
533 }
534 
535 /*
536  * pg_sleep - delay for N seconds
537  */
538 Datum
540 {
541  float8 secs = PG_GETARG_FLOAT8(0);
542  float8 endtime;
543 
544  /*
545  * We sleep using WaitLatch, to ensure that we'll wake up promptly if an
546  * important signal (such as SIGALRM or SIGINT) arrives. Because
547  * WaitLatch's upper limit of delay is INT_MAX milliseconds, and the user
548  * might ask for more than that, we sleep for at most 10 minutes and then
549  * loop.
550  *
551  * By computing the intended stop time initially, we avoid accumulation of
552  * extra delay across multiple sleeps. This also ensures we won't delay
553  * less than the specified time when WaitLatch is terminated early by a
554  * non-query-canceling signal such as SIGHUP.
555  */
556 #define GetNowFloat() ((float8) GetCurrentTimestamp() / 1000000.0)
557 
558  endtime = GetNowFloat() + secs;
559 
560  for (;;)
561  {
562  float8 delay;
563  long delay_ms;
564 
566 
567  delay = endtime - GetNowFloat();
568  if (delay >= 600.0)
569  delay_ms = 600000;
570  else if (delay > 0.0)
571  delay_ms = (long) ceil(delay * 1000.0);
572  else
573  break;
574 
575  (void) WaitLatch(MyLatch,
577  delay_ms,
580  }
581 
582  PG_RETURN_VOID();
583 }
584 
585 /* Function to return the list of grammar keywords */
586 Datum
588 {
589  FuncCallContext *funcctx;
590 
591  if (SRF_IS_FIRSTCALL())
592  {
593  MemoryContext oldcontext;
594  TupleDesc tupdesc;
595 
596  funcctx = SRF_FIRSTCALL_INIT();
597  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
598 
599  tupdesc = CreateTemplateTupleDesc(3, false);
600  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "word",
601  TEXTOID, -1, 0);
602  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "catcode",
603  CHAROID, -1, 0);
604  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "catdesc",
605  TEXTOID, -1, 0);
606 
607  funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
608 
609  MemoryContextSwitchTo(oldcontext);
610  }
611 
612  funcctx = SRF_PERCALL_SETUP();
613 
614  if (funcctx->call_cntr < NumScanKeywords)
615  {
616  char *values[3];
617  HeapTuple tuple;
618 
619  /* cast-away-const is ugly but alternatives aren't much better */
620  values[0] = (char *) ScanKeywords[funcctx->call_cntr].name;
621 
622  switch (ScanKeywords[funcctx->call_cntr].category)
623  {
624  case UNRESERVED_KEYWORD:
625  values[1] = "U";
626  values[2] = _("unreserved");
627  break;
628  case COL_NAME_KEYWORD:
629  values[1] = "C";
630  values[2] = _("unreserved (cannot be function or type name)");
631  break;
633  values[1] = "T";
634  values[2] = _("reserved (can be function or type name)");
635  break;
636  case RESERVED_KEYWORD:
637  values[1] = "R";
638  values[2] = _("reserved");
639  break;
640  default: /* shouldn't be possible */
641  values[1] = NULL;
642  values[2] = NULL;
643  break;
644  }
645 
646  tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
647 
648  SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
649  }
650 
651  SRF_RETURN_DONE(funcctx);
652 }
653 
654 
655 /*
656  * Return the type of the argument.
657  */
658 Datum
660 {
661  PG_RETURN_OID(get_fn_expr_argtype(fcinfo->flinfo, 0));
662 }
663 
664 
665 /*
666  * Implementation of the COLLATE FOR expression; returns the collation
667  * of the argument.
668  */
669 Datum
671 {
672  Oid typeid;
673  Oid collid;
674 
675  typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
676  if (!typeid)
677  PG_RETURN_NULL();
678  if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
679  ereport(ERROR,
680  (errcode(ERRCODE_DATATYPE_MISMATCH),
681  errmsg("collations are not supported by type %s",
682  format_type_be(typeid))));
683 
684  collid = PG_GET_COLLATION();
685  if (!collid)
686  PG_RETURN_NULL();
688 }
689 
690 
691 /*
692  * pg_relation_is_updatable - determine which update events the specified
693  * relation supports.
694  *
695  * This relies on relation_is_updatable() in rewriteHandler.c, which see
696  * for additional information.
697  */
698 Datum
700 {
701  Oid reloid = PG_GETARG_OID(0);
702  bool include_triggers = PG_GETARG_BOOL(1);
703 
704  PG_RETURN_INT32(relation_is_updatable(reloid, include_triggers, NULL));
705 }
706 
707 /*
708  * pg_column_is_updatable - determine whether a column is updatable
709  *
710  * This function encapsulates the decision about just what
711  * information_schema.columns.is_updatable actually means. It's not clear
712  * whether deletability of the column's relation should be required, so
713  * we want that decision in C code where we could change it without initdb.
714  */
715 Datum
717 {
718  Oid reloid = PG_GETARG_OID(0);
721  bool include_triggers = PG_GETARG_BOOL(2);
722  int events;
723 
724  /* System columns are never updatable */
725  if (attnum <= 0)
726  PG_RETURN_BOOL(false);
727 
728  events = relation_is_updatable(reloid, include_triggers,
729  bms_make_singleton(col));
730 
731  /* We require both updatability and deletability of the relation */
732 #define REQ_EVENTS ((1 << CMD_UPDATE) | (1 << CMD_DELETE))
733 
734  PG_RETURN_BOOL((events & REQ_EVENTS) == REQ_EVENTS);
735 }
736 
737 
738 /*
739  * Is character a valid identifier start?
740  * Must match scan.l's {ident_start} character class.
741  */
742 static bool
743 is_ident_start(unsigned char c)
744 {
745  /* Underscores and ASCII letters are OK */
746  if (c == '_')
747  return true;
748  if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
749  return true;
750  /* Any high-bit-set character is OK (might be part of a multibyte char) */
751  if (IS_HIGHBIT_SET(c))
752  return true;
753  return false;
754 }
755 
756 /*
757  * Is character a valid identifier continuation?
758  * Must match scan.l's {ident_cont} character class.
759  */
760 static bool
761 is_ident_cont(unsigned char c)
762 {
763  /* Can be digit or dollar sign ... */
764  if ((c >= '0' && c <= '9') || c == '$')
765  return true;
766  /* ... or an identifier start character */
767  return is_ident_start(c);
768 }
769 
770 /*
771  * parse_ident - parse a SQL qualified identifier into separate identifiers.
772  * When strict mode is active (second parameter), then any chars after
773  * the last identifier are disallowed.
774  */
775 Datum
777 {
778  text *qualname = PG_GETARG_TEXT_PP(0);
779  bool strict = PG_GETARG_BOOL(1);
780  char *qualname_str = text_to_cstring(qualname);
781  ArrayBuildState *astate = NULL;
782  char *nextp;
783  bool after_dot = false;
784 
785  /*
786  * The code below scribbles on qualname_str in some cases, so we should
787  * reconvert qualname if we need to show the original string in error
788  * messages.
789  */
790  nextp = qualname_str;
791 
792  /* skip leading whitespace */
793  while (scanner_isspace(*nextp))
794  nextp++;
795 
796  for (;;)
797  {
798  char *curname;
799  bool missing_ident = true;
800 
801  if (*nextp == '"')
802  {
803  char *endp;
804 
805  curname = nextp + 1;
806  for (;;)
807  {
808  endp = strchr(nextp + 1, '"');
809  if (endp == NULL)
810  ereport(ERROR,
811  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
812  errmsg("string is not a valid identifier: \"%s\"",
813  text_to_cstring(qualname)),
814  errdetail("String has unclosed double quotes.")));
815  if (endp[1] != '"')
816  break;
817  memmove(endp, endp + 1, strlen(endp));
818  nextp = endp;
819  }
820  nextp = endp + 1;
821  *endp = '\0';
822 
823  if (endp - curname == 0)
824  ereport(ERROR,
825  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
826  errmsg("string is not a valid identifier: \"%s\"",
827  text_to_cstring(qualname)),
828  errdetail("Quoted identifier must not be empty.")));
829 
830  astate = accumArrayResult(astate, CStringGetTextDatum(curname),
831  false, TEXTOID, CurrentMemoryContext);
832  missing_ident = false;
833  }
834  else if (is_ident_start((unsigned char) *nextp))
835  {
836  char *downname;
837  int len;
838  text *part;
839 
840  curname = nextp++;
841  while (is_ident_cont((unsigned char) *nextp))
842  nextp++;
843 
844  len = nextp - curname;
845 
846  /*
847  * We don't implicitly truncate identifiers. This is useful for
848  * allowing the user to check for specific parts of the identifier
849  * being too long. It's easy enough for the user to get the
850  * truncated names by casting our output to name[].
851  */
852  downname = downcase_identifier(curname, len, false, false);
853  part = cstring_to_text_with_len(downname, len);
854  astate = accumArrayResult(astate, PointerGetDatum(part), false,
855  TEXTOID, CurrentMemoryContext);
856  missing_ident = false;
857  }
858 
859  if (missing_ident)
860  {
861  /* Different error messages based on where we failed. */
862  if (*nextp == '.')
863  ereport(ERROR,
864  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
865  errmsg("string is not a valid identifier: \"%s\"",
866  text_to_cstring(qualname)),
867  errdetail("No valid identifier before \".\".")));
868  else if (after_dot)
869  ereport(ERROR,
870  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
871  errmsg("string is not a valid identifier: \"%s\"",
872  text_to_cstring(qualname)),
873  errdetail("No valid identifier after \".\".")));
874  else
875  ereport(ERROR,
876  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
877  errmsg("string is not a valid identifier: \"%s\"",
878  text_to_cstring(qualname))));
879  }
880 
881  while (scanner_isspace(*nextp))
882  nextp++;
883 
884  if (*nextp == '.')
885  {
886  after_dot = true;
887  nextp++;
888  while (scanner_isspace(*nextp))
889  nextp++;
890  }
891  else if (*nextp == '\0')
892  {
893  break;
894  }
895  else
896  {
897  if (strict)
898  ereport(ERROR,
899  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
900  errmsg("string is not a valid identifier: \"%s\"",
901  text_to_cstring(qualname))));
902  break;
903  }
904  }
905 
907 }
908 
909 /*
910  * pg_current_logfile
911  *
912  * Report current log file used by log collector by scanning current_logfiles.
913  */
914 Datum
916 {
917  FILE *fd;
918  char lbuffer[MAXPGPATH];
919  char *logfmt;
920  char *log_filepath;
921  char *log_format = lbuffer;
922  char *nlpos;
923 
924  /* The log format parameter is optional */
925  if (PG_NARGS() == 0 || PG_ARGISNULL(0))
926  logfmt = NULL;
927  else
928  {
929  logfmt = text_to_cstring(PG_GETARG_TEXT_PP(0));
930 
931  if (strcmp(logfmt, "stderr") != 0 && strcmp(logfmt, "csvlog") != 0)
932  ereport(ERROR,
933  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
934  errmsg("log format \"%s\" is not supported", logfmt),
935  errhint("The supported log formats are \"stderr\" and \"csvlog\".")));
936  }
937 
939  if (fd == NULL)
940  {
941  if (errno != ENOENT)
942  ereport(ERROR,
944  errmsg("could not read file \"%s\": %m",
946  PG_RETURN_NULL();
947  }
948 
949  /*
950  * Read the file to gather current log filename(s) registered by the
951  * syslogger.
952  */
953  while (fgets(lbuffer, sizeof(lbuffer), fd) != NULL)
954  {
955  /*
956  * Extract log format and log file path from the line; lbuffer ==
957  * log_format, they share storage.
958  */
959  log_filepath = strchr(lbuffer, ' ');
960  if (log_filepath == NULL)
961  {
962  /* Uh oh. No space found, so file content is corrupted. */
963  elog(ERROR,
964  "missing space character in \"%s\"", LOG_METAINFO_DATAFILE);
965  break;
966  }
967 
968  *log_filepath = '\0';
969  log_filepath++;
970  nlpos = strchr(log_filepath, '\n');
971  if (nlpos == NULL)
972  {
973  /* Uh oh. No newline found, so file content is corrupted. */
974  elog(ERROR,
975  "missing newline character in \"%s\"", LOG_METAINFO_DATAFILE);
976  break;
977  }
978  *nlpos = '\0';
979 
980  if (logfmt == NULL || strcmp(logfmt, log_format) == 0)
981  {
982  FreeFile(fd);
983  PG_RETURN_TEXT_P(cstring_to_text(log_filepath));
984  }
985  }
986 
987  /* Close the current log filename file. */
988  FreeFile(fd);
989 
990  PG_RETURN_NULL();
991 }
992 
993 /*
994  * Report current log file used by log collector (1 argument version)
995  *
996  * note: this wrapper is necessary to pass the sanity check in opr_sanity,
997  * which checks that all built-in functions that share the implementing C
998  * function take the same number of arguments
999  */
1000 Datum
1002 {
1003  return pg_current_logfile(fcinfo);
1004 }
1005 
1006 /*
1007  * SQL wrapper around RelationGetReplicaIndex().
1008  */
1009 Datum
1011 {
1012  Oid reloid = PG_GETARG_OID(0);
1013  Oid idxoid;
1014  Relation rel;
1015 
1016  rel = heap_open(reloid, AccessShareLock);
1017  idxoid = RelationGetReplicaIndex(rel);
1019 
1020  if (OidIsValid(idxoid))
1021  PG_RETURN_OID(idxoid);
1022  else
1023  PG_RETURN_NULL();
1024 }
#define PG_GETARG_FLOAT8(n)
Definition: fmgr.h:251
uint64 call_cntr
Definition: funcapi.h:66
#define PG_GETARG_INT32(n)
Definition: fmgr.h:239
static bool is_ident_start(unsigned char c)
Definition: misc.c:743
Datum pg_get_replica_identity_index(PG_FUNCTION_ARGS)
Definition: misc.c:1010
Datum pg_rotate_logfile(PG_FUNCTION_ARGS)
Definition: misc.c:350
int errhint(const char *fmt,...)
Definition: elog.c:987
Datum pg_relation_is_updatable(PG_FUNCTION_ARGS)
Definition: misc.c:699
Datum parse_ident(PG_FUNCTION_ARGS)
Definition: misc.c:776
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4521
#define WL_TIMEOUT
Definition: latch.h:127
static bool count_nulls(FunctionCallInfo fcinfo, int32 *nargs, int32 *nulls)
Definition: misc.c:56
Oid GetUserId(void)
Definition: miscinit.c:379
PGPROC * BackendPidGetProc(int pid)
Definition: procarray.c:2346
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:294
#define PointerGetDatum(X)
Definition: postgres.h:539
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4833
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define PG_RETURN_INT32(x)
Definition: fmgr.h:319
const int NumScanKeywords
Definition: keywords.c:45
#define AccessShareLock
Definition: lockdefs.h:36
Datum pg_collation_for(PG_FUNCTION_ARGS)
Definition: misc.c:670
bool get_fn_expr_variadic(FmgrInfo *flinfo)
Definition: fmgr.c:2128
Oid roleId
Definition: proc.h:115
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:94
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
#define kill(pid, sig)
Definition: win32_port.h:437
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
bool directory_is_empty(const char *path)
Definition: tablespace.c:833
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
#define UNRESERVED_KEYWORD
Definition: keywords.h:18
#define heap_close(r, l)
Definition: heapam.h:97
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:244
void ResetLatch(volatile Latch *latch)
Definition: latch.c:497
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:216
Definition: dirent.h:9
#define OidIsValid(objectId)
Definition: c.h:605
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:298
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_GET_COLLATION()
Definition: fmgr.h:168
Datum pg_typeof(PG_FUNCTION_ARGS)
Definition: misc.c:659
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:11011
signed int int32
Definition: c.h:313
Oid MyDatabaseTableSpace
Definition: globals.c:88
bool Logging_collector
Definition: syslogger.c:64
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:1195
Datum current_database(PG_FUNCTION_ARGS)
Definition: misc.c:175
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
Datum current_query(PG_FUNCTION_ARGS)
Definition: misc.c:192
#define NAMEDATALEN
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:300
FmgrInfo * flinfo
Definition: fmgr.h:79
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:248
#define GetNowFloat()
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
void pfree(void *pointer)
Definition: mcxt.c:1031
Datum pg_current_logfile(PG_FUNCTION_ARGS)
Definition: misc.c:915
#define IS_HIGHBIT_SET(ch)
Definition: c.h:994
Datum pg_tablespace_location(PG_FUNCTION_ARGS)
Definition: misc.c:483
Definition: dirent.c:25
#define ObjectIdGetDatum(X)
Definition: postgres.h:490
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:458
Datum pg_num_nulls(PG_FUNCTION_ARGS)
Definition: misc.c:142
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1994
#define SIGNAL_BACKEND_SUCCESS
Definition: misc.c:215
#define ARR_DIMS(a)
Definition: array.h:279
#define MAXPGPATH
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
Definition: c.h:570
#define TYPE_FUNC_NAME_KEYWORD
Definition: keywords.h:20
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:26
char * c
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:245
int relation_is_updatable(Oid reloid, bool include_triggers, Bitmapset *include_cols)
const ScanKeyword ScanKeywords[]
Definition: keywords.c:41
#define memmove(d, s, c)
Definition: c.h:1100
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:161
#define PG_GETARG_OID(n)
Definition: fmgr.h:245
#define readlink(path, buf, size)
Definition: win32_port.h:233
AttInMetadata * attinmeta
Definition: funcapi.h:100
const char * name
Definition: keywords.h:26
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
#define SIGHUP
Definition: win32_port.h:163
Datum pg_terminate_backend(PG_FUNCTION_ARGS)
Definition: misc.c:307
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2346
Datum pg_current_logfile_1arg(PG_FUNCTION_ARGS)
Definition: misc.c:1001
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2600
Datum pg_sleep(PG_FUNCTION_ARGS)
Definition: misc.c:539
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define SIGNAL_BACKEND_NOPERMISSION
Definition: misc.c:217
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:600
#define atooid(x)
Definition: postgres_ext.h:42
Datum pg_tablespace_databases(PG_FUNCTION_ARGS)
Definition: misc.c:398
#define ereport(elevel, rest)
Definition: elog.h:122
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5106
bool superuser_arg(Oid roleid)
Definition: superuser.c:57
pid_t PostmasterPid
Definition: globals.c:96
#define WARNING
Definition: elog.h:40
const char * debug_query_string
Definition: postgres.c:86
Datum pg_num_nonnulls(PG_FUNCTION_ARGS)
Definition: misc.c:158
uint8 bits8
Definition: c.h:332
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:324
uintptr_t Datum
Definition: postgres.h:365
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:318
Datum pg_reload_conf(PG_FUNCTION_ARGS)
Definition: misc.c:331
Oid MyDatabaseId
Definition: globals.c:86
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:1146
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
bool scanner_isspace(char ch)
Definition: scansup.c:221
#define PG_GETARG_INT16(n)
Definition: fmgr.h:241
#define REQ_EVENTS
static int sig
Definition: pg_ctl.c:81
#define RESERVED_KEYWORD
Definition: keywords.h:21
#define InvalidOid
Definition: postgres_ext.h:36
char * downcase_identifier(const char *ident, int len, bool warn, bool truncate)
Definition: scansup.c:140
int16 attnum
Definition: pg_attribute.h:79
Datum pg_cancel_backend(PG_FUNCTION_ARGS)
Definition: misc.c:283
#define SIGNAL_BACKEND_NOSUPERUSER
Definition: misc.c:218
#define PG_RETURN_VOID()
Definition: fmgr.h:314
static int pg_signal_backend(int pid, int sig)
Definition: misc.c:220
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:336
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define PG_ARGISNULL(n)
Definition: fmgr.h:179
#define Assert(condition)
Definition: c.h:699
Datum pg_rotate_logfile_v2(PG_FUNCTION_ARGS)
Definition: misc.c:376
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2666
int16 category
Definition: keywords.h:28
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:110
static bool is_ident_cont(unsigned char c)
Definition: misc.c:761
#define PG_NARGS()
Definition: fmgr.h:173
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:231
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:45
#define ARR_NDIM(a)
Definition: array.h:275
#define COL_NAME_KEYWORD
Definition: keywords.h:19
int FreeFile(FILE *file)
Definition: fd.c:2538
static Datum values[MAXATTR]
Definition: bootstrap.c:164
char * text_to_cstring(const text *t)
Definition: varlena.c:182
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5042
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2575
void * user_fctx
Definition: funcapi.h:91
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define CStringGetTextDatum(s)
Definition: builtins.h:95
struct Latch * MyLatch
Definition: globals.c:55
Definition: c.h:516
#define PG_FUNCTION_ARGS
Definition: fmgr.h:163
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:113
char d_name[MAX_PATH]
Definition: dirent.h:14
#define elog
Definition: elog.h:219
Datum pg_get_keywords(PG_FUNCTION_ARGS)
Definition: misc.c:587
NameData * Name
Definition: c.h:574
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:2824
Definition: proc.h:95
#define PG_RETURN_OID(x)
Definition: fmgr.h:325
#define SIGNAL_BACKEND_ERROR
Definition: misc.c:216
char * location
Definition: misc.c:393
#define WL_LATCH_SET
Definition: latch.h:124
int16 AttrNumber
Definition: attnum.h:21
#define _(x)
Definition: elog.c:84
#define ARR_NULLBITMAP(a)
Definition: array.h:285
DIR * dirdesc
Definition: misc.c:394
#define PG_RETURN_NULL()
Definition: fmgr.h:310
#define PG_RETURN_NAME(x)
Definition: fmgr.h:328
int FreeDir(DIR *dir)
Definition: fd.c:2718
Datum pg_column_is_updatable(PG_FUNCTION_ARGS)
Definition: misc.c:716
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:318
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:296