1 /*-------------------------------------------------------------------------
3 * Utility routines for SQL dumping
4 * Basically this is stuff that is useful in both pg_dump and pg_dumpall.
5 * Lately it's also being used by psql and bin/scripts/ ...
8 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
19 #include "dumputils.h"
21 #include "parser/keywords.h"
24 #define supports_grant_options(version) ((version) >= 70400)
26 static bool parseAclItem(const char *item
, const char *type
,
27 const char *name
, const char *subname
, int remoteVersion
,
28 PQExpBuffer grantee
, PQExpBuffer grantor
,
29 PQExpBuffer privs
, PQExpBuffer privswgo
);
30 static char *copyAclUserName(PQExpBuffer output
, char *input
);
31 static void AddAcl(PQExpBuffer aclbuf
, const char *keyword
,
35 static bool parallel_init_done
= false;
36 static DWORD tls_index
;
40 init_parallel_dump_utils(void)
43 if (!parallel_init_done
)
45 tls_index
= TlsAlloc();
46 parallel_init_done
= true;
52 * Quotes input string if it's not a legitimate SQL identifier as-is.
54 * Note that the returned string must be used before calling fmtId again,
55 * since we re-use the same return buffer each time. Non-reentrant but
56 * reduces memory leakage. (On Windows the memory leakage will be one buffer
57 * per thread, which is at least better than one per call).
60 fmtId(const char *rawid
)
63 * The Tls code goes awry if we use a static var, so we provide for both
64 * static and auto, and omit any use of the static var when using Tls.
66 static PQExpBuffer s_id_return
= NULL
;
67 PQExpBuffer id_return
;
70 bool need_quotes
= false;
73 if (parallel_init_done
)
74 id_return
= (PQExpBuffer
) TlsGetValue(tls_index
); /* 0 when not set */
76 id_return
= s_id_return
;
78 id_return
= s_id_return
;
81 if (id_return
) /* first time through? */
83 /* same buffer, just wipe contents */
84 resetPQExpBuffer(id_return
);
89 id_return
= createPQExpBuffer();
91 if (parallel_init_done
)
92 TlsSetValue(tls_index
, id_return
);
94 s_id_return
= id_return
;
96 s_id_return
= id_return
;
102 * These checks need to match the identifier production in scan.l. Don't
105 /* slightly different rules for first character */
106 if (!((rawid
[0] >= 'a' && rawid
[0] <= 'z') || rawid
[0] == '_'))
110 /* otherwise check the entire string */
111 for (cp
= rawid
; *cp
; cp
++)
113 if (!((*cp
>= 'a' && *cp
<= 'z')
114 || (*cp
>= '0' && *cp
<= '9')
126 * Check for keyword. We quote keywords except for unreserved ones.
127 * (In some cases we could avoid quoting a col_name or type_func_name
128 * keyword, but it seems much harder than it's worth to tell that.)
130 * Note: ScanKeywordLookup() does case-insensitive comparison, but
131 * that's fine, since we already know we have all-lower-case.
133 const ScanKeyword
*keyword
= ScanKeywordLookup(rawid
);
135 if (keyword
!= NULL
&& keyword
->category
!= UNRESERVED_KEYWORD
)
141 /* no quoting needed */
142 appendPQExpBufferStr(id_return
, rawid
);
146 appendPQExpBufferChar(id_return
, '\"');
147 for (cp
= rawid
; *cp
; cp
++)
150 * Did we find a double-quote in the string? Then make this a
151 * double double-quote per SQL99. Before, we put in a
152 * backslash/double-quote pair. - thomas 2000-08-05
155 appendPQExpBufferChar(id_return
, '\"');
156 appendPQExpBufferChar(id_return
, *cp
);
158 appendPQExpBufferChar(id_return
, '\"');
161 return id_return
->data
;
166 * Convert a string value to an SQL string literal and append it to
167 * the given buffer. We assume the specified client_encoding and
168 * standard_conforming_strings settings.
170 * This is essentially equivalent to libpq's PQescapeStringInternal,
171 * except for the output buffer structure. We need it in situations
172 * where we do not have a PGconn available. Where we do,
173 * appendStringLiteralConn is a better choice.
176 appendStringLiteral(PQExpBuffer buf
, const char *str
,
177 int encoding
, bool std_strings
)
179 size_t length
= strlen(str
);
180 const char *source
= str
;
183 if (!enlargePQExpBuffer(buf
, 2 * length
+ 2))
186 target
= buf
->data
+ buf
->len
;
189 while (*source
!= '\0')
195 /* Fast path for plain ASCII */
196 if (!IS_HIGHBIT_SET(c
))
198 /* Apply quoting if needed */
199 if (SQL_STR_DOUBLE(c
, !std_strings
))
201 /* Copy the character */
207 /* Slow path for possible multibyte characters */
208 len
= PQmblen(source
, encoding
);
210 /* Copy the character */
211 for (i
= 0; i
< len
; i
++)
215 *target
++ = *source
++;
219 * If we hit premature end of string (ie, incomplete multibyte
220 * character), try to pad out to the correct length with spaces. We
221 * may not be able to pad completely, but we will always be able to
222 * insert at least one pad space (since we'd not have quoted a
223 * multibyte character). This should be enough to make a string that
224 * the server will error out on.
228 char *stop
= buf
->data
+ buf
->maxlen
- 2;
240 /* Write the terminating quote and NUL character. */
244 buf
->len
= target
- buf
->data
;
249 * Convert a string value to an SQL string literal and append it to
250 * the given buffer. Encoding and string syntax rules are as indicated
251 * by current settings of the PGconn.
254 appendStringLiteralConn(PQExpBuffer buf
, const char *str
, PGconn
*conn
)
256 size_t length
= strlen(str
);
259 * XXX This is a kluge to silence escape_string_warning in our utility
260 * programs. It should go away someday.
262 if (strchr(str
, '\\') != NULL
&& PQserverVersion(conn
) >= 80100)
264 /* ensure we are not adjacent to an identifier */
265 if (buf
->len
> 0 && buf
->data
[buf
->len
- 1] != ' ')
266 appendPQExpBufferChar(buf
, ' ');
267 appendPQExpBufferChar(buf
, ESCAPE_STRING_SYNTAX
);
268 appendStringLiteral(buf
, str
, PQclientEncoding(conn
), false);
273 if (!enlargePQExpBuffer(buf
, 2 * length
+ 2))
275 appendPQExpBufferChar(buf
, '\'');
276 buf
->len
+= PQescapeStringConn(conn
, buf
->data
+ buf
->len
,
278 appendPQExpBufferChar(buf
, '\'');
283 * Convert a string value to a dollar quoted literal and append it to
284 * the given buffer. If the dqprefix parameter is not NULL then the
285 * dollar quote delimiter will begin with that (after the opening $).
287 * No escaping is done at all on str, in compliance with the rules
288 * for parsing dollar quoted strings. Also, we need not worry about
292 appendStringLiteralDQ(PQExpBuffer buf
, const char *str
, const char *dqprefix
)
294 static const char suffixes
[] = "_XXXXXXX";
296 PQExpBuffer delimBuf
= createPQExpBuffer();
298 /* start with $ + dqprefix if not NULL */
299 appendPQExpBufferChar(delimBuf
, '$');
301 appendPQExpBufferStr(delimBuf
, dqprefix
);
304 * Make sure we choose a delimiter which (without the trailing $) is not
305 * present in the string being quoted. We don't check with the trailing $
306 * because a string ending in $foo must not be quoted with $foo$.
308 while (strstr(str
, delimBuf
->data
) != NULL
)
310 appendPQExpBufferChar(delimBuf
, suffixes
[nextchar
++]);
311 nextchar
%= sizeof(suffixes
) - 1;
315 appendPQExpBufferChar(delimBuf
, '$');
317 /* quote it and we are all done */
318 appendPQExpBufferStr(buf
, delimBuf
->data
);
319 appendPQExpBufferStr(buf
, str
);
320 appendPQExpBufferStr(buf
, delimBuf
->data
);
322 destroyPQExpBuffer(delimBuf
);
327 * Convert backend's version string into a number.
330 parse_version(const char *versionString
)
337 cnt
= sscanf(versionString
, "%d.%d.%d", &vmaj
, &vmin
, &vrev
);
345 return (100 * vmaj
+ vmin
) * 100 + vrev
;
350 * Deconstruct the text representation of a 1-dimensional Postgres array
351 * into individual items.
353 * On success, returns true and sets *itemarray and *nitems to describe
354 * an array of individual strings. On parse failure, returns false;
355 * *itemarray may exist or be NULL.
357 * NOTE: free'ing itemarray is sufficient to deallocate the working storage.
360 parsePGArray(const char *atext
, char ***itemarray
, int *nitems
)
368 * We expect input in the form of "{item,item,item}" where any item is
369 * either raw data, or surrounded by double quotes (in which case embedded
370 * characters including backslashes and quotes are backslashed).
372 * We build the result as an array of pointers followed by the actual
373 * string data, all in one malloc block for convenience of deallocation.
374 * The worst-case storage need is not more than one pointer and one
375 * character for each input character (consider "{,,,,,,,,,,}").
379 inputlen
= strlen(atext
);
380 if (inputlen
< 2 || atext
[0] != '{' || atext
[inputlen
- 1] != '}')
381 return false; /* bad input */
382 items
= (char **) malloc(inputlen
* (sizeof(char *) + sizeof(char)));
384 return false; /* out of memory */
386 strings
= (char *) (items
+ inputlen
);
388 atext
++; /* advance over initial '{' */
390 while (*atext
!= '}')
393 return false; /* premature end of string */
394 items
[curitem
] = strings
;
395 while (*atext
!= '}' && *atext
!= ',')
398 return false; /* premature end of string */
400 *strings
++ = *atext
++; /* copy unquoted data */
403 /* process quoted substring */
405 while (*atext
!= '"')
408 return false; /* premature end of string */
413 return false; /* premature end of string */
415 *strings
++ = *atext
++; /* copy quoted data */
425 if (atext
[1] != '\0')
426 return false; /* bogus syntax (embedded '}') */
433 * Build GRANT/REVOKE command(s) for an object.
435 * name: the object name, in the form to use in the commands (already quoted)
436 * subname: the sub-object name, if any (already quoted); NULL if none
437 * type: the object type (as seen in GRANT command: must be one of
438 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, or TABLESPACE)
439 * acls: the ACL string fetched from the database
440 * owner: username of object owner (will be passed through fmtId); can be
441 * NULL or empty string to indicate "no owner known"
442 * remoteVersion: version of database
444 * Returns TRUE if okay, FALSE if could not parse the acl string.
445 * The resulting commands (if any) are appended to the contents of 'sql'.
447 * Note: beware of passing a fmtId() result directly as 'name' or 'subname',
448 * since this routine uses fmtId() internally.
451 buildACLCommands(const char *name
, const char *subname
,
452 const char *type
, const char *acls
, const char *owner
,
463 PQExpBuffer firstsql
,
465 bool found_owner_privs
= false;
467 if (strlen(acls
) == 0)
468 return true; /* object has default permissions */
470 /* treat empty-string owner same as NULL */
471 if (owner
&& *owner
== '\0')
474 if (!parsePGArray(acls
, &aclitems
, &naclitems
))
481 grantee
= createPQExpBuffer();
482 grantor
= createPQExpBuffer();
483 privs
= createPQExpBuffer();
484 privswgo
= createPQExpBuffer();
487 * At the end, these two will be pasted together to form the result. But
488 * the owner privileges need to go before the other ones to keep the
489 * dependencies valid. In recent versions this is normally the case, but
490 * in old versions they come after the PUBLIC privileges and that results
491 * in problems if we need to run REVOKE on the owner privileges.
493 firstsql
= createPQExpBuffer();
494 secondsql
= createPQExpBuffer();
497 * Always start with REVOKE ALL FROM PUBLIC, so that we don't have to
498 * wire-in knowledge about the default public privileges for different
501 appendPQExpBuffer(firstsql
, "REVOKE ALL");
503 appendPQExpBuffer(firstsql
, "(%s)", subname
);
504 appendPQExpBuffer(firstsql
, " ON %s %s FROM PUBLIC;\n", type
, name
);
507 * We still need some hacking though to cover the case where new default
508 * public privileges are added in new versions: the REVOKE ALL will revoke
509 * them, leading to behavior different from what the old version had,
510 * which is generally not what's wanted. So add back default privs if the
511 * source database is too old to have had that particular priv.
513 if (remoteVersion
< 80200 && strcmp(type
, "DATABASE") == 0)
515 /* database CONNECT priv didn't exist before 8.2 */
516 appendPQExpBuffer(firstsql
, "GRANT CONNECT ON %s %s TO PUBLIC;\n",
520 /* Scan individual ACL items */
521 for (i
= 0; i
< naclitems
; i
++)
523 if (!parseAclItem(aclitems
[i
], type
, name
, subname
, remoteVersion
,
524 grantee
, grantor
, privs
, privswgo
))
527 if (grantor
->len
== 0 && owner
)
528 printfPQExpBuffer(grantor
, "%s", owner
);
530 if (privs
->len
> 0 || privswgo
->len
> 0)
533 && strcmp(grantee
->data
, owner
) == 0
534 && strcmp(grantor
->data
, owner
) == 0)
536 found_owner_privs
= true;
539 * For the owner, the default privilege level is ALL WITH
540 * GRANT OPTION (only ALL prior to 7.4).
542 if (supports_grant_options(remoteVersion
)
543 ? strcmp(privswgo
->data
, "ALL") != 0
544 : strcmp(privs
->data
, "ALL") != 0)
546 appendPQExpBuffer(firstsql
, "REVOKE ALL");
548 appendPQExpBuffer(firstsql
, "(%s)", subname
);
549 appendPQExpBuffer(firstsql
, " ON %s %s FROM %s;\n",
550 type
, name
, fmtId(grantee
->data
));
552 appendPQExpBuffer(firstsql
,
553 "GRANT %s ON %s %s TO %s;\n",
554 privs
->data
, type
, name
,
555 fmtId(grantee
->data
));
556 if (privswgo
->len
> 0)
557 appendPQExpBuffer(firstsql
,
558 "GRANT %s ON %s %s TO %s WITH GRANT OPTION;\n",
559 privswgo
->data
, type
, name
,
560 fmtId(grantee
->data
));
566 * Otherwise can assume we are starting from no privs.
569 && (!owner
|| strcmp(owner
, grantor
->data
) != 0))
570 appendPQExpBuffer(secondsql
, "SET SESSION AUTHORIZATION %s;\n",
571 fmtId(grantor
->data
));
575 appendPQExpBuffer(secondsql
, "GRANT %s ON %s %s TO ",
576 privs
->data
, type
, name
);
577 if (grantee
->len
== 0)
578 appendPQExpBuffer(secondsql
, "PUBLIC;\n");
579 else if (strncmp(grantee
->data
, "group ",
580 strlen("group ")) == 0)
581 appendPQExpBuffer(secondsql
, "GROUP %s;\n",
582 fmtId(grantee
->data
+ strlen("group ")));
584 appendPQExpBuffer(secondsql
, "%s;\n", fmtId(grantee
->data
));
586 if (privswgo
->len
> 0)
588 appendPQExpBuffer(secondsql
, "GRANT %s ON %s %s TO ",
589 privswgo
->data
, type
, name
);
590 if (grantee
->len
== 0)
591 appendPQExpBuffer(secondsql
, "PUBLIC");
592 else if (strncmp(grantee
->data
, "group ",
593 strlen("group ")) == 0)
594 appendPQExpBuffer(secondsql
, "GROUP %s",
595 fmtId(grantee
->data
+ strlen("group ")));
597 appendPQExpBuffer(secondsql
, "%s", fmtId(grantee
->data
));
598 appendPQExpBuffer(secondsql
, " WITH GRANT OPTION;\n");
602 && (!owner
|| strcmp(owner
, grantor
->data
) != 0))
603 appendPQExpBuffer(secondsql
, "RESET SESSION AUTHORIZATION;\n");
609 * If we didn't find any owner privs, the owner must have revoked 'em all
611 if (!found_owner_privs
&& owner
)
613 appendPQExpBuffer(firstsql
, "REVOKE ALL");
615 appendPQExpBuffer(firstsql
, "(%s)", subname
);
616 appendPQExpBuffer(firstsql
, " ON %s %s FROM %s;\n",
617 type
, name
, fmtId(owner
));
620 destroyPQExpBuffer(grantee
);
621 destroyPQExpBuffer(grantor
);
622 destroyPQExpBuffer(privs
);
623 destroyPQExpBuffer(privswgo
);
625 appendPQExpBuffer(sql
, "%s%s", firstsql
->data
, secondsql
->data
);
626 destroyPQExpBuffer(firstsql
);
627 destroyPQExpBuffer(secondsql
);
635 * This will parse an aclitem string, having the general form
636 * username=privilegecodes/grantor
638 * group groupname=privilegecodes/grantor
639 * (the /grantor part will not be present if pre-7.4 database).
641 * The returned grantee string will be the dequoted username or groupname
642 * (preceded with "group " in the latter case). The returned grantor is
643 * the dequoted grantor name or empty. Privilege characters are decoded
644 * and split between privileges with grant option (privswgo) and without
647 * Note: for cross-version compatibility, it's important to use ALL when
651 parseAclItem(const char *item
, const char *type
,
652 const char *name
, const char *subname
, int remoteVersion
,
653 PQExpBuffer grantee
, PQExpBuffer grantor
,
654 PQExpBuffer privs
, PQExpBuffer privswgo
)
657 bool all_with_go
= true;
658 bool all_without_go
= true;
667 /* user or group name is string up to = */
668 eqpos
= copyAclUserName(grantee
, buf
);
672 /* grantor may be listed after / */
673 slpos
= strchr(eqpos
+ 1, '/');
677 slpos
= copyAclUserName(grantor
, slpos
);
682 resetPQExpBuffer(grantor
);
684 /* privilege codes */
685 #define CONVERT_PRIV(code, keywd) \
687 if ((pos = strchr(eqpos + 1, code))) \
689 if (*(pos + 1) == '*') \
691 AddAcl(privswgo, keywd, subname); \
692 all_without_go = false; \
696 AddAcl(privs, keywd, subname); \
697 all_with_go = false; \
701 all_with_go = all_without_go = false; \
704 resetPQExpBuffer(privs
);
705 resetPQExpBuffer(privswgo
);
707 if (strcmp(type
, "TABLE") == 0 || strcmp(type
, "SEQUENCE") == 0)
709 CONVERT_PRIV('r', "SELECT");
711 if (strcmp(type
, "SEQUENCE") == 0)
713 CONVERT_PRIV('U', "USAGE");
717 CONVERT_PRIV('a', "INSERT");
718 if (remoteVersion
>= 70200)
719 CONVERT_PRIV('x', "REFERENCES");
720 /* rest are not applicable to columns */
723 if (remoteVersion
>= 70200)
725 CONVERT_PRIV('d', "DELETE");
726 CONVERT_PRIV('t', "TRIGGER");
728 if (remoteVersion
>= 80400)
729 CONVERT_PRIV('D', "TRUNCATE");
734 if (remoteVersion
>= 70200 || strcmp(type
, "SEQUENCE") == 0)
735 CONVERT_PRIV('w', "UPDATE");
737 /* 7.0 and 7.1 have a simpler worldview */
738 CONVERT_PRIV('w', "UPDATE,DELETE");
740 else if (strcmp(type
, "FUNCTION") == 0)
741 CONVERT_PRIV('X', "EXECUTE");
742 else if (strcmp(type
, "LANGUAGE") == 0)
743 CONVERT_PRIV('U', "USAGE");
744 else if (strcmp(type
, "SCHEMA") == 0)
746 CONVERT_PRIV('C', "CREATE");
747 CONVERT_PRIV('U', "USAGE");
749 else if (strcmp(type
, "DATABASE") == 0)
751 CONVERT_PRIV('C', "CREATE");
752 CONVERT_PRIV('c', "CONNECT");
753 CONVERT_PRIV('T', "TEMPORARY");
755 else if (strcmp(type
, "TABLESPACE") == 0)
756 CONVERT_PRIV('C', "CREATE");
757 else if (strcmp(type
, "FOREIGN DATA WRAPPER") == 0)
758 CONVERT_PRIV('U', "USAGE");
759 else if (strcmp(type
, "SERVER") == 0)
760 CONVERT_PRIV('U', "USAGE");
768 resetPQExpBuffer(privs
);
769 printfPQExpBuffer(privswgo
, "ALL");
771 appendPQExpBuffer(privswgo
, "(%s)", subname
);
773 else if (all_without_go
)
775 resetPQExpBuffer(privswgo
);
776 printfPQExpBuffer(privs
, "ALL");
778 appendPQExpBuffer(privs
, "(%s)", subname
);
787 * Transfer a user or group name starting at *input into the output buffer,
788 * dequoting if needed. Returns a pointer to just past the input name.
789 * The name is taken to end at an unquoted '=' or end of string.
792 copyAclUserName(PQExpBuffer output
, char *input
)
794 resetPQExpBuffer(output
);
796 while (*input
&& *input
!= '=')
799 * If user name isn't quoted, then just add it to the output buffer
802 appendPQExpBufferChar(output
, *input
++);
805 /* Otherwise, it's a quoted username */
807 /* Loop until we come across an unescaped quote */
808 while (!(*input
== '"' && *(input
+ 1) != '"'))
811 return input
; /* really a syntax error... */
814 * Quoting convention is to escape " as "". Keep this code in
815 * sync with putid() in backend's acl.c.
817 if (*input
== '"' && *(input
+ 1) == '"')
819 appendPQExpBufferChar(output
, *input
++);
828 * Append a privilege keyword to a keyword list, inserting comma if needed.
831 AddAcl(PQExpBuffer aclbuf
, const char *keyword
, const char *subname
)
834 appendPQExpBufferChar(aclbuf
, ',');
835 appendPQExpBuffer(aclbuf
, "%s", keyword
);
837 appendPQExpBuffer(aclbuf
, "(%s)", subname
);
842 * processSQLNamePattern
844 * Scan a wildcard-pattern string and generate appropriate WHERE clauses
845 * to limit the set of objects returned. The WHERE clauses are appended
846 * to the already-partially-constructed query in buf.
848 * conn: connection query will be sent to (consulted for escaping rules).
849 * buf: output parameter.
850 * pattern: user-specified pattern option, or NULL if none ("*" is implied).
851 * have_where: true if caller already emitted "WHERE" (clauses will be ANDed
852 * onto the existing WHERE clause).
853 * force_escape: always quote regexp special characters, even outside
854 * double quotes (else they are quoted only between double quotes).
855 * schemavar: name of query variable to match against a schema-name pattern.
856 * Can be NULL if no schema.
857 * namevar: name of query variable to match against an object-name pattern.
858 * altnamevar: NULL, or name of an alternative variable to match against name.
859 * visibilityrule: clause to use if we want to restrict to visible objects
860 * (for example, "pg_catalog.pg_table_is_visible(p.oid)"). Can be NULL.
862 * Formatting note: the text already present in buf should end with a newline.
863 * The appended text, if any, will end with one too.
866 processSQLNamePattern(PGconn
*conn
, PQExpBuffer buf
, const char *pattern
,
867 bool have_where
, bool force_escape
,
868 const char *schemavar
, const char *namevar
,
869 const char *altnamevar
, const char *visibilityrule
)
871 PQExpBufferData schemabuf
;
872 PQExpBufferData namebuf
;
873 int encoding
= PQclientEncoding(conn
);
879 (appendPQExpBufferStr(buf, have_where ? " AND " : "WHERE "), have_where = true)
883 /* Default: select all visible objects */
887 appendPQExpBuffer(buf
, "%s\n", visibilityrule
);
892 initPQExpBuffer(&schemabuf
);
893 initPQExpBuffer(&namebuf
);
896 * Parse the pattern, converting quotes and lower-casing unquoted letters.
897 * Also, adjust shell-style wildcard characters into regexp notation.
899 * We surround the pattern with "^(...)$" to force it to match the whole
900 * string, as per SQL practice. We have to have parens in case the string
901 * contains "|", else the "^" and "$" will be bound into the first and
902 * last alternatives which is not what we want.
904 * Note: the result of this pass is the actual regexp pattern(s) we want
905 * to execute. Quoting/escaping into SQL literal format will be done
906 * below using appendStringLiteralConn().
908 appendPQExpBufferStr(&namebuf
, "^(");
919 if (inquotes
&& cp
[1] == '"')
921 /* emit one quote, stay in inquotes mode */
922 appendPQExpBufferChar(&namebuf
, '"');
926 inquotes
= !inquotes
;
929 else if (!inquotes
&& isupper((unsigned char) ch
))
931 appendPQExpBufferChar(&namebuf
,
932 pg_tolower((unsigned char) ch
));
935 else if (!inquotes
&& ch
== '*')
937 appendPQExpBufferStr(&namebuf
, ".*");
940 else if (!inquotes
&& ch
== '?')
942 appendPQExpBufferChar(&namebuf
, '.');
945 else if (!inquotes
&& ch
== '.')
947 /* Found schema/name separator, move current pattern to schema */
948 resetPQExpBuffer(&schemabuf
);
949 appendPQExpBufferStr(&schemabuf
, namebuf
.data
);
950 resetPQExpBuffer(&namebuf
);
951 appendPQExpBufferStr(&namebuf
, "^(");
957 * Dollar is always quoted, whether inside quotes or not. The
958 * reason is that it's allowed in SQL identifiers, so there's a
959 * significant use-case for treating it literally, while because
960 * we anchor the pattern automatically there is no use-case for
961 * having it possess its regexp meaning.
963 appendPQExpBufferStr(&namebuf
, "\\$");
969 * Ordinary data character, transfer to pattern
971 * Inside double quotes, or at all times if force_escape is true,
972 * quote regexp special characters with a backslash to avoid
973 * regexp errors. Outside quotes, however, let them pass through
974 * as-is; this lets knowledgeable users build regexp expressions
975 * that are more powerful than shell-style patterns.
977 if ((inquotes
|| force_escape
) &&
978 strchr("|*+?()[]{}.^$\\", ch
))
979 appendPQExpBufferChar(&namebuf
, '\\');
980 i
= PQmblen(cp
, encoding
);
983 appendPQExpBufferChar(&namebuf
, *cp
);
990 * Now decide what we need to emit. Note there will be a leading "^(" in
991 * the patterns in any case.
995 /* We have a name pattern, so constrain the namevar(s) */
997 appendPQExpBufferStr(&namebuf
, ")$");
998 /* Optimize away a "*" pattern */
999 if (strcmp(namebuf
.data
, "^(.*)$") != 0)
1004 appendPQExpBuffer(buf
, "(%s ~ ", namevar
);
1005 appendStringLiteralConn(buf
, namebuf
.data
, conn
);
1006 appendPQExpBuffer(buf
, "\n OR %s ~ ", altnamevar
);
1007 appendStringLiteralConn(buf
, namebuf
.data
, conn
);
1008 appendPQExpBufferStr(buf
, ")\n");
1012 appendPQExpBuffer(buf
, "%s ~ ", namevar
);
1013 appendStringLiteralConn(buf
, namebuf
.data
, conn
);
1014 appendPQExpBufferChar(buf
, '\n');
1019 if (schemabuf
.len
> 2)
1021 /* We have a schema pattern, so constrain the schemavar */
1023 appendPQExpBufferStr(&schemabuf
, ")$");
1024 /* Optimize away a "*" pattern */
1025 if (strcmp(schemabuf
.data
, "^(.*)$") != 0 && schemavar
)
1028 appendPQExpBuffer(buf
, "%s ~ ", schemavar
);
1029 appendStringLiteralConn(buf
, schemabuf
.data
, conn
);
1030 appendPQExpBufferChar(buf
, '\n');
1035 /* No schema pattern given, so select only visible objects */
1039 appendPQExpBuffer(buf
, "%s\n", visibilityrule
);
1043 termPQExpBuffer(&schemabuf
);
1044 termPQExpBuffer(&namebuf
);