1 /*-------------------------------------------------------------------------
4 * Functions for the variable-length built-in types.
6 * Portions Copyright (c) 1996-2003, 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.105 2003/08/04 04:03: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);
271 PG_RETURN_TEXT_P(result);
275 * textout - converts internal representation to "..."
278 textout(PG_FUNCTION_ARGS)
280 text *t = PG_GETARG_TEXT_P(0);
284 len = VARSIZE(t) - VARHDRSZ;
285 result = (char *) palloc(len + 1);
286 memcpy(result, VARDATA(t), len);
289 PG_RETURN_CSTRING(result);
293 * textrecv - converts external binary format to text
296 textrecv(PG_FUNCTION_ARGS)
298 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
303 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
304 result = (text *) palloc(nbytes + VARHDRSZ);
305 VARATT_SIZEP(result) = nbytes + VARHDRSZ;
306 memcpy(VARDATA(result), str, nbytes);
308 PG_RETURN_TEXT_P(result);
312 * textsend - converts text to binary format
315 textsend(PG_FUNCTION_ARGS)
317 text *t = PG_GETARG_TEXT_P(0);
320 pq_begintypsend(&buf);
321 pq_sendtext(&buf, VARDATA(t), VARSIZE(t) - VARHDRSZ);
322 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
327 * unknownin - converts "..." to internal representation
330 unknownin(PG_FUNCTION_ARGS)
332 char *inputStr = PG_GETARG_CSTRING(0);
336 len = strlen(inputStr) + VARHDRSZ;
338 result = (unknown *) palloc(len);
339 VARATT_SIZEP(result) = len;
341 memcpy(VARDATA(result), inputStr, len - VARHDRSZ);
343 PG_RETURN_UNKNOWN_P(result);
347 * unknownout - converts internal representation to "..."
350 unknownout(PG_FUNCTION_ARGS)
352 unknown *t = PG_GETARG_UNKNOWN_P(0);
356 len = VARSIZE(t) - VARHDRSZ;
357 result = (char *) palloc(len + 1);
358 memcpy(result, VARDATA(t), len);
361 PG_RETURN_CSTRING(result);
365 * unknownrecv - converts external binary format to unknown
368 unknownrecv(PG_FUNCTION_ARGS)
370 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
374 nbytes = buf->len - buf->cursor;
375 result = (unknown *) palloc(nbytes + VARHDRSZ);
376 VARATT_SIZEP(result) = nbytes + VARHDRSZ;
377 pq_copymsgbytes(buf, VARDATA(result), nbytes);
378 PG_RETURN_UNKNOWN_P(result);
382 * unknownsend - converts unknown to binary format
384 * This is a special case: just copy the input, since it's
385 * effectively the same format as bytea
388 unknownsend(PG_FUNCTION_ARGS)
390 unknown *vlena = PG_GETARG_UNKNOWN_P_COPY(0);
392 PG_RETURN_UNKNOWN_P(vlena);
396 /* ========== PUBLIC ROUTINES ========== */
400 * returns the logical length of a text*
401 * (which is less than the VARSIZE of the text*)
404 textlen(PG_FUNCTION_ARGS)
406 PG_RETURN_INT32(text_length(PG_GETARG_DATUM(0)));
411 * Does the real work for textlen()
412 * This is broken out so it can be called directly by other string processing
416 text_length(Datum str)
418 /* fastpath when max encoding length is one */
419 if (pg_database_encoding_max_length() == 1)
420 PG_RETURN_INT32(toast_raw_datum_size(str) - VARHDRSZ);
422 if (pg_database_encoding_max_length() > 1)
424 text *t = DatumGetTextP(str);
426 PG_RETURN_INT32(pg_mbstrlen_with_len(VARDATA(t),
427 VARSIZE(t) - VARHDRSZ));
430 /* should never get here */
431 elog(ERROR, "invalid backend encoding: encoding max length < 1");
433 /* not reached: suppress compiler warning */
439 * returns the physical length of a text*
440 * (which is less than the VARSIZE of the text*)
443 textoctetlen(PG_FUNCTION_ARGS)
445 PG_RETURN_INT32(toast_raw_datum_size(PG_GETARG_DATUM(0)) - VARHDRSZ);
450 * takes two text* and returns a text* that is the concatenation of
453 * Rewritten by Sapa, sapa@hq.icb.chel.su. 8-Jul-96.
454 * Updated by Thomas, Thomas.Lockhart@jpl.nasa.gov 1997-07-10.
455 * Allocate space for output in all cases.
456 * XXX - thomas 1997-07-10
459 textcat(PG_FUNCTION_ARGS)
461 text *t1 = PG_GETARG_TEXT_P(0);
462 text *t2 = PG_GETARG_TEXT_P(1);
469 len1 = (VARSIZE(t1) - VARHDRSZ);
473 len2 = (VARSIZE(t2) - VARHDRSZ);
477 len = len1 + len2 + VARHDRSZ;
478 result = (text *) palloc(len);
480 /* Set size of result string... */
481 VARATT_SIZEP(result) = len;
483 /* Fill data field of result string... */
484 ptr = VARDATA(result);
486 memcpy(ptr, VARDATA(t1), len1);
488 memcpy(ptr + len1, VARDATA(t2), len2);
490 PG_RETURN_TEXT_P(result);
495 * Return a substring starting at the specified position.
496 * - thomas 1997-12-31
500 * - starting position (is one-based)
503 * If the starting position is zero or less, then return from the start of the string
504 * adjusting the length to be consistent with the "negative start" per SQL92.
505 * If the length is less than zero, return the remaining string.
507 * Note that the arguments operate on octet length,
508 * so not aware of multibyte character sets.
510 * Added multibyte support.
511 * - Tatsuo Ishii 1998-4-21
512 * Changed behavior if starting position is less than one to conform to SQL92 behavior.
513 * Formerly returned the entire string; now returns a portion.
514 * - Thomas Lockhart 1998-12-10
515 * Now uses faster TOAST-slicing interface
516 * - John Gray 2002-02-22
517 * Remove "#ifdef MULTIBYTE" and test for encoding_max_length instead. Change
518 * behaviors conflicting with SQL92 to meet SQL92 (if E = S + L < S throw
519 * error; if E < 1, return '', not entire string). Fixed MB related bug when
520 * S > LC and < LC + 4 sometimes garbage characters are returned.
521 * - Joe Conway 2002-08-10
524 text_substr(PG_FUNCTION_ARGS)
526 PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0),
533 * text_substr_no_len -
534 * Wrapper to avoid opr_sanity failure due to
535 * one function accepting a different number of args.
538 text_substr_no_len(PG_FUNCTION_ARGS)
540 PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0),
547 * Does the real work for text_substr() and text_substr_no_len()
548 * This is broken out so it can be called directly by other string processing
552 text_substring(Datum str, int32 start, int32 length, bool length_not_specified)
554 int32 eml = pg_database_encoding_max_length();
555 int32 S = start; /* start position */
556 int32 S1; /* adjusted start position */
557 int32 L1; /* adjusted substring length */
559 /* life is easy if the encoding max length is 1 */
564 if (length_not_specified) /* special case - get length to
573 * A negative value for L is the only way for the end position
574 * to be before the start. SQL99 says to throw an error.
578 (errcode(ERRCODE_SUBSTRING_ERROR),
579 errmsg("negative substring length not allowed")));
582 * A zero or negative value for the end position can happen if
583 * the start was negative or one. SQL99 says to return a
584 * zero-length string.
587 return PG_STR_GET_TEXT("");
593 * If the start position is past the end of the string, SQL99 says
594 * to return a zero-length string -- PG_GETARG_TEXT_P_SLICE() will
595 * do that for us. Convert to zero-based starting position
597 return DatumGetTextPSlice(str, S1 - 1, L1);
602 * When encoding max length is > 1, we can't get LC without
603 * detoasting, so we'll grab a conservatively large slice now and
604 * go back later to do the right thing
617 * if S is past the end of the string, the tuple toaster will
618 * return a zero-length string to us
623 * We need to start at position zero because there is no way to
624 * know in advance which byte offset corresponds to the supplied
629 if (length_not_specified) /* special case - get length to
631 slice_size = L1 = -1;
637 * A negative value for L is the only way for the end position
638 * to be before the start. SQL99 says to throw an error.
642 (errcode(ERRCODE_SUBSTRING_ERROR),
643 errmsg("negative substring length not allowed")));
646 * A zero or negative value for the end position can happen if
647 * the start was negative or one. SQL99 says to return a
648 * zero-length string.
651 return PG_STR_GET_TEXT("");
654 * if E is past the end of the string, the tuple toaster will
655 * truncate the length for us
660 * Total slice size in bytes can't be any longer than the
661 * start position plus substring length times the encoding max
664 slice_size = (S1 + L1) * eml;
666 slice = DatumGetTextPSlice(str, slice_start, slice_size);
668 /* see if we got back an empty string */
669 if ((VARSIZE(slice) - VARHDRSZ) == 0)
670 return PG_STR_GET_TEXT("");
672 /* Now we can get the actual length of the slice in MB characters */
673 slice_strlen = pg_mbstrlen_with_len(VARDATA(slice), VARSIZE(slice) - VARHDRSZ);
676 * Check that the start position wasn't > slice_strlen. If so,
677 * SQL99 says to return a zero-length string.
679 if (S1 > slice_strlen)
680 return PG_STR_GET_TEXT("");
683 * Adjust L1 and E1 now that we know the slice string length.
684 * Again remember that S1 is one based, and slice_start is zero
688 E1 = Min(S1 + L1, slice_start + 1 + slice_strlen);
690 E1 = slice_start + 1 + slice_strlen;
693 * Find the start position in the slice; remember S1 is not zero
697 for (i = 0; i < S1 - 1; i++)
700 /* hang onto a pointer to our start position */
704 * Count the actual bytes used by the substring of the requested
707 for (i = S1; i < E1; i++)
710 ret = (text *) palloc(VARHDRSZ + (p - s));
711 VARATT_SIZEP(ret) = VARHDRSZ + (p - s);
712 memcpy(VARDATA(ret), s, (p - s));
717 elog(ERROR, "invalid backend encoding: encoding max length < 1");
719 /* not reached: suppress compiler warning */
720 return PG_STR_GET_TEXT("");
725 * Return the position of the specified substring.
726 * Implements the SQL92 POSITION() function.
727 * Ref: A Guide To The SQL Standard, Date & Darwen, 1997
728 * - thomas 1997-07-27
731 textpos(PG_FUNCTION_ARGS)
733 PG_RETURN_INT32(text_position(PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), 1));
738 * Does the real work for textpos()
739 * This is broken out so it can be called directly by other string processing
743 text_position(Datum str, Datum search_str, int matchnum)
745 int eml = pg_database_encoding_max_length();
746 text *t1 = DatumGetTextP(str);
747 text *t2 = DatumGetTextP(search_str);
756 return 0; /* result for 0th match */
758 if (VARSIZE(t2) <= VARHDRSZ)
759 PG_RETURN_INT32(1); /* result for empty pattern */
761 len1 = (VARSIZE(t1) - VARHDRSZ);
762 len2 = (VARSIZE(t2) - VARHDRSZ);
764 /* no use in searching str past point where search_str will fit */
767 if (eml == 1) /* simple case - single byte encoding */
775 for (p = 0; p <= px; p++)
777 if ((*p2 == *p1) && (strncmp(p1, p2, len2) == 0))
779 if (++match == matchnum)
788 else if (eml > 1) /* not as simple - multibyte encoding */
795 ps1 = p1 = (pg_wchar *) palloc((len1 + 1) * sizeof(pg_wchar));
796 (void) pg_mb2wchar_with_len((unsigned char *) VARDATA(t1), p1, len1);
797 len1 = pg_wchar_strlen(p1);
798 ps2 = p2 = (pg_wchar *) palloc((len2 + 1) * sizeof(pg_wchar));
799 (void) pg_mb2wchar_with_len((unsigned char *) VARDATA(t2), p2, len2);
800 len2 = pg_wchar_strlen(p2);
802 for (p = 0; p <= px; p++)
804 if ((*p2 == *p1) && (pg_wchar_strncmp(p1, p2, len2) == 0))
806 if (++match == matchnum)
819 elog(ERROR, "invalid backend encoding: encoding max length < 1");
821 PG_RETURN_INT32(pos);
825 * Comparison function for text strings with given lengths.
826 * Includes locale support, but must copy strings to temporary memory
827 * to allow null-termination for inputs to strcoll().
831 varstr_cmp(char *arg1, int len1, char *arg2, int len2)
836 * Unfortunately, there is no strncoll(), so in the non-C locale case
837 * we have to do some memory copying. This turns out to be
838 * significantly slower, so we optimize the case where LC_COLLATE is
839 * C. We also try to optimize relatively-short strings by avoiding
840 * palloc/pfree overhead.
842 #define STACKBUFLEN 1024
844 if (!lc_collate_is_c())
846 char a1buf[STACKBUFLEN];
847 char a2buf[STACKBUFLEN];
851 if (len1 >= STACKBUFLEN)
852 a1p = (char *) palloc(len1 + 1);
855 if (len2 >= STACKBUFLEN)
856 a2p = (char *) palloc(len2 + 1);
860 memcpy(a1p, arg1, len1);
862 memcpy(a2p, arg2, len2);
865 result = strcoll(a1p, a2p);
867 if (len1 >= STACKBUFLEN)
869 if (len2 >= STACKBUFLEN)
874 result = strncmp(arg1, arg2, Min(len1, len2));
875 if ((result == 0) && (len1 != len2))
876 result = (len1 < len2) ? -1 : 1;
884 * Internal comparison function for text strings.
888 text_cmp(text *arg1, text *arg2)
898 len1 = VARSIZE(arg1) - VARHDRSZ;
899 len2 = VARSIZE(arg2) - VARHDRSZ;
901 return varstr_cmp(a1p, len1, a2p, len2);
905 * Comparison functions for text strings.
907 * Note: btree indexes need these routines not to leak memory; therefore,
908 * be careful to free working copies of toasted datums. Most places don't
909 * need to be so careful.
913 texteq(PG_FUNCTION_ARGS)
915 text *arg1 = PG_GETARG_TEXT_P(0);
916 text *arg2 = PG_GETARG_TEXT_P(1);
919 /* fast path for different-length inputs */
920 if (VARSIZE(arg1) != VARSIZE(arg2))
923 result = (text_cmp(arg1, arg2) == 0);
925 PG_FREE_IF_COPY(arg1, 0);
926 PG_FREE_IF_COPY(arg2, 1);
928 PG_RETURN_BOOL(result);
932 textne(PG_FUNCTION_ARGS)
934 text *arg1 = PG_GETARG_TEXT_P(0);
935 text *arg2 = PG_GETARG_TEXT_P(1);
938 /* fast path for different-length inputs */
939 if (VARSIZE(arg1) != VARSIZE(arg2))
942 result = (text_cmp(arg1, arg2) != 0);
944 PG_FREE_IF_COPY(arg1, 0);
945 PG_FREE_IF_COPY(arg2, 1);
947 PG_RETURN_BOOL(result);
951 text_lt(PG_FUNCTION_ARGS)
953 text *arg1 = PG_GETARG_TEXT_P(0);
954 text *arg2 = PG_GETARG_TEXT_P(1);
957 result = (text_cmp(arg1, arg2) < 0);
959 PG_FREE_IF_COPY(arg1, 0);
960 PG_FREE_IF_COPY(arg2, 1);
962 PG_RETURN_BOOL(result);
966 text_le(PG_FUNCTION_ARGS)
968 text *arg1 = PG_GETARG_TEXT_P(0);
969 text *arg2 = PG_GETARG_TEXT_P(1);
972 result = (text_cmp(arg1, arg2) <= 0);
974 PG_FREE_IF_COPY(arg1, 0);
975 PG_FREE_IF_COPY(arg2, 1);
977 PG_RETURN_BOOL(result);
981 text_gt(PG_FUNCTION_ARGS)
983 text *arg1 = PG_GETARG_TEXT_P(0);
984 text *arg2 = PG_GETARG_TEXT_P(1);
987 result = (text_cmp(arg1, arg2) > 0);
989 PG_FREE_IF_COPY(arg1, 0);
990 PG_FREE_IF_COPY(arg2, 1);
992 PG_RETURN_BOOL(result);
996 text_ge(PG_FUNCTION_ARGS)
998 text *arg1 = PG_GETARG_TEXT_P(0);
999 text *arg2 = PG_GETARG_TEXT_P(1);
1002 result = (text_cmp(arg1, arg2) >= 0);
1004 PG_FREE_IF_COPY(arg1, 0);
1005 PG_FREE_IF_COPY(arg2, 1);
1007 PG_RETURN_BOOL(result);
1011 bttextcmp(PG_FUNCTION_ARGS)
1013 text *arg1 = PG_GETARG_TEXT_P(0);
1014 text *arg2 = PG_GETARG_TEXT_P(1);
1017 result = text_cmp(arg1, arg2);
1019 PG_FREE_IF_COPY(arg1, 0);
1020 PG_FREE_IF_COPY(arg2, 1);
1022 PG_RETURN_INT32(result);
1027 text_larger(PG_FUNCTION_ARGS)
1029 text *arg1 = PG_GETARG_TEXT_P(0);
1030 text *arg2 = PG_GETARG_TEXT_P(1);
1033 result = ((text_cmp(arg1, arg2) > 0) ? arg1 : arg2);
1035 PG_RETURN_TEXT_P(result);
1039 text_smaller(PG_FUNCTION_ARGS)
1041 text *arg1 = PG_GETARG_TEXT_P(0);
1042 text *arg2 = PG_GETARG_TEXT_P(1);
1045 result = ((text_cmp(arg1, arg2) < 0) ? arg1 : arg2);
1047 PG_RETURN_TEXT_P(result);
1052 * The following operators support character-by-character comparison
1053 * of text data types, to allow building indexes suitable for LIKE
1058 internal_text_pattern_compare(text *arg1, text *arg2)
1062 result = memcmp(VARDATA(arg1), VARDATA(arg2),
1063 Min(VARSIZE(arg1), VARSIZE(arg2)) - VARHDRSZ);
1066 else if (VARSIZE(arg1) < VARSIZE(arg2))
1068 else if (VARSIZE(arg1) > VARSIZE(arg2))
1076 text_pattern_lt(PG_FUNCTION_ARGS)
1078 text *arg1 = PG_GETARG_TEXT_P(0);
1079 text *arg2 = PG_GETARG_TEXT_P(1);
1082 result = internal_text_pattern_compare(arg1, arg2);
1084 PG_FREE_IF_COPY(arg1, 0);
1085 PG_FREE_IF_COPY(arg2, 1);
1087 PG_RETURN_BOOL(result < 0);
1092 text_pattern_le(PG_FUNCTION_ARGS)
1094 text *arg1 = PG_GETARG_TEXT_P(0);
1095 text *arg2 = PG_GETARG_TEXT_P(1);
1098 result = internal_text_pattern_compare(arg1, arg2);
1100 PG_FREE_IF_COPY(arg1, 0);
1101 PG_FREE_IF_COPY(arg2, 1);
1103 PG_RETURN_BOOL(result <= 0);
1108 text_pattern_eq(PG_FUNCTION_ARGS)
1110 text *arg1 = PG_GETARG_TEXT_P(0);
1111 text *arg2 = PG_GETARG_TEXT_P(1);
1114 if (VARSIZE(arg1) != VARSIZE(arg2))
1117 result = internal_text_pattern_compare(arg1, arg2);
1119 PG_FREE_IF_COPY(arg1, 0);
1120 PG_FREE_IF_COPY(arg2, 1);
1122 PG_RETURN_BOOL(result == 0);
1127 text_pattern_ge(PG_FUNCTION_ARGS)
1129 text *arg1 = PG_GETARG_TEXT_P(0);
1130 text *arg2 = PG_GETARG_TEXT_P(1);
1133 result = internal_text_pattern_compare(arg1, arg2);
1135 PG_FREE_IF_COPY(arg1, 0);
1136 PG_FREE_IF_COPY(arg2, 1);
1138 PG_RETURN_BOOL(result >= 0);
1143 text_pattern_gt(PG_FUNCTION_ARGS)
1145 text *arg1 = PG_GETARG_TEXT_P(0);
1146 text *arg2 = PG_GETARG_TEXT_P(1);
1149 result = internal_text_pattern_compare(arg1, arg2);
1151 PG_FREE_IF_COPY(arg1, 0);
1152 PG_FREE_IF_COPY(arg2, 1);
1154 PG_RETURN_BOOL(result > 0);
1159 text_pattern_ne(PG_FUNCTION_ARGS)
1161 text *arg1 = PG_GETARG_TEXT_P(0);
1162 text *arg2 = PG_GETARG_TEXT_P(1);
1165 if (VARSIZE(arg1) != VARSIZE(arg2))
1168 result = internal_text_pattern_compare(arg1, arg2);
1170 PG_FREE_IF_COPY(arg1, 0);
1171 PG_FREE_IF_COPY(arg2, 1);
1173 PG_RETURN_BOOL(result != 0);
1178 bttext_pattern_cmp(PG_FUNCTION_ARGS)
1180 text *arg1 = PG_GETARG_TEXT_P(0);
1181 text *arg2 = PG_GETARG_TEXT_P(1);
1184 result = internal_text_pattern_compare(arg1, arg2);
1186 PG_FREE_IF_COPY(arg1, 0);
1187 PG_FREE_IF_COPY(arg2, 1);
1189 PG_RETURN_INT32(result);
1193 /*-------------------------------------------------------------
1196 * get the number of bytes contained in an instance of type 'bytea'
1197 *-------------------------------------------------------------
1200 byteaoctetlen(PG_FUNCTION_ARGS)
1202 PG_RETURN_INT32(toast_raw_datum_size(PG_GETARG_DATUM(0)) - VARHDRSZ);
1207 * takes two bytea* and returns a bytea* that is the concatenation of
1210 * Cloned from textcat and modified as required.
1213 byteacat(PG_FUNCTION_ARGS)
1215 bytea *t1 = PG_GETARG_BYTEA_P(0);
1216 bytea *t2 = PG_GETARG_BYTEA_P(1);
1223 len1 = (VARSIZE(t1) - VARHDRSZ);
1227 len2 = (VARSIZE(t2) - VARHDRSZ);
1231 len = len1 + len2 + VARHDRSZ;
1232 result = (bytea *) palloc(len);
1234 /* Set size of result string... */
1235 VARATT_SIZEP(result) = len;
1237 /* Fill data field of result string... */
1238 ptr = VARDATA(result);
1240 memcpy(ptr, VARDATA(t1), len1);
1242 memcpy(ptr + len1, VARDATA(t2), len2);
1244 PG_RETURN_BYTEA_P(result);
1247 #define PG_STR_GET_BYTEA(str_) \
1248 DatumGetByteaP(DirectFunctionCall1(byteain, CStringGetDatum(str_)))
1251 * Return a substring starting at the specified position.
1252 * Cloned from text_substr and modified as required.
1256 * - starting position (is one-based)
1257 * - string length (optional)
1259 * If the starting position is zero or less, then return from the start of the string
1260 * adjusting the length to be consistent with the "negative start" per SQL92.
1261 * If the length is less than zero, an ERROR is thrown. If no third argument
1262 * (length) is provided, the length to the end of the string is assumed.
1265 bytea_substr(PG_FUNCTION_ARGS)
1267 int S = PG_GETARG_INT32(1); /* start position */
1268 int S1; /* adjusted start position */
1269 int L1; /* adjusted substring length */
1273 if (fcinfo->nargs == 2)
1276 * Not passed a length - PG_GETARG_BYTEA_P_SLICE() grabs
1277 * everything to the end of the string if we pass it a negative
1285 int E = S + PG_GETARG_INT32(2);
1288 * A negative value for L is the only way for the end position to
1289 * be before the start. SQL99 says to throw an error.
1293 (errcode(ERRCODE_SUBSTRING_ERROR),
1294 errmsg("negative substring length not allowed")));
1297 * A zero or negative value for the end position can happen if the
1298 * start was negative or one. SQL99 says to return a zero-length
1302 PG_RETURN_BYTEA_P(PG_STR_GET_BYTEA(""));
1308 * If the start position is past the end of the string, SQL99 says to
1309 * return a zero-length string -- PG_GETARG_TEXT_P_SLICE() will do
1310 * that for us. Convert to zero-based starting position
1312 PG_RETURN_BYTEA_P(PG_GETARG_BYTEA_P_SLICE(0, S1 - 1, L1));
1316 * bytea_substr_no_len -
1317 * Wrapper to avoid opr_sanity failure due to
1318 * one function accepting a different number of args.
1321 bytea_substr_no_len(PG_FUNCTION_ARGS)
1323 return bytea_substr(fcinfo);
1328 * Return the position of the specified substring.
1329 * Implements the SQL92 POSITION() function.
1330 * Cloned from textpos and modified as required.
1333 byteapos(PG_FUNCTION_ARGS)
1335 bytea *t1 = PG_GETARG_BYTEA_P(0);
1336 bytea *t2 = PG_GETARG_BYTEA_P(1);
1345 if (VARSIZE(t2) <= VARHDRSZ)
1346 PG_RETURN_INT32(1); /* result for empty pattern */
1348 len1 = (VARSIZE(t1) - VARHDRSZ);
1349 len2 = (VARSIZE(t2) - VARHDRSZ);
1356 for (p = 0; p <= px; p++)
1358 if ((*p2 == *p1) && (memcmp(p1, p2, len2) == 0))
1366 PG_RETURN_INT32(pos);
1369 /*-------------------------------------------------------------
1372 * this routine treats "bytea" as an array of bytes.
1373 * It returns the Nth byte (a number between 0 and 255).
1374 *-------------------------------------------------------------
1377 byteaGetByte(PG_FUNCTION_ARGS)
1379 bytea *v = PG_GETARG_BYTEA_P(0);
1380 int32 n = PG_GETARG_INT32(1);
1384 len = VARSIZE(v) - VARHDRSZ;
1386 if (n < 0 || n >= len)
1388 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1389 errmsg("index %d out of valid range, 0..%d",
1392 byte = ((unsigned char *) VARDATA(v))[n];
1394 PG_RETURN_INT32(byte);
1397 /*-------------------------------------------------------------
1400 * This routine treats a "bytea" type like an array of bits.
1401 * It returns the value of the Nth bit (0 or 1).
1403 *-------------------------------------------------------------
1406 byteaGetBit(PG_FUNCTION_ARGS)
1408 bytea *v = PG_GETARG_BYTEA_P(0);
1409 int32 n = PG_GETARG_INT32(1);
1415 len = VARSIZE(v) - VARHDRSZ;
1417 if (n < 0 || n >= len * 8)
1419 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1420 errmsg("index %d out of valid range, 0..%d",
1426 byte = ((unsigned char *) VARDATA(v))[byteNo];
1428 if (byte & (1 << bitNo))
1434 /*-------------------------------------------------------------
1437 * Given an instance of type 'bytea' creates a new one with
1438 * the Nth byte set to the given value.
1440 *-------------------------------------------------------------
1443 byteaSetByte(PG_FUNCTION_ARGS)
1445 bytea *v = PG_GETARG_BYTEA_P(0);
1446 int32 n = PG_GETARG_INT32(1);
1447 int32 newByte = PG_GETARG_INT32(2);
1451 len = VARSIZE(v) - VARHDRSZ;
1453 if (n < 0 || n >= len)
1455 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1456 errmsg("index %d out of valid range, 0..%d",
1460 * Make a copy of the original varlena.
1462 res = (bytea *) palloc(VARSIZE(v));
1463 memcpy((char *) res, (char *) v, VARSIZE(v));
1468 ((unsigned char *) VARDATA(res))[n] = newByte;
1470 PG_RETURN_BYTEA_P(res);
1473 /*-------------------------------------------------------------
1476 * Given an instance of type 'bytea' creates a new one with
1477 * the Nth bit set to the given value.
1479 *-------------------------------------------------------------
1482 byteaSetBit(PG_FUNCTION_ARGS)
1484 bytea *v = PG_GETARG_BYTEA_P(0);
1485 int32 n = PG_GETARG_INT32(1);
1486 int32 newBit = PG_GETARG_INT32(2);
1494 len = VARSIZE(v) - VARHDRSZ;
1496 if (n < 0 || n >= len * 8)
1498 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1499 errmsg("index %d out of valid range, 0..%d",
1508 if (newBit != 0 && newBit != 1)
1510 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1511 errmsg("new bit must be 0 or 1")));
1514 * Make a copy of the original varlena.
1516 res = (bytea *) palloc(VARSIZE(v));
1517 memcpy((char *) res, (char *) v, VARSIZE(v));
1522 oldByte = ((unsigned char *) VARDATA(res))[byteNo];
1525 newByte = oldByte & (~(1 << bitNo));
1527 newByte = oldByte | (1 << bitNo);
1529 ((unsigned char *) VARDATA(res))[byteNo] = newByte;
1531 PG_RETURN_BYTEA_P(res);
1536 * Converts a text type to a Name type.
1539 text_name(PG_FUNCTION_ARGS)
1541 text *s = PG_GETARG_TEXT_P(0);
1545 len = VARSIZE(s) - VARHDRSZ;
1547 /* Truncate oversize input */
1548 if (len >= NAMEDATALEN)
1549 len = NAMEDATALEN - 1;
1552 printf("text- convert string length %d (%d) ->%d\n",
1553 VARSIZE(s) - VARHDRSZ, VARSIZE(s), len);
1556 result = (Name) palloc(NAMEDATALEN);
1557 memcpy(NameStr(*result), VARDATA(s), len);
1559 /* now null pad to full length... */
1560 while (len < NAMEDATALEN)
1562 *(NameStr(*result) + len) = '\0';
1566 PG_RETURN_NAME(result);
1570 * Converts a Name type to a text type.
1573 name_text(PG_FUNCTION_ARGS)
1575 Name s = PG_GETARG_NAME(0);
1579 len = strlen(NameStr(*s));
1582 printf("text- convert string length %d (%d) ->%d\n",
1583 VARSIZE(s) - VARHDRSZ, VARSIZE(s), len);
1586 result = palloc(VARHDRSZ + len);
1587 VARATT_SIZEP(result) = VARHDRSZ + len;
1588 memcpy(VARDATA(result), NameStr(*s), len);
1590 PG_RETURN_TEXT_P(result);
1595 * textToQualifiedNameList - convert a text object to list of names
1597 * This implements the input parsing needed by nextval() and other
1598 * functions that take a text parameter representing a qualified name.
1599 * We split the name at dots, downcase if not double-quoted, and
1600 * truncate names if they're too long.
1603 textToQualifiedNameList(text *textval, const char *caller)
1610 /* Convert to C string (handles possible detoasting). */
1611 /* Note we rely on being able to modify rawname below. */
1612 rawname = DatumGetCString(DirectFunctionCall1(textout,
1613 PointerGetDatum(textval)));
1615 if (!SplitIdentifierString(rawname, '.', &namelist))
1617 (errcode(ERRCODE_INVALID_NAME),
1618 errmsg("invalid name syntax")));
1620 if (namelist == NIL)
1622 (errcode(ERRCODE_INVALID_NAME),
1623 errmsg("invalid name syntax")));
1625 foreach(l, namelist)
1627 char *curname = (char *) lfirst(l);
1629 result = lappend(result, makeString(pstrdup(curname)));
1639 * SplitIdentifierString --- parse a string containing identifiers
1641 * This is the guts of textToQualifiedNameList, and is exported for use in
1642 * other situations such as parsing GUC variables. In the GUC case, it's
1643 * important to avoid memory leaks, so the API is designed to minimize the
1644 * amount of stuff that needs to be allocated and freed.
1647 * rawstring: the input string; must be overwritable! On return, it's
1648 * been modified to contain the separated identifiers.
1649 * separator: the separator punctuation expected between identifiers
1650 * (typically '.' or ','). Whitespace may also appear around
1653 * namelist: filled with a palloc'd list of pointers to identifiers within
1654 * rawstring. Caller should freeList() this even on error return.
1656 * Returns TRUE if okay, FALSE if there is a syntax error in the string.
1658 * Note that an empty string is considered okay here, though not in
1659 * textToQualifiedNameList.
1662 SplitIdentifierString(char *rawstring, char separator,
1665 char *nextp = rawstring;
1670 while (isspace((unsigned char) *nextp))
1671 nextp++; /* skip leading whitespace */
1674 return true; /* allow empty string */
1676 /* At the top of the loop, we are at start of a new identifier. */
1685 /* Quoted name --- collapse quote-quote pairs, no downcasing */
1686 curname = nextp + 1;
1689 endp = strchr(nextp + 1, '\"');
1691 return false; /* mismatched quotes */
1692 if (endp[1] != '\"')
1693 break; /* found end of quoted name */
1694 /* Collapse adjacent quotes into one quote, and look again */
1695 memmove(endp, endp + 1, strlen(endp));
1698 /* endp now points at the terminating quote */
1703 /* Unquoted name --- extends to separator or whitespace */
1705 while (*nextp && *nextp != separator &&
1706 !isspace((unsigned char) *nextp))
1709 * It's important that this match the identifier
1710 * downcasing code used by backend/parser/scan.l.
1712 if (isupper((unsigned char) *nextp))
1713 *nextp = tolower((unsigned char) *nextp);
1717 if (curname == nextp)
1718 return false; /* empty unquoted name not allowed */
1721 while (isspace((unsigned char) *nextp))
1722 nextp++; /* skip trailing whitespace */
1724 if (*nextp == separator)
1727 while (isspace((unsigned char) *nextp))
1728 nextp++; /* skip leading whitespace for next */
1729 /* we expect another name, so done remains false */
1731 else if (*nextp == '\0')
1734 return false; /* invalid syntax */
1736 /* Now safe to overwrite separator with a null */
1739 /* Truncate name if it's overlength; again, should match scan.l */
1740 curlen = strlen(curname);
1741 if (curlen >= NAMEDATALEN)
1743 curlen = pg_mbcliplen(curname, curlen, NAMEDATALEN - 1);
1744 curname[curlen] = '\0';
1748 * Finished isolating current name --- add it to list
1750 *namelist = lappend(*namelist, curname);
1752 /* Loop back if we didn't reach end of string */
1759 /*****************************************************************************
1760 * Comparison Functions used for bytea
1762 * Note: btree indexes need these routines not to leak memory; therefore,
1763 * be careful to free working copies of toasted datums. Most places don't
1764 * need to be so careful.
1765 *****************************************************************************/
1768 byteaeq(PG_FUNCTION_ARGS)
1770 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1771 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1776 len1 = VARSIZE(arg1) - VARHDRSZ;
1777 len2 = VARSIZE(arg2) - VARHDRSZ;
1779 /* fast path for different-length inputs */
1783 result = (memcmp(VARDATA(arg1), VARDATA(arg2), len1) == 0);
1785 PG_FREE_IF_COPY(arg1, 0);
1786 PG_FREE_IF_COPY(arg2, 1);
1788 PG_RETURN_BOOL(result);
1792 byteane(PG_FUNCTION_ARGS)
1794 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1795 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1800 len1 = VARSIZE(arg1) - VARHDRSZ;
1801 len2 = VARSIZE(arg2) - VARHDRSZ;
1803 /* fast path for different-length inputs */
1807 result = (memcmp(VARDATA(arg1), VARDATA(arg2), len1) != 0);
1809 PG_FREE_IF_COPY(arg1, 0);
1810 PG_FREE_IF_COPY(arg2, 1);
1812 PG_RETURN_BOOL(result);
1816 bytealt(PG_FUNCTION_ARGS)
1818 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1819 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1824 len1 = VARSIZE(arg1) - VARHDRSZ;
1825 len2 = VARSIZE(arg2) - VARHDRSZ;
1827 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1829 PG_FREE_IF_COPY(arg1, 0);
1830 PG_FREE_IF_COPY(arg2, 1);
1832 PG_RETURN_BOOL((cmp < 0) || ((cmp == 0) && (len1 < len2)));
1836 byteale(PG_FUNCTION_ARGS)
1838 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1839 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1844 len1 = VARSIZE(arg1) - VARHDRSZ;
1845 len2 = VARSIZE(arg2) - VARHDRSZ;
1847 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1849 PG_FREE_IF_COPY(arg1, 0);
1850 PG_FREE_IF_COPY(arg2, 1);
1852 PG_RETURN_BOOL((cmp < 0) || ((cmp == 0) && (len1 <= len2)));
1856 byteagt(PG_FUNCTION_ARGS)
1858 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1859 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1864 len1 = VARSIZE(arg1) - VARHDRSZ;
1865 len2 = VARSIZE(arg2) - VARHDRSZ;
1867 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1869 PG_FREE_IF_COPY(arg1, 0);
1870 PG_FREE_IF_COPY(arg2, 1);
1872 PG_RETURN_BOOL((cmp > 0) || ((cmp == 0) && (len1 > len2)));
1876 byteage(PG_FUNCTION_ARGS)
1878 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1879 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1884 len1 = VARSIZE(arg1) - VARHDRSZ;
1885 len2 = VARSIZE(arg2) - VARHDRSZ;
1887 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1889 PG_FREE_IF_COPY(arg1, 0);
1890 PG_FREE_IF_COPY(arg2, 1);
1892 PG_RETURN_BOOL((cmp > 0) || ((cmp == 0) && (len1 >= len2)));
1896 byteacmp(PG_FUNCTION_ARGS)
1898 bytea *arg1 = PG_GETARG_BYTEA_P(0);
1899 bytea *arg2 = PG_GETARG_BYTEA_P(1);
1904 len1 = VARSIZE(arg1) - VARHDRSZ;
1905 len2 = VARSIZE(arg2) - VARHDRSZ;
1907 cmp = memcmp(VARDATA(arg1), VARDATA(arg2), Min(len1, len2));
1908 if ((cmp == 0) && (len1 != len2))
1909 cmp = (len1 < len2) ? -1 : 1;
1911 PG_FREE_IF_COPY(arg1, 0);
1912 PG_FREE_IF_COPY(arg2, 1);
1914 PG_RETURN_INT32(cmp);
1919 * replace all occurrences of 'old_sub_str' in 'orig_str'
1920 * with 'new_sub_str' to form 'new_str'
1922 * returns 'orig_str' if 'old_sub_str' == '' or 'orig_str' == ''
1923 * otherwise returns 'new_str'
1926 replace_text(PG_FUNCTION_ARGS)
1933 text *src_text = PG_GETARG_TEXT_P(0);
1934 int src_text_len = TEXTLEN(src_text);
1935 text *from_sub_text = PG_GETARG_TEXT_P(1);
1936 int from_sub_text_len = TEXTLEN(from_sub_text);
1937 text *to_sub_text = PG_GETARG_TEXT_P(2);
1938 char *to_sub_str = PG_TEXT_GET_STR(to_sub_text);
1939 StringInfo str = makeStringInfo();
1941 if (src_text_len == 0 || from_sub_text_len == 0)
1942 PG_RETURN_TEXT_P(src_text);
1944 buf_text = TEXTDUP(src_text);
1945 curr_posn = TEXTPOS(buf_text, from_sub_text);
1947 while (curr_posn > 0)
1949 left_text = LEFT(buf_text, from_sub_text);
1950 right_text = RIGHT(buf_text, from_sub_text, from_sub_text_len);
1952 appendStringInfoString(str, PG_TEXT_GET_STR(left_text));
1953 appendStringInfoString(str, to_sub_str);
1957 buf_text = right_text;
1958 curr_posn = TEXTPOS(buf_text, from_sub_text);
1961 appendStringInfoString(str, PG_TEXT_GET_STR(buf_text));
1964 ret_text = PG_STR_GET_TEXT(str->data);
1968 PG_RETURN_TEXT_P(ret_text);
1973 * parse input string
1974 * return ord item (1 based)
1975 * based on provided field separator
1978 split_text(PG_FUNCTION_ARGS)
1980 text *inputstring = PG_GETARG_TEXT_P(0);
1981 int inputstring_len = TEXTLEN(inputstring);
1982 text *fldsep = PG_GETARG_TEXT_P(1);
1983 int fldsep_len = TEXTLEN(fldsep);
1984 int fldnum = PG_GETARG_INT32(2);
1989 /* return empty string for empty input string */
1990 if (inputstring_len < 1)
1991 PG_RETURN_TEXT_P(PG_STR_GET_TEXT(""));
1993 /* empty field separator */
1996 if (fldnum == 1) /* first field - just return the input
1998 PG_RETURN_TEXT_P(inputstring);
2000 /* otherwise return an empty string */
2001 PG_RETURN_TEXT_P(PG_STR_GET_TEXT(""));
2004 /* field number is 1 based */
2007 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2008 errmsg("field position must be greater than zero")));
2010 start_posn = text_position(PointerGetDatum(inputstring),
2011 PointerGetDatum(fldsep),
2013 end_posn = text_position(PointerGetDatum(inputstring),
2014 PointerGetDatum(fldsep),
2017 if ((start_posn == 0) && (end_posn == 0)) /* fldsep not found */
2019 if (fldnum == 1) /* first field - just return the input
2021 PG_RETURN_TEXT_P(inputstring);
2023 /* otherwise return an empty string */
2024 PG_RETURN_TEXT_P(PG_STR_GET_TEXT(""));
2026 else if ((start_posn != 0) && (end_posn == 0))
2028 /* last field requested */
2029 result_text = text_substring(PointerGetDatum(inputstring), start_posn + fldsep_len, -1, true);
2030 PG_RETURN_TEXT_P(result_text);
2032 else if ((start_posn == 0) && (end_posn != 0))
2034 /* first field requested */
2035 result_text = LEFT(inputstring, fldsep);
2036 PG_RETURN_TEXT_P(result_text);
2040 /* prior to last field requested */
2041 result_text = text_substring(PointerGetDatum(inputstring), start_posn + fldsep_len, end_posn - start_posn - fldsep_len, false);
2042 PG_RETURN_TEXT_P(result_text);
2048 * parse input string
2049 * return text array of elements
2050 * based on provided field separator
2053 text_to_array(PG_FUNCTION_ARGS)
2055 text *inputstring = PG_GETARG_TEXT_P(0);
2056 int inputstring_len = TEXTLEN(inputstring);
2057 text *fldsep = PG_GETARG_TEXT_P(1);
2058 int fldsep_len = TEXTLEN(fldsep);
2062 text *result_text = NULL;
2063 ArrayBuildState *astate = NULL;
2064 MemoryContext oldcontext = CurrentMemoryContext;
2066 /* return NULL for empty input string */
2067 if (inputstring_len < 1)
2071 * empty field separator return one element, 1D, array using the input
2075 PG_RETURN_ARRAYTYPE_P(create_singleton_array(fcinfo, TEXTOID,
2076 CStringGetDatum(inputstring), 1));
2078 /* start with end position holding the initial start position */
2080 for (fldnum = 1;; fldnum++) /* field number is 1 based */
2083 bool disnull = false;
2085 start_posn = end_posn;
2086 end_posn = text_position(PointerGetDatum(inputstring),
2087 PointerGetDatum(fldsep),
2090 if ((start_posn == 0) && (end_posn == 0)) /* fldsep not found */
2095 * first element return one element, 1D, array using the
2098 PG_RETURN_ARRAYTYPE_P(create_singleton_array(fcinfo, TEXTOID,
2099 CStringGetDatum(inputstring), 1));
2103 /* otherwise create array and exit */
2104 PG_RETURN_ARRAYTYPE_P(makeArrayResult(astate, oldcontext));
2107 else if ((start_posn != 0) && (end_posn == 0))
2109 /* last field requested */
2110 result_text = text_substring(PointerGetDatum(inputstring), start_posn + fldsep_len, -1, true);
2112 else if ((start_posn == 0) && (end_posn != 0))
2114 /* first field requested */
2115 result_text = LEFT(inputstring, fldsep);
2119 /* prior to last field requested */
2120 result_text = text_substring(PointerGetDatum(inputstring), start_posn + fldsep_len, end_posn - start_posn - fldsep_len, false);
2123 /* stash away current value */
2124 dvalue = PointerGetDatum(result_text);
2125 astate = accumArrayResult(astate, dvalue,
2126 disnull, TEXTOID, oldcontext);
2130 /* never reached -- keep compiler quiet */
2136 * concatenate Cstring representation of input array elements
2137 * using provided field separator
2140 array_to_text(PG_FUNCTION_ARGS)
2142 ArrayType *v = PG_GETARG_ARRAYTYPE_P(0);
2143 char *fldsep = PG_TEXTARG_GET_STR(1);
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
2171 * element 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)
2185 * Get info about element type, including its output conversion
2188 get_type_io_data(element_type, IOFunc_output,
2189 &my_extra->typlen, &my_extra->typbyval,
2190 &my_extra->typalign, &my_extra->typdelim,
2191 &my_extra->typelem, &my_extra->typiofunc);
2192 fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
2193 fcinfo->flinfo->fn_mcxt);
2194 my_extra->element_type = element_type;
2196 typlen = my_extra->typlen;
2197 typbyval = my_extra->typbyval;
2198 typalign = my_extra->typalign;
2199 typelem = my_extra->typelem;
2201 for (i = 0; i < nitems; i++)
2206 itemvalue = fetch_att(p, typbyval, typlen);
2208 value = DatumGetCString(FunctionCall3(&my_extra->proc,
2210 ObjectIdGetDatum(typelem),
2211 Int32GetDatum(-1)));
2214 appendStringInfo(result_str, "%s%s", fldsep, value);
2216 appendStringInfo(result_str, "%s", value);
2218 p = att_addlength(p, typlen, PointerGetDatum(p));
2219 p = (char *) att_align(p, typalign);
2222 PG_RETURN_TEXT_P(PG_STR_GET_TEXT(result_str->data));
2227 * Convert a int32 to a string containing a base 16 (hex) representation of
2231 to_hex32(PG_FUNCTION_ARGS)
2233 static char digits[] = "0123456789abcdef";
2234 char buf[32]; /* bigger than needed, but reasonable */
2237 int32 value = PG_GETARG_INT32(0);
2239 ptr = buf + sizeof(buf) - 1;
2244 *--ptr = digits[value % HEXBASE];
2246 } while (ptr > buf && value);
2248 result_text = PG_STR_GET_TEXT(ptr);
2249 PG_RETURN_TEXT_P(result_text);
2253 * Convert a int64 to a string containing a base 16 (hex) representation of
2257 to_hex64(PG_FUNCTION_ARGS)
2259 static char digits[] = "0123456789abcdef";
2260 char buf[32]; /* bigger than needed, but reasonable */
2263 int64 value = PG_GETARG_INT64(0);
2265 ptr = buf + sizeof(buf) - 1;
2270 *--ptr = digits[value % HEXBASE];
2272 } while (ptr > buf && value);
2274 result_text = PG_STR_GET_TEXT(ptr);
2275 PG_RETURN_TEXT_P(result_text);
2279 * Create an md5 hash of a text string and return it as hex
2281 * md5 produces a 16 byte (128 bit) hash; double it for hex
2283 #define MD5_HASH_LEN 32
2286 md5_text(PG_FUNCTION_ARGS)
2288 char *buff = PG_TEXT_GET_STR(PG_GETARG_TEXT_P(0));
2289 size_t len = strlen(buff);
2293 /* leave room for the terminating '\0' */
2294 hexsum = (char *) palloc(MD5_HASH_LEN + 1);
2296 /* get the hash result */
2297 md5_hash((void *) buff, len, hexsum);
2299 /* convert to text and return it */
2300 result_text = PG_STR_GET_TEXT(hexsum);
2301 PG_RETURN_TEXT_P(result_text);