1 /*-------------------------------------------------------------------------
2 *
3 * misc.c
4 *
5 *
6 * Portions Copyright (c) 1996-2020, 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 <dirent.h>
19 #include <fcntl.h>
20 #include <math.h>
21 #include <unistd.h>
22
23 #include "access/sysattr.h"
24 #include "access/table.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 "parser/scansup.h"
34 #include "pgstat.h"
35 #include "postmaster/syslogger.h"
36 #include "rewrite/rewriteHandler.h"
37 #include "storage/fd.h"
38 #include "tcop/tcopprot.h"
39 #include "utils/builtins.h"
40 #include "utils/lsyscache.h"
41 #include "utils/ruleutils.h"
42 #include "utils/timestamp.h"
43
44 /*
45 * Common subroutine for num_nulls() and num_nonnulls().
46 * Returns true if successful, false if function should return NULL.
47 * If successful, total argument count and number of nulls are
48 * returned into *nargs and *nulls.
49 */
50 static bool
51 count_nulls(FunctionCallInfo fcinfo,
52 int32 *nargs, int32 *nulls)
53 {
54 int32 count = 0;
scanint8(const char * str,bool errorOK,int64 * result)55 int i;
56
57 /* Did we get a VARIADIC array argument, or separate arguments? */
58 if (get_fn_expr_variadic(fcinfo->flinfo))
59 {
60 ArrayType *arr;
61 int ndims,
62 nitems,
63 *dims;
64 bits8 *bitmap;
65
66 Assert(PG_NARGS() == 1);
67
68 /*
69 * If we get a null as VARIADIC array argument, we can't say anything
70 * useful about the number of elements, so return NULL. This behavior
71 * is consistent with other variadic functions - see concat_internal.
72 */
73 if (PG_ARGISNULL(0))
74 return false;
75
76 /*
77 * Non-null argument had better be an array. We assume that any call
78 * context that could let get_fn_expr_variadic return true will have
79 * checked that a VARIADIC-labeled parameter actually is an array. So
80 * it should be okay to just Assert that it's an array rather than
81 * doing a full-fledged error check.
82 */
83 Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, 0))));
84
85 /* OK, safe to fetch the array value */
86 arr = PG_GETARG_ARRAYTYPE_P(0);
87
88 /* Count the array elements */
89 ndims = ARR_NDIM(arr);
90 dims = ARR_DIMS(arr);
91 nitems = ArrayGetNItems(ndims, dims);
92
93 /* Count those that are NULL */
94 bitmap = ARR_NULLBITMAP(arr);
95 if (bitmap)
96 {
97 int bitmask = 1;
98
99 for (i = 0; i < nitems; i++)
100 {
101 if ((*bitmap & bitmask) == 0)
102 count++;
103
104 bitmask <<= 1;
105 if (bitmask == 0x100)
106 {
107 bitmap++;
108 bitmask = 1;
109 }
110 }
111 }
112
113 *nargs = nitems;
114 *nulls = count;
115 }
116 else
117 {
118 /* Separate arguments, so just count 'em */
119 for (i = 0; i < PG_NARGS(); i++)
120 {
121 if (PG_ARGISNULL(i))
122 count++;
123 }
124
125 *nargs = PG_NARGS();
126 *nulls = count;
127 }
128
129 return true;
130 }
131
132 /*
133 * num_nulls()
int8in(PG_FUNCTION_ARGS)134 * Count the number of NULL arguments
135 */
136 Datum
137 pg_num_nulls(PG_FUNCTION_ARGS)
138 {
139 int32 nargs,
140 nulls;
141
142 if (!count_nulls(fcinfo, &nargs, &nulls))
143 PG_RETURN_NULL();
144
145 PG_RETURN_INT32(nulls);
146 }
int8out(PG_FUNCTION_ARGS)147
148 /*
149 * num_nonnulls()
150 * Count the number of non-NULL arguments
151 */
152 Datum
153 pg_num_nonnulls(PG_FUNCTION_ARGS)
154 {
155 int32 nargs,
156 nulls;
157
158 if (!count_nulls(fcinfo, &nargs, &nulls))
159 PG_RETURN_NULL();
160
161 PG_RETURN_INT32(nargs - nulls);
162 }
163
164
165 /*
166 * current_database()
167 * Expose the current database to the user
168 */
169 Datum
170 current_database(PG_FUNCTION_ARGS)
171 {
172 Name db;
int8send(PG_FUNCTION_ARGS)173
174 db = (Name) palloc(NAMEDATALEN);
175
176 namestrcpy(db, get_database_name(MyDatabaseId));
177 PG_RETURN_NAME(db);
178 }
179
180
181 /*
182 * current_query()
183 * Expose the current query to the user (useful in stored procedures)
184 * We might want to use ActivePortal->sourceText someday.
185 */
186 Datum
187 current_query(PG_FUNCTION_ARGS)
188 {
189 /* there is no easy way to access the more concise 'query_string' */
190 if (debug_query_string)
191 PG_RETURN_TEXT_P(cstring_to_text(debug_query_string));
int8eq(PG_FUNCTION_ARGS)192 else
193 PG_RETURN_NULL();
194 }
195
196 /* Function to find out which databases make use of a tablespace */
197
198 Datum
199 pg_tablespace_databases(PG_FUNCTION_ARGS)
200 {
int8ne(PG_FUNCTION_ARGS)201 Oid tablespaceOid = PG_GETARG_OID(0);
202 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
203 bool randomAccess;
204 TupleDesc tupdesc;
205 Tuplestorestate *tupstore;
206 char *location;
207 DIR *dirdesc;
208 struct dirent *de;
209 MemoryContext oldcontext;
int8lt(PG_FUNCTION_ARGS)210
211 /* check to see if caller supports us returning a tuplestore */
212 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
213 ereport(ERROR,
214 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
215 errmsg("set-valued function called in context that cannot accept a set")));
216 if (!(rsinfo->allowedModes & SFRM_Materialize))
217 ereport(ERROR,
218 (errcode(ERRCODE_SYNTAX_ERROR),
int8gt(PG_FUNCTION_ARGS)219 errmsg("materialize mode required, but it is not allowed in this context")));
220
221 /* The tupdesc and tuplestore must be created in ecxt_per_query_memory */
222 oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
223
224 tupdesc = CreateTemplateTupleDesc(1);
225 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "pg_tablespace_databases",
226 OIDOID, -1, 0);
227
int8le(PG_FUNCTION_ARGS)228 randomAccess = (rsinfo->allowedModes & SFRM_Materialize_Random) != 0;
229 tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
230
231 rsinfo->returnMode = SFRM_Materialize;
232 rsinfo->setResult = tupstore;
233 rsinfo->setDesc = tupdesc;
234
235 MemoryContextSwitchTo(oldcontext);
236
int8ge(PG_FUNCTION_ARGS)237 if (tablespaceOid == GLOBALTABLESPACE_OID)
238 {
239 ereport(WARNING,
240 (errmsg("global tablespace never has databases")));
241 /* return empty tuplestore */
242 return (Datum) 0;
243 }
244
245 if (tablespaceOid == DEFAULTTABLESPACE_OID)
246 location = psprintf("base");
247 else
248 location = psprintf("pg_tblspc/%u/%s", tablespaceOid,
int84eq(PG_FUNCTION_ARGS)249 TABLESPACE_VERSION_DIRECTORY);
250
251 dirdesc = AllocateDir(location);
252
253 if (!dirdesc)
254 {
255 /* the only expected error is ENOENT */
256 if (errno != ENOENT)
257 ereport(ERROR,
int84ne(PG_FUNCTION_ARGS)258 (errcode_for_file_access(),
259 errmsg("could not open directory \"%s\": %m",
260 location)));
261 ereport(WARNING,
262 (errmsg("%u is not a tablespace OID", tablespaceOid)));
263 /* return empty tuplestore */
264 return (Datum) 0;
265 }
266
int84lt(PG_FUNCTION_ARGS)267 while ((de = ReadDir(dirdesc, location)) != NULL)
268 {
269 Oid datOid = atooid(de->d_name);
270 char *subdir;
271 bool isempty;
272 Datum values[1];
273 bool nulls[1];
274
275 /* this test skips . and .., but is awfully weak */
276 if (!datOid)
277 continue;
278
279 /* if database subdir is empty, don't report tablespace as used */
280
281 subdir = psprintf("%s/%s", location, de->d_name);
282 isempty = directory_is_empty(subdir);
283 pfree(subdir);
284
285 if (isempty)
286 continue; /* indeed, nothing in it */
287
288 values[0] = ObjectIdGetDatum(datOid);
289 nulls[0] = false;
290
291 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
292 }
293
int84ge(PG_FUNCTION_ARGS)294 FreeDir(dirdesc);
295 return (Datum) 0;
296 }
297
298
299 /*
300 * pg_tablespace_location - get location for a tablespace
301 */
302 Datum
303 pg_tablespace_location(PG_FUNCTION_ARGS)
304 {
305 Oid tablespaceOid = PG_GETARG_OID(0);
int48eq(PG_FUNCTION_ARGS)306 char sourcepath[MAXPGPATH];
307 char targetpath[MAXPGPATH];
308 int rllen;
309
310 /*
311 * It's useful to apply this function to pg_class.reltablespace, wherein
312 * zero means "the database's default tablespace". So, rather than
313 * throwing an error for zero, we choose to assume that's what is meant.
314 */
int48ne(PG_FUNCTION_ARGS)315 if (tablespaceOid == InvalidOid)
316 tablespaceOid = MyDatabaseTableSpace;
317
318 /*
319 * Return empty string for the cluster's default tablespaces
320 */
321 if (tablespaceOid == DEFAULTTABLESPACE_OID ||
322 tablespaceOid == GLOBALTABLESPACE_OID)
323 PG_RETURN_TEXT_P(cstring_to_text(""));
int48lt(PG_FUNCTION_ARGS)324
325 #if defined(HAVE_READLINK) || defined(WIN32)
326
327 /*
328 * Find the location of the tablespace by reading the symbolic link that
329 * is in pg_tblspc/<oid>.
330 */
331 snprintf(sourcepath, sizeof(sourcepath), "pg_tblspc/%u", tablespaceOid);
332
int48gt(PG_FUNCTION_ARGS)333 rllen = readlink(sourcepath, targetpath, sizeof(targetpath));
334 if (rllen < 0)
335 ereport(ERROR,
336 (errcode_for_file_access(),
337 errmsg("could not read symbolic link \"%s\": %m",
338 sourcepath)));
339 if (rllen >= sizeof(targetpath))
340 ereport(ERROR,
341 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
int48le(PG_FUNCTION_ARGS)342 errmsg("symbolic link \"%s\" target is too long",
343 sourcepath)));
344 targetpath[rllen] = '\0';
345
346 PG_RETURN_TEXT_P(cstring_to_text(targetpath));
347 #else
348 ereport(ERROR,
349 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
350 errmsg("tablespaces are not supported on this platform")));
int48ge(PG_FUNCTION_ARGS)351 PG_RETURN_NULL();
352 #endif
353 }
354
355 /*
356 * pg_sleep - delay for N seconds
357 */
358 Datum
359 pg_sleep(PG_FUNCTION_ARGS)
360 {
361 float8 secs = PG_GETARG_FLOAT8(0);
362 float8 endtime;
int82eq(PG_FUNCTION_ARGS)363
364 /*
365 * We sleep using WaitLatch, to ensure that we'll wake up promptly if an
366 * important signal (such as SIGALRM or SIGINT) arrives. Because
367 * WaitLatch's upper limit of delay is INT_MAX milliseconds, and the user
368 * might ask for more than that, we sleep for at most 10 minutes and then
369 * loop.
370 *
371 * By computing the intended stop time initially, we avoid accumulation of
372 * extra delay across multiple sleeps. This also ensures we won't delay
373 * less than the specified time when WaitLatch is terminated early by a
374 * non-query-canceling signal such as SIGHUP.
375 */
376 #define GetNowFloat() ((float8) GetCurrentTimestamp() / 1000000.0)
377
378 endtime = GetNowFloat() + secs;
379
380 for (;;)
int82lt(PG_FUNCTION_ARGS)381 {
382 float8 delay;
383 long delay_ms;
384
385 CHECK_FOR_INTERRUPTS();
386
387 delay = endtime - GetNowFloat();
388 if (delay >= 600.0)
389 delay_ms = 600000;
390 else if (delay > 0.0)
391 delay_ms = (long) ceil(delay * 1000.0);
392 else
393 break;
394
395 (void) WaitLatch(MyLatch,
396 WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
397 delay_ms,
398 WAIT_EVENT_PG_SLEEP);
399 ResetLatch(MyLatch);
400 }
401
402 PG_RETURN_VOID();
403 }
404
405 /* Function to return the list of grammar keywords */
406 Datum
407 pg_get_keywords(PG_FUNCTION_ARGS)
int82ge(PG_FUNCTION_ARGS)408 {
409 FuncCallContext *funcctx;
410
411 if (SRF_IS_FIRSTCALL())
412 {
413 MemoryContext oldcontext;
414 TupleDesc tupdesc;
415
416 funcctx = SRF_FIRSTCALL_INIT();
417 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
418
419 tupdesc = CreateTemplateTupleDesc(3);
420 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "word",
421 TEXTOID, -1, 0);
422 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "catcode",
423 CHAROID, -1, 0);
424 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "catdesc",
425 TEXTOID, -1, 0);
426
427 funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
428
429 MemoryContextSwitchTo(oldcontext);
430 }
431
432 funcctx = SRF_PERCALL_SETUP();
433
434 if (funcctx->call_cntr < ScanKeywords.num_keywords)
435 {
436 char *values[3];
437 HeapTuple tuple;
438
439 /* cast-away-const is ugly but alternatives aren't much better */
440 values[0] = unconstify(char *,
441 GetScanKeyword(funcctx->call_cntr,
442 &ScanKeywords));
443
444 switch (ScanKeywordCategories[funcctx->call_cntr])
445 {
446 case UNRESERVED_KEYWORD:
447 values[1] = "U";
448 values[2] = _("unreserved");
449 break;
450 case COL_NAME_KEYWORD:
451 values[1] = "C";
452 values[2] = _("unreserved (cannot be function or type name)");
453 break;
454 case TYPE_FUNC_NAME_KEYWORD:
455 values[1] = "T";
456 values[2] = _("reserved (can be function or type name)");
457 break;
458 case RESERVED_KEYWORD:
459 values[1] = "R";
460 values[2] = _("reserved");
461 break;
462 default: /* shouldn't be possible */
463 values[1] = NULL;
464 values[2] = NULL;
465 break;
466 }
467
468 tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
469
470 SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
471 }
472
473 SRF_RETURN_DONE(funcctx);
474 }
475
476
477 /*
478 * Return the type of the argument.
479 */
in_range_int8_int8(PG_FUNCTION_ARGS)480 Datum
481 pg_typeof(PG_FUNCTION_ARGS)
482 {
483 PG_RETURN_OID(get_fn_expr_argtype(fcinfo->flinfo, 0));
484 }
485
486
487 /*
488 * Implementation of the COLLATE FOR expression; returns the collation
489 * of the argument.
490 */
491 Datum
492 pg_collation_for(PG_FUNCTION_ARGS)
493 {
494 Oid typeid;
495 Oid collid;
496
497 typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
498 if (!typeid)
499 PG_RETURN_NULL();
500 if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
501 ereport(ERROR,
502 (errcode(ERRCODE_DATATYPE_MISMATCH),
503 errmsg("collations are not supported by type %s",
504 format_type_be(typeid))));
505
506 collid = PG_GET_COLLATION();
507 if (!collid)
508 PG_RETURN_NULL();
509 PG_RETURN_TEXT_P(cstring_to_text(generate_collation_name(collid)));
510 }
511
512
513 /*
514 * pg_relation_is_updatable - determine which update events the specified
515 * relation supports.
516 *
517 * This relies on relation_is_updatable() in rewriteHandler.c, which see
518 * for additional information.
int8um(PG_FUNCTION_ARGS)519 */
520 Datum
521 pg_relation_is_updatable(PG_FUNCTION_ARGS)
522 {
523 Oid reloid = PG_GETARG_OID(0);
524 bool include_triggers = PG_GETARG_BOOL(1);
525
526 PG_RETURN_INT32(relation_is_updatable(reloid, NIL, include_triggers, NULL));
527 }
528
529 /*
530 * pg_column_is_updatable - determine whether a column is updatable
531 *
532 * This function encapsulates the decision about just what
int8up(PG_FUNCTION_ARGS)533 * information_schema.columns.is_updatable actually means. It's not clear
534 * whether deletability of the column's relation should be required, so
535 * we want that decision in C code where we could change it without initdb.
536 */
537 Datum
538 pg_column_is_updatable(PG_FUNCTION_ARGS)
539 {
540 Oid reloid = PG_GETARG_OID(0);
541 AttrNumber attnum = PG_GETARG_INT16(1);
542 AttrNumber col = attnum - FirstLowInvalidHeapAttributeNumber;
543 bool include_triggers = PG_GETARG_BOOL(2);
544 int events;
545
546 /* System columns are never updatable */
547 if (attnum <= 0)
548 PG_RETURN_BOOL(false);
549
550 events = relation_is_updatable(reloid, NIL, include_triggers,
551 bms_make_singleton(col));
552
553 /* We require both updatability and deletability of the relation */
554 #define REQ_EVENTS ((1 << CMD_UPDATE) | (1 << CMD_DELETE))
555
556 PG_RETURN_BOOL((events & REQ_EVENTS) == REQ_EVENTS);
557 }
558
559
560 /*
561 * Is character a valid identifier start?
562 * Must match scan.l's {ident_start} character class.
563 */
564 static bool
565 is_ident_start(unsigned char c)
566 {
567 /* Underscores and ASCII letters are OK */
568 if (c == '_')
int8mul(PG_FUNCTION_ARGS)569 return true;
570 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
571 return true;
572 /* Any high-bit-set character is OK (might be part of a multibyte char) */
573 if (IS_HIGHBIT_SET(c))
574 return true;
575 return false;
576 }
577
578 /*
579 * Is character a valid identifier continuation?
580 * Must match scan.l's {ident_cont} character class.
581 */
582 static bool
int8div(PG_FUNCTION_ARGS)583 is_ident_cont(unsigned char c)
584 {
585 /* Can be digit or dollar sign ... */
586 if ((c >= '0' && c <= '9') || c == '$')
587 return true;
588 /* ... or an identifier start character */
589 return is_ident_start(c);
590 }
591
592 /*
593 * parse_ident - parse a SQL qualified identifier into separate identifiers.
594 * When strict mode is active (second parameter), then any chars after
595 * the last identifier are disallowed.
596 */
597 Datum
598 parse_ident(PG_FUNCTION_ARGS)
599 {
600 text *qualname = PG_GETARG_TEXT_PP(0);
601 bool strict = PG_GETARG_BOOL(1);
602 char *qualname_str = text_to_cstring(qualname);
603 ArrayBuildState *astate = NULL;
604 char *nextp;
605 bool after_dot = false;
606
607 /*
608 * The code below scribbles on qualname_str in some cases, so we should
609 * reconvert qualname if we need to show the original string in error
610 * messages.
611 */
612 nextp = qualname_str;
613
614 /* skip leading whitespace */
615 while (scanner_isspace(*nextp))
616 nextp++;
617
618 for (;;)
619 {
620 char *curname;
621 bool missing_ident = true;
622
623 if (*nextp == '"')
624 {
int8abs(PG_FUNCTION_ARGS)625 char *endp;
626
627 curname = nextp + 1;
628 for (;;)
629 {
630 endp = strchr(nextp + 1, '"');
631 if (endp == NULL)
632 ereport(ERROR,
633 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
634 errmsg("string is not a valid identifier: \"%s\"",
635 text_to_cstring(qualname)),
636 errdetail("String has unclosed double quotes.")));
637 if (endp[1] != '"')
638 break;
639 memmove(endp, endp + 1, strlen(endp));
640 nextp = endp;
641 }
int8mod(PG_FUNCTION_ARGS)642 nextp = endp + 1;
643 *endp = '\0';
644
645 if (endp - curname == 0)
646 ereport(ERROR,
647 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
648 errmsg("string is not a valid identifier: \"%s\"",
649 text_to_cstring(qualname)),
650 errdetail("Quoted identifier must not be empty.")));
651
652 astate = accumArrayResult(astate, CStringGetTextDatum(curname),
653 false, TEXTOID, CurrentMemoryContext);
654 missing_ident = false;
655 }
656 else if (is_ident_start((unsigned char) *nextp))
657 {
658 char *downname;
659 int len;
660 text *part;
661
662 curname = nextp++;
663 while (is_ident_cont((unsigned char) *nextp))
664 nextp++;
665
666 len = nextp - curname;
667
668 /*
669 * We don't implicitly truncate identifiers. This is useful for
670 * allowing the user to check for specific parts of the identifier
671 * being too long. It's easy enough for the user to get the
672 * truncated names by casting our output to name[].
673 */
674 downname = downcase_identifier(curname, len, false, false);
675 part = cstring_to_text_with_len(downname, len);
676 astate = accumArrayResult(astate, PointerGetDatum(part), false,
677 TEXTOID, CurrentMemoryContext);
678 missing_ident = false;
679 }
680
681 if (missing_ident)
682 {
683 /* Different error messages based on where we failed. */
684 if (*nextp == '.')
int8gcd_internal(int64 arg1,int64 arg2)685 ereport(ERROR,
686 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
687 errmsg("string is not a valid identifier: \"%s\"",
688 text_to_cstring(qualname)),
689 errdetail("No valid identifier before \".\".")));
690 else if (after_dot)
691 ereport(ERROR,
692 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
693 errmsg("string is not a valid identifier: \"%s\"",
694 text_to_cstring(qualname)),
695 errdetail("No valid identifier after \".\".")));
696 else
697 ereport(ERROR,
698 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
699 errmsg("string is not a valid identifier: \"%s\"",
700 text_to_cstring(qualname))));
701 }
702
703 while (scanner_isspace(*nextp))
704 nextp++;
705
706 if (*nextp == '.')
707 {
708 after_dot = true;
709 nextp++;
710 while (scanner_isspace(*nextp))
711 nextp++;
712 }
713 else if (*nextp == '\0')
714 {
715 break;
716 }
717 else
718 {
719 if (strict)
720 ereport(ERROR,
721 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
722 errmsg("string is not a valid identifier: \"%s\"",
723 text_to_cstring(qualname))));
724 break;
725 }
726 }
727
728 PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
729 }
730
731 /*
732 * pg_current_logfile
733 *
734 * Report current log file used by log collector by scanning current_logfiles.
735 */
736 Datum
737 pg_current_logfile(PG_FUNCTION_ARGS)
738 {
739 FILE *fd;
740 char lbuffer[MAXPGPATH];
741 char *logfmt;
742
743 /* The log format parameter is optional */
744 if (PG_NARGS() == 0 || PG_ARGISNULL(0))
745 logfmt = NULL;
int8gcd(PG_FUNCTION_ARGS)746 else
747 {
748 logfmt = text_to_cstring(PG_GETARG_TEXT_PP(0));
749
750 if (strcmp(logfmt, "stderr") != 0 && strcmp(logfmt, "csvlog") != 0)
751 ereport(ERROR,
752 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
753 errmsg("log format \"%s\" is not supported", logfmt),
754 errhint("The supported log formats are \"stderr\" and \"csvlog\".")));
755 }
756
757 fd = AllocateFile(LOG_METAINFO_DATAFILE, "r");
758 if (fd == NULL)
759 {
760 if (errno != ENOENT)
int8lcm(PG_FUNCTION_ARGS)761 ereport(ERROR,
762 (errcode_for_file_access(),
763 errmsg("could not read file \"%s\": %m",
764 LOG_METAINFO_DATAFILE)));
765 PG_RETURN_NULL();
766 }
767
768 #ifdef WIN32
769 /* syslogger.c writes CRLF line endings on Windows */
770 _setmode(_fileno(fd), _O_TEXT);
771 #endif
772
773 /*
774 * Read the file to gather current log filename(s) registered by the
775 * syslogger.
776 */
777 while (fgets(lbuffer, sizeof(lbuffer), fd) != NULL)
778 {
779 char *log_format;
780 char *log_filepath;
781 char *nlpos;
782
783 /* Extract log format and log file path from the line. */
784 log_format = lbuffer;
785 log_filepath = strchr(lbuffer, ' ');
786 if (log_filepath == NULL)
787 {
788 /* Uh oh. No space found, so file content is corrupted. */
789 elog(ERROR,
790 "missing space character in \"%s\"", LOG_METAINFO_DATAFILE);
791 break;
792 }
793
794 *log_filepath = '\0';
795 log_filepath++;
796 nlpos = strchr(log_filepath, '\n');
797 if (nlpos == NULL)
int8inc(PG_FUNCTION_ARGS)798 {
799 /* Uh oh. No newline found, so file content is corrupted. */
800 elog(ERROR,
801 "missing newline character in \"%s\"", LOG_METAINFO_DATAFILE);
802 break;
803 }
804 *nlpos = '\0';
805
806 if (logfmt == NULL || strcmp(logfmt, log_format) == 0)
807 {
808 FreeFile(fd);
809 PG_RETURN_TEXT_P(cstring_to_text(log_filepath));
810 }
811 }
812
813 /* Close the current log filename file. */
814 FreeFile(fd);
815
816 PG_RETURN_NULL();
817 }
818
819 /*
820 * Report current log file used by log collector (1 argument version)
821 *
822 * note: this wrapper is necessary to pass the sanity check in opr_sanity,
823 * which checks that all built-in functions that share the implementing C
824 * function take the same number of arguments
825 */
826 Datum
827 pg_current_logfile_1arg(PG_FUNCTION_ARGS)
828 {
829 return pg_current_logfile(fcinfo);
830 }
831
832 /*
833 * SQL wrapper around RelationGetReplicaIndex().
834 */
835 Datum
int8dec(PG_FUNCTION_ARGS)836 pg_get_replica_identity_index(PG_FUNCTION_ARGS)
837 {
838 Oid reloid = PG_GETARG_OID(0);
839 Oid idxoid;
840 Relation rel;
841
842 rel = table_open(reloid, AccessShareLock);
843 idxoid = RelationGetReplicaIndex(rel);
844 table_close(rel, AccessShareLock);
845
846 if (OidIsValid(idxoid))
847 PG_RETURN_OID(idxoid);
848 else
849 PG_RETURN_NULL();
850 }
851