1 /*-------------------------------------------------------------------------
6 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/adt/misc.c
13 *-------------------------------------------------------------------------
23 #include "catalog/catalog.h"
24 #include "catalog/pg_tablespace.h"
25 #include "catalog/pg_type.h"
26 #include "commands/dbcommands.h"
27 #include "common/relpath.h"
29 #include "miscadmin.h"
30 #include "parser/keywords.h"
31 #include "postmaster/syslogger.h"
32 #include "rewrite/rewriteHandler.h"
33 #include "storage/fd.h"
34 #include "storage/pmsignal.h"
35 #include "storage/proc.h"
36 #include "storage/procarray.h"
37 #include "utils/lsyscache.h"
38 #include "tcop/tcopprot.h"
39 #include "utils/builtins.h"
40 #include "utils/timestamp.h"
42 #define atooid(x) ((Oid) strtoul((x), NULL, 10))
47 * Expose the current database to the user
50 current_database(PG_FUNCTION_ARGS)
54 db = (Name) palloc(NAMEDATALEN);
56 namestrcpy(db, get_database_name(MyDatabaseId));
63 * Expose the current query to the user (useful in stored procedures)
64 * We might want to use ActivePortal->sourceText someday.
67 current_query(PG_FUNCTION_ARGS)
69 /* there is no easy way to access the more concise 'query_string' */
70 if (debug_query_string)
71 PG_RETURN_TEXT_P(cstring_to_text(debug_query_string));
77 * Send a signal to another backend.
79 * The signal is delivered if the user is either a superuser or the same
80 * role as the backend being signaled. For "dangerous" signals, an explicit
81 * check for superuser needs to be done prior to calling this function.
83 * Returns 0 on success, 1 on general failure, and 2 on permission error.
84 * In the event of a general failure (return code 1), a warning message will
85 * be emitted. For permission errors, doing that is the responsibility of
88 #define SIGNAL_BACKEND_SUCCESS 0
89 #define SIGNAL_BACKEND_ERROR 1
90 #define SIGNAL_BACKEND_NOPERMISSION 2
92 pg_signal_backend(int pid, int sig)
94 PGPROC *proc = BackendPidGetProc(pid);
97 * BackendPidGetProc returns NULL if the pid isn't valid; but by the time
98 * we reach kill(), a process for which we get a valid proc here might
99 * have terminated on its own. There's no way to acquire a lock on an
100 * arbitrary process to prevent that. But since so far all the callers of
101 * this mechanism involve some request for ending the process anyway, that
102 * it might end on its own first is not a problem.
107 * This is just a warning so a loop-through-resultset will not abort
108 * if one backend terminated on its own during the run.
111 (errmsg("PID %d is not a PostgreSQL server process", pid)));
112 return SIGNAL_BACKEND_ERROR;
115 if (!(superuser() || proc->roleId == GetUserId()))
116 return SIGNAL_BACKEND_NOPERMISSION;
119 * Can the process we just validated above end, followed by the pid being
120 * recycled for a new process, before reaching here? Then we'd be trying
121 * to kill the wrong thing. Seems near impossible when sequential pid
122 * assignment and wraparound is used. Perhaps it could happen on a system
123 * where pid re-use is randomized. That race condition possibility seems
124 * too unlikely to worry about.
127 /* If we have setsid(), signal the backend's whole process group */
134 /* Again, just a warning to allow loops */
136 (errmsg("could not send signal to process %d: %m", pid)));
137 return SIGNAL_BACKEND_ERROR;
139 return SIGNAL_BACKEND_SUCCESS;
143 * Signal to cancel a backend process. This is allowed if you are superuser or
144 * have the same role as the process being canceled.
147 pg_cancel_backend(PG_FUNCTION_ARGS)
149 int r = pg_signal_backend(PG_GETARG_INT32(0), SIGINT);
151 if (r == SIGNAL_BACKEND_NOPERMISSION)
153 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
154 (errmsg("must be superuser or have the same role to cancel queries running in other server processes"))));
156 PG_RETURN_BOOL(r == SIGNAL_BACKEND_SUCCESS);
160 * Signal to terminate a backend process. This is allowed if you are superuser
161 * or have the same role as the process being terminated.
164 pg_terminate_backend(PG_FUNCTION_ARGS)
166 int r = pg_signal_backend(PG_GETARG_INT32(0), SIGTERM);
168 if (r == SIGNAL_BACKEND_NOPERMISSION)
170 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
171 (errmsg("must be superuser or have the same role to terminate other server processes"))));
173 PG_RETURN_BOOL(r == SIGNAL_BACKEND_SUCCESS);
177 * Signal to reload the database configuration
180 pg_reload_conf(PG_FUNCTION_ARGS)
184 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
185 (errmsg("must be superuser to signal the postmaster"))));
187 if (kill(PostmasterPid, SIGHUP))
190 (errmsg("failed to send signal to postmaster: %m")));
191 PG_RETURN_BOOL(false);
194 PG_RETURN_BOOL(true);
202 pg_rotate_logfile(PG_FUNCTION_ARGS)
206 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
207 (errmsg("must be superuser to rotate log files"))));
209 if (!Logging_collector)
212 (errmsg("rotation not possible because log collection not active")));
213 PG_RETURN_BOOL(false);
216 SendPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE);
217 PG_RETURN_BOOL(true);
220 /* Function to find out which databases make use of a tablespace */
229 pg_tablespace_databases(PG_FUNCTION_ARGS)
231 FuncCallContext *funcctx;
235 if (SRF_IS_FIRSTCALL())
237 MemoryContext oldcontext;
238 Oid tablespaceOid = PG_GETARG_OID(0);
240 funcctx = SRF_FIRSTCALL_INIT();
241 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
243 fctx = palloc(sizeof(ts_db_fctx));
246 * size = tablespace dirname length + dir sep char + oid + terminator
248 fctx->location = (char *) palloc(9 + 1 + OIDCHARS + 1 +
249 strlen(TABLESPACE_VERSION_DIRECTORY) + 1);
250 if (tablespaceOid == GLOBALTABLESPACE_OID)
252 fctx->dirdesc = NULL;
254 (errmsg("global tablespace never has databases")));
258 if (tablespaceOid == DEFAULTTABLESPACE_OID)
259 sprintf(fctx->location, "base");
261 sprintf(fctx->location, "pg_tblspc/%u/%s", tablespaceOid,
262 TABLESPACE_VERSION_DIRECTORY);
264 fctx->dirdesc = AllocateDir(fctx->location);
268 /* the only expected error is ENOENT */
271 (errcode_for_file_access(),
272 errmsg("could not open directory \"%s\": %m",
275 (errmsg("%u is not a tablespace OID", tablespaceOid)));
278 funcctx->user_fctx = fctx;
279 MemoryContextSwitchTo(oldcontext);
282 funcctx = SRF_PERCALL_SETUP();
283 fctx = (ts_db_fctx *) funcctx->user_fctx;
285 if (!fctx->dirdesc) /* not a tablespace */
286 SRF_RETURN_DONE(funcctx);
288 while ((de = ReadDir(fctx->dirdesc, fctx->location)) != NULL)
292 Oid datOid = atooid(de->d_name);
294 /* this test skips . and .., but is awfully weak */
298 /* if database subdir is empty, don't report tablespace as used */
300 /* size = path length + dir sep char + file name + terminator */
301 subdir = palloc(strlen(fctx->location) + 1 + strlen(de->d_name) + 1);
302 sprintf(subdir, "%s/%s", fctx->location, de->d_name);
303 dirdesc = AllocateDir(subdir);
304 while ((de = ReadDir(dirdesc, subdir)) != NULL)
306 if (strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0)
313 continue; /* indeed, nothing in it */
315 SRF_RETURN_NEXT(funcctx, ObjectIdGetDatum(datOid));
318 FreeDir(fctx->dirdesc);
319 SRF_RETURN_DONE(funcctx);
324 * pg_tablespace_location - get location for a tablespace
327 pg_tablespace_location(PG_FUNCTION_ARGS)
329 Oid tablespaceOid = PG_GETARG_OID(0);
330 char sourcepath[MAXPGPATH];
331 char targetpath[MAXPGPATH];
335 * It's useful to apply this function to pg_class.reltablespace, wherein
336 * zero means "the database's default tablespace". So, rather than
337 * throwing an error for zero, we choose to assume that's what is meant.
339 if (tablespaceOid == InvalidOid)
340 tablespaceOid = MyDatabaseTableSpace;
343 * Return empty string for the cluster's default tablespaces
345 if (tablespaceOid == DEFAULTTABLESPACE_OID ||
346 tablespaceOid == GLOBALTABLESPACE_OID)
347 PG_RETURN_TEXT_P(cstring_to_text(""));
349 #if defined(HAVE_READLINK) || defined(WIN32)
352 * Find the location of the tablespace by reading the symbolic link that
353 * is in pg_tblspc/<oid>.
355 snprintf(sourcepath, sizeof(sourcepath), "pg_tblspc/%u", tablespaceOid);
357 rllen = readlink(sourcepath, targetpath, sizeof(targetpath));
360 (errmsg("could not read symbolic link \"%s\": %m",
362 else if (rllen >= sizeof(targetpath))
364 (errmsg("symbolic link \"%s\" target is too long",
366 targetpath[rllen] = '\0';
368 PG_RETURN_TEXT_P(cstring_to_text(targetpath));
371 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
372 errmsg("tablespaces are not supported on this platform")));
378 * pg_sleep - delay for N seconds
381 pg_sleep(PG_FUNCTION_ARGS)
383 float8 secs = PG_GETARG_FLOAT8(0);
387 * We break the requested sleep into segments of no more than 1 second, to
388 * put an upper bound on how long it will take us to respond to a cancel
389 * or die interrupt. (Note that pg_usleep is interruptible by signals on
390 * some platforms but not others.) Also, this method avoids exposing
391 * pg_usleep's upper bound on allowed delays.
393 * By computing the intended stop time initially, we avoid accumulation of
394 * extra delay across multiple sleeps. This also ensures we won't delay
395 * less than the specified time if pg_usleep is interrupted by other
396 * signals such as SIGHUP.
399 #ifdef HAVE_INT64_TIMESTAMP
400 #define GetNowFloat() ((float8) GetCurrentTimestamp() / 1000000.0)
402 #define GetNowFloat() GetCurrentTimestamp()
405 endtime = GetNowFloat() + secs;
411 CHECK_FOR_INTERRUPTS();
412 delay = endtime - GetNowFloat();
415 else if (delay > 0.0)
416 pg_usleep((long) ceil(delay * 1000000.0));
424 /* Function to return the list of grammar keywords */
426 pg_get_keywords(PG_FUNCTION_ARGS)
428 FuncCallContext *funcctx;
430 if (SRF_IS_FIRSTCALL())
432 MemoryContext oldcontext;
435 funcctx = SRF_FIRSTCALL_INIT();
436 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
438 tupdesc = CreateTemplateTupleDesc(3, false);
439 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "word",
441 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "catcode",
443 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "catdesc",
446 funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
448 MemoryContextSwitchTo(oldcontext);
451 funcctx = SRF_PERCALL_SETUP();
453 if (funcctx->call_cntr < NumScanKeywords)
458 /* cast-away-const is ugly but alternatives aren't much better */
459 values[0] = (char *) ScanKeywords[funcctx->call_cntr].name;
461 switch (ScanKeywords[funcctx->call_cntr].category)
463 case UNRESERVED_KEYWORD:
465 values[2] = _("unreserved");
467 case COL_NAME_KEYWORD:
469 values[2] = _("unreserved (cannot be function or type name)");
471 case TYPE_FUNC_NAME_KEYWORD:
473 values[2] = _("reserved (can be function or type name)");
475 case RESERVED_KEYWORD:
477 values[2] = _("reserved");
479 default: /* shouldn't be possible */
485 tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
487 SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
490 SRF_RETURN_DONE(funcctx);
495 * Return the type of the argument.
498 pg_typeof(PG_FUNCTION_ARGS)
500 PG_RETURN_OID(get_fn_expr_argtype(fcinfo->flinfo, 0));
505 * Implementation of the COLLATE FOR expression; returns the collation
509 pg_collation_for(PG_FUNCTION_ARGS)
514 typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
517 if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
519 (errcode(ERRCODE_DATATYPE_MISMATCH),
520 errmsg("collations are not supported by type %s",
521 format_type_be(typeid))));
523 collid = PG_GET_COLLATION();
526 PG_RETURN_TEXT_P(cstring_to_text(generate_collation_name(collid)));
531 * pg_relation_is_updatable - determine which update events the specified
534 * This relies on relation_is_updatable() in rewriteHandler.c, which see
535 * for additional information.
538 pg_relation_is_updatable(PG_FUNCTION_ARGS)
540 Oid reloid = PG_GETARG_OID(0);
541 bool include_triggers = PG_GETARG_BOOL(1);
543 PG_RETURN_INT32(relation_is_updatable(reloid, include_triggers));
547 * pg_column_is_updatable - determine whether a column is updatable
549 * Currently we just check whether the column's relation is updatable.
550 * Eventually we might allow views to have some updatable and some
551 * non-updatable columns.
553 * Also, this function encapsulates the decision about just what
554 * information_schema.columns.is_updatable actually means. It's not clear
555 * whether deletability of the column's relation should be required, so
556 * we want that decision in C code where we could change it without initdb.
559 pg_column_is_updatable(PG_FUNCTION_ARGS)
561 Oid reloid = PG_GETARG_OID(0);
562 AttrNumber attnum = PG_GETARG_INT16(1);
563 bool include_triggers = PG_GETARG_BOOL(2);
566 /* System columns are never updatable */
568 PG_RETURN_BOOL(false);
570 events = relation_is_updatable(reloid, include_triggers);
572 /* We require both updatability and deletability of the relation */
573 #define REQ_EVENTS ((1 << CMD_UPDATE) | (1 << CMD_DELETE))
575 PG_RETURN_BOOL((events & REQ_EVENTS) == REQ_EVENTS);