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