Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * varlena.c
4 : : * Functions for the variable-length built-in types.
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/utils/adt/varlena.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include <ctype.h>
18 : : #include <limits.h>
19 : :
20 : : #include "access/detoast.h"
21 : : #include "access/toast_compression.h"
22 : : #include "access/tupmacs.h"
23 : : #include "catalog/pg_collation.h"
24 : : #include "catalog/pg_type.h"
25 : : #include "common/hashfn.h"
26 : : #include "common/int.h"
27 : : #include "common/unicode_category.h"
28 : : #include "common/unicode_norm.h"
29 : : #include "common/unicode_version.h"
30 : : #include "funcapi.h"
31 : : #include "lib/hyperloglog.h"
32 : : #include "libpq/pqformat.h"
33 : : #include "miscadmin.h"
34 : : #include "nodes/execnodes.h"
35 : : #include "parser/scansup.h"
36 : : #include "port/pg_bswap.h"
37 : : #include "regex/regex.h"
38 : : #include "utils/builtins.h"
39 : : #include "utils/guc.h"
40 : : #include "utils/lsyscache.h"
41 : : #include "utils/memutils.h"
42 : : #include "utils/pg_locale.h"
43 : : #include "utils/sortsupport.h"
44 : : #include "utils/tuplestore.h"
45 : : #include "utils/varlena.h"
46 : :
47 : : typedef varlena VarString;
48 : :
49 : : /*
50 : : * State for text_position_* functions.
51 : : */
52 : : typedef struct
53 : : {
54 : : pg_locale_t locale; /* collation used for substring matching */
55 : : bool is_multibyte_char_in_char; /* need to check char boundaries? */
56 : : bool greedy; /* find longest possible substring? */
57 : :
58 : : char *str1; /* haystack string */
59 : : char *str2; /* needle string */
60 : : int len1; /* string lengths in bytes */
61 : : int len2;
62 : :
63 : : /* Skip table for Boyer-Moore-Horspool search algorithm: */
64 : : int skiptablemask; /* mask for ANDing with skiptable subscripts */
65 : : int skiptable[256]; /* skip distance for given mismatched char */
66 : :
67 : : /*
68 : : * Note that with nondeterministic collations, the length of the last
69 : : * match is not necessarily equal to the length of the "needle" passed in.
70 : : */
71 : : char *last_match; /* pointer to last match in 'str1' */
72 : : int last_match_len; /* length of last match */
73 : : int last_match_len_tmp; /* same but for internal use */
74 : :
75 : : /*
76 : : * Sometimes we need to convert the byte position of a match to a
77 : : * character position. These store the last position that was converted,
78 : : * so that on the next call, we can continue from that point, rather than
79 : : * count characters from the very beginning.
80 : : */
81 : : char *refpoint; /* pointer within original haystack string */
82 : : int refpos; /* 0-based character offset of the same point */
83 : : } TextPositionState;
84 : :
85 : : typedef struct
86 : : {
87 : : char *buf1; /* 1st string, or abbreviation original string
88 : : * buf */
89 : : char *buf2; /* 2nd string, or abbreviation strxfrm() buf */
90 : : int buflen1; /* Allocated length of buf1 */
91 : : int buflen2; /* Allocated length of buf2 */
92 : : int last_len1; /* Length of last buf1 string/strxfrm() input */
93 : : int last_len2; /* Length of last buf2 string/strxfrm() blob */
94 : : int last_returned; /* Last comparison result (cache) */
95 : : bool cache_blob; /* Does buf2 contain strxfrm() blob, etc? */
96 : : bool collate_c;
97 : : Oid typid; /* Actual datatype (text/bpchar/name) */
98 : : hyperLogLogState abbr_card; /* Abbreviated key cardinality state */
99 : : hyperLogLogState full_card; /* Full key cardinality state */
100 : : double prop_card; /* Required cardinality proportion */
101 : : pg_locale_t locale;
102 : : } VarStringSortSupport;
103 : :
104 : : /*
105 : : * Output data for split_text(): we output either to an array or a table.
106 : : * tupstore and tupdesc must be set up in advance to output to a table.
107 : : */
108 : : typedef struct
109 : : {
110 : : ArrayBuildState *astate;
111 : : Tuplestorestate *tupstore;
112 : : TupleDesc tupdesc;
113 : : } SplitTextOutputData;
114 : :
115 : : /*
116 : : * This should be large enough that most strings will fit, but small enough
117 : : * that we feel comfortable putting it on the stack
118 : : */
119 : : #define TEXTBUFLEN 1024
120 : :
121 : : #define DatumGetVarStringP(X) ((VarString *) PG_DETOAST_DATUM(X))
122 : : #define DatumGetVarStringPP(X) ((VarString *) PG_DETOAST_DATUM_PACKED(X))
123 : :
124 : : static int varstrfastcmp_c(Datum x, Datum y, SortSupport ssup);
125 : : static int bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup);
126 : : static int namefastcmp_c(Datum x, Datum y, SortSupport ssup);
127 : : static int varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup);
128 : : static int namefastcmp_locale(Datum x, Datum y, SortSupport ssup);
129 : : static int varstrfastcmp_locale(char *a1p, int len1, char *a2p, int len2, SortSupport ssup);
130 : : static Datum varstr_abbrev_convert(Datum original, SortSupport ssup);
131 : : static bool varstr_abbrev_abort(int memtupcount, SortSupport ssup);
132 : : static int32 text_length(Datum str);
133 : : static text *text_catenate(text *t1, text *t2);
134 : : static text *text_substring(Datum str,
135 : : int32 start,
136 : : int32 length,
137 : : bool length_not_specified);
138 : : static int pg_mbcharcliplen_chars(const char *mbstr, int len, int limit);
139 : : static text *text_overlay(text *t1, text *t2, int sp, int sl);
140 : : static int text_position(text *t1, text *t2, Oid collid);
141 : : static void text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state);
142 : : static bool text_position_next(TextPositionState *state);
143 : : static char *text_position_next_internal(char *start_ptr, TextPositionState *state);
144 : : static char *text_position_get_match_ptr(TextPositionState *state);
145 : : static int text_position_get_match_pos(TextPositionState *state);
146 : : static void text_position_cleanup(TextPositionState *state);
147 : : static void check_collation_set(Oid collid);
148 : : static int text_cmp(text *arg1, text *arg2, Oid collid);
149 : : static void appendStringInfoText(StringInfo str, const text *t);
150 : : static bool split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate);
151 : : static void split_text_accum_result(SplitTextOutputData *tstate,
152 : : text *field_value,
153 : : text *null_string,
154 : : Oid collation);
155 : : static text *array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v,
156 : : const char *fldsep, const char *null_string);
157 : : static StringInfo makeStringAggState(FunctionCallInfo fcinfo);
158 : : static bool text_format_parse_digits(const char **ptr, const char *end_ptr,
159 : : int *value);
160 : : static const char *text_format_parse_format(const char *start_ptr,
161 : : const char *end_ptr,
162 : : int *argpos, int *widthpos,
163 : : int *flags, int *width);
164 : : static void text_format_string_conversion(StringInfo buf, char conversion,
165 : : FmgrInfo *typOutputInfo,
166 : : Datum value, bool isNull,
167 : : int flags, int width);
168 : : static void text_format_append_string(StringInfo buf, const char *str,
169 : : int flags, int width);
170 : :
171 : :
172 : : /*****************************************************************************
173 : : * CONVERSION ROUTINES EXPORTED FOR USE BY C CODE *
174 : : *****************************************************************************/
175 : :
176 : : /*
177 : : * cstring_to_text
178 : : *
179 : : * Create a text value from a null-terminated C string.
180 : : *
181 : : * The new text value is freshly palloc'd with a full-size VARHDR.
182 : : */
183 : : text *
184 : 16064997 : cstring_to_text(const char *s)
185 : : {
186 : 16064997 : return cstring_to_text_with_len(s, strlen(s));
187 : : }
188 : :
189 : : /*
190 : : * cstring_to_text_with_len
191 : : *
192 : : * Same as cstring_to_text except the caller specifies the string length;
193 : : * the string need not be null_terminated.
194 : : */
195 : : text *
196 : 17611690 : cstring_to_text_with_len(const char *s, int len)
197 : : {
198 : 17611690 : text *result = (text *) palloc(len + VARHDRSZ);
199 : :
200 : 17611690 : SET_VARSIZE(result, len + VARHDRSZ);
201 : 17611690 : memcpy(VARDATA(result), s, len);
202 : :
203 : 17611690 : return result;
204 : : }
205 : :
206 : : /*
207 : : * text_to_cstring
208 : : *
209 : : * Create a palloc'd, null-terminated C string from a text value.
210 : : *
211 : : * We support being passed a compressed or toasted text value.
212 : : * This is a bit bogus since such values shouldn't really be referred to as
213 : : * "text *", but it seems useful for robustness. If we didn't handle that
214 : : * case here, we'd need another routine that did, anyway.
215 : : */
216 : : char *
217 : 10376484 : text_to_cstring(const text *t)
218 : : {
219 : : /* must cast away the const, unfortunately */
220 : 10376484 : text *tunpacked = pg_detoast_datum_packed(unconstify(text *, t));
221 : 10376484 : int len = VARSIZE_ANY_EXHDR(tunpacked);
222 : : char *result;
223 : :
224 : 10376484 : result = (char *) palloc(len + 1);
225 : 10376484 : memcpy(result, VARDATA_ANY(tunpacked), len);
226 : 10376484 : result[len] = '\0';
227 : :
228 [ + + ]: 10376484 : if (tunpacked != t)
229 : 28655 : pfree(tunpacked);
230 : :
231 : 10376484 : return result;
232 : : }
233 : :
234 : : /*
235 : : * text_to_cstring_buffer
236 : : *
237 : : * Copy a text value into a caller-supplied buffer of size dst_len.
238 : : *
239 : : * The text string is truncated if necessary to fit. The result is
240 : : * guaranteed null-terminated (unless dst_len == 0).
241 : : *
242 : : * We support being passed a compressed or toasted text value.
243 : : * This is a bit bogus since such values shouldn't really be referred to as
244 : : * "text *", but it seems useful for robustness. If we didn't handle that
245 : : * case here, we'd need another routine that did, anyway.
246 : : */
247 : : void
248 : 727 : text_to_cstring_buffer(const text *src, char *dst, size_t dst_len)
249 : : {
250 : : /* must cast away the const, unfortunately */
251 : 727 : text *srcunpacked = pg_detoast_datum_packed(unconstify(text *, src));
252 : 727 : size_t src_len = VARSIZE_ANY_EXHDR(srcunpacked);
253 : :
254 [ + - ]: 727 : if (dst_len > 0)
255 : : {
256 : 727 : dst_len--;
257 [ + - ]: 727 : if (dst_len >= src_len)
258 : 727 : dst_len = src_len;
259 : : else /* ensure truncation is encoding-safe */
260 : 0 : dst_len = pg_mbcliplen(VARDATA_ANY(srcunpacked), src_len, dst_len);
261 : 727 : memcpy(dst, VARDATA_ANY(srcunpacked), dst_len);
262 : 727 : dst[dst_len] = '\0';
263 : : }
264 : :
265 [ - + ]: 727 : if (srcunpacked != src)
266 : 0 : pfree(srcunpacked);
267 : 727 : }
268 : :
269 : :
270 : : /*****************************************************************************
271 : : * USER I/O ROUTINES *
272 : : *****************************************************************************/
273 : :
274 : : /*
275 : : * textin - converts cstring to internal representation
276 : : */
277 : : Datum
278 : 13758161 : textin(PG_FUNCTION_ARGS)
279 : : {
280 : 13758161 : char *inputText = PG_GETARG_CSTRING(0);
281 : :
282 : 13758161 : PG_RETURN_TEXT_P(cstring_to_text(inputText));
283 : : }
284 : :
285 : : /*
286 : : * textout - converts internal representation to cstring
287 : : */
288 : : Datum
289 : 4445659 : textout(PG_FUNCTION_ARGS)
290 : : {
291 : 4445659 : Datum txt = PG_GETARG_DATUM(0);
292 : :
293 : 4445659 : PG_RETURN_CSTRING(TextDatumGetCString(txt));
294 : : }
295 : :
296 : : /*
297 : : * textrecv - converts external binary format to text
298 : : */
299 : : Datum
300 : 27 : textrecv(PG_FUNCTION_ARGS)
301 : : {
302 : 27 : StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
303 : : text *result;
304 : : char *str;
305 : : int nbytes;
306 : :
307 : 27 : str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
308 : :
309 : 27 : result = cstring_to_text_with_len(str, nbytes);
310 : 27 : pfree(str);
311 : 27 : PG_RETURN_TEXT_P(result);
312 : : }
313 : :
314 : : /*
315 : : * textsend - converts text to binary format
316 : : */
317 : : Datum
318 : 2949 : textsend(PG_FUNCTION_ARGS)
319 : : {
320 : 2949 : text *t = PG_GETARG_TEXT_PP(0);
321 : : StringInfoData buf;
322 : :
323 : 2949 : pq_begintypsend(&buf);
324 : 2949 : pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
325 : 2949 : PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
326 : : }
327 : :
328 : :
329 : : /*
330 : : * unknownin - converts cstring to internal representation
331 : : */
332 : : Datum
333 : 0 : unknownin(PG_FUNCTION_ARGS)
334 : : {
335 : 0 : char *str = PG_GETARG_CSTRING(0);
336 : :
337 : : /* representation is same as cstring */
338 : 0 : PG_RETURN_CSTRING(pstrdup(str));
339 : : }
340 : :
341 : : /*
342 : : * unknownout - converts internal representation to cstring
343 : : */
344 : : Datum
345 : 700 : unknownout(PG_FUNCTION_ARGS)
346 : : {
347 : : /* representation is same as cstring */
348 : 700 : char *str = PG_GETARG_CSTRING(0);
349 : :
350 : 700 : PG_RETURN_CSTRING(pstrdup(str));
351 : : }
352 : :
353 : : /*
354 : : * unknownrecv - converts external binary format to unknown
355 : : */
356 : : Datum
357 : 0 : unknownrecv(PG_FUNCTION_ARGS)
358 : : {
359 : 0 : StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
360 : : char *str;
361 : : int nbytes;
362 : :
363 : 0 : str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
364 : : /* representation is same as cstring */
365 : 0 : PG_RETURN_CSTRING(str);
366 : : }
367 : :
368 : : /*
369 : : * unknownsend - converts unknown to binary format
370 : : */
371 : : Datum
372 : 0 : unknownsend(PG_FUNCTION_ARGS)
373 : : {
374 : : /* representation is same as cstring */
375 : 0 : char *str = PG_GETARG_CSTRING(0);
376 : : StringInfoData buf;
377 : :
378 : 0 : pq_begintypsend(&buf);
379 : 0 : pq_sendtext(&buf, str, strlen(str));
380 : 0 : PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
381 : : }
382 : :
383 : :
384 : : /* ========== PUBLIC ROUTINES ========== */
385 : :
386 : : /*
387 : : * textlen -
388 : : * returns the logical length of a text*
389 : : * (which is less than the VARSIZE of the text*)
390 : : */
391 : : Datum
392 : 286169 : textlen(PG_FUNCTION_ARGS)
393 : : {
394 : 286169 : Datum str = PG_GETARG_DATUM(0);
395 : :
396 : : /* try to avoid decompressing argument */
397 : 286169 : PG_RETURN_INT32(text_length(str));
398 : : }
399 : :
400 : : /*
401 : : * text_length -
402 : : * Does the real work for textlen()
403 : : *
404 : : * This is broken out so it can be called directly by other string processing
405 : : * functions. Note that the argument is passed as a Datum, to indicate that
406 : : * it may still be in compressed form. We can avoid decompressing it at all
407 : : * in some cases.
408 : : */
409 : : static int32
410 : 286179 : text_length(Datum str)
411 : : {
412 : : /* fastpath when max encoding length is one */
413 [ + + ]: 286179 : if (pg_database_encoding_max_length() == 1)
414 : 10 : return (toast_raw_datum_size(str) - VARHDRSZ);
415 : : else
416 : : {
417 : 286169 : text *t = DatumGetTextPP(str);
418 : :
419 : 286169 : return (pg_mbstrlen_with_len(VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t)));
420 : : }
421 : : }
422 : :
423 : : /*
424 : : * textoctetlen -
425 : : * returns the physical length of a text*
426 : : * (which is less than the VARSIZE of the text*)
427 : : */
428 : : Datum
429 : 45 : textoctetlen(PG_FUNCTION_ARGS)
430 : : {
431 : 45 : Datum str = PG_GETARG_DATUM(0);
432 : :
433 : : /* We need not detoast the input at all */
434 : 45 : PG_RETURN_INT32(toast_raw_datum_size(str) - VARHDRSZ);
435 : : }
436 : :
437 : : /*
438 : : * textcat -
439 : : * takes two text* and returns a text* that is the concatenation of
440 : : * the two.
441 : : *
442 : : * Rewritten by Sapa, sapa@hq.icb.chel.su. 8-Jul-96.
443 : : * Updated by Thomas, Thomas.Lockhart@jpl.nasa.gov 1997-07-10.
444 : : * Allocate space for output in all cases.
445 : : * XXX - thomas 1997-07-10
446 : : */
447 : : Datum
448 : 1378114 : textcat(PG_FUNCTION_ARGS)
449 : : {
450 : 1378114 : text *t1 = PG_GETARG_TEXT_PP(0);
451 : 1378114 : text *t2 = PG_GETARG_TEXT_PP(1);
452 : :
453 : 1378114 : PG_RETURN_TEXT_P(text_catenate(t1, t2));
454 : : }
455 : :
456 : : /*
457 : : * text_catenate
458 : : * Guts of textcat(), broken out so it can be used by other functions
459 : : *
460 : : * Arguments can be in short-header form, but not compressed or out-of-line
461 : : */
462 : : static text *
463 : 1378170 : text_catenate(text *t1, text *t2)
464 : : {
465 : : text *result;
466 : : int len1,
467 : : len2,
468 : : len;
469 : : char *ptr;
470 : :
471 : 1378170 : len1 = VARSIZE_ANY_EXHDR(t1);
472 : 1378170 : len2 = VARSIZE_ANY_EXHDR(t2);
473 : :
474 : : /* paranoia ... probably should throw error instead? */
475 [ - + ]: 1378170 : if (len1 < 0)
476 : 0 : len1 = 0;
477 [ - + ]: 1378170 : if (len2 < 0)
478 : 0 : len2 = 0;
479 : :
480 : 1378170 : len = len1 + len2 + VARHDRSZ;
481 : 1378170 : result = (text *) palloc(len);
482 : :
483 : : /* Set size of result string... */
484 : 1378170 : SET_VARSIZE(result, len);
485 : :
486 : : /* Fill data field of result string... */
487 : 1378170 : ptr = VARDATA(result);
488 [ + + ]: 1378170 : if (len1 > 0)
489 : 1376057 : memcpy(ptr, VARDATA_ANY(t1), len1);
490 [ + + ]: 1378170 : if (len2 > 0)
491 : 1378029 : memcpy(ptr + len1, VARDATA_ANY(t2), len2);
492 : :
493 : 1378170 : return result;
494 : : }
495 : :
496 : : /*
497 : : * charlen_to_bytelen()
498 : : * Compute the number of bytes occupied by n characters starting at *p
499 : : *
500 : : * The caller shall ensure there are n complete characters. Callers achieve
501 : : * this by deriving "n" from regmatch_t findings from searching a wchar array.
502 : : * pg_mb2wchar_with_len() skips any trailing incomplete character, so regex
503 : : * matches will end no later than the last complete character. (The string
504 : : * need not be null-terminated.)
505 : : */
506 : : static int
507 : 11694 : charlen_to_bytelen(const char *p, int n)
508 : : {
509 [ + + ]: 11694 : if (pg_database_encoding_max_length() == 1)
510 : : {
511 : : /* Optimization for single-byte encodings */
512 : 90 : return n;
513 : : }
514 : : else
515 : : {
516 : : const char *s;
517 : :
518 [ + + ]: 3899949 : for (s = p; n > 0; n--)
519 : 3888345 : s += pg_mblen_unbounded(s); /* caller verified encoding */
520 : :
521 : 11604 : return s - p;
522 : : }
523 : : }
524 : :
525 : : /*
526 : : * text_substr()
527 : : * Return a substring starting at the specified position.
528 : : * - thomas 1997-12-31
529 : : *
530 : : * Input:
531 : : * - string
532 : : * - starting position (is one-based)
533 : : * - string length
534 : : *
535 : : * If the starting position is zero or less, then return from the start of the string
536 : : * adjusting the length to be consistent with the "negative start" per SQL.
537 : : * If the length is less than zero, return the remaining string.
538 : : *
539 : : * Added multibyte support.
540 : : * - Tatsuo Ishii 1998-4-21
541 : : * Changed behavior if starting position is less than one to conform to SQL behavior.
542 : : * Formerly returned the entire string; now returns a portion.
543 : : * - Thomas Lockhart 1998-12-10
544 : : * Now uses faster TOAST-slicing interface
545 : : * - John Gray 2002-02-22
546 : : * Remove "#ifdef MULTIBYTE" and test for encoding_max_length instead. Change
547 : : * behaviors conflicting with SQL to meet SQL (if E = S + L < S throw
548 : : * error; if E < 1, return '', not entire string). Fixed MB related bug when
549 : : * S > LC and < LC + 4 sometimes garbage characters are returned.
550 : : * - Joe Conway 2002-08-10
551 : : */
552 : : Datum
553 : 369874 : text_substr(PG_FUNCTION_ARGS)
554 : : {
555 : 369874 : PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0),
556 : : PG_GETARG_INT32(1),
557 : : PG_GETARG_INT32(2),
558 : : false));
559 : : }
560 : :
561 : : /*
562 : : * text_substr_no_len -
563 : : * Wrapper to avoid opr_sanity failure due to
564 : : * one function accepting a different number of args.
565 : : */
566 : : Datum
567 : 64 : text_substr_no_len(PG_FUNCTION_ARGS)
568 : : {
569 : 64 : PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0),
570 : : PG_GETARG_INT32(1),
571 : : -1, true));
572 : : }
573 : :
574 : : /*
575 : : * text_substring -
576 : : * Does the real work for text_substr() and text_substr_no_len()
577 : : *
578 : : * This is broken out so it can be called directly by other string processing
579 : : * functions. Note that the argument is passed as a Datum, to indicate that
580 : : * it may still be in compressed/toasted form. We can avoid detoasting all
581 : : * of it in some cases.
582 : : *
583 : : * The result is always a freshly palloc'd datum.
584 : : */
585 : : static text *
586 : 396682 : text_substring(Datum str, int32 start, int32 length, bool length_not_specified)
587 : : {
588 : 396682 : int32 eml = pg_database_encoding_max_length();
589 : 396682 : int32 S = start; /* start position */
590 : : int32 S1; /* adjusted start position */
591 : : int32 L1; /* adjusted substring length */
592 : : int32 E; /* end position, exclusive */
593 : :
594 : : /*
595 : : * SQL99 says S can be zero or negative (which we don't document), but we
596 : : * still must fetch from the start of the string.
597 : : * https://www.postgresql.org/message-id/170905442373.643.11536838320909376197%40wrigleys.postgresql.org
598 : : */
599 : 396682 : S1 = Max(S, 1);
600 : :
601 : : /* life is easy if the encoding max length is 1 */
602 [ + + ]: 396682 : if (eml == 1)
603 : : {
604 [ - + ]: 11 : if (length_not_specified) /* special case - get length to end of
605 : : * string */
606 : 0 : L1 = -1;
607 [ - + ]: 11 : else if (length < 0)
608 : : {
609 : : /* SQL99 says to throw an error for E < S, i.e., negative length */
610 [ # # ]: 0 : ereport(ERROR,
611 : : (errcode(ERRCODE_SUBSTRING_ERROR),
612 : : errmsg("negative substring length not allowed")));
613 : : L1 = -1; /* silence stupider compilers */
614 : : }
615 [ - + ]: 11 : else if (pg_add_s32_overflow(S, length, &E))
616 : : {
617 : : /*
618 : : * L could be large enough for S + L to overflow, in which case
619 : : * the substring must run to end of string.
620 : : */
621 : 0 : L1 = -1;
622 : : }
623 : : else
624 : : {
625 : : /*
626 : : * A zero or negative value for the end position can happen if the
627 : : * start was negative or one. SQL99 says to return a zero-length
628 : : * string.
629 : : */
630 [ - + ]: 11 : if (E < 1)
631 : 0 : return cstring_to_text("");
632 : :
633 : 11 : L1 = E - S1;
634 : : }
635 : :
636 : : /*
637 : : * If the start position is past the end of the string, SQL99 says to
638 : : * return a zero-length string -- DatumGetTextPSlice() will do that
639 : : * for us. We need only convert S1 to zero-based starting position.
640 : : */
641 : 11 : return DatumGetTextPSlice(str, S1 - 1, L1);
642 : : }
643 [ + - ]: 396671 : else if (eml > 1)
644 : : {
645 : : /*
646 : : * When encoding max length is > 1, we can't get LC without
647 : : * detoasting, so we'll grab a conservatively large slice now and go
648 : : * back later to do the right thing
649 : : */
650 : : int32 slice_start;
651 : : int32 slice_size;
652 : : int32 slice_strlen;
653 : : int32 slice_len;
654 : : text *slice;
655 : : int32 E1;
656 : : int32 i;
657 : : char *p;
658 : : char *s;
659 : : text *ret;
660 : :
661 : : /*
662 : : * We need to start at position zero because there is no way to know
663 : : * in advance which byte offset corresponds to the supplied start
664 : : * position.
665 : : */
666 : 396671 : slice_start = 0;
667 : :
668 [ + + ]: 396671 : if (length_not_specified) /* special case - get length to end of
669 : : * string */
670 : 92 : E = slice_size = L1 = -1;
671 [ + + ]: 396579 : else if (length < 0)
672 : : {
673 : : /* SQL99 says to throw an error for E < S, i.e., negative length */
674 [ + - ]: 12 : ereport(ERROR,
675 : : (errcode(ERRCODE_SUBSTRING_ERROR),
676 : : errmsg("negative substring length not allowed")));
677 : : E = slice_size = L1 = -1; /* silence stupider compilers */
678 : : }
679 [ + + ]: 396567 : else if (pg_add_s32_overflow(S, length, &E))
680 : : {
681 : : /*
682 : : * L could be large enough for S + L to overflow, in which case
683 : : * the substring must run to end of string.
684 : : */
685 : 5 : slice_size = L1 = -1;
686 : : }
687 : : else
688 : : {
689 : : /*
690 : : * Ending at position 1, exclusive, obviously yields an empty
691 : : * string. A zero or negative value can happen if the start was
692 : : * negative or one. SQL99 says to return a zero-length string.
693 : : */
694 [ + + ]: 396562 : if (E <= 1)
695 : 8 : return cstring_to_text("");
696 : :
697 : : /*
698 : : * if E is past the end of the string, the tuple toaster will
699 : : * truncate the length for us
700 : : */
701 : 396554 : L1 = E - S1;
702 : :
703 : : /*
704 : : * Total slice size in bytes can't be any longer than the
705 : : * inclusive end position times the encoding max length. If that
706 : : * overflows, we can just use -1.
707 : : */
708 [ + + ]: 396554 : if (pg_mul_s32_overflow(E - 1, eml, &slice_size))
709 : 5 : slice_size = -1;
710 : : }
711 : :
712 : : /*
713 : : * If we're working with an untoasted source, no need to do an extra
714 : : * copying step.
715 : : */
716 [ + + + + ]: 793190 : if (VARATT_IS_COMPRESSED(DatumGetPointer(str)) ||
717 : 396539 : VARATT_IS_EXTERNAL(DatumGetPointer(str)))
718 : 312 : slice = DatumGetTextPSlice(str, slice_start, slice_size);
719 : : else
720 : 396339 : slice = (text *) DatumGetPointer(str);
721 : :
722 : : /* see if we got back an empty string */
723 : 396651 : slice_len = VARSIZE_ANY_EXHDR(slice);
724 [ - + ]: 396651 : if (slice_len == 0)
725 : : {
726 [ # # ]: 0 : if (slice != (text *) DatumGetPointer(str))
727 : 0 : pfree(slice);
728 : 0 : return cstring_to_text("");
729 : : }
730 : :
731 : : /*
732 : : * Now we can get the actual length of the slice in MB characters,
733 : : * stopping at the end of the substring. Continuing beyond the
734 : : * substring end could find an incomplete character attributable
735 : : * solely to DatumGetTextPSlice() chopping in the middle of a
736 : : * character, and it would be superfluous work at best.
737 : : */
738 : 396643 : slice_strlen =
739 : 396651 : (slice_size == -1 ?
740 [ + + ]: 396651 : pg_mbstrlen_with_len(VARDATA_ANY(slice), slice_len) :
741 : 396549 : pg_mbcharcliplen_chars(VARDATA_ANY(slice), slice_len, E - 1));
742 : :
743 : : /*
744 : : * Check that the start position wasn't > slice_strlen. If so, SQL99
745 : : * says to return a zero-length string.
746 : : */
747 [ + + ]: 396643 : if (S1 > slice_strlen)
748 : : {
749 [ + + ]: 25 : if (slice != (text *) DatumGetPointer(str))
750 : 4 : pfree(slice);
751 : 25 : return cstring_to_text("");
752 : : }
753 : :
754 : : /*
755 : : * Adjust L1 and E1 now that we know the slice string length. Again
756 : : * remember that S1 is one based, and slice_start is zero based.
757 : : */
758 [ + + ]: 396618 : if (L1 > -1)
759 : 396534 : E1 = Min(S1 + L1, slice_start + 1 + slice_strlen);
760 : : else
761 : 84 : E1 = slice_start + 1 + slice_strlen;
762 : :
763 : : /*
764 : : * Find the start position in the slice; remember S1 is not zero based
765 : : */
766 : 396618 : p = VARDATA_ANY(slice);
767 [ + + ]: 9837384 : for (i = 0; i < S1 - 1; i++)
768 : 9440766 : p += pg_mblen_unbounded(p);
769 : :
770 : : /* hang onto a pointer to our start position */
771 : 396618 : s = p;
772 : :
773 : : /*
774 : : * Count the actual bytes used by the substring of the requested
775 : : * length.
776 : : */
777 [ + + ]: 6237269 : for (i = S1; i < E1; i++)
778 : 5840651 : p += pg_mblen_unbounded(p);
779 : :
780 : 396618 : ret = (text *) palloc(VARHDRSZ + (p - s));
781 : 396618 : SET_VARSIZE(ret, VARHDRSZ + (p - s));
782 : 396618 : memcpy(VARDATA(ret), s, (p - s));
783 : :
784 [ + + ]: 396618 : if (slice != (text *) DatumGetPointer(str))
785 : 304 : pfree(slice);
786 : :
787 : 396618 : return ret;
788 : : }
789 : : else
790 [ # # ]: 0 : elog(ERROR, "invalid backend encoding: encoding max length < 1");
791 : :
792 : : /* not reached: suppress compiler warning */
793 : : return NULL;
794 : : }
795 : :
796 : : /*
797 : : * pg_mbcharcliplen_chars -
798 : : * Mirror pg_mbcharcliplen(), except return value unit is chars, not bytes.
799 : : *
800 : : * This mirrors all the dubious historical behavior, so it's static to
801 : : * discourage proliferation. The assertions are specific to the one caller.
802 : : */
803 : : static int
804 : 396549 : pg_mbcharcliplen_chars(const char *mbstr, int len, int limit)
805 : : {
806 : 396549 : int nch = 0;
807 : : int l;
808 : :
809 : : Assert(len > 0);
810 : : Assert(limit > 0);
811 : : Assert(pg_database_encoding_max_length() > 1);
812 : :
813 [ + + + + ]: 9713595 : while (len > 0 && *mbstr)
814 : : {
815 : 9713242 : l = pg_mblen_with_len(mbstr, len);
816 : 9713234 : nch++;
817 [ + + ]: 9713234 : if (nch == limit)
818 : 396188 : break;
819 : 9317046 : len -= l;
820 : 9317046 : mbstr += l;
821 : : }
822 : 396541 : return nch;
823 : : }
824 : :
825 : : /*
826 : : * textoverlay
827 : : * Replace specified substring of first string with second
828 : : *
829 : : * The SQL standard defines OVERLAY() in terms of substring and concatenation.
830 : : * This code is a direct implementation of what the standard says.
831 : : */
832 : : Datum
833 : 18 : textoverlay(PG_FUNCTION_ARGS)
834 : : {
835 : 18 : text *t1 = PG_GETARG_TEXT_PP(0);
836 : 18 : text *t2 = PG_GETARG_TEXT_PP(1);
837 : 18 : int sp = PG_GETARG_INT32(2); /* substring start position */
838 : 18 : int sl = PG_GETARG_INT32(3); /* substring length */
839 : :
840 : 18 : PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl));
841 : : }
842 : :
843 : : Datum
844 : 10 : textoverlay_no_len(PG_FUNCTION_ARGS)
845 : : {
846 : 10 : text *t1 = PG_GETARG_TEXT_PP(0);
847 : 10 : text *t2 = PG_GETARG_TEXT_PP(1);
848 : 10 : int sp = PG_GETARG_INT32(2); /* substring start position */
849 : : int sl;
850 : :
851 : 10 : sl = text_length(PointerGetDatum(t2)); /* defaults to length(t2) */
852 : 10 : PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl));
853 : : }
854 : :
855 : : static text *
856 : 28 : text_overlay(text *t1, text *t2, int sp, int sl)
857 : : {
858 : : text *result;
859 : : text *s1;
860 : : text *s2;
861 : : int sp_pl_sl;
862 : :
863 : : /*
864 : : * Check for possible integer-overflow cases. For negative sp, throw a
865 : : * "substring length" error because that's what should be expected
866 : : * according to the spec's definition of OVERLAY().
867 : : */
868 [ - + ]: 28 : if (sp <= 0)
869 [ # # ]: 0 : ereport(ERROR,
870 : : (errcode(ERRCODE_SUBSTRING_ERROR),
871 : : errmsg("negative substring length not allowed")));
872 [ - + ]: 28 : if (pg_add_s32_overflow(sp, sl, &sp_pl_sl))
873 [ # # ]: 0 : ereport(ERROR,
874 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
875 : : errmsg("integer out of range")));
876 : :
877 : 28 : s1 = text_substring(PointerGetDatum(t1), 1, sp - 1, false);
878 : 28 : s2 = text_substring(PointerGetDatum(t1), sp_pl_sl, -1, true);
879 : 28 : result = text_catenate(s1, t2);
880 : 28 : result = text_catenate(result, s2);
881 : :
882 : 28 : return result;
883 : : }
884 : :
885 : : /*
886 : : * textpos -
887 : : * Return the position of the specified substring.
888 : : * Implements the SQL POSITION() function.
889 : : * Ref: A Guide To The SQL Standard, Date & Darwen, 1997
890 : : * - thomas 1997-07-27
891 : : */
892 : : Datum
893 : 87 : textpos(PG_FUNCTION_ARGS)
894 : : {
895 : 87 : text *str = PG_GETARG_TEXT_PP(0);
896 : 87 : text *search_str = PG_GETARG_TEXT_PP(1);
897 : :
898 : 87 : PG_RETURN_INT32((int32) text_position(str, search_str, PG_GET_COLLATION()));
899 : : }
900 : :
901 : : /*
902 : : * text_position -
903 : : * Does the real work for textpos()
904 : : *
905 : : * Inputs:
906 : : * t1 - string to be searched
907 : : * t2 - pattern to match within t1
908 : : * Result:
909 : : * Character index of the first matched char, starting from 1,
910 : : * or 0 if no match.
911 : : *
912 : : * This is broken out so it can be called directly by other string processing
913 : : * functions.
914 : : */
915 : : static int
916 : 87 : text_position(text *t1, text *t2, Oid collid)
917 : : {
918 : : TextPositionState state;
919 : : int result;
920 : :
921 : 87 : check_collation_set(collid);
922 : :
923 : : /* Empty needle always matches at position 1 */
924 [ + + ]: 87 : if (VARSIZE_ANY_EXHDR(t2) < 1)
925 : 10 : return 1;
926 : :
927 : : /* Otherwise, can't match if haystack is shorter than needle */
928 [ + + ]: 77 : if (VARSIZE_ANY_EXHDR(t1) < VARSIZE_ANY_EXHDR(t2) &&
929 [ + - ]: 13 : pg_newlocale_from_collation(collid)->deterministic)
930 : 13 : return 0;
931 : :
932 : 64 : text_position_setup(t1, t2, collid, &state);
933 : : /* don't need greedy mode here */
934 : 64 : state.greedy = false;
935 : :
936 [ + + ]: 64 : if (!text_position_next(&state))
937 : 14 : result = 0;
938 : : else
939 : 50 : result = text_position_get_match_pos(&state);
940 : 64 : text_position_cleanup(&state);
941 : 64 : return result;
942 : : }
943 : :
944 : :
945 : : /*
946 : : * text_position_setup, text_position_next, text_position_cleanup -
947 : : * Component steps of text_position()
948 : : *
949 : : * These are broken out so that a string can be efficiently searched for
950 : : * multiple occurrences of the same pattern. text_position_next may be
951 : : * called multiple times, and it advances to the next match on each call.
952 : : * text_position_get_match_ptr() and text_position_get_match_pos() return
953 : : * a pointer or 1-based character position of the last match, respectively.
954 : : *
955 : : * The "state" variable is normally just a local variable in the caller.
956 : : *
957 : : * NOTE: text_position_next skips over the matched portion. For example,
958 : : * searching for "xx" in "xxx" returns only one match, not two.
959 : : */
960 : :
961 : : static void
962 : 1245 : text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state)
963 : : {
964 : 1245 : int len1 = VARSIZE_ANY_EXHDR(t1);
965 : 1245 : int len2 = VARSIZE_ANY_EXHDR(t2);
966 : :
967 : 1245 : check_collation_set(collid);
968 : :
969 : 1245 : state->locale = pg_newlocale_from_collation(collid);
970 : :
971 : : /*
972 : : * Most callers need greedy mode, but some might want to unset this to
973 : : * optimize.
974 : : */
975 : 1245 : state->greedy = true;
976 : :
977 : : Assert(len2 > 0);
978 : :
979 : : /*
980 : : * Even with a multi-byte encoding, we perform the search using the raw
981 : : * byte sequence, ignoring multibyte issues. For UTF-8, that works fine,
982 : : * because in UTF-8 the byte sequence of one character cannot contain
983 : : * another character. For other multi-byte encodings, we do the search
984 : : * initially as a simple byte search, ignoring multibyte issues, but
985 : : * verify afterwards that the match we found is at a character boundary,
986 : : * and continue the search if it was a false match.
987 : : */
988 [ + + ]: 1245 : if (pg_database_encoding_max_length() == 1)
989 : 54 : state->is_multibyte_char_in_char = false;
990 [ + - ]: 1191 : else if (GetDatabaseEncoding() == PG_UTF8)
991 : 1191 : state->is_multibyte_char_in_char = false;
992 : : else
993 : 0 : state->is_multibyte_char_in_char = true;
994 : :
995 : 1245 : state->str1 = VARDATA_ANY(t1);
996 : 1245 : state->str2 = VARDATA_ANY(t2);
997 : 1245 : state->len1 = len1;
998 : 1245 : state->len2 = len2;
999 : 1245 : state->last_match = NULL;
1000 : 1245 : state->refpoint = state->str1;
1001 : 1245 : state->refpos = 0;
1002 : :
1003 : : /*
1004 : : * Prepare the skip table for Boyer-Moore-Horspool searching. In these
1005 : : * notes we use the terminology that the "haystack" is the string to be
1006 : : * searched (t1) and the "needle" is the pattern being sought (t2).
1007 : : *
1008 : : * If the needle is empty or bigger than the haystack then there is no
1009 : : * point in wasting cycles initializing the table. We also choose not to
1010 : : * use B-M-H for needles of length 1, since the skip table can't possibly
1011 : : * save anything in that case.
1012 : : *
1013 : : * (With nondeterministic collations, the search is already
1014 : : * multibyte-aware, so we don't need this.)
1015 : : */
1016 [ + - + + : 1245 : if (len1 >= len2 && len2 > 1 && state->locale->deterministic)
+ + ]
1017 : : {
1018 : 991 : int searchlength = len1 - len2;
1019 : : int skiptablemask;
1020 : : int last;
1021 : : int i;
1022 : 991 : const char *str2 = state->str2;
1023 : :
1024 : : /*
1025 : : * First we must determine how much of the skip table to use. The
1026 : : * declaration of TextPositionState allows up to 256 elements, but for
1027 : : * short search problems we don't really want to have to initialize so
1028 : : * many elements --- it would take too long in comparison to the
1029 : : * actual search time. So we choose a useful skip table size based on
1030 : : * the haystack length minus the needle length. The closer the needle
1031 : : * length is to the haystack length the less useful skipping becomes.
1032 : : *
1033 : : * Note: since we use bit-masking to select table elements, the skip
1034 : : * table size MUST be a power of 2, and so the mask must be 2^N-1.
1035 : : */
1036 [ + + ]: 991 : if (searchlength < 16)
1037 : 112 : skiptablemask = 3;
1038 [ + + ]: 879 : else if (searchlength < 64)
1039 : 24 : skiptablemask = 7;
1040 [ + + ]: 855 : else if (searchlength < 128)
1041 : 15 : skiptablemask = 15;
1042 [ + + ]: 840 : else if (searchlength < 512)
1043 : 195 : skiptablemask = 31;
1044 [ + + ]: 645 : else if (searchlength < 2048)
1045 : 463 : skiptablemask = 63;
1046 [ + + ]: 182 : else if (searchlength < 4096)
1047 : 139 : skiptablemask = 127;
1048 : : else
1049 : 43 : skiptablemask = 255;
1050 : 991 : state->skiptablemask = skiptablemask;
1051 : :
1052 : : /*
1053 : : * Initialize the skip table. We set all elements to the needle
1054 : : * length, since this is the correct skip distance for any character
1055 : : * not found in the needle.
1056 : : */
1057 [ + + ]: 66543 : for (i = 0; i <= skiptablemask; i++)
1058 : 65552 : state->skiptable[i] = len2;
1059 : :
1060 : : /*
1061 : : * Now examine the needle. For each character except the last one,
1062 : : * set the corresponding table element to the appropriate skip
1063 : : * distance. Note that when two characters share the same skip table
1064 : : * entry, the one later in the needle must determine the skip
1065 : : * distance.
1066 : : */
1067 : 991 : last = len2 - 1;
1068 : :
1069 [ + + ]: 12144 : for (i = 0; i < last; i++)
1070 : 11153 : state->skiptable[(unsigned char) str2[i] & skiptablemask] = last - i;
1071 : : }
1072 : 1245 : }
1073 : :
1074 : : /*
1075 : : * Advance to the next match, starting from the end of the previous match
1076 : : * (or the beginning of the string, on first call). Returns true if a match
1077 : : * is found.
1078 : : *
1079 : : * Note that this refuses to match an empty-string needle. Most callers
1080 : : * will have handled that case specially and we'll never see it here.
1081 : : */
1082 : : static bool
1083 : 5969 : text_position_next(TextPositionState *state)
1084 : : {
1085 : 5969 : int needle_len = state->len2;
1086 : : char *start_ptr;
1087 : : char *matchptr;
1088 : :
1089 [ - + ]: 5969 : if (needle_len <= 0)
1090 : 0 : return false; /* result for empty pattern */
1091 : :
1092 : : /* Start from the point right after the previous match. */
1093 [ + + ]: 5969 : if (state->last_match)
1094 : 4710 : start_ptr = state->last_match + state->last_match_len;
1095 : : else
1096 : 1259 : start_ptr = state->str1;
1097 : :
1098 : 5969 : retry:
1099 : 5969 : matchptr = text_position_next_internal(start_ptr, state);
1100 : :
1101 [ + + ]: 5969 : if (!matchptr)
1102 : 1181 : return false;
1103 : :
1104 : : /*
1105 : : * Found a match for the byte sequence. If this is a multibyte encoding,
1106 : : * where one character's byte sequence can appear inside a longer
1107 : : * multi-byte character, we need to verify that the match was at a
1108 : : * character boundary, not in the middle of a multi-byte character.
1109 : : */
1110 [ - + - - ]: 4788 : if (state->is_multibyte_char_in_char && state->locale->deterministic)
1111 : : {
1112 : 0 : const char *haystack_end = state->str1 + state->len1;
1113 : :
1114 : : /* Walk one character at a time, until we reach the match. */
1115 : :
1116 : : /* the search should never move backwards. */
1117 : : Assert(state->refpoint <= matchptr);
1118 : :
1119 [ # # ]: 0 : while (state->refpoint < matchptr)
1120 : : {
1121 : : /* step to next character. */
1122 : 0 : state->refpoint += pg_mblen_range(state->refpoint, haystack_end);
1123 : 0 : state->refpos++;
1124 : :
1125 : : /*
1126 : : * If we stepped over the match's start position, then it was a
1127 : : * false positive, where the byte sequence appeared in the middle
1128 : : * of a multi-byte character. Skip it, and continue the search at
1129 : : * the next character boundary.
1130 : : */
1131 [ # # ]: 0 : if (state->refpoint > matchptr)
1132 : : {
1133 : 0 : start_ptr = state->refpoint;
1134 : 0 : goto retry;
1135 : : }
1136 : : }
1137 : : }
1138 : :
1139 : 4788 : state->last_match = matchptr;
1140 : 4788 : state->last_match_len = state->last_match_len_tmp;
1141 : 4788 : return true;
1142 : : }
1143 : :
1144 : : /*
1145 : : * Subroutine of text_position_next(). This searches for the raw byte
1146 : : * sequence, ignoring any multi-byte encoding issues. Returns the first
1147 : : * match starting at 'start_ptr', or NULL if no match is found.
1148 : : */
1149 : : static char *
1150 : 5969 : text_position_next_internal(char *start_ptr, TextPositionState *state)
1151 : : {
1152 : 5969 : int haystack_len = state->len1;
1153 : 5969 : int needle_len = state->len2;
1154 : 5969 : int skiptablemask = state->skiptablemask;
1155 : 5969 : const char *haystack = state->str1;
1156 : 5969 : char *needle = state->str2;
1157 : 5969 : const char *haystack_end = &haystack[haystack_len];
1158 : : char *hptr;
1159 : :
1160 : : Assert(start_ptr >= haystack && start_ptr <= haystack_end);
1161 : : Assert(needle_len > 0);
1162 : :
1163 : 5969 : state->last_match_len_tmp = needle_len;
1164 : :
1165 [ + + ]: 5969 : if (!state->locale->deterministic)
1166 : : {
1167 : : /*
1168 : : * With a nondeterministic collation, we have to use an unoptimized
1169 : : * route. We walk through the haystack and see if at each position
1170 : : * there is a substring of the remaining string that is equal to the
1171 : : * needle under the given collation.
1172 : : *
1173 : : * Note, the found substring could have a different length than the
1174 : : * needle. Callers that want to skip over the found string need to
1175 : : * read the length of the found substring from last_match_len rather
1176 : : * than just using the length of their needle.
1177 : : *
1178 : : * Most callers will require "greedy" semantics, meaning that we need
1179 : : * to find the longest such substring, not the shortest. For callers
1180 : : * that don't need greedy semantics, we can finish on the first match.
1181 : : *
1182 : : * This loop depends on the assumption that the needle is nonempty and
1183 : : * any matching substring must also be nonempty. (Even if the
1184 : : * collation would accept an empty match, returning one would send
1185 : : * callers that search for successive matches into an infinite loop.)
1186 : : */
1187 : 176 : char *result_hptr = NULL;
1188 : :
1189 : 176 : hptr = start_ptr;
1190 [ + + ]: 482 : while (hptr < haystack_end)
1191 : : {
1192 : : const char *test_end;
1193 : :
1194 : : /*
1195 : : * First check the common case that there is a match in the
1196 : : * haystack of exactly the length of the needle.
1197 : : */
1198 [ + + ]: 403 : if (!state->greedy &&
1199 [ + - + + ]: 72 : haystack_end - hptr >= needle_len &&
1200 : 36 : pg_strncoll(hptr, needle_len, needle, needle_len, state->locale) == 0)
1201 : 8 : return hptr;
1202 : :
1203 : : /*
1204 : : * Else check if any of the non-empty substrings starting at hptr
1205 : : * compare equal to the needle.
1206 : : */
1207 : 395 : test_end = hptr;
1208 : : do
1209 : : {
1210 : 1583 : test_end += pg_mblen_range(test_end, haystack_end);
1211 [ + + ]: 1583 : if (pg_strncoll(hptr, (test_end - hptr), needle, needle_len, state->locale) == 0)
1212 : : {
1213 : 97 : state->last_match_len_tmp = (test_end - hptr);
1214 : 97 : result_hptr = hptr;
1215 [ - + ]: 97 : if (!state->greedy)
1216 : 0 : break;
1217 : : }
1218 [ + + ]: 1583 : } while (test_end < haystack_end);
1219 : :
1220 [ + + ]: 395 : if (result_hptr)
1221 : 89 : break;
1222 : :
1223 : 306 : hptr += pg_mblen_range(hptr, haystack_end);
1224 : : }
1225 : :
1226 : 168 : return result_hptr;
1227 : : }
1228 [ + + ]: 5793 : else if (needle_len == 1)
1229 : : {
1230 : : /* No point in using B-M-H for a one-character needle */
1231 : 597 : char nchar = *needle;
1232 : :
1233 : 597 : hptr = start_ptr;
1234 [ + + ]: 4246 : while (hptr < haystack_end)
1235 : : {
1236 [ + + ]: 4108 : if (*hptr == nchar)
1237 : 459 : return hptr;
1238 : 3649 : hptr++;
1239 : : }
1240 : : }
1241 : : else
1242 : : {
1243 : 5196 : char *needle_last = &needle[needle_len - 1];
1244 : :
1245 : : /* Start at startpos plus the length of the needle */
1246 : 5196 : hptr = start_ptr + needle_len - 1;
1247 [ + + ]: 124914 : while (hptr < haystack_end)
1248 : : {
1249 : : /* Match the needle scanning *backward* */
1250 : : char *nptr;
1251 : : char *p;
1252 : :
1253 : 123950 : nptr = needle_last;
1254 : 123950 : p = hptr;
1255 [ + + ]: 186563 : while (*nptr == *p)
1256 : : {
1257 : : /* Matched it all? If so, return 1-based position */
1258 [ + + ]: 66845 : if (nptr == needle)
1259 : 4232 : return p;
1260 : 62613 : nptr--, p--;
1261 : : }
1262 : :
1263 : : /*
1264 : : * No match, so use the haystack char at hptr to decide how far to
1265 : : * advance. If the needle had any occurrence of that character
1266 : : * (or more precisely, one sharing the same skiptable entry)
1267 : : * before its last character, then we advance far enough to align
1268 : : * the last such needle character with that haystack position.
1269 : : * Otherwise we can advance by the whole needle length.
1270 : : */
1271 : 119718 : hptr += state->skiptable[(unsigned char) *hptr & skiptablemask];
1272 : : }
1273 : : }
1274 : :
1275 : 1102 : return 0; /* not found */
1276 : : }
1277 : :
1278 : : /*
1279 : : * Return a pointer to the current match.
1280 : : *
1281 : : * The returned pointer points into the original haystack string.
1282 : : */
1283 : : static char *
1284 : 4701 : text_position_get_match_ptr(TextPositionState *state)
1285 : : {
1286 : 4701 : return state->last_match;
1287 : : }
1288 : :
1289 : : /*
1290 : : * Return the offset of the current match.
1291 : : *
1292 : : * The offset is in characters, 1-based.
1293 : : */
1294 : : static int
1295 : 50 : text_position_get_match_pos(TextPositionState *state)
1296 : : {
1297 : : /* Convert the byte position to char position. */
1298 : 100 : state->refpos += pg_mbstrlen_with_len(state->refpoint,
1299 : 50 : state->last_match - state->refpoint);
1300 : 50 : state->refpoint = state->last_match;
1301 : 50 : return state->refpos + 1;
1302 : : }
1303 : :
1304 : : /*
1305 : : * Reset search state to the initial state installed by text_position_setup.
1306 : : *
1307 : : * The next call to text_position_next will search from the beginning
1308 : : * of the string.
1309 : : */
1310 : : static void
1311 : 14 : text_position_reset(TextPositionState *state)
1312 : : {
1313 : 14 : state->last_match = NULL;
1314 : 14 : state->refpoint = state->str1;
1315 : 14 : state->refpos = 0;
1316 : 14 : }
1317 : :
1318 : : static void
1319 : 1245 : text_position_cleanup(TextPositionState *state)
1320 : : {
1321 : : /* no cleanup needed */
1322 : 1245 : }
1323 : :
1324 : :
1325 : : static void
1326 : 12104207 : check_collation_set(Oid collid)
1327 : : {
1328 [ + + ]: 12104207 : if (!OidIsValid(collid))
1329 : : {
1330 : : /*
1331 : : * This typically means that the parser could not resolve a conflict
1332 : : * of implicit collations, so report it that way.
1333 : : */
1334 [ + - ]: 20 : ereport(ERROR,
1335 : : (errcode(ERRCODE_INDETERMINATE_COLLATION),
1336 : : errmsg("could not determine which collation to use for string comparison"),
1337 : : errhint("Use the COLLATE clause to set the collation explicitly.")));
1338 : : }
1339 : 12104187 : }
1340 : :
1341 : : /*
1342 : : * varstr_cmp()
1343 : : *
1344 : : * Comparison function for text strings with given lengths, using the
1345 : : * appropriate locale. Returns an integer less than, equal to, or greater than
1346 : : * zero, indicating whether arg1 is less than, equal to, or greater than arg2.
1347 : : *
1348 : : * Note: many functions that depend on this are marked leakproof; therefore,
1349 : : * avoid reporting the actual contents of the input when throwing errors.
1350 : : * All errors herein should be things that can't happen except on corrupt
1351 : : * data, anyway; otherwise we will have trouble with indexing strings that
1352 : : * would cause them.
1353 : : */
1354 : : int
1355 : 6184108 : varstr_cmp(const char *arg1, int len1, const char *arg2, int len2, Oid collid)
1356 : : {
1357 : : int result;
1358 : : pg_locale_t mylocale;
1359 : :
1360 : 6184108 : check_collation_set(collid);
1361 : :
1362 : 6184096 : mylocale = pg_newlocale_from_collation(collid);
1363 : :
1364 [ + + ]: 6184096 : if (mylocale->collate_is_c)
1365 : : {
1366 : 2323992 : result = memcmp(arg1, arg2, Min(len1, len2));
1367 [ + + + + ]: 2323992 : if ((result == 0) && (len1 != len2))
1368 [ + + ]: 89082 : result = (len1 < len2) ? -1 : 1;
1369 : : }
1370 : : else
1371 : : {
1372 : : /*
1373 : : * memcmp() can't tell us which of two unequal strings sorts first,
1374 : : * but it's a cheap way to tell if they're equal. Testing shows that
1375 : : * memcmp() followed by strcoll() is only trivially slower than
1376 : : * strcoll() by itself, so we don't lose much if this doesn't work out
1377 : : * very often, and if it does - for example, because there are many
1378 : : * equal strings in the input - then we win big by avoiding expensive
1379 : : * collation-aware comparisons.
1380 : : */
1381 [ + + + + ]: 3860104 : if (len1 == len2 && memcmp(arg1, arg2, len1) == 0)
1382 : 1061474 : return 0;
1383 : :
1384 : 2798630 : result = pg_strncoll(arg1, len1, arg2, len2, mylocale);
1385 : :
1386 : : /* Break tie if necessary. */
1387 [ + + - + ]: 2798630 : if (result == 0 && mylocale->deterministic)
1388 : : {
1389 : 0 : result = memcmp(arg1, arg2, Min(len1, len2));
1390 [ # # # # ]: 0 : if ((result == 0) && (len1 != len2))
1391 [ # # ]: 0 : result = (len1 < len2) ? -1 : 1;
1392 : : }
1393 : : }
1394 : :
1395 : 5122622 : return result;
1396 : : }
1397 : :
1398 : : /*
1399 : : * text_cmp()
1400 : : * Internal comparison function for text strings.
1401 : : * Returns -1, 0 or 1
1402 : : */
1403 : : static int
1404 : 4819582 : text_cmp(text *arg1, text *arg2, Oid collid)
1405 : : {
1406 : : char *a1p,
1407 : : *a2p;
1408 : : int len1,
1409 : : len2;
1410 : :
1411 : 4819582 : a1p = VARDATA_ANY(arg1);
1412 : 4819582 : a2p = VARDATA_ANY(arg2);
1413 : :
1414 : 4819582 : len1 = VARSIZE_ANY_EXHDR(arg1);
1415 : 4819582 : len2 = VARSIZE_ANY_EXHDR(arg2);
1416 : :
1417 : 4819582 : return varstr_cmp(a1p, len1, a2p, len2, collid);
1418 : : }
1419 : :
1420 : : /*
1421 : : * Comparison functions for text strings.
1422 : : *
1423 : : * Note: btree indexes need these routines not to leak memory; therefore,
1424 : : * be careful to free working copies of toasted datums. Most places don't
1425 : : * need to be so careful.
1426 : : */
1427 : :
1428 : : Datum
1429 : 5284125 : texteq(PG_FUNCTION_ARGS)
1430 : : {
1431 : 5284125 : Oid collid = PG_GET_COLLATION();
1432 : 5284125 : pg_locale_t mylocale = 0;
1433 : : bool result;
1434 : :
1435 : 5284125 : check_collation_set(collid);
1436 : :
1437 : 5284125 : mylocale = pg_newlocale_from_collation(collid);
1438 : :
1439 [ + + ]: 5284125 : if (mylocale->deterministic)
1440 : : {
1441 : 5277711 : Datum arg1 = PG_GETARG_DATUM(0);
1442 : 5277711 : Datum arg2 = PG_GETARG_DATUM(1);
1443 : : Size len1,
1444 : : len2;
1445 : :
1446 : : /*
1447 : : * Since we only care about equality or not-equality, we can avoid all
1448 : : * the expense of strcoll() here, and just do bitwise comparison. In
1449 : : * fact, we don't even have to do a bitwise comparison if we can show
1450 : : * the lengths of the strings are unequal; which might save us from
1451 : : * having to detoast one or both values.
1452 : : */
1453 : 5277711 : len1 = toast_raw_datum_size(arg1);
1454 : 5277711 : len2 = toast_raw_datum_size(arg2);
1455 [ + + ]: 5277711 : if (len1 != len2)
1456 : 2692625 : result = false;
1457 : : else
1458 : : {
1459 : 2585086 : text *targ1 = DatumGetTextPP(arg1);
1460 : 2585086 : text *targ2 = DatumGetTextPP(arg2);
1461 : :
1462 : 2585086 : result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
1463 : : len1 - VARHDRSZ) == 0);
1464 : :
1465 [ + + ]: 2585086 : PG_FREE_IF_COPY(targ1, 0);
1466 [ + + ]: 2585086 : PG_FREE_IF_COPY(targ2, 1);
1467 : : }
1468 : : }
1469 : : else
1470 : : {
1471 : 6414 : text *arg1 = PG_GETARG_TEXT_PP(0);
1472 : 6414 : text *arg2 = PG_GETARG_TEXT_PP(1);
1473 : :
1474 : 6414 : result = (text_cmp(arg1, arg2, collid) == 0);
1475 : :
1476 [ - + ]: 6414 : PG_FREE_IF_COPY(arg1, 0);
1477 [ - + ]: 6414 : PG_FREE_IF_COPY(arg2, 1);
1478 : : }
1479 : :
1480 : 5284125 : PG_RETURN_BOOL(result);
1481 : : }
1482 : :
1483 : : Datum
1484 : 207949 : textne(PG_FUNCTION_ARGS)
1485 : : {
1486 : 207949 : Oid collid = PG_GET_COLLATION();
1487 : : pg_locale_t mylocale;
1488 : : bool result;
1489 : :
1490 : 207949 : check_collation_set(collid);
1491 : :
1492 : 207949 : mylocale = pg_newlocale_from_collation(collid);
1493 : :
1494 [ + + ]: 207949 : if (mylocale->deterministic)
1495 : : {
1496 : 207933 : Datum arg1 = PG_GETARG_DATUM(0);
1497 : 207933 : Datum arg2 = PG_GETARG_DATUM(1);
1498 : : Size len1,
1499 : : len2;
1500 : :
1501 : : /* See comment in texteq() */
1502 : 207933 : len1 = toast_raw_datum_size(arg1);
1503 : 207933 : len2 = toast_raw_datum_size(arg2);
1504 [ + + ]: 207933 : if (len1 != len2)
1505 : 11678 : result = true;
1506 : : else
1507 : : {
1508 : 196255 : text *targ1 = DatumGetTextPP(arg1);
1509 : 196255 : text *targ2 = DatumGetTextPP(arg2);
1510 : :
1511 : 196255 : result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
1512 : : len1 - VARHDRSZ) != 0);
1513 : :
1514 [ - + ]: 196255 : PG_FREE_IF_COPY(targ1, 0);
1515 [ - + ]: 196255 : PG_FREE_IF_COPY(targ2, 1);
1516 : : }
1517 : : }
1518 : : else
1519 : : {
1520 : 16 : text *arg1 = PG_GETARG_TEXT_PP(0);
1521 : 16 : text *arg2 = PG_GETARG_TEXT_PP(1);
1522 : :
1523 : 16 : result = (text_cmp(arg1, arg2, collid) != 0);
1524 : :
1525 [ - + ]: 16 : PG_FREE_IF_COPY(arg1, 0);
1526 [ - + ]: 16 : PG_FREE_IF_COPY(arg2, 1);
1527 : : }
1528 : :
1529 : 207949 : PG_RETURN_BOOL(result);
1530 : : }
1531 : :
1532 : : Datum
1533 : 231934 : text_lt(PG_FUNCTION_ARGS)
1534 : : {
1535 : 231934 : text *arg1 = PG_GETARG_TEXT_PP(0);
1536 : 231934 : text *arg2 = PG_GETARG_TEXT_PP(1);
1537 : : bool result;
1538 : :
1539 : 231934 : result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0);
1540 : :
1541 [ + + ]: 231922 : PG_FREE_IF_COPY(arg1, 0);
1542 [ - + ]: 231922 : PG_FREE_IF_COPY(arg2, 1);
1543 : :
1544 : 231922 : PG_RETURN_BOOL(result);
1545 : : }
1546 : :
1547 : : Datum
1548 : 213777 : text_le(PG_FUNCTION_ARGS)
1549 : : {
1550 : 213777 : text *arg1 = PG_GETARG_TEXT_PP(0);
1551 : 213777 : text *arg2 = PG_GETARG_TEXT_PP(1);
1552 : : bool result;
1553 : :
1554 : 213777 : result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) <= 0);
1555 : :
1556 [ + + ]: 213777 : PG_FREE_IF_COPY(arg1, 0);
1557 [ + + ]: 213777 : PG_FREE_IF_COPY(arg2, 1);
1558 : :
1559 : 213777 : PG_RETURN_BOOL(result);
1560 : : }
1561 : :
1562 : : Datum
1563 : 215858 : text_gt(PG_FUNCTION_ARGS)
1564 : : {
1565 : 215858 : text *arg1 = PG_GETARG_TEXT_PP(0);
1566 : 215858 : text *arg2 = PG_GETARG_TEXT_PP(1);
1567 : : bool result;
1568 : :
1569 : 215858 : result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0);
1570 : :
1571 [ + + ]: 215858 : PG_FREE_IF_COPY(arg1, 0);
1572 [ - + ]: 215858 : PG_FREE_IF_COPY(arg2, 1);
1573 : :
1574 : 215858 : PG_RETURN_BOOL(result);
1575 : : }
1576 : :
1577 : : Datum
1578 : 116298 : text_ge(PG_FUNCTION_ARGS)
1579 : : {
1580 : 116298 : text *arg1 = PG_GETARG_TEXT_PP(0);
1581 : 116298 : text *arg2 = PG_GETARG_TEXT_PP(1);
1582 : : bool result;
1583 : :
1584 : 116298 : result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) >= 0);
1585 : :
1586 [ + + ]: 116298 : PG_FREE_IF_COPY(arg1, 0);
1587 [ - + ]: 116298 : PG_FREE_IF_COPY(arg2, 1);
1588 : :
1589 : 116298 : PG_RETURN_BOOL(result);
1590 : : }
1591 : :
1592 : : Datum
1593 : 25276 : text_starts_with(PG_FUNCTION_ARGS)
1594 : : {
1595 : 25276 : Datum arg1 = PG_GETARG_DATUM(0);
1596 : 25276 : Datum arg2 = PG_GETARG_DATUM(1);
1597 : 25276 : Oid collid = PG_GET_COLLATION();
1598 : : pg_locale_t mylocale;
1599 : : bool result;
1600 : : Size len1,
1601 : : len2;
1602 : :
1603 : 25276 : check_collation_set(collid);
1604 : :
1605 : 25276 : mylocale = pg_newlocale_from_collation(collid);
1606 : :
1607 [ - + ]: 25276 : if (!mylocale->deterministic)
1608 [ # # ]: 0 : ereport(ERROR,
1609 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1610 : : errmsg("nondeterministic collations are not supported for substring searches")));
1611 : :
1612 : 25276 : len1 = toast_raw_datum_size(arg1);
1613 : 25276 : len2 = toast_raw_datum_size(arg2);
1614 [ - + ]: 25276 : if (len2 > len1)
1615 : 0 : result = false;
1616 : : else
1617 : : {
1618 : 25276 : text *targ1 = text_substring(arg1, 1, len2, false);
1619 : 25276 : text *targ2 = DatumGetTextPP(arg2);
1620 : :
1621 : 25276 : result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
1622 : : VARSIZE_ANY_EXHDR(targ2)) == 0);
1623 : :
1624 [ + - ]: 25276 : PG_FREE_IF_COPY(targ1, 0);
1625 [ - + ]: 25276 : PG_FREE_IF_COPY(targ2, 1);
1626 : : }
1627 : :
1628 : 25276 : PG_RETURN_BOOL(result);
1629 : : }
1630 : :
1631 : : Datum
1632 : 3838838 : bttextcmp(PG_FUNCTION_ARGS)
1633 : : {
1634 : 3838838 : text *arg1 = PG_GETARG_TEXT_PP(0);
1635 : 3838838 : text *arg2 = PG_GETARG_TEXT_PP(1);
1636 : : int32 result;
1637 : :
1638 : 3838838 : result = text_cmp(arg1, arg2, PG_GET_COLLATION());
1639 : :
1640 [ + + ]: 3838838 : PG_FREE_IF_COPY(arg1, 0);
1641 [ + + ]: 3838838 : PG_FREE_IF_COPY(arg2, 1);
1642 : :
1643 : 3838838 : PG_RETURN_INT32(result);
1644 : : }
1645 : :
1646 : : Datum
1647 : 50028 : bttextsortsupport(PG_FUNCTION_ARGS)
1648 : : {
1649 : 50028 : SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
1650 : 50028 : Oid collid = ssup->ssup_collation;
1651 : : MemoryContext oldcontext;
1652 : :
1653 : 50028 : oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
1654 : :
1655 : : /* Use generic string SortSupport */
1656 : 50028 : varstr_sortsupport(ssup, TEXTOID, collid);
1657 : :
1658 : 50020 : MemoryContextSwitchTo(oldcontext);
1659 : :
1660 : 50020 : PG_RETURN_VOID();
1661 : : }
1662 : :
1663 : : /*
1664 : : * Generic sortsupport interface for character type's operator classes.
1665 : : * Includes locale support, and support for BpChar semantics (i.e. removing
1666 : : * trailing spaces before comparison).
1667 : : *
1668 : : * Relies on the assumption that text, VarChar, and BpChar all have the
1669 : : * same representation.
1670 : : */
1671 : : void
1672 : 84943 : varstr_sortsupport(SortSupport ssup, Oid typid, Oid collid)
1673 : : {
1674 : 84943 : bool abbreviate = ssup->abbreviate;
1675 : 84943 : bool collate_c = false;
1676 : : VarStringSortSupport *sss;
1677 : : pg_locale_t locale;
1678 : :
1679 : 84943 : check_collation_set(collid);
1680 : :
1681 : 84935 : locale = pg_newlocale_from_collation(collid);
1682 : :
1683 : : /*
1684 : : * If possible, set ssup->comparator to a function which can be used to
1685 : : * directly compare two datums. If we can do this, we'll avoid the
1686 : : * overhead of a trip through the fmgr layer for every comparison, which
1687 : : * can be substantial.
1688 : : *
1689 : : * Most typically, we'll set the comparator to varlenafastcmp_locale,
1690 : : * which uses strcoll() to perform comparisons. We use that for the
1691 : : * BpChar case too, but type NAME uses namefastcmp_locale. However, if
1692 : : * LC_COLLATE = C, we can make things quite a bit faster with
1693 : : * varstrfastcmp_c, bpcharfastcmp_c, or namefastcmp_c, all of which use
1694 : : * memcmp() rather than strcoll().
1695 : : */
1696 [ + + ]: 84935 : if (locale->collate_is_c)
1697 : : {
1698 [ + + ]: 57970 : if (typid == BPCHAROID)
1699 : 158 : ssup->comparator = bpcharfastcmp_c;
1700 [ + + ]: 57812 : else if (typid == NAMEOID)
1701 : : {
1702 : 34249 : ssup->comparator = namefastcmp_c;
1703 : : /* Not supporting abbreviation with type NAME, for now */
1704 : 34249 : abbreviate = false;
1705 : : }
1706 : : else
1707 : 23563 : ssup->comparator = varstrfastcmp_c;
1708 : :
1709 : 57970 : collate_c = true;
1710 : : }
1711 : : else
1712 : : {
1713 : : /*
1714 : : * We use varlenafastcmp_locale except for type NAME.
1715 : : */
1716 [ - + ]: 26965 : if (typid == NAMEOID)
1717 : : {
1718 : 0 : ssup->comparator = namefastcmp_locale;
1719 : : /* Not supporting abbreviation with type NAME, for now */
1720 : 0 : abbreviate = false;
1721 : : }
1722 : : else
1723 : 26965 : ssup->comparator = varlenafastcmp_locale;
1724 : :
1725 : : /*
1726 : : * Unfortunately, it seems that abbreviation for non-C collations is
1727 : : * broken on many common platforms; see pg_strxfrm_enabled().
1728 : : *
1729 : : * Even apart from the risk of broken locales, it's possible that
1730 : : * there are platforms where the use of abbreviated keys should be
1731 : : * disabled at compile time. For example, macOS's strxfrm()
1732 : : * implementation is known to not effectively concentrate a
1733 : : * significant amount of entropy from the original string in earlier
1734 : : * transformed blobs. It's possible that other supported platforms
1735 : : * are similarly encumbered. So, if we ever get past disabling this
1736 : : * categorically, we may still want or need to disable it for
1737 : : * particular platforms.
1738 : : */
1739 [ + + ]: 26965 : if (!pg_strxfrm_enabled(locale))
1740 : 26355 : abbreviate = false;
1741 : : }
1742 : :
1743 : : /*
1744 : : * If we're using abbreviated keys, or if we're using a locale-aware
1745 : : * comparison, we need to initialize a VarStringSortSupport object. Both
1746 : : * cases will make use of the temporary buffers we initialize here for
1747 : : * scratch space (and to detect requirement for BpChar semantics from
1748 : : * caller), and the abbreviation case requires additional state.
1749 : : */
1750 [ + + + + ]: 84935 : if (abbreviate || !collate_c)
1751 : : {
1752 : 39380 : sss = palloc_object(VarStringSortSupport);
1753 : 39380 : sss->buf1 = palloc(TEXTBUFLEN);
1754 : 39380 : sss->buflen1 = TEXTBUFLEN;
1755 : 39380 : sss->buf2 = palloc(TEXTBUFLEN);
1756 : 39380 : sss->buflen2 = TEXTBUFLEN;
1757 : : /* Start with invalid values */
1758 : 39380 : sss->last_len1 = -1;
1759 : 39380 : sss->last_len2 = -1;
1760 : : /* Initialize */
1761 : 39380 : sss->last_returned = 0;
1762 [ + + ]: 39380 : if (collate_c)
1763 : 12415 : sss->locale = NULL;
1764 : : else
1765 : 26965 : sss->locale = locale;
1766 : :
1767 : : /*
1768 : : * To avoid somehow confusing a strxfrm() blob and an original string,
1769 : : * constantly keep track of the variety of data that buf1 and buf2
1770 : : * currently contain.
1771 : : *
1772 : : * Comparisons may be interleaved with conversion calls. Frequently,
1773 : : * conversions and comparisons are batched into two distinct phases,
1774 : : * but the correctness of caching cannot hinge upon this. For
1775 : : * comparison caching, buffer state is only trusted if cache_blob is
1776 : : * found set to false, whereas strxfrm() caching only trusts the state
1777 : : * when cache_blob is found set to true.
1778 : : *
1779 : : * Arbitrarily initialize cache_blob to true.
1780 : : */
1781 : 39380 : sss->cache_blob = true;
1782 : 39380 : sss->collate_c = collate_c;
1783 : 39380 : sss->typid = typid;
1784 : 39380 : ssup->ssup_extra = sss;
1785 : :
1786 : : /*
1787 : : * If possible, plan to use the abbreviated keys optimization. The
1788 : : * core code may switch back to authoritative comparator should
1789 : : * abbreviation be aborted.
1790 : : */
1791 [ + + ]: 39380 : if (abbreviate)
1792 : : {
1793 : 12881 : sss->prop_card = 0.20;
1794 : 12881 : initHyperLogLog(&sss->abbr_card, 10);
1795 : 12881 : initHyperLogLog(&sss->full_card, 10);
1796 : 12881 : ssup->abbrev_full_comparator = ssup->comparator;
1797 : 12881 : ssup->comparator = ssup_datum_uint64_cmp;
1798 : 12881 : ssup->abbrev_converter = varstr_abbrev_convert;
1799 : 12881 : ssup->abbrev_abort = varstr_abbrev_abort;
1800 : : }
1801 : : }
1802 : 84935 : }
1803 : :
1804 : : /*
1805 : : * sortsupport comparison func (for C locale case)
1806 : : */
1807 : : static int
1808 : 26407235 : varstrfastcmp_c(Datum x, Datum y, SortSupport ssup)
1809 : : {
1810 : 26407235 : VarString *arg1 = DatumGetVarStringPP(x);
1811 : 26407235 : VarString *arg2 = DatumGetVarStringPP(y);
1812 : : char *a1p,
1813 : : *a2p;
1814 : : int len1,
1815 : : len2,
1816 : : result;
1817 : :
1818 : 26407235 : a1p = VARDATA_ANY(arg1);
1819 : 26407235 : a2p = VARDATA_ANY(arg2);
1820 : :
1821 : 26407235 : len1 = VARSIZE_ANY_EXHDR(arg1);
1822 : 26407235 : len2 = VARSIZE_ANY_EXHDR(arg2);
1823 : :
1824 : 26407235 : result = memcmp(a1p, a2p, Min(len1, len2));
1825 [ + + + + ]: 26407235 : if ((result == 0) && (len1 != len2))
1826 [ + + ]: 751007 : result = (len1 < len2) ? -1 : 1;
1827 : :
1828 : : /* We can't afford to leak memory here. */
1829 [ - + ]: 26407235 : if (PointerGetDatum(arg1) != x)
1830 : 0 : pfree(arg1);
1831 [ - + ]: 26407235 : if (PointerGetDatum(arg2) != y)
1832 : 0 : pfree(arg2);
1833 : :
1834 : 26407235 : return result;
1835 : : }
1836 : :
1837 : : /*
1838 : : * sortsupport comparison func (for BpChar C locale case)
1839 : : *
1840 : : * BpChar outsources its sortsupport to this module. Specialization for the
1841 : : * varstr_sortsupport BpChar case, modeled on
1842 : : * internal_bpchar_pattern_compare().
1843 : : */
1844 : : static int
1845 : 31849 : bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup)
1846 : : {
1847 : 31849 : BpChar *arg1 = DatumGetBpCharPP(x);
1848 : 31849 : BpChar *arg2 = DatumGetBpCharPP(y);
1849 : : char *a1p,
1850 : : *a2p;
1851 : : int len1,
1852 : : len2,
1853 : : result;
1854 : :
1855 : 31849 : a1p = VARDATA_ANY(arg1);
1856 : 31849 : a2p = VARDATA_ANY(arg2);
1857 : :
1858 : 31849 : len1 = bpchartruelen(a1p, VARSIZE_ANY_EXHDR(arg1));
1859 : 31849 : len2 = bpchartruelen(a2p, VARSIZE_ANY_EXHDR(arg2));
1860 : :
1861 : 31849 : result = memcmp(a1p, a2p, Min(len1, len2));
1862 [ + + + + ]: 31849 : if ((result == 0) && (len1 != len2))
1863 [ - + ]: 2 : result = (len1 < len2) ? -1 : 1;
1864 : :
1865 : : /* We can't afford to leak memory here. */
1866 [ - + ]: 31849 : if (PointerGetDatum(arg1) != x)
1867 : 0 : pfree(arg1);
1868 [ - + ]: 31849 : if (PointerGetDatum(arg2) != y)
1869 : 0 : pfree(arg2);
1870 : :
1871 : 31849 : return result;
1872 : : }
1873 : :
1874 : : /*
1875 : : * sortsupport comparison func (for NAME C locale case)
1876 : : */
1877 : : static int
1878 : 26818473 : namefastcmp_c(Datum x, Datum y, SortSupport ssup)
1879 : : {
1880 : 26818473 : Name arg1 = DatumGetName(x);
1881 : 26818473 : Name arg2 = DatumGetName(y);
1882 : :
1883 : 26818473 : return strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN);
1884 : : }
1885 : :
1886 : : /*
1887 : : * sortsupport comparison func (for locale case with all varlena types)
1888 : : */
1889 : : static int
1890 : 23335605 : varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup)
1891 : : {
1892 : 23335605 : VarString *arg1 = DatumGetVarStringPP(x);
1893 : 23335605 : VarString *arg2 = DatumGetVarStringPP(y);
1894 : : char *a1p,
1895 : : *a2p;
1896 : : int len1,
1897 : : len2,
1898 : : result;
1899 : :
1900 : 23335605 : a1p = VARDATA_ANY(arg1);
1901 : 23335605 : a2p = VARDATA_ANY(arg2);
1902 : :
1903 : 23335605 : len1 = VARSIZE_ANY_EXHDR(arg1);
1904 : 23335605 : len2 = VARSIZE_ANY_EXHDR(arg2);
1905 : :
1906 : 23335605 : result = varstrfastcmp_locale(a1p, len1, a2p, len2, ssup);
1907 : :
1908 : : /* We can't afford to leak memory here. */
1909 [ + + ]: 23335605 : if (PointerGetDatum(arg1) != x)
1910 : 36 : pfree(arg1);
1911 [ + + ]: 23335605 : if (PointerGetDatum(arg2) != y)
1912 : 29 : pfree(arg2);
1913 : :
1914 : 23335605 : return result;
1915 : : }
1916 : :
1917 : : /*
1918 : : * sortsupport comparison func (for locale case with NAME type)
1919 : : */
1920 : : static int
1921 : 0 : namefastcmp_locale(Datum x, Datum y, SortSupport ssup)
1922 : : {
1923 : 0 : Name arg1 = DatumGetName(x);
1924 : 0 : Name arg2 = DatumGetName(y);
1925 : :
1926 : 0 : return varstrfastcmp_locale(NameStr(*arg1), strlen(NameStr(*arg1)),
1927 : 0 : NameStr(*arg2), strlen(NameStr(*arg2)),
1928 : : ssup);
1929 : : }
1930 : :
1931 : : /*
1932 : : * sortsupport comparison func for locale cases
1933 : : */
1934 : : static int
1935 : 23335605 : varstrfastcmp_locale(char *a1p, int len1, char *a2p, int len2, SortSupport ssup)
1936 : : {
1937 : 23335605 : VarStringSortSupport *sss = (VarStringSortSupport *) ssup->ssup_extra;
1938 : : int result;
1939 : : bool arg1_match;
1940 : :
1941 : : /* Fast pre-check for equality, as discussed in varstr_cmp() */
1942 [ + + + + ]: 23335605 : if (len1 == len2 && memcmp(a1p, a2p, len1) == 0)
1943 : : {
1944 : : /*
1945 : : * No change in buf1 or buf2 contents, so avoid changing last_len1 or
1946 : : * last_len2. Existing contents of buffers might still be used by
1947 : : * next call.
1948 : : *
1949 : : * It's fine to allow the comparison of BpChar padding bytes here,
1950 : : * even though that implies that the memcmp() will usually be
1951 : : * performed for BpChar callers (though multibyte characters could
1952 : : * still prevent that from occurring). The memcmp() is still very
1953 : : * cheap, and BpChar's funny semantics have us remove trailing spaces
1954 : : * (not limited to padding), so we need make no distinction between
1955 : : * padding space characters and "real" space characters.
1956 : : */
1957 : 7011803 : return 0;
1958 : : }
1959 : :
1960 [ + + ]: 16323802 : if (sss->typid == BPCHAROID)
1961 : : {
1962 : : /* Get true number of bytes, ignoring trailing spaces */
1963 : 23343 : len1 = bpchartruelen(a1p, len1);
1964 : 23343 : len2 = bpchartruelen(a2p, len2);
1965 : : }
1966 : :
1967 [ + + ]: 16323802 : if (len1 >= sss->buflen1)
1968 : : {
1969 [ + - ]: 7 : sss->buflen1 = Max(len1 + 1, Min(sss->buflen1 * 2, MaxAllocSize));
1970 : 7 : sss->buf1 = repalloc(sss->buf1, sss->buflen1);
1971 : : }
1972 [ + + ]: 16323802 : if (len2 >= sss->buflen2)
1973 : : {
1974 [ + - ]: 4 : sss->buflen2 = Max(len2 + 1, Min(sss->buflen2 * 2, MaxAllocSize));
1975 : 4 : sss->buf2 = repalloc(sss->buf2, sss->buflen2);
1976 : : }
1977 : :
1978 : : /*
1979 : : * We're likely to be asked to compare the same strings repeatedly, and
1980 : : * memcmp() is so much cheaper than strcoll() that it pays to try to cache
1981 : : * comparisons, even though in general there is no reason to think that
1982 : : * that will work out (every string datum may be unique). Caching does
1983 : : * not slow things down measurably when it doesn't work out, and can speed
1984 : : * things up by rather a lot when it does. In part, this is because the
1985 : : * memcmp() compares data from cachelines that are needed in L1 cache even
1986 : : * when the last comparison's result cannot be reused.
1987 : : */
1988 : 16323802 : arg1_match = true;
1989 [ + + + + ]: 16323802 : if (len1 != sss->last_len1 || memcmp(sss->buf1, a1p, len1) != 0)
1990 : : {
1991 : 14837411 : arg1_match = false;
1992 : 14837411 : memcpy(sss->buf1, a1p, len1);
1993 : 14837411 : sss->buf1[len1] = '\0';
1994 : 14837411 : sss->last_len1 = len1;
1995 : : }
1996 : :
1997 : : /*
1998 : : * If we're comparing the same two strings as last time, we can return the
1999 : : * same answer without calling strcoll() again. This is more likely than
2000 : : * it seems (at least with moderate to low cardinality sets), because
2001 : : * quicksort compares the same pivot against many values.
2002 : : */
2003 [ + + + + ]: 16323802 : if (len2 != sss->last_len2 || memcmp(sss->buf2, a2p, len2) != 0)
2004 : : {
2005 : 2519687 : memcpy(sss->buf2, a2p, len2);
2006 : 2519687 : sss->buf2[len2] = '\0';
2007 : 2519687 : sss->last_len2 = len2;
2008 : : }
2009 [ + + + - ]: 13804115 : else if (arg1_match && !sss->cache_blob)
2010 : : {
2011 : : /* Use result cached following last actual strcoll() call */
2012 : 1228289 : return sss->last_returned;
2013 : : }
2014 : :
2015 : 15095513 : result = pg_strcoll(sss->buf1, sss->buf2, sss->locale);
2016 : :
2017 : : /* Break tie if necessary. */
2018 [ + + - + ]: 15095513 : if (result == 0 && sss->locale->deterministic)
2019 : 0 : result = strcmp(sss->buf1, sss->buf2);
2020 : :
2021 : : /* Cache result, perhaps saving an expensive strcoll() call next time */
2022 : 15095513 : sss->cache_blob = false;
2023 : 15095513 : sss->last_returned = result;
2024 : 15095513 : return result;
2025 : : }
2026 : :
2027 : : /*
2028 : : * Conversion routine for sortsupport. Converts original to abbreviated key
2029 : : * representation. Our encoding strategy is simple -- pack the first 8 bytes
2030 : : * of a strxfrm() blob into a Datum (on little-endian machines, the 8 bytes are
2031 : : * stored in reverse order), and treat it as an unsigned integer. When the "C"
2032 : : * locale is used just memcpy() from original instead.
2033 : : */
2034 : : static Datum
2035 : 501115 : varstr_abbrev_convert(Datum original, SortSupport ssup)
2036 : : {
2037 : 501115 : const size_t max_prefix_bytes = sizeof(Datum);
2038 : 501115 : VarStringSortSupport *sss = (VarStringSortSupport *) ssup->ssup_extra;
2039 : 501115 : VarString *authoritative = DatumGetVarStringPP(original);
2040 : 501115 : char *authoritative_data = VARDATA_ANY(authoritative);
2041 : :
2042 : : /* working state */
2043 : : Datum res;
2044 : : char *pres;
2045 : : int len;
2046 : : uint32 hash;
2047 : :
2048 : 501115 : pres = (char *) &res;
2049 : : /* memset(), so any non-overwritten bytes are NUL */
2050 : 501115 : memset(pres, 0, max_prefix_bytes);
2051 : 501115 : len = VARSIZE_ANY_EXHDR(authoritative);
2052 : :
2053 : : /* Get number of bytes, ignoring trailing spaces */
2054 [ + + ]: 501115 : if (sss->typid == BPCHAROID)
2055 : 524 : len = bpchartruelen(authoritative_data, len);
2056 : :
2057 : : /*
2058 : : * If we're using the C collation, use memcpy(), rather than strxfrm(), to
2059 : : * abbreviate keys. The full comparator for the C locale is also
2060 : : * memcmp(). This should be faster than strxfrm().
2061 : : */
2062 [ + + ]: 501115 : if (sss->collate_c)
2063 : 499645 : memcpy(pres, authoritative_data, Min(len, max_prefix_bytes));
2064 : : else
2065 : : {
2066 : : Size bsize;
2067 : :
2068 : : /*
2069 : : * We're not using the C collation, so fall back on strxfrm or ICU
2070 : : * analogs.
2071 : : */
2072 : :
2073 : : /* By convention, we use buffer 1 to store and NUL-terminate */
2074 [ - + ]: 1470 : if (len >= sss->buflen1)
2075 : : {
2076 [ # # ]: 0 : sss->buflen1 = Max(len + 1, Min(sss->buflen1 * 2, MaxAllocSize));
2077 : 0 : sss->buf1 = repalloc(sss->buf1, sss->buflen1);
2078 : : }
2079 : :
2080 : : /* Might be able to reuse strxfrm() blob from last call */
2081 [ + + + - ]: 1470 : if (sss->last_len1 == len && sss->cache_blob &&
2082 [ + + ]: 810 : memcmp(sss->buf1, authoritative_data, len) == 0)
2083 : : {
2084 : 152 : memcpy(pres, sss->buf2, Min(max_prefix_bytes, sss->last_len2));
2085 : : /* No change affecting cardinality, so no hashing required */
2086 : 152 : goto done;
2087 : : }
2088 : :
2089 : 1318 : memcpy(sss->buf1, authoritative_data, len);
2090 : :
2091 : : /*
2092 : : * pg_strxfrm() and pg_strxfrm_prefix expect NUL-terminated strings.
2093 : : */
2094 : 1318 : sss->buf1[len] = '\0';
2095 : 1318 : sss->last_len1 = len;
2096 : :
2097 [ + - ]: 1318 : if (pg_strxfrm_prefix_enabled(sss->locale))
2098 : : {
2099 [ - + ]: 1318 : if (sss->buflen2 < max_prefix_bytes)
2100 : : {
2101 [ # # ]: 0 : sss->buflen2 = Max(max_prefix_bytes,
2102 : : Min(sss->buflen2 * 2, MaxAllocSize));
2103 : 0 : sss->buf2 = repalloc(sss->buf2, sss->buflen2);
2104 : : }
2105 : :
2106 : 1318 : bsize = pg_strxfrm_prefix(sss->buf2, sss->buf1,
2107 : : max_prefix_bytes, sss->locale);
2108 : 1318 : sss->last_len2 = bsize;
2109 : : }
2110 : : else
2111 : : {
2112 : : /*
2113 : : * Loop: Call pg_strxfrm(), possibly enlarge buffer, and try
2114 : : * again. The pg_strxfrm() function leaves the result buffer
2115 : : * content undefined if the result did not fit, so we need to
2116 : : * retry until everything fits, even though we only need the first
2117 : : * few bytes in the end.
2118 : : */
2119 : : for (;;)
2120 : : {
2121 : 0 : bsize = pg_strxfrm(sss->buf2, sss->buf1, sss->buflen2,
2122 : : sss->locale);
2123 : :
2124 : 0 : sss->last_len2 = bsize;
2125 [ # # ]: 0 : if (bsize < sss->buflen2)
2126 : 0 : break;
2127 : :
2128 : : /*
2129 : : * Grow buffer and retry.
2130 : : */
2131 [ # # ]: 0 : sss->buflen2 = Max(bsize + 1,
2132 : : Min(sss->buflen2 * 2, MaxAllocSize));
2133 : 0 : sss->buf2 = repalloc(sss->buf2, sss->buflen2);
2134 : : }
2135 : : }
2136 : :
2137 : : /*
2138 : : * Every Datum byte is always compared. This is safe because the
2139 : : * strxfrm() blob is itself NUL terminated, leaving no danger of
2140 : : * misinterpreting any NUL bytes not intended to be interpreted as
2141 : : * logically representing termination.
2142 : : */
2143 : 1318 : memcpy(pres, sss->buf2, Min(max_prefix_bytes, bsize));
2144 : : }
2145 : :
2146 : : /*
2147 : : * Maintain approximate cardinality of both abbreviated keys and original,
2148 : : * authoritative keys using HyperLogLog. Used as cheap insurance against
2149 : : * the worst case, where we do many string transformations for no saving
2150 : : * in full strcoll()-based comparisons. These statistics are used by
2151 : : * varstr_abbrev_abort().
2152 : : *
2153 : : * First, Hash key proper, or a significant fraction of it. Mix in length
2154 : : * in order to compensate for cases where differences are past
2155 : : * PG_CACHE_LINE_SIZE bytes, so as to limit the overhead of hashing.
2156 : : */
2157 : 500963 : hash = hash_bytes((unsigned char *) authoritative_data,
2158 : : Min(len, PG_CACHE_LINE_SIZE));
2159 : :
2160 [ + + ]: 500963 : if (len > PG_CACHE_LINE_SIZE)
2161 : 96 : hash ^= murmurhash32((uint32) len);
2162 : :
2163 : 500963 : addHyperLogLog(&sss->full_card, hash);
2164 : :
2165 : : /* Hash abbreviated key */
2166 : 500963 : hash = (uint32) murmurhash64(DatumGetUInt64(res));
2167 : :
2168 : 500963 : addHyperLogLog(&sss->abbr_card, hash);
2169 : :
2170 : : /* Cache result, perhaps saving an expensive strxfrm() call next time */
2171 : 500963 : sss->cache_blob = true;
2172 : 501115 : done:
2173 : :
2174 : : /*
2175 : : * Byteswap on little-endian machines.
2176 : : *
2177 : : * This is needed so that ssup_datum_uint64_cmp() (an unsigned integer
2178 : : * 3-way comparator) works correctly on all platforms. If we didn't do
2179 : : * this, the comparator would have to call memcmp() with a pair of
2180 : : * pointers to the first byte of each abbreviated key, which is slower.
2181 : : */
2182 : 501115 : res = DatumBigEndianToNative(res);
2183 : :
2184 : : /* Don't leak memory here */
2185 [ + + ]: 501115 : if (PointerGetDatum(authoritative) != original)
2186 : 1 : pfree(authoritative);
2187 : :
2188 : 501115 : return res;
2189 : : }
2190 : :
2191 : : /*
2192 : : * Callback for estimating effectiveness of abbreviated key optimization, using
2193 : : * heuristic rules. Returns value indicating if the abbreviation optimization
2194 : : * should be aborted, based on its projected effectiveness.
2195 : : */
2196 : : static bool
2197 : 1421 : varstr_abbrev_abort(int memtupcount, SortSupport ssup)
2198 : : {
2199 : 1421 : VarStringSortSupport *sss = (VarStringSortSupport *) ssup->ssup_extra;
2200 : : double abbrev_distinct,
2201 : : key_distinct;
2202 : :
2203 : : Assert(ssup->abbreviate);
2204 : :
2205 : : /* Have a little patience */
2206 [ + + ]: 1421 : if (memtupcount < 100)
2207 : 810 : return false;
2208 : :
2209 : 611 : abbrev_distinct = estimateHyperLogLog(&sss->abbr_card);
2210 : 611 : key_distinct = estimateHyperLogLog(&sss->full_card);
2211 : :
2212 : : /*
2213 : : * Clamp cardinality estimates to at least one distinct value. While
2214 : : * NULLs are generally disregarded, if only NULL values were seen so far,
2215 : : * that might misrepresent costs if we failed to clamp.
2216 : : */
2217 [ - + ]: 611 : if (abbrev_distinct < 1.0)
2218 : 0 : abbrev_distinct = 1.0;
2219 : :
2220 [ - + ]: 611 : if (key_distinct < 1.0)
2221 : 0 : key_distinct = 1.0;
2222 : :
2223 : : /*
2224 : : * In the worst case all abbreviated keys are identical, while at the same
2225 : : * time there are differences within full key strings not captured in
2226 : : * abbreviations.
2227 : : */
2228 [ - + ]: 611 : if (trace_sort)
2229 : : {
2230 : 0 : double norm_abbrev_card = abbrev_distinct / (double) memtupcount;
2231 : :
2232 [ # # ]: 0 : elog(LOG, "varstr_abbrev: abbrev_distinct after %d: %f "
2233 : : "(key_distinct: %f, norm_abbrev_card: %f, prop_card: %f)",
2234 : : memtupcount, abbrev_distinct, key_distinct, norm_abbrev_card,
2235 : : sss->prop_card);
2236 : : }
2237 : :
2238 : : /*
2239 : : * If the number of distinct abbreviated keys approximately matches the
2240 : : * number of distinct authoritative original keys, that's reason enough to
2241 : : * proceed. We can win even with a very low cardinality set if most
2242 : : * tie-breakers only memcmp(). This is by far the most important
2243 : : * consideration.
2244 : : *
2245 : : * While comparisons that are resolved at the abbreviated key level are
2246 : : * considerably cheaper than tie-breakers resolved with memcmp(), both of
2247 : : * those two outcomes are so much cheaper than a full strcoll() once
2248 : : * sorting is underway that it doesn't seem worth it to weigh abbreviated
2249 : : * cardinality against the overall size of the set in order to more
2250 : : * accurately model costs. Assume that an abbreviated comparison, and an
2251 : : * abbreviated comparison with a cheap memcmp()-based authoritative
2252 : : * resolution are equivalent.
2253 : : */
2254 [ + - ]: 611 : if (abbrev_distinct > key_distinct * sss->prop_card)
2255 : : {
2256 : : /*
2257 : : * When we have exceeded 10,000 tuples, decay required cardinality
2258 : : * aggressively for next call.
2259 : : *
2260 : : * This is useful because the number of comparisons required on
2261 : : * average increases at a linearithmic rate, and at roughly 10,000
2262 : : * tuples that factor will start to dominate over the linear costs of
2263 : : * string transformation (this is a conservative estimate). The decay
2264 : : * rate is chosen to be a little less aggressive than halving -- which
2265 : : * (since we're called at points at which memtupcount has doubled)
2266 : : * would never see the cost model actually abort past the first call
2267 : : * following a decay. This decay rate is mostly a precaution against
2268 : : * a sudden, violent swing in how well abbreviated cardinality tracks
2269 : : * full key cardinality. The decay also serves to prevent a marginal
2270 : : * case from being aborted too late, when too much has already been
2271 : : * invested in string transformation.
2272 : : *
2273 : : * It's possible for sets of several million distinct strings with
2274 : : * mere tens of thousands of distinct abbreviated keys to still
2275 : : * benefit very significantly. This will generally occur provided
2276 : : * each abbreviated key is a proxy for a roughly uniform number of the
2277 : : * set's full keys. If it isn't so, we hope to catch that early and
2278 : : * abort. If it isn't caught early, by the time the problem is
2279 : : * apparent it's probably not worth aborting.
2280 : : */
2281 [ + + ]: 611 : if (memtupcount > 10000)
2282 : 2 : sss->prop_card *= 0.65;
2283 : :
2284 : 611 : return false;
2285 : : }
2286 : :
2287 : : /*
2288 : : * Abort abbreviation strategy.
2289 : : *
2290 : : * The worst case, where all abbreviated keys are identical while all
2291 : : * original strings differ will typically only see a regression of about
2292 : : * 10% in execution time for small to medium sized lists of strings.
2293 : : * Whereas on modern CPUs where cache stalls are the dominant cost, we can
2294 : : * often expect very large improvements, particularly with sets of strings
2295 : : * of moderately high to high abbreviated cardinality. There is little to
2296 : : * lose but much to gain, which our strategy reflects.
2297 : : */
2298 [ # # ]: 0 : if (trace_sort)
2299 [ # # ]: 0 : elog(LOG, "varstr_abbrev: aborted abbreviation at %d "
2300 : : "(abbrev_distinct: %f, key_distinct: %f, prop_card: %f)",
2301 : : memtupcount, abbrev_distinct, key_distinct, sss->prop_card);
2302 : :
2303 : 0 : return true;
2304 : : }
2305 : :
2306 : : /*
2307 : : * Generic equalimage support function for character type's operator classes.
2308 : : * Disables the use of deduplication with nondeterministic collations.
2309 : : */
2310 : : Datum
2311 : 5328 : btvarstrequalimage(PG_FUNCTION_ARGS)
2312 : : {
2313 : : #ifdef NOT_USED
2314 : : Oid opcintype = PG_GETARG_OID(0);
2315 : : #endif
2316 : 5328 : Oid collid = PG_GET_COLLATION();
2317 : : pg_locale_t locale;
2318 : :
2319 : 5328 : check_collation_set(collid);
2320 : :
2321 : 5328 : locale = pg_newlocale_from_collation(collid);
2322 : :
2323 : 5328 : PG_RETURN_BOOL(locale->deterministic);
2324 : : }
2325 : :
2326 : : Datum
2327 : 145885 : text_larger(PG_FUNCTION_ARGS)
2328 : : {
2329 : 145885 : text *arg1 = PG_GETARG_TEXT_PP(0);
2330 : 145885 : text *arg2 = PG_GETARG_TEXT_PP(1);
2331 : : text *result;
2332 : :
2333 [ + + ]: 145885 : result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0) ? arg1 : arg2);
2334 : :
2335 : 145885 : PG_RETURN_TEXT_P(result);
2336 : : }
2337 : :
2338 : : Datum
2339 : 50562 : text_smaller(PG_FUNCTION_ARGS)
2340 : : {
2341 : 50562 : text *arg1 = PG_GETARG_TEXT_PP(0);
2342 : 50562 : text *arg2 = PG_GETARG_TEXT_PP(1);
2343 : : text *result;
2344 : :
2345 [ + + ]: 50562 : result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0) ? arg1 : arg2);
2346 : :
2347 : 50562 : PG_RETURN_TEXT_P(result);
2348 : : }
2349 : :
2350 : :
2351 : : /*
2352 : : * Cross-type comparison functions for types text and name.
2353 : : */
2354 : :
2355 : : Datum
2356 : 305667 : nameeqtext(PG_FUNCTION_ARGS)
2357 : : {
2358 : 305667 : Name arg1 = PG_GETARG_NAME(0);
2359 : 305667 : text *arg2 = PG_GETARG_TEXT_PP(1);
2360 : 305667 : size_t len1 = strlen(NameStr(*arg1));
2361 : 305667 : size_t len2 = VARSIZE_ANY_EXHDR(arg2);
2362 : 305667 : Oid collid = PG_GET_COLLATION();
2363 : : bool result;
2364 : :
2365 : 305667 : check_collation_set(collid);
2366 : :
2367 [ + + ]: 305667 : if (collid == C_COLLATION_OID)
2368 [ + + ]: 299420 : result = (len1 == len2 &&
2369 [ + + ]: 97734 : memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
2370 : : else
2371 : 103981 : result = (varstr_cmp(NameStr(*arg1), len1,
2372 : 103981 : VARDATA_ANY(arg2), len2,
2373 : : collid) == 0);
2374 : :
2375 [ - + ]: 305667 : PG_FREE_IF_COPY(arg2, 1);
2376 : :
2377 : 305667 : PG_RETURN_BOOL(result);
2378 : : }
2379 : :
2380 : : Datum
2381 : 5440 : texteqname(PG_FUNCTION_ARGS)
2382 : : {
2383 : 5440 : text *arg1 = PG_GETARG_TEXT_PP(0);
2384 : 5440 : Name arg2 = PG_GETARG_NAME(1);
2385 : 5440 : size_t len1 = VARSIZE_ANY_EXHDR(arg1);
2386 : 5440 : size_t len2 = strlen(NameStr(*arg2));
2387 : 5440 : Oid collid = PG_GET_COLLATION();
2388 : : bool result;
2389 : :
2390 : 5440 : check_collation_set(collid);
2391 : :
2392 [ + + ]: 5440 : if (collid == C_COLLATION_OID)
2393 [ + + ]: 378 : result = (len1 == len2 &&
2394 [ + - ]: 121 : memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
2395 : : else
2396 : 5183 : result = (varstr_cmp(VARDATA_ANY(arg1), len1,
2397 : 5183 : NameStr(*arg2), len2,
2398 : : collid) == 0);
2399 : :
2400 [ - + ]: 5440 : PG_FREE_IF_COPY(arg1, 0);
2401 : :
2402 : 5440 : PG_RETURN_BOOL(result);
2403 : : }
2404 : :
2405 : : Datum
2406 : 27 : namenetext(PG_FUNCTION_ARGS)
2407 : : {
2408 : 27 : Name arg1 = PG_GETARG_NAME(0);
2409 : 27 : text *arg2 = PG_GETARG_TEXT_PP(1);
2410 : 27 : size_t len1 = strlen(NameStr(*arg1));
2411 : 27 : size_t len2 = VARSIZE_ANY_EXHDR(arg2);
2412 : 27 : Oid collid = PG_GET_COLLATION();
2413 : : bool result;
2414 : :
2415 : 27 : check_collation_set(collid);
2416 : :
2417 [ + + ]: 27 : if (collid == C_COLLATION_OID)
2418 [ - + ]: 15 : result = !(len1 == len2 &&
2419 [ # # ]: 0 : memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
2420 : : else
2421 : 12 : result = !(varstr_cmp(NameStr(*arg1), len1,
2422 : 12 : VARDATA_ANY(arg2), len2,
2423 : : collid) == 0);
2424 : :
2425 [ - + ]: 27 : PG_FREE_IF_COPY(arg2, 1);
2426 : :
2427 : 27 : PG_RETURN_BOOL(result);
2428 : : }
2429 : :
2430 : : Datum
2431 : 12 : textnename(PG_FUNCTION_ARGS)
2432 : : {
2433 : 12 : text *arg1 = PG_GETARG_TEXT_PP(0);
2434 : 12 : Name arg2 = PG_GETARG_NAME(1);
2435 : 12 : size_t len1 = VARSIZE_ANY_EXHDR(arg1);
2436 : 12 : size_t len2 = strlen(NameStr(*arg2));
2437 : 12 : Oid collid = PG_GET_COLLATION();
2438 : : bool result;
2439 : :
2440 : 12 : check_collation_set(collid);
2441 : :
2442 [ - + ]: 12 : if (collid == C_COLLATION_OID)
2443 [ # # ]: 0 : result = !(len1 == len2 &&
2444 [ # # ]: 0 : memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
2445 : : else
2446 : 12 : result = !(varstr_cmp(VARDATA_ANY(arg1), len1,
2447 : 12 : NameStr(*arg2), len2,
2448 : : collid) == 0);
2449 : :
2450 [ - + ]: 12 : PG_FREE_IF_COPY(arg1, 0);
2451 : :
2452 : 12 : PG_RETURN_BOOL(result);
2453 : : }
2454 : :
2455 : : Datum
2456 : 174340 : btnametextcmp(PG_FUNCTION_ARGS)
2457 : : {
2458 : 174340 : Name arg1 = PG_GETARG_NAME(0);
2459 : 174340 : text *arg2 = PG_GETARG_TEXT_PP(1);
2460 : : int32 result;
2461 : :
2462 : 174340 : result = varstr_cmp(NameStr(*arg1), strlen(NameStr(*arg1)),
2463 : 174340 : VARDATA_ANY(arg2), VARSIZE_ANY_EXHDR(arg2),
2464 : : PG_GET_COLLATION());
2465 : :
2466 [ - + ]: 174340 : PG_FREE_IF_COPY(arg2, 1);
2467 : :
2468 : 174340 : PG_RETURN_INT32(result);
2469 : : }
2470 : :
2471 : : Datum
2472 : 22 : bttextnamecmp(PG_FUNCTION_ARGS)
2473 : : {
2474 : 22 : text *arg1 = PG_GETARG_TEXT_PP(0);
2475 : 22 : Name arg2 = PG_GETARG_NAME(1);
2476 : : int32 result;
2477 : :
2478 : 22 : result = varstr_cmp(VARDATA_ANY(arg1), VARSIZE_ANY_EXHDR(arg1),
2479 : 22 : NameStr(*arg2), strlen(NameStr(*arg2)),
2480 : : PG_GET_COLLATION());
2481 : :
2482 [ - + ]: 22 : PG_FREE_IF_COPY(arg1, 0);
2483 : :
2484 : 22 : PG_RETURN_INT32(result);
2485 : : }
2486 : :
2487 : : #define CmpCall(cmpfunc) \
2488 : : DatumGetInt32(DirectFunctionCall2Coll(cmpfunc, \
2489 : : PG_GET_COLLATION(), \
2490 : : PG_GETARG_DATUM(0), \
2491 : : PG_GETARG_DATUM(1)))
2492 : :
2493 : : Datum
2494 : 60311 : namelttext(PG_FUNCTION_ARGS)
2495 : : {
2496 : 60311 : PG_RETURN_BOOL(CmpCall(btnametextcmp) < 0);
2497 : : }
2498 : :
2499 : : Datum
2500 : 0 : nameletext(PG_FUNCTION_ARGS)
2501 : : {
2502 : 0 : PG_RETURN_BOOL(CmpCall(btnametextcmp) <= 0);
2503 : : }
2504 : :
2505 : : Datum
2506 : 0 : namegttext(PG_FUNCTION_ARGS)
2507 : : {
2508 : 0 : PG_RETURN_BOOL(CmpCall(btnametextcmp) > 0);
2509 : : }
2510 : :
2511 : : Datum
2512 : 55959 : namegetext(PG_FUNCTION_ARGS)
2513 : : {
2514 : 55959 : PG_RETURN_BOOL(CmpCall(btnametextcmp) >= 0);
2515 : : }
2516 : :
2517 : : Datum
2518 : 0 : textltname(PG_FUNCTION_ARGS)
2519 : : {
2520 : 0 : PG_RETURN_BOOL(CmpCall(bttextnamecmp) < 0);
2521 : : }
2522 : :
2523 : : Datum
2524 : 0 : textlename(PG_FUNCTION_ARGS)
2525 : : {
2526 : 0 : PG_RETURN_BOOL(CmpCall(bttextnamecmp) <= 0);
2527 : : }
2528 : :
2529 : : Datum
2530 : 0 : textgtname(PG_FUNCTION_ARGS)
2531 : : {
2532 : 0 : PG_RETURN_BOOL(CmpCall(bttextnamecmp) > 0);
2533 : : }
2534 : :
2535 : : Datum
2536 : 0 : textgename(PG_FUNCTION_ARGS)
2537 : : {
2538 : 0 : PG_RETURN_BOOL(CmpCall(bttextnamecmp) >= 0);
2539 : : }
2540 : :
2541 : : #undef CmpCall
2542 : :
2543 : :
2544 : : /*
2545 : : * The following operators support character-by-character comparison
2546 : : * of text datums, to allow building indexes suitable for LIKE clauses.
2547 : : * Note that the regular texteq/textne comparison operators, and regular
2548 : : * support functions 1 and 2 with "C" collation are assumed to be
2549 : : * compatible with these!
2550 : : */
2551 : :
2552 : : static int
2553 : 107164 : internal_text_pattern_compare(text *arg1, text *arg2)
2554 : : {
2555 : : int result;
2556 : : int len1,
2557 : : len2;
2558 : :
2559 : 107164 : len1 = VARSIZE_ANY_EXHDR(arg1);
2560 : 107164 : len2 = VARSIZE_ANY_EXHDR(arg2);
2561 : :
2562 : 107164 : result = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2));
2563 [ + + ]: 107164 : if (result != 0)
2564 : 107076 : return result;
2565 [ - + ]: 88 : else if (len1 < len2)
2566 : 0 : return -1;
2567 [ + + ]: 88 : else if (len1 > len2)
2568 : 56 : return 1;
2569 : : else
2570 : 32 : return 0;
2571 : : }
2572 : :
2573 : :
2574 : : Datum
2575 : 32112 : text_pattern_lt(PG_FUNCTION_ARGS)
2576 : : {
2577 : 32112 : text *arg1 = PG_GETARG_TEXT_PP(0);
2578 : 32112 : text *arg2 = PG_GETARG_TEXT_PP(1);
2579 : : int result;
2580 : :
2581 : 32112 : result = internal_text_pattern_compare(arg1, arg2);
2582 : :
2583 [ - + ]: 32112 : PG_FREE_IF_COPY(arg1, 0);
2584 [ - + ]: 32112 : PG_FREE_IF_COPY(arg2, 1);
2585 : :
2586 : 32112 : PG_RETURN_BOOL(result < 0);
2587 : : }
2588 : :
2589 : :
2590 : : Datum
2591 : 25006 : text_pattern_le(PG_FUNCTION_ARGS)
2592 : : {
2593 : 25006 : text *arg1 = PG_GETARG_TEXT_PP(0);
2594 : 25006 : text *arg2 = PG_GETARG_TEXT_PP(1);
2595 : : int result;
2596 : :
2597 : 25006 : result = internal_text_pattern_compare(arg1, arg2);
2598 : :
2599 [ - + ]: 25006 : PG_FREE_IF_COPY(arg1, 0);
2600 [ - + ]: 25006 : PG_FREE_IF_COPY(arg2, 1);
2601 : :
2602 : 25006 : PG_RETURN_BOOL(result <= 0);
2603 : : }
2604 : :
2605 : :
2606 : : Datum
2607 : 25022 : text_pattern_ge(PG_FUNCTION_ARGS)
2608 : : {
2609 : 25022 : text *arg1 = PG_GETARG_TEXT_PP(0);
2610 : 25022 : text *arg2 = PG_GETARG_TEXT_PP(1);
2611 : : int result;
2612 : :
2613 : 25022 : result = internal_text_pattern_compare(arg1, arg2);
2614 : :
2615 [ - + ]: 25022 : PG_FREE_IF_COPY(arg1, 0);
2616 [ - + ]: 25022 : PG_FREE_IF_COPY(arg2, 1);
2617 : :
2618 : 25022 : PG_RETURN_BOOL(result >= 0);
2619 : : }
2620 : :
2621 : :
2622 : : Datum
2623 : 25006 : text_pattern_gt(PG_FUNCTION_ARGS)
2624 : : {
2625 : 25006 : text *arg1 = PG_GETARG_TEXT_PP(0);
2626 : 25006 : text *arg2 = PG_GETARG_TEXT_PP(1);
2627 : : int result;
2628 : :
2629 : 25006 : result = internal_text_pattern_compare(arg1, arg2);
2630 : :
2631 [ - + ]: 25006 : PG_FREE_IF_COPY(arg1, 0);
2632 [ - + ]: 25006 : PG_FREE_IF_COPY(arg2, 1);
2633 : :
2634 : 25006 : PG_RETURN_BOOL(result > 0);
2635 : : }
2636 : :
2637 : :
2638 : : Datum
2639 : 18 : bttext_pattern_cmp(PG_FUNCTION_ARGS)
2640 : : {
2641 : 18 : text *arg1 = PG_GETARG_TEXT_PP(0);
2642 : 18 : text *arg2 = PG_GETARG_TEXT_PP(1);
2643 : : int result;
2644 : :
2645 : 18 : result = internal_text_pattern_compare(arg1, arg2);
2646 : :
2647 [ - + ]: 18 : PG_FREE_IF_COPY(arg1, 0);
2648 [ - + ]: 18 : PG_FREE_IF_COPY(arg2, 1);
2649 : :
2650 : 18 : PG_RETURN_INT32(result);
2651 : : }
2652 : :
2653 : :
2654 : : Datum
2655 : 77 : bttext_pattern_sortsupport(PG_FUNCTION_ARGS)
2656 : : {
2657 : 77 : SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
2658 : : MemoryContext oldcontext;
2659 : :
2660 : 77 : oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
2661 : :
2662 : : /* Use generic string SortSupport, forcing "C" collation */
2663 : 77 : varstr_sortsupport(ssup, TEXTOID, C_COLLATION_OID);
2664 : :
2665 : 77 : MemoryContextSwitchTo(oldcontext);
2666 : :
2667 : 77 : PG_RETURN_VOID();
2668 : : }
2669 : :
2670 : :
2671 : : /*
2672 : : * text_name()
2673 : : * Converts a text type to a Name type.
2674 : : */
2675 : : Datum
2676 : 17771 : text_name(PG_FUNCTION_ARGS)
2677 : : {
2678 : 17771 : text *s = PG_GETARG_TEXT_PP(0);
2679 : : Name result;
2680 : : int len;
2681 : :
2682 : 17771 : len = VARSIZE_ANY_EXHDR(s);
2683 : :
2684 : : /* Truncate oversize input */
2685 [ + + ]: 17771 : if (len >= NAMEDATALEN)
2686 : 5 : len = pg_mbcliplen(VARDATA_ANY(s), len, NAMEDATALEN - 1);
2687 : :
2688 : : /* We use palloc0 here to ensure result is zero-padded */
2689 : 17771 : result = (Name) palloc0(NAMEDATALEN);
2690 : 17771 : memcpy(NameStr(*result), VARDATA_ANY(s), len);
2691 : :
2692 : 17771 : PG_RETURN_NAME(result);
2693 : : }
2694 : :
2695 : : /*
2696 : : * name_text()
2697 : : * Converts a Name type to a text type.
2698 : : */
2699 : : Datum
2700 : 425764 : name_text(PG_FUNCTION_ARGS)
2701 : : {
2702 : 425764 : Name s = PG_GETARG_NAME(0);
2703 : :
2704 : 425764 : PG_RETURN_TEXT_P(cstring_to_text(NameStr(*s)));
2705 : : }
2706 : :
2707 : :
2708 : : /*
2709 : : * textToQualifiedNameList - convert a text object to list of names
2710 : : *
2711 : : * This implements the input parsing needed by nextval() and other
2712 : : * functions that take a text parameter representing a qualified name.
2713 : : * We split the name at dots, downcase if not double-quoted, and
2714 : : * truncate names if they're too long.
2715 : : */
2716 : : List *
2717 : 3121 : textToQualifiedNameList(text *textval)
2718 : : {
2719 : : char *rawname;
2720 : 3121 : List *result = NIL;
2721 : : List *namelist;
2722 : : ListCell *l;
2723 : :
2724 : : /* Convert to C string (handles possible detoasting). */
2725 : : /* Note we rely on being able to modify rawname below. */
2726 : 3121 : rawname = text_to_cstring(textval);
2727 : :
2728 [ - + ]: 3121 : if (!SplitIdentifierString(rawname, '.', &namelist))
2729 [ # # ]: 0 : ereport(ERROR,
2730 : : (errcode(ERRCODE_INVALID_NAME),
2731 : : errmsg("invalid name syntax")));
2732 : :
2733 [ - + ]: 3121 : if (namelist == NIL)
2734 [ # # ]: 0 : ereport(ERROR,
2735 : : (errcode(ERRCODE_INVALID_NAME),
2736 : : errmsg("invalid name syntax")));
2737 : :
2738 [ + - + + : 6435 : foreach(l, namelist)
+ + ]
2739 : : {
2740 : 3314 : char *curname = (char *) lfirst(l);
2741 : :
2742 : 3314 : result = lappend(result, makeString(pstrdup(curname)));
2743 : : }
2744 : :
2745 : 3121 : pfree(rawname);
2746 : 3121 : list_free(namelist);
2747 : :
2748 : 3121 : return result;
2749 : : }
2750 : :
2751 : : /*
2752 : : * scan_quoted_identifier - In-place scanner for quoted identifiers.
2753 : : *
2754 : : * *nextp should point to the opening double-quote character, and will be
2755 : : * updated to point just past the end. *endp is set to the position of
2756 : : * the closing quote. The return value is the identifier, or NULL if the
2757 : : * matching close-quote cannot be found.
2758 : : *
2759 : : * If we find two consecutive double quote characters, that doesn't end the
2760 : : * identifier: instead, we collapse them into a double quote and include them
2761 : : * in the resulting token. Note that this requires overwriting the rest of the
2762 : : * string in place, including the portion beyond the final value of *nextp.
2763 : : */
2764 : : char *
2765 : 25287 : scan_quoted_identifier(char **endp, char **nextp)
2766 : : {
2767 : 25287 : char *token = *nextp + 1;
2768 : :
2769 : : for (;;)
2770 : : {
2771 : 25297 : *endp = strchr(*nextp + 1, '"');
2772 [ + + ]: 25292 : if (*endp == NULL)
2773 : 2 : return NULL; /* mismatched quotes */
2774 [ + + ]: 25290 : if ((*endp)[1] != '"')
2775 : 25285 : break; /* found end of quoted identifier */
2776 : : /* Collapse adjacent quotes into one quote, and look again */
2777 : 5 : memmove(*endp, *endp + 1, strlen(*endp));
2778 : 5 : *nextp = *endp;
2779 : : }
2780 : : /* *endp now points at the terminating quote */
2781 : 25285 : *nextp = *endp + 1;
2782 : :
2783 : 25285 : return token;
2784 : : }
2785 : :
2786 : : /*
2787 : : * scan_identifier - In-place scanner for quoted or unquoted identifiers.
2788 : : *
2789 : : * On success, *endp is set to the position where the caller should write '\0'
2790 : : * to null-terminate the token, and *nextp is advanced past the token (and past
2791 : : * the closing quote, if any). The return value is the token content, or NULL
2792 : : * if there is a syntax error (mismatched quotes or empty unquoted token).
2793 : : *
2794 : : * Unquoted identifiers are terminated by whitespace or the first occurrence
2795 : : * of the separator character. Additionally, if downcase_unquoted = true,
2796 : : * unquoted identifiers are downcased in place. See scan_quoted_identifier for
2797 : : * an additional way in which we modify the string in place.
2798 : : */
2799 : : char *
2800 : 366239 : scan_identifier(char **endp, char **nextp, char separator, bool downcase_unquoted)
2801 : : {
2802 : : char *token;
2803 : :
2804 [ + + ]: 366239 : if (**nextp == '"')
2805 : 25287 : return scan_quoted_identifier(endp, nextp);
2806 : :
2807 : : /* Unquoted identifier --- extends to separator or whitespace */
2808 : 340952 : token = *nextp;
2809 : :
2810 [ + + + + : 3120956 : while (**nextp && **nextp != separator && !scanner_isspace(**nextp))
+ + ]
2811 : 2780004 : (*nextp)++;
2812 : :
2813 [ + + ]: 340952 : if (*nextp == token)
2814 : 2 : return NULL; /* empty token */
2815 : :
2816 : 340950 : *endp = *nextp;
2817 : :
2818 [ + + ]: 340950 : if (downcase_unquoted)
2819 : : {
2820 : : /*
2821 : : * Downcase the identifier, using same code as main lexer does.
2822 : : *
2823 : : * XXX because we want to overwrite the input in-place, we cannot
2824 : : * support a downcasing transformation that increases the string
2825 : : * length. This is not a problem given the current implementation of
2826 : : * downcase_truncate_identifier, but we'll probably have to do
2827 : : * something about this someday.
2828 : : */
2829 : 336557 : int len = *endp - token;
2830 : 336557 : char *downname = downcase_truncate_identifier(token, len, false);
2831 : :
2832 : : Assert(strlen(downname) <= len);
2833 : 336557 : strncpy(token, downname, len); /* strncpy is required here */
2834 : 336557 : pfree(downname);
2835 : : }
2836 : :
2837 : 340950 : return token;
2838 : : }
2839 : :
2840 : :
2841 : : /*
2842 : : * SplitIdentifierString --- parse a string containing identifiers
2843 : : *
2844 : : * This is the guts of textToQualifiedNameList, and is exported for use in
2845 : : * other situations such as parsing GUC variables. In the GUC case, it's
2846 : : * important to avoid memory leaks, so the API is designed to minimize the
2847 : : * amount of stuff that needs to be allocated and freed.
2848 : : *
2849 : : * Inputs:
2850 : : * rawstring: the input string; must be overwritable! On return, it's
2851 : : * been modified to contain the separated identifiers.
2852 : : * separator: the separator punctuation expected between identifiers
2853 : : * (typically '.' or ','). Whitespace may also appear around
2854 : : * identifiers.
2855 : : * Outputs:
2856 : : * namelist: filled with a palloc'd list of pointers to identifiers within
2857 : : * rawstring. Caller should list_free() this even on error return.
2858 : : *
2859 : : * Returns true if okay, false if there is a syntax error in the string.
2860 : : *
2861 : : * Note that an empty string is considered okay here, though not in
2862 : : * textToQualifiedNameList.
2863 : : */
2864 : : bool
2865 : 216090 : SplitIdentifierString(char *rawstring, char separator,
2866 : : List **namelist)
2867 : : {
2868 : 216090 : char *nextp = rawstring;
2869 : 216090 : bool done = false;
2870 : :
2871 : 216090 : *namelist = NIL;
2872 : :
2873 [ + + ]: 216094 : while (scanner_isspace(*nextp))
2874 : 4 : nextp++; /* skip leading whitespace */
2875 : :
2876 [ + + ]: 216090 : if (*nextp == '\0')
2877 : 22203 : return true; /* empty string represents empty list */
2878 : :
2879 : : /* At the top of the loop, we are at start of a new identifier. */
2880 : : do
2881 : : {
2882 : : char *curname;
2883 : : char *endp;
2884 : :
2885 : 361780 : curname = scan_identifier(&endp, &nextp, separator, true);
2886 [ - + ]: 361780 : if (curname == NULL)
2887 : 1 : return false; /* mismatched quotes or empty name */
2888 : :
2889 [ + + ]: 361781 : while (scanner_isspace(*nextp))
2890 : 1 : nextp++; /* skip trailing whitespace */
2891 : :
2892 [ + + ]: 361780 : if (*nextp == separator)
2893 : : {
2894 : 167893 : nextp++;
2895 [ + + ]: 321212 : while (scanner_isspace(*nextp))
2896 : 153319 : nextp++; /* skip leading whitespace for next */
2897 : : /* we expect another name, so done remains false */
2898 : : }
2899 [ + + ]: 193887 : else if (*nextp == '\0')
2900 : 193886 : done = true;
2901 : : else
2902 : 1 : return false; /* invalid syntax */
2903 : :
2904 : : /* Now safe to overwrite separator with a null */
2905 : 361779 : *endp = '\0';
2906 : :
2907 : : /* Truncate name if it's overlength */
2908 : 361779 : truncate_identifier(curname, strlen(curname), false);
2909 : :
2910 : : /*
2911 : : * Finished isolating current name --- add it to list
2912 : : */
2913 : 361779 : *namelist = lappend(*namelist, curname);
2914 : :
2915 : : /* Loop back if we didn't reach end of string */
2916 [ + + ]: 361779 : } while (!done);
2917 : :
2918 : 193886 : return true;
2919 : : }
2920 : :
2921 : :
2922 : : /*
2923 : : * SplitDirectoriesString --- parse a string containing file/directory names
2924 : : *
2925 : : * This works fine on file names too; the function name is historical.
2926 : : *
2927 : : * This is similar to SplitIdentifierString, except that the parsing
2928 : : * rules are meant to handle pathnames instead of identifiers: there is
2929 : : * no downcasing, embedded spaces are allowed, the max length is MAXPGPATH-1,
2930 : : * and we apply canonicalize_path() to each extracted string. Because of the
2931 : : * last, the returned strings are separately palloc'd rather than being
2932 : : * pointers into rawstring --- but we still scribble on rawstring.
2933 : : *
2934 : : * Inputs:
2935 : : * rawstring: the input string; must be modifiable!
2936 : : * separator: the separator punctuation expected between directories
2937 : : * (typically ',' or ';'). Whitespace may also appear around
2938 : : * directories.
2939 : : * Outputs:
2940 : : * namelist: filled with a palloc'd list of directory names.
2941 : : * Caller should list_free_deep() this even on error return.
2942 : : *
2943 : : * Returns true if okay, false if there is a syntax error in the string.
2944 : : *
2945 : : * Note that an empty string is considered okay here.
2946 : : */
2947 : : bool
2948 : 1108 : SplitDirectoriesString(char *rawstring, char separator,
2949 : : List **namelist)
2950 : : {
2951 : 1108 : char *nextp = rawstring;
2952 : 1108 : bool done = false;
2953 : :
2954 : 1108 : *namelist = NIL;
2955 : :
2956 [ - + ]: 1108 : while (scanner_isspace(*nextp))
2957 : 0 : nextp++; /* skip leading whitespace */
2958 : :
2959 [ + + ]: 1108 : if (*nextp == '\0')
2960 : 1 : return true; /* empty string represents empty list */
2961 : :
2962 : : /* At the top of the loop, we are at start of a new directory. */
2963 : : do
2964 : : {
2965 : : char *curname;
2966 : : char *endp;
2967 : :
2968 [ - + ]: 1130 : if (*nextp == '"')
2969 : : {
2970 : : /* Quoted name --- collapse quote-quote pairs */
2971 : 0 : curname = scan_quoted_identifier(&endp, &nextp);
2972 [ # # ]: 0 : if (curname == NULL)
2973 : 0 : return false; /* mismatched quotes */
2974 : : }
2975 : : else
2976 : : {
2977 : : /* Unquoted name --- extends to separator or end of string */
2978 : 1130 : curname = endp = nextp;
2979 [ + + + + ]: 18790 : while (*nextp && *nextp != separator)
2980 : : {
2981 : : /* trailing whitespace should not be included in name */
2982 [ + - ]: 17660 : if (!scanner_isspace(*nextp))
2983 : 17660 : endp = nextp + 1;
2984 : 17660 : nextp++;
2985 : : }
2986 [ - + ]: 1130 : if (curname == endp)
2987 : 0 : return false; /* empty unquoted name not allowed */
2988 : : }
2989 : :
2990 [ - + ]: 1130 : while (scanner_isspace(*nextp))
2991 : 0 : nextp++; /* skip trailing whitespace */
2992 : :
2993 [ + + ]: 1130 : if (*nextp == separator)
2994 : : {
2995 : 23 : nextp++;
2996 [ + + ]: 30 : while (scanner_isspace(*nextp))
2997 : 7 : nextp++; /* skip leading whitespace for next */
2998 : : /* we expect another name, so done remains false */
2999 : : }
3000 [ + - ]: 1107 : else if (*nextp == '\0')
3001 : 1107 : done = true;
3002 : : else
3003 : 0 : return false; /* invalid syntax */
3004 : :
3005 : : /* Now safe to overwrite separator with a null */
3006 : 1130 : *endp = '\0';
3007 : :
3008 : : /* Truncate path if it's overlength */
3009 [ - + ]: 1130 : if (strlen(curname) >= MAXPGPATH)
3010 : 0 : curname[MAXPGPATH - 1] = '\0';
3011 : :
3012 : : /*
3013 : : * Finished isolating current name --- add it to list
3014 : : */
3015 : 1130 : curname = pstrdup(curname);
3016 : 1130 : canonicalize_path(curname);
3017 : 1130 : *namelist = lappend(*namelist, curname);
3018 : :
3019 : : /* Loop back if we didn't reach end of string */
3020 [ + + ]: 1130 : } while (!done);
3021 : :
3022 : 1107 : return true;
3023 : : }
3024 : :
3025 : :
3026 : : /*
3027 : : * SplitGUCList --- parse a string containing identifiers or file names
3028 : : *
3029 : : * This is used to split the value of a GUC_LIST_QUOTE GUC variable, without
3030 : : * presuming whether the elements will be taken as identifiers or file names.
3031 : : * We assume the input has already been through flatten_set_variable_args(),
3032 : : * so that we need never downcase (if appropriate, that was done already).
3033 : : * Nor do we ever truncate, since we don't know the correct max length.
3034 : : * We disallow embedded whitespace for simplicity (it shouldn't matter,
3035 : : * because any embedded whitespace should have led to double-quoting).
3036 : : * Otherwise the API is identical to SplitIdentifierString.
3037 : : *
3038 : : * XXX it's annoying to have so many copies of this string-splitting logic.
3039 : : * However, it's not clear that having one function with a bunch of option
3040 : : * flags would be much better.
3041 : : *
3042 : : * XXX there is a version of this function in src/fe_utils/string_utils.c.
3043 : : * Be sure to update that if you have to change this.
3044 : : *
3045 : : * Inputs:
3046 : : * rawstring: the input string; must be overwritable! On return, it's
3047 : : * been modified to contain the separated identifiers.
3048 : : * separator: the separator punctuation expected between identifiers
3049 : : * (typically '.' or ','). Whitespace may also appear around
3050 : : * identifiers.
3051 : : * Outputs:
3052 : : * namelist: filled with a palloc'd list of pointers to identifiers within
3053 : : * rawstring. Caller should list_free() this even on error return.
3054 : : *
3055 : : * Returns true if okay, false if there is a syntax error in the string.
3056 : : */
3057 : : bool
3058 : 5462 : SplitGUCList(char *rawstring, char separator,
3059 : : List **namelist)
3060 : : {
3061 : 5462 : char *nextp = rawstring;
3062 : 5462 : bool done = false;
3063 : :
3064 : 5462 : *namelist = NIL;
3065 : :
3066 [ - + ]: 5462 : while (scanner_isspace(*nextp))
3067 : 0 : nextp++; /* skip leading whitespace */
3068 : :
3069 [ + + ]: 5462 : if (*nextp == '\0')
3070 : 2363 : return true; /* empty string represents empty list */
3071 : :
3072 : : /* At the top of the loop, we are at start of a new identifier. */
3073 : : do
3074 : : {
3075 : : char *curname;
3076 : : char *endp;
3077 : :
3078 : 4409 : curname = scan_identifier(&endp, &nextp, separator, false);
3079 [ - + ]: 4409 : if (curname == NULL)
3080 : 0 : return false; /* mismatched quotes or empty name */
3081 : :
3082 [ - + ]: 4409 : while (scanner_isspace(*nextp))
3083 : 0 : nextp++; /* skip trailing whitespace */
3084 : :
3085 [ + + ]: 4409 : if (*nextp == separator)
3086 : : {
3087 : 1310 : nextp++;
3088 [ + + ]: 2616 : while (scanner_isspace(*nextp))
3089 : 1306 : nextp++; /* skip leading whitespace for next */
3090 : : /* we expect another name, so done remains false */
3091 : : }
3092 [ + - ]: 3099 : else if (*nextp == '\0')
3093 : 3099 : done = true;
3094 : : else
3095 : 0 : return false; /* invalid syntax */
3096 : :
3097 : : /* Now safe to overwrite separator with a null */
3098 : 4409 : *endp = '\0';
3099 : :
3100 : : /*
3101 : : * Finished isolating current name --- add it to list
3102 : : */
3103 : 4409 : *namelist = lappend(*namelist, curname);
3104 : :
3105 : : /* Loop back if we didn't reach end of string */
3106 [ + + ]: 4409 : } while (!done);
3107 : :
3108 : 3099 : return true;
3109 : : }
3110 : :
3111 : : /*
3112 : : * appendStringInfoText
3113 : : *
3114 : : * Append a text to str.
3115 : : * Like appendStringInfoString(str, text_to_cstring(t)) but faster.
3116 : : */
3117 : : static void
3118 : 1259044 : appendStringInfoText(StringInfo str, const text *t)
3119 : : {
3120 : 1259044 : appendBinaryStringInfo(str, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
3121 : 1259044 : }
3122 : :
3123 : : /*
3124 : : * replace_text
3125 : : * replace all occurrences of 'old_sub_str' in 'orig_str'
3126 : : * with 'new_sub_str' to form 'new_str'
3127 : : *
3128 : : * returns 'orig_str' if 'old_sub_str' == '' or 'orig_str' == ''
3129 : : * otherwise returns 'new_str'
3130 : : */
3131 : : Datum
3132 : 978 : replace_text(PG_FUNCTION_ARGS)
3133 : : {
3134 : 978 : text *src_text = PG_GETARG_TEXT_PP(0);
3135 : 978 : text *from_sub_text = PG_GETARG_TEXT_PP(1);
3136 : 978 : text *to_sub_text = PG_GETARG_TEXT_PP(2);
3137 : : int src_text_len;
3138 : : int from_sub_text_len;
3139 : : TextPositionState state;
3140 : : text *ret_text;
3141 : : int chunk_len;
3142 : : char *curr_ptr;
3143 : : char *start_ptr;
3144 : : StringInfoData str;
3145 : : bool found;
3146 : :
3147 : 978 : src_text_len = VARSIZE_ANY_EXHDR(src_text);
3148 : 978 : from_sub_text_len = VARSIZE_ANY_EXHDR(from_sub_text);
3149 : :
3150 : : /* Return unmodified source string if empty source or pattern */
3151 [ + - - + ]: 978 : if (src_text_len < 1 || from_sub_text_len < 1)
3152 : : {
3153 : 0 : PG_RETURN_TEXT_P(src_text);
3154 : : }
3155 : :
3156 : 978 : text_position_setup(src_text, from_sub_text, PG_GET_COLLATION(), &state);
3157 : :
3158 : 978 : found = text_position_next(&state);
3159 : :
3160 : : /* When the from_sub_text is not found, there is nothing to do. */
3161 [ + + ]: 978 : if (!found)
3162 : : {
3163 : 194 : text_position_cleanup(&state);
3164 : 194 : PG_RETURN_TEXT_P(src_text);
3165 : : }
3166 : 784 : curr_ptr = text_position_get_match_ptr(&state);
3167 : 784 : start_ptr = VARDATA_ANY(src_text);
3168 : :
3169 : 784 : initStringInfo(&str);
3170 : :
3171 : : do
3172 : : {
3173 [ - + ]: 4236 : CHECK_FOR_INTERRUPTS();
3174 : :
3175 : : /* copy the data skipped over by last text_position_next() */
3176 : 4236 : chunk_len = curr_ptr - start_ptr;
3177 : 4236 : appendBinaryStringInfo(&str, start_ptr, chunk_len);
3178 : :
3179 : 4236 : appendStringInfoText(&str, to_sub_text);
3180 : :
3181 : 4236 : start_ptr = curr_ptr + state.last_match_len;
3182 : :
3183 : 4236 : found = text_position_next(&state);
3184 [ + + ]: 4236 : if (found)
3185 : 3452 : curr_ptr = text_position_get_match_ptr(&state);
3186 : : }
3187 [ + + ]: 4236 : while (found);
3188 : :
3189 : : /* copy trailing data */
3190 : 784 : chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
3191 : 784 : appendBinaryStringInfo(&str, start_ptr, chunk_len);
3192 : :
3193 : 784 : text_position_cleanup(&state);
3194 : :
3195 : 784 : ret_text = cstring_to_text_with_len(str.data, str.len);
3196 : 784 : pfree(str.data);
3197 : :
3198 : 784 : PG_RETURN_TEXT_P(ret_text);
3199 : : }
3200 : :
3201 : : /*
3202 : : * check_replace_text_has_escape
3203 : : *
3204 : : * Returns 0 if text contains no backslashes that need processing.
3205 : : * Returns 1 if text contains backslashes, but not regexp submatch specifiers.
3206 : : * Returns 2 if text contains regexp submatch specifiers (\1 .. \9).
3207 : : */
3208 : : static int
3209 : 12402 : check_replace_text_has_escape(const text *replace_text)
3210 : : {
3211 : 12402 : int result = 0;
3212 : 12402 : const char *p = VARDATA_ANY(replace_text);
3213 : 12402 : const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
3214 : :
3215 [ + + ]: 24832 : while (p < p_end)
3216 : : {
3217 : : /* Find next escape char, if any. */
3218 : 11740 : p = memchr(p, '\\', p_end - p);
3219 [ + + ]: 11740 : if (p == NULL)
3220 : 11176 : break;
3221 : 564 : p++;
3222 : : /* Note: a backslash at the end doesn't require extra processing. */
3223 [ + - ]: 564 : if (p < p_end)
3224 : : {
3225 [ + + + + ]: 564 : if (*p >= '1' && *p <= '9')
3226 : 536 : return 2; /* Found a submatch specifier, so done */
3227 : 28 : result = 1; /* Found some other sequence, keep looking */
3228 : 28 : p++;
3229 : : }
3230 : : }
3231 : 11866 : return result;
3232 : : }
3233 : :
3234 : : /*
3235 : : * appendStringInfoRegexpSubstr
3236 : : *
3237 : : * Append replace_text to str, substituting regexp back references for
3238 : : * \n escapes. start_ptr is the start of the match in the source string,
3239 : : * at logical character position data_pos.
3240 : : */
3241 : : static void
3242 : 174 : appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
3243 : : regmatch_t *pmatch,
3244 : : char *start_ptr, int data_pos)
3245 : : {
3246 : 174 : const char *p = VARDATA_ANY(replace_text);
3247 : 174 : const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
3248 : :
3249 [ + + ]: 416 : while (p < p_end)
3250 : : {
3251 : 369 : const char *replace_start = p;
3252 : : int so;
3253 : : int eo;
3254 : :
3255 : : /* Find next escape char, if any. */
3256 : 369 : p = memchr(p, '\\', p_end - p);
3257 [ + + ]: 369 : if (p == NULL)
3258 : 122 : p = p_end;
3259 : :
3260 : : /* Copy the text we just scanned over, if any. */
3261 [ + + ]: 369 : if (p > replace_start)
3262 : 229 : appendBinaryStringInfo(str, replace_start, p - replace_start);
3263 : :
3264 : : /* Done if at end of string, else advance over escape char. */
3265 [ + + ]: 369 : if (p >= p_end)
3266 : 122 : break;
3267 : 247 : p++;
3268 : :
3269 [ + + ]: 247 : if (p >= p_end)
3270 : : {
3271 : : /* Escape at very end of input. Treat same as unexpected char */
3272 : 5 : appendStringInfoChar(str, '\\');
3273 : 5 : break;
3274 : : }
3275 : :
3276 [ + + + + ]: 242 : if (*p >= '1' && *p <= '9')
3277 : 198 : {
3278 : : /* Use the back reference of regexp. */
3279 : 198 : int idx = *p - '0';
3280 : :
3281 : 198 : so = pmatch[idx].rm_so;
3282 : 198 : eo = pmatch[idx].rm_eo;
3283 : 198 : p++;
3284 : : }
3285 [ + + ]: 44 : else if (*p == '&')
3286 : : {
3287 : : /* Use the entire matched string. */
3288 : 15 : so = pmatch[0].rm_so;
3289 : 15 : eo = pmatch[0].rm_eo;
3290 : 15 : p++;
3291 : : }
3292 [ + + ]: 29 : else if (*p == '\\')
3293 : : {
3294 : : /* \\ means transfer one \ to output. */
3295 : 24 : appendStringInfoChar(str, '\\');
3296 : 24 : p++;
3297 : 24 : continue;
3298 : : }
3299 : : else
3300 : : {
3301 : : /*
3302 : : * If escape char is not followed by any expected char, just treat
3303 : : * it as ordinary data to copy. (XXX would it be better to throw
3304 : : * an error?)
3305 : : */
3306 : 5 : appendStringInfoChar(str, '\\');
3307 : 5 : continue;
3308 : : }
3309 : :
3310 [ + - + - ]: 213 : if (so >= 0 && eo >= 0)
3311 : : {
3312 : : /*
3313 : : * Copy the text that is back reference of regexp. Note so and eo
3314 : : * are counted in characters not bytes.
3315 : : */
3316 : : char *chunk_start;
3317 : : int chunk_len;
3318 : :
3319 : : Assert(so >= data_pos);
3320 : 213 : chunk_start = start_ptr;
3321 : 213 : chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
3322 : 213 : chunk_len = charlen_to_bytelen(chunk_start, eo - so);
3323 : 213 : appendBinaryStringInfo(str, chunk_start, chunk_len);
3324 : : }
3325 : : }
3326 : 174 : }
3327 : :
3328 : : /*
3329 : : * replace_text_regexp
3330 : : *
3331 : : * replace substring(s) in src_text that match pattern with replace_text.
3332 : : * The replace_text can contain backslash markers to substitute
3333 : : * (parts of) the matched text.
3334 : : *
3335 : : * cflags: regexp compile flags.
3336 : : * collation: collation to use.
3337 : : * search_start: the character (not byte) offset in src_text at which to
3338 : : * begin searching.
3339 : : * n: if 0, replace all matches; if > 0, replace only the N'th match.
3340 : : */
3341 : : text *
3342 : 12402 : replace_text_regexp(text *src_text, text *pattern_text,
3343 : : text *replace_text,
3344 : : int cflags, Oid collation,
3345 : : int search_start, int n)
3346 : : {
3347 : : text *ret_text;
3348 : : regex_t *re;
3349 : 12402 : int src_text_len = VARSIZE_ANY_EXHDR(src_text);
3350 : 12402 : int nmatches = 0;
3351 : : StringInfoData buf;
3352 : : regmatch_t pmatch[10]; /* main match, plus \1 to \9 */
3353 : 12402 : int nmatch = lengthof(pmatch);
3354 : : pg_wchar *data;
3355 : : size_t data_len;
3356 : : int data_pos;
3357 : : char *start_ptr;
3358 : : int escape_status;
3359 : :
3360 : 12402 : initStringInfo(&buf);
3361 : :
3362 : : /* Convert data string to wide characters. */
3363 : 12402 : data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar));
3364 : 12402 : data_len = pg_mb2wchar_with_len(VARDATA_ANY(src_text), data, src_text_len);
3365 : :
3366 : : /* Check whether replace_text has escapes, especially regexp submatches. */
3367 : 12402 : escape_status = check_replace_text_has_escape(replace_text);
3368 : :
3369 : : /* If no regexp submatches, we can use REG_NOSUB. */
3370 [ + + ]: 12402 : if (escape_status < 2)
3371 : : {
3372 : 11866 : cflags |= REG_NOSUB;
3373 : : /* Also tell pg_regexec we only want the whole-match location. */
3374 : 11866 : nmatch = 1;
3375 : : }
3376 : :
3377 : : /* Prepare the regexp. */
3378 : 12402 : re = RE_compile_and_cache(pattern_text, cflags, collation);
3379 : :
3380 : : /* start_ptr points to the data_pos'th character of src_text */
3381 : 12402 : start_ptr = (char *) VARDATA_ANY(src_text);
3382 : 12402 : data_pos = 0;
3383 : :
3384 [ + + ]: 16706 : while (search_start <= data_len)
3385 : : {
3386 : : int regexec_result;
3387 : :
3388 [ - + ]: 16701 : CHECK_FOR_INTERRUPTS();
3389 : :
3390 : 16701 : regexec_result = pg_regexec(re,
3391 : : data,
3392 : : data_len,
3393 : : search_start,
3394 : : NULL, /* no details */
3395 : : nmatch,
3396 : : pmatch,
3397 : : 0);
3398 : :
3399 [ + + ]: 16701 : if (regexec_result == REG_NOMATCH)
3400 : 10953 : break;
3401 : :
3402 [ - + ]: 5748 : if (regexec_result != REG_OKAY)
3403 : : {
3404 : : char errMsg[100];
3405 : :
3406 : 0 : pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
3407 [ # # ]: 0 : ereport(ERROR,
3408 : : (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
3409 : : errmsg("regular expression failed: %s", errMsg)));
3410 : : }
3411 : :
3412 : : /*
3413 : : * Count matches, and decide whether to replace this match.
3414 : : */
3415 : 5748 : nmatches++;
3416 [ + + + + ]: 5748 : if (n > 0 && nmatches != n)
3417 : : {
3418 : : /*
3419 : : * No, so advance search_start, but not start_ptr/data_pos. (Thus,
3420 : : * we treat the matched text as if it weren't matched, and copy it
3421 : : * to the output later.)
3422 : : */
3423 : 50 : search_start = pmatch[0].rm_eo;
3424 [ - + ]: 50 : if (pmatch[0].rm_so == pmatch[0].rm_eo)
3425 : 0 : search_start++;
3426 : 50 : continue;
3427 : : }
3428 : :
3429 : : /*
3430 : : * Copy the text to the left of the match position. Note we are given
3431 : : * character not byte indexes.
3432 : : */
3433 [ + + ]: 5698 : if (pmatch[0].rm_so - data_pos > 0)
3434 : : {
3435 : : int chunk_len;
3436 : :
3437 : 5570 : chunk_len = charlen_to_bytelen(start_ptr,
3438 : 5570 : pmatch[0].rm_so - data_pos);
3439 : 5570 : appendBinaryStringInfo(&buf, start_ptr, chunk_len);
3440 : :
3441 : : /*
3442 : : * Advance start_ptr over that text, to avoid multiple rescans of
3443 : : * it if the replace_text contains multiple back-references.
3444 : : */
3445 : 5570 : start_ptr += chunk_len;
3446 : 5570 : data_pos = pmatch[0].rm_so;
3447 : : }
3448 : :
3449 : : /*
3450 : : * Copy the replace_text, processing escapes if any are present.
3451 : : */
3452 [ + + ]: 5698 : if (escape_status > 0)
3453 : 174 : appendStringInfoRegexpSubstr(&buf, replace_text, pmatch,
3454 : : start_ptr, data_pos);
3455 : : else
3456 : 5524 : appendStringInfoText(&buf, replace_text);
3457 : :
3458 : : /* Advance start_ptr and data_pos over the matched text. */
3459 : 11396 : start_ptr += charlen_to_bytelen(start_ptr,
3460 : 5698 : pmatch[0].rm_eo - data_pos);
3461 : 5698 : data_pos = pmatch[0].rm_eo;
3462 : :
3463 : : /*
3464 : : * If we only want to replace one occurrence, we're done.
3465 : : */
3466 [ + + ]: 5698 : if (n > 0)
3467 : 1444 : break;
3468 : :
3469 : : /*
3470 : : * Advance search position. Normally we start the next search at the
3471 : : * end of the previous match; but if the match was of zero length, we
3472 : : * have to advance by one character, or we'd just find the same match
3473 : : * again.
3474 : : */
3475 : 4254 : search_start = data_pos;
3476 [ + + ]: 4254 : if (pmatch[0].rm_so == pmatch[0].rm_eo)
3477 : 10 : search_start++;
3478 : : }
3479 : :
3480 : : /*
3481 : : * Copy the text to the right of the last match.
3482 : : */
3483 [ + + ]: 12402 : if (data_pos < data_len)
3484 : : {
3485 : : int chunk_len;
3486 : :
3487 : 11775 : chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
3488 : 11775 : appendBinaryStringInfo(&buf, start_ptr, chunk_len);
3489 : : }
3490 : :
3491 : 12402 : ret_text = cstring_to_text_with_len(buf.data, buf.len);
3492 : 12402 : pfree(buf.data);
3493 : 12402 : pfree(data);
3494 : :
3495 : 12402 : return ret_text;
3496 : : }
3497 : :
3498 : : /*
3499 : : * split_part
3500 : : * parse input string based on provided field separator
3501 : : * return N'th item (1 based, negative counts from end)
3502 : : */
3503 : : Datum
3504 : 124 : split_part(PG_FUNCTION_ARGS)
3505 : : {
3506 : 124 : text *inputstring = PG_GETARG_TEXT_PP(0);
3507 : 124 : text *fldsep = PG_GETARG_TEXT_PP(1);
3508 : 124 : int fldnum = PG_GETARG_INT32(2);
3509 : : int inputstring_len;
3510 : : int fldsep_len;
3511 : : TextPositionState state;
3512 : : char *start_ptr;
3513 : : char *end_ptr;
3514 : : text *result_text;
3515 : : bool found;
3516 : :
3517 : : /* field number is 1 based */
3518 [ + + ]: 124 : if (fldnum == 0)
3519 [ + - ]: 4 : ereport(ERROR,
3520 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3521 : : errmsg("field position must not be zero")));
3522 : :
3523 : 120 : inputstring_len = VARSIZE_ANY_EXHDR(inputstring);
3524 : 120 : fldsep_len = VARSIZE_ANY_EXHDR(fldsep);
3525 : :
3526 : : /* return empty string for empty input string */
3527 [ + + ]: 120 : if (inputstring_len < 1)
3528 : 10 : PG_RETURN_TEXT_P(cstring_to_text(""));
3529 : :
3530 : : /* handle empty field separator */
3531 [ + + ]: 110 : if (fldsep_len < 1)
3532 : : {
3533 : : /* if first or last field, return input string, else empty string */
3534 [ + + + + ]: 20 : if (fldnum == 1 || fldnum == -1)
3535 : 10 : PG_RETURN_TEXT_P(inputstring);
3536 : : else
3537 : 10 : PG_RETURN_TEXT_P(cstring_to_text(""));
3538 : : }
3539 : :
3540 : : /* find the first field separator */
3541 : 90 : text_position_setup(inputstring, fldsep, PG_GET_COLLATION(), &state);
3542 : :
3543 : 90 : found = text_position_next(&state);
3544 : :
3545 : : /* special case if fldsep not found at all */
3546 [ + + ]: 90 : if (!found)
3547 : : {
3548 : 18 : text_position_cleanup(&state);
3549 : : /* if first or last field, return input string, else empty string */
3550 [ + + + + ]: 18 : if (fldnum == 1 || fldnum == -1)
3551 : 9 : PG_RETURN_TEXT_P(inputstring);
3552 : : else
3553 : 9 : PG_RETURN_TEXT_P(cstring_to_text(""));
3554 : : }
3555 : :
3556 : : /*
3557 : : * take care of a negative field number (i.e. count from the right) by
3558 : : * converting to a positive field number; we need total number of fields
3559 : : */
3560 [ + + ]: 72 : if (fldnum < 0)
3561 : : {
3562 : : /* we found a fldsep, so there are at least two fields */
3563 : 36 : int numfields = 2;
3564 : :
3565 [ + + ]: 54 : while (text_position_next(&state))
3566 : 18 : numfields++;
3567 : :
3568 : : /* special case of last field does not require an extra pass */
3569 [ + + ]: 36 : if (fldnum == -1)
3570 : : {
3571 : 17 : start_ptr = text_position_get_match_ptr(&state) + state.last_match_len;
3572 : 17 : end_ptr = VARDATA_ANY(inputstring) + inputstring_len;
3573 : 17 : text_position_cleanup(&state);
3574 : 17 : PG_RETURN_TEXT_P(cstring_to_text_with_len(start_ptr,
3575 : : end_ptr - start_ptr));
3576 : : }
3577 : :
3578 : : /* else, convert fldnum to positive notation */
3579 : 19 : fldnum += numfields + 1;
3580 : :
3581 : : /* if nonexistent field, return empty string */
3582 [ + + ]: 19 : if (fldnum <= 0)
3583 : : {
3584 : 5 : text_position_cleanup(&state);
3585 : 5 : PG_RETURN_TEXT_P(cstring_to_text(""));
3586 : : }
3587 : :
3588 : : /* reset to pointing at first match, but now with positive fldnum */
3589 : 14 : text_position_reset(&state);
3590 : 14 : found = text_position_next(&state);
3591 : : Assert(found);
3592 : : }
3593 : :
3594 : : /* identify bounds of first field */
3595 : 50 : start_ptr = VARDATA_ANY(inputstring);
3596 : 50 : end_ptr = text_position_get_match_ptr(&state);
3597 : :
3598 [ + + + + ]: 99 : while (found && --fldnum > 0)
3599 : : {
3600 : : /* identify bounds of next field */
3601 : 49 : start_ptr = end_ptr + state.last_match_len;
3602 : 49 : found = text_position_next(&state);
3603 [ + + ]: 49 : if (found)
3604 : 27 : end_ptr = text_position_get_match_ptr(&state);
3605 : : }
3606 : :
3607 : 50 : text_position_cleanup(&state);
3608 : :
3609 [ + + ]: 50 : if (fldnum > 0)
3610 : : {
3611 : : /* N'th field separator not found */
3612 : : /* if last field requested, return it, else empty string */
3613 [ + + ]: 22 : if (fldnum == 1)
3614 : : {
3615 : 17 : int last_len = start_ptr - VARDATA_ANY(inputstring);
3616 : :
3617 : 17 : result_text = cstring_to_text_with_len(start_ptr,
3618 : : inputstring_len - last_len);
3619 : : }
3620 : : else
3621 : 5 : result_text = cstring_to_text("");
3622 : : }
3623 : : else
3624 : : {
3625 : : /* non-last field requested */
3626 : 28 : result_text = cstring_to_text_with_len(start_ptr, end_ptr - start_ptr);
3627 : : }
3628 : :
3629 : 50 : PG_RETURN_TEXT_P(result_text);
3630 : : }
3631 : :
3632 : : /*
3633 : : * Convenience function to return true when two text params are equal.
3634 : : */
3635 : : static bool
3636 : 306 : text_isequal(text *txt1, text *txt2, Oid collid)
3637 : : {
3638 : 306 : return DatumGetBool(DirectFunctionCall2Coll(texteq,
3639 : : collid,
3640 : : PointerGetDatum(txt1),
3641 : : PointerGetDatum(txt2)));
3642 : : }
3643 : :
3644 : : /*
3645 : : * text_to_array
3646 : : * parse input string and return text array of elements,
3647 : : * based on provided field separator
3648 : : */
3649 : : Datum
3650 : 136 : text_to_array(PG_FUNCTION_ARGS)
3651 : : {
3652 : : SplitTextOutputData tstate;
3653 : :
3654 : : /* For array output, tstate should start as all zeroes */
3655 : 136 : memset(&tstate, 0, sizeof(tstate));
3656 : :
3657 [ + + ]: 136 : if (!split_text(fcinfo, &tstate))
3658 : 5 : PG_RETURN_NULL();
3659 : :
3660 [ + + ]: 131 : if (tstate.astate == NULL)
3661 : 5 : PG_RETURN_ARRAYTYPE_P(construct_empty_array(TEXTOID));
3662 : :
3663 : 126 : PG_RETURN_DATUM(makeArrayResult(tstate.astate,
3664 : : CurrentMemoryContext));
3665 : : }
3666 : :
3667 : : /*
3668 : : * text_to_array_null
3669 : : * parse input string and return text array of elements,
3670 : : * based on provided field separator and null string
3671 : : *
3672 : : * This is a separate entry point only to prevent the regression tests from
3673 : : * complaining about different argument sets for the same internal function.
3674 : : */
3675 : : Datum
3676 : 50 : text_to_array_null(PG_FUNCTION_ARGS)
3677 : : {
3678 : 50 : return text_to_array(fcinfo);
3679 : : }
3680 : :
3681 : : /*
3682 : : * text_to_table
3683 : : * parse input string and return table of elements,
3684 : : * based on provided field separator
3685 : : */
3686 : : Datum
3687 : 56 : text_to_table(PG_FUNCTION_ARGS)
3688 : : {
3689 : 56 : ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3690 : : SplitTextOutputData tstate;
3691 : :
3692 : 56 : tstate.astate = NULL;
3693 : 56 : InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC);
3694 : 56 : tstate.tupstore = rsi->setResult;
3695 : 56 : tstate.tupdesc = rsi->setDesc;
3696 : :
3697 : 56 : (void) split_text(fcinfo, &tstate);
3698 : :
3699 : 56 : return (Datum) 0;
3700 : : }
3701 : :
3702 : : /*
3703 : : * text_to_table_null
3704 : : * parse input string and return table of elements,
3705 : : * based on provided field separator and null string
3706 : : *
3707 : : * This is a separate entry point only to prevent the regression tests from
3708 : : * complaining about different argument sets for the same internal function.
3709 : : */
3710 : : Datum
3711 : 16 : text_to_table_null(PG_FUNCTION_ARGS)
3712 : : {
3713 : 16 : return text_to_table(fcinfo);
3714 : : }
3715 : :
3716 : : /*
3717 : : * Common code for text_to_array, text_to_array_null, text_to_table
3718 : : * and text_to_table_null functions.
3719 : : *
3720 : : * These are not strict so we have to test for null inputs explicitly.
3721 : : * Returns false if result is to be null, else returns true.
3722 : : *
3723 : : * Note that if the result is valid but empty (zero elements), we return
3724 : : * without changing *tstate --- caller must handle that case, too.
3725 : : */
3726 : : static bool
3727 : 192 : split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate)
3728 : : {
3729 : : text *inputstring;
3730 : : text *fldsep;
3731 : : text *null_string;
3732 : 192 : Oid collation = PG_GET_COLLATION();
3733 : : int inputstring_len;
3734 : : int fldsep_len;
3735 : : char *start_ptr;
3736 : : text *result_text;
3737 : :
3738 : : /* when input string is NULL, then result is NULL too */
3739 [ + + ]: 192 : if (PG_ARGISNULL(0))
3740 : 9 : return false;
3741 : :
3742 : 183 : inputstring = PG_GETARG_TEXT_PP(0);
3743 : :
3744 : : /* fldsep can be NULL */
3745 [ + + ]: 183 : if (!PG_ARGISNULL(1))
3746 : 159 : fldsep = PG_GETARG_TEXT_PP(1);
3747 : : else
3748 : 24 : fldsep = NULL;
3749 : :
3750 : : /* null_string can be NULL or omitted */
3751 [ + + + - ]: 183 : if (PG_NARGS() > 2 && !PG_ARGISNULL(2))
3752 : 66 : null_string = PG_GETARG_TEXT_PP(2);
3753 : : else
3754 : 117 : null_string = NULL;
3755 : :
3756 [ + + ]: 183 : if (fldsep != NULL)
3757 : : {
3758 : : /*
3759 : : * Normal case with non-null fldsep. Use the text_position machinery
3760 : : * to search for occurrences of fldsep.
3761 : : */
3762 : : TextPositionState state;
3763 : :
3764 : 159 : inputstring_len = VARSIZE_ANY_EXHDR(inputstring);
3765 : 159 : fldsep_len = VARSIZE_ANY_EXHDR(fldsep);
3766 : :
3767 : : /* return empty set for empty input string */
3768 [ + + ]: 159 : if (inputstring_len < 1)
3769 : 46 : return true;
3770 : :
3771 : : /* empty field separator: return input string as a one-element set */
3772 [ + + ]: 150 : if (fldsep_len < 1)
3773 : : {
3774 : 37 : split_text_accum_result(tstate, inputstring,
3775 : : null_string, collation);
3776 : 37 : return true;
3777 : : }
3778 : :
3779 : 113 : text_position_setup(inputstring, fldsep, collation, &state);
3780 : :
3781 : 113 : start_ptr = VARDATA_ANY(inputstring);
3782 : :
3783 : : for (;;)
3784 : 371 : {
3785 : : bool found;
3786 : : char *end_ptr;
3787 : : int chunk_len;
3788 : :
3789 [ - + ]: 484 : CHECK_FOR_INTERRUPTS();
3790 : :
3791 : 484 : found = text_position_next(&state);
3792 [ + + ]: 484 : if (!found)
3793 : : {
3794 : : /* fetch last field */
3795 : 113 : chunk_len = ((char *) inputstring + VARSIZE_ANY(inputstring)) - start_ptr;
3796 : 113 : end_ptr = NULL; /* not used, but some compilers complain */
3797 : : }
3798 : : else
3799 : : {
3800 : : /* fetch non-last field */
3801 : 371 : end_ptr = text_position_get_match_ptr(&state);
3802 : 371 : chunk_len = end_ptr - start_ptr;
3803 : : }
3804 : :
3805 : : /* build a temp text datum to pass to split_text_accum_result */
3806 : 484 : result_text = cstring_to_text_with_len(start_ptr, chunk_len);
3807 : :
3808 : : /* stash away this field */
3809 : 484 : split_text_accum_result(tstate, result_text,
3810 : : null_string, collation);
3811 : :
3812 : 484 : pfree(result_text);
3813 : :
3814 [ + + ]: 484 : if (!found)
3815 : 113 : break;
3816 : :
3817 : 371 : start_ptr = end_ptr + state.last_match_len;
3818 : : }
3819 : :
3820 : 113 : text_position_cleanup(&state);
3821 : : }
3822 : : else
3823 : : {
3824 : : const char *end_ptr;
3825 : :
3826 : : /*
3827 : : * When fldsep is NULL, each character in the input string becomes a
3828 : : * separate element in the result set. The separator is effectively
3829 : : * the space between characters.
3830 : : */
3831 : 24 : inputstring_len = VARSIZE_ANY_EXHDR(inputstring);
3832 : :
3833 : 24 : start_ptr = VARDATA_ANY(inputstring);
3834 : 24 : end_ptr = start_ptr + inputstring_len;
3835 : :
3836 [ + + ]: 204 : while (inputstring_len > 0)
3837 : : {
3838 : 180 : int chunk_len = pg_mblen_range(start_ptr, end_ptr);
3839 : :
3840 [ - + ]: 180 : CHECK_FOR_INTERRUPTS();
3841 : :
3842 : : /* build a temp text datum to pass to split_text_accum_result */
3843 : 180 : result_text = cstring_to_text_with_len(start_ptr, chunk_len);
3844 : :
3845 : : /* stash away this field */
3846 : 180 : split_text_accum_result(tstate, result_text,
3847 : : null_string, collation);
3848 : :
3849 : 180 : pfree(result_text);
3850 : :
3851 : 180 : start_ptr += chunk_len;
3852 : 180 : inputstring_len -= chunk_len;
3853 : : }
3854 : : }
3855 : :
3856 : 137 : return true;
3857 : : }
3858 : :
3859 : : /*
3860 : : * Add text item to result set (table or array).
3861 : : *
3862 : : * This is also responsible for checking to see if the item matches
3863 : : * the null_string, in which case we should emit NULL instead.
3864 : : */
3865 : : static void
3866 : 701 : split_text_accum_result(SplitTextOutputData *tstate,
3867 : : text *field_value,
3868 : : text *null_string,
3869 : : Oid collation)
3870 : : {
3871 : 701 : bool is_null = false;
3872 : :
3873 [ + + + + ]: 701 : if (null_string && text_isequal(field_value, null_string, collation))
3874 : 56 : is_null = true;
3875 : :
3876 [ + + ]: 701 : if (tstate->tupstore)
3877 : : {
3878 : : Datum values[1];
3879 : : bool nulls[1];
3880 : :
3881 : 152 : values[0] = PointerGetDatum(field_value);
3882 : 152 : nulls[0] = is_null;
3883 : :
3884 : 152 : tuplestore_putvalues(tstate->tupstore,
3885 : : tstate->tupdesc,
3886 : : values,
3887 : : nulls);
3888 : : }
3889 : : else
3890 : : {
3891 : 549 : tstate->astate = accumArrayResult(tstate->astate,
3892 : : PointerGetDatum(field_value),
3893 : : is_null,
3894 : : TEXTOID,
3895 : : CurrentMemoryContext);
3896 : : }
3897 : 701 : }
3898 : :
3899 : : /*
3900 : : * array_to_text
3901 : : * concatenate Cstring representation of input array elements
3902 : : * using provided field separator
3903 : : */
3904 : : Datum
3905 : 43938 : array_to_text(PG_FUNCTION_ARGS)
3906 : : {
3907 : 43938 : ArrayType *v = PG_GETARG_ARRAYTYPE_P(0);
3908 : 43938 : char *fldsep = text_to_cstring(PG_GETARG_TEXT_PP(1));
3909 : :
3910 : 43938 : PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, NULL));
3911 : : }
3912 : :
3913 : : /*
3914 : : * array_to_text_null
3915 : : * concatenate Cstring representation of input array elements
3916 : : * using provided field separator and null string
3917 : : *
3918 : : * This version is not strict so we have to test for null inputs explicitly.
3919 : : */
3920 : : Datum
3921 : 8 : array_to_text_null(PG_FUNCTION_ARGS)
3922 : : {
3923 : : ArrayType *v;
3924 : : char *fldsep;
3925 : : char *null_string;
3926 : :
3927 : : /* returns NULL when first or second parameter is NULL */
3928 [ + - - + ]: 8 : if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
3929 : 0 : PG_RETURN_NULL();
3930 : :
3931 : 8 : v = PG_GETARG_ARRAYTYPE_P(0);
3932 : 8 : fldsep = text_to_cstring(PG_GETARG_TEXT_PP(1));
3933 : :
3934 : : /* NULL null string is passed through as a null pointer */
3935 [ + + ]: 8 : if (!PG_ARGISNULL(2))
3936 : 4 : null_string = text_to_cstring(PG_GETARG_TEXT_PP(2));
3937 : : else
3938 : 4 : null_string = NULL;
3939 : :
3940 : 8 : PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, null_string));
3941 : : }
3942 : :
3943 : : /*
3944 : : * common code for array_to_text and array_to_text_null functions
3945 : : */
3946 : : static text *
3947 : 43958 : array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v,
3948 : : const char *fldsep, const char *null_string)
3949 : : {
3950 : : text *result;
3951 : : int nitems,
3952 : : *dims,
3953 : : ndims;
3954 : : Oid element_type;
3955 : : int typlen;
3956 : : bool typbyval;
3957 : : char typalign;
3958 : : uint8 typalignby;
3959 : : StringInfoData buf;
3960 : 43958 : bool printed = false;
3961 : : char *p;
3962 : : uint8 *bitmap;
3963 : : int bitmask;
3964 : : int i;
3965 : : ArrayMetaState *my_extra;
3966 : :
3967 : 43958 : ndims = ARR_NDIM(v);
3968 : 43958 : dims = ARR_DIMS(v);
3969 : 43958 : nitems = ArrayGetNItems(ndims, dims);
3970 : :
3971 : : /* if there are no elements, return an empty string */
3972 [ + + ]: 43958 : if (nitems == 0)
3973 : 27211 : return cstring_to_text_with_len("", 0);
3974 : :
3975 : 16747 : element_type = ARR_ELEMTYPE(v);
3976 : 16747 : initStringInfo(&buf);
3977 : :
3978 : : /*
3979 : : * We arrange to look up info about element type, including its output
3980 : : * conversion proc, only once per series of calls, assuming the element
3981 : : * type doesn't change underneath us.
3982 : : */
3983 : 16747 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3984 [ + + ]: 16747 : if (my_extra == NULL)
3985 : : {
3986 : 885 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
3987 : : sizeof(ArrayMetaState));
3988 : 885 : my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3989 : 885 : my_extra->element_type = ~element_type;
3990 : : }
3991 : :
3992 [ + + ]: 16747 : if (my_extra->element_type != element_type)
3993 : : {
3994 : : /*
3995 : : * Get info about element type, including its output conversion proc
3996 : : */
3997 : 885 : get_type_io_data(element_type, IOFunc_output,
3998 : : &my_extra->typlen, &my_extra->typbyval,
3999 : : &my_extra->typalign, &my_extra->typdelim,
4000 : : &my_extra->typioparam, &my_extra->typiofunc);
4001 : 885 : fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
4002 : 885 : fcinfo->flinfo->fn_mcxt);
4003 : 885 : my_extra->element_type = element_type;
4004 : : }
4005 : 16747 : typlen = my_extra->typlen;
4006 : 16747 : typbyval = my_extra->typbyval;
4007 : 16747 : typalign = my_extra->typalign;
4008 : 16747 : typalignby = typalign_to_alignby(typalign);
4009 : :
4010 [ + + ]: 16747 : p = ARR_DATA_PTR(v);
4011 [ + + ]: 16747 : bitmap = ARR_NULLBITMAP(v);
4012 : 16747 : bitmask = 1;
4013 : :
4014 [ + + ]: 56666 : for (i = 0; i < nitems; i++)
4015 : : {
4016 : : Datum itemvalue;
4017 : : char *value;
4018 : :
4019 : : /* Get source element, checking for NULL */
4020 [ + + + + ]: 39919 : if (bitmap && (*bitmap & bitmask) == 0)
4021 : : {
4022 : : /* if null_string is NULL, we just ignore null elements */
4023 [ + + ]: 12 : if (null_string != NULL)
4024 : : {
4025 [ + - ]: 4 : if (printed)
4026 : 4 : appendStringInfo(&buf, "%s%s", fldsep, null_string);
4027 : : else
4028 : 0 : appendStringInfoString(&buf, null_string);
4029 : 4 : printed = true;
4030 : : }
4031 : : }
4032 : : else
4033 : : {
4034 : 39907 : itemvalue = fetch_att(p, typbyval, typlen);
4035 : :
4036 : 39907 : value = OutputFunctionCall(&my_extra->proc, itemvalue);
4037 : :
4038 [ + + ]: 39907 : if (printed)
4039 : 23160 : appendStringInfo(&buf, "%s%s", fldsep, value);
4040 : : else
4041 : 16747 : appendStringInfoString(&buf, value);
4042 : 39907 : printed = true;
4043 : :
4044 [ + + + - ]: 39907 : p = att_addlength_pointer(p, typlen, p);
4045 : 39907 : p = (char *) att_nominal_alignby(p, typalignby);
4046 : : }
4047 : :
4048 : : /* advance bitmap pointer if any */
4049 [ + + ]: 39919 : if (bitmap)
4050 : : {
4051 : 72 : bitmask <<= 1;
4052 [ - + ]: 72 : if (bitmask == 0x100)
4053 : : {
4054 : 0 : bitmap++;
4055 : 0 : bitmask = 1;
4056 : : }
4057 : : }
4058 : : }
4059 : :
4060 : 16747 : result = cstring_to_text_with_len(buf.data, buf.len);
4061 : 16747 : pfree(buf.data);
4062 : :
4063 : 16747 : return result;
4064 : : }
4065 : :
4066 : : /*
4067 : : * Workhorse for to_bin, to_oct, and to_hex. Note that base must be > 1 and <=
4068 : : * 16.
4069 : : */
4070 : : static inline text *
4071 : 20389 : convert_to_base(uint64 value, int base)
4072 : : {
4073 : 20389 : const char *digits = "0123456789abcdef";
4074 : :
4075 : : /* We size the buffer for to_bin's longest possible return value. */
4076 : : char buf[sizeof(uint64) * BITS_PER_BYTE];
4077 : 20389 : char *const end = buf + sizeof(buf);
4078 : 20389 : char *ptr = end;
4079 : :
4080 : : Assert(base > 1);
4081 : : Assert(base <= 16);
4082 : :
4083 : : do
4084 : : {
4085 : 40307 : *--ptr = digits[value % base];
4086 : 40307 : value /= base;
4087 [ + + + + ]: 40307 : } while (ptr > buf && value);
4088 : :
4089 : 20389 : return cstring_to_text_with_len(ptr, end - ptr);
4090 : : }
4091 : :
4092 : : /*
4093 : : * Convert an integer to a string containing a base-2 (binary) representation
4094 : : * of the number.
4095 : : */
4096 : : Datum
4097 : 10 : to_bin32(PG_FUNCTION_ARGS)
4098 : : {
4099 : 10 : uint64 value = (uint32) PG_GETARG_INT32(0);
4100 : :
4101 : 10 : PG_RETURN_TEXT_P(convert_to_base(value, 2));
4102 : : }
4103 : : Datum
4104 : 10 : to_bin64(PG_FUNCTION_ARGS)
4105 : : {
4106 : 10 : uint64 value = (uint64) PG_GETARG_INT64(0);
4107 : :
4108 : 10 : PG_RETURN_TEXT_P(convert_to_base(value, 2));
4109 : : }
4110 : :
4111 : : /*
4112 : : * Convert an integer to a string containing a base-8 (oct) representation of
4113 : : * the number.
4114 : : */
4115 : : Datum
4116 : 10 : to_oct32(PG_FUNCTION_ARGS)
4117 : : {
4118 : 10 : uint64 value = (uint32) PG_GETARG_INT32(0);
4119 : :
4120 : 10 : PG_RETURN_TEXT_P(convert_to_base(value, 8));
4121 : : }
4122 : : Datum
4123 : 10 : to_oct64(PG_FUNCTION_ARGS)
4124 : : {
4125 : 10 : uint64 value = (uint64) PG_GETARG_INT64(0);
4126 : :
4127 : 10 : PG_RETURN_TEXT_P(convert_to_base(value, 8));
4128 : : }
4129 : :
4130 : : /*
4131 : : * Convert an integer to a string containing a base-16 (hex) representation of
4132 : : * the number.
4133 : : */
4134 : : Datum
4135 : 20339 : to_hex32(PG_FUNCTION_ARGS)
4136 : : {
4137 : 20339 : uint64 value = (uint32) PG_GETARG_INT32(0);
4138 : :
4139 : 20339 : PG_RETURN_TEXT_P(convert_to_base(value, 16));
4140 : : }
4141 : : Datum
4142 : 10 : to_hex64(PG_FUNCTION_ARGS)
4143 : : {
4144 : 10 : uint64 value = (uint64) PG_GETARG_INT64(0);
4145 : :
4146 : 10 : PG_RETURN_TEXT_P(convert_to_base(value, 16));
4147 : : }
4148 : :
4149 : : /*
4150 : : * Return the size of a datum, possibly compressed
4151 : : *
4152 : : * Works on any data type
4153 : : */
4154 : : Datum
4155 : 71 : pg_column_size(PG_FUNCTION_ARGS)
4156 : : {
4157 : 71 : Datum value = PG_GETARG_DATUM(0);
4158 : : int32 result;
4159 : : int typlen;
4160 : :
4161 : : /* On first call, get the input type's typlen, and save at *fn_extra */
4162 [ + - ]: 71 : if (fcinfo->flinfo->fn_extra == NULL)
4163 : : {
4164 : : /* Lookup the datatype of the supplied argument */
4165 : 71 : Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4166 : :
4167 : 71 : typlen = get_typlen(argtypeid);
4168 [ - + ]: 71 : if (typlen == 0) /* should not happen */
4169 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", argtypeid);
4170 : :
4171 : 71 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4172 : : sizeof(int));
4173 : 71 : *((int *) fcinfo->flinfo->fn_extra) = typlen;
4174 : : }
4175 : : else
4176 : 0 : typlen = *((int *) fcinfo->flinfo->fn_extra);
4177 : :
4178 [ + - ]: 71 : if (typlen == -1)
4179 : : {
4180 : : /* varlena type, possibly toasted */
4181 : 71 : result = toast_datum_size(value);
4182 : : }
4183 [ # # ]: 0 : else if (typlen == -2)
4184 : : {
4185 : : /* cstring */
4186 : 0 : result = strlen(DatumGetCString(value)) + 1;
4187 : : }
4188 : : else
4189 : : {
4190 : : /* ordinary fixed-width type */
4191 : 0 : result = typlen;
4192 : : }
4193 : :
4194 : 71 : PG_RETURN_INT32(result);
4195 : : }
4196 : :
4197 : : /*
4198 : : * Return the compression method stored in the compressed attribute. Return
4199 : : * NULL for non varlena type or uncompressed data.
4200 : : */
4201 : : Datum
4202 : 150 : pg_column_compression(PG_FUNCTION_ARGS)
4203 : : {
4204 : : int typlen;
4205 : : char *result;
4206 : : ToastCompressionId cmid;
4207 : :
4208 : : /* On first call, get the input type's typlen, and save at *fn_extra */
4209 [ + + ]: 150 : if (fcinfo->flinfo->fn_extra == NULL)
4210 : : {
4211 : : /* Lookup the datatype of the supplied argument */
4212 : 123 : Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4213 : :
4214 : 123 : typlen = get_typlen(argtypeid);
4215 [ - + ]: 123 : if (typlen == 0) /* should not happen */
4216 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", argtypeid);
4217 : :
4218 : 123 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4219 : : sizeof(int));
4220 : 123 : *((int *) fcinfo->flinfo->fn_extra) = typlen;
4221 : : }
4222 : : else
4223 : 27 : typlen = *((int *) fcinfo->flinfo->fn_extra);
4224 : :
4225 [ - + ]: 150 : if (typlen != -1)
4226 : 0 : PG_RETURN_NULL();
4227 : :
4228 : : /* get the compression method id stored in the compressed varlena */
4229 : 150 : cmid = toast_get_compression_id((varlena *)
4230 : 150 : DatumGetPointer(PG_GETARG_DATUM(0)));
4231 [ + + ]: 150 : if (cmid == TOAST_INVALID_COMPRESSION_ID)
4232 : 39 : PG_RETURN_NULL();
4233 : :
4234 : : /* convert compression method id to compression method name */
4235 [ + + - ]: 111 : switch (cmid)
4236 : : {
4237 : 67 : case TOAST_PGLZ_COMPRESSION_ID:
4238 : 67 : result = "pglz";
4239 : 67 : break;
4240 : 44 : case TOAST_LZ4_COMPRESSION_ID:
4241 : 44 : result = "lz4";
4242 : 44 : break;
4243 : 0 : default:
4244 [ # # ]: 0 : elog(ERROR, "invalid compression method id %d", cmid);
4245 : : }
4246 : :
4247 : 111 : PG_RETURN_TEXT_P(cstring_to_text(result));
4248 : : }
4249 : :
4250 : : /*
4251 : : * Return the chunk_id of the on-disk TOASTed value. Return NULL if the value
4252 : : * is un-TOASTed or not on-disk.
4253 : : */
4254 : : Datum
4255 : 133 : pg_column_toast_chunk_id(PG_FUNCTION_ARGS)
4256 : : {
4257 : : int typlen;
4258 : : varlena *attr;
4259 : : toast_external_data toast_ext_data;
4260 : :
4261 : : /* On first call, get the input type's typlen, and save at *fn_extra */
4262 [ + + ]: 133 : if (fcinfo->flinfo->fn_extra == NULL)
4263 : : {
4264 : : /* Lookup the datatype of the supplied argument */
4265 : 39 : Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4266 : :
4267 : 39 : typlen = get_typlen(argtypeid);
4268 [ - + ]: 39 : if (typlen == 0) /* should not happen */
4269 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", argtypeid);
4270 : :
4271 : 39 : fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4272 : : sizeof(int));
4273 : 39 : *((int *) fcinfo->flinfo->fn_extra) = typlen;
4274 : : }
4275 : : else
4276 : 94 : typlen = *((int *) fcinfo->flinfo->fn_extra);
4277 : :
4278 [ - + ]: 133 : if (typlen != -1)
4279 : 0 : PG_RETURN_NULL();
4280 : :
4281 : 133 : attr = (varlena *) DatumGetPointer(PG_GETARG_DATUM(0));
4282 : :
4283 [ + + ]: 133 : if (!VARATT_IS_EXTERNAL_ONDISK(attr))
4284 : 42 : PG_RETURN_NULL();
4285 : :
4286 : 91 : toast_external_info_get(attr, &toast_ext_data);
4287 : :
4288 : 91 : PG_RETURN_OID8(toast_ext_data.valueid);
4289 : : }
4290 : :
4291 : : /*
4292 : : * string_agg - Concatenates values and returns string.
4293 : : *
4294 : : * Syntax: string_agg(value text, delimiter text) RETURNS text
4295 : : *
4296 : : * Note: Any NULL values are ignored. The first-call delimiter isn't
4297 : : * actually used at all, and on subsequent calls the delimiter precedes
4298 : : * the associated value.
4299 : : */
4300 : :
4301 : : /* subroutine to initialize state */
4302 : : static StringInfo
4303 : 1576 : makeStringAggState(FunctionCallInfo fcinfo)
4304 : : {
4305 : : StringInfo state;
4306 : : MemoryContext aggcontext;
4307 : : MemoryContext oldcontext;
4308 : :
4309 [ - + ]: 1576 : if (!AggCheckCallContext(fcinfo, &aggcontext))
4310 : : {
4311 : : /* cannot be called directly because of internal-type argument */
4312 [ # # ]: 0 : elog(ERROR, "string_agg_transfn called in non-aggregate context");
4313 : : }
4314 : :
4315 : : /*
4316 : : * Create state in aggregate context. It'll stay there across subsequent
4317 : : * calls.
4318 : : */
4319 : 1576 : oldcontext = MemoryContextSwitchTo(aggcontext);
4320 : 1576 : state = makeStringInfo();
4321 : 1576 : MemoryContextSwitchTo(oldcontext);
4322 : :
4323 : 1576 : return state;
4324 : : }
4325 : :
4326 : : Datum
4327 : 634674 : string_agg_transfn(PG_FUNCTION_ARGS)
4328 : : {
4329 : : StringInfo state;
4330 : :
4331 [ + + ]: 634674 : state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
4332 : :
4333 : : /* Append the value unless null, preceding it with the delimiter. */
4334 [ + + ]: 634674 : if (!PG_ARGISNULL(1))
4335 : : {
4336 : 624642 : text *value = PG_GETARG_TEXT_PP(1);
4337 : 624642 : bool isfirst = false;
4338 : :
4339 : : /*
4340 : : * You might think we can just throw away the first delimiter, however
4341 : : * we must keep it as we may be a parallel worker doing partial
4342 : : * aggregation building a state to send to the main process. We need
4343 : : * to keep the delimiter of every aggregation so that the combine
4344 : : * function can properly join up the strings of two separately
4345 : : * partially aggregated results. The first delimiter is only stripped
4346 : : * off in the final function. To know how much to strip off the front
4347 : : * of the string, we store the length of the first delimiter in the
4348 : : * StringInfo's cursor field, which we don't otherwise need here.
4349 : : */
4350 [ + + ]: 624642 : if (state == NULL)
4351 : : {
4352 : 1356 : state = makeStringAggState(fcinfo);
4353 : 1356 : isfirst = true;
4354 : : }
4355 : :
4356 [ + - ]: 624642 : if (!PG_ARGISNULL(2))
4357 : : {
4358 : 624642 : text *delim = PG_GETARG_TEXT_PP(2);
4359 : :
4360 : 624642 : appendStringInfoText(state, delim);
4361 [ + + ]: 624642 : if (isfirst)
4362 : 1356 : state->cursor = VARSIZE_ANY_EXHDR(delim);
4363 : : }
4364 : :
4365 : 624642 : appendStringInfoText(state, value);
4366 : : }
4367 : :
4368 : : /*
4369 : : * The transition type for string_agg() is declared to be "internal",
4370 : : * which is a pass-by-value type the same size as a pointer.
4371 : : */
4372 [ + + ]: 634674 : if (state)
4373 : 634615 : PG_RETURN_POINTER(state);
4374 : 59 : PG_RETURN_NULL();
4375 : : }
4376 : :
4377 : : /*
4378 : : * string_agg_combine
4379 : : * Aggregate combine function for string_agg(text) and string_agg(bytea)
4380 : : */
4381 : : Datum
4382 : 140 : string_agg_combine(PG_FUNCTION_ARGS)
4383 : : {
4384 : : StringInfo state1;
4385 : : StringInfo state2;
4386 : : MemoryContext agg_context;
4387 : :
4388 [ - + ]: 140 : if (!AggCheckCallContext(fcinfo, &agg_context))
4389 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
4390 : :
4391 [ + + ]: 140 : state1 = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
4392 [ + - ]: 140 : state2 = PG_ARGISNULL(1) ? NULL : (StringInfo) PG_GETARG_POINTER(1);
4393 : :
4394 [ - + ]: 140 : if (state2 == NULL)
4395 : : {
4396 : : /*
4397 : : * NULL state2 is easy, just return state1, which we know is already
4398 : : * in the agg_context
4399 : : */
4400 [ # # ]: 0 : if (state1 == NULL)
4401 : 0 : PG_RETURN_NULL();
4402 : 0 : PG_RETURN_POINTER(state1);
4403 : : }
4404 : :
4405 [ + + ]: 140 : if (state1 == NULL)
4406 : : {
4407 : : /* We must copy state2's data into the agg_context */
4408 : : MemoryContext old_context;
4409 : :
4410 : 80 : old_context = MemoryContextSwitchTo(agg_context);
4411 : 80 : state1 = makeStringAggState(fcinfo);
4412 : 80 : appendBinaryStringInfo(state1, state2->data, state2->len);
4413 : 80 : state1->cursor = state2->cursor;
4414 : 80 : MemoryContextSwitchTo(old_context);
4415 : : }
4416 [ + - ]: 60 : else if (state2->len > 0)
4417 : : {
4418 : : /* Combine ... state1->cursor does not change in this case */
4419 : 60 : appendBinaryStringInfo(state1, state2->data, state2->len);
4420 : : }
4421 : :
4422 : 140 : PG_RETURN_POINTER(state1);
4423 : : }
4424 : :
4425 : : /*
4426 : : * string_agg_serialize
4427 : : * Aggregate serialize function for string_agg(text) and string_agg(bytea)
4428 : : *
4429 : : * This is strict, so we need not handle NULL input
4430 : : */
4431 : : Datum
4432 : 140 : string_agg_serialize(PG_FUNCTION_ARGS)
4433 : : {
4434 : : StringInfo state;
4435 : : StringInfoData buf;
4436 : : bytea *result;
4437 : :
4438 : : /* cannot be called directly because of internal-type argument */
4439 : : Assert(AggCheckCallContext(fcinfo, NULL));
4440 : :
4441 : 140 : state = (StringInfo) PG_GETARG_POINTER(0);
4442 : :
4443 : 140 : pq_begintypsend(&buf);
4444 : :
4445 : : /* cursor */
4446 : 140 : pq_sendint(&buf, state->cursor, 4);
4447 : :
4448 : : /* data */
4449 : 140 : pq_sendbytes(&buf, state->data, state->len);
4450 : :
4451 : 140 : result = pq_endtypsend(&buf);
4452 : :
4453 : 140 : PG_RETURN_BYTEA_P(result);
4454 : : }
4455 : :
4456 : : /*
4457 : : * string_agg_deserialize
4458 : : * Aggregate deserial function for string_agg(text) and string_agg(bytea)
4459 : : *
4460 : : * This is strict, so we need not handle NULL input
4461 : : */
4462 : : Datum
4463 : 140 : string_agg_deserialize(PG_FUNCTION_ARGS)
4464 : : {
4465 : : bytea *sstate;
4466 : : StringInfo result;
4467 : : StringInfoData buf;
4468 : : const char *data;
4469 : : int datalen;
4470 : :
4471 : : /* cannot be called directly because of internal-type argument */
4472 : : Assert(AggCheckCallContext(fcinfo, NULL));
4473 : :
4474 : 140 : sstate = PG_GETARG_BYTEA_PP(0);
4475 : :
4476 : : /*
4477 : : * Initialize a StringInfo so that we can "receive" it using the standard
4478 : : * recv-function infrastructure.
4479 : : */
4480 : 140 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
4481 : 140 : VARSIZE_ANY_EXHDR(sstate));
4482 : :
4483 : 140 : result = makeStringAggState(fcinfo);
4484 : :
4485 : : /* cursor */
4486 : 140 : result->cursor = pq_getmsgint(&buf, 4);
4487 : :
4488 : : /* data */
4489 : 140 : datalen = VARSIZE_ANY_EXHDR(sstate) - 4;
4490 : 140 : data = pq_getmsgbytes(&buf, datalen);
4491 : 140 : appendBinaryStringInfo(result, data, datalen);
4492 : :
4493 : 140 : pq_getmsgend(&buf);
4494 : :
4495 : 140 : PG_RETURN_POINTER(result);
4496 : : }
4497 : :
4498 : : Datum
4499 : 1382 : string_agg_finalfn(PG_FUNCTION_ARGS)
4500 : : {
4501 : : StringInfo state;
4502 : :
4503 : : /* cannot be called directly because of internal-type argument */
4504 : : Assert(AggCheckCallContext(fcinfo, NULL));
4505 : :
4506 [ + + ]: 1382 : state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
4507 : :
4508 [ + + ]: 1382 : if (state != NULL)
4509 : : {
4510 : : /* As per comment in transfn, strip data before the cursor position */
4511 : 1326 : PG_RETURN_TEXT_P(cstring_to_text_with_len(&state->data[state->cursor],
4512 : : state->len - state->cursor));
4513 : : }
4514 : : else
4515 : 56 : PG_RETURN_NULL();
4516 : : }
4517 : :
4518 : : /*
4519 : : * Prepare cache with fmgr info for the output functions of the datatypes of
4520 : : * the arguments of a concat-like function, beginning with argument "argidx".
4521 : : * (Arguments before that will have corresponding slots in the resulting
4522 : : * FmgrInfo array, but we don't fill those slots.)
4523 : : */
4524 : : static FmgrInfo *
4525 : 70 : build_concat_foutcache(FunctionCallInfo fcinfo, int argidx)
4526 : : {
4527 : : FmgrInfo *foutcache;
4528 : : int i;
4529 : :
4530 : : /* We keep the info in fn_mcxt so it survives across calls */
4531 : 70 : foutcache = (FmgrInfo *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4532 : 70 : PG_NARGS() * sizeof(FmgrInfo));
4533 : :
4534 [ + + ]: 264 : for (i = argidx; i < PG_NARGS(); i++)
4535 : : {
4536 : : Oid valtype;
4537 : : Oid typOutput;
4538 : : bool typIsVarlena;
4539 : :
4540 : 194 : valtype = get_fn_expr_argtype(fcinfo->flinfo, i);
4541 [ - + ]: 194 : if (!OidIsValid(valtype))
4542 [ # # ]: 0 : elog(ERROR, "could not determine data type of concat() input");
4543 : :
4544 : 194 : getTypeOutputInfo(valtype, &typOutput, &typIsVarlena);
4545 : 194 : fmgr_info_cxt(typOutput, &foutcache[i], fcinfo->flinfo->fn_mcxt);
4546 : : }
4547 : :
4548 : 70 : fcinfo->flinfo->fn_extra = foutcache;
4549 : :
4550 : 70 : return foutcache;
4551 : : }
4552 : :
4553 : : /*
4554 : : * Implementation of both concat() and concat_ws().
4555 : : *
4556 : : * sepstr is the separator string to place between values.
4557 : : * argidx identifies the first argument to concatenate (counting from zero);
4558 : : * note that this must be constant across any one series of calls.
4559 : : *
4560 : : * Returns NULL if result should be NULL, else text value.
4561 : : */
4562 : : static text *
4563 : 175 : concat_internal(const char *sepstr, int argidx,
4564 : : FunctionCallInfo fcinfo)
4565 : : {
4566 : : text *result;
4567 : : StringInfoData str;
4568 : : FmgrInfo *foutcache;
4569 : 175 : bool first_arg = true;
4570 : : int i;
4571 : :
4572 : : /*
4573 : : * concat(VARIADIC some-array) is essentially equivalent to
4574 : : * array_to_text(), ie concat the array elements with the given separator.
4575 : : * So we just pass the case off to that code.
4576 : : */
4577 [ + + ]: 175 : if (get_fn_expr_variadic(fcinfo->flinfo))
4578 : : {
4579 : : ArrayType *arr;
4580 : :
4581 : : /* Should have just the one argument */
4582 : : Assert(argidx == PG_NARGS() - 1);
4583 : :
4584 : : /* concat(VARIADIC NULL) is defined as NULL */
4585 [ + + ]: 20 : if (PG_ARGISNULL(argidx))
4586 : 8 : return NULL;
4587 : :
4588 : : /*
4589 : : * Non-null argument had better be an array. We assume that any call
4590 : : * context that could let get_fn_expr_variadic return true will have
4591 : : * checked that a VARIADIC-labeled parameter actually is an array. So
4592 : : * it should be okay to just Assert that it's an array rather than
4593 : : * doing a full-fledged error check.
4594 : : */
4595 : : Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, argidx))));
4596 : :
4597 : : /* OK, safe to fetch the array value */
4598 : 12 : arr = PG_GETARG_ARRAYTYPE_P(argidx);
4599 : :
4600 : : /*
4601 : : * And serialize the array. We tell array_to_text to ignore null
4602 : : * elements, which matches the behavior of the loop below.
4603 : : */
4604 : 12 : return array_to_text_internal(fcinfo, arr, sepstr, NULL);
4605 : : }
4606 : :
4607 : : /* Normal case without explicit VARIADIC marker */
4608 : 155 : initStringInfo(&str);
4609 : :
4610 : : /* Get output function info, building it if first time through */
4611 : 155 : foutcache = (FmgrInfo *) fcinfo->flinfo->fn_extra;
4612 [ + + ]: 155 : if (foutcache == NULL)
4613 : 70 : foutcache = build_concat_foutcache(fcinfo, argidx);
4614 : :
4615 [ + + ]: 544 : for (i = argidx; i < PG_NARGS(); i++)
4616 : : {
4617 [ + + ]: 389 : if (!PG_ARGISNULL(i))
4618 : : {
4619 : 337 : Datum value = PG_GETARG_DATUM(i);
4620 : :
4621 : : /* add separator if appropriate */
4622 [ + + ]: 337 : if (first_arg)
4623 : 151 : first_arg = false;
4624 : : else
4625 : 186 : appendStringInfoString(&str, sepstr);
4626 : :
4627 : : /* call the appropriate type output function, append the result */
4628 : 337 : appendStringInfoString(&str,
4629 : 337 : OutputFunctionCall(&foutcache[i], value));
4630 : : }
4631 : : }
4632 : :
4633 : 155 : result = cstring_to_text_with_len(str.data, str.len);
4634 : 155 : pfree(str.data);
4635 : :
4636 : 155 : return result;
4637 : : }
4638 : :
4639 : : /*
4640 : : * Concatenate all arguments. NULL arguments are ignored.
4641 : : */
4642 : : Datum
4643 : 123 : text_concat(PG_FUNCTION_ARGS)
4644 : : {
4645 : : text *result;
4646 : :
4647 : 123 : result = concat_internal("", 0, fcinfo);
4648 [ + + ]: 123 : if (result == NULL)
4649 : 4 : PG_RETURN_NULL();
4650 : 119 : PG_RETURN_TEXT_P(result);
4651 : : }
4652 : :
4653 : : /*
4654 : : * Concatenate all but first argument value with separators. The first
4655 : : * parameter is used as the separator. NULL arguments are ignored.
4656 : : */
4657 : : Datum
4658 : 56 : text_concat_ws(PG_FUNCTION_ARGS)
4659 : : {
4660 : : char *sep;
4661 : : text *result;
4662 : :
4663 : : /* return NULL when separator is NULL */
4664 [ + + ]: 56 : if (PG_ARGISNULL(0))
4665 : 4 : PG_RETURN_NULL();
4666 : 52 : sep = text_to_cstring(PG_GETARG_TEXT_PP(0));
4667 : :
4668 : 52 : result = concat_internal(sep, 1, fcinfo);
4669 [ + + ]: 52 : if (result == NULL)
4670 : 4 : PG_RETURN_NULL();
4671 : 48 : PG_RETURN_TEXT_P(result);
4672 : : }
4673 : :
4674 : : /*
4675 : : * Return first n characters in the string. When n is negative,
4676 : : * return all but last |n| characters.
4677 : : */
4678 : : Datum
4679 : 1437 : text_left(PG_FUNCTION_ARGS)
4680 : : {
4681 : 1437 : int n = PG_GETARG_INT32(1);
4682 : :
4683 [ + + ]: 1437 : if (n < 0)
4684 : : {
4685 : 25 : text *str = PG_GETARG_TEXT_PP(0);
4686 : 25 : const char *p = VARDATA_ANY(str);
4687 : 25 : int len = VARSIZE_ANY_EXHDR(str);
4688 : : int rlen;
4689 : :
4690 : 25 : n = pg_mbstrlen_with_len(p, len) + n;
4691 : 25 : rlen = pg_mbcharcliplen(p, len, n);
4692 : 25 : PG_RETURN_TEXT_P(cstring_to_text_with_len(p, rlen));
4693 : : }
4694 : : else
4695 : 1412 : PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0), 1, n, false));
4696 : : }
4697 : :
4698 : : /*
4699 : : * Return last n characters in the string. When n is negative,
4700 : : * return all but first |n| characters.
4701 : : */
4702 : : Datum
4703 : 49 : text_right(PG_FUNCTION_ARGS)
4704 : : {
4705 : 49 : text *str = PG_GETARG_TEXT_PP(0);
4706 : 49 : const char *p = VARDATA_ANY(str);
4707 : 49 : int len = VARSIZE_ANY_EXHDR(str);
4708 : 49 : int n = PG_GETARG_INT32(1);
4709 : : int off;
4710 : :
4711 [ + + ]: 49 : if (n < 0)
4712 : : {
4713 : : /*
4714 : : * Negating PG_INT32_MIN would overflow, so clamp instead. Any n
4715 : : * whose absolute value is at least the string's length skips the
4716 : : * whole string, and len can't exceed PG_INT32_MAX, so this is
4717 : : * equivalent.
4718 : : */
4719 [ + + ]: 25 : if (unlikely(n == PG_INT32_MIN))
4720 : 5 : n = PG_INT32_MAX;
4721 : : else
4722 : 20 : n = -n;
4723 : : }
4724 : : else
4725 : 24 : n = pg_mbstrlen_with_len(p, len) - n;
4726 : 49 : off = pg_mbcharcliplen(p, len, n);
4727 : :
4728 : 49 : PG_RETURN_TEXT_P(cstring_to_text_with_len(p + off, len - off));
4729 : : }
4730 : :
4731 : : /*
4732 : : * Return reversed string
4733 : : */
4734 : : Datum
4735 : 29 : text_reverse(PG_FUNCTION_ARGS)
4736 : : {
4737 : 29 : text *str = PG_GETARG_TEXT_PP(0);
4738 : 29 : const char *p = VARDATA_ANY(str);
4739 : 29 : int len = VARSIZE_ANY_EXHDR(str);
4740 : 29 : const char *endp = p + len;
4741 : : text *result;
4742 : : char *dst;
4743 : :
4744 : 29 : result = palloc(len + VARHDRSZ);
4745 : 29 : dst = (char *) VARDATA(result) + len;
4746 : 29 : SET_VARSIZE(result, len + VARHDRSZ);
4747 : :
4748 [ + - ]: 29 : if (pg_database_encoding_max_length() > 1)
4749 : : {
4750 : : /* multibyte version */
4751 [ + + ]: 222 : while (p < endp)
4752 : : {
4753 : : int sz;
4754 : :
4755 : 197 : sz = pg_mblen_range(p, endp);
4756 : 193 : dst -= sz;
4757 : 193 : memcpy(dst, p, sz);
4758 : 193 : p += sz;
4759 : : }
4760 : : }
4761 : : else
4762 : : {
4763 : : /* single byte version */
4764 [ # # ]: 0 : while (p < endp)
4765 : 0 : *(--dst) = *p++;
4766 : : }
4767 : :
4768 : 25 : PG_RETURN_TEXT_P(result);
4769 : : }
4770 : :
4771 : :
4772 : : /*
4773 : : * Support macros for text_format()
4774 : : */
4775 : : #define TEXT_FORMAT_FLAG_MINUS 0x0001 /* is minus flag present? */
4776 : :
4777 : : #define ADVANCE_PARSE_POINTER(ptr,end_ptr) \
4778 : : do { \
4779 : : if (++(ptr) >= (end_ptr)) \
4780 : : ereport(ERROR, \
4781 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE), \
4782 : : errmsg("unterminated format() type specifier"), \
4783 : : errhint("For a single \"%%\" use \"%%%%\"."))); \
4784 : : } while (0)
4785 : :
4786 : : /*
4787 : : * Returns a formatted string
4788 : : */
4789 : : Datum
4790 : 22027 : text_format(PG_FUNCTION_ARGS)
4791 : : {
4792 : : text *fmt;
4793 : : StringInfoData result_str;
4794 : : const char *cp;
4795 : : const char *start_ptr;
4796 : : const char *end_ptr;
4797 : : text *result;
4798 : : int arg;
4799 : : bool funcvariadic;
4800 : : int nargs;
4801 : 22027 : Datum *elements = NULL;
4802 : 22027 : bool *nulls = NULL;
4803 : 22027 : Oid element_type = InvalidOid;
4804 : 22027 : Oid prev_type = InvalidOid;
4805 : 22027 : Oid prev_width_type = InvalidOid;
4806 : : FmgrInfo typoutputfinfo;
4807 : : FmgrInfo typoutputinfo_width;
4808 : :
4809 : : /* When format string is null, immediately return null */
4810 [ + + ]: 22027 : if (PG_ARGISNULL(0))
4811 : 4 : PG_RETURN_NULL();
4812 : :
4813 : : /* If argument is marked VARIADIC, expand array into elements */
4814 [ + + ]: 22023 : if (get_fn_expr_variadic(fcinfo->flinfo))
4815 : : {
4816 : : ArrayType *arr;
4817 : : int16 elmlen;
4818 : : bool elmbyval;
4819 : : char elmalign;
4820 : : int nitems;
4821 : :
4822 : : /* Should have just the one argument */
4823 : : Assert(PG_NARGS() == 2);
4824 : :
4825 : : /* If argument is NULL, we treat it as zero-length array */
4826 [ + + ]: 32 : if (PG_ARGISNULL(1))
4827 : 4 : nitems = 0;
4828 : : else
4829 : : {
4830 : : /*
4831 : : * Non-null argument had better be an array. We assume that any
4832 : : * call context that could let get_fn_expr_variadic return true
4833 : : * will have checked that a VARIADIC-labeled parameter actually is
4834 : : * an array. So it should be okay to just Assert that it's an
4835 : : * array rather than doing a full-fledged error check.
4836 : : */
4837 : : Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, 1))));
4838 : :
4839 : : /* OK, safe to fetch the array value */
4840 : 28 : arr = PG_GETARG_ARRAYTYPE_P(1);
4841 : :
4842 : : /* Get info about array element type */
4843 : 28 : element_type = ARR_ELEMTYPE(arr);
4844 : 28 : get_typlenbyvalalign(element_type,
4845 : : &elmlen, &elmbyval, &elmalign);
4846 : :
4847 : : /* Extract all array elements */
4848 : 28 : deconstruct_array(arr, element_type, elmlen, elmbyval, elmalign,
4849 : : &elements, &nulls, &nitems);
4850 : : }
4851 : :
4852 : 32 : nargs = nitems + 1;
4853 : 32 : funcvariadic = true;
4854 : : }
4855 : : else
4856 : : {
4857 : : /* Non-variadic case, we'll process the arguments individually */
4858 : 21991 : nargs = PG_NARGS();
4859 : 21991 : funcvariadic = false;
4860 : : }
4861 : :
4862 : : /* Setup for main loop. */
4863 : 22023 : fmt = PG_GETARG_TEXT_PP(0);
4864 : 22023 : start_ptr = VARDATA_ANY(fmt);
4865 : 22023 : end_ptr = start_ptr + VARSIZE_ANY_EXHDR(fmt);
4866 : 22023 : initStringInfo(&result_str);
4867 : 22023 : arg = 1; /* next argument position to print */
4868 : :
4869 : : /* Scan format string, looking for conversion specifiers. */
4870 [ + + ]: 702370 : for (cp = start_ptr; cp < end_ptr; cp++)
4871 : : {
4872 : : int argpos;
4873 : : int widthpos;
4874 : : int flags;
4875 : : int width;
4876 : : Datum value;
4877 : : bool isNull;
4878 : : Oid typid;
4879 : :
4880 : : /*
4881 : : * If it's not the start of a conversion specifier, just copy it to
4882 : : * the output buffer.
4883 : : */
4884 [ + + ]: 680387 : if (*cp != '%')
4885 : : {
4886 [ - + ]: 634851 : appendStringInfoCharMacro(&result_str, *cp);
4887 : 634863 : continue;
4888 : : }
4889 : :
4890 [ - + - - ]: 45536 : ADVANCE_PARSE_POINTER(cp, end_ptr);
4891 : :
4892 : : /* Easy case: %% outputs a single % */
4893 [ + + ]: 45536 : if (*cp == '%')
4894 : : {
4895 [ - + ]: 12 : appendStringInfoCharMacro(&result_str, *cp);
4896 : 12 : continue;
4897 : : }
4898 : :
4899 : : /* Parse the optional portions of the format specifier */
4900 : 45524 : cp = text_format_parse_format(cp, end_ptr,
4901 : : &argpos, &widthpos,
4902 : : &flags, &width);
4903 : :
4904 : : /*
4905 : : * Next we should see the main conversion specifier. Whether or not
4906 : : * an argument position was present, it's known that at least one
4907 : : * character remains in the string at this point. Experience suggests
4908 : : * that it's worth checking that that character is one of the expected
4909 : : * ones before we try to fetch arguments, so as to produce the least
4910 : : * confusing response to a mis-formatted specifier.
4911 : : */
4912 [ + + ]: 45508 : if (strchr("sIL", *cp) == NULL)
4913 [ + - ]: 4 : ereport(ERROR,
4914 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4915 : : errmsg("unrecognized format() type specifier \"%.*s\"",
4916 : : pg_mblen_range(cp, end_ptr), cp),
4917 : : errhint("For a single \"%%\" use \"%%%%\".")));
4918 : :
4919 : : /* If indirect width was specified, get its value */
4920 [ + + ]: 45504 : if (widthpos >= 0)
4921 : : {
4922 : : /* Collect the specified or next argument position */
4923 [ + + ]: 28 : if (widthpos > 0)
4924 : 24 : arg = widthpos;
4925 [ - + ]: 28 : if (arg >= nargs)
4926 [ # # ]: 0 : ereport(ERROR,
4927 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4928 : : errmsg("too few arguments for format()")));
4929 : :
4930 : : /* Get the value and type of the selected argument */
4931 [ + - ]: 28 : if (!funcvariadic)
4932 : : {
4933 : 28 : value = PG_GETARG_DATUM(arg);
4934 : 28 : isNull = PG_ARGISNULL(arg);
4935 : 28 : typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
4936 : : }
4937 : : else
4938 : : {
4939 : 0 : value = elements[arg - 1];
4940 : 0 : isNull = nulls[arg - 1];
4941 : 0 : typid = element_type;
4942 : : }
4943 [ - + ]: 28 : if (!OidIsValid(typid))
4944 [ # # ]: 0 : elog(ERROR, "could not determine data type of format() input");
4945 : :
4946 : 28 : arg++;
4947 : :
4948 : : /* We can treat NULL width the same as zero */
4949 [ + + ]: 28 : if (isNull)
4950 : 4 : width = 0;
4951 [ + - ]: 24 : else if (typid == INT4OID)
4952 : 24 : width = DatumGetInt32(value);
4953 [ # # ]: 0 : else if (typid == INT2OID)
4954 : 0 : width = DatumGetInt16(value);
4955 : : else
4956 : : {
4957 : : /* For less-usual datatypes, convert to text then to int */
4958 : : char *str;
4959 : :
4960 [ # # ]: 0 : if (typid != prev_width_type)
4961 : : {
4962 : : Oid typoutputfunc;
4963 : : bool typIsVarlena;
4964 : :
4965 : 0 : getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena);
4966 : 0 : fmgr_info(typoutputfunc, &typoutputinfo_width);
4967 : 0 : prev_width_type = typid;
4968 : : }
4969 : :
4970 : 0 : str = OutputFunctionCall(&typoutputinfo_width, value);
4971 : :
4972 : : /* pg_strtoint32 will complain about bad data or overflow */
4973 : 0 : width = pg_strtoint32(str);
4974 : :
4975 : 0 : pfree(str);
4976 : : }
4977 : : }
4978 : :
4979 : : /* Collect the specified or next argument position */
4980 [ + + ]: 45504 : if (argpos > 0)
4981 : 88 : arg = argpos;
4982 [ + + ]: 45504 : if (arg >= nargs)
4983 [ + - ]: 16 : ereport(ERROR,
4984 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4985 : : errmsg("too few arguments for format()")));
4986 : :
4987 : : /* Get the value and type of the selected argument */
4988 [ + + ]: 45488 : if (!funcvariadic)
4989 : : {
4990 : 44640 : value = PG_GETARG_DATUM(arg);
4991 : 44640 : isNull = PG_ARGISNULL(arg);
4992 : 44640 : typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
4993 : : }
4994 : : else
4995 : : {
4996 : 848 : value = elements[arg - 1];
4997 : 848 : isNull = nulls[arg - 1];
4998 : 848 : typid = element_type;
4999 : : }
5000 [ - + ]: 45488 : if (!OidIsValid(typid))
5001 [ # # ]: 0 : elog(ERROR, "could not determine data type of format() input");
5002 : :
5003 : 45488 : arg++;
5004 : :
5005 : : /*
5006 : : * Get the appropriate typOutput function, reusing previous one if
5007 : : * same type as previous argument. That's particularly useful in the
5008 : : * variadic-array case, but often saves work even for ordinary calls.
5009 : : */
5010 [ + + ]: 45488 : if (typid != prev_type)
5011 : : {
5012 : : Oid typoutputfunc;
5013 : : bool typIsVarlena;
5014 : :
5015 : 23353 : getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena);
5016 : 23353 : fmgr_info(typoutputfunc, &typoutputfinfo);
5017 : 23353 : prev_type = typid;
5018 : : }
5019 : :
5020 : : /*
5021 : : * And now we can format the value.
5022 : : */
5023 [ + - ]: 45488 : switch (*cp)
5024 : : {
5025 : 45488 : case 's':
5026 : : case 'I':
5027 : : case 'L':
5028 : 45488 : text_format_string_conversion(&result_str, *cp, &typoutputfinfo,
5029 : : value, isNull,
5030 : : flags, width);
5031 : 45484 : break;
5032 : 0 : default:
5033 : : /* should not get here, because of previous check */
5034 [ # # ]: 0 : ereport(ERROR,
5035 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5036 : : errmsg("unrecognized format() type specifier \"%.*s\"",
5037 : : pg_mblen_range(cp, end_ptr), cp),
5038 : : errhint("For a single \"%%\" use \"%%%%\".")));
5039 : : break;
5040 : : }
5041 : : }
5042 : :
5043 : : /* Don't need deconstruct_array results anymore. */
5044 [ + + ]: 21983 : if (elements != NULL)
5045 : 28 : pfree(elements);
5046 [ + + ]: 21983 : if (nulls != NULL)
5047 : 28 : pfree(nulls);
5048 : :
5049 : : /* Generate results. */
5050 : 21983 : result = cstring_to_text_with_len(result_str.data, result_str.len);
5051 : 21983 : pfree(result_str.data);
5052 : :
5053 : 21983 : PG_RETURN_TEXT_P(result);
5054 : : }
5055 : :
5056 : : /*
5057 : : * Parse contiguous digits as a decimal number.
5058 : : *
5059 : : * Returns true if some digits could be parsed.
5060 : : * The value is returned into *value, and *ptr is advanced to the next
5061 : : * character to be parsed.
5062 : : *
5063 : : * Note parsing invariant: at least one character is known available before
5064 : : * string end (end_ptr) at entry, and this is still true at exit.
5065 : : */
5066 : : static bool
5067 : 91024 : text_format_parse_digits(const char **ptr, const char *end_ptr, int *value)
5068 : : {
5069 : 91024 : bool found = false;
5070 : 91024 : const char *cp = *ptr;
5071 : 91024 : int val = 0;
5072 : :
5073 [ + + + + ]: 91232 : while (*cp >= '0' && *cp <= '9')
5074 : : {
5075 : 212 : int8 digit = (*cp - '0');
5076 : :
5077 [ + - ]: 212 : if (unlikely(pg_mul_s32_overflow(val, 10, &val)) ||
5078 [ - + ]: 212 : unlikely(pg_add_s32_overflow(val, digit, &val)))
5079 [ # # ]: 0 : ereport(ERROR,
5080 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
5081 : : errmsg("number is out of range")));
5082 [ + + + - ]: 212 : ADVANCE_PARSE_POINTER(cp, end_ptr);
5083 : 208 : found = true;
5084 : : }
5085 : :
5086 : 91020 : *ptr = cp;
5087 : 91020 : *value = val;
5088 : :
5089 : 91020 : return found;
5090 : : }
5091 : :
5092 : : /*
5093 : : * Parse a format specifier (generally following the SUS printf spec).
5094 : : *
5095 : : * We have already advanced over the initial '%', and we are looking for
5096 : : * [argpos][flags][width]type (but the type character is not consumed here).
5097 : : *
5098 : : * Inputs are start_ptr (the position after '%') and end_ptr (string end + 1).
5099 : : * Output parameters:
5100 : : * argpos: argument position for value to be printed. -1 means unspecified.
5101 : : * widthpos: argument position for width. Zero means the argument position
5102 : : * was unspecified (ie, take the next arg) and -1 means no width
5103 : : * argument (width was omitted or specified as a constant).
5104 : : * flags: bitmask of flags.
5105 : : * width: directly-specified width value. Zero means the width was omitted
5106 : : * (note it's not necessary to distinguish this case from an explicit
5107 : : * zero width value).
5108 : : *
5109 : : * The function result is the next character position to be parsed, ie, the
5110 : : * location where the type character is/should be.
5111 : : *
5112 : : * Note parsing invariant: at least one character is known available before
5113 : : * string end (end_ptr) at entry, and this is still true at exit.
5114 : : */
5115 : : static const char *
5116 : 45524 : text_format_parse_format(const char *start_ptr, const char *end_ptr,
5117 : : int *argpos, int *widthpos,
5118 : : int *flags, int *width)
5119 : : {
5120 : 45524 : const char *cp = start_ptr;
5121 : : int n;
5122 : :
5123 : : /* set defaults for output parameters */
5124 : 45524 : *argpos = -1;
5125 : 45524 : *widthpos = -1;
5126 : 45524 : *flags = 0;
5127 : 45524 : *width = 0;
5128 : :
5129 : : /* try to identify first number */
5130 [ + + ]: 45524 : if (text_format_parse_digits(&cp, end_ptr, &n))
5131 : : {
5132 [ + + ]: 116 : if (*cp != '$')
5133 : : {
5134 : : /* Must be just a width and a type, so we're done */
5135 : 16 : *width = n;
5136 : 16 : return cp;
5137 : : }
5138 : : /* The number was argument position */
5139 : 100 : *argpos = n;
5140 : : /* Explicit 0 for argument index is immediately refused */
5141 [ + + ]: 100 : if (n == 0)
5142 [ + - ]: 4 : ereport(ERROR,
5143 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5144 : : errmsg("format specifies argument 0, but arguments are numbered from 1")));
5145 [ + + + - ]: 96 : ADVANCE_PARSE_POINTER(cp, end_ptr);
5146 : : }
5147 : :
5148 : : /* Handle flags (only minus is supported now) */
5149 [ + + ]: 45520 : while (*cp == '-')
5150 : : {
5151 : 20 : *flags |= TEXT_FORMAT_FLAG_MINUS;
5152 [ - + - - ]: 20 : ADVANCE_PARSE_POINTER(cp, end_ptr);
5153 : : }
5154 : :
5155 [ + + ]: 45500 : if (*cp == '*')
5156 : : {
5157 : : /* Handle indirect width */
5158 [ - + - - ]: 32 : ADVANCE_PARSE_POINTER(cp, end_ptr);
5159 [ + + ]: 32 : if (text_format_parse_digits(&cp, end_ptr, &n))
5160 : : {
5161 : : /* number in this position must be closed by $ */
5162 [ - + ]: 28 : if (*cp != '$')
5163 [ # # ]: 0 : ereport(ERROR,
5164 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5165 : : errmsg("width argument position must be ended by \"$\"")));
5166 : : /* The number was width argument position */
5167 : 28 : *widthpos = n;
5168 : : /* Explicit 0 for argument index is immediately refused */
5169 [ + + ]: 28 : if (n == 0)
5170 [ + - ]: 4 : ereport(ERROR,
5171 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5172 : : errmsg("format specifies argument 0, but arguments are numbered from 1")));
5173 [ - + - - ]: 24 : ADVANCE_PARSE_POINTER(cp, end_ptr);
5174 : : }
5175 : : else
5176 : 4 : *widthpos = 0; /* width's argument position is unspecified */
5177 : : }
5178 : : else
5179 : : {
5180 : : /* Check for direct width specification */
5181 [ + + ]: 45468 : if (text_format_parse_digits(&cp, end_ptr, &n))
5182 : 20 : *width = n;
5183 : : }
5184 : :
5185 : : /* cp should now be pointing at type character */
5186 : 45492 : return cp;
5187 : : }
5188 : :
5189 : : /*
5190 : : * Format a %s, %I, or %L conversion
5191 : : */
5192 : : static void
5193 : 45488 : text_format_string_conversion(StringInfo buf, char conversion,
5194 : : FmgrInfo *typOutputInfo,
5195 : : Datum value, bool isNull,
5196 : : int flags, int width)
5197 : : {
5198 : : char *str;
5199 : :
5200 : : /* Handle NULL arguments before trying to stringify the value. */
5201 [ + + ]: 45488 : if (isNull)
5202 : : {
5203 [ + + ]: 228 : if (conversion == 's')
5204 : 180 : text_format_append_string(buf, "", flags, width);
5205 [ + + ]: 48 : else if (conversion == 'L')
5206 : 44 : text_format_append_string(buf, "NULL", flags, width);
5207 [ + - ]: 4 : else if (conversion == 'I')
5208 [ + - ]: 4 : ereport(ERROR,
5209 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5210 : : errmsg("null values cannot be formatted as an SQL identifier")));
5211 : 224 : return;
5212 : : }
5213 : :
5214 : : /* Stringify. */
5215 : 45260 : str = OutputFunctionCall(typOutputInfo, value);
5216 : :
5217 : : /* Escape. */
5218 [ + + ]: 45260 : if (conversion == 'I')
5219 : : {
5220 : : /* quote_identifier may or may not allocate a new string. */
5221 : 3268 : text_format_append_string(buf, quote_identifier(str), flags, width);
5222 : : }
5223 [ + + ]: 41992 : else if (conversion == 'L')
5224 : : {
5225 : 2168 : char *qstr = quote_literal_cstr(str);
5226 : :
5227 : 2168 : text_format_append_string(buf, qstr, flags, width);
5228 : : /* quote_literal_cstr() always allocates a new string */
5229 : 2168 : pfree(qstr);
5230 : : }
5231 : : else
5232 : 39824 : text_format_append_string(buf, str, flags, width);
5233 : :
5234 : : /* Cleanup. */
5235 : 45260 : pfree(str);
5236 : : }
5237 : :
5238 : : /*
5239 : : * Append str to buf, padding as directed by flags/width
5240 : : */
5241 : : static void
5242 : 45484 : text_format_append_string(StringInfo buf, const char *str,
5243 : : int flags, int width)
5244 : : {
5245 : 45484 : bool align_to_left = false;
5246 : : int len;
5247 : :
5248 : : /* fast path for typical easy case */
5249 [ + + ]: 45484 : if (width == 0)
5250 : : {
5251 : 45428 : appendStringInfoString(buf, str);
5252 : 45428 : return;
5253 : : }
5254 : :
5255 [ + + ]: 56 : if (width < 0)
5256 : : {
5257 : : /* Negative width: implicit '-' flag, then take absolute value */
5258 : 4 : align_to_left = true;
5259 : : /* -INT_MIN is undefined */
5260 [ - + ]: 4 : if (width <= INT_MIN)
5261 [ # # ]: 0 : ereport(ERROR,
5262 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
5263 : : errmsg("number is out of range")));
5264 : 4 : width = -width;
5265 : : }
5266 [ + + ]: 52 : else if (flags & TEXT_FORMAT_FLAG_MINUS)
5267 : 16 : align_to_left = true;
5268 : :
5269 : 56 : len = pg_mbstrlen(str);
5270 [ + + ]: 56 : if (align_to_left)
5271 : : {
5272 : : /* left justify */
5273 : 20 : appendStringInfoString(buf, str);
5274 [ + - ]: 20 : if (len < width)
5275 : 20 : appendStringInfoSpaces(buf, width - len);
5276 : : }
5277 : : else
5278 : : {
5279 : : /* right justify */
5280 [ + - ]: 36 : if (len < width)
5281 : 36 : appendStringInfoSpaces(buf, width - len);
5282 : 36 : appendStringInfoString(buf, str);
5283 : : }
5284 : : }
5285 : :
5286 : : /*
5287 : : * text_format_nv - nonvariadic wrapper for text_format function.
5288 : : *
5289 : : * note: this wrapper is necessary to pass the sanity check in opr_sanity,
5290 : : * which checks that all built-in functions that share the implementing C
5291 : : * function take the same number of arguments.
5292 : : */
5293 : : Datum
5294 : 1910 : text_format_nv(PG_FUNCTION_ARGS)
5295 : : {
5296 : 1910 : return text_format(fcinfo);
5297 : : }
5298 : :
5299 : : /*
5300 : : * Helper function for Levenshtein distance functions. Faster than memcmp(),
5301 : : * for this use case.
5302 : : */
5303 : : static inline bool
5304 : 0 : rest_of_char_same(const char *s1, const char *s2, int len)
5305 : : {
5306 [ # # ]: 0 : while (len > 0)
5307 : : {
5308 : 0 : len--;
5309 [ # # ]: 0 : if (s1[len] != s2[len])
5310 : 0 : return false;
5311 : : }
5312 : 0 : return true;
5313 : : }
5314 : :
5315 : : /*
5316 : : * Helper function for checking return value of Levenshtein distance functions.
5317 : : * We calculate it as an int64, but the distance functions return an int32.
5318 : : */
5319 : : static inline int
5320 : 1938 : levenshtein_result(int64 res)
5321 : : {
5322 [ + - + + : 1938 : if (unlikely(res < PG_INT32_MIN || res > PG_INT32_MAX))
+ + ]
5323 [ + - ]: 1 : ereport(ERROR,
5324 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
5325 : : errmsg("levenshtein distance out of range")));
5326 : 1937 : return res;
5327 : : }
5328 : :
5329 : : /* Expand each Levenshtein distance variant */
5330 : : #include "levenshtein.c"
5331 : : #define LEVENSHTEIN_LESS_EQUAL
5332 : : #include "levenshtein.c"
5333 : :
5334 : :
5335 : : /*
5336 : : * The following *ClosestMatch() functions can be used to determine whether a
5337 : : * user-provided string resembles any known valid values, which is useful for
5338 : : * providing hints in log messages, among other things. Use these functions
5339 : : * like so:
5340 : : *
5341 : : * initClosestMatch(&state, source_string, max_distance);
5342 : : *
5343 : : * for (int i = 0; i < num_valid_strings; i++)
5344 : : * updateClosestMatch(&state, valid_strings[i]);
5345 : : *
5346 : : * closestMatch = getClosestMatch(&state);
5347 : : */
5348 : :
5349 : : /*
5350 : : * Initialize the given state with the source string and maximum Levenshtein
5351 : : * distance to consider.
5352 : : */
5353 : : void
5354 : 45 : initClosestMatch(ClosestMatchState *state, const char *source, int max_d)
5355 : : {
5356 : : Assert(state);
5357 : : Assert(max_d >= 0);
5358 : :
5359 : 45 : state->source = source;
5360 : 45 : state->min_d = -1;
5361 : 45 : state->max_d = max_d;
5362 : 45 : state->match = NULL;
5363 : 45 : }
5364 : :
5365 : : /*
5366 : : * If the candidate string is a closer match than the current one saved (or
5367 : : * there is no match saved), save it as the closest match.
5368 : : *
5369 : : * If the source or candidate string is NULL, empty, or too long, this function
5370 : : * takes no action. Likewise, if the Levenshtein distance exceeds the maximum
5371 : : * allowed or more than half the characters are different, no action is taken.
5372 : : */
5373 : : void
5374 : 435 : updateClosestMatch(ClosestMatchState *state, const char *candidate)
5375 : : {
5376 : : int dist;
5377 : :
5378 : : Assert(state);
5379 : :
5380 [ + - + - : 435 : if (state->source == NULL || state->source[0] == '\0' ||
+ - ]
5381 [ - + ]: 435 : candidate == NULL || candidate[0] == '\0')
5382 : 0 : return;
5383 : :
5384 : : /*
5385 : : * To avoid ERROR-ing, we check the lengths here instead of setting
5386 : : * 'trusted' to false in the call to varstr_levenshtein_less_equal().
5387 : : */
5388 [ + - ]: 435 : if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
5389 [ - + ]: 435 : strlen(candidate) > MAX_LEVENSHTEIN_STRLEN)
5390 : 0 : return;
5391 : :
5392 : 435 : dist = varstr_levenshtein_less_equal(state->source, strlen(state->source),
5393 : 435 : candidate, strlen(candidate), 1, 1, 1,
5394 : : state->max_d, true);
5395 [ + + ]: 435 : if (dist <= state->max_d &&
5396 [ + + ]: 39 : dist <= strlen(state->source) / 2 &&
5397 [ - + - - ]: 9 : (state->min_d == -1 || dist < state->min_d))
5398 : : {
5399 : 9 : state->min_d = dist;
5400 : 9 : state->match = candidate;
5401 : : }
5402 : : }
5403 : :
5404 : : /*
5405 : : * Return the closest match. If no suitable candidates were provided via
5406 : : * updateClosestMatch(), return NULL.
5407 : : */
5408 : : const char *
5409 : 45 : getClosestMatch(ClosestMatchState *state)
5410 : : {
5411 : : Assert(state);
5412 : :
5413 : 45 : return state->match;
5414 : : }
5415 : :
5416 : :
5417 : : /*
5418 : : * Unicode support
5419 : : */
5420 : :
5421 : : static UnicodeNormalizationForm
5422 : 209 : unicode_norm_form_from_string(const char *formstr)
5423 : : {
5424 : 209 : UnicodeNormalizationForm form = -1;
5425 : :
5426 : : /*
5427 : : * Might as well check this while we're here.
5428 : : */
5429 [ - + ]: 209 : if (GetDatabaseEncoding() != PG_UTF8)
5430 [ # # ]: 0 : ereport(ERROR,
5431 : : (errcode(ERRCODE_SYNTAX_ERROR),
5432 : : errmsg("Unicode normalization can only be performed if server encoding is UTF8")));
5433 : :
5434 [ + + ]: 209 : if (pg_strcasecmp(formstr, "NFC") == 0)
5435 : 95 : form = UNICODE_NFC;
5436 [ + + ]: 114 : else if (pg_strcasecmp(formstr, "NFD") == 0)
5437 : 56 : form = UNICODE_NFD;
5438 [ + + ]: 58 : else if (pg_strcasecmp(formstr, "NFKC") == 0)
5439 : 25 : form = UNICODE_NFKC;
5440 [ + + ]: 33 : else if (pg_strcasecmp(formstr, "NFKD") == 0)
5441 : 25 : form = UNICODE_NFKD;
5442 : : else
5443 [ + - ]: 8 : ereport(ERROR,
5444 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5445 : : errmsg("invalid normalization form: %s", formstr)));
5446 : :
5447 : 201 : return form;
5448 : : }
5449 : :
5450 : : /*
5451 : : * Returns version of Unicode used by Postgres in "major.minor" format (the
5452 : : * same format as the Unicode version reported by ICU). The third component
5453 : : * ("update version") never involves additions to the character repertoire and
5454 : : * is unimportant for most purposes.
5455 : : *
5456 : : * See: https://unicode.org/versions/
5457 : : */
5458 : : Datum
5459 : 22 : unicode_version(PG_FUNCTION_ARGS)
5460 : : {
5461 : 22 : PG_RETURN_TEXT_P(cstring_to_text(PG_UNICODE_VERSION));
5462 : : }
5463 : :
5464 : : /*
5465 : : * Returns version of Unicode used by ICU, if enabled; otherwise NULL.
5466 : : */
5467 : : Datum
5468 : 1 : icu_unicode_version(PG_FUNCTION_ARGS)
5469 : : {
5470 : 1 : const char *version = pg_icu_unicode_version();
5471 : :
5472 [ + - ]: 1 : if (version)
5473 : 1 : PG_RETURN_TEXT_P(cstring_to_text(version));
5474 : : else
5475 : 0 : PG_RETURN_NULL();
5476 : : }
5477 : :
5478 : : /*
5479 : : * Check whether the string contains only assigned Unicode code
5480 : : * points. Requires that the database encoding is UTF-8.
5481 : : */
5482 : : Datum
5483 : 10 : unicode_assigned(PG_FUNCTION_ARGS)
5484 : : {
5485 : 10 : text *input = PG_GETARG_TEXT_PP(0);
5486 : : unsigned char *p;
5487 : : int size;
5488 : :
5489 [ - + ]: 10 : if (GetDatabaseEncoding() != PG_UTF8)
5490 [ # # ]: 0 : ereport(ERROR,
5491 : : (errmsg("Unicode categorization can only be performed if server encoding is UTF8")));
5492 : :
5493 : : /* convert to char32_t */
5494 : 10 : size = pg_mbstrlen_with_len(VARDATA_ANY(input), VARSIZE_ANY_EXHDR(input));
5495 : 10 : p = (unsigned char *) VARDATA_ANY(input);
5496 [ + + ]: 40 : for (int i = 0; i < size; i++)
5497 : : {
5498 : 35 : char32_t uchar = utf8_to_unicode(p);
5499 : 35 : int category = unicode_category(uchar);
5500 : :
5501 [ + + ]: 35 : if (category == PG_U_UNASSIGNED)
5502 : 5 : PG_RETURN_BOOL(false);
5503 : :
5504 : 30 : p += pg_utf_mblen(p);
5505 : : }
5506 : :
5507 : 5 : PG_RETURN_BOOL(true);
5508 : : }
5509 : :
5510 : : Datum
5511 : 115 : unicode_normalize_func(PG_FUNCTION_ARGS)
5512 : : {
5513 : 115 : text *input = PG_GETARG_TEXT_PP(0);
5514 : 115 : char *formstr = text_to_cstring(PG_GETARG_TEXT_PP(1));
5515 : : UnicodeNormalizationForm form;
5516 : : size_t size;
5517 : : char32_t *input_chars;
5518 : : char32_t *output_chars;
5519 : : unsigned char *p;
5520 : : text *result;
5521 : : size_t i;
5522 : :
5523 : 115 : form = unicode_norm_form_from_string(formstr);
5524 : :
5525 : : /* convert to char32_t */
5526 : 111 : size = pg_mbstrlen_with_len(VARDATA_ANY(input), VARSIZE_ANY_EXHDR(input));
5527 : 111 : input_chars = palloc_array(char32_t, size + 1);
5528 : 111 : p = (unsigned char *) VARDATA_ANY(input);
5529 [ + + ]: 400 : for (i = 0; i < size; i++)
5530 : : {
5531 : 289 : input_chars[i] = utf8_to_unicode(p);
5532 : 289 : p += pg_utf_mblen(p);
5533 : : }
5534 : 111 : input_chars[i] = (char32_t) '\0';
5535 : : Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5536 : :
5537 : : /* action */
5538 : 111 : output_chars = unicode_normalize(form, input_chars);
5539 : :
5540 : : /* convert back to UTF-8 string */
5541 : 111 : size = 0;
5542 [ + + ]: 386 : for (char32_t *wp = output_chars; *wp; wp++)
5543 : : {
5544 : : unsigned char buf[4];
5545 : :
5546 : 275 : unicode_to_utf8(*wp, buf);
5547 : 275 : size += pg_utf_mblen(buf);
5548 : : }
5549 : :
5550 : 111 : result = palloc(size + VARHDRSZ);
5551 : 111 : SET_VARSIZE(result, size + VARHDRSZ);
5552 : :
5553 : 111 : p = (unsigned char *) VARDATA_ANY(result);
5554 [ + + ]: 386 : for (char32_t *wp = output_chars; *wp; wp++)
5555 : : {
5556 : 275 : unicode_to_utf8(*wp, p);
5557 : 275 : p += pg_utf_mblen(p);
5558 : : }
5559 : : Assert((char *) p == (char *) result + size + VARHDRSZ);
5560 : :
5561 : 111 : PG_RETURN_TEXT_P(result);
5562 : : }
5563 : :
5564 : : /*
5565 : : * Check whether the string is in the specified Unicode normalization form.
5566 : : *
5567 : : * This is done by converting the string to the specified normal form and then
5568 : : * comparing that to the original string. To speed that up, we also apply the
5569 : : * "quick check" algorithm specified in UAX #15, which can give a yes or no
5570 : : * answer for many strings by just scanning the string once.
5571 : : *
5572 : : * This function should generally be optimized for the case where the string
5573 : : * is in fact normalized. In that case, we'll end up looking at the entire
5574 : : * string, so it's probably not worth doing any incremental conversion etc.
5575 : : */
5576 : : Datum
5577 : 94 : unicode_is_normalized(PG_FUNCTION_ARGS)
5578 : : {
5579 : 94 : text *input = PG_GETARG_TEXT_PP(0);
5580 : 94 : char *formstr = text_to_cstring(PG_GETARG_TEXT_PP(1));
5581 : : UnicodeNormalizationForm form;
5582 : : size_t size;
5583 : : char32_t *input_chars;
5584 : : char32_t *output_chars;
5585 : : unsigned char *p;
5586 : : size_t i;
5587 : : UnicodeNormalizationQC quickcheck;
5588 : : size_t output_size;
5589 : : bool result;
5590 : :
5591 : 94 : form = unicode_norm_form_from_string(formstr);
5592 : :
5593 : : /* convert to char32_t */
5594 : 90 : size = pg_mbstrlen_with_len(VARDATA_ANY(input), VARSIZE_ANY_EXHDR(input));
5595 : 90 : input_chars = palloc_array(char32_t, size + 1);
5596 : 90 : p = (unsigned char *) VARDATA_ANY(input);
5597 [ + + ]: 344 : for (i = 0; i < size; i++)
5598 : : {
5599 : 254 : input_chars[i] = utf8_to_unicode(p);
5600 : 254 : p += pg_utf_mblen(p);
5601 : : }
5602 : 90 : input_chars[i] = (char32_t) '\0';
5603 : : Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5604 : :
5605 : : /* quick check (see UAX #15) */
5606 : 90 : quickcheck = unicode_is_normalized_quickcheck(form, input_chars);
5607 [ + + ]: 90 : if (quickcheck == UNICODE_NORM_QC_YES)
5608 : 30 : PG_RETURN_BOOL(true);
5609 [ + + ]: 60 : else if (quickcheck == UNICODE_NORM_QC_NO)
5610 : 8 : PG_RETURN_BOOL(false);
5611 : :
5612 : : /* normalize and compare with original */
5613 : 52 : output_chars = unicode_normalize(form, input_chars);
5614 : :
5615 : 52 : output_size = 0;
5616 [ + + ]: 216 : for (char32_t *wp = output_chars; *wp; wp++)
5617 : 164 : output_size++;
5618 : :
5619 [ + + ]: 76 : result = (size == output_size) &&
5620 [ + + ]: 24 : (memcmp(input_chars, output_chars, size * sizeof(char32_t)) == 0);
5621 : :
5622 : 52 : PG_RETURN_BOOL(result);
5623 : : }
5624 : :
5625 : : /*
5626 : : * Check if first n chars are hexadecimal digits
5627 : : */
5628 : : static bool
5629 : 111 : isxdigits_n(const char *instr, size_t n)
5630 : : {
5631 [ + + ]: 469 : for (size_t i = 0; i < n; i++)
5632 [ + + ]: 405 : if (!isxdigit((unsigned char) instr[i]))
5633 : 47 : return false;
5634 : :
5635 : 64 : return true;
5636 : : }
5637 : :
5638 : : static unsigned int
5639 : 358 : hexval(unsigned char c)
5640 : : {
5641 [ + - + + ]: 358 : if (c >= '0' && c <= '9')
5642 : 278 : return c - '0';
5643 [ + + + - ]: 80 : if (c >= 'a' && c <= 'f')
5644 : 40 : return c - 'a' + 0xA;
5645 [ + - + - ]: 40 : if (c >= 'A' && c <= 'F')
5646 : 40 : return c - 'A' + 0xA;
5647 [ # # ]: 0 : elog(ERROR, "invalid hexadecimal digit");
5648 : : return 0; /* not reached */
5649 : : }
5650 : :
5651 : : /*
5652 : : * Translate string with hexadecimal digits to number
5653 : : */
5654 : : static unsigned int
5655 : 64 : hexval_n(const char *instr, size_t n)
5656 : : {
5657 : 64 : unsigned int result = 0;
5658 : :
5659 [ + + ]: 422 : for (size_t i = 0; i < n; i++)
5660 : 358 : result += hexval(instr[i]) << (4 * (n - i - 1));
5661 : :
5662 : 64 : return result;
5663 : : }
5664 : :
5665 : : /*
5666 : : * Replaces Unicode escape sequences by Unicode characters
5667 : : */
5668 : : Datum
5669 : 47 : unistr(PG_FUNCTION_ARGS)
5670 : : {
5671 : 47 : text *input_text = PG_GETARG_TEXT_PP(0);
5672 : : char *instr;
5673 : : int len;
5674 : : StringInfoData str;
5675 : : text *result;
5676 : 47 : char16_t pair_first = 0;
5677 : : char cbuf[MAX_UNICODE_EQUIVALENT_STRING + 1];
5678 : :
5679 : 47 : instr = VARDATA_ANY(input_text);
5680 : 47 : len = VARSIZE_ANY_EXHDR(input_text);
5681 : :
5682 : 47 : initStringInfo(&str);
5683 : :
5684 [ + + ]: 356 : while (len > 0)
5685 : : {
5686 [ + + ]: 337 : if (instr[0] == '\\')
5687 : : {
5688 [ + - ]: 73 : if (len >= 2 &&
5689 [ + + ]: 73 : instr[1] == '\\')
5690 : : {
5691 [ - + ]: 5 : if (pair_first)
5692 : 0 : goto invalid_pair;
5693 : 5 : appendStringInfoChar(&str, '\\');
5694 : 5 : instr += 2;
5695 : 5 : len -= 2;
5696 : : }
5697 [ + + + + : 68 : else if ((len >= 5 && isxdigits_n(instr + 1, 4)) ||
+ + ]
5698 [ + + + - ]: 47 : (len >= 6 && instr[1] == 'u' && isxdigits_n(instr + 2, 4)))
5699 : 22 : {
5700 : : char32_t unicode;
5701 [ + + ]: 30 : int offset = instr[1] == 'u' ? 2 : 1;
5702 : :
5703 : 30 : unicode = hexval_n(instr + offset, 4);
5704 : :
5705 [ - + ]: 30 : if (!is_valid_unicode_codepoint(unicode))
5706 [ # # ]: 0 : ereport(ERROR,
5707 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5708 : : errmsg("invalid Unicode code point: %04X", unicode));
5709 : :
5710 [ + + ]: 30 : if (pair_first)
5711 : : {
5712 [ - + ]: 8 : if (is_utf16_surrogate_second(unicode))
5713 : : {
5714 : 0 : unicode = surrogate_pair_to_codepoint(pair_first, unicode);
5715 : 0 : pair_first = 0;
5716 : : }
5717 : : else
5718 : 8 : goto invalid_pair;
5719 : : }
5720 [ - + ]: 22 : else if (is_utf16_surrogate_second(unicode))
5721 : 0 : goto invalid_pair;
5722 : :
5723 [ + + ]: 22 : if (is_utf16_surrogate_first(unicode))
5724 : 12 : pair_first = unicode;
5725 : : else
5726 : : {
5727 : 10 : pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5728 : 10 : appendStringInfoString(&str, cbuf);
5729 : : }
5730 : :
5731 : 22 : instr += 4 + offset;
5732 : 22 : len -= 4 + offset;
5733 : : }
5734 [ + + + + : 38 : else if (len >= 8 && instr[1] == '+' && isxdigits_n(instr + 2, 6))
+ - ]
5735 : 9 : {
5736 : : char32_t unicode;
5737 : :
5738 : 17 : unicode = hexval_n(instr + 2, 6);
5739 : :
5740 [ + + ]: 17 : if (!is_valid_unicode_codepoint(unicode))
5741 [ + - ]: 4 : ereport(ERROR,
5742 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5743 : : errmsg("invalid Unicode code point: %04X", unicode));
5744 : :
5745 [ + + ]: 13 : if (pair_first)
5746 : : {
5747 [ - + ]: 4 : if (is_utf16_surrogate_second(unicode))
5748 : : {
5749 : 0 : unicode = surrogate_pair_to_codepoint(pair_first, unicode);
5750 : 0 : pair_first = 0;
5751 : : }
5752 : : else
5753 : 4 : goto invalid_pair;
5754 : : }
5755 [ - + ]: 9 : else if (is_utf16_surrogate_second(unicode))
5756 : 0 : goto invalid_pair;
5757 : :
5758 [ + + ]: 9 : if (is_utf16_surrogate_first(unicode))
5759 : 4 : pair_first = unicode;
5760 : : else
5761 : : {
5762 : 5 : pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5763 : 5 : appendStringInfoString(&str, cbuf);
5764 : : }
5765 : :
5766 : 9 : instr += 8;
5767 : 9 : len -= 8;
5768 : : }
5769 [ + + + - : 21 : else if (len >= 10 && instr[1] == 'U' && isxdigits_n(instr + 2, 8))
+ - ]
5770 : 9 : {
5771 : : char32_t unicode;
5772 : :
5773 : 17 : unicode = hexval_n(instr + 2, 8);
5774 : :
5775 [ + + ]: 17 : if (!is_valid_unicode_codepoint(unicode))
5776 [ + - ]: 4 : ereport(ERROR,
5777 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5778 : : errmsg("invalid Unicode code point: %04X", unicode));
5779 : :
5780 [ + + ]: 13 : if (pair_first)
5781 : : {
5782 [ - + ]: 4 : if (is_utf16_surrogate_second(unicode))
5783 : : {
5784 : 0 : unicode = surrogate_pair_to_codepoint(pair_first, unicode);
5785 : 0 : pair_first = 0;
5786 : : }
5787 : : else
5788 : 4 : goto invalid_pair;
5789 : : }
5790 [ - + ]: 9 : else if (is_utf16_surrogate_second(unicode))
5791 : 0 : goto invalid_pair;
5792 : :
5793 [ + + ]: 9 : if (is_utf16_surrogate_first(unicode))
5794 : 4 : pair_first = unicode;
5795 : : else
5796 : : {
5797 : 5 : pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5798 : 5 : appendStringInfoString(&str, cbuf);
5799 : : }
5800 : :
5801 : 9 : instr += 10;
5802 : 9 : len -= 10;
5803 : : }
5804 : : else
5805 [ + - ]: 4 : ereport(ERROR,
5806 : : (errcode(ERRCODE_SYNTAX_ERROR),
5807 : : errmsg("invalid Unicode escape"),
5808 : : errhint("Unicode escapes must be \\XXXX, \\+XXXXXX, \\uXXXX, or \\UXXXXXXXX.")));
5809 : : }
5810 : : else
5811 : : {
5812 [ - + ]: 264 : if (pair_first)
5813 : 0 : goto invalid_pair;
5814 : :
5815 : 264 : appendStringInfoChar(&str, *instr++);
5816 : 264 : len--;
5817 : : }
5818 : : }
5819 : :
5820 : : /* unfinished surrogate pair? */
5821 [ + + ]: 19 : if (pair_first)
5822 : 4 : goto invalid_pair;
5823 : :
5824 : 15 : result = cstring_to_text_with_len(str.data, str.len);
5825 : 15 : pfree(str.data);
5826 : :
5827 : 15 : PG_RETURN_TEXT_P(result);
5828 : :
5829 : 20 : invalid_pair:
5830 [ + - ]: 20 : ereport(ERROR,
5831 : : (errcode(ERRCODE_SYNTAX_ERROR),
5832 : : errmsg("invalid Unicode surrogate pair")));
5833 : : PG_RETURN_NULL(); /* keep compiler quiet */
5834 : : }
|