aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/parser/pg_wrapper/postgresql/src/backend/utils/mb/stringinfo_mb.c
blob: 67a958d72bee16f617c2d2bb06bb56b473fe53d4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*-------------------------------------------------------------------------
 *
 * stringinfo_mb.c
 *		Multibyte encoding-aware additional StringInfo facilities
 *
 * This is separate from common/stringinfo.c so that frontend users
 * of that file need not pull in unnecessary multibyte-encoding support
 * code.
 *
 *
 * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  src/backend/utils/mb/stringinfo_mb.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "mb/stringinfo_mb.h"
#include "mb/pg_wchar.h"


/*
 * appendStringInfoStringQuoted
 *
 * Append up to maxlen bytes from s to str, or the whole input string if
 * maxlen < 0, adding single quotes around it and doubling all single quotes.
 * Add an ellipsis if the copy is incomplete.
 */
void
appendStringInfoStringQuoted(StringInfo str, const char *s, int maxlen)
{
	char	   *copy = NULL;
	const char *chunk_search_start,
			   *chunk_copy_start,
			   *chunk_end;
	int			slen;
	bool		ellipsis;

	Assert(str != NULL);

	slen = strlen(s);
	if (maxlen >= 0 && maxlen < slen)
	{
		int			finallen = pg_mbcliplen(s, slen, maxlen);

		copy = pnstrdup(s, finallen);
		chunk_search_start = copy;
		chunk_copy_start = copy;

		ellipsis = true;
	}
	else
	{
		chunk_search_start = s;
		chunk_copy_start = s;

		ellipsis = false;
	}

	appendStringInfoCharMacro(str, '\'');

	while ((chunk_end = strchr(chunk_search_start, '\'')) != NULL)
	{
		/* copy including the found delimiting ' */
		appendBinaryStringInfoNT(str,
								 chunk_copy_start,
								 chunk_end - chunk_copy_start + 1);

		/* in order to double it, include this ' into the next chunk as well */
		chunk_copy_start = chunk_end;
		chunk_search_start = chunk_end + 1;
	}

	/* copy the last chunk and terminate */
	if (ellipsis)
		appendStringInfo(str, "%s...'", chunk_copy_start);
	else
		appendStringInfo(str, "%s'", chunk_copy_start);

	if (copy)
		pfree(copy);
}