PostgreSQL Source Code  git master
dumputils.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * Utility routines for SQL dumping
4  *
5  * Basically this is stuff that is useful in both pg_dump and pg_dumpall.
6  *
7  *
8  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
9  * Portions Copyright (c) 1994, Regents of the University of California
10  *
11  * src/bin/pg_dump/dumputils.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres_fe.h"
16 
17 #include <ctype.h>
18 
19 #include "dumputils.h"
20 #include "fe_utils/string_utils.h"
21 
22 
23 static bool parseAclItem(const char *item, const char *type,
24  const char *name, const char *subname, int remoteVersion,
25  PQExpBuffer grantee, PQExpBuffer grantor,
26  PQExpBuffer privs, PQExpBuffer privswgo);
27 static char *dequoteAclUserName(PQExpBuffer output, char *input);
28 static void AddAcl(PQExpBuffer aclbuf, const char *keyword,
29  const char *subname);
30 
31 
32 /*
33  * Build GRANT/REVOKE command(s) for an object.
34  *
35  * name: the object name, in the form to use in the commands (already quoted)
36  * subname: the sub-object name, if any (already quoted); NULL if none
37  * nspname: the namespace the object is in (NULL if none); not pre-quoted
38  * type: the object type (as seen in GRANT command: must be one of
39  * TABLE, SEQUENCE, FUNCTION, PROCEDURE, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
40  * FOREIGN DATA WRAPPER, SERVER, PARAMETER or LARGE OBJECT)
41  * acls: the ACL string fetched from the database
42  * baseacls: the initial ACL string for this object
43  * owner: username of object owner (will be passed through fmtId); can be
44  * NULL or empty string to indicate "no owner known"
45  * prefix: string to prefix to each generated command; typically empty
46  * remoteVersion: version of database
47  *
48  * Returns true if okay, false if could not parse the acl string.
49  * The resulting commands (if any) are appended to the contents of 'sql'.
50  *
51  * baseacls is typically the result of acldefault() for the object's type
52  * and owner. However, if there is a pg_init_privs entry for the object,
53  * it should instead be the initprivs ACLs. When acls is itself a
54  * pg_init_privs entry, baseacls is what to dump that relative to; then
55  * it can be either an acldefault() value or an empty ACL "{}".
56  *
57  * Note: when processing a default ACL, prefix is "ALTER DEFAULT PRIVILEGES "
58  * or something similar, and name is an empty string.
59  *
60  * Note: beware of passing a fmtId() result directly as 'name' or 'subname',
61  * since this routine uses fmtId() internally.
62  */
63 bool
64 buildACLCommands(const char *name, const char *subname, const char *nspname,
65  const char *type, const char *acls, const char *baseacls,
66  const char *owner, const char *prefix, int remoteVersion,
67  PQExpBuffer sql)
68 {
69  bool ok = true;
70  char **aclitems = NULL;
71  char **baseitems = NULL;
72  char **grantitems = NULL;
73  char **revokeitems = NULL;
74  int naclitems = 0;
75  int nbaseitems = 0;
76  int ngrantitems = 0;
77  int nrevokeitems = 0;
78  int i;
79  PQExpBuffer grantee,
80  grantor,
81  privs,
82  privswgo;
83  PQExpBuffer firstsql,
84  secondsql;
85 
86  /*
87  * If the acl was NULL (initial default state), we need do nothing. Note
88  * that this is distinguishable from all-privileges-revoked, which will
89  * look like an empty array ("{}").
90  */
91  if (acls == NULL || *acls == '\0')
92  return true; /* object has default permissions */
93 
94  /* treat empty-string owner same as NULL */
95  if (owner && *owner == '\0')
96  owner = NULL;
97 
98  /* Parse the acls array */
99  if (!parsePGArray(acls, &aclitems, &naclitems))
100  {
101  if (aclitems)
102  free(aclitems);
103  return false;
104  }
105 
106  /* Parse the baseacls too */
107  if (!parsePGArray(baseacls, &baseitems, &nbaseitems))
108  {
109  if (aclitems)
110  free(aclitems);
111  if (baseitems)
112  free(baseitems);
113  return false;
114  }
115 
116  /*
117  * Compare the actual ACL with the base ACL, extracting the privileges
118  * that need to be granted (i.e., are in the actual ACL but not the base
119  * ACL) and the ones that need to be revoked (the reverse). We use plain
120  * string comparisons to check for matches. In principle that could be
121  * fooled by extraneous issues such as whitespace, but since all these
122  * strings are the work of aclitemout(), it should be OK in practice.
123  * Besides, a false mismatch will just cause the output to be a little
124  * more verbose than it really needed to be.
125  */
126  grantitems = (char **) pg_malloc(naclitems * sizeof(char *));
127  for (i = 0; i < naclitems; i++)
128  {
129  bool found = false;
130 
131  for (int j = 0; j < nbaseitems; j++)
132  {
133  if (strcmp(aclitems[i], baseitems[j]) == 0)
134  {
135  found = true;
136  break;
137  }
138  }
139  if (!found)
140  grantitems[ngrantitems++] = aclitems[i];
141  }
142  revokeitems = (char **) pg_malloc(nbaseitems * sizeof(char *));
143  for (i = 0; i < nbaseitems; i++)
144  {
145  bool found = false;
146 
147  for (int j = 0; j < naclitems; j++)
148  {
149  if (strcmp(baseitems[i], aclitems[j]) == 0)
150  {
151  found = true;
152  break;
153  }
154  }
155  if (!found)
156  revokeitems[nrevokeitems++] = baseitems[i];
157  }
158 
159  /* Prepare working buffers */
160  grantee = createPQExpBuffer();
161  grantor = createPQExpBuffer();
162  privs = createPQExpBuffer();
163  privswgo = createPQExpBuffer();
164 
165  /*
166  * At the end, these two will be pasted together to form the result.
167  */
168  firstsql = createPQExpBuffer();
169  secondsql = createPQExpBuffer();
170 
171  /*
172  * Build REVOKE statements for ACLs listed in revokeitems[].
173  */
174  for (i = 0; i < nrevokeitems; i++)
175  {
176  if (!parseAclItem(revokeitems[i],
177  type, name, subname, remoteVersion,
178  grantee, grantor, privs, NULL))
179  {
180  ok = false;
181  break;
182  }
183 
184  if (privs->len > 0)
185  {
186  appendPQExpBuffer(firstsql, "%sREVOKE %s ON %s ",
187  prefix, privs->data, type);
188  if (nspname && *nspname)
189  appendPQExpBuffer(firstsql, "%s.", fmtId(nspname));
190  appendPQExpBuffer(firstsql, "%s FROM ", name);
191  if (grantee->len == 0)
192  appendPQExpBufferStr(firstsql, "PUBLIC;\n");
193  else
194  appendPQExpBuffer(firstsql, "%s;\n",
195  fmtId(grantee->data));
196  }
197  }
198 
199  /*
200  * At this point we have issued REVOKE statements for all initial and
201  * default privileges that are no longer present on the object, so we are
202  * almost ready to GRANT the privileges listed in grantitems[].
203  *
204  * We still need some hacking though to cover the case where new default
205  * public privileges are added in new versions: the REVOKE ALL will revoke
206  * them, leading to behavior different from what the old version had,
207  * which is generally not what's wanted. So add back default privs if the
208  * source database is too old to have had that particular priv. (As of
209  * right now, no such cases exist in supported versions.)
210  */
211 
212  /*
213  * Scan individual ACL items to be granted.
214  *
215  * The order in which privileges appear in the ACL string (the order they
216  * have been GRANT'd in, which the backend maintains) must be preserved to
217  * ensure that GRANTs WITH GRANT OPTION and subsequent GRANTs based on
218  * those are dumped in the correct order. However, some old server
219  * versions will show grants to PUBLIC before the owner's own grants; for
220  * consistency's sake, force the owner's grants to be output first.
221  */
222  for (i = 0; i < ngrantitems; i++)
223  {
224  if (parseAclItem(grantitems[i], type, name, subname, remoteVersion,
225  grantee, grantor, privs, privswgo))
226  {
227  /*
228  * If the grantor isn't the owner, we'll need to use SET SESSION
229  * AUTHORIZATION to become the grantor. Issue the SET/RESET only
230  * if there's something useful to do.
231  */
232  if (privs->len > 0 || privswgo->len > 0)
233  {
234  PQExpBuffer thissql;
235 
236  /* Set owner as grantor if that's not explicit in the ACL */
237  if (grantor->len == 0 && owner)
238  printfPQExpBuffer(grantor, "%s", owner);
239 
240  /* Make sure owner's own grants are output before others */
241  if (owner &&
242  strcmp(grantee->data, owner) == 0 &&
243  strcmp(grantor->data, owner) == 0)
244  thissql = firstsql;
245  else
246  thissql = secondsql;
247 
248  if (grantor->len > 0
249  && (!owner || strcmp(owner, grantor->data) != 0))
250  appendPQExpBuffer(thissql, "SET SESSION AUTHORIZATION %s;\n",
251  fmtId(grantor->data));
252 
253  if (privs->len > 0)
254  {
255  appendPQExpBuffer(thissql, "%sGRANT %s ON %s ",
256  prefix, privs->data, type);
257  if (nspname && *nspname)
258  appendPQExpBuffer(thissql, "%s.", fmtId(nspname));
259  appendPQExpBuffer(thissql, "%s TO ", name);
260  if (grantee->len == 0)
261  appendPQExpBufferStr(thissql, "PUBLIC;\n");
262  else
263  appendPQExpBuffer(thissql, "%s;\n", fmtId(grantee->data));
264  }
265  if (privswgo->len > 0)
266  {
267  appendPQExpBuffer(thissql, "%sGRANT %s ON %s ",
268  prefix, privswgo->data, type);
269  if (nspname && *nspname)
270  appendPQExpBuffer(thissql, "%s.", fmtId(nspname));
271  appendPQExpBuffer(thissql, "%s TO ", name);
272  if (grantee->len == 0)
273  appendPQExpBufferStr(thissql, "PUBLIC");
274  else
275  appendPQExpBufferStr(thissql, fmtId(grantee->data));
276  appendPQExpBufferStr(thissql, " WITH GRANT OPTION;\n");
277  }
278 
279  if (grantor->len > 0
280  && (!owner || strcmp(owner, grantor->data) != 0))
281  appendPQExpBufferStr(thissql, "RESET SESSION AUTHORIZATION;\n");
282  }
283  }
284  else
285  {
286  /* parseAclItem failed, give up */
287  ok = false;
288  break;
289  }
290  }
291 
292  destroyPQExpBuffer(grantee);
293  destroyPQExpBuffer(grantor);
294  destroyPQExpBuffer(privs);
295  destroyPQExpBuffer(privswgo);
296 
297  appendPQExpBuffer(sql, "%s%s", firstsql->data, secondsql->data);
298  destroyPQExpBuffer(firstsql);
299  destroyPQExpBuffer(secondsql);
300 
301  if (aclitems)
302  free(aclitems);
303  if (baseitems)
304  free(baseitems);
305  if (grantitems)
306  free(grantitems);
307  if (revokeitems)
308  free(revokeitems);
309 
310  return ok;
311 }
312 
313 /*
314  * Build ALTER DEFAULT PRIVILEGES command(s) for a single pg_default_acl entry.
315  *
316  * type: the object type (TABLES, FUNCTIONS, etc)
317  * nspname: schema name, or NULL for global default privileges
318  * acls: the ACL string fetched from the database
319  * acldefault: the appropriate default ACL for the object type and owner
320  * owner: username of privileges owner (will be passed through fmtId)
321  * remoteVersion: version of database
322  *
323  * Returns true if okay, false if could not parse the acl string.
324  * The resulting commands (if any) are appended to the contents of 'sql'.
325  */
326 bool
327 buildDefaultACLCommands(const char *type, const char *nspname,
328  const char *acls, const char *acldefault,
329  const char *owner,
330  int remoteVersion,
331  PQExpBuffer sql)
332 {
333  PQExpBuffer prefix;
334 
335  prefix = createPQExpBuffer();
336 
337  /*
338  * We incorporate the target role directly into the command, rather than
339  * playing around with SET ROLE or anything like that. This is so that a
340  * permissions error leads to nothing happening, rather than changing
341  * default privileges for the wrong user.
342  */
343  appendPQExpBuffer(prefix, "ALTER DEFAULT PRIVILEGES FOR ROLE %s ",
344  fmtId(owner));
345  if (nspname)
346  appendPQExpBuffer(prefix, "IN SCHEMA %s ", fmtId(nspname));
347 
348  /*
349  * There's no such thing as initprivs for a default ACL, so the base ACL
350  * is always just the object-type-specific default.
351  */
352  if (!buildACLCommands("", NULL, NULL, type,
353  acls, acldefault, owner,
354  prefix->data, remoteVersion, sql))
355  {
356  destroyPQExpBuffer(prefix);
357  return false;
358  }
359 
360  destroyPQExpBuffer(prefix);
361 
362  return true;
363 }
364 
365 /*
366  * This will parse an aclitem string, having the general form
367  * username=privilegecodes/grantor
368  *
369  * Returns true on success, false on parse error. On success, the components
370  * of the string are returned in the PQExpBuffer parameters.
371  *
372  * The returned grantee string will be the dequoted username, or an empty
373  * string in the case of a grant to PUBLIC. The returned grantor is the
374  * dequoted grantor name. Privilege characters are translated to GRANT/REVOKE
375  * comma-separated privileges lists. If "privswgo" is non-NULL, the result is
376  * separate lists for privileges with grant option ("privswgo") and without
377  * ("privs"). Otherwise, "privs" bears every relevant privilege, ignoring the
378  * grant option distinction.
379  *
380  * Note: for cross-version compatibility, it's important to use ALL to
381  * represent the privilege sets whenever appropriate.
382  */
383 static bool
384 parseAclItem(const char *item, const char *type,
385  const char *name, const char *subname, int remoteVersion,
386  PQExpBuffer grantee, PQExpBuffer grantor,
387  PQExpBuffer privs, PQExpBuffer privswgo)
388 {
389  char *buf;
390  bool all_with_go = true;
391  bool all_without_go = true;
392  char *eqpos;
393  char *slpos;
394  char *pos;
395 
396  buf = pg_strdup(item);
397 
398  /* user or group name is string up to = */
399  eqpos = dequoteAclUserName(grantee, buf);
400  if (*eqpos != '=')
401  {
402  pg_free(buf);
403  return false;
404  }
405 
406  /* grantor should appear after / */
407  slpos = strchr(eqpos + 1, '/');
408  if (slpos)
409  {
410  *slpos++ = '\0';
411  slpos = dequoteAclUserName(grantor, slpos);
412  if (*slpos != '\0')
413  {
414  pg_free(buf);
415  return false;
416  }
417  }
418  else
419  {
420  pg_free(buf);
421  return false;
422  }
423 
424  /* privilege codes */
425 #define CONVERT_PRIV(code, keywd) \
426 do { \
427  if ((pos = strchr(eqpos + 1, code))) \
428  { \
429  if (*(pos + 1) == '*' && privswgo != NULL) \
430  { \
431  AddAcl(privswgo, keywd, subname); \
432  all_without_go = false; \
433  } \
434  else \
435  { \
436  AddAcl(privs, keywd, subname); \
437  all_with_go = false; \
438  } \
439  } \
440  else \
441  all_with_go = all_without_go = false; \
442 } while (0)
443 
444  resetPQExpBuffer(privs);
445  resetPQExpBuffer(privswgo);
446 
447  if (strcmp(type, "TABLE") == 0 || strcmp(type, "SEQUENCE") == 0 ||
448  strcmp(type, "TABLES") == 0 || strcmp(type, "SEQUENCES") == 0)
449  {
450  CONVERT_PRIV('r', "SELECT");
451 
452  if (strcmp(type, "SEQUENCE") == 0 ||
453  strcmp(type, "SEQUENCES") == 0)
454  /* sequence only */
455  CONVERT_PRIV('U', "USAGE");
456  else
457  {
458  /* table only */
459  CONVERT_PRIV('a', "INSERT");
460  CONVERT_PRIV('x', "REFERENCES");
461  /* rest are not applicable to columns */
462  if (subname == NULL)
463  {
464  CONVERT_PRIV('d', "DELETE");
465  CONVERT_PRIV('t', "TRIGGER");
466  CONVERT_PRIV('D', "TRUNCATE");
467  }
468  }
469 
470  /* UPDATE */
471  CONVERT_PRIV('w', "UPDATE");
472  }
473  else if (strcmp(type, "FUNCTION") == 0 ||
474  strcmp(type, "FUNCTIONS") == 0)
475  CONVERT_PRIV('X', "EXECUTE");
476  else if (strcmp(type, "PROCEDURE") == 0 ||
477  strcmp(type, "PROCEDURES") == 0)
478  CONVERT_PRIV('X', "EXECUTE");
479  else if (strcmp(type, "LANGUAGE") == 0)
480  CONVERT_PRIV('U', "USAGE");
481  else if (strcmp(type, "SCHEMA") == 0 ||
482  strcmp(type, "SCHEMAS") == 0)
483  {
484  CONVERT_PRIV('C', "CREATE");
485  CONVERT_PRIV('U', "USAGE");
486  }
487  else if (strcmp(type, "DATABASE") == 0)
488  {
489  CONVERT_PRIV('C', "CREATE");
490  CONVERT_PRIV('c', "CONNECT");
491  CONVERT_PRIV('T', "TEMPORARY");
492  }
493  else if (strcmp(type, "TABLESPACE") == 0)
494  CONVERT_PRIV('C', "CREATE");
495  else if (strcmp(type, "TYPE") == 0 ||
496  strcmp(type, "TYPES") == 0)
497  CONVERT_PRIV('U', "USAGE");
498  else if (strcmp(type, "FOREIGN DATA WRAPPER") == 0)
499  CONVERT_PRIV('U', "USAGE");
500  else if (strcmp(type, "FOREIGN SERVER") == 0)
501  CONVERT_PRIV('U', "USAGE");
502  else if (strcmp(type, "FOREIGN TABLE") == 0)
503  CONVERT_PRIV('r', "SELECT");
504  else if (strcmp(type, "PARAMETER") == 0)
505  {
506  CONVERT_PRIV('s', "SET");
507  CONVERT_PRIV('A', "ALTER SYSTEM");
508  }
509  else if (strcmp(type, "LARGE OBJECT") == 0)
510  {
511  CONVERT_PRIV('r', "SELECT");
512  CONVERT_PRIV('w', "UPDATE");
513  }
514  else
515  abort();
516 
517 #undef CONVERT_PRIV
518 
519  if (all_with_go)
520  {
521  resetPQExpBuffer(privs);
522  printfPQExpBuffer(privswgo, "ALL");
523  if (subname)
524  appendPQExpBuffer(privswgo, "(%s)", subname);
525  }
526  else if (all_without_go)
527  {
528  resetPQExpBuffer(privswgo);
529  printfPQExpBuffer(privs, "ALL");
530  if (subname)
531  appendPQExpBuffer(privs, "(%s)", subname);
532  }
533 
534  pg_free(buf);
535 
536  return true;
537 }
538 
539 /*
540  * Transfer the role name at *input into the output buffer, adding
541  * quoting according to the same rules as putid() in backend's acl.c.
542  */
543 void
545 {
546  const char *src;
547  bool safe = true;
548 
549  for (src = input; *src; src++)
550  {
551  /* This test had better match what putid() does */
552  if (!isalnum((unsigned char) *src) && *src != '_')
553  {
554  safe = false;
555  break;
556  }
557  }
558  if (!safe)
560  for (src = input; *src; src++)
561  {
562  /* A double quote character in a username is encoded as "" */
563  if (*src == '"')
566  }
567  if (!safe)
569 }
570 
571 /*
572  * Transfer a user or group name starting at *input into the output buffer,
573  * dequoting if needed. Returns a pointer to just past the input name.
574  * The name is taken to end at an unquoted '=' or end of string.
575  * Note: unlike quoteAclUserName(), this first clears the output buffer.
576  */
577 static char *
579 {
581 
582  while (*input && *input != '=')
583  {
584  /*
585  * If user name isn't quoted, then just add it to the output buffer
586  */
587  if (*input != '"')
588  appendPQExpBufferChar(output, *input++);
589  else
590  {
591  /* Otherwise, it's a quoted username */
592  input++;
593  /* Loop until we come across an unescaped quote */
594  while (!(*input == '"' && *(input + 1) != '"'))
595  {
596  if (*input == '\0')
597  return input; /* really a syntax error... */
598 
599  /*
600  * Quoting convention is to escape " as "". Keep this code in
601  * sync with putid() in backend's acl.c.
602  */
603  if (*input == '"' && *(input + 1) == '"')
604  input++;
605  appendPQExpBufferChar(output, *input++);
606  }
607  input++;
608  }
609  }
610  return input;
611 }
612 
613 /*
614  * Append a privilege keyword to a keyword list, inserting comma if needed.
615  */
616 static void
617 AddAcl(PQExpBuffer aclbuf, const char *keyword, const char *subname)
618 {
619  if (aclbuf->len > 0)
620  appendPQExpBufferChar(aclbuf, ',');
621  appendPQExpBufferStr(aclbuf, keyword);
622  if (subname)
623  appendPQExpBuffer(aclbuf, "(%s)", subname);
624 }
625 
626 
627 /*
628  * buildShSecLabelQuery
629  *
630  * Build a query to retrieve security labels for a shared object.
631  * The object is identified by its OID plus the name of the catalog
632  * it can be found in (e.g., "pg_database" for database names).
633  * The query is appended to "sql". (We don't execute it here so as to
634  * keep this file free of assumptions about how to deal with SQL errors.)
635  */
636 void
637 buildShSecLabelQuery(const char *catalog_name, Oid objectId,
638  PQExpBuffer sql)
639 {
640  appendPQExpBuffer(sql,
641  "SELECT provider, label FROM pg_catalog.pg_shseclabel "
642  "WHERE classoid = 'pg_catalog.%s'::pg_catalog.regclass "
643  "AND objoid = '%u'", catalog_name, objectId);
644 }
645 
646 /*
647  * emitShSecLabels
648  *
649  * Construct SECURITY LABEL commands using the data retrieved by the query
650  * generated by buildShSecLabelQuery, and append them to "buffer".
651  * Here, the target object is identified by its type name (e.g. "DATABASE")
652  * and its name (not pre-quoted).
653  */
654 void
656  const char *objtype, const char *objname)
657 {
658  int i;
659 
660  for (i = 0; i < PQntuples(res); i++)
661  {
662  char *provider = PQgetvalue(res, i, 0);
663  char *label = PQgetvalue(res, i, 1);
664 
665  /* must use fmtId result before calling it again */
666  appendPQExpBuffer(buffer,
667  "SECURITY LABEL FOR %s ON %s",
668  fmtId(provider), objtype);
669  appendPQExpBuffer(buffer,
670  " %s IS ",
671  fmtId(objname));
673  appendPQExpBufferStr(buffer, ";\n");
674  }
675 }
676 
677 
678 /*
679  * Detect whether the given GUC variable is of GUC_LIST_QUOTE type.
680  *
681  * It'd be better if we could inquire this directly from the backend; but even
682  * if there were a function for that, it could only tell us about variables
683  * currently known to guc.c, so that it'd be unsafe for extensions to declare
684  * GUC_LIST_QUOTE variables anyway. Lacking a solution for that, it doesn't
685  * seem worth the work to do more than have this list, which must be kept in
686  * sync with the variables actually marked GUC_LIST_QUOTE in guc.c.
687  */
688 bool
690 {
691  if (pg_strcasecmp(name, "local_preload_libraries") == 0 ||
692  pg_strcasecmp(name, "search_path") == 0 ||
693  pg_strcasecmp(name, "session_preload_libraries") == 0 ||
694  pg_strcasecmp(name, "shared_preload_libraries") == 0 ||
695  pg_strcasecmp(name, "temp_tablespaces") == 0 ||
696  pg_strcasecmp(name, "unix_socket_directories") == 0)
697  return true;
698  else
699  return false;
700 }
701 
702 /*
703  * SplitGUCList --- parse a string containing identifiers or file names
704  *
705  * This is used to split the value of a GUC_LIST_QUOTE GUC variable, without
706  * presuming whether the elements will be taken as identifiers or file names.
707  * See comparable code in src/backend/utils/adt/varlena.c.
708  *
709  * Inputs:
710  * rawstring: the input string; must be overwritable! On return, it's
711  * been modified to contain the separated identifiers.
712  * separator: the separator punctuation expected between identifiers
713  * (typically '.' or ','). Whitespace may also appear around
714  * identifiers.
715  * Outputs:
716  * namelist: receives a malloc'd, null-terminated array of pointers to
717  * identifiers within rawstring. Caller should free this
718  * even on error return.
719  *
720  * Returns true if okay, false if there is a syntax error in the string.
721  */
722 bool
723 SplitGUCList(char *rawstring, char separator,
724  char ***namelist)
725 {
726  char *nextp = rawstring;
727  bool done = false;
728  char **nextptr;
729 
730  /*
731  * Since we disallow empty identifiers, this is a conservative
732  * overestimate of the number of pointers we could need. Allow one for
733  * list terminator.
734  */
735  *namelist = nextptr = (char **)
736  pg_malloc((strlen(rawstring) / 2 + 2) * sizeof(char *));
737  *nextptr = NULL;
738 
739  while (isspace((unsigned char) *nextp))
740  nextp++; /* skip leading whitespace */
741 
742  if (*nextp == '\0')
743  return true; /* allow empty string */
744 
745  /* At the top of the loop, we are at start of a new identifier. */
746  do
747  {
748  char *curname;
749  char *endp;
750 
751  if (*nextp == '"')
752  {
753  /* Quoted name --- collapse quote-quote pairs */
754  curname = nextp + 1;
755  for (;;)
756  {
757  endp = strchr(nextp + 1, '"');
758  if (endp == NULL)
759  return false; /* mismatched quotes */
760  if (endp[1] != '"')
761  break; /* found end of quoted name */
762  /* Collapse adjacent quotes into one quote, and look again */
763  memmove(endp, endp + 1, strlen(endp));
764  nextp = endp;
765  }
766  /* endp now points at the terminating quote */
767  nextp = endp + 1;
768  }
769  else
770  {
771  /* Unquoted name --- extends to separator or whitespace */
772  curname = nextp;
773  while (*nextp && *nextp != separator &&
774  !isspace((unsigned char) *nextp))
775  nextp++;
776  endp = nextp;
777  if (curname == nextp)
778  return false; /* empty unquoted name not allowed */
779  }
780 
781  while (isspace((unsigned char) *nextp))
782  nextp++; /* skip trailing whitespace */
783 
784  if (*nextp == separator)
785  {
786  nextp++;
787  while (isspace((unsigned char) *nextp))
788  nextp++; /* skip leading whitespace for next */
789  /* we expect another name, so done remains false */
790  }
791  else if (*nextp == '\0')
792  done = true;
793  else
794  return false; /* invalid syntax */
795 
796  /* Now safe to overwrite separator with a null */
797  *endp = '\0';
798 
799  /*
800  * Finished isolating current name --- add it to output array
801  */
802  *nextptr++ = curname;
803 
804  /* Loop back if we didn't reach end of string */
805  } while (!done);
806 
807  *nextptr = NULL;
808  return true;
809 }
810 
811 /*
812  * Helper function for dumping "ALTER DATABASE/ROLE SET ..." commands.
813  *
814  * Parse the contents of configitem (a "name=value" string), wrap it in
815  * a complete ALTER command, and append it to buf.
816  *
817  * type is DATABASE or ROLE, and name is the name of the database or role.
818  * If we need an "IN" clause, type2 and name2 similarly define what to put
819  * there; otherwise they should be NULL.
820  * conn is used only to determine string-literal quoting conventions.
821  */
822 void
823 makeAlterConfigCommand(PGconn *conn, const char *configitem,
824  const char *type, const char *name,
825  const char *type2, const char *name2,
827 {
828  char *mine;
829  char *pos;
830 
831  /* Parse the configitem. If we can't find an "=", silently do nothing. */
832  mine = pg_strdup(configitem);
833  pos = strchr(mine, '=');
834  if (pos == NULL)
835  {
836  pg_free(mine);
837  return;
838  }
839  *pos++ = '\0';
840 
841  /* Build the command, with suitable quoting for everything. */
842  appendPQExpBuffer(buf, "ALTER %s %s ", type, fmtId(name));
843  if (type2 != NULL && name2 != NULL)
844  appendPQExpBuffer(buf, "IN %s %s ", type2, fmtId(name2));
845  appendPQExpBuffer(buf, "SET %s TO ", fmtId(mine));
846 
847  /*
848  * Variables that are marked GUC_LIST_QUOTE were already fully quoted by
849  * flatten_set_variable_args() before they were put into the setconfig
850  * array. However, because the quoting rules used there aren't exactly
851  * like SQL's, we have to break the list value apart and then quote the
852  * elements as string literals. (The elements may be double-quoted as-is,
853  * but we can't just feed them to the SQL parser; it would do the wrong
854  * thing with elements that are zero-length or longer than NAMEDATALEN.)
855  *
856  * Variables that are not so marked should just be emitted as simple
857  * string literals. If the variable is not known to
858  * variable_is_guc_list_quote(), we'll do that; this makes it unsafe to
859  * use GUC_LIST_QUOTE for extension variables.
860  */
861  if (variable_is_guc_list_quote(mine))
862  {
863  char **namelist;
864  char **nameptr;
865 
866  /* Parse string into list of identifiers */
867  /* this shouldn't fail really */
868  if (SplitGUCList(pos, ',', &namelist))
869  {
870  for (nameptr = namelist; *nameptr; nameptr++)
871  {
872  if (nameptr != namelist)
873  appendPQExpBufferStr(buf, ", ");
874  appendStringLiteralConn(buf, *nameptr, conn);
875  }
876  }
877  pg_free(namelist);
878  }
879  else
881 
882  appendPQExpBufferStr(buf, ";\n");
883 
884  pg_free(mine);
885 }
Acl * acldefault(ObjectType objtype, Oid ownerId)
Definition: acl.c:743
bool buildACLCommands(const char *name, const char *subname, const char *nspname, const char *type, const char *acls, const char *baseacls, const char *owner, const char *prefix, int remoteVersion, PQExpBuffer sql)
Definition: dumputils.c:64
static char * dequoteAclUserName(PQExpBuffer output, char *input)
Definition: dumputils.c:578
void buildShSecLabelQuery(const char *catalog_name, Oid objectId, PQExpBuffer sql)
Definition: dumputils.c:637
void makeAlterConfigCommand(PGconn *conn, const char *configitem, const char *type, const char *name, const char *type2, const char *name2, PQExpBuffer buf)
Definition: dumputils.c:823
bool buildDefaultACLCommands(const char *type, const char *nspname, const char *acls, const char *acldefault, const char *owner, int remoteVersion, PQExpBuffer sql)
Definition: dumputils.c:327
bool variable_is_guc_list_quote(const char *name)
Definition: dumputils.c:689
void quoteAclUserName(PQExpBuffer output, const char *input)
Definition: dumputils.c:544
static bool parseAclItem(const char *item, const char *type, const char *name, const char *subname, int remoteVersion, PQExpBuffer grantee, PQExpBuffer grantor, PQExpBuffer privs, PQExpBuffer privswgo)
Definition: dumputils.c:384
static void AddAcl(PQExpBuffer aclbuf, const char *keyword, const char *subname)
Definition: dumputils.c:617
void emitShSecLabels(PGconn *conn, PGresult *res, PQExpBuffer buffer, const char *objtype, const char *objname)
Definition: dumputils.c:655
bool SplitGUCList(char *rawstring, char separator, char ***namelist)
Definition: dumputils.c:723
#define CONVERT_PRIV(code, keywd)
const char * name
Definition: encode.c:561
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3340
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3735
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void pg_free(void *ptr)
Definition: fe_memutils.c:105
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
#define free(a)
Definition: header.h:65
int j
Definition: isn.c:74
int i
Definition: isn.c:73
static JitProviderCallbacks provider
Definition: jit.c:43
static char * label
NameData subname
static char * buf
Definition: pg_test_fsync.c:67
static void output(uint64 loop_count)
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
unsigned int Oid
Definition: postgres_ext.h:31
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:116
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGconn * conn
Definition: streamutil.c:54
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
bool parsePGArray(const char *atext, char ***itemarray, int *nitems)
Definition: string_utils.c:657