PostgreSQL Source Code  git master
string_utils.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include "common/keywords.h"
#include "fe_utils/string_utils.h"
Include dependency graph for string_utils.c:

Go to the source code of this file.

Macros

#define WHEREAND()
 

Functions

static PQExpBuffer defaultGetLocalPQExpBuffer (void)
 
const char * fmtId (const char *rawid)
 
const char * fmtQualifiedId (const char *schema, const char *id)
 
char * formatPGVersionNumber (int version_number, bool include_minor, char *buf, size_t buflen)
 
void appendStringLiteral (PQExpBuffer buf, const char *str, int encoding, bool std_strings)
 
void appendStringLiteralConn (PQExpBuffer buf, const char *str, PGconn *conn)
 
void appendStringLiteralDQ (PQExpBuffer buf, const char *str, const char *dqprefix)
 
void appendByteaLiteral (PQExpBuffer buf, const unsigned char *str, size_t length, bool std_strings)
 
void appendShellString (PQExpBuffer buf, const char *str)
 
bool appendShellStringNoError (PQExpBuffer buf, const char *str)
 
void appendConnStrVal (PQExpBuffer buf, const char *str)
 
void appendPsqlMetaConnect (PQExpBuffer buf, const char *dbname)
 
bool parsePGArray (const char *atext, char ***itemarray, int *nitems)
 
void appendPGArray (PQExpBuffer buffer, const char *value)
 
bool appendReloptionsArray (PQExpBuffer buffer, const char *reloptions, const char *prefix, int encoding, bool std_strings)
 
bool processSQLNamePattern (PGconn *conn, PQExpBuffer buf, const char *pattern, bool have_where, bool force_escape, const char *schemavar, const char *namevar, const char *altnamevar, const char *visibilityrule, PQExpBuffer dbnamebuf, int *dotcnt)
 
void patternToSQLRegex (int encoding, PQExpBuffer dbnamebuf, PQExpBuffer schemabuf, PQExpBuffer namebuf, const char *pattern, bool force_escape, bool want_literal_dbname, int *dotcnt)
 

Variables

int quote_all_identifiers = 0
 
PQExpBuffer(* getLocalPQExpBuffer )(void)
 

Macro Definition Documentation

◆ WHEREAND

#define WHEREAND ( )
Value:
(appendPQExpBufferStr(buf, have_where ? " AND " : "WHERE "), \
have_where = true, added_clause = true)
static char * buf
Definition: pg_test_fsync.c:67
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369

Function Documentation

◆ appendByteaLiteral()

void appendByteaLiteral ( PQExpBuffer  buf,
const unsigned char *  str,
size_t  length,
bool  std_strings 
)

Definition at line 374 of file string_utils.c.

376 {
377  const unsigned char *source = str;
378  char *target;
379 
380  static const char hextbl[] = "0123456789abcdef";
381 
382  /*
383  * This implementation is hard-wired to produce hex-format output. We do
384  * not know the server version the output will be loaded into, so making
385  * an intelligent format choice is impossible. It might be better to
386  * always use the old escaped format.
387  */
388  if (!enlargePQExpBuffer(buf, 2 * length + 5))
389  return;
390 
391  target = buf->data + buf->len;
392  *target++ = '\'';
393  if (!std_strings)
394  *target++ = '\\';
395  *target++ = '\\';
396  *target++ = 'x';
397 
398  while (length-- > 0)
399  {
400  unsigned char c = *source++;
401 
402  *target++ = hextbl[(c >> 4) & 0xF];
403  *target++ = hextbl[c & 0xF];
404  }
405 
406  /* Write the terminating quote and NUL character. */
407  *target++ = '\'';
408  *target = '\0';
409 
410  buf->len = target - buf->data;
411 }
static rewind_source * source
Definition: pg_rewind.c:81
static const char hextbl[]
Definition: pgp-info.c:87
int enlargePQExpBuffer(PQExpBuffer str, size_t needed)
Definition: pqexpbuffer.c:174
char * c

References buf, enlargePQExpBuffer(), hextbl, source, and generate_unaccent_rules::str.

◆ appendConnStrVal()

void appendConnStrVal ( PQExpBuffer  buf,
const char *  str 
)

Definition at line 545 of file string_utils.c.

546 {
547  const char *s;
548  bool needquotes;
549 
550  /*
551  * If the string is one or more plain ASCII characters, no need to quote
552  * it. This is quite conservative, but better safe than sorry.
553  */
554  needquotes = true;
555  for (s = str; *s; s++)
556  {
557  if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') ||
558  (*s >= '0' && *s <= '9') || *s == '_' || *s == '.'))
559  {
560  needquotes = true;
561  break;
562  }
563  needquotes = false;
564  }
565 
566  if (needquotes)
567  {
568  appendPQExpBufferChar(buf, '\'');
569  while (*str)
570  {
571  /* ' and \ must be escaped by to \' and \\ */
572  if (*str == '\'' || *str == '\\')
573  appendPQExpBufferChar(buf, '\\');
574 
576  str++;
577  }
578  appendPQExpBufferChar(buf, '\'');
579  }
580  else
582 }
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380

References appendPQExpBufferChar(), appendPQExpBufferStr(), buf, and generate_unaccent_rules::str.

Referenced by appendPsqlMetaConnect(), constructConnStr(), generate_old_dump(), GenerateRecoveryConfig(), get_db_conn(), and runPgDump().

◆ appendPGArray()

void appendPGArray ( PQExpBuffer  buffer,
const char *  value 
)

Definition at line 740 of file string_utils.c.

741 {
742  bool needquote;
743  const char *tmp;
744 
745  if (buffer->data[buffer->len - 1] != '{')
746  appendPQExpBufferChar(buffer, ',');
747 
748  /* Decide if we need quotes; this should match array_out()'s choices. */
749  if (value[0] == '\0')
750  needquote = true; /* force quotes for empty string */
751  else if (pg_strcasecmp(value, "NULL") == 0)
752  needquote = true; /* force quotes for literal NULL */
753  else
754  needquote = false;
755 
756  if (!needquote)
757  {
758  for (tmp = value; *tmp; tmp++)
759  {
760  char ch = *tmp;
761 
762  if (ch == '"' || ch == '\\' ||
763  ch == '{' || ch == '}' || ch == ',' ||
764  /* these match array_isspace(): */
765  ch == ' ' || ch == '\t' || ch == '\n' ||
766  ch == '\r' || ch == '\v' || ch == '\f')
767  {
768  needquote = true;
769  break;
770  }
771  }
772  }
773 
774  if (needquote)
775  {
776  appendPQExpBufferChar(buffer, '"');
777  for (tmp = value; *tmp; tmp++)
778  {
779  char ch = *tmp;
780 
781  if (ch == '"' || ch == '\\')
782  appendPQExpBufferChar(buffer, '\\');
783  appendPQExpBufferChar(buffer, ch);
784  }
785  appendPQExpBufferChar(buffer, '"');
786  }
787  else
788  appendPQExpBufferStr(buffer, value);
789 }
static struct @151 value
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36

References appendPQExpBufferChar(), appendPQExpBufferStr(), PQExpBufferData::data, PQExpBufferData::len, pg_strcasecmp(), and value.

Referenced by getNamespaces().

◆ appendPsqlMetaConnect()

void appendPsqlMetaConnect ( PQExpBuffer  buf,
const char *  dbname 
)

Definition at line 590 of file string_utils.c.

591 {
592  const char *s;
593  bool complex;
594 
595  /*
596  * If the name is plain ASCII characters, emit a trivial "\connect "foo"".
597  * For other names, even many not technically requiring it, skip to the
598  * general case. No database has a zero-length name.
599  */
600  complex = false;
601 
602  for (s = dbname; *s; s++)
603  {
604  if (*s == '\n' || *s == '\r')
605  {
606  fprintf(stderr,
607  _("database name contains a newline or carriage return: \"%s\"\n"),
608  dbname);
610  }
611 
612  if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') ||
613  (*s >= '0' && *s <= '9') || *s == '_' || *s == '.'))
614  {
615  complex = true;
616  }
617  }
618 
619  appendPQExpBufferStr(buf, "\\connect ");
620  if (complex)
621  {
623 
625  appendPQExpBufferStr(&connstr, "dbname=");
627 
628  appendPQExpBufferStr(buf, "-reuse-previous=on ");
629 
630  /*
631  * As long as the name does not contain a newline, SQL identifier
632  * quoting satisfies the psql meta-command parser. Prefer not to
633  * involve psql-interpreted single quotes, which behaved differently
634  * before PostgreSQL 9.2.
635  */
637 
639  }
640  else
642  appendPQExpBufferChar(buf, '\n');
643 }
#define _(x)
Definition: elog.c:89
exit(1)
static char * connstr
Definition: pg_dumpall.c:63
#define fprintf
Definition: port.h:229
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define EXIT_FAILURE
Definition: settings.h:163
char * dbname
Definition: streamutil.c:51
const char * fmtId(const char *rawid)
Definition: string_utils.c:64
void appendConnStrVal(PQExpBuffer buf, const char *str)
Definition: string_utils.c:545

References _, appendConnStrVal(), appendPQExpBufferChar(), appendPQExpBufferStr(), buf, connstr, dbname, exit(), EXIT_FAILURE, fmtId(), fprintf, initPQExpBuffer(), and termPQExpBuffer().

Referenced by _reconnectToDB(), old_9_6_invalidate_hash_indexes(), and report_extension_updates().

◆ appendReloptionsArray()

bool appendReloptionsArray ( PQExpBuffer  buffer,
const char *  reloptions,
const char *  prefix,
int  encoding,
bool  std_strings 
)

Definition at line 804 of file string_utils.c.

806 {
807  char **options;
808  int noptions;
809  int i;
810 
811  if (!parsePGArray(reloptions, &options, &noptions))
812  {
813  if (options)
814  free(options);
815  return false;
816  }
817 
818  for (i = 0; i < noptions; i++)
819  {
820  char *option = options[i];
821  char *name;
822  char *separator;
823  char *value;
824 
825  /*
826  * Each array element should have the form name=value. If the "=" is
827  * missing for some reason, treat it like an empty value.
828  */
829  name = option;
830  separator = strchr(option, '=');
831  if (separator)
832  {
833  *separator = '\0';
834  value = separator + 1;
835  }
836  else
837  value = "";
838 
839  if (i > 0)
840  appendPQExpBufferStr(buffer, ", ");
841  appendPQExpBuffer(buffer, "%s%s=", prefix, fmtId(name));
842 
843  /*
844  * In general we need to quote the value; but to avoid unnecessary
845  * clutter, do not quote if it is an identifier that would not need
846  * quoting. (We could also allow numbers, but that is a bit trickier
847  * than it looks --- for example, are leading zeroes significant? We
848  * don't want to assume very much here about what custom reloptions
849  * might mean.)
850  */
851  if (strcmp(fmtId(value), value) == 0)
852  appendPQExpBufferStr(buffer, value);
853  else
854  appendStringLiteral(buffer, value, encoding, std_strings);
855  }
856 
857  if (options)
858  free(options);
859 
860  return true;
861 }
const char * name
Definition: encode.c:561
#define free(a)
Definition: header.h:65
int i
Definition: isn.c:73
int32 encoding
Definition: pg_database.h:41
static size_t noptions
static char ** options
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
bool parsePGArray(const char *atext, char ***itemarray, int *nitems)
Definition: string_utils.c:657
void appendStringLiteral(PQExpBuffer buf, const char *str, int encoding, bool std_strings)
Definition: string_utils.c:215

References appendPQExpBuffer(), appendPQExpBufferStr(), appendStringLiteral(), encoding, fmtId(), free, i, name, noptions, options, parsePGArray(), and value.

Referenced by appendReloptionsArrayAH(), and get_create_object_cmd().

◆ appendShellString()

void appendShellString ( PQExpBuffer  buf,
const char *  str 
)

Definition at line 429 of file string_utils.c.

430 {
432  {
433  fprintf(stderr,
434  _("shell command argument contains a newline or carriage return: \"%s\"\n"),
435  str);
437  }
438 }
bool appendShellStringNoError(PQExpBuffer buf, const char *str)
Definition: string_utils.c:441

References _, appendShellStringNoError(), buf, exit(), EXIT_FAILURE, fprintf, and generate_unaccent_rules::str.

Referenced by cluster_conn_opts(), ensureCleanShutdown(), generate_old_dump(), getRestoreCommand(), main(), output_completion_banner(), and runPgDump().

◆ appendShellStringNoError()

bool appendShellStringNoError ( PQExpBuffer  buf,
const char *  str 
)

Definition at line 441 of file string_utils.c.

442 {
443 #ifdef WIN32
444  int backslash_run_length = 0;
445 #endif
446  bool ok = true;
447  const char *p;
448 
449  /*
450  * Don't bother with adding quotes if the string is nonempty and clearly
451  * contains only safe characters.
452  */
453  if (*str != '\0' &&
454  strspn(str, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_./:") == strlen(str))
455  {
457  return ok;
458  }
459 
460 #ifndef WIN32
461  appendPQExpBufferChar(buf, '\'');
462  for (p = str; *p; p++)
463  {
464  if (*p == '\n' || *p == '\r')
465  {
466  ok = false;
467  continue;
468  }
469 
470  if (*p == '\'')
471  appendPQExpBufferStr(buf, "'\"'\"'");
472  else
474  }
475  appendPQExpBufferChar(buf, '\'');
476 #else /* WIN32 */
477 
478  /*
479  * A Windows system() argument experiences two layers of interpretation.
480  * First, cmd.exe interprets the string. Its behavior is undocumented,
481  * but a caret escapes any byte except LF or CR that would otherwise have
482  * special meaning. Handling of a caret before LF or CR differs between
483  * "cmd.exe /c" and other modes, and it is unusable here.
484  *
485  * Second, the new process parses its command line to construct argv (see
486  * https://msdn.microsoft.com/en-us/library/17w5ykft.aspx). This treats
487  * backslash-double quote sequences specially.
488  */
489  appendPQExpBufferStr(buf, "^\"");
490  for (p = str; *p; p++)
491  {
492  if (*p == '\n' || *p == '\r')
493  {
494  ok = false;
495  continue;
496  }
497 
498  /* Change N backslashes before a double quote to 2N+1 backslashes. */
499  if (*p == '"')
500  {
501  while (backslash_run_length)
502  {
503  appendPQExpBufferStr(buf, "^\\");
504  backslash_run_length--;
505  }
506  appendPQExpBufferStr(buf, "^\\");
507  }
508  else if (*p == '\\')
509  backslash_run_length++;
510  else
511  backslash_run_length = 0;
512 
513  /*
514  * Decline to caret-escape the most mundane characters, to ease
515  * debugging and lest we approach the command length limit.
516  */
517  if (!((*p >= 'a' && *p <= 'z') ||
518  (*p >= 'A' && *p <= 'Z') ||
519  (*p >= '0' && *p <= '9')))
522  }
523 
524  /*
525  * Change N backslashes at end of argument to 2N backslashes, because they
526  * precede the double quote that terminates the argument.
527  */
528  while (backslash_run_length)
529  {
530  appendPQExpBufferStr(buf, "^\\");
531  backslash_run_length--;
532  }
533  appendPQExpBufferStr(buf, "^\"");
534 #endif /* WIN32 */
535 
536  return ok;
537 }

References appendPQExpBufferChar(), appendPQExpBufferStr(), buf, and generate_unaccent_rules::str.

Referenced by appendShellString(), and psql_get_variable().

◆ appendStringLiteral()

void appendStringLiteral ( PQExpBuffer  buf,
const char *  str,
int  encoding,
bool  std_strings 
)

Definition at line 215 of file string_utils.c.

217 {
218  size_t length = strlen(str);
219  const char *source = str;
220  char *target;
221 
222  if (!enlargePQExpBuffer(buf, 2 * length + 2))
223  return;
224 
225  target = buf->data + buf->len;
226  *target++ = '\'';
227 
228  while (*source != '\0')
229  {
230  char c = *source;
231  int len;
232  int i;
233 
234  /* Fast path for plain ASCII */
235  if (!IS_HIGHBIT_SET(c))
236  {
237  /* Apply quoting if needed */
238  if (SQL_STR_DOUBLE(c, !std_strings))
239  *target++ = c;
240  /* Copy the character */
241  *target++ = c;
242  source++;
243  continue;
244  }
245 
246  /* Slow path for possible multibyte characters */
248 
249  /* Copy the character */
250  for (i = 0; i < len; i++)
251  {
252  if (*source == '\0')
253  break;
254  *target++ = *source++;
255  }
256 
257  /*
258  * If we hit premature end of string (ie, incomplete multibyte
259  * character), try to pad out to the correct length with spaces. We
260  * may not be able to pad completely, but we will always be able to
261  * insert at least one pad space (since we'd not have quoted a
262  * multibyte character). This should be enough to make a string that
263  * the server will error out on.
264  */
265  if (i < len)
266  {
267  char *stop = buf->data + buf->maxlen - 2;
268 
269  for (; i < len; i++)
270  {
271  if (target >= stop)
272  break;
273  *target++ = ' ';
274  }
275  break;
276  }
277  }
278 
279  /* Write the terminating quote and NUL character. */
280  *target++ = '\'';
281  *target = '\0';
282 
283  buf->len = target - buf->data;
284 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1153
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1161
int PQmblen(const char *s, int encoding)
Definition: fe-misc.c:1185
const void size_t len

References buf, encoding, enlargePQExpBuffer(), i, IS_HIGHBIT_SET, len, PQmblen(), source, SQL_STR_DOUBLE, and generate_unaccent_rules::str.

Referenced by appendReloptionsArray(), and appendStringLiteralConn().

◆ appendStringLiteralConn()

void appendStringLiteralConn ( PQExpBuffer  buf,
const char *  str,
PGconn conn 
)

Definition at line 293 of file string_utils.c.

294 {
295  size_t length = strlen(str);
296 
297  /*
298  * XXX This is a kluge to silence escape_string_warning in our utility
299  * programs. It should go away someday.
300  */
301  if (strchr(str, '\\') != NULL && PQserverVersion(conn) >= 80100)
302  {
303  /* ensure we are not adjacent to an identifier */
304  if (buf->len > 0 && buf->data[buf->len - 1] != ' ')
308  return;
309  }
310  /* XXX end kluge */
311 
312  if (!enlargePQExpBuffer(buf, 2 * length + 2))
313  return;
314  appendPQExpBufferChar(buf, '\'');
315  buf->len += PQescapeStringConn(conn, buf->data + buf->len,
316  str, length, NULL);
317  appendPQExpBufferChar(buf, '\'');
318 }
#define ESCAPE_STRING_SYNTAX
Definition: c.h:1164
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6898
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6985
size_t PQescapeStringConn(PGconn *conn, char *to, const char *from, size_t length, int *error)
Definition: fe-exec.c:4005
PGconn * conn
Definition: streamutil.c:54

References appendPQExpBufferChar(), appendStringLiteral(), buf, conn, enlargePQExpBuffer(), ESCAPE_STRING_SYNTAX, PQclientEncoding(), PQescapeStringConn(), PQserverVersion(), and generate_unaccent_rules::str.

Referenced by append_db_pattern_cte(), append_rel_pattern_filtered_cte(), append_rel_pattern_raw_cte(), appendQualifiedRelation(), dumpRoles(), dumpTablespaces(), dumpUserConfig(), emitShSecLabels(), exec_command_password(), get_parallel_object_list(), getTables(), lookup_object_oid(), main(), makeAlterConfigCommand(), processSQLNamePattern(), setup_connection(), and vacuum_one_database().

◆ appendStringLiteralDQ()

void appendStringLiteralDQ ( PQExpBuffer  buf,
const char *  str,
const char *  dqprefix 
)

Definition at line 331 of file string_utils.c.

332 {
333  static const char suffixes[] = "_XXXXXXX";
334  int nextchar = 0;
335  PQExpBuffer delimBuf = createPQExpBuffer();
336 
337  /* start with $ + dqprefix if not NULL */
338  appendPQExpBufferChar(delimBuf, '$');
339  if (dqprefix)
340  appendPQExpBufferStr(delimBuf, dqprefix);
341 
342  /*
343  * Make sure we choose a delimiter which (without the trailing $) is not
344  * present in the string being quoted. We don't check with the trailing $
345  * because a string ending in $foo must not be quoted with $foo$.
346  */
347  while (strstr(str, delimBuf->data) != NULL)
348  {
349  appendPQExpBufferChar(delimBuf, suffixes[nextchar++]);
350  nextchar %= sizeof(suffixes) - 1;
351  }
352 
353  /* add trailing $ */
354  appendPQExpBufferChar(delimBuf, '$');
355 
356  /* quote it and we are all done */
357  appendPQExpBufferStr(buf, delimBuf->data);
359  appendPQExpBufferStr(buf, delimBuf->data);
360 
361  destroyPQExpBuffer(delimBuf);
362 }
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:116

References appendPQExpBufferChar(), appendPQExpBufferStr(), buf, createPQExpBuffer(), PQExpBufferData::data, destroyPQExpBuffer(), and generate_unaccent_rules::str.

Referenced by dumpFunc().

◆ defaultGetLocalPQExpBuffer()

static PQExpBuffer defaultGetLocalPQExpBuffer ( void  )
static

◆ fmtId()

const char* fmtId ( const char *  rawid)

Definition at line 64 of file string_utils.c.

65 {
66  PQExpBuffer id_return = getLocalPQExpBuffer();
67 
68  const char *cp;
69  bool need_quotes = false;
70 
71  /*
72  * These checks need to match the identifier production in scan.l. Don't
73  * use islower() etc.
74  */
76  need_quotes = true;
77  /* slightly different rules for first character */
78  else if (!((rawid[0] >= 'a' && rawid[0] <= 'z') || rawid[0] == '_'))
79  need_quotes = true;
80  else
81  {
82  /* otherwise check the entire string */
83  for (cp = rawid; *cp; cp++)
84  {
85  if (!((*cp >= 'a' && *cp <= 'z')
86  || (*cp >= '0' && *cp <= '9')
87  || (*cp == '_')))
88  {
89  need_quotes = true;
90  break;
91  }
92  }
93  }
94 
95  if (!need_quotes)
96  {
97  /*
98  * Check for keyword. We quote keywords except for unreserved ones.
99  * (In some cases we could avoid quoting a col_name or type_func_name
100  * keyword, but it seems much harder than it's worth to tell that.)
101  *
102  * Note: ScanKeywordLookup() does case-insensitive comparison, but
103  * that's fine, since we already know we have all-lower-case.
104  */
105  int kwnum = ScanKeywordLookup(rawid, &ScanKeywords);
106 
107  if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
108  need_quotes = true;
109  }
110 
111  if (!need_quotes)
112  {
113  /* no quoting needed */
114  appendPQExpBufferStr(id_return, rawid);
115  }
116  else
117  {
118  appendPQExpBufferChar(id_return, '"');
119  for (cp = rawid; *cp; cp++)
120  {
121  /*
122  * Did we find a double-quote in the string? Then make this a
123  * double double-quote per SQL99. Before, we put in a
124  * backslash/double-quote pair. - thomas 2000-08-05
125  */
126  if (*cp == '"')
127  appendPQExpBufferChar(id_return, '"');
128  appendPQExpBufferChar(id_return, *cp);
129  }
130  appendPQExpBufferChar(id_return, '"');
131  }
132 
133  return id_return->data;
134 }
const uint8 ScanKeywordCategories[SCANKEYWORDS_NUM_KEYWORDS]
Definition: keywords.c:29
PGDLLIMPORT const ScanKeywordList ScanKeywords
#define UNRESERVED_KEYWORD
Definition: keywords.h:20
int ScanKeywordLookup(const char *str, const ScanKeywordList *keywords)
Definition: kwlookup.c:38
PQExpBuffer(* getLocalPQExpBuffer)(void)
Definition: string_utils.c:27
int quote_all_identifiers
Definition: string_utils.c:26

References appendPQExpBufferChar(), appendPQExpBufferStr(), PQExpBufferData::data, getLocalPQExpBuffer, quote_all_identifiers, ScanKeywordCategories, ScanKeywordLookup(), ScanKeywords, and UNRESERVED_KEYWORD.

Referenced by _doSetFixedOutputState(), _getObjectDescription(), _printTocEntry(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), append_depends_on_extension(), appendPsqlMetaConnect(), appendReloptionsArray(), binary_upgrade_extension_member(), buildACLCommands(), buildDefaultACLCommands(), createDummyViewAsClause(), describeOneTableDetails(), dropDBs(), dropRoles(), dropTablespaces(), dumpAccessMethod(), dumpAgg(), dumpAttrDef(), dumpBaseType(), dumpCast(), dumpCollation(), dumpCommentExtended(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpIndex(), dumpNamespace(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpPolicy(), dumpProcLang(), dumpPublication(), dumpPublicationNamespace(), dumpPublicationTable(), dumpRangeType(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSecLabel(), dumpSequence(), dumpStatisticsExt(), dumpSubscription(), dumpTable(), dumpTableComment(), dumpTableConstraintComment(), dumpTableData_insert(), dumpTableSchema(), dumpTableSecLabel(), dumpTablespaces(), dumpTransform(), dumpTrigger(), dumpTSConfig(), dumpTSDictionary(), dumpTSParser(), dumpTSTemplate(), dumpUndefinedType(), dumpUserMappings(), emitShSecLabels(), exec_command_password(), fmtCopyColumnList(), fmtQualifiedId(), format_aggregate_signature(), format_function_arguments(), format_function_signature(), get_create_object_cmd(), get_language_name(), getFormattedOperatorName(), getPublicationTables(), main(), makeAlterConfigCommand(), run_reindex_command(), and setup_connection().

◆ fmtQualifiedId()

const char* fmtQualifiedId ( const char *  schema,
const char *  id 
)

Definition at line 145 of file string_utils.c.

146 {
147  PQExpBuffer id_return;
148  PQExpBuffer lcl_pqexp = createPQExpBuffer();
149 
150  /* Some callers might fail to provide a schema name */
151  if (schema && *schema)
152  {
153  appendPQExpBuffer(lcl_pqexp, "%s.", fmtId(schema));
154  }
155  appendPQExpBufferStr(lcl_pqexp, fmtId(id));
156 
157  id_return = getLocalPQExpBuffer();
158 
159  appendPQExpBufferStr(id_return, lcl_pqexp->data);
160  destroyPQExpBuffer(lcl_pqexp);
161 
162  return id_return->data;
163 }

References appendPQExpBuffer(), appendPQExpBufferStr(), createPQExpBuffer(), PQExpBufferData::data, destroyPQExpBuffer(), fmtId(), and getLocalPQExpBuffer.

Referenced by _disableTriggersIfNecessary(), _enableTriggersIfNecessary(), appendQualifiedRelation(), get_parallel_object_list(), lockTableForWorker(), restore_toc_entry(), and vacuum_one_database().

◆ formatPGVersionNumber()

char* formatPGVersionNumber ( int  version_number,
bool  include_minor,
char *  buf,
size_t  buflen 
)

Definition at line 177 of file string_utils.c.

179 {
180  if (version_number >= 100000)
181  {
182  /* New two-part style */
183  if (include_minor)
184  snprintf(buf, buflen, "%d.%d", version_number / 10000,
185  version_number % 10000);
186  else
187  snprintf(buf, buflen, "%d", version_number / 10000);
188  }
189  else
190  {
191  /* Old three-part style */
192  if (include_minor)
193  snprintf(buf, buflen, "%d.%d.%d", version_number / 10000,
194  (version_number / 100) % 100,
195  version_number % 100);
196  else
197  snprintf(buf, buflen, "%d.%d", version_number / 10000,
198  (version_number / 100) % 100);
199  }
200  return buf;
201 }
#define snprintf
Definition: port.h:225

References buf, and snprintf.

Referenced by connection_warnings(), describeAccessMethods(), describeFunctions(), describePublications(), describeSubscriptions(), listEventTriggers(), listExtendedStats(), listPartitionedTables(), listPublications(), printVersion(), and SyncVariables().

◆ parsePGArray()

bool parsePGArray ( const char *  atext,
char ***  itemarray,
int *  nitems 
)

Definition at line 657 of file string_utils.c.

658 {
659  int inputlen;
660  char **items;
661  char *strings;
662  int curitem;
663 
664  /*
665  * We expect input in the form of "{item,item,item}" where any item is
666  * either raw data, or surrounded by double quotes (in which case embedded
667  * characters including backslashes and quotes are backslashed).
668  *
669  * We build the result as an array of pointers followed by the actual
670  * string data, all in one malloc block for convenience of deallocation.
671  * The worst-case storage need is not more than one pointer and one
672  * character for each input character (consider "{,,,,,,,,,,}").
673  */
674  *itemarray = NULL;
675  *nitems = 0;
676  inputlen = strlen(atext);
677  if (inputlen < 2 || atext[0] != '{' || atext[inputlen - 1] != '}')
678  return false; /* bad input */
679  items = (char **) malloc(inputlen * (sizeof(char *) + sizeof(char)));
680  if (items == NULL)
681  return false; /* out of memory */
682  *itemarray = items;
683  strings = (char *) (items + inputlen);
684 
685  atext++; /* advance over initial '{' */
686  curitem = 0;
687  while (*atext != '}')
688  {
689  if (*atext == '\0')
690  return false; /* premature end of string */
691  items[curitem] = strings;
692  while (*atext != '}' && *atext != ',')
693  {
694  if (*atext == '\0')
695  return false; /* premature end of string */
696  if (*atext != '"')
697  *strings++ = *atext++; /* copy unquoted data */
698  else
699  {
700  /* process quoted substring */
701  atext++;
702  while (*atext != '"')
703  {
704  if (*atext == '\0')
705  return false; /* premature end of string */
706  if (*atext == '\\')
707  {
708  atext++;
709  if (*atext == '\0')
710  return false; /* premature end of string */
711  }
712  *strings++ = *atext++; /* copy quoted data */
713  }
714  atext++;
715  }
716  }
717  *strings++ = '\0';
718  if (*atext == ',')
719  atext++;
720  curitem++;
721  }
722  if (atext[1] != '\0')
723  return false; /* bogus syntax (embedded '}') */
724  *nitems = curitem;
725  return true;
726 }
#define malloc(a)
Definition: header.h:50

References malloc.

Referenced by appendReloptionsArray(), buildACLCommands(), dumpFunc(), dumpIndex(), dumpSearchPath(), dumpSubscription(), getPublicationTables(), and processExtensionTables().

◆ patternToSQLRegex()

void patternToSQLRegex ( int  encoding,
PQExpBuffer  dbnamebuf,
PQExpBuffer  schemabuf,
PQExpBuffer  namebuf,
const char *  pattern,
bool  force_escape,
bool  want_literal_dbname,
int *  dotcnt 
)

Definition at line 1065 of file string_utils.c.

1068 {
1069  PQExpBufferData buf[3];
1070  PQExpBufferData left_literal;
1071  PQExpBuffer curbuf;
1072  PQExpBuffer maxbuf;
1073  int i;
1074  bool inquotes;
1075  bool left;
1076  const char *cp;
1077 
1078  Assert(pattern != NULL);
1079  Assert(namebuf != NULL);
1080 
1081  /* callers should never expect "dbname.relname" format */
1082  Assert(dbnamebuf == NULL || schemabuf != NULL);
1083  Assert(dotcnt != NULL);
1084 
1085  *dotcnt = 0;
1086  inquotes = false;
1087  cp = pattern;
1088 
1089  if (dbnamebuf != NULL)
1090  maxbuf = &buf[2];
1091  else if (schemabuf != NULL)
1092  maxbuf = &buf[1];
1093  else
1094  maxbuf = &buf[0];
1095 
1096  curbuf = &buf[0];
1097  if (want_literal_dbname)
1098  {
1099  left = true;
1100  initPQExpBuffer(&left_literal);
1101  }
1102  else
1103  left = false;
1104  initPQExpBuffer(curbuf);
1105  appendPQExpBufferStr(curbuf, "^(");
1106  while (*cp)
1107  {
1108  char ch = *cp;
1109 
1110  if (ch == '"')
1111  {
1112  if (inquotes && cp[1] == '"')
1113  {
1114  /* emit one quote, stay in inquotes mode */
1115  appendPQExpBufferChar(curbuf, '"');
1116  if (left)
1117  appendPQExpBufferChar(&left_literal, '"');
1118  cp++;
1119  }
1120  else
1121  inquotes = !inquotes;
1122  cp++;
1123  }
1124  else if (!inquotes && isupper((unsigned char) ch))
1125  {
1126  appendPQExpBufferChar(curbuf,
1127  pg_tolower((unsigned char) ch));
1128  if (left)
1129  appendPQExpBufferChar(&left_literal,
1130  pg_tolower((unsigned char) ch));
1131  cp++;
1132  }
1133  else if (!inquotes && ch == '*')
1134  {
1135  appendPQExpBufferStr(curbuf, ".*");
1136  if (left)
1137  appendPQExpBufferChar(&left_literal, '*');
1138  cp++;
1139  }
1140  else if (!inquotes && ch == '?')
1141  {
1142  appendPQExpBufferChar(curbuf, '.');
1143  if (left)
1144  appendPQExpBufferChar(&left_literal, '?');
1145  cp++;
1146  }
1147  else if (!inquotes && ch == '.')
1148  {
1149  left = false;
1150  if (dotcnt)
1151  (*dotcnt)++;
1152  if (curbuf < maxbuf)
1153  {
1154  appendPQExpBufferStr(curbuf, ")$");
1155  curbuf++;
1156  initPQExpBuffer(curbuf);
1157  appendPQExpBufferStr(curbuf, "^(");
1158  cp++;
1159  }
1160  else
1161  appendPQExpBufferChar(curbuf, *cp++);
1162  }
1163  else if (ch == '$')
1164  {
1165  /*
1166  * Dollar is always quoted, whether inside quotes or not. The
1167  * reason is that it's allowed in SQL identifiers, so there's a
1168  * significant use-case for treating it literally, while because
1169  * we anchor the pattern automatically there is no use-case for
1170  * having it possess its regexp meaning.
1171  */
1172  appendPQExpBufferStr(curbuf, "\\$");
1173  if (left)
1174  appendPQExpBufferChar(&left_literal, '$');
1175  cp++;
1176  }
1177  else
1178  {
1179  /*
1180  * Ordinary data character, transfer to pattern
1181  *
1182  * Inside double quotes, or at all times if force_escape is true,
1183  * quote regexp special characters with a backslash to avoid
1184  * regexp errors. Outside quotes, however, let them pass through
1185  * as-is; this lets knowledgeable users build regexp expressions
1186  * that are more powerful than shell-style patterns.
1187  *
1188  * As an exception to that, though, always quote "[]", as that's
1189  * much more likely to be an attempt to write an array type name
1190  * than it is to be the start of a regexp bracket expression.
1191  */
1192  if ((inquotes || force_escape) &&
1193  strchr("|*+?()[]{}.^$\\", ch))
1194  appendPQExpBufferChar(curbuf, '\\');
1195  else if (ch == '[' && cp[1] == ']')
1196  appendPQExpBufferChar(curbuf, '\\');
1197  i = PQmblenBounded(cp, encoding);
1198  while (i--)
1199  {
1200  if (left)
1201  appendPQExpBufferChar(&left_literal, *cp);
1202  appendPQExpBufferChar(curbuf, *cp++);
1203  }
1204  }
1205  }
1206  appendPQExpBufferStr(curbuf, ")$");
1207 
1208  if (namebuf)
1209  {
1210  appendPQExpBufferStr(namebuf, curbuf->data);
1211  termPQExpBuffer(curbuf);
1212  curbuf--;
1213  }
1214 
1215  if (schemabuf && curbuf >= buf)
1216  {
1217  appendPQExpBufferStr(schemabuf, curbuf->data);
1218  termPQExpBuffer(curbuf);
1219  curbuf--;
1220  }
1221 
1222  if (dbnamebuf && curbuf >= buf)
1223  {
1224  if (want_literal_dbname)
1225  appendPQExpBufferStr(dbnamebuf, left_literal.data);
1226  else
1227  appendPQExpBufferStr(dbnamebuf, curbuf->data);
1228  termPQExpBuffer(curbuf);
1229  }
1230 }
int PQmblenBounded(const char *s, int encoding)
Definition: fe-misc.c:1195
Assert(fmt[strlen(fmt) - 1] !='\n')
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122

References appendPQExpBufferChar(), appendPQExpBufferStr(), Assert(), buf, PQExpBufferData::data, encoding, i, initPQExpBuffer(), pg_tolower(), PQmblenBounded(), and termPQExpBuffer().

Referenced by append_database_pattern(), append_relation_pattern_helper(), append_schema_pattern(), and processSQLNamePattern().

◆ processSQLNamePattern()

bool processSQLNamePattern ( PGconn conn,
PQExpBuffer  buf,
const char *  pattern,
bool  have_where,
bool  force_escape,
const char *  schemavar,
const char *  namevar,
const char *  altnamevar,
const char *  visibilityrule,
PQExpBuffer  dbnamebuf,
int *  dotcnt 
)

Definition at line 893 of file string_utils.c.

898 {
899  PQExpBufferData schemabuf;
900  PQExpBufferData namebuf;
901  bool added_clause = false;
902  int dcnt;
903 
904 #define WHEREAND() \
905  (appendPQExpBufferStr(buf, have_where ? " AND " : "WHERE "), \
906  have_where = true, added_clause = true)
907 
908  if (dotcnt == NULL)
909  dotcnt = &dcnt;
910  *dotcnt = 0;
911  if (pattern == NULL)
912  {
913  /* Default: select all visible objects */
914  if (visibilityrule)
915  {
916  WHEREAND();
917  appendPQExpBuffer(buf, "%s\n", visibilityrule);
918  }
919  return added_clause;
920  }
921 
922  initPQExpBuffer(&schemabuf);
923  initPQExpBuffer(&namebuf);
924 
925  /*
926  * Convert shell-style 'pattern' into the regular expression(s) we want to
927  * execute. Quoting/escaping into SQL literal format will be done below
928  * using appendStringLiteralConn().
929  *
930  * If the caller provided a schemavar, we want to split the pattern on
931  * ".", otherwise not.
932  */
934  (schemavar ? dbnamebuf : NULL),
935  (schemavar ? &schemabuf : NULL),
936  &namebuf,
937  pattern, force_escape, true, dotcnt);
938 
939  /*
940  * Now decide what we need to emit. We may run under a hostile
941  * search_path, so qualify EVERY name. Note there will be a leading "^("
942  * in the patterns in any case.
943  *
944  * We want the regex matches to use the database's default collation where
945  * collation-sensitive behavior is required (for example, which characters
946  * match '\w'). That happened by default before PG v12, but if the server
947  * is >= v12 then we need to force it through explicit COLLATE clauses,
948  * otherwise the "C" collation attached to "name" catalog columns wins.
949  */
950  if (namevar && namebuf.len > 2)
951  {
952  /* We have a name pattern, so constrain the namevar(s) */
953 
954  /* Optimize away a "*" pattern */
955  if (strcmp(namebuf.data, "^(.*)$") != 0)
956  {
957  WHEREAND();
958  if (altnamevar)
959  {
961  "(%s OPERATOR(pg_catalog.~) ", namevar);
963  if (PQserverVersion(conn) >= 120000)
964  appendPQExpBufferStr(buf, " COLLATE pg_catalog.default");
966  "\n OR %s OPERATOR(pg_catalog.~) ",
967  altnamevar);
969  if (PQserverVersion(conn) >= 120000)
970  appendPQExpBufferStr(buf, " COLLATE pg_catalog.default");
971  appendPQExpBufferStr(buf, ")\n");
972  }
973  else
974  {
975  appendPQExpBuffer(buf, "%s OPERATOR(pg_catalog.~) ", namevar);
977  if (PQserverVersion(conn) >= 120000)
978  appendPQExpBufferStr(buf, " COLLATE pg_catalog.default");
979  appendPQExpBufferChar(buf, '\n');
980  }
981  }
982  }
983 
984  if (schemavar && schemabuf.len > 2)
985  {
986  /* We have a schema pattern, so constrain the schemavar */
987 
988  /* Optimize away a "*" pattern */
989  if (strcmp(schemabuf.data, "^(.*)$") != 0 && schemavar)
990  {
991  WHEREAND();
992  appendPQExpBuffer(buf, "%s OPERATOR(pg_catalog.~) ", schemavar);
993  appendStringLiteralConn(buf, schemabuf.data, conn);
994  if (PQserverVersion(conn) >= 120000)
995  appendPQExpBufferStr(buf, " COLLATE pg_catalog.default");
996  appendPQExpBufferChar(buf, '\n');
997  }
998  }
999  else
1000  {
1001  /* No schema pattern given, so select only visible objects */
1002  if (visibilityrule)
1003  {
1004  WHEREAND();
1005  appendPQExpBuffer(buf, "%s\n", visibilityrule);
1006  }
1007  }
1008 
1009  termPQExpBuffer(&schemabuf);
1010  termPQExpBuffer(&namebuf);
1011 
1012  return added_clause;
1013 #undef WHEREAND
1014 }
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
void patternToSQLRegex(int encoding, PQExpBuffer dbnamebuf, PQExpBuffer schemabuf, PQExpBuffer namebuf, const char *pattern, bool force_escape, bool want_literal_dbname, int *dotcnt)
#define WHEREAND()

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), appendStringLiteralConn(), buf, conn, PQExpBufferData::data, initPQExpBuffer(), PQExpBufferData::len, patternToSQLRegex(), PQclientEncoding(), PQserverVersion(), termPQExpBuffer(), and WHEREAND.

Referenced by describeConfigurationParameters(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), and validateSQLNamePattern().

Variable Documentation

◆ getLocalPQExpBuffer

PQExpBuffer(* getLocalPQExpBuffer) (void) ( void  )
default

Definition at line 27 of file string_utils.c.

40 {
41  static PQExpBuffer id_return = NULL;
42 
43  if (id_return) /* first time through? */
44  {
45  /* same buffer, just wipe contents */
46  resetPQExpBuffer(id_return);
47  }
48  else
49  {
50  /* new buffer */
51  id_return = createPQExpBuffer();
52  }
53 
54  return id_return;
55 }
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148

Referenced by fmtId(), fmtQualifiedId(), and ParallelBackupStart().

◆ quote_all_identifiers

int quote_all_identifiers = 0

Definition at line 26 of file string_utils.c.

Referenced by fmtId().