1 /*-------------------------------------------------------------------------
2 *
3 * misc.c
4 *
5 *
6 * Portions Copyright (c) 1996-2017, 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 <fcntl.h>
21 #include <math.h>
22 #include <unistd.h>
23
24 #include "access/sysattr.h"
25 #include "catalog/pg_authid.h"
26 #include "catalog/catalog.h"
27 #include "catalog/pg_tablespace.h"
28 #include "catalog/pg_type.h"
29 #include "commands/dbcommands.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
count_nulls(FunctionCallInfo fcinfo,int32 * nargs,int32 * nulls)56 count_nulls(FunctionCallInfo fcinfo,
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 */
88 Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, 0))));
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
pg_num_nulls(PG_FUNCTION_ARGS)142 pg_num_nulls(PG_FUNCTION_ARGS)
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
pg_num_nonnulls(PG_FUNCTION_ARGS)158 pg_num_nonnulls(PG_FUNCTION_ARGS)
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
current_database(PG_FUNCTION_ARGS)175 current_database(PG_FUNCTION_ARGS)
176 {
177 Name db;
178
179 db = (Name) palloc(NAMEDATALEN);
180
181 namestrcpy(db, get_database_name(MyDatabaseId));
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
current_query(PG_FUNCTION_ARGS)192 current_query(PG_FUNCTION_ARGS)
193 {
194 /* there is no easy way to access the more concise 'query_string' */
195 if (debug_query_string)
196 PG_RETURN_TEXT_P(cstring_to_text(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
pg_signal_backend(int pid,int sig)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 */
238 ereport(WARNING,
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())
245 return SIGNAL_BACKEND_NOSUPERUSER;
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))
250 return SIGNAL_BACKEND_NOPERMISSION;
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 */
269 ereport(WARNING,
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
pg_cancel_backend(PG_FUNCTION_ARGS)283 pg_cancel_backend(PG_FUNCTION_ARGS)
284 {
285 int r = pg_signal_backend(PG_GETARG_INT32(0), SIGINT);
286
287 if (r == SIGNAL_BACKEND_NOSUPERUSER)
288 ereport(ERROR,
289 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
290 (errmsg("must be a superuser to cancel superuser query"))));
291
292 if (r == SIGNAL_BACKEND_NOPERMISSION)
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
297 PG_RETURN_BOOL(r == SIGNAL_BACKEND_SUCCESS);
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
pg_terminate_backend(PG_FUNCTION_ARGS)307 pg_terminate_backend(PG_FUNCTION_ARGS)
308 {
309 int r = pg_signal_backend(PG_GETARG_INT32(0), SIGTERM);
310
311 if (r == SIGNAL_BACKEND_NOSUPERUSER)
312 ereport(ERROR,
313 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
314 (errmsg("must be a superuser to terminate superuser process"))));
315
316 if (r == SIGNAL_BACKEND_NOPERMISSION)
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
321 PG_RETURN_BOOL(r == SIGNAL_BACKEND_SUCCESS);
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
pg_reload_conf(PG_FUNCTION_ARGS)331 pg_reload_conf(PG_FUNCTION_ARGS)
332 {
333 if (kill(PostmasterPid, SIGHUP))
334 {
335 ereport(WARNING,
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 * Permission checking for this function is managed through the normal
348 * GRANT system.
349 */
350 Datum
pg_rotate_logfile(PG_FUNCTION_ARGS)351 pg_rotate_logfile(PG_FUNCTION_ARGS)
352 {
353 if (!Logging_collector)
354 {
355 ereport(WARNING,
356 (errmsg("rotation not possible because log collection not active")));
357 PG_RETURN_BOOL(false);
358 }
359
360 SendPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE);
361 PG_RETURN_BOOL(true);
362 }
363
364 /* Function to find out which databases make use of a tablespace */
365
366 Datum
pg_tablespace_databases(PG_FUNCTION_ARGS)367 pg_tablespace_databases(PG_FUNCTION_ARGS)
368 {
369 Oid tablespaceOid = PG_GETARG_OID(0);
370 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
371 bool randomAccess;
372 TupleDesc tupdesc;
373 Tuplestorestate *tupstore;
374 char *location;
375 DIR *dirdesc;
376 struct dirent *de;
377 MemoryContext oldcontext;
378
379 /* check to see if caller supports us returning a tuplestore */
380 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
381 ereport(ERROR,
382 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
383 errmsg("set-valued function called in context that cannot accept a set")));
384 if (!(rsinfo->allowedModes & SFRM_Materialize))
385 ereport(ERROR,
386 (errcode(ERRCODE_SYNTAX_ERROR),
387 errmsg("materialize mode required, but it is not allowed in this context")));
388
389 /* The tupdesc and tuplestore must be created in ecxt_per_query_memory */
390 oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
391
392 tupdesc = CreateTemplateTupleDesc(1, false);
393 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "pg_tablespace_databases",
394 OIDOID, -1, 0);
395
396 randomAccess = (rsinfo->allowedModes & SFRM_Materialize_Random) != 0;
397 tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
398
399 rsinfo->returnMode = SFRM_Materialize;
400 rsinfo->setResult = tupstore;
401 rsinfo->setDesc = tupdesc;
402
403 MemoryContextSwitchTo(oldcontext);
404
405 if (tablespaceOid == GLOBALTABLESPACE_OID)
406 {
407 ereport(WARNING,
408 (errmsg("global tablespace never has databases")));
409 /* return empty tuplestore */
410 return (Datum) 0;
411 }
412
413 if (tablespaceOid == DEFAULTTABLESPACE_OID)
414 location = psprintf("base");
415 else
416 location = psprintf("pg_tblspc/%u/%s", tablespaceOid,
417 TABLESPACE_VERSION_DIRECTORY);
418
419 dirdesc = AllocateDir(location);
420
421 if (!dirdesc)
422 {
423 /* the only expected error is ENOENT */
424 if (errno != ENOENT)
425 ereport(ERROR,
426 (errcode_for_file_access(),
427 errmsg("could not open directory \"%s\": %m",
428 location)));
429 ereport(WARNING,
430 (errmsg("%u is not a tablespace OID", tablespaceOid)));
431 /* return empty tuplestore */
432 return (Datum) 0;
433 }
434
435 while ((de = ReadDir(dirdesc, location)) != NULL)
436 {
437 Oid datOid = atooid(de->d_name);
438 char *subdir;
439 DIR *dirdesc2;
440 Datum values[1];
441 bool nulls[1];
442
443 /* this test skips . and .., but is awfully weak */
444 if (!datOid)
445 continue;
446
447 /* if database subdir is empty, don't report tablespace as used */
448
449 subdir = psprintf("%s/%s", location, de->d_name);
450 dirdesc2 = AllocateDir(subdir);
451 while ((de = ReadDir(dirdesc2, subdir)) != NULL)
452 {
453 if (strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0)
454 break;
455 }
456 FreeDir(dirdesc2);
457 pfree(subdir);
458
459 if (!de)
460 continue; /* indeed, nothing in it */
461
462 values[0] = ObjectIdGetDatum(datOid);
463 nulls[0] = false;
464
465 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
466 }
467
468 FreeDir(dirdesc);
469 return (Datum) 0;
470 }
471
472
473 /*
474 * pg_tablespace_location - get location for a tablespace
475 */
476 Datum
pg_tablespace_location(PG_FUNCTION_ARGS)477 pg_tablespace_location(PG_FUNCTION_ARGS)
478 {
479 Oid tablespaceOid = PG_GETARG_OID(0);
480 char sourcepath[MAXPGPATH];
481 char targetpath[MAXPGPATH];
482 int rllen;
483
484 /*
485 * It's useful to apply this function to pg_class.reltablespace, wherein
486 * zero means "the database's default tablespace". So, rather than
487 * throwing an error for zero, we choose to assume that's what is meant.
488 */
489 if (tablespaceOid == InvalidOid)
490 tablespaceOid = MyDatabaseTableSpace;
491
492 /*
493 * Return empty string for the cluster's default tablespaces
494 */
495 if (tablespaceOid == DEFAULTTABLESPACE_OID ||
496 tablespaceOid == GLOBALTABLESPACE_OID)
497 PG_RETURN_TEXT_P(cstring_to_text(""));
498
499 #if defined(HAVE_READLINK) || defined(WIN32)
500
501 /*
502 * Find the location of the tablespace by reading the symbolic link that
503 * is in pg_tblspc/<oid>.
504 */
505 snprintf(sourcepath, sizeof(sourcepath), "pg_tblspc/%u", tablespaceOid);
506
507 rllen = readlink(sourcepath, targetpath, sizeof(targetpath));
508 if (rllen < 0)
509 ereport(ERROR,
510 (errcode_for_file_access(),
511 errmsg("could not read symbolic link \"%s\": %m",
512 sourcepath)));
513 if (rllen >= sizeof(targetpath))
514 ereport(ERROR,
515 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
516 errmsg("symbolic link \"%s\" target is too long",
517 sourcepath)));
518 targetpath[rllen] = '\0';
519
520 PG_RETURN_TEXT_P(cstring_to_text(targetpath));
521 #else
522 ereport(ERROR,
523 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
524 errmsg("tablespaces are not supported on this platform")));
525 PG_RETURN_NULL();
526 #endif
527 }
528
529 /*
530 * pg_sleep - delay for N seconds
531 */
532 Datum
pg_sleep(PG_FUNCTION_ARGS)533 pg_sleep(PG_FUNCTION_ARGS)
534 {
535 float8 secs = PG_GETARG_FLOAT8(0);
536 float8 endtime;
537
538 /*
539 * We sleep using WaitLatch, to ensure that we'll wake up promptly if an
540 * important signal (such as SIGALRM or SIGINT) arrives. Because
541 * WaitLatch's upper limit of delay is INT_MAX milliseconds, and the user
542 * might ask for more than that, we sleep for at most 10 minutes and then
543 * loop.
544 *
545 * By computing the intended stop time initially, we avoid accumulation of
546 * extra delay across multiple sleeps. This also ensures we won't delay
547 * less than the specified time when WaitLatch is terminated early by a
548 * non-query-canceling signal such as SIGHUP.
549 */
550 #define GetNowFloat() ((float8) GetCurrentTimestamp() / 1000000.0)
551
552 endtime = GetNowFloat() + secs;
553
554 for (;;)
555 {
556 float8 delay;
557 long delay_ms;
558
559 CHECK_FOR_INTERRUPTS();
560
561 delay = endtime - GetNowFloat();
562 if (delay >= 600.0)
563 delay_ms = 600000;
564 else if (delay > 0.0)
565 delay_ms = (long) ceil(delay * 1000.0);
566 else
567 break;
568
569 (void) WaitLatch(MyLatch,
570 WL_LATCH_SET | WL_TIMEOUT,
571 delay_ms,
572 WAIT_EVENT_PG_SLEEP);
573 ResetLatch(MyLatch);
574 }
575
576 PG_RETURN_VOID();
577 }
578
579 /* Function to return the list of grammar keywords */
580 Datum
pg_get_keywords(PG_FUNCTION_ARGS)581 pg_get_keywords(PG_FUNCTION_ARGS)
582 {
583 FuncCallContext *funcctx;
584
585 if (SRF_IS_FIRSTCALL())
586 {
587 MemoryContext oldcontext;
588 TupleDesc tupdesc;
589
590 funcctx = SRF_FIRSTCALL_INIT();
591 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
592
593 tupdesc = CreateTemplateTupleDesc(3, false);
594 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "word",
595 TEXTOID, -1, 0);
596 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "catcode",
597 CHAROID, -1, 0);
598 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "catdesc",
599 TEXTOID, -1, 0);
600
601 funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
602
603 MemoryContextSwitchTo(oldcontext);
604 }
605
606 funcctx = SRF_PERCALL_SETUP();
607
608 if (funcctx->call_cntr < NumScanKeywords)
609 {
610 char *values[3];
611 HeapTuple tuple;
612
613 /* cast-away-const is ugly but alternatives aren't much better */
614 values[0] = (char *) ScanKeywords[funcctx->call_cntr].name;
615
616 switch (ScanKeywords[funcctx->call_cntr].category)
617 {
618 case UNRESERVED_KEYWORD:
619 values[1] = "U";
620 values[2] = _("unreserved");
621 break;
622 case COL_NAME_KEYWORD:
623 values[1] = "C";
624 values[2] = _("unreserved (cannot be function or type name)");
625 break;
626 case TYPE_FUNC_NAME_KEYWORD:
627 values[1] = "T";
628 values[2] = _("reserved (can be function or type name)");
629 break;
630 case RESERVED_KEYWORD:
631 values[1] = "R";
632 values[2] = _("reserved");
633 break;
634 default: /* shouldn't be possible */
635 values[1] = NULL;
636 values[2] = NULL;
637 break;
638 }
639
640 tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
641
642 SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
643 }
644
645 SRF_RETURN_DONE(funcctx);
646 }
647
648
649 /*
650 * Return the type of the argument.
651 */
652 Datum
pg_typeof(PG_FUNCTION_ARGS)653 pg_typeof(PG_FUNCTION_ARGS)
654 {
655 PG_RETURN_OID(get_fn_expr_argtype(fcinfo->flinfo, 0));
656 }
657
658
659 /*
660 * Implementation of the COLLATE FOR expression; returns the collation
661 * of the argument.
662 */
663 Datum
pg_collation_for(PG_FUNCTION_ARGS)664 pg_collation_for(PG_FUNCTION_ARGS)
665 {
666 Oid typeid;
667 Oid collid;
668
669 typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
670 if (!typeid)
671 PG_RETURN_NULL();
672 if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
673 ereport(ERROR,
674 (errcode(ERRCODE_DATATYPE_MISMATCH),
675 errmsg("collations are not supported by type %s",
676 format_type_be(typeid))));
677
678 collid = PG_GET_COLLATION();
679 if (!collid)
680 PG_RETURN_NULL();
681 PG_RETURN_TEXT_P(cstring_to_text(generate_collation_name(collid)));
682 }
683
684
685 /*
686 * pg_relation_is_updatable - determine which update events the specified
687 * relation supports.
688 *
689 * This relies on relation_is_updatable() in rewriteHandler.c, which see
690 * for additional information.
691 */
692 Datum
pg_relation_is_updatable(PG_FUNCTION_ARGS)693 pg_relation_is_updatable(PG_FUNCTION_ARGS)
694 {
695 Oid reloid = PG_GETARG_OID(0);
696 bool include_triggers = PG_GETARG_BOOL(1);
697
698 PG_RETURN_INT32(relation_is_updatable(reloid, NIL, include_triggers, NULL));
699 }
700
701 /*
702 * pg_column_is_updatable - determine whether a column is updatable
703 *
704 * This function encapsulates the decision about just what
705 * information_schema.columns.is_updatable actually means. It's not clear
706 * whether deletability of the column's relation should be required, so
707 * we want that decision in C code where we could change it without initdb.
708 */
709 Datum
pg_column_is_updatable(PG_FUNCTION_ARGS)710 pg_column_is_updatable(PG_FUNCTION_ARGS)
711 {
712 Oid reloid = PG_GETARG_OID(0);
713 AttrNumber attnum = PG_GETARG_INT16(1);
714 AttrNumber col = attnum - FirstLowInvalidHeapAttributeNumber;
715 bool include_triggers = PG_GETARG_BOOL(2);
716 int events;
717
718 /* System columns are never updatable */
719 if (attnum <= 0)
720 PG_RETURN_BOOL(false);
721
722 events = relation_is_updatable(reloid, NIL, include_triggers,
723 bms_make_singleton(col));
724
725 /* We require both updatability and deletability of the relation */
726 #define REQ_EVENTS ((1 << CMD_UPDATE) | (1 << CMD_DELETE))
727
728 PG_RETURN_BOOL((events & REQ_EVENTS) == REQ_EVENTS);
729 }
730
731
732 /*
733 * Is character a valid identifier start?
734 * Must match scan.l's {ident_start} character class.
735 */
736 static bool
is_ident_start(unsigned char c)737 is_ident_start(unsigned char c)
738 {
739 /* Underscores and ASCII letters are OK */
740 if (c == '_')
741 return true;
742 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
743 return true;
744 /* Any high-bit-set character is OK (might be part of a multibyte char) */
745 if (IS_HIGHBIT_SET(c))
746 return true;
747 return false;
748 }
749
750 /*
751 * Is character a valid identifier continuation?
752 * Must match scan.l's {ident_cont} character class.
753 */
754 static bool
is_ident_cont(unsigned char c)755 is_ident_cont(unsigned char c)
756 {
757 /* Can be digit or dollar sign ... */
758 if ((c >= '0' && c <= '9') || c == '$')
759 return true;
760 /* ... or an identifier start character */
761 return is_ident_start(c);
762 }
763
764 /*
765 * parse_ident - parse a SQL qualified identifier into separate identifiers.
766 * When strict mode is active (second parameter), then any chars after
767 * the last identifier are disallowed.
768 */
769 Datum
parse_ident(PG_FUNCTION_ARGS)770 parse_ident(PG_FUNCTION_ARGS)
771 {
772 text *qualname = PG_GETARG_TEXT_PP(0);
773 bool strict = PG_GETARG_BOOL(1);
774 char *qualname_str = text_to_cstring(qualname);
775 ArrayBuildState *astate = NULL;
776 char *nextp;
777 bool after_dot = false;
778
779 /*
780 * The code below scribbles on qualname_str in some cases, so we should
781 * reconvert qualname if we need to show the original string in error
782 * messages.
783 */
784 nextp = qualname_str;
785
786 /* skip leading whitespace */
787 while (scanner_isspace(*nextp))
788 nextp++;
789
790 for (;;)
791 {
792 char *curname;
793 bool missing_ident = true;
794
795 if (*nextp == '"')
796 {
797 char *endp;
798
799 curname = nextp + 1;
800 for (;;)
801 {
802 endp = strchr(nextp + 1, '"');
803 if (endp == NULL)
804 ereport(ERROR,
805 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
806 errmsg("string is not a valid identifier: \"%s\"",
807 text_to_cstring(qualname)),
808 errdetail("String has unclosed double quotes.")));
809 if (endp[1] != '"')
810 break;
811 memmove(endp, endp + 1, strlen(endp));
812 nextp = endp;
813 }
814 nextp = endp + 1;
815 *endp = '\0';
816
817 if (endp - curname == 0)
818 ereport(ERROR,
819 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
820 errmsg("string is not a valid identifier: \"%s\"",
821 text_to_cstring(qualname)),
822 errdetail("Quoted identifier must not be empty.")));
823
824 astate = accumArrayResult(astate, CStringGetTextDatum(curname),
825 false, TEXTOID, CurrentMemoryContext);
826 missing_ident = false;
827 }
828 else if (is_ident_start((unsigned char) *nextp))
829 {
830 char *downname;
831 int len;
832 text *part;
833
834 curname = nextp++;
835 while (is_ident_cont((unsigned char) *nextp))
836 nextp++;
837
838 len = nextp - curname;
839
840 /*
841 * We don't implicitly truncate identifiers. This is useful for
842 * allowing the user to check for specific parts of the identifier
843 * being too long. It's easy enough for the user to get the
844 * truncated names by casting our output to name[].
845 */
846 downname = downcase_identifier(curname, len, false, false);
847 part = cstring_to_text_with_len(downname, len);
848 astate = accumArrayResult(astate, PointerGetDatum(part), false,
849 TEXTOID, CurrentMemoryContext);
850 missing_ident = false;
851 }
852
853 if (missing_ident)
854 {
855 /* Different error messages based on where we failed. */
856 if (*nextp == '.')
857 ereport(ERROR,
858 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
859 errmsg("string is not a valid identifier: \"%s\"",
860 text_to_cstring(qualname)),
861 errdetail("No valid identifier before \".\".")));
862 else if (after_dot)
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 after \".\".")));
868 else
869 ereport(ERROR,
870 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
871 errmsg("string is not a valid identifier: \"%s\"",
872 text_to_cstring(qualname))));
873 }
874
875 while (scanner_isspace(*nextp))
876 nextp++;
877
878 if (*nextp == '.')
879 {
880 after_dot = true;
881 nextp++;
882 while (scanner_isspace(*nextp))
883 nextp++;
884 }
885 else if (*nextp == '\0')
886 {
887 break;
888 }
889 else
890 {
891 if (strict)
892 ereport(ERROR,
893 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
894 errmsg("string is not a valid identifier: \"%s\"",
895 text_to_cstring(qualname))));
896 break;
897 }
898 }
899
900 PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
901 }
902
903 /*
904 * pg_current_logfile
905 *
906 * Report current log file used by log collector by scanning current_logfiles.
907 */
908 Datum
pg_current_logfile(PG_FUNCTION_ARGS)909 pg_current_logfile(PG_FUNCTION_ARGS)
910 {
911 FILE *fd;
912 char lbuffer[MAXPGPATH];
913 char *logfmt;
914
915 /* The log format parameter is optional */
916 if (PG_NARGS() == 0 || PG_ARGISNULL(0))
917 logfmt = NULL;
918 else
919 {
920 logfmt = text_to_cstring(PG_GETARG_TEXT_PP(0));
921
922 if (strcmp(logfmt, "stderr") != 0 && strcmp(logfmt, "csvlog") != 0)
923 ereport(ERROR,
924 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
925 errmsg("log format \"%s\" is not supported", logfmt),
926 errhint("The supported log formats are \"stderr\" and \"csvlog\".")));
927 }
928
929 fd = AllocateFile(LOG_METAINFO_DATAFILE, "r");
930 if (fd == NULL)
931 {
932 if (errno != ENOENT)
933 ereport(ERROR,
934 (errcode_for_file_access(),
935 errmsg("could not read file \"%s\": %m",
936 LOG_METAINFO_DATAFILE)));
937 PG_RETURN_NULL();
938 }
939
940 #ifdef WIN32
941 /* syslogger.c writes CRLF line endings on Windows */
942 _setmode(_fileno(fd), _O_TEXT);
943 #endif
944
945 /*
946 * Read the file to gather current log filename(s) registered by the
947 * syslogger.
948 */
949 while (fgets(lbuffer, sizeof(lbuffer), fd) != NULL)
950 {
951 char *log_format;
952 char *log_filepath;
953 char *nlpos;
954
955 /* Extract log format and log file path from the line. */
956 log_format = lbuffer;
957 log_filepath = strchr(lbuffer, ' ');
958 if (log_filepath == NULL)
959 {
960 /* Uh oh. No space found, so file content is corrupted. */
961 elog(ERROR,
962 "missing space character in \"%s\"", LOG_METAINFO_DATAFILE);
963 break;
964 }
965
966 *log_filepath = '\0';
967 log_filepath++;
968 nlpos = strchr(log_filepath, '\n');
969 if (nlpos == NULL)
970 {
971 /* Uh oh. No newline found, so file content is corrupted. */
972 elog(ERROR,
973 "missing newline character in \"%s\"", LOG_METAINFO_DATAFILE);
974 break;
975 }
976 *nlpos = '\0';
977
978 if (logfmt == NULL || strcmp(logfmt, log_format) == 0)
979 {
980 FreeFile(fd);
981 PG_RETURN_TEXT_P(cstring_to_text(log_filepath));
982 }
983 }
984
985 /* Close the current log filename file. */
986 FreeFile(fd);
987
988 PG_RETURN_NULL();
989 }
990
991 /*
992 * Report current log file used by log collector (1 argument version)
993 *
994 * note: this wrapper is necessary to pass the sanity check in opr_sanity,
995 * which checks that all built-in functions that share the implementing C
996 * function take the same number of arguments
997 */
998 Datum
pg_current_logfile_1arg(PG_FUNCTION_ARGS)999 pg_current_logfile_1arg(PG_FUNCTION_ARGS)
1000 {
1001 return pg_current_logfile(fcinfo);
1002 }
1003
1004 /*
1005 * SQL wrapper around RelationGetReplicaIndex().
1006 */
1007 Datum
pg_get_replica_identity_index(PG_FUNCTION_ARGS)1008 pg_get_replica_identity_index(PG_FUNCTION_ARGS)
1009 {
1010 Oid reloid = PG_GETARG_OID(0);
1011 Oid idxoid;
1012 Relation rel;
1013
1014 rel = heap_open(reloid, AccessShareLock);
1015 idxoid = RelationGetReplicaIndex(rel);
1016 heap_close(rel, AccessShareLock);
1017
1018 if (OidIsValid(idxoid))
1019 PG_RETURN_OID(idxoid);
1020 else
1021 PG_RETURN_NULL();
1022 }
1023