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