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