1 /*-------------------------------------------------------------------------
4 * Functions for the variable-length built-in types.
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/utils/adt/varlena.c,v 1.102 2003/07/27 04:53:10 tgl Exp $
13 *-------------------------------------------------------------------------
19 #include "mb/pg_wchar.h"
20 #include "miscadmin.h"
21 #include "access/tuptoaster.h"
22 #include "catalog/pg_type.h"
23 #include "lib/stringinfo.h"
24 #include "libpq/crypt.h"
25 #include "libpq/pqformat.h"
26 #include "utils/array.h"
27 #include "utils/builtins.h"
28 #include "utils/pg_locale.h"
29 #include "utils/lsyscache.h"
32 typedef struct varlena unknown;
34 #define DatumGetUnknownP(X) ((unknown *) PG_DETOAST_DATUM(X))
35 #define DatumGetUnknownPCopy(X) ((unknown *) PG_DETOAST_DATUM_COPY(X))
36 #define PG_GETARG_UNKNOWN_P(n) DatumGetUnknownP(PG_GETARG_DATUM(n))
37 #define PG_GETARG_UNKNOWN_P_COPY(n) DatumGetUnknownPCopy(PG_GETARG_DATUM(n))
38 #define PG_RETURN_UNKNOWN_P(x) PG_RETURN_POINTER(x)
40 #define PG_TEXTARG_GET_STR(arg_) \
41 DatumGetCString(DirectFunctionCall1(textout, PG_GETARG_DATUM(arg_)))
42 #define PG_TEXT_GET_STR(textp_) \
43 DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp_)))
44 #define PG_STR_GET_TEXT(str_) \
45 DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(str_)))
46 #define TEXTLEN(textp) \
47 text_length(PointerGetDatum(textp))
48 #define TEXTPOS(buf_text, from_sub_text) \
49 text_position(PointerGetDatum(buf_text), PointerGetDatum(from_sub_text), 1)
50 #define TEXTDUP(textp) \
51 DatumGetTextPCopy(PointerGetDatum(textp))
52 #define LEFT(buf_text, from_sub_text) \
53 text_substring(PointerGetDatum(buf_text), \
55 TEXTPOS(buf_text, from_sub_text) - 1, false)
56 #define RIGHT(buf_text, from_sub_text, from_sub_text_len) \
57 text_substring(PointerGetDatum(buf_text), \
58 TEXTPOS(buf_text, from_sub_text) + from_sub_text_len, \
61 static int text_cmp(text *arg1, text *arg2);
62 static int32 text_length(Datum str);
63 static int32 text_position(Datum str, Datum search_str, int matchnum);
64 static text *text_substring(Datum str,
67 bool length_not_specified);
70 /*****************************************************************************
72 *****************************************************************************/
75 #define VAL(CH) ((CH) - '0')
76 #define DIG(VAL) ((VAL) + '0')
79 * byteain - converts from printable representation of byte array
81 * Non-printable characters must be passed as '\nnn' (octal) and are
82 * converted to internal form. '\' must be passed as '\\'.
83 * ereport(ERROR, ...) if bad form.
86 * The input is scaned twice.
87 * The error checking of input is minimal.
90 byteain(PG_FUNCTION_ARGS)
92 char *inputText = PG_GETARG_CSTRING(0);
98 for (byte = 0, tp = inputText; *tp != '\0'; byte++)
102 else if ((tp[0] == '\\') &&
103 (tp[1] >= '0' && tp[1] <= '3') &&
104 (tp[2] >= '0' && tp[2] <= '7') &&
105 (tp[3] >= '0' && tp[3] <= '7'))
107 else if ((tp[0] == '\\') &&
113 * one backslash, not followed by 0 or ### valid octal
116 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
117 errmsg("invalid input syntax for bytea")));
122 result = (bytea *) palloc(byte);
123 VARATT_SIZEP(result) = byte; /* set varlena length */
126 rp = VARDATA(result);
131 else if ((tp[0] == '\\') &&
132 (tp[1] >= '0' && tp[1] <= '3') &&
133 (tp[2] >= '0' && tp[2] <= '7') &&
134 (tp[3] >= '0' && tp[3] <= '7'))
140 *rp++ = byte + VAL(tp[3]);
143 else if ((tp[0] == '\\') &&
152 * We should never get here. The first pass should not allow
156 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
157 errmsg("invalid input syntax for bytea")));
161 PG_RETURN_BYTEA_P(result);
165 * byteaout - converts to printable representation of byte array
167 * Non-printable characters are inserted as '\nnn' (octal) and '\' as
170 * NULL vlena should be an error--returning string with NULL for now.
173 byteaout(PG_FUNCTION_ARGS)
175 bytea *vlena = PG_GETARG_BYTEA_P(0);
179 int val; /* holds unprintable chars */
183 len = 1; /* empty string has 1 char */
185 for (i = VARSIZE(vlena) - VARHDRSZ; i != 0; i--, vp++)
189 else if (isprint((unsigned char) *vp))
194 rp = result = (char *) palloc(len);
196 for (i = VARSIZE(vlena) - VARHDRSZ; i != 0; i--, vp++)
203 else if (isprint((unsigned char) *vp))
209 rp[3] = DIG(val & 07);
211 rp[2] = DIG(val & 07);
213 rp[1] = DIG(val & 03);
218 PG_RETURN_CSTRING(result);
222 * bytearecv - converts external binary format to bytea
225 bytearecv(PG_FUNCTION_ARGS)
227 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
231 nbytes = buf->len - buf->cursor;
232 result = (bytea *) palloc(nbytes + VARHDRSZ);
233 VARATT_SIZEP(result) = nbytes + VARHDRSZ;
234 pq_copymsgbytes(buf, VARDATA(result), nbytes);
235 PG_RETURN_BYTEA_P(result);
239 * byteasend - converts bytea to binary format
241 * This is a special case: just copy the input...
244 byteasend(PG_FUNCTION_ARGS)
246 bytea *vlena = PG_GETARG_BYTEA_P_COPY(0);
248 PG_RETURN_BYTEA_P(vlena);
253 * textin - converts "..." to internal representation
256 textin(PG_FUNCTION_ARGS)
258 char *inputText = PG_GETARG_CSTRING(0);
262 /* verify encoding */
263 len = strlen(inputText);
264 pg_verifymbstr(inputText, len, false);
266 result = (text *) palloc(len + VARHDRSZ);
267 VARATT_SIZEP(result) = len + VARHDRSZ;
269 memcpy(VARDATA(result), inputText, len);
272 convertstr(VARDATA(result), len, 0);
275 PG_RETURN_TEXT_P(result);
279 * textout - converts internal representation to "..."
282 textout(PG_FUNCTION_ARGS)
284 text *t = PG_GETARG_TEXT_P(0);
288 len = VARSIZE(t) - VARHDRSZ;
289 result = (char *) palloc(len + 1);
290 memcpy(result, VARDATA(t), len);
294 convertstr(result, len, 1);
297 PG_RETURN_CSTRING(result);
301 * textrecv - converts external binary format to text
304 textrecv(PG_FUNCTION_ARGS)
306 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
311 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
312 result = (text *) palloc(nbytes + VARHDRSZ);
313 VARATT_SIZEP(result) = nbytes + VARHDRSZ;
314 memcpy(VARDATA(result), str, nbytes);
316 PG_RETURN_TEXT_P(result);
320 * textsend - converts text to binary format
323 textsend(PG_FUNCTION_ARGS)
325 text *t = PG_GETARG_TEXT_P(0);
328 pq_begintypsend(&buf);
329 pq_sendtext(&buf, VARDATA(t), VARSIZE(t) - VARHDRSZ);
330 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
335 * unknownin - converts "..." to internal representation
338 unknownin(PG_FUNCTION_ARGS)
340 char *inputStr = PG_GETARG_CSTRING(0);
344 len = strlen(inputStr) + VARHDRSZ;
346 result = (unknown *) palloc(len);
347 VARATT_SIZEP(result) = len;
349 memcpy(VARDATA(result), inputStr, len - VARHDRSZ);
351 PG_RETURN_UNKNOWN_P(result);
355 * unknownout - converts internal representation to "..."
358 unknownout(PG_FUNCTION_ARGS)
360 unknown *t = PG_GETARG_UNKNOWN_P(0);
364 len = VARSIZE(t) - VARHDRSZ;
365 result = (char *) palloc(len + 1);
366 memcpy(result, VARDATA(t), len);
369 PG_RETURN_CSTRING(result);
373 * unknownrecv - converts external binary format to unknown
376 unknownrecv(PG_FUNCTION_ARGS)
378 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
382 nbytes = buf->len - buf->cursor;
383 result = (unknown *) palloc(nbytes + VARHDRSZ);
384 VARATT_SIZEP(result) = nbytes + VARHDRSZ;
385 pq_copymsgbytes(buf, VARDATA(result), nbytes);
386 PG_RETURN_UNKNOWN_P(result);
390 * unknownsend - converts unknown to binary format
392 * This is a special case: just copy the input, since it's
393 * effectively the same format as bytea
396 unknownsend(PG_FUNCTION_ARGS)
398 unknown *vlena = PG_GETARG_UNKNOWN_P_COPY(0);
400 PG_RETURN_UNKNOWN_P(vlena);
404 /* ========== PUBLIC ROUTINES ========== */
408 * returns the logical length of a text*
409 * (which is less than the VARSIZE of the text*)
412 textlen(PG_FUNCTION_ARGS)
414 PG_RETURN_INT32(text_length(PG_GETARG_DATUM(0)));
419 * Does the real work for textlen()
420 * This is broken out so it can be called directly by other string processing
424 text_length(Datum str)
426 /* fastpath when max encoding length is one */
427 if (pg_database_encoding_max_length() == 1)
428 PG_RETURN_INT32(toast_raw_datum_size(str) - VARHDRSZ);
430 if (pg_database_encoding_max_length() > 1)
432 text *t = DatumGetTextP(str);
434 PG_RETURN_INT32(pg_mbstrlen_with_len(VARDATA(t),
435 VARSIZE(t) - VARHDRSZ));
438 /* should never get here */
439 elog(ERROR, "invalid backend encoding: encoding max length < 1");
441 /* not reached: suppress compiler warning */
447 * returns the physical length of a text*
448 * (which is less than the VARSIZE of the text*)
451 textoctetlen(PG_FUNCTION_ARGS)
453 PG_RETURN_INT32(toast_raw_datum_size(PG_GETARG_DATUM(0)) - VARHDRSZ);
458 * takes two text* and returns a text* that is the concatenation of
461 * Rewritten by Sapa, sapa@hq.icb.chel.su. 8-Jul-96.
462 * Updated by Thomas, Thomas.Lockhart@jpl.nasa.gov 1997-07-10.
463 * Allocate space for output in all cases.
464 * XXX - thomas 1997-07-10
467 textcat(PG_FUNCTION_ARGS)
469 text *t1 = PG_GETARG_TEXT_P(0);
470 text *t2 = PG_GETARG_TEXT_P(1);
477 len1 = (VARSIZE(t1) - VARHDRSZ);
481 len2 = (VARSIZE(t2) - VARHDRSZ);
485 len = len1 + len2 + VARHDRSZ;
486 result = (text *) palloc(len);
488 /* Set size of result string... */
489 VARATT_SIZEP(result) = len;
491 /* Fill data field of result string... */
492 ptr = VARDATA(result);
494 memcpy(ptr, VARDATA(t1), len1);
496 memcpy(ptr + len1, VARDATA(t2), len2);
498 PG_RETURN_TEXT_P(result);
503 * Return a substring starting at the specified position.
504 * - thomas 1997-12-31
508 * - starting position (is one-based)
511 * If the starting position is zero or less, then return from the start of the string
512 * adjusting the length to be consistent with the "negative start" per SQL92.
513 * If the length is less than zero, return the remaining string.
515 * Note that the arguments operate on octet length,
516 * so not aware of multibyte character sets.
518 * Added multibyte support.
519 * - Tatsuo Ishii 1998-4-21
520 * Changed behavior if starting position is less than one to conform to SQL92 behavior.
521 * Formerly returned the entire string; now returns a portion.
522 * - Thomas Lockhart 1998-12-10
523 * Now uses faster TOAST-slicing interface
524 * - John Gray 2002-02-22
525 * Remove "#ifdef MULTIBYTE" and test for encoding_max_length instead. Change
526 * behaviors conflicting with SQL92 to meet SQL92 (if E = S + L < S throw
527 * error; if E < 1, return '', not entire string). Fixed MB related bug when
528 * S > LC and < LC + 4 sometimes garbage characters are returned.
529 * - Joe Conway 2002-08-10
532 text_substr(PG_FUNCTION_ARGS)
534 PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0),
541 * text_substr_no_len -
542 * Wrapper to avoid opr_sanity failure due to
543 * one function accepting a different number of args.
546 text_substr_no_len(PG_FUNCTION_ARGS)
548 PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0),
555 * Does the real work for text_substr() and text_substr_no_len()
556 * This is broken out so it can be called directly by other string processing
560 text_substring(Datum str, int32 start, int32 length, bool length_not_specified)
562 int32 eml = pg_database_encoding_max_length();
563 int32 S = start; /* start position */
564 int32 S1; /* adjusted start position */
565 int32 L1; /* adjusted substring length */
567 /* life is easy if the encoding max length is 1 */
572 if (length_not_specified) /* special case - get length to
581 * A negative value for L is the only way for the end position
582 * to be before the start. SQL99 says to throw an error.
586 (errcode(ERRCODE_SUBSTRING_ERROR),
587 errmsg("negative substring length not allowed")));
590 * A zero or negative value for the end position can happen if
591 * the start was negative or one. SQL99 says to return a
592 * zero-length string.
595 return PG_STR_GET_TEXT("");
601 * If the start position is past the end of the string, SQL99 says
602 * to return a zero-length string -- PG_GETARG_TEXT_P_SLICE() will
603 * do that for us. Convert to zero-based starting position
605 return DatumGetTextPSlice(str, S1 - 1, L1);
610 * When encoding max length is > 1, we can't get LC without
611 * detoasting, so we'll grab a conservatively large slice now and
612 * go back later to do the right thing
625 * if S is past the end of the string, the tuple toaster will
626 * return a zero-length string to us
631 * We need to start at position zero because there is no way to
632 * know in advance which byte offset corresponds to the supplied
637 if (length_not_specified) /* special case - get length to
639 slice_size = L1 = -1;
645 * A negative value for L is the only way for the end position
646 * to be before the start. SQL99 says to throw an error.
650 (errcode(ERRCODE_SUBSTRING_ERROR),
651 errmsg("negative substring length not allowed")));
654 * A zero or negative value for the end position can happen if
655 * the start was negative or one. SQL99 says to return a
656 * zero-length string.
659 return PG_STR_GET_TEXT("");
662 * if E is past the end of the string, the tuple toaster will
663 * truncate the length for us
668 * Total slice size in bytes can't be any longer than the
669 * start position plus substring length times the encoding max
672 slice_size = (S1 + L1) * eml;
674 slice = DatumGetTextPSlice(str, slice_start, slice_size);
676 /* see if we got back an empty string */
677 if ((VARSIZE(slice) - VARHDRSZ) == 0)
678 return PG_STR_GET_TEXT("");
680 /* Now we can get the actual length of the slice in MB characters */
681 slice_strlen = pg_mbstrlen_with_len(VARDATA(slice), VARSIZE(slice) - VARHDRSZ);
684 * Check that the start position wasn't > slice_strlen. If so,
685 * SQL99 says to return a zero-length string.
687 if (S1 > slice_strlen)
688 return PG_STR_GET_TEXT("");
691 * Adjust L1 and E1 now that we know the slice string length.
692 * Again remember that S1 is one based, and slice_start is zero
696 E1 = Min(S1 + L1, slice_start + 1 + slice_strlen);
698 E1 = slice_start + 1 + slice_strlen;
701 * Find the start position in the slice; remember S1 is not zero
705 for (i = 0; i < S1 - 1; i++)
708 /* hang onto a pointer to our start position */
712 * Count the actual bytes used by the substring of the requested
715 for (i = S1; i < E1; i++)
718 ret = (text *) palloc(VARHDRSZ + (p - s));
719 VARATT_SIZEP(ret) = VARHDRSZ + (p - s);
720 memcpy(VARDATA(ret), s, (p - s));
725 elog(ERROR, "invalid backend encoding: encoding max length < 1");
727 /* not reached: suppress compiler warning */
728 return PG_STR_GET_TEXT("");
733 * Return the position of the specified substring.
734 * Implements the SQL92 POSITION() function.
735 * Ref: A Guide To The SQL Standard, Date & Darwen, 1997
736 * - thomas 1997-07-27
739 textpos(PG_FUNCTION_ARGS)
741 PG_RETURN_INT32(text_position(PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), 1));
746 * Does the real work for textpos()
747 * This is broken out so it can be called directly by other string processing
751 text_position(Datum str, Datum search_str, int matchnum)
753 int eml = pg_database_encoding_max_length();
754 text *t1 = DatumGetTextP(str);
755 text *t2 = DatumGetTextP(search_str);
764 return 0; /* result for 0th match */
766 if (VARSIZE(t2) <= VARHDRSZ)
767 PG_RETURN_INT32(1); /* result for empty pattern */
769 len1 = (VARSIZE(t1) - VARHDRSZ);
770 len2 = (VARSIZE(t2) - VARHDRSZ);
772 /* no use in searching str past point where search_str will fit */
775 if (eml == 1) /* simple case - single byte encoding */
783 for (p = 0; p <= px; p++)
785 if ((*p2 == *p1) && (strncmp(p1, p2, len2) == 0))
787 if (++match == matchnum)
796 else if (eml > 1) /* not as simple - multibyte encoding */
803 ps1 = p1 = (pg_wchar *) palloc((len1 + 1) * sizeof(pg_wchar));
804 (void) pg_mb2wchar_with_len((unsigned char *) VARDATA(t1), p1, len1);
805 len1 = pg_wchar_strlen(p1);
806 ps2 = p2 = (pg_wchar *) palloc((len2 + 1) * sizeof(pg_wchar));
807 (void) pg_mb2wchar_with_len((unsigned char *) VARDATA(t2), p2, len2);
808 len2 = pg_wchar_strlen(p2);
810 for (p = 0; p <= px; p++)
812 if ((*p2 == *p1) && (pg_wchar_strncmp(p1, p2, len2) == 0))
814 if (++match == matchnum)
827 elog(ERROR, "invalid backend encoding: encoding max length < 1");
829 PG_RETURN_INT32(pos);
833 * Comparison function for text strings with given lengths.
834 * Includes locale support, but must copy strings to temporary memory
835 * to allow null-termination for inputs to strcoll().
839 varstr_cmp(char *arg1, int len1, char *arg2, int len2)
844 * Unfortunately, there is no strncoll(), so in the non-C locale case
845 * we have to do some memory copying. This turns out to be
846 * significantly slower, so we optimize the case where LC_COLLATE is
847 * C. We also try to optimize relatively-short strings by avoiding
848 * palloc/pfree overhead.
850 #define STACKBUFLEN 1024
852 if (!lc_collate_is_c())
854 char a1buf[STACKBUFLEN];
855 char a2buf[STACKBUFLEN];
859 if (len1 >= STACKBUFLEN)
860 a1p = (char *) palloc(len1 + 1);
863 if (len2 >= STACKBUFLEN)
864 a2p = (char *) palloc(len2 + 1);
868 memcpy(a1p, arg1, len1);
870 memcpy(a2p, arg2, len2);
873 result = strcoll(a1p, a2p);
875 if (len1 >= STACKBUFLEN)
877 if (len2 >= STACKBUFLEN)
882 result = strncmp(arg1, arg2, Min(len1, len2));
883 if ((result == 0) && (len1 != len2))
884 result = (len1 < len2) ? -1 : 1;
892 * Internal comparison function for text strings.
896 text_cmp(text *arg1, text *arg2)
906 len1 = VARSIZE(arg1) - VARHDRSZ;
907 len2 = VARSIZE(arg2) - VARHDRSZ;
909 return varstr_cmp(a1p, len1, a2p, len2);
913 * Comparison functions for text strings.
915 * Note: btree indexes need these routines not to leak memory; therefore,
916 * be careful to free working copies of toasted datums. Most places don't
917 * need to be so careful.
921 texteq(PG_FUNCTION_ARGS)
923 text *arg1 = PG_GETARG_TEXT_P(0);
924 text *arg2 = PG_GETARG_TEXT_P(1);
927 /* fast path for different-length inputs */
928 if (VARSIZE(arg1) != VARSIZE(arg2))
931 result = (text_cmp(arg1, arg2) == 0);
933 PG_FREE_IF_COPY(arg1, 0);
934 PG_FREE_IF_COPY(arg2, 1);
936 PG_RETURN_BOOL(result);
940 textne(PG_FUNCTION_ARGS)
942 text *arg1 = PG_GETARG_TEXT_P(0);
943 text *arg2 = PG_GETARG_TEXT_P(1);
946 /* fast path for different-length inputs */
947 if (VARSIZE(arg1) != VARSIZE(arg2))
950 result = (text_cmp(arg1, arg2) != 0);
952 PG_FREE_IF_COPY(arg1, 0);
953 PG_FREE_IF_COPY(arg2, 1);
955 PG_RETURN_BOOL(result);
959 text_lt(PG_FUNCTION_ARGS)
961 text *arg1 = PG_GETARG_TEXT_P(0);
962 text *arg2 = PG_GETARG_TEXT_P(1);
965 result = (text_cmp(arg1, arg2) < 0);
967 PG_FREE_IF_COPY(arg1, 0);
968 PG_FREE_IF_COPY(arg2, 1);
970 PG_RETURN_BOOL(result);
974 text_le(PG_FUNCTION_ARGS)
976 text *arg1 = PG_GETARG_TEXT_P(0);
977 text *arg2 = PG_GETARG_TEXT_P(1);
980 result = (text_cmp(arg1, arg2) <= 0);
982 PG_FREE_IF_COPY(arg1, 0);
983 PG_FREE_IF_COPY(arg2, 1);
985 PG_RETURN_BOOL(result);
989 text_gt(PG_FUNCTION_ARGS)
991 text *arg1 = PG_GETARG_TEXT_P(0);
992 text *arg2 = PG_GETARG_TEXT_P(1);
995 result = (text_cmp(arg1, arg2) > 0);
997 PG_FREE_IF_COPY(arg1, 0);
998 PG_FREE_IF_COPY(arg2, 1);
1000 PG_RETURN_BOOL(result);
1004 text_ge(PG_FUNCTION_ARGS)
1006 text *arg1 = PG_GETARG_TEXT_P(0);
1007 text *arg2 = PG_GETARG_TEXT_P(1);
1010 result = (text_cmp(arg1, arg2) >= 0);
1012 PG_FREE_IF_COPY(arg1, 0);
1013 PG_FREE_IF_COPY(arg2, 1);
1015 PG_RETURN_BOOL(result);
1019 bttextcmp(PG_FUNCTION_ARGS)
1021 text *arg1 = PG_GETARG_TEXT_P(0);
1022 text *arg2 = PG_GETARG_TEXT_P(1);
1025 result = text_cmp(arg1, arg2);
1027 PG_FREE_IF_COPY(arg1, 0);
1028 PG_FREE_IF_COPY(arg2, 1);
1030 PG_RETURN_INT32(result);
1035 text_larger(PG_FUNCTION_ARGS)
1037 text *arg1 = PG_GETARG_TEXT_P(0);
1038 text *arg2 = PG_GETARG_TEXT_P(1);
1041 result = ((text_cmp(arg1, arg2) > 0) ? arg1 : arg2);
1043 PG_RETURN_TEXT_P(result);
1047 text_smaller(PG_FUNCTION_ARGS)
1049 text *arg1 = PG_GETARG_TEXT_P(0);
1050 text *arg2 = PG_GETARG_TEXT_P(1);
1053 result = ((text_cmp(arg1, arg2) < 0) ? arg1 : arg2);
1055 PG_RETURN_TEXT_P(result);
1060 * The following operators support character-by-character comparison
1061 * of text data types, to allow building indexes suitable for LIKE
1066 internal_text_pattern_compare(text *arg1, text *arg2)
1070 result = memcmp(VARDATA(arg1), VARDATA(arg2),
1071 Min(VARSIZE(arg1), VARSIZE(arg2)) - VARHDRSZ);
1074 else if (VARSIZE(arg1) < VARSIZE(arg2))
1076 else if (VARSIZE(arg1) > VARSIZE(arg2))
1084 text_pattern_lt(PG_FUNCTION_ARGS)
1086 text *arg1 = PG_GETARG_TEXT_P(0);
1087 text *arg2 = PG_GETARG_TEXT_P(1);
1090 result = internal_text_pattern_compare(arg1, arg2);
1092 PG_FREE_IF_COPY(arg1, 0);
1093 PG_FREE_IF_COPY(arg2, 1);
1095 PG_RETURN_BOOL(result < 0);
1100 text_pattern_le(PG_FUNCTION_ARGS)
1102 text *arg1 = PG_GETARG_TEXT_P(0);
1103 text *arg2 = PG_GETARG_TEXT_P(1);
1106 result = internal_text_pattern_compare(arg1, arg2);
1108 PG_FREE_IF_COPY(arg1, 0);
1109 PG_FREE_IF_COPY(arg2, 1);
1111 PG_RETURN_BOOL(result <= 0);
1116 text_pattern_eq(PG_FUNCTION_ARGS)
1118 text *arg1 = PG_GETARG_TEXT_P(0);
1119 text *arg2 = PG_GETARG_TEXT_P(1);
1122 if (VARSIZE(arg1) != VARSIZE(arg2))
1125 result = internal_text_pattern_compare(arg1, arg2);
1127 PG_FREE_IF_COPY(arg1, 0);
1128 PG_FREE_IF_COPY(arg2, 1);
1130 PG_RETURN_BOOL(result == 0);
1135 text_pattern_ge(PG_FUNCTION_ARGS)
1137 text *arg1 = PG_GETARG_TEXT_P(0);
1138 text *arg2 = PG_GETARG_TEXT_P(1);
1141 result = internal_text_pattern_compare(arg1, arg2);
1143 PG_FREE_IF_COPY(arg1, 0);
1144 PG_FREE_IF_COPY(arg2, 1);
1146 PG_RETURN_BOOL(result >= 0);
1151 text_pattern_gt(PG_FUNCTION_ARGS)
1153 text *arg1 = PG_GETARG_TEXT_P(0);
1154 text *arg2 = PG_GETARG_TEXT_P(1);
1157 result = internal_text_pattern_compare(arg1, arg2);
1159 PG_FREE_IF_COPY(arg1, 0);
1160 PG_FREE_IF_COPY(arg2, 1);
1162 PG_RETURN_BOOL(result > 0);
1167 text_pattern_ne(PG_FUNCTION_ARGS)
1169 text *arg1 = PG_GETARG_TEXT_P(0);
1170 text *arg2 = PG_GETARG_TEXT_P(1);
1173 if (VARSIZE(arg1) != VARSIZE(arg2))
1176 result = internal_text_pattern_compare(arg1, arg2);
1178 PG_FREE_IF_COPY(arg1, 0);
1179 PG_FREE_IF_COPY(arg2, 1);
1181 PG_RETURN_BOOL(result != 0);
1186 bttext_pattern_cmp(PG_FUNCTION_ARGS)
1188 text *arg1 = PG_GETARG_TEXT_P(0);
1189 text *arg2 = PG_GETARG_TEXT_P(1);
1192 result = internal_text_pattern_compare(arg1, arg2);
1194 PG_FREE_IF_COPY(arg1, 0);
1195 PG_FREE_IF_COPY(arg2, 1);
1197 PG_RETURN_INT32(result);
1201 /*-------------------------------------------------------------
1204 * get the number of bytes contained in an instance of type 'bytea'
1205 *-------------------------------------------------------------
1208 byteaoctetlen(PG_FUNCTION_ARGS)
1210 PG_RETURN_INT32(toast_raw_datum_size(PG_GETARG_DATUM(0)) - VARHDRSZ);
1215 * takes two bytea* and returns a bytea* that is the concatenation of
1218 * Cloned from textcat and modified as required.
1221 byteacat(PG_FUNCTION_ARGS)
1223 bytea *t1 = PG_GETARG_BYTEA_P(0);
1224 bytea *t2 = PG_GETARG_BYTEA_P(1);
1231 len1 = (VARSIZE(t1) - VARHDRSZ);
1235 len2 = (VARSIZE(t2) - VARHDRSZ);
1239 len = len1 + len2 + VARHDRSZ;
1240 result = (bytea *) palloc(len);
1242 /* Set size of result string... */
1243 VARATT_SIZEP(result) = len;
1245 /* Fill data field of result string... */
1246 ptr = VARDATA(result);
1248 memcpy(ptr, VARDATA(t1), len1);
1250 memcpy(ptr + len1, VARDATA(t2), len2);
1252 PG_RETURN_BYTEA_P(result);
1255 #define PG_STR_GET_BYTEA(str_) \
1256 DatumGetByteaP(DirectFunctionCall1(byteain, CStringGetDatum(str_)))
1259 * Return a substring starting at the specified position.
1260 * Cloned from text_substr and modified as required.
1264 * - starting position (is one-based)
1265 * - string length (optional)
1267 * If the starting position is zero or less, then return from the start of the string
1268 * adjusting the length to be consistent with the "negative start" per SQL92.
1269 * If the length is less than zero, an ERROR is thrown. If no third argument
1270 * (length) is provided, the length to the end of the string is assumed.
1273 bytea_substr(PG_FUNCTION_ARGS)
1275 int S = PG_GETARG_INT32(1); /* start position */
1276 int S1; /* adjusted start position */
1277 int L1; /* adjusted substring length */
1281 if (fcinfo->nargs == 2)
1284 * Not passed a length - PG_GETARG_BYTEA_P_SLICE() grabs
1285 * everything to the end of the string if we pass it a negative
1293 int E = S + PG_GETARG_INT32(2);
1296 * A negative value for L is the only way for the end position to
1297 * be before the start. SQL99 says to throw an error.
1301 (errcode(ERRCODE_SUBSTRING_ERROR),
1302 errmsg("negative substring length not allowed")));
1305 * A zero or negative value for the end position can happen if the
1306 * start was negative or one. SQL99 says to return a zero-length
1310 PG_RETURN_BYTEA_P(PG_STR_GET_BYTEA(""));
1316 * If the start position is past the end of the string, SQL99 says to
1317 * return a zero-length string -- PG_GETARG_TEXT_P_SLICE() will do
1318 * that for us. Convert to zero-based starting position
1320 PG_RETURN_BYTEA_P(PG_GETARG_BYTEA_P_SLICE(0, S1 - 1, L1));
1324 * bytea_substr_no_len -
1325 * Wrapper to avoid opr_sanity failure due to
1326 * one function accepting a different number of args.
1329 bytea_substr_no_len(PG_FUNCTION_ARGS)
1331 return bytea_substr(fcinfo);
1336 * Return the position of the specified substring.
1337 * Implements the SQL92 POSITION() function.
1338 * Cloned from textpos and modified as required.
1341 byteapos(PG_FUNCTION_ARGS)
1343 bytea *t1 = PG_GETARG_BYTEA_P(0);
1344 bytea *t2 = PG_GETARG_BYTEA_P(1);
1353 if (VARSIZE(t2) <= VARHDRSZ)
1354 PG_RETURN_INT32(1); /* result for empty pattern */
1356 len1 = (VARSIZE(t1) - VARHDRSZ);
1357 len2 = (VARSIZE(t2) - VARHDRSZ);
1364 for (p = 0; p <= px; p++)
1366 if ((*p2 == *p1) && (memcmp(p1, p2, len2) == 0))
1374 PG_RETURN_INT32(pos);
1377 /*-------------------------------------------------------------
1380 * this routine treats "bytea" as an array of bytes.
1381 * It returns the Nth byte (a number between 0 and 255).
1382 *-------------------------------------------------------------
1385 byteaGetByte(PG_FUNCTION_ARGS)
1387 bytea *v = PG_GETARG_BYTEA_P(0);
1388 int32 n = PG_GETARG_INT32(1);
1392 len = VARSIZE(v) - VARHDRSZ;
1394 if (n < 0 || n >= len)
1396 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1397 errmsg("index %d out of valid range, 0..%d",
1400 byte = ((unsigned char *) VARDATA(v))[n];
1402 PG_RETURN_INT32(byte);
1405 /*-------------------------------------------------------------
1408 * This routine treats a "bytea" type like an array of bits.
1409 * It returns the value of the Nth bit (0 or 1).
1411 *-------------------------------------------------------------
1414 byteaGetBit(PG_FUNCTION_ARGS)
1416 bytea *v = PG_GETARG_BYTEA_P(0);
1417 int32 n = PG_GETARG_INT32(1);
1423 len = VARSIZE(v) - VARHDRSZ;
1425 if (n < 0 || n >= len * 8)
1427 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1428 errmsg("index %d out of valid range, 0..%d",
1434 byte = ((unsigned char *) VARDATA(v))[byteNo];
1436 if (byte & (1 << bitNo))
1442 /*-------------------------------------------------------------
1445 * Given an instance of type 'bytea' creates a new one with
1446 * the Nth byte set to the given value.
1448 *-------------------------------------------------------------
1451 byteaSetByte(PG_FUNCTION_ARGS)
1453 bytea *v = PG_GETARG_BYTEA_P(0);
1454 int32 n = PG_GETARG_INT32(1);
1455 int32 newByte = PG_GETARG_INT32(2);
1459 len = VARSIZE(v) - VARHDRSZ;
1461 if (n < 0 || n >= len)
1463 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1464 errmsg("index %d out of valid range, 0..%d",
1468 * Make a copy of the original varlena.
1470 res = (bytea *) palloc(VARSIZE(v));
1471 memcpy((char *) res, (char *) v, VARSIZE(v));
1476 ((unsigned char *) VARDATA(res))[n] = newByte;
1478 PG_RETURN_BYTEA_P(res);
1481 /*-------------------------------------------------------------
1484 * Given an instance of type 'bytea' creates a new one with
1485 * the Nth bit set to the given value.
1487 *-------------------------------------------------------------
1490 byteaSetBit(PG_FUNCTION_ARGS)
1492 bytea *v = PG_GETARG_BYTEA_P(0);
1493 int32 n = PG_GETARG_INT32(1);
1494 int32 newBit = PG_GETARG_INT32(2);
1502 len = VARSIZE(v) - VARHDRSZ;
1504 if (n < 0 || n >= len * 8)
1506 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1507 errmsg("index %d out of valid range, 0..%d",
1516 if (newBit != 0 && newBit != 1)
1518 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1519 errmsg("new bit must be 0 or 1")));
1522 * Make a copy of the original varlena.
1524 res = (bytea *) palloc(VARSIZE(v));
1525 memcpy((char *) res, (char *) v, VARSIZE(v));
1530 oldByte = ((unsigned char *) VARDATA(res))[byteNo];
1533 newByte = oldByte & (~(1 << bitNo));
1535 newByte = oldByte | (1 << bitNo);
1537 ((unsigned char *) VARDATA(res))[byteNo] = newByte;
1539 PG_RETURN_BYTEA_P(res);
1544 * Converts a text type to a Name type.
1547 text_name(PG_FUNCTION_ARGS)
1549 text *s = PG_GETARG_TEXT_P(0);
1553 len = VARSIZE(s) - VARHDRSZ;
1555 /* Truncate oversize input */
1556 if (len >= NAMEDATALEN)
1557 len = NAMEDATALEN - 1;
1560 printf("text- convert string length %d (%d) ->%d\n",
1561 VARSIZE(s) - VARHDRSZ, VARSIZE(s), len);
1564 result = (Name) palloc(NAMEDATALEN);
1565 memcpy(NameStr(*result), VARDATA(s), len);
1567 /* now null pad to full length... */
1568 while (len < NAMEDATALEN)
1570 *(NameStr(*result) + len) = '\0';
1574 PG_RETURN_NAME(result);
1578 * Converts a Name type to a text type.
1581 name_text(PG_FUNCTION_ARGS)
1583 Name s = PG_GETARG_NAME(0);
1587 len = strlen(NameStr(*s));
1590 printf("text- convert string length %d (%d) ->%d\n",
1591 VARSIZE(s) - VARHDRSZ, VARSIZE(s), len);
1594 result = palloc(VARHDRSZ + len);
1595 VARATT_SIZEP(result) = VARHDRSZ + len;
1596 memcpy(VARDATA(result), NameStr(*s), len);
1598 PG_RETURN_TEXT_P(result);
1603 * textToQualifiedNameList - convert a text object to list of names
1605 * This implements the input parsing needed by nextval() and other
1606 * functions that take a text parameter representing a qualified name.
1607 * We split the name at dots, downcase if not double-quoted, and
1608 * truncate names if they're too long.
1611 textToQualifiedNameList(text *textval, const char *caller)
1618 /* Convert to C string (handles possible detoasting). */
1619 /* Note we rely on being able to modify rawname below. */
1620 rawname = DatumGetCString(DirectFunctionCall1(textout,
1621 PointerGetDatum(textval)));
1623 if (!SplitIdentifierString(rawname, '.', &namelist))
1625 (errcode(ERRCODE_INVALID_NAME),
1626 errmsg("invalid name syntax")));
1628 if (namelist == NIL)
1630 (errcode(ERRCODE_INVALID_NAME),
1631 errmsg("invalid name syntax")));
1633 foreach(l, namelist)
1635 char *curname = (char *) lfirst(l);
1637 result = lappend(result, makeString(pstrdup(curname)));
1647 * SplitIdentifierString --- parse a string containing identifiers
1649 * This is the guts of textToQualifiedNameList, and is exported for use in
1650 * other situations such as parsing GUC variables. In the GUC case, it's
1651 * important to avoid memory leaks, so the API is designed to minimize the
1652 * amount of stuff that needs to be allocated and freed.
1655 * rawstring: the input string; must be overwritable! On return, it's
1656 * been modified to contain the separated identifiers.
1657 * separator: the separator punctuation expected between identifiers
1658 * (typically '.' or ','). Whitespace may also appear around
1661 * namelist: filled with a palloc'd list of pointers to identifiers within
1662 * rawstring. Caller should freeList() this even on error return.
1664 * Returns TRUE if okay, FALSE if there is a syntax error in the string.
1666 * Note that an empty string is considered okay here, though not in
1667 * textToQualifiedNameList.
1670 SplitIdentifierString(char *rawstring, char separator,
1673 char *nextp = rawstring;
1678 while (isspace((unsigned char) *nextp))
1679 nextp++; /* skip leading whitespace */
1682 return true; /* allow empty string */
1684 /* At the top of the loop, we are at start of a new identifier. */
1693 /* Quoted name --- collapse quote-quote pairs, no downcasing */
1694 curname = nextp + 1;
1697 endp = strchr(nextp + 1, '\"');
1699 return false; /* mismatched quotes */
1700 if (endp[1] != '\"')
1701 break; /* found end of quoted name */
1702 /* Collapse adjacent quotes into one quote, and look again */
1703 memmove(endp, endp + 1, strlen(endp));
1706 /* endp now points at the terminating quote */
1711 /* Unquoted name --- extends to separator or whitespace */
1713 while (*nextp && *nextp != separator &&
1714 !isspace((unsigned char) *nextp))
1717 * It's important that this match the identifier
1718 * downcasing code used by backend/parser/scan.l.
1720 if (isupper((unsigned char) *nextp))
1721 *nextp = tolower((unsigned char) *nextp);
1725 if (curname == nextp)
1726 return false; /* empty unquoted name not allowed */
1729 while (isspace((unsigned char) *nextp))
1730 nextp++; /* skip trailing whitespace */
1732 if (*nextp == separator)
1735 while (isspace((unsigned char) *nextp))
1736 nextp++; /* skip leading whitespace for next */
1737 /* we expect another name, so done remains false */
1739 else if (*nextp == '\0')
1742 return false; /* invalid syntax */
1744 /* Now safe to overwrite separator with a null */
1747 /* Truncate name if it's overlength; again, should match scan.l */
1748 curlen = strlen(curname);
1749 if (curlen >= NAMEDATALEN)
1751 curlen = pg_mbcliplen(curname, curlen, NAMEDATALEN - 1);
1752 curname[curlen] = '\0';
1756 * Finished isolating current name --- add it to list
1758 *namelist = lappend(*namelist, curname);
1760 /* Loop back if we didn't reach end of string */
1767 /*****************************************************************************
1768 * Comparison Functions used for bytea
1770 * Note: btree indexes need these routines not to leak memory; therefore,
1771 * be careful to free working copies of toasted datums. Most places don't
1772 * need to be so careful.
1773 *****************************************************************************/
1776 byteaeq(PG_FUNCTION_ARGS)
1778 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1779 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1784 len1 = VARSIZE(arg1) - VARHDRSZ;
1785 len2 = VARSIZE(arg2) - VARHDRSZ;
1787 /* fast path for different-length inputs */
1791 result = (memcmp(VARDATA(arg1), VARDATA(arg2), len1) == 0);
1793 PG_FREE_IF_COPY(arg1, 0);
1794 PG_FREE_IF_COPY(arg2, 1);
1796 PG_RETURN_BOOL(result);
1800 byteane(PG_FUNCTION_ARGS)
1802 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1803 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1808 len1 = VARSIZE(arg1) - VARHDRSZ;
1809 len2 = VARSIZE(arg2) - VARHDRSZ;
1811 /* fast path for different-length inputs */
1815 result = (memcmp(VARDATA(arg1), VARDATA(arg2), len1) != 0);
1817 PG_FREE_IF_COPY(arg1, 0);
1818 PG_FREE_IF_COPY(arg2, 1);
1820 PG_RETURN_BOOL(result);
1824 bytealt(PG_FUNCTION_ARGS)
1826 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1827 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1832 len1 = VARSIZE(arg1) - VARHDRSZ;
1833 len2 = VARSIZE(arg2) - VARHDRSZ;
1835 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1837 PG_FREE_IF_COPY(arg1, 0);
1838 PG_FREE_IF_COPY(arg2, 1);
1840 PG_RETURN_BOOL((cmp < 0) || ((cmp == 0) && (len1 < len2)));
1844 byteale(PG_FUNCTION_ARGS)
1846 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1847 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1852 len1 = VARSIZE(arg1) - VARHDRSZ;
1853 len2 = VARSIZE(arg2) - VARHDRSZ;
1855 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1857 PG_FREE_IF_COPY(arg1, 0);
1858 PG_FREE_IF_COPY(arg2, 1);
1860 PG_RETURN_BOOL((cmp < 0) || ((cmp == 0) && (len1 <= len2)));
1864 byteagt(PG_FUNCTION_ARGS)
1866 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1867 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1872 len1 = VARSIZE(arg1) - VARHDRSZ;
1873 len2 = VARSIZE(arg2) - VARHDRSZ;
1875 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1877 PG_FREE_IF_COPY(arg1, 0);
1878 PG_FREE_IF_COPY(arg2, 1);
1880 PG_RETURN_BOOL((cmp > 0) || ((cmp == 0) && (len1 > len2)));
1884 byteage(PG_FUNCTION_ARGS)
1886 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1887 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1892 len1 = VARSIZE(arg1) - VARHDRSZ;
1893 len2 = VARSIZE(arg2) - VARHDRSZ;
1895 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1897 PG_FREE_IF_COPY(arg1, 0);
1898 PG_FREE_IF_COPY(arg2, 1);
1900 PG_RETURN_BOOL((cmp > 0) || ((cmp == 0) && (len1 >= len2)));
1904 byteacmp(PG_FUNCTION_ARGS)
1906 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1907 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1912 len1 = VARSIZE(arg1) - VARHDRSZ;
1913 len2 = VARSIZE(arg2) - VARHDRSZ;
1915 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1916 if ((cmp == 0) && (len1 != len2))
1917 cmp = (len1 < len2) ? -1 : 1;
1919 PG_FREE_IF_COPY(arg1, 0);
1920 PG_FREE_IF_COPY(arg2, 1);
1922 PG_RETURN_INT32(cmp);
1927 * replace all occurrences of 'old_sub_str' in 'orig_str'
1928 * with 'new_sub_str' to form 'new_str'
1930 * returns 'orig_str' if 'old_sub_str' == '' or 'orig_str' == ''
1931 * otherwise returns 'new_str'
1934 replace_text(PG_FUNCTION_ARGS)
1941 text *src_text = PG_GETARG_TEXT_P(0);
1942 int src_text_len = TEXTLEN(src_text);
1943 text *from_sub_text = PG_GETARG_TEXT_P(1);
1944 int from_sub_text_len = TEXTLEN(from_sub_text);
1945 text *to_sub_text = PG_GETARG_TEXT_P(2);
1946 char *to_sub_str = PG_TEXT_GET_STR(to_sub_text);
1947 StringInfo str = makeStringInfo();
1949 if (src_text_len == 0 || from_sub_text_len == 0)
1950 PG_RETURN_TEXT_P(src_text);
1952 buf_text = TEXTDUP(src_text);
1953 curr_posn = TEXTPOS(buf_text, from_sub_text);
1955 while (curr_posn > 0)
1957 left_text = LEFT(buf_text, from_sub_text);
1958 right_text = RIGHT(buf_text, from_sub_text, from_sub_text_len);
1960 appendStringInfoString(str, PG_TEXT_GET_STR(left_text));
1961 appendStringInfoString(str, to_sub_str);
1965 buf_text = right_text;
1966 curr_posn = TEXTPOS(buf_text, from_sub_text);
1969 appendStringInfoString(str, PG_TEXT_GET_STR(buf_text));
1972 ret_text = PG_STR_GET_TEXT(str->data);
1976 PG_RETURN_TEXT_P(ret_text);
1981 * parse input string
1982 * return ord item (1 based)
1983 * based on provided field separator
1986 split_text(PG_FUNCTION_ARGS)
1988 text *inputstring = PG_GETARG_TEXT_P(0);
1989 int inputstring_len = TEXTLEN(inputstring);
1990 text *fldsep = PG_GETARG_TEXT_P(1);
1991 int fldsep_len = TEXTLEN(fldsep);
1992 int fldnum = PG_GETARG_INT32(2);
1997 /* return empty string for empty input string */
1998 if (inputstring_len < 1)
1999 PG_RETURN_TEXT_P(PG_STR_GET_TEXT(""));
2001 /* empty field separator */
2004 if (fldnum == 1) /* first field - just return the input
2006 PG_RETURN_TEXT_P(inputstring);
2007 else /* otherwise return an empty string */
2008 PG_RETURN_TEXT_P(PG_STR_GET_TEXT(""));
2011 /* field number is 1 based */
2014 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2015 errmsg("field position must be greater than zero")));
2017 start_posn = text_position(PointerGetDatum(inputstring),
2018 PointerGetDatum(fldsep),
2020 end_posn = text_position(PointerGetDatum(inputstring),
2021 PointerGetDatum(fldsep),
2024 if ((start_posn == 0) && (end_posn == 0)) /* fldsep not found */
2026 if (fldnum == 1) /* first field - just return the input
2028 PG_RETURN_TEXT_P(inputstring);
2029 else /* otherwise return an empty string */
2030 PG_RETURN_TEXT_P(PG_STR_GET_TEXT(""));
2032 else if ((start_posn != 0) && (end_posn == 0))
2034 /* last field requested */
2035 result_text = text_substring(PointerGetDatum(inputstring), start_posn + fldsep_len, -1, true);
2036 PG_RETURN_TEXT_P(result_text);
2038 else if ((start_posn == 0) && (end_posn != 0))
2040 /* first field requested */
2041 result_text = LEFT(inputstring, fldsep);
2042 PG_RETURN_TEXT_P(result_text);
2046 /* prior to last field requested */
2047 result_text = text_substring(PointerGetDatum(inputstring), start_posn + fldsep_len, end_posn - start_posn - fldsep_len, false);
2048 PG_RETURN_TEXT_P(result_text);
2054 * parse input string
2055 * return text array of elements
2056 * based on provided field separator
2059 text_to_array(PG_FUNCTION_ARGS)
2061 text *inputstring = PG_GETARG_TEXT_P(0);
2062 int inputstring_len = TEXTLEN(inputstring);
2063 text *fldsep = PG_GETARG_TEXT_P(1);
2064 int fldsep_len = TEXTLEN(fldsep);
2068 text *result_text = NULL;
2069 ArrayBuildState *astate = NULL;
2070 MemoryContext oldcontext = CurrentMemoryContext;
2072 /* return NULL for empty input string */
2073 if (inputstring_len < 1)
2076 /* empty field separator
2077 * return one element, 1D, array using the input string */
2079 PG_RETURN_ARRAYTYPE_P(create_singleton_array(fcinfo, TEXTOID,
2080 CStringGetDatum(inputstring), 1));
2082 /* start with end position holding the initial start position */
2084 for (fldnum=1;;fldnum++) /* field number is 1 based */
2087 bool disnull = false;
2089 start_posn = end_posn;
2090 end_posn = text_position(PointerGetDatum(inputstring),
2091 PointerGetDatum(fldsep),
2094 if ((start_posn == 0) && (end_posn == 0)) /* fldsep not found */
2099 * return one element, 1D, array using the input string */
2100 PG_RETURN_ARRAYTYPE_P(create_singleton_array(fcinfo, TEXTOID,
2101 CStringGetDatum(inputstring), 1));
2105 /* otherwise create array and exit */
2106 PG_RETURN_ARRAYTYPE_P(makeArrayResult(astate, oldcontext));
2109 else if ((start_posn != 0) && (end_posn == 0))
2111 /* last field requested */
2112 result_text = text_substring(PointerGetDatum(inputstring), start_posn + fldsep_len, -1, true);
2114 else if ((start_posn == 0) && (end_posn != 0))
2116 /* first field requested */
2117 result_text = LEFT(inputstring, fldsep);
2121 /* prior to last field requested */
2122 result_text = text_substring(PointerGetDatum(inputstring), start_posn + fldsep_len, end_posn - start_posn - fldsep_len, false);
2125 /* stash away current value */
2126 dvalue = PointerGetDatum(result_text);
2127 astate = accumArrayResult(astate, dvalue,
2128 disnull, TEXTOID, oldcontext);
2132 /* never reached -- keep compiler quiet */
2138 * concatenate Cstring representation of input array elements
2139 * using provided field separator
2142 array_to_text(PG_FUNCTION_ARGS)
2144 ArrayType *v = PG_GETARG_ARRAYTYPE_P(0);
2145 char *fldsep = PG_TEXTARG_GET_STR(1);
2146 int nitems, *dims, ndims;
2153 StringInfo result_str = makeStringInfo();
2155 ArrayMetaState *my_extra;
2157 p = ARR_DATA_PTR(v);
2158 ndims = ARR_NDIM(v);
2160 nitems = ArrayGetNItems(ndims, dims);
2162 /* if there are no elements, return an empty string */
2164 PG_RETURN_TEXT_P(PG_STR_GET_TEXT(""));
2166 element_type = ARR_ELEMTYPE(v);
2169 * We arrange to look up info about element type, including its output
2170 * conversion proc, only once per series of calls, assuming the element
2171 * type doesn't change underneath us.
2173 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
2174 if (my_extra == NULL)
2176 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
2177 sizeof(ArrayMetaState));
2178 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
2179 my_extra->element_type = InvalidOid;
2182 if (my_extra->element_type != element_type)
2184 /* Get info about element type, including its output conversion proc */
2185 get_type_io_data(element_type, IOFunc_output,
2186 &my_extra->typlen, &my_extra->typbyval,
2187 &my_extra->typalign, &my_extra->typdelim,
2188 &my_extra->typelem, &my_extra->typiofunc);
2189 fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
2190 fcinfo->flinfo->fn_mcxt);
2191 my_extra->element_type = element_type;
2193 typlen = my_extra->typlen;
2194 typbyval = my_extra->typbyval;
2195 typalign = my_extra->typalign;
2196 typelem = my_extra->typelem;
2198 for (i = 0; i < nitems; i++)
2203 itemvalue = fetch_att(p, typbyval, typlen);
2205 value = DatumGetCString(FunctionCall3(&my_extra->proc,
2207 ObjectIdGetDatum(typelem),
2208 Int32GetDatum(-1)));
2211 appendStringInfo(result_str, "%s%s", fldsep, value);
2213 appendStringInfo(result_str, "%s", value);
2215 p = att_addlength(p, typlen, PointerGetDatum(p));
2216 p = (char *) att_align(p, typalign);
2219 PG_RETURN_TEXT_P(PG_STR_GET_TEXT(result_str->data));
2224 * Convert a int32 to a string containing a base 16 (hex) representation of
2228 to_hex32(PG_FUNCTION_ARGS)
2230 static char digits[] = "0123456789abcdef";
2231 char buf[32]; /* bigger than needed, but reasonable */
2234 int32 value = PG_GETARG_INT32(0);
2236 ptr = buf + sizeof(buf) - 1;
2241 *--ptr = digits[value % HEXBASE];
2243 } while (ptr > buf && value);
2245 result_text = PG_STR_GET_TEXT(ptr);
2246 PG_RETURN_TEXT_P(result_text);
2250 * Convert a int64 to a string containing a base 16 (hex) representation of
2254 to_hex64(PG_FUNCTION_ARGS)
2256 static char digits[] = "0123456789abcdef";
2257 char buf[32]; /* bigger than needed, but reasonable */
2260 int64 value = PG_GETARG_INT64(0);
2262 ptr = buf + sizeof(buf) - 1;
2267 *--ptr = digits[value % HEXBASE];
2269 } while (ptr > buf && value);
2271 result_text = PG_STR_GET_TEXT(ptr);
2272 PG_RETURN_TEXT_P(result_text);
2276 * Create an md5 hash of a text string and return it as hex
2278 * md5 produces a 16 byte (128 bit) hash; double it for hex
2280 #define MD5_HASH_LEN 32
2283 md5_text(PG_FUNCTION_ARGS)
2285 char *buff = PG_TEXT_GET_STR(PG_GETARG_TEXT_P(0));
2286 size_t len = strlen(buff);
2290 /* leave room for the terminating '\0' */
2291 hexsum = (char *) palloc(MD5_HASH_LEN + 1);
2293 /* get the hash result */
2294 md5_hash((void *) buff, len, hexsum);
2296 /* convert to text and return it */
2297 result_text = PG_STR_GET_TEXT(hexsum);
2298 PG_RETURN_TEXT_P(result_text);