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