PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
string_utils.h File Reference
#include "libpq-fe.h"
#include "pqexpbuffer.h"
Include dependency graph for string_utils.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

const char * fmtId (const char *identifier)
 
const char * fmtQualifiedId (int remoteVersion, 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)
 
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)
 

Variables

int quote_all_identifiers
 
PQExpBuffer(* getLocalPQExpBuffer )(void)
 

Function Documentation

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

Definition at line 379 of file string_utils.c.

References PQExpBufferData::data, enlargePQExpBuffer(), hextbl, and PQExpBufferData::len.

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

Definition at line 551 of file string_utils.c.

References appendPQExpBufferChar(), and appendPQExpBufferStr().

Referenced by _connectDB(), appendPsqlMetaConnect(), CloneArchive(), cluster_all_databases(), constructConnStr(), create_new_objects(), do_connect(), generate_old_dump(), GenerateRecoveryConf(), get_db_conn(), reindex_all_databases(), restore_toc_entry(), runPgDump(), and vacuum_all_databases().

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

Definition at line 596 of file string_utils.c.

References _, appendConnStrVal(), appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), connstr, PQExpBufferData::data, EXIT_FAILURE, fmtId(), initPQExpBuffer(), and termPQExpBuffer().

Referenced by _reconnectToDB(), dumpCreateDB(), dumpDatabases(), new_9_0_populate_pg_largeobject_metadata(), and old_9_6_invalidate_hash_indexes().

597 {
598  const char *s;
599  bool complex;
600 
601  /*
602  * If the name is plain ASCII characters, emit a trivial "\connect "foo"".
603  * For other names, even many not technically requiring it, skip to the
604  * general case. No database has a zero-length name.
605  */
606  complex = false;
607 
608  for (s = dbname; *s; s++)
609  {
610  if (*s == '\n' || *s == '\r')
611  {
612  fprintf(stderr,
613  _("database name contains a newline or carriage return: \"%s\"\n"),
614  dbname);
615  exit(EXIT_FAILURE);
616  }
617 
618  if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') ||
619  (*s >= '0' && *s <= '9') || *s == '_' || *s == '.'))
620  {
621  complex = true;
622  }
623  }
624 
625  appendPQExpBufferStr(buf, "\\connect ");
626  if (complex)
627  {
629 
630  initPQExpBuffer(&connstr);
631  appendPQExpBuffer(&connstr, "dbname=");
632  appendConnStrVal(&connstr, dbname);
633 
634  appendPQExpBuffer(buf, "-reuse-previous=on ");
635 
636  /*
637  * As long as the name does not contain a newline, SQL identifier
638  * quoting satisfies the psql meta-command parser. Prefer not to
639  * involve psql-interpreted single quotes, which behaved differently
640  * before PostgreSQL 9.2.
641  */
642  appendPQExpBufferStr(buf, fmtId(connstr.data));
643 
644  termPQExpBuffer(&connstr);
645  }
646  else
648  appendPQExpBufferChar(buf, '\n');
649 }
const char * fmtId(const char *rawid)
Definition: string_utils.c:66
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
void appendConnStrVal(PQExpBuffer buf, const char *str)
Definition: string_utils.c:551
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
char * dbname
Definition: streamutil.c:39
#define EXIT_FAILURE
Definition: settings.h:151
#define _(x)
Definition: elog.c:84
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
static char * connstr
Definition: pg_dumpall.c:64
bool appendReloptionsArray ( PQExpBuffer  buffer,
const char *  reloptions,
const char *  prefix,
int  encoding,
bool  std_strings 
)

Definition at line 747 of file string_utils.c.

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

Referenced by appendReloptionsArrayAH(), and get_create_object_cmd().

749 {
750  char **options;
751  int noptions;
752  int i;
753 
754  if (!parsePGArray(reloptions, &options, &noptions))
755  {
756  if (options)
757  free(options);
758  return false;
759  }
760 
761  for (i = 0; i < noptions; i++)
762  {
763  char *option = options[i];
764  char *name;
765  char *separator;
766  char *value;
767 
768  /*
769  * Each array element should have the form name=value. If the "=" is
770  * missing for some reason, treat it like an empty value.
771  */
772  name = option;
773  separator = strchr(option, '=');
774  if (separator)
775  {
776  *separator = '\0';
777  value = separator + 1;
778  }
779  else
780  value = "";
781 
782  if (i > 0)
783  appendPQExpBufferStr(buffer, ", ");
784  appendPQExpBuffer(buffer, "%s%s=", prefix, fmtId(name));
785 
786  /*
787  * In general we need to quote the value; but to avoid unnecessary
788  * clutter, do not quote if it is an identifier that would not need
789  * quoting. (We could also allow numbers, but that is a bit trickier
790  * than it looks --- for example, are leading zeroes significant? We
791  * don't want to assume very much here about what custom reloptions
792  * might mean.)
793  */
794  if (strcmp(fmtId(value), value) == 0)
795  appendPQExpBufferStr(buffer, value);
796  else
797  appendStringLiteral(buffer, value, encoding, std_strings);
798  }
799 
800  if (options)
801  free(options);
802 
803  return true;
804 }
bool parsePGArray(const char *atext, char ***itemarray, int *nitems)
Definition: string_utils.c:663
const char * fmtId(const char *rawid)
Definition: string_utils.c:66
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
static struct @121 value
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
void appendStringLiteral(PQExpBuffer buf, const char *str, int encoding, bool std_strings)
Definition: string_utils.c:220
static char ** options
static char * encoding
Definition: initdb.c:122
#define free(a)
Definition: header.h:65
const char * name
Definition: encode.c:521
int i
static size_t noptions
void appendShellString ( PQExpBuffer  buf,
const char *  str 
)

Definition at line 434 of file string_utils.c.

References _, appendShellStringNoError(), and EXIT_FAILURE.

Referenced by cluster_conn_opts(), create_new_objects(), create_script_for_cluster_analyze(), generate_old_dump(), main(), and runPgDump().

435 {
436  if (!appendShellStringNoError(buf, str))
437  {
438  fprintf(stderr,
439  _("shell command argument contains a newline or carriage return: \"%s\"\n"),
440  str);
441  exit(EXIT_FAILURE);
442  }
443 }
bool appendShellStringNoError(PQExpBuffer buf, const char *str)
Definition: string_utils.c:446
#define EXIT_FAILURE
Definition: settings.h:151
#define _(x)
Definition: elog.c:84
bool appendShellStringNoError ( PQExpBuffer  buf,
const char *  str 
)

Definition at line 446 of file string_utils.c.

References appendPQExpBufferChar(), and appendPQExpBufferStr().

Referenced by appendShellString(), and psql_get_variable().

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

Definition at line 220 of file string_utils.c.

References PQExpBufferData::data, enlargePQExpBuffer(), i, IS_HIGHBIT_SET, PQExpBufferData::len, length(), PQExpBufferData::maxlen, PQmblen(), and SQL_STR_DOUBLE.

Referenced by appendReloptionsArray(), and appendStringLiteralConn().

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

Definition at line 298 of file string_utils.c.

References appendPQExpBufferChar(), appendStringLiteral(), PQExpBufferData::data, enlargePQExpBuffer(), ESCAPE_STRING_SYNTAX, PQExpBufferData::len, length(), NULL, PQclientEncoding(), PQescapeStringConn(), and PQserverVersion().

Referenced by dumpCreateDB(), dumpDatabaseConfig(), dumpRoles(), dumpTablespaces(), dumpUserConfig(), emitShSecLabels(), exec_command_password(), getTables(), lookup_object_oid(), main(), makeAlterConfigCommand(), processSQLNamePattern(), and setup_connection().

299 {
300  size_t length = strlen(str);
301 
302  /*
303  * XXX This is a kluge to silence escape_string_warning in our utility
304  * programs. It should go away someday.
305  */
306  if (strchr(str, '\\') != NULL && PQserverVersion(conn) >= 80100)
307  {
308  /* ensure we are not adjacent to an identifier */
309  if (buf->len > 0 && buf->data[buf->len - 1] != ' ')
310  appendPQExpBufferChar(buf, ' ');
312  appendStringLiteral(buf, str, PQclientEncoding(conn), false);
313  return;
314  }
315  /* XXX end kluge */
316 
317  if (!enlargePQExpBuffer(buf, 2 * length + 2))
318  return;
319  appendPQExpBufferChar(buf, '\'');
320  buf->len += PQescapeStringConn(conn, buf->data + buf->len,
321  str, length, NULL);
322  appendPQExpBufferChar(buf, '\'');
323 }
int length(const List *list)
Definition: list.c:1271
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6087
#define ESCAPE_STRING_SYNTAX
Definition: c.h:510
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6157
void appendStringLiteral(PQExpBuffer buf, const char *str, int encoding, bool std_strings)
Definition: string_utils.c:220
size_t PQescapeStringConn(PGconn *conn, char *to, const char *from, size_t length, int *error)
Definition: fe-exec.c:3314
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
#define NULL
Definition: c.h:229
int enlargePQExpBuffer(PQExpBuffer str, size_t needed)
Definition: pqexpbuffer.c:171
void appendStringLiteralDQ ( PQExpBuffer  buf,
const char *  str,
const char *  dqprefix 
)

Definition at line 336 of file string_utils.c.

References appendPQExpBufferChar(), appendPQExpBufferStr(), createPQExpBuffer(), PQExpBufferData::data, destroyPQExpBuffer(), and NULL.

Referenced by dumpFunc().

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

Definition at line 66 of file string_utils.c.

References appendPQExpBufferChar(), appendPQExpBufferStr(), ScanKeyword::category, PQExpBufferData::data, getLocalPQExpBuffer, NULL, NumScanKeywords, quote_all_identifiers, ScanKeywordLookup(), ScanKeywords, and UNRESERVED_KEYWORD.

Referenced by _disableTriggersIfNecessary(), _doSetFixedOutputState(), _enableTriggersIfNecessary(), _getObjectDescription(), _printTocEntry(), _selectOutputSchema(), _selectTablespace(), appendPsqlMetaConnect(), appendReloptionsArray(), binary_upgrade_extension_member(), buildACLCommands(), buildDefaultACLCommands(), createDummyViewAsClause(), describeOneTableDetails(), dropDBs(), dropRoles(), dropTablespaces(), dumpAccessMethod(), dumpAgg(), dumpAttrDef(), dumpBaseType(), dumpCast(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpCreateDB(), dumpDatabase(), dumpDomain(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpGroups(), dumpIndex(), dumpNamespace(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpPolicy(), dumpProcLang(), dumpPublication(), dumpPublicationTable(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSecLabel(), dumpSequence(), dumpSequenceData(), dumpShellType(), dumpStatisticsExt(), dumpSubscription(), dumpTable(), dumpTableComment(), dumpTableConstraintComment(), dumpTableData(), 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_arguments_old(), format_function_signature(), get_create_object_cmd(), get_language_name(), main(), makeAlterConfigCommand(), refreshMatViewData(), reindex_one_database(), reindex_system_catalogs(), restore_toc_entry(), selectSourceSchema(), and setup_connection().

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

Definition at line 150 of file string_utils.c.

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

Referenced by dumpTableData(), dumpTableData_copy(), dumpTableData_insert(), getTables(), lockTableForWorker(), and vacuum_one_database().

151 {
152  PQExpBuffer id_return;
153  PQExpBuffer lcl_pqexp = createPQExpBuffer();
154 
155  /* Suppress schema name if fetching from pre-7.3 DB */
156  if (remoteVersion >= 70300 && schema && *schema)
157  {
158  appendPQExpBuffer(lcl_pqexp, "%s.", fmtId(schema));
159  }
160  appendPQExpBufferStr(lcl_pqexp, fmtId(id));
161 
162  id_return = getLocalPQExpBuffer();
163 
164  appendPQExpBufferStr(id_return, lcl_pqexp->data);
165  destroyPQExpBuffer(lcl_pqexp);
166 
167  return id_return->data;
168 }
const char * fmtId(const char *rawid)
Definition: string_utils.c:66
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:113
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
PQExpBuffer(* getLocalPQExpBuffer)(void)
Definition: string_utils.c:29
char* formatPGVersionNumber ( int  version_number,
bool  include_minor,
char *  buf,
size_t  buflen 
)

Definition at line 182 of file string_utils.c.

References buf, and snprintf().

Referenced by connection_warnings(), describeAccessMethods(), describeFunctions(), describePublications(), describeSubscriptions(), describeTablespaces(), exec_command_ef(), exec_command_ev(), exec_command_sf(), exec_command_sv(), listCollations(), listDbRoleSettings(), listDefaultACLs(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listPublications(), listTSConfigs(), listTSDictionaries(), listTSParsers(), listTSTemplates(), listUserMappings(), and SendQuery().

184 {
185  if (version_number >= 100000)
186  {
187  /* New two-part style */
188  if (include_minor)
189  snprintf(buf, buflen, "%d.%d", version_number / 10000,
190  version_number % 10000);
191  else
192  snprintf(buf, buflen, "%d", version_number / 10000);
193  }
194  else
195  {
196  /* Old three-part style */
197  if (include_minor)
198  snprintf(buf, buflen, "%d.%d.%d", version_number / 10000,
199  (version_number / 100) % 100,
200  version_number % 100);
201  else
202  snprintf(buf, buflen, "%d.%d", version_number / 10000,
203  (version_number / 100) % 100);
204  }
205  return buf;
206 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
static char * buf
Definition: pg_test_fsync.c:66
bool parsePGArray ( const char *  atext,
char ***  itemarray,
int *  nitems 
)

Definition at line 663 of file string_utils.c.

References malloc, and NULL.

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

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

Definition at line 833 of file string_utils.c.

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), appendStringLiteralConn(), PQExpBufferData::data, encoding, i, initPQExpBuffer(), PQExpBufferData::len, NULL, pg_tolower(), PQclientEncoding(), PQmblen(), resetPQExpBuffer(), termPQExpBuffer(), and WHEREAND.

Referenced by describeAccessMethods(), describeAggregates(), describeFunctions(), describeOperators(), describePublications(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), expand_schema_name_patterns(), expand_table_name_patterns(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), objectDescription(), and permissionsList().

837 {
838  PQExpBufferData schemabuf;
839  PQExpBufferData namebuf;
840  int encoding = PQclientEncoding(conn);
841  bool inquotes;
842  const char *cp;
843  int i;
844  bool added_clause = false;
845 
846 #define WHEREAND() \
847  (appendPQExpBufferStr(buf, have_where ? " AND " : "WHERE "), \
848  have_where = true, added_clause = true)
849 
850  if (pattern == NULL)
851  {
852  /* Default: select all visible objects */
853  if (visibilityrule)
854  {
855  WHEREAND();
856  appendPQExpBuffer(buf, "%s\n", visibilityrule);
857  }
858  return added_clause;
859  }
860 
861  initPQExpBuffer(&schemabuf);
862  initPQExpBuffer(&namebuf);
863 
864  /*
865  * Parse the pattern, converting quotes and lower-casing unquoted letters.
866  * Also, adjust shell-style wildcard characters into regexp notation.
867  *
868  * We surround the pattern with "^(...)$" to force it to match the whole
869  * string, as per SQL practice. We have to have parens in case the string
870  * contains "|", else the "^" and "$" will be bound into the first and
871  * last alternatives which is not what we want.
872  *
873  * Note: the result of this pass is the actual regexp pattern(s) we want
874  * to execute. Quoting/escaping into SQL literal format will be done
875  * below using appendStringLiteralConn().
876  */
877  appendPQExpBufferStr(&namebuf, "^(");
878 
879  inquotes = false;
880  cp = pattern;
881 
882  while (*cp)
883  {
884  char ch = *cp;
885 
886  if (ch == '"')
887  {
888  if (inquotes && cp[1] == '"')
889  {
890  /* emit one quote, stay in inquotes mode */
891  appendPQExpBufferChar(&namebuf, '"');
892  cp++;
893  }
894  else
895  inquotes = !inquotes;
896  cp++;
897  }
898  else if (!inquotes && isupper((unsigned char) ch))
899  {
900  appendPQExpBufferChar(&namebuf,
901  pg_tolower((unsigned char) ch));
902  cp++;
903  }
904  else if (!inquotes && ch == '*')
905  {
906  appendPQExpBufferStr(&namebuf, ".*");
907  cp++;
908  }
909  else if (!inquotes && ch == '?')
910  {
911  appendPQExpBufferChar(&namebuf, '.');
912  cp++;
913  }
914  else if (!inquotes && ch == '.')
915  {
916  /* Found schema/name separator, move current pattern to schema */
917  resetPQExpBuffer(&schemabuf);
918  appendPQExpBufferStr(&schemabuf, namebuf.data);
919  resetPQExpBuffer(&namebuf);
920  appendPQExpBufferStr(&namebuf, "^(");
921  cp++;
922  }
923  else if (ch == '$')
924  {
925  /*
926  * Dollar is always quoted, whether inside quotes or not. The
927  * reason is that it's allowed in SQL identifiers, so there's a
928  * significant use-case for treating it literally, while because
929  * we anchor the pattern automatically there is no use-case for
930  * having it possess its regexp meaning.
931  */
932  appendPQExpBufferStr(&namebuf, "\\$");
933  cp++;
934  }
935  else
936  {
937  /*
938  * Ordinary data character, transfer to pattern
939  *
940  * Inside double quotes, or at all times if force_escape is true,
941  * quote regexp special characters with a backslash to avoid
942  * regexp errors. Outside quotes, however, let them pass through
943  * as-is; this lets knowledgeable users build regexp expressions
944  * that are more powerful than shell-style patterns.
945  */
946  if ((inquotes || force_escape) &&
947  strchr("|*+?()[]{}.^$\\", ch))
948  appendPQExpBufferChar(&namebuf, '\\');
949  i = PQmblen(cp, encoding);
950  while (i-- && *cp)
951  {
952  appendPQExpBufferChar(&namebuf, *cp);
953  cp++;
954  }
955  }
956  }
957 
958  /*
959  * Now decide what we need to emit. Note there will be a leading "^(" in
960  * the patterns in any case.
961  */
962  if (namebuf.len > 2)
963  {
964  /* We have a name pattern, so constrain the namevar(s) */
965 
966  appendPQExpBufferStr(&namebuf, ")$");
967  /* Optimize away a "*" pattern */
968  if (strcmp(namebuf.data, "^(.*)$") != 0)
969  {
970  WHEREAND();
971  if (altnamevar)
972  {
973  appendPQExpBuffer(buf, "(%s ~ ", namevar);
974  appendStringLiteralConn(buf, namebuf.data, conn);
975  appendPQExpBuffer(buf, "\n OR %s ~ ", altnamevar);
976  appendStringLiteralConn(buf, namebuf.data, conn);
977  appendPQExpBufferStr(buf, ")\n");
978  }
979  else
980  {
981  appendPQExpBuffer(buf, "%s ~ ", namevar);
982  appendStringLiteralConn(buf, namebuf.data, conn);
983  appendPQExpBufferChar(buf, '\n');
984  }
985  }
986  }
987 
988  if (schemabuf.len > 2)
989  {
990  /* We have a schema pattern, so constrain the schemavar */
991 
992  appendPQExpBufferStr(&schemabuf, ")$");
993  /* Optimize away a "*" pattern */
994  if (strcmp(schemabuf.data, "^(.*)$") != 0 && schemavar)
995  {
996  WHEREAND();
997  appendPQExpBuffer(buf, "%s ~ ", schemavar);
998  appendStringLiteralConn(buf, schemabuf.data, conn);
999  appendPQExpBufferChar(buf, '\n');
1000  }
1001  }
1002  else
1003  {
1004  /* No schema pattern given, so select only visible objects */
1005  if (visibilityrule)
1006  {
1007  WHEREAND();
1008  appendPQExpBuffer(buf, "%s\n", visibilityrule);
1009  }
1010  }
1011 
1012  termPQExpBuffer(&schemabuf);
1013  termPQExpBuffer(&namebuf);
1014 
1015  return added_clause;
1016 #undef WHEREAND
1017 }
#define WHEREAND()
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6157
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
static char * encoding
Definition: initdb.c:122
#define NULL
Definition: c.h:229
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:298
int i
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
int PQmblen(const char *s, int encoding)
Definition: fe-misc.c:1182
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89

Variable Documentation

PQExpBuffer(* getLocalPQExpBuffer)(void)
default

Definition at line 29 of file string_utils.c.

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

42 {
43  static PQExpBuffer id_return = NULL;
44 
45  if (id_return) /* first time through? */
46  {
47  /* same buffer, just wipe contents */
48  resetPQExpBuffer(id_return);
49  }
50  else
51  {
52  /* new buffer */
53  id_return = createPQExpBuffer();
54  }
55 
56  return id_return;
57 }
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
#define NULL
Definition: c.h:229
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
int quote_all_identifiers

Definition at line 298 of file ruleutils.c.