1 /*-------------------------------------------------------------------------
2 *
3 * misc.c
4 *
5 *
6 * Portions Copyright (c) 1996-2016, 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 <math.h>
21 #include <unistd.h>
22
23 #include "access/sysattr.h"
24 #include "catalog/pg_authid.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 "common/keywords.h"
30 #include "funcapi.h"
31 #include "miscadmin.h"
32 #include "parser/scansup.h"
33 #include "postmaster/syslogger.h"
34 #include "rewrite/rewriteHandler.h"
35 #include "storage/fd.h"
36 #include "storage/pmsignal.h"
37 #include "storage/proc.h"
38 #include "storage/procarray.h"
39 #include "utils/lsyscache.h"
40 #include "utils/ruleutils.h"
41 #include "tcop/tcopprot.h"
42 #include "utils/acl.h"
43 #include "utils/builtins.h"
44 #include "utils/timestamp.h"
45
46 #define atooid(x) ((Oid) strtoul((x), NULL, 10))
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
551 #ifdef HAVE_INT64_TIMESTAMP
552 #define GetNowFloat() ((float8) GetCurrentTimestamp() / 1000000.0)
553 #else
554 #define GetNowFloat() GetCurrentTimestamp()
555 #endif
556
557 endtime = GetNowFloat() + secs;
558
559 for (;;)
560 {
561 float8 delay;
562 long delay_ms;
563
564 CHECK_FOR_INTERRUPTS();
565
566 delay = endtime - GetNowFloat();
567 if (delay >= 600.0)
568 delay_ms = 600000;
569 else if (delay > 0.0)
570 delay_ms = (long) ceil(delay * 1000.0);
571 else
572 break;
573
574 (void) WaitLatch(MyLatch,
575 WL_LATCH_SET | WL_TIMEOUT,
576 delay_ms);
577 ResetLatch(MyLatch);
578 }
579
580 PG_RETURN_VOID();
581 }
582
583 /* Function to return the list of grammar keywords */
584 Datum
pg_get_keywords(PG_FUNCTION_ARGS)585 pg_get_keywords(PG_FUNCTION_ARGS)
586 {
587 FuncCallContext *funcctx;
588
589 if (SRF_IS_FIRSTCALL())
590 {
591 MemoryContext oldcontext;
592 TupleDesc tupdesc;
593
594 funcctx = SRF_FIRSTCALL_INIT();
595 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
596
597 tupdesc = CreateTemplateTupleDesc(3, false);
598 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "word",
599 TEXTOID, -1, 0);
600 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "catcode",
601 CHAROID, -1, 0);
602 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "catdesc",
603 TEXTOID, -1, 0);
604
605 funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
606
607 MemoryContextSwitchTo(oldcontext);
608 }
609
610 funcctx = SRF_PERCALL_SETUP();
611
612 if (funcctx->call_cntr < NumScanKeywords)
613 {
614 char *values[3];
615 HeapTuple tuple;
616
617 /* cast-away-const is ugly but alternatives aren't much better */
618 values[0] = (char *) ScanKeywords[funcctx->call_cntr].name;
619
620 switch (ScanKeywords[funcctx->call_cntr].category)
621 {
622 case UNRESERVED_KEYWORD:
623 values[1] = "U";
624 values[2] = _("unreserved");
625 break;
626 case COL_NAME_KEYWORD:
627 values[1] = "C";
628 values[2] = _("unreserved (cannot be function or type name)");
629 break;
630 case TYPE_FUNC_NAME_KEYWORD:
631 values[1] = "T";
632 values[2] = _("reserved (can be function or type name)");
633 break;
634 case RESERVED_KEYWORD:
635 values[1] = "R";
636 values[2] = _("reserved");
637 break;
638 default: /* shouldn't be possible */
639 values[1] = NULL;
640 values[2] = NULL;
641 break;
642 }
643
644 tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
645
646 SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
647 }
648
649 SRF_RETURN_DONE(funcctx);
650 }
651
652
653 /*
654 * Return the type of the argument.
655 */
656 Datum
pg_typeof(PG_FUNCTION_ARGS)657 pg_typeof(PG_FUNCTION_ARGS)
658 {
659 PG_RETURN_OID(get_fn_expr_argtype(fcinfo->flinfo, 0));
660 }
661
662
663 /*
664 * Implementation of the COLLATE FOR expression; returns the collation
665 * of the argument.
666 */
667 Datum
pg_collation_for(PG_FUNCTION_ARGS)668 pg_collation_for(PG_FUNCTION_ARGS)
669 {
670 Oid typeid;
671 Oid collid;
672
673 typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
674 if (!typeid)
675 PG_RETURN_NULL();
676 if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
677 ereport(ERROR,
678 (errcode(ERRCODE_DATATYPE_MISMATCH),
679 errmsg("collations are not supported by type %s",
680 format_type_be(typeid))));
681
682 collid = PG_GET_COLLATION();
683 if (!collid)
684 PG_RETURN_NULL();
685 PG_RETURN_TEXT_P(cstring_to_text(generate_collation_name(collid)));
686 }
687
688
689 /*
690 * pg_relation_is_updatable - determine which update events the specified
691 * relation supports.
692 *
693 * This relies on relation_is_updatable() in rewriteHandler.c, which see
694 * for additional information.
695 */
696 Datum
pg_relation_is_updatable(PG_FUNCTION_ARGS)697 pg_relation_is_updatable(PG_FUNCTION_ARGS)
698 {
699 Oid reloid = PG_GETARG_OID(0);
700 bool include_triggers = PG_GETARG_BOOL(1);
701
702 PG_RETURN_INT32(relation_is_updatable(reloid, NIL, include_triggers, NULL));
703 }
704
705 /*
706 * pg_column_is_updatable - determine whether a column is updatable
707 *
708 * This function encapsulates the decision about just what
709 * information_schema.columns.is_updatable actually means. It's not clear
710 * whether deletability of the column's relation should be required, so
711 * we want that decision in C code where we could change it without initdb.
712 */
713 Datum
pg_column_is_updatable(PG_FUNCTION_ARGS)714 pg_column_is_updatable(PG_FUNCTION_ARGS)
715 {
716 Oid reloid = PG_GETARG_OID(0);
717 AttrNumber attnum = PG_GETARG_INT16(1);
718 AttrNumber col = attnum - FirstLowInvalidHeapAttributeNumber;
719 bool include_triggers = PG_GETARG_BOOL(2);
720 int events;
721
722 /* System columns are never updatable */
723 if (attnum <= 0)
724 PG_RETURN_BOOL(false);
725
726 events = relation_is_updatable(reloid, NIL, include_triggers,
727 bms_make_singleton(col));
728
729 /* We require both updatability and deletability of the relation */
730 #define REQ_EVENTS ((1 << CMD_UPDATE) | (1 << CMD_DELETE))
731
732 PG_RETURN_BOOL((events & REQ_EVENTS) == REQ_EVENTS);
733 }
734
735
736 /*
737 * Is character a valid identifier start?
738 * Must match scan.l's {ident_start} character class.
739 */
740 static bool
is_ident_start(unsigned char c)741 is_ident_start(unsigned char c)
742 {
743 /* Underscores and ASCII letters are OK */
744 if (c == '_')
745 return true;
746 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
747 return true;
748 /* Any high-bit-set character is OK (might be part of a multibyte char) */
749 if (IS_HIGHBIT_SET(c))
750 return true;
751 return false;
752 }
753
754 /*
755 * Is character a valid identifier continuation?
756 * Must match scan.l's {ident_cont} character class.
757 */
758 static bool
is_ident_cont(unsigned char c)759 is_ident_cont(unsigned char c)
760 {
761 /* Can be digit or dollar sign ... */
762 if ((c >= '0' && c <= '9') || c == '$')
763 return true;
764 /* ... or an identifier start character */
765 return is_ident_start(c);
766 }
767
768 /*
769 * parse_ident - parse a SQL qualified identifier into separate identifiers.
770 * When strict mode is active (second parameter), then any chars after
771 * the last identifier are disallowed.
772 */
773 Datum
parse_ident(PG_FUNCTION_ARGS)774 parse_ident(PG_FUNCTION_ARGS)
775 {
776 text *qualname = PG_GETARG_TEXT_PP(0);
777 bool strict = PG_GETARG_BOOL(1);
778 char *qualname_str = text_to_cstring(qualname);
779 ArrayBuildState *astate = NULL;
780 char *nextp;
781 bool after_dot = false;
782
783 /*
784 * The code below scribbles on qualname_str in some cases, so we should
785 * reconvert qualname if we need to show the original string in error
786 * messages.
787 */
788 nextp = qualname_str;
789
790 /* skip leading whitespace */
791 while (scanner_isspace(*nextp))
792 nextp++;
793
794 for (;;)
795 {
796 char *curname;
797 bool missing_ident = true;
798
799 if (*nextp == '"')
800 {
801 char *endp;
802
803 curname = nextp + 1;
804 for (;;)
805 {
806 endp = strchr(nextp + 1, '"');
807 if (endp == NULL)
808 ereport(ERROR,
809 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
810 errmsg("string is not a valid identifier: \"%s\"",
811 text_to_cstring(qualname)),
812 errdetail("String has unclosed double quotes.")));
813 if (endp[1] != '"')
814 break;
815 memmove(endp, endp + 1, strlen(endp));
816 nextp = endp;
817 }
818 nextp = endp + 1;
819 *endp = '\0';
820
821 if (endp - curname == 0)
822 ereport(ERROR,
823 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
824 errmsg("string is not a valid identifier: \"%s\"",
825 text_to_cstring(qualname)),
826 errdetail("Quoted identifier must not be empty.")));
827
828 astate = accumArrayResult(astate, CStringGetTextDatum(curname),
829 false, TEXTOID, CurrentMemoryContext);
830 missing_ident = false;
831 }
832 else if (is_ident_start((unsigned char) *nextp))
833 {
834 char *downname;
835 int len;
836 text *part;
837
838 curname = nextp++;
839 while (is_ident_cont((unsigned char) *nextp))
840 nextp++;
841
842 len = nextp - curname;
843
844 /*
845 * We don't implicitly truncate identifiers. This is useful for
846 * allowing the user to check for specific parts of the identifier
847 * being too long. It's easy enough for the user to get the
848 * truncated names by casting our output to name[].
849 */
850 downname = downcase_identifier(curname, len, false, false);
851 part = cstring_to_text_with_len(downname, len);
852 astate = accumArrayResult(astate, PointerGetDatum(part), false,
853 TEXTOID, CurrentMemoryContext);
854 missing_ident = false;
855 }
856
857 if (missing_ident)
858 {
859 /* Different error messages based on where we failed. */
860 if (*nextp == '.')
861 ereport(ERROR,
862 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
863 errmsg("string is not a valid identifier: \"%s\"",
864 text_to_cstring(qualname)),
865 errdetail("No valid identifier before \".\".")));
866 else if (after_dot)
867 ereport(ERROR,
868 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
869 errmsg("string is not a valid identifier: \"%s\"",
870 text_to_cstring(qualname)),
871 errdetail("No valid identifier after \".\".")));
872 else
873 ereport(ERROR,
874 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
875 errmsg("string is not a valid identifier: \"%s\"",
876 text_to_cstring(qualname))));
877 }
878
879 while (scanner_isspace(*nextp))
880 nextp++;
881
882 if (*nextp == '.')
883 {
884 after_dot = true;
885 nextp++;
886 while (scanner_isspace(*nextp))
887 nextp++;
888 }
889 else if (*nextp == '\0')
890 {
891 break;
892 }
893 else
894 {
895 if (strict)
896 ereport(ERROR,
897 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
898 errmsg("string is not a valid identifier: \"%s\"",
899 text_to_cstring(qualname))));
900 break;
901 }
902 }
903
904 PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
905 }
906