Force a checkpoint in CREATE DATABASE before starting to copy the files,
[PostgreSQL.git] / src / bin / pg_dump / dumputils.c
blob9926caea42e1d913c248bd44cb7531365a15daf9
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-2008, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
17 #include <ctype.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, const char *name,
27 int remoteVersion, PQExpBuffer grantee, PQExpBuffer grantor,
28 PQExpBuffer privs, PQExpBuffer privswgo);
29 static char *copyAclUserName(PQExpBuffer output, char *input);
30 static void AddAcl(PQExpBuffer aclbuf, const char *keyword);
34 * Quotes input string if it's not a legitimate SQL identifier as-is.
36 * Note that the returned string must be used before calling fmtId again,
37 * since we re-use the same return buffer each time. Non-reentrant but
38 * avoids memory leakage.
40 const char *
41 fmtId(const char *rawid)
43 static PQExpBuffer id_return = NULL;
44 const char *cp;
45 bool need_quotes = false;
47 if (id_return) /* first time through? */
48 resetPQExpBuffer(id_return);
49 else
50 id_return = createPQExpBuffer();
53 * These checks need to match the identifier production in scan.l. Don't
54 * use islower() etc.
56 /* slightly different rules for first character */
57 if (!((rawid[0] >= 'a' && rawid[0] <= 'z') || rawid[0] == '_'))
58 need_quotes = true;
59 else
61 /* otherwise check the entire string */
62 for (cp = rawid; *cp; cp++)
64 if (!((*cp >= 'a' && *cp <= 'z')
65 || (*cp >= '0' && *cp <= '9')
66 || (*cp == '_')))
68 need_quotes = true;
69 break;
74 if (!need_quotes)
77 * Check for keyword. We quote keywords except for unreserved ones.
78 * (In some cases we could avoid quoting a col_name or type_func_name
79 * keyword, but it seems much harder than it's worth to tell that.)
81 * Note: ScanKeywordLookup() does case-insensitive comparison, but
82 * that's fine, since we already know we have all-lower-case.
84 const ScanKeyword *keyword = ScanKeywordLookup(rawid);
86 if (keyword != NULL && keyword->category != UNRESERVED_KEYWORD)
87 need_quotes = true;
90 if (!need_quotes)
92 /* no quoting needed */
93 appendPQExpBufferStr(id_return, rawid);
95 else
97 appendPQExpBufferChar(id_return, '\"');
98 for (cp = rawid; *cp; cp++)
101 * Did we find a double-quote in the string? Then make this a
102 * double double-quote per SQL99. Before, we put in a
103 * backslash/double-quote pair. - thomas 2000-08-05
105 if (*cp == '\"')
106 appendPQExpBufferChar(id_return, '\"');
107 appendPQExpBufferChar(id_return, *cp);
109 appendPQExpBufferChar(id_return, '\"');
112 return id_return->data;
117 * Convert a string value to an SQL string literal and append it to
118 * the given buffer. We assume the specified client_encoding and
119 * standard_conforming_strings settings.
121 * This is essentially equivalent to libpq's PQescapeStringInternal,
122 * except for the output buffer structure. We need it in situations
123 * where we do not have a PGconn available. Where we do,
124 * appendStringLiteralConn is a better choice.
126 void
127 appendStringLiteral(PQExpBuffer buf, const char *str,
128 int encoding, bool std_strings)
130 size_t length = strlen(str);
131 const char *source = str;
132 char *target;
134 if (!enlargePQExpBuffer(buf, 2 * length + 2))
135 return;
137 target = buf->data + buf->len;
138 *target++ = '\'';
140 while (*source != '\0')
142 char c = *source;
143 int len;
144 int i;
146 /* Fast path for plain ASCII */
147 if (!IS_HIGHBIT_SET(c))
149 /* Apply quoting if needed */
150 if (SQL_STR_DOUBLE(c, !std_strings))
151 *target++ = c;
152 /* Copy the character */
153 *target++ = c;
154 source++;
155 continue;
158 /* Slow path for possible multibyte characters */
159 len = PQmblen(source, encoding);
161 /* Copy the character */
162 for (i = 0; i < len; i++)
164 if (*source == '\0')
165 break;
166 *target++ = *source++;
170 * If we hit premature end of string (ie, incomplete multibyte
171 * character), try to pad out to the correct length with spaces. We
172 * may not be able to pad completely, but we will always be able to
173 * insert at least one pad space (since we'd not have quoted a
174 * multibyte character). This should be enough to make a string that
175 * the server will error out on.
177 if (i < len)
179 char *stop = buf->data + buf->maxlen - 2;
181 for (; i < len; i++)
183 if (target >= stop)
184 break;
185 *target++ = ' ';
187 break;
191 /* Write the terminating quote and NUL character. */
192 *target++ = '\'';
193 *target = '\0';
195 buf->len = target - buf->data;
200 * Convert a string value to an SQL string literal and append it to
201 * the given buffer. Encoding and string syntax rules are as indicated
202 * by current settings of the PGconn.
204 void
205 appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
207 size_t length = strlen(str);
210 * XXX This is a kluge to silence escape_string_warning in our utility
211 * programs. It should go away someday.
213 if (strchr(str, '\\') != NULL && PQserverVersion(conn) >= 80100)
215 /* ensure we are not adjacent to an identifier */
216 if (buf->len > 0 && buf->data[buf->len - 1] != ' ')
217 appendPQExpBufferChar(buf, ' ');
218 appendPQExpBufferChar(buf, ESCAPE_STRING_SYNTAX);
219 appendStringLiteral(buf, str, PQclientEncoding(conn), false);
220 return;
222 /* XXX end kluge */
224 if (!enlargePQExpBuffer(buf, 2 * length + 2))
225 return;
226 appendPQExpBufferChar(buf, '\'');
227 buf->len += PQescapeStringConn(conn, buf->data + buf->len,
228 str, length, NULL);
229 appendPQExpBufferChar(buf, '\'');
234 * Convert a string value to a dollar quoted literal and append it to
235 * the given buffer. If the dqprefix parameter is not NULL then the
236 * dollar quote delimiter will begin with that (after the opening $).
238 * No escaping is done at all on str, in compliance with the rules
239 * for parsing dollar quoted strings. Also, we need not worry about
240 * encoding issues.
242 void
243 appendStringLiteralDQ(PQExpBuffer buf, const char *str, const char *dqprefix)
245 static const char suffixes[] = "_XXXXXXX";
246 int nextchar = 0;
247 PQExpBuffer delimBuf = createPQExpBuffer();
249 /* start with $ + dqprefix if not NULL */
250 appendPQExpBufferChar(delimBuf, '$');
251 if (dqprefix)
252 appendPQExpBufferStr(delimBuf, dqprefix);
255 * Make sure we choose a delimiter which (without the trailing $) is not
256 * present in the string being quoted. We don't check with the trailing $
257 * because a string ending in $foo must not be quoted with $foo$.
259 while (strstr(str, delimBuf->data) != NULL)
261 appendPQExpBufferChar(delimBuf, suffixes[nextchar++]);
262 nextchar %= sizeof(suffixes) - 1;
265 /* add trailing $ */
266 appendPQExpBufferChar(delimBuf, '$');
268 /* quote it and we are all done */
269 appendPQExpBufferStr(buf, delimBuf->data);
270 appendPQExpBufferStr(buf, str);
271 appendPQExpBufferStr(buf, delimBuf->data);
273 destroyPQExpBuffer(delimBuf);
278 * Convert backend's version string into a number.
281 parse_version(const char *versionString)
283 int cnt;
284 int vmaj,
285 vmin,
286 vrev;
288 cnt = sscanf(versionString, "%d.%d.%d", &vmaj, &vmin, &vrev);
290 if (cnt < 2)
291 return -1;
293 if (cnt == 2)
294 vrev = 0;
296 return (100 * vmaj + vmin) * 100 + vrev;
301 * Deconstruct the text representation of a 1-dimensional Postgres array
302 * into individual items.
304 * On success, returns true and sets *itemarray and *nitems to describe
305 * an array of individual strings. On parse failure, returns false;
306 * *itemarray may exist or be NULL.
308 * NOTE: free'ing itemarray is sufficient to deallocate the working storage.
310 bool
311 parsePGArray(const char *atext, char ***itemarray, int *nitems)
313 int inputlen;
314 char **items;
315 char *strings;
316 int curitem;
319 * We expect input in the form of "{item,item,item}" where any item is
320 * either raw data, or surrounded by double quotes (in which case embedded
321 * characters including backslashes and quotes are backslashed).
323 * We build the result as an array of pointers followed by the actual
324 * string data, all in one malloc block for convenience of deallocation.
325 * The worst-case storage need is not more than one pointer and one
326 * character for each input character (consider "{,,,,,,,,,,}").
328 *itemarray = NULL;
329 *nitems = 0;
330 inputlen = strlen(atext);
331 if (inputlen < 2 || atext[0] != '{' || atext[inputlen - 1] != '}')
332 return false; /* bad input */
333 items = (char **) malloc(inputlen * (sizeof(char *) + sizeof(char)));
334 if (items == NULL)
335 return false; /* out of memory */
336 *itemarray = items;
337 strings = (char *) (items + inputlen);
339 atext++; /* advance over initial '{' */
340 curitem = 0;
341 while (*atext != '}')
343 if (*atext == '\0')
344 return false; /* premature end of string */
345 items[curitem] = strings;
346 while (*atext != '}' && *atext != ',')
348 if (*atext == '\0')
349 return false; /* premature end of string */
350 if (*atext != '"')
351 *strings++ = *atext++; /* copy unquoted data */
352 else
354 /* process quoted substring */
355 atext++;
356 while (*atext != '"')
358 if (*atext == '\0')
359 return false; /* premature end of string */
360 if (*atext == '\\')
362 atext++;
363 if (*atext == '\0')
364 return false; /* premature end of string */
366 *strings++ = *atext++; /* copy quoted data */
368 atext++;
371 *strings++ = '\0';
372 if (*atext == ',')
373 atext++;
374 curitem++;
376 if (atext[1] != '\0')
377 return false; /* bogus syntax (embedded '}') */
378 *nitems = curitem;
379 return true;
384 * Build GRANT/REVOKE command(s) for an object.
386 * name: the object name, in the form to use in the commands (already quoted)
387 * type: the object type (as seen in GRANT command: must be one of
388 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, or TABLESPACE)
389 * acls: the ACL string fetched from the database
390 * owner: username of object owner (will be passed through fmtId); can be
391 * NULL or empty string to indicate "no owner known"
392 * remoteVersion: version of database
394 * Returns TRUE if okay, FALSE if could not parse the acl string.
395 * The resulting commands (if any) are appended to the contents of 'sql'.
397 * Note: beware of passing fmtId() result as 'name', since this routine
398 * uses fmtId() internally.
400 bool
401 buildACLCommands(const char *name, const char *type,
402 const char *acls, const char *owner,
403 int remoteVersion,
404 PQExpBuffer sql)
406 char **aclitems;
407 int naclitems;
408 int i;
409 PQExpBuffer grantee,
410 grantor,
411 privs,
412 privswgo;
413 PQExpBuffer firstsql,
414 secondsql;
415 bool found_owner_privs = false;
417 if (strlen(acls) == 0)
418 return true; /* object has default permissions */
420 /* treat empty-string owner same as NULL */
421 if (owner && *owner == '\0')
422 owner = NULL;
424 if (!parsePGArray(acls, &aclitems, &naclitems))
426 if (aclitems)
427 free(aclitems);
428 return false;
431 grantee = createPQExpBuffer();
432 grantor = createPQExpBuffer();
433 privs = createPQExpBuffer();
434 privswgo = createPQExpBuffer();
437 * At the end, these two will be pasted together to form the result. But
438 * the owner privileges need to go before the other ones to keep the
439 * dependencies valid. In recent versions this is normally the case, but
440 * in old versions they come after the PUBLIC privileges and that results
441 * in problems if we need to run REVOKE on the owner privileges.
443 firstsql = createPQExpBuffer();
444 secondsql = createPQExpBuffer();
447 * Always start with REVOKE ALL FROM PUBLIC, so that we don't have to
448 * wire-in knowledge about the default public privileges for different
449 * kinds of objects.
451 appendPQExpBuffer(firstsql, "REVOKE ALL ON %s %s FROM PUBLIC;\n",
452 type, name);
455 * We still need some hacking though to cover the case where new default
456 * public privileges are added in new versions: the REVOKE ALL will revoke
457 * them, leading to behavior different from what the old version had,
458 * which is generally not what's wanted. So add back default privs if the
459 * source database is too old to have had that particular priv.
461 if (remoteVersion < 80200 && strcmp(type, "DATABASE") == 0)
463 /* database CONNECT priv didn't exist before 8.2 */
464 appendPQExpBuffer(firstsql, "GRANT CONNECT ON %s %s TO PUBLIC;\n",
465 type, name);
468 /* Scan individual ACL items */
469 for (i = 0; i < naclitems; i++)
471 if (!parseAclItem(aclitems[i], type, name, remoteVersion,
472 grantee, grantor, privs, privswgo))
473 return false;
475 if (grantor->len == 0 && owner)
476 printfPQExpBuffer(grantor, "%s", owner);
478 if (privs->len > 0 || privswgo->len > 0)
480 if (owner
481 && strcmp(grantee->data, owner) == 0
482 && strcmp(grantor->data, owner) == 0)
484 found_owner_privs = true;
487 * For the owner, the default privilege level is ALL WITH
488 * GRANT OPTION (only ALL prior to 7.4).
490 if (supports_grant_options(remoteVersion)
491 ? strcmp(privswgo->data, "ALL") != 0
492 : strcmp(privs->data, "ALL") != 0)
494 appendPQExpBuffer(firstsql, "REVOKE ALL ON %s %s FROM %s;\n",
495 type, name,
496 fmtId(grantee->data));
497 if (privs->len > 0)
498 appendPQExpBuffer(firstsql, "GRANT %s ON %s %s TO %s;\n",
499 privs->data, type, name,
500 fmtId(grantee->data));
501 if (privswgo->len > 0)
502 appendPQExpBuffer(firstsql, "GRANT %s ON %s %s TO %s WITH GRANT OPTION;\n",
503 privswgo->data, type, name,
504 fmtId(grantee->data));
507 else
510 * Otherwise can assume we are starting from no privs.
512 if (grantor->len > 0
513 && (!owner || strcmp(owner, grantor->data) != 0))
514 appendPQExpBuffer(secondsql, "SET SESSION AUTHORIZATION %s;\n",
515 fmtId(grantor->data));
517 if (privs->len > 0)
519 appendPQExpBuffer(secondsql, "GRANT %s ON %s %s TO ",
520 privs->data, type, name);
521 if (grantee->len == 0)
522 appendPQExpBuffer(secondsql, "PUBLIC;\n");
523 else if (strncmp(grantee->data, "group ",
524 strlen("group ")) == 0)
525 appendPQExpBuffer(secondsql, "GROUP %s;\n",
526 fmtId(grantee->data + strlen("group ")));
527 else
528 appendPQExpBuffer(secondsql, "%s;\n", fmtId(grantee->data));
530 if (privswgo->len > 0)
532 appendPQExpBuffer(secondsql, "GRANT %s ON %s %s TO ",
533 privswgo->data, type, name);
534 if (grantee->len == 0)
535 appendPQExpBuffer(secondsql, "PUBLIC");
536 else if (strncmp(grantee->data, "group ",
537 strlen("group ")) == 0)
538 appendPQExpBuffer(secondsql, "GROUP %s",
539 fmtId(grantee->data + strlen("group ")));
540 else
541 appendPQExpBuffer(secondsql, "%s", fmtId(grantee->data));
542 appendPQExpBuffer(secondsql, " WITH GRANT OPTION;\n");
545 if (grantor->len > 0
546 && (!owner || strcmp(owner, grantor->data) != 0))
547 appendPQExpBuffer(secondsql, "RESET SESSION AUTHORIZATION;\n");
553 * If we didn't find any owner privs, the owner must have revoked 'em all
555 if (!found_owner_privs && owner)
556 appendPQExpBuffer(firstsql, "REVOKE ALL ON %s %s FROM %s;\n",
557 type, name, fmtId(owner));
559 destroyPQExpBuffer(grantee);
560 destroyPQExpBuffer(grantor);
561 destroyPQExpBuffer(privs);
562 destroyPQExpBuffer(privswgo);
564 appendPQExpBuffer(sql, "%s%s", firstsql->data, secondsql->data);
565 destroyPQExpBuffer(firstsql);
566 destroyPQExpBuffer(secondsql);
568 free(aclitems);
570 return true;
574 * This will parse an aclitem string, having the general form
575 * username=privilegecodes/grantor
576 * or
577 * group groupname=privilegecodes/grantor
578 * (the /grantor part will not be present if pre-7.4 database).
580 * The returned grantee string will be the dequoted username or groupname
581 * (preceded with "group " in the latter case). The returned grantor is
582 * the dequoted grantor name or empty. Privilege characters are decoded
583 * and split between privileges with grant option (privswgo) and without
584 * (privs).
586 * Note: for cross-version compatibility, it's important to use ALL when
587 * appropriate.
589 static bool
590 parseAclItem(const char *item, const char *type, const char *name,
591 int remoteVersion, PQExpBuffer grantee, PQExpBuffer grantor,
592 PQExpBuffer privs, PQExpBuffer privswgo)
594 char *buf;
595 bool all_with_go = true;
596 bool all_without_go = true;
597 char *eqpos;
598 char *slpos;
599 char *pos;
601 buf = strdup(item);
602 if (!buf)
603 return false;
605 /* user or group name is string up to = */
606 eqpos = copyAclUserName(grantee, buf);
607 if (*eqpos != '=')
608 return false;
610 /* grantor may be listed after / */
611 slpos = strchr(eqpos + 1, '/');
612 if (slpos)
614 *slpos++ = '\0';
615 slpos = copyAclUserName(grantor, slpos);
616 if (*slpos != '\0')
617 return false;
619 else
620 resetPQExpBuffer(grantor);
622 /* privilege codes */
623 #define CONVERT_PRIV(code, keywd) \
624 do { \
625 if ((pos = strchr(eqpos + 1, code))) \
627 if (*(pos + 1) == '*') \
629 AddAcl(privswgo, keywd); \
630 all_without_go = false; \
632 else \
634 AddAcl(privs, keywd); \
635 all_with_go = false; \
638 else \
639 all_with_go = all_without_go = false; \
640 } while (0)
642 resetPQExpBuffer(privs);
643 resetPQExpBuffer(privswgo);
645 if (strcmp(type, "TABLE") == 0 || strcmp(type, "SEQUENCE") == 0)
647 CONVERT_PRIV('r', "SELECT");
649 if (strcmp(type, "SEQUENCE") == 0)
650 /* sequence only */
651 CONVERT_PRIV('U', "USAGE");
652 else
654 /* table only */
655 CONVERT_PRIV('a', "INSERT");
656 if (remoteVersion >= 70200)
658 CONVERT_PRIV('d', "DELETE");
659 CONVERT_PRIV('x', "REFERENCES");
660 CONVERT_PRIV('t', "TRIGGER");
662 if (remoteVersion >= 80400)
663 CONVERT_PRIV('D', "TRUNCATE");
666 /* UPDATE */
667 if (remoteVersion >= 70200 || strcmp(type, "SEQUENCE") == 0)
668 CONVERT_PRIV('w', "UPDATE");
669 else
670 /* 7.0 and 7.1 have a simpler worldview */
671 CONVERT_PRIV('w', "UPDATE,DELETE");
673 else if (strcmp(type, "FUNCTION") == 0)
674 CONVERT_PRIV('X', "EXECUTE");
675 else if (strcmp(type, "LANGUAGE") == 0)
676 CONVERT_PRIV('U', "USAGE");
677 else if (strcmp(type, "SCHEMA") == 0)
679 CONVERT_PRIV('C', "CREATE");
680 CONVERT_PRIV('U', "USAGE");
682 else if (strcmp(type, "DATABASE") == 0)
684 CONVERT_PRIV('C', "CREATE");
685 CONVERT_PRIV('c', "CONNECT");
686 CONVERT_PRIV('T', "TEMPORARY");
688 else if (strcmp(type, "TABLESPACE") == 0)
689 CONVERT_PRIV('C', "CREATE");
690 else
691 abort();
693 #undef CONVERT_PRIV
695 if (all_with_go)
697 resetPQExpBuffer(privs);
698 printfPQExpBuffer(privswgo, "ALL");
700 else if (all_without_go)
702 resetPQExpBuffer(privswgo);
703 printfPQExpBuffer(privs, "ALL");
706 free(buf);
708 return true;
712 * Transfer a user or group name starting at *input into the output buffer,
713 * dequoting if needed. Returns a pointer to just past the input name.
714 * The name is taken to end at an unquoted '=' or end of string.
716 static char *
717 copyAclUserName(PQExpBuffer output, char *input)
719 resetPQExpBuffer(output);
721 while (*input && *input != '=')
724 * If user name isn't quoted, then just add it to the output buffer
726 if (*input != '"')
727 appendPQExpBufferChar(output, *input++);
728 else
730 /* Otherwise, it's a quoted username */
731 input++;
732 /* Loop until we come across an unescaped quote */
733 while (!(*input == '"' && *(input + 1) != '"'))
735 if (*input == '\0')
736 return input; /* really a syntax error... */
739 * Quoting convention is to escape " as "". Keep this code in
740 * sync with putid() in backend's acl.c.
742 if (*input == '"' && *(input + 1) == '"')
743 input++;
744 appendPQExpBufferChar(output, *input++);
746 input++;
749 return input;
753 * Append a privilege keyword to a keyword list, inserting comma if needed.
755 static void
756 AddAcl(PQExpBuffer aclbuf, const char *keyword)
758 if (aclbuf->len > 0)
759 appendPQExpBufferChar(aclbuf, ',');
760 appendPQExpBuffer(aclbuf, "%s", keyword);
765 * processSQLNamePattern
767 * Scan a wildcard-pattern string and generate appropriate WHERE clauses
768 * to limit the set of objects returned. The WHERE clauses are appended
769 * to the already-partially-constructed query in buf.
771 * conn: connection query will be sent to (consulted for escaping rules).
772 * buf: output parameter.
773 * pattern: user-specified pattern option, or NULL if none ("*" is implied).
774 * have_where: true if caller already emitted "WHERE" (clauses will be ANDed
775 * onto the existing WHERE clause).
776 * force_escape: always quote regexp special characters, even outside
777 * double quotes (else they are quoted only between double quotes).
778 * schemavar: name of query variable to match against a schema-name pattern.
779 * Can be NULL if no schema.
780 * namevar: name of query variable to match against an object-name pattern.
781 * altnamevar: NULL, or name of an alternative variable to match against name.
782 * visibilityrule: clause to use if we want to restrict to visible objects
783 * (for example, "pg_catalog.pg_table_is_visible(p.oid)"). Can be NULL.
785 * Formatting note: the text already present in buf should end with a newline.
786 * The appended text, if any, will end with one too.
788 void
789 processSQLNamePattern(PGconn *conn, PQExpBuffer buf, const char *pattern,
790 bool have_where, bool force_escape,
791 const char *schemavar, const char *namevar,
792 const char *altnamevar, const char *visibilityrule)
794 PQExpBufferData schemabuf;
795 PQExpBufferData namebuf;
796 int encoding = PQclientEncoding(conn);
797 bool inquotes;
798 const char *cp;
799 int i;
801 #define WHEREAND() \
802 (appendPQExpBufferStr(buf, have_where ? " AND " : "WHERE "), have_where = true)
804 if (pattern == NULL)
806 /* Default: select all visible objects */
807 if (visibilityrule)
809 WHEREAND();
810 appendPQExpBuffer(buf, "%s\n", visibilityrule);
812 return;
815 initPQExpBuffer(&schemabuf);
816 initPQExpBuffer(&namebuf);
819 * Parse the pattern, converting quotes and lower-casing unquoted letters.
820 * Also, adjust shell-style wildcard characters into regexp notation.
822 * We surround the pattern with "^(...)$" to force it to match the whole
823 * string, as per SQL practice. We have to have parens in case the string
824 * contains "|", else the "^" and "$" will be bound into the first and
825 * last alternatives which is not what we want.
827 * Note: the result of this pass is the actual regexp pattern(s) we want
828 * to execute. Quoting/escaping into SQL literal format will be done
829 * below using appendStringLiteralConn().
831 appendPQExpBufferStr(&namebuf, "^(");
833 inquotes = false;
834 cp = pattern;
836 while (*cp)
838 char ch = *cp;
840 if (ch == '"')
842 if (inquotes && cp[1] == '"')
844 /* emit one quote, stay in inquotes mode */
845 appendPQExpBufferChar(&namebuf, '"');
846 cp++;
848 else
849 inquotes = !inquotes;
850 cp++;
852 else if (!inquotes && isupper((unsigned char) ch))
854 appendPQExpBufferChar(&namebuf,
855 pg_tolower((unsigned char) ch));
856 cp++;
858 else if (!inquotes && ch == '*')
860 appendPQExpBufferStr(&namebuf, ".*");
861 cp++;
863 else if (!inquotes && ch == '?')
865 appendPQExpBufferChar(&namebuf, '.');
866 cp++;
868 else if (!inquotes && ch == '.')
870 /* Found schema/name separator, move current pattern to schema */
871 resetPQExpBuffer(&schemabuf);
872 appendPQExpBufferStr(&schemabuf, namebuf.data);
873 resetPQExpBuffer(&namebuf);
874 appendPQExpBufferStr(&namebuf, "^(");
875 cp++;
877 else if (ch == '$')
880 * Dollar is always quoted, whether inside quotes or not. The
881 * reason is that it's allowed in SQL identifiers, so there's a
882 * significant use-case for treating it literally, while because
883 * we anchor the pattern automatically there is no use-case for
884 * having it possess its regexp meaning.
886 appendPQExpBufferStr(&namebuf, "\\$");
887 cp++;
889 else
892 * Ordinary data character, transfer to pattern
894 * Inside double quotes, or at all times if force_escape is true,
895 * quote regexp special characters with a backslash to avoid
896 * regexp errors. Outside quotes, however, let them pass through
897 * as-is; this lets knowledgeable users build regexp expressions
898 * that are more powerful than shell-style patterns.
900 if ((inquotes || force_escape) &&
901 strchr("|*+?()[]{}.^$\\", ch))
902 appendPQExpBufferChar(&namebuf, '\\');
903 i = PQmblen(cp, encoding);
904 while (i-- && *cp)
906 appendPQExpBufferChar(&namebuf, *cp);
907 cp++;
913 * Now decide what we need to emit. Note there will be a leading "^(" in
914 * the patterns in any case.
916 if (namebuf.len > 2)
918 /* We have a name pattern, so constrain the namevar(s) */
920 appendPQExpBufferStr(&namebuf, ")$");
921 /* Optimize away a "*" pattern */
922 if (strcmp(namebuf.data, "^(.*)$") != 0)
924 WHEREAND();
925 if (altnamevar)
927 appendPQExpBuffer(buf, "(%s ~ ", namevar);
928 appendStringLiteralConn(buf, namebuf.data, conn);
929 appendPQExpBuffer(buf, "\n OR %s ~ ", altnamevar);
930 appendStringLiteralConn(buf, namebuf.data, conn);
931 appendPQExpBufferStr(buf, ")\n");
933 else
935 appendPQExpBuffer(buf, "%s ~ ", namevar);
936 appendStringLiteralConn(buf, namebuf.data, conn);
937 appendPQExpBufferChar(buf, '\n');
942 if (schemabuf.len > 2)
944 /* We have a schema pattern, so constrain the schemavar */
946 appendPQExpBufferStr(&schemabuf, ")$");
947 /* Optimize away a "*" pattern */
948 if (strcmp(schemabuf.data, "^(.*)$") != 0 && schemavar)
950 WHEREAND();
951 appendPQExpBuffer(buf, "%s ~ ", schemavar);
952 appendStringLiteralConn(buf, schemabuf.data, conn);
953 appendPQExpBufferChar(buf, '\n');
956 else
958 /* No schema pattern given, so select only visible objects */
959 if (visibilityrule)
961 WHEREAND();
962 appendPQExpBuffer(buf, "%s\n", visibilityrule);
966 termPQExpBuffer(&schemabuf);
967 termPQExpBuffer(&namebuf);
969 #undef WHEREAND