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