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