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