Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * String-processing utility routines for frontend code
4 : : *
5 : : * Assorted utility functions that are useful in constructing SQL queries
6 : : * and interpreting backend output.
7 : : *
8 : : *
9 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
10 : : * Portions Copyright (c) 1994, Regents of the University of California
11 : : *
12 : : * src/fe_utils/string_utils.c
13 : : *
14 : : *-------------------------------------------------------------------------
15 : : */
16 : : #include "postgres_fe.h"
17 : :
18 : : #include <ctype.h>
19 : :
20 : : #include "common/keywords.h"
21 : : #include "common/logging.h"
22 : : #include "fe_utils/string_utils.h"
23 : : #include "mb/pg_wchar.h"
24 : :
25 : : static PQExpBuffer defaultGetLocalPQExpBuffer(void);
26 : :
27 : : /* Globals exported by this file */
28 : : int quote_all_identifiers = 0;
29 : : PQExpBuffer (*getLocalPQExpBuffer) (void) = defaultGetLocalPQExpBuffer;
30 : :
31 : : static int fmtIdEncoding = -1;
32 : :
33 : :
34 : : /*
35 : : * Returns a temporary PQExpBuffer, valid until the next call to the function.
36 : : * This is used by fmtId and fmtQualifiedId.
37 : : *
38 : : * Non-reentrant and non-thread-safe but reduces memory leakage. You can
39 : : * replace this with a custom version by setting the getLocalPQExpBuffer
40 : : * function pointer.
41 : : */
42 : : static PQExpBuffer
43 : 379715 : defaultGetLocalPQExpBuffer(void)
44 : : {
45 : : static PQExpBuffer id_return = NULL;
46 : :
47 [ + + ]: 379715 : if (id_return) /* first time through? */
48 : : {
49 : : /* same buffer, just wipe contents */
50 : 379196 : resetPQExpBuffer(id_return);
51 : : }
52 : : else
53 : : {
54 : : /* new buffer */
55 : 519 : id_return = createPQExpBuffer();
56 : : }
57 : :
58 : 379715 : return id_return;
59 : : }
60 : :
61 : : /*
62 : : * Set the encoding that fmtId() and fmtQualifiedId() use.
63 : : *
64 : : * This is not safe against multiple connections having different encodings,
65 : : * but there is no real other way to address the need to know the encoding for
66 : : * fmtId()/fmtQualifiedId() input for safe escaping. Eventually we should get
67 : : * rid of fmtId().
68 : : */
69 : : void
70 : 12165 : setFmtEncoding(int encoding)
71 : : {
72 : 12165 : fmtIdEncoding = encoding;
73 : 12165 : }
74 : :
75 : : /*
76 : : * Return the currently configured encoding for fmtId() and fmtQualifiedId().
77 : : */
78 : : static int
79 : 255601 : getFmtEncoding(void)
80 : : {
81 [ + - ]: 255601 : if (fmtIdEncoding != -1)
82 : 255601 : return fmtIdEncoding;
83 : :
84 : : /*
85 : : * In assertion builds it seems best to fail hard if the encoding was not
86 : : * set, to make it easier to find places with missing calls. But in
87 : : * production builds that seems like a bad idea, thus we instead just
88 : : * default to UTF-8.
89 : : */
90 : : Assert(fmtIdEncoding != -1);
91 : :
92 : 0 : return PG_UTF8;
93 : : }
94 : :
95 : : /*
96 : : * Quotes input string if it's not a legitimate SQL identifier as-is.
97 : : *
98 : : * Note that the returned string must be used before calling fmtIdEnc again,
99 : : * since we re-use the same return buffer each time.
100 : : */
101 : : const char *
102 : 320798 : fmtIdEnc(const char *rawid, int encoding)
103 : : {
104 : 320798 : PQExpBuffer id_return = getLocalPQExpBuffer();
105 : :
106 : : const char *cp;
107 : 320798 : bool need_quotes = false;
108 : 320798 : size_t remaining = strlen(rawid);
109 : :
110 : : /*
111 : : * These checks need to match the identifier production in scan.l. Don't
112 : : * use islower() etc.
113 : : */
114 [ + + ]: 320798 : if (quote_all_identifiers)
115 : 24355 : need_quotes = true;
116 : : /* slightly different rules for first character */
117 [ + + - + : 296443 : else if (!((rawid[0] >= 'a' && rawid[0] <= 'z') || rawid[0] == '_'))
+ + ]
118 : 737 : need_quotes = true;
119 : : else
120 : : {
121 : : /* otherwise check the entire string */
122 : 295706 : cp = rawid;
123 [ + + ]: 3231676 : for (size_t i = 0; i < remaining; i++, cp++)
124 : : {
125 [ + + - + ]: 2947087 : if (!((*cp >= 'a' && *cp <= 'z')
126 [ + + + + ]: 386641 : || (*cp >= '0' && *cp <= '9')
127 [ + + ]: 270809 : || (*cp == '_')))
128 : : {
129 : 11117 : need_quotes = true;
130 : 11117 : break;
131 : : }
132 : : }
133 : : }
134 : :
135 [ + + ]: 320798 : if (!need_quotes)
136 : : {
137 : : /*
138 : : * Check for keyword. We quote keywords except for unreserved ones.
139 : : * (In some cases we could avoid quoting a col_name or type_func_name
140 : : * keyword, but it seems much harder than it's worth to tell that.)
141 : : *
142 : : * Note: ScanKeywordLookup() does case-insensitive comparison, but
143 : : * that's fine, since we already know we have all-lower-case.
144 : : */
145 : 284589 : int kwnum = ScanKeywordLookup(rawid, &ScanKeywords);
146 : :
147 [ + + + + ]: 284589 : if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
148 : 738 : need_quotes = true;
149 : : }
150 : :
151 [ + + ]: 320798 : if (!need_quotes)
152 : : {
153 : : /* no quoting needed */
154 : 283851 : appendPQExpBufferStr(id_return, rawid);
155 : : }
156 : : else
157 : : {
158 : 36947 : appendPQExpBufferChar(id_return, '"');
159 : :
160 : 36947 : cp = &rawid[0];
161 [ + + ]: 439797 : while (remaining > 0)
162 : : {
163 : : int charlen;
164 : :
165 : : /* Fast path for plain ASCII */
166 [ + + ]: 402850 : if (!IS_HIGHBIT_SET(*cp))
167 : : {
168 : : /*
169 : : * Did we find a double-quote in the string? Then make this a
170 : : * double double-quote per SQL99. Before, we put in a
171 : : * backslash/double-quote pair. - thomas 2000-08-05
172 : : */
173 [ + + ]: 400364 : if (*cp == '"')
174 : 344 : appendPQExpBufferChar(id_return, '"');
175 : 400364 : appendPQExpBufferChar(id_return, *cp);
176 : 400364 : remaining--;
177 : 400364 : cp++;
178 : 400364 : continue;
179 : : }
180 : :
181 : : /* Slow path for possible multibyte characters */
182 : 2486 : charlen = pg_encoding_mblen(encoding, cp);
183 : :
184 [ + + + + ]: 4945 : if (remaining < charlen ||
185 : 2459 : pg_encoding_verifymbchar(encoding, cp, charlen) == -1)
186 : : {
187 : : /*
188 : : * Multibyte character is invalid. It's important to verify
189 : : * that as invalid multibyte characters could e.g. be used to
190 : : * "skip" over quote characters, e.g. when parsing
191 : : * character-by-character.
192 : : *
193 : : * Replace the character's first byte with an invalid
194 : : * sequence. The invalid sequence ensures that the escaped
195 : : * string will trigger an error on the server-side, even if we
196 : : * can't directly report an error here.
197 : : *
198 : : * It would be a bit faster to verify the whole string the
199 : : * first time we encounter a set highbit, but this way we can
200 : : * replace just the invalid data, which probably makes it
201 : : * easier for users to find the invalidly encoded portion of a
202 : : * larger string.
203 : : */
204 [ + - ]: 40 : if (enlargePQExpBuffer(id_return, 2))
205 : : {
206 : 40 : pg_encoding_set_invalid(encoding,
207 : 40 : id_return->data + id_return->len);
208 : 40 : id_return->len += 2;
209 : 40 : id_return->data[id_return->len] = '\0';
210 : : }
211 : :
212 : : /*
213 : : * Handle the following bytes as if this byte didn't exist.
214 : : * That's safer in case the subsequent bytes contain
215 : : * characters that are significant for the caller (e.g. '>' in
216 : : * html).
217 : : */
218 : 40 : remaining--;
219 : 40 : cp++;
220 : : }
221 : : else
222 : : {
223 [ + + ]: 4905 : for (int i = 0; i < charlen; i++)
224 : : {
225 : 2459 : appendPQExpBufferChar(id_return, *cp);
226 : 2459 : remaining--;
227 : 2459 : cp++;
228 : : }
229 : : }
230 : : }
231 : :
232 : 36947 : appendPQExpBufferChar(id_return, '"');
233 : : }
234 : :
235 : 320798 : return id_return->data;
236 : : }
237 : :
238 : : /*
239 : : * Quotes input string if it's not a legitimate SQL identifier as-is.
240 : : *
241 : : * Note that the returned string must be used before calling fmtId again,
242 : : * since we re-use the same return buffer each time.
243 : : *
244 : : * NB: This assumes setFmtEncoding() previously has been called to configure
245 : : * the encoding of rawid. It is preferable to use fmtIdEnc() with an
246 : : * explicit encoding.
247 : : */
248 : : const char *
249 : 202883 : fmtId(const char *rawid)
250 : : {
251 : 202883 : return fmtIdEnc(rawid, getFmtEncoding());
252 : : }
253 : :
254 : : /*
255 : : * fmtQualifiedIdEnc - construct a schema-qualified name, with quoting as
256 : : * needed.
257 : : *
258 : : * Like fmtId, use the result before calling again.
259 : : *
260 : : * Since we call fmtId and it also uses getLocalPQExpBuffer() we cannot
261 : : * use that buffer until we're finished with calling fmtId().
262 : : */
263 : : const char *
264 : 58917 : fmtQualifiedIdEnc(const char *schema, const char *id, int encoding)
265 : : {
266 : : PQExpBuffer id_return;
267 : 58917 : PQExpBuffer lcl_pqexp = createPQExpBuffer();
268 : :
269 : : /* Some callers might fail to provide a schema name */
270 [ + - + - ]: 58917 : if (schema && *schema)
271 : : {
272 : 58917 : appendPQExpBuffer(lcl_pqexp, "%s.", fmtIdEnc(schema, encoding));
273 : : }
274 : 58917 : appendPQExpBufferStr(lcl_pqexp, fmtIdEnc(id, encoding));
275 : :
276 : 58917 : id_return = getLocalPQExpBuffer();
277 : :
278 : 58917 : appendPQExpBufferStr(id_return, lcl_pqexp->data);
279 : 58917 : destroyPQExpBuffer(lcl_pqexp);
280 : :
281 : 58917 : return id_return->data;
282 : : }
283 : :
284 : : /*
285 : : * fmtQualifiedId - construct a schema-qualified name, with quoting as needed.
286 : : *
287 : : * Like fmtId, use the result before calling again.
288 : : *
289 : : * Since we call fmtId and it also uses getLocalPQExpBuffer() we cannot
290 : : * use that buffer until we're finished with calling fmtId().
291 : : *
292 : : * NB: This assumes setFmtEncoding() previously has been called to configure
293 : : * the encoding of schema/id. It is preferable to use fmtQualifiedIdEnc()
294 : : * with an explicit encoding.
295 : : */
296 : : const char *
297 : 52718 : fmtQualifiedId(const char *schema, const char *id)
298 : : {
299 : 52718 : return fmtQualifiedIdEnc(schema, id, getFmtEncoding());
300 : : }
301 : :
302 : :
303 : : /*
304 : : * Format a Postgres version number (in the PG_VERSION_NUM integer format
305 : : * returned by PQserverVersion()) as a string. This exists mainly to
306 : : * encapsulate knowledge about two-part vs. three-part version numbers.
307 : : *
308 : : * For reentrancy, caller must supply the buffer the string is put in.
309 : : * Recommended size of the buffer is 32 bytes.
310 : : *
311 : : * Returns address of 'buf', as a notational convenience.
312 : : */
313 : : char *
314 : 0 : formatPGVersionNumber(int version_number, bool include_minor,
315 : : char *buf, size_t buflen)
316 : : {
317 [ # # ]: 0 : if (version_number >= 100000)
318 : : {
319 : : /* New two-part style */
320 [ # # ]: 0 : if (include_minor)
321 : 0 : snprintf(buf, buflen, "%d.%d", version_number / 10000,
322 : : version_number % 10000);
323 : : else
324 : 0 : snprintf(buf, buflen, "%d", version_number / 10000);
325 : : }
326 : : else
327 : : {
328 : : /* Old three-part style */
329 [ # # ]: 0 : if (include_minor)
330 : 0 : snprintf(buf, buflen, "%d.%d.%d", version_number / 10000,
331 : 0 : (version_number / 100) % 100,
332 : : version_number % 100);
333 : : else
334 : 0 : snprintf(buf, buflen, "%d.%d", version_number / 10000,
335 : 0 : (version_number / 100) % 100);
336 : : }
337 : 0 : return buf;
338 : : }
339 : :
340 : :
341 : : /*
342 : : * Convert a string value to an SQL string literal and append it to
343 : : * the given buffer. We assume the specified client_encoding and
344 : : * standard_conforming_strings settings.
345 : : *
346 : : * This is essentially equivalent to libpq's PQescapeStringInternal,
347 : : * except for the output buffer structure. We need it in situations
348 : : * where we do not have a PGconn available. Where we do,
349 : : * appendStringLiteralConn is a better choice.
350 : : */
351 : : void
352 : 41219 : appendStringLiteral(PQExpBuffer buf, const char *str,
353 : : int encoding, bool std_strings)
354 : : {
355 : 41219 : size_t length = strlen(str);
356 : 41219 : const char *source = str;
357 : : char *target;
358 : 41219 : size_t remaining = length;
359 : :
360 [ - + ]: 41219 : if (!enlargePQExpBuffer(buf, 2 * length + 2))
361 : 0 : return;
362 : :
363 : 41219 : target = buf->data + buf->len;
364 : 41219 : *target++ = '\'';
365 : :
366 [ + + ]: 1030548 : while (remaining > 0)
367 : : {
368 : 989329 : char c = *source;
369 : : int charlen;
370 : : int i;
371 : :
372 : : /* Fast path for plain ASCII */
373 [ + + ]: 989329 : if (!IS_HIGHBIT_SET(c))
374 : : {
375 : : /* Apply quoting if needed */
376 [ + + + + : 989272 : if (SQL_STR_DOUBLE(c, !std_strings))
- + ]
377 : 205 : *target++ = c;
378 : : /* Copy the character */
379 : 989272 : *target++ = c;
380 : 989272 : source++;
381 : 989272 : remaining--;
382 : 989272 : continue;
383 : : }
384 : :
385 : : /* Slow path for possible multibyte characters */
386 : 57 : charlen = PQmblen(source, encoding);
387 : :
388 [ + + + + ]: 87 : if (remaining < charlen ||
389 : 30 : pg_encoding_verifymbchar(encoding, source, charlen) == -1)
390 : : {
391 : : /*
392 : : * Multibyte character is invalid. It's important to verify that
393 : : * as invalid multibyte characters could e.g. be used to "skip"
394 : : * over quote characters, e.g. when parsing
395 : : * character-by-character.
396 : : *
397 : : * Replace the character's first byte with an invalid sequence.
398 : : * The invalid sequence ensures that the escaped string will
399 : : * trigger an error on the server-side, even if we can't directly
400 : : * report an error here.
401 : : *
402 : : * We know there's enough space for the invalid sequence because
403 : : * the "target" buffer is 2 * length + 2 long, and at worst we're
404 : : * replacing a single input byte with two invalid bytes.
405 : : *
406 : : * It would be a bit faster to verify the whole string the first
407 : : * time we encounter a set highbit, but this way we can replace
408 : : * just the invalid data, which probably makes it easier for users
409 : : * to find the invalidly encoded portion of a larger string.
410 : : */
411 : 40 : pg_encoding_set_invalid(encoding, target);
412 : 40 : target += 2;
413 : :
414 : : /*
415 : : * Handle the following bytes as if this byte didn't exist. That's
416 : : * safer in case the subsequent bytes contain important characters
417 : : * for the caller (e.g. '>' in html).
418 : : */
419 : 40 : source++;
420 : 40 : remaining--;
421 : : }
422 : : else
423 : : {
424 : : /* Copy the character */
425 [ + + ]: 52 : for (i = 0; i < charlen; i++)
426 : : {
427 : 35 : *target++ = *source++;
428 : 35 : remaining--;
429 : : }
430 : : }
431 : : }
432 : :
433 : : /* Write the terminating quote and NUL character. */
434 : 41219 : *target++ = '\'';
435 : 41219 : *target = '\0';
436 : :
437 : 41219 : buf->len = target - buf->data;
438 : : }
439 : :
440 : :
441 : : /*
442 : : * Convert a string value to an SQL string literal and append it to
443 : : * the given buffer. Encoding and string syntax rules are as indicated
444 : : * by current settings of the PGconn.
445 : : */
446 : : void
447 : 6200 : appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
448 : : {
449 : 6200 : size_t length = strlen(str);
450 : :
451 : : /*
452 : : * XXX This is a kluge to silence escape_string_warning in our utility
453 : : * programs. It can go away once pre-v19 servers are out of support.
454 : : */
455 [ + + - + ]: 6200 : if (strchr(str, '\\') != NULL && PQserverVersion(conn) < 190000)
456 : : {
457 : : /* ensure we are not adjacent to an identifier */
458 [ # # # # ]: 0 : if (buf->len > 0 && buf->data[buf->len - 1] != ' ')
459 : 0 : appendPQExpBufferChar(buf, ' ');
460 : 0 : appendPQExpBufferChar(buf, ESCAPE_STRING_SYNTAX);
461 : 0 : appendStringLiteral(buf, str, PQclientEncoding(conn), false);
462 : 0 : return;
463 : : }
464 : : /* XXX end kluge */
465 : :
466 [ - + ]: 6200 : if (!enlargePQExpBuffer(buf, 2 * length + 2))
467 : 0 : return;
468 : 6200 : appendPQExpBufferChar(buf, '\'');
469 : 6200 : buf->len += PQescapeStringConn(conn, buf->data + buf->len,
470 : : str, length, NULL);
471 : 6200 : appendPQExpBufferChar(buf, '\'');
472 : : }
473 : :
474 : :
475 : : /*
476 : : * Convert a string value to a dollar quoted literal and append it to
477 : : * the given buffer. If the dqprefix parameter is not NULL then the
478 : : * dollar quote delimiter will begin with that (after the opening $).
479 : : *
480 : : * No escaping is done at all on str, in compliance with the rules
481 : : * for parsing dollar quoted strings. Also, we need not worry about
482 : : * encoding issues.
483 : : */
484 : : void
485 : 1592 : appendStringLiteralDQ(PQExpBuffer buf, const char *str, const char *dqprefix)
486 : : {
487 : : static const char suffixes[] = "_XXXXXXX";
488 : 1592 : int nextchar = 0;
489 : 1592 : PQExpBuffer delimBuf = createPQExpBuffer();
490 : : const char *match;
491 : :
492 : : /* start with $ + dqprefix if not NULL */
493 : 1592 : appendPQExpBufferChar(delimBuf, '$');
494 [ - + ]: 1592 : if (dqprefix)
495 : 0 : appendPQExpBufferStr(delimBuf, dqprefix);
496 : :
497 : : /*
498 : : * Make sure we choose a delimiter which (without the trailing $) is not
499 : : * present in the string being quoted. We don't check with the trailing $
500 : : * because a string ending in $foo must not be quoted with $foo$.
501 : : *
502 : : * Each candidate extends the previous one, so we can resume searching at
503 : : * the previous match.
504 : : */
505 : 1592 : match = str;
506 [ + + ]: 2108 : while ((match = strstr(match, delimBuf->data)) != NULL)
507 : : {
508 : 516 : appendPQExpBufferChar(delimBuf, suffixes[nextchar++]);
509 : 516 : nextchar %= sizeof(suffixes) - 1;
510 : : }
511 : :
512 : : /* add trailing $ */
513 : 1592 : appendPQExpBufferChar(delimBuf, '$');
514 : :
515 : : /* quote it and we are all done */
516 : 1592 : appendPQExpBufferStr(buf, delimBuf->data);
517 : 1592 : appendPQExpBufferStr(buf, str);
518 : 1592 : appendPQExpBufferStr(buf, delimBuf->data);
519 : :
520 : 1592 : destroyPQExpBuffer(delimBuf);
521 : 1592 : }
522 : :
523 : :
524 : : /*
525 : : * Convert a bytea value (presented as raw bytes) to an SQL string literal
526 : : * and append it to the given buffer. We assume the specified
527 : : * standard_conforming_strings setting.
528 : : *
529 : : * This is needed in situations where we do not have a PGconn available.
530 : : * Where we do, PQescapeByteaConn is a better choice.
531 : : */
532 : : void
533 : 45 : appendByteaLiteral(PQExpBuffer buf, const unsigned char *str, size_t length,
534 : : bool std_strings)
535 : : {
536 : 45 : const unsigned char *source = str;
537 : : char *target;
538 : :
539 : : static const char hextbl[] = "0123456789abcdef";
540 : :
541 : : /*
542 : : * This implementation is hard-wired to produce hex-format output. We do
543 : : * not know the server version the output will be loaded into, so making
544 : : * an intelligent format choice is impossible. It might be better to
545 : : * always use the old escaped format.
546 : : */
547 [ - + ]: 45 : if (!enlargePQExpBuffer(buf, 2 * length + 5))
548 : 0 : return;
549 : :
550 : 45 : target = buf->data + buf->len;
551 : 45 : *target++ = '\'';
552 [ - + ]: 45 : if (!std_strings)
553 : 0 : *target++ = '\\';
554 : 45 : *target++ = '\\';
555 : 45 : *target++ = 'x';
556 : :
557 [ + + ]: 4119 : while (length-- > 0)
558 : : {
559 : 4074 : unsigned char c = *source++;
560 : :
561 : 4074 : *target++ = hextbl[(c >> 4) & 0xF];
562 : 4074 : *target++ = hextbl[c & 0xF];
563 : : }
564 : :
565 : : /* Write the terminating quote and NUL character. */
566 : 45 : *target++ = '\'';
567 : 45 : *target = '\0';
568 : :
569 : 45 : buf->len = target - buf->data;
570 : : }
571 : :
572 : :
573 : : /*
574 : : * Append the given string to the shell command being built in the buffer,
575 : : * with shell-style quoting as needed to create exactly one argument.
576 : : *
577 : : * Forbid LF or CR characters, which have scant practical use beyond designing
578 : : * security breaches. The Windows command shell is unusable as a conduit for
579 : : * arguments containing LF or CR characters.
580 : : *
581 : : * appendShellString() simply prints an error and dies if LF or CR appears.
582 : : * appendShellStringNoError() omits those characters from the result, and
583 : : * returns false if there were any.
584 : : */
585 : : void
586 : 593 : appendShellString(PQExpBuffer buf, const char *str)
587 : : {
588 [ - + ]: 593 : if (!appendShellStringNoError(buf, str))
589 : 0 : pg_fatal("shell command argument contains a newline or carriage return: \"%s\"", str);
590 : 593 : }
591 : :
592 : : bool
593 : 593 : appendShellStringNoError(PQExpBuffer buf, const char *str)
594 : : {
595 : : #ifdef WIN32
596 : : int backslash_run_length = 0;
597 : : #endif
598 : 593 : bool ok = true;
599 : : const char *p;
600 : :
601 : : /*
602 : : * Don't bother with adding quotes if the string is nonempty and clearly
603 : : * contains only safe characters.
604 : : */
605 [ + - ]: 593 : if (*str != '\0' &&
606 [ + + ]: 593 : strspn(str, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_./:") == strlen(str))
607 : : {
608 : 497 : appendPQExpBufferStr(buf, str);
609 : 497 : return ok;
610 : : }
611 : :
612 : : #ifndef WIN32
613 : 96 : appendPQExpBufferChar(buf, '\'');
614 [ + + ]: 3761 : for (p = str; *p; p++)
615 : : {
616 [ + - - + ]: 3665 : if (*p == '\n' || *p == '\r')
617 : : {
618 : 0 : ok = false;
619 : 0 : continue;
620 : : }
621 : :
622 [ + + ]: 3665 : if (*p == '\'')
623 : 96 : appendPQExpBufferStr(buf, "'\"'\"'");
624 : : else
625 : 3569 : appendPQExpBufferChar(buf, *p);
626 : : }
627 : 96 : appendPQExpBufferChar(buf, '\'');
628 : : #else /* WIN32 */
629 : :
630 : : /*
631 : : * A Windows system() argument experiences two layers of interpretation.
632 : : * First, cmd.exe interprets the string. Its behavior is undocumented,
633 : : * but a caret escapes any byte except LF or CR that would otherwise have
634 : : * special meaning. Handling of a caret before LF or CR differs between
635 : : * "cmd.exe /c" and other modes, and it is unusable here.
636 : : *
637 : : * Second, the new process parses its command line to construct argv (see
638 : : * https://msdn.microsoft.com/en-us/library/17w5ykft.aspx). This treats
639 : : * backslash-double quote sequences specially.
640 : : */
641 : : appendPQExpBufferStr(buf, "^\"");
642 : : for (p = str; *p; p++)
643 : : {
644 : : if (*p == '\n' || *p == '\r')
645 : : {
646 : : ok = false;
647 : : continue;
648 : : }
649 : :
650 : : /* Change N backslashes before a double quote to 2N+1 backslashes. */
651 : : if (*p == '"')
652 : : {
653 : : while (backslash_run_length)
654 : : {
655 : : appendPQExpBufferStr(buf, "^\\");
656 : : backslash_run_length--;
657 : : }
658 : : appendPQExpBufferStr(buf, "^\\");
659 : : }
660 : : else if (*p == '\\')
661 : : backslash_run_length++;
662 : : else
663 : : backslash_run_length = 0;
664 : :
665 : : /*
666 : : * Decline to caret-escape the most mundane characters, to ease
667 : : * debugging and lest we approach the command length limit.
668 : : */
669 : : if (!((*p >= 'a' && *p <= 'z') ||
670 : : (*p >= 'A' && *p <= 'Z') ||
671 : : (*p >= '0' && *p <= '9')))
672 : : appendPQExpBufferChar(buf, '^');
673 : : appendPQExpBufferChar(buf, *p);
674 : : }
675 : :
676 : : /*
677 : : * Change N backslashes at end of argument to 2N backslashes, because they
678 : : * precede the double quote that terminates the argument.
679 : : */
680 : : while (backslash_run_length)
681 : : {
682 : : appendPQExpBufferStr(buf, "^\\");
683 : : backslash_run_length--;
684 : : }
685 : : appendPQExpBufferStr(buf, "^\"");
686 : : #endif /* WIN32 */
687 : :
688 : 96 : return ok;
689 : : }
690 : :
691 : :
692 : : /*
693 : : * Append the given string to the buffer, with suitable quoting for passing
694 : : * the string as a value in a keyword/value pair in a libpq connection string.
695 : : */
696 : : void
697 : 2947 : appendConnStrVal(PQExpBuffer buf, const char *str)
698 : : {
699 : : const char *s;
700 : : bool needquotes;
701 : :
702 : : /*
703 : : * If the string is one or more plain ASCII characters, no need to quote
704 : : * it. This is quite conservative, but better safe than sorry.
705 : : */
706 : 2947 : needquotes = true;
707 [ + + ]: 20015 : for (s = str; *s; s++)
708 : : {
709 [ + + - + : 18061 : if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') ||
+ + + + ]
710 [ + + + + : 2243 : (*s >= '0' && *s <= '9') || *s == '_' || *s == '.'))
+ + + + ]
711 : : {
712 : 993 : needquotes = true;
713 : 993 : break;
714 : : }
715 : 17068 : needquotes = false;
716 : : }
717 : :
718 [ + + ]: 2947 : if (needquotes)
719 : : {
720 : 993 : appendPQExpBufferChar(buf, '\'');
721 [ + + ]: 20607 : while (*str)
722 : : {
723 : : /* ' and \ must be escaped by to \' and \\ */
724 [ + + + + ]: 19614 : if (*str == '\'' || *str == '\\')
725 : 338 : appendPQExpBufferChar(buf, '\\');
726 : :
727 : 19614 : appendPQExpBufferChar(buf, *str);
728 : 19614 : str++;
729 : : }
730 : 993 : appendPQExpBufferChar(buf, '\'');
731 : : }
732 : : else
733 : 1954 : appendPQExpBufferStr(buf, str);
734 : 2947 : }
735 : :
736 : :
737 : : /*
738 : : * Append a psql meta-command that connects to the given database with the
739 : : * then-current connection's user, host and port.
740 : : */
741 : : void
742 : 45 : appendPsqlMetaConnect(PQExpBuffer buf, const char *dbname)
743 : : {
744 : : const char *s;
745 : : bool complex;
746 : :
747 : : /*
748 : : * If the name is plain ASCII characters, emit a trivial "\connect "foo"".
749 : : * For other names, even many not technically requiring it, skip to the
750 : : * general case. No database has a zero-length name.
751 : : */
752 : 45 : complex = false;
753 : :
754 [ + + ]: 1033 : for (s = dbname; *s; s++)
755 : : {
756 [ + - - + ]: 988 : if (*s == '\n' || *s == '\r')
757 : 0 : pg_fatal("database name contains a newline or carriage return: \"%s\"", dbname);
758 : :
759 [ + + + + : 988 : if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') ||
+ + + + ]
760 [ + + + + : 397 : (*s >= '0' && *s <= '9') || *s == '_' || *s == '.'))
+ + + + ]
761 : : {
762 : 327 : complex = true;
763 : : }
764 : : }
765 : :
766 [ + + ]: 45 : if (complex)
767 : : {
768 : : PQExpBufferData connstr;
769 : :
770 : 10 : initPQExpBuffer(&connstr);
771 : :
772 : : /*
773 : : * Force the target psql's encoding to SQL_ASCII. We don't really
774 : : * know the encoding of the database name, and it doesn't matter as
775 : : * long as psql will forward it to the server unchanged.
776 : : */
777 : 10 : appendPQExpBufferStr(buf, "\\encoding SQL_ASCII\n");
778 : 10 : appendPQExpBufferStr(buf, "\\connect -reuse-previous=on ");
779 : :
780 : 10 : appendPQExpBufferStr(&connstr, "dbname=");
781 : 10 : appendConnStrVal(&connstr, dbname);
782 : :
783 : : /*
784 : : * As long as the name does not contain a newline, SQL identifier
785 : : * quoting satisfies the psql meta-command parser. Prefer not to
786 : : * involve psql-interpreted single quotes, which behaved differently
787 : : * before PostgreSQL 9.2.
788 : : */
789 : 10 : appendPQExpBufferStr(buf, fmtIdEnc(connstr.data, PG_SQL_ASCII));
790 : :
791 : 10 : termPQExpBuffer(&connstr);
792 : : }
793 : : else
794 : : {
795 : 35 : appendPQExpBufferStr(buf, "\\connect ");
796 : 35 : appendPQExpBufferStr(buf, fmtIdEnc(dbname, PG_SQL_ASCII));
797 : : }
798 : 45 : appendPQExpBufferChar(buf, '\n');
799 : 45 : }
800 : :
801 : :
802 : : /*
803 : : * SplitGUCList --- parse a string containing identifiers or file names
804 : : *
805 : : * This is used to split the value of a GUC_LIST_QUOTE GUC variable, without
806 : : * presuming whether the elements will be taken as identifiers or file names.
807 : : * See comparable code in src/backend/utils/adt/varlena.c.
808 : : *
809 : : * Inputs:
810 : : * rawstring: the input string; must be overwritable! On return, it's
811 : : * been modified to contain the separated identifiers.
812 : : * separator: the separator punctuation expected between identifiers
813 : : * (typically '.' or ','). Whitespace may also appear around
814 : : * identifiers.
815 : : * Outputs:
816 : : * namelist: receives a malloc'd, null-terminated array of pointers to
817 : : * identifiers within rawstring. Caller should free this
818 : : * even on error return.
819 : : *
820 : : * Returns true if okay, false if there is a syntax error in the string.
821 : : */
822 : : bool
823 : 18 : SplitGUCList(char *rawstring, char separator,
824 : : char ***namelist)
825 : : {
826 : 18 : char *nextp = rawstring;
827 : 18 : bool done = false;
828 : : char **nextptr;
829 : :
830 : : /*
831 : : * Since we disallow empty identifiers, this is a conservative
832 : : * overestimate of the number of pointers we could need. Allow one for
833 : : * list terminator.
834 : : */
835 : 18 : *namelist = nextptr =
836 : 18 : pg_malloc_array(char *, (strlen(rawstring) / 2 + 2));
837 : 18 : *nextptr = NULL;
838 : :
839 [ - + ]: 18 : while (isspace((unsigned char) *nextp))
840 : 0 : nextp++; /* skip leading whitespace */
841 : :
842 [ + + ]: 18 : if (*nextp == '\0')
843 : 5 : return true; /* empty string represents empty list */
844 : :
845 : : /* At the top of the loop, we are at start of a new identifier. */
846 : : do
847 : : {
848 : : char *curname;
849 : : char *endp;
850 : :
851 [ + + ]: 30 : if (*nextp == '"')
852 : : {
853 : : /* Quoted name --- collapse quote-quote pairs */
854 : 20 : curname = nextp + 1;
855 : : for (;;)
856 : : {
857 : 30 : endp = strchr(nextp + 1, '"');
858 [ - + ]: 25 : if (endp == NULL)
859 : 0 : return false; /* mismatched quotes */
860 [ + + ]: 25 : if (endp[1] != '"')
861 : 20 : break; /* found end of quoted name */
862 : : /* Collapse adjacent quotes into one quote, and look again */
863 : 5 : memmove(endp, endp + 1, strlen(endp));
864 : 5 : nextp = endp;
865 : : }
866 : : /* endp now points at the terminating quote */
867 : 20 : nextp = endp + 1;
868 : : }
869 : : else
870 : : {
871 : : /* Unquoted name --- extends to separator or whitespace */
872 : 10 : curname = nextp;
873 [ + + + + ]: 110 : while (*nextp && *nextp != separator &&
874 [ + - ]: 100 : !isspace((unsigned char) *nextp))
875 : 100 : nextp++;
876 : 10 : endp = nextp;
877 [ - + ]: 10 : if (curname == nextp)
878 : 0 : return false; /* empty unquoted name not allowed */
879 : : }
880 : :
881 [ - + ]: 30 : while (isspace((unsigned char) *nextp))
882 : 0 : nextp++; /* skip trailing whitespace */
883 : :
884 [ + + ]: 30 : if (*nextp == separator)
885 : : {
886 : 17 : nextp++;
887 [ + + ]: 34 : while (isspace((unsigned char) *nextp))
888 : 17 : nextp++; /* skip leading whitespace for next */
889 : : /* we expect another name, so done remains false */
890 : : }
891 [ + - ]: 13 : else if (*nextp == '\0')
892 : 13 : done = true;
893 : : else
894 : 0 : return false; /* invalid syntax */
895 : :
896 : : /* Now safe to overwrite separator with a null */
897 : 30 : *endp = '\0';
898 : :
899 : : /*
900 : : * Finished isolating current name --- add it to output array
901 : : */
902 : 30 : *nextptr++ = curname;
903 : :
904 : : /* Loop back if we didn't reach end of string */
905 [ + + ]: 30 : } while (!done);
906 : :
907 : 13 : *nextptr = NULL;
908 : 13 : return true;
909 : : }
910 : :
911 : :
912 : : /*
913 : : * Deconstruct the text representation of a 1-dimensional Postgres array
914 : : * into individual items.
915 : : *
916 : : * On success, returns true and sets *itemarray and *nitems to describe
917 : : * an array of individual strings. On parse failure, returns false;
918 : : * *itemarray may exist or be NULL.
919 : : *
920 : : * NOTE: free'ing itemarray is sufficient to deallocate the working storage.
921 : : */
922 : : bool
923 : 71205 : parsePGArray(const char *atext, char ***itemarray, int *nitems)
924 : : {
925 : : int inputlen;
926 : : char **items;
927 : : char *strings;
928 : : int curitem;
929 : :
930 : : /*
931 : : * We expect input in the form of "{item,item,item}" where any item is
932 : : * either raw data, or surrounded by double quotes (in which case embedded
933 : : * characters including backslashes and quotes are backslashed).
934 : : *
935 : : * We build the result as an array of pointers followed by the actual
936 : : * string data, all in one malloc block for convenience of deallocation.
937 : : * The worst-case storage need is not more than one pointer and one
938 : : * character for each input character (consider "{,,,,,,,,,,}").
939 : : */
940 : 71205 : *itemarray = NULL;
941 : 71205 : *nitems = 0;
942 : 71205 : inputlen = strlen(atext);
943 [ + - + - : 71205 : if (inputlen < 2 || atext[0] != '{' || atext[inputlen - 1] != '}')
- + ]
944 : 0 : return false; /* bad input */
945 : 71205 : items = (char **) malloc(inputlen * (sizeof(char *) + sizeof(char)));
946 [ - + ]: 71205 : if (items == NULL)
947 : 0 : return false; /* out of memory */
948 : 71205 : *itemarray = items;
949 : 71205 : strings = (char *) (items + inputlen);
950 : :
951 : 71205 : atext++; /* advance over initial '{' */
952 : 71205 : curitem = 0;
953 [ + + ]: 195553 : while (*atext != '}')
954 : : {
955 [ - + ]: 124348 : if (*atext == '\0')
956 : 0 : return false; /* premature end of string */
957 : 124348 : items[curitem] = strings;
958 [ + + + + ]: 2473499 : while (*atext != '}' && *atext != ',')
959 : : {
960 [ - + ]: 2349151 : if (*atext == '\0')
961 : 0 : return false; /* premature end of string */
962 [ + + ]: 2349151 : if (*atext != '"')
963 : 2348956 : *strings++ = *atext++; /* copy unquoted data */
964 : : else
965 : : {
966 : : /* process quoted substring */
967 : 195 : atext++;
968 [ + + ]: 6634 : while (*atext != '"')
969 : : {
970 [ - + ]: 6439 : if (*atext == '\0')
971 : 0 : return false; /* premature end of string */
972 [ + + ]: 6439 : if (*atext == '\\')
973 : : {
974 : 975 : atext++;
975 [ - + ]: 975 : if (*atext == '\0')
976 : 0 : return false; /* premature end of string */
977 : : }
978 : 6439 : *strings++ = *atext++; /* copy quoted data */
979 : : }
980 : 195 : atext++;
981 : : }
982 : : }
983 : 124348 : *strings++ = '\0';
984 [ + + ]: 124348 : if (*atext == ',')
985 : 54586 : atext++;
986 : 124348 : curitem++;
987 : : }
988 [ - + ]: 71205 : if (atext[1] != '\0')
989 : 0 : return false; /* bogus syntax (embedded '}') */
990 : 71205 : *nitems = curitem;
991 : 71205 : return true;
992 : : }
993 : :
994 : :
995 : : /*
996 : : * Append one element to the text representation of a 1-dimensional Postgres
997 : : * array.
998 : : *
999 : : * The caller must provide the initial '{' and closing '}' of the array.
1000 : : * This function handles all else, including insertion of commas and
1001 : : * quoting of values.
1002 : : *
1003 : : * We assume that typdelim is ','.
1004 : : */
1005 : : void
1006 : 4144 : appendPGArray(PQExpBuffer buffer, const char *value)
1007 : : {
1008 : : bool needquote;
1009 : : const char *tmp;
1010 : :
1011 [ + + ]: 4144 : if (buffer->data[buffer->len - 1] != '{')
1012 : 3820 : appendPQExpBufferChar(buffer, ',');
1013 : :
1014 : : /* Decide if we need quotes; this should match array_out()'s choices. */
1015 [ - + ]: 4144 : if (value[0] == '\0')
1016 : 0 : needquote = true; /* force quotes for empty string */
1017 [ - + ]: 4144 : else if (pg_strcasecmp(value, "NULL") == 0)
1018 : 0 : needquote = true; /* force quotes for literal NULL */
1019 : : else
1020 : 4144 : needquote = false;
1021 : :
1022 [ + - ]: 4144 : if (!needquote)
1023 : : {
1024 [ + + ]: 32761 : for (tmp = value; *tmp; tmp++)
1025 : : {
1026 : 28723 : char ch = *tmp;
1027 : :
1028 [ + + + - : 28723 : if (ch == '"' || ch == '\\' ||
+ - ]
1029 [ + - + - : 28617 : ch == '{' || ch == '}' || ch == ',' ||
+ - ]
1030 : : /* these match scanner_isspace(): */
1031 [ + - + - : 28617 : ch == ' ' || ch == '\t' || ch == '\n' ||
+ - ]
1032 [ + - - + ]: 28617 : ch == '\r' || ch == '\v' || ch == '\f')
1033 : : {
1034 : 106 : needquote = true;
1035 : 106 : break;
1036 : : }
1037 : : }
1038 : : }
1039 : :
1040 [ + + ]: 4144 : if (needquote)
1041 : : {
1042 : 106 : appendPQExpBufferChar(buffer, '"');
1043 [ + + ]: 4611 : for (tmp = value; *tmp; tmp++)
1044 : : {
1045 : 4505 : char ch = *tmp;
1046 : :
1047 [ + + + + ]: 4505 : if (ch == '"' || ch == '\\')
1048 : 795 : appendPQExpBufferChar(buffer, '\\');
1049 : 4505 : appendPQExpBufferChar(buffer, ch);
1050 : : }
1051 : 106 : appendPQExpBufferChar(buffer, '"');
1052 : : }
1053 : : else
1054 : 4038 : appendPQExpBufferStr(buffer, value);
1055 : 4144 : }
1056 : :
1057 : :
1058 : : /*
1059 : : * Format a reloptions array and append it to the given buffer.
1060 : : *
1061 : : * "prefix" is prepended to the option names; typically it's "" or "toast.".
1062 : : *
1063 : : * Returns false if the reloptions array could not be parsed (in which case
1064 : : * nothing will have been appended to the buffer), or true on success.
1065 : : *
1066 : : * Note: this logic should generally match the backend's flatten_reloptions()
1067 : : * (in adt/ruleutils.c).
1068 : : */
1069 : : bool
1070 : 223 : appendReloptionsArray(PQExpBuffer buffer, const char *reloptions,
1071 : : const char *prefix, int encoding, bool std_strings)
1072 : : {
1073 : : char **options;
1074 : : int noptions;
1075 : : int i;
1076 : :
1077 [ - + ]: 223 : if (!parsePGArray(reloptions, &options, &noptions))
1078 : : {
1079 : 0 : free(options);
1080 : 0 : return false;
1081 : : }
1082 : :
1083 [ + + ]: 505 : for (i = 0; i < noptions; i++)
1084 : : {
1085 : 282 : char *option = options[i];
1086 : : char *name;
1087 : : char *separator;
1088 : : char *value;
1089 : :
1090 : : /*
1091 : : * Each array element should have the form name=value. If the "=" is
1092 : : * missing for some reason, treat it like an empty value.
1093 : : */
1094 : 282 : name = option;
1095 : 282 : separator = strchr(option, '=');
1096 [ + - ]: 282 : if (separator)
1097 : : {
1098 : 282 : *separator = '\0';
1099 : 282 : value = separator + 1;
1100 : : }
1101 : : else
1102 : 0 : value = "";
1103 : :
1104 [ + + ]: 282 : if (i > 0)
1105 : 59 : appendPQExpBufferStr(buffer, ", ");
1106 : 282 : appendPQExpBuffer(buffer, "%s%s=", prefix, fmtId(name));
1107 : :
1108 : : /*
1109 : : * In general we need to quote the value; but to avoid unnecessary
1110 : : * clutter, do not quote if it is an identifier that would not need
1111 : : * quoting. (We could also allow numbers, but that is a bit trickier
1112 : : * than it looks --- for example, are leading zeroes significant? We
1113 : : * don't want to assume very much here about what custom reloptions
1114 : : * might mean.)
1115 : : */
1116 [ + + ]: 282 : if (strcmp(fmtId(value), value) == 0)
1117 : 32 : appendPQExpBufferStr(buffer, value);
1118 : : else
1119 : 250 : appendStringLiteral(buffer, value, encoding, std_strings);
1120 : : }
1121 : :
1122 : 223 : free(options);
1123 : :
1124 : 223 : return true;
1125 : : }
1126 : :
1127 : :
1128 : : /*
1129 : : * processSQLNamePattern
1130 : : *
1131 : : * Scan a wildcard-pattern string and generate appropriate WHERE clauses
1132 : : * to limit the set of objects returned. The WHERE clauses are appended
1133 : : * to the already-partially-constructed query in buf. Returns whether
1134 : : * any clause was added.
1135 : : *
1136 : : * conn: connection query will be sent to (consulted for escaping rules).
1137 : : * buf: output parameter.
1138 : : * pattern: user-specified pattern option, or NULL if none ("*" is implied).
1139 : : * have_where: true if caller already emitted "WHERE" (clauses will be ANDed
1140 : : * onto the existing WHERE clause).
1141 : : * force_escape: always quote regexp special characters, even outside
1142 : : * double quotes (else they are quoted only between double quotes).
1143 : : * schemavar: name of query variable to match against a schema-name pattern.
1144 : : * Can be NULL if no schema.
1145 : : * namevar: name of query variable to match against an object-name pattern.
1146 : : * altnamevar: NULL, or name of an alternative variable to match against name.
1147 : : * visibilityrule: clause to use if we want to restrict to visible objects
1148 : : * (for example, "pg_catalog.pg_table_is_visible(p.oid)"). Can be NULL.
1149 : : * dbnamebuf: output parameter receiving the database name portion of the
1150 : : * pattern, if any. Can be NULL.
1151 : : * dotcnt: how many separators were parsed from the pattern, by reference.
1152 : : *
1153 : : * Formatting note: the text already present in buf should end with a newline.
1154 : : * The appended text, if any, will end with one too.
1155 : : */
1156 : : bool
1157 : 4870 : processSQLNamePattern(PGconn *conn, PQExpBuffer buf, const char *pattern,
1158 : : bool have_where, bool force_escape,
1159 : : const char *schemavar, const char *namevar,
1160 : : const char *altnamevar, const char *visibilityrule,
1161 : : PQExpBuffer dbnamebuf, int *dotcnt)
1162 : : {
1163 : : PQExpBufferData schemabuf;
1164 : : PQExpBufferData namebuf;
1165 : 4870 : bool added_clause = false;
1166 : : int dcnt;
1167 : :
1168 : : #define WHEREAND() \
1169 : : (appendPQExpBufferStr(buf, have_where ? " AND " : "WHERE "), \
1170 : : have_where = true, added_clause = true)
1171 : :
1172 [ + + ]: 4870 : if (dotcnt == NULL)
1173 : 8 : dotcnt = &dcnt;
1174 : 4870 : *dotcnt = 0;
1175 [ + + ]: 4870 : if (pattern == NULL)
1176 : : {
1177 : : /* Default: select all visible objects */
1178 [ + + ]: 340 : if (visibilityrule)
1179 : : {
1180 [ + + ]: 78 : WHEREAND();
1181 : 78 : appendPQExpBuffer(buf, "%s\n", visibilityrule);
1182 : : }
1183 : 340 : return added_clause;
1184 : : }
1185 : :
1186 : 4530 : initPQExpBuffer(&schemabuf);
1187 : 4530 : initPQExpBuffer(&namebuf);
1188 : :
1189 : : /*
1190 : : * Convert shell-style 'pattern' into the regular expression(s) we want to
1191 : : * execute. Quoting/escaping into SQL literal format will be done below
1192 : : * using appendStringLiteralConn().
1193 : : *
1194 : : * If the caller provided a schemavar, we want to split the pattern on
1195 : : * ".", otherwise not.
1196 : : */
1197 [ + + + + ]: 4530 : patternToSQLRegex(PQclientEncoding(conn),
1198 : : (schemavar ? dbnamebuf : NULL),
1199 : : (schemavar ? &schemabuf : NULL),
1200 : : &namebuf,
1201 : : pattern, force_escape, true, dotcnt);
1202 : :
1203 : : /*
1204 : : * Now decide what we need to emit. We may run under a hostile
1205 : : * search_path, so qualify EVERY name. Note there will be a leading "^("
1206 : : * in the patterns in any case.
1207 : : *
1208 : : * We want the regex matches to use the database's default collation where
1209 : : * collation-sensitive behavior is required (for example, which characters
1210 : : * match '\w'). That happened by default before PG v12, but if the server
1211 : : * is >= v12 then we need to force it through explicit COLLATE clauses,
1212 : : * otherwise the "C" collation attached to "name" catalog columns wins.
1213 : : */
1214 [ + - + - ]: 4530 : if (namevar && namebuf.len > 2)
1215 : : {
1216 : : /* We have a name pattern, so constrain the namevar(s) */
1217 : :
1218 : : /* Optimize away a "*" pattern */
1219 [ + + ]: 4530 : if (strcmp(namebuf.data, "^(.*)$") != 0)
1220 : : {
1221 [ + + ]: 4480 : WHEREAND();
1222 [ + + ]: 4480 : if (altnamevar)
1223 : : {
1224 : 152 : appendPQExpBuffer(buf,
1225 : : "(%s OPERATOR(pg_catalog.~) ", namevar);
1226 : 152 : appendStringLiteralConn(buf, namebuf.data, conn);
1227 [ + - ]: 152 : if (PQserverVersion(conn) >= 120000)
1228 : 152 : appendPQExpBufferStr(buf, " COLLATE pg_catalog.default");
1229 : 152 : appendPQExpBuffer(buf,
1230 : : "\n OR %s OPERATOR(pg_catalog.~) ",
1231 : : altnamevar);
1232 : 152 : appendStringLiteralConn(buf, namebuf.data, conn);
1233 [ + - ]: 152 : if (PQserverVersion(conn) >= 120000)
1234 : 152 : appendPQExpBufferStr(buf, " COLLATE pg_catalog.default");
1235 : 152 : appendPQExpBufferStr(buf, ")\n");
1236 : : }
1237 : : else
1238 : : {
1239 : 4328 : appendPQExpBuffer(buf, "%s OPERATOR(pg_catalog.~) ", namevar);
1240 : 4328 : appendStringLiteralConn(buf, namebuf.data, conn);
1241 [ + - ]: 4328 : if (PQserverVersion(conn) >= 120000)
1242 : 4328 : appendPQExpBufferStr(buf, " COLLATE pg_catalog.default");
1243 : 4328 : appendPQExpBufferChar(buf, '\n');
1244 : : }
1245 : : }
1246 : : }
1247 : :
1248 [ + + + + ]: 4530 : if (schemavar && schemabuf.len > 2)
1249 : : {
1250 : : /* We have a schema pattern, so constrain the schemavar */
1251 : :
1252 : : /* Optimize away a "*" pattern */
1253 [ + + + - ]: 1930 : if (strcmp(schemabuf.data, "^(.*)$") != 0 && schemavar)
1254 : : {
1255 [ + + ]: 963 : WHEREAND();
1256 : 963 : appendPQExpBuffer(buf, "%s OPERATOR(pg_catalog.~) ", schemavar);
1257 : 963 : appendStringLiteralConn(buf, schemabuf.data, conn);
1258 [ + - ]: 963 : if (PQserverVersion(conn) >= 120000)
1259 : 963 : appendPQExpBufferStr(buf, " COLLATE pg_catalog.default");
1260 : 963 : appendPQExpBufferChar(buf, '\n');
1261 : : }
1262 : : }
1263 : : else
1264 : : {
1265 : : /* No schema pattern given, so select only visible objects */
1266 [ + + ]: 3563 : if (visibilityrule)
1267 : : {
1268 [ + - ]: 2826 : WHEREAND();
1269 : 2826 : appendPQExpBuffer(buf, "%s\n", visibilityrule);
1270 : : }
1271 : : }
1272 : :
1273 : 4530 : termPQExpBuffer(&schemabuf);
1274 : 4530 : termPQExpBuffer(&namebuf);
1275 : :
1276 : 4530 : return added_clause;
1277 : : #undef WHEREAND
1278 : : }
1279 : :
1280 : : /*
1281 : : * Transform a possibly qualified shell-style object name pattern into up to
1282 : : * three SQL-style regular expressions, converting quotes, lower-casing
1283 : : * unquoted letters, and adjusting shell-style wildcard characters into regexp
1284 : : * notation.
1285 : : *
1286 : : * If the dbnamebuf and schemabuf arguments are non-NULL, and the pattern
1287 : : * contains two or more dbname/schema/name separators, we parse the portions of
1288 : : * the pattern prior to the first and second separators into dbnamebuf and
1289 : : * schemabuf, and the rest into namebuf.
1290 : : *
1291 : : * If dbnamebuf is NULL and schemabuf is non-NULL, and the pattern contains at
1292 : : * least one separator, we parse the first portion into schemabuf and the rest
1293 : : * into namebuf.
1294 : : *
1295 : : * Otherwise, we parse all the pattern into namebuf.
1296 : : *
1297 : : * If the pattern contains more dotted parts than buffers to parse into, the
1298 : : * extra dots will be treated as literal characters and written into the
1299 : : * namebuf, though they will be counted. Callers should always check the value
1300 : : * returned by reference in dotcnt and handle this error case appropriately.
1301 : : *
1302 : : * We surround the regexps with "^(...)$" to force them to match whole strings,
1303 : : * as per SQL practice. We have to have parens in case strings contain "|",
1304 : : * else the "^" and "$" will be bound into the first and last alternatives
1305 : : * which is not what we want. Whether this is done for dbnamebuf is controlled
1306 : : * by the want_literal_dbname parameter.
1307 : : *
1308 : : * The regexps we parse into the buffers are appended to the data (if any)
1309 : : * already present. If we parse fewer fields than the number of buffers we
1310 : : * were given, the extra buffers are unaltered.
1311 : : *
1312 : : * encoding: the character encoding for the given pattern
1313 : : * dbnamebuf: output parameter receiving the database name portion of the
1314 : : * pattern, if any. Can be NULL.
1315 : : * schemabuf: output parameter receiving the schema name portion of the
1316 : : * pattern, if any. Can be NULL.
1317 : : * namebuf: output parameter receiving the database name portion of the
1318 : : * pattern, if any. Can be NULL.
1319 : : * pattern: user-specified pattern option, or NULL if none ("*" is implied).
1320 : : * force_escape: always quote regexp special characters, even outside
1321 : : * double quotes (else they are quoted only between double quotes).
1322 : : * want_literal_dbname: if true, regexp special characters within the database
1323 : : * name portion of the pattern will not be escaped, nor will the dbname be
1324 : : * converted into a regular expression.
1325 : : * dotcnt: output parameter receiving the number of separators parsed from the
1326 : : * pattern.
1327 : : */
1328 : : void
1329 : 4632 : patternToSQLRegex(int encoding, PQExpBuffer dbnamebuf, PQExpBuffer schemabuf,
1330 : : PQExpBuffer namebuf, const char *pattern, bool force_escape,
1331 : : bool want_literal_dbname, int *dotcnt)
1332 : : {
1333 : : PQExpBufferData buf[3];
1334 : : PQExpBufferData left_literal;
1335 : : PQExpBuffer curbuf;
1336 : : PQExpBuffer maxbuf;
1337 : : int i;
1338 : : bool inquotes;
1339 : : bool left;
1340 : : const char *cp;
1341 : :
1342 : : Assert(pattern != NULL);
1343 : : Assert(namebuf != NULL);
1344 : :
1345 : : /* callers should never expect "dbname.relname" format */
1346 : : Assert(dbnamebuf == NULL || schemabuf != NULL);
1347 : : Assert(dotcnt != NULL);
1348 : :
1349 : 4632 : *dotcnt = 0;
1350 : 4632 : inquotes = false;
1351 : 4632 : cp = pattern;
1352 : :
1353 [ + + ]: 4632 : if (dbnamebuf != NULL)
1354 : 3844 : maxbuf = &buf[2];
1355 [ + + ]: 788 : else if (schemabuf != NULL)
1356 : 29 : maxbuf = &buf[1];
1357 : : else
1358 : 759 : maxbuf = &buf[0];
1359 : :
1360 : 4632 : curbuf = &buf[0];
1361 [ + + ]: 4632 : if (want_literal_dbname)
1362 : : {
1363 : 4530 : left = true;
1364 : 4530 : initPQExpBuffer(&left_literal);
1365 : : }
1366 : : else
1367 : 102 : left = false;
1368 : 4632 : initPQExpBuffer(curbuf);
1369 : 4632 : appendPQExpBufferStr(curbuf, "^(");
1370 [ + + ]: 82855 : while (*cp)
1371 : : {
1372 : 78223 : char ch = *cp;
1373 : :
1374 [ + + ]: 78223 : if (ch == '"')
1375 : : {
1376 [ + + + + ]: 2136 : if (inquotes && cp[1] == '"')
1377 : : {
1378 : : /* emit one quote, stay in inquotes mode */
1379 : 4 : appendPQExpBufferChar(curbuf, '"');
1380 [ + - ]: 4 : if (left)
1381 : 4 : appendPQExpBufferChar(&left_literal, '"');
1382 : 4 : cp++;
1383 : : }
1384 : : else
1385 : 2132 : inquotes = !inquotes;
1386 : 2136 : cp++;
1387 : : }
1388 [ + + + + ]: 76087 : else if (!inquotes && isupper((unsigned char) ch))
1389 : : {
1390 : 160 : appendPQExpBufferChar(curbuf,
1391 : 160 : pg_tolower((unsigned char) ch));
1392 [ + + ]: 160 : if (left)
1393 : 100 : appendPQExpBufferChar(&left_literal,
1394 : 100 : pg_tolower((unsigned char) ch));
1395 : 160 : cp++;
1396 : : }
1397 [ + + + + ]: 75927 : else if (!inquotes && ch == '*')
1398 : : {
1399 : 273 : appendPQExpBufferStr(curbuf, ".*");
1400 [ + + ]: 273 : if (left)
1401 : 213 : appendPQExpBufferChar(&left_literal, '*');
1402 : 273 : cp++;
1403 : : }
1404 [ + + + + ]: 75654 : else if (!inquotes && ch == '?')
1405 : : {
1406 : 4 : appendPQExpBufferChar(curbuf, '.');
1407 [ + - ]: 4 : if (left)
1408 : 4 : appendPQExpBufferChar(&left_literal, '?');
1409 : 4 : cp++;
1410 : : }
1411 [ + + + + ]: 75650 : else if (!inquotes && ch == '.')
1412 : : {
1413 : 1870 : left = false;
1414 [ + - ]: 1870 : if (dotcnt)
1415 : 1870 : (*dotcnt)++;
1416 [ + + ]: 1870 : if (curbuf < maxbuf)
1417 : : {
1418 : 1489 : appendPQExpBufferStr(curbuf, ")$");
1419 : 1489 : curbuf++;
1420 : 1489 : initPQExpBuffer(curbuf);
1421 : 1489 : appendPQExpBufferStr(curbuf, "^(");
1422 : 1489 : cp++;
1423 : : }
1424 : : else
1425 : 381 : appendPQExpBufferChar(curbuf, *cp++);
1426 : : }
1427 [ + + ]: 73780 : else if (ch == '$')
1428 : : {
1429 : : /*
1430 : : * Dollar is always quoted, whether inside quotes or not. The
1431 : : * reason is that it's allowed in SQL identifiers, so there's a
1432 : : * significant use-case for treating it literally, while because
1433 : : * we anchor the pattern automatically there is no use-case for
1434 : : * having it possess its regexp meaning.
1435 : : */
1436 : 8 : appendPQExpBufferStr(curbuf, "\\$");
1437 [ + - ]: 8 : if (left)
1438 : 8 : appendPQExpBufferChar(&left_literal, '$');
1439 : 8 : cp++;
1440 : : }
1441 : : else
1442 : : {
1443 : : /*
1444 : : * Ordinary data character, transfer to pattern
1445 : : *
1446 : : * Inside double quotes, or at all times if force_escape is true,
1447 : : * quote regexp special characters with a backslash to avoid
1448 : : * regexp errors. Outside quotes, however, let them pass through
1449 : : * as-is; this lets knowledgeable users build regexp expressions
1450 : : * that are more powerful than shell-style patterns.
1451 : : *
1452 : : * As an exception to that, though, always quote "[]", as that's
1453 : : * much more likely to be an attempt to write an array type name
1454 : : * than it is to be the start of a regexp bracket expression.
1455 : : */
1456 [ + + + + ]: 73772 : if ((inquotes || force_escape) &&
1457 [ + + ]: 19957 : strchr("|*+?()[]{}.^$\\", ch))
1458 : 2581 : appendPQExpBufferChar(curbuf, '\\');
1459 [ + + + + ]: 71191 : else if (ch == '[' && cp[1] == ']')
1460 : 4 : appendPQExpBufferChar(curbuf, '\\');
1461 : 73772 : i = PQmblenBounded(cp, encoding);
1462 [ + + ]: 147544 : while (i--)
1463 : : {
1464 [ + + ]: 73772 : if (left)
1465 : 51668 : appendPQExpBufferChar(&left_literal, *cp);
1466 : 73772 : appendPQExpBufferChar(curbuf, *cp++);
1467 : : }
1468 : : }
1469 : : }
1470 : 4632 : appendPQExpBufferStr(curbuf, ")$");
1471 : :
1472 [ + - ]: 4632 : if (namebuf)
1473 : : {
1474 : 4632 : appendPQExpBufferStr(namebuf, curbuf->data);
1475 : 4632 : termPQExpBuffer(curbuf);
1476 : 4632 : curbuf--;
1477 : : }
1478 : :
1479 [ + + + + ]: 4632 : if (schemabuf && curbuf >= buf)
1480 : : {
1481 : 993 : appendPQExpBufferStr(schemabuf, curbuf->data);
1482 : 993 : termPQExpBuffer(curbuf);
1483 : 993 : curbuf--;
1484 : : }
1485 : :
1486 [ + + + + ]: 4632 : if (dbnamebuf && curbuf >= buf)
1487 : : {
1488 [ + + ]: 496 : if (want_literal_dbname)
1489 : 479 : appendPQExpBufferStr(dbnamebuf, left_literal.data);
1490 : : else
1491 : 17 : appendPQExpBufferStr(dbnamebuf, curbuf->data);
1492 : 496 : termPQExpBuffer(curbuf);
1493 : : }
1494 : :
1495 [ + + ]: 4632 : if (want_literal_dbname)
1496 : 4530 : termPQExpBuffer(&left_literal);
1497 : 4632 : }
|