1/*-------------------------------------------------------------------------
3 * Utility routines for SQL dumping
5 * Basically this is stuff that is useful in both pg_dump and pg_dumpall.
8 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/bin/pg_dump/dumputils.c
13 *-------------------------------------------------------------------------
24 static const char restrict_chars[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
27 const char *
name,
const char *
subname,
int remoteVersion,
36 * Sanitize a string to be included in an SQL comment or TOC listing, by
37 * replacing any newlines with spaces. This ensures each logical output line
38 * is in fact one physical output line, to prevent corruption of the dump
39 * (which could, in the worst case, present an SQL injection vulnerability
40 * if someone were to incautiously load a dump containing objects with
41 * maliciously crafted names).
43 * The result is a freshly malloc'd string. If the input string is NULL,
44 * return a malloc'ed empty string, unless want_hyphen, in which case return a
47 * Note that we currently don't bother to quote names, meaning that the name
48 * fields aren't automatically parseable. "pg_restore -L" doesn't care because
49 * it only examines the dumpId field, but someday we might want to try harder.
62 for (s = result; *s !=
'0円'; s++)
64 if (*s ==
'\n' || *s ==
'\r')
73 * Build GRANT/REVOKE command(s) for an object.
75 * name: the object name, in the form to use in the commands (already quoted)
76 * subname: the sub-object name, if any (already quoted); NULL if none
77 * nspname: the namespace the object is in (NULL if none); not pre-quoted
78 * type: the object type (as seen in GRANT command: must be one of
79 * TABLE, SEQUENCE, FUNCTION, PROCEDURE, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
80 * FOREIGN DATA WRAPPER, SERVER, PARAMETER or LARGE OBJECT)
81 * acls: the ACL string fetched from the database
82 * baseacls: the initial ACL string for this object
83 * owner: username of object owner (will be passed through fmtId); can be
84 * NULL or empty string to indicate "no owner known"
85 * prefix: string to prefix to each generated command; typically empty
86 * remoteVersion: version of database
88 * Returns true if okay, false if could not parse the acl string.
89 * The resulting commands (if any) are appended to the contents of 'sql'.
91 * baseacls is typically the result of acldefault() for the object's type
92 * and owner. However, if there is a pg_init_privs entry for the object,
93 * it should instead be the initprivs ACLs. When acls is itself a
94 * pg_init_privs entry, baseacls is what to dump that relative to; then
95 * it can be either an acldefault() value or an empty ACL "{}".
97 * Note: when processing a default ACL, prefix is "ALTER DEFAULT PRIVILEGES "
98 * or something similar, and name is an empty string.
100 * Note: beware of passing a fmtId() result directly as 'name' or 'subname',
101 * since this routine uses fmtId() internally.
105 const char *
type,
const char *acls,
const char *baseacls,
106 const char *owner,
const char *prefix,
int remoteVersion,
110 char **aclitems = NULL;
111 char **baseitems = NULL;
112 char **grantitems = NULL;
113 char **revokeitems = NULL;
117 int nrevokeitems = 0;
127 * If the acl was NULL (initial default state), we need do nothing. Note
128 * that this is distinguishable from all-privileges-revoked, which will
129 * look like an empty array ("{}").
131 if (acls == NULL || *acls ==
'0円')
132 return true;
/* object has default permissions */
134 /* treat empty-string owner same as NULL */
135 if (owner && *owner ==
'0円')
138 /* Parse the acls array */
145 /* Parse the baseacls too */
154 * Compare the actual ACL with the base ACL, extracting the privileges
155 * that need to be granted (i.e., are in the actual ACL but not the base
156 * ACL) and the ones that need to be revoked (the reverse). We use plain
157 * string comparisons to check for matches. In principle that could be
158 * fooled by extraneous issues such as whitespace, but since all these
159 * strings are the work of aclitemout(), it should be OK in practice.
160 * Besides, a false mismatch will just cause the output to be a little
161 * more verbose than it really needed to be.
163 grantitems = (
char **)
pg_malloc(naclitems *
sizeof(
char *));
164 for (
i = 0;
i < naclitems;
i++)
168 for (
int j = 0;
j < nbaseitems;
j++)
170 if (strcmp(aclitems[
i], baseitems[
j]) == 0)
177 grantitems[ngrantitems++] = aclitems[
i];
179 revokeitems = (
char **)
pg_malloc(nbaseitems *
sizeof(
char *));
180 for (
i = 0;
i < nbaseitems;
i++)
184 for (
int j = 0;
j < naclitems;
j++)
186 if (strcmp(baseitems[
i], aclitems[
j]) == 0)
193 revokeitems[nrevokeitems++] = baseitems[
i];
196 /* Prepare working buffers */
203 * At the end, these two will be pasted together to form the result.
209 * Build REVOKE statements for ACLs listed in revokeitems[].
211 for (
i = 0;
i < nrevokeitems;
i++)
215 grantee, grantor, privs, NULL))
225 if (nspname && *nspname)
230 if (grantee->
len == 0)
239 * At this point we have issued REVOKE statements for all initial and
240 * default privileges that are no longer present on the object, so we are
241 * almost ready to GRANT the privileges listed in grantitems[].
243 * We still need some hacking though to cover the case where new default
244 * public privileges are added in new versions: the REVOKE ALL will revoke
245 * them, leading to behavior different from what the old version had,
246 * which is generally not what's wanted. So add back default privs if the
247 * source database is too old to have had that particular priv. (As of
248 * right now, no such cases exist in supported versions.)
252 * Scan individual ACL items to be granted.
254 * The order in which privileges appear in the ACL string (the order they
255 * have been GRANT'd in, which the backend maintains) must be preserved to
256 * ensure that GRANTs WITH GRANT OPTION and subsequent GRANTs based on
257 * those are dumped in the correct order. However, some old server
258 * versions will show grants to PUBLIC before the owner's own grants; for
259 * consistency's sake, force the owner's grants to be output first.
261 for (
i = 0;
i < ngrantitems;
i++)
264 grantee, grantor, privs, privswgo))
267 * If the grantor isn't the owner, we'll need to use SET SESSION
268 * AUTHORIZATION to become the grantor. Issue the SET/RESET only
269 * if there's something useful to do.
271 if (privs->
len > 0 || privswgo->
len > 0)
275 /* Set owner as grantor if that's not explicit in the ACL */
276 if (grantor->
len == 0 && owner)
279 /* Make sure owner's own grants are output before others */
281 strcmp(grantee->
data, owner) == 0 &&
282 strcmp(grantor->
data, owner) == 0)
288 && (!owner || strcmp(owner, grantor->
data) != 0))
296 if (nspname && *nspname)
301 if (grantee->
len == 0)
306 if (privswgo->
len > 0)
310 if (nspname && *nspname)
315 if (grantee->
len == 0)
323 && (!owner || strcmp(owner, grantor->
data) != 0))
329 /* parseAclItem failed, give up */
353 * Build ALTER DEFAULT PRIVILEGES command(s) for a single pg_default_acl entry.
355 * type: the object type (TABLES, FUNCTIONS, etc)
356 * nspname: schema name, or NULL for global default privileges
357 * acls: the ACL string fetched from the database
358 * acldefault: the appropriate default ACL for the object type and owner
359 * owner: username of privileges owner (will be passed through fmtId)
360 * remoteVersion: version of database
362 * Returns true if okay, false if could not parse the acl string.
363 * The resulting commands (if any) are appended to the contents of 'sql'.
377 * We incorporate the target role directly into the command, rather than
378 * playing around with SET ROLE or anything like that. This is so that a
379 * permissions error leads to nothing happening, rather than changing
380 * default privileges for the wrong user.
388 * There's no such thing as initprivs for a default ACL, so the base ACL
389 * is always just the object-type-specific default.
393 prefix->
data, remoteVersion, sql))
405 * This will parse an aclitem string, having the general form
406 * username=privilegecodes/grantor
408 * Returns true on success, false on parse error. On success, the components
409 * of the string are returned in the PQExpBuffer parameters.
411 * The returned grantee string will be the dequoted username, or an empty
412 * string in the case of a grant to PUBLIC. The returned grantor is the
413 * dequoted grantor name. Privilege characters are translated to GRANT/REVOKE
414 * comma-separated privileges lists. If "privswgo" is non-NULL, the result is
415 * separate lists for privileges with grant option ("privswgo") and without
416 * ("privs"). Otherwise, "privs" bears every relevant privilege, ignoring the
417 * grant option distinction.
419 * Note: for cross-version compatibility, it's important to use ALL to
420 * represent the privilege sets whenever appropriate.
424 const char *
name,
const char *
subname,
int remoteVersion,
429 bool all_with_go =
true;
430 bool all_without_go =
true;
437 /* user or group name is string up to = */
445 /* grantor should appear after / */
446 slpos = strchr(eqpos + 1,
'/');
463 /* privilege codes */
464#define CONVERT_PRIV(code, keywd) \
466 if ((pos = strchr(eqpos + 1, code))) \
468 if (*(pos + 1) == '*' && privswgo != NULL) \
470 AddAcl(privswgo, keywd, subname); \
471 all_without_go = false; \
475 AddAcl(privs, keywd, subname); \
476 all_with_go = false; \
480 all_with_go = all_without_go = false; \
486 if (strcmp(
type,
"TABLE") == 0 || strcmp(
type,
"SEQUENCE") == 0 ||
487 strcmp(
type,
"TABLES") == 0 || strcmp(
type,
"SEQUENCES") == 0)
491 if (strcmp(
type,
"SEQUENCE") == 0 ||
492 strcmp(
type,
"SEQUENCES") == 0)
500 /* rest are not applicable to columns */
513 else if (strcmp(
type,
"FUNCTION") == 0 ||
514 strcmp(
type,
"FUNCTIONS") == 0)
516 else if (strcmp(
type,
"PROCEDURE") == 0 ||
517 strcmp(
type,
"PROCEDURES") == 0)
519 else if (strcmp(
type,
"LANGUAGE") == 0)
521 else if (strcmp(
type,
"SCHEMA") == 0 ||
522 strcmp(
type,
"SCHEMAS") == 0)
527 else if (strcmp(
type,
"DATABASE") == 0)
533 else if (strcmp(
type,
"TABLESPACE") == 0)
535 else if (strcmp(
type,
"TYPE") == 0 ||
536 strcmp(
type,
"TYPES") == 0)
538 else if (strcmp(
type,
"FOREIGN DATA WRAPPER") == 0)
540 else if (strcmp(
type,
"FOREIGN SERVER") == 0)
542 else if (strcmp(
type,
"FOREIGN TABLE") == 0)
544 else if (strcmp(
type,
"PARAMETER") == 0)
549 else if (strcmp(
type,
"LARGE OBJECT") == 0 ||
550 strcmp(
type,
"LARGE OBJECTS") == 0)
567 else if (all_without_go)
581 * Transfer the role name at *input into the output buffer, adding
582 * quoting according to the same rules as putid() in backend's acl.c.
590 for (src =
input; *src; src++)
592 /* This test had better match what putid() does */
593 if (!isalnum((
unsigned char) *src) && *src !=
'_')
601 for (src =
input; *src; src++)
603 /* A double quote character in a username is encoded as "" */
613 * Transfer a user or group name starting at *input into the output buffer,
614 * dequoting if needed. Returns a pointer to just past the input name.
615 * The name is taken to end at an unquoted '=' or end of string.
616 * Note: unlike quoteAclUserName(), this first clears the output buffer.
626 * If user name isn't quoted, then just add it to the output buffer
632 /* Otherwise, it's a quoted username */
634 /* Loop until we come across an unescaped quote */
635 while (!(*
input ==
'"' && *(
input + 1) !=
'"'))
638 return input;
/* really a syntax error... */
641 * Quoting convention is to escape " as "". Keep this code in
642 * sync with putid() in backend's acl.c.
655 * Append a privilege keyword to a keyword list, inserting comma if needed.
669 * buildShSecLabelQuery
671 * Build a query to retrieve security labels for a shared object.
672 * The object is identified by its OID plus the name of the catalog
673 * it can be found in (e.g., "pg_database" for database names).
674 * The query is appended to "sql". (We don't execute it here so as to
675 * keep this file free of assumptions about how to deal with SQL errors.)
682 "SELECT provider, label FROM pg_catalog.pg_shseclabel "
683 "WHERE classoid = 'pg_catalog.%s'::pg_catalog.regclass "
684 "AND objoid = '%u'", catalog_name, objectId);
690 * Construct SECURITY LABEL commands using the data retrieved by the query
691 * generated by buildShSecLabelQuery, and append them to "buffer".
692 * Here, the target object is identified by its type name (e.g. "DATABASE")
693 * and its name (not pre-quoted).
697 const char *objtype,
const char *objname)
706 /* must use fmtId result before calling it again */
708 "SECURITY LABEL FOR %s ON %s",
720 * Detect whether the given GUC variable is of GUC_LIST_QUOTE type.
722 * It'd be better if we could inquire this directly from the backend; but even
723 * if there were a function for that, it could only tell us about variables
724 * currently known to guc.c, so that it'd be unsafe for extensions to declare
725 * GUC_LIST_QUOTE variables anyway. Lacking a solution for that, it doesn't
726 * seem worth the work to do more than have this list, which must be kept in
727 * sync with the variables actually marked GUC_LIST_QUOTE in guc_parameters.dat.
744 * SplitGUCList --- parse a string containing identifiers or file names
746 * This is used to split the value of a GUC_LIST_QUOTE GUC variable, without
747 * presuming whether the elements will be taken as identifiers or file names.
748 * See comparable code in src/backend/utils/adt/varlena.c.
751 * rawstring: the input string; must be overwritable! On return, it's
752 * been modified to contain the separated identifiers.
753 * separator: the separator punctuation expected between identifiers
754 * (typically '.' or ','). Whitespace may also appear around
757 * namelist: receives a malloc'd, null-terminated array of pointers to
758 * identifiers within rawstring. Caller should free this
759 * even on error return.
761 * Returns true if okay, false if there is a syntax error in the string.
767 char *nextp = rawstring;
772 * Since we disallow empty identifiers, this is a conservative
773 * overestimate of the number of pointers we could need. Allow one for
776 *namelist = nextptr = (
char **)
777 pg_malloc((strlen(rawstring) / 2 + 2) *
sizeof(
char *));
780 while (isspace((
unsigned char) *nextp))
781 nextp++;
/* skip leading whitespace */
784 return true;
/* allow empty string */
786 /* At the top of the loop, we are at start of a new identifier. */
794 /* Quoted name --- collapse quote-quote pairs */
798 endp = strchr(nextp + 1,
'"');
800 return false;
/* mismatched quotes */
802 break;
/* found end of quoted name */
803 /* Collapse adjacent quotes into one quote, and look again */
804 memmove(endp, endp + 1, strlen(endp));
807 /* endp now points at the terminating quote */
812 /* Unquoted name --- extends to separator or whitespace */
815 !isspace((
unsigned char) *nextp))
818 if (curname == nextp)
819 return false;
/* empty unquoted name not allowed */
822 while (isspace((
unsigned char) *nextp))
823 nextp++;
/* skip trailing whitespace */
828 while (isspace((
unsigned char) *nextp))
829 nextp++;
/* skip leading whitespace for next */
830 /* we expect another name, so done remains false */
832 else if (*nextp ==
'0円')
835 return false;
/* invalid syntax */
837 /* Now safe to overwrite separator with a null */
841 * Finished isolating current name --- add it to output array
843 *nextptr++ = curname;
845 /* Loop back if we didn't reach end of string */
853 * Helper function for dumping "ALTER DATABASE/ROLE SET ..." commands.
855 * Parse the contents of configitem (a "name=value" string), wrap it in
856 * a complete ALTER command, and append it to buf.
858 * type is DATABASE or ROLE, and name is the name of the database or role.
859 * If we need an "IN" clause, type2 and name2 similarly define what to put
860 * there; otherwise they should be NULL.
861 * conn is used only to determine string-literal quoting conventions.
866 const char *type2,
const char *name2,
872 /* Parse the configitem. If we can't find an "=", silently do nothing. */
874 pos = strchr(mine,
'=');
882 /* Build the command, with suitable quoting for everything. */
884 if (type2 != NULL && name2 != NULL)
889 * Variables that are marked GUC_LIST_QUOTE were already fully quoted by
890 * flatten_set_variable_args() before they were put into the setconfig
891 * array. However, because the quoting rules used there aren't exactly
892 * like SQL's, we have to break the list value apart and then quote the
893 * elements as string literals. (The elements may be double-quoted as-is,
894 * but we can't just feed them to the SQL parser; it would do the wrong
895 * thing with elements that are zero-length or longer than NAMEDATALEN.)
897 * Variables that are not so marked should just be emitted as simple
898 * string literals. If the variable is not known to
899 * variable_is_guc_list_quote(), we'll do that; this makes it unsafe to
900 * use GUC_LIST_QUOTE for extension variables.
907 /* Parse string into list of identifiers */
908 /* this shouldn't fail really */
911 for (nameptr = namelist; *nameptr; nameptr++)
913 if (nameptr != namelist)
931 * This will create a new directory with the given dirname. If there is
932 * already an empty directory with that name, then use it.
942 /* opendir failed but not with ENOENT */
943 pg_fatal(
"could not open directory \"%s\": %m", dirname);
946 /* directory does not exist */
948 pg_fatal(
"could not create directory \"%s\": %m", dirname);
951 /* exists and is empty, fix perms */
953 pg_fatal(
"could not change permissions of directory \"%s\": %m",
957 /* exists and is not empty */
958 pg_fatal(
"directory \"%s\" is not empty", dirname);
963 * Generates a valid restrict key (i.e., an alphanumeric string) for use with
964 * psql's \restrict and \unrestrict meta-commands. For safety, the value is
976 for (
int i = 0;
i <
sizeof(
buf) - 1;
i++)
982 ret[
sizeof(
buf) - 1] =
'0円';
988 * Checks that a given restrict key (intended for use with psql's \restrict and
989 * \unrestrict meta-commands) contains only alphanumeric characters.
Datum idx(PG_FUNCTION_ARGS)
Acl * acldefault(ObjectType objtype, Oid ownerId)
char * generate_restrict_key(void)
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)
static char * dequoteAclUserName(PQExpBuffer output, char *input)
bool valid_restrict_key(const char *restrict_key)
void buildShSecLabelQuery(const char *catalog_name, Oid objectId, PQExpBuffer sql)
void makeAlterConfigCommand(PGconn *conn, const char *configitem, const char *type, const char *name, const char *type2, const char *name2, PQExpBuffer buf)
bool buildDefaultACLCommands(const char *type, const char *nspname, const char *acls, const char *acldefault, const char *owner, int remoteVersion, PQExpBuffer sql)
char * sanitize_line(const char *str, bool want_hyphen)
void create_or_open_dir(const char *dirname)
bool variable_is_guc_list_quote(const char *name)
void quoteAclUserName(PQExpBuffer output, const char *input)
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)
static void AddAcl(PQExpBuffer aclbuf, const char *keyword, const char *subname)
void emitShSecLabels(PGconn *conn, PGresult *res, PQExpBuffer buffer, const char *objtype, const char *objname)
static const char restrict_chars[]
bool SplitGUCList(char *rawstring, char separator, char ***namelist)
#define CONVERT_PRIV(code, keywd)
void * pg_malloc(size_t size)
char * pg_strdup(const char *in)
static char * restrict_key
bool pg_strong_random(void *buf, size_t len)
int pg_strcasecmp(const char *s1, const char *s2)
int pg_check_dir(const char *dir)
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
PQExpBuffer createPQExpBuffer(void)
void resetPQExpBuffer(PQExpBuffer str)
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
void destroyPQExpBuffer(PQExpBuffer str)
void appendPQExpBufferChar(PQExpBuffer str, char ch)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
const char * fmtId(const char *rawid)
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
bool parsePGArray(const char *atext, char ***itemarray, int *nitems)